mapbox-gl 3.35.2 → 3.35.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/esm/core.js CHANGED
@@ -1 +1 @@
1
- import{eg as e,eh as t,ei as i,ej as s,ek as o,el as r,em as n,en as a,ea as l,eo as c,ep as h,eq as d,er as u,w as _,es as p,et as f,N as m,dM as g,bk as v,bw as y,R as x,e7 as b,eu as w,x as T,v as E,P as I,aQ as S,eb as D,k as R,m as C,b9 as A,ev as L,q as P,b_ as M,ew as O,ex as z,ey as F,T as k,dA as B,g as N,ez as U,ec as V,eA as j,eB as G,eC as q,eD as Z,eE as W,eF as H,eG as $,E as X,b6 as Y,af as K,ax as J,c6 as Q,eH as ee,eI as te,eJ as ie,eK as se,eL as oe,eM as re,bT as ne,f as ae,ab as le,eN as ce,e8 as he,eO as de,eP as ue,eQ as _e,eR as pe,eS as fe,eT as me,eU as ge,bZ as ve,al as ye,eV as xe,eW as be,M as we,eX as Te,a3 as Ee,ae as Ie,aC as Se,am as De,eY as Re,eZ as Ce,l as Ae,e_ as Le,o as Pe,e$ as Me,e1 as Oe,f0 as ze,b$ as Fe,e0 as ke,y as Be,f1 as Ne,f2 as Ue,f3 as Ve,ed as je,O as Ge,a8 as qe,f4 as Ze,f5 as We,dD as He,cj as $e,f6 as Xe,aB as Ye,aH as Ke,f7 as Je,bG as Qe,f8 as et,f9 as tt,fa as it,fb as st,fc as ot,c4 as rt,aA as nt,az as at,dH as lt,S as ct,L as ht,Z as dt,A as ut,bJ as _t,fd as pt,h as ft,fe as mt,b8 as gt,cT as vt,b2 as yt,aO as xt,bx as bt,aZ as wt,$ as Tt,ff as Et,a0 as It,an as St,cZ as Dt,fg as Rt,bM as Ct,e as At,e6 as Lt,fh as Pt,c0 as Mt,ci as Ot,d3 as zt,aG as Ft,a9 as kt,b0 as Bt,fi as Nt,fj as Ut,fk as Vt,fl as jt,da as Gt,cw as qt,W as Zt,aR as Wt,ao as Ht,fm as $t,fn as Xt,fo as Yt,ap as Kt,fp as Jt,cs as Qt,cD as ei,cE as ti,fq as ii,fr as si,fs as oi,b1 as ri,cP as ni,ag as ai,ft as li,_ as ci,fu as hi,fv as di,d8 as ui,fw as _i,fx as pi,fy as fi,d7 as mi,J as gi,dy as vi,dh as yi,fz as xi,bY as bi,fA as wi,ak as Ti,fB as Ei,fC as Ii,bq as Si,bc as Di,U as Ri,c as Ci,a as Ai,b as Li,d as Pi,bI as Mi,bH as Oi,fD as zi,fE as Fi,b3 as ki,bF as Bi,aS as Ni,fF as Ui,fG as Vi,fH as ji,fI as Gi,fJ as qi,fK as Zi,fL as Wi,fM as Hi,fN as $i,fO as Xi,fP as Yi,dr as Ki,fQ as Ji,fR as Qi,fS as es,fT as ts,fU as is,fV as ss,d4 as os,X as rs,fW as ns,fX as as,fY as ls,fZ as cs,ch as hs,f_ as ds,f$ as us,aq as _s,bX as ps,ar as fs,ca as ms,c9 as gs,g0 as vs,aD as ys,g1 as xs,g2 as bs,au as ws,g3 as Ts,z as Es,e9 as Is,g4 as Ss,g5 as Ds,D as Rs,g6 as Cs,g7 as As,cS as Ls,ck as Ps,g8 as Ms,g9 as Os,cI as zs,bR as Fs,ga as ks,gb as Bs,gc as Ns,gd as Us,ge as Vs,gf as js,b7 as Gs,c7 as qs,gg as Zs,ah as Ws,bA as Hs,gh as $s,gi as Xs,ad as Ys,gj as Ks,aa as Js,gk as Qs,gl as eo,gm as to,bL as io,bW as so,cr as oo,gn as ro,go as no,gp as ao,gq as lo,gr as co,gs as ho,gt as uo,gu as _o,gv as po,cg as fo,gw as mo,gx as go,gy as vo,aj as yo,gz as xo,gA as bo,bU as wo,gB as To,gC as Eo,gD as Io,gE as So,gF as Do,gG as Ro,gH as Co,gI as Ao,gJ as Lo,gK as Po,n as Mo,dV as Oo,gL as zo,gM as Fo,gN as ko,ay as Bo,gO as No,a$ as Uo,a_ as Vo,aU as jo,aW as Go,aX as qo,aY as Zo,gP as Wo,gQ as Ho,aI as $o,gR as Xo,gS as Yo,gT as Ko,gU as Jo,gV as Qo,gW as er,aT as tr,gX as ir,gY as sr,cb as or,aL as rr,gZ as nr,g_ as ar,g$ as lr,h0 as cr,h1 as hr,h2 as dr,h3 as ur,h4 as _r,h5 as pr,h6 as fr,ai as mr,a2 as gr,av as vr,a1 as yr,h7 as xr,h8 as br,h9 as wr,cc as Tr,aV as Er,ha as Ir,hb as Sr,hc as Dr,hd as Rr}from"./shared.js";var Cr="3.35.2";const Ar="01",Lr={create:"create",load:"load",fullLoad:"fullLoad"},Pr={mark(e){performance.mark(e)},measure(e,t,i){performance.measure(e,t,i)}};function Mr(r){const n=r.name.split("?")[0];return t(n)&&n.includes("mapbox-gl.js")?"javascript":t(n)&&n.includes("mapbox-gl.css")?"css":i(n)?"fontRange":s(n)?"sprite":e(n)?"style":o(n)?"tilejson":"other"}const Or=/(\.(png|jpg)\d*)(?=$)/,zr=/^.+\/v4\//,Fr=/\.[\w]+$/,kr=/^(\/v4\/|\/(raster|rasterarrays)\/v1\/)/,Br=/^access_token=(.*)$/,Nr="NO_ACCESS_TOKEN";class Ur{constructor(e,t,i){this._transformRequestFn=e,this._customAccessToken=t,this._silenceAuthErrors=!!i,this._createSkuToken()}_createSkuToken(){const e=function(){let e="";for(let t=0;t<10;t++)e+="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"[Math.floor(62*Math.random())];return{token:["1",Ar,e].join(""),tokenExpiresAt:Date.now()+432e5}}();this._skuToken=e.token,this._skuTokenExpiresAt=e.tokenExpiresAt}_isSkuTokenExpired(){return Date.now()>this._skuTokenExpiresAt}async transformRequest(e,t,i){if(!this._transformRequestFn)return{url:e};const s=i?{signal:i}:{};return await this._transformRequestFn(e,t,s)||{url:e}}normalizeStyleURL(e,t){if(!r(e))return e;const i=jr(e);return i.params.push(`sdk=js-${Cr}`),i.path=`/styles/v1${i.path}`,this._makeAPIURL(i,this._customAccessToken||t)}normalizeGlyphsURL(e,t){if(!r(e))return e;const i=jr(e);return i.path=`/fonts/v1${i.path}`,this._makeAPIURL(i,this._customAccessToken||t)}normalizeModelURL(e,t){if(!r(e))return e;const i=jr(e);return i.path=`/models/v1${i.path}`,this._makeAPIURL(i,this._customAccessToken||t)}normalizeSourceURL(e,t,i,s){if(!r(e))return e;const o=jr(e);return o.path=`/v4/${o.authority}.json`,o.params.push("secure"),i&&o.params.push(`language=${i}`),s&&o.params.push(`worldview=${s}`),this._makeAPIURL(o,this._customAccessToken||t)}normalizeIconsetURL(e,t){const i=jr(e);return r(e)?(i.path=`/styles/v1${i.path}/iconset.pbf`,this._makeAPIURL(i,this._customAccessToken||t)):Gr(i)}normalizeSpriteURL(e,t,i,s){const o=jr(e);return r(e)?(o.path=`/styles/v1${o.path}/sprite${t}${i}`,this._makeAPIURL(o,this._customAccessToken||s)):(o.path+=`${t}${i}`,Gr(o))}normalizeTileURL(e,t,i){if(this._isSkuTokenExpired()&&this._createSkuToken(),e&&!r(e))return e;const s=jr(e);s.path=s.path.replace(Or,(t||i&&"raster"!==s.authority&&512===i?"@2x":"")+".webp"),"raster"===s.authority?s.path=`/${l.RASTER_URL_PREFIX}${s.path}`:"rasterarrays"===s.authority?s.path=`/${l.RASTERARRAYS_URL_PREFIX}${s.path}`:"3dtiles"===s.authority?s.path=`/${l.TILES3D_URL_PREFIX}${s.path}`:(s.path=s.path.replace(zr,"/"),s.path=`/${l.TILE_URL_VERSION}${s.path}`);const o=this._customAccessToken||function(e){for(const t of e){const e=t.match(Br);if(e)return e[1]}return null}(s.params)||l.ACCESS_TOKEN;return l.REQUIRE_ACCESS_TOKEN&&o&&this._skuToken&&s.params.push(`sku=${this._skuToken}`),this._makeAPIURL(s,o)}canonicalizeTileURL(e,t){const i=jr(e);if(!kr.test(i.path)||!Fr.test(i.path))return e;let s="mapbox://";i.path.startsWith("/raster/v1/")?s+=`raster/${i.path.replace(`/${l.RASTER_URL_PREFIX}/`,"")}`:i.path.startsWith("/rasterarrays/v1/")?s+=`rasterarrays/${i.path.replace(`/${l.RASTERARRAYS_URL_PREFIX}/`,"")}`:s+=`tiles/${i.path.replace(`/${l.TILE_URL_VERSION}/`,"")}`;let o=i.params;return t&&(o=o.filter(e=>!e.match(Br))),o.length&&(s+=`?${o.join("&")}`),s}canonicalizeTileset(e,t){const i=!!t&&r(t),s=[];for(const t of e.tiles||[])n(t)?s.push(this.canonicalizeTileURL(t,i)):s.push(t);return s}_makeAPIURL(e,t){const i="See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes",s=jr(l.API_URL);if(e.protocol=s.protocol,e.authority=s.authority,"http"===e.protocol){const t=e.params.indexOf("secure");t>=0&&e.params.splice(t,1)}if("/"!==s.path&&(e.path=`${s.path}${e.path}`),!l.REQUIRE_ACCESS_TOKEN)return Gr(e);if(t=t||l.ACCESS_TOKEN,!this._silenceAuthErrors){if(!t)throw new Error(`An API access token is required to use Mapbox GL. ${i}`);if("s"===t[0])throw new Error(`Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). ${i}`)}return e.params=e.params.filter(e=>!e.includes("access_token")),e.params.push(`access_token=${t||""}`),Gr(e)}}const Vr=/^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;function jr(e){const t=e.match(Vr);if(!t)throw new Error("Unable to parse URL object");return{protocol:t[1],authority:t[2],path:t[3]||"/",params:t[4]?t[4].split("&"):[]}}function Gr(e){const t=e.params.length?`?${e.params.join("&")}`:"";return`${e.protocol}://${e.authority}${e.path}${t}`}const qr="mapbox.eventData";function Zr(e){if(!e)return null;const t=e.split(".");if(!t||3!==t.length)return null;try{return JSON.parse(f(t[1]))}catch(e){return null}}function Wr(e){return!(!l.EVENTS_URL||!e&&!l.ACCESS_TOKEN)}let Hr;const $r=/^[\w.+-]+(\/[\w.+-]+)?$/;function Xr(e){"string"!=typeof e||e.length>64||!$r.test(e)?_(`Invalid SDK info "${e}"; expected a "Name/version" string. Ignoring.`):Hr=e}let Yr="other";class Kr{constructor(e){this.type=e,this.anonId=null,this.anonIdTimestamp=null,this.eventData={},this.queue=[],this.pendingRequest=!1}getStorageKey(e){const t=Zr(l.ACCESS_TOKEN);let i="";return i=t&&t.u?d(t.u):l.ACCESS_TOKEN||"",e?`${qr}.${e}:${i}`:`${qr}:${i}`}fetchEventData(){const e=u("localStorage"),t=this.getStorageKey(),i=this.getStorageKey("uuid"),s=this.getStorageKey("uuidTimestamp");if(e)try{const e=localStorage.getItem(t);e&&(this.eventData=JSON.parse(e));const o=localStorage.getItem(i);o&&(this.anonId=o);const r=localStorage.getItem(s);r&&(this.anonIdTimestamp=Number(r));const n=Date.now()-864e5;(!this.anonIdTimestamp||this.anonIdTimestamp<n)&&this.refreshUUID()}catch(e){_("Unable to read from LocalStorage")}}refreshUUID(){this.anonId=c(),this.anonIdTimestamp=Date.now()}saveEventData(){const e=u("localStorage"),t=this.getStorageKey(),i=this.getStorageKey("uuid"),s=this.getStorageKey("uuidTimestamp"),o=this.anonId,r=this.anonIdTimestamp;if(e&&o)try{localStorage.setItem(i,o),Object.keys(this.eventData).length>=1&&localStorage.setItem(t,JSON.stringify(this.eventData)),r&&localStorage.setItem(s,r.toString())}catch(e){_("Unable to write to LocalStorage")}}processRequests(){}postEvent(e,t,i,s){if(!l.EVENTS_URL)return;const o=jr(l.EVENTS_URL);o.params.push(`access_token=${s||l.ACCESS_TOKEN||""}`);const r={event:this.type,created:new Date(e).toISOString()},n=t?Object.assign(r,t):r,a={url:Gr(o),headers:{"Content-Type":"text/plain"},body:JSON.stringify([n])};this.pendingRequest=!0,p(a).then(()=>{this.pendingRequest=!1,i(null),this.saveEventData(),this.processRequests()}).catch(e=>{this.pendingRequest=!1,i(e),this.saveEventData(),this.processRequests()})}queueRequest(e,t){this.queue.push({...e,customAccessToken:t}),this.processRequests()}}class Jr extends Kr{constructor(e){super("metrics"),e&&(this.data=e)}postMetricsEvent(e){if(!Wr(e))return;this.anonId||this.fetchEventData(),a(this.anonId)||this.refreshUUID();const t={...this.data,sessionId:this.anonId};this.queueRequest({timestamp:Date.now(),payload:t},e)}processRequests(){if(this.pendingRequest||0===this.queue.length)return;const{timestamp:e,payload:t,customAccessToken:i}=this.queue.shift();this.postEvent(e,t,()=>{},i)}}const Qr=new class extends Kr{constructor(e){super("appUserTurnstile"),this._customAccessToken=e}postTurnstileEvent(e,t){Wr(t)&&Array.isArray(e)&&e.some(e=>r(e)||n(e))&&this.queueRequest({timestamp:Date.now()},t)}processRequests(){if(this.pendingRequest||0===this.queue.length)return;this.anonId&&this.anonIdTimestamp&&this.eventData.lastSuccess&&this.eventData.tokenU||this.fetchEventData();const e=Zr(l.ACCESS_TOKEN),t=e?e.u:l.ACCESS_TOKEN;let i=t!==this.eventData.tokenU;a(this.anonId)||(this.refreshUUID(),i=!0);const{timestamp:s,customAccessToken:o}=this.queue.shift();if(this.eventData.lastSuccess){const e=new Date(this.eventData.lastSuccess),t=new Date(s),o=(s-this.eventData.lastSuccess)/864e5;i=i||o>=1||o<-1||e.getDate()!==t.getDate()}else i=!0;if(!i)return void this.processRequests();const r={version:"2.2",sdkIdentifier:"mapbox-gl-js",sdkVersion:Cr,skuId:Ar,"enabled.telemetry":!1,userId:this.anonId,bundleFormat:"esm",bundleDistribution:Yr};Hr&&(r.sdkInfo=Hr),this.postEvent(s,r,e=>{e||(this.eventData.lastSuccess=s,this.eventData.tokenU=t)},o)}},en=Qr.postTurnstileEvent.bind(Qr),tn=new class extends Kr{constructor(){super("map.load"),this.success={},this.skuToken=""}postMapLoadEvent(e,t,i,s){this.skuToken=t,this.errorCb=s,l.EVENTS_URL&&(i||l.ACCESS_TOKEN?this.queueRequest({id:e,timestamp:Date.now()},i):this.errorCb(new Error(Nr)))}processRequests(){if(this.pendingRequest||0===this.queue.length)return;const{id:e,timestamp:t,customAccessToken:i}=this.queue.shift();if(e&&this.success[e])return;this.anonId&&this.anonIdTimestamp||this.fetchEventData(),a(this.anonId)||this.refreshUUID();const s={version:"2.2",sdkIdentifier:"mapbox-gl-js",sdkVersion:Cr,skuId:Ar,skuToken:this.skuToken,userId:this.anonId,bundleFormat:"esm",bundleDistribution:Yr};Hr&&(s.sdkInfo=Hr),this.postEvent(t,s,t=>{t?this.errorCb(t):e&&(this.success[e]=!0)},i)}remove(){this.errorCb=null}},sn=tn.postMapLoadEvent.bind(tn),on=new class extends Kr{constructor(){super("style.load"),this.eventIdPerMapInstanceMap=new Map,this.mapInstanceIdMap=new WeakMap}getMapInstanceId(e){let t=this.mapInstanceIdMap.get(e);return t||(t=c(),this.mapInstanceIdMap.set(e,t)),t}getEventId(e){const t=this.eventIdPerMapInstanceMap.get(e)||0;return this.eventIdPerMapInstanceMap.set(e,t+1),t}postStyleLoadEvent(e,t){const{map:i,style:s,importedStyles:o}=t;if(!Wr(e))return;const r=this.getMapInstanceId(i),n={mapInstanceId:r,eventId:this.getEventId(r),style:s};o.length&&(n.importedStyles=o),this.queueRequest({timestamp:Date.now(),payload:n},e)}processRequests(){if(this.pendingRequest||0===this.queue.length)return;const{timestamp:e,payload:t,customAccessToken:i}=this.queue.shift();this.postEvent(e,t,()=>{},i)}},rn=on.postStyleLoadEvent.bind(on),nn=new Jr({attributes:[{name:"maps/js/layer-animations/style-with-appearances"}]}),an=nn.postMetricsEvent.bind(nn),ln=new Jr({attributes:[{name:"maps/js/layer-animations/runtime-appearances"}]}),cn=ln.postMetricsEvent.bind(ln),hn=new class extends Kr{constructor(){super("gljs.performance")}postPerformanceEvent(e,t){Wr(e)&&this.queueRequest({timestamp:Date.now(),performanceData:t},e)}processRequests(){if(this.pendingRequest||0===this.queue.length)return;const{timestamp:t,performanceData:i,customAccessToken:s}=this.queue.shift(),o=function(t){const i=performance.getEntriesByType("resource"),s=performance.getEntriesByType("mark"),o=function(e){const t={};if(e)for(const i in e)if("other"!==i)for(const s of e[i]){const e=`${i}ResolveRangeMin`,o=`${i}ResolveRangeMax`,r=`${i}RequestCount`,n=`${i}RequestCachedCount`;t[e]=Math.min(t[e]||1/0,s.startTime),t[o]=Math.max(t[o]||-1/0,s.responseEnd);const a=e=>{void 0===t[e]&&(t[e]=0),++t[e]};void 0!==s.transferSize&&0===s.transferSize&&a(n),a(r)}return t}(function(e,t){const i={};if(e)for(const s of e){const e=t(s);void 0===i[e]&&(i[e]=[]),i[e].push(s)}return i}(i,Mr)),r=window.devicePixelRatio,n=navigator.connection||navigator.mozConnection||navigator.webkitConnection,a=n?n.effectiveType:void 0,l={counters:[],metadata:[],attributes:[]},c=(e,t,i)=>{null!=i&&e.push({name:t,value:i.toString()})};for(const e in o)c(l.counters,e,o[e]);if(t.interactionRange[0]!==1/0&&t.interactionRange[1]!==-1/0&&(c(l.counters,"interactionRangeMin",t.interactionRange[0]),c(l.counters,"interactionRangeMax",t.interactionRange[1])),s)for(const e of Object.values(Lr)){const t=s.find(t=>t.name===e);t&&c(l.counters,e,t.startTime)}return c(l.counters,"visibilityHidden",t.visibilityHidden),c(l.attributes,"style",function(t){if(t)for(const i of t){const t=i.name.split("?")[0];if(e(t)){const e=t.split("/").slice(-2);if(2===e.length)return`mapbox://styles/${e[0]}/${e[1]}`}}}(i)),c(l.attributes,"terrainEnabled",t.terrainEnabled?"true":"false"),c(l.attributes,"fogEnabled",t.fogEnabled?"true":"false"),c(l.attributes,"projection",t.projection),c(l.attributes,"zoom",t.zoom),c(l.metadata,"devicePixelRatio",r),c(l.metadata,"connectionEffectiveType",a),c(l.metadata,"navigatorUserAgent",navigator.userAgent),c(l.metadata,"screenWidth",window.screen.width),c(l.metadata,"screenHeight",window.screen.height),c(l.metadata,"windowWidth",window.innerWidth),c(l.metadata,"windowHeight",window.innerHeight),c(l.metadata,"mapWidth",t.width/r),c(l.metadata,"mapHeight",t.height/r),c(l.metadata,"webglRenderer",t.renderer),c(l.metadata,"webglVendor",t.vendor),c(l.metadata,"sdkVersion",Cr),c(l.metadata,"sdkIdentifier","mapbox-gl-js"),l}(i);for(const e of o.metadata);for(const e of o.counters);for(const e of o.attributes);this.postEvent(t,o,()=>{},s)}},dn=hn.postPerformanceEvent.bind(hn),un=new class extends Kr{constructor(){super("map.auth"),this.success={},this.skuToken=""}getSession(e,t,i,s){if(!l.API_URL||!l.SESSION_PATH)return;const o=jr(l.API_URL+l.SESSION_PATH);o.params.push(`sku=${t||""}`),o.params.push(`access_token=${s||l.ACCESS_TOKEN||""}`);const r={url:Gr(o),headers:{"Content-Type":"text/plain"}};this.pendingRequest=!0,h(r).then(()=>{this.pendingRequest=!1,i(null),this.saveEventData(),this.processRequests()}).catch(e=>{this.pendingRequest=!1,i(e),this.saveEventData(),this.processRequests()})}getSessionAPI(e,t,i,s){this.skuToken=t,this.errorCb=s,l.EVENTS_URL&&l.SESSION_PATH&&l.API_URL&&(i||l.ACCESS_TOKEN?this.queueRequest({id:e,timestamp:Date.now()},i):this.errorCb(new Error(Nr)))}processRequests(){if(this.pendingRequest||0===this.queue.length)return;const{id:e,timestamp:t,customAccessToken:i}=this.queue.shift();e&&this.success[e]||this.getSession(t,this.skuToken,t=>{t?this.errorCb(t):e&&(this.success[e]=!0)},i)}remove(){this.errorCb=null}},_n=un.getSessionAPI.bind(un),pn=new Set;function fn(e,t){t?pn.add(e):pn.delete(e)}function mn(e){return!function(e){return"undefined"!=typeof window&&"undefined"!=typeof document?Object.hasOwn?"undefined"==typeof Worker?"Web Workers not supported":function(){const e=document.createElement("canvas");e.width=e.height=1;const t=e.getContext("2d");return!!t&&t.getImageData(0,0,1,1).width===e.width}()?function(e){return e?(void 0===yn&&(yn=xn(!0)),yn):(void 0===vn&&(vn=xn(!1)),vn)}(e)?"":"insufficient WebGL2 support":"insufficient Canvas/getImageData support":"Object.hasOwn not supported":"not a browser"}(e)}const gn={antialias:!1,alpha:!0,stencil:!0,depth:!0};let vn,yn;function xn(e){const t=document.createElement("canvas"),i=Object.create(gn);i.failIfMajorPerformanceCaveat=e;const s=t.getContext("webgl2",i);if(!s)return!1;let o;try{o=s.createShader(s.VERTEX_SHADER)}catch(e){return!1}return!(!o||s.isContextLost())&&(s.shaderSource(o,"void main() {}"),s.compileShader(o),!0===s.getShaderParameter(o,s.COMPILE_STATUS))}const bn=/firefox/i,wn=/macintosh/i;function Tn(e,t,i){const s=document.createElement(e);return null!=t&&(s.className=t),i&&i.appendChild(s),s}function En(e,t,i){const s=document.createElementNS("http://www.w3.org/2000/svg",e);for(const e of Object.keys(t))s.setAttributeNS(null,e,String(t[e]));return i&&i.appendChild(s),s}const In="undefined"!=typeof document?document.documentElement&&document.documentElement.style:null,Sn=In&&void 0!==In.userSelect?"userSelect":"WebkitUserSelect";let Dn;function Rn(){In&&Sn&&(Dn=In[Sn],In[Sn]="none")}function Cn(){In&&Sn&&(In[Sn]=Dn)}function An(e){e.preventDefault(),e.stopPropagation(),window.removeEventListener("click",An,!0)}function Ln(){window.addEventListener("click",An,!0),window.setTimeout(()=>{window.removeEventListener("click",An,!0)},0)}function Pn(e,t){const i=e.getBoundingClientRect();return zn(e,i,t)}function Mn(e,t){const i=e.getBoundingClientRect(),s=[];for(let o=0;o<t.length;o++)s.push(zn(e,i,t[o]));return s}function On(e){return bn.test(navigator.userAgent)&&wn.test(navigator.userAgent)&&2===e.button&&e.ctrlKey?0:e.button}function zn(e,t,i){const s=e.offsetWidth===t.width?1:e.offsetWidth/t.width;return new m((i.clientX-t.left)*s,(i.clientY-t.top)*s)}class Fn{constructor(){this._changed=!1,this._updatedLayers=Object.create(null),this._removedLayers=Object.create(null),this._updatedSourceCaches=Object.create(null),this._updatedPaintProps=new Set,this._updatedImages=Object.create(null)}isDirty(){return this._changed}setDirty(){this._changed=!0}getUpdatedSourceCaches(){return this._updatedSourceCaches}updateSourceCache(e,t){this._updatedSourceCaches[e]=t,this.setDirty()}discardSourceCacheUpdate(e){delete this._updatedSourceCaches[e]}updateLayer(e){const t=e.scope;this._updatedLayers[t]=this._updatedLayers[t]||new Set,this._updatedLayers[t].add(e.id),this.setDirty()}removeLayer(e){const t=e.scope;this._removedLayers[t]=this._removedLayers[t]||{},this._updatedLayers[t]=this._updatedLayers[t]||new Set,this._removedLayers[t][e.id]=e,this._updatedLayers[t].delete(e.id),this._updatedPaintProps.delete(e.fqid),this.setDirty()}getRemovedLayer(e){return this._removedLayers[e.scope]?this._removedLayers[e.scope][e.id]:null}discardLayerRemoval(e){this._removedLayers[e.scope]&&delete this._removedLayers[e.scope][e.id]}getLayerUpdatesByScope(){const e={};for(const t in this._updatedLayers)e[t]=e[t]||{},e[t].updatedIds=Array.from(this._updatedLayers[t].values());for(const t in this._removedLayers)e[t]=e[t]||{},e[t].removedIds=Object.keys(this._removedLayers[t]);return e}getUpdatedPaintProperties(){return this._updatedPaintProps}updatePaintProperties(e){this._updatedPaintProps.add(e.fqid),this.setDirty()}getUpdatedImages(e){return this._updatedImages[e]?Array.from(this._updatedImages[e].values()):[]}updateImage(e,t){this._updatedImages[t]=this._updatedImages[t]||new Set,this._updatedImages[t].add(g.toString(e)),this.setDirty()}resetUpdatedImages(e){this._updatedImages[e]&&this._updatedImages[e].clear()}reset(){this._changed=!1,this._updatedLayers=Object.create(null),this._removedLayers=Object.create(null),this._updatedSourceCaches=Object.create(null),this._updatedPaintProps.clear(),this._updatedImages=Object.create(null)}}class kn{constructor(e){this._layer=e,this._filterDependencies=void 0}invalidateFilter(){this._filterDependencies=void 0}get _filterDeps(){return void 0===this._filterDependencies&&(this._filterDependencies=this._computeFilterDependencies()),this._filterDependencies}_computeFilterDependencies(){const e=this._layer;if(!e.type||"custom"===e.type||"background"===e.type||"sky"===e.type||"slot"===e.type||"placement-group"===e.type)return null;const t=v(e.filter,y[`filter_${e.type}`]);return"error"===t.result?null:{configDependencies:t.value.configDependencies,isIndoorDependent:t.value.isIndoorDependent}}hasConfigDependency(e){const t=t=>e?t.has(e):0!==t.size,{_layoutValues:i,_paintValues:s}=this._layer;if(i&&t(i.configDependencies))return!0;if(s&&t(s.configDependencies))return!0;for(const{unevaluatedLayout:e,unevaluatedPaint:i}of this._layer.appearances)if(e&&(t(e.configDependencies)||t(i.configDependencies)))return!0;const o=this._filterDeps;return!!o&&t(o.configDependencies)}get isIndoorDependent(){const{_layoutValues:e,_paintValues:t}=this._layer;if(e&&e.isIndoorDependent())return!0;if(t&&t.isIndoorDependent())return!0;const i=this._filterDeps;return!!i&&i.isIndoorDependent}}function Bn(e){const{userImage:t}=e;return!!(t&&t.render&&t.render())&&(e.data.replace(new Uint8Array(t.data.buffer)),!0)}const Nn=new S(0,0,0);function Un(e,t){const i=[],s=e[`stretch_${t}`];let o=null;for(let e=0;e<s.length;e++)null===o?o=0===i.length?s[0]:i.at(-1)[1]+s[e]:(i.push([o,o+s[e]]),o=null);e[`stretch_${t}_areas`]=i}function Vn(e,t){const i={name:void 0};let s;for(;s=e.nextField(t);)if(1===s)i.name=e.readString();else if(2===s)i.metadata=jn(e,e.readVarint()+e.pos);else if(3===s){const t=e.readVarint()+e.pos,s=e.pos;i.usvg_tree=Zn(e,t,!0),i.data="usvg_tree",i.pending_usvg_tree={buf:e.buf,start:s,end:t}}return function(e){if(e.usvg_tree.height||(e.usvg_tree.height=e.usvg_tree.width),!e.metadata)return e;const{metadata:t}=e;if(t.content_area){const{content_area:i}=t;i.left??=0,i.top??=i.left,i.width??=e.usvg_tree.width,i.height??=i.width}if(t.text_placeholder){const{text_placeholder:e}=t;e.top??=e.left,e.height??=e.width}return t.stretch_x&&t.stretch_x.length&&Un(t,"x"),t.stretch_y&&t.stretch_y.length&&Un(t,"y"),e}(i)}function jn(e,t){const i={stretch_x:null,stretch_y:null,stretch_x_areas:null,stretch_y_areas:null,variables:[]};let s;for(;s=e.nextField(t);)1===s?i.stretch_x=e.readPackedVarint():2===s?i.stretch_y=e.readPackedVarint():3===s?i.content_area=Gn(e,e.readVarint()+e.pos):4===s?i.variables.push(qn(e,e.readVarint()+e.pos)):5===s&&(i.text_placeholder=Gn(e,e.readVarint()+e.pos));return i}function Gn(e,t){const i={};let s;for(;s=e.nextField(t);)1===s?i.left=e.readVarint():2===s?i.width=e.readVarint():3===s?i.top=e.readVarint():4===s&&(i.height=e.readVarint());return i}function qn(e,t){const i={name:void 0};let s;for(;s=e.nextField(t);)1===s?i.name=e.readString():2===s&&(i.rgb_color=Jn(e.readVarint()),i.value="rgb_color");return i}function Zn(e,t,i){const s={width:20,children:[],linear_gradients:[],radial_gradients:[],clip_paths:[],masks:[],height:20};let o;for(;o=e.nextField(t);)if(1===o)s.width=s.height=e.readVarint();else if(2===o)s.height=e.readVarint();else{if(i)continue;3===o?s.children.push(Wn(e,e.readVarint()+e.pos)):4===o?s.linear_gradients.push(Qn(e,e.readVarint()+e.pos)):5===o?s.radial_gradients.push(ta(e,e.readVarint()+e.pos)):7===o?s.clip_paths.push(ia(e,e.readVarint()+e.pos)):8===o&&s.masks.push(sa(e,e.readVarint()+e.pos))}return s}function Wn(e,t){const i={};let s;for(;s=e.nextField(t);)1===s?(i.group=Hn(e,e.readVarint()+e.pos),i.node="group"):2===s&&(i.path=Xn(e,e.readVarint()+e.pos),i.node="path");return i}function Hn(e,t){const i={opacity:255,children:[]};let s;for(;s=e.nextField(t);)1===s?i.transform=$n(e,e.readVarint()+e.pos):2===s?i.opacity=e.readVarint():5===s?i.clip_path_idx=e.readVarint():6===s?i.mask_idx=e.readVarint():7===s&&i.children.push(Wn(e,e.readVarint()+e.pos));return i}function $n(e,t){const i={sx:1,ky:0,kx:0,sy:1,tx:0,ty:0};let s;for(;s=e.nextField(t);)1===s?i.sx=e.readFloat():2===s?i.ky=e.readFloat():3===s?i.kx=e.readFloat():4===s?i.sy=e.readFloat():5===s?i.tx=e.readFloat():6===s&&(i.ty=e.readFloat());return i}function Xn(e,t){const i={paint_order:1,commands:[],step:1,diffs:[],rule:1};let s;for(;s=e.nextField(t);)1===s?i.fill=Yn(e,e.readVarint()+e.pos):2===s?i.stroke=Kn(e,e.readVarint()+e.pos):3===s?i.paint_order=e.readVarint():5===s?e.readPackedVarint(i.commands):6===s?i.step=e.readFloat():7===s?e.readPackedSVarint(i.diffs):8===s&&(i.rule=e.readVarint());return i}function Yn(e,t){const i={rgb_color:Nn,paint:"rgb_color",opacity:255};let s;for(;s=e.nextField(t);)1===s?(i.rgb_color=Jn(e.readVarint()),i.paint="rgb_color"):2===s?(i.linear_gradient_idx=e.readVarint(),i.paint="linear_gradient_idx"):3===s?(i.radial_gradient_idx=e.readVarint(),i.paint="radial_gradient_idx"):5===s&&(i.opacity=e.readVarint());return i}function Kn(e,t){const i={rgb_color:Nn,paint:"rgb_color",dasharray:[],dashoffset:0,miterlimit:4,opacity:255,width:1,linecap:1,linejoin:1};let s;for(;s=e.nextField(t);)1===s?(i.rgb_color=Jn(e.readVarint()),i.paint="rgb_color"):2===s?(i.linear_gradient_idx=e.readVarint(),i.paint="linear_gradient_idx"):3===s?(i.radial_gradient_idx=e.readVarint(),i.paint="radial_gradient_idx"):5===s?e.readPackedFloat(i.dasharray):6===s?i.dashoffset=e.readFloat():7===s?i.miterlimit=e.readFloat():8===s?i.opacity=e.readVarint():9===s?i.width=e.readFloat():10===s?i.linecap=e.readVarint():11===s&&(i.linejoin=e.readVarint());return i}function Jn(e){return new S((e>>16&255)/255,(e>>8&255)/255,(255&e)/255,1)}function Qn(e,t){const i={spread_method:1,stops:[],x1:0,y1:0,x2:1,y2:0};let s;for(;s=e.nextField(t);)1===s?i.transform=$n(e,e.readVarint()+e.pos):2===s?i.spread_method=e.readVarint():3===s?i.stops.push(ea(e,e.readVarint()+e.pos)):4===s?i.x1=e.readFloat():5===s?i.y1=e.readFloat():6===s?i.x2=e.readFloat():7===s&&(i.y2=e.readFloat());return i}function ea(e,t){const i={offset:0,opacity:255,rgb_color:Nn};let s;for(;s=e.nextField(t);)1===s?i.offset=e.readFloat():2===s?i.opacity=e.readVarint():3===s&&(i.rgb_color=Jn(e.readVarint()));return i}function ta(e,t){const i={spread_method:1,stops:[],cx:.5,cy:.5,r:.5,fx:.5,fy:.5,fr:0};let s;for(;s=e.nextField(t);)1===s?i.transform=$n(e,e.readVarint()+e.pos):2===s?i.spread_method=e.readVarint():3===s?i.stops.push(ea(e,e.readVarint()+e.pos)):4===s?i.cx=e.readFloat():5===s?i.cy=e.readFloat():6===s?i.r=e.readFloat():7===s?i.fx=e.readFloat():8===s?i.fy=e.readFloat():9===s&&(i.fr=e.readFloat());return i}function ia(e,t){const i={children:[]};let s;for(;s=e.nextField(t);)1===s?i.transform=$n(e,e.readVarint()+e.pos):2===s?i.clip_path_idx=e.readVarint():3===s&&i.children.push(Wn(e,e.readVarint()+e.pos));return i}function sa(e,t){const i={left:0,width:20,mask_type:1,children:[]};let s;for(;s=e.nextField(t);)1===s?i.left=i.top=e.readFloat():2===s?i.width=i.height=e.readFloat():3===s?i.top=e.readFloat():4===s?i.height=e.readFloat():5===s?i.mask_type=e.readVarint():6===s?i.mask_idx=e.readVarint():7===s&&i.children.push(Wn(e,e.readVarint()+e.pos));return i.height??=i.width,i.top??=i.left,i}class oa{static calculate(e={},t=[]){const i=new Map,s=new Map;if(0===Object.keys(e).length)return i;t.forEach(e=>{s.set(e.name,e.rgb_color||new S(0,0,0))});for(const[t,o]of Object.entries(e))s.has(t)?i.set(s.get(t).toString(),o):console.warn(`Ignoring unknown image variable "${t}"`);return i}}function ra(e,t=255,i){const s=i.get(e.toString())||e;return 255===t?s.toString():new S(s.r,s.g,s.b,s.a*t/255).toString()}const na=[];let aa=0;function la(e,t){if(aa>=na.length){const i=D()?new OffscreenCanvas(e,t).getContext("2d",{willReadFrequently:!0}):document.createElement("canvas").getContext("2d",{willReadFrequently:!0});na.push(i)}const i=na[aa++];return i.canvas.width=e,i.canvas.height=t,i}function ca(){aa--}function ha(e,t,i,s,o){for(const r of s.children)da(e,t,i,r,o)}function da(e,t,i,s,o){s.group?(e.save(),function(e,t,i,s,o){const r=null!=s.mask_idx?i.masks[s.mask_idx]:null,n=null!=s.clip_path_idx?i.clip_paths[s.clip_path_idx]:null;if(s.transform&&(t=xa(s.transform).preMultiplySelf(t)),!function(e,t,i){return 255!==e.opacity||t||i}(s,null!=n,null!=r))return void ha(e,t,i,s,o);const a=la(e.canvas.width,e.canvas.height);ha(a,t,i,s,o),n&&va(a,t,i,n),r&&ya(a,t,i,r,o),e.globalAlpha=s.opacity/255,e.drawImage(a.canvas,0,0),ca()}(e,t,i,s.group,o),e.restore()):s.path&&(e.save(),function(e,t,i,s,o){e.setTransform(t),1===s.paint_order?(ua(e,i,s,o),pa(e,i,s,o)):(pa(e,i,s,o),ua(e,i,s,o))}(e,t,i,s.path,o),e.restore())}function ua(e,t,i,s){const o=i.fill;if(!o)return;const r=o.opacity/255;switch(e.save(),e.beginPath(),ba(i,e),o.paint){case"rgb_color":e.fillStyle=ra(o.rgb_color,o.opacity,s);break;case"linear_gradient_idx":{const i=t.linear_gradients[o.linear_gradient_idx];i.transform&&e.setTransform(xa(i.transform).preMultiplySelf(e.getTransform())),e.fillStyle=fa(e,i,r,s);break}case"radial_gradient_idx":{const i=t.radial_gradients[o.radial_gradient_idx];i.transform&&e.setTransform(xa(i.transform).preMultiplySelf(e.getTransform())),e.fillStyle=ma(e,i,r,s)}}e.fill(_a(i)),e.restore()}function _a(e){return 1===e.rule?"nonzero":2===e.rule?"evenodd":void 0}function pa(e,t,i,s){const o=i.stroke;if(!o)return;const r=2===o.linecap||3===o.linecap,n=ba(i,new Path2D,r?.001*o.width:0);e.lineWidth=o.width,e.miterLimit=o.miterlimit,e.setLineDash(o.dasharray),e.lineDashOffset=o.dashoffset;const a=o.opacity/255;switch(o.paint){case"rgb_color":e.strokeStyle=ra(o.rgb_color,o.opacity,s);break;case"linear_gradient_idx":e.strokeStyle=fa(e,t.linear_gradients[o.linear_gradient_idx],a,s,!0);break;case"radial_gradient_idx":e.strokeStyle=ma(e,t.radial_gradients[o.radial_gradient_idx],a,s,!0)}switch(o.linejoin){case 2:case 1:e.lineJoin="miter";break;case 3:e.lineJoin="round";break;case 4:e.lineJoin="bevel"}switch(o.linecap){case 1:e.lineCap="butt";break;case 2:e.lineCap="round";break;case 3:e.lineCap="square"}e.stroke(n)}function fa(e,t,i,s,o=!1){if(1===t.stops.length){const e=t.stops[0];return ra(e.rgb_color,e.opacity*i,s)}const{x1:r,y1:n,x2:a,y2:l}=t;let c=new DOMPoint(r,n),h=new DOMPoint(a,l);if(o){const e=xa(t.transform);c=e.transformPoint(c),h=e.transformPoint(h)}const d=e.createLinearGradient(c.x,c.y,h.x,h.y);for(const e of t.stops)d.addColorStop(e.offset,ra(e.rgb_color,e.opacity*i,s));return d}function ma(e,t,i,s,o=!1){if(1===t.stops.length){const e=t.stops[0];return ra(e.rgb_color,e.opacity*i,s)}const r=xa(t.transform),{fx:n,fy:a,fr:l,cx:c,cy:h,r:d}=t;let u=new DOMPoint(n,a),_=new DOMPoint(c,h),p=l,f=d;if(o){u=r.transformPoint(u),_=r.transformPoint(_);const e=(r.a+r.d)/2;p=l*e,f=t.r*e}const m=e.createRadialGradient(u.x,u.y,p,_.x,_.y,f);for(const e of t.stops)m.addColorStop(e.offset,ra(e.rgb_color,e.opacity*i,s));return m}function ga(e,t,i,s){const o=s.transform?xa(s.transform).preMultiplySelf(t):t,r=la(e.canvas.width,e.canvas.height);for(const e of s.children)if(e.group)ga(r,o,i,e.group);else if(e.path){const t=e.path,i=new Path2D;i.addPath(wa(t),o),r.fill(i,_a(t))}const n=null!=s.clip_path_idx?i.clip_paths[s.clip_path_idx]:null;n&&va(r,o,i,n),e.globalCompositeOperation="source-over",e.drawImage(r.canvas,0,0),ca()}function va(e,t,i,s){const o=la(e.canvas.width,e.canvas.height);ga(o,t,i,s),e.globalCompositeOperation="destination-in",e.drawImage(o.canvas,0,0),ca()}function ya(e,t,i,s,o){if(0===s.children.length)return;const r=null!=s.mask_idx?i.masks[s.mask_idx]:null;r&&ya(e,t,i,r,o);const n=e.canvas.width,a=e.canvas.height,l=la(n,a),c=s.width,h=s.height,d=s.left,u=s.top,_=new Path2D,p=new Path2D;p.rect(d,u,c,h),_.addPath(p,t),l.clip(_);for(const e of s.children)da(l,t,i,e,o);const f=l.getImageData(0,0,n,a),m=f.data;if(1===s.mask_type)for(let e=0;e<m.length;e+=4)m[e+3]=m[e+3]/255*(.2126*m[e]+.7152*m[e+1]+.0722*m[e+2]);l.putImageData(f,0,0),e.globalCompositeOperation="destination-in",e.drawImage(l.canvas,0,0),ca()}function xa(e){return e?new DOMMatrix([e.sx,e.ky,e.kx,e.sy,e.tx,e.ty]):new DOMMatrix}function ba(e,t,i=0){const s=e.step;let o=e.diffs[0]*s,r=e.diffs[1]*s;t.moveTo(o,r);let n=o,a=r,l=!1,c=!0;const h=()=>!(i<=0||!l||!c||(t.lineTo(n+i,a),0));for(let i=0,d=2;i<e.commands.length;i++)switch(e.commands[i]){case 1:h(),o+=e.diffs[d++]*s,r+=e.diffs[d++]*s,t.moveTo(o,r),n=o,a=r,l=!1,c=!0;break;case 2:o+=e.diffs[d++]*s,r+=e.diffs[d++]*s,t.lineTo(o,r),l=!0,c=c&&o===n&&r===a;break;case 3:{const i=o+e.diffs[d++]*s,h=r+e.diffs[d++]*s;o=i+e.diffs[d++]*s,r=h+e.diffs[d++]*s,t.quadraticCurveTo(i,h,o,r),l=!0,c=c&&i===n&&h===a&&o===n&&r===a;break}case 4:{const i=o+e.diffs[d++]*s,h=r+e.diffs[d++]*s,u=i+e.diffs[d++]*s,_=h+e.diffs[d++]*s;o=u+e.diffs[d++]*s,r=_+e.diffs[d++]*s,t.bezierCurveTo(i,h,u,_,o,r),l=!0,c=c&&i===n&&h===a&&u===n&&_===a&&o===n&&r===a;break}case 5:l=!0,h()?t.moveTo(n,a):t.closePath(),l=!1,c=!0}return h(),t}function wa(e){return ba(e,new Path2D)}class Ta{constructor(){this.cacheMap=new Map,this.cacheDependenciesMap=new Map}static _getImage(e){return new E(e,e.data)}getFromCache(e,t,i){return this.cacheMap.has(i)||this.cacheMap.set(i,new R(150)),this.cacheMap.get(i).get(C(e.toString(),t))}setInCache(e,t,i,s){this.cacheDependenciesMap.has(s)||this.cacheDependenciesMap.set(s,new Map),this.cacheMap.has(s)||this.cacheMap.set(s,new R(150));const o=this.cacheDependenciesMap.get(s),r=C(e.id.toString(),i);o.get(r)||o.set(r,new Set);const n=this.cacheMap.get(s),a=e.toString();o.get(r).add(a),n.put(C(e.toString(),i),t)}removeImagesFromCacheByIds(e,t,i=0){if(!this.cacheMap.has(i)||!this.cacheDependenciesMap.has(i))return;const s=this.cacheMap.get(i),o=this.cacheDependenciesMap.get(i);for(const i of e){const e=C(i.toString(),t);if(o.has(e)){for(const t of o.get(e))s.delete(t);o.delete(e)}}}rasterize(e,t,i,s){const o=this.getFromCache(e,i,s);if(o)return o.clone();!function(e){const t=e.pending_usvg_tree;if(!t)return;delete e.pending_usvg_tree;const i=new I(t.buf);i.pos=t.start,e.usvg_tree=Zn(i,t.end)}(t.icon);const r=function(e,t){const i=oa.calculate(t.params,e.metadata?e.metadata.variables:[]),s=e.usvg_tree,o=s.width,r=s.height,n=Math.max(1,Math.round(o*t.sx)),a=Math.max(1,Math.round(r*t.sy)),l=new DOMMatrix([n/o,0,0,a/r,0,0]),c=la(n,a);ha(c,l,s,s,i);const h=c.getImageData(0,0,n,a);return ca(),h}(t.icon,e),n=Ta._getImage(r);return this.setInCache(e,n,i,s),n.clone()}}class Ea extends A{constructor(e){super(),this.imageProviders=new Map,this.images=new Map,this.updatedImages=new Map,this.callbackDispatchedThisFrame=new Map,this.imageVersions=new Map,this.loaded=new Map,this.requestors=[],this.patterns=new Map,this.patternsInFlight=new Set,this.atlasImage=new Map,this.atlasTexture=new Map,this.imageAtlasCache=new L,this.dirty=!0,this.spriteFormat=e,this.imageRasterizer=new Ta}addScope(e){this.loaded.set(e,!1),this.imageProviders.set(e,new Map),this.images.set(e,new Map),this.updatedImages.set(e,new Set),this.callbackDispatchedThisFrame.set(e,new Set),this.imageVersions.set(e,new Map),this.patterns.set(e,new Map),this.atlasImage.set(e,new E({width:1,height:1}))}removeScope(e){this.loaded.delete(e),this.imageProviders.delete(e),this.images.delete(e),this.updatedImages.delete(e),this.callbackDispatchedThisFrame.delete(e),this.imageVersions.delete(e),this.patterns.delete(e),this.atlasImage.delete(e);const t=this.atlasTexture.get(e);t&&(t.destroy(),this.atlasTexture.delete(e))}addImageProvider(e,t){this.imageProviders.has(t)||this.imageProviders.set(t,new Map),this.imageProviders.get(t).set(e.id,e)}removeImageProvider(e,t){this.imageProviders.has(t)&&this.imageProviders.get(t).delete(e)}getPendingImageProviders(){const e=[];for(const t of this.imageProviders.values())for(const i of t.values())i.hasPendingRequests()&&e.push(i);return e}isLoaded(){for(const e of this.loaded.keys())if(!this.loaded.get(e))return!1;return!0}setLoaded(e,t){if(this.loaded.get(t)!==e&&(this.loaded.set(t,e),e)){for(const{ids:e,callback:i}of this.requestors)this._notify(e,t,i);this.requestors=[]}}hasImage(e,t){return!!this.getImage(e,t)}getImage(e,t){return this.images.get(t).get(e.toString())}addImage(e,t,i){if(this._validate(e,i)){this.images.get(t).set(e.toString(),i);const s=this.imageVersions.get(t),o=s.get(e.toString())||0;s.set(e.toString(),o+1)}}_validate(e,t){let i=!0;return this._validateStretch(t.stretchX,t.data&&t.data.width)||(this.fire(new P(new Error(`Image "${e.name}" has invalid "stretchX" value`))),i=!1),this._validateStretch(t.stretchY,t.data&&t.data.height)||(this.fire(new P(new Error(`Image "${e.name}" has invalid "stretchY" value`))),i=!1),this._validateContent(t.content,t)||(this.fire(new P(new Error(`Image "${e.name}" has invalid "content" value`))),i=!1),i}_validateStretch(e,t){if(!e)return!0;let i=0;for(const s of e){if(s[0]<i||s[1]<s[0]||t<s[1])return!1;i=s[1]}return!0}_validateContent(e,t){if(!e)return!0;if(4!==e.length)return!1;if(!t.usvg){if(e[0]<0||t.data.width<e[0])return!1;if(e[1]<0||t.data.height<e[1])return!1;if(e[2]<0||t.data.width<e[2])return!1;if(e[3]<0||t.data.height<e[3])return!1}return!(e[2]<e[0]||e[3]<e[1])}updateImage(e,t,i){const s=this.images.get(t).get(e.toString());i.version=s.version+1,this.images.get(t).set(e.toString(),i),this.updatedImages.get(t).add(e);const o=this.imageVersions.get(t),r=o.get(e.toString())||0;o.set(e.toString(),r+1),this.removeFromImageRasterizerCache(e,t)}clearUpdatedImages(e){this.updatedImages.get(e).clear()}removeFromImageRasterizerCache(e,t){"raster"!==this.spriteFormat&&this.imageRasterizer.removeImagesFromCacheByIds([e],t)}removeImage(e,t){const i=this.images.get(t),s=i.get(e.toString());i.delete(e.toString());const o=this.imageVersions.get(t),r=o.get(e.toString())||0;o.set(e.toString(),r+1),this.patterns.get(t).delete(e.toString()),this.removeFromImageRasterizerCache(e,t),s.userImage&&s.userImage.onRemove&&s.userImage.onRemove()}listImages(e){return Array.from(this.images.get(e).keys()).map(e=>g.from(e))}hasImageProviderForSource(e,t){const i=this.imageProviders.get(t);if(!i)return!1;for(const t of i.values())if(t.sourceCache.getSource().id===e)return!0;return!1}getImages(e,t,i){const s=[],o=[],r=this.imageProviders.get(t);for(const i of e){if(!i.iconsetId){s.push(i);continue}const e=r.get(i.iconsetId);e&&(this.getImage(i,t)?o.push(i):e.addPendingRequest(i))}if(0===s.length)return void this._notify(o,t,i);let n=!0;const a=!!this.loaded.get(t),l=this.images.get(t);if(!a)for(const e of s)l.has(e.toString())||(n=!1);a||n?this._notify(s,t,i):this.requestors.push({ids:s,scope:t,callback:i})}rasterizeImages(e,t){const i=new Map,{iconTasks:s,patternTasks:o,scope:r}=e;for(const e of[s,o])for(const[t,s]of e.entries()){const e=this.getImage(s.id,r);e&&i.set(t,{image:e,imageVariant:s})}t(null,this._rasterizeImages(r,i))}_rasterizeImages(e,t){const i=new Map;for(const[s,{image:o,imageVariant:r}]of t.entries())i.set(s,this.imageRasterizer.rasterize(r,o,e,0));return i}getUpdatedImages(e){return this.updatedImages.get(e)||new Set}_notify(e,t,i){const s=this.images.get(t),o=new Map,r=this.imageVersions.get(t),n=new Map;for(const t of e){if(!s.get(t.toString())){if(t.iconsetId)continue;this.fire(new M("styleimagemissing",{id:t.name}))}const e=s.get(t.toString());if(!e){_(`Image "${t.name}" 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.`);continue}const i={data:e.usvg?null:e.data.clone(),pixelRatio:e.pixelRatio,sdf:e.sdf,usvg:e.usvg,stretchX:e.stretchX,stretchY:e.stretchY,content:e.content,hasRenderCallback:Boolean(e.userImage&&e.userImage.render)};e.usvg&&Object.assign(i,{width:e.icon.usvg_tree.width,height:e.icon.usvg_tree.height});const a=g.toString(t);o.set(a,i);const l=r&&r.get(a);l&&n.set(a,l)}i(null,{images:o,versions:n})}getPixelSize(e){const{width:t,height:i}=this.atlasImage.get(e);return{width:t,height:i}}getPattern(e,t,i){const s=e.toString(),o=this.patterns.get(t),r=o.get(s),n=this.getImage(e,t);if(!n)return null;if(r){if(r.position.version===n.version)return r.position;r.position.version=n.version}else{if(n.usvg&&!n.data){const o=this.getPatternInFlightId(s,t);if(this.patternsInFlight.has(o))return null;this.patternsInFlight.add(o);const r=new O(e).scaleSelf(T.devicePixelRatio),a=new Map([[r.toString(),{image:n,imageVariant:r}]]),l=this._rasterizeImages(t,a);return this.storePatternImage(r,t,n,i,l),null}this.storePattern(e,t,n)}return this._updatePatternAtlas(t,i),o.get(s).position}getPatternInFlightId(e,t){return C(e,t)}hasPatternsInFlight(){return 0!==this.patternsInFlight.size}storePatternImage(e,t,i,s,o){const r=e.toString(),n=o?o.get(r):void 0;n&&(i.data=n,this.storePattern(e.id,t,i),this._updatePatternAtlas(t,s),this.patternsInFlight.delete(this.getPatternInFlightId(e.id.toString(),t)))}storePattern(e,t,i){const s={w:i.data.width+2*F,h:i.data.height+2*F,x:0,y:0},o=new z(s,i,F);this.patterns.get(t).set(e.toString(),{bin:s,position:o})}destroyAtlasTextures(){for(const e of this.atlasTexture.values())e&&e.destroy();this.atlasTexture.clear()}bind(e,t){const i=e.gl;let s=this.atlasTexture.get(t);s?this.dirty&&(s.update(this.atlasImage.get(t)),this.dirty=!1):(s=new k(e,this.atlasImage.get(t),i.RGBA8),this.atlasTexture.set(t,s)),s.bind(i.LINEAR,i.CLAMP_TO_EDGE)}_updatePatternAtlas(e,t){const i=this.patterns.get(e),s=Array.from(i.values()).map(({bin:e})=>e),{w:o,h:r}=B(s),n=this.atlasImage.get(e);n.resize({width:o||1,height:r||1});const a=this.images.get(e);for(const[e,{bin:s,position:o}]of i.entries()){let i=o.padding;const r=s.x+i,l=s.y+i,c=a.get(e).data,h=c.width,d=c.height;i=i>1?i-1:i,E.copy(c,n,{x:0,y:0},{x:r,y:l},{width:h,height:d},t),E.copy(c,n,{x:0,y:d-i},{x:r,y:l-i},{width:h,height:i},t),E.copy(c,n,{x:0,y:0},{x:r,y:l+d},{width:h,height:i},t),E.copy(c,n,{x:h-i,y:0},{x:r-i,y:l},{width:i,height:d},t),E.copy(c,n,{x:0,y:0},{x:r+h,y:l},{width:i,height:d},t),E.copy(c,n,{x:h-i,y:d-i},{x:r-i,y:l-i},{width:i,height:i},t),E.copy(c,n,{x:0,y:d-i},{x:r+h,y:l-i},{width:i,height:i},t),E.copy(c,n,{x:0,y:0},{x:r+h,y:l+d},{width:i,height:i},t),E.copy(c,n,{x:h-i,y:0},{x:r-i,y:l+d},{width:i,height:i},t)}this.dirty=!0}beginFrame(){for(const e of this.images.keys())this.callbackDispatchedThisFrame.set(e,new Set);this.imageAtlasCache.beginFrame()}dispatchRenderCallbacks(e,t){const i=this.images.get(t);for(const s of e){if(this.callbackDispatchedThisFrame.get(t).has(s.toString()))continue;this.callbackDispatchedThisFrame.get(t).add(s.toString());const e=i.get(s.toString());Bn(e)&&this.updateImage(s,t,e)}}}class Ia{constructor(e){this.pendingRequests=new Map,this.cachedRanges=new Map,this.fontstackCompositing=e&&e.fontstackCompositing||"client"}loadGlyphRange(e,t,i,s,o){if("server"===this.fontstackCompositing)return void Ia.loadGlyphRange(e,t,i,s,o);const r=e.split(",").map(e=>e.trim()).filter(e=>e.length>0);0!==r.length?1!==r.length?this._loadMultipleFonts(r,t,i,s,o):this._loadFont(r[0],t,i,s,o):o(new Error("Empty fontstack"))}_loadMultipleFonts(e,t,i,s,o){const r=e.map(()=>null),n={completed:0,firstError:null,callbackCalled:!1},a=(t,i,s)=>{if(!n.callbackCalled&&(i&&!n.firstError&&(n.firstError=i),s&&(r[t]=s),n.completed++,n.completed===e.length)){n.callbackCalled=!0;const e=r.filter(e=>null!==e);if(0===e.length)return void o(n.firstError||new Error("All fonts failed to load"));const t=this._composeGlyphs(e);o(null,t)}};for(let o=0;o<e.length;o++)this._loadFont(e[o],t,i,s,(e,t)=>{a(o,e,t)})}_loadFont(e,t,i,s,o){const r=`${i}:${e}:${t}`;if(this.cachedRanges.has(r)){const e=this.cachedRanges.get(r);return void T.frame(()=>o(null,e))}const n=this.pendingRequests.get(r);n?n.push(o):(this.pendingRequests.set(r,[o]),Ia.loadGlyphRange(e,t,i,s,(e,t)=>{e||this.cachedRanges.set(r,t||null);const i=this.pendingRequests.get(r);if(this.pendingRequests.delete(r),i)for(const s of i)s(e,t)}))}_composeGlyphs(e){const t={};let i,s;for(const o of e)if(void 0===i&&void 0!==o.ascender&&(i=o.ascender),void 0===s&&void 0!==o.descender&&(s=o.descender),o.glyphs)for(const e in o.glyphs)void 0===t[e]&&(t[e]=o.glyphs[e]);return{glyphs:t,ascender:i,descender:s}}}Ia.loadGlyphRange=async function(e,t,i,s,o){const r=256*t,n=r+255;let a;try{const t=await s.transformRequest(s.normalizeGlyphsURL(i).replace("{fontstack}",e).replace("{range}",`${r}-${n}`),x.Glyphs),{data:o}=await N(t),l={},c=U(o);for(const e of c.glyphs)l[e.id]=e;a={glyphs:l,ascender:c.ascender,descender:c.descender}}catch(e){return o(e)}o(null,a)};class Sa{constructor(e,t,i,s){this.requestManager=e,this.localGlyphs=new V({mode:t,fontFamily:i}),this.url="",this.entries={},this.glyphLoader=new Ia({fontstackCompositing:s})}setURL(e){e!==this.url&&(this.url=e,this.entries={})}getGlyphs(e,t){const i=[],s=Object.keys(e),o=this.url||l.GLYPHS_URL;for(const t in e)for(const s of e[t])i.push({stack:t,id:s});j(i,({stack:e,id:t},i)=>{let s=this.entries[e];s||(s=this.entries[e]={glyphs:{},requests:{},ranges:{},ascender:void 0,descender:void 0});let r=s.glyphs[t];if(void 0!==r)return void i(null,{stack:e,id:t,glyph:r});if(r=this.localGlyphs.draw(e,t),r)return s.glyphs[t]=r,void i(null,{stack:e,id:t,glyph:r});const n=Math.floor(t/256);if(256*n>65535)return _("glyphs > 65535 not supported"),void i(null,{stack:e,id:t,glyph:r});if(s.ranges[n])return void i(null,{stack:e,id:t,glyph:r});let a=s.requests[n];a||(a=s.requests[n]=[],this.glyphLoader.loadGlyphRange(e,n,o,this.requestManager,(e,t)=>{if(t){s.ascender=t.ascender,s.descender=t.descender;for(const e in t.glyphs)this.localGlyphs.supports(+e)||(s.glyphs[+e]=t.glyphs[+e]);s.ranges[n]=!0}for(const i of a)i(e,t);delete s.requests[n]})),a.push((s,o)=>{s?i(s):o&&i(null,{stack:e,id:t,glyph:o.glyphs[t]||null})})},(e,i)=>{if(e)t(e);else if(i){const e={};for(const t of s){const i=this.entries[t];e[t]={glyphs:{},ascender:i&&i.ascender,descender:i&&i.descender}}for(const{stack:t,id:s,glyph:o}of i)e[t].glyphs[s]=o&&{id:o.id,bitmap:o.bitmap.clone(),metrics:o.metrics};t(null,e)}})}}class Da{constructor(e,t,i,s){this.message=(e?`${e}: `:"")+i,s&&(this.identifier=s),null!=t&&t.__line__&&(this.line=t.__line__)}}class Ra extends Da{}const Ca={loaded:!1};let Aa=null;function La(){return null!==Aa||(Aa=import("./debug.js").then(({DebugModule:e})=>{Object.assign(Ca,e)}).catch(()=>{_("Could not load Debug module; style validation is disabled.")})),Aa}function Pa(e,t){let i=!1;if(t&&t.length)for(const s of t)s instanceof Ra?_(s.message):(e.fire(new P(new Error(s.message))),i=!0);return i}function Ma(e){return(...t)=>{const i=Ca[e];return i?i(...t):[]}}const Oa=Ma("validateStyle"),za=Ma("validateSource"),Fa=Ma("validateLight"),ka=Ma("validateLights"),Ba=Ma("validateTerrain"),Na=Ma("validateFog"),Ua=Ma("validateSnow"),Va=Ma("validateRain"),ja=Ma("validateLayer"),Ga=Ma("validateFilter"),qa=Ma("validatePaintProperty"),Za=Ma("validateLayoutProperty"),Wa=Ma("validateModel");class Ha extends A{constructor(e,t,i){super(),this.scope=t,this._transitionable=new G(e,t,i),this.properties=new q(e)}_setValues(e,t){this._values=e,this._transitionable.setTransitionOrValue(e,t?new Map(t):void 0)}updateConfig(e){this._transitionable.setTransitionOrValue(this._values,new Map(e))}resetConfig(e){this.updateConfig(e),this._transitionable.snap()}updateTransitions(e){this._transitionable.updateTransitions(e)}hasTransition(){return this._transitionable.hasTransition()}recalculate(e){this.properties=this._transitionable.possiblyEvaluate(e)}_validate(e,t,i){return(!i||!1!==i.validate)&&Pa(this,e.call(Oa,{value:t,style:{glyphs:!0,sprite:!0},styleSpec:y}))}}const $a=y.light;let Xa;class Ya extends Ha{constructor(e,t="flat"){super(Xa||(Xa=new Z({anchor:new W($a.anchor),position:new H($a.position),color:new W($a.color),intensity:new W($a.intensity)}))),this.setLight(e,t),this._transitionable.snap()}getLight(){return this._transitionable.serialize()}setLight(e,t,i={}){this._validate(Fa,e,i)||(this._setValues(e),this.id=t)}}const Ka=y.terrain,Ja={deferred:0,elevated:1};class Qa extends Ha{constructor(e,t,i,s,o){super(new Z({source:new W(Ka.source),exaggeration:new W(Ka.exaggeration)}),i,s),this._transitionable.setTransitionOrValue(e,s),this._transitionable.snap(),this.drapeRenderMode=t,this.worldview=o}get(){return this._transitionable.serialize()}set(e,t){this._transitionable.setTransitionOrValue(e,t)}getExaggeration(e){return $(this._transitionable._values.exaggeration.state,new X(e,{worldview:this.worldview}))}getAttenuationRange(){if(!this.isZoomDependent())return null;const e=this._transitionable._values.exaggeration.value.expression;let t=-1,i=-1,s=1;for(const o of e.zoomStops)s=e.evaluate(new X(o,{worldview:this.worldview})),s>.01?(t=o,i=-1):i=o;return s<.01&&t>0&&i>t?[t,i]:null}isZoomDependent(){return this._transitionable._values.exaggeration.value.expression instanceof Y}}function el(e,t){const i=e?e.terrain:null;return!!i&&(!t||!!t.projection.requiresDraping||!i.isZoomDependent()||i.getExaggeration(t.zoom)>0)}const tl=y.fog;class il extends Ha{constructor(e,t,i,s){super(new Z({range:new W(tl.range),color:new W(tl.color),"color-use-theme":new W({type:"string","property-type":"data-constant",default:"default"}),"high-color":new W(tl["high-color"]),"high-color-use-theme":new W({type:"string","property-type":"data-constant",default:"default"}),"space-color":new W(tl["space-color"]),"space-color-use-theme":new W({type:"string","property-type":"data-constant",default:"default"}),"horizon-blend":new W(tl["horizon-blend"]),"star-intensity":new W(tl["star-intensity"]),"vertical-range":new W(tl["vertical-range"])}),i,new Map(s)),this._transform=t,this.set(e),this._transitionable.snap()}get state(){const e=this._transform,t="globe"===e.projection.name,i=K(e.zoom),s=this.properties.get("range"),o=[2,4.5],r=.5/Math.tan(.5*e._fov),n=[s[0]+r,s[1]+r];return{range:t?[J(o[0],n[0],i),J(o[1],n[1],i)]:n,horizonBlend:this.properties.get("horizon-blend"),alpha:this.properties.get("color").a}}get(){return this._transitionable.serialize()}set(e,t,i={}){if(this._validate(Na,e,i))return;const s={...e};for(const e of Object.keys(tl))void 0===s[e]&&(s[e]=tl[e].default);this._setValues(s,t)}getOpacity(e){if(!this._transform.projection.supportsFog)return 0;const t=this.properties&&this.properties.get("color")||1;return("globe"===this._transform.projection.name?1:Q(te,ee,e))*t.a}getOpacityAtLatLng(e,t){return this._transform.projection.supportsFog?ie(this.state,e,t):0}getOpacityForTile(e){if(!this._transform.projection.supportsFog)return[1,1];const t=this._transform.calculateFogTileMatrix(e.toUnwrapped());return se(this.state,t,0,0,ae,ae,this._transform)}getOpacityForBounds(e,t,i,s,o){return this._transform.projection.supportsFog?se(this.state,e,t,i,s,o,this._transform):[1,1]}getRangeForProjection(){return this._transform.projection.supportsFog?this.state.range:[0,1]}isVisibleOnFrustum(e){if(!this._transform.projection.supportsFog)return!1;const t=[4,5,6,7];for(const i of t){const t=e.points[i];let s;if(t[2]>=0)s=t;else{const o=e.points[i-4];s=oe(o,t,o[2]/(o[2]-t[2]))}if(re(this.state,s[0],s[1],0,this._transform)>=ne)return!0}return!1}}let sl,ol;class rl extends Ha{constructor(e,t,i,s){super(sl||(sl=new Z({density:new W(y.snow.density),intensity:new W(y.snow.intensity),color:new W(y.snow.color),opacity:new W(y.snow.opacity),vignette:new W(y.snow.vignette),"vignette-color":new W(y.snow["vignette-color"]),"center-thinning":new W(y.snow["center-thinning"]),direction:new W(y.snow.direction),"flake-size":new W(y.snow["flake-size"])})),i,new Map(s)),this.set(e),this._transitionable.snap()}get state(){const e=this.properties.get("opacity"),t=this.properties.get("color"),i=this.properties.get("direction"),s=le(i[0]),o=-Math.max(le(i[1]),.01),r=[Math.cos(s)*Math.cos(o),Math.sin(s)*Math.cos(o),Math.sin(o)],n=this.properties.get("vignette"),a=this.properties.get("vignette-color"),l=new S(a.r,a.g,a.b,n);return{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new S(t.r,t.g,t.b,t.a*e),direction:r,centerThinning:this.properties.get("center-thinning"),flakeSize:this.properties.get("flake-size"),vignetteColor:l}}get(){return this._transitionable.serialize()}set(e,t,i={}){if(this._validate(Ua,e,i))return;const s={...e},o=y.snow;for(const e of Object.keys(o))void 0===s[e]&&(s[e]=o[e].default);this._setValues(s,t)}}class nl extends Ha{constructor(e,t,i,s){super(ol||(ol=new Z({density:new W(y.rain.density),intensity:new W(y.rain.intensity),color:new W(y.rain.color),opacity:new W(y.rain.opacity),vignette:new W(y.rain.vignette),"vignette-color":new W(y.rain["vignette-color"]),"center-thinning":new W(y.rain["center-thinning"]),direction:new W(y.rain.direction),"droplet-size":new W(y.rain["droplet-size"]),"distortion-strength":new W(y.rain["distortion-strength"])})),i,new Map(s)),this.set(e),this._transitionable.snap()}get state(){const e=this.properties.get("opacity"),t=this.properties.get("color"),i=this.properties.get("direction"),s=le(i[0]),o=-Math.max(le(i[1]),.01),r=[Math.cos(s)*Math.cos(o),Math.sin(s)*Math.cos(o),Math.sin(o)],n=this.properties.get("vignette-color"),a=new S(n.r,n.g,n.b,this.properties.get("vignette"));return{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new S(t.r,t.g,t.b,t.a*e),direction:r,centerThinning:this.properties.get("center-thinning"),dropletSize:this.properties.get("droplet-size"),distortionStrength:this.properties.get("distortion-strength"),vignetteColor:a}}get(){return this._transitionable.serialize()}set(e,t,i={}){if(this._validate(Va,e,i))return;const s={...e},o=y.rain;for(const e of Object.keys(o))void 0===s[e]&&(s[e]=o[e].default);this._setValues(s,t)}}const al={workerUrl:""};function ll(e){al.workerUrl=e}function cl(){return al.workerUrl?new Worker(al.workerUrl,{type:"module"}):new Worker(new URL("worker.js",import.meta.url),{type:"module"})}const hl="mapboxgl_preloaded_worker_pool";class dl{constructor(e){this.active={},this.workers=null,this.name=e}acquire(e,t=dl.workerCount){if(!this.workers)for(this.workers=[];this.workers.length<t;){const e=cl();this.workers.push(e)}return this.active[e]=!0,this.workers.slice()}release(e){delete this.active[e],this.workers&&0===this.numActive()&&(this.workers.forEach(e=>{e.terminate()}),this.workers=null)}isPreloaded(){return!!this.active[hl]}numActive(){return Object.keys(this.active).length}}function ul(){return dl.workerCount}function _l(e){dl.workerCount=e}dl.workerCount=2;class pl{constructor(e,t,i="Worker",s=dl.workerCount){this.workerPool=e,this.actors=[],this.currentActor=0,this.id=ce();const o=this.workerPool.acquire(this.id,s);for(let e=0;e<o.length;e++){const s=new pl.Actor(o[e],t,this.id);s.name=`${i} ${e}`,this.actors.push(s)}this.ready=!1,this.send("checkIfReady",null).then(()=>{this.ready=!0}).catch(()=>{})}send(e,t,i){return Promise.all(this.actors.map(s=>s.send(e,t,i)))}broadcast(e,t){for(const i of this.actors)i.notify(e,t)}getActor(){return this.currentActor=(this.currentActor+1)%this.actors.length,this.actors[this.currentActor]}remove(){this.actors.forEach(e=>{e.remove()}),this.actors=[],this.workerPool.release(this.id)}}pl.Actor=he;class fl extends Ha{constructor(e,t,i,s){super(t,i,new Map(s)),this.set(e),this._transitionable.snap()}get(){return this._options.properties=this._transitionable.serialize(),this._options}set(e,t){this._options=e,this._setValues(e.properties,t)}shadowsEnabled(){return!!this.properties&&!0===this.properties.get("cast-shadows")}}let ml;const gl=()=>ml||(ml=new Z({color:new W(y.properties_light_ambient.color),"color-use-theme":new W({type:"string",default:"default","property-type":"data-constant"}),intensity:new W(y.properties_light_ambient.intensity)}));let vl;const yl=()=>vl||(vl=new Z({direction:new de(y.properties_light_directional.direction),color:new W(y.properties_light_directional.color),"color-use-theme":new W({type:"string",default:"default","property-type":"data-constant"}),intensity:new W(y.properties_light_directional.intensity),"cast-shadows":new W(y.properties_light_directional["cast-shadows"]),"shadow-quality":new W(y.properties_light_directional["shadow-quality"]),"shadow-intensity":new W(y.properties_light_directional["shadow-intensity"]),"shadow-draw-before-layer":new W(y.properties_light_directional["shadow-draw-before-layer"])}));function xl(e,t){let i=null,s=null;const o={globals:{zoom:0}};e.forEachFragmentStyle(t=>{if(i)return;const r=t.stylesheet?t.stylesheet.schema:null;if(!r||!r.sdCoverageFadeRange)return;const n=C("sdCoverageFadeRange",t.scope),a=t.options?t.options.get(n):void 0,l=a?a.value||a.default:null;if(l){const e=l.evaluate(o);Array.isArray(e)&&2===e.length&&(e[0]>0||e[1]>0)&&(i=[e[0],e[1]])}const c=C("sdCoverageSourceLayers",t.scope),h=t.options?t.options.get(c):void 0,d=h?h.value||h.default:null;if(d){const e=d.evaluate(o);Array.isArray(e)&&e.length>0&&(s=e)}else{const i=e.stylesheet&&e.stylesheet.imports||[];for(const e of i)if(e.id===t.scope){const t=e.config?e.config.sdCoverageSourceLayers:void 0;Array.isArray(t)&&t.length>0&&(s=t);break}}}),t.frcCoverageFadeRange=i,t.frcCoverageSourceLayers=null!=i?s||["road","structure"]:[]}function bl(e,t){if(e.z<=t.z){const i=t.z-e.z;return t.x>>i===e.x&&t.y>>i===e.y}const i=e.z-t.z;return e.x>>i===t.x&&e.y>>i===t.y}function wl(e,t){return e.sourceFQID!==t.sourceFQID?e.sourceFQID<t.sourceFQID?-1:1:e.tileId.z!==t.tileId.z?e.tileId.z-t.tileId.z:e.tileId.x!==t.tileId.x?e.tileId.x-t.tileId.x:e.tileId.y-t.tileId.y}class Tl{constructor(e=[]){this.tiles=e}getTilesIntersecting(e){const t=[];for(const i of this.tiles)bl(i.tileId,e)&&t.push(i);return t}equals(e){if(this.tiles.length!==e.length)return!1;for(let t=0;t<this.tiles.length;++t){const i=this.tiles[t],s=e[t];if(i.sourceFQID!==s.sourceFQID||i.tileId.z!==s.tileId.z||i.tileId.x!==s.tileId.x||i.tileId.y!==s.tileId.y||i.generation!==s.generation)return!1}return!0}empty(){return 0===this.tiles.length}}function El(e,t,i){if(el(e.style,e.transform))return null;if(!i)return null;const s=e.painter?e.painter.elevationCoverageSnapshot:null,o=!(!e.painter||!e.painter.elevationProvidersReady);return s?function(e,t,i){const s=e.getTilesIntersecting(t);if(0===s.length)return{registry:[],hasCoveringTile:!1,allProvidersReady:i};const o=[];for(const e of s)for(const t of e.features)o.push({tileId:e.tileId,feature:t});return o.sort((e,t)=>e.feature.id-t.feature.id),{registry:o,hasCoveringTile:!0,allProvidersReady:i}}(s,t.tileID.canonical,o):{registry:[],hasCoveringTile:!1,allProvidersReady:o}}const Il={updateFrcCoverageFadeRange:xl,buildElevationRequestParams:El};let Sl=null;function Dl(){return null!==Sl||(Sl=import("./hd.main.js").then(({HD:e})=>{Object.assign(Il,e)}).catch(()=>{Sl=null,_("Could not load HD module.")})),Sl}let Rl=null;function Cl(){return null!==Rl||(Rl=import("./standard.main.js").then(({Standard:e})=>{Object.assign(ue,e)}).catch(()=>{Rl=null,_("Could not load Standard module.")})),Rl}const Al={};let Ll=null;const Pl={};let Ml=null;function Ol(){return null!==Ml||(Ml=import("./raster_array.main.js").then(({RasterArray:e})=>{Object.assign(Pl,e)}).catch(()=>{Ml=null,_("Could not load raster-array module.")})),Ml}class zl{constructor(e,t,i){this.screenBounds=e,this.cameraPoint=i.getCameraPoint(),this._screenRaycastCache={},this._cameraRaycastCache={},this.isAboveHorizon=t,this.screenGeometry=this.bufferedScreenGeometry(0),this.screenGeometryMercator=this._bufferedScreenMercator(0,i)}static createFromScreenPoints(e,t){let i,s;if(e instanceof m||"number"==typeof e[0]){const o=m.convert(e);i=[o],s=t.isPointAboveHorizon(o)}else{const o=m.convert(e[0]),r=m.convert(e[1]),n=o.add(r)._div(2);i=[o,r],s=_e(o,r).every(e=>t.isPointAboveHorizon(e))&&t.isPointAboveHorizon(n)}return new zl(i,s,t)}isPointQuery(){return 1===this.screenBounds.length}bufferedScreenGeometry(e){return _e(this.screenBounds[0],1===this.screenBounds.length?this.screenBounds[0]:this.screenBounds[1],e)}bufferedCameraGeometry(e){const t=this.screenBounds[0],i=1===this.screenBounds.length?this.screenBounds[0].add(new m(1,1)):this.screenBounds[1],s=_e(t,i,0,!1);return this.cameraPoint.y>i.y&&(this.cameraPoint.x>t.x&&this.cameraPoint.x<i.x?s.splice(3,0,this.cameraPoint):this.cameraPoint.x>=i.x?s[2]=this.cameraPoint:this.cameraPoint.x<=t.x&&(s[3]=this.cameraPoint)),pe(s,e)}bufferedCameraGeometryGlobe(e){const t=this.screenBounds[0],i=1===this.screenBounds.length?this.screenBounds[0].add(new m(1,1)):this.screenBounds[1],s=_e(t,i,e),o=this.cameraPoint.clone(),r=Number(o.x>t.x)+Number(o.x>i.x);switch(3*(Number(o.y>t.y)+Number(o.y>i.y))+r){case 0:s[0]=o,s[4]=o.clone();break;case 1:s.splice(1,0,o);break;case 2:s[1]=o;break;case 3:s.splice(4,0,o);break;case 5:s.splice(2,0,o);break;case 6:s[3]=o;break;case 7:s.splice(3,0,o);break;case 8:s[2]=o}return s}containsTile(e,t,i,s=0,o){const r=Math.max(e.queryPadding,e.evaluateQueryRenderedFeaturePadding())/t._pixelsPerMercatorPixel+1,n=i?this._bufferedCameraMercator(r,t):this._bufferedScreenMercator(r,t);let a=e.tileID.wrap+(n.unwrapped?s:0);const l=n.polygon.map(t=>fe(e.tileTransform,t,a));if(!me(l,0,0,ae,ae))return;a=e.tileID.wrap+(this.screenGeometryMercator.unwrapped?s:0);const c=this.screenGeometryMercator.polygon.map(t=>ge(e.tileTransform,t,a)),h=c.map(e=>new m(e[0],e[1])),d=ge(e.tileTransform,o,a),u=c.map(e=>{const t=ve(e,e,d);return ye(t,t),new xe(d,t)}),_=Te(e,1,t.zoom)*t._pixelsPerMercatorPixel;return{queryGeometry:this,tilespaceGeometry:h,tilespaceRays:u,bufferedTilespaceGeometry:l,bufferedTilespaceBounds:(p=be(l),p.min.x=Ee(p.min.x,0,ae),p.min.y=Ee(p.min.y,0,ae),p.max.x=Ee(p.max.x,0,ae),p.max.y=Ee(p.max.y,0,ae),p),tile:e,tileID:e.tileID,pixelToTileUnitsFactor:_};var p}_bufferedScreenMercator(e,t){const i=Bl(e);if(this._screenRaycastCache[i])return this._screenRaycastCache[i];{let s;return s="globe"===t.projection.name?this._projectAndResample(this.bufferedScreenGeometry(e),t):{polygon:this.bufferedScreenGeometry(e).map(e=>t.pointCoordinate3D(e)),unwrapped:!0},this._screenRaycastCache[i]=s,s}}_bufferedCameraMercator(e,t){const i=Bl(e);if(this._cameraRaycastCache[i])return this._cameraRaycastCache[i];{let s;return s="globe"===t.projection.name?this._projectAndResample(this.bufferedCameraGeometryGlobe(e),t):{polygon:this.bufferedCameraGeometry(e).map(e=>t.pointCoordinate3D(e)),unwrapped:!0},this._cameraRaycastCache[i]=s,s}}_projectAndResample(e,t){const i=function(e,t){const i=Ie([],t.pixelMatrix,t.globeMatrix),s=[0,-De,0,1],o=[0,De,0,1],r=[0,0,0,1];Se(s,s,i),Se(o,o,i),Se(r,r,i);const n=new m(s[0]/s[3],s[1]/s[3]),a=new m(o[0]/o[3],o[1]/o[3]),l=Re(e,n)&&s[3]<r[3],c=Re(e,a)&&o[3]<r[3];if(!l&&!c)return null;const h=function(e,t,i){for(let s=1;s<e.length;s++){const o=kl(t.pointCoordinate3D(e[s-1]).x),r=kl(t.pointCoordinate3D(e[s]).x);if(i<0){if(o<r)return{idx:s,t:-o/(r-1-o)}}else if(r<o)return{idx:s,t:(1-o)/(r+1-o)}}return null}(e,t,l?-1:1);if(!h)return null;const{idx:d,t:u}=h;let _=d>1?Fl(e.slice(0,d),t):[],p=d<e.length?Fl(e.slice(d),t):[];_=_.map(e=>new m(kl(e.x),e.y)),p=p.map(e=>new m(kl(e.x),e.y));const f=[..._];0===f.length&&f.push(p.at(-1));const g=f.at(-1),v=J(g.y,(0===p.length?_[0]:p[0]).y,u);let y;return y=l?[new m(0,v),new m(0,0),new m(1,0),new m(1,v)]:[new m(1,v),new m(1,1),new m(0,1),new m(0,v)],f.push(...y),0===p.length?f.push(_[0]):f.push(...p),{polygon:f.map(e=>new we(e.x,e.y)),unwrapped:!1}}(e,t);if(i)return i;const s=function(e,t){let i=!1,s=-1/0,o=0;for(let t=0;t<e.length-1;t++)e[t].x>s&&(s=e[t].x,o=t);for(let t=0;t<e.length-1;t++){const s=(o+t)%(e.length-1),r=e[s],n=e[s+1];Math.abs(r.x-n.x)>.5&&(r.x<n.x?(r.x+=1,0===s&&(e.at(-1).x+=1)):(n.x+=1,s+1===e.length-1&&(e[0].x+=1)),i=!0)}const r=Ae(t.center.lng);return i&&r<Math.abs(r-1)&&e.forEach(e=>{e.x-=1}),{polygon:e,unwrapped:i}}(Fl(e,t).map(e=>new m(kl(e.x),e.y)),t);return{polygon:s.polygon.map(e=>new we(e.x,e.y)),unwrapped:s.unwrapped}}}function Fl(e,t){return Ce(e,e=>{const i=t.pointCoordinate3D(e);e.x=i.x,e.y=i.y},1/256)}function kl(e){return e<0?1+e%1:e%1}function Bl(e){return 100*e|0}function Nl(e,t){const i=Math.pow(2,t.z),s=Math.floor(Ae(e.getWest())*i),o=Math.floor(Pe(e.getNorth())*i),r=Math.ceil(Ae(e.getEast())*i),n=Math.ceil(Pe(e.getSouth())*i);return t.x>=s&&t.x<r&&t.y>=o&&t.y<n}class Ul{constructor(e){this.bounds=e.bounds?Le.convert(this.validateBounds(e.bounds)):null,this.extraBounds=e.extra_bounds&&e.extra_bounds.length>0?e.extra_bounds.map(e=>Le.convert(this.validateBounds(e))):null,this.minzoom=e.minzoom||0,this.maxzoom=e.maxzoom||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){if(e.z>this.maxzoom||e.z<this.minzoom)return!1;if(this.bounds&&!Nl(this.bounds,e))return!1;if(!this.extraBounds)return!0;for(const t of this.extraBounds)if(Nl(t,e))return!0;return!1}}function Vl(e){return e&&r(e)?"id":null}class jl extends A{constructor(e,t,i,s){super(),this.id=e,this.dispatcher=i,this.setEventedParent(s),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme="xyz",this.tileSize=512,this._loaded=!1,this._options={type:"raster",...t},Object.assign(this,Me(t,["url","scheme","tileSize"]))}load(e){this._loaded=!1,this.fire(new M("dataloading",{dataType:"source"}));const t=this.map.getWorldview(),i=(t,i)=>{this._tileJSONRequest=null,this._loaded=!0,t?this.fire(new P(t)):i&&(Object.assign(this,i),i.raster_layers&&(this.rasterLayers=i.raster_layers,this.rasterLayerIds=this.rasterLayers.map(e=>e.id)),this.tileBounds=new Ul(i),en(i.tiles),this.fire(new M("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new M("data",{dataType:"source",sourceDataType:"content"}))),e&&e(t)};this.provider="string"==typeof this._options.provider?this._options.provider:void 0,this._tileProvider=void 0;const s=ze(this._options);return s instanceof Error?(this._loaded=!0,this.fire(new P(s)),void(e&&e())):this.provider&&!s?(this._loaded=!0,this.fire(new P(new Error(`TileProvider "${this.provider}" is not registered`))),void(e&&e())):void(this._tileJSONRequest=s?this.loadTileJSONWithProvider(s,i):Fe(this._options,this.map._requestManager,null,t,i))}loadTileJSONWithProvider(e,t){this.provider=e.name;const i=new AbortController;return(async()=>{const{request:s,options:o}=await Ue(this._options,this.map._requestManager,i.signal);if(i.signal.aborted)return;const r=await je(e.name,e.url);if(i.signal.aborted)return;const n=new r(o);let a=null;if(n.load&&s&&(a=await n.load({request:s}),i.signal.aborted))return;this._tileProvider=n;const l=Ve(this._options,a,this.map._requestManager);l instanceof Error?t(l):t(null,l)})().catch(s=>{i.signal.aborted||t(new Error(`Could not load tile provider ${e.name}`,{cause:s}))}),{cancel:()=>i.abort()}}loaded(){return this._loaded}onAdd(e){this.map=e,this.load()}reload(){this.cancelTileJSONRequest();const e=C(this.id,this.scope);this.load(()=>this.map.style.clearSource(e))}setTiles(e){return this._options.tiles=e,this.reload(),this}setUrl(e){return this.url=e,this._options.url=e,this.reload(),this}setMinzoom(e){return this._options.minzoom=e,this.reload(),this}setMaxzoom(e){return this._options.maxzoom=e,this.reload(),this}onRemove(e){this.cancelTileJSONRequest()}serialize(){return{...this._options}}hasTile(e){return!this.tileBounds||this.tileBounds.contains(e.canonical)}async loadTile(e,t){const i=T.devicePixelRatio>=2,s=this.map._requestManager.normalizeTileURL(e.tileID.canonical.url(this.tiles,this.scheme),i,this.tileSize),o=new AbortController;if(e.request=o,this._tileProvider)this.loadTileWithProvider(e,this._tileProvider,s,o,t);else try{const i=await this.map._requestManager.transformRequest(s,x.Tile,o.signal);if(o.signal.aborted)return delete e.request,t(null);const{data:r,headers:n}=await w(i,o.signal);if(delete e.request,e.aborted)return t(null);const a=Be(n);this.map._refreshExpiredTiles&&e.setExpiryData(a),e.setTexture(r,this.map.painter),e.state="loaded",Ne(this.dispatcher),t(null)}catch(i){if(delete e.request,o.signal.aborted)return t(null);e.state="errored",t(i)}}async loadTileWithProvider(e,t,i,s,o){const{z:r,x:n,y:a}=e.tileID.canonical;try{const l=await this.map._requestManager.transformRequest(i,x.Tile,s.signal);if(s.signal.aborted)return o(null);const c=await t.loadTile({z:r,x:n,y:a},{request:l,signal:s.signal});if(s.signal.aborted)return o(null);if(null==c){const t=new Error("Tile not found");return t.status=404,e.state="errored",o(t)}if(null==c.data)return e.state="loaded",o(null);const h=c.data instanceof ImageBitmap?c.data:await createImageBitmap(new Blob([c.data]));if(s.signal.aborted)return o(null);e.setTexture(h,this.map.painter),e.state="loaded",this.map._refreshExpiredTiles&&e.setExpiryData({cacheControl:c.cacheControl,expires:c.expires}),o(null)}catch(t){if(s.signal.aborted)return o(null);e.state="errored",o(new Error(`Could not load tile from ${i}`,{cause:t}))}finally{delete e.request}}abortTile(e,t){e.request&&(e.request.abort(),delete e.request),t&&t()}unloadTile(e,t){e.texture&&e.texture instanceof k?(e.destroy(!1),e.texture&&e.texture instanceof k&&this.map.painter.saveTileTexture(e.texture)):e.destroy(),t&&t()}hasTransition(){return!1}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}}const Gl=qe([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Uint16",components:2}]);function ql(e,t,i,s,o,r,n,a){const l=[e,t,1,i,s,1,o,r,1],c=[n,a,1],h=it([],l),[d,u,_]=Qe(c,c,h);return st(l,l,[d,0,0,0,u,0,0,0,_])}function Zl(e,t,i,s,o,r,n,a){const l=function(e,t,i,s,o,r,n,a){const l=ql(0,0,1,0,1,1,0,1),c=ql(e,t,i,s,o,r,n,a),h=it([],l);return st(c,c,h)}(e,t,i,s,o,r,n,a);return[l[2]/l[8]/ae,l[5]/l[8]/ae]}function Wl(e){return[e[0],Math.min(Math.max(e[1],-We),We)]}class Hl extends A{constructor(e,t,i,s){super(),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.onNorthPole=!1,this.onSouthPole=!1,this.setEventedParent(s),this.options=t,this._dirty=!1}async load(e,t){if(this._loaded=t||!1,this.fire(new M("dataloading",{dataType:"source"})),this.url=this.options.url,!this.url)return e&&(this.coordinates=e),this._loaded=!0,void this._finishLoading();const i=new AbortController;this._imageRequest=i;try{const t=await this.map._requestManager.transformRequest(this.url,x.Image,i.signal),{data:s}=await w(t,i.signal);this._imageRequest=null,this._loaded=!0,this.image=s,this._dirty=!0,this.width=this.image.width,this.height=this.image.height,e&&(this.coordinates=e),this._finishLoading()}catch(e){if(i.signal.aborted)return;this._imageRequest=null,this._loaded=!0,this.fire(new P(e))}}loaded(){return this._loaded}updateImage(e){return e.url?(this._imageRequest&&e.url!==this.options.url&&(this._imageRequest.abort(),this._imageRequest=null),this.options.url=e.url,this.load(e.coordinates,this._loaded),this):this}setTexture(e){if(!(e.handle instanceof WebGLTexture))throw new Error("The provided handle is not a WebGLTexture instance");return this.texture=new Ze(this.map.painter.context,e.handle),this.width=e.dimensions[0],this.height=e.dimensions[1],this._dirty=!1,this._loaded=!0,this._finishLoading(),this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new M("data",{dataType:"source",sourceDataType:"metadata"})))}onAdd(e){this.map=e,this.load()}onRemove(e){this._imageRequest&&(this._imageRequest.abort(),this._imageRequest=null),!this.texture||this.texture instanceof Ze||this.texture.destroy(),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy())}setCoordinates(e){if(this.coordinates=e,this._boundsArray=void 0,this._unsupportedCoords=!1,!e.length)return this;this.onNorthPole=!1,this.onSouthPole=!1;let t=e[0][1],i=e[0][1];for(const s of e)s[1]>i&&(i=s[1]),s[1]<t&&(t=s[1]);const s=(i+t)/2;if(s>We?this.onNorthPole=!0:s<-We&&(this.onSouthPole=!0),!this.onNorthPole&&!this.onSouthPole){const t=e.map(we.fromLngLat);this.tileID=function(e){let t=1/0,i=1/0,s=-1/0,o=-1/0;for(const r of e)t=Math.min(t,r.x),i=Math.min(i,r.y),s=Math.max(s,r.x),o=Math.max(o,r.y);const r=Math.max(s-t,o-i),n=Math.max(0,Math.floor(-Math.log2(r))),a=Math.pow(2,n);let l=Math.floor((t+s)/2*a);return l>1&&(l-=1),new $e(n,l,Math.floor((i+o)/2*a))}(t),this.minzoom=this.maxzoom=this.tileID.z}return this.fire(new M("data",{dataType:"source",sourceDataType:"content"})),this}_clear(){!this.texture||this.texture instanceof Ze||(this.texture.destroy(),this._dirty=!0),this.texture=null,this._boundsArray=void 0,this._unsupportedCoords=!1}_prepareData(e){for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture)}if(this._boundsArray||this.onNorthPole||this.onSouthPole||this._unsupportedCoords)return;const t=He(new $e(0,0,0),this.map.transform.projection),i=[t.projection.project(this.coordinates[0][0],this.coordinates[0][1]),t.projection.project(this.coordinates[1][0],this.coordinates[1][1]),t.projection.project(this.coordinates[2][0],this.coordinates[2][1]),t.projection.project(this.coordinates[3][0],this.coordinates[3][1])];if(!function(e){const t=e[1].x-e[0].x,i=e[1].y-e[0].y,s=e[2].x-e[1].x,o=e[2].y-e[1].y,r=e[3].x-e[2].x,n=e[3].y-e[2].y,a=e[0].x-e[3].x,l=e[0].y-e[3].y,c=t*o-s*i,h=s*n-r*o,d=r*l-a*n,u=a*i-t*l;return c>0&&h>0&&d>0&&u>0||c<0&&h<0&&d<0&&u<0}(i))return console.warn("Image source coordinates are defining non-convex area in the Mercator projection"),void(this._unsupportedCoords=!0);const s=He(this.tileID,this.map.transform.projection),[o,r,n,a]=this.coordinates.map(e=>{const t=s.projection.project(e[0],e[1]);return fe(s,t)._round()});this.perspectiveTransform=Zl(o.x,o.y,r.x,r.y,n.x,n.y,a.x,a.y);const l=this._boundsArray=new Xe;l.emplaceBack(o.x,o.y,0,0),l.emplaceBack(r.x,r.y,ae,0),l.emplaceBack(a.x,a.y,0,ae),l.emplaceBack(n.x,n.y,ae,ae),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy()),this.boundsBuffer=e.createVertexBuffer(l,Gl.members),this.boundsSegments=Ye.simpleSegment(0,0,4,2);const c=Je,h=c+1,d=c+1,u=h*d,_=c*c*2,p=[],f=function(e){return[Wl(e[0]),Wl(e[1]),Wl(e[2]),Wl(e[3])]}(this.coordinates),[m,g,v,y]=function(e){let t=e[0][0],i=t,s=e[0][1],o=s;for(let r=1;r<e.length;r++)e[r][0]<t?t=e[r][0]:e[r][0]>i&&(i=e[r][0]),e[r][1]<s?s=e[r][1]:e[r][1]>o&&(o=e[r][1]);return[t,s,i-t,o-s]}(f);{const s=new Xe,[o,r,n,a]=function(e){let t=e[0].x,i=t,s=e[0].y,o=s;for(let r=1;r<e.length;r++)e[r].x<t?t=e[r].x:e[r].x>i&&(i=e[r].x),e[r].y<s?s=e[r].y:e[r].y>o&&(o=e[r].y);return[t,s,i-t,o-s]}(i),l=e=>[(e.x-o)/n,(e.y-r)/a],[u,_,f,x]=i.map(l),b=function(e,t,i,s,o,r,n,a){const l=ql(0,0,1,0,1,1,0,1),c=ql(e,t,i,s,o,r,n,a),h=it([],c);return st(l,l,h)}(u[0],u[1],_[0],_[1],f[0],f[1],x[0],x[1]);this.elevatedGlobePerspectiveTransform=Zl(u[0],u[1],_[0],_[1],f[0],f[1],x[0],x[1]);const w=(e,t)=>{p.push(e.lng);const i=Math.round((e.lng-m)/v*ae),o=Math.round((e.lat-g)/y*ae),r=l(t),n=Qe([],[r[0],r[1],1],b),a=Math.round(n[0]/n[2]*ae),c=Math.round(n[1]/n[2]*ae);s.emplaceBack(i,o,a,c)},T=i[3].x-i[0].x,E=i[3].y-i[0].y,I=i[2].x-i[1].x,S=i[2].y-i[1].y;for(let e=0;e<d;e++){const s=e/c,o=[i[0].x+s*T,i[0].y+s*E],r=[i[1].x+s*I,i[1].y+s*S],n=r[0]-o[0],a=r[1]-o[1];for(let e=0;e<h;e++){const i=e/c,s={x:o[0]+n*i,y:o[1]+a*i};w(t.projection.unproject(s.x,s.y),s)}}this.elevatedGlobeVertexBuffer=e.createVertexBuffer(s,Gl.members)}{this.maxLongitudeTriangleSize=0;let t=[],i=new Ke;const s=(e,s,o)=>{i.emplaceBack(e,s,o);const r=p[e],n=p[s],a=p[o],l=Math.min(Math.min(r,n),a),c=Math.max(Math.max(r,n),a)-l;c>this.maxLongitudeTriangleSize&&(this.maxLongitudeTriangleSize=c),t.push(l+c/2)};for(let e=0;e<c;e++)for(let t=0;t<c;t++){const i=e*h+t,o=i+1,r=i+h,n=r+1;s(i,r,o),s(o,r,n)}[t,i]=function(e,t){const i=Array.from({length:e.length},(e,t)=>t);i.sort((t,i)=>e[t]-e[i]);const s=[],o=new Ke;for(let r=0;r<i.length;r++){const n=i[r];s.push(e[n]);const a=3*n,l=a+1;o.emplaceBack(t.uint16[a],t.uint16[l],t.uint16[l+1])}return[s,o]}(t,i),this.elevatedGlobeTrianglesCenterLongitudes=t,this.elevatedGlobeIndexBuffer=e.createIndexBuffer(i)}this.elevatedGlobeSegments=Ye.simpleSegment(0,0,u,_),this.elevatedGlobeGridMatrix=new Float32Array([0,v/ae,0,y/ae,0,0,g,m,0])}prepare(){const e=0!==Object.keys(this.tiles).length;if(this.tileID&&!e)return;const t=this.map.painter.context,i=t.gl;!this._dirty||this.texture instanceof Ze||(this.texture?this.texture.update(this.image):(this.texture=new k(t,this.image,i.RGBA8),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE)),this._dirty=!1),e&&this._prepareData(t)}loadTile(e,t){this.tileID&&this.tileID.equals(e.tileID.canonical)?(this.tiles[String(e.tileID.wrap)]=e,e.buckets={},t(null)):(e.state="errored",t(null))}serialize(){return{type:"image",url:this.options.url,coordinates:this.coordinates}}hasTransition(){return!1}getSegmentsForLongitude(e){const t=this.elevatedGlobeSegments;if(!this.elevatedGlobeTrianglesCenterLongitudes||!t)return null;const i=this.elevatedGlobeTrianglesCenterLongitudes;let s=(o=e+180)+360*Math.round((i[0]-o)/360);var o;const r=new Ye,n=(e,i)=>{r.segments.push({vertexOffset:0,primitiveOffset:e,vertexLength:t.segments[0].vertexLength,primitiveLength:i,sortKey:void 0,vaos:{}})},a=.51*this.maxLongitudeTriangleSize;if(Math.abs(i[0]-s)<=a){const e=et(i,0,i.length,s+a);return e===i.length||n(e,tt(i,e+1,i.length,s+360-a)-e),r}s<i[0]&&(s+=360);const l=tt(i,0,i.length,s-a);if(l===i.length)return n(0,i.length),r;n(0,l-0);const c=et(i,l+1,i.length,s+a);return c!==i.length&&n(c,i.length-c),r}}const $l={vector:class extends A{constructor(e,t,i,s){if(super(),this.id=e,this.dispatcher=i,this.type="vector",this.provider=t.provider,this.minzoom=0,this.maxzoom=22,this.scheme="xyz",this.tileSize=512,this.reparseOverscaled=!0,this.isTileClipped=!0,this._loaded=!1,Object.assign(this,Me(t,["url","scheme","tileSize","promoteId"])),this._options={type:"vector",...t},this._stableIdField=Vl(this.url),this._collectResourceTiming=!!t.collectResourceTiming,512!==this.tileSize)throw new Error("vector tile sources must have a tileSize of 512");this.setEventedParent(s),this._tileWorkers={},this._deduped=new Oe}load(e){this._loaded=!1,this.fire(new M("dataloading",{dataType:"source"}));const t=Array.isArray(this.map._language)?this.map._language.join():this.map._language,i=this.map.getWorldview(),s=(s,o)=>{this._tileJSONRequest=null,this._loaded=!0,s?(t&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${t}`),i&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${i}`),this.fire(new P(s))):o&&(this._setTileJSON(o),Il.updateCrossSourceElevationGate&&this.map.style&&Il.updateCrossSourceElevationGate(this.map.style),en(o.tiles,this.map._requestManager._customAccessToken),this.fire(new M("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new M("data",{dataType:"source",sourceDataType:"content"}))),e&&e(s)};this.provider=this._options.provider;const o=ze(this._options);return o instanceof Error?(this._loaded=!0,this.fire(new P(o)),void(e&&e())):this.provider&&!o?(this._loaded=!0,this.fire(new P(new Error(`TileProvider "${this.provider}" is not registered`))),void(e&&e())):void(this._tileJSONRequest=o?this.loadTileJSONWithProvider(o,s):Fe(this._options,this.map._requestManager,t,i,s))}loadTileJSONWithProvider(e,t){this.provider=e.name;const i=new AbortController;return(async()=>{const{request:s,options:o}=await Ue(this._options,this.map._requestManager,i.signal);if(i.signal.aborted)return;const r=await this.dispatcher.send("loadTileProvider",{name:e.name,url:e.url,source:this.id,scope:this.scope,type:this.type,options:o,request:s},{signal:i.signal});if(i.signal.aborted)return;const n=r?r.find(e=>null!=e):null,a=Ve(this._options,n,this.map._requestManager);a instanceof Error?t(a):t(null,a)})().catch(e=>{i.signal.aborted||t(e)}),{cancel:()=>i.abort()}}_setTileJSON(e){if(Object.assign(this,e),this.hasWorldviews=!!e.worldview_options,e.worldview_default&&(this.worldviewDefault=e.worldview_default),e.vector_layers){this.vectorLayers=e.vector_layers,this.vectorLayerIds=[],this.localizableLayerIds=new Set;for(const t of e.vector_layers)this.vectorLayerIds.push(t.id),e.worldview&&e.worldview[t.source]&&this.localizableLayerIds.add(t.id)}this.tileBounds=new Ul(e)}loaded(){return this._loaded}hasTile(e){return!this.tileBounds||this.tileBounds.contains(e.canonical)}onAdd(e){this.map=e,this.load()}reload(){this.cancelTileJSONRequest();const e=C(this.id,this.scope);this.load(()=>this.map.style.clearSource(e))}setTiles(e){return this._options.tiles=e,this.reload(),this}setUrl(e){return this.url=e,this._options.url=e,this._stableIdField=Vl(e),this.reload(),this}setMinzoom(e){return this._options.minzoom=e,this.reload(),this}setMaxzoom(e){return this._options.maxzoom=e,this.reload(),this}onRemove(e){this.cancelTileJSONRequest()}serialize(){return{...this._options}}async loadTile(e,t){const i=e.tileID.canonical.url(this.tiles,this.scheme),s=this.map._requestManager.normalizeTileURL(i),o=!e.actor||"expired"===e.state;if(!o&&"loading"===e.state)return void(e.reloadCallback=t);o&&(e.actor=this._tileWorkers[s]=this._tileWorkers[s]||this.dispatcher.getActor());const r=new AbortController;e.request=r;try{const n=await this.map._requestManager.transformRequest(s,x.Tile,r.signal);if(r.signal.aborted)return t(null);this.dispatchTile(e,s,i,n,r,o,t)}catch(e){if(r.signal.aborted)return t(null);t(e)}}dispatchTile(e,t,i,s,o,n,a){const l=this.map.style?this.map.style.getLut(this.scope):null,c=l?{image:l.image.clone()}:null,h=!(!this.map.style||!this.map.style._crossSourceElevationActive),d=!(!this.map.style||!h&&Il.loaded),u={request:s,data:void 0,uid:e.uid,tileID:e.tileID,tileZoom:e.tileZoom,zoom:e.tileID.overscaledZ,maxZoom:this.maxzoom,lut:c,tileSize:this.tileSize*e.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,pixelRatio:T.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,showElevationIdDebug:!!this.map.painter&&this.map.painter._debugParams.showElevationIdDebug,promoteId:this.promoteId,stableIdField:this._stableIdField,renderSourceType:e.renderSourceType,frcCoverage:(()=>{const t=this.map.painter,i=t?t.frcCoverageFadeRange:null;if(null==i)return null;const s=t?t.frcCoverageSnapshot:null,o=this.map.transform.zoom<i[0],r=s?s.getTileOrParent(e.tileID.canonical):null,n=e.tileID.overscaledZ>=Math.ceil(i[1]),a=s&&n?s.getFullCoverageMask(e.tileID.canonical):null;return{frcMask:n?a??null:null,resolved:o||null!=s,polygons:r&&0!==r.frcMask?r.polygons:null,tileZoom:r&&0!==r.frcMask?r.tileId.z:null,sourceLayers:t?t.frcCoverageSourceLayers:["road","structure"]}})(),terrainEnabled:el(this.map.style,this.map.transform),crossSourceElevationEnabled:d,elevation:Il.buildElevationRequestParams?Il.buildElevationRequestParams(this.map,e,h):null,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:e.isExtraShadowCaster,tessellationStep:this.map._tessellationStep,scaleFactor:this.map.getScaleFactor(),worldview:this.map.getWorldview()||this.worldviewDefault,indoor:this.map.getIndoorTileOptions(this.id,this.scope)};if(this.hasWorldviews&&r(i)&&(u.localizableLayerIds=this.localizableLayerIds),u.request.collectResourceTiming=this._collectResourceTiming,n)if(this.dispatcher.ready||this.provider)e.request=e.actor.sendCancelable("loadTile",u,{},_.bind(this));else{const t=ke.call({deduped:this._deduped},u,(t,i)=>{e.aborted||(t||!i?_.call(this,t):(u.data={rawData:i.rawData.slice(0),headers:i.headers},e.actor&&(e.request=e.actor.sendCancelable("loadTile",u,{},_.bind(this)))))},!0);o.signal.addEventListener("abort",t,{once:!0})}else e.request=e.actor.sendCancelable("reloadTile",u,{},_.bind(this));function _(t,i){if(delete e.request,e.aborted)return a(null);if(t)return a(t);i&&i.resourceTiming&&(e.resourceTiming=i.resourceTiming),this.map._refreshExpiredTiles&&i&&e.setExpiryData(Be(i.headers));const s=i&&i.containsHdExt&&!Il.loaded,o=i&&i.containsStandardExt&&!ue.loaded;if(s||o){const e=[];return s&&e.push(Dl()),o&&e.push(Cl()),void Promise.all(e).then(()=>r.call(this),()=>r.call(this))}function r(){return e.aborted?a(null):i&&i.containsHdExt&&!Il.loaded?a(new Error("HD module failed to load")):i&&i.containsStandardExt&&!ue.loaded?a(new Error("Standard module failed to load")):(e.loadVectorData(i,this.map.painter),Ne(this.dispatcher),a(null,i),void(e.reloadCallback&&(this.loadTile(e,e.reloadCallback),e.reloadCallback=null)))}r.call(this)}}abortTile(e){e.request&&(e.request.abort(),delete e.request),e.actor&&e.actor.notify("abortTile",{uid:e.uid,type:this.type,source:this.id,scope:this.scope})}unloadTile(e,t){e.actor&&e.actor.notify("removeTile",{uid:e.uid,type:this.type,source:this.id,scope:this.scope}),e.destroy()}hasTransition(){return!1}afterUpdate(){this._tileWorkers={}}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}},raster:jl,"raster-dem":class extends jl{constructor(e,t,i,s){super(e,t,i,s),this.type="raster-dem",this.maxzoom=22,this._options={type:"raster-dem",...t},this.encoding=t.encoding||"mapbox"}loadTileJSONWithProvider(e,t){this.provider=e.name;const i=new AbortController;return(async()=>{const{request:s,options:o}=await Ue(this._options,this.map._requestManager,i.signal);if(i.signal.aborted)return;const r=await this.dispatcher.send("loadTileProvider",{name:e.name,url:e.url,source:this.id,scope:this.scope,type:this.type,options:o,request:s},{signal:i.signal});if(i.signal.aborted)return;const n=r?r.find(e=>null!=e):null,a=Ve(this._options,n,this.map._requestManager);a instanceof Error?t(a):t(null,a)})().catch(e=>{i.signal.aborted||t(e)}),{cancel:()=>i.abort()}}async loadTile(e,t){if(e.actor&&"expired"!==e.state)return;const i=this.map._requestManager.normalizeTileURL(e.tileID.canonical.url(this.tiles,this.scheme),!1,this.tileSize);e.actor=this.dispatcher.getActor();const s=new AbortController;e.request=s;try{const o=await this.map._requestManager.transformRequest(i,x.Tile,s.signal);if(s.signal.aborted)return t(null);e.request=e.actor.sendCancelable("loadTile",{uid:e.uid,tileID:e.tileID,source:this.id,type:this.type,scope:this.scope,request:o,encoding:this.encoding},{},function(i,s){return delete e.request,e.aborted?t(null):i?(e.state="errored",t(i)):(s&&(this.map._refreshExpiredTiles&&e.setExpiryData(Be(s.headers)),s.borderReady||e.neighboringTiles||(e.neighboringTiles=this._getNeighboringTiles(e.tileID)),e.dem=s.dem,e.dem.onDeserialize(),e.needsHillshadePrepare=!0,e.needsDEMTextureUpload=!0),e.state="loaded",void t(null))}.bind(this))}catch(i){if(s.signal.aborted)return t(null);e.state="errored",t(i)}}abortTile(e,t){e.request&&(e.request.abort(),delete e.request),e.actor&&e.actor.notify("abortTile",{uid:e.uid,type:this.type,source:this.id,scope:this.scope}),t&&t()}_getNeighboringTiles(e){const t=e.canonical,i=Math.pow(2,t.z),s=(t.x-1+i)%i,o=0===t.x?e.wrap-1:e.wrap,r=(t.x+1+i)%i,n=t.x+1===i?e.wrap+1:e.wrap,a={};return a[new Ge(e.overscaledZ,o,t.z,s,t.y).key]={backfilled:!1},a[new Ge(e.overscaledZ,n,t.z,r,t.y).key]={backfilled:!1},t.y>0&&(a[new Ge(e.overscaledZ,o,t.z,s,t.y-1).key]={backfilled:!1},a[new Ge(e.overscaledZ,e.wrap,t.z,t.x,t.y-1).key]={backfilled:!1},a[new Ge(e.overscaledZ,n,t.z,r,t.y-1).key]={backfilled:!1}),t.y+1<i&&(a[new Ge(e.overscaledZ,o,t.z,s,t.y+1).key]={backfilled:!1},a[new Ge(e.overscaledZ,e.wrap,t.z,t.x,t.y+1).key]={backfilled:!1},a[new Ge(e.overscaledZ,n,t.z,r,t.y+1).key]={backfilled:!1}),a}},geojson:class extends A{constructor(e,t,i,s){super(),this.id=e,this.type="geojson",this.minzoom=0,this.maxzoom=18,this.tileSize=512,this.isTileClipped=!0,this.reparseOverscaled=!0,this._loaded=!1,this.actor=i.getActor(),this.setEventedParent(s),this._data=t.data,this._options={...t},this._collectResourceTiming=t.collectResourceTiming,void 0!==t.maxzoom&&(this.maxzoom=t.maxzoom),void 0!==t.minzoom&&(this.minzoom=t.minzoom),t.type&&(this.type=t.type),t.attribution&&(this.attribution=t.attribution),this.promoteId=t.promoteId;const o=ae/this.tileSize;this.workerOptions={source:this.id,scope:this.scope,cluster:t.cluster||!1,geojsonVtOptions:{buffer:(void 0!==t.buffer?t.buffer:128)*o,tolerance:(void 0!==t.tolerance?t.tolerance:.375)*o,extent:ae,maxZoom:this.maxzoom,lineMetrics:t.lineMetrics||!1,generateId:t.generateId||!1},superclusterOptions:{maxZoom:void 0!==t.clusterMaxZoom?t.clusterMaxZoom:this.maxzoom-1,minPoints:Math.max(2,t.clusterMinPoints||2),extent:ae,radius:(void 0!==t.clusterRadius?t.clusterRadius:50)*o,log:!1,generateId:t.generateId||!1},clusterProperties:t.clusterProperties,filter:t.filter,dynamic:t.dynamic,...t.workerOptions}}onAdd(e){this.map=e,this.setData(this._data)}setData(e){return this._data=e,this._updateWorkerData(),this}updateData(e){if(!this._options.dynamic)return this.fire(new P(new Error("Can't call updateData on a GeoJSON source with dynamic set to false.")));if("string"!=typeof e&&("Feature"===e.type&&(e={type:"FeatureCollection",features:[e]}),"FeatureCollection"!==e.type))return this.fire(new P(new Error("Data to update should be a feature or a feature collection.")));if(this._coalesce&&"string"!=typeof e&&"string"!=typeof this._data&&"FeatureCollection"===this._data.type){const t=new Map;for(const e of this._data.features)t.set(e.id,e);for(const i of e.features)t.set(i.id,i);this._data.features=[...t.values()]}else this._data=e;return this._updateWorkerData(!0),this}getClusterExpansionZoom(e,t){return this.actor.send("geojson.getClusterExpansionZoom",{clusterId:e,source:this.id,scope:this.scope}).then(e=>t(null,e)).catch(e=>t(e)),this}getClusterChildren(e,t){return this.actor.send("geojson.getClusterChildren",{clusterId:e,source:this.id,scope:this.scope}).then(e=>t(null,e)).catch(e=>t(e)),this}getClusterLeaves(e,t,i,s){return this.actor.send("geojson.getClusterLeaves",{source:this.id,scope:this.scope,clusterId:e,limit:t,offset:i}).then(e=>s(null,e)).catch(e=>s(e)),this}async _updateWorkerData(e=!1){if(this._pendingLoad)return void(this._coalesce=!0);this.fire(new M("dataloading",{dataType:"source"})),this._loaded=!1;const t={append:e,...this.workerOptions};t.scope=this.scope;const i=this._data,s=new AbortController;this._pendingLoad=s;try{if("string"==typeof i){if(t.request=await this.map._requestManager.transformRequest(T.resolveURL(i),x.Source,s.signal),s.signal.aborted)return this._pendingLoad=null,void(this._coalesce=!1);t.request.collectResourceTiming=this._collectResourceTiming}else t.data=JSON.stringify(i);const o=await this.actor.send(`${this.type}.loadData`,t,{signal:s.signal});this._loaded=!0,this._pendingLoad=null;const r={dataType:"source",sourceDataType:this._metadataFired?"content":"metadata"};this._collectResourceTiming&&o&&o.resourceTiming&&o.resourceTiming[this.id]&&(r.resourceTiming=o.resourceTiming[this.id]),e&&(this._partialReload=!0),this.fire(new M("data",r)),this._partialReload=!1,this._metadataFired=!0}catch(e){if(s.signal.aborted)return this._pendingLoad=null,void(this._coalesce=!1);this._loaded=!0,this._pendingLoad=null,this.fire(new P(e))}this._coalesce&&(this._updateWorkerData(e),this._coalesce=!1)}loaded(){return this._loaded}reload(){const e=C(this.id,this.scope);this.map.style.clearSource(e),this._updateWorkerData()}loadTile(e,t){const i=e.actor?"reloadTile":"loadTile";e.actor=this.actor;const s=this.map.style?this.map.style.getLut(this.scope):null,o=s?{image:s.image.clone()}:null,r=this._partialReload,n={type:this.type,uid:e.uid,tileID:e.tileID,tileZoom:e.tileZoom,zoom:e.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,lut:o,scope:this.scope,pixelRatio:T.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,showElevationIdDebug:!!this.map.painter&&this.map.painter._debugParams.showElevationIdDebug,promoteId:this.promoteId,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:e.isExtraShadowCaster,scaleFactor:this.map.getScaleFactor(),partial:r,worldview:this.map.getWorldview(),indoor:this.map.getIndoorTileOptions(this.id,this.scope)};e.request=this.actor.sendCancelable(i,n,{},(s,o)=>{if(r&&!o)return e.state="loaded",t(null);if(delete e.request,e.destroy(!1),e.aborted)return t(null);if(s)return t(s);if(o&&o.containsHdExt&&!Il.loaded){const s=()=>e.aborted?t(null):Il.loaded?(e.loadVectorData(o,this.map.painter,"reloadTile"===i),void t(null)):t(new Error("HD module failed to load"));return void Dl().then(s,s)}e.loadVectorData(o,this.map.painter,"reloadTile"===i),t(null)})}abortTile(e){e.request&&(e.request.abort(),delete e.request),e.aborted=!0}unloadTile(e,t){this.actor.notify("removeTile",{uid:e.uid,type:this.type,source:this.id,scope:this.scope}),e.destroy()}onRemove(e){this._pendingLoad&&this._pendingLoad.abort()}serialize(){return{...this._options,type:this.type,data:this._data}}hasTransition(){return!1}},video:class extends Hl{constructor(e,t,i,s){super(e,t,i,s),this.roundZoom=!0,this.type="video",this.options=t}async load(){this._loaded=!1;const e=this.options,t=new AbortController;this._imageRequest=t;try{const i=await Promise.all(e.urls.map(async e=>(await this.map._requestManager.transformRequest(e,x.Source,t.signal)).url));if(t.signal.aborted)return;this.urls=i;const s=await ot(i);if(t.signal.aborted)return;this._imageRequest=null,this.video=s,this.video.loop=!0,this.video.setAttribute("playsinline",""),this.video.addEventListener("playing",()=>{this.map.triggerRepaint()}),this.map&&this.video.play(),this._finishLoading()}catch(e){if(t.signal.aborted)return;this.fire(new P(e))}finally{this._loaded=!0}}pause(){this.video&&this.video.pause()}play(){this.video&&this.video.play()}seek(e){if(this.video){const t=this.video.seekable;e<t.start(0)||e>t.end(0)?this.fire(new P(new Da(`sources.${this.id}`,null,`Playback for this video can be set only between the ${t.start(0)} and ${t.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,t=e.gl;this.texture?this.video.paused||(this.texture.bind(t.LINEAR,t.CLAMP_TO_EDGE),t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,this.video)):(this.texture=new k(e,this.video,t.RGBA8),this.texture.bind(t.LINEAR,t.CLAMP_TO_EDGE),this.width=this.video.videoWidth,this.height=this.video.videoHeight),this._prepareData(e)}serialize(){return{type:"video",urls:this.options.urls,coordinates:this.coordinates}}hasTransition(){return this.video&&!this.video.paused}},image:Hl,canvas:class extends Hl{constructor(e,t,i,s){super(e,t,i,s),t.coordinates?Array.isArray(t.coordinates)&&4===t.coordinates.length&&!t.coordinates.some(e=>!Array.isArray(e)||2!==e.length||e.some(e=>"number"!=typeof e))||this.fire(new P(new Da(`sources.${e}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new P(new Da(`sources.${e}`,null,'missing required property "coordinates"'))),t.animate&&"boolean"!=typeof t.animate&&this.fire(new P(new Da(`sources.${e}`,null,'optional "animate" property must be a boolean value'))),t.canvas?"string"==typeof t.canvas||t.canvas instanceof HTMLCanvasElement||this.fire(new P(new Da(`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 P(new Da(`sources.${e}`,null,'missing required property "canvas"'))),this.options=t,this.animate=void 0===t.animate||t.animate}async load(){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 P(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(e){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 t=this.map.painter.context;this.texture?!e&&!this._playing||this.texture instanceof Ze||this.texture.update(this.canvas,{premultiply:!0}):this.texture=new k(t,this.canvas,t.gl.RGBA8,{premultiply:!0}),this._prepareData(t)}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}},custom:class extends A{constructor(e,t,i,s){super(),this.id=e,this.type="custom",this._dataType="raster",this._dispatcher=i,this._implementation=t,this.setEventedParent(s),this.scheme="xyz",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this._loaded=!1,this.roundZoom=!0,this._implementation||this.fire(new P(new Error(`Missing implementation for ${this.id} custom source`))),this._implementation.loadTile||this.fire(new P(new Error(`Missing loadTile implementation for ${this.id} custom source`)));const o=t;o.update=this._update.bind(this),o.clearTiles=this._clearTiles.bind(this),o.coveringTiles=this._coveringTiles.bind(this),Object.assign(this,Me(t,["dataType","scheme","minzoom","maxzoom","tileSize","attribution","minTileCacheSize","maxTileCacheSize"])),this._implementation.bounds&&(this.tileBounds=new Ul({bounds:this._implementation.bounds,minzoom:this.minzoom,maxzoom:this.maxzoom}))}serialize(){return Me(this,["type","scheme","minzoom","maxzoom","tileSize","attribution"])}load(){this._loaded=!0,this.fire(new M("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new M("data",{dataType:"source",sourceDataType:"content"}))}loaded(){return this._loaded}onAdd(e){this.map=e,this._loaded=!1,this.fire(new M("dataloading",{dataType:"source"})),this._implementation.onAdd&&this._implementation.onAdd(e),this.load()}onRemove(e){this._implementation.onRemove&&this._implementation.onRemove(e)}hasTile(e){if(this._implementation.hasTile){const{x:t,y:i,z:s}=e.canonical;return this._implementation.hasTile({x:t,y:i,z:s})}return!this.tileBounds||this.tileBounds.contains(e.canonical)}async loadTile(e,t){const{x:i,y:s,z:o}=e.tileID.canonical,r=new AbortController;e.request=r;try{const n=await this._implementation.loadTile({x:i,y:s,z:o},{signal:r.signal});if(delete e.request,e.aborted)return e.state="unloaded",t(null);if(void 0===n)return e.state="errored",t(null);if(null===n)return this.loadTileData(e,{width:this.tileSize,height:this.tileSize,data:null}),e.state="loaded",t(null);if(!function(e){return e instanceof ImageData||e instanceof HTMLCanvasElement||e instanceof ImageBitmap||e instanceof HTMLImageElement}(n))return e.state="errored",t(new Error(`Can't infer data type for ${this.id}, only raster data supported at the moment`));this.loadTileData(e,n),e.state="loaded",t(null)}catch(i){if(r.signal.aborted)return;e.state="errored",t(i)}}loadTileData(e,t){e.setTexture(t,this.map.painter)}unloadTile(e,t){if(e.texture&&e.texture instanceof k?(e.destroy(!1),e.texture&&e.texture instanceof k&&this.map.painter.saveTileTexture(e.texture)):e.destroy(),this._implementation.unloadTile){const{x:t,y:i,z:s}=e.tileID.canonical;this._implementation.unloadTile({x:t,y:i,z:s})}t&&t()}abortTile(e,t){e.request&&(e.request.abort(),delete e.request),t&&t()}hasTransition(){return!1}_coveringTiles(){return this.map.transform.coveringTiles({tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,roundZoom:this.roundZoom}).map(e=>({x:e.canonical.x,y:e.canonical.y,z:e.canonical.z}))}_clearTiles(){const e=C(this.id,this.scope);this.map.style.clearSource(e)}_update(){this.fire(new M("data",{dataType:"source",sourceDataType:"content"}))}}},Xl=function(e,t,i,s){const o=Yl(t.type);if(!o)throw new Error(`Unknown source type "${t.type}"`);const r=new o(e,t,i,s);if(r.id!==e)throw new Error(`Expected Source id to be ${e} instead of ${r.id}`);return rt(["load","abort","unload","serialize","prepare"],r),r},Yl=function(e){return Object.hasOwn($l,e)?$l[e]:void 0},Kl={model:()=>Cl().then(()=>ue.ModelSource),"batched-model":()=>Cl().then(()=>ue.Tiled3dModelSource),"raster-array":()=>Ol().then(()=>Pl.RasterArrayTileSource)};class Jl extends A{constructor(e,t,i,s){super(),this.id=e,this.type=t.type,this._options={...t},this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.setEventedParent(s)}hasTransition(){return!1}startLoad(){const e=this._loader;this._loader=void 0,e&&e()}loaded(){return void 0!==this._loader}onAdd(e){}onRemove(e){}loadTile(e,t){}serialize(){return this._options}_setOption(e,t){return this._options[e]=t,this}}class Ql extends Jl{setTiles(e){return this._setOption("tiles",e)}setUrl(e){return this._setOption("url",e)}setMinzoom(e){return this._setOption("minzoom",e)}setMaxzoom(e){return this._setOption("maxzoom",e)}}class ec extends Jl{getModels(){return[]}setModels(e){return this._setOption("models",e)}}function tc(e,t,i=""){return`${i}:${t.id||""}:${t.layer.id}:${function(e){if("layerId"in e)return`layer:${e.layerId}`;{const{featuresetId:t,importId:i}=e;return`featureset:${t}${i?`:import:${i}`:""}`}}(e.target)}`}function ic(e,t,i,s=""){if(e.uniqueFeatureID){const o=tc(e,t,s);if(i.has(o))return!0;i.add(o)}return!1}function sc(e,t,i,s,o=!1,r=void 0){const n=t.sourceCache.transform,a=t.sourceCache.tilesIn(e,t.has3DLayers,o);a.sort(nc);const l=[];for(const e of a){const a=e.tile.queryRenderedFeatures(t,e,i,s,n,o,r);Object.keys(a).length&&l.push({wrappedTileID:e.tile.tileID.wrapped().key,queryResults:a})}for(const i in t.layers){const o=t.layers[i];if(o.styleLayer){const i=o.styleLayer.queryRenderedFeatures(e,t.sourceCache,s);Object.keys(i).length&&l.push({wrappedTileID:0,queryResults:i})}}return 0===l.length?{}:function(e){const t={},i={};for(const s of e){const e=s.queryResults,o=s.wrappedTileID,r=i[o]=i[o]||{};for(const i in e){const s=e[i],o=r[i]=r[i]||{},n=t[i]=t[i]||[];for(const e of s)o[e.featureIndex]||(o[e.featureIndex]=!0,n.push(e))}}return t}(l)}function oc(e,t,i,s,o,r){const n={},a=s.queryRenderedSymbols(e),l=[];for(const e of Object.keys(a).map(Number))l.push(o[e]);l.sort(nc);for(const e of l){const s=e.featureIndex.lookupSymbolFeatures(a[e.bucketInstanceId],e.bucketIndex,e.sourceLayerIndex,t,i,r);for(const t in s){const i=n[t]=n[t]||[],o=s[t];o.sort((t,i)=>{const s=e.featureSortOrder;if(s){const e=s.indexOf(t.featureIndex);return s.indexOf(i.featureIndex)-e}return i.featureIndex-t.featureIndex});for(const e of o)i.push(e)}}return n}function rc(e,t){const i=e.getRenderableIds().map(t=>e.getTileByID(t)),s=[],o={};for(let e=0;e<i.length;e++){const r=i[e],n=r.tileID.canonical.key;o[n]||(o[n]=!0,r.querySourceFeatures(s,t))}return s}function nc(e,t){const i=e.tileID,s=t.tileID;return i.overscaledZ-s.overscaledZ||i.canonical.y-s.canonical.y||i.wrap-s.wrap||i.canonical.x-s.canonical.x}function ac(e,t){const i={};if(!t)return i;for(const s of e){const e=s.layerIds.map(e=>t.getLayer(e)).filter(Boolean);if(0!==e.length){s.layers=e,s.stateDependentLayerIds&&(s.stateDependentLayers=s.stateDependentLayerIds.map(t=>e.filter(e=>e.id===t)[0])),s.updateExpressions&&s.updateExpressions(e);for(const t of e)i[t.fqid]=s}}return i}const lc=32,cc=33,hc=new Uint16Array(8184);for(let e=0;e<2046;e++){let t=e+2,i=0,s=0,o=0,r=0,n=0,a=0;for(1&t?o=r=n=lc:i=s=a=lc;(t>>=1)>1;){const e=i+o>>1,l=s+r>>1;1&t?(o=i,r=s,i=n,s=a):(i=o,s=r,o=n,r=a),n=e,a=l}const l=4*e;hc[l+0]=i,hc[l+1]=s,hc[l+2]=o,hc[l+3]=r}const dc=new Uint16Array(2178),uc=new Uint8Array(1089),_c=new Uint16Array(1089);function pc(e){return 0===e?-.03125:32===e?.03125:0}const fc=(()=>({type:2,extent:ae,loadGeometry:()=>[[new m(0,0),new m(ae+1,0),new m(ae+1,ae+1),new m(0,ae+1),new m(0,0)]]}))();let mc,gc,vc=0;class yc{constructor(e,t,i,s,o,r){this.tileID=e,this.uid=ce(),this.uses=0,this.tileSize=t,this.tileZoom=i,this.dashIdealZ=e.overscaledZ,this.buckets={},this.expirationTime=null,this.queryPadding=0,this.hasSymbolBuckets=!1,this.hasTunnelGeometry=!1,this.dependencies={},this.isRaster=o,s&&s.style&&(this._lastUpdatedBrightness=s.style.getBrightness()),this._lastAvailableImagesCount=0,this._firstPrepareComplete=!1,this._queryPaddingPaintVersions={},this.expiredRequestCount=0,this.state="loading",s&&s.transform&&(this.projection=s.transform.projection),this.worldview=r,this._hasAppearances=null}registerFadeDuration(e){const t=e+this.timeAdded;t<T.now()||void 0!==this.fadeEndTime&&t<this.fadeEndTime||(this.fadeEndTime=t)}wasRequested(){return"errored"===this.state||"loaded"===this.state||"reloading"===this.state}get tileTransform(){return this._tileTransform||(this._tileTransform=He(this.tileID.canonical,this.projection)),this._tileTransform}loadVectorData(e,t,i){if(this.unloadVectorData(),this.state="loaded",e){e.featureIndex&&(this.latestFeatureIndex=e.featureIndex,e.rawTileData?(this.latestRawTileData=e.rawTileData,this.latestFeatureIndex.rawTileData=e.rawTileData):this.latestRawTileData&&(this.latestFeatureIndex.rawTileData=this.latestRawTileData)),this.collisionBoxArray=e.collisionBoxArray,this.buckets=ac(e.buckets,t.style),e.frcCoveragePolygons&&e.frcCoveragePolygons.length>0&&(this.frcCoveragePolygons=e.frcCoveragePolygons),this.hasDeferredRoadStructure=!!e.hasDeferredRoadStructure,void 0!==e.parsedElevationFeatures&&(this.parsedElevationFeatures=e.parsedElevationFeatures,this.parsedElevationGeneration=++vc),this.hasDeferredElevationFeatures=!!e.hasDeferredElevationFeatures,this.hasSymbolBuckets=!1,this.hasTunnelGeometry=!!e.hasTunnelGeometry;for(const e in this.buckets){const t=this.buckets[e];if(t instanceof ct){if(this.hasSymbolBuckets=!0,!i)break;t.justReloaded=!0}}this.queryPadding=0,this._queryPaddingPaintVersions={};for(const e in this.buckets){const i=this.buckets[e];i instanceof ct&&!i.bucketInstanceId&&(i.bucketInstanceId=ct.maxBucketInstanceId++);const s=t.style.getOwnLayer(e);if(!s)continue;const o=s.queryRadius(i)||0;this.queryPadding=Math.max(this.queryPadding,o),this._queryPaddingPaintVersions[e]=s.paintVersion}e.imageAtlas&&(this.imageAtlas=t.style.imageManager.imageAtlasCache.getOrCache(e.imageAtlas)),e.glyphAtlasImage&&(this.glyphAtlasImage=e.glyphAtlasImage),e.lineAtlas&&(this.lineAtlas=e.lineAtlas),this._lastUpdatedBrightness=e.brightness}else this.collisionBoxArray=new lt}resetPlacementVisibility(){for(const e in this.buckets)this.buckets[e].resetPlacementVisibility?.()}unloadVectorData(){if(this.hasData()){for(const e in this.buckets)this.buckets[e].destroy();this.buckets={},this.imageAtlas&&(this.imageAtlas=null),this.lineAtlas&&(this.lineAtlas=null),this.imageAtlasTexture&&(this.imageAtlasTexture=null),this.glyphAtlasTexture&&this.glyphAtlasTexture.destroy(),this.lineAtlasTexture&&this.lineAtlasTexture.destroy(),this._tileBoundsBuffer&&(this._tileBoundsBuffer.destroy(),this._tileBoundsIndexBuffer.destroy(),this._tileBoundsSegments.destroy(),this._tileBoundsBuffer=null),this._tileDebugBuffer&&(this._tileDebugBuffer.destroy(),this._tileDebugSegments.destroy(),this._tileDebugBuffer=null),this._tileDebugIndexBuffer&&(this._tileDebugIndexBuffer.destroy(),this._tileDebugIndexBuffer=null),this._globeTileDebugBorderBuffer&&(this._globeTileDebugBorderBuffer.destroy(),this._globeTileDebugBorderBuffer=null),this._tileDebugTextBuffer&&(this._tileDebugTextBuffer.destroy(),this._tileDebugTextSegments.destroy(),this._tileDebugTextIndexBuffer.destroy(),this._tileDebugTextBuffer=null),this._globeTileDebugTextBuffer&&(this._globeTileDebugTextBuffer.destroy(),this._globeTileDebugTextBuffer=null),this.latestFeatureIndex=null,this.state="unloaded"}}loadModelData(e,t,i){e&&(e.resourceTiming&&(this.resourceTiming=e.resourceTiming),this.buckets={...this.buckets,...ac(e.buckets,t.style)},e.featureIndex&&(this.latestFeatureIndex=e.featureIndex))}getBucket(e){return this.buckets[e.fqid]}upload(e,t){for(const i in this.buckets){const s=this.buckets[i];if(s.uploadPending()){let i={},o=[],r={zoom:0,pitch:0,brightness:0,worldview:""};if(t){if(t.style){o=t.style.listImages();const e=s.layers[0],r=e.sourceLayer||"_geojsonTileLayer",n=t.style.getLayerSourceCache(e);n&&(i=n._state.getState(r,void 0))}r={zoom:t.transform.zoom||0,pitch:t.transform.pitch||0,brightness:t.style.getBrightness()||0,worldview:t.worldview||""}}s.upload(e,this.tileID.canonical,i,o,r)}}const i=e.gl,s=this.imageAtlas;s&&t&&(this.imageAtlasTexture=t.style.imageManager.imageAtlasCache.getTextureForAtlas(s,e,i.RGBA8)),this.glyphAtlasImage&&(this.glyphAtlasTexture=new k(e,this.glyphAtlasImage,i.R8),this.glyphAtlasImage=null),this.lineAtlas&&!this.lineAtlas.uploaded&&(this.lineAtlasTexture=new k(e,this.lineAtlas.image,i.R8),this.lineAtlas.uploaded=!0)}prepare(e,t,i){if(this.imageAtlas&&this.imageAtlasTexture&&t){const s=t.style.getLut(i);this.imageAtlas.patchUpdatedImages(e,this.imageAtlasTexture,i,s)}if(!t||!this.latestFeatureIndex||!this.latestFeatureIndex.rawTileData)return;const s=t.style.getBrightness(),o=t.style.listImages(),r=o.length,n=this._firstPrepareComplete&&r!==this._lastAvailableImagesCount;this._updatePaint(t,o,s,n),null===this._hasAppearances&&(this._hasAppearances=this.hasAppearances(t));const a=this._lastUpdatedBrightness!==s;this._lastAvailableImagesCount=r,this._firstPrepareComplete=!0,(this._lastUpdatedBrightness||s||this._hasAppearances||n)&&(!this._hasAppearances&&!n&&this._lastUpdatedBrightness&&s&&Math.abs(this._lastUpdatedBrightness-s)<.001||(this.updateBuckets(t,a,void 0,n,o),this._lastUpdatedBrightness=s))}_updatePaint(e,t,i,s){const o=e.style;for(const r in this.buckets){const n=this.buckets[r],a=o.getOwnLayer(r);a&&(n instanceof ht&&"line"===a.type?this._updateBinderPaint(e,n,n.uboBinders[a.id],a,t,i,s):n instanceof ct&&"symbol"===a.type&&(this._updateBinderPaint(e,n,n.text.uboBinder,a,t,i,s),this._updateBinderPaint(e,n,n.icon.uboBinder,a,t,i,s)),this._queryPaddingPaintVersions[r]!==a.paintVersion&&(this._queryPaddingPaintVersions[r]=a.paintVersion,this.queryPadding=Math.max(this.queryPadding,a.queryRadius(n)||0)))}}_updateBinderPaint(e,t,i,s,o,r,n){if(!i)return;const a=i.updatePaint(s);if("unchanged"!==a||n){if("features"===a||n){const n=t.layers[0],a=n.sourceLayer||"_geojsonTileLayer",l=e.style.getLayerSourceCache(n),c=l?l._state.getState(a,void 0):{},h=this.latestFeatureIndex.loadVTLayers()[a];i.updateDynamicExpressions(s,h,this.tileID.canonical,o,c,r)}i.upload(e.context)}}evaluateQueryRenderedFeaturePadding(){let e=0;for(const t in this.buckets){const i=this.buckets[t];i.evaluateQueryRenderedFeaturePadding&&(e=Math.max(e,i.evaluateQueryRenderedFeaturePadding()))}return e}queryRenderedFeatures(e,t,i,s,o,r,n){if(!this.latestFeatureIndex||!this.latestFeatureIndex.rawTileData&&!this.latestFeatureIndex.is3DTile)return{};const a=this.evaluateQueryRenderedFeaturePadding(),l=function(e,t){const i=Ct([],[.5*e.width,.5*-e.height,1]);return At(i,i,[1,-1,0]),Ie(i,i,e.calculateProjMatrix(t.toUnwrapped())),Float32Array.from(i)}(o,this.tileID);return this.latestFeatureIndex.query(e,{tilespaceGeometry:t,pixelPosMatrix:l,transform:s,availableImages:i,tileTransform:this.tileTransform,worldview:this.worldview,queryRadius:a,scope:n})}querySourceFeatures(e,t){const i=this.latestFeatureIndex;if(!i||!i.rawTileData)return;const s=i.loadVTLayers(),o=t?t.sourceLayer:"",r=s._geojsonTileLayer||s[o];if(!r)return;const n=dt(t&&t.filter),{z:a,x:l,y:c}=this.tileID.canonical,h={z:a,x:l,y:c};for(let t=0;t<r.length;t++){const s=r.feature(t);if(n.needGeometry){const e=ut(s,!0);if(!n.filter(new X(this.tileID.overscaledZ,{worldview:this.worldview}),e,this.tileID.canonical))continue}else if(!n.filter(new X(this.tileID.overscaledZ,{worldview:this.worldview}),s))continue;const d=i.getId(s,o),u=new _t(s,a,l,c,d);u.tile=h,e.push(u)}}loaded(){return"loaded"===this.state||"errored"===this.state}hasData(){return"loaded"===this.state||"reloading"===this.state||"expired"===this.state}patternsLoaded(){return!!this.imageAtlas&&!!this.imageAtlas.patternPositions.size}setExpiryData(e){const t=this.expirationTime;if(e.cacheControl){const t=pt(e.cacheControl);t["max-age"]&&(this.expirationTime=Date.now()+1e3*t["max-age"])}else e.expires&&(this.expirationTime=new Date(e.expires).getTime());if(this.expirationTime){const e=Date.now();let i=!1;if(this.expirationTime>e)i=!1;else if(t)if(this.expirationTime<t)i=!0;else{const s=this.expirationTime-t;s?this.expirationTime=e+Math.max(s,3e4):i=!0}else i=!0;i?(this.expiredRequestCount++,this.state="expired"):this.expiredRequestCount=0}}getExpiryTimeout(){if(this.expirationTime)return this.expiredRequestCount?1e3*(1<<Math.min(this.expiredRequestCount-1,31)):Math.min(this.expirationTime-Date.now(),Math.pow(2,31)-1)}refreshFeatureState(e,t){if(!this.latestFeatureIndex||!this.latestFeatureIndex.rawTileData&&!this.latestFeatureIndex.is3DTile||!e)return;const i=e.style.listImages();this.updateBuckets(e,!1,t,void 0,i)}hasAppearances(e){for(const t in this.buckets)if(e.style.hasLayer(t)&&this.buckets[t].layers.some(e=>e.appearances&&e.appearances.length>0))return!0;return!1}updateBuckets(e,t,i,s,o){if(!this.latestFeatureIndex)return;if(!e.style)return;const r=o||e.style.listImages(),n=e.style.getBrightness();for(const o in this.buckets){if(!e.style.hasLayer(o))continue;const a=this.buckets[o],l=a.layers[0],c=l.sourceLayer||"_geojsonTileLayer",h=e.style.getLayerSourceCache(l);let d=i&&i[c]||{};h&&!i&&(d=h._state.getState(c,void 0));const u=this.imageAtlas?Object.fromEntries(this.imageAtlas.patternPositions):{},_=Object.keys(d).length>0&&!t;a.hasAppearances=a.layers.some(e=>e.appearances&&e.appearances.length>0);const p=_?a.stateDependentLayers:a.layers,f=_&&0!==a.stateDependentLayers.length;if(f||t||s){const i=this.latestFeatureIndex.loadVTLayers();if(a.update(d,i[c],r,u,p,t,n,this.tileID.canonical),a instanceof ct)a.text.uboBinder&&a.text.uboBinder.upload(e.context),a.icon.uboBinder&&a.icon.uboBinder.upload(e.context);else if(a instanceof ht)for(const{id:t}of a.layers)a.uboBinders[t].upload(e.context)}if(f||t||a.hasAppearances){const t={zoom:e.transform.zoom,pitch:e.transform.pitch,brightness:e.style.getBrightness()||0,worldview:e.worldview},i=a.updateAppearances(this.tileID.canonical,d,r,t,e.imageManager,f);i&&i.hasUboChanges&&a instanceof ct&&(a.text.uboBinder&&a.text.uboBinder.upload(e.context),a.icon.uboBinder&&a.icon.uboBinder.upload(e.context))}(a instanceof ht||a instanceof ft)&&e._terrain&&e._terrain.enabled&&h&&a.uploadPending()&&e._terrain._clearRenderCacheForTile(h.id,this.tileID);const m=e&&e.style&&e.style.getOwnLayer(o);m&&(this.queryPadding=Math.max(this.queryPadding,m.queryRadius(a)||0))}}holdingForFade(){return void 0!==this.symbolFadeHoldUntil}symbolFadeFinished(){return!this.symbolFadeHoldUntil||this.symbolFadeHoldUntil<T.now()}clearFadeHold(){this.symbolFadeHoldUntil=void 0}setHoldDuration(e){this.symbolFadeHoldUntil=T.now()+e}setTexture(e,t){const i=t.context,s=i.gl;this.texture=this.texture||t.getTileTexture(e.width),this.texture&&this.texture instanceof k?this.texture.update(e):(this.texture=new k(i,e,s.RGBA8,{useMipmap:!0}),this.texture.bind(s.LINEAR,s.CLAMP_TO_EDGE))}setDependencies(e,t){const i={};for(const e of t)i[e]=!0;this.dependencies[e]=i}hasDependency(e,t){for(const i of e){const e=this.dependencies[i];if(e)for(const i of t)if(e[i])return!0}return!1}clearQueryDebugViz(){}_makeDebugTileBoundsBuffers(e,t){if(!t||"mercator"===t.name||this._tileDebugBuffer)return;const i=mt(fc,this.tileID.canonical,this.tileTransform)[0],s=new gt,o=new vt;for(let e=0;e<i.length;e++){const{x:t,y:r}=i[e];s.emplaceBack(t,r),o.emplaceBack(e)}o.emplaceBack(0),this._tileDebugIndexBuffer=e.createIndexBuffer(o),this._tileDebugBuffer=e.createVertexBuffer(s,yt.members),this._tileDebugSegments=Ye.simpleSegment(0,0,s.length,o.length)}_makeTileBoundsBuffers(e,t){if(this._tileBoundsBuffer||!t||"mercator"===t.name)return;const i=mt(fc,this.tileID.canonical,this.tileTransform)[0];let s,o;if(this.isRaster){const e=function(e,t){const i=He(e,t),s=Math.pow(2,e.z);for(let o=0;o<cc;o++)for(let r=0;r<cc;r++){const n=nt((e.x+(r+pc(r))/lc)/s),a=at((e.y+(o+pc(o))/lc)/s),l=t.project(n,a),c=o*cc+r;dc[2*c+0]=Math.round((l.x*i.scale-i.x)*ae),dc[2*c+1]=Math.round((l.y*i.scale-i.y)*ae)}uc.fill(0),_c.fill(0);for(let e=2045;e>=0;e--){const t=4*e,i=hc[t+0],s=hc[t+1],o=hc[t+2],r=hc[t+3],n=i+o>>1,a=s+r>>1,l=n+a-s,c=a+i-n,h=s*cc+i,d=r*cc+o,u=a*cc+n,_=Math.hypot((dc[2*h+0]+dc[2*d+0])/2-dc[2*u+0],(dc[2*h+1]+dc[2*d+1])/2-dc[2*u+1])>=16;uc[u]=uc[u]||(_?1:0),e<1022&&(uc[u]=uc[u]||uc[(s+c>>1)*cc+(i+l>>1)]||uc[(r+c>>1)*cc+(o+l>>1)])}const o=new Xe,r=new Ke;let n=0;function a(e,t){const i=t*cc+e;return 0===_c[i]&&(o.emplaceBack(dc[2*i+0],dc[2*i+1],e*ae/lc,t*ae/lc),_c[i]=++n),_c[i]-1}function l(e,t,i,s,o,n){const c=e+i>>1,h=t+s>>1;if(Math.abs(e-o)+Math.abs(t-n)>1&&uc[h*cc+c])l(o,n,e,t,c,h),l(i,s,o,n,c,h);else{const l=a(e,t),c=a(i,s),h=a(o,n);r.emplaceBack(l,c,h)}}return l(0,0,lc,lc,lc,0),l(lc,lc,0,0,0,lc),{vertices:o,indices:r}}(this.tileID.canonical,t);s=e.vertices,o=e.indices}else{s=new Xe,o=new Ke;for(const{x:e,y:t}of i)s.emplaceBack(e,t,0,0);const e=xt(s.int16.subarray(0,4*s.length),void 0,4);for(let t=0;t<e.length;t+=3)o.emplaceBack(e[t],e[t+1],e[t+2])}this._tileBoundsBuffer=e.createVertexBuffer(s,Gl.members),this._tileBoundsIndexBuffer=e.createIndexBuffer(o),this._tileBoundsSegments=Ye.simpleSegment(0,0,s.length,o.length)}_makeGlobeTileDebugBuffers(e,t){const i=t.projection;if(!i||"globe"!==i.name||t.freezeTileCoverage)return;const s=this.tileID.canonical,o=bt(s,t),r=wt(o),n=K(t.zoom);let a;n>0&&(a=Tt(new Float64Array(16),t.globeMatrix)),this._makeGlobeTileDebugBorderBuffer(e,s,t,r,a,n),this._makeGlobeTileDebugTextBuffer(e,s,t,r,a,n)}_globePoint(e,t,i,s,o,r,n){let a=Et(e,t,i);if(r){const o=1<<i.z,l=Ae(s.center.lng),c=Pe(s.center.lat),h=(i.x+.5)/o-l;let d=0;h>.5?d=-1:h<-.5&&(d=1);let u=(e/ae+i.x)/o+d,_=(t/ae+i.y)/o;u=(u-l)*s._pixelsPerMercatorPixel+l,_=(_-c)*s._pixelsPerMercatorPixel+c;const p=[u*s.worldSize,_*s.worldSize,0];It(p,p,r),a=St(a,p,n)}return It(a,a,o)}_makeGlobeTileDebugBorderBuffer(e,t,i,s,o,r){const n=new gt,a=new vt,l=new Dt,c=(e,c,h,d,u)=>{const _=(h-e)/(u-1),p=(d-c)/(u-1),f=n.length;for(let h=0;h<u;h++){const d=e+h*_,u=c+h*p;n.emplaceBack(d,u);const m=this._globePoint(d,u,t,i,s,o,r);l.emplaceBack(m[0],m[1],m[2]),a.emplaceBack(f+h)}},h=ae;c(0,0,h,0,16),c(h,0,h,h,16),c(h,h,0,h,16),c(0,h,0,0,16),this._tileDebugIndexBuffer=e.createIndexBuffer(a),this._tileDebugBuffer=e.createVertexBuffer(n,yt.members),this._globeTileDebugBorderBuffer=e.createVertexBuffer(l,Rt.members),this._tileDebugSegments=Ye.simpleSegment(0,0,n.length,a.length)}_makeGlobeTileDebugTextBuffer(e,t,i,s,o,r){const n=ae/4,a=new gt,l=new Ke,c=new Dt,h=25;l.reserve(32),a.reserve(h),c.reserve(h);const d=(e,t)=>h*e+t;for(let e=0;e<h;e++){const l=e*n;for(let e=0;e<h;e++){const h=e*n;a.emplaceBack(h,l);const d=this._globePoint(h,l,t,i,s,o,r);c.emplaceBack(d[0],d[1],d[2])}}for(let e=0;e<4;e++)for(let t=0;t<4;t++){const i=d(e,t),s=d(e,t+1),o=d(e+1,t),r=d(e+1,t+1);l.emplaceBack(i,s,o),l.emplaceBack(o,s,r)}this._tileDebugTextIndexBuffer=e.createIndexBuffer(l),this._tileDebugTextBuffer=e.createVertexBuffer(a,yt.members),this._globeTileDebugTextBuffer=e.createVertexBuffer(c,Rt.members),this._tileDebugTextSegments=Ye.simpleSegment(0,0,h,32)}destroy(e=!0){for(const t in this.buckets)this.buckets[t].destroy(e);this.buckets={},this.imageAtlas&&(this.imageAtlas=null),this.lineAtlas&&(this.lineAtlas=null),this.imageAtlasTexture&&delete this.imageAtlasTexture,this.glyphAtlasTexture&&(this.glyphAtlasTexture.destroy(),delete this.glyphAtlasTexture),this.lineAtlasTexture&&(this.lineAtlasTexture.destroy(),delete this.lineAtlasTexture),this._tileBoundsBuffer&&(this._tileBoundsBuffer.destroy(),this._tileBoundsIndexBuffer.destroy(),this._tileBoundsSegments.destroy(),this._tileBoundsBuffer=null),this._tileDebugBuffer&&(this._tileDebugBuffer.destroy(),this._tileDebugSegments.destroy(),this._tileDebugBuffer=null),this._tileDebugIndexBuffer&&(this._tileDebugIndexBuffer.destroy(),this._tileDebugIndexBuffer=null),this._globeTileDebugBorderBuffer&&(this._globeTileDebugBorderBuffer.destroy(),this._globeTileDebugBorderBuffer=null),this._tileDebugTextBuffer&&(this._tileDebugTextBuffer.destroy(),this._tileDebugTextSegments.destroy(),this._tileDebugTextIndexBuffer.destroy(),this._tileDebugTextBuffer=null),this._globeTileDebugTextBuffer&&(this._globeTileDebugTextBuffer.destroy(),this._globeTileDebugTextBuffer=null),e&&this.texture&&this.texture instanceof k&&(this.texture.destroy(),delete this.texture),this.emissiveTexture&&this.emissiveTexture instanceof k&&(this.emissiveTexture.destroy(),delete this.emissiveTexture),this.hillshadeFBO&&(this.hillshadeFBO.destroy(),delete this.hillshadeFBO),this.dem&&delete this.dem,this.neighboringTiles&&delete this.neighboringTiles,this.demTexture&&(this.demTexture.destroy(),delete this.demTexture),this.rasterParticleState&&(this.rasterParticleState.destroy(),delete this.rasterParticleState),this.latestFeatureIndex=null,this.state="unloaded"}}function xc(e){mc=e}class bc{constructor(e,t){this.max=e,this.onRemove=t,this.reset()}reset(){for(const e in this.data)for(const t of this.data[e])t.timeout&&clearTimeout(t.timeout),this.onRemove(t.value);return this.data={},this.order=[],this}add(e,t,i){const s=e.wrapped().key;void 0===this.data[s]&&(this.data[s]=[]);const o={value:t,timeout:void 0};if(void 0!==i&&(o.timeout=setTimeout(()=>{this.remove(e,o)},i)),this.data[s].push(o),this.order.push(s),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,s=void 0===t?0:this.data[i].indexOf(t),o=this.data[i][s];return this.data[i].splice(s,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 s of this.data[i])e(s.value)||t.push(s);for(const e of t)this.remove(e.value.tileID,e)}}class wc{constructor(){this.state=Object.create(null),this.stateChanges=Object.create(null),this.deletedStates=Object.create(null)}updateState(e,t,i){const s=String(t),o=this.stateChanges[e]=this.stateChanges[e]||Object.create(null),r=o[s]=o[s]||Object.create(null);Object.assign(r,i);const n=this.deletedStates[e];if(null===n){const t=this.deletedStates[e]=Object.create(null);for(const i in this.state[e])i!==s&&(t[i]=null);return}if(!n)return;const a=n[s];if(null===a){const t=n[s]=Object.create(null);for(const o in this.state[e][s])i[o]||(t[o]=null);return}if(a)for(const e in i)null===a[e]&&delete a[e]}removeFeatureState(e,t,i){if(null===this.deletedStates[e])return;const s=String(t);if(this.deletedStates[e]=this.deletedStates[e]||Object.create(null),i&&void 0!==t)null!==this.deletedStates[e][s]&&(this.deletedStates[e][s]=this.deletedStates[e][s]||Object.create(null),this.deletedStates[e][s][i]=null);else if(void 0!==t)if(this.stateChanges[e]&&this.stateChanges[e][s])for(i in this.deletedStates[e][s]=Object.create(null),this.stateChanges[e][s])this.deletedStates[e][s][i]=null;else this.deletedStates[e][s]=null;else this.deletedStates[e]=null}getState(e,t){const i=this.state[e]||Object.create(null),s=this.stateChanges[e]||Object.create(null),o=this.deletedStates[e];if(null===o)return Object.create(null);if(void 0!==t){const e=String(t),r=Object.assign(Object.create(null),i[e],s[e]);if(o){const e=o[t];if(null===e)return Object.create(null);for(const t in e)delete r[t]}return r}const r=Object.assign(Object.create(null),i,s);if(o)for(const e in o)delete r[e];return r}initializeTileState(e,t){e.refreshFeatureState(t)}coalesceChanges(e,t){const i=Object.create(null);for(const e in this.stateChanges){this.state[e]=this.state[e]||Object.create(null);const t=Object.create(null);for(const i in this.stateChanges[e])this.state[e][i]||(this.state[e][i]=Object.create(null)),Object.assign(this.state[e][i],this.stateChanges[e][i]),t[i]=this.state[e][i];i[e]=t}for(const e in this.deletedStates){this.state[e]=this.state[e]||Object.create(null);const t=Object.create(null);if(null===this.deletedStates[e])for(const i in this.state[e])t[i]=Object.create(null),this.state[e][i]=Object.create(null);else for(const i in this.deletedStates[e]){if(null===this.deletedStates[e][i])this.state[e][i]=Object.create(null);else if(this.state[e][i])for(const t of Object.keys(this.deletedStates[e][i]))delete this.state[e][i][t];t[i]=this.state[e][i]}i[e]=i[e]||Object.create(null),Object.assign(i[e],t)}if(this.stateChanges=Object.create(null),this.deletedStates=Object.create(null),0!==Object.keys(i).length)for(const s of e.values())s.refreshFeatureState(t,i)}}class Tc{constructor(e,t){this.bucket=e,this.canonical=t,this.keys=[],this.indices=[],this.stableIdMap=new Map;const i=e.symbolInstances,s=[];for(let t=0;t<i.length;t++){const o=e.stableIdFor(t);if(void 0!==o){this.stableIdMap.set(o,t);continue}const{key:r,tileAnchorX:n,tileAnchorY:a}=i.get(t);s.push(n,a),this.keys.push(r),this.indices.push(t)}this.index=new Lt(this.indices.length,16);for(let e=0;e<s.length;e+=2)this.index.add(s[e],s[e+1]);this.index.finish()}findMatch(e,t,i,s){const o=e.stableIdFor(t);if(void 0!==o){const e=this.stableIdMap.get(o);return void 0===e||s.has(e)?-1:(s.add(e),e)}const r=Math.pow(2,this.canonical.z-i.z),{key:n,tileAnchorX:a,tileAnchorY:l}=e.symbolInstances.get(t),c=i.x*ae+a,h=i.y*ae+l,d=Math.floor(c*r)-this.canonical.x*ae,u=Math.floor(h*r)-this.canonical.y*ae,_=Math.ceil((c+1)*r)-1-this.canonical.x*ae,p=Math.ceil((h+1)*r)-1-this.canonical.y*ae;let f=-1;for(const e of this.index.range(d,u,_,p))this.keys[e]===n&&!s.has(this.indices[e])&&(f<0||e<f)&&(f=e);return f<0?-1:(s.add(this.indices[f]),this.indices[f])}}function Ec(e){const t=new Map,i=[];for(const s of e){const{key:e,overscaledZ:o,canonical:r}=s.tile.tileID;t.set(e,s),i.some(e=>e.overscaledZ===o&&e.z===r.z)||i.push({overscaledZ:o,z:r.z})}return i.sort((e,t)=>t.overscaledZ-e.overscaledZ),{byKey:t,zooms:i}}function Ic(e){const t=[],i=[];for(const s of e)(s.held?i:t).push(s);return{owning:Ec(t),held:Ec(i)}}function Sc(e,t,i,s){const{canonical:o}=e,r=Math.pow(2,s.z-o.z)/ae,n=Math.floor((o.x*ae+t)*r),a=Math.floor((o.y*ae+i)*r);return Pt(e.wrap,s.overscaledZ,s.z,n,a)}function Dc(e,t,i,s,o=1/0){for(const r of e.zooms){if(r.overscaledZ>=o)continue;const n=e.byKey.get(Sc(t,i,s,r));if(n)return n}}function Rc(e,t){return Dc(e,t,0,0,t.overscaledZ)}class Cc{constructor(){this.entries=new Map}clear(){this.entries.clear()}sync(e){const t=new Map,i=[],s=new Map,o=[];for(const r of e){let e=this.entries.get(r.uid);if(e){const t=this._updateBuckets(e);t&&s.set(e,t),e.held!==r.holdingForFade()&&o.push(e)}else e={tile:r,buckets:this._indexBuckets(r),held:r.holdingForFade()},i.push(e);t.set(r.uid,e)}const r=[];for(const[e,i]of this.entries)t.has(e)||r.push(i);if(0===i.length&&0===r.length&&0===s.size&&0===o.length)return;const n=Ic(this.entries.values());for(const e of o)e.held=!e.held;const a=Ic(t.values()),l=i.filter(e=>!e.held),c=r.filter(e=>!e.held);for(const e of o)(e.held?c:l).push(e);const h=new Set(l),d=new Set(l);for(const e of s.keys())e.held||d.add(e);for(const e of c){const t=Rc(a.owning,e.tile.tileID);t&&h.add(t)}for(const e of[...l,...c]){const t=Rc(a.owning,e.tile.tileID);t&&d.add(t)}for(const[e,t]of s)!e.held&&t.size>0&&h.add(e);for(const e of h)this._migrate(e,n,a.owning,s.get(e));this.entries=t;for(const e of d)this._markNonOwned(e,a.owning)}_indexBuckets(e){const t=new Map;for(const i in e.buckets){const s=e.buckets[i];s instanceof ct&&s.layerIds[0]===i&&t.set(i,new Tc(s,e.tileID.canonical))}return t}_updateBuckets(e){const t=e.tile,i=t.tileID.canonical,s=e.buckets;let o=!1;const r=new Map,n=new Map;for(const e in t.buckets){const a=t.buckets[e];if(!(a instanceof ct)||a.layerIds[0]!==e)continue;const l=s.get(e);if(l&&l.bucket===a){n.set(e,l);continue}o=!0,n.set(e,new Tc(a,i));const c=new Uint8Array(a.symbolInstances.length),h=new Set;for(let e=0;e<c.length;e++){const t=l?l.findMatch(a,e,i,h):-1;t<0?c[e]=1:a.takePlacementStateFrom(l.bucket,t,e)}c.includes(1)&&r.set(e,c)}return(o||n.size!==s.size)&&(e.buckets=n),o?r:null}_takeState(e,t,i,s,o,r){const n=e.buckets.get(t);if(!n)return!1;let a=r.get(n);a||(a=new Set,r.set(n,a));const l=n.findMatch(i,s,o.canonical,a);return!(l<0)&&i.takePlacementStateFrom(n.bucket,l,s)}_markNonOwned(e,t){const i=e.tile.tileID;for(const{bucket:s}of e.buckets.values()){s.ensurePlacementState();const o=s.nonOwnedSymbols;for(let r=0;r<o.length;r++){const{tileAnchorX:n,tileAnchorY:a}=s.symbolInstances.get(r);o[r]=Dc(t,i,n,a)!==e?1:0}}}_migrate(e,t,i,s){const o=e.tile.tileID;for(const[r,n]of e.buckets){const a=n.bucket,l=s?s.get(r):void 0,c=new Map;for(let s=0;s<a.symbolInstances.length;s++){const{tileAnchorX:n,tileAnchorY:h}=a.symbolInstances.get(s);if(Dc(i,o,n,h)!==e)continue;if((!l||1!==l[s])&&Dc(t.owning,o,n,h)===e)continue;let d=!1;for(const i of t.owning.zooms){const l=t.owning.byKey.get(Sc(o,n,h,i));if(l&&l!==e&&this._takeState(l,r,a,s,o,c)){d=!0;break}}if(!d)for(const i of t.held.zooms){const l=t.held.byKey.get(Sc(o,n,h,i));if(l&&l!==e&&this._takeState(l,r,a,s,o,c))break}}}}}class Ac extends A{constructor(e,t,i){super(),this.id=e,this._renderSourceType=i,this._maxzoomOverride=null,this.setSource(t),this._tiles=new Map,this._cache=new bc(0,this._unloadTile.bind(this)),this._timers=new Map,this._minTileCacheSize=t.minTileCacheSize,this._maxTileCacheSize=t.maxTileCacheSize,this._loadedParentTiles=new Map,this.placementRelations=new Cc,this.castsShadows=!1,this.tileCoverLift=0,this._coveredTiles=new Set,this._shadowCasterTiles=new Set,this._state=new wc,this._isRaster="raster"===this._source.type||"raster-dem"===this._source.type||"raster-array"===this._source.type||"custom"===this._source.type&&"_dataType"in this._source&&"raster"===this._source._dataType,this._supportsFading="raster"===this._source.type||"raster-array"===this._source.type||"image"===this._source.type||"video"===this._source.type||"custom"===this._source.type,this._isRasterElevatedOverTerrain=!1}onAdd(e){this.map=e,this._minTileCacheSize=void 0===this._minTileCacheSize&&e?e._minTileCacheSize:this._minTileCacheSize,this._maxTileCacheSize=void 0===this._maxTileCacheSize&&e?e._maxTileCacheSize:this._maxTileCacheSize}setSource(e){e.on("data",e=>{"source"===e.dataType&&"metadata"===e.sourceDataType&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&"source"===e.dataType&&"content"===e.sourceDataType&&(this.reload(),this.transform&&this.update(this.transform))}),e.on("error",()=>{this._sourceErrored=!0}),this._source=e}loaded(){if(this._sourceErrored)return!0;if(this._source instanceof Jl)return this._source.loaded();if(!this._sourceLoaded)return!1;if(!this._source.loaded())return!1;for(const e of this._tiles.values())if(!e.loaded())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)}setMaxzoomOverride(e){this._maxzoomOverride=e}_loadTile(e,t){return e.renderSourceType=this._renderSourceType,e.isExtraShadowCaster=this._shadowCasterTiles.has(e.tileID.key),this._source.loadTile(e,t)}_unloadTile(e){if(e.aborted=!0,this._abortTile(e),this._source.unloadTile)return this._source.unloadTile(e)}_abortTile(e){if(this._source.abortTile)return this._source.abortTile(e)}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,i]of this._tiles)i.upload(e,this.map?this.map.painter:void 0),i.imageAtlas&&!i.imageAtlasTexture&&"loaded"===i.state&&this._reloadTile(t,"reloading"),i.prepare(this.map.style.imageManager,this.map?this.map.painter:null,this._source.scope)}getIds(){return Array.from(this._tiles.values(),e=>e.tileID).sort(Lc).map(e=>e.key)}getRenderableIds(e,t){const i=[];for(const s of this._tiles.values())this._isTileRenderable(s,e,t)&&i.push(s);return e?i.sort((e,t)=>{const i=e.tileID,s=t.tileID,o=new m(i.canonical.x,i.canonical.y)._rotate(this.transform.angle),r=new m(s.canonical.x,s.canonical.y)._rotate(this.transform.angle);return i.overscaledZ-s.overscaledZ||r.y-o.y||r.x-o.x}).map(e=>e.tileID.key):i.map(e=>e.tileID).sort(Lc).map(e=>e.key)}hasRenderableParent(e){const t=this.findLoadedParent(e,0);return!!t&&this._isIdRenderable(t.tileID.key)}_isIdRenderable(e,t,i){const s=this._tiles.get(e);return!!s&&this._isTileRenderable(s,t,i)}_isTileRenderable(e,t,i){const s=e.tileID.key;return e.hasData()&&!this._coveredTiles.has(s)&&(t||!e.holdingForFade())&&(i||!this._shadowCasterTiles.has(s))}reload(){if(this._paused)this._shouldReloadOnResume=!0;else{this._cache.reset();for(const[e,t]of this._tiles)"errored"!==t.state&&this._reloadTile(e,"reloading")}}_reloadTile(e,t){const i=this._tiles.get(e);i&&("loading"!==i.state&&(i.state=t),this._loadTile(i,this._tileLoaded.bind(this,i,e,t)))}_tileLoaded(e,t,i,s,o){if(e.aborted)return;if(s){if(e.state="errored",Mt(s)){if(this._source.fire(new M("data",{dataType:"source",sourceDataType:"error",sourceId:this._source.id,tile:e})),!this._loadedParentTiles.has(e.tileID.key))return;if("raster-dem"===this._source.type&&this.usedForTerrain&&this.map.painter.terrain){const e=this.map.painter.terrain;this.update(this.transform,e.getScaledDemTileSize(),!0),e.resetTileLookupCache(this.id)}else this.update(this.transform)}else this._source.fire(new P(s,{tile:e}));return}e.timeAdded=T.now(),"expired"===i&&(e.refreshedUponExpiration=!0),this._setTileReloadTimer(t,e),"raster-dem"===this._source.type&&e.dem&&this._backfillDEM(e),this._state.initializeTileState(e,this.map?this.map.painter:null);let r=new Headers;o&&o.headers&&(r=o.headers),this._syncPlacementRelations(),this._source.fire(new M("data",{dataType:"source",tile:e,coord:e.tileID,sourceCacheId:this.id,responseHeaders:r}))}_syncPlacementRelations(){if(!this.map||"global"!==this.map._placementAlgorithm)return;const e=[];for(const t of this._tiles.values())this._isTileRenderable(t,!0)&&e.push(t);this.placementRelations.sync(e)}_hasTunnelGeometry(){for(const e of this._tiles.values())if(e.hasTunnelGeometry)return!0;return!1}_backfillDEM(e){const t=this.getRenderableIds();for(let s=0;s<t.length;s++){const o=t[s];if(e.neighboringTiles&&e.neighboringTiles[o]){const t=this.getTileByID(o);i(e,t),i(t,e)}}function i(e,t){if(!e.dem||e.dem.borderReady)return;e.needsHillshadePrepare=!0,e.needsDEMTextureUpload=!0;let i=t.tileID.canonical.x-e.tileID.canonical.x;const s=t.tileID.canonical.y-e.tileID.canonical.y,o=Math.pow(2,e.tileID.canonical.z),r=t.tileID.key;0===i&&0===s||Math.abs(s)>1||(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,s),e.neighboringTiles&&e.neighboringTiles[r]&&(e.neighboringTiles[r].backfilled=!0)))}}getTile(e){return this.getTileByID(e.key)}getTileByID(e){return this._tiles.get(e)}_retainLoadedChildren(e,t,i,s){const o="raster-array"===this._source.type;for(const[r,n]of this._tiles){let a=n;if(s.has(r)||!a.hasData()||a.tileID.overscaledZ<=t||a.tileID.overscaledZ>i)continue;if(o&&a.parentTile)continue;let l=a.tileID;for(;a&&a.tileID.overscaledZ>t+1;){const e=a.tileID.scaledTo(a.tileID.overscaledZ-1);a=this._tiles.get(e.key),a&&a.hasData()&&(l=e)}let c=l;for(;c.overscaledZ>t;)if(c=c.scaledTo(c.overscaledZ-1),e.has(c.key)){s.set(l.key,l);const e=this._tiles.get(l.key);e&&(e.dashIdealZ=c.overscaledZ);break}}}findLoadedParent(e,t){if(this._loadedParentTiles.has(e.key)){const i=this._loadedParentTiles.get(e.key);return i&&i.tileID.overscaledZ>=t?i:null}for(let i=e.overscaledZ-1;i>=t;i--){const t=e.scaledTo(i),s=this._getLoadedTile(t);if(s)return s}}_getLoadedTile(e){const t=this._tiles.get(e.key);return t&&t.hasData()?t:this._cache.getByKey(this._source.reparseOverscaled?e.wrapped().key:e.canonical.key)}updateCacheSize(e,t){t=t||this._source.tileSize;const i=Math.ceil(e.width/t)+1,s=Math.ceil(e.height/t)+1,o=Math.floor(i*s*5),r="number"==typeof this._minTileCacheSize?Math.max(this._minTileCacheSize,o):o,n="number"==typeof this._maxTileCacheSize?Math.min(this._maxTileCacheSize,r):r;this._cache.setMaxSize(n)}handleWrapJump(e){const t=Math.round((e-(void 0===this._prevLng?e:this._prevLng))/360);if(this._prevLng=e,t){const e=new Map;for(const i of this._tiles.values())i.tileID=i.tileID.unwrapTo(i.tileID.wrap+t),e.set(i.tileID.key,i);this._tiles=e;for(const e of this._timers.values())clearTimeout(e);this._timers.clear();for(const[e,t]of this._tiles)this._setTileReloadTimer(e,t)}}update(e,t,i,s,o){if(this.transform=e,!this._sourceLoaded||this._paused||this.transform.freezeTileCoverage)return;if(this.usedForTerrain&&!i)return;this.updateCacheSize(e,t),"globe"!==this.transform.projection.name&&this.handleWrapJump(this.transform.center.lng),this._shadowCasterTiles=new Set,this._coveredTiles=new Set;const r="batched-model"===this._source.type;let n,a=this._source.maxzoom;null!==this._maxzoomOverride&&(a=Math.min(a,this._maxzoomOverride));const l=this.map&&this.map.painter?this.map.painter._terrain:null;if(l&&l.sourceCache===this&&l.attenuationRange()){const e=l.attenuationRange()[0],t=Math.floor(e)-Math.log2(l.getDemUpscale());a>t&&(a=t)}const c=null===this._maxzoomOverride&&this._source.reparseOverscaled;if(this.used||this.usedForTerrain)if(this._source.tileID)n=e.getVisibleUnwrappedCoordinates(this._source.tileID).map(e=>new Ge(e.canonical.z,e.wrap,e.canonical.z,e.canonical.x,e.canonical.y));else if(0!==this.tileCoverLift){const s=e.clone();s.tileCoverLift=this.tileCoverLift,n=s.coveringTiles({tileSize:t||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:a,roundZoom:this._source.roundZoom&&!i,reparseOverscaled:c,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:r}),this._source.minzoom<=1&&"globe"===e.projection.name&&(n.push(new Ge(1,0,1,0,0)),n.push(new Ge(1,0,1,1,0)),n.push(new Ge(1,0,1,0,1)),n.push(new Ge(1,0,1,1,1)))}else n=e.coveringTiles({tileSize:t||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:a,roundZoom:this._source.roundZoom&&!i,reparseOverscaled:c,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:r});else n=[];if(n.length>0&&"globe"!==this.transform.projection.name&&!this.usedForTerrain&&!this._supportsFading){const l=e.coveringZoomLevel({tileSize:t||this._source.tileSize,roundZoom:this._source.roundZoom&&!i}),c=Math.min(l,a);if(r){const t=e.extendTileCover(n,c);for(const e of t)n.push(e)}else if(o){const t=this.transform.getFrustum(c),i=e.extendTileCoverToNearPlane(n,t,c);for(const e of i)n.push(e);if(c>=18&&this._hasTunnelGeometry()){const i=e.extendTileCoverForTunnels(n,t,c,20);for(const e of i)n.push(e)}}else if(this.castsShadows&&s){const t=e.extendTileCover(n,c,s,16);for(const e of t)this._shadowCasterTiles.add(e.key),n.push(e)}}for(const e of this._tiles.values())e.dashIdealZ=e.tileID.overscaledZ;this._source.hasTile&&(n=n.filter(e=>this._source.hasTile(e)));const h=this._updateRetainedTiles(n);if(this._supportsFading&&0!==n.length){const e=new Map,t=new Set,i=T.now();for(const[s,o]of h){const r=this._tiles.get(s);if(!r||void 0!==r.fadeEndTime&&r.fadeEndTime<=i)continue;const n=this.findLoadedParent(o,Math.max(o.overscaledZ-Ac.maxOverzooming,this._source.minzoom));n&&(this._addTile(n.tileID),e.set(n.tileID.key,n.tileID)),t.add(s)}const s=n.at(-1).overscaledZ;for(const[e,i]of this._tiles){if(h.has(e)||!i.hasData())continue;let o=i.tileID;for(;o.overscaledZ>s;){o=o.scaledTo(o.overscaledZ-1);const s=this._tiles.get(o.key);if(s&&s.hasData()&&t.has(o.key)){h.set(e,i.tileID);break}}}for(const[t,i]of e)h.has(t)||(this._coveredTiles.add(t),h.set(t,i))}for(const e of h.keys())this._tiles.get(e).clearFadeHold();for(const[e,t]of this._tiles)h.has(e)||(t.hasSymbolBuckets&&!t.holdingForFade()?t.setHoldDuration(this.map._fadeDuration):t.hasSymbolBuckets&&!t.symbolFadeFinished()||this._removeTile(e));this._updateLoadedParentTileCache(),this._syncPlacementRelations(),this._renderSourceType===Ot.Symbol&&this._source.afterUpdate&&this._source.afterUpdate()}releaseSymbolFadeTiles(){let e=!1;for(const[t,i]of this._tiles)i.holdingForFade()&&(this._removeTile(t),e=!0);e&&this._syncPlacementRelations()}_updateRetainedTiles(e){const t=new Map;if(0===e.length)return t;const i=new Set,s=e.reduce((e,t)=>Math.min(e,t.overscaledZ),1/0),o=e[0].overscaledZ,r=Math.max(o-Ac.maxOverzooming,this._source.minzoom),n=Math.max(o+Ac.maxUnderzooming,this._source.minzoom),a=new Set;for(const i of e){const e=this._addTile(i);t.set(i.key,i),e.hasData()||s<this._source.maxzoom&&a.add(i.key)}if(this._retainLoadedChildren(a,s,n,t),"raster-array"===this._source.type){const i=this._source,s=this._tiles;for(const o of i.collectOverzoomParentTileIDs(s,e))t.set(o.key,o)}for(const s of e){let e=this._tiles.get(s.key);if(e.hasData())continue;if(s.canonical.z>=this._source.maxzoom){const e=s.children(this._source.maxzoom)[0],i=this.getTile(e);if(i&&i.hasData()){t.set(e.key,e),i.dashIdealZ=s.overscaledZ;continue}}else{const e=s.children(this._source.maxzoom);if(t.has(e[0].key)&&t.has(e[1].key)&&t.has(e[2].key)&&t.has(e[3].key))continue}let o=e.wasRequested();for(let n=s.overscaledZ-1;n>=r;--n){const r=s.scaledTo(n);if(i.has(r.key))break;if(i.add(r.key),e=this.getTile(r),!e&&o&&(e=this._addTile(r)),e&&(t.set(r.key,r),e.dashIdealZ=s.overscaledZ,o=e.wasRequested(),e.hasData()))break}}return t}_updateLoadedParentTileCache(){this._loadedParentTiles.clear();for(const e of this._tiles.values()){const t=[];let i,s=e.tileID;for(;s.overscaledZ>0;){if(this._loadedParentTiles.has(s.key)){i=this._loadedParentTiles.get(s.key);break}t.push(s.key);const e=s.scaledTo(s.overscaledZ-1);if(i=this._getLoadedTile(e),i)break;s=e}for(const e of t)this._loadedParentTiles.set(e,i)}}_addTile(e){let t=this._tiles.get(e.key);const i=this._shadowCasterTiles.has(e.key);if(t)return!0!==t.isExtraShadowCaster||i||this._reloadTile(e.key,"reloading"),t;t=this._cache.getAndRemove(e),t&&(this._setTileReloadTimer(e.key,t),t.tileID=e,this._state.initializeTileState(t,this.map?this.map.painter:null),t.resetPlacementVisibility());const s=Boolean(t);if(!s){const i=this.map?this.map.painter:null,s=this._source.tileSize*e.overscaleFactor();t="raster-array"===this._source.type?function(e,t,i,s,o){if(!mc)throw new Error("Raster-array module is not loaded.");return mc(e,t,i,s,o)}(e,s,this.transform.tileZoom,i,this._isRaster):new yc(e,s,this.transform.tileZoom,i,this._isRaster,this._source.worldview),this._loadTile(t,this._tileLoaded.bind(this,t,e.key,t.state))}return t.uses++,this._tiles.set(e.key,t),s||this._source.fire(new M("dataloading",{tile:t,coord:t.tileID,dataType:"source"})),t}_setTileReloadTimer(e,t){clearTimeout(this._timers.get(e)),this._timers.delete(e);const i=t.getExpiryTimeout();i&&this._timers.set(e,setTimeout(()=>{this._reloadTile(e,"expired"),this._timers.delete(e)},i))}_removeTile(e){const t=this._tiles.get(e);t&&(t.uses--,this._tiles.delete(e),clearTimeout(this._timers.get(e)),this._timers.delete(e),t.uses>0||(t.hasData()&&"reloading"!==t.state||"empty"===t.state?this._cache.add(t.tileID,t,t.getExpiryTimeout()):this._unloadTile(t)))}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(const e of this._tiles.keys())this._removeTile(e);this._source._clear&&this._source._clear(),this._cache.reset(),this.placementRelations.clear(),this.map&&this.usedForTerrain&&this.map.painter.terrain&&this.map.painter.terrain.resetTileLookupCache(this.id)}tilesIn(e,t,i){const s=[],o=this.transform;if(!o)return s;const r="globe"===o.projection.name,n=Ae(o.center.lng),a=o.getFreeCameraOptions().position||new we(0,0,0);for(const l of this._tiles.values()){if(i&&l.clearQueryDebugViz(),l.holdingForFade())continue;let c;if(r){const e=l.tileID.canonical;if(0===e.z){const t=[Math.abs(Ee(n,...Pc(e,-1))-n),Math.abs(Ee(n,...Pc(e,1))-n)];c=[0,2*t.indexOf(Math.min(...t))-1]}else{const t=[Math.abs(Ee(n,...Pc(e,-1))-n),Math.abs(Ee(n,...Pc(e,0))-n),Math.abs(Ee(n,...Pc(e,1))-n)];c=[t.indexOf(Math.min(...t))-1]}}else c=[0];for(const i of c){const r=e.containsTile(l,o,t,i,a);r&&s.push(r)}}return s}getShadowCasterCoordinates(){return this._getRenderableCoordinates(!1,!0)}getVisibleCoordinates(e){return this._getRenderableCoordinates(e)}_getRenderableCoordinates(e,t){if(!this.transform)return[];const i=this.getRenderableIds(e,t).map(e=>this._tiles.get(e).tileID),s="globe"===this.transform.projection.name;for(const e of i)e.projMatrix=this.transform.calculateProjMatrix(e.toUnwrapped()),e.expandedProjMatrix=s?this.transform.calculateProjMatrix(e.toUnwrapped(),!1,!0):e.projMatrix;return i}sortCoordinatesByDistance(e){if(!this.transform)return e.slice();const t=e.slice(),i=this.transform._camera.position,s=this.transform._camera.forward(),o=new Map;for(const e of t){const t=1/(1<<e.canonical.z);o.set(e.key,((e.canonical.x+.5)*t+e.wrap-i[0])*s[0]+((e.canonical.y+.5)*t-i[1])*s[1]-i[2]*s[2])}return t.sort((e,t)=>o.get(e.key)-o.get(t.key)),t}hasTransition(){if(this._source.hasTransition())return!0;if(this._supportsFading){const e=T.now();for(const t of this._tiles.values())if(void 0!==t.fadeEndTime&&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 s=this._tiles.get(e);s&&s.setDependencies(t,i)}reloadTilesForDependencies(e,t){for(const[i,s]of this._tiles)s.hasDependency(e,t)&&this._reloadTile(i,"reloading");this._cache.filter(i=>!i.hasDependency(e,t))}_preloadTiles(e,t){if(!this._sourceLoaded){const i=()=>{this._sourceLoaded&&(this._source.off("data",i),this._preloadTiles(e,t))};return void this._source.on("data",i)}const i=new Map,s=Array.isArray(e)?e:[e],o=this.map.painter.terrain,r=this.usedForTerrain&&o?o.getScaledDemTileSize():this._source.tileSize;for(const e of s){const t=e.coveringTiles({tileSize:r,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom&&!this.usedForTerrain,reparseOverscaled:this._source.reparseOverscaled,isTerrainDEM:this.usedForTerrain});for(const e of t)i.set(e.key,e);this.usedForTerrain&&e.updateElevation(!1)}const n=Array.from(i.values());j(n,(e,t)=>{const i=new yc(e,this._source.tileSize*e.overscaleFactor(),this.transform.tileZoom,this.map.painter,this._isRaster,this._source.worldview);this._loadTile(i,e=>{"raster-dem"===this._source.type&&i.dem&&this._backfillDEM(i),t(e,i)})},t)}}function Lc(e,t){const i=Math.abs(2*e.wrap)-+(e.wrap<0),s=Math.abs(2*t.wrap)-+(t.wrap<0);return e.overscaledZ-t.overscaledZ||s-i||t.canonical.y-e.canonical.y||t.canonical.x-e.canonical.x}function Pc(e,t){const i=1<<e.z;return[e.x/i+t,(e.x+1)/i+t]}Ac.maxOverzooming=10,Ac.maxUnderzooming=3;class Mc{constructor(e){this.style=e,this.layersGotHidden=!1,this.layers=[]}processLayersChanged(){this.layers=[];const e=!1,t=!1;for(const i in this.style._mergedLayers){const s=this.style._mergedLayers[i];if("fill-extrusion"===s.type||"building"===s.type)this.layers.push({layer:s,visible:e,visibilityChanged:t});else if("model"===s.type){const i=this.style.getLayerSource(s);i&&"batched-model"===i.type&&this.layers.push({layer:s,visible:e,visibilityChanged:t})}}}onNewFrame(e){this.layersGotHidden=!1;for(const t of this.layers){const i=t.layer;let s=!1;"fill-extrusion"===i.type?s=!i.isHidden(e)&&i.paint.get("fill-extrusion-opacity")>0:"building"===i.type?s=!i.isHidden(e)&&i.paint.get("building-opacity")>0:"model"===i.type&&(s=!i.isHidden(e)&&i.paint.get("model-opacity").constantOr(1)>0),this.layersGotHidden=this.layersGotHidden||!s&&t.visible,t.visible=s}}updateZOffset(e,t){this.currentBuildingBuckets=[];for(const e of this.layers){const i=e.layer,s=this.style.getLayerSourceCache(i);let o=1;"fill-extrusion"===i.type?o=e.visible?i.paint.get("fill-extrusion-vertical-scale"):0:"building"===i.type&&(o=e.visible?i.paint.get("building-vertical-scale"):0);let r=s?s.getTile(t):null;if(!r&&s)for(const e of s._tiles.values())if(t.canonical.isChildOf(e.tileID.canonical)){r=e;break}this.currentBuildingBuckets.push({bucket:r?r.getBucket(i):null,tileID:r?r.tileID:t,verticalScale:o})}e.hasAnyZOffset=!1;let i=!1;for(let s=0;s<e.symbolInstances.length;s++){const o=e.symbolInstances.get(s),r=o.zOffset,n=this._getHeightAtTileOffset(t,o.tileAnchorX,o.tileAnchorY);o.zOffset=n!==Number.NEGATIVE_INFINITY?n:r,i||r===o.zOffset||(i=!0),e.hasAnyZOffset||0===o.zOffset||(e.hasAnyZOffset=!0)}i&&(e.zOffsetBuffersNeedUpload=!0,e.zOffsetSortDirty=!0)}hasLayerForSourceCache(e){for(const{layer:t}of this.layers){const i=this.style.getLayerSourceCache(t);if(i&&i.id===e)return!0}return!1}_mapCoordToOverlappingTile(e,t,i,s){let o=t,r=i;if(e.canonical.z!==s.canonical.z){const n=s.canonical,a=1/(1<<e.canonical.z-n.z);o=(t+e.canonical.x*ae)*a-n.x*ae|0,r=(i+e.canonical.y*ae)*a-n.y*ae|0}return{tileX:o,tileY:r}}_getHeightAtTileOffset(e,t,i){let s,o;for(let r=0;r<this.layers.length;++r){const n=this.layers[r].layer;if("fill-extrusion"!==n.type&&"building"!==n.type)continue;const{bucket:a,tileID:l,verticalScale:c}=this.currentBuildingBuckets[r];if(!a)continue;const{tileX:h,tileY:d}=this._mapCoordToOverlappingTile(e,t,i,l),u=a.getHeightAtTileCoord(h,d);u&&void 0!==u.height&&(u.hidden?s=u.height:o=Math.max(u.height*c,o||0))}if(void 0!==o)return o;for(let o=0;o<this.layers.length;++o){const r=this.layers[o];if("model"!==r.layer.type||!r.visible)continue;const{bucket:n,tileID:a}=this.currentBuildingBuckets[o];if(!n)continue;const{tileX:l,tileY:c}=this._mapCoordToOverlappingTile(e,t,i,a),h=n.getHeightAtTileCoord(l,c);if(h&&!h.hidden)return void 0===h.height&&void 0!==s?Math.min(h.maxHeight,s)*h.verticalScale:h.height?h.height*h.verticalScale:Number.NEGATIVE_INFINITY}return this.layersGotHidden?0:Number.NEGATIVE_INFINITY}}function Oc(){return gc||(gc=new dl),gc}function zc(){Oc().acquire(hl)}function Fc(){const e=gc;e&&(e.isPreloaded()&&1===e.numActive()?(e.release(hl),gc=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()"))}function kc(e,t){const i={},s=e,o=t,r=i;for(const e in s)"ref"!==e&&(r[e]=s[e]);return zt.forEach(e=>{e in o&&(r[e]=o[e])}),i}function Bc(e){e=e.slice();const t=Object.create(null);for(const i of e)t[i.id]=i;for(let i=0;i<e.length;i++){const s=e[i];if(s&&"ref"in s){const o=t[s.ref];o&&(e[i]=kc(s,o))}}return e}const Nc=Math.tan(85*Math.PI/180);function Uc(e,t,i,s,o,r,n){const a=Bt();if(i)if("globe"===r.name){const e=Nt(o,t);Ie(a,a,e)}else{const e=Ut([],n);a[0]=e[0],a[1]=e[1],a[4]=e[2],a[5]=e[3],s||kt(a,a,o.angle)}else Ie(a,o.labelPlaneMatrix,e);return a}function Vc(e,t,i,s,o,r,n){const a=Uc(e,t,i,s,o,r,n);return"globe"===r.name&&i||(a[2]=a[6]=a[10]=a[14]=0),a}function jc(e,t,i,s,o,r,n){if(i){if("globe"===r.name){const a=Uc(e,t,i,s,o,r,n);return Tt(a,a),Ie(a,e,a),a}{const t=Ft(e),[i,r,a,l]=n,[c,h,d,u,_,p,f,m]=t;return t[0]=i*c+r*_,t[1]=i*h+r*p,t[2]=i*d+r*f,t[3]=i*u+r*m,t[4]=a*c+l*_,t[5]=a*h+l*p,t[6]=a*d+l*f,t[7]=a*u+l*m,s||kt(t,t,-o.angle),t}}return o.glCoordMatrix}function Gc(e,t,i,s){const o=[e,t,i,1];i?Se(o,o,s):Vt(o,o,s);const r=o[3];return o[0]/=r,o[1]/=r,o[2]/=r,o}function qc(e,t){return Math.min(.5+e/t*.5,1.5)}function Zc(e,t){const i=e[0]/e[3],s=e[1]/e[3];return i>=-t[0]&&i<=t[0]&&s>=-t[1]&&s<=t[1]}function Wc(e,t,i,s,o,r,n,a,l,c,h=1){const d=i.transform,u=s?e.textSizeData:e.iconSizeData,_=jt(u,i.transform.zoom,h),p="globe"===d.projection.name,f=(()=>{if(!p)return null;const e=K(d.zoom);return 0===e?null:{t:e,invMatrix:d.projection.createInversionMatrix(d,c.canonical),mercCenter:[Ae(d.center.lng),Pe(d.center.lat)]}})(),g=[256/i.width*2+1,256/i.height*2+1],v=s?e.text.dynamicLayoutVertexArray:e.icon.dynamicLayoutVertexArray;v.clear();let y=null;p&&(y=s?e.text.globeExtVertexArray:e.icon.globeExtVertexArray);const x=e.lineVertexArray,b=s?e.text.placedSymbolArray:e.icon.placedSymbolArray,w=i.transform.width/i.transform.height;let T,E=!1;for(let h=0;h<b.length;h++){const p=b.get(h),{numGlyphs:I,writingMode:S}=p;if(S!==Gt.vertical||E||T===Gt.horizontal||(E=!0),T=S,(p.hidden||S===Gt.vertical)&&!E){th(I,v);continue}E=!1;const D=new m(p.tileAnchorX,p.tileAnchorY),R="road"===e.elevationType,C=!!d.elevation||R;let{x:A,y:L,z:P}=d.projection.projectTilePoint(D.x,D.y,c.canonical);if(f){const[e,t,i]=Yc(D,c.canonical,f);A+=(e-A)*f.t,L+=(t-L)*f.t,P+=(i-P)*f.t}let M=null;if(C){M=R&&e.hdExt?e.hdExt.makeRoadSymbolElevationParams(e,s?e.text:e.icon,h,c,l,d.elevation,d.projection,d.center.lat,d.worldSize):{getElevation:l,elevation:d.elevation,elevationFeature:null};const[t,i,o]=M.getElevation(D,d.elevation,M.elevationFeature);A+=t,L+=i,P+=o}const O=[A,L,P,1];if(Se(O,O,t),!Zc(O,g)){th(I,v);continue}const z=O[3],F=qc(i.transform.getCameraToCenterDistance(d.projection),z),k=Yt(u,_,p),B=n?k/F:k*F,N=Gc(A,L,P,o);if(N[3]<=0){th(I,v);continue}let U={};const V=le(e.layers[0].layout.get("text-max-angle")),j=Math.cos(V),G=n?null:M,q=Xc(p,B,!1,a,t,o,r,e.glyphOffsetArray,x,v,y,N,D,U,w,G,d.projection,c,n,j,f);E=q.useVertical,G&&q.needsFlipping&&(U={}),(q.notEnoughRoom||E||q.needsFlipping&&Xc(p,B,!0,a,t,o,r,e.glyphOffsetArray,x,v,y,N,D,U,w,G,d.projection,c,n,j,f).notEnoughRoom)&&th(I,v)}s?(e.text.dynamicLayoutVertexBuffer.updateData(v),y&&e.text.globeExtVertexBuffer&&e.text.globeExtVertexBuffer.updateData(y)):(e.icon.dynamicLayoutVertexBuffer.updateData(v),y&&e.icon.globeExtVertexBuffer&&e.icon.globeExtVertexBuffer.updateData(y))}function Hc(e,t,i,s,o,r,n,a,l,c,h,d,u,_,p,f,m,g){const{lineStartIndex:v,glyphStartIndex:y,segment:x}=a,b=y+a.numGlyphs,w=v+a.lineLength,T=t.getoffsetX(y),E=t.getoffsetX(b-1),I=eh(e*T,i,s,o,r,n,x,v,w,l,c,h,d,u,!0,_,p,f,m,g);if(!I)return null;const S=eh(e*E,i,s,o,r,n,x,v,w,l,c,h,d,u,!0,_,p,f,m,g);return S?{first:I,last:S}:null}function $c(e,t,i,s){return e===Gt.horizontal&&Math.abs(s)>Math.abs(i)?{useVertical:!0}:e===Gt.vertical?s>0?{needsFlipping:!0}:null:0!==t&&function(e,t){return 0===e||Math.abs(t/e)>Nc}(i,s)?1===t?{needsFlipping:!0}:null:i<0?{needsFlipping:!0}:null}function Xc(e,t,i,s,o,r,n,a,l,c,h,d,u,_,p,f,g,v,y,x,b){const w=t/24,T=e.lineOffsetX*w,E=e.lineOffsetY*w,{lineStartIndex:I,glyphStartIndex:S,numGlyphs:D,segment:R,writingMode:C,flipState:A}=e,L=I+e.lineLength,P=e=>{if(h){const[t,i,s]=e.up,o=c.length;$t(h,o+0,t,i,s),$t(h,o+1,t,i,s),$t(h,o+2,t,i,s),$t(h,o+3,t,i,s)}const[t,i,s]=e.point;Xt(c,t,i,s,e.angle)};if(D>1){const t=Hc(w,a,T,E,i,d,u,e,l,r,_,f,!1,g,v,y,x,b);if(!t)return{notEnoughRoom:!0};if(s&&!i){let[i,s,o]=t.first.point,[r,a,l]=t.last.point;[i,s]=Gc(i,s,o,n),[r,a]=Gc(r,a,l,n);const c=$c(C,A,(r-i)*p,a-s);if(e.flipState=c&&c.needsFlipping?1:2,c)return c}P(t.first);for(let e=S+1;e<S+D-1;e++){const t=eh(w*a.getoffsetX(e),T,E,i,d,u,R,I,L,l,r,_,f,!1,!1,g,v,y,x,b);if(!t)return c.length-=4*(e-S),{notEnoughRoom:!0};P(t)}P(t.last)}else{if(s&&!i){const t=Gc(u.x,u.y,0,o),i=I+R+1,s=new m(l.getx(i),l.gety(i)),r=Gc(s.x,s.y,0,o),n=r[3]>0?r:Jc(u,s,t,1,o,void 0,g,v.canonical),a=$c(C,A,(n[0]-t[0])*p,n[1]-t[1]);if(e.flipState=a&&a.needsFlipping?1:2,a)return a}const t=eh(w*a.getoffsetX(S),T,E,i,d,u,R,I,L,l,r,_,f,!1,!1,g,v,y,x,b);if(!t)return{notEnoughRoom:!0};P(t)}return{}}function Yc(e,t,i){const s=1<<t.z;let o=(e.x/ae+t.x)/s-i.mercCenter[0];const r=(e.y/ae+t.y)/s-i.mercCenter[1];o-=Math.round(o);const n=[o*ae,r*ae,ae/(2*Math.PI),1];return Se(n,n,i.invMatrix),[n[0],n[1],n[2]]}function Kc(e,t,i,s,o,r){let{x:n,y:a,z:l}=s.projectTilePoint(e.x,e.y,t);if(r){const[i,s,o]=Yc(e,t,r);n+=(i-n)*r.t,a+=(s-a)*r.t,l+=(o-l)*r.t}if(!o)return Gc(n,a,l,i);const[c,h,d]=o.getElevation(e,o.elevation,o.elevationFeature);return Gc(n+c,a+h,l+d,i)}function Jc(e,t,i,s,o,r,n,a,l){const c=Kc(e.sub(t)._unit()._add(e),a,o,n,r,l);return ve(c,i,c),ye(c,c),Wt(c,i,c,s)}function Qc(e,t,i,s,o,r,n,a,l,c,h){const d=r[e];if(d)return d;const u=Kc(t,c,n,l,a,h);return u[3]>0?r[e]=u:Jc(i,t,s,o,n,a,l,c,h)}function eh(e,t,i,s,o,r,n,a,l,c,h,d,u,_,p,f,g,v,y,x){const b=s?e-t:e+t;let w=b>0?1:-1,T=0;s&&(w*=-1,T=Math.PI),w<0&&(T+=Math.PI);let E=a+n+(w>0?0:1)|0,I=o,S=o,D=0,R=0;const C=Math.abs(b),A=[],L=[];let P=r,M=P,O=qt([]);for(;D+R<=C;){if(E+=w,E<a||E>=l)return null;S=I,M=P,A.push(S),_&&L.push(M),P=new m(c.getx(E),c.gety(E)),I=Qc(E,P,M,S,C-D+1,d,h,u,f,g.canonical,x),D+=R;const e=ve([],I,S),t=Zt(S,I);if(i&&t>0&&R>0&&Kt(O,e)/(R*t)<y)return null;R=t,O=e}p&&u&&(d[E]&&(I=Jc(M,P,S,C-D+1,h,u,f,g.canonical,x),R=Zt(S,I),O=ve([],I,S)),d[E]=I);const z=(C-D)/R,F=P.sub(M)._mult(z)._add(M),k=Wt([],S,O,z);let B=[0,0,1],N=O[0],U=O[1];if(v&&(B=f.upVector(g.canonical,F.x,F.y),0!==B[0]||0!==B[1]||1!==B[2])){const e=[B[2],0,-B[0]],t=Ht([],B,e);ye(e,e),ye(t,t),N=Kt(O,e),U=Kt(O,t)}if(i){const e=Ht([],B,O);ye(e,e),Wt(k,k,e,i*w)}const V=T+Math.atan2(U,N);return A.push(k),_&&L.push(F),{point:k,angle:V,path:A,tilePath:L,up:B}}function th(e,t){const i=t.length,s=i+4*e;t.resize(s),t.float32.fill(-1/0,4*i,4*s)}class ih{constructor(e,t){this.reset(e,t)}reset(e,t){this.points=e||[],this._distances=[0];for(let e=1;e<this.points.length;e++)this._distances[e]=this._distances[e-1]+this.points[e].dist(this.points[e-1]);this.length=this._distances.at(-1),this.padding=Math.min(t||0,.5*this.length),this.paddedLength=this.length-2*this.padding}lerp(e){if(1===this.points.length)return this.points[0];e=Ee(e,0,1);let t=1,i=this._distances[t];const s=e*this.paddedLength+this.padding;for(;i<s&&t<this._distances.length;)i=this._distances[++t];const o=t-1,r=this._distances[o],n=i-r,a=n>0?(s-r)/n:0;return this.points[o].mult(1-a).add(this.points[t].mult(a))}}const sh=100;class oh{constructor(e,t){this.gridRightBoundary=0,this.gridBottomBoundary=0,this.clippedSymbols=new Map,this.reset(e,t)}reset(e,t){const i=e.width+200,s=e.height+200;i!==this.gridRightBoundary||s!==this.gridBottomBoundary?(this.grid=new Jt(i,s,25),this.ignoredGrid=new Jt(i,s,25)):(this.grid.clear(),this.ignoredGrid.clear()),this.transform=e,this.fogState=t,this.pitchfactor=Math.cos(e._pitch)*e.cameraToCenterDistance,this.screenRightBoundary=e.width+sh,this.screenBottomBoundary=e.height+sh,this.gridRightBoundary=i,this.gridBottomBoundary=s,this.clippedSymbols.clear()}clearClippedSymbolsForBucket(e){this.clippedSymbols.delete(e)}markSymbolAsClipped(e,t){let i=this.clippedSymbols.get(e);i||(i=new Set,this.clippedSymbols.set(e,i)),i.add(t)}placeCollisionBox(e,t,i,s,o,r,n,a,l,c,h){let d=i.projectedAnchorX,u=i.projectedAnchorY,_=i.projectedAnchorZ;const p=i.tileAnchorX,f=i.tileAnchorY,m=i.elevation,g=i.tileID,v=e.getProjection();if(m&&g){const[e,t,s]=v.upVector(g.canonical,i.tileAnchorX,i.tileAnchorY),o=v.upVectorScale(g.canonical,this.transform.center.lat,this.transform.worldSize).metersToTile;d+=e*m*o,u+=t*m*o,_+=s*m*o}const y="globe"===e.projection.name,x="globe"===e.projection.name?K(this.transform.zoom):0;if(g&&y&&x<1&&!r){const e=1<<g.canonical.z,t=Qt(p,f);ei(t,t,1/ae),ti(t,t,Qt(g.canonical.x,g.canonical.y)),ei(t,t,1/e),ii(t,t,Qt(s[0],s[1])),t[0]=si(t[0],-.5,.5),ei(t,t,ae);const i=oi(t[0],t[1],ae/(2*Math.PI),1);Se(i,i,o),d=J(d,i[0],x),u=J(u,i[1],x),_=J(_,i[2],x)}const b=this.projectAndGetPerspectiveRatio(c,d,u,_,i.tileID,"globe"===v.name||!!m||this.transform.pitch>0,v),w=l*b.perspectiveRatio,T=(i.x1*t+n.x-i.padding)*w+b.point.x,E=(i.y1*t+n.y-i.padding)*w+b.point.y,I=(i.x2*t+n.x+i.padding)*w+b.point.x,S=(i.y2*t+n.y+i.padding)*w+b.point.y,D=b.perspectiveRatio<=hi||b.occluded;return!this.isInsideGrid(T,E,I,S)||!a&&this.grid.hitTest(T,E,I,S,h)||D?{box:[],offscreen:!1,occluded:b.occluded}:{box:[T,E,I,S],offscreen:this.isOffscreen(T,E,I,S),occluded:!1}}placeCollisionCircles(e,t,i,s,o,r,n,a,l,c,h,d,u,_,p,f){const g=this.transform.elevation,v=e.getProjection(),y="road"===e.elevationType,x=!!g||y,b=ri.getAtTileOffsetFunc(f,this.transform.center.lat,this.transform.worldSize,v),w=new m(i.tileAnchorX,i.tileAnchorY),T=new m(i.tileAnchorX,i.tileAnchorY);let{x:E,y:I,z:S}=v.projectTilePoint(T.x,T.y,f.canonical),D=null;if(x){D=y&&e.hdExt?e.hdExt.makeRoadSymbolElevationParams(e,e.text,s,f,b,g,v,this.transform.center.lat,this.transform.worldSize):{getElevation:b,elevation:g,elevationFeature:null};const[t,i,o]=D.getElevation(w,g,D.elevationFeature);E+=t,I+=i,S+=o}const R="globe"===v.name,C=this.projectAndGetPerspectiveRatio(a,E,I,S,f,R||!!g||this.transform.pitch>0,v),{perspectiveRatio:A}=C,L=(d?n/A:n*A)/ui,P=Gc(E,I,S,l),M=i.lineOffsetX*L,O=i.lineOffsetY*L,z=le(e.layers[0].layout.get("text-max-angle")),F=Math.cos(z),k=C.signedDistanceFromCamera>0?Hc(L,r,M,O,y&&1===i.flipState,P,T,i,o,l,{},x&&!d?D:null,d&&x,v,f,d,F):null;if(!k||C.occluded)return{circles:[],offscreen:!0,collisionDetected:!1,occluded:C.occluded};const{first:B,last:N}=k,U=function(e,t){const i=[];for(let t=e.path.length-1;t>=1;t--)i.push(e.path[t]);for(let e=1;e<t.path.length;e++)i.push(t.path[e]);return i}(B,N);c&&function(e,t,i,s,o){const r=i.path.length;for(let n=0;n<e.length;n++){const a=e[n];let l=a[2];o&&(l=o.getElevation(n<r-1?i.tilePath[r-1-n]:s.tilePath[n-r+2],o.elevation,o.elevationFeature)[2]);const c=Gc(a[0],a[1],l,t);if(c[3]<=0)return void(e.length=0);e[n]=c}}(U,c,B,N,x&&!R?D:null);let V=[];if(U.length>0){let e=1/0,t=-1/0,i=1/0,s=-1/0;for(const o of U)e=Math.min(e,o[0]),i=Math.min(i,o[1]),t=Math.max(t,o[0]),s=Math.max(s,o[1]);const o=-100,r=-100,n=this.screenRightBoundary,a=this.screenBottomBoundary;if(t>=o&&e<=n&&s>=r&&i<=a){const l=[];for(const e of U)l.push(new m(e[0],e[1]));V=[l],(e<o||t>n||i<r||s>a)&&(V=ni(V,o,r,n,a))}}return this.placeCirclesAlongThePath(V,.5*_*A+p,t,h,u)}placeCirclesAlongThePath(e,t,i,s,o){const r=2.5*t,n=[];let a=!1,l=!1,c=!0;const h=new ih;for(const d of e){h.reset(d,.25*t);const e=h.length<=.5*t?1:Math.ceil(h.paddedLength/r)+1;for(let r=0;r<e;r++){const d=r/Math.max(e-1,1),u=h.lerp(d),_=u.x+sh,p=u.y+sh;n.push(_,p,t,0);const f=_-t,m=p-t,g=_+t,v=p+t;if(c=c&&this.isOffscreen(f,m,g,v),l=l||this.isInsideGrid(f,m,g,v),!i&&this.grid.hitTestCircle(_,p,t,o)){if(!s)return{circles:[],offscreen:!1,collisionDetected:!0,occluded:!1};a=!0}}}return{circles:!s&&a||!l?[]:n,offscreen:c,collisionDetected:a,occluded:!1}}queryRenderedSymbols(e){if(0===e.length||0===this.grid.keysLength()&&0===this.ignoredGrid.keysLength())return{};const t=[];let i=1/0,s=1/0,o=-1/0,r=-1/0;for(const n of e){const e=new m(n.x+sh,n.y+sh);i=Math.min(i,e.x),s=Math.min(s,e.y),o=Math.max(o,e.x),r=Math.max(r,e.y),t.push(e)}const n=this.grid.query(i,s,o,r).concat(this.ignoredGrid.query(i,s,o,r)),a={},l={};for(const e of n){const i=e.key;if(void 0===a[i.bucketInstanceId]&&(a[i.bucketInstanceId]={}),a[i.bucketInstanceId][i.featureIndex])continue;const s=this.clippedSymbols.get(i.bucketInstanceId);if(s&&s.has(i.featureIndex))continue;const o=[new m(e.x1,e.y1),new m(e.x2,e.y1),new m(e.x2,e.y2),new m(e.x1,e.y2)];ai(t,o)&&(a[i.bucketInstanceId][i.featureIndex]=!0,void 0===l[i.bucketInstanceId]&&(l[i.bucketInstanceId]=[]),l[i.bucketInstanceId].push(i.featureIndex))}return l}insertCollisionBox(e,t,i,s,o){(t?this.ignoredGrid:this.grid).insert({bucketInstanceId:i,featureIndex:s,collisionGroupID:o},e[0],e[1],e[2],e[3])}insertCollisionCircles(e,t,i,s,o){const r=t?this.ignoredGrid:this.grid,n={bucketInstanceId:i,featureIndex:s,collisionGroupID:o};for(let t=0;t<e.length;t+=4)r.insertCircle(n,e[t],e[t+1],e[t+2])}projectAndGetPerspectiveRatio(e,t,i,s,o,r,n){const a=[t,i,s,1];let l=!1;s||this.transform.pitch>0?(Se(a,a,e),this.fogState&&o&&"globe"!==n.name&&(l=li(this.fogState,t,i,s,o.toUnwrapped(),this.transform)>di)):Vt(a,a,e);const c=a[3];return{point:new m((a[0]/c+1)/2*this.transform.width+sh,(-a[1]/c+1)/2*this.transform.height+sh),perspectiveRatio:Math.min(.5+this.transform.getCameraToCenterDistance(n)/c*.5,1.5),signedDistanceFromCamera:c,occluded:r&&a[2]>c||l}}isOffscreen(e,t,i,s){return i<sh||e>=this.screenRightBoundary||s<sh||t>this.screenBottomBoundary}isInsideGrid(e,t,i,s){return i>=0&&e<this.gridRightBoundary&&s>=0&&t<this.gridBottomBoundary}getViewportMatrix(){const e=ci([]);return At(e,e,[-100,-100,0]),e}}class rh{constructor(e,t,i,s){this.opacity=e?Math.max(0,Math.min(1,e.opacity+(e.placed?t:-t))):s&&i?1:0,this.placed=i}isHidden(){return 0===this.opacity&&!this.placed}}class nh{constructor(e,t,i,s,o,r=!1){this.text=new rh(e?e.text:null,t,i,o),this.icon=new rh(e?e.icon:null,t,s,o),this.clipped=r}isHidden(){return this.text.isHidden()&&this.icon.isHidden()}}class ah{constructor(e,t,i,s=!1,o=!1){this.text=e,this.icon=t,this.skipFade=i,this.clipped=s,this.dynamicFiltered=o}}class lh{constructor(){this.invProjMatrix=Bt(),this.viewportMatrix=Bt(),this.circles=[]}}class ch{constructor(e,t,i,s,o){this.bucketInstanceId=e,this.featureIndex=t,this.sourceLayerIndex=i,this.bucketIndex=s,this.tileID=o}}class hh{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 dh(e,t,i,s,o){const{horizontalAlign:r,verticalAlign:n}=mi(e),a=-(r-.5)*t,l=-(n-.5)*i,c=vi(e,s);return new m(a+c[0]*o,l+c[1]*o)}function uh(e,t,i,s,o){const r=new m(e,t);return i&&r._rotate(s?o:-o),r}function _h(e,t,i,s){const{leftJustifiedTextSymbolIndex:o,centerJustifiedTextSymbolIndex:r,rightJustifiedTextSymbolIndex:n,verticalPlacedTextSymbolIndex:a,crossTileID:l}=i,c=yi(t),h=s===Gt.vertical?a:"left"===c?o:"center"===c?r:"right"===c?n:-1;o>=0&&(e.text.placedSymbolArray.get(o).crossTileID=h>=0&&o!==h?0:l),r>=0&&(e.text.placedSymbolArray.get(r).crossTileID=h>=0&&r!==h?0:l),n>=0&&(e.text.placedSymbolArray.get(n).crossTileID=h>=0&&n!==h?0:l),a>=0&&(e.text.placedSymbolArray.get(a).crossTileID=h>=0&&a!==h?0:l)}function ph(e,t,i){const s=t===Gt.horizontal||t===Gt.horizontalOnly?t:0,o=t===Gt.vertical?t:0,{leftJustifiedTextSymbolIndex:r,centerJustifiedTextSymbolIndex:n,rightJustifiedTextSymbolIndex:a,verticalPlacedTextSymbolIndex:l}=i,c=e.text.placedSymbolArray;r>=0&&(c.get(r).placedOrientation=s),n>=0&&(c.get(n).placedOrientation=s),a>=0&&(c.get(a).placedOrientation=s),l>=0&&(c.get(l).placedOrientation=o)}class fh{constructor(e,t,i,s,o,r,n){this.transform=e.clone(),this.projection=e.projection.name,n instanceof oh?(n.reset(this.transform,o),this.collisionIndex=n):this.collisionIndex=new oh(this.transform,o),this.buildingIndex=r,this.frontCutoffStart=0,this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=t,this.retainedQueryData={},this.collisionGroups=new hh(i),this.collisionCircleArrays={},this.dynamicFilters=new Map,this.prevPlacement=s,s&&(s.prevPlacement=void 0),this.placedOrientations={},this.lastReplacementSourceUpdateTime=0}getBucketParts(e,t,i,s,o=1){const r=i.getBucket(t),n=i.latestFeatureIndex;if(!r||!n||t.fqid!==r.layerIds[0])return;const a=r.layers[0].layout,l=r.layers[0].paint,c=i.collisionBoxArray,h=Math.pow(2,this.transform.zoom-i.tileID.overscaledZ),d=i.tileSize/ae,u=i.tileID.toUnwrapped();this.transform.setProjection(r.projection);const _=_i(i.tileID,r.getProjection(),this.transform,this.projection),p="map"===a.get("text-pitch-alignment"),f="map"===a.get("text-rotation-alignment");t.compileFilter(t.options);const m=t.dynamicFilter(),g=t.dynamicFilterNeedsFeature(),v=t.dynamicFilterNeedsGeometry(),y=this.transform.calculatePixelsToTileUnitsMatrix(i),x=Vc(_,i.tileID.canonical,p,f,this.transform,r.getProjection(),y);let b=null;const w=r.getProjection().createInversionMatrix(this.transform,i.tileID.canonical);if(p){const e=jc(_,i.tileID.canonical,p,f,this.transform,r.getProjection(),y);b=Ie([],this.transform.labelPlaneMatrix,e)}let T=null;if(m&&i.latestFeatureIndex){this.dynamicFilters.set(t.fqid,m);const e=this.prevPlacement;T={unwrappedTileID:u,canReusePrevResult:!!e&&!!e.retainedQueryData[r.bucketInstanceId]&&e.dynamicFilters.get(t.fqid)===m&&this.transform.equals(e.transform)&&this.transform.cameraWorldSize===e.transform.cameraWorldSize,dynamicFilter:m,dynamicFilterNeedsFeature:g,needGeometry:v}}this.retainedQueryData[r.bucketInstanceId]=new ch(r.bucketInstanceId,n,r.sourceLayerIndex,r.index,i.tileID);const[E,I]=r.layers[0].layout.get("text-size-scale-range"),S=Ee(o,E,I),[D,R]=a.get("icon-size-scale-range"),C=Ee(o,D,R),A={bucket:r,layout:a,paint:l,posMatrix:_,invMatrix:w,mercatorCenter:[Ae(this.transform.center.lng),Pe(this.transform.center.lat)],textLabelPlaneMatrix:x,labelToScreenMatrix:b,clippingData:T,scale:h,textPixelRatio:d,holdingForFade:i.holdingForFade(),collisionBoxArray:c,partiallyEvaluatedTextSize:jt(r.textSizeData,this.transform.zoom,S),partiallyEvaluatedIconSize:jt(r.iconSizeData,this.transform.zoom,C),collisionGroup:this.collisionGroups.get(r.sourceID),latestFeatureIndex:i.latestFeatureIndex};if(s)for(const t of r.sortKeyRanges){const{sortKey:i,symbolInstanceStart:s,symbolInstanceEnd:o}=t;e.push({sortKey:i,symbolInstanceStart:s,symbolInstanceEnd:o,parameters:A})}else e.push({symbolInstanceStart:0,symbolInstanceEnd:r.symbolInstances.length,parameters:A})}placeLayerBucketPart(e,t,i,s=1){const{bucket:o,layout:r,paint:n,posMatrix:a,textLabelPlaneMatrix:l,labelToScreenMatrix:c,clippingData:h,textPixelRatio:d,mercatorCenter:u,invMatrix:p,holdingForFade:f,collisionBoxArray:g,partiallyEvaluatedTextSize:v,partiallyEvaluatedIconSize:y,collisionGroup:x,latestFeatureIndex:b}=e.parameters,w=r.get("text-optional"),T=r.get("icon-optional"),E=r.get("text-allow-overlap"),I=r.get("icon-allow-overlap"),S="map"===r.get("text-rotation-alignment"),D="map"===r.get("icon-rotation-alignment"),R="map"===r.get("text-pitch-alignment"),C=n.get("symbol-z-offset"),A="sea"===r.get("symbol-elevation-reference"),L=r.get("symbol-placement"),P=r.get("text-variable-anchor"),M=S&&"point"!==L,O=D&&"point"!==L,z=P&&o.hasTextData(),F=o.hasIconTextFit()&&z&&o.hasIconData();this.transform.setProjection(o.projection);const k=z||M,B=O||F;let N=E&&(I||!o.hasIconData()||T),U=I&&(E||!o.hasTextData()||w);const V=!C.isConstant(),j=(e,s)=>{const{crossTileID:n,numVerticalGlyphVertices:_}=e,D=o.getCollisionArrays(g,e);let L=null;const M=h&&h.canReusePrevResult?this.prevPlacement.placements[n]:void 0;if(M&&M.dynamicFiltered)return this.placements[n]=new ah(!1,!1,!1,!0,!0),void t.add(n);if(h&&h.dynamicFilterNeedsFeature&&!M||V){const t=this.retainedQueryData[o.bucketInstanceId],i=b.loadFeature({featureIndex:e.featureIndex,bucketIndex:t.bucketIndex,sourceLayerIndex:t.sourceLayerIndex,layoutVertexArrayOffset:0}),s=i.properties?i.properties.worldview:null;if(o.localizable&&o.worldview&&"string"==typeof s)if("all"===s)i.properties.$localized=!0;else{if(!s.split(",").includes(o.worldview))return;i.properties.$localized=!0,i.properties.worldview=o.worldview}L=h&&h.needGeometry?ut(i,!0):i}if(h&&!M&&!(0,h.dynamicFilter)({zoom:this.transform.zoom,pitch:this.transform.pitch,worldview:o.worldview},L,this.retainedQueryData[o.bucketInstanceId].tileID.canonical,new m(e.tileAnchorX,e.tileAnchorY),this.transform.calculateDistanceTileData(h.unwrappedTileID)))return this.placements[n]=new ah(!1,!1,!1,!0,!0),void t.add(n);const O=C.evaluate(L,{});if((e.zOffset||0)+(O||0)>0&&this.frontCutoffStart>0){const i=2*this.frontCutoffStart-1,s=[e.tileAnchorX,e.tileAnchorY,0,1],o=Se(fi(),s,a);if(o[1]/o[3]<i)return this.placements[n]=new ah(!1,!1,!1,!0),void t.add(n)}if(t.has(n))return;if(f)return void(this.placements[n]=new ah(!1,!1,!1));let z=!1,F=!1,j=!0,G=!1,q=!1,Z=null,W={box:null,offscreen:null,occluded:null},H={box:null},$=null,X=null,Y=null,K=0,J=0,Q=0;D.textFeatureIndex?K=D.textFeatureIndex:e.useRuntimeCollisionCircles&&(K=e.featureIndex),D.verticalTextFeatureIndex&&(J=D.verticalTextFeatureIndex);const ee=t=>{t.tileID=this.retainedQueryData[o.bucketInstanceId].tileID;const i=this.transform.elevation;if("road"===o.elevationType)t.elevation=A?O:O+ri.getAtTileOffset(t.tileID,new m(t.tileAnchorX,t.tileAnchorY),i,null);else{const s=o.hdExt?o.hdExt.elevationFeatures[e.elevationFeatureIndex]:void 0;t.elevation=A?O:O+ri.getAtTileOffset(t.tileID,new m(t.tileAnchorX,t.tileAnchorY),i,s)}t.elevation+=e.zOffset},te=D.textBox;if(te){ee(te);const t=t=>{let i=Gt.horizontal;if(o.allowVerticalPlacement&&!t&&this.prevPlacement){const t=this.prevPlacement.placedOrientations[n];t&&(this.placedOrientations[n]=t,i=t,ph(o,i,e))}return i},i=(e,t)=>{if(o.allowVerticalPlacement&&_>0&&D.verticalTextBox){for(const i of o.writingModes)if(i===Gt.vertical?(W=t(),H=W):W=e(),W&&W.box&&W.box.length)break}else W=e()};if(P){let r=P;if(this.prevPlacement&&this.prevPlacement.variableOffsets[n]){const e=this.prevPlacement.variableOffsets[n];r.indexOf(e.anchor)>0&&(r=r.filter(t=>t!==e.anchor),r.unshift(e.anchor))}const l=(t,i,n)=>{const l=o.getSymbolInstanceTextSize(v,e,this.transform.zoom,s),c=(t.x2-t.x1)*l+2*t.padding,h=(t.y2-t.y1)*l+2*t.padding,_=e.hasIconTextFit&&!I?i:null;_&&ee(_);let f={box:[],offscreen:!1,occluded:!1};const m=E?2*r.length:r.length;for(let i=0;i<m;++i){const m=this.attemptAnchorPlacement(r[i%r.length],t,u,p,k,c,h,l,S,R,d,a,x,i>=r.length,e,s,o,n,_,v,y);if(m&&(f=m.placedGlyphBoxes,f&&f.box&&f.box.length)){z=!0,Z=m.shift;break}}return f};i(()=>l(te,D.iconBox,Gt.horizontal),()=>{const e=D.verticalTextBox;return e&&ee(e),o.allowVerticalPlacement&&!(W&&W.box&&W.box.length)&&_>0&&e?l(e,D.verticalIconBox,Gt.vertical):{box:null,offscreen:null,occluded:null}}),W&&(z=W.box,j=W.offscreen,G=W.occluded);const c=t(!(!W||!W.box));if(!z&&this.prevPlacement){const t=this.prevPlacement.variableOffsets[n];t&&(this.variableOffsets[n]=t,_h(o,t.anchor,e,c))}}else{const r=(t,i)=>{const r=o.getSymbolInstanceTextSize(v,e,this.transform.zoom,s),l=this.collisionIndex.placeCollisionBox(o,r,t,u,p,k,new m(0,0),E,d,a,x.predicate);return l&&l.box&&l.box.length&&(ph(o,i,e),this.placedOrientations[n]=i),l};i(()=>r(te,Gt.horizontal),()=>{const e=D.verticalTextBox;return o.allowVerticalPlacement&&_>0&&e?(ee(e),r(e,Gt.vertical)):{box:null,offscreen:null,occluded:null}}),t(!!(W&&W.box&&W.box.length))}}if($=W,z=$&&$.box&&$.box.length>0,j=$&&$.offscreen,G=$&&$.occluded,e.useRuntimeCollisionCircles){const t=e.centerJustifiedTextSymbolIndex>=0?e.centerJustifiedTextSymbolIndex:e.verticalPlacedTextSymbolIndex,s=o.text.placedSymbolArray.get(t),n=Yt(o.textSizeData,v,s),h=r.get("text-padding");X=this.collisionIndex.placeCollisionCircles(o,E,s,t,o.lineVertexArray,o.glyphOffsetArray,n,a,l,c,i,R,x.predicate,e.collisionCircleDiameter*n/ui,h,this.retainedQueryData[o.bucketInstanceId].tileID),z=E||X.circles.length>0&&!X.collisionDetected,j=j&&X.offscreen,G=X.occluded}if(D.iconFeatureIndex&&(Q=D.iconFeatureIndex),D.iconBox){const t=t=>{ee(t);const i=e.hasIconTextFit&&Z?uh(Z.x,Z.y,S,R,this.transform.angle):new m(0,0),s=o.getSymbolInstanceIconSize(y,this.transform.zoom,e.placedIconSymbolIndex);return this.collisionIndex.placeCollisionBox(o,s,t,u,p,B,i,I,d,a,x.predicate)};H&&H.box&&H.box.length&&D.verticalIconBox?(Y=t(D.verticalIconBox),F=Y.box.length>0):(Y=t(D.iconBox),F=Y.box.length>0),j=j&&Y.offscreen,q=Y.occluded}const ie=w||0===e.numHorizontalGlyphVertices&&0===_,se=T||0===e.numIconVertices;if(ie||se?se?ie||(F=F&&z):z=F&&z:F=z=F&&z,z&&$&&$.box&&this.collisionIndex.insertCollisionBox($.box,r.get("text-ignore-placement"),o.bucketInstanceId,H&&H.box&&J?J:K,x.ID),F&&Y&&this.collisionIndex.insertCollisionBox(Y.box,r.get("icon-ignore-placement"),o.bucketInstanceId,Q,x.ID),X&&(z&&this.collisionIndex.insertCollisionCircles(X.circles,r.get("text-ignore-placement"),o.bucketInstanceId,K,x.ID),i)){const e=o.bucketInstanceId;let t=this.collisionCircleArrays[e];void 0===t&&(t=this.collisionCircleArrays[e]=new lh);for(let e=0;e<X.circles.length;e+=4)t.circles.push(X.circles[e+0]),t.circles.push(X.circles[e+1]),t.circles.push(X.circles[e+2]),t.circles.push(X.collisionDetected?1:0)}const oe="globe"!==o.projection.name;N=N&&(oe||!G),U=U&&(oe||!q),this.placements[n]=new ah(z||N,F||U,j||o.justReloaded),t.add(n)},G=this.retainedQueryData[o.bucketInstanceId].tileID;if("offset"===o.elevationType&&this.buildingIndex&&this.buildingIndex.updateZOffset(o,G),"road"===o.elevationType&&o.hdExt&&o.hdExt.updateRoadElevation(o,G.canonical),o.updateZOffset(),o.sortFeaturesByY){const e=o.getSortedSymbolIndexes(this.transform.angle);for(let t=e.length-1;t>=0;--t){const i=e[t];j(o.symbolInstances.get(i),i)}o.hasAnyZOffset&&_(`${o.layerIds[0]} layer symbol-z-elevate: symbols are not sorted by elevation if symbol-z-order is evaluated to viewport-y`)}else if(o.hasAnyZOffset){const e=o.getSortedIndexesByZOffset();for(let t=0;t<e.length;++t){const i=e[t];j(o.symbolInstances.get(i),i)}}else for(let t=e.symbolInstanceStart;t<e.symbolInstanceEnd;t++)j(o.symbolInstances.get(t),t);if(i&&o.bucketInstanceId in this.collisionCircleArrays){const e=this.collisionCircleArrays[o.bucketInstanceId];Tt(e.invProjMatrix,a),e.viewportMatrix=this.collisionIndex.getViewportMatrix()}o.justReloaded=!1}attemptAnchorPlacement(e,t,i,s,o,r,n,a,l,c,h,d,u,_,p,f,m,g,v,y,x){const{textOffset0:b,textOffset1:w,crossTileID:T}=p,E=[b,w],I=dh(e,r,n,E,a),S=this.collisionIndex.placeCollisionBox(m,a,t,i,s,o,uh(I.x,I.y,l,c,this.transform.angle),_,h,d,u.predicate);if(v){const e=m.getSymbolInstanceIconSize(x,this.transform.zoom,p.placedIconSymbolIndex);if(0===this.collisionIndex.placeCollisionBox(m,e,v,i,s,o,uh(I.x,I.y,l,c,this.transform.angle),_,h,d,u.predicate).box.length)return}if(S.box.length>0){let t;return this.prevPlacement&&this.prevPlacement.variableOffsets[T]&&this.prevPlacement.placements[T]&&this.prevPlacement.placements[T].text&&(t=this.prevPlacement.variableOffsets[T].anchor),this.variableOffsets[T]={textOffset:E,width:r,height:n,anchor:e,textScale:a,prevAnchor:t},_h(m,e,p,g),m.allowVerticalPlacement&&(ph(m,g,p),this.placedOrientations[T]=g),{shift:I,placedGlyphBoxes:S}}}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 s=t?t.symbolFadeChange(e):1,o=t?t.opacities:{},r=t?t.variableOffsets:{},n=t?t.placedOrientations:{};for(const e in this.placements){const t=this.placements[e],r=o[e];r?(this.opacities[e]=new nh(r,s,t.text,t.icon,null,t.clipped),i=i||t.text!==r.text.placed||t.icon!==r.icon.placed):(this.opacities[e]=new nh(null,s,t.text,t.icon,t.skipFade,t.clipped),i=i||t.text||t.icon)}for(const e in o){const t=o[e];if(!this.opacities[e]){const o=new nh(t,s,!1,!1);o.isHidden()||(this.opacities[e]=o,i=i||t.text.placed||t.icon.placed)}}for(const e in r)this.variableOffsets[e]||!this.opacities[e]||this.opacities[e].isHidden()||(this.variableOffsets[e]=r[e]);for(const e in n)this.placedOrientations[e]||!this.opacities[e]||this.opacities[e].isHidden()||(this.placedOrientations[e]=n[e]);i?this.lastPlacementChangeTime=e:"number"!=typeof this.lastPlacementChangeTime&&(this.lastPlacementChangeTime=t?t.lastPlacementChangeTime:e)}updateLayerOpacities(e,t,i,s,o=!1,r=1){s&&(this.lastReplacementSourceUpdateTime=s.updateTime);const n=new Set;for(const a of t){const t=a.getBucket(e);if(t&&a.latestFeatureIndex&&e.fqid===t.layerIds[0]&&(this.updateBucketOpacities(t,n,a,a.collisionBoxArray,i,s,a.tileID,e.scope),"offset"===t.elevationType&&this.buildingIndex&&this.buildingIndex.updateZOffset(t,a.tileID),"road"===t.elevationType&&t.hdExt&&t.hdExt.updateRoadElevation(t,a.tileID.canonical),t.updateZOffset(),o&&a.collisionBoxArray)){const e=t.layers[0].layout,[i,s]=e.get("text-size-scale-range"),[o,n]=e.get("icon-size-scale-range"),l=Ee(r,i,s),c=Ee(r,o,n);t.updateCollisionDebugBuffers(this.transform.zoom,a.collisionBoxArray,l,c)}}}updateBucketOpacities(e,t,i,s,o,r,n,a){e.hasTextData()&&e.text.opacityVertexArray.clear(),e.hasIconData()&&e.icon.opacityVertexArray.clear(),e.hasIconCollisionBoxData()&&e.iconCollisionBox.collisionVertexArray.clear(),e.hasTextCollisionBoxData()&&e.textCollisionBox.collisionVertexArray.clear();const l=e.layers[0].layout,c=new nh(null,0,!1,!1,!0),h=l.get("text-allow-overlap"),d=l.get("icon-allow-overlap"),u=!!s&&(e.hasIconCollisionBoxData()||e.hasTextCollisionBoxData()),_=new nh(null,0,h&&(d||!e.hasIconData()||l.get("icon-optional")),d&&(h||!e.hasTextData()||l.get("text-optional")),!0);let p=!1,f=!1,m=0;r&&e.updateReplacement(n,r),this.collisionIndex.clearClippedSymbolsForBucket(e.bucketInstanceId);for(let s=0;s<e.symbolInstances.length;s++){const l=e.symbolInstances.get(s),{numHorizontalGlyphVertices:h,numVerticalGlyphVertices:d,crossTileID:g,numIconVertices:v,tileAnchorX:y,tileAnchorY:x}=l,b=t.has(g);let w=this.opacities[g];b?w=c:w||(w=_,this.opacities[g]=w),t.add(g);const T=h>0||d>0,E=v>0,I=this.placedOrientations[g],S=I===Gt.vertical,D=I===Gt.horizontal||I===Gt.horizontalOnly;!T&&!E||w.isHidden()||m++;const R=(T||E)&&!!r&&pi(e.activeReplacements,y,x,n.canonical,o,gi.Symbol,a);if(R&&this.collisionIndex.markSymbolAsClipped(e.bucketInstanceId,l.featureIndex),T){const t=R?Sh:Ih(w.text);mh(e.text,h,S?Sh:t)&&(p=!0),mh(e.text,d,D?Sh:t)&&(p=!0);const i=w.text.isHidden(),{leftJustifiedTextSymbolIndex:s,centerJustifiedTextSymbolIndex:o,rightJustifiedTextSymbolIndex:r,verticalPlacedTextSymbolIndex:n}=l,a=e.text.placedSymbolArray,c=i||S?1:0;s>=0&&(a.get(s).hidden=c),o>=0&&(a.get(o).hidden=c),r>=0&&(a.get(r).hidden=c),n>=0&&(a.get(n).hidden=i||D?1:0);const u=this.variableOffsets[g];u&&_h(e,u.anchor,l,I);const _=this.placedOrientations[g];_&&(_h(e,"left",l,_),ph(e,_,l))}if(E){const t=R?Sh:Ih(w.icon),{placedIconSymbolIndex:i,verticalPlacedIconSymbolIndex:s}=l,o=e.icon.placedSymbolArray,r=w.icon.isHidden()?1:0;i>=0&&(mh(e.icon,v,S?Sh:t)&&(f=!0),o.get(i).hidden=r),s>=0&&(mh(e.icon,l.numVerticalIconVertices,D?Sh:t)&&(f=!0),o.get(s).hidden=r)}u&&this.updateCollisionBoxes(e,l,w,S,D,i)}if(e.fullyClipped=0===m,e.sortFeatures(this.transform.angle),this.retainedQueryData[e.bucketInstanceId]&&(this.retainedQueryData[e.bucketInstanceId].featureSortOrder=e.featureSortOrder),p&&e.hasTextData()&&e.text.opacityVertexBuffer&&e.text.opacityVertexBuffer.updateData(e.text.opacityVertexArray),f&&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.bucketInstanceId in this.collisionCircleArrays){const t=this.collisionCircleArrays[e.bucketInstanceId];e.placementInvProjMatrix=t.invProjMatrix,e.placementViewportMatrix=t.viewportMatrix,e.collisionCircleArray=t.circles,delete this.collisionCircleArrays[e.bucketInstanceId]}}updateCollisionBoxes(e,t,i,s,o,r){const n=e.layers[0].layout,a=e.layers[0].paint.get("symbol-z-offset"),l="sea"===n.get("symbol-elevation-reference");let c=null;const h=this.retainedQueryData[e.bucketInstanceId];!a.isConstant()&&h&&(c=r.latestFeatureIndex.loadFeature({featureIndex:t.featureIndex,bucketIndex:h.bucketIndex,sourceLayerIndex:h.sourceLayerIndex,layoutVertexArrayOffset:0}));const d=a.evaluate(c,{}),u=t.textBoxStartIndex<t.textBoxEndIndex,_=t.verticalTextBoxStartIndex<t.verticalTextBoxEndIndex,p=t.iconBoxStartIndex<t.iconBoxEndIndex,f=t.verticalIconBoxStartIndex<t.verticalIconBoxEndIndex;let g=new m(0,0),v=!0;if(u||_){if(n.get("text-variable-anchor")){const e=this.variableOffsets[t.crossTileID];e?(g=dh(e.anchor,e.width,e.height,e.textOffset,e.textScale),"map"===n.get("text-rotation-alignment")&&g._rotate("map"===n.get("text-pitch-alignment")?this.transform.angle:-this.transform.angle)):v=!1}e.layers[0].dynamicFilter()&&(v=!i.clipped),u&&gh(e.textCollisionBox.collisionVertexArray,i.text.placed,!v||s,d,l,g.x,g.y),_&&gh(e.textCollisionBox.collisionVertexArray,i.text.placed,!v||o,d,l,g.x,g.y)}const y=v&&!o&&f,x=t.hasIconTextFit?g.x:0,b=t.hasIconTextFit?g.y:0;p&&gh(e.iconCollisionBox.collisionVertexArray,i.icon.placed,y,d,l,x,b),f&&gh(e.iconCollisionBox.collisionVertexArray,i.icon.placed,!y,d,l,x,b)}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 e-this.lastPlacementChangeTime<this.fadeDuration}stillRecent(e,t){const i=this.zoomAtLastRecencyCheck===t?1-this.zoomAdjustment(t):1;return this.zoomAtLastRecencyCheck=t,this.commitTime+this.fadeDuration*i>e}isStale(){return this.stale}setStale(){this.stale=!0}}function mh(e,t,i){const s=e.opacityVertexArray;let o=!1;for(let e=0;e<t/4;e++)s.uint32[s.length]!==i&&(o=!0),s.emplaceBack(i);return o}function gh(e,t,i,s,o,r,n){e.emplaceBack(t?1:0,i?1:0,r||0,n||0,s,o?1:0),e.emplaceBack(t?1:0,i?1:0,r||0,n||0,s,o?1:0),e.emplaceBack(t?1:0,i?1:0,r||0,n||0,s,o?1:0),e.emplaceBack(t?1:0,i?1:0,r||0,n||0,s,o?1:0)}const vh=Math.pow(2,25),yh=Math.pow(2,24),xh=Math.pow(2,17),bh=Math.pow(2,16),wh=Math.pow(2,9),Th=Math.pow(2,8),Eh=Math.pow(2,1);function Ih(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*vh+t*yh+i*xh+t*bh+i*wh+t*Th+i*Eh+t}const Sh=0;class Dh{constructor(e){this._sortAcrossTiles="viewport-y"!==e.layout.get("symbol-z-order")&&void 0!==e.layout.get("symbol-sort-key").constantOr(1),this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs=new Set,this._bucketParts=[]}continuePlacement(e,t,i,s,o,r){const n=this._bucketParts;for(;this._currentTileIndex<e.length;)if(t.getBucketParts(n,s,e[this._currentTileIndex],this._sortAcrossTiles,r),this._currentTileIndex++,o())return!0;for(this._sortAcrossTiles&&(this._sortAcrossTiles=!1,n.sort((e,t)=>e.sortKey-t.sortKey));this._currentPartIndex<n.length;)if(t.placeLayerBucketPart(n[this._currentPartIndex],this._seenCrossTileIDs,i,r),this._currentPartIndex++,o())return!0;return!1}}class Rh{constructor(){this._retiredCI=null}startNewPlacement(e,t,i,s,o,r,n,a){return this.placement=new fh(e,s,o,r,n,a,this._retiredCI),this._retiredCI=null,this._currentPlacementIndex=t.length-1,this._forceFullPlacement=!1,this._showCollisionBoxes=i,this._fadeDuration=s,this._done=!1,this._inProgressLayer=null,this}requestFullPlacement(){this._forceFullPlacement=!0}isFullPlacementRequested(){return this._forceFullPlacement}setStale(){this.placement&&(this.placement.stale=!0)}isStale(){return!!this.placement&&this.placement.stale}isDone(){return this._done}continuePlacement(e,t,i,s,o){const r=T.now(),n=()=>!this.isFullPlacementRequested()&&0!==this._fadeDuration&&T.now()-r>2;for(;this._currentPlacementIndex>=0;){const r=t[e[this._currentPlacementIndex]],a=this.placement.collisionIndex.transform.zoom;if("symbol"===r.type&&"none"!==r.visibility&&(!r.minzoom||r.minzoom<=a)&&(!r.maxzoom||r.maxzoom>a)){const e=r,t=e.layout.get("symbol-z-elevate"),a=void 0!==e.layout.get("symbol-sort-key").constantOr(1),l=e.layout.get("symbol-z-order"),c="viewport-y"===l||"auto"===l&&!("viewport-y"!==l&&a),h=e.layout.get("text-allow-overlap")||e.layout.get("icon-allow-overlap")||e.layout.get("text-ignore-placement")||e.layout.get("icon-ignore-placement"),d=c&&h,u=this._inProgressLayer=this._inProgressLayer||new Dh(e),_=C(r.source,r.scope);if(u.continuePlacement(t||d?s[_]:i[_],this.placement,this._showCollisionBoxes,r,n,o))return;delete this._inProgressLayer}this._currentPlacementIndex--}this._forceFullPlacement=!1,this._done=!0}commit(e){return this._retiredCI=this.placement.prevPlacement?this.placement.prevPlacement.collisionIndex:null,this.placement.commit(e),this.placement}}const Ch=512/ae/2;class Ah{constructor(e,t,i){this.tileID=e,this.bucketInstanceId=i,this.index=new Lt(t.length,16,Int32Array),this.keys=[],this.crossTileIDs=[];const s=e.canonical.x*ae,o=e.canonical.y*ae;for(let e=0;e<t.length;e++){const{key:i,crossTileID:r,tileAnchorX:n,tileAnchorY:a}=t.get(e),l=Math.floor((s+n)*Ch),c=Math.floor((o+a)*Ch);this.index.add(l,c),this.keys.push(i),this.crossTileIDs.push(r)}this.index.finish()}findMatches(e,t,i){const s=this.tileID.canonical.z<t.canonical.z?1:Math.pow(2,this.tileID.canonical.z-t.canonical.z),o=Ch/Math.pow(2,t.canonical.z-this.tileID.canonical.z),r=t.canonical.x*ae,n=t.canonical.y*ae;for(let t=0;t<e.length;t++){const a=e.get(t);if(a.crossTileID)continue;const{key:l,tileAnchorX:c,tileAnchorY:h}=a,d=Math.floor((r+c)*o),u=Math.floor((n+h)*o),_=this.index.range(d-s,u-s,d+s,u+s).sort((e,t)=>e-t);for(const e of _){const t=this.crossTileIDs[e];if(this.keys[e]===l&&!i.has(t)){i.add(t),a.crossTileID=t;break}}}}}class Lh{constructor(){this.maxCrossTileID=0}generate(){return++this.maxCrossTileID}}class Ph{constructor(){this.indexes=[],this.usedCrossTileIDs=[],this.lng=0}handleWrapJump(e){const t=Math.round((e-this.lng)/360);if(0!==t)for(let e=0;e<this.indexes.length;e++){const i=this.indexes[e];if(!i)continue;const s=new Map;for(const e of i.values())e.tileID=e.tileID.unwrapTo(e.tileID.wrap+t),s.set(e.tileID.key,e);this.indexes[e]=s}this.lng=e}addBucket(e,t,i){const s=e.overscaledZ,o=this.indexes[s]&&this.indexes[s].get(e.key);if(o){if(o.bucketInstanceId===t.bucketInstanceId)return!1;this.removeBucketCrossTileIDs(s,o)}for(let e=0;e<t.symbolInstances.length;e++)t.symbolInstances.get(e).crossTileID=0;let r=this.usedCrossTileIDs[s];r||(r=this.usedCrossTileIDs[s]=new Set);for(let i=0;i<this.indexes.length;i++){const o=this.indexes[i];if(o)if(i>s)for(const i of o.values())i.tileID.isChildOf(e)&&i.findMatches(t.symbolInstances,e,r);else{const s=o.get(e.scaledTo(i).key);s&&s.findMatches(t.symbolInstances,e,r)}}for(let e=0;e<t.symbolInstances.length;e++){const s=t.symbolInstances.get(e);s.crossTileID||(s.crossTileID=i.generate(),r.add(s.crossTileID))}let n=this.indexes[s];return n||(n=this.indexes[s]=new Map),n.set(e.key,new Ah(e,t.symbolInstances,t.bucketInstanceId)),!0}removeBucketCrossTileIDs(e,t){for(const i of t.crossTileIDs)this.usedCrossTileIDs[e].delete(i)}removeStaleBuckets(e){let t=!1;for(let i=0;i<this.indexes.length;i++){const s=this.indexes[i];if(s)for(const[o,r]of s)e.has(r.bucketInstanceId)||(this.removeBucketCrossTileIDs(i,r),s.delete(o),t=!0)}return t}}class Mh{constructor(){this.layerIndexes=new Map,this.crossTileIDs=new Lh}addLayer(e,t,i,s){let o=this.layerIndexes.get(e.fqid);void 0===o&&(o=new Ph,this.layerIndexes.set(e.fqid,o));let r=!1;const n=new Set;"globe"!==s.name&&o.handleWrapJump(i);for(const i of t){const t=i.getBucket(e);t&&e.fqid===t.layerIds[0]&&(o.addBucket(i.tileID,t,this.crossTileIDs)&&(r=!0),n.add(t.bucketInstanceId))}return o.removeStaleBuckets(n)&&(r=!0),r}pruneUnusedLayers(e){const t=new Set(e);for(const e of this.layerIndexes.keys())t.has(e)||this.layerIndexes.delete(e)}}function Oh(e,t){const i=(t.right-t.left)/2,s=Math.abs(e.x-(t.left+i));if(s>=e.radius+i)return!1;const o=(t.bottom-t.top)/2,r=Math.abs(e.y-(t.top+o));if(r>=e.radius+o)return!1;if(s<i||r<o)return!0;const n=s-i,a=r-o;return n*n+a*a<e.radius*e.radius}function zh(e,t){return"box"===e.kind&&"box"===t.kind?function(e,t){return e.left<t.right&&t.left<e.right&&e.top<t.bottom&&t.top<e.bottom}(e,t):"circle"===e.kind&&"circle"===t.kind?function(e,t){const i=e.x-t.x,s=e.y-t.y,o=e.radius+t.radius;return i*i+s*s<o*o}(e,t):"circle"===e.kind?Oh(e,t):Oh(t,e)}class Fh{constructor(e,t,i,s){this._cellSize=s,this._padding=i,this._screenWidth=e,this._screenHeight=t,this._grid=new Jt(e+2*i,t+2*i,s),this._workingArea=this._computeWorkingArea(),this._geometries=[],this._geometryData=[]}clearAndResize(e,t){e===this._screenWidth&&t===this._screenHeight?this._grid.clear():(this._screenWidth=e,this._screenHeight=t,this._grid=new Jt(e+2*this._padding,t+2*this._padding,this._cellSize),this._workingArea=this._computeWorkingArea()),this._geometries.length=0,this._geometryData.length=0}_computeWorkingArea(){return{kind:"box",left:-this._padding,top:-this._padding,right:this._grid.xCellCount*this._cellSize-this._padding,bottom:this._grid.yCellCount*this._cellSize-this._padding}}intersects(e,t,i,s){let o="outside-of-grid";for(const r of e){const e=this._elementIntersects(r,t,i,s);if("intersects"===e)return"intersects";"does-not-intersect"===e&&(o="does-not-intersect")}return o}_elementIntersects(e,t,i,s){if(!zh(e,this._workingArea))return"outside-of-grid";const o=this._padding,r=function(e,t){return 0===t?e:"box"===e.kind?{kind:"box",left:e.left-t,top:e.top-t,right:e.right+t,bottom:e.bottom+t}:{kind:"circle",x:e.x,y:e.y,radius:e.radius+t}}(e,t);let n;const a=e=>{if(!zh(this._geometries[e],r))return!1;const t=this._geometryData[e];return!(void 0!==t&&i(t)||(n=t,0))},l="box"===r.kind?this._grid.hitTest(r.left+o,r.top+o,r.right+o,r.bottom+o,a):this._grid.hitTestCircle(r.x+o,r.y+o,r.radius,a);return l&&void 0!==n&&s(n),l?"intersects":"does-not-intersect"}insert(e,t){const i=this._padding;let s=!1;for(const o of e){if(!zh(o,this._workingArea))continue;const e=this._geometries.length;this._geometries.push(o),this._geometryData.push(t),"box"===o.kind?this._grid.insert(e,o.left+i,o.top+i,o.right+i,o.bottom+i):this._grid.insertCircle(e,o.x+i,o.y+i,o.radius),s=!0}return s}}const kh={PLACED:0,COLLIDED:1,OTHER_VARIANT_PLACED:2,DEPENDENCY_NOT_PLACED:3,OUT_OF_BOUNDS:4};function Bh(){}function Nh(e,t){const i=e.get(t.symbolId);return void 0!==i&&i.has(t.variantIdx)}function Uh(e,t){let i=e.get(t.symbolId);i||(i=new Set,e.set(t.symbolId,i)),i.add(t.variantIdx)}class Vh{constructor(){this._runStarted=!1,this._grid=null,this._timestamp=0,this._symbols=[],this._onlyIfPlacedReferencedIds=new Map,this._placedVariantIds=new Map,this._placedSymbolIds=new Map,this._processingSource=null,this._variantProcessingStarted=!1,this._collectDebugData=!1,this._debugSymbols=[],this._lastBlockedBy=void 0}isCollectingDebugData(){return this._collectDebugData}startPlacement(e,t,i,s=!1){if(this._runStarted)throw new Error("Attempt to start a placement run before finishing the previous one");this._runStarted=!0,this._grid?this._grid.clearAndResize(t,i):this._grid=new Fh(t,i,100,32),this._timestamp=e,this._symbols=[],this._onlyIfPlacedReferencedIds.clear(),this._placedVariantIds.clear(),this._placedSymbolIds.clear(),this._collectDebugData=s,this._debugSymbols=[]}debugSymbols(){return this._debugSymbols}timestamp(){return this._timestamp}_addPlacedSymbol(e){this._placedSymbolIds.set(e.symbolId,e.variantIdx)}startSymbolSourceProcessing(e){if(!this._runStarted)throw new Error("Attempt to start symbol source processing outside of a placement run");if(this._processingSource)throw new Error("Attempt to start a placement symbol source processing before finishing the previous one");this._processingSource=e}startSymbolVariantProcessing(e,t,i,s,o){const r=this._processingSource;if(!r)throw new Error("Attempt to start a symbol variant processing outside of symbol source processing");if(this._variantProcessingStarted)throw new Error("Attempt to begin a symbol variant processing before finishing the previous one");this._symbols.push({priority:t,source:r,variantId:e,parts:[],placementRules:i,tileID:s,featureId:o}),i.onlyIfPlaced&&Uh(this._onlyIfPlacedReferencedIds,i.onlyIfPlaced),this._variantProcessingStarted=!0}addSymbolVariantPart(e,t){if(!this._variantProcessingStarted)throw new Error("Attempt to add a symbol variant part outside of symbol variant processing");if(0===e.length)throw new Error("Attempt to add a symbol variant part without geometry");this._symbols.at(-1).parts.push({geometry:e,rules:t})}finishVariantProcessing(e){if(!this._variantProcessingStarted)throw new Error("Attempt to finish a symbol variant processing that was not started");this._variantProcessingStarted=!1;const t=this._symbols.at(-1);0===t.parts.length&&(t.priority.symbolVariantVisibility===xi.VARIANT_VISIBLE&&t.source.hideSymbolVariant(t.variantId,this._timestamp,e),this._symbols.pop())}finishSourceProcessing(){this._processingSource=null}_placeSymbolVariant(e,t){const i=this._grid;this._lastBlockedBy=void 0;const s=this._placedSymbolIds.get(e.variantId.symbolId);if(void 0!==s)return this._collectDebugData&&(this._lastBlockedBy={symbolId:e.variantId.symbolId,variantIdx:s}),kh.OTHER_VARIANT_PLACED;const o=e.placementRules.onlyIfPlaced;if(o&&!Nh(this._placedVariantIds,o))return kh.DEPENDENCY_NOT_PLACED;const r=this._collectDebugData?e=>{this._lastBlockedBy=e}:Bh;let n=!1,a=!1;for(const s of e.parts){const e=s.rules.collisionRules;if(!e)continue;n=!0;const o=e.symbolVariantToIgnoreCollisionWith,l=i.intersects(s.geometry,t,e=>{return void 0!==o&&(t=e).symbolId===(i=o).symbolId&&t.variantIdx===i.variantIdx;var t,i},r);if("intersects"===l)return kh.COLLIDED;"does-not-intersect"===l&&(a=!0)}if(n&&!a)return kh.OUT_OF_BOUNDS;let l=!1,c=!1;for(const t of e.parts)t.rules.insertIntoCollisionGrid&&(i.insert(t.geometry,e.variantId)?l=!0:c=!0);return c&&!l?kh.OUT_OF_BOUNDS:kh.PLACED}finishPlacementRun(e){if(!this._runStarted)throw new Error("Attempt to finish a placement run that was not started");this._runStarted=!1;const t=this._timestamp;this._symbols.sort((e,t)=>function(e,t){return e.placementSubgroupOrder-t.placementSubgroupOrder||e.symbolPlacementPriority-t.symbolPlacementPriority||e.symbolVariantVisibility-t.symbolVariantVisibility||e.symbolPlacementType-t.symbolPlacementType||e.styleLayerOrder-t.styleLayerOrder||e.symbolDisplayOrder-t.symbolDisplayOrder}(t.priority,e.priority));for(const i of this._symbols){const s=i.priority.symbolVariantVisibility===xi.VARIANT_VISIBLE,o=s?0:1,r=this._placeSymbolVariant(i,o),n=r===kh.PLACED;if(n&&(this._addPlacedSymbol(i.variantId),Nh(this._onlyIfPlacedReferencedIds,i.variantId)&&Uh(this._placedVariantIds,i.variantId)),s!==n&&(n?i.source.showSymbolVariant(i.variantId,t,e):i.source.hideSymbolVariant(i.variantId,t,e)),this._collectDebugData){const e=n?0:o,t=[];for(const e of i.parts)t.push(...e.geometry);this._debugSymbols.push({geometry:t,collisionPadding:e,variantId:i.variantId,tileID:i.tileID,featureId:i.featureId,placementRules:i.placementRules,partPlacementRules:i.parts.map(e=>e.rules),status:r,blockedBy:this._lastBlockedBy})}}}}function jh(e){const t=e.properties.get("direction"),i=Ii(t.x,t.y,t.z);i[2]=Ee(i[2],0,75);const s=wi([i[0],i[1],i[2]]);return bi(s.x,s.y,s.z)}function Gh(e,t,i){const s="none"===t.properties.get("color-use-theme"),o=t.properties.get("color"),r=t.properties.get("intensity"),n=t.properties.get("direction"),a=[n.x,n.y,n.z],l="none"===i.properties.get("color-use-theme"),c=i.properties.get("color"),h=i.properties.get("intensity"),d=Math.max(Kt([0,0,1],a),0),u=[0,0,0];Ti(u,c.toPremultipliedRenderColor(l?null:e.getLut(t.scope)).toArray01Linear().slice(0,3),h);const _=[0,0,0];return Ti(_,o.toPremultipliedRenderColor(s?null:e.getLut(i.scope)).toArray01Linear().slice(0,3),d*r),Ei([u[0]>0?u[0]/(u[0]+_[0]):0,u[1]>0?u[1]/(u[1]+_[1]):0,u[2]>0?u[2]/(u[2]+_[2]):0])}function qh(e,t){const i=!e.includes("://");try{return new URL(e,i&&t?"http://example.com":void 0),!0}catch(e){return!1}}function Zh(e){const t=e.value;return t?Si(t)?qh(t,!0)?[]:[new Da(e.key,t,`invalid url "${t}"`)]:[new Da(e.key,t,`string expected, "${Di(t)}" found`)]:[]}class Wh extends A{constructor(e){super(),this.requestManager=e,this.models=Object.create(null),this.models[""]=Object.create(null),this.modelUris=Object.create(null),this.modelUris[""]=Object.create(null),this.modelByURL=Object.create(null),this.numModelsLoading=Object.create(null)}async loadModel(e,t){try{if(await Cl(),!ue.loadModel)return null;const i=await ue.loadModel(e=>this.requestManager.transformRequest(e,x.Model),e,t);return this.modelByURL[t]?i:null}catch(i){if(404===i.status)return null;this.fire(new P(new Error(`Could not load model ${e} from ${t}`,{cause:i})))}}load(e,t,i={forceReload:!1}){this.models[t]||(this.models[t]=Object.create(null));const s=Object.keys(e),o=[],r=[];for(const n of s){const s=e[n];this.hasURLBeenRequested(s)&&!i.forceReload||(this.modelByURL[s]={modelId:n,scope:t},o.push(this.loadModel(n,s)),r.push(n)),this.models[t][n]||(this.models[t][n]={model:null,numReferences:1})}0!==r.length&&(this.numModelsLoading[t]=(this.numModelsLoading[t]||0)+r.length,Promise.allSettled(o).then(e=>{for(let i=0;i<e.length;i++){const{status:s}=e[i];if("rejected"===s)continue;const{value:o}=e[i];this.models[t][r[i]]||(this.models[t][r[i]]={model:null,numReferences:1}),this.models[t][r[i]].model=o}this.numModelsLoading[t]-=r.length,this.fire(new M("data",{dataType:"style"}))}).catch(e=>{this.fire(new P(new Error(`Could not load models: ${e.message}`)))}))}isLoaded(){for(const e in this.numModelsLoading)if(this.numModelsLoading[e]>0)return!1;return!0}hasModel(e,t,i={exactIdMatch:!1}){return!!(i.exactIdMatch?this.getModel(e,t):this.getModelByURL(this.modelUris[t][e]))}getModel(e,t){return this.models[t]||(this.models[t]=Object.create(null)),this.models[t][e]?this.models[t][e].model:void 0}getModelByURL(e){if(!e)return null;const t=this.modelByURL[e];return t?this.models[t.scope][t.modelId].model:null}hasModelBeenAdded(e,t){return this.models[t]&&void 0!==this.models[t][e]}getModelURIs(e){return this.modelUris[e]||Object.create(null)}addModel(e,t,i){this.models[i]||(this.models[i]=Object.create(null)),this.modelUris[i]||(this.modelUris[i]=Object.create(null));const s=this.requestManager.normalizeModelURL(t);if((this.hasModel(e,i,{exactIdMatch:!0})||this.hasModelBeenAdded(e,i))&&this.modelUris[i][e]===s)this.models[i][e].numReferences++;else if(this.hasURLBeenRequested(s)){const{scope:e,modelId:t}=this.modelByURL[s];this.models[e][t].numReferences++}else this.modelUris[i][e]=s,this.load({[e]:this.modelUris[i][e]},i)}addModelURLs(e,t){this.models[t]||(this.models[t]=Object.create(null)),this.modelUris[t]||(this.modelUris[t]=Object.create(null));const i=this.modelUris[t];for(const t of Object.keys(e))i[t]=this.requestManager.normalizeModelURL(e[t])}reloadModels(e){this.load(this.modelUris[e],e,{forceReload:!0})}addModelsFromBucket(e,t){this.models[t]||(this.models[t]=Object.create(null)),this.modelUris[t]||(this.modelUris[t]=Object.create(null));const i=Object.create(null);for(const s of e)this.hasModel(s,t,{exactIdMatch:!0})||this.hasURLBeenRequested(s)?this.models[t][s].numReferences++:this.modelUris[t][s]&&!this.hasURLBeenRequested(s)?i[s]=this.modelUris[t][s]:!this.hasURLBeenRequested(s)&&qh(s,!1)&&(this.modelUris[t][s]=this.requestManager.normalizeModelURL(s),i[s]=this.modelUris[t][s]);this.load(i,t)}hasURLBeenRequested(e){return void 0!==this.modelByURL[e]}removeModel(e,t,i=!1,s=!1){if(this.models[t]&&this.models[t][e]&&(this.models[t][e].numReferences--,0===this.models[t][e].numReferences||s)){const s=this.modelUris[t][e];i||delete this.modelUris[t][e],delete this.modelByURL[s];const o=this.models[t][e].model;if(!o)return;delete this.models[t][e],o.destroy()}}destroy(){for(const e of Object.keys(this.models))for(const t of Object.keys(this.models[e])){const i=this.models[e][t].model;delete this.models[e][t],i&&i.destroy()}this.models=Object.create(null),this.models[""]=Object.create(null),this.modelUris=Object.create(null),this.modelUris[""]=Object.create(null),this.modelByURL=Object.create(null),this.numModelsLoading=Object.create(null)}listModels(e){return this.models[e]||(this.models[e]=Object.create(null)),Object.keys(this.models[e])}upload(e,t){this.models[t]||(this.models[t]=Object.create(null));for(const i in this.models[t])this.models[t][i].model&&this.models[t][i].model.upload(e.context)}}function Hh(e,t,i=0){const s=Math.pow(2,t.tileID.overscaledZ),o=t.tileSize*Math.pow(2,e.transform.tileZoom)/s,r=o*(t.tileID.canonical.x+t.tileID.wrap*s),n=o*t.tileID.canonical.y;return{u_image:0,u_texsize:t.imageAtlasTexture?t.imageAtlasTexture.size:[0,0],u_tile_units_to_pixels:1/Te(t,1,e.transform.tileZoom),u_pixel_coord_upper:[r>>16,n>>16],u_pixel_coord_lower:[65535&r,65535&n],u_pattern_transition:i}}const $h={terrain:0,flat:1},Xh=e=>({u_matrix:new Pi(e),u_edge_radius:new Ri(e),u_width_scale:new Ri(e),u_vertical_scale:new Ri(e),u_height_type:new Ai(e),u_base_type:new Ai(e)}),Yh=Bt(),Kh=[0,0,0],Jh=(e,t,i,s,o,r,n,a,l,c,h,d,u,_,p,f,m,g,v=[0,0,1],y=!1)=>{let x=Kh,b=0,w=Kh;if(!y){const e=t.style.light,i=e.properties.get("position");if(x=[i.x,i.y,i.z],"viewport"===e.properties.get("anchor")){const e=Mi();Oi(e,-t.transform.angle),Qe(x,x,e)}const s=e.properties.get("color").toPremultipliedRenderColor(null);b=e.properties.get("intensity"),w=[s.r,s.g,s.b]}const T=t.transform,E={u_matrix:e,u_lightpos:x,u_lightintensity:b,u_lightcolor:w,u_vertical_gradient:+i,u_opacity:s,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:Yh,u_merc_center:[0,0],u_up_dir:[0,0,0],u_height_lift:0,u_height_type:$h[c],u_base_type:$h[h],u_ao:o,u_edge_radius:r,u_width_scale:n,u_flood_light_color:p,u_vertical_scale:f,u_flood_light_intensity:m,u_ground_shadow_factor:g,u_front_cutoff_params:v};return"globe"===T.projection.name&&(E.u_tile_id=[a.canonical.x,a.canonical.y,1<<a.canonical.z],E.u_zoom_transition=d,E.u_inv_rot_matrix=_,E.u_merc_center=u,E.u_up_dir=T.projection.upVector(new $e(0,0,0),u[0]*ae,u[1]*ae),E.u_height_lift=l),E},Qh=(e,t,i,s,o,r)=>({u_matrix:e,u_edge_radius:t,u_width_scale:i,u_vertical_scale:s,u_height_type:$h[o],u_base_type:$h[r]}),ed=(e,t,i,s,o,r,n,a,l,c,h,d,u,_,p,f,m,g,v=!1)=>{const y=Jh(e,t,i,s,o,r,n,a,c,h,d,u,_,p,f,m,1,[0,0,0],[0,0,1],v),x={u_height_factor:-Math.pow(2,a.overscaledZ)/l.tileSize/8};return Object.assign(y,Hh(t,l,g),x)},td=(e,t,i)=>({u_matrix:e,u_emissive_strength:t,u_ground_shadow_factor:i,u_opacity_multiplier:1}),id=(e,t,i,s,o,r=0)=>Object.assign(td(e,t,o),Hh(i,s,r)),sd=(e,t,i,s)=>({u_matrix:e,u_world:i,u_emissive_strength:t,u_ground_shadow_factor:s,u_opacity_multiplier:1}),od=(e,t,i,s,o,r,n=0)=>Object.assign(id(e,t,i,s,r,n),{u_world:o}),rd=(e,t,i)=>({u_image:e,u_texel_size:t,u_first_pass:i?1:0}),nd=(e,t,i,s,o,r,n,a)=>{const l=ae/r.tileSize;return{u_matrix:e,u_inv_rot_matrix:t,u_camera_to_center_distance:i.getCameraToCenterDistance(a),u_extrude_scale:[i.pixelsToGLUnits[0]/l,i.pixelsToGLUnits[1]/l],u_zoom_transition:s,u_tile_id:n,u_merc_center:o}},ad=(e,t,i,s)=>({u_matrix:e,u_inv_matrix:t,u_camera_to_center_distance:i.getCameraToCenterDistance(s),u_viewport_size:[i.width,i.height]}),ld=(e,t,i,s,o,r)=>({u_viewport_size:e,u_color:t,u_outline_width:i,u_opacity:s,u_stroke_opacity:o,u_collision_padding_opacity:r}),cd=(e,t,i=1)=>({u_matrix:e,u_color:t,u_overlay:0,u_overlay_scale:i}),hd=e=>({u_matrix:e}),dd=Bt(),ud=(e,t,i,s,o,r,n)=>{const a=e.transform,l="globe"===a.projection.name,c=l?Fi(a.zoom,t.canonical)*a._pixelsPerMercatorPixel:Te(i,1,r),h={u_matrix:t.projMatrix,u_extrude_scale:c,u_intensity:n,u_inv_rot_matrix:dd,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0]};if(l){h.u_inv_rot_matrix=s,h.u_merc_center=o,h.u_tile_id=[t.canonical.x,t.canonical.y,1<<t.canonical.z],h.u_zoom_transition=K(a.zoom);const e=o[0]*ae,i=o[1]*ae;h.u_up_dir=a.projection.upVector(new $e(0,0,0),e,i)}return h};function _d(e,t){const i=Math.pow(2,t.canonical.z),s=t.canonical.y;return[new we(0,s/i).toLngLat().lat,new we(0,(s+1)/i).toLngLat().lat]}function pd(e,[t,i,s,o],[r,n]){if(r===n)return[0,0,0,0];const a=255*(e-1)/(e*(n-r));return[t*a,i*a,s*a,o*a]}function fd(e,t,[i,s]){return i===s?0:.5/e+(t-i)*(e-1)/(e*(s-i))}function md(e){const t=e.terrain?e.terrain.exaggeration():1;return(e.transform.pitch<15?J(.07,.7,Ee((14-e.transform.zoom)/5,0,1)):.07)*t}const gd=(e,t,i,s,o,r,n,a,l,c,h,d,u,_,p,f,m,g,v,y,x,b)=>({u_matrix:t,u_normalize_matrix:i,u_globe_matrix:s,u_merc_matrix:o,u_grid_matrix:r,u_tl_parent:n,u_scale_parent:h,u_fade_t:d.mix,u_opacity:d.opacity*u.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:u.paint.get("raster-brightness-min"),u_brightness_high:u.paint.get("raster-brightness-max"),u_saturation_factor:ji(u.paint.get("raster-saturation")),u_contrast_factor:Vi(u.paint.get("raster-contrast")),u_spin_weights:vd(u.paint.get("raster-hue-rotate")),u_perspective_transform:_,u_raster_elevation:p,u_zoom_transition:a,u_merc_center:l,u_cutoff_params:c,u_colorization_mix:pd(Ui,m,v),u_colorization_offset:fd(Ui,g,v),u_color_ramp:f,u_color_ramp_size:Ui,u_texture_offset:[x/(y+2*x),y/(y+2*x)],u_texture_res:[y+2*x,y+2*x],u_emissive_strength:b,u_zbias_factor:md(e)});function vd(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 yd={BaseColor:5,MetallicRoughness:6,Normal:7,Occlusion:8,Emission:9,LUT:10,ShadowMap0:11},xd=Bt(),bd=(e,t,i,s,o,r,n,a,l,c,h,d,u,_,p,f,m,g,v,y,x,b,w,E,I)=>{const S=o.transform,D={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:S.getCameraToCenterDistance(y),u_rotate_symbol:+i,u_aspect_ratio:S.width/S.height,u_fade_change:o.options.fadeDuration?o.symbolFadeChange:1,u_now:0|Math.round(o.now),u_fade_duration:o.options.fadeDuration,u_matrix:r,u_label_plane_matrix:n,u_coord_matrix:a,u_is_text:+c,u_is_sdf:+h,u_elevation_from_sea:l?1:0,u_pitch_with_map:+s,u_texsize:d,u_texsize_icon:u,u_texture:0,u_texture_icon:1,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:xd,u_merc_center:[0,0],u_camera_forward:[0,0,0],u_ecef_origin:[0,0,0],u_tile_matrix:xd,u_up_vector:[0,-1,0],u_color_adj_mat:w,u_icon_transition:E||0,u_gamma_scale:h?s?o.transform.getCameraToCenterDistance(y)*Math.cos(o.terrain?0:o.transform._pitch):1:0,u_device_pixel_ratio:T.devicePixelRatio,u_is_halo:1,u_scale_factor:I||1,u_ground_shadow_factor:x,u_inv_matrix:Tt(Bt(),n),u_normal_scale:b,u_lutTexture:yd.LUT,u_spp_fill_np_color:[0,0,0,1],u_spp_halo_np_color:[0,0,0,0],u_spp_opacity:1,u_spp_halo_width:0,u_spp_halo_blur:0,u_spp_emissive_strength:0,u_spp_occlusion_opacity:1,u_spp_z_offset:0,u_spp_translate_rotation:[1,0],u_spp_zoom_fraction:0,u_opacity_multiplier:1};return"globe"===y.name&&(D.u_tile_id=[p.canonical.x,p.canonical.y,1<<p.canonical.z],D.u_zoom_transition=f,D.u_inv_rot_matrix=g,D.u_merc_center=m,D.u_camera_forward=S._camera.forward(),D.u_ecef_origin=Gi(S.globeMatrix,p.toUnwrapped()),D.u_tile_matrix=S.globeMatrix,D.u_up_vector=v),D},wd=(e,t,i,s)=>({u_matrix:e,u_emissive_strength:t,u_opacity:i,u_color:s}),Td=(e,t,i,s,o,r,n,a,l)=>Object.assign(function(e,t,i,s,o,r){const{width:n,height:a}=s.imageManager.getPixelSize(t),l=Math.pow(2,r.tileID.overscaledZ),c=r.tileSize*Math.pow(2,s.transform.tileZoom)/l,h=c*(r.tileID.canonical.x+r.tileID.wrap*l),d=c*r.tileID.canonical.y;return{u_image:0,u_pattern_tl:i.tl,u_pattern_br:i.br,u_texsize:[n,a],u_pattern_size:i.displaySize,u_pattern_units_to_pixels:o?[s.transform.width,-1*s.transform.height]:[1/Te(r,1,s.transform.tileZoom),1/Te(r,1,s.transform.tileZoom)],u_pixel_coord_upper:[h>>16,d>>16],u_pixel_coord_lower:[65535&h,65535&d]}}(0,r,n,s,a,l),{u_matrix:e,u_emissive_strength:t,u_opacity:i}),Ed={fillExtrusion:e=>({u_matrix:new Pi(e),u_lightpos:new Li(e),u_lightintensity:new Ri(e),u_lightcolor:new Li(e),u_vertical_gradient:new Ri(e),u_opacity:new Ri(e),u_edge_radius:new Ri(e),u_width_scale:new Ri(e),u_ao:new Ci(e),u_height_type:new Ai(e),u_base_type:new Ai(e),u_tile_id:new Li(e),u_zoom_transition:new Ri(e),u_inv_rot_matrix:new Pi(e),u_merc_center:new Ci(e),u_up_dir:new Li(e),u_height_lift:new Ri(e),u_flood_light_color:new Li(e),u_vertical_scale:new Ri(e),u_flood_light_intensity:new Ri(e),u_ground_shadow_factor:new Li(e),u_front_cutoff_params:new Li(e)}),fillExtrusionPattern:e=>({u_matrix:new Pi(e),u_lightpos:new Li(e),u_lightintensity:new Ri(e),u_lightcolor:new Li(e),u_vertical_gradient:new Ri(e),u_height_factor:new Ri(e),u_edge_radius:new Ri(e),u_width_scale:new Ri(e),u_ao:new Ci(e),u_height_type:new Ai(e),u_base_type:new Ai(e),u_tile_id:new Li(e),u_zoom_transition:new Ri(e),u_inv_rot_matrix:new Pi(e),u_merc_center:new Ci(e),u_up_dir:new Li(e),u_height_lift:new Ri(e),u_image:new Ai(e),u_texsize:new Ci(e),u_pixel_coord_upper:new Ci(e),u_pixel_coord_lower:new Ci(e),u_tile_units_to_pixels:new Ri(e),u_opacity:new Ri(e),u_pattern_transition:new Ri(e)}),fill:e=>({u_matrix:new Pi(e),u_emissive_strength:new Ri(e),u_ground_shadow_factor:new Li(e),u_opacity_multiplier:new Ri(e)}),fillPattern:e=>({u_matrix:new Pi(e),u_emissive_strength:new Ri(e),u_image:new Ai(e),u_texsize:new Ci(e),u_pixel_coord_upper:new Ci(e),u_pixel_coord_lower:new Ci(e),u_tile_units_to_pixels:new Ri(e),u_ground_shadow_factor:new Li(e),u_pattern_transition:new Ri(e),u_opacity_multiplier:new Ri(e)}),fillOutline:e=>({u_matrix:new Pi(e),u_emissive_strength:new Ri(e),u_world:new Ci(e),u_ground_shadow_factor:new Li(e),u_opacity_multiplier:new Ri(e)}),fillOutlinePattern:e=>({u_matrix:new Pi(e),u_emissive_strength:new Ri(e),u_world:new Ci(e),u_image:new Ai(e),u_texsize:new Ci(e),u_pixel_coord_upper:new Ci(e),u_pixel_coord_lower:new Ci(e),u_tile_units_to_pixels:new Ri(e),u_ground_shadow_factor:new Li(e),u_pattern_transition:new Ri(e),u_opacity_multiplier:new Ri(e)}),lineBlendComposite:e=>({u_image:new Ai(e),u_opacity:new Ri(e),u_blend_mode:new Ai(e),u_max_density:new Ri(e)}),lineBlendReduce:e=>({u_image:new Ai(e),u_texel_size:new Ci(e),u_first_pass:new Ai(e)}),circle:Wi,collisionBox:e=>({u_matrix:new Pi(e),u_inv_rot_matrix:new Pi(e),u_camera_to_center_distance:new Ri(e),u_extrude_scale:new Ci(e),u_zoom_transition:new Ri(e),u_merc_center:new Ci(e),u_tile_id:new Li(e)}),collisionCircle:e=>({u_matrix:new Pi(e),u_inv_matrix:new Pi(e),u_camera_to_center_distance:new Ri(e),u_viewport_size:new Ci(e)}),placementDebug:e=>({u_viewport_size:new Ci(e),u_color:new zi(e),u_outline_width:new Ri(e),u_opacity:new Ri(e),u_stroke_opacity:new Ri(e),u_collision_padding_opacity:new Ri(e)}),debug:e=>({u_color:new zi(e),u_matrix:new Pi(e),u_overlay:new Ai(e),u_overlay_scale:new Ri(e)}),clippingMask:e=>({u_matrix:new Pi(e)}),heatmap:e=>({u_extrude_scale:new Ri(e),u_intensity:new Ri(e),u_matrix:new Pi(e),u_inv_rot_matrix:new Pi(e),u_merc_center:new Ci(e),u_tile_id:new Li(e),u_zoom_transition:new Ri(e),u_up_dir:new Li(e)}),heatmapTexture:e=>({u_image:new Ai(e),u_color_ramp:new Ai(e),u_opacity:new Ri(e)}),hillshade:e=>({u_matrix:new Pi(e),u_image:new Ai(e),u_latrange:new Ci(e),u_light:new Ci(e),u_shadow:new zi(e),u_highlight:new zi(e),u_emissive_strength:new Ri(e),u_accent:new zi(e)}),hillshadePrepare:e=>({u_matrix:new Pi(e),u_image:new Ai(e),u_dimension:new Ci(e),u_zoom:new Ri(e)}),line:Zi,linePattern:qi,raster:e=>({u_matrix:new Pi(e),u_normalize_matrix:new Pi(e),u_globe_matrix:new Pi(e),u_merc_matrix:new Pi(e),u_grid_matrix:new Ni(e),u_tl_parent:new Ci(e),u_scale_parent:new Ri(e),u_fade_t:new Ri(e),u_opacity:new Ri(e),u_image0:new Ai(e),u_image1:new Ai(e),u_brightness_low:new Ri(e),u_brightness_high:new Ri(e),u_saturation_factor:new Ri(e),u_contrast_factor:new Ri(e),u_spin_weights:new Li(e),u_perspective_transform:new Ci(e),u_raster_elevation:new Ri(e),u_zoom_transition:new Ri(e),u_merc_center:new Ci(e),u_cutoff_params:new Bi(e),u_colorization_mix:new Bi(e),u_colorization_offset:new Ri(e),u_color_ramp:new Ai(e),u_color_ramp_size:new Ri(e),u_texture_offset:new Ci(e),u_texture_res:new Ci(e),u_emissive_strength:new Ri(e),u_zbias_factor:new Ri(e)}),symbol:e=>({u_is_size_zoom_constant:new Ai(e),u_is_size_feature_constant:new Ai(e),u_size_t:new Ri(e),u_size:new Ri(e),u_camera_to_center_distance:new Ri(e),u_rotate_symbol:new Ai(e),u_aspect_ratio:new Ri(e),u_fade_change:new Ri(e),u_now:new Ai(e),u_fade_duration:new Ri(e),u_matrix:new Pi(e),u_label_plane_matrix:new Pi(e),u_coord_matrix:new Pi(e),u_is_text:new Ai(e),u_is_sdf:new Ai(e),u_elevation_from_sea:new Ai(e),u_pitch_with_map:new Ai(e),u_texsize:new Ci(e),u_texsize_icon:new Ci(e),u_texture:new Ai(e),u_texture_icon:new Ai(e),u_gamma_scale:new Ri(e),u_device_pixel_ratio:new Ri(e),u_tile_id:new Li(e),u_zoom_transition:new Ri(e),u_inv_rot_matrix:new Pi(e),u_merc_center:new Ci(e),u_camera_forward:new Li(e),u_tile_matrix:new Pi(e),u_up_vector:new Li(e),u_ecef_origin:new Li(e),u_is_halo:new Ai(e),u_icon_transition:new Ri(e),u_color_adj_mat:new Pi(e),u_scale_factor:new Ri(e),u_ground_shadow_factor:new Li(e),u_inv_matrix:new Pi(e),u_normal_scale:new Ri(e),u_lutTexture:new Ai(e),u_spp_fill_np_color:new Bi(e),u_spp_halo_np_color:new Bi(e),u_spp_opacity:new Ri(e),u_spp_halo_width:new Ri(e),u_spp_halo_blur:new Ri(e),u_spp_emissive_strength:new Ri(e),u_spp_occlusion_opacity:new Ri(e),u_spp_z_offset:new Ri(e),u_spp_translate_rotation:new Ci(e),u_spp_zoom_fraction:new Ri(e),u_opacity_multiplier:new Ri(e)}),background:e=>({u_matrix:new Pi(e),u_emissive_strength:new Ri(e),u_opacity:new Ri(e),u_color:new zi(e)}),backgroundPattern:e=>({u_matrix:new Pi(e),u_emissive_strength:new Ri(e),u_opacity:new Ri(e),u_image:new Ai(e),u_pattern_tl:new Ci(e),u_pattern_br:new Ci(e),u_texsize:new Ci(e),u_pattern_size:new Ci(e),u_pixel_coord_upper:new Ci(e),u_pixel_coord_lower:new Ci(e),u_pattern_units_to_pixels:new Ci(e)}),skybox:e=>({u_matrix:new Pi(e),u_sun_direction:new Li(e),u_cubemap:new Ai(e),u_opacity:new Ri(e),u_temporal_offset:new Ri(e)}),skyboxGradient:e=>({u_matrix:new Pi(e),u_color_ramp:new Ai(e),u_center_direction:new Li(e),u_radius:new Ri(e),u_opacity:new Ri(e),u_temporal_offset:new Ri(e)}),skyboxCapture:e=>({u_matrix_3f:new Ni(e),u_sun_direction:new Li(e),u_sun_intensity:new Ri(e),u_color_tint_r:new Bi(e),u_color_tint_m:new Bi(e),u_luminance:new Ri(e)}),globeAtmosphere:e=>({u_frustum_tl:new Li(e),u_frustum_tr:new Li(e),u_frustum_br:new Li(e),u_frustum_bl:new Li(e),u_horizon:new Ri(e),u_transition:new Ri(e),u_fadeout_range:new Ri(e),u_atmosphere_fog_color:new Bi(e),u_high_color:new Bi(e),u_space_color:new Bi(e),u_temporal_offset:new Ri(e),u_horizon_angle:new Ri(e)}),stars:e=>({u_matrix:new Pi(e),u_up:new Li(e),u_right:new Li(e),u_intensity_multiplier:new Ri(e)}),occlusion:e=>({u_matrix:new Pi(e),u_anchorPos:new Li(e),u_screenSizePx:new Ci(e),u_occluderSizePx:new Ci(e),u_color:new Bi(e)})},Id=["RENDER_SHADOWS","NORMAL_OFFSET"],Sd=new Set(["symbol","circle"]),Dd=class e{constructor(){this._queue=[],this._needsBuild=!0,this._idleHandle=null}needsBuild(){return this._needsBuild}buildQueue(e,t,i){null!=this._idleHandle&&"undefined"!=typeof cancelIdleCallback&&cancelIdleCallback(this._idleHandle),this._idleHandle=null,this._queue=[],this._needsBuild=!1;const s=!!i.fog,o=i.hasTerrain(),r=!(!i.projection||"globe"!==i.projection.name),n=o||r,a=!(!i.directionalLight||!i.directionalLight.shadowsEnabled()),l=i.map&&i.map.painter,c=!l||!l.context.extParallelShaderCompile,h=!!l&&("mrt-fallback"===l.emissiveMode||"mrt-full-rgba"===l.emissiveMode),d=(e,t=[],i={})=>{this._queue.push({programId:e,params:{...i.params,defines:t,overrideFog:!!i.fog,overrideTerrain:!!i.terrain,overrideGlobe:!!i.globe,overrideRtt:!!i.rtt,precompiled:!0}})};for(const u of e){if("none"===u.visibility)continue;const e=u.getProgramIds();if(e)for(const _ of e){if(Sd.has(_))continue;const e=u.getDefaultProgramParams(_,t.zoom,i._styleColorTheme.lut);if(!e)continue;const p=l?l.getShaderSource(_):null,f=n&&(!p||p.usedDefines.has("RENDER_TO_TEXTURE"));let m=e.defines;if(h&&f&&(m=(m||[]).concat("USE_MRT1"),"mrt-full-rgba"===l.emissiveMode&&(m=(m||[]).concat("USE_MRT1_RGBA"))),c){d(_,e.defines,{params:e}),f&&d(_,m,{params:e,rtt:!0});continue}const g=s&&(!p||p.usedDefines.has("FOG")),v=o&&!u.isDraped()&&(!p||p.usedDefines.has("TERRAIN")),y=r&&(!p||p.usedDefines.has("GLOBE")),x=a&&u.hasElevation()&&(!p||p.usedDefines.has("RENDER_SHADOWS"));for(const t of x?[!1,!0]:[!1]){const i=t?(e.defines||[]).concat(Id):e.defines||[];for(const t of v?[!1,!0]:[!1])for(const s of y?[!1,!0]:[!1])for(const o of g?[!1,!0]:[!1])d(_,i,{params:e,fog:o,terrain:t,globe:s})}f&&d(_,m,{params:e,rtt:!0})}}if(d("clippingMask"),o)for(const e of[!1,!0])d("terrainRaster",e?["TERRAIN_VERTEX_MORPHING"]:[],{terrain:!0,fog:s});if(!c){if(e.some(e=>"hillshade"===e.type)&&d("hillshadePrepare"),a)for(const e of[!1,!0])for(const t of[!1,!0]){const i=[];e&&i.push("RENDER_CUTOFF"),i.push("RENDER_SHADOWS"),t&&i.push("NORMAL_OFFSET"),d("groundShadow",i),s&&d("groundShadow",i,{fog:!0})}if(r){for(const e of[[],["TERRAIN_VERTEX_MORPHING"],["GLOBE_POLES"]])for(const t of[!1,!0]){const i=[...e,"PROJECTION_GLOBE_VIEW"];t&&i.push("CUSTOM_ANTIALIASING"),d("globeRaster",i,{terrain:o,globe:!0,fog:s})}for(const e of[!1,!0]){const t=e?["PROJECTION_GLOBE_VIEW","FOG"]:["FOG"];d("globeAtmosphere",t,{fog:!0,terrain:o,globe:e}),d("globeAtmosphere",[...t,"ALPHA_PASS"],{fog:!0,terrain:o,globe:e})}d("stars",[],{fog:s,terrain:o,globe:!0})}}}_executeBatch(t,i,s){if(s.map&&s.map.isMoving())return void(this._idleHandle=T.requestIdleCallback(e=>this._executeBatch(e,i,s)));i.context.sweepPendingPrograms();const o=i.context.extParallelShaderCompile?e.DEADLINE_MARGIN_KHR_MS:e.DEADLINE_MARGIN_SYNC_MS;let r=0;for(;this._queue.length>0;){const e=this._queue.shift();if(!e)break;if(e.programId in Ed&&(i.style=s,i._fogVisible=!!e.params.overrideFog,i.getOrCreateProgram(e.programId,e.params),r++,t.timeRemaining()<=o))break}const n=0===this._queue.length||t.timeRemaining()>o;r>0&&n&&i.context.gl.flush(),this._idleHandle=this._queue.length>0||i.context._pendingPrograms.size>0?T.requestIdleCallback(e=>this._executeBatch(e,i,s)):null}processQueue(e,t){0!==this._queue.length&&(null!=this._idleHandle&&"undefined"!=typeof cancelIdleCallback&&cancelIdleCallback(this._idleHandle),this._idleHandle=T.requestIdleCallback(i=>this._executeBatch(i,e,t)))}reset(){null!=this._idleHandle&&"undefined"!=typeof cancelIdleCallback&&cancelIdleCallback(this._idleHandle),this._queue=[],this._idleHandle=null,this._needsBuild=!0}};Dd.DEADLINE_MARGIN_KHR_MS=5,Dd.DEADLINE_MARGIN_SYNC_MS=25;let Rd=Dd;const Cd=new W(y.colorTheme.data);function Ad(e){if(!e.metadata||!e.metadata.content_area)return;const t=T.devicePixelRatio,{left:i,top:s,width:o,height:r}=e.metadata.content_area,n=i*t,a=s*t;return[n,a,n+o*t,a+r*t]}function Ld(e){if(e)return e.map(([e,t])=>[e*T.devicePixelRatio,t*T.devicePixelRatio])}class Pd{constructor(e,t,i){this.id=e,this.scope=t,this.sourceCache=i,this.pendingRequests=new Set,this.missingRequests=new Set}addPendingRequest(e){this.missingRequests.has(e.name)||this.pendingRequests.has(e.name)||this.pendingRequests.add(e.name)}hasPendingRequests(){return this.pendingRequests.size>0}resolvePendingRequests(){const e=new Map;if(!this.sourceCache.loaded())return e;const t=this.sourceCache.getVisibleCoordinates();if(0===t.length)return e;const i=this.sourceCache.getSource();if("raster-array"!==i.type)return e;const s=t.map(e=>this.sourceCache.getTile(e)),o=i.getImages(s,Array.from(this.pendingRequests));for(const[t,i]of o)e.set(g.from({name:t,iconsetId:this.id}),i),this.pendingRequests.delete(t);for(const e of this.pendingRequests)this.missingRequests.add(e);return this.pendingRequests.clear(),e}}const Md=(e,t)=>Pa(e,t&&t.filter(e=>"source.canvas"!==e.identifier)),Od=new Set(["addLayer","removeLayer","setLights","setPaintProperty","setLayoutProperty","setLayerProperty","setSlot","setFilter","addSource","removeSource","setLayerZoomRange","setLight","setTransition","setGeoJSONSourceData","setTerrain","setFog","setSnow","setRain","setProjection","setCamera","addImport","removeImport","updateImport","addIconset","removeIconset"]),zd=new Set(["setCenter","setZoom","setBearing","setPitch"]),Fd=new Set(["background","sky","slot","custom","placement-group"]),kd={version:8,layers:[],sources:{}},Bd={duration:300,delay:0};class Nd extends A{constructor(e,t={}){super(),this.map=e,this.scope=t.scope||"",this.globalId=null,this.fragments=[],this.importDepth=t.importDepth||0,this.importsCache=t.importsCache||new Map,this.resolvedImports=t.resolvedImports||new Set,this.transition={...Bd},this._buildingIndex=new Mc(this),this.crossTileSymbolIndex=new Mh,this.globalPlacement=null,this._groupOrders=null,this._groupOrdersVersion=-1,this._mergedOrder=[],this._mergedOrderVersion=0,this._drapedFirstOrder=[],this._mergedLayers=Object.create(null),this._mergedIndoor={},this._indoorEnabled=!1,this._mergedSourceCaches={},this._mergedOtherSourceCaches=Object.create(null),this._mergedSymbolSourceCaches=Object.create(null),this._mergedFillExtrusionSourceCaches=Object.create(null),this._mergedHdRoadCoverageSourceCaches=Object.create(null),this._hdCoverage=null,this._hdElevation=null,this._crossSourceElevationActive=!1,this._clipLayerPresent=!1,this._hasAppearances=!1,this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this._importedAsBasemap=!1,this._changes=t.styleChanges||new Fn,this._hasDataDrivenEmissive=!1,this.indoorManager=null,this.dispatcher=t.dispatcher?t.dispatcher:new pl(Oc(),this),this.glyphManager=t.glyphManager?t.glyphManager:new Sa(e._requestManager,t.localFontFamily?$i.all:t.localIdeographFontFamily?$i.ideographs:$i.none,t.localFontFamily||t.localIdeographFontFamily,t.fontstackCompositing);const i={referrer:us(),config:ds()};if(this.map.painter&&this.map.painter.context){const e=Math.floor(this.map.painter.context.maxUniformBlockSize/4);i.contextOptions={maxUniformBlockSizeDwords:e}}if(this.isRootStyle()){const{mode:e,fontFamily:t}=this.glyphManager.localGlyphs;t&&!Xi(t)&&(i.localGlyphs={mode:e,fontFamily:t}),this.dispatcher.broadcast("setGlobalParams",i)}t.imageManager?this.imageManager=t.imageManager:(this.imageManager=new Ea(this.map._spriteFormat),this.imageManager.setEventedParent(this)),this.imageManager.addScope(this.scope),t.modelManager?this.modelManager=t.modelManager:(this.modelManager=new Wh(e._requestManager),this.modelManager.setEventedParent(this)),this._layers=Object.create(null),this._sourceCaches={},this._otherSourceCaches=Object.create(null),this._symbolSourceCaches=Object.create(null),this._fillExtrusionSourceCaches=Object.create(null),this._hdCoverage=null,this._hdElevation=null,this._crossSourceElevationActive=!1,this._loaded=!1,this._drapingLoaded=void 0,this._rasterArrayLoaded=void 0,this._initialBroadcastDone=!1,this._programPrecompiler=this.map._precompilePrograms&&this.isRootStyle()?new Rd:null,this._availableImages=[],this._availableModels={},this._order=[],this._markersNeedUpdate=!1,this.options=t.configOptions?t.configOptions:new Map,this._layerExpressionDependencies=t.layerExpressionDependencies?t.layerExpressionDependencies:new Map,this._config=t.config,this._styleColorTheme={lut:null,lutLoading:!1,lutLoadingCorrelationID:0,colorTheme:null,colorThemeOverride:t.colorThemeOverride},this._styleColorThemeForScope={},this._initialConfig=t.initialConfig,this.on("data",e=>{if("source"!==e.dataType||"metadata"!==e.sourceDataType)return;const t=this.getOwnSource(e.sourceId);if(t&&t.vectorLayerIds)for(const e in this._layers){const i=this._layers[e];i.source===t.id&&this._validateLayer(i)}})}load(e){return e?("string"==typeof e?this.loadURL(e):this.loadJSON(e),this):this}_getGlobalId(e){if(!e)return null;if("string"==typeof e){if(r(e))return e;const t=Yi(e);if(!t.startsWith("http"))try{return new URL(t,location.href).toString()}catch(e){return t}return t}return`json://${Ki(JSON.stringify(e))}`}_diffStyle(e,t,i){this.globalId=this._getGlobalId(e),La();const s=(e,t)=>{try{t(null,this.setState(e,i))}catch(e){t(e,!1)}};if("string"==typeof e){const i=this.map._requestManager.normalizeStyleURL(e),o=new AbortController;this._request={cancel:()=>o.abort()},(async()=>{const e=await this.map._requestManager.transformRequest(i,x.Style,o.signal),{data:r}=await b(e,o.signal);this._request=null,s(r,t)})().catch(e=>{this._request=null,o.signal.aborted||this.fire(new P(e))})}else"object"==typeof e&&s(e,t)}loadURL(e,t={}){this.fire(new M("dataloading",{dataType:"style"}));const i="boolean"==typeof t.validate?t.validate:!r(e);i&&La(),e.startsWith("mapbox://styles/mapbox/standard")&&Cl(),this.globalId=this._getGlobalId(e),e=this.map._requestManager.normalizeStyleURL(e,t.accessToken),this.resolvedImports.add(e);const s=this.importsCache.get(e);if(s)return void this._load(s,i);const o=new AbortController;this._request={cancel:()=>o.abort()},(async()=>{const t=await this.map._requestManager.transformRequest(e,x.Style,o.signal),{data:s}=await b(t,o.signal);this._request=null,this.importsCache.set(e,s),this._load(s,i)})().catch(e=>{this._request=null,o.signal.aborted||this.fire(new P(e))})}loadJSON(e,t={}){this.fire(new M("dataloading",{dataType:"style"}));const i=!1!==t.validate;i&&La(),this.globalId=this._getGlobalId(e),this._request=T.frame(()=>{this._request=null,this._load(e,i)})}loadEmpty(){this.fire(new M("dataloading",{dataType:"style"})),this._load(kd,!1)}_loadImports(e,t,i){if(this.importDepth>=4)return _("Style doesn't support nesting deeper than 5"),Promise.resolve();const s=[];for(const o of e){const e=this._createFragmentStyle(o),r=new Promise(t=>{e.once("style.import.load",t),e.once("error",i=>{e._loaded||t(i)})}).then(()=>{this.mergeAll(),this.fire(new M("data",{dataType:"style"}))});if(s.push(r),this.resolvedImports.has(o.url)){e.loadEmpty();continue}const n=o.data||this.importsCache.get(o.url);n?(o.data?(e.fire(new M("dataloading",{dataType:"style"})),e.globalId=e._getGlobalId(n),t&&La(),queueMicrotask(()=>{e._load(n,t)})):e.loadJSON(n,{validate:t}),this._isInternalStyle(n)&&(e.globalId=null)):o.url?e.loadURL(o.url,{validate:t}):e.loadEmpty();const a={style:e,id:o.id,config:o.config};if(i){const e=this.fragments.findIndex(({id:e})=>e===i);this.fragments=this.fragments.slice(0,e).concat(a).concat(this.fragments.slice(e))}else this.fragments.push(a)}return Promise.allSettled(s)}getImportGlobalIds(e=this,t=new Set){for(const i of e.fragments)i.style.globalId&&t.add(i.style.globalId),this.getImportGlobalIds(i.style,t);return[...t.values()]}_createFragmentStyle(e){const t=this.scope?C(e.id,this.scope):e.id;let i;const s=this._initialConfig&&this._initialConfig[t];(e.config||s)&&(i={...e.config,...s});const o=new Nd(this.map,{scope:t,styleChanges:this._changes,importDepth:this.importDepth+1,importsCache:this.importsCache,resolvedImports:new Set(this.resolvedImports),dispatcher:this.dispatcher,imageManager:this.imageManager,glyphManager:this.glyphManager,modelManager:this.modelManager,config:i,configOptions:this.options,colorThemeOverride:e["color-theme"],layerExpressionDependencies:this._layerExpressionDependencies});return o.setEventedParent(this.map,{style:o}),o}_reloadImports(e=!1){this.mergeAll(),this._updateMapProjection(),e?this._updateEnvConfig("reset"):this.updateConfigDependencies(),this._updateLayers(this._dependentLayerIds(e=>e.isIndoorDependent)),this.map._triggerCameraUpdate(this.camera),(!e||this.isRootStyle()||this.map.style._initialBroadcastDone)&&(e&&this.isRootStyle()?(this.forEachFragmentStyle(e=>{this.dispatcher.broadcast("setLayers",{layers:e._serializeLayers(e._order),scope:e.scope,options:e.options})}),this._initialBroadcastDone=!0):this.dispatcher.broadcast("setLayers",{layers:this._serializeLayers(this._order),scope:this.scope,options:this.options}))}_isInternalStyle(e){return this.isRootStyle()&&(e.fragment||!!e.schema&&!1!==e.fragment)}async _load(e,t){if(this._isInternalStyle(e)){const i={id:"basemap",data:e,url:""},s={...kd,imports:[i],...e.center?{center:e.center}:{},...e.bearing?{bearing:e.bearing}:{},...e.pitch?{pitch:e.pitch}:{},...e.zoom?{zoom:e.zoom}:{},...e.light?{light:e.light}:{}};return this._importedAsBasemap=!0,void this._load(s,t)}if(t){if(await La(),!this.dispatcher.actors.length)return;if(Md(this,Oa(e)))return}e.sprite&&this._loadIconset(e.sprite),this._loaded=!0,this.updateConfig(this._config,e.schema);for(const t in e.sources)this.addSource(t,e.sources[t],{validate:!1,isInitialLoad:!0});this.stylesheet=Ji(e);const i=()=>{if(e.iconsets)for(const t in e.iconsets)this.addIconset(t,e.iconsets[t]);e.sprite||(this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope})),!this.glyphManager.url&&e.glyphs&&this.glyphManager.setURL(e.glyphs);const i=Bc(this.stylesheet.layers);if(this._order=i.map(e=>e.id),this.stylesheet.light&&_("The `light` root property is deprecated, prefer using `lights` with `flat` light type instead."),this.stylesheet.lights)if(1===this.stylesheet.lights.length&&"flat"===this.stylesheet.lights[0].type){const e=this.stylesheet.lights[0];this.light=new Ya(e.properties,e.id)}else this.setLights(this.stylesheet.lights);this.light||(this.light=new Ya(this.stylesheet.light)),this._layers=Object.create(null);let s=!1;for(const e of i){const t=os(e,this.scope,this._styleColorTheme.lut,this.options);this._layerExpressionDependencies.set(t.fqid,new kn(t)),this._hasAppearances=this._hasAppearances||0!==t.getAppearances().length,t.setEventedParent(this,{layer:{id:t.id}}),this._layers[t.id]=t,this._updateHdCoverageSourceCache(t)&&(s=!0);const i=this.getOwnLayerSourceCache(t),o=!!this.directionalLight&&this.directionalLight.shadowsEnabled();i&&t.canCastShadows()&&o&&(i.castsShadows=!0)}s&&Dl().then(()=>{if(!this.map)return;for(const e in this._layers)this._updateHdCoverageSourceCache(this._layers[e]);this.map.style.mergeAll();const e=this.map.transform;for(const t in this.map.style._mergedHdRoadCoverageSourceCaches){const i=this.map.style._mergedHdRoadCoverageSourceCaches[t];i.used=!0,e&&i.update(e)}this.map._update()}),this.stylesheet.featuresets&&this.setFeaturesetSelectors(this.stylesheet.featuresets),this.stylesheet.models&&this.addModelURLs(this.stylesheet.models);const o=this.stylesheet.terrain;o&&(this.checkCanvasFingerprintNoise(),this.disableElevatedTerrain||this.terrainSetForDrapingOnly()||(this._startLiteLoad(),this._createTerrain(o,Ja.elevated))),this.stylesheet.fog&&this._createFog(this.stylesheet.fog),this.stylesheet.snow&&this._createSnow(this.stylesheet.snow),this.stylesheet.rain&&this._createRain(this.stylesheet.rain),this.stylesheet.transition&&this.setTransition(this.stylesheet.transition),this.fire(new M("data",{dataType:"style"}));const r=this.isRootStyle();e.imports?this._loadImports(e.imports,t).then(()=>{this._reloadImports(!0),this.fire(new M(r?"style.load":"style.import.load"))}).catch(e=>{this.fire(new P(new Error("Failed to load imports",e))),this.fire(new M(r?"style.load":"style.import.load"))}):(this._reloadImports(!0),this.fire(new M(r?"style.load":"style.import.load")))};this._styleColorTheme.colorTheme=this.stylesheet["color-theme"];const s=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(s){const e=this._evaluateColorThemeData(s);this._loadColorTheme(e).then(()=>{i()}).catch(e=>{_(`Couldn't load color theme from the stylesheet: ${e}`),i()})}else this._styleColorTheme.lut=null,i()}isRootStyle(){return 0===this.importDepth}hasAppearances(){return this._hasAppearances||this.fragments.some(e=>e.style.hasAppearances())}mergeAll(){let e,t,i,s,o,r,n,a,l,c;const h={};this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(d=>{if(d.stylesheet){if(d.disableElevatedTerrain&&(this.disableElevatedTerrain=!0),null!=d.light&&(e=d.light),d.stylesheet.lights)for(const e of d.stylesheet.lights)"ambient"===e.type&&null!=d.ambientLight&&(t=d.ambientLight),"directional"===e.type&&null!=d.directionalLight&&(i=d.directionalLight);s=this._prioritizeTerrain(s,d.terrain,d.stylesheet.terrain),d.stylesheet.fog&&null!=d.fog&&(o=d.fog),d.stylesheet.snow&&null!=d.snow&&(r=d.snow),d.stylesheet.rain&&null!=d.rain&&(n=d.rain),null!=d.stylesheet.camera&&(c=d.stylesheet.camera),null!=d.stylesheet.projection&&(a=d.stylesheet.projection),null!=d.stylesheet.transition&&(l=d.stylesheet.transition),h[d.scope]=d._styleColorTheme}}),this.light=e,this.ambientLight=t,this.directionalLight=i,this.fog=o,this.snow=r,this.rain=n,this._styleColorThemeForScope=h,null===s?delete this.terrain:this.terrain=s,this.camera=c||{"camera-projection":"perspective"},this.projection=a||{name:"mercator"},this.transition={...Bd,...l},this.mergeSources(),this.mergeLayers(),this.mergeIndoor(),this._programPrecompiler&&this._programPrecompiler.reset()}forEachFragmentStyle(e){const t=i=>{for(const e of i.fragments)t(e.style);e(i)};t(this)}_prioritizeTerrain(e,t,i){const s=e&&e.drapeRenderMode===Ja.deferred;return null===i?t&&t.drapeRenderMode===Ja.deferred?t:s?e:null:null!=t&&(!e||s||t&&t.drapeRenderMode===Ja.elevated)?t:e}mergeTerrain(){let e;this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(t=>{e=this._prioritizeTerrain(e,t.terrain,t.stylesheet.terrain)}),null===e?delete this.terrain:this.terrain=e,this._programPrecompiler&&this._programPrecompiler.reset()}mergeProjection(){let e;this.forEachFragmentStyle(t=>{null!=t.stylesheet.projection&&(e=t.stylesheet.projection)}),this.projection=e||{name:"mercator"},this._programPrecompiler&&this._programPrecompiler.reset()}mergeSources(){const e={},t=Object.create(null),i=Object.create(null),s=Object.create(null),o=Object.create(null);this.forEachFragmentStyle(r=>{for(const t in r._sourceCaches){const i=C(t,r.scope);e[i]=r._sourceCaches[t]}for(const e in r._otherSourceCaches){const i=C(e,r.scope);t[i]=r._otherSourceCaches[e]}for(const e in r._symbolSourceCaches){const t=C(e,r.scope);i[t]=r._symbolSourceCaches[e]}for(const e in r._fillExtrusionSourceCaches){const t=C(e,r.scope);s[t]=r._fillExtrusionSourceCaches[e]}if(r._hdCoverage){const e=r._hdCoverage.coverageSourceCaches;for(const t in e)o[C(t,r.scope)]=e[t]}}),this._mergedSourceCaches=e,this._mergedOtherSourceCaches=t,this._mergedSymbolSourceCaches=i,this._mergedFillExtrusionSourceCaches=s,this._mergedHdRoadCoverageSourceCaches=o,Object.keys(o).length>0&&!this._hdCoverage&&Il.HdCoverageState&&(this._hdCoverage=new Il.HdCoverageState),Il.updateCrossSourceElevationGate&&Il.updateCrossSourceElevationGate(this)}mergeIndoor(){this._mergedIndoor={},this.forEachFragmentStyle(e=>{if(e.stylesheet&&e.stylesheet.indoor)for(const t of Object.values(e.stylesheet.indoor)){const i=t,s=C(i.sourceId,e.scope);this._mergedIndoor[s]=new Set(i.sourceLayers||[])}}),this._updateIndoorEnabled()}_updateIndoorEnabled(){const e=this._indoorEnabled;if(this._indoorEnabled=!1,Object.keys(this._mergedIndoor).length>0)for(const e of this._mergedOrder){const t=this._mergedLayers[e];if("none"!==t.visibility&&this._mergedIndoor[C(t.source,t.scope)]){this._indoorEnabled=!0;break}}!this._indoorEnabled||e||this.indoorManager||Dl().then(()=>{this._initIndoorManager()})}_initIndoorManager(){if(!this.indoorManager&&Il.IndoorManager&&this.isRootStyle()&&0!==Object.keys(this._mergedIndoor).length&&(this.indoorManager=new Il.IndoorManager(this,this._loaded),this._loaded))for(const e of Object.keys(this._mergedIndoor)){const t=this._mergedSourceCaches[e]||this._mergedOtherSourceCaches[e];t&&t.reload()}}mergeLayers(){const e={},t=[],i=Object.create(null);this._mergedSlots=[],this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this.forEachFragmentStyle(i=>{for(const s of i._order){const o=i._layers[s];if("slot"===o.type){const t=Qi(s);if(e[t])continue;e[t]=[]}o.slot&&e[o.slot]?e[o.slot].push(o):t.push(o)}}),this._mergedOrder=[];let s=-1;const o=(t=[])=>{for(const r of t)if("slot"===r.type){const t=Qi(r.id);e[t]&&o(e[t]),this._mergedSlots.push(t)}else{const e=C(r.id,r.scope);this._mergedOrder.push(e),i[e]=r,r.is3D(!!this.terrain)&&(this._has3DLayers=!0,s=this._mergedOrder.length-1),"circle"===r.type&&(this._hasCircleLayers=!0),"symbol"===r.type&&(this._hasSymbolLayers=!0),"clip"===r.type&&(this._clipLayerPresent=!0)}};if(o(t),this._has3DLayers){const e={};for(let t=0;t<this._mergedOrder.length;++t){const o=this._mergedOrder[t];e[o]=t===s?1:t<s?i[o].hasOcclusionOpacityProperties?2:0:4}this._mergedOrder.sort((t,i)=>e[t]-e[i])}this._mergedLayers=i,this._mergedOrderVersion++,this.updateDrapeFirstLayers(),this._buildingIndex.processLayersChanged(),this._updateDataDrivenEmissiveStrength()}terrainSetForDrapingOnly(){return!!this.terrain&&this.terrain.drapeRenderMode===Ja.deferred}getCamera(){return this.stylesheet.camera}setCamera(e){return this.stylesheet.camera={...this.stylesheet.camera,...e},this.camera=this.stylesheet.camera,this}_evaluateColorThemeData(e){return e.data?new Hi(Cd,e.data,this.scope,this.options).possiblyEvaluate(new X(0)):null}_loadColorTheme(e){this._styleColorTheme.lutLoading=!0,this._styleColorTheme.lutLoadingCorrelationID+=1;const t=this._styleColorTheme.lutLoadingCorrelationID;return new Promise((i,s)=>{const o="data:image/png;base64,";if(!e||0===e.length)return this._styleColorTheme.lut=null,this._styleColorTheme.lutLoading=!1,void i();let r=e;r.startsWith(o)||(r=o+r);const n=g.from("mapbox-reserved-lut"),a=new Image;a.src=r,a.onerror=()=>{this._styleColorTheme.lutLoading=!1,s(new Error("Failed to load image data"))},a.onload=()=>{if(this._styleColorTheme.lutLoadingCorrelationID!==t)return void i();this._styleColorTheme.lutLoading=!1;const{width:o,height:r,data:l}=T.getImageData(a);if(r>32)return void s(new Error("The height of the image must be less than or equal to 32 pixels."));if(o!==r*r)return void s(new Error("The width of the image must be equal to the height squared."));this.getImage(n)&&this.removeImage(n),this.addImage(n,{data:new E({width:o,height:r},l),pixelRatio:1,sdf:!1,usvg:!1,version:0});const c=this.imageManager.getImage(n,this.scope);c?(this._styleColorTheme.lut={image:c.data,data:e},i()):s(new Error("Missing LUT image."))}})}getLut(e){const t=this._styleColorThemeForScope[e];return t?t.lut:null}setProjection(e){e?this.stylesheet.projection=e:delete this.stylesheet.projection,this.mergeProjection(),this._updateMapProjection()}applyProjectionUpdate(){this.map.transform.projection.requiresDraping&&this._startLiteLoad(),this._loaded&&(this.dispatcher.broadcast("setProjection",this.map.transform.projectionOptions),this.map.transform.projection.requiresDraping?(this.getTerrain()||this.stylesheet.terrain)&&!this.disableElevatedTerrain||this.setTerrainForDraping():this.terrainSetForDrapingOnly()&&this.setTerrain(null,Ja.deferred))}_updateMapProjection(){this.isRootStyle()&&(this.map._useExplicitProjection?this.applyProjectionUpdate():this.map._prioritizeAndUpdateProjection(null,this.projection))}_loadSprite(e){const t=new AbortController;this._spriteRequest=t,function(e,t,i,s){let o,r,n;const a=T.devicePixelRatio>1?"@2x":"";function l(e){n||e&&i.aborted||(e&&(n=e),function(){if(n)s(n);else if(o&&r){const e=T.getImageData(r),t={};for(const i in o){const{width:s,height:r,x:n,y:a,sdf:l,pixelRatio:c,stretchX:h,stretchY:d,content:u}=o[i],_=new E({width:s,height:r});E.copy(e,_,{x:n,y:a},{x:0,y:0},{width:s,height:r},null),t[i]={data:_,pixelRatio:void 0!==c?c:1,sdf:void 0!==l&&l,stretchX:h,stretchY:d,content:u,usvg:!1,version:0}}s(null,t)}}())}(async function(){const s=await t.transformRequest(t.normalizeSpriteURL(e,a,".json"),x.SpriteJSON,i),{data:r}=await b(s,i);n||(o=r)})().then(()=>l(void 0),e=>l(e)),async function(){const s=await t.transformRequest(t.normalizeSpriteURL(e,a,".png"),x.SpriteImage,i),{data:o}=await w(s,i);n||(r=o)}().then(()=>l(void 0),e=>l(e))}(e,this.map._requestManager,t.signal,(e,t)=>{if(this._spriteRequest=null,e)this.dispatcher.broadcast("spriteLoaded",{scope:this.scope}),this.fire(new P(e));else if(t){const e=new Map;for(const i in t)e.set(g.from(i),t[i]);this.addImages(e,!0)}this.imageManager.setLoaded(!0,this.scope),this.fire(new M("data",{dataType:"style"}))})}addIconset(e,t){if("sprite"===t.type)return void this._loadSprite(t.url);const i=this.getOwnSourceCache(t.source);if(!i)return void this.fire(new P(new Error(`Source "${t.source}" as specified by iconset "${e}" does not exist and cannot be used as an iconset source`)));if("raster-array"!==i.getSource().type)return void this.fire(new P(new Error(`Source "${t.source}" as specified by iconset "${e}" is not a "raster-array" source and cannot be used as an iconset source`)));const s=new Pd(e,this.scope,i);this.imageManager.addImageProvider(s,this.scope)}removeIconset(e){this.imageManager.removeImageProvider(e,this.scope)}_loadIconset(e){if(!r(e)&&"icon_set"!==this.map._spriteFormat||"raster"===this.map._spriteFormat)return void this._loadSprite(e);const t="auto"===this.map._spriteFormat,i=new AbortController;this._spriteRequest=i,async function(e,t,i,s){try{const o=await t.transformRequest(t.normalizeIconsetURL(e),x.Iconset,i),{data:r}=await N(o,i),n={},a=function(e){const t={icons:[]};let i;for(;i=e.nextField(void 0);)1===i&&t.icons.push(Vn(e,e.readVarint()+e.pos));return t}(new I(r));for(const e of a.icons){const t={version:1,pixelRatio:T.devicePixelRatio,content:Ad(e),stretchX:e.metadata?Ld(e.metadata.stretch_x_areas):void 0,stretchY:e.metadata?Ld(e.metadata.stretch_y_areas):void 0,sdf:!1,usvg:!0,icon:e};n[e.name]=t}s(null,n)}catch(e){i.aborted||s(e)}}(e,this.map._requestManager,i.signal,(i,s)=>{if(this._spriteRequest=null,i)t?this._loadSprite(e):(this.dispatcher.broadcast("spriteLoaded",{scope:this.scope}),this.fire(new P(i)));else if(s){const e=new Map;for(const t in s)e.set(g.from(t),s[t]);this.addImages(e,!0)}this.imageManager.setLoaded(!0,this.scope),this.fire(new M("data",{dataType:"style"}))})}_validateLayer(e){const t=this.getOwnSource(e.source);if(!t)return;const i=e.sourceLayer;i&&("geojson"===t.type||t.vectorLayerIds&&!t.vectorLayerIds.includes(i))&&this.fire(new P(new Error(`Source layer "${i}" does not exist on source "${t.id}" as specified by style layer "${e.id}"`)))}loaded(){if(!this._loaded)return!1;if(Object.keys(this._changes.getUpdatedSourceCaches()).length)return!1;for(const e in this._sourceCaches)if(!this._sourceCaches[e].loaded())return!1;if(!this.imageManager.isLoaded())return!1;if(this.imageManager.hasPatternsInFlight())return!1;if(!this.modelManager.isLoaded())return!1;if(this._styleColorTheme.lutLoading)return!1;if(!1===this._drapingLoaded)return!1;if(!1===this._rasterArrayLoaded)return!1;for(const{style:e}of this.fragments)if(!e.loaded())return!1;return!0}_serializeImports(){if(this.stylesheet.imports)return this.stylesheet.imports.map((e,t)=>{const i=this.fragments[t];return i&&i.style&&(e.data=i.style.serialize()),e})}_serializeSources(){const e={};for(const t in this._sourceCaches){const i=this._sourceCaches[t].getSource();e[i.id]||(e[i.id]=i.serialize())}return e}_serializeLayers(e){const t=[];for(const i of e){const e=this._layers[i];e&&"custom"!==e.type&&t.push(e.serialize())}return t}hasLightTransitions(){return!(!this.light||!this.light.hasTransition())||!(!this.ambientLight||!this.ambientLight.hasTransition())||!(!this.directionalLight||!this.directionalLight.hasTransition())}hasFogTransition(){return!!this.fog&&this.fog.hasTransition()}hasSnowTransition(){return!!this.snow&&this.snow.hasTransition()}hasRainTransition(){return!!this.rain&&this.rain.hasTransition()}hasTransitions(){if(this.hasLightTransitions())return!0;if(this.hasFogTransition())return!0;if(this.hasSnowTransition())return!0;if(this.hasRainTransition())return!0;for(const e in this._mergedSourceCaches)if(this._mergedSourceCaches[e].hasTransition())return!0;for(const e in this._mergedLayers)if(this._mergedLayers[e].hasTransition())return!0;return!1}_updateDataDrivenEmissiveStrength(){for(const e in this._mergedLayers){const t=this._mergedLayers[e].getPaintPropertyValue("line-emissive-strength");if(t&&t.isDataDriven())return void(this._hasDataDrivenEmissive=!0)}this._hasDataDrivenEmissive=!1}hasDataDrivenEmissiveStrength(){return this._hasDataDrivenEmissive}get order(){return this.terrain?this._drapedFirstOrder:this._mergedOrder}_getOrder(e){return e?this.order:this._mergedOrder}isLayerDraped(e){return!!this.terrain&&e.isDraped(this.getLayerSourceCache(e))}_checkLoaded(){if(!this._loaded)throw new Error("Style is not done loading")}_checkLayer(e){const t=this.getOwnLayer(e);if(t)return t;this.fire(new P(new Error(`The layer '${e}' does not exist in the map's style.`)))}_checkSource(e){const t=this.getOwnSource(e);if(t)return t;this.fire(new P(new Error(`The source '${e}' does not exist in the map's style.`)))}_resolveLayerFragment(e){const t=this.getLayer(e);if(!t)return void this.fire(new P(new Error(`The layer '${e}' does not exist in the map's style.`)));const i=this.getFragmentStyle(t.scope);return i?{layer:t,fragment:i}:void 0}handleIdle(){const e=this.map.painter;e&&(e.context.sweepPendingPrograms(),this._programPrecompiler&&this._programPrecompiler.processQueue(e,this))}handleContextLost(){this._programPrecompiler&&this._programPrecompiler.reset()}update(e){if(!this._loaded)return;this.ambientLight&&this.ambientLight.recalculate(e),this.directionalLight&&this.directionalLight.recalculate(e);const t=this.calculateLightsBrightness();e.brightness=t||0;let i=!1;t!==this._brightness&&(this._brightness=t,i=!0),e.worldview!==this._worldview&&(this._worldview=e.worldview,i=!0),i&&this.dispatcher.broadcast("upsertRenderParams",{brightness:this._brightness,worldview:this._worldview});const s=this._changes.isDirty();let o=!1;if(this._changes.isDirty()){const t=this._changes.getLayerUpdatesByScope();for(const e in t){const{updatedIds:i,removedIds:s}=t[e];(i||s)&&(this._updateWorkerLayers(e,i,s),o=!0)}this.updateSourceCaches(),this._updateTilesForChangedImages(),this.updateLayers(e),this.light&&this.light.updateTransitions(e),this.ambientLight&&this.ambientLight.updateTransitions(e),this.directionalLight&&this.directionalLight.updateTransitions(e),this.fog&&this.fog.updateTransitions(e),this.snow&&this.snow.updateTransitions(e),this.rain&&this.rain.updateTransitions(e),this._changes.reset()}const r={};for(const e in this._mergedSourceCaches){const t=this._mergedSourceCaches[e];r[e]=t.used,t.used=!1,t.tileCoverLift=0}const n={};for(const t of this._mergedOrder){const i=this._mergedLayers[t],s=i.paint;if("none"===i.visibility&&!i.hasTransition()||!i._dirty&&i.isHidden(e.zoom)||i.recalculate(e,this._availableImages),s&&s!==i.paint&&i.isPlacementAffectedByPaintChanges(s)&&this._setLabelPlacementStale(),!i.isHidden(e.zoom)){i.mayUse("HD")&&(i.prepare(),Dl()),i.mayUse("Standard")&&(i.prepare(),Cl()),i.mayUse("Lite")&&(this.checkCanvasFingerprintNoise(),this.disableElevatedTerrain||this._startLiteLoad()),i.mayUse("RasterArray")&&this._startRasterArrayLoad();const e=this.getLayerSourceCache(i);e&&(e.used=!0,e.tileCoverLift=Math.max(e.tileCoverLift,i.tileCoverLift()))}if(i.source){const e=this._mergedHdRoadCoverageSourceCaches[i.sourceFqid];e&&!e.used&&(e.used=!0)}if("fill-extrusion"===i.type){const e=C(i.source,i.scope);if(e in this._mergedFillExtrusionSourceCaches){const t=i.layout&&i.layout.get("source-max-zoom");if(null!=t){const i=n[e];n[e]=null==i?t:Math.min(i,t)}}}}if(this._programPrecompiler&&this._programPrecompiler.needsBuild()){const t=this._mergedOrder.map(e=>this._mergedLayers[e]);this._programPrecompiler.buildQueue(t,e,this)}for(const e in this._mergedFillExtrusionSourceCaches)this._mergedFillExtrusionSourceCaches[e].setMaxzoomOverride(n[e]??null);this.terrain&&o&&this.mergeLayers();const a=this.imageManager.getPendingImageProviders();for(const e of a)e.sourceCache.used=!0;for(const e in r){const t=this._mergedSourceCaches[e],i=t.getSource();t.used&&i instanceof Jl&&i.startLoad(),r[e]!==t.used&&i.fire(new M("data",{sourceDataType:"visibility",dataType:"source",sourceId:i.id}))}this.light&&this.light.recalculate(e),this.terrain&&this.terrain.recalculate(e),this.fog&&this.fog.recalculate(e),this.snow&&this.snow.recalculate(e),this.rain&&this.rain.recalculate(e),this.z=e.zoom,this._markersNeedUpdate&&(this._updateMarkersOpacity(),this._markersNeedUpdate=!1),this.imageManager.clearUpdatedImages(this.scope),s&&this.fire(new M("data",{dataType:"style"}))}updateImageProviders(){const e=this.imageManager.getPendingImageProviders();for(const t of e){const e=t.resolvePendingRequests(),i=this.getFragmentStyle(t.scope);i&&i.addImages(e)}}_updateTilesForChangedImages(){const e={};for(const t in this._mergedSourceCaches){const i=this._mergedSourceCaches[t].getSource().scope;e[i]=e[i]||this._changes.getUpdatedImages(i),0!==e[i].length&&this._mergedSourceCaches[t].reloadTilesForDependencies(["icons","patterns"],e[i])}for(const t in e)this._changes.resetUpdatedImages(t)}_updateWorkerLayers(e,t,i){const s=this.getFragmentStyle(e);s&&this.dispatcher.broadcast("updateLayers",{layers:t?s._serializeLayers(t):[],scope:e,removedIds:i||[],options:s.options})}setState(e,t){if(this._checkLoaded(),Md(this,Oa(e)))return!1;if((e=Ji(e)).layers=Bc(e.layers),!Ca.diffStyles)throw new Error("Debug module not loaded; cannot diff style.");const i=Ca.diffStyles(this.serialize(),e).filter(e=>!zd.has(e.command));if(0===i.length)return!1;const s=i.filter(e=>!Od.has(e.command));if(s.length>0)throw new Error(`Unimplemented: ${s.map(e=>e.command).join(", ")}.`);const o=[];return i.forEach(e=>{o.push(this[e.command](...e.args))}),t&&Promise.all(o).then(t).catch(t),this.stylesheet=e,this.mergeAll(),this.dispatcher.broadcast("setLayers",{layers:this._serializeLayers(this._order),scope:this.scope,options:this.options}),!0}_updateWorkerImages(e=!1){this._availableImages=this.imageManager.listImages(this.scope);const t={scope:this.scope,images:this._availableImages};e&&(t.isSpriteLoaded=!0),this.dispatcher.broadcast("setImages",t)}_updateWorkerModels(){this._availableModels=this.modelManager.getModelURIs(this.scope),this.dispatcher.broadcast("setModels",{scope:this.scope,models:this._availableModels})}addImages(e,t){if(0===e.size)return t&&this.dispatcher.broadcast("spriteLoaded",{scope:this.scope}),this;for(const[t,i]of e.entries()){if(this.getImage(t))return this.fire(new P(new Error(`An image with the name "${t.name}" already exists.`)));this.imageManager.addImage(t,this.scope,i),this._changes.updateImage(t,this.scope)}return this._updateWorkerImages(t),this.fire(new M("data",{dataType:"style"})),this}addImage(e,t){return this.getImage(e)?this.fire(new P(new Error(`An image with the name "${e.name}" already exists.`))):(this.imageManager.addImage(e,this.scope,t),this._changes.updateImage(e,this.scope),this._updateWorkerImages(),this.fire(new M("data",{dataType:"style"})),this)}updateImage(e,t,i=!1){this.imageManager.updateImage(e,this.scope,t),i&&(this._changes.updateImage(e,this.scope),this._updateWorkerImages(),this.fire(new M("data",{dataType:"style"})))}getImage(e){return this.imageManager.getImage(e,this.scope)}removeImage(e){return this.getImage(e)?(this.imageManager.removeImage(e,this.scope),this._changes.updateImage(e,this.scope),this._updateWorkerImages(),this.fire(new M("data",{dataType:"style"})),this):this.fire(new P(new Error("No image with this name exists.")))}listImages(){return this._checkLoaded(),this._availableImages.slice()}getActualScope(){return this._importedAsBasemap?"basemap":this.scope}addModelURLs(e){return this.modelManager.addModelURLs(e,this.getActualScope()),this._updateWorkerModels(),this.fire(new M("data",{dataType:"style"})),this}addModel(e,t,i={}){return this._checkLoaded(),this._validate(Wa,`models.${e}`,t,null,i)||(this.modelManager.addModel(e,t,this.getActualScope()),this.fire(new M("data",{dataType:"style"}))),this}hasModel(e){return this.modelManager.hasModel(e,this.getActualScope())}removeModel(e){return this.hasModel(e)?(this.modelManager.removeModel(e,this.getActualScope(),!1,!0),this.fire(new M("data",{dataType:"style"})),this):this.fire(new P(new Error("No model with this ID exists.")))}listModels(){return this._checkLoaded(),this.modelManager.listModels(this.getActualScope())}addSource(e,t,i={}){if(this._checkLoaded(),void 0!==this.getOwnSource(e))throw new Error(`There is already a source with ID "${e}".`);if(!t.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(t).join(", ")}.`);if(["vector","raster","geojson","video","image"].includes(t.type)&&this._validate(za,`sources.${e}`,t,null,i))return;this.map&&this.map._collectResourceTiming&&(t.collectResourceTiming=!0);const s=Object.hasOwn(Kl,t.type)&&!Yl(t.type)?function(e,t,i,s){switch(t.type){case"raster-array":return new Ql(e,t,i,s);case"model":return new ec(e,t,i,s);default:return new Jl(e,t,i,s)}}(e,t,this.dispatcher,this):void 0,o=s||Xl(e,t,this.dispatcher,this);o.scope=this.scope;const r=e=>{e.setEventedParent(this,()=>({isSourceLoaded:this._isSourceCacheLoaded(e.id),source:e.serialize(),sourceId:e.id}))};r(o);const n=e=>{const t=(e===Ot.Symbol?"symbol:":e===Ot.FillExtrusion?"fill-extrusion:":"other:")+o.id,i=C(t,this.scope),s=this._sourceCaches[t]=new Ac(i,o,e);e===Ot.Symbol?this._symbolSourceCaches[o.id]=s:e===Ot.FillExtrusion?this._fillExtrusionSourceCaches[o.id]=s:this._otherSourceCaches[o.id]=s,s.onAdd(this.map)};n(Ot.Other),"vector"!==t.type&&"geojson"!==t.type||(n(Ot.Symbol),"vector"===t.type&&n(Ot.FillExtrusion)),o.onAdd&&o.onAdd(this.map),s&&(s._loader=()=>{(async function(e){if(Yl(e))return;const t=Kl[e];if(!t)throw new Error(`Unknown source type "${e}"`);const i=await t();i&&!Yl(e)&&function(e,t){$l[e]=t}(e,i)})(t.type).then(()=>{const i=Yl(t.type),n=this._otherSourceCaches[e];if(!n||n.getSource()!==o)return;if(!i)return void this.fire(new P(new Error(`Could not load module for source type "${t.type}".`)));const a=Xl(e,s._options,this.dispatcher,this);a.scope=this.scope,r(a),n.setSource(a),a.onAdd&&a.onAdd(this.map),this._changes.setDirty()})}),i.isInitialLoad||(this.mergeSources(),this._changes.setDirty())}removeSource(e){this._checkLoaded();const t=this.getOwnSource(e);if(!t)throw new Error("There is no source with this ID");for(const t in this._layers)if(this._layers[t].source===e)return this.fire(new P(new Error(`Source "${e}" cannot be removed while layer "${t}" is using it.`)));if(this.terrain&&this.terrain.scope===this.scope&&this.terrain.get().source===e)return this.fire(new P(new Error(`Source "${e}" cannot be removed while terrain is using it.`)));if(this.stylesheet.iconsets){const t=Object.entries(this.stylesheet.iconsets).find(([t,i])=>"source"===i.type&&i.source===e);if(t)return this.fire(new P(new Error(`Source "${e}" cannot be removed while iconset "${t[0]}" is using it.`)))}const i=this.getOwnSourceCaches(e);for(const e of i){const t=Qi(e.id);delete this._sourceCaches[t],this._changes.discardSourceCacheUpdate(e.id),e.fire(new M("data",{sourceDataType:"metadata",dataType:"source",sourceId:e.getSource().id})),e.setEventedParent(null),e.clearTiles()}return delete this._otherSourceCaches[e],delete this._symbolSourceCaches[e],delete this._fillExtrusionSourceCaches[e],this._hdCoverage&&delete this._hdCoverage.coverageSourceCaches[e],this.mergeSources(),t.setEventedParent(null),t.onRemove&&t.onRemove(this.map),this.dispatcher.broadcast("removeSource",{type:t.type,source:e,scope:t.scope}),this._changes.setDirty(),this}setGeoJSONSourceData(e,t){this._checkLoaded(),this.getOwnSource(e).setData(t),this._changes.setDirty()}getOwnSource(e){const t=this.getOwnSourceCache(e);return t&&t.getSource()}getOwnSources(){const e=[];for(const t in this._otherSourceCaches){const i=this.getOwnSourceCache(t);i&&e.push(i.getSource())}return e}areTilesLoaded(){const e=this._mergedSourceCaches;for(const t in e){const i=e[t];for(const e of i._tiles.values())if("loaded"!==e.state&&"errored"!==e.state)return!1}return!0}setLights(e){if(this._checkLoaded(),this._programPrecompiler&&this._programPrecompiler.reset(),!e)return delete this.ambientLight,void delete this.directionalLight;const t=this._getTransitionParameters();for(const i of e){if(this._validate(ka,"lights",i))return;switch(i.type){case"ambient":if(this.ambientLight){const e=this.ambientLight;e.set(i),e.updateTransitions(t)}else this.ambientLight=new fl(i,gl(),this.scope,this.options);break;case"directional":if(this.directionalLight){const e=this.directionalLight;e.set(i),e.updateTransitions(t)}else this.directionalLight=new fl(i,yl(),this.scope,this.options)}}const i=Object.assign(t,{worldview:this.map.getWorldview()}),s=new X(this.z||0,i);this.ambientLight&&this.ambientLight.recalculate(s),this.directionalLight&&this.directionalLight.recalculate(s),this._brightness=this.calculateLightsBrightness(),this.dispatcher.broadcast("upsertRenderParams",{brightness:this._brightness})}calculateLightsBrightness(){const e=this.directionalLight,t=this.ambientLight;if(!e||!t)return;const i=e=>.2126*(e[0]<=.03928?e[0]/12.92:Math.pow((e[0]+.055)/1.055,2.4))+.7152*(e[1]<=.03928?e[1]/12.92:Math.pow((e[1]+.055)/1.055,2.4))+.0722*(e[2]<=.03928?e[2]/12.92:Math.pow((e[2]+.055)/1.055,2.4)),s=e.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),o=e.properties.get("intensity"),r=e.properties.get("direction"),n=1-Ii(r.x,r.y,r.z)[2]/90,a=i(s)*o*n,l=t.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),c=t.properties.get("intensity"),h=i(l)*c;return Number(((a+h)/2).toFixed(6))}getBrightness(){return this._brightness}getLights(){if(!this.enable3dLights())return null;const e=[];return this.directionalLight&&e.push(this.directionalLight.get()),this.ambientLight&&e.push(this.ambientLight.get()),e}enable3dLights(){return!!this.ambientLight&&!!this.directionalLight}getFragmentStyle(e){if(null==e||""===e&&this.isRootStyle())return this;if(es(e)){const t=ts(e),i=this.fragments.find(({id:e})=>e===t);if(!i)return;const s=Qi(e);return i.style.getFragmentStyle(s)}{const t=this.fragments.find(({id:t})=>t===e);return t?t.style:void 0}}setFeaturesetSelectors(e){if(!e)return;const t=(e,t="")=>`${e}::${t}`;this._featuresetSelectors={};for(const i in e){const s={},o=this._featuresetSelectors[i]=[];for(const r of e[i].selectors){if(r.featureNamespace){const e=this.getOwnLayer(r.layer);if(!e){_(`Layer is undefined for selector: ${r.layer}`);continue}const o=t(e.source,e.sourceLayer);if(o in s&&s[o]!==r.featureNamespace){_(`"featureNamespace ${r.featureNamespace} of featureset ${i}'s selector is not associated to the same source, skip this selector`);continue}s[o]=r.featureNamespace}let e;if(r.properties)for(const t in r.properties){const i=v(r.properties[t]);"success"===i.result&&(e=e||{},e[t]=i.value)}o.push({layerId:r.layer,namespace:r.featureNamespace,properties:e,uniqueFeatureID:r._uniqueFeatureID})}}}getFeaturesetDescriptors(e){const t=this.getFragmentStyle(e);if(!t||!t.stylesheet.featuresets)return[];const i=[];for(const e in t.stylesheet.featuresets)i.push({featuresetId:e,importId:t.scope?t.scope:void 0});return i}getFeaturesetLayers(e,t){const i=this.getFragmentStyle(t),s=i.stylesheet.featuresets;if(!s||!s[e])return this.fire(new P(new Error(`The featureset '${e}' does not exist in the map's style and cannot be queried.`))),[];const o=[];for(const t of s[e].selectors){const e=i.getOwnLayer(t.layer);e&&o.push(e)}return o}getConfigProperty(e,t){const i=this.getFragmentStyle(e);if(!i)return null;const s=C(t,i.scope),o=i.options.get(s),r=o?o.value||o.default:null;return r?r.serialize():null}isIndoorEnabled(){return this._indoorEnabled}getIndoorSourceLayers(e,t){const i=C(e,t);return this._mergedIndoor[i]}setIndoorData(e,t){this.indoorManager&&this.indoorManager.setIndoorData(t)}updateIndoorDependentLayers(){this._updateLayers(this._dependentLayerIds(e=>e.isIndoorDependent)),this.map._styleDirty=!0,this.map.triggerRepaint()}setConfigProperty(e,t,i){const s=this.getFragmentStyle(e);if(!s)return;const o=s.stylesheet.schema;if(!o||!o[t])return;const r=is(i,o[t]);if("success"!==r.result)return void Md(this,r.value);const n=r.value.expression,a=C(t,s.scope),l=s.options.get(a);if(!l)return;let c;const{minValue:h,maxValue:d,stepValue:u,type:_,values:p}=o[t],f=is(o[t].default,o[t]);"success"===f.result&&(c=f.value.expression),c?(this.options.set(a,{...l,value:n,default:c,minValue:h,maxValue:d,stepValue:u,type:_,values:p}),this.updateConfigDependencies(t)):this.fire(new P(new Error(`No schema defined for the config option "${t}" in the "${e}" fragment.`)))}getConfig(e){const t=this.getFragmentStyle(e);if(!t)return null;const i=t.stylesheet.schema;if(!i)return null;const s={};for(const e in i){const i=C(e,t.scope),o=t.options.get(i),r=o?o.value||o.default:null;s[e]=r?r.serialize():null}return s}setConfig(e,t){const i=this.getFragmentStyle(e);i&&(i.updateConfig(t,i.stylesheet.schema),this.updateConfigDependencies())}getSchema(e){const t=this.getFragmentStyle(e);return t?t.stylesheet.schema:null}setSchema(e,t){const i=this.getFragmentStyle(e);i&&(i.stylesheet.schema=t,i.updateConfig(i._config,t),this.updateConfigDependencies())}updateConfig(e,t){if(this._config=e,e||t)if(t)for(const i in t){let s,o;const r=is(t[i].default,t[i]);if("success"===r.result&&(s=r.value.expression),e&&void 0!==e[i]){const s=is(e[i],t[i]);"success"===s.result&&(o=s.value.expression)}const{minValue:n,maxValue:a,stepValue:l,type:c,values:h}=t[i];if(s){const e=C(i,this.scope);this.options.set(e,{default:s,value:o,minValue:n,maxValue:a,stepValue:l,type:c,values:h})}else this.fire(new P(new Error(`No schema defined for config option "${i}".`)))}else this.fire(new P(new Error("Attempting to set config for a style without schema.")))}_updateLayers(e){for(const t of e){const e=this.getLayer(t);e&&(e.possiblyEvaluateVisibility(),e._dirty=!0,this._updateLayer(e),this._changes.setDirty())}}_dependentLayerIds(e){const t=[];for(const[i,s]of this._layerExpressionDependencies)e(s)&&t.push(i);return t}_updateEnvConfig(e="update"){const t="reset"===e?"resetConfig":"updateConfig";this.ambientLight&&this.ambientLight[t](this.options),this.directionalLight&&this.directionalLight[t](this.options),this.fog&&this.fog[t](this.options),this.snow&&this.snow[t](this.options),this.rain&&this.rain[t](this.options)}updateConfigDependencies(e){this._updateLayers(this._dependentLayerIds(t=>t.hasConfigDependency(e))),this._updateEnvConfig(),this.forEachFragmentStyle(e=>{const t=e._styleColorTheme.colorThemeOverride?e._styleColorTheme.colorThemeOverride:e._styleColorTheme.colorTheme;if(t){const i=e._evaluateColorThemeData(t);(!e._styleColorTheme.lut&&""!==i||e._styleColorTheme.lut&&i!==e._styleColorTheme.lut.data)&&e.setColorTheme(t)}}),this._updateIndoorEnabled(),this._changes.setDirty()}addLayer(e,t,i={}){this._checkLoaded();const s=e.id;if(this._layers[s])return void this.fire(new P(new Error(`Layer with id "${s}" already exists on this map`)));let o;if("custom"===e.type){if(Md(this,ss(e)))return;o=os(e,this.scope,this._styleColorTheme.lut,this.options)}else{if("object"==typeof e.source&&(this.addSource(s,e.source),e=Ji(e),e=Object.assign(e,{source:s})),this._validate(ja,`layers.${s}`,e,{arrayIndex:-1},i))return;o=os(e,this.scope,this._styleColorTheme.lut,this.options),this._validateLayer(o),o.setEventedParent(this,{layer:{id:s}})}this._layerExpressionDependencies.set(o.fqid,new kn(o));let r=this._order.length;if(t){const e=this._order.indexOf(t);if(-1===e)return void this.fire(new P(new Error(`Layer with id "${t}" does not exist on this map.`)));o.slot&&o.slot!==this._layers[t].slot?_(`Layer with id "${t}" has a different slot. Layers can only be rearranged within the same slot.`):r=e}this._order.splice(r,0,s),this._handleLayerOrderChange(),this._layers[s]=o;const n=this.getOwnLayerSourceCache(o),a=!!this.directionalLight&&this.directionalLight.shadowsEnabled();n&&o.canCastShadows()&&a&&(n.castsShadows=!0);const l=this._changes.getRemovedLayer(o);if(l&&o.source&&n&&"custom"!==o.type){this._changes.discardLayerRemoval(o);const e=C(o.source,o.scope);l.type!==o.type?this._changes.updateSourceCache(e,"clear"):(this._changes.updateSourceCache(e,"reload"),n.pause())}this._updateLayer(o),o.onAdd&&o.onAdd(this.map),o.scope=this.scope,this.mergeLayers()}moveLayer(e,t){this._checkLoaded();const i=this._checkLayer(e);if(!i)return;if(e===t)return;const s=this._order.indexOf(e);this._order.splice(s,1);let o=this._order.length;if(t){const e=this._order.indexOf(t);if(-1===e)return void this.fire(new P(new Error(`Layer with id "${t}" does not exist on this map.`)));i.slot&&i.slot!==this._layers[t].slot?_(`Layer with id "${t}" has a different slot. Layers can only be rearranged within the same slot.`):o=e}this._order.splice(o,0,e),this._changes.setDirty(),this._handleLayerOrderChange(),this.mergeLayers()}removeLayer(e){this._checkLoaded();const t=this._checkLayer(e);if(!t)return;t.setEventedParent(null);const i=this._order.indexOf(e);this._order.splice(i,1),delete this._layers[e],this._changes.setDirty(),this._handleLayerOrderChange(),this._layerExpressionDependencies.delete(t.fqid),this._changes.removeLayer(t);const s=this.getOwnLayerSourceCache(t);if(s&&s.castsShadows){let e=!1;for(const i in this._layers)if(this._layers[i].source===t.source&&this._layers[i].canCastShadows()){e=!0;break}s.castsShadows=e}t.onRemove&&t.onRemove(this.map),this.mergeLayers()}getOwnLayer(e){return this._layers[e]}hasLayer(e){return e in this._mergedLayers}hasLayerType(e){for(const t in this._layers)if(this._layers[t].type===e)return!0;return!1}setLayerZoomRange(e,t,i){this._checkLoaded();const s=this._checkLayer(e);s&&(s.minzoom===t&&s.maxzoom===i||(null!=t&&(s.minzoom=t),null!=i&&(s.maxzoom=i),this._updateLayer(s)))}getSlots(){return this._checkLoaded(),this._mergedSlots}setSlot(e,t){this._checkLoaded();const i=this._checkLayer(e);i&&i.slot!==t&&(i.slot=t,this._updateLayer(i))}setFilter(e,t,i={}){this._checkLoaded();const s=this._checkLayer(e);if(!s)return;if(rs(s.filter,t))return;const o=this._layerExpressionDependencies.get(s.fqid);if(null==t)return s.filter=void 0,o&&o.invalidateFilter(),void this._updateLayer(s);this._validate(Ga,`layers.${s.id}.filter`,t,{layerType:s.type},i)||(s.filter=Ji(t),o&&o.invalidateFilter(),this._updateLayer(s))}getFilter(e){const t=this._checkLayer(e);if(t)return Ji(t.filter)}setLayoutProperty(e,t,i,s={}){this._checkLoaded();const o=this._checkLayer(e);if(o&&!rs(o.getLayoutProperty(t),i)){if(null!=i&&(!s||!1!==s.validate)&&Md(o,Za.call(Oa,{key:`layers.${e}.layout.${t}`,layerType:o.type,objectKey:t,value:i,styleSpec:y,style:{glyphs:!0,sprite:!0}})))return;o.setLayoutProperty(t,i),this._updateLayer(o)}}getLayerProperty(e,t){const i=this._checkLayer(e);if(i){switch(t){case"minzoom":return i.minzoom;case"maxzoom":return i.maxzoom;case"filter":return this.getFilter(e);case"slot":return i.slot;case"appearances":return i.getAppearances().map(e=>e.serialize())}return i.isPaintProperty(t)?this.getPaintProperty(e,t):this.getLayoutProperty(e,t)}}setLayerProperty(e,t,i,s={}){this._checkLoaded();const o=this._checkLayer(e);if(o){switch(t){case"appearances":return o.setAppearances(i),void this._updateLayer(o);case"minzoom":return this.setLayerZoomRange(e,i);case"maxzoom":return this.setLayerZoomRange(e,null,i);case"filter":return this.setFilter(e,i,s);case"slot":return this.setSlot(e,i)}o.isPaintProperty(t)?this.setPaintProperty(e,t,i,s):this.setLayoutProperty(e,t,i,s)}}getLayoutProperty(e,t){const i=this._checkLayer(e);if(i)return i.getLayoutProperty(t)}setPaintProperty(e,t,i,s={}){this._checkLoaded();const o=this._checkLayer(e);o&&(rs(o.getPaintProperty(t),i)||(null==i||s&&!1===s.validate||!Md(o,qa.call(Oa,{key:`layers.${e}.paint.${t}`,layerType:o.type,objectKey:t,value:i,styleSpec:y})))&&(o.setPaintProperty(t,i)&&this._updateLayer(o),this._changes.updatePaintProperties(o)))}getPaintProperty(e,t){const i=this._checkLayer(e);if(i)return i.getPaintProperty(t)}setFeatureState(e,t){if(this._checkLoaded(),"target"in e){if("featuresetId"in e.target){const{featuresetId:i,importId:s}=e.target,o=this.getFragmentStyle(s),r=o.getFeaturesetLayers(i);for(const{source:i,sourceLayer:s}of r)o.setFeatureState({id:e.id,source:i,sourceLayer:s},t)}else if("layerId"in e.target){const i=this._resolveLayerFragment(e.target.layerId);i?.fragment.setFeatureState({id:e.id,source:i.layer.source,sourceLayer:i.layer.sourceLayer},t)}return}const i=e.source,s=e.sourceLayer,o=this._checkSource(i);if(!o)return;const r=o.type;if("geojson"===r&&s)return void this.fire(new P(new Error("GeoJSON sources cannot have a sourceLayer parameter.")));if("vector"===r&&!s)return void this.fire(new P(new Error("The sourceLayer parameter must be provided for vector source types.")));void 0===e.id&&this.fire(new P(new Error("The feature id parameter must be provided.")));const n=this.getOwnSourceCaches(i);for(const i of n)i.setFeatureState(s,e.id,t)}removeFeatureState(e,t){if(this._checkLoaded(),"target"in e){if("featuresetId"in e.target){const{featuresetId:i,importId:s}=e.target,o=this.getFragmentStyle(s),r=o.getFeaturesetLayers(i);for(const{source:i,sourceLayer:s}of r)o.removeFeatureState({id:e.id,source:i,sourceLayer:s},t)}else if("layerId"in e.target){const i=this._resolveLayerFragment(e.target.layerId);i?.fragment.removeFeatureState({id:e.id,source:i.layer.source,sourceLayer:i.layer.sourceLayer},t)}return}const i=e.source,s=this._checkSource(i);if(!s)return;const o=s.type,r="vector"===o?e.sourceLayer:void 0;if("vector"===o&&!r)return void this.fire(new P(new Error("The sourceLayer parameter must be provided for vector source types.")));if(t&&"string"!=typeof e.id&&"number"!=typeof e.id)return void this.fire(new P(new Error("A feature id is required to remove its specific state property.")));const n=this.getOwnSourceCaches(i);for(const i of n)i.removeFeatureState(r,e.id,t)}getFeatureState(e){if(this._checkLoaded(),"target"in e){let t;if("featuresetId"in e.target){const{featuresetId:i,importId:s}=e.target,o=this.getFragmentStyle(s),r=o.getFeaturesetLayers(i);for(const{source:i,sourceLayer:s}of r){const r=o.getFeatureState({id:e.id,source:i,sourceLayer:s});if(r&&!t)t=r;else if(!rs(t,r))return void this.fire(new P(new Error("The same feature id exists in multiple sources in the featureset, but their feature states are not consistent through the sources.")))}}else if("layerId"in e.target){const i=this._resolveLayerFragment(e.target.layerId);t=i?.fragment.getFeatureState({id:e.id,source:i.layer.source,sourceLayer:i.layer.sourceLayer})}return t}const t=e.source,i=e.sourceLayer,s=this._checkSource(t);if(s){if("vector"!==s.type||i)return void 0===e.id&&this.fire(new P(new Error("The feature id parameter must be provided."))),this.getOwnSourceCaches(t)[0].getFeatureState(i,e.id);this.fire(new P(new Error("The sourceLayer parameter must be provided for vector source types.")))}}resetFeatureStates(e){if(this._checkLoaded(),"featuresetId"in e){const{featuresetId:t,importId:i}=e,s=this.getFragmentStyle(i);if(!s)return;const o=s.getFeaturesetLayers(t);for(const{source:e,sourceLayer:t}of o)s.removeFeatureState({source:e,sourceLayer:t})}else{const t=this._resolveLayerFragment(e.layerId);t?.fragment.removeFeatureState({source:t.layer.source,sourceLayer:t.layer.sourceLayer})}}setTransition(e){return this.stylesheet.transition={...this.stylesheet.transition,...e},this.transition=this.stylesheet.transition,this}getTransition(){return{...this.stylesheet.transition}}setWorldview(e){e!==this._worldview&&(this._worldview=e,this.dispatcher.broadcast("upsertRenderParams",{worldview:this._worldview}),this.reloadSources())}serialize(){this._checkLoaded();const e=this.getTerrain(),t=e&&this.terrain&&this.terrain.scope===this.scope?e:this.stylesheet.terrain;return ns({version:this.stylesheet.version,name:this.stylesheet.name,metadata:this.stylesheet.metadata,fragment:this.stylesheet.fragment,iconsets:this.stylesheet.iconsets,featuresets:this.stylesheet.featuresets,imports:this._serializeImports(),schema:this.stylesheet.schema,camera:this.stylesheet.camera,light:this.stylesheet.light,lights:this.stylesheet.lights,terrain:t,fog:this.stylesheet.fog,snow:this.stylesheet.snow,rain:this.stylesheet.rain,indoor:this.stylesheet.indoor,center:this.stylesheet.center,"color-theme":this.stylesheet["color-theme"],zoom:this.stylesheet.zoom,bearing:this.stylesheet.bearing,pitch:this.stylesheet.pitch,sprite:this.stylesheet.sprite,glyphs:this.stylesheet.glyphs,transition:this.stylesheet.transition,projection:this.stylesheet.projection,sources:this._serializeSources(),layers:this._serializeLayers(this._order)},e=>void 0!==e)}_updateFilteredLayers(e){for(const t of Object.values(this._mergedLayers))e(t)&&this._updateLayer(t)}_updateLayer(e){this._changes.updateLayer(e);const t=this.getLayerSourceCache(e),i=e.sourceFqid,s=this._changes.getUpdatedSourceCaches();e.source&&!s[i]&&t&&"raster"!==t.getSource().type&&(this._changes.updateSourceCache(i,"reload"),t.pause()),e.invalidateCompiledFilter()}_flattenAndSortRenderedFeatures(e){const t=e=>this._mergedLayers[e].is3D(!!this.terrain),i=this.order,s={},o=[];for(let r=i.length-1;r>=0;r--){const n=i[r];if(t(n)){s[n]=r;for(const t of e){const e=t[n];if(e)for(const t of e)o.push(t)}}}o.sort((e,t)=>t.intersectionZ-e.intersectionZ);const r=[];for(let n=i.length-1;n>=0;n--){const a=i[n];if(t(a))for(let e=o.length-1;e>=0;e--){const t=o[e].feature;if(t.layer&&s[t.layer.id]<n)break;r.push(t),o.pop()}else for(const t of e){const e=t[a];if(e)for(const t of e)r.push(t.feature)}}return r}queryRasterValue(e,t,i){const s=this.getOwnSource(e);return s?"raster-array"!==s.type?(this.fire(new P(new Error('queryRasterValue support only "raster-array" sources.'))),Promise.resolve(null)):s.queryRasterArrayValue(t,i):(this.fire(new P(new Error(`Source with id "${e}" does not exist in the style.`))),Promise.resolve(null))}queryRenderedFeatures(e,t,i){let s;t&&!Array.isArray(t)&&t.filter&&(this._validate(Ga,"queryRenderedFeatures.filter",t.filter,null,t),s=dt(t.filter));const o={},r=e=>{if(Fd.has(e.type))return;const t=this.getOwnLayerSourceCache(e),i=o[t.id]=o[t.id]||{sourceCache:t,layers:{},has3DLayers:!1};e.is3D(!!this.terrain)&&(i.has3DLayers=!0),i.layers[e.fqid]=i.layers[e.fqid]||{styleLayer:e,targets:[]},i.layers[e.fqid].targets.push({filter:s})};if(t&&t.layers){if(!Array.isArray(t.layers))return this.fire(new P(new Error("parameters.layers must be an Array."))),[];for(const e of t.layers){const t=this._layers[e];if(!t)return this.fire(new P(new Error(`The layer '${e}' does not exist in the map's style and cannot be queried for features.`))),[];r(t)}}else for(const e in this._layers)r(this._layers[e]);const n=this._queryRenderedFeatures(e,o,i),a=this._flattenAndSortRenderedFeatures(n),l=[];for(const e of a)as(e.layer.id)===this.scope&&l.push(e);return l}queryRenderedFeatureset(e,t,i){let s;t&&!Array.isArray(t)&&t.filter&&(this._validate(Ga,"queryRenderedFeatures.filter",t.filter,null,t),s=dt(t.filter));const o="mock",r=[];if(t&&t.target)r.push({...t,targetId:o,filter:s});else{const e=this.getFeaturesetDescriptors();for(const t of e)r.push({targetId:o,filter:s,target:t});for(const{style:e}of this.fragments){const t=e.getFeaturesetDescriptors();for(const e of t)r.push({targetId:o,filter:s,target:e})}}const n=this.queryRenderedTargets(e,r,i),a=[],l=new Set;for(const e of n)for(const t of e.variants[o])ic(t,e,l)||a.push(new ls(e,t));return a}queryRenderedTargets(e,t,i){const s={},o=(e,t,i,o)=>{const r=s[t.id]=s[t.id]||{sourceCache:t,layers:{},has3DLayers:!1};if(r.layers[e.fqid]=r.layers[e.fqid]||{styleLayer:e,targets:[]},e.is3D(!!this.terrain)&&(r.has3DLayers=!0),!o)return i.uniqueFeatureID=!1,void r.layers[e.fqid].targets.push(i);r.layers[e.fqid].targets.push({...i,namespace:o.namespace,properties:o.properties,uniqueFeatureID:o.uniqueFeatureID})};for(const e of t)if("featuresetId"in e.target){const{featuresetId:t,importId:i}=e.target,s=this.getFragmentStyle(i);if(!s||!s._featuresetSelectors)continue;const r=s._featuresetSelectors[t];if(!r){this.fire(new P(new Error(`The featureset '${t}' does not exist in the map's style and cannot be queried for features.`)));continue}for(const t of r){const i=s.getOwnLayer(t.layerId);i&&!Fd.has(i.type)&&o(i,s.getOwnLayerSourceCache(i),e,t)}}else if("layerId"in e.target){const{layerId:t}=e.target,i=this.getLayer(t);if(!i||Fd.has(i.type))continue;o(i,this.getLayerSourceCache(i),e)}const r=this._queryRenderedFeatures(e,s,i);return this._flattenAndSortRenderedFeatures(r)}_queryRenderedFeatures(e,t,i){const s=[],o=!!this.map._showQueryGeometry,r=zl.createFromScreenPoints(e,i);for(const e in t){const n=sc(r,t[e],this._availableImages,i,o,this.getActualScope());Object.keys(n).length&&s.push(n)}if(this.placement)for(const e in t){if(t[e].sourceCache._renderSourceType!==Ot.Symbol)continue;const i=oc(r.screenGeometry,t[e],this._availableImages,this.placement.collisionIndex,this.placement.retainedQueryData,this.map.getWorldview());Object.keys(i).length&&s.push(i)}return s}querySourceFeatures(e,t){const i=t&&t.filter;i&&this._validate(Ga,"querySourceFeatures.filter",i,null,t);let s=[];const o=this.getOwnSourceCaches(e);for(const e of o)s=s.concat(rc(e,t));return s}getFlatLight(){return this.light.getLight()}setFlatLight(e,t,i={}){this._checkLoaded();const s=this.light.getLight();let o=!1;for(const t in e)if(!rs(e[t],s[t])){o=!0;break}if(!o)return;const r=this._getTransitionParameters();this.light.setLight(e,t,i),this.light.updateTransitions(r)}hasTerrain(){return!!this.terrain&&this.terrain.drapeRenderMode===Ja.elevated}getTerrain(){return this.hasTerrain()?this.terrain.get():null}_startLiteLoad(){if(void 0!==this._drapingLoaded)return;this._drapingLoaded=!1;const e=!!Al.loaded;(null!==Ll||(Ll=import("./lite.main.js").then(({Lite:e})=>{Object.assign(Al,e)}).catch(()=>{Ll=null,_("Could not load Lite module.")})),Ll).then(()=>{this._drapingLoaded=!0,this.map._removed||0===this.dispatcher.actors.length||(e?this.map.triggerRepaint():(this.applyProjectionUpdate(),this.map._update(!1)))})}_getRasterMaskUser(e,t){for(const i of this._order){const s=this._layers[i];if("raster"!==s.type||!s.getPaintProperty("raster-mask"))continue;const o=s.getPaintProperty("raster-mask-import");if("import"===t?o===e:!o&&s.getPaintProperty("raster-mask")===e)return i}}_startRasterArrayLoad(){void 0===this._rasterArrayLoaded&&(this._rasterArrayLoaded=!1,Ol().then(()=>{this._rasterArrayLoaded=!0,this.map._removed||this.map.triggerRepaint()}))}setTerrainForDraping(){this._startLiteLoad(),this.setTerrain({source:"",exaggeration:0},Ja.deferred)}checkCanvasFingerprintNoise(){void 0===this.disableElevatedTerrain&&(this.disableElevatedTerrain=T.hasCanvasFingerprintNoise(),this.disableElevatedTerrain&&_("Terrain and hillshade are disabled because of Canvas2D limitations when fingerprinting protection is enabled (e.g. in private browsing mode)."))}setTerrain(e,t=Ja.elevated){if(this._checkLoaded(),!e)return this.terrainSetForDrapingOnly()||(delete this.terrain,this.map.transform.projection.requiresDraping&&this.setTerrainForDraping()),t===Ja.deferred&&delete this.terrain,null===e?this.stylesheet.terrain=null:delete this.stylesheet.terrain,this._force3DLayerUpdate(),void(this._markersNeedUpdate=!0);this.checkCanvasFingerprintNoise();let i=e;const s=!("source"in e)||null==e.source;if(t===Ja.elevated){if(this._startLiteLoad(),this.disableElevatedTerrain)return;if("source"in i&&"object"==typeof i.source){const e="terrain-dem-src";this.addSource(e,i.source),i=Ji(i),i=Object.assign(i,{source:e})}const e={...i},t={};if(this.terrain&&s){e.source=this.terrain.get().source;const i=this.terrain?this.getFragmentStyle(this.terrain.scope):null;i&&(t.style=i.serialize())}if(this._validate(Ba,"terrain",e,t))return}if(!this.terrain||this.terrain.scope!==this.scope&&!s||this.terrain&&t!==this.terrain.drapeRenderMode){if(!i)return;this._createTerrain(i,t),this.fire(new M("data",{dataType:"style"}))}else{const t=this.terrain,s=t.get();for(const e of Object.keys(y.terrain))!Object.hasOwn(i,e)&&y.terrain[e].default&&(i[e]=y.terrain[e].default);for(const i in e)if(!rs(e[i],s[i])){t.set(e,this.options),this.stylesheet.terrain=e;const i=this._getTransitionParameters({duration:0});t.updateTransitions(i),this.fire(new M("data",{dataType:"style"}));break}}this.mergeTerrain(),this.updateDrapeFirstLayers(),this._markersNeedUpdate=!0}_createFog(e){const t=this.fog=new il(e,this.map.transform,this.scope,this.options);this.stylesheet.fog=t.get();const i=this._getTransitionParameters({duration:0});t.updateTransitions(i)}_createSnow(e){const t=this.snow=new rl(e,this.map.transform,this.scope,this.options);this.stylesheet.snow=t.get();const i=this._getTransitionParameters({duration:0});t.updateTransitions(i)}_createRain(e){const t=this.rain=new nl(e,this.map.transform,this.scope,this.options);this.stylesheet.rain=t.get();const i=this._getTransitionParameters({duration:0});t.updateTransitions(i)}_updateMarkersOpacity(){0!==this.map._markers.length&&this.map._requestDomTask(()=>{for(const e of this.map._markers)e._evaluateOpacity()})}getFog(){return this.fog?this.fog.get():null}setFog(e){if(this._checkLoaded(),e)if(this.fog){const t=this.fog;if(!rs(t.get(),e)){t.set(e,this.options),this.stylesheet.fog=t.get();const i=this._getTransitionParameters({duration:0});t.updateTransitions(i)}}else this._createFog(e);else delete this.fog,delete this.stylesheet.fog;this._markersNeedUpdate=!0,this._programPrecompiler&&this._programPrecompiler.reset()}getSnow(){return this.snow?this.snow.get():null}setSnow(e){if(this._checkLoaded(),!e)return delete this.snow,void delete this.stylesheet.snow;if(this.snow){const t=this.snow;if(!rs(t.get(),e)){t.set(e,this.options),this.stylesheet.snow=t.get();const i=this._getTransitionParameters({duration:0});t.updateTransitions(i)}}else this._createSnow(e);this._markersNeedUpdate=!0}getRain(){return this.rain?this.rain.get():null}setRain(e){if(this._checkLoaded(),!e)return delete this.rain,void delete this.stylesheet.rain;if(this.rain){const t=this.rain;if(!rs(t.get(),e)){t.set(e,this.options),this.stylesheet.rain=t.get();const i=this._getTransitionParameters({duration:0});t.updateTransitions(i)}}else this._createRain(e);this._markersNeedUpdate=!0}_reloadColorTheme(){const e=()=>{for(const e in this._layers)this._layers[e].lut=this._styleColorTheme.lut;for(const e in this._sourceCaches)this._sourceCaches[e].clearTiles()},t=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(!t)return this._styleColorTheme.lut=null,void e();const i=this._evaluateColorThemeData(t);this._loadColorTheme(i).then(()=>{this.fire(new M("colorthemeset")),e()}).catch(e=>{_(`Couldn't set color theme: ${e}`)})}setColorTheme(e){this._checkLoaded(),this._styleColorTheme.colorThemeOverride&&_("Note: setColorTheme is called on a style with a color-theme override, the passed color-theme won't be visible."),this._styleColorTheme.colorTheme=e,this._reloadColorTheme()}setImportColorTheme(e,t){const i=this.getFragmentStyle(e);i&&(i._styleColorTheme.colorThemeOverride=t,i._reloadColorTheme())}_getTransitionParameters(e){return{now:T.now(),transition:Object.assign(this.transition,e)}}updateDrapeFirstLayers(){if(!this.terrain)return;const e=[],t=[];for(const i of this._mergedOrder)this.isLayerDraped(this._mergedLayers[i])?e.push(i):t.push(i);this._drapedFirstOrder=[],this._drapedFirstOrder.push(...e),this._drapedFirstOrder.push(...t)}_createTerrain(e,t){const i=this.terrain=new Qa(e,t,this.scope,this.options,this.map.getWorldview());t===Ja.elevated&&(this.stylesheet.terrain=e),this.mergeTerrain(),this.updateDrapeFirstLayers(),this._force3DLayerUpdate();const s=this._getTransitionParameters({duration:0});i.updateTransitions(s);const o=new X(this.z||0,{...s,worldview:this.map.getWorldview()});i.recalculate(o)}_force3DLayerUpdate(){for(const e in this._layers){const t=this._layers[e];"fill-extrusion"===t.type&&this._updateLayer(t)}}_forceSymbolLayerUpdate(){for(const e in this._layers){const t=this._layers[e];"symbol"===t.type&&this._updateLayer(t)}}_validate(e,t,i,s,o={}){if(o&&!1===o.validate)return!1;const r={...this.serialize()};return Md(this,e.call(Oa,{key:t,style:r,value:i,styleSpec:y,...s}))}_remove(){this._programPrecompiler&&(this._programPrecompiler.reset(),this._programPrecompiler=null),this._request&&(this._request.cancel(),this._request=null),this._spriteRequest&&(this._spriteRequest.abort(),this._spriteRequest=null);for(const e in this._mergedLayers)this._mergedLayers[e].setEventedParent(null);for(const e in this._mergedSourceCaches){const t=this._mergedSourceCaches[e];t.clearTiles(),t.setEventedParent(null);const i=t.getSource();i&&i.onRemove&&i.onRemove(this.map)}this.imageManager.removeScope(this.scope),this.isRootStyle()?this.imageManager.imageAtlasCache.clear():this.imageManager.imageAtlasCache.removeScope(this.scope),this.setEventedParent(null),delete this.fog,delete this.snow,delete this.rain,delete this.terrain,delete this.ambientLight,delete this.directionalLight,this.indoorManager&&this.indoorManager.destroy(),this.isRootStyle()&&(this.imageManager.setEventedParent(null),this.modelManager.setEventedParent(null),this.modelManager.destroy(),this.dispatcher.remove())}clearSource(e){const t=this.getSourceCaches(e);for(const e of t)e.clearTiles()}clearSources(){for(const e in this._mergedSourceCaches)this._mergedSourceCaches[e].clearTiles()}clearLayers(){for(const e in this._mergedLayers){const t=this._mergedLayers[e];t._clear&&t._clear()}}reloadSource(e){const t=this.getSourceCaches(e);for(const e of t)e.resume(),e.reload()}reloadSources(){for(const e of this.getSources())e.reload&&e.reload()}reloadModels(){this.modelManager.reloadModels(""),this.forEachFragmentStyle(e=>{e.modelManager.reloadModels(e.scope)})}updateSources(e){let t;this.directionalLight&&(t=jh(this.directionalLight));const i=new Set,s=new Set,o=new Set;for(const e in this._mergedLayers){const t=this._mergedLayers[e];"building"===t.type?i.add(t.source):"raster"===t.type&&t.paint&&"ground"===t.paint.get("raster-elevation-reference")&&o.add(t.source),t.hasElevation()&&!s.has(t.source)&&s.add(t.source)}this.updateFrcCoverageFadeRange();for(const r in this._mergedSourceCaches){const n=this._mergedSourceCaches[r],a=s.has(n._source.id);n._isRasterElevatedOverTerrain=o.has(n._source.id),i.has(n._source.id)&&(n._source.reparseOverscaled=!1),n.update(e,void 0,void 0,t,a)}this.updateFrcCoverage(),this.updateElevationCoverage()}_reloadSources(){for(const e in this._sourceCaches){const t=this._sourceCaches[e];t.resume(),t.reload()}}updateFrcCoverageFadeRange(){this.map.painter&&Il.updateFrcCoverageFadeRange&&Il.updateFrcCoverageFadeRange(this,this.map.painter)}updateFrcCoverage(){this._hdCoverage&&Il.updateFrcCoverage&&Il.updateFrcCoverage(this,this._hdCoverage)}updateElevationCoverage(){this.isRootStyle()&&Il.setupAndUpdateElevationCoverage&&Il.setupAndUpdateElevationCoverage(this)}_handleLayerOrderChange(){this._requestFullLabelPlacement(),this.fire(new M("neworder"))}_requestFullLabelPlacement(){this.pauseablePlacement||(this.pauseablePlacement=new Rh),this.pauseablePlacement.requestFullPlacement()}_setLabelPlacementStale(){this.placement&&this.placement.setStale()}_updatePlacement(e,t,i,s,o,r){this.pauseablePlacement||(this.pauseablePlacement=new Rh);let n=!1,a=!1;const l={},c={},h="global"===r,d=h?[]:this._mergedOrder;let u=!1;h&&(u=this._driveGlobalPlacement(e,o,i,t));for(const t of d){const i=this._mergedLayers[t];if("symbol"!==i.type)continue;const s=C(i.source,i.scope);let o=l[s];if(!o){const e=this.getLayerSourceCache(i);if(!e)continue;const t=e.getRenderableIds(!0).map(t=>e.getTileByID(t));c[s]=t.slice(),o=l[s]=t.sort((e,t)=>t.tileID.overscaledZ-e.tileID.overscaledZ||(e.tileID.isLessThan(t.tileID)?-1:1))}const r=this.crossTileSymbolIndex.addLayer(i,o,e.center.lng,e.projection);n=n||r}this.crossTileSymbolIndex.pruneUnusedLayers(d);const _=Boolean(this.placement&&!e.equals(this.placement.transform)),p=Boolean(this.placement&&(0!==this.placement.lastReplacementSourceUpdateTime&&!o||this.placement.lastReplacementSourceUpdateTime!==o.updateTime)),f=_||p||n,m=(f||this.pauseablePlacement.isStale())&&0===i,g=this.pauseablePlacement.isDone()&&!this.placement.stillRecent(T.now(),e.zoom)&&0!==i;if((this.pauseablePlacement.isFullPlacementRequested()||!this.pauseablePlacement.placement||m||g)&&(this.pauseablePlacement=this.pauseablePlacement.startNewPlacement(e,d,t,i,s,this.placement,this.fog&&e.projection.supportsFog?this.fog.state:null,this._buildingIndex),this.map.painter)){const t=this.map.painter.maxFrontCutoffRawStart;if(t>0){const i=180*e.pitch/Math.PI;if(i>=15){const e=Math.min(1,Math.max(0,(i-15)/5)),s=e*e*(3-2*e);this.pauseablePlacement.placement.frontCutoffStart=-.5*(1-s)+t*s}}}if(this.pauseablePlacement.isDone()?f&&0!==i&&this.pauseablePlacement.setStale():(this.pauseablePlacement.continuePlacement(d,this._mergedLayers,l,c,this.map.painter.scaleFactor),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(T.now()),a=!0),n&&this.pauseablePlacement.setStale()),a||n){this._buildingIndex.onNewFrame(e.zoom);for(let e=0;e<d.length;e++){const i=this._mergedLayers[d[e]];if("symbol"!==i.type)continue;if("none"===i.visibility)continue;const s=this.isLayerClipped(i);this.placement.updateLayerOpacities(i,l[C(i.source,i.scope)],e,s?o:null,t,this.map.painter.scaleFactor)}}return!this.pauseablePlacement.isDone()||this.placement.isStale()||this.placement.hasTransitions(T.now())||u}_driveGlobalPlacement(e,t,i,s){if(0===e.width||0===e.height)return!1;this.globalPlacement||(this.globalPlacement=new Vh);const o=this.globalPlacement;o.startPlacement(T.now(),e.width,e.height,s),this._buildingIndex.onNewFrame(e.zoom);const r=this.fog&&e.projection.supportsFog?this.fog.state:null;if(this._groupOrdersVersion!==this._mergedOrderVersion||!this._groupOrders){const e=new Map;for(let t=0;t<this._mergedOrder.length;t++){const i=this._mergedLayers[this._mergedOrder[t]];"placement-group"===i.type&&e.set(i.fqid,cs(t))}this._groupOrders=e,this._groupOrdersVersion=this._mergedOrderVersion}const n=this._groupOrders,a=[Ae(e.center.lng),Pe(e.center.lat)],l={globalPlacement:o,transform:e,buildingIndex:this._buildingIndex,fogState:r,groupOrders:n,replacementSource:t,mercatorCenter:a,fadeDuration:i},c={};let h=!1;for(let e=0;e<this._mergedOrder.length;e++){const t=this._mergedLayers[this._mergedOrder[e]];if("symbol"!==t.type)continue;const i=this.getLayerSourceCache(t);if(!i)continue;const s=C(t.source,t.scope);let o=c[s];o||(o=c[s]=i.getRenderableIds(!0).map(e=>i.getTileByID(e)));const r=this.isLayerClipped(t);t.placeSymbols(l,o,e,i,r);for(const e of o){const i=e.getBucket(t);i&&t.fqid===i.layerIds[0]&&i.hasActiveFade()&&(h=!0)}}return o.finishPlacementRun(i),h}_releaseSymbolFadeTiles(){for(const e in this._mergedSourceCaches)this._mergedSourceCaches[e].releaseSymbolFadeTiles()}addImport(e,t){if(this._checkLoaded(),new Set(["__proto__","constructor","prototype"]).has(e.id))return void this.fire(new P(new Error(`Import id can't be "${e.id}".`)));const i=this.stylesheet.imports=this.stylesheet.imports||[];if(-1!==i.findIndex(({id:t})=>t===e.id))return void this.fire(new P(new Error(`Import with id '${e.id}' already exists in the map's style.`)));if(!t)return i.push(e),this._loadImports([e],!0);const s=i.findIndex(({id:e})=>e===t);return-1===s&&this.fire(new P(new Error(`Import with id "${t}" does not exist on this map.`))),this.stylesheet.imports=i.slice(0,s).concat(e).concat(i.slice(s)),this._loadImports([e],!0,t)}updateImport(e,t){this._checkLoaded();const i=this.stylesheet.imports||[],s=this.getImportIndex(e);return-1===s?this:"string"==typeof t?(this.setImportUrl(e,t),this):(t.url&&t.url!==i[s].url&&this.setImportUrl(e,t.url),rs(t.config,i[s].config)||this.setImportConfig(e,t.config,t.data.schema),rs(t.data,i[s].data)||this.setImportData(e,t.data),this)}moveImport(e,t){this._checkLoaded();let i=this.stylesheet.imports||[];const s=this.getImportIndex(e);if(-1===s)return this;const o=this.getImportIndex(t);if(-1===o)return this;const r=i[s],n=this.fragments[s];return i=i.filter(({id:t})=>t!==e),this.fragments=this.fragments.filter(({id:t})=>t!==e),this.stylesheet.imports=i.slice(0,o).concat(r).concat(i.slice(o)),this.fragments=this.fragments.slice(0,o).concat(n).concat(this.fragments.slice(o)),this.mergeLayers(),this}setImportUrl(e,t){this._checkLoaded();const i=this.stylesheet.imports||[],s=this.getImportIndex(e);if(-1===s)return this;i[s].url=t;const o=this.fragments[s];return o.style=this._createFragmentStyle(i[s]),o.style.on("style.import.load",()=>this.mergeAll()),o.style.loadURL(t),this}setImportData(e,t){this._checkLoaded();const i=this.getImportIndex(e),s=this.stylesheet.imports||[];return-1===i?this:t?(this.fragments[i].style.setState(t),this._reloadImports(),this):(delete s[i].data,this.setImportUrl(e,s[i].url))}setImportConfig(e,t,i){this._checkLoaded();const s=this.getImportIndex(e),o=this.stylesheet.imports||[];if(-1===s)return this;t?o[s].config=t:delete o[s].config;const r=this.fragments[s];i&&r.style.stylesheet&&(r.style.stylesheet.schema=i);const n=r.style.stylesheet&&r.style.stylesheet.schema;return r.config=t,r.style.updateConfig(t,n),this.updateConfigDependencies(),this}removeImport(e){this._checkLoaded();const t=this.stylesheet.imports||[],i=this.getImportIndex(e);-1!==i&&(t.splice(i,1),this.fragments[i].style._remove(),this.fragments.splice(i,1),this._reloadImports())}getImportIndex(e){const t=(this.stylesheet.imports||[]).findIndex(t=>t.id===e);return-1===t&&this.fire(new P(new Error(`Import '${e}' does not exist in the map's style and cannot be updated.`))),t}getLayer(e){return this._mergedLayers[e]}getSources(){const e=[];for(const t in this._mergedOtherSourceCaches){const i=this._mergedOtherSourceCaches[t];i&&e.push(i.getSource())}return e}getSource(e,t){const i=this.getSourceCache(e,t);return i&&i.getSource()}getLayerSource(e){const t=this.getLayerSourceCache(e);return t&&t.getSource()}getSourceCache(e,t){const i=C(e,t);return this._mergedOtherSourceCaches[i]}getLayerSourceCache(e){const t=e.sourceFqid;return"symbol"===e.type?this._mergedSymbolSourceCaches[t]:"fill-extrusion"===e.type?this._mergedFillExtrusionSourceCaches[t]||this._mergedOtherSourceCaches[t]:"fill"===e.type&&e.sourceLayer===hs&&this._mergedHdRoadCoverageSourceCaches[t]?this._mergedHdRoadCoverageSourceCaches[t]:this._mergedOtherSourceCaches[t]}getSourceCaches(e){return null==e?Object.values(this._mergedSourceCaches):[this._mergedOtherSourceCaches[e],this._mergedSymbolSourceCaches[e],this._mergedFillExtrusionSourceCaches[e],this._mergedHdRoadCoverageSourceCaches[e]].filter(Boolean)}updateSourceCaches(){const e=this._changes.getUpdatedSourceCaches();for(const t in e){const i=e[t];"reload"===i?this.reloadSource(t):"clear"===i&&this.clearSource(t)}}updateLayers(e){const t=this._changes.getUpdatedPaintProperties();for(const i of t){const t=this.getLayer(i);t&&t.updateTransitions(e)}}getGlyphsUrl(){return this.stylesheet.glyphs}setGlyphsUrl(e){if(this.stylesheet.glyphs=e,e!==this.glyphManager.url){this.glyphManager.setURL(e);for(const e in this._mergedSymbolSourceCaches)this._mergedSymbolSourceCaches[e].reload()}}getOwnSourceCache(e){return this._otherSourceCaches[e]}getOwnLayerSourceCache(e){return"symbol"===e.type?this._symbolSourceCaches[e.source]:"fill-extrusion"===e.type&&this._fillExtrusionSourceCaches[e.source]||this._otherSourceCaches[e.source]}getOwnSourceCaches(e){return[this._otherSourceCaches[e],this._symbolSourceCaches[e],this._fillExtrusionSourceCaches[e],this._hdCoverage&&this._hdCoverage.coverageSourceCaches[e]].filter(Boolean)}_updateHdCoverageSourceCache(e){return Il.HdCoverageState&&Il.updateHdCoverageSourceCache?(this._hdCoverage||(this._hdCoverage=new Il.HdCoverageState),Il.updateHdCoverageSourceCache(this,this._hdCoverage,e),!1):"fill"===e.type&&e.sourceLayer===hs}_isSourceCacheLoaded(e){const t=this.getOwnSourceCaches(e);return 0===t.length?(this.fire(new P(new Error(`There is no source with ID '${e}'`))),!1):t.every(e=>e.loaded())}has3DLayers(){return this._has3DLayers}hasSymbolLayers(){return this._hasSymbolLayers}hasCircleLayers(){return this._hasCircleLayers}isLayerClipped(e,t){if(!this._clipLayerPresent&&"fill-extrusion"!==e.type&&"building"!==e.type)return!1;const i="fill-extrusion"===e.type&&("building"===e.sourceLayer||"procedural_buildings"===e.sourceLayer),s="building"===e.type;if(e.is3D(!!this.terrain)){if(i||s||t&&"batched-model"===t.type)return!0;if("model"===e.type)return!0}else if("symbol"===e.type)return!0;return!1}_clearWorkerCaches(){this.dispatcher.broadcast("clearCaches")}getBOMObject(){}destroy(){this._clearWorkerCaches(),this.imageManager.imageAtlasCache.clear(),this.fragments.forEach(e=>{e.style._remove()}),this.terrainSetForDrapingOnly()&&(delete this.terrain,delete this.stylesheet.terrain)}async getImages(e,t){const i=new Promise((e,i)=>{this.imageManager.getImages(t.icons.concat(t.patterns),t.scope,(t,s)=>{t?i(t):e(s)})});this._updateTilesForChangedImages();const s=t.icons.map(e=>g.toString(e)),o=t.patterns.map(e=>g.toString(e)),r=e=>{e&&(e.setDependencies(t.tileID.key,"icons",s),e.setDependencies(t.tileID.key,"patterns",o))},n=C(t.source,t.scope);return r(this._mergedOtherSourceCaches[n]),r(this._mergedSymbolSourceCaches[n]),(t.icons.some(e=>e.iconsetId)||t.patterns.some(e=>e.iconsetId))&&this.fire(new M("data",{dataType:"style"})),i}async rasterizeImages(e,t){return new Promise((e,i)=>{this.imageManager.rasterizeImages(t,(t,s)=>{t?i(t):e(s)})})}async checkAtlasCache(e,t){const i=this.imageManager.imageAtlasCache.findCachedAtlas(t.descriptor);return i&&i.contentDescriptor?{iconPositions:i.iconPositions,patternPositions:i.patternPositions,sourceHash:i.contentDescriptor.hash}:null}async getGlyphs(e,t){return new Promise((e,i)=>{this.glyphManager.getGlyphs(t.stacks,(t,s)=>{t?i(t):e(s)})})}}const Ud="\n#define EPSILON 0.0000001\n#define PI 3.141592653589793\n#define storage_depth_to_native_ndc_z(z01) ((z01)*2.0-1.0)\n#define native_ndc_z_to_storage_depth(ndc_z) ((ndc_z)*0.5+0.5)\n#define native_clip_z_to_cutoff_depth(clip_z,clip_w) (clip_z)\n#define native_depth_epsilon(eps) (eps)\n#define depth_range_to_native_ndc_z(z01,unpack) ((z01)*(unpack).x+(unpack).y)\n#define bottom_left_to_native_uv(uv) (uv)\n#define native_cubemap_direction(dir) vec3((dir).x,-(dir).y,(dir).z)\n#define ndc_xy_to_framebuffer_uv(ndc_xy) ((ndc_xy)*0.5+0.5)\n#define ndc_xy_to_depth_texture_uv(ndc_xy) bottom_left_to_native_uv((ndc_xy)*0.5+0.5)\n#ifdef RENDER_CUTOFF\nfloat cutoff_opacity(vec4 cutoff_params,float depth) {float near=cutoff_params.x;float far=cutoff_params.y;float cutoffStart=cutoff_params.z;float cutoffEnd=cutoff_params.w;float linearDepth=(depth-near)/(far-near);return clamp((linearDepth-cutoffStart)/(cutoffEnd-cutoffStart),0.0,1.0);}\n#endif",Vd="\n#define fragcoord_to_bottom_left_uv(frag,size) ((frag)/(size))\n#define fragcoord_to_ndc_y(fragY,invY) ((fragY)*(invY)*2.0-1.0)\n#define native_window_space_normal(fdx,fdy) (normalize(cross((fdx),(fdy)))*-1.0)\n#define fragcoord_to_framebuffer_uv(frag,inv) ((frag)*(inv))\n#define native_window_space_tangent(axis) (axis)\n#define native_tbn_view_dir(position) (normalize(-(position)))\n#ifdef DUAL_SOURCE_BLENDING\nlayout(location=0,index=0) out vec4 glFragColor;layout(location=0,index=1) out vec4 glFragColorSrc1;\n#elif defined(FLOAT_RENDER_TARGET)\nlayout(location=0) out highp vec4 glFragColor;\n#else\nlayout(location=0) out vec4 glFragColor;\n#endif\n#ifdef USE_MRT1\nlayout(location=1) out vec4 out_Target1;\n#endif\nhighp float unpack_depth(highp vec4 rgba_depth)\n{const highp vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return storage_depth_to_native_ndc_z(dot(rgba_depth,bit_shift));}highp vec4 pack_depth(highp float ndc_z) {highp float depth=native_ndc_z_to_storage_depth(ndc_z);const highp vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const highp vec4 bit_mask =vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);highp vec4 res=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;}const float DITHER_THRESHOLDS[16]=float[16](\n1.0/17.0, 9.0/17.0, 3.0/17.0,11.0/17.0,13.0/17.0, 5.0/17.0,15.0/17.0, 7.0/17.0,4.0/17.0,12.0/17.0, 2.0/17.0,10.0/17.0,16.0/17.0, 8.0/17.0,14.0/17.0, 6.0/17.0\n);int viewport_dither_index(vec2 fragCoordXY) {return (int(fragCoordXY.x) % 4)*4+(int(fragCoordXY.y) % 4);}\n#ifdef DEBUG_WIREFRAME\n#define HANDLE_WIREFRAME_DEBUG \\\nglFragColor=vec4(0.7,0.0,0.0,0.7); \\\ngl_FragDepth=gl_FragCoord.z-0.0001;\n#else\n#define HANDLE_WIREFRAME_DEBUG\n#endif\n#ifdef RENDER_CUTOFF\nuniform highp vec4 u_cutoff_params;in float v_cutoff_opacity;\n#endif\nvec4 textureLodCustom(sampler2D image,highp vec2 pos,highp vec2 lod_coord) {highp vec2 size=vec2(textureSize(image,0));highp vec2 dx=dFdx(lod_coord.xy*size);highp vec2 dy=dFdy(lod_coord.xy*size);highp float delta_max_sqr=max(dot(dx,dx),dot(dy,dy));highp float lod=0.5*log2(delta_max_sqr);return textureLod(image,pos,lod);}vec4 premultiplyColor(vec3 nonPremultipliedColor,float a) {return vec4(nonPremultipliedColor*a,a);}vec3 unpremultiplyColor(vec4 premultipliedColor) {if (premultipliedColor.a > 0.0) {return premultipliedColor.rgb/premultipliedColor.a;}return premultipliedColor.rgb;}vec3 applyLUT(highp sampler3D lut,vec3 col) {vec3 size=vec3(textureSize(lut,0));vec3 uvw=(col.rbg*float(size-1.0)+0.5)/size;return texture(lut,uvw).rgb;}vec4 applyLUT(highp sampler3D lut,vec4 premultipliedColor) {return premultiplyColor(applyLUT(lut,unpremultiplyColor(premultipliedColor)),premultipliedColor.a);}void storeEmissiveColor(vec4 color,float emissiveStrength) {\n#ifdef DUAL_SOURCE_BLENDING\nglFragColorSrc1=vec4(vec3(0.0),emissiveStrength);\n#else\n#ifdef USE_MRT1\n#ifdef USE_MRT1_RGBA\nout_Target1=vec4(color.rgb*emissiveStrength,color.a);\n#else\nout_Target1=vec4(emissiveStrength*color.a,0.0,0.0,glFragColor.a);\n#endif\n#endif\n#endif\n}",jd="\n#define EXTENT 8192.0\n#define RAD_TO_DEG 180.0/PI\n#define DEG_TO_RAD PI/180.0\n#define GLOBE_RADIUS EXTENT/PI/2.0\nfloat wrap(float n,float min,float max) {float d=max-min;float w=mod(mod(n-min,d)+d,d)+min;return (w==min) ? max : w;}\n#ifdef PROJECTION_GLOBE_VIEW\nvec3 mercator_tile_position(mat4 matrix,vec2 tile_anchor,vec3 tile_id,vec2 mercator_center) {\n#ifndef PROJECTED_POS_ON_VIEWPORT\nfloat tiles=tile_id.z;vec2 mercator=(tile_anchor/EXTENT+tile_id.xy)/tiles;mercator-=mercator_center;mercator.x=wrap(mercator.x,-0.5,0.5);vec4 mercator_tile=vec4(mercator.xy*EXTENT,EXTENT/(2.0*PI),1.0);mercator_tile=matrix*mercator_tile;return mercator_tile.xyz;\n#else\nreturn vec3(0.0);\n#endif\n}vec3 mix_globe_mercator(vec3 globe,vec3 mercator,float t) {return mix(globe,mercator,t);}mat3 globe_mercator_surface_vectors(vec3 pos_normal,vec3 up_dir,float zoom_transition) {vec3 normal=zoom_transition==0.0 ? pos_normal : normalize(mix(pos_normal,up_dir,zoom_transition));vec3 xAxis=normalize(vec3(normal.z,0.0,-normal.x));vec3 yAxis=normalize(cross(normal,xAxis));return mat3(xAxis,yAxis,normal);}\n#endif\nvec2 unpack_float(const float packedValue) {int packedIntValue=int(packedValue);int v0=packedIntValue/256;return vec2(v0,packedIntValue-v0*256);}vec4 decode_color(const vec2 encodedColor) {return vec4(\nunpack_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 vec2 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 (units_to_pixels*pos+offset)/pattern_size;}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) {return get_pattern_pos(pixel_coord_upper,pixel_coord_lower,pattern_size,vec2(tile_units_to_pixels),pos);}float mercatorXfromLng(float lng) {return (180.0+lng)/360.0;}float mercatorYfromLat(float lat) {return (180.0-(RAD_TO_DEG*log(tan(PI/4.0+lat/2.0*DEG_TO_RAD))))/360.0;}vec3 latLngToECEF(vec2 latLng) {latLng=DEG_TO_RAD*latLng;float cosLat=cos(latLng[0]);float sinLat=sin(latLng[0]);float cosLng=cos(latLng[1]);float sinLng=sin(latLng[1]);float sx=cosLat*sinLng*GLOBE_RADIUS;float sy=-sinLat*GLOBE_RADIUS;float sz=cosLat*cosLng*GLOBE_RADIUS;return vec3(sx,sy,sz);}\n#ifdef RENDER_CUTOFF\nuniform vec4 u_cutoff_params;out float v_cutoff_opacity;\n#endif\nconst vec4 AWAY=vec4(-1000.0,-1000.0,-1000.0,1);const float skirtOffset=24575.0;vec3 decomposeToPosAndSkirt(ivec2 posWithComposedSkirt)\n{float skirt=float(float(posWithComposedSkirt.x) >=skirtOffset);vec2 pos=vec2(posWithComposedSkirt)-vec2(skirt*skirtOffset,0.0);return vec3(pos,skirt);}\n#define GET_ATTRIBUTE_float(attrib,matInfo,attrib_id) attrib\n#define GET_ATTRIBUTE_vec4(attrib,matInfo,attrib_id) attrib\n#define GET_ATTRIBUTE_vec2(attrib,matInfo,attrib_id) attrib\n#define DECLARE_MATERIAL_TABLE_INFO\n",Gd="in highp vec3 a_pos_3f;uniform lowp mat4 u_matrix;out highp vec3 v_uv;void main() {const mat3 half_neg_pi_around_x=mat3(1.0,0.0, 0.0,0.0,0.0,-1.0,0.0,1.0, 0.0);v_uv=half_neg_pi_around_x*a_pos_3f;vec4 pos=u_matrix*vec4(a_pos_3f,1.0);gl_Position=pos.xyww;}",qd="\n#define ELEVATION_SCALE 7.0\n#define ELEVATION_OFFSET 450.0\n#ifdef PROJECTION_GLOBE_VIEW\nuniform vec3 u_tile_tl_up;uniform vec3 u_tile_tr_up;uniform vec3 u_tile_br_up;uniform vec3 u_tile_bl_up;uniform float u_tile_up_scale;\n#endif\nvec3 elevationVector(vec2 pos) {\n#ifdef PROJECTION_GLOBE_VIEW\nvec2 uv=pos/EXTENT;vec3 up=normalize(mix(\nmix(u_tile_tl_up,u_tile_tr_up,uv.xxx),mix(u_tile_bl_up,u_tile_br_up,uv.xxx),uv.yyy));return up*u_tile_up_scale;\n#else\nreturn vec3(0,0,1);\n#endif\n}\n#ifdef TERRAIN\nuniform highp sampler2D u_dem;\n#ifdef TERRAIN_VERTEX_MORPHING\nuniform highp sampler2D u_dem_prev;\n#endif\nuniform vec2 u_dem_tl;uniform vec2 u_dem_tl_prev;uniform float u_dem_scale;uniform float u_dem_scale_prev;uniform float u_dem_size;uniform float u_dem_lerp;uniform float u_exaggeration;uniform float u_meter_to_dem;uniform mat4 u_label_plane_matrix_inv;vec4 tileUvToDemSample(vec2 uv,float dem_size,float dem_scale,vec2 dem_tl) {vec2 pos=dem_size*(uv*dem_scale+dem_tl)+1.0;vec2 f=fract(pos);return vec4((pos-f+0.5)/(dem_size+2.0),f);}float currentElevation(vec2 apos) {\n#ifdef TERRAIN_DEM_FLOAT_FORMAT\nvec2 pos=(u_dem_size*(apos/8192.0*u_dem_scale+u_dem_tl)+1.5)/(u_dem_size+2.0);return u_exaggeration*texture(u_dem,pos).r;\n#else\nfloat dd=1.0/(u_dem_size+2.0);vec4 r=tileUvToDemSample(apos/8192.0,u_dem_size,u_dem_scale,u_dem_tl);vec2 pos=r.xy;vec2 f=r.zw;float tl=texture(u_dem,pos).r;float tr=texture(u_dem,pos+vec2(dd,0)).r;float bl=texture(u_dem,pos+vec2(0,dd)).r;float br=texture(u_dem,pos+vec2(dd,dd)).r;return u_exaggeration*mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y);\n#endif\n}\n#ifdef TERRAIN_VERTEX_MORPHING\nfloat prevElevation(vec2 apos) {\n#ifdef TERRAIN_DEM_FLOAT_FORMAT\nvec2 pos=(u_dem_size*(apos/8192.0*u_dem_scale_prev+u_dem_tl_prev)+1.5)/(u_dem_size+2.0);return u_exaggeration*texture(u_dem_prev,pos).r;\n#else\nfloat dd=1.0/(u_dem_size+2.0);vec4 r=tileUvToDemSample(apos/8192.0,u_dem_size,u_dem_scale_prev,u_dem_tl_prev);vec2 pos=r.xy;vec2 f=r.zw;float tl=texture(u_dem_prev,pos).r;float tr=texture(u_dem_prev,pos+vec2(dd,0)).r;float bl=texture(u_dem_prev,pos+vec2(0,dd)).r;float br=texture(u_dem_prev,pos+vec2(dd,dd)).r;return u_exaggeration*mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y);\n#endif\n}\n#endif\nvec4 fourSample(vec2 pos,vec2 off) {float tl=texture(u_dem,pos).r;float tr=texture(u_dem,pos+vec2(off.x,0.0)).r;float bl=texture(u_dem,pos+vec2(0.0,off.y)).r;float br=texture(u_dem,pos+off).r;return vec4(tl,tr,bl,br);}float flatElevation(vec2 pack) {vec2 apos=floor(pack/8.0);vec2 span=10.0*(pack-apos*8.0);vec2 uvTex=(apos-vec2(1.0,1.0))/8190.0;float size=u_dem_size+2.0;float dd=1.0/size;vec2 pos=u_dem_size*(uvTex*u_dem_scale+u_dem_tl)+1.0;vec2 f=fract(pos);pos=(pos-f+0.5)*dd;vec4 h=fourSample(pos,vec2(dd));float z=mix(mix(h.x,h.y,f.x),mix(h.z,h.w,f.x),f.y);vec2 w=floor(0.5*(span*u_meter_to_dem-1.0));vec2 d=dd*w;h=fourSample(pos-d,2.0*d+vec2(dd));vec4 diff=abs(h.xzxy-h.ywzw);vec2 slope=min(vec2(0.25),u_meter_to_dem*0.5*(diff.xz+diff.yw)/(2.0*w+vec2(1.0)));vec2 fix=slope*span;float base=z+max(fix.x,fix.y);return u_exaggeration*base;}float elevationFromUint16(float word) {return u_exaggeration*(word/ELEVATION_SCALE-ELEVATION_OFFSET);}\n#endif\nfloat elevation(vec2 apos) {\n#ifdef TERRAIN\n#ifdef TERRAIN_VERTEX_MORPHING\nfloat nextElevation=currentElevation(apos);float prevElevation=prevElevation(apos);return mix(prevElevation,nextElevation,u_dem_lerp);\n#else\nreturn currentElevation(apos);\n#endif\n#else\nreturn 0.0;\n#endif\n}\n#ifdef DEPTH_OCCLUSION\nuniform highp sampler2D u_depth;uniform highp vec2 u_depth_size_inv;uniform highp vec2 u_depth_range_unpack;uniform highp float u_occluder_half_size;uniform highp float u_occlusion_depth_offset;\n#ifdef DEPTH_D24\nfloat unpack_depth(float depth) {return depth_range_to_native_ndc_z(depth,u_depth_range_unpack);}vec4 unpack_depth4(vec4 depth) {return depth_range_to_native_ndc_z(depth,u_depth_range_unpack);}\n#else\nhighp float unpack_depth_rgba(vec4 rgba_depth)\n{const highp vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return storage_depth_to_native_ndc_z(dot(rgba_depth,bit_shift));}\n#endif\nhighp vec2 occlusionDepthUv(highp vec2 ndc_xy) {return ndc_xy_to_depth_texture_uv(ndc_xy);}\n#define occlusion_depth_bias native_depth_epsilon(u_occlusion_depth_offset)\n#define occlusion_fade_slope(native_delta) (300.0*(native_delta)/native_depth_epsilon(1.0))\nbool isOccluded(vec4 frag) {vec3 coord=frag.xyz/frag.w;highp vec2 uv=occlusionDepthUv(coord.xy);\n#ifdef DEPTH_D24\nfloat depth=unpack_depth(texture(u_depth,uv).r);\n#else\nfloat depth=unpack_depth_rgba(texture(u_depth,uv));\n#endif\nreturn coord.z+occlusion_depth_bias > depth;}highp vec4 getCornerDepths(vec2 coord) {highp vec3 df=vec3(u_occluder_half_size*u_depth_size_inv,0.0);highp vec2 uv=occlusionDepthUv(coord);\n#ifdef DEPTH_D24\nhighp vec4 depth=vec4(\ntexture(u_depth,uv-df.xz).r,texture(u_depth,uv+df.xz).r,texture(u_depth,uv-df.zy).r,texture(u_depth,uv+df.zy).r\n);depth=unpack_depth4(depth);\n#else\nhighp vec4 depth=vec4(\nunpack_depth_rgba(texture(u_depth,uv-df.xz)),unpack_depth_rgba(texture(u_depth,uv+df.xz)),unpack_depth_rgba(texture(u_depth,uv-df.zy)),unpack_depth_rgba(texture(u_depth,uv+df.zy))\n);\n#endif\nreturn depth;}highp float occlusionFadeMultiSample(vec4 frag) {highp vec3 coord=frag.xyz/frag.w;highp vec2 uv=occlusionDepthUv(coord.xy);int NX=3;int NY=4;highp vec2 df=u_occluder_half_size*u_depth_size_inv;highp vec2 oneStep=2.0*u_occluder_half_size*u_depth_size_inv/vec2(NX-1,NY-1);highp float res=0.0;for (int y=0; y < NY;++y) {for (int x=0; x < NX;++x) {\n#ifdef DEPTH_D24\nhighp float depth=unpack_depth(texture(u_depth,uv-df+vec2(float(x)*oneStep.x,float(y)*oneStep.y)).r);\n#else\nhighp float depth=unpack_depth_rgba(texture(u_depth,uv-df+vec2(float(x)*oneStep.x,float(y)*oneStep.y)));\n#endif\nres+=1.0-clamp(occlusion_fade_slope(coord.z+occlusion_depth_bias-depth),0.0,1.0);}}res=clamp(2.0*res/float(NX*NY)-0.5,0.0,1.0);return res;}highp float occlusionFade(vec4 frag) {highp vec3 coord=frag.xyz/frag.w;highp vec4 depth=getCornerDepths(coord.xy);return dot(vec4(0.25),vec4(1.0)-clamp(occlusion_fade_slope(vec4(coord.z+occlusion_depth_bias)-depth),0.0,1.0));}\n#else\nbool isOccluded(vec4 frag) { return false; }highp float occlusionFade(vec4 frag) { return 1.0; }highp float occlusionFadeMultiSample(vec4 frag) { return 1.0; }\n#endif",Zd="#ifdef FOG\nuniform mediump vec4 u_fog_color;uniform mediump vec2 u_fog_range;uniform mediump float u_fog_horizon_blend;uniform mediump mat4 u_fog_matrix;out vec3 v_fog_pos;float fog_range(float depth) {return (depth-u_fog_range[0])/(u_fog_range[1]-u_fog_range[0]);}float fog_horizon_blending(vec3 camera_dir) {float t=max(0.0,camera_dir.z/u_fog_horizon_blend);return u_fog_color.a*exp(-3.0*t*t);}float fog_opacity(float t) {const float decay=6.0;float falloff=1.0-min(1.0,exp(-decay*t));falloff*=falloff*falloff;return u_fog_color.a*min(1.0,1.00747*falloff);}vec3 fog_position(vec3 pos) {return (u_fog_matrix*vec4(pos,1.0)).xyz;}vec3 fog_position(vec2 pos) {return fog_position(vec3(pos,0.0));}float fog(vec3 pos) {float depth=length(pos);float opacity=fog_opacity(fog_range(depth));return opacity*fog_horizon_blending(pos/depth);}\n#endif",Wd="#ifdef FOG\nuniform mediump vec4 u_fog_color;uniform mediump vec2 u_fog_range;uniform mediump float u_fog_horizon_blend;uniform mediump vec2 u_fog_vertical_limit;uniform mediump float u_fog_temporal_offset;in vec3 v_fog_pos;uniform highp vec3 u_frustum_tl;uniform highp vec3 u_frustum_tr;uniform highp vec3 u_frustum_br;uniform highp vec3 u_frustum_bl;uniform highp vec3 u_globe_pos;uniform highp float u_globe_radius;uniform highp vec2 u_viewport;uniform float u_globe_transition;uniform int u_is_globe;float fog_range(float depth) {return (depth-u_fog_range[0])/(u_fog_range[1]-u_fog_range[0]);}float fog_horizon_blending(vec3 camera_dir) {float t=max(0.0,camera_dir.z/u_fog_horizon_blend);return u_fog_color.a*exp(-3.0*t*t);}float fog_opacity(float t) {const float decay=6.0;float falloff=1.0-min(1.0,exp(-decay*t));falloff*=falloff*falloff;return u_fog_color.a*min(1.0,1.00747*falloff);}float globe_glow_progress() {highp vec2 uv=fragcoord_to_bottom_left_uv(gl_FragCoord.xy,u_viewport);highp vec3 ray_dir=mix(\nmix(u_frustum_tl,u_frustum_tr,uv.x),mix(u_frustum_bl,u_frustum_br,uv.x),1.0-uv.y);highp vec3 dir=normalize(ray_dir);highp vec3 closest_point=dot(u_globe_pos,dir)*dir;highp float sdf=length(closest_point-u_globe_pos)/u_globe_radius;return sdf+PI*0.5;}float fog_opacity(vec3 pos) {float depth=length(pos);return fog_opacity(fog_range(depth));}vec3 fog_apply(vec3 color,vec3 pos,float opacity_limit) {float depth=length(pos);float opacity;if (u_is_globe==1) {float glow_progress=globe_glow_progress();float t=mix(glow_progress,depth,u_globe_transition);opacity=fog_opacity(fog_range(t));} else {opacity=fog_opacity(fog_range(depth));opacity*=fog_horizon_blending(pos/depth);}return mix(color,u_fog_color.rgb,min(opacity,opacity_limit));}vec3 fog_apply(vec3 color,vec3 pos) {return fog_apply(color,pos,1.0);}vec4 fog_apply_from_vert(vec4 color,float fog_opac) {float alpha=EPSILON+color.a;color.rgb=mix(color.rgb/alpha,u_fog_color.rgb,fog_opac)*alpha;return color;}vec3 fog_apply_sky_gradient(vec3 camera_ray,vec3 sky_color) {float horizon_blend=fog_horizon_blending(normalize(camera_ray));return mix(sky_color,u_fog_color.rgb,horizon_blend);}vec4 fog_apply_premultiplied(vec4 color,vec3 pos) {float alpha=EPSILON+color.a;color.rgb=fog_apply(color.rgb/alpha,pos)*alpha;return color;}vec4 fog_apply_premultiplied(vec4 color,vec3 pos,float heightMeters) {float verticalProgress=(u_fog_vertical_limit.x > 0.0 || u_fog_vertical_limit.y > 0.0) ? smoothstep(u_fog_vertical_limit.x,u_fog_vertical_limit.y,heightMeters) : 0.0;float opacityLimit=1.0-smoothstep(0.9,1.0,fog_opacity(pos));return mix(fog_apply_premultiplied(color,pos),color,min(verticalProgress,opacityLimit));}vec3 fog_dither(vec3 color) {return color;}vec4 fog_dither(vec4 color) {return vec4(fog_dither(color.rgb),color.a);}\n#endif",Hd="\n#ifndef MAX_UBO_SIZE_VEC4\n#define MAX_UBO_SIZE_VEC4 1024u\n#endif\nfloat zoomFactor(float zm,float zM,float zoomFraction) {if (zm==zM) return zoomFraction-zm >=0.0 ? 1.0 : 0.0;return clamp((zoomFraction-zm)/(zM-zm),0.0,1.0);}",$d="\n#ifdef LIGHTING_3D_MODE\nuniform mediump vec3 u_lighting_ambient_color;uniform mediump vec3 u_lighting_directional_dir;uniform mediump vec3 u_lighting_directional_color;uniform mediump vec3 u_ground_radiance;float calculate_ambient_directional_factor(vec3 normal) {float NdotL=dot(normal,u_lighting_directional_dir);const float factor_reduction_max=0.3;float dir_luminance=dot(u_lighting_directional_color,vec3(0.2126,0.7152,0.0722));float directional_factor_min=1.0-factor_reduction_max*min(dir_luminance,1.0);float ambient_directional_factor=mix(directional_factor_min,1.0,min((NdotL+1.0),1.0));const float vertical_factor_min=0.92;float vertical_factor=mix(vertical_factor_min,1.0,normal.z*0.5+0.5);return vertical_factor*ambient_directional_factor;}vec3 linearProduct(vec3 srgbIn,vec3 k) {return srgbIn*pow(k,vec3(1./2.2));}vec3 apply_lighting(vec3 color,vec3 normal,float dir_factor) {float ambient_directional_factor=calculate_ambient_directional_factor(normal);vec3 ambient_contrib=ambient_directional_factor*u_lighting_ambient_color;vec3 directional_contrib=u_lighting_directional_color*dir_factor;return linearProduct(color,ambient_contrib+directional_contrib);}vec4 apply_lighting(vec4 color,vec3 normal,float dir_factor) {return vec4(apply_lighting(color.rgb,normal,dir_factor),color.a);}vec3 apply_lighting(vec3 color,vec3 normal) {float dir_factor=max(dot(normal,u_lighting_directional_dir),0.0);return apply_lighting(color.rgb,normal,dir_factor);}vec4 apply_lighting(vec4 color,vec3 normal) {float dir_factor=max(dot(normal,u_lighting_directional_dir),0.0);return vec4(apply_lighting(color.rgb,normal,dir_factor),color.a);}vec3 apply_lighting_ground(vec3 color) {return color*u_ground_radiance;}vec4 apply_lighting_ground(vec4 color) {return vec4(apply_lighting_ground(color.rgb),color.a);}float calculate_NdotL(vec3 normal) {const float ext=0.70710678118;return (clamp(dot(normal,u_lighting_directional_dir),-ext,1.0)+ext)/(1.0+ext);}vec4 apply_lighting_with_emission_ground(vec4 color,float emissive_strength) {return mix(apply_lighting_ground(color),color,emissive_strength);}vec3 compute_flood_lighting(vec3 flood_light_color,float fully_occluded_factor,float occlusion,vec3 ground_shadow_factor) {vec3 fully_occluded_color=flood_light_color*mix(ground_shadow_factor,vec3(1.0),fully_occluded_factor);float occlusion_ramp=smoothstep(0.0,0.2,1.0-occlusion);return mix(fully_occluded_color,flood_light_color,occlusion_ramp);}vec3 compute_emissive_draped(vec3 unlit_color,float fully_occluded_factor,float occlusion,vec3 ground_shadow_factor) {vec3 fully_occluded_color=unlit_color*mix(ground_shadow_factor,vec3(1.0),fully_occluded_factor);return mix(fully_occluded_color,unlit_color,1.0-occlusion);}\n#endif",Xd="#ifdef RASTER_ARRAY\nuniform highp sampler2D u_image0;uniform sampler2D u_image1;const vec4 NODATA=vec4(1);ivec4 _raTexLinearCoord(highp vec2 texCoord,highp vec2 texResolution,out highp vec2 fxy) {texCoord=texCoord*texResolution-0.5;fxy=fract(texCoord);texCoord-=fxy;return ivec4(texCoord.xxyy+vec2(1.5,0.5).xyxy);}vec2 _raTexLinearMix(highp vec2 fxy,highp vec4 colorMix,highp float colorOffset,highp vec4 t00,highp vec4 t10,highp vec4 t01,highp vec4 t11) {vec2 c00=t00==NODATA ? vec2(0) : vec2(colorOffset+dot(t00,colorMix),1);vec2 c10=t10==NODATA ? vec2(0) : vec2(colorOffset+dot(t10,colorMix),1);vec2 c01=t01==NODATA ? vec2(0) : vec2(colorOffset+dot(t01,colorMix),1);vec2 c11=t11==NODATA ? vec2(0) : vec2(colorOffset+dot(t11,colorMix),1);return mix(mix(c01,c11,fxy.x),mix(c00,c10,fxy.x),fxy.y);}vec2 raTexture2D_image0_linear(highp vec2 texCoord,highp vec2 texResolution,highp vec4 colorMix,highp float colorOffset) {vec2 fxy;ivec4 c=_raTexLinearCoord(texCoord,texResolution,fxy);return _raTexLinearMix(fxy,colorMix,colorOffset,texelFetch(u_image0,c.yz,0),texelFetch(u_image0,c.xz,0),texelFetch(u_image0,c.yw,0),texelFetch(u_image0,c.xw,0)\n);}vec2 raTexture2D_image1_linear(highp vec2 texCoord,highp vec2 texResolution,highp vec4 colorMix,highp float colorOffset) {vec2 fxy;ivec4 c=_raTexLinearCoord(texCoord,texResolution,fxy);return _raTexLinearMix(fxy,colorMix,colorOffset,texelFetch(u_image1,c.yz,0),texelFetch(u_image1,c.xz,0),texelFetch(u_image1,c.yw,0),texelFetch(u_image1,c.xw,0)\n);}vec2 raTexture2D_image0_nearest(highp vec2 texCoord,highp vec2 texResolution,highp vec4 colorMix,highp float colorOffset) {vec4 t=texelFetch(u_image0,ivec2(texCoord*texResolution),0);return t==NODATA ? vec2(0) : vec2(colorOffset+dot(t,colorMix),1);}vec2 raTexture2D_image1_nearest(highp vec2 texCoord,highp vec2 texResolution,highp vec4 colorMix,highp float colorOffset) {vec4 t=texelFetch(u_image1,ivec2(texCoord*texResolution),0);return t==NODATA ? vec2(0) : vec2(colorOffset+dot(t,colorMix),1);}\n#endif",Yd="#ifdef RENDER_SHADOWS\nuniform mediump vec3 u_shadow_direction;uniform highp vec3 u_shadow_normal_offset;vec3 shadow_normal_offset(vec3 normal) {float tileInMeters=u_shadow_normal_offset[0];vec3 n=vec3(-normal.xy,tileInMeters*normal.z);float dotScale=min(1.0-dot(normal,u_shadow_direction),1.0)*0.5+0.5;return n*dotScale;}vec3 shadow_normal_offset_model(vec3 normal) {vec3 transformed_normal=vec3(-normal.xy,normal.z);float NDotL=dot(normalize(transformed_normal),u_shadow_direction);float dotScale=min(1.0-NDotL,1.0)*0.5+0.5;return normal*dotScale;}float shadow_normal_offset_multiplier0() {return u_shadow_normal_offset[1];}float shadow_normal_offset_multiplier1() {return u_shadow_normal_offset[2];}\n#endif",Kd="#ifdef RENDER_SHADOWS\nprecision highp sampler2DShadow;uniform sampler2DShadow u_shadowmap_0;uniform sampler2DShadow u_shadowmap_1;uniform float u_shadow_intensity;uniform float u_shadow_map_resolution;uniform float u_shadow_texel_size;uniform highp vec3 u_shadow_normal_offset;uniform vec2 u_fade_range;uniform mediump vec3 u_shadow_direction;uniform highp vec3 u_shadow_bias;highp vec2 shadow_map_ndc_to_uv(highp vec2 ndc_xy) {return ndc_xy*0.5+0.5;}highp vec3 shadow_map_ndc_to_sample_space(highp vec3 ndc) {return vec3(shadow_map_ndc_to_uv(ndc.xy),native_ndc_z_to_storage_depth(ndc.z));}float shadow_sample(sampler2DShadow shadowmap,highp vec3 pos,highp float bias) {highp vec3 coord=vec3(shadow_map_ndc_to_uv(pos.xy),native_ndc_z_to_storage_depth(pos.z)-bias);return texture(shadowmap,coord);}float shadow_occlusion(highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth,highp float bias) {light_view_pos0.xyz/=light_view_pos0.w;\n#ifdef SHADOWS_SINGLE_CASCADE\nvec2 abs_bounds=abs(light_view_pos0.xy);if (abs_bounds.x >=1.0 || abs_bounds.y >=1.0) {return 0.0;}return shadow_sample(u_shadowmap_0,light_view_pos0.xyz,bias);\n#else\nlight_view_pos1.xyz/=light_view_pos1.w;vec4 abs_bounds=abs(vec4(light_view_pos0.xy,light_view_pos1.xy));if (abs_bounds.x < 1.0 && abs_bounds.y < 1.0) {return shadow_sample(u_shadowmap_0,light_view_pos0.xyz,bias);}if (abs_bounds.z >=1.0 || abs_bounds.w >=1.0) {return 0.0;}float occlusion1=shadow_sample(u_shadowmap_1,light_view_pos1.xyz,bias);return clamp(mix(occlusion1,0.0,smoothstep(u_fade_range.x,u_fade_range.y,view_depth)),0.0,1.0);\n#endif\n}highp float calculate_shadow_bias(float NDotL) {\n#ifdef NORMAL_OFFSET\nreturn 0.5*u_shadow_bias.x;\n#else\nreturn 0.5*(u_shadow_bias.x+clamp(u_shadow_bias.y*tan(acos(NDotL)),0.0,u_shadow_bias.z));\n#endif\n}float shadowed_light_factor_normal(vec3 N,highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float NDotL=dot(N,u_shadow_direction);float bias=calculate_shadow_bias(NDotL);float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);return mix(0.0,(1.0-(u_shadow_intensity*occlusion))*NDotL,step(0.0,NDotL));}float shadowed_light_factor_normal_opacity(vec3 N,highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth,float shadow_opacity) {float NDotL=dot(N,u_shadow_direction);float bias=calculate_shadow_bias(NDotL);float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias)*shadow_opacity;return mix(0.0,(1.0-(u_shadow_intensity*occlusion))*NDotL,step(0.0,NDotL));}float shadowed_light_factor_normal_unbiased(vec3 N,highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float NDotL=dot(N,u_shadow_direction);float bias=0.0;float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);return mix(0.0,(1.0-(u_shadow_intensity*occlusion))*NDotL,step(0.0,NDotL));}highp vec2 compute_receiver_plane_depth_bias(highp vec3 pos_dx,highp vec3 pos_dy)\n{highp vec2 biasUV=vec2(\npos_dy.y*pos_dx.z-pos_dx.y*pos_dy.z,pos_dx.x*pos_dy.z-pos_dy.x*pos_dx.z);biasUV*=1.0/((pos_dx.x*pos_dy.y)-(pos_dx.y*pos_dy.x));return biasUV;}float shadowed_light_factor_plane_bias(highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {highp vec3 light_view_pos0_xyz=shadow_map_ndc_to_sample_space(light_view_pos0.xyz/light_view_pos0.w);highp vec3 light_view_pos0_ddx=dFdx(light_view_pos0_xyz);highp vec3 light_view_pos0_ddy=dFdy(light_view_pos0_xyz);highp vec2 plane_depth_bias=compute_receiver_plane_depth_bias(light_view_pos0_ddx,light_view_pos0_ddy);highp float bias=dot(vec2(u_shadow_texel_size,u_shadow_texel_size),plane_depth_bias)+0.0001;float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);return 1.0-(u_shadow_intensity*occlusion);}float shadowed_light_factor(highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float bias=0.0;float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);return 1.0-(u_shadow_intensity*occlusion);}float shadow_occlusion(float ndotl,highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float bias=calculate_shadow_bias(ndotl);return shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);}\n#endif",Jd=/^#include\s+"([^"]+)"\s*\r?\n/gm,Qd=/#pragma mapbox: ([\w\-]+) ([\w]+) ([\w]+) ([\w]+)/g,eu=/\b[A-Za-z_][A-Za-z0-9_]*\b/g,tu=new Set(["ifdef","ifndef","elif","if","defined"]),iu=new Set;uu(Ud,iu),uu(jd,iu),uu(Vd,iu);const su={"_prelude_fog.vertex.glsl":Zd,"_prelude_terrain.vertex.glsl":qd,"_prelude_shadow.vertex.glsl":Yd,"_prelude_material_table.vertex.glsl":"","_prelude_fog.fragment.glsl":Wd,"_prelude_shadow.fragment.glsl":Kd,"_prelude_lighting.glsl":$d,"_prelude_ubo_properties.glsl":Hd,"_prelude_raster_array.glsl":Xd,"_prelude_indicator_cutout.fragment.glsl":"\nvec4 applyCutout(vec4 color,float height) {return color;}","_prelude_feature_cutout.fragment.glsl":"// feature cutout (gl-native only)\n","_prelude_feature_cutout.vertex.glsl":"// feature cutout (gl-native only)\n"},ou={},ru="precision highp float;",nu="precision mediump float;",au="\n#if defined(GL_EXT_blend_func_extended) && defined(DUAL_SOURCE_BLENDING)\n#extension GL_EXT_blend_func_extended : require\n#endif",lu={preludeTerrain:pu("",qd),preludeUBOProperties:pu("",Hd),preludeFog:pu(Wd,Zd),preludeShadow:pu(Kd,Yd),preludeRasterArray:pu(Xd,""),preludeLighting:pu($d,$d),preludePrecisionQualifiers:pu(nu,ru),prelude:pu(Vd,jd),preludeExtensions:pu(au,"")},cu=[au,nu,Ud,lu.prelude.fragmentSource].join("\n"),hu=[ru,Ud,lu.prelude.vertexSource].join("\n"),du={background:pu('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_feature_cutout.fragment.glsl"\nuniform vec4 u_color;uniform float u_opacity;uniform mediump float u_emissive_strength;\n#ifdef LIGHTING_3D_MODE\nin vec4 v_color;\n#endif\nvoid main() {vec4 out_color;\n#ifdef LIGHTING_3D_MODE\nout_color=v_color;\n#else\nout_color=u_color;\n#endif\n#ifdef FOG\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\n#endif\nglFragColor=out_color*u_opacity;storeEmissiveColor(glFragColor,u_emissive_strength);\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}','#include "_prelude_fog.vertex.glsl"\n#include "_prelude_lighting.glsl"\nin ivec2 a_pos;uniform mat4 u_matrix;uniform mediump float u_emissive_strength;\n#ifdef LIGHTING_3D_MODE\nuniform mediump vec4 u_color;out vec4 v_color;\n#endif\nvoid main() {gl_Position=u_matrix*vec4(a_pos,0,1);\n#ifdef LIGHTING_3D_MODE\nv_color=apply_lighting_with_emission_ground(u_color,u_emissive_strength);\n#endif\n#ifdef FOG\nv_fog_pos=fog_position(vec2(a_pos));\n#endif\n}'),backgroundPattern:pu('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_lighting.glsl"\nuniform vec2 u_pattern_tl;uniform vec2 u_pattern_br;uniform vec2 u_texsize;uniform float u_opacity;uniform float u_emissive_strength;uniform sampler2D u_image;in highp vec2 v_pos;void main() {highp vec2 imagecoord=mod(v_pos,1.0);highp vec2 pos=mix(u_pattern_tl/u_texsize,u_pattern_br/u_texsize,imagecoord);vec4 out_color=textureLodCustom(u_image,pos,v_pos);\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength);\n#endif\n#ifdef FOG\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\n#endif\nglFragColor=out_color*u_opacity;storeEmissiveColor(glFragColor,u_emissive_strength);\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}','#include "_prelude_fog.vertex.glsl"\nuniform mat4 u_matrix;uniform vec2 u_pattern_size;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec2 u_pattern_units_to_pixels;in ivec2 a_pos;out highp vec2 v_pos;void main() {vec2 pos=vec2(a_pos);gl_Position=u_matrix*vec4(pos,0,1);v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_pattern_size,u_pattern_units_to_pixels,pos);\n#ifdef FOG\nv_fog_pos=fog_position(pos);\n#endif\n}'),circle:pu('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_lighting.glsl"\nin vec3 v_data;in 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\nuniform float u_emissive_strength;void 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 blur_positive=blur < 0.0 ? 0.0 : 1.0;lowp float antialiasblur=v_data.z;float extrude_length=length(extrude)+antialiasblur*(1.0-blur_positive);float antialiased_blur=-max(abs(blur),antialiasblur);float antialiase_blur_opacity=smoothstep(0.0,antialiasblur,extrude_length-1.0);float opacity_t=blur_positive==1.0 ?\nsmoothstep(0.0,-antialiased_blur,1.0-extrude_length) :\nsmoothstep(antialiased_blur,0.0,extrude_length-1.0)-antialiase_blur_opacity;float color_t=stroke_width < 0.01 ? 0.0 : smoothstep(\nantialiased_blur,0.0,extrude_length-radius/(radius+stroke_width)\n);vec4 out_color=mix(color*opacity,stroke_color*stroke_opacity,color_t);\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength);\n#endif\n#ifdef FOG\nout_color=fog_apply_premultiplied(out_color,v_fog_pos);\n#endif\nglFragColor=out_color*(v_visibility*opacity_t);\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\n}','#include "_prelude_fog.vertex.glsl"\n#include "_prelude_terrain.vertex.glsl"\n#define NUM_VISIBILITY_RINGS 2\n#define INV_SQRT2 0.70710678\n#define ELEVATION_BIAS 0.0001\n#define NUM_VISIBILITY_SAMPLES_PER_RING 16\nuniform mat4 u_matrix;uniform mat2 u_extrude_scale;uniform lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;in ivec2 a_pos;\n#ifdef PROJECTION_GLOBE_VIEW\nin ivec4 a_pos_3;in ivec4 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir;\n#endif\n#ifdef ELEVATED_ROADS\nin float a_circle_z_offset;\n#endif\nout vec3 v_data;out 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\nvec2 calc_offset(vec2 extrusion,float radius,float stroke_width, float perspective_scale) {return extrusion*(radius+stroke_width)*u_extrude_scale*perspective_scale;}float cantilevered_elevation(vec2 pos,float radius,float stroke_width,float perspective_scale) {vec2 c1=pos+calc_offset(vec2(-1.0,-1.0),radius,stroke_width,perspective_scale);vec2 c2=pos+calc_offset(vec2(1.0,-1.0),radius,stroke_width,perspective_scale);vec2 c3=pos+calc_offset(vec2(1.0,1.0),radius,stroke_width,perspective_scale);vec2 c4=pos+calc_offset(vec2(-1.0,1.0),radius,stroke_width,perspective_scale);float h1=elevation(c1)+ELEVATION_BIAS;float h2=elevation(c2)+ELEVATION_BIAS;float h3=elevation(c3)+ELEVATION_BIAS;float h4=elevation(c4)+ELEVATION_BIAS;return max(h4,max(h3,max(h1,h2)));}float circle_elevation(vec2 pos) {\n#if defined(TERRAIN)\nreturn elevation(pos)+ELEVATION_BIAS;\n#else\nreturn 0.0;\n#endif\n}vec4 project_vertex(vec2 extrusion,vec4 world_center,vec4 projected_center,float radius,float stroke_width, float perspective_scale,mat3 surface_vectors) {vec2 sample_offset=calc_offset(extrusion,radius,stroke_width,perspective_scale);\n#ifdef PITCH_WITH_MAP\n#ifdef PROJECTION_GLOBE_VIEW\nreturn u_matrix*( world_center+vec4(sample_offset.x*surface_vectors[0]+sample_offset.y*surface_vectors[1],0) );\n#else\nreturn u_matrix*( world_center+vec4(sample_offset,0,0) );\n#endif\n#else\nreturn projected_center+vec4(sample_offset,0,0);\n#endif\n}void 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 pos2=vec2(a_pos);vec2 extrude=vec2(mod(pos2,2.0)*2.0-1.0);vec2 circle_center=floor(pos2*0.5);float height=circle_elevation(circle_center);vec4 world_center;mat3 surface_vectors;\n#ifdef PROJECTION_GLOBE_VIEW\nsurface_vectors=globe_mercator_surface_vectors(vec3(a_pos_normal_3)/16384.0,u_up_dir,u_zoom_transition);vec3 surface_extrusion=extrude.x*surface_vectors[0]+extrude.y*surface_vectors[1];vec3 globe_elevation=elevationVector(circle_center)*height;vec3 globe_pos=vec3(a_pos_3)+surface_extrusion+globe_elevation;vec3 mercator_elevation=u_up_dir*u_tile_up_scale*height;vec3 merc_pos=mercator_tile_position(u_inv_rot_matrix,circle_center,u_tile_id,u_merc_center)+surface_extrusion+mercator_elevation;vec3 pos=mix_globe_mercator(globe_pos,merc_pos,u_zoom_transition);world_center=vec4(pos,1);\n#else\nsurface_vectors=mat3(1.0);world_center=vec4(circle_center,height,1);\n#endif\n#ifdef ELEVATED_ROADS\nworld_center.z+=a_circle_z_offset+ELEVATION_BIAS;\n#endif\nvec4 projected_center=u_matrix*world_center;float perspective_scale=0.0;\n#ifdef PITCH_WITH_MAP\n#ifdef SCALE_WITH_MAP\nperspective_scale=1.0;\n#else\nperspective_scale=projected_center.w/u_camera_to_center_distance;\n#endif\n#else\n#ifdef SCALE_WITH_MAP\nperspective_scale=u_camera_to_center_distance;\n#else\nperspective_scale=projected_center.w;\n#endif\n#endif\ngl_Position=project_vertex(extrude,world_center,projected_center,radius,stroke_width,perspective_scale,surface_vectors);float terrain_visibility=0.0;\n#ifdef TERRAIN\nfloat arc;vec4 occlusion_world_center;vec4 occlusion_projected_center;\n#ifdef PITCH_WITH_MAP\narc=2.0*PI;float cantilevered_height=cantilevered_elevation(circle_center,radius,stroke_width,perspective_scale);occlusion_world_center=vec4(circle_center,cantilevered_height,1);occlusion_projected_center=u_matrix*occlusion_world_center;\n#else\narc=PI;occlusion_world_center=world_center;occlusion_projected_center=projected_center;\n#endif\nfloat step=arc/float(NUM_VISIBILITY_SAMPLES_PER_RING);for(int ring=0; ring < NUM_VISIBILITY_RINGS; ring++) {float ring_radius_fraction=(float(ring)+1.0)/float(NUM_VISIBILITY_RINGS);for(int i=0; i < NUM_VISIBILITY_SAMPLES_PER_RING; i++) {vec2 extrusion=vec2(cos(step*float(i)),-sin(step*float(i)))*ring_radius_fraction;vec4 frag_pos=project_vertex(extrusion,occlusion_world_center,occlusion_projected_center,radius,stroke_width,perspective_scale,surface_vectors);terrain_visibility+=float(!isOccluded(frag_pos));}}terrain_visibility/=float(NUM_VISIBILITY_RINGS)*float(NUM_VISIBILITY_SAMPLES_PER_RING);\n#else\nterrain_visibility=1.0;\n#endif\n#ifdef PROJECTION_GLOBE_VIEW\nterrain_visibility=1.0;\n#endif\nv_visibility=terrain_visibility;lowp float antialiasblur=1.0/u_device_pixel_ratio/(radius+stroke_width);v_data=vec3(extrude.x,extrude.y,antialiasblur);\n#ifdef FOG\nv_fog_pos=fog_position(world_center.xyz);\n#endif\n}'),clippingMask:pu("void main() {glFragColor=vec4(1.0);}","in ivec2 a_pos;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);}"),heatmap:pu('#include "_prelude_fog.fragment.glsl"\nuniform highp float u_intensity;in 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);glFragColor=vec4(val,1.0,1.0,1.0);\n#ifdef FOG\nif (u_is_globe==0) {glFragColor.r*=pow(1.0-fog_opacity(v_fog_pos),2.0);}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}','#include "_prelude_terrain.vertex.glsl"\n#include "_prelude_fog.vertex.glsl"\nuniform mat4 u_matrix;uniform float u_extrude_scale;uniform float u_intensity;in ivec2 a_pos;\n#ifdef PROJECTION_GLOBE_VIEW\nin ivec4 a_pos_3;in ivec4 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir;\n#endif\nout 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() {\n#pragma mapbox: initialize highp float weight\n#pragma mapbox: initialize mediump float radius\nvec2 unscaled_extrude=vec2(mod(vec2(a_pos),2.0)*2.0-1.0);float S=sqrt(-2.0*log(ZERO/weight/u_intensity/GAUSS_COEF))/3.0;v_extrude=S*unscaled_extrude;vec2 extrude=v_extrude*radius*u_extrude_scale;vec2 tilePos=floor(vec2(a_pos)*0.5);vec3 pos;\n#ifdef PROJECTION_GLOBE_VIEW\nvec3 pos_normal_3=vec3(a_pos_normal_3)/16384.0;mat3 surface_vectors=globe_mercator_surface_vectors(pos_normal_3,u_up_dir,u_zoom_transition);vec3 surface_extrusion=extrude.x*surface_vectors[0]+extrude.y*surface_vectors[1];vec3 globe_elevation=elevationVector(tilePos)*elevation(tilePos);vec3 globe_pos=vec3(a_pos_3)+surface_extrusion+globe_elevation;vec3 mercator_elevation=u_up_dir*u_tile_up_scale*elevation(tilePos);vec3 merc_pos=mercator_tile_position(u_inv_rot_matrix,tilePos,u_tile_id,u_merc_center)+surface_extrusion+mercator_elevation;pos=mix_globe_mercator(globe_pos,merc_pos,u_zoom_transition);\n#else\npos=vec3(tilePos+extrude,elevation(tilePos));\n#endif\ngl_Position=u_matrix*vec4(pos,1);\n#ifdef FOG\nv_fog_pos=fog_position(pos);\n#endif\n}'),heatmapTexture:pu("uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;in vec2 v_pos;void main() {float t=texture(u_image,v_pos).r;vec4 color=texture(u_color_ramp,vec2(t,0.5));glFragColor=color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(0.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}","in ivec2 a_pos;out vec2 v_pos;void main() {gl_Position=vec4(a_pos,0,1);v_pos=bottom_left_to_native_uv(vec2(a_pos)*0.5+0.5);}"),collisionBox:pu("in float v_placed;in float v_notUsed;void main() {vec4 red =vec4(1.0,0.0,0.0,1.0);vec4 blue=vec4(0.0,0.0,1.0,0.5);glFragColor =mix(red,blue,step(0.5,v_placed))*0.5;glFragColor*=mix(1.0,0.1,step(0.5,v_notUsed));}",'#include "_prelude_terrain.vertex.glsl"\nin ivec4 a_pos;in ivec2 a_anchor_pos;in ivec2 a_extrude;in uvec2 a_placed;in vec2 a_shift;in vec2 a_elevation_from_sea;in float a_size_scale;in vec2 a_padding;in float a_auto_z_offset;uniform mat4 u_matrix;uniform vec2 u_extrude_scale;uniform float u_camera_to_center_distance;\n#ifdef PROJECTION_GLOBE_VIEW\nuniform vec3 u_tile_id;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform float u_zoom_transition;\n#endif\nout float v_placed;out float v_notUsed;void main() {vec2 anchor_pos=vec2(a_anchor_pos);float feature_elevation=a_elevation_from_sea.x+a_auto_z_offset;float terrain_elevation=(a_elevation_from_sea.y==1.0 ? 0.0 : elevation(anchor_pos));vec3 proj_pos=vec3(a_pos)+elevationVector(anchor_pos)*(feature_elevation+terrain_elevation);\n#ifdef PROJECTION_GLOBE_VIEW\n#ifndef PROJECTED_POS_ON_VIEWPORT\nvec3 globe_pos=proj_pos;vec3 mercator_pos=mercator_tile_position(u_inv_rot_matrix,anchor_pos,u_tile_id,u_merc_center);proj_pos=mix_globe_mercator(globe_pos,mercator_pos,u_zoom_transition);\n#endif\n#endif\nvec4 projectedPoint=u_matrix*vec4(proj_pos,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float collision_perspective_ratio=clamp(\n0.5+0.5*(u_camera_to_center_distance/camera_to_anchor_distance),0.0,1.5);gl_Position=projectedPoint;gl_Position.xy+=(vec2(a_extrude)*a_size_scale+a_shift+a_padding)*u_extrude_scale*gl_Position.w*collision_perspective_ratio;v_placed=float(a_placed.x);v_notUsed=float(a_placed.y);}'),collisionCircle:pu("in float v_radius;in vec2 v_extrude;in float v_perspective_ratio;in float v_collision;void main() {float alpha=0.5*min(v_perspective_ratio,1.0);float stroke_radius=0.9*max(v_perspective_ratio,1.0);float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);glFragColor=color*alpha*opacity_t;}","in vec2 a_pos_2f;in float a_radius;in ivec2 a_flags;uniform mat4 u_matrix;uniform mat4 u_inv_matrix;uniform vec2 u_viewport_size;uniform float u_camera_to_center_distance;out float v_radius;out vec2 v_extrude;out float v_perspective_ratio;out float v_collision;vec3 toTilePosition(vec2 screenPos) {vec4 rayStart=u_inv_matrix*vec4(screenPos,-1.0,1.0);vec4 rayEnd =u_inv_matrix*vec4(screenPos, 1.0,1.0);rayStart.xyz/=rayStart.w;rayEnd.xyz /=rayEnd.w;highp float t=(0.0-rayStart.z)/(rayEnd.z-rayStart.z);return mix(rayStart.xyz,rayEnd.xyz,t);}void main() {vec2 anchorScreenPos=a_pos_2f;float radius=a_radius;int vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(\nmix(-1.0,1.0,float(vertexIdx >=2)),mix(-1.0,1.0,float(vertexIdx >=1 && vertexIdx <=2)));vec2 quadVertexExtent=quadVertexOffset*radius;vec3 tilePos=toTilePosition(anchorScreenPos);vec4 clipPos=u_matrix*vec4(tilePos,1.0);highp float camera_to_anchor_distance=clipPos.w;highp float collision_perspective_ratio=clamp(\n0.5+0.5*(u_camera_to_center_distance/camera_to_anchor_distance),0.0,4.0);float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_perspective_ratio=collision_perspective_ratio;v_collision=float(a_flags.x);gl_Position=vec4(clipPos.xyz/clipPos.w,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}"),placementDebug:pu("uniform vec4 u_color;uniform float u_outline_width;uniform float u_opacity;uniform float u_stroke_opacity;uniform float u_collision_padding_opacity;in vec2 v_offset;in vec2 v_half_size;in float v_is_circle;in float v_collision_padding;float boxDistance(vec2 offset,vec2 halfSize) {vec2 toCorner=abs(offset)-halfSize;return max(toCorner.x,toCorner.y);}float circleDistance(vec2 offset,float radius) {return length(offset)-radius;}float linearStep(float start,float end,float x) {return (clamp(x,start,end)-start)/(end-start);}float onePxLongLinearStepAt(float center,float x) {const float halfPx=0.5;return linearStep(center-halfPx,center+halfPx,x);}void main() {float distanceToEdge=mix(boxDistance(v_offset,v_half_size),circleDistance(v_offset,v_half_size.x),v_is_circle);float linearStepAtMinusOutlineWidth=onePxLongLinearStepAt(-u_outline_width,distanceToEdge);float linearStepAtZero=onePxLongLinearStepAt(0.0,distanceToEdge);float linearStepAtCollisionPadding=onePxLongLinearStepAt(v_collision_padding,distanceToEdge);float interiorCoverage=1.0-linearStepAtMinusOutlineWidth;float outlineCoverage=linearStepAtMinusOutlineWidth-linearStepAtZero;float collisionPaddingCoverage=linearStepAtZero-linearStepAtCollisionPadding;glFragColor=u_color*(u_opacity*interiorCoverage+u_stroke_opacity*outlineCoverage+u_collision_padding_opacity*collisionPaddingCoverage);}","\nin vec2 a_pos_2f;in vec2 a_size;in float a_collision_padding;in ivec2 a_flags;uniform vec2 u_viewport_size;out vec2 v_offset;out vec2 v_half_size;out float v_is_circle;out float v_collision_padding;const vec2 QUAD_CORNERS[4]=vec2[4](vec2(-1.0,-1.0),vec2(1.0,-1.0),vec2(1.0,1.0),vec2(-1.0,1.0));const float AA_width=1.0;void main() {vec2 offset=QUAD_CORNERS[a_flags.y]*(a_size+a_collision_padding+AA_width);v_offset=offset;v_half_size=a_size;v_is_circle=float(a_flags.x);v_collision_padding=a_collision_padding;vec2 viewportPos=(a_pos_2f+offset)/u_viewport_size;gl_Position=vec4(viewportPos*vec2(2.0,-2.0)+vec2(-1.0,1.0),0.0,1.0);}"),debug:pu("uniform highp vec4 u_color;uniform sampler2D u_overlay;in vec2 v_uv;void main() {vec4 overlay_color=texture(u_overlay,v_uv);glFragColor=mix(u_color,overlay_color,overlay_color.a);}",'#include "_prelude_terrain.vertex.glsl"\nin ivec2 a_pos;\n#ifdef PROJECTION_GLOBE_VIEW\nin ivec4 a_pos_3;\n#endif\nout vec2 v_uv;uniform mat4 u_matrix;uniform float u_overlay_scale;void main() {vec2 pos=vec2(a_pos);float h=elevation(pos);v_uv=pos/8192.0;\n#ifdef PROJECTION_GLOBE_VIEW\ngl_Position=u_matrix*vec4(vec3(a_pos_3)+elevationVector(pos)*h,1);\n#else\ngl_Position=u_matrix*vec4(pos*u_overlay_scale,h,1);\n#endif\n}'),fill:pu('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_lighting.glsl"\n#include "_prelude_shadow.fragment.glsl"\n#include "_prelude_indicator_cutout.fragment.glsl"\n#include "_prelude_feature_cutout.fragment.glsl"\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nuniform float u_emissive_strength;uniform lowp float u_opacity_multiplier;\n#ifdef RENDER_SHADOWS\nuniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth;\n#endif\n#ifdef ELEVATED_ROADS\nin highp float v_road_z_offset;\n#endif\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\nvec2 cutout_factors=vec2(0.0);vec4 out_color=color;\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength);\n#ifdef RENDER_SHADOWS\nfloat light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y);out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light);\n#endif\n#endif\n#ifdef FOG\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\n#endif\nout_color*=(opacity*u_opacity_multiplier);glFragColor=out_color;storeEmissiveColor(glFragColor,u_emissive_strength);\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}','#include "_prelude_fog.vertex.glsl"\n#include "_prelude_shadow.vertex.glsl"\nin ivec2 a_pos;\n#ifdef ELEVATED_ROADS\nin float a_road_z_offset;out highp float v_road_z_offset;\n#endif\n#ifdef RENDER_SHADOWS\nuniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth;\n#endif\nuniform mat4 u_matrix;uniform lowp float u_opacity_multiplier;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp float z_offset\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp float z_offset\n#ifdef ELEVATED_ROADS\nz_offset+=a_road_z_offset;v_road_z_offset=z_offset;\n#endif\nfloat hidden=float(opacity==0.0);gl_Position=mix(u_matrix*vec4(a_pos,z_offset,1),AWAY,hidden);\n#ifdef RENDER_SHADOWS\nvec3 shd_pos0=vec3(a_pos,z_offset);vec3 shd_pos1=vec3(a_pos,z_offset);\n#ifdef NORMAL_OFFSET\nvec3 offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1();\n#endif\nv_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w;\n#endif\n#ifdef FOG\nv_fog_pos=fog_position(vec2(a_pos));\n#endif\n}'),fillOutline:pu('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_lighting.glsl"\n#include "_prelude_shadow.fragment.glsl"\n#include "_prelude_feature_cutout.fragment.glsl"\nin highp vec2 v_pos;uniform float u_emissive_strength;uniform lowp float u_opacity_multiplier;\n#ifdef ELEVATED_ROADS\nin highp float v_road_z_offset;\n#endif\n#ifdef RENDER_SHADOWS\nuniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp 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);vec4 out_color=outline_color;vec2 cutout_factors=vec2(0.0);\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength);\n#ifdef RENDER_SHADOWS\nfloat light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y);out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light);\n#endif\n#endif\n#ifdef FOG\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\n#endif\nglFragColor=out_color*(alpha*opacity*u_opacity_multiplier);storeEmissiveColor(glFragColor,u_emissive_strength);\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}','#include "_prelude_fog.vertex.glsl"\n#include "_prelude_shadow.vertex.glsl"\nin ivec2 a_pos;\n#ifdef ELEVATED_ROADS\nin float a_road_z_offset;out highp float v_road_z_offset;\n#endif\n#ifdef RENDER_SHADOWS\nuniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth;\n#endif\nuniform mat4 u_matrix;uniform vec2 u_world;uniform lowp float u_opacity_multiplier;out highp vec2 v_pos;\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp float z_offset\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp float z_offset\n#ifdef ELEVATED_ROADS\nz_offset+=a_road_z_offset;v_road_z_offset=z_offset;\n#endif\nfloat hidden=float(opacity==0.0);gl_Position=mix(u_matrix*vec4(a_pos,z_offset,1),AWAY,hidden);v_pos=ndc_xy_to_framebuffer_uv(gl_Position.xy/gl_Position.w)*u_world;\n#ifdef RENDER_SHADOWS\nvec3 shd_pos0=vec3(a_pos,z_offset);vec3 shd_pos1=vec3(a_pos,z_offset);\n#ifdef NORMAL_OFFSET\nvec3 offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1();\n#endif\nv_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w;\n#endif\n#ifdef FOG\nv_fog_pos=fog_position(vec2(a_pos));\n#endif\n}'),fillOutlinePattern:pu('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_lighting.glsl"\n#include "_prelude_shadow.fragment.glsl"\n#include "_prelude_feature_cutout.fragment.glsl"\nuniform vec2 u_texsize;uniform sampler2D u_image;\n#ifdef FILL_PATTERN_TRANSITION\nuniform float u_pattern_transition;\n#endif\nuniform float u_emissive_strength;uniform lowp float u_opacity_multiplier;\n#ifdef APPLY_LUT_ON_GPU\nuniform highp sampler3D u_lutTexture;\n#endif\n#ifdef RENDER_SHADOWS\nuniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth;\n#endif\n#ifdef ELEVATED_ROADS\nin highp float v_road_z_offset;\n#endif\nin highp vec2 v_pos;in highp vec2 v_pos_world;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp uvec4 pattern\n#ifdef FILL_PATTERN_TRANSITION\n#pragma mapbox: define mediump uvec4 pattern_b\n#endif\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump uvec4 pattern\n#ifdef FILL_PATTERN_TRANSITION\n#pragma mapbox: initialize mediump uvec4 pattern_b\n#endif\nvec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);highp vec2 imagecoord=mod(v_pos,1.0);highp vec2 pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,imagecoord);highp vec2 lod_pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,v_pos);float dist=length(v_pos_world-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);vec4 out_color=textureLodCustom(u_image,pos,lod_pos);\n#ifdef APPLY_LUT_ON_GPU\nout_color=applyLUT(u_lutTexture,out_color);\n#endif\n#ifdef FILL_PATTERN_TRANSITION\nvec2 pattern_b_tl=vec2(pattern_b.xy);vec2 pattern_b_br=vec2(pattern_b.zw);highp vec2 pos_b=mix(pattern_b_tl/u_texsize,pattern_b_br/u_texsize,imagecoord);vec4 color_b=textureLodCustom(u_image,pos_b,lod_pos);out_color=out_color*(1.0-u_pattern_transition)+color_b*u_pattern_transition;\n#endif\nvec2 cutout_factors=vec2(0.0);\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength);\n#ifdef RENDER_SHADOWS\nfloat light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y);out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light);\n#endif\n#endif\n#ifdef FOG\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\n#endif\nglFragColor=out_color*(alpha*opacity*u_opacity_multiplier);storeEmissiveColor(glFragColor,u_emissive_strength);\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}','#include "_prelude_fog.vertex.glsl"\n#include "_prelude_shadow.vertex.glsl"\nuniform mat4 u_matrix;uniform vec2 u_world;uniform lowp float u_opacity_multiplier;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_tile_units_to_pixels;in ivec2 a_pos;\n#ifdef ELEVATED_ROADS\nin float a_road_z_offset;out highp float v_road_z_offset;\n#endif\n#ifdef RENDER_SHADOWS\nuniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth;\n#endif\nout highp vec2 v_pos;out highp vec2 v_pos_world;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp uvec4 pattern\n#ifdef FILL_PATTERN_TRANSITION\n#pragma mapbox: define mediump uvec4 pattern_b\n#endif\n#pragma mapbox: define lowp float pixel_ratio\n#pragma mapbox: define highp float z_offset\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump uvec4 pattern\n#ifdef FILL_PATTERN_TRANSITION\n#pragma mapbox: initialize mediump uvec4 pattern_b\n#endif\n#pragma mapbox: initialize lowp float pixel_ratio\n#pragma mapbox: initialize highp float z_offset\nvec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);\n#ifdef ELEVATED_ROADS\nz_offset+=a_road_z_offset;v_road_z_offset=z_offset;\n#endif\nfloat hidden=float(opacity==0.0);vec2 pos=vec2(a_pos);gl_Position=mix(u_matrix*vec4(pos,z_offset,1),AWAY,hidden);vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio;v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,display_size,u_tile_units_to_pixels,pos);v_pos_world=ndc_xy_to_framebuffer_uv(gl_Position.xy/gl_Position.w)*u_world;\n#ifdef RENDER_SHADOWS\nvec3 shd_pos0=vec3(pos,z_offset);vec3 shd_pos1=vec3(pos,z_offset);\n#ifdef NORMAL_OFFSET\nvec3 offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1();\n#endif\nv_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w;\n#endif\n#ifdef FOG\nv_fog_pos=fog_position(pos);\n#endif\n}'),fillPattern:pu('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_lighting.glsl"\n#include "_prelude_shadow.fragment.glsl"\n#include "_prelude_feature_cutout.fragment.glsl"\nuniform vec2 u_texsize;uniform sampler2D u_image;\n#ifdef FILL_PATTERN_TRANSITION\nuniform float u_pattern_transition;\n#endif\nin highp vec2 v_pos;uniform float u_emissive_strength;uniform lowp float u_opacity_multiplier;\n#ifdef RENDER_SHADOWS\nuniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth;\n#endif\n#ifdef ELEVATED_ROADS\nin highp float v_road_z_offset;\n#endif\n#ifdef APPLY_LUT_ON_GPU\nuniform highp sampler3D u_lutTexture;\n#endif\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp uvec4 pattern\n#ifdef FILL_PATTERN_TRANSITION\n#pragma mapbox: define mediump uvec4 pattern_b\n#endif\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump uvec4 pattern\n#ifdef FILL_PATTERN_TRANSITION\n#pragma mapbox: initialize mediump uvec4 pattern_b\n#endif\nvec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);highp vec2 imagecoord=mod(v_pos,1.0);highp vec2 pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,imagecoord);highp vec2 lod_pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,v_pos);vec4 out_color=textureLodCustom(u_image,pos,lod_pos);\n#ifdef APPLY_LUT_ON_GPU\nout_color=applyLUT(u_lutTexture,out_color);\n#endif\n#ifdef FILL_PATTERN_TRANSITION\nvec2 pattern_b_tl=vec2(pattern_b.xy);vec2 pattern_b_br=vec2(pattern_b.zw);highp vec2 pos_b=mix(pattern_b_tl/u_texsize,pattern_b_br/u_texsize,imagecoord);vec4 color_b=textureLodCustom(u_image,pos_b,lod_pos);out_color=out_color*(1.0-u_pattern_transition)+color_b*u_pattern_transition;\n#endif\nvec2 cutout_factors=vec2(0.0);\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength);\n#ifdef RENDER_SHADOWS\nfloat light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y);\n#ifdef ELEVATED_ROADS\nout_color.rgb*=mix(v_road_z_offset !=0.0 ? u_ground_shadow_factor : vec3(1.0),vec3(1.0),light);\n#else\nout_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light);\n#endif\n#endif\n#endif\n#ifdef FOG\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\n#endif\nglFragColor=out_color*(opacity*u_opacity_multiplier);storeEmissiveColor(glFragColor,u_emissive_strength);\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}','#include "_prelude_fog.vertex.glsl"\n#include "_prelude_shadow.vertex.glsl"\nuniform mat4 u_matrix;uniform lowp float u_opacity_multiplier;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_tile_units_to_pixels;in ivec2 a_pos;\n#ifdef ELEVATED_ROADS\nin float a_road_z_offset;out highp float v_road_z_offset;\n#endif\n#ifdef RENDER_SHADOWS\nuniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth;\n#endif\nout highp vec2 v_pos;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp uvec4 pattern\n#ifdef FILL_PATTERN_TRANSITION\n#pragma mapbox: define mediump uvec4 pattern_b\n#endif\n#pragma mapbox: define lowp float pixel_ratio\n#pragma mapbox: define highp float z_offset\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump uvec4 pattern\n#pragma mapbox: initialize lowp float pixel_ratio\n#pragma mapbox: initialize highp float z_offset\n#ifdef FILL_PATTERN_TRANSITION\n#pragma mapbox: initialize mediump uvec4 pattern_b\n#endif\nvec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio;\n#ifdef ELEVATED_ROADS\nz_offset+=a_road_z_offset;v_road_z_offset=z_offset;\n#endif\nfloat hidden=float(opacity==0.0);vec2 pos=vec2(a_pos);gl_Position=mix(u_matrix*vec4(pos,z_offset,1),AWAY,hidden);v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,display_size,u_tile_units_to_pixels,pos);\n#ifdef RENDER_SHADOWS\nvec3 shd_pos0=vec3(pos,z_offset);vec3 shd_pos1=vec3(pos,z_offset);\n#ifdef NORMAL_OFFSET\nvec3 offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1();\n#endif\nv_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w;\n#endif\n#ifdef FOG\nv_fog_pos=fog_position(pos);\n#endif\n}'),lineBlendComposite:pu("uniform highp sampler2D u_image;uniform float u_opacity;uniform int u_blend_mode;uniform highp float u_max_density;in vec2 v_pos;\n#define ADDITIVE 1\nvoid main() {vec4 color=texture(u_image,v_pos);if (u_blend_mode==ADDITIVE) {if (color.a <=0.0) {discard;}highp float density=color.a;vec3 avgColor=color.rgb/max(density,0.001);highp float n=density/max(u_max_density,0.001);highp float t=sqrt(n/(n+1.0));glFragColor=vec4(avgColor*t,t);} else {vec3 multiplyFactor=color.rgb*u_opacity+(1.0-u_opacity);glFragColor=vec4(multiplyFactor,1.0);}\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(0.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}","in ivec2 a_pos;out vec2 v_pos;void main() {gl_Position=vec4(a_pos,0,1);v_pos=vec2(a_pos)*0.5+0.5;}"),lineBlendReduce:pu("uniform highp sampler2D u_image;uniform vec2 u_texel_size;uniform bool u_first_pass;in vec2 v_pos;void main() {vec2 o=u_texel_size*0.5;vec4 s0=texture(u_image,v_pos+vec2(-o.x,-o.y));vec4 s1=texture(u_image,v_pos+vec2( o.x,-o.y));vec4 s2=texture(u_image,v_pos+vec2(-o.x, o.y));vec4 s3=texture(u_image,v_pos+vec2( o.x, o.y));float r0; float g0;float r1; float g1;float r2; float g2;float r3; float g3;if (u_first_pass) {float a0=s0.a;float a1=s1.a;float a2=s2.a;float a3=s3.a;r0=a0; g0=a0 > 0.0 ? 1.0 : 0.0;r1=a1; g1=a1 > 0.0 ? 1.0 : 0.0;r2=a2; g2=a2 > 0.0 ? 1.0 : 0.0;r3=a3; g3=a3 > 0.0 ? 1.0 : 0.0;} else {r0=s0.r; g0=s0.g;r1=s1.r; g1=s1.g;r2=s2.r; g2=s2.g;r3=s3.r; g3=s3.g;}glFragColor=vec4((r0+r1+r2+r3)*0.25,(g0+g1+g2+g3)*0.25,0.0,0.0);}","in ivec2 a_pos;out vec2 v_pos;void main() {gl_Position=vec4(a_pos,0,1);v_pos=vec2(a_pos)*0.5+0.5;}"),fillExtrusion:pu('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_shadow.fragment.glsl"\n#include "_prelude_lighting.glsl"\n#include "_prelude_indicator_cutout.fragment.glsl"\n#include "_prelude_feature_cutout.fragment.glsl"\nin vec4 v_color;in vec4 v_flat;\n#if defined(RENDER_FRONT_CUTOFF) || defined(ROUTE_CORRIDOR)\nin float v_dither_opacity;\n#endif\n#ifdef RENDER_SHADOWS\nin highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;\n#endif\nuniform lowp float u_opacity;\n#ifdef FAUX_AO\nuniform lowp vec2 u_ao;in vec2 v_ao;\n#endif\n#if defined(ZERO_ROOF_RADIUS) && !defined(LIGHTING_3D_MODE)\nin vec4 v_roof_color;\n#endif\n#if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE)\nin highp vec3 v_normal;\n#endif\nuniform vec3 u_flood_light_color;uniform highp float u_vertical_scale;uniform float u_flood_light_intensity;uniform vec3 u_ground_shadow_factor;\n#if defined(LIGHTING_3D_MODE) && defined(FLOOD_LIGHT)\nin float v_flood_radius;in float v_has_floodlight;\n#endif\nin float v_height;\n#pragma mapbox: define highp float emissive_strength\nvoid main() {\n#pragma mapbox: initialize highp float emissive_strength\n#if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE)\nvec3 normal=normalize(v_normal);\n#endif\nfloat z;vec4 color=v_color;\n#ifdef ZERO_ROOF_RADIUS\nz=float(normal.z > 0.00001);\n#ifdef LIGHTING_3D_MODE\nnormal=mix(normal,vec3(0.0,0.0,1.0),z);\n#else\ncolor=mix(v_color,v_roof_color,z);\n#endif\n#endif\nfloat h=max(0.0,v_height);float ao_shade=1.0;\n#ifdef FAUX_AO\nfloat intensity=u_ao[0];float h_floors=h/(u_ao[1]*u_vertical_scale);float y_shade=1.0-0.9*intensity*min(v_ao.y,1.0);ao_shade=(1.0-0.08*intensity)*(y_shade+(1.0-y_shade)*(1.0-pow(1.0-min(h_floors/16.0,1.0),16.0)))+0.08*intensity*min(h_floors/160.0,1.0);float concave=v_ao.x*v_ao.x;\n#ifdef ZERO_ROOF_RADIUS\nconcave*=(1.0-z);\n#endif\nfloat x_shade=mix(1.0,mix(0.6,0.75,min(h_floors/30.0,1.0)),intensity)+0.1*intensity*min(h,1.0);ao_shade*=mix(1.0,x_shade*x_shade*x_shade,concave);\n#ifdef LIGHTING_3D_MODE\n#ifdef FLOOD_LIGHT\ncolor.rgb*=mix(ao_shade,1.0,v_has_floodlight);\n#else\ncolor.rgb*=ao_shade;\n#endif\n#else\ncolor.rgb*=ao_shade;\n#endif\n#endif\n#ifdef LIGHTING_3D_MODE\nfloat flood_radiance=0.0;\n#ifdef FLOOD_LIGHT\nflood_radiance=(1.0-min(h/v_flood_radius,1.0))*u_flood_light_intensity*v_has_floodlight;\n#endif\n#ifdef RENDER_SHADOWS\n#ifdef FLOOD_LIGHT\nfloat ndotl_unclamped=dot(normal,u_shadow_direction);float ndotl=max(0.0,ndotl_unclamped);float occlusion=ndotl_unclamped < 0.0 ? 1.0 : shadow_occlusion(ndotl,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w);vec3 litColor=apply_lighting(color.rgb,normal,(1.0-u_shadow_intensity*occlusion)*ndotl);vec3 floodLitColor=compute_flood_lighting(u_flood_light_color*u_opacity,1.0-u_shadow_intensity,occlusion,u_ground_shadow_factor);color.rgb=mix(litColor,floodLitColor,flood_radiance);\n#else\nfloat shadowed_lighting_factor;\n#ifdef RENDER_CUTOFF\nshadowed_lighting_factor=shadowed_light_factor_normal_opacity(normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w,v_cutoff_opacity);if (v_cutoff_opacity==0.0) {discard;}\n#else\nshadowed_lighting_factor=shadowed_light_factor_normal(normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w);\n#endif\ncolor.rgb=apply_lighting(color.rgb,normal,shadowed_lighting_factor);\n#endif\n#else\ncolor.rgb=apply_lighting(color.rgb,normal);\n#ifdef FLOOD_LIGHT\ncolor.rgb=mix(color.rgb,u_flood_light_color*u_opacity,flood_radiance);\n#endif\n#endif\ncolor.rgb=mix(color.rgb,v_flat.rgb,emissive_strength);color*=u_opacity;\n#endif\n#ifdef FOG\ncolor=fog_dither(fog_apply_premultiplied(color,v_fog_pos,h));\n#endif\n#if defined(RENDER_FRONT_CUTOFF) || defined(ROUTE_CORRIDOR)\nif (v_dither_opacity < 1.0) {int index=viewport_dither_index(gl_FragCoord.xy);if (v_dither_opacity < DITHER_THRESHOLDS[index]) {discard;}}\n#endif\nglFragColor=color;\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}','#include "_prelude_fog.vertex.glsl"\n#include "_prelude_terrain.vertex.glsl"\n#include "_prelude_shadow.vertex.glsl"\n#include "_prelude_lighting.glsl"\n#include "_prelude_material_table.vertex.glsl"\n#include "_prelude_feature_cutout.vertex.glsl"\nuniform mat4 u_matrix;\n#ifndef LIGHTING_3D_MODE\nuniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;\n#endif\nuniform float u_vertical_gradient;uniform lowp float u_opacity;uniform float u_edge_radius;uniform float u_width_scale;in ivec4 a_pos_normal_ed;\n#if defined(HAS_CENTROID) || defined(TERRAIN)\nin uvec2 a_centroid_pos;\n#endif\n#ifdef RENDER_WALL_MODE\nin ivec4 a_join_normal_inside;\n#endif\n#ifdef PROJECTION_GLOBE_VIEW\nin ivec4 a_pos_3;in ivec4 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir;uniform float u_height_lift;\n#endif\n#ifdef TERRAIN\nuniform int u_height_type;uniform int u_base_type;\n#endif\nuniform highp float u_vertical_scale;\n#if defined(RENDER_FRONT_CUTOFF) || defined(ROUTE_CORRIDOR)\n#ifdef RENDER_FRONT_CUTOFF\nuniform vec3 u_front_cutoff_params;\n#endif\nout float v_dither_opacity;\n#endif\nout vec4 v_color;out vec4 v_flat;\n#ifdef RENDER_SHADOWS\nuniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;\n#endif\n#if defined(ZERO_ROOF_RADIUS) && !defined(LIGHTING_3D_MODE)\nout vec4 v_roof_color;\n#endif\n#if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE)\nout highp vec3 v_normal;\n#endif\n#ifdef FAUX_AO\nuniform lowp vec2 u_ao;out vec2 v_ao;invariant gl_Position;\n#endif\n#if defined(LIGHTING_3D_MODE) && defined(FLOOD_LIGHT)\nout float v_flood_radius;out float v_has_floodlight;\n#endif\nout float v_height;vec3 linearTosRGB(vec3 color) {return pow(color,vec3(1./2.2));}vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));}\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define highp float flood_light_wall_radius\n#pragma mapbox: define highp float line_width\n#pragma mapbox: define highp float emissive_strength\nvoid main() {DECLARE_MATERIAL_TABLE_INFO\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize highp float flood_light_wall_radius\n#pragma mapbox: initialize highp float line_width\n#pragma mapbox: initialize highp float emissive_strength\nbase*=u_vertical_scale;height*=u_vertical_scale;vec4 top_up_ny_start=vec4(a_pos_normal_ed & 1);vec4 pos_nx=vec4(a_pos_normal_ed >> 1);float x_normal=pos_nx.z/8192.0;vec3 normal=top_up_ny_start.y==1.0 ? vec3(0.0,0.0,1.0) : normalize(vec3(x_normal,(2.0*top_up_ny_start.z-1.0)*(1.0-abs(x_normal)),0.0));\n#if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE)\nv_normal=normal;\n#endif\nbase=max(0.0,base);float attr_height=height;height=max(0.0,top_up_ny_start.y==0.0 && top_up_ny_start.x==1.0 ? height-u_edge_radius : height);float t=top_up_ny_start.x;vec2 centroid_pos=vec2(0.0);\n#if defined(HAS_CENTROID) || defined(TERRAIN)\ncentroid_pos=vec2(a_centroid_pos);\n#endif\nfloat ele=0.0;float h=0.0;float c_ele=0.0;vec3 pos;\n#ifdef TERRAIN\nbool is_flat_height=centroid_pos.x !=0.0 && u_height_type==1;bool is_flat_base=centroid_pos.x !=0.0 && u_base_type==1;ele=elevation(pos_nx.xy);bool is_elevation_encoded=centroid_pos.y==0.0 || (centroid_pos.y > 0.0 && (int(centroid_pos.y) & 7)==7);c_ele=is_flat_height || is_flat_base ? (is_elevation_encoded ? elevationFromUint16(centroid_pos.x) : flatElevation(centroid_pos)) : ele;float h_height=is_flat_height ? max(c_ele+height,ele+base+2.0) : ele+height;float h_base=is_flat_base ? max(c_ele+base,ele+base) : ele+(base==0.0 ?-5.0 : base);h=t > 0.0 ? max(h_base,h_height) : h_base;\n#else\nh=t > 0.0 ? height : base;\n#endif\npos=vec3(pos_nx.xy,h);\n#ifdef PROJECTION_GLOBE_VIEW\nfloat lift=float((t+base) > 0.0)*u_height_lift;h+=lift;vec3 globe_normal=normalize(mix(vec3(a_pos_normal_3)/16384.0,u_up_dir,u_zoom_transition));vec3 globe_pos=vec3(a_pos_3)+globe_normal*(u_tile_up_scale*h);vec3 merc_pos=mercator_tile_position(u_inv_rot_matrix,pos.xy,u_tile_id,u_merc_center)+u_up_dir*u_tile_up_scale*pos.z;pos=mix_globe_mercator(globe_pos,merc_pos,u_zoom_transition);\n#endif\nfloat cutoff=1.0;vec3 scaled_pos=pos;\n#if defined(RENDER_CUTOFF) || defined(RENDER_FRONT_CUTOFF) || defined(ROUTE_CORRIDOR)\nvec2 centroid_decoded=pos.xy;bool isBorderCentroid=false;if (centroid_pos.x > 0.0 && centroid_pos.y > 0.0) {int iy=int(centroid_pos.y);int spanYbits=iy & 7;if (spanYbits==7) {isBorderCentroid=true;int borderID=(iy >> 3) & 3;float coordAlongBorder=float(iy >> 5)*4.0;if (borderID==0) centroid_decoded=vec2(0.0,coordAlongBorder);else if (borderID==1) centroid_decoded=vec2(EXTENT,coordAlongBorder);else if (borderID==2) centroid_decoded=vec2(coordAlongBorder,0.0);else centroid_decoded=vec2(coordAlongBorder,EXTENT);} else {centroid_decoded=floor(centroid_pos/8.0);}}\n#endif\n#if defined(RENDER_FRONT_CUTOFF) || defined(ROUTE_CORRIDOR)\nfloat frontCutoffOpacity=1.0;float routeFade=0.0;\n#endif\n#if defined(RENDER_CUTOFF) || defined(RENDER_FRONT_CUTOFF)\nvec4 ground=u_matrix*vec4(centroid_decoded,ele,1.0);\n#endif\n#ifdef RENDER_CUTOFF\ncutoff=cutoff_opacity(u_cutoff_params,native_clip_z_to_cutoff_depth(ground.z,ground.w));if (centroid_pos.y !=0.0 && centroid_pos.x !=0.0) {vec3 centroid_random=vec3(centroid_pos.xy,centroid_pos.x+centroid_pos.y+1.0);vec3 ground_pos=centroid_random/8.0;vec3 g=floor(ground_pos);vec3 mod_=centroid_random-g*8.0;float seed=min(1.0,0.1*(min(3.5,max(mod_.x+mod_.y,0.2*attr_height))*0.35+mod_.z));if (cutoff < 0.8-seed) {cutoff=0.0;}}float cutoff_scale=cutoff;v_cutoff_opacity=cutoff;scaled_pos.z=mix(c_ele,h,cutoff_scale);\n#endif\nfloat hidden=float((centroid_pos.x==0.0 && centroid_pos.y==1.0) || (cutoff==0.0 && centroid_pos.x !=0.0) || (color.a==0.0));\n#ifdef RENDER_FRONT_CUTOFF\nif (centroid_pos.x > 0.0 && centroid_pos.y > 0.0) {hidden=max(hidden,float(ground.w <=0.0));float ndc_y=ground.y/max(ground.w,0.001);float threshold=u_front_cutoff_params.x*2.0-1.0;float range_ndc=u_front_cutoff_params.y*2.0;if (!isBorderCentroid) {hidden=max(hidden,float(ndc_y < threshold-range_ndc));}float t=clamp((ndc_y-(threshold-range_ndc))/max(range_ndc,0.001),0.0,1.0);frontCutoffOpacity=mix(u_front_cutoff_params.z,1.0,t);}\n#endif\n#if defined(RENDER_FRONT_CUTOFF) || defined(ROUTE_CORRIDOR)\nv_dither_opacity=1.0;\n#ifdef RENDER_FRONT_CUTOFF\nv_dither_opacity=min(v_dither_opacity,frontCutoffOpacity);\n#endif\nif (centroid_pos.x > 0.0 && centroid_pos.y > 0.0) {hidden=max(hidden,float(v_dither_opacity <=0.0));}\n#endif\n#ifdef RENDER_WALL_MODE\nvec3 join_normal_inside=vec3(a_join_normal_inside);vec2 wall_offset=u_width_scale*line_width*(join_normal_inside.xy/EXTENT);scaled_pos.xy+=(1.0-join_normal_inside.z)*wall_offset*0.5;scaled_pos.xy-=join_normal_inside.z*wall_offset*0.5;\n#endif\ngl_Position=mix(u_matrix*vec4(scaled_pos,1),AWAY,hidden);h=h-ele;v_height=h;\n#ifdef RENDER_SHADOWS\nvec3 shd_pos0=pos;vec3 shd_pos1=pos;\n#ifdef NORMAL_OFFSET\nvec3 offset=shadow_normal_offset(normal);shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1();\n#endif\nv_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);\n#endif\nfloat NdotL=0.0;float colorvalue=0.0;\n#ifndef LIGHTING_3D_MODE\ncolorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;NdotL=clamp(dot(normal,u_lightpos),0.0,1.0);NdotL=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),NdotL);if (normal.y !=0.0) {float r=0.84;r=mix(0.7,0.98,1.0-u_lightintensity);NdotL*=(\n(1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),r,1.0)));}\n#endif\n#ifdef FAUX_AO\nfloat concave=pos_nx.w-floor(pos_nx.w*0.5)*2.0;float start=top_up_ny_start.w;float y_ground=1.0-clamp(t+base,0.0,1.0);float top_height=height;\n#ifdef TERRAIN\ntop_height=mix(max(c_ele+height,ele+base+2.0),ele+height,float(centroid_pos.x==0.0))-ele;y_ground+=y_ground*5.0/max(3.0,top_height);\n#endif\nv_ao=vec2(mix(concave,-concave,start),y_ground);NdotL*=(1.0+0.05*(1.0-top_up_ny_start.y)*u_ao[0]);\n#ifdef PROJECTION_GLOBE_VIEW\ntop_height+=u_height_lift;\n#endif\nfloat z_bias=native_depth_epsilon(0.0000006);gl_Position.z-=(z_bias*(min(top_height,500.)+2.0*min(base,500.0)+60.0*concave+3.0*start))*gl_Position.w;\n#endif\n#ifdef LIGHTING_3D_MODE\n#ifdef FLOOD_LIGHT\nfloat is_wall=1.0-float(t > 0.0 && top_up_ny_start.y > 0.0);v_has_floodlight=float(flood_light_wall_radius > 0.0 && is_wall > 0.0);v_flood_radius=flood_light_wall_radius*u_vertical_scale;\n#endif\nv_color=vec4(color.rgb,1.0);float ndotl=calculate_NdotL(normal);v_flat.rgb=sRGBToLinear(color.rgb);v_flat.rgb=v_flat.rgb*(ndotl+(1.0-min(ndotl*57.29,1.0))*emissive_strength);v_flat=vec4(linearTosRGB(v_flat.rgb),1.0);\n#else\nv_color=vec4(0.0,0.0,0.0,1.0);v_color.rgb+=clamp(color.rgb*NdotL*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_color*=u_opacity;\n#endif\n#if defined(ZERO_ROOF_RADIUS) && !defined(LIGHTING_3D_MODE)\nfloat roofNdotL=clamp(u_lightpos.z,0.0,1.0);roofNdotL=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),roofNdotL);v_roof_color=vec4(0.0,0.0,0.0,1.0);v_roof_color.rgb+=clamp(color.rgb*roofNdotL*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_roof_color*=u_opacity;\n#endif\n#ifdef FOG\nv_fog_pos=fog_position(pos);\n#endif\n}'),fillExtrusionPattern:pu('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_lighting.glsl"\n#include "_prelude_indicator_cutout.fragment.glsl"\nuniform vec2 u_texsize;uniform sampler2D u_image;\n#ifdef FILL_EXTRUSION_PATTERN_TRANSITION\nuniform float u_pattern_transition;\n#endif\n#ifdef FAUX_AO\nuniform lowp vec2 u_ao;in vec3 v_ao;\n#endif\n#ifdef LIGHTING_3D_MODE\nin vec3 v_normal;\n#endif\n#ifdef APPLY_LUT_ON_GPU\nuniform highp sampler3D u_lutTexture;\n#endif\nin highp vec2 v_pos;in vec4 v_lighting;uniform lowp float u_opacity;\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define mediump uvec4 pattern\n#ifdef FILL_EXTRUSION_PATTERN_TRANSITION\n#pragma mapbox: define mediump uvec4 pattern_b\n#endif\n#pragma mapbox: define highp float pixel_ratio\nvoid main() {\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize mediump uvec4 pattern\n#ifdef FILL_EXTRUSION_PATTERN_TRANSITION\n#pragma mapbox: initialize mediump uvec4 pattern_b\n#endif\n#pragma mapbox: initialize highp float pixel_ratio\nvec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);highp vec2 imagecoord=mod(v_pos,1.0);highp vec2 pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,imagecoord);highp vec2 lod_pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,v_pos);vec4 out_color=textureLodCustom(u_image,pos,lod_pos);\n#ifdef APPLY_LUT_ON_GPU\nout_color=applyLUT(u_lutTexture,out_color);\n#endif\n#ifdef FILL_EXTRUSION_PATTERN_TRANSITION\nvec2 pattern_b_tl=vec2(pattern_b.xy);vec2 pattern_b_br=vec2(pattern_b.zw);highp vec2 pos_b=mix(pattern_b_tl/u_texsize,pattern_b_br/u_texsize,imagecoord);vec4 color_b=textureLodCustom(u_image,pos_b,lod_pos);out_color=out_color*(1.0-u_pattern_transition)+color_b*u_pattern_transition;\n#endif\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting(out_color,normalize(v_normal))*u_opacity;\n#else\nout_color=out_color*v_lighting;\n#endif\n#ifdef FAUX_AO\nfloat intensity=u_ao[0];float h=max(0.0,v_ao.z);float h_floors=h/u_ao[1];float y_shade=1.0-0.9*intensity*min(v_ao.y,1.0);float shade=(1.0-0.08*intensity)*(y_shade+(1.0-y_shade)*(1.0-pow(1.0-min(h_floors/16.0,1.0),16.0)))+0.08*intensity*min(h_floors/160.0,1.0);float concave=v_ao.x*v_ao.x;float x_shade=mix(1.0,mix(0.6,0.75,min(h_floors/30.0,1.0)),intensity)+0.1*intensity*min(h,1.0);shade*=mix(1.0,x_shade*x_shade*x_shade,concave);out_color.rgb=out_color.rgb*shade;\n#endif\n#ifdef FOG\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\n#endif\nglFragColor=out_color;\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}','#include "_prelude_fog.vertex.glsl"\n#include "_prelude_terrain.vertex.glsl"\n#include "_prelude_lighting.glsl"\n#include "_prelude_material_table.vertex.glsl"\nuniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform float u_tile_units_to_pixels;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform float u_width_scale;\n#ifndef LIGHTING_3D_MODE\nuniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;\n#endif\nin ivec4 a_pos_normal_ed;\n#if defined(HAS_CENTROID) || defined(TERRAIN)\nin uvec2 a_centroid_pos;\n#endif\n#ifdef RENDER_WALL_MODE\nin ivec4 a_join_normal_inside;\n#endif\n#ifdef PROJECTION_GLOBE_VIEW\nin ivec4 a_pos_3;in ivec4 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir;uniform float u_height_lift;\n#endif\n#ifdef TERRAIN\nuniform int u_height_type;uniform int u_base_type;\n#endif\nout highp vec2 v_pos;out vec4 v_lighting;\n#ifdef FAUX_AO\nuniform lowp vec2 u_ao;out vec3 v_ao;invariant gl_Position;\n#endif\n#ifdef LIGHTING_3D_MODE\nout vec3 v_normal;\n#endif\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump uvec4 pattern\n#ifdef FILL_EXTRUSION_PATTERN_TRANSITION\n#pragma mapbox: define mediump uvec4 pattern_b\n#endif\n#pragma mapbox: define highp float pixel_ratio\n#pragma mapbox: define highp float line_width\nvoid main() {DECLARE_MATERIAL_TABLE_INFO\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump uvec4 pattern\n#ifdef FILL_EXTRUSION_PATTERN_TRANSITION\n#pragma mapbox: initialize mediump uvec4 pattern_b\n#endif\n#pragma mapbox: initialize highp float pixel_ratio\n#pragma mapbox: initialize highp float line_width\nvec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);vec4 top_up_ny_start=vec4(a_pos_normal_ed & 1);vec4 pos_nx=vec4(a_pos_normal_ed >> 1);float x_normal=pos_nx.z/8192.0;vec3 normal=top_up_ny_start.y==1.0 ? vec3(0.0,0.0,1.0) : normalize(vec3(x_normal,(2.0*top_up_ny_start.z-1.0)*(1.0-abs(x_normal)),0.0));float edgedistance=float(a_pos_normal_ed.w);vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio;base=max(0.0,base);height=max(0.0,height);float t=top_up_ny_start.x;float z=t > 0.0 ? height : base;vec2 centroid_pos=vec2(0.0);\n#if defined(HAS_CENTROID) || defined(TERRAIN)\ncentroid_pos=vec2(a_centroid_pos);\n#endif\nfloat ele=0.0;float h=z;vec3 p;float c_ele;\n#ifdef TERRAIN\nbool is_flat_height=centroid_pos.x !=0.0 && u_height_type==1;bool is_flat_base=centroid_pos.x !=0.0 && u_base_type==1;ele=elevation(pos_nx.xy);bool is_elevation_encoded=centroid_pos.y==0.0 || (centroid_pos.y > 0.0 && int(centroid_pos.y)-(int(centroid_pos.y)/8)*8==7);c_ele=is_flat_height || is_flat_base ? (is_elevation_encoded ? elevationFromUint16(centroid_pos.x) : flatElevation(centroid_pos)) : ele;float h_height=is_flat_height ? max(c_ele+height,ele+base+2.0) : ele+height;float h_base=is_flat_base ? max(c_ele+base,ele+base) : ele+(base==0.0 ?-5.0 : base);h=t > 0.0 ? max(h_base,h_height) : h_base;p=vec3(pos_nx.xy,h);\n#else\np=vec3(pos_nx.xy,z);\n#endif\n#ifdef PROJECTION_GLOBE_VIEW\nfloat lift=float((t+base) > 0.0)*u_height_lift;h+=lift;vec3 globe_normal=normalize(mix(vec3(a_pos_normal_3)/16384.0,u_up_dir,u_zoom_transition));vec3 globe_pos=vec3(a_pos_3)+globe_normal*(u_tile_up_scale*(p.z+lift));vec3 merc_pos=mercator_tile_position(u_inv_rot_matrix,p.xy,u_tile_id,u_merc_center)+u_up_dir*u_tile_up_scale*p.z;p=mix_globe_mercator(globe_pos,merc_pos,u_zoom_transition);\n#endif\n#ifdef RENDER_WALL_MODE\nvec3 join_normal_inside=vec3(a_join_normal_inside);vec2 wall_offset=u_width_scale*line_width*(join_normal_inside.xy/EXTENT);p.xy+=(1.0-join_normal_inside.z)*wall_offset*0.5;p.xy-=join_normal_inside.z*wall_offset*0.5;\n#endif\nfloat hidden=float((centroid_pos.x==0.0 && centroid_pos.y==1.0) || (color.a==0.0));gl_Position=mix(u_matrix*vec4(p,1),AWAY,hidden);vec2 pos=normal.z==1.0\n? pos_nx.xy\n: vec2(edgedistance,z*u_height_factor);v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,display_size,u_tile_units_to_pixels,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float NdotL=0.0;\n#ifdef LIGHTING_3D_MODE\nNdotL=calculate_NdotL(normal);\n#else\nNdotL=clamp(dot(normal,u_lightpos),0.0,1.0);NdotL=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),NdotL);\n#endif\nif (normal.y !=0.0) {float r=0.84;\n#ifndef LIGHTING_3D_MODE\nr=mix(0.7,0.98,1.0-u_lightintensity);\n#endif\nNdotL*=(\n(1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),r,1.0)));}\n#ifdef FAUX_AO\nfloat concave=pos_nx.w-floor(pos_nx.w*0.5)*2.0;float start=top_up_ny_start.w;float y_ground=1.0-clamp(t+base,0.0,1.0);float top_height=height;\n#ifdef TERRAIN\ntop_height=mix(max(c_ele+height,ele+base+2.0),ele+height,float(centroid_pos.x==0.0))-ele;y_ground+=y_ground*5.0/max(3.0,top_height);\n#endif\nv_ao=vec3(mix(concave,-concave,start),y_ground,h-ele);NdotL*=(1.0+0.05*(1.0-top_up_ny_start.y)*u_ao[0]);\n#ifdef PROJECTION_GLOBE_VIEW\ntop_height+=u_height_lift;\n#endif\nfloat z_bias=native_depth_epsilon(0.0000006);gl_Position.z-=(z_bias*(min(top_height,500.)+2.0*min(base,500.0)+60.0*concave+3.0*start))*gl_Position.w;\n#endif\n#ifdef LIGHTING_3D_MODE\nv_normal=normal;\n#else\nv_lighting.rgb+=clamp(NdotL*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity;\n#endif\n#ifdef FOG\nv_fog_pos=fog_position(p);\n#endif\n}'),hillshadePrepare:pu("precision highp float;uniform highp sampler2D u_image;in vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;float getElevation(vec2 coord) {return texture(u_image,coord).r/4.0;}void main() {vec2 epsilon=1.0/u_dimension;float a=getElevation(v_pos+vec2(-epsilon.x,-epsilon.y));float b=getElevation(v_pos+vec2(0,-epsilon.y));float c=getElevation(v_pos+vec2(epsilon.x,-epsilon.y));float d=getElevation(v_pos+vec2(-epsilon.x,0));float e=getElevation(v_pos+vec2(epsilon.x,0));float f=getElevation(v_pos+vec2(-epsilon.x,epsilon.y));float g=getElevation(v_pos+vec2(0,epsilon.y));float h=getElevation(v_pos+vec2(epsilon.x,epsilon.y));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(\n(c+e+e+h)-(a+d+d+f),(f+g+g+h)-(a+b+b+c)\n)/pow(2.0,exaggeration+(19.2562-u_zoom));glFragColor=clamp(vec4(\nderiv.x/2.0+0.5,deriv.y/2.0+0.5,1.0,1.0),0.0,1.0);}","uniform mat4 u_matrix;uniform vec2 u_dimension;in ivec2 a_pos;in uvec2 a_texture_pos;out 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=(vec2(a_texture_pos)/8192.0)*scale+epsilon;}"),hillshade:pu('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_lighting.glsl"\nuniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_latrange;uniform vec2 u_light;uniform vec4 u_shadow;uniform vec4 u_highlight;uniform vec4 u_accent;uniform float u_emissive_strength;void main() {vec4 pixel=texture(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);glFragColor=accent_color*(1.0-shade_color.a)+shade_color;\n#ifdef LIGHTING_3D_MODE\nglFragColor=apply_lighting_with_emission_ground(glFragColor,u_emissive_strength);\n#endif\n#ifdef FOG\nglFragColor=fog_dither(fog_apply_premultiplied(glFragColor,v_fog_pos));\n#endif\nstoreEmissiveColor(glFragColor,u_emissive_strength);\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}','#include "_prelude_fog.vertex.glsl"\nuniform mat4 u_matrix;in ivec2 a_pos;in uvec2 a_texture_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos=bottom_left_to_native_uv(vec2(a_texture_pos)/8192.0);\n#ifdef FOG\nv_fog_pos=fog_position(vec2(a_pos));\n#endif\n}'),line:pu('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_lighting.glsl"\n#include "_prelude_shadow.fragment.glsl"\n#include "_prelude_indicator_cutout.fragment.glsl"\n#include "_prelude_feature_cutout.fragment.glsl"\nuniform lowp float u_device_pixel_ratio;uniform highp float u_width_scale;uniform float u_alpha_discard_threshold;uniform lowp float u_opacity_multiplier;\n#ifdef ELEVATED_ROADS\nuniform bool u_clip_to_tile_borders;uniform vec4 u_child_quadrants;\n#endif\nin vec4 v_width2_dilute;in vec2 v_normal;in float v_gamma_scale;in highp vec2 v_tile_pos;\n#ifdef LINE_ROUND_JOIN_CLIP_BORDER_OVERLAP\nin highp vec4 v_round_join_conflict_offset;in highp vec4 v_round_join_conflict_dir;in mediump vec2 v_round_join_conflict_test;\n#endif\n#ifdef ELEVATED_ROADS\nin highp float v_road_z_offset;\n#endif\n#ifdef VARIABLE_LINE_WIDTH\nin float stub_side;in highp vec2 v_distance;uniform highp float u_width_addition;\n#endif\nuniform bool u_has_dash;uniform bool u_has_border;uniform sampler2D u_dash_image;uniform highp float u_floor_width_scale;in highp vec2 v_tex;\n#ifdef DEBUG_ELEVATION_ID\nin vec3 v_elevation_id_col;\n#endif\n#if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_BORDER_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET)\nin highp vec3 v_uv;\n#endif\n#ifdef RENDER_LINE_GRADIENT\nuniform sampler2D u_gradient_image;\n#endif\n#ifdef RENDER_LINE_BORDER_GRADIENT\nuniform sampler2D u_border_gradient_image;\n#endif\n#ifdef RENDER_LINE_TRIM_OFFSET\nuniform highp vec2 u_trim_offset;uniform highp vec2 u_trim_fade_range;uniform highp vec2 u_trim_gradient_mix_range;uniform lowp vec4 u_trim_color;\n#endif\n#ifdef RENDER_SHADOWS\nuniform bool u_emissive_in_shadows;uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth;\n#endif\nfloat luminance(vec3 c) {return (c.r+c.r+c.b+c.g+c.g+c.g)*0.1667;}in highp vec4 v_line_color;in lowp vec4 v_border_color;in lowp float v_opacity;in lowp float v_blur;in lowp float v_floorwidth;in lowp float v_border_width;in lowp float v_emissive_strength;in highp vec2 v_dash;\n#ifdef LINE_ROUND_JOIN_CLIP_BORDER_OVERLAP\nconst highp float ROUND_JOIN_NO_CONFLICT=32768.0;highp float roundJoinConflictDistance(highp vec2 conflictOffset,highp vec2 conflictDir,mediump float test) {if (test <=0.0) {return ROUND_JOIN_NO_CONFLICT;}highp float dirLenSq=max(dot(conflictDir,conflictDir),1e-6);highp float t=clamp(dot(conflictOffset,conflictDir)/dirLenSq,0.0,1.0);return length(conflictOffset-t*conflictDir);}float insideRoundJoinTestArea(highp float dist,vec2 testBounds,float pxStep) {float inside=1.0-smoothstep(testBounds.y-pxStep,testBounds.y+pxStep,dist);float pastGap=testBounds.x > 0.0 ? smoothstep(testBounds.x-pxStep,testBounds.x+pxStep,dist) : 1.0;return inside*pastGap;}float insideRoundJoinConflictBody(highp float dist,vec3 testBounds,float pxStep) {vec2 body=vec2(testBounds.x,testBounds.y-pxStep);return insideRoundJoinTestArea(dist,body,pxStep);}float insideRoundJoinConflictFill(highp float dist,vec3 testBounds,float pxStep) {float gap=testBounds.x;float outer=testBounds.y;float border=testBounds.z;vec2 fill=vec2(gap+(gap > 0.0 ? border : 0.0),max(outer-border,0.0));return insideRoundJoinTestArea(dist,fill,pxStep);}\n#endif\nfloat linearstep(float edge0,float edge1,float x) {return clamp((x-edge0)/(edge1-edge0),0.0,1.0);}void main() {highp vec4 color=vec4(v_line_color.rgb*v_line_color.a,v_line_color.a);float floorwidth=v_floorwidth;float blur=v_blur;float opacity=v_opacity;float border_width=v_border_width;vec4 border_color=vec4(v_border_color.rgb*v_border_color.a,v_border_color.a);float emissive_strength=v_emissive_strength;float dist=length(v_normal)*v_width2_dilute.x;float ANTIALIASING=1.0/u_device_pixel_ratio/2.0;\n#ifndef VARIABLE_LINE_WIDTH\nif (u_has_border) {ANTIALIASING*=8.0;}\n#endif\n#ifdef VARIABLE_LINE_WIDTH\nfloat opposite_blur=border_width > 0.0 ? abs(u_width_addition) : 0.0;blur=mix(blur,opposite_blur,stub_side);\n#endif\nfloat diluted_opacity=opacity*v_width2_dilute.z;float blur2=(u_width_scale*blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha;\n#ifdef VARIABLE_LINE_WIDTH\nfloat centre_distance=length(v_distance);float edge=mix(v_width2_dilute.y,v_width2_dilute.x,0.5+0.5*v_distance.y/max(centre_distance,1e-4));float inv_radius=1.0/max(length(vec4(dFdx(v_distance),dFdy(v_distance))),1e-4);vec2 edges=clamp((vec2(edge,-edge)-centre_distance)*inv_radius,-1.0,1.0);vec2 window=edges*(1.0-0.5*abs(edges));float blur_fade=clamp(edge*(1.0-centre_distance/(edge+ANTIALIASING))/blur2,0.0,1.0);alpha=mix(window.x-window.y,blur_fade,smoothstep(1.0,2.0,u_width_scale*blur*inv_radius));\n#else\nalpha=clamp(min(dist-(v_width2_dilute.y-blur2),v_width2_dilute.x-dist)/blur2,0.0,1.0);if (!u_has_border) {float half_band=0.5*(v_width2_dilute.x-v_width2_dilute.y);if (u_has_dash && blur < 0.01 && half_band >=ANTIALIASING) {float edge_hi=v_width2_dilute.x-ANTIALIASING;float edge_lo=v_width2_dilute.y > 0.0 ? v_width2_dilute.y-ANTIALIASING :-edge_hi;float px=max(blur2,1e-6);float true_px=min(length(vec2(dFdx(v_normal.y),dFdy(v_normal.y)))*v_width2_dilute.x,4.0*px);float t=clamp(true_px/px-1.0,0.0,1.0);float h=max(blur2,true_px)*mix(0.5,1.5,t);alpha=clamp(smoothstep(-h,h,edge_hi-dist)-smoothstep(-h,h,edge_lo-dist),0.0,1.0);}}\n#endif\nfloat pxStep;float delta;float alpha2=1.0;\n#ifndef VARIABLE_LINE_WIDTH\nif (u_has_border) {pxStep=fwidth(dist);float out_edge=v_width2_dilute.x-dist;float in_edge=dist-(v_width2_dilute.y-2.0*ANTIALIASING);delta=v_width2_dilute.y > 0.0 ? min(in_edge,out_edge) : out_edge;float edge=ANTIALIASING;alpha=delta > 0.0 ? smoothstep(edge-pxStep,u_width_scale*blur+edge+pxStep,delta) : 0.0;float borderPx=border_width*u_width_scale;float edge2=borderPx+ANTIALIASING;alpha2=smoothstep(edge2-pxStep,edge2+pxStep,delta);\n#ifdef LINE_ROUND_JOIN_CLIP_BORDER_OVERLAP\nif (alpha > 0.0 && alpha2 < 1.0 &&\n(v_round_join_conflict_test.x > 0.0 || v_round_join_conflict_test.y > 0.0)) {highp float prevDist=roundJoinConflictDistance(v_round_join_conflict_offset.xy,v_round_join_conflict_dir.xy,v_round_join_conflict_test.x);highp float nextDist=roundJoinConflictDistance(v_round_join_conflict_offset.zw,v_round_join_conflict_dir.zw,v_round_join_conflict_test.y);vec3 testBounds=vec3(max(v_width2_dilute.y-ANTIALIASING,0.0),v_width2_dilute.x-ANTIALIASING,borderPx);float insideConflictFill=max(insideRoundJoinConflictFill(prevDist,testBounds,pxStep),insideRoundJoinConflictFill(nextDist,testBounds,pxStep));alpha2=max(alpha2,insideConflictFill);const float diluteEpsilon=0.004;if (u_alpha_discard_threshold !=0.0 && blur==0.0 && v_width2_dilute.z >=1.0-diluteEpsilon) {float insideConflictBody=max(insideRoundJoinConflictBody(prevDist,testBounds,pxStep),insideRoundJoinConflictBody(nextDist,testBounds,pxStep));alpha=max(alpha,delta >=edge ? insideConflictBody : 0.0);}}\n#endif\n}\n#endif\nif (u_has_dash) {highp float dash_len=v_dash.x;float sdfgamma=ANTIALIASING/float(dash_len);float scaled_floorwidth=(floorwidth*u_floor_width_scale);float periods_per_pixel=fwidth(v_tex.x);float dash_coverage=v_dash.y;float fade=linearstep(0.25,0.5,periods_per_pixel);float gamma=max(sdfgamma/scaled_floorwidth,0.5*periods_per_pixel);if (fade >=1.0) {alpha*=dash_coverage;} else if (periods_per_pixel < 0.1) {float sdfdist=texture(u_dash_image,v_tex).r;alpha*=linearstep(0.5-gamma,0.5+gamma,sdfdist);} else {float span=min(periods_per_pixel,1.0);float tap_offset=span*0.25;float sdf0=texture(u_dash_image,vec2(v_tex.x-tap_offset,v_tex.y)).r;float sdf1=texture(u_dash_image,vec2(v_tex.x+tap_offset,v_tex.y)).r;alpha*=mix(0.5*(\nlinearstep(0.5-gamma,0.5+gamma,sdf0)+linearstep(0.5-gamma,0.5+gamma,sdf1)\n),dash_coverage,fade);}}highp vec4 out_color;\n#ifdef RENDER_LINE_GRADIENT\nout_color=texture(u_gradient_image,v_uv.xy);\n#else\nout_color=color;\n#endif\nfloat trim_alpha=1.0;\n#ifdef RENDER_LINE_TRIM_OFFSET\nhighp float trim_start=u_trim_offset[0];highp float trim_end=u_trim_offset[1];highp float line_progress=v_uv[2];if (trim_end > trim_start) {highp float start_transition=max(0.0,min(1.0,(line_progress-trim_start)/max(u_trim_fade_range[0],1.0e-9)));highp float end_transition=max(0.0,min(1.0,(trim_end-line_progress)/max(u_trim_fade_range[1],1.0e-9)));highp float transition_factor=min(start_transition,end_transition);highp float gradient_trim_color_mix_factor=0.0;\n#ifdef RENDER_LINE_GRADIENT\ngradient_trim_color_mix_factor=smoothstep(u_trim_gradient_mix_range.x,u_trim_gradient_mix_range.y,line_progress);\n#endif\nhighp vec4 trim_color=mix(u_trim_color,out_color,gradient_trim_color_mix_factor);out_color=mix(u_trim_gradient_mix_range.x < 1.0 ? color : out_color,trim_color,transition_factor);trim_alpha=1.0-transition_factor;}\n#endif\nif (u_alpha_discard_threshold !=0.0) {if (alpha < u_alpha_discard_threshold) {discard;}}\n#ifdef VARIABLE_LINE_WIDTH\nif (alpha <=0.0) {discard;}\n#endif\n#ifndef VARIABLE_LINE_WIDTH\nif (u_has_border && alpha2 < 1.) {\n#ifdef RENDER_LINE_BORDER_GRADIENT\nvec4 border_gradient_color=texture(u_border_gradient_image,v_uv.xy);out_color=mix(border_gradient_color*trim_alpha,out_color,alpha2);\n#else\nif (border_color.a==0.0) {\n#ifndef RENDER_LINE_GRADIENT\nfloat Y=(out_color.a > 0.01) ? luminance(out_color.rgb/out_color.a) : 1.;float adjustment=(Y > 0.) ? 0.5/Y : 0.45;if (out_color.a > 0.25 && Y < 0.25) {vec3 borderColor=(Y > 0.) ? out_color.rgb : vec3(1,1,1)*out_color.a;out_color.rgb=out_color.rgb+borderColor*(adjustment*(1.0-alpha2));} else {out_color.rgb*=(0.6+0.4*alpha2);}\n#else\nout_color.rgb*=(0.6+0.4*alpha2);\n#endif\n} else {out_color=mix(border_color*trim_alpha,out_color,alpha2);}\n#endif\nout_color*=v_width2_dilute.w;}\n#endif\nvec2 cutout_factors=vec2(0.0);\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(out_color,emissive_strength);\n#ifdef RENDER_SHADOWS\nfloat light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y);light=u_emissive_in_shadows ? mix(light,1.0,emissive_strength) : light;\n#ifdef ELEVATED_ROADS\nout_color.rgb*=mix(v_road_z_offset !=0.0 ? u_ground_shadow_factor : vec3(1.0),vec3(1.0),light);\n#else\nout_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light);\n#endif\n#endif\n#endif\n#ifdef FOG\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\n#endif\nout_color*=(alpha*diluted_opacity*u_opacity_multiplier);\n#ifdef LINE_BLEND_ADDITIVE\n{float cov=alpha*diluted_opacity;glFragColor=vec4(cov > 0.0 ? out_color.rgb/cov : vec3(0.0),cov);}\n#else\n#ifdef LINE_BLEND_MULTIPLY\nglFragColor=vec4(out_color.rgb+(1.0-out_color.a),1.0);\n#else\nglFragColor=out_color;\n#endif\n#endif\nstoreEmissiveColor(glFragColor,emissive_strength);\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\n#ifdef DEBUG_ELEVATION_ID\nglFragColor=vec4(v_elevation_id_col,1.0);\n#endif\n#ifdef ELEVATED_ROADS\nif (u_clip_to_tile_borders) {if (v_tile_pos.x > 1.0 || v_tile_pos.y > 1.0 || v_tile_pos.x < 0.0 || v_tile_pos.y < 0.0) {discard;}vec2 quadrant=step(vec2(0.5),v_tile_pos);vec2 row=mix(u_child_quadrants.xz,u_child_quadrants.yw,quadrant.x);if (mix(row.x,row.y,quadrant.y) > 0.5) {discard;}}\n#endif\nHANDLE_WIREFRAME_DEBUG;}','#include "_prelude_fog.vertex.glsl"\n#include "_prelude_shadow.vertex.glsl"\n#include "_prelude_terrain.vertex.glsl"\n#include "_prelude_ubo_properties.glsl"\n#define EXTRUDE_SCALE 0.015873016\nin ivec2 a_pos_normal;in uvec4 a_data;\n#if defined(ELEVATED) || defined(ELEVATED_ROADS) || defined(VARIABLE_LINE_WIDTH) || defined(VARIABLE_LINE_EMISSIVE_STRENGTH)\nin vec4 a_z_offset_width;\n#endif\n#ifdef DEBUG_ELEVATION_ID\nin vec3 a_elevation_id_col;\n#endif\n#ifdef DEBUG_ELEVATION_ID\nout vec3 v_elevation_id_col;\n#endif\n#ifdef ELEVATION_GROUND_SCALE\nin float a_elevation_ground_scale;\n#endif\n#ifdef LINE_ROUND_JOIN_CLIP_BORDER_OVERLAP\nin highp ivec4 a_round_join_conflict_segments;\n#endif\n#if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_BORDER_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET)\nin highp vec3 a_packed;\n#endif\nuniform bool u_has_dash;uniform bool u_has_border;in float a_linesofar;uniform mat4 u_matrix;uniform mat2 u_pixels_to_tile_units;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;uniform float u_width_scale;uniform float u_z_offset;uniform highp float u_road_view_depth_bias;\n#ifdef ELEVATED\nuniform lowp float u_zbias_factor;uniform lowp float u_tile_to_meter;float sample_elevation(vec2 apos) {\n#ifdef ELEVATION_REFERENCE_SEA\nreturn 0.0;\n#else\nreturn elevation(apos);\n#endif\n}\n#endif\nout vec2 v_normal;out vec4 v_width2_dilute;out float v_gamma_scale;out highp vec2 v_tile_pos;\n#ifdef LINE_ROUND_JOIN_CLIP_BORDER_OVERLAP\nout highp vec4 v_round_join_conflict_offset;out highp vec4 v_round_join_conflict_dir;out mediump vec2 v_round_join_conflict_test;\n#endif\n#ifdef ELEVATED_ROADS\nout highp float v_road_z_offset;\n#endif\n#ifdef VARIABLE_LINE_WIDTH\nout float stub_side;out highp vec2 v_distance;uniform float u_width_addition;\n#endif\nuniform highp float u_floor_width_scale;uniform vec2 u_texsize;uniform float u_tile_units_to_pixels;out highp vec2 v_tex;\n#if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_BORDER_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET)\nout highp vec3 v_uv;\n#endif\n#if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_BORDER_GRADIENT)\nuniform float u_image_height;\n#endif\n#ifdef RENDER_SHADOWS\nuniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth;\n#endif\n#define LPP_HEADER_SIZE_VEC4 5u\nstruct LinePaintProperties {vec4 color;vec4 border_color;float opacity;float blur;float width;float gap_width;float offset;float floorwidth;float border_width;float emissive_strength;vec4 dash;};uniform highp vec4 u_lpp_color;uniform lowp vec4 u_lpp_border_color;uniform lowp float u_lpp_opacity;uniform lowp float u_lpp_blur;uniform mediump float u_lpp_width;uniform mediump float u_lpp_gap_width;uniform lowp float u_lpp_offset;uniform lowp float u_lpp_floorwidth;uniform lowp float u_lpp_border_width;uniform lowp float u_lpp_emissive_strength;uniform highp vec4 u_lpp_dash;uniform highp float u_lpp_zoom_fraction;in float a_feature_index;layout(std140) uniform LinePaintPropertiesHeaderUniform {uvec4 header[LPP_HEADER_SIZE_VEC4];} u_lpp_header;layout(std140) uniform LinePaintPropertiesUniform {vec4 properties[MAX_UBO_SIZE_VEC4];} u_lpp_properties;out highp vec4 v_line_color;out lowp vec4 v_border_color;out lowp float v_opacity;out lowp float v_blur;out lowp float v_floorwidth;out lowp float v_border_width;out lowp float v_emissive_strength;out highp vec2 v_dash;vec4 readColor(uint base,bool isDataDriven,uint offsetVec4,vec2 headerZoom,vec4 fallbackValue) {if (!isDataDriven) return fallbackValue;vec4 value=u_lpp_properties.properties[base+offsetVec4];return unpack_mix_color(value,zoomFactor(headerZoom.x,headerZoom.y,u_lpp_zoom_fraction));}float readFloat(uint base,bool isDataDriven,uint offsetVec4,float fallbackValue) {if (!isDataDriven) return fallbackValue;vec4 slot=u_lpp_properties.properties[base+offsetVec4];return unpack_mix_vec2(slot.xy,zoomFactor(slot.z,slot.w,u_lpp_zoom_fraction));}highp vec4 readRaw(uint base,bool isDataDriven,uint offsetVec4,highp vec4 fallbackValue) {if (!isDataDriven) return fallbackValue;return u_lpp_properties.properties[base+offsetVec4];}LinePaintProperties readLinePaintProperties() {uint dataDrivenMask=u_lpp_header.header[0][0];uint blockSizeVec4 =u_lpp_header.header[0][2];vec2 colorHeaderZoom =uintBitsToFloat(u_lpp_header.header[4].xy);vec2 borderHeaderZoom=uintBitsToFloat(u_lpp_header.header[4].zw);uint base=uint(a_feature_index)*blockSizeVec4;LinePaintProperties props;props.color =readColor(base,(dataDrivenMask & (1u << 0u)) !=0u,u_lpp_header.header[0][3],colorHeaderZoom,u_lpp_color);props.border_color =readColor(base,(dataDrivenMask & (1u << 1u)) !=0u,u_lpp_header.header[1][0],borderHeaderZoom,u_lpp_border_color);props.opacity =readFloat(base,(dataDrivenMask & (1u << 2u)) !=0u,u_lpp_header.header[1][1],u_lpp_opacity);props.blur =readFloat(base,(dataDrivenMask & (1u << 3u)) !=0u,u_lpp_header.header[1][2],u_lpp_blur);props.width =readFloat(base,(dataDrivenMask & (1u << 4u)) !=0u,u_lpp_header.header[1][3],u_lpp_width);props.gap_width =readFloat(base,(dataDrivenMask & (1u << 5u)) !=0u,u_lpp_header.header[2][0],u_lpp_gap_width);props.offset =readFloat(base,(dataDrivenMask & (1u << 6u)) !=0u,u_lpp_header.header[2][1],u_lpp_offset);props.floorwidth =readFloat(base,(dataDrivenMask & (1u << 7u)) !=0u,u_lpp_header.header[2][2],u_lpp_floorwidth);props.border_width =readFloat(base,(dataDrivenMask & (1u << 8u)) !=0u,u_lpp_header.header[2][3],u_lpp_border_width);props.emissive_strength=readFloat(base,(dataDrivenMask & (1u << 9u)) !=0u,u_lpp_header.header[3][0],u_lpp_emissive_strength);props.dash =readRaw(base,(dataDrivenMask & (1u << 10u)) !=0u,u_lpp_header.header[3][1],u_lpp_dash);return props;}\n#ifdef LINE_ROUND_JOIN_CLIP_BORDER_OVERLAP\nhighp vec3 unpackRoundJoinTestCoordinate(highp int packedCoord) {highp int x=(((packedCoord & 0xfffe) ^ 0x8000)-0x8000) >> 1;return vec3(float(x),float(packedCoord >> 16),float(packedCoord & 1));}\n#endif\nvoid main() {LinePaintProperties paint_properties=readLinePaintProperties();v_line_color=paint_properties.color;float floorwidth=paint_properties.floorwidth;float blur=paint_properties.blur;float opacity=paint_properties.opacity;float gapwidth=paint_properties.gap_width;float offset=paint_properties.offset;float width=paint_properties.width;float border_width=paint_properties.border_width;vec4 border_color=paint_properties.border_color;float emissive_strength=paint_properties.emissive_strength;\n#ifdef VARIABLE_LINE_EMISSIVE_STRENGTH\nemissive_strength=a_z_offset_width.w;\n#endif\nv_border_color=border_color;v_opacity=opacity;v_blur=blur;v_floorwidth=floorwidth;v_border_width=border_width;v_emissive_strength=emissive_strength;float a_z_offset=u_z_offset;\n#if defined(ELEVATED) || defined(ELEVATED_ROADS)\na_z_offset+=a_z_offset_width.x;\n#endif\n#ifdef DEBUG_ELEVATION_ID\nv_elevation_id_col=a_elevation_id_col;\n#endif\nhighp float line_progress=0.0;\n#if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_BORDER_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET)\nline_progress=a_packed[2];\n#endif\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;\n#ifndef VARIABLE_LINE_WIDTH\nif (u_has_border) {ANTIALIASING*=8.0;}\n#endif\nvec2 a_extrude=vec2(a_data.xy)-128.0;float a_direction=float(a_data.z & 3u)-1.0;vec2 pos_normal=vec2(a_pos_normal);vec2 pos=floor(pos_normal*0.5);mediump vec2 normal=pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;offset=-1.0*offset*u_width_scale;bool left=normal.y==1.0;gapwidth=gapwidth/2.0;float halfwidth;float dilute_scale=1.0;float dilute_border_scale=1.0;vec2 side_widths=vec2(0.0);\n#ifdef VARIABLE_LINE_WIDTH\nfloat left_width=a_z_offset_width.y;float right_width=a_z_offset_width.z;bool zero_right_width=right_width==0.0;side_widths=u_width_scale*(zero_right_width ? vec2(left_width+u_width_addition) : vec2(left_width,right_width)+0.5*u_width_addition);halfwidth=left ? side_widths.x : (zero_right_width ? 0.0 : side_widths.y);offset=border_width > 0.0 ? (left_width+right_width+u_width_addition+border_width*0.5)*u_width_scale : offset;halfwidth=border_width > 0.0 ? border_width*u_width_scale*0.5 : halfwidth;side_widths=border_width > 0.0 ? vec2(halfwidth) : side_widths;stub_side=zero_right_width ?-normal.y : 0.0;ANTIALIASING=!left && zero_right_width ? 0.0 : ANTIALIASING;\n#else\nhalfwidth=(u_width_scale*width)/2.0;\n#endif\nfloat inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth > 0.0 ? ANTIALIASING : 0.0);\n#ifdef VARIABLE_LINE_WIDTH\nv_distance=v_normal*outset;\n#endif\nmediump vec2 dist=outset*a_extrude*EXTRUDE_SCALE;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*EXTRUDE_SCALE*normal.y*mat2(t,-u,u,t);float hidden=float(opacity==0.0);vec2 extrude=dist*u_pixels_to_tile_units;vec4 projected_extrude=u_matrix*vec4(extrude,0.0,0.0);vec2 projected_extrude_xy=projected_extrude.xy;\n#ifdef ELEVATED_ROADS\nv_road_z_offset=a_z_offset;v_tile_pos=pos+offset2*u_pixels_to_tile_units;gl_Position=u_matrix*vec4(v_tile_pos,a_z_offset,1.0);\n#else\n#ifdef ELEVATED\nvec2 offsetTile=offset2*u_pixels_to_tile_units;vec2 offset_pos=pos+offsetTile;float ele=0.0;float scaled_z_offset=a_z_offset;\n#ifdef ELEVATION_GROUND_SCALE\nscaled_z_offset=a_z_offset*mix(1.0,u_exaggeration,a_elevation_ground_scale);\n#endif\n#ifdef CROSS_SLOPE_VERTICAL\nfloat top=pos_normal.y-2.0*floor(pos_normal.y*0.5);float line_height=2.0*u_tile_to_meter*outset*top*u_pixels_to_tile_units[1][1]+scaled_z_offset;ele=sample_elevation(offset_pos)+line_height;projected_extrude=vec4(0);\n#else\n#ifdef CROSS_SLOPE_HORIZONTAL\nfloat ele0=sample_elevation(offset_pos);float ele1=max(sample_elevation(offset_pos+extrude),sample_elevation(offset_pos+extrude/2.0));float ele2=max(sample_elevation(offset_pos-extrude),sample_elevation(offset_pos-extrude/2.0));float ele_max=max(ele0,max(ele1,ele2));ele=ele_max+scaled_z_offset;\n#else\nfloat ele0=sample_elevation(offset_pos);float ele1=max(sample_elevation(offset_pos+extrude),sample_elevation(offset_pos+extrude/2.0));float ele2=max(sample_elevation(offset_pos-extrude),sample_elevation(offset_pos-extrude/2.0));float ele_max=max(ele0,0.5*(ele1+ele2));ele=ele_max-ele0+ele1+scaled_z_offset;\n#endif\n#endif\nv_tile_pos=offset_pos;gl_Position=u_matrix*vec4(v_tile_pos,ele,1.0)+projected_extrude;float z=clamp(gl_Position.z/gl_Position.w,0.5,1.0);float zbias=max(0.00005,(pow(z,0.8)-z)*u_zbias_factor*u_exaggeration);gl_Position.z-=(gl_Position.w*zbias);gl_Position=mix(gl_Position,AWAY,hidden);\n#else\nv_tile_pos=pos+offset2*u_pixels_to_tile_units;gl_Position=u_matrix*vec4(v_tile_pos,0.0,1.0);\n#endif\n#endif\n#ifndef ELEVATED\n#ifndef VARIABLE_LINE_WIDTH\n#ifndef RENDER_TO_TEXTURE\nfloat base_w=gl_Position.w;vec2 screen_width=abs(projected_extrude.xy/base_w*u_units_to_pixels);float max_extrude_component=max(screen_width.x,screen_width.y);if (width >=1.0 && base_w > 0.0 && max_extrude_component > 0.0001) {float min_pixel=1.05;if (max_extrude_component < min_pixel) {vec2 abs_pos=abs(gl_Position.xy);float is_out=max(abs_pos.x,abs_pos.y)/base_w;dilute_scale=mix(max_extrude_component/min_pixel,1.0,smoothstep(2.5,4.5,is_out));projected_extrude.xy/=dilute_scale;projected_extrude_xy=projected_extrude.xy;}else if (gapwidth > 0.0) {float visible_ratio=(halfwidth+ANTIALIASING)/outset;vec2 visible_screen_width=screen_width*visible_ratio;float max_visible_component=max(visible_screen_width.x,visible_screen_width.y);dilute_scale=min(1.0,max_visible_component/min_pixel);if (!u_has_border) {if (u_has_dash && blur < 0.01 && halfwidth >=ANTIALIASING) {dilute_scale=1.0;}}}else\n{if (u_has_border) {float border_ratio=(border_width*u_width_scale+ANTIALIASING)/outset;screen_width*=border_ratio;float max_border_component=max(screen_width.x,screen_width.y);dilute_border_scale=min(1.0,max_border_component/min_pixel);}}}\n#endif\n#endif\n#ifdef VARIABLE_LINE_WIDTH\n#ifndef RENDER_TO_TEXTURE\nvec2 ndc=gl_Position.xy/gl_Position.w;vec4 projected_tangent=u_matrix*vec4(extrude.y,-extrude.x,0.0,0.0);vec2 screen_extrude=(projected_extrude.xy-ndc*projected_extrude.w)*u_units_to_pixels;vec2 screen_tangent=(projected_tangent.xy-ndc*projected_tangent.w)*u_units_to_pixels;float thickness=abs(screen_extrude.x*screen_tangent.y-screen_extrude.y*screen_tangent.x)/max(length(screen_tangent),1e-6);float thickness_px=max(thickness,0.2*length(screen_extrude))/gl_Position.w*u_device_pixel_ratio;float headroom_scale=gl_Position.w > 0.0 ? 1.0+(1.0-smoothstep(2.0,4.0,thickness_px))/max(thickness_px,0.0001) : 1.0;projected_extrude*=headroom_scale;extrude*=headroom_scale;v_distance*=headroom_scale;\n#endif\n#endif\nv_tile_pos=(v_tile_pos+extrude)/EXTENT;\n#ifdef ELEVATED_ROADS\ngl_Position=gl_Position+projected_extrude;\n#ifdef VARIABLE_LINE_WIDTH\n#ifndef ELEVATED\ngl_Position.z-=u_road_view_depth_bias*smoothstep(-0.5,0.0,a_z_offset);\n#endif\n#endif\n#else\ngl_Position=mix(gl_Position+projected_extrude,AWAY,hidden);\n#endif\n#endif\n#ifdef ELEVATED_ROADS\n#ifdef RENDER_SHADOWS\nvec3 shd_pos=vec3(pos+(offset2+dist)*u_pixels_to_tile_units,a_z_offset);vec3 shd_pos0=shd_pos;vec3 shd_pos1=shd_pos;\n#ifdef NORMAL_OFFSET\nvec3 shd_pos_offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=shd_pos_offset*shadow_normal_offset_multiplier0();shd_pos1+=shd_pos_offset*shadow_normal_offset_multiplier1();\n#endif\nv_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w;\n#endif\n#endif\n#ifndef RENDER_TO_TEXTURE\nfloat epsilon=0.0001;float extrude_length_without_perspective=max(length(dist),epsilon);float extrude_length_with_perspective=max(length(projected_extrude_xy/gl_Position.w*u_units_to_pixels),epsilon);v_gamma_scale=mix(extrude_length_without_perspective/extrude_length_with_perspective,1.0,step(0.01,blur));\n#else\nv_gamma_scale=1.0;\n#endif\n#if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_BORDER_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET)\nhighp float a_uv_x=a_packed[0];float a_split_index=a_packed[1];\n#if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_BORDER_GRADIENT)\nhighp float texel_height=1.0/u_image_height;highp float half_texel_height=0.5*texel_height;v_uv=vec3(a_uv_x,a_split_index*texel_height-half_texel_height,line_progress);\n#else\nv_uv=vec3(a_uv_x,0.0,line_progress);\n#endif\n#endif\nif (u_has_dash) {highp vec4 dashf=paint_properties.dash;highp float dash_w=dashf.w;highp float totalLength=dashf.z+dash_w/65535.0;float scale=totalLength==0.0 ? 0.0 : u_tile_units_to_pixels/totalLength;highp uint dash_bits=uint(dashf.y+0.5);float dash_half_height=float(dash_bits & 15u);float dash_coverage=float(dash_bits >> 4u)/4095.0;v_tex=vec2(a_linesofar*scale/(floorwidth*u_floor_width_scale),(-normal.y*dash_half_height+dashf.x+0.5)/u_texsize.y);v_dash=vec2(totalLength,dash_coverage);} else {v_tex=vec2(0.0);v_dash=vec2(0.0);}v_width2_dilute=vec4(outset,inset,dilute_scale,dilute_border_scale);\n#ifdef VARIABLE_LINE_WIDTH\nv_width2_dilute.xy=side_widths;\n#endif\n#ifdef LINE_ROUND_JOIN_CLIP_BORDER_OVERLAP\nhighp float tileToPixels=1.0/u_pixels_to_tile_units[0][0];highp vec2 testPos=pos+extrude/dilute_scale;highp vec3 prevA=unpackRoundJoinTestCoordinate(a_round_join_conflict_segments.x);highp vec3 prevB=unpackRoundJoinTestCoordinate(a_round_join_conflict_segments.y);highp vec3 nextA=unpackRoundJoinTestCoordinate(a_round_join_conflict_segments.z);highp vec3 nextB=unpackRoundJoinTestCoordinate(a_round_join_conflict_segments.w);v_round_join_conflict_offset=vec4(testPos-prevA.xy,testPos-nextA.xy)*tileToPixels;v_round_join_conflict_dir=vec4(prevB.xy-prevA.xy,nextB.xy-nextA.xy)*tileToPixels;v_round_join_conflict_test=vec2(prevA.z,nextA.z);\n#endif\n#ifdef FOG\nv_fog_pos=fog_position(pos);\n#endif\n}'),linePattern:pu('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_lighting.glsl"\n#include "_prelude_shadow.fragment.glsl"\n#include "_prelude_indicator_cutout.fragment.glsl"\nuniform highp float u_device_pixel_ratio;uniform highp float u_width_scale;uniform highp float u_alpha_discard_threshold;uniform lowp float u_opacity_multiplier;uniform highp vec2 u_texsize;uniform highp float u_tile_units_to_pixels;uniform highp vec2 u_trim_offset;uniform highp vec2 u_trim_fade_range;uniform lowp vec4 u_trim_color;uniform sampler2D u_image;\n#ifdef APPLY_LUT_ON_GPU\nuniform highp sampler3D u_lutTexture;\n#endif\n#ifdef LINE_PATTERN_TRANSITION\nuniform float u_pattern_transition;\n#endif\nin vec2 v_normal;in vec2 v_width2;in highp float v_linesofar;in float v_gamma_scale;in float v_width;\n#ifdef RENDER_LINE_TRIM_OFFSET\nin highp vec3 v_uv;\n#endif\n#ifdef ELEVATED_ROADS\nin highp float v_road_z_offset;\n#endif\n#ifdef LINE_JOIN_NONE\nin vec2 v_pattern_data;\n#endif\n#ifdef RENDER_SHADOWS\nuniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth;\n#endif\n#pragma mapbox: define mediump uvec4 pattern\n#ifdef LINE_PATTERN_TRANSITION\n#pragma mapbox: define mediump uvec4 pattern_b\n#endif\n#pragma mapbox: define mediump float pixel_ratio\n#pragma mapbox: define mediump float blur\n#pragma mapbox: define mediump float opacity\n#pragma mapbox: define lowp float emissive_strength\nvoid main() {\n#pragma mapbox: initialize mediump uvec4 pattern\n#ifdef LINE_PATTERN_TRANSITION\n#pragma mapbox: initialize mediump uvec4 pattern_b\n#endif\n#pragma mapbox: initialize mediump float pixel_ratio\n#pragma mapbox: initialize mediump float blur\n#pragma mapbox: initialize mediump float opacity\n#pragma mapbox: initialize lowp float emissive_strength\nvec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio;highp float pattern_size=display_size.x/u_tile_units_to_pixels;float aspect=display_size.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(u_width_scale*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);highp float pattern_x=v_linesofar/pattern_size*aspect;highp float x=mod(pattern_x,1.0);highp float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;highp vec2 pos=mix(pattern_tl*texel_size-texel_size,pattern_br*texel_size+texel_size,vec2(x,y));highp vec2 lod_pos=mix(pattern_tl*texel_size-texel_size,pattern_br*texel_size+texel_size,vec2(pattern_x,y));vec4 color=textureLodCustom(u_image,pos,lod_pos);\n#ifdef APPLY_LUT_ON_GPU\ncolor=applyLUT(u_lutTexture,color);\n#endif\n#ifdef LINE_PATTERN_TRANSITION\nvec2 pattern_b_tl=vec2(pattern_b.xy);vec2 pattern_b_br=vec2(pattern_b.zw);highp vec2 pos_b=mix(pattern_b_tl*texel_size-texel_size,pattern_b_br*texel_size+texel_size,vec2(x,y));vec4 color_b=textureLodCustom(u_image,pos_b,lod_pos);color=color*(1.0-u_pattern_transition)+color_b*u_pattern_transition;\n#endif\n#ifdef RENDER_LINE_TRIM_OFFSET\nhighp float trim_start=u_trim_offset[0];highp float trim_end=u_trim_offset[1];highp float line_progress=v_uv[2];if (trim_end > trim_start) {highp float start_transition=max(0.0,min(1.0,(line_progress-trim_start)/max(u_trim_fade_range[0],1.0e-9)));highp float end_transition=max(0.0,min(1.0,(trim_end-line_progress)/max(u_trim_fade_range[1],1.0e-9)));highp float transition_factor=min(start_transition,end_transition);color=mix(color,color.a*u_trim_color,transition_factor);}\n#endif\n#ifdef LINE_JOIN_NONE\nhighp float pattern_len=pattern_size/aspect;highp float segment_phase=pattern_len-mod(v_linesofar-v_pattern_data.x+pattern_len,pattern_len);highp float visible_start=segment_phase-step(pattern_len*0.5,segment_phase)*pattern_len;highp float visible_end=floor((v_pattern_data.y-segment_phase)/pattern_len)*pattern_len+segment_phase;visible_end+=step(pattern_len*0.5,v_pattern_data.y-visible_end)*pattern_len;if (v_pattern_data.x < visible_start || v_pattern_data.x >=visible_end) {color=vec4(0.0);}\n#endif\n#ifdef LIGHTING_3D_MODE\ncolor=apply_lighting_with_emission_ground(color,emissive_strength);\n#ifdef RENDER_SHADOWS\nfloat light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);\n#ifdef ELEVATED_ROADS\ncolor.rgb*=mix(v_road_z_offset !=0.0 ? u_ground_shadow_factor : vec3(1.0),vec3(1.0),light);\n#else\ncolor.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light);\n#endif\n#endif\n#endif\n#ifdef FOG\ncolor=fog_dither(fog_apply_premultiplied(color,v_fog_pos));\n#endif\ncolor*=(alpha*opacity*u_opacity_multiplier);if (u_alpha_discard_threshold !=0.0) {if (color.a < u_alpha_discard_threshold) {discard;}}glFragColor=color;storeEmissiveColor(glFragColor,emissive_strength);\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}','#include "_prelude_fog.vertex.glsl"\n#include "_prelude_shadow.vertex.glsl"\n#include "_prelude_terrain.vertex.glsl"\n#define scale 0.015873016\nin ivec2 a_pos_normal;in uvec4 a_data;\n#if defined(ELEVATED) || defined(ELEVATED_ROADS)\nin vec4 a_z_offset_width;\n#endif\n#ifdef ELEVATION_GROUND_SCALE\nin float a_elevation_ground_scale;\n#endif\n#ifdef RENDER_LINE_TRIM_OFFSET\nin highp vec3 a_packed;\n#endif\nin highp float a_linesofar;\n#ifdef LINE_JOIN_NONE\nin highp vec3 a_pattern_data;out vec2 v_pattern_data;\n#endif\nuniform mat4 u_matrix;uniform float u_tile_units_to_pixels;uniform vec2 u_units_to_pixels;uniform mat2 u_pixels_to_tile_units;uniform float u_device_pixel_ratio;uniform float u_width_scale;uniform float u_floor_width_scale;\n#ifdef ELEVATED\nuniform lowp float u_zbias_factor;uniform lowp float u_tile_to_meter;float sample_elevation(vec2 apos) {\n#ifdef ELEVATION_REFERENCE_SEA\nreturn 0.0;\n#else\nreturn elevation(apos);\n#endif\n}\n#endif\nout vec2 v_normal;out vec2 v_width2;out highp float v_linesofar;out float v_gamma_scale;out float v_width;\n#ifdef RENDER_LINE_TRIM_OFFSET\nout highp vec3 v_uv;\n#endif\n#ifdef ELEVATED_ROADS\nout highp float v_road_z_offset;\n#endif\n#ifdef RENDER_SHADOWS\nuniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth;\n#endif\n#pragma mapbox: define mediump float blur\n#pragma mapbox: define mediump float opacity\n#pragma mapbox: define mediump float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n#pragma mapbox: define mediump float floorwidth\n#pragma mapbox: define mediump uvec4 pattern\n#ifdef LINE_PATTERN_TRANSITION\n#pragma mapbox: define mediump uvec4 pattern_b\n#endif\n#pragma mapbox: define mediump float pixel_ratio\n#pragma mapbox: define lowp float emissive_strength\nvoid main() {\n#pragma mapbox: initialize mediump float blur\n#pragma mapbox: initialize mediump float opacity\n#pragma mapbox: initialize mediump float offset\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize mediump float floorwidth\n#pragma mapbox: initialize mediump uvec4 pattern\n#ifdef LINE_PATTERN_TRANSITION\n#pragma mapbox: initialize mediump uvec4 pattern_b\n#endif\n#pragma mapbox: initialize mediump float pixel_ratio\n#pragma mapbox: initialize lowp float emissive_strength\nfloat a_z_offset;\n#if defined(ELEVATED) || defined(ELEVATED_ROADS)\na_z_offset=a_z_offset_width.x;\n#endif\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=vec2(a_data.xy)-128.0;float a_direction=float(a_data.z & 3u)-1.0;vec2 pos_normal=vec2(a_pos_normal);vec2 pos=floor(pos_normal*0.5);vec2 normal=pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=(u_width_scale*width)/2.0;offset=-1.0*offset*u_width_scale;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);vec2 dist=outset*a_extrude*scale;float u=0.5*a_direction;float t=1.0-abs(u);vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float hidden=float(opacity==0.0);vec2 extrude=dist*u_pixels_to_tile_units;vec4 projected_extrude=u_matrix*vec4(extrude,0.0,0.0);vec2 projected_extrude_xy=projected_extrude.xy;\n#ifdef ELEVATED_ROADS\nv_road_z_offset=a_z_offset;gl_Position=u_matrix*vec4(pos+offset2*u_pixels_to_tile_units,a_z_offset,1.0)+projected_extrude;\n#else\n#ifdef ELEVATED\nvec2 offsetTile=offset2*u_pixels_to_tile_units;vec2 offset_pos=pos+offsetTile;float ele=0.0;float scaled_z_offset=a_z_offset;\n#ifdef ELEVATION_GROUND_SCALE\nscaled_z_offset=a_z_offset*mix(1.0,u_exaggeration,a_elevation_ground_scale);\n#endif\n#ifdef CROSS_SLOPE_VERTICAL\nfloat top=pos_normal.y-2.0*floor(pos_normal.y*0.5);float line_height=2.0*u_tile_to_meter*outset*top*u_pixels_to_tile_units[1][1]+scaled_z_offset;ele=sample_elevation(offset_pos)+line_height;projected_extrude=vec4(0);\n#else\n#ifdef CROSS_SLOPE_HORIZONTAL\nfloat ele0=sample_elevation(offset_pos);float ele1=max(sample_elevation(offset_pos+extrude),sample_elevation(offset_pos+extrude/2.0));float ele2=max(sample_elevation(offset_pos-extrude),sample_elevation(offset_pos-extrude/2.0));float ele_max=max(ele0,max(ele1,ele2));ele=ele_max+scaled_z_offset;\n#else\nfloat ele0=sample_elevation(offset_pos);float ele1=max(sample_elevation(offset_pos+extrude),sample_elevation(offset_pos+extrude/2.0));float ele2=max(sample_elevation(offset_pos-extrude),sample_elevation(offset_pos-extrude/2.0));float ele_max=max(ele0,0.5*(ele1+ele2));ele=ele_max-ele0+ele1+scaled_z_offset;\n#endif\n#endif\ngl_Position=u_matrix*vec4(offset_pos,ele,1.0)+projected_extrude;float z=clamp(gl_Position.z/gl_Position.w,0.5,1.0);float zbias=max(0.00005,(pow(z,0.8)-z)*u_zbias_factor*u_exaggeration);gl_Position.z-=(gl_Position.w*zbias);gl_Position=mix(gl_Position,AWAY,hidden);\n#else\ngl_Position=mix(u_matrix*vec4(pos+offset2*u_pixels_to_tile_units,0.0,1.0)+projected_extrude,AWAY,hidden);\n#endif\n#endif\n#ifdef ELEVATED_ROADS\n#ifdef RENDER_SHADOWS\nvec3 shd_pos=vec3(pos+(offset2+dist)*u_pixels_to_tile_units,a_z_offset);vec3 shd_pos0=shd_pos;vec3 shd_pos1=shd_pos;\n#ifdef NORMAL_OFFSET\nvec3 shd_pos_offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=shd_pos_offset*shadow_normal_offset_multiplier0();shd_pos1+=shd_pos_offset*shadow_normal_offset_multiplier1();\n#endif\nv_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w;\n#endif\n#endif\n#ifndef RENDER_TO_TEXTURE\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude_xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=mix(extrude_length_without_perspective/extrude_length_with_perspective,1.0,step(0.01,blur));\n#else\nv_gamma_scale=1.0;\n#endif\n#ifdef RENDER_LINE_TRIM_OFFSET\nhighp float a_uv_x=a_packed[0];highp float line_progress=a_packed[2];v_uv=vec3(a_uv_x,0.0,line_progress);\n#endif\nv_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=(floorwidth*u_floor_width_scale);\n#ifdef LINE_JOIN_NONE\nv_width=(floorwidth*u_floor_width_scale)+ANTIALIASING;mediump float pixels_to_tile_units=1.0/u_tile_units_to_pixels;mediump float pixel_ratio_inverse=1.0/pixel_ratio;mediump float aspect=v_width/(float(pattern.w-pattern.y)*pixel_ratio_inverse);highp float subt_multiple=float(pattern.z-pattern.x)*pixel_ratio_inverse*pixels_to_tile_units*aspect*32.0;highp float subt=floor(a_pattern_data.z/subt_multiple)*subt_multiple;float offset_sign=(fract(a_pattern_data.x)-0.5)*4.0;float line_progress_offset=offset_sign*v_width*0.5*pixels_to_tile_units;v_linesofar=(a_pattern_data.z-subt)+a_linesofar+line_progress_offset;v_pattern_data=vec2(a_pattern_data.x+line_progress_offset,a_pattern_data.y);\n#endif\n#ifdef FOG\nv_fog_pos=fog_position(pos);\n#endif\n}'),raster:pu('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_lighting.glsl"\n#include "_prelude_raster_array.glsl"\nuniform float u_fade_t;uniform float u_opacity;uniform highp float u_raster_elevation;uniform highp float u_zoom_transition;in vec2 v_pos0;in vec2 v_pos1;in float v_depth;\n#ifdef PROJECTION_GLOBE_VIEW\nin float v_split_fade;\n#endif\nuniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;uniform float u_emissive_strength;\n#ifndef RASTER_ARRAY\nuniform highp sampler2D u_image0;uniform sampler2D u_image1;\n#endif\n#ifdef RASTER_COLOR\nuniform sampler2D u_color_ramp;uniform highp vec4 u_colorization_mix;uniform highp float u_colorization_offset;uniform vec2 u_texture_res;uniform highp float u_color_ramp_size;\n#endif\nvoid main() {vec4 color0,color1,color;vec2 value;\n#ifdef RASTER_COLOR\n#ifdef RASTER_ARRAY\n#ifdef RASTER_ARRAY_LINEAR\nvalue=mix(\nraTexture2D_image0_linear(v_pos0,u_texture_res,u_colorization_mix,u_colorization_offset),raTexture2D_image1_linear(v_pos1,u_texture_res,u_colorization_mix,u_colorization_offset),u_fade_t\n);\n#else\nvalue=mix(\nraTexture2D_image0_nearest(v_pos0,u_texture_res,u_colorization_mix,u_colorization_offset),raTexture2D_image1_nearest(v_pos1,u_texture_res,u_colorization_mix,u_colorization_offset),u_fade_t\n);\n#endif\nif (value.y > 0.0) value.x/=value.y;\n#ifdef RASTER_COLOR_SCALE_LOG\nfloat N=u_color_ramp_size;float vNorm=max((value.x-0.5/N)*N/(N-1.0),0.0);vNorm=log(vNorm*(10.0-1.0)+1.0)/log(10.0);value.x=0.5/N+vNorm*(N-1.0)/N;\n#endif\n#else\ncolor=mix(texture(u_image0,v_pos0),texture(u_image1,v_pos1),u_fade_t);value=vec2(u_colorization_offset+dot(color.rgb,u_colorization_mix.rgb),color.a);\n#endif\ncolor=texture(u_color_ramp,vec2(value.x,0.5));if (color.a > 0.0) color.rgb/=color.a;color.a*=value.y;\n#else\ncolor0=texture(u_image0,v_pos0);color1=texture(u_image1,v_pos1);if (color0.a > 0.0) color0.rgb/=color0.a;if (color1.a > 0.0) color1.rgb/=color1.a;color=mix(color0,color1,u_fade_t);\n#endif\ncolor.a*=u_opacity;\n#ifdef GLOBE_POLES\ncolor.a*=1.0-smoothstep(0.0,0.05,u_zoom_transition);\n#endif\nvec3 rgb=color.rgb;rgb=vec3(\ndot(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);vec3 out_color=mix(u_high_vec,u_low_vec,rgb);\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(vec4(out_color,1.0),u_emissive_strength).rgb;\n#endif\n#ifdef FOG\nhighp float fog_limit_high_meters=1000000.0;highp float fog_limit_low_meters=600000.0;float fog_limit=1.0-smoothstep(fog_limit_low_meters,fog_limit_high_meters,u_raster_elevation);out_color=fog_dither(fog_apply(out_color,v_fog_pos,fog_limit));\n#endif\nglFragColor=vec4(out_color*color.a,color.a);\n#ifdef PROJECTION_GLOBE_VIEW\nglFragColor*=mix(1.0,1.0-smoothstep(0.0,0.05,u_zoom_transition),smoothstep(0.8,0.9,v_split_fade));\n#endif\n#ifdef RENDER_CUTOFF\nglFragColor=glFragColor*cutoff_opacity(u_cutoff_params,v_depth);\n#endif\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nstoreEmissiveColor(glFragColor,u_emissive_strength);HANDLE_WIREFRAME_DEBUG;}','#include "_prelude_fog.vertex.glsl"\n#include "_prelude_terrain.vertex.glsl"\nuniform mat4 u_matrix;uniform mat4 u_normalize_matrix;uniform mat4 u_globe_matrix;uniform mat4 u_merc_matrix;uniform mat3 u_grid_matrix;uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform vec2 u_perspective_transform;uniform vec2 u_texture_offset;uniform float u_raster_elevation;uniform float u_zoom_transition;uniform vec2 u_merc_center;\n#ifdef ELEVATED\nuniform lowp float u_zbias_factor;\n#endif\n#define GLOBE_UPSCALE GLOBE_RADIUS/6371008.8\n#ifdef GLOBE_POLES\nin vec3 a_globe_pos;in vec2 a_uv;\n#else\nin ivec2 a_pos;in uvec2 a_texture_pos;\n#endif\nout vec2 v_pos0;out vec2 v_pos1;out float v_depth;\n#ifdef PROJECTION_GLOBE_VIEW\nout float v_split_fade;\n#endif\nvoid main() {vec2 uv;\n#ifdef GLOBE_POLES\nvec3 globe_pos=a_globe_pos;uv=a_uv;float ele=u_raster_elevation;\n#ifdef ELEVATION_REFERENCE_GROUND\nele+=elevation(uv*EXTENT);\n#endif\nglobe_pos+=normalize(globe_pos)*ele*GLOBE_UPSCALE;gl_Position=u_matrix*u_globe_matrix*vec4(globe_pos,1.0);\n#ifdef FOG\nv_fog_pos=fog_position((u_normalize_matrix*vec4(a_globe_pos,1.0)).xyz);\n#endif\n#else\nvec4 world_pos;\n#ifdef PROJECTION_GLOBE_VIEW\nvec2 texture_pos=vec2(a_texture_pos);uv=texture_pos/8192.0;vec3 decomposed_pos_and_skirt=decomposeToPosAndSkirt(a_pos);vec3 latLng=u_grid_matrix*vec3(decomposed_pos_and_skirt.xy,1.0);float mercatorY=mercatorYfromLat(latLng[0]);float mercatorX=mercatorXfromLng(latLng[1]);float tiles=u_grid_matrix[0][2];if (tiles > 0.0) {float idx=u_grid_matrix[1][2];float idy=u_grid_matrix[2][2];float uvY=mercatorY*tiles-idy;float uvX=mercatorX*tiles-idx;uv=vec2(uvX,uvY);}float ele=u_raster_elevation;\n#ifdef ELEVATION_REFERENCE_GROUND\nele+=elevation(uv*EXTENT)-decomposed_pos_and_skirt.z;\n#endif\nvec4 merc_world_pos=vec4(0.0);v_split_fade=0.0;if (u_zoom_transition > 0.0) {vec2 merc_pos=vec2(mercatorX,mercatorY);merc_world_pos=vec4(merc_pos,ele,1.0);merc_world_pos.xy-=u_merc_center;merc_world_pos.x=wrap(merc_world_pos.x,-0.5,0.5);merc_world_pos=u_merc_matrix*merc_world_pos;float opposite_merc_center=mod(u_merc_center.x+0.5,1.0);float dist_from_poles=(abs(mercatorY-0.5)*2.0);float range=0.1;v_split_fade=abs(opposite_merc_center-mercatorX);v_split_fade=clamp(1.0-v_split_fade,0.0,1.0);v_split_fade=max(smoothstep(1.0-range,1.0,dist_from_poles),max(smoothstep(1.0-range,1.0,v_split_fade),smoothstep(1.0-range,1.0,1.0-v_split_fade)));}vec3 globe_pos=latLngToECEF(latLng.xy);globe_pos+=normalize(globe_pos)*ele*GLOBE_UPSCALE;vec4 globe_world_pos=u_globe_matrix*vec4(globe_pos,1.0);world_pos=vec4(mix(globe_world_pos.xyz,merc_world_pos.xyz,u_zoom_transition),1.0);\n#ifdef FOG\nv_fog_pos=fog_position((u_normalize_matrix*vec4(globe_pos,1.0)).xyz);\n#endif\n#else\nfloat ele=0.0;vec2 decodedPos=vec2(a_pos);\n#ifdef ELEVATION_REFERENCE_GROUND\nvec3 decomposedPosAndSkirt=decomposeToPosAndSkirt(a_pos);float skirt=decomposedPosAndSkirt.z;decodedPos=decomposedPosAndSkirt.xy;uv=decodedPos/8192.0;ele=elevation(decodedPos)-skirt;\n#else\nuv=vec2(a_texture_pos)/8192.0;\n#endif\nworld_pos=vec4(decodedPos,(u_raster_elevation+ele),1.0);\n#ifdef FOG\nv_fog_pos=fog_position(decodedPos);\n#endif\n#endif\nfloat w=1.0+dot(uv*EXTENT,u_perspective_transform);gl_Position=u_matrix*world_pos*w;\n#endif\nv_pos0=uv;v_pos1=(v_pos0*u_scale_parent)+u_tl_parent;v_pos0=u_texture_offset.x+u_texture_offset.y*v_pos0;v_pos1=u_texture_offset.x+u_texture_offset.y*v_pos1;\n#ifdef ELEVATED\nfloat z=clamp(gl_Position.z/gl_Position.w,0.5,1.0);float zbias=max(0.00005,(pow(z,0.8)-z)*u_zbias_factor);gl_Position.z-=(gl_Position.w*zbias);\n#endif\n#ifdef RENDER_CUTOFF\nv_depth=native_clip_z_to_cutoff_depth(gl_Position.z,gl_Position.w);\n#endif\n}'),symbol:pu('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_lighting.glsl"\n#include "_prelude_shadow.fragment.glsl"\n#include "_prelude_indicator_cutout.fragment.glsl"\n#include "_prelude_feature_cutout.fragment.glsl"\n#define SDF_PX 8.0\n#define SDF 1.0\n#define ICON 0.0\nuniform sampler2D u_texture;\n#ifdef RENDER_TEXT_AND_SYMBOL\nuniform sampler2D u_texture_icon;\n#endif\nuniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;uniform bool u_is_sdf;uniform lowp float u_scale_factor;uniform lowp float u_opacity_multiplier;\n#ifdef ICON_TRANSITION\nuniform float u_icon_transition;\n#endif\n#ifdef COLOR_ADJUSTMENT\nuniform mat4 u_color_adj_mat;\n#endif\n#ifdef RENDER_SHADOWS\nin highp float v_z_offset;\n#endif\nin vec2 v_tex_a;\n#ifdef ICON_TRANSITION\nin vec2 v_tex_b;\n#endif\nin float v_draw_halo;in vec3 v_gamma_scale_size_fade_opacity;\n#ifdef RENDER_TEXT_AND_SYMBOL\nin float is_sdf;in vec2 v_tex_a_icon;\n#endif\n#ifdef RENDER_SHADOWS\nuniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth;\n#endif\n#ifdef APPLY_LUT_ON_GPU\nuniform highp sampler3D u_lutTexture;\n#endif\nin lowp float v_opacity;in lowp vec4 v_fill_np_color;in lowp vec4 v_halo_np_color;in lowp float v_halo_width;in lowp float v_halo_blur;\n#ifdef LIGHTING_3D_MODE\nin lowp float v_emissive_strength;\n#endif\nvoid main() {lowp float opacity=v_opacity;lowp vec4 fill_color=vec4(0.0);lowp vec4 halo_color=vec4(0.0);lowp float halo_width=0.0;lowp float halo_blur=0.0;if (u_is_sdf) {fill_color=vec4(v_fill_np_color.rgb*v_fill_np_color.a,v_fill_np_color.a);halo_color=vec4(v_halo_np_color.rgb*v_halo_np_color.a,v_halo_np_color.a);halo_width=v_halo_width;halo_blur=v_halo_blur;}lowp float emissive_strength=0.0;\n#ifdef LIGHTING_3D_MODE\nemissive_strength=v_emissive_strength;\n#endif\nvec4 out_color;float fade_opacity=v_gamma_scale_size_fade_opacity[2];\n#ifdef RENDER_TEXT_AND_SYMBOL\nif (is_sdf==ICON) {vec2 tex_icon=v_tex_a_icon;lowp float alpha=opacity*fade_opacity*u_opacity_multiplier;vec4 icon_color=texture(u_texture_icon,tex_icon)*alpha;\n#ifdef FOG\nicon_color=fog_dither(fog_apply_premultiplied(icon_color,v_fog_pos));\n#endif\nglFragColor=icon_color;\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nreturn;}\n#endif\nvec2 cutout_factors=vec2(0.0);if (u_is_sdf) {float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_gamma_scale_size_fade_opacity.x;float size=v_gamma_scale_size_fade_opacity.y;float fontScale=u_is_text ? size/24.0 : size;out_color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;bool draw_halo=v_draw_halo > 0.0;if (draw_halo) {out_color=halo_color;gamma=(halo_blur*u_scale_factor*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width*u_scale_factor/fontScale)/SDF_PX;}lowp float dist=texture(u_texture,v_tex_a).r;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);out_color*=alpha;} else {\n#ifdef ICON_TRANSITION\nvec4 a=texture(u_texture,v_tex_a)*(1.0-u_icon_transition);vec4 b=texture(u_texture,v_tex_b)*u_icon_transition;out_color=(a+b);\n#else\nout_color=texture(u_texture,v_tex_a);\n#endif\n#ifdef APPLY_LUT_ON_GPU\nout_color=applyLUT(u_lutTexture,out_color);\n#endif\n#ifdef COLOR_ADJUSTMENT\nout_color=u_color_adj_mat*out_color;\n#endif\n}out_color*=opacity*fade_opacity*u_opacity_multiplier;\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(out_color,emissive_strength);\n#ifdef RENDER_SHADOWS\nfloat light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y);\n#ifdef TERRAIN\nout_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light);\n#else\nout_color.rgb*=mix(v_z_offset !=0.0 ? u_ground_shadow_factor : vec3(1.0),vec3(1.0),light);\n#endif\n#endif\n#endif\n#ifdef FOG\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\n#endif\nglFragColor=out_color;\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}','#include "_prelude_fog.vertex.glsl"\n#include "_prelude_terrain.vertex.glsl"\n#include "_prelude_shadow.vertex.glsl"\n#include "_prelude_ubo_properties.glsl"\n#define USING_APPEARANCE 1.0\nin ivec4 a_pos_offset;in uvec4 a_tex_size;in ivec4 a_pixeloffset;in vec4 a_projected_pos;\n#define FADE_TIME_HALF_PERIOD 2147483648u\n#define FADE_TIME_PERIOD 4294967296.0\n#ifdef GLOBAL_PLACEMENT_FADE\nin highp ivec2 a_fade_ref_time;\n#endif\n#ifdef LEGACY_PLACEMENT_FADE\nin uint a_fade_opacity;\n#endif\n#ifdef Z_OFFSET\nin float a_auto_z_offset;\n#endif\n#ifdef PROJECTION_GLOBE_VIEW\nin ivec4 a_globe_anchor;in vec3 a_globe_normal;\n#endif\n#ifdef ICON_TRANSITION\nin uvec2 a_texb;\n#endif\n#ifdef ELEVATED_ROADS\nin vec3 a_x_axis;in vec3 a_y_axis;uniform float u_normal_scale;\n#endif\n#ifdef RENDER_SHADOWS\nout highp float v_z_offset;\n#endif\nuniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;\n#ifdef RENDER_SHADOWS\nuniform mat4 u_inv_matrix;\n#endif\nuniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_elevation_from_sea;uniform bool u_pitch_with_map;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;\n#ifdef GLOBAL_PLACEMENT_FADE\nuniform highp int u_now;uniform float u_fade_duration;\n#endif\n#ifdef LEGACY_PLACEMENT_FADE\nuniform float u_fade_change;\n#endif\nuniform vec2 u_texsize;\n#ifdef PROJECTION_GLOBE_VIEW\nuniform vec3 u_up_vector;\n#endif\n#ifdef RENDER_TEXT_AND_SYMBOL\nuniform vec2 u_texsize_icon;\n#endif\nuniform bool u_is_halo;\n#ifdef PROJECTION_GLOBE_VIEW\nuniform vec3 u_tile_id;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_camera_forward;uniform float u_zoom_transition;uniform vec3 u_ecef_origin;uniform mat4 u_tile_matrix;\n#endif\nout vec2 v_tex_a;\n#ifdef ICON_TRANSITION\nout vec2 v_tex_b;\n#endif\nout float v_draw_halo;out vec3 v_gamma_scale_size_fade_opacity;\n#ifdef RENDER_TEXT_AND_SYMBOL\nout float is_sdf;out vec2 v_tex_a_icon;\n#endif\n#ifdef RENDER_SHADOWS\nuniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth;\n#endif\n#define SPP_HEADER_SIZE_VEC4 4u\nstruct SymbolPaintProperties {vec4 fill_np_color;vec4 halo_np_color;float opacity;float halo_width;float halo_blur;float emissive_strength;float occlusion_opacity;float z_offset;vec2 translate;};uniform lowp vec4 u_spp_fill_np_color;uniform lowp vec4 u_spp_halo_np_color;uniform lowp float u_spp_opacity;uniform lowp float u_spp_halo_width;uniform lowp float u_spp_halo_blur;uniform lowp float u_spp_emissive_strength;uniform lowp float u_spp_occlusion_opacity;uniform highp float u_spp_z_offset;uniform lowp vec2 u_spp_translate_rotation;uniform highp float u_spp_zoom_fraction;in float a_feature_index;layout(std140) uniform SymbolPaintPropertiesHeaderUniform {uvec4 header[SPP_HEADER_SIZE_VEC4];} u_spp_header;layout(std140) uniform SymbolPaintPropertiesUniform {vec4 properties[MAX_UBO_SIZE_VEC4];} u_spp_properties;layout(std140) uniform SymbolPaintPropertiesIndexUniform {uvec4 block_indices[MAX_UBO_SIZE_VEC4];} u_spp_index;out lowp float v_opacity;out lowp vec4 v_fill_np_color;out lowp vec4 v_halo_np_color;out lowp float v_halo_width;out lowp float v_halo_blur;\n#ifdef LIGHTING_3D_MODE\nout lowp float v_emissive_strength;\n#endif\nuint uvec4At(uvec4 v,uint index) {return (index==0u) ? v.x :\n(index==1u) ? v.y :\n(index==2u) ? v.z : v.w;}vec4 readColor(uint base,bool isDataDriven,uint offsetVec4,uint dzr,vec2 headerZoom,vec4 fallbackValue) {if (!isDataDriven) return fallbackValue;vec4 value=u_spp_properties.properties[base+offsetVec4];vec2 blockZoom=u_spp_properties.properties[base+offsetVec4+dzr].xy;vec2 zr=mix(headerZoom,blockZoom,float(dzr));return unpack_mix_color(value,zoomFactor(zr.x,zr.y,u_spp_zoom_fraction));}float readScalar(uint base,bool isDataDriven,uint offsetVec4,float fallbackValue) {if (!isDataDriven) return fallbackValue;vec4 slot=u_spp_properties.properties[base+offsetVec4];return unpack_mix_vec2(slot.xy,zoomFactor(slot.z,slot.w,u_spp_zoom_fraction));}vec2 readTranslate(uint base,bool isDataDriven,uint offsetVec4,uint dzr) {if (!isDataDriven) return vec2(0.0);vec4 value=u_spp_properties.properties[base+offsetVec4];vec2 blockZoom=u_spp_properties.properties[base+offsetVec4+dzr].xy;float t=zoomFactor(blockZoom.x,blockZoom.y,u_spp_zoom_fraction)*float(dzr);return mix(value.xy,value.zw,t);}SymbolPaintProperties readSymbolPaintProperties() {uint dataDrivenMask=u_spp_header.header[0][0];uint dzrMask =u_spp_header.header[0][1];uint blockSizeVec4 =u_spp_header.header[0][2];uint fillColorDzr=dzrMask & 1u;uint haloColorDzr=(dzrMask >> 1u) & 1u;vec2 fillColorHeaderZoom=uintBitsToFloat(u_spp_header.header[3].xy);vec2 haloColorHeaderZoom=uintBitsToFloat(u_spp_header.header[3].zw);uint featureIndex=uint(a_feature_index);uvec4 indexSlot=u_spp_index.block_indices[featureIndex/4u];uint base=uvec4At(indexSlot,featureIndex % 4u)*blockSizeVec4;SymbolPaintProperties props;props.fill_np_color =readColor(base,(dataDrivenMask & (1u << 0u)) !=0u,u_spp_header.header[0][3],fillColorDzr,fillColorHeaderZoom,u_spp_fill_np_color);props.halo_np_color =readColor(base,(dataDrivenMask & (1u << 1u)) !=0u,u_spp_header.header[1][0],haloColorDzr,haloColorHeaderZoom,u_spp_halo_np_color);props.opacity =readScalar(base,(dataDrivenMask & (1u << 2u)) !=0u,u_spp_header.header[1][1],u_spp_opacity);props.halo_width =readScalar(base,(dataDrivenMask & (1u << 3u)) !=0u,u_spp_header.header[1][2],u_spp_halo_width);props.halo_blur =readScalar(base,(dataDrivenMask & (1u << 4u)) !=0u,u_spp_header.header[1][3],u_spp_halo_blur);props.emissive_strength=readScalar(base,(dataDrivenMask & (1u << 5u)) !=0u,u_spp_header.header[2][0],u_spp_emissive_strength);props.occlusion_opacity=readScalar(base,(dataDrivenMask & (1u << 6u)) !=0u,u_spp_header.header[2][1],u_spp_occlusion_opacity);props.z_offset =readScalar(base,(dataDrivenMask & (1u << 7u)) !=0u,u_spp_header.header[2][2],u_spp_z_offset);uint translateDzr=(dzrMask >> 8u) & 1u;props.translate =readTranslate(base,(dataDrivenMask & (1u << 8u)) !=0u,u_spp_header.header[2][3],translateDzr);return props;}vec2 unpack_opacity(uint packedOpacity) {return vec2(float(packedOpacity/2u)/127.0,float(packedOpacity & 1u));}void main() {SymbolPaintProperties paint_properties=readSymbolPaintProperties();lowp float opacity=paint_properties.opacity;v_opacity=opacity;v_fill_np_color=paint_properties.fill_np_color;v_halo_np_color=paint_properties.halo_np_color;v_halo_width=paint_properties.halo_width;v_halo_blur=paint_properties.halo_blur;\n#ifdef LIGHTING_3D_MODE\nv_emissive_strength=paint_properties.emissive_strength;\n#endif\nlowp float occlusion_opacity=paint_properties.occlusion_opacity;highp float z_offset=paint_properties.z_offset;vec2 a_pos=vec2(a_pos_offset.xy);vec2 a_offset=vec2(a_pos_offset.zw);vec2 a_tex=vec2(a_tex_size.xy);vec2 a_size=vec2(a_tex_size.zw);float a_size_min=floor(a_size[0]*0.5);float a_size_max= floor(a_size[1]*0.5);float a_apperance=a_size[1]-2.0*a_size_max;vec2 a_pxoffset=vec2(a_pixeloffset.xy);vec2 a_min_font_scale=vec2(a_pixeloffset.zw)/256.0;highp float segment_angle=-a_projected_pos[3];float size;if (a_apperance==USING_APPEARANCE) {size=a_size_max/128.0;} else if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size_max,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 tile_anchor=a_pos;float e=u_elevation_from_sea ? z_offset : z_offset+elevation(tile_anchor);\n#ifdef Z_OFFSET\ne+=a_auto_z_offset;\n#endif\nvec3 h=elevationVector(tile_anchor)*e;float globe_occlusion_fade;vec3 world_pos;vec3 mercator_pos;vec3 world_pos_globe;\n#ifdef PROJECTION_GLOBE_VIEW\nmercator_pos=mercator_tile_position(u_inv_rot_matrix,tile_anchor,u_tile_id,u_merc_center);world_pos_globe=vec3(a_globe_anchor)+h;world_pos=mix_globe_mercator(world_pos_globe,mercator_pos,u_zoom_transition);vec4 ecef_point=u_tile_matrix*vec4(world_pos,1.0);vec3 origin_to_point=ecef_point.xyz-u_ecef_origin;globe_occlusion_fade=dot(origin_to_point,u_camera_forward) >=0.0 ? 0.0 : 1.0;\n#else\nworld_pos=vec3(tile_anchor,0)+h;globe_occlusion_fade=1.0;\n#endif\nvec4 projected_point=u_matrix*vec4(world_pos,1);highp float camera_to_anchor_distance=projected_point.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(\n0.5+0.5*distance_ratio,0.0,1.5);size*=perspective_ratio;float font_scale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetprojected_point;vec2 a;\n#ifdef PROJECTION_GLOBE_VIEW\nvec3 displacement=vec3(a_globe_normal.z,0,-a_globe_normal.x);offsetprojected_point=u_matrix*vec4(vec3(a_globe_anchor)+displacement,1);vec4 projected_point_globe=u_matrix*vec4(world_pos_globe,1);a=projected_point_globe.xy/projected_point_globe.w;\n#else\noffsetprojected_point=u_matrix*vec4(tile_anchor+vec2(1,0),0,1);a=projected_point.xy/projected_point.w;\n#endif\nvec2 b=offsetprojected_point.xy/offsetprojected_point.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}vec4 projected_pos;\n#ifdef PROJECTION_GLOBE_VIEW\n#ifdef PROJECTED_POS_ON_VIEWPORT\nprojected_pos=u_label_plane_matrix*vec4(a_projected_pos.xyz+h,1.0);\n#else\nvec3 proj_pos=mix_globe_mercator(a_projected_pos.xyz,mercator_pos,u_zoom_transition)+h;projected_pos=u_label_plane_matrix*vec4(proj_pos,1.0);\n#endif\n#else\nprojected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,h.z,1.0);\n#endif\nhighp 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);float z=0.0;vec2 offset=rotation_matrix*(a_offset/32.0*max(a_min_font_scale,font_scale)+a_pxoffset/16.0);\n#ifdef TERRAIN\n#ifdef PITCH_WITH_MAP_TERRAIN\nvec4 tile_pos=u_label_plane_matrix_inv*vec4(a_projected_pos.xy+offset,0.0,1.0);z=elevation(tile_pos.xy);\n#endif\n#endif\n#ifdef Z_OFFSET\nz+=u_pitch_with_map ? a_auto_z_offset+z_offset : 0.0;\n#else\nz+=u_pitch_with_map ? z_offset : 0.0;\n#endif\nfloat occlusion_fade=globe_occlusion_fade;float out_fade_opacity=occlusion_fade;\n#ifdef GLOBAL_PLACEMENT_FADE\nhighp int fade_state=a_fade_ref_time.y;float fade_target=float(fade_state & 1);highp uint fade_elapsed_bits=uint(u_now)-uint(a_fade_ref_time.x);float fade_elapsed=float(fade_elapsed_bits);if (fade_elapsed_bits >=FADE_TIME_HALF_PERIOD) fade_elapsed-=FADE_TIME_PERIOD;bool fade_settled=(fade_state & 2) !=0;float fade_t=(fade_settled || u_fade_duration==0.0) ? 1.0 : fade_elapsed/u_fade_duration;float raw_fade_opacity=fade_target > 0.5 ? fade_t : 1.0-fade_t;out_fade_opacity=clamp(raw_fade_opacity,0.0,occlusion_fade);\n#endif\n#ifdef LEGACY_PLACEMENT_FADE\nvec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;out_fade_opacity=max(0.0,min(occlusion_fade,fade_opacity[0]+fade_change));\n#endif\n#ifdef DEPTH_OCCLUSION\nfloat depth_occlusion=occlusionFadeMultiSample(projected_point);float depth_occlusion_multplier=mix(occlusion_opacity,1.0,depth_occlusion);out_fade_opacity*=depth_occlusion_multplier;\n#endif\nfloat alpha=opacity*out_fade_opacity;float hidden=float(alpha==0.0 || projected_point.w <=0.0 || occlusion_fade==0.0);vec3 pos;\n#ifdef PROJECTION_GLOBE_VIEW\nvec3 xAxis=u_pitch_with_map ? normalize(cross(a_globe_normal,u_up_vector)) : vec3(1,0,0);vec3 yAxis=u_pitch_with_map ? normalize(cross(a_globe_normal,xAxis)) : vec3(0,1,0);pos=projected_pos.xyz/projected_pos.w+xAxis*offset.x+yAxis*offset.y;\n#else\n#ifdef ELEVATED_ROADS\nvec3 xAxis=vec3(a_x_axis.xy,a_x_axis.z*u_normal_scale);vec3 yAxis=vec3(a_y_axis.xy,a_y_axis.z*u_normal_scale);pos=projected_pos.xyz/projected_pos.w+xAxis*offset.x+yAxis*offset.y;\n#else\npos=vec3(projected_pos.xy/projected_pos.w+offset,z);\n#endif\n#endif\ngl_Position=mix(u_coord_matrix*vec4(pos,1.0),AWAY,hidden);{vec2 tr=paint_properties.translate;vec2 rotated_tr=vec2(\nu_spp_translate_rotation.x*tr.x-u_spp_translate_rotation.y*tr.y,u_spp_translate_rotation.y*tr.x+u_spp_translate_rotation.x*tr.y\n);gl_Position.xy+=(u_coord_matrix*vec4(rotated_tr,0.0,0.0)).xy;}float gamma_scale=gl_Position.w;v_draw_halo=(u_is_halo && float(gl_InstanceID)==0.0) ? 1.0 : 0.0;v_gamma_scale_size_fade_opacity=vec3(gamma_scale,size,out_fade_opacity);v_tex_a=a_tex/u_texsize;\n#ifdef RENDER_TEXT_AND_SYMBOL\nis_sdf=a_size[0]-2.0*a_size_min;v_tex_a_icon=a_tex/u_texsize_icon;\n#endif\n#ifdef ICON_TRANSITION\nv_tex_b=vec2(a_texb)/u_texsize;\n#endif\n#ifdef RENDER_SHADOWS\nvec4 shd_pos=u_inv_matrix*vec4(pos,1.0);vec3 shd_pos0=shd_pos.xyz;vec3 shd_pos1=shd_pos.xyz;\n#ifdef NORMAL_OFFSET\nvec3 shd_pos_offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=shd_pos_offset*shadow_normal_offset_multiplier0();shd_pos1+=shd_pos_offset*shadow_normal_offset_multiplier1();\n#endif\nv_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w;\n#endif\n#ifdef FOG\nv_fog_pos=fog_position(world_pos);\n#endif\n#ifdef RENDER_SHADOWS\nv_z_offset=e;\n#endif\n}'),skybox:pu('#include "_prelude_fog.fragment.glsl"\nin lowp vec3 v_uv;uniform lowp samplerCube u_cubemap;uniform lowp float u_opacity;uniform highp float u_temporal_offset;uniform highp vec3 u_sun_direction;float sun_disk(highp vec3 ray_direction,highp vec3 sun_direction) {highp float cos_angle=dot(normalize(ray_direction),sun_direction);const highp float cos_sun_angular_diameter=0.99996192306;const highp float smoothstep_delta=1e-5;return smoothstep(\ncos_sun_angular_diameter-smoothstep_delta,cos_sun_angular_diameter+smoothstep_delta,cos_angle);}float map(float value,float start,float end,float new_start,float new_end) {return ((value-start)*(new_end-new_start))/(end-start)+new_start;}void main() {vec3 uv=v_uv;const float y_bias=0.015;uv.y+=y_bias;uv.y=pow(abs(uv.y),1.0/5.0);uv.y=map(uv.y,0.0,1.0,-1.0,1.0);vec3 sky_color=texture(u_cubemap,uv).rgb;\n#ifdef FOG\nsky_color=fog_apply_sky_gradient(v_uv.xzy,sky_color);\n#endif\nsky_color+=0.1*sun_disk(v_uv,u_sun_direction);glFragColor=vec4(sky_color*u_opacity,u_opacity);\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\n}',Gd),skyboxGradient:pu('#include "_prelude_fog.fragment.glsl"\nin highp vec3 v_uv;uniform lowp sampler2D u_color_ramp;uniform highp vec3 u_center_direction;uniform lowp float u_radius;uniform lowp float u_opacity;uniform highp float u_temporal_offset;void main() {float progress=acos(dot(normalize(v_uv),u_center_direction))/u_radius;vec4 color=texture(u_color_ramp,vec2(progress,0.5));\n#ifdef FOG\ncolor.rgb=fog_apply_sky_gradient(v_uv.xzy,color.rgb/color.a)*color.a;\n#endif\ncolor*=u_opacity;glFragColor=color;\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\n}',Gd),skyboxCapture:pu("\nin highp vec3 v_position;uniform highp float u_sun_intensity;uniform highp float u_luminance;uniform lowp vec3 u_sun_direction;uniform highp vec4 u_color_tint_r;uniform highp vec4 u_color_tint_m;precision highp float;\n#define BETA_R vec3(5.5e-6,13.0e-6,22.4e-6)\n#define BETA_M vec3(21e-6,21e-6,21e-6)\n#define MIE_G 0.76\n#define DENSITY_HEIGHT_SCALE_R 8000.0\n#define DENSITY_HEIGHT_SCALE_M 1200.0\n#define PLANET_RADIUS 6360e3\n#define ATMOSPHERE_RADIUS 6420e3\n#define SAMPLE_STEPS 10\n#define DENSITY_STEPS 4\nfloat ray_sphere_exit(vec3 orig,vec3 dir,float radius) {float a=dot(dir,dir);float b=2.0*dot(dir,orig);float c=dot(orig,orig)-radius*radius;float d=sqrt(b*b-4.0*a*c);return (-b+d)/(2.0*a);}vec3 extinction(vec2 density) {return exp(-vec3(BETA_R*u_color_tint_r.a*density.x+BETA_M*u_color_tint_m.a*density.y));}vec2 local_density(vec3 point) {float height=max(length(point)-PLANET_RADIUS,0.0);float exp_r=exp(-height/DENSITY_HEIGHT_SCALE_R);float exp_m=exp(-height/DENSITY_HEIGHT_SCALE_M);return vec2(exp_r,exp_m);}float phase_ray(float cos_angle) {return (3.0/(16.0*PI))*(1.0+cos_angle*cos_angle);}float phase_mie(float cos_angle) {return (3.0/(8.0*PI))*((1.0-MIE_G*MIE_G)*(1.0+cos_angle*cos_angle))/((2.0+MIE_G*MIE_G)*pow(1.0+MIE_G*MIE_G-2.0*MIE_G*cos_angle,1.5));}vec2 density_to_atmosphere(vec3 point,vec3 light_dir) {float ray_len=ray_sphere_exit(point,light_dir,ATMOSPHERE_RADIUS);float step_len=ray_len/float(DENSITY_STEPS);vec2 density_point_to_atmosphere=vec2(0.0);for (int i=0; i < DENSITY_STEPS;++i) {vec3 point_on_ray=point+light_dir*((float(i)+0.5)*step_len);density_point_to_atmosphere+=local_density(point_on_ray)*step_len;;}return density_point_to_atmosphere;}vec3 atmosphere(vec3 ray_dir,vec3 sun_direction,float sun_intensity) {vec2 density_orig_to_point=vec2(0.0);vec3 scatter_r=vec3(0.0);vec3 scatter_m=vec3(0.0);vec3 origin=vec3(0.0,PLANET_RADIUS,0.0);float ray_len=ray_sphere_exit(origin,ray_dir,ATMOSPHERE_RADIUS);float step_len=ray_len/float(SAMPLE_STEPS);for (int i=0; i < SAMPLE_STEPS;++i) {vec3 point_on_ray=origin+ray_dir*((float(i)+0.5)*step_len);vec2 density=local_density(point_on_ray)*step_len;density_orig_to_point+=density;vec2 density_point_to_atmosphere=density_to_atmosphere(point_on_ray,sun_direction);vec2 density_orig_to_atmosphere=density_orig_to_point+density_point_to_atmosphere;vec3 extinction=extinction(density_orig_to_atmosphere);scatter_r+=density.x*extinction;scatter_m+=density.y*extinction;}float cos_angle=dot(ray_dir,sun_direction);float phase_r=phase_ray(cos_angle);float phase_m=phase_mie(cos_angle);vec3 beta_r=BETA_R*u_color_tint_r.rgb*u_color_tint_r.a;vec3 beta_m=BETA_M*u_color_tint_m.rgb*u_color_tint_m.a;return (scatter_r*phase_r*beta_r+scatter_m*phase_m*beta_m)*sun_intensity;}const float A=0.15;const float B=0.50;const float C=0.10;const float D=0.20;const float E=0.02;const float F=0.30;vec3 uncharted2_tonemap(vec3 x) {return ((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;}void main() {vec3 ray_direction=v_position;ray_direction.y=pow(ray_direction.y,5.0);const float y_bias=0.015;ray_direction.y+=y_bias;vec3 color=atmosphere(normalize(ray_direction),u_sun_direction,u_sun_intensity);float white_scale=1.0748724675633854;color=uncharted2_tonemap((log2(2.0/pow(u_luminance,4.0)))*color)*white_scale;glFragColor=vec4(color,1.0);}","in highp vec3 a_pos_3f;uniform mat3 u_matrix_3f;out highp vec3 v_position;float map(float value,float start,float end,float new_start,float new_end) {return ((value-start)*(new_end-new_start))/(end-start)+new_start;}void main() {vec4 pos=vec4(u_matrix_3f*a_pos_3f,1.0);v_position=native_cubemap_direction(pos.xyz);v_position.y=map(v_position.y,-1.0,1.0,0.0,1.0);gl_Position=vec4(a_pos_3f.xy,0.0,1.0);}"),globeAtmosphere:pu('#include "_prelude_fog.fragment.glsl"\nuniform float u_transition;uniform highp float u_fadeout_range;uniform highp float u_temporal_offset;uniform vec4 u_atmosphere_fog_color;uniform vec4 u_high_color;uniform vec4 u_space_color;uniform float u_horizon_angle;in highp vec3 v_ray_dir;in highp vec3 v_horizon_dir;void main() {highp vec3 dir=normalize(v_ray_dir);float globe_pos_dot_dir;\n#ifdef PROJECTION_GLOBE_VIEW\nglobe_pos_dot_dir=dot(u_globe_pos,dir);highp vec3 closest_point_forward=abs(globe_pos_dot_dir)*dir;float norm_dist_from_center=length(closest_point_forward-u_globe_pos)/u_globe_radius;if (norm_dist_from_center < 0.98) {\n#ifdef ALPHA_PASS\nglFragColor=vec4(0,0,0,0);return;\n#else\nglFragColor=vec4(0,0,0,1);return;\n#endif\n}\n#endif\nhighp vec3 horizon_dir=normalize(v_horizon_dir);float horizon_angle_mercator=dir.y < horizon_dir.y ?\n0.0 : max(acos(clamp(dot(dir,horizon_dir),-1.0,1.0)),0.0);float horizon_angle;\n#ifdef PROJECTION_GLOBE_VIEW\nhighp vec3 closest_point=globe_pos_dot_dir*dir;highp float closest_point_to_center=length(closest_point-u_globe_pos);highp float theta=asin(clamp(closest_point_to_center/length(u_globe_pos),-1.0,1.0));horizon_angle=globe_pos_dot_dir < 0.0 ?\nPI-theta-u_horizon_angle : theta-u_horizon_angle;float angle_t=pow(u_transition,10.0);horizon_angle=mix(horizon_angle,horizon_angle_mercator,angle_t);\n#else\nhorizon_angle=horizon_angle_mercator;\n#endif\nhorizon_angle/=PI;float t=exp(-horizon_angle/u_fadeout_range);float alpha_0=u_atmosphere_fog_color.a;float alpha_1=u_high_color.a;float alpha_2=u_space_color.a;vec3 color_stop_0=u_atmosphere_fog_color.rgb;vec3 color_stop_1=u_high_color.rgb;vec3 color_stop_2=u_space_color.rgb;\n#ifdef ALPHA_PASS\nfloat a0=mix(alpha_2,1.0,alpha_1);float a1=mix(a0,1.0,alpha_0);float a2=mix(a0,a1,t);float a =mix(alpha_2,a2,t);glFragColor=vec4(1.0,1.0,1.0,a);\n#else\nvec3 c0=mix(color_stop_2,color_stop_1,alpha_1);vec3 c1=mix(c0,color_stop_0,alpha_0);vec3 c2=mix(c0,c1,t);vec3 c=c2;glFragColor=vec4(c*t,t);\n#endif\n}',"in vec3 a_pos;in vec2 a_uv;uniform vec3 u_frustum_tl;uniform vec3 u_frustum_tr;uniform vec3 u_frustum_br;uniform vec3 u_frustum_bl;uniform float u_horizon;out highp vec3 v_ray_dir;out highp vec3 v_horizon_dir;void main() {v_ray_dir=mix(\nmix(u_frustum_tl,u_frustum_tr,a_uv.x),mix(u_frustum_bl,u_frustum_br,a_uv.x),a_uv.y);v_horizon_dir=mix(\nmix(u_frustum_tl,u_frustum_bl,u_horizon),mix(u_frustum_tr,u_frustum_br,u_horizon),a_uv.x);gl_Position=vec4(a_pos,1.0);}"),stars:pu("in highp vec2 v_uv;in mediump float v_intensity;float shapeCircle(in vec2 uv)\n{float beginFade=0.6;float lengthFromCenter=length(v_uv);return 1.0-clamp((lengthFromCenter-beginFade)/(1.0-beginFade),0.0,1.0);}void main() {float alpha=shapeCircle(v_uv);vec3 color=vec3(1.0,1.0,1.0);alpha*=v_intensity;glFragColor=vec4(color*alpha,alpha);HANDLE_WIREFRAME_DEBUG;}","\nin vec3 a_pos_3f;in vec2 a_uv;in float a_size_scale;in float a_opacity;uniform mat4 u_matrix;uniform vec3 u_up;uniform vec3 u_right;uniform float u_intensity_multiplier;out highp vec2 v_uv;out mediump float v_intensity;void main() {v_uv=a_uv;v_intensity=a_opacity*u_intensity_multiplier;vec3 pos=a_pos_3f;pos+=a_uv.x*u_right*a_size_scale;pos+=a_uv.y*u_up*a_size_scale;gl_Position=u_matrix*vec4(pos,1.0);}"),occlusion:pu("uniform vec4 u_color;void main() {glFragColor=u_color;}",'#include "_prelude_terrain.vertex.glsl"\nin highp vec2 a_offset_xy;uniform highp vec3 u_anchorPos;uniform mat4 u_matrix;uniform vec2 u_screenSizePx;uniform vec2 u_occluderSizePx;void main() {vec3 world_pos=u_anchorPos;\n#ifdef TERRAIN\nfloat e=elevation(world_pos.xy);world_pos.z+=e;\n#endif\nvec4 projected_point=u_matrix*vec4(world_pos,1.0);projected_point.xy+=projected_point.w*a_offset_xy*0.5*u_occluderSizePx/u_screenSizePx;gl_Position=projected_point;}')};function uu(e,t){const i=e.split("\n");for(let e of i){if(e=e.trimStart(),"#"!==e[0])continue;if(!e.includes("if"))continue;if(e.startsWith("#endif"))continue;const i=e.match(eu);if(i)for(const e of i)tu.has(e)||t.add(e)}}function _u(e){return new Set(["uint","int","uvec2","ivec2","uvec3","ivec3","uvec4","ivec4"]).has(e)}function pu(e,t){const i=new Set,s=[],o=[];e=e.replace(Jd,(e,t)=>(o.push(t),"")),t=t.replace(Jd,(e,t)=>(s.push(t),""));let r=new Set(iu);uu(e,r),uu(t,r);for(const e of[...s,...o])ou[e]||(ou[e]=new Set,uu(su[e],ou[e])),r=new Set([...r,...ou[e]]);return{fragmentSource:e=e.replace(Qd,(e,t,s,o,r)=>(i.add(r),"define"===t?`\n#ifndef HAS_UNIFORM_u_${r}\n${_u(o)?"flat ":""}in ${s} ${o} ${r};\n#else\nuniform ${s} ${o} u_${r};\n#endif\n`:"initialize"===t?`\n#ifdef HAS_UNIFORM_u_${r}\n ${s} ${o} ${r} = u_${r};\n#endif\n`:"define-attribute"===t?`\n#ifdef HAS_ATTRIBUTE_a_${r}\n in ${s} ${o} ${r};\n#endif\n`:"initialize-attribute"===t?"":void 0)),vertexSource:t=t.replace(Qd,(e,t,s,o,r)=>{const n=`MATERIAL_ATTRIBUTE_OFFSET_${r}`,a="float"===o?"vec2":o,l=`GET_ATTRIBUTE_${a}(a_${r}, materialInfo, ${n})`,c=r.includes("color")?"color":a;return"define-attribute-vertex-shader-only"===t?`\n#ifdef HAS_ATTRIBUTE_a_${r}\nin ${s} ${o} a_${r};\n#endif\n`:i.has(r)?"define"===t?`\n#ifndef HAS_UNIFORM_u_${r}\nuniform lowp float u_${r}_t;\n #if !defined(${n})\n in ${s} ${a} a_${r};\n #endif\n${_u(o)?"flat ":""}out ${s} ${o} ${r};\n#else\nuniform ${s} ${o} u_${r};\n#endif\n`:"initialize"===t?"vec4"===c||"uvec4"===c?`\n#ifndef HAS_UNIFORM_u_${r}\n ${r} = a_${r};\n#else\n ${s} ${o} ${r} = u_${r};\n#endif\n`:`\n#if !defined(HAS_UNIFORM_u_${r})\n #ifdef ${n}\n ${r} = unpack_mix_${c}(${l}, u_${r}_t);\n #else\n ${r} = unpack_mix_${c}(a_${r}, u_${r}_t);\n #endif\n#else\n ${s} ${o} ${r} = u_${r};\n#endif\n`:"define-attribute"===t?`\n#ifdef HAS_ATTRIBUTE_a_${r}\n in ${s} ${o} a_${r};\n out ${s} ${o} ${r};\n#endif\n`:"initialize-attribute"===t?`\n#ifdef HAS_ATTRIBUTE_a_${r}\n ${r} = a_${r};\n#endif\n`:void 0:"define"===t?`\n#ifndef HAS_UNIFORM_u_${r}\nuniform lowp float u_${r}_t;\n #if !defined(${n})\n in ${s} ${a} a_${r};\n #endif\n#else\nuniform ${s} ${o} u_${r};\n#endif\n`:"define-instanced"===t?"mat4"===c?`\n#ifdef INSTANCED_ARRAYS\nin vec4 a_${r}0;\nin vec4 a_${r}1;\nin vec4 a_${r}2;\nin vec4 a_${r}3;\n#else\nuniform ${s} ${o} u_${r};\n#endif\n`:`\n#ifdef INSTANCED_ARRAYS\nin ${s} ${a} a_${r};\n#else\nuniform ${s} ${o} u_${r};\n#endif\n`:"initialize-attribute-custom"===t?`\n#ifdef HAS_ATTRIBUTE_a_${r}\n ${s} ${o} ${r} = a_${r};\n#endif\n`:"vec4"===c||"uvec4"===c?`\n#ifndef HAS_UNIFORM_u_${r}\n #ifdef ${n}\n ${s} ${o} ${r} = ${l};\n #else\n ${s} ${o} ${r} = a_${r};\n #endif\n#else\n ${s} ${o} ${r} = u_${r};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${r}\n #ifdef ${n}\n ${s} ${o} ${r} = unpack_mix_${c}(${l}, u_${r}_t);\n #else\n ${s} ${o} ${r} = unpack_mix_${c}(a_${r}, u_${r}_t);\n #endif\n#else\n ${s} ${o} ${r} = u_${r};\n#endif\n`}),usedDefines:r,vertexIncludes:s,fragmentIncludes:o}}class fu{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffers=[],this.vao=null}bind(e,t,i,s,o,r,n,a){this.context=e;let l=this.boundPaintVertexBuffers.length!==s.length;for(let e=0;!l&&e<s.length;e++)this.boundPaintVertexBuffers[e]!==s[e]&&(l=!0);let c=this.boundDynamicVertexBuffers.length!==n.length;for(let e=0;!c&&e<n.length;e++){const t=this.boundDynamicVertexBuffers[e],i=n[e];t===i||t&&i&&t.attributes===i.attributes||(c=!0)}if(!this.vao||this.boundProgram!==t||this.boundLayoutVertexBuffer!==i||l||c||this.boundIndexBuffer!==o||this.boundVertexOffset!==r)this.freshBind(t,i,s,o,r,n,a);else{e.bindVertexArrayOES.set(this.vao);for(let i=0;i<n.length;i++){const s=n[i];s&&(s!==this.boundDynamicVertexBuffers[i]&&(s.bind(),s.setVertexAttribPointers(e.gl,t,r)),a&&s.instanceCount&&s.setVertexAttribDivisor(e.gl,t,a))}o&&o.dynamicDraw&&o.bind(),this.boundDynamicVertexBuffers=n}}freshBind(e,t,i,s,o,r,n){const a=this.context,l=a.gl;this.vao&&this.destroy(),this.vao=a.gl.createVertexArray(),a.bindVertexArrayOES.set(this.vao),this.boundProgram=e,this.boundLayoutVertexBuffer=t,this.boundPaintVertexBuffers=i,this.boundIndexBuffer=s,this.boundVertexOffset=o,this.boundDynamicVertexBuffers=r,t.enableAttributes(l,e),t.bind(),t.setVertexAttribPointers(l,e,o);for(const t of i)t.enableAttributes(l,e),t.bind(),t.setVertexAttribPointers(l,e,o);for(const t of r)t&&(t.enableAttributes(l,e),t.bind(),t.setVertexAttribPointers(l,e,o),n&&t.instanceCount&&t.setVertexAttribDivisor(l,e,n));s&&s.bind()}destroy(){this.vao&&(this.context.gl.deleteVertexArray(this.vao),this.vao=null)}}function mu(){return{u_dem:2,u_dem_prev:4,u_dem_tl:[0,0],u_dem_tl_prev:[0,0],u_dem_scale:0,u_dem_scale_prev:0,u_dem_size:0,u_dem_lerp:1,u_depth:3,u_depth_size_inv:[0,0],u_depth_range_unpack:[0,1],u_occluder_half_size:16,u_occlusion_depth_offset:-1e-4,u_exaggeration:0}}class gu{constructor(e=0,t=0,i=0,s=0){if(isNaN(e)||e<0||isNaN(t)||t<0||isNaN(i)||i<0||isNaN(s)||s<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=s}interpolate(e,t,i){return null!=t.top&&null!=e.top&&(this.top=J(e.top,t.top,i)),null!=t.bottom&&null!=e.bottom&&(this.bottom=J(e.bottom,t.bottom,i)),null!=t.left&&null!=e.left&&(this.left=J(e.left,t.left,i)),null!=t.right&&null!=e.right&&(this.right=J(e.right,t.right,i)),this}getCenter(e,t){const i=Ee((this.left+e-this.right)/2,0,e),s=Ee((this.top+t-this.bottom)/2,0,t);return new m(i,s)}equals(e){return this.top===e.top&&this.bottom===e.bottom&&this.left===e.left&&this.right===e.right}clone(){return new gu(this.top,this.bottom,this.left,this.right)}toJSON(){return{top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}function vu(e,t){const i=bs(e,3);ys(e,t),Ts(e,3,i)}function yu(e,t){const i=fs([]);return ms(i,i,-t),gs(i,i,-e),i}function xu(e,t){const i=[e[0],e[1],0],s=[t[0],t[1],0];if(_s(i)>=1e-15){const e=ye([],i);Ti(s,e,Kt(s,e)),t[0]=s[0],t[1]=s[1]}const o=Ht([],t,e);if(ps(o)<1e-15)return null;const r=Math.atan2(-o[1],o[0]);return yu(Math.atan2(Math.sqrt(e[0]*e[0]+e[1]*e[1]),-e[2]),r)}class bu{constructor(e,t){this.position=e,this.orientation=t}get position(){return this._position}set position(e){if(e){const t=e instanceof we?e:new we(e[0],e[1],e[2]);this._renderWorldCopies&&(t.x=si(t.x,0,1)),this._position=t}else this._position=null}lookAtPoint(e,t,i){if(this.orientation=null,!this.position)return;const s=this.position,o=i||(this._elevation?this._elevation.getAtPointOrZero(we.fromLngLat(e)):0),r=we.fromLngLat(e,o),n=[r.x-s.x,r.y-s.y,r.z-s.z];t||(t=[0,0,1]),t[2]=Math.abs(t[2]),this.orientation=xu(n,t)}setPitchBearing(e,t){this.orientation=yu(le(e),le(-t))}}class wu{constructor(e,t){this._transform=ci([]),this.orientation=t,this.position=e}get mercatorPosition(){const e=this.position;return new we(e[0],e[1],e[2])}get position(){const e=bs(this._transform,3);return[e[0],e[1],e[2]]}set position(e){var t;e&&Ts(this._transform,3,[(t=e)[0],t[1],t[2],1])}get orientation(){return this._orientation}set orientation(e){this._orientation=e||fs([]),e&&vu(this._transform,this._orientation)}getPitchBearing(){const e=this.forward(),t=this.right();return{bearing:Math.atan2(-t[1],t[0]),pitch:Math.atan2(Math.sqrt(e[0]*e[0]+e[1]*e[1]),-e[2])}}setPitchBearing(e,t){this._orientation=yu(e,t),vu(this._transform,this._orientation)}forward(){const e=bs(this._transform,2);return[-e[0],-e[1],-e[2]]}up(){const e=bs(this._transform,1);return[-e[0],-e[1],-e[2]]}right(){const e=bs(this._transform,0);return[e[0],e[1],e[2]]}getCameraToWorld(e,t){const i=new Float64Array(16);return Tt(i,this.getWorldToCamera(e,t)),i}getCameraToWorldMercator(){return this._transform}getWorldToCameraPosition(e,t,i){const s=this.position;Ti(s,s,-e);const o=new Float64Array(16);return Ct(o,[i,i,i]),At(o,o,s),o[10]*=t,o}getWorldToCamera(e,t){const i=new Float64Array(16),s=new Float64Array(4),o=this.position;return vs(s,this._orientation),Ti(o,o,-e),ys(i,s),At(i,i,o),i[1]*=-1,i[5]*=-1,i[9]*=-1,i[13]*=-1,i[8]*=t,i[9]*=t,i[10]*=t,i[11]*=t,i}getCameraToClipPerspective(e,t,i,s){const o=new Float64Array(16);return xs(o,e,t,i,s),o}getCameraToClipOrthographic(e,t,i,s,o,r){const n=new Float64Array(16);return ki(n,e,t,i,s,o,r),n}getDistanceToElevation(e,t=!1){const i=0===e?0:ws(e,t?at(this.position[1]):this.position[1]),s=this.forward();return(i-this.position[2])/s[2]}clone(){return new wu([...this.position],[...this.orientation])}}const Tu=15;class Eu{constructor(e,t,i,s,o,r,n){this.tileSize=512,this._renderWorldCopies=void 0===o||o,this._minZoom=e||0,this._maxZoom=t||22,this._minPitch=i??0,this._maxPitch=s??60,this.setProjection(r),this.setMaxBounds(n),this.width=0,this.height=0,this._center=new Es(0,0),this.zoom=0,this.angle=0,this._fov=.6435011087932844,this._pitch=0,this._nearZ=0,this._farZ=0,this._nearClipOffset=0,this._unmodified=!0,this._edgeInsets=new gu,this._frustumCache=new Map,this._posMatrixCache=new Map,this._projMatrixCache=new Map,this._alignedProjMatrixCache=new Map,this._pixelsToTileUnitsCache=new Map,this._fogTileMatrixCache=new Map,this._expandedProjMatrixCache=new Map,this._distanceTileDataCache=new Map,this._camera=new wu,this._centerAltitude=0,this._averageElevation=0,this.cameraElevationReference="ground",this._pixelsPerMercatorPixel=1,this.globeRadius=0,this.globeCenterInViewSpace=[0,0,0],this._tileCoverLift=0,this.freezeTileCoverage=!1,this._horizonShift=.1,this._orthographicProjectionAtLowPitch=!1,this._allowWorldUnderZoom=!1,this.mercatorMatrix=new Float64Array(16),this.mercatorFogMatrix=new Float32Array(16),this.invProjMatrix=new Float64Array(16),this._cameraToClip=new Float64Array(16),this._worldToCamera=new Float64Array(16),this._expandedFarZProjMatrixBuf=new Float64Array(16),this.expandedFarZProjMatrix=this._expandedFarZProjMatrixBuf,this.starsProjMatrix=new Float32Array(16),this.skyboxMatrix=new Float32Array(16),this._mat4Scratch=new Float64Array(16),this.alignedProjMatrix=new Float64Array(16),this.labelPlaneMatrix=new Float32Array(16),this.glCoordMatrix=new Float32Array(16),this.pixelMatrix=new Float64Array(16),this.pixelMatrixInverse=new Float64Array(16)}clone(){const e=new Eu(this._minZoom,this._maxZoom,this._minPitch,this.maxPitch,this._renderWorldCopies,this.getProjection(),this.maxBounds);return e._elevation=this._elevation,e._centerAltitude=this._centerAltitude,e._centerAltitudeValidForExaggeration=this._centerAltitudeValidForExaggeration,e.tileSize=this.tileSize,e.mercatorFromTransition=this.mercatorFromTransition,e.width=this.width,e.height=this.height,e.cameraElevationReference=this.cameraElevationReference,e._center=this._center,e._setZoom(this.zoom),e._seaLevelZoom=this._seaLevelZoom,e.angle=this.angle,e._fov=this._fov,e._pitch=this._pitch,e._nearZ=this._nearZ,e._farZ=this._farZ,e._nearClipOffset=this._nearClipOffset,e._averageElevation=this._averageElevation,e._orthographicProjectionAtLowPitch=this._orthographicProjectionAtLowPitch,e._unmodified=this._unmodified,e._edgeInsets=this._edgeInsets.clone(),e._camera=this._camera.clone(),e._calcMatrices(),e.freezeTileCoverage=this.freezeTileCoverage,e.frustumCorners=this.frustumCorners,e._allowWorldUnderZoom=this._allowWorldUnderZoom,e}get isOrthographic(){return"globe"!==this.projection.name&&this._orthographicProjectionAtLowPitch&&this.pitch<Tu}get elevation(){return this._elevation}set elevation(e){this._elevation!==e&&(this._elevation=e,this._updateCameraOnTerrain(),this._calcMatrices())}get nearClipOffset(){return this._nearClipOffset}set nearClipOffset(e){this._nearClipOffset=e,this._calcMatrices()}get depthOcclusionForSymbolsAndCircles(){return"globe"!==this.projection.name&&!this.isOrthographic}updateElevation(e,t=!1){const i=this._elevation&&this._elevation.exaggeration()!==this._centerAltitudeValidForExaggeration;(null==this._seaLevelZoom||i)&&this._updateCameraOnTerrain(),(e||i)&&this._constrainCamera(t),this._calcMatrices()}getProjection(){return Me(this.projection,["name","center","parallels"])}setProjection(e){this.projectionOptions=e||{name:"mercator"};const t=this.projection?this.getProjection():void 0;this.projection=Is(this.projectionOptions);const i=this.getProjection(),s=!rs(t,i);return s&&this._calcMatrices(),this.mercatorFromTransition=!1,s}setOrthographicProjectionAtLowPitch(e){return this._orthographicProjectionAtLowPitch!==e&&(this._orthographicProjectionAtLowPitch=e,this._calcMatrices(),!0)}setMercatorFromTransition(){const e=this.projection.name;this.mercatorFromTransition=!0,this.projectionOptions={name:"mercator"},this.projection=Is({name:"mercator"});const t=e!==this.projection.name;return t&&this._calcMatrices(),t}get minZoom(){return this._minZoom}set minZoom(e){this._minZoom!==e&&(this._minZoom=e,this.zoom=Math.max(this.zoom,e))}get maxZoom(){return this._maxZoom}set maxZoom(e){this._maxZoom!==e&&(this._maxZoom=e,this.zoom=Math.min(this.zoom,e))}get minPitch(){return this._minPitch}set minPitch(e){this._minPitch!==e&&(this._minPitch=e,this.pitch=Math.max(this.pitch,e))}get maxPitch(){return this._maxPitch}set maxPitch(e){this._maxPitch!==e&&(this._maxPitch=e,this.pitch=Math.min(this.pitch,e))}get renderWorldCopies(){return this._renderWorldCopies&&!0===this.projection.supportsWorldCopies}set renderWorldCopies(e){void 0===e?e=!0:null===e&&(e=!1),this._renderWorldCopies=e}get worldSize(){return this.tileSize*this.scale}get cameraWorldSizeForFog(){const e=Math.max(this._camera.getDistanceToElevation(this._averageElevation),Number.EPSILON);return this._worldSizeFromZoom(this._zoomFromMercatorZ(e))}get cameraWorldSize(){const e=Math.max(this._camera.getDistanceToElevation(this._averageElevation,!0),Number.EPSILON);return this._worldSizeFromZoom(this._zoomFromMercatorZ(e))}get pixelsPerMeter(){return this.projection.pixelsPerMeter(this.center.lat,this.worldSize)}get cameraPixelsPerMeter(){return ws(1,this.center.lat)*this.cameraWorldSizeForFog}get centerOffset(){return this.centerPoint._sub(this.size._div(2))}get size(){return new m(this.width,this.height)}get bearing(){return si(this.rotation,-180,180)}set bearing(e){this.rotation=e}get rotation(){return-this.angle/Math.PI*180}set rotation(e){const t=-e*Math.PI/180;if(this.angle===t)return;this._unmodified=!1,this.angle=t,this._calcMatrices();const i=Math.sin(this.angle),s=Math.cos(this.angle);this.rotationMatrix=[s,i,-i,s]}get pitch(){return this._pitch/Math.PI*180}set pitch(e){const t=Ee(e,this.minPitch,this.maxPitch)/180*Math.PI;this._pitch!==t&&(this._unmodified=!1,this._pitch=t,this._calcMatrices())}get aspect(){return this.width/this.height}get fov(){return this._fov/Math.PI*180}set fov(e){e=Math.max(.01,Math.min(60,e)),this._fov!==e&&(this._unmodified=!1,this._fov=le(e),this._calcMatrices())}get fovX(){return this._fov}get fovY(){const e=1/Math.tan(.5*this.fovX);return 2*Math.atan(1/this.aspect/e)}get horizontalFov(){return Ss(2*Math.atan(Math.tan(.5*this._fov)*this.aspect))}get averageElevation(){return this._averageElevation}set averageElevation(e){this._averageElevation=e,this._calcFogMatrices(),this._distanceTileDataCache.clear()}get zoom(){return this._zoom}set zoom(e){const t=Math.min(Math.max(e,this.minZoom),this.maxZoom);this._zoom!==t&&(this._unmodified=!1,this._setZoom(t),this._updateSeaLevelZoom(),this._constrain(),this._calcMatrices())}_setZoom(e){this._zoom=e,this.scale=this.zoomScale(e),this.tileZoom=Math.floor(e),this.zoomFraction=e-this.tileZoom}get tileCoverLift(){return this._tileCoverLift}set tileCoverLift(e){this._tileCoverLift!==e&&(this._tileCoverLift=e)}_updateCameraOnTerrain(){const e=this.elevation?this.elevation.getAtPoint(this.locationCoordinate(this.center),Number.NEGATIVE_INFINITY):Number.NEGATIVE_INFINITY,t=this.elevation&&e===Number.NEGATIVE_INFINITY&&this.elevation.visibleDemTiles.length>0&&this.elevation.exaggeration()>0&&this._centerAltitudeValidForExaggeration;if(!this._elevation||e===Number.NEGATIVE_INFINITY&&(!t||!this._centerAltitude))return this._centerAltitude=0,this._seaLevelZoom=null,void(this._centerAltitudeValidForExaggeration=void 0);const i=this._elevation;t||this._centerAltitude&&this._centerAltitudeValidForExaggeration&&i.exaggeration()&&this._centerAltitudeValidForExaggeration!==i.exaggeration()?(this._centerAltitude=this._centerAltitude/this._centerAltitudeValidForExaggeration*i.exaggeration(),this._centerAltitudeValidForExaggeration=i.exaggeration()):(this._centerAltitude=e||0,this._centerAltitudeValidForExaggeration=i.exaggeration()),this._updateSeaLevelZoom()}_updateSeaLevelZoom(){if(void 0===this._centerAltitudeValidForExaggeration)return;const e=Math.max(0,(this.pixelsPerMeter*this._centerAltitude+this.cameraToCenterDistance)/this.worldSize);this._seaLevelZoom=this._zoomFromMercatorZ(e)}sampleAverageElevation(){if(!this._elevation)return 0;const e=this._elevation,t=[[.5,.2],[.3,.5],[.5,.5],[.7,.5],[.5,.8]],i=this.horizonLineFromTop();let s=0,o=0;for(let r=0;r<t.length;r++){const n=new m(t[r][0]*this.width,i+t[r][1]*(this.height-i)),a=e.pointCoordinate(n);if(!a)continue;const l=1/Math.hypot(a[0]-this._camera.position[0],a[1]-this._camera.position[1]);s+=a[3]*l,o+=l}return 0===o?NaN:s/o}get center(){return this._center}set center(e){e.lat===this._center.lat&&e.lng===this._center.lng||(this._unmodified=!1,this._center=e,this._terrainEnabled()&&("ground"===this.cameraElevationReference?this._updateCameraOnTerrain():this._updateZoomFromElevation()),this._constrain(),this._calcMatrices())}_updateZoomFromElevation(){if(null==this._seaLevelZoom||!this._elevation)return;const e=this._seaLevelZoom,t=this._elevation.getAtPointOrZero(this.locationCoordinate(this.center)),i=this.pixelsPerMeter/this.worldSize*t,s=this._mercatorZfromZoom(e),o=this._mercatorZfromZoom(this._maxZoom),r=Math.max(s-i,o);this._setZoom(this._zoomFromMercatorZ(r))}get padding(){return this._edgeInsets.toJSON()}set padding(e){this._edgeInsets.equals(e)||(this._unmodified=!1,this._edgeInsets.interpolate(this._edgeInsets,e,1),this._calcMatrices())}equals(e){const t=this.elevation,i=e.elevation,s=null!=t!=(null!=i)||t&&i&&t.exaggeration()!==i.exaggeration();return this.width===e.width&&this.height===e.height&&this.center.lng===e.center.lng&&this.center.lat===e.center.lat&&this.zoom===e.zoom&&this.bearing===e.bearing&&this.pitch===e.pitch&&this.fov===e.fov&&this.projection.name===e.projection.name&&this._edgeInsets.equals(e.padding)&&!s}computeZoomRelativeTo(e){const t=this.rayIntersectionCoordinate(this.pointRayIntersection(this.centerPoint,e.toAltitude()));let i;i=e.z<this._camera.position[2]?[t.x,t.y,t.z]:[e.x,e.y,e.z];const s=_s(ve([],this._camera.position,i));return Ee(this._zoomFromMercatorZ(s),this._minZoom,this._maxZoom)}setFreeCameraOptions(e){if(!this.height)return;if(!e.position&&!e.orientation)return;this._updateCameraState();let t=!1;if(e.orientation&&!Ds(e.orientation,this._camera.orientation)&&(t=this._setCameraOrientation(e.orientation)),e.position){const i=[e.position.x,e.position.y,e.position.z];Rs(i,this._camera.position)||(this._setCameraPosition(i),t=!0)}t&&(this._updateStateFromCamera(),this.recenterOnTerrain())}getFreeCameraOptions(){this._updateCameraState();const e=this._camera.position,t=new bu;return t.position=new we(e[0],e[1],e[2]),t.orientation=this._camera.orientation,t._elevation=this.elevation,t._renderWorldCopies=this.renderWorldCopies,t}_setCameraOrientation(e){if(!Cs(e))return!1;As(e,e);const t=Ls([],[0,0,-1],e),i=Ls([],[0,-1,0],e);if(i[2]<0)return!1;const s=xu(t,i);return!!s&&(this._camera.orientation=s,!0)}_setCameraPosition(e){const t=this.zoomScale(this.minZoom)*this.tileSize,i=this.zoomScale(this.maxZoom)*this.tileSize,s=this.cameraToCenterDistance;e[2]=Ee(e[2],s/i,s/t),this._camera.position=e}get centerPoint(){return this._edgeInsets.getCenter(this.width,this.height)}get fovAboveCenter(){return this._fov*(.5+this.centerOffset.y/this.height)}isPaddingEqual(e){return this._edgeInsets.equals(e)}interpolatePadding(e,t,i){this._unmodified=!1,this._edgeInsets.interpolate(e,t,i),this._constrain(),this._calcMatrices()}coveringZoomLevel(e){const t=(e.roundZoom?Math.round:Math.floor)(this.zoom+this.scaleZoom(this.tileSize/e.tileSize));return Math.max(0,t)}getVisibleUnwrappedCoordinates(e){const t=[new Ps(0,e)];if(this.renderWorldCopies){const i=this.pointCoordinate(new m(0,0)),s=this.pointCoordinate(new m(this.width,0)),o=this.pointCoordinate(new m(this.width,this.height)),r=this.pointCoordinate(new m(0,this.height)),n=Math.floor(Math.min(i.x,s.x,o.x,r.x)),a=Math.floor(Math.max(i.x,s.x,o.x,r.x)),l=1;for(let i=n-l;i<=a+l;i++)0!==i&&t.push(new Ps(i,e))}return t}isLODDisabled(e){return(!e||this.pitch<=60)&&this._edgeInsets.top<=this._edgeInsets.bottom&&!this._elevation&&!this.projection.isReprojectedInTileSpace}extendTileCover(e,t,i,s){let o=[];const r=null!=i,n=!r;if(n&&this.zoom<t)return o;if(r&&0===i[0]&&0===i[1])return o;const a=new Set,l=(e,t,i,s,r)=>{const n=Pt(t,e,i,s,r);a.has(n)||(o.push(new Ge(e,t,i,s,r)),a.add(n))};for(let o=0;o<e.length;o++){const a=e[o];if(n&&a.canonical.z!==t)continue;if(r&&void 0!==s&&s>a.canonical.z)continue;const c=a.canonical,h=a.overscaledZ,d=a.wrap,u=1<<c.z,_=c.x+1<u,p=c.x>0,f=c.y+1<u,m=c.y>0,g=a.wrap-(p?0:1),v=a.wrap+(_?0:1),y=p?c.x-1:u-1,x=_?c.x+1:0;if(r)i[0]<0?(l(h,v,c.z,x,c.y),i[1]<0&&f&&(l(h,d,c.z,c.x,c.y+1),l(h,v,c.z,x,c.y+1)),i[1]>0&&m&&(l(h,d,c.z,c.x,c.y-1),l(h,v,c.z,x,c.y-1))):i[0]>0?(l(h,g,c.z,y,c.y),i[1]<0&&f&&(l(h,d,c.z,c.x,c.y+1),l(h,g,c.z,y,c.y+1)),i[1]>0&&m&&(l(h,d,c.z,c.x,c.y-1),l(h,g,c.z,y,c.y-1))):i[1]<0&&f?l(h,d,c.z,c.x,c.y+1):m&&l(h,d,c.z,c.x,c.y-1);else{const e=a.visibleQuadrants;1&e&&(l(h,g,c.z,y,c.y),m&&(l(h,d,c.z,c.x,c.y-1),l(h,g,c.z,y,c.y-1))),2&e&&(l(h,v,c.z,x,c.y),m&&(l(h,d,c.z,c.x,c.y-1),l(h,v,c.z,x,c.y-1))),4&e&&(l(h,g,c.z,y,c.y),f&&(l(h,d,c.z,c.x,c.y+1),l(h,g,c.z,y,c.y+1))),8&e&&(l(h,v,c.z,x,c.y),f&&(l(h,d,c.z,c.x,c.y+1),l(h,v,c.z,x,c.y+1)))}}const c=[];for(const e of o)o.some(t=>e.isChildOf(t))||c.push(e);if(o=c.filter(i=>!e.some(e=>!!(i.overscaledZ<t&&e.isChildOf(i))||i.equals(e)||i.isChildOf(e))),n){const e=1<<t,i="globe"===this.projection.name?this._camera.mercatorPosition:this.pointCoordinate(this.getCameraPoint()),s=[e*i.x,e*i.y],r=4,n=r*r;o=o.filter(e=>{const t=e.canonical.x+.5-s[0],i=e.canonical.y+.5-s[1];return t*t+i*i<n})}return o}extendTileCoverToNearPlane(e,t,i){const s=[],o=new Set;for(const t of e)o.add(t.key);const r=(e,t,i,r,n)=>{const a=Pt(t,e,i,r,n);o.has(a)||(s.push(new Ge(e,t,i,r,n)),o.add(a))},n=e.reduce((e,t)=>Math.max(e,t.overscaledZ),i),a=1<<i,l=[new m(0,0),new m(ae,0),new m(ae,ae),new m(0,ae)],c=new m(0,0),h=new m(0,0),d=(e,t)=>{const s=Math.floor(e[0]),o=Math.floor(e[1]),d=(e[0]-s)*ae,u=(e[1]-o)*ae,_=Math.floor(t[0]),p=Math.floor(t[1]),f=(t[0]-_)*ae,m=(t[1]-p)*ae;for(let e=-1;e<=1;e++){const t=s+e;if(!(t<0||t>=a)){c.x=d-e*ae,h.x=f-(t-_)*ae;for(let e=-1;e<=1;e++){const s=o+e;c.y=u-e*ae,h.y=m-(s-p)*ae,oo(c,h,l)&&r(n,0,i,t,s)}}}},u=t.points,_=u[ro],p=u[no],f=this._projectToGround(_,u[Ms]),g=this._projectToGround(p,u[Os]);return d(_,f),d(p,g),s}_projectToGround(e,t){return zs(Fs(),e,t,e[2]/(e[2]-t[2]))}_projectToZ(e,t,i){const s=e[2]-t[2];return Math.abs(s)<1e-6?ks(e):zs(Fs(),e,t,(e[2]-i)/s)}extendTileCoverForTunnels(e,t,i,s){if(i<18)return[];const o=t.points,r=o[ao],n=o[lo],a=o[co],l=o[ho];if(a[2]>=0&&l[2]>=0||r[2]<=0||n[2]<=0)return[];const c=a[2]<0?this._projectToZ(r,a,0):a,h=l[2]<0?this._projectToZ(n,l,0):l,d=-s,u=a[2]<d?this._projectToZ(r,a,d):a,_=l[2]<d?this._projectToZ(n,l,d):l,p=this._findExtensionTilesInQuad(e,i,[_,u,h,c],[.5*(c[0]+h[0]),.5*(c[1]+h[1])]);return p.length>3&&(p.length=3),p}_findExtensionTilesInQuad(e,t,i,s){const o=[],r=new Set;for(const t of e)r.add(t.key);const n=e.reduce((e,t)=>Math.max(e,t.overscaledZ),t),a=1<<t,l=[new m(i[0][0],i[0][1]),new m(i[1][0],i[1][1]),new m(i[3][0],i[3][1]),new m(i[2][0],i[2][1]),new m(i[0][0],i[0][1])],c=i[0][0],h=i[1][0],d=i[2][0],u=i[3][0],_=i[0][1],p=i[1][1],f=i[2][1],g=i[3][1],v=Math.max(0,Math.floor(Math.min(c,h,d,u))),y=Math.min(a-1,Math.ceil(Math.max(c,h,d,u))-1),x=Math.max(0,Math.floor(Math.min(_,p,f,g))),b=Math.min(a-1,Math.ceil(Math.max(_,p,f,g))-1);for(let e=x;e<=b;e++)for(let i=v;i<=y;i++){if(!me(l,i,e,i+1,e+1))continue;const s=Pt(0,n,t,i,e);r.has(s)||(o.push(new Ge(n,0,t,i,e)),r.add(s))}const w=s[0],T=s[1];return o.sort((e,t)=>{const i=e.canonical.x+.5-w,s=e.canonical.y+.5-T,o=t.canonical.x+.5-w,r=t.canonical.y+.5-T;return i*i+s*s-(o*o+r*r)||e.canonical.x-t.canonical.x||e.canonical.y-t.canonical.y}),o}coveringTiles(e){let t=this.coveringZoomLevel(e);const i=t,s=this.elevation&&this.elevation.exaggeration(),o=s&&!e.isTerrainDEM,r="mercator"===this.projection.name;if(void 0!==e.minzoom&&t<e.minzoom)return[];void 0!==e.maxzoom&&t>e.maxzoom&&(t=e.maxzoom);const n=this.locationCoordinate(this.center),a=this.center.lat,l=1<<t,c=[l*n.x,l*n.y,0],h="globe"===this.projection.name,d=!h,u=this.getFrustum(t),_=h?this._camera.mercatorPosition:this.pointCoordinate(this.getCameraPoint()),p=l*ws(1,this.center.lat),f=this._camera.position[2]/ws(1,this.center.lat),m=[l*_.x,l*_.y,f*(d?1:p)],g=h||s,v=this._camera.forward(),y=this.cameraToCenterDistance/e.tileSize*(e.roundZoom?1:.502),x=this.isLODDisabled(!0)?t:0;let b;if(this._elevation&&e.isTerrainDEM)b=1e4*this._elevation.exaggeration();else if(this._elevation){const e=this._elevation.getMinMaxForVisibleTiles();b=e?e.max:this._centerAltitude}else b=this._centerAltitude;const w=e.isTerrainDEM?-b:this._elevation?this._elevation.getMinElevationBelowMSL():0,T=this.projection.isReprojectedInTileSpace?Bs(this):1,E=e=>{const t=1/4e4,i=new we(e.x+t,e.y,e.z),s=new we(e.x,e.y+t,e.z),o=e.toLngLat(),r=i.toLngLat(),n=s.toLngLat(),a=this.locationCoordinate(o),l=this.locationCoordinate(r),c=this.locationCoordinate(n),h=Math.hypot(l.x-a.x,l.y-a.y),d=Math.hypot(c.x-a.x,c.y-a.y);return Math.sqrt(h*d)*T/t},I=e=>{const t=b,i=w;return{aabb:Us(this,l,0,0,0,e,i,t,this.projection),zoom:0,x:0,y:0,minZ:i,maxZ:t,wrap:e,fullyVisible:!1}},S=[];let D=[];const R=t,C=e.reparseOverscaled?i:t,A=(f-this._centerAltitude)*p,L=e=>{if(!this._elevation||!e.tileID||!r)return;const t=this._elevation.getMinMaxForTile(e.tileID),i=e.aabb;t?(i.min[2]=t.min,i.max[2]=t.max,i.center[2]=(i.min[2]+i.max[2])/2):(e.shouldSplit=M(e),e.shouldSplit||(i.min[2]=i.max[2]=i.center[2]=this._centerAltitude))},P=(e,t)=>{if(.707*t<e)return 1;const i=t/e;return i/(1.4144271570014144+(Math.pow(1.1,i-1.4144271570014144+1)-1)/(1.1-1)-1)},M=e=>{if(e.zoom<x)return!0;if(e.zoom===R)return!1;if(null!=e.shouldSplit)return e.shouldSplit;const t=e.aabb.distanceX(m),s=e.aabb.distanceY(m);let n=A,l=1;if(h){n=e.aabb.distanceZ(m);const t=Math.pow(2,e.zoom),i=at((e.y+1)/t),s=at(e.y/t),o=Math.min(Math.max(a,i),s),r=mo(o)/mo(a);if(l=o===a?1/Math.max(1,this._mercatorScaleRatio-.3):Math.min(1,r/this._mercatorScaleRatio),this.zoom<=uo&&e.zoom===R-1&&r>=.9)return!0}else if(o&&(n=e.aabb.distanceZ(m)*p),this.projection.isReprojectedInTileSpace&&i<=5){const t=Math.pow(2,e.zoom),i=E(new we((e.x+.5)/t,(e.y+.5)/t));l=i>.85?1:i}if(!r&&!h){const i=Math.sqrt(t*t+s*s+n*n);let o=(1<<R-e.zoom)*y*l;return o*=P(Math.max(n,A),i),i<o}let d=Number.MAX_VALUE,u=0;const{min:_,max:f}=e.aabb;for(let e=0;e<8;e++){const t=3&e;let i=(e>=4?f[2]:_[2])-m[2];h||(i=o?i*p:A);const s=((1===t||2===t?f[0]:_[0])-m[0])*v[0]+((t>=2?f[1]:_[1])-m[1])*v[1]+i*v[2];s<d&&(d=s,u=Math.abs(i))}let g=(1<<R-e.zoom)*y*l;if(g*=P(Math.max(u,A),d),d<g)return!0;const b=e.aabb.closestPoint(c);return b[0]===c[0]&&b[1]===c[1]};if(this.renderWorldCopies)for(let e=1;e<=3;e++)S.push(I(-e)),S.push(I(e));for(S.push(I(0));S.length>0;){const i=S.pop(),s=i.x,n=i.y;let a=i.fullyVisible;const d=()=>"globe"===this.projection.name&&(0===i.y||i.y===(1<<i.zoom)-1);if(!a){let e=g?i.aabb.intersects(u):i.aabb.intersectsFlat(u);if(0===e&&d()){const t=new $e(i.zoom,s,n);e=Ns(this,l,t,!0).intersects(u)}if(0===e)continue;a=2===e}if(i.zoom===R||!M(i)){const o=i.zoom===R?C:i.zoom;if(e.minzoom&&e.minzoom>o)continue;let r=0;if(!a){let t=g?i.aabb.intersectsPrecise(u):i.aabb.intersectsPreciseFlat(u);if(0===t&&d()){const e=new $e(i.zoom,s,n);t=Ns(this,l,e,!0).intersectsPrecise(u)}if(0===t)continue;if(e.calculateQuadrantVisibility)if(u.containsPoint(i.aabb.center))r=15;else for(let e=0;e<4;e++)0!==i.aabb.quadrant(e).intersects(u)&&(r|=1<<e)}const h=c[0]-(.5+s+(i.wrap<<i.zoom))*(1<<t-i.zoom),_=c[1]-.5-n,p=i.tileID?i.tileID:new Ge(o,i.wrap,i.zoom,s,n);e.calculateQuadrantVisibility&&(p.visibleQuadrants=r),D.push({tileID:p,distanceSq:h*h+_*_});continue}for(let e=0;e<4;e++){const t=(s<<1)+e%2,c=(n<<1)+(e>>1),d={aabb:r?i.aabb.quadrant(e):Us(this,l,i.zoom+1,t,c,i.wrap,i.minZ,i.maxZ,this.projection),zoom:i.zoom+1,x:t,y:c,wrap:i.wrap,fullyVisible:a,tileID:void 0,shouldSplit:void 0,minZ:i.minZ,maxZ:i.maxZ};o&&!h&&(d.tileID=new Ge(i.zoom+1===R?C:i.zoom+1,i.wrap,i.zoom+1,t,c),L(d)),S.push(d)}}if(this.fogCullDistSq){const t=this.fogCullDistSq,i=this.horizonLineFromTop();D=D.filter(s=>{const o=[0,0,0,1],r=[ae,ae,0,1],n=this.calculateFogTileMatrix(s.tileID.toUnwrapped());Se(o,o,n),Se(r,r,n);const a=Vs([],o,r),l=js([],o,r),c=_o(a,l);if(0===c)return!0;let h=!1;const d=this._elevation;if(d&&c>t&&0!==i){const t=this.calculateProjMatrix(s.tileID.toUnwrapped());let o;e.isTerrainDEM||(o=d.getMinMaxForTile(s.tileID)),o||(o={min:w,max:b});const r=go(this.rotation),n=[r[0]*ae,r[1]*ae,o.max];It(n,n,t),h=(1-n[1])*this.height*.5<i}return c<t||h})}return D.sort((e,t)=>e.distanceSq-t.distanceSq).map(e=>e.tileID)}resize(e,t){this.width=e,this.height=t,this.pixelsToGLUnits=[2/e,-2/t],this._constrain(),this._calcMatrices()}get unmodified(){return this._unmodified}zoomScale(e){return Math.pow(2,e)}scaleZoom(e){return Math.log2(e)}project(e){const t=Ee(e.lat,-We,We),i=this.projection.project(e.lng,t);return new m(i.x*this.worldSize,i.y*this.worldSize)}unproject(e){return this.projection.unproject(e.x/this.worldSize,e.y/this.worldSize)}get point(){return this.project(this.center)}get pointMerc(){return this.point._div(this.worldSize)}get pixelsPerMeterRatio(){return this.pixelsPerMeter/ws(1,this.center.lat)/this.worldSize}setLocationAtPoint(e,t){let i,s;const o=this.centerPoint;if("globe"===this.projection.name){const e=this.worldSize;i=(t.x-o.x)/e,s=(t.y-o.y)/e}else{const e=this.pointCoordinate(t),r=this.pointCoordinate(o);i=e.x-r.x,s=e.y-r.y}const r=this.locationCoordinate(e);this.setLocation(new we(r.x-i,r.y-s))}setLocation(e){this.center=this.coordinateLocation(e),this.projection.wrap&&(this.center=this.center.wrap())}locationPoint(e,t){return this.projection.locationPoint(this,e,t)}locationPoint3D(e,t){return this.projection.locationPoint(this,e,t,!0)}pointLocation(e){return this.coordinateLocation(this.pointCoordinate(e))}pointLocation3D(e,t){return this.coordinateLocation(this.pointCoordinate3D(e,t))}locationCoordinate(e,t){const i=t?ws(t,e.lat):void 0,s=this.projection.project(e.lng,e.lat);return new we(s.x,s.y,i)}coordinateLocation(e){return this.projection.unproject(e.x,e.y)}pointRayIntersection(e,t){const i=t??this._centerAltitude,s=[e.x,e.y,0,1],o=[e.x,e.y,1,1];Se(s,s,this.pixelMatrixInverse),Se(o,o,this.pixelMatrixInverse);const r=o[3];Gs(s,s,1/s[3]),Gs(o,o,1/r);const n=s[2],a=o[2];return{p0:s,p1:o,t:n===a?0:(i-n)/(a-n)}}screenPointToMercatorRay(e){const t=[e.x,e.y,0,1],i=[e.x,e.y,1,1];return Se(t,t,this.pixelMatrixInverse),Se(i,i,this.pixelMatrixInverse),Gs(t,t,1/t[3]),Gs(i,i,1/i[3]),t[2]=ws(t[2],this._center.lat)*this.worldSize,i[2]=ws(i[2],this._center.lat)*this.worldSize,Gs(t,t,1/this.worldSize),Gs(i,i,1/this.worldSize),new xe([t[0],t[1],t[2]],ye([],ve([],i,t)))}rayIntersectionCoordinate(e){const{p0:t,p1:i,t:s}=e,o=ws(t[2],this._center.lat),r=ws(i[2],this._center.lat);return new we(J(t[0],i[0],s)/this.worldSize,J(t[1],i[1],s)/this.worldSize,J(o,r,s))}pointCoordinate(e,t=this._centerAltitude){return this.projection.pointCoordinate(this,e.x,e.y,t)}pointCoordinate3D(e,t){if(!this.elevation)return this.pointCoordinate(e,t);let i=this.projection.pointCoordinate3D(this,e.x,e.y);if(i)return new we(i[0],i[1],i[2]);let s=0,o=this.horizonLineFromTop();if(e.y>o)return this.pointCoordinate(e,t);const r=.02*o,n=e.clone();for(let e=0;e<10&&o-s>r;e++){n.y=J(s,o,.66);const e=this.projection.pointCoordinate3D(this,n.x,n.y);e?(o=n.y,i=e):s=n.y}return i?new we(i[0],i[1],i[2]):this.pointCoordinate(e)}isPointAboveHorizon(e){return this.projection.isPointAboveHorizon(this,e)}isPointOnSurface(e){if(e.y<0||e.y>this.height||e.x<0||e.x>this.width)return!1;if(this.elevation||this.zoom>=qs)return!this.isPointAboveHorizon(e);const t=this.pointCoordinate(e);return t.y>=0&&t.y<=1}_coordinatePoint(e,t){const i=t&&this.elevation?this.elevation.getAtPointOrZero(e,this._centerAltitude):this._centerAltitude,s=[e.x*this.worldSize,e.y*this.worldSize,i+e.toAltitude(),1];return Se(s,s,this.pixelMatrix),s[3]>0?new m(s[0]/s[3],s[1]/s[3]):new m(Number.MAX_VALUE,Number.MAX_VALUE)}_getBoundsNonRectangular(){const{top:e,left:t}=this._edgeInsets,i=this.height-this._edgeInsets.bottom,s=this.width-this._edgeInsets.right,o=this.pointLocation3D(new m(t,e)),r=this.pointLocation3D(new m(s,e)),n=this.pointLocation3D(new m(s,i)),a=this.pointLocation3D(new m(t,i));let l=Math.min(o.lng,r.lng,n.lng,a.lng),c=Math.max(o.lng,r.lng,n.lng,a.lng),h=Math.min(o.lat,r.lat,n.lat,a.lat),d=Math.max(o.lat,r.lat,n.lat,a.lat);const u=Math.pow(2,-this.zoom)/16*270,_="globe"===this.projection.name?1:4,p=(e,t,i,s,o)=>{const r=(e+i)/2,n=(t+s)/2,a=new m(r,n),{lng:f,lat:g}=this.pointLocation3D(a),v=Math.max(0,l-f,h-g,f-c,g-d);l=Math.min(l,f),c=Math.max(c,f),h=Math.min(h,g),d=Math.max(d,g),(o<_||v>u)&&(p(e,t,r,n,o+1),p(r,n,i,s,o+1))};if(p(t,e,s,e,1),p(s,e,s,i,1),p(s,i,t,i,1),p(t,i,t,e,1),"globe"===this.projection.name){const[e,t]=Zs(this);e?(d=90,c=180,l=-180):t&&(h=-90,c=180,l=-180)}return new Le(new Es(l,h),new Es(c,d))}_getBoundsRectangular(e,t){const{top:i,left:s}=this._edgeInsets,o=this.height-this._edgeInsets.bottom,r=this.width-this._edgeInsets.right,n=new m(s,i),a=new m(r,i),l=new m(r,o),c=new m(s,o);let h=this.pointCoordinate(n,e),d=this.pointCoordinate(a,e);const u=this.pointCoordinate(l,t),_=this.pointCoordinate(c,t),p=(e,t)=>(t.y-e.y)/(t.x-e.x);return h.y>1&&d.y>=0?h=new we((1-_.y)/p(_,h)+_.x,1):h.y<0&&d.y<=1&&(h=new we(-_.y/p(_,h)+_.x,0)),d.y>1&&h.y>=0?d=new we((1-u.y)/p(u,d)+u.x,1):d.y<0&&h.y<=1&&(d=new we(-u.y/p(u,d)+u.x,0)),(new Le).extend(this.coordinateLocation(h)).extend(this.coordinateLocation(d)).extend(this.coordinateLocation(_)).extend(this.coordinateLocation(u))}_getBoundsRectangularTerrain(){const e=this.elevation;if(!e.visibleDemTiles.length||e.isUsingMockSource())return this._getBoundsRectangular(0,0);const t=e.visibleDemTiles.reduce((e,t)=>{if(t.dem){const i=t.dem.tree;e.min=Math.min(e.min,i.minimums[0]),e.max=Math.max(e.max,i.maximums[0])}return e},{min:Number.MAX_VALUE,max:0});return this._getBoundsRectangular(t.min*e.exaggeration(),t.max*e.exaggeration())}getBounds(){return"mercator"===this.projection.name||"equirectangular"===this.projection.name?this._terrainEnabled()?this._getBoundsRectangularTerrain():this._getBoundsRectangular(0,0):this._getBoundsNonRectangular()}horizonLineFromTop(e=!0){const t=this.height/2/Math.tan(this._fov/2)/Math.tan(Math.max(this._pitch,.1))-this.centerOffset.y,i=this.height/2-t*(1-this._horizonShift);return e?Math.max(0,i):i}getMaxBounds(){return this.maxBounds}setMaxBounds(e){this.maxBounds=e,this.minLat=-We,this.maxLat=We,this.minLng=-180,this.maxLng=180,e&&(this.minLat=e.getSouth(),this.maxLat=e.getNorth(),this.minLng=e.getWest(),this.maxLng=e.getEast(),this.maxLng<this.minLng&&(this.maxLng+=360)),this.worldMinX=Ae(this.minLng)*this.tileSize,this.worldMaxX=Ae(this.maxLng)*this.tileSize,this.worldMinY=Pe(this.maxLat)*this.tileSize,this.worldMaxY=Pe(this.minLat)*this.tileSize,this._constrain()}calculatePosMatrix(e){let t=this._posMatrixCache.get(e.key);return t||(t=this.projection.createTileMatrix(this,this.worldSize,e),this._posMatrixCache.set(e.key,t)),t}calculateDistanceTileData(e){const t=this._distanceTileDataCache.get(e.key);if(t)return t;const i=e.canonical,s=1/this.height,o=this.cameraWorldSize,r=o/this.zoomScale(i.z),n=(i.x+Math.pow(2,i.z)*e.wrap)*r,a=i.y*r,l=this.point;l.x*=o/this.worldSize,l.y*=o/this.worldSize;const c=this.angle,h={bearing:[Math.sin(-c),-Math.cos(-c)],center:[(l.x-n)*s,(l.y-a)*s],scale:r/ae*s};return this._distanceTileDataCache.set(e.key,h),h}calculateFogTileMatrix(e){const t=this._fogTileMatrixCache.get(e.key);if(t)return t;const i=this.projection.createTileMatrix(this,this.cameraWorldSizeForFog,e);Ie(i,this.worldToFogMatrix,i);const s=new Float32Array(i);return this._fogTileMatrixCache.set(e.key,s),s}calculateProjMatrix(e,t=!1,i=!1){const s=i?this._expandedProjMatrixCache:t?this._alignedProjMatrixCache:this._projMatrixCache,o=s.get(e.key);if(o)return o;let r;r=this.projection.isReprojectedInTileSpace?this.mercatorMatrix:i?this.expandedFarZProjMatrix:t?this.alignedProjMatrix:this.projMatrix;const n=Ie(new Float32Array(16),r,this.calculatePosMatrix(e));return s.set(e.key,n),n}calculatePixelsToTileUnitsMatrix(e){const t=this._pixelsToTileUnitsCache.get(e.tileID.key);if(t)return t;const i=po(e,this);return this._pixelsToTileUnitsCache.set(e.tileID.key,i),i}customLayerMatrix(){return this.mercatorMatrix.slice()}globeToMercatorMatrix(){if("globe"===this.projection.name){const e=1/this.worldSize,t=Ct([],[e,e,e]);return Ie(t,t,this.globeMatrix),t}}recenterOnTerrain(){if(!this._elevation||"globe"===this.projection.name)return;const e=this._elevation;this._updateCameraState();const t=ws(1,this._center.lat)*this.worldSize,i=this._computeCameraPosition(t),s=this._camera.forward(),o=ws(1,this._center.lat);i[2]/=o,s[2]/=o,ye(s,s);const r=e.raycast(i,s,e.exaggeration());if(r){const e=Wt([],i,s,r),t=new we(e[0],e[1],ws(e[2],at(e[1]))),n=(t.z+_s([t.x-i[0],t.y-i[1],t.z-i[2]*o]))*this._pixelsPerMercatorPixel;this._seaLevelZoom=this._zoomFromMercatorZ(n),this._centerAltitude=t.toAltitude(),this._center=this.coordinateLocation(t),this._updateZoomFromElevation(),this._constrain(),this._calcMatrices()}}_constrainCamera(e=!1){if(!this._elevation)return;const t=this._elevation,i=ws(1,this._center.lat)*this.worldSize,s=this._computeCameraPosition(i),o=t.getAtPointOrZero(new we(...s)),r=this.pixelsPerMeter/this.worldSize*o,n=this._minimumHeightOverTerrain(),a=s[2]-r;if(a<=n)if(a<0||e){const e=this.locationCoordinate(this._center,this._centerAltitude),t=[s[0],s[1],e.z-s[2]],i=_s(t);t[2]-=(n-a)/this._pixelsPerMercatorPixel;const o=_s(t);if(0===o)return;Ti(t,t,i/o*this._pixelsPerMercatorPixel),this._camera.position=[s[0],s[1],e.z*this._pixelsPerMercatorPixel-t[2]],this._updateStateFromCamera()}else this._isCameraConstrained=!0}_constrain(){if(!this.center||!this.width||!this.height||this._constraining)return;this._constraining=!0;const e="globe"===this.projection.name||this.mercatorFromTransition;if(this.projection.isReprojectedInTileSpace||e){const t=this.center;return t.lat=Ee(t.lat,this.minLat,this.maxLat),(this.maxBounds||!this.renderWorldCopies&&!e)&&(t.lng=Ee(t.lng,this.minLng,this.maxLng)),this.center=t,void(this._constraining=!1)}const t=this._unmodified,{x:i,y:s}=this.point;let o=0,r=i,n=s;const a=this.width/2,l=this.height/2,c=this.worldMinY*this.scale,h=this.worldMaxY*this.scale;if(s-l<c&&(n=c+l),s+l>h&&(n=h-l),h-c<this.height&&(o=Math.max(o,this.height/(h-c)),n=(h+c)/2),this.maxBounds||!this._renderWorldCopies||!this.projection.wrap){const e=this.worldMinX*this.scale,t=this.worldMaxX*this.scale,s=this.worldSize/2-(e+t)/2;r=(i+s+this.worldSize)%this.worldSize-s,r-a<e&&(r=e+a),r+a>t&&(r=t-a),t-e<this.width&&(o=Math.max(o,this.width/(t-e)),r=(t+e)/2)}r===i&&n===s||this._allowWorldUnderZoom||(this.center=this.unproject(new m(r,n))),o&&!this._allowWorldUnderZoom&&(this.zoom+=this.scaleZoom(o)),this._constrainCamera(),this._unmodified=t,this._constraining=!1}_minZoomForBounds(){let e=Math.max(0,this.scaleZoom(Math.max(0,this.height)/(this.worldMaxY-this.worldMinY)));return this.maxBounds&&(e=Math.max(e,this.scaleZoom(this.width/(this.worldMaxX-this.worldMinX)))),e}_maxCameraBoundsDistance(){return this._mercatorZfromZoom(this._minZoomForBounds())}_calcMatrices(){if(!this.height)return;const e=this.centerOffset,t="globe"===this.projection.name,i=this.pixelsPerMeter;"globe"===this.projection.name&&(this._mercatorScaleRatio=ws(1,this.center.lat)/ws(1,vo));const s=Ws(this.projection,this.zoom,this.width,this.height,1024);this._pixelsPerMercatorPixel=this.projection.pixelSpaceConversion(this.center.lat,this.worldSize,s),this.cameraToCenterDistance=.5/Math.tan(.5*this._fov)*this.height*this._pixelsPerMercatorPixel,this._updateCameraState(),this._farZ=this.projection.farthestPixelDistance(this),this._nearZ=this.height/50;const o="meters"===this.projection.zAxisUnit?i:1,r=this._camera.getWorldToCamera(this.worldSize,o);let n;const a=this._camera.getCameraToClipPerspective(this._fov,this.width/this.height,this._nearZ,this._farZ);if(a[8]=2*-e.x/this.width,a[9]=2*e.y/this.height,this.isOrthographic){let t=.5*this.height/Math.tan(this._fov/2)*1*Math.tan(.5*this._fov),i=t*this.aspect,s=-i,o=-t;i-=e.x,s-=e.x,t+=e.y,o+=e.y,n=this._camera.getCameraToClipOrthographic(s,i,o,t,this._nearZ+this._nearClipOffset,this._farZ),((e,t,i,s)=>{for(let o=0;o<16;o++)e[o]=J(t[o],i[o],s)})(n,n,a,fo(this.pitch>=Tu?1:this.pitch/Tu))}else n=a;this._cameraToClip=n;const l=Hs(new Float64Array(16),a,r),c=Hs(new Float64Array(16),n,r);if(this.projection.isReprojectedInTileSpace){const e=this.locationCoordinate(this.center);ci(this._mat4Scratch);const t=this._mat4Scratch;At(t,t,[e.x*this.worldSize,e.y*this.worldSize,0]),Ie(t,t,$s(this)),At(t,t,[-e.x*this.worldSize,-e.y*this.worldSize,0]),Ie(c,c,t),Ie(l,l,t),this.inverseAdjustmentMatrix=Xs(this)}else this.inverseAdjustmentMatrix=[1,0,0,1];if(Ys(this.mercatorMatrix,c,[this.worldSize,this.worldSize,this.worldSize/o,1]),this.projMatrix=c,Tt(this.invProjMatrix,this.projMatrix),this._frustumCache.clear(),t){const t=this._camera.getCameraToClipPerspective(this._fov,this.width/this.height,this._nearZ,1/0);t[8]=2*-e.x/this.width,t[9]=2*e.y/this.height,Hs(this._expandedFarZProjMatrixBuf,t,r),this.expandedFarZProjMatrix=this._expandedFarZProjMatrixBuf}else this.expandedFarZProjMatrix=this.projMatrix;Tt(this._mat4Scratch,n),this.frustumCorners=Ks.fromInvProjectionMatrix(this._mat4Scratch,this.horizonLineFromTop(),this.height),Ct(this.skyboxMatrix,[1,-1,1]),Js(this.skyboxMatrix,this.skyboxMatrix,this._pitch),kt(this.skyboxMatrix,this.skyboxMatrix,this.angle),xs(this.starsProjMatrix,this._fov,this.width/this.height,this._nearZ,this._farZ);const h=(Math.PI/2-this._pitch)*(this.height/this._fov)*this._horizonShift;Qs(this._mat4Scratch,this.starsProjMatrix),this._mat4Scratch[8]=2*-e.x/this.width,this._mat4Scratch[9]=2*(e.y+h)/this.height,Ie(this.skyboxMatrix,this._mat4Scratch,this.skyboxMatrix);const d=this.point,u=d.x,_=d.y,p=this.width%2/2,f=this.height%2/2,m=Math.cos(this.angle),g=Math.sin(this.angle),v=u-Math.round(u)+m*p+g*f,y=_-Math.round(_)+m*f+g*p;if(Qs(this.alignedProjMatrix,c),At(this.alignedProjMatrix,this.alignedProjMatrix,[v>.5?v-1:v,y>.5?y-1:y,0]),Ct(this.labelPlaneMatrix,[this.width/2,-this.height/2,1]),At(this.labelPlaneMatrix,this.labelPlaneMatrix,[1,-1,0]),Ct(this.glCoordMatrix,[1,-1,1]),At(this.glCoordMatrix,this.glCoordMatrix,[-1,-1,0]),Ys(this.glCoordMatrix,this.glCoordMatrix,[2/this.width,2/this.height,1]),Ie(this.pixelMatrix,this.labelPlaneMatrix,l),this._calcFogMatrices(),this._distanceTileDataCache.clear(),!Tt(this.pixelMatrixInverse,this.pixelMatrix))throw new Error("failed to invert matrix");if("globe"===this.projection.name||this.mercatorFromTransition){this.globeMatrix=eo(this);const e=[this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]];this.globeCenterInViewSpace=It(e,e,r),this.globeRadius=this.worldSize/2/Math.PI-1}else this.globeMatrix=this.pixelMatrixInverse;this._worldToCamera="globe"===this.projection.name?Ie(new Float64Array(16),r,this.globeMatrix):r,this._posMatrixCache.clear(),this._projMatrixCache.clear(),this._alignedProjMatrixCache.clear(),this._pixelsToTileUnitsCache.clear(),this._expandedProjMatrixCache.clear()}_calcFogMatrices(){this._fogTileMatrixCache.clear();const e=this.cameraWorldSizeForFog,t=this.cameraPixelsPerMeter,i=this._camera.position,s=1/this.height/this._pixelsPerMercatorPixel,o=[e,e,t];Ti(o,o,s),Ti(i,i,-1),to(i,i,o),io(this.mercatorFogMatrix,i),Ys(this.mercatorFogMatrix,this.mercatorFogMatrix,o),this.worldToFogMatrix=this._camera.getWorldToCameraPosition(e,t,s)}_computeCameraPosition(e){const t=(e=e||this.pixelsPerMeter)/this.pixelsPerMeter,i=this._camera.forward(),s=this.point,o=this._mercatorZfromZoom(this._seaLevelZoom?this._seaLevelZoom:this._zoom)*t-e/this.worldSize*this._centerAltitude;return[s.x/this.worldSize-i[0]*o,s.y/this.worldSize-i[1]*o,e/this.worldSize*this._centerAltitude-i[2]*o]}_updateCameraState(){this.height&&(this._camera.setPitchBearing(this._pitch,this.angle),this._camera.position=this._computeCameraPosition())}_translateCameraConstrained(e){const t=this._maxCameraBoundsDistance()*Math.cos(this._pitch),i=this._camera.position[2],s=e[2];let o=1;this.projection.wrap&&(this.center=this.center.wrap()),s>0&&(o=Math.min((t-i)/s,1)),this._camera.position=Wt([],this._camera.position,e,o),this._updateStateFromCamera()}_updateStateFromCamera(){const e=this._camera.position,t=this._camera.forward(),{pitch:i,bearing:s}=this._camera.getPitchBearing(),o=ws(this._centerAltitude,this.center.lat)*this._pixelsPerMercatorPixel,r=this._mercatorZfromZoom(this._maxZoom)*Math.cos(le(this._maxPitch)),n=Math.max((e[2]-o)/Math.cos(i),r),a=this._zoomFromMercatorZ(n);Wt(e,e,t,n),this._pitch=Ee(i,le(this.minPitch),le(this.maxPitch)),this.angle=si(s,-Math.PI,Math.PI),this._setZoom(Ee(a,this._minZoom,this._maxZoom)),this._updateSeaLevelZoom(),this._center=this.coordinateLocation(new we(e[0],e[1],e[2])),this._unmodified=!1,this._constrain(),this._calcMatrices()}_worldSizeFromZoom(e){return Math.pow(2,e)*this.tileSize}_mercatorZfromZoom(e){return this.cameraToCenterDistance/this._worldSizeFromZoom(e)}_minimumHeightOverTerrain(){const e=Math.min(this._seaLevelZoom??this._zoom,this._maxZoom)+4;return this._mercatorZfromZoom(e)}_zoomFromMercatorZ(e){return this.scaleZoom(this.cameraToCenterDistance/(Math.max(0,e)*this.tileSize))}zoomFromMercatorZAdjusted(e){let t=0,i=qs,s=0,o=1/0;for(;i-t>1e-6&&i>t;){const r=t+.5*(i-t),n=this.tileSize*Math.pow(2,r),a=this.getCameraToCenterDistance(this.projection,r,n),l=this.scaleZoom(a/(Math.max(0,e)*this.tileSize)),c=Math.abs(r-l);c<o&&(o=c,s=r),r<l?t=r:i=r}return s}_terrainEnabled(){return!(!this._elevation||!this.projection.supportsTerrain&&(_("Terrain is not yet supported with alternate projections. Use mercator or globe to enable terrain."),1))}anyCornerOffEdge(e,t){const i=Math.min(e.x,t.x),s=Math.max(e.x,t.x),o=Math.min(e.y,t.y),r=Math.max(e.y,t.y);if(o<this.horizonLineFromTop(!1))return!0;if("mercator"!==this.projection.name)return!1;const n=[new m(i,o),new m(s,r),new m(i,r),new m(s,o)],a=this.renderWorldCopies?-3:0,l=this.renderWorldCopies?4:1;for(const e of n){const t=this.pointRayIntersection(e);if(t.t<0)return!0;const i=this.rayIntersectionCoordinate(t);if(i.x<a||i.y<0||i.x>l||i.y>1)return!0}return!1}isHorizonVisible(){return this.pitch+Ss(this.fovAboveCenter)>88||this.anyCornerOffEdge(new m(0,0),new m(this.width,this.height))}zoomDeltaToMovement(e,t){const i=_s(ve([],this._camera.position,e)),s=this._zoomFromMercatorZ(i)+t;return i-this._mercatorZfromZoom(s)}getCameraPoint(){if("globe"===this.projection.name){const e=function([e,t,i],s){const o=[e,t,i,1];Se(o,o,s);const r=o[3]=Math.max(o[3],1e-6);return o[0]/=r,o[1]/=r,o[2]/=r,o}([this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]],this.pixelMatrix);return new m(e[0],e[1])}{const e=Math.tan(this._pitch)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new m(0,e))}}getCameraToCenterDistance(e,t=this.zoom,i=this.worldSize){const s=Ws(e,t,this.width,this.height,1024),o=e.pixelSpaceConversion(this.center.lat,i,s);let r=.5/Math.tan(.5*this._fov)*this.height*o;return this.isOrthographic&&(r=J(1,r,fo(this.pitch>=Tu?1:this.pitch/Tu))),r}getWorldToCameraMatrix(){return this._worldToCamera}getCameraToClipMatrix(){return this._cameraToClip}getFrustum(e){let t=this._frustumCache.get(e);return t||(t=so.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,e,"meters"===this.projection.zAxisUnit),this._frustumCache.set(e,t)),t}get cameraFrustum(){return this.getFrustum(0)}}const Iu=(e,t)=>{if(t<=0||e.terrain)return{shouldRenderCutoff:!1,uniformValues:{u_cutoff_params:[0,0,0,1]}};const i=e.transform,s=i.pitch,o=i.isLODDisabled(!1)?60:30;if(s<o-15)return{shouldRenderCutoff:!1,uniformValues:{u_cutoff_params:[0,0,0,1]}};const r=i._farZ-i._nearZ,n=t*i.height*1.3,a=Math.pow(2,.85*Math.max(i._zoom-e.minCutoffZoom,0)),l=1.4*i.cameraToCenterDistance*a,c=Q(o-15,o,s),h=J(i._farZ+n,l,c),d=Math.min(n,h-i._nearZ);return{shouldRenderCutoff:c>0,uniformValues:{u_cutoff_params:[i._nearZ,i._farZ,(h-i._nearZ)/r,(h-d-i._nearZ)/r]}}};function Su(e,t,i){const s=function(e,t,i){const s=Kt(t,e),o=Kt(i,[.2126,.7152,.0722]),r=1-.3*Math.min(o,1),n=J(r,1,Math.min(s+1,1));return J(.92,1,Math.asin(Ee(t[2],-1,1))/Math.PI+.5)*n}(e,[0,0,1],t),o=[0,0,0];Ti(o,i.slice(0,3),s);const r=[0,0,0];Ti(r,t.slice(0,3),e[2]);const n=[0,0,0];return yo(n,o,r),Ei(n)}const Du=(e,t,i,s)=>{const o=e.properties.get("direction"),r="none"===e.properties.get("color-use-theme"),n=e.properties.get("color").toNonPremultipliedRenderColor(r?null:i.getLut(e.scope)).toArray01();let a=e.properties.get("intensity");const l="none"===t.properties.get("color-use-theme"),c=t.properties.get("color").toNonPremultipliedRenderColor(l?null:i.getLut(t.scope)).toArray01();let h=t.properties.get("intensity");const d=[o.x,o.y,o.z];s&&(void 0!==s.ambientIntensity&&(h=s.ambientIntensity),void 0!==s.directionalIntensity&&(a=s.directionalIntensity),void 0!==s.ambientColor&&(c[0]=s.ambientColor[0],c[1]=s.ambientColor[1],c[2]=s.ambientColor[2]),void 0!==s.directionalColor&&(n[0]=s.directionalColor[0],n[1]=s.directionalColor[1],n[2]=s.directionalColor[2]));const u=xo(c,h),_=xo(n,a);return{u_lighting_ambient_color:u,u_lighting_directional_dir:d,u_lighting_directional_color:_,u_ground_radiance:Su(d,_,u)}};function Ru(){return{u_light_matrix_0:new Float32Array(16),u_light_matrix_1:new Float32Array(16),u_shadow_intensity:0,u_fade_range:[0,0],u_shadow_normal_offset:[1,1,1],u_shadow_texel_size:1,u_shadow_map_resolution:1,u_shadow_direction:[0,0,1],u_shadow_bias:[36e-5,.0012,.012],u_shadowmap_0:0,u_shadowmap_1:0}}class Cu{constructor(e,t,i){this.func=e,this.mask=t,this.range=i}}Cu.ReadOnly=!1,Cu.ReadWrite=!0,Cu.disabled=new Cu(519,Cu.ReadOnly,[0,1]);const Au=7680,Lu=128;class Pu{constructor(e,t,i,s,o,r){this.test=e,this.ref=t,this.mask=i,this.fail=s,this.depthFail=o,this.pass=r}}Pu.disabled=new Pu({func:519,mask:0},0,0,Au,Au,Au);const Mu=770,Ou=771;class zu{constructor(e,t,i,s){this.blendFunction=e,this.blendColor=t.toNonPremultipliedRenderColor(null),this.mask=i,this.blendEquation=s}}zu.Replace=[1,0,1,0],zu.disabled=new zu(zu.Replace,S.transparent,[!1,!1,!1,!1]),zu.unblended=new zu(zu.Replace,S.transparent,[!0,!0,!0,!0]),zu.alphaBlended=new zu([1,Ou,1,Ou],S.transparent,[!0,!0,!0,!0]),zu.alphaBlendedNonPremultiplied=new zu([Mu,Ou,Mu,Ou],S.transparent,[!0,!0,!0,!0]),zu.multiply=new zu([774,0,774,0],S.transparent,[!0,!0,!0,!0]),zu.multiplyAccumulateAlpha=new zu([774,0,1,Ou],S.transparent,[!0,!0,!0,!0]),zu.additive=new zu([1,1,1,1],S.transparent,[!0,!0,!0,!0]),zu.additiveAlphaWeighted=new zu([Mu,1,773,1],S.transparent,[!0,!0,!0,!0]),zu.additiveAlphaWeightedUnboundedAlpha=new zu([Mu,1,1,1],S.transparent,[!0,!0,!0,!0]);const Fu=["fill","fillOutline","fillPattern","line","linePattern","background","backgroundPattern","hillshade","raster"],ku=["stars","rainParticle","snowParticle","fillExtrusion","fillExtrusionGroundEffect","building","buildingBloom","elevatedStructures","model","symbol"];function Bu(e,t,i){for(const s of i)(s.includes(" ")||t.usedDefines.has(s))&&(e+=`/${s}`);return e}let Nu=class{static cacheKey(e,t,i,s,o){let r=t;return o&&(r+=`/${o.cacheKey}`),r=Bu(r,e,i),s?Bu(r,e,s):r}constructor(e,t,i,s,o,r,n=!1){const a=e.gl;this.program=a.createProgram(),this._context=e,this._fixedUniformsFn=o,this._pending=!0,this._precompiled=n,this.attributes={},this.configuration=s,this.name=t,this.fixedDefines=[...r],n?e._compileStats.precompiled++:e._compileStats.onDemand++;const l=`#version 300 es\n${(s?s.defines():[]).concat(r.map(e=>`#define ${e}`)).join("\n")}`,c=[l,cu];for(const e of i.fragmentIncludes)c.push(su[e]);c.push(i.fragmentSource);const h=c.join("\n"),d=[l,hu];for(const e of i.vertexIncludes)d.push(su[e]);this.forceManualRenderingForInstanceIDShaders=e.forceManualRenderingForInstanceIDShaders&&i.vertexSource.includes("gl_InstanceID"),this.forceManualRenderingForInstanceIDShaders&&d.push("uniform int u_instanceID;"),d.push(i.vertexSource);let u=d.join("\n");this.forceManualRenderingForInstanceIDShaders&&(u=u.replaceAll("gl_InstanceID","u_instanceID"));const _=a.createShader(a.FRAGMENT_SHADER);if(a.isContextLost())return this.failedToCreate=!0,void(this._pending=!1);a.shaderSource(_,h),a.compileShader(_),a.attachShader(this.program,_);const p=a.createShader(a.VERTEX_SHADER);if(a.isContextLost())return this.failedToCreate=!0,void(this._pending=!1);a.shaderSource(p,u),a.compileShader(p),a.attachShader(this.program,p),a.linkProgram(this.program),this._fragmentShader=_,this._vertexShader=p,e.extParallelShaderCompile?e._pendingPrograms.add(this):this._finalize()}_finalize(){if(!this._pending)return;this._pending=!1;const e=this._context,t=e.gl;e._pendingPrograms.delete(this);const i=T.now(),s=t.getProgramParameter(this.program,t.LINK_STATUS),o=T.now()-i,r=e._compileStats;if(r.totalStallMs+=o,o>r.maxStallMs&&(r.maxStallMs=o),o>1){r.framesMissed+=Math.floor(60*o/1e3);const e=this.fixedDefines.join(",");r.stalls.push({name:`${this.name}${e?"/":""}${e}`,ms:o,timestamp:i})}if(this._fragmentShader&&(s||_(`Fragment shader '${this.name}': ${t.getShaderInfoLog(this._fragmentShader)}`),t.deleteShader(this._fragmentShader),this._fragmentShader=null),this._vertexShader&&(s||_(`Vertex shader '${this.name}': ${t.getShaderInfoLog(this._vertexShader)}`),t.deleteShader(this._vertexShader),this._vertexShader=null),!s)return _(`Failed to link program '${this.name}': ${t.getProgramInfoLog(this.program)}`),void(this.failedToCreate=!0);this.fixedUniforms=this._fixedUniformsFn(e),this.activeUniforms=Object.entries(this.fixedUniforms).filter(([e,t])=>t.fetchUniformLocation(this.program,e)),this.binderUniforms=this.configuration?this.configuration.getUniforms(e):[],this.forceManualRenderingForInstanceIDShaders&&(this.instancingUniforms=(e=>({u_instanceID:new Ai(e)}))(e));const n=this.fixedDefines,a=this.name;(n.includes("TERRAIN")||n.includes("ELEVATED")||a.includes("symbol")||a.includes("circle"))&&(this.terrainUniforms=(e=>({u_dem:new Ai(e),u_dem_prev:new Ai(e),u_dem_tl:new Ci(e),u_dem_scale:new Ri(e),u_dem_tl_prev:new Ci(e),u_dem_scale_prev:new Ri(e),u_dem_size:new Ri(e),u_dem_lerp:new Ri(e),u_exaggeration:new Ri(e),u_depth:new Ai(e),u_depth_size_inv:new Ci(e),u_depth_range_unpack:new Ci(e),u_occluder_half_size:new Ri(e),u_occlusion_depth_offset:new Ri(e),u_meter_to_dem:new Ri(e),u_label_plane_matrix_inv:new Pi(e)}))(e)),n.includes("GLOBE")&&(this.globeUniforms=(e=>({u_tile_tl_up:new Li(e),u_tile_tr_up:new Li(e),u_tile_br_up:new Li(e),u_tile_bl_up:new Li(e),u_tile_up_scale:new Ri(e)}))(e)),n.includes("FOG")&&(this.fogUniforms=(e=>({u_fog_matrix:new Pi(e),u_fog_range:new Ci(e),u_fog_color:new Bi(e),u_fog_horizon_blend:new Ri(e),u_fog_vertical_limit:new Ci(e),u_fog_temporal_offset:new Ri(e),u_frustum_tl:new Li(e),u_frustum_tr:new Li(e),u_frustum_br:new Li(e),u_frustum_bl:new Li(e),u_globe_pos:new Li(e),u_globe_radius:new Ri(e),u_globe_transition:new Ri(e),u_is_globe:new Ai(e),u_viewport:new Ci(e)}))(e)),n.includes("RENDER_CUTOFF")&&(this.cutoffUniforms=(e=>({u_cutoff_params:new Bi(e)}))(e)),n.includes("LIGHTING_3D_MODE")&&(this.lightsUniforms=(e=>({u_lighting_ambient_color:new Li(e),u_lighting_directional_dir:new Li(e),u_lighting_directional_color:new Li(e),u_ground_radiance:new Li(e)}))(e)),n.includes("RENDER_SHADOWS")&&(this.shadowUniforms=(e=>({u_light_matrix_0:new Pi(e),u_light_matrix_1:new Pi(e),u_fade_range:new Ci(e),u_shadow_normal_offset:new Li(e),u_shadow_intensity:new Ri(e),u_shadow_texel_size:new Ri(e),u_shadow_map_resolution:new Ri(e),u_shadow_direction:new Li(e),u_shadow_bias:new Li(e),u_shadowmap_0:new Ai(e),u_shadowmap_1:new Ai(e)}))(e))}maybeFinalize(){if(!this._pending)return;const e=this._context.extParallelShaderCompile;e&&!this._context.gl.getProgramParameter(this.program,e.COMPLETION_STATUS_KHR)||this._finalize()}_ensureReady(){this._pending&&(this._finalize(),this._context.sweepPendingPrograms())}getAttributeLocation(e,t){this._ensureReady();let i=this.attributes[t];return void 0===i&&(i=this.attributes[t]=e.getAttribLocation(this.program,t)),i}_setUniformGroup(e,t,i){this._ensureReady();const s=this[t];if(!this.failedToCreate&&s){e.program.set(this.program);for(const e in i){const t=s[e];t&&t.set(this.program,e,i[e])}}}setTerrainUniformValues(e,t){this._setUniformGroup(e,"terrainUniforms",t)}setGlobeUniformValues(e,t){this._setUniformGroup(e,"globeUniforms",t)}setFogUniformValues(e,t){this._setUniformGroup(e,"fogUniforms",t)}setCutoffUniformValues(e,t){this._setUniformGroup(e,"cutoffUniforms",t)}setLightsUniformValues(e,t){this._setUniformGroup(e,"lightsUniforms",t)}setShadowUniformValues(e,t){this._setUniformGroup(e,"shadowUniforms",t)}_drawDebugWireframe(e,t,i,s,o,r,n,a,l,c,h){const d=e.options.wireframe;if(!1===d.terrain&&!1===d.layers2D&&!1===d.layers3D)return;const u=e.context;if(!(()=>!(!d.terrain||"terrainRaster"!==this.name&&"globeRaster"!==this.name)||!(!d.layers2D||e._terrain&&e._terrain.renderingToTexture||!Fu.includes(this.name))||!(!d.layers3D||!ku.includes(this.name)))())return;const _=u.gl,p=e.wireframeDebugCache.getLinesFromTrianglesBuffer(e.frameCounter,o,u);if(!p)return;const f=[...this.fixedDefines,"DEBUG_WIREFRAME"],m=e.getOrCreateProgram(this.name,{config:this.configuration,defines:f});m._ensureReady(),u.program.set(m.program),h&&h.bind(u,m.program);const g=(e,t,i)=>{if(t[e]&&i[e])for(const s in t[e])i[e][s]&&i[e][s].set(i.program,s,t[e][s].current)};l&&l.setUniforms(m.program,u,m.binderUniforms,n,{zoom:a}),g("fixedUniforms",this,m),g("terrainUniforms",this,m),g("globeUniforms",this,m),g("fogUniforms",this,m),g("lightsUniforms",this,m),g("shadowUniforms",this,m),p.bind(),u.setColorMode(new zu([_.ONE,_.ONE_MINUS_SRC_ALPHA,_.ZERO,_.ONE],S.transparent,[!0,!0,!0,!1])),u.setDepthMode(new Cu(t.func===_.LESS?_.LEQUAL:t.func,Cu.ReadOnly,t.range)),u.setStencilMode(Pu.disabled);const v=3*r.primitiveLength*2,y=3*r.primitiveOffset*2*2;if(this.forceManualRenderingForInstanceIDShaders){const e=c||1;for(let t=0;t<e;++t)m.instancingUniforms.u_instanceID.set(this.program,"u_instanceID",t),_.drawElements(_.LINES,v,_.UNSIGNED_SHORT,y)}else c&&c>1?_.drawElementsInstanced(_.LINES,v,_.UNSIGNED_SHORT,y,c):_.drawElements(_.LINES,v,_.UNSIGNED_SHORT,y);o.bind(),u.program.set(this.program),u.setDepthMode(t),u.setStencilMode(i),u.setColorMode(s)}checkUniforms(e,t,i){if(this.fixedDefines.includes(t))for(const s of Object.keys(i))if(!i[s].initialized)throw new Error(`Program '${this.name}', from draw '${e}': uniform ${s} not set but required by ${t} being defined`)}draw(e,t,i,s,o,r,n,a,l,c,h,d,u,_,p,f,m){const g=e.context,v=g.gl;if(this._ensureReady(),this.failedToCreate)return;g.program.set(this.program),g.setDepthMode(i),g.setStencilMode(s),g.setColorMode(o),g.setCullFace(r);for(const[e,t]of this.activeUniforms)t.set(this.program,e,n[e]);_&&_.setUniforms(this.program,g,this.binderUniforms,d,{zoom:u});const y=t===v.TRIANGLES?3:t===v.LINES?2:1;this.checkUniforms(a,"RENDER_SHADOWS",this.shadowUniforms);const x=p||[],b=_?_.getPaintVertexBuffers():[],w=t===v.TRIANGLES&&c,T=f&&f>0?1:void 0;for(const r of h.get()){const n=r.vaos||(r.vaos={}),h=n[a]||(n[a]=new Map);let p=h.get(this.program);if(p||h.set(this.program,p=new fu),p.bind(g,this,l,b,c,r.vertexOffset,x,T),this.forceManualRenderingForInstanceIDShaders){const e=f||1;for(let i=0;i<e;++i)this.instancingUniforms.u_instanceID.set(this.program,"u_instanceID",i),c?v.drawElements(t,r.primitiveLength*y,v.UNSIGNED_SHORT,r.primitiveOffset*y*2):v.drawArrays(t,r.vertexOffset,r.vertexLength)}else f&&f>1?v.drawElementsInstanced(t,r.primitiveLength*y,v.UNSIGNED_SHORT,r.primitiveOffset*y*2,f):c?v.drawElements(t,r.primitiveLength*y,v.UNSIGNED_SHORT,r.primitiveOffset*y*2):v.drawArrays(t,r.vertexOffset,r.vertexLength);w&&this._drawDebugWireframe(e,i,s,o,c,r,d,u,_,f,m)}}};class Uu{constructor(e,t,i,s){this.id=Uu.uniqueIdxCounter,Uu.uniqueIdxCounter++,this.context=e;const o=e.gl;this.buffer=o.createBuffer(),this.dynamicDraw=Boolean(i),this.context.unbindVAO(),e.bindElementBuffer.set(this.buffer),o.bufferData(o.ELEMENT_ARRAY_BUFFER,t.arrayBuffer,this.dynamicDraw?o.DYNAMIC_DRAW:o.STATIC_DRAW),this.dynamicDraw||s||t.destroy()}bind(){this.context.bindElementBuffer.set(this.buffer)}updateData(e){this.id=Uu.uniqueIdxCounter,Uu.uniqueIdxCounter++;const t=this.context.gl;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)}}Uu.uniqueIdxCounter=0;const Vu={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class ju{constructor(e,t,i,s,o,r){this.length=t.length,this.attributes=i,this.itemSize=t.bytesPerElement,this.dynamicDraw=s,this.instanceCount=r,this.context=e;const n=e.gl;this.buffer=n.createBuffer(),e.bindVertexBuffer.set(this.buffer),n.bufferData(n.ARRAY_BUFFER,t.arrayBuffer,this.dynamicDraw?n.DYNAMIC_DRAW:n.STATIC_DRAW),this.dynamicDraw||o||t.destroy()}bind(){this.context.bindVertexBuffer.set(this.buffer)}updateData(e,t=0,i=e.length){if(t===i)return;const s=this.context.gl;this.bind();const o=e.bytesPerElement;s.bufferSubData(s.ARRAY_BUFFER,t*o,e.uint8,t*o,(i-t)*o)}enableAttributes(e,t){for(const i of this.attributes){const s=t.getAttributeLocation(e,i.name);-1!==s&&e.enableVertexAttribArray(s)}}setVertexAttribPointers(e,t,i){for(const s of this.attributes){const o=t.getAttributeLocation(e,s.name);if(-1!==o){const t=s.offset+this.itemSize*(i||0);"Float32"===s.type||s.normalized?e.vertexAttribPointer(o,s.components,e[Vu[s.type]],!!s.normalized,this.itemSize,t):e.vertexAttribIPointer(o,s.components,e[Vu[s.type]],this.itemSize,t)}}}setVertexAttribDivisor(e,t,i){for(let s=0;s<this.attributes.length;s++){const o=t.getAttributeLocation(e,this.attributes[s].name);-1!==o&&this.instanceCount&&this.instanceCount>0&&e.vertexAttribDivisor(o,i)}}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}class Gu{constructor(e){this.gl=e.gl,this.default=this.getDefault(),this.current=this.default,this.dirty=!1}get(){return this.current}set(e){}getDefault(){return this.default}setDefault(){this.set(this.default)}}class qu extends Gu{getDefault(){return S.transparent.toNonPremultipliedRenderColor(null)}set(e){const t=this.current;(e.r!==t.r||e.g!==t.g||e.b!==t.b||e.a!==t.a||this.dirty)&&(this.gl.clearColor(e.r,e.g,e.b,e.a),this.current=e,this.dirty=!1)}}class Zu extends Gu{getDefault(){return 1}set(e){(e!==this.current||this.dirty)&&(this.gl.clearDepth(e),this.current=e,this.dirty=!1)}}class Wu extends Gu{getDefault(){return 0}set(e){(e!==this.current||this.dirty)&&(this.gl.clearStencil(e),this.current=e,this.dirty=!1)}}class Hu extends Gu{getDefault(){return[!0,!0,!0,!0]}set(e){const t=this.current;(e[0]!==t[0]||e[1]!==t[1]||e[2]!==t[2]||e[3]!==t[3]||this.dirty)&&(this.gl.colorMask(e[0],e[1],e[2],e[3]),this.current=e,this.dirty=!1)}}class $u extends Gu{getDefault(){return!0}set(e){(e!==this.current||this.dirty)&&(this.gl.depthMask(e),this.current=e,this.dirty=!1)}}class Xu extends Gu{getDefault(){return 255}set(e){(e!==this.current||this.dirty)&&(this.gl.stencilMask(e),this.current=e,this.dirty=!1)}}class Yu extends Gu{getDefault(){return{func:this.gl.ALWAYS,ref:0,mask:255}}set(e){const t=this.current;(e.func!==t.func||e.ref!==t.ref||e.mask!==t.mask||this.dirty)&&(this.gl.stencilFunc(e.func,e.ref,e.mask),this.current=e,this.dirty=!1)}}class Ku extends Gu{getDefault(){const e=this.gl;return[e.KEEP,e.KEEP,e.KEEP]}set(e){const t=this.current;(e[0]!==t[0]||e[1]!==t[1]||e[2]!==t[2]||this.dirty)&&(this.gl.stencilOp(e[0],e[1],e[2]),this.current=e,this.dirty=!1)}}class Ju extends Gu{getDefault(){return!1}set(e){if(e===this.current&&!this.dirty)return;const t=this.gl;e?t.enable(t.STENCIL_TEST):t.disable(t.STENCIL_TEST),this.current=e,this.dirty=!1}}class Qu extends Gu{getDefault(){return[0,1]}set(e){const t=this.current;(e[0]!==t[0]||e[1]!==t[1]||this.dirty)&&(this.gl.depthRange(e[0],e[1]),this.current=e,this.dirty=!1)}}class e_ extends Gu{getDefault(){return!1}set(e){if(e===this.current&&!this.dirty)return;const t=this.gl;e?t.enable(t.DEPTH_TEST):t.disable(t.DEPTH_TEST),this.current=e,this.dirty=!1}}class t_ extends Gu{getDefault(){return this.gl.LESS}set(e){(e!==this.current||this.dirty)&&(this.gl.depthFunc(e),this.current=e,this.dirty=!1)}}class i_ extends Gu{getDefault(){return!1}set(e){if(e===this.current&&!this.dirty)return;const t=this.gl;e?t.enable(t.BLEND):t.disable(t.BLEND),this.current=e,this.dirty=!1}}class s_ extends Gu{getDefault(){const e=this.gl;return[e.ONE,e.ZERO,e.ONE,e.ZERO]}set(e){const t=this.current;(e[0]!==t[0]||e[1]!==t[1]||e[2]!==t[2]||e[3]!==t[3]||this.dirty)&&(this.gl.blendFuncSeparate(e[0],e[1],e[2],e[3]),this.current=e,this.dirty=!1)}}class o_ extends Gu{getDefault(){return S.transparent.toNonPremultipliedRenderColor(null)}set(e){const t=this.current;(e.r!==t.r||e.g!==t.g||e.b!==t.b||e.a!==t.a||this.dirty)&&(this.gl.blendColor(e.r,e.g,e.b,e.a),this.current=e,this.dirty=!1)}}class r_ extends Gu{getDefault(){return this.gl.FUNC_ADD}set(e){(e!==this.current||this.dirty)&&(this.gl.blendEquationSeparate(e,e),this.current=e,this.dirty=!1)}}class n_ extends Gu{getDefault(){return!1}set(e){if(e===this.current&&!this.dirty)return;const t=this.gl;e?t.enable(t.CULL_FACE):t.disable(t.CULL_FACE),this.current=e,this.dirty=!1}}class a_ extends Gu{getDefault(){return this.gl.BACK}set(e){(e!==this.current||this.dirty)&&(this.gl.cullFace(e),this.current=e,this.dirty=!1)}}class l_ extends Gu{getDefault(){return this.gl.CCW}set(e){(e!==this.current||this.dirty)&&(this.gl.frontFace(e),this.current=e,this.dirty=!1)}}class c_ extends Gu{getDefault(){return null}set(e){(e!==this.current||this.dirty)&&(this.gl.useProgram(e),this.current=e,this.dirty=!1)}}class h_ extends Gu{getDefault(){return this.gl.TEXTURE0}set(e){(e!==this.current||this.dirty)&&(this.gl.activeTexture(e),this.current=e,this.dirty=!1)}}class d_ extends Gu{getDefault(){const e=this.gl;return[0,0,e.drawingBufferWidth,e.drawingBufferHeight]}set(e){const t=this.current;(e[0]!==t[0]||e[1]!==t[1]||e[2]!==t[2]||e[3]!==t[3]||this.dirty)&&(this.gl.viewport(e[0],e[1],e[2],e[3]),this.current=e,this.dirty=!1)}}class u_ extends Gu{getDefault(){return null}set(e){if(e===this.current&&!this.dirty)return;const t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,e),this.current=e,this.dirty=!1}}class __ extends Gu{getDefault(){return null}set(e){if(e===this.current&&!this.dirty)return;const t=this.gl;t.bindRenderbuffer(t.RENDERBUFFER,e),this.current=e,this.dirty=!1}}class p_ extends Gu{getDefault(){return null}set(e){if(e===this.current&&!this.dirty)return;const t=this.gl;t.bindTexture(t.TEXTURE_2D,e),this.current=e,this.dirty=!1}}class f_ extends Gu{getDefault(){return null}set(e){if(e===this.current&&!this.dirty)return;const t=this.gl;t.bindBuffer(t.ARRAY_BUFFER,e),this.current=e,this.dirty=!1}}class m_ extends Gu{getDefault(){return null}set(e){const t=this.gl;t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,e),this.current=e,this.dirty=!1}}class g_ extends Gu{getDefault(){return null}set(e){this.gl&&(e!==this.current||this.dirty)&&(this.gl.bindVertexArray(e),this.current=e,this.dirty=!1)}}class v_ extends Gu{getDefault(){return 4}set(e){if(e===this.current&&!this.dirty)return;const t=this.gl;t.pixelStorei(t.UNPACK_ALIGNMENT,e),this.current=e,this.dirty=!1}}class y_ extends Gu{getDefault(){return!1}set(e){if(e===this.current&&!this.dirty)return;const t=this.gl;t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e),this.current=e,this.dirty=!1}}class x_ extends Gu{getDefault(){return!1}set(e){if(e===this.current&&!this.dirty)return;const t=this.gl;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,e),this.current=e,this.dirty=!1}}class b_ extends Gu{constructor(e,t){super(e),this.context=e,this.parent=t}getDefault(){return null}}class w_ extends b_{constructor(e,t,i=0){super(e,t),this.attachmentPoint=e.gl.COLOR_ATTACHMENT0+i}setDirty(){this.dirty=!0}set(e){if(e===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const t=this.gl;t.framebufferTexture2D(t.FRAMEBUFFER,this.attachmentPoint,t.TEXTURE_2D,e,0),this.current=e,this.dirty=!1}}class T_ extends b_{attachment(){return this.gl.DEPTH_ATTACHMENT}set(e){if(e===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const t=this.gl;t.framebufferRenderbuffer(t.FRAMEBUFFER,this.attachment(),t.RENDERBUFFER,e),this.current=e,this.dirty=!1}}class E_ extends b_{attachment(){return this.gl.DEPTH_ATTACHMENT}set(e){if(e===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const t=this.gl;t.framebufferTexture2D(t.FRAMEBUFFER,this.attachment(),t.TEXTURE_2D,e,0),this.current=e,this.dirty=!1}}class I_ extends T_{attachment(){return this.gl.DEPTH_STENCIL_ATTACHMENT}}class S_{constructor(e,t,i,s,o){this.context=e,this.width=t,this.height=i;const r=this.framebuffer=e.gl.createFramebuffer();s>0&&(this.colorAttachment0=new w_(e,r,0)),s>1&&(this.colorAttachment1=new w_(e,r,1)),o&&(this.depthAttachmentType=o,this.depthAttachment="renderbuffer"===o?new T_(e,r):new E_(e,r))}static createWithTexture(e,t,i,s,o){const r=e.gl;if(e.activeTexture.set(r.TEXTURE1),e.viewport.set([0,0,i,s]),t&&t.width===i&&t.height===s)return r.bindTexture(r.TEXTURE_2D,t.colorAttachment0.get()),e.bindFramebuffer.set(t.framebuffer),t;t&&t.destroy();const n=e.extRenderToTextureHalfFloat||e.extColorBufferFloat?e.gl.RGBA16F:e.gl.RGBA8,a=new k(e,{width:i,height:s,data:null},n);a.bind(r.LINEAR,r.CLAMP_TO_EDGE);const l=e.createFramebuffer(i,s,1,null);if(l.format=n,l.colorAttachment0.set(a.texture),o){const t=e.createRenderbuffer(r.DEPTH24_STENCIL8,i,s);e.bindFramebuffer.set(l.framebuffer),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.RENDERBUFFER,t),l._stencilRbo=t}return l}createColorAttachment(e,t){0===t?this.colorAttachment0=new w_(e,this.framebuffer,0):1===t&&(this.colorAttachment1=new w_(e,this.framebuffer,1))}removeColorAttachment(e,t){const i=this.context.gl;let s;0===t?(s=this.colorAttachment0.get(),this.colorAttachment0=void 0):1===t&&(s=this.colorAttachment1.get(),this.colorAttachment1=void 0),s&&i.deleteTexture(s)}destroy(){const e=this.context.gl;if(this.colorAttachment0){const t=this.colorAttachment0.get();t&&e.deleteTexture(t)}if(this.colorAttachment1){const t=this.colorAttachment1.get();t&&e.deleteTexture(t)}if(this.depthAttachment&&this.depthAttachmentType)if("renderbuffer"===this.depthAttachmentType){const t=this.depthAttachment.get();t&&e.deleteRenderbuffer(t)}else{const t=this.depthAttachment.get();t&&e.deleteTexture(t)}this._stencilRbo&&(e.deleteRenderbuffer(this._stencilRbo),this._stencilRbo=null),e.deleteFramebuffer(this.framebuffer)}}class D_{constructor(e,t){this.gl=e,this._pendingPrograms=new Set,this._compileStats={precompiled:0,onDemand:0,totalStallMs:0,maxStallMs:0,framesMissed:0,stalls:[]},this.clearColor=new qu(this),this.clearDepth=new Zu(this),this.clearStencil=new Wu(this),this.colorMask=new Hu(this),this.depthMask=new $u(this),this.stencilMask=new Xu(this),this.stencilFunc=new Yu(this),this.stencilOp=new Ku(this),this.stencilTest=new Ju(this),this.depthRange=new Qu(this),this.depthTest=new e_(this),this.depthFunc=new t_(this),this.blend=new i_(this),this.blendFunc=new s_(this),this.blendColor=new o_(this),this.blendEquation=new r_(this),this.cullFace=new n_(this),this.cullFaceSide=new a_(this),this.frontFace=new l_(this),this.program=new c_(this),this.activeTexture=new h_(this),this.viewport=new d_(this),this.bindFramebuffer=new u_(this),this.bindRenderbuffer=new __(this),this.bindTexture=new p_(this),this.bindVertexBuffer=new f_(this),this.bindElementBuffer=new m_(this),this.bindVertexArrayOES=new g_(this),this.pixelStoreUnpack=new v_(this),this.pixelStoreUnpackPremultiplyAlpha=new y_(this),this.pixelStoreUnpackFlipY=new x_(this),this.options=t?{...t}:{},this.options.extTextureFilterAnisotropicForceOff||(this.extTextureFilterAnisotropic=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic"),this.extTextureFilterAnisotropic&&(this.extTextureFilterAnisotropicMax=e.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT))),this.extDebugRendererInfo=e.getExtension("WEBGL_debug_renderer_info"),this.extDebugRendererInfo&&(this.renderer=e.getParameter(this.extDebugRendererInfo.UNMASKED_RENDERER_WEBGL),this.vendor=e.getParameter(this.extDebugRendererInfo.UNMASKED_VENDOR_WEBGL)),this.forceManualRenderingForInstanceIDShaders=t&&!!t.forceManualRenderingForInstanceIDShaders||this.renderer&&this.renderer.includes("PowerVR"),this.options.extTextureFloatLinearForceOff||(this.extTextureFloatLinear=e.getExtension("OES_texture_float_linear")),this.extRenderToTextureHalfFloat=e.getExtension("EXT_color_buffer_half_float"),this.extColorBufferFloat=e.getExtension("EXT_color_buffer_float"),this.extTimerQuery=e.getExtension("EXT_disjoint_timer_query_webgl2"),this.maxTextureSize=e.getParameter(e.MAX_TEXTURE_SIZE),this.maxUniformBlockSize=Math.min(e.getParameter(e.MAX_UNIFORM_BLOCK_SIZE),32768),this.extBlendFuncExtended=e.getExtension("WEBGL_blend_func_extended"),this.extParallelShaderCompile=e.getExtension("KHR_parallel_shader_compile")}sweepPendingPrograms(){if(0!==this._pendingPrograms.size)for(const e of this._pendingPrograms)e.maybeFinalize()}setDefault(){this.unbindVAO(),this.clearColor.setDefault(),this.clearDepth.setDefault(),this.clearStencil.setDefault(),this.colorMask.setDefault(),this.depthMask.setDefault(),this.stencilMask.setDefault(),this.stencilFunc.setDefault(),this.stencilOp.setDefault(),this.stencilTest.setDefault(),this.depthRange.setDefault(),this.depthTest.setDefault(),this.depthFunc.setDefault(),this.blend.setDefault(),this.blendFunc.setDefault(),this.blendColor.setDefault(),this.blendEquation.setDefault(),this.cullFace.setDefault(),this.cullFaceSide.setDefault(),this.frontFace.setDefault(),this.program.setDefault(),this.activeTexture.setDefault(),this.bindFramebuffer.setDefault(),this.pixelStoreUnpack.setDefault(),this.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.pixelStoreUnpackFlipY.setDefault()}setDirty(){this.clearColor.dirty=!0,this.clearDepth.dirty=!0,this.clearStencil.dirty=!0,this.colorMask.dirty=!0,this.depthMask.dirty=!0,this.stencilMask.dirty=!0,this.stencilFunc.dirty=!0,this.stencilOp.dirty=!0,this.stencilTest.dirty=!0,this.depthRange.dirty=!0,this.depthTest.dirty=!0,this.depthFunc.dirty=!0,this.blend.dirty=!0,this.blendFunc.dirty=!0,this.blendColor.dirty=!0,this.blendEquation.dirty=!0,this.cullFace.dirty=!0,this.cullFaceSide.dirty=!0,this.frontFace.dirty=!0,this.program.dirty=!0,this.activeTexture.dirty=!0,this.viewport.dirty=!0,this.bindFramebuffer.dirty=!0,this.bindRenderbuffer.dirty=!0,this.bindTexture.dirty=!0,this.bindVertexBuffer.dirty=!0,this.bindElementBuffer.dirty=!0,this.bindVertexArrayOES.dirty=!0,this.pixelStoreUnpack.dirty=!0,this.pixelStoreUnpackPremultiplyAlpha.dirty=!0,this.pixelStoreUnpackFlipY.dirty=!0}createIndexBuffer(e,t,i){return new Uu(this,e,t,i)}createVertexBuffer(e,t,i,s,o){return new ju(this,e,t,i,s,o)}createRenderbuffer(e,t,i){const s=this.gl,o=s.createRenderbuffer();return this.bindRenderbuffer.set(o),s.renderbufferStorage(s.RENDERBUFFER,e,t,i),this.bindRenderbuffer.set(null),o}createFramebuffer(e,t,i,s){return new S_(this,e,t,i,s)}clear({color:e,depth:t,stencil:i,colorMask:s}){const o=this.gl;let r=0;e&&(r|=o.COLOR_BUFFER_BIT,this.clearColor.set(e.toNonPremultipliedRenderColor(null)),this.colorMask.set(s||[!0,!0,!0,!0])),void 0!==t&&(r|=o.DEPTH_BUFFER_BIT,this.depthRange.set([0,1]),this.clearDepth.set(t),this.depthMask.set(!0)),void 0!==i&&(r|=o.STENCIL_BUFFER_BIT,this.clearStencil.set(i),this.stencilMask.set(255)),o.clear(r)}setCullFace(e){!1===e.enable?this.cullFace.set(!1):(this.cullFace.set(!0),this.cullFaceSide.set(e.mode),this.frontFace.set(e.frontFace))}setDepthMode(e){e.func!==this.gl.ALWAYS||e.mask?(this.depthTest.set(!0),this.depthFunc.set(e.func),this.depthMask.set(e.mask),this.depthRange.set(e.range)):this.depthTest.set(!1)}setStencilMode(e){e.test.func!==this.gl.ALWAYS||e.mask?(this.stencilTest.set(!0),this.stencilMask.set(e.mask),this.stencilOp.set([e.fail,e.depthFail,e.pass]),this.stencilFunc.set({func:e.test.func,ref:e.ref,mask:e.test.mask})):this.stencilTest.set(!1)}setColorMode(e){e.blendFunction===zu.Replace?this.blend.set(!1):(this.blend.set(!0),this.blendFunc.set(e.blendFunction),this.blendColor.set(e.blendColor),e.blendEquation?this.blendEquation.set(e.blendEquation):this.blendEquation.setDefault()),this.colorMask.set(e.mask)}unbindVAO(){this.bindVertexArrayOES.set(null)}}const R_=1029,C_=2305;class A_{constructor(e,t,i){this.enable=e,this.mode=t,this.frontFace=i}}A_.disabled=new A_(!1,R_,C_),A_.backCCW=new A_(!0,R_,C_),A_.backCW=new A_(!0,R_,2304),A_.frontCW=new A_(!0,1028,2304),A_.frontCCW=new A_(!0,1028,C_);const L_=Bt();function P_({width:e,height:t,anchor:i,textOffset:s,textScale:o},r){const{horizontalAlign:n,verticalAlign:a}=mi(i),l=-(n-.5)*e,c=-(a-.5)*t,h=vi(i,s);return new m((l/o+h[0])*r,(c/o+h[1])*r)}function M_(e,t,i,s,o,r,n,a,l,c){const h=e.text.placedSymbolArray,d=e.text.dynamicLayoutVertexArray,u=e.icon.dynamicLayoutVertexArray,_={},p=e.getProjection(),f=bo(n,p,o),g=o.elevation,v=p.upVectorScale(n.canonical,o.center.lat,o.worldSize).metersToTile;d.clear();for(let u=0;u<h.length;u++){const y=h.get(u),{tileAnchorX:x,tileAnchorY:b,numGlyphs:w}=y,T=y.hidden||!y.crossTileID||e.allowVerticalPlacement&&!y.placedOrientation?null:s[y.crossTileID];if(T){let s=0,h=0,E=0;const I="road"===e.elevationType;if(g||I){const t=new m(x,b);let i=0;if(I&&e.hdExt){const s=e.symbolInstances.get(e.text.symbolInstanceIndices[u]);if(e.hdExt.isCrossTileRoadElevation(s.elevationFeatureIndex,n.canonical)){const s=e.hdExt.getRoadFeatureHeightForPlacedSymbol(e,e.text,u,t,n.canonical);i=null!==s?s:0}else{const s=e.hdExt.getElevationFeatureForPlacedSymbol(e,e.text,u);i=ri.getAtTileOffset(n,t,g,void 0!==s?s:null)}}else i=ri.getAtTileOffset(n,t,g,null);const[o,r,a]=p.upVector(n.canonical,x,b);s=i*o*v,h=i*r*v,E=i*a*v}let[S,D,R,C]=Gc(y.projectedAnchorX+s,y.projectedAnchorY+h,y.projectedAnchorZ+E,i?f:r);const A=qc(o.getCameraToCenterDistance(p),C);let L=Yt(e.textSizeData,l,y)*A/ui;i&&(L*=e.tilePixelRatio/a);const P=P_(T,L);i?(({x:S,y:D,z:R}=p.projectTilePoint(x+P.x,b+P.y,n.canonical)),[S,D,R]=Gc(S+s,D+h,R+E,r)):(t&&P._rotate(-o.angle),S+=P.x,D+=P.y,R=0);const M=e.allowVerticalPlacement&&y.placedOrientation===Gt.vertical?Math.PI/2:0;for(let e=0;e<w;e++)Xt(d,S,D,R,M);c&&y.associatedIconIndex>=0&&(_[y.associatedIconIndex]={x:S,y:D,z:R,angle:M})}else th(w,d)}if(c){u.clear();const t=e.icon.placedSymbolArray;for(let e=0;e<t.length;e++){const i=t.get(e),{numGlyphs:s}=i,o=_[e];if(i.hidden||!o)th(s,u);else{const{x:e,y:t,z:i,angle:r}=o;for(let o=0;o<s;o++)Xt(u,e,t,i,r)}}e.icon.dynamicLayoutVertexBuffer.updateData(u)}e.text.dynamicLayoutVertexBuffer.updateData(d)}function O_(e,t,i,s,o,r,n={}){const a=i.paint.get("icon-translate"),l=i.paint.get("text-translate"),c=i.paint.get("icon-translate-anchor"),h=i.paint.get("text-translate-anchor"),d=i.layout.get("icon-rotation-alignment"),u=i.layout.get("text-rotation-alignment"),_=i.layout.get("icon-pitch-alignment"),p=i.layout.get("text-pitch-alignment"),f=i.layout.get("icon-keep-upright"),m=i.layout.get("text-keep-upright"),g=i.paint.get("icon-color-saturation"),v=i.paint.get("icon-color-contrast"),y=i.paint.get("icon-color-brightness-min"),x=i.paint.get("icon-color-brightness-max"),b="sea"===i.layout.get("symbol-elevation-reference"),w="none"===i.layout.get("icon-image-use-theme"),T=e.context,E=T.gl,I=e.transform,S="map"===d,D="map"===u,R="map"===_,C="map"===p,A=void 0!==i.layout.get("symbol-sort-key").constantOr(1);let L=!1;const P=e.depthModeForSublayer(0,Cu.ReadOnly),M=new Cu(e.context.gl.LEQUAL,Cu.ReadOnly,e.depthRangeFor3D),O=[Ae(I.center.lng),Pe(I.center.lat)],z=i.layout.get("text-variable-anchor"),F="globe"===I.projection.name,k=[],B=[0,-1,0];let N;const U=()=>N=N||function(e){const t=e._camera.getWorldToCamera(e.worldSize,1),i=Ie(new Float64Array(16),t,e.globeMatrix);Tt(i,i);const s=[0,0,0],o=[0,1,0,0];return Se(o,o,i),s[0]=o[0],s[1]=o[1],s[2]=o[2],ye(s,s),s}(I);for(const o of s){const s=t.getTile(o),r=s.getBucket(i);if(!r)continue;if("mercator"===r.projection.name&&F)continue;if(r.fullyClipped)continue;const d="globe"===r.projection.name,u=d?K(I.zoom):0,_=bo(o,r.getProjection(),I),p=r.getProjection().name!==I.projection.name?Ie(Bt(),I.worldToFogMatrix,r.getProjection().createTileMatrix(I,I.cameraWorldSizeForFog,o.toUnwrapped())):null,N=I.calculatePixelsToTileUnitsMatrix(s),V=z&&r.hasTextData(),j=r.hasIconTextFit()&&V&&r.hasIconData(),G=r.getProjection().createInversionMatrix(I,o.canonical),q=(1<<s.tileID.canonical.z)*ae/e.transform.worldSize,Z=t=>{let i=[0,0,0];if(t){const t=e.style.directionalLight,s=e.style.ambientLight;t&&s&&(i=Gh(e.style,t,s))}return i},W=t=>{const i=Math.floor(e.context.maxUniformBlockSize/4),s=Math.floor(i/4);t.push(`MAX_UBO_SIZE_VEC4 ${s}u`)},H=t=>{I.depthOcclusionForSymbolsAndCircles&&(i.hasOcclusionOpacityProperties||e.terrain)&&(t.push("DEPTH_D24"),t.push("DEPTH_OCCLUSION"))},$=t=>{i.lut&&!w&&(i.lut.texture||(i.lut.texture=new wo(e.context,i.lut.image,[i.lut.image.height,i.lut.image.height,i.lut.image.height],T.gl.RGBA8)),T.activeTexture.set(T.gl.TEXTURE0+yd.LUT),i.lut.texture&&i.lut.texture.bind(T.gl.LINEAR,T.gl.CLAMP_TO_EDGE),t.push("APPLY_LUT_ON_GPU"))},X=()=>{const t=S&&"point"!==i.layout.get("symbol-placement"),n=[];H(n),$(n);const l=t||j,h="road"===r.elevationType,m=e.shadowRenderer,w=h&&R&&!!m&&m.enabled,T=Z(w),D=h&&R&&!e.terrain?M:P,C=i.paint.get("icon-image-cross-fade");e.terrainRenderModeElevated()&&R&&n.push("PITCH_WITH_MAP_TERRAIN"),d&&(n.push("PROJECTION_GLOBE_VIEW"),l&&n.push("PROJECTED_POS_ON_VIEWPORT")),C>0&&r.hasAnySecondaryIcon&&n.push("ICON_TRANSITION"),!r.icon.zOffsetVertexBuffer||h&&e.terrain||n.push("Z_OFFSET"),n.push(r.icon.fadeVertexBuffer?"GLOBAL_PLACEMENT_FADE":"LEGACY_PLACEMENT_FADE"),0===g&&0===v&&0===y&&1===x||n.push("COLOR_ADJUSTMENT"),w&&n.push("RENDER_SHADOWS","NORMAL_OFFSET"),h&&R&&!e.terrain&&r.icon.orientationVertexBuffer&&n.push("ELEVATED_ROADS"),W(n);const A=R&&!d&&e.isTileAffectedByFog(o),L=e.getOrCreateProgram("symbol",{defines:n,overrideFog:A}),z=s.imageAtlasTexture?s.imageAtlasTexture.size:[0,0],k=r.iconSizeData,V=jt(k,I.zoom),X=R||!I.isOrthographic,Y=Uc(_,s.tileID.canonical,R,S,I,r.getProjection(),N),K=jc(_,s.tileID.canonical,R,S,I,r.getProjection(),N),J=r.icon.uboBinder&&r.icon.uboBinder.hasPerFeatureTranslate()?[0,0]:a,Q=e.translatePosMatrix(K,s,J,c,!0),ee=e.translatePosMatrix(_,s,J,c),te=l?L_:Y,ie=S&&!R&&!t,se=d&&(F||I.mercatorFromTransition)&&!S?U():B,oe=i.getColorAdjustmentMatrix(g,v,y,x),re=bd(k.kind,V,ie,R,e,ee,te,Q,b,!1,r.sdfIcons,z,[0,0],0,o,u,O,G,se,r.getProjection(),T,q,oe,C,null),ne=s.imageAtlasTexture?s.imageAtlasTexture:null,ae=1!==i.layout.get("icon-size").constantOr(0)||r.iconsNeedLinear,le=R&&!r.sdfIcons&&!!ne&&!!ne.useMipmap,ce=r.sdfIcons||e.options.rotating||e.options.zooming||ae||X?E.LINEAR:E.NEAREST,he=r.sdfIcons&&0!==i.paint.get("icon-halo-width").constantOr(1),de=e.terrain&&R&&t?Tt(Bt(),Y):L_;if(t&&r.icon){const t=ri.getAtTileOffsetFunc(o,I.center.lat,I.worldSize,r.getProjection()),n=Vc(_,s.tileID.canonical,R,S,I,r.getProjection(),N),a=i.layout.get("icon-size-scale-range"),l=Ee(e.scaleFactor,a[0],a[1]);Wc(r,_,e,!1,n,K,R,f,t,o,l)}return{program:L,buffers:r.icon,uniformValues:re,atlasTexture:ne,atlasTextureIcon:null,atlasInterpolation:ce,atlasInterpolationIcon:null,atlasMipmaps:le,isSDF:r.sdfIcons,hasHalo:he,depthMode:D,tile:s,renderWithShadows:w,labelPlaneMatrixInv:de,fogMatrix:p}},Y=()=>{const t=D&&"point"!==i.layout.get("symbol-placement"),n=[],a=t||z||j,c="road"===r.elevationType,f=e.shadowRenderer,g=c&&C&&!!f&&f.enabled,v=Z(g),y=c&&C&&!e.terrain?M:P;e.terrainRenderModeElevated()&&C&&n.push("PITCH_WITH_MAP_TERRAIN"),d&&(n.push("PROJECTION_GLOBE_VIEW"),a&&n.push("PROJECTED_POS_ON_VIEWPORT")),!r.text.zOffsetVertexBuffer||c&&e.terrain||n.push("Z_OFFSET"),n.push(r.text.fadeVertexBuffer?"GLOBAL_PLACEMENT_FADE":"LEGACY_PLACEMENT_FADE"),r.iconsInText&&n.push("RENDER_TEXT_AND_SYMBOL"),g&&n.push("RENDER_SHADOWS","NORMAL_OFFSET"),c&&C&&!e.terrain&&r.text.orientationVertexBuffer&&n.push("ELEVATED_ROADS"),H(n),W(n);const x=C&&!d&&e.isTileAffectedByFog(o),w=e.getOrCreateProgram("symbol",{defines:n,overrideFog:x});let T,S=[0,0],R=null;const A=r.textSizeData;r.iconsInText&&(S=s.imageAtlasTexture?s.imageAtlasTexture.size:[0,0],R=s.imageAtlasTexture?s.imageAtlasTexture:null,T=C||!I.isOrthographic||e.options.rotating||e.options.zooming||"composite"===A.kind||"camera"===A.kind?E.LINEAR:E.NEAREST);const L=s.glyphAtlasTexture?s.glyphAtlasTexture.size:[0,0],k=i.layout.get("text-size-scale-range"),V=Ee(e.scaleFactor,k[0],k[1]),$=jt(A,I.zoom,V),X=Uc(_,s.tileID.canonical,C,D,I,r.getProjection(),N),Y=jc(_,s.tileID.canonical,C,D,I,r.getProjection(),N),K=r.text.uboBinder&&r.text.uboBinder.hasPerFeatureTranslate()?[0,0]:l,J=e.translatePosMatrix(Y,s,K,h,!0),Q=e.translatePosMatrix(_,s,K,h),ee=a?L_:X,te=D&&!C&&!t,ie=d&&(F||I.mercatorFromTransition)&&!D?U():B,se=bd(A.kind,$,te,C,e,Q,ee,J,b,!0,!0,L,S,0,o,u,O,G,ie,r.getProjection(),v,q,null,null,V),oe=s.glyphAtlasTexture?s.glyphAtlasTexture:null,re=E.LINEAR,ne=0!==i.paint.get("text-halo-width").constantOr(1),ae=e.terrain&&C&&t?Tt(Bt(),X):L_;if(t&&r.text){const t=ri.getAtTileOffsetFunc(o,I.center.lat,I.worldSize,r.getProjection()),i=Vc(_,s.tileID.canonical,C,D,I,r.getProjection(),N);Wc(r,_,e,!0,i,Y,C,m,t,o,V)}return{program:w,buffers:r.text,uniformValues:se,atlasTexture:oe,atlasTextureIcon:R,atlasInterpolation:re,atlasInterpolationIcon:T,atlasMipmaps:!1,isSDF:!0,hasHalo:ne,depthMode:y,tile:s,renderWithShadows:g,labelPlaneMatrixInv:ae,fogMatrix:p}},J=r.icon.segments.get().length,Q=r.text.segments.get().length,ee=J&&!n.onlyText?X():null,te=Q&&!n.onlyIcons?Y():null,ie=i.paint.get("icon-opacity").constantOr(1),se=i.paint.get("text-opacity").constantOr(1);if(A&&r.canOverlap){L=!0;const e=ie&&!n.onlyText?r.icon.segments.get():[],t=se&&!n.onlyIcons?r.text.segments.get():[];for(const t of e)k.push({segments:new Ye([t]),sortKey:t.sortKey,state:ee});for(const e of t)k.push({segments:new Ye([e]),sortKey:e.sortKey,state:te})}else n.onlyText||k.push({segments:ie?r.icon.segments:new Ye([]),sortKey:0,state:ee}),n.onlyIcons||k.push({segments:se?r.text.segments:new Ye([]),sortKey:0,state:te})}L&&k.sort((e,t)=>e.sortKey-t.sortKey);for(const t of k){const s=t.state;if(s)if(e.terrain?e.terrain.setupElevationDraw(s.tile,s.program,{useDepthForOcclusion:I.depthOcclusionForSymbolsAndCircles,labelPlaneMatrixInv:s.labelPlaneMatrixInv}):e.setupDepthForOcclusion(I.depthOcclusionForSymbolsAndCircles,s.program),T.activeTexture.set(E.TEXTURE0),s.atlasTexture&&s.atlasTexture.bind(s.atlasInterpolation,E.CLAMP_TO_EDGE,!s.atlasMipmaps,s.atlasMipmaps),s.atlasTextureIcon&&(T.activeTexture.set(E.TEXTURE1),s.atlasTextureIcon&&s.atlasTextureIcon.bind(s.atlasInterpolationIcon,E.CLAMP_TO_EDGE,!0)),s.renderWithShadows&&e.shadowRenderer.setupShadows(s.tile.tileID.toUnwrapped(),s.program,"vector-tile"),e.uploadCommonUniforms(e.context,s.program,s.fogMatrix?null:s.tile.tileID.toUnwrapped(),s.fogMatrix),s.hasHalo){const n=s.uniformValues;n.u_is_halo=1,z_(s.buffers,t.segments,i,e,s.program,s.depthMode,o,r,n,2),n.u_is_halo=0}else{if(s.isSDF){const n=s.uniformValues;s.hasHalo&&(n.u_is_halo=1,z_(s.buffers,t.segments,i,e,s.program,s.depthMode,o,r,n,1)),n.u_is_halo=0}z_(s.buffers,t.segments,i,e,s.program,s.depthMode,o,r,s.uniformValues,1)}}}function z_(e,t,i,s,o,r,n,a,l,c){const h=s.context,d=h.gl,u=[e.dynamicLayoutVertexBuffer,e.opacityVertexBuffer,e.iconTransitioningVertexBuffer,e.globeExtVertexBuffer,e.zOffsetVertexBuffer,e.orientationVertexBuffer];e.featureIdBuffer&&u.push(e.featureIdBuffer),e.fadeVertexBuffer&&u.push(e.fadeVertexBuffer);const _=e.uboBinder?null:e.programConfigurations.get(i.id);if(e.uboBinder){e.uboBinder.layer=i;const t=s.transform.zoom,o=s.style.getBrightness?s.style.getBrightness():null,r=e.uboBinder.getConstantUniformValues(o);l.u_spp_fill_np_color=r.fill_np_color,l.u_spp_halo_np_color=r.halo_np_color,l.u_spp_opacity=r.opacity,l.u_spp_halo_width=r.halo_width,l.u_spp_halo_blur=r.halo_blur,l.u_spp_emissive_strength=r.emissive_strength,l.u_spp_occlusion_opacity=r.occlusion_opacity,l.u_spp_z_offset=r.z_offset,l.u_spp_zoom_fraction=t-e.uboBinder._floorZoom;const n=i.paint.get(e.uboBinder.isText?"text-translate-anchor":"icon-translate-anchor"),a=e.uboBinder.hasPerFeatureTranslate()&&"map"===n?s.transform.angle:0;l.u_spp_translate_rotation=[Math.cos(a),Math.sin(a)]}const{batchIndices:p,batchSegments:f}=e.getBatchGrouping(t);for(const t of p){const p=f.get(t);e.uboBinder&&e.uboBinder.bind(h,o.program,t),o.draw(s,d.TRIANGLES,r,n,a,A_.disabled,l,i.id,e.layoutVertexBuffer,e.indexBuffer,p,i.paint,s.transform.zoom,_,u,c,e.uboBinder?e.uboBinder.getUBO(t):void 0)}}function F_(e,t,i,s,o,r){const n=i.paint.get("line-width"),a=i.paint.get("line-emissive-strength").isConstant(),l=i.paint.get("line-emissive-strength").constantOr(0),c=i.paint.get("line-occlusion-opacity"),h=i.layout.get("line-elevation-reference"),d="meters"===i.layout.get("line-width-unit"),u="sea"===h,p=!(!e.terrain||!e.terrain.enabled),f=e.context,m=f.gl;if(i.hasElevatedBuckets&&"globe"===e.transform.projection.name)return;const g=i.layout.get("line-cross-slope"),v=void 0!==g,y=g<1,x=o||e.colorModeForDrapableLayerRenderPass(a?l:null),b=e.terrain&&e.terrain.renderingToTexture||r,w=b?1:T.devicePixelRatio,E=i.paint.get("line-dasharray"),I=E.constantOr(1),S=i.layout.get("line-cap"),D=E.constantOr(null),R=S.constantOr(null),C=i.paint.get("line-pattern"),A=C.constantOr(1),L=i.paint.get("line-pattern-cross-fade"),P=C.constantOr(null),M=i.paint.get("line-opacity").constantOr(1);let O=!A&&1!==M||e.depthOcclusion&&c>0&&c<1;const z=i.paint.get("line-gradient"),F=0!==i.paint.get("line-border-width").constantOr(1)?i.paint.get("line-border-gradient"):null,B=A?"linePattern":"line",N=Io(i);if(!A){const t=Math.floor(e.context.maxUniformBlockSize/4),i=Math.floor(t/4);N.push(`MAX_UBO_SIZE_VEC4 ${i}u`)}let U;if(b&&e.terrain&&e.terrain.clipOrMaskOverlapStencilType()&&(O=!1),0!==c&&e.depthOcclusion){const e=i.paint._values["line-opacity"];e&&e.value&&"constant"===e.value.kind?U=e.value:_(`Occlusion opacity for layer ${i.id} is supported only when line-opacity isn't data-driven.`)}"constant"!==n.value.kind&&!1===n.value.isLineProgressConstant&&N.push("VARIABLE_LINE_WIDTH");const V=i.paint.get("line-emissive-strength");A||"constant"===V.value.kind||!1!==V.value.isLineProgressConstant||N.push("VARIABLE_LINE_EMISSIVE_STRENGTH"),e._debugParams.showElevationIdDebug&&N.push("DEBUG_ELEVATION_ID"),b&&("dual-source-blending"!==e.emissiveMode||a?e.isEmissiveMrtActive()&&(N.push("USE_MRT1"),"mrt-full-rgba"===e.emissiveMode&&N.push("USE_MRT1_RGBA")):N.push("DUAL_SOURCE_BLENDING"));const j={};let G=null;const q=[],Z=(s,o,r,n,a,l)=>{for(const h of s){const s=t.getTile(h);if(A&&!s.patternsLoaded())continue;const u=s.getBucket(i);if(!u)continue;if("none"!==u.elevationType&&!a||"none"===u.elevationType&&a)continue;e.prepareDrawTile();const _=[...o],p="road"===u.elevationType,g=e.shadowRenderer,v=p&&!!g&&g.enabled;let y=[0,0,0];if(v){const t=e.style.directionalLight,i=e.style.ambientLight;t&&i&&(y=Gh(e.style,t,i)),_.push("RENDER_SHADOWS","NORMAL_OFFSET")}const T=A?u.programConfigurations.get(i.id):null,E=A?null:u.uboBinders[i.id];let S=!1;if(T&&P&&s.imageAtlas){const e=So.from(P),t=e.getPrimary().scaleSelf(w).toString(),i=s.imageAtlas.patternPositions.get(t),o=e.getSecondary(),r=o?s.imageAtlas.patternPositions.get(o.scaleSelf(w).toString()):null;S=!!i&&!!r,i&&T.setConstantPatternPositions(i,r)}T&&L>0&&(S||T.getPatternTransitionVertexBuffer("line-pattern"))&&_.push("LINE_PATTERN_TRANSITION"),u.elevationGroundScaleVertexBuffer&&_.push("ELEVATION_GROUND_SCALE");const C=e.isTileAffectedByFog(h),N=e.getOrCreateProgram(B,{config:T,defines:_,overrideFog:C});let V=null;!A&&D&&R&&s.lineAtlas&&(V=s.lineAtlas.getDash(D,R)),v&&g.setupShadows(s.tileID.toUnwrapped(),N,"vector-tile");let[Z,W]=i.paint.get("line-trim-offset");if("round"===R||"square"===R){const e=1;Z!==W&&(0===Z&&(Z-=e),1===W&&(W+=e))}const H=b?h.projMatrix:null,$=d?1/u.tileToMeter/Te(s,1,e.transform.zoom):1,X=d?1/u.tileToMeter/Te(s,1,Math.floor(e.transform.zoom)):1,Y=A&&I?i.paint._values["line-floorwidth"]:null;let K;const J=s.dashIdealZ;if(Y&&"constant"===Y.value.kind&&J!==s.tileID.overscaledZ){const e=u.zoom;e in j||(j[e]=Math.max(.01,i.getPaintPropertyValue("line-width").expression.evaluate({zoom:e}))),K=Y.value.value,Y.value.value=j[e]*Math.pow(2,J-e)}const Q=A?Do(e,s,i,H,w,$,X,[Z,W],y,L):Ro(e,s,i,H,u.lineClipsArray.length,w,$,X,[Z,W],y),ee=(s,o,r,n,a,l)=>{let c=s.texture;if(o!==s.version){let l=256;if(r){const i=t.getSource().maxzoom,s=h.canonical.z===i?Math.ceil(1<<e.transform.maxZoom-h.canonical.z):1;l=Ee(Po(u.maxLineLength/ae*1024*s),256,f.maxTextureSize)}s.gradient=Lo({expression:n,evaluationKey:"lineProgress",resolution:l,image:s.gradient||void 0,clips:u.lineClipsArray,lut:a?null:i.lut}),s.texture?s.texture.update(s.gradient):s.texture=new k(f,s.gradient,m.RGBA8),s.version=o,c=s.texture}f.activeTexture.set(l),c.bind(r?m.NEAREST:m.LINEAR,m.CLAMP_TO_EDGE)};if(E){E.layer=i;const t=e.transform.zoom;if(!G){const t=e.style.getBrightness?e.style.getBrightness():null;G=E.getConstantUniformValues(t)}const o=G,r=Q;if(r.u_lpp_color=o.color_np_color,r.u_lpp_border_color=o.border_np_color,r.u_lpp_opacity=o.opacity,r.u_lpp_blur=o.blur,r.u_lpp_width=o.width,r.u_lpp_gap_width=o.gap_width,r.u_lpp_offset=o.offset,r.u_lpp_floorwidth=o.floorwidth,r.u_lpp_border_width=o.border_width,r.u_lpp_emissive_strength=o.emissive_strength,V&&(r.u_lpp_dash=[V.tl[0],V.tl[1],V.br[0],V.br[1]]),r.u_lpp_zoom_fraction=t-E._floorZoom,I&&J!==s.tileID.overscaledZ&&0===(E.header[Co]&Ao)){const e=u.zoom;e in j||(j[e]=Math.max(.01,i.getPaintPropertyValue("line-width").expression.evaluate({zoom:e}))),r.u_lpp_floorwidth=j[e]*Math.pow(2,J-e)}}z&&ee(u.gradients[i.id],i.gradientVersion,i.stepInterpolant,i.getPaintPropertyValue("line-gradient").expression,"none"===i.paint.get("line-gradient-use-theme").constantOr("default"),m.TEXTURE1),F&&ee(u.borderGradients[i.id],i.borderGradientVersion,i.borderStepInterpolant,i.getPaintPropertyValue("line-border-gradient").expression,"none"===i.paint.get("line-border-gradient-use-theme").constantOr("default"),m.TEXTURE2),I?(f.activeTexture.set(m.TEXTURE0),s.lineAtlasTexture&&s.lineAtlasTexture.bind(m.LINEAR,m.REPEAT)):A||(f.activeTexture.set(m.TEXTURE0),e.emptyTexture.bind(m.LINEAR,m.CLAMP_TO_EDGE)),A&&T&&(f.activeTexture.set(m.TEXTURE0),s.imageAtlasTexture&&s.imageAtlasTexture.bind(m.LINEAR,m.CLAMP_TO_EDGE),T.updatePaintBuffers()),a&&!p&&e.terrain.setupElevationDraw(s,N),e.uploadCommonUniforms(f,N,h.toUnwrapped());const te=(t,s,o)=>{if(s&&0!==s.get().length){if(null!=U&&(U.value=M*c,E&&(Q.u_lpp_opacity=M*c)),void 0!==o&&(Q.u_opacity_multiplier=o),E){const{batchIndices:o,batchSegments:n}=u.getBatchGrouping(s);for(const s of o)E.bind(f,N.program,s),N.draw(e,m.TRIANGLES,r,t,x,A_.disabled,Q,i.id,u.layoutVertexBuffer,u.indexBuffer,n.get(s),i.paint,e.transform.zoom,T,[u.layoutVertexBuffer2,u.patternVertexBuffer,u.zOffsetVertexBuffer,u.elevationIdColVertexBuffer,u.elevationGroundScaleVertexBuffer],void 0,E.getUBO(s))}else N.draw(e,m.TRIANGLES,r,t,x,A_.disabled,Q,i.id,u.layoutVertexBuffer,u.indexBuffer,s,i.paint,e.transform.zoom,T,[u.layoutVertexBuffer2,u.patternVertexBuffer,u.zOffsetVertexBuffer,u.elevationIdColVertexBuffer,u.elevationGroundScaleVertexBuffer]);void 0!==o&&(Q.u_opacity_multiplier=1),null!=U&&(U.value=M,E&&(Q.u_lpp_opacity=M))}},ie=Il.drawLineFrcCoverageDetect?Il.drawLineFrcCoverageDetect(e,u,h,a,te,q):null,se=e=>{ie&&ie.active&&Il.drawLineFrcRenderLine?Il.drawLineFrcRenderLine(u,ie,e,te):te(e,u.segments)};if(O&&!a){const t=e.stencilModeForClipping(h).ref;0===t&&b&&f.clear({stencil:0});const i={func:m.EQUAL,mask:255};Q.u_alpha_discard_threshold=.8,se(new Pu(i,t,255,m.KEEP,m.KEEP,m.INVERT)),Q.u_alpha_discard_threshold=0,se(new Pu(i,t,255,m.KEEP,m.KEEP,m.KEEP))}else Q.u_alpha_discard_threshold=O&&a&&l?.8:0,se(a?n:e.stencilModeForClipping(h));ie&&Il.drawLineFrcFadePass&&Il.drawLineFrcFadePass(e,u,h,ie,a,n,te),void 0!==K&&(Y.value.value=K)}};let W=e.depthModeForSublayer(0,Cu.ReadOnly);const H=new Cu(e.depthOcclusion?m.GREATER:m.LEQUAL,Cu.ReadOnly,e.depthRangeFor3D);if(i.hasNonElevatedBuckets){const t=!b&&e.terrain;0!==c&&t?_(`Occlusion opacity for layer ${i.id} is supported on terrain only if the layer has line-z-offset enabled.`):t?_(`Cannot render non-elevated lines in immediate mode when terrain is enabled. Layer: ${i.id}.`):Z(s,N,W,Pu.disabled,!1,!0)}if(i.hasElevatedBuckets){"hd-road-markup"===h?p||(W=H,N.push("ELEVATED_ROADS")):(N.push("ELEVATED"),W=H,v&&N.push(y?"CROSS_SLOPE_HORIZONTAL":"CROSS_SLOPE_VERTICAL"),u&&N.push("ELEVATION_REFERENCE_SEA"));const t=O?e.stencilModeFor3D():Pu.disabled;"hd-road-markup"!==h&&(e.forceTerrainMode=!0),Z(s,N,W,t,!0,!0),O&&Z(s,N,W,t,!0,!1),"hd-road-markup"!==h&&(e.forceTerrainMode=!1)}Il.drawLineFrcCoverageSecondPass&&Il.drawLineFrcCoverageSecondPass(e,i,q),O&&(e.resetStencilClippingMasks(),b&&f.clear({stencil:0})),0===c||e.depthOcclusion||b||e.layersWithOcclusionOpacity.push(e.currentLayer)}class k_{destroy(){this.fbo&&(this.fbo.destroy(),this.fbo=null),this.drapeFbo&&(this.drapeFbo.destroy(),this.drapeFbo=null)}}class B_{constructor(e){this.pbo=e.createBuffer(),this.sync=null,this.fboA=null,this.fboB=null,this.maxDensity=0}destroy(e){this.sync&&(e.deleteSync(this.sync),this.sync=null),e.deleteBuffer(this.pbo),this.fboA&&(this.fboA.destroy(),this.fboA=null),this.fboB&&(this.fboB.destroy(),this.fboB=null)}}const N_={additive:{clearColor:new S(0,0,0,0),colorMode:zu.additiveAlphaWeighted,compositeUniformValue:1},multiply:{clearColor:new S(1,1,1,1),colorMode:zu.multiply,compositeUniformValue:0}};function U_(e){return!(!e.extRenderToTextureHalfFloat&&!e.extColorBufferFloat)}function V_(e,t){return"additive"===e&&U_(t)?zu.additiveAlphaWeightedUnboundedAlpha:N_[e].colorMode}function j_(e,t,i){const s=e.context,o=s.gl;let r=i.width,n=i.height,a=i.colorAttachment0.get();t.lineBlendDensityReadback||(t.lineBlendDensityReadback=new B_(o));const l=t.lineBlendDensityReadback;let c=0,h=!0;for(;r>1||n>1;){const i=Math.max(1,Math.floor(r/2)),d=Math.max(1,Math.floor(n/2)),u=0===c?"fboA":"fboB";l[u]=S_.createWithTexture(s,l[u],i,d,!1);const _=l[u];s.bindFramebuffer.set(_.framebuffer),s.viewport.set([0,0,i,d]),s.activeTexture.set(o.TEXTURE0),o.bindTexture(o.TEXTURE_2D,a),e.getOrCreateProgram("lineBlendReduce").draw(e,o.TRIANGLES,Cu.disabled,Pu.disabled,zu.unblended,A_.disabled,rd(0,[1/r,1/n],h),t.id,e.viewportBuffer,e.quadTriangleIndexBuffer,e.viewportSegments,t.paint,e.transform.zoom),r=i,n=d,a=_.colorAttachment0.get(),c=1-c,h=!1}const d=U_(s),u=d?16:4;l.sync&&(o.deleteSync(l.sync),l.sync=null),o.bindBuffer(o.PIXEL_PACK_BUFFER,l.pbo),o.bufferData(o.PIXEL_PACK_BUFFER,u,o.STREAM_READ),o.readPixels(0,0,1,1,o.RGBA,d?o.FLOAT:o.UNSIGNED_BYTE,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),l.sync=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0),s.viewport.set([0,0,e.width,e.height])}function G_(e,t,i){if(!U_(e.context))return;const s=t.lineBlendDensityReadback;s&&s.sync?(function(e,t,i){if(e.sync&&t.getSyncParameter(e.sync,t.SYNC_STATUS)===t.SIGNALED){if(t.deleteSync(e.sync),e.sync=null,t.bindBuffer(t.PIXEL_PACK_BUFFER,e.pbo),U_(i)){const i=new Float32Array(4);t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,i);const s=i[1];e.maxDensity=Math.max(2*(s>0?i[0]/s:0),1)}else e.maxDensity=1;t.bindBuffer(t.PIXEL_PACK_BUFFER,null)}}(s,e.context.gl,e.context),s.sync||(j_(e,t,i),e.style.map.triggerRepaint())):(j_(e,t,i),e.style.map.triggerRepaint())}function q_(e,t,i,s,o,r){const n=e.context,a=n.gl,l="additive"===i?1:t.paint.get("line-opacity").constantOr(1),c="additive"===i?function(e,t){const i=t.paint.get("line-blend-additive-clamp");if(i>0)return i;const s=t.lineBlendDensityReadback;return s&&0!==s.maxDensity?s.maxDensity:null}(0,t):1;if(null===c)return;n.bindFramebuffer.set(o),r&&n.viewport.set([0,0,r[0],r[1]]),n.activeTexture.set(a.TEXTURE0),a.bindTexture(a.TEXTURE_2D,s.colorAttachment0.get());const h=V_(i,e.context);e.getOrCreateProgram("lineBlendComposite").draw(e,a.TRIANGLES,Cu.disabled,Pu.disabled,h,A_.disabled,((e,t,i,s)=>({u_image:0,u_opacity:t,u_blend_mode:i,u_max_density:s}))(0,l,N_[i].compositeUniformValue,c),t.id,e.viewportBuffer,e.quadTriangleIndexBuffer,e.viewportSegments,t.paint,e.transform.zoom)}function Z_(e,t,i,s){const{painter:o,sourceCache:r,layer:n,coords:a,colorMode:l,elevationType:c,terrainEnabled:h,pass:d}=e,u=o.context.gl,_=n.paint.get("fill-pattern"),p=n.paint.get("fill-pattern-cross-fade"),f=_.constantOr(null);let m=c;"road"!==c||t&&!h||(m="none");const g="road"===m,v=e.painter.shadowRenderer,y=g&&!!v&&v.enabled,x=new Cu(o.context.gl.LEQUAL,Cu.ReadOnly,o.depthRangeFor3D);let b=[0,0,0];if(y){const e=o.style.directionalLight,t=o.style.ambientLight;e&&t&&(b=Gh(o.style,e,t))}const w=_&&_.constantOr(1),E=o.terrain&&o.terrain.renderingToTexture,I=(e,d)=>{let _,m,I,S,D;d?(_=w&&!n.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",I=u.LINES):(_=w?"fillPattern":"fill",I=u.TRIANGLES);const R=[];for(const C of a){const a=r.getTile(C);if(w&&!a.patternsLoaded())continue;const A=a.getBucket(n);if(!A)continue;const L=t?A.hdExt&&A.hdExt.elevationBufferData:A.bufferData;if(!L||L.isEmpty())continue;o.prepareDrawTile();const P=L.programConfigurations.get(n.id),M=o.isTileAffectedByFog(C),O=[],z=[];g&&(O.push("ELEVATED_ROADS"),z.push(L.elevatedLayoutVertexBuffer)),y&&O.push("RENDER_SHADOWS","NORMAL_OFFSET"),E&&i&&(O.push("USE_MRT1"),"mrt-full-rgba"===o.emissiveMode&&O.push("USE_MRT1_RGBA")),w&&(o.context.activeTexture.set(u.TEXTURE0),a.imageAtlasTexture&&a.imageAtlasTexture.bind(u.LINEAR,u.CLAMP_TO_EDGE),P.updatePaintBuffers());let F=!1;if(f&&a.imageAtlas){const e=a.imageAtlas,t=So.from(f),i=t.getPrimary().scaleSelf(T.devicePixelRatio).toString(),s=t.getSecondary(),o=e.patternPositions.get(i),r=s?e.patternPositions.get(s.scaleSelf(T.devicePixelRatio).toString()):null;F=!!o&&!!r,o&&P.setConstantPatternPositions(o,r)}p>0&&(F||P.getPatternTransitionVertexBuffer("fill-pattern"))&&O.push("FILL_PATTERN_TRANSITION");const k=o.getOrCreateProgram(_,{config:P,overrideFog:M,defines:O}),B=o.translatePosMatrix(C.projMatrix,a,n.paint.get("fill-translate"),n.paint.get("fill-translate-anchor"));y&&v.setupShadows(a.tileID.toUnwrapped(),k,"vector-tile");const N=n.paint.get("fill-emissive-strength");if(d){S=L.lineIndexBuffer,D=L.lineSegments;const e=o.terrain&&o.terrain.renderingToTexture?o.terrain.drapeBufferSize:[u.drawingBufferWidth,u.drawingBufferHeight];m="fillOutlinePattern"===_&&w?od(B,N,o,a,e,b,p):sd(B,N,e,b)}else S=L.indexBuffer,D=L.triangleSegments,m=w?id(B,N,o,a,b,p):td(B,N,b);o.uploadCommonUniforms(o.context,k,C.toUnwrapped());let U=e;if(("road"===c&&!h||"offset"===c)&&(U=x),!D||D.get&&0===D.get().length)continue;const V=s||o.stencilModeForClipping(C);let j="fallthrough";!d&&Il.drawFillFrcCoverageFirstPass&&(j=Il.drawFillFrcCoverageFirstPass({painter:o,layer:n,bucket:A,coord:C,elevatedGeometry:t,program:k,programConfiguration:P,uniformValues:m,drawMode:I,depthMode:U,stencilMode:V,colorMode:l,bufferData:L,indexBuffer:S,segments:D,dynamicBuffers:z,polygonCoverageTiles:R})),"fallthrough"===j&&k.draw(o,I,U,V,l,A_.disabled,m,n.id,L.layoutVertexBuffer,S,D,n.paint,o.transform.zoom,P,z)}!d&&Il.drawFillFrcCoverageSecondPass&&Il.drawFillFrcCoverageSecondPass(o,n,R,I,l)};o.renderPass===d&&I(o.depthModeForSublayer(1,"opaque"===o.renderPass?Cu.ReadWrite:Cu.ReadOnly),!1),"none"===m&&"translucent"===o.renderPass&&n.paint.get("fill-antialias")&&I(o.depthModeForSublayer(n.getPaintProperty("fill-outline-color")?2:0,Cu.ReadOnly),!0)}function W_(e,t,i,s,o,r,n,a){i.resetLayerRenderingStats(e);const l=e.context,c=l.gl,h=e.transform,d=i.paint.get("fill-extrusion-pattern"),u=i.paint.get("fill-extrusion-pattern-cross-fade"),_=d.constantOr(null),p=d.constantOr(1),f=i.paint.get("fill-extrusion-opacity"),m=e.style.enable3dLights(),g=i.paint.get(m&&!p?"fill-extrusion-ambient-occlusion-wall-radius":"fill-extrusion-ambient-occlusion-radius"),v=[i.paint.get("fill-extrusion-ambient-occlusion-intensity"),g],y=i.layout.get("fill-extrusion-edge-radius"),x=y>0&&!i.paint.get("fill-extrusion-rounded-roof"),b=x?0:y,w="globe"===h.projection.name?No():0,E="globe"===h.projection.name,I=E?K(h.zoom):0,S=[Ae(h.center.lng),Pe(h.center.lat)],D="none"===i.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default"),R=i.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(D?null:i.lut).toArray01().slice(0,3),C=i.paint.get("fill-extrusion-flood-light-intensity"),A=i.paint.get("fill-extrusion-vertical-scale"),L=0!==i.paint.get("fill-extrusion-line-width").constantOr(1),P=i.paint.get("fill-extrusion-height-alignment"),M=i.paint.get("fill-extrusion-base-alignment"),O=Iu(e,i.paint.get("fill-extrusion-cutoff-fade-range")),z=i.paint.get("fill-extrusion-front-cutoff"),F=$_(h.pitch,z,!!e.terrain),k=F[2]<1;k&&(e.maxFrontCutoffRawStart=Math.max(e.maxFrontCutoffRawStart,z[0]));const B=[];let N;E&&B.push("PROJECTION_GLOBE_VIEW"),v[0]>0&&B.push("FAUX_AO"),x&&B.push("ZERO_ROOF_RADIUS"),a&&B.push("HAS_CENTROID"),C>0&&B.push("FLOOD_LIGHT"),O.shouldRenderCutoff&&B.push("RENDER_CUTOFF"),k&&B.push("RENDER_FRONT_CUTOFF"),L&&B.push("RENDER_WALL_MODE");const U="shadow"===e.renderPass,V=e.shadowRenderer,j=U&&!!V,G=U?A_.disabled:A_.backCCW;e.shadowRenderer&&(e.shadowRenderer.useNormalOffset=!0);let q=[0,0,0];if(V){const t=e.style.directionalLight,i=e.style.ambientLight;t&&i&&(q=Gh(e.style,t,i)),U||(B.push("RENDER_SHADOWS"),V.useNormalOffset&&B.push("NORMAL_OFFSET")),N=B.concat(["SHADOWS_SINGLE_CASCADE"])}const Z=j?"fillExtrusionDepth":p?"fillExtrusionPattern":"fillExtrusion",W=i.getLayerRenderingStats();for(const d of s){const s=t.getTile(d),m=s.getBucket(i);if(!m||m.projection.name!==h.projection.name)continue;let g=!1;V&&(g=0===V.getMaxCascadeForTile(d.toUnwrapped()));const y=e.isTileAffectedByFog(d),x=m.programConfigurations.get(i.id);let D=!1;if(_&&s.imageAtlas){const e=s.imageAtlas,t=So.from(_),i=t.getPrimary().scaleSelf(T.devicePixelRatio).toString(),o=t.getSecondary(),r=e.patternPositions.get(i),n=o?e.patternPositions.get(o.scaleSelf(T.devicePixelRatio).toString()):null;D=!!r&&!!n,r&&x.setConstantPatternPositions(r,n)}u>0&&(D||x.getPatternTransitionVertexBuffer("fill-extrusion-pattern"))&&B.push("FILL_EXTRUSION_PATTERN_TRANSITION");const z=e.getOrCreateProgram(Z,{config:x,defines:g?N:B,overrideFog:y});if(e.terrain&&e.terrain.setupElevationDraw(s,z,{useMeterToDem:!0}),!m.centroidVertexBuffer){const e=z.getAttributeLocation(c,"a_centroid_pos");-1!==e&&c.vertexAttribI4ui(e,0,0,0,0)}!U&&V&&V.setupShadows(s.tileID.toUnwrapped(),z,"vector-tile"),p&&(e.context.activeTexture.set(c.TEXTURE0),s.imageAtlasTexture&&s.imageAtlasTexture.bind(c.LINEAR,c.CLAMP_TO_EDGE),x.updatePaintBuffers());const k=i.paint.get("fill-extrusion-vertical-gradient"),j=1/m.tileToMeter;let H;if(U&&V){if(Q_(s.tileID,m.maxHeight,e))continue;const t=V.calculateShadowPassMatrixFromTile(s.tileID.toUnwrapped());H=Qh(t,b,j,A,P,M)}else{const t=e.translatePosMatrix(d.expandedProjMatrix,s,i.paint.get("fill-extrusion-translate"),i.paint.get("fill-extrusion-translate-anchor")),o=h.projection.createInversionMatrix(h,d.canonical),r=z.fixedDefines.includes("LIGHTING_3D_MODE");H=p?ed(t,e,k,f,v,b,j,d,s,w,P,M,I,S,o,R,A,u,r):Jh(t,e,k,f,v,b,j,d,w,P,M,I,S,o,R,A,C,q,F,r)}e.uploadCommonUniforms(l,z,d.toUnwrapped(),null,O);let $=m.segments;if("mercator"===h.projection.name&&!U&&($=m.getVisibleSegments(s.tileID,e.terrain,e.transform.getFrustum(0)),!$.get().length))continue;if(W)if(U)for(const e of $.get())W.numRenderedVerticesInShadowPass+=e.primitiveLength;else for(const e of $.get())W.numRenderedVerticesInTransparentPass+=e.primitiveLength;const X=[];(e.terrain||a)&&X.push(m.centroidVertexBuffer),E&&X.push(m.layoutVertexExtBuffer),L&&X.push(m.wallVertexBuffer),z.draw(e,l.gl.TRIANGLES,o,r,n,G,H,i.id,m.layoutVertexBuffer,m.indexBuffer,$,i.paint,e.transform.zoom,x,X)}e.shadowRenderer&&(e.shadowRenderer.useNormalOffset=!1)}class H_{constructor(){this.translate=[0,0],this.translateAnchor="map",this.edgeRadius=0,this.cutoffFadeRange=0}}function $_(e,t,i){if(!(t[2]<1)||i)return[0,0,1];const s=180*e/Math.PI;if(s<15)return[-.5,t[1],t[2]];const o=Math.min(1,Math.max(0,(s-15)/5)),r=o*o*(3-2*o);return[-.5*(1-r)+t[0]*r,t[1],t[2]]}function X_(e,t,i,s,o,r,n){0===s.centroidVertexArray.length&&s.createCentroidsBuffer();const a=r?r.findDEMTileFor(i):null;if(!(a&&a.dem||n))return;r&&a&&a.dem&&s.selfDEMTileTimestamp!==a.dem._timestamp&&(s.borderDoneWithNeighborZ=[-1,-1,-1,-1],s.selfDEMTileTimestamp=a.dem._timestamp);const l=(e,t)=>{(e.flags|t.flags)&zo?(e.flags|=zo,t.flags|=zo):(e.flags&=~zo,t.flags&=~zo)},c=e=>new m(Math.ceil((e+Fo)*ko),0),h=(e,t,i)=>{const s=Math.ceil((e+Fo)*ko),o=Math.floor(Math.max(0,Math.min(ae-1,i))/4);return new m(s,o<<5|(3&t)<<3|7)},d=(e,t)=>{const i=Number.MAX_VALUE,s=t[0][0]!==i,o=t[1][0]!==i,r=t[2][0]!==i,n=t[3][0]!==i;if(!((s?1:0)+(o?1:0)+(r?1:0)+(n?1:0)>2))return e<2?r===n?void 0:r?0:ae-1:s===o?void 0:s?0:ae-1},u=(e,t,i,s)=>(t?d(e,t):void 0)??(s?d(i,s):void 0),_=e=>{const i=t.getSource().minzoom,s=e=>{const i=t.getTileByID(e);if(i&&i.hasData())return i.getBucket(o)},r=[0,-1,1];for(const t of r){if(e.overscaledZ+t<i)continue;const o=s(e.calculateScaledKey(e.overscaledZ+t));if(o)return o}},p=[0,0,0],f=(e,t)=>(p[0]=Math.min(e.min.y,t.min.y),p[1]=Math.max(e.max.y,t.max.y),p[2]=ae-t.min.x>e.max.x?t.min.x-ae:e.max.x,p),g=(e,t)=>(p[0]=Math.min(e.min.x,t.min.x),p[1]=Math.max(e.max.x,t.max.x),p[2]=ae-t.min.y>e.max.y?t.min.y-ae:e.max.y,p),v=[(e,t)=>f(e,t),(e,t)=>f(t,e),(e,t)=>g(e,t),(e,t)=>g(t,e)],y=(e,t,s,o,n,l,c)=>{if(!r)return 0;const h=[[l?s:e,l?e:s,0],[l?s:t,l?t:s,0]],d=c<0?ae+c:c,u=[l?d:(e+t)/2,l?(e+t)/2:d,0];return 0===s&&c<0||0!==s&&c>0?r.getForTilePoints(n,[u],!0,o):h.push(u),r.getForTilePoints(i,h,!0,a),Math.max(h[0][2],h[1][2],u[2])/r.exaggeration()};for(let e=0;e<4;e++){const t=s.borderFeatureIndices[e];if(0===t.length)continue;const o=Mo[e](i),a=_(o);if(!(a&&a instanceof Oo))continue;const d=r?r.findDEMTileFor(o):null;if(!(d&&d.dem||n))continue;if(r&&d&&d.dem&&s.borderDEMTileTimestamp[e]!==d.dem._timestamp&&(s.borderDoneWithNeighborZ[e]=-1,s.borderDEMTileTimestamp[e]=d.dem._timestamp),s.borderDoneWithNeighborZ[e]===a.canonical.z)continue;0===a.centroidVertexArray.length&&a.createCentroidsBuffer();const p=(e<2?1:5)-e,f=a.borderDoneWithNeighborZ[p]!==s.canonical.z,g=a.borderFeatureIndices[p];let x=0;if(s.canonical.z!==a.canonical.z){for(const e of t)s.showCentroid(s.featuresOnBorder[e],"discard");if(f)for(const e of g)a.showCentroid(a.featuresOnBorder[e],"discard");s.borderDoneWithNeighborZ[e]=a.canonical.z,a.borderDoneWithNeighborZ[p]=s.canonical.z;continue}const b=new Map,w=new Set,T=new Set;for(let e=0;e<g.length;e++){const t=a.featuresOnBorder[g[e]];void 0!==t.buildingId&&b.set(t.buildingId,e)}for(const i of t){const t=s.featuresOnBorder[i],c=s.centroidData.get(t.centroidDataIndex);if(void 0===t.buildingId)continue;const _=b.get(t.buildingId);if(void 0===_)continue;const f=a.featuresOnBorder[g[_]],m=a.centroidData.get(f.centroidDataIndex);w.add(i),T.add(_),n&&l(c,m);const x=0!==c.groupCentroidPos.x||0!==c.groupCentroidPos.y?c.groupCentroidPos:t.centroid(),E=0!==m.groupCentroidPos.x||0!==m.groupCentroidPos.y?m.groupCentroidPos:f.centroid(),I=r?void 0:u(e,t.borders,p,f.borders),S=void 0!==I?I:e<2?Math.round((x.y+E.y)/2):Math.round((x.x+E.x)/2),D=t.intersectsCount()>1||f.intersectsCount()>1;{let t=0;if(d&&d.dem&&!D){const i=v[e](c,m),s=e%2?ae-1:0;t=y(i[0],Math.min(ae-1,i[1]),s,d,o,e<2,i[2])}c.centroidXY=h(t,e,S),m.centroidXY=h(t,p,S)}s.writeCentroidToBuffer(c),a.writeCentroidToBuffer(m),s.setBuildingCentroid(t.buildingId,c.centroidXY),a.setBuildingCentroid(t.buildingId,m.centroidXY)}for(const i of t){if(w.has(i))continue;const t=s.featuresOnBorder[i],_=s.centroidData.get(t.centroidDataIndex),f=t.borders[e];let b;for(;x<g.length;){if(T.has(x)){x++;continue}b=a.featuresOnBorder[g[x]];const e=b.borders[p];if(e[1]>f[0]+3||e[0]>f[0]-3)break;a.showCentroid(b,"keep"),x++}if(b&&x<g.length){let i=x,w=0;for(;;)if(T.has(x)){if(++x===g.length)break;b=a.featuresOnBorder[g[x]]}else{if(b.borders[p][0]>f[1]-3)break;if(w++,++x===g.length)break;b=a.featuresOnBorder[g[x]]}for(;i<g.length&&T.has(i);)i++;if(i>=g.length){s.showCentroid(t,"keep");continue}b=a.featuresOnBorder[g[i]];let E=!1;if(w>=1){const e=b.borders[p];Math.abs(f[0]-e[0])<3&&Math.abs(f[1]-e[1])<3&&(w=1,E=!0,x=i+1)}else if(0===w){s.showCentroid(t,"keep");continue}const I=a.centroidData.get(b.centroidDataIndex);n&&E&&l(_,I);const S=t.intersectsCount()>1||b.intersectsCount()>1;if(w>1)x=i,_.centroidXY=I.centroidXY=new m(0,0);else if(d&&d.dem&&!S){const t=v[e](_,I),i=e%2?ae-1:0,s=y(t[0],Math.min(ae-1,t[1]),i,d,o,e<2,t[2]);_.centroidXY=I.centroidXY=c(s)}else if(S){const i=r?void 0:u(e,t.borders,p,b.borders);void 0!==i?(_.centroidXY=h(0,e,i),I.centroidXY=h(0,p,i)):_.centroidXY=I.centroidXY=new m(0,0)}else _.centroidXY=s.encodeBorderCentroid(t),I.centroidXY=a.encodeBorderCentroid(b);s.writeCentroidToBuffer(_),a.writeCentroidToBuffer(I)}else s.showCentroid(t,"keep")}s.borderDoneWithNeighborZ[e]=a.canonical.z,a.borderDoneWithNeighborZ[p]=s.canonical.z}(s.needsCentroidUpdate||!s.centroidVertexBuffer&&0!==s.centroidVertexArray.length)&&s.uploadCentroid(e)}const Y_=[1,0,0],K_=[0,1,0],J_=[0,0,1];function Q_(e,t,i){const s=i.transform,o=i.shadowRenderer;if(!o)return!0;const r=i.frameCounter,n=i.currentShadowCascade;let a=i._shadowCullCache;if(!a||a.frame!==r||a.cascade!==n){const e=s.tileSize*o._cascades[n].scale,t=s.scaleZoom(e),l=o.shadowDirection,c=[l[0],l[1],-l[2]],h=[Y_,K_,J_,c,[c[0],0,c[2]],[0,c[1],c[2]]];a={frame:r,cascade:n,cameraFrustum:so.fromInvProjectionMatrix(s.invProjMatrix,s.worldSize,t,!("globe"===s.projection.name)),edges:h,shadowDir:c,ws:e,zoom:t},i._shadowCullCache=a}const{cameraFrustum:l,edges:c,shadowDir:h,ws:d,zoom:u}=a;let _=t;if(s.elevation){const t=s.elevation.getMinMaxForTile(e);t&&(_+=t.max)}_/=Bo(s.center.lat,u);const p=o.computeSimplifiedTileShadowVolume(e.toUnwrapped(),_,d,h);if(!p)return!1;const{vertices:f,planes:m}=p;return 0===l.intersectsPrecise(f,m,c)||0===o.getCurrentCascadeFrustum().intersectsPrecise(f,m,c)}function ep(e,t,i,s,o,r,n){const a=e.context,l=a.gl,c=i.hillshadeFBO;if(!c)return;e.prepareDrawTile();const h=e.isTileAffectedByFog(t),d=[];e.terrain&&e.terrain.renderingToTexture&&e.isEmissiveMrtActive()&&(d.push("USE_MRT1"),"mrt-full-rgba"===e.emissiveMode&&d.push("USE_MRT1_RGBA"));const u=e.getOrCreateProgram("hillshade",{overrideFog:h,defines:d});a.activeTexture.set(l.TEXTURE0),l.bindTexture(l.TEXTURE_2D,c.colorAttachment0.get());const _=((e,t,i,s)=>{const o=i.paint.get("hillshade-shadow-color"),r="none"===i.paint.get("hillshade-shadow-color-use-theme").constantOr("default"),n=i.paint.get("hillshade-highlight-color"),a="none"===i.paint.get("hillshade-highlight-color-use-theme").constantOr("default"),l=i.paint.get("hillshade-accent-color"),c="none"===i.paint.get("hillshade-accent-color-use-theme").constantOr("default"),h=i.paint.get("hillshade-emissive-strength");let d=le(i.paint.get("hillshade-illumination-direction"));if("viewport"===i.paint.get("hillshade-illumination-anchor"))d-=e.transform.angle;else if(e.style&&e.style.enable3dLights()&&e.style.directionalLight){const t=e.style.directionalLight.properties.get("direction"),i=Ii(t.x,t.y,t.z);d=le(i[1])}const u=!e.options.moving;return{u_matrix:s||e.transform.calculateProjMatrix(t.tileID.toUnwrapped(),u),u_image:0,u_latrange:_d(0,t.tileID),u_light:[i.paint.get("hillshade-exaggeration"),d],u_shadow:o.toPremultipliedRenderColor(r?null:i.lut),u_highlight:n.toPremultipliedRenderColor(a?null:i.lut),u_emissive_strength:h,u_accent:l.toPremultipliedRenderColor(c?null:i.lut)}})(e,i,s,e.terrain?t.projMatrix:null);e.uploadCommonUniforms(a,u,t.toUnwrapped());const{tileBoundsBuffer:p,tileBoundsIndexBuffer:f,tileBoundsSegments:m}=e.getTileBoundsBuffers(i);u.draw(e,l.TRIANGLES,o,r,n,A_.disabled,_,s.id,p,f,m)}function tp(e,t,i){if(!t.needsDEMTextureUpload)return;const s=e.context,o=s.gl;s.pixelStoreUnpackPremultiplyAlpha.set(!1),t.demTexture=t.demTexture||e.getTileTexture(i.stride);const r=i.getPixels();t.demTexture?t.demTexture.update(r,{premultiply:!1}):t.demTexture=new k(s,r,o.R32F,{premultiply:!1}),t.needsDEMTextureUpload=!1}function ip(e,t,i){const s=e.context,o=s.gl;if(!t.dem)return;const r=t.dem;if(s.activeTexture.set(o.TEXTURE1),tp(e,t,r),!t.demTexture)return;t.demTexture.bind(o.NEAREST,o.CLAMP_TO_EDGE);const n=r.dim;s.activeTexture.set(o.TEXTURE0);let a=t.hillshadeFBO;if(!a){const e=new k(s,{width:n,height:n,data:null},o.RGBA8);e.bind(o.LINEAR,o.CLAMP_TO_EDGE),a=t.hillshadeFBO=s.createFramebuffer(n,n,1,"renderbuffer"),a.colorAttachment0.set(e.texture)}s.bindFramebuffer.set(a.framebuffer),s.viewport.set([0,0,n,n]);const{tileBoundsBuffer:l,tileBoundsIndexBuffer:c,tileBoundsSegments:h}=e.getMercatorTileBoundsBuffers(),d=[];e.linearFloatFilteringSupported()&&d.push("TERRAIN_DEM_FLOAT_FORMAT"),e.terrain&&e.terrain.renderingToTexture&&e.isEmissiveMrtActive()&&(d.push("USE_MRT1"),"mrt-full-rgba"===e.emissiveMode&&d.push("USE_MRT1_RGBA")),e.getOrCreateProgram("hillshadePrepare",{defines:d}).draw(e,o.TRIANGLES,Cu.disabled,Pu.disabled,zu.unblended,A_.disabled,((e,t)=>{const i=t.stride,s=Bt();return ki(s,0,ae,-ae,0,0,1),At(s,s,[0,-ae,0]),{u_matrix:s,u_image:1,u_dimension:[i,i],u_zoom:e.overscaledZ}})(t.tileID,r),i.id,l,c,h),t.needsHillshadePrepare=!1}function sp(e,t,i,s,o){if(o>0){const r=T.now(),n=(r-e.timeAdded)/o,a=t?(r-t.timeAdded)/o:-1,l=i.getSource(),c=s.coveringZoomLevel({tileSize:l.tileSize,roundZoom:l.roundZoom}),h=!t||Math.abs(t.tileID.overscaledZ-c)>Math.abs(e.tileID.overscaledZ-c),d=h&&e.refreshedUponExpiration?1:Ee(h?n:1-a,0,1);return t?{opacity:1,mix:1-d,isFading:n<1}:{opacity:d,mix:0,isFading:n<1}}return{opacity:1,mix:0,isFading:!1}}function op(e){return[e[0]*Wo,e[1]*Wo,e[2]*Wo,0]}function rp(e,t,i,s,o,r,n,a,l,c){const h=o.getSource(),d=s.globeSharedBuffers;if(!d)return;let u,_,p;if(i&&(u=o.getTile(i)),h instanceof Hl?(_=h.texture,p=Uo(0,0,s.transform)):u&&i&&(_=u.texture,p=Uo(i.canonical.z,i.canonical.x,s.transform)),!_||!p)return;t||(p=Ys(Bt(),p,[1,-1,1]));const f=s.context,m=f.gl,g="nearest"===r.paint.get("raster-resampling")?m.NEAREST:m.LINEAR,v=s.colorModeForDrapableLayerRenderPass(n),y=a.defines;y.push("GLOBE_POLES");const x=new Cu(m.LEQUAL,Cu.ReadWrite,s.depthRangeFor3D),b=s.transform.expandedFarZProjMatrix,w=Float32Array.from(wt(Vo(new $e(0,0,0))));s.terrain&&s.terrain.prepareDrawTile(),f.activeTexture.set(m.TEXTURE0),_.bind(g,m.CLAMP_TO_EDGE),f.activeTexture.set(m.TEXTURE1),_.bind(g,m.CLAMP_TO_EDGE),"useMipmap"in _&&f.extTextureFilterAnisotropic&&s.transform.pitch>20&&m.texParameterf(m.TEXTURE_2D,f.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,f.extTextureFilterAnisotropicMax);const[T,E,I,S]=i?d.getPoleBuffers(i.canonical.z,!1):d.getPoleBuffers(0,!0),D=e;let R;t?(R=T,s.renderDefaultNorthPole=0!==D):(R=E,s.renderDefaultSouthPole=0!==D);const C=op(a.mix),A=((e,t,i,s,o,r,n,a,l,c,h,d,u,_)=>gd(e,t,i,s,new Float32Array(16),new Float32Array(9),[0,0],o,[0,0],[0,0,0,0],1,{opacity:1,mix:0},n,[0,0]||[0,0],l,2,h,d,u,1,0,_))(s,b,w,p,K(s.transform.zoom),0,r,0,D,0,C,a.offset,a.range,n),L=s.getOrCreateProgram("raster",{defines:y});s.uploadCommonUniforms(f,L,null),L.draw(s,m.TRIANGLES,x,c,v,l,A,r.id,R,I,S)}function np(e){if(e.isOrthographic)return[0,0,0,0];const t=e._nearZ,i=e.projection.farthestPixelDistance(e),s=i-t,o=.2*e.height,r=t+o;return[t,i,(r-o-t)/s,(r-t)/s]}function ap(e,t,i,s){if(e)return"raster-array"===t.type?t.getTextureDescriptor(e,i,!0):{texture:e.texture,mix:op(s.mix),offset:s.offset,buffer:0,tileSize:1}}const lp=ci(new Float32Array(16)),cp={"dual-source-blending":"dual-source-blending","mrt-fallback":"mrt","mrt-full-rgba":"mrt-rgba"},hp=qe([{name:"a_pos_3f",components:3,type:"Float32"}]),{members:dp}=hp;function up(e,t,i,s){e.emplaceBack(t,i,s)}class _p{constructor(e){this.vertexArray=new $o,this.indices=new Ke,up(this.vertexArray,-1,-1,1),up(this.vertexArray,1,-1,1),up(this.vertexArray,-1,1,1),up(this.vertexArray,1,1,1),up(this.vertexArray,-1,-1,-1),up(this.vertexArray,1,-1,-1),up(this.vertexArray,-1,1,-1),up(this.vertexArray,1,1,-1),this.indices.emplaceBack(5,1,3),this.indices.emplaceBack(3,7,5),this.indices.emplaceBack(6,2,0),this.indices.emplaceBack(0,4,6),this.indices.emplaceBack(2,6,7),this.indices.emplaceBack(7,3,2),this.indices.emplaceBack(5,4,0),this.indices.emplaceBack(0,1,5),this.indices.emplaceBack(0,2,3),this.indices.emplaceBack(3,1,0),this.indices.emplaceBack(7,6,4),this.indices.emplaceBack(4,5,7),this.vertexBuffer=e.createVertexBuffer(this.vertexArray,dp),this.indexBuffer=e.createIndexBuffer(this.indices),this.segment=Ye.simpleSegment(0,0,36,12)}}function pp(e,t,i,s,o,r){const n=e.context.gl,a=t.paint.get("sky-atmosphere-color"),l=t.paint.get("sky-atmosphere-halo-color"),c=t.paint.get("sky-atmosphere-sun-intensity"),h=((e,t,i,s,o)=>({u_matrix_3f:e,u_sun_direction:t,u_sun_intensity:i,u_color_tint_r:[s.r,s.g,s.b,s.a],u_color_tint_m:[o.r,o.g,o.b,o.a],u_luminance:5e-5}))(Ko(Mi(),s),o,c,a.toPremultipliedRenderColor(null),l.toPremultipliedRenderColor(null));n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_CUBE_MAP_POSITIVE_X+r,t.skyboxTexture,0),i.draw(e,n.TRIANGLES,Cu.disabled,Pu.disabled,zu.unblended,A_.frontCW,h,"skyboxCapture",t.skyboxGeometry.vertexBuffer,t.skyboxGeometry.indexBuffer,t.skyboxGeometry.segment)}const fp=qe([{type:"Float32",name:"a_pos",components:3},{type:"Float32",name:"a_uv",components:2}]);class mp{constructor(e){const t=new Jo;t.emplaceBack(-1,1,1,0,0),t.emplaceBack(1,1,1,1,0),t.emplaceBack(1,-1,1,1,1),t.emplaceBack(-1,-1,1,0,1);const i=new Ke;i.emplaceBack(0,1,2),i.emplaceBack(2,3,0),this.vertexBuffer=e.createVertexBuffer(t,fp.members),this.indexBuffer=e.createIndexBuffer(i),this.segments=Ye.simpleSegment(0,0,4,2)}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy()}}const gp=qe([{type:"Float32",name:"a_pos_3f",components:3},{type:"Float32",name:"a_uv",components:2},{type:"Float32",name:"a_size_scale",components:1},{type:"Float32",name:"a_opacity",components:1}]);class vp{constructor(){this.colorModeAlphaBlendedWriteRGB=new zu([1,Ou,1,Ou],S.transparent,[!0,!0,!0,!1]),this.colorModeWriteAlpha=new zu(zu.Replace,S.transparent,[!1,!1,!1,!0]),this.params={starsCount:16e3,sizeMultiplier:.15,sizeRange:100,intensityRange:200},this.updateNeeded=!0,this._painter=null,this._devtoolsFolder=null}update(e){this._painter=e;const t=e.context;if(!this.atmosphereBuffer||this.updateNeeded){this.updateNeeded=!1,this.atmosphereBuffer=new mp(t);let e=this.params;const i=e.sizeRange,s=e.intensityRange,o=function(e){const t=or(30),i=[];for(let s=0;s<e;++s){const e=2*Math.PI*t(),s=Math.acos(1-2*t())-.5*Math.PI;i.push(bi(Math.cos(s)*Math.cos(e),Math.cos(s)*Math.sin(e),Math.sin(s)))}return i}(e.starsCount),r=or(300),n=new Qo,a=new Ke;let l=0;for(let e=0;e<o.length;++e){const t=Ti([],o[e],200),c=Math.max(0,1+.01*i*(1*r()-.5)),h=Math.max(0,1+.01*s*(1*r()-.5));n.emplaceBack(t[0],t[1],t[2],-1,-1,c,h),n.emplaceBack(t[0],t[1],t[2],1,-1,c,h),n.emplaceBack(t[0],t[1],t[2],1,1,c,h),n.emplaceBack(t[0],t[1],t[2],-1,1,c,h),a.emplaceBack(l+0,l+1,l+2),a.emplaceBack(l+0,l+2,l+3),l+=4}this.starsVx=t.createVertexBuffer(n,gp.members),this.starsIdx=t.createIndexBuffer(a),this.starsSegments=Ye.simpleSegment(0,0,n.length,a.length)}}destroy(){this.atmosphereBuffer&&this.atmosphereBuffer.destroy(),this.starsVx&&this.starsVx.destroy(),this.starsIdx&&this.starsIdx.destroy(),this._painter=null}drawAtmosphereGlow(e,t){const i=e.context,s=i.gl,o=e.transform,r=new Cu(s.LEQUAL,Cu.ReadOnly,[0,1]),n=K(o.zoom),a=e.style.getLut(t.scope),l="none"===t.properties.get("color-use-theme"),c=t.properties.get("color").toNonPremultipliedRenderColor(l?null:a),h="none"===t.properties.get("high-color-use-theme"),d=t.properties.get("high-color").toNonPremultipliedRenderColor(h?null:a),u="none"===t.properties.get("space-color-use-theme"),_=t.properties.get("space-color").toNonPremultipliedRenderColor(u?null:a),p=5e-4,f=er(t.properties.get("horizon-blend"),0,1,p,.25),m=tr(e,i,o)&&f===p?o.worldSize/(2*Math.PI*1.025)-1:o.globeRadius,g=e.frameCounter/1e3%1,v=_s(o.globeCenterInViewSpace),y=Math.sqrt(Math.pow(v,2)-Math.pow(m,2)),x=Math.acos(y/v),b=t=>{const a="globe"===o.projection.name?["PROJECTION_GLOBE_VIEW","FOG"]:["FOG"];t&&a.push("ALPHA_PASS");const l=e.getOrCreateProgram("globeAtmosphere",{defines:a}),h=((e,t,i,s,o,r,n,a,l,c,h,d)=>({u_frustum_tl:e,u_frustum_tr:t,u_frustum_br:i,u_frustum_bl:s,u_horizon:o,u_transition:r,u_fadeout_range:n,u_atmosphere_fog_color:a.toArray01(),u_high_color:l.toArray01(),u_space_color:c.toArray01(),u_temporal_offset:h,u_horizon_angle:d}))(o.frustumCorners.TL,o.frustumCorners.TR,o.frustumCorners.BR,o.frustumCorners.BL,o.frustumCorners.horizon,n,f,c,d,_,g,x);e.uploadCommonUniforms(i,l);const u=this.atmosphereBuffer;u&&l.draw(e,s.TRIANGLES,r,Pu.disabled,t?this.colorModeWriteAlpha:this.colorModeAlphaBlendedWriteRGB,A_.backCW,h,t?"atmosphere_glow_alpha":"atmosphere_glow",u.vertexBuffer,u.indexBuffer,u.segments)};b(!1),b(!0)}drawStars(e,t){const i=Ee(t.properties.get("star-intensity"),0,1);if(0===i)return;const s=e.context,o=s.gl,r=e.transform,n=e.getOrCreateProgram("stars"),a=fs([]);gs(a,a,-r._pitch),ms(a,a,-r.angle),gs(a,a,le(r._center.lat)),ir(a,a,-le(r._center.lng));const l=ys(new Float32Array(16),a),c=Ie([],r.starsProjMatrix,l),h=Ko([],l),d=sr([],h);let u=this.params.sizeMultiplier;const _=[0,1,0];Qe(_,_,d),Ti(_,_,u);const p=[1,0,0];Qe(p,p,d),Ti(p,p,u);const f=(m=_,g=p,v=i,{u_matrix:Float32Array.from(c),u_up:m,u_right:g,u_intensity_multiplier:v});var m,g,v;e.uploadCommonUniforms(s,n),this.starsVx&&this.starsIdx&&n.draw(e,o.TRIANGLES,Cu.disabled,Pu.disabled,this.colorModeAlphaBlendedWriteRGB,A_.disabled,f,"atmosphere_stars",this.starsVx,this.starsIdx,this.starsSegments)}}let yp=null;const xp=[];function bp(e){yp=e;for(const e of xp.splice(0))e()}function wp(e,t){return yp?yp.create(e,t):null}class Tp{}class Ep{constructor(){this._storage=new Map}getLinesFromTrianglesBuffer(e,t,i){{const i=this._storage.get(t.id);if(i)return i.lastUsedFrameIdx=e,i.buf}const s=i.gl,o=s.getBufferParameter(s.ELEMENT_ARRAY_BUFFER,s.BUFFER_SIZE),r=new ArrayBuffer(o),n=new Int16Array(r);s.getBufferSubData(s.ELEMENT_ARRAY_BUFFER,0,new Int16Array(r));const a=new rr;for(let e=0;e<o/2;e+=3){const t=n[e],i=n[e+1],s=n[e+2];a.emplaceBack(t,i),a.emplaceBack(i,s),a.emplaceBack(s,t)}const l=i.bindVertexArrayOES.current,c=new Tp;return c.buf=new Uu(i,a),c.lastUsedFrameIdx=e,this._storage.set(t.id,c),i.bindVertexArrayOES.set(l),c.buf}update(e){for(const[t,i]of this._storage)e-i.lastUsedFrameIdx>30&&(i.buf.destroy(),this._storage.delete(t))}destroy(){for(const[e,t]of this._storage)t.buf.destroy(),this._storage.delete(e)}}class Ip{constructor(){this.occluderSize=30,this.depthOffset=-1e-4}}const Sp={symbol:function(e,t,i,s,o){if("translucent"!==e.renderPass)return;const r=Pu.disabled,n=e.colorModeForRenderPass(),a=i.layout.get("text-variable-anchor"),l=i.layout.get("text-size-scale-range"),c=Ee(e.scaleFactor,l[0],l[1]);a&&function(e,t,i,s,o,r,n,a){const l=t.transform,c="map"===o,h="map"===r;for(const t of e){const e=s.getTile(t),o=e.getBucket(i);if(!o||!o.text||!o.text.segments.get().length)continue;const r=jt(o.textSizeData,l.zoom,a),d=bo(t,o.getProjection(),l),u=l.calculatePixelsToTileUnitsMatrix(e),_=Uc(d,e.tileID.canonical,h,c,l,o.getProjection(),u),p=o.hasIconTextFit()&&o.hasIconData();r&&M_(o,c,h,n,l,_,t,Math.pow(2,l.zoom-e.tileID.overscaledZ),r,p)}}(s,e,i,t,i.layout.get("text-rotation-alignment"),i.layout.get("text-pitch-alignment"),o,c);const h=0!==i.paint.get("icon-opacity").constantOr(1),d=0!==i.paint.get("text-opacity").constantOr(1);void 0!==i.layout.get("symbol-sort-key").constantOr(1)&&(h||d)?O_(e,t,i,s,r,n):(h&&O_(e,t,i,s,r,n,{onlyIcons:!0}),d&&O_(e,t,i,s,r,n,{onlyText:!0})),t.map.showCollisionBoxes&&"global"!==t.map._placementAlgorithm&&Ca.drawCollisionDebug&&(Ca.drawCollisionDebug(e,t,i,s,i.paint.get("text-translate"),i.paint.get("text-translate-anchor"),!0),Ca.drawCollisionDebug(e,t,i,s,i.paint.get("icon-translate"),i.paint.get("icon-translate-anchor"),!1))},circle:function(e,t,i,s){if("translucent"!==e.renderPass)return;const o=i.paint.get("circle-opacity"),r=i.paint.get("circle-stroke-width"),n=i.paint.get("circle-stroke-opacity"),a=void 0!==i.layout.get("circle-sort-key").constantOr(1),l=i.paint.get("circle-emissive-strength");if(0===o.constantOr(1)&&(0===r.constantOr(1)||0===n.constantOr(1)))return;const c=e.context,h=c.gl,d=e.transform,u=!(!e.terrain||!e.terrain.enabled),_=i.layout.get("circle-elevation-reference"),p=e.depthModeForSublayer(0,Cu.ReadOnly),f=new Cu(e.context.gl.LEQUAL,Cu.ReadOnly,e.depthRangeFor3D),m="none"===_||u?p:f,g=Pu.disabled,v=e.colorModeForDrapableLayerRenderPass(l),y="globe"===d.projection.name,x=[Ae(d.center.lng),Pe(d.center.lat)],b=[];for(let o=0;o<s.length;o++){const r=s[o],n=t.getTile(r),l=n.getBucket(i);if(!l||l.projection.name!==d.projection.name)continue;const c=l.programConfigurations.get(i.id),h=l.layoutVertexBuffer,u=l.globeExtVertexBuffer,_=l.indexBuffer,p=To(i),f=[u],m=e.isTileAffectedByFog(r);y&&p.push("PROJECTION_GLOBE_VIEW"),p.push("DEPTH_D24"),e.terrain&&d.depthOcclusionForSymbolsAndCircles&&p.push("DEPTH_OCCLUSION"),l.hdExt&&l.hdExt.hasElevation&&!e.terrain&&(p.push("ELEVATED_ROADS"),f.push(l.hdExt.elevatedLayoutVertexBuffer));const g=e.getOrCreateProgram("circle",{config:c,defines:p,overrideFog:m}),v=d.projection.createInversionMatrix(d,r.canonical),w={programConfiguration:c,program:g,layoutVertexBuffer:h,dynamicBuffers:f,indexBuffer:_,uniformValues:Eo(e,r,n,v,x,i),tile:n};if(a){const e=l.segments.get();for(const t of e)b.push({segments:new Ye([t]),sortKey:t.sortKey,state:w})}else b.push({segments:l.segments,sortKey:0,state:w})}a&&b.sort((e,t)=>e.sortKey-t.sortKey);const w={useDepthForOcclusion:d.depthOcclusionForSymbolsAndCircles};for(const t of b){const{programConfiguration:s,program:o,layoutVertexBuffer:r,dynamicBuffers:n,indexBuffer:a,uniformValues:l,tile:u}=t.state,_=t.segments;e.terrain&&e.terrain.setupElevationDraw(u,o,w),e.uploadCommonUniforms(c,o,u.tileID.toUnwrapped()),o.draw(e,h.TRIANGLES,m,g,v,A_.disabled,l,i.id,r,a,_,i.paint,d.zoom,s,n)}},heatmap:function(e,t,i,s){if(0!==i.paint.get("heatmap-opacity"))if("offscreen"===e.renderPass){const o=e.context,r=o.gl,n=Pu.disabled,a=new zu([r.ONE,r.ONE,r.ONE,r.ONE],S.transparent,[!0,!0,!0,!0]),l="globe"===e.transform.projection.name?.5:.25;i.heatmapFbo=S_.createWithTexture(o,i.heatmapFbo,e.width*l,e.height*l),o.clear({color:S.transparent});const c=e.transform,h="globe"===c.projection.name,d=h?["PROJECTION_GLOBE_VIEW"]:[],u=h?A_.frontCCW:A_.disabled,_=[Ae(c.center.lng),Pe(c.center.lat)];for(let l=0;l<s.length;l++){const p=s[l];if(t.hasRenderableParent(p))continue;const f=t.getTile(p),m=f.getBucket(i);if(!m||m.projection.name!==c.projection.name)continue;const g=e.isTileAffectedByFog(p),v=m.programConfigurations.get(i.id),y=e.getOrCreateProgram("heatmap",{config:v,defines:d,overrideFog:g}),{zoom:x}=e.transform;e.terrain&&e.terrain.setupElevationDraw(f,y),e.uploadCommonUniforms(o,y,p.toUnwrapped());const b=c.projection.createInversionMatrix(c,p.canonical);y.draw(e,r.TRIANGLES,Cu.disabled,n,a,u,ud(e,p,f,b,_,x,i.paint.get("heatmap-intensity")),i.id,m.layoutVertexBuffer,m.indexBuffer,m.segments,i.paint,e.transform.zoom,v,h?[m.globeExtVertexBuffer]:null)}o.viewport.set([0,0,e.width,e.height])}else"translucent"===e.renderPass&&(e.context.setColorMode(e.colorModeForRenderPass()),function(e,t){const i=e.context,s=i.gl,o=t.heatmapFbo;if(!o)return;i.activeTexture.set(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,o.colorAttachment0.get()),i.activeTexture.set(s.TEXTURE1);let r=t.colorRampTexture;r||(r=t.colorRampTexture=new k(i,t.colorRamp,s.RGBA8)),r.bind(s.LINEAR,s.CLAMP_TO_EDGE),e.getOrCreateProgram("heatmapTexture").draw(e,s.TRIANGLES,Cu.disabled,Pu.disabled,e.colorModeForRenderPass(),A_.disabled,((e,t)=>({u_image:0,u_color_ramp:1,u_opacity:t.paint.get("heatmap-opacity")}))(0,t),t.id,e.viewportBuffer,e.quadTriangleIndexBuffer,e.viewportSegments,t.paint,e.transform.zoom)}(e,i))},line:function(e,t,i,s){const o=i.paint.get("line-opacity"),r=i.paint.get("line-width");if(0===o.constantOr(1)||0===r.constantOr(1))return;const n=i.paint.get("line-blend-mode"),a=e.terrain&&e.terrain.renderingToTexture;if("default"===n||"globe"===e.transform.projection.name)"translucent"===e.renderPass&&F_(e,t,i,s);else{if(a)return void function(e,t,i,s,o){if("translucent"!==e.renderPass)return;const r=e.context,n=r.gl,a=e.terrain;if(!a)return;const l=r.bindFramebuffer.current,c=e.isEmissiveMrtActive(),h=a.drapeBufferSize[0],d=a.drapeBufferSize[1];i.lineBlendFbos||(i.lineBlendFbos=new k_),i.lineBlendFbos.drapeFbo=S_.createWithTexture(r,i.lineBlendFbos.drapeFbo,h,d,!0),c&&n.drawBuffers([n.COLOR_ATTACHMENT0]),r.clear({color:N_[o].clearColor,depth:1,stencil:0});const u=e.currentStencilSource,_=e._tileClippingMaskIDs,p=e.nextStencilID;e.currentStencilSource=void 0,e._tileClippingMaskIDs=new Map,e.nextStencilID=1;const f=e._terrain;e._terrain=null,e._renderTileClippingMasks(i,t,s),F_(e,t,i,s,V_(o,e.context),!0),e._terrain=f,e.currentStencilSource=u,e._tileClippingMaskIDs=_,e.nextStencilID=p,c&&n.drawBuffers([n.COLOR_ATTACHMENT0,n.COLOR_ATTACHMENT1]);const m=a.drapeBufferSize,g=i.lineBlendFbos&&i.lineBlendFbos.drapeFbo;g&&("additive"===o&&G_(e,i,g),q_(e,i,o,g,l,m))}(e,t,i,s,n);if("offscreen"===e.renderPass)return void function(e,t,i,s,o){const r=e.context,n=Math.ceil(e.width),a=Math.ceil(e.height);i.lineBlendFbos||(i.lineBlendFbos=new k_),i.lineBlendFbos.fbo=S_.createWithTexture(r,i.lineBlendFbos.fbo,n,a,!0),r.clear({color:N_[o].clearColor,depth:1,stencil:0});const l=e.currentStencilSource,c=e._tileClippingMaskIDs,h=e.nextStencilID;e.currentStencilSource=void 0,e._tileClippingMaskIDs=new Map,e.nextStencilID=1,e._renderTileClippingMasks(i,t,s);const d=e.renderPass;e.renderPass="translucent",F_(e,t,i,s,V_(o,e.context)),e.renderPass=d,e.currentStencilSource=l,e._tileClippingMaskIDs=c,e.nextStencilID=h,r.viewport.set([0,0,e.width,e.height]),"additive"===o&&G_(e,i,i.lineBlendFbos.fbo)}(e,t,i,s,n);if("translucent"===e.renderPass){const t=i.lineBlendFbos&&i.lineBlendFbos.fbo;return void(t&&q_(e,i,n,t,null))}}},fill:function(e,t,i,s){const o=i.paint.get("fill-color"),r=i.paint.get("fill-opacity");if(0===r.constantOr(1))return;const n=i.paint.get("fill-emissive-strength"),a=e.colorModeForDrapableLayerRenderPass(n),l=i.paint.get("fill-pattern"),c=e.opaquePassEnabledForLayer()&&!l.constantOr(1)&&1===o.constantOr(S.transparent).a&&1===r.constantOr(0)?"opaque":"translucent";let h="none";"none"!==i.layout.get("fill-elevation-reference")?h="road":0!==i.paint.get("fill-z-offset").constantOr(1)&&(h="offset");const d=!(!e.terrain||!e.terrain.enabled),u={painter:e,sourceCache:t,layer:i,coords:s,colorMode:a,elevationType:h,terrainEnabled:d,pass:c};if("shadow"===e.renderPass)return void(e.shadowRenderer&&"road"===h&&!d&&Il.drawElevatedFillShadows&&Il.drawElevatedFillShadows(u));const _=e.isEmissiveMrtActive();if("offset"!==h){if(Z_(u,!1,_),"road"===h){const o=!d&&"translucent"===e.renderPass;o&&Il.drawDepthPrepass&&Il.drawDepthPrepass(e,t,i,s,"geometry"),Z_(u,!0,_,Pu.disabled),o&&Il.drawElevatedStructures&&Il.drawElevatedStructures(u)}}else Z_(u,!1,_,e.stencilModeFor3D())},"fill-extrusion":function(e,t,i,s){const o=i.paint.get("fill-extrusion-opacity"),r=e.context,n=r.gl,a=e.terrain,l=a&&a.renderingToTexture;if(0===o)return;const c=e.isEmissiveMrtActive(),h=e.conflationActive&&e.style.isLayerClipped(i,t.getSource()),d=e.style.order.indexOf(i.fqid);if(h&&function(e,t,i,s,o){for(const r of s){const s=t.getTile(r).getBucket(i);s&&(s.updateReplacement(r,e.replacementSource,o),s.uploadCentroid(e.context))}}(e,t,i,s,d),a||h)for(const o of s){const s=t.getTile(o).getBucket(i);s&&X_(e.context,t,o,s,i,a,h)}if(e.depthPrepassPhase){if(!l){const o=new Cu(n.LEQUAL,Cu.ReadWrite,e.depthRangeFor3D);W_(e,t,i,s,o,Pu.disabled,zu.disabled,h)}}else if("shadow"===e.renderPass&&e.shadowRenderer){const r=e.shadowRenderer;if(a&&o<.65&&i.getPaintPropertyValue("fill-extrusion-opacity").expression instanceof Y)return;const n=r.getShadowPassDepthMode();W_(e,t,i,s,n,Pu.disabled,zu.disabled,h)}else if("translucent"===e.renderPass){const d=!i.paint.get("fill-extrusion-pattern").constantOr(1),u=i.paint.get("fill-extrusion-color").constantOr(S.white);if(!l&&0!==u.a){const r=new Cu(e.context.gl.LEQUAL,Cu.ReadWrite,e.depthRangeFor3D);1===o&&d?W_(e,t,i,s,r,Pu.disabled,zu.unblended,h):(e.hasGrouped3DDepthPrepass(e.currentLayer)||W_(e,t,i,s,r,Pu.disabled,zu.disabled,h),W_(e,t,i,s,r,e.stencilModeFor3DGroup(e.currentLayer),e.colorModeForRenderPass(),h),e.resetStencilClippingMasks())}const _=e.style.enable3dLights()&&d&&(!a&&"globe"!==e.transform.projection.name||l);if(_&&!ue.drawGroundEffect&&Cl(),_&&ue.drawGroundEffect){const o=i.paint.get("fill-extrusion-opacity"),d=i.paint.get("fill-extrusion-ambient-occlusion-intensity"),u=i.paint.get("fill-extrusion-ambient-occlusion-ground-radius"),_=i.paint.get("fill-extrusion-flood-light-intensity"),p="none"===i.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default"),f=i.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(p?null:i.lut).toArray01().slice(0,3),m=d>0&&u>0,g=_>0,v=new H_;v.translate=i.paint.get("fill-extrusion-translate"),v.translateAnchor=i.paint.get("fill-extrusion-translate-anchor"),v.edgeRadius=i.layout.get("fill-extrusion-edge-radius"),v.cutoffFadeRange=i.paint.get("fill-extrusion-cutoff-fade-range");const y=r=>{const a=e.depthModeForSublayer(1,Cu.ReadOnly,n.LEQUAL,!0),l=i.paint.get(r?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),c=J(.1,3,l),p=e._showOverdrawInspector;if(!p){const l=new Pu({func:n.ALWAYS,mask:255},255,255,n.KEEP,n.KEEP,n.REPLACE),p=new zu([n.ONE,n.ONE,n.ONE,n.ONE],S.transparent,[!1,!1,!1,!0],n.MIN);ue.drawGroundEffect(v,e,t,i,s,a,l,p,A_.disabled,r,"sdf",o,d,u,_,f,c,h,!1)}{const l=p?Pu.disabled:new Pu({func:n.EQUAL,mask:255},255,255,n.KEEP,n.DECR,n.DECR),m=p?e.colorModeForRenderPass():new zu([n.ONE_MINUS_DST_ALPHA,n.DST_ALPHA,n.ONE,n.ONE],S.transparent,[!0,!0,!0,!0]);ue.drawGroundEffect(v,e,t,i,s,a,l,m,A_.disabled,r,"color",o,d,u,_,f,c,h,!1)}};if(l){const l=()=>{const e=a.drapeBufferSize[0],t=a.drapeBufferSize[1];let i=a.framebufferCopyTexture;return i&&(!i||i.size[0]===e&&i.size[1]===t)||(i&&i.destroy(),i=a.framebufferCopyTexture=new k(r,new E({width:e,height:t}),n.RGBA8)),i.bind(n.LINEAR,n.CLAMP_TO_EDGE),n.copyTexSubImage2D(n.TEXTURE_2D,0,0,0,0,0,e,t),i},p=(r,a,p)=>{const m=e.depthModeForSublayer(1,Cu.ReadOnly,n.LEQUAL,!1),g=i.paint.get(r?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),y=J(.1,3,g);{const l=new zu([n.ONE,n.ONE,n.ONE,n.ONE],S.transparent,[!1,!1,!1,!0]);ue.drawGroundEffect(v,e,t,i,s,m,Pu.disabled,l,A_.disabled,r,"clear",o,d,u,_,f,y,h,a)}{const l=new Pu({func:n.ALWAYS,mask:255},255,255,n.KEEP,n.KEEP,n.REPLACE),c=new zu([n.ONE,n.ONE,n.ONE,n.ONE],S.transparent,[!1,!1,!1,!0],n.MIN);ue.drawGroundEffect(v,e,t,i,s,m,l,c,A_.disabled,r,"sdf",o,d,u,_,f,y,h,a)}c&&!r&&(p=l());{const l=r?n.ZERO:n.ONE_MINUS_DST_ALPHA,c=new Pu({func:n.EQUAL,mask:255},255,255,n.KEEP,n.DECR,n.DECR),p=new zu([l,n.DST_ALPHA,n.ONE_MINUS_DST_ALPHA,n.ZERO],S.transparent,[!0,!0,!0,!0]);ue.drawGroundEffect(v,e,t,i,s,m,c,p,A_.disabled,r,"color",o,d,u,_,f,y,h,a)}if(!c||r){const l=new zu([n.ONE,n.ONE,n.ONE,r?n.ZERO:n.ONE],S.transparent,[!1,!1,!1,!0],r?n.FUNC_ADD:n.MAX);ue.drawGroundEffect(v,e,t,i,s,m,Pu.disabled,l,A_.disabled,r,"clear",o,d,u,_,f,y,h,a,p)}else{n.drawBuffers([n.NONE,n.COLOR_ATTACHMENT1]);const l=new Pu({func:n.EQUAL,mask:255},254,255,n.KEEP,n.DECR,n.DECR),c=new zu([n.ONE,n.ONE,n.ONE,n.ONE],S.transparent,[!0,!1,!1,!1],n.MAX);ue.drawGroundEffect(v,e,t,i,s,m,l,c,A_.disabled,r,"emissive",o,d,u,_,f,y,h,a,p),n.drawBuffers([n.COLOR_ATTACHMENT0])}};if(m||g){let t;e.prepareDrawTile(),c&&!m||(t=l()),m&&p(!0,!1,t),g&&p(!1,!0,t)}}else m&&y(!0),g&&y(!1),(m||g)&&e.resetStencilClippingMasks()}}},hillshade:function(e,t,i,s){if("offscreen"!==e.renderPass&&"translucent"!==e.renderPass)return;if(e.style.disableElevatedTerrain)return;const o=e.context,r=e.terrain&&e.terrain.renderingToTexture,[n,a]="translucent"!==e.renderPass||r?[{},s]:e.stencilConfigForOverlap(s);for(const s of a){const o=t.getTile(s);if(o.needsHillshadePrepare&&"offscreen"===e.renderPass)ip(e,o,i);else if("translucent"===e.renderPass){const t=e.depthModeForSublayer(0,Cu.ReadOnly),a=i.paint.get("hillshade-emissive-strength"),l=e.colorModeForDrapableLayerRenderPass(a),c=r&&e.terrain?e.terrain.stencilModeForRTTOverlap(s):n[s.overscaledZ];ep(e,s,o,i,t,c,l)}}o.viewport.set([0,0,e.width,e.height]),e.resetStencilClippingMasks()},raster:function(e,t,i,s,o,r){if("translucent"!==e.renderPass)return;const n=i.paint.get("raster-opacity");if(0===n)return;const a="globe"===e.transform.projection.name,l=i.paint.get("raster-elevation"),c="ground"===i.paint.get("raster-elevation-reference"),h=l>0,d=e.terrain&&e.terrain.exaggeration()>0&&h&&c,u=h&&a,_=!a&&d;if(e.renderElevatedRasterBackface&&!u)return;const p=e.context,f=p.gl,m=t.getSource(),g=function(e,t,i,s,o){const r=i.paint.get("raster-color"),n="raster-array"===t.type,a=[],l=i.paint.get("raster-resampling"),c=i.paint.get("raster-color-mix");let h=i.paint.get("raster-color-range");const d=[c[0],c[1],c[2],0],u=c[3];let _="nearest"===l?o.NEAREST:o.LINEAR;if(n&&(a.push("RASTER_ARRAY"),r||a.push("RASTER_COLOR"),"linear"===l&&a.push("RASTER_ARRAY_LINEAR"),_=o.NEAREST,r&&"log"===i.paint.get("raster-color-scale")&&a.push("RASTER_COLOR_SCALE_LOG"),!h&&t.rasterLayers)){const e=t.rasterLayers.find(({id:e})=>e===i.sourceLayer);e&&e.fields&&e.fields.range&&(h=e.fields.range)}if(h=h||[0,1],r){a.push("RASTER_COLOR"),s.activeTexture.set(o.TEXTURE2),i.updateColorRamp(h);let e=i.colorRampTexture;e||(e=i.colorRampTexture=new k(s,i.colorRamp,o.RGBA8)),e.bind(_,o.CLAMP_TO_EDGE)}return e.terrain&&e.terrain.renderingToTexture&&e.isEmissiveMrtActive()&&(a.push("USE_MRT1"),"mrt-full-rgba"===e.emissiveMode&&a.push("USE_MRT1_RGBA")),{mix:d,range:h,offset:u,defines:a,resampling:_}}(e,m,i,p,f);if(m instanceof Hl&&!s.length&&!a)return;const v=i.paint.get("raster-emissive-strength"),y=e.colorModeForDrapableLayerRenderPass(v),x=e.terrain&&e.terrain.renderingToTexture,b=!e.options.moving,w="nearest"===i.paint.get("raster-resampling")?f.NEAREST:f.LINEAR;if(m instanceof Hl&&!s.length&&(m.onNorthPole||m.onSouthPole)){const s=h?e.stencilModeFor3D():Pu.disabled;return void rp(l,!!m.onNorthPole,null,e,t,i,v,g,A_.disabled,s)}if(!s.length)return;if(i.paint.get("raster-mask")&&!Pl.resolveRasterMask)return;const T=Pl.resolveRasterMask?Pl.resolveRasterMask(e,i):null;if("unavailable"===T)return;let E=!1;const[I,S]=m instanceof Hl||x?[{},s]:e.stencilConfigForOverlap(s,T?128:void 0),D=S.at(-1).overscaledZ;u&&g.defines.push("PROJECTION_GLOBE_VIEW"),h&&g.defines.push("RENDER_CUTOFF","ELEVATED"),d&&g.defines.push("ELEVATION_REFERENCE_GROUND");const R=(s,o,c)=>{for(const T of s){const s=T.toUnwrapped(),S=t.getTile(T);if(x&&(!S||!S.hasData()))continue;p.activeTexture.set(f.TEXTURE0);const R=ap(S,m,i,g);if(!R||!R.texture)continue;const{texture:C,mix:A,offset:L,tileSize:P,buffer:M}=R;let O,z;x?(O=Cu.disabled,z=T.projMatrix):h?(O=new Cu(f.LEQUAL,Cu.ReadWrite,e.depthRangeFor3D),z=a?e.transform.expandedFarZProjMatrix:e.transform.calculateProjMatrix(s,b)):(O=e.depthModeForSublayer(T.overscaledZ-D,1===n?Cu.ReadWrite:Cu.ReadOnly,f.LESS),z=e.transform.calculateProjMatrix(s,b));let F=e.terrain&&x?e.terrain.stencilModeForRTTOverlap(T):I[T.overscaledZ];E&&(F=Pl.stencilModeWithRasterMask(e,F));const k=r?0:i.paint.get("raster-fade-duration");S.registerFadeDuration(k);const B=t.findLoadedParent(T,0),N=sp(S,B,t,e.transform,k);let U,V;!N.isFading&&S.refreshedUponExpiration&&(S.refreshedUponExpiration=!1),e.terrain&&e.terrain.prepareDrawTile(),p.activeTexture.set(f.TEXTURE0),C.bind(w,f.CLAMP_TO_EDGE),p.activeTexture.set(f.TEXTURE1),B?(B.texture&&B.texture.bind(w,f.CLAMP_TO_EDGE),U=Math.pow(2,B.tileID.overscaledZ-S.tileID.overscaledZ),V=[S.tileID.canonical.x*U%1,S.tileID.canonical.y*U%1]):C.bind(w,f.CLAMP_TO_EDGE),"useMipmap"in C&&p.extTextureFilterAnisotropic&&e.transform.pitch>20&&f.texParameterf(f.TEXTURE_2D,p.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,p.extTextureFilterAnisotropicMax);const j=e.transform;let G;const q=h?np(j):[0,0,0,0];let Z,W,H,$,X,Y=0;if(u&&m instanceof Hl&&m.coordinates.length>3)Z=Float32Array.from(wt(Vo(new $e(0,0,0)))),W=Float32Array.from(j.globeMatrix),H=Float32Array.from(jo(j)),$=[Ae(j.center.lng),Pe(j.center.lat)],G=m.elevatedGlobePerspectiveTransform,X=m.elevatedGlobeGridMatrix||new Float32Array(9);else if(u){const e=Go(T.canonical);Y=qo(e.getCenter().lat),Z=Float32Array.from(wt(Vo(T.canonical))),W=Float32Array.from(j.globeMatrix),H=Float32Array.from(jo(j)),$=[Ae(j.center.lng),Pe(j.center.lat)],G=[0,0],X=Float32Array.from(Zo(T.canonical,e,Y,j.worldSize/j._pixelsPerMercatorPixel))}else G=m instanceof Hl?m.perspectiveTransform:[0,0],Z=new Float32Array(16),W=new Float32Array(9),H=new Float32Array(16),$=[0,0],X=new Float32Array(9);const J=gd(e,z,Z,W,H,X,V||[0,0],K(e.transform.zoom),$,q,U||1,N,i,G,l,2,A,L,g.range,P,M,v),Q=e.isTileAffectedByFog(T),ee=e.getOrCreateProgram("raster",{defines:g.defines,overrideFog:Q});if(e.uploadCommonUniforms(p,ee,s),m instanceof Hl){const t=E?Pl.stencilModeWithRasterMask(e,Pu.disabled):Pu.disabled,s=m.elevatedGlobeVertexBuffer,r=m.elevatedGlobeIndexBuffer;if(x||!a)m.boundsBuffer&&m.boundsSegments&&ee.draw(e,f.TRIANGLES,O,t,y,A_.disabled,J,i.id,m.boundsBuffer,e.quadTriangleIndexBuffer,m.boundsSegments);else if(s&&r){const n=j.zoom<=uo?m.elevatedGlobeSegments:m.getSegmentsForLongitude(j.center.lng);n&&ee.draw(e,f.TRIANGLES,O,t,y,o,J,i.id,s,r,n)}}else if(u){O=new Cu(f.LEQUAL,Cu.ReadOnly,e.depthRangeFor3D);const t=e.globeSharedBuffers;if(t){d&&(e.terrain.setupElevationDraw(S,ee),e.uploadCommonUniforms(p,ee,S.tileID.toUnwrapped()));const[s,r,n]=t.getGridBuffers(Y,!1),a=ee.getAttributeLocation(f,"a_texture_pos");-1!==a&&f.vertexAttribI4ui(a,0,0,0,0),ee.draw(e,f.TRIANGLES,O,c||F,e.colorModeForRenderPass(),o,J,i.id,s,r,n)}}else if(_)O=new Cu(f.LEQUAL,Cu.ReadOnly,e.depthRangeFor3D),e.terrain.setupElevationDraw(S,ee),e.uploadCommonUniforms(p,ee,S.tileID.toUnwrapped()),j.pitch>20&&ee.draw(e,f.TRIANGLES,O,Pu.disabled,zu.disabled,A_.frontCCW,J,i.id,e.terrain.gridBuffer,e.terrain.gridIndexBuffer,e.terrain.gridSegments),ee.draw(e,f.TRIANGLES,O,F,y,A_.backCCW,J,i.id,e.terrain.gridBuffer,e.terrain.gridIndexBuffer,e.terrain.gridSegments);else{const{tileBoundsBuffer:t,tileBoundsIndexBuffer:s,tileBoundsSegments:o}=e.getTileBoundsBuffers(S);ee.draw(e,f.TRIANGLES,O,F,y,A_.disabled,J,i.id,t,s,o)}}if(!(m instanceof Hl)&&u)for(const r of s){const s=r.canonical.y===(1<<r.canonical.z)-1;0===r.canonical.y&&rp(l,!0,r,e,t,i,v,g,o,c||Pu.disabled),s&&rp(l,!1,r,e,t,i,v,g,o===A_.frontCW?A_.backCW:A_.frontCW,c||Pu.disabled)}};u?R(S,e.renderElevatedRasterBackface?A_.backCW:A_.frontCW,e.stencilModeFor3D()):(T&&(Pl.renderRasterMask(e,T),E=!0),R(S,A_.disabled,void 0),E&&(Pl.clearRasterMask(e),E=!1)),e.resetStencilClippingMasks()},background:function(e,t,i,s){const o=i.paint.get("background-color"),r="none"===i.paint.get("background-color-use-theme").constantOr("default"),n=i.paint.get("background-opacity"),a=i.paint.get("background-emissive-strength"),l="viewport"===i.paint.get("background-pitch-alignment");if(0===n)return;const c=e.context,h=c.gl,d=e.transform,u=d.tileSize,_=i.paint.get("background-pattern");let p;if(void 0!==_){if(null===_)return;if(p=e.imageManager.getPattern(g.from(_.toString()),i.scope,e.style.getLut(i.scope)),!p)return}const f=!_&&1===o.a&&1===n&&e.opaquePassEnabledForLayer()?"opaque":"translucent";if(e.renderPass!==f)return;const m=Pu.disabled,v=e.depthModeForSublayer(0,"opaque"===f?Cu.ReadWrite:Cu.ReadOnly),y=e.colorModeForDrapableLayerRenderPass(a),x=_?"backgroundPattern":"background";let b,w=s;w||(b=e.getBackgroundTiles(),w=Object.values(b).map(e=>e.tileID)),_&&(c.activeTexture.set(h.TEXTURE0),e.imageManager.bind(e.context,i.scope));const T=[];if(e.terrain&&e.terrain.renderingToTexture&&e.isEmissiveMrtActive()&&(T.push("USE_MRT1"),"mrt-full-rgba"===e.emissiveMode&&T.push("USE_MRT1_RGBA")),l){const t=e.getOrCreateProgram(x,{overrideFog:!1,overrideRtt:!0,defines:T}),s=lp,c=new Ge(0,0,0,0,0),d=_?Td(s,a,n,e,0,i.scope,p,l,{tileID:c,tileSize:u}):wd(s,a,n,o.toPremultipliedRenderColor(r?null:i.lut));return void t.draw(e,h.TRIANGLES,v,m,y,A_.disabled,d,i.id,e.viewportBuffer,e.quadTriangleIndexBuffer,e.viewportSegments)}for(const f of w){const g=e.isTileAffectedByFog(f),w=e.getOrCreateProgram(x,{overrideFog:g,defines:T}),E=f.toUnwrapped(),I=s?f.projMatrix:e.transform.calculateProjMatrix(E);e.prepareDrawTile();const S=t?t.getTile(f):b?b[f.key]:new yc(f,u,d.zoom,e),D=_?Td(I,a,n,e,0,i.scope,p,l,{tileID:f,tileSize:u}):wd(I,a,n,o.toPremultipliedRenderColor(r?null:i.lut));e.uploadCommonUniforms(c,w,E);const{tileBoundsBuffer:R,tileBoundsIndexBuffer:C,tileBoundsSegments:A}=e.getTileBoundsBuffers(S);w.draw(e,h.TRIANGLES,v,m,y,A_.disabled,D,i.id,R,C,A)}},sky:function(e,t,i){const s=e._atmosphere?K(e.transform.zoom):1,o=i.paint.get("sky-opacity")*s;if(0===o)return;const r=e.context,n=i.paint.get("sky-type"),a=new Cu(r.gl.LEQUAL,Cu.ReadOnly,[0,1]),l=e.frameCounter/1e3%1;"atmosphere"===n?"offscreen"===e.renderPass?i.needsSkyboxCapture(e)&&(function(e,t){const i=e.context,s=i.gl;let o=t.skyboxFbo;if(!o){o=t.skyboxFbo=i.createFramebuffer(32,32,1,null),t.skyboxGeometry=new _p(i),t.skyboxTexture=i.gl.createTexture(),s.bindTexture(s.TEXTURE_CUBE_MAP,t.skyboxTexture),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MIN_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MAG_FILTER,s.LINEAR);for(let e=0;e<6;++e)s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,s.RGBA,32,32,0,s.RGBA,s.UNSIGNED_BYTE,null)}i.bindFramebuffer.set(o.framebuffer),i.viewport.set([0,0,32,32]);const r=t.getCenter(e,!0),n=e.getOrCreateProgram("skyboxCapture"),a=new Float64Array(16);Xo(a,.5*-Math.PI),pp(e,t,n,a,r,0),Xo(a,.5*Math.PI),pp(e,t,n,a,r,1),Yo(a,.5*-Math.PI),pp(e,t,n,a,r,2),Yo(a,.5*Math.PI),pp(e,t,n,a,r,3),ci(a),pp(e,t,n,a,r,4),Xo(a,Math.PI),pp(e,t,n,a,r,5),i.viewport.set([0,0,e.width,e.height])}(e,i),i.markSkyboxValid(e)):"sky"===e.renderPass&&function(e,t,i,s,o){const r=e.context,n=r.gl,a=e.transform,l=e.getOrCreateProgram("skybox");r.activeTexture.set(n.TEXTURE0),n.bindTexture(n.TEXTURE_CUBE_MAP,t.skyboxTexture);const c=((e,t,i,s,o)=>({u_matrix:e,u_sun_direction:t,u_cubemap:0,u_opacity:s,u_temporal_offset:o}))(a.skyboxMatrix,t.getCenter(e,!1),0,s,o);e.uploadCommonUniforms(r,l),l.draw(e,n.TRIANGLES,i,Pu.disabled,e.colorModeForRenderPass(),A_.backCW,c,"skybox",t.skyboxGeometry.vertexBuffer,t.skyboxGeometry.indexBuffer,t.skyboxGeometry.segment)}(e,i,a,o,l):"gradient"===n&&"sky"===e.renderPass&&function(e,t,i,s,o){const r=e.context,n=r.gl,a=e.transform,l=e.getOrCreateProgram("skyboxGradient");t.skyboxGeometry||(t.skyboxGeometry=new _p(r)),r.activeTexture.set(n.TEXTURE0);let c=t.colorRampTexture;c||(c=t.colorRampTexture=new k(r,t.colorRamp,n.RGBA8)),c.bind(n.LINEAR,n.CLAMP_TO_EDGE);const h=((e,t,i,s,o)=>({u_matrix:e,u_color_ramp:0,u_center_direction:t,u_radius:le(i),u_opacity:s,u_temporal_offset:o}))(a.skyboxMatrix,t.getCenter(e,!1),t.paint.get("sky-gradient-radius"),s,o);e.uploadCommonUniforms(r,l),l.draw(e,n.TRIANGLES,i,Pu.disabled,e.colorModeForRenderPass(),A_.backCW,h,"skyboxGradient",t.skyboxGeometry.vertexBuffer,t.skyboxGeometry.indexBuffer,t.skyboxGeometry.segment)}(e,i,a,o,l)},custom:function(e,t,i,s){const o=e.context,r=i.implementation;if(e.transform.projection.unsupportedLayers&&e.transform.projection.unsupportedLayers.includes("custom")&&(!e.terrain||!e.terrain.renderingToTexture&&"offscreen"!==e.renderPass||!i.isDraped(t)))return void _("Custom layers are not yet supported with this projection. Use mercator or globe to enable usage of custom layers.");const n=function(e){if(e._customRenderArgs&&e._customRenderArgsFrameCounter===e.frameCounter)return e._customRenderArgs;const t=e.transform;let i=null,s=null;if("globe"===t.projection.name){const e=Ho(t),o=_s(e);if(o>0){const t=Ti([],e,1/o);i=[t[0],t[1],t[2],-De*De/o]}const r=t.projection.globeCenterToScreenPoint(t);r&&(s=[r.x,r.y])}const o={projectionMatrix:new Float64Array(t.getCameraToClipMatrix()),viewMatrix:new Float64Array(t.getWorldToCameraMatrix()),globeClippingPlane:i,globeCenterInScreenPixels:s};return e._customRenderArgs=o,e._customRenderArgsFrameCounter=e.frameCounter,o}(e);if("offscreen"===e.renderPass){const t=r.prerender;if(t){if(e.setCustomLayerDefaults(),o.setColorMode(e.colorModeForRenderPass()),"globe"===e.transform.projection.name){const i=e.transform.pointMerc;t.call(r,o.gl,e.transform.customLayerMatrix(),e.transform.getProjection(),e.transform.globeToMercatorMatrix(),K(e.transform.zoom),[i.x,i.y],e.transform.pixelsPerMeterRatio,n)}else t.call(r,o.gl,e.transform.customLayerMatrix(),void 0,void 0,void 0,void 0,void 0,n);o.setDirty(),e.setBaseState()}}else if("translucent"===e.renderPass){if(e.terrain&&e.terrain.renderingToTexture){const t=r.renderToTile;if(t){const i=s[0].canonical,n={x:i.x+s[0].wrap*(r.wrapTileId?0:1<<i.z),y:i.y,z:i.z};o.setDepthMode(Cu.disabled),o.setStencilMode(Pu.disabled),o.setColorMode(e.colorModeForRenderPass()),e.setCustomLayerDefaults();const a=cp[e.emissiveMode],l=o.gl,c=r.supportsEmissiveMode,h=a&&c&&c.call(r,a);e.isEmissiveMrtActive()&&!h&&l.drawBuffers([l.COLOR_ATTACHMENT0]),t.call(r,o.gl,n,a),e.isEmissiveMrtActive()&&!h&&l.drawBuffers([l.COLOR_ATTACHMENT0,l.COLOR_ATTACHMENT1]),o.setDirty(),e.setBaseState()}return}e.setCustomLayerDefaults(),o.setColorMode(e.colorModeForRenderPass()),o.setStencilMode(Pu.disabled);const t="3d"===r.renderingMode?new Cu(e.context.gl.LEQUAL,Cu.ReadWrite,e.depthRangeFor3D):e.depthModeForSublayer(0,Cu.ReadOnly);if(o.setDepthMode(t),"globe"===e.transform.projection.name){const t=e.transform.pointMerc;r.render(o.gl,e.transform.customLayerMatrix(),e.transform.getProjection(),e.transform.globeToMercatorMatrix(),K(e.transform.zoom),[t.x,t.y],e.transform.pixelsPerMeterRatio,n)}else r.render(o.gl,e.transform.customLayerMatrix(),void 0,void 0,void 0,void 0,void 0,n);o.setDirty(),e.setBaseState(),o.bindFramebuffer.set(null)}}},Dp={line:function(e,t,i){if(e.hasElevatedBuckets=!1,e.hasNonElevatedBuckets=!1,void 0!==e.getLayoutPropertyValue("line-elevation-reference").value||void 0!==e.getLayoutPropertyValue("line-z-offset").value){if(t){const i=t.getVisibleCoordinates();for(const s of i){const i=t.getTile(s).getBucket(e);if(i&&("none"!==i.elevationType?e.hasElevatedBuckets=!0:e.hasNonElevatedBuckets=!0,e.hasElevatedBuckets&&e.hasNonElevatedBuckets))break}}}else e.hasNonElevatedBuckets=!0},raster:function(e,t,i){const s=t.getSource();if("raster-array"!==s.type||!s.loaded())return;const o=e.sourceLayer||s.rasterLayerIds&&s.rasterLayerIds[0];if(!o)return;const r=e.paint.get("raster-array-band")||s.getInitialBand(o);if(null==r)return;const n=t.getIds().map(e=>t.getTileByID(e));for(const t of n)t.updateNeeded(e.id,r)&&s.prepareTile(t,o,e.id,r)}};async function Rp(e){if(await Cl(),Object.assign(Sp,{model:ue.drawModels}),Object.assign(Dp,{model:ue.prepare}),e&&!e._destroyed&&!e._shadowRenderer){const t=ue.ShadowRenderer;t&&(e._shadowRenderer=new t(e))}}class Cp{constructor(e,t,i,s,o,r){this._lightsUniforms=null,this._fogUniforms=null,this._forceFullRgbaEmissive=!1,this.context=new D_(e,t),this._forceFullRgbaEmissive="exact"===r,this.transform=i,this.cache=new Map,this._tileTextures={},this.frameCopies=[],this.loadTimeStamps=[],this.frcCoverageSnapshot=null,this.elevationCoverageSnapshot=null,this.elevationProvidersReady=void 0,this.frcCoverageFadeRange=null,this.frcCoverageSourceLayers=[],this.frcCoverageRenderer=Il.FrcCoverageRenderer?new Il.FrcCoverageRenderer:null,this._debugParams={averageFPS:0,fpsHistory:[],fpsWindow:30,continousRedraw:!1,enabledLayers:{},buildingsShowNormals:!1,buildingsDrawGroundAO:!0,buildingsDrawShadowPass:!0,buildingsDrawTranslucentPass:!0,showTerrainProxyTiles:!1,terrainSortTilesHiZFirst:!0,terrainDisableRenderCache:!1,forceEnablePrecipitation:!1,overrideSnowParams:!1,snowParamsOverride:null,snowRevealParamsOverride:null,snowVignetteParamsOverride:null,overrideRainParams:!1,rainParamsOverride:null,rainRevealParamsOverride:null,rainVignetteParamsOverride:null,overrideStarsParams:!1,starsParamsOverride:null,show3DModelFootprints:!1,showElevationIdDebug:!1,lodSwitchDistance:-1,lodSwitchFadeDuration:.5},this.occlusionParams=new Ip,this.setup(),this.numSublayers=Ac.maxUnderzooming+Ac.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.deferredRenderGpuTimeQueries=[],this.gpuTimers={},this.frameCounter=0,this.frameTimeDelta=0,this.lastPaintStartTimeStamp=0,this._shadowCullCache=null,this._backgroundTiles={},this.depthPrepassPhase=!1,this._grouped3DDepthPrepassStart=-1,this._grouped3DDepthPrepassEnd=-1,this._grouped3DStencil=null,this.conflationActive=!1,this.replacementSource=new nr,this.longestCutoffRange=0,this.minCutoffZoom=0,this._fogVisible=!1,this._cachedTileFogOpacities=new Map,this._wireframeDebugCache=new Ep,this.renderDefaultNorthPole=!0,this.renderDefaultSouthPole=!0,this.layersWithOcclusionOpacity=[];const n=new E({width:1,height:1},Uint8Array.of(0,0,0,0));this.emptyDepthTexture=new k(this.context,n,e.RGBA8),this._clippingActiveLastFrame=!1,this.scaleFactor=s,this.maxFrontCutoffRawStart=0,this.worldview=o,this._forceEmissiveMode=!1,this.emissiveMode="constant"}updateTerrain(e,t){const i=!!e&&!!e.terrain&&this.transform.projection.supportsTerrain;var s;(i||this._terrain&&this._terrain.enabled)&&(this._terrain||(this._terrain=wp(this,e),this._terrain)?(this.transform.elevation=i?this._terrain:null,this._terrain.update(e,this.transform,t),this.transform.elevation&&!this._terrain.enabled&&(this.transform.elevation=null)):this._terrainRendererRetryPending||(this._terrainRendererRetryPending=!0,s=()=>{this._terrainRendererRetryPending=!1,this.style&&this.style.map&&this.style.map._update(!1)},yp?s():xp.push(s)))}_updateFog(e){const t=e.fog;if(!t||"globe"===this.transform.projection.name||t.getOpacity(this.transform.pitch)<1||t.properties.get("horizon-blend")<.03)return void(this.transform.fogCullDistSq=null);const[i,s]=t.getRangeForProjection();if(i>s)return void(this.transform.fogCullDistSq=null);const o=i+.78*(s-i);this.transform.fogCullDistSq=o*o}get terrain(){return this.transform._terrainEnabled()&&this._terrain&&this._terrain.enabled||this._forceTerrainMode?this._terrain:null}get forceTerrainMode(){return this._forceTerrainMode}set forceTerrainMode(e){e&&!this._terrain&&(this._terrain=wp(this,this.style),this._terrain||console.warn("forceTerrainMode: Lite module not loaded yet, terrain renderer unavailable")),this._forceTerrainMode=e}get shadowRenderer(){return this._shadowRenderer&&this._shadowRenderer.enabled?this._shadowRenderer:null}get wireframeDebugCache(){return this._wireframeDebugCache}resize(e,t){if(this.width=e*T.devicePixelRatio,this.height=t*T.devicePixelRatio,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const e of this.style.order)this.style._mergedLayers[e].resize()}setup(){const e=this.context,t=new gt;t.emplaceBack(0,0),t.emplaceBack(ae,0),t.emplaceBack(0,ae),t.emplaceBack(ae,ae),this.tileExtentBuffer=e.createVertexBuffer(t,yt.members),this.tileExtentSegments=Ye.simpleSegment(0,0,4,2);const i=new gt;i.emplaceBack(0,0),i.emplaceBack(ae,0),i.emplaceBack(0,ae),i.emplaceBack(ae,ae),this.debugBuffer=e.createVertexBuffer(i,yt.members),this.debugSegments=Ye.simpleSegment(0,0,4,5);const s=new gt;s.emplaceBack(-1,-1),s.emplaceBack(1,-1),s.emplaceBack(-1,1),s.emplaceBack(1,1),this.viewportBuffer=e.createVertexBuffer(s,yt.members),this.viewportSegments=Ye.simpleSegment(0,0,4,2);const o=new Xe;o.emplaceBack(0,0,0,0),o.emplaceBack(ae,0,ae,0),o.emplaceBack(0,ae,0,ae),o.emplaceBack(ae,ae,ae,ae),this.mercatorBoundsBuffer=e.createVertexBuffer(o,Gl.members),this.mercatorBoundsSegments=Ye.simpleSegment(0,0,4,2);const r=new Ke;r.emplaceBack(0,1,2),r.emplaceBack(2,1,3),this.quadTriangleIndexBuffer=e.createIndexBuffer(r);const n=new vt;for(const e of[0,1,3,2,0])n.emplaceBack(e);this.debugIndexBuffer=e.createIndexBuffer(n),this.emptyTexture=new k(e,new E({width:1,height:1},Uint8Array.of(0,0,0,0)),e.gl.RGBA8),this.identityMat=Bt();const a=this.context.gl;this.stencilClearMode=new Pu({func:a.ALWAYS,mask:0},0,255,a.ZERO,a.ZERO,a.ZERO),this.loadTimeStamps.push(performance.now())}getMercatorTileBoundsBuffers(){return{tileBoundsBuffer:this.mercatorBoundsBuffer,tileBoundsIndexBuffer:this.quadTriangleIndexBuffer,tileBoundsSegments:this.mercatorBoundsSegments}}getTileBoundsBuffers(e){return e._makeTileBoundsBuffers(this.context,this.transform.projection),e._tileBoundsBuffer?{tileBoundsBuffer:e._tileBoundsBuffer,tileBoundsIndexBuffer:e._tileBoundsIndexBuffer,tileBoundsSegments:e._tileBoundsSegments}:this.getMercatorTileBoundsBuffers()}clearStencil(){const e=this.context.gl;this.nextStencilID=1,this.currentStencilSource=void 0,this._tileClippingMaskIDs=new Map,this._grouped3DStencil=null,this.getOrCreateProgram("clippingMask").draw(this,e.TRIANGLES,Cu.disabled,this.stencilClearMode,zu.disabled,A_.disabled,hd(this.identityMat),"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments)}resetStencilClippingMasks(){this.terrain||(this.currentStencilSource=void 0,this._tileClippingMaskIDs=new Map)}_renderTileClippingMasks(e,t,i){if(!t||this.currentStencilSource===t.id||!e.isTileClipped()||!i||0===i.length)return;if(this._tileClippingMaskIDs&&!this.terrain){let e=!1;for(const t of i)if(!this._tileClippingMaskIDs.has(t.key)){e=!0;break}if(!e)return}this.currentStencilSource=t.id;const s=this.context,o=s.gl;this.nextStencilID+i.length-1>253&&this.clearStencil(),s.setColorMode(zu.disabled),s.setDepthMode(Cu.disabled);const r=this.getOrCreateProgram("clippingMask");this._tileClippingMaskIDs=new Map;for(const e of i){const i=t.getTile(e),s=this.nextStencilID++;this._tileClippingMaskIDs.set(e.key,s);const{tileBoundsBuffer:n,tileBoundsIndexBuffer:a,tileBoundsSegments:l}=this.getTileBoundsBuffers(i);r.draw(this,o.TRIANGLES,Cu.disabled,new Pu({func:o.ALWAYS,mask:0},s,255,o.KEEP,o.KEEP,o.REPLACE),zu.disabled,A_.disabled,hd(e.projMatrix),"$clipping",n,a,l)}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID>253&&this.clearStencil();const e=this.nextStencilID++,t=this.context.gl;return new Pu({func:t.NOTEQUAL,mask:255},e,255,t.KEEP,t.KEEP,t.REPLACE)}_beginGrouped3DDepthPrepass(e,t){const i=this.currentLayer;if(!e[i].hasBlended3DDepthPrepass())return;const s=[];let o=i;for(let t=i;t<e.length;t++){const i=e[t];if(!i.isHidden(this.transform.zoom)){if(!i.hasBlended3DDepthPrepass()||s.includes(i.type))break;s.push(i.type),o=t+1}}if(!(s.length<2)){for(this._grouped3DDepthPrepassStart=i,this._grouped3DDepthPrepassEnd=o,this._grouped3DStencil=null,this.depthPrepassPhase=!0,this.currentLayer=i;this.currentLayer<o;this.currentLayer++){const i=e[this.currentLayer],s=this.style.getLayerSourceCache(i);this.renderLayer(this,s,i,t(i,s))}this.depthPrepassPhase=!1,this.currentLayer=i}}hasGrouped3DDepthPrepass(e){return e>=this._grouped3DDepthPrepassStart&&e<this._grouped3DDepthPrepassEnd}stencilModeFor3DGroup(e){return this.hasGrouped3DDepthPrepass(e)?(this._grouped3DStencil||(this._grouped3DStencil=this.stencilModeFor3D()),this.currentStencilSource=void 0,this._grouped3DStencil):this.stencilModeFor3D()}stencilModeForClipping(e){if(this.terrain)return this.terrain.stencilModeForRTTOverlap(e);const t=this.context.gl,i=this._tileClippingMaskIDs.get(e.key);return new Pu({func:t.EQUAL,mask:255},i,0,t.KEEP,t.KEEP,t.REPLACE)}stencilConfigForOverlap(e,t=254){const i=this.context.gl,s=e.sort((e,t)=>t.overscaledZ-e.overscaledZ),o=s.at(-1).overscaledZ,r=s[0].overscaledZ-o+1;if(r>1){this.currentStencilSource=void 0,this.nextStencilID+r>t&&this.clearStencil();const e={};for(let t=0;t<r;t++)e[t+o]=new Pu({func:i.GEQUAL,mask:255},t+this.nextStencilID,255,i.KEEP,i.KEEP,i.REPLACE);return this.nextStencilID+=r,[e,s]}return[{[o]:Pu.disabled},s]}colorModeForRenderPass(){const e=this.context.gl;if(this._showOverdrawInspector){const t=1/8;return new zu([e.CONSTANT_COLOR,e.ONE,e.CONSTANT_COLOR,e.ONE],new S(t,t,t,0),[!0,!0,!0,!0])}return"opaque"===this.renderPass?zu.unblended:zu.alphaBlended}isEmissiveMrtActive(){return"mrt-fallback"===this.emissiveMode||"mrt-full-rgba"===this.emissiveMode}colorModeForDrapableLayerRenderPass(e){const t=this.context.gl;return(()=>this.style&&this.style.enable3dLights()&&!!this._terrain&&this._terrain.renderingToTexture)()&&"translucent"===this.renderPass?null!=e&&!this.isEmissiveMrtActive()||"constant"===this.emissiveMode?new zu([t.ONE,t.ONE_MINUS_SRC_ALPHA,t.CONSTANT_ALPHA,t.ONE_MINUS_SRC_ALPHA],new S(0,0,0,e??0),[!0,!0,!0,!0]):"dual-source-blending"===this.emissiveMode?new zu([t.ONE,t.ONE_MINUS_SRC_ALPHA,this.context.extBlendFuncExtended.SRC1_ALPHA_WEBGL,t.ONE_MINUS_SRC_ALPHA],S.transparent,[!0,!0,!0,!0]):this.colorModeForRenderPass():this.colorModeForRenderPass()}depthModeForSublayer(e,t,i,s=!1){if(this.depthOcclusion)return new Cu(this.context.gl.GREATER,Cu.ReadOnly,this.depthRangeFor3D);if(!this.opaquePassEnabledForLayer()&&!s)return Cu.disabled;const o=1-((1+this.currentLayer)*this.numSublayers+e)*this.depthEpsilon;return new Cu(i||this.context.gl.LEQUAL,t,[o,o])}opaquePassEnabledForLayer(){return this.currentLayer<this.opaquePassCutoff}blitDepth(){const e=this.context.gl,t=Math.ceil(this.width),i=Math.ceil(this.height),s=this.context.bindFramebuffer.get(),o=e.getParameter(e.TEXTURE_BINDING_2D);this.depthFBO&&this.depthFBO.width===t&&this.depthFBO.height===i||(this.depthFBO&&(this.depthFBO.destroy(),this.depthFBO=void 0,this.depthTexture=void 0),0!==t&&0!==i&&(this.depthFBO=new S_(this.context,t,i,0,"texture"),this.depthTexture=new k(this.context,{width:t,height:i,data:null},e.DEPTH24_STENCIL8),this.depthFBO.depthAttachment.set(this.depthTexture.texture))),this.context.bindFramebuffer.set(s),e.bindTexture(e.TEXTURE_2D,o),this.depthFBO&&(e.bindFramebuffer(e.READ_FRAMEBUFFER,null),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,this.depthFBO.framebuffer),e.blitFramebuffer(0,0,t,i,0,0,t,i,e.DEPTH_BUFFER_BIT,e.NEAREST),e.bindFramebuffer(e.FRAMEBUFFER,this.context.bindFramebuffer.current))}render(e,t){this.context.sweepPendingPrograms(),this.frameTimeDelta=0===this.lastPaintStartTimeStamp?0:t.paintStartTimeStamp-this.lastPaintStartTimeStamp,this.lastPaintStartTimeStamp=t.paintStartTimeStamp,this._wireframeDebugCache.update(this.frameCounter),this.style=e,this.options=t;const{directionalLight:i,ambientLight:s}=e;this._lightsUniforms=e.enable3dLights()&&i&&s?Du(i,s,e):null;const o=this.transform;this._fogUniforms=e.fog?((e,t,i,s,o,r,n,a,l,c)=>{const h=e.transform,d="none"===t.properties.get("color-use-theme"),u=t.properties.get("color").toNonPremultipliedRenderColor(d?null:e.style.getLut(t.scope)).toArray01();u[3]=i;const _=e.frameCounter/1e3%1,[p,f]=t.properties.get("vertical-range");return{u_fog_matrix:e.identityMat,u_fog_range:t.getRangeForProjection(),u_fog_color:u,u_fog_horizon_blend:t.properties.get("horizon-blend"),u_fog_vertical_limit:[Math.min(p,f),f],u_fog_temporal_offset:_,u_frustum_tl:s,u_frustum_tr:o,u_frustum_br:r,u_frustum_bl:n,u_globe_pos:a,u_globe_radius:l,u_viewport:c,u_globe_transition:K(h.zoom),u_is_globe:+("globe"===h.projection.name)}})(this,e.fog,e.fog.getOpacity(o.pitch),o.frustumCorners.TL,o.frustumCorners.TR,o.frustumCorners.BR,o.frustumCorners.BL,o.globeCenterInViewSpace,o.globeRadius,[this.width,this.height]):null,this.frcCoverageSnapshot&&!this.frcCoverageSnapshot.empty()&&(!this.frcCoverageRenderer&&Il.FrcCoverageRenderer&&(this.frcCoverageRenderer=new Il.FrcCoverageRenderer),this.frcCoverageRenderer&&this.frcCoverageRenderer.update(this.context,this.frcCoverageSnapshot.tiles));const r=this.style._mergedLayers,n=!(!this.terrain||!this.terrain.enabled),a=()=>this.style._getOrder(n);let l=a(),c=!1,h=!1,d=null,u=0,_=!1;for(const e of l){const t=r[e];"none"!==t.visibility&&("circle"===t.type?c=!0:"building"===t.type?(d=t,++u):"symbol"===t.type&&(t.hasOcclusionOpacityProperties?h=!0:c=!0))}this.updateEmissiveMode();let p=l.map(e=>r[e]);const f=this.style._mergedSourceCaches;this.imageManager=e.imageManager,this.modelManager=e.modelManager,this.now=T.now(),this.symbolFadeChange=e.placement?e.placement.symbolFadeChange(this.now):1,this.imageManager.beginFrame();for(const e in f){const t=f[e];t.used&&(t.prepare(this.context),t.getSource().usedInConflation&&++u)}let m=!1;for(const e of p)e.isHidden(this.transform.zoom)||("clip"===e.type&&(m=!0),this.prepareLayer(e));const g={},v={},y={},x={},b={};for(const e in f){const t=f[e];g[e]=t.getVisibleCoordinates(),v[e]=g[e].slice().reverse(),y[e]=t.getVisibleCoordinates(!0).reverse(),x[e]=t.getShadowCasterCoordinates(),b[e]=t.sortCoordinatesByDistance(g[e])}const w=e=>{const t=this.style.getLayerSourceCache(e);return t&&t.used?t.getSource():null};if(u||m||this._clippingActiveLastFrame){const e=[],t=[];let i=0;for(const s of p)this.isSourceForClippingOrConflation(s,w(s))&&(e.push(s),t.push(i)),i++;if(e&&(m||e.length>1)||this._clippingActiveLastFrame){m=!1;const i=[];for(let s=0;s<e.length;s++){const o=e[s],r=t[s],n=this.style.getLayerSourceCache(o);if(!n||!n.used||!n.getSource().usedInConflation&&"clip"!==o.type&&"building"!==o.type)continue;let a=lr,l=gi.None;const c=[];let h=!0;if("building"===o.type)a=cr;else if("clip"===o.type)if(a=r,o.isHidden(this.transform.zoom))h=!1;else{if(!o.layout){h=!1;continue}for(const e of o.layout.get("clip-layer-types"))l|="model"===e?gi.Model:"symbol"===e?gi.Symbol:gi.FillExtrusion;for(const e of o.layout.get("clip-layer-scope"))c.push(C(e,o.scope));m=!0}h&&i.push({layer:o.fqid,cache:n,order:a,clipMask:l,clipScope:c})}this.replacementSource.setSources(i),_=!0}}this._clippingActiveLastFrame=m,_||this.replacementSource.clear(),this.conflationActive=_,this.minCutoffZoom=0,this.longestCutoffRange=0,this.maxFrontCutoffRawStart=0,this.opaquePassCutoff=1/0,this._lastOcclusionLayer=-1,this.layersWithOcclusionOpacity=[];for(let e=0;e<p.length;e++){const t=p[e];if("none"===t.visibility)continue;const i=t.cutoffRange();if(this.longestCutoffRange=Math.max(i,this.longestCutoffRange),i>0){const e=w(t);e&&(this.minCutoffZoom=Math.max(e.minzoom,this.minCutoffZoom)),t.minzoom&&(this.minCutoffZoom=Math.max(t.minzoom,this.minCutoffZoom))}t.is3D(n)&&(this.opaquePassCutoff===1/0&&(this.opaquePassCutoff=e),this._lastOcclusionLayer=e)}const E=this.style&&this.style.fog;E?(this._fogVisible=0!==E.getOpacity(this.transform.pitch),this._fogVisible&&"globe"!==this.transform.projection.name&&(this._fogVisible=E.isVisibleOnFrustum(this.transform.cameraFrustum))):this._fogVisible=!1,this._cachedTileFogOpacities.clear(),this.terrain&&(this.terrain.updateTileBinding(y),this.opaquePassCutoff=0,l=a(),p=l.map(e=>r[e])),this.style.enable3dLights()&&!this._shadowRenderer&&Rp(this);const I=this._shadowRenderer;if(I){I.updateShadowParameters(this.transform,this.style.directionalLight,x);for(const e in f)for(const t of g[e]){let e={min:0,max:0};this.terrain&&(e=this.terrain.getMinMaxForTile(t)||e),I.addShadowReceiver(t.toUnwrapped(),e.min,e.max)}}"globe"!==this.transform.projection.name||this.globeSharedBuffers||(this.globeSharedBuffers=new ar(this.context)),this.style.fog&&this.transform.projection.supportsFog?(this._atmosphere||(this._atmosphere=new vp),this._atmosphere.update(this)):this._atmosphere&&(this._atmosphere.destroy(),this._atmosphere=void 0);let D=!(!this.style||!this.style.snow),R=!(!this.style||!this.style.rain);if(!D&&!R||Il.loaded||Dl(),D&&!this._snow&&Il.Snow&&(this._snow=new Il.Snow),!D&&this._snow&&(this._snow.destroy(),delete this._snow),R&&!this._rain&&Il.Rain&&(this._rain=new Il.Rain),!R&&this._rain&&(this._rain.destroy(),delete this._rain),this._snow&&this._snow.update(this),this._rain&&this._rain.update(this),d&&(!this.buildingTileBorderManager&&Il.BuildingTileBorderManager&&(this.buildingTileBorderManager=new Il.BuildingTileBorderManager),this.buildingTileBorderManager)){const e=this.style.getLayerSourceCache(d);this.buildingTileBorderManager.updateBorders(e,d)}if(!pn.has(this.context.gl))return;this.renderPass="offscreen";for(const t of p){const i=e.getLayerSourceCache(t);if(!t.hasOffscreenPass()||t.isHidden(this.transform.zoom))continue;const s=i?v[i.id]:void 0;("custom"===t.type||"raster"===t.type||"raster-particle"===t.type||t.isSky()||s&&s.length)&&this.renderLayer(this,i,t,s)}this.depthRangeFor3D=[0,1-(p.length+2)*this.numSublayers*this.depthEpsilon],this._shadowRenderer&&(this.renderPass="shadow",this._shadowRenderer.drawShadowPass(this.style,x)),this.context.bindFramebuffer.set(null),this.context.viewport.set([0,0,this.width,this.height]);const A="globe"===this.transform.projection.name||this.transform.isHorizonVisible(),L=(()=>{if(t.showOverdrawInspector)return S.black;const e=this.style.fog;if(e&&this.transform.projection.supportsFog){const t=this.style.getLut(e.scope);if(!A){const i="none"===e.properties.get("color-use-theme"),s=e.properties.get("color").toNonPremultipliedRenderColor(i?null:t).toArray01();return new S(...s)}if(A){const i="none"===e.properties.get("space-color-use-theme"),s=e.properties.get("space-color").toNonPremultipliedRenderColor(i?null:t).toArray01();return new S(...s)}}return S.transparent})();if(this.context.clear({color:L,depth:1}),this.clearStencil(),this._showOverdrawInspector=t.showOverdrawInspector,this.renderPass="opaque",this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&A&&this._atmosphere.drawStars(this,this.style.fog),!this.terrain)for(this.currentLayer=l.length-1;this.currentLayer>=0;this.currentLayer--){const t=p[this.currentLayer],i=e.getLayerSourceCache(t);if(t.isSky())continue;const s=i?(t.is3D(n)?b:v)[i.id]:void 0;this._renderTileClippingMasks(t,i,s),this.renderLayer(this,i,t,s)}if(this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&A&&this._atmosphere.drawAtmosphereGlow(this,this.style.fog),this.renderPass="sky",(!this._atmosphere||K(this.transform.zoom)>0)&&("globe"===this.transform.projection.name||this.transform.isHorizonVisible()))for(this.currentLayer=0;this.currentLayer<l.length;this.currentLayer++){const t=p[this.currentLayer],i=e.getLayerSourceCache(t);t.isSky()&&this.renderLayer(this,i,t,i?v[i.id]:void 0)}function P(e,t){let i;return t&&(i=("symbol"===e.type?y:e.is3D(n)?b:v)[t.id]),i}if(this.renderPass="translucent","globe"===this.transform.projection.name){for(this.renderElevatedRasterBackface=!0,this.currentLayer=0;this.currentLayer<l.length;){const t=p[this.currentLayer];if("raster"===t.type||"raster-particle"===t.type){const i=e.getLayerSourceCache(t);this.renderLayer(this,i,t,P(t,i))}++this.currentLayer}this.renderElevatedRasterBackface=!1}this.currentLayer=0,this.firstLightBeamLayer=Number.MAX_SAFE_INTEGER,this.depthPrepassPhase=!1,this._grouped3DDepthPrepassStart=-1,this._grouped3DDepthPrepassEnd=-1,this._grouped3DStencil=null;const M=I?I.getGroundShadowLayerIndex():-1;let O=!1,z=-1;for(let e=0;e<l.length;++e){const t=p[e];t.isHidden(this.transform.zoom)||t.is3D(n)&&(z=e)}h&&-1===z&&(c=!0);let F=!1;for(;this.currentLayer<l.length;){const t=p[this.currentLayer],i=e.getLayerSourceCache(t);if(t.isSky())++this.currentLayer;else if(this.terrain&&this.style.isLayerDraped(t)){if(t.isHidden(this.transform.zoom)){++this.currentLayer;continue}this.currentLayer=this.terrain.renderBatch(this.currentLayer),this._lastOcclusionLayer=Math.max(this.currentLayer,this._lastOcclusionLayer)}else{if(!F&&t.is3D(n)&&!n){const e=this.currentLayer,t=e=>{for(this.currentLayer=0;this.currentLayer<p.length;this.currentLayer++){const t=p[this.currentLayer];if("fill"===t.type&&Il.drawDepthPrepass){const i=this.style.getLayerSourceCache(t);Il.drawDepthPrepass(this,i,t,P(t,i),e)}}};t("initialize"),t("reset"),this.currentLayer=e,F=!0}if(c&&!O&&this.terrain&&!this.transform.isOrthographic&&(O=!0,this.blitDepth()),h&&-1!==z&&this.currentLayer===z+1&&!this.transform.isOrthographic&&this.blitDepth(),!n&&this._grouped3DDepthPrepassEnd<=this.currentLayer&&this._beginGrouped3DDepthPrepass(p,P),this.terrain||this._renderTileClippingMasks(t,i,i?g[i.id]:void 0),this.renderLayer(this,i,t,P(t,i)),!this.terrain&&I&&this.currentLayer===M){{this.clearStencil(),this.resetStencilClippingMasks();const e=this.currentLayer;for(this.currentLayer=0;this.currentLayer<p.length;this.currentLayer++){const e=p[this.currentLayer];if("fill"===e.type&&Il.drawGroundShadowMask){const t=this.style.getLayerSourceCache(e);Il.drawGroundShadowMask(this,t,e,P(e,t))}}this.currentLayer=e}if(I.drawGroundShadows(),this.firstLightBeamLayer<=this.currentLayer){const t=this.currentLayer;for(this.renderPass="light-beam",this.currentLayer=this.firstLightBeamLayer;this.currentLayer<=t;this.currentLayer++){const t=p[this.currentLayer];if(!t.hasLightBeamPass())continue;const i=e.getLayerSourceCache(t);this.renderLayer(this,i,t,i?v[i.id]:void 0)}this.currentLayer=t,this.renderPass="translucent"}}if(this.currentLayer>=this._lastOcclusionLayer&&this.layersWithOcclusionOpacity.length>0){const t=this.currentLayer;this.depthOcclusion=!0;for(const t of this.layersWithOcclusionOpacity){this.currentLayer=t;const i=p[this.currentLayer],s=e.getLayerSourceCache(i),o=s?v[s.id]:void 0;this.terrain||this._renderTileClippingMasks(i,s,s?g[s.id]:void 0),this.renderLayer(this,s,i,o)}this.depthOcclusion=!1,this.currentLayer=t,this.renderPass="translucent",this.layersWithOcclusionOpacity=[]}++this.currentLayer}}if(this.terrain&&this.terrain.postRender(),this._snow&&this._snow.draw(this),this._rain&&this._rain.draw(this),this.options.showTileBoundaries||this.options.showQueryGeometry||this.options.showTileAABBs){let t=null;p.forEach(i=>{const s=e.getLayerSourceCache(i);s&&!i.isHidden(this.transform.zoom)&&s.getVisibleCoordinates().length&&(!t||t.getSource().maxzoom<s.getSource().maxzoom)&&(t=s)}),t&&this.options.showTileBoundaries&&Ca.drawDebug&&Ca.drawDebug(this,t,t.getVisibleCoordinates(),S.red,!1,this.options.showParseStatus)}this.options.showPadding&&Ca.drawDebugPadding&&Ca.drawDebugPadding(this),Ca.drawPlacementDebug&&Ca.drawPlacementDebug(this),this.context.setDefault(),this.frameCounter=(this.frameCounter+1)%Number.MAX_SAFE_INTEGER,this.tileLoaded&&this.options.speedIndexTiming&&(this.loadTimeStamps.push(performance.now()),this.saveCanvasCopy()),_||(this.conflationActive=!1)}prepareLayer(e){this.gpuTimingStart(e);const{unsupportedLayers:t}=this.transform.projection,i=!t||!t.includes(e.type);if(Dp[e.type]&&(i||this.terrain&&"custom"===e.type)){const t=this.style.getLayerSourceCache(e);Dp[e.type](e,t,this)}this.gpuTimingEnd()}renderLayer(e,t,i,s){i.isHidden(this.transform.zoom)||("background"===i.type||"sky"===i.type||"custom"===i.type||"model"===i.type||"raster"===i.type||"raster-particle"===i.type||s&&s.length)&&(this.id=i.id,this.gpuTimingStart(i),(!e.transform.projection.unsupportedLayers||!e.transform.projection.unsupportedLayers.includes(i.type)||e.terrain&&"custom"===i.type)&&"clip"!==i.type&&"slot"!==i.type&&"placement-group"!==i.type&&Sp[i.type]&&Sp[i.type](e,t,i,s,this.style.placement?this.style.placement.variableOffsets:{},this.options.isInitialLoad),Sp[i.type]||(i.mayUse("HD")&&async function(){await Dl(),Object.assign(Sp,{building:Il.drawBuilding,"raster-particle":Il.drawRasterParticle}),Object.assign(Dp,{"raster-particle":Il.prepareRasterParticle})}(),i.mayUse("Standard")&&Rp(e)),this.gpuTimingEnd())}gpuTimingStart(e){if(!this.options.gpuTiming)return;const t=this.context.extTimerQuery,i=this.context.gl;let s=this.gpuTimers[e.id];s||(s=this.gpuTimers[e.id]={calls:0,cpuTime:0,query:i.createQuery()}),s.calls++,i.beginQuery(t.TIME_ELAPSED_EXT,s.query)}gpuTimingDeferredRenderStart(){if(this.options.gpuTimingDeferredRender){const e=this.context.extTimerQuery,t=this.context.gl,i=t.createQuery();this.deferredRenderGpuTimeQueries.push(i),t.beginQuery(e.TIME_ELAPSED_EXT,i)}}gpuTimingDeferredRenderEnd(){this.options.gpuTimingDeferredRender&&this.context.gl.endQuery(this.context.extTimerQuery.TIME_ELAPSED_EXT)}gpuTimingEnd(){this.options.gpuTiming&&this.context.gl.endQuery(this.context.extTimerQuery.TIME_ELAPSED_EXT)}collectGpuTimers(){const e=this.gpuTimers;return this.gpuTimers={},e}collectDeferredRenderGpuQueries(){const e=this.deferredRenderGpuTimeQueries;return this.deferredRenderGpuTimeQueries=[],e}queryGpuTimers(e){const t={};for(const i in e){const s=e[i],o=this.context.extTimerQuery,r=o.getQueryParameter(s.query,this.context.gl.QUERY_RESULT)/1e6;o.deleteQueryEXT(s.query),t[i]=r}return t}queryGpuTimeDeferredRender(e){if(!this.options.gpuTimingDeferredRender)return 0;const t=this.context.gl;let i=0;for(const s of e)i+=t.getQueryParameter(s,t.QUERY_RESULT)/1e6,t.deleteQuery(s);return i}translatePosMatrix(e,t,i,s,o){if(!i[0]&&!i[1])return e;const r=o?"map"===s?this.transform.angle:0:"viewport"===s?-this.transform.angle:0;if(r){const e=Math.sin(r),t=Math.cos(r);i=[i[0]*t-i[1]*e,i[0]*e+i[1]*t]}const n=[o?i[0]:Te(t,i[0],this.transform.zoom),o?i[1]:Te(t,i[1],this.transform.zoom),0],a=new Float32Array(16);return At(a,e,n),a}saveTileTexture(e){if(e.context!==this.context)return;const t=e.size[0],i=this._tileTextures[t];i?i.push(e):this._tileTextures[t]=[e]}getTileTexture(e){const t=this._tileTextures[e];return t&&t.length>0?t.pop():null}terrainRenderModeElevated(){return this.style&&this.style.hasTerrain()&&!!this.terrain&&!this.terrain.renderingToTexture||this.forceTerrainMode}linearFloatFilteringSupported(){return null!=this.context.extTextureFloatLinear}currentGlobalDefines(e,t,i,s,o){const r=void 0===i?!!this._terrain&&this._terrain.renderingToTexture:i,n=void 0===s?this.terrainRenderModeElevated():s,a=void 0===o?"globe"===this.transform.projection.name:o,l=[];return this.style&&this.style.enable3dLights()&&("globeRaster"===e||"terrainRaster"===e?(l.push("LIGHTING_3D_MODE"),l.push("LIGHTING_3D_ALPHA_EMISSIVENESS"),"mrt-full-rgba"===this.emissiveMode&&l.push("USE_MRT1_RGBA")):r||l.push("LIGHTING_3D_MODE")),n&&(l.push("TERRAIN"),this.linearFloatFilteringSupported()&&l.push("TERRAIN_DEM_FLOAT_FORMAT")),a&&l.push("GLOBE"),!this._fogVisible||r||void 0!==t&&!t||l.push("FOG"),r&&l.push("RENDER_TO_TEXTURE"),this._showOverdrawInspector&&l.push("OVERDRAW_INSPECTOR"),l}getOrCreateProgram(e,t){const{defines:i,config:s,overrideFog:o,overrideRtt:r,overrideTerrain:n,overrideGlobe:a,precompiled:l}=t||{},c=this.currentGlobalDefines(e,o,r,n,a),h=this.getShaderSource(e),d=Nu.cacheKey(h,e,c,i,s);let u=this.cache.get(d);if(!u){const t=Il.programUniforms,o=ue.programUniforms,r=Ed[e]||t&&t[e]||o&&o[e],n=i?c.concat(i):c;u=new Nu(this.context,e,h,s,r,n,l),this.cache.set(d,u)}return u}getShaderSource(e){const t=Il.shaders,i=ue.shaders,s=Al.shaders;return du[e]||t&&t[e]||i&&i[e]||s&&s[e]}setCustomLayerDefaults(){this.context.unbindVAO(),this.context.cullFace.setDefault(),this.context.frontFace.setDefault(),this.context.cullFaceSide.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 k(this.context,this.debugOverlayCanvas,this.context.gl.RGBA8))}destroy(){this._terrain&&this._terrain.destroy(),this._atmosphere&&(this._atmosphere.destroy(),this._atmosphere=void 0),this.globeSharedBuffers&&this.globeSharedBuffers.destroy(),this.emptyTexture.destroy(),this.debugOverlayTexture&&this.debugOverlayTexture.destroy(),this._wireframeDebugCache.destroy(),this.depthFBO&&(this.depthFBO.destroy(),this.depthFBO=void 0,this.depthTexture=void 0),this.emptyDepthTexture&&this.emptyDepthTexture.destroy(),this._destroyed=!0}prepareDrawTile(){this.terrain&&this.terrain.prepareDrawTile()}uploadCommonLightUniforms(e,t,i){const s=i&&this._lightsUniforms?Du(this.style.directionalLight,this.style.ambientLight,this.style,i):this._lightsUniforms;s&&t.setLightsUniformValues(e,s)}uploadCommonUniforms(e,t,i,s,o,r){if(this.uploadCommonLightUniforms(e,t,r),this.terrain&&this.terrain.renderingToTexture)return;const n=this._fogUniforms;n&&(n.u_fog_matrix=i?this.transform.calculateFogTileMatrix(i):s||this.identityMat,t.setFogUniformValues(e,n)),o&&t.setCutoffUniformValues(e,o.uniformValues)}setTileLoadedFlag(e){this.tileLoaded=e}saveCanvasCopy(){const e=this.canvasCopy();e&&(this.frameCopies.push(e),this.tileLoaded=!1)}canvasCopy(){const e=this.context.gl,t=e.createTexture();return e.bindTexture(e.TEXTURE_2D,t),e.copyTexImage2D(e.TEXTURE_2D,0,e.RGBA,0,0,e.drawingBufferWidth,e.drawingBufferHeight,0),t}getCanvasCopiesAndTimestamps(){return{canvasCopies:this.frameCopies,timeStamps:this.loadTimeStamps}}averageElevationNeedsEasing(){if(!this.transform._elevation)return!1;const e=this.style&&this.style.fog;return!!e&&0!==e.getOpacity(this.transform.pitch)}getBackgroundTiles(){const e=this._backgroundTiles,t=this._backgroundTiles={},i=this.transform.coveringTiles({tileSize:512});for(const s of i)t[s.key]=e[s.key]||new yc(s,512,this.transform.tileZoom,this,void 0,this.worldview);return t}clearBackgroundTiles(){this._backgroundTiles={}}isSourceForClippingOrConflation(e,t){return!(!e.is3D(!(!this.terrain||!this.terrain.enabled))||"clip"!==e.type&&"building"!==e.type&&(e.minzoom&&e.minzoom>this.transform.zoom||(this.style._clipLayerPresent||"building"!==e.sourceLayer&&"procedural_buildings"!==e.sourceLayer)&&(!t||"batched-model"!==t.type)))}isTileAffectedByFog(e){if(!this._fogVisible)return!1;if("globe"===this.transform.projection.name)return!0;let t=this._cachedTileFogOpacities.get(e.key);return t||(t=this.style.fog.getOpacityForTile(e),this._cachedTileFogOpacities.set(e.key,t)),t[0]>=ne||t[1]>=ne}setupDepthForOcclusion(e,t,i){const s=this.context,o=s.gl,r=!!i;var n;i||(i={u_dem:2,u_dem_prev:4,u_dem_tl:[0,0],u_dem_tl_prev:[0,0],u_dem_scale:0,u_dem_scale_prev:0,u_dem_size:0,u_dem_lerp:1,u_depth:3,u_depth_size_inv:[0,0],u_depth_range_unpack:[0,1],u_occluder_half_size:16,u_occlusion_depth_offset:-1e-4,u_exaggeration:0}),s.activeTexture.set(o.TEXTURE3),e&&this.depthFBO&&this.depthTexture?(this.depthTexture.bind(o.NEAREST,o.CLAMP_TO_EDGE),i.u_depth_size_inv=[1/this.depthFBO.width,1/this.depthFBO.height],i.u_depth_range_unpack=[2/((n=this.depthRangeFor3D)[1]-n[0]),-1-2*n[0]/(n[1]-n[0])],i.u_occluder_half_size=.5*this.occlusionParams.occluderSize,i.u_occlusion_depth_offset=this.occlusionParams.depthOffset):this.emptyDepthTexture.bind(o.NEAREST,o.CLAMP_TO_EDGE),s.activeTexture.set(o.TEXTURE0),r||t.setTerrainUniformValues(s,i)}updateEmissiveMode(){if(this._forceEmissiveMode)return;const e=this.style.hasDataDrivenEmissiveStrength();this.emissiveMode=this._forceFullRgbaEmissive?"mrt-full-rgba":e?this.context.extBlendFuncExtended?"dual-source-blending":"mrt-fallback":"constant"}}function Ap(e,t){let i=!1,s=null;const o=()=>{s=null,i&&(e(),s=setTimeout(o,t),i=!1)};return()=>(i=!0,s||o(),s)}const Lp=/(#.+)?$/;class Pp{constructor(e){this._hashName=e&&encodeURIComponent(e),rt(["_getCurrentHash","_onHashChange","_updateHash"],this),this._updateHash=Ap(this._updateHashUnthrottled.bind(this),300)}addTo(e){return this._map=e,window.addEventListener("hashchange",this._onHashChange,!1),e.on("moveend",this._updateHash),this}remove(){return this._map?(this._map.off("moveend",this._updateHash),window.removeEventListener("hashchange",this._onHashChange,!1),clearTimeout(this._updateHash()),this._map=void 0,this):this}getHashString(){const e=this._map;if(!e)return"";const t=Mp(e);if(this._hashName){const e=this._hashName;let i=!1;const s=location.hash.slice(1).split("&").map(s=>{const o=s.split("=")[0];return o===e?(i=!0,`${o}=${t}`):s}).filter(e=>e);return i||s.push(`${e}=${t}`),`#${s.join("&")}`}return`#${t}`}_getCurrentHash(){const e=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("/")}_onHashChange(){const e=this._map;if(!e)return!1;const t=this._getCurrentHash();if(t.length>=3&&!t.some(e=>isNaN(Number(e)))){const i=e.dragRotate.isEnabled()&&e.touchZoomRotate.isEnabled()?+(t[3]||0):e.getBearing();return e.jumpTo({center:[+t[2],+t[1]],zoom:+t[0],bearing:i,pitch:+(t[4]||0)}),!0}return!1}_updateHashUnthrottled(){history.replaceState(history.state,"",location.href.replace(Lp,this.getHashString()))}}function Mp(e,t){const i=e.getCenter(),s=Math.round(100*e.getZoom())/100,o=Math.ceil((s*Math.LN2+Math.log(512/360/.5))/Math.LN10),r=Math.pow(10,o),n=Math.round(i.lng*r)/r,a=Math.round(i.lat*r)/r,l=e.getBearing(),c=e.getPitch();let h=t?`/${n}/${a}/${s}`:`${s}/${a}/${n}`;return(l||c)&&(h+="/"+Math.round(10*l)/10),c&&(h+=`/${Math.round(c)}`),h}const Op={linearity:.3,easing:hr(0,0,.3,1)},zp={deceleration:2500,maxSpeed:1400,...Op},Fp={deceleration:20,maxSpeed:1400,...Op},kp={deceleration:1e3,maxSpeed:360,...Op},Bp={deceleration:1e3,maxSpeed:90,...Op};class Np{constructor(e){this._map=e,this.clear()}clear(){this._inertiaBuffer=[]}record(e){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:T.now(),settings:e})}_drainInertiaBuffer(){const e=this._inertiaBuffer,t=T.now();for(;e.length>0&&t-e[0].time>160;)e.shift()}_onMoveEnd(e){if(this._map._prefersReducedMotion())return;if(this._drainInertiaBuffer(),this._inertiaBuffer.length<2)return;const t={zoom:0,bearing:0,pitch:0,pan:new m(0,0),pinchAround:void 0,around:void 0};for(const{settings:e}of this._inertiaBuffer)t.zoom+=e.zoomDelta||0,t.bearing+=e.bearingDelta||0,t.pitch+=e.pitchDelta||0,e.panDelta&&t.pan._add(e.panDelta),e.around&&(t.around=e.around),e.pinchAround&&(t.pinchAround=e.pinchAround);const i=this._inertiaBuffer.at(-1).time-this._inertiaBuffer[0].time,s={};if(t.pan.mag()){const o=Vp(t.pan.mag(),i,{...zp,...e||{}});s.offset=t.pan.mult(o.amount/t.pan.mag()),s.center=this._map.transform.center,Up(s,o)}if(t.zoom){const e=Vp(t.zoom,i,Fp);s.zoom=this._map.transform.zoom+e.amount,Up(s,e)}if(t.bearing){const e=Vp(t.bearing,i,kp);s.bearing=this._map.transform.bearing+Ee(e.amount,-179,179),Up(s,e)}if(t.pitch){const e=Vp(t.pitch,i,Bp);s.pitch=this._map.transform.pitch+e.amount,Up(s,e)}if(s.zoom||s.bearing){const e=void 0===t.pinchAround?t.around:t.pinchAround;s.around=e?this._map.unproject(e):this._map.getCenter()}return this.clear(),s.noMoveStart=!0,s}}function Up(e,t){(!e.duration||e.duration<t.duration)&&(e.duration=t.duration,e.easing=t.easing)}function Vp(e,t,i){const{maxSpeed:s,linearity:o,deceleration:r}=i,n=Ee(e*o/(t/1e3),-s,s),a=Math.abs(n)/(r*o);return{easing:i.easing,duration:1e3*a,amount:n*(a/2)}}class jp extends M{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(e,t,i,s={}){const o=Pn(t.getCanvasContainer(),i);super(e,{point:o,lngLat:t.unproject(o),originalEvent:i,...s}),this._defaultPrevented=!1,this.target=t}}class Gp extends M{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(e,t,i){const s="touchend"===e?i.changedTouches:i.touches,o=Mn(t.getCanvasContainer(),s),r=o.map(e=>t.unproject(e)),n=o.reduce((e,t,i,s)=>e.add(t.div(s.length)),new m(0,0));super(e,{points:o,point:n,lngLats:r,lngLat:t.unproject(n),originalEvent:i}),this._defaultPrevented=!1}}class qp extends M{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(e,t){super("wheel",{originalEvent:t}),this._defaultPrevented=!1}}class Zp{constructor(e,t){this._map=e,this._clickTolerance=t.clickTolerance}reset(){this._mousedownPos=void 0}wheel(e){return this._firePreventable(new qp(this._map,e))}mousedown(e,t){return this._mousedownPos=t,this._firePreventable(new jp(e.type,this._map,e))}mouseup(e){this._map.fire(new jp(e.type,this._map,e))}preclick(e){const t=new MouseEvent("preclick",e);this._map.fire(new jp(t.type,this._map,t))}click(e,t){this._mousedownPos&&this._mousedownPos.dist(t)>=this._clickTolerance||(this.preclick(e),this._map.fire(new jp(e.type,this._map,e)))}dblclick(e){return this._firePreventable(new jp(e.type,this._map,e))}mouseover(e){this._map.fire(new jp(e.type,this._map,e))}mouseout(e){this._map.fire(new jp(e.type,this._map,e))}touchstart(e){return this._firePreventable(new Gp(e.type,this._map,e))}touchmove(e){this._map.fire(new Gp(e.type,this._map,e))}touchend(e){this._map.fire(new Gp(e.type,this._map,e))}touchcancel(e){this._map.fire(new Gp(e.type,this._map,e))}_firePreventable(e){if(this._map.fire(e),e.defaultPrevented)return{}}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class Wp{constructor(e){this._map=e}reset(){this._delayContextMenu=!1,this._contextMenuEvent=void 0}mousemove(e){this._map.fire(new jp(e.type,this._map,e))}mousedown(){this._delayContextMenu=!0}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new jp("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent)}contextmenu(e){this._delayContextMenu?this._contextMenuEvent=e:this._map.fire(new jp(e.type,this._map,e)),this._map.listens("contextmenu")&&e.preventDefault()}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class Hp{constructor(e,t){this._map=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&&(Rn(),this._startPos=this._lastPos=t,this._active=!0)}mousemoveWindow(e,t){if(!this._active)return;const i=t,s=this._startPos,o=this._lastPos;if(!s||!o||o.equals(i)||!this._box&&i.dist(s)<this._clickTolerance)return;this._lastPos=i,this._box||(this._box=Tn("div","mapboxgl-boxzoom",this._container),this._container.classList.add("mapboxgl-crosshair"),this._fireEvent("boxzoomstart",e));const r=Math.min(s.x,i.x),n=Math.max(s.x,i.x),a=Math.min(s.y,i.y),l=Math.max(s.y,i.y);this._map._requestDomTask(()=>{this._box&&(this._box.style.transform=`translate(${r}px,${a}px)`,this._box.style.width=n-r+"px",this._box.style.height=l-a+"px")})}mouseupWindow(e,t){if(!this._active)return;const i=this._startPos,s=t;if(i&&0===e.button){if(this.reset(),Ln(),i.x!==s.x||i.y!==s.y)return this._map.fire(new M("boxzoomend",{originalEvent:e})),{cameraAnimation:e=>e.fitScreenCoordinates(i,s,this._map.getBearing(),{linear:!1})};this._fireEvent("boxzoomcancel",e)}}keydown(e){this._active&&27===e.keyCode&&(this.reset(),this._fireEvent("boxzoomcancel",e))}blur(){this.reset()}reset(){this._active=!1,this._container.classList.remove("mapboxgl-crosshair"),this._box&&(this._box.remove(),this._box=null),Cn(),delete this._startPos,delete this._lastPos}_fireEvent(e,t){return this._map.fire(new M(e,{originalEvent:t}))}}function $p(e,t){const i={};for(let s=0;s<e.length;s++)i[e[s].identifier]=t[s];return i}class Xp{constructor(e){this.reset(),this.numTouches=e.numTouches}reset(){this.centroid=void 0,this.startTime=0,this.touches={},this.aborted=!1}touchstart(e,t,i){(this.centroid||i.length>this.numTouches)&&(this.aborted=!0),this.aborted||(0===this.startTime&&(this.startTime=e.timeStamp),i.length===this.numTouches&&(this.centroid=function(e){const t=new m(0,0);for(const i of e)t._add(i);return t.div(e.length)}(t),this.touches=$p(i,t)))}touchmove(e,t,i){if(this.aborted||!this.centroid)return;const s=$p(i,t);for(const e in this.touches){const t=s[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 Yp{constructor(e){this.singleTap=new Xp(e),this.numTaps=e.numTaps,this.reset()}reset(){this.lastTime=1/0,this.lastTap=void 0,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 s=this.singleTap.touchend(e,t,i);if(s){const t=e.timeStamp-this.lastTime<500,i=!this.lastTap||this.lastTap.dist(s)<30;if(t&&i||this.reset(),this.count++,this.lastTime=e.timeStamp,this.lastTap=s,this.count===this.numTaps)return this.reset(),s}}}class Kp{constructor(){this._zoomIn=new Yp({numTouches:1,numTaps:2}),this._zoomOut=new Yp({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 s=this._zoomIn.touchend(e,t,i),o=this._zoomOut.touchend(e,t,i);return s?(this._active=!0,e.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:t=>t.easeTo({duration:300,zoom:t.getZoom()+1,around:t.unproject(s)},{originalEvent:e})}):o?(this._active=!0,e.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:t=>t.easeTo({duration:300,zoom:t.getZoom()-1,around:t.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}}const Jp=0,Qp=2,ef={[Jp]:1,[Qp]:2},tf={Control:"ctrlKey",Alt:"altKey",Shift:"shiftKey",Meta:"metaKey"};class sf{constructor(e){this.reset(),this._clickTolerance=e.clickTolerance||1}blur(){this.reset()}reset(){this._active=!1,this._moved=!1,this._lastPoint=void 0,this._eventButton=void 0}_correctButton(e,t){return!1}_move(e,t){return{}}mousedown(e,t){if(this._lastPoint)return;const i=On(e);this._correctButton(e,i)&&(this._lastPoint=t,this._eventButton=i)}mousemoveWindow(e,t){const i=this._lastPoint;if(i)if(e.preventDefault(),null!=this._eventButton&&function(e,t){const i=ef[t];return void 0===e.buttons||(e.buttons&i)!==i}(e,this._eventButton))this.reset();else if(this._moved||!(t.dist(i)<this._clickTolerance))return this._moved=!0,this._lastPoint=t,this._move(i,t)}mouseupWindow(e){this._lastPoint&&On(e)===this._eventButton&&(this._moved&&Ln(),this.reset())}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class of extends sf{mousedown(e,t){super.mousedown(e,t),this._lastPoint&&(this._active=!0)}_correctButton(e,t){return 0===t&&!e.ctrlKey}_move(e,t){return{around:t,panDelta:t.sub(e)}}}class rf extends sf{constructor(e){super(e),this._pitchRotateKey=e.pitchRotateKey?tf[e.pitchRotateKey]:void 0}_correctButton(e,t){return this._pitchRotateKey?0===t&&e[this._pitchRotateKey]:0===t&&e.ctrlKey||2===t}_move(e,t){const i=.8*(t.x-e.x);if(i)return this._active=!0,{bearingDelta:i}}contextmenu(e){this._pitchRotateKey||e.preventDefault()}}class nf extends sf{constructor(e){super(e),this._pitchRotateKey=e.pitchRotateKey?tf[e.pitchRotateKey]:void 0}_correctButton(e,t){return this._pitchRotateKey?0===t&&e[this._pitchRotateKey]:0===t&&e.ctrlKey||2===t}_move(e,t){const i=-.5*(t.y-e.y);if(i)return this._active=!0,{pitchDelta:i}}contextmenu(e){this._pitchRotateKey||e.preventDefault()}}class af{constructor(e,t){this._map=e,this._el=e.getCanvasContainer(),this._minTouches=1,this._clickTolerance=t.clickTolerance||1,this.reset(),rt(["_addTouchPanBlocker","_showTouchPanBlockerAlert"],this)}reset(){this._active=!1,this._touches={},this._sum=new m(0,0)}touchstart(e,t,i){return this._calculateTransform(e,t,i)}touchmove(e,t,i){if(this._active&&!(i.length<this._minTouches)){if(this._map._cooperativeGestures&&!this._map.isMoving()){if(1===i.length&&!dr())return void this._showTouchPanBlockerAlert();"hidden"!==this._alertContainer.style.visibility&&(this._alertContainer.style.visibility="hidden",clearTimeout(this._alertTimer))}return e.cancelable&&e.preventDefault(),this._calculateTransform(e,t,i)}}touchend(e,t,i){this._calculateTransform(e,t,i),this._active&&i.length<this._minTouches&&this.reset()}touchcancel(){this.reset()}_calculateTransform(e,t,i){i.length>0&&(this._active=!0);const s=$p(i,t),o=new m(0,0),r=new m(0,0);let n=0;for(const e in s){const t=s[e],i=this._touches[e];i&&(o._add(t),r._add(t.sub(i)),n++,s[e]=t)}if(this._touches=s,n<this._minTouches||!r.mag())return;const a=r.div(n);return this._sum._add(a),this._sum.mag()<this._clickTolerance?void 0:{around:o.div(n),panDelta:a}}enable(){this._enabled=!0,this._map._cooperativeGestures&&(this._addTouchPanBlocker(),this._el.classList.add("mapboxgl-touch-pan-blocker-override","mapboxgl-scrollable-page"))}disable(){this._enabled=!1,this._map._cooperativeGestures&&(clearTimeout(this._alertTimer),this._alertContainer.remove(),this._el.classList.remove("mapboxgl-touch-pan-blocker-override","mapboxgl-scrollable-page")),this.reset()}isEnabled(){return!!this._enabled}isActive(){return!!this._active}_addTouchPanBlocker(){this._map&&!this._alertContainer&&(this._alertContainer=Tn("div","mapboxgl-touch-pan-blocker",this._map._container),this._alertContainer.textContent=this._map._getUIString("TouchPanBlocker.Message"),this._alertContainer.style.fontSize=`${Math.max(10,Math.min(24,Math.floor(.05*this._el.clientWidth)))}px`)}_showTouchPanBlockerAlert(){this._alertContainer.style.visibility="visible",this._alertContainer.classList.add("mapboxgl-touch-pan-blocker-show"),this._alertContainer.setAttribute("role","alert"),clearTimeout(this._alertTimer),this._alertTimer=window.setTimeout(()=>{this._alertContainer.classList.remove("mapboxgl-touch-pan-blocker-show"),this._alertContainer.removeAttribute("role")},500)}}class lf{constructor(){this.reset()}reset(){this._active=!1,this._firstTwoTouches=void 0}_start(e){}_move(e,t,i){return{}}touchstart(e,t,i){this._firstTwoTouches||i.length<2||(this._firstTwoTouches=[i[0].identifier,i[1].identifier],this._start([t[0],t[1]]))}touchmove(e,t,i){const s=this._firstTwoTouches;if(!s)return;e.preventDefault();const[o,r]=s,n=cf(i,t,o),a=cf(i,t,r);if(!n||!a)return;const l=this._aroundCenter?null:n.add(a).div(2);return this._move([n,a],l,e)}touchend(e,t,i){if(!this._firstTwoTouches)return;const[s,o]=this._firstTwoTouches,r=cf(i,t,s),n=cf(i,t,o);r&&n||(this._active&&Ln(),this.reset())}touchcancel(){this.reset()}enable(e){this._enabled=!0,this._aroundCenter=!!e&&"center"===e.around}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}function cf(e,t,i){for(let s=0;s<e.length;s++)if(e[s].identifier===i)return t[s]}function hf(e,t){return Math.log2(e/t)}class df extends lf{reset(){super.reset(),this._distance=0,this._startDistance=0}_start(e){this._startDistance=this._distance=e[0].dist(e[1])}_move(e,t){const i=this._distance;if(this._distance=e[0].dist(e[1]),this._active||!(Math.abs(hf(this._distance,this._startDistance))<.1))return this._active=!0,{zoomDelta:hf(this._distance,i),pinchAround:t}}}function uf(e,t){return 180*e.angleWith(t)/Math.PI}class _f extends lf{reset(){super.reset(),this._minDiameter=0,this._startVector=void 0,this._vector=void 0}_start(e){this._startVector=this._vector=e[0].sub(e[1]),this._minDiameter=e[0].dist(e[1])}_move(e,t){const i=this._vector;if(this._vector=e[0].sub(e[1]),i&&(this._active||!this._isBelowThreshold(this._vector)))return this._active=!0,{bearingDelta:uf(this._vector,i),pinchAround:t}}_isBelowThreshold(e){this._minDiameter=Math.min(this._minDiameter,e.mag());const t=25/(Math.PI*this._minDiameter)*360,i=this._startVector;if(!i)return!1;const s=uf(e,i);return Math.abs(s)<t}}function pf(e){return Math.abs(e.y)>Math.abs(e.x)}class ff extends lf{constructor(e){super(),this._map=e}reset(){super.reset(),this._valid=void 0,this._firstMove=void 0,this._lastPoints=void 0}_start(e){this._lastPoints=e,pf(e[0].sub(e[1]))&&(this._valid=!1)}_move(e,t,i){const s=this._lastPoints;if(!s)return;const o=e[0].sub(s[0]),r=e[1].sub(s[1]);return this._map._cooperativeGestures&&!dr()&&i.touches.length<3||(this._valid=this.gestureBeginsVertically(o,r,i.timeStamp),!this._valid)?void 0:(this._lastPoints=e,this._active=!0,{pitchDelta:(o.y+r.y)/2*-.5})}gestureBeginsVertically(e,t,i){if(void 0!==this._valid)return this._valid;const s=e.mag()>=2,o=t.mag()>=2;if(!s&&!o)return;if(!s||!o)return this._firstMove??=i,i-this._firstMove<100&&void 0;const r=e.y>0==t.y>0;return pf(e)&&pf(t)&&r}}const mf={panStep:100,bearingStep:15,pitchStep:10};class gf{constructor(){const e=mf;this._panStep=e.panStep,this._bearingStep=e.bearingStep,this._pitchStep=e.pitchStep,this._bearingDisabled=!1,this._pitchDisabled=!1,this._panDisabled=!1,this._zoomDisabled=!1}blur(){this.reset()}reset(){this._active=!1}keydown(e){if(e.altKey||e.ctrlKey||e.metaKey)return;if(!this.isEnabled())return;let t=0,i=0,s=0,o=0,r=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?s=1:(e.preventDefault(),r=-1);break;case 40:e.shiftKey?s=-1:(e.preventDefault(),r=1);break;default:return}return this._bearingDisabled&&(i=0),this._pitchDisabled&&(s=0),this._panDisabled&&(o=0,r=0),this._zoomDisabled&&(t=0),{cameraAnimation:n=>{const a=n.getZoom();n.easeTo({duration:300,easeId:"keyboardHandler",easing:vf,zoom:t?Math.round(a)+t*(e.shiftKey?2:1):a,bearing:n.getBearing()+i*this._bearingStep,pitch:n.getPitch()+s*this._pitchStep,offset:[-o*this._panStep,-r*this._panStep],center:n.getCenter()},{originalEvent:e})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled&&!(this._bearingDisabled&&this._pitchDisabled&&this._panDisabled&&this._zoomDisabled)}isActive(){return this._active}disableRotation(){this._pitchDisabled=!0,this._bearingDisabled=!0}enableRotation(){this._pitchDisabled=!1,this._bearingDisabled=!1}isRotationEnabled(){return!this._pitchDisabled&&!this._bearingDisabled}disablePan(){this._panDisabled=!0}enablePan(){this._panDisabled=!1}isPanEnabled(){return!this._panDisabled}disableZoom(){this._zoomDisabled=!0}enableZoom(){this._zoomDisabled=!1}isZoomEnabled(){return!this._zoomDisabled}disablePitch(){this._pitchDisabled=!0}enablePitch(){this._pitchDisabled=!1}isPitchEnabled(){return!this._pitchDisabled}disableBearing(){this._bearingDisabled=!0}enableBearing(){this._bearingDisabled=!1}isBearingEnabled(){return!this._bearingDisabled}}function vf(e){return e*(2-e)}const yf=4.000244140625,xf=1/450,bf=/(Mac|iPad)/i;class wf{constructor(e,t){this._map=e,this._el=e.getCanvasContainer(),this._handler=t,this._delta=0,this._lastDelta=0,this._defaultZoomRate=.01,this._wheelZoomRate=xf,rt(["_onTimeout","_addScrollZoomBlocker","_showBlockerAlert"],this)}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,this._map._cooperativeGestures&&this._addScrollZoomBlocker())}disable(){this.isEnabled()&&(this._enabled=!1,this._map._cooperativeGestures&&(clearTimeout(this._alertTimer),this._alertContainer.remove()))}wheel(e){if(!this.isEnabled())return;if(this._map._cooperativeGestures){if(!(e.ctrlKey||e.metaKey||this.isZooming()||dr()))return void this._showBlockerAlert();"hidden"!==this._alertContainer.style.visibility&&(this._alertContainer.style.visibility="hidden",clearTimeout(this._alertTimer))}let t=e.deltaMode===WheelEvent.DOM_DELTA_LINE?40*e.deltaY:e.deltaY;const i=T.now(),s=i-(this._lastWheelEventTime||0);this._lastWheelEventTime=i,0!==t&&t%yf===0?this._type="wheel":0!==t&&Math.abs(t)<4?this._type="trackpad":s>400?(this._type=null,this._lastValue=t,this._timeout=window.setTimeout(this._onTimeout,40,e)):this._type||(this._type=Math.abs(s*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()}_onTimeout(e){this._type="wheel",this._delta-=this._lastValue,this._active||this._start(e)}_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 t=Pn(this._el,e);this._aroundPoint=this._aroundCenter?this._map.transform.centerPoint:t,this._aroundCoord=this._map.transform.pointCoordinate3D(this._aroundPoint),this._targetZoom=void 0,this._frameId||(this._frameId=!0,this._handler._triggerRenderFrame())}renderFrame(){if(!this._frameId)return;if(this._frameId=null,!this.isActive())return;const e=this._map.transform;"wheel"===this._type&&e.projection.wrap&&(e._center.lng>=180||e._center.lng<=-180)&&(this._prevEase=null,this._easing=null,this._lastWheelEvent=null,this._lastWheelEventTime=0);const t=()=>e._terrainEnabled()&&this._aroundCoord?e.computeZoomRelativeTo(this._aroundCoord):e.zoom;if(0!==this._delta){const i="wheel"===this._type&&Math.abs(this._delta)>yf?this._wheelZoomRate:this._defaultZoomRate;let s=2/(1+Math.exp(-Math.abs(this._delta*i)));this._delta<0&&0!==s&&(s=1/s);const o=t(),r=Math.pow(2,o),n="number"==typeof this._targetZoom?e.zoomScale(this._targetZoom):r;this._targetZoom=Math.min(e.maxZoom,Math.max(e.minZoom,e.scaleZoom(n*s))),"wheel"===this._type&&(this._startZoom=o,this._easing=this._smoothOutEasing(200)),this._lastDelta=this._delta,this._delta=0}const i="number"==typeof this._targetZoom?this._targetZoom:t(),s=this._startZoom,o=this._easing;let r,n=!1;if("wheel"===this._type&&s&&o){const e=Math.min((T.now()-this._lastWheelEventTime)/200,1),t=o(e);r=J(s,i,t),e<1?this._frameId||(this._frameId=!0):n=!0}else r=i,n=!0;this._active=!0,n&&(this._active=!1,this._finishTimeout=window.setTimeout(()=>{this._zooming=!1,this._handler._triggerRenderFrame(),delete this._targetZoom,delete this._finishTimeout},200));let a=r-t();return a*this._lastDelta<0&&(a=0),{noInertia:!0,needsRenderFrame:!n,zoomDelta:a,around:this._aroundPoint,aroundCoord:this._aroundCoord,originalEvent:this._lastWheelEvent}}_smoothOutEasing(e){let t=ur;if(this._prevEase){const e=this._prevEase,i=(T.now()-e.start)/e.duration,s=e.easing(i+.01)-e.easing(i),o=.27/Math.sqrt(s*s+1e-4)*.01,r=Math.sqrt(.0729-o*o);t=hr(o,r,.25,1)}return this._prevEase={start:T.now(),duration:e,easing:t},t}blur(){this.reset()}reset(){this._active=!1}_addScrollZoomBlocker(){this._map&&!this._alertContainer&&(this._alertContainer=Tn("div","mapboxgl-scroll-zoom-blocker",this._map._container),this._alertContainer.textContent=bf.test(navigator.userAgent)?this._map._getUIString("ScrollZoomBlocker.CmdMessage"):this._map._getUIString("ScrollZoomBlocker.CtrlMessage"),this._alertContainer.style.fontSize=`${Math.max(10,Math.min(24,Math.floor(.05*this._el.clientWidth)))}px`)}_showBlockerAlert(){this._alertContainer.style.visibility="visible",this._alertContainer.classList.add("mapboxgl-scroll-zoom-blocker-show"),this._alertContainer.setAttribute("role","alert"),clearTimeout(this._alertTimer),this._alertTimer=window.setTimeout(()=>{this._alertContainer.classList.remove("mapboxgl-scroll-zoom-blocker-show"),this._alertContainer.removeAttribute("role")},200)}}class Tf{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 Ef{constructor(){this.reset()}reset(){this._active=!1}blur(){this.reset()}dblclick(e,t){return e.preventDefault(),{cameraAnimation:i=>{i.easeTo({duration:300,zoom:i.getZoom()+(e.shiftKey?-1:1),around:i.unproject(t)},{originalEvent:e})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class If{constructor(){this._tap=new Yp({numTouches:1,numTaps:1}),this.reset()}reset(){this._active=!1,this._swipePoint=void 0,this._swipeTouch=0,this._tapTime=0,this._tap.reset()}touchstart(e,t,i){this._swipePoint||(this._tapTime&&e.timeStamp-this._tapTime>500&&this.reset(),this._tapTime?i.length>0&&(this._swipePoint=t[0],this._swipeTouch=i[0].identifier):this._tap.touchstart(e,t,i))}touchmove(e,t,i){if(this._tapTime){if(this._swipePoint){if(i[0].identifier!==this._swipeTouch)return;const s=t[0],o=s.y-this._swipePoint.y;return this._swipePoint=s,e.preventDefault(),this._active=!0,{zoomDelta:o/128}}}else this._tap.touchmove(e,t,i)}touchend(e,t,i){this._tapTime?this._swipePoint&&0===i.length&&this.reset():this._tap.touchend(e,t,i)&&(this._tapTime=e.timeStamp)}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class Sf{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("mapboxgl-touch-drag-pan")}disable(){this._mousePan.disable(),this._touchPan.disable(),this._el.classList.remove("mapboxgl-touch-drag-pan")}isEnabled(){return this._mousePan.isEnabled()&&this._touchPan.isEnabled()}isActive(){return this._mousePan.isActive()||this._touchPan.isActive()}}class Df{constructor(e,t,i){this._pitchWithRotate=e.pitchWithRotate,this._mouseRotate=t,this._mousePitch=i,this._pitchDisabled=!1,this._rotationDisabled=!1}enable(){this._rotationDisabled||this._mouseRotate.enable(),this._pitchWithRotate&&!this._pitchDisabled&&this._mousePitch.enable()}disable(){this._mouseRotate.disable(),this._mousePitch.disable()}isEnabled(){return this._pitchWithRotate?!this._rotationDisabled&&this._mouseRotate.isEnabled()||!this._pitchDisabled&&this._mousePitch.isEnabled():!this._rotationDisabled&&this._mouseRotate.isEnabled()}isActive(){return this._mouseRotate.isActive()||this._mousePitch.isActive()}disablePitch(){this._pitchDisabled=!0,this._mousePitch.disable()}enablePitch(){this._pitchDisabled=!1,this._pitchWithRotate&&this._mousePitch.enable()}isPitchEnabled(){return!this._pitchDisabled&&this._mousePitch.isEnabled()}disableRotation(){this._rotationDisabled=!0,this._mouseRotate.disable()}enableRotation(){this._rotationDisabled=!1,this._mouseRotate.enable()}isRotationEnabled(){return!this._rotationDisabled&&this._mouseRotate.isEnabled()}}class Rf{constructor(e,t,i,s){this._el=e,this._touchZoom=t,this._touchRotate=i,this._tapDragZoom=s,this._rotationDisabled=!1,this._tapDragZoomDisabled=!1,this._enabled=!0}enable(e){this._touchZoom.enable(e),this._rotationDisabled||this._touchRotate.enable(e),this._tapDragZoomDisabled||this._tapDragZoom.enable(),this._el.classList.add("mapboxgl-touch-zoom-rotate")}disable(){this._touchZoom.disable(),this._touchRotate.disable(),this._tapDragZoom.disable(),this._el.classList.remove("mapboxgl-touch-zoom-rotate")}isEnabled(){return this._touchZoom.isEnabled()||!this._rotationDisabled&&this._touchRotate.isEnabled()||!this._tapDragZoomDisabled&&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()}isRotationEnabled(){return!this._rotationDisabled}disableTapDragZoom(){this._tapDragZoomDisabled=!0,this._tapDragZoom.disable()}enableTapDragZoom(){this._tapDragZoomDisabled=!1,this._touchZoom.isEnabled()&&this._tapDragZoom.enable()}isTapDragZoomEnabled(){return!this._tapDragZoomDisabled}}const Cf=e=>e.zoom||e.drag||e.pitch||e.rotate;class Af extends M{}class Lf{constructor(){this.constants=[1,1,.01],this.radius=0}setup(e,t){const i=ve([],t,e);this.radius=_s(i[2]<0?pr([],i,this.constants):[i[0],i[1],0])}projectRay(e){pr(e,e,this.constants),ye(e,e),fr(e,e,this.constants);const t=Ti([],e,this.radius);if(t[2]>0){const e=Ti([],[0,0,1],Kt(t,[0,0,1])),i=Ti([],ye([],[t[0],t[1],0]),this.radius),s=yo([],t,Ti([],ve([],yo([],i,e),t),2));t[0]=s[0],t[1]=s[1]}return t}}function Pf(e){return e.panDelta&&e.panDelta.mag()||e.zoomDelta||e.bearingDelta||e.pitchDelta}class Mf{constructor(e,t){this._map=e,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new Np(e),this._bearingSnap=t.bearingSnap,this._previousActiveHandlers={},this._trackingEllipsoid=new Lf,this._dragOrigin=null,this._mouseBeingPressed=!1,this._activeTouchCount=0,this._eventsInProgress={},this._addDefaultHandlers(t),rt(["handleEvent","handleWindowEvent"],this);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){const s=e===document?this.handleWindowEvent:this.handleEvent;e.addEventListener(t,s,i)}}destroy(){for(const[e,t,i]of this._listeners){const s=e===document?this.handleWindowEvent:this.handleEvent;e.removeEventListener(t,s,i)}}_addDefaultHandlers(e){const t=this._map,i=t.getCanvasContainer();this._add("mapEvent",new Zp(t,e));const s=t.boxZoom=new Hp(t,e);this._add("boxZoom",s);const o=new Kp,r=new Ef;t.doubleClickZoom=new Tf(r,o),this._add("tapZoom",o),this._add("clickZoom",r);const n=new If;this._add("tapDragZoom",n);const a=t.touchPitch=new ff(t);this._add("touchPitch",a);const l=new rf(e),c=new nf(e);t.dragRotate=new Df(e,l,c),this._add("mouseRotate",l,["mousePitch"]),this._add("mousePitch",c,["mouseRotate"]);const h=new of(e),d=new af(t,e);t.dragPan=new Sf(i,h,d),this._add("mousePan",h),this._add("touchPan",d,["touchZoom","touchRotate"]);const u=new _f,_=new df;t.touchZoomRotate=new Rf(i,_,u,n),this._add("touchRotate",u,["touchPan","touchZoom"]),this._add("touchZoom",_,["touchPan","touchRotate"]),this._add("blockableMapEvent",new Wp(t));const p=t.scrollZoom=new wf(t,this);this._add("scrollZoom",p,["mousePan"]);const f=t.keyboard=new gf;this._add("keyboard",f);for(const i of["boxZoom","doubleClickZoom","tapDragZoom","touchPitch","dragRotate","dragPan","touchZoomRotate","scrollZoom","keyboard"])e.interactive&&e[i]&&t[i].enable(e[i])}_add(e,t,i){this._handlers.push({handlerName:e,handler:t,allowed:i}),this._handlersById[e]=t}stop(e="never"){if(!this._updatingCamera&&!("always"===e||"ifPointerDown"===e&&this._isPointerDown())){for(const{handler:e}of this._handlers)e.reset();this._inertia.clear(),this._fireEvents({},{},!1),this._changes=[],this._originalZoom=void 0}}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!!Cf(this._eventsInProgress)||this.isZooming()}_isDragging(){return!!this._eventsInProgress.drag}_blockedByActive(e,t,i){for(const s in e)if(!(s===i||t&&t.includes(s)))return!0;return!1}handleWindowEvent(e){this.handleEvent(e,`${e.type}Window`)}_getMapTouches(e){const t=[];for(const i of e)this._el.contains(i.target)&&t.push(i);return t}_updatePointerLiveness(e){switch(e.type){case"mousedown":this._mouseBeingPressed=!0;break;case"mousemove":0===e.buttons&&(this._mouseBeingPressed=!1);break;case"mouseup":this._mouseBeingPressed=!1;break;case"touchstart":case"touchmove":case"touchend":case"touchcancel":this._activeTouchCount=e.touches?e.touches.length:0;break;case"blur":this._mouseBeingPressed=!1,this._activeTouchCount=0}}_isPointerDown(){return this._mouseBeingPressed||this._activeTouchCount>0}handleEvent(e,t){this._updatePointerLiveness(e),this._updatingCamera=!0;const i="renderFrame"===e.type,s=i?void 0:e,o={needsRenderFrame:!1},r={},n={},a=e.touches?this._getMapTouches(e.touches):void 0,l=a?Mn(this._el,a):i?void 0:Pn(this._el,e);for(const{handlerName:i,handler:c,allowed:h}of this._handlers){if(!c.isEnabled())continue;let d;this._blockedByActive(n,h,i)?c.reset():c[t||e.type]&&(d=c[t||e.type](e,l,a),this.mergeHandlerResult(o,r,d,i,s),d&&d.needsRenderFrame&&this._triggerRenderFrame()),(d||c.isActive())&&(n[i]=c)}const c={};for(const e in this._previousActiveHandlers)n[e]||(c[e]=s);this._previousActiveHandlers=n,(Object.keys(c).length||Pf(o))&&(this._changes.push([o,r,c]),this._triggerRenderFrame()),(Object.keys(n).length||Pf(o))&&this._map._stop({keepGesture:"always"}),this._updatingCamera=!1;const{cameraAnimation:h}=o;h&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],h(this._map))}mergeHandlerResult(e,t,i,s,o){if(!i)return;Object.assign(e,i);const r={handlerName:s,originalEvent:i.originalEvent||o};void 0!==i.zoomDelta&&(t.zoom=r),void 0!==i.panDelta&&(t.drag=r),void 0!==i.pitchDelta&&(t.pitch=r),void 0!==i.bearingDelta&&(t.rotate=r)}_applyChanges(){const e={},t={},i={};for(const[s,o,r]of this._changes)s.panDelta&&(e.panDelta=(e.panDelta||new m(0,0))._add(s.panDelta)),s.zoomDelta&&(e.zoomDelta=(e.zoomDelta||0)+s.zoomDelta),s.bearingDelta&&(e.bearingDelta=(e.bearingDelta||0)+s.bearingDelta),s.pitchDelta&&(e.pitchDelta=(e.pitchDelta||0)+s.pitchDelta),void 0!==s.around&&(e.around=s.around),void 0!==s.aroundCoord&&(e.aroundCoord=s.aroundCoord),void 0!==s.pinchAround&&(e.pinchAround=s.pinchAround),s.noInertia&&(e.noInertia=s.noInertia),Object.assign(t,o),Object.assign(i,r);this._updateMapTransform(e,t,i),this._changes=[]}_updateMapTransform(e,t,i){const s=this._map,o=s.transform,r=e=>[e.x,e.y,e.z];if((()=>{const e=this._eventsInProgress.drag;return e&&!this._handlersById[e.handlerName].isActive()})()&&!Pf(e)){const e=o.zoom;o.cameraElevationReference="sea",null!=this._originalZoom&&o._orthographicProjectionAtLowPitch&&"globe"!==o.projection.name&&0===o.pitch?(o.cameraElevationReference="ground",o.zoom=this._originalZoom):(o.recenterOnTerrain(),o.cameraElevationReference="ground"),e!==o.zoom&&this._map._update(!0)}if(o._isCameraConstrained&&s._stop({keepGesture:"always"}),!Pf(e))return void this._fireEvents(t,i,!0);let{panDelta:n,zoomDelta:a,bearingDelta:l,pitchDelta:c,around:h,aroundCoord:d,pinchAround:u}=e;o._isCameraConstrained&&(a>0&&(a=0),o._isCameraConstrained=!1),void 0!==u&&(h=u),(a||(e=>t[e]&&!this._eventsInProgress[e])("drag"))&&h&&(this._dragOrigin=r(o.pointCoordinate3D(h)),this._originalZoom=o.zoom,this._trackingEllipsoid.setup(o._camera.position,this._dragOrigin)),o.cameraElevationReference="sea",s._stop({keepGesture:"always"}),h=h||s.transform.centerPoint,l&&(o.bearing+=l),c&&(o.pitch+=c),o._updateCameraState();const _=[0,0,0];if(n)if("mercator"===o.projection.name){const e=this._trackingEllipsoid.projectRay(o.screenPointToMercatorRay(h).dir),t=this._trackingEllipsoid.projectRay(o.screenPointToMercatorRay(h.sub(n)).dir);_[0]=t[0]-e[0],_[1]=t[1]-e[1]}else{const e=o.pointCoordinate(h);if("globe"===o.projection.name){n=n.rotate(-o.angle);const t=o._pixelsPerMercatorPixel/o.worldSize;_[0]=-n.x*_r(at(e.y))*t,_[1]=-n.y*_r(o.center.lat)*t}else{const t=o.pointCoordinate(h.sub(n));e&&t&&(_[0]=t.x-e.x,_[1]=t.y-e.y)}}const p=o.zoom,f=[0,0,0];if(a){const e=r(d||o.pointCoordinate3D(h)),t={dir:ye([],ve([],e,o._camera.position))};if(t.dir[2]<0){const i=o.zoomDeltaToMovement(e,a);Ti(f,t.dir,i)}}const m=yo(_,_,f);o._translateCameraConstrained(m),a&&Math.abs(o.zoom-p)>1e-4&&o.recenterOnTerrain(),o.cameraElevationReference="ground",this._map._update(),e.noInertia||this._inertia.record(e),this._fireEvents(t,i,!0)}_fireEvents(e,t,i){const s=Cf(this._eventsInProgress),o=Cf(e),r={};for(const t in e){const{originalEvent:i}=e[t];this._eventsInProgress[t]||(r[`${t}start`]=i),this._eventsInProgress[t]=e[t]}!s&&o&&this._fireEvent("movestart",o.originalEvent);for(const e in r)this._fireEvent(e,r[e]);o&&this._fireEvent("move",o.originalEvent);for(const t in e){const{originalEvent:i}=e[t];this._fireEvent(t,i)}const n={};let a;for(const e in this._eventsInProgress){const{handlerName:i,originalEvent:s}=this._eventsInProgress[e];this._handlersById[i].isActive()||(delete this._eventsInProgress[e],a=t[i]||s,n[`${e}end`]=a)}for(const e in n)this._fireEvent(e,n[e]);const l=Cf(this._eventsInProgress);if(i&&(s||o)&&!l){this._updatingCamera=!0;const e=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),t=e=>0!==e&&-this._bearingSnap<e&&e<this._bearingSnap;e?(t(e.bearing||this._map.getBearing())&&(e.bearing=0),this._map.easeTo(e,{originalEvent:a})):(this._map.fire(new M("moveend",{originalEvent:a})),t(this._map.getBearing())&&this._map.resetNorth()),this._updatingCamera=!1}}_fireEvent(e,t){this._map.fire(new M(e,t?{originalEvent:t}:{}))}_requestFrame(){return this._map.triggerRepaint(),this._map._renderTaskQueue.add(e=>{this._frameId=void 0,this.handleEvent(new Af("renderFrame",{timeStamp:e})),this._applyChanges()})}_triggerRenderFrame(){void 0===this._frameId&&(this._frameId=this._requestFrame())}}const Of="map.setFreeCameraOptions(...) and map.getFreeCameraOptions() are not yet supported for non-mercator projections.";class zf extends A{constructor(e,t){super(),this._moving=!1,this._zooming=!1,this.transform=e,this._bearingSnap=t.bearingSnap,this._respectPrefersReducedMotion=!1!==t.respectPrefersReducedMotion,rt(["_renderFrameCallback"],this)}getCenter(){return new Es(this.transform.center.lng,this.transform.center.lat)}setCenter(e,t){return this.jumpTo({center:e},t)}panBy(e,t,i){return e=m.convert(e).mult(-1),this.panTo(this.transform.center,{offset:e,...t},i)}panTo(e,t,i){return this.easeTo({center:e,...t},i)}getZoom(){return this.transform.zoom}setZoom(e,t){return this.jumpTo({zoom:e},t),this}zoomTo(e,t,i){return this.easeTo({zoom:e,...t},i)}zoomIn(e,t){return this.zoomTo(this.getZoom()+1,e,t),this}zoomOut(e,t){return this.zoomTo(this.getZoom()-1,e,t),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,t,i){return this.easeTo({bearing:e,...t},i)}resetNorth(e,t){return this.rotateTo(0,{duration:1e3,...e},t),this}resetNorthPitch(e,t){return this.easeTo({bearing:0,pitch:0,duration:1e3,...e},t),this}snapToNorth(e,t){return Math.abs(this.getBearing())<this._bearingSnap?this.resetNorth(e,t):this}getPitch(){return this.transform.pitch}setPitch(e,t){return this.jumpTo({pitch:e},t),this}getVerticalFieldOfView(){return this.transform.fov}setVerticalFieldOfView(e,t){return this.jumpTo({fov:e},t)}getHorizontalFieldOfView(){return this.transform.horizontalFov}cameraForBounds(e,t){e=Le.convert(e);const i=t&&t.bearing||0,s=t&&t.pitch||0,o=e.getNorthWest(),r=e.getSouthEast();return this._cameraForBounds(this.transform,o,r,i,s,t)}_extendPadding(e){const t={top:0,right:0,bottom:0,left:0};return null==e?{...t,...this.transform.padding}:"number"==typeof e?{top:e,bottom:e,right:e,left:e}:{...t,...e}}_extendCameraOptions(e){return(e={offset:[0,0],maxZoom:this.transform.maxZoom,...e}).padding=this._extendPadding(e.padding),e}_minimumAABBFrustumDistance(e,t){const i=t.max[0]-t.min[0],s=t.max[1]-t.min[1];return i/s>e.aspect?i/(2*Math.tan(.5*e.fovX)*e.aspect):s/(2*Math.tan(.5*e.fovY)*e.aspect)}_cameraForBoundsOnGlobe(e,t,i,s,o,r){const n=e.clone(),a=this._extendCameraOptions(r);n.bearing=s,n.pitch=o;const l=Es.convert(t),c=Es.convert(i),h=.5*(l.lat+c.lat),d=.5*(l.lng+c.lng),u=mr(h,d),p=ye([],u),f=ye([],Ht([],p,[0,1,0])),m=Ht([],f,p),g=[f[0],f[1],f[2],0,m[0],m[1],m[2],0,p[0],p[1],p[2],0,0,0,0,1],v=[u,mr(l.lat,l.lng),mr(c.lat,l.lng),mr(c.lat,c.lng),mr(l.lat,c.lng),mr(h,l.lng),mr(h,c.lng),mr(l.lat,d),mr(c.lat,d)];let y=gr.fromPoints(v.map(e=>[Kt(f,e),Kt(m,e),Kt(p,e)]));const x=It([],y.center,g);0===vr(x)&&yr(x,0,0,1),ye(x,x),Ti(x,x,De),n.center=xr(x);const b=n.getWorldToCameraMatrix(),w=Tt(new Float64Array(16),b);y=gr.applyTransform(y,Ie([],b,g));const T=this._extendAABB(y,n,a,s);if(!T)return void _("Map cannot fit within canvas with the given bounds, padding, and/or offset.");y=T,It(x,x,b);const E=.5*(y.max[2]-y.min[2]),I=this._minimumAABBFrustumDistance(n,y),S=Ti([],[0,0,1],E),D=yo(S,x,S),R=I+(0===n.pitch?0:Zt(x,D)),C=n.globeCenterInViewSpace,A=ve([],x,[C[0],C[1],C[2]]);ye(A,A),Ti(A,A,R);const L=yo([],x,A);It(L,L,w);const P=Tr/De,M=_s(L),O=ws(Math.max(M*P-Tr,Number.EPSILON),0),z=Math.min(n.zoomFromMercatorZAdjusted(O),a.maxZoom);return z>.5*(uo+qs)?(n.setProjection({name:"mercator"}),n.zoom=z,this._cameraForBounds(n,t,i,s,o,r)):{center:n.center,zoom:z,bearing:s,pitch:o}}_extendAABB(e,t,i,s){const o=.5*((i.padding.left||0)+(i.padding.right||0)),r=.5*((i.padding.top||0)+(i.padding.bottom||0)),n=r,a=o,l=o,c=r,h=t.width-(a+l),d=t.height-(n+c),u=ve([],e.max,e.min),_=Math.min(h/u[0],d/u[1]),p=Math.min(t.scaleZoom(t.scale*_),i.maxZoom);if(isNaN(p))return null;const f=t.scale/t.zoomScale(p),g=new gr([e.min[0]-a*f,e.min[1]-c*f,e.min[2]],[e.max[0]+l*f,e.max[1]+n*f,e.max[2]]),v=("number"==typeof i.offset.x&&"number"==typeof i.offset.y?new m(i.offset.x,i.offset.y):m.convert(i.offset)).rotate(-le(s));return g.center[0]-=v.x*f,g.center[1]+=v.y*f,g}queryTerrainElevation(e,t){const i=this.transform.elevation;return i?(t={exaggerated:!0,...t},i.getAtPoint(we.fromLngLat(e),null,t.exaggerated)):null}_cameraForBounds(e,t,i,s,o,r){if("globe"===e.projection.name)return this._cameraForBoundsOnGlobe(e,t,i,s,o,r);const n=e.clone(),a=this._extendCameraOptions(r);n.bearing=s,n.pitch=o;const l=Es.convert(t),c=Es.convert(i),h=new Es(l.lng,c.lat),d=new Es(c.lng,l.lat),u=n.project(l),p=n.project(c),f=this.queryTerrainElevation(l),g=this.queryTerrainElevation(c),v=this.queryTerrainElevation(h),y=this.queryTerrainElevation(d),x=[[u.x,u.y,Math.min(f||0,g||0,v||0,y||0)],[p.x,p.y,Math.max(f||0,g||0,v||0,y||0)]];let b=gr.fromPoints(x);const w=n.getWorldToCameraMatrix(),T=Tt(new Float64Array(16),w);b=gr.applyTransform(b,w);const E=this._extendAABB(b,n,a,s);if(!E)return void _("Map cannot fit within canvas with the given bounds, padding, and/or offset.");b=E;const I=.5*ve([],b.max,b.min)[2],S=this._minimumAABBFrustumDistance(n,b),D=[0,0,1,0];Se(D,D,w),br(D,D);const R=Ti([],D,S+I),C=yo([],b.center,R);It(b.center,b.center,T),It(C,C,T);const A=n.unproject(new m(b.center[0],b.center[1])),L=wr(n.projection,A),P=Math.pow(2,L),M=Math.min(n._zoomFromMercatorZ(C[2]*n.pixelsPerMeter*P/n.worldSize),a.maxZoom);return n.mercatorFromTransition&&M<.5*(uo+qs)?(n.setProjection({name:"globe"}),n.zoom=M,this._cameraForBounds(n,t,i,s,o,r)):{center:A,zoom:M,bearing:s,pitch:o}}fitBounds(e,t,i){const s=this.cameraForBounds(e,t);return this._fitInternal(s,t,i)}fitScreenCoordinates(e,t,i,s,o){const r=m.convert(e),n=m.convert(t),a=new m(Math.min(r.x,n.x),Math.min(r.y,n.y)),l=new m(Math.max(r.x,n.x),Math.max(r.y,n.y));if("mercator"===this.transform.projection.name&&this.transform.anyCornerOffEdge(r,n))return this;const c=this.transform.pointLocation3D(a),h=this.transform.pointLocation3D(l),d=this.transform.pointLocation3D(new m(a.x,l.y)),u=this.transform.pointLocation3D(new m(l.x,a.y)),_=[Math.min(c.lng,h.lng,d.lng,u.lng),Math.min(c.lat,h.lat,d.lat,u.lat)],p=[Math.max(c.lng,h.lng,d.lng,u.lng),Math.max(c.lat,h.lat,d.lat,u.lat)],f=s&&s.pitch?s.pitch:this.getPitch(),g=this._cameraForBounds(this.transform,_,p,i,f,s);return this._fitInternal(g,s,o)}_fitInternal(e,t,i){return e?(t=Object.assign(e,t)).linear?this.easeTo(t,i):this.flyTo(t,i):this}jumpTo(e,t){this._stop({keepGesture:"ifPointerDown"});const i=e.preloadOnly?this.transform.clone():this.transform;let s=!1,o=!1,r=!1;"zoom"in e&&i.zoom!==+e.zoom&&(s=!0,i.zoom=+e.zoom),void 0!==e.center&&(i.center=Es.convert(e.center)),"bearing"in e&&i.bearing!==+e.bearing&&(o=!0,i.bearing=+e.bearing),"pitch"in e&&i.pitch!==+e.pitch&&(r=!0,i.pitch=+e.pitch),"fov"in e&&(i.fov=+e.fov);const n="number"==typeof e.padding?this._extendPadding(e.padding):e.padding;if(null!=e.padding&&!i.isPaddingEqual(n))if(!1===e.retainPadding){const e=i.clone();e.padding=n,i.setLocationAtPoint(i.center,e.centerPoint)}else i.padding=n;return e.preloadOnly?(this._preloadTiles(i),this):(this.fire(new M("movestart",t)).fire(new M("move",t)),s&&this.fire(new M("zoomstart",t)).fire(new M("zoom",t)).fire(new M("zoomend",t)),o&&this.fire(new M("rotatestart",t)).fire(new M("rotate",t)).fire(new M("rotateend",t)),r&&this.fire(new M("pitchstart",t)).fire(new M("pitch",t)).fire(new M("pitchend",t)),this.fire(new M("moveend",t)))}getFreeCameraOptions(){return this.transform.projection.supportsFreeCamera||_(Of),this.transform.getFreeCameraOptions()}setFreeCameraOptions(e,t){const i=this.transform;if(!i.projection.supportsFreeCamera)return _(Of),this;this.stop();const s=i.zoom,o=i.pitch,r=i.bearing;i.setFreeCameraOptions(e);const n=s!==i.zoom,a=o!==i.pitch,l=r!==i.bearing;return this.fire(new M("movestart",t)).fire(new M("move",t)),n&&this.fire(new M("zoomstart",t)).fire(new M("zoom",t)).fire(new M("zoomend",t)),l&&this.fire(new M("rotatestart",t)).fire(new M("rotate",t)).fire(new M("rotateend",t)),a&&this.fire(new M("pitchstart",t)).fire(new M("pitch",t)).fire(new M("pitchend",t)),this.fire(new M("moveend",t)),this}easeTo(e,t){this._stop({easeId:e.easeId}),(!1===(e={offset:[0,0],duration:500,easing:ur,...e}).animate||this._prefersReducedMotion(e))&&(e.duration=0);const i=e.preloadOnly?this.transform.clone():this.transform,s=this.getZoom(),o=this.getBearing(),r=this.getPitch(),n=this.getPadding(),a=this.getVerticalFieldOfView(),l="zoom"in e?+e.zoom:s,c="bearing"in e?this._normalizeBearing(e.bearing,o):o,h="pitch"in e?+e.pitch:r,d="fov"in e?+e.fov:a,u=this._extendPadding(e.padding),_=m.convert(e.offset);let p,f,g;if("globe"===i.projection.name){const t=we.fromLngLat(i.center),s=_.rotate(-i.angle);t.x+=s.x/i.worldSize,t.y+=s.y/i.worldSize;const o=t.toLngLat(),r=Es.convert(e.center||o);this._normalizeCenter(r),p=i.centerPoint.add(s),f=new m(t.x,t.y).mult(i.worldSize),g=new m(Ae(r.lng),Pe(r.lat)).mult(i.worldSize).sub(f)}else{p=i.centerPoint.add(_);const t=i.pointLocation(p),s=Es.convert(e.center||t);this._normalizeCenter(s),f=i.project(t),g=i.project(s).sub(f)}const v=i.zoomScale(l-s);let y,x;e.around&&(y=Es.convert(e.around),x=i.locationPoint(y));const b=this._zooming||l!==s,w=this._rotating||o!==c,T=this._pitching||h!==r,E=d!==a,I=!i.isPaddingEqual(u),S=!1===e.retainPadding?i.clone():i,D=i=>m=>{if(b&&(i.zoom=J(s,l,m)),w&&(i.bearing=J(o,c,m)),T&&(i.pitch=J(r,h,m)),E&&(i.fov=J(a,d,m)),I&&(S.interpolatePadding(n,u,m),p=S.centerPoint.add(_)),y)i.setLocationAtPoint(y,x);else{const e=i.zoomScale(i.zoom-s),t=l>s?Math.min(2,v):Math.max(.5,v),o=Math.pow(t,1-m),r=i.unproject(f.add(g.mult(m*o)).mult(e));i.setLocationAtPoint(i.renderWorldCopies?r.wrap():r,p)}return e.preloadOnly||this._fireMoveEvents(t),i};if(e.preloadOnly){const t=this._emulate(D,e.duration,i);return this._preloadTiles(t),this}const R={moving:this._moving,zooming:this._zooming,rotating:this._rotating,pitching:this._pitching};return this._zooming=b,this._rotating=w,this._pitching=T,this._padding=I,this._easeId=e.easeId,this._prepareEase(t,e.noMoveStart,R),this._ease(D(i),e=>{"sea"===i.cameraElevationReference&&i.recenterOnTerrain(),this._afterEase(t,e)},e),this}_prepareEase(e,t,i={}){this._moving=!0,this.transform.cameraElevationReference="sea",this.transform._orthographicProjectionAtLowPitch&&0===this.transform.pitch&&"globe"!==this.transform.projection.name&&(this.transform.cameraElevationReference="ground"),t||i.moving||this.fire(new M("movestart",e)),this._zooming&&!i.zooming&&this.fire(new M("zoomstart",e)),this._rotating&&!i.rotating&&this.fire(new M("rotatestart",e)),this._pitching&&!i.pitching&&this.fire(new M("pitchstart",e))}_fireMoveEvents(e){this.fire(new M("move",e)),this._zooming&&this.fire(new M("zoom",e)),this._rotating&&this.fire(new M("rotate",e)),this._pitching&&this.fire(new M("pitch",e))}_afterEase(e,t){if(this._easeId&&t&&this._easeId===t)return;this._easeId=void 0,this.transform.cameraElevationReference="ground";const i=this._zooming,s=this._rotating,o=this._pitching;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._padding=!1,i&&this.fire(new M("zoomend",e)),s&&this.fire(new M("rotateend",e)),o&&this.fire(new M("pitchend",e)),this.fire(new M("moveend",e))}flyTo(e,t){if(this._prefersReducedMotion(e)){const i=Me(e,["center","zoom","bearing","pitch","fov","around","padding","retainPadding"]);return this.jumpTo(i,t)}this.stop();const i=(e={offset:[0,0],speed:1.2,curve:1.42,easing:ur,...e}).preloadOnly?this.transform.clone():this.transform,s=this.getZoom(),o=this.getBearing(),r=this.getPitch(),n=this.getPadding(),a=this.getVerticalFieldOfView(),l="zoom"in e?Ee(+e.zoom,i.minZoom,i.maxZoom):s,c="bearing"in e?this._normalizeBearing(e.bearing,o):o,h="pitch"in e?+e.pitch:r,d="fov"in e?+e.fov:a,u=d!==a,_=this._extendPadding(e.padding),p=i.zoomScale(l-s),f=m.convert(e.offset);let g=i.centerPoint.add(f);const v=i.pointLocation(g),y=Es.convert(e.center||v);this._normalizeCenter(y);const x=i.project(v),b=i.project(y).sub(x);let w=e.curve;const T=Math.max(i.width,i.height),E=T/p,I=b.mag();if("minZoom"in e){const t=Ee(Math.min(e.minZoom,s,l),i.minZoom,i.maxZoom),o=T/i.zoomScale(t-s);w=Math.sqrt(o/I*2)}const S=w*w;function D(e){return-Math.asinh((E*E-T*T+(e?-1:1)*S*S*I*I)/(2*(e?E:T)*S*I))}function R(e){return(Math.exp(e)-Math.exp(-e))/2}function C(e){return(Math.exp(e)+Math.exp(-e))/2}const A=D(0);let L=function(e){return C(A)/C(A+w*e)},P=function(e){return T*((C(A)*(R(t=A+w*e)/C(t))-R(A))/S)/I;var t},M=(D(1)-A)/w;if(Math.abs(I)<1e-6||!isFinite(M)){if(Math.abs(T-E)<1e-6)return this.easeTo(e,t);const i=E<T?-1:1;M=Math.abs(Math.log(E/T))/w,P=function(){return 0},L=function(e){return Math.exp(i*w*e)}}e.duration="duration"in e?+e.duration:1e3*M/("screenSpeed"in e?+e.screenSpeed/w:+e.speed),e.maxDuration&&e.duration>e.maxDuration&&(e.duration=0);const O=o!==c,z=h!==r,F=!i.isPaddingEqual(_),k=!1===e.retainPadding?i.clone():i,B=i=>p=>{const m=p*M,v=1/L(m);i.zoom=1===p?l:s+i.scaleZoom(v),O&&(i.bearing=J(o,c,p)),z&&(i.pitch=J(r,h,p)),u&&(i.fov=J(a,d,p)),F&&(k.interpolatePadding(n,_,p),g=k.centerPoint.add(f));const w=1===p?y:i.unproject(x.add(b.mult(P(m))).mult(v));return i.setLocationAtPoint(i.renderWorldCopies?w.wrap():w,g),i._updateCameraOnTerrain(),e.preloadOnly||this._fireMoveEvents(t),i};if(e.preloadOnly){const t=this._emulate(B,e.duration,i);return this._preloadTiles(t),this}return this._zooming=!0,this._rotating=O,this._pitching=z,this._padding=F,this._prepareEase(t,!1),this._ease(B(i),()=>this._afterEase(t),e),this}isEasing(){return!!this._easeFrameId}stop(){return this._stop()}_requestRenderFrame(e){}_cancelRenderFrame(e){}_stop({easeId:e,keepGesture:t}={}){if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),this._easeFrameId=void 0,this._onEaseFrame=void 0),this._onEaseEnd){const t=this._onEaseEnd;this._onEaseEnd=void 0,t.call(this,e)}const i=this.handlers;return i&&i.stop(t),this}_ease(e,t,i){!1===i.animate||0===i.duration?(e(1),t()):(this._easeStart=T.now(),this._easeOptions=i,this._onEaseFrame=e,this._onEaseEnd=t,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback))}_renderFrameCallback(){const e=Math.min((T.now()-this._easeStart)/this._easeOptions.duration,1),t=this._onEaseFrame;t&&t(this._easeOptions.easing(e)),e<1?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop()}_normalizeBearing(e,t){e=si(e,-180,180);const i=Math.abs(e-t);return Math.abs(e-360-t)<i&&(e-=360),Math.abs(e+360-t)<i&&(e+=360),e}_normalizeCenter(e){const t=this.transform;if(t.maxBounds)return;if("globe"!==t.projection.name&&!t.renderWorldCopies)return;const i=e.lng-t.center.lng;e.lng+=i>180?-360:i<-180?360:0}_prefersReducedMotion(e){return this._respectPrefersReducedMotion&&T.prefersReducedMotion&&!(e&&e.essential)}_emulate(e,t,i){const s=Math.ceil(15*t/1e3),o=[],r=e(i.clone());for(let e=0;e<=s;e++){const t=r(e/s);o.push(t.clone())}return o}_preloadTiles(e,t){}}const Ff=/^(https?:|mailto:)/i;class kf{constructor(e={}){this.options=e,rt(["_toggleAttribution","_updateEditLink","_updateData","_updateCompact"],this)}getDefaultPosition(){return"bottom-right"}onAdd(e){const t=this.options&&this.options.compact,i=e._getUIString("AttributionControl.ToggleAttribution");this._map=e,this._container=Tn("div","mapboxgl-ctrl mapboxgl-ctrl-attrib"),this._compactButton=Tn("button","mapboxgl-ctrl-attrib-button",this._container),this._compactButton.type="button",this._compactButton.addEventListener("click",this._toggleAttribution),this._compactButton.setAttribute("aria-label",i);const s=Tn("span","mapboxgl-ctrl-icon",this._compactButton);return s.setAttribute("aria-hidden","true"),s.setAttribute("title",i),this._innerContainer=Tn("div","mapboxgl-ctrl-attrib-inner",this._container),t&&this._container.classList.add("mapboxgl-compact"),this._updateAttributions(),this._updateEditLink(),this._map.on("styledata",this._updateData),this._map.on("sourcedata",this._updateData),this._map.on("moveend",this._updateEditLink),void 0===t&&(this._map.on("resize",this._updateCompact),this._updateCompact()),this._container}onRemove(){this._container.remove(),this._map.off("styledata",this._updateData),this._map.off("sourcedata",this._updateData),this._map.off("moveend",this._updateEditLink),this._map.off("resize",this._updateCompact),this._map=void 0,this._attribHTML=void 0}_toggleAttribution(){this._container.classList.contains("mapboxgl-compact-show")?(this._container.classList.remove("mapboxgl-compact-show"),this._compactButton.setAttribute("aria-expanded","false")):(this._container.classList.add("mapboxgl-compact-show"),this._compactButton.setAttribute("aria-expanded","true"))}_updateEditLink(){let e=this._editLink;e||(e=this._editLink=this._container.querySelector(".mapbox-improve-map"));const t=[{key:"owner",value:this.styleOwner},{key:"id",value:this.styleId},{key:"access_token",value:this._map._requestManager._customAccessToken||l.ACCESS_TOKEN}];if(e){const i=t.reduce((e,i,s)=>(i.value&&(e+=`${i.key}=${i.value}${s<t.length-1?"&":""}`),e),"?");e.href=`${l.FEEDBACK_URL}/${i}#${Mp(this._map,!0)}`,e.rel="noopener nofollow"}}_updateData(e){!e||("source"!==e.dataType||"metadata"!==e.sourceDataType&&"visibility"!==e.sourceDataType)&&"style"!==e.dataType||(this._updateAttributions(),this._updateEditLink())}_updateAttributions(){if(!this._map.style)return;let e=[];if(this._map.style.stylesheet){const e=this._map.style.stylesheet;this.styleOwner=e.owner,this.styleId=e.id}const t=this._map.style._mergedSourceCaches;for(const i in t){const s=t[i];if(s.used){const t=s.getSource();t.attribution&&!e.includes(t.attribution)&&e.push(t.attribution)}}e.sort((e,t)=>e.length-t.length),e=e.filter((t,i)=>{for(let s=i+1;s<e.length;s++)if(e[s].includes(t))return!1;return!0}),this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?e=[...this.options.customAttribution,...e]:e.unshift(this.options.customAttribution));const i=e.map(e=>function(e){const t=(new DOMParser).parseFromString(e,"text/html");return Array.from(t.body.querySelectorAll("*")).reverse().forEach(e=>{const i=e.textContent||"";if("A"!==e.tagName)return void e.replaceWith(...e.childNodes);const s=e.getAttribute("href");if(!s||!Ff.test(s))return void e.replaceWith(t.createTextNode(i));const o=t.createElement("a");o.href=s,o.textContent=i,o.rel="noopener nofollow";const r=e.getAttribute("class");r&&(o.className=r),e.replaceWith(o)}),t.body.innerHTML}(e)).join(" | ");i!==this._attribHTML&&(this._attribHTML=i,e.length?(this._innerContainer.innerHTML=i,this._container.classList.remove("mapboxgl-attrib-empty")):this._container.classList.add("mapboxgl-attrib-empty"),this._editLink=null)}_updateCompact(){this._map.getCanvasContainer().offsetWidth<=640?this._container.classList.add("mapboxgl-compact"):this._container.classList.remove("mapboxgl-compact","mapboxgl-compact-show")}}class Bf{constructor(){rt(["_updateLogo","_updateCompact"],this)}onAdd(e){this._map=e,this._container=Tn("div","mapboxgl-ctrl");const t=Tn("a","mapboxgl-ctrl-logo");return t.target="_blank",t.rel="noopener nofollow",t.href="https://www.mapbox.com/",t.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),t.setAttribute("rel","noopener nofollow"),this._container.appendChild(t),this._container.style.display="none",this._map.on("sourcedata",this._updateLogo),this._updateLogo(),this._map.on("resize",this._updateCompact),this._updateCompact(),this._container}onRemove(){this._container.remove(),this._map.off("sourcedata",this._updateLogo),this._map.off("resize",this._updateCompact)}getDefaultPosition(){return"bottom-left"}_updateLogo(e){e&&"metadata"!==e.sourceDataType||(this._container.style.display=this._logoRequired()?"block":"none")}_logoRequired(){if(!this._map.style)return!0;const e=this._map.style._mergedSourceCaches;if(0===Object.entries(e).length)return!0;for(const t in e){const i=e[t].getSource();if(Object.hasOwn(i,"mapbox_logo")&&!i.mapbox_logo)return!1}return!0}_updateCompact(){const e=this._container.children;if(e.length){const t=e[0];this._map.getCanvasContainer().offsetWidth<250?t.classList.add("mapboxgl-compact"):t.classList.remove("mapboxgl-compact")}}}class Nf{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){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=[]}}class Uf{constructor(e){this.jumpTo(e)}getValue(e){if(e<=this._startTime)return this._start;if(e>=this._endTime)return this._end;const t=Er((e-this._startTime)/(this._endTime-this._startTime));return this._start*(1-t)+this._end*t}isEasing(e){return e>=this._startTime&&e<=this._endTime}jumpTo(e){this._startTime=-1/0,this._endTime=-1/0,this._start=e,this._end=e}easeTo(e,t,i){this._start=this.getValue(t),this._end=e,this._startTime=t,this._endTime=t+i}}const Vf={"AttributionControl.ToggleAttribution":"Toggle attribution","FullscreenControl.Enter":"Enter fullscreen","FullscreenControl.Exit":"Exit fullscreen","GeolocateControl.FindMyLocation":"Find my location","GeolocateControl.LocationNotAvailable":"Location not available","LogoControl.Title":"Mapbox homepage","Map.Title":"Map","NavigationControl.ResetBearing":"Reset bearing to north","NavigationControl.ZoomIn":"Zoom in","NavigationControl.ZoomOut":"Zoom out","ScrollZoomBlocker.CtrlMessage":"Use ctrl + scroll to zoom the map","ScrollZoomBlocker.CmdMessage":"Use ⌘ + scroll to zoom the map","TouchPanBlocker.Message":"Use two fingers to move the map"};class jf extends M{constructor(e,t,i,s){const{point:o,lngLat:r,originalEvent:n,target:a}=e;super(e.type,{point:o,lngLat:r,originalEvent:n,target:a}),this.preventDefault=()=>{e.preventDefault()},this.id=t,this.interaction=i,this.feature=s}}class Gf{constructor(e){this.map=e,this.interactionsByType=new Map,this.delegatedInteractions=new Map,this.typeById=new Map,this.filters=new Map,this.handleType=this.handleType.bind(this),this.handleMove=this.handleMove.bind(this),this.handleOut=this.handleOut.bind(this),this.hoveredFeatures=new Map,this.prevHoveredFeatures=new Map}add(e,t){if(this.typeById.has(e))throw new Error(`Interaction id "${e}" already exists.`);const i=t.filter;let s=t.type;i&&this.filters.set(e,dt(i)),"mouseover"===s&&(s="mouseenter"),"mouseout"===s&&(s="mouseleave");const o=this.interactionsByType.get(s)||new Map;"mouseenter"===s||"mouseleave"===s?(0===this.delegatedInteractions.size&&(this.map.on("mousemove",this.handleMove),this.map.on("mouseout",this.handleOut)),this.delegatedInteractions.set(e,t)):0===o.size&&this.map.on(s,this.handleType),0===o.size&&this.interactionsByType.set(s,o),o.set(e,t),this.typeById.set(e,s)}get(e){const t=this.typeById.get(e);if(!t)return;const i=this.interactionsByType.get(t);return i?i.get(e):void 0}remove(e){const t=this.typeById.get(e);if(!t)return;this.typeById.delete(e),this.filters.delete(e);const i=this.interactionsByType.get(t);i&&(i.delete(e),"mouseenter"===t||"mouseleave"===t?(this.delegatedInteractions.delete(e),0===this.delegatedInteractions.size&&(this.map.off("mousemove",this.handleMove),this.map.off("mouseout",this.handleOut))):0===i.size&&this.map.off(t,this.handleType))}queryTargets(e,t){const i=[];for(const[e,s]of t)s.target&&i.push({targetId:e,target:s.target,filter:this.filters.get(e)});return this.map.style.queryRenderedTargets(e,i,this.map.transform)}handleMove(e){this.prevHoveredFeatures=this.hoveredFeatures,this.hoveredFeatures=new Map;const t=this.queryTargets(e.point,Array.from(this.delegatedInteractions).reverse());t.length&&(e.type="mouseenter",this.handleType(e,t));const i=new Map;for(const[e,{feature:t}]of this.prevHoveredFeatures)this.hoveredFeatures.has(e)||i.set(t.id,t);i.size&&(e.type="mouseleave",this.handleType(e,Array.from(i.values())))}handleOut(e){const t=Array.from(this.hoveredFeatures.values()).map(({feature:e})=>e);t.length&&(e.type="mouseleave",this.handleType(e,t)),this.hoveredFeatures.clear()}handleType(e,t){const i="mouseenter"===e.type;if(i&&!this.interactionsByType.has(e.type))return void _("mouseenter interaction required for mouseleave to work.");const s=Array.from(this.interactionsByType.get(e.type)).reverse(),o=!!t;t=t||this.queryTargets(e.point,s);let r=!1;const n=new Set;for(const a of t){for(const[t,l]of s){if(!l.target)continue;const s=a.variants?a.variants[t]:null;if(s){for(const c of s){if(ic(c,a,n,t))continue;const s=new ls(a,c),h=tc(c,a,t);o&&void 0!==s.id&&(s.state=this.map.getFeatureState(s));const d=i?this.prevHoveredFeatures.get(h):null,u=new jf(e,t,l,s),_=d?d.stop:l.handler(u);if(i&&this.hoveredFeatures.set(h,{feature:a,stop:_}),!1!==_){r=!0;break}}if(r)break}}if(r)break}if(!r)for(const[t,i]of s){const{handler:s,target:o}=i;if(!o&&!1!==s(new jf(e,t,i,null)))break}}}function qf(e,t){if(Array.isArray(e)&&Array.isArray(t)){const i=new Set(e),s=new Set(t);return i.size===s.size&&e.every(e=>s.has(e))}return rs(e,t)}const Zf=/matrix.*\((.+)\)/,Wf={center:[0,0],zoom:0,bearing:0,pitch:0,minZoom:-2,maxZoom:22,minPitch:0,maxPitch:85,interactive:!0,scrollZoom:!0,boxZoom:!0,dragRotate:!0,dragPan:!0,keyboard:!0,doubleClickZoom:!0,touchZoomRotate:!0,touchPitch:!0,cooperativeGestures:!1,performanceMetricsCollection:!0,bearingSnap:7,clickTolerance:3,pitchWithRotate:!0,hash:!1,attributionControl:!0,antialias:!1,failIfMajorPerformanceCaveat:!1,preserveDrawingBuffer:!1,trackResize:!0,renderWorldCopies:!0,refreshExpiredTiles:!0,minTileCacheSize:null,maxTileCacheSize:null,localIdeographFontFamily:"sans-serif",localFontFamily:null,fontstackCompositing:"client",transformRequest:null,accessToken:null,fadeDuration:300,respectPrefersReducedMotion:!0,crossSourceCollisions:!0,collectResourceTiming:!1,testMode:!1,precompilePrograms:!0,scaleFactor:1,emissiveColorPrecision:"approximate"};let Hf=class extends zf{constructor(e){Pr.mark(Lr.create);const t=e;if(null!=(e={...Wf,...e}).minZoom&&null!=e.maxZoom&&e.minZoom>e.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(null!=e.minPitch&&null!=e.maxPitch&&e.minPitch>e.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(null!=e.minPitch&&e.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(null!=e.maxPitch&&e.maxPitch>85)throw new Error("maxPitch must be less than or equal to 85");super(new Eu(e.minZoom,e.maxZoom,e.minPitch,e.maxPitch,e.renderWorldCopies,null,null),e),this._animationFrameProvider=e.animationFrameProvider,this._repaint=!!e.repaint,this._interactive=e.interactive,this._minTileCacheSize=e.minTileCacheSize,this._maxTileCacheSize=e.maxTileCacheSize,this._failIfMajorPerformanceCaveat=e.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=e.preserveDrawingBuffer,this._antialias=e.antialias,this._trackResize=e.trackResize,this._bearingSnap=e.bearingSnap,this._refreshExpiredTiles=e.refreshExpiredTiles,this._fadeDuration=e.fadeDuration,this._placementAlgorithm=e.placementAlgorithm||"default",this._staticMode=!1,this._isInitialLoad=!0,this._crossSourceCollisions=e.crossSourceCollisions,this._collectResourceTiming=e.collectResourceTiming,this._language=this._parseLanguage(e.language),this._worldview=e.worldview,this._renderTaskQueue=new Nf,this._domRenderTaskQueue=new Nf,this._controls=[],this._markers=[],this._popups=[],this._mapId=ce(),this._locale={...Vf,...e.locale},this._clickTolerance=e.clickTolerance,this._cooperativeGestures=e.cooperativeGestures,this._performanceMetricsCollection=e.performanceMetricsCollection,this._tessellationStep=e.tessellationStep,this._containerWidth=0,this._containerHeight=0,this._showParseStatus=!0,this._precompilePrograms=e.precompilePrograms,this._averageElevationLastSampledAt=-1/0,this._averageElevationExaggeration=0,this._averageElevation=new Uf(0),this._interactionRange=[1/0,-1/0],this._visibilityHidden=0,this._useExplicitProjection=!1,this._frameId=0,this._emissiveColorPrecision=e.emissiveColorPrecision,this._scaleFactor=e.scaleFactor,this._requestManager=new Ur(e.transformRequest,e.accessToken,e.testMode);const i=Zr(e.accessToken||l.ACCESS_TOKEN);if(i&&"atlas"in i&&"number"==typeof i.atlas&&(this._tokenExpiration=i.atlas),this._silenceAuthErrors=!!e.testMode,this._contextCreateOptions=e.contextCreateOptions?{...e.contextCreateOptions}:{},"string"==typeof e.container){const t=document.getElementById(e.container);if(!t)throw new Error(`Container '${e.container.toString()}' not found.`);this._container=t}else{if(!(e.container instanceof HTMLElement))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=e.container}if(this._container.childNodes.length>0&&_("The map container element should be empty, otherwise the map's interactivity will be negatively impacted. If you want to display a message when WebGL is not supported, use the Mapbox GL Supported plugin instead."),e.maxBounds&&this.setMaxBounds(e.maxBounds),this._spriteFormat="auto",rt(["_onWindowOnline","_onWindowResize","_onVisibilityChange","_onMapScroll","_contextLost","_contextRestored"],this),this._setupContainer(),this._setupPainter(),void 0===this.painter)throw new Error("Failed to initialize WebGL.");if(this.on("move",()=>this._update(!1)),this.on("moveend",()=>this._update(!1)),this.on("zoom",()=>this._update(!0)),this._fullscreenchangeEvent="onfullscreenchange"in document?"fullscreenchange":"webkitfullscreenchange",window.addEventListener("online",this._onWindowOnline,!1),window.addEventListener("resize",this._onWindowResize,!1),window.addEventListener("orientationchange",this._onWindowResize,!1),window.addEventListener(this._fullscreenchangeEvent,this._onWindowResize,!1),window.addEventListener("visibilitychange",this._onVisibilityChange,!1),this.handlers=new Mf(this,e),this._localFontFamily=e.localFontFamily,this._localIdeographFontFamily=e.localIdeographFontFamily,this._fontstackCompositing=e.fontstackCompositing,(e.style||!e.testMode)&&this.setStyle(e.style||l.DEFAULT_STYLE,{config:e.config,localFontFamily:this._localFontFamily,localIdeographFontFamily:this._localIdeographFontFamily,fontstackCompositing:this._fontstackCompositing}),e.projection&&this.setProjection(e.projection),e.hash&&(this._hash=new Pp("string"==typeof e.hash&&e.hash||void 0).addTo(this)),!this._hash||!this._hash._onHashChange()){null==t.center&&null==t.zoom||(this.transform._unmodified=!1),this.jumpTo({center:e.center,zoom:e.zoom,bearing:e.bearing,pitch:e.pitch});const i=e.bounds;i&&(this.resize(),this.fitBounds(i,{...e.fitBoundsOptions,duration:0}))}this.resize(),e.attributionControl&&this.addControl(new kf({customAttribution:e.customAttribution})),this._logoControl=new Bf,this.addControl(this._logoControl,e.logoPosition),this.on("style.load",()=>{this.transform.unmodified&&this.jumpTo(this.style.stylesheet),this._postStyleLoadEvent(),this._postStyleWithAppearanceEvent()}),this.on("data",e=>{this._update("style"===e.dataType),this.fire(new M(`${e.dataType}data`,e))}),this.on("dataloading",e=>{this.fire(new M(`${e.dataType}dataloading`,e))}),this._interactions=new Gf(this)}_getMapId(){return this._mapId}addControl(e,t){let i,s;if("string"==typeof t?i=t:t&&(i=t.position,s=t.offset),void 0===i&&(i=e.getDefaultPosition?e.getDefaultPosition():"top-right"),!e||!e.onAdd)return this.fire(new P(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));const o=e.onAdd(this);this._controls.push(e),function(e,t,i){const s=i&&void 0!==i.x?`${Math.max(0,i.x)}px`:"",o=i&&void 0!==i.y?`${Math.max(0,i.y)}px`:"";e.style.marginLeft=t.includes("left")?s:"",e.style.marginRight=t.includes("right")?s:"",e.style.marginTop=t.includes("top")?o:"",e.style.marginBottom=t.includes("bottom")?o:""}(o,i,s);const r=this._controlPositions[i];return i.includes("bottom")?r.insertBefore(o,r.firstChild):r.appendChild(o),this}removeControl(e){if(!e||!e.onRemove)return this.fire(new P(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));const t=this._controls.indexOf(e);return t>-1&&this._controls.splice(t,1),e.onRemove(this),this}hasControl(e){return this._controls.includes(e)}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}resize(e){if(this._updateContainerDimensions(),this._containerWidth===this.transform.width&&this._containerHeight===this.transform.height)return this;this._resizeCanvas(this._containerWidth,this._containerHeight),this.transform.resize(this._containerWidth,this._containerHeight),this.painter.resize(Math.ceil(this._containerWidth),Math.ceil(this._containerHeight));const t=!this._moving;return t&&this.fire(new M("movestart",e)).fire(new M("move",e)),this.fire(new M("resize",e)),t&&this.fire(new M("moveend",e)),this}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()||null}setMaxBounds(e){return this.transform.setMaxBounds(Le.convert(e)),this._update()}setMinZoom(e){if((e=e??-2)>=-2&&e<=this.transform.maxZoom)return this.transform.minZoom=e,this._update(),this.getZoom()<e?this.setZoom(e):this.fire(new M("zoomstart",{})).fire(new M("zoom",{})).fire(new M("zoomend",{})),this;throw new Error("minZoom must be between -2 and the current maxZoom, inclusive")}getMinZoom(){return this.transform.minZoom}setMaxZoom(e){if((e=e??22)>=this.transform.minZoom)return this.transform.maxZoom=e,this._update(),this.getZoom()>e?this.setZoom(e):this.fire(new M("zoomstart",{})).fire(new M("zoom",{})).fire(new M("zoomend",{})),this;throw new Error("maxZoom must be greater than the current minZoom")}getMaxZoom(){return this.transform.maxZoom}setMinPitch(e){if((e=e??0)<0)throw new Error("minPitch must be greater than or equal to 0");if(e>=0&&e<=this.transform.maxPitch)return this.transform.minPitch=e,this._update(),this.getPitch()<e?this.setPitch(e):this.fire(new M("pitchstart",{})).fire(new M("pitch",{})).fire(new M("pitchend",{})),this;throw new Error("minPitch must be between 0 and the current maxPitch, inclusive")}getMinPitch(){return this.transform.minPitch}setMaxPitch(e){if((e=e??85)>85)throw new Error("maxPitch must be less than or equal to 85");if(e>=this.transform.minPitch)return this.transform.maxPitch=e,this._update(),this.getPitch()>e?this.setPitch(e):this.fire(new M("pitchstart",{})).fire(new M("pitch",{})).fire(new M("pitchend",{})),this;throw new Error("maxPitch must be greater than or equal to minPitch")}getMaxPitch(){return this.transform.maxPitch}getScaleFactor(){return this._scaleFactor}setScaleFactor(e){return this._scaleFactor=e,this.painter.scaleFactor=e,this.style&&this.style._setLabelPlacementStale(),this.style._updateFilteredLayers(e=>"symbol"===e.type),this._update(!0),this}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(e){return this.transform.renderWorldCopies=e,this.transform.renderWorldCopies||this._forceMarkerAndPopupUpdate(!0),this._update()}getLanguage(){return this._language}_parseLanguage(e){return"auto"===e?navigator.language:Array.isArray(e)?0===e.length?void 0:e.map(e=>"auto"===e?navigator.language:e):e}setLanguage(e){const t=this._parseLanguage(e);if(!this.style||t===this._language)return this;this._language=t,this.style.reloadSources();for(const e of this._controls)e._setLanguage&&e._setLanguage(this._language);return this}getWorldview(){return this._worldview}setWorldview(e){return this.style&&e!==this._worldview?(this._worldview=e,this._styleDirty=!0,this.style.setWorldview(e),this):this}getProjection(){return this.transform.mercatorFromTransition?{name:"globe",center:[0,0]}:this.transform.getProjection()}_showingGlobe(){return"globe"===this.transform.projection.name}setProjection(e){return this._lazyInitEmptyStyle(),e?"string"==typeof e&&(e={name:e}):e=null,this._useExplicitProjection=!!e,this._prioritizeAndUpdateProjection(e,this.style.projection)}_updateProjectionTransition(){if("globe"!==this.getProjection().name)return;const e=this.transform,t=e.projection.name;let i;"globe"===t&&e.zoom>=qs?(e.setMercatorFromTransition(),i=!0):"mercator"===t&&e.zoom<qs&&(e.setProjection({name:"globe"}),i=!0),i&&(this.style.applyProjectionUpdate(),this.style._forceSymbolLayerUpdate(),this._update(!0))}_prioritizeAndUpdateProjection(e,t){return this._updateProjection(e||t||{name:"mercator"})}_updateProjection(e){let t;const i=this.transform.mercatorFromTransition;t="globe"===e.name&&this.transform.zoom>=qs?this.transform.setMercatorFromTransition():this.transform.setProjection(e),this.style.applyProjectionUpdate();const s="mercator"===this.transform.getProjection().name&&i!==this.transform.mercatorFromTransition;return(t||s)&&(this.painter.clearBackgroundTiles(),this.style.clearSources(),this._update(!0),this._forceMarkerAndPopupUpdate(!0)),this}project(e,t){return this.transform.locationPoint3D(Es.convert(e),t)}unproject(e,t){return this.transform.pointLocation3D(m.convert(e),t)}isMoving(){return this._moving||this.handlers&&this.handlers.isMoving()||!1}isZooming(){return this._zooming||this.handlers&&this.handlers.isZooming()||!1}isRotating(){return this._rotating||this.handlers&&this.handlers.isRotating()||!1}_isDragging(){return this.handlers&&this.handlers._isDragging()||!1}_createDelegatedListener(e,t,i){const s=e=>{let i=[];if(Array.isArray(t)){const s=t.filter(e=>this.getLayer(e));i=s.length?this.queryRenderedFeatures(e,{layers:s}):[]}else i=this.queryRenderedFeatures(e,{target:t});return i};if("mouseenter"===e||"mouseover"===e){let o=!1;const r=t=>{const r=s(t.point);r.length?o||(o=!0,i.call(this,new jp(e,this,t.originalEvent,{features:r}))):o=!1};return{listener:i,targets:t,delegates:{mousemove:r,mouseout:()=>{o=!1}}}}if("mouseleave"===e||"mouseout"===e){let o=!1;const r=t=>{s(t.point).length?o=!0:o&&(o=!1,i.call(this,new jp(e,this,t.originalEvent)))},n=t=>{o&&(o=!1,i.call(this,new jp(e,this,t.originalEvent)))};return{listener:i,targets:t,delegates:{mousemove:r,mouseout:n}}}{const o=e=>{const t=s(e.point);t.length&&(e.features=t,i.call(this,e),delete e.features)};return{listener:i,targets:t,delegates:{[e]:o}}}}on(e,t,i){if("function"==typeof t||void 0===i)return super.on(e,t);if("string"==typeof t&&(t=[t]),!this._areTargetsValid(t))return this;const s=this._createDelegatedListener(e,t,i);this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[e]=this._delegatedListeners[e]||[],this._delegatedListeners[e].push(s);for(const e in s.delegates)this.on(e,s.delegates[e]);return this}once(e,t,i){if("function"==typeof t||void 0===i)return super.once(e,t);if("string"==typeof t&&(t=[t]),!this._areTargetsValid(t))return this;const s=this._createDelegatedListener(e,t,i);for(const e in s.delegates)this.once(e,s.delegates[e]);return this}off(e,t,i){if("function"==typeof t||void 0===i)return super.off(e,t);if("string"==typeof t&&(t=[t]),!this._areTargetsValid(t))return this;const s=this._delegatedListeners?this._delegatedListeners[e]:void 0;return s&&(e=>{for(let s=0;s<e.length;s++){const o=e[s];if(o.listener===i&&qf(o.targets,t)){for(const e in o.delegates)this.off(e,o.delegates[e]);return e.splice(s,1),this}}})(s),this}queryRenderedFeatures(e,t){if(!this.style)return[];if(void 0===e||e instanceof m||Array.isArray(e)||void 0!==t||(t=e,e=void 0),e=e||[[0,0],[this.transform.width,this.transform.height]],!t){const t=this.style.queryRenderedFeatures(e,void 0,this.transform),i=this.style.queryRenderedFeatureset(e,void 0,this.transform);return t.concat(i)}let i=!0;if(t.target&&(i=this._isTargetValid(t.target),i&&!t.layers))return this.style.queryRenderedFeatureset(e,t,this.transform);let s=!0;if(t.layers&&Array.isArray(t.layers)){for(const e of t.layers)if(!this._isValidId(e)){s=!1;break}if(s&&!t.target)return this.style.queryRenderedFeatures(e,t,this.transform)}let o=[];return s&&(o=o.concat(this.style.queryRenderedFeatures(e,t,this.transform))),i&&(o=o.concat(this.style.queryRenderedFeatureset(e,t,this.transform))),o}querySourceFeatures(e,t){return!e||"string"==typeof e&&!this._isValidId(e)?[]:this.style.querySourceFeatures(e,t)}queryRasterValue(e,t,i){return this._isValidId(e)?this.style.queryRasterValue(e,t,i):Promise.resolve(null)}isPointOnSurface(e){const{name:t}=this.transform.projection;return"globe"!==t&&"mercator"!==t&&_(`${t} projection does not support isPointOnSurface, this API may behave unexpectedly.`),this.transform.isPointOnSurface(m.convert(e))}addInteraction(e,t){return this._interactions.add(e,t),this}removeInteraction(e){return this._interactions.remove(e),this}getCooperativeGestures(){return this._cooperativeGestures}setCooperativeGestures(e){return this._cooperativeGestures=e,this}setStyle(e,t){return t={localIdeographFontFamily:this._localIdeographFontFamily,localFontFamily:this._localFontFamily,fontstackCompositing:this._fontstackCompositing,...t},this.style&&e&&!1!==t.diff&&t.localFontFamily===this._localFontFamily&&t.localIdeographFontFamily===this._localIdeographFontFamily&&t.fontstackCompositing===this._fontstackCompositing&&!t.config?(this.style._diffStyle(e,(i,s)=>{if(i){const s="string"==typeof i?i:i instanceof Error?i.message:i.error;_(`Unable to perform style diff: ${s}. Rebuilding the style from scratch.`),this._updateStyle(e,t)}else s&&this._update(!0)},()=>this._postStyleLoadEvent()),this):(this._localIdeographFontFamily=t.localIdeographFontFamily,this._localFontFamily=t.localFontFamily,this._fontstackCompositing=t.fontstackCompositing,this._updateStyle(e,t))}_getUIString(e){const t=this._locale[e];if(null==t)throw new Error(`Missing UI string '${e}'`);return t}_updateStyle(e,t){if(this.style&&(this.style.setEventedParent(null),this.style._remove(),this.style=void 0),e){const i={...t};t&&t.config&&(i.initialConfig=t.config,delete i.config),this.style=new Nd(this,i).load(e),this.style.setEventedParent(this,{style:this.style})}return this._updateTerrain(),this}_lazyInitEmptyStyle(){this.style||(this.style=new Nd(this,{}),this.style.setEventedParent(this,{style:this.style}),this.style.loadEmpty())}getStyle(){if(this.style)return this.style.serialize()}isStyleLoaded(){return this.style?this.style.loaded():(_("There is no style added to the map."),!1)}_isValidId(e){return null==e?(this.fire(new P(new Error("IDs can't be empty."))),!1):es(e)?(this.fire(new P(new Error(`IDs can't contain special symbols: "${e}".`))),!1):"__proto__"!==e&&"constructor"!==e&&"prototype"!==e||(this.fire(new P(new Error(`IDs can't be "${e}".`))),!1)}_isTargetValid(e){return"featuresetId"in e?this._isValidId("importId"in e?e.importId:e.featuresetId):"layerId"in e&&this._isValidId(e.layerId)}_areTargetsValid(e){if(Array.isArray(e)){for(const t of e)if(!this._isValidId(t))return!1;return!0}return this._isTargetValid(e)}addSource(e,t){return this._isValidId(e)?(this._lazyInitEmptyStyle(),this.style.addSource(e,t),this._update(!0)):this}isSourceLoaded(e){return!!this._isValidId(e)&&!!this.style&&this.style._isSourceCacheLoaded(e)}areTilesLoaded(){return this.style.areTilesLoaded()}removeSource(e){return this._isValidId(e)?(this.style.removeSource(e),this._updateTerrain(),this._update(!0)):this}getSource(e){return this._isValidId(e)?this.style.getOwnSource(e):null}addImage(e,t,{pixelRatio:i=1,sdf:s=!1,stretchX:o,stretchY:r,content:n}={}){this._lazyInitEmptyStyle();const a=g.from(e);if(t instanceof HTMLImageElement||ImageBitmap&&t instanceof ImageBitmap){const{width:e,height:l,data:c}=T.getImageData(t);this.style.addImage(a,{data:new E({width:e,height:l},c),pixelRatio:i,stretchX:o,stretchY:r,content:n,sdf:s,version:0,usvg:!1})}else if(void 0===t.width||void 0===t.height)this.fire(new P(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));else{const{width:l,height:c}=t,h=t;this.style.addImage(a,{data:new E({width:l,height:c},new Uint8Array(h.data)),pixelRatio:i,stretchX:o,stretchY:r,content:n,sdf:s,usvg:!1,version:0,userImage:h}),h.onAdd&&h.onAdd(this,e)}}updateImage(e,t){this._lazyInitEmptyStyle();const i=g.from(e),s=this.style.getImage(i);if(!s)return void this.fire(new P(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));const o=t instanceof HTMLImageElement||ImageBitmap&&t instanceof ImageBitmap?T.getImageData(t):t,{width:r,height:n,data:a}=o;if(void 0===r||void 0===n)return void this.fire(new P(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(r!==(s.usvg?s.icon.usvg_tree.width:s.data.width)||n!==(s.usvg?s.icon.usvg_tree.height:s.data.height))return void this.fire(new P(new Error(`The width and height of the updated image (${r}, ${n})\n must be that same as the previous version of the image\n (${s.data.width}, ${s.data.height})`)));const l=!(t instanceof HTMLImageElement||ImageBitmap&&t instanceof ImageBitmap);let c=!1;s.usvg?(s.data=new E({width:r,height:n},new Uint8Array(a)),s.usvg=!1,s.icon=void 0,c=!0):s.data.replace(a,l),this.style.updateImage(i,s,c)}hasImage(e){return e?!!this.style&&!!this.style.getImage(g.from(e)):(this.fire(new P(new Error("Missing required image id"))),!1)}removeImage(e){this.style.removeImage(g.from(e))}loadImage(e,t){(async()=>{const t=await this._requestManager.transformRequest(e,x.Image),{data:i}=await w(t);return i})().then(e=>t(null,e)).catch(t)}listImages(){return this.style.listImages().map(e=>e.name)}addModel(e,t){this._lazyInitEmptyStyle(),this.style.addModel(e,t)}hasModel(e){return e?this.style.hasModel(e):(this.fire(new P(new Error("Missing required model id"))),!1)}removeModel(e){this.style.removeModel(e)}listModels(){return this.style.listModels()}addLayer(e,t){return this._isValidId(e.id)?(this._lazyInitEmptyStyle(),this.style.addLayer(e,t),this._update(!0)):this}getSlot(e){const t=this.getLayer(e);return t&&t.slot||null}setSlot(e,t){return this.style.setSlot(e,t),this.style.mergeLayers(),this._update(!0)}addImport(e,t){return this._isValidId(e.id)?(this.style.addImport(e,t).catch(e=>this.fire(new P(new Error("Failed to add import",e)))),this):this}updateImport(e,t){return"string"!=typeof t&&t.id!==e?(this.removeImport(e),this.addImport(t)):(this.style.updateImport(e,t),this._update(!0))}removeImport(e){const t=this.style._getRasterMaskUser(e,"import");return t?(this.fire(new P(new Error(`Import "${e}" cannot be removed while layer "${t}" uses it in "raster-mask-import".`))),this):(this.style.removeImport(e),this)}moveImport(e,t){return this.style.moveImport(e,t),this._update(!0)}moveLayer(e,t){return this._isValidId(e)?(this.style.moveLayer(e,t),this._update(!0)):this}removeLayer(e){if(!this._isValidId(e))return this;const t=this.style._getRasterMaskUser(e,"layer");return t?(this.fire(new P(new Error(`Layer "${e}" cannot be removed while layer "${t}" uses it in "raster-mask".`))),this):(this.style.removeLayer(e),this._update(!0))}getLayer(e){if(!this._isValidId(e))return null;const t=this.style.getOwnLayer(e);return t?"custom"===t.type?t.implementation:t.serialize():void 0}getSlots(){return this.style.getSlots()}setLayerZoomRange(e,t,i){return this._isValidId(e)?(this.style.setLayerZoomRange(e,t,i),this._update(!0)):this}setFilter(e,t,i={}){return this._isValidId(e)?(this.style.setFilter(e,t,i),this._update(!0)):this}getFilter(e){return this._isValidId(e)?this.style.getFilter(e):null}setPaintProperty(e,t,i,s={}){return this._isValidId(e)?(this.style.setPaintProperty(e,t,i,s),this._update(!0)):this}getPaintProperty(e,t){return this._isValidId(e)?this.style.getPaintProperty(e,t):null}setLayoutProperty(e,t,i,s={}){return this._isValidId(e)?(this.style.setLayoutProperty(e,t,i,s),this._update(!0)):this}getLayoutProperty(e,t){return this._isValidId(e)?this.style.getLayoutProperty(e,t):null}getLayerProperty(e,t){return this._isValidId(e)?this.style.getLayerProperty(e,t):null}setLayerProperty(e,t,i,s={}){return this._isValidId(e)?("appearances"===t&&this._postAddingAppearancesToStyleEvent(),this.style.setLayerProperty(e,t,i,s),this._update(!0)):this}getGlyphsUrl(){return this.style.getGlyphsUrl()}setGlyphsUrl(e){return this.style.setGlyphsUrl(e),this._update(!0)}getSchema(e){return this.style.getSchema(e)}setSchema(e,t){return this.style.setSchema(e,t),this._update(!0)}getConfig(e){return this.style.getConfig(e)}setConfig(e,t){return this.style.setConfig(e,t),this._update(!0)}getConfigProperty(e,t){return this.style.getConfigProperty(e,t)}setConfigProperty(e,t,i){return this.style.setConfigProperty(e,t,i),this._update(!0)}getFeaturesetDescriptors(e){return this.style.getFeaturesetDescriptors(e)}setLights(e){if(this._lazyInitEmptyStyle(),e&&1===e.length&&"flat"===e[0].type){const t=e[0];t.properties?this.style.setFlatLight(t.properties,t.id,{}):this.style.setFlatLight({},"flat")}else this.style.setLights(e),this.painter.terrain&&(this.painter.terrain.invalidateRenderCache=!0);return this._update(!0)}getLights(){const e=this.style.getLights()||[];return 0===e.length&&e.push({id:this.style.light.id,type:"flat",properties:this.style.getFlatLight()}),e}setLight(e,t={}){return console.log("The `map.setLight` function is deprecated, prefer using `map.setLights` with `flat` light type instead."),this.setLights([{id:"flat",type:"flat",properties:e}])}getLight(){return console.log("The `map.getLight` function is deprecated, prefer using `map.getLights` instead."),this.style.getFlatLight()}setTerrain(e){return this._lazyInitEmptyStyle(),!e&&this.transform.projection.requiresDraping?this.style.setTerrainForDraping():this.style.setTerrain(e),this._averageElevationLastSampledAt=-1/0,this._update(!0)}getTerrain(){return this.style?this.style.getTerrain():null}setFog(e){return this._lazyInitEmptyStyle(),this.style.setFog(e),this._update(!0)}getFog(){return this.style?this.style.getFog():null}setSnow(e){return this._lazyInitEmptyStyle(),this.style.setSnow(e),this._update(!0)}getSnow(){return this.style?this.style.getSnow():null}setRain(e){return this._lazyInitEmptyStyle(),this.style.setRain(e),this._update(!0)}getRain(){return this.style?this.style.getRain():null}setColorTheme(e){return this._lazyInitEmptyStyle(),this.style.setColorTheme(e),this._update(!0)}setImportColorTheme(e,t){return this._lazyInitEmptyStyle(),this.style.setImportColorTheme(e,t),this._update(!0)}setCamera(e){return this.style.setCamera(e),this._triggerCameraUpdate(e)}getNearClipOffset(){return this.transform.nearClipOffset}setNearClipOffset(e){const t=this.transform.nearClipOffset!==e;return this.transform.nearClipOffset=e,this._update(t)}_triggerCameraUpdate(e){return this._update(this.transform.setOrthographicProjectionAtLowPitch("orthographic"===e["camera-projection"]))}getCamera(){return this.style.camera}_queryFogOpacity(e){return this.style&&this.style.fog?this.style.fog.getOpacityAtLatLng(Es.convert(e),this.transform):0}setFeatureState(e,t){return e.source&&!this._isValidId(e.source)?this:(this.style.setFeatureState(e,t),this._update())}removeFeatureState(e,t){return e.source&&!this._isValidId(e.source)?this:(this.style.removeFeatureState(e,t),this._update())}getFeatureState(e){return e.source&&!this._isValidId(e.source)?null:this.style.getFeatureState(e)}resetFeatureStates(e){return this.style.resetFeatureStates(e),this._update()}_selectIndoorFloor(e){this.style.indoorManager&&this.style.indoorManager.selectFloor(e)}_setIndoorActiveFloorsVisibility(e){this.style.indoorManager&&this.style.indoorManager.setActiveFloorsVisibility(e)}getIndoorTileOptions(e,t){return this.style&&this.style.isIndoorEnabled()&&this.style.indoorManager?this.style.indoorManager.getIndoorTileOptions(e,t):null}_updateContainerDimensions(){if(!this._container)return;const e=this._container.getBoundingClientRect().width||400,t=this._container.getBoundingClientRect().height||300;let i,s,o,r=this._container;for(;r&&(!s||!o);){const e=window.getComputedStyle(r).transform;e&&"none"!==e&&(i=e.match(Zf)[1].split(", "),i[0]&&"0"!==i[0]&&"1"!==i[0]&&(s=i[0]),i[3]&&"0"!==i[3]&&"1"!==i[3]&&(o=i[3])),r=r.parentElement}this._containerWidth=s?Math.abs(e/s):e,this._containerHeight=o?Math.abs(t/o):t}_detectMissingCSS(){"rgb(250, 128, 114)"!==window.getComputedStyle(this._missingCSSCanary).getPropertyValue("background-color")&&_("This page appears to be missing CSS declarations for Mapbox GL JS, which may cause the map to display incorrectly. Please ensure your page includes mapbox-gl.css, as described in https://www.mapbox.com/mapbox-gl-js/api/.")}_setupContainer(){const e=this._container;e.classList.add("mapboxgl-map"),(this._missingCSSCanary=Tn("div","mapboxgl-canary",e)).style.visibility="hidden",this._detectMissingCSS();const t=this._canvasContainer=Tn("div","mapboxgl-canvas-container",e);this._canvas=Tn("canvas","mapboxgl-canvas",t),this._interactive&&(t.classList.add("mapboxgl-interactive"),this._canvas.setAttribute("tabindex","0")),this._canvas.addEventListener("webglcontextlost",this._contextLost,!1),this._canvas.addEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.setAttribute("aria-label",this._getUIString("Map.Title")),this._canvas.setAttribute("role","region"),this._updateContainerDimensions(),this._resizeCanvas(this._containerWidth,this._containerHeight);const i=this._controlContainer=Tn("div","mapboxgl-control-container",e),s=this._controlPositions={};["top-left","top","top-right","right","bottom-right","bottom","bottom-left","left"].forEach(e=>{s[e]=Tn("div",`mapboxgl-ctrl-${e}`,i)}),this._container.addEventListener("scroll",this._onMapScroll,!1)}_resizeCanvas(e,t){const i=T.devicePixelRatio||1;this._canvas.width=i*Math.ceil(e),this._canvas.height=i*Math.ceil(t),this._canvas.style.width=`${e}px`,this._canvas.style.height=`${t}px`}_addMarker(e){this._markers.push(e)}_removeMarker(e){const t=this._markers.indexOf(e);-1!==t&&this._markers.splice(t,1)}_addPopup(e){this._popups.push(e)}_removePopup(e){const t=this._popups.indexOf(e);-1!==t&&this._popups.splice(t,1)}_setupPainter(){const e={...gn,failIfMajorPerformanceCaveat:this._failIfMajorPerformanceCaveat,preserveDrawingBuffer:this._preserveDrawingBuffer,antialias:this._antialias||!1},t=this._canvas.getContext("webgl2",e);t?(fn(t,!0),this.painter=new Cp(t,this._contextCreateOptions,this.transform,this._scaleFactor,this._worldview,this._emissiveColorPrecision),this.on("data",e=>{if("source"===e.dataType){const t=this.transform.elevation?this.transform.elevation._source():null;t&&e.sourceCacheId===t.id&&this.style&&this.style._setLabelPlacementStale(),this.style&&e.sourceCacheId&&this.style._buildingIndex.hasLayerForSourceCache(e.sourceCacheId)&&this.style._requestFullLabelPlacement(),this.painter.setTileLoadedFlag(!0)}})):this.fire(new P(new Error("Failed to initialize WebGL")))}_contextLost(e){e.preventDefault(),this._frame&&(this._frame.cancel(),this._frame=null),this.style&&this.style.handleContextLost(),this.fire(new M("webglcontextlost",{originalEvent:e}))}_contextRestored(e){this._setupPainter(),this.painter.resize(Math.ceil(this._containerWidth),Math.ceil(this._containerHeight)),this._updateTerrain(),this.style&&(this.style.clearLayers(),this.style.imageManager.destroyAtlasTextures(),this.style.imageManager.imageAtlasCache.clear(),this.style.reloadModels(),this.style.clearSources()),this._update(),this.fire(new M("webglcontextrestored",{originalEvent:e}))}_onMapScroll(e){if(e.target===this._container)return this._container.scrollTop=0,this._container.scrollLeft=0,!1}idle(){return!this.isMoving()&&this.loaded()}loaded(){return!this._styleDirty&&!this._sourcesDirty&&!!this.style&&this.style.loaded()}frameReady(){return this.loaded()&&!this._placementDirty}_update(e){return this.style?(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)}_requestDomTask(e){!this.loaded()||this.loaded()&&!this.isMoving()?e():this._domRenderTaskQueue.add(e)}_render(e){let t;this.fire(new M("renderstart")),++this._frameId;const i=this.painter.context.extTimerQuery,s=T.now(),o=this.painter.context.gl;if(this.listens("gpu-timing-frame")&&(t=o.createQuery(),o.beginQuery(i.TIME_ELAPSED_EXT,t)),this.painter.context.setDirty(),this.painter.setBaseState(),(this.isMoving()||this.isRotating()||this.isZooming())&&(this._interactionRange[0]=Math.min(this._interactionRange[0],performance.now()),this._interactionRange[1]=Math.max(this._interactionRange[1],performance.now())),this._renderTaskQueue.run(e),this._domRenderTaskQueue.run(e),this._removed)return;this._updateProjectionTransition();const r=this._isInitialLoad?0:this._fadeDuration;if(this.style&&this._styleDirty){this._styleDirty=!1;const e=this.transform.zoom,t=this.transform.pitch,i=T.now(),s=new X(e,{now:i,fadeDuration:r,pitch:t,transition:this._loaded?this.style.transition:{duration:0,delay:0},worldview:this._worldview});this.style.update(s)}this.style&&this.style.hasFogTransition()&&(this.style._markersNeedUpdate=!0,this._sourcesDirty=!0);let n=!1;if(this.style&&this._sourcesDirty?(this._sourcesDirty=!1,this.painter._updateFog(this.style),this._updateTerrain(),n=this._updateAverageElevation(s),this.style.updateSources(this.transform),this.style.updateImageProviders(),this.isMoving()||this._forceMarkerAndPopupUpdate()):n=this._updateAverageElevation(s),this.style){const e=this._staticMode&&!this.style.loaded();this._placementDirty=e||this.style._updatePlacement(this.painter.transform,this.showCollisionBoxes,r,this._crossSourceCollisions,this.painter.replacementSource,this._placementAlgorithm)}if(!this.style||this.transform.projection.requiresDraping&&!Al.loaded||this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showParseStatus:this.showParseStatus,wireframe:{terrain:this.showTerrainWireframe,layers2D:this.showLayers2DWireframe,layers3D:this.showLayers3DWireframe},showOverdrawInspector:this._showOverdrawInspector,showQueryGeometry:!!this._showQueryGeometry,showTileAABBs:this.showTileAABBs,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:r,isInitialLoad:this._isInitialLoad,showPadding:this.showPadding,gpuTiming:!!this.listens("gpu-timing-layer"),gpuTimingDeferredRender:!!this.listens("gpu-timing-deferred-render"),speedIndexTiming:this.speedIndexTiming,paintStartTimeStamp:e}),this.fire(new M("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,Pr.mark(Lr.load),this.fire(new M("load"))),this.style&&this.style.hasTransitions()&&(this._styleDirty=!0),this.style&&this.style.imageManager.hasPatternsInFlight()&&(this._styleDirty=!0),this.style&&!this._placementDirty&&this.style._releaseSymbolFadeTiles(),t){const e=T.now()-s;o.endQuery(i.TIME_ELAPSED_EXT),setTimeout(()=>{const i=o.getQueryParameter(t,o.QUERY_RESULT)/1e6;o.deleteQuery(t),this.fire(new M("gpu-timing-frame",{cpuTime:e,gpuTime:i}))},50)}if(this.listens("gpu-timing-layer")){const e=this.painter.collectGpuTimers();setTimeout(()=>{const t=this.painter.queryGpuTimers(e);this.fire(new M("gpu-timing-layer",{layerTimes:t}))},50)}if(this.listens("gpu-timing-deferred-render")){const e=this.painter.collectDeferredRenderGpuQueries();setTimeout(()=>{const t=this.painter.queryGpuTimeDeferredRender(e);this.fire(new M("gpu-timing-deferred-render",{gpuTime:t}))},50)}const a=this._sourcesDirty||this._styleDirty||this._placementDirty||n;if(a||this._repaint||this.style&&(this.style.snow||this.style.rain))this.triggerRepaint();else{const e=this.idle();if(e&&(n=this._updateAverageElevation(s,!0)),n)this.triggerRepaint();else{if(this._triggerFrame(!1),e&&(this.fire(new M("idle")),this._isInitialLoad=!1,this.speedIndexTiming)){const e=this._calculateSpeedIndex();this.fire(new M("speedindexcompleted",{speedIndex:e})),this.speedIndexTiming=!1}e&&this.style&&this.style.handleIdle()}}!this._loaded||this._fullyLoaded||a||(this._fullyLoaded=!0,Pr.mark(Lr.fullLoad),this._performanceMetricsCollection&&dn(this._requestManager._customAccessToken,{width:this.painter.width,height:this.painter.height,interactionRange:this._interactionRange,visibilityHidden:this._visibilityHidden,terrainEnabled:this.painter.style.hasTerrain(),fogEnabled:!!this.painter.style.getFog(),projection:this.getProjection().name,zoom:this.transform.zoom,renderer:this.painter.context.renderer,vendor:this.painter.context.vendor}),this._authenticate())}_forceMarkerAndPopupUpdate(e){for(const t of this._markers)e&&!this.getRenderWorldCopies()&&(t._lngLat=t._lngLat.wrap()),t._update();for(const t of this._popups)!e||this.getRenderWorldCopies()||t._trackPointer||(t._lngLat=t._lngLat.wrap()),t._update()}_updateAverageElevation(e,t=!1){const i=e=>(this.transform.averageElevation=e,this._update(!1),!0);if(!this.painter.averageElevationNeedsEasing())return 0!==this.transform.averageElevation&&i(0);const s=this.transform.elevation&&this.transform.elevation.exaggeration()!==this._averageElevationExaggeration;if(s||(t||e-this._averageElevationLastSampledAt>500)&&!this._averageElevation.isEasing(e)){const t=this.transform.averageElevation;let o=this.transform.sampleAverageElevation();null!=this.transform.elevation&&(this._averageElevationExaggeration=this.transform.elevation.exaggeration()),isNaN(o)?o=0:this._averageElevationLastSampledAt=e;const r=Math.abs(t-o);if(r>1){if(this._isInitialLoad||s)return this._averageElevation.jumpTo(o),i(o);this._averageElevation.easeTo(o,e,300)}else if(r>1e-4)return this._averageElevation.jumpTo(o),i(o)}return!!this._averageElevation.isEasing(e)&&i(this._averageElevation.getValue(e))}_isTokenExpired(){return null!=this._tokenExpiration&&Date.now()>this._tokenExpiration}_revokeAuth(){const e=this.painter.context.gl;fn(e,!1),this._logoControl instanceof Bf&&this._logoControl._updateLogo(),e&&e.clear(e.DEPTH_BUFFER_BIT|e.COLOR_BUFFER_BIT|e.STENCIL_BUFFER_BIT),this._silenceAuthErrors||this.fire(new P(new Error("A valid Mapbox access token is required to use Mapbox GL JS. To create an account or a new access token, visit https://account.mapbox.com/")))}_authenticate(){_n(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,e=>{e&&(e.message!==Nr&&401!==e.status||this._revokeAuth())}),this._isTokenExpired()&&this._revokeAuth(),sn(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,()=>{})}_postStyleLoadEvent(){this.style.globalId&&rn(this._requestManager._customAccessToken,{map:this,style:this.style.globalId,importedStyles:this.style.getImportGlobalIds()})}_postStyleWithAppearanceEvent(){this.style.globalId&&this.style.hasAppearances()&&an(this._requestManager._customAccessToken)}_postAddingAppearancesToStyleEvent(){cn(this._requestManager._customAccessToken)}_updateTerrain(){const e=this._isDragging();this.painter.updateTerrain(this.style,e)}_calculateSpeedIndex(){const e=this.painter.canvasCopy(),t=this.painter.getCanvasCopiesAndTimestamps();t.timeStamps.push(performance.now());const i=this.painter.context.gl,s=i.createFramebuffer();function o(e){i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,e,0);const t=new Uint8Array(i.drawingBufferWidth*i.drawingBufferHeight*4);return i.readPixels(0,0,i.drawingBufferWidth,i.drawingBufferHeight,i.RGBA,i.UNSIGNED_BYTE,t),t}return i.bindFramebuffer(i.FRAMEBUFFER,s),this._canvasPixelComparison(o(e),t.canvasCopies.map(o),t.timeStamps)}_canvasPixelComparison(e,t,i){let s=i[1]-i[0];const o=e.length/4;for(let r=0;r<t.length;r++){const n=t[r];let a=0;for(let t=0;t<n.length;t+=4)n[t]===e[t]&&n[t+1]===e[t+1]&&n[t+2]===e[t+2]&&n[t+3]===e[t+3]&&(a+=1);s+=(i[r+2]-i[r+1])*(1-a/o)}return s}remove(){if(this._removed)return;this._hash&&this._hash.remove();for(const e of this._controls)e.onRemove(this);this._controls=[],this._frame&&(this._frame.cancel(),this._frame=null),this._renderTaskQueue.clear(),this._domRenderTaskQueue.clear(),this.style&&this.style.destroy(),this.painter.destroy(),this.handlers&&this.handlers.destroy(),this.handlers=void 0,this.setStyle(null),window.removeEventListener("resize",this._onWindowResize,!1),window.removeEventListener("orientationchange",this._onWindowResize,!1),window.removeEventListener(this._fullscreenchangeEvent,this._onWindowResize,!1),window.removeEventListener("online",this._onWindowOnline,!1),window.removeEventListener("visibilitychange",this._onVisibilityChange,!1);const e=this.painter.context.gl.getExtension("WEBGL_lose_context");e&&e.loseContext(),this._canvas.removeEventListener("webglcontextlost",this._contextLost,!1),this._canvas.removeEventListener("webglcontextrestored",this._contextRestored,!1),this._canvasContainer.remove(),this._controlContainer.remove(),this._missingCSSCanary.remove(),this._canvas=void 0,this._canvasContainer=void 0,this._controlContainer=void 0,this._missingCSSCanary=void 0,this._container.classList.remove("mapboxgl-map"),this._container.removeEventListener("scroll",this._onMapScroll,!1),pn.delete(this.painter.context.gl),un.remove(),tn.remove(),this._removed=!0,this.fire(new M("remove"))}triggerRepaint(){this._triggerFrame(!0)}_triggerFrame(e){if(this._renderNextFrame=this._renderNextFrame||e,!this.style||this._frame)return;const t=this._animationFrameProvider;if(!t)return void(this._frame=T.frame(e=>{const t=!!this._renderNextFrame;this._frame=null,this._renderNextFrame=null,t&&this._render(e)}));const i=e=>{const t=!!this._renderNextFrame;this._renderNextFrame=null;try{t&&this._render(e)}finally{this._frame=null}t&&!this._removed&&Promise.resolve().then(()=>this._triggerFrame(!1))};let s=null;this._frame={cancel:()=>{null!==s&&t.cancelAnimationFrame(s)}};try{s=t.requestAnimationFrame(i)}catch(e){throw this._frame=null,e}}_preloadTiles(e){const t=this.style?this.style.getSourceCaches():[];return j(t,(t,i)=>t._preloadTiles(e,i),()=>{this.triggerRepaint()}),this}_onWindowOnline(){this._update()}_onWindowResize(e){this._trackResize&&this.resize({originalEvent:e})._update()}_onVisibilityChange(){"hidden"===document.visibilityState&&this._visibilityHidden++}get showTileBoundaries(){return!!this._showTileBoundaries}set showTileBoundaries(e){this._showTileBoundaries!==e&&(this._showTileBoundaries=e,e&&La(),this._update())}get showParseStatus(){return!!this._showParseStatus}set showParseStatus(e){this._showParseStatus!==e&&(this._showParseStatus=e,this._update())}get showTerrainWireframe(){return!!this._showTerrainWireframe}set showTerrainWireframe(e){this._showTerrainWireframe!==e&&(this._showTerrainWireframe=e,this._update())}get showLayers2DWireframe(){return!!this._showLayers2DWireframe}set showLayers2DWireframe(e){this._showLayers2DWireframe!==e&&(this._showLayers2DWireframe=e,this._update())}get showLayers3DWireframe(){return!!this._showLayers3DWireframe}set showLayers3DWireframe(e){this._showLayers3DWireframe!==e&&(this._showLayers3DWireframe=e,this._update())}get showElevationIdDebug(){return!!this.painter&&this.painter._debugParams.showElevationIdDebug}set showElevationIdDebug(e){this.painter&&this.painter._debugParams.showElevationIdDebug!==e&&(this.painter._debugParams.showElevationIdDebug=e,this.style&&e?this.style._reloadSources():this._update())}get speedIndexTiming(){return!!this._speedIndexTiming}set speedIndexTiming(e){this._speedIndexTiming!==e&&(this._speedIndexTiming=e,this._update())}get showPadding(){return!!this._showPadding}set showPadding(e){this._showPadding!==e&&(this._showPadding=e,e&&La(),this._update())}get showCollisionBoxes(){return!!this._showCollisionBoxes}set showCollisionBoxes(e){this._showCollisionBoxes!==e&&(this._showCollisionBoxes=e,e&&La(),this.style&&e?this.style._reloadSources():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 showTileAABBs(){return!!this._showTileAABBs}set showTileAABBs(e){this._showTileAABBs!==e&&(this._showTileAABBs=e,e&&this._update())}_setCacheLimits(e,t){Ir(e,t)}get version(){return Cr}};const $f={showCompass:!0,showZoom:!0,visualizePitch:!1};class Xf{constructor(e={}){this.options={...$f,...e},this._container=Tn("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.addEventListener("contextmenu",e=>e.preventDefault()),this.options.showZoom&&(rt(["_setButtonTitle","_updateZoomButtons"],this),this._zoomInButton=this._createButton("mapboxgl-ctrl-zoom-in",e=>{this._map&&this._map.zoomIn({},{originalEvent:e})}),Tn("span","mapboxgl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true"),this._zoomOutButton=this._createButton("mapboxgl-ctrl-zoom-out",e=>{this._map&&this._map.zoomOut({},{originalEvent:e})}),Tn("span","mapboxgl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(rt(["_rotateCompassArrow"],this),this._compass=this._createButton("mapboxgl-ctrl-compass",e=>{const t=this._map;t&&(this.options.visualizePitch?t.resetNorthPitch({},{originalEvent:e}):t.resetNorth({},{originalEvent:e}))}),this._compassIcon=Tn("span","mapboxgl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"))}_updateZoomButtons(){const e=this._map;if(!e)return;const t=e.getZoom(),i=t===e.getMaxZoom(),s=t===e.getMinZoom();this._zoomInButton.disabled=i,this._zoomOutButton.disabled=s,this._zoomInButton.setAttribute("aria-disabled",i.toString()),this._zoomOutButton.setAttribute("aria-disabled",s.toString())}_rotateCompassArrow(){const e=this._map;if(!e)return;const t=this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(e.transform.pitch*(Math.PI/180)),.5)}) rotateX(${e.transform.pitch}deg) rotateZ(${e.transform.angle*(180/Math.PI)}deg)`:`rotate(${e.transform.angle*(180/Math.PI)}deg)`;e._requestDomTask(()=>{this._compassIcon&&(this._compassIcon.style.transform=t)})}onAdd(e){return this._map=e,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),e.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&e.on("pitch",this._rotateCompassArrow),e.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new Yf(e,this._compass,this.options.visualizePitch)),this._container}onRemove(){const e=this._map;e&&(this._container.remove(),this.options.showZoom&&e.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&e.off("pitch",this._rotateCompassArrow),e.off("rotate",this._rotateCompassArrow),this._handler&&this._handler.off(),this._handler=void 0),this._map=void 0)}_createButton(e,t){const i=Tn("button",e,this._container);return i.type="button",i.addEventListener("click",t),i}_setButtonTitle(e,t){if(!this._map)return;const i=this._map._getUIString(`NavigationControl.${t}`);e.setAttribute("aria-label",i),e.firstElementChild&&e.firstElementChild.setAttribute("title",i)}}class Yf{constructor(e,t,i=!1){this._clickTolerance=10,this.element=t,this.mouseRotate=new rf({clickTolerance:e.dragRotate._mouseRotate._clickTolerance}),this.map=e,i&&(this.mousePitch=new nf({clickTolerance:e.dragRotate._mousePitch._clickTolerance})),rt(["mousedown","mousemove","mouseup","touchstart","touchmove","touchend","reset"],this),t.addEventListener("mousedown",this.mousedown),t.addEventListener("touchstart",this.touchstart,{passive:!1}),t.addEventListener("touchmove",this.touchmove),t.addEventListener("touchend",this.touchend),t.addEventListener("touchcancel",this.reset)}down(e,t){this.mouseRotate.mousedown(e,t),this.mousePitch&&this.mousePitch.mousedown(e,t),Rn()}move(e,t){const i=this.map,s=this.mouseRotate.mousemoveWindow(e,t),o=s&&s.bearingDelta;if(o&&i.setBearing(i.getBearing()+o),this.mousePitch){const s=this.mousePitch.mousemoveWindow(e,t),o=s&&s.pitchDelta;o&&i.setPitch(i.getPitch()+o)}}off(){const e=this.element;e.removeEventListener("mousedown",this.mousedown),e.removeEventListener("touchstart",this.touchstart),e.removeEventListener("touchmove",this.touchmove),e.removeEventListener("touchend",this.touchend),e.removeEventListener("touchcancel",this.reset),this.offTemp()}offTemp(){Cn(),window.removeEventListener("mousemove",this.mousemove),window.removeEventListener("mouseup",this.mouseup)}mousedown(e){this.down({...e,button:e.button,type:e.type,ctrlKey:!0,preventDefault:()=>e.preventDefault()},Pn(this.element,e)),window.addEventListener("mousemove",this.mousemove),window.addEventListener("mouseup",this.mouseup)}mousemove(e){this.move(e,Pn(this.element,e))}mouseup(e){this.mouseRotate.mouseupWindow(e),this.mousePitch&&this.mousePitch.mouseupWindow(e),this.offTemp()}touchstart(e){1!==e.targetTouches.length?this.reset():(this._startPos=this._lastPos=Mn(this.element,e.targetTouches)[0],this.down({type:"mousedown",button:0,ctrlKey:!0,preventDefault:()=>e.preventDefault()},this._startPos))}touchmove(e){1!==e.targetTouches.length?this.reset():(this._lastPos=Mn(this.element,e.targetTouches)[0],this.move({buttons:1,preventDefault:()=>e.preventDefault()},this._lastPos))}touchend(e){0===e.targetTouches.length&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos)<this._clickTolerance&&this.element.click(),this.reset()}reset(){this.mouseRotate.reset(),this.mousePitch&&this.mousePitch.reset(),delete this._startPos,delete this._lastPos,this.offTemp()}}function Kf(e,t,i){if(e=new Es(e.lng,e.lat),t){const s=new Es(e.lng-360,e.lat),o=new Es(e.lng+360,e.lat),r=360*Math.ceil(Math.abs(e.lng-i.center.lng)/360),n=i.locationPoint3D(e).distSqr(t),a=t.x<0||t.y<0||t.x>i.width||t.y>i.height;i.locationPoint3D(s).distSqr(t)<n&&(a||Math.abs(s.lng-i.center.lng)<r)?e=s:i.locationPoint3D(o).distSqr(t)<n&&(a||Math.abs(o.lng-i.center.lng)<r)&&(e=o)}for(;Math.abs(e.lng-i.center.lng)>180;){const t=i.locationPoint3D(e);if(t.x>=0&&t.y>=0&&t.x<=i.width&&t.y<=i.height)break;e.lng>i.center.lng?e.lng-=360:e.lng+=360}return e}const Jf={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%)"},Qf=/\s+/,em={rotation:0,rotationAlignment:"auto",pitchAlignment:"auto",occludedOpacity:.2,altitude:0};class tm extends A{constructor(e,t){super(),(e instanceof HTMLElement||t)&&(e={element:e,...t}),rt(["_update","_onMove","_onUp","_addDragHandler","_onMapClick","_onKeyPress","_clearFadeTimer"],this);const{anchor:i="center",color:s="#3FB1CE",scale:o=1,draggable:r=!1,clickTolerance:n=0,rotation:a=em.rotation,rotationAlignment:l=em.rotationAlignment,pitchAlignment:c=em.pitchAlignment,occludedOpacity:h=em.occludedOpacity,altitude:d=em.altitude}=e||{};this._anchor=i,this._color=s,this._scale=o,this._draggable=r,this._clickTolerance=n,this._rotation=a,this._rotationAlignment=l,this._pitchAlignment=c,this._occludedOpacity=h,this._altitude=d,this._state="inactive",this._isDragging=!1,this._pointerEvents=null,this._updateMoving=()=>this._update(!0),e&&e.element?(this._element=e.element,this._offset=m.convert(e&&e.offset||[0,0])):(this._defaultMarker=!0,this._element=this._createDefaultMarker(),this._offset=m.convert(e&&e.offset||[0,-14])),this._element.hasAttribute("aria-label")||this._element.setAttribute("aria-label","Map marker"),this._element.hasAttribute("role")||this._element.setAttribute("role","img"),this._element.classList.add("mapboxgl-marker"),this._element.addEventListener("dragstart",e=>{e.preventDefault()}),this._element.addEventListener("mousedown",e=>{e.preventDefault()});const u=this._element.classList;for(const e in Jf)u.remove(`mapboxgl-marker-anchor-${e}`);u.add(`mapboxgl-marker-anchor-${this._anchor}`),e&&e.className&&u.add(...e.className.trim().split(Qf)),this._popup=null}_createDefaultMarker(){const e=Tn("div"),t=En("svg",{display:"block",height:41*this._scale+"px",width:27*this._scale+"px",viewBox:"0 0 27 41"},e);this._svgElement=t;const i=En("radialGradient",{id:"shadowGradient"},En("defs",{},t));En("stop",{offset:"10%","stop-opacity":.4},i),En("stop",{offset:"100%","stop-opacity":.05},i);const s=En("ellipse",{cx:13.5,cy:34.8,rx:10.5,ry:5.25,fill:"url(#shadowGradient)"});return this._shadowElement=s,0===this._altitude&&t.insertBefore(s,t.firstChild),En("path",{fill:this._color,d:"M27,13.5C27,19.07 20.25,27 14.75,34.5C14.02,35.5 12.98,35.5 12.25,34.5C6.75,27 0,19.22 0,13.5C0,6.04 6.04,0 13.5,0C20.96,0 27,6.04 27,13.5Z"},t),En("path",{opacity:.25,d:"M13.5,0C6.04,0 0,6.04 0,13.5C0,19.22 6.75,27 12.25,34.5C13,35.52 14.02,35.5 14.75,34.5C20.25,27 27,19.07 27,13.5C27,6.04 20.96,0 13.5,0ZM13.5,1C20.42,1 26,6.58 26,13.5C26,15.9 24.5,19.18 22.22,22.74C19.95,26.3 16.71,30.14 13.94,33.91C13.74,34.18 13.61,34.32 13.5,34.44C13.39,34.32 13.26,34.18 13.06,33.91C10.28,30.13 7.41,26.31 5.02,22.77C2.62,19.23 1,15.95 1,13.5C1,6.58 6.58,1 13.5,1Z"},t),En("circle",{fill:"white",cx:13.5,cy:13.5,r:5.5},t),e}addTo(e){return e===this._map||(this.remove(),this._map=e,e.getCanvasContainer().appendChild(this._element),e.on("move",this._updateMoving),e.on("moveend",this._update),e.on("remove",this._clearFadeTimer),e._addMarker(this),this.setDraggable(this._draggable),this._update(),e.on("click",this._onMapClick)),this}remove(){const e=this._map;return e&&(e.off("click",this._onMapClick),e.off("move",this._updateMoving),e.off("moveend",this._update),e.off("mousedown",this._addDragHandler),e.off("touchstart",this._addDragHandler),e.off("mouseup",this._onUp),e.off("touchend",this._onUp),e.off("mousemove",this._onMove),e.off("touchmove",this._onMove),e.off("remove",this._clearFadeTimer),e._removeMarker(this),this._map=void 0),this._clearFadeTimer(),this._element.remove(),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(e){return this._lngLat=Es.convert(e),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(!0),this}setAltitude(e){if(e===this._altitude)return this;const t=this._altitude;return this._altitude=e||em.altitude,this._defaultMarker&&0===t!=(0===this._altitude)&&(0===this._altitude?this._svgElement.insertBefore(this._shadowElement,this._svgElement.firstChild):this._shadowElement.remove()),this._update(),this}getAltitude(){return this._altitude}getElement(){return this._element}setPopup(e){if(this._popup&&(this._popup.remove(),this._popup=null,this._element.removeAttribute("role"),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,s=Math.sqrt(Math.pow(i,2)/2);e.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-t],"bottom-left":[s,-1*(t-i+s)],"bottom-right":[-s,-1*(t-i+s)],left:[i,-1*(t-i)],right:[-i,-1*(t-i)]}:this._offset}this._popup=e,e._marker=this,e._altitude=this._altitude,this._lngLat&&this._popup.setLngLat(this._lngLat),this._element.setAttribute("role","button"),this._originalTabIndex=this._element.getAttribute("tabindex"),this._originalTabIndex||this._element.setAttribute("tabindex","0"),this._element.addEventListener("keypress",this._onKeyPress),this._element.setAttribute("aria-expanded","false")}return this}_onKeyPress(e){const t=e.code,i=e.charCode||e.keyCode;"Space"!==t&&"Enter"!==t&&32!==i&&13!==i||this.togglePopup()}_onMapClick(e){const t=e.originalEvent.target,i=this._element;this._popup&&(t===i||i.contains(t))&&this.togglePopup()}getPopup(){return this._popup}togglePopup(){const e=this._popup;return e?(e.isOpen()?(e.remove(),this._element.setAttribute("aria-expanded","false")):this._map&&(e.addTo(this._map),this._element.setAttribute("aria-expanded","true")),this):this}_behindTerrain(){const e=this._map,t=this._pos;if(!e||!t)return!1;const i=e.unproject(t,this._altitude),s=e.getFreeCameraOptions();if(!s.position)return!1;const o=s.position.toLngLat();return o.distanceTo(i)<.9*o.distanceTo(this._lngLat)}_evaluateOpacity(){const e=this._map;if(!e)return;const t=this._pos;if(!t||t.x<0||t.x>e.transform.width||t.y<0||t.y>e.transform.height)return void this._clearFadeTimer();const i=e.unproject(t,this._altitude);let s;e._showingGlobe()&&Sr(e.transform,this._lngLat)?s=0:(s=1-e._queryFogOpacity(i),e.transform._terrainEnabled()&&e.style&&e.style.hasTerrain()&&this._behindTerrain()&&(s*=this._occludedOpacity)),this._element.style.opacity=`${s}`;const o=this._element.style.pointerEvents;(null===this._pointerEvents?""===o:o===this._pointerEvents)&&(this._pointerEvents=s>0?"auto":"none",this._element.style.pointerEvents=this._pointerEvents),this._popup&&this._popup._setOpacity(s),this._fadeTimer=null}_clearFadeTimer(){this._fadeTimer&&(clearTimeout(this._fadeTimer),this._fadeTimer=null)}_updateDOM(){const e=this._pos;if(!e||!this._map)return;const t=this._offset.mult(this._scale);this._element.style.transform=`\n translate(${e.x}px,${e.y}px)\n ${Jf[this._anchor]}\n ${this._calculateXYTransform()} ${this._calculateZTransform()}\n translate(${t.x}px,${t.y}px)\n `}_calculateXYTransform(){const e=this._pos,t=this._map,i=this.getPitchAlignment();if(!t||!e||"map"!==i)return"";if(!t._showingGlobe()){const e=t.getPitch();return e?`rotateX(${e}deg)`:""}const s=Ss(Dr(t.transform,this._lngLat)),o=e.sub(Rr(t.transform)),r=Math.abs(o.x)+Math.abs(o.y);if(0===r)return"";const n=s/r;return`rotateX(${-o.y*n}deg) rotateY(${o.x*n}deg)`}_calculateZTransform(){const e=this._pos,t=this._map;if(!t||!e)return"";let i=0;const s=this.getRotationAlignment();if("map"===s)if(t._showingGlobe()){const e=t.project(new Es(this._lngLat.lng,this._lngLat.lat+.001),this._altitude),s=t.project(new Es(this._lngLat.lng,this._lngLat.lat-.001),this._altitude).sub(e);i=Ss(Math.atan2(s.y,s.x))-90}else i=-t.getBearing();else if("horizon"===s){const s=Q(4,6,t.getZoom()),o=Rr(t.transform);o.y+=s*t.transform.height;const r=e.sub(o),n=Ss(Math.atan2(r.y,r.x));i=(n>90?n-270:n+90)*(1-s)}return i+=this._rotation,i?`rotateZ(${i}deg)`:""}_update(e){cancelAnimationFrame(this._updateFrameId);const t=this._map;t&&(t.transform.renderWorldCopies&&(this._lngLat=Kf(this._lngLat,this._pos,t.transform)),this._pos=t.project(this._lngLat,this._altitude),!0===e?this._updateFrameId=requestAnimationFrame(()=>{this._element&&this._pos&&this._anchor&&(this._pos=this._pos.round(),this._updateDOM())}):this._pos=this._pos.round(),t._requestDomTask(()=>{this._map&&(this._element&&this._pos&&this._anchor&&this._updateDOM(),(t._showingGlobe()||t.style&&t.style.hasTerrain()||t.getFog())&&!this._fadeTimer&&(this._fadeTimer=window.setTimeout(this._evaluateOpacity.bind(this),60)))}))}getOffset(){return this._offset}setOffset(e){return this._offset=m.convert(e),this._update(),this}addClassName(e){return this._element.classList.add(e),this}removeClassName(e){return this._element.classList.remove(e),this}toggleClassName(e){return this._element.classList.toggle(e)}_onMove(e){const t=this._map;if(!t)return;const i=this._pointerdownPos,s=this._positionDelta;if(i&&s){if(!this._isDragging){const s=this._clickTolerance||t._clickTolerance;if(e.point.dist(i)<s)return;this._isDragging=!0}this._pos=e.point.sub(s),this._lngLat=t.unproject(this._pos,this._altitude),this.setLngLat(this._lngLat),this._element.style.pointerEvents="none","pending"===this._state&&(this._state="active",this.fire(new M("dragstart"))),this.fire(new M("drag"))}}_onUp(){this._element.style.pointerEvents="auto",this._positionDelta=null,this._pointerdownPos=null,this._isDragging=!1;const e=this._map;e&&(e.off("mousemove",this._onMove),e.off("touchmove",this._onMove)),"active"===this._state&&this.fire(new M("dragend")),this._state="inactive"}_addDragHandler(e){const t=this._map,i=this._pos;t&&i&&this._element.contains(e.originalEvent.target)&&(e.preventDefault(),this._positionDelta=e.point.sub(i),this._pointerdownPos=e.point,this._state="pending",t.on("mousemove",this._onMove),t.on("touchmove",this._onMove),t.once("mouseup",this._onUp),t.once("touchend",this._onUp))}setDraggable(e){this._draggable=!!e;const t=this._map;return t&&(e?(t.on("mousedown",this._addDragHandler),t.on("touchstart",this._addDragHandler)):(t.off("mousedown",this._addDragHandler),t.off("touchstart",this._addDragHandler))),this}isDraggable(){return this._draggable}setRotation(e){return this._rotation=e||em.rotation,this._update(),this}getRotation(){return this._rotation}setRotationAlignment(e){return this._rotationAlignment=e||em.rotationAlignment,this._update(),this}getRotationAlignment(){return"auto"===this._rotationAlignment||"horizon"===this._rotationAlignment&&this._map&&!this._map._showingGlobe()?"viewport":this._rotationAlignment}setPitchAlignment(e){return this._pitchAlignment=e||em.pitchAlignment,this._update(),this}getPitchAlignment(){return"auto"===this._pitchAlignment?this.getRotationAlignment():this._pitchAlignment}setOccludedOpacity(e){return this._occludedOpacity=e||em.occludedOpacity,this._update(),this}getOccludedOpacity(){return this._occludedOpacity}}const im={OFF:[],WAITING_ACTIVE:["waiting","active"],ACTIVE_LOCK:["active"],ACTIVE_ERROR:["waiting","active-error"],BACKGROUND:["background"],BACKGROUND_ERROR:["waiting","background-error"]},sm=e=>`mapboxgl-ctrl-geolocate-${e}`,om=["waiting","active","active-error","background","background-error"].map(sm),rm={positionOptions:{enableHighAccuracy:!1,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showAccuracyCircle:!0,showUserLocation:!0,showUserHeading:!1,showButton:!0,followUserLocation:!0};class nm extends A{constructor(e={}){super();const t=navigator.geolocation;this.options={geolocation:t,...rm,...e},rt(["_onSuccess","_onError","_onZoom","_finish","_setupUI","_updateCamera","_updateMarker","_updateMarkerRotation","_onDeviceOrientation"],this),this._updateMarkerRotationThrottled=Ap(this._updateMarkerRotation,20),this._numberOfWatches=0}onAdd(e){return this._map=e,this._container=Tn("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._checkGeolocationSupport(this._setupUI),this._container}onRemove(){this._clearRequestTimeout(),void 0!==this._geolocationWatchID&&(this.options.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),this._container.remove(),this._map.off("zoom",this._onZoom),this._map=void 0,this._numberOfWatches=0,this._noTimeout=!1}_checkGeolocationSupport(e){const t=(t=!!this.options.geolocation)=>{this._supportsGeolocation=t,e(t)};void 0!==this._supportsGeolocation?e(this._supportsGeolocation):void 0!==navigator.permissions?navigator.permissions.query({name:"geolocation"}).then(e=>t("denied"!==e.state)).catch(()=>t()):t()}_isOutOfMapMaxBounds(e){const t=this._map.getMaxBounds(),i=e.coords;return!!t&&(i.longitude<t.getWest()||i.longitude>t.getEast()||i.latitude<t.getSouth()||i.latitude>t.getNorth())}_setWatchState(e){this._watchState=e;const t=this._geolocateButton.classList;t.remove(...om);for(const i of im[e])t.add(sm(i))}_setButtonTitle(e){const t=this._map._getUIString(e);this._geolocateButton.setAttribute("aria-label",t),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",t)}_setErrorState(){switch(this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":this._setWatchState("ACTIVE_ERROR");break;case"BACKGROUND":this._setWatchState("BACKGROUND_ERROR")}}_onSuccess(e){if(this._map){if(this._clearRequestTimeout(),this._isOutOfMapMaxBounds(e))return this._setErrorState(),this.fire(new M("outofmaxbounds",e)),this._updateMarker(),void this._finish();if(this._lastKnownPosition=e,this.options.trackUserLocation)switch(this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":this._setWatchState(this.options.followUserLocation?"ACTIVE_LOCK":"BACKGROUND");break;case"BACKGROUND":case"BACKGROUND_ERROR":this._setWatchState("BACKGROUND")}this.options.showUserLocation&&"OFF"!==this._watchState&&this._updateMarker(e),this.options.followUserLocation&&(!this.options.trackUserLocation||"ACTIVE_LOCK"===this._watchState)&&this._updateCamera(e),this.options.showUserLocation&&this._userLocationDotMarker.removeClassName("mapboxgl-user-location-dot-stale"),this.fire(new M("geolocate",{coords:e.coords,timestamp:e.timestamp,...e.toJSON?{toJSON:e.toJSON.bind(e)}:{}})),this._finish()}}_updateCamera(e){const t=new Es(e.coords.longitude,e.coords.latitude),i=e.coords.accuracy,s={bearing:this._map.getBearing(),...this.options.fitBoundsOptions};this._map.fitBounds(t.toBounds(i),s,{geolocateSource:!0})}_updateMarker(e){if(e){const t=new Es(e.coords.longitude,e.coords.latitude);this.options.showAccuracyCircle?this._accuracyCircleMarker.setLngLat(t).addTo(this._map):this._accuracyCircleMarker.remove(),this._userLocationDotMarker.setLngLat(t).addTo(this._map),this._accuracy=e.coords.accuracy,this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius()}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove()}_updateCircleRadius(){const e=this._map.transform,t=ws(1,e._center.lat)*e.worldSize,i=Math.ceil(2*this._accuracy*t);this._circleElement.style.width=`${i}px`,this._circleElement.style.height=`${i}px`}_onZoom(){this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius()}_updateMarkerRotation(){this._userLocationDotMarker&&"number"==typeof this._heading?(this._userLocationDotMarker.setRotation(this._heading),this._userLocationDotMarker.addClassName("mapboxgl-user-location-show-heading")):(this._userLocationDotMarker.removeClassName("mapboxgl-user-location-show-heading"),this._userLocationDotMarker.setRotation(0))}_onError(e){if(this._map){if(this._clearRequestTimeout(),this.options.trackUserLocation)if(1===e.code)this._setWatchState("OFF"),this._geolocateButton.disabled=!0,this._setButtonTitle("GeolocateControl.LocationNotAvailable"),void 0!==this._geolocationWatchID&&this._clearWatch();else{if(3===e.code&&this._noTimeout)return;this._setErrorState()}"OFF"!==this._watchState&&this.options.showUserLocation&&this._userLocationDotMarker.addClassName("mapboxgl-user-location-dot-stale"),this.fire(new M("error",{code:e.code,message:e.message,PERMISSION_DENIED:e.PERMISSION_DENIED,POSITION_UNAVAILABLE:e.POSITION_UNAVAILABLE,TIMEOUT:e.TIMEOUT})),this._finish()}}_finish(){this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0}_startRequestTimeout(){this._clearRequestTimeout();const e=this.options.positionOptions.timeout;e&&(this._requestTimeoutId=window.setTimeout(()=>{this._onError({code:3,message:"Geolocation request timed out"})},e))}_clearRequestTimeout(){void 0!==this._requestTimeoutId&&(clearTimeout(this._requestTimeoutId),this._requestTimeoutId=void 0)}_setupUI(e){void 0!==this._map&&(this._container.addEventListener("contextmenu",e=>e.preventDefault()),this._geolocateButton=Tn("button","mapboxgl-ctrl-geolocate",this._container),Tn("span","mapboxgl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",!1===e?(_("Geolocation support is not available so the GeolocateControl will be disabled."),this._geolocateButton.disabled=!0,this._setButtonTitle("GeolocateControl.LocationNotAvailable")):this._setButtonTitle("GeolocateControl.FindMyLocation"),this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._createUserLocationMarkers(),this.options.trackUserLocation&&(this._watchState="OFF"),this._map.on("zoom",this._onZoom)),this._geolocateButton.addEventListener("click",this.trigger.bind(this)),this._setup=!0,this.options.showButton||(this._container.style.display="none"),this.options.trackUserLocation&&this._map.on("movestart",e=>{e.geolocateSource||"ACTIVE_LOCK"!==this._watchState||e.originalEvent&&"resize"===e.originalEvent.type||(this._setWatchState("BACKGROUND"),this.fire(new M("trackuserlocationend")))}),this.fire(new M("ready")))}_onDeviceOrientation(e){this._userLocationDotMarker&&(e.webkitCompassHeading?this._heading=e.webkitCompassHeading:!0===e.absolute&&(this._heading=-1*e.alpha),this._updateMarkerRotationThrottled())}trigger(){if(!this._setup)return _("Geolocate control triggered before added to a map"),!1;if(this.options.trackUserLocation){switch(this._watchState){case"OFF":this._setWatchState("WAITING_ACTIVE"),this.fire(new M("trackuserlocationstart"));break;case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":case"BACKGROUND_ERROR":this._numberOfWatches--,this._noTimeout=!1,this._setWatchState("OFF"),this.fire(new M("trackuserlocationend"));break;case"BACKGROUND":this._setWatchState("ACTIVE_LOCK"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new M("trackuserlocationstart"))}if("OFF"===this._watchState&&void 0!==this._geolocationWatchID)this._clearWatch();else if(void 0===this._geolocationWatchID){let e;this._geolocateButton.classList.add(sm("waiting")),this._geolocateButton.setAttribute("aria-pressed","true"),this._numberOfWatches++,this._numberOfWatches>1?(e={maximumAge:6e5,timeout:0},this._noTimeout=!0):(e=this.options.positionOptions,this._noTimeout=!1),this._geolocationWatchID=this.options.geolocation.watchPosition(this._onSuccess,this._onError,e),this._startRequestTimeout(),this.options.showUserHeading&&this._addDeviceOrientationListener()}}else this.options.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._startRequestTimeout(),this._timeoutId=window.setTimeout(this._finish,1e4);return!0}setFollowUserLocation(e){return this.options.followUserLocation=e??rm.followUserLocation,this.options.trackUserLocation&&"OFF"!==this._watchState&&(this.options.followUserLocation?"BACKGROUND"!==this._watchState&&"BACKGROUND_ERROR"!==this._watchState||(this._setWatchState("ACTIVE_LOCK"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new M("trackuserlocationstart"))):"ACTIVE_LOCK"!==this._watchState&&"ACTIVE_ERROR"!==this._watchState||(this._setWatchState("BACKGROUND"),this.fire(new M("trackuserlocationend")))),this}setShowAccuracyCircle(e){if(this.options.showAccuracyCircle=e??rm.showAccuracyCircle,!this._accuracyCircleMarker)return this;if(this.options.showAccuracyCircle){if(this.options.showUserLocation&&this._lastKnownPosition){const{longitude:e,latitude:t,accuracy:i}=this._lastKnownPosition.coords;this._accuracy=i,this._accuracyCircleMarker.setLngLat(new Es(e,t)).addTo(this._map),this._updateCircleRadius()}}else this._accuracyCircleMarker.remove();return this}setShowUserHeading(e){return this.options.showUserHeading=e??rm.showUserHeading,this._setup?(this.options.showUserHeading?void 0!==this._geolocationWatchID&&this._addDeviceOrientationListener():(this._removeDeviceOrientationListener(),this._heading=void 0,this._userLocationDotMarker&&this._updateMarkerRotation()),this):this}setFitBoundsOptions(e){return this.options.fitBoundsOptions=e??rm.fitBoundsOptions,this}setShowUserLocation(e){return this.options.showUserLocation=e??rm.showUserLocation,this._setup?(this.options.showUserLocation?(this._userLocationDotMarker||(this._createUserLocationMarkers(),this._map.on("zoom",this._onZoom)),!this._lastKnownPosition||void 0!==this._watchState&&"OFF"===this._watchState||this._updateMarker(this._lastKnownPosition)):(this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this._accuracyCircleMarker&&this._accuracyCircleMarker.remove()),this):this}_addDeviceOrientationListener(){const e=()=>{const e="ondeviceorientationabsolute"in window?"deviceorientationabsolute":"deviceorientation";window.addEventListener(e,this._onDeviceOrientation)},t=DeviceOrientationEvent;"function"==typeof t?.requestPermission?t.requestPermission().then(t=>{"granted"===t?e():_("GeolocateControl: permission to use device orientation was denied, so the user heading arrow will not be shown.")}).catch(()=>{_("GeolocateControl: could not request device orientation permission. Enable the user heading from a user gesture (click/tap) so the browser can prompt for access.")}):e()}_removeDeviceOrientationListener(){window.removeEventListener("deviceorientation",this._onDeviceOrientation),window.removeEventListener("deviceorientationabsolute",this._onDeviceOrientation)}_createUserLocationMarkers(){this._dotElement=Tn("div","mapboxgl-user-location"),this._dotElement.appendChild(Tn("div","mapboxgl-user-location-dot")),this._dotElement.appendChild(Tn("div","mapboxgl-user-location-heading")),this._userLocationDotMarker=new tm({element:this._dotElement,rotationAlignment:"map",pitchAlignment:"map"}),this._circleElement=Tn("div","mapboxgl-user-location-accuracy-circle"),this._accuracyCircleMarker=new tm({element:this._circleElement,pitchAlignment:"map"})}_clearWatch(){this._clearRequestTimeout(),this.options.geolocation.clearWatch(this._geolocationWatchID),this._removeDeviceOrientationListener(),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove(sm("waiting")),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null)}}const am={maxWidth:100,unit:"metric"},lm={kilometer:"km",meter:"m",mile:"mi",foot:"ft","nautical-mile":"nm"};class cm{constructor(e={}){this.options={...am,...e},rt(["_update","_setScale","setUnit"],this)}getDefaultPosition(){return"bottom-left"}_update(){const e=this.options.maxWidth||100,t=this._map,i=t._containerHeight/2,s=t._containerWidth/2-e/2,o=t.unproject([s,i]),r=t.unproject([s+e,i]),n=o.distanceTo(r);if("imperial"===this.options.unit){const t=3.2808*n;t>5280?this._setScale(e,t/5280,"mile"):this._setScale(e,t,"foot")}else"nautical"===this.options.unit?this._setScale(e,n/1852,"nautical-mile"):n>=1e3?this._setScale(e,n/1e3,"kilometer"):this._setScale(e,n,"meter")}_setScale(e,t,i){this._map._requestDomTask(()=>{const s=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}(t),o=s/t;this._container.innerHTML="nautical-mile"!==i?new Intl.NumberFormat(this._language,{style:"unit",unitDisplay:"short",unit:i}).format(s):`${s}&nbsp;${lm[i]}`,this._container.style.width=e*o+"px"})}onAdd(e){return this._map=e,this._language=e.getLanguage(),this._container=Tn("div","mapboxgl-ctrl mapboxgl-ctrl-scale",e.getContainer()),this._container.dir="auto",this._map.on("move",this._update),this._update(),this._container}onRemove(){this._container.remove(),this._map.off("move",this._update),this._map=void 0}_setLanguage(e){this._language=e,this._update()}setUnit(e){this.options.unit=e,this._update()}}class hm{constructor(e={}){this._fullscreen=!1,e&&e.container&&(e.container instanceof HTMLElement?this._container=e.container:_("Full screen control 'container' must be a DOM element.")),rt(["_onClickFullscreen","_changeIcon"],this),"onfullscreenchange"in document?this._fullscreenchange="fullscreenchange":"onwebkitfullscreenchange"in document&&(this._fullscreenchange="webkitfullscreenchange")}onAdd(e){return this._map=e,this._container||(this._container=this._map.getContainer()),this._controlContainer=Tn("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._checkFullscreenSupport()?this._setupUI():(this._controlContainer.style.display="none",_("This device does not support fullscreen mode.")),this._controlContainer}onRemove(){this._controlContainer.remove(),this._map=null,document.removeEventListener(this._fullscreenchange,this._changeIcon)}_checkFullscreenSupport(){return!(!document.fullscreenEnabled&&!document.webkitFullscreenEnabled)}_setupUI(){const e=this._fullscreenButton=Tn("button","mapboxgl-ctrl-fullscreen",this._controlContainer);Tn("span","mapboxgl-ctrl-icon",e).setAttribute("aria-hidden","true"),e.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),document.addEventListener(this._fullscreenchange,this._changeIcon)}_updateTitle(){const e=this._getTitle();this._fullscreenButton.setAttribute("aria-label",e),this._fullscreenButton.firstElementChild&&this._fullscreenButton.firstElementChild.setAttribute("title",e)}_getTitle(){return this._map._getUIString(this._isFullscreen()?"FullscreenControl.Exit":"FullscreenControl.Enter")}_isFullscreen(){return this._fullscreen}_changeIcon(){(document.fullscreenElement||document.webkitFullscreenElement)===this._container!==this._fullscreen&&(this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle("mapboxgl-ctrl-shrink"),this._fullscreenButton.classList.toggle("mapboxgl-ctrl-fullscreen"),this._updateTitle())}_onClickFullscreen(){this._isFullscreen()?document.exitFullscreen?document.exitFullscreen():document.webkitCancelFullScreen&&document.webkitCancelFullScreen():this._container.requestFullscreen?this._container.requestFullscreen():this._container.webkitRequestFullscreen&&this._container.webkitRequestFullscreen()}}class dm{constructor(){rt(["_onIndoorUpdate","_onStyleData","_scrollUp","_scrollDown","_toggleIndoor"],this),this._visibleFloorStart=0,this._lastSelectedFloorId=null}onAdd(e){return this._map=e,this._container=Tn("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.style.display="none",this._map.on("styledata",this._onStyleData),this._map.on("idle",this._onStyleData),this._updateConnection(),this._container}_onStyleData(){this._updateConnection()}_updateConnection(){if(this._map&&this._map.style&&this._map.style.indoorManager){const e=this._map.style.indoorManager;e.off("selector-update",this._onIndoorUpdate),e.on("selector-update",this._onIndoorUpdate),this._onIndoorUpdate(e.getControlState()),this._map.off("idle",this._onStyleData)}}_createButton(e,t){const i=Tn("button",e,this._container);return i.type="button",i.addEventListener("click",t),i}_setButtonTitle(e,t){e.setAttribute("aria-label",t),e.textContent=t}onRemove(){this._container&&this._container.remove(),this._map&&(this._map.off("styledata",this._onStyleData),this._map.off("idle",this._onStyleData),this._map.style&&this._map.style.indoorManager&&this._map.style.indoorManager.off("selector-update",this._onIndoorUpdate),this._map=null)}getDefaultPosition(){return"top-right"}_onIndoorUpdate(e){if(!e||!e.floors||0===e.floors.length)return this._model=e,void(this._container.style.display="none");const t=this._model;this._model=e,this._container.style.display="inline-block";const i=!t||t.floors.length!==e.floors.length||t.floors.some((t,i)=>t.id!==e.floors[i].id);if(i&&(this._visibleFloorStart=0,this._lastSelectedFloorId=null),e.selectedFloorId){if(e.selectedFloorId!==this._lastSelectedFloorId||i){const t=e.floors.findIndex(t=>t.id===e.selectedFloorId);if(-1!==t){const i=e.floors.length;let s,o;i<=5?(s=0,o=i-1):0===this._visibleFloorStart?(s=0,o=3):this._visibleFloorStart>=i-3?(s=i-3-1,o=i-1):(s=this._visibleFloorStart,o=this._visibleFloorStart+3-1),t<s?this._visibleFloorStart=t:t>o&&(this._visibleFloorStart=t-2)}}this._lastSelectedFloorId=e.selectedFloorId}this._render()}_render(){if(!this._container||!this._model||!this._model.floors)return;this._container.innerHTML="";const e=this._createButton("mapboxgl-ctrl-indoor-toggle",this._toggleIndoor);Tn("span","mapboxgl-ctrl-icon",e).setAttribute("aria-hidden","true"),this._model.activeFloorsVisible||e.classList.add("mapboxgl-ctrl-level-button-selected"),this._container.appendChild(e);const t=this._model.floors,i=t.length;if(i<=5)return void t.forEach(e=>this._createFloorButton(e));const s=0===this._visibleFloorStart,o=this._visibleFloorStart>=i-3;if(s)this._createFloorButton(t[0]);else{const e=this._createButton("mapboxgl-ctrl-arrow-up",this._scrollUp);Tn("span","mapboxgl-ctrl-icon",e).setAttribute("aria-hidden","true"),this._container.appendChild(e)}let r=[];if(r=s?t.slice(1,4):o?t.slice(this._visibleFloorStart-1,this._visibleFloorStart+3-1):t.slice(this._visibleFloorStart,this._visibleFloorStart+3),r.forEach(e=>this._createFloorButton(e)),o)this._createFloorButton(t[i-1]);else{const e=this._createButton("mapboxgl-ctrl-arrow-down",this._scrollDown);Tn("span","mapboxgl-ctrl-icon",e).setAttribute("aria-hidden","true"),this._container.appendChild(e)}}_createFloorButton(e){const t=this._createButton("mapboxgl-ctrl-level-button",()=>{const t=e.id;this._model&&this._model.selectedFloorId===t&&this._model.activeFloorsVisible||this._map&&(this._model&&!this._model.activeFloorsVisible&&this._map.style&&this._map.style.indoorManager&&this._map.style.indoorManager.setActiveFloorsVisibility(!0),this._map._selectIndoorFloor(t))}),i=(e.name||"").trim(),s=e.zIndex.toString(),o=i?Array.from(i).slice(0,3).join(""):s;this._setButtonTitle(t,o),this._model&&this._model.activeFloorsVisible&&e.id===this._model.selectedFloorId&&t.classList.add("mapboxgl-ctrl-level-button-selected"),this._container&&this._container.appendChild(t)}_toggleIndoor(){this._map&&this._map.style&&this._map.style.indoorManager&&this._model&&this._model.activeFloorsVisible&&this._map.style.indoorManager.setActiveFloorsVisibility(!1)}_scrollUp(){if(this._visibleFloorStart>0){this._visibleFloorStart--,1===this._visibleFloorStart&&(this._visibleFloorStart=0);const e=this._model&&this._model.floors||[];if(e.length>3){const t=e.length-3;this._visibleFloorStart===t-1&&(this._visibleFloorStart=t-2)}this._render()}}_scrollDown(){if(this._model&&this._model.floors){const e=this._model.floors.length-3;this._visibleFloorStart<e&&(this._visibleFloorStart++,1===this._visibleFloorStart&&(this._visibleFloorStart=2),this._visibleFloorStart===e-1&&(this._visibleFloorStart=e),this._visibleFloorStart>e&&(this._visibleFloorStart=e),this._render())}}}const um=/\s+/,_m={closeButton:!0,closeOnClick:!0,focusAfterOpen:!0,className:"",maxWidth:"240px",altitude:0},pm=["a[href]","[tabindex]:not([tabindex='-1'])","[contenteditable]:not([contenteditable='false'])","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])"].join(", ");class fm extends A{constructor(e){super(),this.options=Object.assign(Object.create(_m),e),this._altitude=this.options.altitude,rt(["_update","_onClose","remove","_onMouseEvent"],this),this._classList=new Set(e&&e.className?e.className.trim().split(um):[])}addTo(e){return this._map&&this.remove(),this._map=e,this.options.closeOnClick&&e.on("preclick",this._onClose),this.options.closeOnMove&&e.on("move",this._onClose),e.on("remove",this.remove),this._update(),e._addPopup(this),this._focusFirstElement(),this._trackPointer?(e.on("mousemove",this._onMouseEvent),e.on("mouseup",this._onMouseEvent),e._canvasContainer.classList.add("mapboxgl-track-pointer")):e.on("move",this._update),this.fire(new M("open")),this}isOpen(){return!!this._map}remove(){this._content&&this._content.remove(),this._container&&(this._container.remove(),this._container=void 0);const e=this._map;return e&&(e.off("move",this._update),e.off("move",this._onClose),e.off("preclick",this._onClose),e.off("click",this._onClose),e.off("remove",this.remove),e.off("mousemove",this._onMouseEvent),e.off("mouseup",this._onMouseEvent),e.off("drag",this._onMouseEvent),e._canvasContainer&&e._canvasContainer.classList.remove("mapboxgl-track-pointer"),e._removePopup(this),this._map=void 0),this.fire(new M("close")),this}getLngLat(){return this._lngLat}setLngLat(e){this._lngLat=Es.convert(e),this._pos=null,this._trackPointer=!1,this._update();const t=this._map;return t&&(t.on("move",this._update),t.off("mousemove",this._onMouseEvent),t._canvasContainer.classList.remove("mapboxgl-track-pointer")),this}getAltitude(){return this._altitude}setAltitude(e){return this._altitude=e,this._update(),this}trackPointer(){this._trackPointer=!0,this._pos=null,this._update();const e=this._map;return e&&(e.off("move",this._update),e.on("mousemove",this._onMouseEvent),e.on("drag",this._onMouseEvent),e._canvasContainer.classList.add("mapboxgl-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 s;for(i.innerHTML=e;s=i.firstChild,s;)t.appendChild(s);return this.setDOMContent(t)}getMaxWidth(){return this._container&&this._container.style.maxWidth}setMaxWidth(e){return this.options.maxWidth=e,this._update(),this}setDOMContent(e){let t=this._content;if(t)for(;t.hasChildNodes();)t.firstChild&&t.removeChild(t.firstChild);else t=this._content=Tn("div","mapboxgl-popup-content",this._container||void 0);if(t.appendChild(e),this.options.closeButton){const e=this._closeButton=Tn("button","mapboxgl-popup-close-button",t);e.type="button",e.setAttribute("aria-label","Close popup"),e.innerHTML='<span aria-hidden="true">&#215;</span>',e.addEventListener("click",this._onClose)}return this._update(),this._focusFirstElement(),this}addClassName(e){return this._classList.add(e),this._updateClassList(),this}removeClassName(e){return this._classList.delete(e),this._updateClassList(),this}setOffset(e){return this.options.offset=e,this._update(),this}toggleClassName(e){let t;return this._classList.delete(e)?t=!1:(this._classList.add(e),t=!0),this._updateClassList(),t}_onMouseEvent(e){this._update(e.point)}_getAnchor(e){if(this.options.anchor)return this.options.anchor;const t=this._map,i=this._container,s=this._pos;if(!t||!i||!s)return"bottom";const o=i.offsetWidth,r=i.offsetHeight,n=s.x<o/2,a=s.x>t.transform.width-o/2;if(s.y+e<r)return n?"top-left":a?"top-right":"top";if(s.y>t.transform.height-r){if(n)return"bottom-left";if(a)return"bottom-right"}return n?"left":a?"right":"bottom"}_updateClassList(){const e=this._container;if(!e)return;const t=[...this._classList];t.push("mapboxgl-popup"),this._anchor&&t.push(`mapboxgl-popup-anchor-${this._anchor}`),this._trackPointer&&t.push("mapboxgl-popup-track-pointer"),e.className=t.join(" ")}_update(e){const t=this._map,i=this._content;if(!t||!this._lngLat&&!this._trackPointer||!i)return;let s=this._container;if(s||(s=this._container=Tn("div","mapboxgl-popup",t.getContainer()),this._tip=Tn("div","mapboxgl-popup-tip",s),s.appendChild(i)),this.options.maxWidth&&s.style.maxWidth!==this.options.maxWidth&&(s.style.maxWidth=this.options.maxWidth),t.transform.renderWorldCopies&&!this._trackPointer&&(this._lngLat=Kf(this._lngLat,this._pos,t.transform)),!this._trackPointer||e){const i=this._pos=this._trackPointer&&e instanceof m?e:t.project(this._lngLat,this._altitude),s=mm(this.options.offset),o=this._anchor=this._getAnchor(s.y),r=mm(this.options.offset,o),n=i.add(r).round();t._requestDomTask(()=>{this._container&&o&&(this._container.style.transform=`${Jf[o]} translate(${n.x}px,${n.y}px)`)})}if(!this._marker&&t._showingGlobe()){const e=Sr(t.transform,this._lngLat)?0:1;this._setOpacity(e)}this._updateClassList()}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const e=this._container.querySelector(pm);e&&e.focus()}_onClose(){this.remove()}_setOpacity(e){this._container&&(this._container.style.opacity=`${e}`),this._content&&(this._content.style.pointerEvents=e?"auto":"none")}}function mm(e=new m(0,0),t="bottom"){if("number"==typeof e){const i=Math.round(Math.sqrt(.5*Math.pow(e,2)));switch(t){case"top":return new m(0,e);case"top-left":return new m(i,i);case"top-right":return new m(-i,i);case"bottom":return new m(0,-e);case"bottom-left":return new m(i,-i);case"bottom-right":return new m(-i,-i);case"left":return new m(e,0);case"right":return new m(-e,0)}return new m(0,0)}return e instanceof m||Array.isArray(e)?m.convert(e):m.convert(e[t]||[0,0])}var gm;gm=t(import.meta.url)?"cdn":"other",Yr=gm;const vm=Cr;export{tm as $,Ul as A,en as B,zu as C,Cu as D,Q_ as E,wu as F,H_ as G,$_ as H,pd as I,fd as J,su as K,Tl as L,wl as M,el as N,Tu as O,El as P,xl as Q,jl as R,Pu as S,yc as T,kf as U,Da as V,bu as W,hm as X,nm as Y,dm as Z,Hf as _,Lu as a,Xf as a0,fm as a1,cm as a2,Nd as a3,Fc as a4,ul as a5,zc as a6,Xr as a7,_l as a8,ll as a9,mn as aa,vm as ab,A_ as b,hd as c,Gh as d,I_ as e,sp as f,Iu as g,Ja as h,mu as i,Ac as j,pu as k,bp as l,Ed as m,Ra as n,cd as o,tp as p,nd as q,xc as r,ad as s,kh as t,ld as u,Zh as v,yd as w,Xh as x,Ru as y,jh as z};//# sourceMappingURL=core.js.map
1
+ import{eg as e,eh as t,ei as i,ej as s,ek as o,el as r,em as n,en as a,ea as l,eo as c,ep as h,eq as d,er as u,w as _,es as p,et as f,N as m,dM as g,bk as v,bw as y,R as x,e7 as b,eu as w,x as T,v as E,P as I,aQ as S,eb as D,k as R,m as C,b9 as A,ev as L,q as P,b_ as M,ew as O,ex as z,ey as F,T as k,dA as B,g as N,ez as U,ec as V,eA as j,eB as G,eC as q,eD as Z,eE as W,eF as H,eG as $,E as X,b6 as Y,af as K,ax as J,c6 as Q,eH as ee,eI as te,eJ as ie,eK as se,eL as oe,eM as re,bT as ne,f as ae,ab as le,eN as ce,e8 as he,eO as de,eP as ue,eQ as _e,eR as pe,eS as fe,eT as me,eU as ge,bZ as ve,al as ye,eV as xe,eW as be,M as we,eX as Te,a3 as Ee,ae as Ie,aC as Se,am as De,eY as Re,eZ as Ce,l as Ae,e_ as Le,o as Pe,e$ as Me,e1 as Oe,f0 as ze,b$ as Fe,e0 as ke,y as Be,f1 as Ne,f2 as Ue,f3 as Ve,ed as je,O as Ge,a8 as qe,f4 as Ze,f5 as We,dD as He,cj as $e,f6 as Xe,aB as Ye,aH as Ke,f7 as Je,bG as Qe,f8 as et,f9 as tt,fa as it,fb as st,fc as ot,c4 as rt,aA as nt,az as at,dH as lt,S as ct,L as ht,Z as dt,A as ut,bJ as _t,fd as pt,h as ft,fe as mt,b8 as gt,cT as vt,b2 as yt,aO as xt,bx as bt,aZ as wt,$ as Tt,ff as Et,a0 as It,an as St,cZ as Dt,fg as Rt,bM as Ct,e as At,e6 as Lt,fh as Pt,c0 as Mt,ci as Ot,d3 as zt,aG as Ft,a9 as kt,b0 as Bt,fi as Nt,fj as Ut,fk as Vt,fl as jt,da as Gt,cw as qt,W as Zt,aR as Wt,ao as Ht,fm as $t,fn as Xt,fo as Yt,ap as Kt,fp as Jt,cs as Qt,cD as ei,cE as ti,fq as ii,fr as si,fs as oi,b1 as ri,cP as ni,ag as ai,ft as li,_ as ci,fu as hi,fv as di,d8 as ui,fw as _i,fx as pi,fy as fi,d7 as mi,J as gi,dy as vi,dh as yi,fz as xi,bY as bi,fA as wi,ak as Ti,fB as Ei,fC as Ii,bq as Si,bc as Di,U as Ri,c as Ci,a as Ai,b as Li,d as Pi,bI as Mi,bH as Oi,fD as zi,fE as Fi,b3 as ki,bF as Bi,aS as Ni,fF as Ui,fG as Vi,fH as ji,fI as Gi,fJ as qi,fK as Zi,fL as Wi,fM as Hi,fN as $i,fO as Xi,fP as Yi,dr as Ki,fQ as Ji,fR as Qi,fS as es,fT as ts,fU as is,fV as ss,d4 as os,X as rs,fW as ns,fX as as,fY as ls,fZ as cs,ch as hs,f_ as ds,f$ as us,aq as _s,bX as ps,ar as fs,ca as ms,c9 as gs,g0 as vs,aD as ys,g1 as xs,g2 as bs,au as ws,g3 as Ts,z as Es,e9 as Is,g4 as Ss,g5 as Ds,D as Rs,g6 as Cs,g7 as As,cS as Ls,ck as Ps,g8 as Ms,g9 as Os,cI as zs,bR as Fs,ga as ks,gb as Bs,gc as Ns,gd as Us,ge as Vs,gf as js,b7 as Gs,c7 as qs,gg as Zs,ah as Ws,bA as Hs,gh as $s,gi as Xs,ad as Ys,gj as Ks,aa as Js,gk as Qs,gl as eo,gm as to,bL as io,bW as so,cr as oo,gn as ro,go as no,gp as ao,gq as lo,gr as co,gs as ho,gt as uo,gu as _o,gv as po,cg as fo,gw as mo,gx as go,gy as vo,aj as yo,gz as xo,gA as bo,bU as wo,gB as To,gC as Eo,gD as Io,gE as So,gF as Do,gG as Ro,gH as Co,gI as Ao,gJ as Lo,gK as Po,n as Mo,dV as Oo,gL as zo,gM as Fo,gN as ko,ay as Bo,gO as No,a$ as Uo,a_ as Vo,aU as jo,aW as Go,aX as qo,aY as Zo,gP as Wo,gQ as Ho,aI as $o,gR as Xo,gS as Yo,gT as Ko,gU as Jo,gV as Qo,gW as er,aT as tr,gX as ir,gY as sr,cb as or,aL as rr,gZ as nr,g_ as ar,g$ as lr,h0 as cr,h1 as hr,h2 as dr,h3 as ur,h4 as _r,h5 as pr,h6 as fr,ai as mr,a2 as gr,av as vr,a1 as yr,h7 as xr,h8 as br,h9 as wr,cc as Tr,aV as Er,ha as Ir,hb as Sr,hc as Dr,hd as Rr}from"./shared.js";var Cr="3.35.3";const Ar="01",Lr={create:"create",load:"load",fullLoad:"fullLoad"},Pr={mark(e){performance.mark(e)},measure(e,t,i){performance.measure(e,t,i)}};function Mr(r){const n=r.name.split("?")[0];return t(n)&&n.includes("mapbox-gl.js")?"javascript":t(n)&&n.includes("mapbox-gl.css")?"css":i(n)?"fontRange":s(n)?"sprite":e(n)?"style":o(n)?"tilejson":"other"}const Or=/(\.(png|jpg)\d*)(?=$)/,zr=/^.+\/v4\//,Fr=/\.[\w]+$/,kr=/^(\/v4\/|\/(raster|rasterarrays)\/v1\/)/,Br=/^access_token=(.*)$/,Nr="NO_ACCESS_TOKEN";class Ur{constructor(e,t,i){this._transformRequestFn=e,this._customAccessToken=t,this._silenceAuthErrors=!!i,this._createSkuToken()}_createSkuToken(){const e=function(){let e="";for(let t=0;t<10;t++)e+="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"[Math.floor(62*Math.random())];return{token:["1",Ar,e].join(""),tokenExpiresAt:Date.now()+432e5}}();this._skuToken=e.token,this._skuTokenExpiresAt=e.tokenExpiresAt}_isSkuTokenExpired(){return Date.now()>this._skuTokenExpiresAt}async transformRequest(e,t,i){if(!this._transformRequestFn)return{url:e};const s=i?{signal:i}:{};return await this._transformRequestFn(e,t,s)||{url:e}}normalizeStyleURL(e,t){if(!r(e))return e;const i=jr(e);return i.params.push(`sdk=js-${Cr}`),i.path=`/styles/v1${i.path}`,this._makeAPIURL(i,this._customAccessToken||t)}normalizeGlyphsURL(e,t){if(!r(e))return e;const i=jr(e);return i.path=`/fonts/v1${i.path}`,this._makeAPIURL(i,this._customAccessToken||t)}normalizeModelURL(e,t){if(!r(e))return e;const i=jr(e);return i.path=`/models/v1${i.path}`,this._makeAPIURL(i,this._customAccessToken||t)}normalizeSourceURL(e,t,i,s){if(!r(e))return e;const o=jr(e);return o.path=`/v4/${o.authority}.json`,o.params.push("secure"),i&&o.params.push(`language=${i}`),s&&o.params.push(`worldview=${s}`),this._makeAPIURL(o,this._customAccessToken||t)}normalizeIconsetURL(e,t){const i=jr(e);return r(e)?(i.path=`/styles/v1${i.path}/iconset.pbf`,this._makeAPIURL(i,this._customAccessToken||t)):Gr(i)}normalizeSpriteURL(e,t,i,s){const o=jr(e);return r(e)?(o.path=`/styles/v1${o.path}/sprite${t}${i}`,this._makeAPIURL(o,this._customAccessToken||s)):(o.path+=`${t}${i}`,Gr(o))}normalizeTileURL(e,t,i){if(this._isSkuTokenExpired()&&this._createSkuToken(),e&&!r(e))return e;const s=jr(e);s.path=s.path.replace(Or,(t||i&&"raster"!==s.authority&&512===i?"@2x":"")+".webp"),"raster"===s.authority?s.path=`/${l.RASTER_URL_PREFIX}${s.path}`:"rasterarrays"===s.authority?s.path=`/${l.RASTERARRAYS_URL_PREFIX}${s.path}`:"3dtiles"===s.authority?s.path=`/${l.TILES3D_URL_PREFIX}${s.path}`:(s.path=s.path.replace(zr,"/"),s.path=`/${l.TILE_URL_VERSION}${s.path}`);const o=this._customAccessToken||function(e){for(const t of e){const e=t.match(Br);if(e)return e[1]}return null}(s.params)||l.ACCESS_TOKEN;return l.REQUIRE_ACCESS_TOKEN&&o&&this._skuToken&&s.params.push(`sku=${this._skuToken}`),this._makeAPIURL(s,o)}canonicalizeTileURL(e,t){const i=jr(e);if(!kr.test(i.path)||!Fr.test(i.path))return e;let s="mapbox://";i.path.startsWith("/raster/v1/")?s+=`raster/${i.path.replace(`/${l.RASTER_URL_PREFIX}/`,"")}`:i.path.startsWith("/rasterarrays/v1/")?s+=`rasterarrays/${i.path.replace(`/${l.RASTERARRAYS_URL_PREFIX}/`,"")}`:s+=`tiles/${i.path.replace(`/${l.TILE_URL_VERSION}/`,"")}`;let o=i.params;return t&&(o=o.filter(e=>!e.match(Br))),o.length&&(s+=`?${o.join("&")}`),s}canonicalizeTileset(e,t){const i=!!t&&r(t),s=[];for(const t of e.tiles||[])n(t)?s.push(this.canonicalizeTileURL(t,i)):s.push(t);return s}_makeAPIURL(e,t){const i="See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes",s=jr(l.API_URL);if(e.protocol=s.protocol,e.authority=s.authority,"http"===e.protocol){const t=e.params.indexOf("secure");t>=0&&e.params.splice(t,1)}if("/"!==s.path&&(e.path=`${s.path}${e.path}`),!l.REQUIRE_ACCESS_TOKEN)return Gr(e);if(t=t||l.ACCESS_TOKEN,!this._silenceAuthErrors){if(!t)throw new Error(`An API access token is required to use Mapbox GL. ${i}`);if("s"===t[0])throw new Error(`Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). ${i}`)}return e.params=e.params.filter(e=>!e.includes("access_token")),e.params.push(`access_token=${t||""}`),Gr(e)}}const Vr=/^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;function jr(e){const t=e.match(Vr);if(!t)throw new Error("Unable to parse URL object");return{protocol:t[1],authority:t[2],path:t[3]||"/",params:t[4]?t[4].split("&"):[]}}function Gr(e){const t=e.params.length?`?${e.params.join("&")}`:"";return`${e.protocol}://${e.authority}${e.path}${t}`}const qr="mapbox.eventData";function Zr(e){if(!e)return null;const t=e.split(".");if(!t||3!==t.length)return null;try{return JSON.parse(f(t[1]))}catch(e){return null}}function Wr(e){return!(!l.EVENTS_URL||!e&&!l.ACCESS_TOKEN)}let Hr;const $r=/^[\w.+-]+(\/[\w.+-]+)?$/;function Xr(e){"string"!=typeof e||e.length>64||!$r.test(e)?_(`Invalid SDK info "${e}"; expected a "Name/version" string. Ignoring.`):Hr=e}let Yr="other";class Kr{constructor(e){this.type=e,this.anonId=null,this.anonIdTimestamp=null,this.eventData={},this.queue=[],this.pendingRequest=!1}getStorageKey(e){const t=Zr(l.ACCESS_TOKEN);let i="";return i=t&&t.u?d(t.u):l.ACCESS_TOKEN||"",e?`${qr}.${e}:${i}`:`${qr}:${i}`}fetchEventData(){const e=u("localStorage"),t=this.getStorageKey(),i=this.getStorageKey("uuid"),s=this.getStorageKey("uuidTimestamp");if(e)try{const e=localStorage.getItem(t);e&&(this.eventData=JSON.parse(e));const o=localStorage.getItem(i);o&&(this.anonId=o);const r=localStorage.getItem(s);r&&(this.anonIdTimestamp=Number(r));const n=Date.now()-864e5;(!this.anonIdTimestamp||this.anonIdTimestamp<n)&&this.refreshUUID()}catch(e){_("Unable to read from LocalStorage")}}refreshUUID(){this.anonId=c(),this.anonIdTimestamp=Date.now()}saveEventData(){const e=u("localStorage"),t=this.getStorageKey(),i=this.getStorageKey("uuid"),s=this.getStorageKey("uuidTimestamp"),o=this.anonId,r=this.anonIdTimestamp;if(e&&o)try{localStorage.setItem(i,o),Object.keys(this.eventData).length>=1&&localStorage.setItem(t,JSON.stringify(this.eventData)),r&&localStorage.setItem(s,r.toString())}catch(e){_("Unable to write to LocalStorage")}}processRequests(){}postEvent(e,t,i,s){if(!l.EVENTS_URL)return;const o=jr(l.EVENTS_URL);o.params.push(`access_token=${s||l.ACCESS_TOKEN||""}`);const r={event:this.type,created:new Date(e).toISOString()},n=t?Object.assign(r,t):r,a={url:Gr(o),headers:{"Content-Type":"text/plain"},body:JSON.stringify([n])};this.pendingRequest=!0,p(a).then(()=>{this.pendingRequest=!1,i(null),this.saveEventData(),this.processRequests()}).catch(e=>{this.pendingRequest=!1,i(e),this.saveEventData(),this.processRequests()})}queueRequest(e,t){this.queue.push({...e,customAccessToken:t}),this.processRequests()}}class Jr extends Kr{constructor(e){super("metrics"),e&&(this.data=e)}postMetricsEvent(e){if(!Wr(e))return;this.anonId||this.fetchEventData(),a(this.anonId)||this.refreshUUID();const t={...this.data,sessionId:this.anonId};this.queueRequest({timestamp:Date.now(),payload:t},e)}processRequests(){if(this.pendingRequest||0===this.queue.length)return;const{timestamp:e,payload:t,customAccessToken:i}=this.queue.shift();this.postEvent(e,t,()=>{},i)}}const Qr=new class extends Kr{constructor(e){super("appUserTurnstile"),this._customAccessToken=e}postTurnstileEvent(e,t){Wr(t)&&Array.isArray(e)&&e.some(e=>r(e)||n(e))&&this.queueRequest({timestamp:Date.now()},t)}processRequests(){if(this.pendingRequest||0===this.queue.length)return;this.anonId&&this.anonIdTimestamp&&this.eventData.lastSuccess&&this.eventData.tokenU||this.fetchEventData();const e=Zr(l.ACCESS_TOKEN),t=e?e.u:l.ACCESS_TOKEN;let i=t!==this.eventData.tokenU;a(this.anonId)||(this.refreshUUID(),i=!0);const{timestamp:s,customAccessToken:o}=this.queue.shift();if(this.eventData.lastSuccess){const e=new Date(this.eventData.lastSuccess),t=new Date(s),o=(s-this.eventData.lastSuccess)/864e5;i=i||o>=1||o<-1||e.getDate()!==t.getDate()}else i=!0;if(!i)return void this.processRequests();const r={version:"2.2",sdkIdentifier:"mapbox-gl-js",sdkVersion:Cr,skuId:Ar,"enabled.telemetry":!1,userId:this.anonId,bundleFormat:"esm",bundleDistribution:Yr};Hr&&(r.sdkInfo=Hr),this.postEvent(s,r,e=>{e||(this.eventData.lastSuccess=s,this.eventData.tokenU=t)},o)}},en=Qr.postTurnstileEvent.bind(Qr),tn=new class extends Kr{constructor(){super("map.load"),this.success={},this.skuToken=""}postMapLoadEvent(e,t,i,s){this.skuToken=t,this.errorCb=s,l.EVENTS_URL&&(i||l.ACCESS_TOKEN?this.queueRequest({id:e,timestamp:Date.now()},i):this.errorCb(new Error(Nr)))}processRequests(){if(this.pendingRequest||0===this.queue.length)return;const{id:e,timestamp:t,customAccessToken:i}=this.queue.shift();if(e&&this.success[e])return;this.anonId&&this.anonIdTimestamp||this.fetchEventData(),a(this.anonId)||this.refreshUUID();const s={version:"2.2",sdkIdentifier:"mapbox-gl-js",sdkVersion:Cr,skuId:Ar,skuToken:this.skuToken,userId:this.anonId,bundleFormat:"esm",bundleDistribution:Yr};Hr&&(s.sdkInfo=Hr),this.postEvent(t,s,t=>{t?this.errorCb(t):e&&(this.success[e]=!0)},i)}remove(){this.errorCb=null}},sn=tn.postMapLoadEvent.bind(tn),on=new class extends Kr{constructor(){super("style.load"),this.eventIdPerMapInstanceMap=new Map,this.mapInstanceIdMap=new WeakMap}getMapInstanceId(e){let t=this.mapInstanceIdMap.get(e);return t||(t=c(),this.mapInstanceIdMap.set(e,t)),t}getEventId(e){const t=this.eventIdPerMapInstanceMap.get(e)||0;return this.eventIdPerMapInstanceMap.set(e,t+1),t}postStyleLoadEvent(e,t){const{map:i,style:s,importedStyles:o}=t;if(!Wr(e))return;const r=this.getMapInstanceId(i),n={mapInstanceId:r,eventId:this.getEventId(r),style:s};o.length&&(n.importedStyles=o),this.queueRequest({timestamp:Date.now(),payload:n},e)}processRequests(){if(this.pendingRequest||0===this.queue.length)return;const{timestamp:e,payload:t,customAccessToken:i}=this.queue.shift();this.postEvent(e,t,()=>{},i)}},rn=on.postStyleLoadEvent.bind(on),nn=new Jr({attributes:[{name:"maps/js/layer-animations/style-with-appearances"}]}),an=nn.postMetricsEvent.bind(nn),ln=new Jr({attributes:[{name:"maps/js/layer-animations/runtime-appearances"}]}),cn=ln.postMetricsEvent.bind(ln),hn=new class extends Kr{constructor(){super("gljs.performance")}postPerformanceEvent(e,t){Wr(e)&&this.queueRequest({timestamp:Date.now(),performanceData:t},e)}processRequests(){if(this.pendingRequest||0===this.queue.length)return;const{timestamp:t,performanceData:i,customAccessToken:s}=this.queue.shift(),o=function(t){const i=performance.getEntriesByType("resource"),s=performance.getEntriesByType("mark"),o=function(e){const t={};if(e)for(const i in e)if("other"!==i)for(const s of e[i]){const e=`${i}ResolveRangeMin`,o=`${i}ResolveRangeMax`,r=`${i}RequestCount`,n=`${i}RequestCachedCount`;t[e]=Math.min(t[e]||1/0,s.startTime),t[o]=Math.max(t[o]||-1/0,s.responseEnd);const a=e=>{void 0===t[e]&&(t[e]=0),++t[e]};void 0!==s.transferSize&&0===s.transferSize&&a(n),a(r)}return t}(function(e,t){const i={};if(e)for(const s of e){const e=t(s);void 0===i[e]&&(i[e]=[]),i[e].push(s)}return i}(i,Mr)),r=window.devicePixelRatio,n=navigator.connection||navigator.mozConnection||navigator.webkitConnection,a=n?n.effectiveType:void 0,l={counters:[],metadata:[],attributes:[]},c=(e,t,i)=>{null!=i&&e.push({name:t,value:i.toString()})};for(const e in o)c(l.counters,e,o[e]);if(t.interactionRange[0]!==1/0&&t.interactionRange[1]!==-1/0&&(c(l.counters,"interactionRangeMin",t.interactionRange[0]),c(l.counters,"interactionRangeMax",t.interactionRange[1])),s)for(const e of Object.values(Lr)){const t=s.find(t=>t.name===e);t&&c(l.counters,e,t.startTime)}return c(l.counters,"visibilityHidden",t.visibilityHidden),c(l.attributes,"style",function(t){if(t)for(const i of t){const t=i.name.split("?")[0];if(e(t)){const e=t.split("/").slice(-2);if(2===e.length)return`mapbox://styles/${e[0]}/${e[1]}`}}}(i)),c(l.attributes,"terrainEnabled",t.terrainEnabled?"true":"false"),c(l.attributes,"fogEnabled",t.fogEnabled?"true":"false"),c(l.attributes,"projection",t.projection),c(l.attributes,"zoom",t.zoom),c(l.metadata,"devicePixelRatio",r),c(l.metadata,"connectionEffectiveType",a),c(l.metadata,"navigatorUserAgent",navigator.userAgent),c(l.metadata,"screenWidth",window.screen.width),c(l.metadata,"screenHeight",window.screen.height),c(l.metadata,"windowWidth",window.innerWidth),c(l.metadata,"windowHeight",window.innerHeight),c(l.metadata,"mapWidth",t.width/r),c(l.metadata,"mapHeight",t.height/r),c(l.metadata,"webglRenderer",t.renderer),c(l.metadata,"webglVendor",t.vendor),c(l.metadata,"sdkVersion",Cr),c(l.metadata,"sdkIdentifier","mapbox-gl-js"),l}(i);for(const e of o.metadata);for(const e of o.counters);for(const e of o.attributes);this.postEvent(t,o,()=>{},s)}},dn=hn.postPerformanceEvent.bind(hn),un=new class extends Kr{constructor(){super("map.auth"),this.success={},this.skuToken=""}getSession(e,t,i,s){if(!l.API_URL||!l.SESSION_PATH)return;const o=jr(l.API_URL+l.SESSION_PATH);o.params.push(`sku=${t||""}`),o.params.push(`access_token=${s||l.ACCESS_TOKEN||""}`);const r={url:Gr(o),headers:{"Content-Type":"text/plain"}};this.pendingRequest=!0,h(r).then(()=>{this.pendingRequest=!1,i(null),this.saveEventData(),this.processRequests()}).catch(e=>{this.pendingRequest=!1,i(e),this.saveEventData(),this.processRequests()})}getSessionAPI(e,t,i,s){this.skuToken=t,this.errorCb=s,l.EVENTS_URL&&l.SESSION_PATH&&l.API_URL&&(i||l.ACCESS_TOKEN?this.queueRequest({id:e,timestamp:Date.now()},i):this.errorCb(new Error(Nr)))}processRequests(){if(this.pendingRequest||0===this.queue.length)return;const{id:e,timestamp:t,customAccessToken:i}=this.queue.shift();e&&this.success[e]||this.getSession(t,this.skuToken,t=>{t?this.errorCb(t):e&&(this.success[e]=!0)},i)}remove(){this.errorCb=null}},_n=un.getSessionAPI.bind(un),pn=new Set;function fn(e,t){t?pn.add(e):pn.delete(e)}function mn(e){return!function(e){return"undefined"!=typeof window&&"undefined"!=typeof document?Object.hasOwn?"undefined"==typeof Worker?"Web Workers not supported":function(){const e=document.createElement("canvas");e.width=e.height=1;const t=e.getContext("2d");return!!t&&t.getImageData(0,0,1,1).width===e.width}()?function(e){return e?(void 0===yn&&(yn=xn(!0)),yn):(void 0===vn&&(vn=xn(!1)),vn)}(e)?"":"insufficient WebGL2 support":"insufficient Canvas/getImageData support":"Object.hasOwn not supported":"not a browser"}(e)}const gn={antialias:!1,alpha:!0,stencil:!0,depth:!0};let vn,yn;function xn(e){const t=document.createElement("canvas"),i=Object.create(gn);i.failIfMajorPerformanceCaveat=e;const s=t.getContext("webgl2",i);if(!s)return!1;let o;try{o=s.createShader(s.VERTEX_SHADER)}catch(e){return!1}return!(!o||s.isContextLost())&&(s.shaderSource(o,"void main() {}"),s.compileShader(o),!0===s.getShaderParameter(o,s.COMPILE_STATUS))}const bn=/firefox/i,wn=/macintosh/i;function Tn(e,t,i){const s=document.createElement(e);return null!=t&&(s.className=t),i&&i.appendChild(s),s}function En(e,t,i){const s=document.createElementNS("http://www.w3.org/2000/svg",e);for(const e of Object.keys(t))s.setAttributeNS(null,e,String(t[e]));return i&&i.appendChild(s),s}const In="undefined"!=typeof document?document.documentElement&&document.documentElement.style:null,Sn=In&&void 0!==In.userSelect?"userSelect":"WebkitUserSelect";let Dn;function Rn(){In&&Sn&&(Dn=In[Sn],In[Sn]="none")}function Cn(){In&&Sn&&(In[Sn]=Dn)}function An(e){e.preventDefault(),e.stopPropagation(),window.removeEventListener("click",An,!0)}function Ln(){window.addEventListener("click",An,!0),window.setTimeout(()=>{window.removeEventListener("click",An,!0)},0)}function Pn(e,t){const i=e.getBoundingClientRect();return zn(e,i,t)}function Mn(e,t){const i=e.getBoundingClientRect(),s=[];for(let o=0;o<t.length;o++)s.push(zn(e,i,t[o]));return s}function On(e){return bn.test(navigator.userAgent)&&wn.test(navigator.userAgent)&&2===e.button&&e.ctrlKey?0:e.button}function zn(e,t,i){const s=e.offsetWidth===t.width?1:e.offsetWidth/t.width;return new m((i.clientX-t.left)*s,(i.clientY-t.top)*s)}class Fn{constructor(){this._changed=!1,this._updatedLayers=Object.create(null),this._removedLayers=Object.create(null),this._updatedSourceCaches=Object.create(null),this._updatedPaintProps=new Set,this._updatedImages=Object.create(null)}isDirty(){return this._changed}setDirty(){this._changed=!0}getUpdatedSourceCaches(){return this._updatedSourceCaches}updateSourceCache(e,t){this._updatedSourceCaches[e]=t,this.setDirty()}discardSourceCacheUpdate(e){delete this._updatedSourceCaches[e]}updateLayer(e){const t=e.scope;this._updatedLayers[t]=this._updatedLayers[t]||new Set,this._updatedLayers[t].add(e.id),this.setDirty()}removeLayer(e){const t=e.scope;this._removedLayers[t]=this._removedLayers[t]||{},this._updatedLayers[t]=this._updatedLayers[t]||new Set,this._removedLayers[t][e.id]=e,this._updatedLayers[t].delete(e.id),this._updatedPaintProps.delete(e.fqid),this.setDirty()}getRemovedLayer(e){return this._removedLayers[e.scope]?this._removedLayers[e.scope][e.id]:null}discardLayerRemoval(e){this._removedLayers[e.scope]&&delete this._removedLayers[e.scope][e.id]}getLayerUpdatesByScope(){const e={};for(const t in this._updatedLayers)e[t]=e[t]||{},e[t].updatedIds=Array.from(this._updatedLayers[t].values());for(const t in this._removedLayers)e[t]=e[t]||{},e[t].removedIds=Object.keys(this._removedLayers[t]);return e}getUpdatedPaintProperties(){return this._updatedPaintProps}updatePaintProperties(e){this._updatedPaintProps.add(e.fqid),this.setDirty()}getUpdatedImages(e){return this._updatedImages[e]?Array.from(this._updatedImages[e].values()):[]}updateImage(e,t){this._updatedImages[t]=this._updatedImages[t]||new Set,this._updatedImages[t].add(g.toString(e)),this.setDirty()}resetUpdatedImages(e){this._updatedImages[e]&&this._updatedImages[e].clear()}reset(){this._changed=!1,this._updatedLayers=Object.create(null),this._removedLayers=Object.create(null),this._updatedSourceCaches=Object.create(null),this._updatedPaintProps.clear(),this._updatedImages=Object.create(null)}}class kn{constructor(e){this._layer=e,this._filterDependencies=void 0}invalidateFilter(){this._filterDependencies=void 0}get _filterDeps(){return void 0===this._filterDependencies&&(this._filterDependencies=this._computeFilterDependencies()),this._filterDependencies}_computeFilterDependencies(){const e=this._layer;if(!e.type||"custom"===e.type||"background"===e.type||"sky"===e.type||"slot"===e.type||"placement-group"===e.type)return null;const t=v(e.filter,y[`filter_${e.type}`]);return"error"===t.result?null:{configDependencies:t.value.configDependencies,isIndoorDependent:t.value.isIndoorDependent}}hasConfigDependency(e){const t=t=>e?t.has(e):0!==t.size,{_layoutValues:i,_paintValues:s}=this._layer;if(i&&t(i.configDependencies))return!0;if(s&&t(s.configDependencies))return!0;for(const{unevaluatedLayout:e,unevaluatedPaint:i}of this._layer.appearances)if(e&&(t(e.configDependencies)||t(i.configDependencies)))return!0;const o=this._filterDeps;return!!o&&t(o.configDependencies)}get isIndoorDependent(){const{_layoutValues:e,_paintValues:t}=this._layer;if(e&&e.isIndoorDependent())return!0;if(t&&t.isIndoorDependent())return!0;const i=this._filterDeps;return!!i&&i.isIndoorDependent}}function Bn(e){const{userImage:t}=e;return!!(t&&t.render&&t.render())&&(e.data.replace(new Uint8Array(t.data.buffer)),!0)}const Nn=new S(0,0,0);function Un(e,t){const i=[],s=e[`stretch_${t}`];let o=null;for(let e=0;e<s.length;e++)null===o?o=0===i.length?s[0]:i.at(-1)[1]+s[e]:(i.push([o,o+s[e]]),o=null);e[`stretch_${t}_areas`]=i}function Vn(e,t){const i={name:void 0};let s;for(;s=e.nextField(t);)if(1===s)i.name=e.readString();else if(2===s)i.metadata=jn(e,e.readVarint()+e.pos);else if(3===s){const t=e.readVarint()+e.pos,s=e.pos;i.usvg_tree=Zn(e,t,!0),i.data="usvg_tree",i.pending_usvg_tree={buf:e.buf,start:s,end:t}}return function(e){if(e.usvg_tree.height||(e.usvg_tree.height=e.usvg_tree.width),!e.metadata)return e;const{metadata:t}=e;if(t.content_area){const{content_area:i}=t;i.left??=0,i.top??=i.left,i.width??=e.usvg_tree.width,i.height??=i.width}if(t.text_placeholder){const{text_placeholder:e}=t;e.top??=e.left,e.height??=e.width}return t.stretch_x&&t.stretch_x.length&&Un(t,"x"),t.stretch_y&&t.stretch_y.length&&Un(t,"y"),e}(i)}function jn(e,t){const i={stretch_x:null,stretch_y:null,stretch_x_areas:null,stretch_y_areas:null,variables:[]};let s;for(;s=e.nextField(t);)1===s?i.stretch_x=e.readPackedVarint():2===s?i.stretch_y=e.readPackedVarint():3===s?i.content_area=Gn(e,e.readVarint()+e.pos):4===s?i.variables.push(qn(e,e.readVarint()+e.pos)):5===s&&(i.text_placeholder=Gn(e,e.readVarint()+e.pos));return i}function Gn(e,t){const i={};let s;for(;s=e.nextField(t);)1===s?i.left=e.readVarint():2===s?i.width=e.readVarint():3===s?i.top=e.readVarint():4===s&&(i.height=e.readVarint());return i}function qn(e,t){const i={name:void 0};let s;for(;s=e.nextField(t);)1===s?i.name=e.readString():2===s&&(i.rgb_color=Jn(e.readVarint()),i.value="rgb_color");return i}function Zn(e,t,i){const s={width:20,children:[],linear_gradients:[],radial_gradients:[],clip_paths:[],masks:[],height:20};let o;for(;o=e.nextField(t);)if(1===o)s.width=s.height=e.readVarint();else if(2===o)s.height=e.readVarint();else{if(i)continue;3===o?s.children.push(Wn(e,e.readVarint()+e.pos)):4===o?s.linear_gradients.push(Qn(e,e.readVarint()+e.pos)):5===o?s.radial_gradients.push(ta(e,e.readVarint()+e.pos)):7===o?s.clip_paths.push(ia(e,e.readVarint()+e.pos)):8===o&&s.masks.push(sa(e,e.readVarint()+e.pos))}return s}function Wn(e,t){const i={};let s;for(;s=e.nextField(t);)1===s?(i.group=Hn(e,e.readVarint()+e.pos),i.node="group"):2===s&&(i.path=Xn(e,e.readVarint()+e.pos),i.node="path");return i}function Hn(e,t){const i={opacity:255,children:[]};let s;for(;s=e.nextField(t);)1===s?i.transform=$n(e,e.readVarint()+e.pos):2===s?i.opacity=e.readVarint():5===s?i.clip_path_idx=e.readVarint():6===s?i.mask_idx=e.readVarint():7===s&&i.children.push(Wn(e,e.readVarint()+e.pos));return i}function $n(e,t){const i={sx:1,ky:0,kx:0,sy:1,tx:0,ty:0};let s;for(;s=e.nextField(t);)1===s?i.sx=e.readFloat():2===s?i.ky=e.readFloat():3===s?i.kx=e.readFloat():4===s?i.sy=e.readFloat():5===s?i.tx=e.readFloat():6===s&&(i.ty=e.readFloat());return i}function Xn(e,t){const i={paint_order:1,commands:[],step:1,diffs:[],rule:1};let s;for(;s=e.nextField(t);)1===s?i.fill=Yn(e,e.readVarint()+e.pos):2===s?i.stroke=Kn(e,e.readVarint()+e.pos):3===s?i.paint_order=e.readVarint():5===s?e.readPackedVarint(i.commands):6===s?i.step=e.readFloat():7===s?e.readPackedSVarint(i.diffs):8===s&&(i.rule=e.readVarint());return i}function Yn(e,t){const i={rgb_color:Nn,paint:"rgb_color",opacity:255};let s;for(;s=e.nextField(t);)1===s?(i.rgb_color=Jn(e.readVarint()),i.paint="rgb_color"):2===s?(i.linear_gradient_idx=e.readVarint(),i.paint="linear_gradient_idx"):3===s?(i.radial_gradient_idx=e.readVarint(),i.paint="radial_gradient_idx"):5===s&&(i.opacity=e.readVarint());return i}function Kn(e,t){const i={rgb_color:Nn,paint:"rgb_color",dasharray:[],dashoffset:0,miterlimit:4,opacity:255,width:1,linecap:1,linejoin:1};let s;for(;s=e.nextField(t);)1===s?(i.rgb_color=Jn(e.readVarint()),i.paint="rgb_color"):2===s?(i.linear_gradient_idx=e.readVarint(),i.paint="linear_gradient_idx"):3===s?(i.radial_gradient_idx=e.readVarint(),i.paint="radial_gradient_idx"):5===s?e.readPackedFloat(i.dasharray):6===s?i.dashoffset=e.readFloat():7===s?i.miterlimit=e.readFloat():8===s?i.opacity=e.readVarint():9===s?i.width=e.readFloat():10===s?i.linecap=e.readVarint():11===s&&(i.linejoin=e.readVarint());return i}function Jn(e){return new S((e>>16&255)/255,(e>>8&255)/255,(255&e)/255,1)}function Qn(e,t){const i={spread_method:1,stops:[],x1:0,y1:0,x2:1,y2:0};let s;for(;s=e.nextField(t);)1===s?i.transform=$n(e,e.readVarint()+e.pos):2===s?i.spread_method=e.readVarint():3===s?i.stops.push(ea(e,e.readVarint()+e.pos)):4===s?i.x1=e.readFloat():5===s?i.y1=e.readFloat():6===s?i.x2=e.readFloat():7===s&&(i.y2=e.readFloat());return i}function ea(e,t){const i={offset:0,opacity:255,rgb_color:Nn};let s;for(;s=e.nextField(t);)1===s?i.offset=e.readFloat():2===s?i.opacity=e.readVarint():3===s&&(i.rgb_color=Jn(e.readVarint()));return i}function ta(e,t){const i={spread_method:1,stops:[],cx:.5,cy:.5,r:.5,fx:.5,fy:.5,fr:0};let s;for(;s=e.nextField(t);)1===s?i.transform=$n(e,e.readVarint()+e.pos):2===s?i.spread_method=e.readVarint():3===s?i.stops.push(ea(e,e.readVarint()+e.pos)):4===s?i.cx=e.readFloat():5===s?i.cy=e.readFloat():6===s?i.r=e.readFloat():7===s?i.fx=e.readFloat():8===s?i.fy=e.readFloat():9===s&&(i.fr=e.readFloat());return i}function ia(e,t){const i={children:[]};let s;for(;s=e.nextField(t);)1===s?i.transform=$n(e,e.readVarint()+e.pos):2===s?i.clip_path_idx=e.readVarint():3===s&&i.children.push(Wn(e,e.readVarint()+e.pos));return i}function sa(e,t){const i={left:0,width:20,mask_type:1,children:[]};let s;for(;s=e.nextField(t);)1===s?i.left=i.top=e.readFloat():2===s?i.width=i.height=e.readFloat():3===s?i.top=e.readFloat():4===s?i.height=e.readFloat():5===s?i.mask_type=e.readVarint():6===s?i.mask_idx=e.readVarint():7===s&&i.children.push(Wn(e,e.readVarint()+e.pos));return i.height??=i.width,i.top??=i.left,i}class oa{static calculate(e={},t=[]){const i=new Map,s=new Map;if(0===Object.keys(e).length)return i;t.forEach(e=>{s.set(e.name,e.rgb_color||new S(0,0,0))});for(const[t,o]of Object.entries(e))s.has(t)?i.set(s.get(t).toString(),o):console.warn(`Ignoring unknown image variable "${t}"`);return i}}function ra(e,t=255,i){const s=i.get(e.toString())||e;return 255===t?s.toString():new S(s.r,s.g,s.b,s.a*t/255).toString()}const na=[];let aa=0;function la(e,t){if(aa>=na.length){const i=D()?new OffscreenCanvas(e,t).getContext("2d",{willReadFrequently:!0}):document.createElement("canvas").getContext("2d",{willReadFrequently:!0});na.push(i)}const i=na[aa++];return i.canvas.width=e,i.canvas.height=t,i}function ca(){aa--}function ha(e,t,i,s,o){for(const r of s.children)da(e,t,i,r,o)}function da(e,t,i,s,o){s.group?(e.save(),function(e,t,i,s,o){const r=null!=s.mask_idx?i.masks[s.mask_idx]:null,n=null!=s.clip_path_idx?i.clip_paths[s.clip_path_idx]:null;if(s.transform&&(t=xa(s.transform).preMultiplySelf(t)),!function(e,t,i){return 255!==e.opacity||t||i}(s,null!=n,null!=r))return void ha(e,t,i,s,o);const a=la(e.canvas.width,e.canvas.height);ha(a,t,i,s,o),n&&va(a,t,i,n),r&&ya(a,t,i,r,o),e.globalAlpha=s.opacity/255,e.drawImage(a.canvas,0,0),ca()}(e,t,i,s.group,o),e.restore()):s.path&&(e.save(),function(e,t,i,s,o){e.setTransform(t),1===s.paint_order?(ua(e,i,s,o),pa(e,i,s,o)):(pa(e,i,s,o),ua(e,i,s,o))}(e,t,i,s.path,o),e.restore())}function ua(e,t,i,s){const o=i.fill;if(!o)return;const r=o.opacity/255;switch(e.save(),e.beginPath(),ba(i,e),o.paint){case"rgb_color":e.fillStyle=ra(o.rgb_color,o.opacity,s);break;case"linear_gradient_idx":{const i=t.linear_gradients[o.linear_gradient_idx];i.transform&&e.setTransform(xa(i.transform).preMultiplySelf(e.getTransform())),e.fillStyle=fa(e,i,r,s);break}case"radial_gradient_idx":{const i=t.radial_gradients[o.radial_gradient_idx];i.transform&&e.setTransform(xa(i.transform).preMultiplySelf(e.getTransform())),e.fillStyle=ma(e,i,r,s)}}e.fill(_a(i)),e.restore()}function _a(e){return 1===e.rule?"nonzero":2===e.rule?"evenodd":void 0}function pa(e,t,i,s){const o=i.stroke;if(!o)return;const r=2===o.linecap||3===o.linecap,n=ba(i,new Path2D,r?.001*o.width:0);e.lineWidth=o.width,e.miterLimit=o.miterlimit,e.setLineDash(o.dasharray),e.lineDashOffset=o.dashoffset;const a=o.opacity/255;switch(o.paint){case"rgb_color":e.strokeStyle=ra(o.rgb_color,o.opacity,s);break;case"linear_gradient_idx":e.strokeStyle=fa(e,t.linear_gradients[o.linear_gradient_idx],a,s,!0);break;case"radial_gradient_idx":e.strokeStyle=ma(e,t.radial_gradients[o.radial_gradient_idx],a,s,!0)}switch(o.linejoin){case 2:case 1:e.lineJoin="miter";break;case 3:e.lineJoin="round";break;case 4:e.lineJoin="bevel"}switch(o.linecap){case 1:e.lineCap="butt";break;case 2:e.lineCap="round";break;case 3:e.lineCap="square"}e.stroke(n)}function fa(e,t,i,s,o=!1){if(1===t.stops.length){const e=t.stops[0];return ra(e.rgb_color,e.opacity*i,s)}const{x1:r,y1:n,x2:a,y2:l}=t;let c=new DOMPoint(r,n),h=new DOMPoint(a,l);if(o){const e=xa(t.transform);c=e.transformPoint(c),h=e.transformPoint(h)}const d=e.createLinearGradient(c.x,c.y,h.x,h.y);for(const e of t.stops)d.addColorStop(e.offset,ra(e.rgb_color,e.opacity*i,s));return d}function ma(e,t,i,s,o=!1){if(1===t.stops.length){const e=t.stops[0];return ra(e.rgb_color,e.opacity*i,s)}const r=xa(t.transform),{fx:n,fy:a,fr:l,cx:c,cy:h,r:d}=t;let u=new DOMPoint(n,a),_=new DOMPoint(c,h),p=l,f=d;if(o){u=r.transformPoint(u),_=r.transformPoint(_);const e=(r.a+r.d)/2;p=l*e,f=t.r*e}const m=e.createRadialGradient(u.x,u.y,p,_.x,_.y,f);for(const e of t.stops)m.addColorStop(e.offset,ra(e.rgb_color,e.opacity*i,s));return m}function ga(e,t,i,s){const o=s.transform?xa(s.transform).preMultiplySelf(t):t,r=la(e.canvas.width,e.canvas.height);for(const e of s.children)if(e.group)ga(r,o,i,e.group);else if(e.path){const t=e.path,i=new Path2D;i.addPath(wa(t),o),r.fill(i,_a(t))}const n=null!=s.clip_path_idx?i.clip_paths[s.clip_path_idx]:null;n&&va(r,o,i,n),e.globalCompositeOperation="source-over",e.drawImage(r.canvas,0,0),ca()}function va(e,t,i,s){const o=la(e.canvas.width,e.canvas.height);ga(o,t,i,s),e.globalCompositeOperation="destination-in",e.drawImage(o.canvas,0,0),ca()}function ya(e,t,i,s,o){if(0===s.children.length)return;const r=null!=s.mask_idx?i.masks[s.mask_idx]:null;r&&ya(e,t,i,r,o);const n=e.canvas.width,a=e.canvas.height,l=la(n,a),c=s.width,h=s.height,d=s.left,u=s.top,_=new Path2D,p=new Path2D;p.rect(d,u,c,h),_.addPath(p,t),l.clip(_);for(const e of s.children)da(l,t,i,e,o);const f=l.getImageData(0,0,n,a),m=f.data;if(1===s.mask_type)for(let e=0;e<m.length;e+=4)m[e+3]=m[e+3]/255*(.2126*m[e]+.7152*m[e+1]+.0722*m[e+2]);l.putImageData(f,0,0),e.globalCompositeOperation="destination-in",e.drawImage(l.canvas,0,0),ca()}function xa(e){return e?new DOMMatrix([e.sx,e.ky,e.kx,e.sy,e.tx,e.ty]):new DOMMatrix}function ba(e,t,i=0){const s=e.step;let o=e.diffs[0]*s,r=e.diffs[1]*s;t.moveTo(o,r);let n=o,a=r,l=!1,c=!0;const h=()=>!(i<=0||!l||!c||(t.lineTo(n+i,a),0));for(let i=0,d=2;i<e.commands.length;i++)switch(e.commands[i]){case 1:h(),o+=e.diffs[d++]*s,r+=e.diffs[d++]*s,t.moveTo(o,r),n=o,a=r,l=!1,c=!0;break;case 2:o+=e.diffs[d++]*s,r+=e.diffs[d++]*s,t.lineTo(o,r),l=!0,c=c&&o===n&&r===a;break;case 3:{const i=o+e.diffs[d++]*s,h=r+e.diffs[d++]*s;o=i+e.diffs[d++]*s,r=h+e.diffs[d++]*s,t.quadraticCurveTo(i,h,o,r),l=!0,c=c&&i===n&&h===a&&o===n&&r===a;break}case 4:{const i=o+e.diffs[d++]*s,h=r+e.diffs[d++]*s,u=i+e.diffs[d++]*s,_=h+e.diffs[d++]*s;o=u+e.diffs[d++]*s,r=_+e.diffs[d++]*s,t.bezierCurveTo(i,h,u,_,o,r),l=!0,c=c&&i===n&&h===a&&u===n&&_===a&&o===n&&r===a;break}case 5:l=!0,h()?t.moveTo(n,a):t.closePath(),l=!1,c=!0}return h(),t}function wa(e){return ba(e,new Path2D)}class Ta{constructor(){this.cacheMap=new Map,this.cacheDependenciesMap=new Map}static _getImage(e){return new E(e,e.data)}getFromCache(e,t,i){return this.cacheMap.has(i)||this.cacheMap.set(i,new R(150)),this.cacheMap.get(i).get(C(e.toString(),t))}setInCache(e,t,i,s){this.cacheDependenciesMap.has(s)||this.cacheDependenciesMap.set(s,new Map),this.cacheMap.has(s)||this.cacheMap.set(s,new R(150));const o=this.cacheDependenciesMap.get(s),r=C(e.id.toString(),i);o.get(r)||o.set(r,new Set);const n=this.cacheMap.get(s),a=e.toString();o.get(r).add(a),n.put(C(e.toString(),i),t)}removeImagesFromCacheByIds(e,t,i=0){if(!this.cacheMap.has(i)||!this.cacheDependenciesMap.has(i))return;const s=this.cacheMap.get(i),o=this.cacheDependenciesMap.get(i);for(const i of e){const e=C(i.toString(),t);if(o.has(e)){for(const t of o.get(e))s.delete(t);o.delete(e)}}}rasterize(e,t,i,s){const o=this.getFromCache(e,i,s);if(o)return o.clone();!function(e){const t=e.pending_usvg_tree;if(!t)return;delete e.pending_usvg_tree;const i=new I(t.buf);i.pos=t.start,e.usvg_tree=Zn(i,t.end)}(t.icon);const r=function(e,t){const i=oa.calculate(t.params,e.metadata?e.metadata.variables:[]),s=e.usvg_tree,o=s.width,r=s.height,n=Math.max(1,Math.round(o*t.sx)),a=Math.max(1,Math.round(r*t.sy)),l=new DOMMatrix([n/o,0,0,a/r,0,0]),c=la(n,a);ha(c,l,s,s,i);const h=c.getImageData(0,0,n,a);return ca(),h}(t.icon,e),n=Ta._getImage(r);return this.setInCache(e,n,i,s),n.clone()}}class Ea extends A{constructor(e){super(),this.imageProviders=new Map,this.images=new Map,this.updatedImages=new Map,this.callbackDispatchedThisFrame=new Map,this.imageVersions=new Map,this.loaded=new Map,this.requestors=[],this.patterns=new Map,this.patternsInFlight=new Set,this.atlasImage=new Map,this.atlasTexture=new Map,this.imageAtlasCache=new L,this.dirty=!0,this.spriteFormat=e,this.imageRasterizer=new Ta}addScope(e){this.loaded.set(e,!1),this.imageProviders.set(e,new Map),this.images.set(e,new Map),this.updatedImages.set(e,new Set),this.callbackDispatchedThisFrame.set(e,new Set),this.imageVersions.set(e,new Map),this.patterns.set(e,new Map),this.atlasImage.set(e,new E({width:1,height:1}))}removeScope(e){this.loaded.delete(e),this.imageProviders.delete(e),this.images.delete(e),this.updatedImages.delete(e),this.callbackDispatchedThisFrame.delete(e),this.imageVersions.delete(e),this.patterns.delete(e),this.atlasImage.delete(e);const t=this.atlasTexture.get(e);t&&(t.destroy(),this.atlasTexture.delete(e))}addImageProvider(e,t){this.imageProviders.has(t)||this.imageProviders.set(t,new Map),this.imageProviders.get(t).set(e.id,e)}removeImageProvider(e,t){this.imageProviders.has(t)&&this.imageProviders.get(t).delete(e)}getPendingImageProviders(){const e=[];for(const t of this.imageProviders.values())for(const i of t.values())i.hasPendingRequests()&&e.push(i);return e}isLoaded(){for(const e of this.loaded.keys())if(!this.loaded.get(e))return!1;return!0}setLoaded(e,t){if(this.loaded.get(t)!==e&&(this.loaded.set(t,e),e)){for(const{ids:e,callback:i}of this.requestors)this._notify(e,t,i);this.requestors=[]}}hasImage(e,t){return!!this.getImage(e,t)}getImage(e,t){return this.images.get(t).get(e.toString())}addImage(e,t,i){if(this._validate(e,i)){this.images.get(t).set(e.toString(),i);const s=this.imageVersions.get(t),o=s.get(e.toString())||0;s.set(e.toString(),o+1)}}_validate(e,t){let i=!0;return this._validateStretch(t.stretchX,t.data&&t.data.width)||(this.fire(new P(new Error(`Image "${e.name}" has invalid "stretchX" value`))),i=!1),this._validateStretch(t.stretchY,t.data&&t.data.height)||(this.fire(new P(new Error(`Image "${e.name}" has invalid "stretchY" value`))),i=!1),this._validateContent(t.content,t)||(this.fire(new P(new Error(`Image "${e.name}" has invalid "content" value`))),i=!1),i}_validateStretch(e,t){if(!e)return!0;let i=0;for(const s of e){if(s[0]<i||s[1]<s[0]||t<s[1])return!1;i=s[1]}return!0}_validateContent(e,t){if(!e)return!0;if(4!==e.length)return!1;if(!t.usvg){if(e[0]<0||t.data.width<e[0])return!1;if(e[1]<0||t.data.height<e[1])return!1;if(e[2]<0||t.data.width<e[2])return!1;if(e[3]<0||t.data.height<e[3])return!1}return!(e[2]<e[0]||e[3]<e[1])}updateImage(e,t,i){const s=this.images.get(t).get(e.toString());i.version=s.version+1,this.images.get(t).set(e.toString(),i),this.updatedImages.get(t).add(e);const o=this.imageVersions.get(t),r=o.get(e.toString())||0;o.set(e.toString(),r+1),this.removeFromImageRasterizerCache(e,t)}clearUpdatedImages(e){this.updatedImages.get(e).clear()}removeFromImageRasterizerCache(e,t){"raster"!==this.spriteFormat&&this.imageRasterizer.removeImagesFromCacheByIds([e],t)}removeImage(e,t){const i=this.images.get(t),s=i.get(e.toString());i.delete(e.toString());const o=this.imageVersions.get(t),r=o.get(e.toString())||0;o.set(e.toString(),r+1),this.patterns.get(t).delete(e.toString()),this.removeFromImageRasterizerCache(e,t),s.userImage&&s.userImage.onRemove&&s.userImage.onRemove()}listImages(e){return Array.from(this.images.get(e).keys()).map(e=>g.from(e))}hasImageProviderForSource(e,t){const i=this.imageProviders.get(t);if(!i)return!1;for(const t of i.values())if(t.sourceCache.getSource().id===e)return!0;return!1}getImages(e,t,i){const s=[],o=[],r=this.imageProviders.get(t);for(const i of e){if(!i.iconsetId){s.push(i);continue}const e=r.get(i.iconsetId);e&&(this.getImage(i,t)?o.push(i):e.addPendingRequest(i))}if(0===s.length)return void this._notify(o,t,i);let n=!0;const a=!!this.loaded.get(t),l=this.images.get(t);if(!a)for(const e of s)l.has(e.toString())||(n=!1);a||n?this._notify(s,t,i):this.requestors.push({ids:s,scope:t,callback:i})}rasterizeImages(e,t){const i=new Map,{iconTasks:s,patternTasks:o,scope:r}=e;for(const e of[s,o])for(const[t,s]of e.entries()){const e=this.getImage(s.id,r);e&&i.set(t,{image:e,imageVariant:s})}t(null,this._rasterizeImages(r,i))}_rasterizeImages(e,t){const i=new Map;for(const[s,{image:o,imageVariant:r}]of t.entries())i.set(s,this.imageRasterizer.rasterize(r,o,e,0));return i}getUpdatedImages(e){return this.updatedImages.get(e)||new Set}_notify(e,t,i){const s=this.images.get(t),o=new Map,r=this.imageVersions.get(t),n=new Map;for(const t of e){if(!s.get(t.toString())){if(t.iconsetId)continue;this.fire(new M("styleimagemissing",{id:t.name}))}const e=s.get(t.toString());if(!e){_(`Image "${t.name}" 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.`);continue}const i={data:e.usvg?null:e.data.clone(),pixelRatio:e.pixelRatio,sdf:e.sdf,usvg:e.usvg,stretchX:e.stretchX,stretchY:e.stretchY,content:e.content,hasRenderCallback:Boolean(e.userImage&&e.userImage.render)};e.usvg&&Object.assign(i,{width:e.icon.usvg_tree.width,height:e.icon.usvg_tree.height});const a=g.toString(t);o.set(a,i);const l=r&&r.get(a);l&&n.set(a,l)}i(null,{images:o,versions:n})}getPixelSize(e){const{width:t,height:i}=this.atlasImage.get(e);return{width:t,height:i}}getPattern(e,t,i){const s=e.toString(),o=this.patterns.get(t),r=o.get(s),n=this.getImage(e,t);if(!n)return null;if(r){if(r.position.version===n.version)return r.position;r.position.version=n.version}else{if(n.usvg&&!n.data){const o=this.getPatternInFlightId(s,t);if(this.patternsInFlight.has(o))return null;this.patternsInFlight.add(o);const r=new O(e).scaleSelf(T.devicePixelRatio),a=new Map([[r.toString(),{image:n,imageVariant:r}]]),l=this._rasterizeImages(t,a);return this.storePatternImage(r,t,n,i,l),null}this.storePattern(e,t,n)}return this._updatePatternAtlas(t,i),o.get(s).position}getPatternInFlightId(e,t){return C(e,t)}hasPatternsInFlight(){return 0!==this.patternsInFlight.size}storePatternImage(e,t,i,s,o){const r=e.toString(),n=o?o.get(r):void 0;n&&(i.data=n,this.storePattern(e.id,t,i),this._updatePatternAtlas(t,s),this.patternsInFlight.delete(this.getPatternInFlightId(e.id.toString(),t)))}storePattern(e,t,i){const s={w:i.data.width+2*F,h:i.data.height+2*F,x:0,y:0},o=new z(s,i,F);this.patterns.get(t).set(e.toString(),{bin:s,position:o})}destroyAtlasTextures(){for(const e of this.atlasTexture.values())e&&e.destroy();this.atlasTexture.clear()}bind(e,t){const i=e.gl;let s=this.atlasTexture.get(t);s?this.dirty&&(s.update(this.atlasImage.get(t)),this.dirty=!1):(s=new k(e,this.atlasImage.get(t),i.RGBA8),this.atlasTexture.set(t,s)),s.bind(i.LINEAR,i.CLAMP_TO_EDGE)}_updatePatternAtlas(e,t){const i=this.patterns.get(e),s=Array.from(i.values()).map(({bin:e})=>e),{w:o,h:r}=B(s),n=this.atlasImage.get(e);n.resize({width:o||1,height:r||1});const a=this.images.get(e);for(const[e,{bin:s,position:o}]of i.entries()){let i=o.padding;const r=s.x+i,l=s.y+i,c=a.get(e).data,h=c.width,d=c.height;i=i>1?i-1:i,E.copy(c,n,{x:0,y:0},{x:r,y:l},{width:h,height:d},t),E.copy(c,n,{x:0,y:d-i},{x:r,y:l-i},{width:h,height:i},t),E.copy(c,n,{x:0,y:0},{x:r,y:l+d},{width:h,height:i},t),E.copy(c,n,{x:h-i,y:0},{x:r-i,y:l},{width:i,height:d},t),E.copy(c,n,{x:0,y:0},{x:r+h,y:l},{width:i,height:d},t),E.copy(c,n,{x:h-i,y:d-i},{x:r-i,y:l-i},{width:i,height:i},t),E.copy(c,n,{x:0,y:d-i},{x:r+h,y:l-i},{width:i,height:i},t),E.copy(c,n,{x:0,y:0},{x:r+h,y:l+d},{width:i,height:i},t),E.copy(c,n,{x:h-i,y:0},{x:r-i,y:l+d},{width:i,height:i},t)}this.dirty=!0}beginFrame(){for(const e of this.images.keys())this.callbackDispatchedThisFrame.set(e,new Set);this.imageAtlasCache.beginFrame()}dispatchRenderCallbacks(e,t){const i=this.images.get(t);for(const s of e){if(this.callbackDispatchedThisFrame.get(t).has(s.toString()))continue;this.callbackDispatchedThisFrame.get(t).add(s.toString());const e=i.get(s.toString());Bn(e)&&this.updateImage(s,t,e)}}}class Ia{constructor(e){this.pendingRequests=new Map,this.cachedRanges=new Map,this.fontstackCompositing=e&&e.fontstackCompositing||"client"}loadGlyphRange(e,t,i,s,o){if("server"===this.fontstackCompositing)return void Ia.loadGlyphRange(e,t,i,s,o);const r=e.split(",").map(e=>e.trim()).filter(e=>e.length>0);0!==r.length?1!==r.length?this._loadMultipleFonts(r,t,i,s,o):this._loadFont(r[0],t,i,s,o):o(new Error("Empty fontstack"))}_loadMultipleFonts(e,t,i,s,o){const r=e.map(()=>null),n={completed:0,firstError:null,callbackCalled:!1},a=(t,i,s)=>{if(!n.callbackCalled&&(i&&!n.firstError&&(n.firstError=i),s&&(r[t]=s),n.completed++,n.completed===e.length)){n.callbackCalled=!0;const e=r.filter(e=>null!==e);if(0===e.length)return void o(n.firstError||new Error("All fonts failed to load"));const t=this._composeGlyphs(e);o(null,t)}};for(let o=0;o<e.length;o++)this._loadFont(e[o],t,i,s,(e,t)=>{a(o,e,t)})}_loadFont(e,t,i,s,o){const r=`${i}:${e}:${t}`;if(this.cachedRanges.has(r)){const e=this.cachedRanges.get(r);return void T.frame(()=>o(null,e))}const n=this.pendingRequests.get(r);n?n.push(o):(this.pendingRequests.set(r,[o]),Ia.loadGlyphRange(e,t,i,s,(e,t)=>{e||this.cachedRanges.set(r,t||null);const i=this.pendingRequests.get(r);if(this.pendingRequests.delete(r),i)for(const s of i)s(e,t)}))}_composeGlyphs(e){const t={};let i,s;for(const o of e)if(void 0===i&&void 0!==o.ascender&&(i=o.ascender),void 0===s&&void 0!==o.descender&&(s=o.descender),o.glyphs)for(const e in o.glyphs)void 0===t[e]&&(t[e]=o.glyphs[e]);return{glyphs:t,ascender:i,descender:s}}}Ia.loadGlyphRange=async function(e,t,i,s,o){const r=256*t,n=r+255;let a;try{const t=await s.transformRequest(s.normalizeGlyphsURL(i).replace("{fontstack}",e).replace("{range}",`${r}-${n}`),x.Glyphs),{data:o}=await N(t),l={},c=U(o);for(const e of c.glyphs)l[e.id]=e;a={glyphs:l,ascender:c.ascender,descender:c.descender}}catch(e){return o(e)}o(null,a)};class Sa{constructor(e,t,i,s){this.requestManager=e,this.localGlyphs=new V({mode:t,fontFamily:i}),this.url="",this.entries={},this.glyphLoader=new Ia({fontstackCompositing:s})}setURL(e){e!==this.url&&(this.url=e,this.entries={})}getGlyphs(e,t){const i=[],s=Object.keys(e),o=this.url||l.GLYPHS_URL;for(const t in e)for(const s of e[t])i.push({stack:t,id:s});j(i,({stack:e,id:t},i)=>{let s=this.entries[e];s||(s=this.entries[e]={glyphs:{},requests:{},ranges:{},ascender:void 0,descender:void 0});let r=s.glyphs[t];if(void 0!==r)return void i(null,{stack:e,id:t,glyph:r});if(r=this.localGlyphs.draw(e,t),r)return s.glyphs[t]=r,void i(null,{stack:e,id:t,glyph:r});const n=Math.floor(t/256);if(256*n>65535)return _("glyphs > 65535 not supported"),void i(null,{stack:e,id:t,glyph:r});if(s.ranges[n])return void i(null,{stack:e,id:t,glyph:r});let a=s.requests[n];a||(a=s.requests[n]=[],this.glyphLoader.loadGlyphRange(e,n,o,this.requestManager,(e,t)=>{if(t){s.ascender=t.ascender,s.descender=t.descender;for(const e in t.glyphs)this.localGlyphs.supports(+e)||(s.glyphs[+e]=t.glyphs[+e]);s.ranges[n]=!0}for(const i of a)i(e,t);delete s.requests[n]})),a.push((s,o)=>{s?i(s):o&&i(null,{stack:e,id:t,glyph:o.glyphs[t]||null})})},(e,i)=>{if(e)t(e);else if(i){const e={};for(const t of s){const i=this.entries[t];e[t]={glyphs:{},ascender:i&&i.ascender,descender:i&&i.descender}}for(const{stack:t,id:s,glyph:o}of i)e[t].glyphs[s]=o&&{id:o.id,bitmap:o.bitmap.clone(),metrics:o.metrics};t(null,e)}})}}class Da{constructor(e,t,i,s){this.message=(e?`${e}: `:"")+i,s&&(this.identifier=s),null!=t&&t.__line__&&(this.line=t.__line__)}}class Ra extends Da{}const Ca={loaded:!1};let Aa=null;function La(){return null!==Aa||(Aa=import("./debug.js").then(({DebugModule:e})=>{Object.assign(Ca,e)}).catch(()=>{_("Could not load Debug module; style validation is disabled.")})),Aa}function Pa(e,t){let i=!1;if(t&&t.length)for(const s of t)s instanceof Ra?_(s.message):(e.fire(new P(new Error(s.message))),i=!0);return i}function Ma(e){return(...t)=>{const i=Ca[e];return i?i(...t):[]}}const Oa=Ma("validateStyle"),za=Ma("validateSource"),Fa=Ma("validateLight"),ka=Ma("validateLights"),Ba=Ma("validateTerrain"),Na=Ma("validateFog"),Ua=Ma("validateSnow"),Va=Ma("validateRain"),ja=Ma("validateLayer"),Ga=Ma("validateFilter"),qa=Ma("validatePaintProperty"),Za=Ma("validateLayoutProperty"),Wa=Ma("validateModel");class Ha extends A{constructor(e,t,i){super(),this.scope=t,this._transitionable=new G(e,t,i),this.properties=new q(e)}_setValues(e,t){this._values=e,this._transitionable.setTransitionOrValue(e,t?new Map(t):void 0)}updateConfig(e){this._transitionable.setTransitionOrValue(this._values,new Map(e))}resetConfig(e){this.updateConfig(e),this._transitionable.snap()}updateTransitions(e){this._transitionable.updateTransitions(e)}hasTransition(){return this._transitionable.hasTransition()}recalculate(e){this.properties=this._transitionable.possiblyEvaluate(e)}_validate(e,t,i){return(!i||!1!==i.validate)&&Pa(this,e.call(Oa,{value:t,style:{glyphs:!0,sprite:!0},styleSpec:y}))}}const $a=y.light;let Xa;class Ya extends Ha{constructor(e,t="flat"){super(Xa||(Xa=new Z({anchor:new W($a.anchor),position:new H($a.position),color:new W($a.color),intensity:new W($a.intensity)}))),this.setLight(e,t),this._transitionable.snap()}getLight(){return this._transitionable.serialize()}setLight(e,t,i={}){this._validate(Fa,e,i)||(this._setValues(e),this.id=t)}}const Ka=y.terrain,Ja={deferred:0,elevated:1};class Qa extends Ha{constructor(e,t,i,s,o){super(new Z({source:new W(Ka.source),exaggeration:new W(Ka.exaggeration)}),i,s),this._transitionable.setTransitionOrValue(e,s),this._transitionable.snap(),this.drapeRenderMode=t,this.worldview=o}get(){return this._transitionable.serialize()}set(e,t){this._transitionable.setTransitionOrValue(e,t)}getExaggeration(e){return $(this._transitionable._values.exaggeration.state,new X(e,{worldview:this.worldview}))}getAttenuationRange(){if(!this.isZoomDependent())return null;const e=this._transitionable._values.exaggeration.value.expression;let t=-1,i=-1,s=1;for(const o of e.zoomStops)s=e.evaluate(new X(o,{worldview:this.worldview})),s>.01?(t=o,i=-1):i=o;return s<.01&&t>0&&i>t?[t,i]:null}isZoomDependent(){return this._transitionable._values.exaggeration.value.expression instanceof Y}}function el(e,t){const i=e?e.terrain:null;return!!i&&(!t||!!t.projection.requiresDraping||!i.isZoomDependent()||i.getExaggeration(t.zoom)>0)}const tl=y.fog;class il extends Ha{constructor(e,t,i,s){super(new Z({range:new W(tl.range),color:new W(tl.color),"color-use-theme":new W({type:"string","property-type":"data-constant",default:"default"}),"high-color":new W(tl["high-color"]),"high-color-use-theme":new W({type:"string","property-type":"data-constant",default:"default"}),"space-color":new W(tl["space-color"]),"space-color-use-theme":new W({type:"string","property-type":"data-constant",default:"default"}),"horizon-blend":new W(tl["horizon-blend"]),"star-intensity":new W(tl["star-intensity"]),"vertical-range":new W(tl["vertical-range"])}),i,new Map(s)),this._transform=t,this.set(e),this._transitionable.snap()}get state(){const e=this._transform,t="globe"===e.projection.name,i=K(e.zoom),s=this.properties.get("range"),o=[2,4.5],r=.5/Math.tan(.5*e._fov),n=[s[0]+r,s[1]+r];return{range:t?[J(o[0],n[0],i),J(o[1],n[1],i)]:n,horizonBlend:this.properties.get("horizon-blend"),alpha:this.properties.get("color").a}}get(){return this._transitionable.serialize()}set(e,t,i={}){if(this._validate(Na,e,i))return;const s={...e};for(const e of Object.keys(tl))void 0===s[e]&&(s[e]=tl[e].default);this._setValues(s,t)}getOpacity(e){if(!this._transform.projection.supportsFog)return 0;const t=this.properties&&this.properties.get("color")||1;return("globe"===this._transform.projection.name?1:Q(te,ee,e))*t.a}getOpacityAtLatLng(e,t){return this._transform.projection.supportsFog?ie(this.state,e,t):0}getOpacityForTile(e){if(!this._transform.projection.supportsFog)return[1,1];const t=this._transform.calculateFogTileMatrix(e.toUnwrapped());return se(this.state,t,0,0,ae,ae,this._transform)}getOpacityForBounds(e,t,i,s,o){return this._transform.projection.supportsFog?se(this.state,e,t,i,s,o,this._transform):[1,1]}getRangeForProjection(){return this._transform.projection.supportsFog?this.state.range:[0,1]}isVisibleOnFrustum(e){if(!this._transform.projection.supportsFog)return!1;const t=[4,5,6,7];for(const i of t){const t=e.points[i];let s;if(t[2]>=0)s=t;else{const o=e.points[i-4];s=oe(o,t,o[2]/(o[2]-t[2]))}if(re(this.state,s[0],s[1],0,this._transform)>=ne)return!0}return!1}}let sl,ol;class rl extends Ha{constructor(e,t,i,s){super(sl||(sl=new Z({density:new W(y.snow.density),intensity:new W(y.snow.intensity),color:new W(y.snow.color),opacity:new W(y.snow.opacity),vignette:new W(y.snow.vignette),"vignette-color":new W(y.snow["vignette-color"]),"center-thinning":new W(y.snow["center-thinning"]),direction:new W(y.snow.direction),"flake-size":new W(y.snow["flake-size"])})),i,new Map(s)),this.set(e),this._transitionable.snap()}get state(){const e=this.properties.get("opacity"),t=this.properties.get("color"),i=this.properties.get("direction"),s=le(i[0]),o=-Math.max(le(i[1]),.01),r=[Math.cos(s)*Math.cos(o),Math.sin(s)*Math.cos(o),Math.sin(o)],n=this.properties.get("vignette"),a=this.properties.get("vignette-color"),l=new S(a.r,a.g,a.b,n);return{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new S(t.r,t.g,t.b,t.a*e),direction:r,centerThinning:this.properties.get("center-thinning"),flakeSize:this.properties.get("flake-size"),vignetteColor:l}}get(){return this._transitionable.serialize()}set(e,t,i={}){if(this._validate(Ua,e,i))return;const s={...e},o=y.snow;for(const e of Object.keys(o))void 0===s[e]&&(s[e]=o[e].default);this._setValues(s,t)}}class nl extends Ha{constructor(e,t,i,s){super(ol||(ol=new Z({density:new W(y.rain.density),intensity:new W(y.rain.intensity),color:new W(y.rain.color),opacity:new W(y.rain.opacity),vignette:new W(y.rain.vignette),"vignette-color":new W(y.rain["vignette-color"]),"center-thinning":new W(y.rain["center-thinning"]),direction:new W(y.rain.direction),"droplet-size":new W(y.rain["droplet-size"]),"distortion-strength":new W(y.rain["distortion-strength"])})),i,new Map(s)),this.set(e),this._transitionable.snap()}get state(){const e=this.properties.get("opacity"),t=this.properties.get("color"),i=this.properties.get("direction"),s=le(i[0]),o=-Math.max(le(i[1]),.01),r=[Math.cos(s)*Math.cos(o),Math.sin(s)*Math.cos(o),Math.sin(o)],n=this.properties.get("vignette-color"),a=new S(n.r,n.g,n.b,this.properties.get("vignette"));return{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new S(t.r,t.g,t.b,t.a*e),direction:r,centerThinning:this.properties.get("center-thinning"),dropletSize:this.properties.get("droplet-size"),distortionStrength:this.properties.get("distortion-strength"),vignetteColor:a}}get(){return this._transitionable.serialize()}set(e,t,i={}){if(this._validate(Va,e,i))return;const s={...e},o=y.rain;for(const e of Object.keys(o))void 0===s[e]&&(s[e]=o[e].default);this._setValues(s,t)}}const al={workerUrl:""};function ll(e){al.workerUrl=e}function cl(){return al.workerUrl?new Worker(al.workerUrl,{type:"module"}):new Worker(new URL("worker.js",import.meta.url),{type:"module"})}const hl="mapboxgl_preloaded_worker_pool";class dl{constructor(e){this.active={},this.workers=null,this.name=e}acquire(e,t=dl.workerCount){if(!this.workers)for(this.workers=[];this.workers.length<t;){const e=cl();this.workers.push(e)}return this.active[e]=!0,this.workers.slice()}release(e){delete this.active[e],this.workers&&0===this.numActive()&&(this.workers.forEach(e=>{e.terminate()}),this.workers=null)}isPreloaded(){return!!this.active[hl]}numActive(){return Object.keys(this.active).length}}function ul(){return dl.workerCount}function _l(e){dl.workerCount=e}dl.workerCount=2;class pl{constructor(e,t,i="Worker",s=dl.workerCount){this.workerPool=e,this.actors=[],this.currentActor=0,this.id=ce();const o=this.workerPool.acquire(this.id,s);for(let e=0;e<o.length;e++){const s=new pl.Actor(o[e],t,this.id);s.name=`${i} ${e}`,this.actors.push(s)}this.ready=!1,this.send("checkIfReady",null).then(()=>{this.ready=!0}).catch(()=>{})}send(e,t,i){return Promise.all(this.actors.map(s=>s.send(e,t,i)))}broadcast(e,t){for(const i of this.actors)i.notify(e,t)}getActor(){return this.currentActor=(this.currentActor+1)%this.actors.length,this.actors[this.currentActor]}remove(){this.actors.forEach(e=>{e.remove()}),this.actors=[],this.workerPool.release(this.id)}}pl.Actor=he;class fl extends Ha{constructor(e,t,i,s){super(t,i,new Map(s)),this.set(e),this._transitionable.snap()}get(){return this._options.properties=this._transitionable.serialize(),this._options}set(e,t){this._options=e,this._setValues(e.properties,t)}shadowsEnabled(){return!!this.properties&&!0===this.properties.get("cast-shadows")}}let ml;const gl=()=>ml||(ml=new Z({color:new W(y.properties_light_ambient.color),"color-use-theme":new W({type:"string",default:"default","property-type":"data-constant"}),intensity:new W(y.properties_light_ambient.intensity)}));let vl;const yl=()=>vl||(vl=new Z({direction:new de(y.properties_light_directional.direction),color:new W(y.properties_light_directional.color),"color-use-theme":new W({type:"string",default:"default","property-type":"data-constant"}),intensity:new W(y.properties_light_directional.intensity),"cast-shadows":new W(y.properties_light_directional["cast-shadows"]),"shadow-quality":new W(y.properties_light_directional["shadow-quality"]),"shadow-intensity":new W(y.properties_light_directional["shadow-intensity"]),"shadow-draw-before-layer":new W(y.properties_light_directional["shadow-draw-before-layer"])}));function xl(e,t){let i=null,s=null;const o={globals:{zoom:0}};e.forEachFragmentStyle(t=>{if(i)return;const r=t.stylesheet?t.stylesheet.schema:null;if(!r||!r.sdCoverageFadeRange)return;const n=C("sdCoverageFadeRange",t.scope),a=t.options?t.options.get(n):void 0,l=a?a.value||a.default:null;if(l){const e=l.evaluate(o);Array.isArray(e)&&2===e.length&&(e[0]>0||e[1]>0)&&(i=[e[0],e[1]])}const c=C("sdCoverageSourceLayers",t.scope),h=t.options?t.options.get(c):void 0,d=h?h.value||h.default:null;if(d){const e=d.evaluate(o);Array.isArray(e)&&e.length>0&&(s=e)}else{const i=e.stylesheet&&e.stylesheet.imports||[];for(const e of i)if(e.id===t.scope){const t=e.config?e.config.sdCoverageSourceLayers:void 0;Array.isArray(t)&&t.length>0&&(s=t);break}}}),t.frcCoverageFadeRange=i,t.frcCoverageSourceLayers=null!=i?s||["road","structure"]:[]}function bl(e,t){if(e.z<=t.z){const i=t.z-e.z;return t.x>>i===e.x&&t.y>>i===e.y}const i=e.z-t.z;return e.x>>i===t.x&&e.y>>i===t.y}function wl(e,t){return e.sourceFQID!==t.sourceFQID?e.sourceFQID<t.sourceFQID?-1:1:e.tileId.z!==t.tileId.z?e.tileId.z-t.tileId.z:e.tileId.x!==t.tileId.x?e.tileId.x-t.tileId.x:e.tileId.y-t.tileId.y}class Tl{constructor(e=[]){this.tiles=e}getTilesIntersecting(e){const t=[];for(const i of this.tiles)bl(i.tileId,e)&&t.push(i);return t}equals(e){if(this.tiles.length!==e.length)return!1;for(let t=0;t<this.tiles.length;++t){const i=this.tiles[t],s=e[t];if(i.sourceFQID!==s.sourceFQID||i.tileId.z!==s.tileId.z||i.tileId.x!==s.tileId.x||i.tileId.y!==s.tileId.y||i.generation!==s.generation)return!1}return!0}empty(){return 0===this.tiles.length}}function El(e,t,i){if(el(e.style,e.transform))return null;if(!i)return null;const s=e.painter?e.painter.elevationCoverageSnapshot:null,o=!(!e.painter||!e.painter.elevationProvidersReady);return s?function(e,t,i){const s=e.getTilesIntersecting(t);if(0===s.length)return{registry:[],hasCoveringTile:!1,allProvidersReady:i};const o=[];for(const e of s)for(const t of e.features)o.push({tileId:e.tileId,feature:t});return o.sort((e,t)=>e.feature.id-t.feature.id),{registry:o,hasCoveringTile:!0,allProvidersReady:i}}(s,t.tileID.canonical,o):{registry:[],hasCoveringTile:!1,allProvidersReady:o}}const Il={updateFrcCoverageFadeRange:xl,buildElevationRequestParams:El};let Sl=null;function Dl(){return null!==Sl||(Sl=import("./hd.main.js").then(({HD:e})=>{Object.assign(Il,e)}).catch(()=>{Sl=null,_("Could not load HD module.")})),Sl}let Rl=null;function Cl(){return null!==Rl||(Rl=import("./standard.main.js").then(({Standard:e})=>{Object.assign(ue,e)}).catch(()=>{Rl=null,_("Could not load Standard module.")})),Rl}const Al={};let Ll=null;const Pl={};let Ml=null;function Ol(){return null!==Ml||(Ml=import("./raster_array.main.js").then(({RasterArray:e})=>{Object.assign(Pl,e)}).catch(()=>{Ml=null,_("Could not load raster-array module.")})),Ml}class zl{constructor(e,t,i){this.screenBounds=e,this.cameraPoint=i.getCameraPoint(),this._screenRaycastCache={},this._cameraRaycastCache={},this.isAboveHorizon=t,this.screenGeometry=this.bufferedScreenGeometry(0),this.screenGeometryMercator=this._bufferedScreenMercator(0,i)}static createFromScreenPoints(e,t){let i,s;if(e instanceof m||"number"==typeof e[0]){const o=m.convert(e);i=[o],s=t.isPointAboveHorizon(o)}else{const o=m.convert(e[0]),r=m.convert(e[1]),n=o.add(r)._div(2);i=[o,r],s=_e(o,r).every(e=>t.isPointAboveHorizon(e))&&t.isPointAboveHorizon(n)}return new zl(i,s,t)}isPointQuery(){return 1===this.screenBounds.length}bufferedScreenGeometry(e){return _e(this.screenBounds[0],1===this.screenBounds.length?this.screenBounds[0]:this.screenBounds[1],e)}bufferedCameraGeometry(e){const t=this.screenBounds[0],i=1===this.screenBounds.length?this.screenBounds[0].add(new m(1,1)):this.screenBounds[1],s=_e(t,i,0,!1);return this.cameraPoint.y>i.y&&(this.cameraPoint.x>t.x&&this.cameraPoint.x<i.x?s.splice(3,0,this.cameraPoint):this.cameraPoint.x>=i.x?s[2]=this.cameraPoint:this.cameraPoint.x<=t.x&&(s[3]=this.cameraPoint)),pe(s,e)}bufferedCameraGeometryGlobe(e){const t=this.screenBounds[0],i=1===this.screenBounds.length?this.screenBounds[0].add(new m(1,1)):this.screenBounds[1],s=_e(t,i,e),o=this.cameraPoint.clone(),r=Number(o.x>t.x)+Number(o.x>i.x);switch(3*(Number(o.y>t.y)+Number(o.y>i.y))+r){case 0:s[0]=o,s[4]=o.clone();break;case 1:s.splice(1,0,o);break;case 2:s[1]=o;break;case 3:s.splice(4,0,o);break;case 5:s.splice(2,0,o);break;case 6:s[3]=o;break;case 7:s.splice(3,0,o);break;case 8:s[2]=o}return s}containsTile(e,t,i,s=0,o){const r=Math.max(e.queryPadding,e.evaluateQueryRenderedFeaturePadding())/t._pixelsPerMercatorPixel+1,n=i?this._bufferedCameraMercator(r,t):this._bufferedScreenMercator(r,t);let a=e.tileID.wrap+(n.unwrapped?s:0);const l=n.polygon.map(t=>fe(e.tileTransform,t,a));if(!me(l,0,0,ae,ae))return;a=e.tileID.wrap+(this.screenGeometryMercator.unwrapped?s:0);const c=this.screenGeometryMercator.polygon.map(t=>ge(e.tileTransform,t,a)),h=c.map(e=>new m(e[0],e[1])),d=ge(e.tileTransform,o,a),u=c.map(e=>{const t=ve(e,e,d);return ye(t,t),new xe(d,t)}),_=Te(e,1,t.zoom)*t._pixelsPerMercatorPixel;return{queryGeometry:this,tilespaceGeometry:h,tilespaceRays:u,bufferedTilespaceGeometry:l,bufferedTilespaceBounds:(p=be(l),p.min.x=Ee(p.min.x,0,ae),p.min.y=Ee(p.min.y,0,ae),p.max.x=Ee(p.max.x,0,ae),p.max.y=Ee(p.max.y,0,ae),p),tile:e,tileID:e.tileID,pixelToTileUnitsFactor:_};var p}_bufferedScreenMercator(e,t){const i=Bl(e);if(this._screenRaycastCache[i])return this._screenRaycastCache[i];{let s;return s="globe"===t.projection.name?this._projectAndResample(this.bufferedScreenGeometry(e),t):{polygon:this.bufferedScreenGeometry(e).map(e=>t.pointCoordinate3D(e)),unwrapped:!0},this._screenRaycastCache[i]=s,s}}_bufferedCameraMercator(e,t){const i=Bl(e);if(this._cameraRaycastCache[i])return this._cameraRaycastCache[i];{let s;return s="globe"===t.projection.name?this._projectAndResample(this.bufferedCameraGeometryGlobe(e),t):{polygon:this.bufferedCameraGeometry(e).map(e=>t.pointCoordinate3D(e)),unwrapped:!0},this._cameraRaycastCache[i]=s,s}}_projectAndResample(e,t){const i=function(e,t){const i=Ie([],t.pixelMatrix,t.globeMatrix),s=[0,-De,0,1],o=[0,De,0,1],r=[0,0,0,1];Se(s,s,i),Se(o,o,i),Se(r,r,i);const n=new m(s[0]/s[3],s[1]/s[3]),a=new m(o[0]/o[3],o[1]/o[3]),l=Re(e,n)&&s[3]<r[3],c=Re(e,a)&&o[3]<r[3];if(!l&&!c)return null;const h=function(e,t,i){for(let s=1;s<e.length;s++){const o=kl(t.pointCoordinate3D(e[s-1]).x),r=kl(t.pointCoordinate3D(e[s]).x);if(i<0){if(o<r)return{idx:s,t:-o/(r-1-o)}}else if(r<o)return{idx:s,t:(1-o)/(r+1-o)}}return null}(e,t,l?-1:1);if(!h)return null;const{idx:d,t:u}=h;let _=d>1?Fl(e.slice(0,d),t):[],p=d<e.length?Fl(e.slice(d),t):[];_=_.map(e=>new m(kl(e.x),e.y)),p=p.map(e=>new m(kl(e.x),e.y));const f=[..._];0===f.length&&f.push(p.at(-1));const g=f.at(-1),v=J(g.y,(0===p.length?_[0]:p[0]).y,u);let y;return y=l?[new m(0,v),new m(0,0),new m(1,0),new m(1,v)]:[new m(1,v),new m(1,1),new m(0,1),new m(0,v)],f.push(...y),0===p.length?f.push(_[0]):f.push(...p),{polygon:f.map(e=>new we(e.x,e.y)),unwrapped:!1}}(e,t);if(i)return i;const s=function(e,t){let i=!1,s=-1/0,o=0;for(let t=0;t<e.length-1;t++)e[t].x>s&&(s=e[t].x,o=t);for(let t=0;t<e.length-1;t++){const s=(o+t)%(e.length-1),r=e[s],n=e[s+1];Math.abs(r.x-n.x)>.5&&(r.x<n.x?(r.x+=1,0===s&&(e.at(-1).x+=1)):(n.x+=1,s+1===e.length-1&&(e[0].x+=1)),i=!0)}const r=Ae(t.center.lng);return i&&r<Math.abs(r-1)&&e.forEach(e=>{e.x-=1}),{polygon:e,unwrapped:i}}(Fl(e,t).map(e=>new m(kl(e.x),e.y)),t);return{polygon:s.polygon.map(e=>new we(e.x,e.y)),unwrapped:s.unwrapped}}}function Fl(e,t){return Ce(e,e=>{const i=t.pointCoordinate3D(e);e.x=i.x,e.y=i.y},1/256)}function kl(e){return e<0?1+e%1:e%1}function Bl(e){return 100*e|0}function Nl(e,t){const i=Math.pow(2,t.z),s=Math.floor(Ae(e.getWest())*i),o=Math.floor(Pe(e.getNorth())*i),r=Math.ceil(Ae(e.getEast())*i),n=Math.ceil(Pe(e.getSouth())*i);return t.x>=s&&t.x<r&&t.y>=o&&t.y<n}class Ul{constructor(e){this.bounds=e.bounds?Le.convert(this.validateBounds(e.bounds)):null,this.extraBounds=e.extra_bounds&&e.extra_bounds.length>0?e.extra_bounds.map(e=>Le.convert(this.validateBounds(e))):null,this.minzoom=e.minzoom||0,this.maxzoom=e.maxzoom||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){if(e.z>this.maxzoom||e.z<this.minzoom)return!1;if(this.bounds&&!Nl(this.bounds,e))return!1;if(!this.extraBounds)return!0;for(const t of this.extraBounds)if(Nl(t,e))return!0;return!1}}function Vl(e){return e&&r(e)?"id":null}class jl extends A{constructor(e,t,i,s){super(),this.id=e,this.dispatcher=i,this.setEventedParent(s),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme="xyz",this.tileSize=512,this._loaded=!1,this._options={type:"raster",...t},Object.assign(this,Me(t,["url","scheme","tileSize"]))}load(e){this._loaded=!1,this.fire(new M("dataloading",{dataType:"source"}));const t=this.map.getWorldview(),i=(t,i)=>{this._tileJSONRequest=null,this._loaded=!0,t?this.fire(new P(t)):i&&(Object.assign(this,i),i.raster_layers&&(this.rasterLayers=i.raster_layers,this.rasterLayerIds=this.rasterLayers.map(e=>e.id)),this.tileBounds=new Ul(i),en(i.tiles),this.fire(new M("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new M("data",{dataType:"source",sourceDataType:"content"}))),e&&e(t)};this.provider="string"==typeof this._options.provider?this._options.provider:void 0,this._tileProvider=void 0;const s=ze(this._options);return s instanceof Error?(this._loaded=!0,this.fire(new P(s)),void(e&&e())):this.provider&&!s?(this._loaded=!0,this.fire(new P(new Error(`TileProvider "${this.provider}" is not registered`))),void(e&&e())):void(this._tileJSONRequest=s?this.loadTileJSONWithProvider(s,i):Fe(this._options,this.map._requestManager,null,t,i))}loadTileJSONWithProvider(e,t){this.provider=e.name;const i=new AbortController;return(async()=>{const{request:s,options:o}=await Ue(this._options,this.map._requestManager,i.signal);if(i.signal.aborted)return;const r=await je(e.name,e.url);if(i.signal.aborted)return;const n=new r(o);let a=null;if(n.load&&s&&(a=await n.load({request:s}),i.signal.aborted))return;this._tileProvider=n;const l=Ve(this._options,a,this.map._requestManager);l instanceof Error?t(l):t(null,l)})().catch(s=>{i.signal.aborted||t(new Error(`Could not load tile provider ${e.name}`,{cause:s}))}),{cancel:()=>i.abort()}}loaded(){return this._loaded}onAdd(e){this.map=e,this.load()}reload(){this.cancelTileJSONRequest();const e=C(this.id,this.scope);this.load(()=>this.map.style.clearSource(e))}setTiles(e){return this._options.tiles=e,this.reload(),this}setUrl(e){return this.url=e,this._options.url=e,this.reload(),this}setMinzoom(e){return this._options.minzoom=e,this.reload(),this}setMaxzoom(e){return this._options.maxzoom=e,this.reload(),this}onRemove(e){this.cancelTileJSONRequest()}serialize(){return{...this._options}}hasTile(e){return!this.tileBounds||this.tileBounds.contains(e.canonical)}async loadTile(e,t){const i=T.devicePixelRatio>=2,s=this.map._requestManager.normalizeTileURL(e.tileID.canonical.url(this.tiles,this.scheme),i,this.tileSize),o=new AbortController;if(e.request=o,this._tileProvider)this.loadTileWithProvider(e,this._tileProvider,s,o,t);else try{const i=await this.map._requestManager.transformRequest(s,x.Tile,o.signal);if(o.signal.aborted)return delete e.request,t(null);const{data:r,headers:n}=await w(i,o.signal);if(delete e.request,e.aborted)return t(null);const a=Be(n);this.map._refreshExpiredTiles&&e.setExpiryData(a),e.setTexture(r,this.map.painter),e.state="loaded",Ne(this.dispatcher),t(null)}catch(i){if(delete e.request,o.signal.aborted)return t(null);e.state="errored",t(i)}}async loadTileWithProvider(e,t,i,s,o){const{z:r,x:n,y:a}=e.tileID.canonical;try{const l=await this.map._requestManager.transformRequest(i,x.Tile,s.signal);if(s.signal.aborted)return o(null);const c=await t.loadTile({z:r,x:n,y:a},{request:l,signal:s.signal});if(s.signal.aborted)return o(null);if(null==c){const t=new Error("Tile not found");return t.status=404,e.state="errored",o(t)}if(null==c.data)return e.state="loaded",o(null);const h=c.data instanceof ImageBitmap?c.data:await createImageBitmap(new Blob([c.data]));if(s.signal.aborted)return o(null);e.setTexture(h,this.map.painter),e.state="loaded",this.map._refreshExpiredTiles&&e.setExpiryData({cacheControl:c.cacheControl,expires:c.expires}),o(null)}catch(t){if(s.signal.aborted)return o(null);e.state="errored",o(new Error(`Could not load tile from ${i}`,{cause:t}))}finally{delete e.request}}abortTile(e,t){e.request&&(e.request.abort(),delete e.request),t&&t()}unloadTile(e,t){e.texture&&e.texture instanceof k?(e.destroy(!1),e.texture&&e.texture instanceof k&&this.map.painter.saveTileTexture(e.texture)):e.destroy(),t&&t()}hasTransition(){return!1}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}}const Gl=qe([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Uint16",components:2}]);function ql(e,t,i,s,o,r,n,a){const l=[e,t,1,i,s,1,o,r,1],c=[n,a,1],h=it([],l),[d,u,_]=Qe(c,c,h);return st(l,l,[d,0,0,0,u,0,0,0,_])}function Zl(e,t,i,s,o,r,n,a){const l=function(e,t,i,s,o,r,n,a){const l=ql(0,0,1,0,1,1,0,1),c=ql(e,t,i,s,o,r,n,a),h=it([],l);return st(c,c,h)}(e,t,i,s,o,r,n,a);return[l[2]/l[8]/ae,l[5]/l[8]/ae]}function Wl(e){return[e[0],Math.min(Math.max(e[1],-We),We)]}class Hl extends A{constructor(e,t,i,s){super(),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.onNorthPole=!1,this.onSouthPole=!1,this.setEventedParent(s),this.options=t,this._dirty=!1}async load(e,t){if(this._loaded=t||!1,this.fire(new M("dataloading",{dataType:"source"})),this.url=this.options.url,!this.url)return e&&(this.coordinates=e),this._loaded=!0,void this._finishLoading();const i=new AbortController;this._imageRequest=i;try{const t=await this.map._requestManager.transformRequest(this.url,x.Image,i.signal),{data:s}=await w(t,i.signal);this._imageRequest=null,this._loaded=!0,this.image=s,this._dirty=!0,this.width=this.image.width,this.height=this.image.height,e&&(this.coordinates=e),this._finishLoading()}catch(e){if(i.signal.aborted)return;this._imageRequest=null,this._loaded=!0,this.fire(new P(e))}}loaded(){return this._loaded}updateImage(e){return e.url?(this._imageRequest&&e.url!==this.options.url&&(this._imageRequest.abort(),this._imageRequest=null),this.options.url=e.url,this.load(e.coordinates,this._loaded),this):this}setTexture(e){if(!(e.handle instanceof WebGLTexture))throw new Error("The provided handle is not a WebGLTexture instance");return this.texture=new Ze(this.map.painter.context,e.handle),this.width=e.dimensions[0],this.height=e.dimensions[1],this._dirty=!1,this._loaded=!0,this._finishLoading(),this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new M("data",{dataType:"source",sourceDataType:"metadata"})))}onAdd(e){this.map=e,this.load()}onRemove(e){this._imageRequest&&(this._imageRequest.abort(),this._imageRequest=null),!this.texture||this.texture instanceof Ze||this.texture.destroy(),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy())}setCoordinates(e){if(this.coordinates=e,this._boundsArray=void 0,this._unsupportedCoords=!1,!e.length)return this;this.onNorthPole=!1,this.onSouthPole=!1;let t=e[0][1],i=e[0][1];for(const s of e)s[1]>i&&(i=s[1]),s[1]<t&&(t=s[1]);const s=(i+t)/2;if(s>We?this.onNorthPole=!0:s<-We&&(this.onSouthPole=!0),!this.onNorthPole&&!this.onSouthPole){const t=e.map(we.fromLngLat);this.tileID=function(e){let t=1/0,i=1/0,s=-1/0,o=-1/0;for(const r of e)t=Math.min(t,r.x),i=Math.min(i,r.y),s=Math.max(s,r.x),o=Math.max(o,r.y);const r=Math.max(s-t,o-i),n=Math.max(0,Math.floor(-Math.log2(r))),a=Math.pow(2,n);let l=Math.floor((t+s)/2*a);return l>1&&(l-=1),new $e(n,l,Math.floor((i+o)/2*a))}(t),this.minzoom=this.maxzoom=this.tileID.z}return this.fire(new M("data",{dataType:"source",sourceDataType:"content"})),this}_clear(){!this.texture||this.texture instanceof Ze||(this.texture.destroy(),this._dirty=!0),this.texture=null,this._boundsArray=void 0,this._unsupportedCoords=!1}_prepareData(e){for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture)}if(this._boundsArray||this.onNorthPole||this.onSouthPole||this._unsupportedCoords)return;const t=He(new $e(0,0,0),this.map.transform.projection),i=[t.projection.project(this.coordinates[0][0],this.coordinates[0][1]),t.projection.project(this.coordinates[1][0],this.coordinates[1][1]),t.projection.project(this.coordinates[2][0],this.coordinates[2][1]),t.projection.project(this.coordinates[3][0],this.coordinates[3][1])];if(!function(e){const t=e[1].x-e[0].x,i=e[1].y-e[0].y,s=e[2].x-e[1].x,o=e[2].y-e[1].y,r=e[3].x-e[2].x,n=e[3].y-e[2].y,a=e[0].x-e[3].x,l=e[0].y-e[3].y,c=t*o-s*i,h=s*n-r*o,d=r*l-a*n,u=a*i-t*l;return c>0&&h>0&&d>0&&u>0||c<0&&h<0&&d<0&&u<0}(i))return console.warn("Image source coordinates are defining non-convex area in the Mercator projection"),void(this._unsupportedCoords=!0);const s=He(this.tileID,this.map.transform.projection),[o,r,n,a]=this.coordinates.map(e=>{const t=s.projection.project(e[0],e[1]);return fe(s,t)._round()});this.perspectiveTransform=Zl(o.x,o.y,r.x,r.y,n.x,n.y,a.x,a.y);const l=this._boundsArray=new Xe;l.emplaceBack(o.x,o.y,0,0),l.emplaceBack(r.x,r.y,ae,0),l.emplaceBack(a.x,a.y,0,ae),l.emplaceBack(n.x,n.y,ae,ae),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy()),this.boundsBuffer=e.createVertexBuffer(l,Gl.members),this.boundsSegments=Ye.simpleSegment(0,0,4,2);const c=Je,h=c+1,d=c+1,u=h*d,_=c*c*2,p=[],f=function(e){return[Wl(e[0]),Wl(e[1]),Wl(e[2]),Wl(e[3])]}(this.coordinates),[m,g,v,y]=function(e){let t=e[0][0],i=t,s=e[0][1],o=s;for(let r=1;r<e.length;r++)e[r][0]<t?t=e[r][0]:e[r][0]>i&&(i=e[r][0]),e[r][1]<s?s=e[r][1]:e[r][1]>o&&(o=e[r][1]);return[t,s,i-t,o-s]}(f);{const s=new Xe,[o,r,n,a]=function(e){let t=e[0].x,i=t,s=e[0].y,o=s;for(let r=1;r<e.length;r++)e[r].x<t?t=e[r].x:e[r].x>i&&(i=e[r].x),e[r].y<s?s=e[r].y:e[r].y>o&&(o=e[r].y);return[t,s,i-t,o-s]}(i),l=e=>[(e.x-o)/n,(e.y-r)/a],[u,_,f,x]=i.map(l),b=function(e,t,i,s,o,r,n,a){const l=ql(0,0,1,0,1,1,0,1),c=ql(e,t,i,s,o,r,n,a),h=it([],c);return st(l,l,h)}(u[0],u[1],_[0],_[1],f[0],f[1],x[0],x[1]);this.elevatedGlobePerspectiveTransform=Zl(u[0],u[1],_[0],_[1],f[0],f[1],x[0],x[1]);const w=(e,t)=>{p.push(e.lng);const i=Math.round((e.lng-m)/v*ae),o=Math.round((e.lat-g)/y*ae),r=l(t),n=Qe([],[r[0],r[1],1],b),a=Math.round(n[0]/n[2]*ae),c=Math.round(n[1]/n[2]*ae);s.emplaceBack(i,o,a,c)},T=i[3].x-i[0].x,E=i[3].y-i[0].y,I=i[2].x-i[1].x,S=i[2].y-i[1].y;for(let e=0;e<d;e++){const s=e/c,o=[i[0].x+s*T,i[0].y+s*E],r=[i[1].x+s*I,i[1].y+s*S],n=r[0]-o[0],a=r[1]-o[1];for(let e=0;e<h;e++){const i=e/c,s={x:o[0]+n*i,y:o[1]+a*i};w(t.projection.unproject(s.x,s.y),s)}}this.elevatedGlobeVertexBuffer=e.createVertexBuffer(s,Gl.members)}{this.maxLongitudeTriangleSize=0;let t=[],i=new Ke;const s=(e,s,o)=>{i.emplaceBack(e,s,o);const r=p[e],n=p[s],a=p[o],l=Math.min(Math.min(r,n),a),c=Math.max(Math.max(r,n),a)-l;c>this.maxLongitudeTriangleSize&&(this.maxLongitudeTriangleSize=c),t.push(l+c/2)};for(let e=0;e<c;e++)for(let t=0;t<c;t++){const i=e*h+t,o=i+1,r=i+h,n=r+1;s(i,r,o),s(o,r,n)}[t,i]=function(e,t){const i=Array.from({length:e.length},(e,t)=>t);i.sort((t,i)=>e[t]-e[i]);const s=[],o=new Ke;for(let r=0;r<i.length;r++){const n=i[r];s.push(e[n]);const a=3*n,l=a+1;o.emplaceBack(t.uint16[a],t.uint16[l],t.uint16[l+1])}return[s,o]}(t,i),this.elevatedGlobeTrianglesCenterLongitudes=t,this.elevatedGlobeIndexBuffer=e.createIndexBuffer(i)}this.elevatedGlobeSegments=Ye.simpleSegment(0,0,u,_),this.elevatedGlobeGridMatrix=new Float32Array([0,v/ae,0,y/ae,0,0,g,m,0])}prepare(){const e=0!==Object.keys(this.tiles).length;if(this.tileID&&!e)return;const t=this.map.painter.context,i=t.gl;!this._dirty||this.texture instanceof Ze||(this.texture?this.texture.update(this.image):(this.texture=new k(t,this.image,i.RGBA8),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE)),this._dirty=!1),e&&this._prepareData(t)}loadTile(e,t){this.tileID&&this.tileID.equals(e.tileID.canonical)?(this.tiles[String(e.tileID.wrap)]=e,e.buckets={},t(null)):(e.state="errored",t(null))}serialize(){return{type:"image",url:this.options.url,coordinates:this.coordinates}}hasTransition(){return!1}getSegmentsForLongitude(e){const t=this.elevatedGlobeSegments;if(!this.elevatedGlobeTrianglesCenterLongitudes||!t)return null;const i=this.elevatedGlobeTrianglesCenterLongitudes;let s=(o=e+180)+360*Math.round((i[0]-o)/360);var o;const r=new Ye,n=(e,i)=>{r.segments.push({vertexOffset:0,primitiveOffset:e,vertexLength:t.segments[0].vertexLength,primitiveLength:i,sortKey:void 0,vaos:{}})},a=.51*this.maxLongitudeTriangleSize;if(Math.abs(i[0]-s)<=a){const e=et(i,0,i.length,s+a);return e===i.length||n(e,tt(i,e+1,i.length,s+360-a)-e),r}s<i[0]&&(s+=360);const l=tt(i,0,i.length,s-a);if(l===i.length)return n(0,i.length),r;n(0,l-0);const c=et(i,l+1,i.length,s+a);return c!==i.length&&n(c,i.length-c),r}}const $l={vector:class extends A{constructor(e,t,i,s){if(super(),this.id=e,this.dispatcher=i,this.type="vector",this.provider=t.provider,this.minzoom=0,this.maxzoom=22,this.scheme="xyz",this.tileSize=512,this.reparseOverscaled=!0,this.isTileClipped=!0,this._loaded=!1,Object.assign(this,Me(t,["url","scheme","tileSize","promoteId"])),this._options={type:"vector",...t},this._stableIdField=Vl(this.url),this._collectResourceTiming=!!t.collectResourceTiming,512!==this.tileSize)throw new Error("vector tile sources must have a tileSize of 512");this.setEventedParent(s),this._tileWorkers={},this._deduped=new Oe}load(e){this._loaded=!1,this.fire(new M("dataloading",{dataType:"source"}));const t=Array.isArray(this.map._language)?this.map._language.join():this.map._language,i=this.map.getWorldview(),s=(s,o)=>{this._tileJSONRequest=null,this._loaded=!0,s?(t&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${t}`),i&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${i}`),this.fire(new P(s))):o&&(this._setTileJSON(o),Il.updateCrossSourceElevationGate&&this.map.style&&Il.updateCrossSourceElevationGate(this.map.style),en(o.tiles,this.map._requestManager._customAccessToken),this.fire(new M("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new M("data",{dataType:"source",sourceDataType:"content"}))),e&&e(s)};this.provider=this._options.provider;const o=ze(this._options);return o instanceof Error?(this._loaded=!0,this.fire(new P(o)),void(e&&e())):this.provider&&!o?(this._loaded=!0,this.fire(new P(new Error(`TileProvider "${this.provider}" is not registered`))),void(e&&e())):void(this._tileJSONRequest=o?this.loadTileJSONWithProvider(o,s):Fe(this._options,this.map._requestManager,t,i,s))}loadTileJSONWithProvider(e,t){this.provider=e.name;const i=new AbortController;return(async()=>{const{request:s,options:o}=await Ue(this._options,this.map._requestManager,i.signal);if(i.signal.aborted)return;const r=await this.dispatcher.send("loadTileProvider",{name:e.name,url:e.url,source:this.id,scope:this.scope,type:this.type,options:o,request:s},{signal:i.signal});if(i.signal.aborted)return;const n=r?r.find(e=>null!=e):null,a=Ve(this._options,n,this.map._requestManager);a instanceof Error?t(a):t(null,a)})().catch(e=>{i.signal.aborted||t(e)}),{cancel:()=>i.abort()}}_setTileJSON(e){if(Object.assign(this,e),this.hasWorldviews=!!e.worldview_options,e.worldview_default&&(this.worldviewDefault=e.worldview_default),e.vector_layers){this.vectorLayers=e.vector_layers,this.vectorLayerIds=[],this.localizableLayerIds=new Set;for(const t of e.vector_layers)this.vectorLayerIds.push(t.id),e.worldview&&e.worldview[t.source]&&this.localizableLayerIds.add(t.id)}this.tileBounds=new Ul(e)}loaded(){return this._loaded}hasTile(e){return!this.tileBounds||this.tileBounds.contains(e.canonical)}onAdd(e){this.map=e,this.load()}reload(){this.cancelTileJSONRequest();const e=C(this.id,this.scope);this.load(()=>this.map.style.clearSource(e))}setTiles(e){return this._options.tiles=e,this.reload(),this}setUrl(e){return this.url=e,this._options.url=e,this._stableIdField=Vl(e),this.reload(),this}setMinzoom(e){return this._options.minzoom=e,this.reload(),this}setMaxzoom(e){return this._options.maxzoom=e,this.reload(),this}onRemove(e){this.cancelTileJSONRequest()}serialize(){return{...this._options}}async loadTile(e,t){const i=e.tileID.canonical.url(this.tiles,this.scheme),s=this.map._requestManager.normalizeTileURL(i),o=!e.actor||"expired"===e.state;if(!o&&"loading"===e.state)return void(e.reloadCallback=t);o&&(e.actor=this._tileWorkers[s]=this._tileWorkers[s]||this.dispatcher.getActor());const r=new AbortController;e.request=r;try{const n=await this.map._requestManager.transformRequest(s,x.Tile,r.signal);if(r.signal.aborted)return t(null);this.dispatchTile(e,s,i,n,r,o,t)}catch(e){if(r.signal.aborted)return t(null);t(e)}}dispatchTile(e,t,i,s,o,n,a){const l=this.map.style?this.map.style.getLut(this.scope):null,c=l?{image:l.image.clone()}:null,h=!(!this.map.style||!this.map.style._crossSourceElevationActive),d=!(!this.map.style||!h&&Il.loaded),u={request:s,data:void 0,uid:e.uid,tileID:e.tileID,tileZoom:e.tileZoom,zoom:e.tileID.overscaledZ,maxZoom:this.maxzoom,lut:c,tileSize:this.tileSize*e.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,pixelRatio:T.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,showElevationIdDebug:!!this.map.painter&&this.map.painter._debugParams.showElevationIdDebug,promoteId:this.promoteId,stableIdField:this._stableIdField,renderSourceType:e.renderSourceType,frcCoverage:(()=>{const t=this.map.painter,i=t?t.frcCoverageFadeRange:null;if(null==i)return null;const s=t?t.frcCoverageSnapshot:null,o=this.map.transform.zoom<i[0],r=s?s.getTileOrParent(e.tileID.canonical):null,n=e.tileID.overscaledZ>=Math.ceil(i[1]),a=s&&n?s.getFullCoverageMask(e.tileID.canonical):null;return{frcMask:n?a??null:null,resolved:o||null!=s,polygons:r&&0!==r.frcMask?r.polygons:null,tileZoom:r&&0!==r.frcMask?r.tileId.z:null,sourceLayers:t?t.frcCoverageSourceLayers:["road","structure"]}})(),terrainEnabled:el(this.map.style,this.map.transform),crossSourceElevationEnabled:d,elevation:Il.buildElevationRequestParams?Il.buildElevationRequestParams(this.map,e,h):null,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:e.isExtraShadowCaster,tessellationStep:this.map._tessellationStep,scaleFactor:this.map.getScaleFactor(),worldview:this.map.getWorldview()||this.worldviewDefault,indoor:this.map.getIndoorTileOptions(this.id,this.scope)};if(this.hasWorldviews&&r(i)&&(u.localizableLayerIds=this.localizableLayerIds),u.request.collectResourceTiming=this._collectResourceTiming,n)if(this.dispatcher.ready||this.provider)e.request=e.actor.sendCancelable("loadTile",u,{},_.bind(this));else{const t=ke.call({deduped:this._deduped},u,(t,i)=>{e.aborted||(t||!i?_.call(this,t):(u.data={rawData:i.rawData.slice(0),headers:i.headers},e.actor&&(e.request=e.actor.sendCancelable("loadTile",u,{},_.bind(this)))))},!0);o.signal.addEventListener("abort",t,{once:!0})}else e.request=e.actor.sendCancelable("reloadTile",u,{},_.bind(this));function _(t,i){if(delete e.request,e.aborted)return a(null);if(t)return a(t);i&&i.resourceTiming&&(e.resourceTiming=i.resourceTiming),this.map._refreshExpiredTiles&&i&&e.setExpiryData(Be(i.headers));const s=i&&i.containsHdExt&&!Il.loaded,o=i&&i.containsStandardExt&&!ue.loaded;if(s||o){const e=[];return s&&e.push(Dl()),o&&e.push(Cl()),void Promise.all(e).then(()=>r.call(this),()=>r.call(this))}function r(){return e.aborted?a(null):i&&i.containsHdExt&&!Il.loaded?a(new Error("HD module failed to load")):i&&i.containsStandardExt&&!ue.loaded?a(new Error("Standard module failed to load")):(e.loadVectorData(i,this.map.painter),Ne(this.dispatcher),a(null,i),void(e.reloadCallback&&(this.loadTile(e,e.reloadCallback),e.reloadCallback=null)))}r.call(this)}}abortTile(e){e.request&&(e.request.abort(),delete e.request),e.actor&&e.actor.notify("abortTile",{uid:e.uid,type:this.type,source:this.id,scope:this.scope})}unloadTile(e,t){e.actor&&e.actor.notify("removeTile",{uid:e.uid,type:this.type,source:this.id,scope:this.scope}),e.destroy()}hasTransition(){return!1}afterUpdate(){this._tileWorkers={}}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}},raster:jl,"raster-dem":class extends jl{constructor(e,t,i,s){super(e,t,i,s),this.type="raster-dem",this.maxzoom=22,this._options={type:"raster-dem",...t},this.encoding=t.encoding||"mapbox"}loadTileJSONWithProvider(e,t){this.provider=e.name;const i=new AbortController;return(async()=>{const{request:s,options:o}=await Ue(this._options,this.map._requestManager,i.signal);if(i.signal.aborted)return;const r=await this.dispatcher.send("loadTileProvider",{name:e.name,url:e.url,source:this.id,scope:this.scope,type:this.type,options:o,request:s},{signal:i.signal});if(i.signal.aborted)return;const n=r?r.find(e=>null!=e):null,a=Ve(this._options,n,this.map._requestManager);a instanceof Error?t(a):t(null,a)})().catch(e=>{i.signal.aborted||t(e)}),{cancel:()=>i.abort()}}async loadTile(e,t){if(e.actor&&"expired"!==e.state)return;const i=this.map._requestManager.normalizeTileURL(e.tileID.canonical.url(this.tiles,this.scheme),!1,this.tileSize);e.actor=this.dispatcher.getActor();const s=new AbortController;e.request=s;try{const o=await this.map._requestManager.transformRequest(i,x.Tile,s.signal);if(s.signal.aborted)return t(null);e.request=e.actor.sendCancelable("loadTile",{uid:e.uid,tileID:e.tileID,source:this.id,type:this.type,scope:this.scope,request:o,encoding:this.encoding},{},function(i,s){return delete e.request,e.aborted?t(null):i?(e.state="errored",t(i)):(s&&(this.map._refreshExpiredTiles&&e.setExpiryData(Be(s.headers)),s.borderReady||e.neighboringTiles||(e.neighboringTiles=this._getNeighboringTiles(e.tileID)),e.dem=s.dem,e.dem.onDeserialize(),e.needsHillshadePrepare=!0,e.needsDEMTextureUpload=!0),e.state="loaded",void t(null))}.bind(this))}catch(i){if(s.signal.aborted)return t(null);e.state="errored",t(i)}}abortTile(e,t){e.request&&(e.request.abort(),delete e.request),e.actor&&e.actor.notify("abortTile",{uid:e.uid,type:this.type,source:this.id,scope:this.scope}),t&&t()}_getNeighboringTiles(e){const t=e.canonical,i=Math.pow(2,t.z),s=(t.x-1+i)%i,o=0===t.x?e.wrap-1:e.wrap,r=(t.x+1+i)%i,n=t.x+1===i?e.wrap+1:e.wrap,a={};return a[new Ge(e.overscaledZ,o,t.z,s,t.y).key]={backfilled:!1},a[new Ge(e.overscaledZ,n,t.z,r,t.y).key]={backfilled:!1},t.y>0&&(a[new Ge(e.overscaledZ,o,t.z,s,t.y-1).key]={backfilled:!1},a[new Ge(e.overscaledZ,e.wrap,t.z,t.x,t.y-1).key]={backfilled:!1},a[new Ge(e.overscaledZ,n,t.z,r,t.y-1).key]={backfilled:!1}),t.y+1<i&&(a[new Ge(e.overscaledZ,o,t.z,s,t.y+1).key]={backfilled:!1},a[new Ge(e.overscaledZ,e.wrap,t.z,t.x,t.y+1).key]={backfilled:!1},a[new Ge(e.overscaledZ,n,t.z,r,t.y+1).key]={backfilled:!1}),a}},geojson:class extends A{constructor(e,t,i,s){super(),this.id=e,this.type="geojson",this.minzoom=0,this.maxzoom=18,this.tileSize=512,this.isTileClipped=!0,this.reparseOverscaled=!0,this._loaded=!1,this.actor=i.getActor(),this.setEventedParent(s),this._data=t.data,this._options={...t},this._collectResourceTiming=t.collectResourceTiming,void 0!==t.maxzoom&&(this.maxzoom=t.maxzoom),void 0!==t.minzoom&&(this.minzoom=t.minzoom),t.type&&(this.type=t.type),t.attribution&&(this.attribution=t.attribution),this.promoteId=t.promoteId;const o=ae/this.tileSize;this.workerOptions={source:this.id,scope:this.scope,cluster:t.cluster||!1,geojsonVtOptions:{buffer:(void 0!==t.buffer?t.buffer:128)*o,tolerance:(void 0!==t.tolerance?t.tolerance:.375)*o,extent:ae,maxZoom:this.maxzoom,lineMetrics:t.lineMetrics||!1,generateId:t.generateId||!1},superclusterOptions:{maxZoom:void 0!==t.clusterMaxZoom?t.clusterMaxZoom:this.maxzoom-1,minPoints:Math.max(2,t.clusterMinPoints||2),extent:ae,radius:(void 0!==t.clusterRadius?t.clusterRadius:50)*o,log:!1,generateId:t.generateId||!1},clusterProperties:t.clusterProperties,filter:t.filter,dynamic:t.dynamic,...t.workerOptions}}onAdd(e){this.map=e,this.setData(this._data)}setData(e){return this._data=e,this._updateWorkerData(),this}updateData(e){if(!this._options.dynamic)return this.fire(new P(new Error("Can't call updateData on a GeoJSON source with dynamic set to false.")));if("string"!=typeof e&&("Feature"===e.type&&(e={type:"FeatureCollection",features:[e]}),"FeatureCollection"!==e.type))return this.fire(new P(new Error("Data to update should be a feature or a feature collection.")));if(this._coalesce&&"string"!=typeof e&&"string"!=typeof this._data&&"FeatureCollection"===this._data.type){const t=new Map;for(const e of this._data.features)t.set(e.id,e);for(const i of e.features)t.set(i.id,i);this._data.features=[...t.values()]}else this._data=e;return this._updateWorkerData(!0),this}getClusterExpansionZoom(e,t){return this.actor.send("geojson.getClusterExpansionZoom",{clusterId:e,source:this.id,scope:this.scope}).then(e=>t(null,e)).catch(e=>t(e)),this}getClusterChildren(e,t){return this.actor.send("geojson.getClusterChildren",{clusterId:e,source:this.id,scope:this.scope}).then(e=>t(null,e)).catch(e=>t(e)),this}getClusterLeaves(e,t,i,s){return this.actor.send("geojson.getClusterLeaves",{source:this.id,scope:this.scope,clusterId:e,limit:t,offset:i}).then(e=>s(null,e)).catch(e=>s(e)),this}async _updateWorkerData(e=!1){if(this._pendingLoad)return void(this._coalesce=!0);this.fire(new M("dataloading",{dataType:"source"})),this._loaded=!1;const t={append:e,...this.workerOptions};t.scope=this.scope;const i=this._data,s=new AbortController;this._pendingLoad=s;try{if("string"==typeof i){if(t.request=await this.map._requestManager.transformRequest(T.resolveURL(i),x.Source,s.signal),s.signal.aborted)return this._pendingLoad=null,void(this._coalesce=!1);t.request.collectResourceTiming=this._collectResourceTiming}else t.data=JSON.stringify(i);const o=await this.actor.send(`${this.type}.loadData`,t,{signal:s.signal});this._loaded=!0,this._pendingLoad=null;const r={dataType:"source",sourceDataType:this._metadataFired?"content":"metadata"};this._collectResourceTiming&&o&&o.resourceTiming&&o.resourceTiming[this.id]&&(r.resourceTiming=o.resourceTiming[this.id]),e&&(this._partialReload=!0),this.fire(new M("data",r)),this._partialReload=!1,this._metadataFired=!0}catch(e){if(s.signal.aborted)return this._pendingLoad=null,void(this._coalesce=!1);this._loaded=!0,this._pendingLoad=null,this.fire(new P(e))}this._coalesce&&(this._updateWorkerData(e),this._coalesce=!1)}loaded(){return this._loaded}reload(){const e=C(this.id,this.scope);this.map.style.clearSource(e),this._updateWorkerData()}loadTile(e,t){const i=e.actor?"reloadTile":"loadTile";e.actor=this.actor;const s=this.map.style?this.map.style.getLut(this.scope):null,o=s?{image:s.image.clone()}:null,r=this._partialReload,n={type:this.type,uid:e.uid,tileID:e.tileID,tileZoom:e.tileZoom,zoom:e.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,lut:o,scope:this.scope,pixelRatio:T.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,showElevationIdDebug:!!this.map.painter&&this.map.painter._debugParams.showElevationIdDebug,promoteId:this.promoteId,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:e.isExtraShadowCaster,scaleFactor:this.map.getScaleFactor(),partial:r,worldview:this.map.getWorldview(),indoor:this.map.getIndoorTileOptions(this.id,this.scope)};e.request=this.actor.sendCancelable(i,n,{},(s,o)=>{if(r&&!o)return e.state="loaded",t(null);if(delete e.request,e.destroy(!1),e.aborted)return t(null);if(s)return t(s);if(o&&o.containsHdExt&&!Il.loaded){const s=()=>e.aborted?t(null):Il.loaded?(e.loadVectorData(o,this.map.painter,"reloadTile"===i),void t(null)):t(new Error("HD module failed to load"));return void Dl().then(s,s)}e.loadVectorData(o,this.map.painter,"reloadTile"===i),t(null)})}abortTile(e){e.request&&(e.request.abort(),delete e.request),e.aborted=!0}unloadTile(e,t){this.actor.notify("removeTile",{uid:e.uid,type:this.type,source:this.id,scope:this.scope}),e.destroy()}onRemove(e){this._pendingLoad&&this._pendingLoad.abort()}serialize(){return{...this._options,type:this.type,data:this._data}}hasTransition(){return!1}},video:class extends Hl{constructor(e,t,i,s){super(e,t,i,s),this.roundZoom=!0,this.type="video",this.options=t}async load(){this._loaded=!1;const e=this.options,t=new AbortController;this._imageRequest=t;try{const i=await Promise.all(e.urls.map(async e=>(await this.map._requestManager.transformRequest(e,x.Source,t.signal)).url));if(t.signal.aborted)return;this.urls=i;const s=await ot(i);if(t.signal.aborted)return;this._imageRequest=null,this.video=s,this.video.loop=!0,this.video.setAttribute("playsinline",""),this.video.addEventListener("playing",()=>{this.map.triggerRepaint()}),this.map&&this.video.play(),this._finishLoading()}catch(e){if(t.signal.aborted)return;this.fire(new P(e))}finally{this._loaded=!0}}pause(){this.video&&this.video.pause()}play(){this.video&&this.video.play()}seek(e){if(this.video){const t=this.video.seekable;e<t.start(0)||e>t.end(0)?this.fire(new P(new Da(`sources.${this.id}`,null,`Playback for this video can be set only between the ${t.start(0)} and ${t.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,t=e.gl;this.texture?this.video.paused||(this.texture.bind(t.LINEAR,t.CLAMP_TO_EDGE),t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,this.video)):(this.texture=new k(e,this.video,t.RGBA8),this.texture.bind(t.LINEAR,t.CLAMP_TO_EDGE),this.width=this.video.videoWidth,this.height=this.video.videoHeight),this._prepareData(e)}serialize(){return{type:"video",urls:this.options.urls,coordinates:this.coordinates}}hasTransition(){return this.video&&!this.video.paused}},image:Hl,canvas:class extends Hl{constructor(e,t,i,s){super(e,t,i,s),t.coordinates?Array.isArray(t.coordinates)&&4===t.coordinates.length&&!t.coordinates.some(e=>!Array.isArray(e)||2!==e.length||e.some(e=>"number"!=typeof e))||this.fire(new P(new Da(`sources.${e}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new P(new Da(`sources.${e}`,null,'missing required property "coordinates"'))),t.animate&&"boolean"!=typeof t.animate&&this.fire(new P(new Da(`sources.${e}`,null,'optional "animate" property must be a boolean value'))),t.canvas?"string"==typeof t.canvas||t.canvas instanceof HTMLCanvasElement||this.fire(new P(new Da(`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 P(new Da(`sources.${e}`,null,'missing required property "canvas"'))),this.options=t,this.animate=void 0===t.animate||t.animate}async load(){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 P(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(e){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 t=this.map.painter.context;this.texture?!e&&!this._playing||this.texture instanceof Ze||this.texture.update(this.canvas,{premultiply:!0}):this.texture=new k(t,this.canvas,t.gl.RGBA8,{premultiply:!0}),this._prepareData(t)}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}},custom:class extends A{constructor(e,t,i,s){super(),this.id=e,this.type="custom",this._dataType="raster",this._dispatcher=i,this._implementation=t,this.setEventedParent(s),this.scheme="xyz",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this._loaded=!1,this.roundZoom=!0,this._implementation||this.fire(new P(new Error(`Missing implementation for ${this.id} custom source`))),this._implementation.loadTile||this.fire(new P(new Error(`Missing loadTile implementation for ${this.id} custom source`)));const o=t;o.update=this._update.bind(this),o.clearTiles=this._clearTiles.bind(this),o.coveringTiles=this._coveringTiles.bind(this),Object.assign(this,Me(t,["dataType","scheme","minzoom","maxzoom","tileSize","attribution","minTileCacheSize","maxTileCacheSize"])),this._implementation.bounds&&(this.tileBounds=new Ul({bounds:this._implementation.bounds,minzoom:this.minzoom,maxzoom:this.maxzoom}))}serialize(){return Me(this,["type","scheme","minzoom","maxzoom","tileSize","attribution"])}load(){this._loaded=!0,this.fire(new M("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new M("data",{dataType:"source",sourceDataType:"content"}))}loaded(){return this._loaded}onAdd(e){this.map=e,this._loaded=!1,this.fire(new M("dataloading",{dataType:"source"})),this._implementation.onAdd&&this._implementation.onAdd(e),this.load()}onRemove(e){this._implementation.onRemove&&this._implementation.onRemove(e)}hasTile(e){if(this._implementation.hasTile){const{x:t,y:i,z:s}=e.canonical;return this._implementation.hasTile({x:t,y:i,z:s})}return!this.tileBounds||this.tileBounds.contains(e.canonical)}async loadTile(e,t){const{x:i,y:s,z:o}=e.tileID.canonical,r=new AbortController;e.request=r;try{const n=await this._implementation.loadTile({x:i,y:s,z:o},{signal:r.signal});if(delete e.request,e.aborted)return e.state="unloaded",t(null);if(void 0===n)return e.state="errored",t(null);if(null===n)return this.loadTileData(e,{width:this.tileSize,height:this.tileSize,data:null}),e.state="loaded",t(null);if(!function(e){return e instanceof ImageData||e instanceof HTMLCanvasElement||e instanceof ImageBitmap||e instanceof HTMLImageElement}(n))return e.state="errored",t(new Error(`Can't infer data type for ${this.id}, only raster data supported at the moment`));this.loadTileData(e,n),e.state="loaded",t(null)}catch(i){if(r.signal.aborted)return;e.state="errored",t(i)}}loadTileData(e,t){e.setTexture(t,this.map.painter)}unloadTile(e,t){if(e.texture&&e.texture instanceof k?(e.destroy(!1),e.texture&&e.texture instanceof k&&this.map.painter.saveTileTexture(e.texture)):e.destroy(),this._implementation.unloadTile){const{x:t,y:i,z:s}=e.tileID.canonical;this._implementation.unloadTile({x:t,y:i,z:s})}t&&t()}abortTile(e,t){e.request&&(e.request.abort(),delete e.request),t&&t()}hasTransition(){return!1}_coveringTiles(){return this.map.transform.coveringTiles({tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,roundZoom:this.roundZoom}).map(e=>({x:e.canonical.x,y:e.canonical.y,z:e.canonical.z}))}_clearTiles(){const e=C(this.id,this.scope);this.map.style.clearSource(e)}_update(){this.fire(new M("data",{dataType:"source",sourceDataType:"content"}))}}},Xl=function(e,t,i,s){const o=Yl(t.type);if(!o)throw new Error(`Unknown source type "${t.type}"`);const r=new o(e,t,i,s);if(r.id!==e)throw new Error(`Expected Source id to be ${e} instead of ${r.id}`);return rt(["load","abort","unload","serialize","prepare"],r),r},Yl=function(e){return Object.hasOwn($l,e)?$l[e]:void 0},Kl={model:()=>Cl().then(()=>ue.ModelSource),"batched-model":()=>Cl().then(()=>ue.Tiled3dModelSource),"raster-array":()=>Ol().then(()=>Pl.RasterArrayTileSource)};class Jl extends A{constructor(e,t,i,s){super(),this.id=e,this.type=t.type,this._options={...t},this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.setEventedParent(s)}hasTransition(){return!1}startLoad(){const e=this._loader;this._loader=void 0,e&&e()}loaded(){return void 0!==this._loader}onAdd(e){}onRemove(e){}loadTile(e,t){}serialize(){return this._options}_setOption(e,t){return this._options[e]=t,this}}class Ql extends Jl{setTiles(e){return this._setOption("tiles",e)}setUrl(e){return this._setOption("url",e)}setMinzoom(e){return this._setOption("minzoom",e)}setMaxzoom(e){return this._setOption("maxzoom",e)}}class ec extends Jl{getModels(){return[]}setModels(e){return this._setOption("models",e)}}function tc(e,t,i=""){return`${i}:${t.id||""}:${t.layer.id}:${function(e){if("layerId"in e)return`layer:${e.layerId}`;{const{featuresetId:t,importId:i}=e;return`featureset:${t}${i?`:import:${i}`:""}`}}(e.target)}`}function ic(e,t,i,s=""){if(e.uniqueFeatureID){const o=tc(e,t,s);if(i.has(o))return!0;i.add(o)}return!1}function sc(e,t,i,s,o=!1,r=void 0){const n=t.sourceCache.transform,a=t.sourceCache.tilesIn(e,t.has3DLayers,o);a.sort(nc);const l=[];for(const e of a){const a=e.tile.queryRenderedFeatures(t,e,i,s,n,o,r);Object.keys(a).length&&l.push({wrappedTileID:e.tile.tileID.wrapped().key,queryResults:a})}for(const i in t.layers){const o=t.layers[i];if(o.styleLayer){const i=o.styleLayer.queryRenderedFeatures(e,t.sourceCache,s);Object.keys(i).length&&l.push({wrappedTileID:0,queryResults:i})}}return 0===l.length?{}:function(e){const t={},i={};for(const s of e){const e=s.queryResults,o=s.wrappedTileID,r=i[o]=i[o]||{};for(const i in e){const s=e[i],o=r[i]=r[i]||{},n=t[i]=t[i]||[];for(const e of s)o[e.featureIndex]||(o[e.featureIndex]=!0,n.push(e))}}return t}(l)}function oc(e,t,i,s,o,r){const n={},a=s.queryRenderedSymbols(e),l=[];for(const e of Object.keys(a).map(Number))l.push(o[e]);l.sort(nc);for(const e of l){const s=e.featureIndex.lookupSymbolFeatures(a[e.bucketInstanceId],e.bucketIndex,e.sourceLayerIndex,t,i,r);for(const t in s){const i=n[t]=n[t]||[],o=s[t];o.sort((t,i)=>{const s=e.featureSortOrder;if(s){const e=s.indexOf(t.featureIndex);return s.indexOf(i.featureIndex)-e}return i.featureIndex-t.featureIndex});for(const e of o)i.push(e)}}return n}function rc(e,t){const i=e.getRenderableIds().map(t=>e.getTileByID(t)),s=[],o={};for(let e=0;e<i.length;e++){const r=i[e],n=r.tileID.canonical.key;o[n]||(o[n]=!0,r.querySourceFeatures(s,t))}return s}function nc(e,t){const i=e.tileID,s=t.tileID;return i.overscaledZ-s.overscaledZ||i.canonical.y-s.canonical.y||i.wrap-s.wrap||i.canonical.x-s.canonical.x}function ac(e,t){const i={};if(!t)return i;for(const s of e){const e=s.layerIds.map(e=>t.getLayer(e)).filter(Boolean);if(0!==e.length){s.layers=e,s.stateDependentLayerIds&&(s.stateDependentLayers=s.stateDependentLayerIds.map(t=>e.filter(e=>e.id===t)[0])),s.updateExpressions&&s.updateExpressions(e);for(const t of e)i[t.fqid]=s}}return i}const lc=32,cc=33,hc=new Uint16Array(8184);for(let e=0;e<2046;e++){let t=e+2,i=0,s=0,o=0,r=0,n=0,a=0;for(1&t?o=r=n=lc:i=s=a=lc;(t>>=1)>1;){const e=i+o>>1,l=s+r>>1;1&t?(o=i,r=s,i=n,s=a):(i=o,s=r,o=n,r=a),n=e,a=l}const l=4*e;hc[l+0]=i,hc[l+1]=s,hc[l+2]=o,hc[l+3]=r}const dc=new Uint16Array(2178),uc=new Uint8Array(1089),_c=new Uint16Array(1089);function pc(e){return 0===e?-.03125:32===e?.03125:0}const fc=(()=>({type:2,extent:ae,loadGeometry:()=>[[new m(0,0),new m(ae+1,0),new m(ae+1,ae+1),new m(0,ae+1),new m(0,0)]]}))();let mc,gc,vc=0;class yc{constructor(e,t,i,s,o,r){this.tileID=e,this.uid=ce(),this.uses=0,this.tileSize=t,this.tileZoom=i,this.dashIdealZ=e.overscaledZ,this.buckets={},this.expirationTime=null,this.queryPadding=0,this.hasSymbolBuckets=!1,this.hasTunnelGeometry=!1,this.dependencies={},this.isRaster=o,s&&s.style&&(this._lastUpdatedBrightness=s.style.getBrightness()),this._lastAvailableImagesCount=0,this._firstPrepareComplete=!1,this._queryPaddingPaintVersions={},this.expiredRequestCount=0,this.state="loading",s&&s.transform&&(this.projection=s.transform.projection),this.worldview=r,this._hasAppearances=null}registerFadeDuration(e){const t=e+this.timeAdded;t<T.now()||void 0!==this.fadeEndTime&&t<this.fadeEndTime||(this.fadeEndTime=t)}wasRequested(){return"errored"===this.state||"loaded"===this.state||"reloading"===this.state}get tileTransform(){return this._tileTransform||(this._tileTransform=He(this.tileID.canonical,this.projection)),this._tileTransform}loadVectorData(e,t,i){if(this.unloadVectorData(),this.state="loaded",e){e.featureIndex&&(this.latestFeatureIndex=e.featureIndex,e.rawTileData?(this.latestRawTileData=e.rawTileData,this.latestFeatureIndex.rawTileData=e.rawTileData):this.latestRawTileData&&(this.latestFeatureIndex.rawTileData=this.latestRawTileData)),this.collisionBoxArray=e.collisionBoxArray,this.buckets=ac(e.buckets,t.style),e.frcCoveragePolygons&&e.frcCoveragePolygons.length>0&&(this.frcCoveragePolygons=e.frcCoveragePolygons),this.hasDeferredRoadStructure=!!e.hasDeferredRoadStructure,void 0!==e.parsedElevationFeatures&&(this.parsedElevationFeatures=e.parsedElevationFeatures,this.parsedElevationGeneration=++vc),this.hasDeferredElevationFeatures=!!e.hasDeferredElevationFeatures,this.hasSymbolBuckets=!1,this.hasTunnelGeometry=!!e.hasTunnelGeometry;for(const e in this.buckets){const t=this.buckets[e];if(t instanceof ct){if(this.hasSymbolBuckets=!0,!i)break;t.justReloaded=!0}}this.queryPadding=0,this._queryPaddingPaintVersions={};for(const e in this.buckets){const i=this.buckets[e];i instanceof ct&&!i.bucketInstanceId&&(i.bucketInstanceId=ct.maxBucketInstanceId++);const s=t.style.getOwnLayer(e);if(!s)continue;const o=s.queryRadius(i)||0;this.queryPadding=Math.max(this.queryPadding,o),this._queryPaddingPaintVersions[e]=s.paintVersion}e.imageAtlas&&(this.imageAtlas=t.style.imageManager.imageAtlasCache.getOrCache(e.imageAtlas)),e.glyphAtlasImage&&(this.glyphAtlasImage=e.glyphAtlasImage),e.lineAtlas&&(this.lineAtlas=e.lineAtlas),this._lastUpdatedBrightness=e.brightness}else this.collisionBoxArray=new lt}resetPlacementVisibility(){for(const e in this.buckets)this.buckets[e].resetPlacementVisibility?.()}unloadVectorData(){if(this.hasData()){for(const e in this.buckets)this.buckets[e].destroy();this.buckets={},this.imageAtlas&&(this.imageAtlas=null),this.lineAtlas&&(this.lineAtlas=null),this.imageAtlasTexture&&(this.imageAtlasTexture=null),this.glyphAtlasTexture&&this.glyphAtlasTexture.destroy(),this.lineAtlasTexture&&this.lineAtlasTexture.destroy(),this._tileBoundsBuffer&&(this._tileBoundsBuffer.destroy(),this._tileBoundsIndexBuffer.destroy(),this._tileBoundsSegments.destroy(),this._tileBoundsBuffer=null),this._tileDebugBuffer&&(this._tileDebugBuffer.destroy(),this._tileDebugSegments.destroy(),this._tileDebugBuffer=null),this._tileDebugIndexBuffer&&(this._tileDebugIndexBuffer.destroy(),this._tileDebugIndexBuffer=null),this._globeTileDebugBorderBuffer&&(this._globeTileDebugBorderBuffer.destroy(),this._globeTileDebugBorderBuffer=null),this._tileDebugTextBuffer&&(this._tileDebugTextBuffer.destroy(),this._tileDebugTextSegments.destroy(),this._tileDebugTextIndexBuffer.destroy(),this._tileDebugTextBuffer=null),this._globeTileDebugTextBuffer&&(this._globeTileDebugTextBuffer.destroy(),this._globeTileDebugTextBuffer=null),this.latestFeatureIndex=null,this.state="unloaded"}}loadModelData(e,t,i){e&&(e.resourceTiming&&(this.resourceTiming=e.resourceTiming),this.buckets={...this.buckets,...ac(e.buckets,t.style)},e.featureIndex&&(this.latestFeatureIndex=e.featureIndex))}getBucket(e){return this.buckets[e.fqid]}upload(e,t){for(const i in this.buckets){const s=this.buckets[i];if(s.uploadPending()){let i={},o=[],r={zoom:0,pitch:0,brightness:0,worldview:""};if(t){if(t.style){o=t.style.listImages();const e=s.layers[0],r=e.sourceLayer||"_geojsonTileLayer",n=t.style.getLayerSourceCache(e);n&&(i=n._state.getState(r,void 0))}r={zoom:t.transform.zoom||0,pitch:t.transform.pitch||0,brightness:t.style.getBrightness()||0,worldview:t.worldview||""}}s.upload(e,this.tileID.canonical,i,o,r)}}const i=e.gl,s=this.imageAtlas;s&&t&&(this.imageAtlasTexture=t.style.imageManager.imageAtlasCache.getTextureForAtlas(s,e,i.RGBA8)),this.glyphAtlasImage&&(this.glyphAtlasTexture=new k(e,this.glyphAtlasImage,i.R8),this.glyphAtlasImage=null),this.lineAtlas&&!this.lineAtlas.uploaded&&(this.lineAtlasTexture=new k(e,this.lineAtlas.image,i.R8),this.lineAtlas.uploaded=!0)}prepare(e,t,i){if(this.imageAtlas&&this.imageAtlasTexture&&t){const s=t.style.getLut(i);this.imageAtlas.patchUpdatedImages(e,this.imageAtlasTexture,i,s)}if(!t||!this.latestFeatureIndex||!this.latestFeatureIndex.rawTileData)return;const s=t.style.getBrightness(),o=t.style.listImages(),r=o.length,n=this._firstPrepareComplete&&r!==this._lastAvailableImagesCount;this._updatePaint(t,o,s,n),null===this._hasAppearances&&(this._hasAppearances=this.hasAppearances(t));const a=this._lastUpdatedBrightness!==s;this._lastAvailableImagesCount=r,this._firstPrepareComplete=!0,(this._lastUpdatedBrightness||s||this._hasAppearances||n)&&(!this._hasAppearances&&!n&&this._lastUpdatedBrightness&&s&&Math.abs(this._lastUpdatedBrightness-s)<.001||(this.updateBuckets(t,a,void 0,n,o),this._lastUpdatedBrightness=s))}_updatePaint(e,t,i,s){const o=e.style;for(const r in this.buckets){const n=this.buckets[r],a=o.getOwnLayer(r);a&&(n instanceof ht&&"line"===a.type?this._updateBinderPaint(e,n,n.uboBinders[a.id],a,t,i,s):n instanceof ct&&"symbol"===a.type&&(this._updateBinderPaint(e,n,n.text.uboBinder,a,t,i,s),this._updateBinderPaint(e,n,n.icon.uboBinder,a,t,i,s)),this._queryPaddingPaintVersions[r]!==a.paintVersion&&(this._queryPaddingPaintVersions[r]=a.paintVersion,this.queryPadding=Math.max(this.queryPadding,a.queryRadius(n)||0)))}}_updateBinderPaint(e,t,i,s,o,r,n){if(!i)return;const a=i.updatePaint(s);if("unchanged"!==a||n){if("features"===a||n){const n=t.layers[0],a=n.sourceLayer||"_geojsonTileLayer",l=e.style.getLayerSourceCache(n),c=l?l._state.getState(a,void 0):{},h=this.latestFeatureIndex.loadVTLayers()[a];i.updateDynamicExpressions(s,h,this.tileID.canonical,o,c,r)}i.upload(e.context)}}evaluateQueryRenderedFeaturePadding(){let e=0;for(const t in this.buckets){const i=this.buckets[t];i.evaluateQueryRenderedFeaturePadding&&(e=Math.max(e,i.evaluateQueryRenderedFeaturePadding()))}return e}queryRenderedFeatures(e,t,i,s,o,r,n){if(!this.latestFeatureIndex||!this.latestFeatureIndex.rawTileData&&!this.latestFeatureIndex.is3DTile)return{};const a=this.evaluateQueryRenderedFeaturePadding(),l=function(e,t){const i=Ct([],[.5*e.width,.5*-e.height,1]);return At(i,i,[1,-1,0]),Ie(i,i,e.calculateProjMatrix(t.toUnwrapped())),Float32Array.from(i)}(o,this.tileID);return this.latestFeatureIndex.query(e,{tilespaceGeometry:t,pixelPosMatrix:l,transform:s,availableImages:i,tileTransform:this.tileTransform,worldview:this.worldview,queryRadius:a,scope:n})}querySourceFeatures(e,t){const i=this.latestFeatureIndex;if(!i||!i.rawTileData)return;const s=i.loadVTLayers(),o=t?t.sourceLayer:"",r=s._geojsonTileLayer||s[o];if(!r)return;const n=dt(t&&t.filter),{z:a,x:l,y:c}=this.tileID.canonical,h={z:a,x:l,y:c};for(let t=0;t<r.length;t++){const s=r.feature(t);if(n.needGeometry){const e=ut(s,!0);if(!n.filter(new X(this.tileID.overscaledZ,{worldview:this.worldview}),e,this.tileID.canonical))continue}else if(!n.filter(new X(this.tileID.overscaledZ,{worldview:this.worldview}),s))continue;const d=i.getId(s,o),u=new _t(s,a,l,c,d);u.tile=h,e.push(u)}}loaded(){return"loaded"===this.state||"errored"===this.state}hasData(){return"loaded"===this.state||"reloading"===this.state||"expired"===this.state}patternsLoaded(){return!!this.imageAtlas&&!!this.imageAtlas.patternPositions.size}setExpiryData(e){const t=this.expirationTime;if(e.cacheControl){const t=pt(e.cacheControl);t["max-age"]&&(this.expirationTime=Date.now()+1e3*t["max-age"])}else e.expires&&(this.expirationTime=new Date(e.expires).getTime());if(this.expirationTime){const e=Date.now();let i=!1;if(this.expirationTime>e)i=!1;else if(t)if(this.expirationTime<t)i=!0;else{const s=this.expirationTime-t;s?this.expirationTime=e+Math.max(s,3e4):i=!0}else i=!0;i?(this.expiredRequestCount++,this.state="expired"):this.expiredRequestCount=0}}getExpiryTimeout(){if(this.expirationTime)return this.expiredRequestCount?1e3*(1<<Math.min(this.expiredRequestCount-1,31)):Math.min(this.expirationTime-Date.now(),Math.pow(2,31)-1)}refreshFeatureState(e,t){if(!this.latestFeatureIndex||!this.latestFeatureIndex.rawTileData&&!this.latestFeatureIndex.is3DTile||!e)return;const i=e.style.listImages();this.updateBuckets(e,!1,t,void 0,i)}hasAppearances(e){for(const t in this.buckets)if(e.style.hasLayer(t)&&this.buckets[t].layers.some(e=>e.appearances&&e.appearances.length>0))return!0;return!1}updateBuckets(e,t,i,s,o){if(!this.latestFeatureIndex)return;if(!e.style)return;const r=o||e.style.listImages(),n=e.style.getBrightness();for(const o in this.buckets){if(!e.style.hasLayer(o))continue;const a=this.buckets[o],l=a.layers[0],c=l.sourceLayer||"_geojsonTileLayer",h=e.style.getLayerSourceCache(l);let d=i&&i[c]||{};h&&!i&&(d=h._state.getState(c,void 0));const u=this.imageAtlas?Object.fromEntries(this.imageAtlas.patternPositions):{},_=Object.keys(d).length>0&&!t;a.hasAppearances=a.layers.some(e=>e.appearances&&e.appearances.length>0);const p=_?a.stateDependentLayers:a.layers,f=_&&0!==a.stateDependentLayers.length;if(f||t||s){const i=this.latestFeatureIndex.loadVTLayers();if(a.update(d,i[c],r,u,p,t,n,this.tileID.canonical),a instanceof ct)a.text.uboBinder&&a.text.uboBinder.upload(e.context),a.icon.uboBinder&&a.icon.uboBinder.upload(e.context);else if(a instanceof ht)for(const{id:t}of a.layers)a.uboBinders[t].upload(e.context)}if(f||t||a.hasAppearances){const t={zoom:e.transform.zoom,pitch:e.transform.pitch,brightness:e.style.getBrightness()||0,worldview:e.worldview},i=a.updateAppearances(this.tileID.canonical,d,r,t,e.imageManager,f);i&&i.hasUboChanges&&a instanceof ct&&(a.text.uboBinder&&a.text.uboBinder.upload(e.context),a.icon.uboBinder&&a.icon.uboBinder.upload(e.context))}(a instanceof ht||a instanceof ft)&&e._terrain&&e._terrain.enabled&&h&&a.uploadPending()&&e._terrain._clearRenderCacheForTile(h.id,this.tileID);const m=e&&e.style&&e.style.getOwnLayer(o);m&&(this.queryPadding=Math.max(this.queryPadding,m.queryRadius(a)||0))}}holdingForFade(){return void 0!==this.symbolFadeHoldUntil}symbolFadeFinished(){return!this.symbolFadeHoldUntil||this.symbolFadeHoldUntil<T.now()}clearFadeHold(){this.symbolFadeHoldUntil=void 0}setHoldDuration(e){this.symbolFadeHoldUntil=T.now()+e}setTexture(e,t){const i=t.context,s=i.gl;this.texture=this.texture||t.getTileTexture(e.width),this.texture&&this.texture instanceof k?this.texture.update(e):(this.texture=new k(i,e,s.RGBA8,{useMipmap:!0}),this.texture.bind(s.LINEAR,s.CLAMP_TO_EDGE))}setDependencies(e,t){const i={};for(const e of t)i[e]=!0;this.dependencies[e]=i}hasDependency(e,t){for(const i of e){const e=this.dependencies[i];if(e)for(const i of t)if(e[i])return!0}return!1}clearQueryDebugViz(){}_makeDebugTileBoundsBuffers(e,t){if(!t||"mercator"===t.name||this._tileDebugBuffer)return;const i=mt(fc,this.tileID.canonical,this.tileTransform)[0],s=new gt,o=new vt;for(let e=0;e<i.length;e++){const{x:t,y:r}=i[e];s.emplaceBack(t,r),o.emplaceBack(e)}o.emplaceBack(0),this._tileDebugIndexBuffer=e.createIndexBuffer(o),this._tileDebugBuffer=e.createVertexBuffer(s,yt.members),this._tileDebugSegments=Ye.simpleSegment(0,0,s.length,o.length)}_makeTileBoundsBuffers(e,t){if(this._tileBoundsBuffer||!t||"mercator"===t.name)return;const i=mt(fc,this.tileID.canonical,this.tileTransform)[0];let s,o;if(this.isRaster){const e=function(e,t){const i=He(e,t),s=Math.pow(2,e.z);for(let o=0;o<cc;o++)for(let r=0;r<cc;r++){const n=nt((e.x+(r+pc(r))/lc)/s),a=at((e.y+(o+pc(o))/lc)/s),l=t.project(n,a),c=o*cc+r;dc[2*c+0]=Math.round((l.x*i.scale-i.x)*ae),dc[2*c+1]=Math.round((l.y*i.scale-i.y)*ae)}uc.fill(0),_c.fill(0);for(let e=2045;e>=0;e--){const t=4*e,i=hc[t+0],s=hc[t+1],o=hc[t+2],r=hc[t+3],n=i+o>>1,a=s+r>>1,l=n+a-s,c=a+i-n,h=s*cc+i,d=r*cc+o,u=a*cc+n,_=Math.hypot((dc[2*h+0]+dc[2*d+0])/2-dc[2*u+0],(dc[2*h+1]+dc[2*d+1])/2-dc[2*u+1])>=16;uc[u]=uc[u]||(_?1:0),e<1022&&(uc[u]=uc[u]||uc[(s+c>>1)*cc+(i+l>>1)]||uc[(r+c>>1)*cc+(o+l>>1)])}const o=new Xe,r=new Ke;let n=0;function a(e,t){const i=t*cc+e;return 0===_c[i]&&(o.emplaceBack(dc[2*i+0],dc[2*i+1],e*ae/lc,t*ae/lc),_c[i]=++n),_c[i]-1}function l(e,t,i,s,o,n){const c=e+i>>1,h=t+s>>1;if(Math.abs(e-o)+Math.abs(t-n)>1&&uc[h*cc+c])l(o,n,e,t,c,h),l(i,s,o,n,c,h);else{const l=a(e,t),c=a(i,s),h=a(o,n);r.emplaceBack(l,c,h)}}return l(0,0,lc,lc,lc,0),l(lc,lc,0,0,0,lc),{vertices:o,indices:r}}(this.tileID.canonical,t);s=e.vertices,o=e.indices}else{s=new Xe,o=new Ke;for(const{x:e,y:t}of i)s.emplaceBack(e,t,0,0);const e=xt(s.int16.subarray(0,4*s.length),void 0,4);for(let t=0;t<e.length;t+=3)o.emplaceBack(e[t],e[t+1],e[t+2])}this._tileBoundsBuffer=e.createVertexBuffer(s,Gl.members),this._tileBoundsIndexBuffer=e.createIndexBuffer(o),this._tileBoundsSegments=Ye.simpleSegment(0,0,s.length,o.length)}_makeGlobeTileDebugBuffers(e,t){const i=t.projection;if(!i||"globe"!==i.name||t.freezeTileCoverage)return;const s=this.tileID.canonical,o=bt(s,t),r=wt(o),n=K(t.zoom);let a;n>0&&(a=Tt(new Float64Array(16),t.globeMatrix)),this._makeGlobeTileDebugBorderBuffer(e,s,t,r,a,n),this._makeGlobeTileDebugTextBuffer(e,s,t,r,a,n)}_globePoint(e,t,i,s,o,r,n){let a=Et(e,t,i);if(r){const o=1<<i.z,l=Ae(s.center.lng),c=Pe(s.center.lat),h=(i.x+.5)/o-l;let d=0;h>.5?d=-1:h<-.5&&(d=1);let u=(e/ae+i.x)/o+d,_=(t/ae+i.y)/o;u=(u-l)*s._pixelsPerMercatorPixel+l,_=(_-c)*s._pixelsPerMercatorPixel+c;const p=[u*s.worldSize,_*s.worldSize,0];It(p,p,r),a=St(a,p,n)}return It(a,a,o)}_makeGlobeTileDebugBorderBuffer(e,t,i,s,o,r){const n=new gt,a=new vt,l=new Dt,c=(e,c,h,d,u)=>{const _=(h-e)/(u-1),p=(d-c)/(u-1),f=n.length;for(let h=0;h<u;h++){const d=e+h*_,u=c+h*p;n.emplaceBack(d,u);const m=this._globePoint(d,u,t,i,s,o,r);l.emplaceBack(m[0],m[1],m[2]),a.emplaceBack(f+h)}},h=ae;c(0,0,h,0,16),c(h,0,h,h,16),c(h,h,0,h,16),c(0,h,0,0,16),this._tileDebugIndexBuffer=e.createIndexBuffer(a),this._tileDebugBuffer=e.createVertexBuffer(n,yt.members),this._globeTileDebugBorderBuffer=e.createVertexBuffer(l,Rt.members),this._tileDebugSegments=Ye.simpleSegment(0,0,n.length,a.length)}_makeGlobeTileDebugTextBuffer(e,t,i,s,o,r){const n=ae/4,a=new gt,l=new Ke,c=new Dt,h=25;l.reserve(32),a.reserve(h),c.reserve(h);const d=(e,t)=>h*e+t;for(let e=0;e<h;e++){const l=e*n;for(let e=0;e<h;e++){const h=e*n;a.emplaceBack(h,l);const d=this._globePoint(h,l,t,i,s,o,r);c.emplaceBack(d[0],d[1],d[2])}}for(let e=0;e<4;e++)for(let t=0;t<4;t++){const i=d(e,t),s=d(e,t+1),o=d(e+1,t),r=d(e+1,t+1);l.emplaceBack(i,s,o),l.emplaceBack(o,s,r)}this._tileDebugTextIndexBuffer=e.createIndexBuffer(l),this._tileDebugTextBuffer=e.createVertexBuffer(a,yt.members),this._globeTileDebugTextBuffer=e.createVertexBuffer(c,Rt.members),this._tileDebugTextSegments=Ye.simpleSegment(0,0,h,32)}destroy(e=!0){for(const t in this.buckets)this.buckets[t].destroy(e);this.buckets={},this.imageAtlas&&(this.imageAtlas=null),this.lineAtlas&&(this.lineAtlas=null),this.imageAtlasTexture&&delete this.imageAtlasTexture,this.glyphAtlasTexture&&(this.glyphAtlasTexture.destroy(),delete this.glyphAtlasTexture),this.lineAtlasTexture&&(this.lineAtlasTexture.destroy(),delete this.lineAtlasTexture),this._tileBoundsBuffer&&(this._tileBoundsBuffer.destroy(),this._tileBoundsIndexBuffer.destroy(),this._tileBoundsSegments.destroy(),this._tileBoundsBuffer=null),this._tileDebugBuffer&&(this._tileDebugBuffer.destroy(),this._tileDebugSegments.destroy(),this._tileDebugBuffer=null),this._tileDebugIndexBuffer&&(this._tileDebugIndexBuffer.destroy(),this._tileDebugIndexBuffer=null),this._globeTileDebugBorderBuffer&&(this._globeTileDebugBorderBuffer.destroy(),this._globeTileDebugBorderBuffer=null),this._tileDebugTextBuffer&&(this._tileDebugTextBuffer.destroy(),this._tileDebugTextSegments.destroy(),this._tileDebugTextIndexBuffer.destroy(),this._tileDebugTextBuffer=null),this._globeTileDebugTextBuffer&&(this._globeTileDebugTextBuffer.destroy(),this._globeTileDebugTextBuffer=null),e&&this.texture&&this.texture instanceof k&&(this.texture.destroy(),delete this.texture),this.emissiveTexture&&this.emissiveTexture instanceof k&&(this.emissiveTexture.destroy(),delete this.emissiveTexture),this.hillshadeFBO&&(this.hillshadeFBO.destroy(),delete this.hillshadeFBO),this.dem&&delete this.dem,this.neighboringTiles&&delete this.neighboringTiles,this.demTexture&&(this.demTexture.destroy(),delete this.demTexture),this.rasterParticleState&&(this.rasterParticleState.destroy(),delete this.rasterParticleState),this.latestFeatureIndex=null,this.state="unloaded"}}function xc(e){mc=e}class bc{constructor(e,t){this.max=e,this.onRemove=t,this.reset()}reset(){for(const e in this.data)for(const t of this.data[e])t.timeout&&clearTimeout(t.timeout),this.onRemove(t.value);return this.data={},this.order=[],this}add(e,t,i){const s=e.wrapped().key;void 0===this.data[s]&&(this.data[s]=[]);const o={value:t,timeout:void 0};if(void 0!==i&&(o.timeout=setTimeout(()=>{this.remove(e,o)},i)),this.data[s].push(o),this.order.push(s),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,s=void 0===t?0:this.data[i].indexOf(t),o=this.data[i][s];return this.data[i].splice(s,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 s of this.data[i])e(s.value)||t.push(s);for(const e of t)this.remove(e.value.tileID,e)}}class wc{constructor(){this.state=Object.create(null),this.stateChanges=Object.create(null),this.deletedStates=Object.create(null)}updateState(e,t,i){const s=String(t),o=this.stateChanges[e]=this.stateChanges[e]||Object.create(null),r=o[s]=o[s]||Object.create(null);Object.assign(r,i);const n=this.deletedStates[e];if(null===n){const t=this.deletedStates[e]=Object.create(null);for(const i in this.state[e])i!==s&&(t[i]=null);return}if(!n)return;const a=n[s];if(null===a){const t=n[s]=Object.create(null);for(const o in this.state[e][s])i[o]||(t[o]=null);return}if(a)for(const e in i)null===a[e]&&delete a[e]}removeFeatureState(e,t,i){if(null===this.deletedStates[e])return;const s=String(t);if(this.deletedStates[e]=this.deletedStates[e]||Object.create(null),i&&void 0!==t)null!==this.deletedStates[e][s]&&(this.deletedStates[e][s]=this.deletedStates[e][s]||Object.create(null),this.deletedStates[e][s][i]=null);else if(void 0!==t)if(this.stateChanges[e]&&this.stateChanges[e][s])for(i in this.deletedStates[e][s]=Object.create(null),this.stateChanges[e][s])this.deletedStates[e][s][i]=null;else this.deletedStates[e][s]=null;else this.deletedStates[e]=null}getState(e,t){const i=this.state[e]||Object.create(null),s=this.stateChanges[e]||Object.create(null),o=this.deletedStates[e];if(null===o)return Object.create(null);if(void 0!==t){const e=String(t),r=Object.assign(Object.create(null),i[e],s[e]);if(o){const e=o[t];if(null===e)return Object.create(null);for(const t in e)delete r[t]}return r}const r=Object.assign(Object.create(null),i,s);if(o)for(const e in o)delete r[e];return r}initializeTileState(e,t){e.refreshFeatureState(t)}coalesceChanges(e,t){const i=Object.create(null);for(const e in this.stateChanges){this.state[e]=this.state[e]||Object.create(null);const t=Object.create(null);for(const i in this.stateChanges[e])this.state[e][i]||(this.state[e][i]=Object.create(null)),Object.assign(this.state[e][i],this.stateChanges[e][i]),t[i]=this.state[e][i];i[e]=t}for(const e in this.deletedStates){this.state[e]=this.state[e]||Object.create(null);const t=Object.create(null);if(null===this.deletedStates[e])for(const i in this.state[e])t[i]=Object.create(null),this.state[e][i]=Object.create(null);else for(const i in this.deletedStates[e]){if(null===this.deletedStates[e][i])this.state[e][i]=Object.create(null);else if(this.state[e][i])for(const t of Object.keys(this.deletedStates[e][i]))delete this.state[e][i][t];t[i]=this.state[e][i]}i[e]=i[e]||Object.create(null),Object.assign(i[e],t)}if(this.stateChanges=Object.create(null),this.deletedStates=Object.create(null),0!==Object.keys(i).length)for(const s of e.values())s.refreshFeatureState(t,i)}}class Tc{constructor(e,t){this.bucket=e,this.canonical=t,this.keys=[],this.indices=[],this.stableIdMap=new Map;const i=e.symbolInstances,s=[];for(let t=0;t<i.length;t++){const o=e.stableIdFor(t);if(void 0!==o){this.stableIdMap.set(o,t);continue}const{key:r,tileAnchorX:n,tileAnchorY:a}=i.get(t);s.push(n,a),this.keys.push(r),this.indices.push(t)}this.index=new Lt(this.indices.length,16);for(let e=0;e<s.length;e+=2)this.index.add(s[e],s[e+1]);this.index.finish()}findMatch(e,t,i,s){const o=e.stableIdFor(t);if(void 0!==o){const e=this.stableIdMap.get(o);return void 0===e||s.has(e)?-1:(s.add(e),e)}const r=Math.pow(2,this.canonical.z-i.z),{key:n,tileAnchorX:a,tileAnchorY:l}=e.symbolInstances.get(t),c=i.x*ae+a,h=i.y*ae+l,d=Math.floor(c*r)-this.canonical.x*ae,u=Math.floor(h*r)-this.canonical.y*ae,_=Math.ceil((c+1)*r)-1-this.canonical.x*ae,p=Math.ceil((h+1)*r)-1-this.canonical.y*ae;let f=-1;for(const e of this.index.range(d,u,_,p))this.keys[e]===n&&!s.has(this.indices[e])&&(f<0||e<f)&&(f=e);return f<0?-1:(s.add(this.indices[f]),this.indices[f])}}function Ec(e){const t=new Map,i=[];for(const s of e){const{key:e,overscaledZ:o,canonical:r}=s.tile.tileID;t.set(e,s),i.some(e=>e.overscaledZ===o&&e.z===r.z)||i.push({overscaledZ:o,z:r.z})}return i.sort((e,t)=>t.overscaledZ-e.overscaledZ),{byKey:t,zooms:i}}function Ic(e){const t=[],i=[];for(const s of e)(s.held?i:t).push(s);return{owning:Ec(t),held:Ec(i)}}function Sc(e,t,i,s){const{canonical:o}=e,r=Math.pow(2,s.z-o.z)/ae,n=Math.floor((o.x*ae+t)*r),a=Math.floor((o.y*ae+i)*r);return Pt(e.wrap,s.overscaledZ,s.z,n,a)}function Dc(e,t,i,s,o=1/0){for(const r of e.zooms){if(r.overscaledZ>=o)continue;const n=e.byKey.get(Sc(t,i,s,r));if(n)return n}}function Rc(e,t){return Dc(e,t,0,0,t.overscaledZ)}class Cc{constructor(){this.entries=new Map}clear(){this.entries.clear()}sync(e){const t=new Map,i=[],s=new Map,o=[];for(const r of e){let e=this.entries.get(r.uid);if(e){const t=this._updateBuckets(e);t&&s.set(e,t),e.held!==r.holdingForFade()&&o.push(e)}else e={tile:r,buckets:this._indexBuckets(r),held:r.holdingForFade()},i.push(e);t.set(r.uid,e)}const r=[];for(const[e,i]of this.entries)t.has(e)||r.push(i);if(0===i.length&&0===r.length&&0===s.size&&0===o.length)return;const n=Ic(this.entries.values());for(const e of o)e.held=!e.held;const a=Ic(t.values()),l=i.filter(e=>!e.held),c=r.filter(e=>!e.held);for(const e of o)(e.held?c:l).push(e);const h=new Set(l),d=new Set(l);for(const e of s.keys())e.held||d.add(e);for(const e of c){const t=Rc(a.owning,e.tile.tileID);t&&h.add(t)}for(const e of[...l,...c]){const t=Rc(a.owning,e.tile.tileID);t&&d.add(t)}for(const[e,t]of s)!e.held&&t.size>0&&h.add(e);for(const e of h)this._migrate(e,n,a.owning,s.get(e));this.entries=t;for(const e of d)this._markNonOwned(e,a.owning)}_indexBuckets(e){const t=new Map;for(const i in e.buckets){const s=e.buckets[i];s instanceof ct&&s.layerIds[0]===i&&t.set(i,new Tc(s,e.tileID.canonical))}return t}_updateBuckets(e){const t=e.tile,i=t.tileID.canonical,s=e.buckets;let o=!1;const r=new Map,n=new Map;for(const e in t.buckets){const a=t.buckets[e];if(!(a instanceof ct)||a.layerIds[0]!==e)continue;const l=s.get(e);if(l&&l.bucket===a){n.set(e,l);continue}o=!0,n.set(e,new Tc(a,i));const c=new Uint8Array(a.symbolInstances.length),h=new Set;for(let e=0;e<c.length;e++){const t=l?l.findMatch(a,e,i,h):-1;t<0?c[e]=1:a.takePlacementStateFrom(l.bucket,t,e)}c.includes(1)&&r.set(e,c)}return(o||n.size!==s.size)&&(e.buckets=n),o?r:null}_takeState(e,t,i,s,o,r){const n=e.buckets.get(t);if(!n)return!1;let a=r.get(n);a||(a=new Set,r.set(n,a));const l=n.findMatch(i,s,o.canonical,a);return!(l<0)&&i.takePlacementStateFrom(n.bucket,l,s)}_markNonOwned(e,t){const i=e.tile.tileID;for(const{bucket:s}of e.buckets.values()){s.ensurePlacementState();const o=s.nonOwnedSymbols;for(let r=0;r<o.length;r++){const{tileAnchorX:n,tileAnchorY:a}=s.symbolInstances.get(r);o[r]=Dc(t,i,n,a)!==e?1:0}}}_migrate(e,t,i,s){const o=e.tile.tileID;for(const[r,n]of e.buckets){const a=n.bucket,l=s?s.get(r):void 0,c=new Map;for(let s=0;s<a.symbolInstances.length;s++){const{tileAnchorX:n,tileAnchorY:h}=a.symbolInstances.get(s);if(Dc(i,o,n,h)!==e)continue;if((!l||1!==l[s])&&Dc(t.owning,o,n,h)===e)continue;let d=!1;for(const i of t.owning.zooms){const l=t.owning.byKey.get(Sc(o,n,h,i));if(l&&l!==e&&this._takeState(l,r,a,s,o,c)){d=!0;break}}if(!d)for(const i of t.held.zooms){const l=t.held.byKey.get(Sc(o,n,h,i));if(l&&l!==e&&this._takeState(l,r,a,s,o,c))break}}}}}class Ac extends A{constructor(e,t,i){super(),this.id=e,this._renderSourceType=i,this._maxzoomOverride=null,this.setSource(t),this._tiles=new Map,this._cache=new bc(0,this._unloadTile.bind(this)),this._timers=new Map,this._minTileCacheSize=t.minTileCacheSize,this._maxTileCacheSize=t.maxTileCacheSize,this._loadedParentTiles=new Map,this.placementRelations=new Cc,this.castsShadows=!1,this.tileCoverLift=0,this._coveredTiles=new Set,this._shadowCasterTiles=new Set,this._state=new wc,this._isRaster="raster"===this._source.type||"raster-dem"===this._source.type||"raster-array"===this._source.type||"custom"===this._source.type&&"_dataType"in this._source&&"raster"===this._source._dataType,this._supportsFading="raster"===this._source.type||"raster-array"===this._source.type||"image"===this._source.type||"video"===this._source.type||"custom"===this._source.type,this._isRasterElevatedOverTerrain=!1}onAdd(e){this.map=e,this._minTileCacheSize=void 0===this._minTileCacheSize&&e?e._minTileCacheSize:this._minTileCacheSize,this._maxTileCacheSize=void 0===this._maxTileCacheSize&&e?e._maxTileCacheSize:this._maxTileCacheSize}setSource(e){e.on("data",e=>{"source"===e.dataType&&"metadata"===e.sourceDataType&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&"source"===e.dataType&&"content"===e.sourceDataType&&(this.reload(),this.transform&&this.update(this.transform))}),e.on("error",()=>{this._sourceErrored=!0}),this._source=e}loaded(){if(this._sourceErrored)return!0;if(this._source instanceof Jl)return this._source.loaded();if(!this._sourceLoaded)return!1;if(!this._source.loaded())return!1;for(const e of this._tiles.values())if(!e.loaded())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)}setMaxzoomOverride(e){this._maxzoomOverride=e}_loadTile(e,t){return e.renderSourceType=this._renderSourceType,e.isExtraShadowCaster=this._shadowCasterTiles.has(e.tileID.key),this._source.loadTile(e,t)}_unloadTile(e){if(e.aborted=!0,this._abortTile(e),this._source.unloadTile)return this._source.unloadTile(e)}_abortTile(e){if(this._source.abortTile)return this._source.abortTile(e)}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,i]of this._tiles)i.upload(e,this.map?this.map.painter:void 0),i.imageAtlas&&!i.imageAtlasTexture&&"loaded"===i.state&&this._reloadTile(t,"reloading"),i.prepare(this.map.style.imageManager,this.map?this.map.painter:null,this._source.scope)}getIds(){return Array.from(this._tiles.values(),e=>e.tileID).sort(Lc).map(e=>e.key)}getRenderableIds(e,t){const i=[];for(const s of this._tiles.values())this._isTileRenderable(s,e,t)&&i.push(s);return e?i.sort((e,t)=>{const i=e.tileID,s=t.tileID,o=new m(i.canonical.x,i.canonical.y)._rotate(this.transform.angle),r=new m(s.canonical.x,s.canonical.y)._rotate(this.transform.angle);return i.overscaledZ-s.overscaledZ||r.y-o.y||r.x-o.x}).map(e=>e.tileID.key):i.map(e=>e.tileID).sort(Lc).map(e=>e.key)}hasRenderableParent(e){const t=this.findLoadedParent(e,0);return!!t&&this._isIdRenderable(t.tileID.key)}_isIdRenderable(e,t,i){const s=this._tiles.get(e);return!!s&&this._isTileRenderable(s,t,i)}_isTileRenderable(e,t,i){const s=e.tileID.key;return e.hasData()&&!this._coveredTiles.has(s)&&(t||!e.holdingForFade())&&(i||!this._shadowCasterTiles.has(s))}reload(){if(this._paused)this._shouldReloadOnResume=!0;else{this._cache.reset();for(const[e,t]of this._tiles)"errored"!==t.state&&this._reloadTile(e,"reloading")}}_reloadTile(e,t){const i=this._tiles.get(e);i&&("loading"!==i.state&&(i.state=t),this._loadTile(i,this._tileLoaded.bind(this,i,e,t)))}_tileLoaded(e,t,i,s,o){if(e.aborted)return;if(s){if(e.state="errored",Mt(s)){if(this._source.fire(new M("data",{dataType:"source",sourceDataType:"error",sourceId:this._source.id,tile:e})),!this._loadedParentTiles.has(e.tileID.key))return;if("raster-dem"===this._source.type&&this.usedForTerrain&&this.map.painter.terrain){const e=this.map.painter.terrain;this.update(this.transform,e.getScaledDemTileSize(),!0),e.resetTileLookupCache(this.id)}else this.update(this.transform)}else this._source.fire(new P(s,{tile:e}));return}e.timeAdded=T.now(),"expired"===i&&(e.refreshedUponExpiration=!0),this._setTileReloadTimer(t,e),"raster-dem"===this._source.type&&e.dem&&this._backfillDEM(e),this._state.initializeTileState(e,this.map?this.map.painter:null);let r=new Headers;o&&o.headers&&(r=o.headers),this._syncPlacementRelations(),this._source.fire(new M("data",{dataType:"source",tile:e,coord:e.tileID,sourceCacheId:this.id,responseHeaders:r}))}_syncPlacementRelations(){if(!this.map||"global"!==this.map._placementAlgorithm)return;const e=[];for(const t of this._tiles.values())this._isTileRenderable(t,!0)&&e.push(t);this.placementRelations.sync(e)}_hasTunnelGeometry(){for(const e of this._tiles.values())if(e.hasTunnelGeometry)return!0;return!1}_backfillDEM(e){const t=this.getRenderableIds();for(let s=0;s<t.length;s++){const o=t[s];if(e.neighboringTiles&&e.neighboringTiles[o]){const t=this.getTileByID(o);i(e,t),i(t,e)}}function i(e,t){if(!e.dem||e.dem.borderReady)return;e.needsHillshadePrepare=!0,e.needsDEMTextureUpload=!0;let i=t.tileID.canonical.x-e.tileID.canonical.x;const s=t.tileID.canonical.y-e.tileID.canonical.y,o=Math.pow(2,e.tileID.canonical.z),r=t.tileID.key;0===i&&0===s||Math.abs(s)>1||(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,s),e.neighboringTiles&&e.neighboringTiles[r]&&(e.neighboringTiles[r].backfilled=!0)))}}getTile(e){return this.getTileByID(e.key)}getTileByID(e){return this._tiles.get(e)}_retainLoadedChildren(e,t,i,s){const o="raster-array"===this._source.type;for(const[r,n]of this._tiles){let a=n;if(s.has(r)||!a.hasData()||a.tileID.overscaledZ<=t||a.tileID.overscaledZ>i)continue;if(o&&a.parentTile)continue;let l=a.tileID;for(;a&&a.tileID.overscaledZ>t+1;){const e=a.tileID.scaledTo(a.tileID.overscaledZ-1);a=this._tiles.get(e.key),a&&a.hasData()&&(l=e)}let c=l;for(;c.overscaledZ>t;)if(c=c.scaledTo(c.overscaledZ-1),e.has(c.key)){s.set(l.key,l);const e=this._tiles.get(l.key);e&&(e.dashIdealZ=c.overscaledZ);break}}}findLoadedParent(e,t){if(this._loadedParentTiles.has(e.key)){const i=this._loadedParentTiles.get(e.key);return i&&i.tileID.overscaledZ>=t?i:null}for(let i=e.overscaledZ-1;i>=t;i--){const t=e.scaledTo(i),s=this._getLoadedTile(t);if(s)return s}}_getLoadedTile(e){const t=this._tiles.get(e.key);return t&&t.hasData()?t:this._cache.getByKey(this._source.reparseOverscaled?e.wrapped().key:e.canonical.key)}updateCacheSize(e,t){t=t||this._source.tileSize;const i=Math.ceil(e.width/t)+1,s=Math.ceil(e.height/t)+1,o=Math.floor(i*s*5),r="number"==typeof this._minTileCacheSize?Math.max(this._minTileCacheSize,o):o,n="number"==typeof this._maxTileCacheSize?Math.min(this._maxTileCacheSize,r):r;this._cache.setMaxSize(n)}handleWrapJump(e){const t=Math.round((e-(void 0===this._prevLng?e:this._prevLng))/360);if(this._prevLng=e,t){const e=new Map;for(const i of this._tiles.values())i.tileID=i.tileID.unwrapTo(i.tileID.wrap+t),e.set(i.tileID.key,i);this._tiles=e;for(const e of this._timers.values())clearTimeout(e);this._timers.clear();for(const[e,t]of this._tiles)this._setTileReloadTimer(e,t)}}update(e,t,i,s,o){if(this.transform=e,!this._sourceLoaded||this._paused||this.transform.freezeTileCoverage)return;if(this.usedForTerrain&&!i)return;this.updateCacheSize(e,t),"globe"!==this.transform.projection.name&&this.handleWrapJump(this.transform.center.lng),this._shadowCasterTiles=new Set,this._coveredTiles=new Set;const r="batched-model"===this._source.type;let n,a=this._source.maxzoom;null!==this._maxzoomOverride&&(a=Math.min(a,this._maxzoomOverride));const l=this.map&&this.map.painter?this.map.painter._terrain:null;if(l&&l.sourceCache===this&&l.attenuationRange()){const e=l.attenuationRange()[0],t=Math.floor(e)-Math.log2(l.getDemUpscale());a>t&&(a=t)}const c=null===this._maxzoomOverride&&this._source.reparseOverscaled;if(this.used||this.usedForTerrain)if(this._source.tileID)n=e.getVisibleUnwrappedCoordinates(this._source.tileID).map(e=>new Ge(e.canonical.z,e.wrap,e.canonical.z,e.canonical.x,e.canonical.y));else if(0!==this.tileCoverLift){const s=e.clone();s.tileCoverLift=this.tileCoverLift,n=s.coveringTiles({tileSize:t||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:a,roundZoom:this._source.roundZoom&&!i,reparseOverscaled:c,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:r}),this._source.minzoom<=1&&"globe"===e.projection.name&&(n.push(new Ge(1,0,1,0,0)),n.push(new Ge(1,0,1,1,0)),n.push(new Ge(1,0,1,0,1)),n.push(new Ge(1,0,1,1,1)))}else n=e.coveringTiles({tileSize:t||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:a,roundZoom:this._source.roundZoom&&!i,reparseOverscaled:c,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:r});else n=[];if(n.length>0&&"globe"!==this.transform.projection.name&&!this.usedForTerrain&&!this._supportsFading){const l=e.coveringZoomLevel({tileSize:t||this._source.tileSize,roundZoom:this._source.roundZoom&&!i}),c=Math.min(l,a);if(r){const t=e.extendTileCover(n,c);for(const e of t)n.push(e)}else if(o){const t=this.transform.getFrustum(c),i=e.extendTileCoverToNearPlane(n,t,c);for(const e of i)n.push(e);if(c>=18&&this._hasTunnelGeometry()){const i=e.extendTileCoverForTunnels(n,t,c,20);for(const e of i)n.push(e)}}else if(this.castsShadows&&s){const t=e.extendTileCover(n,c,s,16);for(const e of t)this._shadowCasterTiles.add(e.key),n.push(e)}}for(const e of this._tiles.values())e.dashIdealZ=e.tileID.overscaledZ;this._source.hasTile&&(n=n.filter(e=>this._source.hasTile(e)));const h=this._updateRetainedTiles(n);if(this._supportsFading&&0!==n.length){const e=new Map,t=new Set,i=T.now();for(const[s,o]of h){const r=this._tiles.get(s);if(!r||void 0!==r.fadeEndTime&&r.fadeEndTime<=i)continue;const n=this.findLoadedParent(o,Math.max(o.overscaledZ-Ac.maxOverzooming,this._source.minzoom));n&&(this._addTile(n.tileID),e.set(n.tileID.key,n.tileID)),t.add(s)}const s=n.at(-1).overscaledZ;for(const[e,i]of this._tiles){if(h.has(e)||!i.hasData())continue;let o=i.tileID;for(;o.overscaledZ>s;){o=o.scaledTo(o.overscaledZ-1);const s=this._tiles.get(o.key);if(s&&s.hasData()&&t.has(o.key)){h.set(e,i.tileID);break}}}for(const[t,i]of e)h.has(t)||(this._coveredTiles.add(t),h.set(t,i))}for(const e of h.keys())this._tiles.get(e).clearFadeHold();for(const[e,t]of this._tiles)h.has(e)||(t.hasSymbolBuckets&&!t.holdingForFade()?t.setHoldDuration(this.map._fadeDuration):t.hasSymbolBuckets&&!t.symbolFadeFinished()||this._removeTile(e));this._updateLoadedParentTileCache(),this._syncPlacementRelations(),this._renderSourceType===Ot.Symbol&&this._source.afterUpdate&&this._source.afterUpdate()}releaseSymbolFadeTiles(){let e=!1;for(const[t,i]of this._tiles)i.holdingForFade()&&(this._removeTile(t),e=!0);e&&this._syncPlacementRelations()}_updateRetainedTiles(e){const t=new Map;if(0===e.length)return t;const i=new Set,s=e.reduce((e,t)=>Math.min(e,t.overscaledZ),1/0),o=e[0].overscaledZ,r=Math.max(o-Ac.maxOverzooming,this._source.minzoom),n=Math.max(o+Ac.maxUnderzooming,this._source.minzoom),a=new Set;for(const i of e){const e=this._addTile(i);t.set(i.key,i),e.hasData()||s<this._source.maxzoom&&a.add(i.key)}if(this._retainLoadedChildren(a,s,n,t),"raster-array"===this._source.type){const i=this._source,s=this._tiles;for(const o of i.collectOverzoomParentTileIDs(s,e))t.set(o.key,o)}for(const s of e){let e=this._tiles.get(s.key);if(e.hasData())continue;if(s.canonical.z>=this._source.maxzoom){const e=s.children(this._source.maxzoom)[0],i=this.getTile(e);if(i&&i.hasData()){t.set(e.key,e),i.dashIdealZ=s.overscaledZ;continue}}else{const e=s.children(this._source.maxzoom);if(t.has(e[0].key)&&t.has(e[1].key)&&t.has(e[2].key)&&t.has(e[3].key))continue}let o=e.wasRequested();for(let n=s.overscaledZ-1;n>=r;--n){const r=s.scaledTo(n);if(i.has(r.key))break;if(i.add(r.key),e=this.getTile(r),!e&&o&&(e=this._addTile(r)),e&&(t.set(r.key,r),e.dashIdealZ=s.overscaledZ,o=e.wasRequested(),e.hasData()))break}}return t}_updateLoadedParentTileCache(){this._loadedParentTiles.clear();for(const e of this._tiles.values()){const t=[];let i,s=e.tileID;for(;s.overscaledZ>0;){if(this._loadedParentTiles.has(s.key)){i=this._loadedParentTiles.get(s.key);break}t.push(s.key);const e=s.scaledTo(s.overscaledZ-1);if(i=this._getLoadedTile(e),i)break;s=e}for(const e of t)this._loadedParentTiles.set(e,i)}}_addTile(e){let t=this._tiles.get(e.key);const i=this._shadowCasterTiles.has(e.key);if(t)return!0!==t.isExtraShadowCaster||i||this._reloadTile(e.key,"reloading"),t;t=this._cache.getAndRemove(e),t&&(this._setTileReloadTimer(e.key,t),t.tileID=e,this._state.initializeTileState(t,this.map?this.map.painter:null),t.resetPlacementVisibility());const s=Boolean(t);if(!s){const i=this.map?this.map.painter:null,s=this._source.tileSize*e.overscaleFactor();t="raster-array"===this._source.type?function(e,t,i,s,o){if(!mc)throw new Error("Raster-array module is not loaded.");return mc(e,t,i,s,o)}(e,s,this.transform.tileZoom,i,this._isRaster):new yc(e,s,this.transform.tileZoom,i,this._isRaster,this._source.worldview),this._loadTile(t,this._tileLoaded.bind(this,t,e.key,t.state))}return t.uses++,this._tiles.set(e.key,t),s||this._source.fire(new M("dataloading",{tile:t,coord:t.tileID,dataType:"source"})),t}_setTileReloadTimer(e,t){clearTimeout(this._timers.get(e)),this._timers.delete(e);const i=t.getExpiryTimeout();i&&this._timers.set(e,setTimeout(()=>{this._reloadTile(e,"expired"),this._timers.delete(e)},i))}_removeTile(e){const t=this._tiles.get(e);t&&(t.uses--,this._tiles.delete(e),clearTimeout(this._timers.get(e)),this._timers.delete(e),t.uses>0||(t.hasData()&&"reloading"!==t.state||"empty"===t.state?this._cache.add(t.tileID,t,t.getExpiryTimeout()):this._unloadTile(t)))}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(const e of this._tiles.keys())this._removeTile(e);this._source._clear&&this._source._clear(),this._cache.reset(),this.placementRelations.clear(),this.map&&this.usedForTerrain&&this.map.painter.terrain&&this.map.painter.terrain.resetTileLookupCache(this.id)}tilesIn(e,t,i){const s=[],o=this.transform;if(!o)return s;const r="globe"===o.projection.name,n=Ae(o.center.lng),a=o.getFreeCameraOptions().position||new we(0,0,0);for(const l of this._tiles.values()){if(i&&l.clearQueryDebugViz(),l.holdingForFade())continue;let c;if(r){const e=l.tileID.canonical;if(0===e.z){const t=[Math.abs(Ee(n,...Pc(e,-1))-n),Math.abs(Ee(n,...Pc(e,1))-n)];c=[0,2*t.indexOf(Math.min(...t))-1]}else{const t=[Math.abs(Ee(n,...Pc(e,-1))-n),Math.abs(Ee(n,...Pc(e,0))-n),Math.abs(Ee(n,...Pc(e,1))-n)];c=[t.indexOf(Math.min(...t))-1]}}else c=[0];for(const i of c){const r=e.containsTile(l,o,t,i,a);r&&s.push(r)}}return s}getShadowCasterCoordinates(){return this._getRenderableCoordinates(!1,!0)}getVisibleCoordinates(e){return this._getRenderableCoordinates(e)}_getRenderableCoordinates(e,t){if(!this.transform)return[];const i=this.getRenderableIds(e,t).map(e=>this._tiles.get(e).tileID),s="globe"===this.transform.projection.name;for(const e of i)e.projMatrix=this.transform.calculateProjMatrix(e.toUnwrapped()),e.expandedProjMatrix=s?this.transform.calculateProjMatrix(e.toUnwrapped(),!1,!0):e.projMatrix;return i}sortCoordinatesByDistance(e){if(!this.transform)return e.slice();const t=e.slice(),i=this.transform._camera.position,s=this.transform._camera.forward(),o=new Map;for(const e of t){const t=1/(1<<e.canonical.z);o.set(e.key,((e.canonical.x+.5)*t+e.wrap-i[0])*s[0]+((e.canonical.y+.5)*t-i[1])*s[1]-i[2]*s[2])}return t.sort((e,t)=>o.get(e.key)-o.get(t.key)),t}hasTransition(){if(this._source.hasTransition())return!0;if(this._supportsFading){const e=T.now();for(const t of this._tiles.values())if(void 0!==t.fadeEndTime&&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 s=this._tiles.get(e);s&&s.setDependencies(t,i)}reloadTilesForDependencies(e,t){for(const[i,s]of this._tiles)s.hasDependency(e,t)&&this._reloadTile(i,"reloading");this._cache.filter(i=>!i.hasDependency(e,t))}_preloadTiles(e,t){if(!this._sourceLoaded){const i=()=>{this._sourceLoaded&&(this._source.off("data",i),this._preloadTiles(e,t))};return void this._source.on("data",i)}const i=new Map,s=Array.isArray(e)?e:[e],o=this.map.painter.terrain,r=this.usedForTerrain&&o?o.getScaledDemTileSize():this._source.tileSize;for(const e of s){const t=e.coveringTiles({tileSize:r,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom&&!this.usedForTerrain,reparseOverscaled:this._source.reparseOverscaled,isTerrainDEM:this.usedForTerrain});for(const e of t)i.set(e.key,e);this.usedForTerrain&&e.updateElevation(!1)}const n=Array.from(i.values());j(n,(e,t)=>{const i=new yc(e,this._source.tileSize*e.overscaleFactor(),this.transform.tileZoom,this.map.painter,this._isRaster,this._source.worldview);this._loadTile(i,e=>{"raster-dem"===this._source.type&&i.dem&&this._backfillDEM(i),t(e,i)})},t)}}function Lc(e,t){const i=Math.abs(2*e.wrap)-+(e.wrap<0),s=Math.abs(2*t.wrap)-+(t.wrap<0);return e.overscaledZ-t.overscaledZ||s-i||t.canonical.y-e.canonical.y||t.canonical.x-e.canonical.x}function Pc(e,t){const i=1<<e.z;return[e.x/i+t,(e.x+1)/i+t]}Ac.maxOverzooming=10,Ac.maxUnderzooming=3;class Mc{constructor(e){this.style=e,this.layersGotHidden=!1,this.layers=[]}processLayersChanged(){this.layers=[];const e=!1,t=!1;for(const i in this.style._mergedLayers){const s=this.style._mergedLayers[i];if("fill-extrusion"===s.type||"building"===s.type)this.layers.push({layer:s,visible:e,visibilityChanged:t});else if("model"===s.type){const i=this.style.getLayerSource(s);i&&"batched-model"===i.type&&this.layers.push({layer:s,visible:e,visibilityChanged:t})}}}onNewFrame(e){this.layersGotHidden=!1;for(const t of this.layers){const i=t.layer;let s=!1;"fill-extrusion"===i.type?s=!i.isHidden(e)&&i.paint.get("fill-extrusion-opacity")>0:"building"===i.type?s=!i.isHidden(e)&&i.paint.get("building-opacity")>0:"model"===i.type&&(s=!i.isHidden(e)&&i.paint.get("model-opacity").constantOr(1)>0),this.layersGotHidden=this.layersGotHidden||!s&&t.visible,t.visible=s}}updateZOffset(e,t){this.currentBuildingBuckets=[];for(const e of this.layers){const i=e.layer,s=this.style.getLayerSourceCache(i);let o=1;"fill-extrusion"===i.type?o=e.visible?i.paint.get("fill-extrusion-vertical-scale"):0:"building"===i.type&&(o=e.visible?i.paint.get("building-vertical-scale"):0);let r=s?s.getTile(t):null;if(!r&&s)for(const e of s._tiles.values())if(t.canonical.isChildOf(e.tileID.canonical)){r=e;break}this.currentBuildingBuckets.push({bucket:r?r.getBucket(i):null,tileID:r?r.tileID:t,verticalScale:o})}e.hasAnyZOffset=!1;let i=!1;for(let s=0;s<e.symbolInstances.length;s++){const o=e.symbolInstances.get(s),r=o.zOffset,n=this._getHeightAtTileOffset(t,o.tileAnchorX,o.tileAnchorY);o.zOffset=n!==Number.NEGATIVE_INFINITY?n:r,i||r===o.zOffset||(i=!0),e.hasAnyZOffset||0===o.zOffset||(e.hasAnyZOffset=!0)}i&&(e.zOffsetBuffersNeedUpload=!0,e.zOffsetSortDirty=!0)}hasLayerForSourceCache(e){for(const{layer:t}of this.layers){const i=this.style.getLayerSourceCache(t);if(i&&i.id===e)return!0}return!1}_mapCoordToOverlappingTile(e,t,i,s){let o=t,r=i;if(e.canonical.z!==s.canonical.z){const n=s.canonical,a=1/(1<<e.canonical.z-n.z);o=(t+e.canonical.x*ae)*a-n.x*ae|0,r=(i+e.canonical.y*ae)*a-n.y*ae|0}return{tileX:o,tileY:r}}_getHeightAtTileOffset(e,t,i){let s,o;for(let r=0;r<this.layers.length;++r){const n=this.layers[r].layer;if("fill-extrusion"!==n.type&&"building"!==n.type)continue;const{bucket:a,tileID:l,verticalScale:c}=this.currentBuildingBuckets[r];if(!a)continue;const{tileX:h,tileY:d}=this._mapCoordToOverlappingTile(e,t,i,l),u=a.getHeightAtTileCoord(h,d);u&&void 0!==u.height&&(u.hidden?s=u.height:o=Math.max(u.height*c,o||0))}if(void 0!==o)return o;for(let o=0;o<this.layers.length;++o){const r=this.layers[o];if("model"!==r.layer.type||!r.visible)continue;const{bucket:n,tileID:a}=this.currentBuildingBuckets[o];if(!n)continue;const{tileX:l,tileY:c}=this._mapCoordToOverlappingTile(e,t,i,a),h=n.getHeightAtTileCoord(l,c);if(h&&!h.hidden)return void 0===h.height&&void 0!==s?Math.min(h.maxHeight,s)*h.verticalScale:h.height?h.height*h.verticalScale:Number.NEGATIVE_INFINITY}return this.layersGotHidden?0:Number.NEGATIVE_INFINITY}}function Oc(){return gc||(gc=new dl),gc}function zc(){Oc().acquire(hl)}function Fc(){const e=gc;e&&(e.isPreloaded()&&1===e.numActive()?(e.release(hl),gc=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()"))}function kc(e,t){const i={},s=e,o=t,r=i;for(const e in s)"ref"!==e&&(r[e]=s[e]);return zt.forEach(e=>{e in o&&(r[e]=o[e])}),i}function Bc(e){e=e.slice();const t=Object.create(null);for(const i of e)t[i.id]=i;for(let i=0;i<e.length;i++){const s=e[i];if(s&&"ref"in s){const o=t[s.ref];o&&(e[i]=kc(s,o))}}return e}const Nc=Math.tan(85*Math.PI/180);function Uc(e,t,i,s,o,r,n){const a=Bt();if(i)if("globe"===r.name){const e=Nt(o,t);Ie(a,a,e)}else{const e=Ut([],n);a[0]=e[0],a[1]=e[1],a[4]=e[2],a[5]=e[3],s||kt(a,a,o.angle)}else Ie(a,o.labelPlaneMatrix,e);return a}function Vc(e,t,i,s,o,r,n){const a=Uc(e,t,i,s,o,r,n);return"globe"===r.name&&i||(a[2]=a[6]=a[10]=a[14]=0),a}function jc(e,t,i,s,o,r,n){if(i){if("globe"===r.name){const a=Uc(e,t,i,s,o,r,n);return Tt(a,a),Ie(a,e,a),a}{const t=Ft(e),[i,r,a,l]=n,[c,h,d,u,_,p,f,m]=t;return t[0]=i*c+r*_,t[1]=i*h+r*p,t[2]=i*d+r*f,t[3]=i*u+r*m,t[4]=a*c+l*_,t[5]=a*h+l*p,t[6]=a*d+l*f,t[7]=a*u+l*m,s||kt(t,t,-o.angle),t}}return o.glCoordMatrix}function Gc(e,t,i,s){const o=[e,t,i,1];i?Se(o,o,s):Vt(o,o,s);const r=o[3];return o[0]/=r,o[1]/=r,o[2]/=r,o}function qc(e,t){return Math.min(.5+e/t*.5,1.5)}function Zc(e,t){const i=e[0]/e[3],s=e[1]/e[3];return i>=-t[0]&&i<=t[0]&&s>=-t[1]&&s<=t[1]}function Wc(e,t,i,s,o,r,n,a,l,c,h=1){const d=i.transform,u=s?e.textSizeData:e.iconSizeData,_=jt(u,i.transform.zoom,h),p="globe"===d.projection.name,f=(()=>{if(!p)return null;const e=K(d.zoom);return 0===e?null:{t:e,invMatrix:d.projection.createInversionMatrix(d,c.canonical),mercCenter:[Ae(d.center.lng),Pe(d.center.lat)]}})(),g=[256/i.width*2+1,256/i.height*2+1],v=s?e.text.dynamicLayoutVertexArray:e.icon.dynamicLayoutVertexArray;v.clear();let y=null;p&&(y=s?e.text.globeExtVertexArray:e.icon.globeExtVertexArray);const x=e.lineVertexArray,b=s?e.text.placedSymbolArray:e.icon.placedSymbolArray,w=i.transform.width/i.transform.height;let T,E=!1;for(let h=0;h<b.length;h++){const p=b.get(h),{numGlyphs:I,writingMode:S}=p;if(S!==Gt.vertical||E||T===Gt.horizontal||(E=!0),T=S,(p.hidden||S===Gt.vertical)&&!E){th(I,v);continue}E=!1;const D=new m(p.tileAnchorX,p.tileAnchorY),R="road"===e.elevationType,C=!!d.elevation||R;let{x:A,y:L,z:P}=d.projection.projectTilePoint(D.x,D.y,c.canonical);if(f){const[e,t,i]=Yc(D,c.canonical,f);A+=(e-A)*f.t,L+=(t-L)*f.t,P+=(i-P)*f.t}let M=null;if(C){M=R&&e.hdExt?e.hdExt.makeRoadSymbolElevationParams(e,s?e.text:e.icon,h,c,l,d.elevation,d.projection,d.center.lat,d.worldSize):{getElevation:l,elevation:d.elevation,elevationFeature:null};const[t,i,o]=M.getElevation(D,d.elevation,M.elevationFeature);A+=t,L+=i,P+=o}const O=[A,L,P,1];if(Se(O,O,t),!Zc(O,g)){th(I,v);continue}const z=O[3],F=qc(i.transform.getCameraToCenterDistance(d.projection),z),k=Yt(u,_,p),B=n?k/F:k*F,N=Gc(A,L,P,o);if(N[3]<=0){th(I,v);continue}let U={};const V=le(e.layers[0].layout.get("text-max-angle")),j=Math.cos(V),G=n?null:M,q=Xc(p,B,!1,a,t,o,r,e.glyphOffsetArray,x,v,y,N,D,U,w,G,d.projection,c,n,j,f);E=q.useVertical,G&&q.needsFlipping&&(U={}),(q.notEnoughRoom||E||q.needsFlipping&&Xc(p,B,!0,a,t,o,r,e.glyphOffsetArray,x,v,y,N,D,U,w,G,d.projection,c,n,j,f).notEnoughRoom)&&th(I,v)}s?(e.text.dynamicLayoutVertexBuffer.updateData(v),y&&e.text.globeExtVertexBuffer&&e.text.globeExtVertexBuffer.updateData(y)):(e.icon.dynamicLayoutVertexBuffer.updateData(v),y&&e.icon.globeExtVertexBuffer&&e.icon.globeExtVertexBuffer.updateData(y))}function Hc(e,t,i,s,o,r,n,a,l,c,h,d,u,_,p,f,m,g){const{lineStartIndex:v,glyphStartIndex:y,segment:x}=a,b=y+a.numGlyphs,w=v+a.lineLength,T=t.getoffsetX(y),E=t.getoffsetX(b-1),I=eh(e*T,i,s,o,r,n,x,v,w,l,c,h,d,u,!0,_,p,f,m,g);if(!I)return null;const S=eh(e*E,i,s,o,r,n,x,v,w,l,c,h,d,u,!0,_,p,f,m,g);return S?{first:I,last:S}:null}function $c(e,t,i,s){return e===Gt.horizontal&&Math.abs(s)>Math.abs(i)?{useVertical:!0}:e===Gt.vertical?s>0?{needsFlipping:!0}:null:0!==t&&function(e,t){return 0===e||Math.abs(t/e)>Nc}(i,s)?1===t?{needsFlipping:!0}:null:i<0?{needsFlipping:!0}:null}function Xc(e,t,i,s,o,r,n,a,l,c,h,d,u,_,p,f,g,v,y,x,b){const w=t/24,T=e.lineOffsetX*w,E=e.lineOffsetY*w,{lineStartIndex:I,glyphStartIndex:S,numGlyphs:D,segment:R,writingMode:C,flipState:A}=e,L=I+e.lineLength,P=e=>{if(h){const[t,i,s]=e.up,o=c.length;$t(h,o+0,t,i,s),$t(h,o+1,t,i,s),$t(h,o+2,t,i,s),$t(h,o+3,t,i,s)}const[t,i,s]=e.point;Xt(c,t,i,s,e.angle)};if(D>1){const t=Hc(w,a,T,E,i,d,u,e,l,r,_,f,!1,g,v,y,x,b);if(!t)return{notEnoughRoom:!0};if(s&&!i){let[i,s,o]=t.first.point,[r,a,l]=t.last.point;[i,s]=Gc(i,s,o,n),[r,a]=Gc(r,a,l,n);const c=$c(C,A,(r-i)*p,a-s);if(e.flipState=c&&c.needsFlipping?1:2,c)return c}P(t.first);for(let e=S+1;e<S+D-1;e++){const t=eh(w*a.getoffsetX(e),T,E,i,d,u,R,I,L,l,r,_,f,!1,!1,g,v,y,x,b);if(!t)return c.length-=4*(e-S),{notEnoughRoom:!0};P(t)}P(t.last)}else{if(s&&!i){const t=Gc(u.x,u.y,0,o),i=I+R+1,s=new m(l.getx(i),l.gety(i)),r=Gc(s.x,s.y,0,o),n=r[3]>0?r:Jc(u,s,t,1,o,void 0,g,v.canonical),a=$c(C,A,(n[0]-t[0])*p,n[1]-t[1]);if(e.flipState=a&&a.needsFlipping?1:2,a)return a}const t=eh(w*a.getoffsetX(S),T,E,i,d,u,R,I,L,l,r,_,f,!1,!1,g,v,y,x,b);if(!t)return{notEnoughRoom:!0};P(t)}return{}}function Yc(e,t,i){const s=1<<t.z;let o=(e.x/ae+t.x)/s-i.mercCenter[0];const r=(e.y/ae+t.y)/s-i.mercCenter[1];o-=Math.round(o);const n=[o*ae,r*ae,ae/(2*Math.PI),1];return Se(n,n,i.invMatrix),[n[0],n[1],n[2]]}function Kc(e,t,i,s,o,r){let{x:n,y:a,z:l}=s.projectTilePoint(e.x,e.y,t);if(r){const[i,s,o]=Yc(e,t,r);n+=(i-n)*r.t,a+=(s-a)*r.t,l+=(o-l)*r.t}if(!o)return Gc(n,a,l,i);const[c,h,d]=o.getElevation(e,o.elevation,o.elevationFeature);return Gc(n+c,a+h,l+d,i)}function Jc(e,t,i,s,o,r,n,a,l){const c=Kc(e.sub(t)._unit()._add(e),a,o,n,r,l);return ve(c,i,c),ye(c,c),Wt(c,i,c,s)}function Qc(e,t,i,s,o,r,n,a,l,c,h){const d=r[e];if(d)return d;const u=Kc(t,c,n,l,a,h);return u[3]>0?r[e]=u:Jc(i,t,s,o,n,a,l,c,h)}function eh(e,t,i,s,o,r,n,a,l,c,h,d,u,_,p,f,g,v,y,x){const b=s?e-t:e+t;let w=b>0?1:-1,T=0;s&&(w*=-1,T=Math.PI),w<0&&(T+=Math.PI);let E=a+n+(w>0?0:1)|0,I=o,S=o,D=0,R=0;const C=Math.abs(b),A=[],L=[];let P=r,M=P,O=qt([]);for(;D+R<=C;){if(E+=w,E<a||E>=l)return null;S=I,M=P,A.push(S),_&&L.push(M),P=new m(c.getx(E),c.gety(E)),I=Qc(E,P,M,S,C-D+1,d,h,u,f,g.canonical,x),D+=R;const e=ve([],I,S),t=Zt(S,I);if(i&&t>0&&R>0&&Kt(O,e)/(R*t)<y)return null;R=t,O=e}p&&u&&(d[E]&&(I=Jc(M,P,S,C-D+1,h,u,f,g.canonical,x),R=Zt(S,I),O=ve([],I,S)),d[E]=I);const z=(C-D)/R,F=P.sub(M)._mult(z)._add(M),k=Wt([],S,O,z);let B=[0,0,1],N=O[0],U=O[1];if(v&&(B=f.upVector(g.canonical,F.x,F.y),0!==B[0]||0!==B[1]||1!==B[2])){const e=[B[2],0,-B[0]],t=Ht([],B,e);ye(e,e),ye(t,t),N=Kt(O,e),U=Kt(O,t)}if(i){const e=Ht([],B,O);ye(e,e),Wt(k,k,e,i*w)}const V=T+Math.atan2(U,N);return A.push(k),_&&L.push(F),{point:k,angle:V,path:A,tilePath:L,up:B}}function th(e,t){const i=t.length,s=i+4*e;t.resize(s),t.float32.fill(-1/0,4*i,4*s)}class ih{constructor(e,t){this.reset(e,t)}reset(e,t){this.points=e||[],this._distances=[0];for(let e=1;e<this.points.length;e++)this._distances[e]=this._distances[e-1]+this.points[e].dist(this.points[e-1]);this.length=this._distances.at(-1),this.padding=Math.min(t||0,.5*this.length),this.paddedLength=this.length-2*this.padding}lerp(e){if(1===this.points.length)return this.points[0];e=Ee(e,0,1);let t=1,i=this._distances[t];const s=e*this.paddedLength+this.padding;for(;i<s&&t<this._distances.length;)i=this._distances[++t];const o=t-1,r=this._distances[o],n=i-r,a=n>0?(s-r)/n:0;return this.points[o].mult(1-a).add(this.points[t].mult(a))}}const sh=100;class oh{constructor(e,t){this.gridRightBoundary=0,this.gridBottomBoundary=0,this.clippedSymbols=new Map,this.reset(e,t)}reset(e,t){const i=e.width+200,s=e.height+200;i!==this.gridRightBoundary||s!==this.gridBottomBoundary?(this.grid=new Jt(i,s,25),this.ignoredGrid=new Jt(i,s,25)):(this.grid.clear(),this.ignoredGrid.clear()),this.transform=e,this.fogState=t,this.pitchfactor=Math.cos(e._pitch)*e.cameraToCenterDistance,this.screenRightBoundary=e.width+sh,this.screenBottomBoundary=e.height+sh,this.gridRightBoundary=i,this.gridBottomBoundary=s,this.clippedSymbols.clear()}clearClippedSymbolsForBucket(e){this.clippedSymbols.delete(e)}markSymbolAsClipped(e,t){let i=this.clippedSymbols.get(e);i||(i=new Set,this.clippedSymbols.set(e,i)),i.add(t)}placeCollisionBox(e,t,i,s,o,r,n,a,l,c,h){let d=i.projectedAnchorX,u=i.projectedAnchorY,_=i.projectedAnchorZ;const p=i.tileAnchorX,f=i.tileAnchorY,m=i.elevation,g=i.tileID,v=e.getProjection();if(m&&g){const[e,t,s]=v.upVector(g.canonical,i.tileAnchorX,i.tileAnchorY),o=v.upVectorScale(g.canonical,this.transform.center.lat,this.transform.worldSize).metersToTile;d+=e*m*o,u+=t*m*o,_+=s*m*o}const y="globe"===e.projection.name,x="globe"===e.projection.name?K(this.transform.zoom):0;if(g&&y&&x<1&&!r){const e=1<<g.canonical.z,t=Qt(p,f);ei(t,t,1/ae),ti(t,t,Qt(g.canonical.x,g.canonical.y)),ei(t,t,1/e),ii(t,t,Qt(s[0],s[1])),t[0]=si(t[0],-.5,.5),ei(t,t,ae);const i=oi(t[0],t[1],ae/(2*Math.PI),1);Se(i,i,o),d=J(d,i[0],x),u=J(u,i[1],x),_=J(_,i[2],x)}const b=this.projectAndGetPerspectiveRatio(c,d,u,_,i.tileID,"globe"===v.name||!!m||this.transform.pitch>0,v),w=l*b.perspectiveRatio,T=(i.x1*t+n.x-i.padding)*w+b.point.x,E=(i.y1*t+n.y-i.padding)*w+b.point.y,I=(i.x2*t+n.x+i.padding)*w+b.point.x,S=(i.y2*t+n.y+i.padding)*w+b.point.y,D=b.perspectiveRatio<=hi||b.occluded;return!this.isInsideGrid(T,E,I,S)||!a&&this.grid.hitTest(T,E,I,S,h)||D?{box:[],offscreen:!1,occluded:b.occluded}:{box:[T,E,I,S],offscreen:this.isOffscreen(T,E,I,S),occluded:!1}}placeCollisionCircles(e,t,i,s,o,r,n,a,l,c,h,d,u,_,p,f){const g=this.transform.elevation,v=e.getProjection(),y="road"===e.elevationType,x=!!g||y,b=ri.getAtTileOffsetFunc(f,this.transform.center.lat,this.transform.worldSize,v),w=new m(i.tileAnchorX,i.tileAnchorY),T=new m(i.tileAnchorX,i.tileAnchorY);let{x:E,y:I,z:S}=v.projectTilePoint(T.x,T.y,f.canonical),D=null;if(x){D=y&&e.hdExt?e.hdExt.makeRoadSymbolElevationParams(e,e.text,s,f,b,g,v,this.transform.center.lat,this.transform.worldSize):{getElevation:b,elevation:g,elevationFeature:null};const[t,i,o]=D.getElevation(w,g,D.elevationFeature);E+=t,I+=i,S+=o}const R="globe"===v.name,C=this.projectAndGetPerspectiveRatio(a,E,I,S,f,R||!!g||this.transform.pitch>0,v),{perspectiveRatio:A}=C,L=(d?n/A:n*A)/ui,P=Gc(E,I,S,l),M=i.lineOffsetX*L,O=i.lineOffsetY*L,z=le(e.layers[0].layout.get("text-max-angle")),F=Math.cos(z),k=C.signedDistanceFromCamera>0?Hc(L,r,M,O,y&&1===i.flipState,P,T,i,o,l,{},x&&!d?D:null,d&&x,v,f,d,F):null;if(!k||C.occluded)return{circles:[],offscreen:!0,collisionDetected:!1,occluded:C.occluded};const{first:B,last:N}=k,U=function(e,t){const i=[];for(let t=e.path.length-1;t>=1;t--)i.push(e.path[t]);for(let e=1;e<t.path.length;e++)i.push(t.path[e]);return i}(B,N);c&&function(e,t,i,s,o){const r=i.path.length;for(let n=0;n<e.length;n++){const a=e[n];let l=a[2];o&&(l=o.getElevation(n<r-1?i.tilePath[r-1-n]:s.tilePath[n-r+2],o.elevation,o.elevationFeature)[2]);const c=Gc(a[0],a[1],l,t);if(c[3]<=0)return void(e.length=0);e[n]=c}}(U,c,B,N,x&&!R?D:null);let V=[];if(U.length>0){let e=1/0,t=-1/0,i=1/0,s=-1/0;for(const o of U)e=Math.min(e,o[0]),i=Math.min(i,o[1]),t=Math.max(t,o[0]),s=Math.max(s,o[1]);const o=-100,r=-100,n=this.screenRightBoundary,a=this.screenBottomBoundary;if(t>=o&&e<=n&&s>=r&&i<=a){const l=[];for(const e of U)l.push(new m(e[0],e[1]));V=[l],(e<o||t>n||i<r||s>a)&&(V=ni(V,o,r,n,a))}}return this.placeCirclesAlongThePath(V,.5*_*A+p,t,h,u)}placeCirclesAlongThePath(e,t,i,s,o){const r=2.5*t,n=[];let a=!1,l=!1,c=!0;const h=new ih;for(const d of e){h.reset(d,.25*t);const e=h.length<=.5*t?1:Math.ceil(h.paddedLength/r)+1;for(let r=0;r<e;r++){const d=r/Math.max(e-1,1),u=h.lerp(d),_=u.x+sh,p=u.y+sh;n.push(_,p,t,0);const f=_-t,m=p-t,g=_+t,v=p+t;if(c=c&&this.isOffscreen(f,m,g,v),l=l||this.isInsideGrid(f,m,g,v),!i&&this.grid.hitTestCircle(_,p,t,o)){if(!s)return{circles:[],offscreen:!1,collisionDetected:!0,occluded:!1};a=!0}}}return{circles:!s&&a||!l?[]:n,offscreen:c,collisionDetected:a,occluded:!1}}queryRenderedSymbols(e){if(0===e.length||0===this.grid.keysLength()&&0===this.ignoredGrid.keysLength())return{};const t=[];let i=1/0,s=1/0,o=-1/0,r=-1/0;for(const n of e){const e=new m(n.x+sh,n.y+sh);i=Math.min(i,e.x),s=Math.min(s,e.y),o=Math.max(o,e.x),r=Math.max(r,e.y),t.push(e)}const n=this.grid.query(i,s,o,r).concat(this.ignoredGrid.query(i,s,o,r)),a={},l={};for(const e of n){const i=e.key;if(void 0===a[i.bucketInstanceId]&&(a[i.bucketInstanceId]={}),a[i.bucketInstanceId][i.featureIndex])continue;const s=this.clippedSymbols.get(i.bucketInstanceId);if(s&&s.has(i.featureIndex))continue;const o=[new m(e.x1,e.y1),new m(e.x2,e.y1),new m(e.x2,e.y2),new m(e.x1,e.y2)];ai(t,o)&&(a[i.bucketInstanceId][i.featureIndex]=!0,void 0===l[i.bucketInstanceId]&&(l[i.bucketInstanceId]=[]),l[i.bucketInstanceId].push(i.featureIndex))}return l}insertCollisionBox(e,t,i,s,o){(t?this.ignoredGrid:this.grid).insert({bucketInstanceId:i,featureIndex:s,collisionGroupID:o},e[0],e[1],e[2],e[3])}insertCollisionCircles(e,t,i,s,o){const r=t?this.ignoredGrid:this.grid,n={bucketInstanceId:i,featureIndex:s,collisionGroupID:o};for(let t=0;t<e.length;t+=4)r.insertCircle(n,e[t],e[t+1],e[t+2])}projectAndGetPerspectiveRatio(e,t,i,s,o,r,n){const a=[t,i,s,1];let l=!1;s||this.transform.pitch>0?(Se(a,a,e),this.fogState&&o&&"globe"!==n.name&&(l=li(this.fogState,t,i,s,o.toUnwrapped(),this.transform)>di)):Vt(a,a,e);const c=a[3];return{point:new m((a[0]/c+1)/2*this.transform.width+sh,(-a[1]/c+1)/2*this.transform.height+sh),perspectiveRatio:Math.min(.5+this.transform.getCameraToCenterDistance(n)/c*.5,1.5),signedDistanceFromCamera:c,occluded:r&&a[2]>c||l}}isOffscreen(e,t,i,s){return i<sh||e>=this.screenRightBoundary||s<sh||t>this.screenBottomBoundary}isInsideGrid(e,t,i,s){return i>=0&&e<this.gridRightBoundary&&s>=0&&t<this.gridBottomBoundary}getViewportMatrix(){const e=ci([]);return At(e,e,[-100,-100,0]),e}}class rh{constructor(e,t,i,s){this.opacity=e?Math.max(0,Math.min(1,e.opacity+(e.placed?t:-t))):s&&i?1:0,this.placed=i}isHidden(){return 0===this.opacity&&!this.placed}}class nh{constructor(e,t,i,s,o,r=!1){this.text=new rh(e?e.text:null,t,i,o),this.icon=new rh(e?e.icon:null,t,s,o),this.clipped=r}isHidden(){return this.text.isHidden()&&this.icon.isHidden()}}class ah{constructor(e,t,i,s=!1,o=!1){this.text=e,this.icon=t,this.skipFade=i,this.clipped=s,this.dynamicFiltered=o}}class lh{constructor(){this.invProjMatrix=Bt(),this.viewportMatrix=Bt(),this.circles=[]}}class ch{constructor(e,t,i,s,o){this.bucketInstanceId=e,this.featureIndex=t,this.sourceLayerIndex=i,this.bucketIndex=s,this.tileID=o}}class hh{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 dh(e,t,i,s,o){const{horizontalAlign:r,verticalAlign:n}=mi(e),a=-(r-.5)*t,l=-(n-.5)*i,c=vi(e,s);return new m(a+c[0]*o,l+c[1]*o)}function uh(e,t,i,s,o){const r=new m(e,t);return i&&r._rotate(s?o:-o),r}function _h(e,t,i,s){const{leftJustifiedTextSymbolIndex:o,centerJustifiedTextSymbolIndex:r,rightJustifiedTextSymbolIndex:n,verticalPlacedTextSymbolIndex:a,crossTileID:l}=i,c=yi(t),h=s===Gt.vertical?a:"left"===c?o:"center"===c?r:"right"===c?n:-1;o>=0&&(e.text.placedSymbolArray.get(o).crossTileID=h>=0&&o!==h?0:l),r>=0&&(e.text.placedSymbolArray.get(r).crossTileID=h>=0&&r!==h?0:l),n>=0&&(e.text.placedSymbolArray.get(n).crossTileID=h>=0&&n!==h?0:l),a>=0&&(e.text.placedSymbolArray.get(a).crossTileID=h>=0&&a!==h?0:l)}function ph(e,t,i){const s=t===Gt.horizontal||t===Gt.horizontalOnly?t:0,o=t===Gt.vertical?t:0,{leftJustifiedTextSymbolIndex:r,centerJustifiedTextSymbolIndex:n,rightJustifiedTextSymbolIndex:a,verticalPlacedTextSymbolIndex:l}=i,c=e.text.placedSymbolArray;r>=0&&(c.get(r).placedOrientation=s),n>=0&&(c.get(n).placedOrientation=s),a>=0&&(c.get(a).placedOrientation=s),l>=0&&(c.get(l).placedOrientation=o)}class fh{constructor(e,t,i,s,o,r,n){this.transform=e.clone(),this.projection=e.projection.name,n instanceof oh?(n.reset(this.transform,o),this.collisionIndex=n):this.collisionIndex=new oh(this.transform,o),this.buildingIndex=r,this.frontCutoffStart=0,this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=t,this.retainedQueryData={},this.collisionGroups=new hh(i),this.collisionCircleArrays={},this.dynamicFilters=new Map,this.prevPlacement=s,s&&(s.prevPlacement=void 0),this.placedOrientations={},this.lastReplacementSourceUpdateTime=0}getBucketParts(e,t,i,s,o=1){const r=i.getBucket(t),n=i.latestFeatureIndex;if(!r||!n||t.fqid!==r.layerIds[0])return;const a=r.layers[0].layout,l=r.layers[0].paint,c=i.collisionBoxArray,h=Math.pow(2,this.transform.zoom-i.tileID.overscaledZ),d=i.tileSize/ae,u=i.tileID.toUnwrapped();this.transform.setProjection(r.projection);const _=_i(i.tileID,r.getProjection(),this.transform,this.projection),p="map"===a.get("text-pitch-alignment"),f="map"===a.get("text-rotation-alignment");t.compileFilter(t.options);const m=t.dynamicFilter(),g=t.dynamicFilterNeedsFeature(),v=t.dynamicFilterNeedsGeometry(),y=this.transform.calculatePixelsToTileUnitsMatrix(i),x=Vc(_,i.tileID.canonical,p,f,this.transform,r.getProjection(),y);let b=null;const w=r.getProjection().createInversionMatrix(this.transform,i.tileID.canonical);if(p){const e=jc(_,i.tileID.canonical,p,f,this.transform,r.getProjection(),y);b=Ie([],this.transform.labelPlaneMatrix,e)}let T=null;if(m&&i.latestFeatureIndex){this.dynamicFilters.set(t.fqid,m);const e=this.prevPlacement;T={unwrappedTileID:u,canReusePrevResult:!!e&&!!e.retainedQueryData[r.bucketInstanceId]&&e.dynamicFilters.get(t.fqid)===m&&this.transform.equals(e.transform)&&this.transform.cameraWorldSize===e.transform.cameraWorldSize,dynamicFilter:m,dynamicFilterNeedsFeature:g,needGeometry:v}}this.retainedQueryData[r.bucketInstanceId]=new ch(r.bucketInstanceId,n,r.sourceLayerIndex,r.index,i.tileID);const[E,I]=r.layers[0].layout.get("text-size-scale-range"),S=Ee(o,E,I),[D,R]=a.get("icon-size-scale-range"),C=Ee(o,D,R),A={bucket:r,layout:a,paint:l,posMatrix:_,invMatrix:w,mercatorCenter:[Ae(this.transform.center.lng),Pe(this.transform.center.lat)],textLabelPlaneMatrix:x,labelToScreenMatrix:b,clippingData:T,scale:h,textPixelRatio:d,holdingForFade:i.holdingForFade(),collisionBoxArray:c,partiallyEvaluatedTextSize:jt(r.textSizeData,this.transform.zoom,S),partiallyEvaluatedIconSize:jt(r.iconSizeData,this.transform.zoom,C),collisionGroup:this.collisionGroups.get(r.sourceID),latestFeatureIndex:i.latestFeatureIndex};if(s)for(const t of r.sortKeyRanges){const{sortKey:i,symbolInstanceStart:s,symbolInstanceEnd:o}=t;e.push({sortKey:i,symbolInstanceStart:s,symbolInstanceEnd:o,parameters:A})}else e.push({symbolInstanceStart:0,symbolInstanceEnd:r.symbolInstances.length,parameters:A})}placeLayerBucketPart(e,t,i,s=1){const{bucket:o,layout:r,paint:n,posMatrix:a,textLabelPlaneMatrix:l,labelToScreenMatrix:c,clippingData:h,textPixelRatio:d,mercatorCenter:u,invMatrix:p,holdingForFade:f,collisionBoxArray:g,partiallyEvaluatedTextSize:v,partiallyEvaluatedIconSize:y,collisionGroup:x,latestFeatureIndex:b}=e.parameters,w=r.get("text-optional"),T=r.get("icon-optional"),E=r.get("text-allow-overlap"),I=r.get("icon-allow-overlap"),S="map"===r.get("text-rotation-alignment"),D="map"===r.get("icon-rotation-alignment"),R="map"===r.get("text-pitch-alignment"),C=n.get("symbol-z-offset"),A="sea"===r.get("symbol-elevation-reference"),L=r.get("symbol-placement"),P=r.get("text-variable-anchor"),M=S&&"point"!==L,O=D&&"point"!==L,z=P&&o.hasTextData(),F=o.hasIconTextFit()&&z&&o.hasIconData();this.transform.setProjection(o.projection);const k=z||M,B=O||F;let N=E&&(I||!o.hasIconData()||T),U=I&&(E||!o.hasTextData()||w);const V=!C.isConstant(),j=(e,s)=>{const{crossTileID:n,numVerticalGlyphVertices:_}=e,D=o.getCollisionArrays(g,e);let L=null;const M=h&&h.canReusePrevResult?this.prevPlacement.placements[n]:void 0;if(M&&M.dynamicFiltered)return this.placements[n]=new ah(!1,!1,!1,!0,!0),void t.add(n);if(h&&h.dynamicFilterNeedsFeature&&!M||V){const t=this.retainedQueryData[o.bucketInstanceId],i=b.loadFeature({featureIndex:e.featureIndex,bucketIndex:t.bucketIndex,sourceLayerIndex:t.sourceLayerIndex,layoutVertexArrayOffset:0}),s=i.properties?i.properties.worldview:null;if(o.localizable&&o.worldview&&"string"==typeof s)if("all"===s)i.properties.$localized=!0;else{if(!s.split(",").includes(o.worldview))return;i.properties.$localized=!0,i.properties.worldview=o.worldview}L=h&&h.needGeometry?ut(i,!0):i}if(h&&!M&&!(0,h.dynamicFilter)({zoom:this.transform.zoom,pitch:this.transform.pitch,worldview:o.worldview},L,this.retainedQueryData[o.bucketInstanceId].tileID.canonical,new m(e.tileAnchorX,e.tileAnchorY),this.transform.calculateDistanceTileData(h.unwrappedTileID)))return this.placements[n]=new ah(!1,!1,!1,!0,!0),void t.add(n);const O=C.evaluate(L,{});if((e.zOffset||0)+(O||0)>0&&this.frontCutoffStart>0){const i=2*this.frontCutoffStart-1,s=[e.tileAnchorX,e.tileAnchorY,0,1],o=Se(fi(),s,a);if(o[1]/o[3]<i)return this.placements[n]=new ah(!1,!1,!1,!0),void t.add(n)}if(t.has(n))return;if(f)return void(this.placements[n]=new ah(!1,!1,!1));let z=!1,F=!1,j=!0,G=!1,q=!1,Z=null,W={box:null,offscreen:null,occluded:null},H={box:null},$=null,X=null,Y=null,K=0,J=0,Q=0;D.textFeatureIndex?K=D.textFeatureIndex:e.useRuntimeCollisionCircles&&(K=e.featureIndex),D.verticalTextFeatureIndex&&(J=D.verticalTextFeatureIndex);const ee=t=>{t.tileID=this.retainedQueryData[o.bucketInstanceId].tileID;const i=this.transform.elevation;if("road"===o.elevationType)t.elevation=A?O:O+ri.getAtTileOffset(t.tileID,new m(t.tileAnchorX,t.tileAnchorY),i,null);else{const s=o.hdExt?o.hdExt.elevationFeatures[e.elevationFeatureIndex]:void 0;t.elevation=A?O:O+ri.getAtTileOffset(t.tileID,new m(t.tileAnchorX,t.tileAnchorY),i,s)}t.elevation+=e.zOffset},te=D.textBox;if(te){ee(te);const t=t=>{let i=Gt.horizontal;if(o.allowVerticalPlacement&&!t&&this.prevPlacement){const t=this.prevPlacement.placedOrientations[n];t&&(this.placedOrientations[n]=t,i=t,ph(o,i,e))}return i},i=(e,t)=>{if(o.allowVerticalPlacement&&_>0&&D.verticalTextBox){for(const i of o.writingModes)if(i===Gt.vertical?(W=t(),H=W):W=e(),W&&W.box&&W.box.length)break}else W=e()};if(P){let r=P;if(this.prevPlacement&&this.prevPlacement.variableOffsets[n]){const e=this.prevPlacement.variableOffsets[n];r.indexOf(e.anchor)>0&&(r=r.filter(t=>t!==e.anchor),r.unshift(e.anchor))}const l=(t,i,n)=>{const l=o.getSymbolInstanceTextSize(v,e,this.transform.zoom,s),c=(t.x2-t.x1)*l+2*t.padding,h=(t.y2-t.y1)*l+2*t.padding,_=e.hasIconTextFit&&!I?i:null;_&&ee(_);let f={box:[],offscreen:!1,occluded:!1};const m=E?2*r.length:r.length;for(let i=0;i<m;++i){const m=this.attemptAnchorPlacement(r[i%r.length],t,u,p,k,c,h,l,S,R,d,a,x,i>=r.length,e,s,o,n,_,v,y);if(m&&(f=m.placedGlyphBoxes,f&&f.box&&f.box.length)){z=!0,Z=m.shift;break}}return f};i(()=>l(te,D.iconBox,Gt.horizontal),()=>{const e=D.verticalTextBox;return e&&ee(e),o.allowVerticalPlacement&&!(W&&W.box&&W.box.length)&&_>0&&e?l(e,D.verticalIconBox,Gt.vertical):{box:null,offscreen:null,occluded:null}}),W&&(z=W.box,j=W.offscreen,G=W.occluded);const c=t(!(!W||!W.box));if(!z&&this.prevPlacement){const t=this.prevPlacement.variableOffsets[n];t&&(this.variableOffsets[n]=t,_h(o,t.anchor,e,c))}}else{const r=(t,i)=>{const r=o.getSymbolInstanceTextSize(v,e,this.transform.zoom,s),l=this.collisionIndex.placeCollisionBox(o,r,t,u,p,k,new m(0,0),E,d,a,x.predicate);return l&&l.box&&l.box.length&&(ph(o,i,e),this.placedOrientations[n]=i),l};i(()=>r(te,Gt.horizontal),()=>{const e=D.verticalTextBox;return o.allowVerticalPlacement&&_>0&&e?(ee(e),r(e,Gt.vertical)):{box:null,offscreen:null,occluded:null}}),t(!!(W&&W.box&&W.box.length))}}if($=W,z=$&&$.box&&$.box.length>0,j=$&&$.offscreen,G=$&&$.occluded,e.useRuntimeCollisionCircles){const t=e.centerJustifiedTextSymbolIndex>=0?e.centerJustifiedTextSymbolIndex:e.verticalPlacedTextSymbolIndex,s=o.text.placedSymbolArray.get(t),n=Yt(o.textSizeData,v,s),h=r.get("text-padding");X=this.collisionIndex.placeCollisionCircles(o,E,s,t,o.lineVertexArray,o.glyphOffsetArray,n,a,l,c,i,R,x.predicate,e.collisionCircleDiameter*n/ui,h,this.retainedQueryData[o.bucketInstanceId].tileID),z=E||X.circles.length>0&&!X.collisionDetected,j=j&&X.offscreen,G=X.occluded}if(D.iconFeatureIndex&&(Q=D.iconFeatureIndex),D.iconBox){const t=t=>{ee(t);const i=e.hasIconTextFit&&Z?uh(Z.x,Z.y,S,R,this.transform.angle):new m(0,0),s=o.getSymbolInstanceIconSize(y,this.transform.zoom,e.placedIconSymbolIndex);return this.collisionIndex.placeCollisionBox(o,s,t,u,p,B,i,I,d,a,x.predicate)};H&&H.box&&H.box.length&&D.verticalIconBox?(Y=t(D.verticalIconBox),F=Y.box.length>0):(Y=t(D.iconBox),F=Y.box.length>0),j=j&&Y.offscreen,q=Y.occluded}const ie=w||0===e.numHorizontalGlyphVertices&&0===_,se=T||0===e.numIconVertices;if(ie||se?se?ie||(F=F&&z):z=F&&z:F=z=F&&z,z&&$&&$.box&&this.collisionIndex.insertCollisionBox($.box,r.get("text-ignore-placement"),o.bucketInstanceId,H&&H.box&&J?J:K,x.ID),F&&Y&&this.collisionIndex.insertCollisionBox(Y.box,r.get("icon-ignore-placement"),o.bucketInstanceId,Q,x.ID),X&&(z&&this.collisionIndex.insertCollisionCircles(X.circles,r.get("text-ignore-placement"),o.bucketInstanceId,K,x.ID),i)){const e=o.bucketInstanceId;let t=this.collisionCircleArrays[e];void 0===t&&(t=this.collisionCircleArrays[e]=new lh);for(let e=0;e<X.circles.length;e+=4)t.circles.push(X.circles[e+0]),t.circles.push(X.circles[e+1]),t.circles.push(X.circles[e+2]),t.circles.push(X.collisionDetected?1:0)}const oe="globe"!==o.projection.name;N=N&&(oe||!G),U=U&&(oe||!q),this.placements[n]=new ah(z||N,F||U,j||o.justReloaded),t.add(n)},G=this.retainedQueryData[o.bucketInstanceId].tileID;if("offset"===o.elevationType&&this.buildingIndex&&this.buildingIndex.updateZOffset(o,G),"road"===o.elevationType&&o.hdExt&&o.hdExt.updateRoadElevation(o,G.canonical),o.updateZOffset(),o.sortFeaturesByY){const e=o.getSortedSymbolIndexes(this.transform.angle);for(let t=e.length-1;t>=0;--t){const i=e[t];j(o.symbolInstances.get(i),i)}o.hasAnyZOffset&&_(`${o.layerIds[0]} layer symbol-z-elevate: symbols are not sorted by elevation if symbol-z-order is evaluated to viewport-y`)}else if(o.hasAnyZOffset){const e=o.getSortedIndexesByZOffset();for(let t=0;t<e.length;++t){const i=e[t];j(o.symbolInstances.get(i),i)}}else for(let t=e.symbolInstanceStart;t<e.symbolInstanceEnd;t++)j(o.symbolInstances.get(t),t);if(i&&o.bucketInstanceId in this.collisionCircleArrays){const e=this.collisionCircleArrays[o.bucketInstanceId];Tt(e.invProjMatrix,a),e.viewportMatrix=this.collisionIndex.getViewportMatrix()}o.justReloaded=!1}attemptAnchorPlacement(e,t,i,s,o,r,n,a,l,c,h,d,u,_,p,f,m,g,v,y,x){const{textOffset0:b,textOffset1:w,crossTileID:T}=p,E=[b,w],I=dh(e,r,n,E,a),S=this.collisionIndex.placeCollisionBox(m,a,t,i,s,o,uh(I.x,I.y,l,c,this.transform.angle),_,h,d,u.predicate);if(v){const e=m.getSymbolInstanceIconSize(x,this.transform.zoom,p.placedIconSymbolIndex);if(0===this.collisionIndex.placeCollisionBox(m,e,v,i,s,o,uh(I.x,I.y,l,c,this.transform.angle),_,h,d,u.predicate).box.length)return}if(S.box.length>0){let t;return this.prevPlacement&&this.prevPlacement.variableOffsets[T]&&this.prevPlacement.placements[T]&&this.prevPlacement.placements[T].text&&(t=this.prevPlacement.variableOffsets[T].anchor),this.variableOffsets[T]={textOffset:E,width:r,height:n,anchor:e,textScale:a,prevAnchor:t},_h(m,e,p,g),m.allowVerticalPlacement&&(ph(m,g,p),this.placedOrientations[T]=g),{shift:I,placedGlyphBoxes:S}}}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 s=t?t.symbolFadeChange(e):1,o=t?t.opacities:{},r=t?t.variableOffsets:{},n=t?t.placedOrientations:{};for(const e in this.placements){const t=this.placements[e],r=o[e];r?(this.opacities[e]=new nh(r,s,t.text,t.icon,null,t.clipped),i=i||t.text!==r.text.placed||t.icon!==r.icon.placed):(this.opacities[e]=new nh(null,s,t.text,t.icon,t.skipFade,t.clipped),i=i||t.text||t.icon)}for(const e in o){const t=o[e];if(!this.opacities[e]){const o=new nh(t,s,!1,!1);o.isHidden()||(this.opacities[e]=o,i=i||t.text.placed||t.icon.placed)}}for(const e in r)this.variableOffsets[e]||!this.opacities[e]||this.opacities[e].isHidden()||(this.variableOffsets[e]=r[e]);for(const e in n)this.placedOrientations[e]||!this.opacities[e]||this.opacities[e].isHidden()||(this.placedOrientations[e]=n[e]);i?this.lastPlacementChangeTime=e:"number"!=typeof this.lastPlacementChangeTime&&(this.lastPlacementChangeTime=t?t.lastPlacementChangeTime:e)}updateLayerOpacities(e,t,i,s,o=!1,r=1){s&&(this.lastReplacementSourceUpdateTime=s.updateTime);const n=new Set;for(const a of t){const t=a.getBucket(e);if(t&&a.latestFeatureIndex&&e.fqid===t.layerIds[0]&&(this.updateBucketOpacities(t,n,a,a.collisionBoxArray,i,s,a.tileID,e.scope),"offset"===t.elevationType&&this.buildingIndex&&this.buildingIndex.updateZOffset(t,a.tileID),"road"===t.elevationType&&t.hdExt&&t.hdExt.updateRoadElevation(t,a.tileID.canonical),t.updateZOffset(),o&&a.collisionBoxArray)){const e=t.layers[0].layout,[i,s]=e.get("text-size-scale-range"),[o,n]=e.get("icon-size-scale-range"),l=Ee(r,i,s),c=Ee(r,o,n);t.updateCollisionDebugBuffers(this.transform.zoom,a.collisionBoxArray,l,c)}}}updateBucketOpacities(e,t,i,s,o,r,n,a){e.hasTextData()&&e.text.opacityVertexArray.clear(),e.hasIconData()&&e.icon.opacityVertexArray.clear(),e.hasIconCollisionBoxData()&&e.iconCollisionBox.collisionVertexArray.clear(),e.hasTextCollisionBoxData()&&e.textCollisionBox.collisionVertexArray.clear();const l=e.layers[0].layout,c=new nh(null,0,!1,!1,!0),h=l.get("text-allow-overlap"),d=l.get("icon-allow-overlap"),u=!!s&&(e.hasIconCollisionBoxData()||e.hasTextCollisionBoxData()),_=new nh(null,0,h&&(d||!e.hasIconData()||l.get("icon-optional")),d&&(h||!e.hasTextData()||l.get("text-optional")),!0);let p=!1,f=!1,m=0;r&&e.updateReplacement(n,r),this.collisionIndex.clearClippedSymbolsForBucket(e.bucketInstanceId);for(let s=0;s<e.symbolInstances.length;s++){const l=e.symbolInstances.get(s),{numHorizontalGlyphVertices:h,numVerticalGlyphVertices:d,crossTileID:g,numIconVertices:v,tileAnchorX:y,tileAnchorY:x}=l,b=t.has(g);let w=this.opacities[g];b?w=c:w||(w=_,this.opacities[g]=w),t.add(g);const T=h>0||d>0,E=v>0,I=this.placedOrientations[g],S=I===Gt.vertical,D=I===Gt.horizontal||I===Gt.horizontalOnly;!T&&!E||w.isHidden()||m++;const R=(T||E)&&!!r&&pi(e.activeReplacements,y,x,n.canonical,o,gi.Symbol,a);if(R&&this.collisionIndex.markSymbolAsClipped(e.bucketInstanceId,l.featureIndex),T){const t=R?Sh:Ih(w.text);mh(e.text,h,S?Sh:t)&&(p=!0),mh(e.text,d,D?Sh:t)&&(p=!0);const i=w.text.isHidden(),{leftJustifiedTextSymbolIndex:s,centerJustifiedTextSymbolIndex:o,rightJustifiedTextSymbolIndex:r,verticalPlacedTextSymbolIndex:n}=l,a=e.text.placedSymbolArray,c=i||S?1:0;s>=0&&(a.get(s).hidden=c),o>=0&&(a.get(o).hidden=c),r>=0&&(a.get(r).hidden=c),n>=0&&(a.get(n).hidden=i||D?1:0);const u=this.variableOffsets[g];u&&_h(e,u.anchor,l,I);const _=this.placedOrientations[g];_&&(_h(e,"left",l,_),ph(e,_,l))}if(E){const t=R?Sh:Ih(w.icon),{placedIconSymbolIndex:i,verticalPlacedIconSymbolIndex:s}=l,o=e.icon.placedSymbolArray,r=w.icon.isHidden()?1:0;i>=0&&(mh(e.icon,v,S?Sh:t)&&(f=!0),o.get(i).hidden=r),s>=0&&(mh(e.icon,l.numVerticalIconVertices,D?Sh:t)&&(f=!0),o.get(s).hidden=r)}u&&this.updateCollisionBoxes(e,l,w,S,D,i)}if(e.fullyClipped=0===m,e.sortFeatures(this.transform.angle),this.retainedQueryData[e.bucketInstanceId]&&(this.retainedQueryData[e.bucketInstanceId].featureSortOrder=e.featureSortOrder),p&&e.hasTextData()&&e.text.opacityVertexBuffer&&e.text.opacityVertexBuffer.updateData(e.text.opacityVertexArray),f&&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.bucketInstanceId in this.collisionCircleArrays){const t=this.collisionCircleArrays[e.bucketInstanceId];e.placementInvProjMatrix=t.invProjMatrix,e.placementViewportMatrix=t.viewportMatrix,e.collisionCircleArray=t.circles,delete this.collisionCircleArrays[e.bucketInstanceId]}}updateCollisionBoxes(e,t,i,s,o,r){const n=e.layers[0].layout,a=e.layers[0].paint.get("symbol-z-offset"),l="sea"===n.get("symbol-elevation-reference");let c=null;const h=this.retainedQueryData[e.bucketInstanceId];!a.isConstant()&&h&&(c=r.latestFeatureIndex.loadFeature({featureIndex:t.featureIndex,bucketIndex:h.bucketIndex,sourceLayerIndex:h.sourceLayerIndex,layoutVertexArrayOffset:0}));const d=a.evaluate(c,{}),u=t.textBoxStartIndex<t.textBoxEndIndex,_=t.verticalTextBoxStartIndex<t.verticalTextBoxEndIndex,p=t.iconBoxStartIndex<t.iconBoxEndIndex,f=t.verticalIconBoxStartIndex<t.verticalIconBoxEndIndex;let g=new m(0,0),v=!0;if(u||_){if(n.get("text-variable-anchor")){const e=this.variableOffsets[t.crossTileID];e?(g=dh(e.anchor,e.width,e.height,e.textOffset,e.textScale),"map"===n.get("text-rotation-alignment")&&g._rotate("map"===n.get("text-pitch-alignment")?this.transform.angle:-this.transform.angle)):v=!1}e.layers[0].dynamicFilter()&&(v=!i.clipped),u&&gh(e.textCollisionBox.collisionVertexArray,i.text.placed,!v||s,d,l,g.x,g.y),_&&gh(e.textCollisionBox.collisionVertexArray,i.text.placed,!v||o,d,l,g.x,g.y)}const y=v&&!o&&f,x=t.hasIconTextFit?g.x:0,b=t.hasIconTextFit?g.y:0;p&&gh(e.iconCollisionBox.collisionVertexArray,i.icon.placed,y,d,l,x,b),f&&gh(e.iconCollisionBox.collisionVertexArray,i.icon.placed,!y,d,l,x,b)}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 e-this.lastPlacementChangeTime<this.fadeDuration}stillRecent(e,t){const i=this.zoomAtLastRecencyCheck===t?1-this.zoomAdjustment(t):1;return this.zoomAtLastRecencyCheck=t,this.commitTime+this.fadeDuration*i>e}isStale(){return this.stale}setStale(){this.stale=!0}}function mh(e,t,i){const s=e.opacityVertexArray;let o=!1;for(let e=0;e<t/4;e++)s.uint32[s.length]!==i&&(o=!0),s.emplaceBack(i);return o}function gh(e,t,i,s,o,r,n){e.emplaceBack(t?1:0,i?1:0,r||0,n||0,s,o?1:0),e.emplaceBack(t?1:0,i?1:0,r||0,n||0,s,o?1:0),e.emplaceBack(t?1:0,i?1:0,r||0,n||0,s,o?1:0),e.emplaceBack(t?1:0,i?1:0,r||0,n||0,s,o?1:0)}const vh=Math.pow(2,25),yh=Math.pow(2,24),xh=Math.pow(2,17),bh=Math.pow(2,16),wh=Math.pow(2,9),Th=Math.pow(2,8),Eh=Math.pow(2,1);function Ih(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*vh+t*yh+i*xh+t*bh+i*wh+t*Th+i*Eh+t}const Sh=0;class Dh{constructor(e){this._sortAcrossTiles="viewport-y"!==e.layout.get("symbol-z-order")&&void 0!==e.layout.get("symbol-sort-key").constantOr(1),this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs=new Set,this._bucketParts=[]}continuePlacement(e,t,i,s,o,r){const n=this._bucketParts;for(;this._currentTileIndex<e.length;)if(t.getBucketParts(n,s,e[this._currentTileIndex],this._sortAcrossTiles,r),this._currentTileIndex++,o())return!0;for(this._sortAcrossTiles&&(this._sortAcrossTiles=!1,n.sort((e,t)=>e.sortKey-t.sortKey));this._currentPartIndex<n.length;)if(t.placeLayerBucketPart(n[this._currentPartIndex],this._seenCrossTileIDs,i,r),this._currentPartIndex++,o())return!0;return!1}}class Rh{constructor(){this._retiredCI=null}startNewPlacement(e,t,i,s,o,r,n,a){return this.placement=new fh(e,s,o,r,n,a,this._retiredCI),this._retiredCI=null,this._currentPlacementIndex=t.length-1,this._forceFullPlacement=!1,this._showCollisionBoxes=i,this._fadeDuration=s,this._done=!1,this._inProgressLayer=null,this}requestFullPlacement(){this._forceFullPlacement=!0}isFullPlacementRequested(){return this._forceFullPlacement}setStale(){this.placement&&(this.placement.stale=!0)}isStale(){return!!this.placement&&this.placement.stale}isDone(){return this._done}continuePlacement(e,t,i,s,o){const r=T.now(),n=()=>!this.isFullPlacementRequested()&&0!==this._fadeDuration&&T.now()-r>2;for(;this._currentPlacementIndex>=0;){const r=t[e[this._currentPlacementIndex]],a=this.placement.collisionIndex.transform.zoom;if("symbol"===r.type&&"none"!==r.visibility&&(!r.minzoom||r.minzoom<=a)&&(!r.maxzoom||r.maxzoom>a)){const e=r,t=e.layout.get("symbol-z-elevate"),a=void 0!==e.layout.get("symbol-sort-key").constantOr(1),l=e.layout.get("symbol-z-order"),c="viewport-y"===l||"auto"===l&&!("viewport-y"!==l&&a),h=e.layout.get("text-allow-overlap")||e.layout.get("icon-allow-overlap")||e.layout.get("text-ignore-placement")||e.layout.get("icon-ignore-placement"),d=c&&h,u=this._inProgressLayer=this._inProgressLayer||new Dh(e),_=C(r.source,r.scope);if(u.continuePlacement(t||d?s[_]:i[_],this.placement,this._showCollisionBoxes,r,n,o))return;delete this._inProgressLayer}this._currentPlacementIndex--}this._forceFullPlacement=!1,this._done=!0}commit(e){return this._retiredCI=this.placement.prevPlacement?this.placement.prevPlacement.collisionIndex:null,this.placement.commit(e),this.placement}}const Ch=512/ae/2;class Ah{constructor(e,t,i){this.tileID=e,this.bucketInstanceId=i,this.index=new Lt(t.length,16,Int32Array),this.keys=[],this.crossTileIDs=[];const s=e.canonical.x*ae,o=e.canonical.y*ae;for(let e=0;e<t.length;e++){const{key:i,crossTileID:r,tileAnchorX:n,tileAnchorY:a}=t.get(e),l=Math.floor((s+n)*Ch),c=Math.floor((o+a)*Ch);this.index.add(l,c),this.keys.push(i),this.crossTileIDs.push(r)}this.index.finish()}findMatches(e,t,i){const s=this.tileID.canonical.z<t.canonical.z?1:Math.pow(2,this.tileID.canonical.z-t.canonical.z),o=Ch/Math.pow(2,t.canonical.z-this.tileID.canonical.z),r=t.canonical.x*ae,n=t.canonical.y*ae;for(let t=0;t<e.length;t++){const a=e.get(t);if(a.crossTileID)continue;const{key:l,tileAnchorX:c,tileAnchorY:h}=a,d=Math.floor((r+c)*o),u=Math.floor((n+h)*o),_=this.index.range(d-s,u-s,d+s,u+s).sort((e,t)=>e-t);for(const e of _){const t=this.crossTileIDs[e];if(this.keys[e]===l&&!i.has(t)){i.add(t),a.crossTileID=t;break}}}}}class Lh{constructor(){this.maxCrossTileID=0}generate(){return++this.maxCrossTileID}}class Ph{constructor(){this.indexes=[],this.usedCrossTileIDs=[],this.lng=0}handleWrapJump(e){const t=Math.round((e-this.lng)/360);if(0!==t)for(let e=0;e<this.indexes.length;e++){const i=this.indexes[e];if(!i)continue;const s=new Map;for(const e of i.values())e.tileID=e.tileID.unwrapTo(e.tileID.wrap+t),s.set(e.tileID.key,e);this.indexes[e]=s}this.lng=e}addBucket(e,t,i){const s=e.overscaledZ,o=this.indexes[s]&&this.indexes[s].get(e.key);if(o){if(o.bucketInstanceId===t.bucketInstanceId)return!1;this.removeBucketCrossTileIDs(s,o)}for(let e=0;e<t.symbolInstances.length;e++)t.symbolInstances.get(e).crossTileID=0;let r=this.usedCrossTileIDs[s];r||(r=this.usedCrossTileIDs[s]=new Set);for(let i=0;i<this.indexes.length;i++){const o=this.indexes[i];if(o)if(i>s)for(const i of o.values())i.tileID.isChildOf(e)&&i.findMatches(t.symbolInstances,e,r);else{const s=o.get(e.scaledTo(i).key);s&&s.findMatches(t.symbolInstances,e,r)}}for(let e=0;e<t.symbolInstances.length;e++){const s=t.symbolInstances.get(e);s.crossTileID||(s.crossTileID=i.generate(),r.add(s.crossTileID))}let n=this.indexes[s];return n||(n=this.indexes[s]=new Map),n.set(e.key,new Ah(e,t.symbolInstances,t.bucketInstanceId)),!0}removeBucketCrossTileIDs(e,t){for(const i of t.crossTileIDs)this.usedCrossTileIDs[e].delete(i)}removeStaleBuckets(e){let t=!1;for(let i=0;i<this.indexes.length;i++){const s=this.indexes[i];if(s)for(const[o,r]of s)e.has(r.bucketInstanceId)||(this.removeBucketCrossTileIDs(i,r),s.delete(o),t=!0)}return t}}class Mh{constructor(){this.layerIndexes=new Map,this.crossTileIDs=new Lh}addLayer(e,t,i,s){let o=this.layerIndexes.get(e.fqid);void 0===o&&(o=new Ph,this.layerIndexes.set(e.fqid,o));let r=!1;const n=new Set;"globe"!==s.name&&o.handleWrapJump(i);for(const i of t){const t=i.getBucket(e);t&&e.fqid===t.layerIds[0]&&(o.addBucket(i.tileID,t,this.crossTileIDs)&&(r=!0),n.add(t.bucketInstanceId))}return o.removeStaleBuckets(n)&&(r=!0),r}pruneUnusedLayers(e){const t=new Set(e);for(const e of this.layerIndexes.keys())t.has(e)||this.layerIndexes.delete(e)}}function Oh(e,t){const i=(t.right-t.left)/2,s=Math.abs(e.x-(t.left+i));if(s>=e.radius+i)return!1;const o=(t.bottom-t.top)/2,r=Math.abs(e.y-(t.top+o));if(r>=e.radius+o)return!1;if(s<i||r<o)return!0;const n=s-i,a=r-o;return n*n+a*a<e.radius*e.radius}function zh(e,t){return"box"===e.kind&&"box"===t.kind?function(e,t){return e.left<t.right&&t.left<e.right&&e.top<t.bottom&&t.top<e.bottom}(e,t):"circle"===e.kind&&"circle"===t.kind?function(e,t){const i=e.x-t.x,s=e.y-t.y,o=e.radius+t.radius;return i*i+s*s<o*o}(e,t):"circle"===e.kind?Oh(e,t):Oh(t,e)}class Fh{constructor(e,t,i,s){this._cellSize=s,this._padding=i,this._screenWidth=e,this._screenHeight=t,this._grid=new Jt(e+2*i,t+2*i,s),this._workingArea=this._computeWorkingArea(),this._geometries=[],this._geometryData=[]}clearAndResize(e,t){e===this._screenWidth&&t===this._screenHeight?this._grid.clear():(this._screenWidth=e,this._screenHeight=t,this._grid=new Jt(e+2*this._padding,t+2*this._padding,this._cellSize),this._workingArea=this._computeWorkingArea()),this._geometries.length=0,this._geometryData.length=0}_computeWorkingArea(){return{kind:"box",left:-this._padding,top:-this._padding,right:this._grid.xCellCount*this._cellSize-this._padding,bottom:this._grid.yCellCount*this._cellSize-this._padding}}intersects(e,t,i,s){let o="outside-of-grid";for(const r of e){const e=this._elementIntersects(r,t,i,s);if("intersects"===e)return"intersects";"does-not-intersect"===e&&(o="does-not-intersect")}return o}_elementIntersects(e,t,i,s){if(!zh(e,this._workingArea))return"outside-of-grid";const o=this._padding,r=function(e,t){return 0===t?e:"box"===e.kind?{kind:"box",left:e.left-t,top:e.top-t,right:e.right+t,bottom:e.bottom+t}:{kind:"circle",x:e.x,y:e.y,radius:e.radius+t}}(e,t);let n;const a=e=>{if(!zh(this._geometries[e],r))return!1;const t=this._geometryData[e];return!(void 0!==t&&i(t)||(n=t,0))},l="box"===r.kind?this._grid.hitTest(r.left+o,r.top+o,r.right+o,r.bottom+o,a):this._grid.hitTestCircle(r.x+o,r.y+o,r.radius,a);return l&&void 0!==n&&s(n),l?"intersects":"does-not-intersect"}insert(e,t){const i=this._padding;let s=!1;for(const o of e){if(!zh(o,this._workingArea))continue;const e=this._geometries.length;this._geometries.push(o),this._geometryData.push(t),"box"===o.kind?this._grid.insert(e,o.left+i,o.top+i,o.right+i,o.bottom+i):this._grid.insertCircle(e,o.x+i,o.y+i,o.radius),s=!0}return s}}const kh={PLACED:0,COLLIDED:1,OTHER_VARIANT_PLACED:2,DEPENDENCY_NOT_PLACED:3,OUT_OF_BOUNDS:4};function Bh(){}function Nh(e,t){const i=e.get(t.symbolId);return void 0!==i&&i.has(t.variantIdx)}function Uh(e,t){let i=e.get(t.symbolId);i||(i=new Set,e.set(t.symbolId,i)),i.add(t.variantIdx)}class Vh{constructor(){this._runStarted=!1,this._grid=null,this._timestamp=0,this._symbols=[],this._onlyIfPlacedReferencedIds=new Map,this._placedVariantIds=new Map,this._placedSymbolIds=new Map,this._processingSource=null,this._variantProcessingStarted=!1,this._collectDebugData=!1,this._debugSymbols=[],this._lastBlockedBy=void 0}isCollectingDebugData(){return this._collectDebugData}startPlacement(e,t,i,s=!1){if(this._runStarted)throw new Error("Attempt to start a placement run before finishing the previous one");this._runStarted=!0,this._grid?this._grid.clearAndResize(t,i):this._grid=new Fh(t,i,100,32),this._timestamp=e,this._symbols=[],this._onlyIfPlacedReferencedIds.clear(),this._placedVariantIds.clear(),this._placedSymbolIds.clear(),this._collectDebugData=s,this._debugSymbols=[]}debugSymbols(){return this._debugSymbols}timestamp(){return this._timestamp}_addPlacedSymbol(e){this._placedSymbolIds.set(e.symbolId,e.variantIdx)}startSymbolSourceProcessing(e){if(!this._runStarted)throw new Error("Attempt to start symbol source processing outside of a placement run");if(this._processingSource)throw new Error("Attempt to start a placement symbol source processing before finishing the previous one");this._processingSource=e}startSymbolVariantProcessing(e,t,i,s,o){const r=this._processingSource;if(!r)throw new Error("Attempt to start a symbol variant processing outside of symbol source processing");if(this._variantProcessingStarted)throw new Error("Attempt to begin a symbol variant processing before finishing the previous one");this._symbols.push({priority:t,source:r,variantId:e,parts:[],placementRules:i,tileID:s,featureId:o}),i.onlyIfPlaced&&Uh(this._onlyIfPlacedReferencedIds,i.onlyIfPlaced),this._variantProcessingStarted=!0}addSymbolVariantPart(e,t){if(!this._variantProcessingStarted)throw new Error("Attempt to add a symbol variant part outside of symbol variant processing");if(0===e.length)throw new Error("Attempt to add a symbol variant part without geometry");this._symbols.at(-1).parts.push({geometry:e,rules:t})}finishVariantProcessing(e){if(!this._variantProcessingStarted)throw new Error("Attempt to finish a symbol variant processing that was not started");this._variantProcessingStarted=!1;const t=this._symbols.at(-1);0===t.parts.length&&(t.priority.symbolVariantVisibility===xi.VARIANT_VISIBLE&&t.source.hideSymbolVariant(t.variantId,this._timestamp,e),this._symbols.pop())}finishSourceProcessing(){this._processingSource=null}_placeSymbolVariant(e,t){const i=this._grid;this._lastBlockedBy=void 0;const s=this._placedSymbolIds.get(e.variantId.symbolId);if(void 0!==s)return this._collectDebugData&&(this._lastBlockedBy={symbolId:e.variantId.symbolId,variantIdx:s}),kh.OTHER_VARIANT_PLACED;const o=e.placementRules.onlyIfPlaced;if(o&&!Nh(this._placedVariantIds,o))return kh.DEPENDENCY_NOT_PLACED;const r=this._collectDebugData?e=>{this._lastBlockedBy=e}:Bh;let n=!1,a=!1;for(const s of e.parts){const e=s.rules.collisionRules;if(!e)continue;n=!0;const o=e.symbolVariantToIgnoreCollisionWith,l=i.intersects(s.geometry,t,e=>{return void 0!==o&&(t=e).symbolId===(i=o).symbolId&&t.variantIdx===i.variantIdx;var t,i},r);if("intersects"===l)return kh.COLLIDED;"does-not-intersect"===l&&(a=!0)}if(n&&!a)return kh.OUT_OF_BOUNDS;let l=!1,c=!1;for(const t of e.parts)t.rules.insertIntoCollisionGrid&&(i.insert(t.geometry,e.variantId)?l=!0:c=!0);return c&&!l?kh.OUT_OF_BOUNDS:kh.PLACED}finishPlacementRun(e){if(!this._runStarted)throw new Error("Attempt to finish a placement run that was not started");this._runStarted=!1;const t=this._timestamp;this._symbols.sort((e,t)=>function(e,t){return e.placementSubgroupOrder-t.placementSubgroupOrder||e.symbolPlacementPriority-t.symbolPlacementPriority||e.symbolVariantVisibility-t.symbolVariantVisibility||e.symbolPlacementType-t.symbolPlacementType||e.styleLayerOrder-t.styleLayerOrder||e.symbolDisplayOrder-t.symbolDisplayOrder}(t.priority,e.priority));for(const i of this._symbols){const s=i.priority.symbolVariantVisibility===xi.VARIANT_VISIBLE,o=s?0:1,r=this._placeSymbolVariant(i,o),n=r===kh.PLACED;if(n&&(this._addPlacedSymbol(i.variantId),Nh(this._onlyIfPlacedReferencedIds,i.variantId)&&Uh(this._placedVariantIds,i.variantId)),s!==n&&(n?i.source.showSymbolVariant(i.variantId,t,e):i.source.hideSymbolVariant(i.variantId,t,e)),this._collectDebugData){const e=n?0:o,t=[];for(const e of i.parts)t.push(...e.geometry);this._debugSymbols.push({geometry:t,collisionPadding:e,variantId:i.variantId,tileID:i.tileID,featureId:i.featureId,placementRules:i.placementRules,partPlacementRules:i.parts.map(e=>e.rules),status:r,blockedBy:this._lastBlockedBy})}}}}function jh(e){const t=e.properties.get("direction"),i=Ii(t.x,t.y,t.z);i[2]=Ee(i[2],0,75);const s=wi([i[0],i[1],i[2]]);return bi(s.x,s.y,s.z)}function Gh(e,t,i){const s="none"===t.properties.get("color-use-theme"),o=t.properties.get("color"),r=t.properties.get("intensity"),n=t.properties.get("direction"),a=[n.x,n.y,n.z],l="none"===i.properties.get("color-use-theme"),c=i.properties.get("color"),h=i.properties.get("intensity"),d=Math.max(Kt([0,0,1],a),0),u=[0,0,0];Ti(u,c.toPremultipliedRenderColor(l?null:e.getLut(t.scope)).toArray01Linear().slice(0,3),h);const _=[0,0,0];return Ti(_,o.toPremultipliedRenderColor(s?null:e.getLut(i.scope)).toArray01Linear().slice(0,3),d*r),Ei([u[0]>0?u[0]/(u[0]+_[0]):0,u[1]>0?u[1]/(u[1]+_[1]):0,u[2]>0?u[2]/(u[2]+_[2]):0])}function qh(e,t){const i=!e.includes("://");try{return new URL(e,i&&t?"http://example.com":void 0),!0}catch(e){return!1}}function Zh(e){const t=e.value;return t?Si(t)?qh(t,!0)?[]:[new Da(e.key,t,`invalid url "${t}"`)]:[new Da(e.key,t,`string expected, "${Di(t)}" found`)]:[]}class Wh extends A{constructor(e){super(),this.requestManager=e,this.models=Object.create(null),this.models[""]=Object.create(null),this.modelUris=Object.create(null),this.modelUris[""]=Object.create(null),this.modelByURL=Object.create(null),this.numModelsLoading=Object.create(null)}async loadModel(e,t){try{if(await Cl(),!ue.loadModel)return null;const i=await ue.loadModel(e=>this.requestManager.transformRequest(e,x.Model),e,t);return this.modelByURL[t]?i:null}catch(i){if(404===i.status)return null;this.fire(new P(new Error(`Could not load model ${e} from ${t}`,{cause:i})))}}load(e,t,i={forceReload:!1}){this.models[t]||(this.models[t]=Object.create(null));const s=Object.keys(e),o=[],r=[];for(const n of s){const s=e[n];this.hasURLBeenRequested(s)&&!i.forceReload||(this.modelByURL[s]={modelId:n,scope:t},o.push(this.loadModel(n,s)),r.push(n)),this.models[t][n]||(this.models[t][n]={model:null,numReferences:1})}0!==r.length&&(this.numModelsLoading[t]=(this.numModelsLoading[t]||0)+r.length,Promise.allSettled(o).then(e=>{for(let i=0;i<e.length;i++){const{status:s}=e[i];if("rejected"===s)continue;const{value:o}=e[i];this.models[t][r[i]]||(this.models[t][r[i]]={model:null,numReferences:1}),this.models[t][r[i]].model=o}this.numModelsLoading[t]-=r.length,this.fire(new M("data",{dataType:"style"}))}).catch(e=>{this.fire(new P(new Error(`Could not load models: ${e.message}`)))}))}isLoaded(){for(const e in this.numModelsLoading)if(this.numModelsLoading[e]>0)return!1;return!0}hasModel(e,t,i={exactIdMatch:!1}){return!!(i.exactIdMatch?this.getModel(e,t):this.getModelByURL(this.modelUris[t][e]))}getModel(e,t){return this.models[t]||(this.models[t]=Object.create(null)),this.models[t][e]?this.models[t][e].model:void 0}getModelByURL(e){if(!e)return null;const t=this.modelByURL[e];return t?this.models[t.scope][t.modelId].model:null}hasModelBeenAdded(e,t){return this.models[t]&&void 0!==this.models[t][e]}getModelURIs(e){return this.modelUris[e]||Object.create(null)}addModel(e,t,i){this.models[i]||(this.models[i]=Object.create(null)),this.modelUris[i]||(this.modelUris[i]=Object.create(null));const s=this.requestManager.normalizeModelURL(t);if((this.hasModel(e,i,{exactIdMatch:!0})||this.hasModelBeenAdded(e,i))&&this.modelUris[i][e]===s)this.models[i][e].numReferences++;else if(this.hasURLBeenRequested(s)){const{scope:e,modelId:t}=this.modelByURL[s];this.models[e][t].numReferences++}else this.modelUris[i][e]=s,this.load({[e]:this.modelUris[i][e]},i)}addModelURLs(e,t){this.models[t]||(this.models[t]=Object.create(null)),this.modelUris[t]||(this.modelUris[t]=Object.create(null));const i=this.modelUris[t];for(const t of Object.keys(e))i[t]=this.requestManager.normalizeModelURL(e[t])}reloadModels(e){this.load(this.modelUris[e],e,{forceReload:!0})}addModelsFromBucket(e,t){this.models[t]||(this.models[t]=Object.create(null)),this.modelUris[t]||(this.modelUris[t]=Object.create(null));const i=Object.create(null);for(const s of e)this.hasModel(s,t,{exactIdMatch:!0})||this.hasURLBeenRequested(s)?this.models[t][s].numReferences++:this.modelUris[t][s]&&!this.hasURLBeenRequested(s)?i[s]=this.modelUris[t][s]:!this.hasURLBeenRequested(s)&&qh(s,!1)&&(this.modelUris[t][s]=this.requestManager.normalizeModelURL(s),i[s]=this.modelUris[t][s]);this.load(i,t)}hasURLBeenRequested(e){return void 0!==this.modelByURL[e]}removeModel(e,t,i=!1,s=!1){if(this.models[t]&&this.models[t][e]&&(this.models[t][e].numReferences--,0===this.models[t][e].numReferences||s)){const s=this.modelUris[t][e];i||delete this.modelUris[t][e],delete this.modelByURL[s];const o=this.models[t][e].model;if(!o)return;delete this.models[t][e],o.destroy()}}destroy(){for(const e of Object.keys(this.models))for(const t of Object.keys(this.models[e])){const i=this.models[e][t].model;delete this.models[e][t],i&&i.destroy()}this.models=Object.create(null),this.models[""]=Object.create(null),this.modelUris=Object.create(null),this.modelUris[""]=Object.create(null),this.modelByURL=Object.create(null),this.numModelsLoading=Object.create(null)}listModels(e){return this.models[e]||(this.models[e]=Object.create(null)),Object.keys(this.models[e])}upload(e,t){this.models[t]||(this.models[t]=Object.create(null));for(const i in this.models[t])this.models[t][i].model&&this.models[t][i].model.upload(e.context)}}function Hh(e,t,i=0){const s=Math.pow(2,t.tileID.overscaledZ),o=t.tileSize*Math.pow(2,e.transform.tileZoom)/s,r=o*(t.tileID.canonical.x+t.tileID.wrap*s),n=o*t.tileID.canonical.y;return{u_image:0,u_texsize:t.imageAtlasTexture?t.imageAtlasTexture.size:[0,0],u_tile_units_to_pixels:1/Te(t,1,e.transform.tileZoom),u_pixel_coord_upper:[r>>16,n>>16],u_pixel_coord_lower:[65535&r,65535&n],u_pattern_transition:i}}const $h={terrain:0,flat:1},Xh=e=>({u_matrix:new Pi(e),u_edge_radius:new Ri(e),u_width_scale:new Ri(e),u_vertical_scale:new Ri(e),u_height_type:new Ai(e),u_base_type:new Ai(e)}),Yh=Bt(),Kh=[0,0,0],Jh=(e,t,i,s,o,r,n,a,l,c,h,d,u,_,p,f,m,g,v=[0,0,1],y=!1)=>{let x=Kh,b=0,w=Kh;if(!y){const e=t.style.light,i=e.properties.get("position");if(x=[i.x,i.y,i.z],"viewport"===e.properties.get("anchor")){const e=Mi();Oi(e,-t.transform.angle),Qe(x,x,e)}const s=e.properties.get("color").toPremultipliedRenderColor(null);b=e.properties.get("intensity"),w=[s.r,s.g,s.b]}const T=t.transform,E={u_matrix:e,u_lightpos:x,u_lightintensity:b,u_lightcolor:w,u_vertical_gradient:+i,u_opacity:s,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:Yh,u_merc_center:[0,0],u_up_dir:[0,0,0],u_height_lift:0,u_height_type:$h[c],u_base_type:$h[h],u_ao:o,u_edge_radius:r,u_width_scale:n,u_flood_light_color:p,u_vertical_scale:f,u_flood_light_intensity:m,u_ground_shadow_factor:g,u_front_cutoff_params:v};return"globe"===T.projection.name&&(E.u_tile_id=[a.canonical.x,a.canonical.y,1<<a.canonical.z],E.u_zoom_transition=d,E.u_inv_rot_matrix=_,E.u_merc_center=u,E.u_up_dir=T.projection.upVector(new $e(0,0,0),u[0]*ae,u[1]*ae),E.u_height_lift=l),E},Qh=(e,t,i,s,o,r)=>({u_matrix:e,u_edge_radius:t,u_width_scale:i,u_vertical_scale:s,u_height_type:$h[o],u_base_type:$h[r]}),ed=(e,t,i,s,o,r,n,a,l,c,h,d,u,_,p,f,m,g,v=!1)=>{const y=Jh(e,t,i,s,o,r,n,a,c,h,d,u,_,p,f,m,1,[0,0,0],[0,0,1],v),x={u_height_factor:-Math.pow(2,a.overscaledZ)/l.tileSize/8};return Object.assign(y,Hh(t,l,g),x)},td=(e,t,i)=>({u_matrix:e,u_emissive_strength:t,u_ground_shadow_factor:i,u_opacity_multiplier:1}),id=(e,t,i,s,o,r=0)=>Object.assign(td(e,t,o),Hh(i,s,r)),sd=(e,t,i,s)=>({u_matrix:e,u_world:i,u_emissive_strength:t,u_ground_shadow_factor:s,u_opacity_multiplier:1}),od=(e,t,i,s,o,r,n=0)=>Object.assign(id(e,t,i,s,r,n),{u_world:o}),rd=(e,t,i)=>({u_image:e,u_texel_size:t,u_first_pass:i?1:0}),nd=(e,t,i,s,o,r,n,a)=>{const l=ae/r.tileSize;return{u_matrix:e,u_inv_rot_matrix:t,u_camera_to_center_distance:i.getCameraToCenterDistance(a),u_extrude_scale:[i.pixelsToGLUnits[0]/l,i.pixelsToGLUnits[1]/l],u_zoom_transition:s,u_tile_id:n,u_merc_center:o}},ad=(e,t,i,s)=>({u_matrix:e,u_inv_matrix:t,u_camera_to_center_distance:i.getCameraToCenterDistance(s),u_viewport_size:[i.width,i.height]}),ld=(e,t,i,s,o,r)=>({u_viewport_size:e,u_color:t,u_outline_width:i,u_opacity:s,u_stroke_opacity:o,u_collision_padding_opacity:r}),cd=(e,t,i=1)=>({u_matrix:e,u_color:t,u_overlay:0,u_overlay_scale:i}),hd=e=>({u_matrix:e}),dd=Bt(),ud=(e,t,i,s,o,r,n)=>{const a=e.transform,l="globe"===a.projection.name,c=l?Fi(a.zoom,t.canonical)*a._pixelsPerMercatorPixel:Te(i,1,r),h={u_matrix:t.projMatrix,u_extrude_scale:c,u_intensity:n,u_inv_rot_matrix:dd,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0]};if(l){h.u_inv_rot_matrix=s,h.u_merc_center=o,h.u_tile_id=[t.canonical.x,t.canonical.y,1<<t.canonical.z],h.u_zoom_transition=K(a.zoom);const e=o[0]*ae,i=o[1]*ae;h.u_up_dir=a.projection.upVector(new $e(0,0,0),e,i)}return h};function _d(e,t){const i=Math.pow(2,t.canonical.z),s=t.canonical.y;return[new we(0,s/i).toLngLat().lat,new we(0,(s+1)/i).toLngLat().lat]}function pd(e,[t,i,s,o],[r,n]){if(r===n)return[0,0,0,0];const a=255*(e-1)/(e*(n-r));return[t*a,i*a,s*a,o*a]}function fd(e,t,[i,s]){return i===s?0:.5/e+(t-i)*(e-1)/(e*(s-i))}function md(e){const t=e.terrain?e.terrain.exaggeration():1;return(e.transform.pitch<15?J(.07,.7,Ee((14-e.transform.zoom)/5,0,1)):.07)*t}const gd=(e,t,i,s,o,r,n,a,l,c,h,d,u,_,p,f,m,g,v,y,x,b)=>({u_matrix:t,u_normalize_matrix:i,u_globe_matrix:s,u_merc_matrix:o,u_grid_matrix:r,u_tl_parent:n,u_scale_parent:h,u_fade_t:d.mix,u_opacity:d.opacity*u.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:u.paint.get("raster-brightness-min"),u_brightness_high:u.paint.get("raster-brightness-max"),u_saturation_factor:ji(u.paint.get("raster-saturation")),u_contrast_factor:Vi(u.paint.get("raster-contrast")),u_spin_weights:vd(u.paint.get("raster-hue-rotate")),u_perspective_transform:_,u_raster_elevation:p,u_zoom_transition:a,u_merc_center:l,u_cutoff_params:c,u_colorization_mix:pd(Ui,m,v),u_colorization_offset:fd(Ui,g,v),u_color_ramp:f,u_color_ramp_size:Ui,u_texture_offset:[x/(y+2*x),y/(y+2*x)],u_texture_res:[y+2*x,y+2*x],u_emissive_strength:b,u_zbias_factor:md(e)});function vd(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 yd={BaseColor:5,MetallicRoughness:6,Normal:7,Occlusion:8,Emission:9,LUT:10,ShadowMap0:11},xd=Bt(),bd=(e,t,i,s,o,r,n,a,l,c,h,d,u,_,p,f,m,g,v,y,x,b,w,E,I)=>{const S=o.transform,D={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:S.getCameraToCenterDistance(y),u_rotate_symbol:+i,u_aspect_ratio:S.width/S.height,u_fade_change:o.options.fadeDuration?o.symbolFadeChange:1,u_now:0|Math.round(o.now),u_fade_duration:o.options.fadeDuration,u_matrix:r,u_label_plane_matrix:n,u_coord_matrix:a,u_is_text:+c,u_is_sdf:+h,u_elevation_from_sea:l?1:0,u_pitch_with_map:+s,u_texsize:d,u_texsize_icon:u,u_texture:0,u_texture_icon:1,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:xd,u_merc_center:[0,0],u_camera_forward:[0,0,0],u_ecef_origin:[0,0,0],u_tile_matrix:xd,u_up_vector:[0,-1,0],u_color_adj_mat:w,u_icon_transition:E||0,u_gamma_scale:h?s?o.transform.getCameraToCenterDistance(y)*Math.cos(o.terrain?0:o.transform._pitch):1:0,u_device_pixel_ratio:T.devicePixelRatio,u_is_halo:1,u_scale_factor:I||1,u_ground_shadow_factor:x,u_inv_matrix:Tt(Bt(),n),u_normal_scale:b,u_lutTexture:yd.LUT,u_spp_fill_np_color:[0,0,0,1],u_spp_halo_np_color:[0,0,0,0],u_spp_opacity:1,u_spp_halo_width:0,u_spp_halo_blur:0,u_spp_emissive_strength:0,u_spp_occlusion_opacity:1,u_spp_z_offset:0,u_spp_translate_rotation:[1,0],u_spp_zoom_fraction:0,u_opacity_multiplier:1};return"globe"===y.name&&(D.u_tile_id=[p.canonical.x,p.canonical.y,1<<p.canonical.z],D.u_zoom_transition=f,D.u_inv_rot_matrix=g,D.u_merc_center=m,D.u_camera_forward=S._camera.forward(),D.u_ecef_origin=Gi(S.globeMatrix,p.toUnwrapped()),D.u_tile_matrix=S.globeMatrix,D.u_up_vector=v),D},wd=(e,t,i,s)=>({u_matrix:e,u_emissive_strength:t,u_opacity:i,u_color:s}),Td=(e,t,i,s,o,r,n,a,l)=>Object.assign(function(e,t,i,s,o,r){const{width:n,height:a}=s.imageManager.getPixelSize(t),l=Math.pow(2,r.tileID.overscaledZ),c=r.tileSize*Math.pow(2,s.transform.tileZoom)/l,h=c*(r.tileID.canonical.x+r.tileID.wrap*l),d=c*r.tileID.canonical.y;return{u_image:0,u_pattern_tl:i.tl,u_pattern_br:i.br,u_texsize:[n,a],u_pattern_size:i.displaySize,u_pattern_units_to_pixels:o?[s.transform.width,-1*s.transform.height]:[1/Te(r,1,s.transform.tileZoom),1/Te(r,1,s.transform.tileZoom)],u_pixel_coord_upper:[h>>16,d>>16],u_pixel_coord_lower:[65535&h,65535&d]}}(0,r,n,s,a,l),{u_matrix:e,u_emissive_strength:t,u_opacity:i}),Ed={fillExtrusion:e=>({u_matrix:new Pi(e),u_lightpos:new Li(e),u_lightintensity:new Ri(e),u_lightcolor:new Li(e),u_vertical_gradient:new Ri(e),u_opacity:new Ri(e),u_edge_radius:new Ri(e),u_width_scale:new Ri(e),u_ao:new Ci(e),u_height_type:new Ai(e),u_base_type:new Ai(e),u_tile_id:new Li(e),u_zoom_transition:new Ri(e),u_inv_rot_matrix:new Pi(e),u_merc_center:new Ci(e),u_up_dir:new Li(e),u_height_lift:new Ri(e),u_flood_light_color:new Li(e),u_vertical_scale:new Ri(e),u_flood_light_intensity:new Ri(e),u_ground_shadow_factor:new Li(e),u_front_cutoff_params:new Li(e)}),fillExtrusionPattern:e=>({u_matrix:new Pi(e),u_lightpos:new Li(e),u_lightintensity:new Ri(e),u_lightcolor:new Li(e),u_vertical_gradient:new Ri(e),u_height_factor:new Ri(e),u_edge_radius:new Ri(e),u_width_scale:new Ri(e),u_ao:new Ci(e),u_height_type:new Ai(e),u_base_type:new Ai(e),u_tile_id:new Li(e),u_zoom_transition:new Ri(e),u_inv_rot_matrix:new Pi(e),u_merc_center:new Ci(e),u_up_dir:new Li(e),u_height_lift:new Ri(e),u_image:new Ai(e),u_texsize:new Ci(e),u_pixel_coord_upper:new Ci(e),u_pixel_coord_lower:new Ci(e),u_tile_units_to_pixels:new Ri(e),u_opacity:new Ri(e),u_pattern_transition:new Ri(e)}),fill:e=>({u_matrix:new Pi(e),u_emissive_strength:new Ri(e),u_ground_shadow_factor:new Li(e),u_opacity_multiplier:new Ri(e)}),fillPattern:e=>({u_matrix:new Pi(e),u_emissive_strength:new Ri(e),u_image:new Ai(e),u_texsize:new Ci(e),u_pixel_coord_upper:new Ci(e),u_pixel_coord_lower:new Ci(e),u_tile_units_to_pixels:new Ri(e),u_ground_shadow_factor:new Li(e),u_pattern_transition:new Ri(e),u_opacity_multiplier:new Ri(e)}),fillOutline:e=>({u_matrix:new Pi(e),u_emissive_strength:new Ri(e),u_world:new Ci(e),u_ground_shadow_factor:new Li(e),u_opacity_multiplier:new Ri(e)}),fillOutlinePattern:e=>({u_matrix:new Pi(e),u_emissive_strength:new Ri(e),u_world:new Ci(e),u_image:new Ai(e),u_texsize:new Ci(e),u_pixel_coord_upper:new Ci(e),u_pixel_coord_lower:new Ci(e),u_tile_units_to_pixels:new Ri(e),u_ground_shadow_factor:new Li(e),u_pattern_transition:new Ri(e),u_opacity_multiplier:new Ri(e)}),lineBlendComposite:e=>({u_image:new Ai(e),u_opacity:new Ri(e),u_blend_mode:new Ai(e),u_max_density:new Ri(e)}),lineBlendReduce:e=>({u_image:new Ai(e),u_texel_size:new Ci(e),u_first_pass:new Ai(e)}),circle:Wi,collisionBox:e=>({u_matrix:new Pi(e),u_inv_rot_matrix:new Pi(e),u_camera_to_center_distance:new Ri(e),u_extrude_scale:new Ci(e),u_zoom_transition:new Ri(e),u_merc_center:new Ci(e),u_tile_id:new Li(e)}),collisionCircle:e=>({u_matrix:new Pi(e),u_inv_matrix:new Pi(e),u_camera_to_center_distance:new Ri(e),u_viewport_size:new Ci(e)}),placementDebug:e=>({u_viewport_size:new Ci(e),u_color:new zi(e),u_outline_width:new Ri(e),u_opacity:new Ri(e),u_stroke_opacity:new Ri(e),u_collision_padding_opacity:new Ri(e)}),debug:e=>({u_color:new zi(e),u_matrix:new Pi(e),u_overlay:new Ai(e),u_overlay_scale:new Ri(e)}),clippingMask:e=>({u_matrix:new Pi(e)}),heatmap:e=>({u_extrude_scale:new Ri(e),u_intensity:new Ri(e),u_matrix:new Pi(e),u_inv_rot_matrix:new Pi(e),u_merc_center:new Ci(e),u_tile_id:new Li(e),u_zoom_transition:new Ri(e),u_up_dir:new Li(e)}),heatmapTexture:e=>({u_image:new Ai(e),u_color_ramp:new Ai(e),u_opacity:new Ri(e)}),hillshade:e=>({u_matrix:new Pi(e),u_image:new Ai(e),u_latrange:new Ci(e),u_light:new Ci(e),u_shadow:new zi(e),u_highlight:new zi(e),u_emissive_strength:new Ri(e),u_accent:new zi(e)}),hillshadePrepare:e=>({u_matrix:new Pi(e),u_image:new Ai(e),u_dimension:new Ci(e),u_zoom:new Ri(e)}),line:Zi,linePattern:qi,raster:e=>({u_matrix:new Pi(e),u_normalize_matrix:new Pi(e),u_globe_matrix:new Pi(e),u_merc_matrix:new Pi(e),u_grid_matrix:new Ni(e),u_tl_parent:new Ci(e),u_scale_parent:new Ri(e),u_fade_t:new Ri(e),u_opacity:new Ri(e),u_image0:new Ai(e),u_image1:new Ai(e),u_brightness_low:new Ri(e),u_brightness_high:new Ri(e),u_saturation_factor:new Ri(e),u_contrast_factor:new Ri(e),u_spin_weights:new Li(e),u_perspective_transform:new Ci(e),u_raster_elevation:new Ri(e),u_zoom_transition:new Ri(e),u_merc_center:new Ci(e),u_cutoff_params:new Bi(e),u_colorization_mix:new Bi(e),u_colorization_offset:new Ri(e),u_color_ramp:new Ai(e),u_color_ramp_size:new Ri(e),u_texture_offset:new Ci(e),u_texture_res:new Ci(e),u_emissive_strength:new Ri(e),u_zbias_factor:new Ri(e)}),symbol:e=>({u_is_size_zoom_constant:new Ai(e),u_is_size_feature_constant:new Ai(e),u_size_t:new Ri(e),u_size:new Ri(e),u_camera_to_center_distance:new Ri(e),u_rotate_symbol:new Ai(e),u_aspect_ratio:new Ri(e),u_fade_change:new Ri(e),u_now:new Ai(e),u_fade_duration:new Ri(e),u_matrix:new Pi(e),u_label_plane_matrix:new Pi(e),u_coord_matrix:new Pi(e),u_is_text:new Ai(e),u_is_sdf:new Ai(e),u_elevation_from_sea:new Ai(e),u_pitch_with_map:new Ai(e),u_texsize:new Ci(e),u_texsize_icon:new Ci(e),u_texture:new Ai(e),u_texture_icon:new Ai(e),u_gamma_scale:new Ri(e),u_device_pixel_ratio:new Ri(e),u_tile_id:new Li(e),u_zoom_transition:new Ri(e),u_inv_rot_matrix:new Pi(e),u_merc_center:new Ci(e),u_camera_forward:new Li(e),u_tile_matrix:new Pi(e),u_up_vector:new Li(e),u_ecef_origin:new Li(e),u_is_halo:new Ai(e),u_icon_transition:new Ri(e),u_color_adj_mat:new Pi(e),u_scale_factor:new Ri(e),u_ground_shadow_factor:new Li(e),u_inv_matrix:new Pi(e),u_normal_scale:new Ri(e),u_lutTexture:new Ai(e),u_spp_fill_np_color:new Bi(e),u_spp_halo_np_color:new Bi(e),u_spp_opacity:new Ri(e),u_spp_halo_width:new Ri(e),u_spp_halo_blur:new Ri(e),u_spp_emissive_strength:new Ri(e),u_spp_occlusion_opacity:new Ri(e),u_spp_z_offset:new Ri(e),u_spp_translate_rotation:new Ci(e),u_spp_zoom_fraction:new Ri(e),u_opacity_multiplier:new Ri(e)}),background:e=>({u_matrix:new Pi(e),u_emissive_strength:new Ri(e),u_opacity:new Ri(e),u_color:new zi(e)}),backgroundPattern:e=>({u_matrix:new Pi(e),u_emissive_strength:new Ri(e),u_opacity:new Ri(e),u_image:new Ai(e),u_pattern_tl:new Ci(e),u_pattern_br:new Ci(e),u_texsize:new Ci(e),u_pattern_size:new Ci(e),u_pixel_coord_upper:new Ci(e),u_pixel_coord_lower:new Ci(e),u_pattern_units_to_pixels:new Ci(e)}),skybox:e=>({u_matrix:new Pi(e),u_sun_direction:new Li(e),u_cubemap:new Ai(e),u_opacity:new Ri(e),u_temporal_offset:new Ri(e)}),skyboxGradient:e=>({u_matrix:new Pi(e),u_color_ramp:new Ai(e),u_center_direction:new Li(e),u_radius:new Ri(e),u_opacity:new Ri(e),u_temporal_offset:new Ri(e)}),skyboxCapture:e=>({u_matrix_3f:new Ni(e),u_sun_direction:new Li(e),u_sun_intensity:new Ri(e),u_color_tint_r:new Bi(e),u_color_tint_m:new Bi(e),u_luminance:new Ri(e)}),globeAtmosphere:e=>({u_frustum_tl:new Li(e),u_frustum_tr:new Li(e),u_frustum_br:new Li(e),u_frustum_bl:new Li(e),u_horizon:new Ri(e),u_transition:new Ri(e),u_fadeout_range:new Ri(e),u_atmosphere_fog_color:new Bi(e),u_high_color:new Bi(e),u_space_color:new Bi(e),u_temporal_offset:new Ri(e),u_horizon_angle:new Ri(e)}),stars:e=>({u_matrix:new Pi(e),u_up:new Li(e),u_right:new Li(e),u_intensity_multiplier:new Ri(e)}),occlusion:e=>({u_matrix:new Pi(e),u_anchorPos:new Li(e),u_screenSizePx:new Ci(e),u_occluderSizePx:new Ci(e),u_color:new Bi(e)})},Id=["RENDER_SHADOWS","NORMAL_OFFSET"],Sd=new Set(["symbol","circle"]),Dd=class e{constructor(){this._queue=[],this._needsBuild=!0,this._idleHandle=null}needsBuild(){return this._needsBuild}buildQueue(e,t,i){null!=this._idleHandle&&"undefined"!=typeof cancelIdleCallback&&cancelIdleCallback(this._idleHandle),this._idleHandle=null,this._queue=[],this._needsBuild=!1;const s=!!i.fog,o=i.hasTerrain(),r=!(!i.projection||"globe"!==i.projection.name),n=o||r,a=!(!i.directionalLight||!i.directionalLight.shadowsEnabled()),l=i.map&&i.map.painter,c=!l||!l.context.extParallelShaderCompile,h=!!l&&("mrt-fallback"===l.emissiveMode||"mrt-full-rgba"===l.emissiveMode),d=(e,t=[],i={})=>{this._queue.push({programId:e,params:{...i.params,defines:t,overrideFog:!!i.fog,overrideTerrain:!!i.terrain,overrideGlobe:!!i.globe,overrideRtt:!!i.rtt,precompiled:!0}})};for(const u of e){if("none"===u.visibility)continue;const e=u.getProgramIds();if(e)for(const _ of e){if(Sd.has(_))continue;const e=u.getDefaultProgramParams(_,t.zoom,i._styleColorTheme.lut);if(!e)continue;const p=l?l.getShaderSource(_):null,f=n&&(!p||p.usedDefines.has("RENDER_TO_TEXTURE"));let m=e.defines;if(h&&f&&(m=(m||[]).concat("USE_MRT1"),"mrt-full-rgba"===l.emissiveMode&&(m=(m||[]).concat("USE_MRT1_RGBA"))),c){d(_,e.defines,{params:e}),f&&d(_,m,{params:e,rtt:!0});continue}const g=s&&(!p||p.usedDefines.has("FOG")),v=o&&!u.isDraped()&&(!p||p.usedDefines.has("TERRAIN")),y=r&&(!p||p.usedDefines.has("GLOBE")),x=a&&u.hasElevation()&&(!p||p.usedDefines.has("RENDER_SHADOWS"));for(const t of x?[!1,!0]:[!1]){const i=t?(e.defines||[]).concat(Id):e.defines||[];for(const t of v?[!1,!0]:[!1])for(const s of y?[!1,!0]:[!1])for(const o of g?[!1,!0]:[!1])d(_,i,{params:e,fog:o,terrain:t,globe:s})}f&&d(_,m,{params:e,rtt:!0})}}if(d("clippingMask"),o)for(const e of[!1,!0])d("terrainRaster",e?["TERRAIN_VERTEX_MORPHING"]:[],{terrain:!0,fog:s});if(!c){if(e.some(e=>"hillshade"===e.type)&&d("hillshadePrepare"),a)for(const e of[!1,!0])for(const t of[!1,!0]){const i=[];e&&i.push("RENDER_CUTOFF"),i.push("RENDER_SHADOWS"),t&&i.push("NORMAL_OFFSET"),d("groundShadow",i),s&&d("groundShadow",i,{fog:!0})}if(r){for(const e of[[],["TERRAIN_VERTEX_MORPHING"],["GLOBE_POLES"]])for(const t of[!1,!0]){const i=[...e,"PROJECTION_GLOBE_VIEW"];t&&i.push("CUSTOM_ANTIALIASING"),d("globeRaster",i,{terrain:o,globe:!0,fog:s})}for(const e of[!1,!0]){const t=e?["PROJECTION_GLOBE_VIEW","FOG"]:["FOG"];d("globeAtmosphere",t,{fog:!0,terrain:o,globe:e}),d("globeAtmosphere",[...t,"ALPHA_PASS"],{fog:!0,terrain:o,globe:e})}d("stars",[],{fog:s,terrain:o,globe:!0})}}}_executeBatch(t,i,s){if(s.map&&s.map.isMoving())return void(this._idleHandle=T.requestIdleCallback(e=>this._executeBatch(e,i,s)));i.context.sweepPendingPrograms();const o=i.context.extParallelShaderCompile?e.DEADLINE_MARGIN_KHR_MS:e.DEADLINE_MARGIN_SYNC_MS;let r=0;for(;this._queue.length>0;){const e=this._queue.shift();if(!e)break;if(e.programId in Ed&&(i.style=s,i._fogVisible=!!e.params.overrideFog,i.getOrCreateProgram(e.programId,e.params),r++,t.timeRemaining()<=o))break}const n=0===this._queue.length||t.timeRemaining()>o;r>0&&n&&i.context.gl.flush(),this._idleHandle=this._queue.length>0||i.context._pendingPrograms.size>0?T.requestIdleCallback(e=>this._executeBatch(e,i,s)):null}processQueue(e,t){0!==this._queue.length&&(null!=this._idleHandle&&"undefined"!=typeof cancelIdleCallback&&cancelIdleCallback(this._idleHandle),this._idleHandle=T.requestIdleCallback(i=>this._executeBatch(i,e,t)))}reset(){null!=this._idleHandle&&"undefined"!=typeof cancelIdleCallback&&cancelIdleCallback(this._idleHandle),this._queue=[],this._idleHandle=null,this._needsBuild=!0}};Dd.DEADLINE_MARGIN_KHR_MS=5,Dd.DEADLINE_MARGIN_SYNC_MS=25;let Rd=Dd;const Cd=new W(y.colorTheme.data);function Ad(e){if(!e.metadata||!e.metadata.content_area)return;const t=T.devicePixelRatio,{left:i,top:s,width:o,height:r}=e.metadata.content_area,n=i*t,a=s*t;return[n,a,n+o*t,a+r*t]}function Ld(e){if(e)return e.map(([e,t])=>[e*T.devicePixelRatio,t*T.devicePixelRatio])}class Pd{constructor(e,t,i){this.id=e,this.scope=t,this.sourceCache=i,this.pendingRequests=new Set,this.missingRequests=new Set}addPendingRequest(e){this.missingRequests.has(e.name)||this.pendingRequests.has(e.name)||this.pendingRequests.add(e.name)}hasPendingRequests(){return this.pendingRequests.size>0}resolvePendingRequests(){const e=new Map;if(!this.sourceCache.loaded())return e;const t=this.sourceCache.getVisibleCoordinates();if(0===t.length)return e;const i=this.sourceCache.getSource();if("raster-array"!==i.type)return e;const s=t.map(e=>this.sourceCache.getTile(e)),o=i.getImages(s,Array.from(this.pendingRequests));for(const[t,i]of o)e.set(g.from({name:t,iconsetId:this.id}),i),this.pendingRequests.delete(t);for(const e of this.pendingRequests)this.missingRequests.add(e);return this.pendingRequests.clear(),e}}const Md=(e,t)=>Pa(e,t&&t.filter(e=>"source.canvas"!==e.identifier)),Od=new Set(["addLayer","removeLayer","setLights","setPaintProperty","setLayoutProperty","setLayerProperty","setSlot","setFilter","addSource","removeSource","setLayerZoomRange","setLight","setTransition","setGeoJSONSourceData","setTerrain","setFog","setSnow","setRain","setProjection","setCamera","addImport","removeImport","updateImport","addIconset","removeIconset"]),zd=new Set(["setCenter","setZoom","setBearing","setPitch"]),Fd=new Set(["background","sky","slot","custom","placement-group"]),kd={version:8,layers:[],sources:{}},Bd={duration:300,delay:0};class Nd extends A{constructor(e,t={}){super(),this.map=e,this.scope=t.scope||"",this.globalId=null,this.fragments=[],this.importDepth=t.importDepth||0,this.importsCache=t.importsCache||new Map,this.resolvedImports=t.resolvedImports||new Set,this.transition={...Bd},this._buildingIndex=new Mc(this),this.crossTileSymbolIndex=new Mh,this.globalPlacement=null,this._groupOrders=null,this._groupOrdersVersion=-1,this._mergedOrder=[],this._mergedOrderVersion=0,this._drapedFirstOrder=[],this._mergedLayers=Object.create(null),this._mergedIndoor={},this._indoorEnabled=!1,this._mergedSourceCaches={},this._mergedOtherSourceCaches=Object.create(null),this._mergedSymbolSourceCaches=Object.create(null),this._mergedFillExtrusionSourceCaches=Object.create(null),this._mergedHdRoadCoverageSourceCaches=Object.create(null),this._hdCoverage=null,this._hdElevation=null,this._crossSourceElevationActive=!1,this._clipLayerPresent=!1,this._hasAppearances=!1,this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this._importedAsBasemap=!1,this._changes=t.styleChanges||new Fn,this._hasDataDrivenEmissive=!1,this.indoorManager=null,this.dispatcher=t.dispatcher?t.dispatcher:new pl(Oc(),this),this.glyphManager=t.glyphManager?t.glyphManager:new Sa(e._requestManager,t.localFontFamily?$i.all:t.localIdeographFontFamily?$i.ideographs:$i.none,t.localFontFamily||t.localIdeographFontFamily,t.fontstackCompositing);const i={referrer:us(),config:ds()};if(this.map.painter&&this.map.painter.context){const e=Math.floor(this.map.painter.context.maxUniformBlockSize/4);i.contextOptions={maxUniformBlockSizeDwords:e}}if(this.isRootStyle()){const{mode:e,fontFamily:t}=this.glyphManager.localGlyphs;t&&!Xi(t)&&(i.localGlyphs={mode:e,fontFamily:t}),this.dispatcher.broadcast("setGlobalParams",i)}t.imageManager?this.imageManager=t.imageManager:(this.imageManager=new Ea(this.map._spriteFormat),this.imageManager.setEventedParent(this)),this.imageManager.addScope(this.scope),t.modelManager?this.modelManager=t.modelManager:(this.modelManager=new Wh(e._requestManager),this.modelManager.setEventedParent(this)),this._layers=Object.create(null),this._sourceCaches={},this._otherSourceCaches=Object.create(null),this._symbolSourceCaches=Object.create(null),this._fillExtrusionSourceCaches=Object.create(null),this._hdCoverage=null,this._hdElevation=null,this._crossSourceElevationActive=!1,this._loaded=!1,this._drapingLoaded=void 0,this._rasterArrayLoaded=void 0,this._initialBroadcastDone=!1,this._programPrecompiler=this.map._precompilePrograms&&this.isRootStyle()?new Rd:null,this._availableImages=[],this._availableModels={},this._order=[],this._markersNeedUpdate=!1,this.options=t.configOptions?t.configOptions:new Map,this._layerExpressionDependencies=t.layerExpressionDependencies?t.layerExpressionDependencies:new Map,this._config=t.config,this._styleColorTheme={lut:null,lutLoading:!1,lutLoadingCorrelationID:0,colorTheme:null,colorThemeOverride:t.colorThemeOverride},this._styleColorThemeForScope={},this._initialConfig=t.initialConfig,this.on("data",e=>{if("source"!==e.dataType||"metadata"!==e.sourceDataType)return;const t=this.getOwnSource(e.sourceId);if(t&&t.vectorLayerIds)for(const e in this._layers){const i=this._layers[e];i.source===t.id&&this._validateLayer(i)}})}load(e){return e?("string"==typeof e?this.loadURL(e):this.loadJSON(e),this):this}_getGlobalId(e){if(!e)return null;if("string"==typeof e){if(r(e))return e;const t=Yi(e);if(!t.startsWith("http"))try{return new URL(t,location.href).toString()}catch(e){return t}return t}return`json://${Ki(JSON.stringify(e))}`}_diffStyle(e,t,i){this.globalId=this._getGlobalId(e),La();const s=(e,t)=>{try{t(null,this.setState(e,i))}catch(e){t(e,!1)}};if("string"==typeof e){const i=this.map._requestManager.normalizeStyleURL(e),o=new AbortController;this._request={cancel:()=>o.abort()},(async()=>{const e=await this.map._requestManager.transformRequest(i,x.Style,o.signal),{data:r}=await b(e,o.signal);this._request=null,s(r,t)})().catch(e=>{this._request=null,o.signal.aborted||this.fire(new P(e))})}else"object"==typeof e&&s(e,t)}loadURL(e,t={}){this.fire(new M("dataloading",{dataType:"style"}));const i="boolean"==typeof t.validate?t.validate:!r(e);i&&La(),e.startsWith("mapbox://styles/mapbox/standard")&&Cl(),this.globalId=this._getGlobalId(e),e=this.map._requestManager.normalizeStyleURL(e,t.accessToken),this.resolvedImports.add(e);const s=this.importsCache.get(e);if(s)return void this._load(s,i);const o=new AbortController;this._request={cancel:()=>o.abort()},(async()=>{const t=await this.map._requestManager.transformRequest(e,x.Style,o.signal),{data:s}=await b(t,o.signal);this._request=null,this.importsCache.set(e,s),this._load(s,i)})().catch(e=>{this._request=null,o.signal.aborted||this.fire(new P(e))})}loadJSON(e,t={}){this.fire(new M("dataloading",{dataType:"style"}));const i=!1!==t.validate;i&&La(),this.globalId=this._getGlobalId(e),this._request=T.frame(()=>{this._request=null,this._load(e,i)})}loadEmpty(){this.fire(new M("dataloading",{dataType:"style"})),this._load(kd,!1)}_loadImports(e,t,i){if(this.importDepth>=4)return _("Style doesn't support nesting deeper than 5"),Promise.resolve();const s=[];for(const o of e){const e=this._createFragmentStyle(o),r=new Promise(t=>{e.once("style.import.load",t),e.once("error",i=>{e._loaded||t(i)})}).then(()=>{this.mergeAll(),this.fire(new M("data",{dataType:"style"}))});if(s.push(r),this.resolvedImports.has(o.url)){e.loadEmpty();continue}const n=o.data||this.importsCache.get(o.url);n?(o.data?(e.fire(new M("dataloading",{dataType:"style"})),e.globalId=e._getGlobalId(n),t&&La(),queueMicrotask(()=>{e._load(n,t)})):e.loadJSON(n,{validate:t}),this._isInternalStyle(n)&&(e.globalId=null)):o.url?e.loadURL(o.url,{validate:t}):e.loadEmpty();const a={style:e,id:o.id,config:o.config};if(i){const e=this.fragments.findIndex(({id:e})=>e===i);this.fragments=this.fragments.slice(0,e).concat(a).concat(this.fragments.slice(e))}else this.fragments.push(a)}return Promise.allSettled(s)}getImportGlobalIds(e=this,t=new Set){for(const i of e.fragments)i.style.globalId&&t.add(i.style.globalId),this.getImportGlobalIds(i.style,t);return[...t.values()]}_createFragmentStyle(e){const t=this.scope?C(e.id,this.scope):e.id;let i;const s=this._initialConfig&&this._initialConfig[t];(e.config||s)&&(i={...e.config,...s});const o=new Nd(this.map,{scope:t,styleChanges:this._changes,importDepth:this.importDepth+1,importsCache:this.importsCache,resolvedImports:new Set(this.resolvedImports),dispatcher:this.dispatcher,imageManager:this.imageManager,glyphManager:this.glyphManager,modelManager:this.modelManager,config:i,configOptions:this.options,colorThemeOverride:e["color-theme"],layerExpressionDependencies:this._layerExpressionDependencies});return o.setEventedParent(this.map,{style:o}),o}_reloadImports(e=!1){this.mergeAll(),this._updateMapProjection(),e?this._updateEnvConfig("reset"):this.updateConfigDependencies(),this._updateLayers(this._dependentLayerIds(e=>e.isIndoorDependent)),this.map._triggerCameraUpdate(this.camera),(!e||this.isRootStyle()||this.map.style._initialBroadcastDone)&&(e&&this.isRootStyle()?(this.forEachFragmentStyle(e=>{this.dispatcher.broadcast("setLayers",{layers:e._serializeLayers(e._order),scope:e.scope,options:e.options})}),this._initialBroadcastDone=!0):this.dispatcher.broadcast("setLayers",{layers:this._serializeLayers(this._order),scope:this.scope,options:this.options}))}_isInternalStyle(e){return this.isRootStyle()&&(e.fragment||!!e.schema&&!1!==e.fragment)}async _load(e,t){if(this._isInternalStyle(e)){const i={id:"basemap",data:e,url:""},s={...kd,imports:[i],...e.center?{center:e.center}:{},...e.bearing?{bearing:e.bearing}:{},...e.pitch?{pitch:e.pitch}:{},...e.zoom?{zoom:e.zoom}:{},...e.light?{light:e.light}:{}};return this._importedAsBasemap=!0,void this._load(s,t)}if(t){if(await La(),!this.dispatcher.actors.length)return;if(Md(this,Oa(e)))return}e.sprite&&this._loadIconset(e.sprite),this._loaded=!0,this.updateConfig(this._config,e.schema);for(const t in e.sources)this.addSource(t,e.sources[t],{validate:!1,isInitialLoad:!0});this.stylesheet=Ji(e);const i=()=>{if(e.iconsets)for(const t in e.iconsets)this.addIconset(t,e.iconsets[t]);e.sprite||(this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope})),!this.glyphManager.url&&e.glyphs&&this.glyphManager.setURL(e.glyphs);const i=Bc(this.stylesheet.layers);if(this._order=i.map(e=>e.id),this.stylesheet.light&&_("The `light` root property is deprecated, prefer using `lights` with `flat` light type instead."),this.stylesheet.lights)if(1===this.stylesheet.lights.length&&"flat"===this.stylesheet.lights[0].type){const e=this.stylesheet.lights[0];this.light=new Ya(e.properties,e.id)}else this.setLights(this.stylesheet.lights);this.light||(this.light=new Ya(this.stylesheet.light)),this._layers=Object.create(null);let s=!1;for(const e of i){const t=os(e,this.scope,this._styleColorTheme.lut,this.options);this._layerExpressionDependencies.set(t.fqid,new kn(t)),this._hasAppearances=this._hasAppearances||0!==t.getAppearances().length,t.setEventedParent(this,{layer:{id:t.id}}),this._layers[t.id]=t,this._updateHdCoverageSourceCache(t)&&(s=!0);const i=this.getOwnLayerSourceCache(t),o=!!this.directionalLight&&this.directionalLight.shadowsEnabled();i&&t.canCastShadows()&&o&&(i.castsShadows=!0)}s&&Dl().then(()=>{if(!this.map)return;for(const e in this._layers)this._updateHdCoverageSourceCache(this._layers[e]);this.map.style.mergeAll();const e=this.map.transform;for(const t in this.map.style._mergedHdRoadCoverageSourceCaches){const i=this.map.style._mergedHdRoadCoverageSourceCaches[t];i.used=!0,e&&i.update(e)}this.map._update()}),this.stylesheet.featuresets&&this.setFeaturesetSelectors(this.stylesheet.featuresets),this.stylesheet.models&&this.addModelURLs(this.stylesheet.models);const o=this.stylesheet.terrain;o&&(this.checkCanvasFingerprintNoise(),this.disableElevatedTerrain||this.terrainSetForDrapingOnly()||(this._startLiteLoad(),this._createTerrain(o,Ja.elevated))),this.stylesheet.fog&&this._createFog(this.stylesheet.fog),this.stylesheet.snow&&this._createSnow(this.stylesheet.snow),this.stylesheet.rain&&this._createRain(this.stylesheet.rain),this.stylesheet.transition&&this.setTransition(this.stylesheet.transition),this.fire(new M("data",{dataType:"style"}));const r=this.isRootStyle();e.imports?this._loadImports(e.imports,t).then(()=>{this._reloadImports(!0),this.fire(new M(r?"style.load":"style.import.load"))}).catch(e=>{this.fire(new P(new Error("Failed to load imports",e))),this.fire(new M(r?"style.load":"style.import.load"))}):(this._reloadImports(!0),this.fire(new M(r?"style.load":"style.import.load")))};this._styleColorTheme.colorTheme=this.stylesheet["color-theme"];const s=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(s){const e=this._evaluateColorThemeData(s);this._loadColorTheme(e).then(()=>{i()}).catch(e=>{_(`Couldn't load color theme from the stylesheet: ${e}`),i()})}else this._styleColorTheme.lut=null,i()}isRootStyle(){return 0===this.importDepth}hasAppearances(){return this._hasAppearances||this.fragments.some(e=>e.style.hasAppearances())}mergeAll(){let e,t,i,s,o,r,n,a,l,c;const h={};this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(d=>{if(d.stylesheet){if(d.disableElevatedTerrain&&(this.disableElevatedTerrain=!0),null!=d.light&&(e=d.light),d.stylesheet.lights)for(const e of d.stylesheet.lights)"ambient"===e.type&&null!=d.ambientLight&&(t=d.ambientLight),"directional"===e.type&&null!=d.directionalLight&&(i=d.directionalLight);s=this._prioritizeTerrain(s,d.terrain,d.stylesheet.terrain),d.stylesheet.fog&&null!=d.fog&&(o=d.fog),d.stylesheet.snow&&null!=d.snow&&(r=d.snow),d.stylesheet.rain&&null!=d.rain&&(n=d.rain),null!=d.stylesheet.camera&&(c=d.stylesheet.camera),null!=d.stylesheet.projection&&(a=d.stylesheet.projection),null!=d.stylesheet.transition&&(l=d.stylesheet.transition),h[d.scope]=d._styleColorTheme}}),this.light=e,this.ambientLight=t,this.directionalLight=i,this.fog=o,this.snow=r,this.rain=n,this._styleColorThemeForScope=h,null===s?delete this.terrain:this.terrain=s,this.camera=c||{"camera-projection":"perspective"},this.projection=a||{name:"mercator"},this.transition={...Bd,...l},this.mergeSources(),this.mergeLayers(),this.mergeIndoor(),this._programPrecompiler&&this._programPrecompiler.reset()}forEachFragmentStyle(e){const t=i=>{for(const e of i.fragments)t(e.style);e(i)};t(this)}_prioritizeTerrain(e,t,i){const s=e&&e.drapeRenderMode===Ja.deferred;return null===i?t&&t.drapeRenderMode===Ja.deferred?t:s?e:null:null!=t&&(!e||s||t&&t.drapeRenderMode===Ja.elevated)?t:e}mergeTerrain(){let e;this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(t=>{e=this._prioritizeTerrain(e,t.terrain,t.stylesheet.terrain)}),null===e?delete this.terrain:this.terrain=e,this._programPrecompiler&&this._programPrecompiler.reset()}mergeProjection(){let e;this.forEachFragmentStyle(t=>{null!=t.stylesheet.projection&&(e=t.stylesheet.projection)}),this.projection=e||{name:"mercator"},this._programPrecompiler&&this._programPrecompiler.reset()}mergeSources(){const e={},t=Object.create(null),i=Object.create(null),s=Object.create(null),o=Object.create(null);this.forEachFragmentStyle(r=>{for(const t in r._sourceCaches){const i=C(t,r.scope);e[i]=r._sourceCaches[t]}for(const e in r._otherSourceCaches){const i=C(e,r.scope);t[i]=r._otherSourceCaches[e]}for(const e in r._symbolSourceCaches){const t=C(e,r.scope);i[t]=r._symbolSourceCaches[e]}for(const e in r._fillExtrusionSourceCaches){const t=C(e,r.scope);s[t]=r._fillExtrusionSourceCaches[e]}if(r._hdCoverage){const e=r._hdCoverage.coverageSourceCaches;for(const t in e)o[C(t,r.scope)]=e[t]}}),this._mergedSourceCaches=e,this._mergedOtherSourceCaches=t,this._mergedSymbolSourceCaches=i,this._mergedFillExtrusionSourceCaches=s,this._mergedHdRoadCoverageSourceCaches=o,Object.keys(o).length>0&&!this._hdCoverage&&Il.HdCoverageState&&(this._hdCoverage=new Il.HdCoverageState),Il.updateCrossSourceElevationGate&&Il.updateCrossSourceElevationGate(this)}mergeIndoor(){this._mergedIndoor={},this.forEachFragmentStyle(e=>{if(e.stylesheet&&e.stylesheet.indoor)for(const t of Object.values(e.stylesheet.indoor)){const i=t,s=C(i.sourceId,e.scope);this._mergedIndoor[s]=new Set(i.sourceLayers||[])}}),this._updateIndoorEnabled()}_updateIndoorEnabled(){const e=this._indoorEnabled;if(this._indoorEnabled=!1,Object.keys(this._mergedIndoor).length>0)for(const e of this._mergedOrder){const t=this._mergedLayers[e];if("none"!==t.visibility&&this._mergedIndoor[C(t.source,t.scope)]){this._indoorEnabled=!0;break}}!this._indoorEnabled||e||this.indoorManager||Dl().then(()=>{this._initIndoorManager()})}_initIndoorManager(){if(!this.indoorManager&&Il.IndoorManager&&this.isRootStyle()&&0!==Object.keys(this._mergedIndoor).length&&(this.indoorManager=new Il.IndoorManager(this,this._loaded),this._loaded))for(const e of Object.keys(this._mergedIndoor)){const t=this._mergedSourceCaches[e]||this._mergedOtherSourceCaches[e];t&&t.reload()}}mergeLayers(){const e={},t=[],i=Object.create(null);this._mergedSlots=[],this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this.forEachFragmentStyle(i=>{for(const s of i._order){const o=i._layers[s];if("slot"===o.type){const t=Qi(s);if(e[t])continue;e[t]=[]}o.slot&&e[o.slot]?e[o.slot].push(o):t.push(o)}}),this._mergedOrder=[];let s=-1;const o=(t=[])=>{for(const r of t)if("slot"===r.type){const t=Qi(r.id);e[t]&&o(e[t]),this._mergedSlots.push(t)}else{const e=C(r.id,r.scope);this._mergedOrder.push(e),i[e]=r,r.is3D(!!this.terrain)&&(this._has3DLayers=!0,s=this._mergedOrder.length-1),"circle"===r.type&&(this._hasCircleLayers=!0),"symbol"===r.type&&(this._hasSymbolLayers=!0),"clip"===r.type&&(this._clipLayerPresent=!0)}};if(o(t),this._has3DLayers){const e={};for(let t=0;t<this._mergedOrder.length;++t){const o=this._mergedOrder[t];e[o]=t===s?1:t<s?i[o].hasOcclusionOpacityProperties?2:0:4}this._mergedOrder.sort((t,i)=>e[t]-e[i])}this._mergedLayers=i,this._mergedOrderVersion++,this.updateDrapeFirstLayers(),this._buildingIndex.processLayersChanged(),this._updateDataDrivenEmissiveStrength()}terrainSetForDrapingOnly(){return!!this.terrain&&this.terrain.drapeRenderMode===Ja.deferred}getCamera(){return this.stylesheet.camera}setCamera(e){return this.stylesheet.camera={...this.stylesheet.camera,...e},this.camera=this.stylesheet.camera,this}_evaluateColorThemeData(e){return e.data?new Hi(Cd,e.data,this.scope,this.options).possiblyEvaluate(new X(0)):null}_loadColorTheme(e){this._styleColorTheme.lutLoading=!0,this._styleColorTheme.lutLoadingCorrelationID+=1;const t=this._styleColorTheme.lutLoadingCorrelationID;return new Promise((i,s)=>{const o="data:image/png;base64,";if(!e||0===e.length)return this._styleColorTheme.lut=null,this._styleColorTheme.lutLoading=!1,void i();let r=e;r.startsWith(o)||(r=o+r);const n=g.from("mapbox-reserved-lut"),a=new Image;a.src=r,a.onerror=()=>{this._styleColorTheme.lutLoading=!1,s(new Error("Failed to load image data"))},a.onload=()=>{if(this._styleColorTheme.lutLoadingCorrelationID!==t)return void i();this._styleColorTheme.lutLoading=!1;const{width:o,height:r,data:l}=T.getImageData(a);if(r>32)return void s(new Error("The height of the image must be less than or equal to 32 pixels."));if(o!==r*r)return void s(new Error("The width of the image must be equal to the height squared."));this.getImage(n)&&this.removeImage(n),this.addImage(n,{data:new E({width:o,height:r},l),pixelRatio:1,sdf:!1,usvg:!1,version:0});const c=this.imageManager.getImage(n,this.scope);c?(this._styleColorTheme.lut={image:c.data,data:e},i()):s(new Error("Missing LUT image."))}})}getLut(e){const t=this._styleColorThemeForScope[e];return t?t.lut:null}setProjection(e){e?this.stylesheet.projection=e:delete this.stylesheet.projection,this.mergeProjection(),this._updateMapProjection()}applyProjectionUpdate(){this.map.transform.projection.requiresDraping&&this._startLiteLoad(),this._loaded&&(this.dispatcher.broadcast("setProjection",this.map.transform.projectionOptions),this.map.transform.projection.requiresDraping?(this.getTerrain()||this.stylesheet.terrain)&&!this.disableElevatedTerrain||this.setTerrainForDraping():this.terrainSetForDrapingOnly()&&this.setTerrain(null,Ja.deferred))}_updateMapProjection(){this.isRootStyle()&&(this.map._useExplicitProjection?this.applyProjectionUpdate():this.map._prioritizeAndUpdateProjection(null,this.projection))}_loadSprite(e){const t=new AbortController;this._spriteRequest=t,function(e,t,i,s){let o,r,n;const a=T.devicePixelRatio>1?"@2x":"";function l(e){n||e&&i.aborted||(e&&(n=e),function(){if(n)s(n);else if(o&&r){const e=T.getImageData(r),t={};for(const i in o){const{width:s,height:r,x:n,y:a,sdf:l,pixelRatio:c,stretchX:h,stretchY:d,content:u}=o[i],_=new E({width:s,height:r});E.copy(e,_,{x:n,y:a},{x:0,y:0},{width:s,height:r},null),t[i]={data:_,pixelRatio:void 0!==c?c:1,sdf:void 0!==l&&l,stretchX:h,stretchY:d,content:u,usvg:!1,version:0}}s(null,t)}}())}(async function(){const s=await t.transformRequest(t.normalizeSpriteURL(e,a,".json"),x.SpriteJSON,i),{data:r}=await b(s,i);n||(o=r)})().then(()=>l(void 0),e=>l(e)),async function(){const s=await t.transformRequest(t.normalizeSpriteURL(e,a,".png"),x.SpriteImage,i),{data:o}=await w(s,i);n||(r=o)}().then(()=>l(void 0),e=>l(e))}(e,this.map._requestManager,t.signal,(e,t)=>{if(this._spriteRequest=null,e)this.dispatcher.broadcast("spriteLoaded",{scope:this.scope}),this.fire(new P(e));else if(t){const e=new Map;for(const i in t)e.set(g.from(i),t[i]);this.addImages(e,!0)}this.imageManager.setLoaded(!0,this.scope),this.fire(new M("data",{dataType:"style"}))})}addIconset(e,t){if("sprite"===t.type)return void this._loadSprite(t.url);const i=this.getOwnSourceCache(t.source);if(!i)return void this.fire(new P(new Error(`Source "${t.source}" as specified by iconset "${e}" does not exist and cannot be used as an iconset source`)));if("raster-array"!==i.getSource().type)return void this.fire(new P(new Error(`Source "${t.source}" as specified by iconset "${e}" is not a "raster-array" source and cannot be used as an iconset source`)));const s=new Pd(e,this.scope,i);this.imageManager.addImageProvider(s,this.scope)}removeIconset(e){this.imageManager.removeImageProvider(e,this.scope)}_loadIconset(e){if(!r(e)&&"icon_set"!==this.map._spriteFormat||"raster"===this.map._spriteFormat)return void this._loadSprite(e);const t="auto"===this.map._spriteFormat,i=new AbortController;this._spriteRequest=i,async function(e,t,i,s){try{const o=await t.transformRequest(t.normalizeIconsetURL(e),x.Iconset,i),{data:r}=await N(o,i),n={},a=function(e){const t={icons:[]};let i;for(;i=e.nextField(void 0);)1===i&&t.icons.push(Vn(e,e.readVarint()+e.pos));return t}(new I(r));for(const e of a.icons){const t={version:1,pixelRatio:T.devicePixelRatio,content:Ad(e),stretchX:e.metadata?Ld(e.metadata.stretch_x_areas):void 0,stretchY:e.metadata?Ld(e.metadata.stretch_y_areas):void 0,sdf:!1,usvg:!0,icon:e};n[e.name]=t}s(null,n)}catch(e){i.aborted||s(e)}}(e,this.map._requestManager,i.signal,(i,s)=>{if(this._spriteRequest=null,i)t?this._loadSprite(e):(this.dispatcher.broadcast("spriteLoaded",{scope:this.scope}),this.fire(new P(i)));else if(s){const e=new Map;for(const t in s)e.set(g.from(t),s[t]);this.addImages(e,!0)}this.imageManager.setLoaded(!0,this.scope),this.fire(new M("data",{dataType:"style"}))})}_validateLayer(e){const t=this.getOwnSource(e.source);if(!t)return;const i=e.sourceLayer;i&&("geojson"===t.type||t.vectorLayerIds&&!t.vectorLayerIds.includes(i))&&this.fire(new P(new Error(`Source layer "${i}" does not exist on source "${t.id}" as specified by style layer "${e.id}"`)))}loaded(){if(!this._loaded)return!1;if(Object.keys(this._changes.getUpdatedSourceCaches()).length)return!1;for(const e in this._sourceCaches)if(!this._sourceCaches[e].loaded())return!1;if(!this.imageManager.isLoaded())return!1;if(this.imageManager.hasPatternsInFlight())return!1;if(!this.modelManager.isLoaded())return!1;if(this._styleColorTheme.lutLoading)return!1;if(!1===this._drapingLoaded)return!1;if(!1===this._rasterArrayLoaded)return!1;for(const{style:e}of this.fragments)if(!e.loaded())return!1;return!0}_serializeImports(){if(this.stylesheet.imports)return this.stylesheet.imports.map((e,t)=>{const i=this.fragments[t];return i&&i.style&&(e.data=i.style.serialize()),e})}_serializeSources(){const e={};for(const t in this._sourceCaches){const i=this._sourceCaches[t].getSource();e[i.id]||(e[i.id]=i.serialize())}return e}_serializeLayers(e){const t=[];for(const i of e){const e=this._layers[i];e&&"custom"!==e.type&&t.push(e.serialize())}return t}hasLightTransitions(){return!(!this.light||!this.light.hasTransition())||!(!this.ambientLight||!this.ambientLight.hasTransition())||!(!this.directionalLight||!this.directionalLight.hasTransition())}hasFogTransition(){return!!this.fog&&this.fog.hasTransition()}hasSnowTransition(){return!!this.snow&&this.snow.hasTransition()}hasRainTransition(){return!!this.rain&&this.rain.hasTransition()}hasTransitions(){if(this.hasLightTransitions())return!0;if(this.hasFogTransition())return!0;if(this.hasSnowTransition())return!0;if(this.hasRainTransition())return!0;for(const e in this._mergedSourceCaches)if(this._mergedSourceCaches[e].hasTransition())return!0;for(const e in this._mergedLayers)if(this._mergedLayers[e].hasTransition())return!0;return!1}_updateDataDrivenEmissiveStrength(){for(const e in this._mergedLayers){const t=this._mergedLayers[e].getPaintPropertyValue("line-emissive-strength");if(t&&t.isDataDriven())return void(this._hasDataDrivenEmissive=!0)}this._hasDataDrivenEmissive=!1}hasDataDrivenEmissiveStrength(){return this._hasDataDrivenEmissive}get order(){return this.terrain?this._drapedFirstOrder:this._mergedOrder}_getOrder(e){return e?this.order:this._mergedOrder}isLayerDraped(e){return!!this.terrain&&e.isDraped(this.getLayerSourceCache(e))}_checkLoaded(){if(!this._loaded)throw new Error("Style is not done loading")}_checkLayer(e){const t=this.getOwnLayer(e);if(t)return t;this.fire(new P(new Error(`The layer '${e}' does not exist in the map's style.`)))}_checkSource(e){const t=this.getOwnSource(e);if(t)return t;this.fire(new P(new Error(`The source '${e}' does not exist in the map's style.`)))}_resolveLayerFragment(e){const t=this.getLayer(e);if(!t)return void this.fire(new P(new Error(`The layer '${e}' does not exist in the map's style.`)));const i=this.getFragmentStyle(t.scope);return i?{layer:t,fragment:i}:void 0}handleIdle(){const e=this.map.painter;e&&(e.context.sweepPendingPrograms(),this._programPrecompiler&&this._programPrecompiler.processQueue(e,this))}handleContextLost(){this._programPrecompiler&&this._programPrecompiler.reset()}update(e){if(!this._loaded)return;this.ambientLight&&this.ambientLight.recalculate(e),this.directionalLight&&this.directionalLight.recalculate(e);const t=this.calculateLightsBrightness();e.brightness=t||0;let i=!1;t!==this._brightness&&(this._brightness=t,i=!0),e.worldview!==this._worldview&&(this._worldview=e.worldview,i=!0),i&&this.dispatcher.broadcast("upsertRenderParams",{brightness:this._brightness,worldview:this._worldview});const s=this._changes.isDirty();let o=!1;if(this._changes.isDirty()){const t=this._changes.getLayerUpdatesByScope();for(const e in t){const{updatedIds:i,removedIds:s}=t[e];(i||s)&&(this._updateWorkerLayers(e,i,s),o=!0)}this.updateSourceCaches(),this._updateTilesForChangedImages(),this.updateLayers(e),this.light&&this.light.updateTransitions(e),this.ambientLight&&this.ambientLight.updateTransitions(e),this.directionalLight&&this.directionalLight.updateTransitions(e),this.fog&&this.fog.updateTransitions(e),this.snow&&this.snow.updateTransitions(e),this.rain&&this.rain.updateTransitions(e),this._changes.reset()}const r={};for(const e in this._mergedSourceCaches){const t=this._mergedSourceCaches[e];r[e]=t.used,t.used=!1,t.tileCoverLift=0}const n={};for(const t of this._mergedOrder){const i=this._mergedLayers[t],s=i.paint;if("none"===i.visibility&&!i.hasTransition()||!i._dirty&&i.isHidden(e.zoom)||i.recalculate(e,this._availableImages),s&&s!==i.paint&&i.isPlacementAffectedByPaintChanges(s)&&this._setLabelPlacementStale(),!i.isHidden(e.zoom)){i.mayUse("HD")&&(i.prepare(),Dl()),i.mayUse("Standard")&&(i.prepare(),Cl()),i.mayUse("Lite")&&(this.checkCanvasFingerprintNoise(),this.disableElevatedTerrain||this._startLiteLoad()),i.mayUse("RasterArray")&&this._startRasterArrayLoad();const e=this.getLayerSourceCache(i);e&&(e.used=!0,e.tileCoverLift=Math.max(e.tileCoverLift,i.tileCoverLift()))}if(i.source){const e=this._mergedHdRoadCoverageSourceCaches[i.sourceFqid];e&&!e.used&&(e.used=!0)}if("fill-extrusion"===i.type){const e=C(i.source,i.scope);if(e in this._mergedFillExtrusionSourceCaches){const t=i.layout&&i.layout.get("source-max-zoom");if(null!=t){const i=n[e];n[e]=null==i?t:Math.min(i,t)}}}}if(this._programPrecompiler&&this._programPrecompiler.needsBuild()){const t=this._mergedOrder.map(e=>this._mergedLayers[e]);this._programPrecompiler.buildQueue(t,e,this)}for(const e in this._mergedFillExtrusionSourceCaches)this._mergedFillExtrusionSourceCaches[e].setMaxzoomOverride(n[e]??null);this.terrain&&o&&this.mergeLayers();const a=this.imageManager.getPendingImageProviders();for(const e of a)e.sourceCache.used=!0;for(const e in r){const t=this._mergedSourceCaches[e],i=t.getSource();t.used&&i instanceof Jl&&i.startLoad(),r[e]!==t.used&&i.fire(new M("data",{sourceDataType:"visibility",dataType:"source",sourceId:i.id}))}this.light&&this.light.recalculate(e),this.terrain&&this.terrain.recalculate(e),this.fog&&this.fog.recalculate(e),this.snow&&this.snow.recalculate(e),this.rain&&this.rain.recalculate(e),this.z=e.zoom,this._markersNeedUpdate&&(this._updateMarkersOpacity(),this._markersNeedUpdate=!1),this.imageManager.clearUpdatedImages(this.scope),s&&this.fire(new M("data",{dataType:"style"}))}updateImageProviders(){const e=this.imageManager.getPendingImageProviders();for(const t of e){const e=t.resolvePendingRequests(),i=this.getFragmentStyle(t.scope);i&&i.addImages(e)}}_updateTilesForChangedImages(){const e={};for(const t in this._mergedSourceCaches){const i=this._mergedSourceCaches[t].getSource().scope;e[i]=e[i]||this._changes.getUpdatedImages(i),0!==e[i].length&&this._mergedSourceCaches[t].reloadTilesForDependencies(["icons","patterns"],e[i])}for(const t in e)this._changes.resetUpdatedImages(t)}_updateWorkerLayers(e,t,i){const s=this.getFragmentStyle(e);s&&this.dispatcher.broadcast("updateLayers",{layers:t?s._serializeLayers(t):[],scope:e,removedIds:i||[],options:s.options})}setState(e,t){if(this._checkLoaded(),Md(this,Oa(e)))return!1;if((e=Ji(e)).layers=Bc(e.layers),!Ca.diffStyles)throw new Error("Debug module not loaded; cannot diff style.");const i=Ca.diffStyles(this.serialize(),e).filter(e=>!zd.has(e.command));if(0===i.length)return!1;const s=i.filter(e=>!Od.has(e.command));if(s.length>0)throw new Error(`Unimplemented: ${s.map(e=>e.command).join(", ")}.`);const o=[];return i.forEach(e=>{o.push(this[e.command](...e.args))}),t&&Promise.all(o).then(t).catch(t),this.stylesheet=e,this.mergeAll(),this.dispatcher.broadcast("setLayers",{layers:this._serializeLayers(this._order),scope:this.scope,options:this.options}),!0}_updateWorkerImages(e=!1){this._availableImages=this.imageManager.listImages(this.scope);const t={scope:this.scope,images:this._availableImages};e&&(t.isSpriteLoaded=!0),this.dispatcher.broadcast("setImages",t)}_updateWorkerModels(){this._availableModels=this.modelManager.getModelURIs(this.scope),this.dispatcher.broadcast("setModels",{scope:this.scope,models:this._availableModels})}addImages(e,t){if(0===e.size)return t&&this.dispatcher.broadcast("spriteLoaded",{scope:this.scope}),this;for(const[t,i]of e.entries()){if(this.getImage(t))return this.fire(new P(new Error(`An image with the name "${t.name}" already exists.`)));this.imageManager.addImage(t,this.scope,i),this._changes.updateImage(t,this.scope)}return this._updateWorkerImages(t),this.fire(new M("data",{dataType:"style"})),this}addImage(e,t){return this.getImage(e)?this.fire(new P(new Error(`An image with the name "${e.name}" already exists.`))):(this.imageManager.addImage(e,this.scope,t),this._changes.updateImage(e,this.scope),this._updateWorkerImages(),this.fire(new M("data",{dataType:"style"})),this)}updateImage(e,t,i=!1){this.imageManager.updateImage(e,this.scope,t),i&&(this._changes.updateImage(e,this.scope),this._updateWorkerImages(),this.fire(new M("data",{dataType:"style"})))}getImage(e){return this.imageManager.getImage(e,this.scope)}removeImage(e){return this.getImage(e)?(this.imageManager.removeImage(e,this.scope),this._changes.updateImage(e,this.scope),this._updateWorkerImages(),this.fire(new M("data",{dataType:"style"})),this):this.fire(new P(new Error("No image with this name exists.")))}listImages(){return this._checkLoaded(),this._availableImages.slice()}getActualScope(){return this._importedAsBasemap?"basemap":this.scope}addModelURLs(e){return this.modelManager.addModelURLs(e,this.getActualScope()),this._updateWorkerModels(),this.fire(new M("data",{dataType:"style"})),this}addModel(e,t,i={}){return this._checkLoaded(),this._validate(Wa,`models.${e}`,t,null,i)||(this.modelManager.addModel(e,t,this.getActualScope()),this.fire(new M("data",{dataType:"style"}))),this}hasModel(e){return this.modelManager.hasModel(e,this.getActualScope())}removeModel(e){return this.hasModel(e)?(this.modelManager.removeModel(e,this.getActualScope(),!1,!0),this.fire(new M("data",{dataType:"style"})),this):this.fire(new P(new Error("No model with this ID exists.")))}listModels(){return this._checkLoaded(),this.modelManager.listModels(this.getActualScope())}addSource(e,t,i={}){if(this._checkLoaded(),void 0!==this.getOwnSource(e))throw new Error(`There is already a source with ID "${e}".`);if(!t.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(t).join(", ")}.`);if(["vector","raster","geojson","video","image"].includes(t.type)&&this._validate(za,`sources.${e}`,t,null,i))return;this.map&&this.map._collectResourceTiming&&(t.collectResourceTiming=!0);const s=Object.hasOwn(Kl,t.type)&&!Yl(t.type)?function(e,t,i,s){switch(t.type){case"raster-array":return new Ql(e,t,i,s);case"model":return new ec(e,t,i,s);default:return new Jl(e,t,i,s)}}(e,t,this.dispatcher,this):void 0,o=s||Xl(e,t,this.dispatcher,this);o.scope=this.scope;const r=e=>{e.setEventedParent(this,()=>({isSourceLoaded:this._isSourceCacheLoaded(e.id),source:e.serialize(),sourceId:e.id}))};r(o);const n=e=>{const t=(e===Ot.Symbol?"symbol:":e===Ot.FillExtrusion?"fill-extrusion:":"other:")+o.id,i=C(t,this.scope),s=this._sourceCaches[t]=new Ac(i,o,e);e===Ot.Symbol?this._symbolSourceCaches[o.id]=s:e===Ot.FillExtrusion?this._fillExtrusionSourceCaches[o.id]=s:this._otherSourceCaches[o.id]=s,s.onAdd(this.map)};n(Ot.Other),"vector"!==t.type&&"geojson"!==t.type||(n(Ot.Symbol),"vector"===t.type&&n(Ot.FillExtrusion)),o.onAdd&&o.onAdd(this.map),s&&(s._loader=()=>{(async function(e){if(Yl(e))return;const t=Kl[e];if(!t)throw new Error(`Unknown source type "${e}"`);const i=await t();i&&!Yl(e)&&function(e,t){$l[e]=t}(e,i)})(t.type).then(()=>{const i=Yl(t.type),n=this._otherSourceCaches[e];if(!n||n.getSource()!==o)return;if(!i)return void this.fire(new P(new Error(`Could not load module for source type "${t.type}".`)));const a=Xl(e,s._options,this.dispatcher,this);a.scope=this.scope,r(a),n.setSource(a),a.onAdd&&a.onAdd(this.map),this._changes.setDirty()})}),i.isInitialLoad||(this.mergeSources(),this._changes.setDirty())}removeSource(e){this._checkLoaded();const t=this.getOwnSource(e);if(!t)throw new Error("There is no source with this ID");for(const t in this._layers)if(this._layers[t].source===e)return this.fire(new P(new Error(`Source "${e}" cannot be removed while layer "${t}" is using it.`)));if(this.terrain&&this.terrain.scope===this.scope&&this.terrain.get().source===e)return this.fire(new P(new Error(`Source "${e}" cannot be removed while terrain is using it.`)));if(this.stylesheet.iconsets){const t=Object.entries(this.stylesheet.iconsets).find(([t,i])=>"source"===i.type&&i.source===e);if(t)return this.fire(new P(new Error(`Source "${e}" cannot be removed while iconset "${t[0]}" is using it.`)))}const i=this.getOwnSourceCaches(e);for(const e of i){const t=Qi(e.id);delete this._sourceCaches[t],this._changes.discardSourceCacheUpdate(e.id),e.fire(new M("data",{sourceDataType:"metadata",dataType:"source",sourceId:e.getSource().id})),e.setEventedParent(null),e.clearTiles()}return delete this._otherSourceCaches[e],delete this._symbolSourceCaches[e],delete this._fillExtrusionSourceCaches[e],this._hdCoverage&&delete this._hdCoverage.coverageSourceCaches[e],this.mergeSources(),t.setEventedParent(null),t.onRemove&&t.onRemove(this.map),this.dispatcher.broadcast("removeSource",{type:t.type,source:e,scope:t.scope}),this._changes.setDirty(),this}setGeoJSONSourceData(e,t){this._checkLoaded(),this.getOwnSource(e).setData(t),this._changes.setDirty()}getOwnSource(e){const t=this.getOwnSourceCache(e);return t&&t.getSource()}getOwnSources(){const e=[];for(const t in this._otherSourceCaches){const i=this.getOwnSourceCache(t);i&&e.push(i.getSource())}return e}areTilesLoaded(){const e=this._mergedSourceCaches;for(const t in e){const i=e[t];for(const e of i._tiles.values())if("loaded"!==e.state&&"errored"!==e.state)return!1}return!0}setLights(e){if(this._checkLoaded(),this._programPrecompiler&&this._programPrecompiler.reset(),!e)return delete this.ambientLight,void delete this.directionalLight;const t=this._getTransitionParameters();for(const i of e){if(this._validate(ka,"lights",i))return;switch(i.type){case"ambient":if(this.ambientLight){const e=this.ambientLight;e.set(i),e.updateTransitions(t)}else this.ambientLight=new fl(i,gl(),this.scope,this.options);break;case"directional":if(this.directionalLight){const e=this.directionalLight;e.set(i),e.updateTransitions(t)}else this.directionalLight=new fl(i,yl(),this.scope,this.options)}}const i=Object.assign(t,{worldview:this.map.getWorldview()}),s=new X(this.z||0,i);this.ambientLight&&this.ambientLight.recalculate(s),this.directionalLight&&this.directionalLight.recalculate(s),this._brightness=this.calculateLightsBrightness(),this.dispatcher.broadcast("upsertRenderParams",{brightness:this._brightness})}calculateLightsBrightness(){const e=this.directionalLight,t=this.ambientLight;if(!e||!t)return;const i=e=>.2126*(e[0]<=.03928?e[0]/12.92:Math.pow((e[0]+.055)/1.055,2.4))+.7152*(e[1]<=.03928?e[1]/12.92:Math.pow((e[1]+.055)/1.055,2.4))+.0722*(e[2]<=.03928?e[2]/12.92:Math.pow((e[2]+.055)/1.055,2.4)),s=e.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),o=e.properties.get("intensity"),r=e.properties.get("direction"),n=1-Ii(r.x,r.y,r.z)[2]/90,a=i(s)*o*n,l=t.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),c=t.properties.get("intensity"),h=i(l)*c;return Number(((a+h)/2).toFixed(6))}getBrightness(){return this._brightness}getLights(){if(!this.enable3dLights())return null;const e=[];return this.directionalLight&&e.push(this.directionalLight.get()),this.ambientLight&&e.push(this.ambientLight.get()),e}enable3dLights(){return!!this.ambientLight&&!!this.directionalLight}getFragmentStyle(e){if(null==e||""===e&&this.isRootStyle())return this;if(es(e)){const t=ts(e),i=this.fragments.find(({id:e})=>e===t);if(!i)return;const s=Qi(e);return i.style.getFragmentStyle(s)}{const t=this.fragments.find(({id:t})=>t===e);return t?t.style:void 0}}setFeaturesetSelectors(e){if(!e)return;const t=(e,t="")=>`${e}::${t}`;this._featuresetSelectors={};for(const i in e){const s={},o=this._featuresetSelectors[i]=[];for(const r of e[i].selectors){if(r.featureNamespace){const e=this.getOwnLayer(r.layer);if(!e){_(`Layer is undefined for selector: ${r.layer}`);continue}const o=t(e.source,e.sourceLayer);if(o in s&&s[o]!==r.featureNamespace){_(`"featureNamespace ${r.featureNamespace} of featureset ${i}'s selector is not associated to the same source, skip this selector`);continue}s[o]=r.featureNamespace}let e;if(r.properties)for(const t in r.properties){const i=v(r.properties[t]);"success"===i.result&&(e=e||{},e[t]=i.value)}o.push({layerId:r.layer,namespace:r.featureNamespace,properties:e,uniqueFeatureID:r._uniqueFeatureID})}}}getFeaturesetDescriptors(e){const t=this.getFragmentStyle(e);if(!t||!t.stylesheet.featuresets)return[];const i=[];for(const e in t.stylesheet.featuresets)i.push({featuresetId:e,importId:t.scope?t.scope:void 0});return i}getFeaturesetLayers(e,t){const i=this.getFragmentStyle(t),s=i.stylesheet.featuresets;if(!s||!s[e])return this.fire(new P(new Error(`The featureset '${e}' does not exist in the map's style and cannot be queried.`))),[];const o=[];for(const t of s[e].selectors){const e=i.getOwnLayer(t.layer);e&&o.push(e)}return o}getConfigProperty(e,t){const i=this.getFragmentStyle(e);if(!i)return null;const s=C(t,i.scope),o=i.options.get(s),r=o?o.value||o.default:null;return r?r.serialize():null}isIndoorEnabled(){return this._indoorEnabled}getIndoorSourceLayers(e,t){const i=C(e,t);return this._mergedIndoor[i]}setIndoorData(e,t){this.indoorManager&&this.indoorManager.setIndoorData(t)}updateIndoorDependentLayers(){this._updateLayers(this._dependentLayerIds(e=>e.isIndoorDependent)),this.map._styleDirty=!0,this.map.triggerRepaint()}setConfigProperty(e,t,i){const s=this.getFragmentStyle(e);if(!s)return;const o=s.stylesheet.schema;if(!o||!o[t])return;const r=is(i,o[t]);if("success"!==r.result)return void Md(this,r.value);const n=r.value.expression,a=C(t,s.scope),l=s.options.get(a);if(!l)return;let c;const{minValue:h,maxValue:d,stepValue:u,type:_,values:p}=o[t],f=is(o[t].default,o[t]);"success"===f.result&&(c=f.value.expression),c?(this.options.set(a,{...l,value:n,default:c,minValue:h,maxValue:d,stepValue:u,type:_,values:p}),this.updateConfigDependencies(t)):this.fire(new P(new Error(`No schema defined for the config option "${t}" in the "${e}" fragment.`)))}getConfig(e){const t=this.getFragmentStyle(e);if(!t)return null;const i=t.stylesheet.schema;if(!i)return null;const s={};for(const e in i){const i=C(e,t.scope),o=t.options.get(i),r=o?o.value||o.default:null;s[e]=r?r.serialize():null}return s}setConfig(e,t){const i=this.getFragmentStyle(e);i&&(i.updateConfig(t,i.stylesheet.schema),this.updateConfigDependencies())}getSchema(e){const t=this.getFragmentStyle(e);return t?t.stylesheet.schema:null}setSchema(e,t){const i=this.getFragmentStyle(e);i&&(i.stylesheet.schema=t,i.updateConfig(i._config,t),this.updateConfigDependencies())}updateConfig(e,t){if(this._config=e,e||t)if(t)for(const i in t){let s,o;const r=is(t[i].default,t[i]);if("success"===r.result&&(s=r.value.expression),e&&void 0!==e[i]){const s=is(e[i],t[i]);"success"===s.result&&(o=s.value.expression)}const{minValue:n,maxValue:a,stepValue:l,type:c,values:h}=t[i];if(s){const e=C(i,this.scope);this.options.set(e,{default:s,value:o,minValue:n,maxValue:a,stepValue:l,type:c,values:h})}else this.fire(new P(new Error(`No schema defined for config option "${i}".`)))}else this.fire(new P(new Error("Attempting to set config for a style without schema.")))}_updateLayers(e){for(const t of e){const e=this.getLayer(t);e&&(e.possiblyEvaluateVisibility(),e._dirty=!0,this._updateLayer(e),this._changes.setDirty())}}_dependentLayerIds(e){const t=[];for(const[i,s]of this._layerExpressionDependencies)e(s)&&t.push(i);return t}_updateEnvConfig(e="update"){const t="reset"===e?"resetConfig":"updateConfig";this.ambientLight&&this.ambientLight[t](this.options),this.directionalLight&&this.directionalLight[t](this.options),this.fog&&this.fog[t](this.options),this.snow&&this.snow[t](this.options),this.rain&&this.rain[t](this.options)}updateConfigDependencies(e){this._updateLayers(this._dependentLayerIds(t=>t.hasConfigDependency(e))),this._updateEnvConfig(),this.forEachFragmentStyle(e=>{const t=e._styleColorTheme.colorThemeOverride?e._styleColorTheme.colorThemeOverride:e._styleColorTheme.colorTheme;if(t){const i=e._evaluateColorThemeData(t);(!e._styleColorTheme.lut&&""!==i||e._styleColorTheme.lut&&i!==e._styleColorTheme.lut.data)&&e.setColorTheme(t)}}),this._updateIndoorEnabled(),this._changes.setDirty()}addLayer(e,t,i={}){this._checkLoaded();const s=e.id;if(this._layers[s])return void this.fire(new P(new Error(`Layer with id "${s}" already exists on this map`)));let o;if("custom"===e.type){if(Md(this,ss(e)))return;o=os(e,this.scope,this._styleColorTheme.lut,this.options)}else{if("object"==typeof e.source&&(this.addSource(s,e.source),e=Ji(e),e=Object.assign(e,{source:s})),this._validate(ja,`layers.${s}`,e,{arrayIndex:-1},i))return;o=os(e,this.scope,this._styleColorTheme.lut,this.options),this._validateLayer(o),o.setEventedParent(this,{layer:{id:s}})}this._layerExpressionDependencies.set(o.fqid,new kn(o));let r=this._order.length;if(t){const e=this._order.indexOf(t);if(-1===e)return void this.fire(new P(new Error(`Layer with id "${t}" does not exist on this map.`)));o.slot&&o.slot!==this._layers[t].slot?_(`Layer with id "${t}" has a different slot. Layers can only be rearranged within the same slot.`):r=e}this._order.splice(r,0,s),this._handleLayerOrderChange(),this._layers[s]=o;const n=this.getOwnLayerSourceCache(o),a=!!this.directionalLight&&this.directionalLight.shadowsEnabled();n&&o.canCastShadows()&&a&&(n.castsShadows=!0);const l=this._changes.getRemovedLayer(o);if(l&&o.source&&n&&"custom"!==o.type){this._changes.discardLayerRemoval(o);const e=C(o.source,o.scope);l.type!==o.type?this._changes.updateSourceCache(e,"clear"):(this._changes.updateSourceCache(e,"reload"),n.pause())}this._updateLayer(o),o.onAdd&&o.onAdd(this.map),o.scope=this.scope,this.mergeLayers()}moveLayer(e,t){this._checkLoaded();const i=this._checkLayer(e);if(!i)return;if(e===t)return;const s=this._order.indexOf(e);this._order.splice(s,1);let o=this._order.length;if(t){const e=this._order.indexOf(t);if(-1===e)return void this.fire(new P(new Error(`Layer with id "${t}" does not exist on this map.`)));i.slot&&i.slot!==this._layers[t].slot?_(`Layer with id "${t}" has a different slot. Layers can only be rearranged within the same slot.`):o=e}this._order.splice(o,0,e),this._changes.setDirty(),this._handleLayerOrderChange(),this.mergeLayers()}removeLayer(e){this._checkLoaded();const t=this._checkLayer(e);if(!t)return;t.setEventedParent(null);const i=this._order.indexOf(e);this._order.splice(i,1),delete this._layers[e],this._changes.setDirty(),this._handleLayerOrderChange(),this._layerExpressionDependencies.delete(t.fqid),this._changes.removeLayer(t);const s=this.getOwnLayerSourceCache(t);if(s&&s.castsShadows){let e=!1;for(const i in this._layers)if(this._layers[i].source===t.source&&this._layers[i].canCastShadows()){e=!0;break}s.castsShadows=e}t.onRemove&&t.onRemove(this.map),this.mergeLayers()}getOwnLayer(e){return this._layers[e]}hasLayer(e){return e in this._mergedLayers}hasLayerType(e){for(const t in this._layers)if(this._layers[t].type===e)return!0;return!1}setLayerZoomRange(e,t,i){this._checkLoaded();const s=this._checkLayer(e);s&&(s.minzoom===t&&s.maxzoom===i||(null!=t&&(s.minzoom=t),null!=i&&(s.maxzoom=i),this._updateLayer(s)))}getSlots(){return this._checkLoaded(),this._mergedSlots}setSlot(e,t){this._checkLoaded();const i=this._checkLayer(e);i&&i.slot!==t&&(i.slot=t,this._updateLayer(i))}setFilter(e,t,i={}){this._checkLoaded();const s=this._checkLayer(e);if(!s)return;if(rs(s.filter,t))return;const o=this._layerExpressionDependencies.get(s.fqid);if(null==t)return s.filter=void 0,o&&o.invalidateFilter(),void this._updateLayer(s);this._validate(Ga,`layers.${s.id}.filter`,t,{layerType:s.type},i)||(s.filter=Ji(t),o&&o.invalidateFilter(),this._updateLayer(s))}getFilter(e){const t=this._checkLayer(e);if(t)return Ji(t.filter)}setLayoutProperty(e,t,i,s={}){this._checkLoaded();const o=this._checkLayer(e);if(o&&!rs(o.getLayoutProperty(t),i)){if(null!=i&&(!s||!1!==s.validate)&&Md(o,Za.call(Oa,{key:`layers.${e}.layout.${t}`,layerType:o.type,objectKey:t,value:i,styleSpec:y,style:{glyphs:!0,sprite:!0}})))return;o.setLayoutProperty(t,i),this._updateLayer(o)}}getLayerProperty(e,t){const i=this._checkLayer(e);if(i){switch(t){case"minzoom":return i.minzoom;case"maxzoom":return i.maxzoom;case"filter":return this.getFilter(e);case"slot":return i.slot;case"appearances":return i.getAppearances().map(e=>e.serialize())}return i.isPaintProperty(t)?this.getPaintProperty(e,t):this.getLayoutProperty(e,t)}}setLayerProperty(e,t,i,s={}){this._checkLoaded();const o=this._checkLayer(e);if(o){switch(t){case"appearances":return o.setAppearances(i),void this._updateLayer(o);case"minzoom":return this.setLayerZoomRange(e,i);case"maxzoom":return this.setLayerZoomRange(e,null,i);case"filter":return this.setFilter(e,i,s);case"slot":return this.setSlot(e,i)}o.isPaintProperty(t)?this.setPaintProperty(e,t,i,s):this.setLayoutProperty(e,t,i,s)}}getLayoutProperty(e,t){const i=this._checkLayer(e);if(i)return i.getLayoutProperty(t)}setPaintProperty(e,t,i,s={}){this._checkLoaded();const o=this._checkLayer(e);o&&(rs(o.getPaintProperty(t),i)||(null==i||s&&!1===s.validate||!Md(o,qa.call(Oa,{key:`layers.${e}.paint.${t}`,layerType:o.type,objectKey:t,value:i,styleSpec:y})))&&(o.setPaintProperty(t,i)&&this._updateLayer(o),this._changes.updatePaintProperties(o)))}getPaintProperty(e,t){const i=this._checkLayer(e);if(i)return i.getPaintProperty(t)}setFeatureState(e,t){if(this._checkLoaded(),"target"in e){if("featuresetId"in e.target){const{featuresetId:i,importId:s}=e.target,o=this.getFragmentStyle(s),r=o.getFeaturesetLayers(i);for(const{source:i,sourceLayer:s}of r)o.setFeatureState({id:e.id,source:i,sourceLayer:s},t)}else if("layerId"in e.target){const i=this._resolveLayerFragment(e.target.layerId);i?.fragment.setFeatureState({id:e.id,source:i.layer.source,sourceLayer:i.layer.sourceLayer},t)}return}const i=e.source,s=e.sourceLayer,o=this._checkSource(i);if(!o)return;const r=o.type;if("geojson"===r&&s)return void this.fire(new P(new Error("GeoJSON sources cannot have a sourceLayer parameter.")));if("vector"===r&&!s)return void this.fire(new P(new Error("The sourceLayer parameter must be provided for vector source types.")));void 0===e.id&&this.fire(new P(new Error("The feature id parameter must be provided.")));const n=this.getOwnSourceCaches(i);for(const i of n)i.setFeatureState(s,e.id,t)}removeFeatureState(e,t){if(this._checkLoaded(),"target"in e){if("featuresetId"in e.target){const{featuresetId:i,importId:s}=e.target,o=this.getFragmentStyle(s),r=o.getFeaturesetLayers(i);for(const{source:i,sourceLayer:s}of r)o.removeFeatureState({id:e.id,source:i,sourceLayer:s},t)}else if("layerId"in e.target){const i=this._resolveLayerFragment(e.target.layerId);i?.fragment.removeFeatureState({id:e.id,source:i.layer.source,sourceLayer:i.layer.sourceLayer},t)}return}const i=e.source,s=this._checkSource(i);if(!s)return;const o=s.type,r="vector"===o?e.sourceLayer:void 0;if("vector"===o&&!r)return void this.fire(new P(new Error("The sourceLayer parameter must be provided for vector source types.")));if(t&&"string"!=typeof e.id&&"number"!=typeof e.id)return void this.fire(new P(new Error("A feature id is required to remove its specific state property.")));const n=this.getOwnSourceCaches(i);for(const i of n)i.removeFeatureState(r,e.id,t)}getFeatureState(e){if(this._checkLoaded(),"target"in e){let t;if("featuresetId"in e.target){const{featuresetId:i,importId:s}=e.target,o=this.getFragmentStyle(s),r=o.getFeaturesetLayers(i);for(const{source:i,sourceLayer:s}of r){const r=o.getFeatureState({id:e.id,source:i,sourceLayer:s});if(r&&!t)t=r;else if(!rs(t,r))return void this.fire(new P(new Error("The same feature id exists in multiple sources in the featureset, but their feature states are not consistent through the sources.")))}}else if("layerId"in e.target){const i=this._resolveLayerFragment(e.target.layerId);t=i?.fragment.getFeatureState({id:e.id,source:i.layer.source,sourceLayer:i.layer.sourceLayer})}return t}const t=e.source,i=e.sourceLayer,s=this._checkSource(t);if(s){if("vector"!==s.type||i)return void 0===e.id&&this.fire(new P(new Error("The feature id parameter must be provided."))),this.getOwnSourceCaches(t)[0].getFeatureState(i,e.id);this.fire(new P(new Error("The sourceLayer parameter must be provided for vector source types.")))}}resetFeatureStates(e){if(this._checkLoaded(),"featuresetId"in e){const{featuresetId:t,importId:i}=e,s=this.getFragmentStyle(i);if(!s)return;const o=s.getFeaturesetLayers(t);for(const{source:e,sourceLayer:t}of o)s.removeFeatureState({source:e,sourceLayer:t})}else{const t=this._resolveLayerFragment(e.layerId);t?.fragment.removeFeatureState({source:t.layer.source,sourceLayer:t.layer.sourceLayer})}}setTransition(e){return this.stylesheet.transition={...this.stylesheet.transition,...e},this.transition=this.stylesheet.transition,this}getTransition(){return{...this.stylesheet.transition}}setWorldview(e){e!==this._worldview&&(this._worldview=e,this.dispatcher.broadcast("upsertRenderParams",{worldview:this._worldview}),this.reloadSources())}serialize(){this._checkLoaded();const e=this.getTerrain(),t=e&&this.terrain&&this.terrain.scope===this.scope?e:this.stylesheet.terrain;return ns({version:this.stylesheet.version,name:this.stylesheet.name,metadata:this.stylesheet.metadata,fragment:this.stylesheet.fragment,iconsets:this.stylesheet.iconsets,featuresets:this.stylesheet.featuresets,imports:this._serializeImports(),schema:this.stylesheet.schema,camera:this.stylesheet.camera,light:this.stylesheet.light,lights:this.stylesheet.lights,terrain:t,fog:this.stylesheet.fog,snow:this.stylesheet.snow,rain:this.stylesheet.rain,indoor:this.stylesheet.indoor,center:this.stylesheet.center,"color-theme":this.stylesheet["color-theme"],zoom:this.stylesheet.zoom,bearing:this.stylesheet.bearing,pitch:this.stylesheet.pitch,sprite:this.stylesheet.sprite,glyphs:this.stylesheet.glyphs,transition:this.stylesheet.transition,projection:this.stylesheet.projection,sources:this._serializeSources(),layers:this._serializeLayers(this._order)},e=>void 0!==e)}_updateFilteredLayers(e){for(const t of Object.values(this._mergedLayers))e(t)&&this._updateLayer(t)}_updateLayer(e){this._changes.updateLayer(e);const t=this.getLayerSourceCache(e),i=e.sourceFqid,s=this._changes.getUpdatedSourceCaches();e.source&&!s[i]&&t&&"raster"!==t.getSource().type&&(this._changes.updateSourceCache(i,"reload"),t.pause()),e.invalidateCompiledFilter()}_flattenAndSortRenderedFeatures(e){const t=e=>this._mergedLayers[e].is3D(!!this.terrain),i=this.order,s={},o=[];for(let r=i.length-1;r>=0;r--){const n=i[r];if(t(n)){s[n]=r;for(const t of e){const e=t[n];if(e)for(const t of e)o.push(t)}}}o.sort((e,t)=>t.intersectionZ-e.intersectionZ);const r=[];for(let n=i.length-1;n>=0;n--){const a=i[n];if(t(a))for(let e=o.length-1;e>=0;e--){const t=o[e].feature;if(t.layer&&s[t.layer.id]<n)break;r.push(t),o.pop()}else for(const t of e){const e=t[a];if(e)for(const t of e)r.push(t.feature)}}return r}queryRasterValue(e,t,i){const s=this.getOwnSource(e);return s?"raster-array"!==s.type?(this.fire(new P(new Error('queryRasterValue support only "raster-array" sources.'))),Promise.resolve(null)):s.queryRasterArrayValue(t,i):(this.fire(new P(new Error(`Source with id "${e}" does not exist in the style.`))),Promise.resolve(null))}queryRenderedFeatures(e,t,i){let s;t&&!Array.isArray(t)&&t.filter&&(this._validate(Ga,"queryRenderedFeatures.filter",t.filter,null,t),s=dt(t.filter));const o={},r=e=>{if(Fd.has(e.type))return;const t=this.getOwnLayerSourceCache(e),i=o[t.id]=o[t.id]||{sourceCache:t,layers:{},has3DLayers:!1};e.is3D(!!this.terrain)&&(i.has3DLayers=!0),i.layers[e.fqid]=i.layers[e.fqid]||{styleLayer:e,targets:[]},i.layers[e.fqid].targets.push({filter:s})};if(t&&t.layers){if(!Array.isArray(t.layers))return this.fire(new P(new Error("parameters.layers must be an Array."))),[];for(const e of t.layers){const t=this._layers[e];if(!t)return this.fire(new P(new Error(`The layer '${e}' does not exist in the map's style and cannot be queried for features.`))),[];r(t)}}else for(const e in this._layers)r(this._layers[e]);const n=this._queryRenderedFeatures(e,o,i),a=this._flattenAndSortRenderedFeatures(n),l=[];for(const e of a)as(e.layer.id)===this.scope&&l.push(e);return l}queryRenderedFeatureset(e,t,i){let s;t&&!Array.isArray(t)&&t.filter&&(this._validate(Ga,"queryRenderedFeatures.filter",t.filter,null,t),s=dt(t.filter));const o="mock",r=[];if(t&&t.target)r.push({...t,targetId:o,filter:s});else{const e=this.getFeaturesetDescriptors();for(const t of e)r.push({targetId:o,filter:s,target:t});for(const{style:e}of this.fragments){const t=e.getFeaturesetDescriptors();for(const e of t)r.push({targetId:o,filter:s,target:e})}}const n=this.queryRenderedTargets(e,r,i),a=[],l=new Set;for(const e of n)for(const t of e.variants[o])ic(t,e,l)||a.push(new ls(e,t));return a}queryRenderedTargets(e,t,i){const s={},o=(e,t,i,o)=>{const r=s[t.id]=s[t.id]||{sourceCache:t,layers:{},has3DLayers:!1};if(r.layers[e.fqid]=r.layers[e.fqid]||{styleLayer:e,targets:[]},e.is3D(!!this.terrain)&&(r.has3DLayers=!0),!o)return i.uniqueFeatureID=!1,void r.layers[e.fqid].targets.push(i);r.layers[e.fqid].targets.push({...i,namespace:o.namespace,properties:o.properties,uniqueFeatureID:o.uniqueFeatureID})};for(const e of t)if("featuresetId"in e.target){const{featuresetId:t,importId:i}=e.target,s=this.getFragmentStyle(i);if(!s||!s._featuresetSelectors)continue;const r=s._featuresetSelectors[t];if(!r){this.fire(new P(new Error(`The featureset '${t}' does not exist in the map's style and cannot be queried for features.`)));continue}for(const t of r){const i=s.getOwnLayer(t.layerId);i&&!Fd.has(i.type)&&o(i,s.getOwnLayerSourceCache(i),e,t)}}else if("layerId"in e.target){const{layerId:t}=e.target,i=this.getLayer(t);if(!i||Fd.has(i.type))continue;o(i,this.getLayerSourceCache(i),e)}const r=this._queryRenderedFeatures(e,s,i);return this._flattenAndSortRenderedFeatures(r)}_queryRenderedFeatures(e,t,i){const s=[],o=!!this.map._showQueryGeometry,r=zl.createFromScreenPoints(e,i);for(const e in t){const n=sc(r,t[e],this._availableImages,i,o,this.getActualScope());Object.keys(n).length&&s.push(n)}if(this.placement)for(const e in t){if(t[e].sourceCache._renderSourceType!==Ot.Symbol)continue;const i=oc(r.screenGeometry,t[e],this._availableImages,this.placement.collisionIndex,this.placement.retainedQueryData,this.map.getWorldview());Object.keys(i).length&&s.push(i)}return s}querySourceFeatures(e,t){const i=t&&t.filter;i&&this._validate(Ga,"querySourceFeatures.filter",i,null,t);let s=[];const o=this.getOwnSourceCaches(e);for(const e of o)s=s.concat(rc(e,t));return s}getFlatLight(){return this.light.getLight()}setFlatLight(e,t,i={}){this._checkLoaded();const s=this.light.getLight();let o=!1;for(const t in e)if(!rs(e[t],s[t])){o=!0;break}if(!o)return;const r=this._getTransitionParameters();this.light.setLight(e,t,i),this.light.updateTransitions(r)}hasTerrain(){return!!this.terrain&&this.terrain.drapeRenderMode===Ja.elevated}getTerrain(){return this.hasTerrain()?this.terrain.get():null}_startLiteLoad(){if(void 0!==this._drapingLoaded)return;this._drapingLoaded=!1;const e=!!Al.loaded;(null!==Ll||(Ll=import("./lite.main.js").then(({Lite:e})=>{Object.assign(Al,e)}).catch(()=>{Ll=null,_("Could not load Lite module.")})),Ll).then(()=>{this._drapingLoaded=!0,this.map._removed||0===this.dispatcher.actors.length||(e?this.map.triggerRepaint():(this.applyProjectionUpdate(),this.map._update(!1)))})}_getRasterMaskUser(e,t){for(const i of this._order){const s=this._layers[i];if("raster"!==s.type||!s.getPaintProperty("raster-mask"))continue;const o=s.getPaintProperty("raster-mask-import");if("import"===t?o===e:!o&&s.getPaintProperty("raster-mask")===e)return i}}_startRasterArrayLoad(){void 0===this._rasterArrayLoaded&&(this._rasterArrayLoaded=!1,Ol().then(()=>{this._rasterArrayLoaded=!0,this.map._removed||this.map.triggerRepaint()}))}setTerrainForDraping(){this._startLiteLoad(),this.setTerrain({source:"",exaggeration:0},Ja.deferred)}checkCanvasFingerprintNoise(){void 0===this.disableElevatedTerrain&&(this.disableElevatedTerrain=T.hasCanvasFingerprintNoise(),this.disableElevatedTerrain&&_("Terrain and hillshade are disabled because of Canvas2D limitations when fingerprinting protection is enabled (e.g. in private browsing mode)."))}setTerrain(e,t=Ja.elevated){if(this._checkLoaded(),!e)return this.terrainSetForDrapingOnly()||(delete this.terrain,this.map.transform.projection.requiresDraping&&this.setTerrainForDraping()),t===Ja.deferred&&delete this.terrain,null===e?this.stylesheet.terrain=null:delete this.stylesheet.terrain,this._force3DLayerUpdate(),void(this._markersNeedUpdate=!0);this.checkCanvasFingerprintNoise();let i=e;const s=!("source"in e)||null==e.source;if(t===Ja.elevated){if(this._startLiteLoad(),this.disableElevatedTerrain)return;if("source"in i&&"object"==typeof i.source){const e="terrain-dem-src";this.addSource(e,i.source),i=Ji(i),i=Object.assign(i,{source:e})}const e={...i},t={};if(this.terrain&&s){e.source=this.terrain.get().source;const i=this.terrain?this.getFragmentStyle(this.terrain.scope):null;i&&(t.style=i.serialize())}if(this._validate(Ba,"terrain",e,t))return}if(!this.terrain||this.terrain.scope!==this.scope&&!s||this.terrain&&t!==this.terrain.drapeRenderMode){if(!i)return;this._createTerrain(i,t),this.fire(new M("data",{dataType:"style"}))}else{const t=this.terrain,s=t.get();for(const e of Object.keys(y.terrain))!Object.hasOwn(i,e)&&y.terrain[e].default&&(i[e]=y.terrain[e].default);for(const i in e)if(!rs(e[i],s[i])){t.set(e,this.options),this.stylesheet.terrain=e;const i=this._getTransitionParameters({duration:0});t.updateTransitions(i),this.fire(new M("data",{dataType:"style"}));break}}this.mergeTerrain(),this.updateDrapeFirstLayers(),this._markersNeedUpdate=!0}_createFog(e){const t=this.fog=new il(e,this.map.transform,this.scope,this.options);this.stylesheet.fog=t.get();const i=this._getTransitionParameters({duration:0});t.updateTransitions(i)}_createSnow(e){const t=this.snow=new rl(e,this.map.transform,this.scope,this.options);this.stylesheet.snow=t.get();const i=this._getTransitionParameters({duration:0});t.updateTransitions(i)}_createRain(e){const t=this.rain=new nl(e,this.map.transform,this.scope,this.options);this.stylesheet.rain=t.get();const i=this._getTransitionParameters({duration:0});t.updateTransitions(i)}_updateMarkersOpacity(){0!==this.map._markers.length&&this.map._requestDomTask(()=>{for(const e of this.map._markers)e._evaluateOpacity()})}getFog(){return this.fog?this.fog.get():null}setFog(e){if(this._checkLoaded(),e)if(this.fog){const t=this.fog;if(!rs(t.get(),e)){t.set(e,this.options),this.stylesheet.fog=t.get();const i=this._getTransitionParameters({duration:0});t.updateTransitions(i)}}else this._createFog(e);else delete this.fog,delete this.stylesheet.fog;this._markersNeedUpdate=!0,this._programPrecompiler&&this._programPrecompiler.reset()}getSnow(){return this.snow?this.snow.get():null}setSnow(e){if(this._checkLoaded(),!e)return delete this.snow,void delete this.stylesheet.snow;if(this.snow){const t=this.snow;if(!rs(t.get(),e)){t.set(e,this.options),this.stylesheet.snow=t.get();const i=this._getTransitionParameters({duration:0});t.updateTransitions(i)}}else this._createSnow(e);this._markersNeedUpdate=!0}getRain(){return this.rain?this.rain.get():null}setRain(e){if(this._checkLoaded(),!e)return delete this.rain,void delete this.stylesheet.rain;if(this.rain){const t=this.rain;if(!rs(t.get(),e)){t.set(e,this.options),this.stylesheet.rain=t.get();const i=this._getTransitionParameters({duration:0});t.updateTransitions(i)}}else this._createRain(e);this._markersNeedUpdate=!0}_reloadColorTheme(){const e=()=>{for(const e in this._layers)this._layers[e].lut=this._styleColorTheme.lut;for(const e in this._sourceCaches)this._sourceCaches[e].clearTiles()},t=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(!t)return this._styleColorTheme.lut=null,void e();const i=this._evaluateColorThemeData(t);this._loadColorTheme(i).then(()=>{this.fire(new M("colorthemeset")),e()}).catch(e=>{_(`Couldn't set color theme: ${e}`)})}setColorTheme(e){this._checkLoaded(),this._styleColorTheme.colorThemeOverride&&_("Note: setColorTheme is called on a style with a color-theme override, the passed color-theme won't be visible."),this._styleColorTheme.colorTheme=e,this._reloadColorTheme()}setImportColorTheme(e,t){const i=this.getFragmentStyle(e);i&&(i._styleColorTheme.colorThemeOverride=t,i._reloadColorTheme())}_getTransitionParameters(e){return{now:T.now(),transition:Object.assign(this.transition,e)}}updateDrapeFirstLayers(){if(!this.terrain)return;const e=[],t=[];for(const i of this._mergedOrder)this.isLayerDraped(this._mergedLayers[i])?e.push(i):t.push(i);this._drapedFirstOrder=[],this._drapedFirstOrder.push(...e),this._drapedFirstOrder.push(...t)}_createTerrain(e,t){const i=this.terrain=new Qa(e,t,this.scope,this.options,this.map.getWorldview());t===Ja.elevated&&(this.stylesheet.terrain=e),this.mergeTerrain(),this.updateDrapeFirstLayers(),this._force3DLayerUpdate();const s=this._getTransitionParameters({duration:0});i.updateTransitions(s);const o=new X(this.z||0,{...s,worldview:this.map.getWorldview()});i.recalculate(o)}_force3DLayerUpdate(){for(const e in this._layers){const t=this._layers[e];"fill-extrusion"===t.type&&this._updateLayer(t)}}_forceSymbolLayerUpdate(){for(const e in this._layers){const t=this._layers[e];"symbol"===t.type&&this._updateLayer(t)}}_validate(e,t,i,s,o={}){if(o&&!1===o.validate)return!1;const r={...this.serialize()};return Md(this,e.call(Oa,{key:t,style:r,value:i,styleSpec:y,...s}))}_remove(){this._programPrecompiler&&(this._programPrecompiler.reset(),this._programPrecompiler=null),this._request&&(this._request.cancel(),this._request=null),this._spriteRequest&&(this._spriteRequest.abort(),this._spriteRequest=null);for(const e in this._mergedLayers)this._mergedLayers[e].setEventedParent(null);for(const e in this._mergedSourceCaches){const t=this._mergedSourceCaches[e];t.clearTiles(),t.setEventedParent(null);const i=t.getSource();i&&i.onRemove&&i.onRemove(this.map)}this.imageManager.removeScope(this.scope),this.isRootStyle()?this.imageManager.imageAtlasCache.clear():this.imageManager.imageAtlasCache.removeScope(this.scope),this.setEventedParent(null),delete this.fog,delete this.snow,delete this.rain,delete this.terrain,delete this.ambientLight,delete this.directionalLight,this.indoorManager&&this.indoorManager.destroy(),this.isRootStyle()&&(this.imageManager.setEventedParent(null),this.modelManager.setEventedParent(null),this.modelManager.destroy(),this.dispatcher.remove())}clearSource(e){const t=this.getSourceCaches(e);for(const e of t)e.clearTiles()}clearSources(){for(const e in this._mergedSourceCaches)this._mergedSourceCaches[e].clearTiles()}clearLayers(){for(const e in this._mergedLayers){const t=this._mergedLayers[e];t._clear&&t._clear()}}reloadSource(e){const t=this.getSourceCaches(e);for(const e of t)e.resume(),e.reload()}reloadSources(){for(const e of this.getSources())e.reload&&e.reload()}reloadModels(){this.modelManager.reloadModels(""),this.forEachFragmentStyle(e=>{e.modelManager.reloadModels(e.scope)})}updateSources(e){let t;this.directionalLight&&(t=jh(this.directionalLight));const i=new Set,s=new Set,o=new Set;for(const e in this._mergedLayers){const t=this._mergedLayers[e];"building"===t.type?i.add(t.source):"raster"===t.type&&t.paint&&"ground"===t.paint.get("raster-elevation-reference")&&o.add(t.source),t.hasElevation()&&!s.has(t.source)&&s.add(t.source)}this.updateFrcCoverageFadeRange();for(const r in this._mergedSourceCaches){const n=this._mergedSourceCaches[r],a=s.has(n._source.id);n._isRasterElevatedOverTerrain=o.has(n._source.id),i.has(n._source.id)&&(n._source.reparseOverscaled=!1),n.update(e,void 0,void 0,t,a)}this.updateFrcCoverage(),this.updateElevationCoverage()}_reloadSources(){for(const e in this._sourceCaches){const t=this._sourceCaches[e];t.resume(),t.reload()}}updateFrcCoverageFadeRange(){this.map.painter&&Il.updateFrcCoverageFadeRange&&Il.updateFrcCoverageFadeRange(this,this.map.painter)}updateFrcCoverage(){this._hdCoverage&&Il.updateFrcCoverage&&Il.updateFrcCoverage(this,this._hdCoverage)}updateElevationCoverage(){this.isRootStyle()&&Il.setupAndUpdateElevationCoverage&&Il.setupAndUpdateElevationCoverage(this)}_handleLayerOrderChange(){this._requestFullLabelPlacement(),this.fire(new M("neworder"))}_requestFullLabelPlacement(){this.pauseablePlacement||(this.pauseablePlacement=new Rh),this.pauseablePlacement.requestFullPlacement()}_setLabelPlacementStale(){this.placement&&this.placement.setStale()}_updatePlacement(e,t,i,s,o,r){this.pauseablePlacement||(this.pauseablePlacement=new Rh);let n=!1,a=!1;const l={},c={},h="global"===r,d=h?[]:this._mergedOrder;let u=!1;h&&(u=this._driveGlobalPlacement(e,o,i,t));for(const t of d){const i=this._mergedLayers[t];if("symbol"!==i.type)continue;const s=C(i.source,i.scope);let o=l[s];if(!o){const e=this.getLayerSourceCache(i);if(!e)continue;const t=e.getRenderableIds(!0).map(t=>e.getTileByID(t));c[s]=t.slice(),o=l[s]=t.sort((e,t)=>t.tileID.overscaledZ-e.tileID.overscaledZ||(e.tileID.isLessThan(t.tileID)?-1:1))}const r=this.crossTileSymbolIndex.addLayer(i,o,e.center.lng,e.projection);n=n||r}this.crossTileSymbolIndex.pruneUnusedLayers(d);const _=Boolean(this.placement&&!e.equals(this.placement.transform)),p=Boolean(this.placement&&(0!==this.placement.lastReplacementSourceUpdateTime&&!o||this.placement.lastReplacementSourceUpdateTime!==o.updateTime)),f=_||p||n,m=(f||this.pauseablePlacement.isStale())&&0===i,g=this.pauseablePlacement.isDone()&&!this.placement.stillRecent(T.now(),e.zoom)&&0!==i;if((this.pauseablePlacement.isFullPlacementRequested()||!this.pauseablePlacement.placement||m||g)&&(this.pauseablePlacement=this.pauseablePlacement.startNewPlacement(e,d,t,i,s,this.placement,this.fog&&e.projection.supportsFog?this.fog.state:null,this._buildingIndex),this.map.painter)){const t=this.map.painter.maxFrontCutoffRawStart;if(t>0){const i=180*e.pitch/Math.PI;if(i>=15){const e=Math.min(1,Math.max(0,(i-15)/5)),s=e*e*(3-2*e);this.pauseablePlacement.placement.frontCutoffStart=-.5*(1-s)+t*s}}}if(this.pauseablePlacement.isDone()?f&&0!==i&&this.pauseablePlacement.setStale():(this.pauseablePlacement.continuePlacement(d,this._mergedLayers,l,c,this.map.painter.scaleFactor),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(T.now()),a=!0),n&&this.pauseablePlacement.setStale()),a||n){this._buildingIndex.onNewFrame(e.zoom);for(let e=0;e<d.length;e++){const i=this._mergedLayers[d[e]];if("symbol"!==i.type)continue;if("none"===i.visibility)continue;const s=this.isLayerClipped(i);this.placement.updateLayerOpacities(i,l[C(i.source,i.scope)],e,s?o:null,t,this.map.painter.scaleFactor)}}return!this.pauseablePlacement.isDone()||this.placement.isStale()||this.placement.hasTransitions(T.now())||u}_driveGlobalPlacement(e,t,i,s){if(0===e.width||0===e.height)return!1;this.globalPlacement||(this.globalPlacement=new Vh);const o=this.globalPlacement;o.startPlacement(T.now(),e.width,e.height,s),this._buildingIndex.onNewFrame(e.zoom);const r=this.fog&&e.projection.supportsFog?this.fog.state:null;if(this._groupOrdersVersion!==this._mergedOrderVersion||!this._groupOrders){const e=new Map;for(let t=0;t<this._mergedOrder.length;t++){const i=this._mergedLayers[this._mergedOrder[t]];"placement-group"===i.type&&e.set(i.fqid,cs(t))}this._groupOrders=e,this._groupOrdersVersion=this._mergedOrderVersion}const n=this._groupOrders,a=[Ae(e.center.lng),Pe(e.center.lat)],l={globalPlacement:o,transform:e,buildingIndex:this._buildingIndex,fogState:r,groupOrders:n,replacementSource:t,mercatorCenter:a,fadeDuration:i},c={};let h=!1;for(let e=0;e<this._mergedOrder.length;e++){const t=this._mergedLayers[this._mergedOrder[e]];if("symbol"!==t.type)continue;const i=this.getLayerSourceCache(t);if(!i)continue;const s=C(t.source,t.scope);let o=c[s];o||(o=c[s]=i.getRenderableIds(!0).map(e=>i.getTileByID(e)));const r=this.isLayerClipped(t);t.placeSymbols(l,o,e,i,r);for(const e of o){const i=e.getBucket(t);i&&t.fqid===i.layerIds[0]&&i.hasActiveFade()&&(h=!0)}}return o.finishPlacementRun(i),h}_releaseSymbolFadeTiles(){for(const e in this._mergedSourceCaches)this._mergedSourceCaches[e].releaseSymbolFadeTiles()}addImport(e,t){if(this._checkLoaded(),new Set(["__proto__","constructor","prototype"]).has(e.id))return void this.fire(new P(new Error(`Import id can't be "${e.id}".`)));const i=this.stylesheet.imports=this.stylesheet.imports||[];if(-1!==i.findIndex(({id:t})=>t===e.id))return void this.fire(new P(new Error(`Import with id '${e.id}' already exists in the map's style.`)));if(!t)return i.push(e),this._loadImports([e],!0);const s=i.findIndex(({id:e})=>e===t);return-1===s&&this.fire(new P(new Error(`Import with id "${t}" does not exist on this map.`))),this.stylesheet.imports=i.slice(0,s).concat(e).concat(i.slice(s)),this._loadImports([e],!0,t)}updateImport(e,t){this._checkLoaded();const i=this.stylesheet.imports||[],s=this.getImportIndex(e);return-1===s?this:"string"==typeof t?(this.setImportUrl(e,t),this):(t.url&&t.url!==i[s].url&&this.setImportUrl(e,t.url),rs(t.config,i[s].config)||this.setImportConfig(e,t.config,t.data.schema),rs(t.data,i[s].data)||this.setImportData(e,t.data),this)}moveImport(e,t){this._checkLoaded();let i=this.stylesheet.imports||[];const s=this.getImportIndex(e);if(-1===s)return this;const o=this.getImportIndex(t);if(-1===o)return this;const r=i[s],n=this.fragments[s];return i=i.filter(({id:t})=>t!==e),this.fragments=this.fragments.filter(({id:t})=>t!==e),this.stylesheet.imports=i.slice(0,o).concat(r).concat(i.slice(o)),this.fragments=this.fragments.slice(0,o).concat(n).concat(this.fragments.slice(o)),this.mergeLayers(),this}setImportUrl(e,t){this._checkLoaded();const i=this.stylesheet.imports||[],s=this.getImportIndex(e);if(-1===s)return this;i[s].url=t;const o=this.fragments[s];return o.style=this._createFragmentStyle(i[s]),o.style.on("style.import.load",()=>this.mergeAll()),o.style.loadURL(t),this}setImportData(e,t){this._checkLoaded();const i=this.getImportIndex(e),s=this.stylesheet.imports||[];return-1===i?this:t?(this.fragments[i].style.setState(t),this._reloadImports(),this):(delete s[i].data,this.setImportUrl(e,s[i].url))}setImportConfig(e,t,i){this._checkLoaded();const s=this.getImportIndex(e),o=this.stylesheet.imports||[];if(-1===s)return this;t?o[s].config=t:delete o[s].config;const r=this.fragments[s];i&&r.style.stylesheet&&(r.style.stylesheet.schema=i);const n=r.style.stylesheet&&r.style.stylesheet.schema;return r.config=t,r.style.updateConfig(t,n),this.updateConfigDependencies(),this}removeImport(e){this._checkLoaded();const t=this.stylesheet.imports||[],i=this.getImportIndex(e);-1!==i&&(t.splice(i,1),this.fragments[i].style._remove(),this.fragments.splice(i,1),this._reloadImports())}getImportIndex(e){const t=(this.stylesheet.imports||[]).findIndex(t=>t.id===e);return-1===t&&this.fire(new P(new Error(`Import '${e}' does not exist in the map's style and cannot be updated.`))),t}getLayer(e){return this._mergedLayers[e]}getSources(){const e=[];for(const t in this._mergedOtherSourceCaches){const i=this._mergedOtherSourceCaches[t];i&&e.push(i.getSource())}return e}getSource(e,t){const i=this.getSourceCache(e,t);return i&&i.getSource()}getLayerSource(e){const t=this.getLayerSourceCache(e);return t&&t.getSource()}getSourceCache(e,t){const i=C(e,t);return this._mergedOtherSourceCaches[i]}getLayerSourceCache(e){const t=e.sourceFqid;return"symbol"===e.type?this._mergedSymbolSourceCaches[t]:"fill-extrusion"===e.type?this._mergedFillExtrusionSourceCaches[t]||this._mergedOtherSourceCaches[t]:"fill"===e.type&&e.sourceLayer===hs&&this._mergedHdRoadCoverageSourceCaches[t]?this._mergedHdRoadCoverageSourceCaches[t]:this._mergedOtherSourceCaches[t]}getSourceCaches(e){return null==e?Object.values(this._mergedSourceCaches):[this._mergedOtherSourceCaches[e],this._mergedSymbolSourceCaches[e],this._mergedFillExtrusionSourceCaches[e],this._mergedHdRoadCoverageSourceCaches[e]].filter(Boolean)}updateSourceCaches(){const e=this._changes.getUpdatedSourceCaches();for(const t in e){const i=e[t];"reload"===i?this.reloadSource(t):"clear"===i&&this.clearSource(t)}}updateLayers(e){const t=this._changes.getUpdatedPaintProperties();for(const i of t){const t=this.getLayer(i);t&&t.updateTransitions(e)}}getGlyphsUrl(){return this.stylesheet.glyphs}setGlyphsUrl(e){if(this.stylesheet.glyphs=e,e!==this.glyphManager.url){this.glyphManager.setURL(e);for(const e in this._mergedSymbolSourceCaches)this._mergedSymbolSourceCaches[e].reload()}}getOwnSourceCache(e){return this._otherSourceCaches[e]}getOwnLayerSourceCache(e){return"symbol"===e.type?this._symbolSourceCaches[e.source]:"fill-extrusion"===e.type&&this._fillExtrusionSourceCaches[e.source]||this._otherSourceCaches[e.source]}getOwnSourceCaches(e){return[this._otherSourceCaches[e],this._symbolSourceCaches[e],this._fillExtrusionSourceCaches[e],this._hdCoverage&&this._hdCoverage.coverageSourceCaches[e]].filter(Boolean)}_updateHdCoverageSourceCache(e){return Il.HdCoverageState&&Il.updateHdCoverageSourceCache?(this._hdCoverage||(this._hdCoverage=new Il.HdCoverageState),Il.updateHdCoverageSourceCache(this,this._hdCoverage,e),!1):"fill"===e.type&&e.sourceLayer===hs}_isSourceCacheLoaded(e){const t=this.getOwnSourceCaches(e);return 0===t.length?(this.fire(new P(new Error(`There is no source with ID '${e}'`))),!1):t.every(e=>e.loaded())}has3DLayers(){return this._has3DLayers}hasSymbolLayers(){return this._hasSymbolLayers}hasCircleLayers(){return this._hasCircleLayers}isLayerClipped(e,t){if(!this._clipLayerPresent&&"fill-extrusion"!==e.type&&"building"!==e.type)return!1;const i="fill-extrusion"===e.type&&("building"===e.sourceLayer||"procedural_buildings"===e.sourceLayer),s="building"===e.type;if(e.is3D(!!this.terrain)){if(i||s||t&&"batched-model"===t.type)return!0;if("model"===e.type)return!0}else if("symbol"===e.type)return!0;return!1}_clearWorkerCaches(){this.dispatcher.broadcast("clearCaches")}getBOMObject(){}destroy(){this._clearWorkerCaches(),this.imageManager.imageAtlasCache.clear(),this.fragments.forEach(e=>{e.style._remove()}),this.terrainSetForDrapingOnly()&&(delete this.terrain,delete this.stylesheet.terrain)}async getImages(e,t){const i=new Promise((e,i)=>{this.imageManager.getImages(t.icons.concat(t.patterns),t.scope,(t,s)=>{t?i(t):e(s)})});this._updateTilesForChangedImages();const s=t.icons.map(e=>g.toString(e)),o=t.patterns.map(e=>g.toString(e)),r=e=>{e&&(e.setDependencies(t.tileID.key,"icons",s),e.setDependencies(t.tileID.key,"patterns",o))},n=C(t.source,t.scope);return r(this._mergedOtherSourceCaches[n]),r(this._mergedSymbolSourceCaches[n]),(t.icons.some(e=>e.iconsetId)||t.patterns.some(e=>e.iconsetId))&&this.fire(new M("data",{dataType:"style"})),i}async rasterizeImages(e,t){return new Promise((e,i)=>{this.imageManager.rasterizeImages(t,(t,s)=>{t?i(t):e(s)})})}async checkAtlasCache(e,t){const i=this.imageManager.imageAtlasCache.findCachedAtlas(t.descriptor);return i&&i.contentDescriptor?{iconPositions:i.iconPositions,patternPositions:i.patternPositions,sourceHash:i.contentDescriptor.hash}:null}async getGlyphs(e,t){return new Promise((e,i)=>{this.glyphManager.getGlyphs(t.stacks,(t,s)=>{t?i(t):e(s)})})}}const Ud="\n#define EPSILON 0.0000001\n#define PI 3.141592653589793\n#define storage_depth_to_native_ndc_z(z01) ((z01)*2.0-1.0)\n#define native_ndc_z_to_storage_depth(ndc_z) ((ndc_z)*0.5+0.5)\n#define native_clip_z_to_cutoff_depth(clip_z,clip_w) (clip_z)\n#define native_depth_epsilon(eps) (eps)\n#define depth_range_to_native_ndc_z(z01,unpack) ((z01)*(unpack).x+(unpack).y)\n#define bottom_left_to_native_uv(uv) (uv)\n#define native_cubemap_direction(dir) vec3((dir).x,-(dir).y,(dir).z)\n#define ndc_xy_to_framebuffer_uv(ndc_xy) ((ndc_xy)*0.5+0.5)\n#define ndc_xy_to_depth_texture_uv(ndc_xy) bottom_left_to_native_uv((ndc_xy)*0.5+0.5)\n#ifdef RENDER_CUTOFF\nfloat cutoff_opacity(vec4 cutoff_params,float depth) {float near=cutoff_params.x;float far=cutoff_params.y;float cutoffStart=cutoff_params.z;float cutoffEnd=cutoff_params.w;float linearDepth=(depth-near)/(far-near);return clamp((linearDepth-cutoffStart)/(cutoffEnd-cutoffStart),0.0,1.0);}\n#endif",Vd="\n#define fragcoord_to_bottom_left_uv(frag,size) ((frag)/(size))\n#define fragcoord_to_ndc_y(fragY,invY) ((fragY)*(invY)*2.0-1.0)\n#define native_window_space_normal(fdx,fdy) (normalize(cross((fdx),(fdy)))*-1.0)\n#define fragcoord_to_framebuffer_uv(frag,inv) ((frag)*(inv))\n#define native_window_space_tangent(axis) (axis)\n#define native_tbn_view_dir(position) (normalize(-(position)))\n#ifdef DUAL_SOURCE_BLENDING\nlayout(location=0,index=0) out vec4 glFragColor;layout(location=0,index=1) out vec4 glFragColorSrc1;\n#elif defined(FLOAT_RENDER_TARGET)\nlayout(location=0) out highp vec4 glFragColor;\n#else\nlayout(location=0) out vec4 glFragColor;\n#endif\n#ifdef USE_MRT1\nlayout(location=1) out vec4 out_Target1;\n#endif\nhighp float unpack_depth(highp vec4 rgba_depth)\n{const highp vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return storage_depth_to_native_ndc_z(dot(rgba_depth,bit_shift));}highp vec4 pack_depth(highp float ndc_z) {highp float depth=native_ndc_z_to_storage_depth(ndc_z);const highp vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const highp vec4 bit_mask =vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);highp vec4 res=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;}const float DITHER_THRESHOLDS[16]=float[16](\n1.0/17.0, 9.0/17.0, 3.0/17.0,11.0/17.0,13.0/17.0, 5.0/17.0,15.0/17.0, 7.0/17.0,4.0/17.0,12.0/17.0, 2.0/17.0,10.0/17.0,16.0/17.0, 8.0/17.0,14.0/17.0, 6.0/17.0\n);int viewport_dither_index(vec2 fragCoordXY) {return (int(fragCoordXY.x) % 4)*4+(int(fragCoordXY.y) % 4);}\n#ifdef DEBUG_WIREFRAME\n#define HANDLE_WIREFRAME_DEBUG \\\nglFragColor=vec4(0.7,0.0,0.0,0.7); \\\ngl_FragDepth=gl_FragCoord.z-0.0001;\n#else\n#define HANDLE_WIREFRAME_DEBUG\n#endif\n#ifdef RENDER_CUTOFF\nuniform highp vec4 u_cutoff_params;in float v_cutoff_opacity;\n#endif\nvec4 textureLodCustom(sampler2D image,highp vec2 pos,highp vec2 lod_coord) {highp vec2 size=vec2(textureSize(image,0));highp vec2 dx=dFdx(lod_coord.xy*size);highp vec2 dy=dFdy(lod_coord.xy*size);highp float delta_max_sqr=max(dot(dx,dx),dot(dy,dy));highp float lod=0.5*log2(delta_max_sqr);return textureLod(image,pos,lod);}vec4 premultiplyColor(vec3 nonPremultipliedColor,float a) {return vec4(nonPremultipliedColor*a,a);}vec3 unpremultiplyColor(vec4 premultipliedColor) {if (premultipliedColor.a > 0.0) {return premultipliedColor.rgb/premultipliedColor.a;}return premultipliedColor.rgb;}vec3 applyLUT(highp sampler3D lut,vec3 col) {vec3 size=vec3(textureSize(lut,0));vec3 uvw=(col.rbg*float(size-1.0)+0.5)/size;return texture(lut,uvw).rgb;}vec4 applyLUT(highp sampler3D lut,vec4 premultipliedColor) {return premultiplyColor(applyLUT(lut,unpremultiplyColor(premultipliedColor)),premultipliedColor.a);}void storeEmissiveColor(vec4 color,float emissiveStrength) {\n#ifdef DUAL_SOURCE_BLENDING\nglFragColorSrc1=vec4(vec3(0.0),emissiveStrength);\n#else\n#ifdef USE_MRT1\n#ifdef USE_MRT1_RGBA\nout_Target1=vec4(color.rgb*emissiveStrength,color.a);\n#else\nout_Target1=vec4(emissiveStrength*color.a,0.0,0.0,glFragColor.a);\n#endif\n#endif\n#endif\n}",jd="\n#define EXTENT 8192.0\n#define RAD_TO_DEG 180.0/PI\n#define DEG_TO_RAD PI/180.0\n#define GLOBE_RADIUS EXTENT/PI/2.0\nfloat wrap(float n,float min,float max) {float d=max-min;float w=mod(mod(n-min,d)+d,d)+min;return (w==min) ? max : w;}\n#ifdef PROJECTION_GLOBE_VIEW\nvec3 mercator_tile_position(mat4 matrix,vec2 tile_anchor,vec3 tile_id,vec2 mercator_center) {\n#ifndef PROJECTED_POS_ON_VIEWPORT\nfloat tiles=tile_id.z;vec2 mercator=(tile_anchor/EXTENT+tile_id.xy)/tiles;mercator-=mercator_center;mercator.x=wrap(mercator.x,-0.5,0.5);vec4 mercator_tile=vec4(mercator.xy*EXTENT,EXTENT/(2.0*PI),1.0);mercator_tile=matrix*mercator_tile;return mercator_tile.xyz;\n#else\nreturn vec3(0.0);\n#endif\n}vec3 mix_globe_mercator(vec3 globe,vec3 mercator,float t) {return mix(globe,mercator,t);}mat3 globe_mercator_surface_vectors(vec3 pos_normal,vec3 up_dir,float zoom_transition) {vec3 normal=zoom_transition==0.0 ? pos_normal : normalize(mix(pos_normal,up_dir,zoom_transition));vec3 xAxis=normalize(vec3(normal.z,0.0,-normal.x));vec3 yAxis=normalize(cross(normal,xAxis));return mat3(xAxis,yAxis,normal);}\n#endif\nvec2 unpack_float(const float packedValue) {int packedIntValue=int(packedValue);int v0=packedIntValue/256;return vec2(v0,packedIntValue-v0*256);}vec4 decode_color(const vec2 encodedColor) {return vec4(\nunpack_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 vec2 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 (units_to_pixels*pos+offset)/pattern_size;}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) {return get_pattern_pos(pixel_coord_upper,pixel_coord_lower,pattern_size,vec2(tile_units_to_pixels),pos);}float mercatorXfromLng(float lng) {return (180.0+lng)/360.0;}float mercatorYfromLat(float lat) {return (180.0-(RAD_TO_DEG*log(tan(PI/4.0+lat/2.0*DEG_TO_RAD))))/360.0;}vec3 latLngToECEF(vec2 latLng) {latLng=DEG_TO_RAD*latLng;float cosLat=cos(latLng[0]);float sinLat=sin(latLng[0]);float cosLng=cos(latLng[1]);float sinLng=sin(latLng[1]);float sx=cosLat*sinLng*GLOBE_RADIUS;float sy=-sinLat*GLOBE_RADIUS;float sz=cosLat*cosLng*GLOBE_RADIUS;return vec3(sx,sy,sz);}\n#ifdef RENDER_CUTOFF\nuniform vec4 u_cutoff_params;out float v_cutoff_opacity;\n#endif\nconst vec4 AWAY=vec4(-1000.0,-1000.0,-1000.0,1);const float skirtOffset=24575.0;vec3 decomposeToPosAndSkirt(ivec2 posWithComposedSkirt)\n{float skirt=float(float(posWithComposedSkirt.x) >=skirtOffset);vec2 pos=vec2(posWithComposedSkirt)-vec2(skirt*skirtOffset,0.0);return vec3(pos,skirt);}\n#define GET_ATTRIBUTE_float(attrib,matInfo,attrib_id) attrib\n#define GET_ATTRIBUTE_vec4(attrib,matInfo,attrib_id) attrib\n#define GET_ATTRIBUTE_vec2(attrib,matInfo,attrib_id) attrib\n#define DECLARE_MATERIAL_TABLE_INFO\n",Gd="in highp vec3 a_pos_3f;uniform lowp mat4 u_matrix;out highp vec3 v_uv;void main() {const mat3 half_neg_pi_around_x=mat3(1.0,0.0, 0.0,0.0,0.0,-1.0,0.0,1.0, 0.0);v_uv=half_neg_pi_around_x*a_pos_3f;vec4 pos=u_matrix*vec4(a_pos_3f,1.0);gl_Position=pos.xyww;}",qd="\n#define ELEVATION_SCALE 7.0\n#define ELEVATION_OFFSET 450.0\n#ifdef PROJECTION_GLOBE_VIEW\nuniform vec3 u_tile_tl_up;uniform vec3 u_tile_tr_up;uniform vec3 u_tile_br_up;uniform vec3 u_tile_bl_up;uniform float u_tile_up_scale;\n#endif\nvec3 elevationVector(vec2 pos) {\n#ifdef PROJECTION_GLOBE_VIEW\nvec2 uv=pos/EXTENT;vec3 up=normalize(mix(\nmix(u_tile_tl_up,u_tile_tr_up,uv.xxx),mix(u_tile_bl_up,u_tile_br_up,uv.xxx),uv.yyy));return up*u_tile_up_scale;\n#else\nreturn vec3(0,0,1);\n#endif\n}\n#ifdef TERRAIN\nuniform highp sampler2D u_dem;\n#ifdef TERRAIN_VERTEX_MORPHING\nuniform highp sampler2D u_dem_prev;\n#endif\nuniform vec2 u_dem_tl;uniform vec2 u_dem_tl_prev;uniform float u_dem_scale;uniform float u_dem_scale_prev;uniform float u_dem_size;uniform float u_dem_lerp;uniform float u_exaggeration;uniform float u_meter_to_dem;uniform mat4 u_label_plane_matrix_inv;vec4 tileUvToDemSample(vec2 uv,float dem_size,float dem_scale,vec2 dem_tl) {vec2 pos=dem_size*(uv*dem_scale+dem_tl)+1.0;vec2 f=fract(pos);return vec4((pos-f+0.5)/(dem_size+2.0),f);}float currentElevation(vec2 apos) {\n#ifdef TERRAIN_DEM_FLOAT_FORMAT\nvec2 pos=(u_dem_size*(apos/8192.0*u_dem_scale+u_dem_tl)+1.5)/(u_dem_size+2.0);return u_exaggeration*texture(u_dem,pos).r;\n#else\nfloat dd=1.0/(u_dem_size+2.0);vec4 r=tileUvToDemSample(apos/8192.0,u_dem_size,u_dem_scale,u_dem_tl);vec2 pos=r.xy;vec2 f=r.zw;float tl=texture(u_dem,pos).r;float tr=texture(u_dem,pos+vec2(dd,0)).r;float bl=texture(u_dem,pos+vec2(0,dd)).r;float br=texture(u_dem,pos+vec2(dd,dd)).r;return u_exaggeration*mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y);\n#endif\n}\n#ifdef TERRAIN_VERTEX_MORPHING\nfloat prevElevation(vec2 apos) {\n#ifdef TERRAIN_DEM_FLOAT_FORMAT\nvec2 pos=(u_dem_size*(apos/8192.0*u_dem_scale_prev+u_dem_tl_prev)+1.5)/(u_dem_size+2.0);return u_exaggeration*texture(u_dem_prev,pos).r;\n#else\nfloat dd=1.0/(u_dem_size+2.0);vec4 r=tileUvToDemSample(apos/8192.0,u_dem_size,u_dem_scale_prev,u_dem_tl_prev);vec2 pos=r.xy;vec2 f=r.zw;float tl=texture(u_dem_prev,pos).r;float tr=texture(u_dem_prev,pos+vec2(dd,0)).r;float bl=texture(u_dem_prev,pos+vec2(0,dd)).r;float br=texture(u_dem_prev,pos+vec2(dd,dd)).r;return u_exaggeration*mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y);\n#endif\n}\n#endif\nvec4 fourSample(vec2 pos,vec2 off) {float tl=texture(u_dem,pos).r;float tr=texture(u_dem,pos+vec2(off.x,0.0)).r;float bl=texture(u_dem,pos+vec2(0.0,off.y)).r;float br=texture(u_dem,pos+off).r;return vec4(tl,tr,bl,br);}float flatElevation(vec2 pack) {vec2 apos=floor(pack/8.0);vec2 span=10.0*(pack-apos*8.0);vec2 uvTex=(apos-vec2(1.0,1.0))/8190.0;float size=u_dem_size+2.0;float dd=1.0/size;vec2 pos=u_dem_size*(uvTex*u_dem_scale+u_dem_tl)+1.0;vec2 f=fract(pos);pos=(pos-f+0.5)*dd;vec4 h=fourSample(pos,vec2(dd));float z=mix(mix(h.x,h.y,f.x),mix(h.z,h.w,f.x),f.y);vec2 w=floor(0.5*(span*u_meter_to_dem-1.0));vec2 d=dd*w;h=fourSample(pos-d,2.0*d+vec2(dd));vec4 diff=abs(h.xzxy-h.ywzw);vec2 slope=min(vec2(0.25),u_meter_to_dem*0.5*(diff.xz+diff.yw)/(2.0*w+vec2(1.0)));vec2 fix=slope*span;float base=z+max(fix.x,fix.y);return u_exaggeration*base;}float elevationFromUint16(float word) {return u_exaggeration*(word/ELEVATION_SCALE-ELEVATION_OFFSET);}\n#endif\nfloat elevation(vec2 apos) {\n#ifdef TERRAIN\n#ifdef TERRAIN_VERTEX_MORPHING\nfloat nextElevation=currentElevation(apos);float prevElevation=prevElevation(apos);return mix(prevElevation,nextElevation,u_dem_lerp);\n#else\nreturn currentElevation(apos);\n#endif\n#else\nreturn 0.0;\n#endif\n}\n#ifdef DEPTH_OCCLUSION\nuniform highp sampler2D u_depth;uniform highp vec2 u_depth_size_inv;uniform highp vec2 u_depth_range_unpack;uniform highp float u_occluder_half_size;uniform highp float u_occlusion_depth_offset;\n#ifdef DEPTH_D24\nfloat unpack_depth(float depth) {return depth_range_to_native_ndc_z(depth,u_depth_range_unpack);}vec4 unpack_depth4(vec4 depth) {return depth_range_to_native_ndc_z(depth,u_depth_range_unpack);}\n#else\nhighp float unpack_depth_rgba(vec4 rgba_depth)\n{const highp vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return storage_depth_to_native_ndc_z(dot(rgba_depth,bit_shift));}\n#endif\nhighp vec2 occlusionDepthUv(highp vec2 ndc_xy) {return ndc_xy_to_depth_texture_uv(ndc_xy);}\n#define occlusion_depth_bias native_depth_epsilon(u_occlusion_depth_offset)\n#define occlusion_fade_slope(native_delta) (300.0*(native_delta)/native_depth_epsilon(1.0))\nbool isOccluded(vec4 frag) {vec3 coord=frag.xyz/frag.w;highp vec2 uv=occlusionDepthUv(coord.xy);\n#ifdef DEPTH_D24\nfloat depth=unpack_depth(texture(u_depth,uv).r);\n#else\nfloat depth=unpack_depth_rgba(texture(u_depth,uv));\n#endif\nreturn coord.z+occlusion_depth_bias > depth;}highp vec4 getCornerDepths(vec2 coord) {highp vec3 df=vec3(u_occluder_half_size*u_depth_size_inv,0.0);highp vec2 uv=occlusionDepthUv(coord);\n#ifdef DEPTH_D24\nhighp vec4 depth=vec4(\ntexture(u_depth,uv-df.xz).r,texture(u_depth,uv+df.xz).r,texture(u_depth,uv-df.zy).r,texture(u_depth,uv+df.zy).r\n);depth=unpack_depth4(depth);\n#else\nhighp vec4 depth=vec4(\nunpack_depth_rgba(texture(u_depth,uv-df.xz)),unpack_depth_rgba(texture(u_depth,uv+df.xz)),unpack_depth_rgba(texture(u_depth,uv-df.zy)),unpack_depth_rgba(texture(u_depth,uv+df.zy))\n);\n#endif\nreturn depth;}highp float occlusionFadeMultiSample(vec4 frag) {highp vec3 coord=frag.xyz/frag.w;highp vec2 uv=occlusionDepthUv(coord.xy);int NX=3;int NY=4;highp vec2 df=u_occluder_half_size*u_depth_size_inv;highp vec2 oneStep=2.0*u_occluder_half_size*u_depth_size_inv/vec2(NX-1,NY-1);highp float res=0.0;for (int y=0; y < NY;++y) {for (int x=0; x < NX;++x) {\n#ifdef DEPTH_D24\nhighp float depth=unpack_depth(texture(u_depth,uv-df+vec2(float(x)*oneStep.x,float(y)*oneStep.y)).r);\n#else\nhighp float depth=unpack_depth_rgba(texture(u_depth,uv-df+vec2(float(x)*oneStep.x,float(y)*oneStep.y)));\n#endif\nres+=1.0-clamp(occlusion_fade_slope(coord.z+occlusion_depth_bias-depth),0.0,1.0);}}res=clamp(2.0*res/float(NX*NY)-0.5,0.0,1.0);return res;}highp float occlusionFade(vec4 frag) {highp vec3 coord=frag.xyz/frag.w;highp vec4 depth=getCornerDepths(coord.xy);return dot(vec4(0.25),vec4(1.0)-clamp(occlusion_fade_slope(vec4(coord.z+occlusion_depth_bias)-depth),0.0,1.0));}\n#else\nbool isOccluded(vec4 frag) { return false; }highp float occlusionFade(vec4 frag) { return 1.0; }highp float occlusionFadeMultiSample(vec4 frag) { return 1.0; }\n#endif",Zd="#ifdef FOG\nuniform mediump vec4 u_fog_color;uniform mediump vec2 u_fog_range;uniform mediump float u_fog_horizon_blend;uniform mediump mat4 u_fog_matrix;out vec3 v_fog_pos;float fog_range(float depth) {return (depth-u_fog_range[0])/(u_fog_range[1]-u_fog_range[0]);}float fog_horizon_blending(vec3 camera_dir) {float t=max(0.0,camera_dir.z/u_fog_horizon_blend);return u_fog_color.a*exp(-3.0*t*t);}float fog_opacity(float t) {const float decay=6.0;float falloff=1.0-min(1.0,exp(-decay*t));falloff*=falloff*falloff;return u_fog_color.a*min(1.0,1.00747*falloff);}vec3 fog_position(vec3 pos) {return (u_fog_matrix*vec4(pos,1.0)).xyz;}vec3 fog_position(vec2 pos) {return fog_position(vec3(pos,0.0));}float fog(vec3 pos) {float depth=length(pos);float opacity=fog_opacity(fog_range(depth));return opacity*fog_horizon_blending(pos/depth);}\n#endif",Wd="#ifdef FOG\nuniform mediump vec4 u_fog_color;uniform mediump vec2 u_fog_range;uniform mediump float u_fog_horizon_blend;uniform mediump vec2 u_fog_vertical_limit;uniform mediump float u_fog_temporal_offset;in vec3 v_fog_pos;uniform highp vec3 u_frustum_tl;uniform highp vec3 u_frustum_tr;uniform highp vec3 u_frustum_br;uniform highp vec3 u_frustum_bl;uniform highp vec3 u_globe_pos;uniform highp float u_globe_radius;uniform highp vec2 u_viewport;uniform float u_globe_transition;uniform int u_is_globe;float fog_range(float depth) {return (depth-u_fog_range[0])/(u_fog_range[1]-u_fog_range[0]);}float fog_horizon_blending(vec3 camera_dir) {float t=max(0.0,camera_dir.z/u_fog_horizon_blend);return u_fog_color.a*exp(-3.0*t*t);}float fog_opacity(float t) {const float decay=6.0;float falloff=1.0-min(1.0,exp(-decay*t));falloff*=falloff*falloff;return u_fog_color.a*min(1.0,1.00747*falloff);}float globe_glow_progress() {highp vec2 uv=fragcoord_to_bottom_left_uv(gl_FragCoord.xy,u_viewport);highp vec3 ray_dir=mix(\nmix(u_frustum_tl,u_frustum_tr,uv.x),mix(u_frustum_bl,u_frustum_br,uv.x),1.0-uv.y);highp vec3 dir=normalize(ray_dir);highp vec3 closest_point=dot(u_globe_pos,dir)*dir;highp float sdf=length(closest_point-u_globe_pos)/u_globe_radius;return sdf+PI*0.5;}float fog_opacity(vec3 pos) {float depth=length(pos);return fog_opacity(fog_range(depth));}vec3 fog_apply(vec3 color,vec3 pos,float opacity_limit) {float depth=length(pos);float opacity;if (u_is_globe==1) {float glow_progress=globe_glow_progress();float t=mix(glow_progress,depth,u_globe_transition);opacity=fog_opacity(fog_range(t));} else {opacity=fog_opacity(fog_range(depth));opacity*=fog_horizon_blending(pos/depth);}return mix(color,u_fog_color.rgb,min(opacity,opacity_limit));}vec3 fog_apply(vec3 color,vec3 pos) {return fog_apply(color,pos,1.0);}vec4 fog_apply_from_vert(vec4 color,float fog_opac) {float alpha=EPSILON+color.a;color.rgb=mix(color.rgb/alpha,u_fog_color.rgb,fog_opac)*alpha;return color;}vec3 fog_apply_sky_gradient(vec3 camera_ray,vec3 sky_color) {float horizon_blend=fog_horizon_blending(normalize(camera_ray));return mix(sky_color,u_fog_color.rgb,horizon_blend);}vec4 fog_apply_premultiplied(vec4 color,vec3 pos) {float alpha=EPSILON+color.a;color.rgb=fog_apply(color.rgb/alpha,pos)*alpha;return color;}vec4 fog_apply_premultiplied(vec4 color,vec3 pos,float heightMeters) {float verticalProgress=(u_fog_vertical_limit.x > 0.0 || u_fog_vertical_limit.y > 0.0) ? smoothstep(u_fog_vertical_limit.x,u_fog_vertical_limit.y,heightMeters) : 0.0;float opacityLimit=1.0-smoothstep(0.9,1.0,fog_opacity(pos));return mix(fog_apply_premultiplied(color,pos),color,min(verticalProgress,opacityLimit));}vec3 fog_dither(vec3 color) {return color;}vec4 fog_dither(vec4 color) {return vec4(fog_dither(color.rgb),color.a);}\n#endif",Hd="\n#ifndef MAX_UBO_SIZE_VEC4\n#define MAX_UBO_SIZE_VEC4 1024u\n#endif\nfloat zoomFactor(float zm,float zM,float zoomFraction) {if (zm==zM) return zoomFraction-zm >=0.0 ? 1.0 : 0.0;return clamp((zoomFraction-zm)/(zM-zm),0.0,1.0);}",$d="\n#ifdef LIGHTING_3D_MODE\nuniform mediump vec3 u_lighting_ambient_color;uniform mediump vec3 u_lighting_directional_dir;uniform mediump vec3 u_lighting_directional_color;uniform mediump vec3 u_ground_radiance;float calculate_ambient_directional_factor(vec3 normal) {float NdotL=dot(normal,u_lighting_directional_dir);const float factor_reduction_max=0.3;float dir_luminance=dot(u_lighting_directional_color,vec3(0.2126,0.7152,0.0722));float directional_factor_min=1.0-factor_reduction_max*min(dir_luminance,1.0);float ambient_directional_factor=mix(directional_factor_min,1.0,min((NdotL+1.0),1.0));const float vertical_factor_min=0.92;float vertical_factor=mix(vertical_factor_min,1.0,normal.z*0.5+0.5);return vertical_factor*ambient_directional_factor;}vec3 linearProduct(vec3 srgbIn,vec3 k) {return srgbIn*pow(k,vec3(1./2.2));}vec3 apply_lighting(vec3 color,vec3 normal,float dir_factor) {float ambient_directional_factor=calculate_ambient_directional_factor(normal);vec3 ambient_contrib=ambient_directional_factor*u_lighting_ambient_color;vec3 directional_contrib=u_lighting_directional_color*dir_factor;return linearProduct(color,ambient_contrib+directional_contrib);}vec4 apply_lighting(vec4 color,vec3 normal,float dir_factor) {return vec4(apply_lighting(color.rgb,normal,dir_factor),color.a);}vec3 apply_lighting(vec3 color,vec3 normal) {float dir_factor=max(dot(normal,u_lighting_directional_dir),0.0);return apply_lighting(color.rgb,normal,dir_factor);}vec4 apply_lighting(vec4 color,vec3 normal) {float dir_factor=max(dot(normal,u_lighting_directional_dir),0.0);return vec4(apply_lighting(color.rgb,normal,dir_factor),color.a);}vec3 apply_lighting_ground(vec3 color) {return color*u_ground_radiance;}vec4 apply_lighting_ground(vec4 color) {return vec4(apply_lighting_ground(color.rgb),color.a);}float calculate_NdotL(vec3 normal) {const float ext=0.70710678118;return (clamp(dot(normal,u_lighting_directional_dir),-ext,1.0)+ext)/(1.0+ext);}vec4 apply_lighting_with_emission_ground(vec4 color,float emissive_strength) {return mix(apply_lighting_ground(color),color,emissive_strength);}vec3 compute_flood_lighting(vec3 flood_light_color,float fully_occluded_factor,float occlusion,vec3 ground_shadow_factor) {vec3 fully_occluded_color=flood_light_color*mix(ground_shadow_factor,vec3(1.0),fully_occluded_factor);float occlusion_ramp=smoothstep(0.0,0.2,1.0-occlusion);return mix(fully_occluded_color,flood_light_color,occlusion_ramp);}vec3 compute_emissive_draped(vec3 unlit_color,float fully_occluded_factor,float occlusion,vec3 ground_shadow_factor) {vec3 fully_occluded_color=unlit_color*mix(ground_shadow_factor,vec3(1.0),fully_occluded_factor);return mix(fully_occluded_color,unlit_color,1.0-occlusion);}\n#endif",Xd="#ifdef RASTER_ARRAY\nuniform highp sampler2D u_image0;uniform sampler2D u_image1;const vec4 NODATA=vec4(1);ivec4 _raTexLinearCoord(highp vec2 texCoord,highp vec2 texResolution,out highp vec2 fxy) {texCoord=texCoord*texResolution-0.5;fxy=fract(texCoord);texCoord-=fxy;return ivec4(texCoord.xxyy+vec2(1.5,0.5).xyxy);}vec2 _raTexLinearMix(highp vec2 fxy,highp vec4 colorMix,highp float colorOffset,highp vec4 t00,highp vec4 t10,highp vec4 t01,highp vec4 t11) {vec2 c00=t00==NODATA ? vec2(0) : vec2(colorOffset+dot(t00,colorMix),1);vec2 c10=t10==NODATA ? vec2(0) : vec2(colorOffset+dot(t10,colorMix),1);vec2 c01=t01==NODATA ? vec2(0) : vec2(colorOffset+dot(t01,colorMix),1);vec2 c11=t11==NODATA ? vec2(0) : vec2(colorOffset+dot(t11,colorMix),1);return mix(mix(c01,c11,fxy.x),mix(c00,c10,fxy.x),fxy.y);}vec2 raTexture2D_image0_linear(highp vec2 texCoord,highp vec2 texResolution,highp vec4 colorMix,highp float colorOffset) {vec2 fxy;ivec4 c=_raTexLinearCoord(texCoord,texResolution,fxy);return _raTexLinearMix(fxy,colorMix,colorOffset,texelFetch(u_image0,c.yz,0),texelFetch(u_image0,c.xz,0),texelFetch(u_image0,c.yw,0),texelFetch(u_image0,c.xw,0)\n);}vec2 raTexture2D_image1_linear(highp vec2 texCoord,highp vec2 texResolution,highp vec4 colorMix,highp float colorOffset) {vec2 fxy;ivec4 c=_raTexLinearCoord(texCoord,texResolution,fxy);return _raTexLinearMix(fxy,colorMix,colorOffset,texelFetch(u_image1,c.yz,0),texelFetch(u_image1,c.xz,0),texelFetch(u_image1,c.yw,0),texelFetch(u_image1,c.xw,0)\n);}vec2 raTexture2D_image0_nearest(highp vec2 texCoord,highp vec2 texResolution,highp vec4 colorMix,highp float colorOffset) {vec4 t=texelFetch(u_image0,ivec2(texCoord*texResolution),0);return t==NODATA ? vec2(0) : vec2(colorOffset+dot(t,colorMix),1);}vec2 raTexture2D_image1_nearest(highp vec2 texCoord,highp vec2 texResolution,highp vec4 colorMix,highp float colorOffset) {vec4 t=texelFetch(u_image1,ivec2(texCoord*texResolution),0);return t==NODATA ? vec2(0) : vec2(colorOffset+dot(t,colorMix),1);}\n#endif",Yd="#ifdef RENDER_SHADOWS\nuniform mediump vec3 u_shadow_direction;uniform highp vec3 u_shadow_normal_offset;vec3 shadow_normal_offset(vec3 normal) {float tileInMeters=u_shadow_normal_offset[0];vec3 n=vec3(-normal.xy,tileInMeters*normal.z);float dotScale=min(1.0-dot(normal,u_shadow_direction),1.0)*0.5+0.5;return n*dotScale;}vec3 shadow_normal_offset_model(vec3 normal) {vec3 transformed_normal=vec3(-normal.xy,normal.z);float NDotL=dot(normalize(transformed_normal),u_shadow_direction);float dotScale=min(1.0-NDotL,1.0)*0.5+0.5;return normal*dotScale;}float shadow_normal_offset_multiplier0() {return u_shadow_normal_offset[1];}float shadow_normal_offset_multiplier1() {return u_shadow_normal_offset[2];}\n#endif",Kd="#ifdef RENDER_SHADOWS\nprecision highp sampler2DShadow;uniform sampler2DShadow u_shadowmap_0;uniform sampler2DShadow u_shadowmap_1;uniform float u_shadow_intensity;uniform float u_shadow_map_resolution;uniform float u_shadow_texel_size;uniform highp vec3 u_shadow_normal_offset;uniform vec2 u_fade_range;uniform mediump vec3 u_shadow_direction;uniform highp vec3 u_shadow_bias;highp vec2 shadow_map_ndc_to_uv(highp vec2 ndc_xy) {return ndc_xy*0.5+0.5;}highp vec3 shadow_map_ndc_to_sample_space(highp vec3 ndc) {return vec3(shadow_map_ndc_to_uv(ndc.xy),native_ndc_z_to_storage_depth(ndc.z));}float shadow_sample(sampler2DShadow shadowmap,highp vec3 pos,highp float bias) {highp vec3 coord=vec3(shadow_map_ndc_to_uv(pos.xy),native_ndc_z_to_storage_depth(pos.z)-bias);return texture(shadowmap,coord);}float shadow_occlusion(highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth,highp float bias) {light_view_pos0.xyz/=light_view_pos0.w;\n#ifdef SHADOWS_SINGLE_CASCADE\nvec2 abs_bounds=abs(light_view_pos0.xy);if (abs_bounds.x >=1.0 || abs_bounds.y >=1.0) {return 0.0;}return shadow_sample(u_shadowmap_0,light_view_pos0.xyz,bias);\n#else\nlight_view_pos1.xyz/=light_view_pos1.w;vec4 abs_bounds=abs(vec4(light_view_pos0.xy,light_view_pos1.xy));if (abs_bounds.x < 1.0 && abs_bounds.y < 1.0) {return shadow_sample(u_shadowmap_0,light_view_pos0.xyz,bias);}if (abs_bounds.z >=1.0 || abs_bounds.w >=1.0) {return 0.0;}float occlusion1=shadow_sample(u_shadowmap_1,light_view_pos1.xyz,bias);return clamp(mix(occlusion1,0.0,smoothstep(u_fade_range.x,u_fade_range.y,view_depth)),0.0,1.0);\n#endif\n}highp float calculate_shadow_bias(float NDotL) {\n#ifdef NORMAL_OFFSET\nreturn 0.5*u_shadow_bias.x;\n#else\nreturn 0.5*(u_shadow_bias.x+clamp(u_shadow_bias.y*tan(acos(NDotL)),0.0,u_shadow_bias.z));\n#endif\n}float shadowed_light_factor_normal(vec3 N,highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float NDotL=dot(N,u_shadow_direction);float bias=calculate_shadow_bias(NDotL);float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);return mix(0.0,(1.0-(u_shadow_intensity*occlusion))*NDotL,step(0.0,NDotL));}float shadowed_light_factor_normal_opacity(vec3 N,highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth,float shadow_opacity) {float NDotL=dot(N,u_shadow_direction);float bias=calculate_shadow_bias(NDotL);float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias)*shadow_opacity;return mix(0.0,(1.0-(u_shadow_intensity*occlusion))*NDotL,step(0.0,NDotL));}float shadowed_light_factor_normal_unbiased(vec3 N,highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float NDotL=dot(N,u_shadow_direction);float bias=0.0;float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);return mix(0.0,(1.0-(u_shadow_intensity*occlusion))*NDotL,step(0.0,NDotL));}highp vec2 compute_receiver_plane_depth_bias(highp vec3 pos_dx,highp vec3 pos_dy)\n{highp vec2 biasUV=vec2(\npos_dy.y*pos_dx.z-pos_dx.y*pos_dy.z,pos_dx.x*pos_dy.z-pos_dy.x*pos_dx.z);biasUV*=1.0/((pos_dx.x*pos_dy.y)-(pos_dx.y*pos_dy.x));return biasUV;}float shadowed_light_factor_plane_bias(highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {highp vec3 light_view_pos0_xyz=shadow_map_ndc_to_sample_space(light_view_pos0.xyz/light_view_pos0.w);highp vec3 light_view_pos0_ddx=dFdx(light_view_pos0_xyz);highp vec3 light_view_pos0_ddy=dFdy(light_view_pos0_xyz);highp vec2 plane_depth_bias=compute_receiver_plane_depth_bias(light_view_pos0_ddx,light_view_pos0_ddy);highp float bias=dot(vec2(u_shadow_texel_size,u_shadow_texel_size),plane_depth_bias)+0.0001;float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);return 1.0-(u_shadow_intensity*occlusion);}float shadowed_light_factor(highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float bias=0.0;float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);return 1.0-(u_shadow_intensity*occlusion);}float shadow_occlusion(float ndotl,highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float bias=calculate_shadow_bias(ndotl);return shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);}\n#endif",Jd=/^#include\s+"([^"]+)"\s*\r?\n/gm,Qd=/#pragma mapbox: ([\w\-]+) ([\w]+) ([\w]+) ([\w]+)/g,eu=/\b[A-Za-z_][A-Za-z0-9_]*\b/g,tu=new Set(["ifdef","ifndef","elif","if","defined"]),iu=new Set;uu(Ud,iu),uu(jd,iu),uu(Vd,iu);const su={"_prelude_fog.vertex.glsl":Zd,"_prelude_terrain.vertex.glsl":qd,"_prelude_shadow.vertex.glsl":Yd,"_prelude_material_table.vertex.glsl":"","_prelude_fog.fragment.glsl":Wd,"_prelude_shadow.fragment.glsl":Kd,"_prelude_lighting.glsl":$d,"_prelude_ubo_properties.glsl":Hd,"_prelude_raster_array.glsl":Xd,"_prelude_indicator_cutout.fragment.glsl":"\nvec4 applyCutout(vec4 color,float height) {return color;}","_prelude_feature_cutout.fragment.glsl":"// feature cutout (gl-native only)\n","_prelude_feature_cutout.vertex.glsl":"// feature cutout (gl-native only)\n"},ou={},ru="precision highp float;",nu="precision mediump float;",au="\n#if defined(GL_EXT_blend_func_extended) && defined(DUAL_SOURCE_BLENDING)\n#extension GL_EXT_blend_func_extended : require\n#endif",lu={preludeTerrain:pu("",qd),preludeUBOProperties:pu("",Hd),preludeFog:pu(Wd,Zd),preludeShadow:pu(Kd,Yd),preludeRasterArray:pu(Xd,""),preludeLighting:pu($d,$d),preludePrecisionQualifiers:pu(nu,ru),prelude:pu(Vd,jd),preludeExtensions:pu(au,"")},cu=[au,nu,Ud,lu.prelude.fragmentSource].join("\n"),hu=[ru,Ud,lu.prelude.vertexSource].join("\n"),du={background:pu('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_feature_cutout.fragment.glsl"\nuniform vec4 u_color;uniform float u_opacity;uniform mediump float u_emissive_strength;\n#ifdef LIGHTING_3D_MODE\nin vec4 v_color;\n#endif\nvoid main() {vec4 out_color;\n#ifdef LIGHTING_3D_MODE\nout_color=v_color;\n#else\nout_color=u_color;\n#endif\n#ifdef FOG\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\n#endif\nglFragColor=out_color*u_opacity;storeEmissiveColor(glFragColor,u_emissive_strength);\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}','#include "_prelude_fog.vertex.glsl"\n#include "_prelude_lighting.glsl"\nin ivec2 a_pos;uniform mat4 u_matrix;uniform mediump float u_emissive_strength;\n#ifdef LIGHTING_3D_MODE\nuniform mediump vec4 u_color;out vec4 v_color;\n#endif\nvoid main() {gl_Position=u_matrix*vec4(a_pos,0,1);\n#ifdef LIGHTING_3D_MODE\nv_color=apply_lighting_with_emission_ground(u_color,u_emissive_strength);\n#endif\n#ifdef FOG\nv_fog_pos=fog_position(vec2(a_pos));\n#endif\n}'),backgroundPattern:pu('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_lighting.glsl"\nuniform vec2 u_pattern_tl;uniform vec2 u_pattern_br;uniform vec2 u_texsize;uniform float u_opacity;uniform float u_emissive_strength;uniform sampler2D u_image;in highp vec2 v_pos;void main() {highp vec2 imagecoord=mod(v_pos,1.0);highp vec2 pos=mix(u_pattern_tl/u_texsize,u_pattern_br/u_texsize,imagecoord);vec4 out_color=textureLodCustom(u_image,pos,v_pos);\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength);\n#endif\n#ifdef FOG\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\n#endif\nglFragColor=out_color*u_opacity;storeEmissiveColor(glFragColor,u_emissive_strength);\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}','#include "_prelude_fog.vertex.glsl"\nuniform mat4 u_matrix;uniform vec2 u_pattern_size;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec2 u_pattern_units_to_pixels;in ivec2 a_pos;out highp vec2 v_pos;void main() {vec2 pos=vec2(a_pos);gl_Position=u_matrix*vec4(pos,0,1);v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_pattern_size,u_pattern_units_to_pixels,pos);\n#ifdef FOG\nv_fog_pos=fog_position(pos);\n#endif\n}'),circle:pu('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_lighting.glsl"\nin vec3 v_data;in 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\nuniform float u_emissive_strength;void 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 blur_positive=blur < 0.0 ? 0.0 : 1.0;lowp float antialiasblur=v_data.z;float extrude_length=length(extrude)+antialiasblur*(1.0-blur_positive);float antialiased_blur=-max(abs(blur),antialiasblur);float antialiase_blur_opacity=smoothstep(0.0,antialiasblur,extrude_length-1.0);float opacity_t=blur_positive==1.0 ?\nsmoothstep(0.0,-antialiased_blur,1.0-extrude_length) :\nsmoothstep(antialiased_blur,0.0,extrude_length-1.0)-antialiase_blur_opacity;float color_t=stroke_width < 0.01 ? 0.0 : smoothstep(\nantialiased_blur,0.0,extrude_length-radius/(radius+stroke_width)\n);vec4 out_color=mix(color*opacity,stroke_color*stroke_opacity,color_t);\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength);\n#endif\n#ifdef FOG\nout_color=fog_apply_premultiplied(out_color,v_fog_pos);\n#endif\nglFragColor=out_color*(v_visibility*opacity_t);\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\n}','#include "_prelude_fog.vertex.glsl"\n#include "_prelude_terrain.vertex.glsl"\n#define NUM_VISIBILITY_RINGS 2\n#define INV_SQRT2 0.70710678\n#define ELEVATION_BIAS 0.0001\n#define NUM_VISIBILITY_SAMPLES_PER_RING 16\nuniform mat4 u_matrix;uniform mat2 u_extrude_scale;uniform lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;in ivec2 a_pos;\n#ifdef PROJECTION_GLOBE_VIEW\nin ivec4 a_pos_3;in ivec4 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir;\n#endif\n#ifdef ELEVATED_ROADS\nin float a_circle_z_offset;\n#endif\nout vec3 v_data;out 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\nvec2 calc_offset(vec2 extrusion,float radius,float stroke_width, float perspective_scale) {return extrusion*(radius+stroke_width)*u_extrude_scale*perspective_scale;}float cantilevered_elevation(vec2 pos,float radius,float stroke_width,float perspective_scale) {vec2 c1=pos+calc_offset(vec2(-1.0,-1.0),radius,stroke_width,perspective_scale);vec2 c2=pos+calc_offset(vec2(1.0,-1.0),radius,stroke_width,perspective_scale);vec2 c3=pos+calc_offset(vec2(1.0,1.0),radius,stroke_width,perspective_scale);vec2 c4=pos+calc_offset(vec2(-1.0,1.0),radius,stroke_width,perspective_scale);float h1=elevation(c1)+ELEVATION_BIAS;float h2=elevation(c2)+ELEVATION_BIAS;float h3=elevation(c3)+ELEVATION_BIAS;float h4=elevation(c4)+ELEVATION_BIAS;return max(h4,max(h3,max(h1,h2)));}float circle_elevation(vec2 pos) {\n#if defined(TERRAIN)\nreturn elevation(pos)+ELEVATION_BIAS;\n#else\nreturn 0.0;\n#endif\n}vec4 project_vertex(vec2 extrusion,vec4 world_center,vec4 projected_center,float radius,float stroke_width, float perspective_scale,mat3 surface_vectors) {vec2 sample_offset=calc_offset(extrusion,radius,stroke_width,perspective_scale);\n#ifdef PITCH_WITH_MAP\n#ifdef PROJECTION_GLOBE_VIEW\nreturn u_matrix*( world_center+vec4(sample_offset.x*surface_vectors[0]+sample_offset.y*surface_vectors[1],0) );\n#else\nreturn u_matrix*( world_center+vec4(sample_offset,0,0) );\n#endif\n#else\nreturn projected_center+vec4(sample_offset,0,0);\n#endif\n}void 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 pos2=vec2(a_pos);vec2 extrude=vec2(mod(pos2,2.0)*2.0-1.0);vec2 circle_center=floor(pos2*0.5);float height=circle_elevation(circle_center);vec4 world_center;mat3 surface_vectors;\n#ifdef PROJECTION_GLOBE_VIEW\nsurface_vectors=globe_mercator_surface_vectors(vec3(a_pos_normal_3)/16384.0,u_up_dir,u_zoom_transition);vec3 surface_extrusion=extrude.x*surface_vectors[0]+extrude.y*surface_vectors[1];vec3 globe_elevation=elevationVector(circle_center)*height;vec3 globe_pos=vec3(a_pos_3)+surface_extrusion+globe_elevation;vec3 mercator_elevation=u_up_dir*u_tile_up_scale*height;vec3 merc_pos=mercator_tile_position(u_inv_rot_matrix,circle_center,u_tile_id,u_merc_center)+surface_extrusion+mercator_elevation;vec3 pos=mix_globe_mercator(globe_pos,merc_pos,u_zoom_transition);world_center=vec4(pos,1);\n#else\nsurface_vectors=mat3(1.0);world_center=vec4(circle_center,height,1);\n#endif\n#ifdef ELEVATED_ROADS\nworld_center.z+=a_circle_z_offset+ELEVATION_BIAS;\n#endif\nvec4 projected_center=u_matrix*world_center;float perspective_scale=0.0;\n#ifdef PITCH_WITH_MAP\n#ifdef SCALE_WITH_MAP\nperspective_scale=1.0;\n#else\nperspective_scale=projected_center.w/u_camera_to_center_distance;\n#endif\n#else\n#ifdef SCALE_WITH_MAP\nperspective_scale=u_camera_to_center_distance;\n#else\nperspective_scale=projected_center.w;\n#endif\n#endif\ngl_Position=project_vertex(extrude,world_center,projected_center,radius,stroke_width,perspective_scale,surface_vectors);float terrain_visibility=0.0;\n#ifdef TERRAIN\nfloat arc;vec4 occlusion_world_center;vec4 occlusion_projected_center;\n#ifdef PITCH_WITH_MAP\narc=2.0*PI;float cantilevered_height=cantilevered_elevation(circle_center,radius,stroke_width,perspective_scale);occlusion_world_center=vec4(circle_center,cantilevered_height,1);occlusion_projected_center=u_matrix*occlusion_world_center;\n#else\narc=PI;occlusion_world_center=world_center;occlusion_projected_center=projected_center;\n#endif\nfloat step=arc/float(NUM_VISIBILITY_SAMPLES_PER_RING);for(int ring=0; ring < NUM_VISIBILITY_RINGS; ring++) {float ring_radius_fraction=(float(ring)+1.0)/float(NUM_VISIBILITY_RINGS);for(int i=0; i < NUM_VISIBILITY_SAMPLES_PER_RING; i++) {vec2 extrusion=vec2(cos(step*float(i)),-sin(step*float(i)))*ring_radius_fraction;vec4 frag_pos=project_vertex(extrusion,occlusion_world_center,occlusion_projected_center,radius,stroke_width,perspective_scale,surface_vectors);terrain_visibility+=float(!isOccluded(frag_pos));}}terrain_visibility/=float(NUM_VISIBILITY_RINGS)*float(NUM_VISIBILITY_SAMPLES_PER_RING);\n#else\nterrain_visibility=1.0;\n#endif\n#ifdef PROJECTION_GLOBE_VIEW\nterrain_visibility=1.0;\n#endif\nv_visibility=terrain_visibility;lowp float antialiasblur=1.0/u_device_pixel_ratio/(radius+stroke_width);v_data=vec3(extrude.x,extrude.y,antialiasblur);\n#ifdef FOG\nv_fog_pos=fog_position(world_center.xyz);\n#endif\n}'),clippingMask:pu("void main() {glFragColor=vec4(1.0);}","in ivec2 a_pos;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);}"),heatmap:pu('#include "_prelude_fog.fragment.glsl"\nuniform highp float u_intensity;in 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);glFragColor=vec4(val,1.0,1.0,1.0);\n#ifdef FOG\nif (u_is_globe==0) {glFragColor.r*=pow(1.0-fog_opacity(v_fog_pos),2.0);}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}','#include "_prelude_terrain.vertex.glsl"\n#include "_prelude_fog.vertex.glsl"\nuniform mat4 u_matrix;uniform float u_extrude_scale;uniform float u_intensity;in ivec2 a_pos;\n#ifdef PROJECTION_GLOBE_VIEW\nin ivec4 a_pos_3;in ivec4 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir;\n#endif\nout 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() {\n#pragma mapbox: initialize highp float weight\n#pragma mapbox: initialize mediump float radius\nvec2 unscaled_extrude=vec2(mod(vec2(a_pos),2.0)*2.0-1.0);float S=sqrt(-2.0*log(ZERO/weight/u_intensity/GAUSS_COEF))/3.0;v_extrude=S*unscaled_extrude;vec2 extrude=v_extrude*radius*u_extrude_scale;vec2 tilePos=floor(vec2(a_pos)*0.5);vec3 pos;\n#ifdef PROJECTION_GLOBE_VIEW\nvec3 pos_normal_3=vec3(a_pos_normal_3)/16384.0;mat3 surface_vectors=globe_mercator_surface_vectors(pos_normal_3,u_up_dir,u_zoom_transition);vec3 surface_extrusion=extrude.x*surface_vectors[0]+extrude.y*surface_vectors[1];vec3 globe_elevation=elevationVector(tilePos)*elevation(tilePos);vec3 globe_pos=vec3(a_pos_3)+surface_extrusion+globe_elevation;vec3 mercator_elevation=u_up_dir*u_tile_up_scale*elevation(tilePos);vec3 merc_pos=mercator_tile_position(u_inv_rot_matrix,tilePos,u_tile_id,u_merc_center)+surface_extrusion+mercator_elevation;pos=mix_globe_mercator(globe_pos,merc_pos,u_zoom_transition);\n#else\npos=vec3(tilePos+extrude,elevation(tilePos));\n#endif\ngl_Position=u_matrix*vec4(pos,1);\n#ifdef FOG\nv_fog_pos=fog_position(pos);\n#endif\n}'),heatmapTexture:pu("uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;in vec2 v_pos;void main() {float t=texture(u_image,v_pos).r;vec4 color=texture(u_color_ramp,vec2(t,0.5));glFragColor=color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(0.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}","in ivec2 a_pos;out vec2 v_pos;void main() {gl_Position=vec4(a_pos,0,1);v_pos=bottom_left_to_native_uv(vec2(a_pos)*0.5+0.5);}"),collisionBox:pu("in float v_placed;in float v_notUsed;void main() {vec4 red =vec4(1.0,0.0,0.0,1.0);vec4 blue=vec4(0.0,0.0,1.0,0.5);glFragColor =mix(red,blue,step(0.5,v_placed))*0.5;glFragColor*=mix(1.0,0.1,step(0.5,v_notUsed));}",'#include "_prelude_terrain.vertex.glsl"\nin ivec4 a_pos;in ivec2 a_anchor_pos;in ivec2 a_extrude;in uvec2 a_placed;in vec2 a_shift;in vec2 a_elevation_from_sea;in float a_size_scale;in vec2 a_padding;in float a_auto_z_offset;uniform mat4 u_matrix;uniform vec2 u_extrude_scale;uniform float u_camera_to_center_distance;\n#ifdef PROJECTION_GLOBE_VIEW\nuniform vec3 u_tile_id;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform float u_zoom_transition;\n#endif\nout float v_placed;out float v_notUsed;void main() {vec2 anchor_pos=vec2(a_anchor_pos);float feature_elevation=a_elevation_from_sea.x+a_auto_z_offset;float terrain_elevation=(a_elevation_from_sea.y==1.0 ? 0.0 : elevation(anchor_pos));vec3 proj_pos=vec3(a_pos)+elevationVector(anchor_pos)*(feature_elevation+terrain_elevation);\n#ifdef PROJECTION_GLOBE_VIEW\n#ifndef PROJECTED_POS_ON_VIEWPORT\nvec3 globe_pos=proj_pos;vec3 mercator_pos=mercator_tile_position(u_inv_rot_matrix,anchor_pos,u_tile_id,u_merc_center);proj_pos=mix_globe_mercator(globe_pos,mercator_pos,u_zoom_transition);\n#endif\n#endif\nvec4 projectedPoint=u_matrix*vec4(proj_pos,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float collision_perspective_ratio=clamp(\n0.5+0.5*(u_camera_to_center_distance/camera_to_anchor_distance),0.0,1.5);gl_Position=projectedPoint;gl_Position.xy+=(vec2(a_extrude)*a_size_scale+a_shift+a_padding)*u_extrude_scale*gl_Position.w*collision_perspective_ratio;v_placed=float(a_placed.x);v_notUsed=float(a_placed.y);}'),collisionCircle:pu("in float v_radius;in vec2 v_extrude;in float v_perspective_ratio;in float v_collision;void main() {float alpha=0.5*min(v_perspective_ratio,1.0);float stroke_radius=0.9*max(v_perspective_ratio,1.0);float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);glFragColor=color*alpha*opacity_t;}","in vec2 a_pos_2f;in float a_radius;in ivec2 a_flags;uniform mat4 u_matrix;uniform mat4 u_inv_matrix;uniform vec2 u_viewport_size;uniform float u_camera_to_center_distance;out float v_radius;out vec2 v_extrude;out float v_perspective_ratio;out float v_collision;vec3 toTilePosition(vec2 screenPos) {vec4 rayStart=u_inv_matrix*vec4(screenPos,-1.0,1.0);vec4 rayEnd =u_inv_matrix*vec4(screenPos, 1.0,1.0);rayStart.xyz/=rayStart.w;rayEnd.xyz /=rayEnd.w;highp float t=(0.0-rayStart.z)/(rayEnd.z-rayStart.z);return mix(rayStart.xyz,rayEnd.xyz,t);}void main() {vec2 anchorScreenPos=a_pos_2f;float radius=a_radius;int vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(\nmix(-1.0,1.0,float(vertexIdx >=2)),mix(-1.0,1.0,float(vertexIdx >=1 && vertexIdx <=2)));vec2 quadVertexExtent=quadVertexOffset*radius;vec3 tilePos=toTilePosition(anchorScreenPos);vec4 clipPos=u_matrix*vec4(tilePos,1.0);highp float camera_to_anchor_distance=clipPos.w;highp float collision_perspective_ratio=clamp(\n0.5+0.5*(u_camera_to_center_distance/camera_to_anchor_distance),0.0,4.0);float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_perspective_ratio=collision_perspective_ratio;v_collision=float(a_flags.x);gl_Position=vec4(clipPos.xyz/clipPos.w,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}"),placementDebug:pu("uniform vec4 u_color;uniform float u_outline_width;uniform float u_opacity;uniform float u_stroke_opacity;uniform float u_collision_padding_opacity;in vec2 v_offset;in vec2 v_half_size;in float v_is_circle;in float v_collision_padding;float boxDistance(vec2 offset,vec2 halfSize) {vec2 toCorner=abs(offset)-halfSize;return max(toCorner.x,toCorner.y);}float circleDistance(vec2 offset,float radius) {return length(offset)-radius;}float linearStep(float start,float end,float x) {return (clamp(x,start,end)-start)/(end-start);}float onePxLongLinearStepAt(float center,float x) {const float halfPx=0.5;return linearStep(center-halfPx,center+halfPx,x);}void main() {float distanceToEdge=mix(boxDistance(v_offset,v_half_size),circleDistance(v_offset,v_half_size.x),v_is_circle);float linearStepAtMinusOutlineWidth=onePxLongLinearStepAt(-u_outline_width,distanceToEdge);float linearStepAtZero=onePxLongLinearStepAt(0.0,distanceToEdge);float linearStepAtCollisionPadding=onePxLongLinearStepAt(v_collision_padding,distanceToEdge);float interiorCoverage=1.0-linearStepAtMinusOutlineWidth;float outlineCoverage=linearStepAtMinusOutlineWidth-linearStepAtZero;float collisionPaddingCoverage=linearStepAtZero-linearStepAtCollisionPadding;glFragColor=u_color*(u_opacity*interiorCoverage+u_stroke_opacity*outlineCoverage+u_collision_padding_opacity*collisionPaddingCoverage);}","\nin vec2 a_pos_2f;in vec2 a_size;in float a_collision_padding;in ivec2 a_flags;uniform vec2 u_viewport_size;out vec2 v_offset;out vec2 v_half_size;out float v_is_circle;out float v_collision_padding;const vec2 QUAD_CORNERS[4]=vec2[4](vec2(-1.0,-1.0),vec2(1.0,-1.0),vec2(1.0,1.0),vec2(-1.0,1.0));const float AA_width=1.0;void main() {vec2 offset=QUAD_CORNERS[a_flags.y]*(a_size+a_collision_padding+AA_width);v_offset=offset;v_half_size=a_size;v_is_circle=float(a_flags.x);v_collision_padding=a_collision_padding;vec2 viewportPos=(a_pos_2f+offset)/u_viewport_size;gl_Position=vec4(viewportPos*vec2(2.0,-2.0)+vec2(-1.0,1.0),0.0,1.0);}"),debug:pu("uniform highp vec4 u_color;uniform sampler2D u_overlay;in vec2 v_uv;void main() {vec4 overlay_color=texture(u_overlay,v_uv);glFragColor=mix(u_color,overlay_color,overlay_color.a);}",'#include "_prelude_terrain.vertex.glsl"\nin ivec2 a_pos;\n#ifdef PROJECTION_GLOBE_VIEW\nin ivec4 a_pos_3;\n#endif\nout vec2 v_uv;uniform mat4 u_matrix;uniform float u_overlay_scale;void main() {vec2 pos=vec2(a_pos);float h=elevation(pos);v_uv=pos/8192.0;\n#ifdef PROJECTION_GLOBE_VIEW\ngl_Position=u_matrix*vec4(vec3(a_pos_3)+elevationVector(pos)*h,1);\n#else\ngl_Position=u_matrix*vec4(pos*u_overlay_scale,h,1);\n#endif\n}'),fill:pu('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_lighting.glsl"\n#include "_prelude_shadow.fragment.glsl"\n#include "_prelude_indicator_cutout.fragment.glsl"\n#include "_prelude_feature_cutout.fragment.glsl"\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nuniform float u_emissive_strength;uniform lowp float u_opacity_multiplier;\n#ifdef RENDER_SHADOWS\nuniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth;\n#endif\n#ifdef ELEVATED_ROADS\nin highp float v_road_z_offset;\n#endif\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\nvec2 cutout_factors=vec2(0.0);vec4 out_color=color;\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength);\n#ifdef RENDER_SHADOWS\nfloat light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y);out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light);\n#endif\n#endif\n#ifdef FOG\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\n#endif\nout_color*=(opacity*u_opacity_multiplier);glFragColor=out_color;storeEmissiveColor(glFragColor,u_emissive_strength);\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}','#include "_prelude_fog.vertex.glsl"\n#include "_prelude_shadow.vertex.glsl"\nin ivec2 a_pos;\n#ifdef ELEVATED_ROADS\nin float a_road_z_offset;out highp float v_road_z_offset;\n#endif\n#ifdef RENDER_SHADOWS\nuniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth;\n#endif\nuniform mat4 u_matrix;uniform lowp float u_opacity_multiplier;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp float z_offset\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp float z_offset\n#ifdef ELEVATED_ROADS\nz_offset+=a_road_z_offset;v_road_z_offset=z_offset;\n#endif\nfloat hidden=float(opacity==0.0);gl_Position=mix(u_matrix*vec4(a_pos,z_offset,1),AWAY,hidden);\n#ifdef RENDER_SHADOWS\nvec3 shd_pos0=vec3(a_pos,z_offset);vec3 shd_pos1=vec3(a_pos,z_offset);\n#ifdef NORMAL_OFFSET\nvec3 offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1();\n#endif\nv_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w;\n#endif\n#ifdef FOG\nv_fog_pos=fog_position(vec2(a_pos));\n#endif\n}'),fillOutline:pu('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_lighting.glsl"\n#include "_prelude_shadow.fragment.glsl"\n#include "_prelude_feature_cutout.fragment.glsl"\nin highp vec2 v_pos;uniform float u_emissive_strength;uniform lowp float u_opacity_multiplier;\n#ifdef ELEVATED_ROADS\nin highp float v_road_z_offset;\n#endif\n#ifdef RENDER_SHADOWS\nuniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp 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);vec4 out_color=outline_color;vec2 cutout_factors=vec2(0.0);\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength);\n#ifdef RENDER_SHADOWS\nfloat light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y);out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light);\n#endif\n#endif\n#ifdef FOG\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\n#endif\nglFragColor=out_color*(alpha*opacity*u_opacity_multiplier);storeEmissiveColor(glFragColor,u_emissive_strength);\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}','#include "_prelude_fog.vertex.glsl"\n#include "_prelude_shadow.vertex.glsl"\nin ivec2 a_pos;\n#ifdef ELEVATED_ROADS\nin float a_road_z_offset;out highp float v_road_z_offset;\n#endif\n#ifdef RENDER_SHADOWS\nuniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth;\n#endif\nuniform mat4 u_matrix;uniform vec2 u_world;uniform lowp float u_opacity_multiplier;out highp vec2 v_pos;\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp float z_offset\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp float z_offset\n#ifdef ELEVATED_ROADS\nz_offset+=a_road_z_offset;v_road_z_offset=z_offset;\n#endif\nfloat hidden=float(opacity==0.0);gl_Position=mix(u_matrix*vec4(a_pos,z_offset,1),AWAY,hidden);v_pos=ndc_xy_to_framebuffer_uv(gl_Position.xy/gl_Position.w)*u_world;\n#ifdef RENDER_SHADOWS\nvec3 shd_pos0=vec3(a_pos,z_offset);vec3 shd_pos1=vec3(a_pos,z_offset);\n#ifdef NORMAL_OFFSET\nvec3 offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1();\n#endif\nv_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w;\n#endif\n#ifdef FOG\nv_fog_pos=fog_position(vec2(a_pos));\n#endif\n}'),fillOutlinePattern:pu('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_lighting.glsl"\n#include "_prelude_shadow.fragment.glsl"\n#include "_prelude_feature_cutout.fragment.glsl"\nuniform vec2 u_texsize;uniform sampler2D u_image;\n#ifdef FILL_PATTERN_TRANSITION\nuniform float u_pattern_transition;\n#endif\nuniform float u_emissive_strength;uniform lowp float u_opacity_multiplier;\n#ifdef APPLY_LUT_ON_GPU\nuniform highp sampler3D u_lutTexture;\n#endif\n#ifdef RENDER_SHADOWS\nuniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth;\n#endif\n#ifdef ELEVATED_ROADS\nin highp float v_road_z_offset;\n#endif\nin highp vec2 v_pos;in highp vec2 v_pos_world;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp uvec4 pattern\n#ifdef FILL_PATTERN_TRANSITION\n#pragma mapbox: define mediump uvec4 pattern_b\n#endif\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump uvec4 pattern\n#ifdef FILL_PATTERN_TRANSITION\n#pragma mapbox: initialize mediump uvec4 pattern_b\n#endif\nvec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);highp vec2 imagecoord=mod(v_pos,1.0);highp vec2 pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,imagecoord);highp vec2 lod_pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,v_pos);float dist=length(v_pos_world-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);vec4 out_color=textureLodCustom(u_image,pos,lod_pos);\n#ifdef APPLY_LUT_ON_GPU\nout_color=applyLUT(u_lutTexture,out_color);\n#endif\n#ifdef FILL_PATTERN_TRANSITION\nvec2 pattern_b_tl=vec2(pattern_b.xy);vec2 pattern_b_br=vec2(pattern_b.zw);highp vec2 pos_b=mix(pattern_b_tl/u_texsize,pattern_b_br/u_texsize,imagecoord);vec4 color_b=textureLodCustom(u_image,pos_b,lod_pos);out_color=out_color*(1.0-u_pattern_transition)+color_b*u_pattern_transition;\n#endif\nvec2 cutout_factors=vec2(0.0);\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength);\n#ifdef RENDER_SHADOWS\nfloat light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y);out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light);\n#endif\n#endif\n#ifdef FOG\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\n#endif\nglFragColor=out_color*(alpha*opacity*u_opacity_multiplier);storeEmissiveColor(glFragColor,u_emissive_strength);\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}','#include "_prelude_fog.vertex.glsl"\n#include "_prelude_shadow.vertex.glsl"\nuniform mat4 u_matrix;uniform vec2 u_world;uniform lowp float u_opacity_multiplier;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_tile_units_to_pixels;in ivec2 a_pos;\n#ifdef ELEVATED_ROADS\nin float a_road_z_offset;out highp float v_road_z_offset;\n#endif\n#ifdef RENDER_SHADOWS\nuniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth;\n#endif\nout highp vec2 v_pos;out highp vec2 v_pos_world;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp uvec4 pattern\n#ifdef FILL_PATTERN_TRANSITION\n#pragma mapbox: define mediump uvec4 pattern_b\n#endif\n#pragma mapbox: define lowp float pixel_ratio\n#pragma mapbox: define highp float z_offset\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump uvec4 pattern\n#ifdef FILL_PATTERN_TRANSITION\n#pragma mapbox: initialize mediump uvec4 pattern_b\n#endif\n#pragma mapbox: initialize lowp float pixel_ratio\n#pragma mapbox: initialize highp float z_offset\nvec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);\n#ifdef ELEVATED_ROADS\nz_offset+=a_road_z_offset;v_road_z_offset=z_offset;\n#endif\nfloat hidden=float(opacity==0.0);vec2 pos=vec2(a_pos);gl_Position=mix(u_matrix*vec4(pos,z_offset,1),AWAY,hidden);vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio;v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,display_size,u_tile_units_to_pixels,pos);v_pos_world=ndc_xy_to_framebuffer_uv(gl_Position.xy/gl_Position.w)*u_world;\n#ifdef RENDER_SHADOWS\nvec3 shd_pos0=vec3(pos,z_offset);vec3 shd_pos1=vec3(pos,z_offset);\n#ifdef NORMAL_OFFSET\nvec3 offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1();\n#endif\nv_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w;\n#endif\n#ifdef FOG\nv_fog_pos=fog_position(pos);\n#endif\n}'),fillPattern:pu('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_lighting.glsl"\n#include "_prelude_shadow.fragment.glsl"\n#include "_prelude_feature_cutout.fragment.glsl"\nuniform vec2 u_texsize;uniform sampler2D u_image;\n#ifdef FILL_PATTERN_TRANSITION\nuniform float u_pattern_transition;\n#endif\nin highp vec2 v_pos;uniform float u_emissive_strength;uniform lowp float u_opacity_multiplier;\n#ifdef RENDER_SHADOWS\nuniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth;\n#endif\n#ifdef ELEVATED_ROADS\nin highp float v_road_z_offset;\n#endif\n#ifdef APPLY_LUT_ON_GPU\nuniform highp sampler3D u_lutTexture;\n#endif\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp uvec4 pattern\n#ifdef FILL_PATTERN_TRANSITION\n#pragma mapbox: define mediump uvec4 pattern_b\n#endif\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump uvec4 pattern\n#ifdef FILL_PATTERN_TRANSITION\n#pragma mapbox: initialize mediump uvec4 pattern_b\n#endif\nvec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);highp vec2 imagecoord=mod(v_pos,1.0);highp vec2 pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,imagecoord);highp vec2 lod_pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,v_pos);vec4 out_color=textureLodCustom(u_image,pos,lod_pos);\n#ifdef APPLY_LUT_ON_GPU\nout_color=applyLUT(u_lutTexture,out_color);\n#endif\n#ifdef FILL_PATTERN_TRANSITION\nvec2 pattern_b_tl=vec2(pattern_b.xy);vec2 pattern_b_br=vec2(pattern_b.zw);highp vec2 pos_b=mix(pattern_b_tl/u_texsize,pattern_b_br/u_texsize,imagecoord);vec4 color_b=textureLodCustom(u_image,pos_b,lod_pos);out_color=out_color*(1.0-u_pattern_transition)+color_b*u_pattern_transition;\n#endif\nvec2 cutout_factors=vec2(0.0);\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength);\n#ifdef RENDER_SHADOWS\nfloat light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y);\n#ifdef ELEVATED_ROADS\nout_color.rgb*=mix(v_road_z_offset !=0.0 ? u_ground_shadow_factor : vec3(1.0),vec3(1.0),light);\n#else\nout_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light);\n#endif\n#endif\n#endif\n#ifdef FOG\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\n#endif\nglFragColor=out_color*(opacity*u_opacity_multiplier);storeEmissiveColor(glFragColor,u_emissive_strength);\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}','#include "_prelude_fog.vertex.glsl"\n#include "_prelude_shadow.vertex.glsl"\nuniform mat4 u_matrix;uniform lowp float u_opacity_multiplier;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_tile_units_to_pixels;in ivec2 a_pos;\n#ifdef ELEVATED_ROADS\nin float a_road_z_offset;out highp float v_road_z_offset;\n#endif\n#ifdef RENDER_SHADOWS\nuniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth;\n#endif\nout highp vec2 v_pos;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp uvec4 pattern\n#ifdef FILL_PATTERN_TRANSITION\n#pragma mapbox: define mediump uvec4 pattern_b\n#endif\n#pragma mapbox: define lowp float pixel_ratio\n#pragma mapbox: define highp float z_offset\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump uvec4 pattern\n#pragma mapbox: initialize lowp float pixel_ratio\n#pragma mapbox: initialize highp float z_offset\n#ifdef FILL_PATTERN_TRANSITION\n#pragma mapbox: initialize mediump uvec4 pattern_b\n#endif\nvec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio;\n#ifdef ELEVATED_ROADS\nz_offset+=a_road_z_offset;v_road_z_offset=z_offset;\n#endif\nfloat hidden=float(opacity==0.0);vec2 pos=vec2(a_pos);gl_Position=mix(u_matrix*vec4(pos,z_offset,1),AWAY,hidden);v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,display_size,u_tile_units_to_pixels,pos);\n#ifdef RENDER_SHADOWS\nvec3 shd_pos0=vec3(pos,z_offset);vec3 shd_pos1=vec3(pos,z_offset);\n#ifdef NORMAL_OFFSET\nvec3 offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1();\n#endif\nv_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w;\n#endif\n#ifdef FOG\nv_fog_pos=fog_position(pos);\n#endif\n}'),lineBlendComposite:pu("uniform highp sampler2D u_image;uniform float u_opacity;uniform int u_blend_mode;uniform highp float u_max_density;in vec2 v_pos;\n#define ADDITIVE 1\nvoid main() {vec4 color=texture(u_image,v_pos);if (u_blend_mode==ADDITIVE) {if (color.a <=0.0) {discard;}highp float density=color.a;vec3 avgColor=color.rgb/max(density,0.001);highp float n=density/max(u_max_density,0.001);highp float t=sqrt(n/(n+1.0));glFragColor=vec4(avgColor*t,t);} else {vec3 multiplyFactor=color.rgb*u_opacity+(1.0-u_opacity);glFragColor=vec4(multiplyFactor,1.0);}\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(0.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}","in ivec2 a_pos;out vec2 v_pos;void main() {gl_Position=vec4(a_pos,0,1);v_pos=vec2(a_pos)*0.5+0.5;}"),lineBlendReduce:pu("uniform highp sampler2D u_image;uniform vec2 u_texel_size;uniform bool u_first_pass;in vec2 v_pos;void main() {vec2 o=u_texel_size*0.5;vec4 s0=texture(u_image,v_pos+vec2(-o.x,-o.y));vec4 s1=texture(u_image,v_pos+vec2( o.x,-o.y));vec4 s2=texture(u_image,v_pos+vec2(-o.x, o.y));vec4 s3=texture(u_image,v_pos+vec2( o.x, o.y));float r0; float g0;float r1; float g1;float r2; float g2;float r3; float g3;if (u_first_pass) {float a0=s0.a;float a1=s1.a;float a2=s2.a;float a3=s3.a;r0=a0; g0=a0 > 0.0 ? 1.0 : 0.0;r1=a1; g1=a1 > 0.0 ? 1.0 : 0.0;r2=a2; g2=a2 > 0.0 ? 1.0 : 0.0;r3=a3; g3=a3 > 0.0 ? 1.0 : 0.0;} else {r0=s0.r; g0=s0.g;r1=s1.r; g1=s1.g;r2=s2.r; g2=s2.g;r3=s3.r; g3=s3.g;}glFragColor=vec4((r0+r1+r2+r3)*0.25,(g0+g1+g2+g3)*0.25,0.0,0.0);}","in ivec2 a_pos;out vec2 v_pos;void main() {gl_Position=vec4(a_pos,0,1);v_pos=vec2(a_pos)*0.5+0.5;}"),fillExtrusion:pu('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_shadow.fragment.glsl"\n#include "_prelude_lighting.glsl"\n#include "_prelude_indicator_cutout.fragment.glsl"\n#include "_prelude_feature_cutout.fragment.glsl"\nin vec4 v_color;in vec4 v_flat;\n#if defined(RENDER_FRONT_CUTOFF) || defined(ROUTE_CORRIDOR)\nin float v_dither_opacity;\n#endif\n#ifdef RENDER_SHADOWS\nin highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;\n#endif\nuniform lowp float u_opacity;\n#ifdef FAUX_AO\nuniform lowp vec2 u_ao;in vec2 v_ao;\n#endif\n#if defined(ZERO_ROOF_RADIUS) && !defined(LIGHTING_3D_MODE)\nin vec4 v_roof_color;\n#endif\n#if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE)\nin highp vec3 v_normal;\n#endif\nuniform vec3 u_flood_light_color;uniform highp float u_vertical_scale;uniform float u_flood_light_intensity;uniform vec3 u_ground_shadow_factor;\n#if defined(LIGHTING_3D_MODE) && defined(FLOOD_LIGHT)\nin float v_flood_radius;in float v_has_floodlight;\n#endif\nin float v_height;\n#pragma mapbox: define highp float emissive_strength\nvoid main() {\n#pragma mapbox: initialize highp float emissive_strength\n#if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE)\nvec3 normal=normalize(v_normal);\n#endif\nfloat z;vec4 color=v_color;\n#ifdef ZERO_ROOF_RADIUS\nz=float(normal.z > 0.00001);\n#ifdef LIGHTING_3D_MODE\nnormal=mix(normal,vec3(0.0,0.0,1.0),z);\n#else\ncolor=mix(v_color,v_roof_color,z);\n#endif\n#endif\nfloat h=max(0.0,v_height);float ao_shade=1.0;\n#ifdef FAUX_AO\nfloat intensity=u_ao[0];float h_floors=h/(u_ao[1]*u_vertical_scale);float y_shade=1.0-0.9*intensity*min(v_ao.y,1.0);ao_shade=(1.0-0.08*intensity)*(y_shade+(1.0-y_shade)*(1.0-pow(1.0-min(h_floors/16.0,1.0),16.0)))+0.08*intensity*min(h_floors/160.0,1.0);float concave=v_ao.x*v_ao.x;\n#ifdef ZERO_ROOF_RADIUS\nconcave*=(1.0-z);\n#endif\nfloat x_shade=mix(1.0,mix(0.6,0.75,min(h_floors/30.0,1.0)),intensity)+0.1*intensity*min(h,1.0);ao_shade*=mix(1.0,x_shade*x_shade*x_shade,concave);\n#ifdef LIGHTING_3D_MODE\n#ifdef FLOOD_LIGHT\ncolor.rgb*=mix(ao_shade,1.0,v_has_floodlight);\n#else\ncolor.rgb*=ao_shade;\n#endif\n#else\ncolor.rgb*=ao_shade;\n#endif\n#endif\n#ifdef LIGHTING_3D_MODE\nfloat flood_radiance=0.0;\n#ifdef FLOOD_LIGHT\nflood_radiance=(1.0-min(h/v_flood_radius,1.0))*u_flood_light_intensity*v_has_floodlight;\n#endif\n#ifdef RENDER_SHADOWS\n#ifdef FLOOD_LIGHT\nfloat ndotl_unclamped=dot(normal,u_shadow_direction);float ndotl=max(0.0,ndotl_unclamped);float occlusion=ndotl_unclamped < 0.0 ? 1.0 : shadow_occlusion(ndotl,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w);vec3 litColor=apply_lighting(color.rgb,normal,(1.0-u_shadow_intensity*occlusion)*ndotl);vec3 floodLitColor=compute_flood_lighting(u_flood_light_color*u_opacity,1.0-u_shadow_intensity,occlusion,u_ground_shadow_factor);color.rgb=mix(litColor,floodLitColor,flood_radiance);\n#else\nfloat shadowed_lighting_factor;\n#ifdef RENDER_CUTOFF\nshadowed_lighting_factor=shadowed_light_factor_normal_opacity(normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w,v_cutoff_opacity);if (v_cutoff_opacity==0.0) {discard;}\n#else\nshadowed_lighting_factor=shadowed_light_factor_normal(normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w);\n#endif\ncolor.rgb=apply_lighting(color.rgb,normal,shadowed_lighting_factor);\n#endif\n#else\ncolor.rgb=apply_lighting(color.rgb,normal);\n#ifdef FLOOD_LIGHT\ncolor.rgb=mix(color.rgb,u_flood_light_color*u_opacity,flood_radiance);\n#endif\n#endif\ncolor.rgb=mix(color.rgb,v_flat.rgb,emissive_strength);color*=u_opacity;\n#endif\n#ifdef FOG\ncolor=fog_dither(fog_apply_premultiplied(color,v_fog_pos,h));\n#endif\n#if defined(RENDER_FRONT_CUTOFF) || defined(ROUTE_CORRIDOR)\nif (v_dither_opacity < 1.0) {int index=viewport_dither_index(gl_FragCoord.xy);if (v_dither_opacity < DITHER_THRESHOLDS[index]) {discard;}}\n#endif\nglFragColor=color;\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}','#include "_prelude_fog.vertex.glsl"\n#include "_prelude_terrain.vertex.glsl"\n#include "_prelude_shadow.vertex.glsl"\n#include "_prelude_lighting.glsl"\n#include "_prelude_material_table.vertex.glsl"\n#include "_prelude_feature_cutout.vertex.glsl"\nuniform mat4 u_matrix;\n#ifndef LIGHTING_3D_MODE\nuniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;\n#endif\nuniform float u_vertical_gradient;uniform lowp float u_opacity;uniform float u_edge_radius;uniform float u_width_scale;in ivec4 a_pos_normal_ed;\n#if defined(HAS_CENTROID) || defined(TERRAIN)\nin uvec2 a_centroid_pos;\n#endif\n#ifdef RENDER_WALL_MODE\nin ivec4 a_join_normal_inside;\n#endif\n#ifdef PROJECTION_GLOBE_VIEW\nin ivec4 a_pos_3;in ivec4 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir;uniform float u_height_lift;\n#endif\n#ifdef TERRAIN\nuniform int u_height_type;uniform int u_base_type;\n#endif\nuniform highp float u_vertical_scale;\n#if defined(RENDER_FRONT_CUTOFF) || defined(ROUTE_CORRIDOR)\n#ifdef RENDER_FRONT_CUTOFF\nuniform vec3 u_front_cutoff_params;\n#endif\nout float v_dither_opacity;\n#endif\nout vec4 v_color;out vec4 v_flat;\n#ifdef RENDER_SHADOWS\nuniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;\n#endif\n#if defined(ZERO_ROOF_RADIUS) && !defined(LIGHTING_3D_MODE)\nout vec4 v_roof_color;\n#endif\n#if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE)\nout highp vec3 v_normal;\n#endif\n#ifdef FAUX_AO\nuniform lowp vec2 u_ao;out vec2 v_ao;invariant gl_Position;\n#endif\n#if defined(LIGHTING_3D_MODE) && defined(FLOOD_LIGHT)\nout float v_flood_radius;out float v_has_floodlight;\n#endif\nout float v_height;vec3 linearTosRGB(vec3 color) {return pow(color,vec3(1./2.2));}vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));}\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define highp float flood_light_wall_radius\n#pragma mapbox: define highp float line_width\n#pragma mapbox: define highp float emissive_strength\nvoid main() {DECLARE_MATERIAL_TABLE_INFO\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize highp float flood_light_wall_radius\n#pragma mapbox: initialize highp float line_width\n#pragma mapbox: initialize highp float emissive_strength\nbase*=u_vertical_scale;height*=u_vertical_scale;vec4 top_up_ny_start=vec4(a_pos_normal_ed & 1);vec4 pos_nx=vec4(a_pos_normal_ed >> 1);float x_normal=pos_nx.z/8192.0;vec3 normal=top_up_ny_start.y==1.0 ? vec3(0.0,0.0,1.0) : normalize(vec3(x_normal,(2.0*top_up_ny_start.z-1.0)*(1.0-abs(x_normal)),0.0));\n#if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE)\nv_normal=normal;\n#endif\nbase=max(0.0,base);float attr_height=height;height=max(0.0,top_up_ny_start.y==0.0 && top_up_ny_start.x==1.0 ? height-u_edge_radius : height);float t=top_up_ny_start.x;vec2 centroid_pos=vec2(0.0);\n#if defined(HAS_CENTROID) || defined(TERRAIN)\ncentroid_pos=vec2(a_centroid_pos);\n#endif\nfloat ele=0.0;float h=0.0;float c_ele=0.0;vec3 pos;\n#ifdef TERRAIN\nbool is_flat_height=centroid_pos.x !=0.0 && u_height_type==1;bool is_flat_base=centroid_pos.x !=0.0 && u_base_type==1;ele=elevation(pos_nx.xy);bool is_elevation_encoded=centroid_pos.y==0.0 || (centroid_pos.y > 0.0 && (int(centroid_pos.y) & 7)==7);c_ele=is_flat_height || is_flat_base ? (is_elevation_encoded ? elevationFromUint16(centroid_pos.x) : flatElevation(centroid_pos)) : ele;float h_height=is_flat_height ? max(c_ele+height,ele+base+2.0) : ele+height;float h_base=is_flat_base ? max(c_ele+base,ele+base) : ele+(base==0.0 ?-5.0 : base);h=t > 0.0 ? max(h_base,h_height) : h_base;\n#else\nh=t > 0.0 ? height : base;\n#endif\npos=vec3(pos_nx.xy,h);\n#ifdef PROJECTION_GLOBE_VIEW\nfloat lift=float((t+base) > 0.0)*u_height_lift;h+=lift;vec3 globe_normal=normalize(mix(vec3(a_pos_normal_3)/16384.0,u_up_dir,u_zoom_transition));vec3 globe_pos=vec3(a_pos_3)+globe_normal*(u_tile_up_scale*h);vec3 merc_pos=mercator_tile_position(u_inv_rot_matrix,pos.xy,u_tile_id,u_merc_center)+u_up_dir*u_tile_up_scale*pos.z;pos=mix_globe_mercator(globe_pos,merc_pos,u_zoom_transition);\n#endif\nfloat cutoff=1.0;vec3 scaled_pos=pos;\n#if defined(RENDER_CUTOFF) || defined(RENDER_FRONT_CUTOFF) || defined(ROUTE_CORRIDOR)\nvec2 centroid_decoded=pos.xy;bool isBorderCentroid=false;if (centroid_pos.x > 0.0 && centroid_pos.y > 0.0) {int iy=int(centroid_pos.y);int spanYbits=iy & 7;if (spanYbits==7) {isBorderCentroid=true;int borderID=(iy >> 3) & 3;float coordAlongBorder=float(iy >> 5)*4.0;if (borderID==0) centroid_decoded=vec2(0.0,coordAlongBorder);else if (borderID==1) centroid_decoded=vec2(EXTENT,coordAlongBorder);else if (borderID==2) centroid_decoded=vec2(coordAlongBorder,0.0);else centroid_decoded=vec2(coordAlongBorder,EXTENT);} else {centroid_decoded=floor(centroid_pos/8.0);}}\n#endif\n#if defined(RENDER_FRONT_CUTOFF) || defined(ROUTE_CORRIDOR)\nfloat frontCutoffOpacity=1.0;float routeFade=0.0;\n#endif\n#if defined(RENDER_CUTOFF) || defined(RENDER_FRONT_CUTOFF)\nvec4 ground=u_matrix*vec4(centroid_decoded,ele,1.0);\n#endif\n#ifdef RENDER_CUTOFF\ncutoff=cutoff_opacity(u_cutoff_params,native_clip_z_to_cutoff_depth(ground.z,ground.w));if (centroid_pos.y !=0.0 && centroid_pos.x !=0.0) {vec3 centroid_random=vec3(centroid_pos.xy,centroid_pos.x+centroid_pos.y+1.0);vec3 ground_pos=centroid_random/8.0;vec3 g=floor(ground_pos);vec3 mod_=centroid_random-g*8.0;float seed=min(1.0,0.1*(min(3.5,max(mod_.x+mod_.y,0.2*attr_height))*0.35+mod_.z));if (cutoff < 0.8-seed) {cutoff=0.0;}}float cutoff_scale=cutoff;v_cutoff_opacity=cutoff;scaled_pos.z=mix(c_ele,h,cutoff_scale);\n#endif\nfloat hidden=float((centroid_pos.x==0.0 && centroid_pos.y==1.0) || (cutoff==0.0 && centroid_pos.x !=0.0) || (color.a==0.0));\n#ifdef RENDER_FRONT_CUTOFF\nif (centroid_pos.x > 0.0 && centroid_pos.y > 0.0) {hidden=max(hidden,float(ground.w <=0.0));float ndc_y=ground.y/max(ground.w,0.001);float threshold=u_front_cutoff_params.x*2.0-1.0;float range_ndc=u_front_cutoff_params.y*2.0;if (!isBorderCentroid) {hidden=max(hidden,float(ndc_y < threshold-range_ndc));}float t=clamp((ndc_y-(threshold-range_ndc))/max(range_ndc,0.001),0.0,1.0);frontCutoffOpacity=mix(u_front_cutoff_params.z,1.0,t);}\n#endif\n#if defined(RENDER_FRONT_CUTOFF) || defined(ROUTE_CORRIDOR)\nv_dither_opacity=1.0;\n#ifdef RENDER_FRONT_CUTOFF\nv_dither_opacity=min(v_dither_opacity,frontCutoffOpacity);\n#endif\nif (centroid_pos.x > 0.0 && centroid_pos.y > 0.0) {hidden=max(hidden,float(v_dither_opacity <=0.0));}\n#endif\n#ifdef RENDER_WALL_MODE\nvec3 join_normal_inside=vec3(a_join_normal_inside);vec2 wall_offset=u_width_scale*line_width*(join_normal_inside.xy/EXTENT);scaled_pos.xy+=(1.0-join_normal_inside.z)*wall_offset*0.5;scaled_pos.xy-=join_normal_inside.z*wall_offset*0.5;\n#endif\ngl_Position=mix(u_matrix*vec4(scaled_pos,1),AWAY,hidden);h=h-ele;v_height=h;\n#ifdef RENDER_SHADOWS\nvec3 shd_pos0=pos;vec3 shd_pos1=pos;\n#ifdef NORMAL_OFFSET\nvec3 offset=shadow_normal_offset(normal);shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1();\n#endif\nv_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);\n#endif\nfloat NdotL=0.0;float colorvalue=0.0;\n#ifndef LIGHTING_3D_MODE\ncolorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;NdotL=clamp(dot(normal,u_lightpos),0.0,1.0);NdotL=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),NdotL);if (normal.y !=0.0) {float r=0.84;r=mix(0.7,0.98,1.0-u_lightintensity);NdotL*=(\n(1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),r,1.0)));}\n#endif\n#ifdef FAUX_AO\nfloat concave=pos_nx.w-floor(pos_nx.w*0.5)*2.0;float start=top_up_ny_start.w;float y_ground=1.0-clamp(t+base,0.0,1.0);float top_height=height;\n#ifdef TERRAIN\ntop_height=mix(max(c_ele+height,ele+base+2.0),ele+height,float(centroid_pos.x==0.0))-ele;y_ground+=y_ground*5.0/max(3.0,top_height);\n#endif\nv_ao=vec2(mix(concave,-concave,start),y_ground);NdotL*=(1.0+0.05*(1.0-top_up_ny_start.y)*u_ao[0]);\n#ifdef PROJECTION_GLOBE_VIEW\ntop_height+=u_height_lift;\n#endif\nfloat z_bias=native_depth_epsilon(0.0000006);gl_Position.z-=(z_bias*(min(top_height,500.)+2.0*min(base,500.0)+60.0*concave+3.0*start))*gl_Position.w;\n#endif\n#ifdef LIGHTING_3D_MODE\n#ifdef FLOOD_LIGHT\nfloat is_wall=1.0-float(t > 0.0 && top_up_ny_start.y > 0.0);v_has_floodlight=float(flood_light_wall_radius > 0.0 && is_wall > 0.0);v_flood_radius=flood_light_wall_radius*u_vertical_scale;\n#endif\nv_color=vec4(color.rgb,1.0);float ndotl=calculate_NdotL(normal);v_flat.rgb=sRGBToLinear(color.rgb);v_flat.rgb=v_flat.rgb*(ndotl+(1.0-min(ndotl*57.29,1.0))*emissive_strength);v_flat=vec4(linearTosRGB(v_flat.rgb),1.0);\n#else\nv_color=vec4(0.0,0.0,0.0,1.0);v_color.rgb+=clamp(color.rgb*NdotL*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_color*=u_opacity;\n#endif\n#if defined(ZERO_ROOF_RADIUS) && !defined(LIGHTING_3D_MODE)\nfloat roofNdotL=clamp(u_lightpos.z,0.0,1.0);roofNdotL=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),roofNdotL);v_roof_color=vec4(0.0,0.0,0.0,1.0);v_roof_color.rgb+=clamp(color.rgb*roofNdotL*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_roof_color*=u_opacity;\n#endif\n#ifdef FOG\nv_fog_pos=fog_position(pos);\n#endif\n}'),fillExtrusionPattern:pu('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_lighting.glsl"\n#include "_prelude_indicator_cutout.fragment.glsl"\nuniform vec2 u_texsize;uniform sampler2D u_image;\n#ifdef FILL_EXTRUSION_PATTERN_TRANSITION\nuniform float u_pattern_transition;\n#endif\n#ifdef FAUX_AO\nuniform lowp vec2 u_ao;in vec3 v_ao;\n#endif\n#ifdef LIGHTING_3D_MODE\nin vec3 v_normal;\n#endif\n#ifdef APPLY_LUT_ON_GPU\nuniform highp sampler3D u_lutTexture;\n#endif\nin highp vec2 v_pos;in vec4 v_lighting;uniform lowp float u_opacity;\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define mediump uvec4 pattern\n#ifdef FILL_EXTRUSION_PATTERN_TRANSITION\n#pragma mapbox: define mediump uvec4 pattern_b\n#endif\n#pragma mapbox: define highp float pixel_ratio\nvoid main() {\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize mediump uvec4 pattern\n#ifdef FILL_EXTRUSION_PATTERN_TRANSITION\n#pragma mapbox: initialize mediump uvec4 pattern_b\n#endif\n#pragma mapbox: initialize highp float pixel_ratio\nvec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);highp vec2 imagecoord=mod(v_pos,1.0);highp vec2 pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,imagecoord);highp vec2 lod_pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,v_pos);vec4 out_color=textureLodCustom(u_image,pos,lod_pos);\n#ifdef APPLY_LUT_ON_GPU\nout_color=applyLUT(u_lutTexture,out_color);\n#endif\n#ifdef FILL_EXTRUSION_PATTERN_TRANSITION\nvec2 pattern_b_tl=vec2(pattern_b.xy);vec2 pattern_b_br=vec2(pattern_b.zw);highp vec2 pos_b=mix(pattern_b_tl/u_texsize,pattern_b_br/u_texsize,imagecoord);vec4 color_b=textureLodCustom(u_image,pos_b,lod_pos);out_color=out_color*(1.0-u_pattern_transition)+color_b*u_pattern_transition;\n#endif\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting(out_color,normalize(v_normal))*u_opacity;\n#else\nout_color=out_color*v_lighting;\n#endif\n#ifdef FAUX_AO\nfloat intensity=u_ao[0];float h=max(0.0,v_ao.z);float h_floors=h/u_ao[1];float y_shade=1.0-0.9*intensity*min(v_ao.y,1.0);float shade=(1.0-0.08*intensity)*(y_shade+(1.0-y_shade)*(1.0-pow(1.0-min(h_floors/16.0,1.0),16.0)))+0.08*intensity*min(h_floors/160.0,1.0);float concave=v_ao.x*v_ao.x;float x_shade=mix(1.0,mix(0.6,0.75,min(h_floors/30.0,1.0)),intensity)+0.1*intensity*min(h,1.0);shade*=mix(1.0,x_shade*x_shade*x_shade,concave);out_color.rgb=out_color.rgb*shade;\n#endif\n#ifdef FOG\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\n#endif\nglFragColor=out_color;\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}','#include "_prelude_fog.vertex.glsl"\n#include "_prelude_terrain.vertex.glsl"\n#include "_prelude_lighting.glsl"\n#include "_prelude_material_table.vertex.glsl"\nuniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform float u_tile_units_to_pixels;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform float u_width_scale;\n#ifndef LIGHTING_3D_MODE\nuniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;\n#endif\nin ivec4 a_pos_normal_ed;\n#if defined(HAS_CENTROID) || defined(TERRAIN)\nin uvec2 a_centroid_pos;\n#endif\n#ifdef RENDER_WALL_MODE\nin ivec4 a_join_normal_inside;\n#endif\n#ifdef PROJECTION_GLOBE_VIEW\nin ivec4 a_pos_3;in ivec4 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir;uniform float u_height_lift;\n#endif\n#ifdef TERRAIN\nuniform int u_height_type;uniform int u_base_type;\n#endif\nout highp vec2 v_pos;out vec4 v_lighting;\n#ifdef FAUX_AO\nuniform lowp vec2 u_ao;out vec3 v_ao;invariant gl_Position;\n#endif\n#ifdef LIGHTING_3D_MODE\nout vec3 v_normal;\n#endif\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump uvec4 pattern\n#ifdef FILL_EXTRUSION_PATTERN_TRANSITION\n#pragma mapbox: define mediump uvec4 pattern_b\n#endif\n#pragma mapbox: define highp float pixel_ratio\n#pragma mapbox: define highp float line_width\nvoid main() {DECLARE_MATERIAL_TABLE_INFO\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump uvec4 pattern\n#ifdef FILL_EXTRUSION_PATTERN_TRANSITION\n#pragma mapbox: initialize mediump uvec4 pattern_b\n#endif\n#pragma mapbox: initialize highp float pixel_ratio\n#pragma mapbox: initialize highp float line_width\nvec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);vec4 top_up_ny_start=vec4(a_pos_normal_ed & 1);vec4 pos_nx=vec4(a_pos_normal_ed >> 1);float x_normal=pos_nx.z/8192.0;vec3 normal=top_up_ny_start.y==1.0 ? vec3(0.0,0.0,1.0) : normalize(vec3(x_normal,(2.0*top_up_ny_start.z-1.0)*(1.0-abs(x_normal)),0.0));float edgedistance=float(a_pos_normal_ed.w);vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio;base=max(0.0,base);height=max(0.0,height);float t=top_up_ny_start.x;float z=t > 0.0 ? height : base;vec2 centroid_pos=vec2(0.0);\n#if defined(HAS_CENTROID) || defined(TERRAIN)\ncentroid_pos=vec2(a_centroid_pos);\n#endif\nfloat ele=0.0;float h=z;vec3 p;float c_ele;\n#ifdef TERRAIN\nbool is_flat_height=centroid_pos.x !=0.0 && u_height_type==1;bool is_flat_base=centroid_pos.x !=0.0 && u_base_type==1;ele=elevation(pos_nx.xy);bool is_elevation_encoded=centroid_pos.y==0.0 || (centroid_pos.y > 0.0 && int(centroid_pos.y)-(int(centroid_pos.y)/8)*8==7);c_ele=is_flat_height || is_flat_base ? (is_elevation_encoded ? elevationFromUint16(centroid_pos.x) : flatElevation(centroid_pos)) : ele;float h_height=is_flat_height ? max(c_ele+height,ele+base+2.0) : ele+height;float h_base=is_flat_base ? max(c_ele+base,ele+base) : ele+(base==0.0 ?-5.0 : base);h=t > 0.0 ? max(h_base,h_height) : h_base;p=vec3(pos_nx.xy,h);\n#else\np=vec3(pos_nx.xy,z);\n#endif\n#ifdef PROJECTION_GLOBE_VIEW\nfloat lift=float((t+base) > 0.0)*u_height_lift;h+=lift;vec3 globe_normal=normalize(mix(vec3(a_pos_normal_3)/16384.0,u_up_dir,u_zoom_transition));vec3 globe_pos=vec3(a_pos_3)+globe_normal*(u_tile_up_scale*(p.z+lift));vec3 merc_pos=mercator_tile_position(u_inv_rot_matrix,p.xy,u_tile_id,u_merc_center)+u_up_dir*u_tile_up_scale*p.z;p=mix_globe_mercator(globe_pos,merc_pos,u_zoom_transition);\n#endif\n#ifdef RENDER_WALL_MODE\nvec3 join_normal_inside=vec3(a_join_normal_inside);vec2 wall_offset=u_width_scale*line_width*(join_normal_inside.xy/EXTENT);p.xy+=(1.0-join_normal_inside.z)*wall_offset*0.5;p.xy-=join_normal_inside.z*wall_offset*0.5;\n#endif\nfloat hidden=float((centroid_pos.x==0.0 && centroid_pos.y==1.0) || (color.a==0.0));gl_Position=mix(u_matrix*vec4(p,1),AWAY,hidden);vec2 pos=normal.z==1.0\n? pos_nx.xy\n: vec2(edgedistance,z*u_height_factor);v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,display_size,u_tile_units_to_pixels,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float NdotL=0.0;\n#ifdef LIGHTING_3D_MODE\nNdotL=calculate_NdotL(normal);\n#else\nNdotL=clamp(dot(normal,u_lightpos),0.0,1.0);NdotL=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),NdotL);\n#endif\nif (normal.y !=0.0) {float r=0.84;\n#ifndef LIGHTING_3D_MODE\nr=mix(0.7,0.98,1.0-u_lightintensity);\n#endif\nNdotL*=(\n(1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),r,1.0)));}\n#ifdef FAUX_AO\nfloat concave=pos_nx.w-floor(pos_nx.w*0.5)*2.0;float start=top_up_ny_start.w;float y_ground=1.0-clamp(t+base,0.0,1.0);float top_height=height;\n#ifdef TERRAIN\ntop_height=mix(max(c_ele+height,ele+base+2.0),ele+height,float(centroid_pos.x==0.0))-ele;y_ground+=y_ground*5.0/max(3.0,top_height);\n#endif\nv_ao=vec3(mix(concave,-concave,start),y_ground,h-ele);NdotL*=(1.0+0.05*(1.0-top_up_ny_start.y)*u_ao[0]);\n#ifdef PROJECTION_GLOBE_VIEW\ntop_height+=u_height_lift;\n#endif\nfloat z_bias=native_depth_epsilon(0.0000006);gl_Position.z-=(z_bias*(min(top_height,500.)+2.0*min(base,500.0)+60.0*concave+3.0*start))*gl_Position.w;\n#endif\n#ifdef LIGHTING_3D_MODE\nv_normal=normal;\n#else\nv_lighting.rgb+=clamp(NdotL*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity;\n#endif\n#ifdef FOG\nv_fog_pos=fog_position(p);\n#endif\n}'),hillshadePrepare:pu("precision highp float;uniform highp sampler2D u_image;in vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;float getElevation(vec2 coord) {return texture(u_image,coord).r/4.0;}void main() {vec2 epsilon=1.0/u_dimension;float a=getElevation(v_pos+vec2(-epsilon.x,-epsilon.y));float b=getElevation(v_pos+vec2(0,-epsilon.y));float c=getElevation(v_pos+vec2(epsilon.x,-epsilon.y));float d=getElevation(v_pos+vec2(-epsilon.x,0));float e=getElevation(v_pos+vec2(epsilon.x,0));float f=getElevation(v_pos+vec2(-epsilon.x,epsilon.y));float g=getElevation(v_pos+vec2(0,epsilon.y));float h=getElevation(v_pos+vec2(epsilon.x,epsilon.y));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(\n(c+e+e+h)-(a+d+d+f),(f+g+g+h)-(a+b+b+c)\n)/pow(2.0,exaggeration+(19.2562-u_zoom));glFragColor=clamp(vec4(\nderiv.x/2.0+0.5,deriv.y/2.0+0.5,1.0,1.0),0.0,1.0);}","uniform mat4 u_matrix;uniform vec2 u_dimension;in ivec2 a_pos;in uvec2 a_texture_pos;out 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=(vec2(a_texture_pos)/8192.0)*scale+epsilon;}"),hillshade:pu('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_lighting.glsl"\nuniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_latrange;uniform vec2 u_light;uniform vec4 u_shadow;uniform vec4 u_highlight;uniform vec4 u_accent;uniform float u_emissive_strength;void main() {vec4 pixel=texture(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);glFragColor=accent_color*(1.0-shade_color.a)+shade_color;\n#ifdef LIGHTING_3D_MODE\nglFragColor=apply_lighting_with_emission_ground(glFragColor,u_emissive_strength);\n#endif\n#ifdef FOG\nglFragColor=fog_dither(fog_apply_premultiplied(glFragColor,v_fog_pos));\n#endif\nstoreEmissiveColor(glFragColor,u_emissive_strength);\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}','#include "_prelude_fog.vertex.glsl"\nuniform mat4 u_matrix;in ivec2 a_pos;in uvec2 a_texture_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos=bottom_left_to_native_uv(vec2(a_texture_pos)/8192.0);\n#ifdef FOG\nv_fog_pos=fog_position(vec2(a_pos));\n#endif\n}'),line:pu('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_lighting.glsl"\n#include "_prelude_shadow.fragment.glsl"\n#include "_prelude_indicator_cutout.fragment.glsl"\n#include "_prelude_feature_cutout.fragment.glsl"\nuniform lowp float u_device_pixel_ratio;uniform highp float u_width_scale;uniform float u_alpha_discard_threshold;uniform lowp float u_opacity_multiplier;\n#ifdef ELEVATED_ROADS\nuniform bool u_clip_to_tile_borders;uniform vec4 u_child_quadrants;\n#endif\nin vec4 v_width2_dilute;in vec2 v_normal;in float v_gamma_scale;in highp vec2 v_tile_pos;\n#ifdef LINE_ROUND_JOIN_CLIP_BORDER_OVERLAP\nin highp vec4 v_round_join_conflict_offset;in highp vec4 v_round_join_conflict_dir;in mediump vec2 v_round_join_conflict_test;\n#endif\n#ifdef ELEVATED_ROADS\nin highp float v_road_z_offset;\n#endif\n#ifdef VARIABLE_LINE_WIDTH\nin float stub_side;in highp vec2 v_distance;uniform highp float u_width_addition;\n#endif\nuniform bool u_has_dash;uniform bool u_has_border;uniform sampler2D u_dash_image;uniform highp float u_floor_width_scale;in highp vec2 v_tex;\n#ifdef DEBUG_ELEVATION_ID\nin vec3 v_elevation_id_col;\n#endif\n#if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_BORDER_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET)\nin highp vec3 v_uv;\n#endif\n#ifdef RENDER_LINE_GRADIENT\nuniform sampler2D u_gradient_image;\n#endif\n#ifdef RENDER_LINE_BORDER_GRADIENT\nuniform sampler2D u_border_gradient_image;\n#endif\n#ifdef RENDER_LINE_TRIM_OFFSET\nuniform highp vec2 u_trim_offset;uniform highp vec2 u_trim_fade_range;uniform highp vec2 u_trim_gradient_mix_range;uniform lowp vec4 u_trim_color;\n#endif\n#ifdef RENDER_SHADOWS\nuniform bool u_emissive_in_shadows;uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth;\n#endif\nfloat luminance(vec3 c) {return (c.r+c.r+c.b+c.g+c.g+c.g)*0.1667;}in highp vec4 v_line_color;in lowp vec4 v_border_color;in lowp float v_opacity;in lowp float v_blur;in lowp float v_floorwidth;in lowp float v_border_width;in lowp float v_emissive_strength;in highp vec2 v_dash;\n#ifdef LINE_ROUND_JOIN_CLIP_BORDER_OVERLAP\nconst highp float ROUND_JOIN_NO_CONFLICT=32768.0;highp float roundJoinConflictDistance(highp vec2 conflictOffset,highp vec2 conflictDir,mediump float test) {if (test <=0.0) {return ROUND_JOIN_NO_CONFLICT;}highp float dirLenSq=max(dot(conflictDir,conflictDir),1e-6);highp float t=clamp(dot(conflictOffset,conflictDir)/dirLenSq,0.0,1.0);return length(conflictOffset-t*conflictDir);}float insideRoundJoinTestArea(highp float dist,vec2 testBounds,float pxStep) {float inside=1.0-smoothstep(testBounds.y-pxStep,testBounds.y+pxStep,dist);float pastGap=testBounds.x > 0.0 ? smoothstep(testBounds.x-pxStep,testBounds.x+pxStep,dist) : 1.0;return inside*pastGap;}float insideRoundJoinConflictBody(highp float dist,vec3 testBounds,float pxStep) {vec2 body=vec2(testBounds.x,testBounds.y-pxStep);return insideRoundJoinTestArea(dist,body,pxStep);}float insideRoundJoinConflictFill(highp float dist,vec3 testBounds,float pxStep) {float gap=testBounds.x;float outer=testBounds.y;float border=testBounds.z;vec2 fill=vec2(gap+(gap > 0.0 ? border : 0.0),max(outer-border,0.0));return insideRoundJoinTestArea(dist,fill,pxStep);}\n#endif\nfloat linearstep(float edge0,float edge1,float x) {return clamp((x-edge0)/(edge1-edge0),0.0,1.0);}void main() {highp vec4 color=vec4(v_line_color.rgb*v_line_color.a,v_line_color.a);float floorwidth=v_floorwidth;float blur=v_blur;float opacity=v_opacity;float border_width=v_border_width;vec4 border_color=vec4(v_border_color.rgb*v_border_color.a,v_border_color.a);float emissive_strength=v_emissive_strength;float dist=length(v_normal)*v_width2_dilute.x;float ANTIALIASING=1.0/u_device_pixel_ratio/2.0;\n#ifndef VARIABLE_LINE_WIDTH\nif (u_has_border) {ANTIALIASING*=8.0;}\n#endif\n#ifdef VARIABLE_LINE_WIDTH\nfloat opposite_blur=border_width > 0.0 ? abs(u_width_addition) : 0.0;blur=mix(blur,opposite_blur,stub_side);\n#endif\nfloat diluted_opacity=opacity*v_width2_dilute.z;float blur2=(u_width_scale*blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha;\n#ifdef VARIABLE_LINE_WIDTH\nfloat centre_distance=length(v_distance);float edge=mix(v_width2_dilute.y,v_width2_dilute.x,0.5+0.5*v_distance.y/max(centre_distance,1e-4));float inv_radius=1.0/max(length(vec4(dFdx(v_distance),dFdy(v_distance))),1e-4);vec2 edges=clamp((vec2(edge,-edge)-centre_distance)*inv_radius,-1.0,1.0);vec2 window=edges*(1.0-0.5*abs(edges));float blur_fade=clamp(edge*(1.0-centre_distance/(edge+ANTIALIASING))/blur2,0.0,1.0);alpha=mix(window.x-window.y,blur_fade,smoothstep(1.0,2.0,u_width_scale*blur*inv_radius));\n#else\nalpha=clamp(min(dist-(v_width2_dilute.y-blur2),v_width2_dilute.x-dist)/blur2,0.0,1.0);if (!u_has_border) {float half_band=0.5*(v_width2_dilute.x-v_width2_dilute.y);if (u_has_dash && blur < 0.01 && half_band >=ANTIALIASING) {float edge_hi=v_width2_dilute.x-ANTIALIASING;float edge_lo=v_width2_dilute.y > 0.0 ? v_width2_dilute.y-ANTIALIASING :-edge_hi;float px=max(blur2,1e-6);float true_px=min(length(vec2(dFdx(v_normal.y),dFdy(v_normal.y)))*v_width2_dilute.x,4.0*px);float t=clamp(true_px/px-1.0,0.0,1.0);float h=max(blur2,true_px)*mix(0.5,1.5,t);alpha=clamp(smoothstep(-h,h,edge_hi-dist)-smoothstep(-h,h,edge_lo-dist),0.0,1.0);}}\n#endif\nfloat pxStep;float delta;float alpha2=1.0;\n#ifndef VARIABLE_LINE_WIDTH\nif (u_has_border) {pxStep=fwidth(dist);float out_edge=v_width2_dilute.x-dist;float in_edge=dist-(v_width2_dilute.y-2.0*ANTIALIASING);delta=v_width2_dilute.y > 0.0 ? min(in_edge,out_edge) : out_edge;float edge=ANTIALIASING;alpha=delta > 0.0 ? smoothstep(edge-pxStep,u_width_scale*blur+edge+pxStep,delta) : 0.0;float borderPx=border_width*u_width_scale;float edge2=borderPx+ANTIALIASING;alpha2=smoothstep(edge2-pxStep,edge2+pxStep,delta);\n#ifdef LINE_ROUND_JOIN_CLIP_BORDER_OVERLAP\nif (alpha > 0.0 && alpha2 < 1.0 &&\n(v_round_join_conflict_test.x > 0.0 || v_round_join_conflict_test.y > 0.0)) {highp float prevDist=roundJoinConflictDistance(v_round_join_conflict_offset.xy,v_round_join_conflict_dir.xy,v_round_join_conflict_test.x);highp float nextDist=roundJoinConflictDistance(v_round_join_conflict_offset.zw,v_round_join_conflict_dir.zw,v_round_join_conflict_test.y);vec3 testBounds=vec3(max(v_width2_dilute.y-ANTIALIASING,0.0),v_width2_dilute.x-ANTIALIASING,borderPx);float insideConflictFill=max(insideRoundJoinConflictFill(prevDist,testBounds,pxStep),insideRoundJoinConflictFill(nextDist,testBounds,pxStep));alpha2=max(alpha2,insideConflictFill);const float diluteEpsilon=0.004;if (u_alpha_discard_threshold !=0.0 && blur==0.0 && v_width2_dilute.z >=1.0-diluteEpsilon) {float insideConflictBody=max(insideRoundJoinConflictBody(prevDist,testBounds,pxStep),insideRoundJoinConflictBody(nextDist,testBounds,pxStep));alpha=max(alpha,delta >=edge ? insideConflictBody : 0.0);}}\n#endif\n}\n#endif\nif (u_has_dash) {highp float dash_len=v_dash.x;float sdfgamma=ANTIALIASING/float(dash_len);float scaled_floorwidth=(floorwidth*u_floor_width_scale);float periods_per_pixel=fwidth(v_tex.x);float dash_coverage=v_dash.y;float fade=linearstep(0.25,0.5,periods_per_pixel);float gamma=max(sdfgamma/scaled_floorwidth,0.5*periods_per_pixel);if (fade >=1.0) {alpha*=dash_coverage;} else if (periods_per_pixel < 0.1) {float sdfdist=texture(u_dash_image,v_tex).r;alpha*=linearstep(0.5-gamma,0.5+gamma,sdfdist);} else {float span=min(periods_per_pixel,1.0);float tap_offset=span*0.25;float sdf0=texture(u_dash_image,vec2(v_tex.x-tap_offset,v_tex.y)).r;float sdf1=texture(u_dash_image,vec2(v_tex.x+tap_offset,v_tex.y)).r;alpha*=mix(0.5*(\nlinearstep(0.5-gamma,0.5+gamma,sdf0)+linearstep(0.5-gamma,0.5+gamma,sdf1)\n),dash_coverage,fade);}}highp vec4 out_color;\n#ifdef RENDER_LINE_GRADIENT\nout_color=texture(u_gradient_image,v_uv.xy);\n#else\nout_color=color;\n#endif\nfloat trim_alpha=1.0;\n#ifdef RENDER_LINE_TRIM_OFFSET\nhighp float trim_start=u_trim_offset[0];highp float trim_end=u_trim_offset[1];highp float line_progress=v_uv[2];if (trim_end > trim_start) {highp float start_transition=max(0.0,min(1.0,(line_progress-trim_start)/max(u_trim_fade_range[0],1.0e-9)));highp float end_transition=max(0.0,min(1.0,(trim_end-line_progress)/max(u_trim_fade_range[1],1.0e-9)));highp float transition_factor=min(start_transition,end_transition);highp float gradient_trim_color_mix_factor=0.0;\n#ifdef RENDER_LINE_GRADIENT\ngradient_trim_color_mix_factor=smoothstep(u_trim_gradient_mix_range.x,u_trim_gradient_mix_range.y,line_progress);\n#endif\nhighp vec4 trim_color=mix(u_trim_color,out_color,gradient_trim_color_mix_factor);out_color=mix(u_trim_gradient_mix_range.x < 1.0 ? color : out_color,trim_color,transition_factor);trim_alpha=1.0-transition_factor;}\n#endif\nif (u_alpha_discard_threshold !=0.0) {if (alpha < u_alpha_discard_threshold) {discard;}}\n#ifdef VARIABLE_LINE_WIDTH\nif (alpha <=0.0) {discard;}\n#endif\n#ifndef VARIABLE_LINE_WIDTH\nif (u_has_border && alpha2 < 1.) {\n#ifdef RENDER_LINE_BORDER_GRADIENT\nvec4 border_gradient_color=texture(u_border_gradient_image,v_uv.xy);out_color=mix(border_gradient_color*trim_alpha,out_color,alpha2);\n#else\nif (border_color.a==0.0) {\n#ifndef RENDER_LINE_GRADIENT\nfloat Y=(out_color.a > 0.01) ? luminance(out_color.rgb/out_color.a) : 1.;float adjustment=(Y > 0.) ? 0.5/Y : 0.45;if (out_color.a > 0.25 && Y < 0.25) {vec3 borderColor=(Y > 0.) ? out_color.rgb : vec3(1,1,1)*out_color.a;out_color.rgb=out_color.rgb+borderColor*(adjustment*(1.0-alpha2));} else {out_color.rgb*=(0.6+0.4*alpha2);}\n#else\nout_color.rgb*=(0.6+0.4*alpha2);\n#endif\n} else {out_color=mix(border_color*trim_alpha,out_color,alpha2);}\n#endif\nout_color*=v_width2_dilute.w;}\n#endif\nvec2 cutout_factors=vec2(0.0);\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(out_color,emissive_strength);\n#ifdef RENDER_SHADOWS\nfloat light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y);light=u_emissive_in_shadows ? mix(light,1.0,emissive_strength) : light;\n#ifdef ELEVATED_ROADS\nout_color.rgb*=mix(v_road_z_offset !=0.0 ? u_ground_shadow_factor : vec3(1.0),vec3(1.0),light);\n#else\nout_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light);\n#endif\n#endif\n#endif\n#ifdef FOG\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\n#endif\nout_color*=(alpha*diluted_opacity*u_opacity_multiplier);\n#ifdef LINE_BLEND_ADDITIVE\n{float cov=alpha*diluted_opacity;glFragColor=vec4(cov > 0.0 ? out_color.rgb/cov : vec3(0.0),cov);}\n#else\n#ifdef LINE_BLEND_MULTIPLY\nglFragColor=vec4(out_color.rgb+(1.0-out_color.a),1.0);\n#else\nglFragColor=out_color;\n#endif\n#endif\nstoreEmissiveColor(glFragColor,emissive_strength);\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\n#ifdef DEBUG_ELEVATION_ID\nglFragColor=vec4(v_elevation_id_col,1.0);\n#endif\n#ifdef ELEVATED_ROADS\nif (u_clip_to_tile_borders) {if (v_tile_pos.x > 1.0 || v_tile_pos.y > 1.0 || v_tile_pos.x < 0.0 || v_tile_pos.y < 0.0) {discard;}vec2 quadrant=step(vec2(0.5),v_tile_pos);vec2 row=mix(u_child_quadrants.xz,u_child_quadrants.yw,quadrant.x);if (mix(row.x,row.y,quadrant.y) > 0.5) {discard;}}\n#endif\nHANDLE_WIREFRAME_DEBUG;}','#include "_prelude_fog.vertex.glsl"\n#include "_prelude_shadow.vertex.glsl"\n#include "_prelude_terrain.vertex.glsl"\n#include "_prelude_ubo_properties.glsl"\n#define EXTRUDE_SCALE 0.015873016\nin ivec2 a_pos_normal;in uvec4 a_data;\n#if defined(ELEVATED) || defined(ELEVATED_ROADS) || defined(VARIABLE_LINE_WIDTH) || defined(VARIABLE_LINE_EMISSIVE_STRENGTH)\nin vec4 a_z_offset_width;\n#endif\n#ifdef DEBUG_ELEVATION_ID\nin vec3 a_elevation_id_col;\n#endif\n#ifdef DEBUG_ELEVATION_ID\nout vec3 v_elevation_id_col;\n#endif\n#ifdef ELEVATION_GROUND_SCALE\nin float a_elevation_ground_scale;\n#endif\n#ifdef LINE_ROUND_JOIN_CLIP_BORDER_OVERLAP\nin highp ivec4 a_round_join_conflict_segments;\n#endif\n#if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_BORDER_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET)\nin highp vec3 a_packed;\n#endif\nuniform bool u_has_dash;uniform bool u_has_border;in float a_linesofar;uniform mat4 u_matrix;uniform mat2 u_pixels_to_tile_units;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;uniform float u_width_scale;uniform float u_z_offset;uniform highp float u_road_view_depth_bias;\n#ifdef ELEVATED\nuniform lowp float u_zbias_factor;uniform lowp float u_tile_to_meter;float sample_elevation(vec2 apos) {\n#ifdef ELEVATION_REFERENCE_SEA\nreturn 0.0;\n#else\nreturn elevation(apos);\n#endif\n}\n#endif\nout vec2 v_normal;out vec4 v_width2_dilute;out float v_gamma_scale;out highp vec2 v_tile_pos;\n#ifdef LINE_ROUND_JOIN_CLIP_BORDER_OVERLAP\nout highp vec4 v_round_join_conflict_offset;out highp vec4 v_round_join_conflict_dir;out mediump vec2 v_round_join_conflict_test;\n#endif\n#ifdef ELEVATED_ROADS\nout highp float v_road_z_offset;\n#endif\n#ifdef VARIABLE_LINE_WIDTH\nout float stub_side;out highp vec2 v_distance;uniform float u_width_addition;\n#endif\nuniform highp float u_floor_width_scale;uniform vec2 u_texsize;uniform float u_tile_units_to_pixels;out highp vec2 v_tex;\n#if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_BORDER_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET)\nout highp vec3 v_uv;\n#endif\n#if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_BORDER_GRADIENT)\nuniform float u_image_height;\n#endif\n#ifdef RENDER_SHADOWS\nuniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth;\n#endif\n#define LPP_HEADER_SIZE_VEC4 5u\nstruct LinePaintProperties {vec4 color;vec4 border_color;float opacity;float blur;float width;float gap_width;float offset;float floorwidth;float border_width;float emissive_strength;vec4 dash;};uniform highp vec4 u_lpp_color;uniform lowp vec4 u_lpp_border_color;uniform lowp float u_lpp_opacity;uniform lowp float u_lpp_blur;uniform mediump float u_lpp_width;uniform mediump float u_lpp_gap_width;uniform lowp float u_lpp_offset;uniform lowp float u_lpp_floorwidth;uniform lowp float u_lpp_border_width;uniform lowp float u_lpp_emissive_strength;uniform highp vec4 u_lpp_dash;uniform highp float u_lpp_zoom_fraction;in float a_feature_index;layout(std140) uniform LinePaintPropertiesHeaderUniform {uvec4 header[LPP_HEADER_SIZE_VEC4];} u_lpp_header;layout(std140) uniform LinePaintPropertiesUniform {vec4 properties[MAX_UBO_SIZE_VEC4];} u_lpp_properties;out highp vec4 v_line_color;out lowp vec4 v_border_color;out lowp float v_opacity;out lowp float v_blur;out lowp float v_floorwidth;out lowp float v_border_width;out lowp float v_emissive_strength;out highp vec2 v_dash;vec4 readColor(uint base,bool isDataDriven,uint offsetVec4,vec2 headerZoom,vec4 fallbackValue) {if (!isDataDriven) return fallbackValue;vec4 value=u_lpp_properties.properties[base+offsetVec4];return unpack_mix_color(value,zoomFactor(headerZoom.x,headerZoom.y,u_lpp_zoom_fraction));}float readFloat(uint base,bool isDataDriven,uint offsetVec4,float fallbackValue) {if (!isDataDriven) return fallbackValue;vec4 slot=u_lpp_properties.properties[base+offsetVec4];return unpack_mix_vec2(slot.xy,zoomFactor(slot.z,slot.w,u_lpp_zoom_fraction));}highp vec4 readRaw(uint base,bool isDataDriven,uint offsetVec4,highp vec4 fallbackValue) {if (!isDataDriven) return fallbackValue;return u_lpp_properties.properties[base+offsetVec4];}LinePaintProperties readLinePaintProperties() {uint dataDrivenMask=u_lpp_header.header[0][0];uint blockSizeVec4 =u_lpp_header.header[0][2];vec2 colorHeaderZoom =uintBitsToFloat(u_lpp_header.header[4].xy);vec2 borderHeaderZoom=uintBitsToFloat(u_lpp_header.header[4].zw);uint base=uint(a_feature_index)*blockSizeVec4;LinePaintProperties props;props.color =readColor(base,(dataDrivenMask & (1u << 0u)) !=0u,u_lpp_header.header[0][3],colorHeaderZoom,u_lpp_color);props.border_color =readColor(base,(dataDrivenMask & (1u << 1u)) !=0u,u_lpp_header.header[1][0],borderHeaderZoom,u_lpp_border_color);props.opacity =readFloat(base,(dataDrivenMask & (1u << 2u)) !=0u,u_lpp_header.header[1][1],u_lpp_opacity);props.blur =readFloat(base,(dataDrivenMask & (1u << 3u)) !=0u,u_lpp_header.header[1][2],u_lpp_blur);props.width =readFloat(base,(dataDrivenMask & (1u << 4u)) !=0u,u_lpp_header.header[1][3],u_lpp_width);props.gap_width =readFloat(base,(dataDrivenMask & (1u << 5u)) !=0u,u_lpp_header.header[2][0],u_lpp_gap_width);props.offset =readFloat(base,(dataDrivenMask & (1u << 6u)) !=0u,u_lpp_header.header[2][1],u_lpp_offset);props.floorwidth =readFloat(base,(dataDrivenMask & (1u << 7u)) !=0u,u_lpp_header.header[2][2],u_lpp_floorwidth);props.border_width =readFloat(base,(dataDrivenMask & (1u << 8u)) !=0u,u_lpp_header.header[2][3],u_lpp_border_width);props.emissive_strength=readFloat(base,(dataDrivenMask & (1u << 9u)) !=0u,u_lpp_header.header[3][0],u_lpp_emissive_strength);props.dash =readRaw(base,(dataDrivenMask & (1u << 10u)) !=0u,u_lpp_header.header[3][1],u_lpp_dash);return props;}\n#ifdef LINE_ROUND_JOIN_CLIP_BORDER_OVERLAP\nhighp vec3 unpackRoundJoinTestCoordinate(highp int packedCoord) {highp int x=(((packedCoord & 0xfffe) ^ 0x8000)-0x8000) >> 1;return vec3(float(x),float(packedCoord >> 16),float(packedCoord & 1));}\n#endif\nvoid main() {LinePaintProperties paint_properties=readLinePaintProperties();v_line_color=paint_properties.color;float floorwidth=paint_properties.floorwidth;float blur=paint_properties.blur;float opacity=paint_properties.opacity;float gapwidth=paint_properties.gap_width;float offset=paint_properties.offset;float width=paint_properties.width;float border_width=paint_properties.border_width;vec4 border_color=paint_properties.border_color;float emissive_strength=paint_properties.emissive_strength;\n#ifdef VARIABLE_LINE_EMISSIVE_STRENGTH\nemissive_strength=a_z_offset_width.w;\n#endif\nv_border_color=border_color;v_opacity=opacity;v_blur=blur;v_floorwidth=floorwidth;v_border_width=border_width;v_emissive_strength=emissive_strength;float a_z_offset=u_z_offset;\n#if defined(ELEVATED) || defined(ELEVATED_ROADS)\na_z_offset+=a_z_offset_width.x;\n#endif\n#ifdef DEBUG_ELEVATION_ID\nv_elevation_id_col=a_elevation_id_col;\n#endif\nhighp float line_progress=0.0;\n#if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_BORDER_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET)\nline_progress=a_packed[2];\n#endif\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;\n#ifndef VARIABLE_LINE_WIDTH\nif (u_has_border) {ANTIALIASING*=8.0;}\n#endif\nvec2 a_extrude=vec2(a_data.xy)-128.0;float a_direction=float(a_data.z & 3u)-1.0;vec2 pos_normal=vec2(a_pos_normal);vec2 pos=floor(pos_normal*0.5);mediump vec2 normal=pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;offset=-1.0*offset*u_width_scale;bool left=normal.y==1.0;gapwidth=gapwidth/2.0;float halfwidth;float dilute_scale=1.0;float dilute_border_scale=1.0;vec2 side_widths=vec2(0.0);\n#ifdef VARIABLE_LINE_WIDTH\nfloat left_width=a_z_offset_width.y;float right_width=a_z_offset_width.z;bool zero_right_width=right_width==0.0;side_widths=u_width_scale*(zero_right_width ? vec2(left_width+u_width_addition) : vec2(left_width,right_width)+0.5*u_width_addition);halfwidth=left ? side_widths.x : (zero_right_width ? 0.0 : side_widths.y);offset=border_width > 0.0 ? (left_width+right_width+u_width_addition+border_width*0.5)*u_width_scale : offset;halfwidth=border_width > 0.0 ? border_width*u_width_scale*0.5 : halfwidth;side_widths=border_width > 0.0 ? vec2(halfwidth) : side_widths;stub_side=zero_right_width ?-normal.y : 0.0;ANTIALIASING=!left && zero_right_width ? 0.0 : ANTIALIASING;\n#else\nhalfwidth=(u_width_scale*width)/2.0;\n#endif\nfloat inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth > 0.0 ? ANTIALIASING : 0.0);\n#ifdef VARIABLE_LINE_WIDTH\nv_distance=v_normal*outset;\n#endif\nmediump vec2 dist=outset*a_extrude*EXTRUDE_SCALE;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*EXTRUDE_SCALE*normal.y*mat2(t,-u,u,t);float hidden=float(opacity==0.0);vec2 extrude=dist*u_pixels_to_tile_units;vec4 projected_extrude=u_matrix*vec4(extrude,0.0,0.0);vec2 projected_extrude_xy=projected_extrude.xy;\n#ifdef ELEVATED_ROADS\nv_road_z_offset=a_z_offset;v_tile_pos=pos+offset2*u_pixels_to_tile_units;gl_Position=u_matrix*vec4(v_tile_pos,a_z_offset,1.0);\n#else\n#ifdef ELEVATED\nvec2 offsetTile=offset2*u_pixels_to_tile_units;vec2 offset_pos=pos+offsetTile;float ele=0.0;float scaled_z_offset=a_z_offset;\n#ifdef ELEVATION_GROUND_SCALE\nscaled_z_offset=a_z_offset*mix(1.0,u_exaggeration,a_elevation_ground_scale);\n#endif\n#ifdef CROSS_SLOPE_VERTICAL\nfloat top=pos_normal.y-2.0*floor(pos_normal.y*0.5);float line_height=2.0*u_tile_to_meter*outset*top*u_pixels_to_tile_units[1][1]+scaled_z_offset;ele=sample_elevation(offset_pos)+line_height;projected_extrude=vec4(0);\n#else\n#ifdef CROSS_SLOPE_HORIZONTAL\nfloat ele0=sample_elevation(offset_pos);float ele1=max(sample_elevation(offset_pos+extrude),sample_elevation(offset_pos+extrude/2.0));float ele2=max(sample_elevation(offset_pos-extrude),sample_elevation(offset_pos-extrude/2.0));float ele_max=max(ele0,max(ele1,ele2));ele=ele_max+scaled_z_offset;\n#else\nfloat ele0=sample_elevation(offset_pos);float ele1=max(sample_elevation(offset_pos+extrude),sample_elevation(offset_pos+extrude/2.0));float ele2=max(sample_elevation(offset_pos-extrude),sample_elevation(offset_pos-extrude/2.0));float ele_max=max(ele0,0.5*(ele1+ele2));ele=ele_max-ele0+ele1+scaled_z_offset;\n#endif\n#endif\nv_tile_pos=offset_pos;gl_Position=u_matrix*vec4(v_tile_pos,ele,1.0)+projected_extrude;float z=clamp(gl_Position.z/gl_Position.w,0.5,1.0);float zbias=max(0.00005,(pow(z,0.8)-z)*u_zbias_factor*u_exaggeration);gl_Position.z-=(gl_Position.w*zbias);gl_Position=mix(gl_Position,AWAY,hidden);\n#else\nv_tile_pos=pos+offset2*u_pixels_to_tile_units;gl_Position=u_matrix*vec4(v_tile_pos,0.0,1.0);\n#endif\n#endif\n#ifndef ELEVATED\n#ifndef VARIABLE_LINE_WIDTH\n#ifndef RENDER_TO_TEXTURE\nfloat base_w=gl_Position.w;vec2 screen_width=abs(projected_extrude.xy/base_w*u_units_to_pixels);float max_extrude_component=max(screen_width.x,screen_width.y);if (width >=1.0 && base_w > 0.0 && max_extrude_component > 0.0001) {float min_pixel=1.05;if (max_extrude_component < min_pixel) {vec2 abs_pos=abs(gl_Position.xy);float is_out=max(abs_pos.x,abs_pos.y)/base_w;dilute_scale=mix(max_extrude_component/min_pixel,1.0,smoothstep(2.5,4.5,is_out));projected_extrude.xy/=dilute_scale;projected_extrude_xy=projected_extrude.xy;}else if (gapwidth > 0.0) {float visible_ratio=(halfwidth+ANTIALIASING)/outset;vec2 visible_screen_width=screen_width*visible_ratio;float max_visible_component=max(visible_screen_width.x,visible_screen_width.y);dilute_scale=min(1.0,max_visible_component/min_pixel);if (!u_has_border) {if (u_has_dash && blur < 0.01 && halfwidth >=ANTIALIASING) {dilute_scale=1.0;}}}else\n{if (u_has_border) {float border_ratio=(border_width*u_width_scale+ANTIALIASING)/outset;screen_width*=border_ratio;float max_border_component=max(screen_width.x,screen_width.y);dilute_border_scale=min(1.0,max_border_component/min_pixel);}}}\n#endif\n#endif\n#ifdef VARIABLE_LINE_WIDTH\n#ifndef RENDER_TO_TEXTURE\nvec2 ndc=gl_Position.xy/gl_Position.w;vec4 projected_tangent=u_matrix*vec4(extrude.y,-extrude.x,0.0,0.0);vec2 screen_extrude=(projected_extrude.xy-ndc*projected_extrude.w)*u_units_to_pixels;vec2 screen_tangent=(projected_tangent.xy-ndc*projected_tangent.w)*u_units_to_pixels;float thickness=abs(screen_extrude.x*screen_tangent.y-screen_extrude.y*screen_tangent.x)/max(length(screen_tangent),1e-6);float thickness_px=max(thickness,0.2*length(screen_extrude))/gl_Position.w*u_device_pixel_ratio;float headroom_scale=gl_Position.w > 0.0 ? 1.0+(1.0-smoothstep(2.0,4.0,thickness_px))/max(thickness_px,0.0001) : 1.0;projected_extrude*=headroom_scale;extrude*=headroom_scale;v_distance*=headroom_scale;\n#endif\n#endif\nv_tile_pos=(v_tile_pos+extrude)/EXTENT;\n#ifdef ELEVATED_ROADS\ngl_Position=gl_Position+projected_extrude;\n#ifdef VARIABLE_LINE_WIDTH\n#ifndef ELEVATED\ngl_Position.z-=u_road_view_depth_bias*smoothstep(-0.5,0.0,a_z_offset);\n#endif\n#endif\n#else\ngl_Position=mix(gl_Position+projected_extrude,AWAY,hidden);\n#endif\n#endif\n#ifdef ELEVATED_ROADS\n#ifdef RENDER_SHADOWS\nvec3 shd_pos=vec3(pos+(offset2+dist)*u_pixels_to_tile_units,a_z_offset);vec3 shd_pos0=shd_pos;vec3 shd_pos1=shd_pos;\n#ifdef NORMAL_OFFSET\nvec3 shd_pos_offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=shd_pos_offset*shadow_normal_offset_multiplier0();shd_pos1+=shd_pos_offset*shadow_normal_offset_multiplier1();\n#endif\nv_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w;\n#endif\n#endif\n#ifndef RENDER_TO_TEXTURE\nfloat epsilon=0.0001;float extrude_length_without_perspective=max(length(dist),epsilon);float extrude_length_with_perspective=max(length(projected_extrude_xy/gl_Position.w*u_units_to_pixels),epsilon);v_gamma_scale=mix(extrude_length_without_perspective/extrude_length_with_perspective,1.0,step(0.01,blur));\n#else\nv_gamma_scale=1.0;\n#endif\n#if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_BORDER_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET)\nhighp float a_uv_x=a_packed[0];float a_split_index=a_packed[1];\n#if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_BORDER_GRADIENT)\nhighp float texel_height=1.0/u_image_height;highp float half_texel_height=0.5*texel_height;v_uv=vec3(a_uv_x,a_split_index*texel_height-half_texel_height,line_progress);\n#else\nv_uv=vec3(a_uv_x,0.0,line_progress);\n#endif\n#endif\nif (u_has_dash) {highp vec4 dashf=paint_properties.dash;highp float dash_w=dashf.w;highp float totalLength=dashf.z+dash_w/65535.0;float scale=totalLength==0.0 ? 0.0 : u_tile_units_to_pixels/totalLength;highp uint dash_bits=uint(dashf.y+0.5);float dash_half_height=float(dash_bits & 15u);float dash_coverage=float(dash_bits >> 4u)/4095.0;v_tex=vec2(a_linesofar*scale/(floorwidth*u_floor_width_scale),(-normal.y*dash_half_height+dashf.x+0.5)/u_texsize.y);v_dash=vec2(totalLength,dash_coverage);} else {v_tex=vec2(0.0);v_dash=vec2(0.0);}v_width2_dilute=vec4(outset,inset,dilute_scale,dilute_border_scale);\n#ifdef VARIABLE_LINE_WIDTH\nv_width2_dilute.xy=side_widths;\n#endif\n#ifdef LINE_ROUND_JOIN_CLIP_BORDER_OVERLAP\nhighp float tileToPixels=1.0/u_pixels_to_tile_units[0][0];highp vec2 testPos=pos+extrude/dilute_scale;highp vec3 prevA=unpackRoundJoinTestCoordinate(a_round_join_conflict_segments.x);highp vec3 prevB=unpackRoundJoinTestCoordinate(a_round_join_conflict_segments.y);highp vec3 nextA=unpackRoundJoinTestCoordinate(a_round_join_conflict_segments.z);highp vec3 nextB=unpackRoundJoinTestCoordinate(a_round_join_conflict_segments.w);v_round_join_conflict_offset=vec4(testPos-prevA.xy,testPos-nextA.xy)*tileToPixels;v_round_join_conflict_dir=vec4(prevB.xy-prevA.xy,nextB.xy-nextA.xy)*tileToPixels;v_round_join_conflict_test=vec2(prevA.z,nextA.z);\n#endif\n#ifdef FOG\nv_fog_pos=fog_position(pos);\n#endif\n}'),linePattern:pu('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_lighting.glsl"\n#include "_prelude_shadow.fragment.glsl"\n#include "_prelude_indicator_cutout.fragment.glsl"\nuniform highp float u_device_pixel_ratio;uniform highp float u_width_scale;uniform highp float u_alpha_discard_threshold;uniform lowp float u_opacity_multiplier;uniform highp vec2 u_texsize;uniform highp float u_tile_units_to_pixels;uniform highp vec2 u_trim_offset;uniform highp vec2 u_trim_fade_range;uniform lowp vec4 u_trim_color;uniform sampler2D u_image;\n#ifdef APPLY_LUT_ON_GPU\nuniform highp sampler3D u_lutTexture;\n#endif\n#ifdef LINE_PATTERN_TRANSITION\nuniform float u_pattern_transition;\n#endif\nin vec2 v_normal;in vec2 v_width2;in highp float v_linesofar;in float v_gamma_scale;in float v_width;\n#ifdef RENDER_LINE_TRIM_OFFSET\nin highp vec3 v_uv;\n#endif\n#ifdef ELEVATED_ROADS\nin highp float v_road_z_offset;\n#endif\n#ifdef LINE_JOIN_NONE\nin vec2 v_pattern_data;\n#endif\n#ifdef RENDER_SHADOWS\nuniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth;\n#endif\n#pragma mapbox: define mediump uvec4 pattern\n#ifdef LINE_PATTERN_TRANSITION\n#pragma mapbox: define mediump uvec4 pattern_b\n#endif\n#pragma mapbox: define mediump float pixel_ratio\n#pragma mapbox: define mediump float blur\n#pragma mapbox: define mediump float opacity\n#pragma mapbox: define lowp float emissive_strength\nvoid main() {\n#pragma mapbox: initialize mediump uvec4 pattern\n#ifdef LINE_PATTERN_TRANSITION\n#pragma mapbox: initialize mediump uvec4 pattern_b\n#endif\n#pragma mapbox: initialize mediump float pixel_ratio\n#pragma mapbox: initialize mediump float blur\n#pragma mapbox: initialize mediump float opacity\n#pragma mapbox: initialize lowp float emissive_strength\nvec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio;highp float pattern_size=display_size.x/u_tile_units_to_pixels;float aspect=display_size.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(u_width_scale*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);highp float pattern_x=v_linesofar/pattern_size*aspect;highp float x=mod(pattern_x,1.0);highp float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;highp vec2 pos=mix(pattern_tl*texel_size-texel_size,pattern_br*texel_size+texel_size,vec2(x,y));highp vec2 lod_pos=mix(pattern_tl*texel_size-texel_size,pattern_br*texel_size+texel_size,vec2(pattern_x,y));vec4 color=textureLodCustom(u_image,pos,lod_pos);\n#ifdef APPLY_LUT_ON_GPU\ncolor=applyLUT(u_lutTexture,color);\n#endif\n#ifdef LINE_PATTERN_TRANSITION\nvec2 pattern_b_tl=vec2(pattern_b.xy);vec2 pattern_b_br=vec2(pattern_b.zw);highp vec2 pos_b=mix(pattern_b_tl*texel_size-texel_size,pattern_b_br*texel_size+texel_size,vec2(x,y));vec4 color_b=textureLodCustom(u_image,pos_b,lod_pos);color=color*(1.0-u_pattern_transition)+color_b*u_pattern_transition;\n#endif\n#ifdef RENDER_LINE_TRIM_OFFSET\nhighp float trim_start=u_trim_offset[0];highp float trim_end=u_trim_offset[1];highp float line_progress=v_uv[2];if (trim_end > trim_start) {highp float start_transition=max(0.0,min(1.0,(line_progress-trim_start)/max(u_trim_fade_range[0],1.0e-9)));highp float end_transition=max(0.0,min(1.0,(trim_end-line_progress)/max(u_trim_fade_range[1],1.0e-9)));highp float transition_factor=min(start_transition,end_transition);color=mix(color,color.a*u_trim_color,transition_factor);}\n#endif\n#ifdef LINE_JOIN_NONE\nhighp float pattern_len=pattern_size/aspect;highp float segment_phase=pattern_len-mod(v_linesofar-v_pattern_data.x+pattern_len,pattern_len);highp float visible_start=segment_phase-step(pattern_len*0.5,segment_phase)*pattern_len;highp float visible_end=floor((v_pattern_data.y-segment_phase)/pattern_len)*pattern_len+segment_phase;visible_end+=step(pattern_len*0.5,v_pattern_data.y-visible_end)*pattern_len;if (v_pattern_data.x < visible_start || v_pattern_data.x >=visible_end) {color=vec4(0.0);}\n#endif\n#ifdef LIGHTING_3D_MODE\ncolor=apply_lighting_with_emission_ground(color,emissive_strength);\n#ifdef RENDER_SHADOWS\nfloat light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);\n#ifdef ELEVATED_ROADS\ncolor.rgb*=mix(v_road_z_offset !=0.0 ? u_ground_shadow_factor : vec3(1.0),vec3(1.0),light);\n#else\ncolor.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light);\n#endif\n#endif\n#endif\n#ifdef FOG\ncolor=fog_dither(fog_apply_premultiplied(color,v_fog_pos));\n#endif\ncolor*=(alpha*opacity*u_opacity_multiplier);if (u_alpha_discard_threshold !=0.0) {if (color.a < u_alpha_discard_threshold) {discard;}}glFragColor=color;storeEmissiveColor(glFragColor,emissive_strength);\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}','#include "_prelude_fog.vertex.glsl"\n#include "_prelude_shadow.vertex.glsl"\n#include "_prelude_terrain.vertex.glsl"\n#define scale 0.015873016\nin ivec2 a_pos_normal;in uvec4 a_data;\n#if defined(ELEVATED) || defined(ELEVATED_ROADS)\nin vec4 a_z_offset_width;\n#endif\n#ifdef ELEVATION_GROUND_SCALE\nin float a_elevation_ground_scale;\n#endif\n#ifdef RENDER_LINE_TRIM_OFFSET\nin highp vec3 a_packed;\n#endif\nin highp float a_linesofar;\n#ifdef LINE_JOIN_NONE\nin highp vec3 a_pattern_data;out vec2 v_pattern_data;\n#endif\nuniform mat4 u_matrix;uniform float u_tile_units_to_pixels;uniform vec2 u_units_to_pixels;uniform mat2 u_pixels_to_tile_units;uniform float u_device_pixel_ratio;uniform float u_width_scale;uniform float u_floor_width_scale;\n#ifdef ELEVATED\nuniform lowp float u_zbias_factor;uniform lowp float u_tile_to_meter;float sample_elevation(vec2 apos) {\n#ifdef ELEVATION_REFERENCE_SEA\nreturn 0.0;\n#else\nreturn elevation(apos);\n#endif\n}\n#endif\nout vec2 v_normal;out vec2 v_width2;out highp float v_linesofar;out float v_gamma_scale;out float v_width;\n#ifdef RENDER_LINE_TRIM_OFFSET\nout highp vec3 v_uv;\n#endif\n#ifdef ELEVATED_ROADS\nout highp float v_road_z_offset;\n#endif\n#ifdef RENDER_SHADOWS\nuniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth;\n#endif\n#pragma mapbox: define mediump float blur\n#pragma mapbox: define mediump float opacity\n#pragma mapbox: define mediump float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n#pragma mapbox: define mediump float floorwidth\n#pragma mapbox: define mediump uvec4 pattern\n#ifdef LINE_PATTERN_TRANSITION\n#pragma mapbox: define mediump uvec4 pattern_b\n#endif\n#pragma mapbox: define mediump float pixel_ratio\n#pragma mapbox: define lowp float emissive_strength\nvoid main() {\n#pragma mapbox: initialize mediump float blur\n#pragma mapbox: initialize mediump float opacity\n#pragma mapbox: initialize mediump float offset\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize mediump float floorwidth\n#pragma mapbox: initialize mediump uvec4 pattern\n#ifdef LINE_PATTERN_TRANSITION\n#pragma mapbox: initialize mediump uvec4 pattern_b\n#endif\n#pragma mapbox: initialize mediump float pixel_ratio\n#pragma mapbox: initialize lowp float emissive_strength\nfloat a_z_offset;\n#if defined(ELEVATED) || defined(ELEVATED_ROADS)\na_z_offset=a_z_offset_width.x;\n#endif\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=vec2(a_data.xy)-128.0;float a_direction=float(a_data.z & 3u)-1.0;vec2 pos_normal=vec2(a_pos_normal);vec2 pos=floor(pos_normal*0.5);vec2 normal=pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=(u_width_scale*width)/2.0;offset=-1.0*offset*u_width_scale;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);vec2 dist=outset*a_extrude*scale;float u=0.5*a_direction;float t=1.0-abs(u);vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float hidden=float(opacity==0.0);vec2 extrude=dist*u_pixels_to_tile_units;vec4 projected_extrude=u_matrix*vec4(extrude,0.0,0.0);vec2 projected_extrude_xy=projected_extrude.xy;\n#ifdef ELEVATED_ROADS\nv_road_z_offset=a_z_offset;gl_Position=u_matrix*vec4(pos+offset2*u_pixels_to_tile_units,a_z_offset,1.0)+projected_extrude;\n#else\n#ifdef ELEVATED\nvec2 offsetTile=offset2*u_pixels_to_tile_units;vec2 offset_pos=pos+offsetTile;float ele=0.0;float scaled_z_offset=a_z_offset;\n#ifdef ELEVATION_GROUND_SCALE\nscaled_z_offset=a_z_offset*mix(1.0,u_exaggeration,a_elevation_ground_scale);\n#endif\n#ifdef CROSS_SLOPE_VERTICAL\nfloat top=pos_normal.y-2.0*floor(pos_normal.y*0.5);float line_height=2.0*u_tile_to_meter*outset*top*u_pixels_to_tile_units[1][1]+scaled_z_offset;ele=sample_elevation(offset_pos)+line_height;projected_extrude=vec4(0);\n#else\n#ifdef CROSS_SLOPE_HORIZONTAL\nfloat ele0=sample_elevation(offset_pos);float ele1=max(sample_elevation(offset_pos+extrude),sample_elevation(offset_pos+extrude/2.0));float ele2=max(sample_elevation(offset_pos-extrude),sample_elevation(offset_pos-extrude/2.0));float ele_max=max(ele0,max(ele1,ele2));ele=ele_max+scaled_z_offset;\n#else\nfloat ele0=sample_elevation(offset_pos);float ele1=max(sample_elevation(offset_pos+extrude),sample_elevation(offset_pos+extrude/2.0));float ele2=max(sample_elevation(offset_pos-extrude),sample_elevation(offset_pos-extrude/2.0));float ele_max=max(ele0,0.5*(ele1+ele2));ele=ele_max-ele0+ele1+scaled_z_offset;\n#endif\n#endif\ngl_Position=u_matrix*vec4(offset_pos,ele,1.0)+projected_extrude;float z=clamp(gl_Position.z/gl_Position.w,0.5,1.0);float zbias=max(0.00005,(pow(z,0.8)-z)*u_zbias_factor*u_exaggeration);gl_Position.z-=(gl_Position.w*zbias);gl_Position=mix(gl_Position,AWAY,hidden);\n#else\ngl_Position=mix(u_matrix*vec4(pos+offset2*u_pixels_to_tile_units,0.0,1.0)+projected_extrude,AWAY,hidden);\n#endif\n#endif\n#ifdef ELEVATED_ROADS\n#ifdef RENDER_SHADOWS\nvec3 shd_pos=vec3(pos+(offset2+dist)*u_pixels_to_tile_units,a_z_offset);vec3 shd_pos0=shd_pos;vec3 shd_pos1=shd_pos;\n#ifdef NORMAL_OFFSET\nvec3 shd_pos_offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=shd_pos_offset*shadow_normal_offset_multiplier0();shd_pos1+=shd_pos_offset*shadow_normal_offset_multiplier1();\n#endif\nv_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w;\n#endif\n#endif\n#ifndef RENDER_TO_TEXTURE\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude_xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=mix(extrude_length_without_perspective/extrude_length_with_perspective,1.0,step(0.01,blur));\n#else\nv_gamma_scale=1.0;\n#endif\n#ifdef RENDER_LINE_TRIM_OFFSET\nhighp float a_uv_x=a_packed[0];highp float line_progress=a_packed[2];v_uv=vec3(a_uv_x,0.0,line_progress);\n#endif\nv_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=(floorwidth*u_floor_width_scale);\n#ifdef LINE_JOIN_NONE\nv_width=(floorwidth*u_floor_width_scale)+ANTIALIASING;mediump float pixels_to_tile_units=1.0/u_tile_units_to_pixels;mediump float pixel_ratio_inverse=1.0/pixel_ratio;mediump float aspect=v_width/(float(pattern.w-pattern.y)*pixel_ratio_inverse);highp float subt_multiple=float(pattern.z-pattern.x)*pixel_ratio_inverse*pixels_to_tile_units*aspect*32.0;highp float subt=floor(a_pattern_data.z/subt_multiple)*subt_multiple;float offset_sign=(fract(a_pattern_data.x)-0.5)*4.0;float line_progress_offset=offset_sign*v_width*0.5*pixels_to_tile_units;v_linesofar=(a_pattern_data.z-subt)+a_linesofar+line_progress_offset;v_pattern_data=vec2(a_pattern_data.x+line_progress_offset,a_pattern_data.y);\n#endif\n#ifdef FOG\nv_fog_pos=fog_position(pos);\n#endif\n}'),raster:pu('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_lighting.glsl"\n#include "_prelude_raster_array.glsl"\nuniform float u_fade_t;uniform float u_opacity;uniform highp float u_raster_elevation;uniform highp float u_zoom_transition;in vec2 v_pos0;in vec2 v_pos1;in float v_depth;\n#ifdef PROJECTION_GLOBE_VIEW\nin float v_split_fade;\n#endif\nuniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;uniform float u_emissive_strength;\n#ifndef RASTER_ARRAY\nuniform highp sampler2D u_image0;uniform sampler2D u_image1;\n#endif\n#ifdef RASTER_COLOR\nuniform sampler2D u_color_ramp;uniform highp vec4 u_colorization_mix;uniform highp float u_colorization_offset;uniform vec2 u_texture_res;uniform highp float u_color_ramp_size;\n#endif\nvoid main() {vec4 color0,color1,color;vec2 value;\n#ifdef RASTER_COLOR\n#ifdef RASTER_ARRAY\n#ifdef RASTER_ARRAY_LINEAR\nvalue=mix(\nraTexture2D_image0_linear(v_pos0,u_texture_res,u_colorization_mix,u_colorization_offset),raTexture2D_image1_linear(v_pos1,u_texture_res,u_colorization_mix,u_colorization_offset),u_fade_t\n);\n#else\nvalue=mix(\nraTexture2D_image0_nearest(v_pos0,u_texture_res,u_colorization_mix,u_colorization_offset),raTexture2D_image1_nearest(v_pos1,u_texture_res,u_colorization_mix,u_colorization_offset),u_fade_t\n);\n#endif\nif (value.y > 0.0) value.x/=value.y;\n#ifdef RASTER_COLOR_SCALE_LOG\nfloat N=u_color_ramp_size;float vNorm=max((value.x-0.5/N)*N/(N-1.0),0.0);vNorm=log(vNorm*(10.0-1.0)+1.0)/log(10.0);value.x=0.5/N+vNorm*(N-1.0)/N;\n#endif\n#else\ncolor=mix(texture(u_image0,v_pos0),texture(u_image1,v_pos1),u_fade_t);value=vec2(u_colorization_offset+dot(color.rgb,u_colorization_mix.rgb),color.a);\n#endif\ncolor=texture(u_color_ramp,vec2(value.x,0.5));if (color.a > 0.0) color.rgb/=color.a;color.a*=value.y;\n#else\ncolor0=texture(u_image0,v_pos0);color1=texture(u_image1,v_pos1);if (color0.a > 0.0) color0.rgb/=color0.a;if (color1.a > 0.0) color1.rgb/=color1.a;color=mix(color0,color1,u_fade_t);\n#endif\ncolor.a*=u_opacity;\n#ifdef GLOBE_POLES\ncolor.a*=1.0-smoothstep(0.0,0.05,u_zoom_transition);\n#endif\nvec3 rgb=color.rgb;rgb=vec3(\ndot(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);vec3 out_color=mix(u_high_vec,u_low_vec,rgb);\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(vec4(out_color,1.0),u_emissive_strength).rgb;\n#endif\n#ifdef FOG\nhighp float fog_limit_high_meters=1000000.0;highp float fog_limit_low_meters=600000.0;float fog_limit=1.0-smoothstep(fog_limit_low_meters,fog_limit_high_meters,u_raster_elevation);out_color=fog_dither(fog_apply(out_color,v_fog_pos,fog_limit));\n#endif\nglFragColor=vec4(out_color*color.a,color.a);\n#ifdef PROJECTION_GLOBE_VIEW\nglFragColor*=mix(1.0,1.0-smoothstep(0.0,0.05,u_zoom_transition),smoothstep(0.8,0.9,v_split_fade));\n#endif\n#ifdef RENDER_CUTOFF\nglFragColor=glFragColor*cutoff_opacity(u_cutoff_params,v_depth);\n#endif\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nstoreEmissiveColor(glFragColor,u_emissive_strength);HANDLE_WIREFRAME_DEBUG;}','#include "_prelude_fog.vertex.glsl"\n#include "_prelude_terrain.vertex.glsl"\nuniform mat4 u_matrix;uniform mat4 u_normalize_matrix;uniform mat4 u_globe_matrix;uniform mat4 u_merc_matrix;uniform mat3 u_grid_matrix;uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform vec2 u_perspective_transform;uniform vec2 u_texture_offset;uniform float u_raster_elevation;uniform float u_zoom_transition;uniform vec2 u_merc_center;\n#ifdef ELEVATED\nuniform lowp float u_zbias_factor;\n#endif\n#define GLOBE_UPSCALE GLOBE_RADIUS/6371008.8\n#ifdef GLOBE_POLES\nin vec3 a_globe_pos;in vec2 a_uv;\n#else\nin ivec2 a_pos;in uvec2 a_texture_pos;\n#endif\nout vec2 v_pos0;out vec2 v_pos1;out float v_depth;\n#ifdef PROJECTION_GLOBE_VIEW\nout float v_split_fade;\n#endif\nvoid main() {vec2 uv;\n#ifdef GLOBE_POLES\nvec3 globe_pos=a_globe_pos;uv=a_uv;float ele=u_raster_elevation;\n#ifdef ELEVATION_REFERENCE_GROUND\nele+=elevation(uv*EXTENT);\n#endif\nglobe_pos+=normalize(globe_pos)*ele*GLOBE_UPSCALE;gl_Position=u_matrix*u_globe_matrix*vec4(globe_pos,1.0);\n#ifdef FOG\nv_fog_pos=fog_position((u_normalize_matrix*vec4(a_globe_pos,1.0)).xyz);\n#endif\n#else\nvec4 world_pos;\n#ifdef PROJECTION_GLOBE_VIEW\nvec2 texture_pos=vec2(a_texture_pos);uv=texture_pos/8192.0;vec3 decomposed_pos_and_skirt=decomposeToPosAndSkirt(a_pos);vec3 latLng=u_grid_matrix*vec3(decomposed_pos_and_skirt.xy,1.0);float mercatorY=mercatorYfromLat(latLng[0]);float mercatorX=mercatorXfromLng(latLng[1]);float tiles=u_grid_matrix[0][2];if (tiles > 0.0) {float idx=u_grid_matrix[1][2];float idy=u_grid_matrix[2][2];float uvY=mercatorY*tiles-idy;float uvX=mercatorX*tiles-idx;uv=vec2(uvX,uvY);}float ele=u_raster_elevation;\n#ifdef ELEVATION_REFERENCE_GROUND\nele+=elevation(uv*EXTENT)-decomposed_pos_and_skirt.z;\n#endif\nvec4 merc_world_pos=vec4(0.0);v_split_fade=0.0;if (u_zoom_transition > 0.0) {vec2 merc_pos=vec2(mercatorX,mercatorY);merc_world_pos=vec4(merc_pos,ele,1.0);merc_world_pos.xy-=u_merc_center;merc_world_pos.x=wrap(merc_world_pos.x,-0.5,0.5);merc_world_pos=u_merc_matrix*merc_world_pos;float opposite_merc_center=mod(u_merc_center.x+0.5,1.0);float dist_from_poles=(abs(mercatorY-0.5)*2.0);float range=0.1;v_split_fade=abs(opposite_merc_center-mercatorX);v_split_fade=clamp(1.0-v_split_fade,0.0,1.0);v_split_fade=max(smoothstep(1.0-range,1.0,dist_from_poles),max(smoothstep(1.0-range,1.0,v_split_fade),smoothstep(1.0-range,1.0,1.0-v_split_fade)));}vec3 globe_pos=latLngToECEF(latLng.xy);globe_pos+=normalize(globe_pos)*ele*GLOBE_UPSCALE;vec4 globe_world_pos=u_globe_matrix*vec4(globe_pos,1.0);world_pos=vec4(mix(globe_world_pos.xyz,merc_world_pos.xyz,u_zoom_transition),1.0);\n#ifdef FOG\nv_fog_pos=fog_position((u_normalize_matrix*vec4(globe_pos,1.0)).xyz);\n#endif\n#else\nfloat ele=0.0;vec2 decodedPos=vec2(a_pos);\n#ifdef ELEVATION_REFERENCE_GROUND\nvec3 decomposedPosAndSkirt=decomposeToPosAndSkirt(a_pos);float skirt=decomposedPosAndSkirt.z;decodedPos=decomposedPosAndSkirt.xy;uv=decodedPos/8192.0;ele=elevation(decodedPos)-skirt;\n#else\nuv=vec2(a_texture_pos)/8192.0;\n#endif\nworld_pos=vec4(decodedPos,(u_raster_elevation+ele),1.0);\n#ifdef FOG\nv_fog_pos=fog_position(decodedPos);\n#endif\n#endif\nfloat w=1.0+dot(uv*EXTENT,u_perspective_transform);gl_Position=u_matrix*world_pos*w;\n#endif\nv_pos0=uv;v_pos1=(v_pos0*u_scale_parent)+u_tl_parent;v_pos0=u_texture_offset.x+u_texture_offset.y*v_pos0;v_pos1=u_texture_offset.x+u_texture_offset.y*v_pos1;\n#ifdef ELEVATED\nfloat z=clamp(gl_Position.z/gl_Position.w,0.5,1.0);float zbias=max(0.00005,(pow(z,0.8)-z)*u_zbias_factor);gl_Position.z-=(gl_Position.w*zbias);\n#endif\n#ifdef RENDER_CUTOFF\nv_depth=native_clip_z_to_cutoff_depth(gl_Position.z,gl_Position.w);\n#endif\n}'),symbol:pu('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_lighting.glsl"\n#include "_prelude_shadow.fragment.glsl"\n#include "_prelude_indicator_cutout.fragment.glsl"\n#include "_prelude_feature_cutout.fragment.glsl"\n#define SDF_PX 8.0\n#define SDF 1.0\n#define ICON 0.0\nuniform sampler2D u_texture;\n#ifdef RENDER_TEXT_AND_SYMBOL\nuniform sampler2D u_texture_icon;\n#endif\nuniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;uniform bool u_is_sdf;uniform lowp float u_scale_factor;uniform lowp float u_opacity_multiplier;\n#ifdef ICON_TRANSITION\nuniform float u_icon_transition;\n#endif\n#ifdef COLOR_ADJUSTMENT\nuniform mat4 u_color_adj_mat;\n#endif\n#ifdef RENDER_SHADOWS\nin highp float v_z_offset;\n#endif\nin vec2 v_tex_a;\n#ifdef ICON_TRANSITION\nin vec2 v_tex_b;\n#endif\nin float v_draw_halo;in vec3 v_gamma_scale_size_fade_opacity;\n#ifdef RENDER_TEXT_AND_SYMBOL\nin float is_sdf;in vec2 v_tex_a_icon;\n#endif\n#ifdef RENDER_SHADOWS\nuniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth;\n#endif\n#ifdef APPLY_LUT_ON_GPU\nuniform highp sampler3D u_lutTexture;\n#endif\nin lowp float v_opacity;in lowp vec4 v_fill_np_color;in lowp vec4 v_halo_np_color;in lowp float v_halo_width;in lowp float v_halo_blur;\n#ifdef LIGHTING_3D_MODE\nin lowp float v_emissive_strength;\n#endif\nvoid main() {lowp float opacity=v_opacity;lowp vec4 fill_color=vec4(0.0);lowp vec4 halo_color=vec4(0.0);lowp float halo_width=0.0;lowp float halo_blur=0.0;if (u_is_sdf) {fill_color=vec4(v_fill_np_color.rgb*v_fill_np_color.a,v_fill_np_color.a);halo_color=vec4(v_halo_np_color.rgb*v_halo_np_color.a,v_halo_np_color.a);halo_width=v_halo_width;halo_blur=v_halo_blur;}lowp float emissive_strength=0.0;\n#ifdef LIGHTING_3D_MODE\nemissive_strength=v_emissive_strength;\n#endif\nvec4 out_color;float fade_opacity=v_gamma_scale_size_fade_opacity[2];\n#ifdef RENDER_TEXT_AND_SYMBOL\nif (is_sdf==ICON) {vec2 tex_icon=v_tex_a_icon;lowp float alpha=opacity*fade_opacity*u_opacity_multiplier;vec4 icon_color=texture(u_texture_icon,tex_icon)*alpha;\n#ifdef FOG\nicon_color=fog_dither(fog_apply_premultiplied(icon_color,v_fog_pos));\n#endif\nglFragColor=icon_color;\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nreturn;}\n#endif\nvec2 cutout_factors=vec2(0.0);if (u_is_sdf) {float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_gamma_scale_size_fade_opacity.x;float size=v_gamma_scale_size_fade_opacity.y;float fontScale=u_is_text ? size/24.0 : size;out_color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;bool draw_halo=v_draw_halo > 0.0;if (draw_halo) {out_color=halo_color;gamma=(halo_blur*u_scale_factor*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width*u_scale_factor/fontScale)/SDF_PX;}lowp float dist=texture(u_texture,v_tex_a).r;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);out_color*=alpha;} else {\n#ifdef ICON_TRANSITION\nvec4 a=texture(u_texture,v_tex_a)*(1.0-u_icon_transition);vec4 b=texture(u_texture,v_tex_b)*u_icon_transition;out_color=(a+b);\n#else\nout_color=texture(u_texture,v_tex_a);\n#endif\n#ifdef APPLY_LUT_ON_GPU\nout_color=applyLUT(u_lutTexture,out_color);\n#endif\n#ifdef COLOR_ADJUSTMENT\nout_color=u_color_adj_mat*out_color;\n#endif\n}out_color*=opacity*fade_opacity*u_opacity_multiplier;\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(out_color,emissive_strength);\n#ifdef RENDER_SHADOWS\nfloat light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y);\n#ifdef TERRAIN\nout_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light);\n#else\nout_color.rgb*=mix(v_z_offset !=0.0 ? u_ground_shadow_factor : vec3(1.0),vec3(1.0),light);\n#endif\n#endif\n#endif\n#ifdef FOG\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\n#endif\nglFragColor=out_color;\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}','#include "_prelude_fog.vertex.glsl"\n#include "_prelude_terrain.vertex.glsl"\n#include "_prelude_shadow.vertex.glsl"\n#include "_prelude_ubo_properties.glsl"\n#define USING_APPEARANCE 1.0\nin ivec4 a_pos_offset;in uvec4 a_tex_size;in ivec4 a_pixeloffset;in vec4 a_projected_pos;\n#define FADE_TIME_HALF_PERIOD 2147483648u\n#define FADE_TIME_PERIOD 4294967296.0\n#ifdef GLOBAL_PLACEMENT_FADE\nin highp ivec2 a_fade_ref_time;\n#endif\n#ifdef LEGACY_PLACEMENT_FADE\nin uint a_fade_opacity;\n#endif\n#ifdef Z_OFFSET\nin float a_auto_z_offset;\n#endif\n#ifdef PROJECTION_GLOBE_VIEW\nin ivec4 a_globe_anchor;in vec3 a_globe_normal;\n#endif\n#ifdef ICON_TRANSITION\nin uvec2 a_texb;\n#endif\n#ifdef ELEVATED_ROADS\nin vec3 a_x_axis;in vec3 a_y_axis;uniform float u_normal_scale;\n#endif\n#ifdef RENDER_SHADOWS\nout highp float v_z_offset;\n#endif\nuniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;\n#ifdef RENDER_SHADOWS\nuniform mat4 u_inv_matrix;\n#endif\nuniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_elevation_from_sea;uniform bool u_pitch_with_map;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;\n#ifdef GLOBAL_PLACEMENT_FADE\nuniform highp int u_now;uniform float u_fade_duration;\n#endif\n#ifdef LEGACY_PLACEMENT_FADE\nuniform float u_fade_change;\n#endif\nuniform vec2 u_texsize;\n#ifdef PROJECTION_GLOBE_VIEW\nuniform vec3 u_up_vector;\n#endif\n#ifdef RENDER_TEXT_AND_SYMBOL\nuniform vec2 u_texsize_icon;\n#endif\nuniform bool u_is_halo;\n#ifdef PROJECTION_GLOBE_VIEW\nuniform vec3 u_tile_id;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_camera_forward;uniform float u_zoom_transition;uniform vec3 u_ecef_origin;uniform mat4 u_tile_matrix;\n#endif\nout vec2 v_tex_a;\n#ifdef ICON_TRANSITION\nout vec2 v_tex_b;\n#endif\nout float v_draw_halo;out vec3 v_gamma_scale_size_fade_opacity;\n#ifdef RENDER_TEXT_AND_SYMBOL\nout float is_sdf;out vec2 v_tex_a_icon;\n#endif\n#ifdef RENDER_SHADOWS\nuniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth;\n#endif\n#define SPP_HEADER_SIZE_VEC4 4u\nstruct SymbolPaintProperties {vec4 fill_np_color;vec4 halo_np_color;float opacity;float halo_width;float halo_blur;float emissive_strength;float occlusion_opacity;float z_offset;vec2 translate;};uniform lowp vec4 u_spp_fill_np_color;uniform lowp vec4 u_spp_halo_np_color;uniform lowp float u_spp_opacity;uniform lowp float u_spp_halo_width;uniform lowp float u_spp_halo_blur;uniform lowp float u_spp_emissive_strength;uniform lowp float u_spp_occlusion_opacity;uniform highp float u_spp_z_offset;uniform lowp vec2 u_spp_translate_rotation;uniform highp float u_spp_zoom_fraction;in float a_feature_index;layout(std140) uniform SymbolPaintPropertiesHeaderUniform {uvec4 header[SPP_HEADER_SIZE_VEC4];} u_spp_header;layout(std140) uniform SymbolPaintPropertiesUniform {vec4 properties[MAX_UBO_SIZE_VEC4];} u_spp_properties;layout(std140) uniform SymbolPaintPropertiesIndexUniform {uvec4 block_indices[MAX_UBO_SIZE_VEC4];} u_spp_index;out lowp float v_opacity;out lowp vec4 v_fill_np_color;out lowp vec4 v_halo_np_color;out lowp float v_halo_width;out lowp float v_halo_blur;\n#ifdef LIGHTING_3D_MODE\nout lowp float v_emissive_strength;\n#endif\nuint uvec4At(uvec4 v,uint index) {return (index==0u) ? v.x :\n(index==1u) ? v.y :\n(index==2u) ? v.z : v.w;}vec4 readColor(uint base,bool isDataDriven,uint offsetVec4,uint dzr,vec2 headerZoom,vec4 fallbackValue) {if (!isDataDriven) return fallbackValue;vec4 value=u_spp_properties.properties[base+offsetVec4];vec2 blockZoom=u_spp_properties.properties[base+offsetVec4+dzr].xy;vec2 zr=mix(headerZoom,blockZoom,float(dzr));return unpack_mix_color(value,zoomFactor(zr.x,zr.y,u_spp_zoom_fraction));}float readScalar(uint base,bool isDataDriven,uint offsetVec4,float fallbackValue) {if (!isDataDriven) return fallbackValue;vec4 slot=u_spp_properties.properties[base+offsetVec4];return unpack_mix_vec2(slot.xy,zoomFactor(slot.z,slot.w,u_spp_zoom_fraction));}vec2 readTranslate(uint base,bool isDataDriven,uint offsetVec4,uint dzr) {if (!isDataDriven) return vec2(0.0);vec4 value=u_spp_properties.properties[base+offsetVec4];vec2 blockZoom=u_spp_properties.properties[base+offsetVec4+dzr].xy;float t=zoomFactor(blockZoom.x,blockZoom.y,u_spp_zoom_fraction)*float(dzr);return mix(value.xy,value.zw,t);}SymbolPaintProperties readSymbolPaintProperties() {uint dataDrivenMask=u_spp_header.header[0][0];uint dzrMask =u_spp_header.header[0][1];uint blockSizeVec4 =u_spp_header.header[0][2];uint fillColorDzr=dzrMask & 1u;uint haloColorDzr=(dzrMask >> 1u) & 1u;vec2 fillColorHeaderZoom=uintBitsToFloat(u_spp_header.header[3].xy);vec2 haloColorHeaderZoom=uintBitsToFloat(u_spp_header.header[3].zw);uint featureIndex=uint(a_feature_index);uvec4 indexSlot=u_spp_index.block_indices[featureIndex/4u];uint base=uvec4At(indexSlot,featureIndex % 4u)*blockSizeVec4;SymbolPaintProperties props;props.fill_np_color =readColor(base,(dataDrivenMask & (1u << 0u)) !=0u,u_spp_header.header[0][3],fillColorDzr,fillColorHeaderZoom,u_spp_fill_np_color);props.halo_np_color =readColor(base,(dataDrivenMask & (1u << 1u)) !=0u,u_spp_header.header[1][0],haloColorDzr,haloColorHeaderZoom,u_spp_halo_np_color);props.opacity =readScalar(base,(dataDrivenMask & (1u << 2u)) !=0u,u_spp_header.header[1][1],u_spp_opacity);props.halo_width =readScalar(base,(dataDrivenMask & (1u << 3u)) !=0u,u_spp_header.header[1][2],u_spp_halo_width);props.halo_blur =readScalar(base,(dataDrivenMask & (1u << 4u)) !=0u,u_spp_header.header[1][3],u_spp_halo_blur);props.emissive_strength=readScalar(base,(dataDrivenMask & (1u << 5u)) !=0u,u_spp_header.header[2][0],u_spp_emissive_strength);props.occlusion_opacity=readScalar(base,(dataDrivenMask & (1u << 6u)) !=0u,u_spp_header.header[2][1],u_spp_occlusion_opacity);props.z_offset =readScalar(base,(dataDrivenMask & (1u << 7u)) !=0u,u_spp_header.header[2][2],u_spp_z_offset);uint translateDzr=(dzrMask >> 8u) & 1u;props.translate =readTranslate(base,(dataDrivenMask & (1u << 8u)) !=0u,u_spp_header.header[2][3],translateDzr);return props;}vec2 unpack_opacity(uint packedOpacity) {return vec2(float(packedOpacity/2u)/127.0,float(packedOpacity & 1u));}void main() {SymbolPaintProperties paint_properties=readSymbolPaintProperties();lowp float opacity=paint_properties.opacity;v_opacity=opacity;v_fill_np_color=paint_properties.fill_np_color;v_halo_np_color=paint_properties.halo_np_color;v_halo_width=paint_properties.halo_width;v_halo_blur=paint_properties.halo_blur;\n#ifdef LIGHTING_3D_MODE\nv_emissive_strength=paint_properties.emissive_strength;\n#endif\nlowp float occlusion_opacity=paint_properties.occlusion_opacity;highp float z_offset=paint_properties.z_offset;vec2 a_pos=vec2(a_pos_offset.xy);vec2 a_offset=vec2(a_pos_offset.zw);vec2 a_tex=vec2(a_tex_size.xy);vec2 a_size=vec2(a_tex_size.zw);float a_size_min=floor(a_size[0]*0.5);float a_size_max= floor(a_size[1]*0.5);float a_apperance=a_size[1]-2.0*a_size_max;vec2 a_pxoffset=vec2(a_pixeloffset.xy);vec2 a_min_font_scale=vec2(a_pixeloffset.zw)/256.0;highp float segment_angle=-a_projected_pos[3];float size;if (a_apperance==USING_APPEARANCE) {size=a_size_max/128.0;} else if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size_max,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 tile_anchor=a_pos;float e=u_elevation_from_sea ? z_offset : z_offset+elevation(tile_anchor);\n#ifdef Z_OFFSET\ne+=a_auto_z_offset;\n#endif\nvec3 h=elevationVector(tile_anchor)*e;float globe_occlusion_fade;vec3 world_pos;vec3 mercator_pos;vec3 world_pos_globe;\n#ifdef PROJECTION_GLOBE_VIEW\nmercator_pos=mercator_tile_position(u_inv_rot_matrix,tile_anchor,u_tile_id,u_merc_center);world_pos_globe=vec3(a_globe_anchor)+h;world_pos=mix_globe_mercator(world_pos_globe,mercator_pos,u_zoom_transition);vec4 ecef_point=u_tile_matrix*vec4(world_pos,1.0);vec3 origin_to_point=ecef_point.xyz-u_ecef_origin;globe_occlusion_fade=dot(origin_to_point,u_camera_forward) >=0.0 ? 0.0 : 1.0;\n#else\nworld_pos=vec3(tile_anchor,0)+h;globe_occlusion_fade=1.0;\n#endif\nvec4 projected_point=u_matrix*vec4(world_pos,1);highp float camera_to_anchor_distance=projected_point.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(\n0.5+0.5*distance_ratio,0.0,1.5);size*=perspective_ratio;float font_scale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetprojected_point;vec2 a;\n#ifdef PROJECTION_GLOBE_VIEW\nvec3 displacement=vec3(a_globe_normal.z,0,-a_globe_normal.x);offsetprojected_point=u_matrix*vec4(vec3(a_globe_anchor)+displacement,1);vec4 projected_point_globe=u_matrix*vec4(world_pos_globe,1);a=projected_point_globe.xy/projected_point_globe.w;\n#else\noffsetprojected_point=u_matrix*vec4(tile_anchor+vec2(1,0),0,1);a=projected_point.xy/projected_point.w;\n#endif\nvec2 b=offsetprojected_point.xy/offsetprojected_point.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}vec4 projected_pos;\n#ifdef PROJECTION_GLOBE_VIEW\n#ifdef PROJECTED_POS_ON_VIEWPORT\nprojected_pos=u_label_plane_matrix*vec4(a_projected_pos.xyz+h,1.0);\n#else\nvec3 proj_pos=mix_globe_mercator(a_projected_pos.xyz,mercator_pos,u_zoom_transition)+h;projected_pos=u_label_plane_matrix*vec4(proj_pos,1.0);\n#endif\n#else\nprojected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,h.z,1.0);\n#endif\nhighp 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);float z=0.0;vec2 offset=rotation_matrix*(a_offset/32.0*max(a_min_font_scale,font_scale)+a_pxoffset/16.0);\n#ifdef TERRAIN\n#ifdef PITCH_WITH_MAP_TERRAIN\nvec4 tile_pos=u_label_plane_matrix_inv*vec4(a_projected_pos.xy+offset,0.0,1.0);z=elevation(tile_pos.xy);\n#endif\n#endif\n#ifdef Z_OFFSET\nz+=u_pitch_with_map ? a_auto_z_offset+z_offset : 0.0;\n#else\nz+=u_pitch_with_map ? z_offset : 0.0;\n#endif\nfloat occlusion_fade=globe_occlusion_fade;float out_fade_opacity=occlusion_fade;\n#ifdef GLOBAL_PLACEMENT_FADE\nhighp int fade_state=a_fade_ref_time.y;float fade_target=float(fade_state & 1);highp uint fade_elapsed_bits=uint(u_now)-uint(a_fade_ref_time.x);float fade_elapsed=float(fade_elapsed_bits);if (fade_elapsed_bits >=FADE_TIME_HALF_PERIOD) fade_elapsed-=FADE_TIME_PERIOD;bool fade_settled=(fade_state & 2) !=0;float fade_t=(fade_settled || u_fade_duration==0.0) ? 1.0 : fade_elapsed/u_fade_duration;float raw_fade_opacity=fade_target > 0.5 ? fade_t : 1.0-fade_t;out_fade_opacity=clamp(raw_fade_opacity,0.0,occlusion_fade);\n#endif\n#ifdef LEGACY_PLACEMENT_FADE\nvec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;out_fade_opacity=max(0.0,min(occlusion_fade,fade_opacity[0]+fade_change));\n#endif\n#ifdef DEPTH_OCCLUSION\nfloat depth_occlusion=occlusionFadeMultiSample(projected_point);float depth_occlusion_multplier=mix(occlusion_opacity,1.0,depth_occlusion);out_fade_opacity*=depth_occlusion_multplier;\n#endif\nfloat alpha=opacity*out_fade_opacity;float hidden=float(alpha==0.0 || projected_point.w <=0.0 || occlusion_fade==0.0);vec3 pos;\n#ifdef PROJECTION_GLOBE_VIEW\nvec3 xAxis=u_pitch_with_map ? normalize(cross(a_globe_normal,u_up_vector)) : vec3(1,0,0);vec3 yAxis=u_pitch_with_map ? normalize(cross(a_globe_normal,xAxis)) : vec3(0,1,0);pos=projected_pos.xyz/projected_pos.w+xAxis*offset.x+yAxis*offset.y;\n#else\n#ifdef ELEVATED_ROADS\nvec3 xAxis=vec3(a_x_axis.xy,a_x_axis.z*u_normal_scale);vec3 yAxis=vec3(a_y_axis.xy,a_y_axis.z*u_normal_scale);pos=projected_pos.xyz/projected_pos.w+xAxis*offset.x+yAxis*offset.y;\n#else\npos=vec3(projected_pos.xy/projected_pos.w+offset,z);\n#endif\n#endif\ngl_Position=mix(u_coord_matrix*vec4(pos,1.0),AWAY,hidden);{vec2 tr=paint_properties.translate;vec2 rotated_tr=vec2(\nu_spp_translate_rotation.x*tr.x-u_spp_translate_rotation.y*tr.y,u_spp_translate_rotation.y*tr.x+u_spp_translate_rotation.x*tr.y\n);gl_Position.xy+=(u_coord_matrix*vec4(rotated_tr,0.0,0.0)).xy;}float gamma_scale=gl_Position.w;v_draw_halo=(u_is_halo && float(gl_InstanceID)==0.0) ? 1.0 : 0.0;v_gamma_scale_size_fade_opacity=vec3(gamma_scale,size,out_fade_opacity);v_tex_a=a_tex/u_texsize;\n#ifdef RENDER_TEXT_AND_SYMBOL\nis_sdf=a_size[0]-2.0*a_size_min;v_tex_a_icon=a_tex/u_texsize_icon;\n#endif\n#ifdef ICON_TRANSITION\nv_tex_b=vec2(a_texb)/u_texsize;\n#endif\n#ifdef RENDER_SHADOWS\nvec4 shd_pos=u_inv_matrix*vec4(pos,1.0);vec3 shd_pos0=shd_pos.xyz;vec3 shd_pos1=shd_pos.xyz;\n#ifdef NORMAL_OFFSET\nvec3 shd_pos_offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=shd_pos_offset*shadow_normal_offset_multiplier0();shd_pos1+=shd_pos_offset*shadow_normal_offset_multiplier1();\n#endif\nv_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w;\n#endif\n#ifdef FOG\nv_fog_pos=fog_position(world_pos);\n#endif\n#ifdef RENDER_SHADOWS\nv_z_offset=e;\n#endif\n}'),skybox:pu('#include "_prelude_fog.fragment.glsl"\nin lowp vec3 v_uv;uniform lowp samplerCube u_cubemap;uniform lowp float u_opacity;uniform highp float u_temporal_offset;uniform highp vec3 u_sun_direction;float sun_disk(highp vec3 ray_direction,highp vec3 sun_direction) {highp float cos_angle=dot(normalize(ray_direction),sun_direction);const highp float cos_sun_angular_diameter=0.99996192306;const highp float smoothstep_delta=1e-5;return smoothstep(\ncos_sun_angular_diameter-smoothstep_delta,cos_sun_angular_diameter+smoothstep_delta,cos_angle);}float map(float value,float start,float end,float new_start,float new_end) {return ((value-start)*(new_end-new_start))/(end-start)+new_start;}void main() {vec3 uv=v_uv;const float y_bias=0.015;uv.y+=y_bias;uv.y=pow(abs(uv.y),1.0/5.0);uv.y=map(uv.y,0.0,1.0,-1.0,1.0);vec3 sky_color=texture(u_cubemap,uv).rgb;\n#ifdef FOG\nsky_color=fog_apply_sky_gradient(v_uv.xzy,sky_color);\n#endif\nsky_color+=0.1*sun_disk(v_uv,u_sun_direction);glFragColor=vec4(sky_color*u_opacity,u_opacity);\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\n}',Gd),skyboxGradient:pu('#include "_prelude_fog.fragment.glsl"\nin highp vec3 v_uv;uniform lowp sampler2D u_color_ramp;uniform highp vec3 u_center_direction;uniform lowp float u_radius;uniform lowp float u_opacity;uniform highp float u_temporal_offset;void main() {float progress=acos(dot(normalize(v_uv),u_center_direction))/u_radius;vec4 color=texture(u_color_ramp,vec2(progress,0.5));\n#ifdef FOG\ncolor.rgb=fog_apply_sky_gradient(v_uv.xzy,color.rgb/color.a)*color.a;\n#endif\ncolor*=u_opacity;glFragColor=color;\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\n}',Gd),skyboxCapture:pu("\nin highp vec3 v_position;uniform highp float u_sun_intensity;uniform highp float u_luminance;uniform lowp vec3 u_sun_direction;uniform highp vec4 u_color_tint_r;uniform highp vec4 u_color_tint_m;precision highp float;\n#define BETA_R vec3(5.5e-6,13.0e-6,22.4e-6)\n#define BETA_M vec3(21e-6,21e-6,21e-6)\n#define MIE_G 0.76\n#define DENSITY_HEIGHT_SCALE_R 8000.0\n#define DENSITY_HEIGHT_SCALE_M 1200.0\n#define PLANET_RADIUS 6360e3\n#define ATMOSPHERE_RADIUS 6420e3\n#define SAMPLE_STEPS 10\n#define DENSITY_STEPS 4\nfloat ray_sphere_exit(vec3 orig,vec3 dir,float radius) {float a=dot(dir,dir);float b=2.0*dot(dir,orig);float c=dot(orig,orig)-radius*radius;float d=sqrt(b*b-4.0*a*c);return (-b+d)/(2.0*a);}vec3 extinction(vec2 density) {return exp(-vec3(BETA_R*u_color_tint_r.a*density.x+BETA_M*u_color_tint_m.a*density.y));}vec2 local_density(vec3 point) {float height=max(length(point)-PLANET_RADIUS,0.0);float exp_r=exp(-height/DENSITY_HEIGHT_SCALE_R);float exp_m=exp(-height/DENSITY_HEIGHT_SCALE_M);return vec2(exp_r,exp_m);}float phase_ray(float cos_angle) {return (3.0/(16.0*PI))*(1.0+cos_angle*cos_angle);}float phase_mie(float cos_angle) {return (3.0/(8.0*PI))*((1.0-MIE_G*MIE_G)*(1.0+cos_angle*cos_angle))/((2.0+MIE_G*MIE_G)*pow(1.0+MIE_G*MIE_G-2.0*MIE_G*cos_angle,1.5));}vec2 density_to_atmosphere(vec3 point,vec3 light_dir) {float ray_len=ray_sphere_exit(point,light_dir,ATMOSPHERE_RADIUS);float step_len=ray_len/float(DENSITY_STEPS);vec2 density_point_to_atmosphere=vec2(0.0);for (int i=0; i < DENSITY_STEPS;++i) {vec3 point_on_ray=point+light_dir*((float(i)+0.5)*step_len);density_point_to_atmosphere+=local_density(point_on_ray)*step_len;;}return density_point_to_atmosphere;}vec3 atmosphere(vec3 ray_dir,vec3 sun_direction,float sun_intensity) {vec2 density_orig_to_point=vec2(0.0);vec3 scatter_r=vec3(0.0);vec3 scatter_m=vec3(0.0);vec3 origin=vec3(0.0,PLANET_RADIUS,0.0);float ray_len=ray_sphere_exit(origin,ray_dir,ATMOSPHERE_RADIUS);float step_len=ray_len/float(SAMPLE_STEPS);for (int i=0; i < SAMPLE_STEPS;++i) {vec3 point_on_ray=origin+ray_dir*((float(i)+0.5)*step_len);vec2 density=local_density(point_on_ray)*step_len;density_orig_to_point+=density;vec2 density_point_to_atmosphere=density_to_atmosphere(point_on_ray,sun_direction);vec2 density_orig_to_atmosphere=density_orig_to_point+density_point_to_atmosphere;vec3 extinction=extinction(density_orig_to_atmosphere);scatter_r+=density.x*extinction;scatter_m+=density.y*extinction;}float cos_angle=dot(ray_dir,sun_direction);float phase_r=phase_ray(cos_angle);float phase_m=phase_mie(cos_angle);vec3 beta_r=BETA_R*u_color_tint_r.rgb*u_color_tint_r.a;vec3 beta_m=BETA_M*u_color_tint_m.rgb*u_color_tint_m.a;return (scatter_r*phase_r*beta_r+scatter_m*phase_m*beta_m)*sun_intensity;}const float A=0.15;const float B=0.50;const float C=0.10;const float D=0.20;const float E=0.02;const float F=0.30;vec3 uncharted2_tonemap(vec3 x) {return ((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;}void main() {vec3 ray_direction=v_position;ray_direction.y=pow(ray_direction.y,5.0);const float y_bias=0.015;ray_direction.y+=y_bias;vec3 color=atmosphere(normalize(ray_direction),u_sun_direction,u_sun_intensity);float white_scale=1.0748724675633854;color=uncharted2_tonemap((log2(2.0/pow(u_luminance,4.0)))*color)*white_scale;glFragColor=vec4(color,1.0);}","in highp vec3 a_pos_3f;uniform mat3 u_matrix_3f;out highp vec3 v_position;float map(float value,float start,float end,float new_start,float new_end) {return ((value-start)*(new_end-new_start))/(end-start)+new_start;}void main() {vec4 pos=vec4(u_matrix_3f*a_pos_3f,1.0);v_position=native_cubemap_direction(pos.xyz);v_position.y=map(v_position.y,-1.0,1.0,0.0,1.0);gl_Position=vec4(a_pos_3f.xy,0.0,1.0);}"),globeAtmosphere:pu('#include "_prelude_fog.fragment.glsl"\nuniform float u_transition;uniform highp float u_fadeout_range;uniform highp float u_temporal_offset;uniform vec4 u_atmosphere_fog_color;uniform vec4 u_high_color;uniform vec4 u_space_color;uniform float u_horizon_angle;in highp vec3 v_ray_dir;in highp vec3 v_horizon_dir;void main() {highp vec3 dir=normalize(v_ray_dir);float globe_pos_dot_dir;\n#ifdef PROJECTION_GLOBE_VIEW\nglobe_pos_dot_dir=dot(u_globe_pos,dir);highp vec3 closest_point_forward=abs(globe_pos_dot_dir)*dir;float norm_dist_from_center=length(closest_point_forward-u_globe_pos)/u_globe_radius;if (norm_dist_from_center < 0.98) {\n#ifdef ALPHA_PASS\nglFragColor=vec4(0,0,0,0);return;\n#else\nglFragColor=vec4(0,0,0,1);return;\n#endif\n}\n#endif\nhighp vec3 horizon_dir=normalize(v_horizon_dir);float horizon_angle_mercator=dir.y < horizon_dir.y ?\n0.0 : max(acos(clamp(dot(dir,horizon_dir),-1.0,1.0)),0.0);float horizon_angle;\n#ifdef PROJECTION_GLOBE_VIEW\nhighp vec3 closest_point=globe_pos_dot_dir*dir;highp float closest_point_to_center=length(closest_point-u_globe_pos);highp float theta=asin(clamp(closest_point_to_center/length(u_globe_pos),-1.0,1.0));horizon_angle=globe_pos_dot_dir < 0.0 ?\nPI-theta-u_horizon_angle : theta-u_horizon_angle;float angle_t=pow(u_transition,10.0);horizon_angle=mix(horizon_angle,horizon_angle_mercator,angle_t);\n#else\nhorizon_angle=horizon_angle_mercator;\n#endif\nhorizon_angle/=PI;float t=exp(-horizon_angle/u_fadeout_range);float alpha_0=u_atmosphere_fog_color.a;float alpha_1=u_high_color.a;float alpha_2=u_space_color.a;vec3 color_stop_0=u_atmosphere_fog_color.rgb;vec3 color_stop_1=u_high_color.rgb;vec3 color_stop_2=u_space_color.rgb;\n#ifdef ALPHA_PASS\nfloat a0=mix(alpha_2,1.0,alpha_1);float a1=mix(a0,1.0,alpha_0);float a2=mix(a0,a1,t);float a =mix(alpha_2,a2,t);glFragColor=vec4(1.0,1.0,1.0,a);\n#else\nvec3 c0=mix(color_stop_2,color_stop_1,alpha_1);vec3 c1=mix(c0,color_stop_0,alpha_0);vec3 c2=mix(c0,c1,t);vec3 c=c2;glFragColor=vec4(c*t,t);\n#endif\n}',"in vec3 a_pos;in vec2 a_uv;uniform vec3 u_frustum_tl;uniform vec3 u_frustum_tr;uniform vec3 u_frustum_br;uniform vec3 u_frustum_bl;uniform float u_horizon;out highp vec3 v_ray_dir;out highp vec3 v_horizon_dir;void main() {v_ray_dir=mix(\nmix(u_frustum_tl,u_frustum_tr,a_uv.x),mix(u_frustum_bl,u_frustum_br,a_uv.x),a_uv.y);v_horizon_dir=mix(\nmix(u_frustum_tl,u_frustum_bl,u_horizon),mix(u_frustum_tr,u_frustum_br,u_horizon),a_uv.x);gl_Position=vec4(a_pos,1.0);}"),stars:pu("in highp vec2 v_uv;in mediump float v_intensity;float shapeCircle(in vec2 uv)\n{float beginFade=0.6;float lengthFromCenter=length(v_uv);return 1.0-clamp((lengthFromCenter-beginFade)/(1.0-beginFade),0.0,1.0);}void main() {float alpha=shapeCircle(v_uv);vec3 color=vec3(1.0,1.0,1.0);alpha*=v_intensity;glFragColor=vec4(color*alpha,alpha);HANDLE_WIREFRAME_DEBUG;}","\nin vec3 a_pos_3f;in vec2 a_uv;in float a_size_scale;in float a_opacity;uniform mat4 u_matrix;uniform vec3 u_up;uniform vec3 u_right;uniform float u_intensity_multiplier;out highp vec2 v_uv;out mediump float v_intensity;void main() {v_uv=a_uv;v_intensity=a_opacity*u_intensity_multiplier;vec3 pos=a_pos_3f;pos+=a_uv.x*u_right*a_size_scale;pos+=a_uv.y*u_up*a_size_scale;gl_Position=u_matrix*vec4(pos,1.0);}"),occlusion:pu("uniform vec4 u_color;void main() {glFragColor=u_color;}",'#include "_prelude_terrain.vertex.glsl"\nin highp vec2 a_offset_xy;uniform highp vec3 u_anchorPos;uniform mat4 u_matrix;uniform vec2 u_screenSizePx;uniform vec2 u_occluderSizePx;void main() {vec3 world_pos=u_anchorPos;\n#ifdef TERRAIN\nfloat e=elevation(world_pos.xy);world_pos.z+=e;\n#endif\nvec4 projected_point=u_matrix*vec4(world_pos,1.0);projected_point.xy+=projected_point.w*a_offset_xy*0.5*u_occluderSizePx/u_screenSizePx;gl_Position=projected_point;}')};function uu(e,t){const i=e.split("\n");for(let e of i){if(e=e.trimStart(),"#"!==e[0])continue;if(!e.includes("if"))continue;if(e.startsWith("#endif"))continue;const i=e.match(eu);if(i)for(const e of i)tu.has(e)||t.add(e)}}function _u(e){return new Set(["uint","int","uvec2","ivec2","uvec3","ivec3","uvec4","ivec4"]).has(e)}function pu(e,t){const i=new Set,s=[],o=[];e=e.replace(Jd,(e,t)=>(o.push(t),"")),t=t.replace(Jd,(e,t)=>(s.push(t),""));let r=new Set(iu);uu(e,r),uu(t,r);for(const e of[...s,...o])ou[e]||(ou[e]=new Set,uu(su[e],ou[e])),r=new Set([...r,...ou[e]]);return{fragmentSource:e=e.replace(Qd,(e,t,s,o,r)=>(i.add(r),"define"===t?`\n#ifndef HAS_UNIFORM_u_${r}\n${_u(o)?"flat ":""}in ${s} ${o} ${r};\n#else\nuniform ${s} ${o} u_${r};\n#endif\n`:"initialize"===t?`\n#ifdef HAS_UNIFORM_u_${r}\n ${s} ${o} ${r} = u_${r};\n#endif\n`:"define-attribute"===t?`\n#ifdef HAS_ATTRIBUTE_a_${r}\n in ${s} ${o} ${r};\n#endif\n`:"initialize-attribute"===t?"":void 0)),vertexSource:t=t.replace(Qd,(e,t,s,o,r)=>{const n=`MATERIAL_ATTRIBUTE_OFFSET_${r}`,a="float"===o?"vec2":o,l=`GET_ATTRIBUTE_${a}(a_${r}, materialInfo, ${n})`,c=r.includes("color")?"color":a;return"define-attribute-vertex-shader-only"===t?`\n#ifdef HAS_ATTRIBUTE_a_${r}\nin ${s} ${o} a_${r};\n#endif\n`:i.has(r)?"define"===t?`\n#ifndef HAS_UNIFORM_u_${r}\nuniform lowp float u_${r}_t;\n #if !defined(${n})\n in ${s} ${a} a_${r};\n #endif\n${_u(o)?"flat ":""}out ${s} ${o} ${r};\n#else\nuniform ${s} ${o} u_${r};\n#endif\n`:"initialize"===t?"vec4"===c||"uvec4"===c?`\n#ifndef HAS_UNIFORM_u_${r}\n ${r} = a_${r};\n#else\n ${s} ${o} ${r} = u_${r};\n#endif\n`:`\n#if !defined(HAS_UNIFORM_u_${r})\n #ifdef ${n}\n ${r} = unpack_mix_${c}(${l}, u_${r}_t);\n #else\n ${r} = unpack_mix_${c}(a_${r}, u_${r}_t);\n #endif\n#else\n ${s} ${o} ${r} = u_${r};\n#endif\n`:"define-attribute"===t?`\n#ifdef HAS_ATTRIBUTE_a_${r}\n in ${s} ${o} a_${r};\n out ${s} ${o} ${r};\n#endif\n`:"initialize-attribute"===t?`\n#ifdef HAS_ATTRIBUTE_a_${r}\n ${r} = a_${r};\n#endif\n`:void 0:"define"===t?`\n#ifndef HAS_UNIFORM_u_${r}\nuniform lowp float u_${r}_t;\n #if !defined(${n})\n in ${s} ${a} a_${r};\n #endif\n#else\nuniform ${s} ${o} u_${r};\n#endif\n`:"define-instanced"===t?"mat4"===c?`\n#ifdef INSTANCED_ARRAYS\nin vec4 a_${r}0;\nin vec4 a_${r}1;\nin vec4 a_${r}2;\nin vec4 a_${r}3;\n#else\nuniform ${s} ${o} u_${r};\n#endif\n`:`\n#ifdef INSTANCED_ARRAYS\nin ${s} ${a} a_${r};\n#else\nuniform ${s} ${o} u_${r};\n#endif\n`:"initialize-attribute-custom"===t?`\n#ifdef HAS_ATTRIBUTE_a_${r}\n ${s} ${o} ${r} = a_${r};\n#endif\n`:"vec4"===c||"uvec4"===c?`\n#ifndef HAS_UNIFORM_u_${r}\n #ifdef ${n}\n ${s} ${o} ${r} = ${l};\n #else\n ${s} ${o} ${r} = a_${r};\n #endif\n#else\n ${s} ${o} ${r} = u_${r};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${r}\n #ifdef ${n}\n ${s} ${o} ${r} = unpack_mix_${c}(${l}, u_${r}_t);\n #else\n ${s} ${o} ${r} = unpack_mix_${c}(a_${r}, u_${r}_t);\n #endif\n#else\n ${s} ${o} ${r} = u_${r};\n#endif\n`}),usedDefines:r,vertexIncludes:s,fragmentIncludes:o}}class fu{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffers=[],this.vao=null}bind(e,t,i,s,o,r,n,a){this.context=e;let l=this.boundPaintVertexBuffers.length!==s.length;for(let e=0;!l&&e<s.length;e++)this.boundPaintVertexBuffers[e]!==s[e]&&(l=!0);let c=this.boundDynamicVertexBuffers.length!==n.length;for(let e=0;!c&&e<n.length;e++){const t=this.boundDynamicVertexBuffers[e],i=n[e];t===i||t&&i&&t.attributes===i.attributes||(c=!0)}if(!this.vao||this.boundProgram!==t||this.boundLayoutVertexBuffer!==i||l||c||this.boundIndexBuffer!==o||this.boundVertexOffset!==r)this.freshBind(t,i,s,o,r,n,a);else{e.bindVertexArrayOES.set(this.vao);for(let i=0;i<n.length;i++){const s=n[i];s&&(s!==this.boundDynamicVertexBuffers[i]&&(s.bind(),s.setVertexAttribPointers(e.gl,t,r)),a&&s.instanceCount&&s.setVertexAttribDivisor(e.gl,t,a))}o&&o.dynamicDraw&&o.bind(),this.boundDynamicVertexBuffers=n}}freshBind(e,t,i,s,o,r,n){const a=this.context,l=a.gl;this.vao&&this.destroy(),this.vao=a.gl.createVertexArray(),a.bindVertexArrayOES.set(this.vao),this.boundProgram=e,this.boundLayoutVertexBuffer=t,this.boundPaintVertexBuffers=i,this.boundIndexBuffer=s,this.boundVertexOffset=o,this.boundDynamicVertexBuffers=r,t.enableAttributes(l,e),t.bind(),t.setVertexAttribPointers(l,e,o);for(const t of i)t.enableAttributes(l,e),t.bind(),t.setVertexAttribPointers(l,e,o);for(const t of r)t&&(t.enableAttributes(l,e),t.bind(),t.setVertexAttribPointers(l,e,o),n&&t.instanceCount&&t.setVertexAttribDivisor(l,e,n));s&&s.bind()}destroy(){this.vao&&(this.context.gl.deleteVertexArray(this.vao),this.vao=null)}}function mu(){return{u_dem:2,u_dem_prev:4,u_dem_tl:[0,0],u_dem_tl_prev:[0,0],u_dem_scale:0,u_dem_scale_prev:0,u_dem_size:0,u_dem_lerp:1,u_depth:3,u_depth_size_inv:[0,0],u_depth_range_unpack:[0,1],u_occluder_half_size:16,u_occlusion_depth_offset:-1e-4,u_exaggeration:0}}class gu{constructor(e=0,t=0,i=0,s=0){if(isNaN(e)||e<0||isNaN(t)||t<0||isNaN(i)||i<0||isNaN(s)||s<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=s}interpolate(e,t,i){return null!=t.top&&null!=e.top&&(this.top=J(e.top,t.top,i)),null!=t.bottom&&null!=e.bottom&&(this.bottom=J(e.bottom,t.bottom,i)),null!=t.left&&null!=e.left&&(this.left=J(e.left,t.left,i)),null!=t.right&&null!=e.right&&(this.right=J(e.right,t.right,i)),this}getCenter(e,t){const i=Ee((this.left+e-this.right)/2,0,e),s=Ee((this.top+t-this.bottom)/2,0,t);return new m(i,s)}equals(e){return this.top===e.top&&this.bottom===e.bottom&&this.left===e.left&&this.right===e.right}clone(){return new gu(this.top,this.bottom,this.left,this.right)}toJSON(){return{top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}function vu(e,t){const i=bs(e,3);ys(e,t),Ts(e,3,i)}function yu(e,t){const i=fs([]);return ms(i,i,-t),gs(i,i,-e),i}function xu(e,t){const i=[e[0],e[1],0],s=[t[0],t[1],0];if(_s(i)>=1e-15){const e=ye([],i);Ti(s,e,Kt(s,e)),t[0]=s[0],t[1]=s[1]}const o=Ht([],t,e);if(ps(o)<1e-15)return null;const r=Math.atan2(-o[1],o[0]);return yu(Math.atan2(Math.sqrt(e[0]*e[0]+e[1]*e[1]),-e[2]),r)}class bu{constructor(e,t){this.position=e,this.orientation=t}get position(){return this._position}set position(e){if(e){const t=e instanceof we?e:new we(e[0],e[1],e[2]);this._renderWorldCopies&&(t.x=si(t.x,0,1)),this._position=t}else this._position=null}lookAtPoint(e,t,i){if(this.orientation=null,!this.position)return;const s=this.position,o=i||(this._elevation?this._elevation.getAtPointOrZero(we.fromLngLat(e)):0),r=we.fromLngLat(e,o),n=[r.x-s.x,r.y-s.y,r.z-s.z];t||(t=[0,0,1]),t[2]=Math.abs(t[2]),this.orientation=xu(n,t)}setPitchBearing(e,t){this.orientation=yu(le(e),le(-t))}}class wu{constructor(e,t){this._transform=ci([]),this.orientation=t,this.position=e}get mercatorPosition(){const e=this.position;return new we(e[0],e[1],e[2])}get position(){const e=bs(this._transform,3);return[e[0],e[1],e[2]]}set position(e){var t;e&&Ts(this._transform,3,[(t=e)[0],t[1],t[2],1])}get orientation(){return this._orientation}set orientation(e){this._orientation=e||fs([]),e&&vu(this._transform,this._orientation)}getPitchBearing(){const e=this.forward(),t=this.right();return{bearing:Math.atan2(-t[1],t[0]),pitch:Math.atan2(Math.sqrt(e[0]*e[0]+e[1]*e[1]),-e[2])}}setPitchBearing(e,t){this._orientation=yu(e,t),vu(this._transform,this._orientation)}forward(){const e=bs(this._transform,2);return[-e[0],-e[1],-e[2]]}up(){const e=bs(this._transform,1);return[-e[0],-e[1],-e[2]]}right(){const e=bs(this._transform,0);return[e[0],e[1],e[2]]}getCameraToWorld(e,t){const i=new Float64Array(16);return Tt(i,this.getWorldToCamera(e,t)),i}getCameraToWorldMercator(){return this._transform}getWorldToCameraPosition(e,t,i){const s=this.position;Ti(s,s,-e);const o=new Float64Array(16);return Ct(o,[i,i,i]),At(o,o,s),o[10]*=t,o}getWorldToCamera(e,t){const i=new Float64Array(16),s=new Float64Array(4),o=this.position;return vs(s,this._orientation),Ti(o,o,-e),ys(i,s),At(i,i,o),i[1]*=-1,i[5]*=-1,i[9]*=-1,i[13]*=-1,i[8]*=t,i[9]*=t,i[10]*=t,i[11]*=t,i}getCameraToClipPerspective(e,t,i,s){const o=new Float64Array(16);return xs(o,e,t,i,s),o}getCameraToClipOrthographic(e,t,i,s,o,r){const n=new Float64Array(16);return ki(n,e,t,i,s,o,r),n}getDistanceToElevation(e,t=!1){const i=0===e?0:ws(e,t?at(this.position[1]):this.position[1]),s=this.forward();return(i-this.position[2])/s[2]}clone(){return new wu([...this.position],[...this.orientation])}}const Tu=15;class Eu{constructor(e,t,i,s,o,r,n){this.tileSize=512,this._renderWorldCopies=void 0===o||o,this._minZoom=e||0,this._maxZoom=t||22,this._minPitch=i??0,this._maxPitch=s??60,this.setProjection(r),this.setMaxBounds(n),this.width=0,this.height=0,this._center=new Es(0,0),this.zoom=0,this.angle=0,this._fov=.6435011087932844,this._pitch=0,this._nearZ=0,this._farZ=0,this._nearClipOffset=0,this._unmodified=!0,this._edgeInsets=new gu,this._frustumCache=new Map,this._posMatrixCache=new Map,this._projMatrixCache=new Map,this._alignedProjMatrixCache=new Map,this._pixelsToTileUnitsCache=new Map,this._fogTileMatrixCache=new Map,this._expandedProjMatrixCache=new Map,this._distanceTileDataCache=new Map,this._camera=new wu,this._centerAltitude=0,this._averageElevation=0,this.cameraElevationReference="ground",this._pixelsPerMercatorPixel=1,this.globeRadius=0,this.globeCenterInViewSpace=[0,0,0],this._tileCoverLift=0,this.freezeTileCoverage=!1,this._horizonShift=.1,this._orthographicProjectionAtLowPitch=!1,this._allowWorldUnderZoom=!1,this.mercatorMatrix=new Float64Array(16),this.mercatorFogMatrix=new Float32Array(16),this.invProjMatrix=new Float64Array(16),this._cameraToClip=new Float64Array(16),this._worldToCamera=new Float64Array(16),this._expandedFarZProjMatrixBuf=new Float64Array(16),this.expandedFarZProjMatrix=this._expandedFarZProjMatrixBuf,this.starsProjMatrix=new Float32Array(16),this.skyboxMatrix=new Float32Array(16),this._mat4Scratch=new Float64Array(16),this.alignedProjMatrix=new Float64Array(16),this.labelPlaneMatrix=new Float32Array(16),this.glCoordMatrix=new Float32Array(16),this.pixelMatrix=new Float64Array(16),this.pixelMatrixInverse=new Float64Array(16)}clone(){const e=new Eu(this._minZoom,this._maxZoom,this._minPitch,this.maxPitch,this._renderWorldCopies,this.getProjection(),this.maxBounds);return e._elevation=this._elevation,e._centerAltitude=this._centerAltitude,e._centerAltitudeValidForExaggeration=this._centerAltitudeValidForExaggeration,e.tileSize=this.tileSize,e.mercatorFromTransition=this.mercatorFromTransition,e.width=this.width,e.height=this.height,e.cameraElevationReference=this.cameraElevationReference,e._center=this._center,e._setZoom(this.zoom),e._seaLevelZoom=this._seaLevelZoom,e.angle=this.angle,e._fov=this._fov,e._pitch=this._pitch,e._nearZ=this._nearZ,e._farZ=this._farZ,e._nearClipOffset=this._nearClipOffset,e._averageElevation=this._averageElevation,e._orthographicProjectionAtLowPitch=this._orthographicProjectionAtLowPitch,e._unmodified=this._unmodified,e._edgeInsets=this._edgeInsets.clone(),e._camera=this._camera.clone(),e._calcMatrices(),e.freezeTileCoverage=this.freezeTileCoverage,e.frustumCorners=this.frustumCorners,e._allowWorldUnderZoom=this._allowWorldUnderZoom,e}get isOrthographic(){return"globe"!==this.projection.name&&this._orthographicProjectionAtLowPitch&&this.pitch<Tu}get elevation(){return this._elevation}set elevation(e){this._elevation!==e&&(this._elevation=e,this._updateCameraOnTerrain(),this._calcMatrices())}get nearClipOffset(){return this._nearClipOffset}set nearClipOffset(e){this._nearClipOffset=e,this._calcMatrices()}get depthOcclusionForSymbolsAndCircles(){return"globe"!==this.projection.name&&!this.isOrthographic}updateElevation(e,t=!1){const i=this._elevation&&this._elevation.exaggeration()!==this._centerAltitudeValidForExaggeration;(null==this._seaLevelZoom||i)&&this._updateCameraOnTerrain(),(e||i)&&this._constrainCamera(t),this._calcMatrices()}getProjection(){return Me(this.projection,["name","center","parallels"])}setProjection(e){this.projectionOptions=e||{name:"mercator"};const t=this.projection?this.getProjection():void 0;this.projection=Is(this.projectionOptions);const i=this.getProjection(),s=!rs(t,i);return s&&this._calcMatrices(),this.mercatorFromTransition=!1,s}setOrthographicProjectionAtLowPitch(e){return this._orthographicProjectionAtLowPitch!==e&&(this._orthographicProjectionAtLowPitch=e,this._calcMatrices(),!0)}setMercatorFromTransition(){const e=this.projection.name;this.mercatorFromTransition=!0,this.projectionOptions={name:"mercator"},this.projection=Is({name:"mercator"});const t=e!==this.projection.name;return t&&this._calcMatrices(),t}get minZoom(){return this._minZoom}set minZoom(e){this._minZoom!==e&&(this._minZoom=e,this.zoom=Math.max(this.zoom,e))}get maxZoom(){return this._maxZoom}set maxZoom(e){this._maxZoom!==e&&(this._maxZoom=e,this.zoom=Math.min(this.zoom,e))}get minPitch(){return this._minPitch}set minPitch(e){this._minPitch!==e&&(this._minPitch=e,this.pitch=Math.max(this.pitch,e))}get maxPitch(){return this._maxPitch}set maxPitch(e){this._maxPitch!==e&&(this._maxPitch=e,this.pitch=Math.min(this.pitch,e))}get renderWorldCopies(){return this._renderWorldCopies&&!0===this.projection.supportsWorldCopies}set renderWorldCopies(e){void 0===e?e=!0:null===e&&(e=!1),this._renderWorldCopies=e}get worldSize(){return this.tileSize*this.scale}get cameraWorldSizeForFog(){const e=Math.max(this._camera.getDistanceToElevation(this._averageElevation),Number.EPSILON);return this._worldSizeFromZoom(this._zoomFromMercatorZ(e))}get cameraWorldSize(){const e=Math.max(this._camera.getDistanceToElevation(this._averageElevation,!0),Number.EPSILON);return this._worldSizeFromZoom(this._zoomFromMercatorZ(e))}get pixelsPerMeter(){return this.projection.pixelsPerMeter(this.center.lat,this.worldSize)}get cameraPixelsPerMeter(){return ws(1,this.center.lat)*this.cameraWorldSizeForFog}get centerOffset(){return this.centerPoint._sub(this.size._div(2))}get size(){return new m(this.width,this.height)}get bearing(){return si(this.rotation,-180,180)}set bearing(e){this.rotation=e}get rotation(){return-this.angle/Math.PI*180}set rotation(e){const t=-e*Math.PI/180;if(this.angle===t)return;this._unmodified=!1,this.angle=t,this._calcMatrices();const i=Math.sin(this.angle),s=Math.cos(this.angle);this.rotationMatrix=[s,i,-i,s]}get pitch(){return this._pitch/Math.PI*180}set pitch(e){const t=Ee(e,this.minPitch,this.maxPitch)/180*Math.PI;this._pitch!==t&&(this._unmodified=!1,this._pitch=t,this._calcMatrices())}get aspect(){return this.width/this.height}get fov(){return this._fov/Math.PI*180}set fov(e){e=Math.max(.01,Math.min(60,e)),this._fov!==e&&(this._unmodified=!1,this._fov=le(e),this._calcMatrices())}get fovX(){return this._fov}get fovY(){const e=1/Math.tan(.5*this.fovX);return 2*Math.atan(1/this.aspect/e)}get horizontalFov(){return Ss(2*Math.atan(Math.tan(.5*this._fov)*this.aspect))}get averageElevation(){return this._averageElevation}set averageElevation(e){this._averageElevation=e,this._calcFogMatrices(),this._distanceTileDataCache.clear()}get zoom(){return this._zoom}set zoom(e){const t=Math.min(Math.max(e,this.minZoom),this.maxZoom);this._zoom!==t&&(this._unmodified=!1,this._setZoom(t),this._updateSeaLevelZoom(),this._constrain(),this._calcMatrices())}_setZoom(e){this._zoom=e,this.scale=this.zoomScale(e),this.tileZoom=Math.floor(e),this.zoomFraction=e-this.tileZoom}get tileCoverLift(){return this._tileCoverLift}set tileCoverLift(e){this._tileCoverLift!==e&&(this._tileCoverLift=e)}_updateCameraOnTerrain(){const e=this.elevation?this.elevation.getAtPoint(this.locationCoordinate(this.center),Number.NEGATIVE_INFINITY):Number.NEGATIVE_INFINITY,t=this.elevation&&e===Number.NEGATIVE_INFINITY&&this.elevation.visibleDemTiles.length>0&&this.elevation.exaggeration()>0&&this._centerAltitudeValidForExaggeration;if(!this._elevation||e===Number.NEGATIVE_INFINITY&&(!t||!this._centerAltitude))return this._centerAltitude=0,this._seaLevelZoom=null,void(this._centerAltitudeValidForExaggeration=void 0);const i=this._elevation;t||this._centerAltitude&&this._centerAltitudeValidForExaggeration&&i.exaggeration()&&this._centerAltitudeValidForExaggeration!==i.exaggeration()?(this._centerAltitude=this._centerAltitude/this._centerAltitudeValidForExaggeration*i.exaggeration(),this._centerAltitudeValidForExaggeration=i.exaggeration()):(this._centerAltitude=e||0,this._centerAltitudeValidForExaggeration=i.exaggeration()),this._updateSeaLevelZoom()}_updateSeaLevelZoom(){if(void 0===this._centerAltitudeValidForExaggeration)return;const e=Math.max(0,(this.pixelsPerMeter*this._centerAltitude+this.cameraToCenterDistance)/this.worldSize);this._seaLevelZoom=this._zoomFromMercatorZ(e)}sampleAverageElevation(){if(!this._elevation)return 0;const e=this._elevation,t=[[.5,.2],[.3,.5],[.5,.5],[.7,.5],[.5,.8]],i=this.horizonLineFromTop();let s=0,o=0;for(let r=0;r<t.length;r++){const n=new m(t[r][0]*this.width,i+t[r][1]*(this.height-i)),a=e.pointCoordinate(n);if(!a)continue;const l=1/Math.hypot(a[0]-this._camera.position[0],a[1]-this._camera.position[1]);s+=a[3]*l,o+=l}return 0===o?NaN:s/o}get center(){return this._center}set center(e){e.lat===this._center.lat&&e.lng===this._center.lng||(this._unmodified=!1,this._center=e,this._terrainEnabled()&&("ground"===this.cameraElevationReference?this._updateCameraOnTerrain():this._updateZoomFromElevation()),this._constrain(),this._calcMatrices())}_updateZoomFromElevation(){if(null==this._seaLevelZoom||!this._elevation)return;const e=this._seaLevelZoom,t=this._elevation.getAtPointOrZero(this.locationCoordinate(this.center)),i=this.pixelsPerMeter/this.worldSize*t,s=this._mercatorZfromZoom(e),o=this._mercatorZfromZoom(this._maxZoom),r=Math.max(s-i,o);this._setZoom(this._zoomFromMercatorZ(r))}get padding(){return this._edgeInsets.toJSON()}set padding(e){this._edgeInsets.equals(e)||(this._unmodified=!1,this._edgeInsets.interpolate(this._edgeInsets,e,1),this._calcMatrices())}equals(e){const t=this.elevation,i=e.elevation,s=null!=t!=(null!=i)||t&&i&&t.exaggeration()!==i.exaggeration();return this.width===e.width&&this.height===e.height&&this.center.lng===e.center.lng&&this.center.lat===e.center.lat&&this.zoom===e.zoom&&this.bearing===e.bearing&&this.pitch===e.pitch&&this.fov===e.fov&&this.projection.name===e.projection.name&&this._edgeInsets.equals(e.padding)&&!s}computeZoomRelativeTo(e){const t=this.rayIntersectionCoordinate(this.pointRayIntersection(this.centerPoint,e.toAltitude()));let i;i=e.z<this._camera.position[2]?[t.x,t.y,t.z]:[e.x,e.y,e.z];const s=_s(ve([],this._camera.position,i));return Ee(this._zoomFromMercatorZ(s),this._minZoom,this._maxZoom)}setFreeCameraOptions(e){if(!this.height)return;if(!e.position&&!e.orientation)return;this._updateCameraState();let t=!1;if(e.orientation&&!Ds(e.orientation,this._camera.orientation)&&(t=this._setCameraOrientation(e.orientation)),e.position){const i=[e.position.x,e.position.y,e.position.z];Rs(i,this._camera.position)||(this._setCameraPosition(i),t=!0)}t&&(this._updateStateFromCamera(),this.recenterOnTerrain())}getFreeCameraOptions(){this._updateCameraState();const e=this._camera.position,t=new bu;return t.position=new we(e[0],e[1],e[2]),t.orientation=this._camera.orientation,t._elevation=this.elevation,t._renderWorldCopies=this.renderWorldCopies,t}_setCameraOrientation(e){if(!Cs(e))return!1;As(e,e);const t=Ls([],[0,0,-1],e),i=Ls([],[0,-1,0],e);if(i[2]<0)return!1;const s=xu(t,i);return!!s&&(this._camera.orientation=s,!0)}_setCameraPosition(e){const t=this.zoomScale(this.minZoom)*this.tileSize,i=this.zoomScale(this.maxZoom)*this.tileSize,s=this.cameraToCenterDistance;e[2]=Ee(e[2],s/i,s/t),this._camera.position=e}get centerPoint(){return this._edgeInsets.getCenter(this.width,this.height)}get fovAboveCenter(){return this._fov*(.5+this.centerOffset.y/this.height)}isPaddingEqual(e){return this._edgeInsets.equals(e)}interpolatePadding(e,t,i){this._unmodified=!1,this._edgeInsets.interpolate(e,t,i),this._constrain(),this._calcMatrices()}coveringZoomLevel(e){const t=(e.roundZoom?Math.round:Math.floor)(this.zoom+this.scaleZoom(this.tileSize/e.tileSize));return Math.max(0,t)}getVisibleUnwrappedCoordinates(e){const t=[new Ps(0,e)];if(this.renderWorldCopies){const i=this.pointCoordinate(new m(0,0)),s=this.pointCoordinate(new m(this.width,0)),o=this.pointCoordinate(new m(this.width,this.height)),r=this.pointCoordinate(new m(0,this.height)),n=Math.floor(Math.min(i.x,s.x,o.x,r.x)),a=Math.floor(Math.max(i.x,s.x,o.x,r.x)),l=1;for(let i=n-l;i<=a+l;i++)0!==i&&t.push(new Ps(i,e))}return t}isLODDisabled(e){return(!e||this.pitch<=60)&&this._edgeInsets.top<=this._edgeInsets.bottom&&!this._elevation&&!this.projection.isReprojectedInTileSpace}extendTileCover(e,t,i,s){let o=[];const r=null!=i,n=!r;if(n&&this.zoom<t)return o;if(r&&0===i[0]&&0===i[1])return o;const a=new Set,l=(e,t,i,s,r)=>{const n=Pt(t,e,i,s,r);a.has(n)||(o.push(new Ge(e,t,i,s,r)),a.add(n))};for(let o=0;o<e.length;o++){const a=e[o];if(n&&a.canonical.z!==t)continue;if(r&&void 0!==s&&s>a.canonical.z)continue;const c=a.canonical,h=a.overscaledZ,d=a.wrap,u=1<<c.z,_=c.x+1<u,p=c.x>0,f=c.y+1<u,m=c.y>0,g=a.wrap-(p?0:1),v=a.wrap+(_?0:1),y=p?c.x-1:u-1,x=_?c.x+1:0;if(r)i[0]<0?(l(h,v,c.z,x,c.y),i[1]<0&&f&&(l(h,d,c.z,c.x,c.y+1),l(h,v,c.z,x,c.y+1)),i[1]>0&&m&&(l(h,d,c.z,c.x,c.y-1),l(h,v,c.z,x,c.y-1))):i[0]>0?(l(h,g,c.z,y,c.y),i[1]<0&&f&&(l(h,d,c.z,c.x,c.y+1),l(h,g,c.z,y,c.y+1)),i[1]>0&&m&&(l(h,d,c.z,c.x,c.y-1),l(h,g,c.z,y,c.y-1))):i[1]<0&&f?l(h,d,c.z,c.x,c.y+1):m&&l(h,d,c.z,c.x,c.y-1);else{const e=a.visibleQuadrants;1&e&&(l(h,g,c.z,y,c.y),m&&(l(h,d,c.z,c.x,c.y-1),l(h,g,c.z,y,c.y-1))),2&e&&(l(h,v,c.z,x,c.y),m&&(l(h,d,c.z,c.x,c.y-1),l(h,v,c.z,x,c.y-1))),4&e&&(l(h,g,c.z,y,c.y),f&&(l(h,d,c.z,c.x,c.y+1),l(h,g,c.z,y,c.y+1))),8&e&&(l(h,v,c.z,x,c.y),f&&(l(h,d,c.z,c.x,c.y+1),l(h,v,c.z,x,c.y+1)))}}const c=[];for(const e of o)o.some(t=>e.isChildOf(t))||c.push(e);if(o=c.filter(i=>!e.some(e=>!!(i.overscaledZ<t&&e.isChildOf(i))||i.equals(e)||i.isChildOf(e))),n){const e=1<<t,i="globe"===this.projection.name?this._camera.mercatorPosition:this.pointCoordinate(this.getCameraPoint()),s=[e*i.x,e*i.y],r=4,n=r*r;o=o.filter(e=>{const t=e.canonical.x+.5-s[0],i=e.canonical.y+.5-s[1];return t*t+i*i<n})}return o}extendTileCoverToNearPlane(e,t,i){const s=[],o=new Set;for(const t of e)o.add(t.key);const r=(e,t,i,r,n)=>{const a=Pt(t,e,i,r,n);o.has(a)||(s.push(new Ge(e,t,i,r,n)),o.add(a))},n=e.reduce((e,t)=>Math.max(e,t.overscaledZ),i),a=1<<i,l=[new m(0,0),new m(ae,0),new m(ae,ae),new m(0,ae)],c=new m(0,0),h=new m(0,0),d=(e,t)=>{const s=Math.floor(e[0]),o=Math.floor(e[1]),d=(e[0]-s)*ae,u=(e[1]-o)*ae,_=Math.floor(t[0]),p=Math.floor(t[1]),f=(t[0]-_)*ae,m=(t[1]-p)*ae;for(let e=-1;e<=1;e++){const t=s+e;if(!(t<0||t>=a)){c.x=d-e*ae,h.x=f-(t-_)*ae;for(let e=-1;e<=1;e++){const s=o+e;c.y=u-e*ae,h.y=m-(s-p)*ae,oo(c,h,l)&&r(n,0,i,t,s)}}}},u=t.points,_=u[ro],p=u[no],f=this._projectToGround(_,u[Ms]),g=this._projectToGround(p,u[Os]);return d(_,f),d(p,g),s}_projectToGround(e,t){return zs(Fs(),e,t,e[2]/(e[2]-t[2]))}_projectToZ(e,t,i){const s=e[2]-t[2];return Math.abs(s)<1e-6?ks(e):zs(Fs(),e,t,(e[2]-i)/s)}extendTileCoverForTunnels(e,t,i,s){if(i<18)return[];const o=t.points,r=o[ao],n=o[lo],a=o[co],l=o[ho];if(a[2]>=0&&l[2]>=0||r[2]<=0||n[2]<=0)return[];const c=a[2]<0?this._projectToZ(r,a,0):a,h=l[2]<0?this._projectToZ(n,l,0):l,d=-s,u=a[2]<d?this._projectToZ(r,a,d):a,_=l[2]<d?this._projectToZ(n,l,d):l,p=this._findExtensionTilesInQuad(e,i,[_,u,h,c],[.5*(c[0]+h[0]),.5*(c[1]+h[1])]);return p.length>3&&(p.length=3),p}_findExtensionTilesInQuad(e,t,i,s){const o=[],r=new Set;for(const t of e)r.add(t.key);const n=e.reduce((e,t)=>Math.max(e,t.overscaledZ),t),a=1<<t,l=[new m(i[0][0],i[0][1]),new m(i[1][0],i[1][1]),new m(i[3][0],i[3][1]),new m(i[2][0],i[2][1]),new m(i[0][0],i[0][1])],c=i[0][0],h=i[1][0],d=i[2][0],u=i[3][0],_=i[0][1],p=i[1][1],f=i[2][1],g=i[3][1],v=Math.max(0,Math.floor(Math.min(c,h,d,u))),y=Math.min(a-1,Math.ceil(Math.max(c,h,d,u))-1),x=Math.max(0,Math.floor(Math.min(_,p,f,g))),b=Math.min(a-1,Math.ceil(Math.max(_,p,f,g))-1);for(let e=x;e<=b;e++)for(let i=v;i<=y;i++){if(!me(l,i,e,i+1,e+1))continue;const s=Pt(0,n,t,i,e);r.has(s)||(o.push(new Ge(n,0,t,i,e)),r.add(s))}const w=s[0],T=s[1];return o.sort((e,t)=>{const i=e.canonical.x+.5-w,s=e.canonical.y+.5-T,o=t.canonical.x+.5-w,r=t.canonical.y+.5-T;return i*i+s*s-(o*o+r*r)||e.canonical.x-t.canonical.x||e.canonical.y-t.canonical.y}),o}coveringTiles(e){let t=this.coveringZoomLevel(e);const i=t,s=this.elevation&&this.elevation.exaggeration(),o=s&&!e.isTerrainDEM,r="mercator"===this.projection.name;if(void 0!==e.minzoom&&t<e.minzoom)return[];void 0!==e.maxzoom&&t>e.maxzoom&&(t=e.maxzoom);const n=this.locationCoordinate(this.center),a=this.center.lat,l=1<<t,c=[l*n.x,l*n.y,0],h="globe"===this.projection.name,d=!h,u=this.getFrustum(t),_=h?this._camera.mercatorPosition:this.pointCoordinate(this.getCameraPoint()),p=l*ws(1,this.center.lat),f=this._camera.position[2]/ws(1,this.center.lat),m=[l*_.x,l*_.y,f*(d?1:p)],g=h||s,v=this._camera.forward(),y=this.cameraToCenterDistance/e.tileSize*(e.roundZoom?1:.502),x=this.isLODDisabled(!0)?t:0;let b;if(this._elevation&&e.isTerrainDEM)b=1e4*this._elevation.exaggeration();else if(this._elevation){const e=this._elevation.getMinMaxForVisibleTiles();b=e?e.max:this._centerAltitude}else b=this._centerAltitude;const w=e.isTerrainDEM?-b:this._elevation?this._elevation.getMinElevationBelowMSL():0,T=this.projection.isReprojectedInTileSpace?Bs(this):1,E=e=>{const t=1/4e4,i=new we(e.x+t,e.y,e.z),s=new we(e.x,e.y+t,e.z),o=e.toLngLat(),r=i.toLngLat(),n=s.toLngLat(),a=this.locationCoordinate(o),l=this.locationCoordinate(r),c=this.locationCoordinate(n),h=Math.hypot(l.x-a.x,l.y-a.y),d=Math.hypot(c.x-a.x,c.y-a.y);return Math.sqrt(h*d)*T/t},I=e=>{const t=b,i=w;return{aabb:Us(this,l,0,0,0,e,i,t,this.projection),zoom:0,x:0,y:0,minZ:i,maxZ:t,wrap:e,fullyVisible:!1}},S=[];let D=[];const R=t,C=e.reparseOverscaled?i:t,A=(f-this._centerAltitude)*p,L=e=>{if(!this._elevation||!e.tileID||!r)return;const t=this._elevation.getMinMaxForTile(e.tileID),i=e.aabb;t?(i.min[2]=t.min,i.max[2]=t.max,i.center[2]=(i.min[2]+i.max[2])/2):(e.shouldSplit=M(e),e.shouldSplit||(i.min[2]=i.max[2]=i.center[2]=this._centerAltitude))},P=(e,t)=>{if(.707*t<e)return 1;const i=t/e;return i/(1.4144271570014144+(Math.pow(1.1,i-1.4144271570014144+1)-1)/(1.1-1)-1)},M=e=>{if(e.zoom<x)return!0;if(e.zoom===R)return!1;if(null!=e.shouldSplit)return e.shouldSplit;const t=e.aabb.distanceX(m),s=e.aabb.distanceY(m);let n=A,l=1;if(h){n=e.aabb.distanceZ(m);const t=Math.pow(2,e.zoom),i=at((e.y+1)/t),s=at(e.y/t),o=Math.min(Math.max(a,i),s),r=mo(o)/mo(a);if(l=o===a?1/Math.max(1,this._mercatorScaleRatio-.3):Math.min(1,r/this._mercatorScaleRatio),this.zoom<=uo&&e.zoom===R-1&&r>=.9)return!0}else if(o&&(n=e.aabb.distanceZ(m)*p),this.projection.isReprojectedInTileSpace&&i<=5){const t=Math.pow(2,e.zoom),i=E(new we((e.x+.5)/t,(e.y+.5)/t));l=i>.85?1:i}if(!r&&!h){const i=Math.sqrt(t*t+s*s+n*n);let o=(1<<R-e.zoom)*y*l;return o*=P(Math.max(n,A),i),i<o}let d=Number.MAX_VALUE,u=0;const{min:_,max:f}=e.aabb;for(let e=0;e<8;e++){const t=3&e;let i=(e>=4?f[2]:_[2])-m[2];h||(i=o?i*p:A);const s=((1===t||2===t?f[0]:_[0])-m[0])*v[0]+((t>=2?f[1]:_[1])-m[1])*v[1]+i*v[2];s<d&&(d=s,u=Math.abs(i))}let g=(1<<R-e.zoom)*y*l;if(g*=P(Math.max(u,A),d),d<g)return!0;const b=e.aabb.closestPoint(c);return b[0]===c[0]&&b[1]===c[1]};if(this.renderWorldCopies)for(let e=1;e<=3;e++)S.push(I(-e)),S.push(I(e));for(S.push(I(0));S.length>0;){const i=S.pop(),s=i.x,n=i.y;let a=i.fullyVisible;const d=()=>"globe"===this.projection.name&&(0===i.y||i.y===(1<<i.zoom)-1);if(!a){let e=g?i.aabb.intersects(u):i.aabb.intersectsFlat(u);if(0===e&&d()){const t=new $e(i.zoom,s,n);e=Ns(this,l,t,!0).intersects(u)}if(0===e)continue;a=2===e}if(i.zoom===R||!M(i)){const o=i.zoom===R?C:i.zoom;if(e.minzoom&&e.minzoom>o)continue;let r=0;if(!a){let t=g?i.aabb.intersectsPrecise(u):i.aabb.intersectsPreciseFlat(u);if(0===t&&d()){const e=new $e(i.zoom,s,n);t=Ns(this,l,e,!0).intersectsPrecise(u)}if(0===t)continue;if(e.calculateQuadrantVisibility)if(u.containsPoint(i.aabb.center))r=15;else for(let e=0;e<4;e++)0!==i.aabb.quadrant(e).intersects(u)&&(r|=1<<e)}const h=c[0]-(.5+s+(i.wrap<<i.zoom))*(1<<t-i.zoom),_=c[1]-.5-n,p=i.tileID?i.tileID:new Ge(o,i.wrap,i.zoom,s,n);e.calculateQuadrantVisibility&&(p.visibleQuadrants=r),D.push({tileID:p,distanceSq:h*h+_*_});continue}for(let e=0;e<4;e++){const t=(s<<1)+e%2,c=(n<<1)+(e>>1),d={aabb:r?i.aabb.quadrant(e):Us(this,l,i.zoom+1,t,c,i.wrap,i.minZ,i.maxZ,this.projection),zoom:i.zoom+1,x:t,y:c,wrap:i.wrap,fullyVisible:a,tileID:void 0,shouldSplit:void 0,minZ:i.minZ,maxZ:i.maxZ};o&&!h&&(d.tileID=new Ge(i.zoom+1===R?C:i.zoom+1,i.wrap,i.zoom+1,t,c),L(d)),S.push(d)}}if(this.fogCullDistSq){const t=this.fogCullDistSq,i=this.horizonLineFromTop();D=D.filter(s=>{const o=[0,0,0,1],r=[ae,ae,0,1],n=this.calculateFogTileMatrix(s.tileID.toUnwrapped());Se(o,o,n),Se(r,r,n);const a=Vs([],o,r),l=js([],o,r),c=_o(a,l);if(0===c)return!0;let h=!1;const d=this._elevation;if(d&&c>t&&0!==i){const t=this.calculateProjMatrix(s.tileID.toUnwrapped());let o;e.isTerrainDEM||(o=d.getMinMaxForTile(s.tileID)),o||(o={min:w,max:b});const r=go(this.rotation),n=[r[0]*ae,r[1]*ae,o.max];It(n,n,t),h=(1-n[1])*this.height*.5<i}return c<t||h})}return D.sort((e,t)=>e.distanceSq-t.distanceSq).map(e=>e.tileID)}resize(e,t){this.width=e,this.height=t,this.pixelsToGLUnits=[2/e,-2/t],this._constrain(),this._calcMatrices()}get unmodified(){return this._unmodified}zoomScale(e){return Math.pow(2,e)}scaleZoom(e){return Math.log2(e)}project(e){const t=Ee(e.lat,-We,We),i=this.projection.project(e.lng,t);return new m(i.x*this.worldSize,i.y*this.worldSize)}unproject(e){return this.projection.unproject(e.x/this.worldSize,e.y/this.worldSize)}get point(){return this.project(this.center)}get pointMerc(){return this.point._div(this.worldSize)}get pixelsPerMeterRatio(){return this.pixelsPerMeter/ws(1,this.center.lat)/this.worldSize}setLocationAtPoint(e,t){let i,s;const o=this.centerPoint;if("globe"===this.projection.name){const e=this.worldSize;i=(t.x-o.x)/e,s=(t.y-o.y)/e}else{const e=this.pointCoordinate(t),r=this.pointCoordinate(o);i=e.x-r.x,s=e.y-r.y}const r=this.locationCoordinate(e);this.setLocation(new we(r.x-i,r.y-s))}setLocation(e){this.center=this.coordinateLocation(e),this.projection.wrap&&(this.center=this.center.wrap())}locationPoint(e,t){return this.projection.locationPoint(this,e,t)}locationPoint3D(e,t){return this.projection.locationPoint(this,e,t,!0)}pointLocation(e){return this.coordinateLocation(this.pointCoordinate(e))}pointLocation3D(e,t){return this.coordinateLocation(this.pointCoordinate3D(e,t))}locationCoordinate(e,t){const i=t?ws(t,e.lat):void 0,s=this.projection.project(e.lng,e.lat);return new we(s.x,s.y,i)}coordinateLocation(e){return this.projection.unproject(e.x,e.y)}pointRayIntersection(e,t){const i=t??this._centerAltitude,s=[e.x,e.y,0,1],o=[e.x,e.y,1,1];Se(s,s,this.pixelMatrixInverse),Se(o,o,this.pixelMatrixInverse);const r=o[3];Gs(s,s,1/s[3]),Gs(o,o,1/r);const n=s[2],a=o[2];return{p0:s,p1:o,t:n===a?0:(i-n)/(a-n)}}screenPointToMercatorRay(e){const t=[e.x,e.y,0,1],i=[e.x,e.y,1,1];return Se(t,t,this.pixelMatrixInverse),Se(i,i,this.pixelMatrixInverse),Gs(t,t,1/t[3]),Gs(i,i,1/i[3]),t[2]=ws(t[2],this._center.lat)*this.worldSize,i[2]=ws(i[2],this._center.lat)*this.worldSize,Gs(t,t,1/this.worldSize),Gs(i,i,1/this.worldSize),new xe([t[0],t[1],t[2]],ye([],ve([],i,t)))}rayIntersectionCoordinate(e){const{p0:t,p1:i,t:s}=e,o=ws(t[2],this._center.lat),r=ws(i[2],this._center.lat);return new we(J(t[0],i[0],s)/this.worldSize,J(t[1],i[1],s)/this.worldSize,J(o,r,s))}pointCoordinate(e,t=this._centerAltitude){return this.projection.pointCoordinate(this,e.x,e.y,t)}pointCoordinate3D(e,t){if(!this.elevation)return this.pointCoordinate(e,t);let i=this.projection.pointCoordinate3D(this,e.x,e.y);if(i)return new we(i[0],i[1],i[2]);let s=0,o=this.horizonLineFromTop();if(e.y>o)return this.pointCoordinate(e,t);const r=.02*o,n=e.clone();for(let e=0;e<10&&o-s>r;e++){n.y=J(s,o,.66);const e=this.projection.pointCoordinate3D(this,n.x,n.y);e?(o=n.y,i=e):s=n.y}return i?new we(i[0],i[1],i[2]):this.pointCoordinate(e)}isPointAboveHorizon(e){return this.projection.isPointAboveHorizon(this,e)}isPointOnSurface(e){if(e.y<0||e.y>this.height||e.x<0||e.x>this.width)return!1;if(this.elevation||this.zoom>=qs)return!this.isPointAboveHorizon(e);const t=this.pointCoordinate(e);return t.y>=0&&t.y<=1}_coordinatePoint(e,t){const i=t&&this.elevation?this.elevation.getAtPointOrZero(e,this._centerAltitude):this._centerAltitude,s=[e.x*this.worldSize,e.y*this.worldSize,i+e.toAltitude(),1];return Se(s,s,this.pixelMatrix),s[3]>0?new m(s[0]/s[3],s[1]/s[3]):new m(Number.MAX_VALUE,Number.MAX_VALUE)}_getBoundsNonRectangular(){const{top:e,left:t}=this._edgeInsets,i=this.height-this._edgeInsets.bottom,s=this.width-this._edgeInsets.right,o=this.pointLocation3D(new m(t,e)),r=this.pointLocation3D(new m(s,e)),n=this.pointLocation3D(new m(s,i)),a=this.pointLocation3D(new m(t,i));let l=Math.min(o.lng,r.lng,n.lng,a.lng),c=Math.max(o.lng,r.lng,n.lng,a.lng),h=Math.min(o.lat,r.lat,n.lat,a.lat),d=Math.max(o.lat,r.lat,n.lat,a.lat);const u=Math.pow(2,-this.zoom)/16*270,_="globe"===this.projection.name?1:4,p=(e,t,i,s,o)=>{const r=(e+i)/2,n=(t+s)/2,a=new m(r,n),{lng:f,lat:g}=this.pointLocation3D(a),v=Math.max(0,l-f,h-g,f-c,g-d);l=Math.min(l,f),c=Math.max(c,f),h=Math.min(h,g),d=Math.max(d,g),(o<_||v>u)&&(p(e,t,r,n,o+1),p(r,n,i,s,o+1))};if(p(t,e,s,e,1),p(s,e,s,i,1),p(s,i,t,i,1),p(t,i,t,e,1),"globe"===this.projection.name){const[e,t]=Zs(this);e?(d=90,c=180,l=-180):t&&(h=-90,c=180,l=-180)}return new Le(new Es(l,h),new Es(c,d))}_getBoundsRectangular(e,t){const{top:i,left:s}=this._edgeInsets,o=this.height-this._edgeInsets.bottom,r=this.width-this._edgeInsets.right,n=new m(s,i),a=new m(r,i),l=new m(r,o),c=new m(s,o);let h=this.pointCoordinate(n,e),d=this.pointCoordinate(a,e);const u=this.pointCoordinate(l,t),_=this.pointCoordinate(c,t),p=(e,t)=>(t.y-e.y)/(t.x-e.x);return h.y>1&&d.y>=0?h=new we((1-_.y)/p(_,h)+_.x,1):h.y<0&&d.y<=1&&(h=new we(-_.y/p(_,h)+_.x,0)),d.y>1&&h.y>=0?d=new we((1-u.y)/p(u,d)+u.x,1):d.y<0&&h.y<=1&&(d=new we(-u.y/p(u,d)+u.x,0)),(new Le).extend(this.coordinateLocation(h)).extend(this.coordinateLocation(d)).extend(this.coordinateLocation(_)).extend(this.coordinateLocation(u))}_getBoundsRectangularTerrain(){const e=this.elevation;if(!e.visibleDemTiles.length||e.isUsingMockSource())return this._getBoundsRectangular(0,0);const t=e.visibleDemTiles.reduce((e,t)=>{if(t.dem){const i=t.dem.tree;e.min=Math.min(e.min,i.minimums[0]),e.max=Math.max(e.max,i.maximums[0])}return e},{min:Number.MAX_VALUE,max:0});return this._getBoundsRectangular(t.min*e.exaggeration(),t.max*e.exaggeration())}getBounds(){return"mercator"===this.projection.name||"equirectangular"===this.projection.name?this._terrainEnabled()?this._getBoundsRectangularTerrain():this._getBoundsRectangular(0,0):this._getBoundsNonRectangular()}horizonLineFromTop(e=!0){const t=this.height/2/Math.tan(this._fov/2)/Math.tan(Math.max(this._pitch,.1))-this.centerOffset.y,i=this.height/2-t*(1-this._horizonShift);return e?Math.max(0,i):i}getMaxBounds(){return this.maxBounds}setMaxBounds(e){this.maxBounds=e,this.minLat=-We,this.maxLat=We,this.minLng=-180,this.maxLng=180,e&&(this.minLat=e.getSouth(),this.maxLat=e.getNorth(),this.minLng=e.getWest(),this.maxLng=e.getEast(),this.maxLng<this.minLng&&(this.maxLng+=360)),this.worldMinX=Ae(this.minLng)*this.tileSize,this.worldMaxX=Ae(this.maxLng)*this.tileSize,this.worldMinY=Pe(this.maxLat)*this.tileSize,this.worldMaxY=Pe(this.minLat)*this.tileSize,this._constrain()}calculatePosMatrix(e){let t=this._posMatrixCache.get(e.key);return t||(t=this.projection.createTileMatrix(this,this.worldSize,e),this._posMatrixCache.set(e.key,t)),t}calculateDistanceTileData(e){const t=this._distanceTileDataCache.get(e.key);if(t)return t;const i=e.canonical,s=1/this.height,o=this.cameraWorldSize,r=o/this.zoomScale(i.z),n=(i.x+Math.pow(2,i.z)*e.wrap)*r,a=i.y*r,l=this.point;l.x*=o/this.worldSize,l.y*=o/this.worldSize;const c=this.angle,h={bearing:[Math.sin(-c),-Math.cos(-c)],center:[(l.x-n)*s,(l.y-a)*s],scale:r/ae*s};return this._distanceTileDataCache.set(e.key,h),h}calculateFogTileMatrix(e){const t=this._fogTileMatrixCache.get(e.key);if(t)return t;const i=this.projection.createTileMatrix(this,this.cameraWorldSizeForFog,e);Ie(i,this.worldToFogMatrix,i);const s=new Float32Array(i);return this._fogTileMatrixCache.set(e.key,s),s}calculateProjMatrix(e,t=!1,i=!1){const s=i?this._expandedProjMatrixCache:t?this._alignedProjMatrixCache:this._projMatrixCache,o=s.get(e.key);if(o)return o;let r;r=this.projection.isReprojectedInTileSpace?this.mercatorMatrix:i?this.expandedFarZProjMatrix:t?this.alignedProjMatrix:this.projMatrix;const n=Ie(new Float32Array(16),r,this.calculatePosMatrix(e));return s.set(e.key,n),n}calculatePixelsToTileUnitsMatrix(e){const t=this._pixelsToTileUnitsCache.get(e.tileID.key);if(t)return t;const i=po(e,this);return this._pixelsToTileUnitsCache.set(e.tileID.key,i),i}customLayerMatrix(){return this.mercatorMatrix.slice()}globeToMercatorMatrix(){if("globe"===this.projection.name){const e=1/this.worldSize,t=Ct([],[e,e,e]);return Ie(t,t,this.globeMatrix),t}}recenterOnTerrain(){if(!this._elevation||"globe"===this.projection.name)return;const e=this._elevation;this._updateCameraState();const t=ws(1,this._center.lat)*this.worldSize,i=this._computeCameraPosition(t),s=this._camera.forward(),o=ws(1,this._center.lat);i[2]/=o,s[2]/=o,ye(s,s);const r=e.raycast(i,s,e.exaggeration());if(r){const e=Wt([],i,s,r),t=new we(e[0],e[1],ws(e[2],at(e[1]))),n=(t.z+_s([t.x-i[0],t.y-i[1],t.z-i[2]*o]))*this._pixelsPerMercatorPixel;this._seaLevelZoom=this._zoomFromMercatorZ(n),this._centerAltitude=t.toAltitude(),this._center=this.coordinateLocation(t),this._updateZoomFromElevation(),this._constrain(),this._calcMatrices()}}_constrainCamera(e=!1){if(!this._elevation)return;const t=this._elevation,i=ws(1,this._center.lat)*this.worldSize,s=this._computeCameraPosition(i),o=t.getAtPointOrZero(new we(...s)),r=this.pixelsPerMeter/this.worldSize*o,n=this._minimumHeightOverTerrain(),a=s[2]-r;if(a<=n)if(a<0||e){const e=this.locationCoordinate(this._center,this._centerAltitude),t=[s[0],s[1],e.z-s[2]],i=_s(t);t[2]-=(n-a)/this._pixelsPerMercatorPixel;const o=_s(t);if(0===o)return;Ti(t,t,i/o*this._pixelsPerMercatorPixel),this._camera.position=[s[0],s[1],e.z*this._pixelsPerMercatorPixel-t[2]],this._updateStateFromCamera()}else this._isCameraConstrained=!0}_constrain(){if(!this.center||!this.width||!this.height||this._constraining)return;this._constraining=!0;const e="globe"===this.projection.name||this.mercatorFromTransition;if(this.projection.isReprojectedInTileSpace||e){const t=this.center;return t.lat=Ee(t.lat,this.minLat,this.maxLat),(this.maxBounds||!this.renderWorldCopies&&!e)&&(t.lng=Ee(t.lng,this.minLng,this.maxLng)),this.center=t,void(this._constraining=!1)}const t=this._unmodified,{x:i,y:s}=this.point;let o=0,r=i,n=s;const a=this.width/2,l=this.height/2,c=this.worldMinY*this.scale,h=this.worldMaxY*this.scale;if(s-l<c&&(n=c+l),s+l>h&&(n=h-l),h-c<this.height&&(o=Math.max(o,this.height/(h-c)),n=(h+c)/2),this.maxBounds||!this._renderWorldCopies||!this.projection.wrap){const e=this.worldMinX*this.scale,t=this.worldMaxX*this.scale,s=this.worldSize/2-(e+t)/2;r=(i+s+this.worldSize)%this.worldSize-s,r-a<e&&(r=e+a),r+a>t&&(r=t-a),t-e<this.width&&(o=Math.max(o,this.width/(t-e)),r=(t+e)/2)}r===i&&n===s||this._allowWorldUnderZoom||(this.center=this.unproject(new m(r,n))),o&&!this._allowWorldUnderZoom&&(this.zoom+=this.scaleZoom(o)),this._constrainCamera(),this._unmodified=t,this._constraining=!1}_minZoomForBounds(){let e=Math.max(0,this.scaleZoom(Math.max(0,this.height)/(this.worldMaxY-this.worldMinY)));return this.maxBounds&&(e=Math.max(e,this.scaleZoom(this.width/(this.worldMaxX-this.worldMinX)))),e}_maxCameraBoundsDistance(){return this._mercatorZfromZoom(this._minZoomForBounds())}_calcMatrices(){if(!this.height)return;const e=this.centerOffset,t="globe"===this.projection.name,i=this.pixelsPerMeter;"globe"===this.projection.name&&(this._mercatorScaleRatio=ws(1,this.center.lat)/ws(1,vo));const s=Ws(this.projection,this.zoom,this.width,this.height,1024);this._pixelsPerMercatorPixel=this.projection.pixelSpaceConversion(this.center.lat,this.worldSize,s),this.cameraToCenterDistance=.5/Math.tan(.5*this._fov)*this.height*this._pixelsPerMercatorPixel,this._updateCameraState(),this._farZ=this.projection.farthestPixelDistance(this),this._nearZ=this.height/50;const o="meters"===this.projection.zAxisUnit?i:1,r=this._camera.getWorldToCamera(this.worldSize,o);let n;const a=this._camera.getCameraToClipPerspective(this._fov,this.width/this.height,this._nearZ,this._farZ);if(a[8]=2*-e.x/this.width,a[9]=2*e.y/this.height,this.isOrthographic){let t=.5*this.height/Math.tan(this._fov/2)*1*Math.tan(.5*this._fov),i=t*this.aspect,s=-i,o=-t;i-=e.x,s-=e.x,t+=e.y,o+=e.y,n=this._camera.getCameraToClipOrthographic(s,i,o,t,this._nearZ+this._nearClipOffset,this._farZ),((e,t,i,s)=>{for(let o=0;o<16;o++)e[o]=J(t[o],i[o],s)})(n,n,a,fo(this.pitch>=Tu?1:this.pitch/Tu))}else n=a;this._cameraToClip=n;const l=Hs(new Float64Array(16),a,r),c=Hs(new Float64Array(16),n,r);if(this.projection.isReprojectedInTileSpace){const e=this.locationCoordinate(this.center);ci(this._mat4Scratch);const t=this._mat4Scratch;At(t,t,[e.x*this.worldSize,e.y*this.worldSize,0]),Ie(t,t,$s(this)),At(t,t,[-e.x*this.worldSize,-e.y*this.worldSize,0]),Ie(c,c,t),Ie(l,l,t),this.inverseAdjustmentMatrix=Xs(this)}else this.inverseAdjustmentMatrix=[1,0,0,1];if(Ys(this.mercatorMatrix,c,[this.worldSize,this.worldSize,this.worldSize/o,1]),this.projMatrix=c,Tt(this.invProjMatrix,this.projMatrix),this._frustumCache.clear(),t){const t=this._camera.getCameraToClipPerspective(this._fov,this.width/this.height,this._nearZ,1/0);t[8]=2*-e.x/this.width,t[9]=2*e.y/this.height,Hs(this._expandedFarZProjMatrixBuf,t,r),this.expandedFarZProjMatrix=this._expandedFarZProjMatrixBuf}else this.expandedFarZProjMatrix=this.projMatrix;Tt(this._mat4Scratch,n),this.frustumCorners=Ks.fromInvProjectionMatrix(this._mat4Scratch,this.horizonLineFromTop(),this.height),Ct(this.skyboxMatrix,[1,-1,1]),Js(this.skyboxMatrix,this.skyboxMatrix,this._pitch),kt(this.skyboxMatrix,this.skyboxMatrix,this.angle),xs(this.starsProjMatrix,this._fov,this.width/this.height,this._nearZ,this._farZ);const h=(Math.PI/2-this._pitch)*(this.height/this._fov)*this._horizonShift;Qs(this._mat4Scratch,this.starsProjMatrix),this._mat4Scratch[8]=2*-e.x/this.width,this._mat4Scratch[9]=2*(e.y+h)/this.height,Ie(this.skyboxMatrix,this._mat4Scratch,this.skyboxMatrix);const d=this.point,u=d.x,_=d.y,p=this.width%2/2,f=this.height%2/2,m=Math.cos(this.angle),g=Math.sin(this.angle),v=u-Math.round(u)+m*p+g*f,y=_-Math.round(_)+m*f+g*p;if(Qs(this.alignedProjMatrix,c),At(this.alignedProjMatrix,this.alignedProjMatrix,[v>.5?v-1:v,y>.5?y-1:y,0]),Ct(this.labelPlaneMatrix,[this.width/2,-this.height/2,1]),At(this.labelPlaneMatrix,this.labelPlaneMatrix,[1,-1,0]),Ct(this.glCoordMatrix,[1,-1,1]),At(this.glCoordMatrix,this.glCoordMatrix,[-1,-1,0]),Ys(this.glCoordMatrix,this.glCoordMatrix,[2/this.width,2/this.height,1]),Ie(this.pixelMatrix,this.labelPlaneMatrix,l),this._calcFogMatrices(),this._distanceTileDataCache.clear(),!Tt(this.pixelMatrixInverse,this.pixelMatrix))throw new Error("failed to invert matrix");if("globe"===this.projection.name||this.mercatorFromTransition){this.globeMatrix=eo(this);const e=[this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]];this.globeCenterInViewSpace=It(e,e,r),this.globeRadius=this.worldSize/2/Math.PI-1}else this.globeMatrix=this.pixelMatrixInverse;this._worldToCamera="globe"===this.projection.name?Ie(new Float64Array(16),r,this.globeMatrix):r,this._posMatrixCache.clear(),this._projMatrixCache.clear(),this._alignedProjMatrixCache.clear(),this._pixelsToTileUnitsCache.clear(),this._expandedProjMatrixCache.clear()}_calcFogMatrices(){this._fogTileMatrixCache.clear();const e=this.cameraWorldSizeForFog,t=this.cameraPixelsPerMeter,i=this._camera.position,s=1/this.height/this._pixelsPerMercatorPixel,o=[e,e,t];Ti(o,o,s),Ti(i,i,-1),to(i,i,o),io(this.mercatorFogMatrix,i),Ys(this.mercatorFogMatrix,this.mercatorFogMatrix,o),this.worldToFogMatrix=this._camera.getWorldToCameraPosition(e,t,s)}_computeCameraPosition(e){const t=(e=e||this.pixelsPerMeter)/this.pixelsPerMeter,i=this._camera.forward(),s=this.point,o=this._mercatorZfromZoom(this._seaLevelZoom?this._seaLevelZoom:this._zoom)*t-e/this.worldSize*this._centerAltitude;return[s.x/this.worldSize-i[0]*o,s.y/this.worldSize-i[1]*o,e/this.worldSize*this._centerAltitude-i[2]*o]}_updateCameraState(){this.height&&(this._camera.setPitchBearing(this._pitch,this.angle),this._camera.position=this._computeCameraPosition())}_translateCameraConstrained(e){const t=this._maxCameraBoundsDistance()*Math.cos(this._pitch),i=this._camera.position[2],s=e[2];let o=1;this.projection.wrap&&(this.center=this.center.wrap()),s>0&&(o=Math.min((t-i)/s,1)),this._camera.position=Wt([],this._camera.position,e,o),this._updateStateFromCamera()}_updateStateFromCamera(){const e=this._camera.position,t=this._camera.forward(),{pitch:i,bearing:s}=this._camera.getPitchBearing(),o=ws(this._centerAltitude,this.center.lat)*this._pixelsPerMercatorPixel,r=this._mercatorZfromZoom(this._maxZoom)*Math.cos(le(this._maxPitch)),n=Math.max((e[2]-o)/Math.cos(i),r),a=this._zoomFromMercatorZ(n);Wt(e,e,t,n),this._pitch=Ee(i,le(this.minPitch),le(this.maxPitch)),this.angle=si(s,-Math.PI,Math.PI),this._setZoom(Ee(a,this._minZoom,this._maxZoom)),this._updateSeaLevelZoom(),this._center=this.coordinateLocation(new we(e[0],e[1],e[2])),this._unmodified=!1,this._constrain(),this._calcMatrices()}_worldSizeFromZoom(e){return Math.pow(2,e)*this.tileSize}_mercatorZfromZoom(e){return this.cameraToCenterDistance/this._worldSizeFromZoom(e)}_minimumHeightOverTerrain(){const e=Math.min(this._seaLevelZoom??this._zoom,this._maxZoom)+4;return this._mercatorZfromZoom(e)}_zoomFromMercatorZ(e){return this.scaleZoom(this.cameraToCenterDistance/(Math.max(0,e)*this.tileSize))}zoomFromMercatorZAdjusted(e){let t=0,i=qs,s=0,o=1/0;for(;i-t>1e-6&&i>t;){const r=t+.5*(i-t),n=this.tileSize*Math.pow(2,r),a=this.getCameraToCenterDistance(this.projection,r,n),l=this.scaleZoom(a/(Math.max(0,e)*this.tileSize)),c=Math.abs(r-l);c<o&&(o=c,s=r),r<l?t=r:i=r}return s}_terrainEnabled(){return!(!this._elevation||!this.projection.supportsTerrain&&(_("Terrain is not yet supported with alternate projections. Use mercator or globe to enable terrain."),1))}anyCornerOffEdge(e,t){const i=Math.min(e.x,t.x),s=Math.max(e.x,t.x),o=Math.min(e.y,t.y),r=Math.max(e.y,t.y);if(o<this.horizonLineFromTop(!1))return!0;if("mercator"!==this.projection.name)return!1;const n=[new m(i,o),new m(s,r),new m(i,r),new m(s,o)],a=this.renderWorldCopies?-3:0,l=this.renderWorldCopies?4:1;for(const e of n){const t=this.pointRayIntersection(e);if(t.t<0)return!0;const i=this.rayIntersectionCoordinate(t);if(i.x<a||i.y<0||i.x>l||i.y>1)return!0}return!1}isHorizonVisible(){return this.pitch+Ss(this.fovAboveCenter)>88||this.anyCornerOffEdge(new m(0,0),new m(this.width,this.height))}zoomDeltaToMovement(e,t){const i=_s(ve([],this._camera.position,e)),s=this._zoomFromMercatorZ(i)+t;return i-this._mercatorZfromZoom(s)}getCameraPoint(){if("globe"===this.projection.name){const e=function([e,t,i],s){const o=[e,t,i,1];Se(o,o,s);const r=o[3]=Math.max(o[3],1e-6);return o[0]/=r,o[1]/=r,o[2]/=r,o}([this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]],this.pixelMatrix);return new m(e[0],e[1])}{const e=Math.tan(this._pitch)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new m(0,e))}}getCameraToCenterDistance(e,t=this.zoom,i=this.worldSize){const s=Ws(e,t,this.width,this.height,1024),o=e.pixelSpaceConversion(this.center.lat,i,s);let r=.5/Math.tan(.5*this._fov)*this.height*o;return this.isOrthographic&&(r=J(1,r,fo(this.pitch>=Tu?1:this.pitch/Tu))),r}getWorldToCameraMatrix(){return this._worldToCamera}getCameraToClipMatrix(){return this._cameraToClip}getFrustum(e){let t=this._frustumCache.get(e);return t||(t=so.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,e,"meters"===this.projection.zAxisUnit),this._frustumCache.set(e,t)),t}get cameraFrustum(){return this.getFrustum(0)}}const Iu=(e,t)=>{if(t<=0||e.terrain)return{shouldRenderCutoff:!1,uniformValues:{u_cutoff_params:[0,0,0,1]}};const i=e.transform,s=i.pitch,o=i.isLODDisabled(!1)?60:30;if(s<o-15)return{shouldRenderCutoff:!1,uniformValues:{u_cutoff_params:[0,0,0,1]}};const r=i._farZ-i._nearZ,n=t*i.height*1.3,a=Math.pow(2,.85*Math.max(i._zoom-e.minCutoffZoom,0)),l=1.4*i.cameraToCenterDistance*a,c=Q(o-15,o,s),h=J(i._farZ+n,l,c),d=Math.min(n,h-i._nearZ);return{shouldRenderCutoff:c>0,uniformValues:{u_cutoff_params:[i._nearZ,i._farZ,(h-i._nearZ)/r,(h-d-i._nearZ)/r]}}};function Su(e,t,i){const s=function(e,t,i){const s=Kt(t,e),o=Kt(i,[.2126,.7152,.0722]),r=1-.3*Math.min(o,1),n=J(r,1,Math.min(s+1,1));return J(.92,1,Math.asin(Ee(t[2],-1,1))/Math.PI+.5)*n}(e,[0,0,1],t),o=[0,0,0];Ti(o,i.slice(0,3),s);const r=[0,0,0];Ti(r,t.slice(0,3),e[2]);const n=[0,0,0];return yo(n,o,r),Ei(n)}const Du=(e,t,i,s)=>{const o=e.properties.get("direction"),r="none"===e.properties.get("color-use-theme"),n=e.properties.get("color").toNonPremultipliedRenderColor(r?null:i.getLut(e.scope)).toArray01();let a=e.properties.get("intensity");const l="none"===t.properties.get("color-use-theme"),c=t.properties.get("color").toNonPremultipliedRenderColor(l?null:i.getLut(t.scope)).toArray01();let h=t.properties.get("intensity");const d=[o.x,o.y,o.z];s&&(void 0!==s.ambientIntensity&&(h=s.ambientIntensity),void 0!==s.directionalIntensity&&(a=s.directionalIntensity),void 0!==s.ambientColor&&(c[0]=s.ambientColor[0],c[1]=s.ambientColor[1],c[2]=s.ambientColor[2]),void 0!==s.directionalColor&&(n[0]=s.directionalColor[0],n[1]=s.directionalColor[1],n[2]=s.directionalColor[2]));const u=xo(c,h),_=xo(n,a);return{u_lighting_ambient_color:u,u_lighting_directional_dir:d,u_lighting_directional_color:_,u_ground_radiance:Su(d,_,u)}};function Ru(){return{u_light_matrix_0:new Float32Array(16),u_light_matrix_1:new Float32Array(16),u_shadow_intensity:0,u_fade_range:[0,0],u_shadow_normal_offset:[1,1,1],u_shadow_texel_size:1,u_shadow_map_resolution:1,u_shadow_direction:[0,0,1],u_shadow_bias:[36e-5,.0012,.012],u_shadowmap_0:0,u_shadowmap_1:0}}class Cu{constructor(e,t,i){this.func=e,this.mask=t,this.range=i}}Cu.ReadOnly=!1,Cu.ReadWrite=!0,Cu.disabled=new Cu(519,Cu.ReadOnly,[0,1]);const Au=7680,Lu=128;class Pu{constructor(e,t,i,s,o,r){this.test=e,this.ref=t,this.mask=i,this.fail=s,this.depthFail=o,this.pass=r}}Pu.disabled=new Pu({func:519,mask:0},0,0,Au,Au,Au);const Mu=770,Ou=771;class zu{constructor(e,t,i,s){this.blendFunction=e,this.blendColor=t.toNonPremultipliedRenderColor(null),this.mask=i,this.blendEquation=s}}zu.Replace=[1,0,1,0],zu.disabled=new zu(zu.Replace,S.transparent,[!1,!1,!1,!1]),zu.unblended=new zu(zu.Replace,S.transparent,[!0,!0,!0,!0]),zu.alphaBlended=new zu([1,Ou,1,Ou],S.transparent,[!0,!0,!0,!0]),zu.alphaBlendedNonPremultiplied=new zu([Mu,Ou,Mu,Ou],S.transparent,[!0,!0,!0,!0]),zu.multiply=new zu([774,0,774,0],S.transparent,[!0,!0,!0,!0]),zu.multiplyAccumulateAlpha=new zu([774,0,1,Ou],S.transparent,[!0,!0,!0,!0]),zu.additive=new zu([1,1,1,1],S.transparent,[!0,!0,!0,!0]),zu.additiveAlphaWeighted=new zu([Mu,1,773,1],S.transparent,[!0,!0,!0,!0]),zu.additiveAlphaWeightedUnboundedAlpha=new zu([Mu,1,1,1],S.transparent,[!0,!0,!0,!0]);const Fu=["fill","fillOutline","fillPattern","line","linePattern","background","backgroundPattern","hillshade","raster"],ku=["stars","rainParticle","snowParticle","fillExtrusion","fillExtrusionGroundEffect","building","buildingBloom","elevatedStructures","model","symbol"];function Bu(e,t,i){for(const s of i)(s.includes(" ")||t.usedDefines.has(s))&&(e+=`/${s}`);return e}let Nu=class{static cacheKey(e,t,i,s,o){let r=t;return o&&(r+=`/${o.cacheKey}`),r=Bu(r,e,i),s?Bu(r,e,s):r}constructor(e,t,i,s,o,r,n=!1){const a=e.gl;this.program=a.createProgram(),this._context=e,this._fixedUniformsFn=o,this._pending=!0,this._precompiled=n,this.attributes={},this.configuration=s,this.name=t,this.fixedDefines=[...r],n?e._compileStats.precompiled++:e._compileStats.onDemand++;const l=`#version 300 es\n${(s?s.defines():[]).concat(r.map(e=>`#define ${e}`)).join("\n")}`,c=[l,cu];for(const e of i.fragmentIncludes)c.push(su[e]);c.push(i.fragmentSource);const h=c.join("\n"),d=[l,hu];for(const e of i.vertexIncludes)d.push(su[e]);this.forceManualRenderingForInstanceIDShaders=e.forceManualRenderingForInstanceIDShaders&&i.vertexSource.includes("gl_InstanceID"),this.forceManualRenderingForInstanceIDShaders&&d.push("uniform int u_instanceID;"),d.push(i.vertexSource);let u=d.join("\n");this.forceManualRenderingForInstanceIDShaders&&(u=u.replaceAll("gl_InstanceID","u_instanceID"));const _=a.createShader(a.FRAGMENT_SHADER);if(a.isContextLost())return this.failedToCreate=!0,void(this._pending=!1);a.shaderSource(_,h),a.compileShader(_),a.attachShader(this.program,_);const p=a.createShader(a.VERTEX_SHADER);if(a.isContextLost())return this.failedToCreate=!0,void(this._pending=!1);a.shaderSource(p,u),a.compileShader(p),a.attachShader(this.program,p),a.linkProgram(this.program),this._fragmentShader=_,this._vertexShader=p,e.extParallelShaderCompile?e._pendingPrograms.add(this):this._finalize()}_finalize(){if(!this._pending)return;this._pending=!1;const e=this._context,t=e.gl;e._pendingPrograms.delete(this);const i=T.now(),s=t.getProgramParameter(this.program,t.LINK_STATUS),o=T.now()-i,r=e._compileStats;if(r.totalStallMs+=o,o>r.maxStallMs&&(r.maxStallMs=o),o>1){r.framesMissed+=Math.floor(60*o/1e3);const e=this.fixedDefines.join(",");r.stalls.push({name:`${this.name}${e?"/":""}${e}`,ms:o,timestamp:i})}if(this._fragmentShader&&(s||_(`Fragment shader '${this.name}': ${t.getShaderInfoLog(this._fragmentShader)}`),t.deleteShader(this._fragmentShader),this._fragmentShader=null),this._vertexShader&&(s||_(`Vertex shader '${this.name}': ${t.getShaderInfoLog(this._vertexShader)}`),t.deleteShader(this._vertexShader),this._vertexShader=null),!s)return _(`Failed to link program '${this.name}': ${t.getProgramInfoLog(this.program)}`),void(this.failedToCreate=!0);this.fixedUniforms=this._fixedUniformsFn(e),this.activeUniforms=Object.entries(this.fixedUniforms).filter(([e,t])=>t.fetchUniformLocation(this.program,e)),this.binderUniforms=this.configuration?this.configuration.getUniforms(e):[],this.forceManualRenderingForInstanceIDShaders&&(this.instancingUniforms=(e=>({u_instanceID:new Ai(e)}))(e));const n=this.fixedDefines,a=this.name;(n.includes("TERRAIN")||n.includes("ELEVATED")||a.includes("symbol")||a.includes("circle"))&&(this.terrainUniforms=(e=>({u_dem:new Ai(e),u_dem_prev:new Ai(e),u_dem_tl:new Ci(e),u_dem_scale:new Ri(e),u_dem_tl_prev:new Ci(e),u_dem_scale_prev:new Ri(e),u_dem_size:new Ri(e),u_dem_lerp:new Ri(e),u_exaggeration:new Ri(e),u_depth:new Ai(e),u_depth_size_inv:new Ci(e),u_depth_range_unpack:new Ci(e),u_occluder_half_size:new Ri(e),u_occlusion_depth_offset:new Ri(e),u_meter_to_dem:new Ri(e),u_label_plane_matrix_inv:new Pi(e)}))(e)),n.includes("GLOBE")&&(this.globeUniforms=(e=>({u_tile_tl_up:new Li(e),u_tile_tr_up:new Li(e),u_tile_br_up:new Li(e),u_tile_bl_up:new Li(e),u_tile_up_scale:new Ri(e)}))(e)),n.includes("FOG")&&(this.fogUniforms=(e=>({u_fog_matrix:new Pi(e),u_fog_range:new Ci(e),u_fog_color:new Bi(e),u_fog_horizon_blend:new Ri(e),u_fog_vertical_limit:new Ci(e),u_fog_temporal_offset:new Ri(e),u_frustum_tl:new Li(e),u_frustum_tr:new Li(e),u_frustum_br:new Li(e),u_frustum_bl:new Li(e),u_globe_pos:new Li(e),u_globe_radius:new Ri(e),u_globe_transition:new Ri(e),u_is_globe:new Ai(e),u_viewport:new Ci(e)}))(e)),n.includes("RENDER_CUTOFF")&&(this.cutoffUniforms=(e=>({u_cutoff_params:new Bi(e)}))(e)),n.includes("LIGHTING_3D_MODE")&&(this.lightsUniforms=(e=>({u_lighting_ambient_color:new Li(e),u_lighting_directional_dir:new Li(e),u_lighting_directional_color:new Li(e),u_ground_radiance:new Li(e)}))(e)),n.includes("RENDER_SHADOWS")&&(this.shadowUniforms=(e=>({u_light_matrix_0:new Pi(e),u_light_matrix_1:new Pi(e),u_fade_range:new Ci(e),u_shadow_normal_offset:new Li(e),u_shadow_intensity:new Ri(e),u_shadow_texel_size:new Ri(e),u_shadow_map_resolution:new Ri(e),u_shadow_direction:new Li(e),u_shadow_bias:new Li(e),u_shadowmap_0:new Ai(e),u_shadowmap_1:new Ai(e)}))(e))}maybeFinalize(){if(!this._pending)return;const e=this._context.extParallelShaderCompile;e&&!this._context.gl.getProgramParameter(this.program,e.COMPLETION_STATUS_KHR)||this._finalize()}_ensureReady(){this._pending&&(this._finalize(),this._context.sweepPendingPrograms())}getAttributeLocation(e,t){this._ensureReady();let i=this.attributes[t];return void 0===i&&(i=this.attributes[t]=e.getAttribLocation(this.program,t)),i}_setUniformGroup(e,t,i){this._ensureReady();const s=this[t];if(!this.failedToCreate&&s){e.program.set(this.program);for(const e in i){const t=s[e];t&&t.set(this.program,e,i[e])}}}setTerrainUniformValues(e,t){this._setUniformGroup(e,"terrainUniforms",t)}setGlobeUniformValues(e,t){this._setUniformGroup(e,"globeUniforms",t)}setFogUniformValues(e,t){this._setUniformGroup(e,"fogUniforms",t)}setCutoffUniformValues(e,t){this._setUniformGroup(e,"cutoffUniforms",t)}setLightsUniformValues(e,t){this._setUniformGroup(e,"lightsUniforms",t)}setShadowUniformValues(e,t){this._setUniformGroup(e,"shadowUniforms",t)}_drawDebugWireframe(e,t,i,s,o,r,n,a,l,c,h){const d=e.options.wireframe;if(!1===d.terrain&&!1===d.layers2D&&!1===d.layers3D)return;const u=e.context;if(!(()=>!(!d.terrain||"terrainRaster"!==this.name&&"globeRaster"!==this.name)||!(!d.layers2D||e._terrain&&e._terrain.renderingToTexture||!Fu.includes(this.name))||!(!d.layers3D||!ku.includes(this.name)))())return;const _=u.gl,p=e.wireframeDebugCache.getLinesFromTrianglesBuffer(e.frameCounter,o,u);if(!p)return;const f=[...this.fixedDefines,"DEBUG_WIREFRAME"],m=e.getOrCreateProgram(this.name,{config:this.configuration,defines:f});m._ensureReady(),u.program.set(m.program),h&&h.bind(u,m.program);const g=(e,t,i)=>{if(t[e]&&i[e])for(const s in t[e])i[e][s]&&i[e][s].set(i.program,s,t[e][s].current)};l&&l.setUniforms(m.program,u,m.binderUniforms,n,{zoom:a}),g("fixedUniforms",this,m),g("terrainUniforms",this,m),g("globeUniforms",this,m),g("fogUniforms",this,m),g("lightsUniforms",this,m),g("shadowUniforms",this,m),p.bind(),u.setColorMode(new zu([_.ONE,_.ONE_MINUS_SRC_ALPHA,_.ZERO,_.ONE],S.transparent,[!0,!0,!0,!1])),u.setDepthMode(new Cu(t.func===_.LESS?_.LEQUAL:t.func,Cu.ReadOnly,t.range)),u.setStencilMode(Pu.disabled);const v=3*r.primitiveLength*2,y=3*r.primitiveOffset*2*2;if(this.forceManualRenderingForInstanceIDShaders){const e=c||1;for(let t=0;t<e;++t)m.instancingUniforms.u_instanceID.set(this.program,"u_instanceID",t),_.drawElements(_.LINES,v,_.UNSIGNED_SHORT,y)}else c&&c>1?_.drawElementsInstanced(_.LINES,v,_.UNSIGNED_SHORT,y,c):_.drawElements(_.LINES,v,_.UNSIGNED_SHORT,y);o.bind(),u.program.set(this.program),u.setDepthMode(t),u.setStencilMode(i),u.setColorMode(s)}checkUniforms(e,t,i){if(this.fixedDefines.includes(t))for(const s of Object.keys(i))if(!i[s].initialized)throw new Error(`Program '${this.name}', from draw '${e}': uniform ${s} not set but required by ${t} being defined`)}draw(e,t,i,s,o,r,n,a,l,c,h,d,u,_,p,f,m){const g=e.context,v=g.gl;if(this._ensureReady(),this.failedToCreate)return;g.program.set(this.program),g.setDepthMode(i),g.setStencilMode(s),g.setColorMode(o),g.setCullFace(r);for(const[e,t]of this.activeUniforms)t.set(this.program,e,n[e]);_&&_.setUniforms(this.program,g,this.binderUniforms,d,{zoom:u});const y=t===v.TRIANGLES?3:t===v.LINES?2:1;this.checkUniforms(a,"RENDER_SHADOWS",this.shadowUniforms);const x=p||[],b=_?_.getPaintVertexBuffers():[],w=t===v.TRIANGLES&&c,T=f&&f>0?1:void 0;for(const r of h.get()){const n=r.vaos||(r.vaos={}),h=n[a]||(n[a]=new Map);let p=h.get(this.program);if(p||h.set(this.program,p=new fu),p.bind(g,this,l,b,c,r.vertexOffset,x,T),this.forceManualRenderingForInstanceIDShaders){const e=f||1;for(let i=0;i<e;++i)this.instancingUniforms.u_instanceID.set(this.program,"u_instanceID",i),c?v.drawElements(t,r.primitiveLength*y,v.UNSIGNED_SHORT,r.primitiveOffset*y*2):v.drawArrays(t,r.vertexOffset,r.vertexLength)}else f&&f>1?v.drawElementsInstanced(t,r.primitiveLength*y,v.UNSIGNED_SHORT,r.primitiveOffset*y*2,f):c?v.drawElements(t,r.primitiveLength*y,v.UNSIGNED_SHORT,r.primitiveOffset*y*2):v.drawArrays(t,r.vertexOffset,r.vertexLength);w&&this._drawDebugWireframe(e,i,s,o,c,r,d,u,_,f,m)}}};class Uu{constructor(e,t,i,s){this.id=Uu.uniqueIdxCounter,Uu.uniqueIdxCounter++,this.context=e;const o=e.gl;this.buffer=o.createBuffer(),this.dynamicDraw=Boolean(i),this.context.unbindVAO(),e.bindElementBuffer.set(this.buffer),o.bufferData(o.ELEMENT_ARRAY_BUFFER,t.arrayBuffer,this.dynamicDraw?o.DYNAMIC_DRAW:o.STATIC_DRAW),this.dynamicDraw||s||t.destroy()}bind(){this.context.bindElementBuffer.set(this.buffer)}updateData(e){this.id=Uu.uniqueIdxCounter,Uu.uniqueIdxCounter++;const t=this.context.gl;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)}}Uu.uniqueIdxCounter=0;const Vu={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class ju{constructor(e,t,i,s,o,r){this.length=t.length,this.attributes=i,this.itemSize=t.bytesPerElement,this.dynamicDraw=s,this.instanceCount=r,this.context=e;const n=e.gl;this.buffer=n.createBuffer(),e.bindVertexBuffer.set(this.buffer),n.bufferData(n.ARRAY_BUFFER,t.arrayBuffer,this.dynamicDraw?n.DYNAMIC_DRAW:n.STATIC_DRAW),this.dynamicDraw||o||t.destroy()}bind(){this.context.bindVertexBuffer.set(this.buffer)}updateData(e,t=0,i=e.length){if(t===i)return;const s=this.context.gl;this.bind();const o=e.bytesPerElement;s.bufferSubData(s.ARRAY_BUFFER,t*o,e.uint8,t*o,(i-t)*o)}enableAttributes(e,t){for(const i of this.attributes){const s=t.getAttributeLocation(e,i.name);-1!==s&&e.enableVertexAttribArray(s)}}setVertexAttribPointers(e,t,i){for(const s of this.attributes){const o=t.getAttributeLocation(e,s.name);if(-1!==o){const t=s.offset+this.itemSize*(i||0);"Float32"===s.type||s.normalized?e.vertexAttribPointer(o,s.components,e[Vu[s.type]],!!s.normalized,this.itemSize,t):e.vertexAttribIPointer(o,s.components,e[Vu[s.type]],this.itemSize,t)}}}setVertexAttribDivisor(e,t,i){for(let s=0;s<this.attributes.length;s++){const o=t.getAttributeLocation(e,this.attributes[s].name);-1!==o&&this.instanceCount&&this.instanceCount>0&&e.vertexAttribDivisor(o,i)}}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}class Gu{constructor(e){this.gl=e.gl,this.default=this.getDefault(),this.current=this.default,this.dirty=!1}get(){return this.current}set(e){}getDefault(){return this.default}setDefault(){this.set(this.default)}}class qu extends Gu{getDefault(){return S.transparent.toNonPremultipliedRenderColor(null)}set(e){const t=this.current;(e.r!==t.r||e.g!==t.g||e.b!==t.b||e.a!==t.a||this.dirty)&&(this.gl.clearColor(e.r,e.g,e.b,e.a),this.current=e,this.dirty=!1)}}class Zu extends Gu{getDefault(){return 1}set(e){(e!==this.current||this.dirty)&&(this.gl.clearDepth(e),this.current=e,this.dirty=!1)}}class Wu extends Gu{getDefault(){return 0}set(e){(e!==this.current||this.dirty)&&(this.gl.clearStencil(e),this.current=e,this.dirty=!1)}}class Hu extends Gu{getDefault(){return[!0,!0,!0,!0]}set(e){const t=this.current;(e[0]!==t[0]||e[1]!==t[1]||e[2]!==t[2]||e[3]!==t[3]||this.dirty)&&(this.gl.colorMask(e[0],e[1],e[2],e[3]),this.current=e,this.dirty=!1)}}class $u extends Gu{getDefault(){return!0}set(e){(e!==this.current||this.dirty)&&(this.gl.depthMask(e),this.current=e,this.dirty=!1)}}class Xu extends Gu{getDefault(){return 255}set(e){(e!==this.current||this.dirty)&&(this.gl.stencilMask(e),this.current=e,this.dirty=!1)}}class Yu extends Gu{getDefault(){return{func:this.gl.ALWAYS,ref:0,mask:255}}set(e){const t=this.current;(e.func!==t.func||e.ref!==t.ref||e.mask!==t.mask||this.dirty)&&(this.gl.stencilFunc(e.func,e.ref,e.mask),this.current=e,this.dirty=!1)}}class Ku extends Gu{getDefault(){const e=this.gl;return[e.KEEP,e.KEEP,e.KEEP]}set(e){const t=this.current;(e[0]!==t[0]||e[1]!==t[1]||e[2]!==t[2]||this.dirty)&&(this.gl.stencilOp(e[0],e[1],e[2]),this.current=e,this.dirty=!1)}}class Ju extends Gu{getDefault(){return!1}set(e){if(e===this.current&&!this.dirty)return;const t=this.gl;e?t.enable(t.STENCIL_TEST):t.disable(t.STENCIL_TEST),this.current=e,this.dirty=!1}}class Qu extends Gu{getDefault(){return[0,1]}set(e){const t=this.current;(e[0]!==t[0]||e[1]!==t[1]||this.dirty)&&(this.gl.depthRange(e[0],e[1]),this.current=e,this.dirty=!1)}}class e_ extends Gu{getDefault(){return!1}set(e){if(e===this.current&&!this.dirty)return;const t=this.gl;e?t.enable(t.DEPTH_TEST):t.disable(t.DEPTH_TEST),this.current=e,this.dirty=!1}}class t_ extends Gu{getDefault(){return this.gl.LESS}set(e){(e!==this.current||this.dirty)&&(this.gl.depthFunc(e),this.current=e,this.dirty=!1)}}class i_ extends Gu{getDefault(){return!1}set(e){if(e===this.current&&!this.dirty)return;const t=this.gl;e?t.enable(t.BLEND):t.disable(t.BLEND),this.current=e,this.dirty=!1}}class s_ extends Gu{getDefault(){const e=this.gl;return[e.ONE,e.ZERO,e.ONE,e.ZERO]}set(e){const t=this.current;(e[0]!==t[0]||e[1]!==t[1]||e[2]!==t[2]||e[3]!==t[3]||this.dirty)&&(this.gl.blendFuncSeparate(e[0],e[1],e[2],e[3]),this.current=e,this.dirty=!1)}}class o_ extends Gu{getDefault(){return S.transparent.toNonPremultipliedRenderColor(null)}set(e){const t=this.current;(e.r!==t.r||e.g!==t.g||e.b!==t.b||e.a!==t.a||this.dirty)&&(this.gl.blendColor(e.r,e.g,e.b,e.a),this.current=e,this.dirty=!1)}}class r_ extends Gu{getDefault(){return this.gl.FUNC_ADD}set(e){(e!==this.current||this.dirty)&&(this.gl.blendEquationSeparate(e,e),this.current=e,this.dirty=!1)}}class n_ extends Gu{getDefault(){return!1}set(e){if(e===this.current&&!this.dirty)return;const t=this.gl;e?t.enable(t.CULL_FACE):t.disable(t.CULL_FACE),this.current=e,this.dirty=!1}}class a_ extends Gu{getDefault(){return this.gl.BACK}set(e){(e!==this.current||this.dirty)&&(this.gl.cullFace(e),this.current=e,this.dirty=!1)}}class l_ extends Gu{getDefault(){return this.gl.CCW}set(e){(e!==this.current||this.dirty)&&(this.gl.frontFace(e),this.current=e,this.dirty=!1)}}class c_ extends Gu{getDefault(){return null}set(e){(e!==this.current||this.dirty)&&(this.gl.useProgram(e),this.current=e,this.dirty=!1)}}class h_ extends Gu{getDefault(){return this.gl.TEXTURE0}set(e){(e!==this.current||this.dirty)&&(this.gl.activeTexture(e),this.current=e,this.dirty=!1)}}class d_ extends Gu{getDefault(){const e=this.gl;return[0,0,e.drawingBufferWidth,e.drawingBufferHeight]}set(e){const t=this.current;(e[0]!==t[0]||e[1]!==t[1]||e[2]!==t[2]||e[3]!==t[3]||this.dirty)&&(this.gl.viewport(e[0],e[1],e[2],e[3]),this.current=e,this.dirty=!1)}}class u_ extends Gu{getDefault(){return null}set(e){if(e===this.current&&!this.dirty)return;const t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,e),this.current=e,this.dirty=!1}}class __ extends Gu{getDefault(){return null}set(e){if(e===this.current&&!this.dirty)return;const t=this.gl;t.bindRenderbuffer(t.RENDERBUFFER,e),this.current=e,this.dirty=!1}}class p_ extends Gu{getDefault(){return null}set(e){if(e===this.current&&!this.dirty)return;const t=this.gl;t.bindTexture(t.TEXTURE_2D,e),this.current=e,this.dirty=!1}}class f_ extends Gu{getDefault(){return null}set(e){if(e===this.current&&!this.dirty)return;const t=this.gl;t.bindBuffer(t.ARRAY_BUFFER,e),this.current=e,this.dirty=!1}}class m_ extends Gu{getDefault(){return null}set(e){const t=this.gl;t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,e),this.current=e,this.dirty=!1}}class g_ extends Gu{getDefault(){return null}set(e){this.gl&&(e!==this.current||this.dirty)&&(this.gl.bindVertexArray(e),this.current=e,this.dirty=!1)}}class v_ extends Gu{getDefault(){return 4}set(e){if(e===this.current&&!this.dirty)return;const t=this.gl;t.pixelStorei(t.UNPACK_ALIGNMENT,e),this.current=e,this.dirty=!1}}class y_ extends Gu{getDefault(){return!1}set(e){if(e===this.current&&!this.dirty)return;const t=this.gl;t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e),this.current=e,this.dirty=!1}}class x_ extends Gu{getDefault(){return!1}set(e){if(e===this.current&&!this.dirty)return;const t=this.gl;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,e),this.current=e,this.dirty=!1}}class b_ extends Gu{constructor(e,t){super(e),this.context=e,this.parent=t}getDefault(){return null}}class w_ extends b_{constructor(e,t,i=0){super(e,t),this.attachmentPoint=e.gl.COLOR_ATTACHMENT0+i}setDirty(){this.dirty=!0}set(e){if(e===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const t=this.gl;t.framebufferTexture2D(t.FRAMEBUFFER,this.attachmentPoint,t.TEXTURE_2D,e,0),this.current=e,this.dirty=!1}}class T_ extends b_{attachment(){return this.gl.DEPTH_ATTACHMENT}set(e){if(e===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const t=this.gl;t.framebufferRenderbuffer(t.FRAMEBUFFER,this.attachment(),t.RENDERBUFFER,e),this.current=e,this.dirty=!1}}class E_ extends b_{attachment(){return this.gl.DEPTH_ATTACHMENT}set(e){if(e===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const t=this.gl;t.framebufferTexture2D(t.FRAMEBUFFER,this.attachment(),t.TEXTURE_2D,e,0),this.current=e,this.dirty=!1}}class I_ extends T_{attachment(){return this.gl.DEPTH_STENCIL_ATTACHMENT}}class S_{constructor(e,t,i,s,o){this.context=e,this.width=t,this.height=i;const r=this.framebuffer=e.gl.createFramebuffer();s>0&&(this.colorAttachment0=new w_(e,r,0)),s>1&&(this.colorAttachment1=new w_(e,r,1)),o&&(this.depthAttachmentType=o,this.depthAttachment="renderbuffer"===o?new T_(e,r):new E_(e,r))}static createWithTexture(e,t,i,s,o){const r=e.gl;if(e.activeTexture.set(r.TEXTURE1),e.viewport.set([0,0,i,s]),t&&t.width===i&&t.height===s)return r.bindTexture(r.TEXTURE_2D,t.colorAttachment0.get()),e.bindFramebuffer.set(t.framebuffer),t;t&&t.destroy();const n=e.extRenderToTextureHalfFloat||e.extColorBufferFloat?e.gl.RGBA16F:e.gl.RGBA8,a=new k(e,{width:i,height:s,data:null},n);a.bind(r.LINEAR,r.CLAMP_TO_EDGE);const l=e.createFramebuffer(i,s,1,null);if(l.format=n,l.colorAttachment0.set(a.texture),o){const t=e.createRenderbuffer(r.DEPTH24_STENCIL8,i,s);e.bindFramebuffer.set(l.framebuffer),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.RENDERBUFFER,t),l._stencilRbo=t}return l}createColorAttachment(e,t){0===t?this.colorAttachment0=new w_(e,this.framebuffer,0):1===t&&(this.colorAttachment1=new w_(e,this.framebuffer,1))}removeColorAttachment(e,t){const i=this.context.gl;let s;0===t?(s=this.colorAttachment0.get(),this.colorAttachment0=void 0):1===t&&(s=this.colorAttachment1.get(),this.colorAttachment1=void 0),s&&i.deleteTexture(s)}destroy(){const e=this.context.gl;if(this.colorAttachment0){const t=this.colorAttachment0.get();t&&e.deleteTexture(t)}if(this.colorAttachment1){const t=this.colorAttachment1.get();t&&e.deleteTexture(t)}if(this.depthAttachment&&this.depthAttachmentType)if("renderbuffer"===this.depthAttachmentType){const t=this.depthAttachment.get();t&&e.deleteRenderbuffer(t)}else{const t=this.depthAttachment.get();t&&e.deleteTexture(t)}this._stencilRbo&&(e.deleteRenderbuffer(this._stencilRbo),this._stencilRbo=null),e.deleteFramebuffer(this.framebuffer)}}class D_{constructor(e,t){this.gl=e,this._pendingPrograms=new Set,this._compileStats={precompiled:0,onDemand:0,totalStallMs:0,maxStallMs:0,framesMissed:0,stalls:[]},this.clearColor=new qu(this),this.clearDepth=new Zu(this),this.clearStencil=new Wu(this),this.colorMask=new Hu(this),this.depthMask=new $u(this),this.stencilMask=new Xu(this),this.stencilFunc=new Yu(this),this.stencilOp=new Ku(this),this.stencilTest=new Ju(this),this.depthRange=new Qu(this),this.depthTest=new e_(this),this.depthFunc=new t_(this),this.blend=new i_(this),this.blendFunc=new s_(this),this.blendColor=new o_(this),this.blendEquation=new r_(this),this.cullFace=new n_(this),this.cullFaceSide=new a_(this),this.frontFace=new l_(this),this.program=new c_(this),this.activeTexture=new h_(this),this.viewport=new d_(this),this.bindFramebuffer=new u_(this),this.bindRenderbuffer=new __(this),this.bindTexture=new p_(this),this.bindVertexBuffer=new f_(this),this.bindElementBuffer=new m_(this),this.bindVertexArrayOES=new g_(this),this.pixelStoreUnpack=new v_(this),this.pixelStoreUnpackPremultiplyAlpha=new y_(this),this.pixelStoreUnpackFlipY=new x_(this),this.options=t?{...t}:{},this.options.extTextureFilterAnisotropicForceOff||(this.extTextureFilterAnisotropic=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic"),this.extTextureFilterAnisotropic&&(this.extTextureFilterAnisotropicMax=e.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT))),this.extDebugRendererInfo=e.getExtension("WEBGL_debug_renderer_info"),this.extDebugRendererInfo&&(this.renderer=e.getParameter(this.extDebugRendererInfo.UNMASKED_RENDERER_WEBGL),this.vendor=e.getParameter(this.extDebugRendererInfo.UNMASKED_VENDOR_WEBGL)),this.forceManualRenderingForInstanceIDShaders=t&&!!t.forceManualRenderingForInstanceIDShaders||this.renderer&&this.renderer.includes("PowerVR"),this.options.extTextureFloatLinearForceOff||(this.extTextureFloatLinear=e.getExtension("OES_texture_float_linear")),this.extRenderToTextureHalfFloat=e.getExtension("EXT_color_buffer_half_float"),this.extColorBufferFloat=e.getExtension("EXT_color_buffer_float"),this.extTimerQuery=e.getExtension("EXT_disjoint_timer_query_webgl2"),this.maxTextureSize=e.getParameter(e.MAX_TEXTURE_SIZE),this.maxUniformBlockSize=Math.min(e.getParameter(e.MAX_UNIFORM_BLOCK_SIZE),32768),this.extBlendFuncExtended=e.getExtension("WEBGL_blend_func_extended"),this.extParallelShaderCompile=e.getExtension("KHR_parallel_shader_compile")}sweepPendingPrograms(){if(0!==this._pendingPrograms.size)for(const e of this._pendingPrograms)e.maybeFinalize()}setDefault(){this.unbindVAO(),this.clearColor.setDefault(),this.clearDepth.setDefault(),this.clearStencil.setDefault(),this.colorMask.setDefault(),this.depthMask.setDefault(),this.stencilMask.setDefault(),this.stencilFunc.setDefault(),this.stencilOp.setDefault(),this.stencilTest.setDefault(),this.depthRange.setDefault(),this.depthTest.setDefault(),this.depthFunc.setDefault(),this.blend.setDefault(),this.blendFunc.setDefault(),this.blendColor.setDefault(),this.blendEquation.setDefault(),this.cullFace.setDefault(),this.cullFaceSide.setDefault(),this.frontFace.setDefault(),this.program.setDefault(),this.activeTexture.setDefault(),this.bindFramebuffer.setDefault(),this.pixelStoreUnpack.setDefault(),this.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.pixelStoreUnpackFlipY.setDefault()}setDirty(){this.clearColor.dirty=!0,this.clearDepth.dirty=!0,this.clearStencil.dirty=!0,this.colorMask.dirty=!0,this.depthMask.dirty=!0,this.stencilMask.dirty=!0,this.stencilFunc.dirty=!0,this.stencilOp.dirty=!0,this.stencilTest.dirty=!0,this.depthRange.dirty=!0,this.depthTest.dirty=!0,this.depthFunc.dirty=!0,this.blend.dirty=!0,this.blendFunc.dirty=!0,this.blendColor.dirty=!0,this.blendEquation.dirty=!0,this.cullFace.dirty=!0,this.cullFaceSide.dirty=!0,this.frontFace.dirty=!0,this.program.dirty=!0,this.activeTexture.dirty=!0,this.viewport.dirty=!0,this.bindFramebuffer.dirty=!0,this.bindRenderbuffer.dirty=!0,this.bindTexture.dirty=!0,this.bindVertexBuffer.dirty=!0,this.bindElementBuffer.dirty=!0,this.bindVertexArrayOES.dirty=!0,this.pixelStoreUnpack.dirty=!0,this.pixelStoreUnpackPremultiplyAlpha.dirty=!0,this.pixelStoreUnpackFlipY.dirty=!0}createIndexBuffer(e,t,i){return new Uu(this,e,t,i)}createVertexBuffer(e,t,i,s,o){return new ju(this,e,t,i,s,o)}createRenderbuffer(e,t,i){const s=this.gl,o=s.createRenderbuffer();return this.bindRenderbuffer.set(o),s.renderbufferStorage(s.RENDERBUFFER,e,t,i),this.bindRenderbuffer.set(null),o}createFramebuffer(e,t,i,s){return new S_(this,e,t,i,s)}clear({color:e,depth:t,stencil:i,colorMask:s}){const o=this.gl;let r=0;e&&(r|=o.COLOR_BUFFER_BIT,this.clearColor.set(e.toNonPremultipliedRenderColor(null)),this.colorMask.set(s||[!0,!0,!0,!0])),void 0!==t&&(r|=o.DEPTH_BUFFER_BIT,this.depthRange.set([0,1]),this.clearDepth.set(t),this.depthMask.set(!0)),void 0!==i&&(r|=o.STENCIL_BUFFER_BIT,this.clearStencil.set(i),this.stencilMask.set(255)),o.clear(r)}setCullFace(e){!1===e.enable?this.cullFace.set(!1):(this.cullFace.set(!0),this.cullFaceSide.set(e.mode),this.frontFace.set(e.frontFace))}setDepthMode(e){e.func!==this.gl.ALWAYS||e.mask?(this.depthTest.set(!0),this.depthFunc.set(e.func),this.depthMask.set(e.mask),this.depthRange.set(e.range)):this.depthTest.set(!1)}setStencilMode(e){e.test.func!==this.gl.ALWAYS||e.mask?(this.stencilTest.set(!0),this.stencilMask.set(e.mask),this.stencilOp.set([e.fail,e.depthFail,e.pass]),this.stencilFunc.set({func:e.test.func,ref:e.ref,mask:e.test.mask})):this.stencilTest.set(!1)}setColorMode(e){e.blendFunction===zu.Replace?this.blend.set(!1):(this.blend.set(!0),this.blendFunc.set(e.blendFunction),this.blendColor.set(e.blendColor),e.blendEquation?this.blendEquation.set(e.blendEquation):this.blendEquation.setDefault()),this.colorMask.set(e.mask)}unbindVAO(){this.bindVertexArrayOES.set(null)}}const R_=1029,C_=2305;class A_{constructor(e,t,i){this.enable=e,this.mode=t,this.frontFace=i}}A_.disabled=new A_(!1,R_,C_),A_.backCCW=new A_(!0,R_,C_),A_.backCW=new A_(!0,R_,2304),A_.frontCW=new A_(!0,1028,2304),A_.frontCCW=new A_(!0,1028,C_);const L_=Bt();function P_({width:e,height:t,anchor:i,textOffset:s,textScale:o},r){const{horizontalAlign:n,verticalAlign:a}=mi(i),l=-(n-.5)*e,c=-(a-.5)*t,h=vi(i,s);return new m((l/o+h[0])*r,(c/o+h[1])*r)}function M_(e,t,i,s,o,r,n,a,l,c){const h=e.text.placedSymbolArray,d=e.text.dynamicLayoutVertexArray,u=e.icon.dynamicLayoutVertexArray,_={},p=e.getProjection(),f=bo(n,p,o),g=o.elevation,v=p.upVectorScale(n.canonical,o.center.lat,o.worldSize).metersToTile;d.clear();for(let u=0;u<h.length;u++){const y=h.get(u),{tileAnchorX:x,tileAnchorY:b,numGlyphs:w}=y,T=y.hidden||!y.crossTileID||e.allowVerticalPlacement&&!y.placedOrientation?null:s[y.crossTileID];if(T){let s=0,h=0,E=0;const I="road"===e.elevationType;if(g||I){const t=new m(x,b);let i=0;if(I&&e.hdExt){const s=e.symbolInstances.get(e.text.symbolInstanceIndices[u]);if(e.hdExt.isCrossTileRoadElevation(s.elevationFeatureIndex,n.canonical)){const s=e.hdExt.getRoadFeatureHeightForPlacedSymbol(e,e.text,u,t,n.canonical);i=null!==s?s:0}else{const s=e.hdExt.getElevationFeatureForPlacedSymbol(e,e.text,u);i=ri.getAtTileOffset(n,t,g,void 0!==s?s:null)}}else i=ri.getAtTileOffset(n,t,g,null);const[o,r,a]=p.upVector(n.canonical,x,b);s=i*o*v,h=i*r*v,E=i*a*v}let[S,D,R,C]=Gc(y.projectedAnchorX+s,y.projectedAnchorY+h,y.projectedAnchorZ+E,i?f:r);const A=qc(o.getCameraToCenterDistance(p),C);let L=Yt(e.textSizeData,l,y)*A/ui;i&&(L*=e.tilePixelRatio/a);const P=P_(T,L);i?(({x:S,y:D,z:R}=p.projectTilePoint(x+P.x,b+P.y,n.canonical)),[S,D,R]=Gc(S+s,D+h,R+E,r)):(t&&P._rotate(-o.angle),S+=P.x,D+=P.y,R=0);const M=e.allowVerticalPlacement&&y.placedOrientation===Gt.vertical?Math.PI/2:0;for(let e=0;e<w;e++)Xt(d,S,D,R,M);c&&y.associatedIconIndex>=0&&(_[y.associatedIconIndex]={x:S,y:D,z:R,angle:M})}else th(w,d)}if(c){u.clear();const t=e.icon.placedSymbolArray;for(let e=0;e<t.length;e++){const i=t.get(e),{numGlyphs:s}=i,o=_[e];if(i.hidden||!o)th(s,u);else{const{x:e,y:t,z:i,angle:r}=o;for(let o=0;o<s;o++)Xt(u,e,t,i,r)}}e.icon.dynamicLayoutVertexBuffer.updateData(u)}e.text.dynamicLayoutVertexBuffer.updateData(d)}function O_(e,t,i,s,o,r,n={}){const a=i.paint.get("icon-translate"),l=i.paint.get("text-translate"),c=i.paint.get("icon-translate-anchor"),h=i.paint.get("text-translate-anchor"),d=i.layout.get("icon-rotation-alignment"),u=i.layout.get("text-rotation-alignment"),_=i.layout.get("icon-pitch-alignment"),p=i.layout.get("text-pitch-alignment"),f=i.layout.get("icon-keep-upright"),m=i.layout.get("text-keep-upright"),g=i.paint.get("icon-color-saturation"),v=i.paint.get("icon-color-contrast"),y=i.paint.get("icon-color-brightness-min"),x=i.paint.get("icon-color-brightness-max"),b="sea"===i.layout.get("symbol-elevation-reference"),w="none"===i.layout.get("icon-image-use-theme"),T=e.context,E=T.gl,I=e.transform,S="map"===d,D="map"===u,R="map"===_,C="map"===p,A=void 0!==i.layout.get("symbol-sort-key").constantOr(1);let L=!1;const P=e.depthModeForSublayer(0,Cu.ReadOnly),M=new Cu(e.context.gl.LEQUAL,Cu.ReadOnly,e.depthRangeFor3D),O=[Ae(I.center.lng),Pe(I.center.lat)],z=i.layout.get("text-variable-anchor"),F="globe"===I.projection.name,k=[],B=[0,-1,0];let N;const U=()=>N=N||function(e){const t=e._camera.getWorldToCamera(e.worldSize,1),i=Ie(new Float64Array(16),t,e.globeMatrix);Tt(i,i);const s=[0,0,0],o=[0,1,0,0];return Se(o,o,i),s[0]=o[0],s[1]=o[1],s[2]=o[2],ye(s,s),s}(I);for(const o of s){const s=t.getTile(o),r=s.getBucket(i);if(!r)continue;if("mercator"===r.projection.name&&F)continue;if(r.fullyClipped)continue;const d="globe"===r.projection.name,u=d?K(I.zoom):0,_=bo(o,r.getProjection(),I),p=r.getProjection().name!==I.projection.name?Ie(Bt(),I.worldToFogMatrix,r.getProjection().createTileMatrix(I,I.cameraWorldSizeForFog,o.toUnwrapped())):null,N=I.calculatePixelsToTileUnitsMatrix(s),V=z&&r.hasTextData(),j=r.hasIconTextFit()&&V&&r.hasIconData(),G=r.getProjection().createInversionMatrix(I,o.canonical),q=(1<<s.tileID.canonical.z)*ae/e.transform.worldSize,Z=t=>{let i=[0,0,0];if(t){const t=e.style.directionalLight,s=e.style.ambientLight;t&&s&&(i=Gh(e.style,t,s))}return i},W=t=>{const i=Math.floor(e.context.maxUniformBlockSize/4),s=Math.floor(i/4);t.push(`MAX_UBO_SIZE_VEC4 ${s}u`)},H=t=>{I.depthOcclusionForSymbolsAndCircles&&(i.hasOcclusionOpacityProperties||e.terrain)&&(t.push("DEPTH_D24"),t.push("DEPTH_OCCLUSION"))},$=t=>{i.lut&&!w&&(i.lut.texture||(i.lut.texture=new wo(e.context,i.lut.image,[i.lut.image.height,i.lut.image.height,i.lut.image.height],T.gl.RGBA8)),T.activeTexture.set(T.gl.TEXTURE0+yd.LUT),i.lut.texture&&i.lut.texture.bind(T.gl.LINEAR,T.gl.CLAMP_TO_EDGE),t.push("APPLY_LUT_ON_GPU"))},X=()=>{const t=S&&"point"!==i.layout.get("symbol-placement"),n=[];H(n),$(n);const l=t||j,h="road"===r.elevationType,m=e.shadowRenderer,w=h&&R&&!!m&&m.enabled,T=Z(w),D=h&&R&&!e.terrain?M:P,C=i.paint.get("icon-image-cross-fade");e.terrainRenderModeElevated()&&R&&n.push("PITCH_WITH_MAP_TERRAIN"),d&&(n.push("PROJECTION_GLOBE_VIEW"),l&&n.push("PROJECTED_POS_ON_VIEWPORT")),C>0&&r.hasAnySecondaryIcon&&n.push("ICON_TRANSITION"),!r.icon.zOffsetVertexBuffer||h&&e.terrain||n.push("Z_OFFSET"),n.push(r.icon.fadeVertexBuffer?"GLOBAL_PLACEMENT_FADE":"LEGACY_PLACEMENT_FADE"),0===g&&0===v&&0===y&&1===x||n.push("COLOR_ADJUSTMENT"),w&&n.push("RENDER_SHADOWS","NORMAL_OFFSET"),h&&R&&!e.terrain&&r.icon.orientationVertexBuffer&&n.push("ELEVATED_ROADS"),W(n);const A=R&&!d&&e.isTileAffectedByFog(o),L=e.getOrCreateProgram("symbol",{defines:n,overrideFog:A}),z=s.imageAtlasTexture?s.imageAtlasTexture.size:[0,0],k=r.iconSizeData,V=jt(k,I.zoom),X=R||!I.isOrthographic,Y=Uc(_,s.tileID.canonical,R,S,I,r.getProjection(),N),K=jc(_,s.tileID.canonical,R,S,I,r.getProjection(),N),J=r.icon.uboBinder&&r.icon.uboBinder.hasPerFeatureTranslate()?[0,0]:a,Q=e.translatePosMatrix(K,s,J,c,!0),ee=e.translatePosMatrix(_,s,J,c),te=l?L_:Y,ie=S&&!R&&!t,se=d&&(F||I.mercatorFromTransition)&&!S?U():B,oe=i.getColorAdjustmentMatrix(g,v,y,x),re=bd(k.kind,V,ie,R,e,ee,te,Q,b,!1,r.sdfIcons,z,[0,0],0,o,u,O,G,se,r.getProjection(),T,q,oe,C,null),ne=s.imageAtlasTexture?s.imageAtlasTexture:null,ae=1!==i.layout.get("icon-size").constantOr(0)||r.iconsNeedLinear,le=R&&!r.sdfIcons&&!!ne&&!!ne.useMipmap,ce=r.sdfIcons||e.options.rotating||e.options.zooming||ae||X?E.LINEAR:E.NEAREST,he=r.sdfIcons&&0!==i.paint.get("icon-halo-width").constantOr(1),de=e.terrain&&R&&t?Tt(Bt(),Y):L_;if(t&&r.icon){const t=ri.getAtTileOffsetFunc(o,I.center.lat,I.worldSize,r.getProjection()),n=Vc(_,s.tileID.canonical,R,S,I,r.getProjection(),N),a=i.layout.get("icon-size-scale-range"),l=Ee(e.scaleFactor,a[0],a[1]);Wc(r,_,e,!1,n,K,R,f,t,o,l)}return{program:L,buffers:r.icon,uniformValues:re,atlasTexture:ne,atlasTextureIcon:null,atlasInterpolation:ce,atlasInterpolationIcon:null,atlasMipmaps:le,isSDF:r.sdfIcons,hasHalo:he,depthMode:D,tile:s,renderWithShadows:w,labelPlaneMatrixInv:de,fogMatrix:p}},Y=()=>{const t=D&&"point"!==i.layout.get("symbol-placement"),n=[],a=t||z||j,c="road"===r.elevationType,f=e.shadowRenderer,g=c&&C&&!!f&&f.enabled,v=Z(g),y=c&&C&&!e.terrain?M:P;e.terrainRenderModeElevated()&&C&&n.push("PITCH_WITH_MAP_TERRAIN"),d&&(n.push("PROJECTION_GLOBE_VIEW"),a&&n.push("PROJECTED_POS_ON_VIEWPORT")),!r.text.zOffsetVertexBuffer||c&&e.terrain||n.push("Z_OFFSET"),n.push(r.text.fadeVertexBuffer?"GLOBAL_PLACEMENT_FADE":"LEGACY_PLACEMENT_FADE"),r.iconsInText&&n.push("RENDER_TEXT_AND_SYMBOL"),g&&n.push("RENDER_SHADOWS","NORMAL_OFFSET"),c&&C&&!e.terrain&&r.text.orientationVertexBuffer&&n.push("ELEVATED_ROADS"),H(n),W(n);const x=C&&!d&&e.isTileAffectedByFog(o),w=e.getOrCreateProgram("symbol",{defines:n,overrideFog:x});let T,S=[0,0],R=null;const A=r.textSizeData;r.iconsInText&&(S=s.imageAtlasTexture?s.imageAtlasTexture.size:[0,0],R=s.imageAtlasTexture?s.imageAtlasTexture:null,T=C||!I.isOrthographic||e.options.rotating||e.options.zooming||"composite"===A.kind||"camera"===A.kind?E.LINEAR:E.NEAREST);const L=s.glyphAtlasTexture?s.glyphAtlasTexture.size:[0,0],k=i.layout.get("text-size-scale-range"),V=Ee(e.scaleFactor,k[0],k[1]),$=jt(A,I.zoom,V),X=Uc(_,s.tileID.canonical,C,D,I,r.getProjection(),N),Y=jc(_,s.tileID.canonical,C,D,I,r.getProjection(),N),K=r.text.uboBinder&&r.text.uboBinder.hasPerFeatureTranslate()?[0,0]:l,J=e.translatePosMatrix(Y,s,K,h,!0),Q=e.translatePosMatrix(_,s,K,h),ee=a?L_:X,te=D&&!C&&!t,ie=d&&(F||I.mercatorFromTransition)&&!D?U():B,se=bd(A.kind,$,te,C,e,Q,ee,J,b,!0,!0,L,S,0,o,u,O,G,ie,r.getProjection(),v,q,null,null,V),oe=s.glyphAtlasTexture?s.glyphAtlasTexture:null,re=E.LINEAR,ne=0!==i.paint.get("text-halo-width").constantOr(1),ae=e.terrain&&C&&t?Tt(Bt(),X):L_;if(t&&r.text){const t=ri.getAtTileOffsetFunc(o,I.center.lat,I.worldSize,r.getProjection()),i=Vc(_,s.tileID.canonical,C,D,I,r.getProjection(),N);Wc(r,_,e,!0,i,Y,C,m,t,o,V)}return{program:w,buffers:r.text,uniformValues:se,atlasTexture:oe,atlasTextureIcon:R,atlasInterpolation:re,atlasInterpolationIcon:T,atlasMipmaps:!1,isSDF:!0,hasHalo:ne,depthMode:y,tile:s,renderWithShadows:g,labelPlaneMatrixInv:ae,fogMatrix:p}},J=r.icon.segments.get().length,Q=r.text.segments.get().length,ee=J&&!n.onlyText?X():null,te=Q&&!n.onlyIcons?Y():null,ie=i.paint.get("icon-opacity").constantOr(1),se=i.paint.get("text-opacity").constantOr(1);if(A&&r.canOverlap){L=!0;const e=ie&&!n.onlyText?r.icon.segments.get():[],t=se&&!n.onlyIcons?r.text.segments.get():[];for(const t of e)k.push({segments:new Ye([t]),sortKey:t.sortKey,state:ee});for(const e of t)k.push({segments:new Ye([e]),sortKey:e.sortKey,state:te})}else n.onlyText||k.push({segments:ie?r.icon.segments:new Ye([]),sortKey:0,state:ee}),n.onlyIcons||k.push({segments:se?r.text.segments:new Ye([]),sortKey:0,state:te})}L&&k.sort((e,t)=>e.sortKey-t.sortKey);for(const t of k){const s=t.state;if(s)if(e.terrain?e.terrain.setupElevationDraw(s.tile,s.program,{useDepthForOcclusion:I.depthOcclusionForSymbolsAndCircles,labelPlaneMatrixInv:s.labelPlaneMatrixInv}):e.setupDepthForOcclusion(I.depthOcclusionForSymbolsAndCircles,s.program),T.activeTexture.set(E.TEXTURE0),s.atlasTexture&&s.atlasTexture.bind(s.atlasInterpolation,E.CLAMP_TO_EDGE,!s.atlasMipmaps,s.atlasMipmaps),s.atlasTextureIcon&&(T.activeTexture.set(E.TEXTURE1),s.atlasTextureIcon&&s.atlasTextureIcon.bind(s.atlasInterpolationIcon,E.CLAMP_TO_EDGE,!0)),s.renderWithShadows&&e.shadowRenderer.setupShadows(s.tile.tileID.toUnwrapped(),s.program,"vector-tile"),e.uploadCommonUniforms(e.context,s.program,s.fogMatrix?null:s.tile.tileID.toUnwrapped(),s.fogMatrix),s.hasHalo){const n=s.uniformValues;n.u_is_halo=1,z_(s.buffers,t.segments,i,e,s.program,s.depthMode,o,r,n,2),n.u_is_halo=0}else{if(s.isSDF){const n=s.uniformValues;s.hasHalo&&(n.u_is_halo=1,z_(s.buffers,t.segments,i,e,s.program,s.depthMode,o,r,n,1)),n.u_is_halo=0}z_(s.buffers,t.segments,i,e,s.program,s.depthMode,o,r,s.uniformValues,1)}}}function z_(e,t,i,s,o,r,n,a,l,c){const h=s.context,d=h.gl,u=[e.dynamicLayoutVertexBuffer,e.opacityVertexBuffer,e.iconTransitioningVertexBuffer,e.globeExtVertexBuffer,e.zOffsetVertexBuffer,e.orientationVertexBuffer];e.featureIdBuffer&&u.push(e.featureIdBuffer),e.fadeVertexBuffer&&u.push(e.fadeVertexBuffer);const _=e.uboBinder?null:e.programConfigurations.get(i.id);if(e.uboBinder){e.uboBinder.layer=i;const t=s.transform.zoom,o=s.style.getBrightness?s.style.getBrightness():null,r=e.uboBinder.getConstantUniformValues(o);l.u_spp_fill_np_color=r.fill_np_color,l.u_spp_halo_np_color=r.halo_np_color,l.u_spp_opacity=r.opacity,l.u_spp_halo_width=r.halo_width,l.u_spp_halo_blur=r.halo_blur,l.u_spp_emissive_strength=r.emissive_strength,l.u_spp_occlusion_opacity=r.occlusion_opacity,l.u_spp_z_offset=r.z_offset,l.u_spp_zoom_fraction=t-e.uboBinder._floorZoom;const n=i.paint.get(e.uboBinder.isText?"text-translate-anchor":"icon-translate-anchor"),a=e.uboBinder.hasPerFeatureTranslate()&&"map"===n?s.transform.angle:0;l.u_spp_translate_rotation=[Math.cos(a),Math.sin(a)]}const{batchIndices:p,batchSegments:f}=e.getBatchGrouping(t);for(const t of p){const p=f.get(t);e.uboBinder&&e.uboBinder.bind(h,o.program,t),o.draw(s,d.TRIANGLES,r,n,a,A_.disabled,l,i.id,e.layoutVertexBuffer,e.indexBuffer,p,i.paint,s.transform.zoom,_,u,c,e.uboBinder?e.uboBinder.getUBO(t):void 0)}}function F_(e,t,i,s,o,r){const n=i.paint.get("line-width"),a=i.paint.get("line-emissive-strength").isConstant(),l=i.paint.get("line-emissive-strength").constantOr(0),c=i.paint.get("line-occlusion-opacity"),h=i.layout.get("line-elevation-reference"),d="meters"===i.layout.get("line-width-unit"),u="sea"===h,p=!(!e.terrain||!e.terrain.enabled),f=e.context,m=f.gl;if(i.hasElevatedBuckets&&"globe"===e.transform.projection.name)return;const g=i.layout.get("line-cross-slope"),v=void 0!==g,y=g<1,x=o||e.colorModeForDrapableLayerRenderPass(a?l:null),b=e.terrain&&e.terrain.renderingToTexture||r,w=b?1:T.devicePixelRatio,E=i.paint.get("line-dasharray"),I=E.constantOr(1),S=i.layout.get("line-cap"),D=E.constantOr(null),R=S.constantOr(null),C=i.paint.get("line-pattern"),A=C.constantOr(1),L=i.paint.get("line-pattern-cross-fade"),P=C.constantOr(null),M=i.paint.get("line-opacity").constantOr(1);let O=!A&&1!==M||e.depthOcclusion&&c>0&&c<1;const z=i.paint.get("line-gradient"),F=0!==i.paint.get("line-border-width").constantOr(1)?i.paint.get("line-border-gradient"):null,B=A?"linePattern":"line",N=Io(i);if(!A){const t=Math.floor(e.context.maxUniformBlockSize/4),i=Math.floor(t/4);N.push(`MAX_UBO_SIZE_VEC4 ${i}u`)}let U;if(b&&e.terrain&&e.terrain.clipOrMaskOverlapStencilType()&&(O=!1),0!==c&&e.depthOcclusion){const e=i.paint._values["line-opacity"];e&&e.value&&"constant"===e.value.kind?U=e.value:_(`Occlusion opacity for layer ${i.id} is supported only when line-opacity isn't data-driven.`)}"constant"!==n.value.kind&&!1===n.value.isLineProgressConstant&&N.push("VARIABLE_LINE_WIDTH");const V=i.paint.get("line-emissive-strength");A||"constant"===V.value.kind||!1!==V.value.isLineProgressConstant||N.push("VARIABLE_LINE_EMISSIVE_STRENGTH"),e._debugParams.showElevationIdDebug&&N.push("DEBUG_ELEVATION_ID"),b&&("dual-source-blending"!==e.emissiveMode||a?e.isEmissiveMrtActive()&&(N.push("USE_MRT1"),"mrt-full-rgba"===e.emissiveMode&&N.push("USE_MRT1_RGBA")):N.push("DUAL_SOURCE_BLENDING"));const j={};let G=null;const q=[],Z=(s,o,r,n,a,l)=>{for(const h of s){const s=t.getTile(h);if(A&&!s.patternsLoaded())continue;const u=s.getBucket(i);if(!u)continue;if("none"!==u.elevationType&&!a||"none"===u.elevationType&&a)continue;e.prepareDrawTile();const _=[...o],p="road"===u.elevationType,g=e.shadowRenderer,v=p&&!!g&&g.enabled;let y=[0,0,0];if(v){const t=e.style.directionalLight,i=e.style.ambientLight;t&&i&&(y=Gh(e.style,t,i)),_.push("RENDER_SHADOWS","NORMAL_OFFSET")}const T=A?u.programConfigurations.get(i.id):null,E=A?null:u.uboBinders[i.id];let S=!1;if(T&&P&&s.imageAtlas){const e=So.from(P),t=e.getPrimary().scaleSelf(w).toString(),i=s.imageAtlas.patternPositions.get(t),o=e.getSecondary(),r=o?s.imageAtlas.patternPositions.get(o.scaleSelf(w).toString()):null;S=!!i&&!!r,i&&T.setConstantPatternPositions(i,r)}T&&L>0&&(S||T.getPatternTransitionVertexBuffer("line-pattern"))&&_.push("LINE_PATTERN_TRANSITION"),u.elevationGroundScaleVertexBuffer&&_.push("ELEVATION_GROUND_SCALE");const C=e.isTileAffectedByFog(h),N=e.getOrCreateProgram(B,{config:T,defines:_,overrideFog:C});let V=null;!A&&D&&R&&s.lineAtlas&&(V=s.lineAtlas.getDash(D,R)),v&&g.setupShadows(s.tileID.toUnwrapped(),N,"vector-tile");let[Z,W]=i.paint.get("line-trim-offset");if("round"===R||"square"===R){const e=1;Z!==W&&(0===Z&&(Z-=e),1===W&&(W+=e))}const H=b?h.projMatrix:null,$=d?1/u.tileToMeter/Te(s,1,e.transform.zoom):1,X=d?1/u.tileToMeter/Te(s,1,Math.floor(e.transform.zoom)):1,Y=A&&I?i.paint._values["line-floorwidth"]:null;let K;const J=s.dashIdealZ;if(Y&&"constant"===Y.value.kind&&J!==s.tileID.overscaledZ){const e=u.zoom;e in j||(j[e]=Math.max(.01,i.getPaintPropertyValue("line-width").expression.evaluate({zoom:e}))),K=Y.value.value,Y.value.value=j[e]*Math.pow(2,J-e)}const Q=A?Do(e,s,i,H,w,$,X,[Z,W],y,L):Ro(e,s,i,H,u.lineClipsArray.length,w,$,X,[Z,W],y),ee=(s,o,r,n,a,l)=>{let c=s.texture;if(o!==s.version){let l=256;if(r){const i=t.getSource().maxzoom,s=h.canonical.z===i?Math.ceil(1<<e.transform.maxZoom-h.canonical.z):1;l=Ee(Po(u.maxLineLength/ae*1024*s),256,f.maxTextureSize)}s.gradient=Lo({expression:n,evaluationKey:"lineProgress",resolution:l,image:s.gradient||void 0,clips:u.lineClipsArray,lut:a?null:i.lut}),s.texture?s.texture.update(s.gradient):s.texture=new k(f,s.gradient,m.RGBA8),s.version=o,c=s.texture}f.activeTexture.set(l),c.bind(r?m.NEAREST:m.LINEAR,m.CLAMP_TO_EDGE)};if(E){E.layer=i;const t=e.transform.zoom;if(!G){const t=e.style.getBrightness?e.style.getBrightness():null;G=E.getConstantUniformValues(t)}const o=G,r=Q;if(r.u_lpp_color=o.color_np_color,r.u_lpp_border_color=o.border_np_color,r.u_lpp_opacity=o.opacity,r.u_lpp_blur=o.blur,r.u_lpp_width=o.width,r.u_lpp_gap_width=o.gap_width,r.u_lpp_offset=o.offset,r.u_lpp_floorwidth=o.floorwidth,r.u_lpp_border_width=o.border_width,r.u_lpp_emissive_strength=o.emissive_strength,V&&(r.u_lpp_dash=[V.tl[0],V.tl[1],V.br[0],V.br[1]]),r.u_lpp_zoom_fraction=t-E._floorZoom,I&&J!==s.tileID.overscaledZ&&0===(E.header[Co]&Ao)){const e=u.zoom;e in j||(j[e]=Math.max(.01,i.getPaintPropertyValue("line-width").expression.evaluate({zoom:e}))),r.u_lpp_floorwidth=j[e]*Math.pow(2,J-e)}}z&&ee(u.gradients[i.id],i.gradientVersion,i.stepInterpolant,i.getPaintPropertyValue("line-gradient").expression,"none"===i.paint.get("line-gradient-use-theme").constantOr("default"),m.TEXTURE1),F&&ee(u.borderGradients[i.id],i.borderGradientVersion,i.borderStepInterpolant,i.getPaintPropertyValue("line-border-gradient").expression,"none"===i.paint.get("line-border-gradient-use-theme").constantOr("default"),m.TEXTURE2),I?(f.activeTexture.set(m.TEXTURE0),s.lineAtlasTexture&&s.lineAtlasTexture.bind(m.LINEAR,m.REPEAT)):A||(f.activeTexture.set(m.TEXTURE0),e.emptyTexture.bind(m.LINEAR,m.CLAMP_TO_EDGE)),A&&T&&(f.activeTexture.set(m.TEXTURE0),s.imageAtlasTexture&&s.imageAtlasTexture.bind(m.LINEAR,m.CLAMP_TO_EDGE),T.updatePaintBuffers()),a&&!p&&e.terrain.setupElevationDraw(s,N),e.uploadCommonUniforms(f,N,h.toUnwrapped());const te=(t,s,o)=>{if(s&&0!==s.get().length){if(null!=U&&(U.value=M*c,E&&(Q.u_lpp_opacity=M*c)),void 0!==o&&(Q.u_opacity_multiplier=o),E){const{batchIndices:o,batchSegments:n}=u.getBatchGrouping(s);for(const s of o)E.bind(f,N.program,s),N.draw(e,m.TRIANGLES,r,t,x,A_.disabled,Q,i.id,u.layoutVertexBuffer,u.indexBuffer,n.get(s),i.paint,e.transform.zoom,T,[u.layoutVertexBuffer2,u.patternVertexBuffer,u.zOffsetVertexBuffer,u.elevationIdColVertexBuffer,u.elevationGroundScaleVertexBuffer],void 0,E.getUBO(s))}else N.draw(e,m.TRIANGLES,r,t,x,A_.disabled,Q,i.id,u.layoutVertexBuffer,u.indexBuffer,s,i.paint,e.transform.zoom,T,[u.layoutVertexBuffer2,u.patternVertexBuffer,u.zOffsetVertexBuffer,u.elevationIdColVertexBuffer,u.elevationGroundScaleVertexBuffer]);void 0!==o&&(Q.u_opacity_multiplier=1),null!=U&&(U.value=M,E&&(Q.u_lpp_opacity=M))}},ie=Il.drawLineFrcCoverageDetect?Il.drawLineFrcCoverageDetect(e,u,h,a,te,q):null,se=e=>{ie&&ie.active&&Il.drawLineFrcRenderLine?Il.drawLineFrcRenderLine(u,ie,e,te):te(e,u.segments)};if(O&&!a){const t=e.stencilModeForClipping(h).ref;0===t&&b&&f.clear({stencil:0});const i={func:m.EQUAL,mask:255};Q.u_alpha_discard_threshold=.8,se(new Pu(i,t,255,m.KEEP,m.KEEP,m.INVERT)),Q.u_alpha_discard_threshold=0,se(new Pu(i,t,255,m.KEEP,m.KEEP,m.KEEP))}else Q.u_alpha_discard_threshold=O&&a&&l?.8:0,se(a?n:e.stencilModeForClipping(h));ie&&Il.drawLineFrcFadePass&&Il.drawLineFrcFadePass(e,u,h,ie,a,n,te),void 0!==K&&(Y.value.value=K)}};let W=e.depthModeForSublayer(0,Cu.ReadOnly);const H=new Cu(e.depthOcclusion?m.GREATER:m.LEQUAL,Cu.ReadOnly,e.depthRangeFor3D);if(i.hasNonElevatedBuckets){const t=!b&&e.terrain;0!==c&&t?_(`Occlusion opacity for layer ${i.id} is supported on terrain only if the layer has line-z-offset enabled.`):t?_(`Cannot render non-elevated lines in immediate mode when terrain is enabled. Layer: ${i.id}.`):Z(s,N,W,Pu.disabled,!1,!0)}if(i.hasElevatedBuckets){"hd-road-markup"===h?p||(W=H,N.push("ELEVATED_ROADS")):(N.push("ELEVATED"),W=H,v&&N.push(y?"CROSS_SLOPE_HORIZONTAL":"CROSS_SLOPE_VERTICAL"),u&&N.push("ELEVATION_REFERENCE_SEA"));const t=O?e.stencilModeFor3D():Pu.disabled;"hd-road-markup"!==h&&(e.forceTerrainMode=!0),Z(s,N,W,t,!0,!0),O&&Z(s,N,W,t,!0,!1),"hd-road-markup"!==h&&(e.forceTerrainMode=!1)}Il.drawLineFrcCoverageSecondPass&&Il.drawLineFrcCoverageSecondPass(e,i,q),O&&(e.resetStencilClippingMasks(),b&&f.clear({stencil:0})),0===c||e.depthOcclusion||b||e.layersWithOcclusionOpacity.push(e.currentLayer)}class k_{destroy(){this.fbo&&(this.fbo.destroy(),this.fbo=null),this.drapeFbo&&(this.drapeFbo.destroy(),this.drapeFbo=null)}}class B_{constructor(e){this.pbo=e.createBuffer(),this.sync=null,this.fboA=null,this.fboB=null,this.maxDensity=0}destroy(e){this.sync&&(e.deleteSync(this.sync),this.sync=null),e.deleteBuffer(this.pbo),this.fboA&&(this.fboA.destroy(),this.fboA=null),this.fboB&&(this.fboB.destroy(),this.fboB=null)}}const N_={additive:{clearColor:new S(0,0,0,0),colorMode:zu.additiveAlphaWeighted,compositeUniformValue:1},multiply:{clearColor:new S(1,1,1,1),colorMode:zu.multiply,compositeUniformValue:0}};function U_(e){return!(!e.extRenderToTextureHalfFloat&&!e.extColorBufferFloat)}function V_(e,t){return"additive"===e&&U_(t)?zu.additiveAlphaWeightedUnboundedAlpha:N_[e].colorMode}function j_(e,t,i){const s=e.context,o=s.gl;let r=i.width,n=i.height,a=i.colorAttachment0.get();t.lineBlendDensityReadback||(t.lineBlendDensityReadback=new B_(o));const l=t.lineBlendDensityReadback;let c=0,h=!0;for(;r>1||n>1;){const i=Math.max(1,Math.floor(r/2)),d=Math.max(1,Math.floor(n/2)),u=0===c?"fboA":"fboB";l[u]=S_.createWithTexture(s,l[u],i,d,!1);const _=l[u];s.bindFramebuffer.set(_.framebuffer),s.viewport.set([0,0,i,d]),s.activeTexture.set(o.TEXTURE0),o.bindTexture(o.TEXTURE_2D,a),e.getOrCreateProgram("lineBlendReduce").draw(e,o.TRIANGLES,Cu.disabled,Pu.disabled,zu.unblended,A_.disabled,rd(0,[1/r,1/n],h),t.id,e.viewportBuffer,e.quadTriangleIndexBuffer,e.viewportSegments,t.paint,e.transform.zoom),r=i,n=d,a=_.colorAttachment0.get(),c=1-c,h=!1}const d=U_(s),u=d?16:4;l.sync&&(o.deleteSync(l.sync),l.sync=null),o.bindBuffer(o.PIXEL_PACK_BUFFER,l.pbo),o.bufferData(o.PIXEL_PACK_BUFFER,u,o.STREAM_READ),o.readPixels(0,0,1,1,o.RGBA,d?o.FLOAT:o.UNSIGNED_BYTE,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),l.sync=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0),s.viewport.set([0,0,e.width,e.height])}function G_(e,t,i){if(!U_(e.context))return;const s=t.lineBlendDensityReadback;s&&s.sync?(function(e,t,i){if(e.sync&&t.getSyncParameter(e.sync,t.SYNC_STATUS)===t.SIGNALED){if(t.deleteSync(e.sync),e.sync=null,t.bindBuffer(t.PIXEL_PACK_BUFFER,e.pbo),U_(i)){const i=new Float32Array(4);t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,i);const s=i[1];e.maxDensity=Math.max(2*(s>0?i[0]/s:0),1)}else e.maxDensity=1;t.bindBuffer(t.PIXEL_PACK_BUFFER,null)}}(s,e.context.gl,e.context),s.sync||(j_(e,t,i),e.style.map.triggerRepaint())):(j_(e,t,i),e.style.map.triggerRepaint())}function q_(e,t,i,s,o,r){const n=e.context,a=n.gl,l="additive"===i?1:t.paint.get("line-opacity").constantOr(1),c="additive"===i?function(e,t){const i=t.paint.get("line-blend-additive-clamp");if(i>0)return i;const s=t.lineBlendDensityReadback;return s&&0!==s.maxDensity?s.maxDensity:null}(0,t):1;if(null===c)return;n.bindFramebuffer.set(o),r&&n.viewport.set([0,0,r[0],r[1]]),n.activeTexture.set(a.TEXTURE0),a.bindTexture(a.TEXTURE_2D,s.colorAttachment0.get());const h=V_(i,e.context);e.getOrCreateProgram("lineBlendComposite").draw(e,a.TRIANGLES,Cu.disabled,Pu.disabled,h,A_.disabled,((e,t,i,s)=>({u_image:0,u_opacity:t,u_blend_mode:i,u_max_density:s}))(0,l,N_[i].compositeUniformValue,c),t.id,e.viewportBuffer,e.quadTriangleIndexBuffer,e.viewportSegments,t.paint,e.transform.zoom)}function Z_(e,t,i,s){const{painter:o,sourceCache:r,layer:n,coords:a,colorMode:l,elevationType:c,terrainEnabled:h,pass:d}=e,u=o.context.gl,_=n.paint.get("fill-pattern"),p=n.paint.get("fill-pattern-cross-fade"),f=_.constantOr(null);let m=c;"road"!==c||t&&!h||(m="none");const g="road"===m,v=e.painter.shadowRenderer,y=g&&!!v&&v.enabled,x=new Cu(o.context.gl.LEQUAL,Cu.ReadOnly,o.depthRangeFor3D);let b=[0,0,0];if(y){const e=o.style.directionalLight,t=o.style.ambientLight;e&&t&&(b=Gh(o.style,e,t))}const w=_&&_.constantOr(1),E=o.terrain&&o.terrain.renderingToTexture,I=(e,d)=>{let _,m,I,S,D;d?(_=w&&!n.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",I=u.LINES):(_=w?"fillPattern":"fill",I=u.TRIANGLES);const R=[];for(const C of a){const a=r.getTile(C);if(w&&!a.patternsLoaded())continue;const A=a.getBucket(n);if(!A)continue;const L=t?A.hdExt&&A.hdExt.elevationBufferData:A.bufferData;if(!L||L.isEmpty())continue;o.prepareDrawTile();const P=L.programConfigurations.get(n.id),M=o.isTileAffectedByFog(C),O=[],z=[];g&&(O.push("ELEVATED_ROADS"),z.push(L.elevatedLayoutVertexBuffer)),y&&O.push("RENDER_SHADOWS","NORMAL_OFFSET"),E&&i&&(O.push("USE_MRT1"),"mrt-full-rgba"===o.emissiveMode&&O.push("USE_MRT1_RGBA")),w&&(o.context.activeTexture.set(u.TEXTURE0),a.imageAtlasTexture&&a.imageAtlasTexture.bind(u.LINEAR,u.CLAMP_TO_EDGE),P.updatePaintBuffers());let F=!1;if(f&&a.imageAtlas){const e=a.imageAtlas,t=So.from(f),i=t.getPrimary().scaleSelf(T.devicePixelRatio).toString(),s=t.getSecondary(),o=e.patternPositions.get(i),r=s?e.patternPositions.get(s.scaleSelf(T.devicePixelRatio).toString()):null;F=!!o&&!!r,o&&P.setConstantPatternPositions(o,r)}p>0&&(F||P.getPatternTransitionVertexBuffer("fill-pattern"))&&O.push("FILL_PATTERN_TRANSITION");const k=o.getOrCreateProgram(_,{config:P,overrideFog:M,defines:O}),B=o.translatePosMatrix(C.projMatrix,a,n.paint.get("fill-translate"),n.paint.get("fill-translate-anchor"));y&&v.setupShadows(a.tileID.toUnwrapped(),k,"vector-tile");const N=n.paint.get("fill-emissive-strength");if(d){S=L.lineIndexBuffer,D=L.lineSegments;const e=o.terrain&&o.terrain.renderingToTexture?o.terrain.drapeBufferSize:[u.drawingBufferWidth,u.drawingBufferHeight];m="fillOutlinePattern"===_&&w?od(B,N,o,a,e,b,p):sd(B,N,e,b)}else S=L.indexBuffer,D=L.triangleSegments,m=w?id(B,N,o,a,b,p):td(B,N,b);o.uploadCommonUniforms(o.context,k,C.toUnwrapped());let U=e;if(("road"===c&&!h||"offset"===c)&&(U=x),!D||D.get&&0===D.get().length)continue;const V=s||o.stencilModeForClipping(C);let j="fallthrough";!d&&Il.drawFillFrcCoverageFirstPass&&(j=Il.drawFillFrcCoverageFirstPass({painter:o,layer:n,bucket:A,coord:C,elevatedGeometry:t,program:k,programConfiguration:P,uniformValues:m,drawMode:I,depthMode:U,stencilMode:V,colorMode:l,bufferData:L,indexBuffer:S,segments:D,dynamicBuffers:z,polygonCoverageTiles:R})),"fallthrough"===j&&k.draw(o,I,U,V,l,A_.disabled,m,n.id,L.layoutVertexBuffer,S,D,n.paint,o.transform.zoom,P,z)}!d&&Il.drawFillFrcCoverageSecondPass&&Il.drawFillFrcCoverageSecondPass(o,n,R,I,l)};o.renderPass===d&&I(o.depthModeForSublayer(1,"opaque"===o.renderPass?Cu.ReadWrite:Cu.ReadOnly),!1),"none"===m&&"translucent"===o.renderPass&&n.paint.get("fill-antialias")&&I(o.depthModeForSublayer(n.getPaintProperty("fill-outline-color")?2:0,Cu.ReadOnly),!0)}function W_(e,t,i,s,o,r,n,a){i.resetLayerRenderingStats(e);const l=e.context,c=l.gl,h=e.transform,d=i.paint.get("fill-extrusion-pattern"),u=i.paint.get("fill-extrusion-pattern-cross-fade"),_=d.constantOr(null),p=d.constantOr(1),f=i.paint.get("fill-extrusion-opacity"),m=e.style.enable3dLights(),g=i.paint.get(m&&!p?"fill-extrusion-ambient-occlusion-wall-radius":"fill-extrusion-ambient-occlusion-radius"),v=[i.paint.get("fill-extrusion-ambient-occlusion-intensity"),g],y=i.layout.get("fill-extrusion-edge-radius"),x=y>0&&!i.paint.get("fill-extrusion-rounded-roof"),b=x?0:y,w="globe"===h.projection.name?No():0,E="globe"===h.projection.name,I=E?K(h.zoom):0,S=[Ae(h.center.lng),Pe(h.center.lat)],D="none"===i.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default"),R=i.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(D?null:i.lut).toArray01().slice(0,3),C=i.paint.get("fill-extrusion-flood-light-intensity"),A=i.paint.get("fill-extrusion-vertical-scale"),L=0!==i.paint.get("fill-extrusion-line-width").constantOr(1),P=i.paint.get("fill-extrusion-height-alignment"),M=i.paint.get("fill-extrusion-base-alignment"),O=Iu(e,i.paint.get("fill-extrusion-cutoff-fade-range")),z=i.paint.get("fill-extrusion-front-cutoff"),F=$_(h.pitch,z,!!e.terrain),k=F[2]<1;k&&(e.maxFrontCutoffRawStart=Math.max(e.maxFrontCutoffRawStart,z[0]));const B=[];let N;E&&B.push("PROJECTION_GLOBE_VIEW"),v[0]>0&&B.push("FAUX_AO"),x&&B.push("ZERO_ROOF_RADIUS"),a&&B.push("HAS_CENTROID"),C>0&&B.push("FLOOD_LIGHT"),O.shouldRenderCutoff&&B.push("RENDER_CUTOFF"),k&&B.push("RENDER_FRONT_CUTOFF"),L&&B.push("RENDER_WALL_MODE");const U="shadow"===e.renderPass,V=e.shadowRenderer,j=U&&!!V,G=U?A_.disabled:A_.backCCW;e.shadowRenderer&&(e.shadowRenderer.useNormalOffset=!0);let q=[0,0,0];if(V){const t=e.style.directionalLight,i=e.style.ambientLight;t&&i&&(q=Gh(e.style,t,i)),U||(B.push("RENDER_SHADOWS"),V.useNormalOffset&&B.push("NORMAL_OFFSET")),N=B.concat(["SHADOWS_SINGLE_CASCADE"])}const Z=j?"fillExtrusionDepth":p?"fillExtrusionPattern":"fillExtrusion",W=i.getLayerRenderingStats();for(const d of s){const s=t.getTile(d),m=s.getBucket(i);if(!m||m.projection.name!==h.projection.name)continue;let g=!1;V&&(g=0===V.getMaxCascadeForTile(d.toUnwrapped()));const y=e.isTileAffectedByFog(d),x=m.programConfigurations.get(i.id);let D=!1;if(_&&s.imageAtlas){const e=s.imageAtlas,t=So.from(_),i=t.getPrimary().scaleSelf(T.devicePixelRatio).toString(),o=t.getSecondary(),r=e.patternPositions.get(i),n=o?e.patternPositions.get(o.scaleSelf(T.devicePixelRatio).toString()):null;D=!!r&&!!n,r&&x.setConstantPatternPositions(r,n)}u>0&&(D||x.getPatternTransitionVertexBuffer("fill-extrusion-pattern"))&&B.push("FILL_EXTRUSION_PATTERN_TRANSITION");const z=e.getOrCreateProgram(Z,{config:x,defines:g?N:B,overrideFog:y});if(e.terrain&&e.terrain.setupElevationDraw(s,z,{useMeterToDem:!0}),!m.centroidVertexBuffer){const e=z.getAttributeLocation(c,"a_centroid_pos");-1!==e&&c.vertexAttribI4ui(e,0,0,0,0)}!U&&V&&V.setupShadows(s.tileID.toUnwrapped(),z,"vector-tile"),p&&(e.context.activeTexture.set(c.TEXTURE0),s.imageAtlasTexture&&s.imageAtlasTexture.bind(c.LINEAR,c.CLAMP_TO_EDGE),x.updatePaintBuffers());const k=i.paint.get("fill-extrusion-vertical-gradient"),j=1/m.tileToMeter;let H;if(U&&V){if(Q_(s.tileID,m.maxHeight,e))continue;const t=V.calculateShadowPassMatrixFromTile(s.tileID.toUnwrapped());H=Qh(t,b,j,A,P,M)}else{const t=e.translatePosMatrix(d.expandedProjMatrix,s,i.paint.get("fill-extrusion-translate"),i.paint.get("fill-extrusion-translate-anchor")),o=h.projection.createInversionMatrix(h,d.canonical),r=z.fixedDefines.includes("LIGHTING_3D_MODE");H=p?ed(t,e,k,f,v,b,j,d,s,w,P,M,I,S,o,R,A,u,r):Jh(t,e,k,f,v,b,j,d,w,P,M,I,S,o,R,A,C,q,F,r)}e.uploadCommonUniforms(l,z,d.toUnwrapped(),null,O);let $=m.segments;if("mercator"===h.projection.name&&!U&&($=m.getVisibleSegments(s.tileID,e.terrain,e.transform.getFrustum(0)),!$.get().length))continue;if(W)if(U)for(const e of $.get())W.numRenderedVerticesInShadowPass+=e.primitiveLength;else for(const e of $.get())W.numRenderedVerticesInTransparentPass+=e.primitiveLength;const X=[];(e.terrain||a)&&X.push(m.centroidVertexBuffer),E&&X.push(m.layoutVertexExtBuffer),L&&X.push(m.wallVertexBuffer),z.draw(e,l.gl.TRIANGLES,o,r,n,G,H,i.id,m.layoutVertexBuffer,m.indexBuffer,$,i.paint,e.transform.zoom,x,X)}e.shadowRenderer&&(e.shadowRenderer.useNormalOffset=!1)}class H_{constructor(){this.translate=[0,0],this.translateAnchor="map",this.edgeRadius=0,this.cutoffFadeRange=0}}function $_(e,t,i){if(!(t[2]<1)||i)return[0,0,1];const s=180*e/Math.PI;if(s<15)return[-.5,t[1],t[2]];const o=Math.min(1,Math.max(0,(s-15)/5)),r=o*o*(3-2*o);return[-.5*(1-r)+t[0]*r,t[1],t[2]]}function X_(e,t,i,s,o,r,n){0===s.centroidVertexArray.length&&s.createCentroidsBuffer();const a=r?r.findDEMTileFor(i):null;if(!(a&&a.dem||n))return;r&&a&&a.dem&&s.selfDEMTileTimestamp!==a.dem._timestamp&&(s.borderDoneWithNeighborZ=[-1,-1,-1,-1],s.selfDEMTileTimestamp=a.dem._timestamp);const l=(e,t)=>{(e.flags|t.flags)&zo?(e.flags|=zo,t.flags|=zo):(e.flags&=~zo,t.flags&=~zo)},c=e=>new m(Math.ceil((e+Fo)*ko),0),h=(e,t,i)=>{const s=Math.ceil((e+Fo)*ko),o=Math.floor(Math.max(0,Math.min(ae-1,i))/4);return new m(s,o<<5|(3&t)<<3|7)},d=(e,t)=>{const i=Number.MAX_VALUE,s=t[0][0]!==i,o=t[1][0]!==i,r=t[2][0]!==i,n=t[3][0]!==i;if(!((s?1:0)+(o?1:0)+(r?1:0)+(n?1:0)>2))return e<2?r===n?void 0:r?0:ae-1:s===o?void 0:s?0:ae-1},u=(e,t,i,s)=>(t?d(e,t):void 0)??(s?d(i,s):void 0),_=e=>{const i=t.getSource().minzoom,s=e=>{const i=t.getTileByID(e);if(i&&i.hasData())return i.getBucket(o)},r=[0,-1,1];for(const t of r){if(e.overscaledZ+t<i)continue;const o=s(e.calculateScaledKey(e.overscaledZ+t));if(o)return o}},p=[0,0,0],f=(e,t)=>(p[0]=Math.min(e.min.y,t.min.y),p[1]=Math.max(e.max.y,t.max.y),p[2]=ae-t.min.x>e.max.x?t.min.x-ae:e.max.x,p),g=(e,t)=>(p[0]=Math.min(e.min.x,t.min.x),p[1]=Math.max(e.max.x,t.max.x),p[2]=ae-t.min.y>e.max.y?t.min.y-ae:e.max.y,p),v=[(e,t)=>f(e,t),(e,t)=>f(t,e),(e,t)=>g(e,t),(e,t)=>g(t,e)],y=(e,t,s,o,n,l,c)=>{if(!r)return 0;const h=[[l?s:e,l?e:s,0],[l?s:t,l?t:s,0]],d=c<0?ae+c:c,u=[l?d:(e+t)/2,l?(e+t)/2:d,0];return 0===s&&c<0||0!==s&&c>0?r.getForTilePoints(n,[u],!0,o):h.push(u),r.getForTilePoints(i,h,!0,a),Math.max(h[0][2],h[1][2],u[2])/r.exaggeration()};for(let e=0;e<4;e++){const t=s.borderFeatureIndices[e];if(0===t.length)continue;const o=Mo[e](i),a=_(o);if(!(a&&a instanceof Oo))continue;const d=r?r.findDEMTileFor(o):null;if(!(d&&d.dem||n))continue;if(r&&d&&d.dem&&s.borderDEMTileTimestamp[e]!==d.dem._timestamp&&(s.borderDoneWithNeighborZ[e]=-1,s.borderDEMTileTimestamp[e]=d.dem._timestamp),s.borderDoneWithNeighborZ[e]===a.canonical.z)continue;0===a.centroidVertexArray.length&&a.createCentroidsBuffer();const p=(e<2?1:5)-e,f=a.borderDoneWithNeighborZ[p]!==s.canonical.z,g=a.borderFeatureIndices[p];let x=0;if(s.canonical.z!==a.canonical.z){for(const e of t)s.showCentroid(s.featuresOnBorder[e],"discard");if(f)for(const e of g)a.showCentroid(a.featuresOnBorder[e],"discard");s.borderDoneWithNeighborZ[e]=a.canonical.z,a.borderDoneWithNeighborZ[p]=s.canonical.z;continue}const b=new Map,w=new Set,T=new Set;for(let e=0;e<g.length;e++){const t=a.featuresOnBorder[g[e]];void 0!==t.buildingId&&b.set(t.buildingId,e)}for(const i of t){const t=s.featuresOnBorder[i],c=s.centroidData.get(t.centroidDataIndex);if(void 0===t.buildingId)continue;const _=b.get(t.buildingId);if(void 0===_)continue;const f=a.featuresOnBorder[g[_]],m=a.centroidData.get(f.centroidDataIndex);w.add(i),T.add(_),n&&l(c,m);const x=0!==c.groupCentroidPos.x||0!==c.groupCentroidPos.y?c.groupCentroidPos:t.centroid(),E=0!==m.groupCentroidPos.x||0!==m.groupCentroidPos.y?m.groupCentroidPos:f.centroid(),I=r?void 0:u(e,t.borders,p,f.borders),S=void 0!==I?I:e<2?Math.round((x.y+E.y)/2):Math.round((x.x+E.x)/2),D=t.intersectsCount()>1||f.intersectsCount()>1;{let t=0;if(d&&d.dem&&!D){const i=v[e](c,m),s=e%2?ae-1:0;t=y(i[0],Math.min(ae-1,i[1]),s,d,o,e<2,i[2])}c.centroidXY=h(t,e,S),m.centroidXY=h(t,p,S)}s.writeCentroidToBuffer(c),a.writeCentroidToBuffer(m),s.setBuildingCentroid(t.buildingId,c.centroidXY),a.setBuildingCentroid(t.buildingId,m.centroidXY)}for(const i of t){if(w.has(i))continue;const t=s.featuresOnBorder[i],_=s.centroidData.get(t.centroidDataIndex),f=t.borders[e];let b;for(;x<g.length;){if(T.has(x)){x++;continue}b=a.featuresOnBorder[g[x]];const e=b.borders[p];if(e[1]>f[0]+3||e[0]>f[0]-3)break;a.showCentroid(b,"keep"),x++}if(b&&x<g.length){let i=x,w=0;for(;;)if(T.has(x)){if(++x===g.length)break;b=a.featuresOnBorder[g[x]]}else{if(b.borders[p][0]>f[1]-3)break;if(w++,++x===g.length)break;b=a.featuresOnBorder[g[x]]}for(;i<g.length&&T.has(i);)i++;if(i>=g.length){s.showCentroid(t,"keep");continue}b=a.featuresOnBorder[g[i]];let E=!1;if(w>=1){const e=b.borders[p];Math.abs(f[0]-e[0])<3&&Math.abs(f[1]-e[1])<3&&(w=1,E=!0,x=i+1)}else if(0===w){s.showCentroid(t,"keep");continue}const I=a.centroidData.get(b.centroidDataIndex);n&&E&&l(_,I);const S=t.intersectsCount()>1||b.intersectsCount()>1;if(w>1)x=i,_.centroidXY=I.centroidXY=new m(0,0);else if(d&&d.dem&&!S){const t=v[e](_,I),i=e%2?ae-1:0,s=y(t[0],Math.min(ae-1,t[1]),i,d,o,e<2,t[2]);_.centroidXY=I.centroidXY=c(s)}else if(S){const i=r?void 0:u(e,t.borders,p,b.borders);void 0!==i?(_.centroidXY=h(0,e,i),I.centroidXY=h(0,p,i)):_.centroidXY=I.centroidXY=new m(0,0)}else _.centroidXY=s.encodeBorderCentroid(t),I.centroidXY=a.encodeBorderCentroid(b);s.writeCentroidToBuffer(_),a.writeCentroidToBuffer(I)}else s.showCentroid(t,"keep")}s.borderDoneWithNeighborZ[e]=a.canonical.z,a.borderDoneWithNeighborZ[p]=s.canonical.z}(s.needsCentroidUpdate||!s.centroidVertexBuffer&&0!==s.centroidVertexArray.length)&&s.uploadCentroid(e)}const Y_=[1,0,0],K_=[0,1,0],J_=[0,0,1];function Q_(e,t,i){const s=i.transform,o=i.shadowRenderer;if(!o)return!0;const r=i.frameCounter,n=i.currentShadowCascade;let a=i._shadowCullCache;if(!a||a.frame!==r||a.cascade!==n){const e=s.tileSize*o._cascades[n].scale,t=s.scaleZoom(e),l=o.shadowDirection,c=[l[0],l[1],-l[2]],h=[Y_,K_,J_,c,[c[0],0,c[2]],[0,c[1],c[2]]];a={frame:r,cascade:n,cameraFrustum:so.fromInvProjectionMatrix(s.invProjMatrix,s.worldSize,t,!("globe"===s.projection.name)),edges:h,shadowDir:c,ws:e,zoom:t},i._shadowCullCache=a}const{cameraFrustum:l,edges:c,shadowDir:h,ws:d,zoom:u}=a;let _=t;if(s.elevation){const t=s.elevation.getMinMaxForTile(e);t&&(_+=t.max)}_/=Bo(s.center.lat,u);const p=o.computeSimplifiedTileShadowVolume(e.toUnwrapped(),_,d,h);if(!p)return!1;const{vertices:f,planes:m}=p;return 0===l.intersectsPrecise(f,m,c)||0===o.getCurrentCascadeFrustum().intersectsPrecise(f,m,c)}function ep(e,t,i,s,o,r,n){const a=e.context,l=a.gl,c=i.hillshadeFBO;if(!c)return;e.prepareDrawTile();const h=e.isTileAffectedByFog(t),d=[];e.terrain&&e.terrain.renderingToTexture&&e.isEmissiveMrtActive()&&(d.push("USE_MRT1"),"mrt-full-rgba"===e.emissiveMode&&d.push("USE_MRT1_RGBA"));const u=e.getOrCreateProgram("hillshade",{overrideFog:h,defines:d});a.activeTexture.set(l.TEXTURE0),l.bindTexture(l.TEXTURE_2D,c.colorAttachment0.get());const _=((e,t,i,s)=>{const o=i.paint.get("hillshade-shadow-color"),r="none"===i.paint.get("hillshade-shadow-color-use-theme").constantOr("default"),n=i.paint.get("hillshade-highlight-color"),a="none"===i.paint.get("hillshade-highlight-color-use-theme").constantOr("default"),l=i.paint.get("hillshade-accent-color"),c="none"===i.paint.get("hillshade-accent-color-use-theme").constantOr("default"),h=i.paint.get("hillshade-emissive-strength");let d=le(i.paint.get("hillshade-illumination-direction"));if("viewport"===i.paint.get("hillshade-illumination-anchor"))d-=e.transform.angle;else if(e.style&&e.style.enable3dLights()&&e.style.directionalLight){const t=e.style.directionalLight.properties.get("direction"),i=Ii(t.x,t.y,t.z);d=le(i[1])}const u=!e.options.moving;return{u_matrix:s||e.transform.calculateProjMatrix(t.tileID.toUnwrapped(),u),u_image:0,u_latrange:_d(0,t.tileID),u_light:[i.paint.get("hillshade-exaggeration"),d],u_shadow:o.toPremultipliedRenderColor(r?null:i.lut),u_highlight:n.toPremultipliedRenderColor(a?null:i.lut),u_emissive_strength:h,u_accent:l.toPremultipliedRenderColor(c?null:i.lut)}})(e,i,s,e.terrain?t.projMatrix:null);e.uploadCommonUniforms(a,u,t.toUnwrapped());const{tileBoundsBuffer:p,tileBoundsIndexBuffer:f,tileBoundsSegments:m}=e.getTileBoundsBuffers(i);u.draw(e,l.TRIANGLES,o,r,n,A_.disabled,_,s.id,p,f,m)}function tp(e,t,i){if(!t.needsDEMTextureUpload)return;const s=e.context,o=s.gl;s.pixelStoreUnpackPremultiplyAlpha.set(!1),t.demTexture=t.demTexture||e.getTileTexture(i.stride);const r=i.getPixels();t.demTexture?t.demTexture.update(r,{premultiply:!1}):t.demTexture=new k(s,r,o.R32F,{premultiply:!1}),t.needsDEMTextureUpload=!1}function ip(e,t,i){const s=e.context,o=s.gl;if(!t.dem)return;const r=t.dem;if(s.activeTexture.set(o.TEXTURE1),tp(e,t,r),!t.demTexture)return;t.demTexture.bind(o.NEAREST,o.CLAMP_TO_EDGE);const n=r.dim;s.activeTexture.set(o.TEXTURE0);let a=t.hillshadeFBO;if(!a){const e=new k(s,{width:n,height:n,data:null},o.RGBA8);e.bind(o.LINEAR,o.CLAMP_TO_EDGE),a=t.hillshadeFBO=s.createFramebuffer(n,n,1,"renderbuffer"),a.colorAttachment0.set(e.texture)}s.bindFramebuffer.set(a.framebuffer),s.viewport.set([0,0,n,n]);const{tileBoundsBuffer:l,tileBoundsIndexBuffer:c,tileBoundsSegments:h}=e.getMercatorTileBoundsBuffers(),d=[];e.linearFloatFilteringSupported()&&d.push("TERRAIN_DEM_FLOAT_FORMAT"),e.terrain&&e.terrain.renderingToTexture&&e.isEmissiveMrtActive()&&(d.push("USE_MRT1"),"mrt-full-rgba"===e.emissiveMode&&d.push("USE_MRT1_RGBA")),e.getOrCreateProgram("hillshadePrepare",{defines:d}).draw(e,o.TRIANGLES,Cu.disabled,Pu.disabled,zu.unblended,A_.disabled,((e,t)=>{const i=t.stride,s=Bt();return ki(s,0,ae,-ae,0,0,1),At(s,s,[0,-ae,0]),{u_matrix:s,u_image:1,u_dimension:[i,i],u_zoom:e.overscaledZ}})(t.tileID,r),i.id,l,c,h),t.needsHillshadePrepare=!1}function sp(e,t,i,s,o){if(o>0){const r=T.now(),n=(r-e.timeAdded)/o,a=t?(r-t.timeAdded)/o:-1,l=i.getSource(),c=s.coveringZoomLevel({tileSize:l.tileSize,roundZoom:l.roundZoom}),h=!t||Math.abs(t.tileID.overscaledZ-c)>Math.abs(e.tileID.overscaledZ-c),d=h&&e.refreshedUponExpiration?1:Ee(h?n:1-a,0,1);return t?{opacity:1,mix:1-d,isFading:n<1}:{opacity:d,mix:0,isFading:n<1}}return{opacity:1,mix:0,isFading:!1}}function op(e){return[e[0]*Wo,e[1]*Wo,e[2]*Wo,0]}function rp(e,t,i,s,o,r,n,a,l,c){const h=o.getSource(),d=s.globeSharedBuffers;if(!d)return;let u,_,p;if(i&&(u=o.getTile(i)),h instanceof Hl?(_=h.texture,p=Uo(0,0,s.transform)):u&&i&&(_=u.texture,p=Uo(i.canonical.z,i.canonical.x,s.transform)),!_||!p)return;t||(p=Ys(Bt(),p,[1,-1,1]));const f=s.context,m=f.gl,g="nearest"===r.paint.get("raster-resampling")?m.NEAREST:m.LINEAR,v=s.colorModeForDrapableLayerRenderPass(n),y=a.defines;y.push("GLOBE_POLES");const x=new Cu(m.LEQUAL,Cu.ReadWrite,s.depthRangeFor3D),b=s.transform.expandedFarZProjMatrix,w=Float32Array.from(wt(Vo(new $e(0,0,0))));s.terrain&&s.terrain.prepareDrawTile(),f.activeTexture.set(m.TEXTURE0),_.bind(g,m.CLAMP_TO_EDGE),f.activeTexture.set(m.TEXTURE1),_.bind(g,m.CLAMP_TO_EDGE),"useMipmap"in _&&f.extTextureFilterAnisotropic&&s.transform.pitch>20&&m.texParameterf(m.TEXTURE_2D,f.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,f.extTextureFilterAnisotropicMax);const[T,E,I,S]=i?d.getPoleBuffers(i.canonical.z,!1):d.getPoleBuffers(0,!0),D=e;let R;t?(R=T,s.renderDefaultNorthPole=0!==D):(R=E,s.renderDefaultSouthPole=0!==D);const C=op(a.mix),A=((e,t,i,s,o,r,n,a,l,c,h,d,u,_)=>gd(e,t,i,s,new Float32Array(16),new Float32Array(9),[0,0],o,[0,0],[0,0,0,0],1,{opacity:1,mix:0},n,[0,0]||[0,0],l,2,h,d,u,1,0,_))(s,b,w,p,K(s.transform.zoom),0,r,0,D,0,C,a.offset,a.range,n),L=s.getOrCreateProgram("raster",{defines:y});s.uploadCommonUniforms(f,L,null),L.draw(s,m.TRIANGLES,x,c,v,l,A,r.id,R,I,S)}function np(e){if(e.isOrthographic)return[0,0,0,0];const t=e._nearZ,i=e.projection.farthestPixelDistance(e),s=i-t,o=.2*e.height,r=t+o;return[t,i,(r-o-t)/s,(r-t)/s]}function ap(e,t,i,s){if(e)return"raster-array"===t.type?t.getTextureDescriptor(e,i,!0):{texture:e.texture,mix:op(s.mix),offset:s.offset,buffer:0,tileSize:1}}const lp=ci(new Float32Array(16)),cp={"dual-source-blending":"dual-source-blending","mrt-fallback":"mrt","mrt-full-rgba":"mrt-rgba"},hp=qe([{name:"a_pos_3f",components:3,type:"Float32"}]),{members:dp}=hp;function up(e,t,i,s){e.emplaceBack(t,i,s)}class _p{constructor(e){this.vertexArray=new $o,this.indices=new Ke,up(this.vertexArray,-1,-1,1),up(this.vertexArray,1,-1,1),up(this.vertexArray,-1,1,1),up(this.vertexArray,1,1,1),up(this.vertexArray,-1,-1,-1),up(this.vertexArray,1,-1,-1),up(this.vertexArray,-1,1,-1),up(this.vertexArray,1,1,-1),this.indices.emplaceBack(5,1,3),this.indices.emplaceBack(3,7,5),this.indices.emplaceBack(6,2,0),this.indices.emplaceBack(0,4,6),this.indices.emplaceBack(2,6,7),this.indices.emplaceBack(7,3,2),this.indices.emplaceBack(5,4,0),this.indices.emplaceBack(0,1,5),this.indices.emplaceBack(0,2,3),this.indices.emplaceBack(3,1,0),this.indices.emplaceBack(7,6,4),this.indices.emplaceBack(4,5,7),this.vertexBuffer=e.createVertexBuffer(this.vertexArray,dp),this.indexBuffer=e.createIndexBuffer(this.indices),this.segment=Ye.simpleSegment(0,0,36,12)}}function pp(e,t,i,s,o,r){const n=e.context.gl,a=t.paint.get("sky-atmosphere-color"),l=t.paint.get("sky-atmosphere-halo-color"),c=t.paint.get("sky-atmosphere-sun-intensity"),h=((e,t,i,s,o)=>({u_matrix_3f:e,u_sun_direction:t,u_sun_intensity:i,u_color_tint_r:[s.r,s.g,s.b,s.a],u_color_tint_m:[o.r,o.g,o.b,o.a],u_luminance:5e-5}))(Ko(Mi(),s),o,c,a.toPremultipliedRenderColor(null),l.toPremultipliedRenderColor(null));n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_CUBE_MAP_POSITIVE_X+r,t.skyboxTexture,0),i.draw(e,n.TRIANGLES,Cu.disabled,Pu.disabled,zu.unblended,A_.frontCW,h,"skyboxCapture",t.skyboxGeometry.vertexBuffer,t.skyboxGeometry.indexBuffer,t.skyboxGeometry.segment)}const fp=qe([{type:"Float32",name:"a_pos",components:3},{type:"Float32",name:"a_uv",components:2}]);class mp{constructor(e){const t=new Jo;t.emplaceBack(-1,1,1,0,0),t.emplaceBack(1,1,1,1,0),t.emplaceBack(1,-1,1,1,1),t.emplaceBack(-1,-1,1,0,1);const i=new Ke;i.emplaceBack(0,1,2),i.emplaceBack(2,3,0),this.vertexBuffer=e.createVertexBuffer(t,fp.members),this.indexBuffer=e.createIndexBuffer(i),this.segments=Ye.simpleSegment(0,0,4,2)}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy()}}const gp=qe([{type:"Float32",name:"a_pos_3f",components:3},{type:"Float32",name:"a_uv",components:2},{type:"Float32",name:"a_size_scale",components:1},{type:"Float32",name:"a_opacity",components:1}]);class vp{constructor(){this.colorModeAlphaBlendedWriteRGB=new zu([1,Ou,1,Ou],S.transparent,[!0,!0,!0,!1]),this.colorModeWriteAlpha=new zu(zu.Replace,S.transparent,[!1,!1,!1,!0]),this.params={starsCount:16e3,sizeMultiplier:.15,sizeRange:100,intensityRange:200},this.updateNeeded=!0,this._painter=null,this._devtoolsFolder=null}update(e){this._painter=e;const t=e.context;if(!this.atmosphereBuffer||this.updateNeeded){this.updateNeeded=!1,this.atmosphereBuffer=new mp(t);let e=this.params;const i=e.sizeRange,s=e.intensityRange,o=function(e){const t=or(30),i=[];for(let s=0;s<e;++s){const e=2*Math.PI*t(),s=Math.acos(1-2*t())-.5*Math.PI;i.push(bi(Math.cos(s)*Math.cos(e),Math.cos(s)*Math.sin(e),Math.sin(s)))}return i}(e.starsCount),r=or(300),n=new Qo,a=new Ke;let l=0;for(let e=0;e<o.length;++e){const t=Ti([],o[e],200),c=Math.max(0,1+.01*i*(1*r()-.5)),h=Math.max(0,1+.01*s*(1*r()-.5));n.emplaceBack(t[0],t[1],t[2],-1,-1,c,h),n.emplaceBack(t[0],t[1],t[2],1,-1,c,h),n.emplaceBack(t[0],t[1],t[2],1,1,c,h),n.emplaceBack(t[0],t[1],t[2],-1,1,c,h),a.emplaceBack(l+0,l+1,l+2),a.emplaceBack(l+0,l+2,l+3),l+=4}this.starsVx=t.createVertexBuffer(n,gp.members),this.starsIdx=t.createIndexBuffer(a),this.starsSegments=Ye.simpleSegment(0,0,n.length,a.length)}}destroy(){this.atmosphereBuffer&&this.atmosphereBuffer.destroy(),this.starsVx&&this.starsVx.destroy(),this.starsIdx&&this.starsIdx.destroy(),this._painter=null}drawAtmosphereGlow(e,t){const i=e.context,s=i.gl,o=e.transform,r=new Cu(s.LEQUAL,Cu.ReadOnly,[0,1]),n=K(o.zoom),a=e.style.getLut(t.scope),l="none"===t.properties.get("color-use-theme"),c=t.properties.get("color").toNonPremultipliedRenderColor(l?null:a),h="none"===t.properties.get("high-color-use-theme"),d=t.properties.get("high-color").toNonPremultipliedRenderColor(h?null:a),u="none"===t.properties.get("space-color-use-theme"),_=t.properties.get("space-color").toNonPremultipliedRenderColor(u?null:a),p=5e-4,f=er(t.properties.get("horizon-blend"),0,1,p,.25),m=tr(e,i,o)&&f===p?o.worldSize/(2*Math.PI*1.025)-1:o.globeRadius,g=e.frameCounter/1e3%1,v=_s(o.globeCenterInViewSpace),y=Math.sqrt(Math.pow(v,2)-Math.pow(m,2)),x=Math.acos(y/v),b=t=>{const a="globe"===o.projection.name?["PROJECTION_GLOBE_VIEW","FOG"]:["FOG"];t&&a.push("ALPHA_PASS");const l=e.getOrCreateProgram("globeAtmosphere",{defines:a}),h=((e,t,i,s,o,r,n,a,l,c,h,d)=>({u_frustum_tl:e,u_frustum_tr:t,u_frustum_br:i,u_frustum_bl:s,u_horizon:o,u_transition:r,u_fadeout_range:n,u_atmosphere_fog_color:a.toArray01(),u_high_color:l.toArray01(),u_space_color:c.toArray01(),u_temporal_offset:h,u_horizon_angle:d}))(o.frustumCorners.TL,o.frustumCorners.TR,o.frustumCorners.BR,o.frustumCorners.BL,o.frustumCorners.horizon,n,f,c,d,_,g,x);e.uploadCommonUniforms(i,l);const u=this.atmosphereBuffer;u&&l.draw(e,s.TRIANGLES,r,Pu.disabled,t?this.colorModeWriteAlpha:this.colorModeAlphaBlendedWriteRGB,A_.backCW,h,t?"atmosphere_glow_alpha":"atmosphere_glow",u.vertexBuffer,u.indexBuffer,u.segments)};b(!1),b(!0)}drawStars(e,t){const i=Ee(t.properties.get("star-intensity"),0,1);if(0===i)return;const s=e.context,o=s.gl,r=e.transform,n=e.getOrCreateProgram("stars"),a=fs([]);gs(a,a,-r._pitch),ms(a,a,-r.angle),gs(a,a,le(r._center.lat)),ir(a,a,-le(r._center.lng));const l=ys(new Float32Array(16),a),c=Ie([],r.starsProjMatrix,l),h=Ko([],l),d=sr([],h);let u=this.params.sizeMultiplier;const _=[0,1,0];Qe(_,_,d),Ti(_,_,u);const p=[1,0,0];Qe(p,p,d),Ti(p,p,u);const f=(m=_,g=p,v=i,{u_matrix:Float32Array.from(c),u_up:m,u_right:g,u_intensity_multiplier:v});var m,g,v;e.uploadCommonUniforms(s,n),this.starsVx&&this.starsIdx&&n.draw(e,o.TRIANGLES,Cu.disabled,Pu.disabled,this.colorModeAlphaBlendedWriteRGB,A_.disabled,f,"atmosphere_stars",this.starsVx,this.starsIdx,this.starsSegments)}}let yp=null;const xp=[];function bp(e){yp=e;for(const e of xp.splice(0))e()}function wp(e,t){return yp?yp.create(e,t):null}class Tp{}class Ep{constructor(){this._storage=new Map}getLinesFromTrianglesBuffer(e,t,i){{const i=this._storage.get(t.id);if(i)return i.lastUsedFrameIdx=e,i.buf}const s=i.gl,o=s.getBufferParameter(s.ELEMENT_ARRAY_BUFFER,s.BUFFER_SIZE),r=new ArrayBuffer(o),n=new Int16Array(r);s.getBufferSubData(s.ELEMENT_ARRAY_BUFFER,0,new Int16Array(r));const a=new rr;for(let e=0;e<o/2;e+=3){const t=n[e],i=n[e+1],s=n[e+2];a.emplaceBack(t,i),a.emplaceBack(i,s),a.emplaceBack(s,t)}const l=i.bindVertexArrayOES.current,c=new Tp;return c.buf=new Uu(i,a),c.lastUsedFrameIdx=e,this._storage.set(t.id,c),i.bindVertexArrayOES.set(l),c.buf}update(e){for(const[t,i]of this._storage)e-i.lastUsedFrameIdx>30&&(i.buf.destroy(),this._storage.delete(t))}destroy(){for(const[e,t]of this._storage)t.buf.destroy(),this._storage.delete(e)}}class Ip{constructor(){this.occluderSize=30,this.depthOffset=-1e-4}}const Sp={symbol:function(e,t,i,s,o){if("translucent"!==e.renderPass)return;const r=Pu.disabled,n=e.colorModeForRenderPass(),a=i.layout.get("text-variable-anchor"),l=i.layout.get("text-size-scale-range"),c=Ee(e.scaleFactor,l[0],l[1]);a&&function(e,t,i,s,o,r,n,a){const l=t.transform,c="map"===o,h="map"===r;for(const t of e){const e=s.getTile(t),o=e.getBucket(i);if(!o||!o.text||!o.text.segments.get().length)continue;const r=jt(o.textSizeData,l.zoom,a),d=bo(t,o.getProjection(),l),u=l.calculatePixelsToTileUnitsMatrix(e),_=Uc(d,e.tileID.canonical,h,c,l,o.getProjection(),u),p=o.hasIconTextFit()&&o.hasIconData();r&&M_(o,c,h,n,l,_,t,Math.pow(2,l.zoom-e.tileID.overscaledZ),r,p)}}(s,e,i,t,i.layout.get("text-rotation-alignment"),i.layout.get("text-pitch-alignment"),o,c);const h=0!==i.paint.get("icon-opacity").constantOr(1),d=0!==i.paint.get("text-opacity").constantOr(1);void 0!==i.layout.get("symbol-sort-key").constantOr(1)&&(h||d)?O_(e,t,i,s,r,n):(h&&O_(e,t,i,s,r,n,{onlyIcons:!0}),d&&O_(e,t,i,s,r,n,{onlyText:!0})),t.map.showCollisionBoxes&&"global"!==t.map._placementAlgorithm&&Ca.drawCollisionDebug&&(Ca.drawCollisionDebug(e,t,i,s,i.paint.get("text-translate"),i.paint.get("text-translate-anchor"),!0),Ca.drawCollisionDebug(e,t,i,s,i.paint.get("icon-translate"),i.paint.get("icon-translate-anchor"),!1))},circle:function(e,t,i,s){if("translucent"!==e.renderPass)return;const o=i.paint.get("circle-opacity"),r=i.paint.get("circle-stroke-width"),n=i.paint.get("circle-stroke-opacity"),a=void 0!==i.layout.get("circle-sort-key").constantOr(1),l=i.paint.get("circle-emissive-strength");if(0===o.constantOr(1)&&(0===r.constantOr(1)||0===n.constantOr(1)))return;const c=e.context,h=c.gl,d=e.transform,u=!(!e.terrain||!e.terrain.enabled),_=i.layout.get("circle-elevation-reference"),p=e.depthModeForSublayer(0,Cu.ReadOnly),f=new Cu(e.context.gl.LEQUAL,Cu.ReadOnly,e.depthRangeFor3D),m="none"===_||u?p:f,g=Pu.disabled,v=e.colorModeForDrapableLayerRenderPass(l),y="globe"===d.projection.name,x=[Ae(d.center.lng),Pe(d.center.lat)],b=[];for(let o=0;o<s.length;o++){const r=s[o],n=t.getTile(r),l=n.getBucket(i);if(!l||l.projection.name!==d.projection.name)continue;const c=l.programConfigurations.get(i.id),h=l.layoutVertexBuffer,u=l.globeExtVertexBuffer,_=l.indexBuffer,p=To(i),f=[u],m=e.isTileAffectedByFog(r);y&&p.push("PROJECTION_GLOBE_VIEW"),p.push("DEPTH_D24"),e.terrain&&d.depthOcclusionForSymbolsAndCircles&&p.push("DEPTH_OCCLUSION"),l.hdExt&&l.hdExt.hasElevation&&!e.terrain&&(p.push("ELEVATED_ROADS"),f.push(l.hdExt.elevatedLayoutVertexBuffer));const g=e.getOrCreateProgram("circle",{config:c,defines:p,overrideFog:m}),v=d.projection.createInversionMatrix(d,r.canonical),w={programConfiguration:c,program:g,layoutVertexBuffer:h,dynamicBuffers:f,indexBuffer:_,uniformValues:Eo(e,r,n,v,x,i),tile:n};if(a){const e=l.segments.get();for(const t of e)b.push({segments:new Ye([t]),sortKey:t.sortKey,state:w})}else b.push({segments:l.segments,sortKey:0,state:w})}a&&b.sort((e,t)=>e.sortKey-t.sortKey);const w={useDepthForOcclusion:d.depthOcclusionForSymbolsAndCircles};for(const t of b){const{programConfiguration:s,program:o,layoutVertexBuffer:r,dynamicBuffers:n,indexBuffer:a,uniformValues:l,tile:u}=t.state,_=t.segments;e.terrain&&e.terrain.setupElevationDraw(u,o,w),e.uploadCommonUniforms(c,o,u.tileID.toUnwrapped()),o.draw(e,h.TRIANGLES,m,g,v,A_.disabled,l,i.id,r,a,_,i.paint,d.zoom,s,n)}},heatmap:function(e,t,i,s){if(0!==i.paint.get("heatmap-opacity"))if("offscreen"===e.renderPass){const o=e.context,r=o.gl,n=Pu.disabled,a=new zu([r.ONE,r.ONE,r.ONE,r.ONE],S.transparent,[!0,!0,!0,!0]),l="globe"===e.transform.projection.name?.5:.25;i.heatmapFbo=S_.createWithTexture(o,i.heatmapFbo,e.width*l,e.height*l),o.clear({color:S.transparent});const c=e.transform,h="globe"===c.projection.name,d=h?["PROJECTION_GLOBE_VIEW"]:[],u=h?A_.frontCCW:A_.disabled,_=[Ae(c.center.lng),Pe(c.center.lat)];for(let l=0;l<s.length;l++){const p=s[l];if(t.hasRenderableParent(p))continue;const f=t.getTile(p),m=f.getBucket(i);if(!m||m.projection.name!==c.projection.name)continue;const g=e.isTileAffectedByFog(p),v=m.programConfigurations.get(i.id),y=e.getOrCreateProgram("heatmap",{config:v,defines:d,overrideFog:g}),{zoom:x}=e.transform;e.terrain&&e.terrain.setupElevationDraw(f,y),e.uploadCommonUniforms(o,y,p.toUnwrapped());const b=c.projection.createInversionMatrix(c,p.canonical);y.draw(e,r.TRIANGLES,Cu.disabled,n,a,u,ud(e,p,f,b,_,x,i.paint.get("heatmap-intensity")),i.id,m.layoutVertexBuffer,m.indexBuffer,m.segments,i.paint,e.transform.zoom,v,h?[m.globeExtVertexBuffer]:null)}o.viewport.set([0,0,e.width,e.height])}else"translucent"===e.renderPass&&(e.context.setColorMode(e.colorModeForRenderPass()),function(e,t){const i=e.context,s=i.gl,o=t.heatmapFbo;if(!o)return;i.activeTexture.set(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,o.colorAttachment0.get()),i.activeTexture.set(s.TEXTURE1);let r=t.colorRampTexture;r||(r=t.colorRampTexture=new k(i,t.colorRamp,s.RGBA8)),r.bind(s.LINEAR,s.CLAMP_TO_EDGE),e.getOrCreateProgram("heatmapTexture").draw(e,s.TRIANGLES,Cu.disabled,Pu.disabled,e.colorModeForRenderPass(),A_.disabled,((e,t)=>({u_image:0,u_color_ramp:1,u_opacity:t.paint.get("heatmap-opacity")}))(0,t),t.id,e.viewportBuffer,e.quadTriangleIndexBuffer,e.viewportSegments,t.paint,e.transform.zoom)}(e,i))},line:function(e,t,i,s){const o=i.paint.get("line-opacity"),r=i.paint.get("line-width");if(0===o.constantOr(1)||0===r.constantOr(1))return;const n=i.paint.get("line-blend-mode"),a=e.terrain&&e.terrain.renderingToTexture;if("default"===n||"globe"===e.transform.projection.name)"translucent"===e.renderPass&&F_(e,t,i,s);else{if(a)return void function(e,t,i,s,o){if("translucent"!==e.renderPass)return;const r=e.context,n=r.gl,a=e.terrain;if(!a)return;const l=r.bindFramebuffer.current,c=e.isEmissiveMrtActive(),h=a.drapeBufferSize[0],d=a.drapeBufferSize[1];i.lineBlendFbos||(i.lineBlendFbos=new k_),i.lineBlendFbos.drapeFbo=S_.createWithTexture(r,i.lineBlendFbos.drapeFbo,h,d,!0),c&&n.drawBuffers([n.COLOR_ATTACHMENT0]),r.clear({color:N_[o].clearColor,depth:1,stencil:0});const u=e.currentStencilSource,_=e._tileClippingMaskIDs,p=e.nextStencilID;e.currentStencilSource=void 0,e._tileClippingMaskIDs=new Map,e.nextStencilID=1;const f=e._terrain;e._terrain=null,e._renderTileClippingMasks(i,t,s),F_(e,t,i,s,V_(o,e.context),!0),e._terrain=f,e.currentStencilSource=u,e._tileClippingMaskIDs=_,e.nextStencilID=p,c&&n.drawBuffers([n.COLOR_ATTACHMENT0,n.COLOR_ATTACHMENT1]);const m=a.drapeBufferSize,g=i.lineBlendFbos&&i.lineBlendFbos.drapeFbo;g&&("additive"===o&&G_(e,i,g),q_(e,i,o,g,l,m))}(e,t,i,s,n);if("offscreen"===e.renderPass)return void function(e,t,i,s,o){const r=e.context,n=Math.ceil(e.width),a=Math.ceil(e.height);i.lineBlendFbos||(i.lineBlendFbos=new k_),i.lineBlendFbos.fbo=S_.createWithTexture(r,i.lineBlendFbos.fbo,n,a,!0),r.clear({color:N_[o].clearColor,depth:1,stencil:0});const l=e.currentStencilSource,c=e._tileClippingMaskIDs,h=e.nextStencilID;e.currentStencilSource=void 0,e._tileClippingMaskIDs=new Map,e.nextStencilID=1,e._renderTileClippingMasks(i,t,s);const d=e.renderPass;e.renderPass="translucent",F_(e,t,i,s,V_(o,e.context)),e.renderPass=d,e.currentStencilSource=l,e._tileClippingMaskIDs=c,e.nextStencilID=h,r.viewport.set([0,0,e.width,e.height]),"additive"===o&&G_(e,i,i.lineBlendFbos.fbo)}(e,t,i,s,n);if("translucent"===e.renderPass){const t=i.lineBlendFbos&&i.lineBlendFbos.fbo;return void(t&&q_(e,i,n,t,null))}}},fill:function(e,t,i,s){const o=i.paint.get("fill-color"),r=i.paint.get("fill-opacity");if(0===r.constantOr(1))return;const n=i.paint.get("fill-emissive-strength"),a=e.colorModeForDrapableLayerRenderPass(n),l=i.paint.get("fill-pattern"),c=e.opaquePassEnabledForLayer()&&!l.constantOr(1)&&1===o.constantOr(S.transparent).a&&1===r.constantOr(0)?"opaque":"translucent";let h="none";"none"!==i.layout.get("fill-elevation-reference")?h="road":0!==i.paint.get("fill-z-offset").constantOr(1)&&(h="offset");const d=!(!e.terrain||!e.terrain.enabled),u={painter:e,sourceCache:t,layer:i,coords:s,colorMode:a,elevationType:h,terrainEnabled:d,pass:c};if("shadow"===e.renderPass)return void(e.shadowRenderer&&"road"===h&&!d&&Il.drawElevatedFillShadows&&Il.drawElevatedFillShadows(u));const _=e.isEmissiveMrtActive();if("offset"!==h){if(Z_(u,!1,_),"road"===h){const o=!d&&"translucent"===e.renderPass;o&&Il.drawDepthPrepass&&Il.drawDepthPrepass(e,t,i,s,"geometry"),Z_(u,!0,_,Pu.disabled),o&&Il.drawElevatedStructures&&Il.drawElevatedStructures(u)}}else Z_(u,!1,_,e.stencilModeFor3D())},"fill-extrusion":function(e,t,i,s){const o=i.paint.get("fill-extrusion-opacity"),r=e.context,n=r.gl,a=e.terrain,l=a&&a.renderingToTexture;if(0===o)return;const c=e.isEmissiveMrtActive(),h=e.conflationActive&&e.style.isLayerClipped(i,t.getSource()),d=e.style.order.indexOf(i.fqid);if(h&&function(e,t,i,s,o){for(const r of s){const s=t.getTile(r).getBucket(i);s&&(s.updateReplacement(r,e.replacementSource,o),s.uploadCentroid(e.context))}}(e,t,i,s,d),a||h)for(const o of s){const s=t.getTile(o).getBucket(i);s&&X_(e.context,t,o,s,i,a,h)}if(e.depthPrepassPhase){if(!l){const o=new Cu(n.LEQUAL,Cu.ReadWrite,e.depthRangeFor3D);W_(e,t,i,s,o,Pu.disabled,zu.disabled,h)}}else if("shadow"===e.renderPass&&e.shadowRenderer){const r=e.shadowRenderer;if(a&&o<.65&&i.getPaintPropertyValue("fill-extrusion-opacity").expression instanceof Y)return;const n=r.getShadowPassDepthMode();W_(e,t,i,s,n,Pu.disabled,zu.disabled,h)}else if("translucent"===e.renderPass){const d=!i.paint.get("fill-extrusion-pattern").constantOr(1),u=i.paint.get("fill-extrusion-color").constantOr(S.white);if(!l&&0!==u.a){const r=new Cu(e.context.gl.LEQUAL,Cu.ReadWrite,e.depthRangeFor3D);1===o&&d?W_(e,t,i,s,r,Pu.disabled,zu.unblended,h):(e.hasGrouped3DDepthPrepass(e.currentLayer)||W_(e,t,i,s,r,Pu.disabled,zu.disabled,h),W_(e,t,i,s,r,e.stencilModeFor3DGroup(e.currentLayer),e.colorModeForRenderPass(),h),e.resetStencilClippingMasks())}const _=e.style.enable3dLights()&&d&&(!a&&"globe"!==e.transform.projection.name||l);if(_&&!ue.drawGroundEffect&&Cl(),_&&ue.drawGroundEffect){const o=i.paint.get("fill-extrusion-opacity"),d=i.paint.get("fill-extrusion-ambient-occlusion-intensity"),u=i.paint.get("fill-extrusion-ambient-occlusion-ground-radius"),_=i.paint.get("fill-extrusion-flood-light-intensity"),p="none"===i.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default"),f=i.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(p?null:i.lut).toArray01().slice(0,3),m=d>0&&u>0,g=_>0,v=new H_;v.translate=i.paint.get("fill-extrusion-translate"),v.translateAnchor=i.paint.get("fill-extrusion-translate-anchor"),v.edgeRadius=i.layout.get("fill-extrusion-edge-radius"),v.cutoffFadeRange=i.paint.get("fill-extrusion-cutoff-fade-range");const y=r=>{const a=e.depthModeForSublayer(1,Cu.ReadOnly,n.LEQUAL,!0),l=i.paint.get(r?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),c=J(.1,3,l),p=e._showOverdrawInspector;if(!p){const l=new Pu({func:n.ALWAYS,mask:255},255,255,n.KEEP,n.KEEP,n.REPLACE),p=new zu([n.ONE,n.ONE,n.ONE,n.ONE],S.transparent,[!1,!1,!1,!0],n.MIN);ue.drawGroundEffect(v,e,t,i,s,a,l,p,A_.disabled,r,"sdf",o,d,u,_,f,c,h,!1)}{const l=p?Pu.disabled:new Pu({func:n.EQUAL,mask:255},255,255,n.KEEP,n.DECR,n.DECR),m=p?e.colorModeForRenderPass():new zu([n.ONE_MINUS_DST_ALPHA,n.DST_ALPHA,n.ONE,n.ONE],S.transparent,[!0,!0,!0,!0]);ue.drawGroundEffect(v,e,t,i,s,a,l,m,A_.disabled,r,"color",o,d,u,_,f,c,h,!1)}};if(l){const l=()=>{const e=a.drapeBufferSize[0],t=a.drapeBufferSize[1];let i=a.framebufferCopyTexture;return i&&(!i||i.size[0]===e&&i.size[1]===t)||(i&&i.destroy(),i=a.framebufferCopyTexture=new k(r,new E({width:e,height:t}),n.RGBA8)),i.bind(n.LINEAR,n.CLAMP_TO_EDGE),n.copyTexSubImage2D(n.TEXTURE_2D,0,0,0,0,0,e,t),i},p=(r,a,p)=>{const m=e.depthModeForSublayer(1,Cu.ReadOnly,n.LEQUAL,!1),g=i.paint.get(r?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),y=J(.1,3,g);{const l=new zu([n.ONE,n.ONE,n.ONE,n.ONE],S.transparent,[!1,!1,!1,!0]);ue.drawGroundEffect(v,e,t,i,s,m,Pu.disabled,l,A_.disabled,r,"clear",o,d,u,_,f,y,h,a)}{const l=new Pu({func:n.ALWAYS,mask:255},255,255,n.KEEP,n.KEEP,n.REPLACE),c=new zu([n.ONE,n.ONE,n.ONE,n.ONE],S.transparent,[!1,!1,!1,!0],n.MIN);ue.drawGroundEffect(v,e,t,i,s,m,l,c,A_.disabled,r,"sdf",o,d,u,_,f,y,h,a)}c&&!r&&(p=l());{const l=r?n.ZERO:n.ONE_MINUS_DST_ALPHA,c=new Pu({func:n.EQUAL,mask:255},255,255,n.KEEP,n.DECR,n.DECR),p=new zu([l,n.DST_ALPHA,n.ONE_MINUS_DST_ALPHA,n.ZERO],S.transparent,[!0,!0,!0,!0]);ue.drawGroundEffect(v,e,t,i,s,m,c,p,A_.disabled,r,"color",o,d,u,_,f,y,h,a)}if(!c||r){const l=new zu([n.ONE,n.ONE,n.ONE,r?n.ZERO:n.ONE],S.transparent,[!1,!1,!1,!0],r?n.FUNC_ADD:n.MAX);ue.drawGroundEffect(v,e,t,i,s,m,Pu.disabled,l,A_.disabled,r,"clear",o,d,u,_,f,y,h,a,p)}else{n.drawBuffers([n.NONE,n.COLOR_ATTACHMENT1]);const l=new Pu({func:n.EQUAL,mask:255},254,255,n.KEEP,n.DECR,n.DECR),c=new zu([n.ONE,n.ONE,n.ONE,n.ONE],S.transparent,[!0,!1,!1,!1],n.MAX);ue.drawGroundEffect(v,e,t,i,s,m,l,c,A_.disabled,r,"emissive",o,d,u,_,f,y,h,a,p),n.drawBuffers([n.COLOR_ATTACHMENT0])}};if(m||g){let t;e.prepareDrawTile(),c&&!m||(t=l()),m&&p(!0,!1,t),g&&p(!1,!0,t)}}else m&&y(!0),g&&y(!1),(m||g)&&e.resetStencilClippingMasks()}}},hillshade:function(e,t,i,s){if("offscreen"!==e.renderPass&&"translucent"!==e.renderPass)return;if(e.style.disableElevatedTerrain)return;const o=e.context,r=e.terrain&&e.terrain.renderingToTexture,[n,a]="translucent"!==e.renderPass||r?[{},s]:e.stencilConfigForOverlap(s);for(const s of a){const o=t.getTile(s);if(o.needsHillshadePrepare&&"offscreen"===e.renderPass)ip(e,o,i);else if("translucent"===e.renderPass){const t=e.depthModeForSublayer(0,Cu.ReadOnly),a=i.paint.get("hillshade-emissive-strength"),l=e.colorModeForDrapableLayerRenderPass(a),c=r&&e.terrain?e.terrain.stencilModeForRTTOverlap(s):n[s.overscaledZ];ep(e,s,o,i,t,c,l)}}o.viewport.set([0,0,e.width,e.height]),e.resetStencilClippingMasks()},raster:function(e,t,i,s,o,r){if("translucent"!==e.renderPass)return;const n=i.paint.get("raster-opacity");if(0===n)return;const a="globe"===e.transform.projection.name,l=i.paint.get("raster-elevation"),c="ground"===i.paint.get("raster-elevation-reference"),h=l>0,d=e.terrain&&e.terrain.exaggeration()>0&&h&&c,u=h&&a,_=!a&&d;if(e.renderElevatedRasterBackface&&!u)return;const p=e.context,f=p.gl,m=t.getSource(),g=function(e,t,i,s,o){const r=i.paint.get("raster-color"),n="raster-array"===t.type,a=[],l=i.paint.get("raster-resampling"),c=i.paint.get("raster-color-mix");let h=i.paint.get("raster-color-range");const d=[c[0],c[1],c[2],0],u=c[3];let _="nearest"===l?o.NEAREST:o.LINEAR;if(n&&(a.push("RASTER_ARRAY"),r||a.push("RASTER_COLOR"),"linear"===l&&a.push("RASTER_ARRAY_LINEAR"),_=o.NEAREST,r&&"log"===i.paint.get("raster-color-scale")&&a.push("RASTER_COLOR_SCALE_LOG"),!h&&t.rasterLayers)){const e=t.rasterLayers.find(({id:e})=>e===i.sourceLayer);e&&e.fields&&e.fields.range&&(h=e.fields.range)}if(h=h||[0,1],r){a.push("RASTER_COLOR"),s.activeTexture.set(o.TEXTURE2),i.updateColorRamp(h);let e=i.colorRampTexture;e||(e=i.colorRampTexture=new k(s,i.colorRamp,o.RGBA8)),e.bind(_,o.CLAMP_TO_EDGE)}return e.terrain&&e.terrain.renderingToTexture&&e.isEmissiveMrtActive()&&(a.push("USE_MRT1"),"mrt-full-rgba"===e.emissiveMode&&a.push("USE_MRT1_RGBA")),{mix:d,range:h,offset:u,defines:a,resampling:_}}(e,m,i,p,f);if(m instanceof Hl&&!s.length&&!a)return;const v=i.paint.get("raster-emissive-strength"),y=e.colorModeForDrapableLayerRenderPass(v),x=e.terrain&&e.terrain.renderingToTexture,b=!e.options.moving,w="nearest"===i.paint.get("raster-resampling")?f.NEAREST:f.LINEAR;if(m instanceof Hl&&!s.length&&(m.onNorthPole||m.onSouthPole)){const s=h?e.stencilModeFor3D():Pu.disabled;return void rp(l,!!m.onNorthPole,null,e,t,i,v,g,A_.disabled,s)}if(!s.length)return;if(i.paint.get("raster-mask")&&!Pl.resolveRasterMask)return;const T=Pl.resolveRasterMask?Pl.resolveRasterMask(e,i):null;if("unavailable"===T)return;let E=!1;const[I,S]=m instanceof Hl||x?[{},s]:e.stencilConfigForOverlap(s,T?128:void 0),D=S.at(-1).overscaledZ;u&&g.defines.push("PROJECTION_GLOBE_VIEW"),h&&g.defines.push("RENDER_CUTOFF","ELEVATED"),d&&g.defines.push("ELEVATION_REFERENCE_GROUND");const R=(s,o,c)=>{for(const T of s){const s=T.toUnwrapped(),S=t.getTile(T);if(x&&(!S||!S.hasData()))continue;p.activeTexture.set(f.TEXTURE0);const R=ap(S,m,i,g);if(!R||!R.texture)continue;const{texture:C,mix:A,offset:L,tileSize:P,buffer:M}=R;let O,z;x?(O=Cu.disabled,z=T.projMatrix):h?(O=new Cu(f.LEQUAL,Cu.ReadWrite,e.depthRangeFor3D),z=a?e.transform.expandedFarZProjMatrix:e.transform.calculateProjMatrix(s,b)):(O=e.depthModeForSublayer(T.overscaledZ-D,1===n?Cu.ReadWrite:Cu.ReadOnly,f.LESS),z=e.transform.calculateProjMatrix(s,b));let F=e.terrain&&x?e.terrain.stencilModeForRTTOverlap(T):I[T.overscaledZ];E&&(F=Pl.stencilModeWithRasterMask(e,F));const k=r?0:i.paint.get("raster-fade-duration");S.registerFadeDuration(k);const B=t.findLoadedParent(T,0),N=sp(S,B,t,e.transform,k);let U,V;!N.isFading&&S.refreshedUponExpiration&&(S.refreshedUponExpiration=!1),e.terrain&&e.terrain.prepareDrawTile(),p.activeTexture.set(f.TEXTURE0),C.bind(w,f.CLAMP_TO_EDGE),p.activeTexture.set(f.TEXTURE1),B?(B.texture&&B.texture.bind(w,f.CLAMP_TO_EDGE),U=Math.pow(2,B.tileID.overscaledZ-S.tileID.overscaledZ),V=[S.tileID.canonical.x*U%1,S.tileID.canonical.y*U%1]):C.bind(w,f.CLAMP_TO_EDGE),"useMipmap"in C&&p.extTextureFilterAnisotropic&&e.transform.pitch>20&&f.texParameterf(f.TEXTURE_2D,p.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,p.extTextureFilterAnisotropicMax);const j=e.transform;let G;const q=h?np(j):[0,0,0,0];let Z,W,H,$,X,Y=0;if(u&&m instanceof Hl&&m.coordinates.length>3)Z=Float32Array.from(wt(Vo(new $e(0,0,0)))),W=Float32Array.from(j.globeMatrix),H=Float32Array.from(jo(j)),$=[Ae(j.center.lng),Pe(j.center.lat)],G=m.elevatedGlobePerspectiveTransform,X=m.elevatedGlobeGridMatrix||new Float32Array(9);else if(u){const e=Go(T.canonical);Y=qo(e.getCenter().lat),Z=Float32Array.from(wt(Vo(T.canonical))),W=Float32Array.from(j.globeMatrix),H=Float32Array.from(jo(j)),$=[Ae(j.center.lng),Pe(j.center.lat)],G=[0,0],X=Float32Array.from(Zo(T.canonical,e,Y,j.worldSize/j._pixelsPerMercatorPixel))}else G=m instanceof Hl?m.perspectiveTransform:[0,0],Z=new Float32Array(16),W=new Float32Array(9),H=new Float32Array(16),$=[0,0],X=new Float32Array(9);const J=gd(e,z,Z,W,H,X,V||[0,0],K(e.transform.zoom),$,q,U||1,N,i,G,l,2,A,L,g.range,P,M,v),Q=e.isTileAffectedByFog(T),ee=e.getOrCreateProgram("raster",{defines:g.defines,overrideFog:Q});if(e.uploadCommonUniforms(p,ee,s),m instanceof Hl){const t=E?Pl.stencilModeWithRasterMask(e,Pu.disabled):Pu.disabled,s=m.elevatedGlobeVertexBuffer,r=m.elevatedGlobeIndexBuffer;if(x||!a)m.boundsBuffer&&m.boundsSegments&&ee.draw(e,f.TRIANGLES,O,t,y,A_.disabled,J,i.id,m.boundsBuffer,e.quadTriangleIndexBuffer,m.boundsSegments);else if(s&&r){const n=j.zoom<=uo?m.elevatedGlobeSegments:m.getSegmentsForLongitude(j.center.lng);n&&ee.draw(e,f.TRIANGLES,O,t,y,o,J,i.id,s,r,n)}}else if(u){O=new Cu(f.LEQUAL,Cu.ReadOnly,e.depthRangeFor3D);const t=e.globeSharedBuffers;if(t){d&&(e.terrain.setupElevationDraw(S,ee),e.uploadCommonUniforms(p,ee,S.tileID.toUnwrapped()));const[s,r,n]=t.getGridBuffers(Y,!1),a=ee.getAttributeLocation(f,"a_texture_pos");-1!==a&&f.vertexAttribI4ui(a,0,0,0,0),ee.draw(e,f.TRIANGLES,O,c||F,e.colorModeForRenderPass(),o,J,i.id,s,r,n)}}else if(_)O=new Cu(f.LEQUAL,Cu.ReadOnly,e.depthRangeFor3D),e.terrain.setupElevationDraw(S,ee),e.uploadCommonUniforms(p,ee,S.tileID.toUnwrapped()),j.pitch>20&&ee.draw(e,f.TRIANGLES,O,Pu.disabled,zu.disabled,A_.frontCCW,J,i.id,e.terrain.gridBuffer,e.terrain.gridIndexBuffer,e.terrain.gridSegments),ee.draw(e,f.TRIANGLES,O,F,y,A_.backCCW,J,i.id,e.terrain.gridBuffer,e.terrain.gridIndexBuffer,e.terrain.gridSegments);else{const{tileBoundsBuffer:t,tileBoundsIndexBuffer:s,tileBoundsSegments:o}=e.getTileBoundsBuffers(S);ee.draw(e,f.TRIANGLES,O,F,y,A_.disabled,J,i.id,t,s,o)}}if(!(m instanceof Hl)&&u)for(const r of s){const s=r.canonical.y===(1<<r.canonical.z)-1;0===r.canonical.y&&rp(l,!0,r,e,t,i,v,g,o,c||Pu.disabled),s&&rp(l,!1,r,e,t,i,v,g,o===A_.frontCW?A_.backCW:A_.frontCW,c||Pu.disabled)}};u?R(S,e.renderElevatedRasterBackface?A_.backCW:A_.frontCW,e.stencilModeFor3D()):(T&&(Pl.renderRasterMask(e,T),E=!0),R(S,A_.disabled,void 0),E&&(Pl.clearRasterMask(e),E=!1)),e.resetStencilClippingMasks()},background:function(e,t,i,s){const o=i.paint.get("background-color"),r="none"===i.paint.get("background-color-use-theme").constantOr("default"),n=i.paint.get("background-opacity"),a=i.paint.get("background-emissive-strength"),l="viewport"===i.paint.get("background-pitch-alignment");if(0===n)return;const c=e.context,h=c.gl,d=e.transform,u=d.tileSize,_=i.paint.get("background-pattern");let p;if(void 0!==_){if(null===_)return;if(p=e.imageManager.getPattern(g.from(_.toString()),i.scope,e.style.getLut(i.scope)),!p)return}const f=!_&&1===o.a&&1===n&&e.opaquePassEnabledForLayer()?"opaque":"translucent";if(e.renderPass!==f)return;const m=Pu.disabled,v=e.depthModeForSublayer(0,"opaque"===f?Cu.ReadWrite:Cu.ReadOnly),y=e.colorModeForDrapableLayerRenderPass(a),x=_?"backgroundPattern":"background";let b,w=s;w||(b=e.getBackgroundTiles(),w=Object.values(b).map(e=>e.tileID)),_&&(c.activeTexture.set(h.TEXTURE0),e.imageManager.bind(e.context,i.scope));const T=[];if(e.terrain&&e.terrain.renderingToTexture&&e.isEmissiveMrtActive()&&(T.push("USE_MRT1"),"mrt-full-rgba"===e.emissiveMode&&T.push("USE_MRT1_RGBA")),l){const t=e.getOrCreateProgram(x,{overrideFog:!1,overrideRtt:!0,defines:T}),s=lp,c=new Ge(0,0,0,0,0),d=_?Td(s,a,n,e,0,i.scope,p,l,{tileID:c,tileSize:u}):wd(s,a,n,o.toPremultipliedRenderColor(r?null:i.lut));return void t.draw(e,h.TRIANGLES,v,m,y,A_.disabled,d,i.id,e.viewportBuffer,e.quadTriangleIndexBuffer,e.viewportSegments)}for(const f of w){const g=e.isTileAffectedByFog(f),w=e.getOrCreateProgram(x,{overrideFog:g,defines:T}),E=f.toUnwrapped(),I=s?f.projMatrix:e.transform.calculateProjMatrix(E);e.prepareDrawTile();const S=t?t.getTile(f):b?b[f.key]:new yc(f,u,d.zoom,e),D=_?Td(I,a,n,e,0,i.scope,p,l,{tileID:f,tileSize:u}):wd(I,a,n,o.toPremultipliedRenderColor(r?null:i.lut));e.uploadCommonUniforms(c,w,E);const{tileBoundsBuffer:R,tileBoundsIndexBuffer:C,tileBoundsSegments:A}=e.getTileBoundsBuffers(S);w.draw(e,h.TRIANGLES,v,m,y,A_.disabled,D,i.id,R,C,A)}},sky:function(e,t,i){const s=e._atmosphere?K(e.transform.zoom):1,o=i.paint.get("sky-opacity")*s;if(0===o)return;const r=e.context,n=i.paint.get("sky-type"),a=new Cu(r.gl.LEQUAL,Cu.ReadOnly,[0,1]),l=e.frameCounter/1e3%1;"atmosphere"===n?"offscreen"===e.renderPass?i.needsSkyboxCapture(e)&&(function(e,t){const i=e.context,s=i.gl;let o=t.skyboxFbo;if(!o){o=t.skyboxFbo=i.createFramebuffer(32,32,1,null),t.skyboxGeometry=new _p(i),t.skyboxTexture=i.gl.createTexture(),s.bindTexture(s.TEXTURE_CUBE_MAP,t.skyboxTexture),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MIN_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MAG_FILTER,s.LINEAR);for(let e=0;e<6;++e)s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,s.RGBA,32,32,0,s.RGBA,s.UNSIGNED_BYTE,null)}i.bindFramebuffer.set(o.framebuffer),i.viewport.set([0,0,32,32]);const r=t.getCenter(e,!0),n=e.getOrCreateProgram("skyboxCapture"),a=new Float64Array(16);Xo(a,.5*-Math.PI),pp(e,t,n,a,r,0),Xo(a,.5*Math.PI),pp(e,t,n,a,r,1),Yo(a,.5*-Math.PI),pp(e,t,n,a,r,2),Yo(a,.5*Math.PI),pp(e,t,n,a,r,3),ci(a),pp(e,t,n,a,r,4),Xo(a,Math.PI),pp(e,t,n,a,r,5),i.viewport.set([0,0,e.width,e.height])}(e,i),i.markSkyboxValid(e)):"sky"===e.renderPass&&function(e,t,i,s,o){const r=e.context,n=r.gl,a=e.transform,l=e.getOrCreateProgram("skybox");r.activeTexture.set(n.TEXTURE0),n.bindTexture(n.TEXTURE_CUBE_MAP,t.skyboxTexture);const c=((e,t,i,s,o)=>({u_matrix:e,u_sun_direction:t,u_cubemap:0,u_opacity:s,u_temporal_offset:o}))(a.skyboxMatrix,t.getCenter(e,!1),0,s,o);e.uploadCommonUniforms(r,l),l.draw(e,n.TRIANGLES,i,Pu.disabled,e.colorModeForRenderPass(),A_.backCW,c,"skybox",t.skyboxGeometry.vertexBuffer,t.skyboxGeometry.indexBuffer,t.skyboxGeometry.segment)}(e,i,a,o,l):"gradient"===n&&"sky"===e.renderPass&&function(e,t,i,s,o){const r=e.context,n=r.gl,a=e.transform,l=e.getOrCreateProgram("skyboxGradient");t.skyboxGeometry||(t.skyboxGeometry=new _p(r)),r.activeTexture.set(n.TEXTURE0);let c=t.colorRampTexture;c||(c=t.colorRampTexture=new k(r,t.colorRamp,n.RGBA8)),c.bind(n.LINEAR,n.CLAMP_TO_EDGE);const h=((e,t,i,s,o)=>({u_matrix:e,u_color_ramp:0,u_center_direction:t,u_radius:le(i),u_opacity:s,u_temporal_offset:o}))(a.skyboxMatrix,t.getCenter(e,!1),t.paint.get("sky-gradient-radius"),s,o);e.uploadCommonUniforms(r,l),l.draw(e,n.TRIANGLES,i,Pu.disabled,e.colorModeForRenderPass(),A_.backCW,h,"skyboxGradient",t.skyboxGeometry.vertexBuffer,t.skyboxGeometry.indexBuffer,t.skyboxGeometry.segment)}(e,i,a,o,l)},custom:function(e,t,i,s){const o=e.context,r=i.implementation;if(e.transform.projection.unsupportedLayers&&e.transform.projection.unsupportedLayers.includes("custom")&&(!e.terrain||!e.terrain.renderingToTexture&&"offscreen"!==e.renderPass||!i.isDraped(t)))return void _("Custom layers are not yet supported with this projection. Use mercator or globe to enable usage of custom layers.");const n=function(e){if(e._customRenderArgs&&e._customRenderArgsFrameCounter===e.frameCounter)return e._customRenderArgs;const t=e.transform;let i=null,s=null;if("globe"===t.projection.name){const e=Ho(t),o=_s(e);if(o>0){const t=Ti([],e,1/o);i=[t[0],t[1],t[2],-De*De/o]}const r=t.projection.globeCenterToScreenPoint(t);r&&(s=[r.x,r.y])}const o={projectionMatrix:new Float64Array(t.getCameraToClipMatrix()),viewMatrix:new Float64Array(t.getWorldToCameraMatrix()),globeClippingPlane:i,globeCenterInScreenPixels:s};return e._customRenderArgs=o,e._customRenderArgsFrameCounter=e.frameCounter,o}(e);if("offscreen"===e.renderPass){const t=r.prerender;if(t){if(e.setCustomLayerDefaults(),o.setColorMode(e.colorModeForRenderPass()),"globe"===e.transform.projection.name){const i=e.transform.pointMerc;t.call(r,o.gl,e.transform.customLayerMatrix(),e.transform.getProjection(),e.transform.globeToMercatorMatrix(),K(e.transform.zoom),[i.x,i.y],e.transform.pixelsPerMeterRatio,n)}else t.call(r,o.gl,e.transform.customLayerMatrix(),void 0,void 0,void 0,void 0,void 0,n);o.setDirty(),e.setBaseState()}}else if("translucent"===e.renderPass){if(e.terrain&&e.terrain.renderingToTexture){const t=r.renderToTile;if(t){const i=s[0].canonical,n={x:i.x+s[0].wrap*(r.wrapTileId?0:1<<i.z),y:i.y,z:i.z};o.setDepthMode(Cu.disabled),o.setStencilMode(Pu.disabled),o.setColorMode(e.colorModeForRenderPass()),e.setCustomLayerDefaults();const a=cp[e.emissiveMode],l=o.gl,c=r.supportsEmissiveMode,h=a&&c&&c.call(r,a);e.isEmissiveMrtActive()&&!h&&l.drawBuffers([l.COLOR_ATTACHMENT0]),t.call(r,o.gl,n,a),e.isEmissiveMrtActive()&&!h&&l.drawBuffers([l.COLOR_ATTACHMENT0,l.COLOR_ATTACHMENT1]),o.setDirty(),e.setBaseState()}return}e.setCustomLayerDefaults(),o.setColorMode(e.colorModeForRenderPass()),o.setStencilMode(Pu.disabled);const t="3d"===r.renderingMode?new Cu(e.context.gl.LEQUAL,Cu.ReadWrite,e.depthRangeFor3D):e.depthModeForSublayer(0,Cu.ReadOnly);if(o.setDepthMode(t),"globe"===e.transform.projection.name){const t=e.transform.pointMerc;r.render(o.gl,e.transform.customLayerMatrix(),e.transform.getProjection(),e.transform.globeToMercatorMatrix(),K(e.transform.zoom),[t.x,t.y],e.transform.pixelsPerMeterRatio,n)}else r.render(o.gl,e.transform.customLayerMatrix(),void 0,void 0,void 0,void 0,void 0,n);o.setDirty(),e.setBaseState(),o.bindFramebuffer.set(null)}}},Dp={line:function(e,t,i){if(e.hasElevatedBuckets=!1,e.hasNonElevatedBuckets=!1,void 0!==e.getLayoutPropertyValue("line-elevation-reference").value||void 0!==e.getLayoutPropertyValue("line-z-offset").value){if(t){const i=t.getVisibleCoordinates();for(const s of i){const i=t.getTile(s).getBucket(e);if(i&&("none"!==i.elevationType?e.hasElevatedBuckets=!0:e.hasNonElevatedBuckets=!0,e.hasElevatedBuckets&&e.hasNonElevatedBuckets))break}}}else e.hasNonElevatedBuckets=!0},raster:function(e,t,i){const s=t.getSource();if("raster-array"!==s.type||!s.loaded())return;const o=e.sourceLayer||s.rasterLayerIds&&s.rasterLayerIds[0];if(!o)return;const r=e.paint.get("raster-array-band")||s.getInitialBand(o);if(null==r)return;const n=t.getIds().map(e=>t.getTileByID(e));for(const t of n)t.updateNeeded(e.id,r)&&s.prepareTile(t,o,e.id,r)}};async function Rp(e){if(await Cl(),Object.assign(Sp,{model:ue.drawModels}),Object.assign(Dp,{model:ue.prepare}),e&&!e._destroyed&&!e._shadowRenderer){const t=ue.ShadowRenderer;t&&(e._shadowRenderer=new t(e))}}class Cp{constructor(e,t,i,s,o,r){this._lightsUniforms=null,this._fogUniforms=null,this._forceFullRgbaEmissive=!1,this.context=new D_(e,t),this._forceFullRgbaEmissive="exact"===r,this.transform=i,this.cache=new Map,this._tileTextures={},this.frameCopies=[],this.loadTimeStamps=[],this.frcCoverageSnapshot=null,this.elevationCoverageSnapshot=null,this.elevationProvidersReady=void 0,this.frcCoverageFadeRange=null,this.frcCoverageSourceLayers=[],this.frcCoverageRenderer=Il.FrcCoverageRenderer?new Il.FrcCoverageRenderer:null,this._debugParams={averageFPS:0,fpsHistory:[],fpsWindow:30,continousRedraw:!1,enabledLayers:{},buildingsShowNormals:!1,buildingsDrawGroundAO:!0,buildingsDrawShadowPass:!0,buildingsDrawTranslucentPass:!0,showTerrainProxyTiles:!1,terrainSortTilesHiZFirst:!0,terrainDisableRenderCache:!1,forceEnablePrecipitation:!1,overrideSnowParams:!1,snowParamsOverride:null,snowRevealParamsOverride:null,snowVignetteParamsOverride:null,overrideRainParams:!1,rainParamsOverride:null,rainRevealParamsOverride:null,rainVignetteParamsOverride:null,overrideStarsParams:!1,starsParamsOverride:null,show3DModelFootprints:!1,showElevationIdDebug:!1,lodSwitchDistance:-1,lodSwitchFadeDuration:.5},this.occlusionParams=new Ip,this.setup(),this.numSublayers=Ac.maxUnderzooming+Ac.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.deferredRenderGpuTimeQueries=[],this.gpuTimers={},this.frameCounter=0,this.frameTimeDelta=0,this.lastPaintStartTimeStamp=0,this._shadowCullCache=null,this._backgroundTiles={},this.depthPrepassPhase=!1,this._grouped3DDepthPrepassStart=-1,this._grouped3DDepthPrepassEnd=-1,this._grouped3DStencil=null,this.conflationActive=!1,this.replacementSource=new nr,this.longestCutoffRange=0,this.minCutoffZoom=0,this._fogVisible=!1,this._cachedTileFogOpacities=new Map,this._wireframeDebugCache=new Ep,this.renderDefaultNorthPole=!0,this.renderDefaultSouthPole=!0,this.layersWithOcclusionOpacity=[];const n=new E({width:1,height:1},Uint8Array.of(0,0,0,0));this.emptyDepthTexture=new k(this.context,n,e.RGBA8),this._clippingActiveLastFrame=!1,this.scaleFactor=s,this.maxFrontCutoffRawStart=0,this.worldview=o,this._forceEmissiveMode=!1,this.emissiveMode="constant"}updateTerrain(e,t){const i=!!e&&!!e.terrain&&this.transform.projection.supportsTerrain;var s;(i||this._terrain&&this._terrain.enabled)&&(this._terrain||(this._terrain=wp(this,e),this._terrain)?(this.transform.elevation=i?this._terrain:null,this._terrain.update(e,this.transform,t),this.transform.elevation&&!this._terrain.enabled&&(this.transform.elevation=null)):this._terrainRendererRetryPending||(this._terrainRendererRetryPending=!0,s=()=>{this._terrainRendererRetryPending=!1,this.style&&this.style.map&&this.style.map._update(!1)},yp?s():xp.push(s)))}_updateFog(e){const t=e.fog;if(!t||"globe"===this.transform.projection.name||t.getOpacity(this.transform.pitch)<1||t.properties.get("horizon-blend")<.03)return void(this.transform.fogCullDistSq=null);const[i,s]=t.getRangeForProjection();if(i>s)return void(this.transform.fogCullDistSq=null);const o=i+.78*(s-i);this.transform.fogCullDistSq=o*o}get terrain(){return this.transform._terrainEnabled()&&this._terrain&&this._terrain.enabled||this._forceTerrainMode?this._terrain:null}get forceTerrainMode(){return this._forceTerrainMode}set forceTerrainMode(e){e&&!this._terrain&&(this._terrain=wp(this,this.style),this._terrain||console.warn("forceTerrainMode: Lite module not loaded yet, terrain renderer unavailable")),this._forceTerrainMode=e}get shadowRenderer(){return this._shadowRenderer&&this._shadowRenderer.enabled?this._shadowRenderer:null}get wireframeDebugCache(){return this._wireframeDebugCache}resize(e,t){if(this.width=e*T.devicePixelRatio,this.height=t*T.devicePixelRatio,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const e of this.style.order)this.style._mergedLayers[e].resize()}setup(){const e=this.context,t=new gt;t.emplaceBack(0,0),t.emplaceBack(ae,0),t.emplaceBack(0,ae),t.emplaceBack(ae,ae),this.tileExtentBuffer=e.createVertexBuffer(t,yt.members),this.tileExtentSegments=Ye.simpleSegment(0,0,4,2);const i=new gt;i.emplaceBack(0,0),i.emplaceBack(ae,0),i.emplaceBack(0,ae),i.emplaceBack(ae,ae),this.debugBuffer=e.createVertexBuffer(i,yt.members),this.debugSegments=Ye.simpleSegment(0,0,4,5);const s=new gt;s.emplaceBack(-1,-1),s.emplaceBack(1,-1),s.emplaceBack(-1,1),s.emplaceBack(1,1),this.viewportBuffer=e.createVertexBuffer(s,yt.members),this.viewportSegments=Ye.simpleSegment(0,0,4,2);const o=new Xe;o.emplaceBack(0,0,0,0),o.emplaceBack(ae,0,ae,0),o.emplaceBack(0,ae,0,ae),o.emplaceBack(ae,ae,ae,ae),this.mercatorBoundsBuffer=e.createVertexBuffer(o,Gl.members),this.mercatorBoundsSegments=Ye.simpleSegment(0,0,4,2);const r=new Ke;r.emplaceBack(0,1,2),r.emplaceBack(2,1,3),this.quadTriangleIndexBuffer=e.createIndexBuffer(r);const n=new vt;for(const e of[0,1,3,2,0])n.emplaceBack(e);this.debugIndexBuffer=e.createIndexBuffer(n),this.emptyTexture=new k(e,new E({width:1,height:1},Uint8Array.of(0,0,0,0)),e.gl.RGBA8),this.identityMat=Bt();const a=this.context.gl;this.stencilClearMode=new Pu({func:a.ALWAYS,mask:0},0,255,a.ZERO,a.ZERO,a.ZERO),this.loadTimeStamps.push(performance.now())}getMercatorTileBoundsBuffers(){return{tileBoundsBuffer:this.mercatorBoundsBuffer,tileBoundsIndexBuffer:this.quadTriangleIndexBuffer,tileBoundsSegments:this.mercatorBoundsSegments}}getTileBoundsBuffers(e){return e._makeTileBoundsBuffers(this.context,this.transform.projection),e._tileBoundsBuffer?{tileBoundsBuffer:e._tileBoundsBuffer,tileBoundsIndexBuffer:e._tileBoundsIndexBuffer,tileBoundsSegments:e._tileBoundsSegments}:this.getMercatorTileBoundsBuffers()}clearStencil(){const e=this.context.gl;this.nextStencilID=1,this.currentStencilSource=void 0,this._tileClippingMaskIDs=new Map,this._grouped3DStencil=null,this.getOrCreateProgram("clippingMask").draw(this,e.TRIANGLES,Cu.disabled,this.stencilClearMode,zu.disabled,A_.disabled,hd(this.identityMat),"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments)}resetStencilClippingMasks(){this.terrain||(this.currentStencilSource=void 0,this._tileClippingMaskIDs=new Map)}_renderTileClippingMasks(e,t,i){if(!t||this.currentStencilSource===t.id||!e.isTileClipped()||!i||0===i.length)return;if(this._tileClippingMaskIDs&&!this.terrain){let e=!1;for(const t of i)if(!this._tileClippingMaskIDs.has(t.key)){e=!0;break}if(!e)return}this.currentStencilSource=t.id;const s=this.context,o=s.gl;this.nextStencilID+i.length-1>253&&this.clearStencil(),s.setColorMode(zu.disabled),s.setDepthMode(Cu.disabled);const r=this.getOrCreateProgram("clippingMask");this._tileClippingMaskIDs=new Map;for(const e of i){const i=t.getTile(e),s=this.nextStencilID++;this._tileClippingMaskIDs.set(e.key,s);const{tileBoundsBuffer:n,tileBoundsIndexBuffer:a,tileBoundsSegments:l}=this.getTileBoundsBuffers(i);r.draw(this,o.TRIANGLES,Cu.disabled,new Pu({func:o.ALWAYS,mask:0},s,255,o.KEEP,o.KEEP,o.REPLACE),zu.disabled,A_.disabled,hd(e.projMatrix),"$clipping",n,a,l)}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID>253&&this.clearStencil();const e=this.nextStencilID++,t=this.context.gl;return new Pu({func:t.NOTEQUAL,mask:255},e,255,t.KEEP,t.KEEP,t.REPLACE)}_beginGrouped3DDepthPrepass(e,t){const i=this.currentLayer;if(!e[i].hasBlended3DDepthPrepass())return;const s=[];let o=i;for(let t=i;t<e.length;t++){const i=e[t];if(!i.isHidden(this.transform.zoom)){if(!i.hasBlended3DDepthPrepass()||s.includes(i.type))break;s.push(i.type),o=t+1}}if(!(s.length<2)){for(this._grouped3DDepthPrepassStart=i,this._grouped3DDepthPrepassEnd=o,this._grouped3DStencil=null,this.depthPrepassPhase=!0,this.currentLayer=i;this.currentLayer<o;this.currentLayer++){const i=e[this.currentLayer],s=this.style.getLayerSourceCache(i);this.renderLayer(this,s,i,t(i,s))}this.depthPrepassPhase=!1,this.currentLayer=i}}hasGrouped3DDepthPrepass(e){return e>=this._grouped3DDepthPrepassStart&&e<this._grouped3DDepthPrepassEnd}stencilModeFor3DGroup(e){return this.hasGrouped3DDepthPrepass(e)?(this._grouped3DStencil||(this._grouped3DStencil=this.stencilModeFor3D()),this.currentStencilSource=void 0,this._grouped3DStencil):this.stencilModeFor3D()}stencilModeForClipping(e){if(this.terrain)return this.terrain.stencilModeForRTTOverlap(e);const t=this.context.gl,i=this._tileClippingMaskIDs.get(e.key);return new Pu({func:t.EQUAL,mask:255},i,0,t.KEEP,t.KEEP,t.REPLACE)}stencilConfigForOverlap(e,t=254){const i=this.context.gl,s=e.sort((e,t)=>t.overscaledZ-e.overscaledZ),o=s.at(-1).overscaledZ,r=s[0].overscaledZ-o+1;if(r>1){this.currentStencilSource=void 0,this.nextStencilID+r>t&&this.clearStencil();const e={};for(let t=0;t<r;t++)e[t+o]=new Pu({func:i.GEQUAL,mask:255},t+this.nextStencilID,255,i.KEEP,i.KEEP,i.REPLACE);return this.nextStencilID+=r,[e,s]}return[{[o]:Pu.disabled},s]}colorModeForRenderPass(){const e=this.context.gl;if(this._showOverdrawInspector){const t=1/8;return new zu([e.CONSTANT_COLOR,e.ONE,e.CONSTANT_COLOR,e.ONE],new S(t,t,t,0),[!0,!0,!0,!0])}return"opaque"===this.renderPass?zu.unblended:zu.alphaBlended}isEmissiveMrtActive(){return"mrt-fallback"===this.emissiveMode||"mrt-full-rgba"===this.emissiveMode}colorModeForDrapableLayerRenderPass(e){const t=this.context.gl;return(()=>this.style&&this.style.enable3dLights()&&!!this._terrain&&this._terrain.renderingToTexture)()&&"translucent"===this.renderPass?null!=e&&!this.isEmissiveMrtActive()||"constant"===this.emissiveMode?new zu([t.ONE,t.ONE_MINUS_SRC_ALPHA,t.CONSTANT_ALPHA,t.ONE_MINUS_SRC_ALPHA],new S(0,0,0,e??0),[!0,!0,!0,!0]):"dual-source-blending"===this.emissiveMode?new zu([t.ONE,t.ONE_MINUS_SRC_ALPHA,this.context.extBlendFuncExtended.SRC1_ALPHA_WEBGL,t.ONE_MINUS_SRC_ALPHA],S.transparent,[!0,!0,!0,!0]):this.colorModeForRenderPass():this.colorModeForRenderPass()}depthModeForSublayer(e,t,i,s=!1){if(this.depthOcclusion)return new Cu(this.context.gl.GREATER,Cu.ReadOnly,this.depthRangeFor3D);if(!this.opaquePassEnabledForLayer()&&!s)return Cu.disabled;const o=1-((1+this.currentLayer)*this.numSublayers+e)*this.depthEpsilon;return new Cu(i||this.context.gl.LEQUAL,t,[o,o])}opaquePassEnabledForLayer(){return this.currentLayer<this.opaquePassCutoff}blitDepth(){const e=this.context.gl,t=Math.ceil(this.width),i=Math.ceil(this.height),s=this.context.bindFramebuffer.get(),o=e.getParameter(e.TEXTURE_BINDING_2D);this.depthFBO&&this.depthFBO.width===t&&this.depthFBO.height===i||(this.depthFBO&&(this.depthFBO.destroy(),this.depthFBO=void 0,this.depthTexture=void 0),0!==t&&0!==i&&(this.depthFBO=new S_(this.context,t,i,0,"texture"),this.depthTexture=new k(this.context,{width:t,height:i,data:null},e.DEPTH24_STENCIL8),this.depthFBO.depthAttachment.set(this.depthTexture.texture))),this.context.bindFramebuffer.set(s),e.bindTexture(e.TEXTURE_2D,o),this.depthFBO&&(e.bindFramebuffer(e.READ_FRAMEBUFFER,null),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,this.depthFBO.framebuffer),e.blitFramebuffer(0,0,t,i,0,0,t,i,e.DEPTH_BUFFER_BIT,e.NEAREST),e.bindFramebuffer(e.FRAMEBUFFER,this.context.bindFramebuffer.current))}render(e,t){this.context.sweepPendingPrograms(),this.frameTimeDelta=0===this.lastPaintStartTimeStamp?0:t.paintStartTimeStamp-this.lastPaintStartTimeStamp,this.lastPaintStartTimeStamp=t.paintStartTimeStamp,this._wireframeDebugCache.update(this.frameCounter),this.style=e,this.options=t;const{directionalLight:i,ambientLight:s}=e;this._lightsUniforms=e.enable3dLights()&&i&&s?Du(i,s,e):null;const o=this.transform;this._fogUniforms=e.fog?((e,t,i,s,o,r,n,a,l,c)=>{const h=e.transform,d="none"===t.properties.get("color-use-theme"),u=t.properties.get("color").toNonPremultipliedRenderColor(d?null:e.style.getLut(t.scope)).toArray01();u[3]=i;const _=e.frameCounter/1e3%1,[p,f]=t.properties.get("vertical-range");return{u_fog_matrix:e.identityMat,u_fog_range:t.getRangeForProjection(),u_fog_color:u,u_fog_horizon_blend:t.properties.get("horizon-blend"),u_fog_vertical_limit:[Math.min(p,f),f],u_fog_temporal_offset:_,u_frustum_tl:s,u_frustum_tr:o,u_frustum_br:r,u_frustum_bl:n,u_globe_pos:a,u_globe_radius:l,u_viewport:c,u_globe_transition:K(h.zoom),u_is_globe:+("globe"===h.projection.name)}})(this,e.fog,e.fog.getOpacity(o.pitch),o.frustumCorners.TL,o.frustumCorners.TR,o.frustumCorners.BR,o.frustumCorners.BL,o.globeCenterInViewSpace,o.globeRadius,[this.width,this.height]):null,this.frcCoverageSnapshot&&!this.frcCoverageSnapshot.empty()&&(!this.frcCoverageRenderer&&Il.FrcCoverageRenderer&&(this.frcCoverageRenderer=new Il.FrcCoverageRenderer),this.frcCoverageRenderer&&this.frcCoverageRenderer.update(this.context,this.frcCoverageSnapshot.tiles));const r=this.style._mergedLayers,n=!(!this.terrain||!this.terrain.enabled),a=()=>this.style._getOrder(n);let l=a(),c=!1,h=!1,d=null,u=0,_=!1;for(const e of l){const t=r[e];"none"!==t.visibility&&("circle"===t.type?c=!0:"building"===t.type?(d=t,++u):"symbol"===t.type&&(t.hasOcclusionOpacityProperties?h=!0:c=!0))}this.updateEmissiveMode();let p=l.map(e=>r[e]);const f=this.style._mergedSourceCaches;this.imageManager=e.imageManager,this.modelManager=e.modelManager,this.now=T.now(),this.symbolFadeChange=e.placement?e.placement.symbolFadeChange(this.now):1,this.imageManager.beginFrame();for(const e in f){const t=f[e];t.used&&(t.prepare(this.context),t.getSource().usedInConflation&&++u)}let m=!1;for(const e of p)e.isHidden(this.transform.zoom)||("clip"===e.type&&(m=!0),this.prepareLayer(e));const g={},v={},y={},x={},b={};for(const e in f){const t=f[e];g[e]=t.getVisibleCoordinates(),v[e]=g[e].slice().reverse(),y[e]=t.getVisibleCoordinates(!0).reverse(),x[e]=t.getShadowCasterCoordinates(),b[e]=t.sortCoordinatesByDistance(g[e])}const w=e=>{const t=this.style.getLayerSourceCache(e);return t&&t.used?t.getSource():null};if(u||m||this._clippingActiveLastFrame){const e=[],t=[];let i=0;for(const s of p)this.isSourceForClippingOrConflation(s,w(s))&&(e.push(s),t.push(i)),i++;if(e&&(m||e.length>1)||this._clippingActiveLastFrame){m=!1;const i=[];for(let s=0;s<e.length;s++){const o=e[s],r=t[s],n=this.style.getLayerSourceCache(o);if(!n||!n.used||!n.getSource().usedInConflation&&"clip"!==o.type&&"building"!==o.type)continue;let a=lr,l=gi.None;const c=[];let h=!0;if("building"===o.type)a=cr;else if("clip"===o.type)if(a=r,o.isHidden(this.transform.zoom))h=!1;else{if(!o.layout){h=!1;continue}for(const e of o.layout.get("clip-layer-types"))l|="model"===e?gi.Model:"symbol"===e?gi.Symbol:gi.FillExtrusion;for(const e of o.layout.get("clip-layer-scope"))c.push(C(e,o.scope));m=!0}h&&i.push({layer:o.fqid,cache:n,order:a,clipMask:l,clipScope:c})}this.replacementSource.setSources(i),_=!0}}this._clippingActiveLastFrame=m,_||this.replacementSource.clear(),this.conflationActive=_,this.minCutoffZoom=0,this.longestCutoffRange=0,this.maxFrontCutoffRawStart=0,this.opaquePassCutoff=1/0,this._lastOcclusionLayer=-1,this.layersWithOcclusionOpacity=[];for(let e=0;e<p.length;e++){const t=p[e];if("none"===t.visibility)continue;const i=t.cutoffRange();if(this.longestCutoffRange=Math.max(i,this.longestCutoffRange),i>0){const e=w(t);e&&(this.minCutoffZoom=Math.max(e.minzoom,this.minCutoffZoom)),t.minzoom&&(this.minCutoffZoom=Math.max(t.minzoom,this.minCutoffZoom))}t.is3D(n)&&(this.opaquePassCutoff===1/0&&(this.opaquePassCutoff=e),this._lastOcclusionLayer=e)}const E=this.style&&this.style.fog;E?(this._fogVisible=0!==E.getOpacity(this.transform.pitch),this._fogVisible&&"globe"!==this.transform.projection.name&&(this._fogVisible=E.isVisibleOnFrustum(this.transform.cameraFrustum))):this._fogVisible=!1,this._cachedTileFogOpacities.clear(),this.terrain&&(this.terrain.updateTileBinding(y),this.opaquePassCutoff=0,l=a(),p=l.map(e=>r[e])),this.style.enable3dLights()&&!this._shadowRenderer&&Rp(this);const I=this._shadowRenderer;if(I){I.updateShadowParameters(this.transform,this.style.directionalLight,x);for(const e in f)for(const t of g[e]){let e={min:0,max:0};this.terrain&&(e=this.terrain.getMinMaxForTile(t)||e),I.addShadowReceiver(t.toUnwrapped(),e.min,e.max)}}"globe"!==this.transform.projection.name||this.globeSharedBuffers||(this.globeSharedBuffers=new ar(this.context)),this.style.fog&&this.transform.projection.supportsFog?(this._atmosphere||(this._atmosphere=new vp),this._atmosphere.update(this)):this._atmosphere&&(this._atmosphere.destroy(),this._atmosphere=void 0);let D=!(!this.style||!this.style.snow),R=!(!this.style||!this.style.rain);if(!D&&!R||Il.loaded||Dl(),D&&!this._snow&&Il.Snow&&(this._snow=new Il.Snow),!D&&this._snow&&(this._snow.destroy(),delete this._snow),R&&!this._rain&&Il.Rain&&(this._rain=new Il.Rain),!R&&this._rain&&(this._rain.destroy(),delete this._rain),this._snow&&this._snow.update(this),this._rain&&this._rain.update(this),d&&(!this.buildingTileBorderManager&&Il.BuildingTileBorderManager&&(this.buildingTileBorderManager=new Il.BuildingTileBorderManager),this.buildingTileBorderManager)){const e=this.style.getLayerSourceCache(d);this.buildingTileBorderManager.updateBorders(e,d)}if(!pn.has(this.context.gl))return;this.renderPass="offscreen";for(const t of p){const i=e.getLayerSourceCache(t);if(!t.hasOffscreenPass()||t.isHidden(this.transform.zoom))continue;const s=i?v[i.id]:void 0;("custom"===t.type||"raster"===t.type||"raster-particle"===t.type||t.isSky()||s&&s.length)&&this.renderLayer(this,i,t,s)}this.depthRangeFor3D=[0,1-(p.length+2)*this.numSublayers*this.depthEpsilon],this._shadowRenderer&&(this.renderPass="shadow",this._shadowRenderer.drawShadowPass(this.style,x)),this.context.bindFramebuffer.set(null),this.context.viewport.set([0,0,this.width,this.height]);const A="globe"===this.transform.projection.name||this.transform.isHorizonVisible(),L=(()=>{if(t.showOverdrawInspector)return S.black;const e=this.style.fog;if(e&&this.transform.projection.supportsFog){const t=this.style.getLut(e.scope);if(!A){const i="none"===e.properties.get("color-use-theme"),s=e.properties.get("color").toNonPremultipliedRenderColor(i?null:t).toArray01();return new S(...s)}if(A){const i="none"===e.properties.get("space-color-use-theme"),s=e.properties.get("space-color").toNonPremultipliedRenderColor(i?null:t).toArray01();return new S(...s)}}return S.transparent})();if(this.context.clear({color:L,depth:1}),this.clearStencil(),this._showOverdrawInspector=t.showOverdrawInspector,this.renderPass="opaque",this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&A&&this._atmosphere.drawStars(this,this.style.fog),!this.terrain)for(this.currentLayer=l.length-1;this.currentLayer>=0;this.currentLayer--){const t=p[this.currentLayer],i=e.getLayerSourceCache(t);if(t.isSky())continue;const s=i?(t.is3D(n)?b:v)[i.id]:void 0;this._renderTileClippingMasks(t,i,s),this.renderLayer(this,i,t,s)}if(this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&A&&this._atmosphere.drawAtmosphereGlow(this,this.style.fog),this.renderPass="sky",(!this._atmosphere||K(this.transform.zoom)>0)&&("globe"===this.transform.projection.name||this.transform.isHorizonVisible()))for(this.currentLayer=0;this.currentLayer<l.length;this.currentLayer++){const t=p[this.currentLayer],i=e.getLayerSourceCache(t);t.isSky()&&this.renderLayer(this,i,t,i?v[i.id]:void 0)}function P(e,t){let i;return t&&(i=("symbol"===e.type?y:e.is3D(n)?b:v)[t.id]),i}if(this.renderPass="translucent","globe"===this.transform.projection.name){for(this.renderElevatedRasterBackface=!0,this.currentLayer=0;this.currentLayer<l.length;){const t=p[this.currentLayer];if("raster"===t.type||"raster-particle"===t.type){const i=e.getLayerSourceCache(t);this.renderLayer(this,i,t,P(t,i))}++this.currentLayer}this.renderElevatedRasterBackface=!1}this.currentLayer=0,this.firstLightBeamLayer=Number.MAX_SAFE_INTEGER,this.depthPrepassPhase=!1,this._grouped3DDepthPrepassStart=-1,this._grouped3DDepthPrepassEnd=-1,this._grouped3DStencil=null;const M=I?I.getGroundShadowLayerIndex():-1;let O=!1,z=-1;for(let e=0;e<l.length;++e){const t=p[e];t.isHidden(this.transform.zoom)||t.is3D(n)&&(z=e)}h&&-1===z&&(c=!0);let F=!1;for(;this.currentLayer<l.length;){const t=p[this.currentLayer],i=e.getLayerSourceCache(t);if(t.isSky())++this.currentLayer;else if(this.terrain&&this.style.isLayerDraped(t)){if(t.isHidden(this.transform.zoom)){++this.currentLayer;continue}this.currentLayer=this.terrain.renderBatch(this.currentLayer),this._lastOcclusionLayer=Math.max(this.currentLayer,this._lastOcclusionLayer)}else{if(!F&&t.is3D(n)&&!n){const e=this.currentLayer,t=e=>{for(this.currentLayer=0;this.currentLayer<p.length;this.currentLayer++){const t=p[this.currentLayer];if("fill"===t.type&&Il.drawDepthPrepass){const i=this.style.getLayerSourceCache(t);Il.drawDepthPrepass(this,i,t,P(t,i),e)}}};t("initialize"),t("reset"),this.currentLayer=e,F=!0}if(c&&!O&&this.terrain&&!this.transform.isOrthographic&&(O=!0,this.blitDepth()),h&&-1!==z&&this.currentLayer===z+1&&!this.transform.isOrthographic&&this.blitDepth(),!n&&this._grouped3DDepthPrepassEnd<=this.currentLayer&&this._beginGrouped3DDepthPrepass(p,P),this.terrain||this._renderTileClippingMasks(t,i,i?g[i.id]:void 0),this.renderLayer(this,i,t,P(t,i)),!this.terrain&&I&&this.currentLayer===M){{this.clearStencil(),this.resetStencilClippingMasks();const e=this.currentLayer;for(this.currentLayer=0;this.currentLayer<p.length;this.currentLayer++){const e=p[this.currentLayer];if("fill"===e.type&&Il.drawGroundShadowMask){const t=this.style.getLayerSourceCache(e);Il.drawGroundShadowMask(this,t,e,P(e,t))}}this.currentLayer=e}if(I.drawGroundShadows(),this.firstLightBeamLayer<=this.currentLayer){const t=this.currentLayer;for(this.renderPass="light-beam",this.currentLayer=this.firstLightBeamLayer;this.currentLayer<=t;this.currentLayer++){const t=p[this.currentLayer];if(!t.hasLightBeamPass())continue;const i=e.getLayerSourceCache(t);this.renderLayer(this,i,t,i?v[i.id]:void 0)}this.currentLayer=t,this.renderPass="translucent"}}if(this.currentLayer>=this._lastOcclusionLayer&&this.layersWithOcclusionOpacity.length>0){const t=this.currentLayer;this.depthOcclusion=!0;for(const t of this.layersWithOcclusionOpacity){this.currentLayer=t;const i=p[this.currentLayer],s=e.getLayerSourceCache(i),o=s?v[s.id]:void 0;this.terrain||this._renderTileClippingMasks(i,s,s?g[s.id]:void 0),this.renderLayer(this,s,i,o)}this.depthOcclusion=!1,this.currentLayer=t,this.renderPass="translucent",this.layersWithOcclusionOpacity=[]}++this.currentLayer}}if(this.terrain&&this.terrain.postRender(),this._snow&&this._snow.draw(this),this._rain&&this._rain.draw(this),this.options.showTileBoundaries||this.options.showQueryGeometry||this.options.showTileAABBs){let t=null;p.forEach(i=>{const s=e.getLayerSourceCache(i);s&&!i.isHidden(this.transform.zoom)&&s.getVisibleCoordinates().length&&(!t||t.getSource().maxzoom<s.getSource().maxzoom)&&(t=s)}),t&&this.options.showTileBoundaries&&Ca.drawDebug&&Ca.drawDebug(this,t,t.getVisibleCoordinates(),S.red,!1,this.options.showParseStatus)}this.options.showPadding&&Ca.drawDebugPadding&&Ca.drawDebugPadding(this),Ca.drawPlacementDebug&&Ca.drawPlacementDebug(this),this.context.setDefault(),this.frameCounter=(this.frameCounter+1)%Number.MAX_SAFE_INTEGER,this.tileLoaded&&this.options.speedIndexTiming&&(this.loadTimeStamps.push(performance.now()),this.saveCanvasCopy()),_||(this.conflationActive=!1)}prepareLayer(e){this.gpuTimingStart(e);const{unsupportedLayers:t}=this.transform.projection,i=!t||!t.includes(e.type);if(Dp[e.type]&&(i||this.terrain&&"custom"===e.type)){const t=this.style.getLayerSourceCache(e);Dp[e.type](e,t,this)}this.gpuTimingEnd()}renderLayer(e,t,i,s){i.isHidden(this.transform.zoom)||("background"===i.type||"sky"===i.type||"custom"===i.type||"model"===i.type||"raster"===i.type||"raster-particle"===i.type||s&&s.length)&&(this.id=i.id,this.gpuTimingStart(i),(!e.transform.projection.unsupportedLayers||!e.transform.projection.unsupportedLayers.includes(i.type)||e.terrain&&"custom"===i.type)&&"clip"!==i.type&&"slot"!==i.type&&"placement-group"!==i.type&&Sp[i.type]&&Sp[i.type](e,t,i,s,this.style.placement?this.style.placement.variableOffsets:{},this.options.isInitialLoad),Sp[i.type]||(i.mayUse("HD")&&async function(){await Dl(),Object.assign(Sp,{building:Il.drawBuilding,"raster-particle":Il.drawRasterParticle}),Object.assign(Dp,{"raster-particle":Il.prepareRasterParticle})}(),i.mayUse("Standard")&&Rp(e)),this.gpuTimingEnd())}gpuTimingStart(e){if(!this.options.gpuTiming)return;const t=this.context.extTimerQuery,i=this.context.gl;let s=this.gpuTimers[e.id];s||(s=this.gpuTimers[e.id]={calls:0,cpuTime:0,query:i.createQuery()}),s.calls++,i.beginQuery(t.TIME_ELAPSED_EXT,s.query)}gpuTimingDeferredRenderStart(){if(this.options.gpuTimingDeferredRender){const e=this.context.extTimerQuery,t=this.context.gl,i=t.createQuery();this.deferredRenderGpuTimeQueries.push(i),t.beginQuery(e.TIME_ELAPSED_EXT,i)}}gpuTimingDeferredRenderEnd(){this.options.gpuTimingDeferredRender&&this.context.gl.endQuery(this.context.extTimerQuery.TIME_ELAPSED_EXT)}gpuTimingEnd(){this.options.gpuTiming&&this.context.gl.endQuery(this.context.extTimerQuery.TIME_ELAPSED_EXT)}collectGpuTimers(){const e=this.gpuTimers;return this.gpuTimers={},e}collectDeferredRenderGpuQueries(){const e=this.deferredRenderGpuTimeQueries;return this.deferredRenderGpuTimeQueries=[],e}queryGpuTimers(e){const t={};for(const i in e){const s=e[i],o=this.context.extTimerQuery,r=o.getQueryParameter(s.query,this.context.gl.QUERY_RESULT)/1e6;o.deleteQueryEXT(s.query),t[i]=r}return t}queryGpuTimeDeferredRender(e){if(!this.options.gpuTimingDeferredRender)return 0;const t=this.context.gl;let i=0;for(const s of e)i+=t.getQueryParameter(s,t.QUERY_RESULT)/1e6,t.deleteQuery(s);return i}translatePosMatrix(e,t,i,s,o){if(!i[0]&&!i[1])return e;const r=o?"map"===s?this.transform.angle:0:"viewport"===s?-this.transform.angle:0;if(r){const e=Math.sin(r),t=Math.cos(r);i=[i[0]*t-i[1]*e,i[0]*e+i[1]*t]}const n=[o?i[0]:Te(t,i[0],this.transform.zoom),o?i[1]:Te(t,i[1],this.transform.zoom),0],a=new Float32Array(16);return At(a,e,n),a}saveTileTexture(e){if(e.context!==this.context)return;const t=e.size[0],i=this._tileTextures[t];i?i.push(e):this._tileTextures[t]=[e]}getTileTexture(e){const t=this._tileTextures[e];return t&&t.length>0?t.pop():null}terrainRenderModeElevated(){return this.style&&this.style.hasTerrain()&&!!this.terrain&&!this.terrain.renderingToTexture||this.forceTerrainMode}linearFloatFilteringSupported(){return null!=this.context.extTextureFloatLinear}currentGlobalDefines(e,t,i,s,o){const r=void 0===i?!!this._terrain&&this._terrain.renderingToTexture:i,n=void 0===s?this.terrainRenderModeElevated():s,a=void 0===o?"globe"===this.transform.projection.name:o,l=[];return this.style&&this.style.enable3dLights()&&("globeRaster"===e||"terrainRaster"===e?(l.push("LIGHTING_3D_MODE"),l.push("LIGHTING_3D_ALPHA_EMISSIVENESS"),"mrt-full-rgba"===this.emissiveMode&&l.push("USE_MRT1_RGBA")):r||l.push("LIGHTING_3D_MODE")),n&&(l.push("TERRAIN"),this.linearFloatFilteringSupported()&&l.push("TERRAIN_DEM_FLOAT_FORMAT")),a&&l.push("GLOBE"),!this._fogVisible||r||void 0!==t&&!t||l.push("FOG"),r&&l.push("RENDER_TO_TEXTURE"),this._showOverdrawInspector&&l.push("OVERDRAW_INSPECTOR"),l}getOrCreateProgram(e,t){const{defines:i,config:s,overrideFog:o,overrideRtt:r,overrideTerrain:n,overrideGlobe:a,precompiled:l}=t||{},c=this.currentGlobalDefines(e,o,r,n,a),h=this.getShaderSource(e),d=Nu.cacheKey(h,e,c,i,s);let u=this.cache.get(d);if(!u){const t=Il.programUniforms,o=ue.programUniforms,r=Ed[e]||t&&t[e]||o&&o[e],n=i?c.concat(i):c;u=new Nu(this.context,e,h,s,r,n,l),this.cache.set(d,u)}return u}getShaderSource(e){const t=Il.shaders,i=ue.shaders,s=Al.shaders;return du[e]||t&&t[e]||i&&i[e]||s&&s[e]}setCustomLayerDefaults(){this.context.unbindVAO(),this.context.cullFace.setDefault(),this.context.frontFace.setDefault(),this.context.cullFaceSide.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 k(this.context,this.debugOverlayCanvas,this.context.gl.RGBA8))}destroy(){this._terrain&&this._terrain.destroy(),this._atmosphere&&(this._atmosphere.destroy(),this._atmosphere=void 0),this.globeSharedBuffers&&this.globeSharedBuffers.destroy(),this.emptyTexture.destroy(),this.debugOverlayTexture&&this.debugOverlayTexture.destroy(),this._wireframeDebugCache.destroy(),this.depthFBO&&(this.depthFBO.destroy(),this.depthFBO=void 0,this.depthTexture=void 0),this.emptyDepthTexture&&this.emptyDepthTexture.destroy(),this._destroyed=!0}prepareDrawTile(){this.terrain&&this.terrain.prepareDrawTile()}uploadCommonLightUniforms(e,t,i){const s=i&&this._lightsUniforms?Du(this.style.directionalLight,this.style.ambientLight,this.style,i):this._lightsUniforms;s&&t.setLightsUniformValues(e,s)}uploadCommonUniforms(e,t,i,s,o,r){if(this.uploadCommonLightUniforms(e,t,r),this.terrain&&this.terrain.renderingToTexture)return;const n=this._fogUniforms;n&&(n.u_fog_matrix=i?this.transform.calculateFogTileMatrix(i):s||this.identityMat,t.setFogUniformValues(e,n)),o&&t.setCutoffUniformValues(e,o.uniformValues)}setTileLoadedFlag(e){this.tileLoaded=e}saveCanvasCopy(){const e=this.canvasCopy();e&&(this.frameCopies.push(e),this.tileLoaded=!1)}canvasCopy(){const e=this.context.gl,t=e.createTexture();return e.bindTexture(e.TEXTURE_2D,t),e.copyTexImage2D(e.TEXTURE_2D,0,e.RGBA,0,0,e.drawingBufferWidth,e.drawingBufferHeight,0),t}getCanvasCopiesAndTimestamps(){return{canvasCopies:this.frameCopies,timeStamps:this.loadTimeStamps}}averageElevationNeedsEasing(){if(!this.transform._elevation)return!1;const e=this.style&&this.style.fog;return!!e&&0!==e.getOpacity(this.transform.pitch)}getBackgroundTiles(){const e=this._backgroundTiles,t=this._backgroundTiles={},i=this.transform.coveringTiles({tileSize:512});for(const s of i)t[s.key]=e[s.key]||new yc(s,512,this.transform.tileZoom,this,void 0,this.worldview);return t}clearBackgroundTiles(){this._backgroundTiles={}}isSourceForClippingOrConflation(e,t){return!(!e.is3D(!(!this.terrain||!this.terrain.enabled))||"clip"!==e.type&&"building"!==e.type&&(e.minzoom&&e.minzoom>this.transform.zoom||(this.style._clipLayerPresent||"building"!==e.sourceLayer&&"procedural_buildings"!==e.sourceLayer)&&(!t||"batched-model"!==t.type)))}isTileAffectedByFog(e){if(!this._fogVisible)return!1;if("globe"===this.transform.projection.name)return!0;let t=this._cachedTileFogOpacities.get(e.key);return t||(t=this.style.fog.getOpacityForTile(e),this._cachedTileFogOpacities.set(e.key,t)),t[0]>=ne||t[1]>=ne}setupDepthForOcclusion(e,t,i){const s=this.context,o=s.gl,r=!!i;var n;i||(i={u_dem:2,u_dem_prev:4,u_dem_tl:[0,0],u_dem_tl_prev:[0,0],u_dem_scale:0,u_dem_scale_prev:0,u_dem_size:0,u_dem_lerp:1,u_depth:3,u_depth_size_inv:[0,0],u_depth_range_unpack:[0,1],u_occluder_half_size:16,u_occlusion_depth_offset:-1e-4,u_exaggeration:0}),s.activeTexture.set(o.TEXTURE3),e&&this.depthFBO&&this.depthTexture?(this.depthTexture.bind(o.NEAREST,o.CLAMP_TO_EDGE),i.u_depth_size_inv=[1/this.depthFBO.width,1/this.depthFBO.height],i.u_depth_range_unpack=[2/((n=this.depthRangeFor3D)[1]-n[0]),-1-2*n[0]/(n[1]-n[0])],i.u_occluder_half_size=.5*this.occlusionParams.occluderSize,i.u_occlusion_depth_offset=this.occlusionParams.depthOffset):this.emptyDepthTexture.bind(o.NEAREST,o.CLAMP_TO_EDGE),s.activeTexture.set(o.TEXTURE0),r||t.setTerrainUniformValues(s,i)}updateEmissiveMode(){if(this._forceEmissiveMode)return;const e=this.style.hasDataDrivenEmissiveStrength();this.emissiveMode=this._forceFullRgbaEmissive?"mrt-full-rgba":e?this.context.extBlendFuncExtended?"dual-source-blending":"mrt-fallback":"constant"}}function Ap(e,t){let i=!1,s=null;const o=()=>{s=null,i&&(e(),s=setTimeout(o,t),i=!1)};return()=>(i=!0,s||o(),s)}const Lp=/(#.+)?$/;class Pp{constructor(e){this._hashName=e&&encodeURIComponent(e),rt(["_getCurrentHash","_onHashChange","_updateHash"],this),this._updateHash=Ap(this._updateHashUnthrottled.bind(this),300)}addTo(e){return this._map=e,window.addEventListener("hashchange",this._onHashChange,!1),e.on("moveend",this._updateHash),this}remove(){return this._map?(this._map.off("moveend",this._updateHash),window.removeEventListener("hashchange",this._onHashChange,!1),clearTimeout(this._updateHash()),this._map=void 0,this):this}getHashString(){const e=this._map;if(!e)return"";const t=Mp(e);if(this._hashName){const e=this._hashName;let i=!1;const s=location.hash.slice(1).split("&").map(s=>{const o=s.split("=")[0];return o===e?(i=!0,`${o}=${t}`):s}).filter(e=>e);return i||s.push(`${e}=${t}`),`#${s.join("&")}`}return`#${t}`}_getCurrentHash(){const e=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("/")}_onHashChange(){const e=this._map;if(!e)return!1;const t=this._getCurrentHash();if(t.length>=3&&!t.some(e=>isNaN(Number(e)))){const i=e.dragRotate.isEnabled()&&e.touchZoomRotate.isEnabled()?+(t[3]||0):e.getBearing();return e.jumpTo({center:[+t[2],+t[1]],zoom:+t[0],bearing:i,pitch:+(t[4]||0)}),!0}return!1}_updateHashUnthrottled(){history.replaceState(history.state,"",location.href.replace(Lp,this.getHashString()))}}function Mp(e,t){const i=e.getCenter(),s=Math.round(100*e.getZoom())/100,o=Math.ceil((s*Math.LN2+Math.log(512/360/.5))/Math.LN10),r=Math.pow(10,o),n=Math.round(i.lng*r)/r,a=Math.round(i.lat*r)/r,l=e.getBearing(),c=e.getPitch();let h=t?`/${n}/${a}/${s}`:`${s}/${a}/${n}`;return(l||c)&&(h+="/"+Math.round(10*l)/10),c&&(h+=`/${Math.round(c)}`),h}const Op={linearity:.3,easing:hr(0,0,.3,1)},zp={deceleration:2500,maxSpeed:1400,...Op},Fp={deceleration:20,maxSpeed:1400,...Op},kp={deceleration:1e3,maxSpeed:360,...Op},Bp={deceleration:1e3,maxSpeed:90,...Op};class Np{constructor(e){this._map=e,this.clear()}clear(){this._inertiaBuffer=[]}record(e){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:T.now(),settings:e})}_drainInertiaBuffer(){const e=this._inertiaBuffer,t=T.now();for(;e.length>0&&t-e[0].time>160;)e.shift()}_onMoveEnd(e){if(this._map._prefersReducedMotion())return;if(this._drainInertiaBuffer(),this._inertiaBuffer.length<2)return;const t={zoom:0,bearing:0,pitch:0,pan:new m(0,0),pinchAround:void 0,around:void 0};for(const{settings:e}of this._inertiaBuffer)t.zoom+=e.zoomDelta||0,t.bearing+=e.bearingDelta||0,t.pitch+=e.pitchDelta||0,e.panDelta&&t.pan._add(e.panDelta),e.around&&(t.around=e.around),e.pinchAround&&(t.pinchAround=e.pinchAround);const i=this._inertiaBuffer.at(-1).time-this._inertiaBuffer[0].time,s={};if(t.pan.mag()){const o=Vp(t.pan.mag(),i,{...zp,...e||{}});s.offset=t.pan.mult(o.amount/t.pan.mag()),s.center=this._map.transform.center,Up(s,o)}if(t.zoom){const e=Vp(t.zoom,i,Fp);s.zoom=this._map.transform.zoom+e.amount,Up(s,e)}if(t.bearing){const e=Vp(t.bearing,i,kp);s.bearing=this._map.transform.bearing+Ee(e.amount,-179,179),Up(s,e)}if(t.pitch){const e=Vp(t.pitch,i,Bp);s.pitch=this._map.transform.pitch+e.amount,Up(s,e)}if(s.zoom||s.bearing){const e=void 0===t.pinchAround?t.around:t.pinchAround;s.around=e?this._map.unproject(e):this._map.getCenter()}return this.clear(),s.noMoveStart=!0,s}}function Up(e,t){(!e.duration||e.duration<t.duration)&&(e.duration=t.duration,e.easing=t.easing)}function Vp(e,t,i){const{maxSpeed:s,linearity:o,deceleration:r}=i,n=Ee(e*o/(t/1e3),-s,s),a=Math.abs(n)/(r*o);return{easing:i.easing,duration:1e3*a,amount:n*(a/2)}}class jp extends M{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(e,t,i,s={}){const o=Pn(t.getCanvasContainer(),i);super(e,{point:o,lngLat:t.unproject(o),originalEvent:i,...s}),this._defaultPrevented=!1,this.target=t}}class Gp extends M{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(e,t,i){const s="touchend"===e?i.changedTouches:i.touches,o=Mn(t.getCanvasContainer(),s),r=o.map(e=>t.unproject(e)),n=o.reduce((e,t,i,s)=>e.add(t.div(s.length)),new m(0,0));super(e,{points:o,point:n,lngLats:r,lngLat:t.unproject(n),originalEvent:i}),this._defaultPrevented=!1}}class qp extends M{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(e,t){super("wheel",{originalEvent:t}),this._defaultPrevented=!1}}class Zp{constructor(e,t){this._map=e,this._clickTolerance=t.clickTolerance}reset(){this._mousedownPos=void 0}wheel(e){return this._firePreventable(new qp(this._map,e))}mousedown(e,t){return this._mousedownPos=t,this._firePreventable(new jp(e.type,this._map,e))}mouseup(e){this._map.fire(new jp(e.type,this._map,e))}preclick(e){const t=new MouseEvent("preclick",e);this._map.fire(new jp(t.type,this._map,t))}click(e,t){this._mousedownPos&&this._mousedownPos.dist(t)>=this._clickTolerance||(this.preclick(e),this._map.fire(new jp(e.type,this._map,e)))}dblclick(e){return this._firePreventable(new jp(e.type,this._map,e))}mouseover(e){this._map.fire(new jp(e.type,this._map,e))}mouseout(e){this._map.fire(new jp(e.type,this._map,e))}touchstart(e){return this._firePreventable(new Gp(e.type,this._map,e))}touchmove(e){this._map.fire(new Gp(e.type,this._map,e))}touchend(e){this._map.fire(new Gp(e.type,this._map,e))}touchcancel(e){this._map.fire(new Gp(e.type,this._map,e))}_firePreventable(e){if(this._map.fire(e),e.defaultPrevented)return{}}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class Wp{constructor(e){this._map=e}reset(){this._delayContextMenu=!1,this._contextMenuEvent=void 0}mousemove(e){this._map.fire(new jp(e.type,this._map,e))}mousedown(){this._delayContextMenu=!0}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new jp("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent)}contextmenu(e){this._delayContextMenu?this._contextMenuEvent=e:this._map.fire(new jp(e.type,this._map,e)),this._map.listens("contextmenu")&&e.preventDefault()}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class Hp{constructor(e,t){this._map=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&&(Rn(),this._startPos=this._lastPos=t,this._active=!0)}mousemoveWindow(e,t){if(!this._active)return;const i=t,s=this._startPos,o=this._lastPos;if(!s||!o||o.equals(i)||!this._box&&i.dist(s)<this._clickTolerance)return;this._lastPos=i,this._box||(this._box=Tn("div","mapboxgl-boxzoom",this._container),this._container.classList.add("mapboxgl-crosshair"),this._fireEvent("boxzoomstart",e));const r=Math.min(s.x,i.x),n=Math.max(s.x,i.x),a=Math.min(s.y,i.y),l=Math.max(s.y,i.y);this._map._requestDomTask(()=>{this._box&&(this._box.style.transform=`translate(${r}px,${a}px)`,this._box.style.width=n-r+"px",this._box.style.height=l-a+"px")})}mouseupWindow(e,t){if(!this._active)return;const i=this._startPos,s=t;if(i&&0===e.button){if(this.reset(),Ln(),i.x!==s.x||i.y!==s.y)return this._map.fire(new M("boxzoomend",{originalEvent:e})),{cameraAnimation:e=>e.fitScreenCoordinates(i,s,this._map.getBearing(),{linear:!1})};this._fireEvent("boxzoomcancel",e)}}keydown(e){this._active&&27===e.keyCode&&(this.reset(),this._fireEvent("boxzoomcancel",e))}blur(){this.reset()}reset(){this._active=!1,this._container.classList.remove("mapboxgl-crosshair"),this._box&&(this._box.remove(),this._box=null),Cn(),delete this._startPos,delete this._lastPos}_fireEvent(e,t){return this._map.fire(new M(e,{originalEvent:t}))}}function $p(e,t){const i={};for(let s=0;s<e.length;s++)i[e[s].identifier]=t[s];return i}class Xp{constructor(e){this.reset(),this.numTouches=e.numTouches}reset(){this.centroid=void 0,this.startTime=0,this.touches={},this.aborted=!1}touchstart(e,t,i){(this.centroid||i.length>this.numTouches)&&(this.aborted=!0),this.aborted||(0===this.startTime&&(this.startTime=e.timeStamp),i.length===this.numTouches&&(this.centroid=function(e){const t=new m(0,0);for(const i of e)t._add(i);return t.div(e.length)}(t),this.touches=$p(i,t)))}touchmove(e,t,i){if(this.aborted||!this.centroid)return;const s=$p(i,t);for(const e in this.touches){const t=s[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 Yp{constructor(e){this.singleTap=new Xp(e),this.numTaps=e.numTaps,this.reset()}reset(){this.lastTime=1/0,this.lastTap=void 0,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 s=this.singleTap.touchend(e,t,i);if(s){const t=e.timeStamp-this.lastTime<500,i=!this.lastTap||this.lastTap.dist(s)<30;if(t&&i||this.reset(),this.count++,this.lastTime=e.timeStamp,this.lastTap=s,this.count===this.numTaps)return this.reset(),s}}}class Kp{constructor(){this._zoomIn=new Yp({numTouches:1,numTaps:2}),this._zoomOut=new Yp({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 s=this._zoomIn.touchend(e,t,i),o=this._zoomOut.touchend(e,t,i);return s?(this._active=!0,e.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:t=>t.easeTo({duration:300,zoom:t.getZoom()+1,around:t.unproject(s)},{originalEvent:e})}):o?(this._active=!0,e.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:t=>t.easeTo({duration:300,zoom:t.getZoom()-1,around:t.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}}const Jp=0,Qp=2,ef={[Jp]:1,[Qp]:2},tf={Control:"ctrlKey",Alt:"altKey",Shift:"shiftKey",Meta:"metaKey"};class sf{constructor(e){this.reset(),this._clickTolerance=e.clickTolerance||1}blur(){this.reset()}reset(){this._active=!1,this._moved=!1,this._lastPoint=void 0,this._eventButton=void 0}_correctButton(e,t){return!1}_move(e,t){return{}}mousedown(e,t){if(this._lastPoint)return;const i=On(e);this._correctButton(e,i)&&(this._lastPoint=t,this._eventButton=i)}mousemoveWindow(e,t){const i=this._lastPoint;if(i)if(e.preventDefault(),null!=this._eventButton&&function(e,t){const i=ef[t];return void 0===e.buttons||(e.buttons&i)!==i}(e,this._eventButton))this.reset();else if(this._moved||!(t.dist(i)<this._clickTolerance))return this._moved=!0,this._lastPoint=t,this._move(i,t)}mouseupWindow(e){this._lastPoint&&On(e)===this._eventButton&&(this._moved&&Ln(),this.reset())}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class of extends sf{mousedown(e,t){super.mousedown(e,t),this._lastPoint&&(this._active=!0)}_correctButton(e,t){return 0===t&&!e.ctrlKey}_move(e,t){return{around:t,panDelta:t.sub(e)}}}class rf extends sf{constructor(e){super(e),this._pitchRotateKey=e.pitchRotateKey?tf[e.pitchRotateKey]:void 0}_correctButton(e,t){return this._pitchRotateKey?0===t&&e[this._pitchRotateKey]:0===t&&e.ctrlKey||2===t}_move(e,t){const i=.8*(t.x-e.x);if(i)return this._active=!0,{bearingDelta:i}}contextmenu(e){this._pitchRotateKey||e.preventDefault()}}class nf extends sf{constructor(e){super(e),this._pitchRotateKey=e.pitchRotateKey?tf[e.pitchRotateKey]:void 0}_correctButton(e,t){return this._pitchRotateKey?0===t&&e[this._pitchRotateKey]:0===t&&e.ctrlKey||2===t}_move(e,t){const i=-.5*(t.y-e.y);if(i)return this._active=!0,{pitchDelta:i}}contextmenu(e){this._pitchRotateKey||e.preventDefault()}}class af{constructor(e,t){this._map=e,this._el=e.getCanvasContainer(),this._minTouches=1,this._clickTolerance=t.clickTolerance||1,this.reset(),rt(["_addTouchPanBlocker","_showTouchPanBlockerAlert"],this)}reset(){this._active=!1,this._touches={},this._sum=new m(0,0)}touchstart(e,t,i){return this._calculateTransform(e,t,i)}touchmove(e,t,i){if(this._active&&!(i.length<this._minTouches)){if(this._map._cooperativeGestures&&!this._map.isMoving()){if(1===i.length&&!dr())return void this._showTouchPanBlockerAlert();"hidden"!==this._alertContainer.style.visibility&&(this._alertContainer.style.visibility="hidden",clearTimeout(this._alertTimer))}return e.cancelable&&e.preventDefault(),this._calculateTransform(e,t,i)}}touchend(e,t,i){this._calculateTransform(e,t,i),this._active&&i.length<this._minTouches&&this.reset()}touchcancel(){this.reset()}_calculateTransform(e,t,i){i.length>0&&(this._active=!0);const s=$p(i,t),o=new m(0,0),r=new m(0,0);let n=0;for(const e in s){const t=s[e],i=this._touches[e];i&&(o._add(t),r._add(t.sub(i)),n++,s[e]=t)}if(this._touches=s,n<this._minTouches||!r.mag())return;const a=r.div(n);return this._sum._add(a),this._sum.mag()<this._clickTolerance?void 0:{around:o.div(n),panDelta:a}}enable(){this._enabled=!0,this._map._cooperativeGestures&&(this._addTouchPanBlocker(),this._el.classList.add("mapboxgl-touch-pan-blocker-override","mapboxgl-scrollable-page"))}disable(){this._enabled=!1,this._map._cooperativeGestures&&(clearTimeout(this._alertTimer),this._alertContainer.remove(),this._el.classList.remove("mapboxgl-touch-pan-blocker-override","mapboxgl-scrollable-page")),this.reset()}isEnabled(){return!!this._enabled}isActive(){return!!this._active}_addTouchPanBlocker(){this._map&&!this._alertContainer&&(this._alertContainer=Tn("div","mapboxgl-touch-pan-blocker",this._map._container),this._alertContainer.textContent=this._map._getUIString("TouchPanBlocker.Message"),this._alertContainer.style.fontSize=`${Math.max(10,Math.min(24,Math.floor(.05*this._el.clientWidth)))}px`)}_showTouchPanBlockerAlert(){this._alertContainer.style.visibility="visible",this._alertContainer.classList.add("mapboxgl-touch-pan-blocker-show"),this._alertContainer.setAttribute("role","alert"),clearTimeout(this._alertTimer),this._alertTimer=window.setTimeout(()=>{this._alertContainer.classList.remove("mapboxgl-touch-pan-blocker-show"),this._alertContainer.removeAttribute("role")},500)}}class lf{constructor(){this.reset()}reset(){this._active=!1,this._firstTwoTouches=void 0}_start(e){}_move(e,t,i){return{}}touchstart(e,t,i){this._firstTwoTouches||i.length<2||(this._firstTwoTouches=[i[0].identifier,i[1].identifier],this._start([t[0],t[1]]))}touchmove(e,t,i){const s=this._firstTwoTouches;if(!s)return;e.preventDefault();const[o,r]=s,n=cf(i,t,o),a=cf(i,t,r);if(!n||!a)return;const l=this._aroundCenter?null:n.add(a).div(2);return this._move([n,a],l,e)}touchend(e,t,i){if(!this._firstTwoTouches)return;const[s,o]=this._firstTwoTouches,r=cf(i,t,s),n=cf(i,t,o);r&&n||(this._active&&Ln(),this.reset())}touchcancel(){this.reset()}enable(e){this._enabled=!0,this._aroundCenter=!!e&&"center"===e.around}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}function cf(e,t,i){for(let s=0;s<e.length;s++)if(e[s].identifier===i)return t[s]}function hf(e,t){return Math.log2(e/t)}class df extends lf{reset(){super.reset(),this._distance=0,this._startDistance=0}_start(e){this._startDistance=this._distance=e[0].dist(e[1])}_move(e,t){const i=this._distance;if(this._distance=e[0].dist(e[1]),this._active||!(Math.abs(hf(this._distance,this._startDistance))<.1))return this._active=!0,{zoomDelta:hf(this._distance,i),pinchAround:t}}}function uf(e,t){return 180*e.angleWith(t)/Math.PI}class _f extends lf{reset(){super.reset(),this._minDiameter=0,this._startVector=void 0,this._vector=void 0}_start(e){this._startVector=this._vector=e[0].sub(e[1]),this._minDiameter=e[0].dist(e[1])}_move(e,t){const i=this._vector;if(this._vector=e[0].sub(e[1]),i&&(this._active||!this._isBelowThreshold(this._vector)))return this._active=!0,{bearingDelta:uf(this._vector,i),pinchAround:t}}_isBelowThreshold(e){this._minDiameter=Math.min(this._minDiameter,e.mag());const t=25/(Math.PI*this._minDiameter)*360,i=this._startVector;if(!i)return!1;const s=uf(e,i);return Math.abs(s)<t}}function pf(e){return Math.abs(e.y)>Math.abs(e.x)}class ff extends lf{constructor(e){super(),this._map=e}reset(){super.reset(),this._valid=void 0,this._firstMove=void 0,this._lastPoints=void 0}_start(e){this._lastPoints=e,pf(e[0].sub(e[1]))&&(this._valid=!1)}_move(e,t,i){const s=this._lastPoints;if(!s)return;const o=e[0].sub(s[0]),r=e[1].sub(s[1]);return this._map._cooperativeGestures&&!dr()&&i.touches.length<3||(this._valid=this.gestureBeginsVertically(o,r,i.timeStamp),!this._valid)?void 0:(this._lastPoints=e,this._active=!0,{pitchDelta:(o.y+r.y)/2*-.5})}gestureBeginsVertically(e,t,i){if(void 0!==this._valid)return this._valid;const s=e.mag()>=2,o=t.mag()>=2;if(!s&&!o)return;if(!s||!o)return this._firstMove??=i,i-this._firstMove<100&&void 0;const r=e.y>0==t.y>0;return pf(e)&&pf(t)&&r}}const mf={panStep:100,bearingStep:15,pitchStep:10};class gf{constructor(){const e=mf;this._panStep=e.panStep,this._bearingStep=e.bearingStep,this._pitchStep=e.pitchStep,this._bearingDisabled=!1,this._pitchDisabled=!1,this._panDisabled=!1,this._zoomDisabled=!1}blur(){this.reset()}reset(){this._active=!1}keydown(e){if(e.altKey||e.ctrlKey||e.metaKey)return;if(!this.isEnabled())return;let t=0,i=0,s=0,o=0,r=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?s=1:(e.preventDefault(),r=-1);break;case 40:e.shiftKey?s=-1:(e.preventDefault(),r=1);break;default:return}return this._bearingDisabled&&(i=0),this._pitchDisabled&&(s=0),this._panDisabled&&(o=0,r=0),this._zoomDisabled&&(t=0),{cameraAnimation:n=>{const a=n.getZoom();n.easeTo({duration:300,easeId:"keyboardHandler",easing:vf,zoom:t?Math.round(a)+t*(e.shiftKey?2:1):a,bearing:n.getBearing()+i*this._bearingStep,pitch:n.getPitch()+s*this._pitchStep,offset:[-o*this._panStep,-r*this._panStep],center:n.getCenter()},{originalEvent:e})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled&&!(this._bearingDisabled&&this._pitchDisabled&&this._panDisabled&&this._zoomDisabled)}isActive(){return this._active}disableRotation(){this._pitchDisabled=!0,this._bearingDisabled=!0}enableRotation(){this._pitchDisabled=!1,this._bearingDisabled=!1}isRotationEnabled(){return!this._pitchDisabled&&!this._bearingDisabled}disablePan(){this._panDisabled=!0}enablePan(){this._panDisabled=!1}isPanEnabled(){return!this._panDisabled}disableZoom(){this._zoomDisabled=!0}enableZoom(){this._zoomDisabled=!1}isZoomEnabled(){return!this._zoomDisabled}disablePitch(){this._pitchDisabled=!0}enablePitch(){this._pitchDisabled=!1}isPitchEnabled(){return!this._pitchDisabled}disableBearing(){this._bearingDisabled=!0}enableBearing(){this._bearingDisabled=!1}isBearingEnabled(){return!this._bearingDisabled}}function vf(e){return e*(2-e)}const yf=4.000244140625,xf=1/450,bf=/(Mac|iPad)/i;class wf{constructor(e,t){this._map=e,this._el=e.getCanvasContainer(),this._handler=t,this._delta=0,this._lastDelta=0,this._defaultZoomRate=.01,this._wheelZoomRate=xf,rt(["_onTimeout","_addScrollZoomBlocker","_showBlockerAlert"],this)}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,this._map._cooperativeGestures&&this._addScrollZoomBlocker())}disable(){this.isEnabled()&&(this._enabled=!1,this._map._cooperativeGestures&&(clearTimeout(this._alertTimer),this._alertContainer.remove()))}wheel(e){if(!this.isEnabled())return;if(this._map._cooperativeGestures){if(!(e.ctrlKey||e.metaKey||this.isZooming()||dr()))return void this._showBlockerAlert();"hidden"!==this._alertContainer.style.visibility&&(this._alertContainer.style.visibility="hidden",clearTimeout(this._alertTimer))}let t=e.deltaMode===WheelEvent.DOM_DELTA_LINE?40*e.deltaY:e.deltaY;const i=T.now(),s=i-(this._lastWheelEventTime||0);this._lastWheelEventTime=i,0!==t&&t%yf===0?this._type="wheel":0!==t&&Math.abs(t)<4?this._type="trackpad":s>400?(this._type=null,this._lastValue=t,this._timeout=window.setTimeout(this._onTimeout,40,e)):this._type||(this._type=Math.abs(s*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()}_onTimeout(e){this._type="wheel",this._delta-=this._lastValue,this._active||this._start(e)}_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 t=Pn(this._el,e);this._aroundPoint=this._aroundCenter?this._map.transform.centerPoint:t,this._aroundCoord=this._map.transform.pointCoordinate3D(this._aroundPoint),this._targetZoom=void 0,this._frameId||(this._frameId=!0,this._handler._triggerRenderFrame())}renderFrame(){if(!this._frameId)return;if(this._frameId=null,!this.isActive())return;const e=this._map.transform;"wheel"===this._type&&e.projection.wrap&&(e._center.lng>=180||e._center.lng<=-180)&&(this._prevEase=null,this._easing=null,this._lastWheelEvent=null,this._lastWheelEventTime=0);const t=()=>e._terrainEnabled()&&this._aroundCoord?e.computeZoomRelativeTo(this._aroundCoord):e.zoom;if(0!==this._delta){const i="wheel"===this._type&&Math.abs(this._delta)>yf?this._wheelZoomRate:this._defaultZoomRate;let s=2/(1+Math.exp(-Math.abs(this._delta*i)));this._delta<0&&0!==s&&(s=1/s);const o=t(),r=Math.pow(2,o),n="number"==typeof this._targetZoom?e.zoomScale(this._targetZoom):r;this._targetZoom=Math.min(e.maxZoom,Math.max(e.minZoom,e.scaleZoom(n*s))),"wheel"===this._type&&(this._startZoom=o,this._easing=this._smoothOutEasing(200)),this._lastDelta=this._delta,this._delta=0}const i="number"==typeof this._targetZoom?this._targetZoom:t(),s=this._startZoom,o=this._easing;let r,n=!1;if("wheel"===this._type&&s&&o){const e=Math.min((T.now()-this._lastWheelEventTime)/200,1),t=o(e);r=J(s,i,t),e<1?this._frameId||(this._frameId=!0):n=!0}else r=i,n=!0;this._active=!0,n&&(this._active=!1,this._finishTimeout=window.setTimeout(()=>{this._zooming=!1,this._handler._triggerRenderFrame(),delete this._targetZoom,delete this._finishTimeout},200));let a=r-t();return a*this._lastDelta<0&&(a=0),{noInertia:!0,needsRenderFrame:!n,zoomDelta:a,around:this._aroundPoint,aroundCoord:this._aroundCoord,originalEvent:this._lastWheelEvent}}_smoothOutEasing(e){let t=ur;if(this._prevEase){const e=this._prevEase,i=(T.now()-e.start)/e.duration,s=e.easing(i+.01)-e.easing(i),o=.27/Math.sqrt(s*s+1e-4)*.01,r=Math.sqrt(.0729-o*o);t=hr(o,r,.25,1)}return this._prevEase={start:T.now(),duration:e,easing:t},t}blur(){this.reset()}reset(){this._active=!1}_addScrollZoomBlocker(){this._map&&!this._alertContainer&&(this._alertContainer=Tn("div","mapboxgl-scroll-zoom-blocker",this._map._container),this._alertContainer.textContent=bf.test(navigator.userAgent)?this._map._getUIString("ScrollZoomBlocker.CmdMessage"):this._map._getUIString("ScrollZoomBlocker.CtrlMessage"),this._alertContainer.style.fontSize=`${Math.max(10,Math.min(24,Math.floor(.05*this._el.clientWidth)))}px`)}_showBlockerAlert(){this._alertContainer.style.visibility="visible",this._alertContainer.classList.add("mapboxgl-scroll-zoom-blocker-show"),this._alertContainer.setAttribute("role","alert"),clearTimeout(this._alertTimer),this._alertTimer=window.setTimeout(()=>{this._alertContainer.classList.remove("mapboxgl-scroll-zoom-blocker-show"),this._alertContainer.removeAttribute("role")},200)}}class Tf{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 Ef{constructor(){this.reset()}reset(){this._active=!1}blur(){this.reset()}dblclick(e,t){return e.preventDefault(),{cameraAnimation:i=>{i.easeTo({duration:300,zoom:i.getZoom()+(e.shiftKey?-1:1),around:i.unproject(t)},{originalEvent:e})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class If{constructor(){this._tap=new Yp({numTouches:1,numTaps:1}),this.reset()}reset(){this._active=!1,this._swipePoint=void 0,this._swipeTouch=0,this._tapTime=0,this._tap.reset()}touchstart(e,t,i){this._swipePoint||(this._tapTime&&e.timeStamp-this._tapTime>500&&this.reset(),this._tapTime?i.length>0&&(this._swipePoint=t[0],this._swipeTouch=i[0].identifier):this._tap.touchstart(e,t,i))}touchmove(e,t,i){if(this._tapTime){if(this._swipePoint){if(i[0].identifier!==this._swipeTouch)return;const s=t[0],o=s.y-this._swipePoint.y;return this._swipePoint=s,e.preventDefault(),this._active=!0,{zoomDelta:o/128}}}else this._tap.touchmove(e,t,i)}touchend(e,t,i){this._tapTime?this._swipePoint&&0===i.length&&this.reset():this._tap.touchend(e,t,i)&&(this._tapTime=e.timeStamp)}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class Sf{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("mapboxgl-touch-drag-pan")}disable(){this._mousePan.disable(),this._touchPan.disable(),this._el.classList.remove("mapboxgl-touch-drag-pan")}isEnabled(){return this._mousePan.isEnabled()&&this._touchPan.isEnabled()}isActive(){return this._mousePan.isActive()||this._touchPan.isActive()}}class Df{constructor(e,t,i){this._pitchWithRotate=e.pitchWithRotate,this._mouseRotate=t,this._mousePitch=i,this._pitchDisabled=!1,this._rotationDisabled=!1}enable(){this._rotationDisabled||this._mouseRotate.enable(),this._pitchWithRotate&&!this._pitchDisabled&&this._mousePitch.enable()}disable(){this._mouseRotate.disable(),this._mousePitch.disable()}isEnabled(){return this._pitchWithRotate?!this._rotationDisabled&&this._mouseRotate.isEnabled()||!this._pitchDisabled&&this._mousePitch.isEnabled():!this._rotationDisabled&&this._mouseRotate.isEnabled()}isActive(){return this._mouseRotate.isActive()||this._mousePitch.isActive()}disablePitch(){this._pitchDisabled=!0,this._mousePitch.disable()}enablePitch(){this._pitchDisabled=!1,this._pitchWithRotate&&this._mousePitch.enable()}isPitchEnabled(){return!this._pitchDisabled&&this._mousePitch.isEnabled()}disableRotation(){this._rotationDisabled=!0,this._mouseRotate.disable()}enableRotation(){this._rotationDisabled=!1,this._mouseRotate.enable()}isRotationEnabled(){return!this._rotationDisabled&&this._mouseRotate.isEnabled()}}class Rf{constructor(e,t,i,s){this._el=e,this._touchZoom=t,this._touchRotate=i,this._tapDragZoom=s,this._rotationDisabled=!1,this._tapDragZoomDisabled=!1,this._enabled=!0}enable(e){this._touchZoom.enable(e),this._rotationDisabled||this._touchRotate.enable(e),this._tapDragZoomDisabled||this._tapDragZoom.enable(),this._el.classList.add("mapboxgl-touch-zoom-rotate")}disable(){this._touchZoom.disable(),this._touchRotate.disable(),this._tapDragZoom.disable(),this._el.classList.remove("mapboxgl-touch-zoom-rotate")}isEnabled(){return this._touchZoom.isEnabled()||!this._rotationDisabled&&this._touchRotate.isEnabled()||!this._tapDragZoomDisabled&&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()}isRotationEnabled(){return!this._rotationDisabled}disableTapDragZoom(){this._tapDragZoomDisabled=!0,this._tapDragZoom.disable()}enableTapDragZoom(){this._tapDragZoomDisabled=!1,this._touchZoom.isEnabled()&&this._tapDragZoom.enable()}isTapDragZoomEnabled(){return!this._tapDragZoomDisabled}}const Cf=e=>e.zoom||e.drag||e.pitch||e.rotate;class Af extends M{}class Lf{constructor(){this.constants=[1,1,.01],this.radius=0}setup(e,t){const i=ve([],t,e);this.radius=_s(i[2]<0?pr([],i,this.constants):[i[0],i[1],0])}projectRay(e){pr(e,e,this.constants),ye(e,e),fr(e,e,this.constants);const t=Ti([],e,this.radius);if(t[2]>0){const e=Ti([],[0,0,1],Kt(t,[0,0,1])),i=Ti([],ye([],[t[0],t[1],0]),this.radius),s=yo([],t,Ti([],ve([],yo([],i,e),t),2));t[0]=s[0],t[1]=s[1]}return t}}function Pf(e){return e.panDelta&&e.panDelta.mag()||e.zoomDelta||e.bearingDelta||e.pitchDelta}class Mf{constructor(e,t){this._map=e,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new Np(e),this._bearingSnap=t.bearingSnap,this._previousActiveHandlers={},this._trackingEllipsoid=new Lf,this._dragOrigin=null,this._mouseBeingPressed=!1,this._activeTouchCount=0,this._eventsInProgress={},this._addDefaultHandlers(t),rt(["handleEvent","handleWindowEvent"],this);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){const s=e===document?this.handleWindowEvent:this.handleEvent;e.addEventListener(t,s,i)}}destroy(){for(const[e,t,i]of this._listeners){const s=e===document?this.handleWindowEvent:this.handleEvent;e.removeEventListener(t,s,i)}}_addDefaultHandlers(e){const t=this._map,i=t.getCanvasContainer();this._add("mapEvent",new Zp(t,e));const s=t.boxZoom=new Hp(t,e);this._add("boxZoom",s);const o=new Kp,r=new Ef;t.doubleClickZoom=new Tf(r,o),this._add("tapZoom",o),this._add("clickZoom",r);const n=new If;this._add("tapDragZoom",n);const a=t.touchPitch=new ff(t);this._add("touchPitch",a);const l=new rf(e),c=new nf(e);t.dragRotate=new Df(e,l,c),this._add("mouseRotate",l,["mousePitch"]),this._add("mousePitch",c,["mouseRotate"]);const h=new of(e),d=new af(t,e);t.dragPan=new Sf(i,h,d),this._add("mousePan",h),this._add("touchPan",d,["touchZoom","touchRotate"]);const u=new _f,_=new df;t.touchZoomRotate=new Rf(i,_,u,n),this._add("touchRotate",u,["touchPan","touchZoom"]),this._add("touchZoom",_,["touchPan","touchRotate"]),this._add("blockableMapEvent",new Wp(t));const p=t.scrollZoom=new wf(t,this);this._add("scrollZoom",p,["mousePan"]);const f=t.keyboard=new gf;this._add("keyboard",f);for(const i of["boxZoom","doubleClickZoom","tapDragZoom","touchPitch","dragRotate","dragPan","touchZoomRotate","scrollZoom","keyboard"])e.interactive&&e[i]&&t[i].enable(e[i])}_add(e,t,i){this._handlers.push({handlerName:e,handler:t,allowed:i}),this._handlersById[e]=t}stop(e="never"){if(!this._updatingCamera&&!("always"===e||"ifPointerDown"===e&&this._isPointerDown())){for(const{handler:e}of this._handlers)e.reset();this._inertia.clear(),this._fireEvents({},{},!1),this._changes=[],this._originalZoom=void 0}}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!!Cf(this._eventsInProgress)||this.isZooming()}_isDragging(){return!!this._eventsInProgress.drag}_blockedByActive(e,t,i){for(const s in e)if(!(s===i||t&&t.includes(s)))return!0;return!1}handleWindowEvent(e){this.handleEvent(e,`${e.type}Window`)}_getMapTouches(e){const t=[];for(const i of e)this._el.contains(i.target)&&t.push(i);return t}_updatePointerLiveness(e){switch(e.type){case"mousedown":this._mouseBeingPressed=!0;break;case"mousemove":0===e.buttons&&(this._mouseBeingPressed=!1);break;case"mouseup":this._mouseBeingPressed=!1;break;case"touchstart":case"touchmove":case"touchend":case"touchcancel":this._activeTouchCount=e.touches?e.touches.length:0;break;case"blur":this._mouseBeingPressed=!1,this._activeTouchCount=0}}_isPointerDown(){return this._mouseBeingPressed||this._activeTouchCount>0}handleEvent(e,t){this._updatePointerLiveness(e),this._updatingCamera=!0;const i="renderFrame"===e.type,s=i?void 0:e,o={needsRenderFrame:!1},r={},n={},a=e.touches?this._getMapTouches(e.touches):void 0,l=a?Mn(this._el,a):i?void 0:Pn(this._el,e);for(const{handlerName:i,handler:c,allowed:h}of this._handlers){if(!c.isEnabled())continue;let d;this._blockedByActive(n,h,i)?c.reset():c[t||e.type]&&(d=c[t||e.type](e,l,a),this.mergeHandlerResult(o,r,d,i,s),d&&d.needsRenderFrame&&this._triggerRenderFrame()),(d||c.isActive())&&(n[i]=c)}const c={};for(const e in this._previousActiveHandlers)n[e]||(c[e]=s);this._previousActiveHandlers=n,(Object.keys(c).length||Pf(o))&&(this._changes.push([o,r,c]),this._triggerRenderFrame()),(Object.keys(n).length||Pf(o))&&this._map._stop({keepGesture:"always"}),this._updatingCamera=!1;const{cameraAnimation:h}=o;h&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],h(this._map))}mergeHandlerResult(e,t,i,s,o){if(!i)return;Object.assign(e,i);const r={handlerName:s,originalEvent:i.originalEvent||o};void 0!==i.zoomDelta&&(t.zoom=r),void 0!==i.panDelta&&(t.drag=r),void 0!==i.pitchDelta&&(t.pitch=r),void 0!==i.bearingDelta&&(t.rotate=r)}_applyChanges(){const e={},t={},i={};for(const[s,o,r]of this._changes)s.panDelta&&(e.panDelta=(e.panDelta||new m(0,0))._add(s.panDelta)),s.zoomDelta&&(e.zoomDelta=(e.zoomDelta||0)+s.zoomDelta),s.bearingDelta&&(e.bearingDelta=(e.bearingDelta||0)+s.bearingDelta),s.pitchDelta&&(e.pitchDelta=(e.pitchDelta||0)+s.pitchDelta),void 0!==s.around&&(e.around=s.around),void 0!==s.aroundCoord&&(e.aroundCoord=s.aroundCoord),void 0!==s.pinchAround&&(e.pinchAround=s.pinchAround),s.noInertia&&(e.noInertia=s.noInertia),Object.assign(t,o),Object.assign(i,r);this._updateMapTransform(e,t,i),this._changes=[]}_updateMapTransform(e,t,i){const s=this._map,o=s.transform,r=e=>[e.x,e.y,e.z];if((()=>{const e=this._eventsInProgress.drag;return e&&!this._handlersById[e.handlerName].isActive()})()&&!Pf(e)){const e=o.zoom;o.cameraElevationReference="sea",null!=this._originalZoom&&o._orthographicProjectionAtLowPitch&&"globe"!==o.projection.name&&0===o.pitch?(o.cameraElevationReference="ground",o.zoom=this._originalZoom):(o.recenterOnTerrain(),o.cameraElevationReference="ground"),e!==o.zoom&&this._map._update(!0)}if(o._isCameraConstrained&&s._stop({keepGesture:"always"}),!Pf(e))return void this._fireEvents(t,i,!0);let{panDelta:n,zoomDelta:a,bearingDelta:l,pitchDelta:c,around:h,aroundCoord:d,pinchAround:u}=e;o._isCameraConstrained&&(a>0&&(a=0),o._isCameraConstrained=!1),void 0!==u&&(h=u),(a||(e=>t[e]&&!this._eventsInProgress[e])("drag"))&&h&&(this._dragOrigin=r(o.pointCoordinate3D(h)),this._originalZoom=o.zoom,this._trackingEllipsoid.setup(o._camera.position,this._dragOrigin)),o.cameraElevationReference="sea",s._stop({keepGesture:"always"}),h=h||s.transform.centerPoint,l&&(o.bearing+=l),c&&(o.pitch+=c),o._updateCameraState();const _=[0,0,0];if(n)if("mercator"===o.projection.name){const e=this._trackingEllipsoid.projectRay(o.screenPointToMercatorRay(h).dir),t=this._trackingEllipsoid.projectRay(o.screenPointToMercatorRay(h.sub(n)).dir);_[0]=t[0]-e[0],_[1]=t[1]-e[1]}else{const e=o.pointCoordinate(h);if("globe"===o.projection.name){n=n.rotate(-o.angle);const t=o._pixelsPerMercatorPixel/o.worldSize;_[0]=-n.x*_r(at(e.y))*t,_[1]=-n.y*_r(o.center.lat)*t}else{const t=o.pointCoordinate(h.sub(n));e&&t&&(_[0]=t.x-e.x,_[1]=t.y-e.y)}}const p=o.zoom,f=[0,0,0];if(a){const e=r(d||o.pointCoordinate3D(h)),t={dir:ye([],ve([],e,o._camera.position))};if(t.dir[2]<0){const i=o.zoomDeltaToMovement(e,a);Ti(f,t.dir,i)}}const m=yo(_,_,f);o._translateCameraConstrained(m),a&&Math.abs(o.zoom-p)>1e-4&&o.recenterOnTerrain(),o.cameraElevationReference="ground",this._map._update(),e.noInertia||this._inertia.record(e),this._fireEvents(t,i,!0)}_fireEvents(e,t,i){const s=Cf(this._eventsInProgress),o=Cf(e),r={};for(const t in e){const{originalEvent:i}=e[t];this._eventsInProgress[t]||(r[`${t}start`]=i),this._eventsInProgress[t]=e[t]}!s&&o&&this._fireEvent("movestart",o.originalEvent);for(const e in r)this._fireEvent(e,r[e]);o&&this._fireEvent("move",o.originalEvent);for(const t in e){const{originalEvent:i}=e[t];this._fireEvent(t,i)}const n={};let a;for(const e in this._eventsInProgress){const{handlerName:i,originalEvent:s}=this._eventsInProgress[e];this._handlersById[i].isActive()||(delete this._eventsInProgress[e],a=t[i]||s,n[`${e}end`]=a)}for(const e in n)this._fireEvent(e,n[e]);const l=Cf(this._eventsInProgress);if(i&&(s||o)&&!l){this._updatingCamera=!0;const e=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),t=e=>0!==e&&-this._bearingSnap<e&&e<this._bearingSnap;e?(t(e.bearing||this._map.getBearing())&&(e.bearing=0),this._map.easeTo(e,{originalEvent:a})):(this._map.fire(new M("moveend",{originalEvent:a})),t(this._map.getBearing())&&this._map.resetNorth()),this._updatingCamera=!1}}_fireEvent(e,t){this._map.fire(new M(e,t?{originalEvent:t}:{}))}_requestFrame(){return this._map.triggerRepaint(),this._map._renderTaskQueue.add(e=>{this._frameId=void 0,this.handleEvent(new Af("renderFrame",{timeStamp:e})),this._applyChanges()})}_triggerRenderFrame(){void 0===this._frameId&&(this._frameId=this._requestFrame())}}const Of="map.setFreeCameraOptions(...) and map.getFreeCameraOptions() are not yet supported for non-mercator projections.";class zf extends A{constructor(e,t){super(),this._moving=!1,this._zooming=!1,this.transform=e,this._bearingSnap=t.bearingSnap,this._respectPrefersReducedMotion=!1!==t.respectPrefersReducedMotion,rt(["_renderFrameCallback"],this)}getCenter(){return new Es(this.transform.center.lng,this.transform.center.lat)}setCenter(e,t){return this.jumpTo({center:e},t)}panBy(e,t,i){return e=m.convert(e).mult(-1),this.panTo(this.transform.center,{offset:e,...t},i)}panTo(e,t,i){return this.easeTo({center:e,...t},i)}getZoom(){return this.transform.zoom}setZoom(e,t){return this.jumpTo({zoom:e},t),this}zoomTo(e,t,i){return this.easeTo({zoom:e,...t},i)}zoomIn(e,t){return this.zoomTo(this.getZoom()+1,e,t),this}zoomOut(e,t){return this.zoomTo(this.getZoom()-1,e,t),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,t,i){return this.easeTo({bearing:e,...t},i)}resetNorth(e,t){return this.rotateTo(0,{duration:1e3,...e},t),this}resetNorthPitch(e,t){return this.easeTo({bearing:0,pitch:0,duration:1e3,...e},t),this}snapToNorth(e,t){return Math.abs(this.getBearing())<this._bearingSnap?this.resetNorth(e,t):this}getPitch(){return this.transform.pitch}setPitch(e,t){return this.jumpTo({pitch:e},t),this}getVerticalFieldOfView(){return this.transform.fov}setVerticalFieldOfView(e,t){return this.jumpTo({fov:e},t)}getHorizontalFieldOfView(){return this.transform.horizontalFov}cameraForBounds(e,t){e=Le.convert(e);const i=t&&t.bearing||0,s=t&&t.pitch||0,o=e.getNorthWest(),r=e.getSouthEast();return this._cameraForBounds(this.transform,o,r,i,s,t)}_extendPadding(e){const t={top:0,right:0,bottom:0,left:0};return null==e?{...t,...this.transform.padding}:"number"==typeof e?{top:e,bottom:e,right:e,left:e}:{...t,...e}}_extendCameraOptions(e){return(e={offset:[0,0],maxZoom:this.transform.maxZoom,...e}).padding=this._extendPadding(e.padding),e}_minimumAABBFrustumDistance(e,t){const i=t.max[0]-t.min[0],s=t.max[1]-t.min[1];return i/s>e.aspect?i/(2*Math.tan(.5*e.fovX)*e.aspect):s/(2*Math.tan(.5*e.fovY)*e.aspect)}_cameraForBoundsOnGlobe(e,t,i,s,o,r){const n=e.clone(),a=this._extendCameraOptions(r);n.bearing=s,n.pitch=o;const l=Es.convert(t),c=Es.convert(i),h=.5*(l.lat+c.lat),d=.5*(l.lng+c.lng),u=mr(h,d),p=ye([],u),f=ye([],Ht([],p,[0,1,0])),m=Ht([],f,p),g=[f[0],f[1],f[2],0,m[0],m[1],m[2],0,p[0],p[1],p[2],0,0,0,0,1],v=[u,mr(l.lat,l.lng),mr(c.lat,l.lng),mr(c.lat,c.lng),mr(l.lat,c.lng),mr(h,l.lng),mr(h,c.lng),mr(l.lat,d),mr(c.lat,d)];let y=gr.fromPoints(v.map(e=>[Kt(f,e),Kt(m,e),Kt(p,e)]));const x=It([],y.center,g);0===vr(x)&&yr(x,0,0,1),ye(x,x),Ti(x,x,De),n.center=xr(x);const b=n.getWorldToCameraMatrix(),w=Tt(new Float64Array(16),b);y=gr.applyTransform(y,Ie([],b,g));const T=this._extendAABB(y,n,a,s);if(!T)return void _("Map cannot fit within canvas with the given bounds, padding, and/or offset.");y=T,It(x,x,b);const E=.5*(y.max[2]-y.min[2]),I=this._minimumAABBFrustumDistance(n,y),S=Ti([],[0,0,1],E),D=yo(S,x,S),R=I+(0===n.pitch?0:Zt(x,D)),C=n.globeCenterInViewSpace,A=ve([],x,[C[0],C[1],C[2]]);ye(A,A),Ti(A,A,R);const L=yo([],x,A);It(L,L,w);const P=Tr/De,M=_s(L),O=ws(Math.max(M*P-Tr,Number.EPSILON),0),z=Math.min(n.zoomFromMercatorZAdjusted(O),a.maxZoom);return z>.5*(uo+qs)?(n.setProjection({name:"mercator"}),n.zoom=z,this._cameraForBounds(n,t,i,s,o,r)):{center:n.center,zoom:z,bearing:s,pitch:o}}_extendAABB(e,t,i,s){const o=.5*((i.padding.left||0)+(i.padding.right||0)),r=.5*((i.padding.top||0)+(i.padding.bottom||0)),n=r,a=o,l=o,c=r,h=t.width-(a+l),d=t.height-(n+c),u=ve([],e.max,e.min),_=Math.min(h/u[0],d/u[1]),p=Math.min(t.scaleZoom(t.scale*_),i.maxZoom);if(isNaN(p))return null;const f=t.scale/t.zoomScale(p),g=new gr([e.min[0]-a*f,e.min[1]-c*f,e.min[2]],[e.max[0]+l*f,e.max[1]+n*f,e.max[2]]),v=("number"==typeof i.offset.x&&"number"==typeof i.offset.y?new m(i.offset.x,i.offset.y):m.convert(i.offset)).rotate(-le(s));return g.center[0]-=v.x*f,g.center[1]+=v.y*f,g}queryTerrainElevation(e,t){const i=this.transform.elevation;return i?(t={exaggerated:!0,...t},i.getAtPoint(we.fromLngLat(e),null,t.exaggerated)):null}_cameraForBounds(e,t,i,s,o,r){if("globe"===e.projection.name)return this._cameraForBoundsOnGlobe(e,t,i,s,o,r);const n=e.clone(),a=this._extendCameraOptions(r);n.bearing=s,n.pitch=o;const l=Es.convert(t),c=Es.convert(i),h=new Es(l.lng,c.lat),d=new Es(c.lng,l.lat),u=n.project(l),p=n.project(c),f=this.queryTerrainElevation(l),g=this.queryTerrainElevation(c),v=this.queryTerrainElevation(h),y=this.queryTerrainElevation(d),x=[[u.x,u.y,Math.min(f||0,g||0,v||0,y||0)],[p.x,p.y,Math.max(f||0,g||0,v||0,y||0)]];let b=gr.fromPoints(x);const w=n.getWorldToCameraMatrix(),T=Tt(new Float64Array(16),w);b=gr.applyTransform(b,w);const E=this._extendAABB(b,n,a,s);if(!E)return void _("Map cannot fit within canvas with the given bounds, padding, and/or offset.");b=E;const I=.5*ve([],b.max,b.min)[2],S=this._minimumAABBFrustumDistance(n,b),D=[0,0,1,0];Se(D,D,w),br(D,D);const R=Ti([],D,S+I),C=yo([],b.center,R);It(b.center,b.center,T),It(C,C,T);const A=n.unproject(new m(b.center[0],b.center[1])),L=wr(n.projection,A),P=Math.pow(2,L),M=Math.min(n._zoomFromMercatorZ(C[2]*n.pixelsPerMeter*P/n.worldSize),a.maxZoom);return n.mercatorFromTransition&&M<.5*(uo+qs)?(n.setProjection({name:"globe"}),n.zoom=M,this._cameraForBounds(n,t,i,s,o,r)):{center:A,zoom:M,bearing:s,pitch:o}}fitBounds(e,t,i){const s=this.cameraForBounds(e,t);return this._fitInternal(s,t,i)}fitScreenCoordinates(e,t,i,s,o){const r=m.convert(e),n=m.convert(t),a=new m(Math.min(r.x,n.x),Math.min(r.y,n.y)),l=new m(Math.max(r.x,n.x),Math.max(r.y,n.y));if("mercator"===this.transform.projection.name&&this.transform.anyCornerOffEdge(r,n))return this;const c=this.transform.pointLocation3D(a),h=this.transform.pointLocation3D(l),d=this.transform.pointLocation3D(new m(a.x,l.y)),u=this.transform.pointLocation3D(new m(l.x,a.y)),_=[Math.min(c.lng,h.lng,d.lng,u.lng),Math.min(c.lat,h.lat,d.lat,u.lat)],p=[Math.max(c.lng,h.lng,d.lng,u.lng),Math.max(c.lat,h.lat,d.lat,u.lat)],f=s&&s.pitch?s.pitch:this.getPitch(),g=this._cameraForBounds(this.transform,_,p,i,f,s);return this._fitInternal(g,s,o)}_fitInternal(e,t,i){return e?(t=Object.assign(e,t)).linear?this.easeTo(t,i):this.flyTo(t,i):this}jumpTo(e,t){this._stop({keepGesture:"ifPointerDown"});const i=e.preloadOnly?this.transform.clone():this.transform;let s=!1,o=!1,r=!1;"zoom"in e&&i.zoom!==+e.zoom&&(s=!0,i.zoom=+e.zoom),void 0!==e.center&&(i.center=Es.convert(e.center)),"bearing"in e&&i.bearing!==+e.bearing&&(o=!0,i.bearing=+e.bearing),"pitch"in e&&i.pitch!==+e.pitch&&(r=!0,i.pitch=+e.pitch),"fov"in e&&(i.fov=+e.fov);const n="number"==typeof e.padding?this._extendPadding(e.padding):e.padding;if(null!=e.padding&&!i.isPaddingEqual(n))if(!1===e.retainPadding){const e=i.clone();e.padding=n,i.setLocationAtPoint(i.center,e.centerPoint)}else i.padding=n;return e.preloadOnly?(this._preloadTiles(i),this):(this.fire(new M("movestart",t)).fire(new M("move",t)),s&&this.fire(new M("zoomstart",t)).fire(new M("zoom",t)).fire(new M("zoomend",t)),o&&this.fire(new M("rotatestart",t)).fire(new M("rotate",t)).fire(new M("rotateend",t)),r&&this.fire(new M("pitchstart",t)).fire(new M("pitch",t)).fire(new M("pitchend",t)),this.fire(new M("moveend",t)))}getFreeCameraOptions(){return this.transform.projection.supportsFreeCamera||_(Of),this.transform.getFreeCameraOptions()}setFreeCameraOptions(e,t){const i=this.transform;if(!i.projection.supportsFreeCamera)return _(Of),this;this.stop();const s=i.zoom,o=i.pitch,r=i.bearing;i.setFreeCameraOptions(e);const n=s!==i.zoom,a=o!==i.pitch,l=r!==i.bearing;return this.fire(new M("movestart",t)).fire(new M("move",t)),n&&this.fire(new M("zoomstart",t)).fire(new M("zoom",t)).fire(new M("zoomend",t)),l&&this.fire(new M("rotatestart",t)).fire(new M("rotate",t)).fire(new M("rotateend",t)),a&&this.fire(new M("pitchstart",t)).fire(new M("pitch",t)).fire(new M("pitchend",t)),this.fire(new M("moveend",t)),this}easeTo(e,t){this._stop({easeId:e.easeId}),(!1===(e={offset:[0,0],duration:500,easing:ur,...e}).animate||this._prefersReducedMotion(e))&&(e.duration=0);const i=e.preloadOnly?this.transform.clone():this.transform,s=this.getZoom(),o=this.getBearing(),r=this.getPitch(),n=this.getPadding(),a=this.getVerticalFieldOfView(),l="zoom"in e?+e.zoom:s,c="bearing"in e?this._normalizeBearing(e.bearing,o):o,h="pitch"in e?+e.pitch:r,d="fov"in e?+e.fov:a,u=this._extendPadding(e.padding),_=m.convert(e.offset);let p,f,g;if("globe"===i.projection.name){const t=we.fromLngLat(i.center),s=_.rotate(-i.angle);t.x+=s.x/i.worldSize,t.y+=s.y/i.worldSize;const o=t.toLngLat(),r=Es.convert(e.center||o);this._normalizeCenter(r),p=i.centerPoint.add(s),f=new m(t.x,t.y).mult(i.worldSize),g=new m(Ae(r.lng),Pe(r.lat)).mult(i.worldSize).sub(f)}else{p=i.centerPoint.add(_);const t=i.pointLocation(p),s=Es.convert(e.center||t);this._normalizeCenter(s),f=i.project(t),g=i.project(s).sub(f)}const v=i.zoomScale(l-s);let y,x;e.around&&(y=Es.convert(e.around),x=i.locationPoint(y));const b=this._zooming||l!==s,w=this._rotating||o!==c,T=this._pitching||h!==r,E=d!==a,I=!i.isPaddingEqual(u),S=!1===e.retainPadding?i.clone():i,D=i=>m=>{if(b&&(i.zoom=J(s,l,m)),w&&(i.bearing=J(o,c,m)),T&&(i.pitch=J(r,h,m)),E&&(i.fov=J(a,d,m)),I&&(S.interpolatePadding(n,u,m),p=S.centerPoint.add(_)),y)i.setLocationAtPoint(y,x);else{const e=i.zoomScale(i.zoom-s),t=l>s?Math.min(2,v):Math.max(.5,v),o=Math.pow(t,1-m),r=i.unproject(f.add(g.mult(m*o)).mult(e));i.setLocationAtPoint(i.renderWorldCopies?r.wrap():r,p)}return e.preloadOnly||this._fireMoveEvents(t),i};if(e.preloadOnly){const t=this._emulate(D,e.duration,i);return this._preloadTiles(t),this}const R={moving:this._moving,zooming:this._zooming,rotating:this._rotating,pitching:this._pitching};return this._zooming=b,this._rotating=w,this._pitching=T,this._padding=I,this._easeId=e.easeId,this._prepareEase(t,e.noMoveStart,R),this._ease(D(i),e=>{"sea"===i.cameraElevationReference&&i.recenterOnTerrain(),this._afterEase(t,e)},e),this}_prepareEase(e,t,i={}){this._moving=!0,this.transform.cameraElevationReference="sea",this.transform._orthographicProjectionAtLowPitch&&0===this.transform.pitch&&"globe"!==this.transform.projection.name&&(this.transform.cameraElevationReference="ground"),t||i.moving||this.fire(new M("movestart",e)),this._zooming&&!i.zooming&&this.fire(new M("zoomstart",e)),this._rotating&&!i.rotating&&this.fire(new M("rotatestart",e)),this._pitching&&!i.pitching&&this.fire(new M("pitchstart",e))}_fireMoveEvents(e){this.fire(new M("move",e)),this._zooming&&this.fire(new M("zoom",e)),this._rotating&&this.fire(new M("rotate",e)),this._pitching&&this.fire(new M("pitch",e))}_afterEase(e,t){if(this._easeId&&t&&this._easeId===t)return;this._easeId=void 0,this.transform.cameraElevationReference="ground";const i=this._zooming,s=this._rotating,o=this._pitching;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._padding=!1,i&&this.fire(new M("zoomend",e)),s&&this.fire(new M("rotateend",e)),o&&this.fire(new M("pitchend",e)),this.fire(new M("moveend",e))}flyTo(e,t){if(this._prefersReducedMotion(e)){const i=Me(e,["center","zoom","bearing","pitch","fov","around","padding","retainPadding"]);return this.jumpTo(i,t)}this.stop();const i=(e={offset:[0,0],speed:1.2,curve:1.42,easing:ur,...e}).preloadOnly?this.transform.clone():this.transform,s=this.getZoom(),o=this.getBearing(),r=this.getPitch(),n=this.getPadding(),a=this.getVerticalFieldOfView(),l="zoom"in e?Ee(+e.zoom,i.minZoom,i.maxZoom):s,c="bearing"in e?this._normalizeBearing(e.bearing,o):o,h="pitch"in e?+e.pitch:r,d="fov"in e?+e.fov:a,u=d!==a,_=this._extendPadding(e.padding),p=i.zoomScale(l-s),f=m.convert(e.offset);let g=i.centerPoint.add(f);const v=i.pointLocation(g),y=Es.convert(e.center||v);this._normalizeCenter(y);const x=i.project(v),b=i.project(y).sub(x);let w=e.curve;const T=Math.max(i.width,i.height),E=T/p,I=b.mag();if("minZoom"in e){const t=Ee(Math.min(e.minZoom,s,l),i.minZoom,i.maxZoom),o=T/i.zoomScale(t-s);w=Math.sqrt(o/I*2)}const S=w*w;function D(e){return-Math.asinh((E*E-T*T+(e?-1:1)*S*S*I*I)/(2*(e?E:T)*S*I))}function R(e){return(Math.exp(e)-Math.exp(-e))/2}function C(e){return(Math.exp(e)+Math.exp(-e))/2}const A=D(0);let L=function(e){return C(A)/C(A+w*e)},P=function(e){return T*((C(A)*(R(t=A+w*e)/C(t))-R(A))/S)/I;var t},M=(D(1)-A)/w;if(Math.abs(I)<1e-6||!isFinite(M)){if(Math.abs(T-E)<1e-6)return this.easeTo(e,t);const i=E<T?-1:1;M=Math.abs(Math.log(E/T))/w,P=function(){return 0},L=function(e){return Math.exp(i*w*e)}}e.duration="duration"in e?+e.duration:1e3*M/("screenSpeed"in e?+e.screenSpeed/w:+e.speed),e.maxDuration&&e.duration>e.maxDuration&&(e.duration=0);const O=o!==c,z=h!==r,F=!i.isPaddingEqual(_),k=!1===e.retainPadding?i.clone():i,B=i=>p=>{const m=p*M,v=1/L(m);i.zoom=1===p?l:s+i.scaleZoom(v),O&&(i.bearing=J(o,c,p)),z&&(i.pitch=J(r,h,p)),u&&(i.fov=J(a,d,p)),F&&(k.interpolatePadding(n,_,p),g=k.centerPoint.add(f));const w=1===p?y:i.unproject(x.add(b.mult(P(m))).mult(v));return i.setLocationAtPoint(i.renderWorldCopies?w.wrap():w,g),i._updateCameraOnTerrain(),e.preloadOnly||this._fireMoveEvents(t),i};if(e.preloadOnly){const t=this._emulate(B,e.duration,i);return this._preloadTiles(t),this}return this._zooming=!0,this._rotating=O,this._pitching=z,this._padding=F,this._prepareEase(t,!1),this._ease(B(i),()=>this._afterEase(t),e),this}isEasing(){return!!this._easeFrameId}stop(){return this._stop()}_requestRenderFrame(e){}_cancelRenderFrame(e){}_stop({easeId:e,keepGesture:t}={}){if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),this._easeFrameId=void 0,this._onEaseFrame=void 0),this._onEaseEnd){const t=this._onEaseEnd;this._onEaseEnd=void 0,t.call(this,e)}const i=this.handlers;return i&&i.stop(t),this}_ease(e,t,i){!1===i.animate||0===i.duration?(e(1),t()):(this._easeStart=T.now(),this._easeOptions=i,this._onEaseFrame=e,this._onEaseEnd=t,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback))}_renderFrameCallback(){const e=Math.min((T.now()-this._easeStart)/this._easeOptions.duration,1),t=this._onEaseFrame;t&&t(this._easeOptions.easing(e)),e<1?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop()}_normalizeBearing(e,t){e=si(e,-180,180);const i=Math.abs(e-t);return Math.abs(e-360-t)<i&&(e-=360),Math.abs(e+360-t)<i&&(e+=360),e}_normalizeCenter(e){const t=this.transform;if(t.maxBounds)return;if("globe"!==t.projection.name&&!t.renderWorldCopies)return;const i=e.lng-t.center.lng;e.lng+=i>180?-360:i<-180?360:0}_prefersReducedMotion(e){return this._respectPrefersReducedMotion&&T.prefersReducedMotion&&!(e&&e.essential)}_emulate(e,t,i){const s=Math.ceil(15*t/1e3),o=[],r=e(i.clone());for(let e=0;e<=s;e++){const t=r(e/s);o.push(t.clone())}return o}_preloadTiles(e,t){}}const Ff=/^(https?:|mailto:)/i;class kf{constructor(e={}){this.options=e,rt(["_toggleAttribution","_updateEditLink","_updateData","_updateCompact"],this)}getDefaultPosition(){return"bottom-right"}onAdd(e){const t=this.options&&this.options.compact,i=e._getUIString("AttributionControl.ToggleAttribution");this._map=e,this._container=Tn("div","mapboxgl-ctrl mapboxgl-ctrl-attrib"),this._compactButton=Tn("button","mapboxgl-ctrl-attrib-button",this._container),this._compactButton.type="button",this._compactButton.addEventListener("click",this._toggleAttribution),this._compactButton.setAttribute("aria-label",i);const s=Tn("span","mapboxgl-ctrl-icon",this._compactButton);return s.setAttribute("aria-hidden","true"),s.setAttribute("title",i),this._innerContainer=Tn("div","mapboxgl-ctrl-attrib-inner",this._container),t&&this._container.classList.add("mapboxgl-compact"),this._updateAttributions(),this._updateEditLink(),this._map.on("styledata",this._updateData),this._map.on("sourcedata",this._updateData),this._map.on("moveend",this._updateEditLink),void 0===t&&(this._map.on("resize",this._updateCompact),this._updateCompact()),this._container}onRemove(){this._container.remove(),this._map.off("styledata",this._updateData),this._map.off("sourcedata",this._updateData),this._map.off("moveend",this._updateEditLink),this._map.off("resize",this._updateCompact),this._map=void 0,this._attribHTML=void 0}_toggleAttribution(){this._container.classList.contains("mapboxgl-compact-show")?(this._container.classList.remove("mapboxgl-compact-show"),this._compactButton.setAttribute("aria-expanded","false")):(this._container.classList.add("mapboxgl-compact-show"),this._compactButton.setAttribute("aria-expanded","true"))}_updateEditLink(){let e=this._editLink;e||(e=this._editLink=this._container.querySelector(".mapbox-improve-map"));const t=[{key:"owner",value:this.styleOwner},{key:"id",value:this.styleId},{key:"access_token",value:this._map._requestManager._customAccessToken||l.ACCESS_TOKEN}];if(e){const i=t.reduce((e,i,s)=>(i.value&&(e+=`${i.key}=${i.value}${s<t.length-1?"&":""}`),e),"?");e.href=`${l.FEEDBACK_URL}/${i}#${Mp(this._map,!0)}`,e.rel="noopener nofollow"}}_updateData(e){!e||("source"!==e.dataType||"metadata"!==e.sourceDataType&&"visibility"!==e.sourceDataType)&&"style"!==e.dataType||(this._updateAttributions(),this._updateEditLink())}_updateAttributions(){if(!this._map.style)return;let e=[];if(this._map.style.stylesheet){const e=this._map.style.stylesheet;this.styleOwner=e.owner,this.styleId=e.id}const t=this._map.style._mergedSourceCaches;for(const i in t){const s=t[i];if(s.used){const t=s.getSource();t.attribution&&!e.includes(t.attribution)&&e.push(t.attribution)}}e.sort((e,t)=>e.length-t.length),e=e.filter((t,i)=>{for(let s=i+1;s<e.length;s++)if(e[s].includes(t))return!1;return!0}),this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?e=[...this.options.customAttribution,...e]:e.unshift(this.options.customAttribution));const i=e.map(e=>function(e){const t=(new DOMParser).parseFromString(e,"text/html");return Array.from(t.body.querySelectorAll("*")).reverse().forEach(e=>{const i=e.textContent||"";if("A"!==e.tagName)return void e.replaceWith(...e.childNodes);const s=e.getAttribute("href");if(!s||!Ff.test(s))return void e.replaceWith(t.createTextNode(i));const o=t.createElement("a");o.href=s,o.textContent=i,o.rel="noopener nofollow";const r=e.getAttribute("class");r&&(o.className=r),e.replaceWith(o)}),t.body.innerHTML}(e)).join(" | ");i!==this._attribHTML&&(this._attribHTML=i,e.length?(this._innerContainer.innerHTML=i,this._container.classList.remove("mapboxgl-attrib-empty")):this._container.classList.add("mapboxgl-attrib-empty"),this._editLink=null)}_updateCompact(){this._map.getCanvasContainer().offsetWidth<=640?this._container.classList.add("mapboxgl-compact"):this._container.classList.remove("mapboxgl-compact","mapboxgl-compact-show")}}class Bf{constructor(){rt(["_updateLogo","_updateCompact"],this)}onAdd(e){this._map=e,this._container=Tn("div","mapboxgl-ctrl");const t=Tn("a","mapboxgl-ctrl-logo");return t.target="_blank",t.rel="noopener nofollow",t.href="https://www.mapbox.com/",t.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),t.setAttribute("rel","noopener nofollow"),this._container.appendChild(t),this._container.style.display="none",this._map.on("sourcedata",this._updateLogo),this._updateLogo(),this._map.on("resize",this._updateCompact),this._updateCompact(),this._container}onRemove(){this._container.remove(),this._map.off("sourcedata",this._updateLogo),this._map.off("resize",this._updateCompact)}getDefaultPosition(){return"bottom-left"}_updateLogo(e){e&&"metadata"!==e.sourceDataType||(this._container.style.display=this._logoRequired()?"block":"none")}_logoRequired(){if(!this._map.style)return!0;const e=this._map.style._mergedSourceCaches;if(0===Object.entries(e).length)return!0;for(const t in e){const i=e[t].getSource();if(Object.hasOwn(i,"mapbox_logo")&&!i.mapbox_logo)return!1}return!0}_updateCompact(){const e=this._container.children;if(e.length){const t=e[0];this._map.getCanvasContainer().offsetWidth<250?t.classList.add("mapboxgl-compact"):t.classList.remove("mapboxgl-compact")}}}class Nf{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){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=[]}}class Uf{constructor(e){this.jumpTo(e)}getValue(e){if(e<=this._startTime)return this._start;if(e>=this._endTime)return this._end;const t=Er((e-this._startTime)/(this._endTime-this._startTime));return this._start*(1-t)+this._end*t}isEasing(e){return e>=this._startTime&&e<=this._endTime}jumpTo(e){this._startTime=-1/0,this._endTime=-1/0,this._start=e,this._end=e}easeTo(e,t,i){this._start=this.getValue(t),this._end=e,this._startTime=t,this._endTime=t+i}}const Vf={"AttributionControl.ToggleAttribution":"Toggle attribution","FullscreenControl.Enter":"Enter fullscreen","FullscreenControl.Exit":"Exit fullscreen","GeolocateControl.FindMyLocation":"Find my location","GeolocateControl.LocationNotAvailable":"Location not available","LogoControl.Title":"Mapbox homepage","Map.Title":"Map","NavigationControl.ResetBearing":"Reset bearing to north","NavigationControl.ZoomIn":"Zoom in","NavigationControl.ZoomOut":"Zoom out","ScrollZoomBlocker.CtrlMessage":"Use ctrl + scroll to zoom the map","ScrollZoomBlocker.CmdMessage":"Use ⌘ + scroll to zoom the map","TouchPanBlocker.Message":"Use two fingers to move the map"};class jf extends M{constructor(e,t,i,s){const{point:o,lngLat:r,originalEvent:n,target:a}=e;super(e.type,{point:o,lngLat:r,originalEvent:n,target:a}),this.preventDefault=()=>{e.preventDefault()},this.id=t,this.interaction=i,this.feature=s}}class Gf{constructor(e){this.map=e,this.interactionsByType=new Map,this.delegatedInteractions=new Map,this.typeById=new Map,this.filters=new Map,this.handleType=this.handleType.bind(this),this.handleMove=this.handleMove.bind(this),this.handleOut=this.handleOut.bind(this),this.hoveredFeatures=new Map,this.prevHoveredFeatures=new Map}add(e,t){if(this.typeById.has(e))throw new Error(`Interaction id "${e}" already exists.`);const i=t.filter;let s=t.type;i&&this.filters.set(e,dt(i)),"mouseover"===s&&(s="mouseenter"),"mouseout"===s&&(s="mouseleave");const o=this.interactionsByType.get(s)||new Map;"mouseenter"===s||"mouseleave"===s?(0===this.delegatedInteractions.size&&(this.map.on("mousemove",this.handleMove),this.map.on("mouseout",this.handleOut)),this.delegatedInteractions.set(e,t)):0===o.size&&this.map.on(s,this.handleType),0===o.size&&this.interactionsByType.set(s,o),o.set(e,t),this.typeById.set(e,s)}get(e){const t=this.typeById.get(e);if(!t)return;const i=this.interactionsByType.get(t);return i?i.get(e):void 0}remove(e){const t=this.typeById.get(e);if(!t)return;this.typeById.delete(e),this.filters.delete(e);const i=this.interactionsByType.get(t);i&&(i.delete(e),"mouseenter"===t||"mouseleave"===t?(this.delegatedInteractions.delete(e),0===this.delegatedInteractions.size&&(this.map.off("mousemove",this.handleMove),this.map.off("mouseout",this.handleOut))):0===i.size&&this.map.off(t,this.handleType))}queryTargets(e,t){const i=[];for(const[e,s]of t)s.target&&i.push({targetId:e,target:s.target,filter:this.filters.get(e)});return this.map.style.queryRenderedTargets(e,i,this.map.transform)}handleMove(e){this.prevHoveredFeatures=this.hoveredFeatures,this.hoveredFeatures=new Map;const t=this.queryTargets(e.point,Array.from(this.delegatedInteractions).reverse());t.length&&(e.type="mouseenter",this.handleType(e,t));const i=new Map;for(const[e,{feature:t}]of this.prevHoveredFeatures)this.hoveredFeatures.has(e)||i.set(t.id,t);i.size&&(e.type="mouseleave",this.handleType(e,Array.from(i.values())))}handleOut(e){const t=Array.from(this.hoveredFeatures.values()).map(({feature:e})=>e);t.length&&(e.type="mouseleave",this.handleType(e,t)),this.hoveredFeatures.clear()}handleType(e,t){const i="mouseenter"===e.type;if(i&&!this.interactionsByType.has(e.type))return void _("mouseenter interaction required for mouseleave to work.");const s=Array.from(this.interactionsByType.get(e.type)).reverse(),o=!!t;t=t||this.queryTargets(e.point,s);let r=!1;const n=new Set;for(const a of t){for(const[t,l]of s){if(!l.target)continue;const s=a.variants?a.variants[t]:null;if(s){for(const c of s){if(ic(c,a,n,t))continue;const s=new ls(a,c),h=tc(c,a,t);o&&void 0!==s.id&&(s.state=this.map.getFeatureState(s));const d=i?this.prevHoveredFeatures.get(h):null,u=new jf(e,t,l,s),_=d?d.stop:l.handler(u);if(i&&this.hoveredFeatures.set(h,{feature:a,stop:_}),!1!==_){r=!0;break}}if(r)break}}if(r)break}if(!r)for(const[t,i]of s){const{handler:s,target:o}=i;if(!o&&!1!==s(new jf(e,t,i,null)))break}}}function qf(e,t){if(Array.isArray(e)&&Array.isArray(t)){const i=new Set(e),s=new Set(t);return i.size===s.size&&e.every(e=>s.has(e))}return rs(e,t)}const Zf=/matrix.*\((.+)\)/,Wf={center:[0,0],zoom:0,bearing:0,pitch:0,minZoom:-2,maxZoom:22,minPitch:0,maxPitch:85,interactive:!0,scrollZoom:!0,boxZoom:!0,dragRotate:!0,dragPan:!0,keyboard:!0,doubleClickZoom:!0,touchZoomRotate:!0,touchPitch:!0,cooperativeGestures:!1,performanceMetricsCollection:!0,bearingSnap:7,clickTolerance:3,pitchWithRotate:!0,hash:!1,attributionControl:!0,antialias:!1,failIfMajorPerformanceCaveat:!1,preserveDrawingBuffer:!1,trackResize:!0,renderWorldCopies:!0,refreshExpiredTiles:!0,minTileCacheSize:null,maxTileCacheSize:null,localIdeographFontFamily:"sans-serif",localFontFamily:null,fontstackCompositing:"client",transformRequest:null,accessToken:null,fadeDuration:300,respectPrefersReducedMotion:!0,crossSourceCollisions:!0,collectResourceTiming:!1,testMode:!1,precompilePrograms:!0,scaleFactor:1,emissiveColorPrecision:"approximate"};let Hf=class extends zf{constructor(e){Pr.mark(Lr.create);const t=e;if(null!=(e={...Wf,...e}).minZoom&&null!=e.maxZoom&&e.minZoom>e.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(null!=e.minPitch&&null!=e.maxPitch&&e.minPitch>e.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(null!=e.minPitch&&e.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(null!=e.maxPitch&&e.maxPitch>85)throw new Error("maxPitch must be less than or equal to 85");super(new Eu(e.minZoom,e.maxZoom,e.minPitch,e.maxPitch,e.renderWorldCopies,null,null),e),this._animationFrameProvider=e.animationFrameProvider,this._repaint=!!e.repaint,this._interactive=e.interactive,this._minTileCacheSize=e.minTileCacheSize,this._maxTileCacheSize=e.maxTileCacheSize,this._failIfMajorPerformanceCaveat=e.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=e.preserveDrawingBuffer,this._antialias=e.antialias,this._trackResize=e.trackResize,this._bearingSnap=e.bearingSnap,this._refreshExpiredTiles=e.refreshExpiredTiles,this._fadeDuration=e.fadeDuration,this._placementAlgorithm=e.placementAlgorithm||"default",this._staticMode=!1,this._isInitialLoad=!0,this._crossSourceCollisions=e.crossSourceCollisions,this._collectResourceTiming=e.collectResourceTiming,this._language=this._parseLanguage(e.language),this._worldview=e.worldview,this._renderTaskQueue=new Nf,this._domRenderTaskQueue=new Nf,this._controls=[],this._markers=[],this._popups=[],this._mapId=ce(),this._locale={...Vf,...e.locale},this._clickTolerance=e.clickTolerance,this._cooperativeGestures=e.cooperativeGestures,this._performanceMetricsCollection=e.performanceMetricsCollection,this._tessellationStep=e.tessellationStep,this._containerWidth=0,this._containerHeight=0,this._showParseStatus=!0,this._precompilePrograms=e.precompilePrograms,this._averageElevationLastSampledAt=-1/0,this._averageElevationExaggeration=0,this._averageElevation=new Uf(0),this._interactionRange=[1/0,-1/0],this._visibilityHidden=0,this._useExplicitProjection=!1,this._frameId=0,this._emissiveColorPrecision=e.emissiveColorPrecision,this._scaleFactor=e.scaleFactor,this._requestManager=new Ur(e.transformRequest,e.accessToken,e.testMode);const i=Zr(e.accessToken||l.ACCESS_TOKEN);if(i&&"atlas"in i&&"number"==typeof i.atlas&&(this._tokenExpiration=i.atlas),this._silenceAuthErrors=!!e.testMode,this._contextCreateOptions=e.contextCreateOptions?{...e.contextCreateOptions}:{},"string"==typeof e.container){const t=document.getElementById(e.container);if(!t)throw new Error(`Container '${e.container.toString()}' not found.`);this._container=t}else{if(!(e.container instanceof HTMLElement))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=e.container}if(this._container.childNodes.length>0&&_("The map container element should be empty, otherwise the map's interactivity will be negatively impacted. If you want to display a message when WebGL is not supported, use the Mapbox GL Supported plugin instead."),e.maxBounds&&this.setMaxBounds(e.maxBounds),this._spriteFormat="auto",rt(["_onWindowOnline","_onWindowResize","_onVisibilityChange","_onMapScroll","_contextLost","_contextRestored"],this),this._setupContainer(),this._setupPainter(),void 0===this.painter)throw new Error("Failed to initialize WebGL.");if(this.on("move",()=>this._update(!1)),this.on("moveend",()=>this._update(!1)),this.on("zoom",()=>this._update(!0)),this._fullscreenchangeEvent="onfullscreenchange"in document?"fullscreenchange":"webkitfullscreenchange",window.addEventListener("online",this._onWindowOnline,!1),window.addEventListener("resize",this._onWindowResize,!1),window.addEventListener("orientationchange",this._onWindowResize,!1),window.addEventListener(this._fullscreenchangeEvent,this._onWindowResize,!1),window.addEventListener("visibilitychange",this._onVisibilityChange,!1),this.handlers=new Mf(this,e),this._localFontFamily=e.localFontFamily,this._localIdeographFontFamily=e.localIdeographFontFamily,this._fontstackCompositing=e.fontstackCompositing,(e.style||!e.testMode)&&this.setStyle(e.style||l.DEFAULT_STYLE,{config:e.config,localFontFamily:this._localFontFamily,localIdeographFontFamily:this._localIdeographFontFamily,fontstackCompositing:this._fontstackCompositing}),e.projection&&this.setProjection(e.projection),e.hash&&(this._hash=new Pp("string"==typeof e.hash&&e.hash||void 0).addTo(this)),!this._hash||!this._hash._onHashChange()){null==t.center&&null==t.zoom||(this.transform._unmodified=!1),this.jumpTo({center:e.center,zoom:e.zoom,bearing:e.bearing,pitch:e.pitch});const i=e.bounds;i&&(this.resize(),this.fitBounds(i,{...e.fitBoundsOptions,duration:0}))}this.resize(),e.attributionControl&&this.addControl(new kf({customAttribution:e.customAttribution})),this._logoControl=new Bf,this.addControl(this._logoControl,e.logoPosition),this.on("style.load",()=>{this.transform.unmodified&&this.jumpTo(this.style.stylesheet),this._postStyleLoadEvent(),this._postStyleWithAppearanceEvent()}),this.on("data",e=>{this._update("style"===e.dataType),this.fire(new M(`${e.dataType}data`,e))}),this.on("dataloading",e=>{this.fire(new M(`${e.dataType}dataloading`,e))}),this._interactions=new Gf(this)}_getMapId(){return this._mapId}addControl(e,t){let i,s;if("string"==typeof t?i=t:t&&(i=t.position,s=t.offset),void 0===i&&(i=e.getDefaultPosition?e.getDefaultPosition():"top-right"),!e||!e.onAdd)return this.fire(new P(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));const o=e.onAdd(this);this._controls.push(e),function(e,t,i){const s=i&&void 0!==i.x?`${Math.max(0,i.x)}px`:"",o=i&&void 0!==i.y?`${Math.max(0,i.y)}px`:"";e.style.marginLeft=t.includes("left")?s:"",e.style.marginRight=t.includes("right")?s:"",e.style.marginTop=t.includes("top")?o:"",e.style.marginBottom=t.includes("bottom")?o:""}(o,i,s);const r=this._controlPositions[i];return i.includes("bottom")?r.insertBefore(o,r.firstChild):r.appendChild(o),this}removeControl(e){if(!e||!e.onRemove)return this.fire(new P(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));const t=this._controls.indexOf(e);return t>-1&&this._controls.splice(t,1),e.onRemove(this),this}hasControl(e){return this._controls.includes(e)}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}resize(e){if(this._updateContainerDimensions(),this._containerWidth===this.transform.width&&this._containerHeight===this.transform.height)return this;this._resizeCanvas(this._containerWidth,this._containerHeight),this.transform.resize(this._containerWidth,this._containerHeight),this.painter.resize(Math.ceil(this._containerWidth),Math.ceil(this._containerHeight));const t=!this._moving;return t&&this.fire(new M("movestart",e)).fire(new M("move",e)),this.fire(new M("resize",e)),t&&this.fire(new M("moveend",e)),this}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()||null}setMaxBounds(e){return this.transform.setMaxBounds(Le.convert(e)),this._update()}setMinZoom(e){if((e=e??-2)>=-2&&e<=this.transform.maxZoom)return this.transform.minZoom=e,this._update(),this.getZoom()<e?this.setZoom(e):this.fire(new M("zoomstart",{})).fire(new M("zoom",{})).fire(new M("zoomend",{})),this;throw new Error("minZoom must be between -2 and the current maxZoom, inclusive")}getMinZoom(){return this.transform.minZoom}setMaxZoom(e){if((e=e??22)>=this.transform.minZoom)return this.transform.maxZoom=e,this._update(),this.getZoom()>e?this.setZoom(e):this.fire(new M("zoomstart",{})).fire(new M("zoom",{})).fire(new M("zoomend",{})),this;throw new Error("maxZoom must be greater than the current minZoom")}getMaxZoom(){return this.transform.maxZoom}setMinPitch(e){if((e=e??0)<0)throw new Error("minPitch must be greater than or equal to 0");if(e>=0&&e<=this.transform.maxPitch)return this.transform.minPitch=e,this._update(),this.getPitch()<e?this.setPitch(e):this.fire(new M("pitchstart",{})).fire(new M("pitch",{})).fire(new M("pitchend",{})),this;throw new Error("minPitch must be between 0 and the current maxPitch, inclusive")}getMinPitch(){return this.transform.minPitch}setMaxPitch(e){if((e=e??85)>85)throw new Error("maxPitch must be less than or equal to 85");if(e>=this.transform.minPitch)return this.transform.maxPitch=e,this._update(),this.getPitch()>e?this.setPitch(e):this.fire(new M("pitchstart",{})).fire(new M("pitch",{})).fire(new M("pitchend",{})),this;throw new Error("maxPitch must be greater than or equal to minPitch")}getMaxPitch(){return this.transform.maxPitch}getScaleFactor(){return this._scaleFactor}setScaleFactor(e){return this._scaleFactor=e,this.painter.scaleFactor=e,this.style&&this.style._setLabelPlacementStale(),this.style._updateFilteredLayers(e=>"symbol"===e.type),this._update(!0),this}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(e){return this.transform.renderWorldCopies=e,this.transform.renderWorldCopies||this._forceMarkerAndPopupUpdate(!0),this._update()}getLanguage(){return this._language}_parseLanguage(e){return"auto"===e?navigator.language:Array.isArray(e)?0===e.length?void 0:e.map(e=>"auto"===e?navigator.language:e):e}setLanguage(e){const t=this._parseLanguage(e);if(!this.style||t===this._language)return this;this._language=t,this.style.reloadSources();for(const e of this._controls)e._setLanguage&&e._setLanguage(this._language);return this}getWorldview(){return this._worldview}setWorldview(e){return this.style&&e!==this._worldview?(this._worldview=e,this._styleDirty=!0,this.style.setWorldview(e),this):this}getProjection(){return this.transform.mercatorFromTransition?{name:"globe",center:[0,0]}:this.transform.getProjection()}_showingGlobe(){return"globe"===this.transform.projection.name}setProjection(e){return this._lazyInitEmptyStyle(),e?"string"==typeof e&&(e={name:e}):e=null,this._useExplicitProjection=!!e,this._prioritizeAndUpdateProjection(e,this.style.projection)}_updateProjectionTransition(){if("globe"!==this.getProjection().name)return;const e=this.transform,t=e.projection.name;let i;"globe"===t&&e.zoom>=qs?(e.setMercatorFromTransition(),i=!0):"mercator"===t&&e.zoom<qs&&(e.setProjection({name:"globe"}),i=!0),i&&(this.style.applyProjectionUpdate(),this.style._forceSymbolLayerUpdate(),this._update(!0))}_prioritizeAndUpdateProjection(e,t){return this._updateProjection(e||t||{name:"mercator"})}_updateProjection(e){let t;const i=this.transform.mercatorFromTransition;t="globe"===e.name&&this.transform.zoom>=qs?this.transform.setMercatorFromTransition():this.transform.setProjection(e),this.style.applyProjectionUpdate();const s="mercator"===this.transform.getProjection().name&&i!==this.transform.mercatorFromTransition;return(t||s)&&(this.painter.clearBackgroundTiles(),this.style.clearSources(),this._update(!0),this._forceMarkerAndPopupUpdate(!0)),this}project(e,t){return this.transform.locationPoint3D(Es.convert(e),t)}unproject(e,t){return this.transform.pointLocation3D(m.convert(e),t)}isMoving(){return this._moving||this.handlers&&this.handlers.isMoving()||!1}isZooming(){return this._zooming||this.handlers&&this.handlers.isZooming()||!1}isRotating(){return this._rotating||this.handlers&&this.handlers.isRotating()||!1}_isDragging(){return this.handlers&&this.handlers._isDragging()||!1}_createDelegatedListener(e,t,i){const s=e=>{let i=[];if(Array.isArray(t)){const s=t.filter(e=>this.getLayer(e));i=s.length?this.queryRenderedFeatures(e,{layers:s}):[]}else i=this.queryRenderedFeatures(e,{target:t});return i};if("mouseenter"===e||"mouseover"===e){let o=!1;const r=t=>{const r=s(t.point);r.length?o||(o=!0,i.call(this,new jp(e,this,t.originalEvent,{features:r}))):o=!1};return{listener:i,targets:t,delegates:{mousemove:r,mouseout:()=>{o=!1}}}}if("mouseleave"===e||"mouseout"===e){let o=!1;const r=t=>{s(t.point).length?o=!0:o&&(o=!1,i.call(this,new jp(e,this,t.originalEvent)))},n=t=>{o&&(o=!1,i.call(this,new jp(e,this,t.originalEvent)))};return{listener:i,targets:t,delegates:{mousemove:r,mouseout:n}}}{const o=e=>{const t=s(e.point);t.length&&(e.features=t,i.call(this,e),delete e.features)};return{listener:i,targets:t,delegates:{[e]:o}}}}on(e,t,i){if("function"==typeof t||void 0===i)return super.on(e,t);if("string"==typeof t&&(t=[t]),!this._areTargetsValid(t))return this;const s=this._createDelegatedListener(e,t,i);this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[e]=this._delegatedListeners[e]||[],this._delegatedListeners[e].push(s);for(const e in s.delegates)this.on(e,s.delegates[e]);return this}once(e,t,i){if("function"==typeof t||void 0===i)return super.once(e,t);if("string"==typeof t&&(t=[t]),!this._areTargetsValid(t))return this;const s=this._createDelegatedListener(e,t,i);for(const e in s.delegates)this.once(e,s.delegates[e]);return this}off(e,t,i){if("function"==typeof t||void 0===i)return super.off(e,t);if("string"==typeof t&&(t=[t]),!this._areTargetsValid(t))return this;const s=this._delegatedListeners?this._delegatedListeners[e]:void 0;return s&&(e=>{for(let s=0;s<e.length;s++){const o=e[s];if(o.listener===i&&qf(o.targets,t)){for(const e in o.delegates)this.off(e,o.delegates[e]);return e.splice(s,1),this}}})(s),this}queryRenderedFeatures(e,t){if(!this.style)return[];if(void 0===e||e instanceof m||Array.isArray(e)||void 0!==t||(t=e,e=void 0),e=e||[[0,0],[this.transform.width,this.transform.height]],!t){const t=this.style.queryRenderedFeatures(e,void 0,this.transform),i=this.style.queryRenderedFeatureset(e,void 0,this.transform);return t.concat(i)}let i=!0;if(t.target&&(i=this._isTargetValid(t.target),i&&!t.layers))return this.style.queryRenderedFeatureset(e,t,this.transform);let s=!0;if(t.layers&&Array.isArray(t.layers)){for(const e of t.layers)if(!this._isValidId(e)){s=!1;break}if(s&&!t.target)return this.style.queryRenderedFeatures(e,t,this.transform)}let o=[];return s&&(o=o.concat(this.style.queryRenderedFeatures(e,t,this.transform))),i&&(o=o.concat(this.style.queryRenderedFeatureset(e,t,this.transform))),o}querySourceFeatures(e,t){return!e||"string"==typeof e&&!this._isValidId(e)?[]:this.style.querySourceFeatures(e,t)}queryRasterValue(e,t,i){return this._isValidId(e)?this.style.queryRasterValue(e,t,i):Promise.resolve(null)}isPointOnSurface(e){const{name:t}=this.transform.projection;return"globe"!==t&&"mercator"!==t&&_(`${t} projection does not support isPointOnSurface, this API may behave unexpectedly.`),this.transform.isPointOnSurface(m.convert(e))}addInteraction(e,t){return this._interactions.add(e,t),this}removeInteraction(e){return this._interactions.remove(e),this}getCooperativeGestures(){return this._cooperativeGestures}setCooperativeGestures(e){return this._cooperativeGestures=e,this}setStyle(e,t){return t={localIdeographFontFamily:this._localIdeographFontFamily,localFontFamily:this._localFontFamily,fontstackCompositing:this._fontstackCompositing,...t},this.style&&e&&!1!==t.diff&&t.localFontFamily===this._localFontFamily&&t.localIdeographFontFamily===this._localIdeographFontFamily&&t.fontstackCompositing===this._fontstackCompositing&&!t.config?(this.style._diffStyle(e,(i,s)=>{if(i){const s="string"==typeof i?i:i instanceof Error?i.message:i.error;_(`Unable to perform style diff: ${s}. Rebuilding the style from scratch.`),this._updateStyle(e,t)}else s&&this._update(!0)},()=>this._postStyleLoadEvent()),this):(this._localIdeographFontFamily=t.localIdeographFontFamily,this._localFontFamily=t.localFontFamily,this._fontstackCompositing=t.fontstackCompositing,this._updateStyle(e,t))}_getUIString(e){const t=this._locale[e];if(null==t)throw new Error(`Missing UI string '${e}'`);return t}_updateStyle(e,t){if(this.style&&(this.style.setEventedParent(null),this.style._remove(),this.style=void 0),e){const i={...t};t&&t.config&&(i.initialConfig=t.config,delete i.config),this.style=new Nd(this,i).load(e),this.style.setEventedParent(this,{style:this.style})}return this._updateTerrain(),this}_lazyInitEmptyStyle(){this.style||(this.style=new Nd(this,{}),this.style.setEventedParent(this,{style:this.style}),this.style.loadEmpty())}getStyle(){if(this.style)return this.style.serialize()}isStyleLoaded(){return this.style?this.style.loaded():(_("There is no style added to the map."),!1)}_isValidId(e){return null==e?(this.fire(new P(new Error("IDs can't be empty."))),!1):es(e)?(this.fire(new P(new Error(`IDs can't contain special symbols: "${e}".`))),!1):"__proto__"!==e&&"constructor"!==e&&"prototype"!==e||(this.fire(new P(new Error(`IDs can't be "${e}".`))),!1)}_isTargetValid(e){return"featuresetId"in e?this._isValidId("importId"in e?e.importId:e.featuresetId):"layerId"in e&&this._isValidId(e.layerId)}_areTargetsValid(e){if(Array.isArray(e)){for(const t of e)if(!this._isValidId(t))return!1;return!0}return this._isTargetValid(e)}addSource(e,t){return this._isValidId(e)?(this._lazyInitEmptyStyle(),this.style.addSource(e,t),this._update(!0)):this}isSourceLoaded(e){return!!this._isValidId(e)&&!!this.style&&this.style._isSourceCacheLoaded(e)}areTilesLoaded(){return this.style.areTilesLoaded()}removeSource(e){return this._isValidId(e)?(this.style.removeSource(e),this._updateTerrain(),this._update(!0)):this}getSource(e){return this._isValidId(e)?this.style.getOwnSource(e):null}addImage(e,t,{pixelRatio:i=1,sdf:s=!1,stretchX:o,stretchY:r,content:n}={}){this._lazyInitEmptyStyle();const a=g.from(e);if(t instanceof HTMLImageElement||ImageBitmap&&t instanceof ImageBitmap){const{width:e,height:l,data:c}=T.getImageData(t);this.style.addImage(a,{data:new E({width:e,height:l},c),pixelRatio:i,stretchX:o,stretchY:r,content:n,sdf:s,version:0,usvg:!1})}else if(void 0===t.width||void 0===t.height)this.fire(new P(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));else{const{width:l,height:c}=t,h=t;this.style.addImage(a,{data:new E({width:l,height:c},new Uint8Array(h.data)),pixelRatio:i,stretchX:o,stretchY:r,content:n,sdf:s,usvg:!1,version:0,userImage:h}),h.onAdd&&h.onAdd(this,e)}}updateImage(e,t){this._lazyInitEmptyStyle();const i=g.from(e),s=this.style.getImage(i);if(!s)return void this.fire(new P(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));const o=t instanceof HTMLImageElement||ImageBitmap&&t instanceof ImageBitmap?T.getImageData(t):t,{width:r,height:n,data:a}=o;if(void 0===r||void 0===n)return void this.fire(new P(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(r!==(s.usvg?s.icon.usvg_tree.width:s.data.width)||n!==(s.usvg?s.icon.usvg_tree.height:s.data.height))return void this.fire(new P(new Error(`The width and height of the updated image (${r}, ${n})\n must be that same as the previous version of the image\n (${s.data.width}, ${s.data.height})`)));const l=!(t instanceof HTMLImageElement||ImageBitmap&&t instanceof ImageBitmap);let c=!1;s.usvg?(s.data=new E({width:r,height:n},new Uint8Array(a)),s.usvg=!1,s.icon=void 0,c=!0):s.data.replace(a,l),this.style.updateImage(i,s,c)}hasImage(e){return e?!!this.style&&!!this.style.getImage(g.from(e)):(this.fire(new P(new Error("Missing required image id"))),!1)}removeImage(e){this.style.removeImage(g.from(e))}loadImage(e,t){(async()=>{const t=await this._requestManager.transformRequest(e,x.Image),{data:i}=await w(t);return i})().then(e=>t(null,e)).catch(t)}listImages(){return this.style.listImages().map(e=>e.name)}addModel(e,t){this._lazyInitEmptyStyle(),this.style.addModel(e,t)}hasModel(e){return e?this.style.hasModel(e):(this.fire(new P(new Error("Missing required model id"))),!1)}removeModel(e){this.style.removeModel(e)}listModels(){return this.style.listModels()}addLayer(e,t){return this._isValidId(e.id)?(this._lazyInitEmptyStyle(),this.style.addLayer(e,t),this._update(!0)):this}getSlot(e){const t=this.getLayer(e);return t&&t.slot||null}setSlot(e,t){return this.style.setSlot(e,t),this.style.mergeLayers(),this._update(!0)}addImport(e,t){return this._isValidId(e.id)?(this.style.addImport(e,t).catch(e=>this.fire(new P(new Error("Failed to add import",e)))),this):this}updateImport(e,t){return"string"!=typeof t&&t.id!==e?(this.removeImport(e),this.addImport(t)):(this.style.updateImport(e,t),this._update(!0))}removeImport(e){const t=this.style._getRasterMaskUser(e,"import");return t?(this.fire(new P(new Error(`Import "${e}" cannot be removed while layer "${t}" uses it in "raster-mask-import".`))),this):(this.style.removeImport(e),this)}moveImport(e,t){return this.style.moveImport(e,t),this._update(!0)}moveLayer(e,t){return this._isValidId(e)?(this.style.moveLayer(e,t),this._update(!0)):this}removeLayer(e){if(!this._isValidId(e))return this;const t=this.style._getRasterMaskUser(e,"layer");return t?(this.fire(new P(new Error(`Layer "${e}" cannot be removed while layer "${t}" uses it in "raster-mask".`))),this):(this.style.removeLayer(e),this._update(!0))}getLayer(e){if(!this._isValidId(e))return null;const t=this.style.getOwnLayer(e);return t?"custom"===t.type?t.implementation:t.serialize():void 0}getSlots(){return this.style.getSlots()}setLayerZoomRange(e,t,i){return this._isValidId(e)?(this.style.setLayerZoomRange(e,t,i),this._update(!0)):this}setFilter(e,t,i={}){return this._isValidId(e)?(this.style.setFilter(e,t,i),this._update(!0)):this}getFilter(e){return this._isValidId(e)?this.style.getFilter(e):null}setPaintProperty(e,t,i,s={}){return this._isValidId(e)?(this.style.setPaintProperty(e,t,i,s),this._update(!0)):this}getPaintProperty(e,t){return this._isValidId(e)?this.style.getPaintProperty(e,t):null}setLayoutProperty(e,t,i,s={}){return this._isValidId(e)?(this.style.setLayoutProperty(e,t,i,s),this._update(!0)):this}getLayoutProperty(e,t){return this._isValidId(e)?this.style.getLayoutProperty(e,t):null}getLayerProperty(e,t){return this._isValidId(e)?this.style.getLayerProperty(e,t):null}setLayerProperty(e,t,i,s={}){return this._isValidId(e)?("appearances"===t&&this._postAddingAppearancesToStyleEvent(),this.style.setLayerProperty(e,t,i,s),this._update(!0)):this}getGlyphsUrl(){return this.style.getGlyphsUrl()}setGlyphsUrl(e){return this.style.setGlyphsUrl(e),this._update(!0)}getSchema(e){return this.style.getSchema(e)}setSchema(e,t){return this.style.setSchema(e,t),this._update(!0)}getConfig(e){return this.style.getConfig(e)}setConfig(e,t){return this.style.setConfig(e,t),this._update(!0)}getConfigProperty(e,t){return this.style.getConfigProperty(e,t)}setConfigProperty(e,t,i){return this.style.setConfigProperty(e,t,i),this._update(!0)}getFeaturesetDescriptors(e){return this.style.getFeaturesetDescriptors(e)}setLights(e){if(this._lazyInitEmptyStyle(),e&&1===e.length&&"flat"===e[0].type){const t=e[0];t.properties?this.style.setFlatLight(t.properties,t.id,{}):this.style.setFlatLight({},"flat")}else this.style.setLights(e),this.painter.terrain&&(this.painter.terrain.invalidateRenderCache=!0);return this._update(!0)}getLights(){const e=this.style.getLights()||[];return 0===e.length&&e.push({id:this.style.light.id,type:"flat",properties:this.style.getFlatLight()}),e}setLight(e,t={}){return console.log("The `map.setLight` function is deprecated, prefer using `map.setLights` with `flat` light type instead."),this.setLights([{id:"flat",type:"flat",properties:e}])}getLight(){return console.log("The `map.getLight` function is deprecated, prefer using `map.getLights` instead."),this.style.getFlatLight()}setTerrain(e){return this._lazyInitEmptyStyle(),!e&&this.transform.projection.requiresDraping?this.style.setTerrainForDraping():this.style.setTerrain(e),this._averageElevationLastSampledAt=-1/0,this._update(!0)}getTerrain(){return this.style?this.style.getTerrain():null}setFog(e){return this._lazyInitEmptyStyle(),this.style.setFog(e),this._update(!0)}getFog(){return this.style?this.style.getFog():null}setSnow(e){return this._lazyInitEmptyStyle(),this.style.setSnow(e),this._update(!0)}getSnow(){return this.style?this.style.getSnow():null}setRain(e){return this._lazyInitEmptyStyle(),this.style.setRain(e),this._update(!0)}getRain(){return this.style?this.style.getRain():null}setColorTheme(e){return this._lazyInitEmptyStyle(),this.style.setColorTheme(e),this._update(!0)}setImportColorTheme(e,t){return this._lazyInitEmptyStyle(),this.style.setImportColorTheme(e,t),this._update(!0)}setCamera(e){return this.style.setCamera(e),this._triggerCameraUpdate(e)}getNearClipOffset(){return this.transform.nearClipOffset}setNearClipOffset(e){const t=this.transform.nearClipOffset!==e;return this.transform.nearClipOffset=e,this._update(t)}_triggerCameraUpdate(e){return this._update(this.transform.setOrthographicProjectionAtLowPitch("orthographic"===e["camera-projection"]))}getCamera(){return this.style.camera}_queryFogOpacity(e){return this.style&&this.style.fog?this.style.fog.getOpacityAtLatLng(Es.convert(e),this.transform):0}setFeatureState(e,t){return e.source&&!this._isValidId(e.source)?this:(this.style.setFeatureState(e,t),this._update())}removeFeatureState(e,t){return e.source&&!this._isValidId(e.source)?this:(this.style.removeFeatureState(e,t),this._update())}getFeatureState(e){return e.source&&!this._isValidId(e.source)?null:this.style.getFeatureState(e)}resetFeatureStates(e){return this.style.resetFeatureStates(e),this._update()}_selectIndoorFloor(e){this.style.indoorManager&&this.style.indoorManager.selectFloor(e)}_setIndoorActiveFloorsVisibility(e){this.style.indoorManager&&this.style.indoorManager.setActiveFloorsVisibility(e)}getIndoorTileOptions(e,t){return this.style&&this.style.isIndoorEnabled()&&this.style.indoorManager?this.style.indoorManager.getIndoorTileOptions(e,t):null}_updateContainerDimensions(){if(!this._container)return;const e=this._container.getBoundingClientRect().width||400,t=this._container.getBoundingClientRect().height||300;let i,s,o,r=this._container;for(;r&&(!s||!o);){const e=window.getComputedStyle(r).transform;e&&"none"!==e&&(i=e.match(Zf)[1].split(", "),i[0]&&"0"!==i[0]&&"1"!==i[0]&&(s=i[0]),i[3]&&"0"!==i[3]&&"1"!==i[3]&&(o=i[3])),r=r.parentElement}this._containerWidth=s?Math.abs(e/s):e,this._containerHeight=o?Math.abs(t/o):t}_detectMissingCSS(){"rgb(250, 128, 114)"!==window.getComputedStyle(this._missingCSSCanary).getPropertyValue("background-color")&&_("This page appears to be missing CSS declarations for Mapbox GL JS, which may cause the map to display incorrectly. Please ensure your page includes mapbox-gl.css, as described in https://www.mapbox.com/mapbox-gl-js/api/.")}_setupContainer(){const e=this._container;e.classList.add("mapboxgl-map"),(this._missingCSSCanary=Tn("div","mapboxgl-canary",e)).style.visibility="hidden",this._detectMissingCSS();const t=this._canvasContainer=Tn("div","mapboxgl-canvas-container",e);this._canvas=Tn("canvas","mapboxgl-canvas",t),this._interactive&&(t.classList.add("mapboxgl-interactive"),this._canvas.setAttribute("tabindex","0")),this._canvas.addEventListener("webglcontextlost",this._contextLost,!1),this._canvas.addEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.setAttribute("aria-label",this._getUIString("Map.Title")),this._canvas.setAttribute("role","region"),this._updateContainerDimensions(),this._resizeCanvas(this._containerWidth,this._containerHeight);const i=this._controlContainer=Tn("div","mapboxgl-control-container",e),s=this._controlPositions={};["top-left","top","top-right","right","bottom-right","bottom","bottom-left","left"].forEach(e=>{s[e]=Tn("div",`mapboxgl-ctrl-${e}`,i)}),this._container.addEventListener("scroll",this._onMapScroll,!1)}_resizeCanvas(e,t){const i=T.devicePixelRatio||1;this._canvas.width=i*Math.ceil(e),this._canvas.height=i*Math.ceil(t),this._canvas.style.width=`${e}px`,this._canvas.style.height=`${t}px`}_addMarker(e){this._markers.push(e)}_removeMarker(e){const t=this._markers.indexOf(e);-1!==t&&this._markers.splice(t,1)}_addPopup(e){this._popups.push(e)}_removePopup(e){const t=this._popups.indexOf(e);-1!==t&&this._popups.splice(t,1)}_setupPainter(){const e={...gn,failIfMajorPerformanceCaveat:this._failIfMajorPerformanceCaveat,preserveDrawingBuffer:this._preserveDrawingBuffer,antialias:this._antialias||!1},t=this._canvas.getContext("webgl2",e);t?(fn(t,!0),this.painter=new Cp(t,this._contextCreateOptions,this.transform,this._scaleFactor,this._worldview,this._emissiveColorPrecision),this.on("data",e=>{if("source"===e.dataType){const t=this.transform.elevation?this.transform.elevation._source():null;t&&e.sourceCacheId===t.id&&this.style&&this.style._setLabelPlacementStale(),this.style&&e.sourceCacheId&&this.style._buildingIndex.hasLayerForSourceCache(e.sourceCacheId)&&this.style._requestFullLabelPlacement(),this.painter.setTileLoadedFlag(!0)}})):this.fire(new P(new Error("Failed to initialize WebGL")))}_contextLost(e){e.preventDefault(),this._frame&&(this._frame.cancel(),this._frame=null),this.style&&this.style.handleContextLost(),this.fire(new M("webglcontextlost",{originalEvent:e}))}_contextRestored(e){this._setupPainter(),this.painter.resize(Math.ceil(this._containerWidth),Math.ceil(this._containerHeight)),this._updateTerrain(),this.style&&(this.style.clearLayers(),this.style.imageManager.destroyAtlasTextures(),this.style.imageManager.imageAtlasCache.clear(),this.style.reloadModels(),this.style.clearSources()),this._update(),this.fire(new M("webglcontextrestored",{originalEvent:e}))}_onMapScroll(e){if(e.target===this._container)return this._container.scrollTop=0,this._container.scrollLeft=0,!1}idle(){return!this.isMoving()&&this.loaded()}loaded(){return!this._styleDirty&&!this._sourcesDirty&&!!this.style&&this.style.loaded()}frameReady(){return this.loaded()&&!this._placementDirty}_update(e){return this.style?(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)}_requestDomTask(e){!this.loaded()||this.loaded()&&!this.isMoving()?e():this._domRenderTaskQueue.add(e)}_render(e){let t;this.fire(new M("renderstart")),++this._frameId;const i=this.painter.context.extTimerQuery,s=T.now(),o=this.painter.context.gl;if(this.listens("gpu-timing-frame")&&(t=o.createQuery(),o.beginQuery(i.TIME_ELAPSED_EXT,t)),this.painter.context.setDirty(),this.painter.setBaseState(),(this.isMoving()||this.isRotating()||this.isZooming())&&(this._interactionRange[0]=Math.min(this._interactionRange[0],performance.now()),this._interactionRange[1]=Math.max(this._interactionRange[1],performance.now())),this._renderTaskQueue.run(e),this._domRenderTaskQueue.run(e),this._removed)return;this._updateProjectionTransition();const r=this._isInitialLoad?0:this._fadeDuration;if(this.style&&this._styleDirty){this._styleDirty=!1;const e=this.transform.zoom,t=this.transform.pitch,i=T.now(),s=new X(e,{now:i,fadeDuration:r,pitch:t,transition:this._loaded?this.style.transition:{duration:0,delay:0},worldview:this._worldview});this.style.update(s)}this.style&&this.style.hasFogTransition()&&(this.style._markersNeedUpdate=!0,this._sourcesDirty=!0);let n=!1;if(this.style&&this._sourcesDirty?(this._sourcesDirty=!1,this.painter._updateFog(this.style),this._updateTerrain(),n=this._updateAverageElevation(s),this.style.updateSources(this.transform),this.style.updateImageProviders(),this.isMoving()||this._forceMarkerAndPopupUpdate()):n=this._updateAverageElevation(s),this.style){const e=this._staticMode&&!this.style.loaded();this._placementDirty=e||this.style._updatePlacement(this.painter.transform,this.showCollisionBoxes,r,this._crossSourceCollisions,this.painter.replacementSource,this._placementAlgorithm)}if(!this.style||this.transform.projection.requiresDraping&&!Al.loaded||this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showParseStatus:this.showParseStatus,wireframe:{terrain:this.showTerrainWireframe,layers2D:this.showLayers2DWireframe,layers3D:this.showLayers3DWireframe},showOverdrawInspector:this._showOverdrawInspector,showQueryGeometry:!!this._showQueryGeometry,showTileAABBs:this.showTileAABBs,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:r,isInitialLoad:this._isInitialLoad,showPadding:this.showPadding,gpuTiming:!!this.listens("gpu-timing-layer"),gpuTimingDeferredRender:!!this.listens("gpu-timing-deferred-render"),speedIndexTiming:this.speedIndexTiming,paintStartTimeStamp:e}),this.fire(new M("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,Pr.mark(Lr.load),this.fire(new M("load"))),this.style&&this.style.hasTransitions()&&(this._styleDirty=!0),this.style&&this.style.imageManager.hasPatternsInFlight()&&(this._styleDirty=!0),this.style&&!this._placementDirty&&this.style._releaseSymbolFadeTiles(),t){const e=T.now()-s;o.endQuery(i.TIME_ELAPSED_EXT),setTimeout(()=>{const i=o.getQueryParameter(t,o.QUERY_RESULT)/1e6;o.deleteQuery(t),this.fire(new M("gpu-timing-frame",{cpuTime:e,gpuTime:i}))},50)}if(this.listens("gpu-timing-layer")){const e=this.painter.collectGpuTimers();setTimeout(()=>{const t=this.painter.queryGpuTimers(e);this.fire(new M("gpu-timing-layer",{layerTimes:t}))},50)}if(this.listens("gpu-timing-deferred-render")){const e=this.painter.collectDeferredRenderGpuQueries();setTimeout(()=>{const t=this.painter.queryGpuTimeDeferredRender(e);this.fire(new M("gpu-timing-deferred-render",{gpuTime:t}))},50)}const a=this._sourcesDirty||this._styleDirty||this._placementDirty||n;if(a||this._repaint||this.style&&(this.style.snow||this.style.rain))this.triggerRepaint();else{const e=this.idle();if(e&&(n=this._updateAverageElevation(s,!0)),n)this.triggerRepaint();else{if(this._triggerFrame(!1),e&&(this.fire(new M("idle")),this._isInitialLoad=!1,this.speedIndexTiming)){const e=this._calculateSpeedIndex();this.fire(new M("speedindexcompleted",{speedIndex:e})),this.speedIndexTiming=!1}e&&this.style&&this.style.handleIdle()}}!this._loaded||this._fullyLoaded||a||(this._fullyLoaded=!0,Pr.mark(Lr.fullLoad),this._performanceMetricsCollection&&dn(this._requestManager._customAccessToken,{width:this.painter.width,height:this.painter.height,interactionRange:this._interactionRange,visibilityHidden:this._visibilityHidden,terrainEnabled:this.painter.style.hasTerrain(),fogEnabled:!!this.painter.style.getFog(),projection:this.getProjection().name,zoom:this.transform.zoom,renderer:this.painter.context.renderer,vendor:this.painter.context.vendor}),this._authenticate())}_forceMarkerAndPopupUpdate(e){for(const t of this._markers)e&&!this.getRenderWorldCopies()&&(t._lngLat=t._lngLat.wrap()),t._update();for(const t of this._popups)!e||this.getRenderWorldCopies()||t._trackPointer||(t._lngLat=t._lngLat.wrap()),t._update()}_updateAverageElevation(e,t=!1){const i=e=>(this.transform.averageElevation=e,this._update(!1),!0);if(!this.painter.averageElevationNeedsEasing())return 0!==this.transform.averageElevation&&i(0);const s=this.transform.elevation&&this.transform.elevation.exaggeration()!==this._averageElevationExaggeration;if(s||(t||e-this._averageElevationLastSampledAt>500)&&!this._averageElevation.isEasing(e)){const t=this.transform.averageElevation;let o=this.transform.sampleAverageElevation();null!=this.transform.elevation&&(this._averageElevationExaggeration=this.transform.elevation.exaggeration()),isNaN(o)?o=0:this._averageElevationLastSampledAt=e;const r=Math.abs(t-o);if(r>1){if(this._isInitialLoad||s)return this._averageElevation.jumpTo(o),i(o);this._averageElevation.easeTo(o,e,300)}else if(r>1e-4)return this._averageElevation.jumpTo(o),i(o)}return!!this._averageElevation.isEasing(e)&&i(this._averageElevation.getValue(e))}_isTokenExpired(){return null!=this._tokenExpiration&&Date.now()>this._tokenExpiration}_revokeAuth(){const e=this.painter.context.gl;fn(e,!1),this._logoControl instanceof Bf&&this._logoControl._updateLogo(),e&&e.clear(e.DEPTH_BUFFER_BIT|e.COLOR_BUFFER_BIT|e.STENCIL_BUFFER_BIT),this._silenceAuthErrors||this.fire(new P(new Error("A valid Mapbox access token is required to use Mapbox GL JS. To create an account or a new access token, visit https://account.mapbox.com/")))}_authenticate(){_n(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,e=>{e&&(e.message!==Nr&&401!==e.status||this._revokeAuth())}),this._isTokenExpired()&&this._revokeAuth(),sn(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,()=>{})}_postStyleLoadEvent(){this.style.globalId&&rn(this._requestManager._customAccessToken,{map:this,style:this.style.globalId,importedStyles:this.style.getImportGlobalIds()})}_postStyleWithAppearanceEvent(){this.style.globalId&&this.style.hasAppearances()&&an(this._requestManager._customAccessToken)}_postAddingAppearancesToStyleEvent(){cn(this._requestManager._customAccessToken)}_updateTerrain(){const e=this._isDragging();this.painter.updateTerrain(this.style,e)}_calculateSpeedIndex(){const e=this.painter.canvasCopy(),t=this.painter.getCanvasCopiesAndTimestamps();t.timeStamps.push(performance.now());const i=this.painter.context.gl,s=i.createFramebuffer();function o(e){i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,e,0);const t=new Uint8Array(i.drawingBufferWidth*i.drawingBufferHeight*4);return i.readPixels(0,0,i.drawingBufferWidth,i.drawingBufferHeight,i.RGBA,i.UNSIGNED_BYTE,t),t}return i.bindFramebuffer(i.FRAMEBUFFER,s),this._canvasPixelComparison(o(e),t.canvasCopies.map(o),t.timeStamps)}_canvasPixelComparison(e,t,i){let s=i[1]-i[0];const o=e.length/4;for(let r=0;r<t.length;r++){const n=t[r];let a=0;for(let t=0;t<n.length;t+=4)n[t]===e[t]&&n[t+1]===e[t+1]&&n[t+2]===e[t+2]&&n[t+3]===e[t+3]&&(a+=1);s+=(i[r+2]-i[r+1])*(1-a/o)}return s}remove(){if(this._removed)return;this._hash&&this._hash.remove();for(const e of this._controls)e.onRemove(this);this._controls=[],this._frame&&(this._frame.cancel(),this._frame=null),this._renderTaskQueue.clear(),this._domRenderTaskQueue.clear(),this.style&&this.style.destroy(),this.painter.destroy(),this.handlers&&this.handlers.destroy(),this.handlers=void 0,this.setStyle(null),window.removeEventListener("resize",this._onWindowResize,!1),window.removeEventListener("orientationchange",this._onWindowResize,!1),window.removeEventListener(this._fullscreenchangeEvent,this._onWindowResize,!1),window.removeEventListener("online",this._onWindowOnline,!1),window.removeEventListener("visibilitychange",this._onVisibilityChange,!1);const e=this.painter.context.gl.getExtension("WEBGL_lose_context");e&&e.loseContext(),this._canvas.removeEventListener("webglcontextlost",this._contextLost,!1),this._canvas.removeEventListener("webglcontextrestored",this._contextRestored,!1),this._canvasContainer.remove(),this._controlContainer.remove(),this._missingCSSCanary.remove(),this._canvas=void 0,this._canvasContainer=void 0,this._controlContainer=void 0,this._missingCSSCanary=void 0,this._container.classList.remove("mapboxgl-map"),this._container.removeEventListener("scroll",this._onMapScroll,!1),pn.delete(this.painter.context.gl),un.remove(),tn.remove(),this._removed=!0,this.fire(new M("remove"))}triggerRepaint(){this._triggerFrame(!0)}_triggerFrame(e){if(this._renderNextFrame=this._renderNextFrame||e,!this.style||this._frame)return;const t=this._animationFrameProvider;if(!t)return void(this._frame=T.frame(e=>{const t=!!this._renderNextFrame;this._frame=null,this._renderNextFrame=null,t&&this._render(e)}));const i=e=>{const t=!!this._renderNextFrame;this._renderNextFrame=null;try{t&&this._render(e)}finally{this._frame=null}t&&!this._removed&&Promise.resolve().then(()=>this._triggerFrame(!1))};let s=null;this._frame={cancel:()=>{null!==s&&t.cancelAnimationFrame(s)}};try{s=t.requestAnimationFrame(i)}catch(e){throw this._frame=null,e}}_preloadTiles(e){const t=this.style?this.style.getSourceCaches():[];return j(t,(t,i)=>t._preloadTiles(e,i),()=>{this.triggerRepaint()}),this}_onWindowOnline(){this._update()}_onWindowResize(e){this._trackResize&&this.resize({originalEvent:e})._update()}_onVisibilityChange(){"hidden"===document.visibilityState&&this._visibilityHidden++}get showTileBoundaries(){return!!this._showTileBoundaries}set showTileBoundaries(e){this._showTileBoundaries!==e&&(this._showTileBoundaries=e,e&&La(),this._update())}get showParseStatus(){return!!this._showParseStatus}set showParseStatus(e){this._showParseStatus!==e&&(this._showParseStatus=e,this._update())}get showTerrainWireframe(){return!!this._showTerrainWireframe}set showTerrainWireframe(e){this._showTerrainWireframe!==e&&(this._showTerrainWireframe=e,this._update())}get showLayers2DWireframe(){return!!this._showLayers2DWireframe}set showLayers2DWireframe(e){this._showLayers2DWireframe!==e&&(this._showLayers2DWireframe=e,this._update())}get showLayers3DWireframe(){return!!this._showLayers3DWireframe}set showLayers3DWireframe(e){this._showLayers3DWireframe!==e&&(this._showLayers3DWireframe=e,this._update())}get showElevationIdDebug(){return!!this.painter&&this.painter._debugParams.showElevationIdDebug}set showElevationIdDebug(e){this.painter&&this.painter._debugParams.showElevationIdDebug!==e&&(this.painter._debugParams.showElevationIdDebug=e,this.style&&e?this.style._reloadSources():this._update())}get speedIndexTiming(){return!!this._speedIndexTiming}set speedIndexTiming(e){this._speedIndexTiming!==e&&(this._speedIndexTiming=e,this._update())}get showPadding(){return!!this._showPadding}set showPadding(e){this._showPadding!==e&&(this._showPadding=e,e&&La(),this._update())}get showCollisionBoxes(){return!!this._showCollisionBoxes}set showCollisionBoxes(e){this._showCollisionBoxes!==e&&(this._showCollisionBoxes=e,e&&La(),this.style&&e?this.style._reloadSources():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 showTileAABBs(){return!!this._showTileAABBs}set showTileAABBs(e){this._showTileAABBs!==e&&(this._showTileAABBs=e,e&&this._update())}_setCacheLimits(e,t){Ir(e,t)}get version(){return Cr}};const $f={showCompass:!0,showZoom:!0,visualizePitch:!1};class Xf{constructor(e={}){this.options={...$f,...e},this._container=Tn("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.addEventListener("contextmenu",e=>e.preventDefault()),this.options.showZoom&&(rt(["_setButtonTitle","_updateZoomButtons"],this),this._zoomInButton=this._createButton("mapboxgl-ctrl-zoom-in",e=>{this._map&&this._map.zoomIn({},{originalEvent:e})}),Tn("span","mapboxgl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true"),this._zoomOutButton=this._createButton("mapboxgl-ctrl-zoom-out",e=>{this._map&&this._map.zoomOut({},{originalEvent:e})}),Tn("span","mapboxgl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(rt(["_rotateCompassArrow"],this),this._compass=this._createButton("mapboxgl-ctrl-compass",e=>{const t=this._map;t&&(this.options.visualizePitch?t.resetNorthPitch({},{originalEvent:e}):t.resetNorth({},{originalEvent:e}))}),this._compassIcon=Tn("span","mapboxgl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"))}_updateZoomButtons(){const e=this._map;if(!e)return;const t=e.getZoom(),i=t===e.getMaxZoom(),s=t===e.getMinZoom();this._zoomInButton.disabled=i,this._zoomOutButton.disabled=s,this._zoomInButton.setAttribute("aria-disabled",i.toString()),this._zoomOutButton.setAttribute("aria-disabled",s.toString())}_rotateCompassArrow(){const e=this._map;if(!e)return;const t=this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(e.transform.pitch*(Math.PI/180)),.5)}) rotateX(${e.transform.pitch}deg) rotateZ(${e.transform.angle*(180/Math.PI)}deg)`:`rotate(${e.transform.angle*(180/Math.PI)}deg)`;e._requestDomTask(()=>{this._compassIcon&&(this._compassIcon.style.transform=t)})}onAdd(e){return this._map=e,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),e.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&e.on("pitch",this._rotateCompassArrow),e.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new Yf(e,this._compass,this.options.visualizePitch)),this._container}onRemove(){const e=this._map;e&&(this._container.remove(),this.options.showZoom&&e.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&e.off("pitch",this._rotateCompassArrow),e.off("rotate",this._rotateCompassArrow),this._handler&&this._handler.off(),this._handler=void 0),this._map=void 0)}_createButton(e,t){const i=Tn("button",e,this._container);return i.type="button",i.addEventListener("click",t),i}_setButtonTitle(e,t){if(!this._map)return;const i=this._map._getUIString(`NavigationControl.${t}`);e.setAttribute("aria-label",i),e.firstElementChild&&e.firstElementChild.setAttribute("title",i)}}class Yf{constructor(e,t,i=!1){this._clickTolerance=10,this.element=t,this.mouseRotate=new rf({clickTolerance:e.dragRotate._mouseRotate._clickTolerance}),this.map=e,i&&(this.mousePitch=new nf({clickTolerance:e.dragRotate._mousePitch._clickTolerance})),rt(["mousedown","mousemove","mouseup","touchstart","touchmove","touchend","reset"],this),t.addEventListener("mousedown",this.mousedown),t.addEventListener("touchstart",this.touchstart,{passive:!1}),t.addEventListener("touchmove",this.touchmove),t.addEventListener("touchend",this.touchend),t.addEventListener("touchcancel",this.reset)}down(e,t){this.mouseRotate.mousedown(e,t),this.mousePitch&&this.mousePitch.mousedown(e,t),Rn()}move(e,t){const i=this.map,s=this.mouseRotate.mousemoveWindow(e,t),o=s&&s.bearingDelta;if(o&&i.setBearing(i.getBearing()+o),this.mousePitch){const s=this.mousePitch.mousemoveWindow(e,t),o=s&&s.pitchDelta;o&&i.setPitch(i.getPitch()+o)}}off(){const e=this.element;e.removeEventListener("mousedown",this.mousedown),e.removeEventListener("touchstart",this.touchstart),e.removeEventListener("touchmove",this.touchmove),e.removeEventListener("touchend",this.touchend),e.removeEventListener("touchcancel",this.reset),this.offTemp()}offTemp(){Cn(),window.removeEventListener("mousemove",this.mousemove),window.removeEventListener("mouseup",this.mouseup)}mousedown(e){this.down({...e,button:e.button,type:e.type,ctrlKey:!0,preventDefault:()=>e.preventDefault()},Pn(this.element,e)),window.addEventListener("mousemove",this.mousemove),window.addEventListener("mouseup",this.mouseup)}mousemove(e){this.move(e,Pn(this.element,e))}mouseup(e){this.mouseRotate.mouseupWindow(e),this.mousePitch&&this.mousePitch.mouseupWindow(e),this.offTemp()}touchstart(e){1!==e.targetTouches.length?this.reset():(this._startPos=this._lastPos=Mn(this.element,e.targetTouches)[0],this.down({type:"mousedown",button:0,ctrlKey:!0,preventDefault:()=>e.preventDefault()},this._startPos))}touchmove(e){1!==e.targetTouches.length?this.reset():(this._lastPos=Mn(this.element,e.targetTouches)[0],this.move({buttons:1,preventDefault:()=>e.preventDefault()},this._lastPos))}touchend(e){0===e.targetTouches.length&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos)<this._clickTolerance&&this.element.click(),this.reset()}reset(){this.mouseRotate.reset(),this.mousePitch&&this.mousePitch.reset(),delete this._startPos,delete this._lastPos,this.offTemp()}}function Kf(e,t,i){if(e=new Es(e.lng,e.lat),t){const s=new Es(e.lng-360,e.lat),o=new Es(e.lng+360,e.lat),r=360*Math.ceil(Math.abs(e.lng-i.center.lng)/360),n=i.locationPoint3D(e).distSqr(t),a=t.x<0||t.y<0||t.x>i.width||t.y>i.height;i.locationPoint3D(s).distSqr(t)<n&&(a||Math.abs(s.lng-i.center.lng)<r)?e=s:i.locationPoint3D(o).distSqr(t)<n&&(a||Math.abs(o.lng-i.center.lng)<r)&&(e=o)}for(;Math.abs(e.lng-i.center.lng)>180;){const t=i.locationPoint3D(e);if(t.x>=0&&t.y>=0&&t.x<=i.width&&t.y<=i.height)break;e.lng>i.center.lng?e.lng-=360:e.lng+=360}return e}const Jf={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%)"},Qf=/\s+/,em={rotation:0,rotationAlignment:"auto",pitchAlignment:"auto",occludedOpacity:.2,altitude:0};class tm extends A{constructor(e,t){super(),(e instanceof HTMLElement||t)&&(e={element:e,...t}),rt(["_update","_onMove","_onUp","_addDragHandler","_onMapClick","_onKeyPress","_clearFadeTimer"],this);const{anchor:i="center",color:s="#3FB1CE",scale:o=1,draggable:r=!1,clickTolerance:n=0,rotation:a=em.rotation,rotationAlignment:l=em.rotationAlignment,pitchAlignment:c=em.pitchAlignment,occludedOpacity:h=em.occludedOpacity,altitude:d=em.altitude}=e||{};this._anchor=i,this._color=s,this._scale=o,this._draggable=r,this._clickTolerance=n,this._rotation=a,this._rotationAlignment=l,this._pitchAlignment=c,this._occludedOpacity=h,this._altitude=d,this._state="inactive",this._isDragging=!1,this._pointerEvents=null,this._updateMoving=()=>this._update(!0),e&&e.element?(this._element=e.element,this._offset=m.convert(e&&e.offset||[0,0])):(this._defaultMarker=!0,this._element=this._createDefaultMarker(),this._offset=m.convert(e&&e.offset||[0,-14])),this._element.hasAttribute("aria-label")||this._element.setAttribute("aria-label","Map marker"),this._element.hasAttribute("role")||this._element.setAttribute("role","img"),this._element.classList.add("mapboxgl-marker"),this._element.addEventListener("dragstart",e=>{e.preventDefault()}),this._element.addEventListener("mousedown",e=>{e.preventDefault()});const u=this._element.classList;for(const e in Jf)u.remove(`mapboxgl-marker-anchor-${e}`);u.add(`mapboxgl-marker-anchor-${this._anchor}`),e&&e.className&&u.add(...e.className.trim().split(Qf)),this._popup=null}_createDefaultMarker(){const e=Tn("div"),t=En("svg",{display:"block",height:41*this._scale+"px",width:27*this._scale+"px",viewBox:"0 0 27 41"},e);this._svgElement=t;const i=En("radialGradient",{id:"shadowGradient"},En("defs",{},t));En("stop",{offset:"10%","stop-opacity":.4},i),En("stop",{offset:"100%","stop-opacity":.05},i);const s=En("ellipse",{cx:13.5,cy:34.8,rx:10.5,ry:5.25,fill:"url(#shadowGradient)"});return this._shadowElement=s,0===this._altitude&&t.insertBefore(s,t.firstChild),En("path",{fill:this._color,d:"M27,13.5C27,19.07 20.25,27 14.75,34.5C14.02,35.5 12.98,35.5 12.25,34.5C6.75,27 0,19.22 0,13.5C0,6.04 6.04,0 13.5,0C20.96,0 27,6.04 27,13.5Z"},t),En("path",{opacity:.25,d:"M13.5,0C6.04,0 0,6.04 0,13.5C0,19.22 6.75,27 12.25,34.5C13,35.52 14.02,35.5 14.75,34.5C20.25,27 27,19.07 27,13.5C27,6.04 20.96,0 13.5,0ZM13.5,1C20.42,1 26,6.58 26,13.5C26,15.9 24.5,19.18 22.22,22.74C19.95,26.3 16.71,30.14 13.94,33.91C13.74,34.18 13.61,34.32 13.5,34.44C13.39,34.32 13.26,34.18 13.06,33.91C10.28,30.13 7.41,26.31 5.02,22.77C2.62,19.23 1,15.95 1,13.5C1,6.58 6.58,1 13.5,1Z"},t),En("circle",{fill:"white",cx:13.5,cy:13.5,r:5.5},t),e}addTo(e){return e===this._map||(this.remove(),this._map=e,e.getCanvasContainer().appendChild(this._element),e.on("move",this._updateMoving),e.on("moveend",this._update),e.on("remove",this._clearFadeTimer),e._addMarker(this),this.setDraggable(this._draggable),this._update(),e.on("click",this._onMapClick)),this}remove(){const e=this._map;return e&&(e.off("click",this._onMapClick),e.off("move",this._updateMoving),e.off("moveend",this._update),e.off("mousedown",this._addDragHandler),e.off("touchstart",this._addDragHandler),e.off("mouseup",this._onUp),e.off("touchend",this._onUp),e.off("mousemove",this._onMove),e.off("touchmove",this._onMove),e.off("remove",this._clearFadeTimer),e._removeMarker(this),this._map=void 0),this._clearFadeTimer(),this._element.remove(),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(e){return this._lngLat=Es.convert(e),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(!0),this}setAltitude(e){if(e===this._altitude)return this;const t=this._altitude;return this._altitude=e||em.altitude,this._defaultMarker&&0===t!=(0===this._altitude)&&(0===this._altitude?this._svgElement.insertBefore(this._shadowElement,this._svgElement.firstChild):this._shadowElement.remove()),this._update(),this}getAltitude(){return this._altitude}getElement(){return this._element}setPopup(e){if(this._popup&&(this._popup.remove(),this._popup=null,this._element.removeAttribute("role"),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,s=Math.sqrt(Math.pow(i,2)/2);e.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-t],"bottom-left":[s,-1*(t-i+s)],"bottom-right":[-s,-1*(t-i+s)],left:[i,-1*(t-i)],right:[-i,-1*(t-i)]}:this._offset}this._popup=e,e._marker=this,e._altitude=this._altitude,this._lngLat&&this._popup.setLngLat(this._lngLat),this._element.setAttribute("role","button"),this._originalTabIndex=this._element.getAttribute("tabindex"),this._originalTabIndex||this._element.setAttribute("tabindex","0"),this._element.addEventListener("keypress",this._onKeyPress),this._element.setAttribute("aria-expanded","false")}return this}_onKeyPress(e){const t=e.code,i=e.charCode||e.keyCode;"Space"!==t&&"Enter"!==t&&32!==i&&13!==i||this.togglePopup()}_onMapClick(e){const t=e.originalEvent.target,i=this._element;this._popup&&(t===i||i.contains(t))&&this.togglePopup()}getPopup(){return this._popup}togglePopup(){const e=this._popup;return e?(e.isOpen()?(e.remove(),this._element.setAttribute("aria-expanded","false")):this._map&&(e.addTo(this._map),this._element.setAttribute("aria-expanded","true")),this):this}_behindTerrain(){const e=this._map,t=this._pos;if(!e||!t)return!1;const i=e.unproject(t,this._altitude),s=e.getFreeCameraOptions();if(!s.position)return!1;const o=s.position.toLngLat();return o.distanceTo(i)<.9*o.distanceTo(this._lngLat)}_evaluateOpacity(){const e=this._map;if(!e)return;const t=this._pos;if(!t||t.x<0||t.x>e.transform.width||t.y<0||t.y>e.transform.height)return void this._clearFadeTimer();const i=e.unproject(t,this._altitude);let s;e._showingGlobe()&&Sr(e.transform,this._lngLat)?s=0:(s=1-e._queryFogOpacity(i),e.transform._terrainEnabled()&&e.style&&e.style.hasTerrain()&&this._behindTerrain()&&(s*=this._occludedOpacity)),this._element.style.opacity=`${s}`;const o=this._element.style.pointerEvents;(null===this._pointerEvents?""===o:o===this._pointerEvents)&&(this._pointerEvents=s>0?"auto":"none",this._element.style.pointerEvents=this._pointerEvents),this._popup&&this._popup._setOpacity(s),this._fadeTimer=null}_clearFadeTimer(){this._fadeTimer&&(clearTimeout(this._fadeTimer),this._fadeTimer=null)}_updateDOM(){const e=this._pos;if(!e||!this._map)return;const t=this._offset.mult(this._scale);this._element.style.transform=`\n translate(${e.x}px,${e.y}px)\n ${Jf[this._anchor]}\n ${this._calculateXYTransform()} ${this._calculateZTransform()}\n translate(${t.x}px,${t.y}px)\n `}_calculateXYTransform(){const e=this._pos,t=this._map,i=this.getPitchAlignment();if(!t||!e||"map"!==i)return"";if(!t._showingGlobe()){const e=t.getPitch();return e?`rotateX(${e}deg)`:""}const s=Ss(Dr(t.transform,this._lngLat)),o=e.sub(Rr(t.transform)),r=Math.abs(o.x)+Math.abs(o.y);if(0===r)return"";const n=s/r;return`rotateX(${-o.y*n}deg) rotateY(${o.x*n}deg)`}_calculateZTransform(){const e=this._pos,t=this._map;if(!t||!e)return"";let i=0;const s=this.getRotationAlignment();if("map"===s)if(t._showingGlobe()){const e=t.project(new Es(this._lngLat.lng,this._lngLat.lat+.001),this._altitude),s=t.project(new Es(this._lngLat.lng,this._lngLat.lat-.001),this._altitude).sub(e);i=Ss(Math.atan2(s.y,s.x))-90}else i=-t.getBearing();else if("horizon"===s){const s=Q(4,6,t.getZoom()),o=Rr(t.transform);o.y+=s*t.transform.height;const r=e.sub(o),n=Ss(Math.atan2(r.y,r.x));i=(n>90?n-270:n+90)*(1-s)}return i+=this._rotation,i?`rotateZ(${i}deg)`:""}_update(e){cancelAnimationFrame(this._updateFrameId);const t=this._map;t&&(t.transform.renderWorldCopies&&(this._lngLat=Kf(this._lngLat,this._pos,t.transform)),this._pos=t.project(this._lngLat,this._altitude),!0===e?this._updateFrameId=requestAnimationFrame(()=>{this._element&&this._pos&&this._anchor&&(this._pos=this._pos.round(),this._updateDOM())}):this._pos=this._pos.round(),t._requestDomTask(()=>{this._map&&(this._element&&this._pos&&this._anchor&&this._updateDOM(),(t._showingGlobe()||t.style&&t.style.hasTerrain()||t.getFog())&&!this._fadeTimer&&(this._fadeTimer=window.setTimeout(this._evaluateOpacity.bind(this),60)))}))}getOffset(){return this._offset}setOffset(e){return this._offset=m.convert(e),this._update(),this}addClassName(e){return this._element.classList.add(e),this}removeClassName(e){return this._element.classList.remove(e),this}toggleClassName(e){return this._element.classList.toggle(e)}_onMove(e){const t=this._map;if(!t)return;const i=this._pointerdownPos,s=this._positionDelta;if(i&&s){if(!this._isDragging){const s=this._clickTolerance||t._clickTolerance;if(e.point.dist(i)<s)return;this._isDragging=!0}this._pos=e.point.sub(s),this._lngLat=t.unproject(this._pos,this._altitude),this.setLngLat(this._lngLat),this._element.style.pointerEvents="none","pending"===this._state&&(this._state="active",this.fire(new M("dragstart"))),this.fire(new M("drag"))}}_onUp(){this._element.style.pointerEvents="auto",this._positionDelta=null,this._pointerdownPos=null,this._isDragging=!1;const e=this._map;e&&(e.off("mousemove",this._onMove),e.off("touchmove",this._onMove)),"active"===this._state&&this.fire(new M("dragend")),this._state="inactive"}_addDragHandler(e){const t=this._map,i=this._pos;t&&i&&this._element.contains(e.originalEvent.target)&&(e.preventDefault(),this._positionDelta=e.point.sub(i),this._pointerdownPos=e.point,this._state="pending",t.on("mousemove",this._onMove),t.on("touchmove",this._onMove),t.once("mouseup",this._onUp),t.once("touchend",this._onUp))}setDraggable(e){this._draggable=!!e;const t=this._map;return t&&(e?(t.on("mousedown",this._addDragHandler),t.on("touchstart",this._addDragHandler)):(t.off("mousedown",this._addDragHandler),t.off("touchstart",this._addDragHandler))),this}isDraggable(){return this._draggable}setRotation(e){return this._rotation=e||em.rotation,this._update(),this}getRotation(){return this._rotation}setRotationAlignment(e){return this._rotationAlignment=e||em.rotationAlignment,this._update(),this}getRotationAlignment(){return"auto"===this._rotationAlignment||"horizon"===this._rotationAlignment&&this._map&&!this._map._showingGlobe()?"viewport":this._rotationAlignment}setPitchAlignment(e){return this._pitchAlignment=e||em.pitchAlignment,this._update(),this}getPitchAlignment(){return"auto"===this._pitchAlignment?this.getRotationAlignment():this._pitchAlignment}setOccludedOpacity(e){return this._occludedOpacity=e||em.occludedOpacity,this._update(),this}getOccludedOpacity(){return this._occludedOpacity}}const im={OFF:[],WAITING_ACTIVE:["waiting","active"],ACTIVE_LOCK:["active"],ACTIVE_ERROR:["waiting","active-error"],BACKGROUND:["background"],BACKGROUND_ERROR:["waiting","background-error"]},sm=e=>`mapboxgl-ctrl-geolocate-${e}`,om=["waiting","active","active-error","background","background-error"].map(sm),rm={positionOptions:{enableHighAccuracy:!1,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showAccuracyCircle:!0,showUserLocation:!0,showUserHeading:!1,showButton:!0,followUserLocation:!0};class nm extends A{constructor(e={}){super();const t=navigator.geolocation;this.options={geolocation:t,...rm,...e},rt(["_onSuccess","_onError","_onZoom","_finish","_setupUI","_updateCamera","_updateMarker","_updateMarkerRotation","_onDeviceOrientation"],this),this._updateMarkerRotationThrottled=Ap(this._updateMarkerRotation,20),this._numberOfWatches=0}onAdd(e){return this._map=e,this._container=Tn("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._checkGeolocationSupport(this._setupUI),this._container}onRemove(){this._clearRequestTimeout(),void 0!==this._geolocationWatchID&&(this.options.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),this._container.remove(),this._map.off("zoom",this._onZoom),this._map=void 0,this._numberOfWatches=0,this._noTimeout=!1}_checkGeolocationSupport(e){const t=(t=!!this.options.geolocation)=>{this._supportsGeolocation=t,e(t)};void 0!==this._supportsGeolocation?e(this._supportsGeolocation):void 0!==navigator.permissions?navigator.permissions.query({name:"geolocation"}).then(e=>t("denied"!==e.state)).catch(()=>t()):t()}_isOutOfMapMaxBounds(e){const t=this._map.getMaxBounds(),i=e.coords;return!!t&&(i.longitude<t.getWest()||i.longitude>t.getEast()||i.latitude<t.getSouth()||i.latitude>t.getNorth())}_setWatchState(e){this._watchState=e;const t=this._geolocateButton.classList;t.remove(...om);for(const i of im[e])t.add(sm(i))}_setButtonTitle(e){const t=this._map._getUIString(e);this._geolocateButton.setAttribute("aria-label",t),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",t)}_setErrorState(){switch(this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":this._setWatchState("ACTIVE_ERROR");break;case"BACKGROUND":this._setWatchState("BACKGROUND_ERROR")}}_onSuccess(e){if(this._map){if(this._clearRequestTimeout(),this._isOutOfMapMaxBounds(e))return this._setErrorState(),this.fire(new M("outofmaxbounds",e)),this._updateMarker(),void this._finish();if(this._lastKnownPosition=e,this.options.trackUserLocation)switch(this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":this._setWatchState(this.options.followUserLocation?"ACTIVE_LOCK":"BACKGROUND");break;case"BACKGROUND":case"BACKGROUND_ERROR":this._setWatchState("BACKGROUND")}this.options.showUserLocation&&"OFF"!==this._watchState&&this._updateMarker(e),this.options.followUserLocation&&(!this.options.trackUserLocation||"ACTIVE_LOCK"===this._watchState)&&this._updateCamera(e),this.options.showUserLocation&&this._userLocationDotMarker.removeClassName("mapboxgl-user-location-dot-stale"),this.fire(new M("geolocate",{coords:e.coords,timestamp:e.timestamp,...e.toJSON?{toJSON:e.toJSON.bind(e)}:{}})),this._finish()}}_updateCamera(e){const t=new Es(e.coords.longitude,e.coords.latitude),i=e.coords.accuracy,s={bearing:this._map.getBearing(),...this.options.fitBoundsOptions};this._map.fitBounds(t.toBounds(i),s,{geolocateSource:!0})}_updateMarker(e){if(e){const t=new Es(e.coords.longitude,e.coords.latitude);this.options.showAccuracyCircle?this._accuracyCircleMarker.setLngLat(t).addTo(this._map):this._accuracyCircleMarker.remove(),this._userLocationDotMarker.setLngLat(t).addTo(this._map),this._accuracy=e.coords.accuracy,this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius()}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove()}_updateCircleRadius(){const e=this._map.transform,t=ws(1,e._center.lat)*e.worldSize,i=Math.ceil(2*this._accuracy*t);this._circleElement.style.width=`${i}px`,this._circleElement.style.height=`${i}px`}_onZoom(){this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius()}_updateMarkerRotation(){this._userLocationDotMarker&&"number"==typeof this._heading?(this._userLocationDotMarker.setRotation(this._heading),this._userLocationDotMarker.addClassName("mapboxgl-user-location-show-heading")):(this._userLocationDotMarker.removeClassName("mapboxgl-user-location-show-heading"),this._userLocationDotMarker.setRotation(0))}_onError(e){if(this._map){if(this._clearRequestTimeout(),this.options.trackUserLocation)if(1===e.code)this._setWatchState("OFF"),this._geolocateButton.disabled=!0,this._setButtonTitle("GeolocateControl.LocationNotAvailable"),void 0!==this._geolocationWatchID&&this._clearWatch();else{if(3===e.code&&this._noTimeout)return;this._setErrorState()}"OFF"!==this._watchState&&this.options.showUserLocation&&this._userLocationDotMarker.addClassName("mapboxgl-user-location-dot-stale"),this.fire(new M("error",{code:e.code,message:e.message,PERMISSION_DENIED:e.PERMISSION_DENIED,POSITION_UNAVAILABLE:e.POSITION_UNAVAILABLE,TIMEOUT:e.TIMEOUT})),this._finish()}}_finish(){this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0}_startRequestTimeout(){this._clearRequestTimeout();const e=this.options.positionOptions.timeout;e&&(this._requestTimeoutId=window.setTimeout(()=>{this._onError({code:3,message:"Geolocation request timed out"})},e))}_clearRequestTimeout(){void 0!==this._requestTimeoutId&&(clearTimeout(this._requestTimeoutId),this._requestTimeoutId=void 0)}_setupUI(e){void 0!==this._map&&(this._container.addEventListener("contextmenu",e=>e.preventDefault()),this._geolocateButton=Tn("button","mapboxgl-ctrl-geolocate",this._container),Tn("span","mapboxgl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",!1===e?(_("Geolocation support is not available so the GeolocateControl will be disabled."),this._geolocateButton.disabled=!0,this._setButtonTitle("GeolocateControl.LocationNotAvailable")):this._setButtonTitle("GeolocateControl.FindMyLocation"),this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._createUserLocationMarkers(),this.options.trackUserLocation&&(this._watchState="OFF"),this._map.on("zoom",this._onZoom)),this._geolocateButton.addEventListener("click",this.trigger.bind(this)),this._setup=!0,this.options.showButton||(this._container.style.display="none"),this.options.trackUserLocation&&this._map.on("movestart",e=>{e.geolocateSource||"ACTIVE_LOCK"!==this._watchState||e.originalEvent&&"resize"===e.originalEvent.type||(this._setWatchState("BACKGROUND"),this.fire(new M("trackuserlocationend")))}),this.fire(new M("ready")))}_onDeviceOrientation(e){this._userLocationDotMarker&&(e.webkitCompassHeading?this._heading=e.webkitCompassHeading:!0===e.absolute&&(this._heading=-1*e.alpha),this._updateMarkerRotationThrottled())}trigger(){if(!this._setup)return _("Geolocate control triggered before added to a map"),!1;if(this.options.trackUserLocation){switch(this._watchState){case"OFF":this._setWatchState("WAITING_ACTIVE"),this.fire(new M("trackuserlocationstart"));break;case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":case"BACKGROUND_ERROR":this._numberOfWatches--,this._noTimeout=!1,this._setWatchState("OFF"),this.fire(new M("trackuserlocationend"));break;case"BACKGROUND":this._setWatchState("ACTIVE_LOCK"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new M("trackuserlocationstart"))}if("OFF"===this._watchState&&void 0!==this._geolocationWatchID)this._clearWatch();else if(void 0===this._geolocationWatchID){let e;this._geolocateButton.classList.add(sm("waiting")),this._geolocateButton.setAttribute("aria-pressed","true"),this._numberOfWatches++,this._numberOfWatches>1?(e={maximumAge:6e5,timeout:0},this._noTimeout=!0):(e=this.options.positionOptions,this._noTimeout=!1),this._geolocationWatchID=this.options.geolocation.watchPosition(this._onSuccess,this._onError,e),this._startRequestTimeout(),this.options.showUserHeading&&this._addDeviceOrientationListener()}}else this.options.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._startRequestTimeout(),this._timeoutId=window.setTimeout(this._finish,1e4);return!0}setFollowUserLocation(e){return this.options.followUserLocation=e??rm.followUserLocation,this.options.trackUserLocation&&"OFF"!==this._watchState&&(this.options.followUserLocation?"BACKGROUND"!==this._watchState&&"BACKGROUND_ERROR"!==this._watchState||(this._setWatchState("ACTIVE_LOCK"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new M("trackuserlocationstart"))):"ACTIVE_LOCK"!==this._watchState&&"ACTIVE_ERROR"!==this._watchState||(this._setWatchState("BACKGROUND"),this.fire(new M("trackuserlocationend")))),this}setShowAccuracyCircle(e){if(this.options.showAccuracyCircle=e??rm.showAccuracyCircle,!this._accuracyCircleMarker)return this;if(this.options.showAccuracyCircle){if(this.options.showUserLocation&&this._lastKnownPosition){const{longitude:e,latitude:t,accuracy:i}=this._lastKnownPosition.coords;this._accuracy=i,this._accuracyCircleMarker.setLngLat(new Es(e,t)).addTo(this._map),this._updateCircleRadius()}}else this._accuracyCircleMarker.remove();return this}setShowUserHeading(e){return this.options.showUserHeading=e??rm.showUserHeading,this._setup?(this.options.showUserHeading?void 0!==this._geolocationWatchID&&this._addDeviceOrientationListener():(this._removeDeviceOrientationListener(),this._heading=void 0,this._userLocationDotMarker&&this._updateMarkerRotation()),this):this}setFitBoundsOptions(e){return this.options.fitBoundsOptions=e??rm.fitBoundsOptions,this}setShowUserLocation(e){return this.options.showUserLocation=e??rm.showUserLocation,this._setup?(this.options.showUserLocation?(this._userLocationDotMarker||(this._createUserLocationMarkers(),this._map.on("zoom",this._onZoom)),!this._lastKnownPosition||void 0!==this._watchState&&"OFF"===this._watchState||this._updateMarker(this._lastKnownPosition)):(this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this._accuracyCircleMarker&&this._accuracyCircleMarker.remove()),this):this}_addDeviceOrientationListener(){const e=()=>{const e="ondeviceorientationabsolute"in window?"deviceorientationabsolute":"deviceorientation";window.addEventListener(e,this._onDeviceOrientation)},t=DeviceOrientationEvent;"function"==typeof t?.requestPermission?t.requestPermission().then(t=>{"granted"===t?e():_("GeolocateControl: permission to use device orientation was denied, so the user heading arrow will not be shown.")}).catch(()=>{_("GeolocateControl: could not request device orientation permission. Enable the user heading from a user gesture (click/tap) so the browser can prompt for access.")}):e()}_removeDeviceOrientationListener(){window.removeEventListener("deviceorientation",this._onDeviceOrientation),window.removeEventListener("deviceorientationabsolute",this._onDeviceOrientation)}_createUserLocationMarkers(){this._dotElement=Tn("div","mapboxgl-user-location"),this._dotElement.appendChild(Tn("div","mapboxgl-user-location-dot")),this._dotElement.appendChild(Tn("div","mapboxgl-user-location-heading")),this._userLocationDotMarker=new tm({element:this._dotElement,rotationAlignment:"map",pitchAlignment:"map"}),this._circleElement=Tn("div","mapboxgl-user-location-accuracy-circle"),this._accuracyCircleMarker=new tm({element:this._circleElement,pitchAlignment:"map"})}_clearWatch(){this._clearRequestTimeout(),this.options.geolocation.clearWatch(this._geolocationWatchID),this._removeDeviceOrientationListener(),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove(sm("waiting")),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null)}}const am={maxWidth:100,unit:"metric"},lm={kilometer:"km",meter:"m",mile:"mi",foot:"ft","nautical-mile":"nm"};class cm{constructor(e={}){this.options={...am,...e},rt(["_update","_setScale","setUnit"],this)}getDefaultPosition(){return"bottom-left"}_update(){const e=this.options.maxWidth||100,t=this._map,i=t._containerHeight/2,s=t._containerWidth/2-e/2,o=t.unproject([s,i]),r=t.unproject([s+e,i]),n=o.distanceTo(r);if("imperial"===this.options.unit){const t=3.2808*n;t>5280?this._setScale(e,t/5280,"mile"):this._setScale(e,t,"foot")}else"nautical"===this.options.unit?this._setScale(e,n/1852,"nautical-mile"):n>=1e3?this._setScale(e,n/1e3,"kilometer"):this._setScale(e,n,"meter")}_setScale(e,t,i){this._map._requestDomTask(()=>{const s=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}(t),o=s/t;this._container.innerHTML="nautical-mile"!==i?new Intl.NumberFormat(this._language,{style:"unit",unitDisplay:"short",unit:i}).format(s):`${s}&nbsp;${lm[i]}`,this._container.style.width=e*o+"px"})}onAdd(e){return this._map=e,this._language=e.getLanguage(),this._container=Tn("div","mapboxgl-ctrl mapboxgl-ctrl-scale",e.getContainer()),this._container.dir="auto",this._map.on("move",this._update),this._update(),this._container}onRemove(){this._container.remove(),this._map.off("move",this._update),this._map=void 0}_setLanguage(e){this._language=e,this._update()}setUnit(e){this.options.unit=e,this._update()}}class hm{constructor(e={}){this._fullscreen=!1,e&&e.container&&(e.container instanceof HTMLElement?this._container=e.container:_("Full screen control 'container' must be a DOM element.")),rt(["_onClickFullscreen","_changeIcon"],this),"onfullscreenchange"in document?this._fullscreenchange="fullscreenchange":"onwebkitfullscreenchange"in document&&(this._fullscreenchange="webkitfullscreenchange")}onAdd(e){return this._map=e,this._container||(this._container=this._map.getContainer()),this._controlContainer=Tn("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._checkFullscreenSupport()?this._setupUI():(this._controlContainer.style.display="none",_("This device does not support fullscreen mode.")),this._controlContainer}onRemove(){this._controlContainer.remove(),this._map=null,document.removeEventListener(this._fullscreenchange,this._changeIcon)}_checkFullscreenSupport(){return!(!document.fullscreenEnabled&&!document.webkitFullscreenEnabled)}_setupUI(){const e=this._fullscreenButton=Tn("button","mapboxgl-ctrl-fullscreen",this._controlContainer);Tn("span","mapboxgl-ctrl-icon",e).setAttribute("aria-hidden","true"),e.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),document.addEventListener(this._fullscreenchange,this._changeIcon)}_updateTitle(){const e=this._getTitle();this._fullscreenButton.setAttribute("aria-label",e),this._fullscreenButton.firstElementChild&&this._fullscreenButton.firstElementChild.setAttribute("title",e)}_getTitle(){return this._map._getUIString(this._isFullscreen()?"FullscreenControl.Exit":"FullscreenControl.Enter")}_isFullscreen(){return this._fullscreen}_changeIcon(){(document.fullscreenElement||document.webkitFullscreenElement)===this._container!==this._fullscreen&&(this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle("mapboxgl-ctrl-shrink"),this._fullscreenButton.classList.toggle("mapboxgl-ctrl-fullscreen"),this._updateTitle())}_onClickFullscreen(){this._isFullscreen()?document.exitFullscreen?document.exitFullscreen():document.webkitCancelFullScreen&&document.webkitCancelFullScreen():this._container.requestFullscreen?this._container.requestFullscreen():this._container.webkitRequestFullscreen&&this._container.webkitRequestFullscreen()}}class dm{constructor(){rt(["_onIndoorUpdate","_onStyleData","_scrollUp","_scrollDown","_toggleIndoor"],this),this._visibleFloorStart=0,this._lastSelectedFloorId=null}onAdd(e){return this._map=e,this._container=Tn("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.style.display="none",this._map.on("styledata",this._onStyleData),this._map.on("idle",this._onStyleData),this._updateConnection(),this._container}_onStyleData(){this._updateConnection()}_updateConnection(){if(this._map&&this._map.style&&this._map.style.indoorManager){const e=this._map.style.indoorManager;e.off("selector-update",this._onIndoorUpdate),e.on("selector-update",this._onIndoorUpdate),this._onIndoorUpdate(e.getControlState()),this._map.off("idle",this._onStyleData)}}_createButton(e,t){const i=Tn("button",e,this._container);return i.type="button",i.addEventListener("click",t),i}_setButtonTitle(e,t){e.setAttribute("aria-label",t),e.textContent=t}onRemove(){this._container&&this._container.remove(),this._map&&(this._map.off("styledata",this._onStyleData),this._map.off("idle",this._onStyleData),this._map.style&&this._map.style.indoorManager&&this._map.style.indoorManager.off("selector-update",this._onIndoorUpdate),this._map=null)}getDefaultPosition(){return"top-right"}_onIndoorUpdate(e){if(!e||!e.floors||0===e.floors.length)return this._model=e,void(this._container.style.display="none");const t=this._model;this._model=e,this._container.style.display="inline-block";const i=!t||t.floors.length!==e.floors.length||t.floors.some((t,i)=>t.id!==e.floors[i].id);if(i&&(this._visibleFloorStart=0,this._lastSelectedFloorId=null),e.selectedFloorId){if(e.selectedFloorId!==this._lastSelectedFloorId||i){const t=e.floors.findIndex(t=>t.id===e.selectedFloorId);if(-1!==t){const i=e.floors.length;let s,o;i<=5?(s=0,o=i-1):0===this._visibleFloorStart?(s=0,o=3):this._visibleFloorStart>=i-3?(s=i-3-1,o=i-1):(s=this._visibleFloorStart,o=this._visibleFloorStart+3-1),t<s?this._visibleFloorStart=t:t>o&&(this._visibleFloorStart=t-2)}}this._lastSelectedFloorId=e.selectedFloorId}this._render()}_render(){if(!this._container||!this._model||!this._model.floors)return;this._container.innerHTML="";const e=this._createButton("mapboxgl-ctrl-indoor-toggle",this._toggleIndoor);Tn("span","mapboxgl-ctrl-icon",e).setAttribute("aria-hidden","true"),this._model.activeFloorsVisible||e.classList.add("mapboxgl-ctrl-level-button-selected"),this._container.appendChild(e);const t=this._model.floors,i=t.length;if(i<=5)return void t.forEach(e=>this._createFloorButton(e));const s=0===this._visibleFloorStart,o=this._visibleFloorStart>=i-3;if(s)this._createFloorButton(t[0]);else{const e=this._createButton("mapboxgl-ctrl-arrow-up",this._scrollUp);Tn("span","mapboxgl-ctrl-icon",e).setAttribute("aria-hidden","true"),this._container.appendChild(e)}let r=[];if(r=s?t.slice(1,4):o?t.slice(this._visibleFloorStart-1,this._visibleFloorStart+3-1):t.slice(this._visibleFloorStart,this._visibleFloorStart+3),r.forEach(e=>this._createFloorButton(e)),o)this._createFloorButton(t[i-1]);else{const e=this._createButton("mapboxgl-ctrl-arrow-down",this._scrollDown);Tn("span","mapboxgl-ctrl-icon",e).setAttribute("aria-hidden","true"),this._container.appendChild(e)}}_createFloorButton(e){const t=this._createButton("mapboxgl-ctrl-level-button",()=>{const t=e.id;this._model&&this._model.selectedFloorId===t&&this._model.activeFloorsVisible||this._map&&(this._model&&!this._model.activeFloorsVisible&&this._map.style&&this._map.style.indoorManager&&this._map.style.indoorManager.setActiveFloorsVisibility(!0),this._map._selectIndoorFloor(t))}),i=(e.name||"").trim(),s=e.zIndex.toString(),o=i?Array.from(i).slice(0,3).join(""):s;this._setButtonTitle(t,o),this._model&&this._model.activeFloorsVisible&&e.id===this._model.selectedFloorId&&t.classList.add("mapboxgl-ctrl-level-button-selected"),this._container&&this._container.appendChild(t)}_toggleIndoor(){this._map&&this._map.style&&this._map.style.indoorManager&&this._model&&this._model.activeFloorsVisible&&this._map.style.indoorManager.setActiveFloorsVisibility(!1)}_scrollUp(){if(this._visibleFloorStart>0){this._visibleFloorStart--,1===this._visibleFloorStart&&(this._visibleFloorStart=0);const e=this._model&&this._model.floors||[];if(e.length>3){const t=e.length-3;this._visibleFloorStart===t-1&&(this._visibleFloorStart=t-2)}this._render()}}_scrollDown(){if(this._model&&this._model.floors){const e=this._model.floors.length-3;this._visibleFloorStart<e&&(this._visibleFloorStart++,1===this._visibleFloorStart&&(this._visibleFloorStart=2),this._visibleFloorStart===e-1&&(this._visibleFloorStart=e),this._visibleFloorStart>e&&(this._visibleFloorStart=e),this._render())}}}const um=/\s+/,_m={closeButton:!0,closeOnClick:!0,focusAfterOpen:!0,className:"",maxWidth:"240px",altitude:0},pm=["a[href]","[tabindex]:not([tabindex='-1'])","[contenteditable]:not([contenteditable='false'])","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])"].join(", ");class fm extends A{constructor(e){super(),this.options=Object.assign(Object.create(_m),e),this._altitude=this.options.altitude,rt(["_update","_onClose","remove","_onMouseEvent"],this),this._classList=new Set(e&&e.className?e.className.trim().split(um):[])}addTo(e){return this._map&&this.remove(),this._map=e,this.options.closeOnClick&&e.on("preclick",this._onClose),this.options.closeOnMove&&e.on("move",this._onClose),e.on("remove",this.remove),this._update(),e._addPopup(this),this._focusFirstElement(),this._trackPointer?(e.on("mousemove",this._onMouseEvent),e.on("mouseup",this._onMouseEvent),e._canvasContainer.classList.add("mapboxgl-track-pointer")):e.on("move",this._update),this.fire(new M("open")),this}isOpen(){return!!this._map}remove(){this._content&&this._content.remove(),this._container&&(this._container.remove(),this._container=void 0);const e=this._map;return e&&(e.off("move",this._update),e.off("move",this._onClose),e.off("preclick",this._onClose),e.off("click",this._onClose),e.off("remove",this.remove),e.off("mousemove",this._onMouseEvent),e.off("mouseup",this._onMouseEvent),e.off("drag",this._onMouseEvent),e._canvasContainer&&e._canvasContainer.classList.remove("mapboxgl-track-pointer"),e._removePopup(this),this._map=void 0),this.fire(new M("close")),this}getLngLat(){return this._lngLat}setLngLat(e){this._lngLat=Es.convert(e),this._pos=null,this._trackPointer=!1,this._update();const t=this._map;return t&&(t.on("move",this._update),t.off("mousemove",this._onMouseEvent),t._canvasContainer.classList.remove("mapboxgl-track-pointer")),this}getAltitude(){return this._altitude}setAltitude(e){return this._altitude=e,this._update(),this}trackPointer(){this._trackPointer=!0,this._pos=null,this._update();const e=this._map;return e&&(e.off("move",this._update),e.on("mousemove",this._onMouseEvent),e.on("drag",this._onMouseEvent),e._canvasContainer.classList.add("mapboxgl-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 s;for(i.innerHTML=e;s=i.firstChild,s;)t.appendChild(s);return this.setDOMContent(t)}getMaxWidth(){return this._container&&this._container.style.maxWidth}setMaxWidth(e){return this.options.maxWidth=e,this._update(),this}setDOMContent(e){let t=this._content;if(t)for(;t.hasChildNodes();)t.firstChild&&t.removeChild(t.firstChild);else t=this._content=Tn("div","mapboxgl-popup-content",this._container||void 0);if(t.appendChild(e),this.options.closeButton){const e=this._closeButton=Tn("button","mapboxgl-popup-close-button",t);e.type="button",e.setAttribute("aria-label","Close popup"),e.innerHTML='<span aria-hidden="true">&#215;</span>',e.addEventListener("click",this._onClose)}return this._update(),this._focusFirstElement(),this}addClassName(e){return this._classList.add(e),this._updateClassList(),this}removeClassName(e){return this._classList.delete(e),this._updateClassList(),this}setOffset(e){return this.options.offset=e,this._update(),this}toggleClassName(e){let t;return this._classList.delete(e)?t=!1:(this._classList.add(e),t=!0),this._updateClassList(),t}_onMouseEvent(e){this._update(e.point)}_getAnchor(e){if(this.options.anchor)return this.options.anchor;const t=this._map,i=this._container,s=this._pos;if(!t||!i||!s)return"bottom";const o=i.offsetWidth,r=i.offsetHeight,n=s.x<o/2,a=s.x>t.transform.width-o/2;if(s.y+e<r)return n?"top-left":a?"top-right":"top";if(s.y>t.transform.height-r){if(n)return"bottom-left";if(a)return"bottom-right"}return n?"left":a?"right":"bottom"}_updateClassList(){const e=this._container;if(!e)return;const t=[...this._classList];t.push("mapboxgl-popup"),this._anchor&&t.push(`mapboxgl-popup-anchor-${this._anchor}`),this._trackPointer&&t.push("mapboxgl-popup-track-pointer"),e.className=t.join(" ")}_update(e){const t=this._map,i=this._content;if(!t||!this._lngLat&&!this._trackPointer||!i)return;let s=this._container;if(s||(s=this._container=Tn("div","mapboxgl-popup",t.getContainer()),this._tip=Tn("div","mapboxgl-popup-tip",s),s.appendChild(i)),this.options.maxWidth&&s.style.maxWidth!==this.options.maxWidth&&(s.style.maxWidth=this.options.maxWidth),t.transform.renderWorldCopies&&!this._trackPointer&&(this._lngLat=Kf(this._lngLat,this._pos,t.transform)),!this._trackPointer||e){const i=this._pos=this._trackPointer&&e instanceof m?e:t.project(this._lngLat,this._altitude),s=mm(this.options.offset),o=this._anchor=this._getAnchor(s.y),r=mm(this.options.offset,o),n=i.add(r).round();t._requestDomTask(()=>{this._container&&o&&(this._container.style.transform=`${Jf[o]} translate(${n.x}px,${n.y}px)`)})}if(!this._marker&&t._showingGlobe()){const e=Sr(t.transform,this._lngLat)?0:1;this._setOpacity(e)}this._updateClassList()}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const e=this._container.querySelector(pm);e&&e.focus()}_onClose(){this.remove()}_setOpacity(e){this._container&&(this._container.style.opacity=`${e}`),this._content&&(this._content.style.pointerEvents=e?"auto":"none")}}function mm(e=new m(0,0),t="bottom"){if("number"==typeof e){const i=Math.round(Math.sqrt(.5*Math.pow(e,2)));switch(t){case"top":return new m(0,e);case"top-left":return new m(i,i);case"top-right":return new m(-i,i);case"bottom":return new m(0,-e);case"bottom-left":return new m(i,-i);case"bottom-right":return new m(-i,-i);case"left":return new m(e,0);case"right":return new m(-e,0)}return new m(0,0)}return e instanceof m||Array.isArray(e)?m.convert(e):m.convert(e[t]||[0,0])}var gm;gm=t(import.meta.url)?"cdn":"other",Yr=gm;const vm=Cr;export{tm as $,Ul as A,en as B,zu as C,Cu as D,Q_ as E,wu as F,H_ as G,$_ as H,pd as I,fd as J,su as K,Tl as L,wl as M,el as N,Tu as O,El as P,xl as Q,jl as R,Pu as S,yc as T,kf as U,Da as V,bu as W,hm as X,nm as Y,dm as Z,Hf as _,Lu as a,Xf as a0,fm as a1,cm as a2,Nd as a3,Fc as a4,ul as a5,zc as a6,Xr as a7,_l as a8,ll as a9,mn as aa,vm as ab,A_ as b,hd as c,Gh as d,I_ as e,sp as f,Iu as g,Ja as h,mu as i,Ac as j,pu as k,bp as l,Ed as m,Ra as n,cd as o,tp as p,nd as q,xc as r,ad as s,kh as t,ld as u,Zh as v,yd as w,Xh as x,Ru as y,jh as z};//# sourceMappingURL=core.js.map