From 0c0f190f4d40ac4c3d57c4cba77ef167ff829a63 Mon Sep 17 00:00:00 2001 From: HarelM Date: Wed, 27 Nov 2024 08:48:52 +0000 Subject: [PATCH] deploy: 1ac0a1b9936c97789f5a5dd9e917603749495559 --- benchmarks/main/benchmarks_generated.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/benchmarks/main/benchmarks_generated.js b/benchmarks/main/benchmarks_generated.js index bd18744cdc..4af6f43b27 100644 --- a/benchmarks/main/benchmarks_generated.js +++ b/benchmarks/main/benchmarks_generated.js @@ -39,7 +39,7 @@ define("shared",["exports"],(function(t){"use strict";function e(t,e,r,n){return define("worker",["./shared"],(function(e){"use strict";class t{constructor(e,t,r){this.actor=e,this.layerIndex=t,this.availableImages=r,this.fetching={},this.loading={},this.loaded={};}loadVectorTile(t,r){return e.__awaiter(this,void 0,void 0,(function*(){const o=yield e.getArrayBuffer(t.request,r);try{return {vectorTile:new e.mvt.VectorTile(new e.Protobuf(o.data)),rawData:o.data,cacheControl:o.cacheControl,expires:o.expires}}catch(e){const r=new Uint8Array(o.data);let i=`Unable to parse the tile at ${t.request.url}, `;throw i+=31===r[0]&&139===r[1]?"please make sure the data is not gzipped and that you have configured the relevant header in the server":`got error: ${e.message}`,new Error(i)}}))}loadTile(t){return e.__awaiter(this,void 0,void 0,(function*(){const r=t.uid,o=!!(t&&t.request&&t.request.collectResourceTiming)&&new e.RequestPerformance(t.request),i=new e.WorkerTile(t);this.loading[r]=i;const n=new AbortController;i.abort=n;try{const s=yield this.loadVectorTile(t,n);if(delete this.loading[r],!s)return null;const a=s.rawData,l={};s.expires&&(l.expires=s.expires),s.cacheControl&&(l.cacheControl=s.cacheControl);const u={};if(o){const e=o.finish();e&&(u.resourceTiming=JSON.parse(JSON.stringify(e)));}i.vectorTile=s.vectorTile;const c=i.parse(s.vectorTile,this.layerIndex,this.availableImages,this.actor,t.subdivisionGranularity);this.loaded[r]=i,this.fetching[r]={rawTileData:a,cacheControl:l,resourceTiming:u};try{const t=yield c;return e.extend({rawTileData:a.slice(0)},t,l,u)}finally{delete this.fetching[r];}}catch(e){throw delete this.loading[r],i.status="done",this.loaded[r]=i,e}}))}reloadTile(t){return e.__awaiter(this,void 0,void 0,(function*(){const r=t.uid;if(!this.loaded||!this.loaded[r])throw new Error("Should not be trying to reload a tile that was never loaded or has been removed");const o=this.loaded[r];if(o.showCollisionBoxes=t.showCollisionBoxes,"parsing"===o.status){const i=yield o.parse(o.vectorTile,this.layerIndex,this.availableImages,this.actor,t.subdivisionGranularity);let n;if(this.fetching[r]){const{rawTileData:t,cacheControl:o,resourceTiming:s}=this.fetching[r];delete this.fetching[r],n=e.extend({rawTileData:t.slice(0)},i,o,s);}else n=i;return n}if("done"===o.status&&o.vectorTile)return o.parse(o.vectorTile,this.layerIndex,this.availableImages,this.actor,t.subdivisionGranularity)}))}abortTile(t){return e.__awaiter(this,void 0,void 0,(function*(){const e=this.loading,r=t.uid;e&&e[r]&&e[r].abort&&(e[r].abort.abort(),delete e[r]);}))}removeTile(t){return e.__awaiter(this,void 0,void 0,(function*(){this.loaded&&this.loaded[t.uid]&&delete this.loaded[t.uid];}))}}class r{constructor(){this.loaded={};}loadTile(t){return e.__awaiter(this,void 0,void 0,(function*(){const{uid:r,encoding:o,rawImageData:i,redFactor:n,greenFactor:s,blueFactor:a,baseShift:l}=t,u=i.width+2,c=i.height+2,h=e.isImageBitmap(i)?new e.RGBAImage({width:u,height:c},yield e.getImageData(i,-1,-1,u,c)):i,d=new e.DEMData(r,h,o,n,s,a,l);return this.loaded=this.loaded||{},this.loaded[r]=d,d}))}removeTile(e){const t=this.loaded,r=e.uid;t&&t[r]&&delete t[r];}}var o,i,n=function(){if(i)return o;function e(e,r){if(0!==e.length){t(e[0],r);for(var o=1;o=Math.abs(a)?r-l+a:a-l+r,r=l;}r+o>=0!=!!t&&e.reverse();}return i=1,o=function t(r,o){var i,n=r&&r.type;if("FeatureCollection"===n)for(i=0;i>31}function u(e,t){for(var r=e.loadGeometry(),o=e.type,i=0,n=0,s=r.length,u=0;ue},y=Math.fround||(v=new Float32Array(1),e=>(v[0]=+e,v[0]));var v;const w=3,x=5,_=6;class M{constructor(e){this.options=Object.assign(Object.create(m),e),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[];}load(e){const{log:t,minZoom:r,maxZoom:o}=this.options;t&&console.time("total time");const i=`prepare ${e.length} points`;t&&console.time(i),this.points=e;const n=[];for(let t=0;t=r;e--){const r=+Date.now();s=this.trees[e]=this._createTree(this._cluster(s,e)),t&&console.log("z%d: %d clusters in %dms",e,s.numItems,+Date.now()-r);}return t&&console.timeEnd("total time"),this}getClusters(e,t){let r=((e[0]+180)%360+360)%360-180;const o=Math.max(-90,Math.min(90,e[1]));let i=180===e[2]?180:((e[2]+180)%360+360)%360-180;const n=Math.max(-90,Math.min(90,e[3]));if(e[2]-e[0]>=360)r=-180,i=180;else if(r>i){const e=this.getClusters([r,o,180,n],t),s=this.getClusters([-180,o,i,n],t);return e.concat(s)}const s=this.trees[this._limitZoom(t)],a=s.range(P(r),T(n),P(i),T(o)),l=s.data,u=[];for(const e of a){const t=this.stride*e;u.push(l[t+x]>1?S(l,t,this.clusterProps):this.points[l[t+w]]);}return u}getChildren(e){const t=this._getOriginId(e),r=this._getOriginZoom(e),o="No cluster with the specified id.",i=this.trees[r];if(!i)throw new Error(o);const n=i.data;if(t*this.stride>=n.length)throw new Error(o);const s=this.options.radius/(this.options.extent*Math.pow(2,r-1)),a=i.within(n[t*this.stride],n[t*this.stride+1],s),l=[];for(const t of a){const r=t*this.stride;n[r+4]===e&&l.push(n[r+x]>1?S(n,r,this.clusterProps):this.points[n[r+w]]);}if(0===l.length)throw new Error(o);return l}getLeaves(e,t,r){const o=[];return this._appendLeaves(o,e,t=t||10,r=r||0,0),o}getTile(e,t,r){const o=this.trees[this._limitZoom(e)],i=Math.pow(2,e),{extent:n,radius:s}=this.options,a=s/n,l=(r-a)/i,u=(r+1+a)/i,c={features:[]};return this._addTileFeatures(o.range((t-a)/i,l,(t+1+a)/i,u),o.data,t,r,i,c),0===t&&this._addTileFeatures(o.range(1-a/i,l,1,u),o.data,i,r,i,c),t===i-1&&this._addTileFeatures(o.range(0,l,a/i,u),o.data,-1,r,i,c),c.features.length?c:null}getClusterExpansionZoom(e){let t=this._getOriginZoom(e)-1;for(;t<=this.options.maxZoom;){const r=this.getChildren(e);if(t++,1!==r.length)break;e=r[0].properties.cluster_id;}return t}_appendLeaves(e,t,r,o,i){const n=this.getChildren(t);for(const t of n){const n=t.properties;if(n&&n.cluster?i+n.point_count<=o?i+=n.point_count:i=this._appendLeaves(e,n.cluster_id,r,o,i):i1;let l,u,c;if(a)l=b(t,e,this.clusterProps),u=t[e],c=t[e+1];else {const r=this.points[t[e+w]];l=r.properties;const[o,i]=r.geometry.coordinates;u=P(o),c=T(i);}const h={type:1,geometry:[[Math.round(this.options.extent*(u*i-r)),Math.round(this.options.extent*(c*i-o))]],tags:l};let d;d=a||this.options.generateId?t[e+w]:this.points[t[e+w]].id,void 0!==d&&(h.id=d),n.features.push(h);}}_limitZoom(e){return Math.max(this.options.minZoom,Math.min(Math.floor(+e),this.options.maxZoom+1))}_cluster(e,t){const{radius:r,extent:o,reduce:i,minPoints:n}=this.options,s=r/(o*Math.pow(2,t)),a=e.data,l=[],u=this.stride;for(let r=0;rt&&(f+=a[r+x]);}if(f>d&&f>=n){let e,n=o*d,s=c*d,g=-1;const p=((r/u|0)<<5)+(t+1)+this.points.length;for(const o of h){const l=o*u;if(a[l+2]<=t)continue;a[l+2]=t;const c=a[l+x];n+=a[l]*c,s+=a[l+1]*c,a[l+4]=p,i&&(e||(e=this._map(a,r,!0),g=this.clusterProps.length,this.clusterProps.push(e)),i(e,this._map(a,l)));}a[r+4]=p,l.push(n/f,s/f,1/0,p,-1,f),i&&l.push(g);}else {for(let e=0;e1)for(const e of h){const r=e*u;if(!(a[r+2]<=t)){a[r+2]=t;for(let e=0;e>5}_getOriginZoom(e){return (e-this.points.length)%32}_map(e,t,r){if(e[t+x]>1){const o=this.clusterProps[e[t+_]];return r?Object.assign({},o):o}const o=this.points[e[t+w]].properties,i=this.options.map(o);return r&&i===o?Object.assign({},i):i}}function S(e,t,r){return {type:"Feature",id:e[t+w],properties:b(e,t,r),geometry:{type:"Point",coordinates:[(o=e[t],360*(o-.5)),I(e[t+1])]}};var o;}function b(e,t,r){const o=e[t+x],i=o>=1e4?`${Math.round(o/1e3)}k`:o>=1e3?Math.round(o/100)/10+"k":o,n=e[t+_],s=-1===n?{}:Object.assign({},r[n]);return Object.assign(s,{cluster:!0,cluster_id:e[t+w],point_count:o,point_count_abbreviated:i})}function P(e){return e/360+.5}function T(e){const t=Math.sin(e*Math.PI/180),r=.5-.25*Math.log((1+t)/(1-t))/Math.PI;return r<0?0:r>1?1:r}function I(e){const t=(180-360*e)*Math.PI/180;return 360*Math.atan(Math.exp(t))/Math.PI-90}function k(e,t,r,o){let i=o;const n=t+(r-t>>1);let s,a=r-t;const l=e[t],u=e[t+1],c=e[r],h=e[r+1];for(let o=t+3;oi)s=o,i=t;else if(t===i){const e=Math.abs(o-n);eo&&(s-t>3&&k(e,t,s,o),e[s+2]=i,r-s>3&&k(e,s,r,o));}function O(e,t,r,o,i,n){let s=i-r,a=n-o;if(0!==s||0!==a){const l=((e-r)*s+(t-o)*a)/(s*s+a*a);l>1?(r=i,o=n):l>0&&(r+=s*l,o+=a*l);}return s=e-r,a=t-o,s*s+a*a}function L(e,t,r,o){const i={id:null==e?null:e,type:t,geometry:r,tags:o,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if("Point"===t||"MultiPoint"===t||"LineString"===t)C(i,r);else if("Polygon"===t)C(i,r[0]);else if("MultiLineString"===t)for(const e of r)C(i,e);else if("MultiPolygon"===t)for(const e of r)C(i,e[0]);return i}function C(e,t){for(let r=0;r0&&(s+=o?(i*l-a*n)/2:Math.sqrt(Math.pow(a-i,2)+Math.pow(l-n,2))),i=a,n=l;}const a=t.length-3;t[2]=1,k(t,0,a,r),t[a+2]=1,t.size=Math.abs(s),t.start=0,t.end=t.size;}function G(e,t,r,o){for(let i=0;i1?1:r}function Z(e,t,r,o,i,n,s,a){if(o/=t,n>=(r/=t)&&s=o)return null;const l=[];for(const t of e){const e=t.geometry;let n=t.type;const s=0===i?t.minX:t.minY,u=0===i?t.maxX:t.maxY;if(s>=r&&u=o)continue;let c=[];if("Point"===n||"MultiPoint"===n)J(e,c,r,o,i);else if("LineString"===n)j(e,c,r,o,i,!1,a.lineMetrics);else if("MultiLineString"===n)q(e,c,r,o,i,!1);else if("Polygon"===n)q(e,c,r,o,i,!0);else if("MultiPolygon"===n)for(const t of e){const e=[];q(t,e,r,o,i,!0),e.length&&c.push(e);}if(c.length){if(a.lineMetrics&&"LineString"===n){for(const e of c)l.push(L(t.id,n,e,t.tags));continue}"LineString"!==n&&"MultiLineString"!==n||(1===c.length?(n="LineString",c=c[0]):n="MultiLineString"),"Point"!==n&&"MultiPoint"!==n||(n=3===c.length?"Point":"MultiPoint"),l.push(L(t.id,n,c,t.tags));}}return l.length?l:null}function J(e,t,r,o,i){for(let n=0;n=r&&s<=o&&Y(t,e[n],e[n+1],e[n+2]);}}function j(e,t,r,o,i,n,s){let a=A(e);const l=0===i?z:V;let u,c,h=e.start;for(let d=0;dr&&(c=l(a,f,g,m,y,r),s&&(a.start=h+u*c)):v>o?w=r&&(c=l(a,f,g,m,y,r),x=!0),w>o&&v<=o&&(c=l(a,f,g,m,y,o),x=!0),!n&&x&&(s&&(a.end=h+u*c),t.push(a),a=A(e)),s&&(h+=u);}let d=e.length-3;const f=e[d],g=e[d+1],p=0===i?f:g;p>=r&&p<=o&&Y(a,f,g,e[d+2]),d=a.length-3,n&&d>=3&&(a[d]!==a[0]||a[d+1]!==a[1])&&Y(a,a[0],a[1],a[2]),a.length&&t.push(a);}function A(e){const t=[];return t.size=e.size,t.start=e.start,t.end=e.end,t}function q(e,t,r,o,i,n){for(const s of e)j(s,t,r,o,i,n,!1);}function Y(e,t,r,o){e.push(t,r,o);}function z(e,t,r,o,i,n){const s=(n-t)/(o-t);return Y(e,n,r+(i-r)*s,1),s}function V(e,t,r,o,i,n){const s=(n-r)/(i-r);return Y(e,t+(o-t)*s,n,1),s}function R(e,t){const r=[];for(let o=0;o0&&t.size<(i?s:o))return void(r.numPoints+=t.length/3);const a=[];for(let e=0;es)&&(r.numSimplified++,a.push(t[e],t[e+1])),r.numPoints++;i&&function(e,t){let r=0;for(let t=0,o=e.length,i=o-2;t0===t)for(let t=0,r=e.length;t24)throw new Error("maxZoom should be in the 0-24 range");if(t.promoteId&&t.generateId)throw new Error("promoteId and generateId cannot be used together.");let o=function(e,t){const r=[];if("FeatureCollection"===e.type)for(let o=0;o1&&console.time("creation"),d=this.tiles[h]=$(e,t,r,o,l),this.tileCoords.push({z:t,x:r,y:o}),u)){u>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",t,r,o,d.numFeatures,d.numPoints,d.numSimplified),console.timeEnd("creation"));const e=`z${t}`;this.stats[e]=(this.stats[e]||0)+1,this.total++;}if(d.source=e,null==i){if(t===l.indexMaxZoom||d.numPoints<=l.indexMaxPoints)continue}else {if(t===l.maxZoom||t===i)continue;if(null!=i){const e=i-t;if(r!==n>>e||o!==s>>e)continue}}if(d.source=null,0===e.length)continue;u>1&&console.time("clipping");const f=.5*l.buffer/l.extent,g=.5-f,p=.5+f,m=1+f;let y=null,v=null,w=null,x=null,_=Z(e,c,r-f,r+p,0,d.minX,d.maxX,l),M=Z(e,c,r+g,r+m,0,d.minX,d.maxX,l);e=null,_&&(y=Z(_,c,o-f,o+p,1,d.minY,d.maxY,l),v=Z(_,c,o+g,o+m,1,d.minY,d.maxY,l),_=null),M&&(w=Z(M,c,o-f,o+p,1,d.minY,d.maxY,l),x=Z(M,c,o+g,o+m,1,d.minY,d.maxY,l),M=null),u>1&&console.timeEnd("clipping"),a.push(y||[],t+1,2*r,2*o),a.push(v||[],t+1,2*r,2*o+1),a.push(w||[],t+1,2*r+1,2*o),a.push(x||[],t+1,2*r+1,2*o+1);}}getTile(e,t,r){e=+e,t=+t,r=+r;const o=this.options,{extent:i,debug:n}=o;if(e<0||e>24)return null;const s=1<1&&console.log("drilling down to z%d-%d-%d",e,t,r);let l,u=e,c=t,h=r;for(;!l&&u>0;)u--,c>>=1,h>>=1,l=this.tiles[te(u,c,h)];return l&&l.source?(n>1&&(console.log("found parent tile z%d-%d-%d",u,c,h),console.time("drilling down")),this.splitTile(l.source,u,c,h,e,t,r),n>1&&console.timeEnd("drilling down"),this.tiles[a]?H(this.tiles[a],i):null):null}}function te(e,t,r){return 32*((1<{s.properties=e;const t={};for(const e of a)t[e]=o[e].evaluate(n,s);return t},t.reduce=(e,t)=>{s.properties=t;for(const t of a)n.accumulated=e[t],e[t]=i[t].evaluate(n,s);},t}(t)).load((yield this._pendingData).features):(i=yield this._pendingData,new ee(i,t.geojsonVtOptions)),this.loaded={};const r={};if(o){const e=o.finish();e&&(r.resourceTiming={},r.resourceTiming[t.source]=JSON.parse(JSON.stringify(e)));}return r}catch(t){if(delete this._pendingRequest,e.isAbortError(t))return {abandoned:!0};throw t}var i;}))}getData(){return e.__awaiter(this,void 0,void 0,(function*(){return this._pendingData}))}reloadTile(e){const t=this.loaded;return t&&t[e.uid]?super.reloadTile(e):this.loadTile(e)}loadAndProcessGeoJSON(t,r){return e.__awaiter(this,void 0,void 0,(function*(){let o=yield this.loadGeoJSON(t,r);if(delete this._pendingRequest,"object"!=typeof o)throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`);if(s(o,!0),t.filter){const r=e.createExpression(t.filter,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if("error"===r.result)throw new Error(r.value.map((e=>`${e.key}: ${e.message}`)).join(", "));const i=o.features.filter((e=>r.value.evaluate({zoom:0},e)));o={type:"FeatureCollection",features:i};}return o}))}loadGeoJSON(t,r){return e.__awaiter(this,void 0,void 0,(function*(){const{promoteId:o}=t;if(t.request){const i=yield e.getJSON(t.request,r);return this._dataUpdateable=oe(i.data,o)?ie(i.data,o):void 0,i.data}if("string"==typeof t.data)try{const e=JSON.parse(t.data);return this._dataUpdateable=oe(e,o)?ie(e,o):void 0,e}catch(e){throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`)}if(!t.dataDiff)throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`);if(!this._dataUpdateable)throw new Error(`Cannot update existing geojson data in ${t.source}`);return function(e,t,r){var o,i,n,s;if(t.removeAll&&e.clear(),t.remove)for(const r of t.remove)e.delete(r);if(t.add)for(const o of t.add){const t=re(o,r);null!=t&&e.set(t,o);}if(t.update)for(const r of t.update){let t=e.get(r.id);if(null==t)continue;const a=!r.removeAllProperties&&((null===(o=r.removeProperties)||void 0===o?void 0:o.length)>0||(null===(i=r.addOrUpdateProperties)||void 0===i?void 0:i.length)>0);if((r.newGeometry||r.removeAllProperties||a)&&(t=Object.assign({},t),e.set(r.id,t),a&&(t.properties=Object.assign({},t.properties))),r.newGeometry&&(t.geometry=r.newGeometry),r.removeAllProperties)t.properties={};else if((null===(n=r.removeProperties)||void 0===n?void 0:n.length)>0)for(const e of r.removeProperties)Object.prototype.hasOwnProperty.call(t.properties,e)&&delete t.properties[e];if((null===(s=r.addOrUpdateProperties)||void 0===s?void 0:s.length)>0)for(const{key:e,value:o}of r.addOrUpdateProperties)t.properties[e]=o;}}(this._dataUpdateable,t.dataDiff,o),{type:"FeatureCollection",features:Array.from(this._dataUpdateable.values())}}))}removeSource(t){return e.__awaiter(this,void 0,void 0,(function*(){this._pendingRequest&&this._pendingRequest.abort();}))}getClusterExpansionZoom(e){return this._geoJSONIndex.getClusterExpansionZoom(e.clusterId)}getClusterChildren(e){return this._geoJSONIndex.getChildren(e.clusterId)}getClusterLeaves(e){return this._geoJSONIndex.getLeaves(e.clusterId,e.limit,e.offset)}}class se{constructor(t){this.self=t,this.actor=new e.Actor(t),this.layerIndexes={},this.availableImages={},this.workerSources={},this.demWorkerSources={},this.externalWorkerSourceTypes={},this.self.registerWorkerSource=(e,t)=>{if(this.externalWorkerSourceTypes[e])throw new Error(`Worker source with name "${e}" already registered.`);this.externalWorkerSourceTypes[e]=t;},this.self.addProtocol=e.addProtocol,this.self.removeProtocol=e.removeProtocol,this.self.registerRTLTextPlugin=t=>{e.rtlWorkerPlugin.setMethods(t);},this.actor.registerMessageHandler("LDT",((e,t)=>this._getDEMWorkerSource(e,t.source).loadTile(t))),this.actor.registerMessageHandler("RDT",((t,r)=>e.__awaiter(this,void 0,void 0,(function*(){this._getDEMWorkerSource(t,r.source).removeTile(r);})))),this.actor.registerMessageHandler("GCEZ",((t,r)=>e.__awaiter(this,void 0,void 0,(function*(){return this._getWorkerSource(t,r.type,r.source).getClusterExpansionZoom(r)})))),this.actor.registerMessageHandler("GCC",((t,r)=>e.__awaiter(this,void 0,void 0,(function*(){return this._getWorkerSource(t,r.type,r.source).getClusterChildren(r)})))),this.actor.registerMessageHandler("GCL",((t,r)=>e.__awaiter(this,void 0,void 0,(function*(){return this._getWorkerSource(t,r.type,r.source).getClusterLeaves(r)})))),this.actor.registerMessageHandler("LD",((e,t)=>this._getWorkerSource(e,t.type,t.source).loadData(t))),this.actor.registerMessageHandler("GD",((e,t)=>this._getWorkerSource(e,t.type,t.source).getData())),this.actor.registerMessageHandler("LT",((e,t)=>this._getWorkerSource(e,t.type,t.source).loadTile(t))),this.actor.registerMessageHandler("RT",((e,t)=>this._getWorkerSource(e,t.type,t.source).reloadTile(t))),this.actor.registerMessageHandler("AT",((e,t)=>this._getWorkerSource(e,t.type,t.source).abortTile(t))),this.actor.registerMessageHandler("RMT",((e,t)=>this._getWorkerSource(e,t.type,t.source).removeTile(t))),this.actor.registerMessageHandler("RS",((t,r)=>e.__awaiter(this,void 0,void 0,(function*(){if(!this.workerSources[t]||!this.workerSources[t][r.type]||!this.workerSources[t][r.type][r.source])return;const e=this.workerSources[t][r.type][r.source];delete this.workerSources[t][r.type][r.source],void 0!==e.removeSource&&e.removeSource(r);})))),this.actor.registerMessageHandler("RM",(t=>e.__awaiter(this,void 0,void 0,(function*(){delete this.layerIndexes[t],delete this.availableImages[t],delete this.workerSources[t],delete this.demWorkerSources[t];})))),this.actor.registerMessageHandler("SR",((t,r)=>e.__awaiter(this,void 0,void 0,(function*(){this.referrer=r;})))),this.actor.registerMessageHandler("SRPS",((e,t)=>this._syncRTLPluginState(e,t))),this.actor.registerMessageHandler("IS",((t,r)=>e.__awaiter(this,void 0,void 0,(function*(){this.self.importScripts(r);})))),this.actor.registerMessageHandler("SI",((e,t)=>this._setImages(e,t))),this.actor.registerMessageHandler("UL",((t,r)=>e.__awaiter(this,void 0,void 0,(function*(){this._getLayerIndex(t).update(r.layers,r.removedIds);})))),this.actor.registerMessageHandler("SL",((t,r)=>e.__awaiter(this,void 0,void 0,(function*(){this._getLayerIndex(t).replace(r);}))));}_setImages(t,r){return e.__awaiter(this,void 0,void 0,(function*(){this.availableImages[t]=r;for(const e in this.workerSources[t]){const o=this.workerSources[t][e];for(const e in o)o[e].availableImages=r;}}))}_syncRTLPluginState(t,r){return e.__awaiter(this,void 0,void 0,(function*(){return yield e.rtlWorkerPlugin.syncState(r,this.self.importScripts)}))}_getAvailableImages(e){let t=this.availableImages[e];return t||(t=[]),t}_getLayerIndex(t){let r=this.layerIndexes[t];return r||(r=this.layerIndexes[t]=new e.StyleLayerIndex),r}_getWorkerSource(e,r,o){if(this.workerSources[e]||(this.workerSources[e]={}),this.workerSources[e][r]||(this.workerSources[e][r]={}),!this.workerSources[e][r][o]){const i={sendAsync:(t,r)=>(t.targetMapId=e,this.actor.sendAsync(t,r))};switch(r){case"vector":this.workerSources[e][r][o]=new t(i,this._getLayerIndex(e),this._getAvailableImages(e));break;case"geojson":this.workerSources[e][r][o]=new ne(i,this._getLayerIndex(e),this._getAvailableImages(e));break;default:this.workerSources[e][r][o]=new this.externalWorkerSourceTypes[r](i,this._getLayerIndex(e),this._getAvailableImages(e));}}return this.workerSources[e][r][o]}_getDEMWorkerSource(e,t){return this.demWorkerSources[e]||(this.demWorkerSources[e]={}),this.demWorkerSources[e][t]||(this.demWorkerSources[e][t]=new r),this.demWorkerSources[e][t]}}return e.isWorker(self)&&(self.worker=new se(self)),se})); -define("index",["exports","./shared"],(function(e,t){"use strict";function i(){var e=new t.ARRAY_TYPE(4);return t.ARRAY_TYPE!=Float32Array&&(e[1]=0,e[2]=0),e[0]=1,e[3]=1,e}function r(e){return e.map((e=>{const{coordinates:i}=e.geometry,{zoom:r}=e.properties,{x:o,y:a}=t.MercatorCoordinate.fromLngLat({lng:i[0],lat:i[1]}),s=Math.pow(2,r),n=Math.floor(o*s),l=Math.floor(a*s);return {description:e.properties.place_name,tileID:[new t.OverscaledTileID(r,0,r,n,l)],zoom:r,center:i}}))}var o=[{type:"Feature",geometry:{type:"Point",coordinates:[-95.392,29.799]},properties:{place_name:"Roads, Houston, z12",zoom:12,tags:["road"]}},{type:"Feature",geometry:{type:"Point",coordinates:[-95.381,29.749]},properties:{place_name:"Roads, Houston, z13",zoom:13,tags:["road","poi_label","landuse"]}},{type:"Feature",geometry:{type:"Point",coordinates:[-73.985,40.758]},properties:{place_name:"High zoom labels, buildings, roads, New York City, z16",zoom:16,tags:["poi_label","building","road"]}},{type:"Feature",geometry:{type:"Point",coordinates:[-73.985,40.758]},properties:{place_name:"High zoom labels, buildings, roads, New York City, z17, overzoomed",zoom:17,tags:["poi_label","road","building"]}},{type:"Feature",geometry:{type:"Point",coordinates:[139.76,35.695]},properties:{place_name:"High zoom cjk labels, when using local lang, buildings, roads, Tokyo, z16",zoom:16,tags:["poi_label","building","road"]}},{type:"Feature",geometry:{type:"Point",coordinates:[139.76,35.695]},properties:{place_name:"High zoom cjk labels, when using local lang, buildings, roads, Tokyo, z17, overzoomed",zoom:17,tags:["poi_label","road","building"]}},{type:"Feature",geometry:{type:"Point",coordinates:[27.602,61.521]},properties:{place_name:"Water, Finland, z10",zoom:10,tags:["water"]}},{type:"Feature",geometry:{type:"Point",coordinates:[2.21,48.745]},properties:{place_name:"Landuse and roads, Paris, z11",zoom:11,tags:["place_label:settlement","road","landuse","poi_label","hillshade"]}},{type:"Feature",geometry:{type:"Point",coordinates:[-118.314,33.996]},properties:{place_name:"Buildings, LA, z16",zoom:16,tags:["building","road"]}},{type:"Feature",geometry:{type:"Point",coordinates:[2.316,48.867]},properties:{place_name:"High zoom roads, paths, landuse, labels, Paris, 15",zoom:15,tags:["road","road:pedestrian","poi_label","landuse","transit_stop_label"]}},{type:"Feature",geometry:{type:"Point",coordinates:[2.316,48.867]},properties:{place_name:"High zoom pedestrian polygon fills, roads, paths, landuse, labels, Paris, z16",zoom:16,tags:["landuse","road","road:pedestrian","poi_label","road:path"]}},{type:"Feature",geometry:{type:"Point",coordinates:[8.835,46.317]},properties:{place_name:"Hillshading, Switzerland, z9",zoom:9,tags:["hillshade","place_label"]}},{type:"Feature",geometry:{type:"Point",coordinates:[8.835,46.317]},properties:{place_name:"Hillshading and contours, Switzerland, z12",zoom:12,tags:["hillshade"]}},{type:"Feature",geometry:{type:"Point",coordinates:[8.416,51.056]},properties:{place_name:"Landcover, Germany z6",zoom:6,tags:["landcover","place_label:settlement","road","admin"]}},{type:"Feature",geometry:{type:"Point",coordinates:[7.762,50.322]},properties:{place_name:"Landcover, Germany z8",zoom:8,tags:["place_label:settlement","road","hillshade"]}}];class a{constructor(){this.minimumMeasurements=210;}setup(){}bench(){}teardown(){}run(){return t.__awaiter(this,void 0,void 0,(function*(){try{return yield this.setup(),this._begin()}catch(e){console.error(e);}}))}_done(){return this._elapsed>=500&&this._measurements.length>this.minimumMeasurements}_begin(){this._measurements=[],this._elapsed=0,this._iterationsPerMeasurement=1,this._start=performance.now();const e=this.bench();return e instanceof Promise?e.then((()=>this._measureAsync())):this._measureSync()}_measureSync(){for(;;){const e=performance.now()-this._start;if(this._elapsed+=e,e<5?this._iterationsPerMeasurement++:this._measurements.push({time:e,iterations:this._iterationsPerMeasurement}),this._done())return this._end();this._start=performance.now();for(let e=this._iterationsPerMeasurement;e>0;--e)this.bench();}}_measureAsync(){return t.__awaiter(this,void 0,void 0,(function*(){for(;;){const e=performance.now()-this._start;if(this._elapsed+=e,e<5?this._iterationsPerMeasurement++:this._measurements.push({time:e,iterations:this._iterationsPerMeasurement}),this._done())return this._end();this._start=performance.now();for(let e=this._iterationsPerMeasurement;e>0;--e)yield this.bench();}}))}_end(){return t.__awaiter(this,void 0,void 0,(function*(){return yield this.teardown(),this._measurements}))}}function s(e){return "string"==typeof e?fetch(e).then((e=>e.json())):Promise.resolve(e)}const n={supported:!1,testSupport:function(e){!h&&c&&(u?d(e):l=e);}};let l,c,h=!1,u=!1;function d(e){const t=e.createTexture();e.bindTexture(e.TEXTURE_2D,t);try{if(e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,c),e.isContextLost())return;n.supported=!0;}catch(e){}e.deleteTexture(t),h=!0;}var _;let p,m;"undefined"!=typeof document&&(c=document.createElement("img"),c.onload=()=>{l&&d(l),l=null,u=!0;},c.onerror=()=>{h=!0,l=null;},c.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA="),function(e){let i,r,o,a;e.resetRequestQueue=()=>{i=[],r=0,o=0,a={};},e.addThrottleControl=e=>{const t=o++;return a[t]=e,t},e.removeThrottleControl=e=>{delete a[e],l();},e.getImage=(e,r,o=!0)=>new Promise(((a,s)=>{n.supported&&(e.headers||(e.headers={}),e.headers.accept="image/webp,*/*"),t.extend(e,{type:"image"}),i.push({abortController:r,requestParameters:e,supportImageRefresh:o,state:"queued",onError:e=>{s(e);},onSuccess:e=>{a(e);}}),l();}));const s=e=>t.__awaiter(this,void 0,void 0,(function*(){e.state="running";const{requestParameters:i,supportImageRefresh:o,onError:a,onSuccess:s,abortController:n}=e,h=!1===o&&!t.isWorker(self)&&!t.getProtocol(i.url)&&(!i.headers||Object.keys(i.headers).reduce(((e,t)=>e&&"accept"===t),!0));r++;const u=h?c(i,n):t.makeRequest(i,n);try{const i=yield u;delete e.abortController,e.state="completed",i.data instanceof HTMLImageElement||t.isImageBitmap(i.data)?s(i):i.data&&s({data:yield(d=i.data,"function"==typeof createImageBitmap?t.arrayBufferToImageBitmap(d):t.arrayBufferToImage(d)),cacheControl:i.cacheControl,expires:i.expires});}catch(t){delete e.abortController,a(t);}finally{r--,l();}var d;})),l=()=>{const e=(()=>{for(const e of Object.keys(a))if(a[e]())return !0;return !1})()?t.config.MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME:t.config.MAX_PARALLEL_IMAGE_REQUESTS;for(let t=r;t0;t++){const e=i.shift();e.abortController.signal.aborted?t--:s(e);}},c=(e,i)=>new Promise(((r,o)=>{const a=new Image,s=e.url,n=e.credentials;n&&"include"===n?a.crossOrigin="use-credentials":(n&&"same-origin"===n||!t.sameOrigin(s))&&(a.crossOrigin="anonymous"),i.signal.addEventListener("abort",(()=>{a.src="",o(t.createAbortError());})),a.fetchPriority="high",a.onload=()=>{a.onerror=a.onload=null,r({data:a});},a.onerror=()=>{a.onerror=a.onload=null,i.signal.aborted||o(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."));},a.src=s;}));}(_||(_={})),_.resetRequestQueue();const f={now:"undefined"!=typeof performance&&performance&&performance.now?performance.now.bind(performance):Date.now.bind(Date),frameAsync:e=>new Promise(((i,r)=>{const o=requestAnimationFrame(i);e.signal.addEventListener("abort",(()=>{cancelAnimationFrame(o),r(t.createAbortError());}));})),getImageData(e,t=0){return this.getImageCanvasContext(e).getImageData(-t,-t,e.width+2*t,e.height+2*t)},getImageCanvasContext(e){const t=window.document.createElement("canvas"),i=t.getContext("2d",{willReadFrequently:!0});if(!i)throw new Error("failed to create canvas 2d context");return t.width=e.width,t.height=e.height,i.drawImage(e,0,0,e.width,e.height),i},resolveURL:e=>(p||(p=document.createElement("a")),p.href=e,p.href),hardwareConcurrency:"undefined"!=typeof navigator&&navigator.hardwareConcurrency||4,get prefersReducedMotion(){return !!matchMedia&&(null==m&&(m=matchMedia("(prefers-reduced-motion: reduce)")),m.matches)}};function g(e){const t=[];if("string"==typeof e)t.push({id:"default",url:e});else if(e&&e.length>0){const i=[];for(const{id:r,url:o}of e){const e=`${r}${o}`;-1===i.indexOf(e)&&(i.push(e),t.push({id:r,url:o}));}}return t}function v(e,t,i){try{const r=new URL(e);return r.pathname+=`${t}${i}`,r.toString()}catch(t){throw new Error(`Invalid sprite URL "${e}", must be absolute. Modify style specification directly or use TransformStyleFunction to correct the issue dynamically`)}}class y{constructor(e,t,i,r){this.context=e,this.format=i,this.texture=e.gl.createTexture(),this.update(t,r);}update(e,i,r){const{width:o,height:a}=e,s=!(this.size&&this.size[0]===o&&this.size[1]===a||r),{context:n}=this,{gl:l}=n;if(this.useMipmap=Boolean(i&&i.useMipmap),l.bindTexture(l.TEXTURE_2D,this.texture),n.pixelStoreUnpackFlipY.set(!1),n.pixelStoreUnpack.set(1),n.pixelStoreUnpackPremultiplyAlpha.set(this.format===l.RGBA&&(!i||!1!==i.premultiply)),s)this.size=[o,a],e instanceof HTMLImageElement||e instanceof HTMLCanvasElement||e instanceof HTMLVideoElement||e instanceof ImageData||t.isImageBitmap(e)?l.texImage2D(l.TEXTURE_2D,0,this.format,this.format,l.UNSIGNED_BYTE,e):l.texImage2D(l.TEXTURE_2D,0,this.format,o,a,0,this.format,l.UNSIGNED_BYTE,e.data);else {const{x:i,y:s}=r||{x:0,y:0};e instanceof HTMLImageElement||e instanceof HTMLCanvasElement||e instanceof HTMLVideoElement||e instanceof ImageData||t.isImageBitmap(e)?l.texSubImage2D(l.TEXTURE_2D,0,i,s,l.RGBA,l.UNSIGNED_BYTE,e):l.texSubImage2D(l.TEXTURE_2D,0,i,s,o,a,l.RGBA,l.UNSIGNED_BYTE,e.data);}this.useMipmap&&this.isSizePowerOfTwo()&&l.generateMipmap(l.TEXTURE_2D);}bind(e,t,i){const{context:r}=this,{gl:o}=r;o.bindTexture(o.TEXTURE_2D,this.texture),i!==o.LINEAR_MIPMAP_NEAREST||this.isSizePowerOfTwo()||(i=o.LINEAR),e!==this.filter&&(o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,e),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,i||e),this.filter=e),t!==this.wrap&&(o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,t),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,t),this.wrap=t);}isSizePowerOfTwo(){return this.size[0]===this.size[1]&&Math.log(this.size[0])/Math.LN2%1==0}destroy(){const{gl:e}=this.context;e.deleteTexture(this.texture),this.texture=null;}}function x(e){const{userImage:t}=e;return !!(t&&t.render&&t.render())&&(e.data.replace(new Uint8Array(t.data.buffer)),!0)}class b extends t.Evented{constructor(){super(),this.images={},this.updatedImages={},this.callbackDispatchedThisFrame={},this.loaded=!1,this.requestors=[],this.patterns={},this.atlasImage=new t.RGBAImage({width:1,height:1}),this.dirty=!0;}isLoaded(){return this.loaded}setLoaded(e){if(this.loaded!==e&&(this.loaded=e,e)){for(const{ids:e,promiseResolve:t}of this.requestors)t(this._getImagesForIds(e));this.requestors=[];}}getImage(e){const i=this.images[e];if(i&&!i.data&&i.spriteData){const e=i.spriteData;i.data=new t.RGBAImage({width:e.width,height:e.height},e.context.getImageData(e.x,e.y,e.width,e.height).data),i.spriteData=null;}return i}addImage(e,t){if(this.images[e])throw new Error(`Image id ${e} already exist, use updateImage instead`);this._validate(e,t)&&(this.images[e]=t);}_validate(e,i){let r=!0;const o=i.data||i.spriteData;return this._validateStretch(i.stretchX,o&&o.width)||(this.fire(new t.ErrorEvent(new Error(`Image "${e}" has invalid "stretchX" value`))),r=!1),this._validateStretch(i.stretchY,o&&o.height)||(this.fire(new t.ErrorEvent(new Error(`Image "${e}" has invalid "stretchY" value`))),r=!1),this._validateContent(i.content,i)||(this.fire(new t.ErrorEvent(new Error(`Image "${e}" has invalid "content" value`))),r=!1),r}_validateStretch(e,t){if(!e)return !0;let i=0;for(const r of e){if(r[0]{let r=!0;if(!this.isLoaded())for(const t of e)this.images[t]||(r=!1);this.isLoaded()||r?t(this._getImagesForIds(e)):this.requestors.push({ids:e,promiseResolve:t});}))}_getImagesForIds(e){const i={};for(const r of e){let e=this.getImage(r);e||(this.fire(new t.Event("styleimagemissing",{id:r})),e=this.getImage(r)),e?i[r]={data:e.data.clone(),pixelRatio:e.pixelRatio,sdf:e.sdf,version:e.version,stretchX:e.stretchX,stretchY:e.stretchY,content:e.content,textFitWidth:e.textFitWidth,textFitHeight:e.textFitHeight,hasRenderCallback:Boolean(e.userImage&&e.userImage.render)}:t.warnOnce(`Image "${r}" 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 i}getPixelSize(){const{width:e,height:t}=this.atlasImage;return {width:e,height:t}}getPattern(e){const i=this.patterns[e],r=this.getImage(e);if(!r)return null;if(i&&i.position.version===r.version)return i.position;if(i)i.position.version=r.version;else {const i={w:r.data.width+2,h:r.data.height+2,x:0,y:0},o=new t.ImagePosition(i,r);this.patterns[e]={bin:i,position:o};}return this._updatePatternAtlas(),this.patterns[e].position}bind(e){const t=e.gl;this.atlasTexture?this.dirty&&(this.atlasTexture.update(this.atlasImage),this.dirty=!1):this.atlasTexture=new y(e,this.atlasImage,t.RGBA),this.atlasTexture.bind(t.LINEAR,t.CLAMP_TO_EDGE);}_updatePatternAtlas(){const e=[];for(const t in this.patterns)e.push(this.patterns[t].bin);const{w:i,h:r}=t.potpack(e),o=this.atlasImage;o.resize({width:i||1,height:r||1});for(const e in this.patterns){const{bin:i}=this.patterns[e],r=i.x+1,a=i.y+1,s=this.getImage(e).data,n=s.width,l=s.height;t.RGBAImage.copy(s,o,{x:0,y:0},{x:r,y:a},{width:n,height:l}),t.RGBAImage.copy(s,o,{x:0,y:l-1},{x:r,y:a-1},{width:n,height:1}),t.RGBAImage.copy(s,o,{x:0,y:0},{x:r,y:a+l},{width:n,height:1}),t.RGBAImage.copy(s,o,{x:n-1,y:0},{x:r-1,y:a},{width:1,height:l}),t.RGBAImage.copy(s,o,{x:0,y:0},{x:r+n,y:a},{width:1,height:l});}this.dirty=!0;}beginFrame(){this.callbackDispatchedThisFrame={};}dispatchRenderCallbacks(e){for(const i of e){if(this.callbackDispatchedThisFrame[i])continue;this.callbackDispatchedThisFrame[i]=!0;const e=this.getImage(i);e||t.warnOnce(`Image with ID: "${i}" was not found`),x(e)&&this.updateImage(i,e);}}}const w=1e20;function T(e,t,i,r,o,a,s,n,l){for(let c=t;c-1);l++,a[l]=n,s[l]=c,s[l+1]=w;}for(let n=0,l=0;n65535)throw new Error("glyphs > 65535 not supported");if(t.ranges[o])return {stack:e,id:i,glyph:r};if(!this.url)throw new Error("glyphsUrl is not set");if(!t.requests[o]){const i=P.loadGlyphRange(e,o,this.url,this.requestManager);t.requests[o]=i;}const a=yield t.requests[o];for(const e in a)this._doesCharSupportLocalGlyph(+e)||(t.glyphs[+e]=a[+e]);return t.ranges[o]=!0,{stack:e,id:i,glyph:a[i]||null}}))}_doesCharSupportLocalGlyph(e){return !!this.localIdeographFontFamily&&/\p{Ideo}|\p{sc=Hang}|\p{sc=Hira}|\p{sc=Kana}/u.test(String.fromCodePoint(e))}_tinySDF(e,i,r){const o=this.localIdeographFontFamily;if(!o)return;if(!this._doesCharSupportLocalGlyph(r))return;let a=e.tinySDF;if(!a){let t="400";/bold/i.test(i)?t="900":/medium/i.test(i)?t="500":/light/i.test(i)&&(t="200"),a=e.tinySDF=new P.TinySDF({fontSize:48,buffer:6,radius:16,cutoff:.25,fontFamily:o,fontWeight:t});}const s=a.draw(String.fromCharCode(r));return {id:r,bitmap:new t.AlphaImage({width:s.width||60,height:s.height||60},s.data),metrics:{width:s.glyphWidth/2||24,height:s.glyphHeight/2||24,left:s.glyphLeft/2+.5||0,top:s.glyphTop/2-27.5||-8,advance:s.glyphAdvance/2||24,isDoubleResolution:!0}}}}P.loadGlyphRange=function(e,i,r,o){return t.__awaiter(this,void 0,void 0,(function*(){const a=256*i,s=a+255,n=o.transformRequest(r.replace("{fontstack}",e).replace("{range}",`${a}-${s}`),"Glyphs"),l=yield t.getArrayBuffer(n,new AbortController);if(!l||!l.data)throw new Error(`Could not load glyph range. range: ${i}, ${a}-${s}`);const c={};for(const e of t.parseGlyphPbf(l.data))c[e.id]=e;return c}))},P.TinySDF=class{constructor({fontSize:e=24,buffer:t=3,radius:i=8,cutoff:r=.25,fontFamily:o="sans-serif",fontWeight:a="normal",fontStyle:s="normal"}={}){this.buffer=t,this.cutoff=r,this.radius=i;const n=this.size=e+4*t,l=this._createCanvas(n),c=this.ctx=l.getContext("2d",{willReadFrequently:!0});c.font=`${s} ${a} ${e}px ${o}`,c.textBaseline="alphabetic",c.textAlign="left",c.fillStyle="black",this.gridOuter=new Float64Array(n*n),this.gridInner=new Float64Array(n*n),this.f=new Float64Array(n),this.z=new Float64Array(n+1),this.v=new Uint16Array(n);}_createCanvas(e){const t=document.createElement("canvas");return t.width=t.height=e,t}draw(e){const{width:t,actualBoundingBoxAscent:i,actualBoundingBoxDescent:r,actualBoundingBoxLeft:o,actualBoundingBoxRight:a}=this.ctx.measureText(e),s=Math.ceil(i),n=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(a-o))),l=Math.min(this.size-this.buffer,s+Math.ceil(r)),c=n+2*this.buffer,h=l+2*this.buffer,u=Math.max(c*h,0),d=new Uint8ClampedArray(u),_={data:d,width:c,height:h,glyphWidth:n,glyphHeight:l,glyphTop:s,glyphLeft:0,glyphAdvance:t};if(0===n||0===l)return _;const{ctx:p,buffer:m,gridInner:f,gridOuter:g}=this;p.clearRect(m,m,n,l),p.fillText(e,m,m+s);const v=p.getImageData(m,m,n,l);g.fill(w,0,u),f.fill(0,0,u);for(let e=0;e0?e*e:0,f[r]=e<0?e*e:0;}}T(g,0,0,c,h,c,this.f,this.v,this.z),T(f,m,m,n,l,c,this.f,this.v,this.z);for(let e=0;e1&&(s=e[++a]);const l=Math.abs(n-s.left),c=Math.abs(n-s.right),h=Math.min(l,c);let u;const d=t/i*(r+1);if(s.isDash){const e=r-Math.abs(d);u=Math.sqrt(h*h+e*e);}else u=r-Math.sqrt(h*h+d*d);this.data[o+n]=Math.max(0,Math.min(255,u+128));}}}addRegularDash(e){for(let t=e.length-1;t>=0;--t){const i=e[t],r=e[t+1];i.zeroLength?e.splice(t,1):r&&r.isDash===i.isDash&&(r.left=i.left,e.splice(t,1));}const t=e[0],i=e[e.length-1];t.isDash===i.isDash&&(t.left=i.left-this.width,i.right=t.right+this.width);const r=this.width*this.nextRow;let o=0,a=e[o];for(let t=0;t1&&(a=e[++o]);const i=Math.abs(t-a.left),s=Math.abs(t-a.right),n=Math.min(i,s);this.data[r+t]=Math.max(0,Math.min(255,(a.isDash?n:-n)+128));}}addDash(e,i){const r=i?7:0,o=2*r+1;if(this.nextRow+o>this.height)return t.warnOnce("LineAtlas out of space"),null;let a=0;for(let t=0;t{e.terminate();})),this.workers=null);}isPreloaded(){return !!this.active[z]}numActive(){return Object.keys(this.active).length}}const A=Math.floor(f.hardwareConcurrency/2);let k,F;function B(){return k||(k=new L),k}L.workerCount=t.isSafari(globalThis)?Math.max(Math.min(A,3),1):1;class O{constructor(e,i){this.workerPool=e,this.actors=[],this.currentActor=0,this.id=i;const r=this.workerPool.acquire(i);for(let e=0;e{e.remove();})),this.actors=[],e&&this.workerPool.release(this.id);}registerMessageHandler(e,t){for(const i of this.actors)i.registerMessageHandler(e,t);}}function U(){return F||(F=new O(B(),t.GLOBAL_DISPATCHER_ID),F.registerMessageHandler("GR",((e,i,r)=>t.makeRequest(i,r)))),F}function j(e,i){const r=t.create();return t.translate(r,r,[1,1,0]),t.scale(r,r,[.5*e.width,.5*e.height,1]),e.calculatePosMatrix?t.multiply(r,r,e.calculatePosMatrix(i.toUnwrapped())):r}function N(e,t,i,r,o,a){var s;const n=function(e,t,i){if(e)for(const r of e){const e=t[r];if(e&&e.source===i&&"fill-extrusion"===e.type)return !0}else for(const e in t){const r=t[e];if(r.source===i&&"fill-extrusion"===r.type)return !0}return !1}(null!==(s=null==o?void 0:o.layers)&&void 0!==s?s:null,t,e.id),l=a.maxPitchScaleFactor(),c=e.tilesIn(r,l,n);c.sort(G);const h=[];for(const r of c)h.push({wrappedTileID:r.tileID.wrapped().key,queryResults:r.tile.queryRenderedFeatures(t,i,e._state,r.queryGeometry,r.cameraQueryGeometry,r.scale,o,a,l,j(e.transform,r.tileID))});const u=function(e){const t={},i={};for(const r of e){const e=r.queryResults,o=r.wrappedTileID,a=i[o]=i[o]||{};for(const i in e){const r=e[i],o=a[i]=a[i]||{},s=t[i]=t[i]||[];for(const e of r)o[e.featureIndex]||(o[e.featureIndex]=!0,s.push(e));}}return t}(h);for(const t in u)u[t].forEach((t=>{const i=t.feature,r=e.getFeatureState(i.layer["source-layer"],i.id);i.source=i.layer.source,i.layer["source-layer"]&&(i.sourceLayer=i.layer["source-layer"]),i.state=r;}));return u}function G(e,t){const i=e.tileID,r=t.tileID;return i.overscaledZ-r.overscaledZ||i.canonical.y-r.canonical.y||i.wrap-r.wrap||i.canonical.x-r.canonical.x}function Z(e,i,r){return t.__awaiter(this,void 0,void 0,(function*(){let o=e;if(e.url?o=(yield t.getJSON(i.transformRequest(e.url,"Source"),r)).data:yield f.frameAsync(r),!o)return null;const a=t.pick(t.extend(o,e),["tiles","minzoom","maxzoom","attribution","bounds","scheme","tileSize","encoding"]);return "vector_layers"in o&&o.vector_layers&&(a.vectorLayerIds=o.vector_layers.map((e=>e.id))),a}))}class V{constructor(e,t){e&&(t?this.setSouthWest(e).setNorthEast(t):Array.isArray(e)&&(4===e.length?this.setSouthWest([e[0],e[1]]).setNorthEast([e[2],e[3]]):this.setSouthWest(e[0]).setNorthEast(e[1])));}setNorthEast(e){return this._ne=e instanceof t.LngLat?new t.LngLat(e.lng,e.lat):t.LngLat.convert(e),this}setSouthWest(e){return this._sw=e instanceof t.LngLat?new t.LngLat(e.lng,e.lat):t.LngLat.convert(e),this}extend(e){const i=this._sw,r=this._ne;let o,a;if(e instanceof t.LngLat)o=e,a=e;else {if(!(e instanceof V))return Array.isArray(e)?4===e.length||e.every(Array.isArray)?this.extend(V.convert(e)):this.extend(t.LngLat.convert(e)):e&&("lng"in e||"lon"in e)&&"lat"in e?this.extend(t.LngLat.convert(e)):this;if(o=e._sw,a=e._ne,!o||!a)return this}return i||r?(i.lng=Math.min(o.lng,i.lng),i.lat=Math.min(o.lat,i.lat),r.lng=Math.max(a.lng,r.lng),r.lat=Math.max(a.lat,r.lat)):(this._sw=new t.LngLat(o.lng,o.lat),this._ne=new t.LngLat(a.lng,a.lat)),this}getCenter(){return new t.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 t.LngLat(this.getWest(),this.getNorth())}getSouthEast(){return new t.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(e){const{lng:i,lat:r}=t.LngLat.convert(e);let o=this._sw.lng<=i&&i<=this._ne.lng;return this._sw.lng>this._ne.lng&&(o=this._sw.lng>=i&&i>=this._ne.lng),this._sw.lat<=r&&r<=this._ne.lat&&o}static convert(e){return e instanceof V?e:e?new V(e):e}static fromLngLat(e,i=0){const r=360*i/40075017,o=r/Math.cos(Math.PI/180*e.lat);return new V(new t.LngLat(e.lng-o,e.lat-r),new t.LngLat(e.lng+o,e.lat+r))}adjustAntiMeridian(){const e=new t.LngLat(this._sw.lng,this._sw.lat),i=new t.LngLat(this._ne.lng,this._ne.lat);return new V(e,e.lng>i.lng?new t.LngLat(i.lng+360,i.lat):i)}}class q{constructor(e,t,i){this.bounds=V.convert(this.validateBounds(e)),this.minzoom=t||0,this.maxzoom=i||24;}validateBounds(e){return Array.isArray(e)&&4===e.length?[Math.max(-180,e[0]),Math.max(-90,e[1]),Math.min(180,e[2]),Math.min(90,e[3])]:[-180,-90,180,90]}contains(e){const i=Math.pow(2,e.z),r=Math.floor(t.mercatorXfromLng(this.bounds.getWest())*i),o=Math.floor(t.mercatorYfromLat(this.bounds.getNorth())*i),a=Math.ceil(t.mercatorXfromLng(this.bounds.getEast())*i),s=Math.ceil(t.mercatorYfromLat(this.bounds.getSouth())*i);return e.x>=r&&e.x=o&&e.y{this._options.tiles=e;})),this}setUrl(e){return this.setSourceProperty((()=>{this.url=e,this._options.url=e;})),this}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null);}serialize(){return t.extend({},this._options)}loadTile(e){return t.__awaiter(this,void 0,void 0,(function*(){const t=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),i={request:this.map._requestManager.transformRequest(t,"Tile"),uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,tileSize:this.tileSize*e.tileID.overscaleFactor(),type:this.type,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,subdivisionGranularity:this.map.style.projection.subdivisionGranularity};i.request.collectResourceTiming=this._collectResourceTiming;let r="RT";if(e.actor&&"expired"!==e.state){if("loading"===e.state)return new Promise(((t,i)=>{e.reloadPromise={resolve:t,reject:i};}))}else e.actor=this.dispatcher.getActor(),r="LT";e.abortController=new AbortController;try{const t=yield e.actor.sendAsync({type:r,data:i},e.abortController);if(delete e.abortController,e.aborted)return;this._afterTileLoadWorkerResponse(e,t);}catch(t){if(delete e.abortController,e.aborted)return;if(t&&404!==t.status)throw t;this._afterTileLoadWorkerResponse(e,null);}}))}_afterTileLoadWorkerResponse(e,t){if(t&&t.resourceTiming&&(e.resourceTiming=t.resourceTiming),t&&this.map._refreshExpiredTiles&&e.setExpiryData(t),e.loadVectorData(t,this.map.painter),e.reloadPromise){const t=e.reloadPromise;e.reloadPromise=null,this.loadTile(e).then(t.resolve).catch(t.reject);}}abortTile(e){return t.__awaiter(this,void 0,void 0,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController),e.actor&&(yield e.actor.sendAsync({type:"AT",data:{uid:e.uid,type:this.type,source:this.id}}));}))}unloadTile(e){return t.__awaiter(this,void 0,void 0,(function*(){e.unloadVectorData(),e.actor&&(yield e.actor.sendAsync({type:"RMT",data:{uid:e.uid,type:this.type,source:this.id}}));}))}hasTransition(){return !1}}class X extends t.Evented{constructor(e,i,r,o){super(),this.id=e,this.dispatcher=r,this.setEventedParent(o),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme="xyz",this.tileSize=512,this._loaded=!1,this._options=t.extend({type:"raster"},i),t.extend(this,t.pick(i,["url","scheme","tileSize"]));}load(){return t.__awaiter(this,arguments,void 0,(function*(e=!1){this._loaded=!1,this.fire(new t.Event("dataloading",{dataType:"source"})),this._tileJSONRequest=new AbortController;try{const i=yield Z(this._options,this.map._requestManager,this._tileJSONRequest);this._tileJSONRequest=null,this._loaded=!0,i&&(t.extend(this,i),i.bounds&&(this.tileBounds=new q(i.bounds,this.minzoom,this.maxzoom)),this.fire(new t.Event("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new t.Event("data",{dataType:"source",sourceDataType:"content",sourceDataChanged:e})));}catch(e){this._tileJSONRequest=null,this.fire(new t.ErrorEvent(e));}}))}loaded(){return this._loaded}onAdd(e){this.map=e,this.load();}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null);}setSourceProperty(e){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null),e(),this.load(!0);}setTiles(e){return this.setSourceProperty((()=>{this._options.tiles=e;})),this}setUrl(e){return this.setSourceProperty((()=>{this.url=e,this._options.url=e;})),this}serialize(){return t.extend({},this._options)}hasTile(e){return !this.tileBounds||this.tileBounds.contains(e.canonical)}loadTile(e){return t.__awaiter(this,void 0,void 0,(function*(){const t=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme);e.abortController=new AbortController;try{const i=yield _.getImage(this.map._requestManager.transformRequest(t,"Tile"),e.abortController,this.map._refreshExpiredTiles);if(delete e.abortController,e.aborted)return void(e.state="unloaded");if(i&&i.data){this.map._refreshExpiredTiles&&i.cacheControl&&i.expires&&e.setExpiryData({cacheControl:i.cacheControl,expires:i.expires});const t=this.map.painter.context,r=t.gl,o=i.data;e.texture=this.map.painter.getTileTexture(o.width),e.texture?e.texture.update(o,{useMipmap:!0}):(e.texture=new y(t,o,r.RGBA,{useMipmap:!0}),e.texture.bind(r.LINEAR,r.CLAMP_TO_EDGE,r.LINEAR_MIPMAP_NEAREST)),e.state="loaded";}}catch(t){if(delete e.abortController,e.aborted)e.state="unloaded";else if(t)throw e.state="errored",t}}))}abortTile(e){return t.__awaiter(this,void 0,void 0,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController);}))}unloadTile(e){return t.__awaiter(this,void 0,void 0,(function*(){e.texture&&this.map.painter.saveTileTexture(e.texture);}))}hasTransition(){return !1}}class $ extends X{constructor(e,i,r,o){super(e,i,r,o),this.type="raster-dem",this.maxzoom=22,this._options=t.extend({type:"raster-dem"},i),this.encoding=i.encoding||"mapbox",this.redFactor=i.redFactor,this.greenFactor=i.greenFactor,this.blueFactor=i.blueFactor,this.baseShift=i.baseShift;}loadTile(e){return t.__awaiter(this,void 0,void 0,(function*(){const i=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),r=this.map._requestManager.transformRequest(i,"Tile");e.neighboringTiles=this._getNeighboringTiles(e.tileID),e.abortController=new AbortController;try{const i=yield _.getImage(r,e.abortController,this.map._refreshExpiredTiles);if(delete e.abortController,e.aborted)return void(e.state="unloaded");if(i&&i.data){const r=i.data;this.map._refreshExpiredTiles&&i.cacheControl&&i.expires&&e.setExpiryData({cacheControl:i.cacheControl,expires:i.expires});const o=t.isImageBitmap(r)&&t.offscreenCanvasSupported()?r:yield this.readImageNow(r),a={type:this.type,uid:e.uid,source:this.id,rawImageData:o,encoding:this.encoding,redFactor:this.redFactor,greenFactor:this.greenFactor,blueFactor:this.blueFactor,baseShift:this.baseShift};if(!e.actor||"expired"===e.state){e.actor=this.dispatcher.getActor();const t=yield e.actor.sendAsync({type:"LDT",data:a});e.dem=t,e.needsHillshadePrepare=!0,e.needsTerrainPrepare=!0,e.state="loaded";}}}catch(t){if(delete e.abortController,e.aborted)e.state="unloaded";else if(t)throw e.state="errored",t}}))}readImageNow(e){return t.__awaiter(this,void 0,void 0,(function*(){if("undefined"!=typeof VideoFrame&&t.isOffscreenCanvasDistorted()){const i=e.width+2,r=e.height+2;try{return new t.RGBAImage({width:i,height:r},yield t.readImageUsingVideoFrame(e,-1,-1,i,r))}catch(e){}}return f.getImageData(e,1)}))}_getNeighboringTiles(e){const i=e.canonical,r=Math.pow(2,i.z),o=(i.x-1+r)%r,a=0===i.x?e.wrap-1:e.wrap,s=(i.x+1+r)%r,n=i.x+1===r?e.wrap+1:e.wrap,l={};return l[new t.OverscaledTileID(e.overscaledZ,a,i.z,o,i.y).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,n,i.z,s,i.y).key]={backfilled:!1},i.y>0&&(l[new t.OverscaledTileID(e.overscaledZ,a,i.z,o,i.y-1).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,e.wrap,i.z,i.x,i.y-1).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,n,i.z,s,i.y-1).key]={backfilled:!1}),i.y+10&&t.extend(o,{resourceTiming:r}),this.fire(new t.Event("data",Object.assign(Object.assign({},o),{sourceDataType:"metadata"}))),this.fire(new t.Event("data",Object.assign(Object.assign({},o),{sourceDataType:"content"})));}catch(e){if(this._pendingLoads--,this._removed)return void this.fire(new t.Event("dataabort",{dataType:"source"}));this.fire(new t.ErrorEvent(e));}}))}loaded(){return 0===this._pendingLoads}loadTile(e){return t.__awaiter(this,void 0,void 0,(function*(){const t=e.actor?"RT":"LT";e.actor=this.actor;const i={type:this.type,uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,subdivisionGranularity:this.map.style.projection.subdivisionGranularity};e.abortController=new AbortController;const r=yield this.actor.sendAsync({type:t,data:i},e.abortController);delete e.abortController,e.unloadVectorData(),e.aborted||e.loadVectorData(r,this.map.painter,"RT"===t);}))}abortTile(e){return t.__awaiter(this,void 0,void 0,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController),e.aborted=!0;}))}unloadTile(e){return t.__awaiter(this,void 0,void 0,(function*(){e.unloadVectorData(),yield this.actor.sendAsync({type:"RMT",data:{uid:e.uid,type:this.type,source:this.id}});}))}onRemove(){this._removed=!0,this.actor.sendAsync({type:"RS",data:{type:this.type,source:this.id}});}serialize(){return t.extend({},this._options,{type:this.type,data:this._data})}hasTransition(){return !1}}class K extends t.Evented{constructor(e,t,i,r){super(),this.flippedWindingOrder=!1,this.id=e,this.dispatcher=i,this.coordinates=t.coordinates,this.type="image",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.tiles={},this._loaded=!1,this.setEventedParent(r),this.options=t;}load(e){return t.__awaiter(this,void 0,void 0,(function*(){this._loaded=!1,this.fire(new t.Event("dataloading",{dataType:"source"})),this.url=this.options.url,this._request=new AbortController;try{const t=yield _.getImage(this.map._requestManager.transformRequest(this.url,"Image"),this._request);this._request=null,this._loaded=!0,t&&t.data&&(this.image=t.data,e&&(this.coordinates=e),this._finishLoading());}catch(e){this._request=null,this._loaded=!0,this.fire(new t.ErrorEvent(e));}}))}loaded(){return this._loaded}updateImage(e){return e.url?(this._request&&(this._request.abort(),this._request=null),this.options.url=e.url,this.load(e.coordinates).finally((()=>{this.texture=null;})),this):this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new t.Event("data",{dataType:"source",sourceDataType:"metadata"})));}onAdd(e){this.map=e,this.load();}onRemove(){this._request&&(this._request.abort(),this._request=null);}setCoordinates(e){this.coordinates=e;const i=e.map(t.MercatorCoordinate.fromLngLat);var r;return this.tileID=function(e){let i=1/0,r=1/0,o=-1/0,a=-1/0;for(const t of e)i=Math.min(i,t.x),r=Math.min(r,t.y),o=Math.max(o,t.x),a=Math.max(a,t.y);const s=Math.max(o-i,a-r),n=Math.max(0,Math.floor(-Math.log(s)/Math.LN2)),l=Math.pow(2,n);return new t.CanonicalTileID(n,Math.floor((i+o)/2*l),Math.floor((r+a)/2*l))}(i),this.minzoom=this.maxzoom=this.tileID.z,this.tileCoords=i.map((e=>this.tileID.getTilePoint(e)._round())),this.flippedWindingOrder=((r=this.tileCoords)[1].x-r[0].x)*(r[2].y-r[0].y)-(r[1].y-r[0].y)*(r[2].x-r[0].x)<0,this.fire(new t.Event("data",{dataType:"source",sourceDataType:"content"})),this}prepare(){if(0===Object.keys(this.tiles).length||!this.image)return;const e=this.map.painter.context,i=e.gl;this.texture||(this.texture=new y(e,this.image,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE));let r=!1;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,r=!0);}r&&this.fire(new t.Event("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}loadTile(e){return t.__awaiter(this,void 0,void 0,(function*(){this.tileID&&this.tileID.equals(e.tileID.canonical)?(this.tiles[String(e.tileID.wrap)]=e,e.buckets={}):e.state="errored";}))}serialize(){return {type:"image",url:this.options.url,coordinates:this.coordinates}}hasTransition(){return !1}}class Y extends K{constructor(e,t,i,r){super(e,t,i,r),this.roundZoom=!0,this.type="video",this.options=t;}load(){return t.__awaiter(this,void 0,void 0,(function*(){this._loaded=!1;const e=this.options;this.urls=[];for(const t of e.urls)this.urls.push(this.map._requestManager.transformRequest(t,"Source").url);try{const e=yield t.getVideo(this.urls);if(this._loaded=!0,!e)return;this.video=e,this.video.loop=!0,this.video.addEventListener("playing",(()=>{this.map.triggerRepaint();})),this.map&&this.video.play(),this._finishLoading();}catch(e){this.fire(new t.ErrorEvent(e));}}))}pause(){this.video&&this.video.pause();}play(){this.video&&this.video.play();}seek(e){if(this.video){const i=this.video.seekable;ei.end(0)?this.fire(new t.ErrorEvent(new t.ValidationError(`sources.${this.id}`,null,`Playback for this video can be set only between the ${i.start(0)} and ${i.end(0)}-second mark.`))):this.video.currentTime=e;}}getVideo(){return this.video}onAdd(e){this.map||(this.map=e,this.load(),this.video&&(this.video.play(),this.setCoordinates(this.coordinates)));}prepare(){if(0===Object.keys(this.tiles).length||this.video.readyState<2)return;const e=this.map.painter.context,i=e.gl;this.texture?this.video.paused||(this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE),i.texSubImage2D(i.TEXTURE_2D,0,0,0,i.RGBA,i.UNSIGNED_BYTE,this.video)):(this.texture=new y(e,this.video,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE));let r=!1;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,r=!0);}r&&this.fire(new t.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 J extends K{constructor(e,i,r,o){super(e,i,r,o),i.coordinates?Array.isArray(i.coordinates)&&4===i.coordinates.length&&!i.coordinates.some((e=>!Array.isArray(e)||2!==e.length||e.some((e=>"number"!=typeof e))))||this.fire(new t.ErrorEvent(new t.ValidationError(`sources.${e}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new t.ErrorEvent(new t.ValidationError(`sources.${e}`,null,'missing required property "coordinates"'))),i.animate&&"boolean"!=typeof i.animate&&this.fire(new t.ErrorEvent(new t.ValidationError(`sources.${e}`,null,'optional "animate" property must be a boolean value'))),i.canvas?"string"==typeof i.canvas||i.canvas instanceof HTMLCanvasElement||this.fire(new t.ErrorEvent(new t.ValidationError(`sources.${e}`,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))):this.fire(new t.ErrorEvent(new t.ValidationError(`sources.${e}`,null,'missing required property "canvas"'))),this.options=i,this.animate=void 0===i.animate||i.animate;}load(){return t.__awaiter(this,void 0,void 0,(function*(){this._loaded=!0,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,this._hasInvalidDimensions()?this.fire(new t.ErrorEvent(new Error("Canvas dimensions cannot be less than or equal to zero."))):(this.play=function(){this._playing=!0,this.map.triggerRepaint();},this.pause=function(){this._playing&&(this.prepare(),this._playing=!1);},this._finishLoading());}))}getCanvas(){return this.canvas}onAdd(e){this.map=e,this.load(),this.canvas&&this.animate&&this.play();}onRemove(){this.pause();}prepare(){let e=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,e=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,e=!0),this._hasInvalidDimensions())return;if(0===Object.keys(this.tiles).length)return;const i=this.map.painter.context,r=i.gl;this.texture?(e||this._playing)&&this.texture.update(this.canvas,{premultiply:!0}):this.texture=new y(i,this.canvas,r.RGBA,{premultiply:!0});let o=!1;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,o=!0);}o&&this.fire(new t.Event("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}serialize(){return {type:"canvas",coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(const e of [this.canvas.width,this.canvas.height])if(isNaN(e)||e<=0)return !0;return !1}}const Q={},ee=e=>{switch(e){case"geojson":return H;case"image":return K;case"raster":return X;case"raster-dem":return $;case"vector":return W;case"video":return Y;case"canvas":return J}return Q[e]},te="RTLPluginLoaded";class ie extends t.Evented{constructor(){super(...arguments),this.status="unavailable",this.url=null,this.dispatcher=U();}_syncState(e){return this.status=e,this.dispatcher.broadcast("SRPS",{pluginStatus:e,pluginURL:this.url}).catch((e=>{throw this.status="error",e}))}getRTLTextPluginStatus(){return this.status}clearRTLTextPlugin(){this.status="unavailable",this.url=null;}setRTLTextPlugin(e){return t.__awaiter(this,arguments,void 0,(function*(e,t=!1){if(this.url)throw new Error("setRTLTextPlugin cannot be called multiple times.");if(this.url=f.resolveURL(e),!this.url)throw new Error(`requested url ${e} is invalid`);if("unavailable"===this.status){if(!t)return this._requestImport();this.status="deferred",this._syncState(this.status);}else if("requested"===this.status)return this._requestImport()}))}_requestImport(){return t.__awaiter(this,void 0,void 0,(function*(){yield this._syncState("loading"),this.status="loaded",this.fire(new t.Event(te));}))}lazyLoad(){"unavailable"===this.status?this.status="requested":"deferred"===this.status&&this._requestImport();}}let re=null;function oe(){return re||(re=new ie),re}class ae{constructor(e,i){this.timeAdded=0,this.fadeEndTime=0,this.tileID=e,this.uid=t.uniqueId(),this.uses=0,this.tileSize=i,this.buckets={},this.expirationTime=null,this.queryPadding=0,this.hasSymbolBuckets=!1,this.hasRTLText=!1,this.dependencies={},this.rtt=[],this.rttCoords={},this.expiredRequestCount=0,this.state="loading";}registerFadeDuration(e){const t=e+this.timeAdded;tt.getLayer(e))).filter(Boolean);if(0!==e.length){r.layers=e,r.stateDependentLayerIds&&(r.stateDependentLayers=r.stateDependentLayerIds.map((t=>e.filter((e=>e.id===t))[0])));for(const t of e)i[t.id]=r;}}return i}(e.buckets,null==i?void 0:i.style),this.hasSymbolBuckets=!1;for(const e in this.buckets){const i=this.buckets[e];if(i instanceof t.SymbolBucket){if(this.hasSymbolBuckets=!0,!r)break;i.justReloaded=!0;}}if(this.hasRTLText=!1,this.hasSymbolBuckets)for(const e in this.buckets){const i=this.buckets[e];if(i instanceof t.SymbolBucket&&i.hasRTLText){this.hasRTLText=!0,oe().lazyLoad();break}}this.queryPadding=0;for(const e in this.buckets){const t=this.buckets[e];this.queryPadding=Math.max(this.queryPadding,i.style.getLayer(e).queryRadius(t));}e.imageAtlas&&(this.imageAtlas=e.imageAtlas),e.glyphAtlasImage&&(this.glyphAtlasImage=e.glyphAtlasImage);}else this.collisionBoxArray=new t.CollisionBoxArray;}unloadVectorData(){for(const e in this.buckets)this.buckets[e].destroy();this.buckets={},this.imageAtlasTexture&&this.imageAtlasTexture.destroy(),this.imageAtlas&&(this.imageAtlas=null),this.glyphAtlasTexture&&this.glyphAtlasTexture.destroy(),this.latestFeatureIndex=null,this.state="unloaded";}getBucket(e){return this.buckets[e.id]}upload(e){for(const t in this.buckets){const i=this.buckets[t];i.uploadPending()&&i.upload(e);}const t=e.gl;this.imageAtlas&&!this.imageAtlas.uploaded&&(this.imageAtlasTexture=new y(e,this.imageAtlas.image,t.RGBA),this.imageAtlas.uploaded=!0),this.glyphAtlasImage&&(this.glyphAtlasTexture=new y(e,this.glyphAtlasImage,t.ALPHA),this.glyphAtlasImage=null);}prepare(e){this.imageAtlas&&this.imageAtlas.patchUpdatedImages(e,this.imageAtlasTexture);}queryRenderedFeatures(e,t,i,r,o,a,s,n,l,c){return this.latestFeatureIndex&&this.latestFeatureIndex.rawTileData?this.latestFeatureIndex.query({queryGeometry:r,cameraQueryGeometry:o,scale:a,tileSize:this.tileSize,pixelPosMatrix:c,transform:n,params:s,queryPadding:this.queryPadding*l},e,t,i):{}}querySourceFeatures(e,i){const r=this.latestFeatureIndex;if(!r||!r.rawTileData)return;const o=r.loadVTLayers(),a=i&&i.sourceLayer?i.sourceLayer:"",s=o._geojsonTileLayer||o[a];if(!s)return;const n=t.featureFilter(i&&i.filter),{z:l,x:c,y:h}=this.tileID.canonical,u={z:l,x:c,y:h};for(let i=0;ie)t=!1;else if(i)if(this.expirationTime{this.remove(e,o);}),i)),this.data[r].push(o),this.order.push(r),this.order.length>this.max){const e=this._getAndRemoveByKey(this.order[0]);e&&this.onRemove(e);}return this}has(e){return e.wrapped().key in this.data}getAndRemove(e){return this.has(e)?this._getAndRemoveByKey(e.wrapped().key):null}_getAndRemoveByKey(e){const t=this.data[e].shift();return t.timeout&&clearTimeout(t.timeout),0===this.data[e].length&&delete this.data[e],this.order.splice(this.order.indexOf(e),1),t.value}getByKey(e){const t=this.data[e];return t?t[0].value:null}get(e){return this.has(e)?this.data[e.wrapped().key][0].value:null}remove(e,t){if(!this.has(e))return this;const i=e.wrapped().key,r=void 0===t?0:this.data[i].indexOf(t),o=this.data[i][r];return this.data[i].splice(r,1),o.timeout&&clearTimeout(o.timeout),0===this.data[i].length&&delete this.data[i],this.onRemove(o.value),this.order.splice(this.order.indexOf(i),1),this}setMaxSize(e){for(this.max=e;this.order.length>this.max;){const e=this._getAndRemoveByKey(this.order[0]);e&&this.onRemove(e);}return this}filter(e){const t=[];for(const i in this.data)for(const r of this.data[i])e(r.value)||t.push(r);for(const e of t)this.remove(e.value.tileID,e);}}class ne{constructor(){this.state={},this.stateChanges={},this.deletedStates={};}updateState(e,i,r){const o=String(i);if(this.stateChanges[e]=this.stateChanges[e]||{},this.stateChanges[e][o]=this.stateChanges[e][o]||{},t.extend(this.stateChanges[e][o],r),null===this.deletedStates[e]){this.deletedStates[e]={};for(const t in this.state[e])t!==o&&(this.deletedStates[e][t]=null);}else if(this.deletedStates[e]&&null===this.deletedStates[e][o]){this.deletedStates[e][o]={};for(const t in this.state[e][o])r[t]||(this.deletedStates[e][o][t]=null);}else for(const t in r)this.deletedStates[e]&&this.deletedStates[e][o]&&null===this.deletedStates[e][o][t]&&delete this.deletedStates[e][o][t];}removeFeatureState(e,t,i){if(null===this.deletedStates[e])return;const r=String(t);if(this.deletedStates[e]=this.deletedStates[e]||{},i&&void 0!==t)null!==this.deletedStates[e][r]&&(this.deletedStates[e][r]=this.deletedStates[e][r]||{},this.deletedStates[e][r][i]=null);else if(void 0!==t)if(this.stateChanges[e]&&this.stateChanges[e][r])for(i in this.deletedStates[e][r]={},this.stateChanges[e][r])this.deletedStates[e][r][i]=null;else this.deletedStates[e][r]=null;else this.deletedStates[e]=null;}getState(e,i){const r=String(i),o=t.extend({},(this.state[e]||{})[r],(this.stateChanges[e]||{})[r]);if(null===this.deletedStates[e])return {};if(this.deletedStates[e]){const t=this.deletedStates[e][i];if(null===t)return {};for(const e in t)delete o[e];}return o}initializeTileState(e,t){e.setFeatureState(this.state,t);}coalesceChanges(e,i){const r={};for(const e in this.stateChanges){this.state[e]=this.state[e]||{};const i={};for(const r in this.stateChanges[e])this.state[e][r]||(this.state[e][r]={}),t.extend(this.state[e][r],this.stateChanges[e][r]),i[r]=this.state[e][r];r[e]=i;}for(const e in this.deletedStates){this.state[e]=this.state[e]||{};const i={};if(null===this.deletedStates[e])for(const t in this.state[e])i[t]={},this.state[e][t]={};else for(const t in this.deletedStates[e]){if(null===this.deletedStates[e][t])this.state[e][t]={};else for(const i of Object.keys(this.deletedStates[e][t]))delete this.state[e][t][i];i[t]=this.state[e][t];}r[e]=r[e]||{},t.extend(r[e],i);}if(this.stateChanges={},this.deletedStates={},0!==Object.keys(r).length)for(const t in e)e[t].setFeatureState(r,i);}}class le{constructor(e=0,t=0,i=0,r=0){if(isNaN(e)||e<0||isNaN(t)||t<0||isNaN(i)||i<0||isNaN(r)||r<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=e,this.bottom=t,this.left=i,this.right=r;}interpolate(e,i,r){return null!=i.top&&null!=e.top&&(this.top=t.interpolateFactory.number(e.top,i.top,r)),null!=i.bottom&&null!=e.bottom&&(this.bottom=t.interpolateFactory.number(e.bottom,i.bottom,r)),null!=i.left&&null!=e.left&&(this.left=t.interpolateFactory.number(e.left,i.left,r)),null!=i.right&&null!=e.right&&(this.right=t.interpolateFactory.number(e.right,i.right,r)),this}getCenter(e,i){const r=t.clamp((this.left+e-this.right)/2,0,e),o=t.clamp((this.top+i-this.bottom)/2,0,i);return new t.Point(r,o)}equals(e){return this.top===e.top&&this.bottom===e.bottom&&this.left===e.left&&this.right===e.right}clone(){return new le(this.top,this.bottom,this.left,this.right)}toJSON(){return {top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}const ce=85.051129;function he(e,t){if(!e.renderWorldCopies||e.lngRange)return;const i=t.lng-e.center.lng;t.lng+=i>180?-360:i<-180?360:0;}function ue(e){return Math.pow(2,e)}function de(e){return Math.log(e)/Math.LN2}function _e(e){return Math.max(0,Math.floor(e))}class pe{constructor(e,i,r,o,a,s){this._callbacks=e,this._tileSize=512,this._renderWorldCopies=void 0===s||!!s,this._minZoom=i||0,this._maxZoom=r||22,this._minPitch=null==o?0:o,this._maxPitch=null==a?60:a,this.setMaxBounds(),this._width=0,this._height=0,this._center=new t.LngLat(0,0),this._elevation=0,this._zoom=0,this._tileZoom=_e(this._zoom),this._scale=ue(this._zoom),this._bearingInRadians=0,this._fovInRadians=.6435011087932844,this._pitchInRadians=0,this._rollInRadians=0,this._unmodified=!0,this._edgeInsets=new le,this._minElevationForCurrentTile=0;}apply(e,t){this._latRange=e.latRange,this._lngRange=e.lngRange,this._width=e.width,this._height=e.height,this._center=e.center,this._elevation=e.elevation,this._minElevationForCurrentTile=e.minElevationForCurrentTile,this._zoom=e.zoom,this._tileZoom=_e(this._zoom),this._scale=ue(this._zoom),this._bearingInRadians=e.bearingInRadians,this._fovInRadians=e.fovInRadians,this._pitchInRadians=e.pitchInRadians,this._rollInRadians=e.rollInRadians,this._unmodified=e.unmodified,this._edgeInsets=new le(e.padding.top,e.padding.bottom,e.padding.left,e.padding.right),this._minZoom=e.minZoom,this._maxZoom=e.maxZoom,this._minPitch=e.minPitch,this._maxPitch=e.maxPitch,this._renderWorldCopies=e.renderWorldCopies,t&&this._constrain(),this._calcMatrices();}get pixelsToClipSpaceMatrix(){return this._pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._clipSpaceToPixelsMatrix}get minElevationForCurrentTile(){return this._minElevationForCurrentTile}setMinElevationForCurrentTile(e){this._minElevationForCurrentTile=e;}get tileSize(){return this._tileSize}get tileZoom(){return this._tileZoom}get scale(){return this._scale}get width(){return this._width}get height(){return this._height}get bearingInRadians(){return this._bearingInRadians}get lngRange(){return this._lngRange}get latRange(){return this._latRange}get pixelsToGLUnits(){return this._pixelsToGLUnits}get minZoom(){return this._minZoom}setMinZoom(e){this._minZoom!==e&&(this._minZoom=e,this.setZoom(this.getConstrained(this._center,this.zoom).zoom));}get maxZoom(){return this._maxZoom}setMaxZoom(e){this._maxZoom!==e&&(this._maxZoom=e,this.setZoom(this.getConstrained(this._center,this.zoom).zoom));}get minPitch(){return this._minPitch}setMinPitch(e){this._minPitch!==e&&(this._minPitch=e,this.setPitch(Math.max(this.pitch,e)));}get maxPitch(){return this._maxPitch}setMaxPitch(e){this._maxPitch!==e&&(this._maxPitch=e,this.setPitch(Math.min(this.pitch,e)));}get renderWorldCopies(){return this._renderWorldCopies}setRenderWorldCopies(e){void 0===e?e=!0:null===e&&(e=!1),this._renderWorldCopies=e;}get worldSize(){return this._tileSize*this._scale}get centerOffset(){return this.centerPoint._sub(this.size._div(2))}get size(){return new t.Point(this._width,this._height)}get bearing(){return this._bearingInRadians/Math.PI*180}setBearing(e){const r=t.wrap(e,-180,180)*Math.PI/180;var o,a,s,n,l,c,h,u,d;this._bearingInRadians!==r&&(this._unmodified=!1,this._bearingInRadians=r,this._calcMatrices(),this._rotationMatrix=i(),o=this._rotationMatrix,s=-this._bearingInRadians,n=(a=this._rotationMatrix)[0],l=a[1],c=a[2],h=a[3],u=Math.sin(s),d=Math.cos(s),o[0]=n*d+c*u,o[1]=l*d+h*u,o[2]=n*-u+c*d,o[3]=l*-u+h*d);}get rotationMatrix(){return this._rotationMatrix}get pitchInRadians(){return this._pitchInRadians}get pitch(){return this._pitchInRadians/Math.PI*180}setPitch(e){const i=t.clamp(e,this.minPitch,this.maxPitch)/180*Math.PI;this._pitchInRadians!==i&&(this._unmodified=!1,this._pitchInRadians=i,this._calcMatrices());}get rollInRadians(){return this._rollInRadians}get roll(){return this._rollInRadians/Math.PI*180}setRoll(e){const t=e/180*Math.PI;this._rollInRadians!==t&&(this._unmodified=!1,this._rollInRadians=t,this._calcMatrices());}get fovInRadians(){return this._fovInRadians}get fov(){return t.radiansToDegrees(this._fovInRadians)}setFov(e){e=t.clamp(e,.1,150),this.fov!==e&&(this._unmodified=!1,this._fovInRadians=t.degreesToRadians(e),this._calcMatrices());}get zoom(){return this._zoom}setZoom(e){const t=this.getConstrained(this._center,e).zoom;this._zoom!==t&&(this._unmodified=!1,this._zoom=t,this._tileZoom=Math.max(0,Math.floor(t)),this._scale=ue(t),this._constrain(),this._calcMatrices());}get center(){return this._center}setCenter(e){e.lat===this._center.lat&&e.lng===this._center.lng||(this._unmodified=!1,this._center=e,this._constrain(),this._calcMatrices());}get elevation(){return this._elevation}setElevation(e){e!==this._elevation&&(this._elevation=e,this._constrain(),this._calcMatrices());}get padding(){return this._edgeInsets.toJSON()}setPadding(e){this._edgeInsets.equals(e)||(this._unmodified=!1,this._edgeInsets.interpolate(this._edgeInsets,e,1),this._calcMatrices());}get centerPoint(){return this._edgeInsets.getCenter(this._width,this._height)}get pixelsPerMeter(){return this._pixelPerMeter}get unmodified(){return this._unmodified}isPaddingEqual(e){return this._edgeInsets.equals(e)}interpolatePadding(e,t,i){this._unmodified=!1,this._edgeInsets.interpolate(e,t,i),this._constrain(),this._calcMatrices();}resize(e,t){this._width=e,this._height=t,this._constrain(),this._calcMatrices();}getMaxBounds(){return this._latRange&&2===this._latRange.length&&this._lngRange&&2===this._lngRange.length?new V([this._lngRange[0],this._latRange[0]],[this._lngRange[1],this._latRange[1]]):null}setMaxBounds(e){e?(this._lngRange=[e.getWest(),e.getEast()],this._latRange=[e.getSouth(),e.getNorth()],this._constrain()):(this._lngRange=null,this._latRange=[-85.051129,ce]);}getConstrained(e,t){return this._callbacks.getConstrained(e,t)}getCameraQueryGeometry(e,i){if(1===i.length)return [i[0],e];{let r=e.x,o=e.y,a=e.x,s=e.y;for(const e of i)r=Math.min(r,e.x),o=Math.min(o,e.y),a=Math.max(a,e.x),s=Math.max(s,e.y);return [new t.Point(r,o),new t.Point(a,o),new t.Point(a,s),new t.Point(r,s),new t.Point(r,o)]}}_constrain(){if(!this.center||!this._width||!this._height||this._constraining)return;this._constraining=!0;const e=this._unmodified,{center:t,zoom:i}=this.getConstrained(this.center,this.zoom);this.setCenter(t),this.setZoom(i),this._unmodified=e,this._constraining=!1;}_calcMatrices(){if(this._width&&this._height){this._pixelsToGLUnits=[2/this._width,-2/this._height];let e=t.identity(new Float64Array(16));t.scale(e,e,[this._width/2,-this._height/2,1]),t.translate(e,e,[1,-1,0]),this._clipSpaceToPixelsMatrix=e,e=t.identity(new Float64Array(16)),t.scale(e,e,[1,-1,1]),t.translate(e,e,[-1,-1,0]),t.scale(e,e,[2/this._width,2/this._height,1]),this._pixelsToClipSpaceMatrix=e;}this._callbacks.calcMatrices();}}function me(e,t,i){const r=t.intersectsFrustum(e);if(!i)return r;const o=t.intersectsPlane(i);return 0===r||0===o?0:2===r&&2===o?2:1}function fe(e,i,r,o,a){let s=e;const n=Math.atan(i/r);return s=e+de(o/Math.hypot(i,r)/Math.max(.5,Math.cos(t.degreesToRadians(a/2)))),s+=1*de(Math.cos(n))/2,s+=t.clamp(e-s,-0,0),s}function ge(e,t){const i=(t.roundZoom?Math.round:Math.floor)(e.zoom+de(e.tileSize/t.tileSize));return Math.max(0,i)}function ve(e,i){const r=e.getCameraFrustum(),o=e.getClippingPlane(),a=e.screenPointToMercatorCoordinate(e.getCameraPoint()),s=t.MercatorCoordinate.fromLngLat(e.center,e.elevation);a.z=s.z+Math.cos(e.pitchInRadians)*e.cameraToCenterDistance/e.worldSize;const n=e.getCoveringTilesDetailsProvider(),l=n.allowVariableZoom(e,i),c=ge(e,i),h=i.minzoom||0,u=void 0!==i.maxzoom?i.maxzoom:e.maxZoom,d=Math.min(Math.max(0,c),u),_=Math.pow(2,d),p=[_*a.x,_*a.y,0],m=[_*s.x,_*s.y,0],f=Math.hypot(s.x-a.x,s.y-a.y),g=Math.abs(s.z-a.z),v=Math.hypot(f,g),y=e=>({zoom:0,x:0,y:0,wrap:e,fullyVisible:!1}),x=[],b=[];if(e.renderWorldCopies)for(let e=1;e<=3;e++)x.push(y(-e)),x.push(y(e));for(x.push(y(0));x.length>0;){const _=x.pop(),f=_.x,y=_.y;let w=_.fullyVisible;const T={x:f,y:y,z:_.zoom},E=n.getTileAABB(T,_.wrap,e.elevation,i);if(!w){const e=me(r,E,o);if(0===e)continue;w=2===e;}const P=n.distanceToTile2d(a.x,a.y,T,E);let I=c;l&&(I=(i.calculateTileZoom||fe)(e.zoom+de(e.tileSize/i.tileSize),P,g,v,e.fov)),I=(i.roundZoom?Math.round:Math.floor)(I),I=Math.max(0,I);const C=Math.min(I,u);if(_.wrap=n.getWrap(s,T,_.wrap),_.zoom>=C){if(_.zoom>1),wrap:_.wrap,fullyVisible:w});}return b.sort(((e,t)=>e.distanceSq-t.distanceSq)).map((e=>e.tileID))}class ye extends t.Evented{constructor(e,t,i){super(),this.id=e,this.dispatcher=i,this.on("data",(e=>this._dataHandler(e))),this.on("dataloading",(()=>{this._sourceErrored=!1;})),this.on("error",(()=>{this._sourceErrored=this._source.loaded();})),this._source=((e,t,i,r)=>{const o=new(ee(t.type))(e,t,i,r);if(o.id!==e)throw new Error(`Expected Source id to be ${e} instead of ${o.id}`);return o})(e,t,i,this),this._tiles={},this._cache=new se(0,(e=>this._unloadTile(e))),this._timers={},this._cacheTimers={},this._maxTileCacheSize=null,this._maxTileCacheZoomLevels=null,this._loadedParentTiles={},this._coveredTiles={},this._state=new ne,this._didEmitContent=!1,this._updated=!1;}onAdd(e){this.map=e,this._maxTileCacheSize=e?e._maxTileCacheSize:null,this._maxTileCacheZoomLevels=e?e._maxTileCacheZoomLevels:null,this._source&&this._source.onAdd&&this._source.onAdd(e);}onRemove(e){this.clearTiles(),this._source&&this._source.onRemove&&this._source.onRemove(e);}loaded(){if(this._sourceErrored)return !0;if(!this._sourceLoaded)return !1;if(!this._source.loaded())return !1;if(!(void 0===this.used&&void 0===this.usedForTerrain||this.used||this.usedForTerrain))return !0;if(!this._updated)return !1;for(const e in this._tiles){const t=this._tiles[e];if("loaded"!==t.state&&"errored"!==t.state)return !1}return !0}getSource(){return this._source}pause(){this._paused=!0;}resume(){if(!this._paused)return;const e=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,e&&this.reload(),this.transform&&this.update(this.transform,this.terrain);}_loadTile(e,i,r){return t.__awaiter(this,void 0,void 0,(function*(){try{yield this._source.loadTile(e),this._tileLoaded(e,i,r);}catch(i){e.state="errored",404!==i.status?this._source.fire(new t.ErrorEvent(i,{tile:e})):this.update(this.transform,this.terrain);}}))}_unloadTile(e){this._source.unloadTile&&this._source.unloadTile(e);}_abortTile(e){this._source.abortTile&&this._source.abortTile(e),this._source.fire(new t.Event("dataabort",{tile:e,coord:e.tileID,dataType:"source"}));}serialize(){return this._source.serialize()}prepare(e){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null);for(const t in this._tiles){const i=this._tiles[t];i.upload(e),i.prepare(this.map.style.imageManager);}}getIds(){return Object.values(this._tiles).map((e=>e.tileID)).sort(xe).map((e=>e.key))}getRenderableIds(e){const i=[];for(const t in this._tiles)this._isIdRenderable(t,e)&&i.push(this._tiles[t]);return e?i.sort(((e,i)=>{const r=e.tileID,o=i.tileID,a=new t.Point(r.canonical.x,r.canonical.y)._rotate(-this.transform.bearingInRadians),s=new t.Point(o.canonical.x,o.canonical.y)._rotate(-this.transform.bearingInRadians);return r.overscaledZ-o.overscaledZ||s.y-a.y||s.x-a.x})).map((e=>e.tileID.key)):i.map((e=>e.tileID)).sort(xe).map((e=>e.key))}hasRenderableParent(e){const t=this.findLoadedParent(e,0);return !!t&&this._isIdRenderable(t.tileID.key)}_isIdRenderable(e,t){return this._tiles[e]&&this._tiles[e].hasData()&&!this._coveredTiles[e]&&(t||!this._tiles[e].holdingForFade())}reload(e){if(this._paused)this._shouldReloadOnResume=!0;else {this._cache.reset();for(const t in this._tiles)(e||"errored"!==this._tiles[t].state)&&this._reloadTile(t,"reloading");}}_reloadTile(e,i){return t.__awaiter(this,void 0,void 0,(function*(){const t=this._tiles[e];t&&("loading"!==t.state&&(t.state=i),yield this._loadTile(t,e,i));}))}_tileLoaded(e,i,r){e.timeAdded=f.now(),"expired"===r&&(e.refreshedUponExpiration=!0),this._setTileReloadTimer(i,e),"raster-dem"===this.getSource().type&&e.dem&&this._backfillDEM(e),this._state.initializeTileState(e,this.map?this.map.painter:null),e.aborted||this._source.fire(new t.Event("data",{dataType:"source",tile:e,coord:e.tileID}));}_backfillDEM(e){const t=this.getRenderableIds();for(let r=0;r1||(Math.abs(i)>1&&(1===Math.abs(i+o)?i+=o:1===Math.abs(i-o)&&(i-=o)),t.dem&&e.dem&&(e.dem.backfillBorder(t.dem,i,r),e.neighboringTiles&&e.neighboringTiles[a]&&(e.neighboringTiles[a].backfilled=!0)));}}getTile(e){return this.getTileByID(e.key)}getTileByID(e){return this._tiles[e]}_retainLoadedChildren(e,t,i,r){for(const o in this._tiles){let a=this._tiles[o];if(r[o]||!a.hasData()||a.tileID.overscaledZ<=t||a.tileID.overscaledZ>i)continue;let s=a.tileID;for(;a&&a.tileID.overscaledZ>t+1;){const e=a.tileID.scaledTo(a.tileID.overscaledZ-1);a=this._tiles[e.key],a&&a.hasData()&&(s=e);}let n=s;for(;n.overscaledZ>t;)if(n=n.scaledTo(n.overscaledZ-1),e[n.key]){r[s.key]=s;break}}}findLoadedParent(e,t){if(e.key in this._loadedParentTiles){const i=this._loadedParentTiles[e.key];return i&&i.tileID.overscaledZ>=t?i:null}for(let i=e.overscaledZ-1;i>=t;i--){const t=e.scaledTo(i),r=this._getLoadedTile(t);if(r)return r}}findLoadedSibling(e){return this._getLoadedTile(e)}_getLoadedTile(e){const t=this._tiles[e.key];return t&&t.hasData()?t:this._cache.getByKey(e.wrapped().key)}updateCacheSize(e){const i=Math.ceil(e.width/this._source.tileSize)+1,r=Math.ceil(e.height/this._source.tileSize)+1,o=Math.floor(i*r*(null===this._maxTileCacheZoomLevels?t.config.MAX_TILE_CACHE_ZOOM_LEVELS:this._maxTileCacheZoomLevels)),a="number"==typeof this._maxTileCacheSize?Math.min(this._maxTileCacheSize,o):o;this._cache.setMaxSize(a);}handleWrapJump(e){const t=Math.round((e-(void 0===this._prevLng?e:this._prevLng))/360);if(this._prevLng=e,t){const e={};for(const i in this._tiles){const r=this._tiles[i];r.tileID=r.tileID.unwrapTo(r.tileID.wrap+t),e[r.tileID.key]=r;}this._tiles=e;for(const e in this._timers)clearTimeout(this._timers[e]),delete this._timers[e];for(const e in this._tiles)this._setTileReloadTimer(e,this._tiles[e]);}}_updateCoveredAndRetainedTiles(e,t,i,r,o,a){const s={},n={},l=Object.keys(e),c=f.now();for(const i of l){const r=e[i],o=this._tiles[i];if(!o||0!==o.fadeEndTime&&o.fadeEndTime<=c)continue;const a=this.findLoadedParent(r,t),l=this.findLoadedSibling(r),h=a||l||null;h&&(this._addTile(h.tileID),s[h.tileID.key]=h.tileID),n[i]=r;}this._retainLoadedChildren(n,r,i,e);for(const t in s)e[t]||(this._coveredTiles[t]=!0,e[t]=s[t]);if(a){const t={},i={};for(const e of o)this._tiles[e.key].hasData()?t[e.key]=e:i[e.key]=e;for(const r in i){const o=i[r].children(this._source.maxzoom);this._tiles[o[0].key]&&this._tiles[o[1].key]&&this._tiles[o[2].key]&&this._tiles[o[3].key]&&(t[o[0].key]=e[o[0].key]=o[0],t[o[1].key]=e[o[1].key]=o[1],t[o[2].key]=e[o[2].key]=o[2],t[o[3].key]=e[o[3].key]=o[3],delete i[r]);}for(const r in i){const o=i[r],a=this.findLoadedParent(o,this._source.minzoom),s=this.findLoadedSibling(o),n=a||s||null;if(n){t[n.tileID.key]=e[n.tileID.key]=n.tileID;for(const e in t)t[e].isChildOf(n.tileID)&&delete t[e];}}for(const e in this._tiles)t[e]||(this._coveredTiles[e]=!0);}}update(e,i){if(!this._sourceLoaded||this._paused)return;let r;this.transform=e,this.terrain=i,this.updateCacheSize(e),this.handleWrapJump(this.transform.center.lng),this._coveredTiles={},this.used||this.usedForTerrain?this._source.tileID?r=e.getVisibleUnwrappedCoordinates(this._source.tileID).map((e=>new t.OverscaledTileID(e.canonical.z,e.wrap,e.canonical.z,e.canonical.x,e.canonical.y))):(r=ve(e,{tileSize:this.usedForTerrain?this.tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:!this.usedForTerrain&&this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled,terrain:i,calculateTileZoom:this._source.calculateTileZoom}),this._source.hasTile&&(r=r.filter((e=>this._source.hasTile(e))))):r=[];const o=ge(e,this._source),a=Math.max(o-ye.maxOverzooming,this._source.minzoom),s=Math.max(o+ye.maxUnderzooming,this._source.minzoom);if(this.usedForTerrain){const e={};for(const t of r)if(t.canonical.z>this._source.minzoom){const i=t.scaledTo(t.canonical.z-1);e[i.key]=i;const r=t.scaledTo(Math.max(this._source.minzoom,Math.min(t.canonical.z,5)));e[r.key]=r;}r=r.concat(Object.values(e));}const n=0===r.length&&!this._updated&&this._didEmitContent;this._updated=!0,n&&this.fire(new t.Event("data",{sourceDataType:"idle",dataType:"source",sourceId:this.id}));const l=this._updateRetainedTiles(r,o);be(this._source.type)&&this._updateCoveredAndRetainedTiles(l,a,s,o,r,i);for(const e in l)this._tiles[e].clearFadeHold();const c=t.keysDifference(this._tiles,l);for(const e of c){const t=this._tiles[e];t.hasSymbolBuckets&&!t.holdingForFade()?t.setHoldDuration(this.map._fadeDuration):t.hasSymbolBuckets&&!t.symbolFadeFinished()||this._removeTile(e);}this._updateLoadedParentTileCache(),this._updateLoadedSiblingTileCache();}releaseSymbolFadeTiles(){for(const e in this._tiles)this._tiles[e].holdingForFade()&&this._removeTile(e);}_updateRetainedTiles(e,t){var i;const r={},o={},a=Math.max(t-ye.maxOverzooming,this._source.minzoom),s=Math.max(t+ye.maxUnderzooming,this._source.minzoom),n={};for(const i of e){const e=this._addTile(i);r[i.key]=i,e.hasData()||tthis._source.maxzoom){const e=s.children(this._source.maxzoom)[0],t=this.getTile(e);if(t&&t.hasData()){r[e.key]=e;continue}}else {const e=s.children(this._source.maxzoom);if(r[e[0].key]&&r[e[1].key]&&r[e[2].key]&&r[e[3].key])continue}let n=e.wasRequested();for(let t=s.overscaledZ-1;t>=a;--t){const a=s.scaledTo(t);if(o[a.key])break;if(o[a.key]=!0,e=this.getTile(a),!e&&n&&(e=this._addTile(a)),e){const t=e.hasData();if((t||!(null===(i=this.map)||void 0===i?void 0:i.cancelPendingTileRequestsWhileZooming)||n)&&(r[a.key]=a),n=e.wasRequested(),t)break}}}return r}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const e in this._tiles){const t=[];let i,r=this._tiles[e].tileID;for(;r.overscaledZ>0;){if(r.key in this._loadedParentTiles){i=this._loadedParentTiles[r.key];break}t.push(r.key);const e=r.scaledTo(r.overscaledZ-1);if(i=this._getLoadedTile(e),i)break;r=e;}for(const e of t)this._loadedParentTiles[e]=i;}}_updateLoadedSiblingTileCache(){this._loadedSiblingTiles={};for(const e in this._tiles){const t=this._tiles[e].tileID,i=this._getLoadedTile(t);this._loadedSiblingTiles[t.key]=i;}}_addTile(e){let i=this._tiles[e.key];if(i)return i;i=this._cache.getAndRemove(e),i&&(this._setTileReloadTimer(e.key,i),i.tileID=e,this._state.initializeTileState(i,this.map?this.map.painter:null),this._cacheTimers[e.key]&&(clearTimeout(this._cacheTimers[e.key]),delete this._cacheTimers[e.key],this._setTileReloadTimer(e.key,i)));const r=i;return i||(i=new ae(e,this._source.tileSize*e.overscaleFactor()),this._loadTile(i,e.key,i.state)),i.uses++,this._tiles[e.key]=i,r||this._source.fire(new t.Event("dataloading",{tile:i,coord:i.tileID,dataType:"source"})),i}_setTileReloadTimer(e,t){e in this._timers&&(clearTimeout(this._timers[e]),delete this._timers[e]);const i=t.getExpiryTimeout();i&&(this._timers[e]=setTimeout((()=>{this._reloadTile(e,"expired"),delete this._timers[e];}),i));}_removeTile(e){const t=this._tiles[e];t&&(t.uses--,delete this._tiles[e],this._timers[e]&&(clearTimeout(this._timers[e]),delete this._timers[e]),t.uses>0||(t.hasData()&&"reloading"!==t.state?this._cache.add(t.tileID,t,t.getExpiryTimeout()):(t.aborted=!0,this._abortTile(t),this._unloadTile(t))));}_dataHandler(e){const t=e.sourceDataType;"source"===e.dataType&&"metadata"===t&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&"source"===e.dataType&&"content"===t&&(this.reload(e.sourceDataChanged),this.transform&&this.update(this.transform,this.terrain),this._didEmitContent=!0);}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(const e in this._tiles)this._removeTile(e);this._cache.reset();}tilesIn(e,i,r){const o=[],a=this.transform;if(!a)return o;const s=r?a.getCameraQueryGeometry(e):e,n=e.map((e=>a.screenPointToMercatorCoordinate(e,this.terrain))),l=s.map((e=>a.screenPointToMercatorCoordinate(e,this.terrain))),c=this.getIds();let h=1/0,u=1/0,d=-1/0,_=-1/0;for(const e of l)h=Math.min(h,e.x),u=Math.min(u,e.y),d=Math.max(d,e.x),_=Math.max(_,e.y);for(let e=0;e=0&&f[1].y+m>=0){const e=n.map((e=>s.getTilePoint(e))),t=l.map((e=>s.getTilePoint(e)));o.push({tile:r,tileID:s,queryGeometry:e,cameraQueryGeometry:t,scale:p});}}return o}getVisibleCoordinates(e){const t=this.getRenderableIds(e).map((e=>this._tiles[e].tileID));return this.transform&&this.transform.precacheTiles(t),t}hasTransition(){if(this._source.hasTransition())return !0;if(be(this._source.type)){const e=f.now();for(const t in this._tiles)if(this._tiles[t].fadeEndTime>=e)return !0}return !1}setFeatureState(e,t,i){this._state.updateState(e=e||"_geojsonTileLayer",t,i);}removeFeatureState(e,t,i){this._state.removeFeatureState(e=e||"_geojsonTileLayer",t,i);}getFeatureState(e,t){return this._state.getState(e=e||"_geojsonTileLayer",t)}setDependencies(e,t,i){const r=this._tiles[e];r&&r.setDependencies(t,i);}reloadTilesForDependencies(e,t){for(const i in this._tiles)this._tiles[i].hasDependency(e,t)&&this._reloadTile(i,"reloading");this._cache.filter((i=>!i.hasDependency(e,t)));}}function xe(e,t){const i=Math.abs(2*e.wrap)-+(e.wrap<0),r=Math.abs(2*t.wrap)-+(t.wrap<0);return e.overscaledZ-t.overscaledZ||r-i||t.canonical.y-e.canonical.y||t.canonical.x-e.canonical.x}function be(e){return "raster"===e||"image"===e||"video"===e}ye.maxOverzooming=10,ye.maxUnderzooming=3;class we{constructor(e,t){this.reset(e,t);}reset(e,t){this.points=e||[],this._distances=[0];for(let e=1;e0?(o-s)/n:0;return this.points[a].mult(1-l).add(this.points[i].mult(l))}}function Te(e,t){let i=!0;return "always"===e||"never"!==e&&"never"!==t||(i=!1),i}class Ee{constructor(e,t,i){const r=this.boxCells=[],o=this.circleCells=[];this.xCellCount=Math.ceil(e/i),this.yCellCount=Math.ceil(t/i);for(let e=0;ethis.width||r<0||t>this.height)return [];const n=[];if(e<=0&&t<=0&&this.width<=i&&this.height<=r){if(o)return [{key:null,x1:e,y1:t,x2:i,y2:r}];for(let e=0;e0}hitTestCircle(e,t,i,r,o){const a=e-i,s=e+i,n=t-i,l=t+i;if(s<0||a>this.width||l<0||n>this.height)return !1;const c=[];return this._forEachCell(a,n,s,l,this._queryCellCircle,c,{hitTest:!0,overlapMode:r,circle:{x:e,y:t,radius:i},seenUids:{box:{},circle:{}}},o),c.length>0}_queryCell(e,t,i,r,o,a,s,n){const{seenUids:l,hitTest:c,overlapMode:h}=s,u=this.boxCells[o];if(null!==u){const o=this.bboxes;for(const s of u)if(!l.box[s]){l.box[s]=!0;const u=4*s,d=this.boxKeys[s];if(e<=o[u+2]&&t<=o[u+3]&&i>=o[u+0]&&r>=o[u+1]&&(!n||n(d))&&(!c||!Te(h,d.overlapMode))&&(a.push({key:d,x1:o[u],y1:o[u+1],x2:o[u+2],y2:o[u+3]}),c))return !0}}const d=this.circleCells[o];if(null!==d){const o=this.circles;for(const s of d)if(!l.circle[s]){l.circle[s]=!0;const u=3*s,d=this.circleKeys[s];if(this._circleAndRectCollide(o[u],o[u+1],o[u+2],e,t,i,r)&&(!n||n(d))&&(!c||!Te(h,d.overlapMode))){const e=o[u],t=o[u+1],i=o[u+2];if(a.push({key:d,x1:e-i,y1:t-i,x2:e+i,y2:t+i}),c)return !0}}}return !1}_queryCellCircle(e,t,i,r,o,a,s,n){const{circle:l,seenUids:c,overlapMode:h}=s,u=this.boxCells[o];if(null!==u){const e=this.bboxes;for(const t of u)if(!c.box[t]){c.box[t]=!0;const i=4*t,r=this.boxKeys[t];if(this._circleAndRectCollide(l.x,l.y,l.radius,e[i+0],e[i+1],e[i+2],e[i+3])&&(!n||n(r))&&!Te(h,r.overlapMode))return a.push(!0),!0}}const d=this.circleCells[o];if(null!==d){const e=this.circles;for(const t of d)if(!c.circle[t]){c.circle[t]=!0;const i=3*t,r=this.circleKeys[t];if(this._circlesCollide(e[i],e[i+1],e[i+2],l.x,l.y,l.radius)&&(!n||n(r))&&!Te(h,r.overlapMode))return a.push(!0),!0}}}_forEachCell(e,t,i,r,o,a,s,n){const l=this._convertToXCellCoord(e),c=this._convertToYCellCoord(t),h=this._convertToXCellCoord(i),u=this._convertToYCellCoord(r);for(let d=l;d<=h;d++)for(let l=c;l<=u;l++)if(o.call(this,e,t,i,r,this.xCellCount*l+d,a,s,n))return}_convertToXCellCoord(e){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(e*this.xScale)))}_convertToYCellCoord(e){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(e*this.yScale)))}_circlesCollide(e,t,i,r,o,a){const s=r-e,n=o-t,l=i+a;return l*l>s*s+n*n}_circleAndRectCollide(e,t,i,r,o,a,s){const n=(a-r)/2,l=Math.abs(e-(r+n));if(l>n+i)return !1;const c=(s-o)/2,h=Math.abs(t-(o+c));if(h>c+i)return !1;if(l<=n||h<=c)return !0;const u=l-n,d=h-c;return u*u+d*d<=i*i}}function Pe(e,r,o){const a=t.create();if(!e){const{vecSouth:e,vecEast:t}=Ce(r),o=i();o[0]=t[0],o[1]=t[1],o[2]=e[0],o[3]=e[1],s=o,(d=(l=(n=o)[0])*(u=n[3])-(h=n[2])*(c=n[1]))&&(s[0]=u*(d=1/d),s[1]=-c*d,s[2]=-h*d,s[3]=l*d),a[0]=o[0],a[1]=o[1],a[4]=o[2],a[5]=o[3];}var s,n,l,c,h,u,d;return t.scale(a,a,[1/o,1/o,1]),a}function Ie(e,i,r,o){if(e){const e=t.create();if(!i){const{vecSouth:t,vecEast:i}=Ce(r);e[0]=i[0],e[1]=i[1],e[4]=t[0],e[5]=t[1];}return t.scale(e,e,[o,o,1]),e}return r.pixelsToClipSpaceMatrix}function Ce(e){const i=Math.cos(e.rollInRadians),r=Math.sin(e.rollInRadians),o=Math.cos(e.pitchInRadians),a=Math.cos(e.bearingInRadians),s=Math.sin(e.bearingInRadians),n=t.create$1();n[0]=-a*o*r-s*i,n[1]=-s*o*r+a*i;const l=t.length(n);l<1e-9?t.zero(n):t.scale$1(n,n,1/l);const c=t.create$1();c[0]=a*o*i-s*r,c[1]=s*o*i+a*r;const h=t.length(c);return h<1e-9?t.zero(c):t.scale$1(c,c,1/h),{vecEast:c,vecSouth:n}}function Me(e,i,r,o){let a;o?(a=[e,i,o(e,i),1],t.transformMat4(a,a,r)):(a=[e,i,0,1],qe(a,a,r));const s=a[3];return {point:new t.Point(a[0]/s,a[1]/s),signedDistanceFromCamera:s,isOccluded:!1}}function Se(e,t){return .5+e/t*.5}function Re(e,t){return e.x>=-t[0]&&e.x<=t[0]&&e.y>=-t[1]&&e.y<=t[1]}function De(e,i,r,o,a,s,n,l,c,h,u,d,_){const p=r?e.textSizeData:e.iconSizeData,m=t.evaluateSizeForZoom(p,i.transform.zoom),f=[256/i.width*2+1,256/i.height*2+1],g=r?e.text.dynamicLayoutVertexArray:e.icon.dynamicLayoutVertexArray;g.clear();const v=e.lineVertexArray,y=r?e.text.placedSymbolArray:e.icon.placedSymbolArray,x=i.transform.width/i.transform.height;let b=!1;for(let r=0;rMath.abs(r.x-i.x)*o?{useVertical:!0}:(e===t.WritingMode.vertical?i.yr.x)?{needsFlipping:!0}:null}function Ae(e){const{projectionContext:i,pitchedLabelPlaneMatrixInverse:r,symbol:o,fontSize:a,flip:s,keepUpright:n,glyphOffsetArray:l,dynamicLayoutVertexArray:c,aspectRatio:h,rotateToLine:u}=e,d=a/24,_=o.lineOffsetX*d,p=o.lineOffsetY*d;let m;if(o.numGlyphs>1){const e=o.glyphStartIndex+o.numGlyphs,t=o.lineStartIndex,a=o.lineStartIndex+o.lineLength,c=ze(d,l,_,p,s,o,u,i);if(!c)return {notEnoughRoom:!0};const f=Oe(c.first.point.x,c.first.point.y,i,r),g=Oe(c.last.point.x,c.last.point.y,i,r);if(n&&!s){const e=Le(o.writingMode,f,g,h);if(e)return e}m=[c.first];for(let r=o.glyphStartIndex+1;r0?n.point:ke(i.tileAnchorPoint,s,e,1,i),c=Oe(e.x,e.y,i,r),u=Oe(l.x,l.y,i,r),d=Le(o.writingMode,c,u,h);if(d)return d}const e=Ge(d*l.getoffsetX(o.glyphStartIndex),_,p,s,o.segment,o.lineStartIndex,o.lineStartIndex+o.lineLength,i,u);if(!e||i.projectionCache.anyProjectionOccluded)return {notEnoughRoom:!0};m=[e];}for(const e of m)t.addDynamicAttributes(c,e.point,e.angle);return {}}function ke(e,t,i,r,o){const a=e.add(e.sub(t)._unit()),s=Be(a.x,a.y,o).point,n=i.sub(s);return i.add(n._mult(r/n.mag()))}function Fe(e,i,r){const o=i.projectionCache;if(o.projections[e])return o.projections[e];const a=new t.Point(i.lineVertexArray.getx(e),i.lineVertexArray.gety(e)),s=Be(a.x,a.y,i);if(s.signedDistanceFromCamera>0)return o.projections[e]=s.point,o.anyProjectionOccluded=o.anyProjectionOccluded||s.isOccluded,s.point;const n=e-r.direction;return ke(0===r.distanceFromAnchor?i.tileAnchorPoint:new t.Point(i.lineVertexArray.getx(n),i.lineVertexArray.gety(n)),a,r.previousVertex,r.absOffsetX-r.distanceFromAnchor+1,i)}function Be(e,t,i){const r=e+i.translation[0],o=t+i.translation[1];let a;return i.pitchWithMap?(a=Me(r,o,i.pitchedLabelPlaneMatrix,i.getElevation),a.isOccluded=!1):(a=i.transform.projectTileCoordinates(r,o,i.unwrappedTileID,i.getElevation),a.point.x=(.5*a.point.x+.5)*i.width,a.point.y=(.5*-a.point.y+.5)*i.height),a}function Oe(e,i,r,o){if(r.pitchWithMap){const a=[e,i,0,1];return t.transformMat4(a,a,o),r.transform.projectTileCoordinates(a[0]/a[3],a[1]/a[3],r.unwrappedTileID,r.getElevation).point}return {x:e/r.width*2-1,y:i/r.height*2-1}}function Ue(e,t,i){return i.transform.projectTileCoordinates(e,t,i.unwrappedTileID,i.getElevation)}function je(e,t,i){return e._unit()._perp()._mult(t*i)}function Ne(e,i,r,o,a,s,n,l,c){if(l.projectionCache.offsets[e])return l.projectionCache.offsets[e];const h=r.add(i);if(e+c.direction=a)return l.projectionCache.offsets[e]=h,h;const u=Fe(e+c.direction,l,c),d=je(u.sub(r),n,c.direction),_=r.add(d),p=u.add(d);return l.projectionCache.offsets[e]=t.findLineIntersection(s,h,_,p)||h,l.projectionCache.offsets[e]}function Ge(e,t,i,r,o,a,s,n,l){const c=r?e-t:e+t;let h=c>0?1:-1,u=0;r&&(h*=-1,u=Math.PI),h<0&&(u+=Math.PI);let d,_=h>0?a+o:a+o+1;n.projectionCache.cachedAnchorPoint?d=n.projectionCache.cachedAnchorPoint:(d=Be(n.tileAnchorPoint.x,n.tileAnchorPoint.y,n).point,n.projectionCache.cachedAnchorPoint=d);let p,m,f=d,g=d,v=0,y=0;const x=Math.abs(c),b=[];let w;for(;v+y<=x;){if(_+=h,_=s)return null;v+=y,g=f,m=p;const e={absOffsetX:x,direction:h,distanceFromAnchor:v,previousVertex:g};if(f=Fe(_,n,e),0===i)b.push(g),w=f.sub(g);else {let t;const r=f.sub(g);t=0===r.mag()?je(Fe(_+h,n,e).sub(f),i,h):je(r,i,h),m||(m=g.add(t)),p=Ne(_,t,f,a,s,m,i,n,e),b.push(m),w=p.sub(m);}y=w.mag();}const T=w._mult((x-v)/y)._add(m||g),E=u+Math.atan2(f.y-g.y,f.x-g.x);return b.push(T),{point:T,angle:l?E:0,path:b}}const Ze=new Float32Array([-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0]);function Ve(e,t){for(let i=0;i=1;e--)_.push(s.path[e]);for(let e=1;ee.signedDistanceFromCamera<=0))?[]:e.map((e=>e.point));}let f=[];if(_.length>0){const e=_[0].clone(),i=_[0].clone();for(let t=1;t<_.length;t++)e.x=Math.min(e.x,_[t].x),e.y=Math.min(e.y,_[t].y),i.x=Math.max(i.x,_[t].x),i.y=Math.max(i.y,_[t].y);f=e.x>=r.x&&i.x<=o.x&&e.y>=r.y&&i.y<=o.y?[_]:i.xo.x||i.yo.y?[]:t.clipLine([_],r.x,r.y,o.x,o.y);}for(const t of f){a.reset(t,.25*i);let r=0;r=a.length<=.5*i?1:Math.ceil(a.paddedLength/p)+1;for(let t=0;t{const t=Me(e.x,e.y,r,i.getElevation),o=i.transform.projectTileCoordinates(t.point.x,t.point.y,i.unwrappedTileID,i.getElevation);return o.point.x=(.5*o.point.x+.5)*i.width,o.point.y=(.5*-o.point.y+.5)*i.height,o}))}(e,i);return function(e){let t=0,i=0,r=0,o=0;for(let a=0;ai&&(i=o,t=r));return e.slice(t,t+i)}(r)}queryRenderedSymbols(e){if(0===e.length||0===this.grid.keysLength()&&0===this.ignoredGrid.keysLength())return {};const i=[];let r=1/0,o=1/0,a=-1/0,s=-1/0;for(const n of e){const e=new t.Point(n.x+We,n.y+We);r=Math.min(r,e.x),o=Math.min(o,e.y),a=Math.max(a,e.x),s=Math.max(s,e.y),i.push(e);}const n=this.grid.query(r,o,a,s).concat(this.ignoredGrid.query(r,o,a,s)),l={},c={};for(const e of n){const r=e.key;if(void 0===l[r.bucketInstanceId]&&(l[r.bucketInstanceId]={}),l[r.bucketInstanceId][r.featureIndex])continue;const o=[new t.Point(e.x1,e.y1),new t.Point(e.x2,e.y1),new t.Point(e.x2,e.y2),new t.Point(e.x1,e.y2)];t.polygonIntersectsPolygon(i,o)&&(l[r.bucketInstanceId][r.featureIndex]=!0,void 0===c[r.bucketInstanceId]&&(c[r.bucketInstanceId]=[]),c[r.bucketInstanceId].push(r.featureIndex));}return c}insertCollisionBox(e,t,i,r,o,a){(i?this.ignoredGrid:this.grid).insert({bucketInstanceId:r,featureIndex:o,collisionGroupID:a,overlapMode:t},e[0],e[1],e[2],e[3]);}insertCollisionCircles(e,t,i,r,o,a){const s=i?this.ignoredGrid:this.grid,n={bucketInstanceId:r,featureIndex:o,collisionGroupID:a,overlapMode:t};for(let t=0;t=this.screenRightBoundary||rthis.screenBottomBoundary}isInsideGrid(e,t,i,r){return i>=0&&e=0&&tthis.projectAndGetPerspectiveRatio(e.x,e.y,o,c,u)));S=e.some((e=>!e.isOccluded)),M=e.map((e=>new t.Point(e.x,e.y)));}else S=!0;return {box:t.getAABB(M),allPointsOccluded:!S}}}class $e{constructor(e,t,i,r){this.opacity=e?Math.max(0,Math.min(1,e.opacity+(e.placed?t:-t))):r&&i?1:0,this.placed=i;}isHidden(){return 0===this.opacity&&!this.placed}}class He{constructor(e,t,i,r,o){this.text=new $e(e?e.text:null,t,i,o),this.icon=new $e(e?e.icon:null,t,r,o);}isHidden(){return this.text.isHidden()&&this.icon.isHidden()}}class Ke{constructor(e,t,i){this.text=e,this.icon=t,this.skipFade=i;}}class Ye{constructor(e,t,i,r,o){this.bucketInstanceId=e,this.featureIndex=t,this.sourceLayerIndex=i,this.bucketIndex=r,this.tileID=o;}}class Je{constructor(e){this.crossSourceCollisions=e,this.maxGroupID=0,this.collisionGroups={};}get(e){if(this.crossSourceCollisions)return {ID:0,predicate:null};if(!this.collisionGroups[e]){const t=++this.maxGroupID;this.collisionGroups[e]={ID:t,predicate:e=>e.collisionGroupID===t};}return this.collisionGroups[e]}}function Qe(e,i,r,o,a){const{horizontalAlign:s,verticalAlign:n}=t.getAnchorAlignment(e);return new t.Point(-(s-.5)*i+o[0]*a,-(n-.5)*r+o[1]*a)}class et{constructor(e,t,i,r,o){this.transform=e.clone(),this.terrain=t,this.collisionIndex=new Xe(this.transform),this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=i,this.retainedQueryData={},this.collisionGroups=new Je(r),this.collisionCircleArrays={},this.collisionBoxArrays=new Map,this.prevPlacement=o,o&&(o.prevPlacement=void 0),this.placedOrientations={};}_getTerrainElevationFunc(e){const t=this.terrain;return t?(i,r)=>t.getElevation(e,i,r):null}getBucketParts(e,i,r,o){const a=r.getBucket(i),s=r.latestFeatureIndex;if(!a||!s||i.id!==a.layerIds[0])return;const n=r.collisionBoxArray,l=a.layers[0].layout,c=a.layers[0].paint,h=Math.pow(2,this.transform.zoom-r.tileID.overscaledZ),u=r.tileSize/t.EXTENT,d=r.tileID.toUnwrapped(),_="map"===l.get("text-rotation-alignment"),p=t.pixelsToTileUnits(r,1,this.transform.zoom),m=t.translatePosition(this.collisionIndex.transform,r,c.get("text-translate"),c.get("text-translate-anchor")),f=t.translatePosition(this.collisionIndex.transform,r,c.get("icon-translate"),c.get("icon-translate-anchor")),g=Pe(_,this.transform,p);this.retainedQueryData[a.bucketInstanceId]=new Ye(a.bucketInstanceId,s,a.sourceLayerIndex,a.index,r.tileID);const v={bucket:a,layout:l,translationText:m,translationIcon:f,unwrappedTileID:d,pitchedLabelPlaneMatrix:g,scale:h,textPixelRatio:u,holdingForFade:r.holdingForFade(),collisionBoxArray:n,partiallyEvaluatedTextSize:t.evaluateSizeForZoom(a.textSizeData,this.transform.zoom),collisionGroup:this.collisionGroups.get(a.sourceID)};if(o)for(const t of a.sortKeyRanges){const{sortKey:i,symbolInstanceStart:r,symbolInstanceEnd:o}=t;e.push({sortKey:i,symbolInstanceStart:r,symbolInstanceEnd:o,parameters:v});}else e.push({symbolInstanceStart:0,symbolInstanceEnd:a.symbolInstances.length,parameters:v});}attemptAnchorPlacement(e,i,r,o,a,s,n,l,c,h,u,d,_,p,m,f,g,v,y,x){const b=t.TextAnchorEnum[e.textAnchor],w=[e.textOffset0,e.textOffset1],T=Qe(b,r,o,w,a),E=this.collisionIndex.placeCollisionBox(i,d,l,c,h,n,s,f,u.predicate,y,T,x);if((!v||this.collisionIndex.placeCollisionBox(v,d,l,c,h,n,s,g,u.predicate,y,T,x).placeable)&&E.placeable){let e;if(this.prevPlacement&&this.prevPlacement.variableOffsets[_.crossTileID]&&this.prevPlacement.placements[_.crossTileID]&&this.prevPlacement.placements[_.crossTileID].text&&(e=this.prevPlacement.variableOffsets[_.crossTileID].anchor),0===_.crossTileID)throw new Error("symbolInstance.crossTileID can't be 0");return this.variableOffsets[_.crossTileID]={textOffset:w,width:r,height:o,anchor:b,textBoxScale:a,prevAnchor:e},this.markUsedJustification(p,b,_,m),p.allowVerticalPlacement&&(this.markUsedOrientation(p,m,_),this.placedOrientations[_.crossTileID]=m),{shift:T,placedGlyphBoxes:E}}}placeLayerBucketPart(e,i,r){const{bucket:o,layout:a,translationText:s,translationIcon:n,unwrappedTileID:l,pitchedLabelPlaneMatrix:c,textPixelRatio:h,holdingForFade:u,collisionBoxArray:d,partiallyEvaluatedTextSize:_,collisionGroup:p}=e.parameters,m=a.get("text-optional"),f=a.get("icon-optional"),g=t.getOverlapMode(a,"text-overlap","text-allow-overlap"),v="always"===g,y=t.getOverlapMode(a,"icon-overlap","icon-allow-overlap"),x="always"===y,b="map"===a.get("text-rotation-alignment"),w="map"===a.get("text-pitch-alignment"),T="none"!==a.get("icon-text-fit"),E="viewport-y"===a.get("symbol-z-order"),P=v&&(x||!o.hasIconData()||f),I=x&&(v||!o.hasTextData()||m);!o.collisionArrays&&d&&o.deserializeCollisionBoxes(d);const C=this.retainedQueryData[o.bucketInstanceId].tileID,M=this._getTerrainElevationFunc(C),S=this.transform.getFastPathSimpleProjectionMatrix(C),R=(e,d,x)=>{var E,R;if(i[e.crossTileID])return;if(u)return void(this.placements[e.crossTileID]=new Ke(!1,!1,!1));let D=!1,z=!1,L=!0,A=null,k={box:null,placeable:!1,offscreen:null,occluded:!1},F={box:null,placeable:!1,offscreen:null},B=null,O=null,U=null,j=0,N=0,G=0;d.textFeatureIndex?j=d.textFeatureIndex:e.useRuntimeCollisionCircles&&(j=e.featureIndex),d.verticalTextFeatureIndex&&(N=d.verticalTextFeatureIndex);const Z=d.textBox;if(Z){const i=i=>{let r=t.WritingMode.horizontal;if(o.allowVerticalPlacement&&!i&&this.prevPlacement){const t=this.prevPlacement.placedOrientations[e.crossTileID];t&&(this.placedOrientations[e.crossTileID]=t,r=t,this.markUsedOrientation(o,r,e));}return r},a=(i,r)=>{if(o.allowVerticalPlacement&&e.numVerticalGlyphVertices>0&&d.verticalTextBox){for(const e of o.writingModes)if(e===t.WritingMode.vertical?(k=r(),F=k):k=i(),k&&k.placeable)break}else k=i();},c=e.textAnchorOffsetStartIndex,u=e.textAnchorOffsetEndIndex;if(u===c){const r=(t,i)=>{const r=this.collisionIndex.placeCollisionBox(t,g,h,C,l,w,b,s,p.predicate,M,void 0,S);return r&&r.placeable&&(this.markUsedOrientation(o,i,e),this.placedOrientations[e.crossTileID]=i),r};a((()=>r(Z,t.WritingMode.horizontal)),(()=>{const i=d.verticalTextBox;return o.allowVerticalPlacement&&e.numVerticalGlyphVertices>0&&i?r(i,t.WritingMode.vertical):{box:null,offscreen:null}})),i(k&&k.placeable);}else {let _=t.TextAnchorEnum[null===(R=null===(E=this.prevPlacement)||void 0===E?void 0:E.variableOffsets[e.crossTileID])||void 0===R?void 0:R.anchor];const m=(t,i,a)=>{const d=t.x2-t.x1,m=t.y2-t.y1,f=e.textBoxScale,v=T&&"never"===y?i:null;let x=null,E="never"===g?1:2,P="never";_&&E++;for(let i=0;im(Z,d.iconBox,t.WritingMode.horizontal)),(()=>{const i=d.verticalTextBox;return o.allowVerticalPlacement&&(!k||!k.placeable)&&e.numVerticalGlyphVertices>0&&i?m(i,d.verticalIconBox,t.WritingMode.vertical):{box:null,occluded:!0,offscreen:null}})),k&&(D=k.placeable,L=k.offscreen);const f=i(k&&k.placeable);if(!D&&this.prevPlacement){const t=this.prevPlacement.variableOffsets[e.crossTileID];t&&(this.variableOffsets[e.crossTileID]=t,this.markUsedJustification(o,t.anchor,e,f));}}}if(B=k,D=B&&B.placeable,L=B&&B.offscreen,e.useRuntimeCollisionCircles){const i=o.text.placedSymbolArray.get(e.centerJustifiedTextSymbolIndex),n=t.evaluateSizeForFeature(o.textSizeData,_,i),h=a.get("text-padding");O=this.collisionIndex.placeCollisionCircles(g,i,o.lineVertexArray,o.glyphOffsetArray,n,l,c,r,w,p.predicate,e.collisionCircleDiameter,h,s,M),O.circles.length&&O.collisionDetected&&!r&&t.warnOnce("Collisions detected, but collision boxes are not shown"),D=v||O.circles.length>0&&!O.collisionDetected,L=L&&O.offscreen;}if(d.iconFeatureIndex&&(G=d.iconFeatureIndex),d.iconBox){const e=e=>this.collisionIndex.placeCollisionBox(e,y,h,C,l,w,b,n,p.predicate,M,T&&A?A:void 0,S);F&&F.placeable&&d.verticalIconBox?(U=e(d.verticalIconBox),z=U.placeable):(U=e(d.iconBox),z=U.placeable),L=L&&U.offscreen;}const V=m||0===e.numHorizontalGlyphVertices&&0===e.numVerticalGlyphVertices,q=f||0===e.numIconVertices;V||q?q?V||(z=z&&D):D=z&&D:z=D=z&&D;const W=z&&U.placeable;if(D&&B.placeable&&this.collisionIndex.insertCollisionBox(B.box,g,a.get("text-ignore-placement"),o.bucketInstanceId,F&&F.placeable&&N?N:j,p.ID),W&&this.collisionIndex.insertCollisionBox(U.box,y,a.get("icon-ignore-placement"),o.bucketInstanceId,G,p.ID),O&&D&&this.collisionIndex.insertCollisionCircles(O.circles,g,a.get("text-ignore-placement"),o.bucketInstanceId,j,p.ID),r&&this.storeCollisionData(o.bucketInstanceId,x,d,B,U,O),0===e.crossTileID)throw new Error("symbolInstance.crossTileID can't be 0");if(0===o.bucketInstanceId)throw new Error("bucket.bucketInstanceId can't be 0");this.placements[e.crossTileID]=new Ke((D||P)&&!(null==B?void 0:B.occluded),(z||I)&&!(null==U?void 0:U.occluded),L||o.justReloaded),i[e.crossTileID]=!0;};if(E){if(0!==e.symbolInstanceStart)throw new Error("bucket.bucketInstanceId should be 0");const t=o.getSortedSymbolIndexes(-this.transform.bearingInRadians);for(let e=t.length-1;e>=0;--e){const i=t[e];R(o.symbolInstances.get(i),o.collisionArrays[i],i);}}else for(let t=e.symbolInstanceStart;t=0&&(e.text.placedSymbolArray.get(t).crossTileID=a>=0&&t!==a?0:r.crossTileID);}markUsedOrientation(e,i,r){const o=i===t.WritingMode.horizontal||i===t.WritingMode.horizontalOnly?i:0,a=i===t.WritingMode.vertical?i:0,s=[r.leftJustifiedTextSymbolIndex,r.centerJustifiedTextSymbolIndex,r.rightJustifiedTextSymbolIndex];for(const t of s)e.text.placedSymbolArray.get(t).placedOrientation=o;r.verticalPlacedTextSymbolIndex&&(e.text.placedSymbolArray.get(r.verticalPlacedTextSymbolIndex).placedOrientation=a);}commit(e){this.commitTime=e,this.zoomAtLastRecencyCheck=this.transform.zoom;const t=this.prevPlacement;let i=!1;this.prevZoomAdjustment=t?t.zoomAdjustment(this.transform.zoom):0;const r=t?t.symbolFadeChange(e):1,o=t?t.opacities:{},a=t?t.variableOffsets:{},s=t?t.placedOrientations:{};for(const e in this.placements){const t=this.placements[e],a=o[e];a?(this.opacities[e]=new He(a,r,t.text,t.icon),i=i||t.text!==a.text.placed||t.icon!==a.icon.placed):(this.opacities[e]=new He(null,r,t.text,t.icon,t.skipFade),i=i||t.text||t.icon);}for(const e in o){const t=o[e];if(!this.opacities[e]){const o=new He(t,r,!1,!1);o.isHidden()||(this.opacities[e]=o,i=i||t.text.placed||t.icon.placed);}}for(const e in a)this.variableOffsets[e]||!this.opacities[e]||this.opacities[e].isHidden()||(this.variableOffsets[e]=a[e]);for(const e in s)this.placedOrientations[e]||!this.opacities[e]||this.opacities[e].isHidden()||(this.placedOrientations[e]=s[e]);if(t&&void 0===t.lastPlacementChangeTime)throw new Error("Last placement time for previous placement is not defined");i?this.lastPlacementChangeTime=e:"number"!=typeof this.lastPlacementChangeTime&&(this.lastPlacementChangeTime=t?t.lastPlacementChangeTime:e);}updateLayerOpacities(e,t){const i={};for(const r of t){const t=r.getBucket(e);t&&r.latestFeatureIndex&&e.id===t.layerIds[0]&&this.updateBucketOpacities(t,r.tileID,i,r.collisionBoxArray);}}updateBucketOpacities(e,i,r,o){e.hasTextData()&&(e.text.opacityVertexArray.clear(),e.text.hasVisibleVertices=!1),e.hasIconData()&&(e.icon.opacityVertexArray.clear(),e.icon.hasVisibleVertices=!1),e.hasIconCollisionBoxData()&&e.iconCollisionBox.collisionVertexArray.clear(),e.hasTextCollisionBoxData()&&e.textCollisionBox.collisionVertexArray.clear();const a=e.layers[0],s=a.layout,n=new He(null,0,!1,!1,!0),l=s.get("text-allow-overlap"),c=s.get("icon-allow-overlap"),h=a._unevaluatedLayout.hasValue("text-variable-anchor")||a._unevaluatedLayout.hasValue("text-variable-anchor-offset"),u="map"===s.get("text-rotation-alignment"),d="map"===s.get("text-pitch-alignment"),_="none"!==s.get("icon-text-fit"),p=new He(null,0,l&&(c||!e.hasIconData()||s.get("icon-optional")),c&&(l||!e.hasTextData()||s.get("text-optional")),!0);!e.collisionArrays&&o&&(e.hasIconCollisionBoxData()||e.hasTextCollisionBoxData())&&e.deserializeCollisionBoxes(o);const m=(e,t,i)=>{for(let r=0;r0,v=this.placedOrientations[o.crossTileID],y=v===t.WritingMode.vertical,x=v===t.WritingMode.horizontal||v===t.WritingMode.horizontalOnly;if(a>0||s>0){const t=ct(c.text);m(e.text,a,y?ht:t),m(e.text,s,x?ht:t);const i=c.text.isHidden();[o.rightJustifiedTextSymbolIndex,o.centerJustifiedTextSymbolIndex,o.leftJustifiedTextSymbolIndex].forEach((t=>{t>=0&&(e.text.placedSymbolArray.get(t).hidden=i||y?1:0);})),o.verticalPlacedTextSymbolIndex>=0&&(e.text.placedSymbolArray.get(o.verticalPlacedTextSymbolIndex).hidden=i||x?1:0);const r=this.variableOffsets[o.crossTileID];r&&this.markUsedJustification(e,r.anchor,o,v);const n=this.placedOrientations[o.crossTileID];n&&(this.markUsedJustification(e,"left",o,n),this.markUsedOrientation(e,n,o));}if(g){const t=ct(c.icon),i=!(_&&o.verticalPlacedIconSymbolIndex&&y);o.placedIconSymbolIndex>=0&&(m(e.icon,o.numIconVertices,i?t:ht),e.icon.placedSymbolArray.get(o.placedIconSymbolIndex).hidden=c.icon.isHidden()),o.verticalPlacedIconSymbolIndex>=0&&(m(e.icon,o.numVerticalIconVertices,i?ht:t),e.icon.placedSymbolArray.get(o.verticalPlacedIconSymbolIndex).hidden=c.icon.isHidden());}const b=f&&f.has(i)?f.get(i):{text:null,icon:null};if(e.hasIconCollisionBoxData()||e.hasTextCollisionBoxData()){const r=e.collisionArrays[i];if(r){let i=new t.Point(0,0);if(r.textBox||r.verticalTextBox){let t=!0;if(h){const e=this.variableOffsets[l];e?(i=Qe(e.anchor,e.width,e.height,e.textOffset,e.textBoxScale),u&&i._rotate(d?-this.transform.bearingInRadians:this.transform.bearingInRadians)):t=!1;}if(r.textBox||r.verticalTextBox){let o;r.textBox&&(o=y),r.verticalTextBox&&(o=x),tt(e.textCollisionBox.collisionVertexArray,c.text.placed,!t||o,b.text,i.x,i.y);}}if(r.iconBox||r.verticalIconBox){const t=Boolean(!x&&r.verticalIconBox);let o;r.iconBox&&(o=t),r.verticalIconBox&&(o=!t),tt(e.iconCollisionBox.collisionVertexArray,c.icon.placed,o,b.icon,_?i.x:0,_?i.y:0);}}}}if(e.sortFeatures(-this.transform.bearingInRadians),this.retainedQueryData[e.bucketInstanceId]&&(this.retainedQueryData[e.bucketInstanceId].featureSortOrder=e.featureSortOrder),e.hasTextData()&&e.text.opacityVertexBuffer&&e.text.opacityVertexBuffer.updateData(e.text.opacityVertexArray),e.hasIconData()&&e.icon.opacityVertexBuffer&&e.icon.opacityVertexBuffer.updateData(e.icon.opacityVertexArray),e.hasIconCollisionBoxData()&&e.iconCollisionBox.collisionVertexBuffer&&e.iconCollisionBox.collisionVertexBuffer.updateData(e.iconCollisionBox.collisionVertexArray),e.hasTextCollisionBoxData()&&e.textCollisionBox.collisionVertexBuffer&&e.textCollisionBox.collisionVertexBuffer.updateData(e.textCollisionBox.collisionVertexArray),e.text.opacityVertexArray.length!==e.text.layoutVertexArray.length/4)throw new Error(`bucket.text.opacityVertexArray.length (= ${e.text.opacityVertexArray.length}) !== bucket.text.layoutVertexArray.length (= ${e.text.layoutVertexArray.length}) / 4`);if(e.icon.opacityVertexArray.length!==e.icon.layoutVertexArray.length/4)throw new Error(`bucket.icon.opacityVertexArray.length (= ${e.icon.opacityVertexArray.length}) !== bucket.icon.layoutVertexArray.length (= ${e.icon.layoutVertexArray.length}) / 4`);e.bucketInstanceId in this.collisionCircleArrays&&(e.collisionCircleArray=this.collisionCircleArrays[e.bucketInstanceId],delete this.collisionCircleArrays[e.bucketInstanceId]);}symbolFadeChange(e){return 0===this.fadeDuration?1:(e-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(e){return Math.max(0,(this.transform.zoom-e)/1.5)}hasTransitions(e){return this.stale||e-this.lastPlacementChangeTimee}setStale(){this.stale=!0;}}function tt(e,t,i,r,o,a){r&&0!==r.length||(r=[0,0,0,0]);const s=r[0]-We,n=r[1]-We,l=r[2]-We,c=r[3]-We;e.emplaceBack(t?1:0,i?1:0,o||0,a||0,s,n),e.emplaceBack(t?1:0,i?1:0,o||0,a||0,l,n),e.emplaceBack(t?1:0,i?1:0,o||0,a||0,l,c),e.emplaceBack(t?1:0,i?1:0,o||0,a||0,s,c);}const it=Math.pow(2,25),rt=Math.pow(2,24),ot=Math.pow(2,17),at=Math.pow(2,16),st=Math.pow(2,9),nt=Math.pow(2,8),lt=Math.pow(2,1);function ct(e){if(0===e.opacity&&!e.placed)return 0;if(1===e.opacity&&e.placed)return 4294967295;const t=e.placed?1:0,i=Math.floor(127*e.opacity);return i*it+t*rt+i*ot+t*at+i*st+t*nt+i*lt+t}const ht=0;class ut{constructor(e){this._sortAcrossTiles="viewport-y"!==e.layout.get("symbol-z-order")&&!e.layout.get("symbol-sort-key").isConstant(),this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs={},this._bucketParts=[];}continuePlacement(e,t,i,r,o){const a=this._bucketParts;for(;this._currentTileIndexe.sortKey-t.sortKey)));this._currentPartIndex!this._forceFullPlacement&&f.now()-r>2;for(;this._currentPlacementIndex>=0;){const r=t[e[this._currentPlacementIndex]],a=this.placement.collisionIndex.transform.zoom;if("symbol"===r.type&&(!r.minzoom||r.minzoom<=a)&&(!r.maxzoom||r.maxzoom>a)){if(this._inProgressLayer||(this._inProgressLayer=new ut(r)),this._inProgressLayer.continuePlacement(i[r.source],this.placement,this._showCollisionBoxes,r,o))return;delete this._inProgressLayer;}this._currentPlacementIndex--;}this._done=!0;}commit(e){return this.placement.commit(e),this.placement}}const _t=512/t.EXTENT/2;class pt{constructor(e,i,r){this.tileID=e,this.bucketInstanceId=r,this._symbolsByKey={};const o=new Map;for(let e=0;e({x:Math.floor(e.anchorX*_t),y:Math.floor(e.anchorY*_t)}))),crossTileIDs:i.map((e=>e.crossTileID))};if(r.positions.length>128){const e=new t.KDBush(r.positions.length,16,Uint16Array);for(const{x:t,y:i}of r.positions)e.add(t,i);e.finish(),delete r.positions,r.index=e;}this._symbolsByKey[e]=r;}}getScaledCoordinates(e,i){const{x:r,y:o,z:a}=this.tileID.canonical,{x:s,y:n,z:l}=i.canonical,c=_t/Math.pow(2,l-a),h=(n*t.EXTENT+e.anchorY)*c,u=o*t.EXTENT*_t;return {x:Math.floor((s*t.EXTENT+e.anchorX)*c-r*t.EXTENT*_t),y:Math.floor(h-u)}}findMatches(e,t,i){const r=this.tileID.canonical.ze))}}class mt{constructor(){this.maxCrossTileID=0;}generate(){return ++this.maxCrossTileID}}class ft{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0;}handleWrapJump(e){const t=Math.round((e-this.lng)/360);if(0!==t)for(const e in this.indexes){const i=this.indexes[e],r={};for(const e in i){const o=i[e];o.tileID=o.tileID.unwrapTo(o.tileID.wrap+t),r[o.tileID.key]=o;}this.indexes[e]=r;}this.lng=e;}addBucket(e,t,i){if(this.indexes[e.overscaledZ]&&this.indexes[e.overscaledZ][e.key]){if(this.indexes[e.overscaledZ][e.key].bucketInstanceId===t.bucketInstanceId)return !1;this.removeBucketCrossTileIDs(e.overscaledZ,this.indexes[e.overscaledZ][e.key]);}for(let e=0;ee.overscaledZ)for(const i in o){const a=o[i];a.tileID.isChildOf(e)&&a.findMatches(t.symbolInstances,e,r);}else {const a=o[e.scaledTo(Number(i)).key];a&&a.findMatches(t.symbolInstances,e,r);}}for(let e=0;e{t[e]=!0;}));for(const e in this.layerIndexes)t[e]||delete this.layerIndexes[e];}}var vt="void main() {gl_FragColor=vec4(1.0);}";const yt={prelude:xt("#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","#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;}mat3 rotationMatrixFromAxisAngle(vec3 u,float angle) {float c=cos(angle);float s=sin(angle);float c2=1.0-c;return mat3(u.x*u.x*c2+ c,u.x*u.y*c2-u.z*s,u.x*u.z*c2+u.y*s,u.y*u.x*c2+u.z*s,u.y*u.y*c2+ c,u.y*u.z*c2-u.x*s,u.z*u.x*c2-u.y*s,u.z*u.y*c2+u.x*s,u.z*u.z*c2+ c\n);}\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}const float PI=3.141592653589793;uniform mat4 u_projection_matrix;"),projectionMercator:xt("","float projectLineThickness(float tileY) {return 1.0;}float projectCircleRadius(float tileY) {return 1.0;}vec4 projectTile(vec2 p) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);return result;}vec4 projectTile(vec2 p,vec2 rawPos) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);if (rawPos.y <-32767.5 || rawPos.y > 32766.5) {result.z=-10000000.0;}return result;}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_projection_matrix*vec4(posInTile,elevation,1.0);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {return projectTileWithElevation(posInTile,elevation);}"),projectionGlobe:xt("","#define GLOBE_RADIUS 6371008.8\nuniform highp vec4 u_projection_tile_mercator_coords;uniform highp vec4 u_projection_clipping_plane;uniform highp float u_projection_transition;uniform mat4 u_projection_fallback_matrix;vec3 globeRotateVector(vec3 vec,vec2 angles) {vec3 axisRight=vec3(vec.z,0.0,-vec.x);vec3 axisUp=cross(axisRight,vec);axisRight=normalize(axisRight);axisUp=normalize(axisUp);vec2 t=tan(angles);return normalize(vec+axisRight*t.x+axisUp*t.y);}mat3 globeGetRotationMatrix(vec3 spherePos) {vec3 axisRight=vec3(spherePos.z,0.0,-spherePos.x);vec3 axisDown=cross(axisRight,spherePos);axisRight=normalize(axisRight);axisDown=normalize(axisDown);return mat3(axisRight,axisDown,spherePos\n);}float circumferenceRatioAtTileY(float tileY) {float mercator_pos_y=u_projection_tile_mercator_coords.y+u_projection_tile_mercator_coords.w*tileY;float spherical_y=2.0*atan(exp(PI-(mercator_pos_y*PI*2.0)))-PI*0.5;return cos(spherical_y);}float projectLineThickness(float tileY) {float thickness=1.0/circumferenceRatioAtTileY(tileY); \nif (u_projection_transition < 0.999) {return mix(1.0,thickness,u_projection_transition);} else {return thickness;}}vec3 projectToSphere(vec2 posInTile,vec2 rawPos) {vec2 mercator_pos=u_projection_tile_mercator_coords.xy+u_projection_tile_mercator_coords.zw*posInTile;vec2 spherical;spherical.x=mercator_pos.x*PI*2.0+PI;spherical.y=2.0*atan(exp(PI-(mercator_pos.y*PI*2.0)))-PI*0.5;float len=cos(spherical.y);vec3 pos=vec3(sin(spherical.x)*len,sin(spherical.y),cos(spherical.x)*len\n);if (rawPos.y <-32767.5) {pos=vec3(0.0,1.0,0.0);}if (rawPos.y > 32766.5) {pos=vec3(0.0,-1.0,0.0);}return pos;}vec3 projectToSphere(vec2 posInTile) {return projectToSphere(posInTile,vec2(0.0,0.0));}float globeComputeClippingZ(vec3 spherePos) {return (1.0-(dot(spherePos,u_projection_clipping_plane.xyz)+u_projection_clipping_plane.w));}vec4 interpolateProjection(vec2 posInTile,vec3 spherePos,float elevation) {vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);globePosition.z=globeComputeClippingZ(elevatedPos)*globePosition.w;if (u_projection_transition < 0.999) {vec4 flatPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);const float z_globeness_threshold=0.2;vec4 result=globePosition;result.z=mix(0.0,globePosition.z,clamp((u_projection_transition-z_globeness_threshold)/(1.0-z_globeness_threshold),0.0,1.0));result.xyw=mix(flatPosition.xyw,globePosition.xyw,u_projection_transition);if ((posInTile.y <-32767.5) || (posInTile.y > 32766.5)) {result=globePosition;const float poles_hidden_anim_percentage=0.02;result.z=mix(globePosition.z,100.0,pow(max((1.0-u_projection_transition)/poles_hidden_anim_percentage,0.0),8.0));}return result;}return globePosition;}vec4 interpolateProjectionFor3D(vec2 posInTile,vec3 spherePos,float elevation) {vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);vec4 fallbackPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);return mix(fallbackPosition,globePosition,u_projection_transition);}vec4 projectTile(vec2 posInTile) {return interpolateProjection(posInTile,projectToSphere(posInTile),0.0);}vec4 projectTile(vec2 posInTile,vec2 rawPos) {return interpolateProjection(posInTile,projectToSphere(posInTile,rawPos),0.0);}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return interpolateProjection(posInTile,projectToSphere(posInTile),elevation);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {vec3 spherePos=projectToSphere(posInTile);return interpolateProjectionFor3D(posInTile,spherePos,elevation);}"),background:xt("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}","attribute vec2 a_pos;void main() {gl_Position=projectTile(a_pos);}"),backgroundPattern:xt("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}","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=projectTile(a_pos);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);}"),circle:xt("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);float antialiased_blur=v_data.z;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);const float epsilon=0.5/255.0;if (gl_FragColor.r < epsilon && gl_FragColor.g < epsilon && gl_FragColor.b < epsilon && gl_FragColor.a < epsilon) {discard;}\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform bool u_scale_with_map;uniform bool u_pitch_with_map;uniform vec2 u_extrude_scale;uniform highp float u_globe_extrude_scale;uniform lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;uniform vec2 u_translate;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 pos_raw=a_pos+32768.0;vec2 extrude=vec2(mod(pos_raw,8.0)/7.0*2.0-1.0);vec2 circle_center=floor(pos_raw/8.0)+u_translate;float ele=get_elevation(circle_center);v_visibility=calculate_visibility(projectTileWithElevation(circle_center,ele));if (u_pitch_with_map) {\n#ifdef GLOBE\nvec3 center_vector=projectToSphere(circle_center);\n#endif\nfloat angle_scale=u_globe_extrude_scale;vec2 corner_position=circle_center;if (u_scale_with_map) {angle_scale*=(radius+stroke_width);corner_position+=extrude*u_extrude_scale*(radius+stroke_width);} else {\n#ifdef GLOBE\nvec4 projected_center=interpolateProjection(circle_center,center_vector,ele);\n#else\nvec4 projected_center=projectTileWithElevation(circle_center,ele);\n#endif\ncorner_position+=extrude*u_extrude_scale*(radius+stroke_width)*(projected_center.w/u_camera_to_center_distance);angle_scale*=(radius+stroke_width)*(projected_center.w/u_camera_to_center_distance);}\n#ifdef GLOBE\nvec2 angles=extrude*angle_scale;vec3 corner_vector=globeRotateVector(center_vector,angles);gl_Position=interpolateProjection(corner_position,corner_vector,ele);\n#else\ngl_Position=projectTileWithElevation(corner_position,ele);\n#endif\n} else {gl_Position=projectTileWithElevation(circle_center,ele);if (gl_Position.z/gl_Position.w > 1.0) {gl_Position.xy=vec2(10000.0);}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;}}float antialiasblur=-max(1.0/u_device_pixel_ratio/(radius+stroke_width),blur);v_data=vec3(extrude.x,extrude.y,antialiasblur);}"),clippingMask:xt(vt,"attribute vec2 a_pos;void main() {gl_Position=projectTile(a_pos);}"),heatmap:xt("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}","uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;uniform highp float u_globe_extrude_scale;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 pos_raw=a_pos+32768.0;vec2 unscaled_extrude=vec2(mod(pos_raw,8.0)/7.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;vec2 circle_center=floor(pos_raw/8.0);\n#ifdef GLOBE\nvec2 angles=v_extrude*radius*u_globe_extrude_scale;vec3 center_vector=projectToSphere(circle_center);vec3 corner_vector=globeRotateVector(center_vector,angles);gl_Position=interpolateProjection(circle_center+extrude,corner_vector,0.0);\n#else\ngl_Position=projectTileFor3D(circle_center+extrude,get_elevation(circle_center));\n#endif\n}"),heatmapTexture:xt("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}","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;}"),collisionBox:xt("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;}}","attribute vec2 a_anchor_pos;attribute vec2 a_placed;attribute vec2 a_box_real;uniform vec2 u_pixel_extrude_scale;varying float v_placed;varying float v_notUsed;void main() {gl_Position=projectTileWithElevation(a_anchor_pos,get_elevation(a_anchor_pos));gl_Position.xy=((a_box_real+0.5)*u_pixel_extrude_scale*2.0-1.0)*vec2(1.0,-1.0)*gl_Position.w;if (gl_Position.z/gl_Position.w < 1.1) {gl_Position.z=0.5;}v_placed=a_placed.x;v_notUsed=a_placed.y;}"),collisionCircle:xt("varying float v_radius;varying vec2 v_extrude;varying float v_collision;void main() {float alpha=0.5;float stroke_radius=0.9;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;}","attribute vec2 a_pos;attribute float a_radius;attribute vec2 a_flags;uniform vec2 u_viewport_size;varying float v_radius;varying vec2 v_extrude;varying float v_collision;void main() {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;float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_collision=collision;gl_Position=vec4((a_pos/u_viewport_size*2.0-1.0)*vec2(1.0,-1.0),0.0,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}"),debug:xt("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);}","attribute vec2 a_pos;varying vec2 v_uv;uniform float u_overlay_scale;void main() {v_uv=a_pos/8192.0;gl_Position=projectTileWithElevation(a_pos*u_overlay_scale,get_elevation(a_pos));}"),depth:xt(vt,"attribute vec2 a_pos;void main() {\n#ifdef GLOBE\ngl_Position=projectTileFor3D(a_pos,0.0);\n#else\ngl_Position=u_projection_matrix*vec4(a_pos,0.0,1.0);\n#endif\n}"),fill:xt("#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}","uniform vec2 u_fill_translate;attribute vec2 a_pos;\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=projectTile(a_pos+u_fill_translate,a_pos);}"),fillOutline:xt("varying vec2 v_pos;\n#ifdef GLOBE\nvarying float v_depth;\n#endif\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 GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_world;uniform vec2 u_fill_translate;attribute vec2 a_pos;varying vec2 v_pos;\n#ifdef GLOBE\nvarying float v_depth;\n#endif\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=projectTile(a_pos+u_fill_translate,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n}"),fillOutlinePattern:xt("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#ifdef GLOBE\nvarying float v_depth;\n#endif\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 GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;uniform vec2 u_fill_translate;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec2 v_pos;\n#ifdef GLOBE\nvarying float v_depth;\n#endif\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=projectTile(a_pos+u_fill_translate,a_pos);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;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n}"),fillPattern:xt("#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}","uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;uniform vec2 u_fill_translate;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=projectTile(a_pos+u_fill_translate,a_pos);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);}"),fillExtrusion:xt("varying vec4 v_color;void main() {gl_FragColor=v_color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec2 u_fill_translate;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);float elevation=t > 0.0 ? height : base;vec2 posInTile=a_pos+u_fill_translate;\n#ifdef GLOBE\nvec3 spherePos=projectToSphere(posInTile,a_pos);gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);\n#else\ngl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);\n#endif\nfloat 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;vec3 normalForLighting=normal/16384.0;float directional=clamp(dot(normalForLighting,u_lightpos),0.0,1.0);\n#ifdef GLOBE\nmat3 rotMatrix=globeGetRotationMatrix(spherePos);normalForLighting=rotMatrix*normalForLighting;directional=mix(directional,clamp(dot(normalForLighting,u_lightpos_globe),0.0,1.0),u_projection_transition);\n#endif\ndirectional=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;}"),fillExtrusionPattern:xt("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}","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 vec2 u_fill_translate;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;attribute vec2 a_pos;attribute vec4 a_normal_ed;\n#ifdef TERRAIN3D\nattribute vec2 a_centroid;\n#endif\n#ifdef GLOBE\nvarying vec3 v_sphere_pos;\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 elevation=t > 0.0 ? height : base;vec2 posInTile=a_pos+u_fill_translate;\n#ifdef GLOBE\nvec3 spherePos=projectToSphere(posInTile,a_pos);vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);v_sphere_pos=elevatedPos;gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);\n#else\ngl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);\n#endif\nvec2 pos=normal.x==1.0 && normal.y==0.0 && normal.z==16384.0\n? a_pos\n: vec2(edgedistance,elevation*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;}"),hillshadePrepare:xt("#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}","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;}"),hillshade:xt("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}","uniform mat4 u_matrix;attribute vec2 a_pos;varying vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);v_pos=a_pos/8192.0;if (a_pos.y <-32767.5) {v_pos.y=0.0;}if (a_pos.y > 32766.5) {v_pos.y=1.0;}}"),line:xt("uniform lowp float u_device_pixel_ratio;varying vec2 v_width2;varying vec2 v_normal;varying float v_gamma_scale;\n#ifdef GLOBE\nvarying float v_depth;\n#endif\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 GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform vec2 u_translation;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#ifdef GLOBE\nvarying float v_depth;\n#endif\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);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}"),lineGradient:xt("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#ifdef GLOBE\nvarying float v_depth;\n#endif\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 GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","\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 vec2 u_translation;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#ifdef GLOBE\nvarying float v_depth;\n#endif\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);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}"),linePattern:xt("#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#ifdef GLOBE\nvarying float v_depth;\n#endif\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 GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform vec2 u_translation;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#ifdef GLOBE\nvarying float v_depth;\n#endif\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);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.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;}"),lineSDF:xt("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#ifdef GLOBE\nvarying float v_depth;\n#endif\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 GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform vec2 u_translation;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#ifdef GLOBE\nvarying float v_depth;\n#endif\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);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.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);}"),raster:xt("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}","uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_buffer_scale;uniform vec4 u_coords_top;uniform vec4 u_coords_bottom;attribute vec2 a_pos;varying vec2 v_pos0;varying vec2 v_pos1;void main() {vec2 fractionalPos=a_pos/8192.0;vec2 position=mix(mix(u_coords_top.xy,u_coords_top.zw,fractionalPos.x),mix(u_coords_bottom.xy,u_coords_bottom.zw,fractionalPos.x),fractionalPos.y);gl_Position=projectTile(position,position);v_pos0=((fractionalPos-0.5)/u_buffer_scale)+0.5;\n#ifdef GLOBE\nif (a_pos.y <-32767.5) {v_pos0.y=0.0;}if (a_pos.y > 32766.5) {v_pos0.y=1.0;}\n#endif\nv_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}"),symbolIcon:xt("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}","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_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform vec2 u_texsize;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;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;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);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=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);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;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map && !u_is_along_line) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset/16.0)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}gl_Position=finalPos;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));}"),symbolSDF:xt("#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}","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_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;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_translation;uniform float u_pitched_scale;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;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);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=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);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;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale+a_pxoffset)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;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);}"),symbolTextAndIcon:xt("#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}","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_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;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;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;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);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=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);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;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map && !u_is_along_line) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;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);}"),terrain:xt("uniform sampler2D u_texture;uniform vec4 u_fog_color;uniform vec4 u_horizon_color;uniform float u_fog_ground_blend;uniform float u_fog_ground_blend_opacity;uniform float u_horizon_fog_blend;uniform bool u_is_globe_mode;varying vec2 v_texture_pos;varying float v_fog_depth;const float gamma=2.2;vec4 gammaToLinear(vec4 color) {return pow(color,vec4(gamma));}vec4 linearToGamma(vec4 color) {return pow(color,vec4(1.0/gamma));}void main() {vec4 surface_color=texture2D(u_texture,vec2(v_texture_pos.x,1.0-v_texture_pos.y));if (!u_is_globe_mode && v_fog_depth > u_fog_ground_blend) {vec4 surface_color_linear=gammaToLinear(surface_color);float blend_color=smoothstep(0.0,1.0,max((v_fog_depth-u_horizon_fog_blend)/(1.0-u_horizon_fog_blend),0.0));vec4 fog_horizon_color_linear=mix(gammaToLinear(u_fog_color),gammaToLinear(u_horizon_color),blend_color);float factor_fog=max(v_fog_depth-u_fog_ground_blend,0.0)/(1.0-u_fog_ground_blend);gl_FragColor=linearToGamma(mix(surface_color_linear,fog_horizon_color_linear,pow(factor_fog,2.0)*u_fog_ground_blend_opacity));} else {gl_FragColor=surface_color;}}","attribute vec3 a_pos3d;uniform mat4 u_fog_matrix;uniform float u_ele_delta;varying vec2 v_texture_pos;varying float v_fog_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=projectTileFor3D(a_pos3d.xy,get_elevation(a_pos3d.xy)-ele_delta);vec4 pos=u_fog_matrix*vec4(a_pos3d.xy,ele,1.0);v_fog_depth=pos.z/pos.w*0.5+0.5;}"),terrainDepth:xt("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);}","attribute vec3 a_pos3d;uniform float u_ele_delta;varying float v_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);v_depth=gl_Position.z/gl_Position.w;}"),terrainCoords:xt("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);}","attribute vec3 a_pos3d;uniform float u_ele_delta;varying vec2 v_texture_pos;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);}"),projectionErrorMeasurement:xt("varying vec4 v_output_error_encoded;void main() {gl_FragColor=v_output_error_encoded;}","attribute vec2 a_pos;uniform highp float u_input;uniform highp float u_output_expected;varying vec4 v_output_error_encoded;void main() {float real_output=2.0*atan(exp(PI-(u_input*PI*2.0)))-PI*0.5;float error=real_output-u_output_expected;float abs_error=abs(error)*128.0;v_output_error_encoded.x=min(floor(abs_error*256.0),255.0)/255.0;abs_error-=v_output_error_encoded.x;v_output_error_encoded.y=min(floor(abs_error*65536.0),255.0)/255.0;abs_error-=v_output_error_encoded.x/255.0;v_output_error_encoded.z=min(floor(abs_error*16777216.0),255.0)/255.0;v_output_error_encoded.w=error >=0.0 ? 1.0 : 0.0;gl_Position=vec4(a_pos,0.0,1.0);}"),atmosphere:xt("varying vec3 view_direction;uniform vec3 u_sun_pos;uniform vec3 u_globe_position;uniform float u_globe_radius;uniform float u_atmosphere_blend;/**Shader use from https:*Made some change to adapt to MapLibre Globe geometry*/const float PI=3.141592653589793;const int iSteps=5;const int jSteps=3;/*radius of the planet*/const float EARTH_RADIUS=6371e3;/*radius of the atmosphere*/const float ATMOS_RADIUS=6471e3;vec2 rsi(vec3 r0,vec3 rd,float sr) {float a=dot(rd,rd);float b=2.0*dot(rd,r0);float c=dot(r0,r0)-(sr*sr);float d=(b*b)-4.0*a*c;if (d < 0.0) return vec2(1e5,-1e5);return vec2((-b-sqrt(d))/(2.0*a),(-b+sqrt(d))/(2.0*a));}vec4 atmosphere(vec3 r,vec3 r0,vec3 pSun,float iSun,float rPlanet,float rAtmos,vec3 kRlh,float kMie,float shRlh,float shMie,float g) {pSun=normalize(pSun);r=normalize(r);vec2 p=rsi(r0,r,rAtmos);if (p.x > p.y) return vec4(0,0,0,0);if (p.x < 0.0) {p.x=0.0;}vec3 pos=r0+r*p.x;vec2 p2=rsi(r0,r,rPlanet);if (p2.x <=p2.y && p2.x > 0.0) {p.y=min(p.y,p2.x);}float iStepSize=(p.y-p.x)/float(iSteps);float iTime=p.x+iStepSize*0.5;vec3 totalRlh=vec3(0,0,0);vec3 totalMie=vec3(0,0,0);float iOdRlh=0.0;float iOdMie=0.0;float mu=dot(r,pSun);float mumu=mu*mu;float gg=g*g;float pRlh=3.0/(16.0*PI)*(1.0+mumu);float pMie=3.0/(8.0*PI)*((1.0-gg)*(mumu+1.0))/(pow(1.0+gg-2.0*mu*g,1.5)*(2.0+gg));for (int i=0; i < iSteps; i++) {vec3 iPos=r0+r*iTime;float iHeight=length(iPos)-rPlanet;float odStepRlh=exp(-iHeight/shRlh)*iStepSize;float odStepMie=exp(-iHeight/shMie)*iStepSize;iOdRlh+=odStepRlh;iOdMie+=odStepMie;float jStepSize=rsi(iPos,pSun,rAtmos).y/float(jSteps);float jTime=jStepSize*0.5;float jOdRlh=0.0;float jOdMie=0.0;for (int j=0; j < jSteps; j++) {vec3 jPos=iPos+pSun*jTime;float jHeight=length(jPos)-rPlanet;jOdRlh+=exp(-jHeight/shRlh)*jStepSize;jOdMie+=exp(-jHeight/shMie)*jStepSize;jTime+=jStepSize;}vec3 attn=exp(-(kMie*(iOdMie+jOdMie)+kRlh*(iOdRlh+jOdRlh)));totalRlh+=odStepRlh*attn;totalMie+=odStepMie*attn;iTime+=iStepSize;}float opacity=min(0.75,exp(-(length(kRlh)*length(totalRlh)+kMie*length(totalMie))));vec3 color=iSun*(pRlh*kRlh*totalRlh+pMie*kMie*totalMie);return vec4(color,opacity);}void main() {vec3 scale_camera_pos=-u_globe_position*EARTH_RADIUS/u_globe_radius;vec4 color=atmosphere(normalize(view_direction),scale_camera_pos,u_sun_pos,22.0,EARTH_RADIUS,ATMOS_RADIUS,vec3(5.5e-6,13.0e-6,22.4e-6),21e-6,8e3,1.2e3,0.758\n);color.xyz=1.0-exp(-1.0*color.xyz);vec4 no_effect_color=vec4(0,0,0,0);gl_FragColor=mix(color,no_effect_color,1.0-u_atmosphere_blend);}","attribute vec2 a_pos;uniform mat4 u_inv_proj_matrix;varying vec3 view_direction;void main() {view_direction=(u_inv_proj_matrix*vec4(a_pos,0.0,1.0)).xyz;gl_Position=vec4(a_pos,0.0,1.0);}"),sky:xt("uniform vec4 u_sky_color;uniform vec4 u_horizon_color;uniform vec2 u_horizon;uniform vec2 u_horizon_normal;uniform float u_sky_horizon_blend;uniform float u_sky_blend;void main() {float x=gl_FragCoord.x;float y=gl_FragCoord.y;float blend=(y-u_horizon.y)*u_horizon_normal.y+(x-u_horizon.x)*u_horizon_normal.x;if (blend > 0.0) {if (blend < u_sky_horizon_blend) {gl_FragColor=mix(u_sky_color,u_horizon_color,pow(1.0-blend/u_sky_horizon_blend,2.0));} else {gl_FragColor=u_sky_color;}}gl_FragColor=mix(gl_FragColor,vec4(vec3(0.0),0.0),u_sky_blend);}","attribute vec2 a_pos;void main() {gl_Position=vec4(a_pos,1.0,1.0);}")};function xt(e,t){const i=/#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g,r=t.match(/attribute ([\w]+) ([\w]+)/g),o=e.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),a=t.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),s=a?a.concat(o):o,n={};return {fragmentSource:e=e.replace(i,((e,t,i,r,o)=>(n[o]=!0,"define"===t?`\n#ifndef HAS_UNIFORM_u_${o}\nvarying ${i} ${r} ${o};\n#else\nuniform ${i} ${r} u_${o};\n#endif\n`:`\n#ifdef HAS_UNIFORM_u_${o}\n ${i} ${r} ${o} = u_${o};\n#endif\n`))),vertexSource:t=t.replace(i,((e,t,i,r,o)=>{const a="float"===r?"vec2":"vec4",s=o.match(/color/)?"color":a;return n[o]?"define"===t?`\n#ifndef HAS_UNIFORM_u_${o}\nuniform lowp float u_${o}_t;\nattribute ${i} ${a} a_${o};\nvarying ${i} ${r} ${o};\n#else\nuniform ${i} ${r} u_${o};\n#endif\n`:"vec4"===s?`\n#ifndef HAS_UNIFORM_u_${o}\n ${o} = a_${o};\n#else\n ${i} ${r} ${o} = u_${o};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${o}\n ${o} = unpack_mix_${s}(a_${o}, u_${o}_t);\n#else\n ${i} ${r} ${o} = u_${o};\n#endif\n`:"define"===t?`\n#ifndef HAS_UNIFORM_u_${o}\nuniform lowp float u_${o}_t;\nattribute ${i} ${a} a_${o};\n#else\nuniform ${i} ${r} u_${o};\n#endif\n`:"vec4"===s?`\n#ifndef HAS_UNIFORM_u_${o}\n ${i} ${r} ${o} = a_${o};\n#else\n ${i} ${r} ${o} = u_${o};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${o}\n ${i} ${r} ${o} = unpack_mix_${s}(a_${o}, u_${o}_t);\n#else\n ${i} ${r} ${o} = u_${o};\n#endif\n`})),staticAttributes:r,staticUniforms:s}}class bt{constructor(e,t,i){this.vertexBuffer=e,this.indexBuffer=t,this.segments=i;}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.vertexBuffer=null,this.indexBuffer=null,this.segments=null;}}var wt=t.createLayout([{name:"a_pos",type:"Int16",components:2}]);const Tt="#define PROJECTION_MERCATOR",Et="mercator";class Pt{constructor(){this._cachedMesh=null;}get name(){return "mercator"}get useSubdivision(){return !1}get shaderVariantName(){return Et}get shaderDefine(){return Tt}get shaderPreludeCode(){return yt.projectionMercator}get vertexShaderPreludeCode(){return yt.projectionMercator.vertexSource}get subdivisionGranularity(){return t.SubdivisionGranularitySetting.noSubdivision}get useGlobeControls(){return !1}destroy(){}isRenderingDirty(){return !1}updateGPUdependent(e){}getMeshFromTileID(e,i,r,o,a){if(this._cachedMesh)return this._cachedMesh;const s=new t.PosArray;s.emplaceBack(0,0),s.emplaceBack(t.EXTENT,0),s.emplaceBack(0,t.EXTENT),s.emplaceBack(t.EXTENT,t.EXTENT);const n=e.createVertexBuffer(s,wt.members),l=t.SegmentVector.simpleSegment(0,0,4,2),c=new t.TriangleIndexArray;c.emplaceBack(1,0,2),c.emplaceBack(1,2,3);const h=e.createIndexBuffer(c);return this._cachedMesh=new bt(n,h,l),this._cachedMesh}}function It(e){return t.MercatorCoordinate.fromLngLat(e)}function Ct(e){return e&&e.toLngLat()}function Mt(e,i){const r=t.clamp(i.lat,-85.051129,ce);return new t.Point(t.mercatorXfromLng(i.lng)*e,t.mercatorYfromLat(r)*e)}function St(e,i){return new t.MercatorCoordinate(i.x/e,i.y/e).toLngLat()}function Rt(e){return e.cameraToCenterDistance*Math.min(.85*Math.tan(t.degreesToRadians(90-e.pitch)),Math.tan(t.degreesToRadians(89.25-e.pitch)))}function Dt(e,i){const r=e.canonical,o=i/ue(r.z),a=r.x+Math.pow(2,r.z)*e.wrap,s=t.identity(new Float64Array(16));return t.translate(s,s,[a*o,r.y*o,0]),t.scale(s,s,[o/t.EXTENT,o/t.EXTENT,1]),s}function zt(e,i,r,o,a){const s=t.MercatorCoordinate.fromLngLat(e,i),n=a*t.mercatorZfromAltitude(1,e.lat),l=n*Math.cos(t.degreesToRadians(r)),c=Math.sqrt(n*n-l*l),h=c*Math.sin(t.degreesToRadians(-o)),u=c*Math.cos(t.degreesToRadians(-o));return new t.MercatorCoordinate(s.x+h,s.y+u,s.z+l)}class Lt{constructor(e,i){this.min=e,this.max=i,this.center=t.scale$2([],t.add([],this.min,this.max),.5);}quadrant(e){const i=[e%2==0,e<2],r=t.clone(this.min),o=t.clone(this.max);for(let e=0;ethis.max[0]||e.aabb.min[1]>this.max[1]||e.aabb.min[2]>this.max[2]||e.aabb.max[0]0?(t+=e[r]*this.min[r],i+=e[r]*this.max[r]):(i+=e[r]*this.min[r],t+=e[r]*this.max[r]);return t>=0?2:i<0?0:1}}class At{distanceToTile2d(e,t,i,r){const o=r.distanceX([e,t]),a=r.distanceY([e,t]);return Math.hypot(o,a)}getWrap(e,t,i){return i}getTileAABB(e,i,r,o){var a,s;let n=r,l=r;if(o.terrain){const c=new t.OverscaledTileID(e.z,i,e.z,e.x,e.y),h=o.terrain.getMinMaxElevation(c);n=null!==(a=h.minElevation)&&void 0!==a?a:r,l=null!==(s=h.maxElevation)&&void 0!==s?s:r;}const c=1<o||e.padding.top>=.1}}class kt{constructor(e,t,i){this.points=e,this.planes=t,this.aabb=i;}static fromInvProjectionMatrix(e,i=1,r=0){const o=Math.pow(2,r),a=[[-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]].map((r=>{const a=1/(r=t.transformMat4([],r,e))[3]/i*o;return t.mul(r,r,[a,a,1/r[3],a])})),s=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map((e=>{const i=t.sub([],a[e[0]],a[e[1]]),r=t.sub([],a[e[2]],a[e[1]]),o=t.normalize([],t.cross([],i,r)),s=-t.dot(o,a[e[1]]);return o.concat(s)})),n=[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY],l=[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY];for(const e of a)for(let t=0;t<3;t++)n[t]=Math.min(n[t],e[t]),l[t]=Math.max(l[t],e[t]);return new kt(a,s,new Lt(n,l))}}class Ft{get pixelsToClipSpaceMatrix(){return this._helper.pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._helper.clipSpaceToPixelsMatrix}get pixelsToGLUnits(){return this._helper.pixelsToGLUnits}get centerOffset(){return this._helper.centerOffset}get size(){return this._helper.size}get rotationMatrix(){return this._helper.rotationMatrix}get centerPoint(){return this._helper.centerPoint}get pixelsPerMeter(){return this._helper.pixelsPerMeter}setMinZoom(e){this._helper.setMinZoom(e);}setMaxZoom(e){this._helper.setMaxZoom(e);}setMinPitch(e){this._helper.setMinPitch(e);}setMaxPitch(e){this._helper.setMaxPitch(e);}setRenderWorldCopies(e){this._helper.setRenderWorldCopies(e);}setBearing(e){this._helper.setBearing(e);}setPitch(e){this._helper.setPitch(e);}setRoll(e){this._helper.setRoll(e);}setFov(e){this._helper.setFov(e);}setZoom(e){this._helper.setZoom(e);}setCenter(e){this._helper.setCenter(e);}setElevation(e){this._helper.setElevation(e);}setMinElevationForCurrentTile(e){this._helper.setMinElevationForCurrentTile(e);}setPadding(e){this._helper.setPadding(e);}interpolatePadding(e,t,i){return this._helper.interpolatePadding(e,t,i)}isPaddingEqual(e){return this._helper.isPaddingEqual(e)}resize(e,t){this._helper.resize(e,t);}getMaxBounds(){return this._helper.getMaxBounds()}setMaxBounds(e){this._helper.setMaxBounds(e);}getCameraQueryGeometry(e){return this._helper.getCameraQueryGeometry(this.getCameraPoint(),e)}get tileSize(){return this._helper.tileSize}get tileZoom(){return this._helper.tileZoom}get scale(){return this._helper.scale}get worldSize(){return this._helper.worldSize}get width(){return this._helper.width}get height(){return this._helper.height}get lngRange(){return this._helper.lngRange}get latRange(){return this._helper.latRange}get minZoom(){return this._helper.minZoom}get maxZoom(){return this._helper.maxZoom}get zoom(){return this._helper.zoom}get center(){return this._helper.center}get minPitch(){return this._helper.minPitch}get maxPitch(){return this._helper.maxPitch}get pitch(){return this._helper.pitch}get pitchInRadians(){return this._helper.pitchInRadians}get roll(){return this._helper.roll}get rollInRadians(){return this._helper.rollInRadians}get bearing(){return this._helper.bearing}get bearingInRadians(){return this._helper.bearingInRadians}get fov(){return this._helper.fov}get fovInRadians(){return this._helper.fovInRadians}get elevation(){return this._helper.elevation}get minElevationForCurrentTile(){return this._helper.minElevationForCurrentTile}get padding(){return this._helper.padding}get unmodified(){return this._helper.unmodified}get renderWorldCopies(){return this._helper.renderWorldCopies}constructor(e,t,i,r,o){this._posMatrixCache=new Map,this._alignedPosMatrixCache=new Map,this._fogMatrixCacheF32=new Map,this._helper=new pe({calcMatrices:()=>{this._calcMatrices();},getConstrained:(e,t)=>this.getConstrained(e,t)},e,t,i,r,o),this._coveringTilesDetailsProvider=new At;}clone(){const e=new Ft;return e.apply(this),e}apply(e,t){this._helper.apply(e,t);}get cameraToCenterDistance(){return this._cameraToCenterDistance}get cameraPosition(){return this._cameraPosition}get projectionMatrix(){return this._projectionMatrix}get modelViewProjectionMatrix(){return this._viewProjMatrix}get inverseProjectionMatrix(){return this._invProjMatrix}get nearZ(){return this._nearZ}get farZ(){return this._farZ}get mercatorMatrix(){return this._mercatorMatrix}getVisibleUnwrappedCoordinates(e){const i=[new t.UnwrappedTileID(0,e)];if(this._helper._renderWorldCopies){const r=this.screenPointToMercatorCoordinate(new t.Point(0,0)),o=this.screenPointToMercatorCoordinate(new t.Point(this._helper._width,0)),a=this.screenPointToMercatorCoordinate(new t.Point(this._helper._width,this._helper._height)),s=this.screenPointToMercatorCoordinate(new t.Point(0,this._helper._height)),n=Math.floor(Math.min(r.x,o.x,a.x,s.x)),l=Math.floor(Math.max(r.x,o.x,a.x,s.x)),c=1;for(let r=n-c;r<=l+c;r++)0!==r&&i.push(new t.UnwrappedTileID(r,e));}return i}getCameraFrustum(){return kt.fromInvProjectionMatrix(this._invViewProjMatrix,this.worldSize)}getClippingPlane(){return null}getCoveringTilesDetailsProvider(){return this._coveringTilesDetailsProvider}recalculateZoomAndCenter(e){const i=this.screenPointToLocation(this.centerPoint,e),r=e?e.getElevationForLngLatZoom(i,this._helper._tileZoom):0;if(!(this.elevation-r))return;const o=t.mercatorZfromAltitude(1,this.center.lat)*this.worldSize,a=this._cameraToCenterDistance/o,s=t.MercatorCoordinate.fromLngLat(this.center,this.elevation),n=zt(this.center,this.elevation,this.pitch,this.bearing,a);this._helper._elevation=r;const l=this.calculateCenterFromCameraLngLatAlt(n.toLngLat(),t.altitudeFromMercatorZ(n.z,s.y),this.bearing,this.pitch);this._helper._elevation=l.elevation,this._helper._center=l.center,this.setZoom(l.zoom);}setLocationAtPoint(e,i){const r=t.mercatorZfromAltitude(this.elevation,this.center.lat),o=this.screenPointToMercatorCoordinateAtZ(i,r),a=this.screenPointToMercatorCoordinateAtZ(this.centerPoint,r),s=It(e),n=new t.MercatorCoordinate(s.x-(o.x-a.x),s.y-(o.y-a.y));this.setCenter(Ct(n)),this._helper._renderWorldCopies&&this.setCenter(this.center.wrap());}locationToScreenPoint(e,t){return t?this.coordinatePoint(It(e),t.getElevationForLngLatZoom(e,this._helper._tileZoom),this._pixelMatrix3D):this.coordinatePoint(It(e))}screenPointToLocation(e,t){return Ct(this.screenPointToMercatorCoordinate(e,t))}screenPointToMercatorCoordinate(e,t){if(t){const i=t.pointCoordinate(e);if(null!=i)return i}return this.screenPointToMercatorCoordinateAtZ(e)}screenPointToMercatorCoordinateAtZ(e,i){const r=i||0,o=[e.x,e.y,0,1],a=[e.x,e.y,1,1];t.transformMat4(o,o,this._pixelMatrixInverse),t.transformMat4(a,a,this._pixelMatrixInverse);const s=o[3],n=a[3],l=o[1]/s,c=a[1]/n,h=o[2]/s,u=a[2]/n,d=h===u?0:(r-h)/(u-h);return new t.MercatorCoordinate(t.interpolateFactory.number(o[0]/s,a[0]/n,d)/this.worldSize,t.interpolateFactory.number(l,c,d)/this.worldSize,r)}coordinatePoint(e,i=0,r=this._pixelMatrix){const o=[e.x*this.worldSize,e.y*this.worldSize,i,1];return t.transformMat4(o,o,r),new t.Point(o[0]/o[3],o[1]/o[3])}getBounds(){const e=Math.max(0,this._helper._height/2-Rt(this));return (new V).extend(this.screenPointToLocation(new t.Point(0,e))).extend(this.screenPointToLocation(new t.Point(this._helper._width,e))).extend(this.screenPointToLocation(new t.Point(this._helper._width,this._helper._height))).extend(this.screenPointToLocation(new t.Point(0,this._helper._height)))}isPointOnMapSurface(e,t){return t?null!=t.pointCoordinate(e):e.y>this.height/2-Rt(this)}calculatePosMatrix(e,i=!1,r){var o;const a=null!==(o=e.key)&&void 0!==o?o:t.calculateTileKey(e.wrap,e.canonical.z,e.canonical.z,e.canonical.x,e.canonical.y),s=i?this._alignedPosMatrixCache:this._posMatrixCache;if(s.has(a)){const e=s.get(a);return r?e.f32:e.f64}const n=Dt(e,this.worldSize);t.multiply(n,i?this._alignedProjMatrix:this._viewProjMatrix,n);const l={f64:n,f32:new Float32Array(n)};return s.set(a,l),r?l.f32:l.f64}calculateFogMatrix(e){const i=e.key,r=this._fogMatrixCacheF32;if(r.has(i))return r.get(i);const o=Dt(e,this.worldSize);return t.multiply(o,this._fogMatrix,o),r.set(i,new Float32Array(o)),r.get(i)}getConstrained(e,i){i=t.clamp(+i,this.minZoom,this.maxZoom);const r={center:new t.LngLat(e.lng,e.lat),zoom:i};let o=this._helper._lngRange;if(!this._helper._renderWorldCopies&&null===o){const e=180-1e-10;o=[-e,e];}const a=this.tileSize*ue(r.zoom);let s=0,n=a,l=0,c=a,h=0,u=0;const{x:d,y:_}=this.size;if(this._helper._latRange){const e=this._helper._latRange;s=t.mercatorYfromLat(e[1])*a,n=t.mercatorYfromLat(e[0])*a,n-s<_&&(h=_/(n-s));}o&&(l=t.wrap(t.mercatorXfromLng(o[0])*a,0,a),c=t.wrap(t.mercatorXfromLng(o[1])*a,0,a),cn&&(g=n-e);}if(o){const e=(l+c)/2;let i=p;this._helper._renderWorldCopies&&(i=t.wrap(p,e-a/2,e+a/2));const r=d/2;i-rc&&(f=c-r);}if(void 0!==f||void 0!==g){const e=new t.Point(null!=f?f:p,null!=g?g:m);r.center=St(a,e).wrap();}return r}calculateCenterFromCameraLngLatAlt(e,i,r,o){const a=void 0!==r?r:this.bearing,s=o=void 0!==o?o:this.pitch,n=t.MercatorCoordinate.fromLngLat(e,i),l=-Math.cos(t.degreesToRadians(s)),c=Math.sin(t.degreesToRadians(s)),h=c*Math.sin(t.degreesToRadians(a)),u=-c*Math.cos(t.degreesToRadians(a));let d=this.elevation;const _=i-d;let p;l*_>=0||Math.abs(l)<.1?(p=1e4,d=i+p*l):p=-_/l;let m,f,g=t.altitudeFromMercatorZ(1,n.y),v=0;do{if(v+=1,v>10)break;f=p/g,m=new t.MercatorCoordinate(n.x+h*f,n.y+u*f),g=1/m.meterInMercatorCoordinateUnits();}while(Math.abs(p-f*g)>1e-12);return {center:m.toLngLat(),elevation:d,zoom:de(this.height/2/Math.tan(this.fovInRadians/2)/f/this.tileSize)}}_calcMatrices(){if(!this._helper._height)return;const e=this.fovInRadians/2,i=this.centerOffset,r=Mt(this.worldSize,this.center),o=r.x,a=r.y;this._cameraToCenterDistance=.5/Math.tan(e)*this._helper._height,this._helper._pixelPerMeter=t.mercatorZfromAltitude(1,this.center.lat)*this.worldSize;const s=t.degreesToRadians(Math.min(this.pitch,89.25)),n=Math.max(this._cameraToCenterDistance/2,this._cameraToCenterDistance+this._helper._elevation*this._helper._pixelPerMeter/Math.cos(s)),l=Math.min(this.elevation,this.minElevationForCurrentTile,this.getCameraAltitude()-100),c=n-l*this._helper._pixelPerMeter/Math.cos(s),h=l<0?c:n,u=Math.PI/2+this.pitchInRadians,d=t.degreesToRadians(this.fov)*(Math.abs(Math.cos(t.degreesToRadians(this.roll)))*this.height+Math.abs(Math.sin(t.degreesToRadians(this.roll)))*this.width)/this.height*(.5+i.y/this.height),_=Math.sin(d)*h/Math.sin(t.clamp(Math.PI-u-d,.01,Math.PI-.01)),p=Rt(this),m=Math.atan(p/this._cameraToCenterDistance),f=t.degreesToRadians(.75),g=m>f?2*m*(.5+i.y/(2*p)):f,v=Math.sin(g)*h/Math.sin(t.clamp(Math.PI-u-g,.01,Math.PI-.01)),y=Math.min(_,v);let x;this._farZ=1.01*(Math.cos(Math.PI/2-s)*y+h),this._nearZ=this._helper._height/50,x=new Float64Array(16),t.perspective(x,this.fovInRadians,this._helper._width/this._helper._height,this._nearZ,this._farZ),this._invProjMatrix=new Float64Array(16),t.invert(this._invProjMatrix,x),x[8]=2*-i.x/this._helper._width,x[9]=2*i.y/this._helper._height,this._projectionMatrix=t.clone$1(x),t.scale(x,x,[1,-1,1]),t.translate(x,x,[0,0,-this._cameraToCenterDistance]),t.rotateZ(x,x,-this.rollInRadians),t.rotateX(x,x,this.pitchInRadians),t.rotateZ(x,x,-this.bearingInRadians),t.translate(x,x,[-o,-a,0]),this._mercatorMatrix=t.scale([],x,[this.worldSize,this.worldSize,this.worldSize]),t.scale(x,x,[1,1,this._helper._pixelPerMeter]),this._pixelMatrix=t.multiply(new Float64Array(16),this.clipSpaceToPixelsMatrix,x),t.translate(x,x,[0,0,-this.elevation]),this._viewProjMatrix=x,this._invViewProjMatrix=t.invert([],x);const b=[0,0,-1,1];t.transformMat4(b,b,this._invViewProjMatrix),this._cameraPosition=[b[0]/b[3],b[1]/b[3],b[2]/b[3]],this._fogMatrix=new Float64Array(16),t.perspective(this._fogMatrix,this.fovInRadians,this.width/this.height,n,this._farZ),this._fogMatrix[8]=2*-i.x/this.width,this._fogMatrix[9]=2*i.y/this.height,t.scale(this._fogMatrix,this._fogMatrix,[1,-1,1]),t.translate(this._fogMatrix,this._fogMatrix,[0,0,-this.cameraToCenterDistance]),t.rotateZ(this._fogMatrix,this._fogMatrix,-this.rollInRadians),t.rotateX(this._fogMatrix,this._fogMatrix,this.pitchInRadians),t.rotateZ(this._fogMatrix,this._fogMatrix,-this.bearingInRadians),t.translate(this._fogMatrix,this._fogMatrix,[-o,-a,0]),t.scale(this._fogMatrix,this._fogMatrix,[1,1,this._helper._pixelPerMeter]),t.translate(this._fogMatrix,this._fogMatrix,[0,0,-this.elevation]),this._pixelMatrix3D=t.multiply(new Float64Array(16),this.clipSpaceToPixelsMatrix,x);const w=this._helper._width%2/2,T=this._helper._height%2/2,E=Math.cos(this.bearingInRadians),P=Math.sin(-this.bearingInRadians),I=o-Math.round(o)+E*w+P*T,C=a-Math.round(a)+E*T+P*w,M=new Float64Array(x);if(t.translate(M,M,[I>.5?I-1:I,C>.5?C-1:C,0]),this._alignedProjMatrix=M,x=t.invert(new Float64Array(16),this._pixelMatrix),!x)throw new Error("failed to invert matrix");this._pixelMatrixInverse=x,this._clearMatrixCaches();}_clearMatrixCaches(){this._posMatrixCache.clear(),this._alignedPosMatrixCache.clear(),this._fogMatrixCacheF32.clear();}maxPitchScaleFactor(){if(!this._pixelMatrixInverse)return 1;const e=this.screenPointToMercatorCoordinate(new t.Point(0,0)),i=[e.x*this.worldSize,e.y*this.worldSize,0,1];return t.transformMat4(i,i,this._pixelMatrix)[3]/this._cameraToCenterDistance}getCameraPoint(){const e=Math.tan(this.pitchInRadians)*(this._cameraToCenterDistance||1);return this.centerPoint.add(new t.Point(e*Math.sin(this.rollInRadians),e*Math.cos(this.rollInRadians)))}getCameraAltitude(){return Math.cos(this.pitchInRadians)*this._cameraToCenterDistance/this._helper._pixelPerMeter+this.elevation}getCameraLngLat(){const e=.5/Math.tan(this.fovInRadians/2)*this.height,i=t.mercatorZfromAltitude(1,this.center.lat)*this.worldSize;return zt(this.center,this.elevation,this.pitch,this.bearing,e/i).toLngLat()}lngLatToCameraDepth(e,i){const r=It(e),o=[r.x*this.worldSize,r.y*this.worldSize,i,1];return t.transformMat4(o,o,this._viewProjMatrix),o[2]/o[3]}isRenderingDirty(){return !1}getProjectionData(e){const{overscaledTileID:i,aligned:r,applyTerrainMatrix:o}=e;return function(e,i,r=!0){let o,a;if(e){const i=e.canonical.z>=0?1<{if(d&&e.setZoom(t.interpolateFactory.number(r,g,h)),t.equals(a,c)||Ot(a,c,{roll:s,pitch:n,bearing:l},e,h),u&&(e.interpolatePadding(o,i.padding,h),p=e.centerPoint.add(i.offsetAsPoint)),i.around)e.setLocationAtPoint(i.around,i.aroundPoint);else {const t=ue(e.zoom-r),i=g>r?Math.min(2,x):Math.max(.5,x),o=Math.pow(i,1-h),a=St(e.worldSize,v.add(y.mult(h*o)).mult(t));e.setLocationAtPoint(e.renderWorldCopies?a.wrap():a,p);}},isZooming:d,elevationCenter:f}}handleFlyTo(e,i){const r=void 0!==i.zoom,o=e.zoom,a=e.getConstrained(t.LngLat.convert(i.center||i.locationAtOffset),r?+i.zoom:o),s=a.center,n=a.zoom;he(e,s);const l=Mt(e.worldSize,i.locationAtOffset),c=Mt(e.worldSize,s).sub(l),h=c.mag(),u=ue(n-o);let d;if(void 0!==i.minZoom){const t=Math.min(+i.minZoom,o,n);d=ue(e.getConstrained(s,t).zoom-o);}return {easeFunc:(t,i,r,a)=>{e.setZoom(1===t?n:o+de(i));const h=1===t?s:St(e.worldSize,l.add(c.mult(r)).mult(i));e.setLocationAtPoint(e.renderWorldCopies?h.wrap():h,a);},scaleOfZoom:u,targetCenter:s,scaleOfMinZoom:d,pixelPathLength:h}}}class jt{constructor(e,t,i){this.blendFunction=e,this.blendColor=t,this.mask=i;}}jt.Replace=[1,0],jt.disabled=new jt(jt.Replace,t.Color.transparent,[!1,!1,!1,!1]),jt.unblended=new jt(jt.Replace,t.Color.transparent,[!0,!0,!0,!0]),jt.alphaBlended=new jt([1,771],t.Color.transparent,[!0,!0,!0,!0]);const Nt=2305;class Gt{constructor(e,t,i){this.enable=e,this.mode=t,this.frontFace=i;}}Gt.disabled=new Gt(!1,1029,Nt),Gt.backCCW=new Gt(!0,1029,Nt),Gt.frontCCW=new Gt(!0,1028,Nt);class Zt{constructor(e,t,i){this.func=e,this.mask=t,this.range=i;}}Zt.ReadOnly=!1,Zt.ReadWrite=!0,Zt.disabled=new Zt(519,Zt.ReadOnly,[0,1]);const Vt=7680;class qt{constructor(e,t,i,r,o,a){this.test=e,this.ref=t,this.mask=i,this.fail=r,this.depthFail=o,this.pass=a;}}qt.disabled=new qt({func:519,mask:0},0,0,Vt,Vt,Vt);const Wt=new WeakMap;function Xt(e){var t;if(Wt.has(e))return Wt.get(e);{const i=null===(t=e.getParameter(e.VERSION))||void 0===t?void 0:t.startsWith("WebGL 2.0");return Wt.set(e,i),i}}class $t{get awaitingQuery(){return !!this._readbackQueue}constructor(e){this._readbackWaitFrames=4,this._measureWaitFrames=6,this._texWidth=1,this._texHeight=1,this._measuredError=0,this._updateCount=0,this._lastReadbackFrame=-1e3,this._readbackQueue=null,this._cachedRenderContext=e;const i=e.context,r=i.gl;this._texFormat=r.RGBA,this._texType=r.UNSIGNED_BYTE;const o=new t.PosArray;o.emplaceBack(-1,-1),o.emplaceBack(2,-1),o.emplaceBack(-1,2);const a=new t.TriangleIndexArray;a.emplaceBack(0,1,2),this._fullscreenTriangle=new bt(i.createVertexBuffer(o,wt.members),i.createIndexBuffer(a),t.SegmentVector.simpleSegment(0,0,o.length,a.length)),this._resultBuffer=new Uint8Array(4),i.activeTexture.set(r.TEXTURE1);const s=r.createTexture();r.bindTexture(r.TEXTURE_2D,s),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.NEAREST),r.texImage2D(r.TEXTURE_2D,0,this._texFormat,this._texWidth,this._texHeight,0,this._texFormat,this._texType,null),this._fbo=i.createFramebuffer(this._texWidth,this._texHeight,!1,!1),this._fbo.colorAttachment.set(s),Xt(r)&&(this._pbo=r.createBuffer(),r.bindBuffer(r.PIXEL_PACK_BUFFER,this._pbo),r.bufferData(r.PIXEL_PACK_BUFFER,4,r.STREAM_READ),r.bindBuffer(r.PIXEL_PACK_BUFFER,null));}destroy(){const e=this._cachedRenderContext.context.gl;this._fullscreenTriangle.destroy(),this._fbo.destroy(),e.deleteBuffer(this._pbo),this._fullscreenTriangle=null,this._fbo=null,this._pbo=null,this._resultBuffer=null;}updateErrorLoop(e,t){const i=this._updateCount;return this._readbackQueue?i>=this._readbackQueue.frameNumberIssued+this._readbackWaitFrames&&this._tryReadback():i>=this._lastReadbackFrame+this._measureWaitFrames&&this._renderErrorTexture(e,t),this._updateCount++,this._measuredError}_bindFramebuffer(){const e=this._cachedRenderContext.context,t=e.gl;e.activeTexture.set(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this._fbo.colorAttachment.get()),e.bindFramebuffer.set(this._fbo.framebuffer);}_renderErrorTexture(e,i){const r=this._cachedRenderContext.context,o=r.gl;if(this._bindFramebuffer(),r.viewport.set([0,0,this._texWidth,this._texHeight]),r.clear({color:t.Color.transparent}),this._cachedRenderContext.useProgram("projectionErrorMeasurement").draw(r,o.TRIANGLES,Zt.disabled,qt.disabled,jt.unblended,Gt.disabled,((e,t)=>({u_input:e,u_output_expected:t}))(e,i),null,null,"$clipping",this._fullscreenTriangle.vertexBuffer,this._fullscreenTriangle.indexBuffer,this._fullscreenTriangle.segments),this._pbo&&Xt(o)){o.bindBuffer(o.PIXEL_PACK_BUFFER,this._pbo),o.readBuffer(o.COLOR_ATTACHMENT0),o.readPixels(0,0,this._texWidth,this._texHeight,this._texFormat,this._texType,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null);const e=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0);o.flush(),this._readbackQueue={frameNumberIssued:this._updateCount,sync:e};}else this._readbackQueue={frameNumberIssued:this._updateCount,sync:null};}_tryReadback(){const e=this._cachedRenderContext.context.gl;if(this._pbo&&this._readbackQueue&&Xt(e)){const i=e.clientWaitSync(this._readbackQueue.sync,0,0);if(i===e.WAIT_FAILED)return t.warnOnce("WebGL2 clientWaitSync failed."),this._readbackQueue=null,void(this._lastReadbackFrame=this._updateCount);if(i===e.TIMEOUT_EXPIRED)return;e.bindBuffer(e.PIXEL_PACK_BUFFER,this._pbo),e.getBufferSubData(e.PIXEL_PACK_BUFFER,0,this._resultBuffer,0,4),e.bindBuffer(e.PIXEL_PACK_BUFFER,null);}else this._bindFramebuffer(),e.readPixels(0,0,this._texWidth,this._texHeight,this._texFormat,this._texType,this._resultBuffer);this._readbackQueue=null,this._measuredError=$t._parseRGBA8float(this._resultBuffer),this._lastReadbackFrame=this._updateCount;}static _parseRGBA8float(e){let t=0;return t+=e[0]/256,t+=e[1]/65536,t+=e[2]/16777216,e[3]<127&&(t=-t),t/128}}const Ht=t.EXTENT/128;function Kt(e,i){const r=void 0!==e.granularity?Math.max(e.granularity,1):1,o=r+(e.generateBorders?2:0),a=r+(e.extendToNorthPole||e.generateBorders?1:0)+(e.extendToSouthPole||e.generateBorders?1:0),s=o+1,n=a+1,l=e.generateBorders?-1:0,c=e.generateBorders||e.extendToNorthPole?-1:0,h=r+(e.generateBorders?1:0),u=r+(e.generateBorders||e.extendToSouthPole?1:0),d=s*n,_=o*a*6,p=s*n>65536;if(p&&"16bit"===i)throw new Error("Granularity is too large and meshes would not fit inside 16 bit vertex indices.");const m=p||"32bit"===i,f=new Int16Array(2*d);let g;g=m?{vertices:f,indices:new Uint32Array(_),uses32bitIndices:!0}:{vertices:f,indices:new Uint16Array(_),uses32bitIndices:!1};const v=g.indices;let y=0;for(let i=c;i<=u;i++)for(let o=l;o<=h;o++){let a=o/r*t.EXTENT;-1===o&&(a=-Ht),o===r+1&&(a=t.EXTENT+Ht);let s=i/r*t.EXTENT;-1===i&&(s=e.extendToNorthPole?t.NORTH_POLE_Y:-Ht),i===r+1&&(s=e.extendToSouthPole?t.SOUTH_POLE_Y:t.EXTENT+Ht),f[y++]=a,f[y++]=s;}let x=0;for(let e=0;e1e-6){const o=e[0]/r,a=Math.acos(e[2]/r),s=(o>0?a:-a)/Math.PI*180;return new t.LngLat(t.wrap(s,-180,180),i)}return new t.LngLat(0,i)}function oi(e){return Math.cos(e*Math.PI/180)}function ai(e,t){const i=oi(e);return de(oi(t)/i)}function si(e,i){const r=e.rotate(i.bearingInRadians),o=i.zoom+ai(i.center.lat,0),a=t.lerp(1/oi(i.center.lat),1/oi(Math.min(Math.abs(i.center.lat),60)),t.remapSaturate(o,7,3,0,1)),s=360/Qt({worldSize:i.worldSize,center:{lat:i.center.lat}});return new t.LngLat(i.center.lng-r.x*s*a,t.clamp(i.center.lat+r.y*s,-85.051129,ce))}function ni(e){const t=.5*e,i=Math.sin(t),r=Math.cos(t);return Math.log(i+r)-Math.log(r-i)}function li(e,i,r,o){const a=e.lat+r*o;if(Math.abs(r)>1){const s=(Math.sign(e.lat+r)!==Math.sign(e.lat)?-Math.abs(e.lat):Math.abs(e.lat))*Math.PI/180,n=Math.abs(e.lat+r)*Math.PI/180,l=ni(s+o*(n-s)),c=ni(s),h=ni(n);return new t.LngLat(e.lng+i*((l-c)/(h-c)),a)}return new t.LngLat(e.lng+i*o,a)}class ci{constructor(e){this._cachePrevious=new Map,this._cache=new Map,this._hadAnyChanges=!1,this._aabbFactory=e;}newFrame(){if(!this._hadAnyChanges)return;const e=this._cachePrevious;this._cachePrevious=this._cache,this._cache=e,this._cache.clear(),this._hadAnyChanges=!1;}getTileAABB(e,t,i,r){const o=`${e.z}_${e.x}_${e.y}`,a=this._cache.get(o);if(a)return a;const s=this._cachePrevious.get(o);if(s)return this._cache.set(o,s),s;const n=this._aabbFactory(e,t,i,r);return this._cache.set(o,n),this._hadAnyChanges=!0,n}}function hi(e,t,i){const r=e-t;return r<0?-r:Math.max(0,r-i)}function ui(e,t,i,r,o){const a=e-i;let s;return s=a<0?Math.min(-a,1+a-o):a>1?Math.min(Math.max(a-o,0),1-a):0,Math.max(s,hi(t,r,o))}class di{constructor(){this._aabbCache=new ci(this._computeTileAABB);}newFrame(){this._aabbCache.newFrame();}distanceToTile2d(e,t,i,r){const o=1<4}getTileAABB(e,t,i,r){return this._aabbCache.getTileAABB(e,t,i,r)}_computeTileAABB(e,i,r,o){if(e.z<=0)return new Lt([-1,-1,-1],[1,1,1]);if(1===e.z)return new Lt([0===e.x?-1:0,0===e.y?0:-1,-1],[0===e.x?0:1,0===e.y?1:0,1]);{const i=[ei(0,0,e.x,e.y,e.z),ei(t.EXTENT,0,e.x,e.y,e.z),ei(t.EXTENT,t.EXTENT,e.x,e.y,e.z),ei(0,t.EXTENT,e.x,e.y,e.z)],r=[1,1,1],o=[-1,-1,-1];for(const e of i)for(let t=0;t<3;t++)r[t]=Math.min(r[t],e[t]),o[t]=Math.max(o[t],e[t]);if(0===e.y||e.y===(1<0}constructor(e,i=!0,r=!0){this._cachedClippingPlane=t.createVec4f64(),this._lastGlobeStateEnabled=!0,this._lastUpdateTimeSeconds=f.now()/1e3,this._lastGlobeChangeTimeSeconds=f.now()/1e3-10,this._skipNextAnimation=!0,this._projectionMatrix=t.createIdentityMat4f64(),this._globeViewProjMatrix32f=t.createIdentityMat4f32(),this._globeViewProjMatrixNoCorrection=t.createIdentityMat4f64(),this._globeViewProjMatrixNoCorrectionInverted=t.createIdentityMat4f64(),this._globeProjMatrixInverted=t.createIdentityMat4f64(),this._cameraPosition=t.createVec3f64(),this._globeProjectionAllowed=!0,this._globeLatitudeErrorCorrectionRadians=0,this._globeness=1,this._adaptive=r,this._helper=new pe({calcMatrices:()=>{this._calcMatrices();},getConstrained:(e,t)=>this.getConstrained(e,t)}),this._globeProjectionAllowed=i,this._globeness=i?1:0,this._projectionInstance=e,this._mercatorTransform=new Ft,this._coveringTilesDetailsProvider=new di;}clone(){const e=new _i(null,this._globeProjectionAllowed);return e._applyGlobeTransform(this),e.apply(this),e}apply(e){this._helper.apply(e),this._mercatorTransform.apply(this);}_applyGlobeTransform(e){this._globeness=e._globeness,this._globeLatitudeErrorCorrectionRadians=e._globeLatitudeErrorCorrectionRadians;}get projectionMatrix(){return this.isGlobeRendering?this._projectionMatrix:this._mercatorTransform.projectionMatrix}get modelViewProjectionMatrix(){return this.isGlobeRendering?this._globeViewProjMatrixNoCorrection:this._mercatorTransform.modelViewProjectionMatrix}get inverseProjectionMatrix(){return this.isGlobeRendering?this._globeProjMatrixInverted:this._mercatorTransform.inverseProjectionMatrix}get cameraPosition(){const e=t.createVec3f64();return e[0]=this._cameraPosition[0],e[1]=this._cameraPosition[1],e[2]=this._cameraPosition[2],e}get cameraToCenterDistance(){return this._mercatorTransform.cameraToCenterDistance}get nearZ(){return this._nearZ}get farZ(){return this._farZ}getGlobeViewAllowed(){return this._globeProjectionAllowed}setGlobeViewAllowed(e,t=!0){e!==this._globeProjectionAllowed&&(t||(this._skipNextAnimation=!0),this._globeProjectionAllowed=e,this._lastGlobeChangeTimeSeconds=this._lastUpdateTimeSeconds);}newFrameUpdate(){this._lastUpdateTimeSeconds=f.now()/1e3;const e=this.isGlobeRendering;return this._globeness=!this._adaptive&&this._globeProjectionAllowed?1:this._computeGlobenessAnimation(),this._updateErrorCorrectionValue(),this._calcMatrices(),this._coveringTilesDetailsProvider.newFrame(),e===this.isGlobeRendering?{forcePlacementUpdate:!1}:{forcePlacementUpdate:!0,fireProjectionEvent:{type:"projectiontransition",newProjection:this.isGlobeRendering?"globe":"globe-mercator"},forceSourceUpdate:!0}}_updateErrorCorrectionValue(){this._projectionInstance&&(this._projectionInstance.useGlobeRendering=this.isGlobeRendering,this._projectionInstance.errorQueryLatitudeDegrees=this.center.lat,this._globeLatitudeErrorCorrectionRadians=this._projectionInstance.latitudeErrorCorrectionRadians);}_computeGlobenessAnimation(){const e=this._globeProjectionAllowed&&this.zoom<12,i=this._lastUpdateTimeSeconds;e!==this._lastGlobeStateEnabled&&(this._lastGlobeChangeTimeSeconds=i,this._lastGlobeStateEnabled=e);const r=this._globeness,o=Math.min(Math.max((i-this._lastGlobeChangeTimeSeconds)/.5,0),1);let a=e?o:1-o;return this._skipNextAnimation&&(a=e?1:0,this._lastGlobeChangeTimeSeconds=i-1,this._skipNextAnimation=!1),a=t.easeCubicInOut(a),r!==a&&(this.setCenter(new t.LngLat(this._mercatorTransform.center.lng+t.differenceOfAnglesDegrees(this._mercatorTransform.center.lng,this.center.lng)*a,t.lerp(this._mercatorTransform.center.lat,this.center.lat,a))),this.setZoom(t.lerp(this._mercatorTransform.zoom,this.zoom,a))),a}isRenderingDirty(){return this._lastUpdateTimeSeconds-this._lastGlobeChangeTimeSeconds<.5}getProjectionData(e){const{overscaledTileID:t,aligned:i,applyTerrainMatrix:r,applyGlobeMatrix:o}=e,a=this._mercatorTransform.getProjectionData({overscaledTileID:t,aligned:i,applyTerrainMatrix:r});return this.isGlobeRendering&&(a.mainMatrix=this._globeViewProjMatrix32f),a.clippingPlane=this._cachedClippingPlane,a.projectionTransition=o?this._globeness:0,a}_computeClippingPlane(e){const i=this.pitchInRadians,r=this.cameraToCenterDistance/e,o=Math.sin(i)*r,a=Math.cos(i)*r+1,s=1/Math.sqrt(o*o+a*a)*1;let n=-o,l=a;const c=Math.sqrt(n*n+l*l);n/=c,l/=c;const h=[0,n,l];return t.rotateZ$1(h,h,[0,0,0],-this.bearingInRadians),t.rotateX$1(h,h,[0,0,0],-1*this.center.lat*Math.PI/180),t.rotateY(h,h,[0,0,0],this.center.lng*Math.PI/180),t.scale$2(h,h,.25),[...h,.25*-s]}isLocationOccluded(e){return !this.isSurfacePointVisible(ti(e))}transformLightDirection(e){const i=this._helper._center.lng*Math.PI/180,r=this._helper._center.lat*Math.PI/180,o=Math.cos(r),a=[Math.sin(i)*o,Math.sin(r),Math.cos(i)*o],s=[a[2],0,-a[0]],n=[0,0,0];t.cross(n,s,a),t.normalize(s,s),t.normalize(n,n);const l=[0,0,0];return t.normalize(l,[s[0]*e[0]+n[0]*e[1]+a[0]*e[2],s[1]*e[0]+n[1]*e[1]+a[1]*e[2],s[2]*e[0]+n[2]*e[1]+a[2]*e[2]]),l}getAnimatedLatitude(){return t.lerp(this._mercatorTransform.center.lat,this._helper._center.lat,this._globeness)}getPixelScale(){return t.lerp(this._mercatorTransform.getPixelScale(),1/Math.cos(this.getAnimatedLatitude()*Math.PI/180),this._globeness)}getCircleRadiusCorrection(){return t.lerp(this._mercatorTransform.getCircleRadiusCorrection(),Math.cos(this.getAnimatedLatitude()*Math.PI/180),this._globeness)}getPitchedTextCorrection(e,i,r){const o=this._mercatorTransform.getPitchedTextCorrection(e,i,r);if(!this.isGlobeRendering)return o;const a=function(e,i,r){const o=1/(1<a&&(a=i),rn&&(n=r);}const h=[c.lng+s,c.lat+l,c.lng+a,c.lat+n];return this.isSurfacePointOnScreen([0,1,0])&&(h[3]=90,h[0]=-180,h[2]=180),this.isSurfacePointOnScreen([0,-1,0])&&(h[1]=-90,h[0]=-180,h[2]=180),new V(h)}getConstrained(e,i){const r=t.clamp(e.lat,-85.051129,ce),o=t.clamp(+i,this.minZoom+ai(0,r),this.maxZoom);return {center:new t.LngLat(e.lng,r),zoom:o}}calculateCenterFromCameraLngLatAlt(e,t,i,r){return this._mercatorTransform.calculateCenterFromCameraLngLatAlt(e,t,i,r)}setLocationAtPoint(e,i){if(!this.isGlobeRendering)return this._mercatorTransform.setLocationAtPoint(e,i),void this.apply(this._mercatorTransform);const r=ti(this.unprojectScreenPoint(i)),o=ti(e),a=t.createVec3f64();t.zero$1(a);const s=t.createVec3f64();t.rotateY(s,r,a,-this.center.lng*Math.PI/180),t.rotateX$1(s,s,a,this.center.lat*Math.PI/180);const n=o[0]*o[0]+o[2]*o[2],l=s[0]*s[0];if(n=-g&&p<=g,y=f>=-g&&f<=g;let x,b;if(v&&y){const e=this.center.lng*Math.PI/180,i=this.center.lat*Math.PI/180;t.distanceOfAnglesRadians(u,e)+t.distanceOfAnglesRadians(p,i)=0}isSurfacePointOnScreen(e){if(!this.isSurfacePointVisible(e))return !1;const i=t.createVec4f64();return t.transformMat4(i,[...e,1],this._globeViewProjMatrixNoCorrection),i[0]/=i[3],i[1]/=i[3],i[2]/=i[3],i[0]>-1&&i[0]<1&&i[1]>-1&&i[1]<1&&i[2]>-1&&i[2]<1}rayPlanetIntersection(e,i){const r=t.dot(e,i),o=t.createVec3f64(),a=t.createVec3f64();t.scale$2(a,i,r),t.sub(o,e,a);const s=1-t.dot(o,o);if(s<0)return null;const n=t.dot(e,e)-1,l=-r+(r<0?1:-1)*Math.sqrt(s),c=n/l,h=l;return {tMin:Math.min(c,h),tMax:Math.max(c,h)}}unprojectScreenPoint(e){const i=this._cameraPosition,r=this.getRayDirectionFromPixel(e),o=this.rayPlanetIntersection(i,r);if(o){const e=t.createVec3f64();t.add(e,i,[r[0]*o.tMin,r[1]*o.tMin,r[2]*o.tMin]);const a=t.createVec3f64();return t.normalize(a,e),ri(a)}const a=this._cachedClippingPlane[0]*r[0]+this._cachedClippingPlane[1]*r[1]+this._cachedClippingPlane[2]*r[2],s=-t.pointPlaneSignedDistance(this._cachedClippingPlane,i)/a,n=t.createVec3f64();if(s>0)t.add(n,i,[r[0]*s,r[1]*s,r[2]*s]);else {const e=t.createVec3f64();t.add(e,i,[2*r[0],2*r[1],2*r[2]]);const o=t.pointPlaneSignedDistance(this._cachedClippingPlane,e);t.sub(n,e,[this._cachedClippingPlane[0]*o,this._cachedClippingPlane[1]*o,this._cachedClippingPlane[2]*o]);}const l=t.createVec3f64();return t.normalize(l,n),ri(l)}getMatrixForModel(e,i){if(!this.isGlobeRendering)return this._mercatorTransform.getMatrixForModel(e,i);const r=t.LngLat.convert(e),o=1/t.earthRadius,a=t.createIdentityMat4f64();return t.rotateY$1(a,a,r.lng/180*Math.PI),t.rotateX(a,a,-r.lat/180*Math.PI),t.translate(a,a,[0,0,1+i/t.earthRadius]),t.rotateX(a,a,.5*Math.PI),t.scale(a,a,[o,o,o]),a}getProjectionDataForCustomLayer(e=!0){const i=this.getProjectionData({overscaledTileID:new t.OverscaledTileID(0,0,0,0,0),applyGlobeMatrix:e});i.tileMercatorCoords=[0,0,1,1];const r=t.createMat4f32();return t.scale(r,i.fallbackMatrix,[t.EXTENT,t.EXTENT,1]),i.fallbackMatrix=r,i}getFastPathSimpleProjectionMatrix(e){if(!this.isGlobeRendering)return this._mercatorTransform.getFastPathSimpleProjectionMatrix(e)}}class pi{constructor(e){this._globe=e,this._mercatorCameraHelper=new Ut;}get useGlobeControls(){return this._globe.useGlobeRendering}handlePanInertia(e,i){if(!this.useGlobeControls)return this._mercatorCameraHelper.handlePanInertia(e,i);const r=si(e,i);return Math.abs(r.lng-i.center.lng)>180&&(r.lng=i.center.lng+179.5*Math.sign(r.lng-i.center.lng)),{easingCenter:r,easingOffset:new t.Point(0,0)}}handleMapControlsRollPitchBearingZoom(e,i){if(!this.useGlobeControls)return void this._mercatorCameraHelper.handleMapControlsRollPitchBearingZoom(e,i);const r=e.around,o=i.screenPointToLocation(r);e.bearingDelta&&i.setBearing(i.bearing+e.bearingDelta),e.pitchDelta&&i.setPitch(i.pitch+e.pitchDelta),e.rollDelta&&i.setRoll(i.roll+e.rollDelta);const a=i.zoom;e.zoomDelta&&i.setZoom(i.zoom+e.zoomDelta);const s=i.zoom-a;if(0===s)return;const n=t.differenceOfAnglesDegrees(i.center.lng,o.lng),l=n/(Math.abs(n/180)+1),c=t.differenceOfAnglesDegrees(i.center.lat,o.lat),h=i.getRayDirectionFromPixel(r),u=i.cameraPosition,d=-1*t.dot(u,h),_=t.createVec3f64();t.add(_,u,[h[0]*d,h[1]*d,h[2]*d]);const p=t.length$1(_)-1,m=Math.exp(.5*-Math.max(p-.3,0)),f=ii(i.worldSize,i.center.lat)/Math.min(i.width,i.height),g=t.remapSaturate(f,.9,.5,1,.25),v=(1-ue(-s))*Math.min(m,g),y=i.center.lat,x=i.zoom,b=new t.LngLat(i.center.lng+l*v,t.clamp(i.center.lat+c*v,-85.051129,ce));i.setLocationAtPoint(o,r);const w=i.center,T=t.remapSaturate(Math.abs(n),45,85,0,1),E=t.remapSaturate(f,.75,.35,0,1),P=Math.pow(Math.max(T,E),.25),I=t.differenceOfAnglesDegrees(w.lng,b.lng),C=t.differenceOfAnglesDegrees(w.lat,b.lat);i.setCenter(new t.LngLat(w.lng+I*P,w.lat+C*P).wrap()),i.setZoom(x+ai(y,i.center.lat));}handleMapControlsPan(e,t,i){if(!this.useGlobeControls)return void this._mercatorCameraHelper.handleMapControlsPan(e,t,i);if(!e.panDelta)return;const r=t.center.lat,o=t.zoom;t.setCenter(si(e.panDelta,t).wrap()),t.setZoom(o+ai(r,t.center.lat));}cameraForBoxAndBearing(e,i,r,o,a){const s=this._mercatorCameraHelper.cameraForBoxAndBearing(e,i,r,o,a);if(!this.useGlobeControls)return s;const n=i.left/a.width*2-1,l=(a.width-i.right)/a.width*2-1,c=i.top/a.height*-2+1,h=(a.height-i.bottom)/a.height*-2+1,u=t.differenceOfAnglesDegrees(r.getWest(),r.getEast())<0,d=u?r.getEast():r.getWest(),_=u?r.getWest():r.getEast(),p=Math.max(r.getNorth(),r.getSouth()),m=Math.min(r.getNorth(),r.getSouth()),f=d+.5*t.differenceOfAnglesDegrees(d,_),g=p+.5*t.differenceOfAnglesDegrees(p,m),v=a.clone();v.setCenter(s.center),v.setBearing(s.bearing),v.setPitch(0),v.setRoll(0),v.setZoom(s.zoom);const y=v.modelViewProjectionMatrix,x=[ti(r.getNorthWest()),ti(r.getNorthEast()),ti(r.getSouthWest()),ti(r.getSouthEast()),ti(new t.LngLat(_,g)),ti(new t.LngLat(d,g)),ti(new t.LngLat(f,p)),ti(new t.LngLat(f,m))],b=ti(s.center);let w=Number.POSITIVE_INFINITY;for(const e of x)n<0&&(w=pi.getLesserNonNegativeNonNull(w,pi.solveVectorScale(e,b,y,"x",n))),l>0&&(w=pi.getLesserNonNegativeNonNull(w,pi.solveVectorScale(e,b,y,"x",l))),c>0&&(w=pi.getLesserNonNegativeNonNull(w,pi.solveVectorScale(e,b,y,"y",c))),h<0&&(w=pi.getLesserNonNegativeNonNull(w,pi.solveVectorScale(e,b,y,"y",h)));if(Number.isFinite(w)&&0!==w)return s.zoom=v.zoom+de(w),s;Bt();}handleJumpToCenterZoom(e,i){if(!this.useGlobeControls)return void this._mercatorCameraHelper.handleJumpToCenterZoom(e,i);const r=e.center.lat,o=e.getConstrained(i.center?t.LngLat.convert(i.center):e.center,e.zoom).center;e.setCenter(o.wrap());const a=void 0!==i.zoom?+i.zoom:e.zoom+ai(r,o.lat);e.zoom!==a&&e.setZoom(a);}handleEaseTo(e,i){if(!this.useGlobeControls)return this._mercatorCameraHelper.handleEaseTo(e,i);const r=e.zoom,o=e.center,a=t.rollPitchBearingToQuat(e.roll,e.pitch,e.bearing),s=void 0===i.roll?e.roll:i.roll,n=void 0===i.pitch?e.pitch:i.pitch,l=void 0===i.bearing?e.bearing:i.bearing,c=t.rollPitchBearingToQuat(s,n,l),h=void 0!==i.zoom,u=!e.isPaddingEqual(i.padding);let d=!1;const _=i.center?t.LngLat.convert(i.center):o,p=e.getConstrained(_,r).center;he(e,p);const m=e.clone();m.setCenter(p),u&&m.setPadding(i.padding),m.setZoom(h?+i.zoom:r+ai(o.lat,_.lat)),m.setBearing(i.bearing);const f=new t.Point(t.clamp(e.centerPoint.x+i.offsetAsPoint.x,0,e.width),t.clamp(e.centerPoint.y+i.offsetAsPoint.y,0,e.height));m.setLocationAtPoint(p,f);const g=(i.offset&&i.offsetAsPoint.mag())>0?m.center:p,v=h?+i.zoom:r+ai(o.lat,g.lat),y=r+ai(o.lat,0),x=v+ai(g.lat,0),b=t.differenceOfAnglesDegrees(o.lng,g.lng),w=t.differenceOfAnglesDegrees(o.lat,g.lat),T=ue(x-y);return d=v!==r,{easeFunc:r=>{if(t.equals(a,c)||Ot(a,c,{roll:s,pitch:n,bearing:l},e,r),i.around)t.warnOnce("Easing around a point is not supported under globe projection."),e.setLocationAtPoint(i.around,i.aroundPoint);else {const t=x>y?Math.min(2,T):Math.max(.5,T),i=Math.pow(t,1-r),a=li(o,b,w,r*i);e.setCenter(a.wrap());}if(d){const i=t.interpolateFactory.number(y,x,r)+ai(0,e.center.lat);e.setZoom(i);}},isZooming:d,elevationCenter:g}}handleFlyTo(e,i){if(!this.useGlobeControls)return this._mercatorCameraHelper.handleFlyTo(e,i);const r=void 0!==i.zoom,o=e.center,a=e.zoom,s=!e.isPaddingEqual(i.padding),n=e.getConstrained(t.LngLat.convert(i.center||i.locationAtOffset),a).center,l=r?+i.zoom:e.zoom+ai(e.center.lat,n.lat),c=e.clone();c.setCenter(n),s&&c.setPadding(i.padding),c.setZoom(l),c.setBearing(i.bearing);const h=new t.Point(t.clamp(e.centerPoint.x+i.offsetAsPoint.x,0,e.width),t.clamp(e.centerPoint.y+i.offsetAsPoint.y,0,e.height));c.setLocationAtPoint(n,h);const u=c.center;he(e,u);const d=function(e,i,r){const o=ti(i),a=ti(r),s=t.dot(o,a),n=Math.acos(s),l=Qt(e);return n/(2*Math.PI)*l}(e,o,u),_=a+ai(o.lat,0),p=l+ai(u.lat,0),m=ue(p-_);let f;if("number"==typeof i.minZoom){const t=+i.minZoom+ai(u.lat,0),r=Math.min(t,_,p)+ai(0,u.lat);f=ue(e.getConstrained(u,r).zoom+ai(u.lat,0)-_);}const g=t.differenceOfAnglesDegrees(o.lng,u.lng),v=t.differenceOfAnglesDegrees(o.lat,u.lat);return {easeFunc:(t,i,r,a)=>{const s=li(o,g,v,r),n=1===t?u:s;e.setCenter(n.wrap());const c=_+de(i);e.setZoom(1===t?l:c+ai(0,n.lat));},scaleOfZoom:m,targetCenter:u,scaleOfMinZoom:f,pixelPathLength:d}}static solveVectorScale(e,t,i,r,o){const a="x"===r?[i[0],i[4],i[8],i[12]]:[i[1],i[5],i[9],i[13]],s=[i[3],i[7],i[11],i[15]],n=e[0]*a[0]+e[1]*a[1]+e[2]*a[2],l=e[0]*s[0]+e[1]*s[1]+e[2]*s[2],c=t[0]*a[0]+t[1]*a[1]+t[2]*a[2],h=t[0]*s[0]+t[1]*s[1]+t[2]*s[2];return c+o*l===n+o*h||s[3]*(n-c)+a[3]*(h-l)+n*h==c*l?null:(c+a[3]-o*h-o*s[3])/(c-n-o*h+o*l)}static getLesserNonNegativeNonNull(e,t){return null!==t&&t>=0&&tt.emitValidationErrors(e,i&&i.filter((e=>"source.canvas"!==e.identifier))),fi=t.emptyStyle();class gi extends t.Evented{constructor(e,i={}){super(),this._rtlPluginLoaded=()=>{for(const e in this.sourceCaches){const t=this.sourceCaches[e].getSource().type;"vector"!==t&&"geojson"!==t||this.sourceCaches[e].reload();}},this.map=e,this.dispatcher=new O(B(),e._getMapId()),this.dispatcher.registerMessageHandler("GG",((e,t)=>this.getGlyphs(e,t))),this.dispatcher.registerMessageHandler("GI",((e,t)=>this.getImages(e,t))),this.imageManager=new b,this.imageManager.setEventedParent(this),this.glyphManager=new P(e._requestManager,i.localIdeographFontFamily),this.lineAtlas=new D(256,512),this.crossTileSymbolIndex=new gt,this._spritesImagesIds={},this._layers={},this._order=[],this.sourceCaches={},this.zoomHistory=new t.ZoomHistory,this._loaded=!1,this._availableImages=[],this._resetUpdates(),this.dispatcher.broadcast("SR",t.getReferrer()),oe().on(te,this._rtlPluginLoaded),this.on("data",(e=>{if("source"!==e.dataType||"metadata"!==e.sourceDataType)return;const t=this.sourceCaches[e.sourceId];if(!t)return;const i=t.getSource();if(i&&i.vectorLayerIds)for(const e in this._layers){const t=this._layers[e];t.source===i.id&&this._validateLayer(t);}}));}loadURL(e,i={},r){this.fire(new t.Event("dataloading",{dataType:"style"})),i.validate="boolean"!=typeof i.validate||i.validate;const o=this.map._requestManager.transformRequest(e,"Style");this._loadStyleRequest=new AbortController;const a=this._loadStyleRequest;t.getJSON(o,this._loadStyleRequest).then((e=>{this._loadStyleRequest=null,this._load(e.data,i,r);})).catch((e=>{this._loadStyleRequest=null,e&&!a.signal.aborted&&this.fire(new t.ErrorEvent(e));}));}loadJSON(e,i={},r){this.fire(new t.Event("dataloading",{dataType:"style"})),this._frameRequest=new AbortController,f.frameAsync(this._frameRequest).then((()=>{this._frameRequest=null,i.validate=!1!==i.validate,this._load(e,i,r);})).catch((()=>{}));}loadEmpty(){this.fire(new t.Event("dataloading",{dataType:"style"})),this._load(fi,{validate:!1});}_load(e,i,r){var o,a;const s=i.transformStyle?i.transformStyle(r,e):e;if(!i.validate||!mi(this,t.validateStyle(s))){this._loaded=!0,this.stylesheet=s;for(const e in s.sources)this.addSource(e,s.sources[e],{validate:!1});s.sprite?this._loadSprite(s.sprite):this.imageManager.setLoaded(!0),this.glyphManager.setURL(s.glyphs),this._createLayers(),this.light=new M(this.stylesheet.light),this._setProjectionInternal((null===(o=this.stylesheet.projection)||void 0===o?void 0:o.type)||"mercator"),this.sky=new R(this.stylesheet.sky),this.map.setTerrain(null!==(a=this.stylesheet.terrain)&&void 0!==a?a:null),this.fire(new t.Event("data",{dataType:"style"})),this.fire(new t.Event("style.load"));}}_createLayers(){const e=t.derefLayers(this.stylesheet.layers);this.dispatcher.broadcast("SL",e),this._order=e.map((e=>e.id)),this._layers={},this._serializedLayers=null;for(const i of e){const e=t.createStyleLayer(i);e.setEventedParent(this,{layer:{id:i.id}}),this._layers[i.id]=e;}}_loadSprite(e,i=!1,r=void 0){let o;this.imageManager.setLoaded(!1),this._spriteRequest=new AbortController,function(e,i,r,o){return t.__awaiter(this,void 0,void 0,(function*(){const a=g(e),s=r>1?"@2x":"",n={},l={};for(const{id:e,url:r}of a){const a=i.transformRequest(v(r,s,".json"),"SpriteJSON");n[e]=t.getJSON(a,o);const c=i.transformRequest(v(r,s,".png"),"SpriteImage");l[e]=_.getImage(c,o);}return yield Promise.all([...Object.values(n),...Object.values(l)]),function(e,i){return t.__awaiter(this,void 0,void 0,(function*(){const t={};for(const r in e){t[r]={};const o=f.getImageCanvasContext((yield i[r]).data),a=(yield e[r]).data;for(const e in a){const{width:i,height:s,x:n,y:l,sdf:c,pixelRatio:h,stretchX:u,stretchY:d,content:_,textFitWidth:p,textFitHeight:m}=a[e];t[r][e]={data:null,pixelRatio:h,sdf:c,stretchX:u,stretchY:d,content:_,textFitWidth:p,textFitHeight:m,spriteData:{width:i,height:s,x:n,y:l,context:o}};}}return t}))}(n,l)}))}(e,this.map._requestManager,this.map.getPixelRatio(),this._spriteRequest).then((e=>{if(this._spriteRequest=null,e)for(const t in e){this._spritesImagesIds[t]=[];const r=this._spritesImagesIds[t]?this._spritesImagesIds[t].filter((t=>!(t in e))):[];for(const e of r)this.imageManager.removeImage(e),this._changedImages[e]=!0;for(const r in e[t]){const o="default"===t?r:`${t}:${r}`;this._spritesImagesIds[t].push(o),o in this.imageManager.images?this.imageManager.updateImage(o,e[t][r],!1):this.imageManager.addImage(o,e[t][r]),i&&(this._changedImages[o]=!0);}}})).catch((e=>{this._spriteRequest=null,o=e,this.fire(new t.ErrorEvent(o));})).finally((()=>{this.imageManager.setLoaded(!0),this._availableImages=this.imageManager.listImages(),i&&(this._changed=!0),this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.Event("data",{dataType:"style"})),r&&r(o);}));}_unloadSprite(){for(const e of Object.values(this._spritesImagesIds).flat())this.imageManager.removeImage(e),this._changedImages[e]=!0;this._spritesImagesIds={},this._availableImages=this.imageManager.listImages(),this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.Event("data",{dataType:"style"}));}_validateLayer(e){const i=this.sourceCaches[e.source];if(!i)return;const r=e.sourceLayer;if(!r)return;const o=i.getSource();("geojson"===o.type||o.vectorLayerIds&&-1===o.vectorLayerIds.indexOf(r))&&this.fire(new t.ErrorEvent(new Error(`Source layer "${r}" does not exist on source "${o.id}" as specified by style layer "${e.id}".`)));}loaded(){if(!this._loaded)return !1;if(Object.keys(this._updatedSources).length)return !1;for(const e in this.sourceCaches)if(!this.sourceCaches[e].loaded())return !1;return !!this.imageManager.isLoaded()}_serializeByIds(e,i=!1){const r=this._serializedAllLayers();if(!e||0===e.length)return Object.values(i?t.clone$2(r):r);const o=[];for(const a of e)if(r[a]){const e=i?t.clone$2(r[a]):r[a];o.push(e);}return o}_serializedAllLayers(){let e=this._serializedLayers;if(e)return e;e=this._serializedLayers={};const t=Object.keys(this._layers);for(const i of t){const t=this._layers[i];"custom"!==t.type&&(e[i]=t.serialize());}return e}hasTransitions(){if(this.light&&this.light.hasTransition())return !0;if(this.sky&&this.sky.hasTransition())return !0;for(const e in this.sourceCaches)if(this.sourceCaches[e].hasTransition())return !0;for(const e in this._layers)if(this._layers[e].hasTransition())return !0;return !1}_checkLoaded(){if(!this._loaded)throw new Error("Style is not done loading.")}update(e){if(!this._loaded)return;const i=this._changed;if(i){const t=Object.keys(this._updatedLayers),i=Object.keys(this._removedLayers);(t.length||i.length)&&this._updateWorkerLayers(t,i);for(const e in this._updatedSources){const t=this._updatedSources[e];if("reload"===t)this._reloadSource(e);else {if("clear"!==t)throw new Error(`Invalid action ${t}`);this._clearSource(e);}}this._updateTilesForChangedImages(),this._updateTilesForChangedGlyphs();for(const t in this._updatedPaintProps)this._layers[t].updateTransitions(e);this.light.updateTransitions(e),this.sky.updateTransitions(e),this._resetUpdates();}const r={};for(const e in this.sourceCaches){const t=this.sourceCaches[e];r[e]=t.used,t.used=!1;}for(const t of this._order){const i=this._layers[t];i.recalculate(e,this._availableImages),!i.isHidden(e.zoom)&&i.source&&(this.sourceCaches[i.source].used=!0);}for(const e in r){const i=this.sourceCaches[e];!!r[e]!=!!i.used&&i.fire(new t.Event("data",{sourceDataType:"visibility",dataType:"source",sourceId:e}));}this.light.recalculate(e),this.sky.recalculate(e),this.z=e.zoom,i&&this.fire(new t.Event("data",{dataType:"style"}));}_updateTilesForChangedImages(){const e=Object.keys(this._changedImages);if(e.length){for(const t in this.sourceCaches)this.sourceCaches[t].reloadTilesForDependencies(["icons","patterns"],e);this._changedImages={};}}_updateTilesForChangedGlyphs(){if(this._glyphsDidChange){for(const e in this.sourceCaches)this.sourceCaches[e].reloadTilesForDependencies(["glyphs"],[""]);this._glyphsDidChange=!1;}}_updateWorkerLayers(e,t){this.dispatcher.broadcast("UL",{layers:this._serializeByIds(e,!1),removedIds:t});}_resetUpdates(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSources={},this._updatedPaintProps={},this._changedImages={},this._glyphsDidChange=!1;}setState(e,i={}){var r;this._checkLoaded();const o=this.serialize();if(e=i.transformStyle?i.transformStyle(o,e):e,(null===(r=i.validate)||void 0===r||r)&&mi(this,t.validateStyle(e)))return !1;(e=t.clone$2(e)).layers=t.derefLayers(e.layers);const a=t.diff(o,e),s=this._getOperationsToPerform(a);if(s.unimplemented.length>0)throw new Error(`Unimplemented: ${s.unimplemented.join(", ")}.`);if(0===s.operations.length)return !1;for(const e of s.operations)e();return this.stylesheet=e,this._serializedLayers=null,!0}_getOperationsToPerform(e){const t=[],i=[];for(const r of e)switch(r.command){case"setCenter":case"setZoom":case"setBearing":case"setPitch":case"setRoll":continue;case"addLayer":t.push((()=>this.addLayer.apply(this,r.args)));break;case"removeLayer":t.push((()=>this.removeLayer.apply(this,r.args)));break;case"setPaintProperty":t.push((()=>this.setPaintProperty.apply(this,r.args)));break;case"setLayoutProperty":t.push((()=>this.setLayoutProperty.apply(this,r.args)));break;case"setFilter":t.push((()=>this.setFilter.apply(this,r.args)));break;case"addSource":t.push((()=>this.addSource.apply(this,r.args)));break;case"removeSource":t.push((()=>this.removeSource.apply(this,r.args)));break;case"setLayerZoomRange":t.push((()=>this.setLayerZoomRange.apply(this,r.args)));break;case"setLight":t.push((()=>this.setLight.apply(this,r.args)));break;case"setGeoJSONSourceData":t.push((()=>this.setGeoJSONSourceData.apply(this,r.args)));break;case"setGlyphs":t.push((()=>this.setGlyphs.apply(this,r.args)));break;case"setSprite":t.push((()=>this.setSprite.apply(this,r.args)));break;case"setTerrain":t.push((()=>this.map.setTerrain.apply(this,r.args)));break;case"setSky":t.push((()=>this.setSky.apply(this,r.args)));break;case"setProjection":this.setProjection.apply(this,r.args);break;case"setTransition":t.push((()=>{}));break;default:i.push(r.command);}return {operations:t,unimplemented:i}}addImage(e,i){if(this.getImage(e))return this.fire(new t.ErrorEvent(new Error(`An image named "${e}" already exists.`)));this.imageManager.addImage(e,i),this._afterImageUpdated(e);}updateImage(e,t){this.imageManager.updateImage(e,t);}getImage(e){return this.imageManager.getImage(e)}removeImage(e){if(!this.getImage(e))return this.fire(new t.ErrorEvent(new Error(`An image named "${e}" does not exist.`)));this.imageManager.removeImage(e),this._afterImageUpdated(e);}_afterImageUpdated(e){this._availableImages=this.imageManager.listImages(),this._changedImages[e]=!0,this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.Event("data",{dataType:"style"}));}listImages(){return this._checkLoaded(),this.imageManager.listImages()}addSource(e,i,r={}){if(this._checkLoaded(),void 0!==this.sourceCaches[e])throw new Error(`Source "${e}" already exists.`);if(!i.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(i).join(", ")}.`);if(["vector","raster","geojson","video","image"].indexOf(i.type)>=0&&this._validate(t.validateStyle.source,`sources.${e}`,i,null,r))return;this.map&&this.map._collectResourceTiming&&(i.collectResourceTiming=!0);const o=this.sourceCaches[e]=new ye(e,i,this.dispatcher);o.style=this,o.setEventedParent(this,(()=>({isSourceLoaded:o.loaded(),source:o.serialize(),sourceId:e}))),o.onAdd(this.map),this._changed=!0;}removeSource(e){if(this._checkLoaded(),void 0===this.sourceCaches[e])throw new Error("There is no source with this ID");for(const i in this._layers)if(this._layers[i].source===e)return this.fire(new t.ErrorEvent(new Error(`Source "${e}" cannot be removed while layer "${i}" is using it.`)));const i=this.sourceCaches[e];delete this.sourceCaches[e],delete this._updatedSources[e],i.fire(new t.Event("data",{sourceDataType:"metadata",dataType:"source",sourceId:e})),i.setEventedParent(null),i.onRemove(this.map),this._changed=!0;}setGeoJSONSourceData(e,t){if(this._checkLoaded(),void 0===this.sourceCaches[e])throw new Error(`There is no source with this ID=${e}`);const i=this.sourceCaches[e].getSource();if("geojson"!==i.type)throw new Error(`geojsonSource.type is ${i.type}, which is !== 'geojson`);i.setData(t),this._changed=!0;}getSource(e){return this.sourceCaches[e]&&this.sourceCaches[e].getSource()}addLayer(e,i,r={}){this._checkLoaded();const o=e.id;if(this.getLayer(o))return void this.fire(new t.ErrorEvent(new Error(`Layer "${o}" already exists on this map.`)));let a;if("custom"===e.type){if(mi(this,t.validateCustomStyleLayer(e)))return;a=t.createStyleLayer(e);}else {if("source"in e&&"object"==typeof e.source&&(this.addSource(o,e.source),e=t.clone$2(e),e=t.extend(e,{source:o})),this._validate(t.validateStyle.layer,`layers.${o}`,e,{arrayIndex:-1},r))return;a=t.createStyleLayer(e),this._validateLayer(a),a.setEventedParent(this,{layer:{id:o}});}const s=i?this._order.indexOf(i):this._order.length;if(i&&-1===s)this.fire(new t.ErrorEvent(new Error(`Cannot add layer "${o}" before non-existing layer "${i}".`)));else {if(this._order.splice(s,0,o),this._layerOrderChanged=!0,this._layers[o]=a,this._removedLayers[o]&&a.source&&"custom"!==a.type){const e=this._removedLayers[o];delete this._removedLayers[o],e.type!==a.type?this._updatedSources[a.source]="clear":(this._updatedSources[a.source]="reload",this.sourceCaches[a.source].pause());}this._updateLayer(a),a.onAdd&&a.onAdd(this.map);}}moveLayer(e,i){if(this._checkLoaded(),this._changed=!0,!this._layers[e])return void this.fire(new t.ErrorEvent(new Error(`The layer '${e}' does not exist in the map's style and cannot be moved.`)));if(e===i)return;const r=this._order.indexOf(e);this._order.splice(r,1);const o=i?this._order.indexOf(i):this._order.length;i&&-1===o?this.fire(new t.ErrorEvent(new Error(`Cannot move layer "${e}" before non-existing layer "${i}".`))):(this._order.splice(o,0,e),this._layerOrderChanged=!0);}removeLayer(e){this._checkLoaded();const i=this._layers[e];if(!i)return void this.fire(new t.ErrorEvent(new Error(`Cannot remove non-existing layer "${e}".`)));i.setEventedParent(null);const r=this._order.indexOf(e);this._order.splice(r,1),this._layerOrderChanged=!0,this._changed=!0,this._removedLayers[e]=i,delete this._layers[e],this._serializedLayers&&delete this._serializedLayers[e],delete this._updatedLayers[e],delete this._updatedPaintProps[e],i.onRemove&&i.onRemove(this.map);}getLayer(e){return this._layers[e]}getLayersOrder(){return [...this._order]}hasLayer(e){return e in this._layers}setLayerZoomRange(e,i,r){this._checkLoaded();const o=this.getLayer(e);o?o.minzoom===i&&o.maxzoom===r||(null!=i&&(o.minzoom=i),null!=r&&(o.maxzoom=r),this._updateLayer(o)):this.fire(new t.ErrorEvent(new Error(`Cannot set the zoom range of non-existing layer "${e}".`)));}setFilter(e,i,r={}){this._checkLoaded();const o=this.getLayer(e);if(o){if(!t.deepEqual(o.filter,i))return null==i?(o.filter=void 0,void this._updateLayer(o)):void(this._validate(t.validateStyle.filter,`layers.${o.id}.filter`,i,null,r)||(o.filter=t.clone$2(i),this._updateLayer(o)))}else this.fire(new t.ErrorEvent(new Error(`Cannot filter non-existing layer "${e}".`)));}getFilter(e){return t.clone$2(this.getLayer(e).filter)}setLayoutProperty(e,i,r,o={}){this._checkLoaded();const a=this.getLayer(e);a?t.deepEqual(a.getLayoutProperty(i),r)||(a.setLayoutProperty(i,r,o),this._updateLayer(a)):this.fire(new t.ErrorEvent(new Error(`Cannot style non-existing layer "${e}".`)));}getLayoutProperty(e,i){const r=this.getLayer(e);if(r)return r.getLayoutProperty(i);this.fire(new t.ErrorEvent(new Error(`Cannot get style of non-existing layer "${e}".`)));}setPaintProperty(e,i,r,o={}){this._checkLoaded();const a=this.getLayer(e);a?t.deepEqual(a.getPaintProperty(i),r)||(a.setPaintProperty(i,r,o)&&this._updateLayer(a),this._changed=!0,this._updatedPaintProps[e]=!0,this._serializedLayers=null):this.fire(new t.ErrorEvent(new Error(`Cannot style non-existing layer "${e}".`)));}getPaintProperty(e,t){return this.getLayer(e).getPaintProperty(t)}setFeatureState(e,i){this._checkLoaded();const r=e.source,o=e.sourceLayer,a=this.sourceCaches[r];if(void 0===a)return void this.fire(new t.ErrorEvent(new Error(`The source '${r}' does not exist in the map's style.`)));const s=a.getSource().type;"geojson"===s&&o?this.fire(new t.ErrorEvent(new Error("GeoJSON sources cannot have a sourceLayer parameter."))):"vector"!==s||o?(void 0===e.id&&this.fire(new t.ErrorEvent(new Error("The feature id parameter must be provided."))),a.setFeatureState(o,e.id,i)):this.fire(new t.ErrorEvent(new Error("The sourceLayer parameter must be provided for vector source types.")));}removeFeatureState(e,i){this._checkLoaded();const r=e.source,o=this.sourceCaches[r];if(void 0===o)return void this.fire(new t.ErrorEvent(new Error(`The source '${r}' does not exist in the map's style.`)));const a=o.getSource().type,s="vector"===a?e.sourceLayer:void 0;"vector"!==a||s?i&&"string"!=typeof e.id&&"number"!=typeof e.id?this.fire(new t.ErrorEvent(new Error("A feature id is required to remove its specific state property."))):o.removeFeatureState(s,e.id,i):this.fire(new t.ErrorEvent(new Error("The sourceLayer parameter must be provided for vector source types.")));}getFeatureState(e){this._checkLoaded();const i=e.source,r=e.sourceLayer,o=this.sourceCaches[i];if(void 0!==o)return "vector"!==o.getSource().type||r?(void 0===e.id&&this.fire(new t.ErrorEvent(new Error("The feature id parameter must be provided."))),o.getFeatureState(r,e.id)):void this.fire(new t.ErrorEvent(new Error("The sourceLayer parameter must be provided for vector source types.")));this.fire(new t.ErrorEvent(new Error(`The source '${i}' does not exist in the map's style.`)));}getTransition(){return t.extend({duration:300,delay:0},this.stylesheet&&this.stylesheet.transition)}serialize(){if(!this._loaded)return;const e=t.mapObject(this.sourceCaches,(e=>e.serialize())),i=this._serializeByIds(this._order,!0),r=this.map.getTerrain()||void 0,o=this.stylesheet;return t.filterObject({version:o.version,name:o.name,metadata:o.metadata,light:o.light,sky:o.sky,center:o.center,zoom:o.zoom,bearing:o.bearing,pitch:o.pitch,sprite:o.sprite,glyphs:o.glyphs,transition:o.transition,projection:o.projection,sources:e,layers:i,terrain:r},(e=>void 0!==e))}_updateLayer(e){this._updatedLayers[e.id]=!0,e.source&&!this._updatedSources[e.source]&&"raster"!==this.sourceCaches[e.source].getSource().type&&(this._updatedSources[e.source]="reload",this.sourceCaches[e.source].pause()),this._serializedLayers=null,this._changed=!0;}_flattenAndSortRenderedFeatures(e){const t=e=>"fill-extrusion"===this._layers[e].type,i={},r=[];for(let o=this._order.length-1;o>=0;o--){const a=this._order[o];if(t(a)){i[a]=o;for(const t of e){const e=t[a];if(e)for(const t of e)r.push(t);}}}r.sort(((e,t)=>t.intersectionZ-e.intersectionZ));const o=[];for(let a=this._order.length-1;a>=0;a--){const s=this._order[a];if(t(s))for(let e=r.length-1;e>=0;e--){const t=r[e].feature;if(i[t.layer.id]{const r=i.featureSortOrder;if(r){const i=r.indexOf(e.featureIndex);return r.indexOf(t.featureIndex)-i}return t.featureIndex-e.featureIndex}));for(const e of o)t.push(e);}}for(const t in n)n[t].forEach((r=>{const o=r.feature,a=i[e[t].source].getFeatureState(o.layer["source-layer"],o.id);o.source=o.layer.source,o.layer["source-layer"]&&(o.sourceLayer=o.layer["source-layer"]),o.state=a;}));return n}(this._layers,s,this.sourceCaches,e,l,this.placement.collisionIndex,this.placement.retainedQueryData)),this._flattenAndSortRenderedFeatures(a)}querySourceFeatures(e,i){i&&i.filter&&this._validate(t.validateStyle.filter,"querySourceFeatures.filter",i.filter,null,i);const r=this.sourceCaches[e];return r?function(e,t){const i=e.getRenderableIds().map((t=>e.getTileByID(t))),r=[],o={};for(let e=0;ee.getTileByID(t))).sort(((e,t)=>t.tileID.overscaledZ-e.tileID.overscaledZ||(e.tileID.isLessThan(t.tileID)?-1:1)));}const r=this.crossTileSymbolIndex.addLayer(i,n[i.source],e.center.lng);a=a||r;}if(this.crossTileSymbolIndex.pruneUnusedLayers(this._order),((o=o||this._layerOrderChanged||0===i)||!this.pauseablePlacement||this.pauseablePlacement.isDone()&&!this.placement.stillRecent(f.now(),e.zoom))&&(this.pauseablePlacement=new dt(e,this.map.terrain,this._order,o,t,i,r,this.placement),this._layerOrderChanged=!1),this.pauseablePlacement.isDone()?this.placement.setStale():(this.pauseablePlacement.continuePlacement(this._order,this._layers,n),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(f.now()),s=!0),a&&this.pauseablePlacement.placement.setStale()),s||a)for(const e of this._order){const t=this._layers[e];"symbol"===t.type&&this.placement.updateLayerOpacities(t,n[t.source]);}return !this.pauseablePlacement.isDone()||this.placement.hasTransitions(f.now())}_releaseSymbolFadeTiles(){for(const e in this.sourceCaches)this.sourceCaches[e].releaseSymbolFadeTiles();}getImages(e,i){return t.__awaiter(this,void 0,void 0,(function*(){const e=yield this.imageManager.getImages(i.icons);this._updateTilesForChangedImages();const t=this.sourceCaches[i.source];return t&&t.setDependencies(i.tileID.key,i.type,i.icons),e}))}getGlyphs(e,i){return t.__awaiter(this,void 0,void 0,(function*(){const e=yield this.glyphManager.getGlyphs(i.stacks),t=this.sourceCaches[i.source];return t&&t.setDependencies(i.tileID.key,i.type,[""]),e}))}getGlyphsUrl(){return this.stylesheet.glyphs||null}setGlyphs(e,i={}){this._checkLoaded(),e&&this._validate(t.validateStyle.glyphs,"glyphs",e,null,i)||(this._glyphsDidChange=!0,this.stylesheet.glyphs=e,this.glyphManager.entries={},this.glyphManager.setURL(e));}addSprite(e,i,r={},o){this._checkLoaded();const a=[{id:e,url:i}],s=[...g(this.stylesheet.sprite),...a];this._validate(t.validateStyle.sprite,"sprite",s,null,r)||(this.stylesheet.sprite=s,this._loadSprite(a,!0,o));}removeSprite(e){this._checkLoaded();const i=g(this.stylesheet.sprite);if(i.find((t=>t.id===e))){if(this._spritesImagesIds[e])for(const t of this._spritesImagesIds[e])this.imageManager.removeImage(t),this._changedImages[t]=!0;i.splice(i.findIndex((t=>t.id===e)),1),this.stylesheet.sprite=i.length>0?i:void 0,delete this._spritesImagesIds[e],this._availableImages=this.imageManager.listImages(),this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.Event("data",{dataType:"style"}));}else this.fire(new t.ErrorEvent(new Error(`Sprite "${e}" doesn't exists on this map.`)));}getSprite(){return g(this.stylesheet.sprite)}setSprite(e,i={},r){this._checkLoaded(),e&&this._validate(t.validateStyle.sprite,"sprite",e,null,i)||(this.stylesheet.sprite=e,e?this._loadSprite(e,!0,r):(this._unloadSprite(),r&&r(null)));}}class vi{constructor(e){this._transformRequestFn=e;}transformRequest(e,t){return this._transformRequestFn&&this._transformRequestFn(e,t)||{url:e}}setTransformRequest(e){this._transformRequestFn=e;}}class yi extends t.Evented{constructor(){super(),this._requestManager=new vi,this.transform=new Ft;}getPixelRatio(){return devicePixelRatio}setTerrain(){}_getMapId(){return 1}}class xi{constructor(e,i){this.styleJSON=e,this.sourceID=i,this.layerIndex=new t.StyleLayerIndex(t.derefLayers(this.styleJSON.layers)),this.glyphs={},this.icons={};}loadImages(e){return t.__awaiter(this,void 0,void 0,(function*(){const t=JSON.stringify(e);return this.icons[t]||(this.icons[t]=yield this.style.getImages("",e)),this.icons[t]}))}loadGlyphs(e){return t.__awaiter(this,void 0,void 0,(function*(){const t=JSON.stringify(e);return this.glyphs[t]||(this.glyphs[t]=yield this.style.getGlyphs("",e)),this.glyphs[t]}))}setup(){const e=this;return this.actor={sendAsync(t){if("GI"===t.type)return e.loadImages(t.data);if("GG"===t.type)return e.loadGlyphs(t.data);throw new Error(`Invalid action ${t.type}`)}},Promise.all([(t=this.styleJSON,new Promise(((e,i)=>{const r=new yi,o=new gi(r);r.style=o,o.loadJSON(t),o.on("style.load",(()=>e(o))),o.on("error",i);}))),fetch(this.styleJSON.sources[this.sourceID].url).then((e=>e.json()))]).then((([e,t])=>{this.style=e,this.tileJSON=t;}));var t;}fetchTile(e){return fetch(e.canonical.url(this.tileJSON.tiles,devicePixelRatio)).then((e=>e.arrayBuffer())).then((t=>({tileID:e,buffer:t})))}parseTile(e,i){const r=new t.WorkerTile({type:"benchmark",tileID:e.tileID,zoom:e.tileID.overscaledZ,tileSize:512,showCollisionBoxes:!1,source:this.sourceID,uid:"0",maxZoom:22,pixelRatio:1,request:{url:""},returnDependencies:i,promoteId:void 0,subdivisionGranularity:t.SubdivisionGranularitySetting.noSubdivision}),o=new t.mvt.VectorTile(new t.Protobuf(e.buffer));return r.parse(o,this.layerIndex,[],this.actor,t.SubdivisionGranularitySetting.noSubdivision)}}class bi extends a{constructor(e,i){super(),this.style=e,this.tileIDs=i||[new t.OverscaledTileID(12,0,12,655,1583),new t.OverscaledTileID(8,0,8,40,98),new t.OverscaledTileID(4,0,4,3,6),new t.OverscaledTileID(0,0,0,0,0)];}setup(){return t.__awaiter(this,void 0,void 0,(function*(){const e=yield s(this.style);this.parser=new xi(e,"openmaptiles"),yield this.parser.setup(),this.tiles=yield Promise.all(this.tileIDs.map((e=>this.parser.fetchTile(e)))),yield Promise.all(this.tiles.map((e=>this.parser.parseTile(e))));}))}bench(){return t.__awaiter(this,void 0,void 0,(function*(){for(const e of this.tiles)yield this.parser.parseTile(e);}))}}class wi{static testProp(e){if(!wi.docStyle)return e[0];for(let t=0;t{window.removeEventListener("click",wi.suppressClickInternal,!0);}),0);}static getScale(e){const t=e.getBoundingClientRect();return {x:t.width/e.offsetWidth||1,y:t.height/e.offsetHeight||1,boundingClientRect:t}}static getPoint(e,i,r){const o=i.boundingClientRect;return new t.Point((r.clientX-o.left)/i.x-e.clientLeft,(r.clientY-o.top)/i.y-e.clientTop)}static mousePos(e,t){const i=wi.getScale(e);return wi.getPoint(e,i,t)}static touchPos(e,t){const i=[],r=wi.getScale(e);for(let o=0;o({u_texture:0,u_ele_delta:e,u_fog_matrix:i,u_fog_color:r?r.properties.get("fog-color"):t.Color.white,u_fog_ground_blend:r?r.properties.get("fog-ground-blend"):1,u_fog_ground_blend_opacity:a?0:r?r.calculateFogBlendOpacity(o):0,u_horizon_color:r?r.properties.get("horizon-color"):t.Color.white,u_horizon_fog_blend:r?r.properties.get("horizon-fog-blend"):1,u_is_globe_mode:a?1:0}),Ci={mainMatrix:"u_projection_matrix",tileMercatorCoords:"u_projection_tile_mercator_coords",clippingPlane:"u_projection_clipping_plane",projectionTransition:"u_projection_transition",fallbackMatrix:"u_projection_fallback_matrix"};function Mi(e){const t=[];for(let i=0;i({u_depth:new t.Uniform1i(e,i.u_depth),u_terrain:new t.Uniform1i(e,i.u_terrain),u_terrain_dim:new t.Uniform1f(e,i.u_terrain_dim),u_terrain_matrix:new t.UniformMatrix4f(e,i.u_terrain_matrix),u_terrain_unpack:new t.Uniform4f(e,i.u_terrain_unpack),u_terrain_exaggeration:new t.Uniform1f(e,i.u_terrain_exaggeration)}))(e,E),this.projectionUniforms=((e,i)=>({u_projection_matrix:new t.UniformMatrix4f(e,i.u_projection_matrix),u_projection_tile_mercator_coords:new t.Uniform4f(e,i.u_projection_tile_mercator_coords),u_projection_clipping_plane:new t.Uniform4f(e,i.u_projection_clipping_plane),u_projection_transition:new t.Uniform1f(e,i.u_projection_transition),u_projection_fallback_matrix:new t.UniformMatrix4f(e,i.u_projection_fallback_matrix)}))(e,E),this.binderUniforms=r?r.getUniforms(e,E):[];}draw(e,t,i,r,o,a,s,n,l,c,h,u,d,_,p,m,f,g,v){const y=e.gl;if(this.failedToCreate)return;if(e.program.set(this.program),e.setDepthMode(i),e.setStencilMode(r),e.setColorMode(o),e.setCullFace(a),n){e.activeTexture.set(y.TEXTURE2),y.bindTexture(y.TEXTURE_2D,n.depthTexture),e.activeTexture.set(y.TEXTURE3),y.bindTexture(y.TEXTURE_2D,n.texture);for(const e in this.terrainUniforms)this.terrainUniforms[e].set(n[e]);}if(l)for(const e in l)this.projectionUniforms[Ci[e]].set(l[e]);if(s)for(const e in this.fixedUniforms)this.fixedUniforms[e].set(s[e]);m&&m.setUniforms(e,this.binderUniforms,_,{zoom:p});let x=0;switch(t){case y.LINES:x=2;break;case y.TRIANGLES:x=3;break;case y.LINE_STRIP:x=1;}for(const i of d.get()){const r=i.vaos||(i.vaos={});(r[c]||(r[c]=new Pi)).bind(e,this,h,m?m.getPaintVertexBuffers():[],u,i.vertexOffset,f,g,v),y.drawElements(t,i.primitiveLength*x,y.UNSIGNED_SHORT,i.primitiveOffset*x*2);}}}function Ri(e,i,r){const o=1/t.pixelsToTileUnits(r,1,i.transform.tileZoom),a=Math.pow(2,r.tileID.overscaledZ),s=r.tileSize*Math.pow(2,i.transform.tileZoom)/a,n=s*(r.tileID.canonical.x+r.tileID.wrap*a),l=s*r.tileID.canonical.y;return {u_image:0,u_texsize:r.imageAtlasTexture.size,u_scale:[o,e.fromScale,e.toScale],u_fade:e.t,u_pixel_coord_upper:[n>>16,l>>16],u_pixel_coord_lower:[65535&n,65535&l]}}const Di=(e,i,r,o)=>{const a=e.style.light,s=a.properties.get("position"),n=[s.x,s.y,s.z],l=t.create$2();"viewport"===a.properties.get("anchor")&&t.fromRotation(l,e.transform.bearingInRadians),t.transformMat3(n,n,l);const c=e.transform.transformLightDirection(n),h=a.properties.get("color");return {u_lightpos:n,u_lightpos_globe:c,u_lightintensity:a.properties.get("intensity"),u_lightcolor:[h.r,h.g,h.b],u_vertical_gradient:+i,u_opacity:r,u_fill_translate:o}},zi=(e,i,r,o,a,s,n)=>t.extend(Di(e,i,r,o),Ri(s,e,n),{u_height_factor:-Math.pow(2,a.overscaledZ)/n.tileSize/8}),Li=(e,i,r,o)=>t.extend(Ri(i,e,r),{u_fill_translate:o}),Ai=(e,t)=>({u_world:e,u_fill_translate:t}),ki=(e,i,r,o,a)=>t.extend(Li(e,i,r,a),{u_world:o}),Fi=(e,i,r,o,a)=>{const s=e.transform;let n,l,c=0;if("map"===r.paint.get("circle-pitch-alignment")){const e=t.pixelsToTileUnits(i,1,s.zoom);n=!0,l=[e,e],c=e/(t.EXTENT*Math.pow(2,i.tileID.overscaledZ))*2*Math.PI*a;}else n=!1,l=s.pixelsToGLUnits;return {u_camera_to_center_distance:s.cameraToCenterDistance,u_scale_with_map:+("map"===r.paint.get("circle-pitch-scale")),u_pitch_with_map:+n,u_device_pixel_ratio:e.pixelRatio,u_extrude_scale:l,u_globe_extrude_scale:c,u_translate:o}},Bi=e=>({u_pixel_extrude_scale:[1/e.width,1/e.height]}),Oi=e=>({u_viewport_size:[e.width,e.height]}),Ui=(e,t=1)=>({u_color:e,u_overlay:0,u_overlay_scale:t}),ji=(e,i,r,o)=>{const a=t.pixelsToTileUnits(e,1,i)/(t.EXTENT*Math.pow(2,e.tileID.overscaledZ))*2*Math.PI*o;return {u_extrude_scale:t.pixelsToTileUnits(e,1,i),u_intensity:r,u_globe_extrude_scale:a}},Ni=(e,i,r,o)=>{const a=t.create();t.ortho(a,0,e.width,e.height,0,0,1);const s=e.context.gl;return {u_matrix:a,u_world:[s.drawingBufferWidth,s.drawingBufferHeight],u_image:r,u_color_ramp:o,u_opacity:i.paint.get("heatmap-opacity")}},Gi=(e,t,i)=>{const r=i.paint.get("hillshade-shadow-color"),o=i.paint.get("hillshade-highlight-color"),a=i.paint.get("hillshade-accent-color");let s=i.paint.get("hillshade-illumination-direction")*(Math.PI/180);return "viewport"===i.paint.get("hillshade-illumination-anchor")&&(s+=e.transform.bearingInRadians),{u_image:0,u_latrange:Vi(0,t.tileID),u_light:[i.paint.get("hillshade-exaggeration"),s],u_shadow:r,u_highlight:o,u_accent:a}},Zi=(e,i)=>{const r=i.stride,o=t.create();return t.ortho(o,0,t.EXTENT,-t.EXTENT,0,0,1),t.translate(o,o,[0,-t.EXTENT,0]),{u_matrix:o,u_image:1,u_dimension:[r,r],u_zoom:e.overscaledZ,u_unpack:i.getUnpackVector()}};function Vi(e,i){const r=Math.pow(2,i.canonical.z),o=i.canonical.y;return [new t.MercatorCoordinate(0,o/r).toLngLat().lat,new t.MercatorCoordinate(0,(o+1)/r).toLngLat().lat]}const qi=(e,i,r,o)=>{const a=e.transform;return {u_translation:Ki(e,i,r),u_ratio:o/t.pixelsToTileUnits(i,1,a.zoom),u_device_pixel_ratio:e.pixelRatio,u_units_to_pixels:[1/a.pixelsToGLUnits[0],1/a.pixelsToGLUnits[1]]}},Wi=(e,i,r,o,a)=>t.extend(qi(e,i,r,o),{u_image:0,u_image_height:a}),Xi=(e,i,r,o,a)=>{const s=e.transform,n=Hi(i,s);return {u_translation:Ki(e,i,r),u_texsize:i.imageAtlasTexture.size,u_ratio:o/t.pixelsToTileUnits(i,1,s.zoom),u_device_pixel_ratio:e.pixelRatio,u_image:0,u_scale:[n,a.fromScale,a.toScale],u_fade:a.t,u_units_to_pixels:[1/s.pixelsToGLUnits[0],1/s.pixelsToGLUnits[1]]}},$i=(e,i,r,o,a,s)=>{const n=e.lineAtlas,l=Hi(i,e.transform),c="round"===r.layout.get("line-cap"),h=n.getDash(a.from,c),u=n.getDash(a.to,c),d=h.width*s.fromScale,_=u.width*s.toScale;return t.extend(qi(e,i,r,o),{u_patternscale_a:[l/d,-h.height/2],u_patternscale_b:[l/_,-u.height/2],u_sdfgamma:n.width/(256*Math.min(d,_)*e.pixelRatio)/2,u_image:0,u_tex_y_a:h.y,u_tex_y_b:u.y,u_mix:s.t})};function Hi(e,i){return 1/t.pixelsToTileUnits(e,1,i.tileZoom)}function Ki(e,i,r){return t.translatePosition(e.transform,i,r.paint.get("line-translate"),r.paint.get("line-translate-anchor"))}const Yi=(e,t,i,r,o)=>{return {u_tl_parent:e,u_scale_parent:t,u_buffer_scale:1,u_fade_t:i.mix,u_opacity:i.opacity*r.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:r.paint.get("raster-brightness-min"),u_brightness_high:r.paint.get("raster-brightness-max"),u_saturation_factor:(s=r.paint.get("raster-saturation"),s>0?1-1/(1.001-s):-s),u_contrast_factor:(a=r.paint.get("raster-contrast"),a>0?1/(1-a):1+a),u_spin_weights:Ji(r.paint.get("raster-hue-rotate")),u_coords_top:[o[0].x,o[0].y,o[1].x,o[1].y],u_coords_bottom:[o[3].x,o[3].y,o[2].x,o[2].y]};var a,s;};function Ji(e){e*=Math.PI/180;const t=Math.sin(e),i=Math.cos(e);return [(2*i+1)/3,(-Math.sqrt(3)*t-i+1)/3,(Math.sqrt(3)*t-i+1)/3]}const Qi=(e,t,i,r,o,a,s,n,l,c,h,u,d)=>{const _=s.transform;return {u_is_size_zoom_constant:+("constant"===e||"source"===e),u_is_size_feature_constant:+("constant"===e||"camera"===e),u_size_t:t?t.uSizeT:0,u_size:t?t.uSize:0,u_camera_to_center_distance:_.cameraToCenterDistance,u_pitch:_.pitch/360*2*Math.PI,u_rotate_symbol:+i,u_aspect_ratio:_.width/_.height,u_fade_change:s.options.fadeDuration?s.symbolFadeChange:1,u_label_plane_matrix:n,u_coord_matrix:l,u_is_text:+h,u_pitch_with_map:+r,u_is_along_line:o,u_is_variable_anchor:a,u_texsize:u,u_texture:0,u_translation:c,u_pitched_scale:d}},er=(e,i,r,o,a,s,n,l,c,h,u,d,_,p)=>{const m=n.transform;return t.extend(Qi(e,i,r,o,a,s,n,l,c,h,u,d,p),{u_gamma_scale:o?Math.cos(m.pitch*Math.PI/180)*m.cameraToCenterDistance:1,u_device_pixel_ratio:n.pixelRatio,u_is_halo:+_})},tr=(e,i,r,o,a,s,n,l,c,h,u,d,_)=>t.extend(er(e,i,r,o,a,s,n,l,c,h,!0,u,!0,_),{u_texsize_icon:d,u_texture_icon:1}),ir=(e,t)=>({u_opacity:e,u_color:t}),rr=(e,i,r,o,a)=>t.extend(function(e,i,r,o){const a=r.imageManager.getPattern(e.from.toString()),s=r.imageManager.getPattern(e.to.toString()),{width:n,height:l}=r.imageManager.getPixelSize(),c=Math.pow(2,o.tileID.overscaledZ),h=o.tileSize*Math.pow(2,r.transform.tileZoom)/c,u=h*(o.tileID.canonical.x+o.tileID.wrap*c),d=h*o.tileID.canonical.y;return {u_image:0,u_pattern_tl_a:a.tl,u_pattern_br_a:a.br,u_pattern_tl_b:s.tl,u_pattern_br_b:s.br,u_texsize:[n,l],u_mix:i.t,u_pattern_size_a:a.displaySize,u_pattern_size_b:s.displaySize,u_scale_a:i.fromScale,u_scale_b:i.toScale,u_tile_units_to_pixels:1/t.pixelsToTileUnits(o,1,r.transform.tileZoom),u_pixel_coord_upper:[u>>16,d>>16],u_pixel_coord_lower:[65535&u,65535&d]}}(r,a,i,o),{u_opacity:e}),or=(e,t)=>{},ar={fillExtrusion:(e,i)=>({u_lightpos:new t.Uniform3f(e,i.u_lightpos),u_lightpos_globe:new t.Uniform3f(e,i.u_lightpos_globe),u_lightintensity:new t.Uniform1f(e,i.u_lightintensity),u_lightcolor:new t.Uniform3f(e,i.u_lightcolor),u_vertical_gradient:new t.Uniform1f(e,i.u_vertical_gradient),u_opacity:new t.Uniform1f(e,i.u_opacity),u_fill_translate:new t.Uniform2f(e,i.u_fill_translate)}),fillExtrusionPattern:(e,i)=>({u_lightpos:new t.Uniform3f(e,i.u_lightpos),u_lightpos_globe:new t.Uniform3f(e,i.u_lightpos_globe),u_lightintensity:new t.Uniform1f(e,i.u_lightintensity),u_lightcolor:new t.Uniform3f(e,i.u_lightcolor),u_vertical_gradient:new t.Uniform1f(e,i.u_vertical_gradient),u_height_factor:new t.Uniform1f(e,i.u_height_factor),u_opacity:new t.Uniform1f(e,i.u_opacity),u_fill_translate:new t.Uniform2f(e,i.u_fill_translate),u_image:new t.Uniform1i(e,i.u_image),u_texsize:new t.Uniform2f(e,i.u_texsize),u_pixel_coord_upper:new t.Uniform2f(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.Uniform2f(e,i.u_pixel_coord_lower),u_scale:new t.Uniform3f(e,i.u_scale),u_fade:new t.Uniform1f(e,i.u_fade)}),fill:(e,i)=>({u_fill_translate:new t.Uniform2f(e,i.u_fill_translate)}),fillPattern:(e,i)=>({u_image:new t.Uniform1i(e,i.u_image),u_texsize:new t.Uniform2f(e,i.u_texsize),u_pixel_coord_upper:new t.Uniform2f(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.Uniform2f(e,i.u_pixel_coord_lower),u_scale:new t.Uniform3f(e,i.u_scale),u_fade:new t.Uniform1f(e,i.u_fade),u_fill_translate:new t.Uniform2f(e,i.u_fill_translate)}),fillOutline:(e,i)=>({u_world:new t.Uniform2f(e,i.u_world),u_fill_translate:new t.Uniform2f(e,i.u_fill_translate)}),fillOutlinePattern:(e,i)=>({u_world:new t.Uniform2f(e,i.u_world),u_image:new t.Uniform1i(e,i.u_image),u_texsize:new t.Uniform2f(e,i.u_texsize),u_pixel_coord_upper:new t.Uniform2f(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.Uniform2f(e,i.u_pixel_coord_lower),u_scale:new t.Uniform3f(e,i.u_scale),u_fade:new t.Uniform1f(e,i.u_fade),u_fill_translate:new t.Uniform2f(e,i.u_fill_translate)}),circle:(e,i)=>({u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_scale_with_map:new t.Uniform1i(e,i.u_scale_with_map),u_pitch_with_map:new t.Uniform1i(e,i.u_pitch_with_map),u_extrude_scale:new t.Uniform2f(e,i.u_extrude_scale),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_globe_extrude_scale:new t.Uniform1f(e,i.u_globe_extrude_scale),u_translate:new t.Uniform2f(e,i.u_translate)}),collisionBox:(e,i)=>({u_pixel_extrude_scale:new t.Uniform2f(e,i.u_pixel_extrude_scale)}),collisionCircle:(e,i)=>({u_viewport_size:new t.Uniform2f(e,i.u_viewport_size)}),debug:(e,i)=>({u_color:new t.UniformColor(e,i.u_color),u_overlay:new t.Uniform1i(e,i.u_overlay),u_overlay_scale:new t.Uniform1f(e,i.u_overlay_scale)}),depth:or,clippingMask:or,heatmap:(e,i)=>({u_extrude_scale:new t.Uniform1f(e,i.u_extrude_scale),u_intensity:new t.Uniform1f(e,i.u_intensity),u_globe_extrude_scale:new t.Uniform1f(e,i.u_globe_extrude_scale)}),heatmapTexture:(e,i)=>({u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_world:new t.Uniform2f(e,i.u_world),u_image:new t.Uniform1i(e,i.u_image),u_color_ramp:new t.Uniform1i(e,i.u_color_ramp),u_opacity:new t.Uniform1f(e,i.u_opacity)}),hillshade:(e,i)=>({u_image:new t.Uniform1i(e,i.u_image),u_latrange:new t.Uniform2f(e,i.u_latrange),u_light:new t.Uniform2f(e,i.u_light),u_shadow:new t.UniformColor(e,i.u_shadow),u_highlight:new t.UniformColor(e,i.u_highlight),u_accent:new t.UniformColor(e,i.u_accent)}),hillshadePrepare:(e,i)=>({u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_image:new t.Uniform1i(e,i.u_image),u_dimension:new t.Uniform2f(e,i.u_dimension),u_zoom:new t.Uniform1f(e,i.u_zoom),u_unpack:new t.Uniform4f(e,i.u_unpack)}),line:(e,i)=>({u_translation:new t.Uniform2f(e,i.u_translation),u_ratio:new t.Uniform1f(e,i.u_ratio),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.Uniform2f(e,i.u_units_to_pixels)}),lineGradient:(e,i)=>({u_translation:new t.Uniform2f(e,i.u_translation),u_ratio:new t.Uniform1f(e,i.u_ratio),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.Uniform2f(e,i.u_units_to_pixels),u_image:new t.Uniform1i(e,i.u_image),u_image_height:new t.Uniform1f(e,i.u_image_height)}),linePattern:(e,i)=>({u_translation:new t.Uniform2f(e,i.u_translation),u_texsize:new t.Uniform2f(e,i.u_texsize),u_ratio:new t.Uniform1f(e,i.u_ratio),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_image:new t.Uniform1i(e,i.u_image),u_units_to_pixels:new t.Uniform2f(e,i.u_units_to_pixels),u_scale:new t.Uniform3f(e,i.u_scale),u_fade:new t.Uniform1f(e,i.u_fade)}),lineSDF:(e,i)=>({u_translation:new t.Uniform2f(e,i.u_translation),u_ratio:new t.Uniform1f(e,i.u_ratio),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.Uniform2f(e,i.u_units_to_pixels),u_patternscale_a:new t.Uniform2f(e,i.u_patternscale_a),u_patternscale_b:new t.Uniform2f(e,i.u_patternscale_b),u_sdfgamma:new t.Uniform1f(e,i.u_sdfgamma),u_image:new t.Uniform1i(e,i.u_image),u_tex_y_a:new t.Uniform1f(e,i.u_tex_y_a),u_tex_y_b:new t.Uniform1f(e,i.u_tex_y_b),u_mix:new t.Uniform1f(e,i.u_mix)}),raster:(e,i)=>({u_tl_parent:new t.Uniform2f(e,i.u_tl_parent),u_scale_parent:new t.Uniform1f(e,i.u_scale_parent),u_buffer_scale:new t.Uniform1f(e,i.u_buffer_scale),u_fade_t:new t.Uniform1f(e,i.u_fade_t),u_opacity:new t.Uniform1f(e,i.u_opacity),u_image0:new t.Uniform1i(e,i.u_image0),u_image1:new t.Uniform1i(e,i.u_image1),u_brightness_low:new t.Uniform1f(e,i.u_brightness_low),u_brightness_high:new t.Uniform1f(e,i.u_brightness_high),u_saturation_factor:new t.Uniform1f(e,i.u_saturation_factor),u_contrast_factor:new t.Uniform1f(e,i.u_contrast_factor),u_spin_weights:new t.Uniform3f(e,i.u_spin_weights),u_coords_top:new t.Uniform4f(e,i.u_coords_top),u_coords_bottom:new t.Uniform4f(e,i.u_coords_bottom)}),symbolIcon:(e,i)=>({u_is_size_zoom_constant:new t.Uniform1i(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.Uniform1i(e,i.u_is_size_feature_constant),u_size_t:new t.Uniform1f(e,i.u_size_t),u_size:new t.Uniform1f(e,i.u_size),u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_pitch:new t.Uniform1f(e,i.u_pitch),u_rotate_symbol:new t.Uniform1i(e,i.u_rotate_symbol),u_aspect_ratio:new t.Uniform1f(e,i.u_aspect_ratio),u_fade_change:new t.Uniform1f(e,i.u_fade_change),u_label_plane_matrix:new t.UniformMatrix4f(e,i.u_label_plane_matrix),u_coord_matrix:new t.UniformMatrix4f(e,i.u_coord_matrix),u_is_text:new t.Uniform1i(e,i.u_is_text),u_pitch_with_map:new t.Uniform1i(e,i.u_pitch_with_map),u_is_along_line:new t.Uniform1i(e,i.u_is_along_line),u_is_variable_anchor:new t.Uniform1i(e,i.u_is_variable_anchor),u_texsize:new t.Uniform2f(e,i.u_texsize),u_texture:new t.Uniform1i(e,i.u_texture),u_translation:new t.Uniform2f(e,i.u_translation),u_pitched_scale:new t.Uniform1f(e,i.u_pitched_scale)}),symbolSDF:(e,i)=>({u_is_size_zoom_constant:new t.Uniform1i(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.Uniform1i(e,i.u_is_size_feature_constant),u_size_t:new t.Uniform1f(e,i.u_size_t),u_size:new t.Uniform1f(e,i.u_size),u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_pitch:new t.Uniform1f(e,i.u_pitch),u_rotate_symbol:new t.Uniform1i(e,i.u_rotate_symbol),u_aspect_ratio:new t.Uniform1f(e,i.u_aspect_ratio),u_fade_change:new t.Uniform1f(e,i.u_fade_change),u_label_plane_matrix:new t.UniformMatrix4f(e,i.u_label_plane_matrix),u_coord_matrix:new t.UniformMatrix4f(e,i.u_coord_matrix),u_is_text:new t.Uniform1i(e,i.u_is_text),u_pitch_with_map:new t.Uniform1i(e,i.u_pitch_with_map),u_is_along_line:new t.Uniform1i(e,i.u_is_along_line),u_is_variable_anchor:new t.Uniform1i(e,i.u_is_variable_anchor),u_texsize:new t.Uniform2f(e,i.u_texsize),u_texture:new t.Uniform1i(e,i.u_texture),u_gamma_scale:new t.Uniform1f(e,i.u_gamma_scale),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_is_halo:new t.Uniform1i(e,i.u_is_halo),u_translation:new t.Uniform2f(e,i.u_translation),u_pitched_scale:new t.Uniform1f(e,i.u_pitched_scale)}),symbolTextAndIcon:(e,i)=>({u_is_size_zoom_constant:new t.Uniform1i(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.Uniform1i(e,i.u_is_size_feature_constant),u_size_t:new t.Uniform1f(e,i.u_size_t),u_size:new t.Uniform1f(e,i.u_size),u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_pitch:new t.Uniform1f(e,i.u_pitch),u_rotate_symbol:new t.Uniform1i(e,i.u_rotate_symbol),u_aspect_ratio:new t.Uniform1f(e,i.u_aspect_ratio),u_fade_change:new t.Uniform1f(e,i.u_fade_change),u_label_plane_matrix:new t.UniformMatrix4f(e,i.u_label_plane_matrix),u_coord_matrix:new t.UniformMatrix4f(e,i.u_coord_matrix),u_is_text:new t.Uniform1i(e,i.u_is_text),u_pitch_with_map:new t.Uniform1i(e,i.u_pitch_with_map),u_is_along_line:new t.Uniform1i(e,i.u_is_along_line),u_is_variable_anchor:new t.Uniform1i(e,i.u_is_variable_anchor),u_texsize:new t.Uniform2f(e,i.u_texsize),u_texsize_icon:new t.Uniform2f(e,i.u_texsize_icon),u_texture:new t.Uniform1i(e,i.u_texture),u_texture_icon:new t.Uniform1i(e,i.u_texture_icon),u_gamma_scale:new t.Uniform1f(e,i.u_gamma_scale),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_is_halo:new t.Uniform1i(e,i.u_is_halo),u_translation:new t.Uniform2f(e,i.u_translation),u_pitched_scale:new t.Uniform1f(e,i.u_pitched_scale)}),background:(e,i)=>({u_opacity:new t.Uniform1f(e,i.u_opacity),u_color:new t.UniformColor(e,i.u_color)}),backgroundPattern:(e,i)=>({u_opacity:new t.Uniform1f(e,i.u_opacity),u_image:new t.Uniform1i(e,i.u_image),u_pattern_tl_a:new t.Uniform2f(e,i.u_pattern_tl_a),u_pattern_br_a:new t.Uniform2f(e,i.u_pattern_br_a),u_pattern_tl_b:new t.Uniform2f(e,i.u_pattern_tl_b),u_pattern_br_b:new t.Uniform2f(e,i.u_pattern_br_b),u_texsize:new t.Uniform2f(e,i.u_texsize),u_mix:new t.Uniform1f(e,i.u_mix),u_pattern_size_a:new t.Uniform2f(e,i.u_pattern_size_a),u_pattern_size_b:new t.Uniform2f(e,i.u_pattern_size_b),u_scale_a:new t.Uniform1f(e,i.u_scale_a),u_scale_b:new t.Uniform1f(e,i.u_scale_b),u_pixel_coord_upper:new t.Uniform2f(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.Uniform2f(e,i.u_pixel_coord_lower),u_tile_units_to_pixels:new t.Uniform1f(e,i.u_tile_units_to_pixels)}),terrain:(e,i)=>({u_texture:new t.Uniform1i(e,i.u_texture),u_ele_delta:new t.Uniform1f(e,i.u_ele_delta),u_fog_matrix:new t.UniformMatrix4f(e,i.u_fog_matrix),u_fog_color:new t.UniformColor(e,i.u_fog_color),u_fog_ground_blend:new t.Uniform1f(e,i.u_fog_ground_blend),u_fog_ground_blend_opacity:new t.Uniform1f(e,i.u_fog_ground_blend_opacity),u_horizon_color:new t.UniformColor(e,i.u_horizon_color),u_horizon_fog_blend:new t.Uniform1f(e,i.u_horizon_fog_blend),u_is_globe_mode:new t.Uniform1f(e,i.u_is_globe_mode)}),terrainDepth:(e,i)=>({u_ele_delta:new t.Uniform1f(e,i.u_ele_delta)}),terrainCoords:(e,i)=>({u_texture:new t.Uniform1i(e,i.u_texture),u_terrain_coords_id:new t.Uniform1f(e,i.u_terrain_coords_id),u_ele_delta:new t.Uniform1f(e,i.u_ele_delta)}),projectionErrorMeasurement:(e,i)=>({u_input:new t.Uniform1f(e,i.u_input),u_output_expected:new t.Uniform1f(e,i.u_output_expected)}),atmosphere:(e,i)=>({u_sun_pos:new t.Uniform3f(e,i.u_sun_pos),u_atmosphere_blend:new t.Uniform1f(e,i.u_atmosphere_blend),u_globe_position:new t.Uniform3f(e,i.u_globe_position),u_globe_radius:new t.Uniform1f(e,i.u_globe_radius),u_inv_proj_matrix:new t.UniformMatrix4f(e,i.u_inv_proj_matrix)}),sky:(e,i)=>({u_sky_color:new t.UniformColor(e,i.u_sky_color),u_horizon_color:new t.UniformColor(e,i.u_horizon_color),u_horizon:new t.Uniform2f(e,i.u_horizon),u_horizon_normal:new t.Uniform2f(e,i.u_horizon_normal),u_sky_horizon_blend:new t.Uniform1f(e,i.u_sky_horizon_blend),u_sky_blend:new t.Uniform1f(e,i.u_sky_blend)})};class sr{constructor(e,t,i){this.context=e;const r=e.gl;this.buffer=r.createBuffer(),this.dynamicDraw=Boolean(i),this.context.unbindVAO(),e.bindElementBuffer.set(this.buffer),r.bufferData(r.ELEMENT_ARRAY_BUFFER,t.arrayBuffer,this.dynamicDraw?r.DYNAMIC_DRAW:r.STATIC_DRAW),this.dynamicDraw||delete t.arrayBuffer;}bind(){this.context.bindElementBuffer.set(this.buffer);}updateData(e){const t=this.context.gl;if(!this.dynamicDraw)throw new Error("Attempted to update data while not in dynamic mode.");this.context.unbindVAO(),this.bind(),t.bufferSubData(t.ELEMENT_ARRAY_BUFFER,0,e.arrayBuffer);}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer);}}const nr={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class lr{constructor(e,t,i,r){this.length=t.length,this.attributes=i,this.itemSize=t.bytesPerElement,this.dynamicDraw=r,this.context=e;const o=e.gl;this.buffer=o.createBuffer(),e.bindVertexBuffer.set(this.buffer),o.bufferData(o.ARRAY_BUFFER,t.arrayBuffer,this.dynamicDraw?o.DYNAMIC_DRAW:o.STATIC_DRAW),this.dynamicDraw||delete t.arrayBuffer;}bind(){this.context.bindVertexBuffer.set(this.buffer);}updateData(e){if(e.length!==this.length)throw new Error(`Length of new data is ${e.length}, which doesn't match current length of ${this.length}`);const t=this.context.gl;this.bind(),t.bufferSubData(t.ARRAY_BUFFER,0,e.arrayBuffer);}enableAttributes(e,t){for(let i=0;i0&&(h.push({circleArray:f,circleOffset:d,coord:_}),u+=f.length/4,d=u),m&&c.draw(s,l.LINES,Zt.disabled,qt.disabled,e.colorModeForRenderPass(),Gt.disabled,Bi(e.transform),e.style.map.terrain&&e.style.map.terrain.getTerrainData(_),n.getProjectionData({overscaledTileID:_,applyGlobeMatrix:!0,applyTerrainMatrix:!0}),r.id,m.layoutVertexBuffer,m.indexBuffer,m.segments,null,e.transform.zoom,null,null,m.collisionVertexBuffer);}if(!a||!h.length)return;const _=e.useProgram("collisionCircle"),p=new t.CollisionCircleLayoutArray;p.resize(4*u),p._trim();let m=0;for(const e of h)for(let t=0;t=0&&(f[g.associatedIconIndex]={shiftedAnchor:M,angle:S});}else Ve(g.numGlyphs,p);}if(c){m.clear();const i=e.icon.placedSymbolArray;for(let e=0;ee.style.map.terrain.getElevation(l,t,i):null,i="map"===r.layout.get("text-rotation-alignment");De(c,e,a,O,U,v,h,i,l.toUnwrapped(),f.width,f.height,N,t);}const q=a&&E||V,W=y||q?Hr:v?O:e.transform.clipSpaceToPixelsMatrix,X=p&&0!==r.paint.get(a?"text-halo-width":"icon-halo-width").constantOr(1);let $;$=p?c.iconsInText?tr(T.kind,S,x,v,y,q,e,W,j,N,D,k,I):er(T.kind,S,x,v,y,q,e,W,j,N,a,D,!0,I):Qi(T.kind,S,x,v,y,q,e,W,j,N,a,D,I);const H={program:M,buffers:u,uniformValues:$,projectionData:G,atlasTexture:z,atlasTextureIcon:F,atlasInterpolation:L,atlasInterpolationIcon:A,isSDF:p,hasHalo:X};if(b&&c.canOverlap){w=!0;const e=u.segments.get();for(const i of e)P.push({segments:new t.SegmentVector([i]),sortKey:i.sortKey,state:H,terrainData:R});}else P.push({segments:u.segments,sortKey:0,state:H,terrainData:R});}w&&P.sort(((e,t)=>e.sortKey-t.sortKey));for(const t of P){const i=t.state;if(p.activeTexture.set(m.TEXTURE0),i.atlasTexture.bind(i.atlasInterpolation,m.CLAMP_TO_EDGE),i.atlasTextureIcon&&(p.activeTexture.set(m.TEXTURE1),i.atlasTextureIcon&&i.atlasTextureIcon.bind(i.atlasInterpolationIcon,m.CLAMP_TO_EDGE)),i.isSDF){const o=i.uniformValues;i.hasHalo&&(o.u_is_halo=1,to(i.buffers,t.segments,r,e,i.program,T,u,d,o,i.projectionData,t.terrainData)),o.u_is_halo=0;}to(i.buffers,t.segments,r,e,i.program,T,u,d,i.uniformValues,i.projectionData,t.terrainData);}}function to(e,t,i,r,o,a,s,n,l,c,h){const u=r.context;o.draw(u,u.gl.TRIANGLES,a,s,n,Gt.backCCW,l,h,c,i.id,e.layoutVertexBuffer,e.indexBuffer,t,i.paint,r.transform.zoom,e.programConfigurations.get(i.id),e.dynamicLayoutVertexBuffer,e.opacityVertexBuffer);}function io(e,i,r,o,a){const s=e.context,n=s.gl,l=qt.disabled,c=new jt([n.ONE,n.ONE],t.Color.transparent,[!0,!0,!0,!0]),h=i.getBucket(r);if(!h)return;const u=o.key;let d=r.heatmapFbos.get(u);d||(d=oo(s,i.tileSize,i.tileSize),r.heatmapFbos.set(u,d)),s.bindFramebuffer.set(d.framebuffer),s.viewport.set([0,0,i.tileSize,i.tileSize]),s.clear({color:t.Color.transparent});const _=h.programConfigurations.get(r.id),p=e.useProgram("heatmap",_,!a),m=e.transform.getProjectionData({overscaledTileID:i.tileID,applyGlobeMatrix:!0,applyTerrainMatrix:!0}),f=e.style.map.terrain.getTerrainData(o);p.draw(s,n.TRIANGLES,Zt.disabled,l,c,Gt.disabled,ji(i,e.transform.zoom,r.paint.get("heatmap-intensity"),1),f,m,r.id,h.layoutVertexBuffer,h.indexBuffer,h.segments,r.paint,e.transform.zoom,_);}function ro(e,t,i,r,o){const a=e.context,s=a.gl,n=e.transform;a.setColorMode(e.colorModeForRenderPass());const l=ao(a,t),c=i.key,h=t.heatmapFbos.get(c);if(!h)return;a.activeTexture.set(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,h.colorAttachment.get()),a.activeTexture.set(s.TEXTURE1),l.bind(s.LINEAR,s.CLAMP_TO_EDGE);const u=n.getProjectionData({overscaledTileID:i,applyTerrainMatrix:o,applyGlobeMatrix:!r});e.useProgram("heatmapTexture").draw(a,s.TRIANGLES,Zt.disabled,qt.disabled,e.colorModeForRenderPass(),Gt.disabled,Ni(e,t,0,1),null,u,t.id,e.rasterBoundsBuffer,e.quadTriangleIndexBuffer,e.rasterBoundsSegments,t.paint,n.zoom),h.destroy(),t.heatmapFbos.delete(c);}function oo(e,t,i){var r,o;const a=e.gl,s=a.createTexture();a.bindTexture(a.TEXTURE_2D,s),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,a.LINEAR);const n=null!==(r=e.HALF_FLOAT)&&void 0!==r?r:a.UNSIGNED_BYTE,l=null!==(o=e.RGBA16F)&&void 0!==o?o:a.RGBA;a.texImage2D(a.TEXTURE_2D,0,l,t,i,0,a.RGBA,n,null);const c=e.createFramebuffer(t,i,!1,!1);return c.colorAttachment.set(s),c}function ao(e,t){return t.colorRampTexture||(t.colorRampTexture=new y(e,t.colorRamp,e.gl.RGBA)),t.colorRampTexture}function so(e,t,i,r,o){if(!i||!r||!r.imageAtlas)return;const a=r.imageAtlas.patternPositions;let s=a[i.to.toString()],n=a[i.from.toString()];if(!s&&n&&(s=n),!n&&s&&(n=s),!s||!n){const e=o.getPaintProperty(t);s=a[e],n=a[e];}s&&n&&e.setConstantPatternPositions(s,n);}function no(e,i,r,o,a,s,n,l){const c=e.context.gl,h="fill-pattern",u=r.paint.get(h),d=u&&u.constantOr(1),_=r.getCrossfadeParameters();let p,m,f,g,v;const y=e.transform,x=r.paint.get("fill-translate"),b=r.paint.get("fill-translate-anchor");n?(m=d&&!r.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",p=c.LINES):(m=d?"fillPattern":"fill",p=c.TRIANGLES);const w=u.constantOr(null);for(const u of o){const T=i.getTile(u);if(d&&!T.patternsLoaded())continue;const E=T.getBucket(r);if(!E)continue;const P=E.programConfigurations.get(r.id),I=e.useProgram(m,P),C=e.style.map.terrain&&e.style.map.terrain.getTerrainData(u);d&&(e.context.activeTexture.set(c.TEXTURE0),T.imageAtlasTexture.bind(c.LINEAR,c.CLAMP_TO_EDGE),P.updatePaintBuffers(_)),so(P,h,w,T,r);const M=y.getProjectionData({overscaledTileID:u,applyGlobeMatrix:!l,applyTerrainMatrix:!0}),S=t.translatePosition(y,T,x,b);if(n){g=E.indexBuffer2,v=E.segments2;const t=[c.drawingBufferWidth,c.drawingBufferHeight];f="fillOutlinePattern"===m&&d?ki(e,_,T,t,S):Ai(t,S);}else g=E.indexBuffer,v=E.segments,f=d?Li(e,_,T,S):{u_fill_translate:S};let R;if("translucent"===e.renderPass&&l){const[t]=e.getStencilConfigForOverlapAndUpdateStencilID(o);R=t[u.overscaledZ];}else R=e.stencilModeForClipping(u);I.draw(e.context,p,a,R,s,Gt.backCCW,f,C,M,r.id,E.layoutVertexBuffer,g,v,r.paint,e.transform.zoom,P);}}function lo(e,i,r,o,a,s,n,l){const c=e.context,h=c.gl,u="fill-extrusion-pattern",d=r.paint.get(u),_=d.constantOr(1),p=r.getCrossfadeParameters(),m=r.paint.get("fill-extrusion-opacity"),f=d.constantOr(null),g=e.transform;for(const d of o){const o=i.getTile(d),v=o.getBucket(r);if(!v)continue;const y=e.style.map.terrain&&e.style.map.terrain.getTerrainData(d),x=v.programConfigurations.get(r.id),b=e.useProgram(_?"fillExtrusionPattern":"fillExtrusion",x);_&&(e.context.activeTexture.set(h.TEXTURE0),o.imageAtlasTexture.bind(h.LINEAR,h.CLAMP_TO_EDGE),x.updatePaintBuffers(p));const w=g.getProjectionData({overscaledTileID:d,applyGlobeMatrix:!l,applyTerrainMatrix:!0});so(x,u,f,o,r);const T=t.translatePosition(g,o,r.paint.get("fill-extrusion-translate"),r.paint.get("fill-extrusion-translate-anchor")),E=r.paint.get("fill-extrusion-vertical-gradient"),P=_?zi(e,E,m,T,d,p,o):Di(e,E,m,T);b.draw(c,c.gl.TRIANGLES,a,s,n,Gt.backCCW,P,y,w,r.id,v.layoutVertexBuffer,v.indexBuffer,v.segments,r.paint,e.transform.zoom,x,e.style.map.terrain&&v.centroidVertexBuffer);}}function co(e,t,i,r,o,a,s,n,l){var c;const h=e.style.projection,u=e.context,d=e.transform,_=u.gl,p=e.useProgram("hillshade"),m=!e.options.moving;for(const f of r){const r=t.getTile(f),g=r.fbo;if(!g)continue;const v=h.getMeshFromTileID(u,f.canonical,n,!0,"raster"),y=null===(c=e.style.map.terrain)||void 0===c?void 0:c.getTerrainData(f);u.activeTexture.set(_.TEXTURE0),_.bindTexture(_.TEXTURE_2D,g.colorAttachment.get());const x=d.getProjectionData({overscaledTileID:f,aligned:m,applyGlobeMatrix:!l,applyTerrainMatrix:!0});p.draw(u,_.TRIANGLES,a,o[f.overscaledZ],s,Gt.backCCW,Gi(e,r,i),y,x,i.id,v.vertexBuffer,v.indexBuffer,v.segments);}}const ho=[new t.Point(0,0),new t.Point(t.EXTENT,0),new t.Point(t.EXTENT,t.EXTENT),new t.Point(0,t.EXTENT)];function uo(e,t,i,r,o,a,s,n,l=!1,c=!1){const h=r[r.length-1].overscaledZ,u=e.context,d=u.gl,_=e.useProgram("raster"),p=e.transform,m=e.style.projection,f=e.colorModeForRenderPass(),g=!e.options.moving;for(const v of r){const r=e.getDepthModeForSublayer(v.overscaledZ-h,1===i.paint.get("raster-opacity")?Zt.ReadWrite:Zt.ReadOnly,d.LESS),y=t.getTile(v);y.registerFadeDuration(i.paint.get("raster-fade-duration"));const x=t.findLoadedParent(v,0),b=t.findLoadedSibling(v),w=_o(y,x||b||null,t,i,e.transform,e.style.map.terrain);let T,E;const P="nearest"===i.paint.get("raster-resampling")?d.NEAREST:d.LINEAR;u.activeTexture.set(d.TEXTURE0),y.texture.bind(P,d.CLAMP_TO_EDGE,d.LINEAR_MIPMAP_NEAREST),u.activeTexture.set(d.TEXTURE1),x?(x.texture.bind(P,d.CLAMP_TO_EDGE,d.LINEAR_MIPMAP_NEAREST),T=Math.pow(2,x.tileID.overscaledZ-y.tileID.overscaledZ),E=[y.tileID.canonical.x*T%1,y.tileID.canonical.y*T%1]):y.texture.bind(P,d.CLAMP_TO_EDGE,d.LINEAR_MIPMAP_NEAREST),y.texture.useMipmap&&u.extTextureFilterAnisotropic&&e.transform.pitch>20&&d.texParameterf(d.TEXTURE_2D,u.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,u.extTextureFilterAnisotropicMax);const I=e.style.map.terrain&&e.style.map.terrain.getTerrainData(v),C=p.getProjectionData({overscaledTileID:v,aligned:g,applyGlobeMatrix:!c,applyTerrainMatrix:!0}),M=Yi(E||[0,0],T||1,w,i,n),S=m.getMeshFromTileID(u,v.canonical,a,s,"raster");_.draw(u,d.TRIANGLES,r,o?o[v.overscaledZ]:qt.disabled,f,l?Gt.frontCCW:Gt.backCCW,M,I,C,i.id,S.vertexBuffer,S.indexBuffer,S.segments);}}function _o(e,i,r,o,a,s){const n=o.paint.get("raster-fade-duration");if(!s&&n>0){const o=f.now(),s=(o-e.timeAdded)/n,l=i?(o-i.timeAdded)/n:-1,c=r.getSource(),h=ge(a,{tileSize:c.tileSize,roundZoom:c.roundZoom}),u=!i||Math.abs(i.tileID.overscaledZ-h)>Math.abs(e.tileID.overscaledZ-h),d=u&&e.refreshedUponExpiration?1:t.clamp(u?s:1-l,0,1);return e.refreshedUponExpiration&&s>=1&&(e.refreshedUponExpiration=!1),i?{opacity:1,mix:1-d}:{opacity:d,mix:0}}return {opacity:1,mix:0}}const po=new t.Color(1,0,0,1),mo=new t.Color(0,1,0,1),fo=new t.Color(0,0,1,1),go=new t.Color(1,0,1,1),vo=new t.Color(0,1,1,1);function yo(e,t,i,r){bo(e,0,t+i/2,e.transform.width,i,r);}function xo(e,t,i,r){bo(e,t-i/2,0,i,e.transform.height,r);}function bo(e,t,i,r,o,a){const s=e.context,n=s.gl;n.enable(n.SCISSOR_TEST),n.scissor(t*e.pixelRatio,i*e.pixelRatio,r*e.pixelRatio,o*e.pixelRatio),s.clear({color:a}),n.disable(n.SCISSOR_TEST);}function wo(e,i,r){const o=e.context,a=o.gl,s=e.useProgram("debug"),n=Zt.disabled,l=qt.disabled,c=e.colorModeForRenderPass(),h="$debug",u=e.style.map.terrain&&e.style.map.terrain.getTerrainData(r);o.activeTexture.set(a.TEXTURE0);const d=i.getTileByID(r.key).latestRawTileData,_=Math.floor((d&&d.byteLength||0)/1024),p=i.getTile(r).tileSize,m=512/Math.min(p,512)*(r.overscaledZ/e.transform.zoom)*.5;let f=r.canonical.toString();r.overscaledZ!==r.canonical.z&&(f+=` => ${r.overscaledZ}`),function(e,t){e.initDebugOverlayCanvas();const i=e.debugOverlayCanvas,r=e.context.gl,o=e.debugOverlayCanvas.getContext("2d");o.clearRect(0,0,i.width,i.height),o.shadowColor="white",o.shadowBlur=2,o.lineWidth=1.5,o.strokeStyle="white",o.textBaseline="top",o.font="bold 36px Open Sans, sans-serif",o.fillText(t,5,5),o.strokeText(t,5,5),e.debugOverlayTexture.update(i),e.debugOverlayTexture.bind(r.LINEAR,r.CLAMP_TO_EDGE);}(e,`${f} ${_}kB`);const g=e.transform.getProjectionData({overscaledTileID:r,applyGlobeMatrix:!0,applyTerrainMatrix:!0});s.draw(o,a.TRIANGLES,n,l,jt.alphaBlended,Gt.disabled,Ui(t.Color.transparent,m),null,g,h,e.debugBuffer,e.quadTriangleIndexBuffer,e.debugSegments),s.draw(o,a.LINE_STRIP,n,l,c,Gt.disabled,Ui(t.Color.red),u,g,h,e.debugBuffer,e.tileBorderIndexBuffer,e.debugSegments);}function To(e,t,i,r){const{isRenderingGlobe:o}=r,a=e.context,s=a.gl,n=e.transform,l=e.colorModeForRenderPass(),c=e.getDepthModeFor3D(),h=e.useProgram("terrain"),u=t.getTerrainMesh();a.bindFramebuffer.set(null),a.viewport.set([0,0,e.width,e.height]);for(const r of i){const i=e.renderToTexture.getTexture(r),d=t.getTerrainData(r.tileID);a.activeTexture.set(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,i.texture);const _=t.getMeshFrameDelta(n.zoom),p=n.calculateFogMatrix(r.tileID.toUnwrapped()),m=Ii(_,p,e.style.sky,n.pitch,o),f=n.getProjectionData({overscaledTileID:r.tileID,applyTerrainMatrix:!1,applyGlobeMatrix:!0});h.draw(a,s.TRIANGLES,c,qt.disabled,l,Gt.backCCW,m,d,f,"terrain",u.vertexBuffer,u.indexBuffer,u.segments);}}function Eo(e,i){if(!i.mesh){const r=new t.PosArray;r.emplaceBack(-1,-1),r.emplaceBack(1,-1),r.emplaceBack(1,1),r.emplaceBack(-1,1);const o=new t.TriangleIndexArray;o.emplaceBack(0,1,2),o.emplaceBack(0,2,3),i.mesh=new bt(e.createVertexBuffer(r,wt.members),e.createIndexBuffer(o),t.SegmentVector.simpleSegment(0,0,r.length,o.length));}return i.mesh}class Po{constructor(e,i){this.context=new Wr(e),this.transform=i,this._tileTextures={},this.terrainFacilitator={dirty:!0,matrix:t.identity(new Float64Array(16)),renderTime:0},this.setup(),this.numSublayers=ye.maxUnderzooming+ye.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.crossTileSymbolIndex=new gt;}resize(e,t,i){if(this.width=Math.floor(e*i),this.height=Math.floor(t*i),this.pixelRatio=i,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const e of this.style._order)this.style._layers[e].resize();}setup(){const e=this.context,i=new t.PosArray;i.emplaceBack(0,0),i.emplaceBack(t.EXTENT,0),i.emplaceBack(0,t.EXTENT),i.emplaceBack(t.EXTENT,t.EXTENT),this.tileExtentBuffer=e.createVertexBuffer(i,wt.members),this.tileExtentSegments=t.SegmentVector.simpleSegment(0,0,4,2);const r=new t.PosArray;r.emplaceBack(0,0),r.emplaceBack(t.EXTENT,0),r.emplaceBack(0,t.EXTENT),r.emplaceBack(t.EXTENT,t.EXTENT),this.debugBuffer=e.createVertexBuffer(r,wt.members),this.debugSegments=t.SegmentVector.simpleSegment(0,0,4,5);const o=new t.RasterBoundsArray;o.emplaceBack(0,0,0,0),o.emplaceBack(t.EXTENT,0,t.EXTENT,0),o.emplaceBack(0,t.EXTENT,0,t.EXTENT),o.emplaceBack(t.EXTENT,t.EXTENT,t.EXTENT,t.EXTENT),this.rasterBoundsBuffer=e.createVertexBuffer(o,Ei.members),this.rasterBoundsSegments=t.SegmentVector.simpleSegment(0,0,4,2);const a=new t.PosArray;a.emplaceBack(0,0),a.emplaceBack(t.EXTENT,0),a.emplaceBack(0,t.EXTENT),a.emplaceBack(t.EXTENT,t.EXTENT),this.rasterBoundsBufferPosOnly=e.createVertexBuffer(a,wt.members),this.rasterBoundsSegmentsPosOnly=t.SegmentVector.simpleSegment(0,0,4,5);const s=new t.PosArray;s.emplaceBack(0,0),s.emplaceBack(1,0),s.emplaceBack(0,1),s.emplaceBack(1,1),this.viewportBuffer=e.createVertexBuffer(s,wt.members),this.viewportSegments=t.SegmentVector.simpleSegment(0,0,4,2);const n=new t.LineStripIndexArray;n.emplaceBack(0),n.emplaceBack(1),n.emplaceBack(3),n.emplaceBack(2),n.emplaceBack(0),this.tileBorderIndexBuffer=e.createIndexBuffer(n);const l=new t.TriangleIndexArray;l.emplaceBack(1,0,2),l.emplaceBack(1,2,3),this.quadTriangleIndexBuffer=e.createIndexBuffer(l);const c=this.context.gl;this.stencilClearMode=new qt({func:c.ALWAYS,mask:0},0,255,c.ZERO,c.ZERO,c.ZERO),this.tileExtentMesh=new bt(this.tileExtentBuffer,this.quadTriangleIndexBuffer,this.tileExtentSegments);}clearStencil(){const e=this.context,i=e.gl;this.nextStencilID=1,this.currentStencilSource=void 0;const r=t.create();t.ortho(r,0,this.width,this.height,0,0,1),t.scale(r,r,[i.drawingBufferWidth,i.drawingBufferHeight,0]);const o={mainMatrix:r,tileMercatorCoords:[0,0,1,1],clippingPlane:[0,0,0,0],projectionTransition:0,fallbackMatrix:r};this.useProgram("clippingMask",null,!0).draw(e,i.TRIANGLES,Zt.disabled,this.stencilClearMode,jt.disabled,Gt.disabled,null,null,o,"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments);}_renderTileClippingMasks(e,t,i){if(this.currentStencilSource===e.source||!e.isTileClipped()||!t||!t.length)return;this.currentStencilSource=e.source,this.nextStencilID+t.length>256&&this.clearStencil();const r=this.context;r.setColorMode(jt.disabled),r.setDepthMode(Zt.disabled);const o={};for(const e of t)o[e.key]=this.nextStencilID++;this._renderTileMasks(o,t,i,!0),this._renderTileMasks(o,t,i,!1),this._tileClippingMaskIDs=o;}_renderTileMasks(e,t,i,r){const o=this.context,a=o.gl,s=this.style.projection,n=this.transform,l=this.useProgram("clippingMask");for(const c of t){const t=e[c.key],h=this.style.map.terrain&&this.style.map.terrain.getTerrainData(c),u=s.getMeshFromTileID(this.context,c.canonical,r,!0,"stencil"),d=n.getProjectionData({overscaledTileID:c,applyGlobeMatrix:!0,applyTerrainMatrix:!0});l.draw(o,a.TRIANGLES,Zt.disabled,new qt({func:a.ALWAYS,mask:0},t,255,a.KEEP,a.KEEP,a.REPLACE),jt.disabled,i?Gt.disabled:Gt.backCCW,null,h,d,"$clipping",u.vertexBuffer,u.indexBuffer,u.segments);}}_renderTilesDepthBuffer(){const e=this.context,t=e.gl,i=this.style.projection,r=this.transform,o=this.useProgram("depth"),a=this.getDepthModeFor3D(),s=ve(r,{tileSize:r.tileSize});for(const n of s){const s=this.style.map.terrain&&this.style.map.terrain.getTerrainData(n),l=i.getMeshFromTileID(this.context,n.canonical,!0,!0,"raster"),c=r.getProjectionData({overscaledTileID:n,applyGlobeMatrix:!0,applyTerrainMatrix:!0});o.draw(e,t.TRIANGLES,a,qt.disabled,jt.disabled,Gt.backCCW,null,s,c,"$clipping",l.vertexBuffer,l.indexBuffer,l.segments);}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();const e=this.nextStencilID++,t=this.context.gl;return new qt({func:t.NOTEQUAL,mask:255},e,255,t.KEEP,t.KEEP,t.REPLACE)}stencilModeForClipping(e){const t=this.context.gl;return new qt({func:t.EQUAL,mask:255},this._tileClippingMaskIDs[e.key],0,t.KEEP,t.KEEP,t.REPLACE)}getStencilConfigForOverlapAndUpdateStencilID(e){const t=this.context.gl,i=e.sort(((e,t)=>t.overscaledZ-e.overscaledZ)),r=i[i.length-1].overscaledZ,o=i[0].overscaledZ-r+1;if(o>1){this.currentStencilSource=void 0,this.nextStencilID+o>256&&this.clearStencil();const e={};for(let i=0;it.overscaledZ-e.overscaledZ)),r=i[i.length-1].overscaledZ,o=i[0].overscaledZ-r+1;if(this.clearStencil(),o>1){const e={},a={};for(let i=0;ithis.useProgram(e)}),this.context.viewport.set([0,0,this.width,this.height]),this.context.bindFramebuffer.set(null),this.context.clear({color:i.showOverdrawInspector?t.Color.black:t.Color.transparent,depth:1}),this.clearStencil(),this.style.sky&&function(e,t){const i=e.context,r=i.gl,o=((e,t,i)=>{const r=Math.cos(t.rollInRadians),o=Math.sin(t.rollInRadians),a=Rt(t),s=t.getProjectionData({overscaledTileID:null,applyGlobeMatrix:!0,applyTerrainMatrix:!0}).projectionTransition;return {u_sky_color:e.properties.get("sky-color"),u_horizon_color:e.properties.get("horizon-color"),u_horizon:[(t.width/2-a*o)*i,(t.height/2+a*r)*i],u_horizon_normal:[-o,r],u_sky_horizon_blend:e.properties.get("sky-horizon-blend")*t.height/2*i,u_sky_blend:s}})(t,e.style.map.transform,e.pixelRatio),a=new Zt(r.LEQUAL,Zt.ReadWrite,[0,1]),s=qt.disabled,n=e.colorModeForRenderPass(),l=e.useProgram("sky"),c=Eo(i,t);l.draw(i,r.TRIANGLES,a,s,n,Gt.disabled,o,null,void 0,"sky",c.vertexBuffer,c.indexBuffer,c.segments);}(this,this.style.sky),this._showOverdrawInspector=i.showOverdrawInspector,this.depthRangeFor3D=[0,1-(e._order.length+2)*this.numSublayers*this.depthEpsilon],!this.renderToTexture)for(this.renderPass="opaque",this.currentLayer=r.length-1;this.currentLayer>=0;this.currentLayer--){const e=this.style._layers[r[this.currentLayer]],t=o[e.source],i=a[e.source];this._renderTileClippingMasks(e,i,!1),this.renderLayer(this,t,e,i,l);}this.renderPass="translucent";let c=!1;for(this.currentLayer=0;this.currentLayer({u_sun_pos:e,u_atmosphere_blend:t,u_globe_position:i,u_globe_radius:r,u_inv_proj_matrix:o}))(c,u,[p[0],p[1],p[2]],d,_),f=Eo(o,i);s.draw(o,a.TRIANGLES,n,qt.disabled,jt.alphaBlended,Gt.disabled,m,null,null,"atmosphere",f.vertexBuffer,f.indexBuffer,f.segments);}(this,this.style.sky,this.style.light),this.options.showTileBoundaries){const e=function(e,t){let i=null;const r=Object.values(e._layers).flatMap((i=>i.source&&!i.isHidden(t)?[e.sourceCaches[i.source]]:[])),o=r.filter((e=>"vector"===e.getSource().type)),a=r.filter((e=>"vector"!==e.getSource().type)),s=e=>{(!i||i.getSource().maxzooms(e))),i||a.forEach((e=>s(e))),i}(this.style,this.transform.zoom);e&&function(e,t,i){for(let r=0;ru.getElevation(a,e,t):null;Jr(s,d,_,c,h,f,i,p,g,t.translatePosition(h,e,n,l),a.toUnwrapped(),r);}}}(o,e,r,i,r.layout.get("text-rotation-alignment"),r.layout.get("text-pitch-alignment"),r.paint.get("text-translate"),r.paint.get("text-translate-anchor"),a),0!==r.paint.get("icon-opacity").constantOr(1)&&eo(e,i,r,o,!1,r.paint.get("icon-translate"),r.paint.get("icon-translate-anchor"),r.layout.get("icon-rotation-alignment"),r.layout.get("icon-pitch-alignment"),r.layout.get("icon-keep-upright"),l,c,n),0!==r.paint.get("text-opacity").constantOr(1)&&eo(e,i,r,o,!0,r.paint.get("text-translate"),r.paint.get("text-translate-anchor"),r.layout.get("text-rotation-alignment"),r.layout.get("text-pitch-alignment"),r.layout.get("text-keep-upright"),l,c,n),i.map.showCollisionBoxes&&($r(e,i,r,o,!0),$r(e,i,r,o,!1));}(e,i,r,o,this.style.placement.variableOffsets,a):t.isCircleStyleLayer(r)?function(e,i,r,o,a){if("translucent"!==e.renderPass)return;const{isRenderingToTexture:s}=a,n=r.paint.get("circle-opacity"),l=r.paint.get("circle-stroke-width"),c=r.paint.get("circle-stroke-opacity"),h=!r.layout.get("circle-sort-key").isConstant();if(0===n.constantOr(1)&&(0===l.constantOr(1)||0===c.constantOr(1)))return;const u=e.context,d=u.gl,_=e.transform,p=e.getDepthModeForSublayer(0,Zt.ReadOnly),m=qt.disabled,f=e.colorModeForRenderPass(),g=[],v=_.getCircleRadiusCorrection();for(let a=0;ae.sortKey-t.sortKey));for(const t of g){const{programConfiguration:i,program:o,layoutVertexBuffer:a,indexBuffer:s,uniformValues:n,terrainData:l,projectionData:c}=t.state;o.draw(u,d.TRIANGLES,p,m,f,Gt.backCCW,n,l,c,r.id,a,s,t.segments,r.paint,e.transform.zoom,i);}}(e,i,r,o,a):t.isHeatmapStyleLayer(r)?function(e,i,r,o,a){if(0===r.paint.get("heatmap-opacity"))return;const s=e.context,{isRenderingToTexture:n,isRenderingGlobe:l}=a;if(e.style.map.terrain){for(const t of o){const o=i.getTile(t);i.hasRenderableParent(t)||("offscreen"===e.renderPass?io(e,o,r,t,l):"translucent"===e.renderPass&&ro(e,r,t,n,l));}s.viewport.set([0,0,e.width,e.height]);}else "offscreen"===e.renderPass?function(e,i,r,o){const a=e.context,s=a.gl,n=e.transform,l=qt.disabled,c=new jt([s.ONE,s.ONE],t.Color.transparent,[!0,!0,!0,!0]);((function(e,i,r){const o=e.gl;e.activeTexture.set(o.TEXTURE1),e.viewport.set([0,0,i.width/4,i.height/4]);let a=r.heatmapFbos.get(t.HEATMAP_FULL_RENDER_FBO_KEY);a?(o.bindTexture(o.TEXTURE_2D,a.colorAttachment.get()),e.bindFramebuffer.set(a.framebuffer)):(a=oo(e,i.width/4,i.height/4),r.heatmapFbos.set(t.HEATMAP_FULL_RENDER_FBO_KEY,a));}))(a,e,r),a.clear({color:t.Color.transparent});for(let t=0;t0?t.pop():null}isPatternMissing(e){if(!e)return !1;if(!e.from||!e.to)return !0;const t=this.imageManager.getPattern(e.from.toString()),i=this.imageManager.getPattern(e.to.toString());return !t||!i}useProgram(e,t,i=!1){this.cache=this.cache||{};const r=!!this.style.map.terrain,o=this.style.projection,a=e+(t?t.cacheKey:"")+`/${i?Et:o.shaderVariantName}`+(this._showOverdrawInspector?"/overdraw":"")+(r?"/terrain":"");return this.cache[a]||(this.cache[a]=new Si(this.context,yt[e],t,ar[e],this._showOverdrawInspector,r,i?yt.projectionMercator:o.shaderPreludeCode,i?Tt:o.shaderDefine)),this.cache[a]}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 e=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(e.FUNC_ADD);}initDebugOverlayCanvas(){null==this.debugOverlayCanvas&&(this.debugOverlayCanvas=document.createElement("canvas"),this.debugOverlayCanvas.width=512,this.debugOverlayCanvas.height=512,this.debugOverlayTexture=new y(this.context,this.debugOverlayCanvas,this.context.gl.RGBA));}destroy(){this.debugOverlayTexture&&this.debugOverlayTexture.destroy();}overLimit(){const{drawingBufferWidth:e,drawingBufferHeight:t}=this.context.gl;return this.width!==e||this.height!==t}}function Io(e,t){let i,r=!1,o=null,a=null;const s=()=>{o=null,r&&(e.apply(a,i),o=setTimeout(s,t),r=!1);};return (...e)=>(r=!0,a=this,i=e,o||s(),o)}class Co{constructor(e){this._getCurrentHash=()=>{const e=window.location.hash.replace("#","");if(this._hashName){let t;return e.split("&").map((e=>e.split("="))).forEach((e=>{e[0]===this._hashName&&(t=e);})),(t&&t[1]||"").split("/")}return e.split("/")},this._onHashChange=()=>{const e=this._getCurrentHash();if(e.length>=3&&!e.some((e=>isNaN(e)))){const t=this._map.dragRotate.isEnabled()&&this._map.touchZoomRotate.isEnabled()?+(e[3]||0):this._map.getBearing();return this._map.jumpTo({center:[+e[2],+e[1]],zoom:+e[0],bearing:t,pitch:+(e[4]||0)}),!0}return !1},this._updateHashUnthrottled=()=>{const e=window.location.href.replace(/(#.*)?$/,this.getHashString());window.history.replaceState(window.history.state,null,e);},this._removeHash=()=>{const e=this._getCurrentHash();if(0===e.length)return;const t=e.join("/");let i=t;i.split("&").length>0&&(i=i.split("&")[0]),this._hashName&&(i=`${this._hashName}=${t}`);let r=window.location.hash.replace(i,"");r.startsWith("#&")?r=r.slice(0,1)+r.slice(2):"#"===r&&(r="");let o=window.location.href.replace(/(#.+)?$/,r);o=o.replace("&&","&"),window.history.replaceState(window.history.state,null,o);},this._updateHash=Io(this._updateHashUnthrottled,300),this._hashName=e&&encodeURIComponent(e);}addTo(e){return this._map=e,addEventListener("hashchange",this._onHashChange,!1),this._map.on("moveend",this._updateHash),this}remove(){return removeEventListener("hashchange",this._onHashChange,!1),this._map.off("moveend",this._updateHash),clearTimeout(this._updateHash()),this._removeHash(),delete this._map,this}getHashString(e){const t=this._map.getCenter(),i=Math.round(100*this._map.getZoom())/100,r=Math.ceil((i*Math.LN2+Math.log(512/360/.5))/Math.LN10),o=Math.pow(10,r),a=Math.round(t.lng*o)/o,s=Math.round(t.lat*o)/o,n=this._map.getBearing(),l=this._map.getPitch();let c="";if(c+=e?`/${a}/${s}/${i}`:`${i}/${s}/${a}`,(n||l)&&(c+="/"+Math.round(10*n)/10),l&&(c+=`/${Math.round(l)}`),this._hashName){const e=this._hashName;let t=!1;const i=window.location.hash.slice(1).split("&").map((i=>{const r=i.split("=")[0];return r===e?(t=!0,`${r}=${c}`):i})).filter((e=>e));return t||i.push(`${e}=${c}`),`#${i.join("&")}`}return `#${c}`}}const Mo={linearity:.3,easing:t.bezier(0,0,.3,1)},So=t.extend({deceleration:2500,maxSpeed:1400},Mo),Ro=t.extend({deceleration:20,maxSpeed:1400},Mo),Do=t.extend({deceleration:1e3,maxSpeed:360},Mo),zo=t.extend({deceleration:1e3,maxSpeed:90},Mo),Lo=t.extend({deceleration:1e3,maxSpeed:360},Mo);class Ao{constructor(e){this._map=e,this.clear();}clear(){this._inertiaBuffer=[];}record(e){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:f.now(),settings:e});}_drainInertiaBuffer(){const e=this._inertiaBuffer,t=f.now();for(;e.length>0&&t-e[0].time>160;)e.shift();}_onMoveEnd(e){if(this._drainInertiaBuffer(),this._inertiaBuffer.length<2)return;const i={zoom:0,bearing:0,pitch:0,roll:0,pan:new t.Point(0,0),pinchAround:void 0,around:void 0};for(const{settings:e}of this._inertiaBuffer)i.zoom+=e.zoomDelta||0,i.bearing+=e.bearingDelta||0,i.pitch+=e.pitchDelta||0,i.roll+=e.rollDelta||0,e.panDelta&&i.pan._add(e.panDelta),e.around&&(i.around=e.around),e.pinchAround&&(i.pinchAround=e.pinchAround);const r=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,o={};if(i.pan.mag()){const a=Fo(i.pan.mag(),r,t.extend({},So,e||{})),s=i.pan.mult(a.amount/i.pan.mag()),n=this._map.cameraHelper.handlePanInertia(s,this._map.transform);o.center=n.easingCenter,o.offset=n.easingOffset,ko(o,a);}if(i.zoom){const e=Fo(i.zoom,r,Ro);o.zoom=this._map.transform.zoom+e.amount,ko(o,e);}if(i.bearing){const e=Fo(i.bearing,r,Do);o.bearing=this._map.transform.bearing+t.clamp(e.amount,-179,179),ko(o,e);}if(i.pitch){const e=Fo(i.pitch,r,zo);o.pitch=this._map.transform.pitch+e.amount,ko(o,e);}if(i.roll){const e=Fo(i.roll,r,Lo);o.roll=this._map.transform.roll+t.clamp(e.amount,-179,179),ko(o,e);}if(o.zoom||o.bearing){const e=void 0===i.pinchAround?i.around:i.pinchAround;o.around=e?this._map.unproject(e):this._map.getCenter();}return this.clear(),t.extend(o,{noMoveStart:!0})}}function ko(e,t){(!e.duration||e.durationi.unproject(e))),n=a.reduce(((e,t,i,r)=>e.add(t.div(r.length))),new t.Point(0,0));super(e,{points:a,point:n,lngLats:s,lngLat:i.unproject(n),originalEvent:r}),this._defaultPrevented=!1;}}class Uo extends t.Event{preventDefault(){this._defaultPrevented=!0;}get defaultPrevented(){return this._defaultPrevented}constructor(e,t,i){super(e,{originalEvent:i}),this._defaultPrevented=!1;}}class jo{constructor(e,t){this._map=e,this._clickTolerance=t.clickTolerance;}reset(){delete this._mousedownPos;}wheel(e){return this._firePreventable(new Uo(e.type,this._map,e))}mousedown(e,t){return this._mousedownPos=t,this._firePreventable(new Bo(e.type,this._map,e))}mouseup(e){this._map.fire(new Bo(e.type,this._map,e));}click(e,t){this._mousedownPos&&this._mousedownPos.dist(t)>=this._clickTolerance||this._map.fire(new Bo(e.type,this._map,e));}dblclick(e){return this._firePreventable(new Bo(e.type,this._map,e))}mouseover(e){this._map.fire(new Bo(e.type,this._map,e));}mouseout(e){this._map.fire(new Bo(e.type,this._map,e));}touchstart(e){return this._firePreventable(new Oo(e.type,this._map,e))}touchmove(e){this._map.fire(new Oo(e.type,this._map,e));}touchend(e){this._map.fire(new Oo(e.type,this._map,e));}touchcancel(e){this._map.fire(new Oo(e.type,this._map,e));}_firePreventable(e){if(this._map.fire(e),e.defaultPrevented)return {}}isEnabled(){return !0}isActive(){return !1}enable(){}disable(){}}class No{constructor(e){this._map=e;}reset(){this._delayContextMenu=!1,this._ignoreContextMenu=!0,delete this._contextMenuEvent;}mousemove(e){this._map.fire(new Bo(e.type,this._map,e));}mousedown(){this._delayContextMenu=!0,this._ignoreContextMenu=!1;}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new Bo("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent);}contextmenu(e){this._delayContextMenu?this._contextMenuEvent=e:this._ignoreContextMenu||this._map.fire(new Bo(e.type,this._map,e)),this._map.listens("contextmenu")&&e.preventDefault();}isEnabled(){return !0}isActive(){return !1}enable(){}disable(){}}class Go{constructor(e){this._map=e;}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(e){return this.transform.screenPointToLocation(t.Point.convert(e),this._map.terrain)}}class Zo{constructor(e,t){this._map=e,this._tr=new Go(e),this._el=e.getCanvasContainer(),this._container=e.getContainer(),this._clickTolerance=t.clickTolerance||1;}isEnabled(){return !!this._enabled}isActive(){return !!this._active}enable(){this.isEnabled()||(this._enabled=!0);}disable(){this.isEnabled()&&(this._enabled=!1);}mousedown(e,t){this.isEnabled()&&e.shiftKey&&0===e.button&&(wi.disableDrag(),this._startPos=this._lastPos=t,this._active=!0);}mousemoveWindow(e,t){if(!this._active)return;const i=t;if(this._lastPos.equals(i)||!this._box&&i.dist(this._startPos)e.fitScreenCoordinates(r,o,this._tr.bearing,{linear:!0})};this._fireEvent("boxzoomcancel",e);}keydown(e){this._active&&27===e.keyCode&&(this.reset(),this._fireEvent("boxzoomcancel",e));}reset(){this._active=!1,this._container.classList.remove("maplibregl-crosshair"),this._box&&(wi.remove(this._box),this._box=null),wi.enableDrag(),delete this._startPos,delete this._lastPos;}_fireEvent(e,i){return this._map.fire(new t.Event(e,{originalEvent:i}))}}function Vo(e,t){if(e.length!==t.length)throw new Error(`The number of touches and points are not equal - touches ${e.length}, points ${t.length}`);const i={};for(let r=0;rthis.numTouches)&&(this.aborted=!0),this.aborted||(void 0===this.startTime&&(this.startTime=e.timeStamp),r.length===this.numTouches&&(this.centroid=function(e){const i=new t.Point(0,0);for(const t of e)i._add(t);return i.div(e.length)}(i),this.touches=Vo(r,i)));}touchmove(e,t,i){if(this.aborted||!this.centroid)return;const r=Vo(i,t);for(const e in this.touches){const t=r[e];(!t||t.dist(this.touches[e])>30)&&(this.aborted=!0);}}touchend(e,t,i){if((!this.centroid||e.timeStamp-this.startTime>500)&&(this.aborted=!0),0===i.length){const e=!this.aborted&&this.centroid;if(this.reset(),e)return e}}}class Wo{constructor(e){this.singleTap=new qo(e),this.numTaps=e.numTaps,this.reset();}reset(){this.lastTime=1/0,delete this.lastTap,this.count=0,this.singleTap.reset();}touchstart(e,t,i){this.singleTap.touchstart(e,t,i);}touchmove(e,t,i){this.singleTap.touchmove(e,t,i);}touchend(e,t,i){const r=this.singleTap.touchend(e,t,i);if(r){const t=e.timeStamp-this.lastTime<500,i=!this.lastTap||this.lastTap.dist(r)<30;if(t&&i||this.reset(),this.count++,this.lastTime=e.timeStamp,this.lastTap=r,this.count===this.numTaps)return this.reset(),r}}}class Xo{constructor(e){this._tr=new Go(e),this._zoomIn=new Wo({numTouches:1,numTaps:2}),this._zoomOut=new Wo({numTouches:2,numTaps:1}),this.reset();}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset();}touchstart(e,t,i){this._zoomIn.touchstart(e,t,i),this._zoomOut.touchstart(e,t,i);}touchmove(e,t,i){this._zoomIn.touchmove(e,t,i),this._zoomOut.touchmove(e,t,i);}touchend(e,t,i){const r=this._zoomIn.touchend(e,t,i),o=this._zoomOut.touchend(e,t,i),a=this._tr;return r?(this._active=!0,e.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:t=>t.easeTo({duration:300,zoom:a.zoom+1,around:a.unproject(r)},{originalEvent:e})}):o?(this._active=!0,e.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:t=>t.easeTo({duration:300,zoom:a.zoom-1,around:a.unproject(o)},{originalEvent:e})}):void 0}touchcancel(){this.reset();}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class $o{constructor(e){this._enabled=!!e.enable,this._moveStateManager=e.moveStateManager,this._clickTolerance=e.clickTolerance||1,this._moveFunction=e.move,this._activateOnStart=!!e.activateOnStart,e.assignEvents(this),this.reset();}reset(e){this._active=!1,this._moved=!1,delete this._lastPoint,this._moveStateManager.endMove(e);}_move(...e){const t=this._moveFunction(...e);if(t.bearingDelta||t.pitchDelta||t.rollDelta||t.around||t.panDelta)return this._active=!0,t}dragStart(e,t){this.isEnabled()&&!this._lastPoint&&this._moveStateManager.isValidStartEvent(e)&&(this._moveStateManager.startMove(e),this._lastPoint=t.length?t[0]:t,this._activateOnStart&&this._lastPoint&&(this._active=!0));}dragMove(e,i){if(!this.isEnabled())return;const r=this._lastPoint;if(!r)return;if(e.preventDefault(),!this._moveStateManager.isValidMoveEvent(e))return void this.reset(e);const o=Array.isArray(i)?i[0]:i;return !this._moved&&o.dist(r){e.mousedown=e.dragStart,e.mousemoveWindow=e.dragMove,e.mouseup=e.dragEnd,e.contextmenu=e=>{e.preventDefault();};};function Qo({enable:e,clickTolerance:i,aroundCenter:r=!0}){const o=new Ko({checkCorrectEvent:e=>0===wi.mouseButton(e)&&e.ctrlKey||2===wi.mouseButton(e)&&!e.ctrlKey});return new $o({clickTolerance:i,move:(e,i,o)=>r?{bearingDelta:t.getAngleDelta(new t.Point(e.x,i.y),i,o)}:{bearingDelta:.8*(i.x-e.x)},moveStateManager:o,enable:e,assignEvents:Jo})}function ea({enable:e,clickTolerance:t,pitchDegreesPerPixelMoved:i=-.5}){const r=new Ko({checkCorrectEvent:e=>0===wi.mouseButton(e)&&e.ctrlKey||2===wi.mouseButton(e)});return new $o({clickTolerance:t,move:(e,t)=>({pitchDelta:(t.y-e.y)*i}),moveStateManager:r,enable:e,assignEvents:Jo})}class ta{constructor(e,t){this._clickTolerance=e.clickTolerance||1,this._map=t,this.reset();}reset(){this._active=!1,this._touches={},this._sum=new t.Point(0,0);}_shouldBePrevented(e){return e<(this._map.cooperativeGestures.isEnabled()?2:1)}touchstart(e,t,i){return this._calculateTransform(e,t,i)}touchmove(e,t,i){if(this._active){if(!this._shouldBePrevented(i.length))return e.preventDefault(),this._calculateTransform(e,t,i);this._map.cooperativeGestures.notifyGestureBlocked("touch_pan",e);}}touchend(e,t,i){this._calculateTransform(e,t,i),this._active&&this._shouldBePrevented(i.length)&&this.reset();}touchcancel(){this.reset();}_calculateTransform(e,i,r){r.length>0&&(this._active=!0);const o=Vo(r,i),a=new t.Point(0,0),s=new t.Point(0,0);let n=0;for(const e in o){const t=o[e],i=this._touches[e];i&&(a._add(t),s._add(t.sub(i)),n++,o[e]=t);}if(this._touches=o,this._shouldBePrevented(n)||!s.mag())return;const l=s.div(n);return this._sum._add(l),this._sum.mag()Math.abs(e.x)}class ca extends ia{constructor(e){super(),this._currentTouchCount=0,this._map=e;}reset(){super.reset(),this._valid=void 0,delete this._firstMove,delete this._lastPoints;}touchstart(e,t,i){super.touchstart(e,t,i),this._currentTouchCount=i.length;}_start(e){this._lastPoints=e,la(e[0].sub(e[1]))&&(this._valid=!1);}_move(e,t,i){if(this._map.cooperativeGestures.isEnabled()&&this._currentTouchCount<3)return;const r=e[0].sub(this._lastPoints[0]),o=e[1].sub(this._lastPoints[1]);return this._valid=this.gestureBeginsVertically(r,o,i.timeStamp),this._valid?(this._lastPoints=e,this._active=!0,{pitchDelta:(r.y+o.y)/2*-.5}):void 0}gestureBeginsVertically(e,t,i){if(void 0!==this._valid)return this._valid;const r=e.mag()>=2,o=t.mag()>=2;if(!r&&!o)return;if(!r||!o)return void 0===this._firstMove&&(this._firstMove=i),i-this._firstMove<100&&void 0;const a=e.y>0==t.y>0;return la(e)&&la(t)&&a}}const ha={panStep:100,bearingStep:15,pitchStep:10};class ua{constructor(e){this._tr=new Go(e);const t=ha;this._panStep=t.panStep,this._bearingStep=t.bearingStep,this._pitchStep=t.pitchStep,this._rotationDisabled=!1;}reset(){this._active=!1;}keydown(e){if(e.altKey||e.ctrlKey||e.metaKey)return;let t=0,i=0,r=0,o=0,a=0;switch(e.keyCode){case 61:case 107:case 171:case 187:t=1;break;case 189:case 109:case 173:t=-1;break;case 37:e.shiftKey?i=-1:(e.preventDefault(),o=-1);break;case 39:e.shiftKey?i=1:(e.preventDefault(),o=1);break;case 38:e.shiftKey?r=1:(e.preventDefault(),a=-1);break;case 40:e.shiftKey?r=-1:(e.preventDefault(),a=1);break;default:return}return this._rotationDisabled&&(i=0,r=0),{cameraAnimation:s=>{const n=this._tr;s.easeTo({duration:300,easeId:"keyboardHandler",easing:da,zoom:t?Math.round(n.zoom)+t*(e.shiftKey?2:1):n.zoom,bearing:n.bearing+i*this._bearingStep,pitch:n.pitch+r*this._pitchStep,offset:[-o*this._panStep,-a*this._panStep],center:n.center},{originalEvent:e});}}}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}disableRotation(){this._rotationDisabled=!0;}enableRotation(){this._rotationDisabled=!1;}}function da(e){return e*(2-e)}const _a=4.000244140625;class pa{constructor(e,t){this._onTimeout=e=>{this._type="wheel",this._delta-=this._lastValue,this._active||this._start(e);},this._map=e,this._tr=new Go(e),this._triggerRenderFrame=t,this._delta=0,this._defaultZoomRate=.01,this._wheelZoomRate=.0022222222222222222;}setZoomRate(e){this._defaultZoomRate=e;}setWheelZoomRate(e){this._wheelZoomRate=e;}isEnabled(){return !!this._enabled}isActive(){return !!this._active||void 0!==this._finishTimeout}isZooming(){return !!this._zooming}enable(e){this.isEnabled()||(this._enabled=!0,this._aroundCenter=!!e&&"center"===e.around);}disable(){this.isEnabled()&&(this._enabled=!1);}_shouldBePrevented(e){return !!this._map.cooperativeGestures.isEnabled()&&!(e.ctrlKey||this._map.cooperativeGestures.isBypassed(e))}wheel(e){if(!this.isEnabled())return;if(this._shouldBePrevented(e))return void this._map.cooperativeGestures.notifyGestureBlocked("wheel_zoom",e);let t=e.deltaMode===WheelEvent.DOM_DELTA_LINE?40*e.deltaY:e.deltaY;const i=f.now(),r=i-(this._lastWheelEventTime||0);this._lastWheelEventTime=i,0!==t&&t%_a==0?this._type="wheel":0!==t&&Math.abs(t)<4?this._type="trackpad":r>400?(this._type=null,this._lastValue=t,this._timeout=setTimeout(this._onTimeout,40,e)):this._type||(this._type=Math.abs(r*t)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,t+=this._lastValue)),e.shiftKey&&t&&(t/=4),this._type&&(this._lastWheelEvent=e,this._delta-=t,this._active||this._start(e)),e.preventDefault();}_start(e){if(!this._delta)return;this._frameId&&(this._frameId=null),this._active=!0,this.isZooming()||(this._zooming=!0),this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);const i=wi.mousePos(this._map.getCanvas(),e),r=this._tr;this._aroundPoint=this._aroundCenter?r.transform.locationToScreenPoint(t.LngLat.convert(r.center)):i,this._frameId||(this._frameId=!0,this._triggerRenderFrame());}renderFrame(){if(!this._frameId)return;if(this._frameId=null,!this.isActive())return;const e=this._tr.transform;if("number"==typeof this._lastExpectedZoom){const t=e.zoom-this._lastExpectedZoom;"number"==typeof this._startZoom&&(this._startZoom+=t),"number"==typeof this._targetZoom&&(this._targetZoom+=t);}if(0!==this._delta){const t="wheel"===this._type&&Math.abs(this._delta)>_a?this._wheelZoomRate:this._defaultZoomRate;let i=2/(1+Math.exp(-Math.abs(this._delta*t)));this._delta<0&&0!==i&&(i=1/i);const r="number"!=typeof this._targetZoom?e.scale:ue(this._targetZoom);this._targetZoom=Math.min(e.maxZoom,Math.max(e.minZoom,de(r*i))),"wheel"===this._type&&(this._startZoom=e.zoom,this._easing=this._smoothOutEasing(200)),this._delta=0;}const i="number"!=typeof this._targetZoom?e.zoom:this._targetZoom,r=this._startZoom,o=this._easing;let a,s=!1;const n=f.now()-this._lastWheelEventTime;if("wheel"===this._type&&r&&o&&n){const e=Math.min(n/200,1),l=o(e);a=t.interpolateFactory.number(r,i,l),e<1?this._frameId||(this._frameId=!0):s=!0;}else a=i,s=!0;return this._active=!0,s&&(this._active=!1,this._finishTimeout=setTimeout((()=>{this._zooming=!1,this._triggerRenderFrame(),delete this._targetZoom,delete this._lastExpectedZoom,delete this._finishTimeout;}),200)),this._lastExpectedZoom=a,{noInertia:!0,needsRenderFrame:!s,zoomDelta:a-e.zoom,around:this._aroundPoint,originalEvent:this._lastWheelEvent}}_smoothOutEasing(e){let i=t.defaultEasing;if(this._prevEase){const e=this._prevEase,r=(f.now()-e.start)/e.duration,o=e.easing(r+.01)-e.easing(r),a=.27/Math.sqrt(o*o+1e-4)*.01,s=Math.sqrt(.0729-a*a);i=t.bezier(a,s,.25,1);}return this._prevEase={start:f.now(),duration:e,easing:i},i}reset(){this._active=!1,this._zooming=!1,delete this._targetZoom,delete this._lastExpectedZoom,this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);}}class ma{constructor(e,t){this._clickZoom=e,this._tapZoom=t;}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 fa{constructor(e){this._tr=new Go(e),this.reset();}reset(){this._active=!1;}dblclick(e,t){return e.preventDefault(),{cameraAnimation:i=>{i.easeTo({duration:300,zoom:this._tr.zoom+(e.shiftKey?-1:1),around:this._tr.unproject(t)},{originalEvent:e});}}}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class ga{constructor(){this._tap=new Wo({numTouches:1,numTaps:1}),this.reset();}reset(){this._active=!1,delete this._swipePoint,delete this._swipeTouch,delete this._tapTime,delete this._tapPoint,this._tap.reset();}touchstart(e,t,i){if(!this._swipePoint)if(this._tapTime){const r=t[0],o=e.timeStamp-this._tapTime<500,a=this._tapPoint.dist(r)<30;o&&a?i.length>0&&(this._swipePoint=r,this._swipeTouch=i[0].identifier):this.reset();}else this._tap.touchstart(e,t,i);}touchmove(e,t,i){if(this._tapTime){if(this._swipePoint){if(i[0].identifier!==this._swipeTouch)return;const r=t[0],o=r.y-this._swipePoint.y;return this._swipePoint=r,e.preventDefault(),this._active=!0,{zoomDelta:o/128}}}else this._tap.touchmove(e,t,i);}touchend(e,t,i){if(this._tapTime)this._swipePoint&&0===i.length&&this.reset();else {const r=this._tap.touchend(e,t,i);r&&(this._tapTime=e.timeStamp,this._tapPoint=r);}}touchcancel(){this.reset();}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class va{constructor(e,t,i){this._el=e,this._mousePan=t,this._touchPan=i;}enable(e){this._inertiaOptions=e||{},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 ya{constructor(e,t,i,r){this._pitchWithRotate=e.pitchWithRotate,this._rollEnabled=e.rollEnabled,this._mouseRotate=t,this._mousePitch=i,this._mouseRoll=r;}enable(){this._mouseRotate.enable(),this._pitchWithRotate&&this._mousePitch.enable(),this._rollEnabled&&this._mouseRoll.enable();}disable(){this._mouseRotate.disable(),this._mousePitch.disable(),this._mouseRoll.disable();}isEnabled(){return this._mouseRotate.isEnabled()&&(!this._pitchWithRotate||this._mousePitch.isEnabled())&&(!this._rollEnabled||this._mouseRoll.isEnabled())}isActive(){return this._mouseRotate.isActive()||this._mousePitch.isActive()||this._mouseRoll.isActive()}}class xa{constructor(e,t,i,r){this._el=e,this._touchZoom=t,this._touchRotate=i,this._tapDragZoom=r,this._rotationDisabled=!1,this._enabled=!0;}enable(e){this._touchZoom.enable(e),this._rotationDisabled||this._touchRotate.enable(e),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=!0,this._touchRotate.disable();}enableRotation(){this._rotationDisabled=!1,this._touchZoom.isEnabled()&&this._touchRotate.enable();}}class ba{constructor(e,t){this._bypassKey=-1!==navigator.userAgent.indexOf("Mac")?"metaKey":"ctrlKey",this._map=e,this._options=t,this._enabled=!1;}isActive(){return !1}reset(){}_setupUI(){if(this._container)return;const e=this._map.getCanvasContainer();e.classList.add("maplibregl-cooperative-gestures"),this._container=wi.create("div","maplibregl-cooperative-gesture-screen",e);let t=this._map._getUIString("CooperativeGesturesHandler.WindowsHelpText");"metaKey"===this._bypassKey&&(t=this._map._getUIString("CooperativeGesturesHandler.MacHelpText"));const i=this._map._getUIString("CooperativeGesturesHandler.MobileHelpText"),r=document.createElement("div");r.className="maplibregl-desktop-message",r.textContent=t,this._container.appendChild(r);const o=document.createElement("div");o.className="maplibregl-mobile-message",o.textContent=i,this._container.appendChild(o),this._container.setAttribute("aria-hidden","true");}_destroyUI(){this._container&&(wi.remove(this._container),this._map.getCanvasContainer().classList.remove("maplibregl-cooperative-gestures")),delete this._container;}enable(){this._setupUI(),this._enabled=!0;}disable(){this._enabled=!1,this._destroyUI();}isEnabled(){return this._enabled}isBypassed(e){return e[this._bypassKey]}notifyGestureBlocked(e,i){this._enabled&&(this._map.fire(new t.Event("cooperativegestureprevented",{gestureType:e,originalEvent:i})),this._container.classList.add("maplibregl-show"),setTimeout((()=>{this._container.classList.remove("maplibregl-show");}),100));}}const wa=e=>e.zoom||e.drag||e.roll||e.pitch||e.rotate;class Ta extends t.Event{}function Ea(e){return e.panDelta&&e.panDelta.mag()||e.zoomDelta||e.bearingDelta||e.pitchDelta||e.rollDelta}class Pa{constructor(e,t){this.handleWindowEvent=e=>{this.handleEvent(e,`${e.type}Window`);},this.handleEvent=(e,t)=>{if("blur"===e.type)return void this.stop(!0);this._updatingCamera=!0;const i="renderFrame"===e.type?void 0:e,r={needsRenderFrame:!1},o={},a={},s=e.touches,n=s?this._getMapTouches(s):void 0,l=n?wi.touchPos(this._map.getCanvas(),n):wi.mousePos(this._map.getCanvas(),e);for(const{handlerName:s,handler:c,allowed:h}of this._handlers){if(!c.isEnabled())continue;let u;this._blockedByActive(a,h,s)?c.reset():c[t||e.type]&&(u=c[t||e.type](e,l,n),this.mergeHandlerResult(r,o,u,s,i),u&&u.needsRenderFrame&&this._triggerRenderFrame()),(u||c.isActive())&&(a[s]=c);}const c={};for(const e in this._previousActiveHandlers)a[e]||(c[e]=i);this._previousActiveHandlers=a,(Object.keys(c).length||Ea(r))&&(this._changes.push([r,o,c]),this._triggerRenderFrame()),(Object.keys(a).length||Ea(r))&&this._map._stop(!0),this._updatingCamera=!1;const{cameraAnimation:h}=r;h&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],h(this._map));},this._map=e,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new Ao(e),this._bearingSnap=t.bearingSnap,this._previousActiveHandlers={},this._eventsInProgress={},this._addDefaultHandlers(t);const i=this._el;this._listeners=[[i,"touchstart",{passive:!0}],[i,"touchmove",{passive:!1}],[i,"touchend",void 0],[i,"touchcancel",void 0],[i,"mousedown",void 0],[i,"mousemove",void 0],[i,"mouseup",void 0],[document,"mousemove",{capture:!0}],[document,"mouseup",void 0],[i,"mouseover",void 0],[i,"mouseout",void 0],[i,"dblclick",void 0],[i,"click",void 0],[i,"keydown",{capture:!1}],[i,"keyup",void 0],[i,"wheel",{passive:!1}],[i,"contextmenu",void 0],[window,"blur",void 0]];for(const[e,t,i]of this._listeners)wi.addEventListener(e,t,e===document?this.handleWindowEvent:this.handleEvent,i);}destroy(){for(const[e,t,i]of this._listeners)wi.removeEventListener(e,t,e===document?this.handleWindowEvent:this.handleEvent,i);}_addDefaultHandlers(e){const t=this._map,i=t.getCanvasContainer();this._add("mapEvent",new jo(t,e));const r=t.boxZoom=new Zo(t,e);this._add("boxZoom",r),e.interactive&&e.boxZoom&&r.enable();const o=t.cooperativeGestures=new ba(t,e.cooperativeGestures);this._add("cooperativeGestures",o),e.cooperativeGestures&&o.enable();const a=new Xo(t),s=new fa(t);t.doubleClickZoom=new ma(s,a),this._add("tapZoom",a),this._add("clickZoom",s),e.interactive&&e.doubleClickZoom&&t.doubleClickZoom.enable();const n=new ga;this._add("tapDragZoom",n);const l=t.touchPitch=new ca(t);this._add("touchPitch",l),e.interactive&&e.touchPitch&&t.touchPitch.enable(e.touchPitch);const c=Qo(e),h=ea(e),u=function({enable:e,clickTolerance:t,rollDegreesPerPixelMoved:i=.3}){const r=new Ko({checkCorrectEvent:e=>2===wi.mouseButton(e)&&e.ctrlKey});return new $o({clickTolerance:t,move:(e,t,r)=>{let o=(t.x-e.x)*i;return t.y0===wi.mouseButton(e)&&!e.ctrlKey});return new $o({clickTolerance:t,move:(e,t)=>({around:t,panDelta:t.sub(e)}),activateOnStart:!0,moveStateManager:i,enable:e,assignEvents:Jo})}(e),_=new ta(e,t);t.dragPan=new va(i,d,_),this._add("mousePan",d),this._add("touchPan",_,["touchZoom","touchRotate"]),e.interactive&&e.dragPan&&t.dragPan.enable(e.dragPan);const p=new na,m=new aa;t.touchZoomRotate=new xa(i,m,p,n),this._add("touchRotate",p,["touchPan","touchZoom"]),this._add("touchZoom",m,["touchPan","touchRotate"]),e.interactive&&e.touchZoomRotate&&t.touchZoomRotate.enable(e.touchZoomRotate);const f=t.scrollZoom=new pa(t,(()=>this._triggerRenderFrame()));this._add("scrollZoom",f,["mousePan"]),e.interactive&&e.scrollZoom&&t.scrollZoom.enable(e.scrollZoom);const g=t.keyboard=new ua(t);this._add("keyboard",g),e.interactive&&e.keyboard&&t.keyboard.enable(),this._add("blockableMapEvent",new No(t));}_add(e,t,i){this._handlers.push({handlerName:e,handler:t,allowed:i}),this._handlersById[e]=t;}stop(e){if(!this._updatingCamera){for(const{handler:e}of this._handlers)e.reset();this._inertia.clear(),this._fireEvents({},{},e),this._changes=[];}}isActive(){for(const{handler:e}of this._handlers)if(e.isActive())return !0;return !1}isZooming(){return !!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return !!this._eventsInProgress.rotate}isMoving(){return Boolean(wa(this._eventsInProgress))||this.isZooming()}_blockedByActive(e,t,i){for(const r in e)if(r!==i&&(!t||t.indexOf(r)<0))return !0;return !1}_getMapTouches(e){const t=[];for(const i of e)this._el.contains(i.target)&&t.push(i);return t}mergeHandlerResult(e,i,r,o,a){if(!r)return;t.extend(e,r);const s={handlerName:o,originalEvent:r.originalEvent||a};void 0!==r.zoomDelta&&(i.zoom=s),void 0!==r.panDelta&&(i.drag=s),void 0!==r.rollDelta&&(i.roll=s),void 0!==r.pitchDelta&&(i.pitch=s),void 0!==r.bearingDelta&&(i.rotate=s);}_applyChanges(){const e={},i={},r={};for(const[o,a,s]of this._changes)o.panDelta&&(e.panDelta=(e.panDelta||new t.Point(0,0))._add(o.panDelta)),o.zoomDelta&&(e.zoomDelta=(e.zoomDelta||0)+o.zoomDelta),o.bearingDelta&&(e.bearingDelta=(e.bearingDelta||0)+o.bearingDelta),o.pitchDelta&&(e.pitchDelta=(e.pitchDelta||0)+o.pitchDelta),o.rollDelta&&(e.rollDelta=(e.rollDelta||0)+o.rollDelta),void 0!==o.around&&(e.around=o.around),void 0!==o.pinchAround&&(e.pinchAround=o.pinchAround),o.noInertia&&(e.noInertia=o.noInertia),t.extend(i,a),t.extend(r,s);this._updateMapTransform(e,i,r),this._changes=[];}_updateMapTransform(e,t,i){const r=this._map,o=r._getTransformForUpdate(),a=r.terrain;if(!(Ea(e)||a&&this._terrainMovement))return this._fireEvents(t,i,!0);r._stop(!0);let{panDelta:s,zoomDelta:n,bearingDelta:l,pitchDelta:c,rollDelta:h,around:u,pinchAround:d}=e;void 0!==d&&(u=d),u=u||r.transform.centerPoint,a&&!o.isPointOnMapSurface(u)&&(u=o.centerPoint);const _={panDelta:s,zoomDelta:n,rollDelta:h,pitchDelta:c,bearingDelta:l,around:u};this._map.cameraHelper.useGlobeControls&&!o.isPointOnMapSurface(u)&&(u=o.centerPoint);const p=u.distSqr(o.centerPoint)<.01?o.center:o.screenPointToLocation(s?u.sub(s):u);a?(this._map.cameraHelper.handleMapControlsRollPitchBearingZoom(_,o),this._terrainMovement||!t.drag&&!t.zoom?t.drag&&this._terrainMovement?o.setCenter(o.screenPointToLocation(o.centerPoint.sub(s))):this._map.cameraHelper.handleMapControlsPan(_,o,p):(this._terrainMovement=!0,this._map._elevationFreeze=!0,this._map.cameraHelper.handleMapControlsPan(_,o,p))):(this._map.cameraHelper.handleMapControlsRollPitchBearingZoom(_,o),this._map.cameraHelper.handleMapControlsPan(_,o,p)),r._applyUpdatedTransform(o),this._map._update(),e.noInertia||this._inertia.record(e),this._fireEvents(t,i,!0);}_fireEvents(e,i,r){const o=wa(this._eventsInProgress),a=wa(e),s={};for(const t in e){const{originalEvent:i}=e[t];this._eventsInProgress[t]||(s[`${t}start`]=i),this._eventsInProgress[t]=e[t];}!o&&a&&this._fireEvent("movestart",a.originalEvent);for(const e in s)this._fireEvent(e,s[e]);a&&this._fireEvent("move",a.originalEvent);for(const t in e){const{originalEvent:i}=e[t];this._fireEvent(t,i);}const n={};let l;for(const e in this._eventsInProgress){const{handlerName:t,originalEvent:r}=this._eventsInProgress[e];this._handlersById[t].isActive()||(delete this._eventsInProgress[e],l=i[t]||r,n[`${e}end`]=l);}for(const e in n)this._fireEvent(e,n[e]);const c=wa(this._eventsInProgress),h=(o||a)&&!c;if(h&&this._terrainMovement){this._map._elevationFreeze=!1,this._terrainMovement=!1;const e=this._map._getTransformForUpdate();this._map.getCenterClampedToGround()&&e.recalculateZoomAndCenter(this._map.terrain),this._map._applyUpdatedTransform(e);}if(r&&h){this._updatingCamera=!0;const e=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),i=e=>0!==e&&-this._bearingSnap{delete this._frameId,this.handleEvent(new Ta("renderFrame",{timeStamp:e})),this._applyChanges();}))}_triggerRenderFrame(){void 0===this._frameId&&(this._frameId=this._requestFrame());}}class Ia extends t.Evented{constructor(e,t,i){super(),this._renderFrameCallback=()=>{const e=Math.min((f.now()-this._easeStart)/this._easeOptions.duration,1);this._onEaseFrame(this._easeOptions.easing(e)),e<1&&this._easeFrameId?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop();},this._moving=!1,this._zooming=!1,this.transform=e,this._bearingSnap=i.bearingSnap,this.cameraHelper=t,this.on("moveend",(()=>{delete this._requestedCameraState;}));}migrateProjection(e,t){e.apply(this.transform),this.transform=e,this.cameraHelper=t;}getCenter(){return new t.LngLat(this.transform.center.lng,this.transform.center.lat)}setCenter(e,t){return this.jumpTo({center:e},t)}getCenterElevation(){return this.transform.elevation}setCenterElevation(e,t){return this.jumpTo({elevation:e},t),this}getCenterClampedToGround(){return this._centerClampedToGround}setCenterClampedToGround(e){this._centerClampedToGround=e;}panBy(e,i,r){return e=t.Point.convert(e).mult(-1),this.panTo(this.transform.center,t.extend({offset:e},i),r)}panTo(e,i,r){return this.easeTo(t.extend({center:e},i),r)}getZoom(){return this.transform.zoom}setZoom(e,t){return this.jumpTo({zoom:e},t),this}zoomTo(e,i,r){return this.easeTo(t.extend({zoom:e},i),r)}zoomIn(e,t){return this.zoomTo(this.getZoom()+1,e,t),this}zoomOut(e,t){return this.zoomTo(this.getZoom()-1,e,t),this}getVerticalFieldOfView(){return this.transform.fov}setVerticalFieldOfView(e,i){return e!=this.transform.fov&&(this.transform.setFov(e),this.fire(new t.Event("movestart",i)).fire(new t.Event("move",i)).fire(new t.Event("moveend",i))),this}getBearing(){return this.transform.bearing}setBearing(e,t){return this.jumpTo({bearing:e},t),this}getPadding(){return this.transform.padding}setPadding(e,t){return this.jumpTo({padding:e},t),this}rotateTo(e,i,r){return this.easeTo(t.extend({bearing:e},i),r)}resetNorth(e,i){return this.rotateTo(0,t.extend({duration:1e3},e),i),this}resetNorthPitch(e,i){return this.easeTo(t.extend({bearing:0,pitch:0,roll:0,duration:1e3},e),i),this}snapToNorth(e,t){return Math.abs(this.getBearing()){m.easeFunc(t),this.terrain&&!e.freezeElevation&&this._updateElevation(t),this._applyUpdatedTransform(r),this._fireMoveEvents(i);}),(t=>{this.terrain&&e.freezeElevation&&this._finalizeElevation(),this._afterEase(i,t);}),e),this}_prepareEase(e,i,r={}){this._moving=!0,i||r.moving||this.fire(new t.Event("movestart",e)),this._zooming&&!r.zooming&&this.fire(new t.Event("zoomstart",e)),this._rotating&&!r.rotating&&this.fire(new t.Event("rotatestart",e)),this._pitching&&!r.pitching&&this.fire(new t.Event("pitchstart",e)),this._rolling&&!r.rolling&&this.fire(new t.Event("rollstart",e));}_prepareElevation(e){this._elevationCenter=e,this._elevationStart=this.transform.elevation,this._elevationTarget=this.terrain.getElevationForLngLatZoom(e,this.transform.tileZoom),this._elevationFreeze=!0;}_updateElevation(e){this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom));const i=this.terrain.getElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom);if(e<1&&i!==this._elevationTarget){const t=this._elevationTarget-this._elevationStart;this._elevationStart+=e*(t-(i-(t*e+this._elevationStart))/(1-e)),this._elevationTarget=i;}this.transform.setElevation(t.interpolateFactory.number(this._elevationStart,this._elevationTarget,e));}_finalizeElevation(){this._elevationFreeze=!1,this.getCenterClampedToGround()&&this.transform.recalculateZoomAndCenter(this.terrain);}_getTransformForUpdate(){return this.transformCameraUpdate||this.terrain?(this._requestedCameraState||(this._requestedCameraState=this.transform.clone()),this._requestedCameraState):this.transform}_elevateCameraIfInsideTerrain(e){if(!this.terrain&&e.elevation>=0&&e.pitch<=90)return {};const t=e.getCameraLngLat(),i=e.getCameraAltitude(),r=this.terrain?this.terrain.getElevationForLngLatZoom(t,e.zoom):0;if(ithis._elevateCameraIfInsideTerrain(e))),this.transformCameraUpdate&&t.push((e=>this.transformCameraUpdate(e))),!t.length)return;const i=e.clone();for(const e of t){const t=i.clone(),{center:r,zoom:o,roll:a,pitch:s,bearing:n,elevation:l}=e(t);r&&t.setCenter(r),void 0!==l&&t.setElevation(l),void 0!==o&&t.setZoom(o),void 0!==a&&t.setRoll(a),void 0!==s&&t.setPitch(s),void 0!==n&&t.setBearing(n),i.apply(t);}this.transform.apply(i);}_fireMoveEvents(e){this.fire(new t.Event("move",e)),this._zooming&&this.fire(new t.Event("zoom",e)),this._rotating&&this.fire(new t.Event("rotate",e)),this._pitching&&this.fire(new t.Event("pitch",e)),this._rolling&&this.fire(new t.Event("roll",e));}_afterEase(e,i){if(this._easeId&&i&&this._easeId===i)return;delete this._easeId;const r=this._zooming,o=this._rotating,a=this._pitching,s=this._rolling;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._rolling=!1,this._padding=!1,r&&this.fire(new t.Event("zoomend",e)),o&&this.fire(new t.Event("rotateend",e)),a&&this.fire(new t.Event("pitchend",e)),s&&this.fire(new t.Event("rollend",e)),this.fire(new t.Event("moveend",e));}flyTo(e,i){if(!e.essential&&f.prefersReducedMotion){const r=t.pick(e,["center","zoom","bearing","pitch","roll","elevation"]);return this.jumpTo(r,i)}this.stop(),e=t.extend({offset:[0,0],speed:1.2,curve:1.42,easing:t.defaultEasing},e);const r=this._getTransformForUpdate(),o=r.bearing,a=r.pitch,s=r.roll,n=r.padding,l="bearing"in e?this._normalizeBearing(e.bearing,o):o,c="pitch"in e?+e.pitch:a,h="roll"in e?this._normalizeBearing(e.roll,s):s,u="padding"in e?e.padding:r.padding,d=t.Point.convert(e.offset);let _=r.centerPoint.add(d);const p=r.screenPointToLocation(_),m=this.cameraHelper.handleFlyTo(r,{bearing:l,pitch:c,roll:h,padding:u,locationAtOffset:p,offsetAsPoint:d,center:e.center,minZoom:e.minZoom,zoom:e.zoom});let g=e.curve;const v=Math.max(r.width,r.height),y=v/m.scaleOfZoom,x=m.pixelPathLength;"number"==typeof m.scaleOfMinZoom&&(g=Math.sqrt(v/m.scaleOfMinZoom/x*2));const b=g*g;function w(e){const t=(y*y-v*v+(e?-1:1)*b*b*x*x)/(2*(e?y:v)*b*x);return Math.log(Math.sqrt(t*t+1)-t)}function T(e){return (Math.exp(e)-Math.exp(-e))/2}function E(e){return (Math.exp(e)+Math.exp(-e))/2}const P=w(!1);let I=function(e){return E(P)/E(P+g*e)},C=function(e){return v*((E(P)*(T(t=P+g*e)/E(t))-T(P))/b)/x;var t;},M=(w(!0)-P)/g;if(Math.abs(x)<2e-6||!isFinite(M)){if(Math.abs(v-y)<1e-6)return this.easeTo(e,i);const t=y0,I=e=>Math.exp(t*g*e);}return e.duration="duration"in e?+e.duration:1e3*M/("screenSpeed"in e?+e.screenSpeed/g:+e.speed),e.maxDuration&&e.duration>e.maxDuration&&(e.duration=0),this._zooming=!0,this._rotating=o!==l,this._pitching=c!==a,this._rolling=h!==s,this._padding=!r.isPaddingEqual(u),this._prepareEase(i,!1),this.terrain&&this._prepareElevation(m.targetCenter),this._ease((p=>{const f=p*M,g=1/I(f),v=C(f);this._rotating&&r.setBearing(t.interpolateFactory.number(o,l,p)),this._pitching&&r.setPitch(t.interpolateFactory.number(a,c,p)),this._rolling&&r.setRoll(t.interpolateFactory.number(s,h,p)),this._padding&&(r.interpolatePadding(n,u,p),_=r.centerPoint.add(d)),m.easeFunc(p,g,v,_),this.terrain&&!e.freezeElevation&&this._updateElevation(p),this._applyUpdatedTransform(r),this._fireMoveEvents(i);}),(()=>{this.terrain&&e.freezeElevation&&this._finalizeElevation(),this._afterEase(i);}),e),this}isEasing(){return !!this._easeFrameId}stop(){return this._stop()}_stop(e,t){var i;if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),delete this._easeFrameId,delete this._onEaseFrame),this._onEaseEnd){const e=this._onEaseEnd;delete this._onEaseEnd,e.call(this,t);}return e||null===(i=this.handlers)||void 0===i||i.stop(!1),this}_ease(e,t,i){!1===i.animate||0===i.duration?(e(1),t()):(this._easeStart=f.now(),this._easeOptions=i,this._onEaseFrame=e,this._onEaseEnd=t,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback));}_normalizeBearing(e,i){e=t.wrap(e,-180,180);const r=Math.abs(e-i);return Math.abs(e-360-i)MapLibre'};class Ma{constructor(e=Ca){this._toggleAttribution=()=>{this._container.classList.contains("maplibregl-compact")&&(this._container.classList.contains("maplibregl-compact-show")?(this._container.setAttribute("open",""),this._container.classList.remove("maplibregl-compact-show")):(this._container.classList.add("maplibregl-compact-show"),this._container.removeAttribute("open")));},this._updateData=e=>{!e||"metadata"!==e.sourceDataType&&"visibility"!==e.sourceDataType&&"style"!==e.dataType&&"terrain"!==e.type||this._updateAttributions();},this._updateCompact=()=>{this._map.getCanvasContainer().offsetWidth<=640||this._compact?!1===this._compact?this._container.setAttribute("open",""):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")):(this._container.setAttribute("open",""),this._container.classList.contains("maplibregl-compact")&&this._container.classList.remove("maplibregl-compact","maplibregl-compact-show"));},this._updateCompactMinimize=()=>{this._container.classList.contains("maplibregl-compact")&&this._container.classList.contains("maplibregl-compact-show")&&this._container.classList.remove("maplibregl-compact-show");},this.options=e;}getDefaultPosition(){return "bottom-right"}onAdd(e){return this._map=e,this._compact=this.options.compact,this._container=wi.create("details","maplibregl-ctrl maplibregl-ctrl-attrib"),this._compactButton=wi.create("summary","maplibregl-ctrl-attrib-button",this._container),this._compactButton.addEventListener("click",this._toggleAttribution),this._setElementTitle(this._compactButton,"ToggleAttribution"),this._innerContainer=wi.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),this._container}onRemove(){wi.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=void 0,this._compact=void 0,this._sanitizedAttributionHTML=void 0;}_setElementTitle(e,t){const i=this._map._getUIString(`AttributionControl.${t}`);e.title=i,e.setAttribute("aria-label",i);}_updateAttributions(){if(!this._map.style)return;let e=[];if(this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?e=e.concat(this.options.customAttribution.map((e=>"string"!=typeof e?"":e))):"string"==typeof this.options.customAttribution&&e.push(this.options.customAttribution)),this._map.style.stylesheet){const e=this._map.style.stylesheet;this.styleOwner=e.owner,this.styleId=e.id;}const t=this._map.style.sourceCaches;for(const i in t){const r=t[i];if(r.used||r.usedForTerrain){const t=r.getSource();t.attribution&&e.indexOf(t.attribution)<0&&e.push(t.attribution);}}e=e.filter((e=>String(e).trim())),e.sort(((e,t)=>e.length-t.length)),e=e.filter(((t,i)=>{for(let r=i+1;r=0)return !1;return !0}));const i=e.join(" | ");i!==this._sanitizedAttributionHTML&&(this._sanitizedAttributionHTML=wi.sanitize(i),e.length?(this._innerContainer.innerHTML=this._sanitizedAttributionHTML,this._container.classList.remove("maplibregl-attrib-empty")):this._container.classList.add("maplibregl-attrib-empty"),this._updateCompact(),this._editLink=null);}}class Sa{constructor(e={}){this._updateCompact=()=>{const e=this._container.children;if(e.length){const t=e[0];this._map.getCanvasContainer().offsetWidth<=640||this._compact?!1!==this._compact&&t.classList.add("maplibregl-compact"):t.classList.remove("maplibregl-compact");}},this.options=e;}getDefaultPosition(){return "bottom-left"}onAdd(e){this._map=e,this._compact=this.options&&this.options.compact,this._container=wi.create("div","maplibregl-ctrl");const t=wi.create("a","maplibregl-ctrl-logo");return t.target="_blank",t.rel="noopener nofollow",t.href="https://maplibre.org/",t.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),t.setAttribute("rel","noopener nofollow"),this._container.appendChild(t),this._container.style.display="block",this._map.on("resize",this._updateCompact),this._updateCompact(),this._container}onRemove(){wi.remove(this._container),this._map.off("resize",this._updateCompact),this._map=void 0,this._compact=void 0;}}class Ra{constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1;}add(e){const t=++this._id;return this._queue.push({callback:e,id:t,cancelled:!1}),t}remove(e){const t=this._currentlyRunning,i=t?this._queue.concat(t):this._queue;for(const t of i)if(t.id===e)return void(t.cancelled=!0)}run(e=0){if(this._currentlyRunning)throw new Error("Attempting to run(), but is already running.");const t=this._currentlyRunning=this._queue;this._queue=[];for(const i of t)if(!i.cancelled&&(i.callback(e),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1;}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[];}}var Da=t.createLayout([{name:"a_pos3d",type:"Int16",components:3}]);class za extends t.Evented{constructor(e){super(),this._lastTilesetChange=f.now(),this.sourceCache=e,this._tiles={},this._renderableTilesKeys=[],this._sourceTileCache={},this.minzoom=0,this.maxzoom=22,this.deltaZoom=1,this.tileSize=e._source.tileSize*2**this.deltaZoom,e.usedForTerrain=!0,e.tileSize=this.tileSize;}destruct(){this.sourceCache.usedForTerrain=!1,this.sourceCache.tileSize=null;}update(e,i){this.sourceCache.update(e,i),this._renderableTilesKeys=[];const r={};for(const o of ve(e,{tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,reparseOverscaled:!1,terrain:i,calculateTileZoom:this.sourceCache._source.calculateTileZoom}))r[o.key]=!0,this._renderableTilesKeys.push(o.key),this._tiles[o.key]||(o.terrainRttPosMatrix32f=new Float64Array(16),t.ortho(o.terrainRttPosMatrix32f,0,t.EXTENT,t.EXTENT,0,0,1),this._tiles[o.key]=new ae(o,this.tileSize),this._lastTilesetChange=f.now());for(const e in this._tiles)r[e]||delete this._tiles[e];}freeRtt(e){for(const t in this._tiles){const i=this._tiles[t];(!e||i.tileID.equals(e)||i.tileID.isChildOf(e)||e.isChildOf(i.tileID))&&(i.rtt=[]);}}getRenderableTiles(){return this._renderableTilesKeys.map((e=>this.getTileByID(e)))}getTileByID(e){return this._tiles[e]}getTerrainCoords(e){const i={};for(const r of this._renderableTilesKeys){const o=this._tiles[r].tileID,a=e.clone(),s=t.createMat4f64();if(o.canonical.equals(e.canonical))t.ortho(s,0,t.EXTENT,t.EXTENT,0,0,1);else if(o.canonical.isChildOf(e.canonical)){const i=o.canonical.z-e.canonical.z,r=o.canonical.x-(o.canonical.x>>i<>i<>i;t.ortho(s,0,n,n,0,0,1),t.translate(s,s,[-r*n,-a*n,0]);}else {if(!e.canonical.isChildOf(o.canonical))continue;{const i=e.canonical.z-o.canonical.z,r=e.canonical.x-(e.canonical.x>>i<>i<>i;t.ortho(s,0,t.EXTENT,t.EXTENT,0,0,1),t.translate(s,s,[r*n,a*n,0]),t.scale(s,s,[1/2**i,1/2**i,0]);}}a.terrainRttPosMatrix32f=new Float32Array(s),i[r]=a;}return i}getSourceTile(e,t){const i=this.sourceCache._source;let r=e.overscaledZ-this.deltaZoom;if(r>i.maxzoom&&(r=i.maxzoom),r=i.minzoom&&(!o||!o.dem);)o=this.sourceCache.getTileByID(e.scaledTo(r--).key);return o}anyTilesAfterTime(e=Date.now()){return this._lastTilesetChange>=e}}class La{constructor(e,t,i){this.painter=e,this.sourceCache=new za(t),this.options=i,this.exaggeration="number"==typeof i.exaggeration?i.exaggeration:1,this.qualityFactor=2,this.meshSize=128,this._demMatrixCache={},this.coordsIndex=[],this._coordsTextureSize=1024;}getDEMElevation(e,i,r,o=t.EXTENT){var a;if(!(i>=0&&i=0&&re.canonical.z&&(e.canonical.z>=r?o=e.canonical.z-r:t.warnOnce("cannot calculate elevation if elevation maxzoom > source.maxzoom"));const a=e.canonical.x-(e.canonical.x>>o<>o<>8<<4|e>>8,i[t+3]=0;const r=new t.RGBAImage({width:this._coordsTextureSize,height:this._coordsTextureSize},new Uint8Array(i.buffer)),o=new y(e,r,e.gl.RGBA,{premultiply:!1});return o.bind(e.gl.NEAREST,e.gl.CLAMP_TO_EDGE),this._coordsTexture=o,o}pointCoordinate(e){this.painter.maybeDrawDepthAndCoords(!0);const i=new Uint8Array(4),r=this.painter.context,o=r.gl,a=Math.round(e.x*this.painter.pixelRatio/devicePixelRatio),s=Math.round(e.y*this.painter.pixelRatio/devicePixelRatio),n=Math.round(this.painter.height/devicePixelRatio);r.bindFramebuffer.set(this.getFramebuffer("coords").framebuffer),o.readPixels(a,n-s-1,1,1,o.RGBA,o.UNSIGNED_BYTE,i),r.bindFramebuffer.set(null);const l=i[0]+(i[2]>>4<<8),c=i[1]+((15&i[2])<<8),h=this.coordsIndex[255-i[3]],u=h&&this.sourceCache.getTileByID(h);if(!u)return null;const d=this._coordsTextureSize,_=(1<e.id!==t)),this._recentlyUsed.push(e.id);}stampObject(e){e.stamp=++this._stamp;}getOrCreateFreeObject(){for(const e of this._recentlyUsed)if(!this._objects[e].inUse)return this._objects[e];if(this._objects.length>=this._size)throw new Error("No free RenderPool available, call freeAllObjects() required!");const e=this._createObject(this._objects.length);return this._objects.push(e),e}freeObject(e){e.inUse=!1;}freeAllObjects(){for(const e of this._objects)this.freeObject(e);}isFull(){return !(this._objects.length!e.inUse))}}const ka={background:!0,fill:!0,line:!0,raster:!0,hillshade:!0};class Fa{constructor(e,t){this.painter=e,this.terrain=t,this.pool=new Aa(e.context,30,t.sourceCache.tileSize*t.qualityFactor);}destruct(){this.pool.destruct();}getTexture(e){return this.pool.getObjectForId(e.rtt[this._stacks.length-1].id).texture}prepareForRender(e,t){this._stacks=[],this._prevType=null,this._rttTiles=[],this._renderableTiles=this.terrain.sourceCache.getRenderableTiles(),this._renderableLayerIds=e._order.filter((i=>!e._layers[i].isHidden(t))),this._coordsAscending={};for(const t in e.sourceCaches){this._coordsAscending[t]={};const i=e.sourceCaches[t].getVisibleCoordinates();for(const e of i){const i=this.terrain.sourceCache.getTerrainCoords(e);for(const e in i)this._coordsAscending[t][e]||(this._coordsAscending[t][e]=[]),this._coordsAscending[t][e].push(i[e]);}}this._coordsAscendingStr={};for(const t of e._order){const i=e._layers[t],r=i.source;if(ka[i.type]&&!this._coordsAscendingStr[r]){this._coordsAscendingStr[r]={};for(const e in this._coordsAscending[r])this._coordsAscendingStr[r][e]=this._coordsAscending[r][e].map((e=>e.key)).sort().join();}}for(const e of this._renderableTiles)for(const t in this._coordsAscendingStr){const i=this._coordsAscendingStr[t][e.tileID.key];i&&i!==e.rttCoords[t]&&(e.rtt=[]);}}renderLayer(e,i){if(e.isHidden(this.painter.transform.zoom))return !1;const r=Object.assign(Object.assign({},i),{isRenderingToTexture:!0}),o=e.type,a=this.painter,s=this._renderableLayerIds[this._renderableLayerIds.length-1]===e.id;if(ka[o]&&(this._prevType&&ka[this._prevType]||this._stacks.push([]),this._prevType=o,this._stacks[this._stacks.length-1].push(e.id),!s))return !0;if(ka[this._prevType]||ka[o]&&s){this._prevType=o;const e=this._stacks.length-1,i=this._stacks[e]||[];for(const o of this._renderableTiles){if(this.pool.isFull()&&(To(this.painter,this.terrain,this._rttTiles,r),this._rttTiles=[],this.pool.freeAllObjects()),this._rttTiles.push(o),o.rtt[e]){const t=this.pool.getObjectForId(o.rtt[e].id);if(t.stamp===o.rtt[e].stamp){this.pool.useObject(t);continue}}const s=this.pool.getOrCreateFreeObject();this.pool.useObject(s),this.pool.stampObject(s),o.rtt[e]={id:s.id,stamp:s.stamp},a.context.bindFramebuffer.set(s.fbo.framebuffer),a.context.clear({color:t.Color.transparent,stencil:0}),a.currentStencilSource=void 0;for(let e=0;ei.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(null!=i.minPitch&&null!=i.maxPitch&&i.minPitch>i.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(null!=i.minPitch&&i.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(null!=i.maxPitch&&i.maxPitch>180)throw new Error("maxPitch must be less than or equal to 180");const r=new Ft,o=new Ut;if(void 0!==i.minZoom&&r.setMinZoom(i.minZoom),void 0!==i.maxZoom&&r.setMaxZoom(i.maxZoom),void 0!==i.minPitch&&r.setMinPitch(i.minPitch),void 0!==i.maxPitch&&r.setMaxPitch(i.maxPitch),void 0!==i.renderWorldCopies&&r.setRenderWorldCopies(i.renderWorldCopies),super(r,o,{bearingSnap:i.bearingSnap}),this._idleTriggered=!1,this._crossFadingFactor=1,this._renderTaskQueue=new Ra,this._controls=[],this._mapId=t.uniqueId(),this._contextLost=e=>{e.preventDefault(),this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this.fire(new t.Event("webglcontextlost",{originalEvent:e}));},this._contextRestored=e=>{this._setupPainter(),this.resize(),this._update(),this.fire(new t.Event("webglcontextrestored",{originalEvent:e}));},this._onMapScroll=e=>{if(e.target===this._container)return this._container.scrollTop=0,this._container.scrollLeft=0,!1},this._onWindowOnline=()=>{this._update();},this._interactive=i.interactive,this._maxTileCacheSize=i.maxTileCacheSize,this._maxTileCacheZoomLevels=i.maxTileCacheZoomLevels,this._failIfMajorPerformanceCaveat=!0===i.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=!0===i.preserveDrawingBuffer,this._antialias=!0===i.antialias,this._trackResize=!0===i.trackResize,this._bearingSnap=i.bearingSnap,this._centerClampedToGround=i.centerClampedToGround,this._refreshExpiredTiles=!0===i.refreshExpiredTiles,this._fadeDuration=i.fadeDuration,this._crossSourceCollisions=!0===i.crossSourceCollisions,this._collectResourceTiming=!0===i.collectResourceTiming,this._locale=Object.assign(Object.assign({},Ba),i.locale),this._clickTolerance=i.clickTolerance,this._overridePixelRatio=i.pixelRatio,this._maxCanvasSize=i.maxCanvasSize,this.transformCameraUpdate=i.transformCameraUpdate,this.cancelPendingTileRequestsWhileZooming=!0===i.cancelPendingTileRequestsWhileZooming,this._imageQueueHandle=_.addThrottleControl((()=>this.isMoving())),this._requestManager=new vi(i.transformRequest),"string"==typeof i.container){if(this._container=document.getElementById(i.container),!this._container)throw new Error(`Container '${i.container}' not found.`)}else {if(!(i.container instanceof HTMLElement))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=i.container;}if(i.maxBounds&&this.setMaxBounds(i.maxBounds),this._setupContainer(),this._setupPainter(),this.on("move",(()=>this._update(!1))),this.on("moveend",(()=>this._update(!1))),this.on("zoom",(()=>this._update(!0))),this.on("terrain",(()=>{this.painter.terrainFacilitator.dirty=!0,this._update(!0);})),this.once("idle",(()=>{this._idleTriggered=!0;})),"undefined"!=typeof window){addEventListener("online",this._onWindowOnline,!1);let e=!1;const t=Io((e=>{this._trackResize&&!this._removed&&(this.resize(e),this.redraw());}),50);this._resizeObserver=new ResizeObserver((i=>{e?t(i):e=!0;})),this._resizeObserver.observe(this._container);}this.handlers=new Pa(this,i),this._hash=i.hash&&new Co("string"==typeof i.hash&&i.hash||void 0).addTo(this),this._hash&&this._hash._onHashChange()||(this.jumpTo({center:i.center,elevation:i.elevation,zoom:i.zoom,bearing:i.bearing,pitch:i.pitch,roll:i.roll}),i.bounds&&(this.resize(),this.fitBounds(i.bounds,t.extend({},i.fitBoundsOptions,{duration:0})))),this.resize(),this._localIdeographFontFamily=i.localIdeographFontFamily,this._validateStyle=i.validateStyle,i.style&&this.setStyle(i.style,{localIdeographFontFamily:i.localIdeographFontFamily}),i.attributionControl&&this.addControl(new Ma("boolean"==typeof i.attributionControl?void 0:i.attributionControl)),i.maplibreLogo&&this.addControl(new Sa,i.logoPosition),this.on("style.load",(()=>{if(this.transform.unmodified){const e=t.pick(this.style.stylesheet,["center","zoom","bearing","pitch","roll"]);this.jumpTo(e);}})),this.on("data",(e=>{this._update("style"===e.dataType),this.fire(new t.Event(`${e.dataType}data`,e));})),this.on("dataloading",(e=>{this.fire(new t.Event(`${e.dataType}dataloading`,e));})),this.on("dataabort",(e=>{this.fire(new t.Event("sourcedataabort",e));}));}_getMapId(){return this._mapId}addControl(e,i){if(void 0===i&&(i=e.getDefaultPosition?e.getDefaultPosition():"top-right"),!e||!e.onAdd)return this.fire(new t.ErrorEvent(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));const r=e.onAdd(this);this._controls.push(e);const o=this._controlPositions[i];return -1!==i.indexOf("bottom")?o.insertBefore(r,o.firstChild):o.appendChild(r),this}removeControl(e){if(!e||!e.onRemove)return this.fire(new t.ErrorEvent(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));const i=this._controls.indexOf(e);return i>-1&&this._controls.splice(i,1),e.onRemove(this),this}hasControl(e){return this._controls.indexOf(e)>-1}calculateCameraOptionsFromTo(e,t,i,r){return null==r&&this.terrain&&(r=this.terrain.getElevationForLngLatZoom(i,this.transform.tileZoom)),super.calculateCameraOptionsFromTo(e,t,i,r)}resize(e){var i;const r=this._containerDimensions(),o=r[0],a=r[1],s=this._getClampedPixelRatio(o,a);if(this._resizeCanvas(o,a,s),this.painter.resize(o,a,s),this.painter.overLimit()){const e=this.painter.context.gl;this._maxCanvasSize=[e.drawingBufferWidth,e.drawingBufferHeight];const t=this._getClampedPixelRatio(o,a);this._resizeCanvas(o,a,t),this.painter.resize(o,a,t);}this.transform.resize(o,a),null===(i=this._requestedCameraState)||void 0===i||i.resize(o,a);const n=!this._moving;return n&&(this.stop(),this.fire(new t.Event("movestart",e)).fire(new t.Event("move",e))),this.fire(new t.Event("resize",e)),n&&this.fire(new t.Event("moveend",e)),this}_getClampedPixelRatio(e,t){const{0:i,1:r}=this._maxCanvasSize,o=this.getPixelRatio(),a=e*o,s=t*o;return Math.min(a>i?i/a:1,s>r?r/s:1)*o}getPixelRatio(){var e;return null!==(e=this._overridePixelRatio)&&void 0!==e?e:devicePixelRatio}setPixelRatio(e){this._overridePixelRatio=e,this.resize();}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()}setMaxBounds(e){return this.transform.setMaxBounds(V.convert(e)),this._update()}setMinZoom(e){if((e=null==e?-2:e)>=-2&&e<=this.transform.maxZoom)return this.transform.setMinZoom(e),this._update(),this.getZoom()=this.transform.minZoom)return this.transform.setMaxZoom(e),this._update(),this.getZoom()>e&&this.setZoom(e),this;throw new Error("maxZoom must be greater than the current minZoom")}getMaxZoom(){return this.transform.maxZoom}setMinPitch(e){if((e=null==e?0:e)<0)throw new Error("minPitch must be greater than or equal to 0");if(e>=0&&e<=this.transform.maxPitch)return this.transform.setMinPitch(e),this._update(),this.getPitch()180)throw new Error("maxPitch must be less than or equal to 180");if(e>=this.transform.minPitch)return this.transform.setMaxPitch(e),this._update(),this.getPitch()>e&&this.setPitch(e),this;throw new Error("maxPitch must be greater than the current minPitch")}getMaxPitch(){return this.transform.maxPitch}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(e){return this.transform.setRenderWorldCopies(e),this._update()}project(e){return this.transform.locationToScreenPoint(t.LngLat.convert(e),this.style&&this.terrain)}unproject(e){return this.transform.screenPointToLocation(t.Point.convert(e),this.terrain)}isMoving(){var e;return this._moving||(null===(e=this.handlers)||void 0===e?void 0:e.isMoving())}isZooming(){var e;return this._zooming||(null===(e=this.handlers)||void 0===e?void 0:e.isZooming())}isRotating(){var e;return this._rotating||(null===(e=this.handlers)||void 0===e?void 0:e.isRotating())}_createDelegatedListener(e,t,i){if("mouseenter"===e||"mouseover"===e){let r=!1;const o=o=>{const a=t.filter((e=>this.getLayer(e))),s=0!==a.length?this.queryRenderedFeatures(o.point,{layers:a}):[];s.length?r||(r=!0,i.call(this,new Bo(e,this,o.originalEvent,{features:s}))):r=!1;};return {layers:t,listener:i,delegates:{mousemove:o,mouseout:()=>{r=!1;}}}}if("mouseleave"===e||"mouseout"===e){let r=!1;const o=o=>{const a=t.filter((e=>this.getLayer(e)));(0!==a.length?this.queryRenderedFeatures(o.point,{layers:a}):[]).length?r=!0:r&&(r=!1,i.call(this,new Bo(e,this,o.originalEvent)));},a=t=>{r&&(r=!1,i.call(this,new Bo(e,this,t.originalEvent)));};return {layers:t,listener:i,delegates:{mousemove:o,mouseout:a}}}{const r=e=>{const r=t.filter((e=>this.getLayer(e))),o=0!==r.length?this.queryRenderedFeatures(e.point,{layers:r}):[];o.length&&(e.features=o,i.call(this,e),delete e.features);};return {layers:t,listener:i,delegates:{[e]:r}}}}_saveDelegatedListener(e,t){this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[e]=this._delegatedListeners[e]||[],this._delegatedListeners[e].push(t);}_removeDelegatedListener(e,t,i){if(!this._delegatedListeners||!this._delegatedListeners[e])return;const r=this._delegatedListeners[e];for(let e=0;et.includes(e)))){for(const e in o.delegates)this.off(e,o.delegates[e]);return void r.splice(e,1)}}}on(e,t,i){if(void 0===i)return super.on(e,t);const r="string"==typeof t?[t]:t,o=this._createDelegatedListener(e,r,i);this._saveDelegatedListener(e,o);for(const e in o.delegates)this.on(e,o.delegates[e]);return {unsubscribe:()=>{this._removeDelegatedListener(e,r,i);}}}once(e,t,i){if(void 0===i)return super.once(e,t);const r="string"==typeof t?[t]:t,o=this._createDelegatedListener(e,r,i);for(const t in o.delegates){const a=o.delegates[t];o.delegates[t]=(...t)=>{this._removeDelegatedListener(e,r,i),a(...t);};}this._saveDelegatedListener(e,o);for(const e in o.delegates)this.once(e,o.delegates[e]);return this}off(e,t,i){return void 0===i?super.off(e,t):(this._removeDelegatedListener(e,"string"==typeof t?[t]:t,i),this)}queryRenderedFeatures(e,i){if(!this.style)return [];let r;const o=e instanceof t.Point||Array.isArray(e),a=o?e:[[0,0],[this.transform.width,this.transform.height]];if(i=i||(o?{}:e)||{},a instanceof t.Point||"number"==typeof a[0])r=[t.Point.convert(a)];else {const e=t.Point.convert(a[0]),i=t.Point.convert(a[1]);r=[e,new t.Point(i.x,e.y),i,new t.Point(e.x,i.y),e];}return this.style.queryRenderedFeatures(r,i,this.transform)}querySourceFeatures(e,t){return this.style.querySourceFeatures(e,t)}setStyle(e,i){return !1!==(i=t.extend({},{localIdeographFontFamily:this._localIdeographFontFamily,validate:this._validateStyle},i)).diff&&i.localIdeographFontFamily===this._localIdeographFontFamily&&this.style&&e?(this._diffStyle(e,i),this):(this._localIdeographFontFamily=i.localIdeographFontFamily,this._updateStyle(e,i))}setTransformRequest(e){return this._requestManager.setTransformRequest(e),this}_getUIString(e){const t=this._locale[e];if(null==t)throw new Error(`Missing UI string '${e}'`);return t}_updateStyle(e,t){var i,r;if(t.transformStyle&&this.style&&!this.style._loaded)return void this.style.once("style.load",(()=>this._updateStyle(e,t)));const o=this.style&&t.transformStyle?this.style.serialize():void 0;return this.style&&(this.style.setEventedParent(null),this.style._remove(!e)),e?(this.style=new gi(this,t||{}),this.style.setEventedParent(this,{style:this.style}),"string"==typeof e?this.style.loadURL(e,t,o):this.style.loadJSON(e,t,o),this):(null===(r=null===(i=this.style)||void 0===i?void 0:i.projection)||void 0===r||r.destroy(),delete this.style,this)}_lazyInitEmptyStyle(){this.style||(this.style=new gi(this,{}),this.style.setEventedParent(this,{style:this.style}),this.style.loadEmpty());}_diffStyle(e,i){if("string"==typeof e){const r=this._requestManager.transformRequest(e,"Style");t.getJSON(r,new AbortController).then((e=>{this._updateDiff(e.data,i);})).catch((e=>{e&&this.fire(new t.ErrorEvent(e));}));}else "object"==typeof e&&this._updateDiff(e,i);}_updateDiff(e,i){try{this.style.setState(e,i)&&this._update(!0);}catch(r){t.warnOnce(`Unable to perform style diff: ${r.message||r.error||r}. Rebuilding the style from scratch.`),this._updateStyle(e,i);}}getStyle(){if(this.style)return this.style.serialize()}isStyleLoaded(){return this.style?this.style.loaded():t.warnOnce("There is no style added to the map.")}addSource(e,t){return this._lazyInitEmptyStyle(),this.style.addSource(e,t),this._update(!0)}isSourceLoaded(e){const i=this.style&&this.style.sourceCaches[e];if(void 0!==i)return i.loaded();this.fire(new t.ErrorEvent(new Error(`There is no source with ID '${e}'`)));}setTerrain(e){if(this.style._checkLoaded(),this._terrainDataCallback&&this.style.off("data",this._terrainDataCallback),e){const i=this.style.sourceCaches[e.source];if(!i)throw new Error(`cannot load terrain, because there exists no source with ID: ${e.source}`);null===this.terrain&&i.reload();for(const i in this.style._layers){const r=this.style._layers[i];"hillshade"===r.type&&r.source===e.source&&t.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 La(this.painter,i,e),this.painter.renderToTexture=new Fa(this.painter,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._terrainDataCallback=t=>{"style"===t.dataType?this.terrain.sourceCache.freeRtt():"source"===t.dataType&&t.tile&&(t.sourceId!==e.source||this._elevationFreeze||(this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))),this.terrain.sourceCache.freeRtt(t.tile.tileID));},this.style.on("data",this._terrainDataCallback);}else this.terrain&&this.terrain.sourceCache.destruct(),this.terrain=null,this.painter.renderToTexture&&this.painter.renderToTexture.destruct(),this.painter.renderToTexture=null,this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0);return this.fire(new t.Event("terrain",{terrain:e})),this}getTerrain(){var e,t;return null!==(t=null===(e=this.terrain)||void 0===e?void 0:e.options)&&void 0!==t?t:null}areTilesLoaded(){const e=this.style&&this.style.sourceCaches;for(const t in e){const i=e[t]._tiles;for(const e in i){const t=i[e];if("loaded"!==t.state&&"errored"!==t.state)return !1}}return !0}removeSource(e){return this.style.removeSource(e),this._update(!0)}getSource(e){return this.style.getSource(e)}addImage(e,i,r={}){const{pixelRatio:o=1,sdf:a=!1,stretchX:s,stretchY:n,content:l,textFitWidth:c,textFitHeight:h}=r;if(this._lazyInitEmptyStyle(),!(i instanceof HTMLImageElement||t.isImageBitmap(i))){if(void 0===i.width||void 0===i.height)return this.fire(new t.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`")));{const{width:r,height:u,data:d}=i,_=i;return this.style.addImage(e,{data:new t.RGBAImage({width:r,height:u},new Uint8Array(d)),pixelRatio:o,stretchX:s,stretchY:n,content:l,textFitWidth:c,textFitHeight:h,sdf:a,version:0,userImage:_}),_.onAdd&&_.onAdd(this,e),this}}{const{width:r,height:u,data:d}=f.getImageData(i);this.style.addImage(e,{data:new t.RGBAImage({width:r,height:u},d),pixelRatio:o,stretchX:s,stretchY:n,content:l,textFitWidth:c,textFitHeight:h,sdf:a,version:0});}}updateImage(e,i){const r=this.style.getImage(e);if(!r)return this.fire(new t.ErrorEvent(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));const o=i instanceof HTMLImageElement||t.isImageBitmap(i)?f.getImageData(i):i,{width:a,height:s,data:n}=o;if(void 0===a||void 0===s)return this.fire(new t.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(a!==r.data.width||s!==r.data.height)return this.fire(new t.ErrorEvent(new Error("The width and height of the updated image must be that same as the previous version of the image")));const l=!(i instanceof HTMLImageElement||t.isImageBitmap(i));return r.data.replace(n,l),this.style.updateImage(e,r),this}getImage(e){return this.style.getImage(e)}hasImage(e){return e?!!this.style.getImage(e):(this.fire(new t.ErrorEvent(new Error("Missing required image id"))),!1)}removeImage(e){this.style.removeImage(e);}loadImage(e){return _.getImage(this._requestManager.transformRequest(e,"Image"),new AbortController)}listImages(){return this.style.listImages()}addLayer(e,t){return this._lazyInitEmptyStyle(),this.style.addLayer(e,t),this._update(!0)}moveLayer(e,t){return this.style.moveLayer(e,t),this._update(!0)}removeLayer(e){return this.style.removeLayer(e),this._update(!0)}getLayer(e){return this.style.getLayer(e)}getLayersOrder(){return this.style.getLayersOrder()}setLayerZoomRange(e,t,i){return this.style.setLayerZoomRange(e,t,i),this._update(!0)}setFilter(e,t,i={}){return this.style.setFilter(e,t,i),this._update(!0)}getFilter(e){return this.style.getFilter(e)}setPaintProperty(e,t,i,r={}){return this.style.setPaintProperty(e,t,i,r),this._update(!0)}getPaintProperty(e,t){return this.style.getPaintProperty(e,t)}setLayoutProperty(e,t,i,r={}){return this.style.setLayoutProperty(e,t,i,r),this._update(!0)}getLayoutProperty(e,t){return this.style.getLayoutProperty(e,t)}setGlyphs(e,t={}){return this._lazyInitEmptyStyle(),this.style.setGlyphs(e,t),this._update(!0)}getGlyphs(){return this.style.getGlyphsUrl()}addSprite(e,t,i={}){return this._lazyInitEmptyStyle(),this.style.addSprite(e,t,i,(e=>{e||this._update(!0);})),this}removeSprite(e){return this._lazyInitEmptyStyle(),this.style.removeSprite(e),this._update(!0)}getSprite(){return this.style.getSprite()}setSprite(e,t={}){return this._lazyInitEmptyStyle(),this.style.setSprite(e,t,(e=>{e||this._update(!0);})),this}setLight(e,t={}){return this._lazyInitEmptyStyle(),this.style.setLight(e,t),this._update(!0)}getLight(){return this.style.getLight()}setSky(e,t={}){return this._lazyInitEmptyStyle(),this.style.setSky(e,t),this._update(!0)}getSky(){return this.style.getSky()}setFeatureState(e,t){return this.style.setFeatureState(e,t),this._update()}removeFeatureState(e,t){return this.style.removeFeatureState(e,t),this._update()}getFeatureState(e){return this.style.getFeatureState(e)}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}_containerDimensions(){let e=0,t=0;return this._container&&(e=this._container.clientWidth||400,t=this._container.clientHeight||300),[e,t]}_setupContainer(){const e=this._container;e.classList.add("maplibregl-map");const t=this._canvasContainer=wi.create("div","maplibregl-canvas-container",e);this._interactive&&t.classList.add("maplibregl-interactive"),this._canvas=wi.create("canvas","maplibregl-canvas",t),this._canvas.addEventListener("webglcontextlost",this._contextLost,!1),this._canvas.addEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.setAttribute("tabindex",this._interactive?"0":"-1"),this._canvas.setAttribute("aria-label",this._getUIString("Map.Title")),this._canvas.setAttribute("role","region");const i=this._containerDimensions(),r=this._getClampedPixelRatio(i[0],i[1]);this._resizeCanvas(i[0],i[1],r);const o=this._controlContainer=wi.create("div","maplibregl-control-container",e),a=this._controlPositions={};["top-left","top-right","bottom-left","bottom-right"].forEach((e=>{a[e]=wi.create("div",`maplibregl-ctrl-${e} `,o);})),this._container.addEventListener("scroll",this._onMapScroll,!1);}_resizeCanvas(e,t,i){this._canvas.width=Math.floor(i*e),this._canvas.height=Math.floor(i*t),this._canvas.style.width=`${e}px`,this._canvas.style.height=`${t}px`;}_setupPainter(){const e={alpha:!0,stencil:!0,depth:!0,failIfMajorPerformanceCaveat:this._failIfMajorPerformanceCaveat,preserveDrawingBuffer:this._preserveDrawingBuffer,antialias:this._antialias||!1};let t=null;this._canvas.addEventListener("webglcontextcreationerror",(i=>{t={requestedAttributes:e},i&&(t.statusMessage=i.statusMessage,t.type=i.type);}),{once:!0});const i=this._canvas.getContext("webgl2",e)||this._canvas.getContext("webgl",e);if(!i){const e="Failed to initialize WebGL";throw t?(t.message=e,new Error(JSON.stringify(t))):new Error(e)}this.painter=new Po(i,this.transform),n.testSupport(i);}migrateProjection(e,i){super.migrateProjection(e,i),this.painter.transform=e,this.fire(new t.Event("projectiontransition",{newProjection:this.style.projection.name}));}loaded(){return !this._styleDirty&&!this._sourcesDirty&&!!this.style&&this.style.loaded()}_update(e){return this.style&&this.style._loaded?(this._styleDirty=this._styleDirty||e,this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(e){return this._update(),this._renderTaskQueue.add(e)}_cancelRenderFrame(e){this._renderTaskQueue.remove(e);}_render(e){const i=this._idleTriggered?this._fadeDuration:0;if(this.painter.context.setDirty(),this.painter.setBaseState(),this._renderTaskQueue.run(e),this._removed)return;let r=!1;if(this.style&&this._styleDirty){this._styleDirty=!1;const e=this.transform.zoom,o=f.now();this.style.zoomHistory.update(e,o);const a=new t.EvaluationParameters(e,{now:o,fadeDuration:i,zoomHistory:this.style.zoomHistory,transition:this.style.getTransition()}),s=a.crossFadingFactor();1===s&&s===this._crossFadingFactor||(r=!0,this._crossFadingFactor=s),this.style.update(a);}const o=this.transform.newFrameUpdate();this.style&&(this._sourcesDirty||o.forceSourceUpdate)&&(this._sourcesDirty=!1,this.style._updateSources(this.transform)),this.terrain?(this.terrain.sourceCache.update(this.transform,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),!this._elevationFreeze&&this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))):(this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0)),this._placementDirty=this.style&&this.style._updatePlacement(this.transform,this.showCollisionBoxes,i,this._crossSourceCollisions,o.forcePlacementUpdate),o.fireProjectionEvent&&this.fire(new t.Event("projectiontransition",o.fireProjectionEvent)),this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showOverdrawInspector:this._showOverdrawInspector,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:i,showPadding:this.showPadding}),this.fire(new t.Event("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,t.PerformanceUtils.mark(t.PerformanceMarkers.load),this.fire(new t.Event("load"))),this.style&&(this.style.hasTransitions()||r)&&(this._styleDirty=!0),this.style&&!this._placementDirty&&this.style._releaseSymbolFadeTiles();const a=this._sourcesDirty||this._styleDirty||this._placementDirty||this.style.projection.isRenderingDirty()||this.transform.isRenderingDirty();return a||this._repaint?this.triggerRepaint():!this.isMoving()&&this.loaded()&&this.fire(new t.Event("idle")),!this._loaded||this._fullyLoaded||a||(this._fullyLoaded=!0,t.PerformanceUtils.mark(t.PerformanceMarkers.fullLoad)),this}redraw(){return this.style&&(this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._render(0)),this}remove(){var e;this._hash&&this._hash.remove();for(const e of this._controls)e.onRemove(this);this._controls=[],this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._renderTaskQueue.clear(),this.painter.destroy(),this.handlers.destroy(),delete this.handlers,this.setStyle(null),"undefined"!=typeof window&&removeEventListener("online",this._onWindowOnline,!1),_.removeThrottleControl(this._imageQueueHandle),null===(e=this._resizeObserver)||void 0===e||e.disconnect();const i=this.painter.context.gl.getExtension("WEBGL_lose_context");(null==i?void 0:i.loseContext)&&i.loseContext(),this._canvas.removeEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.removeEventListener("webglcontextlost",this._contextLost,!1),wi.remove(this._canvasContainer),wi.remove(this._controlContainer),this._container.removeEventListener("scroll",this._onMapScroll,!1),this._container.classList.remove("maplibregl-map"),t.PerformanceUtils.clearMetrics(),this._removed=!0,this.fire(new t.Event("remove"));}triggerRepaint(){this.style&&!this._frameRequest&&(this._frameRequest=new AbortController,f.frameAsync(this._frameRequest).then((e=>{t.PerformanceUtils.frame(e),this._frameRequest=null,this._render(e);})).catch((()=>{})));}get showTileBoundaries(){return !!this._showTileBoundaries}set showTileBoundaries(e){this._showTileBoundaries!==e&&(this._showTileBoundaries=e,this._update());}get showPadding(){return !!this._showPadding}set showPadding(e){this._showPadding!==e&&(this._showPadding=e,this._update());}get showCollisionBoxes(){return !!this._showCollisionBoxes}set showCollisionBoxes(e){this._showCollisionBoxes!==e&&(this._showCollisionBoxes=e,e?this.style._generateCollisionBoxes():this._update());}get showOverdrawInspector(){return !!this._showOverdrawInspector}set showOverdrawInspector(e){this._showOverdrawInspector!==e&&(this._showOverdrawInspector=e,this._update());}get repaint(){return !!this._repaint}set repaint(e){this._repaint!==e&&(this._repaint=e,this.triggerRepaint());}get vertices(){return !!this._vertices}set vertices(e){this._vertices=e,this._update();}get version(){return Oa}getCameraTargetElevation(){return this.transform.elevation}getProjection(){return this.style.getProjection()}setProjection(e){return this._lazyInitEmptyStyle(),this.style.setProjection(e),this._update(!0)}};const Na=e=>new Promise(((t,i)=>{e&&(e.stubRender=null==e.stubRender||e.stubRender,e.showMap=null!=e.showMap&&e.showMap);const r=document.createElement("div");r.style.width=`${e.width||512}px`,r.style.height=`${e.height||512}px`,r.style.margin="0 auto",r.style.display="block",e.showMap||(r.style.visibility="hidden"),document.body.appendChild(r);const o=new ja(Object.assign({container:r,style:"https://api.maptiler.com/maps/streets/style.json?key=get_your_own_OpIi9ZULNHzrESv6T2vL"},e));o.on(e.idle?"idle":"load",(()=>{e.stubRender&&o._frameRequest&&(o._frameRequest.abort(),o._frameRequest=null),t(o);})),o.on("error",(e=>i(e.error))),o.on("remove",(()=>r.remove()));}));function Ga(e){return JSON.parse(JSON.stringify(e,((e,t)=>ArrayBuffer.isView(t)?{}:t))||"{}")}class Za extends a{constructor(e,t){super(),this.style=e,this.locations=t;}setup(){return t.__awaiter(this,void 0,void 0,(function*(){try{this.maps=yield Promise.all(this.locations.map((e=>Na({zoom:e.zoom,width:1024,height:768,center:e.center,style:this.style}))));}catch(e){console.error(e);}}))}bench(){for(const e of this.maps)e._styleDirty=!0,e._sourcesDirty=!0,e._render(Date.now());}teardown(){for(const e of this.maps)e.remove();}}var Va={version:8,name:"Empty",sources:{openmaptiles:{url:"https://api.maptiler.com/tiles/v3/tiles.json?key=get_your_own_OpIi9ZULNHzrESv6T2vL",type:"vector"},maptiler_attribution:{type:"vector",attribution:'<a href="https://www.maptiler.com/copyright/"; target="_blank">&copy; MapTiler</a> <a href="https://www.openstreetmap.org/copyright"; target="_blank">&copy; OpenStreetMap contributors</a>'}},sprite:"https://api.maptiler.com/maps/streets/sprite",glyphs:"https://api.maptiler.com/fonts/{fontstack}/{range}.pbf?key=get_your_own_OpIi9ZULNHzrESv6T2vL",layers:[]};function qa(e){const t=[];for(let i=0;i<50;i++)t.push(Object.assign({},e,{id:e.id+i}));return t}function Wa(e){const t=[];for(let i=0;i<50;i++)t.push(Object.assign({},e,{id:e.id+i}));return t}class Xa extends a{constructor(e){super(),this.center=e;}setup(){return t.__awaiter(this,void 0,void 0,(function*(){const e=yield fetch("/test/bench/data/naturalearth-land.json"),t=yield e.json();this.numFeatures=t.features.length;const i=Object.assign({},Va,{sources:{land:{type:"geojson",data:t,maxzoom:23}},layers:Wa({id:"layer",type:"fill",source:"land",paint:{"fill-color":["case",["boolean",["feature-state","bench"],!1],["rgb",21,210,210],["rgb",233,233,233]]}})});try{this.map=yield Na({zoom:4,width:1024,height:768,center:this.center,style:i});}catch(e){console.error(e);}}))}bench(){this.map._styleDirty=!0,this.map._sourcesDirty=!0,this.map._render();}teardown(){this.map.remove();}}function $a(e){const t=[];for(let i=0;i<50;i++)t.push(Object.assign({},e,{id:e.id+i}));return t}class Ha extends a{setup(){return t.__awaiter(this,void 0,void 0,(function*(){try{this.map=yield Na({zoom:16,width:1024,height:768,center:[-77.032194,38.912753],style:this.layerStyle});}catch(e){console.error(e);}}))}bench(){this.map._render();}teardown(){this.map.remove();}}class Ka extends a{constructor(e){super(),this.style=e;}setup(){return t.__awaiter(this,void 0,void 0,(function*(){this.json=yield s(this.style);}))}bench(){t.validateStyleMin(this.json);}}class Ya extends a{constructor(e){super(),this.style=e;}setup(){return t.__awaiter(this,void 0,void 0,(function*(){const e=yield s(this.style);this.layers=t.derefLayers(e.layers);}))}bench(){for(const e of this.layers)t.createStyleLayer(e);}}const Ja=[];for(let e=0;e<4;e++)for(let t=0;t<4;t++)Ja.push([e/4*1024,t/4*768]);class Qa extends a{constructor(e,t){super(),this.style=e,this.locations=t;}setup(){return t.__awaiter(this,void 0,void 0,(function*(){try{this.maps=yield Promise.all(this.locations.map((e=>Na({zoom:e.zoom,width:1024,height:768,center:e.center,style:this.style}))));}catch(e){console.error(e);}}))}bench(){for(const e of this.maps)for(const t of Ja)e.queryRenderedFeatures(t,{});}teardown(){for(const e of this.maps)e.remove();}}class es extends a{constructor(e,t){super(),this.style=e,this.locations=t;}setup(){return t.__awaiter(this,void 0,void 0,(function*(){try{this.maps=yield Promise.all(this.locations.map((e=>Na({zoom:e.zoom,width:1024,height:768,center:e.center,style:this.style}))));}catch(e){console.error(e);}}))}bench(){for(const e of this.maps)e.queryRenderedFeatures({});}teardown(){for(const e of this.maps)e.remove();}}class ts extends a{constructor(e){super(),this.style=e;}setup(){return t.__awaiter(this,void 0,void 0,(function*(){const e=yield s(this.style);this.data=[];for(const i of e.layers){if(!i.type)continue;const e=(e,i)=>{const r=t.convertFunction(e,i),o=t.createFunction(e,i),a=t.createPropertyExpression(r,i);if("error"===a.result)throw new Error(a.value.map((e=>`${e.key}: ${e.message}`)).join(", "));return {propertySpec:i,rawValue:e,rawExpression:r,compiledFunction:o,compiledExpression:a.value}};for(const r in i.paint)t.isFunction$1(i.paint[r])&&this.data.push(e(i.paint[r],t.v8Spec[`paint_${i.type}`][r]));for(const r in i.layout)t.isFunction$1(i.layout[r])&&this.data.push(e(i.layout[r],t.v8Spec[`layout_${i.type}`][r]));}}))}}var is=[{filter:["==",["get","class"],"crop"],layer:"landcover"},{filter:["==",["get","class"],"grass"],layer:"landcover"},{filter:["==",["get","class"],"scrub"],layer:"landcover"},{filter:["==",["get","class"],"wood"],layer:"landcover"},{filter:["==",["get","class"],"snow"],layer:"landcover"},{filter:["==",["get","class"],"hospital"],layer:"landuse"},{filter:["==",["get","class"],"school"],layer:"landuse"},{filter:["==",["get","class"],"park"],layer:"landuse"},{filter:["==",["get","class"],"pitch"],layer:"landuse"},{filter:["==",["get","class"],"pitch"],layer:"landuse"},{filter:["==",["get","class"],"cemetery"],layer:"landuse"},{filter:["==",["get","class"],"industrial"],layer:"landuse"},{filter:["==",["get","class"],"sand"],layer:"landuse"},{filter:["==",["get","level"],94],layer:"hillshade"},{filter:["==",["get","level"],90],layer:"hillshade"},{filter:["==",["get","level"],89],layer:"hillshade"},{filter:["==",["get","level"],78],layer:"hillshade"},{filter:["==",["get","level"],67],layer:"hillshade"},{filter:["==",["get","level"],56],layer:"hillshade"},{filter:["all",["match",["get","class"],["river","canal"],!0,!1]],layer:"waterway"},{filter:["all",["==",["get","class"],"land"],["==",["geometry-type"],"Polygon"]],layer:"barrier_line"},{filter:["all",["==",["get","class"],"land"],["==",["geometry-type"],"LineString"]],layer:"barrier_line"},{filter:["all",["==",["get","type"],"apron"],["==",["geometry-type"],"Polygon"]],layer:"aeroway"},{filter:["all",["==",["get","class"],"street_limited"],["==",["geometry-type"],"Polygon"]],layer:"tunnel"},{filter:["==",["get","class"],"path"],layer:"tunnel"},{filter:["all",["==",["get","class"],"street"],["==",["geometry-type"],"LineString"]],layer:"tunnel"},{filter:["all",["==",["get","class"],"street_limited"],["==",["geometry-type"],"LineString"]],layer:"tunnel"},{filter:["==",["get","class"],"motorway_link"],layer:"tunnel"},{filter:["match",["get","class"],["service","driveway"],!0,!1],layer:"tunnel"},{filter:["all",["==",["get","class"],"street_limited"],["!=",["get","type"],"construction"],["==",["geometry-type"],"LineString"]],layer:"tunnel"},{filter:["==",["get","class"],"street"],layer:"tunnel"},{filter:["all",["==",["get","class"],"main"],["!=",["get","type"],"trunk"]],layer:"tunnel"},{filter:["all",["==",["get","class"],"main"],["==",["get","type"],"trunk"]],layer:"tunnel"},{filter:["==",["get","class"],"motorway"],layer:"tunnel"},{filter:["all",["==",["get","class"],"street_limited"],["==",["get","type"],"construction"],["==",["geometry-type"],"LineString"]],layer:"tunnel"},{filter:["all",["==",["get","oneway"],1],["match",["get","class"],["main","street","street_limited"],!0,!1],["!=",["get","type"],"trunk"]],layer:"tunnel"},{filter:["all",["==",["get","oneway"],1],["==",["get","type"],"trunk"]],layer:"tunnel"},{filter:["match",["get","class"],["major_rail","minor_rail"],!0,!1],layer:"tunnel"},{filter:["all",["==",["get","oneway"],1],["match",["get","class"],["motorway","motorway_link"],!0,!1]],layer:"tunnel"},{filter:["==",["get","class"],"path"],layer:"road"},{filter:["all",["==",["get","class"],"street"],["==",["geometry-type"],"LineString"]],layer:"road"},{filter:["all",["==",["get","class"],"street_limited"],["==",["geometry-type"],"LineString"]],layer:"road"},{filter:["match",["get","class"],["service","driveway"],!0,!1],layer:"road"},{filter:["all",["==",["get","class"],"street_limited"],["!=",["get","type"],"construction"],["==",["geometry-type"],"LineString"]],layer:"road"},{filter:["==",["get","class"],"street"],layer:"road"},{filter:["all",["==",["get","class"],"main"],["==",["get","type"],"trunk"]],layer:"road"},{filter:["==",["get","class"],"motorway"],layer:"road"},{filter:["all",["==",["get","oneway"],1],["match",["get","class"],["main","street","street_limited"],!0,!1],["!=",["get","type"],"trunk"]],layer:"road"},{filter:["all",["==",["get","oneway"],1],["==",["get","type"],"trunk"]],layer:"road"},{filter:["match",["get","class"],["major_rail","minor_rail"],!0,!1],layer:"road"},{filter:["all",["==",["get","class"],"street_limited"],["==",["get","type"],"construction"],["==",["geometry-type"],"LineString"]],layer:"road"},{filter:["all",["==",["get","oneway"],1],["match",["get","class"],["motorway","motorway_link"],!0,!1]],layer:"road"},{filter:["all",["==",["get","class"],"street_limited"],["==",["geometry-type"],"Polygon"]],layer:"bridge"},{filter:["==",["get","class"],"path"],layer:"bridge"},{filter:["all",["==",["get","class"],"street"],["==",["geometry-type"],"LineString"]],layer:"bridge"},{filter:["all",["==",["get","class"],"street_limited"],["==",["geometry-type"],"LineString"]],layer:"bridge"},{filter:["==",["get","class"],"motorway_link"],layer:"bridge"},{filter:["match",["get","class"],["service","driveway"],!0,!1],layer:"bridge"},{filter:["all",["==",["get","class"],"street_limited"],["!=",["get","type"],"construction"],["==",["geometry-type"],"LineString"]],layer:"bridge"},{filter:["==",["get","class"],"street"],layer:"bridge"},{filter:["all",["==",["get","oneway"],1],["match",["get","class"],["main","street","street_limited"],!0,!1],["!=",["get","type"],"trunk"]],layer:"bridge"},{filter:["any",["==",["get","class"],"motorway"],["==",["get","type"],"trunk"]],layer:"bridge"},{filter:["match",["get","class"],["service","driveway"],!0,!1],layer:"bridge"},{filter:["all",["==",["get","class"],"street_limited"],["==",["get","type"],"construction"],["==",["geometry-type"],"LineString"]],layer:"bridge"},{filter:["all",["==",["get","class"],"street_limited"],["!=",["get","type"],"construction"],["==",["geometry-type"],"LineString"]],layer:"bridge"},{filter:["==",["get","class"],"street"],layer:"bridge"},{filter:["all",["==",["get","class"],"main"],["!=",["get","type"],"trunk"]],layer:"bridge"},{filter:["all",["==",["get","class"],"main"],["==",["get","type"],"trunk"]],layer:"bridge"},{filter:["all",["==",["get","oneway"],1],["==",["get","type"],"trunk"]],layer:"bridge"},{filter:["==",["get","class"],"motorway"],layer:"bridge"},{filter:["match",["get","class"],["major_rail","minor_rail"],!0,!1],layer:"bridge"},{filter:["==",["get","class"],"aerialway"],layer:"bridge"},{filter:["all",["==",["get","oneway"],1],["match",["get","class"],["motorway","motorway_link"],!0,!1]],layer:"bridge"},{filter:["==",["get","class"],"hedge"],layer:"barrier_line"},{filter:["==",["get","class"],"fence"],layer:"barrier_line"},{filter:["==",["get","class"],"gate"],layer:"barrier_line"},{filter:["all",[">=",["get","admin_level"],3],["==",["get","maritime"],0]],layer:"admin"},{filter:["all",[">=",["get","admin_level"],3],["==",["get","maritime"],0]],layer:"admin"},{filter:["!=",["get","index"],5],layer:"contour"},{filter:["==",["get","index"],5],layer:"contour"},{filter:["==",["get","class"],"river"],layer:"waterway_label"},{filter:["all",["match",["get","maki"],["rail-light","rail-metro","rail","airport","airfield","heliport","rocket","park","golf","cemetery","zoo","campsite","swimming","dog-park"],!1,!0],["==",["get","scalerank"],4],[">=",["get","localrank"],15]],layer:"poi_label"},{filter:["all",["match",["get","maki"],["rail-light","rail-metro","rail","airport","airfield","heliport","rocket","park","golf","cemetery","zoo","campsite","swimming","dog-park"],!1,!0],["==",["get","scalerank"],4],["<=",["get","localrank"],14]],layer:"poi_label"},{filter:["all",["match",["get","maki"],["park","cemetery","golf","zoo","playground"],!0,!1],["==",["get","scalerank"],4]],layer:"poi_label"},{filter:["all",["match",["get","maki"],["rail-light","rail-metro","rail","airport","airfield","heliport","rocket","park","golf","cemetery","zoo","campsite","swimming","dog-park"],!1,!0],["==",["get","scalerank"],3]],layer:"poi_label"},{filter:["all",["match",["get","maki"],["park","cemetery","golf","zoo"],!0,!1],["==",["get","scalerank"],3]],layer:"poi_label"},{filter:["all",["match",["get","class"],["motorway","main","street_limited","street"],!1,!0],["==",["geometry-type"],"LineString"]],layer:"road_label"},{filter:["all",["match",["get","class"],["street","street_limited"],!1,!0],["==",["geometry-type"],"LineString"]],layer:"road_label"},{filter:["match",["get","class"],["main","motorway"],!0,!1],layer:"road_label"},{filter:["all",["match",["get","shield"],["us-interstate","us-interstate-business","us-interstate-duplex"],!1,!0],["<=",["get","reflen"],6]],layer:"road_label"},{filter:["all",["match",["get","shield"],["us-interstate","us-interstate-business","us-interstate-duplex"],!0,!1],["<=",["get","reflen"],6]],layer:"road_label"},{filter:["all",["match",["get","maki"],["rail-light","rail-metro","rail","airport","airfield","heliport","rocket","park","golf","cemetery","zoo","campsite","swimming","dog-park"],!1,!0],["==",["get","scalerank"],2]],layer:"poi_label"},{filter:["all",["match",["get","maki"],["park","golf","cemetery","zoo","campsite","swimming","dog-park"],!0,!1],["==",["get","scalerank"],2]],layer:"poi_label"},{filter:["==",["get","type"],"Rail Station"],layer:"poi_label"},{filter:["<=",["get","area"],1e4],layer:"water_label"},{filter:["all",["match",["get","maki"],["park","golf","cemetery","zoo","campsite","swimming","dog-park"],!0,!1],["<=",["get","scalerank"],1]],layer:"poi_label"},{filter:["all",["match",["get","maki"],["rail-light","rail-metro","rail","airport","airfield","heliport","rocket","park","golf","cemetery","zoo","campsite","swimming","dog-park"],!1,!0],["<=",["get","scalerank"],1],["!=",["get","type"],"Island"]],layer:"poi_label"},{filter:["==",["get","type"],"Islet"],layer:"poi_label"},{filter:["==",["get","type"],"Island"],layer:"poi_label"},{filter:["all",["match",["get","scalerank"],[0,1,2,3,4,5],!1,!0],["==",["get","type"],"city"]],layer:"place_label"},{filter:["all",["match",["get","scalerank"],[3,4,5],!0,!1],["==",["get","type"],"city"],["match",["get","ldir"],["S","SE","SW","E"],!0,!1]],layer:"place_label"},{filter:["all",["match",["get","scalerank"],[3,4,5],!0,!1],["==",["get","type"],"city"],["match",["get","ldir"],["N","NE","NW","W"],!0,!1]],layer:"place_label"}];class rs{constructor(){this.id="tent-3d";}onAdd(e,t){const i=t.createShader(t.VERTEX_SHADER);t.shaderSource(i,"#version 300 es\n\n in vec3 aPos;\n uniform mat4 uMatrix;\n\n void main() {\n gl_Position = uMatrix * vec4(aPos, 1.0);\n }\n "),t.compileShader(i);const r=t.createShader(t.FRAGMENT_SHADER);t.shaderSource(r,"#version 300 es\n\n out highp vec4 fragColor;\n void main() {\n fragColor = vec4(1.0, 0.0, 0.0, 1.0);\n }"),t.compileShader(r),this.program=t.createProgram(),t.attachShader(this.program,i),t.attachShader(this.program,r),t.linkProgram(this.program),t.validateProgram(this.program),this.program.aPos=t.getAttribLocation(this.program,"aPos"),this.program.uMatrix=t.getUniformLocation(this.program,"uMatrix");const o=.485,a=.01,s=new Float32Array([o,.49,0,o+a,.49,0,o,.5,.01,o+a,.5,.01,o,.51,0,o+a,.51,0]),n=new Uint16Array([0,1,2,1,2,3,2,3,4,3,4,5]);this.vertexBuffer=t.createBuffer(),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),t.bufferData(t.ARRAY_BUFFER,s,t.STATIC_DRAW),this.indexBuffer=t.createBuffer(),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,n,t.STATIC_DRAW);}render(e,t){e.useProgram(this.program),e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer),e.enableVertexAttribArray(this.program.a_pos),e.vertexAttribPointer(this.program.aPos,3,e.FLOAT,!1,0,0),e.uniformMatrix4fv(this.program.uMatrix,!1,t),e.drawElements(e.TRIANGLES,12,e.UNSIGNED_SHORT,0);}}class os extends a{constructor(e){super(),this._useGlobeProjection=!1,this._useGlobeProjection=e;}_createTransform(){if(this._useGlobeProjection){const e=new Jt;return {transform:new _i(e,!0),calculatePosMatrix:e=>{}}}{const e=new Ft(0,22,0,60,!0);return {transform:e,calculatePosMatrix:t=>e.calculatePosMatrix(t,!1)}}}setup(){return t.__awaiter(this,void 0,void 0,(function*(){const{transform:e,calculatePosMatrix:i}=this._createTransform();this._transform=e,e.resize(1024,1024);const r=new t.OverscaledTileID(0,0,0,0,0),o=r.toUnwrapped(),a=(s=3735928559,function(){let e=(s=2654435769+(s|=0)|0)^s>>>16;return e=Math.imul(e,569420461),e^=e>>>15,e=Math.imul(e,1935289751),((e^=e>>>15)>>>0)/4294967296});var s;const n=(e,t)=>a()*(t-e)+e;this._symbols=[];for(let e=0;e<2e4;e++)this._symbols.push({collisionBox:{anchorPointX:n(4,t.EXTENT-4),anchorPointY:n(4,t.EXTENT-4),x1:n(-20,-2),y1:n(-20,-2),x2:n(2,20),y2:n(2,20)},overlapMode:"never",textPixelRatio:1,tileID:r,unwrappedTileID:o,pitchWithMap:a()>.5,rotateWithMap:a()>.5,translation:[n(-20,20),n(-20,20)],shift:a()>.5?new t.Point(n(-20,20),n(-20,20)):void 0,simpleProjectionMatrix:i(o)});}))}bench(){return t.__awaiter(this,void 0,void 0,(function*(){const e=new Xe(this._transform);e.grid.hitTest=(e,t,i,r,o,a)=>!0;for(const t of this._symbols)e.placeCollisionBox(t.collisionBox,t.overlapMode,t.textPixelRatio,t.tileID,t.unwrappedTileID,t.pitchWithMap,t.rotateWithMap,t.translation,null,null,t.shift,t.simpleProjectionMatrix);}))}}function as(e,i,r,o){const a=[];for(let s=0;s{e.touchstart=e.dragStart,e.touchmoveWindow=e.dragMove,e.touchend=e.dragEnd;},ns={showCompass:!0,showZoom:!0,visualizePitch:!1,visualizeRoll:!0};class ls{constructor(e,i,r=!1){this.mousedown=e=>{this.startMouse(t.extend({},e,{ctrlKey:!0,preventDefault:()=>e.preventDefault()}),wi.mousePos(this.element,e)),wi.addEventListener(window,"mousemove",this.mousemove),wi.addEventListener(window,"mouseup",this.mouseup);},this.mousemove=e=>{this.moveMouse(e,wi.mousePos(this.element,e));},this.mouseup=e=>{this.mouseRotate.dragEnd(e),this.mousePitch&&this.mousePitch.dragEnd(e),this.offTemp();},this.touchstart=e=>{1!==e.targetTouches.length?this.reset():(this._startPos=this._lastPos=wi.touchPos(this.element,e.targetTouches)[0],this.startTouch(e,this._startPos),wi.addEventListener(window,"touchmove",this.touchmove,{passive:!1}),wi.addEventListener(window,"touchend",this.touchend));},this.touchmove=e=>{1!==e.targetTouches.length?this.reset():(this._lastPos=wi.touchPos(this.element,e.targetTouches)[0],this.moveTouch(e,this._lastPos));},this.touchend=e=>{0===e.targetTouches.length&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos){this.mouseRotate.reset(),this.mousePitch&&this.mousePitch.reset(),this.touchRotate.reset(),this.touchPitch&&this.touchPitch.reset(),delete this._startPos,delete this._lastPos,this.offTemp();},this._clickTolerance=10;const o=e.dragRotate._mouseRotate.getClickTolerance(),a=e.dragRotate._mousePitch.getClickTolerance();this.element=i,this.mouseRotate=Qo({clickTolerance:o,enable:!0,aroundCenter:!1}),this.touchRotate=function({enable:e,clickTolerance:i,aroundCenter:r=!0}){const o=new Yo;return new $o({clickTolerance:i,move:(e,i,o)=>r?{bearingDelta:t.getAngleDelta(new t.Point(e.x,i.y),i,o)}:{bearingDelta:.8*(i.x-e.x)},moveStateManager:o,enable:e,assignEvents:ss})}({clickTolerance:o,enable:!0}),this.map=e,r&&(this.mousePitch=ea({clickTolerance:a,enable:!0}),this.touchPitch=function({enable:e,clickTolerance:t,pitchDegreesPerPixelMoved:i=-.5}){const r=new Yo;return new $o({clickTolerance:t,move:(e,t)=>({pitchDelta:(t.y-e.y)*i}),moveStateManager:r,enable:e,assignEvents:ss})}({clickTolerance:a,enable:!0})),wi.addEventListener(i,"mousedown",this.mousedown),wi.addEventListener(i,"touchstart",this.touchstart,{passive:!1}),wi.addEventListener(i,"touchcancel",this.reset);}startMouse(e,t){this.mouseRotate.dragStart(e,t),this.mousePitch&&this.mousePitch.dragStart(e,t),wi.disableDrag();}startTouch(e,t){this.touchRotate.dragStart(e,t),this.touchPitch&&this.touchPitch.dragStart(e,t),wi.disableDrag();}moveMouse(e,t){const i=this.map,{bearingDelta:r}=this.mouseRotate.dragMove(e,t)||{};if(r&&i.setBearing(i.getBearing()+r),this.mousePitch){const{pitchDelta:r}=this.mousePitch.dragMove(e,t)||{};r&&i.setPitch(i.getPitch()+r);}}moveTouch(e,t){const i=this.map,{bearingDelta:r}=this.touchRotate.dragMove(e,t)||{};if(r&&i.setBearing(i.getBearing()+r),this.touchPitch){const{pitchDelta:r}=this.touchPitch.dragMove(e,t)||{};r&&i.setPitch(i.getPitch()+r);}}off(){const e=this.element;wi.removeEventListener(e,"mousedown",this.mousedown),wi.removeEventListener(e,"touchstart",this.touchstart,{passive:!1}),wi.removeEventListener(window,"touchmove",this.touchmove,{passive:!1}),wi.removeEventListener(window,"touchend",this.touchend),wi.removeEventListener(e,"touchcancel",this.reset),this.offTemp();}offTemp(){wi.enableDrag(),wi.removeEventListener(window,"mousemove",this.mousemove),wi.removeEventListener(window,"mouseup",this.mouseup),wi.removeEventListener(window,"touchmove",this.touchmove,{passive:!1}),wi.removeEventListener(window,"touchend",this.touchend);}}let cs;function hs(e,i,r){const o=new t.LngLat(e.lng,e.lat);if(e=new t.LngLat(e.lng,e.lat),i){const o=new t.LngLat(e.lng-360,e.lat),a=new t.LngLat(e.lng+360,e.lat),s=r.locationToScreenPoint(e).distSqr(i);r.locationToScreenPoint(o).distSqr(i)180;){const t=r.locationToScreenPoint(e);if(t.x>=0&&t.y>=0&&t.x<=r.width&&t.y<=r.height)break;e.lng>r.center.lng?e.lng-=360:e.lng+=360;}return e.lng!==o.lng&&r.isPointOnMapSurface(r.locationToScreenPoint(e))?e:o}const us={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 ds(e,t,i){const r=e.classList;for(const e in us)r.remove(`maplibregl-${i}-anchor-${e}`);r.add(`maplibregl-${i}-anchor-${t}`);}class _s extends t.Evented{constructor(e){if(super(),this._onKeyPress=e=>{const t=e.code,i=e.charCode||e.keyCode;"Space"!==t&&"Enter"!==t&&32!==i&&13!==i||this.togglePopup();},this._onMapClick=e=>{const t=e.originalEvent.target,i=this._element;this._popup&&(t===i||i.contains(t))&&this.togglePopup();},this._update=e=>{var t;if(!this._map)return;const i=this._map.loaded()&&!this._map.isMoving();("terrain"===(null==e?void 0:e.type)||"render"===(null==e?void 0:e.type)&&!i)&&this._map.once("render",this._update),this._lngLat=this._map.transform.renderWorldCopies?hs(this._lngLat,this._flatPos,this._map.transform):null===(t=this._lngLat)||void 0===t?void 0:t.wrap(),this._flatPos=this._pos=this._map.project(this._lngLat)._add(this._offset),this._map.terrain&&(this._flatPos=this._map.transform.locationToScreenPoint(this._lngLat)._add(this._offset));let r="";"viewport"===this._rotationAlignment||"auto"===this._rotationAlignment?r=`rotateZ(${this._rotation}deg)`:"map"===this._rotationAlignment&&(r=`rotateZ(${this._rotation-this._map.getBearing()}deg)`);let o="";"viewport"===this._pitchAlignment||"auto"===this._pitchAlignment?o="rotateX(0deg)":"map"===this._pitchAlignment&&(o=`rotateX(${this._map.getPitch()}deg)`),this._subpixelPositioning||e&&"moveend"!==e.type||(this._pos=this._pos.round()),wi.setTransform(this._element,`${us[this._anchor]} translate(${this._pos.x}px, ${this._pos.y}px) ${o} ${r}`),f.frameAsync(new AbortController).then((()=>{this._updateOpacity(e&&"moveend"===e.type);})).catch((()=>{}));},this._onMove=e=>{if(!this._isDragging){const t=this._clickTolerance||this._map._clickTolerance;this._isDragging=e.point.dist(this._pointerdownPos)>=t;}this._isDragging&&(this._pos=e.point.sub(this._positionDelta),this._lngLat=this._map.unproject(this._pos),this.setLngLat(this._lngLat),this._element.style.pointerEvents="none","pending"===this._state&&(this._state="active",this.fire(new t.Event("dragstart"))),this.fire(new t.Event("drag")));},this._onUp=()=>{this._element.style.pointerEvents="auto",this._positionDelta=null,this._pointerdownPos=null,this._isDragging=!1,this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),"active"===this._state&&this.fire(new t.Event("dragend")),this._state="inactive";},this._addDragHandler=e=>{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=e&&e.anchor||"center",this._color=e&&e.color||"#3FB1CE",this._scale=e&&e.scale||1,this._draggable=e&&e.draggable||!1,this._clickTolerance=e&&e.clickTolerance||0,this._subpixelPositioning=e&&e.subpixelPositioning||!1,this._isDragging=!1,this._state="inactive",this._rotation=e&&e.rotation||0,this._rotationAlignment=e&&e.rotationAlignment||"auto",this._pitchAlignment=e&&e.pitchAlignment&&"auto"!==e.pitchAlignment?e.pitchAlignment:this._rotationAlignment,this.setOpacity(),this.setOpacity(null==e?void 0:e.opacity,null==e?void 0:e.opacityWhenCovered),e&&e.element)this._element=e.element,this._offset=t.Point.convert(e&&e.offset||[0,0]);else {this._defaultMarker=!0,this._element=wi.create("div");const i=wi.createNS("http://www.w3.org/2000/svg","svg"),r=41,o=27;i.setAttributeNS(null,"display","block"),i.setAttributeNS(null,"height",`${r}px`),i.setAttributeNS(null,"width",`${o}px`),i.setAttributeNS(null,"viewBox",`0 0 ${o} ${r}`);const a=wi.createNS("http://www.w3.org/2000/svg","g");a.setAttributeNS(null,"stroke","none"),a.setAttributeNS(null,"stroke-width","1"),a.setAttributeNS(null,"fill","none"),a.setAttributeNS(null,"fill-rule","evenodd");const s=wi.createNS("http://www.w3.org/2000/svg","g");s.setAttributeNS(null,"fill-rule","nonzero");const n=wi.createNS("http://www.w3.org/2000/svg","g");n.setAttributeNS(null,"transform","translate(3.0, 29.0)"),n.setAttributeNS(null,"fill","#000000");const l=[{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 e of l){const t=wi.createNS("http://www.w3.org/2000/svg","ellipse");t.setAttributeNS(null,"opacity","0.04"),t.setAttributeNS(null,"cx","10.5"),t.setAttributeNS(null,"cy","5.80029008"),t.setAttributeNS(null,"rx",e.rx),t.setAttributeNS(null,"ry",e.ry),n.appendChild(t);}const c=wi.createNS("http://www.w3.org/2000/svg","g");c.setAttributeNS(null,"fill",this._color);const h=wi.createNS("http://www.w3.org/2000/svg","path");h.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"),c.appendChild(h);const u=wi.createNS("http://www.w3.org/2000/svg","g");u.setAttributeNS(null,"opacity","0.25"),u.setAttributeNS(null,"fill","#000000");const d=wi.createNS("http://www.w3.org/2000/svg","path");d.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"),u.appendChild(d);const _=wi.createNS("http://www.w3.org/2000/svg","g");_.setAttributeNS(null,"transform","translate(6.0, 7.0)"),_.setAttributeNS(null,"fill","#FFFFFF");const p=wi.createNS("http://www.w3.org/2000/svg","g");p.setAttributeNS(null,"transform","translate(8.0, 8.0)");const m=wi.createNS("http://www.w3.org/2000/svg","circle");m.setAttributeNS(null,"fill","#000000"),m.setAttributeNS(null,"opacity","0.25"),m.setAttributeNS(null,"cx","5.5"),m.setAttributeNS(null,"cy","5.5"),m.setAttributeNS(null,"r","5.4999962");const f=wi.createNS("http://www.w3.org/2000/svg","circle");f.setAttributeNS(null,"fill","#FFFFFF"),f.setAttributeNS(null,"cx","5.5"),f.setAttributeNS(null,"cy","5.5"),f.setAttributeNS(null,"r","5.4999962"),p.appendChild(m),p.appendChild(f),s.appendChild(n),s.appendChild(c),s.appendChild(u),s.appendChild(_),s.appendChild(p),i.appendChild(s),i.setAttributeNS(null,"height",r*this._scale+"px"),i.setAttributeNS(null,"width",o*this._scale+"px"),this._element.appendChild(i),this._offset=t.Point.convert(e&&e.offset||[0,-14]);}if(this._element.classList.add("maplibregl-marker"),this._element.addEventListener("dragstart",(e=>{e.preventDefault();})),this._element.addEventListener("mousedown",(e=>{e.preventDefault();})),ds(this._element,this._anchor,"marker"),e&&e.className)for(const t of e.className.split(" "))this._element.classList.add(t);this._popup=null;}addTo(e){return this.remove(),this._map=e,this._element.setAttribute("aria-label",e._getUIString("Marker.Title")),e.getCanvasContainer().appendChild(this._element),e.on("move",this._update),e.on("moveend",this._update),e.on("terrain",this._update),e.on("projectiontransition",this._update),this.setDraggable(this._draggable),this._update(),this._map.on("click",this._onMapClick),this}remove(){return this._opacityTimeout&&(clearTimeout(this._opacityTimeout),delete this._opacityTimeout),this._map&&(this._map.off("click",this._onMapClick),this._map.off("move",this._update),this._map.off("moveend",this._update),this._map.off("terrain",this._update),this._map.off("projectiontransition",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),wi.remove(this._element),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(e){return this._lngLat=t.LngLat.convert(e),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(),this}getElement(){return this._element}setPopup(e){if(this._popup&&(this._popup.remove(),this._popup=null,this._element.removeEventListener("keypress",this._onKeyPress),this._originalTabIndex||this._element.removeAttribute("tabindex")),e){if(!("offset"in e.options)){const t=38.1,i=13.5,r=Math.abs(i)/Math.SQRT2;e.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-t],"bottom-left":[r,-1*(t-i+r)],"bottom-right":[-r,-1*(t-i+r)],left:[i,-1*(t-i)],right:[-i,-1*(t-i)]}:this._offset;}this._popup=e,this._originalTabIndex=this._element.getAttribute("tabindex"),this._originalTabIndex||this._element.setAttribute("tabindex","0"),this._element.addEventListener("keypress",this._onKeyPress);}return this}setSubpixelPositioning(e){return this._subpixelPositioning=e,this}getPopup(){return this._popup}togglePopup(){const e=this._popup;return this._element.style.opacity===this._opacityWhenCovered?this:e?(e.isOpen()?e.remove():(e.setLngLat(this._lngLat),e.addTo(this._map)),this):this}_updateOpacity(e=!1){var i,r;if(!(null===(i=this._map)||void 0===i?void 0:i.terrain)){const e=this._map.transform.isLocationOccluded(this._lngLat)?this._opacityWhenCovered:this._opacity;return void(this._element.style.opacity!==e&&(this._element.style.opacity=e))}if(e)this._opacityTimeout=null;else {if(this._opacityTimeout)return;this._opacityTimeout=setTimeout((()=>{this._opacityTimeout=null;}),100);}const o=this._map,a=o.terrain.depthAtPoint(this._pos),s=o.terrain.getElevationForLngLatZoom(this._lngLat,o.transform.tileZoom);if(o.transform.lngLatToCameraDepth(this._lngLat,s)-a<.006)return void(this._element.style.opacity=this._opacity);const n=-this._offset.y/o.transform.pixelsPerMeter,l=Math.sin(o.getPitch()*Math.PI/180)*n,c=o.terrain.depthAtPoint(new t.Point(this._pos.x,this._pos.y-this._offset.y)),h=o.transform.lngLatToCameraDepth(this._lngLat,s+l)-c>.006;(null===(r=this._popup)||void 0===r?void 0:r.isOpen())&&h&&this._popup.remove(),this._element.style.opacity=h?this._opacityWhenCovered:this._opacity;}getOffset(){return this._offset}setOffset(e){return this._offset=t.Point.convert(e),this._update(),this}addClassName(e){this._element.classList.add(e);}removeClassName(e){this._element.classList.remove(e);}toggleClassName(e){return this._element.classList.toggle(e)}setDraggable(e){return this._draggable=!!e,this._map&&(e?(this._map.on("mousedown",this._addDragHandler),this._map.on("touchstart",this._addDragHandler)):(this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler))),this}isDraggable(){return this._draggable}setRotation(e){return this._rotation=e||0,this._update(),this}getRotation(){return this._rotation}setRotationAlignment(e){return this._rotationAlignment=e||"auto",this._update(),this}getRotationAlignment(){return this._rotationAlignment}setPitchAlignment(e){return this._pitchAlignment=e&&"auto"!==e?e:this._rotationAlignment,this._update(),this}getPitchAlignment(){return this._pitchAlignment}setOpacity(e,t){return void 0===e&&void 0===t&&(this._opacity="1",this._opacityWhenCovered="0.2"),void 0!==e&&(this._opacity=e),void 0!==t&&(this._opacityWhenCovered=t),this._map&&this._updateOpacity(!0),this}}const ps={positionOptions:{enableHighAccuracy:!1,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showAccuracyCircle:!0,showUserLocation:!0};let ms=0,fs=!1;const gs={maxWidth:100,unit:"metric"};function vs(e,t,i){const r=i&&i.maxWidth||100,o=e._container.clientHeight/2,a=e._container.clientWidth/2,s=e.unproject([a-r/2,o]),n=e.unproject([a+r/2,o]),l=Math.round(e.project(n).x-e.project(s).x),c=Math.min(r,l,e._container.clientWidth),h=s.distanceTo(n);if(i&&"imperial"===i.unit){const i=3.2808*h;i>5280?ys(t,c,i/5280,e._getUIString("ScaleControl.Miles")):ys(t,c,i,e._getUIString("ScaleControl.Feet"));}else i&&"nautical"===i.unit?ys(t,c,h/1852,e._getUIString("ScaleControl.NauticalMiles")):h>=1e3?ys(t,c,h/1e3,e._getUIString("ScaleControl.Kilometers")):ys(t,c,h,e._getUIString("ScaleControl.Meters"));}function ys(e,t,i,r){const o=function(e){const t=Math.pow(10,`${Math.floor(e)}`.length-1);let i=e/t;return i=i>=10?10:i>=5?5:i>=3?3:i>=2?2:i>=1?1:function(e){const t=Math.pow(10,Math.ceil(-Math.log(e)/Math.LN10));return Math.round(e*t)/t}(i),t*i}(i);e.style.width=t*(o/i)+"px",e.innerHTML=`${o} ${r}`;}const xs={closeButton:!0,closeOnClick:!0,focusAfterOpen:!0,className:"",maxWidth:"240px",subpixelPositioning:!1},bs=["a[href]","[tabindex]:not([tabindex='-1'])","[contenteditable]:not([contenteditable='false'])","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])"].join(", ");function ws(e){if(e){if("number"==typeof e){const i=Math.round(Math.abs(e)/Math.SQRT2);return {center:new t.Point(0,0),top:new t.Point(0,e),"top-left":new t.Point(i,i),"top-right":new t.Point(-i,i),bottom:new t.Point(0,-e),"bottom-left":new t.Point(i,-i),"bottom-right":new t.Point(-i,-i),left:new t.Point(e,0),right:new t.Point(-e,0)}}if(e instanceof t.Point||Array.isArray(e)){const i=t.Point.convert(e);return {center:i,top:i,"top-left":i,"top-right":i,bottom:i,"bottom-left":i,"bottom-right":i,left:i,right:i}}return {center:t.Point.convert(e.center||[0,0]),top:t.Point.convert(e.top||[0,0]),"top-left":t.Point.convert(e["top-left"]||[0,0]),"top-right":t.Point.convert(e["top-right"]||[0,0]),bottom:t.Point.convert(e.bottom||[0,0]),"bottom-left":t.Point.convert(e["bottom-left"]||[0,0]),"bottom-right":t.Point.convert(e["bottom-right"]||[0,0]),left:t.Point.convert(e.left||[0,0]),right:t.Point.convert(e.right||[0,0])}}return ws(new t.Point(0,0))}const Ts=Ti,Es=r(o),Ps=window.benchmarks=[];function Is(e,t,i,r){const o=[];for(const e of ["https://api.maptiler.com/maps/streets/style.json?key=get_your_own_OpIi9ZULNHzrESv6T2vL"])o.push({name:"string"==typeof e?e:e.name,bench:new t(e,i)});Ps.push({name:e,versions:o,location:r});}Is("StyleLayerCreate",Ya),Is("Validate",Ka),Es.forEach((e=>Is("Layout",bi,e.tileID,e))),Es.forEach((e=>Is("Paint",Za,[e],e))),Is("QueryPoint",Qa,Es),Is("QueryBox",es,Es),Promise.resolve().then((()=>{B().acquire(-1);}));class Cs extends a{constructor(e){super(),this._pitch=e;}bench(){const e=new Jt,i=new _i(e,!0);i.setCenter(new t.LngLat(0,0)),i.setZoom(4),i.resize(4096,4096),i.setMaxPitch(this._pitch),i.setPitch(this._pitch);for(let e=0;e<40;e++)i.setCenter(new t.LngLat(.2*e,0)),ve(i,{tileSize:256});}}const Ms=r(o).filter((e=>e.zoom<15));function Ss(e,t){window.maplibreglBenchmarks[e]=window.maplibreglBenchmarks[e]||{},window.maplibreglBenchmarks[e]["main 6e4498c"]=t;}window.maplibreglBenchmarks=window.maplibreglBenchmarks||{};const Rs="https://api.maptiler.com/maps/streets/style.json?key=get_your_own_OpIi9ZULNHzrESv6T2vL",Ds=[-77.032194,38.912753],zs=[4,8,11,13,15,17].map((e=>({center:Ds,zoom:e})));Ss("Paint",new Za(Rs,zs)),Ss("QueryPoint",new Qa(Rs,zs)),Ss("QueryBox",new es(Rs,zs)),Ss("Layout",new bi(Rs)),Ss("Placement",new class extends a{constructor(e,t){super(),this.style=e,this.locations=t;}setup(){return t.__awaiter(this,void 0,void 0,(function*(){try{this.maps=yield Promise.all(this.locations.map((e=>Na({zoom:e.zoom,width:1024,height:768,center:e.center,style:this.style,idle:!0}))));}catch(e){console.error(e);}}))}bench(){for(const e of this.maps)e.style._updatePlacement(e.transform,!1,300,!0,!0);}teardown(){for(const e of this.maps)e.remove();}}(Rs,zs)),Ss("Validate",new Ka(Rs)),Ss("StyleLayerCreate",new Ya(Rs)),Ss("FunctionCreate",new class extends ts{bench(){for(const{rawValue:e,propertySpec:i}of this.data)t.createFunction(e,i);}}(Rs)),Ss("FunctionEvaluate",new class extends ts{bench(){for(const{compiledFunction:e}of this.data)e.evaluate({zoom:0});}}(Rs)),Ss("ExpressionCreate",new class extends ts{bench(){for(const{rawExpression:e,propertySpec:i}of this.data)t.createPropertyExpression(e,i);}}(Rs)),Ss("ExpressionEvaluate",new class extends ts{bench(){for(const{compiledExpression:e}of this.data)e.evaluate({zoom:0});}}(Rs)),Ss("WorkerTransfer",new class extends a{constructor(e){super(),this.style=e;}setup(){return t.__awaiter(this,void 0,void 0,(function*(){const e=window.URL.createObjectURL(new Blob(["\n onmessage = (e) => {\n postMessage(e.data);\n };\n "],{type:"text/javascript"}));this.worker=new Worker(e);const i=[new t.OverscaledTileID(8,0,8,73,97),new t.OverscaledTileID(11,0,11,585,783),new t.OverscaledTileID(11,0,11,596,775),new t.OverscaledTileID(13,0,13,2412,3079)],r=yield s(this.style);this.parser=new xi(r,"openmaptiles"),yield this.parser.setup();const o=yield Promise.all(i.map((e=>this.parser.fetchTile(e)))),a=yield Promise.all(o.map((e=>this.parser.parseTile(e)))),n=a.concat(Object.values(this.parser.icons)).concat(Object.values(this.parser.glyphs)).map((e=>t.serialize(e,[])));this.payloadJSON=n.map(Ga),this.payloadTiles=n.slice(0,a.length);}))}sendPayload(e){return new Promise((t=>{this.worker.onmessage=()=>t(),this.worker.postMessage(e);}))}bench(){return t.__awaiter(this,void 0,void 0,(function*(){for(const e of this.payloadJSON)yield this.sendPayload(e);for(const e of this.payloadTiles)t.deserialize(e);}))}teardown(){this.worker.terminate();}}(Rs)),Ss("PaintStates",new class extends a{constructor(e){super(),this.center=e;}setup(){return t.__awaiter(this,void 0,void 0,(function*(){const e=yield fetch("/test/bench/data/naturalearth-land.json"),t=yield e.json();this.numFeatures=t.features.length;const i=Object.assign({},Va,{sources:{land:{type:"geojson",data:t,maxzoom:23}},layers:qa({id:"layer",type:"fill",source:"land",paint:{"fill-color":["case",["boolean",["feature-state","bench"],!1],["rgb",21,210,210],["rgb",233,233,233]]}})});try{this.map=yield Na({zoom:4,width:1024,height:768,center:this.center,style:i});}catch(e){console.error(e);}}))}bench(){this.map._styleDirty=!0,this.map._sourcesDirty=!0,this.map._render();for(let e=0;esuper.setup}});return t.__awaiter(this,void 0,void 0,(function*(){const t=yield fetch("/test/bench/data/naturalearth-land.json"),i=yield t.json();this.layerStyle=Object.assign({},Va,{sources:{heatmap:{type:"geojson",data:i,maxzoom:23}},layers:$a({id:"layer",type:"heatmap",source:"heatmap",paint:{"heatmap-radius":50,"heatmap-weight":{stops:[[0,.5],[4,2]]},"heatmap-intensity":.9,"heatmap-color":["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"]}})}),yield e.setup.call(this);}))}}),Ss("LayerHillshade",new class extends Ha{constructor(){super(),this.layerStyle=Object.assign({},Va,{sources:{"terrain-rgb":{type:"raster-dem",url:"https://api.maptiler.com/tiles/terrain-rgb/tiles.json?key=get_your_own_OpIi9ZULNHzrESv6T2vL"}},layers:$a({id:"layer",type:"hillshade",source:"terrain-rgb"})});}}),Ss("LayerLine",new class extends Ha{constructor(){super(),this.layerStyle=Object.assign({},Va,{layers:$a({id:"linelayer",type:"line",source:"openmaptiles","source-layer":"transportation"})});}}),Ss("LayerRaster",new class extends Ha{constructor(){super(),this.layerStyle=Object.assign({},Va,{sources:{satellite:{url:"https://api.maptiler.com/tiles/satellite/tiles.json?key=get_your_own_OpIi9ZULNHzrESv6T2vL",type:"raster",tileSize:256}},layers:$a({id:"rasterlayer",type:"raster",source:"satellite"})});}}),Ss("LayerSymbol",new class extends Ha{constructor(){super(),this.layerStyle=Object.assign({},Va,{layers:$a({id:"symbollayer",type:"symbol",source:"openmaptiles","source-layer":"poi",layout:{"icon-image":"dot_11","text-field":"{name_en}"}})});}}),Ss("LayerSymbolWithIcons",new class extends Ha{constructor(){super(),this.layerStyle=Object.assign({},Va,{layers:$a({id:"symbollayer",type:"symbol",source:"openmaptiles","source-layer":"poi",layout:{"icon-image":"dot_11","text-field":["format",["get","name_en"],["image","dot_11"]]}})});}}),Ss("LayerTextWithVariableAnchor",new class extends Ha{constructor(){super(),this.layerStyle=Object.assign({},Va,{layers:$a({id:"symbollayer",type:"symbol",source:"openmaptiles","source-layer":"poi",layout:{"text-field":"Test Test Test","text-justify":"auto","text-variable-anchor":["center","top","bottom","left","right","top-left","top-right","bottom-left","bottom-right"]}})});}}),Ss("LayerSymbolWithSortKey",new class extends Ha{constructor(){super(),this.layerStyle=Object.assign({},Va,{layers:this.generateSortKeyLayers()});}generateSortKeyLayers(){const e=[];for(let t=0;t<50;t++)e.push({id:`symbollayer${t}`,type:"symbol",source:"openmaptiles","source-layer":"poi",layout:{"symbol-sort-key":t,"text-field":"{name_en}"}});return e}}),Ss("Load",new class extends a{bench(){return t.__awaiter(this,void 0,void 0,(function*(){try{(yield Na({style:{version:8,sources:{},layers:[]}})).remove();}catch(e){console.error(e);}}))}}),Ss("LoadMatchingFeature",new class extends a{setup(){const e=Object.create(null,{setup:{get:()=>super.setup}});return t.__awaiter(this,void 0,void 0,(function*(){yield e.setup.call(this);const i=new t.OverscaledTileID(0,0,0,0,0);this.featureIndex=new t.FeatureIndex(i);const r=Array.from({length:100},((e,t)=>`layer-${t}`));this.layerIdsToTest=new Set(Array.from({length:100},((e,t)=>`non-existing-layer-${t}`))),this.featureIndex.bucketLayerIDs=[r],this.featureIndex.vtLayers={},this.featureIndex.vtLayers[0]={feature:()=>({})};}))}bench(){this.featureIndex.loadMatchingFeature({},0,0,0,{needGeometry:!1},this.layerIdsToTest,[],{},{});}}),Ss("SymbolLayout",new class extends bi{constructor(e,t){super(e,t),this.parsedTiles=[];}setup(){const e=Object.create(null,{setup:{get:()=>super.setup}});return t.__awaiter(this,void 0,void 0,(function*(){yield e.setup.call(this);for(const e of this.tiles)this.parsedTiles.push(yield this.parser.parseTile(e,!0));}))}bench(){return t.__awaiter(this,void 0,void 0,(function*(){for(const e of this.parsedTiles)for(const i of e.buckets)i instanceof t.SymbolBucket&&(yield t.performSymbolLayout({bucket:i,glyphMap:e.glyphMap,glyphPositions:e.glyphPositions,imageMap:e.iconMap,imagePositions:e.imageAtlas.iconPositions,showCollisionBoxes:!1,canonical:e.featureIndex.tileID.canonical,subdivisionGranularity:t.SubdivisionGranularitySetting.noSubdivision}));}))}}(Rs,Ms.map((e=>e.tileID[0])))),Ss("FilterCreate",new class extends a{bench(){for(const e of is)t.featureFilter(e.filter);}}),Ss("FilterEvaluate",new class extends a{setup(){return t.__awaiter(this,void 0,void 0,(function*(){const e=yield fetch("/test/bench/data/785.vector.pbf"),i=yield e.arrayBuffer(),r=new t.vectorTileExports.VectorTile(new t.Protobuf(i));this.layers=[];for(const e in r.layers){const i=r.layers[e];if(!i.length)continue;const o=[];for(let e=0;e{Na({width:1024,height:1024,style:{version:8,sources:{},layers:[]},center:[-9.4,-26.8],pitch:60,bearing:131,zoom:1.69}).then((t=>{this.map=t,e();})).catch((e=>{console.error(e),t(e);}));}))}bench(){const e=new rs;this.map.addLayer(e),this.map._styleDirty=!0,this.map._sourcesDirty=!0,this.map._render(Date.now());}teardown(){this.map.remove();}}),Ss("MapIdle",new class extends a{constructor(){super(),this.minimumMeasurements=55;}createMap(){return t.__awaiter(this,void 0,void 0,(function*(){try{(yield Na({idle:!0,center:[-77.032194,38.912753],zoom:15})).remove();}catch(e){console.error(e);}}))}setup(){return this.createMap()}bench(){return this.createMap()}}),Ss("SymbolCollisionBox",new os(!1)),Ss("SymbolCollisionBoxGlobe",new os(!0)),Ss("Subdivide",new class extends a{setup(){const e=Object.create(null,{setup:{get:()=>super.setup}});return t.__awaiter(this,void 0,void 0,(function*(){yield e.setup.call(this),this.granularity=64,this.tileID=new t.CanonicalTileID(2,1,1);const i=[];function r(e,r,o,a){i.push(as(e*t.EXTENT,r*t.EXTENT,o*t.EXTENT,a));}i.push(as(t.EXTENT/2,t.EXTENT/2,1.1*t.EXTENT/2,891)),r(.25,.5,.15,176),r(.75,.5,.15,22),r(.5,.1,.05,44),this.polygon=i;}))}bench(){for(let e=0;e<10;e++)t.subdividePolygon(this.polygon,this.tileID,this.granularity,!0);}}),Ss("CoveringTilesGlobe",new Cs(0)),Ss("CoveringTilesGlobePitched",new Cs(60)),Promise.resolve().then((()=>{B().acquire(-1);})),e.AJAXError=t.AJAXError,e.Event=t.Event,e.Evented=t.Evented,e.LngLat=t.LngLat,e.MercatorCoordinate=t.MercatorCoordinate,e.Point=t.Point,e.addProtocol=t.addProtocol,e.config=t.config,e.removeProtocol=t.removeProtocol,e.AttributionControl=Ma,e.BoxZoomHandler=Zo,e.CanvasSource=J,e.CooperativeGesturesHandler=ba,e.DoubleClickZoomHandler=ma,e.DragPanHandler=va,e.DragRotateHandler=ya,e.EdgeInsets=le,e.FullscreenControl=class extends t.Evented{constructor(e={}){super(),this._onFullscreenChange=()=>{var e;let t=window.document.fullscreenElement||window.document.mozFullScreenElement||window.document.webkitFullscreenElement||window.document.msFullscreenElement;for(;null===(e=null==t?void 0:t.shadowRoot)||void 0===e?void 0:e.fullscreenElement;)t=t.shadowRoot.fullscreenElement;t===this._container!==this._fullscreen&&this._handleFullscreenChange();},this._onClickFullscreen=()=>{this._isFullscreen()?this._exitFullscreen():this._requestFullscreen();},this._fullscreen=!1,e&&e.container&&(e.container instanceof HTMLElement?this._container=e.container:t.warnOnce("Full screen control 'container' must be a DOM element.")),"onfullscreenchange"in document?this._fullscreenchange="fullscreenchange":"onmozfullscreenchange"in document?this._fullscreenchange="mozfullscreenchange":"onwebkitfullscreenchange"in document?this._fullscreenchange="webkitfullscreenchange":"onmsfullscreenchange"in document&&(this._fullscreenchange="MSFullscreenChange");}onAdd(e){return this._map=e,this._container||(this._container=this._map.getContainer()),this._controlContainer=wi.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),this._controlContainer}onRemove(){wi.remove(this._controlContainer),this._map=null,window.document.removeEventListener(this._fullscreenchange,this._onFullscreenChange);}_setupUI(){const e=this._fullscreenButton=wi.create("button","maplibregl-ctrl-fullscreen",this._controlContainer);wi.create("span","maplibregl-ctrl-icon",e).setAttribute("aria-hidden","true"),e.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),window.document.addEventListener(this._fullscreenchange,this._onFullscreenChange);}_updateTitle(){const e=this._getTitle();this._fullscreenButton.setAttribute("aria-label",e),this._fullscreenButton.title=e;}_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(),this._fullscreen?(this.fire(new t.Event("fullscreenstart")),this._prevCooperativeGesturesEnabled=this._map.cooperativeGestures.isEnabled(),this._map.cooperativeGestures.disable()):(this.fire(new t.Event("fullscreenend")),this._prevCooperativeGesturesEnabled&&this._map.cooperativeGestures.enable());}_exitFullscreen(){window.document.exitFullscreen?window.document.exitFullscreen():window.document.mozCancelFullScreen?window.document.mozCancelFullScreen():window.document.msExitFullscreen?window.document.msExitFullscreen():window.document.webkitCancelFullScreen?window.document.webkitCancelFullScreen():this._togglePseudoFullScreen();}_requestFullscreen(){this._container.requestFullscreen?this._container.requestFullscreen():this._container.mozRequestFullScreen?this._container.mozRequestFullScreen():this._container.msRequestFullscreen?this._container.msRequestFullscreen():this._container.webkitRequestFullscreen?this._container.webkitRequestFullscreen():this._togglePseudoFullScreen();}_togglePseudoFullScreen(){this._container.classList.toggle("maplibregl-pseudo-fullscreen"),this._handleFullscreenChange(),this._map.resize();}},e.GeoJSONSource=H,e.GeolocateControl=class extends t.Evented{constructor(e){super(),this._onSuccess=e=>{if(this._map){if(this._isOutOfMapMaxBounds(e))return this._setErrorState(),this.fire(new t.Event("outofmaxbounds",e)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=e,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}`)}this.options.showUserLocation&&"OFF"!==this._watchState&&this._updateMarker(e),this.options.trackUserLocation&&"ACTIVE_LOCK"!==this._watchState||this._updateCamera(e),this.options.showUserLocation&&this._dotElement.classList.remove("maplibregl-user-location-dot-stale"),this.fire(new t.Event("geolocate",e)),this._finish();}},this._updateCamera=e=>{const i=new t.LngLat(e.coords.longitude,e.coords.latitude),r=e.coords.accuracy,o=this._map.getBearing(),a=t.extend({bearing:o},this.options.fitBoundsOptions),s=V.fromLngLat(i,r);this._map.fitBounds(s,a,{geolocateSource:!0});},this._updateMarker=e=>{if(e){const i=new t.LngLat(e.coords.longitude,e.coords.latitude);this._accuracyCircleMarker.setLngLat(i).addTo(this._map),this._userLocationDotMarker.setLngLat(i).addTo(this._map),this._accuracy=e.coords.accuracy,this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius();}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove();},this._onZoom=()=>{this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius();},this._onError=e=>{if(this._map){if(this.options.trackUserLocation)if(1===e.code){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=!0;const e=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e),void 0!==this._geolocationWatchID&&this._clearWatch();}else {if(3===e.code&&fs)return;this._setErrorState();}"OFF"!==this._watchState&&this.options.showUserLocation&&this._dotElement.classList.add("maplibregl-user-location-dot-stale"),this.fire(new t.Event("error",e)),this._finish();}},this._finish=()=>{this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0;},this._setupUI=()=>{this._map&&(this._container.addEventListener("contextmenu",(e=>e.preventDefault())),this._geolocateButton=wi.create("button","maplibregl-ctrl-geolocate",this._container),wi.create("span","maplibregl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",this._geolocateButton.disabled=!0);},this._finishSetupUI=e=>{if(this._map){if(!1===e){t.warnOnce("Geolocation support is not available so the GeolocateControl will be disabled.");const e=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=!0,this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e);}else {const e=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.disabled=!1,this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e);}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=wi.create("div","maplibregl-user-location-dot"),this._userLocationDotMarker=new _s({element:this._dotElement}),this._circleElement=wi.create("div","maplibregl-user-location-accuracy-circle"),this._accuracyCircleMarker=new _s({element:this._circleElement,pitchAlignment:"map"}),this.options.trackUserLocation&&(this._watchState="OFF"),this._map.on("zoom",this._onZoom)),this._geolocateButton.addEventListener("click",(()=>this.trigger())),this._setup=!0,this.options.trackUserLocation&&this._map.on("movestart",(e=>{e.geolocateSource||"ACTIVE_LOCK"!==this._watchState||e.originalEvent&&"resize"===e.originalEvent.type||(this._watchState="BACKGROUND",this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this.fire(new t.Event("trackuserlocationend")),this.fire(new t.Event("userlocationlostfocus")));}));}},this.options=t.extend({},ps,e);}onAdd(e){return this._map=e,this._container=wi.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),function(){return t.__awaiter(this,arguments,void 0,(function*(e=!1){if(void 0!==cs&&!e)return cs;if(void 0===window.navigator.permissions)return cs=!!window.navigator.geolocation,cs;try{const e=yield window.navigator.permissions.query({name:"geolocation"});cs="denied"!==e.state;}catch(e){cs=!!window.navigator.geolocation;}return cs}))}().then((e=>this._finishSetupUI(e))),this._container}onRemove(){void 0!==this._geolocationWatchID&&(window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),wi.remove(this._container),this._map.off("zoom",this._onZoom),this._map=void 0,ms=0,fs=!1;}_isOutOfMapMaxBounds(e){const t=this._map.getMaxBounds(),i=e.coords;return t&&(i.longitudet.getEast()||i.latitudet.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 e=this._map.getBounds(),t=e.getSouthEast(),i=e.getNorthEast(),r=t.distanceTo(i),o=Math.ceil(this._accuracy/(r/this._map._container.clientHeight)*2);this._circleElement.style.width=`${o}px`,this._circleElement.style.height=`${o}px`;}trigger(){if(!this._setup)return t.warnOnce("Geolocate control triggered before added to a map"),!1;if(this.options.trackUserLocation){switch(this._watchState){case"OFF":this._watchState="WAITING_ACTIVE",this.fire(new t.Event("trackuserlocationstart"));break;case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":case"BACKGROUND_ERROR":ms--,fs=!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.fire(new t.Event("trackuserlocationend"));break;case"BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new t.Event("trackuserlocationstart")),this.fire(new t.Event("userlocationfocus"));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("OFF"===this._watchState&&void 0!==this._geolocationWatchID)this._clearWatch();else if(void 0===this._geolocationWatchID){let e;this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),ms++,ms>1?(e={maximumAge:6e5,timeout:0},fs=!0):(e=this.options.positionOptions,fs=!1),this._geolocationWatchID=window.navigator.geolocation.watchPosition(this._onSuccess,this._onError,e);}}else window.navigator.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._timeoutId=setTimeout(this._finish,1e4);return !0}_clearWatch(){window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null);}},e.GlobeControl=class{constructor(){this._toggleProjection=()=>{var e;const t=null===(e=this._map.getProjection())||void 0===e?void 0:e.type;this._map.setProjection("mercator"!==t&&t?{type:"mercator"}:{type:"globe"}),this._updateGlobeIcon();},this._updateGlobeIcon=()=>{var e;this._globeButton.classList.remove("maplibregl-ctrl-globe"),this._globeButton.classList.remove("maplibregl-ctrl-globe-enabled"),"globe"===(null===(e=this._map.getProjection())||void 0===e?void 0:e.type)?(this._globeButton.classList.add("maplibregl-ctrl-globe-enabled"),this._globeButton.title=this._map._getUIString("GlobeControl.Disable")):(this._globeButton.classList.add("maplibregl-ctrl-globe"),this._globeButton.title=this._map._getUIString("GlobeControl.Enable"));};}onAdd(e){return this._map=e,this._container=wi.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._globeButton=wi.create("button","maplibregl-ctrl-globe",this._container),wi.create("span","maplibregl-ctrl-icon",this._globeButton).setAttribute("aria-hidden","true"),this._globeButton.type="button",this._globeButton.addEventListener("click",this._toggleProjection),this._updateGlobeIcon(),this._map.on("styledata",this._updateGlobeIcon),this._container}onRemove(){wi.remove(this._container),this._map.off("styledata",this._updateGlobeIcon),this._globeButton.removeEventListener("click",this._toggleProjection),this._map=void 0;}},e.Hash=Co,e.ImageSource=K,e.KeyboardHandler=ua,e.LngLatBounds=V,e.LogoControl=Sa,e.Map=ja,e.MapMouseEvent=Bo,e.MapTouchEvent=Oo,e.MapWheelEvent=Uo,e.Marker=_s,e.NavigationControl=class{constructor(e){this._updateZoomButtons=()=>{const e=this._map.getZoom(),t=e===this._map.getMaxZoom(),i=e===this._map.getMinZoom();this._zoomInButton.disabled=t,this._zoomOutButton.disabled=i,this._zoomInButton.setAttribute("aria-disabled",t.toString()),this._zoomOutButton.setAttribute("aria-disabled",i.toString());},this._rotateCompassArrow=()=>{this._compassIcon.style.transform=this.options.visualizePitch&&this.options.visualizeRoll?`scale(${1/Math.pow(Math.cos(this._map.transform.pitchInRadians),.5)}) rotateZ(${-this._map.transform.roll}deg) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(this._map.transform.pitchInRadians),.5)}) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizeRoll?`rotate(${-this._map.transform.bearing-this._map.transform.roll}deg)`:`rotate(${-this._map.transform.bearing}deg)`;},this._setButtonTitle=(e,t)=>{const i=this._map._getUIString(`NavigationControl.${t}`);e.title=i,e.setAttribute("aria-label",i);},this.options=t.extend({},ns,e),this._container=wi.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._container.addEventListener("contextmenu",(e=>e.preventDefault())),this.options.showZoom&&(this._zoomInButton=this._createButton("maplibregl-ctrl-zoom-in",(e=>this._map.zoomIn({},{originalEvent:e}))),wi.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}))),wi.create("span","maplibregl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(this._compass=this._createButton("maplibregl-ctrl-compass",(e=>{this.options.visualizePitch?this._map.resetNorthPitch({},{originalEvent:e}):this._map.resetNorth({},{originalEvent:e});})),this._compassIcon=wi.create("span","maplibregl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"));}onAdd(e){return this._map=e,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),this._map.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&this._map.on("pitch",this._rotateCompassArrow),this.options.visualizeRoll&&this._map.on("roll",this._rotateCompassArrow),this._map.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new ls(this._map,this._compass,this.options.visualizePitch)),this._container}onRemove(){wi.remove(this._container),this.options.showZoom&&this._map.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&this._map.off("pitch",this._rotateCompassArrow),this.options.visualizeRoll&&this._map.off("roll",this._rotateCompassArrow),this._map.off("rotate",this._rotateCompassArrow),this._handler.off(),delete this._handler),delete this._map;}_createButton(e,t){const i=wi.create("button",e,this._container);return i.type="button",i.addEventListener("click",t),i}},e.Popup=class extends t.Evented{constructor(e){super(),this.remove=()=>(this._content&&wi.remove(this._content),this._container&&(wi.remove(this._container),delete this._container),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 t.Event("close"))),this),this._onMouseUp=e=>{this._update(e.point);},this._onMouseMove=e=>{this._update(e.point);},this._onDrag=e=>{this._update(e.point);},this._update=e=>{var t;if(!this._map||!this._lngLat&&!this._trackPointer||!this._content)return;if(!this._container){if(this._container=wi.create("div","maplibregl-popup",this._map.getContainer()),this._tip=wi.create("div","maplibregl-popup-tip",this._container),this._container.appendChild(this._content),this.options.className)for(const e of this.options.className.split(" "))this._container.classList.add(e);this._closeButton&&this._closeButton.setAttribute("aria-label",this._map._getUIString("Popup.Close")),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),this._lngLat=this._map.transform.renderWorldCopies&&!this._trackPointer?hs(this._lngLat,this._flatPos,this._map.transform):null===(t=this._lngLat)||void 0===t?void 0:t.wrap(),this._trackPointer&&!e)return;const i=this._flatPos=this._pos=this._trackPointer&&e?e:this._map.project(this._lngLat);this._map.terrain&&(this._flatPos=this._trackPointer&&e?e:this._map.transform.locationToScreenPoint(this._lngLat));let r=this.options.anchor;const o=ws(this.options.offset);if(!r){const e=this._container.offsetWidth,t=this._container.offsetHeight;let a;a=i.y+o.bottom.ythis._map.transform.height-t?["bottom"]:[],i.xthis._map.transform.width-e/2&&a.push("right"),r=0===a.length?"bottom":a.join("-");}let a=i.add(o[r]);this.options.subpixelPositioning||(a=a.round()),wi.setTransform(this._container,`${us[r]} translate(${a.x}px,${a.y}px)`),ds(this._container,r,"popup");},this._onClose=()=>{this.remove();},this.options=t.extend(Object.create(xs),e);}addTo(e){return this._map&&this.remove(),this._map=e,this.options.closeOnClick&&this._map.on("click",this._onClose),this.options.closeOnMove&&this._map.on("move",this._onClose),this._map.on("remove",this.remove),this._update(),this._focusFirstElement(),this._trackPointer?(this._map.on("mousemove",this._onMouseMove),this._map.on("mouseup",this._onMouseUp),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")):this._map.on("move",this._update),this.fire(new t.Event("open")),this}isOpen(){return !!this._map}getLngLat(){return this._lngLat}setLngLat(e){return this._lngLat=t.LngLat.convert(e),this._pos=null,this._flatPos=null,this._trackPointer=!1,this._update(),this._map&&(this._map.on("move",this._update),this._map.off("mousemove",this._onMouseMove),this._container&&this._container.classList.remove("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.remove("maplibregl-track-pointer")),this}trackPointer(){return this._trackPointer=!0,this._pos=null,this._flatPos=null,this._update(),this._map&&(this._map.off("move",this._update),this._map.on("mousemove",this._onMouseMove),this._map.on("drag",this._onDrag),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")),this}getElement(){return this._container}setText(e){return this.setDOMContent(document.createTextNode(e))}setHTML(e){const t=document.createDocumentFragment(),i=document.createElement("body");let r;for(i.innerHTML=e;r=i.firstChild,r;)t.appendChild(r);return this.setDOMContent(t)}getMaxWidth(){var e;return null===(e=this._container)||void 0===e?void 0:e.style.maxWidth}setMaxWidth(e){return this.options.maxWidth=e,this._update(),this}setDOMContent(e){if(this._content)for(;this._content.hasChildNodes();)this._content.firstChild&&this._content.removeChild(this._content.firstChild);else this._content=wi.create("div","maplibregl-popup-content",this._container);return this._content.appendChild(e),this._createCloseButton(),this._update(),this._focusFirstElement(),this}addClassName(e){return this._container&&this._container.classList.add(e),this}removeClassName(e){return this._container&&this._container.classList.remove(e),this}setOffset(e){return this.options.offset=e,this._update(),this}toggleClassName(e){if(this._container)return this._container.classList.toggle(e)}setSubpixelPositioning(e){this.options.subpixelPositioning=e;}_createCloseButton(){this.options.closeButton&&(this._closeButton=wi.create("button","maplibregl-popup-close-button",this._content),this._closeButton.type="button",this._closeButton.innerHTML="×",this._closeButton.addEventListener("click",this._onClose));}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const e=this._container.querySelector(bs);e&&e.focus();}},e.RasterDEMTileSource=$,e.RasterTileSource=X,e.ScaleControl=class{constructor(e){this._onMove=()=>{vs(this._map,this._container,this.options);},this.setUnit=e=>{this.options.unit=e,vs(this._map,this._container,this.options);},this.options=Object.assign(Object.assign({},gs),e);}getDefaultPosition(){return "bottom-left"}onAdd(e){return this._map=e,this._container=wi.create("div","maplibregl-ctrl maplibregl-ctrl-scale",e.getContainer()),this._map.on("move",this._onMove),this._onMove(),this._container}onRemove(){wi.remove(this._container),this._map.off("move",this._onMove),this._map=void 0;}},e.ScrollZoomHandler=pa,e.Style=gi,e.TerrainControl=class{constructor(e){this._toggleTerrain=()=>{this._map.getTerrain()?this._map.setTerrain(null):this._map.setTerrain(this.options),this._updateTerrainIcon();},this._updateTerrainIcon=()=>{this._terrainButton.classList.remove("maplibregl-ctrl-terrain"),this._terrainButton.classList.remove("maplibregl-ctrl-terrain-enabled"),this._map.terrain?(this._terrainButton.classList.add("maplibregl-ctrl-terrain-enabled"),this._terrainButton.title=this._map._getUIString("TerrainControl.Disable")):(this._terrainButton.classList.add("maplibregl-ctrl-terrain"),this._terrainButton.title=this._map._getUIString("TerrainControl.Enable"));},this.options=e;}onAdd(e){return this._map=e,this._container=wi.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._terrainButton=wi.create("button","maplibregl-ctrl-terrain",this._container),wi.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),this._container}onRemove(){wi.remove(this._container),this._map.off("terrain",this._updateTerrainIcon),this._map=void 0;}},e.TwoFingersTouchPitchHandler=ca,e.TwoFingersTouchRotateHandler=na,e.TwoFingersTouchZoomHandler=aa,e.TwoFingersTouchZoomRotateHandler=xa,e.VectorTileSource=W,e.VideoSource=Y,e.addSourceType=(e,i)=>t.__awaiter(void 0,void 0,void 0,(function*(){if(ee(e))throw new Error(`A source type called "${e}" already exists.`);((e,t)=>{Q[e]=t;})(e,i);})),e.clearPrewarmedResources=function(){const e=k;e&&(e.isPreloaded()&&1===e.numActive()?(e.release(z),k=null):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()"));},e.createTileMesh=Kt,e.getMaxParallelImageRequests=function(){return t.config.MAX_PARALLEL_IMAGE_REQUESTS},e.getRTLTextPluginStatus=function(){return oe().getRTLTextPluginStatus()},e.getVersion=function(){return Ts},e.getWorkerCount=function(){return L.workerCount},e.getWorkerUrl=function(){return t.config.WORKER_URL},e.importScriptInWorkers=function(e){return U().broadcast("IS",e)},e.prewarm=function(){B().acquire(z);},e.setMaxParallelImageRequests=function(e){t.config.MAX_PARALLEL_IMAGE_REQUESTS=e;},e.setRTLTextPlugin=function(e,t){return oe().setRTLTextPlugin(e,t)},e.setWorkerCount=function(e){L.workerCount=e;},e.setWorkerUrl=function(e){t.config.WORKER_URL=e;};})); +define("index",["exports","./shared"],(function(e,t){"use strict";function i(){var e=new t.ARRAY_TYPE(4);return t.ARRAY_TYPE!=Float32Array&&(e[1]=0,e[2]=0),e[0]=1,e[3]=1,e}function r(e){return e.map((e=>{const{coordinates:i}=e.geometry,{zoom:r}=e.properties,{x:o,y:a}=t.MercatorCoordinate.fromLngLat({lng:i[0],lat:i[1]}),s=Math.pow(2,r),n=Math.floor(o*s),l=Math.floor(a*s);return {description:e.properties.place_name,tileID:[new t.OverscaledTileID(r,0,r,n,l)],zoom:r,center:i}}))}var o=[{type:"Feature",geometry:{type:"Point",coordinates:[-95.392,29.799]},properties:{place_name:"Roads, Houston, z12",zoom:12,tags:["road"]}},{type:"Feature",geometry:{type:"Point",coordinates:[-95.381,29.749]},properties:{place_name:"Roads, Houston, z13",zoom:13,tags:["road","poi_label","landuse"]}},{type:"Feature",geometry:{type:"Point",coordinates:[-73.985,40.758]},properties:{place_name:"High zoom labels, buildings, roads, New York City, z16",zoom:16,tags:["poi_label","building","road"]}},{type:"Feature",geometry:{type:"Point",coordinates:[-73.985,40.758]},properties:{place_name:"High zoom labels, buildings, roads, New York City, z17, overzoomed",zoom:17,tags:["poi_label","road","building"]}},{type:"Feature",geometry:{type:"Point",coordinates:[139.76,35.695]},properties:{place_name:"High zoom cjk labels, when using local lang, buildings, roads, Tokyo, z16",zoom:16,tags:["poi_label","building","road"]}},{type:"Feature",geometry:{type:"Point",coordinates:[139.76,35.695]},properties:{place_name:"High zoom cjk labels, when using local lang, buildings, roads, Tokyo, z17, overzoomed",zoom:17,tags:["poi_label","road","building"]}},{type:"Feature",geometry:{type:"Point",coordinates:[27.602,61.521]},properties:{place_name:"Water, Finland, z10",zoom:10,tags:["water"]}},{type:"Feature",geometry:{type:"Point",coordinates:[2.21,48.745]},properties:{place_name:"Landuse and roads, Paris, z11",zoom:11,tags:["place_label:settlement","road","landuse","poi_label","hillshade"]}},{type:"Feature",geometry:{type:"Point",coordinates:[-118.314,33.996]},properties:{place_name:"Buildings, LA, z16",zoom:16,tags:["building","road"]}},{type:"Feature",geometry:{type:"Point",coordinates:[2.316,48.867]},properties:{place_name:"High zoom roads, paths, landuse, labels, Paris, 15",zoom:15,tags:["road","road:pedestrian","poi_label","landuse","transit_stop_label"]}},{type:"Feature",geometry:{type:"Point",coordinates:[2.316,48.867]},properties:{place_name:"High zoom pedestrian polygon fills, roads, paths, landuse, labels, Paris, z16",zoom:16,tags:["landuse","road","road:pedestrian","poi_label","road:path"]}},{type:"Feature",geometry:{type:"Point",coordinates:[8.835,46.317]},properties:{place_name:"Hillshading, Switzerland, z9",zoom:9,tags:["hillshade","place_label"]}},{type:"Feature",geometry:{type:"Point",coordinates:[8.835,46.317]},properties:{place_name:"Hillshading and contours, Switzerland, z12",zoom:12,tags:["hillshade"]}},{type:"Feature",geometry:{type:"Point",coordinates:[8.416,51.056]},properties:{place_name:"Landcover, Germany z6",zoom:6,tags:["landcover","place_label:settlement","road","admin"]}},{type:"Feature",geometry:{type:"Point",coordinates:[7.762,50.322]},properties:{place_name:"Landcover, Germany z8",zoom:8,tags:["place_label:settlement","road","hillshade"]}}];class a{constructor(){this.minimumMeasurements=210;}setup(){}bench(){}teardown(){}run(){return t.__awaiter(this,void 0,void 0,(function*(){try{return yield this.setup(),this._begin()}catch(e){console.error(e);}}))}_done(){return this._elapsed>=500&&this._measurements.length>this.minimumMeasurements}_begin(){this._measurements=[],this._elapsed=0,this._iterationsPerMeasurement=1,this._start=performance.now();const e=this.bench();return e instanceof Promise?e.then((()=>this._measureAsync())):this._measureSync()}_measureSync(){for(;;){const e=performance.now()-this._start;if(this._elapsed+=e,e<5?this._iterationsPerMeasurement++:this._measurements.push({time:e,iterations:this._iterationsPerMeasurement}),this._done())return this._end();this._start=performance.now();for(let e=this._iterationsPerMeasurement;e>0;--e)this.bench();}}_measureAsync(){return t.__awaiter(this,void 0,void 0,(function*(){for(;;){const e=performance.now()-this._start;if(this._elapsed+=e,e<5?this._iterationsPerMeasurement++:this._measurements.push({time:e,iterations:this._iterationsPerMeasurement}),this._done())return this._end();this._start=performance.now();for(let e=this._iterationsPerMeasurement;e>0;--e)yield this.bench();}}))}_end(){return t.__awaiter(this,void 0,void 0,(function*(){return yield this.teardown(),this._measurements}))}}function s(e){return "string"==typeof e?fetch(e).then((e=>e.json())):Promise.resolve(e)}const n={supported:!1,testSupport:function(e){!h&&c&&(u?d(e):l=e);}};let l,c,h=!1,u=!1;function d(e){const t=e.createTexture();e.bindTexture(e.TEXTURE_2D,t);try{if(e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,c),e.isContextLost())return;n.supported=!0;}catch(e){}e.deleteTexture(t),h=!0;}var _;let p,m;"undefined"!=typeof document&&(c=document.createElement("img"),c.onload=()=>{l&&d(l),l=null,u=!0;},c.onerror=()=>{h=!0,l=null;},c.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA="),function(e){let i,r,o,a;e.resetRequestQueue=()=>{i=[],r=0,o=0,a={};},e.addThrottleControl=e=>{const t=o++;return a[t]=e,t},e.removeThrottleControl=e=>{delete a[e],l();},e.getImage=(e,r,o=!0)=>new Promise(((a,s)=>{n.supported&&(e.headers||(e.headers={}),e.headers.accept="image/webp,*/*"),t.extend(e,{type:"image"}),i.push({abortController:r,requestParameters:e,supportImageRefresh:o,state:"queued",onError:e=>{s(e);},onSuccess:e=>{a(e);}}),l();}));const s=e=>t.__awaiter(this,void 0,void 0,(function*(){e.state="running";const{requestParameters:i,supportImageRefresh:o,onError:a,onSuccess:s,abortController:n}=e,h=!1===o&&!t.isWorker(self)&&!t.getProtocol(i.url)&&(!i.headers||Object.keys(i.headers).reduce(((e,t)=>e&&"accept"===t),!0));r++;const u=h?c(i,n):t.makeRequest(i,n);try{const i=yield u;delete e.abortController,e.state="completed",i.data instanceof HTMLImageElement||t.isImageBitmap(i.data)?s(i):i.data&&s({data:yield(d=i.data,"function"==typeof createImageBitmap?t.arrayBufferToImageBitmap(d):t.arrayBufferToImage(d)),cacheControl:i.cacheControl,expires:i.expires});}catch(t){delete e.abortController,a(t);}finally{r--,l();}var d;})),l=()=>{const e=(()=>{for(const e of Object.keys(a))if(a[e]())return !0;return !1})()?t.config.MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME:t.config.MAX_PARALLEL_IMAGE_REQUESTS;for(let t=r;t0;t++){const e=i.shift();e.abortController.signal.aborted?t--:s(e);}},c=(e,i)=>new Promise(((r,o)=>{const a=new Image,s=e.url,n=e.credentials;n&&"include"===n?a.crossOrigin="use-credentials":(n&&"same-origin"===n||!t.sameOrigin(s))&&(a.crossOrigin="anonymous"),i.signal.addEventListener("abort",(()=>{a.src="",o(t.createAbortError());})),a.fetchPriority="high",a.onload=()=>{a.onerror=a.onload=null,r({data:a});},a.onerror=()=>{a.onerror=a.onload=null,i.signal.aborted||o(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."));},a.src=s;}));}(_||(_={})),_.resetRequestQueue();const f={now:"undefined"!=typeof performance&&performance&&performance.now?performance.now.bind(performance):Date.now.bind(Date),frameAsync:e=>new Promise(((i,r)=>{const o=requestAnimationFrame(i);e.signal.addEventListener("abort",(()=>{cancelAnimationFrame(o),r(t.createAbortError());}));})),getImageData(e,t=0){return this.getImageCanvasContext(e).getImageData(-t,-t,e.width+2*t,e.height+2*t)},getImageCanvasContext(e){const t=window.document.createElement("canvas"),i=t.getContext("2d",{willReadFrequently:!0});if(!i)throw new Error("failed to create canvas 2d context");return t.width=e.width,t.height=e.height,i.drawImage(e,0,0,e.width,e.height),i},resolveURL:e=>(p||(p=document.createElement("a")),p.href=e,p.href),hardwareConcurrency:"undefined"!=typeof navigator&&navigator.hardwareConcurrency||4,get prefersReducedMotion(){return !!matchMedia&&(null==m&&(m=matchMedia("(prefers-reduced-motion: reduce)")),m.matches)}};function g(e){const t=[];if("string"==typeof e)t.push({id:"default",url:e});else if(e&&e.length>0){const i=[];for(const{id:r,url:o}of e){const e=`${r}${o}`;-1===i.indexOf(e)&&(i.push(e),t.push({id:r,url:o}));}}return t}function v(e,t,i){try{const r=new URL(e);return r.pathname+=`${t}${i}`,r.toString()}catch(t){throw new Error(`Invalid sprite URL "${e}", must be absolute. Modify style specification directly or use TransformStyleFunction to correct the issue dynamically`)}}class y{constructor(e,t,i,r){this.context=e,this.format=i,this.texture=e.gl.createTexture(),this.update(t,r);}update(e,i,r){const{width:o,height:a}=e,s=!(this.size&&this.size[0]===o&&this.size[1]===a||r),{context:n}=this,{gl:l}=n;if(this.useMipmap=Boolean(i&&i.useMipmap),l.bindTexture(l.TEXTURE_2D,this.texture),n.pixelStoreUnpackFlipY.set(!1),n.pixelStoreUnpack.set(1),n.pixelStoreUnpackPremultiplyAlpha.set(this.format===l.RGBA&&(!i||!1!==i.premultiply)),s)this.size=[o,a],e instanceof HTMLImageElement||e instanceof HTMLCanvasElement||e instanceof HTMLVideoElement||e instanceof ImageData||t.isImageBitmap(e)?l.texImage2D(l.TEXTURE_2D,0,this.format,this.format,l.UNSIGNED_BYTE,e):l.texImage2D(l.TEXTURE_2D,0,this.format,o,a,0,this.format,l.UNSIGNED_BYTE,e.data);else {const{x:i,y:s}=r||{x:0,y:0};e instanceof HTMLImageElement||e instanceof HTMLCanvasElement||e instanceof HTMLVideoElement||e instanceof ImageData||t.isImageBitmap(e)?l.texSubImage2D(l.TEXTURE_2D,0,i,s,l.RGBA,l.UNSIGNED_BYTE,e):l.texSubImage2D(l.TEXTURE_2D,0,i,s,o,a,l.RGBA,l.UNSIGNED_BYTE,e.data);}this.useMipmap&&this.isSizePowerOfTwo()&&l.generateMipmap(l.TEXTURE_2D);}bind(e,t,i){const{context:r}=this,{gl:o}=r;o.bindTexture(o.TEXTURE_2D,this.texture),i!==o.LINEAR_MIPMAP_NEAREST||this.isSizePowerOfTwo()||(i=o.LINEAR),e!==this.filter&&(o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,e),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,i||e),this.filter=e),t!==this.wrap&&(o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,t),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,t),this.wrap=t);}isSizePowerOfTwo(){return this.size[0]===this.size[1]&&Math.log(this.size[0])/Math.LN2%1==0}destroy(){const{gl:e}=this.context;e.deleteTexture(this.texture),this.texture=null;}}function x(e){const{userImage:t}=e;return !!(t&&t.render&&t.render())&&(e.data.replace(new Uint8Array(t.data.buffer)),!0)}class b extends t.Evented{constructor(){super(),this.images={},this.updatedImages={},this.callbackDispatchedThisFrame={},this.loaded=!1,this.requestors=[],this.patterns={},this.atlasImage=new t.RGBAImage({width:1,height:1}),this.dirty=!0;}isLoaded(){return this.loaded}setLoaded(e){if(this.loaded!==e&&(this.loaded=e,e)){for(const{ids:e,promiseResolve:t}of this.requestors)t(this._getImagesForIds(e));this.requestors=[];}}getImage(e){const i=this.images[e];if(i&&!i.data&&i.spriteData){const e=i.spriteData;i.data=new t.RGBAImage({width:e.width,height:e.height},e.context.getImageData(e.x,e.y,e.width,e.height).data),i.spriteData=null;}return i}addImage(e,t){if(this.images[e])throw new Error(`Image id ${e} already exist, use updateImage instead`);this._validate(e,t)&&(this.images[e]=t);}_validate(e,i){let r=!0;const o=i.data||i.spriteData;return this._validateStretch(i.stretchX,o&&o.width)||(this.fire(new t.ErrorEvent(new Error(`Image "${e}" has invalid "stretchX" value`))),r=!1),this._validateStretch(i.stretchY,o&&o.height)||(this.fire(new t.ErrorEvent(new Error(`Image "${e}" has invalid "stretchY" value`))),r=!1),this._validateContent(i.content,i)||(this.fire(new t.ErrorEvent(new Error(`Image "${e}" has invalid "content" value`))),r=!1),r}_validateStretch(e,t){if(!e)return !0;let i=0;for(const r of e){if(r[0]{let r=!0;if(!this.isLoaded())for(const t of e)this.images[t]||(r=!1);this.isLoaded()||r?t(this._getImagesForIds(e)):this.requestors.push({ids:e,promiseResolve:t});}))}_getImagesForIds(e){const i={};for(const r of e){let e=this.getImage(r);e||(this.fire(new t.Event("styleimagemissing",{id:r})),e=this.getImage(r)),e?i[r]={data:e.data.clone(),pixelRatio:e.pixelRatio,sdf:e.sdf,version:e.version,stretchX:e.stretchX,stretchY:e.stretchY,content:e.content,textFitWidth:e.textFitWidth,textFitHeight:e.textFitHeight,hasRenderCallback:Boolean(e.userImage&&e.userImage.render)}:t.warnOnce(`Image "${r}" 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 i}getPixelSize(){const{width:e,height:t}=this.atlasImage;return {width:e,height:t}}getPattern(e){const i=this.patterns[e],r=this.getImage(e);if(!r)return null;if(i&&i.position.version===r.version)return i.position;if(i)i.position.version=r.version;else {const i={w:r.data.width+2,h:r.data.height+2,x:0,y:0},o=new t.ImagePosition(i,r);this.patterns[e]={bin:i,position:o};}return this._updatePatternAtlas(),this.patterns[e].position}bind(e){const t=e.gl;this.atlasTexture?this.dirty&&(this.atlasTexture.update(this.atlasImage),this.dirty=!1):this.atlasTexture=new y(e,this.atlasImage,t.RGBA),this.atlasTexture.bind(t.LINEAR,t.CLAMP_TO_EDGE);}_updatePatternAtlas(){const e=[];for(const t in this.patterns)e.push(this.patterns[t].bin);const{w:i,h:r}=t.potpack(e),o=this.atlasImage;o.resize({width:i||1,height:r||1});for(const e in this.patterns){const{bin:i}=this.patterns[e],r=i.x+1,a=i.y+1,s=this.getImage(e).data,n=s.width,l=s.height;t.RGBAImage.copy(s,o,{x:0,y:0},{x:r,y:a},{width:n,height:l}),t.RGBAImage.copy(s,o,{x:0,y:l-1},{x:r,y:a-1},{width:n,height:1}),t.RGBAImage.copy(s,o,{x:0,y:0},{x:r,y:a+l},{width:n,height:1}),t.RGBAImage.copy(s,o,{x:n-1,y:0},{x:r-1,y:a},{width:1,height:l}),t.RGBAImage.copy(s,o,{x:0,y:0},{x:r+n,y:a},{width:1,height:l});}this.dirty=!0;}beginFrame(){this.callbackDispatchedThisFrame={};}dispatchRenderCallbacks(e){for(const i of e){if(this.callbackDispatchedThisFrame[i])continue;this.callbackDispatchedThisFrame[i]=!0;const e=this.getImage(i);e||t.warnOnce(`Image with ID: "${i}" was not found`),x(e)&&this.updateImage(i,e);}}}const w=1e20;function T(e,t,i,r,o,a,s,n,l){for(let c=t;c-1);l++,a[l]=n,s[l]=c,s[l+1]=w;}for(let n=0,l=0;n65535)throw new Error("glyphs > 65535 not supported");if(t.ranges[o])return {stack:e,id:i,glyph:r};if(!this.url)throw new Error("glyphsUrl is not set");if(!t.requests[o]){const i=P.loadGlyphRange(e,o,this.url,this.requestManager);t.requests[o]=i;}const a=yield t.requests[o];for(const e in a)this._doesCharSupportLocalGlyph(+e)||(t.glyphs[+e]=a[+e]);return t.ranges[o]=!0,{stack:e,id:i,glyph:a[i]||null}}))}_doesCharSupportLocalGlyph(e){return !!this.localIdeographFontFamily&&/\p{Ideo}|\p{sc=Hang}|\p{sc=Hira}|\p{sc=Kana}/u.test(String.fromCodePoint(e))}_tinySDF(e,i,r){const o=this.localIdeographFontFamily;if(!o)return;if(!this._doesCharSupportLocalGlyph(r))return;let a=e.tinySDF;if(!a){let t="400";/bold/i.test(i)?t="900":/medium/i.test(i)?t="500":/light/i.test(i)&&(t="200"),a=e.tinySDF=new P.TinySDF({fontSize:48,buffer:6,radius:16,cutoff:.25,fontFamily:o,fontWeight:t});}const s=a.draw(String.fromCharCode(r));return {id:r,bitmap:new t.AlphaImage({width:s.width||60,height:s.height||60},s.data),metrics:{width:s.glyphWidth/2||24,height:s.glyphHeight/2||24,left:s.glyphLeft/2+.5||0,top:s.glyphTop/2-27.5||-8,advance:s.glyphAdvance/2||24,isDoubleResolution:!0}}}}P.loadGlyphRange=function(e,i,r,o){return t.__awaiter(this,void 0,void 0,(function*(){const a=256*i,s=a+255,n=o.transformRequest(r.replace("{fontstack}",e).replace("{range}",`${a}-${s}`),"Glyphs"),l=yield t.getArrayBuffer(n,new AbortController);if(!l||!l.data)throw new Error(`Could not load glyph range. range: ${i}, ${a}-${s}`);const c={};for(const e of t.parseGlyphPbf(l.data))c[e.id]=e;return c}))},P.TinySDF=class{constructor({fontSize:e=24,buffer:t=3,radius:i=8,cutoff:r=.25,fontFamily:o="sans-serif",fontWeight:a="normal",fontStyle:s="normal"}={}){this.buffer=t,this.cutoff=r,this.radius=i;const n=this.size=e+4*t,l=this._createCanvas(n),c=this.ctx=l.getContext("2d",{willReadFrequently:!0});c.font=`${s} ${a} ${e}px ${o}`,c.textBaseline="alphabetic",c.textAlign="left",c.fillStyle="black",this.gridOuter=new Float64Array(n*n),this.gridInner=new Float64Array(n*n),this.f=new Float64Array(n),this.z=new Float64Array(n+1),this.v=new Uint16Array(n);}_createCanvas(e){const t=document.createElement("canvas");return t.width=t.height=e,t}draw(e){const{width:t,actualBoundingBoxAscent:i,actualBoundingBoxDescent:r,actualBoundingBoxLeft:o,actualBoundingBoxRight:a}=this.ctx.measureText(e),s=Math.ceil(i),n=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(a-o))),l=Math.min(this.size-this.buffer,s+Math.ceil(r)),c=n+2*this.buffer,h=l+2*this.buffer,u=Math.max(c*h,0),d=new Uint8ClampedArray(u),_={data:d,width:c,height:h,glyphWidth:n,glyphHeight:l,glyphTop:s,glyphLeft:0,glyphAdvance:t};if(0===n||0===l)return _;const{ctx:p,buffer:m,gridInner:f,gridOuter:g}=this;p.clearRect(m,m,n,l),p.fillText(e,m,m+s);const v=p.getImageData(m,m,n,l);g.fill(w,0,u),f.fill(0,0,u);for(let e=0;e0?e*e:0,f[r]=e<0?e*e:0;}}T(g,0,0,c,h,c,this.f,this.v,this.z),T(f,m,m,n,l,c,this.f,this.v,this.z);for(let e=0;e1&&(s=e[++a]);const l=Math.abs(n-s.left),c=Math.abs(n-s.right),h=Math.min(l,c);let u;const d=t/i*(r+1);if(s.isDash){const e=r-Math.abs(d);u=Math.sqrt(h*h+e*e);}else u=r-Math.sqrt(h*h+d*d);this.data[o+n]=Math.max(0,Math.min(255,u+128));}}}addRegularDash(e){for(let t=e.length-1;t>=0;--t){const i=e[t],r=e[t+1];i.zeroLength?e.splice(t,1):r&&r.isDash===i.isDash&&(r.left=i.left,e.splice(t,1));}const t=e[0],i=e[e.length-1];t.isDash===i.isDash&&(t.left=i.left-this.width,i.right=t.right+this.width);const r=this.width*this.nextRow;let o=0,a=e[o];for(let t=0;t1&&(a=e[++o]);const i=Math.abs(t-a.left),s=Math.abs(t-a.right),n=Math.min(i,s);this.data[r+t]=Math.max(0,Math.min(255,(a.isDash?n:-n)+128));}}addDash(e,i){const r=i?7:0,o=2*r+1;if(this.nextRow+o>this.height)return t.warnOnce("LineAtlas out of space"),null;let a=0;for(let t=0;t{e.terminate();})),this.workers=null);}isPreloaded(){return !!this.active[z]}numActive(){return Object.keys(this.active).length}}const A=Math.floor(f.hardwareConcurrency/2);let k,F;function B(){return k||(k=new L),k}L.workerCount=t.isSafari(globalThis)?Math.max(Math.min(A,3),1):1;class O{constructor(e,i){this.workerPool=e,this.actors=[],this.currentActor=0,this.id=i;const r=this.workerPool.acquire(i);for(let e=0;e{e.remove();})),this.actors=[],e&&this.workerPool.release(this.id);}registerMessageHandler(e,t){for(const i of this.actors)i.registerMessageHandler(e,t);}}function U(){return F||(F=new O(B(),t.GLOBAL_DISPATCHER_ID),F.registerMessageHandler("GR",((e,i,r)=>t.makeRequest(i,r)))),F}function j(e,i){const r=t.create();return t.translate(r,r,[1,1,0]),t.scale(r,r,[.5*e.width,.5*e.height,1]),e.calculatePosMatrix?t.multiply(r,r,e.calculatePosMatrix(i.toUnwrapped())):r}function N(e,t,i,r,o,a){var s;const n=function(e,t,i){if(e)for(const r of e){const e=t[r];if(e&&e.source===i&&"fill-extrusion"===e.type)return !0}else for(const e in t){const r=t[e];if(r.source===i&&"fill-extrusion"===r.type)return !0}return !1}(null!==(s=null==o?void 0:o.layers)&&void 0!==s?s:null,t,e.id),l=a.maxPitchScaleFactor(),c=e.tilesIn(r,l,n);c.sort(G);const h=[];for(const r of c)h.push({wrappedTileID:r.tileID.wrapped().key,queryResults:r.tile.queryRenderedFeatures(t,i,e._state,r.queryGeometry,r.cameraQueryGeometry,r.scale,o,a,l,j(e.transform,r.tileID))});const u=function(e){const t={},i={};for(const r of e){const e=r.queryResults,o=r.wrappedTileID,a=i[o]=i[o]||{};for(const i in e){const r=e[i],o=a[i]=a[i]||{},s=t[i]=t[i]||[];for(const e of r)o[e.featureIndex]||(o[e.featureIndex]=!0,s.push(e));}}return t}(h);for(const t in u)u[t].forEach((t=>{const i=t.feature,r=e.getFeatureState(i.layer["source-layer"],i.id);i.source=i.layer.source,i.layer["source-layer"]&&(i.sourceLayer=i.layer["source-layer"]),i.state=r;}));return u}function G(e,t){const i=e.tileID,r=t.tileID;return i.overscaledZ-r.overscaledZ||i.canonical.y-r.canonical.y||i.wrap-r.wrap||i.canonical.x-r.canonical.x}function Z(e,i,r){return t.__awaiter(this,void 0,void 0,(function*(){let o=e;if(e.url?o=(yield t.getJSON(i.transformRequest(e.url,"Source"),r)).data:yield f.frameAsync(r),!o)return null;const a=t.pick(t.extend(o,e),["tiles","minzoom","maxzoom","attribution","bounds","scheme","tileSize","encoding"]);return "vector_layers"in o&&o.vector_layers&&(a.vectorLayerIds=o.vector_layers.map((e=>e.id))),a}))}class V{constructor(e,t){e&&(t?this.setSouthWest(e).setNorthEast(t):Array.isArray(e)&&(4===e.length?this.setSouthWest([e[0],e[1]]).setNorthEast([e[2],e[3]]):this.setSouthWest(e[0]).setNorthEast(e[1])));}setNorthEast(e){return this._ne=e instanceof t.LngLat?new t.LngLat(e.lng,e.lat):t.LngLat.convert(e),this}setSouthWest(e){return this._sw=e instanceof t.LngLat?new t.LngLat(e.lng,e.lat):t.LngLat.convert(e),this}extend(e){const i=this._sw,r=this._ne;let o,a;if(e instanceof t.LngLat)o=e,a=e;else {if(!(e instanceof V))return Array.isArray(e)?4===e.length||e.every(Array.isArray)?this.extend(V.convert(e)):this.extend(t.LngLat.convert(e)):e&&("lng"in e||"lon"in e)&&"lat"in e?this.extend(t.LngLat.convert(e)):this;if(o=e._sw,a=e._ne,!o||!a)return this}return i||r?(i.lng=Math.min(o.lng,i.lng),i.lat=Math.min(o.lat,i.lat),r.lng=Math.max(a.lng,r.lng),r.lat=Math.max(a.lat,r.lat)):(this._sw=new t.LngLat(o.lng,o.lat),this._ne=new t.LngLat(a.lng,a.lat)),this}getCenter(){return new t.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 t.LngLat(this.getWest(),this.getNorth())}getSouthEast(){return new t.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(e){const{lng:i,lat:r}=t.LngLat.convert(e);let o=this._sw.lng<=i&&i<=this._ne.lng;return this._sw.lng>this._ne.lng&&(o=this._sw.lng>=i&&i>=this._ne.lng),this._sw.lat<=r&&r<=this._ne.lat&&o}static convert(e){return e instanceof V?e:e?new V(e):e}static fromLngLat(e,i=0){const r=360*i/40075017,o=r/Math.cos(Math.PI/180*e.lat);return new V(new t.LngLat(e.lng-o,e.lat-r),new t.LngLat(e.lng+o,e.lat+r))}adjustAntiMeridian(){const e=new t.LngLat(this._sw.lng,this._sw.lat),i=new t.LngLat(this._ne.lng,this._ne.lat);return new V(e,e.lng>i.lng?new t.LngLat(i.lng+360,i.lat):i)}}class q{constructor(e,t,i){this.bounds=V.convert(this.validateBounds(e)),this.minzoom=t||0,this.maxzoom=i||24;}validateBounds(e){return Array.isArray(e)&&4===e.length?[Math.max(-180,e[0]),Math.max(-90,e[1]),Math.min(180,e[2]),Math.min(90,e[3])]:[-180,-90,180,90]}contains(e){const i=Math.pow(2,e.z),r=Math.floor(t.mercatorXfromLng(this.bounds.getWest())*i),o=Math.floor(t.mercatorYfromLat(this.bounds.getNorth())*i),a=Math.ceil(t.mercatorXfromLng(this.bounds.getEast())*i),s=Math.ceil(t.mercatorYfromLat(this.bounds.getSouth())*i);return e.x>=r&&e.x=o&&e.y{this._options.tiles=e;})),this}setUrl(e){return this.setSourceProperty((()=>{this.url=e,this._options.url=e;})),this}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null);}serialize(){return t.extend({},this._options)}loadTile(e){return t.__awaiter(this,void 0,void 0,(function*(){const t=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),i={request:this.map._requestManager.transformRequest(t,"Tile"),uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,tileSize:this.tileSize*e.tileID.overscaleFactor(),type:this.type,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,subdivisionGranularity:this.map.style.projection.subdivisionGranularity};i.request.collectResourceTiming=this._collectResourceTiming;let r="RT";if(e.actor&&"expired"!==e.state){if("loading"===e.state)return new Promise(((t,i)=>{e.reloadPromise={resolve:t,reject:i};}))}else e.actor=this.dispatcher.getActor(),r="LT";e.abortController=new AbortController;try{const t=yield e.actor.sendAsync({type:r,data:i},e.abortController);if(delete e.abortController,e.aborted)return;this._afterTileLoadWorkerResponse(e,t);}catch(t){if(delete e.abortController,e.aborted)return;if(t&&404!==t.status)throw t;this._afterTileLoadWorkerResponse(e,null);}}))}_afterTileLoadWorkerResponse(e,t){if(t&&t.resourceTiming&&(e.resourceTiming=t.resourceTiming),t&&this.map._refreshExpiredTiles&&e.setExpiryData(t),e.loadVectorData(t,this.map.painter),e.reloadPromise){const t=e.reloadPromise;e.reloadPromise=null,this.loadTile(e).then(t.resolve).catch(t.reject);}}abortTile(e){return t.__awaiter(this,void 0,void 0,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController),e.actor&&(yield e.actor.sendAsync({type:"AT",data:{uid:e.uid,type:this.type,source:this.id}}));}))}unloadTile(e){return t.__awaiter(this,void 0,void 0,(function*(){e.unloadVectorData(),e.actor&&(yield e.actor.sendAsync({type:"RMT",data:{uid:e.uid,type:this.type,source:this.id}}));}))}hasTransition(){return !1}}class X extends t.Evented{constructor(e,i,r,o){super(),this.id=e,this.dispatcher=r,this.setEventedParent(o),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme="xyz",this.tileSize=512,this._loaded=!1,this._options=t.extend({type:"raster"},i),t.extend(this,t.pick(i,["url","scheme","tileSize"]));}load(){return t.__awaiter(this,arguments,void 0,(function*(e=!1){this._loaded=!1,this.fire(new t.Event("dataloading",{dataType:"source"})),this._tileJSONRequest=new AbortController;try{const i=yield Z(this._options,this.map._requestManager,this._tileJSONRequest);this._tileJSONRequest=null,this._loaded=!0,i&&(t.extend(this,i),i.bounds&&(this.tileBounds=new q(i.bounds,this.minzoom,this.maxzoom)),this.fire(new t.Event("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new t.Event("data",{dataType:"source",sourceDataType:"content",sourceDataChanged:e})));}catch(e){this._tileJSONRequest=null,this.fire(new t.ErrorEvent(e));}}))}loaded(){return this._loaded}onAdd(e){this.map=e,this.load();}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null);}setSourceProperty(e){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null),e(),this.load(!0);}setTiles(e){return this.setSourceProperty((()=>{this._options.tiles=e;})),this}setUrl(e){return this.setSourceProperty((()=>{this.url=e,this._options.url=e;})),this}serialize(){return t.extend({},this._options)}hasTile(e){return !this.tileBounds||this.tileBounds.contains(e.canonical)}loadTile(e){return t.__awaiter(this,void 0,void 0,(function*(){const t=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme);e.abortController=new AbortController;try{const i=yield _.getImage(this.map._requestManager.transformRequest(t,"Tile"),e.abortController,this.map._refreshExpiredTiles);if(delete e.abortController,e.aborted)return void(e.state="unloaded");if(i&&i.data){this.map._refreshExpiredTiles&&i.cacheControl&&i.expires&&e.setExpiryData({cacheControl:i.cacheControl,expires:i.expires});const t=this.map.painter.context,r=t.gl,o=i.data;e.texture=this.map.painter.getTileTexture(o.width),e.texture?e.texture.update(o,{useMipmap:!0}):(e.texture=new y(t,o,r.RGBA,{useMipmap:!0}),e.texture.bind(r.LINEAR,r.CLAMP_TO_EDGE,r.LINEAR_MIPMAP_NEAREST)),e.state="loaded";}}catch(t){if(delete e.abortController,e.aborted)e.state="unloaded";else if(t)throw e.state="errored",t}}))}abortTile(e){return t.__awaiter(this,void 0,void 0,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController);}))}unloadTile(e){return t.__awaiter(this,void 0,void 0,(function*(){e.texture&&this.map.painter.saveTileTexture(e.texture);}))}hasTransition(){return !1}}class $ extends X{constructor(e,i,r,o){super(e,i,r,o),this.type="raster-dem",this.maxzoom=22,this._options=t.extend({type:"raster-dem"},i),this.encoding=i.encoding||"mapbox",this.redFactor=i.redFactor,this.greenFactor=i.greenFactor,this.blueFactor=i.blueFactor,this.baseShift=i.baseShift;}loadTile(e){return t.__awaiter(this,void 0,void 0,(function*(){const i=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),r=this.map._requestManager.transformRequest(i,"Tile");e.neighboringTiles=this._getNeighboringTiles(e.tileID),e.abortController=new AbortController;try{const i=yield _.getImage(r,e.abortController,this.map._refreshExpiredTiles);if(delete e.abortController,e.aborted)return void(e.state="unloaded");if(i&&i.data){const r=i.data;this.map._refreshExpiredTiles&&i.cacheControl&&i.expires&&e.setExpiryData({cacheControl:i.cacheControl,expires:i.expires});const o=t.isImageBitmap(r)&&t.offscreenCanvasSupported()?r:yield this.readImageNow(r),a={type:this.type,uid:e.uid,source:this.id,rawImageData:o,encoding:this.encoding,redFactor:this.redFactor,greenFactor:this.greenFactor,blueFactor:this.blueFactor,baseShift:this.baseShift};if(!e.actor||"expired"===e.state){e.actor=this.dispatcher.getActor();const t=yield e.actor.sendAsync({type:"LDT",data:a});e.dem=t,e.needsHillshadePrepare=!0,e.needsTerrainPrepare=!0,e.state="loaded";}}}catch(t){if(delete e.abortController,e.aborted)e.state="unloaded";else if(t)throw e.state="errored",t}}))}readImageNow(e){return t.__awaiter(this,void 0,void 0,(function*(){if("undefined"!=typeof VideoFrame&&t.isOffscreenCanvasDistorted()){const i=e.width+2,r=e.height+2;try{return new t.RGBAImage({width:i,height:r},yield t.readImageUsingVideoFrame(e,-1,-1,i,r))}catch(e){}}return f.getImageData(e,1)}))}_getNeighboringTiles(e){const i=e.canonical,r=Math.pow(2,i.z),o=(i.x-1+r)%r,a=0===i.x?e.wrap-1:e.wrap,s=(i.x+1+r)%r,n=i.x+1===r?e.wrap+1:e.wrap,l={};return l[new t.OverscaledTileID(e.overscaledZ,a,i.z,o,i.y).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,n,i.z,s,i.y).key]={backfilled:!1},i.y>0&&(l[new t.OverscaledTileID(e.overscaledZ,a,i.z,o,i.y-1).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,e.wrap,i.z,i.x,i.y-1).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,n,i.z,s,i.y-1).key]={backfilled:!1}),i.y+10&&t.extend(o,{resourceTiming:r}),this.fire(new t.Event("data",Object.assign(Object.assign({},o),{sourceDataType:"metadata"}))),this.fire(new t.Event("data",Object.assign(Object.assign({},o),{sourceDataType:"content"})));}catch(e){if(this._pendingLoads--,this._removed)return void this.fire(new t.Event("dataabort",{dataType:"source"}));this.fire(new t.ErrorEvent(e));}}))}loaded(){return 0===this._pendingLoads}loadTile(e){return t.__awaiter(this,void 0,void 0,(function*(){const t=e.actor?"RT":"LT";e.actor=this.actor;const i={type:this.type,uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,subdivisionGranularity:this.map.style.projection.subdivisionGranularity};e.abortController=new AbortController;const r=yield this.actor.sendAsync({type:t,data:i},e.abortController);delete e.abortController,e.unloadVectorData(),e.aborted||e.loadVectorData(r,this.map.painter,"RT"===t);}))}abortTile(e){return t.__awaiter(this,void 0,void 0,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController),e.aborted=!0;}))}unloadTile(e){return t.__awaiter(this,void 0,void 0,(function*(){e.unloadVectorData(),yield this.actor.sendAsync({type:"RMT",data:{uid:e.uid,type:this.type,source:this.id}});}))}onRemove(){this._removed=!0,this.actor.sendAsync({type:"RS",data:{type:this.type,source:this.id}});}serialize(){return t.extend({},this._options,{type:this.type,data:this._data})}hasTransition(){return !1}}class K extends t.Evented{constructor(e,t,i,r){super(),this.flippedWindingOrder=!1,this.id=e,this.dispatcher=i,this.coordinates=t.coordinates,this.type="image",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.tiles={},this._loaded=!1,this.setEventedParent(r),this.options=t;}load(e){return t.__awaiter(this,void 0,void 0,(function*(){this._loaded=!1,this.fire(new t.Event("dataloading",{dataType:"source"})),this.url=this.options.url,this._request=new AbortController;try{const t=yield _.getImage(this.map._requestManager.transformRequest(this.url,"Image"),this._request);this._request=null,this._loaded=!0,t&&t.data&&(this.image=t.data,e&&(this.coordinates=e),this._finishLoading());}catch(e){this._request=null,this._loaded=!0,this.fire(new t.ErrorEvent(e));}}))}loaded(){return this._loaded}updateImage(e){return e.url?(this._request&&(this._request.abort(),this._request=null),this.options.url=e.url,this.load(e.coordinates).finally((()=>{this.texture=null;})),this):this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new t.Event("data",{dataType:"source",sourceDataType:"metadata"})));}onAdd(e){this.map=e,this.load();}onRemove(){this._request&&(this._request.abort(),this._request=null);}setCoordinates(e){this.coordinates=e;const i=e.map(t.MercatorCoordinate.fromLngLat);var r;return this.tileID=function(e){let i=1/0,r=1/0,o=-1/0,a=-1/0;for(const t of e)i=Math.min(i,t.x),r=Math.min(r,t.y),o=Math.max(o,t.x),a=Math.max(a,t.y);const s=Math.max(o-i,a-r),n=Math.max(0,Math.floor(-Math.log(s)/Math.LN2)),l=Math.pow(2,n);return new t.CanonicalTileID(n,Math.floor((i+o)/2*l),Math.floor((r+a)/2*l))}(i),this.minzoom=this.maxzoom=this.tileID.z,this.tileCoords=i.map((e=>this.tileID.getTilePoint(e)._round())),this.flippedWindingOrder=((r=this.tileCoords)[1].x-r[0].x)*(r[2].y-r[0].y)-(r[1].y-r[0].y)*(r[2].x-r[0].x)<0,this.fire(new t.Event("data",{dataType:"source",sourceDataType:"content"})),this}prepare(){if(0===Object.keys(this.tiles).length||!this.image)return;const e=this.map.painter.context,i=e.gl;this.texture||(this.texture=new y(e,this.image,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE));let r=!1;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,r=!0);}r&&this.fire(new t.Event("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}loadTile(e){return t.__awaiter(this,void 0,void 0,(function*(){this.tileID&&this.tileID.equals(e.tileID.canonical)?(this.tiles[String(e.tileID.wrap)]=e,e.buckets={}):e.state="errored";}))}serialize(){return {type:"image",url:this.options.url,coordinates:this.coordinates}}hasTransition(){return !1}}class Y extends K{constructor(e,t,i,r){super(e,t,i,r),this.roundZoom=!0,this.type="video",this.options=t;}load(){return t.__awaiter(this,void 0,void 0,(function*(){this._loaded=!1;const e=this.options;this.urls=[];for(const t of e.urls)this.urls.push(this.map._requestManager.transformRequest(t,"Source").url);try{const e=yield t.getVideo(this.urls);if(this._loaded=!0,!e)return;this.video=e,this.video.loop=!0,this.video.addEventListener("playing",(()=>{this.map.triggerRepaint();})),this.map&&this.video.play(),this._finishLoading();}catch(e){this.fire(new t.ErrorEvent(e));}}))}pause(){this.video&&this.video.pause();}play(){this.video&&this.video.play();}seek(e){if(this.video){const i=this.video.seekable;ei.end(0)?this.fire(new t.ErrorEvent(new t.ValidationError(`sources.${this.id}`,null,`Playback for this video can be set only between the ${i.start(0)} and ${i.end(0)}-second mark.`))):this.video.currentTime=e;}}getVideo(){return this.video}onAdd(e){this.map||(this.map=e,this.load(),this.video&&(this.video.play(),this.setCoordinates(this.coordinates)));}prepare(){if(0===Object.keys(this.tiles).length||this.video.readyState<2)return;const e=this.map.painter.context,i=e.gl;this.texture?this.video.paused||(this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE),i.texSubImage2D(i.TEXTURE_2D,0,0,0,i.RGBA,i.UNSIGNED_BYTE,this.video)):(this.texture=new y(e,this.video,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE));let r=!1;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,r=!0);}r&&this.fire(new t.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 J extends K{constructor(e,i,r,o){super(e,i,r,o),i.coordinates?Array.isArray(i.coordinates)&&4===i.coordinates.length&&!i.coordinates.some((e=>!Array.isArray(e)||2!==e.length||e.some((e=>"number"!=typeof e))))||this.fire(new t.ErrorEvent(new t.ValidationError(`sources.${e}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new t.ErrorEvent(new t.ValidationError(`sources.${e}`,null,'missing required property "coordinates"'))),i.animate&&"boolean"!=typeof i.animate&&this.fire(new t.ErrorEvent(new t.ValidationError(`sources.${e}`,null,'optional "animate" property must be a boolean value'))),i.canvas?"string"==typeof i.canvas||i.canvas instanceof HTMLCanvasElement||this.fire(new t.ErrorEvent(new t.ValidationError(`sources.${e}`,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))):this.fire(new t.ErrorEvent(new t.ValidationError(`sources.${e}`,null,'missing required property "canvas"'))),this.options=i,this.animate=void 0===i.animate||i.animate;}load(){return t.__awaiter(this,void 0,void 0,(function*(){this._loaded=!0,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,this._hasInvalidDimensions()?this.fire(new t.ErrorEvent(new Error("Canvas dimensions cannot be less than or equal to zero."))):(this.play=function(){this._playing=!0,this.map.triggerRepaint();},this.pause=function(){this._playing&&(this.prepare(),this._playing=!1);},this._finishLoading());}))}getCanvas(){return this.canvas}onAdd(e){this.map=e,this.load(),this.canvas&&this.animate&&this.play();}onRemove(){this.pause();}prepare(){let e=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,e=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,e=!0),this._hasInvalidDimensions())return;if(0===Object.keys(this.tiles).length)return;const i=this.map.painter.context,r=i.gl;this.texture?(e||this._playing)&&this.texture.update(this.canvas,{premultiply:!0}):this.texture=new y(i,this.canvas,r.RGBA,{premultiply:!0});let o=!1;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,o=!0);}o&&this.fire(new t.Event("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}serialize(){return {type:"canvas",coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(const e of [this.canvas.width,this.canvas.height])if(isNaN(e)||e<=0)return !0;return !1}}const Q={},ee=e=>{switch(e){case"geojson":return H;case"image":return K;case"raster":return X;case"raster-dem":return $;case"vector":return W;case"video":return Y;case"canvas":return J}return Q[e]},te="RTLPluginLoaded";class ie extends t.Evented{constructor(){super(...arguments),this.status="unavailable",this.url=null,this.dispatcher=U();}_syncState(e){return this.status=e,this.dispatcher.broadcast("SRPS",{pluginStatus:e,pluginURL:this.url}).catch((e=>{throw this.status="error",e}))}getRTLTextPluginStatus(){return this.status}clearRTLTextPlugin(){this.status="unavailable",this.url=null;}setRTLTextPlugin(e){return t.__awaiter(this,arguments,void 0,(function*(e,t=!1){if(this.url)throw new Error("setRTLTextPlugin cannot be called multiple times.");if(this.url=f.resolveURL(e),!this.url)throw new Error(`requested url ${e} is invalid`);if("unavailable"===this.status){if(!t)return this._requestImport();this.status="deferred",this._syncState(this.status);}else if("requested"===this.status)return this._requestImport()}))}_requestImport(){return t.__awaiter(this,void 0,void 0,(function*(){yield this._syncState("loading"),this.status="loaded",this.fire(new t.Event(te));}))}lazyLoad(){"unavailable"===this.status?this.status="requested":"deferred"===this.status&&this._requestImport();}}let re=null;function oe(){return re||(re=new ie),re}class ae{constructor(e,i){this.timeAdded=0,this.fadeEndTime=0,this.tileID=e,this.uid=t.uniqueId(),this.uses=0,this.tileSize=i,this.buckets={},this.expirationTime=null,this.queryPadding=0,this.hasSymbolBuckets=!1,this.hasRTLText=!1,this.dependencies={},this.rtt=[],this.rttCoords={},this.expiredRequestCount=0,this.state="loading";}registerFadeDuration(e){const t=e+this.timeAdded;tt.getLayer(e))).filter(Boolean);if(0!==e.length){r.layers=e,r.stateDependentLayerIds&&(r.stateDependentLayers=r.stateDependentLayerIds.map((t=>e.filter((e=>e.id===t))[0])));for(const t of e)i[t.id]=r;}}return i}(e.buckets,null==i?void 0:i.style),this.hasSymbolBuckets=!1;for(const e in this.buckets){const i=this.buckets[e];if(i instanceof t.SymbolBucket){if(this.hasSymbolBuckets=!0,!r)break;i.justReloaded=!0;}}if(this.hasRTLText=!1,this.hasSymbolBuckets)for(const e in this.buckets){const i=this.buckets[e];if(i instanceof t.SymbolBucket&&i.hasRTLText){this.hasRTLText=!0,oe().lazyLoad();break}}this.queryPadding=0;for(const e in this.buckets){const t=this.buckets[e];this.queryPadding=Math.max(this.queryPadding,i.style.getLayer(e).queryRadius(t));}e.imageAtlas&&(this.imageAtlas=e.imageAtlas),e.glyphAtlasImage&&(this.glyphAtlasImage=e.glyphAtlasImage);}else this.collisionBoxArray=new t.CollisionBoxArray;}unloadVectorData(){for(const e in this.buckets)this.buckets[e].destroy();this.buckets={},this.imageAtlasTexture&&this.imageAtlasTexture.destroy(),this.imageAtlas&&(this.imageAtlas=null),this.glyphAtlasTexture&&this.glyphAtlasTexture.destroy(),this.latestFeatureIndex=null,this.state="unloaded";}getBucket(e){return this.buckets[e.id]}upload(e){for(const t in this.buckets){const i=this.buckets[t];i.uploadPending()&&i.upload(e);}const t=e.gl;this.imageAtlas&&!this.imageAtlas.uploaded&&(this.imageAtlasTexture=new y(e,this.imageAtlas.image,t.RGBA),this.imageAtlas.uploaded=!0),this.glyphAtlasImage&&(this.glyphAtlasTexture=new y(e,this.glyphAtlasImage,t.ALPHA),this.glyphAtlasImage=null);}prepare(e){this.imageAtlas&&this.imageAtlas.patchUpdatedImages(e,this.imageAtlasTexture);}queryRenderedFeatures(e,t,i,r,o,a,s,n,l,c){return this.latestFeatureIndex&&this.latestFeatureIndex.rawTileData?this.latestFeatureIndex.query({queryGeometry:r,cameraQueryGeometry:o,scale:a,tileSize:this.tileSize,pixelPosMatrix:c,transform:n,params:s,queryPadding:this.queryPadding*l},e,t,i):{}}querySourceFeatures(e,i){const r=this.latestFeatureIndex;if(!r||!r.rawTileData)return;const o=r.loadVTLayers(),a=i&&i.sourceLayer?i.sourceLayer:"",s=o._geojsonTileLayer||o[a];if(!s)return;const n=t.featureFilter(i&&i.filter),{z:l,x:c,y:h}=this.tileID.canonical,u={z:l,x:c,y:h};for(let i=0;ie)t=!1;else if(i)if(this.expirationTime{this.remove(e,o);}),i)),this.data[r].push(o),this.order.push(r),this.order.length>this.max){const e=this._getAndRemoveByKey(this.order[0]);e&&this.onRemove(e);}return this}has(e){return e.wrapped().key in this.data}getAndRemove(e){return this.has(e)?this._getAndRemoveByKey(e.wrapped().key):null}_getAndRemoveByKey(e){const t=this.data[e].shift();return t.timeout&&clearTimeout(t.timeout),0===this.data[e].length&&delete this.data[e],this.order.splice(this.order.indexOf(e),1),t.value}getByKey(e){const t=this.data[e];return t?t[0].value:null}get(e){return this.has(e)?this.data[e.wrapped().key][0].value:null}remove(e,t){if(!this.has(e))return this;const i=e.wrapped().key,r=void 0===t?0:this.data[i].indexOf(t),o=this.data[i][r];return this.data[i].splice(r,1),o.timeout&&clearTimeout(o.timeout),0===this.data[i].length&&delete this.data[i],this.onRemove(o.value),this.order.splice(this.order.indexOf(i),1),this}setMaxSize(e){for(this.max=e;this.order.length>this.max;){const e=this._getAndRemoveByKey(this.order[0]);e&&this.onRemove(e);}return this}filter(e){const t=[];for(const i in this.data)for(const r of this.data[i])e(r.value)||t.push(r);for(const e of t)this.remove(e.value.tileID,e);}}class ne{constructor(){this.state={},this.stateChanges={},this.deletedStates={};}updateState(e,i,r){const o=String(i);if(this.stateChanges[e]=this.stateChanges[e]||{},this.stateChanges[e][o]=this.stateChanges[e][o]||{},t.extend(this.stateChanges[e][o],r),null===this.deletedStates[e]){this.deletedStates[e]={};for(const t in this.state[e])t!==o&&(this.deletedStates[e][t]=null);}else if(this.deletedStates[e]&&null===this.deletedStates[e][o]){this.deletedStates[e][o]={};for(const t in this.state[e][o])r[t]||(this.deletedStates[e][o][t]=null);}else for(const t in r)this.deletedStates[e]&&this.deletedStates[e][o]&&null===this.deletedStates[e][o][t]&&delete this.deletedStates[e][o][t];}removeFeatureState(e,t,i){if(null===this.deletedStates[e])return;const r=String(t);if(this.deletedStates[e]=this.deletedStates[e]||{},i&&void 0!==t)null!==this.deletedStates[e][r]&&(this.deletedStates[e][r]=this.deletedStates[e][r]||{},this.deletedStates[e][r][i]=null);else if(void 0!==t)if(this.stateChanges[e]&&this.stateChanges[e][r])for(i in this.deletedStates[e][r]={},this.stateChanges[e][r])this.deletedStates[e][r][i]=null;else this.deletedStates[e][r]=null;else this.deletedStates[e]=null;}getState(e,i){const r=String(i),o=t.extend({},(this.state[e]||{})[r],(this.stateChanges[e]||{})[r]);if(null===this.deletedStates[e])return {};if(this.deletedStates[e]){const t=this.deletedStates[e][i];if(null===t)return {};for(const e in t)delete o[e];}return o}initializeTileState(e,t){e.setFeatureState(this.state,t);}coalesceChanges(e,i){const r={};for(const e in this.stateChanges){this.state[e]=this.state[e]||{};const i={};for(const r in this.stateChanges[e])this.state[e][r]||(this.state[e][r]={}),t.extend(this.state[e][r],this.stateChanges[e][r]),i[r]=this.state[e][r];r[e]=i;}for(const e in this.deletedStates){this.state[e]=this.state[e]||{};const i={};if(null===this.deletedStates[e])for(const t in this.state[e])i[t]={},this.state[e][t]={};else for(const t in this.deletedStates[e]){if(null===this.deletedStates[e][t])this.state[e][t]={};else for(const i of Object.keys(this.deletedStates[e][t]))delete this.state[e][t][i];i[t]=this.state[e][t];}r[e]=r[e]||{},t.extend(r[e],i);}if(this.stateChanges={},this.deletedStates={},0!==Object.keys(r).length)for(const t in e)e[t].setFeatureState(r,i);}}class le{constructor(e=0,t=0,i=0,r=0){if(isNaN(e)||e<0||isNaN(t)||t<0||isNaN(i)||i<0||isNaN(r)||r<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=e,this.bottom=t,this.left=i,this.right=r;}interpolate(e,i,r){return null!=i.top&&null!=e.top&&(this.top=t.interpolateFactory.number(e.top,i.top,r)),null!=i.bottom&&null!=e.bottom&&(this.bottom=t.interpolateFactory.number(e.bottom,i.bottom,r)),null!=i.left&&null!=e.left&&(this.left=t.interpolateFactory.number(e.left,i.left,r)),null!=i.right&&null!=e.right&&(this.right=t.interpolateFactory.number(e.right,i.right,r)),this}getCenter(e,i){const r=t.clamp((this.left+e-this.right)/2,0,e),o=t.clamp((this.top+i-this.bottom)/2,0,i);return new t.Point(r,o)}equals(e){return this.top===e.top&&this.bottom===e.bottom&&this.left===e.left&&this.right===e.right}clone(){return new le(this.top,this.bottom,this.left,this.right)}toJSON(){return {top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}const ce=85.051129;function he(e,t){if(!e.renderWorldCopies||e.lngRange)return;const i=t.lng-e.center.lng;t.lng+=i>180?-360:i<-180?360:0;}function ue(e){return Math.pow(2,e)}function de(e){return Math.log(e)/Math.LN2}function _e(e){return Math.max(0,Math.floor(e))}class pe{constructor(e,i,r,o,a,s){this._callbacks=e,this._tileSize=512,this._renderWorldCopies=void 0===s||!!s,this._minZoom=i||0,this._maxZoom=r||22,this._minPitch=null==o?0:o,this._maxPitch=null==a?60:a,this.setMaxBounds(),this._width=0,this._height=0,this._center=new t.LngLat(0,0),this._elevation=0,this._zoom=0,this._tileZoom=_e(this._zoom),this._scale=ue(this._zoom),this._bearingInRadians=0,this._fovInRadians=.6435011087932844,this._pitchInRadians=0,this._rollInRadians=0,this._unmodified=!0,this._edgeInsets=new le,this._minElevationForCurrentTile=0;}apply(e,t){this._latRange=e.latRange,this._lngRange=e.lngRange,this._width=e.width,this._height=e.height,this._center=e.center,this._elevation=e.elevation,this._minElevationForCurrentTile=e.minElevationForCurrentTile,this._zoom=e.zoom,this._tileZoom=_e(this._zoom),this._scale=ue(this._zoom),this._bearingInRadians=e.bearingInRadians,this._fovInRadians=e.fovInRadians,this._pitchInRadians=e.pitchInRadians,this._rollInRadians=e.rollInRadians,this._unmodified=e.unmodified,this._edgeInsets=new le(e.padding.top,e.padding.bottom,e.padding.left,e.padding.right),this._minZoom=e.minZoom,this._maxZoom=e.maxZoom,this._minPitch=e.minPitch,this._maxPitch=e.maxPitch,this._renderWorldCopies=e.renderWorldCopies,t&&this._constrain(),this._calcMatrices();}get pixelsToClipSpaceMatrix(){return this._pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._clipSpaceToPixelsMatrix}get minElevationForCurrentTile(){return this._minElevationForCurrentTile}setMinElevationForCurrentTile(e){this._minElevationForCurrentTile=e;}get tileSize(){return this._tileSize}get tileZoom(){return this._tileZoom}get scale(){return this._scale}get width(){return this._width}get height(){return this._height}get bearingInRadians(){return this._bearingInRadians}get lngRange(){return this._lngRange}get latRange(){return this._latRange}get pixelsToGLUnits(){return this._pixelsToGLUnits}get minZoom(){return this._minZoom}setMinZoom(e){this._minZoom!==e&&(this._minZoom=e,this.setZoom(this.getConstrained(this._center,this.zoom).zoom));}get maxZoom(){return this._maxZoom}setMaxZoom(e){this._maxZoom!==e&&(this._maxZoom=e,this.setZoom(this.getConstrained(this._center,this.zoom).zoom));}get minPitch(){return this._minPitch}setMinPitch(e){this._minPitch!==e&&(this._minPitch=e,this.setPitch(Math.max(this.pitch,e)));}get maxPitch(){return this._maxPitch}setMaxPitch(e){this._maxPitch!==e&&(this._maxPitch=e,this.setPitch(Math.min(this.pitch,e)));}get renderWorldCopies(){return this._renderWorldCopies}setRenderWorldCopies(e){void 0===e?e=!0:null===e&&(e=!1),this._renderWorldCopies=e;}get worldSize(){return this._tileSize*this._scale}get centerOffset(){return this.centerPoint._sub(this.size._div(2))}get size(){return new t.Point(this._width,this._height)}get bearing(){return this._bearingInRadians/Math.PI*180}setBearing(e){const r=t.wrap(e,-180,180)*Math.PI/180;var o,a,s,n,l,c,h,u,d;this._bearingInRadians!==r&&(this._unmodified=!1,this._bearingInRadians=r,this._calcMatrices(),this._rotationMatrix=i(),o=this._rotationMatrix,s=-this._bearingInRadians,n=(a=this._rotationMatrix)[0],l=a[1],c=a[2],h=a[3],u=Math.sin(s),d=Math.cos(s),o[0]=n*d+c*u,o[1]=l*d+h*u,o[2]=n*-u+c*d,o[3]=l*-u+h*d);}get rotationMatrix(){return this._rotationMatrix}get pitchInRadians(){return this._pitchInRadians}get pitch(){return this._pitchInRadians/Math.PI*180}setPitch(e){const i=t.clamp(e,this.minPitch,this.maxPitch)/180*Math.PI;this._pitchInRadians!==i&&(this._unmodified=!1,this._pitchInRadians=i,this._calcMatrices());}get rollInRadians(){return this._rollInRadians}get roll(){return this._rollInRadians/Math.PI*180}setRoll(e){const t=e/180*Math.PI;this._rollInRadians!==t&&(this._unmodified=!1,this._rollInRadians=t,this._calcMatrices());}get fovInRadians(){return this._fovInRadians}get fov(){return t.radiansToDegrees(this._fovInRadians)}setFov(e){e=t.clamp(e,.1,150),this.fov!==e&&(this._unmodified=!1,this._fovInRadians=t.degreesToRadians(e),this._calcMatrices());}get zoom(){return this._zoom}setZoom(e){const t=this.getConstrained(this._center,e).zoom;this._zoom!==t&&(this._unmodified=!1,this._zoom=t,this._tileZoom=Math.max(0,Math.floor(t)),this._scale=ue(t),this._constrain(),this._calcMatrices());}get center(){return this._center}setCenter(e){e.lat===this._center.lat&&e.lng===this._center.lng||(this._unmodified=!1,this._center=e,this._constrain(),this._calcMatrices());}get elevation(){return this._elevation}setElevation(e){e!==this._elevation&&(this._elevation=e,this._constrain(),this._calcMatrices());}get padding(){return this._edgeInsets.toJSON()}setPadding(e){this._edgeInsets.equals(e)||(this._unmodified=!1,this._edgeInsets.interpolate(this._edgeInsets,e,1),this._calcMatrices());}get centerPoint(){return this._edgeInsets.getCenter(this._width,this._height)}get pixelsPerMeter(){return this._pixelPerMeter}get unmodified(){return this._unmodified}isPaddingEqual(e){return this._edgeInsets.equals(e)}interpolatePadding(e,t,i){this._unmodified=!1,this._edgeInsets.interpolate(e,t,i),this._constrain(),this._calcMatrices();}resize(e,t){this._width=e,this._height=t,this._constrain(),this._calcMatrices();}getMaxBounds(){return this._latRange&&2===this._latRange.length&&this._lngRange&&2===this._lngRange.length?new V([this._lngRange[0],this._latRange[0]],[this._lngRange[1],this._latRange[1]]):null}setMaxBounds(e){e?(this._lngRange=[e.getWest(),e.getEast()],this._latRange=[e.getSouth(),e.getNorth()],this._constrain()):(this._lngRange=null,this._latRange=[-85.051129,ce]);}getConstrained(e,t){return this._callbacks.getConstrained(e,t)}getCameraQueryGeometry(e,i){if(1===i.length)return [i[0],e];{let r=e.x,o=e.y,a=e.x,s=e.y;for(const e of i)r=Math.min(r,e.x),o=Math.min(o,e.y),a=Math.max(a,e.x),s=Math.max(s,e.y);return [new t.Point(r,o),new t.Point(a,o),new t.Point(a,s),new t.Point(r,s),new t.Point(r,o)]}}_constrain(){if(!this.center||!this._width||!this._height||this._constraining)return;this._constraining=!0;const e=this._unmodified,{center:t,zoom:i}=this.getConstrained(this.center,this.zoom);this.setCenter(t),this.setZoom(i),this._unmodified=e,this._constraining=!1;}_calcMatrices(){if(this._width&&this._height){this._pixelsToGLUnits=[2/this._width,-2/this._height];let e=t.identity(new Float64Array(16));t.scale(e,e,[this._width/2,-this._height/2,1]),t.translate(e,e,[1,-1,0]),this._clipSpaceToPixelsMatrix=e,e=t.identity(new Float64Array(16)),t.scale(e,e,[1,-1,1]),t.translate(e,e,[-1,-1,0]),t.scale(e,e,[2/this._width,2/this._height,1]),this._pixelsToClipSpaceMatrix=e;}this._callbacks.calcMatrices();}}function me(e,t,i){const r=t.intersectsFrustum(e);if(!i)return r;const o=t.intersectsPlane(i);return 0===r||0===o?0:2===r&&2===o?2:1}function fe(e,i,r,o,a){let s=e;const n=Math.atan(i/r);return s=e+de(o/Math.hypot(i,r)/Math.max(.5,Math.cos(t.degreesToRadians(a/2)))),s+=1*de(Math.cos(n))/2,s+=t.clamp(e-s,-0,0),s}function ge(e,t){const i=(t.roundZoom?Math.round:Math.floor)(e.zoom+de(e.tileSize/t.tileSize));return Math.max(0,i)}function ve(e,i){const r=e.getCameraFrustum(),o=e.getClippingPlane(),a=e.screenPointToMercatorCoordinate(e.getCameraPoint()),s=t.MercatorCoordinate.fromLngLat(e.center,e.elevation);a.z=s.z+Math.cos(e.pitchInRadians)*e.cameraToCenterDistance/e.worldSize;const n=e.getCoveringTilesDetailsProvider(),l=n.allowVariableZoom(e,i),c=ge(e,i),h=i.minzoom||0,u=void 0!==i.maxzoom?i.maxzoom:e.maxZoom,d=Math.min(Math.max(0,c),u),_=Math.pow(2,d),p=[_*a.x,_*a.y,0],m=[_*s.x,_*s.y,0],f=Math.hypot(s.x-a.x,s.y-a.y),g=Math.abs(s.z-a.z),v=Math.hypot(f,g),y=e=>({zoom:0,x:0,y:0,wrap:e,fullyVisible:!1}),x=[],b=[];if(e.renderWorldCopies)for(let e=1;e<=3;e++)x.push(y(-e)),x.push(y(e));for(x.push(y(0));x.length>0;){const _=x.pop(),f=_.x,y=_.y;let w=_.fullyVisible;const T={x:f,y:y,z:_.zoom},E=n.getTileAABB(T,_.wrap,e.elevation,i);if(!w){const e=me(r,E,o);if(0===e)continue;w=2===e;}const P=n.distanceToTile2d(a.x,a.y,T,E);let I=c;l&&(I=(i.calculateTileZoom||fe)(e.zoom+de(e.tileSize/i.tileSize),P,g,v,e.fov)),I=(i.roundZoom?Math.round:Math.floor)(I),I=Math.max(0,I);const C=Math.min(I,u);if(_.wrap=n.getWrap(s,T,_.wrap),_.zoom>=C){if(_.zoom>1),wrap:_.wrap,fullyVisible:w});}return b.sort(((e,t)=>e.distanceSq-t.distanceSq)).map((e=>e.tileID))}class ye extends t.Evented{constructor(e,t,i){super(),this.id=e,this.dispatcher=i,this.on("data",(e=>this._dataHandler(e))),this.on("dataloading",(()=>{this._sourceErrored=!1;})),this.on("error",(()=>{this._sourceErrored=this._source.loaded();})),this._source=((e,t,i,r)=>{const o=new(ee(t.type))(e,t,i,r);if(o.id!==e)throw new Error(`Expected Source id to be ${e} instead of ${o.id}`);return o})(e,t,i,this),this._tiles={},this._cache=new se(0,(e=>this._unloadTile(e))),this._timers={},this._cacheTimers={},this._maxTileCacheSize=null,this._maxTileCacheZoomLevels=null,this._loadedParentTiles={},this._coveredTiles={},this._state=new ne,this._didEmitContent=!1,this._updated=!1;}onAdd(e){this.map=e,this._maxTileCacheSize=e?e._maxTileCacheSize:null,this._maxTileCacheZoomLevels=e?e._maxTileCacheZoomLevels:null,this._source&&this._source.onAdd&&this._source.onAdd(e);}onRemove(e){this.clearTiles(),this._source&&this._source.onRemove&&this._source.onRemove(e);}loaded(){if(this._sourceErrored)return !0;if(!this._sourceLoaded)return !1;if(!this._source.loaded())return !1;if(!(void 0===this.used&&void 0===this.usedForTerrain||this.used||this.usedForTerrain))return !0;if(!this._updated)return !1;for(const e in this._tiles){const t=this._tiles[e];if("loaded"!==t.state&&"errored"!==t.state)return !1}return !0}getSource(){return this._source}pause(){this._paused=!0;}resume(){if(!this._paused)return;const e=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,e&&this.reload(),this.transform&&this.update(this.transform,this.terrain);}_loadTile(e,i,r){return t.__awaiter(this,void 0,void 0,(function*(){try{yield this._source.loadTile(e),this._tileLoaded(e,i,r);}catch(i){e.state="errored",404!==i.status?this._source.fire(new t.ErrorEvent(i,{tile:e})):this.update(this.transform,this.terrain);}}))}_unloadTile(e){this._source.unloadTile&&this._source.unloadTile(e);}_abortTile(e){this._source.abortTile&&this._source.abortTile(e),this._source.fire(new t.Event("dataabort",{tile:e,coord:e.tileID,dataType:"source"}));}serialize(){return this._source.serialize()}prepare(e){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null);for(const t in this._tiles){const i=this._tiles[t];i.upload(e),i.prepare(this.map.style.imageManager);}}getIds(){return Object.values(this._tiles).map((e=>e.tileID)).sort(xe).map((e=>e.key))}getRenderableIds(e){const i=[];for(const t in this._tiles)this._isIdRenderable(t,e)&&i.push(this._tiles[t]);return e?i.sort(((e,i)=>{const r=e.tileID,o=i.tileID,a=new t.Point(r.canonical.x,r.canonical.y)._rotate(-this.transform.bearingInRadians),s=new t.Point(o.canonical.x,o.canonical.y)._rotate(-this.transform.bearingInRadians);return r.overscaledZ-o.overscaledZ||s.y-a.y||s.x-a.x})).map((e=>e.tileID.key)):i.map((e=>e.tileID)).sort(xe).map((e=>e.key))}hasRenderableParent(e){const t=this.findLoadedParent(e,0);return !!t&&this._isIdRenderable(t.tileID.key)}_isIdRenderable(e,t){return this._tiles[e]&&this._tiles[e].hasData()&&!this._coveredTiles[e]&&(t||!this._tiles[e].holdingForFade())}reload(e){if(this._paused)this._shouldReloadOnResume=!0;else {this._cache.reset();for(const t in this._tiles)(e||"errored"!==this._tiles[t].state)&&this._reloadTile(t,"reloading");}}_reloadTile(e,i){return t.__awaiter(this,void 0,void 0,(function*(){const t=this._tiles[e];t&&("loading"!==t.state&&(t.state=i),yield this._loadTile(t,e,i));}))}_tileLoaded(e,i,r){e.timeAdded=f.now(),"expired"===r&&(e.refreshedUponExpiration=!0),this._setTileReloadTimer(i,e),"raster-dem"===this.getSource().type&&e.dem&&this._backfillDEM(e),this._state.initializeTileState(e,this.map?this.map.painter:null),e.aborted||this._source.fire(new t.Event("data",{dataType:"source",tile:e,coord:e.tileID}));}_backfillDEM(e){const t=this.getRenderableIds();for(let r=0;r1||(Math.abs(i)>1&&(1===Math.abs(i+o)?i+=o:1===Math.abs(i-o)&&(i-=o)),t.dem&&e.dem&&(e.dem.backfillBorder(t.dem,i,r),e.neighboringTiles&&e.neighboringTiles[a]&&(e.neighboringTiles[a].backfilled=!0)));}}getTile(e){return this.getTileByID(e.key)}getTileByID(e){return this._tiles[e]}_retainLoadedChildren(e,t,i,r){for(const o in this._tiles){let a=this._tiles[o];if(r[o]||!a.hasData()||a.tileID.overscaledZ<=t||a.tileID.overscaledZ>i)continue;let s=a.tileID;for(;a&&a.tileID.overscaledZ>t+1;){const e=a.tileID.scaledTo(a.tileID.overscaledZ-1);a=this._tiles[e.key],a&&a.hasData()&&(s=e);}let n=s;for(;n.overscaledZ>t;)if(n=n.scaledTo(n.overscaledZ-1),e[n.key]){r[s.key]=s;break}}}findLoadedParent(e,t){if(e.key in this._loadedParentTiles){const i=this._loadedParentTiles[e.key];return i&&i.tileID.overscaledZ>=t?i:null}for(let i=e.overscaledZ-1;i>=t;i--){const t=e.scaledTo(i),r=this._getLoadedTile(t);if(r)return r}}findLoadedSibling(e){return this._getLoadedTile(e)}_getLoadedTile(e){const t=this._tiles[e.key];return t&&t.hasData()?t:this._cache.getByKey(e.wrapped().key)}updateCacheSize(e){const i=Math.ceil(e.width/this._source.tileSize)+1,r=Math.ceil(e.height/this._source.tileSize)+1,o=Math.floor(i*r*(null===this._maxTileCacheZoomLevels?t.config.MAX_TILE_CACHE_ZOOM_LEVELS:this._maxTileCacheZoomLevels)),a="number"==typeof this._maxTileCacheSize?Math.min(this._maxTileCacheSize,o):o;this._cache.setMaxSize(a);}handleWrapJump(e){const t=Math.round((e-(void 0===this._prevLng?e:this._prevLng))/360);if(this._prevLng=e,t){const e={};for(const i in this._tiles){const r=this._tiles[i];r.tileID=r.tileID.unwrapTo(r.tileID.wrap+t),e[r.tileID.key]=r;}this._tiles=e;for(const e in this._timers)clearTimeout(this._timers[e]),delete this._timers[e];for(const e in this._tiles)this._setTileReloadTimer(e,this._tiles[e]);}}_updateCoveredAndRetainedTiles(e,t,i,r,o,a){const s={},n={},l=Object.keys(e),c=f.now();for(const i of l){const r=e[i],o=this._tiles[i];if(!o||0!==o.fadeEndTime&&o.fadeEndTime<=c)continue;const a=this.findLoadedParent(r,t),l=this.findLoadedSibling(r),h=a||l||null;h&&(this._addTile(h.tileID),s[h.tileID.key]=h.tileID),n[i]=r;}this._retainLoadedChildren(n,r,i,e);for(const t in s)e[t]||(this._coveredTiles[t]=!0,e[t]=s[t]);if(a){const t={},i={};for(const e of o)this._tiles[e.key].hasData()?t[e.key]=e:i[e.key]=e;for(const r in i){const o=i[r].children(this._source.maxzoom);this._tiles[o[0].key]&&this._tiles[o[1].key]&&this._tiles[o[2].key]&&this._tiles[o[3].key]&&(t[o[0].key]=e[o[0].key]=o[0],t[o[1].key]=e[o[1].key]=o[1],t[o[2].key]=e[o[2].key]=o[2],t[o[3].key]=e[o[3].key]=o[3],delete i[r]);}for(const r in i){const o=i[r],a=this.findLoadedParent(o,this._source.minzoom),s=this.findLoadedSibling(o),n=a||s||null;if(n){t[n.tileID.key]=e[n.tileID.key]=n.tileID;for(const e in t)t[e].isChildOf(n.tileID)&&delete t[e];}}for(const e in this._tiles)t[e]||(this._coveredTiles[e]=!0);}}update(e,i){if(!this._sourceLoaded||this._paused)return;let r;this.transform=e,this.terrain=i,this.updateCacheSize(e),this.handleWrapJump(this.transform.center.lng),this._coveredTiles={},this.used||this.usedForTerrain?this._source.tileID?r=e.getVisibleUnwrappedCoordinates(this._source.tileID).map((e=>new t.OverscaledTileID(e.canonical.z,e.wrap,e.canonical.z,e.canonical.x,e.canonical.y))):(r=ve(e,{tileSize:this.usedForTerrain?this.tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:!this.usedForTerrain&&this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled,terrain:i,calculateTileZoom:this._source.calculateTileZoom}),this._source.hasTile&&(r=r.filter((e=>this._source.hasTile(e))))):r=[];const o=ge(e,this._source),a=Math.max(o-ye.maxOverzooming,this._source.minzoom),s=Math.max(o+ye.maxUnderzooming,this._source.minzoom);if(this.usedForTerrain){const e={};for(const t of r)if(t.canonical.z>this._source.minzoom){const i=t.scaledTo(t.canonical.z-1);e[i.key]=i;const r=t.scaledTo(Math.max(this._source.minzoom,Math.min(t.canonical.z,5)));e[r.key]=r;}r=r.concat(Object.values(e));}const n=0===r.length&&!this._updated&&this._didEmitContent;this._updated=!0,n&&this.fire(new t.Event("data",{sourceDataType:"idle",dataType:"source",sourceId:this.id}));const l=this._updateRetainedTiles(r,o);be(this._source.type)&&this._updateCoveredAndRetainedTiles(l,a,s,o,r,i);for(const e in l)this._tiles[e].clearFadeHold();const c=t.keysDifference(this._tiles,l);for(const e of c){const t=this._tiles[e];t.hasSymbolBuckets&&!t.holdingForFade()?t.setHoldDuration(this.map._fadeDuration):t.hasSymbolBuckets&&!t.symbolFadeFinished()||this._removeTile(e);}this._updateLoadedParentTileCache(),this._updateLoadedSiblingTileCache();}releaseSymbolFadeTiles(){for(const e in this._tiles)this._tiles[e].holdingForFade()&&this._removeTile(e);}_updateRetainedTiles(e,t){var i;const r={},o={},a=Math.max(t-ye.maxOverzooming,this._source.minzoom),s=Math.max(t+ye.maxUnderzooming,this._source.minzoom),n={};for(const i of e){const e=this._addTile(i);r[i.key]=i,e.hasData()||tthis._source.maxzoom){const e=s.children(this._source.maxzoom)[0],t=this.getTile(e);if(t&&t.hasData()){r[e.key]=e;continue}}else {const e=s.children(this._source.maxzoom);if(r[e[0].key]&&r[e[1].key]&&r[e[2].key]&&r[e[3].key])continue}let n=e.wasRequested();for(let t=s.overscaledZ-1;t>=a;--t){const a=s.scaledTo(t);if(o[a.key])break;if(o[a.key]=!0,e=this.getTile(a),!e&&n&&(e=this._addTile(a)),e){const t=e.hasData();if((t||!(null===(i=this.map)||void 0===i?void 0:i.cancelPendingTileRequestsWhileZooming)||n)&&(r[a.key]=a),n=e.wasRequested(),t)break}}}return r}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const e in this._tiles){const t=[];let i,r=this._tiles[e].tileID;for(;r.overscaledZ>0;){if(r.key in this._loadedParentTiles){i=this._loadedParentTiles[r.key];break}t.push(r.key);const e=r.scaledTo(r.overscaledZ-1);if(i=this._getLoadedTile(e),i)break;r=e;}for(const e of t)this._loadedParentTiles[e]=i;}}_updateLoadedSiblingTileCache(){this._loadedSiblingTiles={};for(const e in this._tiles){const t=this._tiles[e].tileID,i=this._getLoadedTile(t);this._loadedSiblingTiles[t.key]=i;}}_addTile(e){let i=this._tiles[e.key];if(i)return i;i=this._cache.getAndRemove(e),i&&(this._setTileReloadTimer(e.key,i),i.tileID=e,this._state.initializeTileState(i,this.map?this.map.painter:null),this._cacheTimers[e.key]&&(clearTimeout(this._cacheTimers[e.key]),delete this._cacheTimers[e.key],this._setTileReloadTimer(e.key,i)));const r=i;return i||(i=new ae(e,this._source.tileSize*e.overscaleFactor()),this._loadTile(i,e.key,i.state)),i.uses++,this._tiles[e.key]=i,r||this._source.fire(new t.Event("dataloading",{tile:i,coord:i.tileID,dataType:"source"})),i}_setTileReloadTimer(e,t){e in this._timers&&(clearTimeout(this._timers[e]),delete this._timers[e]);const i=t.getExpiryTimeout();i&&(this._timers[e]=setTimeout((()=>{this._reloadTile(e,"expired"),delete this._timers[e];}),i));}_removeTile(e){const t=this._tiles[e];t&&(t.uses--,delete this._tiles[e],this._timers[e]&&(clearTimeout(this._timers[e]),delete this._timers[e]),t.uses>0||(t.hasData()&&"reloading"!==t.state?this._cache.add(t.tileID,t,t.getExpiryTimeout()):(t.aborted=!0,this._abortTile(t),this._unloadTile(t))));}_dataHandler(e){const t=e.sourceDataType;"source"===e.dataType&&"metadata"===t&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&"source"===e.dataType&&"content"===t&&(this.reload(e.sourceDataChanged),this.transform&&this.update(this.transform,this.terrain),this._didEmitContent=!0);}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(const e in this._tiles)this._removeTile(e);this._cache.reset();}tilesIn(e,i,r){const o=[],a=this.transform;if(!a)return o;const s=r?a.getCameraQueryGeometry(e):e,n=e.map((e=>a.screenPointToMercatorCoordinate(e,this.terrain))),l=s.map((e=>a.screenPointToMercatorCoordinate(e,this.terrain))),c=this.getIds();let h=1/0,u=1/0,d=-1/0,_=-1/0;for(const e of l)h=Math.min(h,e.x),u=Math.min(u,e.y),d=Math.max(d,e.x),_=Math.max(_,e.y);for(let e=0;e=0&&f[1].y+m>=0){const e=n.map((e=>s.getTilePoint(e))),t=l.map((e=>s.getTilePoint(e)));o.push({tile:r,tileID:s,queryGeometry:e,cameraQueryGeometry:t,scale:p});}}return o}getVisibleCoordinates(e){const t=this.getRenderableIds(e).map((e=>this._tiles[e].tileID));return this.transform&&this.transform.precacheTiles(t),t}hasTransition(){if(this._source.hasTransition())return !0;if(be(this._source.type)){const e=f.now();for(const t in this._tiles)if(this._tiles[t].fadeEndTime>=e)return !0}return !1}setFeatureState(e,t,i){this._state.updateState(e=e||"_geojsonTileLayer",t,i);}removeFeatureState(e,t,i){this._state.removeFeatureState(e=e||"_geojsonTileLayer",t,i);}getFeatureState(e,t){return this._state.getState(e=e||"_geojsonTileLayer",t)}setDependencies(e,t,i){const r=this._tiles[e];r&&r.setDependencies(t,i);}reloadTilesForDependencies(e,t){for(const i in this._tiles)this._tiles[i].hasDependency(e,t)&&this._reloadTile(i,"reloading");this._cache.filter((i=>!i.hasDependency(e,t)));}}function xe(e,t){const i=Math.abs(2*e.wrap)-+(e.wrap<0),r=Math.abs(2*t.wrap)-+(t.wrap<0);return e.overscaledZ-t.overscaledZ||r-i||t.canonical.y-e.canonical.y||t.canonical.x-e.canonical.x}function be(e){return "raster"===e||"image"===e||"video"===e}ye.maxOverzooming=10,ye.maxUnderzooming=3;class we{constructor(e,t){this.reset(e,t);}reset(e,t){this.points=e||[],this._distances=[0];for(let e=1;e0?(o-s)/n:0;return this.points[a].mult(1-l).add(this.points[i].mult(l))}}function Te(e,t){let i=!0;return "always"===e||"never"!==e&&"never"!==t||(i=!1),i}class Ee{constructor(e,t,i){const r=this.boxCells=[],o=this.circleCells=[];this.xCellCount=Math.ceil(e/i),this.yCellCount=Math.ceil(t/i);for(let e=0;ethis.width||r<0||t>this.height)return [];const n=[];if(e<=0&&t<=0&&this.width<=i&&this.height<=r){if(o)return [{key:null,x1:e,y1:t,x2:i,y2:r}];for(let e=0;e0}hitTestCircle(e,t,i,r,o){const a=e-i,s=e+i,n=t-i,l=t+i;if(s<0||a>this.width||l<0||n>this.height)return !1;const c=[];return this._forEachCell(a,n,s,l,this._queryCellCircle,c,{hitTest:!0,overlapMode:r,circle:{x:e,y:t,radius:i},seenUids:{box:{},circle:{}}},o),c.length>0}_queryCell(e,t,i,r,o,a,s,n){const{seenUids:l,hitTest:c,overlapMode:h}=s,u=this.boxCells[o];if(null!==u){const o=this.bboxes;for(const s of u)if(!l.box[s]){l.box[s]=!0;const u=4*s,d=this.boxKeys[s];if(e<=o[u+2]&&t<=o[u+3]&&i>=o[u+0]&&r>=o[u+1]&&(!n||n(d))&&(!c||!Te(h,d.overlapMode))&&(a.push({key:d,x1:o[u],y1:o[u+1],x2:o[u+2],y2:o[u+3]}),c))return !0}}const d=this.circleCells[o];if(null!==d){const o=this.circles;for(const s of d)if(!l.circle[s]){l.circle[s]=!0;const u=3*s,d=this.circleKeys[s];if(this._circleAndRectCollide(o[u],o[u+1],o[u+2],e,t,i,r)&&(!n||n(d))&&(!c||!Te(h,d.overlapMode))){const e=o[u],t=o[u+1],i=o[u+2];if(a.push({key:d,x1:e-i,y1:t-i,x2:e+i,y2:t+i}),c)return !0}}}return !1}_queryCellCircle(e,t,i,r,o,a,s,n){const{circle:l,seenUids:c,overlapMode:h}=s,u=this.boxCells[o];if(null!==u){const e=this.bboxes;for(const t of u)if(!c.box[t]){c.box[t]=!0;const i=4*t,r=this.boxKeys[t];if(this._circleAndRectCollide(l.x,l.y,l.radius,e[i+0],e[i+1],e[i+2],e[i+3])&&(!n||n(r))&&!Te(h,r.overlapMode))return a.push(!0),!0}}const d=this.circleCells[o];if(null!==d){const e=this.circles;for(const t of d)if(!c.circle[t]){c.circle[t]=!0;const i=3*t,r=this.circleKeys[t];if(this._circlesCollide(e[i],e[i+1],e[i+2],l.x,l.y,l.radius)&&(!n||n(r))&&!Te(h,r.overlapMode))return a.push(!0),!0}}}_forEachCell(e,t,i,r,o,a,s,n){const l=this._convertToXCellCoord(e),c=this._convertToYCellCoord(t),h=this._convertToXCellCoord(i),u=this._convertToYCellCoord(r);for(let d=l;d<=h;d++)for(let l=c;l<=u;l++)if(o.call(this,e,t,i,r,this.xCellCount*l+d,a,s,n))return}_convertToXCellCoord(e){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(e*this.xScale)))}_convertToYCellCoord(e){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(e*this.yScale)))}_circlesCollide(e,t,i,r,o,a){const s=r-e,n=o-t,l=i+a;return l*l>s*s+n*n}_circleAndRectCollide(e,t,i,r,o,a,s){const n=(a-r)/2,l=Math.abs(e-(r+n));if(l>n+i)return !1;const c=(s-o)/2,h=Math.abs(t-(o+c));if(h>c+i)return !1;if(l<=n||h<=c)return !0;const u=l-n,d=h-c;return u*u+d*d<=i*i}}function Pe(e,r,o){const a=t.create();if(!e){const{vecSouth:e,vecEast:t}=Ce(r),o=i();o[0]=t[0],o[1]=t[1],o[2]=e[0],o[3]=e[1],s=o,(d=(l=(n=o)[0])*(u=n[3])-(h=n[2])*(c=n[1]))&&(s[0]=u*(d=1/d),s[1]=-c*d,s[2]=-h*d,s[3]=l*d),a[0]=o[0],a[1]=o[1],a[4]=o[2],a[5]=o[3];}var s,n,l,c,h,u,d;return t.scale(a,a,[1/o,1/o,1]),a}function Ie(e,i,r,o){if(e){const e=t.create();if(!i){const{vecSouth:t,vecEast:i}=Ce(r);e[0]=i[0],e[1]=i[1],e[4]=t[0],e[5]=t[1];}return t.scale(e,e,[o,o,1]),e}return r.pixelsToClipSpaceMatrix}function Ce(e){const i=Math.cos(e.rollInRadians),r=Math.sin(e.rollInRadians),o=Math.cos(e.pitchInRadians),a=Math.cos(e.bearingInRadians),s=Math.sin(e.bearingInRadians),n=t.create$1();n[0]=-a*o*r-s*i,n[1]=-s*o*r+a*i;const l=t.length(n);l<1e-9?t.zero(n):t.scale$1(n,n,1/l);const c=t.create$1();c[0]=a*o*i-s*r,c[1]=s*o*i+a*r;const h=t.length(c);return h<1e-9?t.zero(c):t.scale$1(c,c,1/h),{vecEast:c,vecSouth:n}}function Me(e,i,r,o){let a;o?(a=[e,i,o(e,i),1],t.transformMat4(a,a,r)):(a=[e,i,0,1],qe(a,a,r));const s=a[3];return {point:new t.Point(a[0]/s,a[1]/s),signedDistanceFromCamera:s,isOccluded:!1}}function Se(e,t){return .5+e/t*.5}function Re(e,t){return e.x>=-t[0]&&e.x<=t[0]&&e.y>=-t[1]&&e.y<=t[1]}function De(e,i,r,o,a,s,n,l,c,h,u,d,_){const p=r?e.textSizeData:e.iconSizeData,m=t.evaluateSizeForZoom(p,i.transform.zoom),f=[256/i.width*2+1,256/i.height*2+1],g=r?e.text.dynamicLayoutVertexArray:e.icon.dynamicLayoutVertexArray;g.clear();const v=e.lineVertexArray,y=r?e.text.placedSymbolArray:e.icon.placedSymbolArray,x=i.transform.width/i.transform.height;let b=!1;for(let r=0;rMath.abs(r.x-i.x)*o?{useVertical:!0}:(e===t.WritingMode.vertical?i.yr.x)?{needsFlipping:!0}:null}function Ae(e){const{projectionContext:i,pitchedLabelPlaneMatrixInverse:r,symbol:o,fontSize:a,flip:s,keepUpright:n,glyphOffsetArray:l,dynamicLayoutVertexArray:c,aspectRatio:h,rotateToLine:u}=e,d=a/24,_=o.lineOffsetX*d,p=o.lineOffsetY*d;let m;if(o.numGlyphs>1){const e=o.glyphStartIndex+o.numGlyphs,t=o.lineStartIndex,a=o.lineStartIndex+o.lineLength,c=ze(d,l,_,p,s,o,u,i);if(!c)return {notEnoughRoom:!0};const f=Oe(c.first.point.x,c.first.point.y,i,r),g=Oe(c.last.point.x,c.last.point.y,i,r);if(n&&!s){const e=Le(o.writingMode,f,g,h);if(e)return e}m=[c.first];for(let r=o.glyphStartIndex+1;r0?n.point:ke(i.tileAnchorPoint,s,e,1,i),c=Oe(e.x,e.y,i,r),u=Oe(l.x,l.y,i,r),d=Le(o.writingMode,c,u,h);if(d)return d}const e=Ge(d*l.getoffsetX(o.glyphStartIndex),_,p,s,o.segment,o.lineStartIndex,o.lineStartIndex+o.lineLength,i,u);if(!e||i.projectionCache.anyProjectionOccluded)return {notEnoughRoom:!0};m=[e];}for(const e of m)t.addDynamicAttributes(c,e.point,e.angle);return {}}function ke(e,t,i,r,o){const a=e.add(e.sub(t)._unit()),s=Be(a.x,a.y,o).point,n=i.sub(s);return i.add(n._mult(r/n.mag()))}function Fe(e,i,r){const o=i.projectionCache;if(o.projections[e])return o.projections[e];const a=new t.Point(i.lineVertexArray.getx(e),i.lineVertexArray.gety(e)),s=Be(a.x,a.y,i);if(s.signedDistanceFromCamera>0)return o.projections[e]=s.point,o.anyProjectionOccluded=o.anyProjectionOccluded||s.isOccluded,s.point;const n=e-r.direction;return ke(0===r.distanceFromAnchor?i.tileAnchorPoint:new t.Point(i.lineVertexArray.getx(n),i.lineVertexArray.gety(n)),a,r.previousVertex,r.absOffsetX-r.distanceFromAnchor+1,i)}function Be(e,t,i){const r=e+i.translation[0],o=t+i.translation[1];let a;return i.pitchWithMap?(a=Me(r,o,i.pitchedLabelPlaneMatrix,i.getElevation),a.isOccluded=!1):(a=i.transform.projectTileCoordinates(r,o,i.unwrappedTileID,i.getElevation),a.point.x=(.5*a.point.x+.5)*i.width,a.point.y=(.5*-a.point.y+.5)*i.height),a}function Oe(e,i,r,o){if(r.pitchWithMap){const a=[e,i,0,1];return t.transformMat4(a,a,o),r.transform.projectTileCoordinates(a[0]/a[3],a[1]/a[3],r.unwrappedTileID,r.getElevation).point}return {x:e/r.width*2-1,y:i/r.height*2-1}}function Ue(e,t,i){return i.transform.projectTileCoordinates(e,t,i.unwrappedTileID,i.getElevation)}function je(e,t,i){return e._unit()._perp()._mult(t*i)}function Ne(e,i,r,o,a,s,n,l,c){if(l.projectionCache.offsets[e])return l.projectionCache.offsets[e];const h=r.add(i);if(e+c.direction=a)return l.projectionCache.offsets[e]=h,h;const u=Fe(e+c.direction,l,c),d=je(u.sub(r),n,c.direction),_=r.add(d),p=u.add(d);return l.projectionCache.offsets[e]=t.findLineIntersection(s,h,_,p)||h,l.projectionCache.offsets[e]}function Ge(e,t,i,r,o,a,s,n,l){const c=r?e-t:e+t;let h=c>0?1:-1,u=0;r&&(h*=-1,u=Math.PI),h<0&&(u+=Math.PI);let d,_=h>0?a+o:a+o+1;n.projectionCache.cachedAnchorPoint?d=n.projectionCache.cachedAnchorPoint:(d=Be(n.tileAnchorPoint.x,n.tileAnchorPoint.y,n).point,n.projectionCache.cachedAnchorPoint=d);let p,m,f=d,g=d,v=0,y=0;const x=Math.abs(c),b=[];let w;for(;v+y<=x;){if(_+=h,_=s)return null;v+=y,g=f,m=p;const e={absOffsetX:x,direction:h,distanceFromAnchor:v,previousVertex:g};if(f=Fe(_,n,e),0===i)b.push(g),w=f.sub(g);else {let t;const r=f.sub(g);t=0===r.mag()?je(Fe(_+h,n,e).sub(f),i,h):je(r,i,h),m||(m=g.add(t)),p=Ne(_,t,f,a,s,m,i,n,e),b.push(m),w=p.sub(m);}y=w.mag();}const T=w._mult((x-v)/y)._add(m||g),E=u+Math.atan2(f.y-g.y,f.x-g.x);return b.push(T),{point:T,angle:l?E:0,path:b}}const Ze=new Float32Array([-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0]);function Ve(e,t){for(let i=0;i=1;e--)_.push(s.path[e]);for(let e=1;ee.signedDistanceFromCamera<=0))?[]:e.map((e=>e.point));}let f=[];if(_.length>0){const e=_[0].clone(),i=_[0].clone();for(let t=1;t<_.length;t++)e.x=Math.min(e.x,_[t].x),e.y=Math.min(e.y,_[t].y),i.x=Math.max(i.x,_[t].x),i.y=Math.max(i.y,_[t].y);f=e.x>=r.x&&i.x<=o.x&&e.y>=r.y&&i.y<=o.y?[_]:i.xo.x||i.yo.y?[]:t.clipLine([_],r.x,r.y,o.x,o.y);}for(const t of f){a.reset(t,.25*i);let r=0;r=a.length<=.5*i?1:Math.ceil(a.paddedLength/p)+1;for(let t=0;t{const t=Me(e.x,e.y,r,i.getElevation),o=i.transform.projectTileCoordinates(t.point.x,t.point.y,i.unwrappedTileID,i.getElevation);return o.point.x=(.5*o.point.x+.5)*i.width,o.point.y=(.5*-o.point.y+.5)*i.height,o}))}(e,i);return function(e){let t=0,i=0,r=0,o=0;for(let a=0;ai&&(i=o,t=r));return e.slice(t,t+i)}(r)}queryRenderedSymbols(e){if(0===e.length||0===this.grid.keysLength()&&0===this.ignoredGrid.keysLength())return {};const i=[];let r=1/0,o=1/0,a=-1/0,s=-1/0;for(const n of e){const e=new t.Point(n.x+We,n.y+We);r=Math.min(r,e.x),o=Math.min(o,e.y),a=Math.max(a,e.x),s=Math.max(s,e.y),i.push(e);}const n=this.grid.query(r,o,a,s).concat(this.ignoredGrid.query(r,o,a,s)),l={},c={};for(const e of n){const r=e.key;if(void 0===l[r.bucketInstanceId]&&(l[r.bucketInstanceId]={}),l[r.bucketInstanceId][r.featureIndex])continue;const o=[new t.Point(e.x1,e.y1),new t.Point(e.x2,e.y1),new t.Point(e.x2,e.y2),new t.Point(e.x1,e.y2)];t.polygonIntersectsPolygon(i,o)&&(l[r.bucketInstanceId][r.featureIndex]=!0,void 0===c[r.bucketInstanceId]&&(c[r.bucketInstanceId]=[]),c[r.bucketInstanceId].push(r.featureIndex));}return c}insertCollisionBox(e,t,i,r,o,a){(i?this.ignoredGrid:this.grid).insert({bucketInstanceId:r,featureIndex:o,collisionGroupID:a,overlapMode:t},e[0],e[1],e[2],e[3]);}insertCollisionCircles(e,t,i,r,o,a){const s=i?this.ignoredGrid:this.grid,n={bucketInstanceId:r,featureIndex:o,collisionGroupID:a,overlapMode:t};for(let t=0;t=this.screenRightBoundary||rthis.screenBottomBoundary}isInsideGrid(e,t,i,r){return i>=0&&e=0&&tthis.projectAndGetPerspectiveRatio(e.x,e.y,o,c,u)));S=e.some((e=>!e.isOccluded)),M=e.map((e=>new t.Point(e.x,e.y)));}else S=!0;return {box:t.getAABB(M),allPointsOccluded:!S}}}class $e{constructor(e,t,i,r){this.opacity=e?Math.max(0,Math.min(1,e.opacity+(e.placed?t:-t))):r&&i?1:0,this.placed=i;}isHidden(){return 0===this.opacity&&!this.placed}}class He{constructor(e,t,i,r,o){this.text=new $e(e?e.text:null,t,i,o),this.icon=new $e(e?e.icon:null,t,r,o);}isHidden(){return this.text.isHidden()&&this.icon.isHidden()}}class Ke{constructor(e,t,i){this.text=e,this.icon=t,this.skipFade=i;}}class Ye{constructor(e,t,i,r,o){this.bucketInstanceId=e,this.featureIndex=t,this.sourceLayerIndex=i,this.bucketIndex=r,this.tileID=o;}}class Je{constructor(e){this.crossSourceCollisions=e,this.maxGroupID=0,this.collisionGroups={};}get(e){if(this.crossSourceCollisions)return {ID:0,predicate:null};if(!this.collisionGroups[e]){const t=++this.maxGroupID;this.collisionGroups[e]={ID:t,predicate:e=>e.collisionGroupID===t};}return this.collisionGroups[e]}}function Qe(e,i,r,o,a){const{horizontalAlign:s,verticalAlign:n}=t.getAnchorAlignment(e);return new t.Point(-(s-.5)*i+o[0]*a,-(n-.5)*r+o[1]*a)}class et{constructor(e,t,i,r,o){this.transform=e.clone(),this.terrain=t,this.collisionIndex=new Xe(this.transform),this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=i,this.retainedQueryData={},this.collisionGroups=new Je(r),this.collisionCircleArrays={},this.collisionBoxArrays=new Map,this.prevPlacement=o,o&&(o.prevPlacement=void 0),this.placedOrientations={};}_getTerrainElevationFunc(e){const t=this.terrain;return t?(i,r)=>t.getElevation(e,i,r):null}getBucketParts(e,i,r,o){const a=r.getBucket(i),s=r.latestFeatureIndex;if(!a||!s||i.id!==a.layerIds[0])return;const n=r.collisionBoxArray,l=a.layers[0].layout,c=a.layers[0].paint,h=Math.pow(2,this.transform.zoom-r.tileID.overscaledZ),u=r.tileSize/t.EXTENT,d=r.tileID.toUnwrapped(),_="map"===l.get("text-rotation-alignment"),p=t.pixelsToTileUnits(r,1,this.transform.zoom),m=t.translatePosition(this.collisionIndex.transform,r,c.get("text-translate"),c.get("text-translate-anchor")),f=t.translatePosition(this.collisionIndex.transform,r,c.get("icon-translate"),c.get("icon-translate-anchor")),g=Pe(_,this.transform,p);this.retainedQueryData[a.bucketInstanceId]=new Ye(a.bucketInstanceId,s,a.sourceLayerIndex,a.index,r.tileID);const v={bucket:a,layout:l,translationText:m,translationIcon:f,unwrappedTileID:d,pitchedLabelPlaneMatrix:g,scale:h,textPixelRatio:u,holdingForFade:r.holdingForFade(),collisionBoxArray:n,partiallyEvaluatedTextSize:t.evaluateSizeForZoom(a.textSizeData,this.transform.zoom),collisionGroup:this.collisionGroups.get(a.sourceID)};if(o)for(const t of a.sortKeyRanges){const{sortKey:i,symbolInstanceStart:r,symbolInstanceEnd:o}=t;e.push({sortKey:i,symbolInstanceStart:r,symbolInstanceEnd:o,parameters:v});}else e.push({symbolInstanceStart:0,symbolInstanceEnd:a.symbolInstances.length,parameters:v});}attemptAnchorPlacement(e,i,r,o,a,s,n,l,c,h,u,d,_,p,m,f,g,v,y,x){const b=t.TextAnchorEnum[e.textAnchor],w=[e.textOffset0,e.textOffset1],T=Qe(b,r,o,w,a),E=this.collisionIndex.placeCollisionBox(i,d,l,c,h,n,s,f,u.predicate,y,T,x);if((!v||this.collisionIndex.placeCollisionBox(v,d,l,c,h,n,s,g,u.predicate,y,T,x).placeable)&&E.placeable){let e;if(this.prevPlacement&&this.prevPlacement.variableOffsets[_.crossTileID]&&this.prevPlacement.placements[_.crossTileID]&&this.prevPlacement.placements[_.crossTileID].text&&(e=this.prevPlacement.variableOffsets[_.crossTileID].anchor),0===_.crossTileID)throw new Error("symbolInstance.crossTileID can't be 0");return this.variableOffsets[_.crossTileID]={textOffset:w,width:r,height:o,anchor:b,textBoxScale:a,prevAnchor:e},this.markUsedJustification(p,b,_,m),p.allowVerticalPlacement&&(this.markUsedOrientation(p,m,_),this.placedOrientations[_.crossTileID]=m),{shift:T,placedGlyphBoxes:E}}}placeLayerBucketPart(e,i,r){const{bucket:o,layout:a,translationText:s,translationIcon:n,unwrappedTileID:l,pitchedLabelPlaneMatrix:c,textPixelRatio:h,holdingForFade:u,collisionBoxArray:d,partiallyEvaluatedTextSize:_,collisionGroup:p}=e.parameters,m=a.get("text-optional"),f=a.get("icon-optional"),g=t.getOverlapMode(a,"text-overlap","text-allow-overlap"),v="always"===g,y=t.getOverlapMode(a,"icon-overlap","icon-allow-overlap"),x="always"===y,b="map"===a.get("text-rotation-alignment"),w="map"===a.get("text-pitch-alignment"),T="none"!==a.get("icon-text-fit"),E="viewport-y"===a.get("symbol-z-order"),P=v&&(x||!o.hasIconData()||f),I=x&&(v||!o.hasTextData()||m);!o.collisionArrays&&d&&o.deserializeCollisionBoxes(d);const C=this.retainedQueryData[o.bucketInstanceId].tileID,M=this._getTerrainElevationFunc(C),S=this.transform.getFastPathSimpleProjectionMatrix(C),R=(e,d,x)=>{var E,R;if(i[e.crossTileID])return;if(u)return void(this.placements[e.crossTileID]=new Ke(!1,!1,!1));let D=!1,z=!1,L=!0,A=null,k={box:null,placeable:!1,offscreen:null,occluded:!1},F={box:null,placeable:!1,offscreen:null},B=null,O=null,U=null,j=0,N=0,G=0;d.textFeatureIndex?j=d.textFeatureIndex:e.useRuntimeCollisionCircles&&(j=e.featureIndex),d.verticalTextFeatureIndex&&(N=d.verticalTextFeatureIndex);const Z=d.textBox;if(Z){const i=i=>{let r=t.WritingMode.horizontal;if(o.allowVerticalPlacement&&!i&&this.prevPlacement){const t=this.prevPlacement.placedOrientations[e.crossTileID];t&&(this.placedOrientations[e.crossTileID]=t,r=t,this.markUsedOrientation(o,r,e));}return r},a=(i,r)=>{if(o.allowVerticalPlacement&&e.numVerticalGlyphVertices>0&&d.verticalTextBox){for(const e of o.writingModes)if(e===t.WritingMode.vertical?(k=r(),F=k):k=i(),k&&k.placeable)break}else k=i();},c=e.textAnchorOffsetStartIndex,u=e.textAnchorOffsetEndIndex;if(u===c){const r=(t,i)=>{const r=this.collisionIndex.placeCollisionBox(t,g,h,C,l,w,b,s,p.predicate,M,void 0,S);return r&&r.placeable&&(this.markUsedOrientation(o,i,e),this.placedOrientations[e.crossTileID]=i),r};a((()=>r(Z,t.WritingMode.horizontal)),(()=>{const i=d.verticalTextBox;return o.allowVerticalPlacement&&e.numVerticalGlyphVertices>0&&i?r(i,t.WritingMode.vertical):{box:null,offscreen:null}})),i(k&&k.placeable);}else {let _=t.TextAnchorEnum[null===(R=null===(E=this.prevPlacement)||void 0===E?void 0:E.variableOffsets[e.crossTileID])||void 0===R?void 0:R.anchor];const m=(t,i,a)=>{const d=t.x2-t.x1,m=t.y2-t.y1,f=e.textBoxScale,v=T&&"never"===y?i:null;let x=null,E="never"===g?1:2,P="never";_&&E++;for(let i=0;im(Z,d.iconBox,t.WritingMode.horizontal)),(()=>{const i=d.verticalTextBox;return o.allowVerticalPlacement&&(!k||!k.placeable)&&e.numVerticalGlyphVertices>0&&i?m(i,d.verticalIconBox,t.WritingMode.vertical):{box:null,occluded:!0,offscreen:null}})),k&&(D=k.placeable,L=k.offscreen);const f=i(k&&k.placeable);if(!D&&this.prevPlacement){const t=this.prevPlacement.variableOffsets[e.crossTileID];t&&(this.variableOffsets[e.crossTileID]=t,this.markUsedJustification(o,t.anchor,e,f));}}}if(B=k,D=B&&B.placeable,L=B&&B.offscreen,e.useRuntimeCollisionCircles){const i=o.text.placedSymbolArray.get(e.centerJustifiedTextSymbolIndex),n=t.evaluateSizeForFeature(o.textSizeData,_,i),h=a.get("text-padding");O=this.collisionIndex.placeCollisionCircles(g,i,o.lineVertexArray,o.glyphOffsetArray,n,l,c,r,w,p.predicate,e.collisionCircleDiameter,h,s,M),O.circles.length&&O.collisionDetected&&!r&&t.warnOnce("Collisions detected, but collision boxes are not shown"),D=v||O.circles.length>0&&!O.collisionDetected,L=L&&O.offscreen;}if(d.iconFeatureIndex&&(G=d.iconFeatureIndex),d.iconBox){const e=e=>this.collisionIndex.placeCollisionBox(e,y,h,C,l,w,b,n,p.predicate,M,T&&A?A:void 0,S);F&&F.placeable&&d.verticalIconBox?(U=e(d.verticalIconBox),z=U.placeable):(U=e(d.iconBox),z=U.placeable),L=L&&U.offscreen;}const V=m||0===e.numHorizontalGlyphVertices&&0===e.numVerticalGlyphVertices,q=f||0===e.numIconVertices;V||q?q?V||(z=z&&D):D=z&&D:z=D=z&&D;const W=z&&U.placeable;if(D&&B.placeable&&this.collisionIndex.insertCollisionBox(B.box,g,a.get("text-ignore-placement"),o.bucketInstanceId,F&&F.placeable&&N?N:j,p.ID),W&&this.collisionIndex.insertCollisionBox(U.box,y,a.get("icon-ignore-placement"),o.bucketInstanceId,G,p.ID),O&&D&&this.collisionIndex.insertCollisionCircles(O.circles,g,a.get("text-ignore-placement"),o.bucketInstanceId,j,p.ID),r&&this.storeCollisionData(o.bucketInstanceId,x,d,B,U,O),0===e.crossTileID)throw new Error("symbolInstance.crossTileID can't be 0");if(0===o.bucketInstanceId)throw new Error("bucket.bucketInstanceId can't be 0");this.placements[e.crossTileID]=new Ke((D||P)&&!(null==B?void 0:B.occluded),(z||I)&&!(null==U?void 0:U.occluded),L||o.justReloaded),i[e.crossTileID]=!0;};if(E){if(0!==e.symbolInstanceStart)throw new Error("bucket.bucketInstanceId should be 0");const t=o.getSortedSymbolIndexes(-this.transform.bearingInRadians);for(let e=t.length-1;e>=0;--e){const i=t[e];R(o.symbolInstances.get(i),o.collisionArrays[i],i);}}else for(let t=e.symbolInstanceStart;t=0&&(e.text.placedSymbolArray.get(t).crossTileID=a>=0&&t!==a?0:r.crossTileID);}markUsedOrientation(e,i,r){const o=i===t.WritingMode.horizontal||i===t.WritingMode.horizontalOnly?i:0,a=i===t.WritingMode.vertical?i:0,s=[r.leftJustifiedTextSymbolIndex,r.centerJustifiedTextSymbolIndex,r.rightJustifiedTextSymbolIndex];for(const t of s)e.text.placedSymbolArray.get(t).placedOrientation=o;r.verticalPlacedTextSymbolIndex&&(e.text.placedSymbolArray.get(r.verticalPlacedTextSymbolIndex).placedOrientation=a);}commit(e){this.commitTime=e,this.zoomAtLastRecencyCheck=this.transform.zoom;const t=this.prevPlacement;let i=!1;this.prevZoomAdjustment=t?t.zoomAdjustment(this.transform.zoom):0;const r=t?t.symbolFadeChange(e):1,o=t?t.opacities:{},a=t?t.variableOffsets:{},s=t?t.placedOrientations:{};for(const e in this.placements){const t=this.placements[e],a=o[e];a?(this.opacities[e]=new He(a,r,t.text,t.icon),i=i||t.text!==a.text.placed||t.icon!==a.icon.placed):(this.opacities[e]=new He(null,r,t.text,t.icon,t.skipFade),i=i||t.text||t.icon);}for(const e in o){const t=o[e];if(!this.opacities[e]){const o=new He(t,r,!1,!1);o.isHidden()||(this.opacities[e]=o,i=i||t.text.placed||t.icon.placed);}}for(const e in a)this.variableOffsets[e]||!this.opacities[e]||this.opacities[e].isHidden()||(this.variableOffsets[e]=a[e]);for(const e in s)this.placedOrientations[e]||!this.opacities[e]||this.opacities[e].isHidden()||(this.placedOrientations[e]=s[e]);if(t&&void 0===t.lastPlacementChangeTime)throw new Error("Last placement time for previous placement is not defined");i?this.lastPlacementChangeTime=e:"number"!=typeof this.lastPlacementChangeTime&&(this.lastPlacementChangeTime=t?t.lastPlacementChangeTime:e);}updateLayerOpacities(e,t){const i={};for(const r of t){const t=r.getBucket(e);t&&r.latestFeatureIndex&&e.id===t.layerIds[0]&&this.updateBucketOpacities(t,r.tileID,i,r.collisionBoxArray);}}updateBucketOpacities(e,i,r,o){e.hasTextData()&&(e.text.opacityVertexArray.clear(),e.text.hasVisibleVertices=!1),e.hasIconData()&&(e.icon.opacityVertexArray.clear(),e.icon.hasVisibleVertices=!1),e.hasIconCollisionBoxData()&&e.iconCollisionBox.collisionVertexArray.clear(),e.hasTextCollisionBoxData()&&e.textCollisionBox.collisionVertexArray.clear();const a=e.layers[0],s=a.layout,n=new He(null,0,!1,!1,!0),l=s.get("text-allow-overlap"),c=s.get("icon-allow-overlap"),h=a._unevaluatedLayout.hasValue("text-variable-anchor")||a._unevaluatedLayout.hasValue("text-variable-anchor-offset"),u="map"===s.get("text-rotation-alignment"),d="map"===s.get("text-pitch-alignment"),_="none"!==s.get("icon-text-fit"),p=new He(null,0,l&&(c||!e.hasIconData()||s.get("icon-optional")),c&&(l||!e.hasTextData()||s.get("text-optional")),!0);!e.collisionArrays&&o&&(e.hasIconCollisionBoxData()||e.hasTextCollisionBoxData())&&e.deserializeCollisionBoxes(o);const m=(e,t,i)=>{for(let r=0;r0,v=this.placedOrientations[o.crossTileID],y=v===t.WritingMode.vertical,x=v===t.WritingMode.horizontal||v===t.WritingMode.horizontalOnly;if(a>0||s>0){const t=ct(c.text);m(e.text,a,y?ht:t),m(e.text,s,x?ht:t);const i=c.text.isHidden();[o.rightJustifiedTextSymbolIndex,o.centerJustifiedTextSymbolIndex,o.leftJustifiedTextSymbolIndex].forEach((t=>{t>=0&&(e.text.placedSymbolArray.get(t).hidden=i||y?1:0);})),o.verticalPlacedTextSymbolIndex>=0&&(e.text.placedSymbolArray.get(o.verticalPlacedTextSymbolIndex).hidden=i||x?1:0);const r=this.variableOffsets[o.crossTileID];r&&this.markUsedJustification(e,r.anchor,o,v);const n=this.placedOrientations[o.crossTileID];n&&(this.markUsedJustification(e,"left",o,n),this.markUsedOrientation(e,n,o));}if(g){const t=ct(c.icon),i=!(_&&o.verticalPlacedIconSymbolIndex&&y);o.placedIconSymbolIndex>=0&&(m(e.icon,o.numIconVertices,i?t:ht),e.icon.placedSymbolArray.get(o.placedIconSymbolIndex).hidden=c.icon.isHidden()),o.verticalPlacedIconSymbolIndex>=0&&(m(e.icon,o.numVerticalIconVertices,i?ht:t),e.icon.placedSymbolArray.get(o.verticalPlacedIconSymbolIndex).hidden=c.icon.isHidden());}const b=f&&f.has(i)?f.get(i):{text:null,icon:null};if(e.hasIconCollisionBoxData()||e.hasTextCollisionBoxData()){const r=e.collisionArrays[i];if(r){let i=new t.Point(0,0);if(r.textBox||r.verticalTextBox){let t=!0;if(h){const e=this.variableOffsets[l];e?(i=Qe(e.anchor,e.width,e.height,e.textOffset,e.textBoxScale),u&&i._rotate(d?-this.transform.bearingInRadians:this.transform.bearingInRadians)):t=!1;}if(r.textBox||r.verticalTextBox){let o;r.textBox&&(o=y),r.verticalTextBox&&(o=x),tt(e.textCollisionBox.collisionVertexArray,c.text.placed,!t||o,b.text,i.x,i.y);}}if(r.iconBox||r.verticalIconBox){const t=Boolean(!x&&r.verticalIconBox);let o;r.iconBox&&(o=t),r.verticalIconBox&&(o=!t),tt(e.iconCollisionBox.collisionVertexArray,c.icon.placed,o,b.icon,_?i.x:0,_?i.y:0);}}}}if(e.sortFeatures(-this.transform.bearingInRadians),this.retainedQueryData[e.bucketInstanceId]&&(this.retainedQueryData[e.bucketInstanceId].featureSortOrder=e.featureSortOrder),e.hasTextData()&&e.text.opacityVertexBuffer&&e.text.opacityVertexBuffer.updateData(e.text.opacityVertexArray),e.hasIconData()&&e.icon.opacityVertexBuffer&&e.icon.opacityVertexBuffer.updateData(e.icon.opacityVertexArray),e.hasIconCollisionBoxData()&&e.iconCollisionBox.collisionVertexBuffer&&e.iconCollisionBox.collisionVertexBuffer.updateData(e.iconCollisionBox.collisionVertexArray),e.hasTextCollisionBoxData()&&e.textCollisionBox.collisionVertexBuffer&&e.textCollisionBox.collisionVertexBuffer.updateData(e.textCollisionBox.collisionVertexArray),e.text.opacityVertexArray.length!==e.text.layoutVertexArray.length/4)throw new Error(`bucket.text.opacityVertexArray.length (= ${e.text.opacityVertexArray.length}) !== bucket.text.layoutVertexArray.length (= ${e.text.layoutVertexArray.length}) / 4`);if(e.icon.opacityVertexArray.length!==e.icon.layoutVertexArray.length/4)throw new Error(`bucket.icon.opacityVertexArray.length (= ${e.icon.opacityVertexArray.length}) !== bucket.icon.layoutVertexArray.length (= ${e.icon.layoutVertexArray.length}) / 4`);e.bucketInstanceId in this.collisionCircleArrays&&(e.collisionCircleArray=this.collisionCircleArrays[e.bucketInstanceId],delete this.collisionCircleArrays[e.bucketInstanceId]);}symbolFadeChange(e){return 0===this.fadeDuration?1:(e-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(e){return Math.max(0,(this.transform.zoom-e)/1.5)}hasTransitions(e){return this.stale||e-this.lastPlacementChangeTimee}setStale(){this.stale=!0;}}function tt(e,t,i,r,o,a){r&&0!==r.length||(r=[0,0,0,0]);const s=r[0]-We,n=r[1]-We,l=r[2]-We,c=r[3]-We;e.emplaceBack(t?1:0,i?1:0,o||0,a||0,s,n),e.emplaceBack(t?1:0,i?1:0,o||0,a||0,l,n),e.emplaceBack(t?1:0,i?1:0,o||0,a||0,l,c),e.emplaceBack(t?1:0,i?1:0,o||0,a||0,s,c);}const it=Math.pow(2,25),rt=Math.pow(2,24),ot=Math.pow(2,17),at=Math.pow(2,16),st=Math.pow(2,9),nt=Math.pow(2,8),lt=Math.pow(2,1);function ct(e){if(0===e.opacity&&!e.placed)return 0;if(1===e.opacity&&e.placed)return 4294967295;const t=e.placed?1:0,i=Math.floor(127*e.opacity);return i*it+t*rt+i*ot+t*at+i*st+t*nt+i*lt+t}const ht=0;class ut{constructor(e){this._sortAcrossTiles="viewport-y"!==e.layout.get("symbol-z-order")&&!e.layout.get("symbol-sort-key").isConstant(),this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs={},this._bucketParts=[];}continuePlacement(e,t,i,r,o){const a=this._bucketParts;for(;this._currentTileIndexe.sortKey-t.sortKey)));this._currentPartIndex!this._forceFullPlacement&&f.now()-r>2;for(;this._currentPlacementIndex>=0;){const r=t[e[this._currentPlacementIndex]],a=this.placement.collisionIndex.transform.zoom;if("symbol"===r.type&&(!r.minzoom||r.minzoom<=a)&&(!r.maxzoom||r.maxzoom>a)){if(this._inProgressLayer||(this._inProgressLayer=new ut(r)),this._inProgressLayer.continuePlacement(i[r.source],this.placement,this._showCollisionBoxes,r,o))return;delete this._inProgressLayer;}this._currentPlacementIndex--;}this._done=!0;}commit(e){return this.placement.commit(e),this.placement}}const _t=512/t.EXTENT/2;class pt{constructor(e,i,r){this.tileID=e,this.bucketInstanceId=r,this._symbolsByKey={};const o=new Map;for(let e=0;e({x:Math.floor(e.anchorX*_t),y:Math.floor(e.anchorY*_t)}))),crossTileIDs:i.map((e=>e.crossTileID))};if(r.positions.length>128){const e=new t.KDBush(r.positions.length,16,Uint16Array);for(const{x:t,y:i}of r.positions)e.add(t,i);e.finish(),delete r.positions,r.index=e;}this._symbolsByKey[e]=r;}}getScaledCoordinates(e,i){const{x:r,y:o,z:a}=this.tileID.canonical,{x:s,y:n,z:l}=i.canonical,c=_t/Math.pow(2,l-a),h=(n*t.EXTENT+e.anchorY)*c,u=o*t.EXTENT*_t;return {x:Math.floor((s*t.EXTENT+e.anchorX)*c-r*t.EXTENT*_t),y:Math.floor(h-u)}}findMatches(e,t,i){const r=this.tileID.canonical.ze))}}class mt{constructor(){this.maxCrossTileID=0;}generate(){return ++this.maxCrossTileID}}class ft{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0;}handleWrapJump(e){const t=Math.round((e-this.lng)/360);if(0!==t)for(const e in this.indexes){const i=this.indexes[e],r={};for(const e in i){const o=i[e];o.tileID=o.tileID.unwrapTo(o.tileID.wrap+t),r[o.tileID.key]=o;}this.indexes[e]=r;}this.lng=e;}addBucket(e,t,i){if(this.indexes[e.overscaledZ]&&this.indexes[e.overscaledZ][e.key]){if(this.indexes[e.overscaledZ][e.key].bucketInstanceId===t.bucketInstanceId)return !1;this.removeBucketCrossTileIDs(e.overscaledZ,this.indexes[e.overscaledZ][e.key]);}for(let e=0;ee.overscaledZ)for(const i in o){const a=o[i];a.tileID.isChildOf(e)&&a.findMatches(t.symbolInstances,e,r);}else {const a=o[e.scaledTo(Number(i)).key];a&&a.findMatches(t.symbolInstances,e,r);}}for(let e=0;e{t[e]=!0;}));for(const e in this.layerIndexes)t[e]||delete this.layerIndexes[e];}}var vt="void main() {gl_FragColor=vec4(1.0);}";const yt={prelude:xt("#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","#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;}mat3 rotationMatrixFromAxisAngle(vec3 u,float angle) {float c=cos(angle);float s=sin(angle);float c2=1.0-c;return mat3(u.x*u.x*c2+ c,u.x*u.y*c2-u.z*s,u.x*u.z*c2+u.y*s,u.y*u.x*c2+u.z*s,u.y*u.y*c2+ c,u.y*u.z*c2-u.x*s,u.z*u.x*c2-u.y*s,u.z*u.y*c2+u.x*s,u.z*u.z*c2+ c\n);}\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}const float PI=3.141592653589793;uniform mat4 u_projection_matrix;"),projectionMercator:xt("","float projectLineThickness(float tileY) {return 1.0;}float projectCircleRadius(float tileY) {return 1.0;}vec4 projectTile(vec2 p) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);return result;}vec4 projectTile(vec2 p,vec2 rawPos) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);if (rawPos.y <-32767.5 || rawPos.y > 32766.5) {result.z=-10000000.0;}return result;}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_projection_matrix*vec4(posInTile,elevation,1.0);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {return projectTileWithElevation(posInTile,elevation);}"),projectionGlobe:xt("","#define GLOBE_RADIUS 6371008.8\nuniform highp vec4 u_projection_tile_mercator_coords;uniform highp vec4 u_projection_clipping_plane;uniform highp float u_projection_transition;uniform mat4 u_projection_fallback_matrix;vec3 globeRotateVector(vec3 vec,vec2 angles) {vec3 axisRight=vec3(vec.z,0.0,-vec.x);vec3 axisUp=cross(axisRight,vec);axisRight=normalize(axisRight);axisUp=normalize(axisUp);vec2 t=tan(angles);return normalize(vec+axisRight*t.x+axisUp*t.y);}mat3 globeGetRotationMatrix(vec3 spherePos) {vec3 axisRight=vec3(spherePos.z,0.0,-spherePos.x);vec3 axisDown=cross(axisRight,spherePos);axisRight=normalize(axisRight);axisDown=normalize(axisDown);return mat3(axisRight,axisDown,spherePos\n);}float circumferenceRatioAtTileY(float tileY) {float mercator_pos_y=u_projection_tile_mercator_coords.y+u_projection_tile_mercator_coords.w*tileY;float spherical_y=2.0*atan(exp(PI-(mercator_pos_y*PI*2.0)))-PI*0.5;return cos(spherical_y);}float projectLineThickness(float tileY) {float thickness=1.0/circumferenceRatioAtTileY(tileY); \nif (u_projection_transition < 0.999) {return mix(1.0,thickness,u_projection_transition);} else {return thickness;}}vec3 projectToSphere(vec2 posInTile,vec2 rawPos) {vec2 mercator_pos=u_projection_tile_mercator_coords.xy+u_projection_tile_mercator_coords.zw*posInTile;vec2 spherical;spherical.x=mercator_pos.x*PI*2.0+PI;spherical.y=2.0*atan(exp(PI-(mercator_pos.y*PI*2.0)))-PI*0.5;float len=cos(spherical.y);vec3 pos=vec3(sin(spherical.x)*len,sin(spherical.y),cos(spherical.x)*len\n);if (rawPos.y <-32767.5) {pos=vec3(0.0,1.0,0.0);}if (rawPos.y > 32766.5) {pos=vec3(0.0,-1.0,0.0);}return pos;}vec3 projectToSphere(vec2 posInTile) {return projectToSphere(posInTile,vec2(0.0,0.0));}float globeComputeClippingZ(vec3 spherePos) {return (1.0-(dot(spherePos,u_projection_clipping_plane.xyz)+u_projection_clipping_plane.w));}vec4 interpolateProjection(vec2 posInTile,vec3 spherePos,float elevation) {vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);globePosition.z=globeComputeClippingZ(elevatedPos)*globePosition.w;if (u_projection_transition < 0.999) {vec4 flatPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);const float z_globeness_threshold=0.2;vec4 result=globePosition;result.z=mix(0.0,globePosition.z,clamp((u_projection_transition-z_globeness_threshold)/(1.0-z_globeness_threshold),0.0,1.0));result.xyw=mix(flatPosition.xyw,globePosition.xyw,u_projection_transition);if ((posInTile.y <-32767.5) || (posInTile.y > 32766.5)) {result=globePosition;const float poles_hidden_anim_percentage=0.02;result.z=mix(globePosition.z,100.0,pow(max((1.0-u_projection_transition)/poles_hidden_anim_percentage,0.0),8.0));}return result;}return globePosition;}vec4 interpolateProjectionFor3D(vec2 posInTile,vec3 spherePos,float elevation) {vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);vec4 fallbackPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);return mix(fallbackPosition,globePosition,u_projection_transition);}vec4 projectTile(vec2 posInTile) {return interpolateProjection(posInTile,projectToSphere(posInTile),0.0);}vec4 projectTile(vec2 posInTile,vec2 rawPos) {return interpolateProjection(posInTile,projectToSphere(posInTile,rawPos),0.0);}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return interpolateProjection(posInTile,projectToSphere(posInTile),elevation);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {vec3 spherePos=projectToSphere(posInTile);return interpolateProjectionFor3D(posInTile,spherePos,elevation);}"),background:xt("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}","attribute vec2 a_pos;void main() {gl_Position=projectTile(a_pos);}"),backgroundPattern:xt("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}","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=projectTile(a_pos);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);}"),circle:xt("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);float antialiased_blur=v_data.z;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);const float epsilon=0.5/255.0;if (gl_FragColor.r < epsilon && gl_FragColor.g < epsilon && gl_FragColor.b < epsilon && gl_FragColor.a < epsilon) {discard;}\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform bool u_scale_with_map;uniform bool u_pitch_with_map;uniform vec2 u_extrude_scale;uniform highp float u_globe_extrude_scale;uniform lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;uniform vec2 u_translate;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 pos_raw=a_pos+32768.0;vec2 extrude=vec2(mod(pos_raw,8.0)/7.0*2.0-1.0);vec2 circle_center=floor(pos_raw/8.0)+u_translate;float ele=get_elevation(circle_center);v_visibility=calculate_visibility(projectTileWithElevation(circle_center,ele));if (u_pitch_with_map) {\n#ifdef GLOBE\nvec3 center_vector=projectToSphere(circle_center);\n#endif\nfloat angle_scale=u_globe_extrude_scale;vec2 corner_position=circle_center;if (u_scale_with_map) {angle_scale*=(radius+stroke_width);corner_position+=extrude*u_extrude_scale*(radius+stroke_width);} else {\n#ifdef GLOBE\nvec4 projected_center=interpolateProjection(circle_center,center_vector,ele);\n#else\nvec4 projected_center=projectTileWithElevation(circle_center,ele);\n#endif\ncorner_position+=extrude*u_extrude_scale*(radius+stroke_width)*(projected_center.w/u_camera_to_center_distance);angle_scale*=(radius+stroke_width)*(projected_center.w/u_camera_to_center_distance);}\n#ifdef GLOBE\nvec2 angles=extrude*angle_scale;vec3 corner_vector=globeRotateVector(center_vector,angles);gl_Position=interpolateProjection(corner_position,corner_vector,ele);\n#else\ngl_Position=projectTileWithElevation(corner_position,ele);\n#endif\n} else {gl_Position=projectTileWithElevation(circle_center,ele);if (gl_Position.z/gl_Position.w > 1.0) {gl_Position.xy=vec2(10000.0);}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;}}float antialiasblur=-max(1.0/u_device_pixel_ratio/(radius+stroke_width),blur);v_data=vec3(extrude.x,extrude.y,antialiasblur);}"),clippingMask:xt(vt,"attribute vec2 a_pos;void main() {gl_Position=projectTile(a_pos);}"),heatmap:xt("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}","uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;uniform highp float u_globe_extrude_scale;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 pos_raw=a_pos+32768.0;vec2 unscaled_extrude=vec2(mod(pos_raw,8.0)/7.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;vec2 circle_center=floor(pos_raw/8.0);\n#ifdef GLOBE\nvec2 angles=v_extrude*radius*u_globe_extrude_scale;vec3 center_vector=projectToSphere(circle_center);vec3 corner_vector=globeRotateVector(center_vector,angles);gl_Position=interpolateProjection(circle_center+extrude,corner_vector,0.0);\n#else\ngl_Position=projectTileFor3D(circle_center+extrude,get_elevation(circle_center));\n#endif\n}"),heatmapTexture:xt("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}","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;}"),collisionBox:xt("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;}}","attribute vec2 a_anchor_pos;attribute vec2 a_placed;attribute vec2 a_box_real;uniform vec2 u_pixel_extrude_scale;varying float v_placed;varying float v_notUsed;void main() {gl_Position=projectTileWithElevation(a_anchor_pos,get_elevation(a_anchor_pos));gl_Position.xy=((a_box_real+0.5)*u_pixel_extrude_scale*2.0-1.0)*vec2(1.0,-1.0)*gl_Position.w;if (gl_Position.z/gl_Position.w < 1.1) {gl_Position.z=0.5;}v_placed=a_placed.x;v_notUsed=a_placed.y;}"),collisionCircle:xt("varying float v_radius;varying vec2 v_extrude;varying float v_collision;void main() {float alpha=0.5;float stroke_radius=0.9;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;}","attribute vec2 a_pos;attribute float a_radius;attribute vec2 a_flags;uniform vec2 u_viewport_size;varying float v_radius;varying vec2 v_extrude;varying float v_collision;void main() {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;float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_collision=collision;gl_Position=vec4((a_pos/u_viewport_size*2.0-1.0)*vec2(1.0,-1.0),0.0,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}"),debug:xt("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);}","attribute vec2 a_pos;varying vec2 v_uv;uniform float u_overlay_scale;void main() {v_uv=a_pos/8192.0;gl_Position=projectTileWithElevation(a_pos*u_overlay_scale,get_elevation(a_pos));}"),depth:xt(vt,"attribute vec2 a_pos;void main() {\n#ifdef GLOBE\ngl_Position=projectTileFor3D(a_pos,0.0);\n#else\ngl_Position=u_projection_matrix*vec4(a_pos,0.0,1.0);\n#endif\n}"),fill:xt("#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}","uniform vec2 u_fill_translate;attribute vec2 a_pos;\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=projectTile(a_pos+u_fill_translate,a_pos);}"),fillOutline:xt("varying vec2 v_pos;\n#ifdef GLOBE\nvarying float v_depth;\n#endif\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 GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_world;uniform vec2 u_fill_translate;attribute vec2 a_pos;varying vec2 v_pos;\n#ifdef GLOBE\nvarying float v_depth;\n#endif\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=projectTile(a_pos+u_fill_translate,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n}"),fillOutlinePattern:xt("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#ifdef GLOBE\nvarying float v_depth;\n#endif\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 GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;uniform vec2 u_fill_translate;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec2 v_pos;\n#ifdef GLOBE\nvarying float v_depth;\n#endif\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=projectTile(a_pos+u_fill_translate,a_pos);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;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n}"),fillPattern:xt("#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}","uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;uniform vec2 u_fill_translate;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=projectTile(a_pos+u_fill_translate,a_pos);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);}"),fillExtrusion:xt("varying vec4 v_color;void main() {gl_FragColor=v_color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec2 u_fill_translate;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);float elevation=t > 0.0 ? height : base;vec2 posInTile=a_pos+u_fill_translate;\n#ifdef GLOBE\nvec3 spherePos=projectToSphere(posInTile,a_pos);gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);\n#else\ngl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);\n#endif\nfloat 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;vec3 normalForLighting=normal/16384.0;float directional=clamp(dot(normalForLighting,u_lightpos),0.0,1.0);\n#ifdef GLOBE\nmat3 rotMatrix=globeGetRotationMatrix(spherePos);normalForLighting=rotMatrix*normalForLighting;directional=mix(directional,clamp(dot(normalForLighting,u_lightpos_globe),0.0,1.0),u_projection_transition);\n#endif\ndirectional=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;}"),fillExtrusionPattern:xt("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}","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 vec2 u_fill_translate;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;attribute vec2 a_pos;attribute vec4 a_normal_ed;\n#ifdef TERRAIN3D\nattribute vec2 a_centroid;\n#endif\n#ifdef GLOBE\nvarying vec3 v_sphere_pos;\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 elevation=t > 0.0 ? height : base;vec2 posInTile=a_pos+u_fill_translate;\n#ifdef GLOBE\nvec3 spherePos=projectToSphere(posInTile,a_pos);vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);v_sphere_pos=elevatedPos;gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);\n#else\ngl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);\n#endif\nvec2 pos=normal.x==1.0 && normal.y==0.0 && normal.z==16384.0\n? a_pos\n: vec2(edgedistance,elevation*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;}"),hillshadePrepare:xt("#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}","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;}"),hillshade:xt("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}","uniform mat4 u_matrix;attribute vec2 a_pos;varying vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);v_pos=a_pos/8192.0;if (a_pos.y <-32767.5) {v_pos.y=0.0;}if (a_pos.y > 32766.5) {v_pos.y=1.0;}}"),line:xt("uniform lowp float u_device_pixel_ratio;varying vec2 v_width2;varying vec2 v_normal;varying float v_gamma_scale;\n#ifdef GLOBE\nvarying float v_depth;\n#endif\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 GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform vec2 u_translation;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#ifdef GLOBE\nvarying float v_depth;\n#endif\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);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}"),lineGradient:xt("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#ifdef GLOBE\nvarying float v_depth;\n#endif\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 GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","\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 vec2 u_translation;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#ifdef GLOBE\nvarying float v_depth;\n#endif\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);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}"),linePattern:xt("#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#ifdef GLOBE\nvarying float v_depth;\n#endif\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 GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform vec2 u_translation;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#ifdef GLOBE\nvarying float v_depth;\n#endif\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);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.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;}"),lineSDF:xt("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#ifdef GLOBE\nvarying float v_depth;\n#endif\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 GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform vec2 u_translation;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#ifdef GLOBE\nvarying float v_depth;\n#endif\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);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.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);}"),raster:xt("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}","uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_buffer_scale;uniform vec4 u_coords_top;uniform vec4 u_coords_bottom;attribute vec2 a_pos;varying vec2 v_pos0;varying vec2 v_pos1;void main() {vec2 fractionalPos=a_pos/8192.0;vec2 position=mix(mix(u_coords_top.xy,u_coords_top.zw,fractionalPos.x),mix(u_coords_bottom.xy,u_coords_bottom.zw,fractionalPos.x),fractionalPos.y);gl_Position=projectTile(position,position);v_pos0=((fractionalPos-0.5)/u_buffer_scale)+0.5;\n#ifdef GLOBE\nif (a_pos.y <-32767.5) {v_pos0.y=0.0;}if (a_pos.y > 32766.5) {v_pos0.y=1.0;}\n#endif\nv_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}"),symbolIcon:xt("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}","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_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform vec2 u_texsize;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;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;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);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=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);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;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map && !u_is_along_line) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset/16.0)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}gl_Position=finalPos;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));}"),symbolSDF:xt("#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}","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_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;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_translation;uniform float u_pitched_scale;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;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);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=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);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;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale+a_pxoffset)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;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);}"),symbolTextAndIcon:xt("#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}","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_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;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;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;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);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=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);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;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map && !u_is_along_line) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;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);}"),terrain:xt("uniform sampler2D u_texture;uniform vec4 u_fog_color;uniform vec4 u_horizon_color;uniform float u_fog_ground_blend;uniform float u_fog_ground_blend_opacity;uniform float u_horizon_fog_blend;uniform bool u_is_globe_mode;varying vec2 v_texture_pos;varying float v_fog_depth;const float gamma=2.2;vec4 gammaToLinear(vec4 color) {return pow(color,vec4(gamma));}vec4 linearToGamma(vec4 color) {return pow(color,vec4(1.0/gamma));}void main() {vec4 surface_color=texture2D(u_texture,vec2(v_texture_pos.x,1.0-v_texture_pos.y));if (!u_is_globe_mode && v_fog_depth > u_fog_ground_blend) {vec4 surface_color_linear=gammaToLinear(surface_color);float blend_color=smoothstep(0.0,1.0,max((v_fog_depth-u_horizon_fog_blend)/(1.0-u_horizon_fog_blend),0.0));vec4 fog_horizon_color_linear=mix(gammaToLinear(u_fog_color),gammaToLinear(u_horizon_color),blend_color);float factor_fog=max(v_fog_depth-u_fog_ground_blend,0.0)/(1.0-u_fog_ground_blend);gl_FragColor=linearToGamma(mix(surface_color_linear,fog_horizon_color_linear,pow(factor_fog,2.0)*u_fog_ground_blend_opacity));} else {gl_FragColor=surface_color;}}","attribute vec3 a_pos3d;uniform mat4 u_fog_matrix;uniform float u_ele_delta;varying vec2 v_texture_pos;varying float v_fog_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=projectTileFor3D(a_pos3d.xy,get_elevation(a_pos3d.xy)-ele_delta);vec4 pos=u_fog_matrix*vec4(a_pos3d.xy,ele,1.0);v_fog_depth=pos.z/pos.w*0.5+0.5;}"),terrainDepth:xt("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);}","attribute vec3 a_pos3d;uniform float u_ele_delta;varying float v_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);v_depth=gl_Position.z/gl_Position.w;}"),terrainCoords:xt("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);}","attribute vec3 a_pos3d;uniform float u_ele_delta;varying vec2 v_texture_pos;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);}"),projectionErrorMeasurement:xt("varying vec4 v_output_error_encoded;void main() {gl_FragColor=v_output_error_encoded;}","attribute vec2 a_pos;uniform highp float u_input;uniform highp float u_output_expected;varying vec4 v_output_error_encoded;void main() {float real_output=2.0*atan(exp(PI-(u_input*PI*2.0)))-PI*0.5;float error=real_output-u_output_expected;float abs_error=abs(error)*128.0;v_output_error_encoded.x=min(floor(abs_error*256.0),255.0)/255.0;abs_error-=v_output_error_encoded.x;v_output_error_encoded.y=min(floor(abs_error*65536.0),255.0)/255.0;abs_error-=v_output_error_encoded.x/255.0;v_output_error_encoded.z=min(floor(abs_error*16777216.0),255.0)/255.0;v_output_error_encoded.w=error >=0.0 ? 1.0 : 0.0;gl_Position=vec4(a_pos,0.0,1.0);}"),atmosphere:xt("varying vec3 view_direction;uniform vec3 u_sun_pos;uniform vec3 u_globe_position;uniform float u_globe_radius;uniform float u_atmosphere_blend;/**Shader use from https:*Made some change to adapt to MapLibre Globe geometry*/const float PI=3.141592653589793;const int iSteps=5;const int jSteps=3;/*radius of the planet*/const float EARTH_RADIUS=6371e3;/*radius of the atmosphere*/const float ATMOS_RADIUS=6471e3;vec2 rsi(vec3 r0,vec3 rd,float sr) {float a=dot(rd,rd);float b=2.0*dot(rd,r0);float c=dot(r0,r0)-(sr*sr);float d=(b*b)-4.0*a*c;if (d < 0.0) return vec2(1e5,-1e5);return vec2((-b-sqrt(d))/(2.0*a),(-b+sqrt(d))/(2.0*a));}vec4 atmosphere(vec3 r,vec3 r0,vec3 pSun,float iSun,float rPlanet,float rAtmos,vec3 kRlh,float kMie,float shRlh,float shMie,float g) {pSun=normalize(pSun);r=normalize(r);vec2 p=rsi(r0,r,rAtmos);if (p.x > p.y) return vec4(0,0,0,0);if (p.x < 0.0) {p.x=0.0;}vec3 pos=r0+r*p.x;vec2 p2=rsi(r0,r,rPlanet);if (p2.x <=p2.y && p2.x > 0.0) {p.y=min(p.y,p2.x);}float iStepSize=(p.y-p.x)/float(iSteps);float iTime=p.x+iStepSize*0.5;vec3 totalRlh=vec3(0,0,0);vec3 totalMie=vec3(0,0,0);float iOdRlh=0.0;float iOdMie=0.0;float mu=dot(r,pSun);float mumu=mu*mu;float gg=g*g;float pRlh=3.0/(16.0*PI)*(1.0+mumu);float pMie=3.0/(8.0*PI)*((1.0-gg)*(mumu+1.0))/(pow(1.0+gg-2.0*mu*g,1.5)*(2.0+gg));for (int i=0; i < iSteps; i++) {vec3 iPos=r0+r*iTime;float iHeight=length(iPos)-rPlanet;float odStepRlh=exp(-iHeight/shRlh)*iStepSize;float odStepMie=exp(-iHeight/shMie)*iStepSize;iOdRlh+=odStepRlh;iOdMie+=odStepMie;float jStepSize=rsi(iPos,pSun,rAtmos).y/float(jSteps);float jTime=jStepSize*0.5;float jOdRlh=0.0;float jOdMie=0.0;for (int j=0; j < jSteps; j++) {vec3 jPos=iPos+pSun*jTime;float jHeight=length(jPos)-rPlanet;jOdRlh+=exp(-jHeight/shRlh)*jStepSize;jOdMie+=exp(-jHeight/shMie)*jStepSize;jTime+=jStepSize;}vec3 attn=exp(-(kMie*(iOdMie+jOdMie)+kRlh*(iOdRlh+jOdRlh)));totalRlh+=odStepRlh*attn;totalMie+=odStepMie*attn;iTime+=iStepSize;}float opacity=min(0.75,exp(-(length(kRlh)*length(totalRlh)+kMie*length(totalMie))));vec3 color=iSun*(pRlh*kRlh*totalRlh+pMie*kMie*totalMie);return vec4(color,opacity);}void main() {vec3 scale_camera_pos=-u_globe_position*EARTH_RADIUS/u_globe_radius;vec4 color=atmosphere(normalize(view_direction),scale_camera_pos,u_sun_pos,22.0,EARTH_RADIUS,ATMOS_RADIUS,vec3(5.5e-6,13.0e-6,22.4e-6),21e-6,8e3,1.2e3,0.758\n);color.xyz=1.0-exp(-1.0*color.xyz);vec4 no_effect_color=vec4(0,0,0,0);gl_FragColor=mix(color,no_effect_color,1.0-u_atmosphere_blend);}","attribute vec2 a_pos;uniform mat4 u_inv_proj_matrix;varying vec3 view_direction;void main() {view_direction=(u_inv_proj_matrix*vec4(a_pos,0.0,1.0)).xyz;gl_Position=vec4(a_pos,0.0,1.0);}"),sky:xt("uniform vec4 u_sky_color;uniform vec4 u_horizon_color;uniform vec2 u_horizon;uniform vec2 u_horizon_normal;uniform float u_sky_horizon_blend;uniform float u_sky_blend;void main() {float x=gl_FragCoord.x;float y=gl_FragCoord.y;float blend=(y-u_horizon.y)*u_horizon_normal.y+(x-u_horizon.x)*u_horizon_normal.x;if (blend > 0.0) {if (blend < u_sky_horizon_blend) {gl_FragColor=mix(u_sky_color,u_horizon_color,pow(1.0-blend/u_sky_horizon_blend,2.0));} else {gl_FragColor=u_sky_color;}}gl_FragColor=mix(gl_FragColor,vec4(vec3(0.0),0.0),u_sky_blend);}","attribute vec2 a_pos;void main() {gl_Position=vec4(a_pos,1.0,1.0);}")};function xt(e,t){const i=/#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g,r=t.match(/attribute ([\w]+) ([\w]+)/g),o=e.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),a=t.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),s=a?a.concat(o):o,n={};return {fragmentSource:e=e.replace(i,((e,t,i,r,o)=>(n[o]=!0,"define"===t?`\n#ifndef HAS_UNIFORM_u_${o}\nvarying ${i} ${r} ${o};\n#else\nuniform ${i} ${r} u_${o};\n#endif\n`:`\n#ifdef HAS_UNIFORM_u_${o}\n ${i} ${r} ${o} = u_${o};\n#endif\n`))),vertexSource:t=t.replace(i,((e,t,i,r,o)=>{const a="float"===r?"vec2":"vec4",s=o.match(/color/)?"color":a;return n[o]?"define"===t?`\n#ifndef HAS_UNIFORM_u_${o}\nuniform lowp float u_${o}_t;\nattribute ${i} ${a} a_${o};\nvarying ${i} ${r} ${o};\n#else\nuniform ${i} ${r} u_${o};\n#endif\n`:"vec4"===s?`\n#ifndef HAS_UNIFORM_u_${o}\n ${o} = a_${o};\n#else\n ${i} ${r} ${o} = u_${o};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${o}\n ${o} = unpack_mix_${s}(a_${o}, u_${o}_t);\n#else\n ${i} ${r} ${o} = u_${o};\n#endif\n`:"define"===t?`\n#ifndef HAS_UNIFORM_u_${o}\nuniform lowp float u_${o}_t;\nattribute ${i} ${a} a_${o};\n#else\nuniform ${i} ${r} u_${o};\n#endif\n`:"vec4"===s?`\n#ifndef HAS_UNIFORM_u_${o}\n ${i} ${r} ${o} = a_${o};\n#else\n ${i} ${r} ${o} = u_${o};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${o}\n ${i} ${r} ${o} = unpack_mix_${s}(a_${o}, u_${o}_t);\n#else\n ${i} ${r} ${o} = u_${o};\n#endif\n`})),staticAttributes:r,staticUniforms:s}}class bt{constructor(e,t,i){this.vertexBuffer=e,this.indexBuffer=t,this.segments=i;}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.vertexBuffer=null,this.indexBuffer=null,this.segments=null;}}var wt=t.createLayout([{name:"a_pos",type:"Int16",components:2}]);const Tt="#define PROJECTION_MERCATOR",Et="mercator";class Pt{constructor(){this._cachedMesh=null;}get name(){return "mercator"}get useSubdivision(){return !1}get shaderVariantName(){return Et}get shaderDefine(){return Tt}get shaderPreludeCode(){return yt.projectionMercator}get vertexShaderPreludeCode(){return yt.projectionMercator.vertexSource}get subdivisionGranularity(){return t.SubdivisionGranularitySetting.noSubdivision}get useGlobeControls(){return !1}destroy(){}isRenderingDirty(){return !1}updateGPUdependent(e){}getMeshFromTileID(e,i,r,o,a){if(this._cachedMesh)return this._cachedMesh;const s=new t.PosArray;s.emplaceBack(0,0),s.emplaceBack(t.EXTENT,0),s.emplaceBack(0,t.EXTENT),s.emplaceBack(t.EXTENT,t.EXTENT);const n=e.createVertexBuffer(s,wt.members),l=t.SegmentVector.simpleSegment(0,0,4,2),c=new t.TriangleIndexArray;c.emplaceBack(1,0,2),c.emplaceBack(1,2,3);const h=e.createIndexBuffer(c);return this._cachedMesh=new bt(n,h,l),this._cachedMesh}}function It(e){return t.MercatorCoordinate.fromLngLat(e)}function Ct(e){return e&&e.toLngLat()}function Mt(e,i){const r=t.clamp(i.lat,-85.051129,ce);return new t.Point(t.mercatorXfromLng(i.lng)*e,t.mercatorYfromLat(r)*e)}function St(e,i){return new t.MercatorCoordinate(i.x/e,i.y/e).toLngLat()}function Rt(e){return e.cameraToCenterDistance*Math.min(.85*Math.tan(t.degreesToRadians(90-e.pitch)),Math.tan(t.degreesToRadians(89.25-e.pitch)))}function Dt(e,i){const r=e.canonical,o=i/ue(r.z),a=r.x+Math.pow(2,r.z)*e.wrap,s=t.identity(new Float64Array(16));return t.translate(s,s,[a*o,r.y*o,0]),t.scale(s,s,[o/t.EXTENT,o/t.EXTENT,1]),s}function zt(e,i,r,o,a){const s=t.MercatorCoordinate.fromLngLat(e,i),n=a*t.mercatorZfromAltitude(1,e.lat),l=n*Math.cos(t.degreesToRadians(r)),c=Math.sqrt(n*n-l*l),h=c*Math.sin(t.degreesToRadians(-o)),u=c*Math.cos(t.degreesToRadians(-o));return new t.MercatorCoordinate(s.x+h,s.y+u,s.z+l)}class Lt{constructor(e,i){this.min=e,this.max=i,this.center=t.scale$2([],t.add([],this.min,this.max),.5);}quadrant(e){const i=[e%2==0,e<2],r=t.clone(this.min),o=t.clone(this.max);for(let e=0;ethis.max[0]||e.aabb.min[1]>this.max[1]||e.aabb.min[2]>this.max[2]||e.aabb.max[0]0?(t+=e[r]*this.min[r],i+=e[r]*this.max[r]):(i+=e[r]*this.min[r],t+=e[r]*this.max[r]);return t>=0?2:i<0?0:1}}class At{distanceToTile2d(e,t,i,r){const o=r.distanceX([e,t]),a=r.distanceY([e,t]);return Math.hypot(o,a)}getWrap(e,t,i){return i}getTileAABB(e,i,r,o){var a,s;let n=r,l=r;if(o.terrain){const c=new t.OverscaledTileID(e.z,i,e.z,e.x,e.y),h=o.terrain.getMinMaxElevation(c);n=null!==(a=h.minElevation)&&void 0!==a?a:r,l=null!==(s=h.maxElevation)&&void 0!==s?s:r;}const c=1<o||e.padding.top>=.1}}class kt{constructor(e,t,i){this.points=e,this.planes=t,this.aabb=i;}static fromInvProjectionMatrix(e,i=1,r=0){const o=Math.pow(2,r),a=[[-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]].map((r=>{const a=1/(r=t.transformMat4([],r,e))[3]/i*o;return t.mul(r,r,[a,a,1/r[3],a])})),s=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map((e=>{const i=t.sub([],a[e[0]],a[e[1]]),r=t.sub([],a[e[2]],a[e[1]]),o=t.normalize([],t.cross([],i,r)),s=-t.dot(o,a[e[1]]);return o.concat(s)})),n=[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY],l=[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY];for(const e of a)for(let t=0;t<3;t++)n[t]=Math.min(n[t],e[t]),l[t]=Math.max(l[t],e[t]);return new kt(a,s,new Lt(n,l))}}class Ft{get pixelsToClipSpaceMatrix(){return this._helper.pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._helper.clipSpaceToPixelsMatrix}get pixelsToGLUnits(){return this._helper.pixelsToGLUnits}get centerOffset(){return this._helper.centerOffset}get size(){return this._helper.size}get rotationMatrix(){return this._helper.rotationMatrix}get centerPoint(){return this._helper.centerPoint}get pixelsPerMeter(){return this._helper.pixelsPerMeter}setMinZoom(e){this._helper.setMinZoom(e);}setMaxZoom(e){this._helper.setMaxZoom(e);}setMinPitch(e){this._helper.setMinPitch(e);}setMaxPitch(e){this._helper.setMaxPitch(e);}setRenderWorldCopies(e){this._helper.setRenderWorldCopies(e);}setBearing(e){this._helper.setBearing(e);}setPitch(e){this._helper.setPitch(e);}setRoll(e){this._helper.setRoll(e);}setFov(e){this._helper.setFov(e);}setZoom(e){this._helper.setZoom(e);}setCenter(e){this._helper.setCenter(e);}setElevation(e){this._helper.setElevation(e);}setMinElevationForCurrentTile(e){this._helper.setMinElevationForCurrentTile(e);}setPadding(e){this._helper.setPadding(e);}interpolatePadding(e,t,i){return this._helper.interpolatePadding(e,t,i)}isPaddingEqual(e){return this._helper.isPaddingEqual(e)}resize(e,t){this._helper.resize(e,t);}getMaxBounds(){return this._helper.getMaxBounds()}setMaxBounds(e){this._helper.setMaxBounds(e);}getCameraQueryGeometry(e){return this._helper.getCameraQueryGeometry(this.getCameraPoint(),e)}get tileSize(){return this._helper.tileSize}get tileZoom(){return this._helper.tileZoom}get scale(){return this._helper.scale}get worldSize(){return this._helper.worldSize}get width(){return this._helper.width}get height(){return this._helper.height}get lngRange(){return this._helper.lngRange}get latRange(){return this._helper.latRange}get minZoom(){return this._helper.minZoom}get maxZoom(){return this._helper.maxZoom}get zoom(){return this._helper.zoom}get center(){return this._helper.center}get minPitch(){return this._helper.minPitch}get maxPitch(){return this._helper.maxPitch}get pitch(){return this._helper.pitch}get pitchInRadians(){return this._helper.pitchInRadians}get roll(){return this._helper.roll}get rollInRadians(){return this._helper.rollInRadians}get bearing(){return this._helper.bearing}get bearingInRadians(){return this._helper.bearingInRadians}get fov(){return this._helper.fov}get fovInRadians(){return this._helper.fovInRadians}get elevation(){return this._helper.elevation}get minElevationForCurrentTile(){return this._helper.minElevationForCurrentTile}get padding(){return this._helper.padding}get unmodified(){return this._helper.unmodified}get renderWorldCopies(){return this._helper.renderWorldCopies}constructor(e,t,i,r,o){this._posMatrixCache=new Map,this._alignedPosMatrixCache=new Map,this._fogMatrixCacheF32=new Map,this._helper=new pe({calcMatrices:()=>{this._calcMatrices();},getConstrained:(e,t)=>this.getConstrained(e,t)},e,t,i,r,o),this._coveringTilesDetailsProvider=new At;}clone(){const e=new Ft;return e.apply(this),e}apply(e,t){this._helper.apply(e,t);}get cameraToCenterDistance(){return this._cameraToCenterDistance}get cameraPosition(){return this._cameraPosition}get projectionMatrix(){return this._projectionMatrix}get modelViewProjectionMatrix(){return this._viewProjMatrix}get inverseProjectionMatrix(){return this._invProjMatrix}get nearZ(){return this._nearZ}get farZ(){return this._farZ}get mercatorMatrix(){return this._mercatorMatrix}getVisibleUnwrappedCoordinates(e){const i=[new t.UnwrappedTileID(0,e)];if(this._helper._renderWorldCopies){const r=this.screenPointToMercatorCoordinate(new t.Point(0,0)),o=this.screenPointToMercatorCoordinate(new t.Point(this._helper._width,0)),a=this.screenPointToMercatorCoordinate(new t.Point(this._helper._width,this._helper._height)),s=this.screenPointToMercatorCoordinate(new t.Point(0,this._helper._height)),n=Math.floor(Math.min(r.x,o.x,a.x,s.x)),l=Math.floor(Math.max(r.x,o.x,a.x,s.x)),c=1;for(let r=n-c;r<=l+c;r++)0!==r&&i.push(new t.UnwrappedTileID(r,e));}return i}getCameraFrustum(){return kt.fromInvProjectionMatrix(this._invViewProjMatrix,this.worldSize)}getClippingPlane(){return null}getCoveringTilesDetailsProvider(){return this._coveringTilesDetailsProvider}recalculateZoomAndCenter(e){const i=this.screenPointToLocation(this.centerPoint,e),r=e?e.getElevationForLngLatZoom(i,this._helper._tileZoom):0;if(!(this.elevation-r))return;const o=t.mercatorZfromAltitude(1,this.center.lat)*this.worldSize,a=this._cameraToCenterDistance/o,s=t.MercatorCoordinate.fromLngLat(this.center,this.elevation),n=zt(this.center,this.elevation,this.pitch,this.bearing,a);this._helper._elevation=r;const l=this.calculateCenterFromCameraLngLatAlt(n.toLngLat(),t.altitudeFromMercatorZ(n.z,s.y),this.bearing,this.pitch);this._helper._elevation=l.elevation,this._helper._center=l.center,this.setZoom(l.zoom);}setLocationAtPoint(e,i){const r=t.mercatorZfromAltitude(this.elevation,this.center.lat),o=this.screenPointToMercatorCoordinateAtZ(i,r),a=this.screenPointToMercatorCoordinateAtZ(this.centerPoint,r),s=It(e),n=new t.MercatorCoordinate(s.x-(o.x-a.x),s.y-(o.y-a.y));this.setCenter(Ct(n)),this._helper._renderWorldCopies&&this.setCenter(this.center.wrap());}locationToScreenPoint(e,t){return t?this.coordinatePoint(It(e),t.getElevationForLngLatZoom(e,this._helper._tileZoom),this._pixelMatrix3D):this.coordinatePoint(It(e))}screenPointToLocation(e,t){return Ct(this.screenPointToMercatorCoordinate(e,t))}screenPointToMercatorCoordinate(e,t){if(t){const i=t.pointCoordinate(e);if(null!=i)return i}return this.screenPointToMercatorCoordinateAtZ(e)}screenPointToMercatorCoordinateAtZ(e,i){const r=i||0,o=[e.x,e.y,0,1],a=[e.x,e.y,1,1];t.transformMat4(o,o,this._pixelMatrixInverse),t.transformMat4(a,a,this._pixelMatrixInverse);const s=o[3],n=a[3],l=o[1]/s,c=a[1]/n,h=o[2]/s,u=a[2]/n,d=h===u?0:(r-h)/(u-h);return new t.MercatorCoordinate(t.interpolateFactory.number(o[0]/s,a[0]/n,d)/this.worldSize,t.interpolateFactory.number(l,c,d)/this.worldSize,r)}coordinatePoint(e,i=0,r=this._pixelMatrix){const o=[e.x*this.worldSize,e.y*this.worldSize,i,1];return t.transformMat4(o,o,r),new t.Point(o[0]/o[3],o[1]/o[3])}getBounds(){const e=Math.max(0,this._helper._height/2-Rt(this));return (new V).extend(this.screenPointToLocation(new t.Point(0,e))).extend(this.screenPointToLocation(new t.Point(this._helper._width,e))).extend(this.screenPointToLocation(new t.Point(this._helper._width,this._helper._height))).extend(this.screenPointToLocation(new t.Point(0,this._helper._height)))}isPointOnMapSurface(e,t){return t?null!=t.pointCoordinate(e):e.y>this.height/2-Rt(this)}calculatePosMatrix(e,i=!1,r){var o;const a=null!==(o=e.key)&&void 0!==o?o:t.calculateTileKey(e.wrap,e.canonical.z,e.canonical.z,e.canonical.x,e.canonical.y),s=i?this._alignedPosMatrixCache:this._posMatrixCache;if(s.has(a)){const e=s.get(a);return r?e.f32:e.f64}const n=Dt(e,this.worldSize);t.multiply(n,i?this._alignedProjMatrix:this._viewProjMatrix,n);const l={f64:n,f32:new Float32Array(n)};return s.set(a,l),r?l.f32:l.f64}calculateFogMatrix(e){const i=e.key,r=this._fogMatrixCacheF32;if(r.has(i))return r.get(i);const o=Dt(e,this.worldSize);return t.multiply(o,this._fogMatrix,o),r.set(i,new Float32Array(o)),r.get(i)}getConstrained(e,i){i=t.clamp(+i,this.minZoom,this.maxZoom);const r={center:new t.LngLat(e.lng,e.lat),zoom:i};let o=this._helper._lngRange;if(!this._helper._renderWorldCopies&&null===o){const e=180-1e-10;o=[-e,e];}const a=this.tileSize*ue(r.zoom);let s=0,n=a,l=0,c=a,h=0,u=0;const{x:d,y:_}=this.size;if(this._helper._latRange){const e=this._helper._latRange;s=t.mercatorYfromLat(e[1])*a,n=t.mercatorYfromLat(e[0])*a,n-s<_&&(h=_/(n-s));}o&&(l=t.wrap(t.mercatorXfromLng(o[0])*a,0,a),c=t.wrap(t.mercatorXfromLng(o[1])*a,0,a),cn&&(g=n-e);}if(o){const e=(l+c)/2;let i=p;this._helper._renderWorldCopies&&(i=t.wrap(p,e-a/2,e+a/2));const r=d/2;i-rc&&(f=c-r);}if(void 0!==f||void 0!==g){const e=new t.Point(null!=f?f:p,null!=g?g:m);r.center=St(a,e).wrap();}return r}calculateCenterFromCameraLngLatAlt(e,i,r,o){const a=void 0!==r?r:this.bearing,s=o=void 0!==o?o:this.pitch,n=t.MercatorCoordinate.fromLngLat(e,i),l=-Math.cos(t.degreesToRadians(s)),c=Math.sin(t.degreesToRadians(s)),h=c*Math.sin(t.degreesToRadians(a)),u=-c*Math.cos(t.degreesToRadians(a));let d=this.elevation;const _=i-d;let p;l*_>=0||Math.abs(l)<.1?(p=1e4,d=i+p*l):p=-_/l;let m,f,g=t.altitudeFromMercatorZ(1,n.y),v=0;do{if(v+=1,v>10)break;f=p/g,m=new t.MercatorCoordinate(n.x+h*f,n.y+u*f),g=1/m.meterInMercatorCoordinateUnits();}while(Math.abs(p-f*g)>1e-12);return {center:m.toLngLat(),elevation:d,zoom:de(this.height/2/Math.tan(this.fovInRadians/2)/f/this.tileSize)}}_calcMatrices(){if(!this._helper._height)return;const e=this.fovInRadians/2,i=this.centerOffset,r=Mt(this.worldSize,this.center),o=r.x,a=r.y;this._cameraToCenterDistance=.5/Math.tan(e)*this._helper._height,this._helper._pixelPerMeter=t.mercatorZfromAltitude(1,this.center.lat)*this.worldSize;const s=t.degreesToRadians(Math.min(this.pitch,89.25)),n=Math.max(this._cameraToCenterDistance/2,this._cameraToCenterDistance+this._helper._elevation*this._helper._pixelPerMeter/Math.cos(s)),l=Math.min(this.elevation,this.minElevationForCurrentTile,this.getCameraAltitude()-100),c=n-l*this._helper._pixelPerMeter/Math.cos(s),h=l<0?c:n,u=Math.PI/2+this.pitchInRadians,d=t.degreesToRadians(this.fov)*(Math.abs(Math.cos(t.degreesToRadians(this.roll)))*this.height+Math.abs(Math.sin(t.degreesToRadians(this.roll)))*this.width)/this.height*(.5+i.y/this.height),_=Math.sin(d)*h/Math.sin(t.clamp(Math.PI-u-d,.01,Math.PI-.01)),p=Rt(this),m=Math.atan(p/this._cameraToCenterDistance),f=t.degreesToRadians(.75),g=m>f?2*m*(.5+i.y/(2*p)):f,v=Math.sin(g)*h/Math.sin(t.clamp(Math.PI-u-g,.01,Math.PI-.01)),y=Math.min(_,v);let x;this._farZ=1.01*(Math.cos(Math.PI/2-s)*y+h),this._nearZ=this._helper._height/50,x=new Float64Array(16),t.perspective(x,this.fovInRadians,this._helper._width/this._helper._height,this._nearZ,this._farZ),this._invProjMatrix=new Float64Array(16),t.invert(this._invProjMatrix,x),x[8]=2*-i.x/this._helper._width,x[9]=2*i.y/this._helper._height,this._projectionMatrix=t.clone$1(x),t.scale(x,x,[1,-1,1]),t.translate(x,x,[0,0,-this._cameraToCenterDistance]),t.rotateZ(x,x,-this.rollInRadians),t.rotateX(x,x,this.pitchInRadians),t.rotateZ(x,x,-this.bearingInRadians),t.translate(x,x,[-o,-a,0]),this._mercatorMatrix=t.scale([],x,[this.worldSize,this.worldSize,this.worldSize]),t.scale(x,x,[1,1,this._helper._pixelPerMeter]),this._pixelMatrix=t.multiply(new Float64Array(16),this.clipSpaceToPixelsMatrix,x),t.translate(x,x,[0,0,-this.elevation]),this._viewProjMatrix=x,this._invViewProjMatrix=t.invert([],x);const b=[0,0,-1,1];t.transformMat4(b,b,this._invViewProjMatrix),this._cameraPosition=[b[0]/b[3],b[1]/b[3],b[2]/b[3]],this._fogMatrix=new Float64Array(16),t.perspective(this._fogMatrix,this.fovInRadians,this.width/this.height,n,this._farZ),this._fogMatrix[8]=2*-i.x/this.width,this._fogMatrix[9]=2*i.y/this.height,t.scale(this._fogMatrix,this._fogMatrix,[1,-1,1]),t.translate(this._fogMatrix,this._fogMatrix,[0,0,-this.cameraToCenterDistance]),t.rotateZ(this._fogMatrix,this._fogMatrix,-this.rollInRadians),t.rotateX(this._fogMatrix,this._fogMatrix,this.pitchInRadians),t.rotateZ(this._fogMatrix,this._fogMatrix,-this.bearingInRadians),t.translate(this._fogMatrix,this._fogMatrix,[-o,-a,0]),t.scale(this._fogMatrix,this._fogMatrix,[1,1,this._helper._pixelPerMeter]),t.translate(this._fogMatrix,this._fogMatrix,[0,0,-this.elevation]),this._pixelMatrix3D=t.multiply(new Float64Array(16),this.clipSpaceToPixelsMatrix,x);const w=this._helper._width%2/2,T=this._helper._height%2/2,E=Math.cos(this.bearingInRadians),P=Math.sin(-this.bearingInRadians),I=o-Math.round(o)+E*w+P*T,C=a-Math.round(a)+E*T+P*w,M=new Float64Array(x);if(t.translate(M,M,[I>.5?I-1:I,C>.5?C-1:C,0]),this._alignedProjMatrix=M,x=t.invert(new Float64Array(16),this._pixelMatrix),!x)throw new Error("failed to invert matrix");this._pixelMatrixInverse=x,this._clearMatrixCaches();}_clearMatrixCaches(){this._posMatrixCache.clear(),this._alignedPosMatrixCache.clear(),this._fogMatrixCacheF32.clear();}maxPitchScaleFactor(){if(!this._pixelMatrixInverse)return 1;const e=this.screenPointToMercatorCoordinate(new t.Point(0,0)),i=[e.x*this.worldSize,e.y*this.worldSize,0,1];return t.transformMat4(i,i,this._pixelMatrix)[3]/this._cameraToCenterDistance}getCameraPoint(){const e=Math.tan(this.pitchInRadians)*(this._cameraToCenterDistance||1);return this.centerPoint.add(new t.Point(e*Math.sin(this.rollInRadians),e*Math.cos(this.rollInRadians)))}getCameraAltitude(){return Math.cos(this.pitchInRadians)*this._cameraToCenterDistance/this._helper._pixelPerMeter+this.elevation}getCameraLngLat(){const e=.5/Math.tan(this.fovInRadians/2)*this.height,i=t.mercatorZfromAltitude(1,this.center.lat)*this.worldSize;return zt(this.center,this.elevation,this.pitch,this.bearing,e/i).toLngLat()}lngLatToCameraDepth(e,i){const r=It(e),o=[r.x*this.worldSize,r.y*this.worldSize,i,1];return t.transformMat4(o,o,this._viewProjMatrix),o[2]/o[3]}isRenderingDirty(){return !1}getProjectionData(e){const{overscaledTileID:i,aligned:r,applyTerrainMatrix:o}=e;return function(e,i,r=!0){let o,a;if(e){const i=e.canonical.z>=0?1<{if(d&&e.setZoom(t.interpolateFactory.number(r,g,h)),t.equals(a,c)||Ot(a,c,{roll:s,pitch:n,bearing:l},e,h),u&&(e.interpolatePadding(o,i.padding,h),p=e.centerPoint.add(i.offsetAsPoint)),i.around)e.setLocationAtPoint(i.around,i.aroundPoint);else {const t=ue(e.zoom-r),i=g>r?Math.min(2,x):Math.max(.5,x),o=Math.pow(i,1-h),a=St(e.worldSize,v.add(y.mult(h*o)).mult(t));e.setLocationAtPoint(e.renderWorldCopies?a.wrap():a,p);}},isZooming:d,elevationCenter:f}}handleFlyTo(e,i){const r=void 0!==i.zoom,o=e.zoom,a=e.getConstrained(t.LngLat.convert(i.center||i.locationAtOffset),r?+i.zoom:o),s=a.center,n=a.zoom;he(e,s);const l=Mt(e.worldSize,i.locationAtOffset),c=Mt(e.worldSize,s).sub(l),h=c.mag(),u=ue(n-o);let d;if(void 0!==i.minZoom){const t=Math.min(+i.minZoom,o,n);d=ue(e.getConstrained(s,t).zoom-o);}return {easeFunc:(t,i,r,a)=>{e.setZoom(1===t?n:o+de(i));const h=1===t?s:St(e.worldSize,l.add(c.mult(r)).mult(i));e.setLocationAtPoint(e.renderWorldCopies?h.wrap():h,a);},scaleOfZoom:u,targetCenter:s,scaleOfMinZoom:d,pixelPathLength:h}}}class jt{constructor(e,t,i){this.blendFunction=e,this.blendColor=t,this.mask=i;}}jt.Replace=[1,0],jt.disabled=new jt(jt.Replace,t.Color.transparent,[!1,!1,!1,!1]),jt.unblended=new jt(jt.Replace,t.Color.transparent,[!0,!0,!0,!0]),jt.alphaBlended=new jt([1,771],t.Color.transparent,[!0,!0,!0,!0]);const Nt=2305;class Gt{constructor(e,t,i){this.enable=e,this.mode=t,this.frontFace=i;}}Gt.disabled=new Gt(!1,1029,Nt),Gt.backCCW=new Gt(!0,1029,Nt),Gt.frontCCW=new Gt(!0,1028,Nt);class Zt{constructor(e,t,i){this.func=e,this.mask=t,this.range=i;}}Zt.ReadOnly=!1,Zt.ReadWrite=!0,Zt.disabled=new Zt(519,Zt.ReadOnly,[0,1]);const Vt=7680;class qt{constructor(e,t,i,r,o,a){this.test=e,this.ref=t,this.mask=i,this.fail=r,this.depthFail=o,this.pass=a;}}qt.disabled=new qt({func:519,mask:0},0,0,Vt,Vt,Vt);const Wt=new WeakMap;function Xt(e){var t;if(Wt.has(e))return Wt.get(e);{const i=null===(t=e.getParameter(e.VERSION))||void 0===t?void 0:t.startsWith("WebGL 2.0");return Wt.set(e,i),i}}class $t{get awaitingQuery(){return !!this._readbackQueue}constructor(e){this._readbackWaitFrames=4,this._measureWaitFrames=6,this._texWidth=1,this._texHeight=1,this._measuredError=0,this._updateCount=0,this._lastReadbackFrame=-1e3,this._readbackQueue=null,this._cachedRenderContext=e;const i=e.context,r=i.gl;this._texFormat=r.RGBA,this._texType=r.UNSIGNED_BYTE;const o=new t.PosArray;o.emplaceBack(-1,-1),o.emplaceBack(2,-1),o.emplaceBack(-1,2);const a=new t.TriangleIndexArray;a.emplaceBack(0,1,2),this._fullscreenTriangle=new bt(i.createVertexBuffer(o,wt.members),i.createIndexBuffer(a),t.SegmentVector.simpleSegment(0,0,o.length,a.length)),this._resultBuffer=new Uint8Array(4),i.activeTexture.set(r.TEXTURE1);const s=r.createTexture();r.bindTexture(r.TEXTURE_2D,s),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.NEAREST),r.texImage2D(r.TEXTURE_2D,0,this._texFormat,this._texWidth,this._texHeight,0,this._texFormat,this._texType,null),this._fbo=i.createFramebuffer(this._texWidth,this._texHeight,!1,!1),this._fbo.colorAttachment.set(s),Xt(r)&&(this._pbo=r.createBuffer(),r.bindBuffer(r.PIXEL_PACK_BUFFER,this._pbo),r.bufferData(r.PIXEL_PACK_BUFFER,4,r.STREAM_READ),r.bindBuffer(r.PIXEL_PACK_BUFFER,null));}destroy(){const e=this._cachedRenderContext.context.gl;this._fullscreenTriangle.destroy(),this._fbo.destroy(),e.deleteBuffer(this._pbo),this._fullscreenTriangle=null,this._fbo=null,this._pbo=null,this._resultBuffer=null;}updateErrorLoop(e,t){const i=this._updateCount;return this._readbackQueue?i>=this._readbackQueue.frameNumberIssued+this._readbackWaitFrames&&this._tryReadback():i>=this._lastReadbackFrame+this._measureWaitFrames&&this._renderErrorTexture(e,t),this._updateCount++,this._measuredError}_bindFramebuffer(){const e=this._cachedRenderContext.context,t=e.gl;e.activeTexture.set(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this._fbo.colorAttachment.get()),e.bindFramebuffer.set(this._fbo.framebuffer);}_renderErrorTexture(e,i){const r=this._cachedRenderContext.context,o=r.gl;if(this._bindFramebuffer(),r.viewport.set([0,0,this._texWidth,this._texHeight]),r.clear({color:t.Color.transparent}),this._cachedRenderContext.useProgram("projectionErrorMeasurement").draw(r,o.TRIANGLES,Zt.disabled,qt.disabled,jt.unblended,Gt.disabled,((e,t)=>({u_input:e,u_output_expected:t}))(e,i),null,null,"$clipping",this._fullscreenTriangle.vertexBuffer,this._fullscreenTriangle.indexBuffer,this._fullscreenTriangle.segments),this._pbo&&Xt(o)){o.bindBuffer(o.PIXEL_PACK_BUFFER,this._pbo),o.readBuffer(o.COLOR_ATTACHMENT0),o.readPixels(0,0,this._texWidth,this._texHeight,this._texFormat,this._texType,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null);const e=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0);o.flush(),this._readbackQueue={frameNumberIssued:this._updateCount,sync:e};}else this._readbackQueue={frameNumberIssued:this._updateCount,sync:null};}_tryReadback(){const e=this._cachedRenderContext.context.gl;if(this._pbo&&this._readbackQueue&&Xt(e)){const i=e.clientWaitSync(this._readbackQueue.sync,0,0);if(i===e.WAIT_FAILED)return t.warnOnce("WebGL2 clientWaitSync failed."),this._readbackQueue=null,void(this._lastReadbackFrame=this._updateCount);if(i===e.TIMEOUT_EXPIRED)return;e.bindBuffer(e.PIXEL_PACK_BUFFER,this._pbo),e.getBufferSubData(e.PIXEL_PACK_BUFFER,0,this._resultBuffer,0,4),e.bindBuffer(e.PIXEL_PACK_BUFFER,null);}else this._bindFramebuffer(),e.readPixels(0,0,this._texWidth,this._texHeight,this._texFormat,this._texType,this._resultBuffer);this._readbackQueue=null,this._measuredError=$t._parseRGBA8float(this._resultBuffer),this._lastReadbackFrame=this._updateCount;}static _parseRGBA8float(e){let t=0;return t+=e[0]/256,t+=e[1]/65536,t+=e[2]/16777216,e[3]<127&&(t=-t),t/128}}const Ht=t.EXTENT/128;function Kt(e,i){const r=void 0!==e.granularity?Math.max(e.granularity,1):1,o=r+(e.generateBorders?2:0),a=r+(e.extendToNorthPole||e.generateBorders?1:0)+(e.extendToSouthPole||e.generateBorders?1:0),s=o+1,n=a+1,l=e.generateBorders?-1:0,c=e.generateBorders||e.extendToNorthPole?-1:0,h=r+(e.generateBorders?1:0),u=r+(e.generateBorders||e.extendToSouthPole?1:0),d=s*n,_=o*a*6,p=s*n>65536;if(p&&"16bit"===i)throw new Error("Granularity is too large and meshes would not fit inside 16 bit vertex indices.");const m=p||"32bit"===i,f=new Int16Array(2*d);let g;g=m?{vertices:f,indices:new Uint32Array(_),uses32bitIndices:!0}:{vertices:f,indices:new Uint16Array(_),uses32bitIndices:!1};const v=g.indices;let y=0;for(let i=c;i<=u;i++)for(let o=l;o<=h;o++){let a=o/r*t.EXTENT;-1===o&&(a=-Ht),o===r+1&&(a=t.EXTENT+Ht);let s=i/r*t.EXTENT;-1===i&&(s=e.extendToNorthPole?t.NORTH_POLE_Y:-Ht),i===r+1&&(s=e.extendToSouthPole?t.SOUTH_POLE_Y:t.EXTENT+Ht),f[y++]=a,f[y++]=s;}let x=0;for(let e=0;e1e-6){const o=e[0]/r,a=Math.acos(e[2]/r),s=(o>0?a:-a)/Math.PI*180;return new t.LngLat(t.wrap(s,-180,180),i)}return new t.LngLat(0,i)}function oi(e){return Math.cos(e*Math.PI/180)}function ai(e,t){const i=oi(e);return de(oi(t)/i)}function si(e,i){const r=e.rotate(i.bearingInRadians),o=i.zoom+ai(i.center.lat,0),a=t.lerp(1/oi(i.center.lat),1/oi(Math.min(Math.abs(i.center.lat),60)),t.remapSaturate(o,7,3,0,1)),s=360/Qt({worldSize:i.worldSize,center:{lat:i.center.lat}});return new t.LngLat(i.center.lng-r.x*s*a,t.clamp(i.center.lat+r.y*s,-85.051129,ce))}function ni(e){const t=.5*e,i=Math.sin(t),r=Math.cos(t);return Math.log(i+r)-Math.log(r-i)}function li(e,i,r,o){const a=e.lat+r*o;if(Math.abs(r)>1){const s=(Math.sign(e.lat+r)!==Math.sign(e.lat)?-Math.abs(e.lat):Math.abs(e.lat))*Math.PI/180,n=Math.abs(e.lat+r)*Math.PI/180,l=ni(s+o*(n-s)),c=ni(s),h=ni(n);return new t.LngLat(e.lng+i*((l-c)/(h-c)),a)}return new t.LngLat(e.lng+i*o,a)}class ci{constructor(e){this._cachePrevious=new Map,this._cache=new Map,this._hadAnyChanges=!1,this._aabbFactory=e;}newFrame(){if(!this._hadAnyChanges)return;const e=this._cachePrevious;this._cachePrevious=this._cache,this._cache=e,this._cache.clear(),this._hadAnyChanges=!1;}getTileAABB(e,t,i,r){const o=`${e.z}_${e.x}_${e.y}`,a=this._cache.get(o);if(a)return a;const s=this._cachePrevious.get(o);if(s)return this._cache.set(o,s),s;const n=this._aabbFactory(e,t,i,r);return this._cache.set(o,n),this._hadAnyChanges=!0,n}}function hi(e,t,i){const r=e-t;return r<0?-r:Math.max(0,r-i)}function ui(e,t,i,r,o){const a=e-i;let s;return s=a<0?Math.min(-a,1+a-o):a>1?Math.min(Math.max(a-o,0),1-a):0,Math.max(s,hi(t,r,o))}class di{constructor(){this._aabbCache=new ci(this._computeTileAABB);}newFrame(){this._aabbCache.newFrame();}distanceToTile2d(e,t,i,r){const o=1<4}getTileAABB(e,t,i,r){return this._aabbCache.getTileAABB(e,t,i,r)}_computeTileAABB(e,i,r,o){if(e.z<=0)return new Lt([-1,-1,-1],[1,1,1]);if(1===e.z)return new Lt([0===e.x?-1:0,0===e.y?0:-1,-1],[0===e.x?0:1,0===e.y?1:0,1]);{const i=[ei(0,0,e.x,e.y,e.z),ei(t.EXTENT,0,e.x,e.y,e.z),ei(t.EXTENT,t.EXTENT,e.x,e.y,e.z),ei(0,t.EXTENT,e.x,e.y,e.z)],r=[1,1,1],o=[-1,-1,-1];for(const e of i)for(let t=0;t<3;t++)r[t]=Math.min(r[t],e[t]),o[t]=Math.max(o[t],e[t]);if(0===e.y||e.y===(1<0}constructor(e,i=!0,r=!0){this._cachedClippingPlane=t.createVec4f64(),this._lastGlobeStateEnabled=!0,this._lastUpdateTimeSeconds=f.now()/1e3,this._lastGlobeChangeTimeSeconds=f.now()/1e3-10,this._skipNextAnimation=!0,this._projectionMatrix=t.createIdentityMat4f64(),this._globeViewProjMatrix32f=t.createIdentityMat4f32(),this._globeViewProjMatrixNoCorrection=t.createIdentityMat4f64(),this._globeViewProjMatrixNoCorrectionInverted=t.createIdentityMat4f64(),this._globeProjMatrixInverted=t.createIdentityMat4f64(),this._cameraPosition=t.createVec3f64(),this._globeProjectionAllowed=!0,this._globeLatitudeErrorCorrectionRadians=0,this._globeness=1,this._adaptive=r,this._helper=new pe({calcMatrices:()=>{this._calcMatrices();},getConstrained:(e,t)=>this.getConstrained(e,t)}),this._globeProjectionAllowed=i,this._globeness=i?1:0,this._projectionInstance=e,this._mercatorTransform=new Ft,this._coveringTilesDetailsProvider=new di;}clone(){const e=new _i(null,this._globeProjectionAllowed);return e._applyGlobeTransform(this),e.apply(this),e}apply(e){this._helper.apply(e),this._mercatorTransform.apply(this);}_applyGlobeTransform(e){this._globeness=e._globeness,this._globeLatitudeErrorCorrectionRadians=e._globeLatitudeErrorCorrectionRadians;}get projectionMatrix(){return this.isGlobeRendering?this._projectionMatrix:this._mercatorTransform.projectionMatrix}get modelViewProjectionMatrix(){return this.isGlobeRendering?this._globeViewProjMatrixNoCorrection:this._mercatorTransform.modelViewProjectionMatrix}get inverseProjectionMatrix(){return this.isGlobeRendering?this._globeProjMatrixInverted:this._mercatorTransform.inverseProjectionMatrix}get cameraPosition(){const e=t.createVec3f64();return e[0]=this._cameraPosition[0],e[1]=this._cameraPosition[1],e[2]=this._cameraPosition[2],e}get cameraToCenterDistance(){return this._mercatorTransform.cameraToCenterDistance}get nearZ(){return this._nearZ}get farZ(){return this._farZ}getGlobeViewAllowed(){return this._globeProjectionAllowed}setGlobeViewAllowed(e,t=!0){e!==this._globeProjectionAllowed&&(t||(this._skipNextAnimation=!0),this._globeProjectionAllowed=e,this._lastGlobeChangeTimeSeconds=this._lastUpdateTimeSeconds);}newFrameUpdate(){this._lastUpdateTimeSeconds=f.now()/1e3;const e=this.isGlobeRendering;return this._globeness=!this._adaptive&&this._globeProjectionAllowed?1:this._computeGlobenessAnimation(),this._updateErrorCorrectionValue(),this._calcMatrices(),this._coveringTilesDetailsProvider.newFrame(),e===this.isGlobeRendering?{forcePlacementUpdate:!1}:{forcePlacementUpdate:!0,fireProjectionEvent:{type:"projectiontransition",newProjection:this.isGlobeRendering?"globe":"globe-mercator"},forceSourceUpdate:!0}}_updateErrorCorrectionValue(){this._projectionInstance&&(this._projectionInstance.useGlobeRendering=this.isGlobeRendering,this._projectionInstance.errorQueryLatitudeDegrees=this.center.lat,this._globeLatitudeErrorCorrectionRadians=this._projectionInstance.latitudeErrorCorrectionRadians);}_computeGlobenessAnimation(){const e=this._globeProjectionAllowed&&this.zoom<12,i=this._lastUpdateTimeSeconds;e!==this._lastGlobeStateEnabled&&(this._lastGlobeChangeTimeSeconds=i,this._lastGlobeStateEnabled=e);const r=this._globeness,o=Math.min(Math.max((i-this._lastGlobeChangeTimeSeconds)/.5,0),1);let a=e?o:1-o;return this._skipNextAnimation&&(a=e?1:0,this._lastGlobeChangeTimeSeconds=i-1,this._skipNextAnimation=!1),a=t.easeCubicInOut(a),r!==a&&(this.setCenter(new t.LngLat(this._mercatorTransform.center.lng+t.differenceOfAnglesDegrees(this._mercatorTransform.center.lng,this.center.lng)*a,t.lerp(this._mercatorTransform.center.lat,this.center.lat,a))),this.setZoom(t.lerp(this._mercatorTransform.zoom,this.zoom,a))),a}isRenderingDirty(){return this._lastUpdateTimeSeconds-this._lastGlobeChangeTimeSeconds<.5}getProjectionData(e){const{overscaledTileID:t,aligned:i,applyTerrainMatrix:r,applyGlobeMatrix:o}=e,a=this._mercatorTransform.getProjectionData({overscaledTileID:t,aligned:i,applyTerrainMatrix:r});return this.isGlobeRendering&&(a.mainMatrix=this._globeViewProjMatrix32f),a.clippingPlane=this._cachedClippingPlane,a.projectionTransition=o?this._globeness:0,a}_computeClippingPlane(e){const i=this.pitchInRadians,r=this.cameraToCenterDistance/e,o=Math.sin(i)*r,a=Math.cos(i)*r+1,s=1/Math.sqrt(o*o+a*a)*1;let n=-o,l=a;const c=Math.sqrt(n*n+l*l);n/=c,l/=c;const h=[0,n,l];return t.rotateZ$1(h,h,[0,0,0],-this.bearingInRadians),t.rotateX$1(h,h,[0,0,0],-1*this.center.lat*Math.PI/180),t.rotateY(h,h,[0,0,0],this.center.lng*Math.PI/180),t.scale$2(h,h,.25),[...h,.25*-s]}isLocationOccluded(e){return !this.isSurfacePointVisible(ti(e))}transformLightDirection(e){const i=this._helper._center.lng*Math.PI/180,r=this._helper._center.lat*Math.PI/180,o=Math.cos(r),a=[Math.sin(i)*o,Math.sin(r),Math.cos(i)*o],s=[a[2],0,-a[0]],n=[0,0,0];t.cross(n,s,a),t.normalize(s,s),t.normalize(n,n);const l=[0,0,0];return t.normalize(l,[s[0]*e[0]+n[0]*e[1]+a[0]*e[2],s[1]*e[0]+n[1]*e[1]+a[1]*e[2],s[2]*e[0]+n[2]*e[1]+a[2]*e[2]]),l}getAnimatedLatitude(){return t.lerp(this._mercatorTransform.center.lat,this._helper._center.lat,this._globeness)}getPixelScale(){return t.lerp(this._mercatorTransform.getPixelScale(),1/Math.cos(this.getAnimatedLatitude()*Math.PI/180),this._globeness)}getCircleRadiusCorrection(){return t.lerp(this._mercatorTransform.getCircleRadiusCorrection(),Math.cos(this.getAnimatedLatitude()*Math.PI/180),this._globeness)}getPitchedTextCorrection(e,i,r){const o=this._mercatorTransform.getPitchedTextCorrection(e,i,r);if(!this.isGlobeRendering)return o;const a=function(e,i,r){const o=1/(1<a&&(a=i),rn&&(n=r);}const h=[c.lng+s,c.lat+l,c.lng+a,c.lat+n];return this.isSurfacePointOnScreen([0,1,0])&&(h[3]=90,h[0]=-180,h[2]=180),this.isSurfacePointOnScreen([0,-1,0])&&(h[1]=-90,h[0]=-180,h[2]=180),new V(h)}getConstrained(e,i){const r=t.clamp(e.lat,-85.051129,ce),o=t.clamp(+i,this.minZoom+ai(0,r),this.maxZoom);return {center:new t.LngLat(e.lng,r),zoom:o}}calculateCenterFromCameraLngLatAlt(e,t,i,r){return this._mercatorTransform.calculateCenterFromCameraLngLatAlt(e,t,i,r)}setLocationAtPoint(e,i){if(!this.isGlobeRendering)return this._mercatorTransform.setLocationAtPoint(e,i),void this.apply(this._mercatorTransform);const r=ti(this.unprojectScreenPoint(i)),o=ti(e),a=t.createVec3f64();t.zero$1(a);const s=t.createVec3f64();t.rotateY(s,r,a,-this.center.lng*Math.PI/180),t.rotateX$1(s,s,a,this.center.lat*Math.PI/180);const n=o[0]*o[0]+o[2]*o[2],l=s[0]*s[0];if(n=-g&&p<=g,y=f>=-g&&f<=g;let x,b;if(v&&y){const e=this.center.lng*Math.PI/180,i=this.center.lat*Math.PI/180;t.distanceOfAnglesRadians(u,e)+t.distanceOfAnglesRadians(p,i)=0}isSurfacePointOnScreen(e){if(!this.isSurfacePointVisible(e))return !1;const i=t.createVec4f64();return t.transformMat4(i,[...e,1],this._globeViewProjMatrixNoCorrection),i[0]/=i[3],i[1]/=i[3],i[2]/=i[3],i[0]>-1&&i[0]<1&&i[1]>-1&&i[1]<1&&i[2]>-1&&i[2]<1}rayPlanetIntersection(e,i){const r=t.dot(e,i),o=t.createVec3f64(),a=t.createVec3f64();t.scale$2(a,i,r),t.sub(o,e,a);const s=1-t.dot(o,o);if(s<0)return null;const n=t.dot(e,e)-1,l=-r+(r<0?1:-1)*Math.sqrt(s),c=n/l,h=l;return {tMin:Math.min(c,h),tMax:Math.max(c,h)}}unprojectScreenPoint(e){const i=this._cameraPosition,r=this.getRayDirectionFromPixel(e),o=this.rayPlanetIntersection(i,r);if(o){const e=t.createVec3f64();t.add(e,i,[r[0]*o.tMin,r[1]*o.tMin,r[2]*o.tMin]);const a=t.createVec3f64();return t.normalize(a,e),ri(a)}const a=this._cachedClippingPlane[0]*r[0]+this._cachedClippingPlane[1]*r[1]+this._cachedClippingPlane[2]*r[2],s=-t.pointPlaneSignedDistance(this._cachedClippingPlane,i)/a,n=t.createVec3f64();if(s>0)t.add(n,i,[r[0]*s,r[1]*s,r[2]*s]);else {const e=t.createVec3f64();t.add(e,i,[2*r[0],2*r[1],2*r[2]]);const o=t.pointPlaneSignedDistance(this._cachedClippingPlane,e);t.sub(n,e,[this._cachedClippingPlane[0]*o,this._cachedClippingPlane[1]*o,this._cachedClippingPlane[2]*o]);}const l=t.createVec3f64();return t.normalize(l,n),ri(l)}getMatrixForModel(e,i){if(!this.isGlobeRendering)return this._mercatorTransform.getMatrixForModel(e,i);const r=t.LngLat.convert(e),o=1/t.earthRadius,a=t.createIdentityMat4f64();return t.rotateY$1(a,a,r.lng/180*Math.PI),t.rotateX(a,a,-r.lat/180*Math.PI),t.translate(a,a,[0,0,1+i/t.earthRadius]),t.rotateX(a,a,.5*Math.PI),t.scale(a,a,[o,o,o]),a}getProjectionDataForCustomLayer(e=!0){const i=this.getProjectionData({overscaledTileID:new t.OverscaledTileID(0,0,0,0,0),applyGlobeMatrix:e});i.tileMercatorCoords=[0,0,1,1];const r=t.createMat4f32();return t.scale(r,i.fallbackMatrix,[t.EXTENT,t.EXTENT,1]),i.fallbackMatrix=r,i}getFastPathSimpleProjectionMatrix(e){if(!this.isGlobeRendering)return this._mercatorTransform.getFastPathSimpleProjectionMatrix(e)}}class pi{constructor(e){this._globe=e,this._mercatorCameraHelper=new Ut;}get useGlobeControls(){return this._globe.useGlobeRendering}handlePanInertia(e,i){if(!this.useGlobeControls)return this._mercatorCameraHelper.handlePanInertia(e,i);const r=si(e,i);return Math.abs(r.lng-i.center.lng)>180&&(r.lng=i.center.lng+179.5*Math.sign(r.lng-i.center.lng)),{easingCenter:r,easingOffset:new t.Point(0,0)}}handleMapControlsRollPitchBearingZoom(e,i){if(!this.useGlobeControls)return void this._mercatorCameraHelper.handleMapControlsRollPitchBearingZoom(e,i);const r=e.around,o=i.screenPointToLocation(r);e.bearingDelta&&i.setBearing(i.bearing+e.bearingDelta),e.pitchDelta&&i.setPitch(i.pitch+e.pitchDelta),e.rollDelta&&i.setRoll(i.roll+e.rollDelta);const a=i.zoom;e.zoomDelta&&i.setZoom(i.zoom+e.zoomDelta);const s=i.zoom-a;if(0===s)return;const n=t.differenceOfAnglesDegrees(i.center.lng,o.lng),l=n/(Math.abs(n/180)+1),c=t.differenceOfAnglesDegrees(i.center.lat,o.lat),h=i.getRayDirectionFromPixel(r),u=i.cameraPosition,d=-1*t.dot(u,h),_=t.createVec3f64();t.add(_,u,[h[0]*d,h[1]*d,h[2]*d]);const p=t.length$1(_)-1,m=Math.exp(.5*-Math.max(p-.3,0)),f=ii(i.worldSize,i.center.lat)/Math.min(i.width,i.height),g=t.remapSaturate(f,.9,.5,1,.25),v=(1-ue(-s))*Math.min(m,g),y=i.center.lat,x=i.zoom,b=new t.LngLat(i.center.lng+l*v,t.clamp(i.center.lat+c*v,-85.051129,ce));i.setLocationAtPoint(o,r);const w=i.center,T=t.remapSaturate(Math.abs(n),45,85,0,1),E=t.remapSaturate(f,.75,.35,0,1),P=Math.pow(Math.max(T,E),.25),I=t.differenceOfAnglesDegrees(w.lng,b.lng),C=t.differenceOfAnglesDegrees(w.lat,b.lat);i.setCenter(new t.LngLat(w.lng+I*P,w.lat+C*P).wrap()),i.setZoom(x+ai(y,i.center.lat));}handleMapControlsPan(e,t,i){if(!this.useGlobeControls)return void this._mercatorCameraHelper.handleMapControlsPan(e,t,i);if(!e.panDelta)return;const r=t.center.lat,o=t.zoom;t.setCenter(si(e.panDelta,t).wrap()),t.setZoom(o+ai(r,t.center.lat));}cameraForBoxAndBearing(e,i,r,o,a){const s=this._mercatorCameraHelper.cameraForBoxAndBearing(e,i,r,o,a);if(!this.useGlobeControls)return s;const n=i.left/a.width*2-1,l=(a.width-i.right)/a.width*2-1,c=i.top/a.height*-2+1,h=(a.height-i.bottom)/a.height*-2+1,u=t.differenceOfAnglesDegrees(r.getWest(),r.getEast())<0,d=u?r.getEast():r.getWest(),_=u?r.getWest():r.getEast(),p=Math.max(r.getNorth(),r.getSouth()),m=Math.min(r.getNorth(),r.getSouth()),f=d+.5*t.differenceOfAnglesDegrees(d,_),g=p+.5*t.differenceOfAnglesDegrees(p,m),v=a.clone();v.setCenter(s.center),v.setBearing(s.bearing),v.setPitch(0),v.setRoll(0),v.setZoom(s.zoom);const y=v.modelViewProjectionMatrix,x=[ti(r.getNorthWest()),ti(r.getNorthEast()),ti(r.getSouthWest()),ti(r.getSouthEast()),ti(new t.LngLat(_,g)),ti(new t.LngLat(d,g)),ti(new t.LngLat(f,p)),ti(new t.LngLat(f,m))],b=ti(s.center);let w=Number.POSITIVE_INFINITY;for(const e of x)n<0&&(w=pi.getLesserNonNegativeNonNull(w,pi.solveVectorScale(e,b,y,"x",n))),l>0&&(w=pi.getLesserNonNegativeNonNull(w,pi.solveVectorScale(e,b,y,"x",l))),c>0&&(w=pi.getLesserNonNegativeNonNull(w,pi.solveVectorScale(e,b,y,"y",c))),h<0&&(w=pi.getLesserNonNegativeNonNull(w,pi.solveVectorScale(e,b,y,"y",h)));if(Number.isFinite(w)&&0!==w)return s.zoom=v.zoom+de(w),s;Bt();}handleJumpToCenterZoom(e,i){if(!this.useGlobeControls)return void this._mercatorCameraHelper.handleJumpToCenterZoom(e,i);const r=e.center.lat,o=e.getConstrained(i.center?t.LngLat.convert(i.center):e.center,e.zoom).center;e.setCenter(o.wrap());const a=void 0!==i.zoom?+i.zoom:e.zoom+ai(r,o.lat);e.zoom!==a&&e.setZoom(a);}handleEaseTo(e,i){if(!this.useGlobeControls)return this._mercatorCameraHelper.handleEaseTo(e,i);const r=e.zoom,o=e.center,a=t.rollPitchBearingToQuat(e.roll,e.pitch,e.bearing),s=void 0===i.roll?e.roll:i.roll,n=void 0===i.pitch?e.pitch:i.pitch,l=void 0===i.bearing?e.bearing:i.bearing,c=t.rollPitchBearingToQuat(s,n,l),h=void 0!==i.zoom,u=!e.isPaddingEqual(i.padding);let d=!1;const _=i.center?t.LngLat.convert(i.center):o,p=e.getConstrained(_,r).center;he(e,p);const m=e.clone();m.setCenter(p),u&&m.setPadding(i.padding),m.setZoom(h?+i.zoom:r+ai(o.lat,_.lat)),m.setBearing(i.bearing);const f=new t.Point(t.clamp(e.centerPoint.x+i.offsetAsPoint.x,0,e.width),t.clamp(e.centerPoint.y+i.offsetAsPoint.y,0,e.height));m.setLocationAtPoint(p,f);const g=(i.offset&&i.offsetAsPoint.mag())>0?m.center:p,v=h?+i.zoom:r+ai(o.lat,g.lat),y=r+ai(o.lat,0),x=v+ai(g.lat,0),b=t.differenceOfAnglesDegrees(o.lng,g.lng),w=t.differenceOfAnglesDegrees(o.lat,g.lat),T=ue(x-y);return d=v!==r,{easeFunc:r=>{if(t.equals(a,c)||Ot(a,c,{roll:s,pitch:n,bearing:l},e,r),i.around)t.warnOnce("Easing around a point is not supported under globe projection."),e.setLocationAtPoint(i.around,i.aroundPoint);else {const t=x>y?Math.min(2,T):Math.max(.5,T),i=Math.pow(t,1-r),a=li(o,b,w,r*i);e.setCenter(a.wrap());}if(d){const i=t.interpolateFactory.number(y,x,r)+ai(0,e.center.lat);e.setZoom(i);}},isZooming:d,elevationCenter:g}}handleFlyTo(e,i){if(!this.useGlobeControls)return this._mercatorCameraHelper.handleFlyTo(e,i);const r=void 0!==i.zoom,o=e.center,a=e.zoom,s=!e.isPaddingEqual(i.padding),n=e.getConstrained(t.LngLat.convert(i.center||i.locationAtOffset),a).center,l=r?+i.zoom:e.zoom+ai(e.center.lat,n.lat),c=e.clone();c.setCenter(n),s&&c.setPadding(i.padding),c.setZoom(l),c.setBearing(i.bearing);const h=new t.Point(t.clamp(e.centerPoint.x+i.offsetAsPoint.x,0,e.width),t.clamp(e.centerPoint.y+i.offsetAsPoint.y,0,e.height));c.setLocationAtPoint(n,h);const u=c.center;he(e,u);const d=function(e,i,r){const o=ti(i),a=ti(r),s=t.dot(o,a),n=Math.acos(s),l=Qt(e);return n/(2*Math.PI)*l}(e,o,u),_=a+ai(o.lat,0),p=l+ai(u.lat,0),m=ue(p-_);let f;if("number"==typeof i.minZoom){const t=+i.minZoom+ai(u.lat,0),r=Math.min(t,_,p)+ai(0,u.lat);f=ue(e.getConstrained(u,r).zoom+ai(u.lat,0)-_);}const g=t.differenceOfAnglesDegrees(o.lng,u.lng),v=t.differenceOfAnglesDegrees(o.lat,u.lat);return {easeFunc:(t,i,r,a)=>{const s=li(o,g,v,r),n=1===t?u:s;e.setCenter(n.wrap());const c=_+de(i);e.setZoom(1===t?l:c+ai(0,n.lat));},scaleOfZoom:m,targetCenter:u,scaleOfMinZoom:f,pixelPathLength:d}}static solveVectorScale(e,t,i,r,o){const a="x"===r?[i[0],i[4],i[8],i[12]]:[i[1],i[5],i[9],i[13]],s=[i[3],i[7],i[11],i[15]],n=e[0]*a[0]+e[1]*a[1]+e[2]*a[2],l=e[0]*s[0]+e[1]*s[1]+e[2]*s[2],c=t[0]*a[0]+t[1]*a[1]+t[2]*a[2],h=t[0]*s[0]+t[1]*s[1]+t[2]*s[2];return c+o*l===n+o*h||s[3]*(n-c)+a[3]*(h-l)+n*h==c*l?null:(c+a[3]-o*h-o*s[3])/(c-n-o*h+o*l)}static getLesserNonNegativeNonNull(e,t){return null!==t&&t>=0&&tt.emitValidationErrors(e,i&&i.filter((e=>"source.canvas"!==e.identifier))),fi=t.emptyStyle();class gi extends t.Evented{constructor(e,i={}){super(),this._rtlPluginLoaded=()=>{for(const e in this.sourceCaches){const t=this.sourceCaches[e].getSource().type;"vector"!==t&&"geojson"!==t||this.sourceCaches[e].reload();}},this.map=e,this.dispatcher=new O(B(),e._getMapId()),this.dispatcher.registerMessageHandler("GG",((e,t)=>this.getGlyphs(e,t))),this.dispatcher.registerMessageHandler("GI",((e,t)=>this.getImages(e,t))),this.imageManager=new b,this.imageManager.setEventedParent(this),this.glyphManager=new P(e._requestManager,i.localIdeographFontFamily),this.lineAtlas=new D(256,512),this.crossTileSymbolIndex=new gt,this._spritesImagesIds={},this._layers={},this._order=[],this.sourceCaches={},this.zoomHistory=new t.ZoomHistory,this._loaded=!1,this._availableImages=[],this._resetUpdates(),this.dispatcher.broadcast("SR",t.getReferrer()),oe().on(te,this._rtlPluginLoaded),this.on("data",(e=>{if("source"!==e.dataType||"metadata"!==e.sourceDataType)return;const t=this.sourceCaches[e.sourceId];if(!t)return;const i=t.getSource();if(i&&i.vectorLayerIds)for(const e in this._layers){const t=this._layers[e];t.source===i.id&&this._validateLayer(t);}}));}loadURL(e,i={},r){this.fire(new t.Event("dataloading",{dataType:"style"})),i.validate="boolean"!=typeof i.validate||i.validate;const o=this.map._requestManager.transformRequest(e,"Style");this._loadStyleRequest=new AbortController;const a=this._loadStyleRequest;t.getJSON(o,this._loadStyleRequest).then((e=>{this._loadStyleRequest=null,this._load(e.data,i,r);})).catch((e=>{this._loadStyleRequest=null,e&&!a.signal.aborted&&this.fire(new t.ErrorEvent(e));}));}loadJSON(e,i={},r){this.fire(new t.Event("dataloading",{dataType:"style"})),this._frameRequest=new AbortController,f.frameAsync(this._frameRequest).then((()=>{this._frameRequest=null,i.validate=!1!==i.validate,this._load(e,i,r);})).catch((()=>{}));}loadEmpty(){this.fire(new t.Event("dataloading",{dataType:"style"})),this._load(fi,{validate:!1});}_load(e,i,r){var o,a;const s=i.transformStyle?i.transformStyle(r,e):e;if(!i.validate||!mi(this,t.validateStyle(s))){this._loaded=!0,this.stylesheet=s;for(const e in s.sources)this.addSource(e,s.sources[e],{validate:!1});s.sprite?this._loadSprite(s.sprite):this.imageManager.setLoaded(!0),this.glyphManager.setURL(s.glyphs),this._createLayers(),this.light=new M(this.stylesheet.light),this._setProjectionInternal((null===(o=this.stylesheet.projection)||void 0===o?void 0:o.type)||"mercator"),this.sky=new R(this.stylesheet.sky),this.map.setTerrain(null!==(a=this.stylesheet.terrain)&&void 0!==a?a:null),this.fire(new t.Event("data",{dataType:"style"})),this.fire(new t.Event("style.load"));}}_createLayers(){const e=t.derefLayers(this.stylesheet.layers);this.dispatcher.broadcast("SL",e),this._order=e.map((e=>e.id)),this._layers={},this._serializedLayers=null;for(const i of e){const e=t.createStyleLayer(i);e.setEventedParent(this,{layer:{id:i.id}}),this._layers[i.id]=e;}}_loadSprite(e,i=!1,r=void 0){let o;this.imageManager.setLoaded(!1),this._spriteRequest=new AbortController,function(e,i,r,o){return t.__awaiter(this,void 0,void 0,(function*(){const a=g(e),s=r>1?"@2x":"",n={},l={};for(const{id:e,url:r}of a){const a=i.transformRequest(v(r,s,".json"),"SpriteJSON");n[e]=t.getJSON(a,o);const c=i.transformRequest(v(r,s,".png"),"SpriteImage");l[e]=_.getImage(c,o);}return yield Promise.all([...Object.values(n),...Object.values(l)]),function(e,i){return t.__awaiter(this,void 0,void 0,(function*(){const t={};for(const r in e){t[r]={};const o=f.getImageCanvasContext((yield i[r]).data),a=(yield e[r]).data;for(const e in a){const{width:i,height:s,x:n,y:l,sdf:c,pixelRatio:h,stretchX:u,stretchY:d,content:_,textFitWidth:p,textFitHeight:m}=a[e];t[r][e]={data:null,pixelRatio:h,sdf:c,stretchX:u,stretchY:d,content:_,textFitWidth:p,textFitHeight:m,spriteData:{width:i,height:s,x:n,y:l,context:o}};}}return t}))}(n,l)}))}(e,this.map._requestManager,this.map.getPixelRatio(),this._spriteRequest).then((e=>{if(this._spriteRequest=null,e)for(const t in e){this._spritesImagesIds[t]=[];const r=this._spritesImagesIds[t]?this._spritesImagesIds[t].filter((t=>!(t in e))):[];for(const e of r)this.imageManager.removeImage(e),this._changedImages[e]=!0;for(const r in e[t]){const o="default"===t?r:`${t}:${r}`;this._spritesImagesIds[t].push(o),o in this.imageManager.images?this.imageManager.updateImage(o,e[t][r],!1):this.imageManager.addImage(o,e[t][r]),i&&(this._changedImages[o]=!0);}}})).catch((e=>{this._spriteRequest=null,o=e,this.fire(new t.ErrorEvent(o));})).finally((()=>{this.imageManager.setLoaded(!0),this._availableImages=this.imageManager.listImages(),i&&(this._changed=!0),this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.Event("data",{dataType:"style"})),r&&r(o);}));}_unloadSprite(){for(const e of Object.values(this._spritesImagesIds).flat())this.imageManager.removeImage(e),this._changedImages[e]=!0;this._spritesImagesIds={},this._availableImages=this.imageManager.listImages(),this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.Event("data",{dataType:"style"}));}_validateLayer(e){const i=this.sourceCaches[e.source];if(!i)return;const r=e.sourceLayer;if(!r)return;const o=i.getSource();("geojson"===o.type||o.vectorLayerIds&&-1===o.vectorLayerIds.indexOf(r))&&this.fire(new t.ErrorEvent(new Error(`Source layer "${r}" does not exist on source "${o.id}" as specified by style layer "${e.id}".`)));}loaded(){if(!this._loaded)return !1;if(Object.keys(this._updatedSources).length)return !1;for(const e in this.sourceCaches)if(!this.sourceCaches[e].loaded())return !1;return !!this.imageManager.isLoaded()}_serializeByIds(e,i=!1){const r=this._serializedAllLayers();if(!e||0===e.length)return Object.values(i?t.clone$2(r):r);const o=[];for(const a of e)if(r[a]){const e=i?t.clone$2(r[a]):r[a];o.push(e);}return o}_serializedAllLayers(){let e=this._serializedLayers;if(e)return e;e=this._serializedLayers={};const t=Object.keys(this._layers);for(const i of t){const t=this._layers[i];"custom"!==t.type&&(e[i]=t.serialize());}return e}hasTransitions(){if(this.light&&this.light.hasTransition())return !0;if(this.sky&&this.sky.hasTransition())return !0;for(const e in this.sourceCaches)if(this.sourceCaches[e].hasTransition())return !0;for(const e in this._layers)if(this._layers[e].hasTransition())return !0;return !1}_checkLoaded(){if(!this._loaded)throw new Error("Style is not done loading.")}update(e){if(!this._loaded)return;const i=this._changed;if(i){const t=Object.keys(this._updatedLayers),i=Object.keys(this._removedLayers);(t.length||i.length)&&this._updateWorkerLayers(t,i);for(const e in this._updatedSources){const t=this._updatedSources[e];if("reload"===t)this._reloadSource(e);else {if("clear"!==t)throw new Error(`Invalid action ${t}`);this._clearSource(e);}}this._updateTilesForChangedImages(),this._updateTilesForChangedGlyphs();for(const t in this._updatedPaintProps)this._layers[t].updateTransitions(e);this.light.updateTransitions(e),this.sky.updateTransitions(e),this._resetUpdates();}const r={};for(const e in this.sourceCaches){const t=this.sourceCaches[e];r[e]=t.used,t.used=!1;}for(const t of this._order){const i=this._layers[t];i.recalculate(e,this._availableImages),!i.isHidden(e.zoom)&&i.source&&(this.sourceCaches[i.source].used=!0);}for(const e in r){const i=this.sourceCaches[e];!!r[e]!=!!i.used&&i.fire(new t.Event("data",{sourceDataType:"visibility",dataType:"source",sourceId:e}));}this.light.recalculate(e),this.sky.recalculate(e),this.z=e.zoom,i&&this.fire(new t.Event("data",{dataType:"style"}));}_updateTilesForChangedImages(){const e=Object.keys(this._changedImages);if(e.length){for(const t in this.sourceCaches)this.sourceCaches[t].reloadTilesForDependencies(["icons","patterns"],e);this._changedImages={};}}_updateTilesForChangedGlyphs(){if(this._glyphsDidChange){for(const e in this.sourceCaches)this.sourceCaches[e].reloadTilesForDependencies(["glyphs"],[""]);this._glyphsDidChange=!1;}}_updateWorkerLayers(e,t){this.dispatcher.broadcast("UL",{layers:this._serializeByIds(e,!1),removedIds:t});}_resetUpdates(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSources={},this._updatedPaintProps={},this._changedImages={},this._glyphsDidChange=!1;}setState(e,i={}){var r;this._checkLoaded();const o=this.serialize();if(e=i.transformStyle?i.transformStyle(o,e):e,(null===(r=i.validate)||void 0===r||r)&&mi(this,t.validateStyle(e)))return !1;(e=t.clone$2(e)).layers=t.derefLayers(e.layers);const a=t.diff(o,e),s=this._getOperationsToPerform(a);if(s.unimplemented.length>0)throw new Error(`Unimplemented: ${s.unimplemented.join(", ")}.`);if(0===s.operations.length)return !1;for(const e of s.operations)e();return this.stylesheet=e,this._serializedLayers=null,!0}_getOperationsToPerform(e){const t=[],i=[];for(const r of e)switch(r.command){case"setCenter":case"setZoom":case"setBearing":case"setPitch":case"setRoll":continue;case"addLayer":t.push((()=>this.addLayer.apply(this,r.args)));break;case"removeLayer":t.push((()=>this.removeLayer.apply(this,r.args)));break;case"setPaintProperty":t.push((()=>this.setPaintProperty.apply(this,r.args)));break;case"setLayoutProperty":t.push((()=>this.setLayoutProperty.apply(this,r.args)));break;case"setFilter":t.push((()=>this.setFilter.apply(this,r.args)));break;case"addSource":t.push((()=>this.addSource.apply(this,r.args)));break;case"removeSource":t.push((()=>this.removeSource.apply(this,r.args)));break;case"setLayerZoomRange":t.push((()=>this.setLayerZoomRange.apply(this,r.args)));break;case"setLight":t.push((()=>this.setLight.apply(this,r.args)));break;case"setGeoJSONSourceData":t.push((()=>this.setGeoJSONSourceData.apply(this,r.args)));break;case"setGlyphs":t.push((()=>this.setGlyphs.apply(this,r.args)));break;case"setSprite":t.push((()=>this.setSprite.apply(this,r.args)));break;case"setTerrain":t.push((()=>this.map.setTerrain.apply(this,r.args)));break;case"setSky":t.push((()=>this.setSky.apply(this,r.args)));break;case"setProjection":this.setProjection.apply(this,r.args);break;case"setTransition":t.push((()=>{}));break;default:i.push(r.command);}return {operations:t,unimplemented:i}}addImage(e,i){if(this.getImage(e))return this.fire(new t.ErrorEvent(new Error(`An image named "${e}" already exists.`)));this.imageManager.addImage(e,i),this._afterImageUpdated(e);}updateImage(e,t){this.imageManager.updateImage(e,t);}getImage(e){return this.imageManager.getImage(e)}removeImage(e){if(!this.getImage(e))return this.fire(new t.ErrorEvent(new Error(`An image named "${e}" does not exist.`)));this.imageManager.removeImage(e),this._afterImageUpdated(e);}_afterImageUpdated(e){this._availableImages=this.imageManager.listImages(),this._changedImages[e]=!0,this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.Event("data",{dataType:"style"}));}listImages(){return this._checkLoaded(),this.imageManager.listImages()}addSource(e,i,r={}){if(this._checkLoaded(),void 0!==this.sourceCaches[e])throw new Error(`Source "${e}" already exists.`);if(!i.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(i).join(", ")}.`);if(["vector","raster","geojson","video","image"].indexOf(i.type)>=0&&this._validate(t.validateStyle.source,`sources.${e}`,i,null,r))return;this.map&&this.map._collectResourceTiming&&(i.collectResourceTiming=!0);const o=this.sourceCaches[e]=new ye(e,i,this.dispatcher);o.style=this,o.setEventedParent(this,(()=>({isSourceLoaded:o.loaded(),source:o.serialize(),sourceId:e}))),o.onAdd(this.map),this._changed=!0;}removeSource(e){if(this._checkLoaded(),void 0===this.sourceCaches[e])throw new Error("There is no source with this ID");for(const i in this._layers)if(this._layers[i].source===e)return this.fire(new t.ErrorEvent(new Error(`Source "${e}" cannot be removed while layer "${i}" is using it.`)));const i=this.sourceCaches[e];delete this.sourceCaches[e],delete this._updatedSources[e],i.fire(new t.Event("data",{sourceDataType:"metadata",dataType:"source",sourceId:e})),i.setEventedParent(null),i.onRemove(this.map),this._changed=!0;}setGeoJSONSourceData(e,t){if(this._checkLoaded(),void 0===this.sourceCaches[e])throw new Error(`There is no source with this ID=${e}`);const i=this.sourceCaches[e].getSource();if("geojson"!==i.type)throw new Error(`geojsonSource.type is ${i.type}, which is !== 'geojson`);i.setData(t),this._changed=!0;}getSource(e){return this.sourceCaches[e]&&this.sourceCaches[e].getSource()}addLayer(e,i,r={}){this._checkLoaded();const o=e.id;if(this.getLayer(o))return void this.fire(new t.ErrorEvent(new Error(`Layer "${o}" already exists on this map.`)));let a;if("custom"===e.type){if(mi(this,t.validateCustomStyleLayer(e)))return;a=t.createStyleLayer(e);}else {if("source"in e&&"object"==typeof e.source&&(this.addSource(o,e.source),e=t.clone$2(e),e=t.extend(e,{source:o})),this._validate(t.validateStyle.layer,`layers.${o}`,e,{arrayIndex:-1},r))return;a=t.createStyleLayer(e),this._validateLayer(a),a.setEventedParent(this,{layer:{id:o}});}const s=i?this._order.indexOf(i):this._order.length;if(i&&-1===s)this.fire(new t.ErrorEvent(new Error(`Cannot add layer "${o}" before non-existing layer "${i}".`)));else {if(this._order.splice(s,0,o),this._layerOrderChanged=!0,this._layers[o]=a,this._removedLayers[o]&&a.source&&"custom"!==a.type){const e=this._removedLayers[o];delete this._removedLayers[o],e.type!==a.type?this._updatedSources[a.source]="clear":(this._updatedSources[a.source]="reload",this.sourceCaches[a.source].pause());}this._updateLayer(a),a.onAdd&&a.onAdd(this.map);}}moveLayer(e,i){if(this._checkLoaded(),this._changed=!0,!this._layers[e])return void this.fire(new t.ErrorEvent(new Error(`The layer '${e}' does not exist in the map's style and cannot be moved.`)));if(e===i)return;const r=this._order.indexOf(e);this._order.splice(r,1);const o=i?this._order.indexOf(i):this._order.length;i&&-1===o?this.fire(new t.ErrorEvent(new Error(`Cannot move layer "${e}" before non-existing layer "${i}".`))):(this._order.splice(o,0,e),this._layerOrderChanged=!0);}removeLayer(e){this._checkLoaded();const i=this._layers[e];if(!i)return void this.fire(new t.ErrorEvent(new Error(`Cannot remove non-existing layer "${e}".`)));i.setEventedParent(null);const r=this._order.indexOf(e);this._order.splice(r,1),this._layerOrderChanged=!0,this._changed=!0,this._removedLayers[e]=i,delete this._layers[e],this._serializedLayers&&delete this._serializedLayers[e],delete this._updatedLayers[e],delete this._updatedPaintProps[e],i.onRemove&&i.onRemove(this.map);}getLayer(e){return this._layers[e]}getLayersOrder(){return [...this._order]}hasLayer(e){return e in this._layers}setLayerZoomRange(e,i,r){this._checkLoaded();const o=this.getLayer(e);o?o.minzoom===i&&o.maxzoom===r||(null!=i&&(o.minzoom=i),null!=r&&(o.maxzoom=r),this._updateLayer(o)):this.fire(new t.ErrorEvent(new Error(`Cannot set the zoom range of non-existing layer "${e}".`)));}setFilter(e,i,r={}){this._checkLoaded();const o=this.getLayer(e);if(o){if(!t.deepEqual(o.filter,i))return null==i?(o.filter=void 0,void this._updateLayer(o)):void(this._validate(t.validateStyle.filter,`layers.${o.id}.filter`,i,null,r)||(o.filter=t.clone$2(i),this._updateLayer(o)))}else this.fire(new t.ErrorEvent(new Error(`Cannot filter non-existing layer "${e}".`)));}getFilter(e){return t.clone$2(this.getLayer(e).filter)}setLayoutProperty(e,i,r,o={}){this._checkLoaded();const a=this.getLayer(e);a?t.deepEqual(a.getLayoutProperty(i),r)||(a.setLayoutProperty(i,r,o),this._updateLayer(a)):this.fire(new t.ErrorEvent(new Error(`Cannot style non-existing layer "${e}".`)));}getLayoutProperty(e,i){const r=this.getLayer(e);if(r)return r.getLayoutProperty(i);this.fire(new t.ErrorEvent(new Error(`Cannot get style of non-existing layer "${e}".`)));}setPaintProperty(e,i,r,o={}){this._checkLoaded();const a=this.getLayer(e);a?t.deepEqual(a.getPaintProperty(i),r)||(a.setPaintProperty(i,r,o)&&this._updateLayer(a),this._changed=!0,this._updatedPaintProps[e]=!0,this._serializedLayers=null):this.fire(new t.ErrorEvent(new Error(`Cannot style non-existing layer "${e}".`)));}getPaintProperty(e,t){return this.getLayer(e).getPaintProperty(t)}setFeatureState(e,i){this._checkLoaded();const r=e.source,o=e.sourceLayer,a=this.sourceCaches[r];if(void 0===a)return void this.fire(new t.ErrorEvent(new Error(`The source '${r}' does not exist in the map's style.`)));const s=a.getSource().type;"geojson"===s&&o?this.fire(new t.ErrorEvent(new Error("GeoJSON sources cannot have a sourceLayer parameter."))):"vector"!==s||o?(void 0===e.id&&this.fire(new t.ErrorEvent(new Error("The feature id parameter must be provided."))),a.setFeatureState(o,e.id,i)):this.fire(new t.ErrorEvent(new Error("The sourceLayer parameter must be provided for vector source types.")));}removeFeatureState(e,i){this._checkLoaded();const r=e.source,o=this.sourceCaches[r];if(void 0===o)return void this.fire(new t.ErrorEvent(new Error(`The source '${r}' does not exist in the map's style.`)));const a=o.getSource().type,s="vector"===a?e.sourceLayer:void 0;"vector"!==a||s?i&&"string"!=typeof e.id&&"number"!=typeof e.id?this.fire(new t.ErrorEvent(new Error("A feature id is required to remove its specific state property."))):o.removeFeatureState(s,e.id,i):this.fire(new t.ErrorEvent(new Error("The sourceLayer parameter must be provided for vector source types.")));}getFeatureState(e){this._checkLoaded();const i=e.source,r=e.sourceLayer,o=this.sourceCaches[i];if(void 0!==o)return "vector"!==o.getSource().type||r?(void 0===e.id&&this.fire(new t.ErrorEvent(new Error("The feature id parameter must be provided."))),o.getFeatureState(r,e.id)):void this.fire(new t.ErrorEvent(new Error("The sourceLayer parameter must be provided for vector source types.")));this.fire(new t.ErrorEvent(new Error(`The source '${i}' does not exist in the map's style.`)));}getTransition(){return t.extend({duration:300,delay:0},this.stylesheet&&this.stylesheet.transition)}serialize(){if(!this._loaded)return;const e=t.mapObject(this.sourceCaches,(e=>e.serialize())),i=this._serializeByIds(this._order,!0),r=this.map.getTerrain()||void 0,o=this.stylesheet;return t.filterObject({version:o.version,name:o.name,metadata:o.metadata,light:o.light,sky:o.sky,center:o.center,zoom:o.zoom,bearing:o.bearing,pitch:o.pitch,sprite:o.sprite,glyphs:o.glyphs,transition:o.transition,projection:o.projection,sources:e,layers:i,terrain:r},(e=>void 0!==e))}_updateLayer(e){this._updatedLayers[e.id]=!0,e.source&&!this._updatedSources[e.source]&&"raster"!==this.sourceCaches[e.source].getSource().type&&(this._updatedSources[e.source]="reload",this.sourceCaches[e.source].pause()),this._serializedLayers=null,this._changed=!0;}_flattenAndSortRenderedFeatures(e){const t=e=>"fill-extrusion"===this._layers[e].type,i={},r=[];for(let o=this._order.length-1;o>=0;o--){const a=this._order[o];if(t(a)){i[a]=o;for(const t of e){const e=t[a];if(e)for(const t of e)r.push(t);}}}r.sort(((e,t)=>t.intersectionZ-e.intersectionZ));const o=[];for(let a=this._order.length-1;a>=0;a--){const s=this._order[a];if(t(s))for(let e=r.length-1;e>=0;e--){const t=r[e].feature;if(i[t.layer.id]{const r=i.featureSortOrder;if(r){const i=r.indexOf(e.featureIndex);return r.indexOf(t.featureIndex)-i}return t.featureIndex-e.featureIndex}));for(const e of o)t.push(e);}}for(const t in n)n[t].forEach((r=>{const o=r.feature,a=i[e[t].source].getFeatureState(o.layer["source-layer"],o.id);o.source=o.layer.source,o.layer["source-layer"]&&(o.sourceLayer=o.layer["source-layer"]),o.state=a;}));return n}(this._layers,s,this.sourceCaches,e,l,this.placement.collisionIndex,this.placement.retainedQueryData)),this._flattenAndSortRenderedFeatures(a)}querySourceFeatures(e,i){i&&i.filter&&this._validate(t.validateStyle.filter,"querySourceFeatures.filter",i.filter,null,i);const r=this.sourceCaches[e];return r?function(e,t){const i=e.getRenderableIds().map((t=>e.getTileByID(t))),r=[],o={};for(let e=0;ee.getTileByID(t))).sort(((e,t)=>t.tileID.overscaledZ-e.tileID.overscaledZ||(e.tileID.isLessThan(t.tileID)?-1:1)));}const r=this.crossTileSymbolIndex.addLayer(i,n[i.source],e.center.lng);a=a||r;}if(this.crossTileSymbolIndex.pruneUnusedLayers(this._order),((o=o||this._layerOrderChanged||0===i)||!this.pauseablePlacement||this.pauseablePlacement.isDone()&&!this.placement.stillRecent(f.now(),e.zoom))&&(this.pauseablePlacement=new dt(e,this.map.terrain,this._order,o,t,i,r,this.placement),this._layerOrderChanged=!1),this.pauseablePlacement.isDone()?this.placement.setStale():(this.pauseablePlacement.continuePlacement(this._order,this._layers,n),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(f.now()),s=!0),a&&this.pauseablePlacement.placement.setStale()),s||a)for(const e of this._order){const t=this._layers[e];"symbol"===t.type&&this.placement.updateLayerOpacities(t,n[t.source]);}return !this.pauseablePlacement.isDone()||this.placement.hasTransitions(f.now())}_releaseSymbolFadeTiles(){for(const e in this.sourceCaches)this.sourceCaches[e].releaseSymbolFadeTiles();}getImages(e,i){return t.__awaiter(this,void 0,void 0,(function*(){const e=yield this.imageManager.getImages(i.icons);this._updateTilesForChangedImages();const t=this.sourceCaches[i.source];return t&&t.setDependencies(i.tileID.key,i.type,i.icons),e}))}getGlyphs(e,i){return t.__awaiter(this,void 0,void 0,(function*(){const e=yield this.glyphManager.getGlyphs(i.stacks),t=this.sourceCaches[i.source];return t&&t.setDependencies(i.tileID.key,i.type,[""]),e}))}getGlyphsUrl(){return this.stylesheet.glyphs||null}setGlyphs(e,i={}){this._checkLoaded(),e&&this._validate(t.validateStyle.glyphs,"glyphs",e,null,i)||(this._glyphsDidChange=!0,this.stylesheet.glyphs=e,this.glyphManager.entries={},this.glyphManager.setURL(e));}addSprite(e,i,r={},o){this._checkLoaded();const a=[{id:e,url:i}],s=[...g(this.stylesheet.sprite),...a];this._validate(t.validateStyle.sprite,"sprite",s,null,r)||(this.stylesheet.sprite=s,this._loadSprite(a,!0,o));}removeSprite(e){this._checkLoaded();const i=g(this.stylesheet.sprite);if(i.find((t=>t.id===e))){if(this._spritesImagesIds[e])for(const t of this._spritesImagesIds[e])this.imageManager.removeImage(t),this._changedImages[t]=!0;i.splice(i.findIndex((t=>t.id===e)),1),this.stylesheet.sprite=i.length>0?i:void 0,delete this._spritesImagesIds[e],this._availableImages=this.imageManager.listImages(),this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.Event("data",{dataType:"style"}));}else this.fire(new t.ErrorEvent(new Error(`Sprite "${e}" doesn't exists on this map.`)));}getSprite(){return g(this.stylesheet.sprite)}setSprite(e,i={},r){this._checkLoaded(),e&&this._validate(t.validateStyle.sprite,"sprite",e,null,i)||(this.stylesheet.sprite=e,e?this._loadSprite(e,!0,r):(this._unloadSprite(),r&&r(null)));}}class vi{constructor(e){this._transformRequestFn=e;}transformRequest(e,t){return this._transformRequestFn&&this._transformRequestFn(e,t)||{url:e}}setTransformRequest(e){this._transformRequestFn=e;}}class yi extends t.Evented{constructor(){super(),this._requestManager=new vi,this.transform=new Ft;}getPixelRatio(){return devicePixelRatio}setTerrain(){}_getMapId(){return 1}}class xi{constructor(e,i){this.styleJSON=e,this.sourceID=i,this.layerIndex=new t.StyleLayerIndex(t.derefLayers(this.styleJSON.layers)),this.glyphs={},this.icons={};}loadImages(e){return t.__awaiter(this,void 0,void 0,(function*(){const t=JSON.stringify(e);return this.icons[t]||(this.icons[t]=yield this.style.getImages("",e)),this.icons[t]}))}loadGlyphs(e){return t.__awaiter(this,void 0,void 0,(function*(){const t=JSON.stringify(e);return this.glyphs[t]||(this.glyphs[t]=yield this.style.getGlyphs("",e)),this.glyphs[t]}))}setup(){const e=this;return this.actor={sendAsync(t){if("GI"===t.type)return e.loadImages(t.data);if("GG"===t.type)return e.loadGlyphs(t.data);throw new Error(`Invalid action ${t.type}`)}},Promise.all([(t=this.styleJSON,new Promise(((e,i)=>{const r=new yi,o=new gi(r);r.style=o,o.loadJSON(t),o.on("style.load",(()=>e(o))),o.on("error",i);}))),fetch(this.styleJSON.sources[this.sourceID].url).then((e=>e.json()))]).then((([e,t])=>{this.style=e,this.tileJSON=t;}));var t;}fetchTile(e){return fetch(e.canonical.url(this.tileJSON.tiles,devicePixelRatio)).then((e=>e.arrayBuffer())).then((t=>({tileID:e,buffer:t})))}parseTile(e,i){const r=new t.WorkerTile({type:"benchmark",tileID:e.tileID,zoom:e.tileID.overscaledZ,tileSize:512,showCollisionBoxes:!1,source:this.sourceID,uid:"0",maxZoom:22,pixelRatio:1,request:{url:""},returnDependencies:i,promoteId:void 0,subdivisionGranularity:t.SubdivisionGranularitySetting.noSubdivision}),o=new t.mvt.VectorTile(new t.Protobuf(e.buffer));return r.parse(o,this.layerIndex,[],this.actor,t.SubdivisionGranularitySetting.noSubdivision)}}class bi extends a{constructor(e,i){super(),this.style=e,this.tileIDs=i||[new t.OverscaledTileID(12,0,12,655,1583),new t.OverscaledTileID(8,0,8,40,98),new t.OverscaledTileID(4,0,4,3,6),new t.OverscaledTileID(0,0,0,0,0)];}setup(){return t.__awaiter(this,void 0,void 0,(function*(){const e=yield s(this.style);this.parser=new xi(e,"openmaptiles"),yield this.parser.setup(),this.tiles=yield Promise.all(this.tileIDs.map((e=>this.parser.fetchTile(e)))),yield Promise.all(this.tiles.map((e=>this.parser.parseTile(e))));}))}bench(){return t.__awaiter(this,void 0,void 0,(function*(){for(const e of this.tiles)yield this.parser.parseTile(e);}))}}class wi{static testProp(e){if(!wi.docStyle)return e[0];for(let t=0;t{window.removeEventListener("click",wi.suppressClickInternal,!0);}),0);}static getScale(e){const t=e.getBoundingClientRect();return {x:t.width/e.offsetWidth||1,y:t.height/e.offsetHeight||1,boundingClientRect:t}}static getPoint(e,i,r){const o=i.boundingClientRect;return new t.Point((r.clientX-o.left)/i.x-e.clientLeft,(r.clientY-o.top)/i.y-e.clientTop)}static mousePos(e,t){const i=wi.getScale(e);return wi.getPoint(e,i,t)}static touchPos(e,t){const i=[],r=wi.getScale(e);for(let o=0;o({u_texture:0,u_ele_delta:e,u_fog_matrix:i,u_fog_color:r?r.properties.get("fog-color"):t.Color.white,u_fog_ground_blend:r?r.properties.get("fog-ground-blend"):1,u_fog_ground_blend_opacity:a?0:r?r.calculateFogBlendOpacity(o):0,u_horizon_color:r?r.properties.get("horizon-color"):t.Color.white,u_horizon_fog_blend:r?r.properties.get("horizon-fog-blend"):1,u_is_globe_mode:a?1:0}),Ci={mainMatrix:"u_projection_matrix",tileMercatorCoords:"u_projection_tile_mercator_coords",clippingPlane:"u_projection_clipping_plane",projectionTransition:"u_projection_transition",fallbackMatrix:"u_projection_fallback_matrix"};function Mi(e){const t=[];for(let i=0;i({u_depth:new t.Uniform1i(e,i.u_depth),u_terrain:new t.Uniform1i(e,i.u_terrain),u_terrain_dim:new t.Uniform1f(e,i.u_terrain_dim),u_terrain_matrix:new t.UniformMatrix4f(e,i.u_terrain_matrix),u_terrain_unpack:new t.Uniform4f(e,i.u_terrain_unpack),u_terrain_exaggeration:new t.Uniform1f(e,i.u_terrain_exaggeration)}))(e,E),this.projectionUniforms=((e,i)=>({u_projection_matrix:new t.UniformMatrix4f(e,i.u_projection_matrix),u_projection_tile_mercator_coords:new t.Uniform4f(e,i.u_projection_tile_mercator_coords),u_projection_clipping_plane:new t.Uniform4f(e,i.u_projection_clipping_plane),u_projection_transition:new t.Uniform1f(e,i.u_projection_transition),u_projection_fallback_matrix:new t.UniformMatrix4f(e,i.u_projection_fallback_matrix)}))(e,E),this.binderUniforms=r?r.getUniforms(e,E):[];}draw(e,t,i,r,o,a,s,n,l,c,h,u,d,_,p,m,f,g,v){const y=e.gl;if(this.failedToCreate)return;if(e.program.set(this.program),e.setDepthMode(i),e.setStencilMode(r),e.setColorMode(o),e.setCullFace(a),n){e.activeTexture.set(y.TEXTURE2),y.bindTexture(y.TEXTURE_2D,n.depthTexture),e.activeTexture.set(y.TEXTURE3),y.bindTexture(y.TEXTURE_2D,n.texture);for(const e in this.terrainUniforms)this.terrainUniforms[e].set(n[e]);}if(l)for(const e in l)this.projectionUniforms[Ci[e]].set(l[e]);if(s)for(const e in this.fixedUniforms)this.fixedUniforms[e].set(s[e]);m&&m.setUniforms(e,this.binderUniforms,_,{zoom:p});let x=0;switch(t){case y.LINES:x=2;break;case y.TRIANGLES:x=3;break;case y.LINE_STRIP:x=1;}for(const i of d.get()){const r=i.vaos||(i.vaos={});(r[c]||(r[c]=new Pi)).bind(e,this,h,m?m.getPaintVertexBuffers():[],u,i.vertexOffset,f,g,v),y.drawElements(t,i.primitiveLength*x,y.UNSIGNED_SHORT,i.primitiveOffset*x*2);}}}function Ri(e,i,r){const o=1/t.pixelsToTileUnits(r,1,i.transform.tileZoom),a=Math.pow(2,r.tileID.overscaledZ),s=r.tileSize*Math.pow(2,i.transform.tileZoom)/a,n=s*(r.tileID.canonical.x+r.tileID.wrap*a),l=s*r.tileID.canonical.y;return {u_image:0,u_texsize:r.imageAtlasTexture.size,u_scale:[o,e.fromScale,e.toScale],u_fade:e.t,u_pixel_coord_upper:[n>>16,l>>16],u_pixel_coord_lower:[65535&n,65535&l]}}const Di=(e,i,r,o)=>{const a=e.style.light,s=a.properties.get("position"),n=[s.x,s.y,s.z],l=t.create$2();"viewport"===a.properties.get("anchor")&&t.fromRotation(l,e.transform.bearingInRadians),t.transformMat3(n,n,l);const c=e.transform.transformLightDirection(n),h=a.properties.get("color");return {u_lightpos:n,u_lightpos_globe:c,u_lightintensity:a.properties.get("intensity"),u_lightcolor:[h.r,h.g,h.b],u_vertical_gradient:+i,u_opacity:r,u_fill_translate:o}},zi=(e,i,r,o,a,s,n)=>t.extend(Di(e,i,r,o),Ri(s,e,n),{u_height_factor:-Math.pow(2,a.overscaledZ)/n.tileSize/8}),Li=(e,i,r,o)=>t.extend(Ri(i,e,r),{u_fill_translate:o}),Ai=(e,t)=>({u_world:e,u_fill_translate:t}),ki=(e,i,r,o,a)=>t.extend(Li(e,i,r,a),{u_world:o}),Fi=(e,i,r,o,a)=>{const s=e.transform;let n,l,c=0;if("map"===r.paint.get("circle-pitch-alignment")){const e=t.pixelsToTileUnits(i,1,s.zoom);n=!0,l=[e,e],c=e/(t.EXTENT*Math.pow(2,i.tileID.overscaledZ))*2*Math.PI*a;}else n=!1,l=s.pixelsToGLUnits;return {u_camera_to_center_distance:s.cameraToCenterDistance,u_scale_with_map:+("map"===r.paint.get("circle-pitch-scale")),u_pitch_with_map:+n,u_device_pixel_ratio:e.pixelRatio,u_extrude_scale:l,u_globe_extrude_scale:c,u_translate:o}},Bi=e=>({u_pixel_extrude_scale:[1/e.width,1/e.height]}),Oi=e=>({u_viewport_size:[e.width,e.height]}),Ui=(e,t=1)=>({u_color:e,u_overlay:0,u_overlay_scale:t}),ji=(e,i,r,o)=>{const a=t.pixelsToTileUnits(e,1,i)/(t.EXTENT*Math.pow(2,e.tileID.overscaledZ))*2*Math.PI*o;return {u_extrude_scale:t.pixelsToTileUnits(e,1,i),u_intensity:r,u_globe_extrude_scale:a}},Ni=(e,i,r,o)=>{const a=t.create();t.ortho(a,0,e.width,e.height,0,0,1);const s=e.context.gl;return {u_matrix:a,u_world:[s.drawingBufferWidth,s.drawingBufferHeight],u_image:r,u_color_ramp:o,u_opacity:i.paint.get("heatmap-opacity")}},Gi=(e,t,i)=>{const r=i.paint.get("hillshade-shadow-color"),o=i.paint.get("hillshade-highlight-color"),a=i.paint.get("hillshade-accent-color");let s=i.paint.get("hillshade-illumination-direction")*(Math.PI/180);return "viewport"===i.paint.get("hillshade-illumination-anchor")&&(s+=e.transform.bearingInRadians),{u_image:0,u_latrange:Vi(0,t.tileID),u_light:[i.paint.get("hillshade-exaggeration"),s],u_shadow:r,u_highlight:o,u_accent:a}},Zi=(e,i)=>{const r=i.stride,o=t.create();return t.ortho(o,0,t.EXTENT,-t.EXTENT,0,0,1),t.translate(o,o,[0,-t.EXTENT,0]),{u_matrix:o,u_image:1,u_dimension:[r,r],u_zoom:e.overscaledZ,u_unpack:i.getUnpackVector()}};function Vi(e,i){const r=Math.pow(2,i.canonical.z),o=i.canonical.y;return [new t.MercatorCoordinate(0,o/r).toLngLat().lat,new t.MercatorCoordinate(0,(o+1)/r).toLngLat().lat]}const qi=(e,i,r,o)=>{const a=e.transform;return {u_translation:Ki(e,i,r),u_ratio:o/t.pixelsToTileUnits(i,1,a.zoom),u_device_pixel_ratio:e.pixelRatio,u_units_to_pixels:[1/a.pixelsToGLUnits[0],1/a.pixelsToGLUnits[1]]}},Wi=(e,i,r,o,a)=>t.extend(qi(e,i,r,o),{u_image:0,u_image_height:a}),Xi=(e,i,r,o,a)=>{const s=e.transform,n=Hi(i,s);return {u_translation:Ki(e,i,r),u_texsize:i.imageAtlasTexture.size,u_ratio:o/t.pixelsToTileUnits(i,1,s.zoom),u_device_pixel_ratio:e.pixelRatio,u_image:0,u_scale:[n,a.fromScale,a.toScale],u_fade:a.t,u_units_to_pixels:[1/s.pixelsToGLUnits[0],1/s.pixelsToGLUnits[1]]}},$i=(e,i,r,o,a,s)=>{const n=e.lineAtlas,l=Hi(i,e.transform),c="round"===r.layout.get("line-cap"),h=n.getDash(a.from,c),u=n.getDash(a.to,c),d=h.width*s.fromScale,_=u.width*s.toScale;return t.extend(qi(e,i,r,o),{u_patternscale_a:[l/d,-h.height/2],u_patternscale_b:[l/_,-u.height/2],u_sdfgamma:n.width/(256*Math.min(d,_)*e.pixelRatio)/2,u_image:0,u_tex_y_a:h.y,u_tex_y_b:u.y,u_mix:s.t})};function Hi(e,i){return 1/t.pixelsToTileUnits(e,1,i.tileZoom)}function Ki(e,i,r){return t.translatePosition(e.transform,i,r.paint.get("line-translate"),r.paint.get("line-translate-anchor"))}const Yi=(e,t,i,r,o)=>{return {u_tl_parent:e,u_scale_parent:t,u_buffer_scale:1,u_fade_t:i.mix,u_opacity:i.opacity*r.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:r.paint.get("raster-brightness-min"),u_brightness_high:r.paint.get("raster-brightness-max"),u_saturation_factor:(s=r.paint.get("raster-saturation"),s>0?1-1/(1.001-s):-s),u_contrast_factor:(a=r.paint.get("raster-contrast"),a>0?1/(1-a):1+a),u_spin_weights:Ji(r.paint.get("raster-hue-rotate")),u_coords_top:[o[0].x,o[0].y,o[1].x,o[1].y],u_coords_bottom:[o[3].x,o[3].y,o[2].x,o[2].y]};var a,s;};function Ji(e){e*=Math.PI/180;const t=Math.sin(e),i=Math.cos(e);return [(2*i+1)/3,(-Math.sqrt(3)*t-i+1)/3,(Math.sqrt(3)*t-i+1)/3]}const Qi=(e,t,i,r,o,a,s,n,l,c,h,u,d)=>{const _=s.transform;return {u_is_size_zoom_constant:+("constant"===e||"source"===e),u_is_size_feature_constant:+("constant"===e||"camera"===e),u_size_t:t?t.uSizeT:0,u_size:t?t.uSize:0,u_camera_to_center_distance:_.cameraToCenterDistance,u_pitch:_.pitch/360*2*Math.PI,u_rotate_symbol:+i,u_aspect_ratio:_.width/_.height,u_fade_change:s.options.fadeDuration?s.symbolFadeChange:1,u_label_plane_matrix:n,u_coord_matrix:l,u_is_text:+h,u_pitch_with_map:+r,u_is_along_line:o,u_is_variable_anchor:a,u_texsize:u,u_texture:0,u_translation:c,u_pitched_scale:d}},er=(e,i,r,o,a,s,n,l,c,h,u,d,_,p)=>{const m=n.transform;return t.extend(Qi(e,i,r,o,a,s,n,l,c,h,u,d,p),{u_gamma_scale:o?Math.cos(m.pitch*Math.PI/180)*m.cameraToCenterDistance:1,u_device_pixel_ratio:n.pixelRatio,u_is_halo:+_})},tr=(e,i,r,o,a,s,n,l,c,h,u,d,_)=>t.extend(er(e,i,r,o,a,s,n,l,c,h,!0,u,!0,_),{u_texsize_icon:d,u_texture_icon:1}),ir=(e,t)=>({u_opacity:e,u_color:t}),rr=(e,i,r,o,a)=>t.extend(function(e,i,r,o){const a=r.imageManager.getPattern(e.from.toString()),s=r.imageManager.getPattern(e.to.toString()),{width:n,height:l}=r.imageManager.getPixelSize(),c=Math.pow(2,o.tileID.overscaledZ),h=o.tileSize*Math.pow(2,r.transform.tileZoom)/c,u=h*(o.tileID.canonical.x+o.tileID.wrap*c),d=h*o.tileID.canonical.y;return {u_image:0,u_pattern_tl_a:a.tl,u_pattern_br_a:a.br,u_pattern_tl_b:s.tl,u_pattern_br_b:s.br,u_texsize:[n,l],u_mix:i.t,u_pattern_size_a:a.displaySize,u_pattern_size_b:s.displaySize,u_scale_a:i.fromScale,u_scale_b:i.toScale,u_tile_units_to_pixels:1/t.pixelsToTileUnits(o,1,r.transform.tileZoom),u_pixel_coord_upper:[u>>16,d>>16],u_pixel_coord_lower:[65535&u,65535&d]}}(r,a,i,o),{u_opacity:e}),or=(e,t)=>{},ar={fillExtrusion:(e,i)=>({u_lightpos:new t.Uniform3f(e,i.u_lightpos),u_lightpos_globe:new t.Uniform3f(e,i.u_lightpos_globe),u_lightintensity:new t.Uniform1f(e,i.u_lightintensity),u_lightcolor:new t.Uniform3f(e,i.u_lightcolor),u_vertical_gradient:new t.Uniform1f(e,i.u_vertical_gradient),u_opacity:new t.Uniform1f(e,i.u_opacity),u_fill_translate:new t.Uniform2f(e,i.u_fill_translate)}),fillExtrusionPattern:(e,i)=>({u_lightpos:new t.Uniform3f(e,i.u_lightpos),u_lightpos_globe:new t.Uniform3f(e,i.u_lightpos_globe),u_lightintensity:new t.Uniform1f(e,i.u_lightintensity),u_lightcolor:new t.Uniform3f(e,i.u_lightcolor),u_vertical_gradient:new t.Uniform1f(e,i.u_vertical_gradient),u_height_factor:new t.Uniform1f(e,i.u_height_factor),u_opacity:new t.Uniform1f(e,i.u_opacity),u_fill_translate:new t.Uniform2f(e,i.u_fill_translate),u_image:new t.Uniform1i(e,i.u_image),u_texsize:new t.Uniform2f(e,i.u_texsize),u_pixel_coord_upper:new t.Uniform2f(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.Uniform2f(e,i.u_pixel_coord_lower),u_scale:new t.Uniform3f(e,i.u_scale),u_fade:new t.Uniform1f(e,i.u_fade)}),fill:(e,i)=>({u_fill_translate:new t.Uniform2f(e,i.u_fill_translate)}),fillPattern:(e,i)=>({u_image:new t.Uniform1i(e,i.u_image),u_texsize:new t.Uniform2f(e,i.u_texsize),u_pixel_coord_upper:new t.Uniform2f(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.Uniform2f(e,i.u_pixel_coord_lower),u_scale:new t.Uniform3f(e,i.u_scale),u_fade:new t.Uniform1f(e,i.u_fade),u_fill_translate:new t.Uniform2f(e,i.u_fill_translate)}),fillOutline:(e,i)=>({u_world:new t.Uniform2f(e,i.u_world),u_fill_translate:new t.Uniform2f(e,i.u_fill_translate)}),fillOutlinePattern:(e,i)=>({u_world:new t.Uniform2f(e,i.u_world),u_image:new t.Uniform1i(e,i.u_image),u_texsize:new t.Uniform2f(e,i.u_texsize),u_pixel_coord_upper:new t.Uniform2f(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.Uniform2f(e,i.u_pixel_coord_lower),u_scale:new t.Uniform3f(e,i.u_scale),u_fade:new t.Uniform1f(e,i.u_fade),u_fill_translate:new t.Uniform2f(e,i.u_fill_translate)}),circle:(e,i)=>({u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_scale_with_map:new t.Uniform1i(e,i.u_scale_with_map),u_pitch_with_map:new t.Uniform1i(e,i.u_pitch_with_map),u_extrude_scale:new t.Uniform2f(e,i.u_extrude_scale),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_globe_extrude_scale:new t.Uniform1f(e,i.u_globe_extrude_scale),u_translate:new t.Uniform2f(e,i.u_translate)}),collisionBox:(e,i)=>({u_pixel_extrude_scale:new t.Uniform2f(e,i.u_pixel_extrude_scale)}),collisionCircle:(e,i)=>({u_viewport_size:new t.Uniform2f(e,i.u_viewport_size)}),debug:(e,i)=>({u_color:new t.UniformColor(e,i.u_color),u_overlay:new t.Uniform1i(e,i.u_overlay),u_overlay_scale:new t.Uniform1f(e,i.u_overlay_scale)}),depth:or,clippingMask:or,heatmap:(e,i)=>({u_extrude_scale:new t.Uniform1f(e,i.u_extrude_scale),u_intensity:new t.Uniform1f(e,i.u_intensity),u_globe_extrude_scale:new t.Uniform1f(e,i.u_globe_extrude_scale)}),heatmapTexture:(e,i)=>({u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_world:new t.Uniform2f(e,i.u_world),u_image:new t.Uniform1i(e,i.u_image),u_color_ramp:new t.Uniform1i(e,i.u_color_ramp),u_opacity:new t.Uniform1f(e,i.u_opacity)}),hillshade:(e,i)=>({u_image:new t.Uniform1i(e,i.u_image),u_latrange:new t.Uniform2f(e,i.u_latrange),u_light:new t.Uniform2f(e,i.u_light),u_shadow:new t.UniformColor(e,i.u_shadow),u_highlight:new t.UniformColor(e,i.u_highlight),u_accent:new t.UniformColor(e,i.u_accent)}),hillshadePrepare:(e,i)=>({u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_image:new t.Uniform1i(e,i.u_image),u_dimension:new t.Uniform2f(e,i.u_dimension),u_zoom:new t.Uniform1f(e,i.u_zoom),u_unpack:new t.Uniform4f(e,i.u_unpack)}),line:(e,i)=>({u_translation:new t.Uniform2f(e,i.u_translation),u_ratio:new t.Uniform1f(e,i.u_ratio),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.Uniform2f(e,i.u_units_to_pixels)}),lineGradient:(e,i)=>({u_translation:new t.Uniform2f(e,i.u_translation),u_ratio:new t.Uniform1f(e,i.u_ratio),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.Uniform2f(e,i.u_units_to_pixels),u_image:new t.Uniform1i(e,i.u_image),u_image_height:new t.Uniform1f(e,i.u_image_height)}),linePattern:(e,i)=>({u_translation:new t.Uniform2f(e,i.u_translation),u_texsize:new t.Uniform2f(e,i.u_texsize),u_ratio:new t.Uniform1f(e,i.u_ratio),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_image:new t.Uniform1i(e,i.u_image),u_units_to_pixels:new t.Uniform2f(e,i.u_units_to_pixels),u_scale:new t.Uniform3f(e,i.u_scale),u_fade:new t.Uniform1f(e,i.u_fade)}),lineSDF:(e,i)=>({u_translation:new t.Uniform2f(e,i.u_translation),u_ratio:new t.Uniform1f(e,i.u_ratio),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.Uniform2f(e,i.u_units_to_pixels),u_patternscale_a:new t.Uniform2f(e,i.u_patternscale_a),u_patternscale_b:new t.Uniform2f(e,i.u_patternscale_b),u_sdfgamma:new t.Uniform1f(e,i.u_sdfgamma),u_image:new t.Uniform1i(e,i.u_image),u_tex_y_a:new t.Uniform1f(e,i.u_tex_y_a),u_tex_y_b:new t.Uniform1f(e,i.u_tex_y_b),u_mix:new t.Uniform1f(e,i.u_mix)}),raster:(e,i)=>({u_tl_parent:new t.Uniform2f(e,i.u_tl_parent),u_scale_parent:new t.Uniform1f(e,i.u_scale_parent),u_buffer_scale:new t.Uniform1f(e,i.u_buffer_scale),u_fade_t:new t.Uniform1f(e,i.u_fade_t),u_opacity:new t.Uniform1f(e,i.u_opacity),u_image0:new t.Uniform1i(e,i.u_image0),u_image1:new t.Uniform1i(e,i.u_image1),u_brightness_low:new t.Uniform1f(e,i.u_brightness_low),u_brightness_high:new t.Uniform1f(e,i.u_brightness_high),u_saturation_factor:new t.Uniform1f(e,i.u_saturation_factor),u_contrast_factor:new t.Uniform1f(e,i.u_contrast_factor),u_spin_weights:new t.Uniform3f(e,i.u_spin_weights),u_coords_top:new t.Uniform4f(e,i.u_coords_top),u_coords_bottom:new t.Uniform4f(e,i.u_coords_bottom)}),symbolIcon:(e,i)=>({u_is_size_zoom_constant:new t.Uniform1i(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.Uniform1i(e,i.u_is_size_feature_constant),u_size_t:new t.Uniform1f(e,i.u_size_t),u_size:new t.Uniform1f(e,i.u_size),u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_pitch:new t.Uniform1f(e,i.u_pitch),u_rotate_symbol:new t.Uniform1i(e,i.u_rotate_symbol),u_aspect_ratio:new t.Uniform1f(e,i.u_aspect_ratio),u_fade_change:new t.Uniform1f(e,i.u_fade_change),u_label_plane_matrix:new t.UniformMatrix4f(e,i.u_label_plane_matrix),u_coord_matrix:new t.UniformMatrix4f(e,i.u_coord_matrix),u_is_text:new t.Uniform1i(e,i.u_is_text),u_pitch_with_map:new t.Uniform1i(e,i.u_pitch_with_map),u_is_along_line:new t.Uniform1i(e,i.u_is_along_line),u_is_variable_anchor:new t.Uniform1i(e,i.u_is_variable_anchor),u_texsize:new t.Uniform2f(e,i.u_texsize),u_texture:new t.Uniform1i(e,i.u_texture),u_translation:new t.Uniform2f(e,i.u_translation),u_pitched_scale:new t.Uniform1f(e,i.u_pitched_scale)}),symbolSDF:(e,i)=>({u_is_size_zoom_constant:new t.Uniform1i(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.Uniform1i(e,i.u_is_size_feature_constant),u_size_t:new t.Uniform1f(e,i.u_size_t),u_size:new t.Uniform1f(e,i.u_size),u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_pitch:new t.Uniform1f(e,i.u_pitch),u_rotate_symbol:new t.Uniform1i(e,i.u_rotate_symbol),u_aspect_ratio:new t.Uniform1f(e,i.u_aspect_ratio),u_fade_change:new t.Uniform1f(e,i.u_fade_change),u_label_plane_matrix:new t.UniformMatrix4f(e,i.u_label_plane_matrix),u_coord_matrix:new t.UniformMatrix4f(e,i.u_coord_matrix),u_is_text:new t.Uniform1i(e,i.u_is_text),u_pitch_with_map:new t.Uniform1i(e,i.u_pitch_with_map),u_is_along_line:new t.Uniform1i(e,i.u_is_along_line),u_is_variable_anchor:new t.Uniform1i(e,i.u_is_variable_anchor),u_texsize:new t.Uniform2f(e,i.u_texsize),u_texture:new t.Uniform1i(e,i.u_texture),u_gamma_scale:new t.Uniform1f(e,i.u_gamma_scale),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_is_halo:new t.Uniform1i(e,i.u_is_halo),u_translation:new t.Uniform2f(e,i.u_translation),u_pitched_scale:new t.Uniform1f(e,i.u_pitched_scale)}),symbolTextAndIcon:(e,i)=>({u_is_size_zoom_constant:new t.Uniform1i(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.Uniform1i(e,i.u_is_size_feature_constant),u_size_t:new t.Uniform1f(e,i.u_size_t),u_size:new t.Uniform1f(e,i.u_size),u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_pitch:new t.Uniform1f(e,i.u_pitch),u_rotate_symbol:new t.Uniform1i(e,i.u_rotate_symbol),u_aspect_ratio:new t.Uniform1f(e,i.u_aspect_ratio),u_fade_change:new t.Uniform1f(e,i.u_fade_change),u_label_plane_matrix:new t.UniformMatrix4f(e,i.u_label_plane_matrix),u_coord_matrix:new t.UniformMatrix4f(e,i.u_coord_matrix),u_is_text:new t.Uniform1i(e,i.u_is_text),u_pitch_with_map:new t.Uniform1i(e,i.u_pitch_with_map),u_is_along_line:new t.Uniform1i(e,i.u_is_along_line),u_is_variable_anchor:new t.Uniform1i(e,i.u_is_variable_anchor),u_texsize:new t.Uniform2f(e,i.u_texsize),u_texsize_icon:new t.Uniform2f(e,i.u_texsize_icon),u_texture:new t.Uniform1i(e,i.u_texture),u_texture_icon:new t.Uniform1i(e,i.u_texture_icon),u_gamma_scale:new t.Uniform1f(e,i.u_gamma_scale),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_is_halo:new t.Uniform1i(e,i.u_is_halo),u_translation:new t.Uniform2f(e,i.u_translation),u_pitched_scale:new t.Uniform1f(e,i.u_pitched_scale)}),background:(e,i)=>({u_opacity:new t.Uniform1f(e,i.u_opacity),u_color:new t.UniformColor(e,i.u_color)}),backgroundPattern:(e,i)=>({u_opacity:new t.Uniform1f(e,i.u_opacity),u_image:new t.Uniform1i(e,i.u_image),u_pattern_tl_a:new t.Uniform2f(e,i.u_pattern_tl_a),u_pattern_br_a:new t.Uniform2f(e,i.u_pattern_br_a),u_pattern_tl_b:new t.Uniform2f(e,i.u_pattern_tl_b),u_pattern_br_b:new t.Uniform2f(e,i.u_pattern_br_b),u_texsize:new t.Uniform2f(e,i.u_texsize),u_mix:new t.Uniform1f(e,i.u_mix),u_pattern_size_a:new t.Uniform2f(e,i.u_pattern_size_a),u_pattern_size_b:new t.Uniform2f(e,i.u_pattern_size_b),u_scale_a:new t.Uniform1f(e,i.u_scale_a),u_scale_b:new t.Uniform1f(e,i.u_scale_b),u_pixel_coord_upper:new t.Uniform2f(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.Uniform2f(e,i.u_pixel_coord_lower),u_tile_units_to_pixels:new t.Uniform1f(e,i.u_tile_units_to_pixels)}),terrain:(e,i)=>({u_texture:new t.Uniform1i(e,i.u_texture),u_ele_delta:new t.Uniform1f(e,i.u_ele_delta),u_fog_matrix:new t.UniformMatrix4f(e,i.u_fog_matrix),u_fog_color:new t.UniformColor(e,i.u_fog_color),u_fog_ground_blend:new t.Uniform1f(e,i.u_fog_ground_blend),u_fog_ground_blend_opacity:new t.Uniform1f(e,i.u_fog_ground_blend_opacity),u_horizon_color:new t.UniformColor(e,i.u_horizon_color),u_horizon_fog_blend:new t.Uniform1f(e,i.u_horizon_fog_blend),u_is_globe_mode:new t.Uniform1f(e,i.u_is_globe_mode)}),terrainDepth:(e,i)=>({u_ele_delta:new t.Uniform1f(e,i.u_ele_delta)}),terrainCoords:(e,i)=>({u_texture:new t.Uniform1i(e,i.u_texture),u_terrain_coords_id:new t.Uniform1f(e,i.u_terrain_coords_id),u_ele_delta:new t.Uniform1f(e,i.u_ele_delta)}),projectionErrorMeasurement:(e,i)=>({u_input:new t.Uniform1f(e,i.u_input),u_output_expected:new t.Uniform1f(e,i.u_output_expected)}),atmosphere:(e,i)=>({u_sun_pos:new t.Uniform3f(e,i.u_sun_pos),u_atmosphere_blend:new t.Uniform1f(e,i.u_atmosphere_blend),u_globe_position:new t.Uniform3f(e,i.u_globe_position),u_globe_radius:new t.Uniform1f(e,i.u_globe_radius),u_inv_proj_matrix:new t.UniformMatrix4f(e,i.u_inv_proj_matrix)}),sky:(e,i)=>({u_sky_color:new t.UniformColor(e,i.u_sky_color),u_horizon_color:new t.UniformColor(e,i.u_horizon_color),u_horizon:new t.Uniform2f(e,i.u_horizon),u_horizon_normal:new t.Uniform2f(e,i.u_horizon_normal),u_sky_horizon_blend:new t.Uniform1f(e,i.u_sky_horizon_blend),u_sky_blend:new t.Uniform1f(e,i.u_sky_blend)})};class sr{constructor(e,t,i){this.context=e;const r=e.gl;this.buffer=r.createBuffer(),this.dynamicDraw=Boolean(i),this.context.unbindVAO(),e.bindElementBuffer.set(this.buffer),r.bufferData(r.ELEMENT_ARRAY_BUFFER,t.arrayBuffer,this.dynamicDraw?r.DYNAMIC_DRAW:r.STATIC_DRAW),this.dynamicDraw||delete t.arrayBuffer;}bind(){this.context.bindElementBuffer.set(this.buffer);}updateData(e){const t=this.context.gl;if(!this.dynamicDraw)throw new Error("Attempted to update data while not in dynamic mode.");this.context.unbindVAO(),this.bind(),t.bufferSubData(t.ELEMENT_ARRAY_BUFFER,0,e.arrayBuffer);}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer);}}const nr={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class lr{constructor(e,t,i,r){this.length=t.length,this.attributes=i,this.itemSize=t.bytesPerElement,this.dynamicDraw=r,this.context=e;const o=e.gl;this.buffer=o.createBuffer(),e.bindVertexBuffer.set(this.buffer),o.bufferData(o.ARRAY_BUFFER,t.arrayBuffer,this.dynamicDraw?o.DYNAMIC_DRAW:o.STATIC_DRAW),this.dynamicDraw||delete t.arrayBuffer;}bind(){this.context.bindVertexBuffer.set(this.buffer);}updateData(e){if(e.length!==this.length)throw new Error(`Length of new data is ${e.length}, which doesn't match current length of ${this.length}`);const t=this.context.gl;this.bind(),t.bufferSubData(t.ARRAY_BUFFER,0,e.arrayBuffer);}enableAttributes(e,t){for(let i=0;i0&&(h.push({circleArray:f,circleOffset:d,coord:_}),u+=f.length/4,d=u),m&&c.draw(s,l.LINES,Zt.disabled,qt.disabled,e.colorModeForRenderPass(),Gt.disabled,Bi(e.transform),e.style.map.terrain&&e.style.map.terrain.getTerrainData(_),n.getProjectionData({overscaledTileID:_,applyGlobeMatrix:!0,applyTerrainMatrix:!0}),r.id,m.layoutVertexBuffer,m.indexBuffer,m.segments,null,e.transform.zoom,null,null,m.collisionVertexBuffer);}if(!a||!h.length)return;const _=e.useProgram("collisionCircle"),p=new t.CollisionCircleLayoutArray;p.resize(4*u),p._trim();let m=0;for(const e of h)for(let t=0;t=0&&(f[g.associatedIconIndex]={shiftedAnchor:M,angle:S});}else Ve(g.numGlyphs,p);}if(c){m.clear();const i=e.icon.placedSymbolArray;for(let e=0;ee.style.map.terrain.getElevation(l,t,i):null,i="map"===r.layout.get("text-rotation-alignment");De(c,e,a,O,U,v,h,i,l.toUnwrapped(),f.width,f.height,N,t);}const q=a&&E||V,W=y||q?Hr:v?O:e.transform.clipSpaceToPixelsMatrix,X=p&&0!==r.paint.get(a?"text-halo-width":"icon-halo-width").constantOr(1);let $;$=p?c.iconsInText?tr(T.kind,S,x,v,y,q,e,W,j,N,D,k,I):er(T.kind,S,x,v,y,q,e,W,j,N,a,D,!0,I):Qi(T.kind,S,x,v,y,q,e,W,j,N,a,D,I);const H={program:M,buffers:u,uniformValues:$,projectionData:G,atlasTexture:z,atlasTextureIcon:F,atlasInterpolation:L,atlasInterpolationIcon:A,isSDF:p,hasHalo:X};if(b&&c.canOverlap){w=!0;const e=u.segments.get();for(const i of e)P.push({segments:new t.SegmentVector([i]),sortKey:i.sortKey,state:H,terrainData:R});}else P.push({segments:u.segments,sortKey:0,state:H,terrainData:R});}w&&P.sort(((e,t)=>e.sortKey-t.sortKey));for(const t of P){const i=t.state;if(p.activeTexture.set(m.TEXTURE0),i.atlasTexture.bind(i.atlasInterpolation,m.CLAMP_TO_EDGE),i.atlasTextureIcon&&(p.activeTexture.set(m.TEXTURE1),i.atlasTextureIcon&&i.atlasTextureIcon.bind(i.atlasInterpolationIcon,m.CLAMP_TO_EDGE)),i.isSDF){const o=i.uniformValues;i.hasHalo&&(o.u_is_halo=1,to(i.buffers,t.segments,r,e,i.program,T,u,d,o,i.projectionData,t.terrainData)),o.u_is_halo=0;}to(i.buffers,t.segments,r,e,i.program,T,u,d,i.uniformValues,i.projectionData,t.terrainData);}}function to(e,t,i,r,o,a,s,n,l,c,h){const u=r.context;o.draw(u,u.gl.TRIANGLES,a,s,n,Gt.backCCW,l,h,c,i.id,e.layoutVertexBuffer,e.indexBuffer,t,i.paint,r.transform.zoom,e.programConfigurations.get(i.id),e.dynamicLayoutVertexBuffer,e.opacityVertexBuffer);}function io(e,i,r,o,a){const s=e.context,n=s.gl,l=qt.disabled,c=new jt([n.ONE,n.ONE],t.Color.transparent,[!0,!0,!0,!0]),h=i.getBucket(r);if(!h)return;const u=o.key;let d=r.heatmapFbos.get(u);d||(d=oo(s,i.tileSize,i.tileSize),r.heatmapFbos.set(u,d)),s.bindFramebuffer.set(d.framebuffer),s.viewport.set([0,0,i.tileSize,i.tileSize]),s.clear({color:t.Color.transparent});const _=h.programConfigurations.get(r.id),p=e.useProgram("heatmap",_,!a),m=e.transform.getProjectionData({overscaledTileID:i.tileID,applyGlobeMatrix:!0,applyTerrainMatrix:!0}),f=e.style.map.terrain.getTerrainData(o);p.draw(s,n.TRIANGLES,Zt.disabled,l,c,Gt.disabled,ji(i,e.transform.zoom,r.paint.get("heatmap-intensity"),1),f,m,r.id,h.layoutVertexBuffer,h.indexBuffer,h.segments,r.paint,e.transform.zoom,_);}function ro(e,t,i,r,o){const a=e.context,s=a.gl,n=e.transform;a.setColorMode(e.colorModeForRenderPass());const l=ao(a,t),c=i.key,h=t.heatmapFbos.get(c);if(!h)return;a.activeTexture.set(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,h.colorAttachment.get()),a.activeTexture.set(s.TEXTURE1),l.bind(s.LINEAR,s.CLAMP_TO_EDGE);const u=n.getProjectionData({overscaledTileID:i,applyTerrainMatrix:o,applyGlobeMatrix:!r});e.useProgram("heatmapTexture").draw(a,s.TRIANGLES,Zt.disabled,qt.disabled,e.colorModeForRenderPass(),Gt.disabled,Ni(e,t,0,1),null,u,t.id,e.rasterBoundsBuffer,e.quadTriangleIndexBuffer,e.rasterBoundsSegments,t.paint,n.zoom),h.destroy(),t.heatmapFbos.delete(c);}function oo(e,t,i){var r,o;const a=e.gl,s=a.createTexture();a.bindTexture(a.TEXTURE_2D,s),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,a.LINEAR);const n=null!==(r=e.HALF_FLOAT)&&void 0!==r?r:a.UNSIGNED_BYTE,l=null!==(o=e.RGBA16F)&&void 0!==o?o:a.RGBA;a.texImage2D(a.TEXTURE_2D,0,l,t,i,0,a.RGBA,n,null);const c=e.createFramebuffer(t,i,!1,!1);return c.colorAttachment.set(s),c}function ao(e,t){return t.colorRampTexture||(t.colorRampTexture=new y(e,t.colorRamp,e.gl.RGBA)),t.colorRampTexture}function so(e,t,i,r,o){if(!i||!r||!r.imageAtlas)return;const a=r.imageAtlas.patternPositions;let s=a[i.to.toString()],n=a[i.from.toString()];if(!s&&n&&(s=n),!n&&s&&(n=s),!s||!n){const e=o.getPaintProperty(t);s=a[e],n=a[e];}s&&n&&e.setConstantPatternPositions(s,n);}function no(e,i,r,o,a,s,n,l){const c=e.context.gl,h="fill-pattern",u=r.paint.get(h),d=u&&u.constantOr(1),_=r.getCrossfadeParameters();let p,m,f,g,v;const y=e.transform,x=r.paint.get("fill-translate"),b=r.paint.get("fill-translate-anchor");n?(m=d&&!r.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",p=c.LINES):(m=d?"fillPattern":"fill",p=c.TRIANGLES);const w=u.constantOr(null);for(const u of o){const T=i.getTile(u);if(d&&!T.patternsLoaded())continue;const E=T.getBucket(r);if(!E)continue;const P=E.programConfigurations.get(r.id),I=e.useProgram(m,P),C=e.style.map.terrain&&e.style.map.terrain.getTerrainData(u);d&&(e.context.activeTexture.set(c.TEXTURE0),T.imageAtlasTexture.bind(c.LINEAR,c.CLAMP_TO_EDGE),P.updatePaintBuffers(_)),so(P,h,w,T,r);const M=y.getProjectionData({overscaledTileID:u,applyGlobeMatrix:!l,applyTerrainMatrix:!0}),S=t.translatePosition(y,T,x,b);if(n){g=E.indexBuffer2,v=E.segments2;const t=[c.drawingBufferWidth,c.drawingBufferHeight];f="fillOutlinePattern"===m&&d?ki(e,_,T,t,S):Ai(t,S);}else g=E.indexBuffer,v=E.segments,f=d?Li(e,_,T,S):{u_fill_translate:S};let R;if("translucent"===e.renderPass&&l){const[t]=e.getStencilConfigForOverlapAndUpdateStencilID(o);R=t[u.overscaledZ];}else R=e.stencilModeForClipping(u);I.draw(e.context,p,a,R,s,Gt.backCCW,f,C,M,r.id,E.layoutVertexBuffer,g,v,r.paint,e.transform.zoom,P);}}function lo(e,i,r,o,a,s,n,l){const c=e.context,h=c.gl,u="fill-extrusion-pattern",d=r.paint.get(u),_=d.constantOr(1),p=r.getCrossfadeParameters(),m=r.paint.get("fill-extrusion-opacity"),f=d.constantOr(null),g=e.transform;for(const d of o){const o=i.getTile(d),v=o.getBucket(r);if(!v)continue;const y=e.style.map.terrain&&e.style.map.terrain.getTerrainData(d),x=v.programConfigurations.get(r.id),b=e.useProgram(_?"fillExtrusionPattern":"fillExtrusion",x);_&&(e.context.activeTexture.set(h.TEXTURE0),o.imageAtlasTexture.bind(h.LINEAR,h.CLAMP_TO_EDGE),x.updatePaintBuffers(p));const w=g.getProjectionData({overscaledTileID:d,applyGlobeMatrix:!l,applyTerrainMatrix:!0});so(x,u,f,o,r);const T=t.translatePosition(g,o,r.paint.get("fill-extrusion-translate"),r.paint.get("fill-extrusion-translate-anchor")),E=r.paint.get("fill-extrusion-vertical-gradient"),P=_?zi(e,E,m,T,d,p,o):Di(e,E,m,T);b.draw(c,c.gl.TRIANGLES,a,s,n,Gt.backCCW,P,y,w,r.id,v.layoutVertexBuffer,v.indexBuffer,v.segments,r.paint,e.transform.zoom,x,e.style.map.terrain&&v.centroidVertexBuffer);}}function co(e,t,i,r,o,a,s,n,l){var c;const h=e.style.projection,u=e.context,d=e.transform,_=u.gl,p=e.useProgram("hillshade"),m=!e.options.moving;for(const f of r){const r=t.getTile(f),g=r.fbo;if(!g)continue;const v=h.getMeshFromTileID(u,f.canonical,n,!0,"raster"),y=null===(c=e.style.map.terrain)||void 0===c?void 0:c.getTerrainData(f);u.activeTexture.set(_.TEXTURE0),_.bindTexture(_.TEXTURE_2D,g.colorAttachment.get());const x=d.getProjectionData({overscaledTileID:f,aligned:m,applyGlobeMatrix:!l,applyTerrainMatrix:!0});p.draw(u,_.TRIANGLES,a,o[f.overscaledZ],s,Gt.backCCW,Gi(e,r,i),y,x,i.id,v.vertexBuffer,v.indexBuffer,v.segments);}}const ho=[new t.Point(0,0),new t.Point(t.EXTENT,0),new t.Point(t.EXTENT,t.EXTENT),new t.Point(0,t.EXTENT)];function uo(e,t,i,r,o,a,s,n,l=!1,c=!1){const h=r[r.length-1].overscaledZ,u=e.context,d=u.gl,_=e.useProgram("raster"),p=e.transform,m=e.style.projection,f=e.colorModeForRenderPass(),g=!e.options.moving;for(const v of r){const r=e.getDepthModeForSublayer(v.overscaledZ-h,1===i.paint.get("raster-opacity")?Zt.ReadWrite:Zt.ReadOnly,d.LESS),y=t.getTile(v);y.registerFadeDuration(i.paint.get("raster-fade-duration"));const x=t.findLoadedParent(v,0),b=t.findLoadedSibling(v),w=_o(y,x||b||null,t,i,e.transform,e.style.map.terrain);let T,E;const P="nearest"===i.paint.get("raster-resampling")?d.NEAREST:d.LINEAR;u.activeTexture.set(d.TEXTURE0),y.texture.bind(P,d.CLAMP_TO_EDGE,d.LINEAR_MIPMAP_NEAREST),u.activeTexture.set(d.TEXTURE1),x?(x.texture.bind(P,d.CLAMP_TO_EDGE,d.LINEAR_MIPMAP_NEAREST),T=Math.pow(2,x.tileID.overscaledZ-y.tileID.overscaledZ),E=[y.tileID.canonical.x*T%1,y.tileID.canonical.y*T%1]):y.texture.bind(P,d.CLAMP_TO_EDGE,d.LINEAR_MIPMAP_NEAREST),y.texture.useMipmap&&u.extTextureFilterAnisotropic&&e.transform.pitch>20&&d.texParameterf(d.TEXTURE_2D,u.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,u.extTextureFilterAnisotropicMax);const I=e.style.map.terrain&&e.style.map.terrain.getTerrainData(v),C=p.getProjectionData({overscaledTileID:v,aligned:g,applyGlobeMatrix:!c,applyTerrainMatrix:!0}),M=Yi(E||[0,0],T||1,w,i,n),S=m.getMeshFromTileID(u,v.canonical,a,s,"raster");_.draw(u,d.TRIANGLES,r,o?o[v.overscaledZ]:qt.disabled,f,l?Gt.frontCCW:Gt.backCCW,M,I,C,i.id,S.vertexBuffer,S.indexBuffer,S.segments);}}function _o(e,i,r,o,a,s){const n=o.paint.get("raster-fade-duration");if(!s&&n>0){const o=f.now(),s=(o-e.timeAdded)/n,l=i?(o-i.timeAdded)/n:-1,c=r.getSource(),h=ge(a,{tileSize:c.tileSize,roundZoom:c.roundZoom}),u=!i||Math.abs(i.tileID.overscaledZ-h)>Math.abs(e.tileID.overscaledZ-h),d=u&&e.refreshedUponExpiration?1:t.clamp(u?s:1-l,0,1);return e.refreshedUponExpiration&&s>=1&&(e.refreshedUponExpiration=!1),i?{opacity:1,mix:1-d}:{opacity:d,mix:0}}return {opacity:1,mix:0}}const po=new t.Color(1,0,0,1),mo=new t.Color(0,1,0,1),fo=new t.Color(0,0,1,1),go=new t.Color(1,0,1,1),vo=new t.Color(0,1,1,1);function yo(e,t,i,r){bo(e,0,t+i/2,e.transform.width,i,r);}function xo(e,t,i,r){bo(e,t-i/2,0,i,e.transform.height,r);}function bo(e,t,i,r,o,a){const s=e.context,n=s.gl;n.enable(n.SCISSOR_TEST),n.scissor(t*e.pixelRatio,i*e.pixelRatio,r*e.pixelRatio,o*e.pixelRatio),s.clear({color:a}),n.disable(n.SCISSOR_TEST);}function wo(e,i,r){const o=e.context,a=o.gl,s=e.useProgram("debug"),n=Zt.disabled,l=qt.disabled,c=e.colorModeForRenderPass(),h="$debug",u=e.style.map.terrain&&e.style.map.terrain.getTerrainData(r);o.activeTexture.set(a.TEXTURE0);const d=i.getTileByID(r.key).latestRawTileData,_=Math.floor((d&&d.byteLength||0)/1024),p=i.getTile(r).tileSize,m=512/Math.min(p,512)*(r.overscaledZ/e.transform.zoom)*.5;let f=r.canonical.toString();r.overscaledZ!==r.canonical.z&&(f+=` => ${r.overscaledZ}`),function(e,t){e.initDebugOverlayCanvas();const i=e.debugOverlayCanvas,r=e.context.gl,o=e.debugOverlayCanvas.getContext("2d");o.clearRect(0,0,i.width,i.height),o.shadowColor="white",o.shadowBlur=2,o.lineWidth=1.5,o.strokeStyle="white",o.textBaseline="top",o.font="bold 36px Open Sans, sans-serif",o.fillText(t,5,5),o.strokeText(t,5,5),e.debugOverlayTexture.update(i),e.debugOverlayTexture.bind(r.LINEAR,r.CLAMP_TO_EDGE);}(e,`${f} ${_}kB`);const g=e.transform.getProjectionData({overscaledTileID:r,applyGlobeMatrix:!0,applyTerrainMatrix:!0});s.draw(o,a.TRIANGLES,n,l,jt.alphaBlended,Gt.disabled,Ui(t.Color.transparent,m),null,g,h,e.debugBuffer,e.quadTriangleIndexBuffer,e.debugSegments),s.draw(o,a.LINE_STRIP,n,l,c,Gt.disabled,Ui(t.Color.red),u,g,h,e.debugBuffer,e.tileBorderIndexBuffer,e.debugSegments);}function To(e,t,i,r){const{isRenderingGlobe:o}=r,a=e.context,s=a.gl,n=e.transform,l=e.colorModeForRenderPass(),c=e.getDepthModeFor3D(),h=e.useProgram("terrain"),u=t.getTerrainMesh();a.bindFramebuffer.set(null),a.viewport.set([0,0,e.width,e.height]);for(const r of i){const i=e.renderToTexture.getTexture(r),d=t.getTerrainData(r.tileID);a.activeTexture.set(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,i.texture);const _=t.getMeshFrameDelta(n.zoom),p=n.calculateFogMatrix(r.tileID.toUnwrapped()),m=Ii(_,p,e.style.sky,n.pitch,o),f=n.getProjectionData({overscaledTileID:r.tileID,applyTerrainMatrix:!1,applyGlobeMatrix:!0});h.draw(a,s.TRIANGLES,c,qt.disabled,l,Gt.backCCW,m,d,f,"terrain",u.vertexBuffer,u.indexBuffer,u.segments);}}function Eo(e,i){if(!i.mesh){const r=new t.PosArray;r.emplaceBack(-1,-1),r.emplaceBack(1,-1),r.emplaceBack(1,1),r.emplaceBack(-1,1);const o=new t.TriangleIndexArray;o.emplaceBack(0,1,2),o.emplaceBack(0,2,3),i.mesh=new bt(e.createVertexBuffer(r,wt.members),e.createIndexBuffer(o),t.SegmentVector.simpleSegment(0,0,r.length,o.length));}return i.mesh}class Po{constructor(e,i){this.context=new Wr(e),this.transform=i,this._tileTextures={},this.terrainFacilitator={dirty:!0,matrix:t.identity(new Float64Array(16)),renderTime:0},this.setup(),this.numSublayers=ye.maxUnderzooming+ye.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.crossTileSymbolIndex=new gt;}resize(e,t,i){if(this.width=Math.floor(e*i),this.height=Math.floor(t*i),this.pixelRatio=i,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const e of this.style._order)this.style._layers[e].resize();}setup(){const e=this.context,i=new t.PosArray;i.emplaceBack(0,0),i.emplaceBack(t.EXTENT,0),i.emplaceBack(0,t.EXTENT),i.emplaceBack(t.EXTENT,t.EXTENT),this.tileExtentBuffer=e.createVertexBuffer(i,wt.members),this.tileExtentSegments=t.SegmentVector.simpleSegment(0,0,4,2);const r=new t.PosArray;r.emplaceBack(0,0),r.emplaceBack(t.EXTENT,0),r.emplaceBack(0,t.EXTENT),r.emplaceBack(t.EXTENT,t.EXTENT),this.debugBuffer=e.createVertexBuffer(r,wt.members),this.debugSegments=t.SegmentVector.simpleSegment(0,0,4,5);const o=new t.RasterBoundsArray;o.emplaceBack(0,0,0,0),o.emplaceBack(t.EXTENT,0,t.EXTENT,0),o.emplaceBack(0,t.EXTENT,0,t.EXTENT),o.emplaceBack(t.EXTENT,t.EXTENT,t.EXTENT,t.EXTENT),this.rasterBoundsBuffer=e.createVertexBuffer(o,Ei.members),this.rasterBoundsSegments=t.SegmentVector.simpleSegment(0,0,4,2);const a=new t.PosArray;a.emplaceBack(0,0),a.emplaceBack(t.EXTENT,0),a.emplaceBack(0,t.EXTENT),a.emplaceBack(t.EXTENT,t.EXTENT),this.rasterBoundsBufferPosOnly=e.createVertexBuffer(a,wt.members),this.rasterBoundsSegmentsPosOnly=t.SegmentVector.simpleSegment(0,0,4,5);const s=new t.PosArray;s.emplaceBack(0,0),s.emplaceBack(1,0),s.emplaceBack(0,1),s.emplaceBack(1,1),this.viewportBuffer=e.createVertexBuffer(s,wt.members),this.viewportSegments=t.SegmentVector.simpleSegment(0,0,4,2);const n=new t.LineStripIndexArray;n.emplaceBack(0),n.emplaceBack(1),n.emplaceBack(3),n.emplaceBack(2),n.emplaceBack(0),this.tileBorderIndexBuffer=e.createIndexBuffer(n);const l=new t.TriangleIndexArray;l.emplaceBack(1,0,2),l.emplaceBack(1,2,3),this.quadTriangleIndexBuffer=e.createIndexBuffer(l);const c=this.context.gl;this.stencilClearMode=new qt({func:c.ALWAYS,mask:0},0,255,c.ZERO,c.ZERO,c.ZERO),this.tileExtentMesh=new bt(this.tileExtentBuffer,this.quadTriangleIndexBuffer,this.tileExtentSegments);}clearStencil(){const e=this.context,i=e.gl;this.nextStencilID=1,this.currentStencilSource=void 0;const r=t.create();t.ortho(r,0,this.width,this.height,0,0,1),t.scale(r,r,[i.drawingBufferWidth,i.drawingBufferHeight,0]);const o={mainMatrix:r,tileMercatorCoords:[0,0,1,1],clippingPlane:[0,0,0,0],projectionTransition:0,fallbackMatrix:r};this.useProgram("clippingMask",null,!0).draw(e,i.TRIANGLES,Zt.disabled,this.stencilClearMode,jt.disabled,Gt.disabled,null,null,o,"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments);}_renderTileClippingMasks(e,t,i){if(this.currentStencilSource===e.source||!e.isTileClipped()||!t||!t.length)return;this.currentStencilSource=e.source,this.nextStencilID+t.length>256&&this.clearStencil();const r=this.context;r.setColorMode(jt.disabled),r.setDepthMode(Zt.disabled);const o={};for(const e of t)o[e.key]=this.nextStencilID++;this._renderTileMasks(o,t,i,!0),this._renderTileMasks(o,t,i,!1),this._tileClippingMaskIDs=o;}_renderTileMasks(e,t,i,r){const o=this.context,a=o.gl,s=this.style.projection,n=this.transform,l=this.useProgram("clippingMask");for(const c of t){const t=e[c.key],h=this.style.map.terrain&&this.style.map.terrain.getTerrainData(c),u=s.getMeshFromTileID(this.context,c.canonical,r,!0,"stencil"),d=n.getProjectionData({overscaledTileID:c,applyGlobeMatrix:!0,applyTerrainMatrix:!0});l.draw(o,a.TRIANGLES,Zt.disabled,new qt({func:a.ALWAYS,mask:0},t,255,a.KEEP,a.KEEP,a.REPLACE),jt.disabled,i?Gt.disabled:Gt.backCCW,null,h,d,"$clipping",u.vertexBuffer,u.indexBuffer,u.segments);}}_renderTilesDepthBuffer(){const e=this.context,t=e.gl,i=this.style.projection,r=this.transform,o=this.useProgram("depth"),a=this.getDepthModeFor3D(),s=ve(r,{tileSize:r.tileSize});for(const n of s){const s=this.style.map.terrain&&this.style.map.terrain.getTerrainData(n),l=i.getMeshFromTileID(this.context,n.canonical,!0,!0,"raster"),c=r.getProjectionData({overscaledTileID:n,applyGlobeMatrix:!0,applyTerrainMatrix:!0});o.draw(e,t.TRIANGLES,a,qt.disabled,jt.disabled,Gt.backCCW,null,s,c,"$clipping",l.vertexBuffer,l.indexBuffer,l.segments);}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();const e=this.nextStencilID++,t=this.context.gl;return new qt({func:t.NOTEQUAL,mask:255},e,255,t.KEEP,t.KEEP,t.REPLACE)}stencilModeForClipping(e){const t=this.context.gl;return new qt({func:t.EQUAL,mask:255},this._tileClippingMaskIDs[e.key],0,t.KEEP,t.KEEP,t.REPLACE)}getStencilConfigForOverlapAndUpdateStencilID(e){const t=this.context.gl,i=e.sort(((e,t)=>t.overscaledZ-e.overscaledZ)),r=i[i.length-1].overscaledZ,o=i[0].overscaledZ-r+1;if(o>1){this.currentStencilSource=void 0,this.nextStencilID+o>256&&this.clearStencil();const e={};for(let i=0;it.overscaledZ-e.overscaledZ)),r=i[i.length-1].overscaledZ,o=i[0].overscaledZ-r+1;if(this.clearStencil(),o>1){const e={},a={};for(let i=0;ithis.useProgram(e)}),this.context.viewport.set([0,0,this.width,this.height]),this.context.bindFramebuffer.set(null),this.context.clear({color:i.showOverdrawInspector?t.Color.black:t.Color.transparent,depth:1}),this.clearStencil(),this.style.sky&&function(e,t){const i=e.context,r=i.gl,o=((e,t,i)=>{const r=Math.cos(t.rollInRadians),o=Math.sin(t.rollInRadians),a=Rt(t),s=t.getProjectionData({overscaledTileID:null,applyGlobeMatrix:!0,applyTerrainMatrix:!0}).projectionTransition;return {u_sky_color:e.properties.get("sky-color"),u_horizon_color:e.properties.get("horizon-color"),u_horizon:[(t.width/2-a*o)*i,(t.height/2+a*r)*i],u_horizon_normal:[-o,r],u_sky_horizon_blend:e.properties.get("sky-horizon-blend")*t.height/2*i,u_sky_blend:s}})(t,e.style.map.transform,e.pixelRatio),a=new Zt(r.LEQUAL,Zt.ReadWrite,[0,1]),s=qt.disabled,n=e.colorModeForRenderPass(),l=e.useProgram("sky"),c=Eo(i,t);l.draw(i,r.TRIANGLES,a,s,n,Gt.disabled,o,null,void 0,"sky",c.vertexBuffer,c.indexBuffer,c.segments);}(this,this.style.sky),this._showOverdrawInspector=i.showOverdrawInspector,this.depthRangeFor3D=[0,1-(e._order.length+2)*this.numSublayers*this.depthEpsilon],!this.renderToTexture)for(this.renderPass="opaque",this.currentLayer=r.length-1;this.currentLayer>=0;this.currentLayer--){const e=this.style._layers[r[this.currentLayer]],t=o[e.source],i=a[e.source];this._renderTileClippingMasks(e,i,!1),this.renderLayer(this,t,e,i,l);}this.renderPass="translucent";let c=!1;for(this.currentLayer=0;this.currentLayer({u_sun_pos:e,u_atmosphere_blend:t,u_globe_position:i,u_globe_radius:r,u_inv_proj_matrix:o}))(c,u,[p[0],p[1],p[2]],d,_),f=Eo(o,i);s.draw(o,a.TRIANGLES,n,qt.disabled,jt.alphaBlended,Gt.disabled,m,null,null,"atmosphere",f.vertexBuffer,f.indexBuffer,f.segments);}(this,this.style.sky,this.style.light),this.options.showTileBoundaries){const e=function(e,t){let i=null;const r=Object.values(e._layers).flatMap((i=>i.source&&!i.isHidden(t)?[e.sourceCaches[i.source]]:[])),o=r.filter((e=>"vector"===e.getSource().type)),a=r.filter((e=>"vector"!==e.getSource().type)),s=e=>{(!i||i.getSource().maxzooms(e))),i||a.forEach((e=>s(e))),i}(this.style,this.transform.zoom);e&&function(e,t,i){for(let r=0;ru.getElevation(a,e,t):null;Jr(s,d,_,c,h,f,i,p,g,t.translatePosition(h,e,n,l),a.toUnwrapped(),r);}}}(o,e,r,i,r.layout.get("text-rotation-alignment"),r.layout.get("text-pitch-alignment"),r.paint.get("text-translate"),r.paint.get("text-translate-anchor"),a),0!==r.paint.get("icon-opacity").constantOr(1)&&eo(e,i,r,o,!1,r.paint.get("icon-translate"),r.paint.get("icon-translate-anchor"),r.layout.get("icon-rotation-alignment"),r.layout.get("icon-pitch-alignment"),r.layout.get("icon-keep-upright"),l,c,n),0!==r.paint.get("text-opacity").constantOr(1)&&eo(e,i,r,o,!0,r.paint.get("text-translate"),r.paint.get("text-translate-anchor"),r.layout.get("text-rotation-alignment"),r.layout.get("text-pitch-alignment"),r.layout.get("text-keep-upright"),l,c,n),i.map.showCollisionBoxes&&($r(e,i,r,o,!0),$r(e,i,r,o,!1));}(e,i,r,o,this.style.placement.variableOffsets,a):t.isCircleStyleLayer(r)?function(e,i,r,o,a){if("translucent"!==e.renderPass)return;const{isRenderingToTexture:s}=a,n=r.paint.get("circle-opacity"),l=r.paint.get("circle-stroke-width"),c=r.paint.get("circle-stroke-opacity"),h=!r.layout.get("circle-sort-key").isConstant();if(0===n.constantOr(1)&&(0===l.constantOr(1)||0===c.constantOr(1)))return;const u=e.context,d=u.gl,_=e.transform,p=e.getDepthModeForSublayer(0,Zt.ReadOnly),m=qt.disabled,f=e.colorModeForRenderPass(),g=[],v=_.getCircleRadiusCorrection();for(let a=0;ae.sortKey-t.sortKey));for(const t of g){const{programConfiguration:i,program:o,layoutVertexBuffer:a,indexBuffer:s,uniformValues:n,terrainData:l,projectionData:c}=t.state;o.draw(u,d.TRIANGLES,p,m,f,Gt.backCCW,n,l,c,r.id,a,s,t.segments,r.paint,e.transform.zoom,i);}}(e,i,r,o,a):t.isHeatmapStyleLayer(r)?function(e,i,r,o,a){if(0===r.paint.get("heatmap-opacity"))return;const s=e.context,{isRenderingToTexture:n,isRenderingGlobe:l}=a;if(e.style.map.terrain){for(const t of o){const o=i.getTile(t);i.hasRenderableParent(t)||("offscreen"===e.renderPass?io(e,o,r,t,l):"translucent"===e.renderPass&&ro(e,r,t,n,l));}s.viewport.set([0,0,e.width,e.height]);}else "offscreen"===e.renderPass?function(e,i,r,o){const a=e.context,s=a.gl,n=e.transform,l=qt.disabled,c=new jt([s.ONE,s.ONE],t.Color.transparent,[!0,!0,!0,!0]);((function(e,i,r){const o=e.gl;e.activeTexture.set(o.TEXTURE1),e.viewport.set([0,0,i.width/4,i.height/4]);let a=r.heatmapFbos.get(t.HEATMAP_FULL_RENDER_FBO_KEY);a?(o.bindTexture(o.TEXTURE_2D,a.colorAttachment.get()),e.bindFramebuffer.set(a.framebuffer)):(a=oo(e,i.width/4,i.height/4),r.heatmapFbos.set(t.HEATMAP_FULL_RENDER_FBO_KEY,a));}))(a,e,r),a.clear({color:t.Color.transparent});for(let t=0;t0?t.pop():null}isPatternMissing(e){if(!e)return !1;if(!e.from||!e.to)return !0;const t=this.imageManager.getPattern(e.from.toString()),i=this.imageManager.getPattern(e.to.toString());return !t||!i}useProgram(e,t,i=!1){this.cache=this.cache||{};const r=!!this.style.map.terrain,o=this.style.projection,a=e+(t?t.cacheKey:"")+`/${i?Et:o.shaderVariantName}`+(this._showOverdrawInspector?"/overdraw":"")+(r?"/terrain":"");return this.cache[a]||(this.cache[a]=new Si(this.context,yt[e],t,ar[e],this._showOverdrawInspector,r,i?yt.projectionMercator:o.shaderPreludeCode,i?Tt:o.shaderDefine)),this.cache[a]}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 e=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(e.FUNC_ADD);}initDebugOverlayCanvas(){null==this.debugOverlayCanvas&&(this.debugOverlayCanvas=document.createElement("canvas"),this.debugOverlayCanvas.width=512,this.debugOverlayCanvas.height=512,this.debugOverlayTexture=new y(this.context,this.debugOverlayCanvas,this.context.gl.RGBA));}destroy(){this.debugOverlayTexture&&this.debugOverlayTexture.destroy();}overLimit(){const{drawingBufferWidth:e,drawingBufferHeight:t}=this.context.gl;return this.width!==e||this.height!==t}}function Io(e,t){let i,r=!1,o=null,a=null;const s=()=>{o=null,r&&(e.apply(a,i),o=setTimeout(s,t),r=!1);};return (...e)=>(r=!0,a=this,i=e,o||s(),o)}class Co{constructor(e){this._getCurrentHash=()=>{const e=window.location.hash.replace("#","");if(this._hashName){let t;return e.split("&").map((e=>e.split("="))).forEach((e=>{e[0]===this._hashName&&(t=e);})),(t&&t[1]||"").split("/")}return e.split("/")},this._onHashChange=()=>{const e=this._getCurrentHash();if(e.length>=3&&!e.some((e=>isNaN(e)))){const t=this._map.dragRotate.isEnabled()&&this._map.touchZoomRotate.isEnabled()?+(e[3]||0):this._map.getBearing();return this._map.jumpTo({center:[+e[2],+e[1]],zoom:+e[0],bearing:t,pitch:+(e[4]||0)}),!0}return !1},this._updateHashUnthrottled=()=>{const e=window.location.href.replace(/(#.*)?$/,this.getHashString());window.history.replaceState(window.history.state,null,e);},this._removeHash=()=>{const e=this._getCurrentHash();if(0===e.length)return;const t=e.join("/");let i=t;i.split("&").length>0&&(i=i.split("&")[0]),this._hashName&&(i=`${this._hashName}=${t}`);let r=window.location.hash.replace(i,"");r.startsWith("#&")?r=r.slice(0,1)+r.slice(2):"#"===r&&(r="");let o=window.location.href.replace(/(#.+)?$/,r);o=o.replace("&&","&"),window.history.replaceState(window.history.state,null,o);},this._updateHash=Io(this._updateHashUnthrottled,300),this._hashName=e&&encodeURIComponent(e);}addTo(e){return this._map=e,addEventListener("hashchange",this._onHashChange,!1),this._map.on("moveend",this._updateHash),this}remove(){return removeEventListener("hashchange",this._onHashChange,!1),this._map.off("moveend",this._updateHash),clearTimeout(this._updateHash()),this._removeHash(),delete this._map,this}getHashString(e){const t=this._map.getCenter(),i=Math.round(100*this._map.getZoom())/100,r=Math.ceil((i*Math.LN2+Math.log(512/360/.5))/Math.LN10),o=Math.pow(10,r),a=Math.round(t.lng*o)/o,s=Math.round(t.lat*o)/o,n=this._map.getBearing(),l=this._map.getPitch();let c="";if(c+=e?`/${a}/${s}/${i}`:`${i}/${s}/${a}`,(n||l)&&(c+="/"+Math.round(10*n)/10),l&&(c+=`/${Math.round(l)}`),this._hashName){const e=this._hashName;let t=!1;const i=window.location.hash.slice(1).split("&").map((i=>{const r=i.split("=")[0];return r===e?(t=!0,`${r}=${c}`):i})).filter((e=>e));return t||i.push(`${e}=${c}`),`#${i.join("&")}`}return `#${c}`}}const Mo={linearity:.3,easing:t.bezier(0,0,.3,1)},So=t.extend({deceleration:2500,maxSpeed:1400},Mo),Ro=t.extend({deceleration:20,maxSpeed:1400},Mo),Do=t.extend({deceleration:1e3,maxSpeed:360},Mo),zo=t.extend({deceleration:1e3,maxSpeed:90},Mo),Lo=t.extend({deceleration:1e3,maxSpeed:360},Mo);class Ao{constructor(e){this._map=e,this.clear();}clear(){this._inertiaBuffer=[];}record(e){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:f.now(),settings:e});}_drainInertiaBuffer(){const e=this._inertiaBuffer,t=f.now();for(;e.length>0&&t-e[0].time>160;)e.shift();}_onMoveEnd(e){if(this._drainInertiaBuffer(),this._inertiaBuffer.length<2)return;const i={zoom:0,bearing:0,pitch:0,roll:0,pan:new t.Point(0,0),pinchAround:void 0,around:void 0};for(const{settings:e}of this._inertiaBuffer)i.zoom+=e.zoomDelta||0,i.bearing+=e.bearingDelta||0,i.pitch+=e.pitchDelta||0,i.roll+=e.rollDelta||0,e.panDelta&&i.pan._add(e.panDelta),e.around&&(i.around=e.around),e.pinchAround&&(i.pinchAround=e.pinchAround);const r=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,o={};if(i.pan.mag()){const a=Fo(i.pan.mag(),r,t.extend({},So,e||{})),s=i.pan.mult(a.amount/i.pan.mag()),n=this._map.cameraHelper.handlePanInertia(s,this._map.transform);o.center=n.easingCenter,o.offset=n.easingOffset,ko(o,a);}if(i.zoom){const e=Fo(i.zoom,r,Ro);o.zoom=this._map.transform.zoom+e.amount,ko(o,e);}if(i.bearing){const e=Fo(i.bearing,r,Do);o.bearing=this._map.transform.bearing+t.clamp(e.amount,-179,179),ko(o,e);}if(i.pitch){const e=Fo(i.pitch,r,zo);o.pitch=this._map.transform.pitch+e.amount,ko(o,e);}if(i.roll){const e=Fo(i.roll,r,Lo);o.roll=this._map.transform.roll+t.clamp(e.amount,-179,179),ko(o,e);}if(o.zoom||o.bearing){const e=void 0===i.pinchAround?i.around:i.pinchAround;o.around=e?this._map.unproject(e):this._map.getCenter();}return this.clear(),t.extend(o,{noMoveStart:!0})}}function ko(e,t){(!e.duration||e.durationi.unproject(e))),n=a.reduce(((e,t,i,r)=>e.add(t.div(r.length))),new t.Point(0,0));super(e,{points:a,point:n,lngLats:s,lngLat:i.unproject(n),originalEvent:r}),this._defaultPrevented=!1;}}class Uo extends t.Event{preventDefault(){this._defaultPrevented=!0;}get defaultPrevented(){return this._defaultPrevented}constructor(e,t,i){super(e,{originalEvent:i}),this._defaultPrevented=!1;}}class jo{constructor(e,t){this._map=e,this._clickTolerance=t.clickTolerance;}reset(){delete this._mousedownPos;}wheel(e){return this._firePreventable(new Uo(e.type,this._map,e))}mousedown(e,t){return this._mousedownPos=t,this._firePreventable(new Bo(e.type,this._map,e))}mouseup(e){this._map.fire(new Bo(e.type,this._map,e));}click(e,t){this._mousedownPos&&this._mousedownPos.dist(t)>=this._clickTolerance||this._map.fire(new Bo(e.type,this._map,e));}dblclick(e){return this._firePreventable(new Bo(e.type,this._map,e))}mouseover(e){this._map.fire(new Bo(e.type,this._map,e));}mouseout(e){this._map.fire(new Bo(e.type,this._map,e));}touchstart(e){return this._firePreventable(new Oo(e.type,this._map,e))}touchmove(e){this._map.fire(new Oo(e.type,this._map,e));}touchend(e){this._map.fire(new Oo(e.type,this._map,e));}touchcancel(e){this._map.fire(new Oo(e.type,this._map,e));}_firePreventable(e){if(this._map.fire(e),e.defaultPrevented)return {}}isEnabled(){return !0}isActive(){return !1}enable(){}disable(){}}class No{constructor(e){this._map=e;}reset(){this._delayContextMenu=!1,this._ignoreContextMenu=!0,delete this._contextMenuEvent;}mousemove(e){this._map.fire(new Bo(e.type,this._map,e));}mousedown(){this._delayContextMenu=!0,this._ignoreContextMenu=!1;}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new Bo("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent);}contextmenu(e){this._delayContextMenu?this._contextMenuEvent=e:this._ignoreContextMenu||this._map.fire(new Bo(e.type,this._map,e)),this._map.listens("contextmenu")&&e.preventDefault();}isEnabled(){return !0}isActive(){return !1}enable(){}disable(){}}class Go{constructor(e){this._map=e;}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(e){return this.transform.screenPointToLocation(t.Point.convert(e),this._map.terrain)}}class Zo{constructor(e,t){this._map=e,this._tr=new Go(e),this._el=e.getCanvasContainer(),this._container=e.getContainer(),this._clickTolerance=t.clickTolerance||1;}isEnabled(){return !!this._enabled}isActive(){return !!this._active}enable(){this.isEnabled()||(this._enabled=!0);}disable(){this.isEnabled()&&(this._enabled=!1);}mousedown(e,t){this.isEnabled()&&e.shiftKey&&0===e.button&&(wi.disableDrag(),this._startPos=this._lastPos=t,this._active=!0);}mousemoveWindow(e,t){if(!this._active)return;const i=t;if(this._lastPos.equals(i)||!this._box&&i.dist(this._startPos)e.fitScreenCoordinates(r,o,this._tr.bearing,{linear:!0})};this._fireEvent("boxzoomcancel",e);}keydown(e){this._active&&27===e.keyCode&&(this.reset(),this._fireEvent("boxzoomcancel",e));}reset(){this._active=!1,this._container.classList.remove("maplibregl-crosshair"),this._box&&(wi.remove(this._box),this._box=null),wi.enableDrag(),delete this._startPos,delete this._lastPos;}_fireEvent(e,i){return this._map.fire(new t.Event(e,{originalEvent:i}))}}function Vo(e,t){if(e.length!==t.length)throw new Error(`The number of touches and points are not equal - touches ${e.length}, points ${t.length}`);const i={};for(let r=0;rthis.numTouches)&&(this.aborted=!0),this.aborted||(void 0===this.startTime&&(this.startTime=e.timeStamp),r.length===this.numTouches&&(this.centroid=function(e){const i=new t.Point(0,0);for(const t of e)i._add(t);return i.div(e.length)}(i),this.touches=Vo(r,i)));}touchmove(e,t,i){if(this.aborted||!this.centroid)return;const r=Vo(i,t);for(const e in this.touches){const t=r[e];(!t||t.dist(this.touches[e])>30)&&(this.aborted=!0);}}touchend(e,t,i){if((!this.centroid||e.timeStamp-this.startTime>500)&&(this.aborted=!0),0===i.length){const e=!this.aborted&&this.centroid;if(this.reset(),e)return e}}}class Wo{constructor(e){this.singleTap=new qo(e),this.numTaps=e.numTaps,this.reset();}reset(){this.lastTime=1/0,delete this.lastTap,this.count=0,this.singleTap.reset();}touchstart(e,t,i){this.singleTap.touchstart(e,t,i);}touchmove(e,t,i){this.singleTap.touchmove(e,t,i);}touchend(e,t,i){const r=this.singleTap.touchend(e,t,i);if(r){const t=e.timeStamp-this.lastTime<500,i=!this.lastTap||this.lastTap.dist(r)<30;if(t&&i||this.reset(),this.count++,this.lastTime=e.timeStamp,this.lastTap=r,this.count===this.numTaps)return this.reset(),r}}}class Xo{constructor(e){this._tr=new Go(e),this._zoomIn=new Wo({numTouches:1,numTaps:2}),this._zoomOut=new Wo({numTouches:2,numTaps:1}),this.reset();}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset();}touchstart(e,t,i){this._zoomIn.touchstart(e,t,i),this._zoomOut.touchstart(e,t,i);}touchmove(e,t,i){this._zoomIn.touchmove(e,t,i),this._zoomOut.touchmove(e,t,i);}touchend(e,t,i){const r=this._zoomIn.touchend(e,t,i),o=this._zoomOut.touchend(e,t,i),a=this._tr;return r?(this._active=!0,e.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:t=>t.easeTo({duration:300,zoom:a.zoom+1,around:a.unproject(r)},{originalEvent:e})}):o?(this._active=!0,e.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:t=>t.easeTo({duration:300,zoom:a.zoom-1,around:a.unproject(o)},{originalEvent:e})}):void 0}touchcancel(){this.reset();}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class $o{constructor(e){this._enabled=!!e.enable,this._moveStateManager=e.moveStateManager,this._clickTolerance=e.clickTolerance||1,this._moveFunction=e.move,this._activateOnStart=!!e.activateOnStart,e.assignEvents(this),this.reset();}reset(e){this._active=!1,this._moved=!1,delete this._lastPoint,this._moveStateManager.endMove(e);}_move(...e){const t=this._moveFunction(...e);if(t.bearingDelta||t.pitchDelta||t.rollDelta||t.around||t.panDelta)return this._active=!0,t}dragStart(e,t){this.isEnabled()&&!this._lastPoint&&this._moveStateManager.isValidStartEvent(e)&&(this._moveStateManager.startMove(e),this._lastPoint=t.length?t[0]:t,this._activateOnStart&&this._lastPoint&&(this._active=!0));}dragMove(e,i){if(!this.isEnabled())return;const r=this._lastPoint;if(!r)return;if(e.preventDefault(),!this._moveStateManager.isValidMoveEvent(e))return void this.reset(e);const o=Array.isArray(i)?i[0]:i;return !this._moved&&o.dist(r){e.mousedown=e.dragStart,e.mousemoveWindow=e.dragMove,e.mouseup=e.dragEnd,e.contextmenu=e=>{e.preventDefault();};};function Qo({enable:e,clickTolerance:i,aroundCenter:r=!0}){const o=new Ko({checkCorrectEvent:e=>0===wi.mouseButton(e)&&e.ctrlKey||2===wi.mouseButton(e)&&!e.ctrlKey});return new $o({clickTolerance:i,move:(e,i,o)=>r?{bearingDelta:t.getAngleDelta(new t.Point(e.x,i.y),i,o)}:{bearingDelta:.8*(i.x-e.x)},moveStateManager:o,enable:e,assignEvents:Jo})}function ea({enable:e,clickTolerance:t,pitchDegreesPerPixelMoved:i=-.5}){const r=new Ko({checkCorrectEvent:e=>0===wi.mouseButton(e)&&e.ctrlKey||2===wi.mouseButton(e)});return new $o({clickTolerance:t,move:(e,t)=>({pitchDelta:(t.y-e.y)*i}),moveStateManager:r,enable:e,assignEvents:Jo})}class ta{constructor(e,t){this._clickTolerance=e.clickTolerance||1,this._map=t,this.reset();}reset(){this._active=!1,this._touches={},this._sum=new t.Point(0,0);}_shouldBePrevented(e){return e<(this._map.cooperativeGestures.isEnabled()?2:1)}touchstart(e,t,i){return this._calculateTransform(e,t,i)}touchmove(e,t,i){if(this._active){if(!this._shouldBePrevented(i.length))return e.preventDefault(),this._calculateTransform(e,t,i);this._map.cooperativeGestures.notifyGestureBlocked("touch_pan",e);}}touchend(e,t,i){this._calculateTransform(e,t,i),this._active&&this._shouldBePrevented(i.length)&&this.reset();}touchcancel(){this.reset();}_calculateTransform(e,i,r){r.length>0&&(this._active=!0);const o=Vo(r,i),a=new t.Point(0,0),s=new t.Point(0,0);let n=0;for(const e in o){const t=o[e],i=this._touches[e];i&&(a._add(t),s._add(t.sub(i)),n++,o[e]=t);}if(this._touches=o,this._shouldBePrevented(n)||!s.mag())return;const l=s.div(n);return this._sum._add(l),this._sum.mag()Math.abs(e.x)}class ca extends ia{constructor(e){super(),this._currentTouchCount=0,this._map=e;}reset(){super.reset(),this._valid=void 0,delete this._firstMove,delete this._lastPoints;}touchstart(e,t,i){super.touchstart(e,t,i),this._currentTouchCount=i.length;}_start(e){this._lastPoints=e,la(e[0].sub(e[1]))&&(this._valid=!1);}_move(e,t,i){if(this._map.cooperativeGestures.isEnabled()&&this._currentTouchCount<3)return;const r=e[0].sub(this._lastPoints[0]),o=e[1].sub(this._lastPoints[1]);return this._valid=this.gestureBeginsVertically(r,o,i.timeStamp),this._valid?(this._lastPoints=e,this._active=!0,{pitchDelta:(r.y+o.y)/2*-.5}):void 0}gestureBeginsVertically(e,t,i){if(void 0!==this._valid)return this._valid;const r=e.mag()>=2,o=t.mag()>=2;if(!r&&!o)return;if(!r||!o)return void 0===this._firstMove&&(this._firstMove=i),i-this._firstMove<100&&void 0;const a=e.y>0==t.y>0;return la(e)&&la(t)&&a}}const ha={panStep:100,bearingStep:15,pitchStep:10};class ua{constructor(e){this._tr=new Go(e);const t=ha;this._panStep=t.panStep,this._bearingStep=t.bearingStep,this._pitchStep=t.pitchStep,this._rotationDisabled=!1;}reset(){this._active=!1;}keydown(e){if(e.altKey||e.ctrlKey||e.metaKey)return;let t=0,i=0,r=0,o=0,a=0;switch(e.keyCode){case 61:case 107:case 171:case 187:t=1;break;case 189:case 109:case 173:t=-1;break;case 37:e.shiftKey?i=-1:(e.preventDefault(),o=-1);break;case 39:e.shiftKey?i=1:(e.preventDefault(),o=1);break;case 38:e.shiftKey?r=1:(e.preventDefault(),a=-1);break;case 40:e.shiftKey?r=-1:(e.preventDefault(),a=1);break;default:return}return this._rotationDisabled&&(i=0,r=0),{cameraAnimation:s=>{const n=this._tr;s.easeTo({duration:300,easeId:"keyboardHandler",easing:da,zoom:t?Math.round(n.zoom)+t*(e.shiftKey?2:1):n.zoom,bearing:n.bearing+i*this._bearingStep,pitch:n.pitch+r*this._pitchStep,offset:[-o*this._panStep,-a*this._panStep],center:n.center},{originalEvent:e});}}}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}disableRotation(){this._rotationDisabled=!0;}enableRotation(){this._rotationDisabled=!1;}}function da(e){return e*(2-e)}const _a=4.000244140625;class pa{constructor(e,t){this._onTimeout=e=>{this._type="wheel",this._delta-=this._lastValue,this._active||this._start(e);},this._map=e,this._tr=new Go(e),this._triggerRenderFrame=t,this._delta=0,this._defaultZoomRate=.01,this._wheelZoomRate=.0022222222222222222;}setZoomRate(e){this._defaultZoomRate=e;}setWheelZoomRate(e){this._wheelZoomRate=e;}isEnabled(){return !!this._enabled}isActive(){return !!this._active||void 0!==this._finishTimeout}isZooming(){return !!this._zooming}enable(e){this.isEnabled()||(this._enabled=!0,this._aroundCenter=!!e&&"center"===e.around);}disable(){this.isEnabled()&&(this._enabled=!1);}_shouldBePrevented(e){return !!this._map.cooperativeGestures.isEnabled()&&!(e.ctrlKey||this._map.cooperativeGestures.isBypassed(e))}wheel(e){if(!this.isEnabled())return;if(this._shouldBePrevented(e))return void this._map.cooperativeGestures.notifyGestureBlocked("wheel_zoom",e);let t=e.deltaMode===WheelEvent.DOM_DELTA_LINE?40*e.deltaY:e.deltaY;const i=f.now(),r=i-(this._lastWheelEventTime||0);this._lastWheelEventTime=i,0!==t&&t%_a==0?this._type="wheel":0!==t&&Math.abs(t)<4?this._type="trackpad":r>400?(this._type=null,this._lastValue=t,this._timeout=setTimeout(this._onTimeout,40,e)):this._type||(this._type=Math.abs(r*t)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,t+=this._lastValue)),e.shiftKey&&t&&(t/=4),this._type&&(this._lastWheelEvent=e,this._delta-=t,this._active||this._start(e)),e.preventDefault();}_start(e){if(!this._delta)return;this._frameId&&(this._frameId=null),this._active=!0,this.isZooming()||(this._zooming=!0),this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);const i=wi.mousePos(this._map.getCanvas(),e),r=this._tr;this._aroundPoint=this._aroundCenter?r.transform.locationToScreenPoint(t.LngLat.convert(r.center)):i,this._frameId||(this._frameId=!0,this._triggerRenderFrame());}renderFrame(){if(!this._frameId)return;if(this._frameId=null,!this.isActive())return;const e=this._tr.transform;if("number"==typeof this._lastExpectedZoom){const t=e.zoom-this._lastExpectedZoom;"number"==typeof this._startZoom&&(this._startZoom+=t),"number"==typeof this._targetZoom&&(this._targetZoom+=t);}if(0!==this._delta){const t="wheel"===this._type&&Math.abs(this._delta)>_a?this._wheelZoomRate:this._defaultZoomRate;let i=2/(1+Math.exp(-Math.abs(this._delta*t)));this._delta<0&&0!==i&&(i=1/i);const r="number"!=typeof this._targetZoom?e.scale:ue(this._targetZoom);this._targetZoom=Math.min(e.maxZoom,Math.max(e.minZoom,de(r*i))),"wheel"===this._type&&(this._startZoom=e.zoom,this._easing=this._smoothOutEasing(200)),this._delta=0;}const i="number"!=typeof this._targetZoom?e.zoom:this._targetZoom,r=this._startZoom,o=this._easing;let a,s=!1;const n=f.now()-this._lastWheelEventTime;if("wheel"===this._type&&r&&o&&n){const e=Math.min(n/200,1),l=o(e);a=t.interpolateFactory.number(r,i,l),e<1?this._frameId||(this._frameId=!0):s=!0;}else a=i,s=!0;return this._active=!0,s&&(this._active=!1,this._finishTimeout=setTimeout((()=>{this._zooming=!1,this._triggerRenderFrame(),delete this._targetZoom,delete this._lastExpectedZoom,delete this._finishTimeout;}),200)),this._lastExpectedZoom=a,{noInertia:!0,needsRenderFrame:!s,zoomDelta:a-e.zoom,around:this._aroundPoint,originalEvent:this._lastWheelEvent}}_smoothOutEasing(e){let i=t.defaultEasing;if(this._prevEase){const e=this._prevEase,r=(f.now()-e.start)/e.duration,o=e.easing(r+.01)-e.easing(r),a=.27/Math.sqrt(o*o+1e-4)*.01,s=Math.sqrt(.0729-a*a);i=t.bezier(a,s,.25,1);}return this._prevEase={start:f.now(),duration:e,easing:i},i}reset(){this._active=!1,this._zooming=!1,delete this._targetZoom,delete this._lastExpectedZoom,this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);}}class ma{constructor(e,t){this._clickZoom=e,this._tapZoom=t;}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 fa{constructor(e){this._tr=new Go(e),this.reset();}reset(){this._active=!1;}dblclick(e,t){return e.preventDefault(),{cameraAnimation:i=>{i.easeTo({duration:300,zoom:this._tr.zoom+(e.shiftKey?-1:1),around:this._tr.unproject(t)},{originalEvent:e});}}}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class ga{constructor(){this._tap=new Wo({numTouches:1,numTaps:1}),this.reset();}reset(){this._active=!1,delete this._swipePoint,delete this._swipeTouch,delete this._tapTime,delete this._tapPoint,this._tap.reset();}touchstart(e,t,i){if(!this._swipePoint)if(this._tapTime){const r=t[0],o=e.timeStamp-this._tapTime<500,a=this._tapPoint.dist(r)<30;o&&a?i.length>0&&(this._swipePoint=r,this._swipeTouch=i[0].identifier):this.reset();}else this._tap.touchstart(e,t,i);}touchmove(e,t,i){if(this._tapTime){if(this._swipePoint){if(i[0].identifier!==this._swipeTouch)return;const r=t[0],o=r.y-this._swipePoint.y;return this._swipePoint=r,e.preventDefault(),this._active=!0,{zoomDelta:o/128}}}else this._tap.touchmove(e,t,i);}touchend(e,t,i){if(this._tapTime)this._swipePoint&&0===i.length&&this.reset();else {const r=this._tap.touchend(e,t,i);r&&(this._tapTime=e.timeStamp,this._tapPoint=r);}}touchcancel(){this.reset();}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class va{constructor(e,t,i){this._el=e,this._mousePan=t,this._touchPan=i;}enable(e){this._inertiaOptions=e||{},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 ya{constructor(e,t,i,r){this._pitchWithRotate=e.pitchWithRotate,this._rollEnabled=e.rollEnabled,this._mouseRotate=t,this._mousePitch=i,this._mouseRoll=r;}enable(){this._mouseRotate.enable(),this._pitchWithRotate&&this._mousePitch.enable(),this._rollEnabled&&this._mouseRoll.enable();}disable(){this._mouseRotate.disable(),this._mousePitch.disable(),this._mouseRoll.disable();}isEnabled(){return this._mouseRotate.isEnabled()&&(!this._pitchWithRotate||this._mousePitch.isEnabled())&&(!this._rollEnabled||this._mouseRoll.isEnabled())}isActive(){return this._mouseRotate.isActive()||this._mousePitch.isActive()||this._mouseRoll.isActive()}}class xa{constructor(e,t,i,r){this._el=e,this._touchZoom=t,this._touchRotate=i,this._tapDragZoom=r,this._rotationDisabled=!1,this._enabled=!0;}enable(e){this._touchZoom.enable(e),this._rotationDisabled||this._touchRotate.enable(e),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=!0,this._touchRotate.disable();}enableRotation(){this._rotationDisabled=!1,this._touchZoom.isEnabled()&&this._touchRotate.enable();}}class ba{constructor(e,t){this._bypassKey=-1!==navigator.userAgent.indexOf("Mac")?"metaKey":"ctrlKey",this._map=e,this._options=t,this._enabled=!1;}isActive(){return !1}reset(){}_setupUI(){if(this._container)return;const e=this._map.getCanvasContainer();e.classList.add("maplibregl-cooperative-gestures"),this._container=wi.create("div","maplibregl-cooperative-gesture-screen",e);let t=this._map._getUIString("CooperativeGesturesHandler.WindowsHelpText");"metaKey"===this._bypassKey&&(t=this._map._getUIString("CooperativeGesturesHandler.MacHelpText"));const i=this._map._getUIString("CooperativeGesturesHandler.MobileHelpText"),r=document.createElement("div");r.className="maplibregl-desktop-message",r.textContent=t,this._container.appendChild(r);const o=document.createElement("div");o.className="maplibregl-mobile-message",o.textContent=i,this._container.appendChild(o),this._container.setAttribute("aria-hidden","true");}_destroyUI(){this._container&&(wi.remove(this._container),this._map.getCanvasContainer().classList.remove("maplibregl-cooperative-gestures")),delete this._container;}enable(){this._setupUI(),this._enabled=!0;}disable(){this._enabled=!1,this._destroyUI();}isEnabled(){return this._enabled}isBypassed(e){return e[this._bypassKey]}notifyGestureBlocked(e,i){this._enabled&&(this._map.fire(new t.Event("cooperativegestureprevented",{gestureType:e,originalEvent:i})),this._container.classList.add("maplibregl-show"),setTimeout((()=>{this._container.classList.remove("maplibregl-show");}),100));}}const wa=e=>e.zoom||e.drag||e.roll||e.pitch||e.rotate;class Ta extends t.Event{}function Ea(e){return e.panDelta&&e.panDelta.mag()||e.zoomDelta||e.bearingDelta||e.pitchDelta||e.rollDelta}class Pa{constructor(e,t){this.handleWindowEvent=e=>{this.handleEvent(e,`${e.type}Window`);},this.handleEvent=(e,t)=>{if("blur"===e.type)return void this.stop(!0);this._updatingCamera=!0;const i="renderFrame"===e.type?void 0:e,r={needsRenderFrame:!1},o={},a={},s=e.touches,n=s?this._getMapTouches(s):void 0,l=n?wi.touchPos(this._map.getCanvas(),n):wi.mousePos(this._map.getCanvas(),e);for(const{handlerName:s,handler:c,allowed:h}of this._handlers){if(!c.isEnabled())continue;let u;this._blockedByActive(a,h,s)?c.reset():c[t||e.type]&&(u=c[t||e.type](e,l,n),this.mergeHandlerResult(r,o,u,s,i),u&&u.needsRenderFrame&&this._triggerRenderFrame()),(u||c.isActive())&&(a[s]=c);}const c={};for(const e in this._previousActiveHandlers)a[e]||(c[e]=i);this._previousActiveHandlers=a,(Object.keys(c).length||Ea(r))&&(this._changes.push([r,o,c]),this._triggerRenderFrame()),(Object.keys(a).length||Ea(r))&&this._map._stop(!0),this._updatingCamera=!1;const{cameraAnimation:h}=r;h&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],h(this._map));},this._map=e,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new Ao(e),this._bearingSnap=t.bearingSnap,this._previousActiveHandlers={},this._eventsInProgress={},this._addDefaultHandlers(t);const i=this._el;this._listeners=[[i,"touchstart",{passive:!0}],[i,"touchmove",{passive:!1}],[i,"touchend",void 0],[i,"touchcancel",void 0],[i,"mousedown",void 0],[i,"mousemove",void 0],[i,"mouseup",void 0],[document,"mousemove",{capture:!0}],[document,"mouseup",void 0],[i,"mouseover",void 0],[i,"mouseout",void 0],[i,"dblclick",void 0],[i,"click",void 0],[i,"keydown",{capture:!1}],[i,"keyup",void 0],[i,"wheel",{passive:!1}],[i,"contextmenu",void 0],[window,"blur",void 0]];for(const[e,t,i]of this._listeners)wi.addEventListener(e,t,e===document?this.handleWindowEvent:this.handleEvent,i);}destroy(){for(const[e,t,i]of this._listeners)wi.removeEventListener(e,t,e===document?this.handleWindowEvent:this.handleEvent,i);}_addDefaultHandlers(e){const t=this._map,i=t.getCanvasContainer();this._add("mapEvent",new jo(t,e));const r=t.boxZoom=new Zo(t,e);this._add("boxZoom",r),e.interactive&&e.boxZoom&&r.enable();const o=t.cooperativeGestures=new ba(t,e.cooperativeGestures);this._add("cooperativeGestures",o),e.cooperativeGestures&&o.enable();const a=new Xo(t),s=new fa(t);t.doubleClickZoom=new ma(s,a),this._add("tapZoom",a),this._add("clickZoom",s),e.interactive&&e.doubleClickZoom&&t.doubleClickZoom.enable();const n=new ga;this._add("tapDragZoom",n);const l=t.touchPitch=new ca(t);this._add("touchPitch",l),e.interactive&&e.touchPitch&&t.touchPitch.enable(e.touchPitch);const c=Qo(e),h=ea(e),u=function({enable:e,clickTolerance:t,rollDegreesPerPixelMoved:i=.3}){const r=new Ko({checkCorrectEvent:e=>2===wi.mouseButton(e)&&e.ctrlKey});return new $o({clickTolerance:t,move:(e,t,r)=>{let o=(t.x-e.x)*i;return t.y0===wi.mouseButton(e)&&!e.ctrlKey});return new $o({clickTolerance:t,move:(e,t)=>({around:t,panDelta:t.sub(e)}),activateOnStart:!0,moveStateManager:i,enable:e,assignEvents:Jo})}(e),_=new ta(e,t);t.dragPan=new va(i,d,_),this._add("mousePan",d),this._add("touchPan",_,["touchZoom","touchRotate"]),e.interactive&&e.dragPan&&t.dragPan.enable(e.dragPan);const p=new na,m=new aa;t.touchZoomRotate=new xa(i,m,p,n),this._add("touchRotate",p,["touchPan","touchZoom"]),this._add("touchZoom",m,["touchPan","touchRotate"]),e.interactive&&e.touchZoomRotate&&t.touchZoomRotate.enable(e.touchZoomRotate);const f=t.scrollZoom=new pa(t,(()=>this._triggerRenderFrame()));this._add("scrollZoom",f,["mousePan"]),e.interactive&&e.scrollZoom&&t.scrollZoom.enable(e.scrollZoom);const g=t.keyboard=new ua(t);this._add("keyboard",g),e.interactive&&e.keyboard&&t.keyboard.enable(),this._add("blockableMapEvent",new No(t));}_add(e,t,i){this._handlers.push({handlerName:e,handler:t,allowed:i}),this._handlersById[e]=t;}stop(e){if(!this._updatingCamera){for(const{handler:e}of this._handlers)e.reset();this._inertia.clear(),this._fireEvents({},{},e),this._changes=[];}}isActive(){for(const{handler:e}of this._handlers)if(e.isActive())return !0;return !1}isZooming(){return !!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return !!this._eventsInProgress.rotate}isMoving(){return Boolean(wa(this._eventsInProgress))||this.isZooming()}_blockedByActive(e,t,i){for(const r in e)if(r!==i&&(!t||t.indexOf(r)<0))return !0;return !1}_getMapTouches(e){const t=[];for(const i of e)this._el.contains(i.target)&&t.push(i);return t}mergeHandlerResult(e,i,r,o,a){if(!r)return;t.extend(e,r);const s={handlerName:o,originalEvent:r.originalEvent||a};void 0!==r.zoomDelta&&(i.zoom=s),void 0!==r.panDelta&&(i.drag=s),void 0!==r.rollDelta&&(i.roll=s),void 0!==r.pitchDelta&&(i.pitch=s),void 0!==r.bearingDelta&&(i.rotate=s);}_applyChanges(){const e={},i={},r={};for(const[o,a,s]of this._changes)o.panDelta&&(e.panDelta=(e.panDelta||new t.Point(0,0))._add(o.panDelta)),o.zoomDelta&&(e.zoomDelta=(e.zoomDelta||0)+o.zoomDelta),o.bearingDelta&&(e.bearingDelta=(e.bearingDelta||0)+o.bearingDelta),o.pitchDelta&&(e.pitchDelta=(e.pitchDelta||0)+o.pitchDelta),o.rollDelta&&(e.rollDelta=(e.rollDelta||0)+o.rollDelta),void 0!==o.around&&(e.around=o.around),void 0!==o.pinchAround&&(e.pinchAround=o.pinchAround),o.noInertia&&(e.noInertia=o.noInertia),t.extend(i,a),t.extend(r,s);this._updateMapTransform(e,i,r),this._changes=[];}_updateMapTransform(e,t,i){const r=this._map,o=r._getTransformForUpdate(),a=r.terrain;if(!(Ea(e)||a&&this._terrainMovement))return this._fireEvents(t,i,!0);r._stop(!0);let{panDelta:s,zoomDelta:n,bearingDelta:l,pitchDelta:c,rollDelta:h,around:u,pinchAround:d}=e;void 0!==d&&(u=d),u=u||r.transform.centerPoint,a&&!o.isPointOnMapSurface(u)&&(u=o.centerPoint);const _={panDelta:s,zoomDelta:n,rollDelta:h,pitchDelta:c,bearingDelta:l,around:u};this._map.cameraHelper.useGlobeControls&&!o.isPointOnMapSurface(u)&&(u=o.centerPoint);const p=u.distSqr(o.centerPoint)<.01?o.center:o.screenPointToLocation(s?u.sub(s):u);a?(this._map.cameraHelper.handleMapControlsRollPitchBearingZoom(_,o),this._terrainMovement||!t.drag&&!t.zoom?t.drag&&this._terrainMovement?o.setCenter(o.screenPointToLocation(o.centerPoint.sub(s))):this._map.cameraHelper.handleMapControlsPan(_,o,p):(this._terrainMovement=!0,this._map._elevationFreeze=!0,this._map.cameraHelper.handleMapControlsPan(_,o,p))):(this._map.cameraHelper.handleMapControlsRollPitchBearingZoom(_,o),this._map.cameraHelper.handleMapControlsPan(_,o,p)),r._applyUpdatedTransform(o),this._map._update(),e.noInertia||this._inertia.record(e),this._fireEvents(t,i,!0);}_fireEvents(e,i,r){const o=wa(this._eventsInProgress),a=wa(e),s={};for(const t in e){const{originalEvent:i}=e[t];this._eventsInProgress[t]||(s[`${t}start`]=i),this._eventsInProgress[t]=e[t];}!o&&a&&this._fireEvent("movestart",a.originalEvent);for(const e in s)this._fireEvent(e,s[e]);a&&this._fireEvent("move",a.originalEvent);for(const t in e){const{originalEvent:i}=e[t];this._fireEvent(t,i);}const n={};let l;for(const e in this._eventsInProgress){const{handlerName:t,originalEvent:r}=this._eventsInProgress[e];this._handlersById[t].isActive()||(delete this._eventsInProgress[e],l=i[t]||r,n[`${e}end`]=l);}for(const e in n)this._fireEvent(e,n[e]);const c=wa(this._eventsInProgress),h=(o||a)&&!c;if(h&&this._terrainMovement){this._map._elevationFreeze=!1,this._terrainMovement=!1;const e=this._map._getTransformForUpdate();this._map.getCenterClampedToGround()&&e.recalculateZoomAndCenter(this._map.terrain),this._map._applyUpdatedTransform(e);}if(r&&h){this._updatingCamera=!0;const e=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),i=e=>0!==e&&-this._bearingSnap{delete this._frameId,this.handleEvent(new Ta("renderFrame",{timeStamp:e})),this._applyChanges();}))}_triggerRenderFrame(){void 0===this._frameId&&(this._frameId=this._requestFrame());}}class Ia extends t.Evented{constructor(e,t,i){super(),this._renderFrameCallback=()=>{const e=Math.min((f.now()-this._easeStart)/this._easeOptions.duration,1);this._onEaseFrame(this._easeOptions.easing(e)),e<1&&this._easeFrameId?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop();},this._moving=!1,this._zooming=!1,this.transform=e,this._bearingSnap=i.bearingSnap,this.cameraHelper=t,this.on("moveend",(()=>{delete this._requestedCameraState;}));}migrateProjection(e,t){e.apply(this.transform),this.transform=e,this.cameraHelper=t;}getCenter(){return new t.LngLat(this.transform.center.lng,this.transform.center.lat)}setCenter(e,t){return this.jumpTo({center:e},t)}getCenterElevation(){return this.transform.elevation}setCenterElevation(e,t){return this.jumpTo({elevation:e},t),this}getCenterClampedToGround(){return this._centerClampedToGround}setCenterClampedToGround(e){this._centerClampedToGround=e;}panBy(e,i,r){return e=t.Point.convert(e).mult(-1),this.panTo(this.transform.center,t.extend({offset:e},i),r)}panTo(e,i,r){return this.easeTo(t.extend({center:e},i),r)}getZoom(){return this.transform.zoom}setZoom(e,t){return this.jumpTo({zoom:e},t),this}zoomTo(e,i,r){return this.easeTo(t.extend({zoom:e},i),r)}zoomIn(e,t){return this.zoomTo(this.getZoom()+1,e,t),this}zoomOut(e,t){return this.zoomTo(this.getZoom()-1,e,t),this}getVerticalFieldOfView(){return this.transform.fov}setVerticalFieldOfView(e,i){return e!=this.transform.fov&&(this.transform.setFov(e),this.fire(new t.Event("movestart",i)).fire(new t.Event("move",i)).fire(new t.Event("moveend",i))),this}getBearing(){return this.transform.bearing}setBearing(e,t){return this.jumpTo({bearing:e},t),this}getPadding(){return this.transform.padding}setPadding(e,t){return this.jumpTo({padding:e},t),this}rotateTo(e,i,r){return this.easeTo(t.extend({bearing:e},i),r)}resetNorth(e,i){return this.rotateTo(0,t.extend({duration:1e3},e),i),this}resetNorthPitch(e,i){return this.easeTo(t.extend({bearing:0,pitch:0,roll:0,duration:1e3},e),i),this}snapToNorth(e,t){return Math.abs(this.getBearing()){m.easeFunc(t),this.terrain&&!e.freezeElevation&&this._updateElevation(t),this._applyUpdatedTransform(r),this._fireMoveEvents(i);}),(t=>{this.terrain&&e.freezeElevation&&this._finalizeElevation(),this._afterEase(i,t);}),e),this}_prepareEase(e,i,r={}){this._moving=!0,i||r.moving||this.fire(new t.Event("movestart",e)),this._zooming&&!r.zooming&&this.fire(new t.Event("zoomstart",e)),this._rotating&&!r.rotating&&this.fire(new t.Event("rotatestart",e)),this._pitching&&!r.pitching&&this.fire(new t.Event("pitchstart",e)),this._rolling&&!r.rolling&&this.fire(new t.Event("rollstart",e));}_prepareElevation(e){this._elevationCenter=e,this._elevationStart=this.transform.elevation,this._elevationTarget=this.terrain.getElevationForLngLatZoom(e,this.transform.tileZoom),this._elevationFreeze=!0;}_updateElevation(e){this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom));const i=this.terrain.getElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom);if(e<1&&i!==this._elevationTarget){const t=this._elevationTarget-this._elevationStart;this._elevationStart+=e*(t-(i-(t*e+this._elevationStart))/(1-e)),this._elevationTarget=i;}this.transform.setElevation(t.interpolateFactory.number(this._elevationStart,this._elevationTarget,e));}_finalizeElevation(){this._elevationFreeze=!1,this.getCenterClampedToGround()&&this.transform.recalculateZoomAndCenter(this.terrain);}_getTransformForUpdate(){return this.transformCameraUpdate||this.terrain?(this._requestedCameraState||(this._requestedCameraState=this.transform.clone()),this._requestedCameraState):this.transform}_elevateCameraIfInsideTerrain(e){if(!this.terrain&&e.elevation>=0&&e.pitch<=90)return {};const t=e.getCameraLngLat(),i=e.getCameraAltitude(),r=this.terrain?this.terrain.getElevationForLngLatZoom(t,e.zoom):0;if(ithis._elevateCameraIfInsideTerrain(e))),this.transformCameraUpdate&&t.push((e=>this.transformCameraUpdate(e))),!t.length)return;const i=e.clone();for(const e of t){const t=i.clone(),{center:r,zoom:o,roll:a,pitch:s,bearing:n,elevation:l}=e(t);r&&t.setCenter(r),void 0!==l&&t.setElevation(l),void 0!==o&&t.setZoom(o),void 0!==a&&t.setRoll(a),void 0!==s&&t.setPitch(s),void 0!==n&&t.setBearing(n),i.apply(t);}this.transform.apply(i);}_fireMoveEvents(e){this.fire(new t.Event("move",e)),this._zooming&&this.fire(new t.Event("zoom",e)),this._rotating&&this.fire(new t.Event("rotate",e)),this._pitching&&this.fire(new t.Event("pitch",e)),this._rolling&&this.fire(new t.Event("roll",e));}_afterEase(e,i){if(this._easeId&&i&&this._easeId===i)return;delete this._easeId;const r=this._zooming,o=this._rotating,a=this._pitching,s=this._rolling;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._rolling=!1,this._padding=!1,r&&this.fire(new t.Event("zoomend",e)),o&&this.fire(new t.Event("rotateend",e)),a&&this.fire(new t.Event("pitchend",e)),s&&this.fire(new t.Event("rollend",e)),this.fire(new t.Event("moveend",e));}flyTo(e,i){if(!e.essential&&f.prefersReducedMotion){const r=t.pick(e,["center","zoom","bearing","pitch","roll","elevation"]);return this.jumpTo(r,i)}this.stop(),e=t.extend({offset:[0,0],speed:1.2,curve:1.42,easing:t.defaultEasing},e);const r=this._getTransformForUpdate(),o=r.bearing,a=r.pitch,s=r.roll,n=r.padding,l="bearing"in e?this._normalizeBearing(e.bearing,o):o,c="pitch"in e?+e.pitch:a,h="roll"in e?this._normalizeBearing(e.roll,s):s,u="padding"in e?e.padding:r.padding,d=t.Point.convert(e.offset);let _=r.centerPoint.add(d);const p=r.screenPointToLocation(_),m=this.cameraHelper.handleFlyTo(r,{bearing:l,pitch:c,roll:h,padding:u,locationAtOffset:p,offsetAsPoint:d,center:e.center,minZoom:e.minZoom,zoom:e.zoom});let g=e.curve;const v=Math.max(r.width,r.height),y=v/m.scaleOfZoom,x=m.pixelPathLength;"number"==typeof m.scaleOfMinZoom&&(g=Math.sqrt(v/m.scaleOfMinZoom/x*2));const b=g*g;function w(e){const t=(y*y-v*v+(e?-1:1)*b*b*x*x)/(2*(e?y:v)*b*x);return Math.log(Math.sqrt(t*t+1)-t)}function T(e){return (Math.exp(e)-Math.exp(-e))/2}function E(e){return (Math.exp(e)+Math.exp(-e))/2}const P=w(!1);let I=function(e){return E(P)/E(P+g*e)},C=function(e){return v*((E(P)*(T(t=P+g*e)/E(t))-T(P))/b)/x;var t;},M=(w(!0)-P)/g;if(Math.abs(x)<2e-6||!isFinite(M)){if(Math.abs(v-y)<1e-6)return this.easeTo(e,i);const t=y0,I=e=>Math.exp(t*g*e);}return e.duration="duration"in e?+e.duration:1e3*M/("screenSpeed"in e?+e.screenSpeed/g:+e.speed),e.maxDuration&&e.duration>e.maxDuration&&(e.duration=0),this._zooming=!0,this._rotating=o!==l,this._pitching=c!==a,this._rolling=h!==s,this._padding=!r.isPaddingEqual(u),this._prepareEase(i,!1),this.terrain&&this._prepareElevation(m.targetCenter),this._ease((p=>{const f=p*M,g=1/I(f),v=C(f);this._rotating&&r.setBearing(t.interpolateFactory.number(o,l,p)),this._pitching&&r.setPitch(t.interpolateFactory.number(a,c,p)),this._rolling&&r.setRoll(t.interpolateFactory.number(s,h,p)),this._padding&&(r.interpolatePadding(n,u,p),_=r.centerPoint.add(d)),m.easeFunc(p,g,v,_),this.terrain&&!e.freezeElevation&&this._updateElevation(p),this._applyUpdatedTransform(r),this._fireMoveEvents(i);}),(()=>{this.terrain&&e.freezeElevation&&this._finalizeElevation(),this._afterEase(i);}),e),this}isEasing(){return !!this._easeFrameId}stop(){return this._stop()}_stop(e,t){var i;if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),delete this._easeFrameId,delete this._onEaseFrame),this._onEaseEnd){const e=this._onEaseEnd;delete this._onEaseEnd,e.call(this,t);}return e||null===(i=this.handlers)||void 0===i||i.stop(!1),this}_ease(e,t,i){!1===i.animate||0===i.duration?(e(1),t()):(this._easeStart=f.now(),this._easeOptions=i,this._onEaseFrame=e,this._onEaseEnd=t,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback));}_normalizeBearing(e,i){e=t.wrap(e,-180,180);const r=Math.abs(e-i);return Math.abs(e-360-i)MapLibre'};class Ma{constructor(e=Ca){this._toggleAttribution=()=>{this._container.classList.contains("maplibregl-compact")&&(this._container.classList.contains("maplibregl-compact-show")?(this._container.setAttribute("open",""),this._container.classList.remove("maplibregl-compact-show")):(this._container.classList.add("maplibregl-compact-show"),this._container.removeAttribute("open")));},this._updateData=e=>{!e||"metadata"!==e.sourceDataType&&"visibility"!==e.sourceDataType&&"style"!==e.dataType&&"terrain"!==e.type||this._updateAttributions();},this._updateCompact=()=>{this._map.getCanvasContainer().offsetWidth<=640||this._compact?!1===this._compact?this._container.setAttribute("open",""):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")):(this._container.setAttribute("open",""),this._container.classList.contains("maplibregl-compact")&&this._container.classList.remove("maplibregl-compact","maplibregl-compact-show"));},this._updateCompactMinimize=()=>{this._container.classList.contains("maplibregl-compact")&&this._container.classList.contains("maplibregl-compact-show")&&this._container.classList.remove("maplibregl-compact-show");},this.options=e;}getDefaultPosition(){return "bottom-right"}onAdd(e){return this._map=e,this._compact=this.options.compact,this._container=wi.create("details","maplibregl-ctrl maplibregl-ctrl-attrib"),this._compactButton=wi.create("summary","maplibregl-ctrl-attrib-button",this._container),this._compactButton.addEventListener("click",this._toggleAttribution),this._setElementTitle(this._compactButton,"ToggleAttribution"),this._innerContainer=wi.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),this._container}onRemove(){wi.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=void 0,this._compact=void 0,this._sanitizedAttributionHTML=void 0;}_setElementTitle(e,t){const i=this._map._getUIString(`AttributionControl.${t}`);e.title=i,e.setAttribute("aria-label",i);}_updateAttributions(){if(!this._map.style)return;let e=[];if(this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?e=e.concat(this.options.customAttribution.map((e=>"string"!=typeof e?"":e))):"string"==typeof this.options.customAttribution&&e.push(this.options.customAttribution)),this._map.style.stylesheet){const e=this._map.style.stylesheet;this.styleOwner=e.owner,this.styleId=e.id;}const t=this._map.style.sourceCaches;for(const i in t){const r=t[i];if(r.used||r.usedForTerrain){const t=r.getSource();t.attribution&&e.indexOf(t.attribution)<0&&e.push(t.attribution);}}e=e.filter((e=>String(e).trim())),e.sort(((e,t)=>e.length-t.length)),e=e.filter(((t,i)=>{for(let r=i+1;r=0)return !1;return !0}));const i=e.join(" | ");i!==this._sanitizedAttributionHTML&&(this._sanitizedAttributionHTML=wi.sanitize(i),e.length?(this._innerContainer.innerHTML=this._sanitizedAttributionHTML,this._container.classList.remove("maplibregl-attrib-empty")):this._container.classList.add("maplibregl-attrib-empty"),this._updateCompact(),this._editLink=null);}}class Sa{constructor(e={}){this._updateCompact=()=>{const e=this._container.children;if(e.length){const t=e[0];this._map.getCanvasContainer().offsetWidth<=640||this._compact?!1!==this._compact&&t.classList.add("maplibregl-compact"):t.classList.remove("maplibregl-compact");}},this.options=e;}getDefaultPosition(){return "bottom-left"}onAdd(e){this._map=e,this._compact=this.options&&this.options.compact,this._container=wi.create("div","maplibregl-ctrl");const t=wi.create("a","maplibregl-ctrl-logo");return t.target="_blank",t.rel="noopener nofollow",t.href="https://maplibre.org/",t.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),t.setAttribute("rel","noopener nofollow"),this._container.appendChild(t),this._container.style.display="block",this._map.on("resize",this._updateCompact),this._updateCompact(),this._container}onRemove(){wi.remove(this._container),this._map.off("resize",this._updateCompact),this._map=void 0,this._compact=void 0;}}class Ra{constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1;}add(e){const t=++this._id;return this._queue.push({callback:e,id:t,cancelled:!1}),t}remove(e){const t=this._currentlyRunning,i=t?this._queue.concat(t):this._queue;for(const t of i)if(t.id===e)return void(t.cancelled=!0)}run(e=0){if(this._currentlyRunning)throw new Error("Attempting to run(), but is already running.");const t=this._currentlyRunning=this._queue;this._queue=[];for(const i of t)if(!i.cancelled&&(i.callback(e),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1;}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[];}}var Da=t.createLayout([{name:"a_pos3d",type:"Int16",components:3}]);class za extends t.Evented{constructor(e){super(),this._lastTilesetChange=f.now(),this.sourceCache=e,this._tiles={},this._renderableTilesKeys=[],this._sourceTileCache={},this.minzoom=0,this.maxzoom=22,this.deltaZoom=1,this.tileSize=e._source.tileSize*2**this.deltaZoom,e.usedForTerrain=!0,e.tileSize=this.tileSize;}destruct(){this.sourceCache.usedForTerrain=!1,this.sourceCache.tileSize=null;}update(e,i){this.sourceCache.update(e,i),this._renderableTilesKeys=[];const r={};for(const o of ve(e,{tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,reparseOverscaled:!1,terrain:i,calculateTileZoom:this.sourceCache._source.calculateTileZoom}))r[o.key]=!0,this._renderableTilesKeys.push(o.key),this._tiles[o.key]||(o.terrainRttPosMatrix32f=new Float64Array(16),t.ortho(o.terrainRttPosMatrix32f,0,t.EXTENT,t.EXTENT,0,0,1),this._tiles[o.key]=new ae(o,this.tileSize),this._lastTilesetChange=f.now());for(const e in this._tiles)r[e]||delete this._tiles[e];}freeRtt(e){for(const t in this._tiles){const i=this._tiles[t];(!e||i.tileID.equals(e)||i.tileID.isChildOf(e)||e.isChildOf(i.tileID))&&(i.rtt=[]);}}getRenderableTiles(){return this._renderableTilesKeys.map((e=>this.getTileByID(e)))}getTileByID(e){return this._tiles[e]}getTerrainCoords(e){const i={};for(const r of this._renderableTilesKeys){const o=this._tiles[r].tileID,a=e.clone(),s=t.createMat4f64();if(o.canonical.equals(e.canonical))t.ortho(s,0,t.EXTENT,t.EXTENT,0,0,1);else if(o.canonical.isChildOf(e.canonical)){const i=o.canonical.z-e.canonical.z,r=o.canonical.x-(o.canonical.x>>i<>i<>i;t.ortho(s,0,n,n,0,0,1),t.translate(s,s,[-r*n,-a*n,0]);}else {if(!e.canonical.isChildOf(o.canonical))continue;{const i=e.canonical.z-o.canonical.z,r=e.canonical.x-(e.canonical.x>>i<>i<>i;t.ortho(s,0,t.EXTENT,t.EXTENT,0,0,1),t.translate(s,s,[r*n,a*n,0]),t.scale(s,s,[1/2**i,1/2**i,0]);}}a.terrainRttPosMatrix32f=new Float32Array(s),i[r]=a;}return i}getSourceTile(e,t){const i=this.sourceCache._source;let r=e.overscaledZ-this.deltaZoom;if(r>i.maxzoom&&(r=i.maxzoom),r=i.minzoom&&(!o||!o.dem);)o=this.sourceCache.getTileByID(e.scaledTo(r--).key);return o}anyTilesAfterTime(e=Date.now()){return this._lastTilesetChange>=e}}class La{constructor(e,t,i){this.painter=e,this.sourceCache=new za(t),this.options=i,this.exaggeration="number"==typeof i.exaggeration?i.exaggeration:1,this.qualityFactor=2,this.meshSize=128,this._demMatrixCache={},this.coordsIndex=[],this._coordsTextureSize=1024;}getDEMElevation(e,i,r,o=t.EXTENT){var a;if(!(i>=0&&i=0&&re.canonical.z&&(e.canonical.z>=r?o=e.canonical.z-r:t.warnOnce("cannot calculate elevation if elevation maxzoom > source.maxzoom"));const a=e.canonical.x-(e.canonical.x>>o<>o<>8<<4|e>>8,i[t+3]=0;const r=new t.RGBAImage({width:this._coordsTextureSize,height:this._coordsTextureSize},new Uint8Array(i.buffer)),o=new y(e,r,e.gl.RGBA,{premultiply:!1});return o.bind(e.gl.NEAREST,e.gl.CLAMP_TO_EDGE),this._coordsTexture=o,o}pointCoordinate(e){this.painter.maybeDrawDepthAndCoords(!0);const i=new Uint8Array(4),r=this.painter.context,o=r.gl,a=Math.round(e.x*this.painter.pixelRatio/devicePixelRatio),s=Math.round(e.y*this.painter.pixelRatio/devicePixelRatio),n=Math.round(this.painter.height/devicePixelRatio);r.bindFramebuffer.set(this.getFramebuffer("coords").framebuffer),o.readPixels(a,n-s-1,1,1,o.RGBA,o.UNSIGNED_BYTE,i),r.bindFramebuffer.set(null);const l=i[0]+(i[2]>>4<<8),c=i[1]+((15&i[2])<<8),h=this.coordsIndex[255-i[3]],u=h&&this.sourceCache.getTileByID(h);if(!u)return null;const d=this._coordsTextureSize,_=(1<e.id!==t)),this._recentlyUsed.push(e.id);}stampObject(e){e.stamp=++this._stamp;}getOrCreateFreeObject(){for(const e of this._recentlyUsed)if(!this._objects[e].inUse)return this._objects[e];if(this._objects.length>=this._size)throw new Error("No free RenderPool available, call freeAllObjects() required!");const e=this._createObject(this._objects.length);return this._objects.push(e),e}freeObject(e){e.inUse=!1;}freeAllObjects(){for(const e of this._objects)this.freeObject(e);}isFull(){return !(this._objects.length!e.inUse))}}const ka={background:!0,fill:!0,line:!0,raster:!0,hillshade:!0};class Fa{constructor(e,t){this.painter=e,this.terrain=t,this.pool=new Aa(e.context,30,t.sourceCache.tileSize*t.qualityFactor);}destruct(){this.pool.destruct();}getTexture(e){return this.pool.getObjectForId(e.rtt[this._stacks.length-1].id).texture}prepareForRender(e,t){this._stacks=[],this._prevType=null,this._rttTiles=[],this._renderableTiles=this.terrain.sourceCache.getRenderableTiles(),this._renderableLayerIds=e._order.filter((i=>!e._layers[i].isHidden(t))),this._coordsAscending={};for(const t in e.sourceCaches){this._coordsAscending[t]={};const i=e.sourceCaches[t].getVisibleCoordinates();for(const e of i){const i=this.terrain.sourceCache.getTerrainCoords(e);for(const e in i)this._coordsAscending[t][e]||(this._coordsAscending[t][e]=[]),this._coordsAscending[t][e].push(i[e]);}}this._coordsAscendingStr={};for(const t of e._order){const i=e._layers[t],r=i.source;if(ka[i.type]&&!this._coordsAscendingStr[r]){this._coordsAscendingStr[r]={};for(const e in this._coordsAscending[r])this._coordsAscendingStr[r][e]=this._coordsAscending[r][e].map((e=>e.key)).sort().join();}}for(const e of this._renderableTiles)for(const t in this._coordsAscendingStr){const i=this._coordsAscendingStr[t][e.tileID.key];i&&i!==e.rttCoords[t]&&(e.rtt=[]);}}renderLayer(e,i){if(e.isHidden(this.painter.transform.zoom))return !1;const r=Object.assign(Object.assign({},i),{isRenderingToTexture:!0}),o=e.type,a=this.painter,s=this._renderableLayerIds[this._renderableLayerIds.length-1]===e.id;if(ka[o]&&(this._prevType&&ka[this._prevType]||this._stacks.push([]),this._prevType=o,this._stacks[this._stacks.length-1].push(e.id),!s))return !0;if(ka[this._prevType]||ka[o]&&s){this._prevType=o;const e=this._stacks.length-1,i=this._stacks[e]||[];for(const o of this._renderableTiles){if(this.pool.isFull()&&(To(this.painter,this.terrain,this._rttTiles,r),this._rttTiles=[],this.pool.freeAllObjects()),this._rttTiles.push(o),o.rtt[e]){const t=this.pool.getObjectForId(o.rtt[e].id);if(t.stamp===o.rtt[e].stamp){this.pool.useObject(t);continue}}const s=this.pool.getOrCreateFreeObject();this.pool.useObject(s),this.pool.stampObject(s),o.rtt[e]={id:s.id,stamp:s.stamp},a.context.bindFramebuffer.set(s.fbo.framebuffer),a.context.clear({color:t.Color.transparent,stencil:0}),a.currentStencilSource=void 0;for(let e=0;ei.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(null!=i.minPitch&&null!=i.maxPitch&&i.minPitch>i.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(null!=i.minPitch&&i.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(null!=i.maxPitch&&i.maxPitch>180)throw new Error("maxPitch must be less than or equal to 180");const r=new Ft,o=new Ut;if(void 0!==i.minZoom&&r.setMinZoom(i.minZoom),void 0!==i.maxZoom&&r.setMaxZoom(i.maxZoom),void 0!==i.minPitch&&r.setMinPitch(i.minPitch),void 0!==i.maxPitch&&r.setMaxPitch(i.maxPitch),void 0!==i.renderWorldCopies&&r.setRenderWorldCopies(i.renderWorldCopies),super(r,o,{bearingSnap:i.bearingSnap}),this._idleTriggered=!1,this._crossFadingFactor=1,this._renderTaskQueue=new Ra,this._controls=[],this._mapId=t.uniqueId(),this._contextLost=e=>{e.preventDefault(),this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this.fire(new t.Event("webglcontextlost",{originalEvent:e}));},this._contextRestored=e=>{this._setupPainter(),this.resize(),this._update(),this.fire(new t.Event("webglcontextrestored",{originalEvent:e}));},this._onMapScroll=e=>{if(e.target===this._container)return this._container.scrollTop=0,this._container.scrollLeft=0,!1},this._onWindowOnline=()=>{this._update();},this._interactive=i.interactive,this._maxTileCacheSize=i.maxTileCacheSize,this._maxTileCacheZoomLevels=i.maxTileCacheZoomLevels,this._failIfMajorPerformanceCaveat=!0===i.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=!0===i.preserveDrawingBuffer,this._antialias=!0===i.antialias,this._trackResize=!0===i.trackResize,this._bearingSnap=i.bearingSnap,this._centerClampedToGround=i.centerClampedToGround,this._refreshExpiredTiles=!0===i.refreshExpiredTiles,this._fadeDuration=i.fadeDuration,this._crossSourceCollisions=!0===i.crossSourceCollisions,this._collectResourceTiming=!0===i.collectResourceTiming,this._locale=Object.assign(Object.assign({},Ba),i.locale),this._clickTolerance=i.clickTolerance,this._overridePixelRatio=i.pixelRatio,this._maxCanvasSize=i.maxCanvasSize,this.transformCameraUpdate=i.transformCameraUpdate,this.cancelPendingTileRequestsWhileZooming=!0===i.cancelPendingTileRequestsWhileZooming,this._imageQueueHandle=_.addThrottleControl((()=>this.isMoving())),this._requestManager=new vi(i.transformRequest),"string"==typeof i.container){if(this._container=document.getElementById(i.container),!this._container)throw new Error(`Container '${i.container}' not found.`)}else {if(!(i.container instanceof HTMLElement))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=i.container;}if(i.maxBounds&&this.setMaxBounds(i.maxBounds),this._setupContainer(),this._setupPainter(),this.on("move",(()=>this._update(!1))),this.on("moveend",(()=>this._update(!1))),this.on("zoom",(()=>this._update(!0))),this.on("terrain",(()=>{this.painter.terrainFacilitator.dirty=!0,this._update(!0);})),this.once("idle",(()=>{this._idleTriggered=!0;})),"undefined"!=typeof window){addEventListener("online",this._onWindowOnline,!1);let e=!1;const t=Io((e=>{this._trackResize&&!this._removed&&(this.resize(e),this.redraw());}),50);this._resizeObserver=new ResizeObserver((i=>{e?t(i):e=!0;})),this._resizeObserver.observe(this._container);}this.handlers=new Pa(this,i),this._hash=i.hash&&new Co("string"==typeof i.hash&&i.hash||void 0).addTo(this),this._hash&&this._hash._onHashChange()||(this.jumpTo({center:i.center,elevation:i.elevation,zoom:i.zoom,bearing:i.bearing,pitch:i.pitch,roll:i.roll}),i.bounds&&(this.resize(),this.fitBounds(i.bounds,t.extend({},i.fitBoundsOptions,{duration:0})))),this.resize(),this._localIdeographFontFamily=i.localIdeographFontFamily,this._validateStyle=i.validateStyle,i.style&&this.setStyle(i.style,{localIdeographFontFamily:i.localIdeographFontFamily}),i.attributionControl&&this.addControl(new Ma("boolean"==typeof i.attributionControl?void 0:i.attributionControl)),i.maplibreLogo&&this.addControl(new Sa,i.logoPosition),this.on("style.load",(()=>{if(this.transform.unmodified){const e=t.pick(this.style.stylesheet,["center","zoom","bearing","pitch","roll"]);this.jumpTo(e);}})),this.on("data",(e=>{this._update("style"===e.dataType),this.fire(new t.Event(`${e.dataType}data`,e));})),this.on("dataloading",(e=>{this.fire(new t.Event(`${e.dataType}dataloading`,e));})),this.on("dataabort",(e=>{this.fire(new t.Event("sourcedataabort",e));}));}_getMapId(){return this._mapId}addControl(e,i){if(void 0===i&&(i=e.getDefaultPosition?e.getDefaultPosition():"top-right"),!e||!e.onAdd)return this.fire(new t.ErrorEvent(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));const r=e.onAdd(this);this._controls.push(e);const o=this._controlPositions[i];return -1!==i.indexOf("bottom")?o.insertBefore(r,o.firstChild):o.appendChild(r),this}removeControl(e){if(!e||!e.onRemove)return this.fire(new t.ErrorEvent(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));const i=this._controls.indexOf(e);return i>-1&&this._controls.splice(i,1),e.onRemove(this),this}hasControl(e){return this._controls.indexOf(e)>-1}calculateCameraOptionsFromTo(e,t,i,r){return null==r&&this.terrain&&(r=this.terrain.getElevationForLngLatZoom(i,this.transform.tileZoom)),super.calculateCameraOptionsFromTo(e,t,i,r)}resize(e){var i;const r=this._containerDimensions(),o=r[0],a=r[1],s=this._getClampedPixelRatio(o,a);if(this._resizeCanvas(o,a,s),this.painter.resize(o,a,s),this.painter.overLimit()){const e=this.painter.context.gl;this._maxCanvasSize=[e.drawingBufferWidth,e.drawingBufferHeight];const t=this._getClampedPixelRatio(o,a);this._resizeCanvas(o,a,t),this.painter.resize(o,a,t);}this.transform.resize(o,a),null===(i=this._requestedCameraState)||void 0===i||i.resize(o,a);const n=!this._moving;return n&&(this.stop(),this.fire(new t.Event("movestart",e)).fire(new t.Event("move",e))),this.fire(new t.Event("resize",e)),n&&this.fire(new t.Event("moveend",e)),this}_getClampedPixelRatio(e,t){const{0:i,1:r}=this._maxCanvasSize,o=this.getPixelRatio(),a=e*o,s=t*o;return Math.min(a>i?i/a:1,s>r?r/s:1)*o}getPixelRatio(){var e;return null!==(e=this._overridePixelRatio)&&void 0!==e?e:devicePixelRatio}setPixelRatio(e){this._overridePixelRatio=e,this.resize();}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()}setMaxBounds(e){return this.transform.setMaxBounds(V.convert(e)),this._update()}setMinZoom(e){if((e=null==e?-2:e)>=-2&&e<=this.transform.maxZoom)return this.transform.setMinZoom(e),this._update(),this.getZoom()=this.transform.minZoom)return this.transform.setMaxZoom(e),this._update(),this.getZoom()>e&&this.setZoom(e),this;throw new Error("maxZoom must be greater than the current minZoom")}getMaxZoom(){return this.transform.maxZoom}setMinPitch(e){if((e=null==e?0:e)<0)throw new Error("minPitch must be greater than or equal to 0");if(e>=0&&e<=this.transform.maxPitch)return this.transform.setMinPitch(e),this._update(),this.getPitch()180)throw new Error("maxPitch must be less than or equal to 180");if(e>=this.transform.minPitch)return this.transform.setMaxPitch(e),this._update(),this.getPitch()>e&&this.setPitch(e),this;throw new Error("maxPitch must be greater than the current minPitch")}getMaxPitch(){return this.transform.maxPitch}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(e){return this.transform.setRenderWorldCopies(e),this._update()}project(e){return this.transform.locationToScreenPoint(t.LngLat.convert(e),this.style&&this.terrain)}unproject(e){return this.transform.screenPointToLocation(t.Point.convert(e),this.terrain)}isMoving(){var e;return this._moving||(null===(e=this.handlers)||void 0===e?void 0:e.isMoving())}isZooming(){var e;return this._zooming||(null===(e=this.handlers)||void 0===e?void 0:e.isZooming())}isRotating(){var e;return this._rotating||(null===(e=this.handlers)||void 0===e?void 0:e.isRotating())}_createDelegatedListener(e,t,i){if("mouseenter"===e||"mouseover"===e){let r=!1;const o=o=>{const a=t.filter((e=>this.getLayer(e))),s=0!==a.length?this.queryRenderedFeatures(o.point,{layers:a}):[];s.length?r||(r=!0,i.call(this,new Bo(e,this,o.originalEvent,{features:s}))):r=!1;};return {layers:t,listener:i,delegates:{mousemove:o,mouseout:()=>{r=!1;}}}}if("mouseleave"===e||"mouseout"===e){let r=!1;const o=o=>{const a=t.filter((e=>this.getLayer(e)));(0!==a.length?this.queryRenderedFeatures(o.point,{layers:a}):[]).length?r=!0:r&&(r=!1,i.call(this,new Bo(e,this,o.originalEvent)));},a=t=>{r&&(r=!1,i.call(this,new Bo(e,this,t.originalEvent)));};return {layers:t,listener:i,delegates:{mousemove:o,mouseout:a}}}{const r=e=>{const r=t.filter((e=>this.getLayer(e))),o=0!==r.length?this.queryRenderedFeatures(e.point,{layers:r}):[];o.length&&(e.features=o,i.call(this,e),delete e.features);};return {layers:t,listener:i,delegates:{[e]:r}}}}_saveDelegatedListener(e,t){this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[e]=this._delegatedListeners[e]||[],this._delegatedListeners[e].push(t);}_removeDelegatedListener(e,t,i){if(!this._delegatedListeners||!this._delegatedListeners[e])return;const r=this._delegatedListeners[e];for(let e=0;et.includes(e)))){for(const e in o.delegates)this.off(e,o.delegates[e]);return void r.splice(e,1)}}}on(e,t,i){if(void 0===i)return super.on(e,t);const r="string"==typeof t?[t]:t,o=this._createDelegatedListener(e,r,i);this._saveDelegatedListener(e,o);for(const e in o.delegates)this.on(e,o.delegates[e]);return {unsubscribe:()=>{this._removeDelegatedListener(e,r,i);}}}once(e,t,i){if(void 0===i)return super.once(e,t);const r="string"==typeof t?[t]:t,o=this._createDelegatedListener(e,r,i);for(const t in o.delegates){const a=o.delegates[t];o.delegates[t]=(...t)=>{this._removeDelegatedListener(e,r,i),a(...t);};}this._saveDelegatedListener(e,o);for(const e in o.delegates)this.once(e,o.delegates[e]);return this}off(e,t,i){return void 0===i?super.off(e,t):(this._removeDelegatedListener(e,"string"==typeof t?[t]:t,i),this)}queryRenderedFeatures(e,i){if(!this.style)return [];let r;const o=e instanceof t.Point||Array.isArray(e),a=o?e:[[0,0],[this.transform.width,this.transform.height]];if(i=i||(o?{}:e)||{},a instanceof t.Point||"number"==typeof a[0])r=[t.Point.convert(a)];else {const e=t.Point.convert(a[0]),i=t.Point.convert(a[1]);r=[e,new t.Point(i.x,e.y),i,new t.Point(e.x,i.y),e];}return this.style.queryRenderedFeatures(r,i,this.transform)}querySourceFeatures(e,t){return this.style.querySourceFeatures(e,t)}setStyle(e,i){return !1!==(i=t.extend({},{localIdeographFontFamily:this._localIdeographFontFamily,validate:this._validateStyle},i)).diff&&i.localIdeographFontFamily===this._localIdeographFontFamily&&this.style&&e?(this._diffStyle(e,i),this):(this._localIdeographFontFamily=i.localIdeographFontFamily,this._updateStyle(e,i))}setTransformRequest(e){return this._requestManager.setTransformRequest(e),this}_getUIString(e){const t=this._locale[e];if(null==t)throw new Error(`Missing UI string '${e}'`);return t}_updateStyle(e,t){var i,r;if(t.transformStyle&&this.style&&!this.style._loaded)return void this.style.once("style.load",(()=>this._updateStyle(e,t)));const o=this.style&&t.transformStyle?this.style.serialize():void 0;return this.style&&(this.style.setEventedParent(null),this.style._remove(!e)),e?(this.style=new gi(this,t||{}),this.style.setEventedParent(this,{style:this.style}),"string"==typeof e?this.style.loadURL(e,t,o):this.style.loadJSON(e,t,o),this):(null===(r=null===(i=this.style)||void 0===i?void 0:i.projection)||void 0===r||r.destroy(),delete this.style,this)}_lazyInitEmptyStyle(){this.style||(this.style=new gi(this,{}),this.style.setEventedParent(this,{style:this.style}),this.style.loadEmpty());}_diffStyle(e,i){if("string"==typeof e){const r=this._requestManager.transformRequest(e,"Style");t.getJSON(r,new AbortController).then((e=>{this._updateDiff(e.data,i);})).catch((e=>{e&&this.fire(new t.ErrorEvent(e));}));}else "object"==typeof e&&this._updateDiff(e,i);}_updateDiff(e,i){try{this.style.setState(e,i)&&this._update(!0);}catch(r){t.warnOnce(`Unable to perform style diff: ${r.message||r.error||r}. Rebuilding the style from scratch.`),this._updateStyle(e,i);}}getStyle(){if(this.style)return this.style.serialize()}isStyleLoaded(){return this.style?this.style.loaded():t.warnOnce("There is no style added to the map.")}addSource(e,t){return this._lazyInitEmptyStyle(),this.style.addSource(e,t),this._update(!0)}isSourceLoaded(e){const i=this.style&&this.style.sourceCaches[e];if(void 0!==i)return i.loaded();this.fire(new t.ErrorEvent(new Error(`There is no source with ID '${e}'`)));}setTerrain(e){if(this.style._checkLoaded(),this._terrainDataCallback&&this.style.off("data",this._terrainDataCallback),e){const i=this.style.sourceCaches[e.source];if(!i)throw new Error(`cannot load terrain, because there exists no source with ID: ${e.source}`);null===this.terrain&&i.reload();for(const i in this.style._layers){const r=this.style._layers[i];"hillshade"===r.type&&r.source===e.source&&t.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 La(this.painter,i,e),this.painter.renderToTexture=new Fa(this.painter,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._terrainDataCallback=t=>{"style"===t.dataType?this.terrain.sourceCache.freeRtt():"source"===t.dataType&&t.tile&&(t.sourceId!==e.source||this._elevationFreeze||(this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))),this.terrain.sourceCache.freeRtt(t.tile.tileID));},this.style.on("data",this._terrainDataCallback);}else this.terrain&&this.terrain.sourceCache.destruct(),this.terrain=null,this.painter.renderToTexture&&this.painter.renderToTexture.destruct(),this.painter.renderToTexture=null,this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0);return this.fire(new t.Event("terrain",{terrain:e})),this}getTerrain(){var e,t;return null!==(t=null===(e=this.terrain)||void 0===e?void 0:e.options)&&void 0!==t?t:null}areTilesLoaded(){const e=this.style&&this.style.sourceCaches;for(const t in e){const i=e[t]._tiles;for(const e in i){const t=i[e];if("loaded"!==t.state&&"errored"!==t.state)return !1}}return !0}removeSource(e){return this.style.removeSource(e),this._update(!0)}getSource(e){return this.style.getSource(e)}addImage(e,i,r={}){const{pixelRatio:o=1,sdf:a=!1,stretchX:s,stretchY:n,content:l,textFitWidth:c,textFitHeight:h}=r;if(this._lazyInitEmptyStyle(),!(i instanceof HTMLImageElement||t.isImageBitmap(i))){if(void 0===i.width||void 0===i.height)return this.fire(new t.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`")));{const{width:r,height:u,data:d}=i,_=i;return this.style.addImage(e,{data:new t.RGBAImage({width:r,height:u},new Uint8Array(d)),pixelRatio:o,stretchX:s,stretchY:n,content:l,textFitWidth:c,textFitHeight:h,sdf:a,version:0,userImage:_}),_.onAdd&&_.onAdd(this,e),this}}{const{width:r,height:u,data:d}=f.getImageData(i);this.style.addImage(e,{data:new t.RGBAImage({width:r,height:u},d),pixelRatio:o,stretchX:s,stretchY:n,content:l,textFitWidth:c,textFitHeight:h,sdf:a,version:0});}}updateImage(e,i){const r=this.style.getImage(e);if(!r)return this.fire(new t.ErrorEvent(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));const o=i instanceof HTMLImageElement||t.isImageBitmap(i)?f.getImageData(i):i,{width:a,height:s,data:n}=o;if(void 0===a||void 0===s)return this.fire(new t.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(a!==r.data.width||s!==r.data.height)return this.fire(new t.ErrorEvent(new Error("The width and height of the updated image must be that same as the previous version of the image")));const l=!(i instanceof HTMLImageElement||t.isImageBitmap(i));return r.data.replace(n,l),this.style.updateImage(e,r),this}getImage(e){return this.style.getImage(e)}hasImage(e){return e?!!this.style.getImage(e):(this.fire(new t.ErrorEvent(new Error("Missing required image id"))),!1)}removeImage(e){this.style.removeImage(e);}loadImage(e){return _.getImage(this._requestManager.transformRequest(e,"Image"),new AbortController)}listImages(){return this.style.listImages()}addLayer(e,t){return this._lazyInitEmptyStyle(),this.style.addLayer(e,t),this._update(!0)}moveLayer(e,t){return this.style.moveLayer(e,t),this._update(!0)}removeLayer(e){return this.style.removeLayer(e),this._update(!0)}getLayer(e){return this.style.getLayer(e)}getLayersOrder(){return this.style.getLayersOrder()}setLayerZoomRange(e,t,i){return this.style.setLayerZoomRange(e,t,i),this._update(!0)}setFilter(e,t,i={}){return this.style.setFilter(e,t,i),this._update(!0)}getFilter(e){return this.style.getFilter(e)}setPaintProperty(e,t,i,r={}){return this.style.setPaintProperty(e,t,i,r),this._update(!0)}getPaintProperty(e,t){return this.style.getPaintProperty(e,t)}setLayoutProperty(e,t,i,r={}){return this.style.setLayoutProperty(e,t,i,r),this._update(!0)}getLayoutProperty(e,t){return this.style.getLayoutProperty(e,t)}setGlyphs(e,t={}){return this._lazyInitEmptyStyle(),this.style.setGlyphs(e,t),this._update(!0)}getGlyphs(){return this.style.getGlyphsUrl()}addSprite(e,t,i={}){return this._lazyInitEmptyStyle(),this.style.addSprite(e,t,i,(e=>{e||this._update(!0);})),this}removeSprite(e){return this._lazyInitEmptyStyle(),this.style.removeSprite(e),this._update(!0)}getSprite(){return this.style.getSprite()}setSprite(e,t={}){return this._lazyInitEmptyStyle(),this.style.setSprite(e,t,(e=>{e||this._update(!0);})),this}setLight(e,t={}){return this._lazyInitEmptyStyle(),this.style.setLight(e,t),this._update(!0)}getLight(){return this.style.getLight()}setSky(e,t={}){return this._lazyInitEmptyStyle(),this.style.setSky(e,t),this._update(!0)}getSky(){return this.style.getSky()}setFeatureState(e,t){return this.style.setFeatureState(e,t),this._update()}removeFeatureState(e,t){return this.style.removeFeatureState(e,t),this._update()}getFeatureState(e){return this.style.getFeatureState(e)}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}_containerDimensions(){let e=0,t=0;return this._container&&(e=this._container.clientWidth||400,t=this._container.clientHeight||300),[e,t]}_setupContainer(){const e=this._container;e.classList.add("maplibregl-map");const t=this._canvasContainer=wi.create("div","maplibregl-canvas-container",e);this._interactive&&t.classList.add("maplibregl-interactive"),this._canvas=wi.create("canvas","maplibregl-canvas",t),this._canvas.addEventListener("webglcontextlost",this._contextLost,!1),this._canvas.addEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.setAttribute("tabindex",this._interactive?"0":"-1"),this._canvas.setAttribute("aria-label",this._getUIString("Map.Title")),this._canvas.setAttribute("role","region");const i=this._containerDimensions(),r=this._getClampedPixelRatio(i[0],i[1]);this._resizeCanvas(i[0],i[1],r);const o=this._controlContainer=wi.create("div","maplibregl-control-container",e),a=this._controlPositions={};["top-left","top-right","bottom-left","bottom-right"].forEach((e=>{a[e]=wi.create("div",`maplibregl-ctrl-${e} `,o);})),this._container.addEventListener("scroll",this._onMapScroll,!1);}_resizeCanvas(e,t,i){this._canvas.width=Math.floor(i*e),this._canvas.height=Math.floor(i*t),this._canvas.style.width=`${e}px`,this._canvas.style.height=`${t}px`;}_setupPainter(){const e={alpha:!0,stencil:!0,depth:!0,failIfMajorPerformanceCaveat:this._failIfMajorPerformanceCaveat,preserveDrawingBuffer:this._preserveDrawingBuffer,antialias:this._antialias||!1};let t=null;this._canvas.addEventListener("webglcontextcreationerror",(i=>{t={requestedAttributes:e},i&&(t.statusMessage=i.statusMessage,t.type=i.type);}),{once:!0});const i=this._canvas.getContext("webgl2",e)||this._canvas.getContext("webgl",e);if(!i){const e="Failed to initialize WebGL";throw t?(t.message=e,new Error(JSON.stringify(t))):new Error(e)}this.painter=new Po(i,this.transform),n.testSupport(i);}migrateProjection(e,i){super.migrateProjection(e,i),this.painter.transform=e,this.fire(new t.Event("projectiontransition",{newProjection:this.style.projection.name}));}loaded(){return !this._styleDirty&&!this._sourcesDirty&&!!this.style&&this.style.loaded()}_update(e){return this.style&&this.style._loaded?(this._styleDirty=this._styleDirty||e,this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(e){return this._update(),this._renderTaskQueue.add(e)}_cancelRenderFrame(e){this._renderTaskQueue.remove(e);}_render(e){const i=this._idleTriggered?this._fadeDuration:0;if(this.painter.context.setDirty(),this.painter.setBaseState(),this._renderTaskQueue.run(e),this._removed)return;let r=!1;if(this.style&&this._styleDirty){this._styleDirty=!1;const e=this.transform.zoom,o=f.now();this.style.zoomHistory.update(e,o);const a=new t.EvaluationParameters(e,{now:o,fadeDuration:i,zoomHistory:this.style.zoomHistory,transition:this.style.getTransition()}),s=a.crossFadingFactor();1===s&&s===this._crossFadingFactor||(r=!0,this._crossFadingFactor=s),this.style.update(a);}const o=this.transform.newFrameUpdate();this.style&&(this._sourcesDirty||o.forceSourceUpdate)&&(this._sourcesDirty=!1,this.style._updateSources(this.transform)),this.terrain?(this.terrain.sourceCache.update(this.transform,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),!this._elevationFreeze&&this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))):(this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0)),this._placementDirty=this.style&&this.style._updatePlacement(this.transform,this.showCollisionBoxes,i,this._crossSourceCollisions,o.forcePlacementUpdate),o.fireProjectionEvent&&this.fire(new t.Event("projectiontransition",o.fireProjectionEvent)),this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showOverdrawInspector:this._showOverdrawInspector,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:i,showPadding:this.showPadding}),this.fire(new t.Event("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,t.PerformanceUtils.mark(t.PerformanceMarkers.load),this.fire(new t.Event("load"))),this.style&&(this.style.hasTransitions()||r)&&(this._styleDirty=!0),this.style&&!this._placementDirty&&this.style._releaseSymbolFadeTiles();const a=this._sourcesDirty||this._styleDirty||this._placementDirty||this.style.projection.isRenderingDirty()||this.transform.isRenderingDirty();return a||this._repaint?this.triggerRepaint():!this.isMoving()&&this.loaded()&&this.fire(new t.Event("idle")),!this._loaded||this._fullyLoaded||a||(this._fullyLoaded=!0,t.PerformanceUtils.mark(t.PerformanceMarkers.fullLoad)),this}redraw(){return this.style&&(this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._render(0)),this}remove(){var e;this._hash&&this._hash.remove();for(const e of this._controls)e.onRemove(this);this._controls=[],this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._renderTaskQueue.clear(),this.painter.destroy(),this.handlers.destroy(),delete this.handlers,this.setStyle(null),"undefined"!=typeof window&&removeEventListener("online",this._onWindowOnline,!1),_.removeThrottleControl(this._imageQueueHandle),null===(e=this._resizeObserver)||void 0===e||e.disconnect();const i=this.painter.context.gl.getExtension("WEBGL_lose_context");(null==i?void 0:i.loseContext)&&i.loseContext(),this._canvas.removeEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.removeEventListener("webglcontextlost",this._contextLost,!1),wi.remove(this._canvasContainer),wi.remove(this._controlContainer),this._container.removeEventListener("scroll",this._onMapScroll,!1),this._container.classList.remove("maplibregl-map"),t.PerformanceUtils.clearMetrics(),this._removed=!0,this.fire(new t.Event("remove"));}triggerRepaint(){this.style&&!this._frameRequest&&(this._frameRequest=new AbortController,f.frameAsync(this._frameRequest).then((e=>{t.PerformanceUtils.frame(e),this._frameRequest=null,this._render(e);})).catch((()=>{})));}get showTileBoundaries(){return !!this._showTileBoundaries}set showTileBoundaries(e){this._showTileBoundaries!==e&&(this._showTileBoundaries=e,this._update());}get showPadding(){return !!this._showPadding}set showPadding(e){this._showPadding!==e&&(this._showPadding=e,this._update());}get showCollisionBoxes(){return !!this._showCollisionBoxes}set showCollisionBoxes(e){this._showCollisionBoxes!==e&&(this._showCollisionBoxes=e,e?this.style._generateCollisionBoxes():this._update());}get showOverdrawInspector(){return !!this._showOverdrawInspector}set showOverdrawInspector(e){this._showOverdrawInspector!==e&&(this._showOverdrawInspector=e,this._update());}get repaint(){return !!this._repaint}set repaint(e){this._repaint!==e&&(this._repaint=e,this.triggerRepaint());}get vertices(){return !!this._vertices}set vertices(e){this._vertices=e,this._update();}get version(){return Oa}getCameraTargetElevation(){return this.transform.elevation}getProjection(){return this.style.getProjection()}setProjection(e){return this._lazyInitEmptyStyle(),this.style.setProjection(e),this._update(!0)}};const Na=e=>new Promise(((t,i)=>{e&&(e.stubRender=null==e.stubRender||e.stubRender,e.showMap=null!=e.showMap&&e.showMap);const r=document.createElement("div");r.style.width=`${e.width||512}px`,r.style.height=`${e.height||512}px`,r.style.margin="0 auto",r.style.display="block",e.showMap||(r.style.visibility="hidden"),document.body.appendChild(r);const o=new ja(Object.assign({container:r,style:"https://api.maptiler.com/maps/streets/style.json?key=get_your_own_OpIi9ZULNHzrESv6T2vL"},e));o.on(e.idle?"idle":"load",(()=>{e.stubRender&&o._frameRequest&&(o._frameRequest.abort(),o._frameRequest=null),t(o);})),o.on("error",(e=>i(e.error))),o.on("remove",(()=>r.remove()));}));function Ga(e){return JSON.parse(JSON.stringify(e,((e,t)=>ArrayBuffer.isView(t)?{}:t))||"{}")}class Za extends a{constructor(e,t){super(),this.style=e,this.locations=t;}setup(){return t.__awaiter(this,void 0,void 0,(function*(){try{this.maps=yield Promise.all(this.locations.map((e=>Na({zoom:e.zoom,width:1024,height:768,center:e.center,style:this.style}))));}catch(e){console.error(e);}}))}bench(){for(const e of this.maps)e._styleDirty=!0,e._sourcesDirty=!0,e._render(Date.now());}teardown(){for(const e of this.maps)e.remove();}}var Va={version:8,name:"Empty",sources:{openmaptiles:{url:"https://api.maptiler.com/tiles/v3/tiles.json?key=get_your_own_OpIi9ZULNHzrESv6T2vL",type:"vector"},maptiler_attribution:{type:"vector",attribution:'<a href="https://www.maptiler.com/copyright/"; target="_blank">&copy; MapTiler</a> <a href="https://www.openstreetmap.org/copyright"; target="_blank">&copy; OpenStreetMap contributors</a>'}},sprite:"https://api.maptiler.com/maps/streets/sprite",glyphs:"https://api.maptiler.com/fonts/{fontstack}/{range}.pbf?key=get_your_own_OpIi9ZULNHzrESv6T2vL",layers:[]};function qa(e){const t=[];for(let i=0;i<50;i++)t.push(Object.assign({},e,{id:e.id+i}));return t}function Wa(e){const t=[];for(let i=0;i<50;i++)t.push(Object.assign({},e,{id:e.id+i}));return t}class Xa extends a{constructor(e){super(),this.center=e;}setup(){return t.__awaiter(this,void 0,void 0,(function*(){const e=yield fetch("/test/bench/data/naturalearth-land.json"),t=yield e.json();this.numFeatures=t.features.length;const i=Object.assign({},Va,{sources:{land:{type:"geojson",data:t,maxzoom:23}},layers:Wa({id:"layer",type:"fill",source:"land",paint:{"fill-color":["case",["boolean",["feature-state","bench"],!1],["rgb",21,210,210],["rgb",233,233,233]]}})});try{this.map=yield Na({zoom:4,width:1024,height:768,center:this.center,style:i});}catch(e){console.error(e);}}))}bench(){this.map._styleDirty=!0,this.map._sourcesDirty=!0,this.map._render();}teardown(){this.map.remove();}}function $a(e){const t=[];for(let i=0;i<50;i++)t.push(Object.assign({},e,{id:e.id+i}));return t}class Ha extends a{setup(){return t.__awaiter(this,void 0,void 0,(function*(){try{this.map=yield Na({zoom:16,width:1024,height:768,center:[-77.032194,38.912753],style:this.layerStyle});}catch(e){console.error(e);}}))}bench(){this.map._render();}teardown(){this.map.remove();}}class Ka extends a{constructor(e){super(),this.style=e;}setup(){return t.__awaiter(this,void 0,void 0,(function*(){this.json=yield s(this.style);}))}bench(){t.validateStyleMin(this.json);}}class Ya extends a{constructor(e){super(),this.style=e;}setup(){return t.__awaiter(this,void 0,void 0,(function*(){const e=yield s(this.style);this.layers=t.derefLayers(e.layers);}))}bench(){for(const e of this.layers)t.createStyleLayer(e);}}const Ja=[];for(let e=0;e<4;e++)for(let t=0;t<4;t++)Ja.push([e/4*1024,t/4*768]);class Qa extends a{constructor(e,t){super(),this.style=e,this.locations=t;}setup(){return t.__awaiter(this,void 0,void 0,(function*(){try{this.maps=yield Promise.all(this.locations.map((e=>Na({zoom:e.zoom,width:1024,height:768,center:e.center,style:this.style}))));}catch(e){console.error(e);}}))}bench(){for(const e of this.maps)for(const t of Ja)e.queryRenderedFeatures(t,{});}teardown(){for(const e of this.maps)e.remove();}}class es extends a{constructor(e,t){super(),this.style=e,this.locations=t;}setup(){return t.__awaiter(this,void 0,void 0,(function*(){try{this.maps=yield Promise.all(this.locations.map((e=>Na({zoom:e.zoom,width:1024,height:768,center:e.center,style:this.style}))));}catch(e){console.error(e);}}))}bench(){for(const e of this.maps)e.queryRenderedFeatures({});}teardown(){for(const e of this.maps)e.remove();}}class ts extends a{constructor(e){super(),this.style=e;}setup(){return t.__awaiter(this,void 0,void 0,(function*(){const e=yield s(this.style);this.data=[];for(const i of e.layers){if(!i.type)continue;const e=(e,i)=>{const r=t.convertFunction(e,i),o=t.createFunction(e,i),a=t.createPropertyExpression(r,i);if("error"===a.result)throw new Error(a.value.map((e=>`${e.key}: ${e.message}`)).join(", "));return {propertySpec:i,rawValue:e,rawExpression:r,compiledFunction:o,compiledExpression:a.value}};for(const r in i.paint)t.isFunction$1(i.paint[r])&&this.data.push(e(i.paint[r],t.v8Spec[`paint_${i.type}`][r]));for(const r in i.layout)t.isFunction$1(i.layout[r])&&this.data.push(e(i.layout[r],t.v8Spec[`layout_${i.type}`][r]));}}))}}var is=[{filter:["==",["get","class"],"crop"],layer:"landcover"},{filter:["==",["get","class"],"grass"],layer:"landcover"},{filter:["==",["get","class"],"scrub"],layer:"landcover"},{filter:["==",["get","class"],"wood"],layer:"landcover"},{filter:["==",["get","class"],"snow"],layer:"landcover"},{filter:["==",["get","class"],"hospital"],layer:"landuse"},{filter:["==",["get","class"],"school"],layer:"landuse"},{filter:["==",["get","class"],"park"],layer:"landuse"},{filter:["==",["get","class"],"pitch"],layer:"landuse"},{filter:["==",["get","class"],"pitch"],layer:"landuse"},{filter:["==",["get","class"],"cemetery"],layer:"landuse"},{filter:["==",["get","class"],"industrial"],layer:"landuse"},{filter:["==",["get","class"],"sand"],layer:"landuse"},{filter:["==",["get","level"],94],layer:"hillshade"},{filter:["==",["get","level"],90],layer:"hillshade"},{filter:["==",["get","level"],89],layer:"hillshade"},{filter:["==",["get","level"],78],layer:"hillshade"},{filter:["==",["get","level"],67],layer:"hillshade"},{filter:["==",["get","level"],56],layer:"hillshade"},{filter:["all",["match",["get","class"],["river","canal"],!0,!1]],layer:"waterway"},{filter:["all",["==",["get","class"],"land"],["==",["geometry-type"],"Polygon"]],layer:"barrier_line"},{filter:["all",["==",["get","class"],"land"],["==",["geometry-type"],"LineString"]],layer:"barrier_line"},{filter:["all",["==",["get","type"],"apron"],["==",["geometry-type"],"Polygon"]],layer:"aeroway"},{filter:["all",["==",["get","class"],"street_limited"],["==",["geometry-type"],"Polygon"]],layer:"tunnel"},{filter:["==",["get","class"],"path"],layer:"tunnel"},{filter:["all",["==",["get","class"],"street"],["==",["geometry-type"],"LineString"]],layer:"tunnel"},{filter:["all",["==",["get","class"],"street_limited"],["==",["geometry-type"],"LineString"]],layer:"tunnel"},{filter:["==",["get","class"],"motorway_link"],layer:"tunnel"},{filter:["match",["get","class"],["service","driveway"],!0,!1],layer:"tunnel"},{filter:["all",["==",["get","class"],"street_limited"],["!=",["get","type"],"construction"],["==",["geometry-type"],"LineString"]],layer:"tunnel"},{filter:["==",["get","class"],"street"],layer:"tunnel"},{filter:["all",["==",["get","class"],"main"],["!=",["get","type"],"trunk"]],layer:"tunnel"},{filter:["all",["==",["get","class"],"main"],["==",["get","type"],"trunk"]],layer:"tunnel"},{filter:["==",["get","class"],"motorway"],layer:"tunnel"},{filter:["all",["==",["get","class"],"street_limited"],["==",["get","type"],"construction"],["==",["geometry-type"],"LineString"]],layer:"tunnel"},{filter:["all",["==",["get","oneway"],1],["match",["get","class"],["main","street","street_limited"],!0,!1],["!=",["get","type"],"trunk"]],layer:"tunnel"},{filter:["all",["==",["get","oneway"],1],["==",["get","type"],"trunk"]],layer:"tunnel"},{filter:["match",["get","class"],["major_rail","minor_rail"],!0,!1],layer:"tunnel"},{filter:["all",["==",["get","oneway"],1],["match",["get","class"],["motorway","motorway_link"],!0,!1]],layer:"tunnel"},{filter:["==",["get","class"],"path"],layer:"road"},{filter:["all",["==",["get","class"],"street"],["==",["geometry-type"],"LineString"]],layer:"road"},{filter:["all",["==",["get","class"],"street_limited"],["==",["geometry-type"],"LineString"]],layer:"road"},{filter:["match",["get","class"],["service","driveway"],!0,!1],layer:"road"},{filter:["all",["==",["get","class"],"street_limited"],["!=",["get","type"],"construction"],["==",["geometry-type"],"LineString"]],layer:"road"},{filter:["==",["get","class"],"street"],layer:"road"},{filter:["all",["==",["get","class"],"main"],["==",["get","type"],"trunk"]],layer:"road"},{filter:["==",["get","class"],"motorway"],layer:"road"},{filter:["all",["==",["get","oneway"],1],["match",["get","class"],["main","street","street_limited"],!0,!1],["!=",["get","type"],"trunk"]],layer:"road"},{filter:["all",["==",["get","oneway"],1],["==",["get","type"],"trunk"]],layer:"road"},{filter:["match",["get","class"],["major_rail","minor_rail"],!0,!1],layer:"road"},{filter:["all",["==",["get","class"],"street_limited"],["==",["get","type"],"construction"],["==",["geometry-type"],"LineString"]],layer:"road"},{filter:["all",["==",["get","oneway"],1],["match",["get","class"],["motorway","motorway_link"],!0,!1]],layer:"road"},{filter:["all",["==",["get","class"],"street_limited"],["==",["geometry-type"],"Polygon"]],layer:"bridge"},{filter:["==",["get","class"],"path"],layer:"bridge"},{filter:["all",["==",["get","class"],"street"],["==",["geometry-type"],"LineString"]],layer:"bridge"},{filter:["all",["==",["get","class"],"street_limited"],["==",["geometry-type"],"LineString"]],layer:"bridge"},{filter:["==",["get","class"],"motorway_link"],layer:"bridge"},{filter:["match",["get","class"],["service","driveway"],!0,!1],layer:"bridge"},{filter:["all",["==",["get","class"],"street_limited"],["!=",["get","type"],"construction"],["==",["geometry-type"],"LineString"]],layer:"bridge"},{filter:["==",["get","class"],"street"],layer:"bridge"},{filter:["all",["==",["get","oneway"],1],["match",["get","class"],["main","street","street_limited"],!0,!1],["!=",["get","type"],"trunk"]],layer:"bridge"},{filter:["any",["==",["get","class"],"motorway"],["==",["get","type"],"trunk"]],layer:"bridge"},{filter:["match",["get","class"],["service","driveway"],!0,!1],layer:"bridge"},{filter:["all",["==",["get","class"],"street_limited"],["==",["get","type"],"construction"],["==",["geometry-type"],"LineString"]],layer:"bridge"},{filter:["all",["==",["get","class"],"street_limited"],["!=",["get","type"],"construction"],["==",["geometry-type"],"LineString"]],layer:"bridge"},{filter:["==",["get","class"],"street"],layer:"bridge"},{filter:["all",["==",["get","class"],"main"],["!=",["get","type"],"trunk"]],layer:"bridge"},{filter:["all",["==",["get","class"],"main"],["==",["get","type"],"trunk"]],layer:"bridge"},{filter:["all",["==",["get","oneway"],1],["==",["get","type"],"trunk"]],layer:"bridge"},{filter:["==",["get","class"],"motorway"],layer:"bridge"},{filter:["match",["get","class"],["major_rail","minor_rail"],!0,!1],layer:"bridge"},{filter:["==",["get","class"],"aerialway"],layer:"bridge"},{filter:["all",["==",["get","oneway"],1],["match",["get","class"],["motorway","motorway_link"],!0,!1]],layer:"bridge"},{filter:["==",["get","class"],"hedge"],layer:"barrier_line"},{filter:["==",["get","class"],"fence"],layer:"barrier_line"},{filter:["==",["get","class"],"gate"],layer:"barrier_line"},{filter:["all",[">=",["get","admin_level"],3],["==",["get","maritime"],0]],layer:"admin"},{filter:["all",[">=",["get","admin_level"],3],["==",["get","maritime"],0]],layer:"admin"},{filter:["!=",["get","index"],5],layer:"contour"},{filter:["==",["get","index"],5],layer:"contour"},{filter:["==",["get","class"],"river"],layer:"waterway_label"},{filter:["all",["match",["get","maki"],["rail-light","rail-metro","rail","airport","airfield","heliport","rocket","park","golf","cemetery","zoo","campsite","swimming","dog-park"],!1,!0],["==",["get","scalerank"],4],[">=",["get","localrank"],15]],layer:"poi_label"},{filter:["all",["match",["get","maki"],["rail-light","rail-metro","rail","airport","airfield","heliport","rocket","park","golf","cemetery","zoo","campsite","swimming","dog-park"],!1,!0],["==",["get","scalerank"],4],["<=",["get","localrank"],14]],layer:"poi_label"},{filter:["all",["match",["get","maki"],["park","cemetery","golf","zoo","playground"],!0,!1],["==",["get","scalerank"],4]],layer:"poi_label"},{filter:["all",["match",["get","maki"],["rail-light","rail-metro","rail","airport","airfield","heliport","rocket","park","golf","cemetery","zoo","campsite","swimming","dog-park"],!1,!0],["==",["get","scalerank"],3]],layer:"poi_label"},{filter:["all",["match",["get","maki"],["park","cemetery","golf","zoo"],!0,!1],["==",["get","scalerank"],3]],layer:"poi_label"},{filter:["all",["match",["get","class"],["motorway","main","street_limited","street"],!1,!0],["==",["geometry-type"],"LineString"]],layer:"road_label"},{filter:["all",["match",["get","class"],["street","street_limited"],!1,!0],["==",["geometry-type"],"LineString"]],layer:"road_label"},{filter:["match",["get","class"],["main","motorway"],!0,!1],layer:"road_label"},{filter:["all",["match",["get","shield"],["us-interstate","us-interstate-business","us-interstate-duplex"],!1,!0],["<=",["get","reflen"],6]],layer:"road_label"},{filter:["all",["match",["get","shield"],["us-interstate","us-interstate-business","us-interstate-duplex"],!0,!1],["<=",["get","reflen"],6]],layer:"road_label"},{filter:["all",["match",["get","maki"],["rail-light","rail-metro","rail","airport","airfield","heliport","rocket","park","golf","cemetery","zoo","campsite","swimming","dog-park"],!1,!0],["==",["get","scalerank"],2]],layer:"poi_label"},{filter:["all",["match",["get","maki"],["park","golf","cemetery","zoo","campsite","swimming","dog-park"],!0,!1],["==",["get","scalerank"],2]],layer:"poi_label"},{filter:["==",["get","type"],"Rail Station"],layer:"poi_label"},{filter:["<=",["get","area"],1e4],layer:"water_label"},{filter:["all",["match",["get","maki"],["park","golf","cemetery","zoo","campsite","swimming","dog-park"],!0,!1],["<=",["get","scalerank"],1]],layer:"poi_label"},{filter:["all",["match",["get","maki"],["rail-light","rail-metro","rail","airport","airfield","heliport","rocket","park","golf","cemetery","zoo","campsite","swimming","dog-park"],!1,!0],["<=",["get","scalerank"],1],["!=",["get","type"],"Island"]],layer:"poi_label"},{filter:["==",["get","type"],"Islet"],layer:"poi_label"},{filter:["==",["get","type"],"Island"],layer:"poi_label"},{filter:["all",["match",["get","scalerank"],[0,1,2,3,4,5],!1,!0],["==",["get","type"],"city"]],layer:"place_label"},{filter:["all",["match",["get","scalerank"],[3,4,5],!0,!1],["==",["get","type"],"city"],["match",["get","ldir"],["S","SE","SW","E"],!0,!1]],layer:"place_label"},{filter:["all",["match",["get","scalerank"],[3,4,5],!0,!1],["==",["get","type"],"city"],["match",["get","ldir"],["N","NE","NW","W"],!0,!1]],layer:"place_label"}];class rs{constructor(){this.id="tent-3d";}onAdd(e,t){const i=t.createShader(t.VERTEX_SHADER);t.shaderSource(i,"#version 300 es\n\n in vec3 aPos;\n uniform mat4 uMatrix;\n\n void main() {\n gl_Position = uMatrix * vec4(aPos, 1.0);\n }\n "),t.compileShader(i);const r=t.createShader(t.FRAGMENT_SHADER);t.shaderSource(r,"#version 300 es\n\n out highp vec4 fragColor;\n void main() {\n fragColor = vec4(1.0, 0.0, 0.0, 1.0);\n }"),t.compileShader(r),this.program=t.createProgram(),t.attachShader(this.program,i),t.attachShader(this.program,r),t.linkProgram(this.program),t.validateProgram(this.program),this.program.aPos=t.getAttribLocation(this.program,"aPos"),this.program.uMatrix=t.getUniformLocation(this.program,"uMatrix");const o=.485,a=.01,s=new Float32Array([o,.49,0,o+a,.49,0,o,.5,.01,o+a,.5,.01,o,.51,0,o+a,.51,0]),n=new Uint16Array([0,1,2,1,2,3,2,3,4,3,4,5]);this.vertexBuffer=t.createBuffer(),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),t.bufferData(t.ARRAY_BUFFER,s,t.STATIC_DRAW),this.indexBuffer=t.createBuffer(),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,n,t.STATIC_DRAW);}render(e,t){e.useProgram(this.program),e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer),e.enableVertexAttribArray(this.program.a_pos),e.vertexAttribPointer(this.program.aPos,3,e.FLOAT,!1,0,0),e.uniformMatrix4fv(this.program.uMatrix,!1,t),e.drawElements(e.TRIANGLES,12,e.UNSIGNED_SHORT,0);}}class os extends a{constructor(e){super(),this._useGlobeProjection=!1,this._useGlobeProjection=e;}_createTransform(){if(this._useGlobeProjection){const e=new Jt;return {transform:new _i(e,!0),calculatePosMatrix:e=>{}}}{const e=new Ft(0,22,0,60,!0);return {transform:e,calculatePosMatrix:t=>e.calculatePosMatrix(t,!1)}}}setup(){return t.__awaiter(this,void 0,void 0,(function*(){const{transform:e,calculatePosMatrix:i}=this._createTransform();this._transform=e,e.resize(1024,1024);const r=new t.OverscaledTileID(0,0,0,0,0),o=r.toUnwrapped(),a=(s=3735928559,function(){let e=(s=2654435769+(s|=0)|0)^s>>>16;return e=Math.imul(e,569420461),e^=e>>>15,e=Math.imul(e,1935289751),((e^=e>>>15)>>>0)/4294967296});var s;const n=(e,t)=>a()*(t-e)+e;this._symbols=[];for(let e=0;e<2e4;e++)this._symbols.push({collisionBox:{anchorPointX:n(4,t.EXTENT-4),anchorPointY:n(4,t.EXTENT-4),x1:n(-20,-2),y1:n(-20,-2),x2:n(2,20),y2:n(2,20)},overlapMode:"never",textPixelRatio:1,tileID:r,unwrappedTileID:o,pitchWithMap:a()>.5,rotateWithMap:a()>.5,translation:[n(-20,20),n(-20,20)],shift:a()>.5?new t.Point(n(-20,20),n(-20,20)):void 0,simpleProjectionMatrix:i(o)});}))}bench(){return t.__awaiter(this,void 0,void 0,(function*(){const e=new Xe(this._transform);e.grid.hitTest=(e,t,i,r,o,a)=>!0;for(const t of this._symbols)e.placeCollisionBox(t.collisionBox,t.overlapMode,t.textPixelRatio,t.tileID,t.unwrappedTileID,t.pitchWithMap,t.rotateWithMap,t.translation,null,null,t.shift,t.simpleProjectionMatrix);}))}}function as(e,i,r,o){const a=[];for(let s=0;s{e.touchstart=e.dragStart,e.touchmoveWindow=e.dragMove,e.touchend=e.dragEnd;},ns={showCompass:!0,showZoom:!0,visualizePitch:!1,visualizeRoll:!0};class ls{constructor(e,i,r=!1){this.mousedown=e=>{this.startMouse(t.extend({},e,{ctrlKey:!0,preventDefault:()=>e.preventDefault()}),wi.mousePos(this.element,e)),wi.addEventListener(window,"mousemove",this.mousemove),wi.addEventListener(window,"mouseup",this.mouseup);},this.mousemove=e=>{this.moveMouse(e,wi.mousePos(this.element,e));},this.mouseup=e=>{this.mouseRotate.dragEnd(e),this.mousePitch&&this.mousePitch.dragEnd(e),this.offTemp();},this.touchstart=e=>{1!==e.targetTouches.length?this.reset():(this._startPos=this._lastPos=wi.touchPos(this.element,e.targetTouches)[0],this.startTouch(e,this._startPos),wi.addEventListener(window,"touchmove",this.touchmove,{passive:!1}),wi.addEventListener(window,"touchend",this.touchend));},this.touchmove=e=>{1!==e.targetTouches.length?this.reset():(this._lastPos=wi.touchPos(this.element,e.targetTouches)[0],this.moveTouch(e,this._lastPos));},this.touchend=e=>{0===e.targetTouches.length&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos){this.mouseRotate.reset(),this.mousePitch&&this.mousePitch.reset(),this.touchRotate.reset(),this.touchPitch&&this.touchPitch.reset(),delete this._startPos,delete this._lastPos,this.offTemp();},this._clickTolerance=10;const o=e.dragRotate._mouseRotate.getClickTolerance(),a=e.dragRotate._mousePitch.getClickTolerance();this.element=i,this.mouseRotate=Qo({clickTolerance:o,enable:!0,aroundCenter:!1}),this.touchRotate=function({enable:e,clickTolerance:i,aroundCenter:r=!0}){const o=new Yo;return new $o({clickTolerance:i,move:(e,i,o)=>r?{bearingDelta:t.getAngleDelta(new t.Point(e.x,i.y),i,o)}:{bearingDelta:.8*(i.x-e.x)},moveStateManager:o,enable:e,assignEvents:ss})}({clickTolerance:o,enable:!0}),this.map=e,r&&(this.mousePitch=ea({clickTolerance:a,enable:!0}),this.touchPitch=function({enable:e,clickTolerance:t,pitchDegreesPerPixelMoved:i=-.5}){const r=new Yo;return new $o({clickTolerance:t,move:(e,t)=>({pitchDelta:(t.y-e.y)*i}),moveStateManager:r,enable:e,assignEvents:ss})}({clickTolerance:a,enable:!0})),wi.addEventListener(i,"mousedown",this.mousedown),wi.addEventListener(i,"touchstart",this.touchstart,{passive:!1}),wi.addEventListener(i,"touchcancel",this.reset);}startMouse(e,t){this.mouseRotate.dragStart(e,t),this.mousePitch&&this.mousePitch.dragStart(e,t),wi.disableDrag();}startTouch(e,t){this.touchRotate.dragStart(e,t),this.touchPitch&&this.touchPitch.dragStart(e,t),wi.disableDrag();}moveMouse(e,t){const i=this.map,{bearingDelta:r}=this.mouseRotate.dragMove(e,t)||{};if(r&&i.setBearing(i.getBearing()+r),this.mousePitch){const{pitchDelta:r}=this.mousePitch.dragMove(e,t)||{};r&&i.setPitch(i.getPitch()+r);}}moveTouch(e,t){const i=this.map,{bearingDelta:r}=this.touchRotate.dragMove(e,t)||{};if(r&&i.setBearing(i.getBearing()+r),this.touchPitch){const{pitchDelta:r}=this.touchPitch.dragMove(e,t)||{};r&&i.setPitch(i.getPitch()+r);}}off(){const e=this.element;wi.removeEventListener(e,"mousedown",this.mousedown),wi.removeEventListener(e,"touchstart",this.touchstart,{passive:!1}),wi.removeEventListener(window,"touchmove",this.touchmove,{passive:!1}),wi.removeEventListener(window,"touchend",this.touchend),wi.removeEventListener(e,"touchcancel",this.reset),this.offTemp();}offTemp(){wi.enableDrag(),wi.removeEventListener(window,"mousemove",this.mousemove),wi.removeEventListener(window,"mouseup",this.mouseup),wi.removeEventListener(window,"touchmove",this.touchmove,{passive:!1}),wi.removeEventListener(window,"touchend",this.touchend);}}let cs;function hs(e,i,r){const o=new t.LngLat(e.lng,e.lat);if(e=new t.LngLat(e.lng,e.lat),i){const o=new t.LngLat(e.lng-360,e.lat),a=new t.LngLat(e.lng+360,e.lat),s=r.locationToScreenPoint(e).distSqr(i);r.locationToScreenPoint(o).distSqr(i)180;){const t=r.locationToScreenPoint(e);if(t.x>=0&&t.y>=0&&t.x<=r.width&&t.y<=r.height)break;e.lng>r.center.lng?e.lng-=360:e.lng+=360;}return e.lng!==o.lng&&r.isPointOnMapSurface(r.locationToScreenPoint(e))?e:o}const us={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 ds(e,t,i){const r=e.classList;for(const e in us)r.remove(`maplibregl-${i}-anchor-${e}`);r.add(`maplibregl-${i}-anchor-${t}`);}class _s extends t.Evented{constructor(e){if(super(),this._onKeyPress=e=>{const t=e.code,i=e.charCode||e.keyCode;"Space"!==t&&"Enter"!==t&&32!==i&&13!==i||this.togglePopup();},this._onMapClick=e=>{const t=e.originalEvent.target,i=this._element;this._popup&&(t===i||i.contains(t))&&this.togglePopup();},this._update=e=>{var t;if(!this._map)return;const i=this._map.loaded()&&!this._map.isMoving();("terrain"===(null==e?void 0:e.type)||"render"===(null==e?void 0:e.type)&&!i)&&this._map.once("render",this._update),this._lngLat=this._map.transform.renderWorldCopies?hs(this._lngLat,this._flatPos,this._map.transform):null===(t=this._lngLat)||void 0===t?void 0:t.wrap(),this._flatPos=this._pos=this._map.project(this._lngLat)._add(this._offset),this._map.terrain&&(this._flatPos=this._map.transform.locationToScreenPoint(this._lngLat)._add(this._offset));let r="";"viewport"===this._rotationAlignment||"auto"===this._rotationAlignment?r=`rotateZ(${this._rotation}deg)`:"map"===this._rotationAlignment&&(r=`rotateZ(${this._rotation-this._map.getBearing()}deg)`);let o="";"viewport"===this._pitchAlignment||"auto"===this._pitchAlignment?o="rotateX(0deg)":"map"===this._pitchAlignment&&(o=`rotateX(${this._map.getPitch()}deg)`),this._subpixelPositioning||e&&"moveend"!==e.type||(this._pos=this._pos.round()),wi.setTransform(this._element,`${us[this._anchor]} translate(${this._pos.x}px, ${this._pos.y}px) ${o} ${r}`),f.frameAsync(new AbortController).then((()=>{this._updateOpacity(e&&"moveend"===e.type);})).catch((()=>{}));},this._onMove=e=>{if(!this._isDragging){const t=this._clickTolerance||this._map._clickTolerance;this._isDragging=e.point.dist(this._pointerdownPos)>=t;}this._isDragging&&(this._pos=e.point.sub(this._positionDelta),this._lngLat=this._map.unproject(this._pos),this.setLngLat(this._lngLat),this._element.style.pointerEvents="none","pending"===this._state&&(this._state="active",this.fire(new t.Event("dragstart"))),this.fire(new t.Event("drag")));},this._onUp=()=>{this._element.style.pointerEvents="auto",this._positionDelta=null,this._pointerdownPos=null,this._isDragging=!1,this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),"active"===this._state&&this.fire(new t.Event("dragend")),this._state="inactive";},this._addDragHandler=e=>{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=e&&e.anchor||"center",this._color=e&&e.color||"#3FB1CE",this._scale=e&&e.scale||1,this._draggable=e&&e.draggable||!1,this._clickTolerance=e&&e.clickTolerance||0,this._subpixelPositioning=e&&e.subpixelPositioning||!1,this._isDragging=!1,this._state="inactive",this._rotation=e&&e.rotation||0,this._rotationAlignment=e&&e.rotationAlignment||"auto",this._pitchAlignment=e&&e.pitchAlignment&&"auto"!==e.pitchAlignment?e.pitchAlignment:this._rotationAlignment,this.setOpacity(),this.setOpacity(null==e?void 0:e.opacity,null==e?void 0:e.opacityWhenCovered),e&&e.element)this._element=e.element,this._offset=t.Point.convert(e&&e.offset||[0,0]);else {this._defaultMarker=!0,this._element=wi.create("div");const i=wi.createNS("http://www.w3.org/2000/svg","svg"),r=41,o=27;i.setAttributeNS(null,"display","block"),i.setAttributeNS(null,"height",`${r}px`),i.setAttributeNS(null,"width",`${o}px`),i.setAttributeNS(null,"viewBox",`0 0 ${o} ${r}`);const a=wi.createNS("http://www.w3.org/2000/svg","g");a.setAttributeNS(null,"stroke","none"),a.setAttributeNS(null,"stroke-width","1"),a.setAttributeNS(null,"fill","none"),a.setAttributeNS(null,"fill-rule","evenodd");const s=wi.createNS("http://www.w3.org/2000/svg","g");s.setAttributeNS(null,"fill-rule","nonzero");const n=wi.createNS("http://www.w3.org/2000/svg","g");n.setAttributeNS(null,"transform","translate(3.0, 29.0)"),n.setAttributeNS(null,"fill","#000000");const l=[{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 e of l){const t=wi.createNS("http://www.w3.org/2000/svg","ellipse");t.setAttributeNS(null,"opacity","0.04"),t.setAttributeNS(null,"cx","10.5"),t.setAttributeNS(null,"cy","5.80029008"),t.setAttributeNS(null,"rx",e.rx),t.setAttributeNS(null,"ry",e.ry),n.appendChild(t);}const c=wi.createNS("http://www.w3.org/2000/svg","g");c.setAttributeNS(null,"fill",this._color);const h=wi.createNS("http://www.w3.org/2000/svg","path");h.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"),c.appendChild(h);const u=wi.createNS("http://www.w3.org/2000/svg","g");u.setAttributeNS(null,"opacity","0.25"),u.setAttributeNS(null,"fill","#000000");const d=wi.createNS("http://www.w3.org/2000/svg","path");d.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"),u.appendChild(d);const _=wi.createNS("http://www.w3.org/2000/svg","g");_.setAttributeNS(null,"transform","translate(6.0, 7.0)"),_.setAttributeNS(null,"fill","#FFFFFF");const p=wi.createNS("http://www.w3.org/2000/svg","g");p.setAttributeNS(null,"transform","translate(8.0, 8.0)");const m=wi.createNS("http://www.w3.org/2000/svg","circle");m.setAttributeNS(null,"fill","#000000"),m.setAttributeNS(null,"opacity","0.25"),m.setAttributeNS(null,"cx","5.5"),m.setAttributeNS(null,"cy","5.5"),m.setAttributeNS(null,"r","5.4999962");const f=wi.createNS("http://www.w3.org/2000/svg","circle");f.setAttributeNS(null,"fill","#FFFFFF"),f.setAttributeNS(null,"cx","5.5"),f.setAttributeNS(null,"cy","5.5"),f.setAttributeNS(null,"r","5.4999962"),p.appendChild(m),p.appendChild(f),s.appendChild(n),s.appendChild(c),s.appendChild(u),s.appendChild(_),s.appendChild(p),i.appendChild(s),i.setAttributeNS(null,"height",r*this._scale+"px"),i.setAttributeNS(null,"width",o*this._scale+"px"),this._element.appendChild(i),this._offset=t.Point.convert(e&&e.offset||[0,-14]);}if(this._element.classList.add("maplibregl-marker"),this._element.addEventListener("dragstart",(e=>{e.preventDefault();})),this._element.addEventListener("mousedown",(e=>{e.preventDefault();})),ds(this._element,this._anchor,"marker"),e&&e.className)for(const t of e.className.split(" "))this._element.classList.add(t);this._popup=null;}addTo(e){return this.remove(),this._map=e,this._element.setAttribute("aria-label",e._getUIString("Marker.Title")),e.getCanvasContainer().appendChild(this._element),e.on("move",this._update),e.on("moveend",this._update),e.on("terrain",this._update),e.on("projectiontransition",this._update),this.setDraggable(this._draggable),this._update(),this._map.on("click",this._onMapClick),this}remove(){return this._opacityTimeout&&(clearTimeout(this._opacityTimeout),delete this._opacityTimeout),this._map&&(this._map.off("click",this._onMapClick),this._map.off("move",this._update),this._map.off("moveend",this._update),this._map.off("terrain",this._update),this._map.off("projectiontransition",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),wi.remove(this._element),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(e){return this._lngLat=t.LngLat.convert(e),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(),this}getElement(){return this._element}setPopup(e){if(this._popup&&(this._popup.remove(),this._popup=null,this._element.removeEventListener("keypress",this._onKeyPress),this._originalTabIndex||this._element.removeAttribute("tabindex")),e){if(!("offset"in e.options)){const t=38.1,i=13.5,r=Math.abs(i)/Math.SQRT2;e.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-t],"bottom-left":[r,-1*(t-i+r)],"bottom-right":[-r,-1*(t-i+r)],left:[i,-1*(t-i)],right:[-i,-1*(t-i)]}:this._offset;}this._popup=e,this._originalTabIndex=this._element.getAttribute("tabindex"),this._originalTabIndex||this._element.setAttribute("tabindex","0"),this._element.addEventListener("keypress",this._onKeyPress);}return this}setSubpixelPositioning(e){return this._subpixelPositioning=e,this}getPopup(){return this._popup}togglePopup(){const e=this._popup;return this._element.style.opacity===this._opacityWhenCovered?this:e?(e.isOpen()?e.remove():(e.setLngLat(this._lngLat),e.addTo(this._map)),this):this}_updateOpacity(e=!1){var i,r;if(!(null===(i=this._map)||void 0===i?void 0:i.terrain)){const e=this._map.transform.isLocationOccluded(this._lngLat)?this._opacityWhenCovered:this._opacity;return void(this._element.style.opacity!==e&&(this._element.style.opacity=e))}if(e)this._opacityTimeout=null;else {if(this._opacityTimeout)return;this._opacityTimeout=setTimeout((()=>{this._opacityTimeout=null;}),100);}const o=this._map,a=o.terrain.depthAtPoint(this._pos),s=o.terrain.getElevationForLngLatZoom(this._lngLat,o.transform.tileZoom);if(o.transform.lngLatToCameraDepth(this._lngLat,s)-a<.006)return void(this._element.style.opacity=this._opacity);const n=-this._offset.y/o.transform.pixelsPerMeter,l=Math.sin(o.getPitch()*Math.PI/180)*n,c=o.terrain.depthAtPoint(new t.Point(this._pos.x,this._pos.y-this._offset.y)),h=o.transform.lngLatToCameraDepth(this._lngLat,s+l)-c>.006;(null===(r=this._popup)||void 0===r?void 0:r.isOpen())&&h&&this._popup.remove(),this._element.style.opacity=h?this._opacityWhenCovered:this._opacity;}getOffset(){return this._offset}setOffset(e){return this._offset=t.Point.convert(e),this._update(),this}addClassName(e){this._element.classList.add(e);}removeClassName(e){this._element.classList.remove(e);}toggleClassName(e){return this._element.classList.toggle(e)}setDraggable(e){return this._draggable=!!e,this._map&&(e?(this._map.on("mousedown",this._addDragHandler),this._map.on("touchstart",this._addDragHandler)):(this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler))),this}isDraggable(){return this._draggable}setRotation(e){return this._rotation=e||0,this._update(),this}getRotation(){return this._rotation}setRotationAlignment(e){return this._rotationAlignment=e||"auto",this._update(),this}getRotationAlignment(){return this._rotationAlignment}setPitchAlignment(e){return this._pitchAlignment=e&&"auto"!==e?e:this._rotationAlignment,this._update(),this}getPitchAlignment(){return this._pitchAlignment}setOpacity(e,t){return void 0===e&&void 0===t&&(this._opacity="1",this._opacityWhenCovered="0.2"),void 0!==e&&(this._opacity=e),void 0!==t&&(this._opacityWhenCovered=t),this._map&&this._updateOpacity(!0),this}}const ps={positionOptions:{enableHighAccuracy:!1,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showAccuracyCircle:!0,showUserLocation:!0};let ms=0,fs=!1;const gs={maxWidth:100,unit:"metric"};function vs(e,t,i){const r=i&&i.maxWidth||100,o=e._container.clientHeight/2,a=e._container.clientWidth/2,s=e.unproject([a-r/2,o]),n=e.unproject([a+r/2,o]),l=Math.round(e.project(n).x-e.project(s).x),c=Math.min(r,l,e._container.clientWidth),h=s.distanceTo(n);if(i&&"imperial"===i.unit){const i=3.2808*h;i>5280?ys(t,c,i/5280,e._getUIString("ScaleControl.Miles")):ys(t,c,i,e._getUIString("ScaleControl.Feet"));}else i&&"nautical"===i.unit?ys(t,c,h/1852,e._getUIString("ScaleControl.NauticalMiles")):h>=1e3?ys(t,c,h/1e3,e._getUIString("ScaleControl.Kilometers")):ys(t,c,h,e._getUIString("ScaleControl.Meters"));}function ys(e,t,i,r){const o=function(e){const t=Math.pow(10,`${Math.floor(e)}`.length-1);let i=e/t;return i=i>=10?10:i>=5?5:i>=3?3:i>=2?2:i>=1?1:function(e){const t=Math.pow(10,Math.ceil(-Math.log(e)/Math.LN10));return Math.round(e*t)/t}(i),t*i}(i);e.style.width=t*(o/i)+"px",e.innerHTML=`${o} ${r}`;}const xs={closeButton:!0,closeOnClick:!0,focusAfterOpen:!0,className:"",maxWidth:"240px",subpixelPositioning:!1},bs=["a[href]","[tabindex]:not([tabindex='-1'])","[contenteditable]:not([contenteditable='false'])","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])"].join(", ");function ws(e){if(e){if("number"==typeof e){const i=Math.round(Math.abs(e)/Math.SQRT2);return {center:new t.Point(0,0),top:new t.Point(0,e),"top-left":new t.Point(i,i),"top-right":new t.Point(-i,i),bottom:new t.Point(0,-e),"bottom-left":new t.Point(i,-i),"bottom-right":new t.Point(-i,-i),left:new t.Point(e,0),right:new t.Point(-e,0)}}if(e instanceof t.Point||Array.isArray(e)){const i=t.Point.convert(e);return {center:i,top:i,"top-left":i,"top-right":i,bottom:i,"bottom-left":i,"bottom-right":i,left:i,right:i}}return {center:t.Point.convert(e.center||[0,0]),top:t.Point.convert(e.top||[0,0]),"top-left":t.Point.convert(e["top-left"]||[0,0]),"top-right":t.Point.convert(e["top-right"]||[0,0]),bottom:t.Point.convert(e.bottom||[0,0]),"bottom-left":t.Point.convert(e["bottom-left"]||[0,0]),"bottom-right":t.Point.convert(e["bottom-right"]||[0,0]),left:t.Point.convert(e.left||[0,0]),right:t.Point.convert(e.right||[0,0])}}return ws(new t.Point(0,0))}const Ts=Ti,Es=r(o),Ps=window.benchmarks=[];function Is(e,t,i,r){const o=[];for(const e of ["https://api.maptiler.com/maps/streets/style.json?key=get_your_own_OpIi9ZULNHzrESv6T2vL"])o.push({name:"string"==typeof e?e:e.name,bench:new t(e,i)});Ps.push({name:e,versions:o,location:r});}Is("StyleLayerCreate",Ya),Is("Validate",Ka),Es.forEach((e=>Is("Layout",bi,e.tileID,e))),Es.forEach((e=>Is("Paint",Za,[e],e))),Is("QueryPoint",Qa,Es),Is("QueryBox",es,Es),Promise.resolve().then((()=>{B().acquire(-1);}));class Cs extends a{constructor(e){super(),this._pitch=e;}bench(){const e=new Jt,i=new _i(e,!0);i.setCenter(new t.LngLat(0,0)),i.setZoom(4),i.resize(4096,4096),i.setMaxPitch(this._pitch),i.setPitch(this._pitch);for(let e=0;e<40;e++)i.setCenter(new t.LngLat(.2*e,0)),ve(i,{tileSize:256});}}const Ms=r(o).filter((e=>e.zoom<15));function Ss(e,t){window.maplibreglBenchmarks[e]=window.maplibreglBenchmarks[e]||{},window.maplibreglBenchmarks[e]["main 1ac0a1b"]=t;}window.maplibreglBenchmarks=window.maplibreglBenchmarks||{};const Rs="https://api.maptiler.com/maps/streets/style.json?key=get_your_own_OpIi9ZULNHzrESv6T2vL",Ds=[-77.032194,38.912753],zs=[4,8,11,13,15,17].map((e=>({center:Ds,zoom:e})));Ss("Paint",new Za(Rs,zs)),Ss("QueryPoint",new Qa(Rs,zs)),Ss("QueryBox",new es(Rs,zs)),Ss("Layout",new bi(Rs)),Ss("Placement",new class extends a{constructor(e,t){super(),this.style=e,this.locations=t;}setup(){return t.__awaiter(this,void 0,void 0,(function*(){try{this.maps=yield Promise.all(this.locations.map((e=>Na({zoom:e.zoom,width:1024,height:768,center:e.center,style:this.style,idle:!0}))));}catch(e){console.error(e);}}))}bench(){for(const e of this.maps)e.style._updatePlacement(e.transform,!1,300,!0,!0);}teardown(){for(const e of this.maps)e.remove();}}(Rs,zs)),Ss("Validate",new Ka(Rs)),Ss("StyleLayerCreate",new Ya(Rs)),Ss("FunctionCreate",new class extends ts{bench(){for(const{rawValue:e,propertySpec:i}of this.data)t.createFunction(e,i);}}(Rs)),Ss("FunctionEvaluate",new class extends ts{bench(){for(const{compiledFunction:e}of this.data)e.evaluate({zoom:0});}}(Rs)),Ss("ExpressionCreate",new class extends ts{bench(){for(const{rawExpression:e,propertySpec:i}of this.data)t.createPropertyExpression(e,i);}}(Rs)),Ss("ExpressionEvaluate",new class extends ts{bench(){for(const{compiledExpression:e}of this.data)e.evaluate({zoom:0});}}(Rs)),Ss("WorkerTransfer",new class extends a{constructor(e){super(),this.style=e;}setup(){return t.__awaiter(this,void 0,void 0,(function*(){const e=window.URL.createObjectURL(new Blob(["\n onmessage = (e) => {\n postMessage(e.data);\n };\n "],{type:"text/javascript"}));this.worker=new Worker(e);const i=[new t.OverscaledTileID(8,0,8,73,97),new t.OverscaledTileID(11,0,11,585,783),new t.OverscaledTileID(11,0,11,596,775),new t.OverscaledTileID(13,0,13,2412,3079)],r=yield s(this.style);this.parser=new xi(r,"openmaptiles"),yield this.parser.setup();const o=yield Promise.all(i.map((e=>this.parser.fetchTile(e)))),a=yield Promise.all(o.map((e=>this.parser.parseTile(e)))),n=a.concat(Object.values(this.parser.icons)).concat(Object.values(this.parser.glyphs)).map((e=>t.serialize(e,[])));this.payloadJSON=n.map(Ga),this.payloadTiles=n.slice(0,a.length);}))}sendPayload(e){return new Promise((t=>{this.worker.onmessage=()=>t(),this.worker.postMessage(e);}))}bench(){return t.__awaiter(this,void 0,void 0,(function*(){for(const e of this.payloadJSON)yield this.sendPayload(e);for(const e of this.payloadTiles)t.deserialize(e);}))}teardown(){this.worker.terminate();}}(Rs)),Ss("PaintStates",new class extends a{constructor(e){super(),this.center=e;}setup(){return t.__awaiter(this,void 0,void 0,(function*(){const e=yield fetch("/test/bench/data/naturalearth-land.json"),t=yield e.json();this.numFeatures=t.features.length;const i=Object.assign({},Va,{sources:{land:{type:"geojson",data:t,maxzoom:23}},layers:qa({id:"layer",type:"fill",source:"land",paint:{"fill-color":["case",["boolean",["feature-state","bench"],!1],["rgb",21,210,210],["rgb",233,233,233]]}})});try{this.map=yield Na({zoom:4,width:1024,height:768,center:this.center,style:i});}catch(e){console.error(e);}}))}bench(){this.map._styleDirty=!0,this.map._sourcesDirty=!0,this.map._render();for(let e=0;esuper.setup}});return t.__awaiter(this,void 0,void 0,(function*(){const t=yield fetch("/test/bench/data/naturalearth-land.json"),i=yield t.json();this.layerStyle=Object.assign({},Va,{sources:{heatmap:{type:"geojson",data:i,maxzoom:23}},layers:$a({id:"layer",type:"heatmap",source:"heatmap",paint:{"heatmap-radius":50,"heatmap-weight":{stops:[[0,.5],[4,2]]},"heatmap-intensity":.9,"heatmap-color":["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"]}})}),yield e.setup.call(this);}))}}),Ss("LayerHillshade",new class extends Ha{constructor(){super(),this.layerStyle=Object.assign({},Va,{sources:{"terrain-rgb":{type:"raster-dem",url:"https://api.maptiler.com/tiles/terrain-rgb/tiles.json?key=get_your_own_OpIi9ZULNHzrESv6T2vL"}},layers:$a({id:"layer",type:"hillshade",source:"terrain-rgb"})});}}),Ss("LayerLine",new class extends Ha{constructor(){super(),this.layerStyle=Object.assign({},Va,{layers:$a({id:"linelayer",type:"line",source:"openmaptiles","source-layer":"transportation"})});}}),Ss("LayerRaster",new class extends Ha{constructor(){super(),this.layerStyle=Object.assign({},Va,{sources:{satellite:{url:"https://api.maptiler.com/tiles/satellite/tiles.json?key=get_your_own_OpIi9ZULNHzrESv6T2vL",type:"raster",tileSize:256}},layers:$a({id:"rasterlayer",type:"raster",source:"satellite"})});}}),Ss("LayerSymbol",new class extends Ha{constructor(){super(),this.layerStyle=Object.assign({},Va,{layers:$a({id:"symbollayer",type:"symbol",source:"openmaptiles","source-layer":"poi",layout:{"icon-image":"dot_11","text-field":"{name_en}"}})});}}),Ss("LayerSymbolWithIcons",new class extends Ha{constructor(){super(),this.layerStyle=Object.assign({},Va,{layers:$a({id:"symbollayer",type:"symbol",source:"openmaptiles","source-layer":"poi",layout:{"icon-image":"dot_11","text-field":["format",["get","name_en"],["image","dot_11"]]}})});}}),Ss("LayerTextWithVariableAnchor",new class extends Ha{constructor(){super(),this.layerStyle=Object.assign({},Va,{layers:$a({id:"symbollayer",type:"symbol",source:"openmaptiles","source-layer":"poi",layout:{"text-field":"Test Test Test","text-justify":"auto","text-variable-anchor":["center","top","bottom","left","right","top-left","top-right","bottom-left","bottom-right"]}})});}}),Ss("LayerSymbolWithSortKey",new class extends Ha{constructor(){super(),this.layerStyle=Object.assign({},Va,{layers:this.generateSortKeyLayers()});}generateSortKeyLayers(){const e=[];for(let t=0;t<50;t++)e.push({id:`symbollayer${t}`,type:"symbol",source:"openmaptiles","source-layer":"poi",layout:{"symbol-sort-key":t,"text-field":"{name_en}"}});return e}}),Ss("Load",new class extends a{bench(){return t.__awaiter(this,void 0,void 0,(function*(){try{(yield Na({style:{version:8,sources:{},layers:[]}})).remove();}catch(e){console.error(e);}}))}}),Ss("LoadMatchingFeature",new class extends a{setup(){const e=Object.create(null,{setup:{get:()=>super.setup}});return t.__awaiter(this,void 0,void 0,(function*(){yield e.setup.call(this);const i=new t.OverscaledTileID(0,0,0,0,0);this.featureIndex=new t.FeatureIndex(i);const r=Array.from({length:100},((e,t)=>`layer-${t}`));this.layerIdsToTest=new Set(Array.from({length:100},((e,t)=>`non-existing-layer-${t}`))),this.featureIndex.bucketLayerIDs=[r],this.featureIndex.vtLayers={},this.featureIndex.vtLayers[0]={feature:()=>({})};}))}bench(){this.featureIndex.loadMatchingFeature({},0,0,0,{needGeometry:!1},this.layerIdsToTest,[],{},{});}}),Ss("SymbolLayout",new class extends bi{constructor(e,t){super(e,t),this.parsedTiles=[];}setup(){const e=Object.create(null,{setup:{get:()=>super.setup}});return t.__awaiter(this,void 0,void 0,(function*(){yield e.setup.call(this);for(const e of this.tiles)this.parsedTiles.push(yield this.parser.parseTile(e,!0));}))}bench(){return t.__awaiter(this,void 0,void 0,(function*(){for(const e of this.parsedTiles)for(const i of e.buckets)i instanceof t.SymbolBucket&&(yield t.performSymbolLayout({bucket:i,glyphMap:e.glyphMap,glyphPositions:e.glyphPositions,imageMap:e.iconMap,imagePositions:e.imageAtlas.iconPositions,showCollisionBoxes:!1,canonical:e.featureIndex.tileID.canonical,subdivisionGranularity:t.SubdivisionGranularitySetting.noSubdivision}));}))}}(Rs,Ms.map((e=>e.tileID[0])))),Ss("FilterCreate",new class extends a{bench(){for(const e of is)t.featureFilter(e.filter);}}),Ss("FilterEvaluate",new class extends a{setup(){return t.__awaiter(this,void 0,void 0,(function*(){const e=yield fetch("/test/bench/data/785.vector.pbf"),i=yield e.arrayBuffer(),r=new t.vectorTileExports.VectorTile(new t.Protobuf(i));this.layers=[];for(const e in r.layers){const i=r.layers[e];if(!i.length)continue;const o=[];for(let e=0;e{Na({width:1024,height:1024,style:{version:8,sources:{},layers:[]},center:[-9.4,-26.8],pitch:60,bearing:131,zoom:1.69}).then((t=>{this.map=t,e();})).catch((e=>{console.error(e),t(e);}));}))}bench(){const e=new rs;this.map.addLayer(e),this.map._styleDirty=!0,this.map._sourcesDirty=!0,this.map._render(Date.now());}teardown(){this.map.remove();}}),Ss("MapIdle",new class extends a{constructor(){super(),this.minimumMeasurements=55;}createMap(){return t.__awaiter(this,void 0,void 0,(function*(){try{(yield Na({idle:!0,center:[-77.032194,38.912753],zoom:15})).remove();}catch(e){console.error(e);}}))}setup(){return this.createMap()}bench(){return this.createMap()}}),Ss("SymbolCollisionBox",new os(!1)),Ss("SymbolCollisionBoxGlobe",new os(!0)),Ss("Subdivide",new class extends a{setup(){const e=Object.create(null,{setup:{get:()=>super.setup}});return t.__awaiter(this,void 0,void 0,(function*(){yield e.setup.call(this),this.granularity=64,this.tileID=new t.CanonicalTileID(2,1,1);const i=[];function r(e,r,o,a){i.push(as(e*t.EXTENT,r*t.EXTENT,o*t.EXTENT,a));}i.push(as(t.EXTENT/2,t.EXTENT/2,1.1*t.EXTENT/2,891)),r(.25,.5,.15,176),r(.75,.5,.15,22),r(.5,.1,.05,44),this.polygon=i;}))}bench(){for(let e=0;e<10;e++)t.subdividePolygon(this.polygon,this.tileID,this.granularity,!0);}}),Ss("CoveringTilesGlobe",new Cs(0)),Ss("CoveringTilesGlobePitched",new Cs(60)),Promise.resolve().then((()=>{B().acquire(-1);})),e.AJAXError=t.AJAXError,e.Event=t.Event,e.Evented=t.Evented,e.LngLat=t.LngLat,e.MercatorCoordinate=t.MercatorCoordinate,e.Point=t.Point,e.addProtocol=t.addProtocol,e.config=t.config,e.removeProtocol=t.removeProtocol,e.AttributionControl=Ma,e.BoxZoomHandler=Zo,e.CanvasSource=J,e.CooperativeGesturesHandler=ba,e.DoubleClickZoomHandler=ma,e.DragPanHandler=va,e.DragRotateHandler=ya,e.EdgeInsets=le,e.FullscreenControl=class extends t.Evented{constructor(e={}){super(),this._onFullscreenChange=()=>{var e;let t=window.document.fullscreenElement||window.document.mozFullScreenElement||window.document.webkitFullscreenElement||window.document.msFullscreenElement;for(;null===(e=null==t?void 0:t.shadowRoot)||void 0===e?void 0:e.fullscreenElement;)t=t.shadowRoot.fullscreenElement;t===this._container!==this._fullscreen&&this._handleFullscreenChange();},this._onClickFullscreen=()=>{this._isFullscreen()?this._exitFullscreen():this._requestFullscreen();},this._fullscreen=!1,e&&e.container&&(e.container instanceof HTMLElement?this._container=e.container:t.warnOnce("Full screen control 'container' must be a DOM element.")),"onfullscreenchange"in document?this._fullscreenchange="fullscreenchange":"onmozfullscreenchange"in document?this._fullscreenchange="mozfullscreenchange":"onwebkitfullscreenchange"in document?this._fullscreenchange="webkitfullscreenchange":"onmsfullscreenchange"in document&&(this._fullscreenchange="MSFullscreenChange");}onAdd(e){return this._map=e,this._container||(this._container=this._map.getContainer()),this._controlContainer=wi.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),this._controlContainer}onRemove(){wi.remove(this._controlContainer),this._map=null,window.document.removeEventListener(this._fullscreenchange,this._onFullscreenChange);}_setupUI(){const e=this._fullscreenButton=wi.create("button","maplibregl-ctrl-fullscreen",this._controlContainer);wi.create("span","maplibregl-ctrl-icon",e).setAttribute("aria-hidden","true"),e.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),window.document.addEventListener(this._fullscreenchange,this._onFullscreenChange);}_updateTitle(){const e=this._getTitle();this._fullscreenButton.setAttribute("aria-label",e),this._fullscreenButton.title=e;}_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(),this._fullscreen?(this.fire(new t.Event("fullscreenstart")),this._prevCooperativeGesturesEnabled=this._map.cooperativeGestures.isEnabled(),this._map.cooperativeGestures.disable()):(this.fire(new t.Event("fullscreenend")),this._prevCooperativeGesturesEnabled&&this._map.cooperativeGestures.enable());}_exitFullscreen(){window.document.exitFullscreen?window.document.exitFullscreen():window.document.mozCancelFullScreen?window.document.mozCancelFullScreen():window.document.msExitFullscreen?window.document.msExitFullscreen():window.document.webkitCancelFullScreen?window.document.webkitCancelFullScreen():this._togglePseudoFullScreen();}_requestFullscreen(){this._container.requestFullscreen?this._container.requestFullscreen():this._container.mozRequestFullScreen?this._container.mozRequestFullScreen():this._container.msRequestFullscreen?this._container.msRequestFullscreen():this._container.webkitRequestFullscreen?this._container.webkitRequestFullscreen():this._togglePseudoFullScreen();}_togglePseudoFullScreen(){this._container.classList.toggle("maplibregl-pseudo-fullscreen"),this._handleFullscreenChange(),this._map.resize();}},e.GeoJSONSource=H,e.GeolocateControl=class extends t.Evented{constructor(e){super(),this._onSuccess=e=>{if(this._map){if(this._isOutOfMapMaxBounds(e))return this._setErrorState(),this.fire(new t.Event("outofmaxbounds",e)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=e,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}`)}this.options.showUserLocation&&"OFF"!==this._watchState&&this._updateMarker(e),this.options.trackUserLocation&&"ACTIVE_LOCK"!==this._watchState||this._updateCamera(e),this.options.showUserLocation&&this._dotElement.classList.remove("maplibregl-user-location-dot-stale"),this.fire(new t.Event("geolocate",e)),this._finish();}},this._updateCamera=e=>{const i=new t.LngLat(e.coords.longitude,e.coords.latitude),r=e.coords.accuracy,o=this._map.getBearing(),a=t.extend({bearing:o},this.options.fitBoundsOptions),s=V.fromLngLat(i,r);this._map.fitBounds(s,a,{geolocateSource:!0});},this._updateMarker=e=>{if(e){const i=new t.LngLat(e.coords.longitude,e.coords.latitude);this._accuracyCircleMarker.setLngLat(i).addTo(this._map),this._userLocationDotMarker.setLngLat(i).addTo(this._map),this._accuracy=e.coords.accuracy,this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius();}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove();},this._onZoom=()=>{this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius();},this._onError=e=>{if(this._map){if(this.options.trackUserLocation)if(1===e.code){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=!0;const e=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e),void 0!==this._geolocationWatchID&&this._clearWatch();}else {if(3===e.code&&fs)return;this._setErrorState();}"OFF"!==this._watchState&&this.options.showUserLocation&&this._dotElement.classList.add("maplibregl-user-location-dot-stale"),this.fire(new t.Event("error",e)),this._finish();}},this._finish=()=>{this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0;},this._setupUI=()=>{this._map&&(this._container.addEventListener("contextmenu",(e=>e.preventDefault())),this._geolocateButton=wi.create("button","maplibregl-ctrl-geolocate",this._container),wi.create("span","maplibregl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",this._geolocateButton.disabled=!0);},this._finishSetupUI=e=>{if(this._map){if(!1===e){t.warnOnce("Geolocation support is not available so the GeolocateControl will be disabled.");const e=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=!0,this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e);}else {const e=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.disabled=!1,this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e);}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=wi.create("div","maplibregl-user-location-dot"),this._userLocationDotMarker=new _s({element:this._dotElement}),this._circleElement=wi.create("div","maplibregl-user-location-accuracy-circle"),this._accuracyCircleMarker=new _s({element:this._circleElement,pitchAlignment:"map"}),this.options.trackUserLocation&&(this._watchState="OFF"),this._map.on("zoom",this._onZoom)),this._geolocateButton.addEventListener("click",(()=>this.trigger())),this._setup=!0,this.options.trackUserLocation&&this._map.on("movestart",(e=>{e.geolocateSource||"ACTIVE_LOCK"!==this._watchState||e.originalEvent&&"resize"===e.originalEvent.type||(this._watchState="BACKGROUND",this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this.fire(new t.Event("trackuserlocationend")),this.fire(new t.Event("userlocationlostfocus")));}));}},this.options=t.extend({},ps,e);}onAdd(e){return this._map=e,this._container=wi.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),function(){return t.__awaiter(this,arguments,void 0,(function*(e=!1){if(void 0!==cs&&!e)return cs;if(void 0===window.navigator.permissions)return cs=!!window.navigator.geolocation,cs;try{const e=yield window.navigator.permissions.query({name:"geolocation"});cs="denied"!==e.state;}catch(e){cs=!!window.navigator.geolocation;}return cs}))}().then((e=>this._finishSetupUI(e))),this._container}onRemove(){void 0!==this._geolocationWatchID&&(window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),wi.remove(this._container),this._map.off("zoom",this._onZoom),this._map=void 0,ms=0,fs=!1;}_isOutOfMapMaxBounds(e){const t=this._map.getMaxBounds(),i=e.coords;return t&&(i.longitudet.getEast()||i.latitudet.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 e=this._map.getBounds(),t=e.getSouthEast(),i=e.getNorthEast(),r=t.distanceTo(i),o=Math.ceil(this._accuracy/(r/this._map._container.clientHeight)*2);this._circleElement.style.width=`${o}px`,this._circleElement.style.height=`${o}px`;}trigger(){if(!this._setup)return t.warnOnce("Geolocate control triggered before added to a map"),!1;if(this.options.trackUserLocation){switch(this._watchState){case"OFF":this._watchState="WAITING_ACTIVE",this.fire(new t.Event("trackuserlocationstart"));break;case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":case"BACKGROUND_ERROR":ms--,fs=!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.fire(new t.Event("trackuserlocationend"));break;case"BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new t.Event("trackuserlocationstart")),this.fire(new t.Event("userlocationfocus"));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("OFF"===this._watchState&&void 0!==this._geolocationWatchID)this._clearWatch();else if(void 0===this._geolocationWatchID){let e;this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),ms++,ms>1?(e={maximumAge:6e5,timeout:0},fs=!0):(e=this.options.positionOptions,fs=!1),this._geolocationWatchID=window.navigator.geolocation.watchPosition(this._onSuccess,this._onError,e);}}else window.navigator.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._timeoutId=setTimeout(this._finish,1e4);return !0}_clearWatch(){window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null);}},e.GlobeControl=class{constructor(){this._toggleProjection=()=>{var e;const t=null===(e=this._map.getProjection())||void 0===e?void 0:e.type;this._map.setProjection("mercator"!==t&&t?{type:"mercator"}:{type:"globe"}),this._updateGlobeIcon();},this._updateGlobeIcon=()=>{var e;this._globeButton.classList.remove("maplibregl-ctrl-globe"),this._globeButton.classList.remove("maplibregl-ctrl-globe-enabled"),"globe"===(null===(e=this._map.getProjection())||void 0===e?void 0:e.type)?(this._globeButton.classList.add("maplibregl-ctrl-globe-enabled"),this._globeButton.title=this._map._getUIString("GlobeControl.Disable")):(this._globeButton.classList.add("maplibregl-ctrl-globe"),this._globeButton.title=this._map._getUIString("GlobeControl.Enable"));};}onAdd(e){return this._map=e,this._container=wi.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._globeButton=wi.create("button","maplibregl-ctrl-globe",this._container),wi.create("span","maplibregl-ctrl-icon",this._globeButton).setAttribute("aria-hidden","true"),this._globeButton.type="button",this._globeButton.addEventListener("click",this._toggleProjection),this._updateGlobeIcon(),this._map.on("styledata",this._updateGlobeIcon),this._container}onRemove(){wi.remove(this._container),this._map.off("styledata",this._updateGlobeIcon),this._globeButton.removeEventListener("click",this._toggleProjection),this._map=void 0;}},e.Hash=Co,e.ImageSource=K,e.KeyboardHandler=ua,e.LngLatBounds=V,e.LogoControl=Sa,e.Map=ja,e.MapMouseEvent=Bo,e.MapTouchEvent=Oo,e.MapWheelEvent=Uo,e.Marker=_s,e.NavigationControl=class{constructor(e){this._updateZoomButtons=()=>{const e=this._map.getZoom(),t=e===this._map.getMaxZoom(),i=e===this._map.getMinZoom();this._zoomInButton.disabled=t,this._zoomOutButton.disabled=i,this._zoomInButton.setAttribute("aria-disabled",t.toString()),this._zoomOutButton.setAttribute("aria-disabled",i.toString());},this._rotateCompassArrow=()=>{this._compassIcon.style.transform=this.options.visualizePitch&&this.options.visualizeRoll?`scale(${1/Math.pow(Math.cos(this._map.transform.pitchInRadians),.5)}) rotateZ(${-this._map.transform.roll}deg) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(this._map.transform.pitchInRadians),.5)}) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizeRoll?`rotate(${-this._map.transform.bearing-this._map.transform.roll}deg)`:`rotate(${-this._map.transform.bearing}deg)`;},this._setButtonTitle=(e,t)=>{const i=this._map._getUIString(`NavigationControl.${t}`);e.title=i,e.setAttribute("aria-label",i);},this.options=t.extend({},ns,e),this._container=wi.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._container.addEventListener("contextmenu",(e=>e.preventDefault())),this.options.showZoom&&(this._zoomInButton=this._createButton("maplibregl-ctrl-zoom-in",(e=>this._map.zoomIn({},{originalEvent:e}))),wi.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}))),wi.create("span","maplibregl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(this._compass=this._createButton("maplibregl-ctrl-compass",(e=>{this.options.visualizePitch?this._map.resetNorthPitch({},{originalEvent:e}):this._map.resetNorth({},{originalEvent:e});})),this._compassIcon=wi.create("span","maplibregl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"));}onAdd(e){return this._map=e,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),this._map.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&this._map.on("pitch",this._rotateCompassArrow),this.options.visualizeRoll&&this._map.on("roll",this._rotateCompassArrow),this._map.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new ls(this._map,this._compass,this.options.visualizePitch)),this._container}onRemove(){wi.remove(this._container),this.options.showZoom&&this._map.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&this._map.off("pitch",this._rotateCompassArrow),this.options.visualizeRoll&&this._map.off("roll",this._rotateCompassArrow),this._map.off("rotate",this._rotateCompassArrow),this._handler.off(),delete this._handler),delete this._map;}_createButton(e,t){const i=wi.create("button",e,this._container);return i.type="button",i.addEventListener("click",t),i}},e.Popup=class extends t.Evented{constructor(e){super(),this.remove=()=>(this._content&&wi.remove(this._content),this._container&&(wi.remove(this._container),delete this._container),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 t.Event("close"))),this),this._onMouseUp=e=>{this._update(e.point);},this._onMouseMove=e=>{this._update(e.point);},this._onDrag=e=>{this._update(e.point);},this._update=e=>{var t;if(!this._map||!this._lngLat&&!this._trackPointer||!this._content)return;if(!this._container){if(this._container=wi.create("div","maplibregl-popup",this._map.getContainer()),this._tip=wi.create("div","maplibregl-popup-tip",this._container),this._container.appendChild(this._content),this.options.className)for(const e of this.options.className.split(" "))this._container.classList.add(e);this._closeButton&&this._closeButton.setAttribute("aria-label",this._map._getUIString("Popup.Close")),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),this._lngLat=this._map.transform.renderWorldCopies&&!this._trackPointer?hs(this._lngLat,this._flatPos,this._map.transform):null===(t=this._lngLat)||void 0===t?void 0:t.wrap(),this._trackPointer&&!e)return;const i=this._flatPos=this._pos=this._trackPointer&&e?e:this._map.project(this._lngLat);this._map.terrain&&(this._flatPos=this._trackPointer&&e?e:this._map.transform.locationToScreenPoint(this._lngLat));let r=this.options.anchor;const o=ws(this.options.offset);if(!r){const e=this._container.offsetWidth,t=this._container.offsetHeight;let a;a=i.y+o.bottom.ythis._map.transform.height-t?["bottom"]:[],i.xthis._map.transform.width-e/2&&a.push("right"),r=0===a.length?"bottom":a.join("-");}let a=i.add(o[r]);this.options.subpixelPositioning||(a=a.round()),wi.setTransform(this._container,`${us[r]} translate(${a.x}px,${a.y}px)`),ds(this._container,r,"popup");},this._onClose=()=>{this.remove();},this.options=t.extend(Object.create(xs),e);}addTo(e){return this._map&&this.remove(),this._map=e,this.options.closeOnClick&&this._map.on("click",this._onClose),this.options.closeOnMove&&this._map.on("move",this._onClose),this._map.on("remove",this.remove),this._update(),this._focusFirstElement(),this._trackPointer?(this._map.on("mousemove",this._onMouseMove),this._map.on("mouseup",this._onMouseUp),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")):this._map.on("move",this._update),this.fire(new t.Event("open")),this}isOpen(){return !!this._map}getLngLat(){return this._lngLat}setLngLat(e){return this._lngLat=t.LngLat.convert(e),this._pos=null,this._flatPos=null,this._trackPointer=!1,this._update(),this._map&&(this._map.on("move",this._update),this._map.off("mousemove",this._onMouseMove),this._container&&this._container.classList.remove("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.remove("maplibregl-track-pointer")),this}trackPointer(){return this._trackPointer=!0,this._pos=null,this._flatPos=null,this._update(),this._map&&(this._map.off("move",this._update),this._map.on("mousemove",this._onMouseMove),this._map.on("drag",this._onDrag),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")),this}getElement(){return this._container}setText(e){return this.setDOMContent(document.createTextNode(e))}setHTML(e){const t=document.createDocumentFragment(),i=document.createElement("body");let r;for(i.innerHTML=e;r=i.firstChild,r;)t.appendChild(r);return this.setDOMContent(t)}getMaxWidth(){var e;return null===(e=this._container)||void 0===e?void 0:e.style.maxWidth}setMaxWidth(e){return this.options.maxWidth=e,this._update(),this}setDOMContent(e){if(this._content)for(;this._content.hasChildNodes();)this._content.firstChild&&this._content.removeChild(this._content.firstChild);else this._content=wi.create("div","maplibregl-popup-content",this._container);return this._content.appendChild(e),this._createCloseButton(),this._update(),this._focusFirstElement(),this}addClassName(e){return this._container&&this._container.classList.add(e),this}removeClassName(e){return this._container&&this._container.classList.remove(e),this}setOffset(e){return this.options.offset=e,this._update(),this}toggleClassName(e){if(this._container)return this._container.classList.toggle(e)}setSubpixelPositioning(e){this.options.subpixelPositioning=e;}_createCloseButton(){this.options.closeButton&&(this._closeButton=wi.create("button","maplibregl-popup-close-button",this._content),this._closeButton.type="button",this._closeButton.innerHTML="×",this._closeButton.addEventListener("click",this._onClose));}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const e=this._container.querySelector(bs);e&&e.focus();}},e.RasterDEMTileSource=$,e.RasterTileSource=X,e.ScaleControl=class{constructor(e){this._onMove=()=>{vs(this._map,this._container,this.options);},this.setUnit=e=>{this.options.unit=e,vs(this._map,this._container,this.options);},this.options=Object.assign(Object.assign({},gs),e);}getDefaultPosition(){return "bottom-left"}onAdd(e){return this._map=e,this._container=wi.create("div","maplibregl-ctrl maplibregl-ctrl-scale",e.getContainer()),this._map.on("move",this._onMove),this._onMove(),this._container}onRemove(){wi.remove(this._container),this._map.off("move",this._onMove),this._map=void 0;}},e.ScrollZoomHandler=pa,e.Style=gi,e.TerrainControl=class{constructor(e){this._toggleTerrain=()=>{this._map.getTerrain()?this._map.setTerrain(null):this._map.setTerrain(this.options),this._updateTerrainIcon();},this._updateTerrainIcon=()=>{this._terrainButton.classList.remove("maplibregl-ctrl-terrain"),this._terrainButton.classList.remove("maplibregl-ctrl-terrain-enabled"),this._map.terrain?(this._terrainButton.classList.add("maplibregl-ctrl-terrain-enabled"),this._terrainButton.title=this._map._getUIString("TerrainControl.Disable")):(this._terrainButton.classList.add("maplibregl-ctrl-terrain"),this._terrainButton.title=this._map._getUIString("TerrainControl.Enable"));},this.options=e;}onAdd(e){return this._map=e,this._container=wi.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._terrainButton=wi.create("button","maplibregl-ctrl-terrain",this._container),wi.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),this._container}onRemove(){wi.remove(this._container),this._map.off("terrain",this._updateTerrainIcon),this._map=void 0;}},e.TwoFingersTouchPitchHandler=ca,e.TwoFingersTouchRotateHandler=na,e.TwoFingersTouchZoomHandler=aa,e.TwoFingersTouchZoomRotateHandler=xa,e.VectorTileSource=W,e.VideoSource=Y,e.addSourceType=(e,i)=>t.__awaiter(void 0,void 0,void 0,(function*(){if(ee(e))throw new Error(`A source type called "${e}" already exists.`);((e,t)=>{Q[e]=t;})(e,i);})),e.clearPrewarmedResources=function(){const e=k;e&&(e.isPreloaded()&&1===e.numActive()?(e.release(z),k=null):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()"));},e.createTileMesh=Kt,e.getMaxParallelImageRequests=function(){return t.config.MAX_PARALLEL_IMAGE_REQUESTS},e.getRTLTextPluginStatus=function(){return oe().getRTLTextPluginStatus()},e.getVersion=function(){return Ts},e.getWorkerCount=function(){return L.workerCount},e.getWorkerUrl=function(){return t.config.WORKER_URL},e.importScriptInWorkers=function(e){return U().broadcast("IS",e)},e.prewarm=function(){B().acquire(z);},e.setMaxParallelImageRequests=function(e){t.config.MAX_PARALLEL_IMAGE_REQUESTS=e;},e.setRTLTextPlugin=function(e,t){return oe().setRTLTextPlugin(e,t)},e.setWorkerCount=function(e){L.workerCount=e;},e.setWorkerUrl=function(e){t.config.WORKER_URL=e;};})); })); //# sourceMappingURL=benchmarks_generated.js.map