2 lines
880 KiB
JavaScript
2 lines
880 KiB
JavaScript
import{i as e,a as t,b as i,c as o,d as s,P as r,v as n,e as a,u as l,g as c,f as h,s as d,w as u,p as _,h as p,j as f,k as m,l as g,I as v,m as y,R as x,n as b,o as w,q as T,E,r as S,D as I,t as C,x as R,y as A,z as D,A as L,B as O,C as P,F as M,T as z,G as F,H as B,V as k,J as N,K as U,L as j,M as G,N as V,O as H,Q as q,S as Z,U as W,W as $,X,Y,Z as K,_ as Q,$ as J,a0 as ee,a1 as te,a2 as ie,a3 as oe,a4 as se,a5 as re,a6 as ne,a7 as ae,a8 as le,a9 as ce,aa as he,ab as de,ac as ue,ad as _e,ae as pe,af as fe,ag as me,ah as ge,ai as ve,aj as ye,ak as xe,al as be,am as we,an as Te,ao as Ee,ap as Se,aq as Ie,ar as Ce,as as Re,at as Ae,au as De,av as Le,aw as Oe,ax as Pe,ay as Me,az as ze,aA as Fe,aB as Be,aC as ke,aD as Ne,aE as Ue,aF as je,aG as Ge,aH as Ve,aI as He,aJ as qe,aK as Ze,aL as We,aM as $e,aN as Xe,aO as Ye,aP as Ke,aQ as Qe,aR as Je,aS as et,aT as tt,aU as it,aV as ot,aW as st,aX as rt,aY as nt,aZ as at,a_ as lt,a$ as ct,b0 as ht,b1 as dt,b2 as ut,b3 as _t,b4 as pt,b5 as ft,b6 as mt,b7 as gt,b8 as vt,b9 as yt,ba as xt,bb as bt,bc as wt,bd as Tt,be as Et,bf as St,bg as It,bh as Ct,bi as Rt,bj as At,bk as Dt,bl as Lt,bm as Ot,bn as Pt,bo as Mt,bp as zt,bq as Ft,br as Bt,bs as kt,bt as Nt,bu as Ut,bv as jt,bw as Gt,bx as Vt,by as Ht,bz as qt,bA as Zt,bB as Wt,bC as $t,bD as Xt,bE as Yt,bF as Kt,bG as Qt,bH as Jt,bI as ei,bJ as ti,bK as ii,bL as oi,bM as si,bN as ri,bO as ni,bP as ai,bQ as li,bR as ci,bS as hi,bT as di,bU as ui,bV as _i,bW as pi,bX as fi,bY as mi,bZ as gi,b_ as vi,b$ as yi,c0 as xi,c1 as bi,c2 as wi,c3 as Ti,c4 as Ei,c5 as Si,c6 as Ii,c7 as Ci,c8 as Ri,c9 as Ai,ca as Di,cb as Li,cc as Oi,cd as Pi,ce as Mi,cf as zi,cg as Fi,ch as Bi,ci as ki,cj as Ni,ck as Ui,cl as ji,cm as Gi,cn as Vi,co as Hi,cp as qi,cq as Zi,cr as Wi,cs as $i,ct as Xi,cu as Yi,cv as Ki,cw as Qi,cx as Ji,cy as eo,cz as to,cA as io,cB as oo,cC as so,cD as ro,cE as no,cF as ao,cG as lo,cH as co,cI as ho,cJ as uo,cK as _o,cL as po,cM as fo,cN as mo,cO as go,cP as vo,cQ as yo,cR as xo,cS as bo,cT as wo,cU as To,cV as Eo,cW as So,cX as Io,cY as Co,cZ as Ro,c_ as Ao,c$ as Do,d0 as Lo,d1 as Oo,d2 as Po,d3 as Mo,d4 as zo,d5 as Fo,d6 as Bo,d7 as ko,d8 as No,d9 as Uo,da as jo,db as Go,dc as Vo,dd as Ho,de as qo,df as Zo,dg as Wo,dh as $o,di as Xo,dj as Yo,dk as Ko,dl as Qo,dm as Jo,dn as es,dp as ts,dq as is,dr as os,ds as ss,dt as rs,du as ns,dv as as,dw as ls,dx as cs,dy as hs,dz as ds,dA as us,dB as _s,dC as ps,dD as fs,dE as ms,dF as gs,dG as vs,dH as ys,dI as xs,dJ as bs,dK as ws,dL as Ts,dM as Es,dN as Ss,dO as Is,dP as Cs,dQ as Rs,dR as As,dS as Ds,dT as Ls,dU as Os,dV as Ps,dW as Ms,dX as zs,dY as Fs,dZ as Bs,d_ as ks,d$ as Ns,e0 as Us,e1 as js,e2 as Gs,e3 as Vs,e4 as Hs,e5 as qs,e6 as Zs,e7 as Ws,e8 as $s,e9 as Xs,ea as Ys,eb as Ks,ec as Qs,ed as Js,ee as er,ef as tr,eg as ir,eh as or,ei as sr,ej as rr,ek as nr,el as ar,em as lr,en as cr,eo as hr,ep as dr,eq as ur,er as _r,es as pr,et as fr,eu as mr,ev as gr,ew as vr,ex as yr,ey as xr,ez as br,eA as wr,eB as Tr,eC as Er,eD as Sr,eE as Ir,eF as Cr,eG as Rr,eH as Ar,eI as Dr,eJ as Lr,eK as Or,eL as Pr,eM as Mr,eN as zr,eO as Fr,eP as Br,eQ as kr,eR as Nr,eS as Ur,eT as jr,eU as Gr,eV as Vr,eW as Hr,eX as qr,eY as Zr,eZ as Wr,e_ as $r,e$ as Xr,f0 as Yr,f1 as Kr,f2 as Qr,f3 as Jr,f4 as en,f5 as tn,f6 as on,f7 as sn,f8 as rn,f9 as nn,fa as an,fb as ln,fc as cn,fd as hn,fe as dn,ff as un,fg as _n,fh as pn,fi as fn}from"./shared.js";var mn="3.17.0";const gn={create:"create",load:"load",fullLoad:"fullLoad"},vn={mark(e){performance.mark(e)},measure(e,t,i){performance.measure(e,t,i)}};function yn(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":o(n)?"sprite":e(n)?"style":s(n)?"tilejson":"other"}var xn,bn={},wn=function(){if(xn)return bn;function e(e){return!t(e)}function t(t){return"undefined"==typeof window||"undefined"==typeof document?"not a browser":function(){if(!("Worker"in window&&"Blob"in window&&"URL"in window))return!1;var e,t,i=new Blob([""],{type:"text/javascript"}),o=URL.createObjectURL(i);try{t=new Worker(o),e=!0}catch(t){e=!1}return t&&t.terminate(),URL.revokeObjectURL(o),e}()?function(){var e=document.createElement("canvas");e.width=e.height=1;var t=e.getContext("2d");if(!t)return!1;var i=t.getImageData(0,0,1,1);return i&&i.width===e.width}()?(void 0===i[o=t&&t.failIfMajorPerformanceCaveat]&&(i[o]=function(t){var i,o=function(t){var i=document.createElement("canvas"),o=Object.create(e.webGLContextAttributes);return o.failIfMajorPerformanceCaveat=t,i.getContext("webgl2",o)}(t);if(!o)return!1;try{i=o.createShader(o.VERTEX_SHADER)}catch(e){return!1}return!(!i||o.isContextLost())&&(o.shaderSource(i,"void main() {}"),o.compileShader(i),!0===o.getShaderParameter(i,o.COMPILE_STATUS))}(o)),i[o]?document.documentMode?"insufficient ECMAScript 6 support":void 0:"insufficient WebGL2 support"):"insufficient Canvas/getImageData support":"insufficient worker support";var o}xn=1,bn.supported=e,bn.notSupportedReason=t;var i={};return e.webGLContextAttributes={antialias:!1,alpha:!0,stencil:!0,depth:!0},bn}();function Tn(e,t,i){const o=document.createElement(e);return null!=t&&(o.className=t),i&&i.appendChild(o),o}function En(e,t,i){const o=document.createElementNS("http://www.w3.org/2000/svg",e);for(const e of Object.keys(t))o.setAttributeNS(null,e,String(t[e]));return i&&i.appendChild(o),o}const Sn="undefined"!=typeof document?document.documentElement&&document.documentElement.style:null,In=Sn&&void 0!==Sn.userSelect?"userSelect":"WebkitUserSelect";let Cn;function Rn(){Sn&&In&&(Cn=Sn[In],Sn[In]="none")}function An(){Sn&&In&&(Sn[In]=Cn)}function Dn(e){e.preventDefault(),e.stopPropagation(),window.removeEventListener("click",Dn,!0)}function Ln(){window.addEventListener("click",Dn,!0),window.setTimeout((()=>{window.removeEventListener("click",Dn,!0)}),0)}function On(e,t){const i=e.getBoundingClientRect();return zn(e,i,t)}function Pn(e,t){const i=e.getBoundingClientRect(),o=[];for(let s=0;s<t.length;s++)o.push(zn(e,i,t[s]));return o}function Mn(e){return/firefox/i.test(navigator.userAgent)&&/macintosh/i.test(navigator.userAgent)&&2===e.button&&e.ctrlKey?0:e.button}function zn(e,t,i){const o=e.offsetWidth===t.width?1:e.offsetWidth/t.width;return new r((i.clientX-t.left)*o,(i.clientY-t.top)*o)}const Fn="01",Bn="NO_ACCESS_TOKEN";class kn{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",Fn,e].join(""),tokenExpiresAt:Date.now()+432e5}}();this._skuToken=e.token,this._skuTokenExpiresAt=e.tokenExpiresAt}_isSkuTokenExpired(){return Date.now()>this._skuTokenExpiresAt}transformRequest(e,t){return this._transformRequestFn&&this._transformRequestFn(e,t)||{url:e}}normalizeStyleURL(e,t){if(!p(e))return e;const i=Un(e);return i.params.push(`sdk=js-${mn}`),i.path=`/styles/v1${i.path}`,this._makeAPIURL(i,this._customAccessToken||t)}normalizeGlyphsURL(e,t){if(!p(e))return e;const i=Un(e);return i.path=`/fonts/v1${i.path}`,this._makeAPIURL(i,this._customAccessToken||t)}normalizeModelURL(e,t){if(!p(e))return e;const i=Un(e);return i.path=`/models/v1${i.path}`,this._makeAPIURL(i,this._customAccessToken||t)}normalizeSourceURL(e,t,i,o){if(!p(e))return e;const s=Un(e);return s.path=`/v4/${s.authority}.json`,s.params.push("secure"),i&&s.params.push(`language=${i}`),o&&s.params.push(`worldview=${o}`),this._makeAPIURL(s,this._customAccessToken||t)}normalizeIconsetURL(e,t){const i=Un(e);return p(e)?(i.path=`/styles/v1${i.path}/iconset.pbf`,this._makeAPIURL(i,this._customAccessToken||t)):jn(i)}normalizeSpriteURL(e,t,i,o){const s=Un(e);return p(e)?(s.path=`/styles/v1${s.path}/sprite${t}${i}`,this._makeAPIURL(s,this._customAccessToken||o)):(s.path+=`${t}${i}`,jn(s))}normalizeTileURL(e,t,i){if(this._isSkuTokenExpired()&&this._createSkuToken(),e&&!p(e))return e;const o=Un(e);o.path=o.path.replace(/(\.(png|jpg)\d*)(?=$)/,`${t||i&&"raster"!==o.authority&&512===i?"@2x":""}${m.supported?".webp":"$1"}`),"raster"===o.authority?o.path=`/${a.RASTER_URL_PREFIX}${o.path}`:"rasterarrays"===o.authority?o.path=`/${a.RASTERARRAYS_URL_PREFIX}${o.path}`:"3dtiles"===o.authority?o.path=`/${a.TILES3D_URL_PREFIX}${o.path}`:(o.path=o.path.replace(/^.+\/v4\//,"/"),o.path=`/${a.TILE_URL_VERSION}${o.path}`);const s=this._customAccessToken||function(e){for(const t of e){const e=t.match(/^access_token=(.*)$/);if(e)return e[1]}return null}(o.params)||a.ACCESS_TOKEN;return a.REQUIRE_ACCESS_TOKEN&&s&&this._skuToken&&o.params.push(`sku=${this._skuToken}`),this._makeAPIURL(o,s)}canonicalizeTileURL(e,t){const i=Un(e);if(!i.path.match(/^(\/v4\/|\/(raster|rasterarrays)\/v1\/)/)||!i.path.match(/\.[\w]+$/))return e;let o="mapbox://";i.path.match(/^\/raster\/v1\//)?o+=`raster/${i.path.replace(`/${a.RASTER_URL_PREFIX}/`,"")}`:i.path.match(/^\/rasterarrays\/v1\//)?o+=`rasterarrays/${i.path.replace(`/${a.RASTERARRAYS_URL_PREFIX}/`,"")}`:o+=`tiles/${i.path.replace(`/${a.TILE_URL_VERSION}/`,"")}`;let s=i.params;return t&&(s=s.filter((e=>!e.match(/^access_token=/)))),s.length&&(o+=`?${s.join("&")}`),o}canonicalizeTileset(e,t){const i=!!t&&p(t),o=[];for(const t of e.tiles||[])f(t)?o.push(this.canonicalizeTileURL(t,i)):o.push(t);return o}_makeAPIURL(e,t){const i="See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes",o=Un(a.API_URL);if(e.protocol=o.protocol,e.authority=o.authority,"http"===e.protocol){const t=e.params.indexOf("secure");t>=0&&e.params.splice(t,1)}if("/"!==o.path&&(e.path=`${o.path}${e.path}`),!a.REQUIRE_ACCESS_TOKEN)return jn(e);if(t=t||a.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=>-1===e.indexOf("access_token"))),e.params.push(`access_token=${t||""}`),jn(e)}}const Nn=/^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;function Un(e){const t=e.match(Nn);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 jn(e){const t=e.params.length?`?${e.params.join("&")}`:"";return`${e.protocol}://${e.authority}${e.path}${t}`}const Gn="mapbox.eventData";function Vn(e){if(!e)return null;const t=e.split(".");if(!t||3!==t.length)return null;try{return JSON.parse(g(t[1]))}catch(e){return null}}class Hn{constructor(e){this.type=e,this.anonId=null,this.anonIdTimestamp=null,this.eventData={},this.queue=[],this.pendingRequest=null}getStorageKey(e){const t=Vn(a.ACCESS_TOKEN);let i="";return i=t&&t.u?h(t.u):a.ACCESS_TOKEN||"",e?`${Gn}.${e}:${i}`:`${Gn}:${i}`}fetchEventData(){const e=d("localStorage"),t=this.getStorageKey(),i=this.getStorageKey("uuid"),o=this.getStorageKey("uuidTimestamp");if(e)try{const e=localStorage.getItem(t);e&&(this.eventData=JSON.parse(e));const s=localStorage.getItem(i);s&&(this.anonId=s);const r=localStorage.getItem(o);r&&(this.anonIdTimestamp=Number(r));const n=Date.now()-864e5;(!this.anonIdTimestamp||this.anonIdTimestamp<n)&&this.refreshUUID()}catch(e){u("Unable to read from LocalStorage")}}refreshUUID(){this.anonId=l(),this.anonIdTimestamp=Date.now()}saveEventData(){const e=d("localStorage"),t=this.getStorageKey(),i=this.getStorageKey("uuid"),o=this.getStorageKey("uuidTimestamp"),s=this.anonId,r=this.anonIdTimestamp;if(e&&s)try{localStorage.setItem(i,s),Object.keys(this.eventData).length>=1&&localStorage.setItem(t,JSON.stringify(this.eventData)),r&&localStorage.setItem(o,r.toString())}catch(e){u("Unable to write to LocalStorage")}}processRequests(e){}postEvent(e,t,i,o){if(!a.EVENTS_URL)return;const s=Un(a.EVENTS_URL);s.params.push(`access_token=${o||a.ACCESS_TOKEN||""}`);const r={event:this.type,created:new Date(e).toISOString()},n=t?Object.assign(r,t):r,l={url:jn(s),headers:{"Content-Type":"text/plain"},body:JSON.stringify([n])};this.pendingRequest=_(l,(e=>{this.pendingRequest=null,i(e),this.saveEventData(),this.processRequests(o)}))}queueRequest(e,t){this.queue.push(e),this.processRequests(t)}}class qn extends Hn{constructor(e){super("metrics"),e&&(this.data=e)}postMetricsEvent(e){if(!a.EVENTS_URL||!e&&!a.ACCESS_TOKEN)return;this.anonId||this.fetchEventData(),n(this.anonId)||this.refreshUUID();const t=Object.assign({},this.data,{sessionId:this.anonId});this.queueRequest({timestamp:Date.now(),payload:t},e)}processRequests(e){if(this.pendingRequest||0===this.queue.length)return;const{timestamp:t,payload:i}=this.queue.shift();this.postEvent(t,i,(()=>{}),e)}}const Zn=new class extends Hn{constructor(e){super("appUserTurnstile"),this._customAccessToken=e}postTurnstileEvent(e,t){a.EVENTS_URL&&a.ACCESS_TOKEN&&Array.isArray(e)&&e.some((e=>p(e)||f(e)))&&this.queueRequest(Date.now(),t)}processRequests(e){if(this.pendingRequest||0===this.queue.length)return;this.anonId&&this.anonIdTimestamp&&this.eventData.lastSuccess&&this.eventData.tokenU||this.fetchEventData();const t=Vn(a.ACCESS_TOKEN),i=t?t.u:a.ACCESS_TOKEN;let o=i!==this.eventData.tokenU;n(this.anonId)||(this.refreshUUID(),o=!0);const s=this.queue.shift();if(this.eventData.lastSuccess){const e=new Date(this.eventData.lastSuccess),t=new Date(s),i=(s-this.eventData.lastSuccess)/864e5;o=o||i>=1||i<-1||e.getDate()!==t.getDate()}else o=!0;o?this.postEvent(s,{sdkIdentifier:"mapbox-gl-js",sdkVersion:mn,skuId:Fn,"enabled.telemetry":!1,userId:this.anonId},(e=>{e||(this.eventData.lastSuccess=s,this.eventData.tokenU=i)}),e):this.processRequests()}},Wn=Zn.postTurnstileEvent.bind(Zn),$n=new class extends Hn{constructor(){super("map.load"),this.success={},this.skuToken=""}postMapLoadEvent(e,t,i,o){this.skuToken=t,this.errorCb=o,a.EVENTS_URL&&(i||a.ACCESS_TOKEN?this.queueRequest({id:e,timestamp:Date.now()},i):this.errorCb(new Error(Bn)))}processRequests(e){if(this.pendingRequest||0===this.queue.length)return;const{id:t,timestamp:i}=this.queue.shift();t&&this.success[t]||(this.anonId&&this.anonIdTimestamp||this.fetchEventData(),n(this.anonId)||this.refreshUUID(),this.postEvent(i,{sdkIdentifier:"mapbox-gl-js",sdkVersion:mn,skuId:Fn,skuToken:this.skuToken,userId:this.anonId},(e=>{e?this.errorCb(e):t&&(this.success[t]=!0)}),e))}remove(){this.errorCb=null}},Xn=$n.postMapLoadEvent.bind($n),Yn=new class extends Hn{constructor(){super("style.load"),this.eventIdPerMapInstanceMap=new Map,this.mapInstanceIdMap=new WeakMap}getMapInstanceId(e){let t=this.mapInstanceIdMap.get(e);return t||(t=l(),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:o,importedStyles:s}=t;if(!a.EVENTS_URL||!e&&!a.ACCESS_TOKEN)return;const r=this.getMapInstanceId(i),n={mapInstanceId:r,eventId:this.getEventId(r),style:o};s.length&&(n.importedStyles=s),this.queueRequest({timestamp:Date.now(),payload:n},e)}processRequests(e){if(this.pendingRequest||0===this.queue.length)return;const{timestamp:t,payload:i}=this.queue.shift();this.postEvent(t,i,(()=>{}),e)}},Kn=Yn.postStyleLoadEvent.bind(Yn),Qn=new qn({attributes:[{name:"maps/js/layer-animations/style-with-appearances"}]}),Jn=Qn.postMetricsEvent.bind(Qn),ea=new qn({attributes:[{name:"maps/js/layer-animations/runtime-appearances"}]}),ta=ea.postMetricsEvent.bind(ea),ia=new class extends Hn{constructor(){super("gljs.performance")}postPerformanceEvent(e,t){a.EVENTS_URL&&(e||a.ACCESS_TOKEN)&&this.queueRequest({timestamp:Date.now(),performanceData:t},e)}processRequests(t){if(this.pendingRequest||0===this.queue.length)return;const{timestamp:i,performanceData:o}=this.queue.shift(),s=function(t){const i=performance.getEntriesByType("resource"),o=performance.getEntriesByType("mark"),s=function(e){const t={};if(e)for(const i in e)if("other"!==i)for(const o of e[i]){const e=`${i}ResolveRangeMin`,s=`${i}ResolveRangeMax`,r=`${i}RequestCount`,n=`${i}RequestCachedCount`;t[e]=Math.min(t[e]||1/0,o.startTime),t[s]=Math.max(t[s]||-1/0,o.responseEnd);const a=e=>{void 0===t[e]&&(t[e]=0),++t[e]};void 0!==o.transferSize&&0===o.transferSize&&a(n),a(r)}return t}(function(e,t){const i={};if(e)for(const o of e){const e=t(o);void 0===i[e]&&(i[e]=[]),i[e].push(o)}return i}(i,yn)),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 s)c(l.counters,e,s[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])),o)for(const e of Object.values(gn)){const t=o.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",mn),c(l.metadata,"sdkIdentifier","mapbox-gl-js"),l}(o);for(const e of s.metadata);for(const e of s.counters);for(const e of s.attributes);this.postEvent(i,s,(()=>{}),t)}},oa=ia.postPerformanceEvent.bind(ia),sa=new class extends Hn{constructor(){super("map.auth"),this.success={},this.skuToken=""}getSession(e,t,i,o){if(!a.API_URL||!a.SESSION_PATH)return;const s=Un(a.API_URL+a.SESSION_PATH);s.params.push(`sku=${t||""}`),s.params.push(`access_token=${o||a.ACCESS_TOKEN||""}`);const r={url:jn(s),headers:{"Content-Type":"text/plain"}};this.pendingRequest=c(r,(e=>{this.pendingRequest=null,i(e),this.saveEventData(),this.processRequests(o)}))}getSessionAPI(e,t,i,o){this.skuToken=t,this.errorCb=o,a.SESSION_PATH&&a.API_URL&&(i||a.ACCESS_TOKEN?this.queueRequest({id:e,timestamp:Date.now()},i):this.errorCb(new Error(Bn)))}processRequests(e){if(this.pendingRequest||0===this.queue.length)return;const{id:t,timestamp:i}=this.queue.shift();t&&this.success[t]||this.getSession(i,this.skuToken,(e=>{e?this.errorCb(e):t&&(this.success[t]=!0)}),e)}remove(){this.errorCb=null}},ra=sa.getSessionAPI.bind(sa),na=new Set;function aa(e,t){t?na.add(e):na.delete(e)}class la{constructor(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSourceCaches={},this._updatedPaintProps=new Set,this._updatedImages={}}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(v.toString(e)),this.setDirty()}resetUpdatedImages(e){this._updatedImages[e]&&this._updatedImages[e].clear()}reset(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSourceCaches={},this._updatedPaintProps.clear(),this._updatedImages={}}}function ca(e){const{userImage:t}=e;return!!(t&&t.render&&t.render())&&(e.data.replace(new Uint8Array(t.data.buffer)),!0)}class ha extends E{constructor(e){super(),this.imageProviders=new Map,this.images=new Map,this.updatedImages=new Map,this.callbackDispatchedThisFrame=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.dirty=!0,this.spriteFormat=e,"raster"!==e&&S()&&(this.imageRasterizerDispatcher=new I(C(),this,"Image Rasterizer Worker",1))}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.patterns.set(e,new Map),this.atlasImage.set(e,new T({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.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}get imageRasterizer(){return this._imageRasterizer||(this._imageRasterizer=new R),this._imageRasterizer}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){this._validate(e,i)&&this.images.get(t).set(e.toString(),i)}_validate(e,t){let i=!0;return this._validateStretch(t.stretchX,t.data&&t.data.width)||(this.fire(new A(new Error(`Image "${e.name}" has invalid "stretchX" value`))),i=!1),this._validateStretch(t.stretchY,t.data&&t.data.height)||(this.fire(new A(new Error(`Image "${e.name}" has invalid "stretchY" value`))),i=!1),this._validateContent(t.content,t)||(this.fire(new A(new Error(`Image "${e.name}" has invalid "content" value`))),i=!1),i}_validateStretch(e,t){if(!e)return!0;let i=0;for(const o of e){if(o[0]<i||o[1]<o[0]||t<o[1])return!1;i=o[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 o=this.images.get(t).get(e.toString());i.version=o.version+1,this.images.get(t).set(e.toString(),i),this.updatedImages.get(t).add(e),this.removeFromImageRasterizerCache(e,t)}clearUpdatedImages(e){this.updatedImages.get(e).clear()}removeFromImageRasterizerCache(e,t){"raster"!==this.spriteFormat&&(S()?this.imageRasterizerDispatcher.getActor().send("removeRasterizedImages",{imageIds:[e],scope:t}):this.imageRasterizer.removeImagesFromCacheByIds([e],t))}removeImage(e,t){const i=this.images.get(t),o=i.get(e.toString());i.delete(e.toString()),this.patterns.get(t).delete(e.toString()),this.removeFromImageRasterizerCache(e,t),o.userImage&&o.userImage.onRemove&&o.userImage.onRemove()}listImages(e){return Array.from(this.images.get(e).keys()).map((e=>v.from(e)))}getImages(e,t,i){const o=[],s=[],r=this.imageProviders.get(t);for(const i of e){if(!i.iconsetId){o.push(i);continue}const e=r.get(i.iconsetId);e&&(this.getImage(i,t)?s.push(i):e.addPendingRequest(i))}if(0===o.length)return void this._notify(s,t,i);let n=!0;const a=!!this.loaded.get(t),l=this.images.get(t);if(!a)for(const e of o)l.has(e.toString())||(n=!1);a||n?this._notify(o,t,i):this.requestors.push({ids:o,scope:t,callback:i})}rasterizeImages(e,t){const i=new Map,{tasks:o,scope:s}=e;for(const[e,t]of o.entries()){const o=this.getImage(t.id,s);o&&i.set(e,{image:o,imageVariant:t})}this._rasterizeImages(s,i,t)}_rasterizeImages(e,t,i){if(S())this.imageRasterizerDispatcher.getActor().send("rasterizeImagesWorker",{tasks:t,scope:e},i);else{const o=new Map;for(const[i,{image:s,imageVariant:r}]of t.entries())o.set(i,this.imageRasterizer.rasterize(r,s,e,0));i(void 0,o)}}getUpdatedImages(e){return this.updatedImages.get(e)||new Set}_notify(e,t,i){const o=this.images.get(t),s=new Map;for(const t of e){if(!o.get(t.toString())){if(t.iconsetId)continue;this.fire(new D("styleimagemissing",{id:t.name}))}const e=o.get(t.toString());if(!e){u(`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,version:e.version,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}),s.set(v.toString(t),i)}i(null,s)}getPixelSize(e){const{width:t,height:i}=this.atlasImage.get(e);return{width:t,height:i}}getPattern(e,t,i){const o=e.toString(),s=this.patterns.get(t),r=s.get(o),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 s=this.getPatternInFlightId(o,t);if(this.patternsInFlight.has(s))return null;this.patternsInFlight.add(s);const r=new L(e).scaleSelf(w.devicePixelRatio),a=new Map([[r.toString(),{image:n,imageVariant:r}]]);return this._rasterizeImages(t,a,((e,o)=>this.storePatternImage(r,t,n,i,o))),null}this.storePattern(e,t,n)}return this._updatePatternAtlas(t,i),s.get(o).position}getPatternInFlightId(e,t){return O(e,t)}hasPatternsInFlight(){return 0!==this.patternsInFlight.size}storePatternImage(e,t,i,o,s){const r=e.toString(),n=s?s.get(r):void 0;n&&(i.data=n,this.storePattern(e.id,t,i),this._updatePatternAtlas(t,o),this.patternsInFlight.delete(this.getPatternInFlightId(e.id.toString(),t)))}storePattern(e,t,i){const o={w:i.data.width+2*M,h:i.data.height+2*M,x:0,y:0},s=new P(o,i,M);this.patterns.get(t).set(e.toString(),{bin:o,position:s})}destroyAtlasTextures(){for(const e of this.atlasTexture.values())e&&e.destroy();this.atlasTexture.clear()}bind(e,t){const i=e.gl;let o=this.atlasTexture.get(t);o?this.dirty&&(o.update(this.atlasImage.get(t)),this.dirty=!1):(o=new z(e,this.atlasImage.get(t),i.RGBA8),this.atlasTexture.set(t,o)),o.bind(i.LINEAR,i.CLAMP_TO_EDGE)}_updatePatternAtlas(e,t){const i=this.patterns.get(e),o=Array.from(i.values()).map((({bin:e})=>e)),{w:s,h:r}=F(o),n=this.atlasImage.get(e);n.resize({width:s||1,height:r||1});const a=this.images.get(e);for(const[e,{bin:o,position:s}]of i.entries()){let i=s.padding;const r=o.x+i,l=o.y+i,c=a.get(e).data,h=c.width,d=c.height;i=i>1?i-1:i,T.copy(c,n,{x:0,y:0},{x:r,y:l},{width:h,height:d},t),T.copy(c,n,{x:0,y:d-i},{x:r,y:l-i},{width:h,height:i},t),T.copy(c,n,{x:0,y:0},{x:r,y:l+d},{width:h,height:i},t),T.copy(c,n,{x:h-i,y:0},{x:r-i,y:l},{width:i,height:d},t),T.copy(c,n,{x:0,y:0},{x:r+h,y:l},{width:i,height:d},t),T.copy(c,n,{x:h-i,y:d-i},{x:r-i,y:l-i},{width:i,height:i},t),T.copy(c,n,{x:0,y:d-i},{x:r+h,y:l-i},{width:i,height:i},t),T.copy(c,n,{x:0,y:0},{x:r+h,y:l+d},{width:i,height:i},t),T.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)}dispatchRenderCallbacks(e,t){const i=this.images.get(t);for(const o of e){if(this.callbackDispatchedThisFrame.get(t).has(o.toString()))continue;this.callbackDispatchedThisFrame.get(t).add(o.toString());const e=i.get(o.toString());ca(e)&&this.updateImage(o,t,e)}}destroy(){this.imageRasterizerDispatcher&&this.imageRasterizerDispatcher.remove()}}function da(e){const t=e.value,i=e.valueSpec,o=e.style,s=e.styleSpec,r=e.key,n=e.arrayElementValidator||Pa;if(!Array.isArray(t))return[new k(r,t,`array expected, ${U(t)} found`)];if(i.length&&t.length!==i.length)return[new k(r,t,`array length ${i.length} expected, length ${t.length} found`)];if(i["min-length"]&&t.length<i["min-length"])return[new k(r,t,`array length at least ${i["min-length"]} expected, length ${t.length} found`)];let a={type:i.value,values:i.values,minimum:i.minimum,maximum:i.maximum,function:void 0};s.$version<7&&(a.function=i.function),B(i.value)&&(a=i.value);let l=[];for(let e=0;e<t.length;e++)l=l.concat(n({array:t,arrayIndex:e,value:t[e],valueSpec:a,style:o,styleSpec:s,key:`${r}[${e}]`},!0));return l}function ua(e){const t=e.key,i=e.value,o=e.valueSpec;if(!j(i))return[new k(t,i,`number expected, ${U(i)} found`)];if(i!=i)return[new k(t,i,"number expected, NaN found")];if("minimum"in o){let s=o.minimum;if(Array.isArray(o.minimum)&&(s=o.minimum[e.arrayIndex]),i<s)return[new k(t,i,`${i} is less than the minimum value ${s}`)]}if("maximum"in o){let s=o.maximum;if(Array.isArray(o.maximum)&&(s=o.maximum[e.arrayIndex]),i>s)return[new k(t,i,`${i} is greater than the maximum value ${s}`)]}return[]}function _a(e){const t=e.key,i=e.value;if(!B(i))return[new k(t,i,`object expected, ${U(i)} found`)];const o=e.valueSpec,s=N(i.type);let r,n,a,l={};const c="categorical"!==s&&void 0===i.property,h=!c,d=function(e){const t=e.stops;return Array.isArray(t)&&Array.isArray(t[0])&&B(t[0][0])}(i),u=Ma({key:e.key,value:e.value,valueSpec:e.styleSpec.function,style:e.style,styleSpec:e.styleSpec,objectElementValidators:{stops:function(e){if("identity"===s)return[new k(e.key,e.value,'identity function may not have a "stops" property')];let t=[];const i=e.value;return t=t.concat(da({key:e.key,value:i,valueSpec:e.valueSpec,style:e.style,styleSpec:e.styleSpec,arrayElementValidator:_})),Array.isArray(i)&&0===i.length&&t.push(new k(e.key,i,"array must have at least one stop")),t},default:function(e){return Pa({key:e.key,value:e.value,valueSpec:o,style:e.style,styleSpec:e.styleSpec})}}});return"identity"===s&&c&&u.push(new k(e.key,e.value,'missing required property "property"')),"identity"===s||i.stops||u.push(new k(e.key,e.value,'missing required property "stops"')),"exponential"===s&&o.expression&&!G(o)&&u.push(new k(e.key,e.value,"exponential functions not supported")),e.styleSpec.$version>=8&&(h&&!V(o)?u.push(new k(e.key,e.value,"property functions not supported")):c&&!H(o)&&u.push(new k(e.key,e.value,"zoom functions not supported"))),"categorical"!==s&&!d||void 0!==i.property||u.push(new k(e.key,e.value,'"property" property is required')),u;function _(e){let t=[];const i=e.value,s=e.key;if(!Array.isArray(i))return[new k(s,i,`array expected, ${U(i)} found`)];if(2!==i.length)return[new k(s,i,`array length 2 expected, length ${i.length} found`)];if(d){if(!B(i[0]))return[new k(s,i,`object expected, ${U(i[0])} found`)];const o=i[0];if(void 0===o.zoom)return[new k(s,i,"object stop key must have zoom")];if(void 0===o.value)return[new k(s,i,"object stop key must have value")];const r=N(o.zoom);if("number"!=typeof r)return[new k(s,o.zoom,"stop zoom values must be numbers")];if(a&&a>r)return[new k(s,o.zoom,"stop zoom values must appear in ascending order")];r!==a&&(a=r,n=void 0,l={}),t=t.concat(Ma({key:`${s}[0]`,value:i[0],valueSpec:{zoom:{}},style:e.style,styleSpec:e.styleSpec,objectElementValidators:{zoom:ua,value:p}}))}else t=t.concat(p({key:`${s}[0]`,value:i[0]},i));return q(Z(i[1]))?t.concat([new k(`${s}[1]`,i[1],"expressions are not allowed in function stops.")]):t.concat(Pa({key:`${s}[1]`,value:i[1],valueSpec:o,style:e.style,styleSpec:e.styleSpec}))}function p(e,t){const i=U(e.value),a=N(e.value),c=null!==e.value?e.value:t;if(r){if(i!==r)return[new k(e.key,c,`${i} stop domain type must match previous stop domain type ${r}`)]}else r=i;if("number"!==i&&"string"!==i&&"boolean"!==i&&"number"!=typeof a&&"string"!=typeof a&&"boolean"!=typeof a)return[new k(e.key,c,"stop domain value must be a number, string, or boolean")];if("number"!==i&&"categorical"!==s){let t=`number expected, ${i} found`;return V(o)&&void 0===s&&(t+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new k(e.key,c,t)]}return"categorical"!==s||"number"!==i||"number"==typeof a&&isFinite(a)&&Math.floor(a)===a?"categorical"!==s&&"number"===i&&"number"==typeof a&&"number"==typeof n&&void 0!==n&&a<n?[new k(e.key,c,"stop domain values must appear in ascending order")]:(n=a,"categorical"===s&&a in l?[new k(e.key,c,"stop domain values must be unique")]:(l[a]=!0,[])):[new k(e.key,c,`integer expected, found ${String(a)}`)]}}function pa(e){const t=("property"===e.expressionContext?$:W)(Z(e.value),e.valueSpec);if("error"===t.result)return t.value.map((t=>new k(`${e.key}${t.key}`,e.value,t.message)));const i=t.value.expression||t.value._styleExpression.expression;if("property"===e.expressionContext&&"text-font"===e.propertyKey&&!i.outputDefined())return[new k(e.key,e.value,`Invalid data expression for "${e.propertyKey}". Output values must be contained as literals within the expression.`)];if("property"===e.expressionContext&&"layout"===e.propertyType&&!K(i))return[new k(e.key,e.value,'"feature-state" data expressions are not supported with layout properties.')];if("filter"===e.expressionContext)return fa(i,e);if("appearance"===e.expressionContext)return ma(i,e);if(e.expressionContext&&0===e.expressionContext.indexOf("cluster")){if(!X(i,["zoom","feature-state"]))return[new k(e.key,e.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if("cluster-initial"===e.expressionContext&&!Y(i))return[new k(e.key,e.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return[]}function fa(e,t){const i=new Set(["zoom","feature-state","pitch","distance-from-center"]);if(t.valueSpec&&t.valueSpec.expression)for(const e of t.valueSpec.expression.parameters)i.delete(e);if(0===i.size)return[];const o=[];return e instanceof Q&&i.has(e.name)?[new k(t.key,t.value,`["${e.name}"] expression is not supported in a filter for a ${t.object.type} layer with id: ${t.object.id}`)]:(e.eachChild((e=>{o.push(...fa(e,t))})),o)}function ma(e,t){const i=new Set;if(t.valueSpec&&t.valueSpec.expression)for(const e of t.valueSpec.expression.parameters)i.add(e);if(0===i.size)return[];const o=[];return e instanceof Q&&!i.has(e.name)?[new k(t.key,t.value,`["${e.name}"] is not an allowed parameter`)]:(e.eachChild((e=>{o.push(...ma(e,t))})),o)}function ga(e){const t=e.key,i=e.value,o=e.valueSpec,s=[];return Array.isArray(o.values)?-1===o.values.indexOf(N(i))&&s.push(new k(t,i,`expected one of [${o.values.join(", ")}], ${JSON.stringify(i)} found`)):-1===Object.keys(o.values).indexOf(N(i))&&s.push(new k(t,i,`expected one of [${Object.keys(o.values).join(", ")}], ${JSON.stringify(i)} found`)),s}function va(e){return ie(Z(e.value))?pa(Object.assign({},e,{expressionContext:"filter",valueSpec:e.styleSpec[`filter_${e.layerType||"fill"}`]})):ya(e)}function ya(e){const t=e.value,i=e.key;if(!Array.isArray(t))return[new k(i,t,`array expected, ${U(t)} found`)];if(t.length<1)return[new k(i,t,"filter array must have at least 1 element")];const o=e.styleSpec;let s=ga({key:`${i}[0]`,value:t[0],valueSpec:o.filter_operator});const r=()=>{t.length>=2&&(ee(t[1])||s.push(new k(`${i}[1]`,t[1],`string expected, ${U(t[1])} found`)));for(let e=2;e<t.length;e++)"$type"===N(t[1])?s=s.concat(ga({key:`${i}[${e}]`,value:t[e],valueSpec:o.geometry_type})):ee(t[e])||j(t[e])||J(t[e])||s.push(new k(`${i}[${e}]`,t[e],`string, number, or boolean expected, ${U(t[e])} found.`))};switch(N(t[0])){case"<":case"<=":case">":case">=":t.length>=2&&"$type"===N(t[1])&&s.push(new k(i,t,`"$type" cannot be use with operator "${t[0]}"`)),3!==t.length&&s.push(new k(i,t,`filter array for operator "${t[0]}" must have 3 elements`)),r();break;case"==":case"!=":3!==t.length&&s.push(new k(i,t,`filter array for operator "${t[0]}" must have 3 elements`)),r();break;case"in":case"!in":r();break;case"any":case"all":case"none":for(let o=1;o<t.length;o++)s=s.concat(ya({key:`${i}[${o}]`,value:t[o],styleSpec:e.styleSpec}));break;case"has":case"!has":2!==t.length?s.push(new k(i,t,`filter array for "${t[0]}" operator must have 2 elements`)):ee(t[1])||s.push(new k(`${i}[1]`,t[1],`string expected, ${U(t[1])} found`))}return s}function xa(e,t){const i=e.key,o=e.style,s=e.layer,r=e.styleSpec,n=e.value,a=e.objectKey,l=r[`${t}_${e.layerType}`];if(!l)return[];const c=a.match(/^(.*)-use-theme$/);if(c&&l[c[1]])return q(Z(n))?[].concat(Pa({key:i,value:n,valueSpec:{type:"string",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},style:o,styleSpec:r,expressionContext:"property",propertyType:t,propertyKey:a})):Pa({key:i,value:n,valueSpec:{type:"string"},style:o,styleSpec:r});const h=a.match(/^(.*)-transition$/);if("paint"===t&&h&&l[h[1]]&&l[h[1]].transition)return Pa({key:i,value:n,valueSpec:r.transition,style:o,styleSpec:r});const d=e.valueSpec||l[a];if(!d)return[new oe(i,n,`unknown property "${a}"`)];let u;if(ee(n)&&V(d)&&!d.tokens&&(u=/^{([^}]+)}$/.exec(n))){const e=`\`{ "type": "identity", "property": ${u?JSON.stringify(u[1]):'"_"'} }\``;return[new k(i,n,`"${a}" does not support interpolation syntax\nUse an identity property function instead: ${e}.`)]}const _=[];if("symbol"===e.layerType)"text-field"!==a||!o||o.glyphs||o.imports||_.push(new k(i,n,'use of "text-field" requires a style "glyphs" property')),"text-font"===a&&se(Z(n))&&"identity"===N(n.type)&&_.push(new k(i,n,'"text-font" does not support identity functions'));else if("model"===e.layerType&&"paint"===t&&s&&s.layout&&s.layout.hasOwnProperty("model-id")&&V(d)&&(re(d)||H(d))){const e=$(Z(n),d).value,t="expression"in e&&e.expression||"_styleExpression"in e&&e._styleExpression&&e._styleExpression.expression;t&&!X(t,["measure-light"])&&("model-emissive-strength"===a&&Y(t)&&K(t)||_.push(new k(i,n,`${a} does not support measure-light expressions when the model layer source is vector tile or GeoJSON.`)))}return _.concat(Pa({key:e.key,value:n,valueSpec:d,style:o,styleSpec:r,expressionContext:"property",propertyType:t,propertyKey:a}))}function ba(e){return xa(e,"paint")}function wa(e){return xa(e,"layout")}function Ta(e){let t=[];const i=e.value,o=e.key,s=e.style,r=e.styleSpec;if(!B(i))return[new k(o,i,"object expected")];i.type||i.ref||t.push(new k(o,i,'either "type" or "ref" is required'));let n=N(i.type);const a=N(i.ref);if(i.id){const r=N(i.id);for(let n=0;n<e.arrayIndex;n++){const e=s.layers[n];N(e.id)===r&&t.push(new k(o,i.id,`duplicate layer id "${r}", previously used at line ${e.id.__line__}`))}}if("ref"in i){let e;["type","source","source-layer","filter","layout"].forEach((e=>{e in i&&t.push(new k(o,i[e],`"${e}" is prohibited for ref layers`))})),s.layers.forEach((t=>{N(t.id)===a&&(e=t)})),e?e.ref?t.push(new k(o,i.ref,"ref cannot reference another ref layer")):n=N(e.type):"string"==typeof a&&t.push(new k(o,i.ref,`ref layer "${a}" not found`))}else if("background"!==n&&"sky"!==n&&"slot"!==n)if(i.source)if(ee(i.source)){const e=s.sources&&s.sources[i.source],r=e&&N(e.type);e?"vector"===r&&"raster"===n?t.push(new k(o,i.source,`layer "${i.id}" requires a raster source`)):"raster"===r&&"raster"!==n?t.push(new k(o,i.source,`layer "${i.id}" requires a vector source`)):"vector"!==r||i["source-layer"]?"raster-dem"===r&&"hillshade"!==n?t.push(new k(o,i.source,"raster-dem source can only be used with layer type 'hillshade'.")):"raster-array"!==r||["raster","raster-particle"].includes(n)?"line"===n&&i.paint&&(i.paint["line-gradient"]||i.paint["line-trim-offset"])&&"geojson"===r&&!e.lineMetrics?t.push(new k(o,i,`layer "${i.id}" specifies a line-gradient, which requires the GeoJSON source to have \`lineMetrics\` enabled.`)):"raster-particle"===n&&"raster-array"!==r&&t.push(new k(o,i.source,`layer "${i.id}" requires a 'raster-array' source.`)):t.push(new k(o,i.source,"raster-array source can only be used with layer type 'raster'.")):t.push(new k(o,i,`layer "${i.id}" must specify a "source-layer"`)):t.push(new k(o,i.source,`source "${i.source}" not found`))}else t.push(new k(`${o}.source`,i.source,'"source" must be a string'));else t.push(new k(o,i,'missing required property "source"'));return t=t.concat(Ma({key:o,value:i,valueSpec:r.layer,style:e.style,styleSpec:e.styleSpec,objectElementValidators:{"*":()=>[],type:()=>Pa({key:`${o}.type`,value:i.type,valueSpec:r.layer.type,style:e.style,styleSpec:e.styleSpec,object:i,objectKey:"type"}),filter:e=>va(Object.assign({layerType:n},e)),layout:e=>Ma({layer:i,key:e.key,value:e.value,valueSpec:{},style:e.style,styleSpec:e.styleSpec,objectElementValidators:{"*":e=>wa(Object.assign({layerType:n},e))}}),paint:e=>Ma({layer:i,key:e.key,value:e.value,valueSpec:{},style:e.style,styleSpec:e.styleSpec,objectElementValidators:{"*":e=>ba(Object.assign({layerType:n,layer:i},e))}}),appearances(e){const t=da({key:e.key,value:e.value,valueSpec:e.valueSpec,style:e.style,styleSpec:e.styleSpec,arrayElementValidator:e=>function(e){const{key:t,layer:i,layerType:o}=e,s=N(e.value),r=N(s.name),n=N(s.condition),a=Ma({key:t,value:s,valueSpec:e.styleSpec.appearance,style:e.style,styleSpec:e.styleSpec,objectElementValidators:{condition:e=>function(e){const t=[];return t.push(...pa({key:e.key,value:e.object.condition,valueSpec:ne.appearance.condition,expressionContext:"appearance"})),t}(Object.assign({layer:i,layerType:o},e)),properties:e=>function(e){const t=[],{styleSpec:i,layer:o,layerType:s}=e,r=i[`paint_${s}`],n=i[`layout_${s}`],a=e.object[e.objectKey];for(const i in a){const l=i in r?"paint":i in n?"layout":void 0;if(!l){t.push(new k(e.key,i,`unknown property "${i}" for layer type "${s}"`));continue}const c=Object.assign({},e,{key:`${e.key}.${i}`,object:a,objectKey:i,layer:o,layerType:s,value:a[i],valueSpec:"paint"===l?r[i]:n[i]});t.push(...xa(c,l))}return t}(Object.assign({layer:i,layerType:o},e))}});return"hidden"!==r&&void 0===n&&a.push(new k(e.key,"name",'Appearance with name different than "hidden" must have a condition')),a}(Object.assign({layerType:n,layer:i},e))}),o=Array.isArray(e.value)?e.value:[],s=new Set;return o.forEach(((o,r)=>{const n=N(o.name);if(n)if(s.has(n)){const o=N(i.id);t.push(new k(e.key,n,`Duplicated appearance name "${n}" for layer "${o}"`))}else s.add(n)})),t}}})),t}function Ea({key:e,value:t}){return ee(t)?[]:[new k(e,t,`string expected, ${U(t)} found`)]}const Sa={promoteId:function e({key:t,value:i}){if(ee(i))return Ea({key:t,value:i});if(Array.isArray(i)){const e=[],o=Z(i),s=W(o);return"error"===s.result&&s.value.forEach((i=>{e.push(new k(`${t}${i.key}`,null,`${i.message}`))})),X(s.value.expression,["zoom","heatmap-density","line-progress","raster-value","sky-radial-progress","accumulated","is-supported-script","pitch","distance-from-center","measure-light","raster-particle-speed"])||e.push(new k(`${t}`,null,"promoteId expression should be only feature dependent")),e}if(!B(i))return[new k(t,i,`string, expression or object expected, "${U(i)}" found`)];const o=[];for(const s in i)o.push(...e({key:`${t}.${s}`,value:i[s]}));return o}};function Ia(e){const t=e.value,i=e.key,o=e.styleSpec,s=e.style;if(!B(t))return[new k(i,t,`object expected, ${U(t)} found`)];if(!("type"in t))return[new k(i,t,'"type" is required')];const r=N(t.type);let n=[];switch(["vector","raster","raster-dem","raster-array"].includes(r)&&("url"in t||"tiles"in t||n.push(new oe(i,t,'Either "url" or "tiles" is required.'))),r){case"vector":case"raster":case"raster-dem":case"raster-array":return n=n.concat(Ma({key:i,value:t,valueSpec:o[`source_${r.replace("-","_")}`],style:e.style,styleSpec:o,objectElementValidators:Sa})),n;case"geojson":if(n=Ma({key:i,value:t,valueSpec:o.source_geojson,style:s,styleSpec:o,objectElementValidators:Sa}),"cluster"in t&&"clusterProperties"in t){if(!B(t.clusterProperties))return[new k(`${i}.clusterProperties`,t,`object expected, ${U(t)} found`)];for(const e in t.clusterProperties){const o=t.clusterProperties[e];if(!Array.isArray(o))return[new k(`${i}.clusterProperties.${e}`,o,"array expected")];const[s,r]=o,a="string"==typeof s?[s,["accumulated"],["get",e]]:s;n.push(...pa({key:`${i}.${e}.map`,value:r,expressionContext:"cluster-map"})),n.push(...pa({key:`${i}.${e}.reduce`,value:a,expressionContext:"cluster-reduce"}))}}return n;case"video":return Ma({key:i,value:t,valueSpec:o.source_video,style:s,styleSpec:o});case"image":return Ma({key:i,value:t,valueSpec:o.source_image,style:s,styleSpec:o});case"canvas":return[new k(i,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return ga({key:`${i}.type`,value:t.type,valueSpec:{values:Ca(o)}})}}function Ca(e){return e.source.reduce(((t,i)=>{const o=e[i];return"enum"===o.type.type&&(t=t.concat(Object.keys(o.type.values||{}))),t}),[])}function Ra(e){const t=e.value,i=e.styleSpec,o=i.light,s=e.style;if(void 0===t)return[];if(!B(t))return[new k("light",t,`object expected, ${U(t)} found`)];let r=[];for(const e in t){const n=e.match(/^(.*)-transition$/),a=e.match(/^(.*)-use-theme$/);r=r.concat(a&&o[a[1]]?Pa({key:e,value:t[e],valueSpec:{type:"string"},style:s,styleSpec:i}):n&&o[n[1]]&&o[n[1]].transition?Pa({key:e,value:t[e],valueSpec:i.transition,style:s,styleSpec:i}):o[e]?Pa({key:e,value:t[e],valueSpec:o[e],style:s,styleSpec:i}):[new k(e,t[e],`unknown property "${e}"`)])}return r}function Aa(e){const t=e.value;if(!t)return[];const i=e.key;if(!B(t))return[new k(i,t,`object expected, ${U(t)} found`)];let o=[];const s=e.styleSpec,r=s["light-3d"],n=e.style,a=e.style.lights;for(const e of["type","id"])if(!(e in t))return o=o.concat([new k(i,t,`missing property "${e}"`)]),o;if(!ee(t.type))return o=o.concat([new k(`${i}.type`,t.type,"string expected")]),o;if(a)for(let s=0;s<e.arrayIndex;s++){const e=N(t.type),r=a[s];N(r.type)===e&&o.push(new k(i,t.id,`duplicate light type "${t.type}", previously defined at line ${r.id.__line__}`))}const l=`properties_light_${t.type}`;if(!(l in s))return o=o.concat([new k(`${i}.type`,t,`Invalid light type ${t.type}`)]),o;const c=s[l];for(const i in t)if("properties"===i){const r=t[i];if(!B(r))return o=o.concat([new k("properties",r,`object expected, ${U(r)} found`)]),o;for(const a in r){const l=a.match(/^(.*)-transition$/),h=a.match(/^(.*)-use-theme$/);o=o.concat(h&&c[h[1]]?Pa({key:i,value:r[a],valueSpec:{type:"string"},style:n,styleSpec:s}):l&&c[l[1]]&&c[l[1]].transition?Pa({key:i,value:t[i],valueSpec:s.transition,style:n,styleSpec:s}):c[a]?Pa({key:a,value:r[a],valueSpec:c[a],style:n,styleSpec:s}):[new oe(e.key,r[a],`unknown property "${a}"`)])}}else o=o.concat(r[i]?Pa({key:i,value:t[i],valueSpec:r[i],style:n,styleSpec:s}):[new oe(i,t[i],`unknown property "${i}"`)]);return o}function Da(e){const t=e.value,i=e.key,o=e.style,s=e.styleSpec,r=s.terrain;if(null==t)return[];if(!B(t))return[new k("terrain",t,`object expected, ${U(t)} found`)];let n=[];for(const e in t){const i=e.match(/^(.*)-transition$/),a=e.match(/^(.*)-use-theme$/);n=n.concat(a&&r[a[1]]?Pa({key:e,value:t[e],valueSpec:{type:"string"},style:o,styleSpec:s}):i&&r[i[1]]&&r[i[1]].transition?Pa({key:e,value:t[e],valueSpec:s.transition,style:o,styleSpec:s}):r[e]?Pa({key:e,value:t[e],valueSpec:r[e],style:o,styleSpec:s}):[new oe(e,t[e],`unknown property "${e}"`)])}if(t.source)if(ee(t.source)){const e=o.sources&&o.sources[t.source],s=e&&N(e.type);e?"raster-dem"!==s&&n.push(new k(`${i}.source`,t.source,`terrain cannot be used with a source of type ${s}, it only be used with a "raster-dem" source type`)):n.push(new k(`${i}.source`,t.source,`source "${t.source}" not found`))}else n.push(new k(`${i}.source`,t.source,"source must be a string"));else n.push(new k(i,t,'terrain is missing required property "source"'));return n}function La(e){const t=e.value,i=e.style,o=e.styleSpec,s=o.fog;if(void 0===t)return[];if(!B(t))return[new k("fog",t,`object expected, ${U(t)} found`)];let r=[];for(const e in t){const n=e.match(/^(.*)-transition$/),a=e.match(/^(.*)-use-theme$/);r=r.concat(a&&s[a[1]]?Pa({key:e,value:t[e],valueSpec:{type:"string"},style:i,styleSpec:o}):n&&s[n[1]]&&s[n[1]].transition?Pa({key:e,value:t[e],valueSpec:o.transition,style:i,styleSpec:o}):s[e]?Pa({key:e,value:t[e],valueSpec:s[e],style:i,styleSpec:o}):[new oe(e,t[e],`unknown property "${e}"`)])}return r}const Oa={"*":()=>[],array:da,boolean:function(e){const t=e.value,i=e.key;return J(t)?[]:[new k(i,t,`boolean expected, ${U(t)} found`)]},number:ua,color:function({key:e,value:t}){return ee(t)?null===te.parseCSSColor(t)?[new k(e,t,`color expected, "${t}" found`)]:[]:[new k(e,t,`color expected, ${U(t)} found`)]},enum:ga,filter:va,function:_a,layer:Ta,object:Ma,source:Ia,model:ae,light:Ra,"light-3d":Aa,terrain:Da,fog:La,string:Ea,formatted:function(e){return 0===Ea(e).length?[]:pa(e)},resolvedImage:function(e){return 0===Ea(e).length?[]:pa(e)},projection:function(e){const t=e.value,i=e.styleSpec,o=i.projection,s=e.style;if(B(t)){let e=[];for(const r in t)e=e.concat(Pa({key:r,value:t[r],valueSpec:o[r],style:s,styleSpec:i}));return e}return ee(t)?[]:[new k("projection",t,`object or string expected, ${U(t)} found`)]},import:function(e){const t=e.key,{value:i,styleSpec:o}=e;if(!B(i))return[new k(t,i,"import must be an object")];const{data:s,...r}=i;Object.defineProperty(r,"__line__",{value:i.__line__,enumerable:!1});let n=Ma(Object.assign({},e,{value:r,valueSpec:o.import}));return""===N(r.id)&&n.push(new k(`${e.key}.id`,r,"import id can't be an empty string")),s&&(n=n.concat(Fa(s,o,{key:`${e.key}.data`}))),n},iconset:function(e){const t=e.value,i=e.key,o=e.styleSpec,s=e.style;if(!B(t))return[new k(i,t,"object expected")];if(!t.type)return[new k(i,t,'"type" is required')];const r=N(t.type);let n=[];if(n=n.concat(Ma({key:i,value:t,valueSpec:o[`iconset_${r}`],style:s,styleSpec:o})),function(e,t){return!("source"!==e||!t.source)}(r,t)){const e=s.sources&&s.sources[t.source],o=e&&N(e.type);e?"raster-array"!==o&&n.push(new k(i,t.source,`iconset cannot be used with a source of type ${String(o)}, it only be used with a "raster-array" source type`)):n.push(new k(i,t.source,`source "${t.source}" not found`))}return n}};function Pa(e,t=!1){const i=e.value,o=e.valueSpec,s=e.styleSpec;if(o.expression){if(se(N(i)))return _a(e);if(q(Z(i)))return pa(e)}if(o.type&&Oa[o.type]){const i=Oa[o.type](e);return!0===t&&i.length>0&&Array.isArray(e.value)?pa(e):i}return Ma(Object.assign({},e,{valueSpec:o.type?s[o.type]:o}))}function Ma(e){const t=e.key,i=e.value,o=e.valueSpec||{},s=e.objectElementValidators||{},r=e.style,n=e.styleSpec;if(!B(i))return[new k(t,i,`object expected, ${U(i)} found`)];let a=[];for(const e in i){const l=e.split(".")[0];let c;s[l]?c=s[l]:o[l]?c=Pa:s["*"]?c=s["*"]:o["*"]&&(c=Pa),c?a=a.concat(c({key:(t?`${t}.`:t)+e,value:i[e],valueSpec:o[l]||o["*"],style:r,styleSpec:n,object:i,objectKey:e},i)):a.push(new oe(t,i[e],`unknown property "${e}"`))}for(const e in o){if(s[e])continue;const r=o[e];r.required&&void 0===r.default&&void 0===i[e]&&a.push(new k(t,i,`missing required property "${e}"`))}return a}function za({key:e,value:t}){const i=Ea({key:e,value:t});if(i.length)return i;const o=t;return-1===o.indexOf("{fontstack}")&&i.push(new k(e,t,'"glyphs" url must include a "{fontstack}" token')),-1===o.indexOf("{range}")&&i.push(new k(e,t,'"glyphs" url must include a "{range}" token')),i}function Fa(e,t=ne,i={}){return Ma({key:i.key||"",value:e,valueSpec:Object.assign(t.$root,{"*":{type:"*"}}),styleSpec:t,style:e,objectElementValidators:{glyphs:za}})}function Ba(e,t=ne){return Ya(Fa(e,t))}const ka=e=>Ya(Ia(e)),Na=e=>Ya(Ra(e)),Ua=e=>Ya(Aa(e)),ja=e=>Ya(Da(e)),Ga=e=>Ya(La(e)),Va=e=>Ya(function(e){const t=e.value,i=e.style,o=e.styleSpec,s=o.snow;if(void 0===t)return[];if(!B(t))return[new k("snow",t,`object expected, ${U(t)} found`)];let r=[];for(const e in t){const n=e.match(/^(.*)-transition$/);r=r.concat(n&&s[n[1]]&&s[n[1]].transition?Pa({key:e,value:t[e],valueSpec:o.transition,style:i,styleSpec:o}):s[e]?Pa({key:e,value:t[e],valueSpec:s[e],style:i,styleSpec:o}):[new oe(e,t[e],`unknown property "${e}"`)])}return r}(e)),Ha=e=>Ya(function(e){const t=e.value,i=e.style,o=e.styleSpec,s=o.rain;if(void 0===t)return[];if(!B(t))return[new k("rain",t,`object expected, ${U(t)} found`)];let r=[];for(const e in t){const n=e.match(/^(.*)-transition$/);r=r.concat(n&&s[n[1]]&&s[n[1]].transition?Pa({key:e,value:t[e],valueSpec:o.transition,style:i,styleSpec:o}):s[e]?Pa({key:e,value:t[e],valueSpec:s[e],style:i,styleSpec:o}):[new oe(e,t[e],`unknown property "${e}"`)])}return r}(e)),qa=e=>Ya(Ta(e)),Za=e=>Ya(va(e)),Wa=e=>Ya(ba(e)),$a=e=>Ya(wa(e)),Xa=e=>Ya(ae(e));function Ya(e){return e.slice().sort(((e,t)=>e.line&&t.line?e.line-t.line:0))}function Ka(e,t){let i=!1;if(t&&t.length)for(const o of t)o instanceof oe?u(o.message):(e.fire(new A(new Error(o.message))),i=!0);return i}const Qa=ne.light;let Ja;class el extends E{constructor(e,t="flat"){super(),this._transitionable=new le(Ja||(Ja=new ce({anchor:new he(Qa.anchor),position:new de(Qa.position),color:new he(Qa.color),intensity:new he(Qa.intensity)}))),this.setLight(e,t),this._transitioning=this._transitionable.untransitioned()}getLight(){return this._transitionable.serialize()}setLight(e,t,i={}){this._validate(Na,e,i)||(this._transitionable.setTransitionOrValue(e),this.id=t)}updateTransitions(e){this._transitioning=this._transitionable.transitioned(e,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(e){this.properties=this._transitioning.possiblyEvaluate(e)}_validate(e,t,i){return(!i||!1!==i.validate)&&Ka(this,e.call(Ba,Object.assign({value:t,style:{glyphs:!0,sprite:!0},styleSpec:ne})))}}const tl=ne.terrain;let il=class extends E{constructor(e,t,i,o,s){super(),this.scope=i,this._transitionable=new le(new ce({source:new he(tl.source),exaggeration:new he(tl.exaggeration)}),i,o),this._transitionable.setTransitionOrValue(e,o),this._transitioning=this._transitionable.untransitioned(),this.drapeRenderMode=t,this.worldview=s}get(){return this._transitionable.serialize()}set(e,t){this._transitionable.setTransitionOrValue(e,t)}updateTransitions(e){this._transitioning=this._transitionable.transitioned(e,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(e){this.properties=this._transitioning.possiblyEvaluate(e)}getExaggeration(e){return this._transitioning.possiblyEvaluate(new ue(e,{worldview:this.worldview})).get("exaggeration")}getAttenuationRange(){if(!this.isZoomDependent())return null;const e=this._transitionable._values.exaggeration;if(!e)return null;const t=e.value.expression;if(!t)return null;let i=-1,o=-1,s=1;for(const e of t.zoomStops)s=t.evaluate(new ue(e,{worldview:this.worldview})),s>.01?(i=e,o=-1):o=e;return s<.01&&i>0&&o>i?[i,o]:null}isZoomDependent(){const e=this._transitionable._values.exaggeration;return null!=e&&null!=e.value&&null!=e.value.expression&&e.value.expression instanceof _e}};const ol=45,sl=65,rl=.05;function nl(e,t,i,o){const s=me(ol,sl,i),[r,n]=al(e,o);let a=1-Math.min(1,Math.exp((t-r)/(n-r)*-6));return a*=a*a,a=Math.min(1,1.00747*a),a*s*e.alpha}function al(e,t){const i=.5/Math.tan(.5*t);return[e.range[0]+i,e.range[1]+i]}function ll(e,t,i,o,s){const r=fe([],[t,i,o],s.mercatorFogMatrix);return nl(e,ge(r),s.pitch,s._fov)}function cl(e,t,i,o,s,r,n){const a=[[i,o,0],[s,o,0],[s,r,0],[i,r,0]];let l=Number.MAX_VALUE,c=-Number.MAX_VALUE;for(const e of a){const i=fe([],e,t),o=ge(i);l=Math.min(l,o),c=Math.max(c,o)}return[nl(e,l,n.pitch,n._fov),nl(e,c,n.pitch,n._fov)]}const hl=ne.fog;class dl extends E{constructor(e,t,i,o){super();const s=new ce({range:new he(hl.range),color:new he(hl.color),"color-use-theme":new he({type:"string","property-type":"data-constant",default:"default"}),"high-color":new he(hl["high-color"]),"high-color-use-theme":new he({type:"string","property-type":"data-constant",default:"default"}),"space-color":new he(hl["space-color"]),"space-color-use-theme":new he({type:"string","property-type":"data-constant",default:"default"}),"horizon-blend":new he(hl["horizon-blend"]),"star-intensity":new he(hl["star-intensity"]),"vertical-range":new he(hl["vertical-range"])});this._transitionable=new le(s,i,new Map(o)),this.set(e,o),this._transitioning=this._transitionable.untransitioned(),this._transform=t,this.properties=new ve(s),this.scope=i}get state(){const e=this._transform,t="globe"===e.projection.name,i=ye(e.zoom),o=this.properties.get("range"),s=[.5,3];return{range:t?[xe(s[0],o[0],i),xe(s[1],o[1],i)]:o,horizonBlend:this.properties.get("horizon-blend"),alpha:this.properties.get("color").a}}get(){return this._transitionable.serialize()}set(e,t,i={}){if(this._validate(Ga,e,i))return;const o=Object.assign({},e);for(const e of Object.keys(hl))void 0===o[e]&&(o[e]=hl[e].default);this._options=o,this._transitionable.setTransitionOrValue(this._options,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:me(ol,sl,e))*t.a}getOpacityAtLatLng(e,t){return this._transform.projection.supportsFog?function(e,t,i){const o=pe.fromLngLat(t),s=i.elevation?i.elevation.getAtPointOrZero(o):0;return ll(e,o.x,o.y,s,i)}(this.state,e,t):0}getOpacityForTile(e){if(!this._transform.projection.supportsFog)return[1,1];const t=this._transform.calculateFogTileMatrix(e.toUnwrapped());return cl(this.state,t,0,0,we,we,this._transform)}getOpacityForBounds(e,t,i,o,s){return this._transform.projection.supportsFog?cl(this.state,e,t,i,o,s,this._transform):[1,1]}getFovAdjustedRange(e){return this._transform.projection.supportsFog?al(this.state,e):[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 o;if(t[2]>=0)o=t;else{const s=e.points[i-4];o=be(s,t,s[2]/(s[2]-t[2]))}if(ll(this.state,o[0],o[1],0,this._transform)>=rl)return!0}return!1}updateConfig(e){this._transitionable.setTransitionOrValue(this._options,new Map(e))}updateTransitions(e){this._transitioning=this._transitionable.transitioned(e,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(e){this.properties=this._transitioning.possiblyEvaluate(e)}_validate(e,t,i){return(!i||!1!==i.validate)&&Ka(this,e.call(Ba,Object.assign({value:t,style:{glyphs:!0,sprite:!0},styleSpec:ne})))}}let ul,_l,pl,fl,ml=class extends E{constructor(e,t,i,o){super();const s=ul||(ul=new ce({density:new he(ne.snow.density),intensity:new he(ne.snow.intensity),color:new he(ne.snow.color),opacity:new he(ne.snow.opacity),vignette:new he(ne.snow.vignette),"vignette-color":new he(ne.snow["vignette-color"]),"center-thinning":new he(ne.snow["center-thinning"]),direction:new he(ne.snow.direction),"flake-size":new he(ne.snow["flake-size"])}));this._transitionable=new le(s,i,new Map(o)),this.set(e,o),this._transitioning=this._transitionable.untransitioned(),this.properties=new ve(s),this.scope=i}get state(){const e=this.properties.get("opacity"),t=this.properties.get("color"),i=this.properties.get("direction"),o=Ee(i[0]),s=-Math.max(Ee(i[1]),.01),r=[Math.cos(o)*Math.cos(s),Math.sin(o)*Math.cos(s),Math.sin(s)],n=this.properties.get("vignette"),a=this.properties.get("vignette-color");return a.a=n,{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new Te(t.r,t.g,t.b,t.a*e),direction:r,centerThinning:this.properties.get("center-thinning"),flakeSize:this.properties.get("flake-size"),vignetteColor:a}}get(){return this._transitionable.serialize()}set(e,t,i={}){if(this._validate(Va,e,i))return;const o=Object.assign({},e),s=ne.snow;for(const e of Object.keys(s))void 0===o[e]&&(o[e]=s[e].default);this._options=o,this._transitionable.setTransitionOrValue(this._options,t)}updateConfig(e){this._transitionable.setTransitionOrValue(this._options,new Map(e))}updateTransitions(e){this._transitioning=this._transitionable.transitioned(e,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(e){this.properties=this._transitioning.possiblyEvaluate(e)}_validate(e,t,i){return(!i||!1!==i.validate)&&Ka(this,e.call(Ba,Object.assign({value:t,style:{glyphs:!0,sprite:!0},styleSpec:ne})))}},gl=class extends E{constructor(e,t,i,o){super();const s=_l||(_l=new ce({density:new he(ne.rain.density),intensity:new he(ne.rain.intensity),color:new he(ne.rain.color),opacity:new he(ne.rain.opacity),vignette:new he(ne.rain.vignette),"vignette-color":new he(ne.rain["vignette-color"]),"center-thinning":new he(ne.rain["center-thinning"]),direction:new he(ne.rain.direction),"droplet-size":new he(ne.rain["droplet-size"]),"distortion-strength":new he(ne.rain["distortion-strength"])}));this._transitionable=new le(s,i,new Map(o)),this.set(e,o),this._transitioning=this._transitionable.untransitioned(),this.properties=new ve(s),this.scope=i}get state(){const e=this.properties.get("opacity"),t=this.properties.get("color"),i=this.properties.get("direction"),o=Ee(i[0]),s=-Math.max(Ee(i[1]),.01),r=[Math.cos(o)*Math.cos(s),Math.sin(o)*Math.cos(s),Math.sin(s)],n=this.properties.get("vignette-color");return n.a=this.properties.get("vignette"),{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new Te(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:n}}get(){return this._transitionable.serialize()}set(e,t,i={}){if(this._validate(Ha,e,i))return;const o=Object.assign({},e),s=ne.rain;for(const e of Object.keys(s))void 0===o[e]&&(o[e]=s[e].default);this._options=o,this._transitionable.setTransitionOrValue(this._options,t)}updateConfig(e){this._transitionable.setTransitionOrValue(this._options,new Map(e))}updateTransitions(e){this._transitioning=this._transitionable.transitioned(e,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(e){this.properties=this._transitioning.possiblyEvaluate(e)}_validate(e,t,i){return(!i||!1!==i.validate)&&Ka(this,e.call(Ba,Object.assign({value:t,style:{glyphs:!0,sprite:!0},styleSpec:ne})))}};class vl extends E{constructor(e,t,i,o){super(),this.scope=i,this._options=e,this.properties=new ve(t),this._transitionable=new le(t,i,new Map(o)),this._transitionable.setTransitionOrValue(e.properties),this._transitioning=this._transitionable.untransitioned()}updateConfig(e){this._transitionable.setTransitionOrValue(this._options.properties,new Map(e))}updateTransitions(e){this._transitioning=this._transitionable.transitioned(e,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(e){this.properties=this._transitioning.possiblyEvaluate(e)}get(){return this._options.properties=this._transitionable.serialize(),this._options}set(e,t){this._options=e,this._transitionable.setTransitionOrValue(e.properties,t)}shadowsEnabled(){return!!this.properties&&!0===this.properties.get("cast-shadows")}}class yl{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,o;if(e instanceof r||"number"==typeof e[0]){const s=r.convert(e);i=[s],o=t.isPointAboveHorizon(s)}else{const s=r.convert(e[0]),n=r.convert(e[1]),a=s.add(n)._div(2);i=[s,n],o=Ie(s,n).every((e=>t.isPointAboveHorizon(e)))&&t.isPointAboveHorizon(a)}return new yl(i,o,t)}isPointQuery(){return 1===this.screenBounds.length}bufferedScreenGeometry(e){return Ie(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 r(1,1)):this.screenBounds[1],o=Ie(t,i,0,!1);return this.cameraPoint.y>i.y&&(this.cameraPoint.x>t.x&&this.cameraPoint.x<i.x?o.splice(3,0,this.cameraPoint):this.cameraPoint.x>=i.x?o[2]=this.cameraPoint:this.cameraPoint.x<=t.x&&(o[3]=this.cameraPoint)),Ce(o,e)}bufferedCameraGeometryGlobe(e){const t=this.screenBounds[0],i=1===this.screenBounds.length?this.screenBounds[0].add(new r(1,1)):this.screenBounds[1],o=Ie(t,i,e),s=this.cameraPoint.clone();switch(3*((s.y>t.y)+(s.y>i.y))+((s.x>t.x)+(s.x>i.x))){case 0:o[0]=s,o[4]=s.clone();break;case 1:o.splice(1,0,s);break;case 2:o[1]=s;break;case 3:o.splice(4,0,s);break;case 5:o.splice(2,0,s);break;case 6:o[3]=s;break;case 7:o.splice(3,0,s);break;case 8:o[2]=s}return o}containsTile(e,t,i,o=0){const s=Math.max(e.queryPadding,e.evaluateQueryRenderedFeaturePadding())/t._pixelsPerMercatorPixel+1,n=i?this._bufferedCameraMercator(s,t):this._bufferedScreenMercator(s,t);let a=e.tileID.wrap+(n.unwrapped?o:0);const l=n.polygon.map((t=>Re(e.tileTransform,t,a)));if(!Ae(l,0,0,we,we))return;a=e.tileID.wrap+(this.screenGeometryMercator.unwrapped?o:0);const c=this.screenGeometryMercator.polygon.map((t=>De(e.tileTransform,t,a))),h=c.map((e=>new r(e[0],e[1]))),d=t.getFreeCameraOptions().position||new pe(0,0,0),u=De(e.tileTransform,d,a),_=c.map((e=>{const t=Le(e,e,u);return Oe(t,t),new Pe(u,t)})),p=ze(e,1,t.zoom)*t._pixelsPerMercatorPixel;return{queryGeometry:this,tilespaceGeometry:h,tilespaceRays:_,bufferedTilespaceGeometry:l,bufferedTilespaceBounds:(f=Me(l),f.min.x=Fe(f.min.x,0,we),f.min.y=Fe(f.min.y,0,we),f.max.x=Fe(f.max.x,0,we),f.max.y=Fe(f.max.y,0,we),f),tile:e,tileID:e.tileID,pixelToTileUnitsFactor:p};var f}_bufferedScreenMercator(e,t){const i=wl(e);if(this._screenRaycastCache[i])return this._screenRaycastCache[i];{let o;return o="globe"===t.projection.name?this._projectAndResample(this.bufferedScreenGeometry(e),t):{polygon:this.bufferedScreenGeometry(e).map((e=>t.pointCoordinate3D(e))),unwrapped:!0},this._screenRaycastCache[i]=o,o}}_bufferedCameraMercator(e,t){const i=wl(e);if(this._cameraRaycastCache[i])return this._cameraRaycastCache[i];{let o;return o="globe"===t.projection.name?this._projectAndResample(this.bufferedCameraGeometryGlobe(e),t):{polygon:this.bufferedCameraGeometry(e).map((e=>t.pointCoordinate3D(e))),unwrapped:!0},this._cameraRaycastCache[i]=o,o}}_projectAndResample(e,t){const i=function(e,t){const i=Be([],t.pixelMatrix,t.globeMatrix),o=[0,-Ne,0,1],s=[0,Ne,0,1],n=[0,0,0,1];ke(o,o,i),ke(s,s,i),ke(n,n,i);const a=new r(o[0]/o[3],o[1]/o[3]),l=new r(s[0]/s[3],s[1]/s[3]),c=Ue(e,a)&&o[3]<n[3],h=Ue(e,l)&&s[3]<n[3];if(!c&&!h)return null;const d=function(e,t,i){for(let o=1;o<e.length;o++){const s=bl(t.pointCoordinate3D(e[o-1]).x),r=bl(t.pointCoordinate3D(e[o]).x);if(i<0){if(s<r)return{idx:o,t:-s/(r-1-s)}}else if(r<s)return{idx:o,t:(1-s)/(r+1-s)}}return null}(e,t,c?-1:1);if(!d)return null;const{idx:u,t:_}=d;let p=u>1?xl(e.slice(0,u),t):[],f=u<e.length?xl(e.slice(u),t):[];p=p.map((e=>new r(bl(e.x),e.y))),f=f.map((e=>new r(bl(e.x),e.y)));const m=[...p];0===m.length&&m.push(f[f.length-1]);const g=xe(m[m.length-1].y,(0===f.length?p[0]:f[0]).y,_);let v;return v=c?[new r(0,g),new r(0,0),new r(1,0),new r(1,g)]:[new r(1,g),new r(1,1),new r(0,1),new r(0,g)],m.push(...v),0===f.length?m.push(p[0]):m.push(...f),{polygon:m.map((e=>new pe(e.x,e.y))),unwrapped:!1}}(e,t);if(i)return i;const o=function(e,t){let i=!1,o=-1/0,s=0;for(let t=0;t<e.length-1;t++)e[t].x>o&&(o=e[t].x,s=t);for(let t=0;t<e.length-1;t++){const o=(s+t)%(e.length-1),r=e[o],n=e[o+1];Math.abs(r.x-n.x)>.5&&(r.x<n.x?(r.x+=1,0===o&&(e[e.length-1].x+=1)):(n.x+=1,o+1===e.length-1&&(e[0].x+=1)),i=!0)}const r=Ge(t.center.lng);return i&&r<Math.abs(r-1)&&e.forEach((e=>{e.x-=1})),{polygon:e,unwrapped:i}}(xl(e,t).map((e=>new r(bl(e.x),e.y))),t);return{polygon:o.polygon.map((e=>new pe(e.x,e.y))),unwrapped:o.unwrapped}}}function xl(e,t){return je(e,(e=>{const i=t.pointCoordinate3D(e);e.x=i.x,e.y=i.y}),1/256)}function bl(e){return e<0?1+e%1:e%1}function wl(e){return 100*e|0}function Tl(e,t,i,o,s){const r=function(i,o){if(i)return s(i);if(o){if(e.url&&o.tiles&&e.tiles&&delete e.tiles,o.variants){if(!Array.isArray(o.variants))return s(new Error("variants must be an array"));for(const e of o.variants){if(null==e||"object"!=typeof e||e.constructor!==Object)return s(new Error("variant must be an object"));if(!Array.isArray(e.capabilities))return s(new Error("capabilities must be an array"));if(1===e.capabilities.length&&"meshopt"===e.capabilities[0]){o=Object.assign(o,e);break}}}const i=Ve(Object.assign({},o,e),["tilejson","tiles","minzoom","maxzoom","attribution","mapbox_logo","bounds","extra_bounds","scheme","tileSize","encoding","vector_layers","raster_layers","worldview_options","worldview_default","worldview"]);i.tiles=t.canonicalizeTileset(i,e.url),s(null,i)}},n=function(e,t,i){if(!e)return null;if(!t&&!i)return e;i=i||e.worldview_default;const o=Object.values(e.language||{});if(0===o.length)return null;const s=Object.values(e.worldview||{});if(0===s.length)return null;const r=o.every((e=>e===t)),n=s.every((e=>e===i));return r&&n?e:t in(e.language_options||{})||i in(e.worldview_options||{})?null:e.language_options&&e.worldview_options?e:null}(e.data,i,o);return n?w.frame((()=>r(null,n))):e.url?y(t.transformRequest(t.normalizeSourceURL(e.url,null,i,o),x.Source),r):w.frame((()=>{const{data:t,...i}=e;r(null,i)}))}function El(e,t){const i=Math.pow(2,t.z),o=Math.floor(Ge(e.getWest())*i),s=Math.floor(qe(e.getNorth())*i),r=Math.ceil(Ge(e.getEast())*i),n=Math.ceil(qe(e.getSouth())*i);return t.x>=o&&t.x<r&&t.y>=s&&t.y<n}class Sl{constructor(e,t,i){this.bounds=e?He.convert(this.validateBounds(e)):null,this.minzoom=t||0,this.maxzoom=i||24}validateBounds(e){return Array.isArray(e)&&4===e.length?[Math.max(-180,e[0]),Math.max(-90,e[1]),Math.min(180,e[2]),Math.min(90,e[3])]:[-180,-90,180,90]}addExtraBounds(e){if(e){this.extraBounds||(this.extraBounds=[]);for(const t of e)this.extraBounds.push(He.convert(this.validateBounds(t)))}}contains(e){if(e.z>this.maxzoom||e.z<this.minzoom)return!1;if(this.bounds&&!El(this.bounds,e))return!1;if(!this.extraBounds)return!0;for(const t of this.extraBounds)if(El(t,e))return!0;return!1}static fromTileJSON(e){if(!e.bounds&&!e.extra_bounds)return null;const t=new Sl(e.bounds,e.minzoom,e.maxzoom);return t.addExtraBounds(e.extra_bounds),t}}class Il extends E{constructor(e,t,i,o){if(super(),this.id=e,this.dispatcher=i,this.type="vector",this.minzoom=0,this.maxzoom=22,this.scheme="xyz",this.tileSize=512,this.reparseOverscaled=!0,this.isTileClipped=!0,this._loaded=!1,Object.assign(this,Ve(t,["url","scheme","tileSize","promoteId"])),this._options=Object.assign({type:"vector"},t),this._collectResourceTiming=!!t.collectResourceTiming,512!==this.tileSize)throw new Error("vector tile sources must have a tileSize of 512");this.setEventedParent(o),this._tileWorkers={},this._deduped=new Ze}load(e){this._loaded=!1,this.fire(new D("dataloading",{dataType:"source"}));const t=Array.isArray(this.map._language)?this.map._language.join():this.map._language,i=this.map.getWorldview();this._tileJSONRequest=Tl(this._options,this.map._requestManager,t,i,((o,s)=>{if(this._tileJSONRequest=null,this._loaded=!0,o)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 A(o));else if(s){if(Object.assign(this,s),this.hasWorldviews=!!s.worldview_options,s.worldview_default&&(this.worldviewDefault=s.worldview_default),s.vector_layers){this.vectorLayers=s.vector_layers,this.vectorLayerIds=[],this.localizableLayerIds=new Set;for(const e of s.vector_layers)this.vectorLayerIds.push(e.id),s.worldview&&s.worldview[e.source]&&this.localizableLayerIds.add(e.id)}this.tileBounds=Sl.fromTileJSON(s),Wn(s.tiles,this.map._requestManager._customAccessToken),this.fire(new D("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new D("data",{dataType:"source",sourceDataType:"content"}))}e&&e(o)}))}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=O(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}onRemove(e){this.cancelTileJSONRequest()}serialize(){return Object.assign({},this._options)}loadTile(e,t){const i=e.tileID.canonical.url(this.tiles,this.scheme),o=this.map._requestManager.normalizeTileURL(i),s=this.map._requestManager.transformRequest(o,x.Tile),r=this.map.style?this.map.style.getLut(this.scope):null,n=r?{image:r.image.clone()}:null,a={request:s,data:void 0,uid:e.uid,tileID:e.tileID,tileZoom:e.tileZoom,zoom:e.tileID.overscaledZ,maxZoom:this.maxzoom,lut:n,tileSize:this.tileSize*e.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,pixelRatio:w.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,isSymbolTile:e.isSymbolTile,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.indoor?this.map.indoor.getIndoorTileOptions(this.id,this.scope):null};if(this.hasWorldviews&&p(i)&&(a.localizableLayerIds=this.localizableLayerIds),a.request.collectResourceTiming=this._collectResourceTiming,e.actor&&"expired"!==e.state)"loading"===e.state?e.reloadCallback=t:e.request=e.actor.send("reloadTile",a,l.bind(this));else if(e.actor=this._tileWorkers[o]=this._tileWorkers[o]||this.dispatcher.getActor(),this.dispatcher.ready)e.request=e.actor.send("loadTile",a,l.bind(this),void 0,!0);else{const t=We.call({deduped:this._deduped},a,((t,i)=>{if(t||!i)l.call(this,t);else{const t=$e(i.responseHeaders);a.data={rawData:i.rawData.slice(0),expires:t.expires,cacheControl:t.cacheControl},e.actor&&e.actor.send("loadTile",a,l.bind(this),void 0,!0)}}),!0);e.request={cancel:t}}function l(i,o){return delete e.request,e.aborted?t(null):i&&i instanceof Xe&&404!==i.status?t(i):(o&&o.resourceTiming&&(e.resourceTiming=o.resourceTiming),this.map._refreshExpiredTiles&&o&&e.setExpiryData(o),e.loadVectorData(o,this.map.painter),Ye(this.dispatcher),t(null,o),void(e.reloadCallback&&(this.loadTile(e,e.reloadCallback),e.reloadCallback=null)))}}abortTile(e){e.request&&(e.request.cancel(),delete e.request),e.actor&&e.actor.send("abortTile",{uid:e.uid,type:this.type,source:this.id,scope:this.scope})}unloadTile(e,t){e.actor&&e.actor.send("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)}}class Cl extends E{constructor(e,t,i,o){super(),this.id=e,this.dispatcher=i,this.setEventedParent(o),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme="xyz",this.tileSize=512,this._loaded=!1,this._options=Object.assign({type:"raster"},t),Object.assign(this,Ve(t,["url","scheme","tileSize"]))}load(e){this._loaded=!1,this.fire(new D("dataloading",{dataType:"source"}));const t=this.map.getWorldview();this._tileJSONRequest=Tl(this._options,this.map._requestManager,null,t,((t,i)=>{this._tileJSONRequest=null,this._loaded=!0,t?this.fire(new A(t)):i&&(Object.assign(this,i),i.raster_layers&&(this.rasterLayers=i.raster_layers,this.rasterLayerIds=this.rasterLayers.map((e=>e.id))),this.tileBounds=Sl.fromTileJSON(i),Wn(i.tiles),this.fire(new D("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new D("data",{dataType:"source",sourceDataType:"content"}))),e&&e(t)}))}loaded(){return this._loaded}onAdd(e){this.map=e,this.load()}reload(){this.cancelTileJSONRequest();const e=O(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}onRemove(e){this.cancelTileJSONRequest()}serialize(){return Object.assign({},this._options)}hasTile(e){return!this.tileBounds||this.tileBounds.contains(e.canonical)}loadTile(e,t){const i=w.devicePixelRatio>=2,o=this.map._requestManager.normalizeTileURL(e.tileID.canonical.url(this.tiles,this.scheme),i,this.tileSize);e.request=b(this.map._requestManager.transformRequest(o,x.Tile),((i,o,s)=>{if(delete e.request,e.aborted)return e.state="unloaded",t(null);if(i)return e.state="errored",t(i);if(!o)return t(null);const r=$e(s);this.map._refreshExpiredTiles&&e.setExpiryData(r),e.setTexture(o,this.map.painter),e.state="loaded",Ye(this.dispatcher),t(null)}))}abortTile(e,t){e.request&&(e.request.cancel(),delete e.request),t&&t()}unloadTile(e,t){e.texture&&e.texture instanceof z?(e.destroy(!1),e.texture&&e.texture instanceof z&&this.map.painter.saveTileTexture(e.texture)):e.destroy(),t&&t()}hasTransition(){return!1}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}}function Rl([e,t],i,o,{scaled:s=!0}={}){const{tileSize:r,buffer:n}=o,{x:a,y:l,z:c}=i;if(!isFinite(a)||!isFinite(l)||!isFinite(c))throw new Error("Invalid MRT header");const h=2**c,d=h*Ge(e),u=h*qe(t);return function([e,t],i,{scaled:o=!0}={}){if(!i)throw new Error("bandView is undefined");const{data:s,tileSize:r,buffer:n,offset:a,scale:l,dimension:c}=i;if(e<-n||e>r+n||t<-n||t>r+n)throw new Error(`Point (${e}, ${t}) out of bounds for tileSize=${r}, buffer=${n}`);const h=(t+n)*(r+2*n)+(e+n);if(4294967295===new Uint32Array(s.buffer)[h])return null;let d=[];d=o?[]:new(0,i.data.constructor)(c);for(let e=0;e<c;e++)d[e]=Math.round(1e12*(s[c*h+e]*l+a))/1e12;return d}([Math.min(Math.max(-n,Math.floor((d-a)*r)),r-1+n),Math.min(Math.max(-n,Math.floor((u-l)*r)),r-1+n)],o,{scaled:s})}class Al extends Cl{constructor(e,t,i,o){super(e,t,i,o),this.type="raster-array",this.maxzoom=22,this.partial=!0,this._loadTilePending={},this._loadTileLoaded={},this._options=Object.assign({type:"raster-array"},t)}triggerRepaint(e){const t=this.map.painter._terrain,i=this.map.style.getSourceCache(this.id);t&&t.enabled&&i&&t._clearRenderCacheForTile(i.id,e.tileID),this.map.triggerRepaint()}loadTile(e,t){const i=this.map._requestManager.normalizeTileURL(e.tileID.canonical.url(this.tiles,this.scheme),!1,this.tileSize),o=this.map._requestManager.transformRequest(i,x.Tile),s={request:o,uid:e.uid,tileID:e.tileID,type:this.type,source:this.id,scope:this.scope,partial:this.partial};e.source=this.id,e.scope=this.scope,e.requestParams=o,e.actor||(e.actor=this.dispatcher.getActor());const r=(i,o,s)=>{if(delete e.request,e.aborted)return e.state="unloaded",t(null);if(i){if("AbortError"===i.name)return;return e.state="errored",t(i)}if(this.map._refreshExpiredTiles&&o){const t=$e(s);e.setExpiryData(t)}if(this.partial&&"expired"!==e.state)e.state="empty";else if(!this.partial){if(!o)return t(null);e.state="loaded",e._isHeaderLoaded=!0,e._mrt=o}t(null)};e.request=this.partial?e.fetchHeader(void 0,r.bind(this)):e.actor.send("loadTile",s,r.bind(this),void 0,!0)}abortTile(e){e.request&&(e.request.cancel(),delete e.request),e.actor&&e.actor.send("abortTile",{uid:e.uid,type:this.type,source:this.id,scope:this.scope})}unloadTile(e,t){const i=e.texturePerLayer;if(e.flushAllQueues(),i.size){e.destroy(!1);for(const e of i.values())this.map.painter.saveTileTexture(e)}else e.destroy()}prepareTile(e,t,i,o){e._isHeaderLoaded&&("empty"!==e.state&&(e.state="reloading"),e.fetchBandForRender(t,i,o,((t,o)=>{if(t)return e.state="errored",this.fire(new A(t)),void this.triggerRepaint(e);o&&(e._isHeaderLoaded=!0,e.setTexturePerLayer(i,o,this.map.painter),e.state="loaded",this.triggerRepaint(e))})))}getInitialBand(e){if(!this.rasterLayers)return 0;const t=this.rasterLayers.find((({id:t})=>t===e)),i=t&&t.fields,o=i&&i.bands&&i.bands;return o?o[0]:0}getTextureDescriptor(e,t,i){if(!e)return;const o=t.sourceLayer||this.rasterLayerIds&&this.rasterLayerIds[0];if(!o)return;let s=null;t instanceof Je?s=t.paint.get("raster-array-band"):t instanceof et&&(s=t.paint.get("raster-particle-array-band"));const r=s||this.getInitialBand(o);if(null==r)return;if(!e.textureDescriptorPerLayer.get(t.id))return void this.prepareTile(e,o,t.id,r);if(e.updateNeeded(t.id,r)&&!i)return;const n=e.textureDescriptorPerLayer.get(t.id);return Object.assign({},n,{texture:e.texturePerLayer.get(t.id)})}getImages(e,t){const i=new Map;for(const o of e)for(const e of t){const[t,s]=e.split("/"),r=o.getLayer(t);if(!r)continue;if(!r.hasBand(s)||!r.hasDataForBand(s))continue;const{bytes:n,tileSize:a,buffer:l}=r.getBandView(s),c=a+2*l,h={data:new T({width:c,height:c},n),pixelRatio:2,sdf:!1,usvg:!1,version:0};i.set(e,h)}return i}queryRasterArrayValueByBandId(e,t,i){const o=t._mrt;return new Promise((s=>{const r={},n=new Set;for(const[a,l]of Object.entries(o.layers)){if(i.layerName&&a!==i.layerName)continue;const c={};r[a]=c;for(const{bands:h}of l.dataIndex)for(const d of h)i.bands&&!i.bands.includes(d)||(n.add(O(a,d)),t.fetchBand(a,null,d,(t=>{w.frame((()=>{c[d]=t?null:Rl([e.lng,e.lat],o,l.getBandView(d)),n.delete(O(a,d)),0===n.size&&s(r)}))}),!1))}0===n.size&&s(r)}))}_loadTileForQuery(e,t){if(this._loadTileLoaded[e.uid])return void t(null,e._mrt);if(this._loadTilePending[e.uid])return void this._loadTilePending[e.uid].push(t);this._loadTilePending[e.uid]=[t];const i=this.map._requestManager.normalizeTileURL(e.tileID.canonical.url(this.tiles,this.scheme),!1,this.tileSize),o=this.map._requestManager.transformRequest(i,x.Tile);e.actor.send("loadTile",{request:o,uid:e.uid,tileID:e.tileID,type:this.type,source:this.id,scope:this.scope,partial:!1},((t,i,o)=>{if(t)return this._loadTilePending[e.uid].forEach((e=>e(t,null))),void delete this._loadTilePending[e.uid];if(!i)return this._loadTilePending[e.uid].forEach((e=>e(null,null))),void delete this._loadTilePending[e.uid];if(this.map._refreshExpiredTiles&&i){const t=$e(o);e.setExpiryData(t)}e._mrt=i,e._isHeaderLoaded=!0,e.state="loaded",this._loadTilePending[e.uid].forEach((e=>e(null,i))),this._loadTileLoaded[e.uid]=!0,delete this._loadTilePending[e.uid]}),void 0,!0)}queryRasterArrayValueByAllBands(e,t,i){return new Promise(((o,s)=>{this._loadTileForQuery(t,((r,n)=>{r?s(r):o(n?this.queryRasterArrayValueByBandId(e,t,i):null)}))}))}queryRasterArrayValue(e,t){const i=tt.convert(e),o=this.findLoadedParent(i);return o&&o._mrt?t.bands||!this.partial?this.queryRasterArrayValueByBandId(i,o,t):this.queryRasterArrayValueByAllBands(i,o,t):Promise.resolve(null)}findLoadedParent(e){const t=pe.fromLngLat(e,this.map.transform.tileSize),i=this.maxzoom+1,o=1<<i,s=Math.floor(t.x),r=Math.floor((t.x-s)*o),n=Math.floor(t.y*o),a=this.map.style.getSourceCache(this.id),l=new Ke(i,s,i,r,n);return a.findLoadedParent(l,this.minzoom)}}const Dl={vector:Il,raster:Cl,"raster-dem":class extends Cl{constructor(e,t,i,o){super(e,t,i,o),this.type="raster-dem",this.maxzoom=22,this._options=Object.assign({type:"raster-dem"},t),this.encoding=t.encoding||"mapbox"}loadTile(e,t){const i=this.map._requestManager.normalizeTileURL(e.tileID.canonical.url(this.tiles,this.scheme),!1,this.tileSize);function o(i,o){i&&(e.state="errored",t(i)),o&&(e.dem=o,e.dem.onDeserialize(),e.needsHillshadePrepare=!0,e.needsDEMTextureUpload=!0,e.state="loaded",t(null))}e.request=b(this.map._requestManager.transformRequest(i,x.Tile),function(i,s,r){if(delete e.request,e.aborted)e.state="unloaded",t(null);else if(i)e.state="errored",t(i);else if(s){const t=$e(r);this.map._refreshExpiredTiles&&e.setExpiryData(t);const i=ImageBitmap&&s instanceof ImageBitmap&&S(),n=1-(s.width-Qe(s.width))/2;n<1||e.neighboringTiles||(e.neighboringTiles=this._getNeighboringTiles(e.tileID));const a=i?s:w.getImageData(s,n),l={uid:e.uid,tileID:e.tileID,source:this.id,type:this.type,scope:this.scope,rawImageData:a,encoding:this.encoding,padding:n};e.actor&&"expired"!==e.state||(e.actor=this.dispatcher.getActor(),e.actor.send("loadTile",l,o.bind(this),void 0,!0))}}.bind(this))}_getNeighboringTiles(e){const t=e.canonical,i=Math.pow(2,t.z),o=(t.x-1+i)%i,s=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 Ke(e.overscaledZ,s,t.z,o,t.y).key]={backfilled:!1},a[new Ke(e.overscaledZ,n,t.z,r,t.y).key]={backfilled:!1},t.y>0&&(a[new Ke(e.overscaledZ,s,t.z,o,t.y-1).key]={backfilled:!1},a[new Ke(e.overscaledZ,e.wrap,t.z,t.x,t.y-1).key]={backfilled:!1},a[new Ke(e.overscaledZ,n,t.z,r,t.y-1).key]={backfilled:!1}),t.y+1<i&&(a[new Ke(e.overscaledZ,s,t.z,o,t.y+1).key]={backfilled:!1},a[new Ke(e.overscaledZ,e.wrap,t.z,t.x,t.y+1).key]={backfilled:!1},a[new Ke(e.overscaledZ,n,t.z,r,t.y+1).key]={backfilled:!1}),a}},"raster-array":Al,geojson:class extends E{constructor(e,t,i,o){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(o),this._data=t.data,this._options=Object.assign({},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 s=we/this.tileSize;this.workerOptions=Object.assign({source:this.id,scope:this.scope,cluster:t.cluster||!1,geojsonVtOptions:{buffer:(void 0!==t.buffer?t.buffer:128)*s,tolerance:(void 0!==t.tolerance?t.tolerance:.375)*s,extent:we,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:we,radius:(void 0!==t.clusterRadius?t.clusterRadius:50)*s,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 A(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 A(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},t),this}getClusterChildren(e,t){return this.actor.send("geojson.getClusterChildren",{clusterId:e,source:this.id,scope:this.scope},t),this}getClusterLeaves(e,t,i,o){return this.actor.send("geojson.getClusterLeaves",{source:this.id,scope:this.scope,clusterId:e,limit:t,offset:i},o),this}_updateWorkerData(e=!1){if(this._pendingLoad)return void(this._coalesce=!0);this.fire(new D("dataloading",{dataType:"source"})),this._loaded=!1;const t=Object.assign({append:e},this.workerOptions);t.scope=this.scope;const i=this._data;"string"==typeof i?(t.request=this.map._requestManager.transformRequest(w.resolveURL(i),x.Source),t.request.collectResourceTiming=this._collectResourceTiming):t.data=JSON.stringify(i),this._pendingLoad=this.actor.send(`${this.type}.loadData`,t,((t,i)=>{if(this._loaded=!0,this._pendingLoad=null,t)this.fire(new A(t));else{const t={dataType:"source",sourceDataType:this._metadataFired?"content":"metadata"};this._collectResourceTiming&&i&&i.resourceTiming&&i.resourceTiming[this.id]&&(t.resourceTiming=i.resourceTiming[this.id]),e&&(this._partialReload=!0),this.fire(new D("data",t)),this._partialReload=!1,this._metadataFired=!0}this._coalesce&&(this._updateWorkerData(e),this._coalesce=!1)}))}loaded(){return this._loaded}reload(){const e=O(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 o=this.map.style?this.map.style.getLut(this.scope):null,s=o?{image:o.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:s,scope:this.scope,pixelRatio:w.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,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.indoor?this.map.indoor.getIndoorTileOptions(this.id,this.scope):null};e.request=this.actor.send(i,n,((o,s)=>r&&!s?(e.state="loaded",t(null)):(delete e.request,e.destroy(!1),e.aborted?t(null):o?t(o):(e.loadVectorData(s,this.map.painter,"reloadTile"===i),t(null)))),void 0,"loadTile"===i)}abortTile(e){e.request&&(e.request.cancel(),delete e.request),e.aborted=!0}unloadTile(e,t){this.actor.send("removeTile",{uid:e.uid,type:this.type,source:this.id,scope:this.scope}),e.destroy()}onRemove(e){this._pendingLoad&&this._pendingLoad.cancel()}serialize(){return Object.assign({},this._options,{type:this.type,data:this._data})}hasTransition(){return!1}},video:class extends it{constructor(e,t,i,o){super(e,t,i,o),this.roundZoom=!0,this.type="video",this.options=t}load(){this._loaded=!1;const e=this.options;this.urls=[];for(const t of e.urls)this.urls.push(this.map._requestManager.transformRequest(t,x.Source).url);ot(this.urls,((e,t)=>{this._loaded=!0,e?this.fire(new A(e)):t&&(this.video=t,this.video.loop=!0,this.video.setAttribute("playsinline",""),this.video.addEventListener("playing",(()=>{this.map.triggerRepaint()})),this.map&&this.video.play(),this._finishLoading())}))}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 A(new k(`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 z(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.urls,coordinates:this.coordinates}}hasTransition(){return this.video&&!this.video.paused}},image:it,model:rt,"batched-model":class extends E{constructor(e,t,i,o){super(),this.type="batched-model",this.id=e,this.tileSize=512,this._options=t,this.tiles=this._options.tiles,this.maxzoom=t.maxzoom||19,this.minzoom=t.minzoom||0,this.roundZoom=!0,this.usedInConflation=!0,this.dispatcher=i,this.reparseOverscaled=!1,this.scheme="xyz",this._loaded=!1,this.setEventedParent(o)}onAdd(e){this.map=e,this.load()}reload(){this.cancelTileJSONRequest();const e=O(this.id,this.scope);this.load((()=>this.map.style.clearSource(e)))}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}load(e){this._loaded=!1,this.fire(new D("dataloading",{dataType:"source"}));const t=Array.isArray(this.map._language)?this.map._language.join():this.map._language,i=this.map.getWorldview();this._tileJSONRequest=Tl(this._options,this.map._requestManager,t,i,((o,s)=>{this._tileJSONRequest=null,this._loaded=!0,o?(t&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${t}`),i&&2!==i.length&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${i}`),this.fire(new A(o))):s&&(Object.assign(this,s),s.bounds&&(this.tileBounds=new Sl(s.bounds,this.minzoom,this.maxzoom)),Wn(s.tiles,this.map._requestManager._customAccessToken),this.fire(new D("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new D("data",{dataType:"source",sourceDataType:"content"}))),e&&e(o)}))}hasTransition(){return!1}hasTile(e){return!this.tileBounds||this.tileBounds.contains(e.canonical)}loaded(){return this._loaded}loadTile(e,t){const i=this.map._requestManager.normalizeTileURL(e.tileID.canonical.url(this.tiles,this.scheme)),o={request:this.map._requestManager.transformRequest(i,x.Tile),data:void 0,uid:e.uid,tileID:e.tileID,tileZoom:e.tileZoom,zoom:e.tileID.overscaledZ,tileSize:this.tileSize*e.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,showCollisionBoxes:this.map.showCollisionBoxes,isSymbolTile:e.isSymbolTile,brightness:this.map.style&&this.map.style.getBrightness()||0,pixelRatio:w.devicePixelRatio,promoteId:this.promoteId};if(e.actor&&"expired"!==e.state)if("loading"===e.state)e.reloadCallback=t;else{if(e.buckets){const t=Object.values(e.buckets);for(const e of t)e.dirty=!0;return void(e.state="loaded")}e.request=e.actor.send("reloadTile",o,s.bind(this))}else e.actor=this.dispatcher.getActor(),e.request=e.actor.send("loadTile",o,s.bind(this),void 0,!0);function s(i,o){return e.aborted?t(null):i&&404!==i.status?t(i):(this.map._refreshExpiredTiles&&o&&e.setExpiryData(o),e.loadModelData(o,this.map.painter),e.state="loaded",void t(null))}}serialize(){return Object.assign({},this._options)}},canvas:class extends it{constructor(e,t,i,o){super(e,t,i,o),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 A(new k(`sources.${e}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new A(new k(`sources.${e}`,null,'missing required property "coordinates"'))),t.animate&&"boolean"!=typeof t.animate&&this.fire(new A(new k(`sources.${e}`,null,'optional "animate" property must be a boolean value'))),t.canvas?"string"==typeof t.canvas||t.canvas instanceof HTMLCanvasElement||this.fire(new A(new k(`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 A(new k(`sources.${e}`,null,'missing required property "canvas"'))),this.options=t,this.animate=void 0===t.animate||t.animate}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 A(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 st||this.texture.update(this.canvas,{premultiply:!0}):this.texture=new z(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 E{constructor(e,t,i,o){super(),this.id=e,this.type="custom",this._dataType="raster",this._dispatcher=i,this._implementation=t,this.setEventedParent(o),this.scheme="xyz",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this._loaded=!1,this.roundZoom=!0,this._implementation||this.fire(new A(new Error(`Missing implementation for ${this.id} custom source`))),this._implementation.loadTile||this.fire(new A(new Error(`Missing loadTile implementation for ${this.id} custom source`))),this._implementation.bounds&&(this.tileBounds=new Sl(this._implementation.bounds,this.minzoom,this.maxzoom)),t.update=this._update.bind(this),t.clearTiles=this._clearTiles.bind(this),t.coveringTiles=this._coveringTiles.bind(this),Object.assign(this,Ve(t,["dataType","scheme","minzoom","maxzoom","tileSize","attribution","minTileCacheSize","maxTileCacheSize"]))}serialize(){return Ve(this,["type","scheme","minzoom","maxzoom","tileSize","attribution"])}load(){this._loaded=!0,this.fire(new D("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new D("data",{dataType:"source",sourceDataType:"content"}))}loaded(){return this._loaded}onAdd(e){this.map=e,this._loaded=!1,this.fire(new D("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:o}=e.canonical;return this._implementation.hasTile({x:t,y:i,z:o})}return!this.tileBounds||this.tileBounds.contains(e.canonical)}loadTile(e,t){const{x:i,y:o,z:s}=e.tileID.canonical,r=new AbortController;e.request=Promise.resolve(this._implementation.loadTile({x:i,y:o,z:s},{signal:r.signal})).then(function(i){return delete e.request,e.aborted?(e.state="unloaded",t(null)):void 0===i?(e.state="errored",t(null)):null===i?(this.loadTileData(e,{width:this.tileSize,height:this.tileSize,data:null}),e.state="loaded",t(null)):function(e){return e instanceof ImageData||e instanceof HTMLCanvasElement||e instanceof ImageBitmap||e instanceof HTMLImageElement}(i)?(this.loadTileData(e,i),e.state="loaded",void t(null)):(e.state="errored",t(new Error(`Can't infer data type for ${this.id}, only raster data supported at the moment`)))}.bind(this)).catch((i=>{"AbortError"!==i.name&&(e.state="errored",t(i))})),e.request.cancel=()=>r.abort()}loadTileData(e,t){e.setTexture(t,this.map.painter)}unloadTile(e,t){if(e.texture&&e.texture instanceof z?(e.destroy(!1),e.texture&&e.texture instanceof z&&this.map.painter.saveTileTexture(e.texture)):e.destroy(),this._implementation.unloadTile){const{x:t,y:i,z:o}=e.tileID.canonical;this._implementation.unloadTile({x:t,y:i,z:o})}t&&t()}abortTile(e,t){e.request&&e.request.cancel&&(e.request.cancel(),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=O(this.id,this.scope);this.map.style.clearSource(e)}_update(){this.fire(new D("data",{dataType:"source",sourceDataType:"content"}))}}},Ll=function(e,t,i,o){const s=new Dl[t.type](e,t,i,o);if(s.id!==e)throw new Error(`Expected Source id to be ${e} instead of ${s.id}`);return nt(["load","abort","unload","serialize","prepare"],s),s};function Ol(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 Pl(e,t,i,o=""){if(e.uniqueFeatureID){const s=Ol(e,t,o);if(i.has(s))return!0;i.add(s)}return!1}function Ml(e,t,i,o,s=!1){const r=t.sourceCache.transform,n=t.sourceCache.tilesIn(e,t.has3DLayers,s);n.sort(Bl);const a=[];for(const e of n){const n=e.tile.queryRenderedFeatures(t,e,i,o,r,s);Object.keys(n).length&&a.push({wrappedTileID:e.tile.tileID.wrapped().key,queryResults:n})}for(const i in t.layers){const s=t.layers[i];if(s.styleLayer){const i=s.styleLayer.queryRenderedFeatures(e,t.sourceCache,o);Object.keys(i).length&&a.push({wrappedTileID:0,queryResults:i})}}return 0===a.length?{}:function(e){const t={},i={};for(const o of e){const e=o.queryResults,s=o.wrappedTileID,r=i[s]=i[s]||{};for(const i in e){const o=e[i],s=r[i]=r[i]||{},n=t[i]=t[i]||[];for(const e of o)s[e.featureIndex]||(s[e.featureIndex]=!0,n.push(e))}}return t}(a)}function zl(e,t,i,o,s,r){const n={},a=o.queryRenderedSymbols(e),l=[];for(const e of Object.keys(a).map(Number))l.push(s[e]);l.sort(Bl);for(const e of l){const o=e.featureIndex.lookupSymbolFeatures(a[e.bucketInstanceId],e.bucketIndex,e.sourceLayerIndex,t,i,r);for(const t in o){const i=n[t]=n[t]||[],s=o[t];s.sort(((t,i)=>{const o=e.featureSortOrder;if(o){const e=o.indexOf(t.featureIndex);return o.indexOf(i.featureIndex)-e}return i.featureIndex-t.featureIndex}));for(const e of s)i.push(e)}}return n}function Fl(e,t){const i=e.getRenderableIds().map((t=>e.getTileByID(t))),o=[],s={};for(let e=0;e<i.length;e++){const r=i[e],n=r.tileID.canonical.key;s[n]||(s[n]=!0,r.querySourceFeatures(o,t))}return o}function Bl(e,t){const i=e.tileID,o=t.tileID;return i.overscaledZ-o.overscaledZ||i.canonical.y-o.canonical.y||i.wrap-o.wrap||i.canonical.x-o.canonical.x}function kl(e,t){const i={};if(!t)return i;for(const o of e){const e=o.layerIds.map((e=>t.getLayer(e))).filter(Boolean);if(0!==e.length){o.layers=e,o.stateDependentLayerIds&&(o.stateDependentLayers=o.stateDependentLayerIds.map((t=>e.filter((e=>e.id===t))[0])));for(const t of e)i[t.fqid]=o}}return i}const Nl=32,Ul=33,jl=new Uint16Array(8184);for(let e=0;e<2046;e++){let t=e+2,i=0,o=0,s=0,r=0,n=0,a=0;for(1&t?s=r=n=Nl:i=o=a=Nl;(t>>=1)>1;){const e=i+s>>1,l=o+r>>1;1&t?(s=i,r=o,i=n,o=a):(i=s,o=r,s=n,r=a),n=e,a=l}const l=4*e;jl[l+0]=i,jl[l+1]=o,jl[l+2]=s,jl[l+3]=r}const Gl=new Uint16Array(2178),Vl=new Uint8Array(1089),Hl=new Uint16Array(1089);function ql(e){return 0===e?-.03125:32===e?.03125:0}const Zl=(()=>({type:2,extent:we,loadGeometry:()=>[[new r(0,0),new r(we+1,0),new r(we+1,we+1),new r(0,we+1),new r(0,0)]]}))();class Wl{constructor(e,t,i,o,s,r){this.tileID=e,this.uid=ut(),this.uses=0,this.tileSize=t,this.tileZoom=i,this.buckets={},this.expirationTime=null,this.queryPadding=0,this.hasSymbolBuckets=!1,this.hasRTLText=!1,this.dependencies={},this.isRaster=s,o&&o.style&&(this._lastUpdatedBrightness=o.style.getBrightness()),this.expiredRequestCount=0,this.state="loading",o&&o.transform&&(this.projection=o.transform.projection),this.worldview=r,this._hasAppearances=null}registerFadeDuration(e){const t=e+this.timeAdded;t<w.now()||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=at(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=kl(e.buckets,t.style),this.hasSymbolBuckets=!1;for(const e in this.buckets){const t=this.buckets[e];if(t instanceof pt){if(this.hasSymbolBuckets=!0,!i)break;t.justReloaded=!0}}if(this.hasRTLText=!1,this.hasSymbolBuckets)for(const e in this.buckets){const t=this.buckets[e];if(t instanceof pt&&t.hasRTLText){this.hasRTLText=!0,ft();break}}this.queryPadding=0;for(const e in this.buckets){const i=this.buckets[e],o=t.style.getOwnLayer(e);if(!o)continue;const s=o.queryRadius(i);this.queryPadding=Math.max(this.queryPadding,s)}e.imageAtlas&&(this.imageAtlas=e.imageAtlas),e.glyphAtlasImage&&(this.glyphAtlasImage=e.glyphAtlasImage),e.lineAtlas&&(this.lineAtlas=e.lineAtlas),this._lastUpdatedBrightness=e.brightness}else this.collisionBoxArray=new _t}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.destroy(),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=Object.assign({},this.buckets,kl(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 o=this.buckets[i];if(o.uploadPending()){let i={},s=[],r={zoom:0,pitch:0,brightness:0,worldview:""};if(t){if(t.style){s=t.style.listImages();const e=o.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||""}}o.upload(e,this.tileID.canonical,i,s,r)}}const i=e.gl,o=this.imageAtlas;o&&!o.uploaded&&(this.imageAtlasTexture=new z(e,o.image,i.RGBA8,{useMipmap:!!o.patternPositions.size}),this.imageAtlas.uploaded=!0),this.glyphAtlasImage&&(this.glyphAtlasTexture=new z(e,this.glyphAtlasImage,i.R8),this.glyphAtlasImage=null),this.lineAtlas&&!this.lineAtlas.uploaded&&(this.lineAtlasTexture=new z(e,this.lineAtlas.image,i.R8),this.lineAtlas.uploaded=!0)}prepare(e,t,i){if(this.imageAtlas&&this.imageAtlasTexture&&this.imageAtlas.patchUpdatedImages(e,this.imageAtlasTexture,i),!t||!this.latestFeatureIndex||!this.latestFeatureIndex.rawTileData)return;const o=t.style.getBrightness();null===this._hasAppearances&&(this._hasAppearances=this.hasAppearances(t)),(this._lastUpdatedBrightness||o||this._hasAppearances)&&(!this._hasAppearances&&this._lastUpdatedBrightness&&o&&Math.abs(this._lastUpdatedBrightness-o)<.001||(this.updateBuckets(t,this._lastUpdatedBrightness!==o),this._lastUpdatedBrightness=o))}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,o,s,r){if(!this.latestFeatureIndex||!this.latestFeatureIndex.rawTileData&&!this.latestFeatureIndex.is3DTile)return{};const n=this.evaluateQueryRenderedFeaturePadding(),a=function(e,t){const i=Ft([],[.5*e.width,.5*-e.height,1]);return Bt(i,i,[1,-1,0]),Be(i,i,e.calculateProjMatrix(t.toUnwrapped())),Float32Array.from(i)}(s,this.tileID);return this.latestFeatureIndex.query(e,{tilespaceGeometry:t,pixelPosMatrix:a,transform:o,availableImages:i,tileTransform:this.tileTransform,worldview:this.worldview,queryRadius:n})}querySourceFeatures(e,t){const i=this.latestFeatureIndex;if(!i||!i.rawTileData)return;const o=i.loadVTLayers(),s=t?t.sourceLayer:"",r=o._geojsonTileLayer||o[s];if(!r)return;const n=mt(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 o=r.feature(t);if(n.needGeometry){const e=gt(o,!0);if(!n.filter(new ue(this.tileID.overscaledZ,{worldview:this.worldview}),e,this.tileID.canonical))continue}else if(!n.filter(new ue(this.tileID.overscaledZ,{worldview:this.worldview}),o))continue;const d=i.getId(o,s),u=new vt(o,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=yt(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 o=this.expirationTime-t;o?this.expirationTime=e+Math.max(o,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-(new Date).getTime(),Math.pow(2,31)-1)}refreshFeatureState(e){this.latestFeatureIndex&&(this.latestFeatureIndex.rawTileData||this.latestFeatureIndex.is3DTile)&&e&&this.updateBuckets(e)}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){if(!this.latestFeatureIndex)return;if(!e.style)return;const i=e.style.listImages(),o=e.style.getBrightness();for(const s in this.buckets){if(!e.style.hasLayer(s))continue;const r=this.buckets[s],n=r.layers[0],a=n.sourceLayer||"_geojsonTileLayer",l=e.style.getLayerSourceCache(n);let c={};l&&(c=l._state.getState(a,void 0));const h=this.imageAtlas?Object.fromEntries(this.imageAtlas.patternPositions):{},d=Object.keys(c).length>0&&!t;r.hasAppearances=r.layers.some((e=>e.appearances&&e.appearances.length>0));const u=d?r.stateDependentLayers:r.layers;if(d&&0!==r.stateDependentLayers.length||t){const e=this.latestFeatureIndex.loadVTLayers();r.update(c,e[a],i,h,u,t,o)}if(d&&0!==r.stateDependentLayers.length||t||r.hasAppearances){const t={zoom:e.transform.zoom,pitch:e.transform.pitch,brightness:e.style.getBrightness()||0,worldview:e.worldview};r.updateAppearances(this.tileID.canonical,c,i,t)}(r instanceof xt||r instanceof bt)&&e._terrain&&e._terrain.enabled&&l&&r.uploadPending()&&e._terrain._clearRenderCacheForTile(l.id,this.tileID);const _=e&&e.style&&e.style.getOwnLayer(s);_&&(this.queryPadding=Math.max(this.queryPadding,_.queryRadius(r)))}}holdingForFade(){return void 0!==this.symbolFadeHoldUntil}symbolFadeFinished(){return!this.symbolFadeHoldUntil||this.symbolFadeHoldUntil<w.now()}clearFadeHold(){this.symbolFadeHoldUntil=void 0}setHoldDuration(e){this.symbolFadeHoldUntil=w.now()+e}setTexture(e,t){const i=t.context,o=i.gl;this.texture=this.texture||t.getTileTexture(e.width),this.texture&&this.texture instanceof z?this.texture.update(e):(this.texture=new z(i,e,o.RGBA8,{useMipmap:!0}),this.texture.bind(o.LINEAR,o.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=wt(Zl,this.tileID.canonical,this.tileTransform)[0],o=new Tt,s=new Et;for(let e=0;e<i.length;e++){const{x:t,y:r}=i[e];o.emplaceBack(t,r),s.emplaceBack(e)}s.emplaceBack(0),this._tileDebugIndexBuffer=e.createIndexBuffer(s),this._tileDebugBuffer=e.createVertexBuffer(o,St.members),this._tileDebugSegments=It.simpleSegment(0,0,o.length,s.length)}_makeTileBoundsBuffers(e,t){if(this._tileBoundsBuffer||!t||"mercator"===t.name)return;const i=wt(Zl,this.tileID.canonical,this.tileTransform)[0];let o,s;if(this.isRaster){const e=function(e,t){const i=at(e,t),o=Math.pow(2,e.z);for(let s=0;s<Ul;s++)for(let r=0;r<Ul;r++){const n=lt((e.x+(r+ql(r))/Nl)/o),a=ct((e.y+(s+ql(s))/Nl)/o),l=t.project(n,a),c=s*Ul+r;Gl[2*c+0]=Math.round((l.x*i.scale-i.x)*we),Gl[2*c+1]=Math.round((l.y*i.scale-i.y)*we)}Vl.fill(0),Hl.fill(0);for(let e=2045;e>=0;e--){const t=4*e,i=jl[t+0],o=jl[t+1],s=jl[t+2],r=jl[t+3],n=i+s>>1,a=o+r>>1,l=n+a-o,c=a+i-n,h=o*Ul+i,d=r*Ul+s,u=a*Ul+n,_=Math.hypot((Gl[2*h+0]+Gl[2*d+0])/2-Gl[2*u+0],(Gl[2*h+1]+Gl[2*d+1])/2-Gl[2*u+1])>=16;Vl[u]=Vl[u]||(_?1:0),e<1022&&(Vl[u]=Vl[u]||Vl[(o+c>>1)*Ul+(i+l>>1)]||Vl[(r+c>>1)*Ul+(s+l>>1)])}const s=new dt,r=new ht;let n=0;function a(e,t){const i=t*Ul+e;return 0===Hl[i]&&(s.emplaceBack(Gl[2*i+0],Gl[2*i+1],e*we/Nl,t*we/Nl),Hl[i]=++n),Hl[i]-1}function l(e,t,i,o,s,n){const c=e+i>>1,h=t+o>>1;if(Math.abs(e-s)+Math.abs(t-n)>1&&Vl[h*Ul+c])l(s,n,e,t,c,h),l(i,o,s,n,c,h);else{const l=a(e,t),c=a(i,o),h=a(s,n);r.emplaceBack(l,c,h)}}return l(0,0,Nl,Nl,Nl,0),l(Nl,Nl,0,0,0,Nl),{vertices:s,indices:r}}(this.tileID.canonical,t);o=e.vertices,s=e.indices}else{o=new dt,s=new ht;for(const{x:e,y:t}of i)o.emplaceBack(e,t,0,0);const e=Ct(o.int16.subarray(0,4*o.length),void 0,4);for(let t=0;t<e.length;t+=3)s.emplaceBack(e[t],e[t+1],e[t+2])}this._tileBoundsBuffer=e.createVertexBuffer(o,Rt.members),this._tileBoundsIndexBuffer=e.createIndexBuffer(s),this._tileBoundsSegments=It.simpleSegment(0,0,o.length,s.length)}_makeGlobeTileDebugBuffers(e,t){const i=t.projection;if(!i||"globe"!==i.name||t.freezeTileCoverage)return;const o=this.tileID.canonical,s=At(o,t),r=Dt(s),n=ye(t.zoom);let a;n>0&&(a=Lt(new Float64Array(16),t.globeMatrix)),this._makeGlobeTileDebugBorderBuffer(e,o,t,r,a,n),this._makeGlobeTileDebugTextBuffer(e,o,t,r,a,n)}_globePoint(e,t,i,o,s,r,n){let a=Ot(e,t,i);if(r){const s=1<<i.z,l=Ge(o.center.lng),c=qe(o.center.lat),h=(i.x+.5)/s-l;let d=0;h>.5?d=-1:h<-.5&&(d=1);let u=(e/we+i.x)/s+d,_=(t/we+i.y)/s;u=(u-l)*o._pixelsPerMercatorPixel+l,_=(_-c)*o._pixelsPerMercatorPixel+c;const p=[u*o.worldSize,_*o.worldSize,0];fe(p,p,r),a=Pt(a,p,n)}return fe(a,a,s)}_makeGlobeTileDebugBorderBuffer(e,t,i,o,s,r){const n=new Tt,a=new Et,l=new Mt,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,o,s,r);l.emplaceBack(m[0],m[1],m[2]),a.emplaceBack(f+h)}},h=we;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,St.members),this._globeTileDebugBorderBuffer=e.createVertexBuffer(l,zt.members),this._tileDebugSegments=It.simpleSegment(0,0,n.length,a.length)}_makeGlobeTileDebugTextBuffer(e,t,i,o,s,r){const n=we/4,a=new Tt,l=new ht,c=new Mt,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,o,s,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),o=d(e,t+1),s=d(e+1,t),r=d(e+1,t+1);l.emplaceBack(i,o,s),l.emplaceBack(s,o,r)}this._tileDebugTextIndexBuffer=e.createIndexBuffer(l),this._tileDebugTextBuffer=e.createVertexBuffer(a,St.members),this._globeTileDebugTextBuffer=e.createVertexBuffer(c,zt.members),this._tileDebugTextSegments=It.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&&(this.imageAtlasTexture.destroy(),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 z&&(this.texture.destroy(),delete this.texture),this.emissiveTexture&&this.emissiveTexture instanceof z&&(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"}}kt.setPbf(Nt);class $l extends Wl{constructor(e,t,i,o,s){super(e,t,i,o,s),this._workQueuePerLayer=new Map,this._fetchQueuePerLayer=new Map,this._taskQueue=new Map,this._isHeaderLoaded=!1,this.textureDescriptorPerLayer=new Map,this.texturePerLayer=new Map}getLayers(){return this._mrt?Object.values(this._mrt.layers):[]}getLayer(e){return this._mrt&&this._mrt.getLayer(e)}setTexturePerLayer(e,t,i){const o=i.context,s=o.gl;let r=this.texturePerLayer.get(e)||i.getTileTexture(t.width);r&&r instanceof z?r.update(t,{premultiply:!1}):r=new z(o,t,s.RGBA8,{premultiply:!1}),this.texturePerLayer.has(e)||this.texturePerLayer.set(e,r)}flushQueues(e){const t=this._workQueuePerLayer.get(e)||[],i=this._fetchQueuePerLayer.get(e)||[];for(;t.length;)t.pop()();for(;i.length;)i.pop()()}flushAllQueues(){for(const e of this._workQueuePerLayer.keys()){const t=this._workQueuePerLayer.get(e)||[];for(;t.length;)t.pop()()}for(const e of this._fetchQueuePerLayer.keys()){const t=this._fetchQueuePerLayer.get(e)||[];for(;t.length;)t.pop()()}}fetchHeader(e=16384,t){const i=this._mrt=new kt(30),o=Object.assign({},this.requestParams,{headers:{Range:"bytes=0-"+(e-1)}});return this.entireBuffer=null,this.request=Ut(o,((o,s,r)=>{if(o)t(o);else try{const o=i.getHeaderLength(s);if(o>e)return void(this.request=this.fetchHeader(o,t));i.parseHeader(s),this._isHeaderLoaded=!0;let n=0;for(const e of Object.values(i.layers))n=Math.max(n,e.dataIndex[e.dataIndex.length-1].lastByte);s.byteLength>=n&&(this.entireBuffer=s),t(null,this.entireBuffer||s,r)}catch(e){t(e)}})),this.request}fetchBandForRender(e,t,i,o){this.fetchBand(e,t,i,(s=>{if(s)return void o(s);this.updateTextureDescriptor(e,t,i);const r=this.textureDescriptorPerLayer.get(t);o(null,r?r.img:null)}))}fetchBand(e,t,i,o,s=!0){const r=this._mrt;if(!this._isHeaderLoaded||!r)return void o(new Error("Tile header is not ready"));const n=this.actor;if(!n)return void o(new Error("Can't fetch tile band without an actor"));let a;const l=O(String(i),O(this.tileID.key,e));let c=this._taskQueue.get(l);c?c.add(o):(c=new Set,c.add(o),this._taskQueue.set(l,c));const h=(e,t)=>{a.complete(e,t),e?o(e):(c.forEach((e=>e(null,t))),this._taskQueue.delete(l))},d=(e,i)=>{if(e)return o(e);const s=n.send("decodeRasterArray",{type:"raster-array",source:this.source,scope:this.scope,tileID:this.tileID,uid:this.uid,buffer:i,task:a},h,void 0,!0);if(null!==t){const e=this._workQueuePerLayer.get(t)||[];e.push((()=>{s&&s.cancel(),a.cancel()})),this._workQueuePerLayer.has(t)||this._workQueuePerLayer.set(t,e)}};let u;try{u=r.getLayer(e)}catch(e){if("reloading"===this.state)return;throw e}if(!u)return void o(new Error(`Unknown sourceLayer "${e}"`));if(u.hasDataForBand(i))return c.forEach((e=>e(null,null))),void this._taskQueue.delete(l);const _=u.getDataRange([i]);if(a=r.createDecodingTask(_),!a||a.tasks.length)if(null!==t&&this.flushQueues(t),this.entireBuffer)d(null,this.entireBuffer.slice(_.firstByte,_.lastByte+1));else{const e=Object.assign({},this.requestParams,{headers:{Range:`bytes=${_.firstByte}-${_.lastByte}`}}),i=Ut(e,d);if(null!==t){const e=this._fetchQueuePerLayer.get(t)||[];e.push((()=>{i.cancel(),a.cancel()})),this._fetchQueuePerLayer.has(t)||this._fetchQueuePerLayer.set(t,e)}}}updateNeeded(e,t){return(!this.textureDescriptorPerLayer.get(e)||this.textureDescriptorPerLayer.get(e).band!==t||this.refreshedUponExpiration)&&"errored"!==this.state}updateTextureDescriptor(e,t,i){if(!this._mrt)return;const o=this._mrt.getLayer(e);if(!o||!o.hasBand(i)||!o.hasDataForBand(i))return;const{bytes:s,tileSize:r,buffer:n,offset:a,scale:l}=o.getBandView(i),c=r+2*n,h=new T({width:c,height:c},s),d=this.texturePerLayer.get(t);d&&d instanceof z&&d.update(h,{premultiply:!1}),this.textureDescriptorPerLayer.set(t,{layer:e,band:i,img:h,buffer:n,offset:a,tileSize:r,format:o.pixelFormat,mix:[l,256*l,65536*l,16777216*l]})}destroy(e=!1){if(super.destroy(e),delete this._mrt,!e)for(const e of this.texturePerLayer.values())e&&e instanceof z&&e.destroy();this.texturePerLayer.clear(),this.textureDescriptorPerLayer.clear(),this.fbo&&(this.fbo.destroy(),delete this.fbo),delete this.request,delete this.requestParams,this._isHeaderLoaded=!1}}class Xl{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 o=e.wrapped().key;void 0===this.data[o]&&(this.data[o]=[]);const s={value:t,timeout:void 0};if(void 0!==i&&(s.timeout=setTimeout((()=>{this.remove(e,s)}),i)),this.data[o].push(s),this.order.push(o),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,o=void 0===t?0:this.data[i].indexOf(t),s=this.data[i][o];return this.data[i].splice(o,1),s.timeout&&clearTimeout(s.timeout),0===this.data[i].length&&delete this.data[i],this.onRemove(s.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 o of this.data[i])e(o.value)||t.push(o);for(const e of t)this.remove(e.value.tileID,e)}}class Yl{constructor(){this.state={},this.stateChanges={},this.deletedStates={}}updateState(e,t,i){const o=String(t);if(this.stateChanges[e]=this.stateChanges[e]||{},this.stateChanges[e][o]=this.stateChanges[e][o]||{},Object.assign(this.stateChanges[e][o],i),null===this.deletedStates[e]){this.deletedStates[e]={};for(const t in this.state[e])t!==o&&(this.deletedStates[e][t]=null)}else if(this.deletedStates[e]&&null===this.deletedStates[e][o]){this.deletedStates[e][o]={};for(const t in this.state[e][o])i[t]||(this.deletedStates[e][o][t]=null)}else for(const t in i)this.deletedStates[e]&&this.deletedStates[e][o]&&null===this.deletedStates[e][o][t]&&delete this.deletedStates[e][o][t]}removeFeatureState(e,t,i){if(null===this.deletedStates[e])return;const o=String(t);if(this.deletedStates[e]=this.deletedStates[e]||{},i&&void 0!==t)null!==this.deletedStates[e][o]&&(this.deletedStates[e][o]=this.deletedStates[e][o]||{},this.deletedStates[e][o][i]=null);else if(void 0!==t)if(this.stateChanges[e]&&this.stateChanges[e][o])for(i in this.deletedStates[e][o]={},this.stateChanges[e][o])this.deletedStates[e][o][i]=null;else this.deletedStates[e][o]=null;else this.deletedStates[e]=null}getState(e,t){const i=this.state[e]||{},o=this.stateChanges[e]||{},s=this.deletedStates[e];if(null===s)return{};if(void 0!==t){const e=String(t),r=Object.assign({},i[e],o[e]);if(s){const e=s[t];if(null===e)return{};for(const t in e)delete r[t]}return r}const r=Object.assign({},i,o);if(s)for(const e in s)delete r[e];return r}initializeTileState(e,t){e.refreshFeatureState(t)}coalesceChanges(e,t){const i={};for(const e in this.stateChanges){this.state[e]=this.state[e]||{};const t={};for(const i in this.stateChanges[e])this.state[e][i]||(this.state[e][i]={}),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]||{};const t={};if(null===this.deletedStates[e])for(const i in this.state[e])t[i]={},this.state[e][i]={};else for(const i in this.deletedStates[e]){if(null===this.deletedStates[e][i])this.state[e][i]={};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.assign(i[e],t)}if(this.stateChanges={},this.deletedStates={},0!==Object.keys(i).length)for(const i in e)e[i].refreshFeatureState(t)}}class Kl extends E{constructor(e,t,i){super(),this.id=e,this._onlySymbols=i,t.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))})),t.on("error",(()=>{this._sourceErrored=!0})),this._source=t,this._tiles={},this._cache=new Xl(0,this._unloadTile.bind(this)),this._timers={},this._cacheTimers={},this._minTileCacheSize=t.minTileCacheSize,this._maxTileCacheSize=t.maxTileCacheSize,this._loadedParentTiles={},this.castsShadows=!1,this.tileCoverLift=0,this._coveredTiles={},this._shadowCasterTiles={},this._state=new Yl,this._isRaster="raster"===this._source.type||"raster-dem"===this._source.type||"raster-array"===this._source.type||"custom"===this._source.type&&"raster"===this._source._dataType}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}loaded(){if(this._sourceErrored)return!0;if(!this._sourceLoaded)return!1;if(!this._source.loaded())return!1;for(const e in this._tiles)if(!this._tiles[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)}_loadTile(e,t){return e.isSymbolTile=this._onlySymbols,e.isExtraShadowCaster=this._shadowCasterTiles[e.tileID.key],this._source.loadTile(e,t)}_unloadTile(e){if(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 in this._tiles){const i=this._tiles[t];i.upload(e,this.map?this.map.painter:void 0),i.prepare(this.map.style.imageManager,this.map?this.map.painter:null,this._source.scope)}}getIds(){return Object.values(this._tiles).map((e=>e.tileID)).sort(Ql).map((e=>e.key))}getRenderableIds(e,t){const i=[];for(const o in this._tiles)this._isIdRenderable(+o,e,t)&&i.push(this._tiles[o]);return e?i.sort(((e,t)=>{const i=e.tileID,o=t.tileID,s=new r(i.canonical.x,i.canonical.y)._rotate(this.transform.angle),n=new r(o.canonical.x,o.canonical.y)._rotate(this.transform.angle);return i.overscaledZ-o.overscaledZ||n.y-s.y||n.x-s.x})).map((e=>e.tileID.key)):i.map((e=>e.tileID)).sort(Ql).map((e=>e.key))}hasRenderableParent(e){const t=this.findLoadedParent(e,0);return!!t&&this._isIdRenderable(t.tileID.key)}_isIdRenderable(e,t,i){return this._tiles[e]&&this._tiles[e].hasData()&&!this._coveredTiles[e]&&(t||!this._tiles[e].holdingForFade())&&(i||!this._shadowCasterTiles[e])}reload(){if(this._paused)this._shouldReloadOnResume=!0;else{this._cache.reset();for(const e in this._tiles)"errored"!==this._tiles[e].state&&this._reloadTile(+e,"reloading")}}_reloadTile(e,t){const i=this._tiles[e];i&&("loading"!==i.state&&(i.state=t),this._loadTile(i,this._tileLoaded.bind(this,i,e,t)))}_tileLoaded(e,t,i,o,s){if(o){if(e.state="errored",404!==o.status)this._source.fire(new A(o,{tile:e}));else{if(this._source.fire(new D("data",{dataType:"source",sourceDataType:"error",sourceId:this._source.id,tile:e})),!(e.tileID.key in this._loadedParentTiles))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)}return}e.timeAdded=w.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 Map;s&&s.responseHeaders&&(r=s.responseHeaders),this._source.fire(new D("data",{dataType:"source",tile:e,coord:e.tileID,sourceCacheId:this.id,responseHeaders:r}))}_backfillDEM(e){const t=this.getRenderableIds();for(let o=0;o<t.length;o++){const s=t[o];if(e.neighboringTiles&&e.neighboringTiles[s]){const t=this.getTileByID(s);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 o=t.tileID.canonical.y-e.tileID.canonical.y,s=Math.pow(2,e.tileID.canonical.z),r=t.tileID.key;0===i&&0===o||Math.abs(o)>1||(Math.abs(i)>1&&(1===Math.abs(i+s)?i+=s:1===Math.abs(i-s)&&(i-=s)),t.dem&&e.dem&&(e.dem.backfillBorder(t.dem,i,o),e.neighboringTiles&&e.neighboringTiles[r]&&(e.neighboringTiles[r].backfilled=!0)))}}getTile(e){return this.getTileByID(e.key)}getTileByID(e){return this._tiles[e]}_retainLoadedChildren(e,t,i,o){for(const s in this._tiles){let r=this._tiles[s];if(o[s]||!r.hasData()||r.tileID.overscaledZ<=t||r.tileID.overscaledZ>i)continue;let n=r.tileID;for(;r&&r.tileID.overscaledZ>t+1;){const e=r.tileID.scaledTo(r.tileID.overscaledZ-1);r=this._tiles[e.key],r&&r.hasData()&&(n=e)}let a=n;for(;a.overscaledZ>t;)if(a=a.scaledTo(a.overscaledZ-1),e[a.key]){o[n.key]=n;break}}}findLoadedParent(e,t){if(e.key in this._loadedParentTiles){const i=this._loadedParentTiles[e.key];return i&&i.tileID.overscaledZ>=t?i:null}for(let i=e.overscaledZ-1;i>=t;i--){const t=e.scaledTo(i),o=this._getLoadedTile(t);if(o)return o}}_getLoadedTile(e){const t=this._tiles[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,o=Math.ceil(e.height/t)+1,s=Math.floor(i*o*5),r="number"==typeof this._minTileCacheSize?Math.max(this._minTileCacheSize,s):s,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={};for(const i in this._tiles){const o=this._tiles[i];o.tileID=o.tileID.unwrapTo(o.tileID.wrap+t),e[o.tileID.key]=o}this._tiles=e;for(const e in this._timers)clearTimeout(this._timers[e]),delete this._timers[e];for(const e in this._tiles)this._setTileReloadTimer(+e,this._tiles[e])}}update(e,t,i,o,s){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={},this._coveredTiles={};const r="batched-model"===this._source.type;let n,a=this._source.maxzoom;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)}if(this.used||this.usedForTerrain){if(this._source.tileID)n=e.getVisibleUnwrappedCoordinates(this._source.tileID).map((e=>new Ke(e.canonical.z,e.wrap,e.canonical.z,e.canonical.x,e.canonical.y)));else if(0!==this.tileCoverLift){const o=e.clone();o.tileCoverLift=this.tileCoverLift,n=o.coveringTiles({tileSize:t||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:a,roundZoom:this._source.roundZoom&&!i,reparseOverscaled:this._source.reparseOverscaled,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:r}),this._source.minzoom<=1&&"globe"===e.projection.name&&(n.push(new Ke(1,0,1,0,0)),n.push(new Ke(1,0,1,1,0)),n.push(new Ke(1,0,1,0,1)),n.push(new Ke(1,0,1,1,1)))}else if(n=e.coveringTiles({tileSize:t||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:a,roundZoom:this._source.roundZoom&&!i,reparseOverscaled:this._source.reparseOverscaled,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:r}),this._source.hasTile){const e=this._source.hasTile.bind(this._source);n=n.filter((t=>e(t)))}}else n=[];if(n.length>0&&"globe"!==this.transform.projection.name&&!this.usedForTerrain&&!Jl(this._source.type)){const a=e.coveringZoomLevel({tileSize:t||this._source.tileSize,roundZoom:this._source.roundZoom&&!i}),l=Math.min(a,this._source.maxzoom);if(r){const t=e.extendTileCover(n,l);for(const e of t)n.push(e)}else if(s){const t=e.extendTileCoverToNearPlane(n,this.transform.getFrustum(l),l);for(const e of t)n.push(e)}else if(this.castsShadows&&o){const t=e.extendTileCover(n,l,o,16);for(const e of t)this._shadowCasterTiles[e.key]=!0,n.push(e)}}const c=this._updateRetainedTiles(n);if(Jl(this._source.type)&&0!==n.length){const e={},t={},i=Object.keys(c);for(const o of i){const i=c[o],s=this._tiles[o];if(!s||s.fadeEndTime&&s.fadeEndTime<=w.now())continue;const r=this.findLoadedParent(i,Math.max(i.overscaledZ-Kl.maxOverzooming,this._source.minzoom));r&&(this._addTile(r.tileID),e[r.tileID.key]=r.tileID),t[o]=i}const o=n[n.length-1].overscaledZ;for(const e in this._tiles){const i=this._tiles[e];if(c[e]||!i.hasData())continue;let s=i.tileID;for(;s.overscaledZ>o;){s=s.scaledTo(s.overscaledZ-1);const o=this._tiles[s.key];if(o&&o.hasData()&&t[s.key]){c[e]=i.tileID;break}}}for(const t in e)c[t]||(this._coveredTiles[t]=!0,c[t]=e[t])}for(const e in c)this._tiles[e].clearFadeHold();const h=jt(this._tiles,c);for(const e of h){const t=this._tiles[e];t.hasSymbolBuckets&&!t.holdingForFade()?t.setHoldDuration(this.map._fadeDuration):t.hasSymbolBuckets&&!t.symbolFadeFinished()||this._removeTile(+e)}this._updateLoadedParentTileCache(),this._onlySymbols&&this._source.afterUpdate&&this._source.afterUpdate()}releaseSymbolFadeTiles(){for(const e in this._tiles)this._tiles[e].holdingForFade()&&this._removeTile(+e)}_updateRetainedTiles(e){const t={};if(0===e.length)return t;const i={},o=e.reduce(((e,t)=>Math.min(e,t.overscaledZ)),1/0),s=e[0].overscaledZ,r=Math.max(s-Kl.maxOverzooming,this._source.minzoom),n=Math.max(s+Kl.maxUnderzooming,this._source.minzoom),a={};for(const i of e){const e=this._addTile(i);t[i.key]=i,e.hasData()||o<this._source.maxzoom&&(a[i.key]=i)}this._retainLoadedChildren(a,o,n,t);for(const o of e){let e=this._tiles[o.key];if(e.hasData())continue;if(o.canonical.z>=this._source.maxzoom){const e=o.children(this._source.maxzoom)[0],i=this.getTile(e);if(i&&i.hasData()){t[e.key]=e;continue}}else{const e=o.children(this._source.maxzoom);if(t[e[0].key]&&t[e[1].key]&&t[e[2].key]&&t[e[3].key])continue}let s=e.wasRequested();for(let n=o.overscaledZ-1;n>=r;--n){const r=o.scaledTo(n);if(i[r.key])break;if(i[r.key]=!0,e=this.getTile(r),!e&&s&&(e=this._addTile(r)),e&&(t[r.key]=r,s=e.wasRequested(),e.hasData()))break}}return t}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const e in this._tiles){const t=[];let i,o=this._tiles[e].tileID;for(;o.overscaledZ>0;){if(o.key in this._loadedParentTiles){i=this._loadedParentTiles[o.key];break}t.push(o.key);const e=o.scaledTo(o.overscaledZ-1);if(i=this._getLoadedTile(e),i)break;o=e}for(const e of t)this._loadedParentTiles[e]=i}}_addTile(e){let t=this._tiles[e.key];if(t)return!0!==t.isExtraShadowCaster||!!this._shadowCasterTiles[e.key]||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),this._cacheTimers[e.key]&&(clearTimeout(this._cacheTimers[e.key]),delete this._cacheTimers[e.key],this._setTileReloadTimer(e.key,t)));const i=Boolean(t);if(!i){const i=this.map?this.map.painter:null,o=this._source.tileSize*e.overscaleFactor();t="raster-array"===this._source.type?new $l(e,o,this.transform.tileZoom,i,this._isRaster):new Wl(e,o,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[e.key]=t,i||this._source.fire(new D("dataloading",{tile:t,coord:t.tileID,dataType:"source"})),t}_setTileReloadTimer(e,t){e in this._timers&&(clearTimeout(this._timers[e]),delete this._timers[e]);const i=t.getExpiryTimeout();i&&(this._timers[e]=setTimeout((()=>{this._reloadTile(e,"expired"),delete this._timers[e]}),i))}_removeTile(e){const t=this._tiles[e];t&&(t.uses--,delete this._tiles[e],this._timers[e]&&(clearTimeout(this._timers[e]),delete this._timers[e]),t.uses>0||(t.hasData()&&"reloading"!==t.state||"empty"===t.state?this._cache.add(t.tileID,t,t.getExpiryTimeout()):(t.aborted=!0,this._abortTile(t),this._unloadTile(t))))}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(const e in this._tiles)this._removeTile(+e);this._source._clear&&this._source._clear(),this._cache.reset(),this.map&&this.usedForTerrain&&this.map.painter.terrain&&this.map.painter.terrain.resetTileLookupCache(this.id)}tilesIn(e,t,i){const o=[],s=this.transform;if(!s)return o;const r="globe"===s.projection.name,n=Ge(s.center.lng);for(const a in this._tiles){const l=this._tiles[a];if(i&&l.clearQueryDebugViz(),l.holdingForFade())continue;let c;if(r){const e=l.tileID.canonical;if(0===e.z){const t=[Math.abs(Fe(n,...ec(e,-1))-n),Math.abs(Fe(n,...ec(e,1))-n)];c=[0,2*t.indexOf(Math.min(...t))-1]}else{const t=[Math.abs(Fe(n,...ec(e,-1))-n),Math.abs(Fe(n,...ec(e,0))-n),Math.abs(Fe(n,...ec(e,1))-n)];c=[t.indexOf(Math.min(...t))-1]}}else c=[0];for(const i of c){const r=e.containsTile(l,s,t,i);r&&o.push(r)}}return o}getShadowCasterCoordinates(){return this._getRenderableCoordinates(!1,!0)}getVisibleCoordinates(e){return this._getRenderableCoordinates(e)}_getRenderableCoordinates(e,t){const i=this.getRenderableIds(e,t).map((e=>this._tiles[e].tileID)),o="globe"===this.transform.projection.name;for(const e of i)e.projMatrix=this.transform.calculateProjMatrix(e.toUnwrapped()),e.expandedProjMatrix=o?this.transform.calculateProjMatrix(e.toUnwrapped(),!1,!0):e.projMatrix;return i}sortCoordinatesByDistance(e){const t=e.slice(),i=this.transform._camera.position,o=this.transform._camera.forward(),s={};for(const e of t){const t=1/(1<<e.canonical.z);s[e.key]=((e.canonical.x+.5)*t+e.wrap-i[0])*o[0]+((e.canonical.y+.5)*t-i[1])*o[1]-i[2]*o[2]}return t.sort(((e,t)=>s[e.key]-s[t.key])),t}hasTransition(){if(this._source.hasTransition())return!0;if(Jl(this._source.type))for(const e in this._tiles){const t=this._tiles[e];if(void 0!==t.fadeEndTime&&t.fadeEndTime>=w.now())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 o=this._tiles[e];o&&o.setDependencies(t,i)}reloadTilesForDependencies(e,t){for(const i in this._tiles)this._tiles[i].hasDependency(e,t)&&this._reloadTile(+i,"reloading");this._cache.filter((i=>!i.hasDependency(e,t)))}_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,o=Array.isArray(e)?e:[e],s=this.map.painter.terrain,r=this.usedForTerrain&&s?s.getScaledDemTileSize():this._source.tileSize;for(const e of o){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());Gt(n,((e,t)=>{const i=new Wl(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 Ql(e,t){const i=Math.abs(2*e.wrap)-+(e.wrap<0),o=Math.abs(2*t.wrap)-+(t.wrap<0);return e.overscaledZ-t.overscaledZ||o-i||t.canonical.y-e.canonical.y||t.canonical.x-e.canonical.x}function Jl(e){return"raster"===e||"image"===e||"video"===e||"custom"===e}function ec(e,t){const i=1<<e.z;return[e.x/i+t,(e.x+1)/i+t]}Kl.maxOverzooming=10,Kl.maxUnderzooming=3;class tc{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 o=this.style._mergedLayers[i];if("fill-extrusion"===o.type||"building"===o.type)this.layers.push({layer:o,visible:e,visibilityChanged:t});else if("model"===o.type){const i=this.style.getLayerSource(o);i&&"batched-model"===i.type&&this.layers.push({layer:o,visible:e,visibilityChanged:t})}}}onNewFrame(e){this.layersGotHidden=!1;for(const t of this.layers){const i=t.layer;let o=!1;"fill-extrusion"===i.type?o=!i.isHidden(e)&&i.paint.get("fill-extrusion-opacity")>0:"building"===i.type?o=!i.isHidden(e)&&i.paint.get("building-opacity")>0:"model"===i.type&&(o=!i.isHidden(e)&&i.paint.get("model-opacity").constantOr(1)>0),this.layersGotHidden=this.layersGotHidden||!o&&t.visible,t.visible=o}}updateZOffset(e,t){this.currentBuildingBuckets=[];for(const e of this.layers){const i=e.layer,o=this.style.getLayerSourceCache(i);let s=1;"fill-extrusion"===i.type?s=e.visible?i.paint.get("fill-extrusion-vertical-scale"):0:"building"===i.type&&(s=e.visible?i.paint.get("building-vertical-scale"):0);let r=o?o.getTile(t):null;if(!r&&o)for(const e in o._tiles){const i=o._tiles[e];if(t.canonical.isChildOf(i.tileID.canonical)){r=i;break}}this.currentBuildingBuckets.push({bucket:r?r.getBucket(i):null,tileID:r?r.tileID:t,verticalScale:s})}e.hasAnyZOffset=!1;let i=!1;for(let o=0;o<e.symbolInstances.length;o++){const s=e.symbolInstances.get(o),r=s.zOffset,n=this._getHeightAtTileOffset(t,s.tileAnchorX,s.tileAnchorY);s.zOffset=n!==Number.NEGATIVE_INFINITY?n:r,i||r===s.zOffset||(i=!0),e.hasAnyZOffset||0===s.zOffset||(e.hasAnyZOffset=!0)}i&&(e.zOffsetBuffersNeedUpload=!0,e.zOffsetSortDirty=!0)}_mapCoordToOverlappingTile(e,t,i,o){let s=t,r=i;if(e.canonical.z!==o.canonical.z){const n=o.canonical,a=1/(1<<e.canonical.z-n.z);s=(t+e.canonical.x*we)*a-n.x*we|0,r=(i+e.canonical.y*we)*a-n.y*we|0}return{tileX:s,tileY:r}}_getHeightAtTileOffset(e,t,i){let o,s;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?o=u.height:s=Math.max(u.height*c,s||0))}if(void 0!==s)return s;for(let s=0;s<this.layers.length;++s){const r=this.layers[s];if("model"!==r.layer.type||!r.visible)continue;const{bucket:n,tileID:a}=this.currentBuildingBuckets[s];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!==o?Math.min(h.maxHeight,o)*h.verticalScale:h.height?h.height*h.verticalScale:Number.NEGATIVE_INFINITY}return this.layersGotHidden?0:Number.NEGATIVE_INFINITY}}function ic(e,t){const i={};for(const t in e)"ref"!==t&&(i[t]=e[t]);return Vt.forEach((e=>{e in t&&(i[e]=t[e])})),i}function oc(e){e=e.slice();const t=Object.create(null);for(let i=0;i<e.length;i++)t[e[i].id]=e[i];for(let i=0;i<e.length;i++)"ref"in e[i]&&(e[i]=ic(e[i],t[e[i].ref]));return e}const sc={setStyle:"setStyle",addLayer:"addLayer",removeLayer:"removeLayer",setPaintProperty:"setPaintProperty",setLayoutProperty:"setLayoutProperty",setSlot:"setSlot",setFilter:"setFilter",addSource:"addSource",removeSource:"removeSource",setGeoJSONSourceData:"setGeoJSONSourceData",setLayerZoomRange:"setLayerZoomRange",setLayerProperty:"setLayerProperty",setCenter:"setCenter",setZoom:"setZoom",setBearing:"setBearing",setPitch:"setPitch",setSprite:"setSprite",setGlyphs:"setGlyphs",setTransition:"setTransition",setLight:"setLight",setTerrain:"setTerrain",setFog:"setFog",setSnow:"setSnow",setRain:"setRain",setCamera:"setCamera",setLights:"setLights",setProjection:"setProjection",addImport:"addImport",removeImport:"removeImport",updateImport:"updateImport",addIconset:"addIconset",removeIconset:"removeIconset"};function rc(e,t,i){i.push({command:sc.addSource,args:[e,t[e]]})}function nc(e,t,i){t.push({command:sc.removeSource,args:[e]}),i[e]=!0}function ac(e,t,i,o){nc(e,i,o),rc(e,t,i)}function lc(e,t,i){let o;for(o in e[i])if(e[i].hasOwnProperty(o)&&"data"!==o&&!Ht(e[i][o],t[i][o]))return!1;for(o in t[i])if(t[i].hasOwnProperty(o)&&"data"!==o&&!Ht(e[i][o],t[i][o]))return!1;return!0}function cc(e,t,i,o,s,r){let n;for(n in t=t||{},e=e||{})e.hasOwnProperty(n)&&(Ht(e[n],t[n])||i.push({command:r,args:[o,n,t[n],s]}));for(n in t)t.hasOwnProperty(n)&&!e.hasOwnProperty(n)&&(Ht(e[n],t[n])||i.push({command:r,args:[o,n,t[n],s]}))}function hc(e){return e.id}function dc(e,t){return e[t.id]=t,e}function uc(e,t,i){const o=t.createTileMatrix(e,e.worldSize,i.toUnwrapped());return Be(new Float32Array(16),e.projMatrix,o)}function _c(e,t,i){if(t.projection.name===i.projection.name)return e.projMatrix;const o=i.clone();return o.setProjection(t.projection),uc(o,t.getProjection(),e)}function pc(e,t,i){return t.name===i.projection.name?e.projMatrix:uc(i,t,e)}class fc{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[this._distances.length-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=Fe(e,0,1);let t=1,i=this._distances[t];const o=e*this.paddedLength+this.padding;for(;i<o&&t<this._distances.length;)i=this._distances[++t];const s=t-1,r=this._distances[s],n=i-r,a=n>0?(o-r)/n:0;return this.points[s].mult(1-a).add(this.points[t].mult(a))}}class mc{constructor(e,t,i){const o=this.boxCells=[],s=this.circleCells=[];this.xCellCount=Math.ceil(e/i),this.yCellCount=Math.ceil(t/i);for(let e=0;e<this.xCellCount*this.yCellCount;e++)o.push([]),s.push([]);this.circleKeys=[],this.boxKeys=[],this.bboxes=[],this.circles=[],this.width=e,this.height=t,this.xScale=this.xCellCount/e,this.yScale=this.yCellCount/t,this.boxUid=0,this.circleUid=0}keysLength(){return this.boxKeys.length+this.circleKeys.length}insert(e,t,i,o,s){this._forEachCell(t,i,o,s,this._insertBoxCell,this.boxUid++),this.boxKeys.push(e),this.bboxes.push(t),this.bboxes.push(i),this.bboxes.push(o),this.bboxes.push(s)}insertCircle(e,t,i,o){this._forEachCell(t-o,i-o,t+o,i+o,this._insertCircleCell,this.circleUid++),this.circleKeys.push(e),this.circles.push(t),this.circles.push(i),this.circles.push(o)}_insertBoxCell(e,t,i,o,s,r){this.boxCells[s].push(r)}_insertCircleCell(e,t,i,o,s,r){this.circleCells[s].push(r)}_query(e,t,i,o,s,r){if(i<0||e>this.width||o<0||t>this.height)return!s&&[];const n=[];if(e<=0&&t<=0&&this.width<=i&&this.height<=o){if(s)return!0;for(let e=0;e<this.boxKeys.length;e++)n.push({key:this.boxKeys[e],x1:this.bboxes[4*e],y1:this.bboxes[4*e+1],x2:this.bboxes[4*e+2],y2:this.bboxes[4*e+3]});for(let e=0;e<this.circleKeys.length;e++){const t=this.circles[3*e],i=this.circles[3*e+1],o=this.circles[3*e+2];n.push({key:this.circleKeys[e],x1:t-o,y1:i-o,x2:t+o,y2:i+o})}return r?n.filter(r):n}return this._forEachCell(e,t,i,o,this._queryCell,n,{hitTest:s,seenUids:{box:{},circle:{}}},r),s?n.length>0:n}_queryCircle(e,t,i,o,s){const r=e-i,n=e+i,a=t-i,l=t+i;if(n<0||r>this.width||l<0||a>this.height)return!o&&[];const c=[];return this._forEachCell(r,a,n,l,this._queryCellCircle,c,{hitTest:o,circle:{x:e,y:t,radius:i},seenUids:{box:{},circle:{}}},s),o?c.length>0:c}query(e,t,i,o,s){return this._query(e,t,i,o,!1,s)}hitTest(e,t,i,o,s){return this._query(e,t,i,o,!0,s)}hitTestCircle(e,t,i,o){return this._queryCircle(e,t,i,!0,o)}_queryCell(e,t,i,o,s,r,n,a){const l=n.seenUids,c=this.boxCells[s];if(null!==c){const s=this.bboxes;for(const h of c)if(!l.box[h]){l.box[h]=!0;const c=4*h;if(e<=s[c+2]&&t<=s[c+3]&&i>=s[c+0]&&o>=s[c+1]&&(!a||a(this.boxKeys[h]))){if(n.hitTest)return r.push(!0),!0;r.push({key:this.boxKeys[h],x1:s[c],y1:s[c+1],x2:s[c+2],y2:s[c+3]})}}}const h=this.circleCells[s];if(null!==h){const s=this.circles;for(const c of h)if(!l.circle[c]){l.circle[c]=!0;const h=3*c;if(this._circleAndRectCollide(s[h],s[h+1],s[h+2],e,t,i,o)&&(!a||a(this.circleKeys[c]))){if(n.hitTest)return r.push(!0),!0;{const e=s[h],t=s[h+1],i=s[h+2];r.push({key:this.circleKeys[c],x1:e-i,y1:t-i,x2:e+i,y2:t+i})}}}}}_queryCellCircle(e,t,i,o,s,r,n,a){const l=n.circle,c=n.seenUids,h=this.boxCells[s];if(null!==h){const e=this.bboxes;for(const t of h)if(!c.box[t]){c.box[t]=!0;const i=4*t;if(this._circleAndRectCollide(l.x,l.y,l.radius,e[i+0],e[i+1],e[i+2],e[i+3])&&(!a||a(this.boxKeys[t])))return r.push(!0),!0}}const d=this.circleCells[s];if(null!==d){const e=this.circles;for(const t of d)if(!c.circle[t]){c.circle[t]=!0;const i=3*t;if(this._circlesCollide(e[i],e[i+1],e[i+2],l.x,l.y,l.radius)&&(!a||a(this.circleKeys[t])))return r.push(!0),!0}}}_forEachCell(e,t,i,o,s,r,n,a){const l=this._convertToXCellCoord(e),c=this._convertToYCellCoord(t),h=this._convertToXCellCoord(i),d=this._convertToYCellCoord(o);for(let u=l;u<=h;u++)for(let l=c;l<=d;l++)if(s.call(this,e,t,i,o,this.xCellCount*l+u,r,n,a))return}_convertToXCellCoord(e){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(e*this.xScale)))}_convertToYCellCoord(e){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(e*this.yScale)))}_circlesCollide(e,t,i,o,s,r){const n=o-e,a=s-t,l=i+r;return l*l>n*n+a*a}_circleAndRectCollide(e,t,i,o,s,r,n){const a=(r-o)/2,l=Math.abs(e-(o+a));if(l>a+i)return!1;const c=(n-s)/2,h=Math.abs(t-(s+c));if(h>c+i)return!1;if(l<=a||h<=c)return!0;const d=l-a,u=h-c;return d*d+u*u<=i*i}}const gc={unknown:0,flipRequired:1,flipNotRequired:2},vc=Math.tan(85*Math.PI/180);function yc(e,t,i,o,s,r,n){const a=$t();if(i)if("globe"===r.name){const e=Xt(s,t);Be(a,a,e)}else{const e=Yt([],n);a[0]=e[0],a[1]=e[1],a[4]=e[2],a[5]=e[3],o||Wt(a,a,s.angle)}else Be(a,s.labelPlaneMatrix,e);return a}function xc(e,t,i,o,s,r,n){const a=yc(e,t,i,o,s,r,n);return"globe"===r.name&&i||(a[2]=a[6]=a[10]=a[14]=0),a}function bc(e,t,i,o,s,r,n){if(i){if("globe"===r.name){const a=yc(e,t,i,o,s,r,n);return Lt(a,a),Be(a,e,a),a}{const t=qt(e),i=Zt([]);return i[0]=n[0],i[1]=n[1],i[4]=n[2],i[5]=n[3],Be(t,t,i),o||Wt(t,t,-s.angle),t}}return s.glCoordMatrix}function wc(e,t,i,o){const s=[e,t,i,1];i?ke(s,s,o):Pc(s,s,o);const r=s[3];return s[0]/=r,s[1]/=r,s[2]/=r,s}function Tc(e,t){return Math.min(.5+e/t*.5,1.5)}function Ec(e,t){const i=e[0]/e[3],o=e[1]/e[3];return i>=-t[0]&&i<=t[0]&&o>=-t[1]&&o<=t[1]}function Sc(e,t,i,o,s,n,a,l,c,h,d=1){const u=i.transform,_=o?e.textSizeData:e.iconSizeData,p=ti(_,i.transform.zoom,d),f="globe"===u.projection.name,m=[256/i.width*2+1,256/i.height*2+1],g=o?e.text.dynamicLayoutVertexArray:e.icon.dynamicLayoutVertexArray;g.clear();let v=null;f&&(v=o?e.text.globeExtVertexArray:e.icon.globeExtVertexArray);const y=e.lineVertexArray,x=o?e.text.placedSymbolArray:e.icon.placedSymbolArray,b=i.transform.width/i.transform.height;let w,T=!1;for(let o=0;o<x.length;o++){const d=x.get(o),{numGlyphs:f,writingMode:E}=d;if(E!==ii.vertical||T||w===ii.horizontal||(T=!0),w=E,(d.hidden||E===ii.vertical)&&!T){Oc(f,g);continue}T=!1;const S=new r(d.tileAnchorX,d.tileAnchorY),I="road"===e.elevationType,C=!!u.elevation||I;let{x:R,y:A,z:D}=u.projection.projectTilePoint(S.x,S.y,h.canonical),L=null;if(C){const t=I?e.getElevationFeatureForText(o):null;L={getElevation:c,elevation:u.elevation,elevationFeature:t};const[i,s,r]=c(S,u.elevation,t);R+=i,A+=s,D+=r}const O=[R,A,D,1];if(ke(O,O,t),!Ec(O,m)){Oc(f,g);continue}const P=O[3],M=Tc(i.transform.getCameraToCenterDistance(u.projection),P),z=ri(_,p,d),F=a?z/M:z*M,B=wc(R,A,D,s);if(B[3]<=0){Oc(f,g);continue}let k={};const N=Ee(e.layers[0].layout.get("text-max-angle")),U=Math.cos(N),j=a?null:L,G=Rc(d,F,!1,l,t,s,n,e.glyphOffsetArray,y,g,v,B,S,k,b,j,u.projection,h,a,U);T=G.useVertical,j&&G.needsFlipping&&(k={}),(G.notEnoughRoom||T||G.needsFlipping&&Rc(d,F,!0,l,t,s,n,e.glyphOffsetArray,y,g,v,B,S,k,b,j,u.projection,h,a,U).notEnoughRoom)&&Oc(f,g)}o?(e.text.dynamicLayoutVertexBuffer.updateData(g),v&&e.text.globeExtVertexBuffer&&e.text.globeExtVertexBuffer.updateData(v)):(e.icon.dynamicLayoutVertexBuffer.updateData(g),v&&e.icon.globeExtVertexBuffer&&e.icon.globeExtVertexBuffer.updateData(v))}function Ic(e,t,i,o,s,r,n,a,l,c,h,d,u,_,p,f,m){const{lineStartIndex:g,glyphStartIndex:v,segment:y}=a,x=v+a.numGlyphs,b=g+a.lineLength,w=t.getoffsetX(v),T=t.getoffsetX(x-1),E=Lc(e*w,i,o,s,r,n,y,g,b,l,c,h,d,u,!0,_,p,f,m);if(!E)return null;const S=Lc(e*T,i,o,s,r,n,y,g,b,l,c,h,d,u,!0,_,p,f,m);return S?{first:E,last:S}:null}function Cc(e,t,i,o){return e===ii.horizontal&&Math.abs(o)>Math.abs(i)?{useVertical:!0}:e===ii.vertical?o>0?{needsFlipping:!0}:null:t!==gc.unknown&&function(e,t){return 0===e||Math.abs(t/e)>vc}(i,o)?t===gc.flipRequired?{needsFlipping:!0}:null:i<0?{needsFlipping:!0}:null}function Rc(e,t,i,o,s,n,a,l,c,h,d,u,_,p,f,m,g,v,y,x){const b=t/24,w=e.lineOffsetX*b,T=e.lineOffsetY*b,{lineStartIndex:E,glyphStartIndex:S,numGlyphs:I,segment:C,writingMode:R,flipState:A}=e,D=E+e.lineLength,L=e=>{if(d){const[t,i,o]=e.up,s=h.length;oi(d,s+0,t,i,o),oi(d,s+1,t,i,o),oi(d,s+2,t,i,o),oi(d,s+3,t,i,o)}const[t,i,o]=e.point;si(h,t,i,o,e.angle)};if(I>1){const t=Ic(b,l,w,T,i,u,_,e,c,n,p,m,!1,g,v,y,x);if(!t)return{notEnoughRoom:!0};if(o&&!i){let[i,o,s]=t.first.point,[r,n,l]=t.last.point;[i,o]=wc(i,o,s,a),[r,n]=wc(r,n,l,a);const c=Cc(R,A,(r-i)*f,n-o);if(e.flipState=c&&c.needsFlipping?gc.flipRequired:gc.flipNotRequired,c)return c}L(t.first);for(let e=S+1;e<S+I-1;e++){const t=Lc(b*l.getoffsetX(e),w,T,i,u,_,C,E,D,c,n,p,m,!1,!1,g,v,y,x);if(!t)return h.length-=4*(e-S),{notEnoughRoom:!0};L(t)}L(t.last)}else{if(o&&!i){const t=wc(_.x,_.y,0,s),i=E+C+1,o=new r(c.getx(i),c.gety(i)),n=wc(o.x,o.y,0,s),a=n[3]>0?n:Dc(_,o,t,1,s,void 0,g,v.canonical),l=Cc(R,A,(a[0]-t[0])*f,a[1]-t[1]);if(e.flipState=l&&l.needsFlipping?gc.flipRequired:gc.flipNotRequired,l)return l}const t=Lc(b*l.getoffsetX(S),w,T,i,u,_,C,E,D,c,n,p,m,!1,!1,g,v,y,x);if(!t)return{notEnoughRoom:!0};L(t)}return{}}function Ac(e,t,i,o,s){const{x:r,y:n,z:a}=o.projectTilePoint(e.x,e.y,t);if(!s)return wc(r,n,a,i);const[l,c,h]=s.getElevation(e,s.elevation,s.elevationFeature);return wc(r+l,n+c,a+h,i)}function Dc(e,t,i,o,s,r,n,a){const l=Ac(e.sub(t)._unit()._add(e),a,s,n,r);return Le(l,i,l),Oe(l,l),Jt(l,i,l,o)}function Lc(e,t,i,o,s,n,a,l,c,h,d,u,_,p,f,m,g,v,y){const x=o?e-t:e+t;let b=x>0?1:-1,w=0;o&&(b*=-1,w=Math.PI),b<0&&(w+=Math.PI);let T=l+a+(b>0?0:1)|0,E=s,S=s,I=0,C=0;const R=Math.abs(x),A=[],D=[];let L=n,O=L,P=Kt([]);const M=()=>Dc(O,L,S,R-I+1,d,_,m,g.canonical);for(;I+C<=R;){if(T+=b,T<l||T>=c)return null;if(S=E,O=L,A.push(S),p&&D.push(O),L=new r(h.getx(T),h.gety(T)),E=u[T],!E){const e=Ac(L,g.canonical,d,m,_);E=e[3]>0?u[T]=e:M()}I+=C;const e=Le([],E,S),t=Qt(S,E);if(i&&t>0&&C>0&&ni(P,e)/(C*t)<y)return null;C=t,P=e}f&&_&&(u[T]&&(E=M(),C=Qt(S,E),P=Le([],E,S)),u[T]=E);const z=(R-I)/C,F=L.sub(O)._mult(z)._add(O),B=Jt([],S,P,z);let k=[0,0,1],N=P[0],U=P[1];if(v&&(k=m.upVector(g.canonical,F.x,F.y),0!==k[0]||0!==k[1]||1!==k[2])){const e=[k[2],0,-k[0]],t=ei([],k,e);Oe(e,e),Oe(t,t),N=ni(P,e),U=ni(P,t)}if(i){const e=ei([],k,P);Oe(e,e),Jt(B,B,e,i*b)}const j=w+Math.atan2(U,N);return A.push(B),p&&D.push(F),{point:B,angle:j,path:A,tilePath:D,up:k}}function Oc(e,t){const i=t.length,o=i+4*e;t.resize(o),t.float32.fill(-1/0,4*i,4*o)}function Pc(e,t,i){const o=t[0],s=t[1];return e[0]=i[0]*o+i[4]*s+i[12],e[1]=i[1]*o+i[5]*s+i[13],e[3]=i[3]*o+i[7]*s+i[15],e}const Mc=100;class zc{constructor(e,t,i=new mc(e.width+200,e.height+200,25),o=new mc(e.width+200,e.height+200,25)){this.transform=e,this.grid=i,this.ignoredGrid=o,this.pitchfactor=Math.cos(e._pitch)*e.cameraToCenterDistance,this.screenRightBoundary=e.width+Mc,this.screenBottomBoundary=e.height+Mc,this.gridRightBoundary=e.width+200,this.gridBottomBoundary=e.height+200,this.fogState=t}placeCollisionBox(e,t,i,o,s,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,o]=v.upVector(g.canonical,i.tileAnchorX,i.tileAnchorY),s=v.upVectorScale(g.canonical,this.transform.center.lat,this.transform.worldSize).metersToTile;d+=e*m*s,u+=t*m*s,_+=o*m*s}const y="globe"===e.projection.name,x="globe"===e.projection.name?ye(this.transform.zoom):0;if(g&&y&&x<1&&!r){const e=1<<g.canonical.z,t=ai(p,f);li(t,t,1/we),ci(t,t,ai(g.canonical.x,g.canonical.y)),li(t,t,1/e),hi(t,t,ai(o[0],o[1])),t[0]=di(t[0],-.5,.5),li(t,t,we);const i=ui(t[0],t[1],we/(2*Math.PI),1);ke(i,i,s),d=xe(d,i[0],x),u=xe(u,i[1],x),_=xe(_,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,S=(i.x2*t+n.x+i.padding)*w+b.point.x,I=(i.y2*t+n.y+i.padding)*w+b.point.y,C=b.perspectiveRatio<=.55||b.occluded;return!this.isInsideGrid(T,E,S,I)||!a&&this.grid.hitTest(T,E,S,I,h)||C?{box:[],offscreen:!1,occluded:b.occluded}:{box:[T,E,S,I],offscreen:this.isOffscreen(T,E,S,I),occluded:!1}}placeCollisionCircles(e,t,i,o,s,n,a,l,c,h,d,u,_,p,f,m){const g=[],v=this.transform.elevation,y=e.getProjection(),x="road"===e.elevationType,b=!!v||x,w=_i.getAtTileOffsetFunc(m,this.transform.center.lat,this.transform.worldSize,y),T=new r(i.tileAnchorX,i.tileAnchorY),E=new r(i.tileAnchorX,i.tileAnchorY);let{x:S,y:I,z:C}=y.projectTilePoint(E.x,E.y,m.canonical),R=null;if(b){const t=x?e.getElevationFeatureForText(o):null;R={getElevation:w,elevation:v,elevationFeature:t};const[i,s,r]=w(T,v,t);S+=i,I+=s,C+=r}const A="globe"===y.name,D=this.projectAndGetPerspectiveRatio(l,S,I,C,m,A||!!v||this.transform.pitch>0,y),{perspectiveRatio:L}=D,O=(u?a/L:a*L)/mi,P=wc(S,I,C,c),M=i.lineOffsetX*O,z=i.lineOffsetY*O,F=Ee(e.layers[0].layout.get("text-max-angle")),B=Math.cos(F),k=D.signedDistanceFromCamera>0?Ic(O,n,M,z,x&&1===i.flipState,P,E,i,s,c,{},b&&!u?R:null,u&&b,y,m,u,B):null;let N=!1,U=!1,j=!0;if(k&&!D.occluded){const e=.5*p*L+f,i=new r(-100,-100),o=new r(this.screenRightBoundary,this.screenBottomBoundary),s=new fc,{first:n,last:a}=k,l=n.path.length;let c=[];for(let e=l-1;e>=1;e--)c.push(n.path[e]);for(let e=1;e<a.path.length;e++)c.push(a.path[e]);const u=2.5*e;h&&(c=c.map((([e,t,i],o)=>(b&&!A&&(i=w(o<l-1?n.tilePath[l-1-o]:a.tilePath[o-l+2],v,R.elevationFeature)[2]),wc(e,t,i,h)))),c.some((e=>e[3]<=0))&&(c=[]));let m=[];if(c.length>0){let e=1/0,t=-1/0,s=1/0,n=-1/0;for(const i of c)e=Math.min(e,i[0]),s=Math.min(s,i[1]),t=Math.max(t,i[0]),n=Math.max(n,i[1]);t>=i.x&&e<=o.x&&n>=i.y&&s<=o.y&&(m=[c.map((e=>new r(e[0],e[1])))],(e<i.x||t>o.x||s<i.y||n>o.y)&&(m=pi(m,i.x,i.y,o.x,o.y)))}for(const i of m){s.reset(i,.25*e);let o=0;o=s.length<=.5*e?1:Math.ceil(s.paddedLength/u)+1;for(let i=0;i<o;i++){const r=i/Math.max(o-1,1),n=s.lerp(r),a=n.x+Mc,l=n.y+Mc;g.push(a,l,e,0);const c=a-e,h=l-e,u=a+e,p=l+e;if(j=j&&this.isOffscreen(c,h,u,p),U=U||this.isInsideGrid(c,h,u,p),!t&&this.grid.hitTestCircle(a,l,e,_)&&(N=!0,!d))return{circles:[],offscreen:!1,collisionDetected:N,occluded:!1}}}}return{circles:!d&&N||!U?[]:g,offscreen:j,collisionDetected:N,occluded:D.occluded}}queryRenderedSymbols(e){if(0===e.length||0===this.grid.keysLength()&&0===this.ignoredGrid.keysLength())return{};const t=[];let i=1/0,o=1/0,s=-1/0,n=-1/0;for(const a of e){const e=new r(a.x+Mc,a.y+Mc);i=Math.min(i,e.x),o=Math.min(o,e.y),s=Math.max(s,e.x),n=Math.max(n,e.y),t.push(e)}const a=this.grid.query(i,o,s,n).concat(this.ignoredGrid.query(i,o,s,n)),l={},c={};for(const e of a){const i=e.key;if(void 0===l[i.bucketInstanceId]&&(l[i.bucketInstanceId]={}),l[i.bucketInstanceId][i.featureIndex])continue;const o=[new r(e.x1,e.y1),new r(e.x2,e.y1),new r(e.x2,e.y2),new r(e.x1,e.y2)];fi(t,o)&&(l[i.bucketInstanceId][i.featureIndex]=!0,void 0===c[i.bucketInstanceId]&&(c[i.bucketInstanceId]=[]),c[i.bucketInstanceId].push(i.featureIndex))}return c}insertCollisionBox(e,t,i,o,s){(t?this.ignoredGrid:this.grid).insert({bucketInstanceId:i,featureIndex:o,collisionGroupID:s},e[0],e[1],e[2],e[3])}insertCollisionCircles(e,t,i,o,s){const r=t?this.ignoredGrid:this.grid,n={bucketInstanceId:i,featureIndex:o,collisionGroupID:s};for(let t=0;t<e.length;t+=4)r.insertCircle(n,e[t],e[t+1],e[t+2])}projectAndGetPerspectiveRatio(e,t,i,o,s,n,a){const l=[t,i,o,1];let c=!1;if(o||this.transform.pitch>0){if(ke(l,l,e),this.fogState&&s&&"globe"!==a.name){const e=function(e,t,i,o,s,r){const n=r.calculateFogTileMatrix(s),a=[t,i,o];return fe(a,a,n),nl(e,ge(a),r.pitch,r._fov)}(this.fogState,t,i,o,s.toUnwrapped(),this.transform);c=e>.9}}else Pc(l,l,e);const h=l[3];return{point:new r((l[0]/h+1)/2*this.transform.width+Mc,(-l[1]/h+1)/2*this.transform.height+Mc),perspectiveRatio:Math.min(.5+this.transform.getCameraToCenterDistance(a)/h*.5,1.5),signedDistanceFromCamera:h,occluded:n&&l[2]>h||c}}isOffscreen(e,t,i,o){return i<Mc||e>=this.screenRightBoundary||o<Mc||t>this.screenBottomBoundary}isInsideGrid(e,t,i,o){return i>=0&&e<this.gridRightBoundary&&o>=0&&t<this.gridBottomBoundary}getViewportMatrix(){const e=Zt([]);return Bt(e,e,[-100,-100,0]),e}}class Fc{constructor(e,t,i,o){this.opacity=e?Math.max(0,Math.min(1,e.opacity+(e.placed?t:-t))):o&&i?1:0,this.placed=i}isHidden(){return 0===this.opacity&&!this.placed}}class Bc{constructor(e,t,i,o,s,r=!1){this.text=new Fc(e?e.text:null,t,i,s),this.icon=new Fc(e?e.icon:null,t,o,s),this.clipped=r}isHidden(){return this.text.isHidden()&&this.icon.isHidden()}}class kc{constructor(e,t,i,o=!1){this.text=e,this.icon=t,this.skipFade=i,this.clipped=o}}class Nc{constructor(){this.invProjMatrix=$t(),this.viewportMatrix=$t(),this.circles=[]}}class Uc{constructor(e,t,i,o,s){this.bucketInstanceId=e,this.featureIndex=t,this.sourceLayerIndex=i,this.bucketIndex=o,this.tileID=s}}class jc{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 Gc(e,t,i,o,s){const{horizontalAlign:n,verticalAlign:a}=bi(e),l=-(n-.5)*t,c=-(a-.5)*i,h=wi(e,o);return new r(l+h[0]*s,c+h[1]*s)}function Vc(e,t,i,o,s){const n=new r(e,t);return i&&n._rotate(o?s:-s),n}class Hc{constructor(e,t,i,o,s,r){this.transform=e.clone(),this.projection=e.projection.name,this.collisionIndex=new zc(this.transform,s),this.buildingIndex=r,this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=t,this.retainedQueryData={},this.collisionGroups=new jc(i),this.collisionCircleArrays={},this.prevPlacement=o,o&&(o.prevPlacement=void 0),this.placedOrientations={},this.lastReplacementSourceUpdateTime=0}getBucketParts(e,t,i,o,s=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/we,u=i.tileID.toUnwrapped();this.transform.setProjection(r.projection);const _=(p=i.tileID,f=r.getProjection(),m=this.transform,f.name===this.projection?m.calculateProjMatrix(p.toUnwrapped()):uc(m,f,p));var p,f,m;const g="map"===a.get("text-pitch-alignment"),v="map"===a.get("text-rotation-alignment");t.compileFilter(t.options);const y=t.dynamicFilter(),x=t.dynamicFilterNeedsFeature(),b=this.transform.calculatePixelsToTileUnitsMatrix(i),w=xc(_,i.tileID.canonical,g,v,this.transform,r.getProjection(),b);let T=null;const E=r.getProjection().createInversionMatrix(this.transform,i.tileID.canonical);if(g){const e=bc(_,i.tileID.canonical,g,v,this.transform,r.getProjection(),b);T=Be([],this.transform.labelPlaneMatrix,e)}let S=null;y&&i.latestFeatureIndex&&(S={unwrappedTileID:u,dynamicFilter:y,dynamicFilterNeedsFeature:x}),this.retainedQueryData[r.bucketInstanceId]=new Uc(r.bucketInstanceId,n,r.sourceLayerIndex,r.index,i.tileID);const[I,C]=r.layers[0].layout.get("text-size-scale-range"),R=Fe(s,I,C),[A,D]=a.get("icon-size-scale-range"),L=Fe(s,A,D),O={bucket:r,layout:a,paint:l,posMatrix:_,invMatrix:E,mercatorCenter:[Ge(this.transform.center.lng),qe(this.transform.center.lat)],textLabelPlaneMatrix:w,labelToScreenMatrix:T,clippingData:S,scale:h,textPixelRatio:d,holdingForFade:i.holdingForFade(),collisionBoxArray:c,partiallyEvaluatedTextSize:ti(r.textSizeData,this.transform.zoom,R),partiallyEvaluatedIconSize:ti(r.iconSizeData,this.transform.zoom,L),collisionGroup:this.collisionGroups.get(r.sourceID),latestFeatureIndex:i.latestFeatureIndex};if(o)for(const t of r.sortKeyRanges){const{sortKey:i,symbolInstanceStart:o,symbolInstanceEnd:s}=t;e.push({sortKey:i,symbolInstanceStart:o,symbolInstanceEnd:s,parameters:O})}else e.push({symbolInstanceStart:0,symbolInstanceEnd:r.symbolInstances.length,parameters:O})}attemptAnchorPlacement(e,t,i,o,s,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],S=Gc(e,r,n,E,a),I=this.collisionIndex.placeCollisionBox(m,a,t,i,o,s,Vc(S.x,S.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,o,s,Vc(S.x,S.y,l,c,this.transform.angle),_,h,d,u.predicate).box.length)return}if(I.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},this.markUsedJustification(m,e,p,g),m.allowVerticalPlacement&&(this.markUsedOrientation(m,g,p),this.placedOrientations[T]=g),{shift:S,placedGlyphBoxes:I}}}placeLayerBucketPart(e,t,i,o,s=1){const{bucket:n,layout:a,paint:l,posMatrix:c,textLabelPlaneMatrix:h,labelToScreenMatrix:d,clippingData:_,textPixelRatio:p,mercatorCenter:f,invMatrix:m,holdingForFade:g,collisionBoxArray:v,partiallyEvaluatedTextSize:y,partiallyEvaluatedIconSize:x,collisionGroup:b,latestFeatureIndex:w}=e.parameters,T=a.get("text-optional"),E=a.get("icon-optional"),S=a.get("text-allow-overlap"),I=a.get("icon-allow-overlap"),C="map"===a.get("text-rotation-alignment"),R="map"===a.get("icon-rotation-alignment"),A="map"===a.get("text-pitch-alignment"),D=l.get("symbol-z-offset"),L="sea"===a.get("symbol-elevation-reference"),O=a.get("symbol-placement"),[P,M]=a.get("text-size-scale-range"),[z,F]=a.get("icon-size-scale-range"),B=Fe(s,P,M),k=Fe(s,z,F),N=a.get("text-variable-anchor"),U=C&&"point"!==O,j=R&&"point"!==O,G=N&&n.hasTextData(),V=n.hasIconTextFit()&&G&&n.hasIconData();this.transform.setProjection(n.projection);const H=G||U,q=j||V;let Z=S&&(I||!n.hasIconData()||E),W=I&&(S||!n.hasTextData()||T);const $=!D.isConstant();!n.collisionArrays&&v&&n.deserializeCollisionBoxes(v),i&&o&&n.updateCollisionDebugBuffers(this.transform.zoom,v,B,k);const X=(e,o,s)=>{const{crossTileID:l,numVerticalGlyphVertices:u}=e;let v=null;if(_&&_.dynamicFilterNeedsFeature||$){const t=this.retainedQueryData[n.bucketInstanceId];v=w.loadFeature({featureIndex:e.featureIndex,bucketIndex:t.bucketIndex,sourceLayerIndex:t.sourceLayerIndex,layoutVertexArrayOffset:0});const i=v.properties?v.properties.worldview:null;if(n.localizable&&n.worldview&&"string"==typeof i)if("all"===i)v.properties.$localized=!0;else{if(!i.split(",").includes(n.worldview))return;v.properties.$localized=!0,v.properties.worldview=n.worldview}}if(_&&!(0,_.dynamicFilter)({zoom:this.transform.zoom,pitch:this.transform.pitch,worldview:n.worldview},v,this.retainedQueryData[n.bucketInstanceId].tileID.canonical,new r(e.tileAnchorX,e.tileAnchorY),this.transform.calculateDistanceTileData(_.unwrappedTileID)))return this.placements[l]=new kc(!1,!1,!1,!0),void t.add(l);const R=D.evaluate(v,{});if(t.has(l))return;if(g)return void(this.placements[l]=new kc(!1,!1,!1));let O=!1,P=!1,M=!0,z=!1,F=!1,B=null,k={box:null,offscreen:null,occluded:null},U={box:null},j=null,G=null,V=null,X=0,Y=0,K=0;s.textFeatureIndex?X=s.textFeatureIndex:e.useRuntimeCollisionCircles&&(X=e.featureIndex),s.verticalTextFeatureIndex&&(Y=s.verticalTextFeatureIndex);const Q=n.elevationFeatures?n.elevationFeatures[e.elevationFeatureIndex]:void 0,J=t=>{t.tileID=this.retainedQueryData[n.bucketInstanceId].tileID;const i=this.transform.elevation;t.elevation=L?R:R+_i.getAtTileOffset(t.tileID,new r(t.tileAnchorX,t.tileAnchorY),i,Q),t.elevation+=e.zOffset},ee=s.textBox;if(ee){J(ee);const t=t=>{let i=ii.horizontal;if(n.allowVerticalPlacement&&!t&&this.prevPlacement){const t=this.prevPlacement.placedOrientations[l];t&&(this.placedOrientations[l]=t,i=t,this.markUsedOrientation(n,i,e))}return i},i=(e,t)=>{if(n.allowVerticalPlacement&&u>0&&s.verticalTextBox){for(const i of n.writingModes)if(i===ii.vertical?(k=t(),U=k):k=e(),k&&k.box&&k.box.length)break}else k=e()};if(N){let r=N;if(this.prevPlacement&&this.prevPlacement.variableOffsets[l]){const e=this.prevPlacement.variableOffsets[l];r.indexOf(e.anchor)>0&&(r=r.filter((t=>t!==e.anchor)),r.unshift(e.anchor))}const a=(t,i,s)=>{const a=n.getSymbolInstanceTextSize(y,e,this.transform.zoom,o),l=(t.x2-t.x1)*a+2*t.padding,h=(t.y2-t.y1)*a+2*t.padding,d=e.hasIconTextFit&&!I?i:null;d&&J(d);let u={box:[],offscreen:!1,occluded:!1};const _=S?2*r.length:r.length;for(let i=0;i<_;++i){const _=this.attemptAnchorPlacement(r[i%r.length],t,f,m,H,l,h,a,C,A,p,c,b,i>=r.length,e,o,n,s,d,y,x);if(_&&(u=_.placedGlyphBoxes,u&&u.box&&u.box.length)){O=!0,B=_.shift;break}}return u};i((()=>a(ee,s.iconBox,ii.horizontal)),(()=>{const e=s.verticalTextBox;return e&&J(e),n.allowVerticalPlacement&&!(k&&k.box&&k.box.length)&&u>0&&e?a(e,s.verticalIconBox,ii.vertical):{box:null,offscreen:null,occluded:null}})),k&&(O=k.box,M=k.offscreen,z=k.occluded);const h=t(!(!k||!k.box));if(!O&&this.prevPlacement){const t=this.prevPlacement.variableOffsets[l];t&&(this.variableOffsets[l]=t,this.markUsedJustification(n,t.anchor,e,h))}}else{const a=(t,i)=>{const s=n.getSymbolInstanceTextSize(y,e,this.transform.zoom,o),a=this.collisionIndex.placeCollisionBox(n,s,t,f,m,H,new r(0,0),S,p,c,b.predicate);return a&&a.box&&a.box.length&&(this.markUsedOrientation(n,i,e),this.placedOrientations[l]=i),a};i((()=>a(ee,ii.horizontal)),(()=>{const e=s.verticalTextBox;return n.allowVerticalPlacement&&u>0&&e?(J(e),a(e,ii.vertical)):{box:null,offscreen:null,occluded:null}})),t(!!(k&&k.box&&k.box.length))}}if(j=k,O=j&&j.box&&j.box.length>0,M=j&&j.offscreen,z=j&&j.occluded,e.useRuntimeCollisionCircles){const t=e.centerJustifiedTextSymbolIndex>=0?e.centerJustifiedTextSymbolIndex:e.verticalPlacedTextSymbolIndex,o=n.text.placedSymbolArray.get(t),s=ri(n.textSizeData,y,o),r=a.get("text-padding");G=this.collisionIndex.placeCollisionCircles(n,S,o,t,n.lineVertexArray,n.glyphOffsetArray,s,c,h,d,i,A,b.predicate,e.collisionCircleDiameter*s/mi,r,this.retainedQueryData[n.bucketInstanceId].tileID),O=S||G.circles.length>0&&!G.collisionDetected,M=M&&G.offscreen,z=G.occluded}if(s.iconFeatureIndex&&(K=s.iconFeatureIndex),s.iconBox){const t=t=>{J(t);const i=e.hasIconTextFit&&B?Vc(B.x,B.y,C,A,this.transform.angle):new r(0,0),o=n.getSymbolInstanceIconSize(x,this.transform.zoom,e.placedIconSymbolIndex);return this.collisionIndex.placeCollisionBox(n,o,t,f,m,q,i,I,p,c,b.predicate)};U&&U.box&&U.box.length&&s.verticalIconBox?(V=t(s.verticalIconBox),P=V.box.length>0):(V=t(s.iconBox),P=V.box.length>0),M=M&&V.offscreen,F=V.occluded}const te=T||0===e.numHorizontalGlyphVertices&&0===u,ie=E||0===e.numIconVertices;if(te||ie?ie?te||(P=P&&O):O=P&&O:P=O=P&&O,O&&j&&j.box&&this.collisionIndex.insertCollisionBox(j.box,a.get("text-ignore-placement"),n.bucketInstanceId,U&&U.box&&Y?Y:X,b.ID),P&&V&&this.collisionIndex.insertCollisionBox(V.box,a.get("icon-ignore-placement"),n.bucketInstanceId,K,b.ID),G&&(O&&this.collisionIndex.insertCollisionCircles(G.circles,a.get("text-ignore-placement"),n.bucketInstanceId,X,b.ID),i)){const e=n.bucketInstanceId;let t=this.collisionCircleArrays[e];void 0===t&&(t=this.collisionCircleArrays[e]=new Nc);for(let e=0;e<G.circles.length;e+=4)t.circles.push(G.circles[e+0]),t.circles.push(G.circles[e+1]),t.circles.push(G.circles[e+2]),t.circles.push(G.collisionDetected?1:0)}const oe="globe"!==n.projection.name;Z=Z&&(oe||!z),W=W&&(oe||!F),this.placements[l]=new kc(O||Z,P||W,M||n.justReloaded),t.add(l)},Y=this.retainedQueryData[n.bucketInstanceId].tileID;if("offset"===n.elevationType&&this.buildingIndex&&this.buildingIndex.updateZOffset(n,Y),"road"===n.elevationType&&n.updateRoadElevation(Y.canonical),n.updateZOffset(),n.sortFeaturesByY){const e=n.getSortedSymbolIndexes(this.transform.angle);for(let t=e.length-1;t>=0;--t){const i=e[t];X(n.symbolInstances.get(i),i,n.collisionArrays[i])}n.hasAnyZOffset&&u(`${n.layerIds[0]} layer symbol-z-elevate: symbols are not sorted by elevation if symbol-z-order is evaluated to viewport-y`)}else if(n.hasAnyZOffset){const e=n.getSortedIndexesByZOffset();for(let t=0;t<e.length;++t){const i=e[t];X(n.symbolInstances.get(i),i,n.collisionArrays[i])}}else for(let t=e.symbolInstanceStart;t<e.symbolInstanceEnd;t++)X(n.symbolInstances.get(t),t,n.collisionArrays[t]);if(i&&n.bucketInstanceId in this.collisionCircleArrays){const e=this.collisionCircleArrays[n.bucketInstanceId];Lt(e.invProjMatrix,c),e.viewportMatrix=this.collisionIndex.getViewportMatrix()}n.justReloaded=!1}markUsedJustification(e,t,i,o){const{leftJustifiedTextSymbolIndex:s,centerJustifiedTextSymbolIndex:r,rightJustifiedTextSymbolIndex:n,verticalPlacedTextSymbolIndex:a,crossTileID:l}=i,c=Ti(t),h=o===ii.vertical?a:"left"===c?s:"center"===c?r:"right"===c?n:-1;s>=0&&(e.text.placedSymbolArray.get(s).crossTileID=h>=0&&s!==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)}markUsedOrientation(e,t,i){const o=t===ii.horizontal||t===ii.horizontalOnly?t:0,s=t===ii.vertical?t:0,{leftJustifiedTextSymbolIndex:r,centerJustifiedTextSymbolIndex:n,rightJustifiedTextSymbolIndex:a,verticalPlacedTextSymbolIndex:l}=i,c=e.text.placedSymbolArray;r>=0&&(c.get(r).placedOrientation=o),n>=0&&(c.get(n).placedOrientation=o),a>=0&&(c.get(a).placedOrientation=o),l>=0&&(c.get(l).placedOrientation=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 o=t?t.symbolFadeChange(e):1,s=t?t.opacities:{},r=t?t.variableOffsets:{},n=t?t.placedOrientations:{};for(const e in this.placements){const t=this.placements[e],r=s[e];r?(this.opacities[e]=new Bc(r,o,t.text,t.icon,null,t.clipped),i=i||t.text!==r.text.placed||t.icon!==r.icon.placed):(this.opacities[e]=new Bc(null,o,t.text,t.icon,t.skipFade,t.clipped),i=i||t.text||t.icon)}for(const e in s){const t=s[e];if(!this.opacities[e]){const s=new Bc(t,o,!1,!1);s.isHidden()||(this.opacities[e]=s,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,o){o&&(this.lastReplacementSourceUpdateTime=o.updateTime);const s=new Set;for(const r of t){const t=r.getBucket(e);t&&r.latestFeatureIndex&&e.fqid===t.layerIds[0]&&(this.updateBucketOpacities(t,s,r,r.collisionBoxArray,i,o,r.tileID,e.scope),"offset"===t.elevationType&&this.buildingIndex&&this.buildingIndex.updateZOffset(t,r.tileID),"road"===t.elevationType&&t.updateRoadElevation(r.tileID.canonical),t.updateZOffset())}}updateBucketOpacities(e,t,i,o,s,n,a,l){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 c=e.layers[0].layout,h=e.layers[0].paint,d=!!e.layers[0].dynamicFilter(),u=new Bc(null,0,!1,!1,!0),_=c.get("text-allow-overlap"),p=c.get("icon-allow-overlap"),f=c.get("text-variable-anchor"),m="map"===c.get("text-rotation-alignment"),g="map"===c.get("text-pitch-alignment"),v=h.get("symbol-z-offset"),y="sea"===c.get("symbol-elevation-reference"),x=!v.isConstant(),b=new Bc(null,0,_&&(p||!e.hasIconData()||c.get("icon-optional")),p&&(_||!e.hasTextData()||c.get("text-optional")),!0);!e.collisionArrays&&o&&(e.hasIconCollisionBoxData()||e.hasTextCollisionBoxData())&&e.deserializeCollisionBoxes(o);const w=(e,t,i)=>{for(let o=0;o<t/4;o++)e.opacityVertexArray.emplaceBack(i)};let T=0;n&&e.updateReplacement(a,n);for(let o=0;o<e.symbolInstances.length;o++){const c=e.symbolInstances.get(o),{numHorizontalGlyphVertices:h,numVerticalGlyphVertices:_,crossTileID:p,numIconVertices:E,tileAnchorX:S,tileAnchorY:I}=c;let C=null;const R=this.retainedQueryData[e.bucketInstanceId];x&&c&&R&&(C=i.latestFeatureIndex.loadFeature({featureIndex:c.featureIndex,bucketIndex:R.bucketIndex,sourceLayerIndex:R.sourceLayerIndex,layoutVertexArrayOffset:0}));const A=v.evaluate(C,{}),D=t.has(p);let L=this.opacities[p];D?L=u:L||(L=b,this.opacities[p]=L),t.add(p);const O=h>0||_>0,P=E>0,M=this.placedOrientations[p],z=M===ii.vertical,F=M===ii.horizontal||M===ii.horizontalOnly;!O&&!P||L.isHidden()||T++;let B=!1;if((O||P)&&n)for(const t of e.activeReplacements){if(gi(t,s,vi.Symbol,l))continue;if(t.min.x>S||S>t.max.x||t.min.y>I||I>t.max.y)continue;const e=xi(S,I,a.canonical,t.footprintTileId.canonical);if(B=yi(e,t.footprint),B)break}if(O){const t=B?eh:Jc(L.text);w(e.text,h,z?eh:t),w(e.text,_,F?eh:t);const i=L.text.isHidden(),{leftJustifiedTextSymbolIndex:o,centerJustifiedTextSymbolIndex:s,rightJustifiedTextSymbolIndex:r,verticalPlacedTextSymbolIndex:n}=c,a=e.text.placedSymbolArray,l=i||z?1:0;o>=0&&(a.get(o).hidden=l),s>=0&&(a.get(s).hidden=l),r>=0&&(a.get(r).hidden=l),n>=0&&(a.get(n).hidden=i||F?1:0);const d=this.variableOffsets[p];d&&this.markUsedJustification(e,d.anchor,c,M);const u=this.placedOrientations[p];u&&(this.markUsedJustification(e,"left",c,u),this.markUsedOrientation(e,u,c))}if(P){const t=B?eh:Jc(L.icon),{placedIconSymbolIndex:i,verticalPlacedIconSymbolIndex:o}=c,s=e.icon.placedSymbolArray,r=L.icon.isHidden()?1:0;i>=0&&(w(e.icon,E,z?eh:t),s.get(i).hidden=r),o>=0&&(w(e.icon,c.numVerticalIconVertices,F?eh:t),s.get(o).hidden=r)}if(e.hasIconCollisionBoxData()||e.hasTextCollisionBoxData()){const t=e.collisionArrays[o];if(t){let i=new r(0,0),o=!0;if(t.textBox||t.verticalTextBox){if(f){const e=this.variableOffsets[p];e?(i=Gc(e.anchor,e.width,e.height,e.textOffset,e.textScale),m&&i._rotate(g?this.transform.angle:-this.transform.angle)):o=!1}d&&(o=!L.clipped),t.textBox&&qc(e.textCollisionBox.collisionVertexArray,L.text.placed,!o||z,A,y,i.x,i.y),t.verticalTextBox&&qc(e.textCollisionBox.collisionVertexArray,L.text.placed,!o||F,A,y,i.x,i.y)}const s=o&&Boolean(!F&&t.verticalIconBox);t.iconBox&&qc(e.iconCollisionBox.collisionVertexArray,L.icon.placed,s,A,y,c.hasIconTextFit?i.x:0,c.hasIconTextFit?i.y:0),t.verticalIconBox&&qc(e.iconCollisionBox.collisionVertexArray,L.icon.placed,!s,A,y,c.hasIconTextFit?i.x:0,c.hasIconTextFit?i.y:0)}}}if(e.fullyClipped=0===T,e.sortFeatures(this.transform.angle),this.retainedQueryData[e.bucketInstanceId]&&(this.retainedQueryData[e.bucketInstanceId].featureSortOrder=e.featureSortOrder),e.hasTextData()&&e.text.opacityVertexBuffer&&e.text.opacityVertexBuffer.updateData(e.text.opacityVertexArray),e.hasIconData()&&e.icon.opacityVertexBuffer&&e.icon.opacityVertexBuffer.updateData(e.icon.opacityVertexArray),e.hasIconCollisionBoxData()&&e.iconCollisionBox.collisionVertexBuffer&&e.iconCollisionBox.collisionVertexBuffer.updateData(e.iconCollisionBox.collisionVertexArray),e.hasTextCollisionBoxData()&&e.textCollisionBox.collisionVertexBuffer&&e.textCollisionBox.collisionVertexBuffer.updateData(e.textCollisionBox.collisionVertexArray),e.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]}}symbolFadeChange(e){return 0===this.fadeDuration?1:(e-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(e){return Math.max(0,(this.transform.zoom-e)/1.5)}hasTransitions(e){return this.stale||e-this.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 qc(e,t,i,o,s,r,n){e.emplaceBack(t?1:0,i?1:0,r||0,n||0,o,s?1:0),e.emplaceBack(t?1:0,i?1:0,r||0,n||0,o,s?1:0),e.emplaceBack(t?1:0,i?1:0,r||0,n||0,o,s?1:0),e.emplaceBack(t?1:0,i?1:0,r||0,n||0,o,s?1:0)}const Zc=Math.pow(2,25),Wc=Math.pow(2,24),$c=Math.pow(2,17),Xc=Math.pow(2,16),Yc=Math.pow(2,9),Kc=Math.pow(2,8),Qc=Math.pow(2,1);function Jc(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*Zc+t*Wc+i*$c+t*Xc+i*Yc+t*Kc+i*Qc+t}const eh=0;class th{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,o,s,r){const n=this._bucketParts;for(;this._currentTileIndex<e.length;)if(t.getBucketParts(n,o,e[this._currentTileIndex],this._sortAcrossTiles,r),this._currentTileIndex++,s())return!0;for(this._sortAcrossTiles&&(this._sortAcrossTiles=!1,n.sort(((e,t)=>e.sortKey-t.sortKey)));this._currentPartIndex<n.length;){const e=n[this._currentPartIndex];if(t.placeLayerBucketPart(e,this._seenCrossTileIDs,i,0===e.symbolInstanceStart,r),this._currentPartIndex++,s())return!0}return!1}}class ih{constructor(e,t,i,o,s,r,n,a,l){this.placement=new Hc(e,s,r,n,a,l),this._currentPlacementIndex=t.length-1,this._forceFullPlacement=i,this._showCollisionBoxes=o,this._done=!1}isDone(){return this._done}continuePlacement(e,t,i,o,s){const r=w.now(),n=()=>{const e=w.now()-r;return!this._forceFullPlacement&&e>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 th(e),_=O(r.source,r.scope);if(u.continuePlacement(t||d?o[_]:i[_],this.placement,this._showCollisionBoxes,r,n,s))return;delete this._inProgressLayer}this._currentPlacementIndex--}this._done=!0}commit(e){return this.placement.commit(e),this.placement}}const oh=512/we/2;class sh{constructor(e,t,i){this.tileID=e,this.bucketInstanceId=i,this.index=new Ei(t.length,16,Int32Array),this.keys=[],this.crossTileIDs=[];const o=e.canonical.x*we,s=e.canonical.y*we;for(let e=0;e<t.length;e++){const{key:i,crossTileID:r,tileAnchorX:n,tileAnchorY:a}=t.get(e),l=Math.floor((o+n)*oh),c=Math.floor((s+a)*oh);this.index.add(l,c),this.keys.push(i),this.crossTileIDs.push(r)}this.index.finish()}findMatches(e,t,i){const o=this.tileID.canonical.z<t.canonical.z?1:Math.pow(2,this.tileID.canonical.z-t.canonical.z),s=oh/Math.pow(2,t.canonical.z-this.tileID.canonical.z),r=t.canonical.x*we,n=t.canonical.y*we;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)*s),u=Math.floor((n+h)*s),_=this.index.range(d-o,u-o,d+o,u+o).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 rh{constructor(){this.maxCrossTileID=0}generate(){return++this.maxCrossTileID}}class nh{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0}handleWrapJump(e){const t=Math.round((e-this.lng)/360);if(0!==t)for(const e in this.indexes){const i=this.indexes[e],o={};for(const e in i){const s=i[e];s.tileID=s.tileID.unwrapTo(s.tileID.wrap+t),o[s.tileID.key]=s}this.indexes[e]=o}this.lng=e}addBucket(e,t,i){if(this.indexes[e.overscaledZ]&&this.indexes[e.overscaledZ][e.key]){if(this.indexes[e.overscaledZ][e.key].bucketInstanceId===t.bucketInstanceId)return!1;this.removeBucketCrossTileIDs(e.overscaledZ,this.indexes[e.overscaledZ][e.key])}for(let e=0;e<t.symbolInstances.length;e++)t.symbolInstances.get(e).crossTileID=0;this.usedCrossTileIDs[e.overscaledZ]||(this.usedCrossTileIDs[e.overscaledZ]=new Set);const o=this.usedCrossTileIDs[e.overscaledZ];for(const i in this.indexes){const s=this.indexes[i];if(Number(i)>e.overscaledZ)for(const i in s){const r=s[i];r.tileID.isChildOf(e)&&r.findMatches(t.symbolInstances,e,o)}else{const r=s[e.scaledTo(Number(i)).key];r&&r.findMatches(t.symbolInstances,e,o)}}for(let e=0;e<t.symbolInstances.length;e++){const s=t.symbolInstances.get(e);s.crossTileID||(s.crossTileID=i.generate(),o.add(s.crossTileID))}return void 0===this.indexes[e.overscaledZ]&&(this.indexes[e.overscaledZ]={}),this.indexes[e.overscaledZ][e.key]=new sh(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(const i in this.indexes){const o=this.indexes[i];for(const s in o)e[o[s].bucketInstanceId]||(this.removeBucketCrossTileIDs(i,o[s]),delete o[s],t=!0)}return t}}class ah{constructor(){this.layerIndexes={},this.crossTileIDs=new rh,this.maxBucketInstanceId=0,this.bucketsInCurrentPlacement={}}addLayer(e,t,i,o){let s=this.layerIndexes[e.fqid];void 0===s&&(s=this.layerIndexes[e.fqid]=new nh);let r=!1;const n={};"globe"!==o.name&&s.handleWrapJump(i);for(const i of t){const t=i.getBucket(e);t&&e.fqid===t.layerIds[0]&&(t.bucketInstanceId||(t.bucketInstanceId=++this.maxBucketInstanceId),s.addBucket(i.tileID,t,this.crossTileIDs)&&(r=!0),n[t.bucketInstanceId]=!0)}return s.removeStaleBuckets(n)&&(r=!0),r}pruneUnusedLayers(e){const t={};e.forEach((e=>{t[e]=!0}));for(const e in this.layerIndexes)t[e]||delete this.layerIndexes[e]}}const lh=771;class ch{constructor(e,t,i,o){this.blendFunction=e,this.blendColor=t.toNonPremultipliedRenderColor(null),this.mask=i,this.blendEquation=o}}ch.Replace=[1,0,1,0],ch.disabled=new ch(ch.Replace,Te.transparent,[!1,!1,!1,!1]),ch.unblended=new ch(ch.Replace,Te.transparent,[!0,!0,!0,!0]),ch.alphaBlended=new ch([1,lh,1,lh],Te.transparent,[!0,!0,!0,!0]),ch.alphaBlendedNonPremultiplied=new ch([770,lh,770,lh],Te.transparent,[!0,!0,!0,!0]),ch.multiply=new ch([774,0,774,0],Te.transparent,[!0,!0,!0,!0]),ch.additive=new ch([1,1,1,1],Te.transparent,[!0,!0,!0,!0]);class hh{constructor(e,t,i){this.func=e,this.mask=t,this.range=i}}hh.ReadOnly=!1,hh.ReadWrite=!0,hh.disabled=new hh(519,hh.ReadOnly,[0,1]);const dh=7680;class uh{constructor(e,t,i,o,s,r){this.test=e,this.ref=t,this.mask=i,this.fail=o,this.depthFail=s,this.pass=r}}uh.disabled=new uh({func:519,mask:0},0,0,dh,dh,dh);const _h=1029,ph=2305;class fh{constructor(e,t,i){this.enable=e,this.mode=t,this.frontFace=i}}function mh(e,t){const i=Di(e,3);Oi(e,t),Fi(e,3,i)}function gh(e,t){const i=Ci([]);return Ri(i,i,-t),Ai(i,i,-e),i}function vh(e,t){const i=[e[0],e[1],0],o=[t[0],t[1],0];if(ge(i)>=1e-15){const e=Oe([],i);Si(o,e,ni(o,e)),t[0]=o[0],t[1]=o[1]}const s=ei([],t,e);if(Ii(s)<1e-15)return null;const r=Math.atan2(-s[1],s[0]);return gh(Math.atan2(Math.sqrt(e[0]*e[0]+e[1]*e[1]),-e[2]),r)}fh.disabled=new fh(!1,_h,ph),fh.backCCW=new fh(!0,_h,ph),fh.backCW=new fh(!0,_h,2304),fh.frontCW=new fh(!0,1028,2304),fh.frontCCW=new fh(!0,1028,ph);class yh{constructor(e,t){this.position=e,this.orientation=t}get position(){return this._position}set position(e){if(e){const t=e instanceof pe?e:new pe(e[0],e[1],e[2]);this._renderWorldCopies&&(t.x=di(t.x,0,1)),this._position=t}else this._position=null}lookAtPoint(e,t,i){if(this.orientation=null,!this.position)return;const o=this.position,s=i||(this._elevation?this._elevation.getAtPointOrZero(pe.fromLngLat(e)):0),r=pe.fromLngLat(e,s),n=[r.x-o.x,r.y-o.y,r.z-o.z];t||(t=[0,0,1]),t[2]=Math.abs(t[2]),this.orientation=vh(n,t)}setPitchBearing(e,t){this.orientation=gh(Ee(e),Ee(-t))}}class xh{constructor(e,t){this._transform=Zt([]),this.orientation=t,this.position=e}get mercatorPosition(){const e=this.position;return new pe(e[0],e[1],e[2])}get position(){const e=Di(this._transform,3);return[e[0],e[1],e[2]]}set position(e){var t;e&&Fi(this._transform,3,[(t=e)[0],t[1],t[2],1])}get orientation(){return this._orientation}set orientation(e){this._orientation=e||Ci([]),e&&mh(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=gh(e,t),mh(this._transform,this._orientation)}forward(){const e=Di(this._transform,2);return[-e[0],-e[1],-e[2]]}up(){const e=Di(this._transform,1);return[-e[0],-e[1],-e[2]]}right(){const e=Di(this._transform,0);return[e[0],e[1],e[2]]}getCameraToWorld(e,t){const i=new Float64Array(16);return Lt(i,this.getWorldToCamera(e,t)),i}getCameraToWorldMercator(){return this._transform}getWorldToCameraPosition(e,t,i){const o=this.position;Si(o,o,-e);const s=new Float64Array(16);return Ft(s,[i,i,i]),Bt(s,s,o),s[10]*=t,s}getWorldToCamera(e,t){const i=new Float64Array(16),o=new Float64Array(4),s=this.position;return Li(o,this._orientation),Si(s,s,-e),Oi(i,o),Bt(i,i,s),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,o){const s=new Float64Array(16);return Pi(s,e,t,i,o),s}getCameraToClipOrthographic(e,t,i,o,s,r){const n=new Float64Array(16);return Mi(n,e,t,i,o,s,r),n}getDistanceToElevation(e,t=!1){const i=0===e?0:zi(e,t?ct(this.position[1]):this.position[1]),o=this.forward();return(i-this.position[2])/o[2]}clone(){return new xh([...this.position],[...this.orientation])}}const bh={BaseColor:5,MetallicRoughness:6,Normal:7,Occlusion:8,Emission:9,LUT:10,ShadowMap0:11};class wh{constructor(e=0,t=0,i=0,o=0){if(isNaN(e)||e<0||isNaN(t)||t<0||isNaN(i)||i<0||isNaN(o)||o<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=o}interpolate(e,t,i){return null!=t.top&&null!=e.top&&(this.top=xe(e.top,t.top,i)),null!=t.bottom&&null!=e.bottom&&(this.bottom=xe(e.bottom,t.bottom,i)),null!=t.left&&null!=e.left&&(this.left=xe(e.left,t.left,i)),null!=t.right&&null!=e.right&&(this.right=xe(e.right,t.right,i)),this}getCenter(e,t){const i=Fe((this.left+e-this.right)/2,0,e),o=Fe((this.top+t-this.bottom)/2,0,t);return new r(i,o)}equals(e){return this.top===e.top&&this.bottom===e.bottom&&this.left===e.left&&this.right===e.right}clone(){return new wh(this.top,this.bottom,this.left,this.right)}toJSON(){return{top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}const Th=15;class Eh{constructor(e,t,i,o,s,r,n){this.tileSize=512,this._renderWorldCopies=void 0===s||s,this._minZoom=e||0,this._maxZoom=t||22,this._minPitch=i??0,this._maxPitch=o??60,this.setProjection(r),this.setMaxBounds(n),this.width=0,this.height=0,this._center=new tt(0,0),this.zoom=0,this.angle=0,this._fov=.6435011087932844,this._pitch=0,this._nearZ=0,this._farZ=0,this._unmodified=!0,this._edgeInsets=new wh,this._projMatrixCache={},this._alignedProjMatrixCache={},this._fogTileMatrixCache={},this._expandedProjMatrixCache={},this._distanceTileDataCache={},this._camera=new xh,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}clone(){const e=new Eh(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._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<Th}get elevation(){return this._elevation}set elevation(e){this._elevation!==e&&(this._elevation=e,this._updateCameraOnTerrain(),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 Ve(this.projection,["name","center","parallels"])}setProjection(e){this.projectionOptions=e||{name:"mercator"};const t=this.projection?this.getProjection():void 0;this.projection=Gi(this.projectionOptions);const i=this.getProjection(),o=!Ht(t,i);return o&&this._calcMatrices(),this.mercatorFromTransition=!1,o}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=Gi({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 zi(1,this.center.lat)*this.cameraWorldSizeForFog}get centerOffset(){return this.centerPoint._sub(this.size._div(2))}get size(){return new r(this.width,this.height)}get bearing(){return di(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;this.angle!==t&&(this._unmodified=!1,this.angle=t,this._calcMatrices(),this.rotationMatrix=Vi(),Hi(this.rotationMatrix,this.rotationMatrix,this.angle))}get pitch(){return this._pitch/Math.PI*180}set pitch(e){const t=Fe(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=Ee(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 averageElevation(){return this._averageElevation}set averageElevation(e){this._averageElevation=e,this._calcFogMatrices(),this._distanceTileDataCache={}}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 o=0,s=0;for(let n=0;n<t.length;n++){const a=new r(t[n][0]*this.width,i+t[n][1]*(this.height-i)),l=e.pointCoordinate(a);if(!l)continue;const c=1/Math.hypot(l[0]-this._camera.position[0],l[1]-this._camera.position[1]);o+=l[3]*c,s+=c}return 0===s?NaN:o/s}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,o=this._mercatorZfromZoom(e),s=this._mercatorZfromZoom(this._maxZoom),r=Math.max(o-i,s);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,o=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)&&!o}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 o=ge(Le([],this._camera.position,i));return Fe(this._zoomFromMercatorZ(o),this._minZoom,this._maxZoom)}setFreeCameraOptions(e){if(!this.height)return;if(!e.position&&!e.orientation)return;this._updateCameraState();let t=!1;if(e.orientation&&!qi(e.orientation,this._camera.orientation)&&(t=this._setCameraOrientation(e.orientation)),e.position){const i=[e.position.x,e.position.y,e.position.z];Zi(i,this._camera.position)||(this._setCameraPosition(i),t=!0)}t&&(this._updateStateFromCamera(),this.recenterOnTerrain())}getFreeCameraOptions(){this._updateCameraState();const e=this._camera.position,t=new yh;return t.position=new pe(e[0],e[1],e[2]),t.orientation=this._camera.orientation,t._elevation=this.elevation,t._renderWorldCopies=this.renderWorldCopies,t}_setCameraOrientation(e){if(!Wi(e))return!1;$i(e,e);const t=Xi([],[0,0,-1],e),i=Xi([],[0,-1,0],e);if(i[2]<0)return!1;const o=vh(t,i);return!!o&&(this._camera.orientation=o,!0)}_setCameraPosition(e){const t=this.zoomScale(this.minZoom)*this.tileSize,i=this.zoomScale(this.maxZoom)*this.tileSize,o=this.cameraToCenterDistance;e[2]=Fe(e[2],o/i,o/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 Yi(0,e)];if(this.renderWorldCopies){const i=this.pointCoordinate(new r(0,0)),o=this.pointCoordinate(new r(this.width,0)),s=this.pointCoordinate(new r(this.width,this.height)),n=this.pointCoordinate(new r(0,this.height)),a=Math.floor(Math.min(i.x,o.x,s.x,n.x)),l=Math.floor(Math.max(i.x,o.x,s.x,n.x)),c=1;for(let i=a-c;i<=l+c;i++)0!==i&&t.push(new Yi(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,o){let s=[];const r=null!=i,n=!r;if(n&&this.zoom<t)return s;if(r&&0===i[0]&&0===i[1])return s;const a=new Set,l=(e,t,i,o,r)=>{const n=Eo(t,e,i,o,r);a.has(n)||(s.push(new Ke(e,t,i,o,r)),a.add(n))};for(let s=0;s<e.length;s++){const a=e[s];if(n&&a.canonical.z!==t)continue;if(r&&void 0!==o&&o>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 s)s.some((t=>e.isChildOf(t)))||c.push(e);if(s=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()),o=[e*i.x,e*i.y],r=4,n=r*r;s=s.filter((e=>{const t=e.canonical.x+.5-o[0],i=e.canonical.y+.5-o[1];return t*t+i*i<n}))}return s}extendTileCoverToNearPlane(e,t,i){const o=[],s=new Set;for(const t of e)s.add(t.key);const n=(e,t,i,r,n)=>{const a=Eo(t,e,i,r,n);s.has(a)||(o.push(new Ke(e,t,i,r,n)),s.add(a))},a=e.reduce(((e,t)=>Math.max(e,t.overscaledZ)),i),l=1<<i,c=[new r(0,0),new r(we,0),new r(we,we),new r(0,we)],h=new r(0,0),d=new r(0,0),u=(e,t)=>{const o=Math.floor(e[0]),s=Math.floor(e[1]),r=(e[0]-o)*we,u=(e[1]-s)*we,_=Math.floor(t[0]),p=Math.floor(t[1]),f=(t[0]-_)*we,m=(t[1]-p)*we;for(let e=-1;e<=1;e++){const t=o+e;if(!(t<0||t>=l)){h.x=r-e*we,d.x=f-(t-_)*we;for(let e=-1;e<=1;e++){const o=s+e;h.y=u-e*we,d.y=m-(o-p)*we,So(h,d,c)&&n(a,0,i,t,o)}}}},_=t.points,p=_[Io],f=_[Co],m=this._projectToGround(p,_[Ki]),g=this._projectToGround(f,_[Qi]);return u(p,m),u(f,g),o}_projectToGround(e,t){return Ji(eo(),e,t,e[2]/(e[2]-t[2]))}coveringTiles(e){let t=this.coveringZoomLevel(e);const i=t,o=this.elevation&&this.elevation.exaggeration(),s=o&&!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=to.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,t,d),_=h?this._camera.mercatorPosition:this.pointCoordinate(this.getCameraPoint()),p=l*zi(1,this.center.lat),f=this._camera.position[2]/zi(1,this.center.lat),m=[l*_.x,l*_.y,f*(d?1:p)],g=h||o,v=this.cameraToCenterDistance/e.tileSize*(e.roundZoom?1:.502),y=this.isLODDisabled(!0)?t:0;let x;if(this._elevation&&e.isTerrainDEM)x=1e4*this._elevation.exaggeration();else if(this._elevation){const e=this._elevation.getMinMaxForVisibleTiles();x=e?e.max:this._centerAltitude}else x=this._centerAltitude;const b=e.isTerrainDEM?-x:this._elevation?this._elevation.getMinElevationBelowMSL():0,w=this.projection.isReprojectedInTileSpace?io(this):1,T=e=>{const t=1/4e4,i=new pe(e.x+t,e.y,e.z),o=new pe(e.x,e.y+t,e.z),s=e.toLngLat(),r=i.toLngLat(),n=o.toLngLat(),a=this.locationCoordinate(s),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)*w/t},E=e=>{const t=x,i=b;return{aabb:ro(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 I=[];const C=t,R=e.reparseOverscaled?i:t,A=(f-this._centerAltitude)*p,D=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=O(e),e.shouldSplit||(i.min[2]=i.max[2]=i.center[2]=this._centerAltitude))},L=(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)},O=e=>{if(e.zoom<y)return!0;if(e.zoom===C)return!1;if(null!=e.shouldSplit)return e.shouldSplit;const t=e.aabb.distanceX(m),o=e.aabb.distanceY(m);let n=A,l=1;if(h){n=e.aabb.distanceZ(m);const t=Math.pow(2,e.zoom),i=ct((e.y+1)/t),o=ct(e.y/t),s=Math.min(Math.max(a,i),o),r=Oo(s)/Oo(a);if(l=s===a?1/Math.max(1,this._mercatorScaleRatio-.3):Math.min(1,r/this._mercatorScaleRatio),this.zoom<=Ro&&e.zoom===C-1&&r>=.9)return!0}else if(s&&(n=e.aabb.distanceZ(m)*p),this.projection.isReprojectedInTileSpace&&i<=5){const t=Math.pow(2,e.zoom),i=T(new pe((e.x+.5)/t,(e.y+.5)/t));l=i>.85?1:i}if(!r&&!h){const i=Math.sqrt(t*t+o*o+n*n);let s=(1<<C-e.zoom)*v*l;return s*=L(Math.max(n,A),i),i<s}let d=Number.MAX_VALUE,u=0;const _=e.aabb.getCorners(),f=[];for(const e of _){Le(f,e,m),h||(s?f[2]*=p:f[2]=A);const t=ni(f,this._camera.forward());t<d&&(d=t,u=Math.abs(f[2]))}let g=(1<<C-e.zoom)*v*l;if(g*=L(Math.max(u,A),d),d<g)return!0;const x=e.aabb.closestPoint(c);return x[0]===c[0]&&x[1]===c[1]};if(this.renderWorldCopies)for(let e=1;e<=3;e++)S.push(E(-e)),S.push(E(e));for(S.push(E(0));S.length>0;){const i=S.pop(),o=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 oo(i.zoom,o,n);e=so(this,l,t,!0).intersects(u)}if(0===e)continue;a=2===e}if(i.zoom!==C&&O(i))for(let e=0;e<4;e++){const t=(o<<1)+e%2,c=(n<<1)+(e>>1),d={aabb:r?i.aabb.quadrant(e):ro(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};s&&!h&&(d.tileID=new Ke(i.zoom+1===C?R:i.zoom+1,i.wrap,i.zoom+1,t,c),D(d)),S.push(d)}else{const s=i.zoom===C?R:i.zoom;if(e.minzoom&&e.minzoom>s)continue;let r=0;if(!a){let t=g?i.aabb.intersectsPrecise(u):i.aabb.intersectsPreciseFlat(u);if(0===t&&d()){const e=new oo(i.zoom,o,n);t=so(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+o+(i.wrap<<i.zoom))*(1<<t-i.zoom),_=c[1]-.5-n,p=i.tileID?i.tileID:new Ke(s,i.wrap,i.zoom,o,n);e.calculateQuadrantVisibility&&(p.visibleQuadrants=r),I.push({tileID:p,distanceSq:h*h+_*_})}}if(this.fogCullDistSq){const t=this.fogCullDistSq,i=this.horizonLineFromTop();I=I.filter((o=>{const s=[0,0,0,1],r=[we,we,0,1],n=this.calculateFogTileMatrix(o.tileID.toUnwrapped());ke(s,s,n),ke(r,r,n);const a=no([],s,r),l=ao([],s,r),c=Ao(a,l);if(0===c)return!0;let h=!1;const d=this._elevation;if(d&&c>t&&0!==i){const t=this.calculateProjMatrix(o.tileID.toUnwrapped());let s;e.isTerrainDEM||(s=d.getMinMaxForTile(o.tileID)),s||(s={min:b,max:x});const r=Do(this.rotation),n=[r[0]*we,r[1]*we,s.max];fe(n,n,t),h=(1-n[1])*this.height*.5<i}return c<t||h}))}return I.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=Fe(e.lat,-uo,uo),i=this.projection.project(e.lng,t);return new r(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/zi(1,this.center.lat)/this.worldSize}setLocationAtPoint(e,t){let i,o;const s=this.centerPoint;if("globe"===this.projection.name){const e=this.worldSize;i=(t.x-s.x)/e,o=(t.y-s.y)/e}else{const e=this.pointCoordinate(t),r=this.pointCoordinate(s);i=e.x-r.x,o=e.y-r.y}const r=this.locationCoordinate(e);this.setLocation(new pe(r.x-i,r.y-o))}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?zi(t,e.lat):void 0,o=this.projection.project(e.lng,e.lat);return new pe(o.x,o.y,i)}coordinateLocation(e){return this.projection.unproject(e.x,e.y)}pointRayIntersection(e,t){const i=null!=t?t:this._centerAltitude,o=[e.x,e.y,0,1],s=[e.x,e.y,1,1];ke(o,o,this.pixelMatrixInverse),ke(s,s,this.pixelMatrixInverse);const r=s[3];lo(o,o,1/o[3]),lo(s,s,1/r);const n=o[2],a=s[2];return{p0:o,p1:s,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 ke(t,t,this.pixelMatrixInverse),ke(i,i,this.pixelMatrixInverse),lo(t,t,1/t[3]),lo(i,i,1/i[3]),t[2]=zi(t[2],this._center.lat)*this.worldSize,i[2]=zi(i[2],this._center.lat)*this.worldSize,lo(t,t,1/this.worldSize),lo(i,i,1/this.worldSize),new Pe([t[0],t[1],t[2]],Oe([],Le([],i,t)))}rayIntersectionCoordinate(e){const{p0:t,p1:i,t:o}=e,s=zi(t[2],this._center.lat),r=zi(i[2],this._center.lat);return new pe(xe(t[0],i[0],o)/this.worldSize,xe(t[1],i[1],o)/this.worldSize,xe(s,r,o))}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 pe(i[0],i[1],i[2]);let o=0,s=this.horizonLineFromTop();if(e.y>s)return this.pointCoordinate(e,t);const r=.02*s,n=e.clone();for(let e=0;e<10&&s-o>r;e++){n.y=xe(o,s,.66);const e=this.projection.pointCoordinate3D(this,n.x,n.y);e?(s=n.y,i=e):o=n.y}return i?new pe(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>=co)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,o=[e.x*this.worldSize,e.y*this.worldSize,i+e.toAltitude(),1];return ke(o,o,this.pixelMatrix),o[3]>0?new r(o[0]/o[3],o[1]/o[3]):new r(Number.MAX_VALUE,Number.MAX_VALUE)}_getBoundsNonRectangular(){const{top:e,left:t}=this._edgeInsets,i=this.height-this._edgeInsets.bottom,o=this.width-this._edgeInsets.right,s=this.pointLocation3D(new r(t,e)),n=this.pointLocation3D(new r(o,e)),a=this.pointLocation3D(new r(o,i)),l=this.pointLocation3D(new r(t,i));let c=Math.min(s.lng,n.lng,a.lng,l.lng),h=Math.max(s.lng,n.lng,a.lng,l.lng),d=Math.min(s.lat,n.lat,a.lat,l.lat),u=Math.max(s.lat,n.lat,a.lat,l.lat);const _=Math.pow(2,-this.zoom)/16*270,p="globe"===this.projection.name?1:4,f=(e,t,i,o,s)=>{const n=(e+i)/2,a=(t+o)/2,l=new r(n,a),{lng:m,lat:g}=this.pointLocation3D(l),v=Math.max(0,c-m,d-g,m-h,g-u);c=Math.min(c,m),h=Math.max(h,m),d=Math.min(d,g),u=Math.max(u,g),(s<p||v>_)&&(f(e,t,n,a,s+1),f(n,a,i,o,s+1))};if(f(t,e,o,e,1),f(o,e,o,i,1),f(o,i,t,i,1),f(t,i,t,e,1),"globe"===this.projection.name){const[e,t]=ho(this);e?(u=90,h=180,c=-180):t&&(d=-90,h=180,c=-180)}return new He(new tt(c,d),new tt(h,u))}_getBoundsRectangular(e,t){const{top:i,left:o}=this._edgeInsets,s=this.height-this._edgeInsets.bottom,n=this.width-this._edgeInsets.right,a=new r(o,i),l=new r(n,i),c=new r(n,s),h=new r(o,s);let d=this.pointCoordinate(a,e),u=this.pointCoordinate(l,e);const _=this.pointCoordinate(c,t),p=this.pointCoordinate(h,t),f=(e,t)=>(t.y-e.y)/(t.x-e.x);return d.y>1&&u.y>=0?d=new pe((1-p.y)/f(p,d)+p.x,1):d.y<0&&u.y<=1&&(d=new pe(-p.y/f(p,d)+p.x,0)),u.y>1&&d.y>=0?u=new pe((1-_.y)/f(_,u)+_.x,1):u.y<0&&d.y<=1&&(u=new pe(-_.y/f(_,u)+_.x,0)),(new He).extend(this.coordinateLocation(d)).extend(this.coordinateLocation(u)).extend(this.coordinateLocation(p)).extend(this.coordinateLocation(_))}_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=-uo,this.maxLat=uo,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=Ge(this.minLng)*this.tileSize,this.worldMaxX=Ge(this.maxLng)*this.tileSize,this.worldMinY=qe(this.maxLat)*this.tileSize,this.worldMaxY=qe(this.minLat)*this.tileSize,this._constrain()}calculatePosMatrix(e,t){return this.projection.createTileMatrix(this,t,e)}calculateDistanceTileData(e){const t=e.key,i=this._distanceTileDataCache;if(i[t])return i[t];const o=e.canonical,s=1/this.height,r=this.cameraWorldSize,n=r/this.zoomScale(o.z),a=(o.x+Math.pow(2,o.z)*e.wrap)*n,l=o.y*n,c=this.point;c.x*=r/this.worldSize,c.y*=r/this.worldSize;const h=this.angle,d=Math.sin(-h),u=-Math.cos(-h);return i[t]={bearing:[d,u],center:[(c.x-a)*s,(c.y-l)*s],scale:n/we*s},i[t]}calculateFogTileMatrix(e){const t=e.key,i=this._fogTileMatrixCache;if(i[t])return i[t];const o=this.projection.createTileMatrix(this,this.cameraWorldSizeForFog,e);return Be(o,this.worldToFogMatrix,o),i[t]=new Float32Array(o),i[t]}calculateProjMatrix(e,t=!1,i=!1){const o=e.key;let s;if(s=i?this._expandedProjMatrixCache:t?this._alignedProjMatrixCache:this._projMatrixCache,s[o])return s[o];const r=this.calculatePosMatrix(e,this.worldSize);let n;return n=this.projection.isReprojectedInTileSpace?this.mercatorMatrix:i?this.expandedFarZProjMatrix:t?this.alignedProjMatrix:this.projMatrix,Be(r,n,r),s[o]=new Float32Array(r),s[o]}calculatePixelsToTileUnitsMatrix(e){const t=e.tileID.key,i=this._pixelsToTileUnitsCache;if(i[t])return i[t];const o=_o(e,this);return i[t]=o,i[t]}customLayerMatrix(){return this.mercatorMatrix.slice()}globeToMercatorMatrix(){if("globe"===this.projection.name){const e=1/this.worldSize,t=Ft([],[e,e,e]);return Be(t,t,this.globeMatrix),t}}recenterOnTerrain(){if(!this._elevation||"globe"===this.projection.name)return;const e=this._elevation;this._updateCameraState();const t=zi(1,this._center.lat)*this.worldSize,i=this._computeCameraPosition(t),o=this._camera.forward(),s=zi(1,this._center.lat);i[2]/=s,o[2]/=s,Oe(o,o);const r=e.raycast(i,o,e.exaggeration());if(r){const e=Jt([],i,o,r),t=new pe(e[0],e[1],zi(e[2],ct(e[1]))),n=(t.z+ge([t.x-i[0],t.y-i[1],t.z-i[2]*s]))*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=zi(1,this._center.lat)*this.worldSize,o=this._computeCameraPosition(i),s=t.getAtPointOrZero(new pe(...o)),r=this.pixelsPerMeter/this.worldSize*s,n=this._minimumHeightOverTerrain(),a=o[2]-r;if(a<=n)if(a<0||e){const e=this.locationCoordinate(this._center,this._centerAltitude),t=[o[0],o[1],e.z-o[2]],i=ge(t);t[2]-=(n-a)/this._pixelsPerMercatorPixel;const s=ge(t);if(0===s)return;Si(t,t,i/s*this._pixelsPerMercatorPixel),this._camera.position=[o[0],o[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=Fe(t.lat,this.minLat,this.maxLat),(this.maxBounds||!this.renderWorldCopies&&!e)&&(t.lng=Fe(t.lng,this.minLng,this.maxLng)),this.center=t,void(this._constraining=!1)}const t=this._unmodified,{x:i,y:o}=this.point;let s=0,n=i,a=o;const l=this.width/2,c=this.height/2,h=this.worldMinY*this.scale,d=this.worldMaxY*this.scale;if(o-c<h&&(a=h+c),o+c>d&&(a=d-c),d-h<this.height&&(s=Math.max(s,this.height/(d-h)),a=(d+h)/2),this.maxBounds||!this._renderWorldCopies||!this.projection.wrap){const e=this.worldMinX*this.scale,t=this.worldMaxX*this.scale,o=this.worldSize/2-(e+t)/2;n=(i+o+this.worldSize)%this.worldSize-o,n-l<e&&(n=e+l),n+l>t&&(n=t-l),t-e<this.width&&(s=Math.max(s,this.width/(t-e)),n=(t+e)/2)}n===i&&a===o||this._allowWorldUnderZoom||(this.center=this.unproject(new r(n,a))),s&&!this._allowWorldUnderZoom&&(this.zoom+=this.scaleZoom(s)),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=zi(1,this.center.lat)/zi(1,Po));const o=po(this.projection,this.zoom,this.width,this.height,1024);this._pixelsPerMercatorPixel=this.projection.pixelSpaceConversion(this.center.lat,this.worldSize,o),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 s="meters"===this.projection.zAxisUnit?i:1,r=this._camera.getWorldToCamera(this.worldSize,s);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,o=-i,s=-t;i-=e.x,o-=e.x,t+=e.y,s+=e.y,n=this._camera.getCameraToClipOrthographic(o,i,s,t,this._nearZ,this._farZ),((e,t,i,o)=>{for(let s=0;s<16;s++)e[s]=xe(t[s],i[s],o)})(n,n,a,Lo(this.pitch>=Th?1:this.pitch/Th))}else n=a;const l=fo([],a,r);let c=fo([],n,r);if(this.projection.isReprojectedInTileSpace){const e=this.locationCoordinate(this.center),t=Zt([]);Bt(t,t,[e.x*this.worldSize,e.y*this.worldSize,0]),Be(t,t,mo(this)),Bt(t,t,[-e.x*this.worldSize,-e.y*this.worldSize,0]),Be(c,c,t),Be(l,l,t),this.inverseAdjustmentMatrix=go(this)}else this.inverseAdjustmentMatrix=[1,0,0,1];if(this.mercatorMatrix=vo([],c,[this.worldSize,this.worldSize,this.worldSize/s,1]),this.projMatrix=c,this.invProjMatrix=Lt(new Float64Array(16),this.projMatrix),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,this.expandedFarZProjMatrix=fo([],t,r)}else this.expandedFarZProjMatrix=this.projMatrix;const h=Lt([],n);this.frustumCorners=yo.fromInvProjectionMatrix(h,this.horizonLineFromTop(),this.height),this.cameraFrustum=to.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,0,!t);const d=new Float32Array(16);Zt(d),vo(d,d,[1,-1,1]),xo(d,d,this._pitch),Wt(d,d,this.angle);const u=Pi(new Float32Array(16),this._fov,this.width/this.height,this._nearZ,this._farZ);this.starsProjMatrix=qt(u);const _=(Math.PI/2-this._pitch)*(this.height/this._fov)*this._horizonShift;u[8]=2*-e.x/this.width,u[9]=2*(e.y+_)/this.height,this.skyboxMatrix=Be(d,u,d);const p=this.point,f=p.x,m=p.y,g=this.width%2/2,v=this.height%2/2,y=Math.cos(this.angle),x=Math.sin(this.angle),b=f-Math.round(f)+y*g+x*v,w=m-Math.round(m)+y*v+x*g,T=new Float64Array(c);if(Bt(T,T,[b>.5?b-1:b,w>.5?w-1:w,0]),this.alignedProjMatrix=T,c=$t(),vo(c,c,[this.width/2,-this.height/2,1]),Bt(c,c,[1,-1,0]),this.labelPlaneMatrix=c,c=$t(),vo(c,c,[1,-1,1]),Bt(c,c,[-1,-1,0]),vo(c,c,[2/this.width,2/this.height,1]),this.glCoordMatrix=c,this.pixelMatrix=Be(new Float64Array(16),this.labelPlaneMatrix,l),this._calcFogMatrices(),this._distanceTileDataCache={},c=Lt(new Float64Array(16),this.pixelMatrix),!c)throw new Error("failed to invert matrix");if(this.pixelMatrixInverse=c,"globe"===this.projection.name||this.mercatorFromTransition){this.globeMatrix=bo(this);const e=[this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]];this.globeCenterInViewSpace=fe(e,e,r),this.globeRadius=this.worldSize/2/Math.PI-1}else this.globeMatrix=c;this._projMatrixCache={},this._alignedProjMatrixCache={},this._pixelsToTileUnitsCache={},this._expandedProjMatrixCache={}}_calcFogMatrices(){this._fogTileMatrixCache={};const e=this.cameraWorldSizeForFog,t=this.cameraPixelsPerMeter,i=this._camera.position,o=1/this.height/this._pixelsPerMercatorPixel,s=[e,e,t];Si(s,s,o),Si(i,i,-1),wo(i,i,s);const r=$t();Bt(r,r,i),vo(r,r,s),this.mercatorFogMatrix=r,this.worldToFogMatrix=this._camera.getWorldToCameraPosition(e,t,o)}_computeCameraPosition(e){const t=(e=e||this.pixelsPerMeter)/this.pixelsPerMeter,i=this._camera.forward(),o=this.point,s=this._mercatorZfromZoom(this._seaLevelZoom?this._seaLevelZoom:this._zoom)*t-e/this.worldSize*this._centerAltitude;return[o.x/this.worldSize-i[0]*s,o.y/this.worldSize-i[1]*s,e/this.worldSize*this._centerAltitude-i[2]*s]}_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],o=e[2];let s=1;this.projection.wrap&&(this.center=this.center.wrap()),o>0&&(s=Math.min((t-i)/o,1)),this._camera.position=Jt([],this._camera.position,e,s),this._updateStateFromCamera()}_updateStateFromCamera(){const e=this._camera.position,t=this._camera.forward(),{pitch:i,bearing:o}=this._camera.getPitchBearing(),s=zi(this._centerAltitude,this.center.lat)*this._pixelsPerMercatorPixel,r=this._mercatorZfromZoom(this._maxZoom)*Math.cos(Ee(this._maxPitch)),n=Math.max((e[2]-s)/Math.cos(i),r),a=this._zoomFromMercatorZ(n);Jt(e,e,t,n),this._pitch=Fe(i,Ee(this.minPitch),Ee(this.maxPitch)),this.angle=di(o,-Math.PI,Math.PI),this._setZoom(Fe(a,this._minZoom,this._maxZoom)),this._updateSeaLevelZoom(),this._center=this.coordinateLocation(new pe(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(null!=this._seaLevelZoom?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=co,o=0,s=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<s&&(s=c,o=r),r<l?t=r:i=r}return o}_terrainEnabled(){return!(!this._elevation||!this.projection.supportsTerrain&&(u("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),o=Math.max(e.x,t.x),s=Math.min(e.y,t.y),n=Math.max(e.y,t.y);if(s<this.horizonLineFromTop(!1))return!0;if("mercator"!==this.projection.name)return!1;const a=[new r(i,s),new r(o,n),new r(i,n),new r(o,s)],l=this.renderWorldCopies?-3:0,c=this.renderWorldCopies?4:1;for(const e of a){const t=this.pointRayIntersection(e);if(t.t<0)return!0;const i=this.rayIntersectionCoordinate(t);if(i.x<l||i.y<0||i.x>c||i.y>1)return!0}return!1}isHorizonVisible(){return this.pitch+To(this.fovAboveCenter)>88||this.anyCornerOffEdge(new r(0,0),new r(this.width,this.height))}zoomDeltaToMovement(e,t){const i=ge(Le([],this._camera.position,e)),o=this._zoomFromMercatorZ(i)+t;return i-this._mercatorZfromZoom(o)}getCameraPoint(){if("globe"===this.projection.name){const e=function([e,t,i],o){const s=[e,t,i,1];ke(s,s,o);const r=s[3]=Math.max(s[3],1e-6);return s[0]/=r,s[1]/=r,s[2]/=r,s}([this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]],this.pixelMatrix);return new r(e[0],e[1])}{const e=Math.tan(this._pitch)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new r(0,e))}}getCameraToCenterDistance(e,t=this.zoom,i=this.worldSize){const o=po(e,t,this.width,this.height,1024),s=e.pixelSpaceConversion(this.center.lat,i,o);let r=.5/Math.tan(.5*this._fov)*this.height*s;return this.isOrthographic&&(r=xe(1,r,Lo(this.pitch>=Th?1:this.pitch/Th))),r}getWorldToCameraMatrix(){const e=this._camera.getWorldToCamera(this.worldSize,"meters"===this.projection.zAxisUnit?this.pixelsPerMeter:1);return"globe"===this.projection.name&&Be(e,e,this.globeMatrix),e}getFrustum(e){return to.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,e,"meters"===this.projection.zAxisUnit)}}const Sh=(e,t)=>{if(t>0&&e.terrain&&u("Cutoff is currently disabled on terrain"),t<=0||e.terrain)return{shouldRenderCutoff:!1,uniformValues:{u_cutoff_params:[0,0,0,1]}};const i=e.transform,o=Math.max(Math.abs(i._zoom-(e.minCutoffZoom-1)),1),s=i.isLODDisabled(!1)?me(60,45,i.pitch):me(30,15,i.pitch),r=i._farZ-i._nearZ,n=t*i.height,a=((1-(l=s))*i.cameraToCenterDistance+l*(i._farZ+n))*o;var l;return{shouldRenderCutoff:s<1,uniformValues:{u_cutoff_params:[i._nearZ,i._farZ,(a-i._nearZ)/r,(a-n-i._nearZ)/r]}}},Ih=2048;class Ch{constructor(e,t){this.aabb=e,this.lastCascade=t}}class Rh{add(e,t){const i=this.receivers[e.key];void 0!==i?(i.aabb.min[0]=Math.min(i.aabb.min[0],t.min[0]),i.aabb.min[1]=Math.min(i.aabb.min[1],t.min[1]),i.aabb.min[2]=Math.min(i.aabb.min[2],t.min[2]),i.aabb.max[0]=Math.max(i.aabb.max[0],t.max[0]),i.aabb.max[1]=Math.max(i.aabb.max[1],t.max[1]),i.aabb.max[2]=Math.max(i.aabb.max[2],t.max[2])):this.receivers[e.key]=new Ch(t,null)}clear(){this.receivers={}}get(e){return this.receivers[e.key]}computeRequiredCascades(e,t,i){const o=No.fromPoints(e.points);let s=0;for(const e in this.receivers){const r=this.receivers[e];if(!r)continue;if(!o.intersectsAabb(r.aabb))continue;r.aabb.min=o.closestPoint(r.aabb.min),r.aabb.max=o.closestPoint(r.aabb.max);const n=r.aabb.getCorners();for(let e=0;e<i.length;e++){let o=!0;for(const s of n){const r=[s[0]*t,s[1]*t,s[2]];if(fe(r,r,i[e].matrix),r[0]<-1||r[0]>1||r[1]<-1||r[1]>1){o=!1;break}}if(r.lastCascade=e,s=Math.max(s,e),o)break}}return s+1}}class Ah{constructor(e){this.painter=e,this._enabled=!1,this._shadowLayerCount=0,this._numCascadesToRender=0,this._cascades=[],this._groundShadowTiles=[],this._receivers=new Rh,this._depthMode=new hh(e.context.gl.LEQUAL,hh.ReadWrite,[0,1]),this._uniformValues={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},this._forceDisable=!1,this.useNormalOffset=!1}destroy(){for(const e of this._cascades)e.texture.destroy(),e.framebuffer.destroy();this._cascades=[]}updateShadowParameters(e,t){const i=this.painter;if(this._enabled=!1,this._shadowLayerCount=0,this._receivers.clear(),!t||!t.properties)return;const o=t.properties.get("shadow-intensity");if(!t.shadowsEnabled()||o<=0)return;if(this._shadowLayerCount=i.style.order.reduce(((t,o)=>{const s=i.style._mergedLayers[o];return t+(s.hasShadowPass()&&!s.isHidden(e.zoom)?1:0)}),0),this._enabled=this._shadowLayerCount>0,!this.enabled)return;const s=i.context,r=Ih,n=Ih;if(0===this._cascades.length||Ih!==this._cascades[0].texture.size[0]){this._cascades=[];for(let e=0;e<2;++e){const e=i._shadowMapDebug,t=s.gl,o=s.createFramebuffer(r,n,e?1:0,"texture"),a=new z(s,{width:r,height:n,data:null},t.DEPTH_COMPONENT16);if(o.depthAttachment.set(a.texture),e){const e=new z(s,{width:r,height:n,data:null},t.RGBA8);o.colorAttachment0.set(e.texture)}this._cascades.push({framebuffer:o,texture:a,matrix:[],far:0,boundingSphereRadius:0,frustum:new to,scale:0})}}this.shadowDirection=Lh(t);let a=0;if(e.elevation){const t=e.elevation,i=[1e4,-1e4];t.visibleDemTiles.filter((e=>e.dem)).forEach((e=>{const t=e.dem.tree;i[0]=Math.min(i[0],t.minimums[0]),i[1]=Math.max(i[1],t.maximums[0])})),1e4!==i[0]&&(a=(i[1]-i[0])*t.exaggeration())}const l=1.5*e.cameraToCenterDistance,c=3*l,h=new Float64Array(16);for(let t=0;t<this._cascades.length;++t){const i=this._cascades[t];let o=e.height/50,s=1;0===t?s=l:(o=l,s=c);const[r,n]=Ph(e,this.shadowDirection,o,s,Ih,a);i.scale=e.scale,i.matrix=r,i.boundingSphereRadius=n,Lt(h,i.matrix),i.frustum=to.fromInvProjectionMatrix(h,1,0,!0),i.far=s}const d=this._cascades.length-1;this._uniformValues.u_fade_range=[.75*this._cascades[d].far,this._cascades[d].far],this._uniformValues.u_shadow_intensity=o,this._uniformValues.u_shadow_direction=[this.shadowDirection[0],this.shadowDirection[1],this.shadowDirection[2]],this._uniformValues.u_shadow_texel_size=.00048828125,this._uniformValues.u_shadow_map_resolution=Ih,this._uniformValues.u_shadowmap_0=bh.ShadowMap0,this._uniformValues.u_shadowmap_1=bh.ShadowMap0+1,this._groundShadowTiles=i.transform.coveringTiles({tileSize:512,renderWorldCopies:!0});const u=i.transform.elevation;for(const e of this._groundShadowTiles){let t={min:0,max:0};if(u){const i=u.getMinMaxForTile(e);i&&(t=i)}this.addShadowReceiver(e.toUnwrapped(),t.min,t.max)}}get enabled(){return this._enabled&&!this._forceDisable}set enabled(e){this._enabled=e}drawShadowPass(e,t){if(!this.enabled)return;const i=this.painter,o=i.context;this._numCascadesToRender=this._receivers.computeRequiredCascades(i.transform.getFrustum(0),i.transform.worldSize,this._cascades),o.viewport.set([0,0,Ih,Ih]);for(let s=0;s<this._numCascadesToRender;++s){i.currentShadowCascade=s,o.bindFramebuffer.set(this._cascades[s].framebuffer.framebuffer),o.clear({color:Te.white,depth:1});for(const o of e.order){const s=e._mergedLayers[o];if(!s.hasShadowPass()||s.isHidden(i.transform.zoom))continue;const r=e.getLayerSourceCache(s),n=r?t[r.id]:void 0;("model"===s.type||n&&n.length)&&i.renderLayer(i,r,s,n)}}i.currentShadowCascade=0}drawGroundShadows(){if(!this.enabled)return;const e=this.painter,t=e.style,i=e.context,o=i.gl,s=t.directionalLight,r=t.ambientLight;if(!s||!r)return;const n=[],a=Sh(e,e.longestCutoffRange);a.shouldRenderCutoff&&n.push("RENDER_CUTOFF"),n.push("RENDER_SHADOWS","DEPTH_TEXTURE"),this.useNormalOffset&&n.push("NORMAL_OFFSET");const l=Oh(t,s,r),c=new hh(o.LEQUAL,hh.ReadOnly,e.depthRangeFor3D),h=new uh({func:o.EQUAL,mask:255},0,255,o.KEEP,o.KEEP,o.KEEP);for(const t of this._groundShadowTiles){const s=t.toUnwrapped(),r=e.isTileAffectedByFog(t),d=e.getOrCreateProgram("groundShadow",{defines:n,overrideFog:r});this.setupShadows(s,d),e.uploadCommonUniforms(i,d,s,null,a);const u={u_matrix:e.transform.calculateProjMatrix(s),u_ground_shadow_factor:l};d.draw(e,o.TRIANGLES,c,h,ch.multiply,fh.disabled,u,"ground_shadow",e.tileExtentBuffer,e.quadTriangleIndexBuffer,e.tileExtentSegments,null,e.transform.zoom,null,null)}}getShadowPassColorMode(){return this.painter._shadowMapDebug?ch.unblended:ch.disabled}getShadowPassDepthMode(){return this._depthMode}getShadowCastingLayerCount(){return this._shadowLayerCount}calculateShadowPassMatrixFromTile(e){const t=this.painter.transform,i=t.calculatePosMatrix(e,t.worldSize);return Be(i,this._cascades[this.painter.currentShadowCascade].matrix,i),Float32Array.from(i)}calculateShadowPassMatrixFromMatrix(e){const t=qt(e);return Be(t,this._cascades[this.painter.currentShadowCascade].matrix,e),t}setupShadows(e,t,i){if(!this.enabled)return;const o=this.painter.transform,s=this.painter.context,r=s.gl,n=this._uniformValues,a=new Float64Array(16),l=o.calculatePosMatrix(e,o.worldSize);for(let e=0;e<this._cascades.length;e++)Be(a,this._cascades[e].matrix,l),n[0===e?"u_light_matrix_0":"u_light_matrix_1"]=Float32Array.from(a),s.activeTexture.set(r.TEXTURE0+bh.ShadowMap0+e),this._cascades[e].texture.bindExtraParam(r.LINEAR,r.LINEAR,r.CLAMP_TO_EDGE,r.CLAMP_TO_EDGE,r.GREATER);if(this.useNormalOffset=!!i,this.useNormalOffset){const t=Bo(e.canonical),s=2/o.tileSize*we/Ih,r=s*this._cascades[0].boundingSphereRadius,a=s*this._cascades[this._cascades.length-1].boundingSphereRadius,l=("vector-tile"===i?1:3)*function(e,t,i,o,s){const r=Fe((e-22)/-22,0,1);return.125*(1-r)+4*r}(o.zoom);n.u_shadow_normal_offset=[t,r*l,a*l],n.u_shadow_bias=[1e-4,.0012,.012]}else n.u_shadow_bias=[36e-5,.0012,.012];t.setShadowUniformValues(s,n)}setupShadowsFromMatrix(e,t,i=!1){if(!this.enabled)return;const o=this.painter.context,s=o.gl,r=this._uniformValues,n=new Float64Array(16);for(let t=0;t<2;t++)Be(n,this._cascades[t].matrix,e),r[0===t?"u_light_matrix_0":"u_light_matrix_1"]=Float32Array.from(n),o.activeTexture.set(s.TEXTURE0+bh.ShadowMap0+t),this._cascades[t].texture.bindExtraParam(s.LINEAR,s.LINEAR,s.CLAMP_TO_EDGE,s.CLAMP_TO_EDGE,s.GREATER);this.useNormalOffset=i,i?(r.u_shadow_normal_offset=[1,3,3],r.u_shadow_bias=[6e-5,.0012,.012]):r.u_shadow_bias=[36e-5,.0012,.012],t.setShadowUniformValues(o,r)}getShadowUniformValues(){return this._uniformValues}getCurrentCascadeFrustum(){return this._cascades[this.painter.currentShadowCascade].frustum}computeSimplifiedTileShadowVolume(e,t,i,o){if(o[2]>=0)return{};const s=function(e,t,i){const o=i/(1<<e.canonical.z);return new No([e.canonical.x*o+e.wrap*i,e.canonical.y*o+e.wrap*i,0],[(e.canonical.x+1)*o+e.wrap*i,(e.canonical.y+1)*o+e.wrap*i,t])}(e,t,i).getCorners(),r=t/-o[2];o[0]<0?(ko(s[0],s[0],[o[0]*r,0,0]),ko(s[3],s[3],[o[0]*r,0,0])):o[0]>0&&(ko(s[1],s[1],[o[0]*r,0,0]),ko(s[2],s[2],[o[0]*r,0,0])),o[1]<0?(ko(s[0],s[0],[0,o[1]*r,0]),ko(s[1],s[1],[0,o[1]*r,0])):o[1]>0&&(ko(s[2],s[2],[0,o[1]*r,0]),ko(s[3],s[3],[0,o[1]*r,0]));const n={};return n.vertices=s,n.planes=[Dh(s[1],s[0],s[4]),Dh(s[2],s[1],s[5]),Dh(s[3],s[2],s[6]),Dh(s[0],s[3],s[7])],n}addShadowReceiver(e,t,i){this._receivers.add(e,No.fromTileIdAndHeight(e,t,i))}getMaxCascadeForTile(e){const t=this._receivers.get(e);return t&&t.lastCascade?t.lastCascade:0}}function Dh(e,t,i){const o=Le([],i,t),s=Le([],e,t),r=ei([],o,s),n=ge(r);return 0===n?[0,0,1,0]:(Si(r,r,1/n),[r[0],r[1],r[2],-ni(r,t)])}function Lh(e){const t=e.properties.get("direction"),i=Go(t.x,t.y,t.z);i[2]=Fe(i[2],0,75);const o=Fo([i[0],i[1],i[2]]);return zo(o.x,o.y,o.z)}function Oh(e,t,i){const o="none"===t.properties.get("color-use-theme"),s=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(ni([0,0,1],a),0),u=[0,0,0];Si(u,c.toPremultipliedRenderColor(l?null:e.getLut(t.scope)).toArray01Linear().slice(0,3),h);const _=[0,0,0];return Si(_,s.toPremultipliedRenderColor(o?null:e.getLut(i.scope)).toArray01Linear().slice(0,3),d*r),jo([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 Ph(e,t,i,o,s,r){const n=e.zoom,a=e.scale,l=e.worldSize,c=1/l,h=e.aspect,d=Math.sqrt(1+h*h)*Math.tan(.5*e.fovX),u=d*d,_=o-i,p=o+i;let f,m;u>_/p?(f=o,m=o*d):(f=.5*p*(1+u),m=.5*Math.sqrt(_*_+2*(o*o+i*i)*u+p*p*u*u));const g=e.projection.pixelsPerMeter(e.center.lat,l),v=e._camera.getCameraToWorldMercator(),y=[0,0,-f*c];fe(y,y,v);let x=m*c;const b=e._edgeInsets;if(!(0===b.left&&0===b.top&&0===b.right&&0===b.bottom||b.left===b.right&&b.top===b.bottom)){const t=e._camera.getWorldToCamera(e.worldSize,"meters"===e.projection.zAxisUnit?g:1),s=e._camera.getCameraToClipPerspective(e._fov,e.width/e.height,i,o);s[8]=2*-e.centerOffset.x/e.width,s[9]=2*e.centerOffset.y/e.height;const r=new Float64Array(16);fo(r,s,t);const c=new Float64Array(16);Lt(c,r);const h=to.fromInvProjectionMatrix(c,l,n,!0);for(const t of h.points){const i=((w=t)[0]/=a,w[1]/=a,w[2]=zi(w[2],e._center.lat),w);x=Math.max(x,Ii(Uo([],y,i)))}}var w;x*=s/(s-1);const T=Math.acos(t[2]),E=Math.atan2(-t[0],-t[1]),S=new xh;S.position=y,S.setPitchBearing(T,E);const I=S.getWorldToCamera(l,g),C=x*l,R=Math.min(e._mercatorZfromZoom(17)*l*-2,-2*C),A=S.getCameraToClipOrthographic(-C,C,-C,C,R,(C+r*g)/t[2]),D=new Float64Array(16);Be(D,A,I);const L=zo(Math.floor(1e6*y[0])/1e6*l,Math.floor(1e6*y[1])/1e6*l,0),O=.5*s,P=[0,0,0];fe(P,L,D),Si(P,P,O);const M=[Math.floor(P[0]),Math.floor(P[1]),Math.floor(P[2])],z=[0,0,0];Le(z,P,M),Si(z,z,-1/O);const F=new Float64Array(16);return Zt(F),Bt(F,F,z),Be(D,F,D),[D,C]}class Mh extends E{constructor(e){super(),this.requestManager=e,this.models={"":{}},this.modelUris={"":{}},this.modelByURL={},this.numModelsLoading={}}loadModel(e,t){return Vo(this.requestManager.transformRequest(t,x.Model).url).then((i=>{if(!i)return;const o=Ho(i),s=new qo(e,t,void 0,void 0,o);return s.computeBoundsAndApplyParent(),s})).catch((i=>{if(i&&404===i.status)return null;this.fire(new A(new Error(`Could not load model ${e} from ${t}: ${i.message}`)))}))}load(e,t,i={forceReload:!1}){this.models[t]||(this.models[t]={});const o=Object.keys(e),s=[],r=[];for(const n of o){const o=e[n];this.hasURLBeenRequested(o)&&!i.forceReload||(this.modelByURL[o]={modelId:n,scope:t},s.push(this.loadModel(n,o)),r.push(n)),this.models[t][n]||(this.models[t][n]={model:null,numReferences:1})}this.numModelsLoading[t]=(this.numModelsLoading[t]||0)+r.length,Promise.allSettled(s).then((e=>{for(let i=0;i<e.length;i++){const{status:o}=e[i];if("rejected"===o)continue;const{value:s}=e[i];this.models[t][r[i]]||(this.models[t][r[i]]={model:null,numReferences:1}),this.models[t][r[i]].model=s}this.numModelsLoading[t]-=r.length,this.fire(new D("data",{dataType:"style"}))})).catch((e=>{this.fire(new A(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]={}),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]||{}}addModel(e,t,i){this.models[i]||(this.models[i]={}),this.modelUris[i]||(this.modelUris[i]={});const o=this.requestManager.normalizeModelURL(t);if((this.hasModel(e,i,{exactIdMatch:!0})||this.hasModelBeenAdded(e,i))&&this.modelUris[i][e]===o)this.models[i][e].numReferences++;else if(this.hasURLBeenRequested(o)){const{scope:e,modelId:t}=this.modelByURL[o];this.models[e][t].numReferences++}else this.modelUris[i][e]=o,this.load({[e]:this.modelUris[i][e]},i)}addModelURLs(e,t){this.models[t]||(this.models[t]={}),this.modelUris[t]||(this.modelUris[t]={});const i=this.modelUris[t];for(const t in 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]={}),this.modelUris[t]||(this.modelUris[t]={});const i={};for(const o of e)this.hasModel(o,t,{exactIdMatch:!0})||this.hasURLBeenRequested(o)?this.models[t][o].numReferences++:this.modelUris[t][o]&&!this.hasURLBeenRequested(o)?i[o]=this.modelUris[t][o]:!this.hasURLBeenRequested(o)&&Zo(o,!1)&&(this.modelUris[t][o]=this.requestManager.normalizeModelURL(o),i[o]=this.modelUris[t][o]);this.load(i,t)}hasURLBeenRequested(e){return void 0!==this.modelByURL[e]}removeModel(e,t,i=!1,o=!1){if(this.models[t]&&this.models[t][e]&&(this.models[t][e].numReferences--,0===this.models[t][e].numReferences||o)){const o=this.modelUris[t][e];i||delete this.modelUris[t][e],delete this.modelByURL[o];const s=this.models[t][e].model;if(!s)return;delete this.models[t][e],s.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={"":{}},this.modelUris={"":{}},this.modelByURL={},this.numModelsLoading={}}listModels(e){return this.models[e]||(this.models[e]={}),Object.keys(this.models[e])}upload(e,t){this.models[t]||(this.models[t]={});for(const i in this.models[t])this.models[t][i].model&&this.models[t][i].model.upload(e.context)}}const zh=ne.colorTheme,Fh=new ce({data:new he(zh.data)});function Bh(e){if(!e.metadata||!e.metadata.content_area)return;const t=w.devicePixelRatio,{left:i,top:o,width:s,height:r}=e.metadata.content_area,n=i*t,a=o*t;return[n,a,n+s*t,a+r*t]}function kh(e){if(e)return e.map((([e,t])=>[e*w.devicePixelRatio,t*w.devicePixelRatio]))}class Nh{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(!(i instanceof Al))return e;const o=t.map((e=>this.sourceCache.getTile(e))),s=i.getImages(o,Array.from(this.pendingRequests));for(const[t,i]of s)e.set(v.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 Uh=(e,t)=>Ka(e,t&&t.filter((e=>"source.canvas"!==e.identifier))),jh=Ve(sc,["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"]),Gh=Ve(sc,["setCenter","setZoom","setBearing","setPitch"]),Vh=new Set(["background","sky","slot","custom"]),Hh={version:8,layers:[],sources:{}},qh={duration:300,delay:0};class Zh extends E{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=Object.assign({},qh),this._buildingIndex=new tc(this),this.crossTileSymbolIndex=new ah,this._mergedOrder=[],this._drapedFirstOrder=[],this._mergedLayers={},this._mergedIndoor={},this._mergedSourceCaches={},this._mergedOtherSourceCaches={},this._mergedSymbolSourceCaches={},this._clipLayerPresent=!1,this._hasAppearances=!1,this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this._importedAsBasemap=!1,this._changes=t.styleChanges||new la,this._hasDataDrivenEmissive=!1,this.dispatcher=t.dispatcher?t.dispatcher:new I($o(),this),t.imageManager?this.imageManager=t.imageManager:(this.imageManager=new ha(this.map._spriteFormat),this.imageManager.setEventedParent(this)),this.imageManager.addScope(this.scope),this.glyphManager=t.glyphManager?t.glyphManager:new Xo(e._requestManager,t.localFontFamily?Yo.all:t.localIdeographFontFamily?Yo.ideographs:Yo.none,t.localFontFamily||t.localIdeographFontFamily),t.modelManager?this.modelManager=t.modelManager:(this.modelManager=new Mh(e._requestManager),this.modelManager.setEventedParent(this)),this._layers={},this._sourceCaches={},this._otherSourceCaches={},this._symbolSourceCaches={},this._loaded=!1,this._precompileDone=!1,this._shouldPrecompile=!1,this._availableImages=[],this._availableModels={},this._order=[],this._markersNeedUpdate=!1,this.options=t.configOptions?t.configOptions:new Map,this._configDependentLayers=t.configDependentLayers?t.configDependentLayers:new Set,this._indoorDependentLayers=t.indoorDependentLayers?t.indoorDependentLayers:new Set,this._config=t.config,this._styleColorTheme={lut:null,lutLoading:!1,lutLoadingCorrelationID:0,colorTheme:null,colorThemeOverride:t.colorThemeOverride},this._styleColorThemeForScope={},this._initialConfig=t.initialConfig,this.dispatcher.broadcast("setReferrer",Ko());const i=this;this._rtlTextPluginCallback=Zh.registerForPluginStateChange((e=>{i.dispatcher.broadcast("syncRTLPluginState",{pluginStatus:e.pluginStatus,pluginURL:e.pluginURL},((e,t)=>{if(Qo(e),t&&t.every((e=>e)))for(const e in i._sourceCaches){const t=i._sourceCaches[e],o=t.getSource().type;"vector"!==o&&"geojson"!==o||t.reload()}}))})),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(p(e))return e;const t=Jo(e);if(!t.startsWith("http"))try{return new URL(t,location.href).toString()}catch(e){return t}return t}return`json://${es(JSON.stringify(e))}`}_diffStyle(e,t,i){this.globalId=this._getGlobalId(e);const o=(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),s=this.map._requestManager.transformRequest(i,x.Style);y(s,((e,i)=>{e?this.fire(new A(e)):i&&o(i,t)}))}else"object"==typeof e&&o(e,t)}loadURL(e,t={}){this.fire(new D("dataloading",{dataType:"style"}));const i="boolean"==typeof t.validate?t.validate:!p(e);this.globalId=this._getGlobalId(e),e=this.map._requestManager.normalizeStyleURL(e,t.accessToken),this.resolvedImports.add(e);const o=this.importsCache.get(e);if(o)return this._load(o,i);const s=this.map._requestManager.transformRequest(e,x.Style);this._request=y(s,((t,o)=>{if(this._request=null,t)this.fire(new A(t));else if(o)return this.importsCache.set(e,o),this._load(o,i)}))}loadJSON(e,t={}){this.fire(new D("dataloading",{dataType:"style"})),this.globalId=this._getGlobalId(e),this._request=w.frame((()=>{this._request=null,this._load(e,!1!==t.validate)}))}loadEmpty(){this.fire(new D("dataloading",{dataType:"style"})),this._load(Hh,!1)}_loadImports(e,t,i){if(this.importDepth>=4)return u("Style doesn't support nesting deeper than 5"),Promise.resolve();const o=[];for(const s of e){const e=this._createFragmentStyle(s),r=new Promise((t=>{e.once("style.import.load",t),e.once("error",t)})).then((()=>this.mergeAll()));if(o.push(r),this.resolvedImports.has(s.url)){e.loadEmpty();continue}const n=s.data||this.importsCache.get(s.url);n?(e.loadJSON(n,{validate:t}),this._isInternalStyle(n)&&(e.globalId=null)):s.url?e.loadURL(s.url,{validate:t}):e.loadEmpty();const a={style:e,id:s.id,config:s.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(o)}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?O(e.id,this.scope):e.id;let i;const o=this._initialConfig&&this._initialConfig[t];(e.config||o)&&(i=Object.assign({},e.config,o));const s=new Zh(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"],configDependentLayers:this._configDependentLayers,indoorDependentLayers:this._indoorDependentLayers});return s.setEventedParent(this.map,{style:s}),s}_reloadImports(){this.mergeAll(),this._updateMapProjection(),this.updateConfigDependencies(),this._updateLayers(this._indoorDependentLayers),this.map._triggerCameraUpdate(this.camera),this.dispatcher.broadcast("setLayers",{layers:this._serializeLayers(this._order),scope:this.scope,options:this.options}),this._shouldPrecompile=this.map._precompilePrograms&&this.isRootStyle()}_isInternalStyle(e){return this.isRootStyle()&&(e.fragment||!!e.schema&&!1!==e.fragment)}_load(e,t){if(this._isInternalStyle(e)){const i=Object.assign({},Hh,{imports:[{id:"basemap",data:e,url:""}]},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(i,t)}if(this.updateConfig(this._config,e.schema),t&&Uh(this,Ba(e)))return;this._loaded=!0,this.stylesheet=ts(e);const i=()=>{for(const t in e.sources)this.addSource(t,e.sources[t],{validate:!1,isInitialLoad:!0});if(e.iconsets)for(const t in e.iconsets)this.addIconset(t,e.iconsets[t]);e.sprite?this._loadIconset(e.sprite):(this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0})),!this.glyphManager.url&&e.glyphs&&this.glyphManager.setURL(e.glyphs);const i=oc(this.stylesheet.layers);if(this._order=i.map((e=>e.id)),this.stylesheet.light&&u("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 el(e.properties,e.id)}else this.setLights(this.stylesheet.lights);this.light||(this.light=new el(this.stylesheet.light)),this._layers={};for(const e of i){const t=ns(e,this.scope,this._styleColorTheme.lut,this.options);0!==t.expressionDependencies.configDependencies.size&&this._configDependentLayers.add(t.fqid),t.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(t.fqid),this._hasAppearances=this._hasAppearances||0!==t.getAppearances().length,t.setEventedParent(this,{layer:{id:t.id}}),this._layers[t.id]=t;const i=this.getOwnLayerSourceCache(t),o=!!this.directionalLight&&this.directionalLight.shadowsEnabled();i&&t.canCastShadows()&&o&&(i.castsShadows=!0)}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._createTerrain(o,1)),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 D("data",{dataType:"style"}));const s=this.isRootStyle();e.imports?this._loadImports(e.imports,t).then((()=>{this._reloadImports(),this.fire(new D(s?"style.load":"style.import.load"))})).catch((e=>{this.fire(new A(new Error("Failed to load imports",e))),this.fire(new D(s?"style.load":"style.import.load"))})):(this._reloadImports(),this.fire(new D(s?"style.load":"style.import.load")))};this._styleColorTheme.colorTheme=this.stylesheet["color-theme"];const o=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(o){const e=this._evaluateColorThemeData(o);this._loadColorTheme(e).then((()=>{i()})).catch((e=>{u(`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,o,s,r,n,a,l,c;const h={};this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle((d=>{if(d.stylesheet){if(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);o=this._prioritizeTerrain(o,d.terrain,d.stylesheet.terrain),d.stylesheet.fog&&null!=d.fog&&(s=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=s,this.snow=r,this.rain=n,this._styleColorThemeForScope=h,null===o?delete this.terrain:this.terrain=o,this.camera=c||{"camera-projection":"perspective"},this.projection=a||{name:"mercator"},this.transition=Object.assign({},qh,l),this.mergeSources(),this.mergeLayers(),this.mergeIndoor()}forEachFragmentStyle(e){const t=i=>{for(const e of i.fragments)t(e.style);e(i)};t(this)}_prioritizeTerrain(e,t,i){const o=e&&0===e.drapeRenderMode;return null===i?t&&0===t.drapeRenderMode?t:o?e:null:null!=t&&(!e||o||t&&1===t.drapeRenderMode)?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}mergeProjection(){let e;this.forEachFragmentStyle((t=>{null!=t.stylesheet.projection&&(e=t.stylesheet.projection)})),this.projection=e||{name:"mercator"}}mergeSources(){const e={},t={},i={};this.forEachFragmentStyle((o=>{for(const t in o._sourceCaches){const i=O(t,o.scope);e[i]=o._sourceCaches[t]}for(const e in o._otherSourceCaches){const i=O(e,o.scope);t[i]=o._otherSourceCaches[e]}for(const e in o._symbolSourceCaches){const t=O(e,o.scope);i[t]=o._symbolSourceCaches[e]}})),this._mergedSourceCaches=e,this._mergedOtherSourceCaches=t,this._mergedSymbolSourceCaches=i}mergeIndoor(){this.forEachFragmentStyle((e=>{if(e.stylesheet&&e.stylesheet.indoor)for(const t of Object.values(e.stylesheet.indoor)){const i=t,o=O(i.sourceId,e.scope);this._mergedIndoor[o]=new Set(i.sourceLayers||[])}}))}mergeLayers(){const e={},t=[],i={};this._mergedSlots=[],this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this.forEachFragmentStyle((i=>{for(const o of i._order){const s=i._layers[o];if("slot"===s.type){const t=is(o);if(e[t])continue;e[t]=[]}s.slot&&e[s.slot]?e[s.slot].push(s):t.push(s)}})),this._mergedOrder=[];let o=-1;const s=(t=[])=>{for(const r of t)if("slot"===r.type){const t=is(r.id);e[t]&&s(e[t]),this._mergedSlots.push(t)}else{const e=O(r.id,r.scope);this._mergedOrder.push(e),i[e]=r,r.is3D(!!this.terrain)&&(this._has3DLayers=!0,o=this._mergedOrder.length-1),"circle"===r.type&&(this._hasCircleLayers=!0),"symbol"===r.type&&(this._hasSymbolLayers=!0),"clip"===r.type&&(this._clipLayerPresent=!0)}};if(s(t),this._has3DLayers){const e={};for(let t=0;t<this._mergedOrder.length;++t){const s=this._mergedOrder[t];e[s]=t===o?1:t<o?i[s].hasOcclusionOpacityProperties?2:0:4}this._mergedOrder.sort(((t,i)=>e[t]-e[i]))}this._mergedLayers=i,this.updateDrapeFirstLayers(),this._buildingIndex.processLayersChanged(),this._updateDataDrivenEmissiveStrength()}terrainSetForDrapingOnly(){return!!this.terrain&&0===this.terrain.drapeRenderMode}getCamera(){return this.stylesheet.camera}setCamera(e){return this.stylesheet.camera=Object.assign({},this.stylesheet.camera,e),this.camera=this.stylesheet.camera,this}_evaluateColorThemeData(e){return e.data?function(e,t,i,o){const s=Object.assign({},t);for(const e of Object.keys(zh))void 0===s[e]&&(s[e]=zh[e].default);const r=new le(Fh,e,new Map(i));return r.setTransitionOrValue(s,i),r.untransitioned().possiblyEvaluate(new ue(0,{worldview:void 0}))}(this.scope,e,this.options).get("data"):null}_loadColorTheme(e){this._styleColorTheme.lutLoading=!0,this._styleColorTheme.lutLoadingCorrelationID+=1;const t=this._styleColorTheme.lutLoadingCorrelationID;return new Promise(((i,o)=>{const s="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(s)||(r=s+r);const n=v.from("mapbox-reserved-lut"),a=new Image;a.src=r,a.onerror=()=>{this._styleColorTheme.lutLoading=!1,o(new Error("Failed to load image data"))},a.onload=()=>{if(this._styleColorTheme.lutLoadingCorrelationID!==t)return void i();this._styleColorTheme.lutLoading=!1;const{width:s,height:r,data:l}=w.getImageData(a);if(r>32)return void o(new Error("The height of the image must be less than or equal to 32 pixels."));if(s!==r*r)return void o(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 T({width:s,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()):o(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._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,0))}_updateMapProjection(){this.isRootStyle()&&(this.map._useExplicitProjection?this.applyProjectionUpdate():this.map._prioritizeAndUpdateProjection(null,this.projection))}_loadSprite(e){this._spriteRequest=function(e,t,i){let o,s,r;const n=w.devicePixelRatio>1?"@2x":"";let a=y(t.transformRequest(t.normalizeSpriteURL(e,n,".json"),x.SpriteJSON),((e,t)=>{a=null,r||(r=e,o=t,c())})),l=b(t.transformRequest(t.normalizeSpriteURL(e,n,".png"),x.SpriteImage),((e,t)=>{l=null,r||(r=e,s=t,c())}));function c(){if(r)i(r);else if(o&&s){const e=w.getImageData(s),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 T({width:s,height:r});T.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}}i(null,t)}}return{cancel(){a&&(a.cancel(),a=null),l&&(l.cancel(),l=null)}}}(e,this.map._requestManager,((e,t)=>{if(this._spriteRequest=null,e)this.fire(new A(e));else if(t){const e=new Map;for(const i in t)e.set(v.from(i),t[i]);this.addImages(e)}this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0}),this.fire(new D("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 A(new Error(`Source "${t.source}" as specified by iconset "${e}" does not exist and cannot be used as an iconset source`)));const o=i.getSource();if("raster-array"!==o.type)return void this.fire(new A(new Error(`Source "${t.source}" as specified by iconset "${e}" is not a "raster-array" source and cannot be used as an iconset source`)));o.partial=!1;const s=new Nh(e,this.scope,i);this.imageManager.addImageProvider(s,this.scope)}removeIconset(e){this.imageManager.removeImageProvider(e,this.scope)}_loadIconset(e){if(!p(e)&&"icon_set"!==this.map._spriteFormat||"raster"===this.map._spriteFormat)return void this._loadSprite(e);const t="auto"===this.map._spriteFormat;var i,o;this._spriteRequest=(o=(i,o)=>{if(this._spriteRequest=null,i)t?this._loadSprite(e):this.fire(new A(i));else if(o){const e=new Map;for(const t in o)e.set(v.from(t),o[t]);this.addImages(e)}this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0}),this.fire(new D("data",{dataType:"style"}))},Ut((i=this.map._requestManager).transformRequest(i.normalizeIconsetURL(e),x.Iconset),((e,t)=>{if(e)return void o(e);const i={},s=Wo(new Nt(t));for(const e of s.icons){const t={version:1,pixelRatio:w.devicePixelRatio,content:Bh(e),stretchX:e.metadata?kh(e.metadata.stretch_x_areas):void 0,stretchY:e.metadata?kh(e.metadata.stretch_y_areas):void 0,sdf:!1,usvg:!0,icon:e};i[e.name]=t}o(null,i)})))}_validateLayer(e){const t=this.getOwnSource(e.source);if(!t)return;const i=e.sourceLayer;i&&("geojson"===t.type||t.vectorLayerIds&&-1===t.vectorLayerIds.indexOf(i))&&this.fire(new A(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;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._sourceCaches)if(this._sourceCaches[e].hasTransition())return!0;for(const e in this._layers)if(this._layers[e].hasTransition())return!0;return!1}_updateDataDrivenEmissiveStrength(){for(const e in this._mergedLayers){const t=this._mergedLayers[e];if(t._transitionablePaint&&t._transitionablePaint._values){const e=t._transitionablePaint._values["line-emissive-strength"];if(e&&e.value&&e.value.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 A(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 A(new Error(`The source '${e}' does not exist in the map's style.`)))}precompilePrograms(e,t){const i=this.map.painter;if(i)for(let o=e.minzoom||0;o<(e.maxzoom||25.5);o++){const o=e.getProgramIds();if(o)for(const s of o){const o=e.getDefaultProgramParams(s,t.zoom,this._styleColorTheme.lut);o&&(i.style=this,this.fog&&(i._fogVisible=!0,o.overrideFog=!0,i.getOrCreateProgram(s,o)),i._fogVisible=!1,o.overrideFog=!1,i.getOrCreateProgram(s,o),(this.stylesheet.terrain||this.stylesheet.projection&&"globe"===this.stylesheet.projection.name)&&(o.overrideRtt=!0,i.getOrCreateProgram(s,o)))}}}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,t!==this._brightness&&(this._brightness=t,this.dispatcher.broadcast("setBrightness",t)),e.worldview!==this._worldview&&(this._worldview=e.worldview,this.dispatcher.broadcast("setWorldview",this._worldview));const i=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 s={};for(const e in this._mergedSourceCaches){const t=this._mergedSourceCaches[e];s[e]=t.used,t.used=!1,t.tileCoverLift=0}for(const t of this._mergedOrder){const i=this._mergedLayers[t];if("none"!==i.visibility&&i.recalculate(e,this._availableImages),!i.isHidden(e.zoom)){const e=this.getLayerSourceCache(i);e&&(e.used=!0,e.tileCoverLift=Math.max(e.tileCoverLift,i.tileCoverLift()))}!this._precompileDone&&this._shouldPrecompile&&("requestIdleCallback"in window?requestIdleCallback((()=>{this.precompilePrograms(i,e)})):this.precompilePrograms(i,e))}this._shouldPrecompile&&(this._precompileDone=!0),this.terrain&&o&&this.mergeLayers();const r=this.imageManager.getPendingImageProviders();for(const e of r)e.sourceCache.used=!0;for(const e in s){const t=this._mergedSourceCaches[e];s[e]!==t.used&&t.getSource().fire(new D("data",{sourceDataType:"visibility",dataType:"source",sourceId:t.getSource().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),i&&this.fire(new D("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 o=this.getFragmentStyle(e);o&&this.dispatcher.broadcast("updateLayers",{layers:t?o._serializeLayers(t):[],scope:e,removedIds:i||[],options:o.options})}setState(e,t){if(this._checkLoaded(),Uh(this,Ba(e)))return!1;(e=ts(e)).layers=oc(e.layers);const i=function(e,t){if(!e)return[{command:sc.setStyle,args:[t]}];let i=[];try{if(!Ht(e.version,t.version))return[{command:sc.setStyle,args:[t]}];if(Ht(e.center,t.center)||i.push({command:sc.setCenter,args:[t.center]}),Ht(e.zoom,t.zoom)||i.push({command:sc.setZoom,args:[t.zoom]}),Ht(e.bearing,t.bearing)||i.push({command:sc.setBearing,args:[t.bearing]}),Ht(e.pitch,t.pitch)||i.push({command:sc.setPitch,args:[t.pitch]}),Ht(e.sprite,t.sprite)||i.push({command:sc.setSprite,args:[t.sprite]}),Ht(e.glyphs,t.glyphs)||i.push({command:sc.setGlyphs,args:[t.glyphs]}),Ht(e.imports,t.imports)||function(e=[],t=[],i){t=t||[];const o=(e=e||[]).map(hc),s=t.map(hc),r=e.reduce(dc,{}),n=t.reduce(dc,{}),a=o.slice();let l,c,h,d;for(l=0,c=0;l<o.length;l++)h=o[l],n.hasOwnProperty(h)?c++:(i.push({command:sc.removeImport,args:[h]}),a.splice(a.indexOf(h,c),1));for(l=0,c=0;l<s.length;l++)h=s[s.length-1-l],a[a.length-1-l]!==h&&(r.hasOwnProperty(h)?(i.push({command:sc.removeImport,args:[h]}),a.splice(a.lastIndexOf(h,a.length-c),1)):c++,d=a[a.length-l],i.push({command:sc.addImport,args:[n[h],d]}),a.splice(a.length-l,0,h));for(const e of t){const t=r[e.id];t&&(delete t.data,Ht(t,e)||i.push({command:sc.updateImport,args:[e.id,e]}))}}(e.imports,t.imports,i),Ht(e.transition,t.transition)||i.push({command:sc.setTransition,args:[t.transition]}),Ht(e.light,t.light)||i.push({command:sc.setLight,args:[t.light]}),Ht(e.fog,t.fog)||i.push({command:sc.setFog,args:[t.fog]}),Ht(e.snow,t.snow)||i.push({command:sc.setSnow,args:[t.snow]}),Ht(e.rain,t.rain)||i.push({command:sc.setRain,args:[t.rain]}),Ht(e.projection,t.projection)||i.push({command:sc.setProjection,args:[t.projection]}),Ht(e.lights,t.lights)||i.push({command:sc.setLights,args:[t.lights]}),Ht(e.camera,t.camera)||i.push({command:sc.setCamera,args:[t.camera]}),Ht(e.iconsets,t.iconsets)||function(e,t,i){let o;for(o in t=t||{},e=e||{})e.hasOwnProperty(o)&&(t.hasOwnProperty(o)||i.push({command:sc.removeIconset,args:[o]}));for(o in t){if(!t.hasOwnProperty(o))continue;const s=t[o];e.hasOwnProperty(o)?Ht(e[o],s)||(i.push({command:sc.removeIconset,args:[o]}),i.push({command:sc.addIconset,args:[o,s]})):i.push({command:sc.addIconset,args:[o,s]})}}(e.iconsets,t.iconsets,i),!Ht(e["color-theme"],t["color-theme"]))return[{command:sc.setStyle,args:[t]}];const o={},s=[];!function(e,t,i,o){let s;for(s in t=t||{},e=e||{})e.hasOwnProperty(s)&&(t.hasOwnProperty(s)||nc(s,i,o));for(s in t){if(!t.hasOwnProperty(s))continue;const r=t[s];e.hasOwnProperty(s)?Ht(e[s],r)||("geojson"===e[s].type&&"geojson"===r.type&&lc(e,t,s)?i.push({command:sc.setGeoJSONSourceData,args:[s,r.data]}):ac(s,t,i,o)):rc(s,t,i)}}(e.sources,t.sources,s,o);const r=[];e.layers&&e.layers.forEach((e=>{e.source&&o[e.source]?i.push({command:sc.removeLayer,args:[e.id]}):r.push(e)}));let n=e.terrain;n&&o[n.source]&&(i.push({command:sc.setTerrain,args:[void 0]}),n=void 0),i=i.concat(s),Ht(n,t.terrain)||i.push({command:sc.setTerrain,args:[t.terrain]}),function(e,t,i){t=t||[];const o=(e=e||[]).map(hc),s=t.map(hc),r=e.reduce(dc,{}),n=t.reduce(dc,{}),a=o.slice(),l=Object.create(null);let c,h,d,u,_,p,f;for(c=0,h=0;c<o.length;c++)d=o[c],n.hasOwnProperty(d)?h++:(i.push({command:sc.removeLayer,args:[d]}),a.splice(a.indexOf(d,h),1));for(c=0,h=0;c<s.length;c++)d=s[s.length-1-c],a[a.length-1-c]!==d&&(r.hasOwnProperty(d)?(i.push({command:sc.removeLayer,args:[d]}),a.splice(a.lastIndexOf(d,a.length-h),1)):h++,p=a[a.length-c],i.push({command:sc.addLayer,args:[n[d],p]}),a.splice(a.length-c,0,d),l[d]=!0);for(c=0;c<s.length;c++)if(d=s[c],u=r[d],_=n[d],!l[d]&&!Ht(u,_))if(Ht(u.source,_.source)&&Ht(u["source-layer"],_["source-layer"])&&Ht(u.type,_.type)){for(f in cc(u.layout,_.layout,i,d,null,sc.setLayoutProperty),cc(u.paint,_.paint,i,d,null,sc.setPaintProperty),Ht(u.slot,_.slot)||i.push({command:sc.setSlot,args:[d,_.slot]}),Ht(u.filter,_.filter)||i.push({command:sc.setFilter,args:[d,_.filter]}),Ht(u.minzoom,_.minzoom)&&Ht(u.maxzoom,_.maxzoom)||i.push({command:sc.setLayerZoomRange,args:[d,_.minzoom,_.maxzoom]}),u)u.hasOwnProperty(f)&&"layout"!==f&&"paint"!==f&&"filter"!==f&&"metadata"!==f&&"minzoom"!==f&&"maxzoom"!==f&&"slot"!==f&&(0===f.indexOf("paint.")?cc(u[f],_[f],i,d,f.slice(6),sc.setPaintProperty):Ht(u[f],_[f])||i.push({command:sc.setLayerProperty,args:[d,f,_[f]]}));for(f in _)_.hasOwnProperty(f)&&!u.hasOwnProperty(f)&&"layout"!==f&&"paint"!==f&&"filter"!==f&&"metadata"!==f&&"minzoom"!==f&&"maxzoom"!==f&&"slot"!==f&&(0===f.indexOf("paint.")?cc(u[f],_[f],i,d,f.slice(6),sc.setPaintProperty):Ht(u[f],_[f])||i.push({command:sc.setLayerProperty,args:[d,f,_[f]]}))}else i.push({command:sc.removeLayer,args:[d]}),p=a[a.lastIndexOf(d)+1],i.push({command:sc.addLayer,args:[_,p]})}(r,t.layers,i)}catch(e){console.warn("Unable to compute style diff:",e),i=[{command:sc.setStyle,args:[t]}]}return i}(this.serialize(),e).filter((e=>!(e.command in Gh)));if(0===i.length)return!1;const o=i.filter((e=>!(e.command in jh)));if(o.length>0)throw new Error(`Unimplemented: ${o.map((e=>e.command)).join(", ")}.`);const s=[];return i.forEach((e=>{s.push(this[e.command](...e.args))})),t&&Promise.all(s).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(){this._availableImages=this.imageManager.listImages(this.scope),this.dispatcher.broadcast("setImages",{scope:this.scope,images:this._availableImages})}_updateWorkerModels(){this._availableModels=this.modelManager.getModelURIs(this.scope),this.dispatcher.broadcast("setModels",{scope:this.scope,models:this._availableModels})}addImages(e){if(0===e.size)return this;for(const[t,i]of e.entries()){if(this.getImage(t))return this.fire(new A(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(),this.fire(new D("data",{dataType:"style"})),this}addImage(e,t){return this.getImage(e)?this.fire(new A(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 D("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 D("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 D("data",{dataType:"style"})),this):this.fire(new A(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 D("data",{dataType:"style"})),this}addModel(e,t,i={}){return this._checkLoaded(),this._validate(Xa,`models.${e}`,t,null,i)||(this.modelManager.addModel(e,t,this.getActualScope()),this.fire(new D("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 D("data",{dataType:"style"})),this):this.fire(new A(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"].indexOf(t.type)>=0&&this._validate(ka,`sources.${e}`,t,null,i))return;this.map&&this.map._collectResourceTiming&&(t.collectResourceTiming=!0);const o=Ll(e,t,this.dispatcher,this);o.scope=this.scope,o.setEventedParent(this,(()=>({isSourceLoaded:this._isSourceCacheLoaded(o.id),source:o.serialize(),sourceId:o.id})));const s=e=>{const t=(e?"symbol:":"other:")+o.id,i=O(t,this.scope),s=this._sourceCaches[t]=new Kl(i,o,e);(e?this._symbolSourceCaches:this._otherSourceCaches)[o.id]=s,s.onAdd(this.map)};s(!1),"vector"!==t.type&&"geojson"!==t.type||s(!0),o.onAdd&&o.onAdd(this.map),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 A(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 A(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 A(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=is(e.id);delete this._sourceCaches[t],this._changes.discardSourceCacheUpdate(e.id),e.fire(new D("data",{sourceDataType:"metadata",dataType:"source",sourceId:e.getSource().id})),e.setEventedParent(null),e.clearTiles()}return delete this._otherSourceCaches[e],delete this._symbolSourceCaches[e],this.mergeSources(),t.setEventedParent(null),t.onRemove&&t.onRemove(this.map),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]._tiles;for(const e in i){const t=i[e];if("loaded"!==t.state&&"errored"!==t.state)return!1}}return!0}setLights(e){if(this._checkLoaded(),!e)return delete this.ambientLight,void delete this.directionalLight;const t=this._getTransitionParameters();for(const i of e){if(this._validate(Ua,"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 vl(i,pl||(pl=new ce({color:new he(ne.properties_light_ambient.color),"color-use-theme":new he({type:"string",default:"default","property-type":"data-constant"}),intensity:new he(ne.properties_light_ambient.intensity)})),this.scope,this.options);break;case"directional":if(this.directionalLight){const e=this.directionalLight;e.set(i),e.updateTransitions(t)}else this.directionalLight=new vl(i,fl||(fl=new ce({direction:new Se(ne.properties_light_directional.direction),color:new he(ne.properties_light_directional.color),"color-use-theme":new he({type:"string",default:"default","property-type":"data-constant"}),intensity:new he(ne.properties_light_directional.intensity),"cast-shadows":new he(ne.properties_light_directional["cast-shadows"]),"shadow-quality":new he(ne.properties_light_directional["shadow-quality"]),"shadow-intensity":new he(ne.properties_light_directional["shadow-intensity"])})),this.scope,this.options)}}const i=Object.assign(t,{worldview:this.map.getWorldview()}),o=new ue(this.z||0,i);this.ambientLight&&this.ambientLight.recalculate(o),this.directionalLight&&this.directionalLight.recalculate(o),this._brightness=this.calculateLightsBrightness(),this.dispatcher.broadcast("setBrightness",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)),o=e.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),s=e.properties.get("intensity"),r=e.properties.get("direction"),n=1-Go(r.x,r.y,r.z)[2]/90,a=i(o)*s*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(os(e)){const t=ss(e),i=this.fragments.find((({id:e})=>e===t));if(!i)return;const o=is(e);return i.style.getFragmentStyle(o)}{const t=this.fragments.find((({id:t})=>t===e));return t?t.style:void 0}}setFeaturesetSelectors(e){if(!e)return;const t={},i=(e,t="")=>`${e}::${t}`;this._featuresetSelectors={};for(const o in e){const s=this._featuresetSelectors[o]=[];for(const r of e[o].selectors){if(r.featureNamespace){const e=this.getOwnLayer(r.layer);if(!e){u(`Layer is undefined for selector: ${r.layer}`);continue}const s=i(e.source,e.sourceLayer);if(s in t&&t[s]!==r.featureNamespace){u(`"featureNamespace ${r.featureNamespace} of featureset ${o}'s selector is not associated to the same source, skip this selector`);continue}t[s]=r.featureNamespace}let e;if(r.properties)for(const t in r.properties){const i=W(r.properties[t]);"success"===i.result&&(e=e||{},e[t]=i.value)}s.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),o=i.stylesheet.featuresets;if(!o||!o[e])return this.fire(new A(new Error(`The featureset '${e}' does not exist in the map's style and cannot be queried.`))),[];const s=[];for(const t of o[e].selectors){const e=i.getOwnLayer(t.layer);e&&s.push(e)}return s}getConfigProperty(e,t){const i=this.getFragmentStyle(e);if(!i)return null;const o=O(t,i.scope),s=i.options.get(o),r=s?s.value||s.default:null;return r?r.serialize():null}isIndoorEnabled(){return Object.keys(this._mergedIndoor).length>0}getIndoorSourceLayers(e,t){const i=O(e,t);return this._mergedIndoor[i]}setIndoorData(e,t){this.map.indoor.setIndoorData(t)}updateIndoorDependentLayers(){this._updateLayers(this._indoorDependentLayers),this.map._styleDirty=!0,this.map.triggerRepaint()}setConfigProperty(e,t,i){const o=this.getFragmentStyle(e);if(!o)return;const s=o.stylesheet.schema;if(!s||!s[t])return;const r=W(i);if("success"!==r.result)return void Uh(this,r.value);const n=r.value.expression,a=O(t,o.scope),l=o.options.get(a);if(!l)return;let c;const{minValue:h,maxValue:d,stepValue:u,type:_,values:p}=s[t],f=W(s[t].default);"success"===f.result&&(c=f.value.expression),c?(this.options.set(a,Object.assign({},l,{value:n,default:c,minValue:h,maxValue:d,stepValue:u,type:_,values:p})),this.updateConfigDependencies(t)):this.fire(new A(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 o={};for(const e in i){const i=O(e,t.scope),s=t.options.get(i),r=s?s.value||s.default:null;o[e]=r?r.serialize():null}return o}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 o,s;const r=W(t[i].default);if("success"===r.result&&(o=r.value.expression),e&&void 0!==e[i]){const t=W(e[i]);"success"===t.result&&(s=t.value.expression)}const{minValue:n,maxValue:a,stepValue:l,type:c,values:h}=t[i];if(o){const e=O(i,this.scope);this.options.set(e,{default:o,value:s,minValue:n,maxValue:a,stepValue:l,type:c,values:h})}else this.fire(new A(new Error(`No schema defined for config option "${i}".`)))}else this.fire(new A(new Error("Attempting to set config for a style without schema.")))}_updateLayers(e,t=(()=>!0)){for(const i of e){const e=this.getLayer(i);e&&t(e)&&(e.possiblyEvaluateVisibility(),this._updateLayer(e),this._changes.setDirty())}}updateConfigDependencies(e){this._updateLayers(this._configDependentLayers,(t=>!e||t.expressionDependencies.configDependencies.has(e))),this.ambientLight&&this.ambientLight.updateConfig(this.options),this.directionalLight&&this.directionalLight.updateConfig(this.options),this.fog&&this.fog.updateConfig(this.options),this.snow&&this.snow.updateConfig(this.options),this.rain&&this.rain.updateConfig(this.options),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._changes.setDirty()}addLayer(e,t,i={}){this._checkLoaded();const o=e.id;if(this._layers[o])return void this.fire(new A(new Error(`Layer with id "${o}" already exists on this map`)));let s;if("custom"===e.type){if(Uh(this,rs(e)))return;s=ns(e,this.scope,this._styleColorTheme.lut,this.options)}else{if("object"==typeof e.source&&(this.addSource(o,e.source),e=ts(e),e=Object.assign(e,{source:o})),this._validate(qa,`layers.${o}`,e,{arrayIndex:-1},i))return;s=ns(e,this.scope,this._styleColorTheme.lut,this.options),this._validateLayer(s),s.setEventedParent(this,{layer:{id:o}})}const r=O(s.source,s.scope);0!==s.expressionDependencies.configDependencies.size&&this._configDependentLayers.add(r),s.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(r);let n=this._order.length;if(t){const e=this._order.indexOf(t);if(-1===e)return void this.fire(new A(new Error(`Layer with id "${t}" does not exist on this map.`)));s.slot===this._layers[t].slot?n=e:u(`Layer with id "${t}" has a different slot. Layers can only be rearranged within the same slot.`)}this._order.splice(n,0,o),this._layerOrderChanged=!0,this._layers[o]=s;const a=this.getOwnLayerSourceCache(s),l=!!this.directionalLight&&this.directionalLight.shadowsEnabled();a&&s.canCastShadows()&&l&&(a.castsShadows=!0);const c=this._changes.getRemovedLayer(s);if(c&&s.source&&a&&"custom"!==s.type){this._changes.discardLayerRemoval(s);const e=O(s.source,s.scope);c.type!==s.type?this._changes.updateSourceCache(e,"clear"):(this._changes.updateSourceCache(e,"reload"),a.pause())}this._updateLayer(s),s.onAdd&&s.onAdd(this.map),s.scope=this.scope,this.mergeLayers()}moveLayer(e,t){this._checkLoaded();const i=this._checkLayer(e);if(!i)return;if(e===t)return;const o=this._order.indexOf(e);this._order.splice(o,1);let s=this._order.length;if(t){const e=this._order.indexOf(t);if(-1===e)return void this.fire(new A(new Error(`Layer with id "${t}" does not exist on this map.`)));i.slot===this._layers[t].slot?s=e:u(`Layer with id "${t}" has a different slot. Layers can only be rearranged within the same slot.`)}this._order.splice(s,0,e),this._changes.setDirty(),this._layerOrderChanged=!0,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._layerOrderChanged=!0,this._configDependentLayers.delete(t.fqid),this._indoorDependentLayers.delete(t.fqid),this._changes.removeLayer(t);const o=this.getOwnLayerSourceCache(t);if(o&&o.castsShadows){let e=!1;for(const i in this._layers)if(this._layers[i].source===t.source&&this._layers[i].canCastShadows()){e=!0;break}o.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 o=this._checkLayer(e);o&&(o.minzoom===t&&o.maxzoom===i||(null!=t&&(o.minzoom=t),null!=i&&(o.maxzoom=i),this._updateLayer(o)))}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 o=this._checkLayer(e);if(o&&!Ht(o.filter,t))return null==t?(o.filter=void 0,void this._updateLayer(o)):void(this._validate(Za,`layers.${o.id}.filter`,t,{layerType:o.type},i)||(o.filter=ts(t),this._updateLayer(o)))}getFilter(e){const t=this._checkLayer(e);if(t)return ts(t.filter)}setLayoutProperty(e,t,i,o={}){this._checkLoaded();const s=this._checkLayer(e);if(s&&!Ht(s.getLayoutProperty(t),i)){if(null!=i&&(!o||!1!==o.validate)&&Uh(s,$a.call(Ba,{key:`layers.${e}.layout.${t}`,layerType:s.type,objectKey:t,value:i,styleSpec:ne,style:{glyphs:!0,sprite:!0}})))return;s.setLayoutProperty(t,i),0!==s.expressionDependencies.configDependencies.size&&this._configDependentLayers.add(s.fqid),s.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(s.fqid),this._updateLayer(s)}}setLayerProperty(e,t,i,o={}){this._checkLoaded();const s=this._checkLayer(e);s&&("appearances"===t?(s.setAppearances(i),this._changes.setDirty()):s.isPaintProperty(t)?this.setPaintProperty(e,t,i,o):this.setLayoutProperty(e,t,i,o))}getLayoutProperty(e,t){const i=this._checkLayer(e);if(i)return i.getLayoutProperty(t)}setPaintProperty(e,t,i,o={}){this._checkLoaded();const s=this._checkLayer(e);if(!s)return;if(Ht(s.getPaintProperty(t),i))return;if(null!=i&&(!o||!1!==o.validate)&&Uh(s,Wa.call(Ba,{key:`layers.${e}.paint.${t}`,layerType:s.type,objectKey:t,value:i,styleSpec:ne})))return;const r=s.setPaintProperty(t,i);0!==s.expressionDependencies.configDependencies.size&&this._configDependentLayers.add(s.fqid),s.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(s.fqid),r&&this._updateLayer(s),this._changes.updatePaintProperties(s)}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:o}=e.target,s=this.getFragmentStyle(o),r=s.getFeaturesetLayers(i);for(const{source:i,sourceLayer:o}of r)s.setFeatureState({id:e.id,source:i,sourceLayer:o},t)}else if("layerId"in e.target){const{layerId:i}=e.target,o=this.getLayer(i);this.setFeatureState({id:e.id,source:o.source,sourceLayer:o.sourceLayer},t)}return}const i=e.source,o=e.sourceLayer,s=this._checkSource(i);if(!s)return;const r=s.type;if("geojson"===r&&o)return void this.fire(new A(new Error("GeoJSON sources cannot have a sourceLayer parameter.")));if("vector"===r&&!o)return void this.fire(new A(new Error("The sourceLayer parameter must be provided for vector source types.")));void 0===e.id&&this.fire(new A(new Error("The feature id parameter must be provided.")));const n=this.getOwnSourceCaches(i);for(const i of n)i.setFeatureState(o,e.id,t)}removeFeatureState(e,t){if(this._checkLoaded(),"target"in e){if("featuresetId"in e.target){const{featuresetId:i,importId:o}=e.target,s=this.getFragmentStyle(o),r=s.getFeaturesetLayers(i);for(const{source:i,sourceLayer:o}of r)s.removeFeatureState({id:e.id,source:i,sourceLayer:o},t)}else if("layerId"in e.target){const{layerId:i}=e.target,o=this.getLayer(i);this.removeFeatureState({id:e.id,source:o.source,sourceLayer:o.sourceLayer},t)}return}const i=e.source,o=this._checkSource(i);if(!o)return;const s=o.type,r="vector"===s?e.sourceLayer:void 0;if("vector"===s&&!r)return void this.fire(new A(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 A(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:o}=e.target,s=this.getFragmentStyle(o),r=s.getFeaturesetLayers(i);for(const{source:i,sourceLayer:o}of r){const r=s.getFeatureState({id:e.id,source:i,sourceLayer:o});if(r&&!t)t=r;else if(!Ht(t,r))return void this.fire(new A(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{layerId:i}=e.target,o=this.getLayer(i);t=this.getFeatureState({id:e.id,source:o.source,sourceLayer:o.sourceLayer})}return t}const t=e.source,i=e.sourceLayer,o=this._checkSource(t);if(o){if("vector"!==o.type||i)return void 0===e.id&&this.fire(new A(new Error("The feature id parameter must be provided."))),this.getOwnSourceCaches(t)[0].getFeatureState(i,e.id);this.fire(new A(new Error("The sourceLayer parameter must be provided for vector source types.")))}}setTransition(e){return this.stylesheet.transition=Object.assign({},this.stylesheet.transition,e),this.transition=this.stylesheet.transition,this}getTransition(){return Object.assign({},this.stylesheet.transition)}serialize(){this._checkLoaded();const e=this.getTerrain(),t=e&&this.terrain&&this.terrain.scope===this.scope?e:this.stylesheet.terrain;return as({version:this.stylesheet.version,name:this.stylesheet.name,metadata:this.stylesheet.metadata,fragment:this.stylesheet.fragment,iconsets:this.stylesheet.iconsets,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,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=O(e.source,e.scope),o=this._changes.getUpdatedSourceCaches();e.source&&!o[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,o={},s=[];for(let r=i.length-1;r>=0;r--){const n=i[r];if(t(n)){o[n]=r;for(const t of e){const e=t[n];if(e)for(const t of e)s.push(t)}}}s.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=s.length-1;e>=0;e--){const t=s[e].feature;if(t.layer&&o[t.layer.id]<n)break;r.push(t),s.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 o=this.getOwnSource(e);return o?"raster-array"!==o.type?(this.fire(new A(new Error('queryRasterValue support only "raster-array" sources.'))),Promise.resolve(null)):o.queryRasterArrayValue(t,i):(this.fire(new A(new Error(`Source with id "${e}" does not exist in the style.`))),Promise.resolve(null))}queryRenderedFeatures(e,t,i){let o;t&&!Array.isArray(t)&&t.filter&&(this._validate(Za,"queryRenderedFeatures.filter",t.filter,null,t),o=mt(t.filter));const s={},r=e=>{if(Vh.has(e.type))return;const t=this.getOwnLayerSourceCache(e),i=s[t.id]=s[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:o})};if(t&&t.layers){if(!Array.isArray(t.layers))return this.fire(new A(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 A(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,s,i),a=this._flattenAndSortRenderedFeatures(n),l=[];for(const e of a)ls(e.layer.id)===this.scope&&l.push(e);return l}queryRenderedFeatureset(e,t,i){let o;t&&!Array.isArray(t)&&t.filter&&(this._validate(Za,"queryRenderedFeatures.filter",t.filter,null,t),o=mt(t.filter));const s="mock",r=[];if(t&&t.target)r.push(Object.assign({},t,{targetId:s,filter:o}));else{const e=this.getFeaturesetDescriptors();for(const t of e)r.push({targetId:s,filter:o,target:t});for(const{style:e}of this.fragments){const t=e.getFeaturesetDescriptors();for(const e of t)r.push({targetId:s,filter:o,target:e})}}const n=this.queryRenderedTargets(e,r,i),a=[],l=new Set;for(const e of n)for(const t of e.variants[s])Pl(t,e,l)||a.push(new cs(e,t));return a}queryRenderedTargets(e,t,i){const o={},s=(e,t,i,s)=>{const r=o[t.id]=o[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),!s)return i.uniqueFeatureID=!1,void r.layers[e.fqid].targets.push(i);r.layers[e.fqid].targets.push(Object.assign({},i,{namespace:s.namespace,properties:s.properties,uniqueFeatureID:s.uniqueFeatureID}))};for(const e of t)if("featuresetId"in e.target){const{featuresetId:t,importId:i}=e.target,o=this.getFragmentStyle(i);if(!o||!o._featuresetSelectors)continue;const r=o._featuresetSelectors[t];if(!r){this.fire(new A(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=o.getOwnLayer(t.layerId);i&&!Vh.has(i.type)&&s(i,o.getOwnLayerSourceCache(i),e,t)}}else if("layerId"in e.target){const{layerId:t}=e.target,i=this.getLayer(t);if(!i||Vh.has(i.type))continue;s(i,this.getLayerSourceCache(i),e)}const r=this._queryRenderedFeatures(e,o,i);return this._flattenAndSortRenderedFeatures(r)}_queryRenderedFeatures(e,t,i){const o=[],s=!!this.map._showQueryGeometry,r=yl.createFromScreenPoints(e,i);for(const e in t){const n=Ml(r,t[e],this._availableImages,i,s);Object.keys(n).length&&o.push(n)}if(this.placement)for(const e in t){if(!t[e].sourceCache._onlySymbols)continue;const i=zl(r.screenGeometry,t[e],this._availableImages,this.placement.collisionIndex,this.placement.retainedQueryData,this.map.getWorldview());Object.keys(i).length&&o.push(i)}return o}querySourceFeatures(e,t){const i=t&&t.filter;i&&this._validate(Za,"querySourceFeatures.filter",i,null,t);let o=[];const s=this.getOwnSourceCaches(e);for(const e of s)o=o.concat(Fl(e,t));return o}addSourceType(e,t,i){return Zh.getSourceType(e)?i(new Error(`A source type called "${e}" already exists.`)):(Zh.setSourceType(e,t),t.workerSourceURL?void this.dispatcher.broadcast("loadWorkerSource",{name:e,url:t.workerSourceURL},i):i(null,null))}getFlatLight(){return this.light.getLight()}setFlatLight(e,t,i={}){this._checkLoaded();const o=this.light.getLight();let s=!1;for(const t in e)if(!Ht(e[t],o[t])){s=!0;break}if(!s)return;const r=this._getTransitionParameters();this.light.setLight(e,t,i),this.light.updateTransitions(r)}getTerrain(){return this.terrain&&1===this.terrain.drapeRenderMode?this.terrain.get():null}setTerrainForDraping(){this.setTerrain({source:"",exaggeration:0},0)}checkCanvasFingerprintNoise(){void 0===this.disableElevatedTerrain&&(this.disableElevatedTerrain=w.hasCanvasFingerprintNoise(),this.disableElevatedTerrain&&u("Terrain and hillshade are disabled because of Canvas2D limitations when fingerprinting protection is enabled (e.g. in private browsing mode)."))}setTerrain(e,t=1){if(this._checkLoaded(),!e)return this.terrainSetForDrapingOnly()||(delete this.terrain,this.map.transform.projection.requiresDraping&&this.setTerrainForDraping()),0===t&&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 o=!("source"in e)||null==e.source;if(1===t){if(this.disableElevatedTerrain)return;if("source"in i&&"object"==typeof i.source){const e="terrain-dem-src";this.addSource(e,i.source),i=ts(i),i=Object.assign(i,{source:e})}const e=Object.assign({},i),t={};if(this.terrain&&o){e.source=this.terrain.get().source;const i=this.terrain?this.getFragmentStyle(this.terrain.scope):null;i&&(t.style=i.serialize())}if(this._validate(ja,"terrain",e,t))return}if(!this.terrain||this.terrain.scope!==this.scope&&!o||this.terrain&&t!==this.terrain.drapeRenderMode){if(!i)return;this._createTerrain(i,t),this.fire(new D("data",{dataType:"style"}))}else{const t=this.terrain,o=t.get();for(const e of Object.keys(ne.terrain))!i.hasOwnProperty(e)&&ne.terrain[e].default&&(i[e]=ne.terrain[e].default);for(const i in e)if(!Ht(e[i],o[i])){t.set(e,this.options),this.stylesheet.terrain=e;const i=this._getTransitionParameters({duration:0});t.updateTransitions(i),this.fire(new D("data",{dataType:"style"}));break}}this.mergeTerrain(),this.updateDrapeFirstLayers(),this._markersNeedUpdate=!0}_createFog(e){const t=this.fog=new dl(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 ml(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 gl(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)return delete this.fog,delete this.stylesheet.fog,void(this._markersNeedUpdate=!0);if(this.fog){const t=this.fog;if(!Ht(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);this._markersNeedUpdate=!0}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(!Ht(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(!Ht(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 D("colorthemeset")),e()})).catch((e=>{u(`Couldn't set color theme: ${e}`)}))}setColorTheme(e){this._checkLoaded(),this._styleColorTheme.colorThemeOverride&&u("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:w.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 il(e,t,this.scope,this.options,this.map.getWorldview());1===t&&(this.stylesheet.terrain=e),this.mergeTerrain(),this.updateDrapeFirstLayers(),this._force3DLayerUpdate();const o=this._getTransitionParameters({duration:0});i.updateTransitions(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,o,s={}){if(s&&!1===s.validate)return!1;const r=Object.assign({},this.serialize());return Uh(this,e.call(Ba,Object.assign({key:t,style:r,value:i,styleSpec:ne},o)))}_remove(){this._request&&(this._request.cancel(),this._request=null),this._spriteRequest&&(this._spriteRequest.cancel(),this._spriteRequest=null),hs.off("pluginStateChange",this._rtlTextPluginCallback);for(const e in this._mergedLayers)this._mergedLayers[e].setEventedParent(null);for(const e in this._mergedSourceCaches)this._mergedSourceCaches[e].clearTiles(),this._mergedSourceCaches[e].setEventedParent(null);this.imageManager.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.isRootStyle()&&(this.imageManager.setEventedParent(null),this.imageManager.destroy(),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=Lh(this.directionalLight));const i=new Set,o=new Set;for(const e in this._mergedLayers){const t=this._mergedLayers[e];"building"===t.type&&i.add(t.source),t.hasElevation()&&!o.has(t.source)&&o.add(t.source)}for(const s in this._mergedSourceCaches){const r=this._mergedSourceCaches[s],n=o.has(r._source.id);i.has(r._source.id)&&(r._source.reparseOverscaled=!1),r.update(e,void 0,void 0,t,n)}}_generateCollisionBoxes(){for(const e in this._sourceCaches){const t=this._sourceCaches[e];t.resume(),t.reload()}}_updatePlacement(e,t,i,o,s,r,n=!1){let a=!1,l=!1;const c={},h={};for(const e of this._mergedOrder){const i=this._mergedLayers[e];if("symbol"!==i.type)continue;const o=O(i.source,i.scope);let s=c[o];if(!s){const e=this.getLayerSourceCache(i);if(!e)continue;const t=e.getRenderableIds(!0).map((t=>e.getTileByID(t)));h[o]=t.slice(),s=c[o]=t.sort(((e,t)=>t.tileID.overscaledZ-e.tileID.overscaledZ||(e.tileID.isLessThan(t.tileID)?-1:1)))}const r=this.crossTileSymbolIndex.addLayer(i,s,t.center.lng,t.projection);a=a||r}this.crossTileSymbolIndex.pruneUnusedLayers(this._mergedOrder),n=n||this._layerOrderChanged,this._layerOrderChanged&&this.fire(new D("neworder"));const d=Boolean(this.placement&&!t.equals(this.placement.transform)),u=Boolean(this.placement&&(0!==this.placement.lastReplacementSourceUpdateTime&&!r||this.placement.lastReplacementSourceUpdateTime!==r.updateTime)),_=(d||u||a||this.placement&&this.placement.isStale())&&0===o;if((n||!this.pauseablePlacement||_||0!==o&&this.pauseablePlacement.isDone()&&!this.placement.stillRecent(w.now(),t.zoom))&&(this.pauseablePlacement=new ih(t,this._mergedOrder,n||0===o,i,o,s,this.placement,this.fog&&t.projection.supportsFog?this.fog.state:null,this._buildingIndex),this._layerOrderChanged=!1),this.pauseablePlacement.isDone()?this.placement.setStale():(this.pauseablePlacement.continuePlacement(this._mergedOrder,this._mergedLayers,c,h,this.map.painter.scaleFactor),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(w.now()),l=!0),a&&this.pauseablePlacement.placement.setStale()),l||a){this._buildingIndex.onNewFrame(t.zoom);for(let e=0;e<this._mergedOrder.length;e++){const t=this._mergedLayers[this._mergedOrder[e]];if("symbol"!==t.type)continue;if("none"===t.visibility)continue;const i=this.isLayerClipped(t);this.placement.updateLayerOpacities(t,c[O(t.source,t.scope)],e,i?r:null)}}return{needsRerender:!this.pauseablePlacement.isDone()||this.placement.hasTransitions(w.now())}}_releaseSymbolFadeTiles(){for(const e in this._sourceCaches)this._sourceCaches[e].releaseSymbolFadeTiles()}addImport(e,t){this._checkLoaded();const i=this.stylesheet.imports=this.stylesheet.imports||[];if(-1!==i.findIndex((({id:t})=>t===e.id)))return void this.fire(new A(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 o=i.findIndex((({id:e})=>e===t));return-1===o&&this.fire(new A(new Error(`Import with id "${t}" does not exist on this map.`))),this.stylesheet.imports=i.slice(0,o).concat(e).concat(i.slice(o)),this._loadImports([e],!0,t)}updateImport(e,t){this._checkLoaded();const i=this.stylesheet.imports||[],o=this.getImportIndex(e);return-1===o?this:"string"==typeof t?(this.setImportUrl(e,t),this):(t.url&&t.url!==i[o].url&&this.setImportUrl(e,t.url),Ht(t.config,i[o].config)||this.setImportConfig(e,t.config,t.data.schema),Ht(t.data,i[o].data)||this.setImportData(e,t.data),this)}moveImport(e,t){this._checkLoaded();let i=this.stylesheet.imports||[];const o=this.getImportIndex(e);if(-1===o)return this;const s=this.getImportIndex(t);if(-1===s)return this;const r=i[o],n=this.fragments[o];return i=i.filter((({id:t})=>t!==e)),this.fragments=this.fragments.filter((({id:t})=>t!==e)),this.stylesheet.imports=i.slice(0,s).concat(r).concat(i.slice(s)),this.fragments=this.fragments.slice(0,s).concat(n).concat(this.fragments.slice(s)),this.mergeLayers(),this}setImportUrl(e,t){this._checkLoaded();const i=this.stylesheet.imports||[],o=this.getImportIndex(e);if(-1===o)return this;i[o].url=t;const s=this.fragments[o];return s.style=this._createFragmentStyle(i[o]),s.style.on("style.import.load",(()=>this.mergeAll())),s.style.loadURL(t),this}setImportData(e,t){this._checkLoaded();const i=this.getImportIndex(e),o=this.stylesheet.imports||[];return-1===i?this:t?(this.fragments[i].style.setState(t),this._reloadImports(),this):(delete o[i].data,this.setImportUrl(e,o[i].url))}setImportConfig(e,t,i){this._checkLoaded();const o=this.getImportIndex(e),s=this.stylesheet.imports||[];if(-1===o)return this;t?s[o].config=t:delete s[o].config;const r=this.fragments[o];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 A(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=O(e,t);return this._mergedOtherSourceCaches[i]}getLayerSourceCache(e){const t=O(e.source,e.scope);return"symbol"===e.type?this._mergedSymbolSourceCaches[t]:this._mergedOtherSourceCaches[t]}getSourceCaches(e){if(null==e)return Object.values(this._mergedSourceCaches);const t=[];return this._mergedOtherSourceCaches[e]&&t.push(this._mergedOtherSourceCaches[e]),this._mergedSymbolSourceCaches[e]&&t.push(this._mergedSymbolSourceCaches[e]),t}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){this.stylesheet.glyphs=e,this.glyphManager.setURL(e)}getImages(e,t,i){this.imageManager.getImages(t.images,t.scope,i),this._updateTilesForChangedImages();const o=e=>{if(e){const i=t.images.map((e=>v.toString(e)));e.setDependencies(t.tileID.key,t.type,i)}},s=O(t.source,t.scope);o(this._mergedOtherSourceCaches[s]),o(this._mergedSymbolSourceCaches[s]),t.images.some((e=>e.iconsetId))&&this.fire(new D("data",{dataType:"style"}))}rasterizeImages(e,t,i){this.imageManager.rasterizeImages(t,i)}getGlyphs(e,t,i){this.glyphManager.getGlyphs(t.stacks,i)}getResource(e,t,i){return ds(t,i)}getOwnSourceCache(e){return this._otherSourceCaches[e]}getOwnLayerSourceCache(e){return"symbol"===e.type?this._symbolSourceCaches[e.source]:this._otherSourceCaches[e.source]}getOwnSourceCaches(e){const t=[];return this._otherSourceCaches[e]&&t.push(this._otherSourceCaches[e]),this._symbolSourceCaches[e]&&t.push(this._symbolSourceCaches[e]),t}_isSourceCacheLoaded(e){const t=this.getOwnSourceCaches(e);return 0===t.length?(this.fire(new A(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),o="building"===e.type;if(e.is3D(!!this.terrain)){if(i||o||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")}destroy(){this._clearWorkerCaches(),this.fragments.forEach((e=>{e.style._remove()})),this.terrainSetForDrapingOnly()&&(delete this.terrain,delete this.stylesheet.terrain)}}Zh.getSourceType=function(e){return Dl[e]},Zh.setSourceType=function(e,t){Dl[e]=t},Zh.registerForPluginStateChange=us;class Wh extends E{constructor(e){super(),this._style=e,this._buildings={},this._activeFloors=new Set,this._activeFloorsVisible=!0,this._indoorState={selectedFloorId:null,lastActiveFloors:null,activeFloorsVisible:!0},nt(["_updateUI"],this)}destroy(){this._buildings={},this._activeFloors=new Set,this._indoorState=null}selectFloor(e){e===this._selectedFloorId&&this._activeFloorsVisible||(this._selectedFloorId=e,this._activeFloorsVisible=!0,this._updateActiveFloors())}setActiveFloorsVisibility(e){this._activeFloorsVisible=e,this._updateActiveFloors(),this._updateIndoorSelector()}setIndoorData(e){for(const[t,i]of Object.entries(e.buildings))if(this._buildings[t])for(const e of i.floorIds)this._buildings[t].floors[e]||(this._buildings[t].floors[e]=i.floors[e]);else this._buildings[t]=i;for(const t of e.activeFloors)this._activeFloors.add(t);this._updateIndoorSelector()}getIndoorTileOptions(e,t){const i=this._style.getIndoorSourceLayers(e,t);return i&&this._indoorState?{sourceLayers:i,indoorState:this._indoorState}:null}_updateUI(e,t,i){const o=function(e,t,i,o){let s=null,r=Number.MAX_SAFE_INTEGER;if(o<16)return null;for(const[o,n]of Object.entries(e)){const e=n.center;if(e){const n=t.distanceTo(tt.convert(e));n<r&&i.contains(e)&&(r=n,s=o)}}return s}(this._buildings,t,i,e);o!==this._closestBuildingId&&(this._closestBuildingId=o,this._updateIndoorSelector())}_updateIndoorSelector(){const e=this._buildings,t=this._closestBuildingId,i=t&&e?e[t]:void 0;if(!i)return void this.fire(new D("selector-update",{selectedFloorId:null,activeFloorsVisible:this._activeFloorsVisible,floors:[]}));let o=null;for(const e of i.floorIds)if(this._activeFloors&&this._activeFloors.has(e)){o=e;break}const s=Array.from(i.floorIds).map((e=>({id:e,name:i.floors[e].name,zIndex:i.floors[e].zIndex}))).sort(((e,t)=>t.zIndex-e.zIndex));this.fire(new D("selector-update",{selectedFloorId:o,activeFloorsVisible:this._activeFloorsVisible,floors:s}))}_updateActiveFloors(){const e=this._activeFloors;this._activeFloors=new Set,this._indoorState={selectedFloorId:this._selectedFloorId,lastActiveFloors:e,activeFloorsVisible:this._activeFloorsVisible},this._style.updateIndoorDependentLayers()}}const $h="\n#define EPSILON 0.0000001\n#define PI 3.141592653589793\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",Xh="\n#ifdef DUAL_SOURCE_BLENDING\nlayout(location=0,index=0) out vec4 glFragColor;layout(location=0,index=1) out vec4 glFragColorSrc1;\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 dot(rgba_depth,bit_shift)*2.0-1.0;}highp vec4 pack_depth(highp float ndc_z) {highp float depth=ndc_z*0.5+0.5;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;}\n#ifdef INDICATOR_CUTOUT\nuniform vec3 u_indicator_cutout_centers;uniform vec4 u_indicator_cutout_params;\n#endif\nvec4 applyCutout(vec4 color,float height) {\n#ifdef INDICATOR_CUTOUT\nfloat verticalFadeRange=u_indicator_cutout_centers.z*0.25;float holeMinOpacity=mix(1.0,u_indicator_cutout_params.x,smoothstep(u_indicator_cutout_centers.z,u_indicator_cutout_centers.z+verticalFadeRange,height));float holeRadius=max(u_indicator_cutout_params.y,0.0);float holeAspectRatio=u_indicator_cutout_params.z;float fadeStart=u_indicator_cutout_params.w;float distA=distance(vec2(gl_FragCoord.x,gl_FragCoord.y*holeAspectRatio),vec2(u_indicator_cutout_centers[0],u_indicator_cutout_centers[1]*holeAspectRatio));return color*min(smoothstep(fadeStart,holeRadius,distA)+holeMinOpacity,1.0);\n#else\nreturn color;\n#endif\n}\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 applyLUT(highp sampler3D lut,vec4 col) {vec3 size=vec3(textureSize(lut,0));vec3 uvw=(col.rbg*float(size-1.0)+0.5)/size;return vec4(texture(lut,uvw).rgb*col.a,col.a);}vec3 applyLUT(highp sampler3D lut,vec3 col) {return applyLUT(lut,vec4(col,1.0)).rgb;}",Yh="\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);}vec2 unpack_opacity(const float packedOpacity) {int intOpacity=int(packedOpacity)/2;return vec2(float(intOpacity)/127.0,mod(packedOpacity,2.0));}vec4 decode_color(const vec2 encodedColor) {return vec4(\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(vec2 posWithComposedSkirt)\n{float skirt=float(posWithComposedSkirt.x >=skirtOffset);vec2 pos=posWithComposedSkirt-vec2(skirt*skirtOffset,0.0);return vec3(pos,skirt);}\n#ifndef HAS_SHADER_STORAGE_BLOCK_material_buffer\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#endif",Kh="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;}",Qh="\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;vec3 elevationVector(vec2 pos) {vec2 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\nvec3 elevationVector(vec2 pos) { return vec3(0,0,1); }\n#endif\n#ifdef TERRAIN\nuniform highp sampler2D u_dem;uniform highp sampler2D u_dem_prev;uniform 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}float 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#ifdef TERRAIN_VERTEX_MORPHING\nfloat elevation(vec2 apos) {\n#ifdef ZERO_EXAGGERATION\nreturn 0.0;\n#endif\nfloat nextElevation=currentElevation(apos);float prevElevation=prevElevation(apos);return mix(prevElevation,nextElevation,u_dem_lerp);}\n#else\nfloat elevation(vec2 apos) {\n#ifdef ZERO_EXAGGERATION\nreturn 0.0;\n#endif\nreturn currentElevation(apos);}\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#else\nfloat elevation(vec2 pos) { return 0.0; }\n#endif\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*u_depth_range_unpack.x+u_depth_range_unpack.y;}vec4 unpack_depth4(vec4 depth) {return depth*u_depth_range_unpack.x+vec4(u_depth_range_unpack.y);}\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 dot(rgba_depth,bit_shift)*2.0-1.0;}\n#endif\nbool isOccluded(vec4 frag) {vec3 coord=frag.xyz/frag.w;\n#ifdef CLIP_ZERO_TO_ONE\ncoord.z=-1.0+2.0*coord.z; \n#endif\n#ifdef DEPTH_D24\nfloat depth=unpack_depth(texture(u_depth,(coord.xy+1.0)*0.5).r);\n#else\nfloat depth=unpack_depth_rgba(texture(u_depth,(coord.xy+1.0)*0.5));\n#endif\nreturn coord.z+u_occlusion_depth_offset > depth;}highp vec4 getCornerDepths(vec2 coord) {highp vec3 df=vec3(u_occluder_half_size*u_depth_size_inv,0.0);highp vec2 uv=0.5*coord.xy+0.5;\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=0.5*coord.xy+0.5;\n#ifdef CLIP_ZERO_TO_ONE\ncoord.z=-1.0+2.0*coord.z; \n#endif\nint 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(300.0*(coord.z+u_occlusion_depth_offset-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;\n#ifdef CLIP_ZERO_TO_ONE\ncoord.z=-1.0+2.0*coord.z; \n#endif\nhighp vec4 depth=getCornerDepths(coord.xy);return dot(vec4(0.25),vec4(1.0)-clamp(300.0*(vec4(coord.z+u_occlusion_depth_offset)-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",Jh="#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",ed="#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=gl_FragCoord.xy/u_viewport;\n#ifdef FLIP_Y\nuv.y=1.0-uv.y;\n#endif\nhighp 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",td="#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",id="#ifdef RASTER_ARRAY\nuniform sampler2D u_velocity;uniform mediump vec2 u_velocity_res;uniform mediump float u_max_speed;const vec4 NO_DATA=vec4(1);const vec2 INVALID_VELOCITY=vec2(-1);uniform highp vec2 u_uv_offset;uniform highp float u_data_offset;uniform highp vec2 u_data_scale;ivec4 rasterArrayLinearCoord(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);}highp vec2 lookup_velocity(highp vec2 uv) {uv=u_uv_offset.x+u_uv_offset.y*uv;highp vec2 fxy;ivec4 c=rasterArrayLinearCoord(uv,u_velocity_res,fxy);highp vec4 tl=texelFetch(u_velocity,c.yz,0);highp vec4 tr=texelFetch(u_velocity,c.xz,0);highp vec4 bl=texelFetch(u_velocity,c.yw,0);highp vec4 br=texelFetch(u_velocity,c.xw,0);if (tl==NO_DATA) {return INVALID_VELOCITY;}if (tr==NO_DATA) {return INVALID_VELOCITY;}if (bl==NO_DATA) {return INVALID_VELOCITY;}if (br==NO_DATA) {return INVALID_VELOCITY;}highp vec4 t=mix(mix(bl,br,fxy.x),mix(tl,tr,fxy.x),fxy.y);highp vec2 velocity=u_data_offset+vec2(dot(t.rg,u_data_scale),dot(t.ba,u_data_scale));velocity.y=-velocity.y;velocity/=max(u_max_speed,length(velocity));return velocity;}\n#endif\nuniform highp float u_particle_pos_scale;uniform highp vec2 u_particle_pos_offset;highp vec4 pack_pos_to_rgba(highp vec2 p) {highp vec2 v=(p+u_particle_pos_offset)/u_particle_pos_scale;highp vec4 r=vec4(v.x,fract(v.x*255.0),v.y,fract(v.y*255.0));return vec4(r.x-r.y/255.0,r.y,r.z-r.w/255.0,r.w);}highp vec2 unpack_pos_from_rgba(highp vec4 v) {v=floor(v*255.0+0.5)/255.0;highp vec2 p=vec2(v.x+(v.y/255.0),v.z+(v.w/255.0));return u_particle_pos_scale*p-u_particle_pos_offset;}",od="#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",sd="#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;float shadow_sample(sampler2DShadow shadowmap,highp vec3 pos,highp float bias) {\n#ifdef CLIP_ZERO_TO_ONE\nhighp vec3 coord=vec3(pos.xy*0.5+0.5,pos.z-bias);\n#else\nhighp vec3 coord=vec3(pos.xy*0.5+0.5,pos.z*0.5+0.5-bias);\n#endif\nreturn 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=light_view_pos0.xyz/light_view_pos0.w*0.5+0.5;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",rd=/#include\s+"([^"]+)"/g,nd=/#pragma mapbox: ([\w\-]+) ([\w]+) ([\w]+) ([\w]+)/g,ad=/\b[A-Za-z_][A-Za-z0-9_]*\b/g,ld=new Set(["ifdef","ifndef","elif","if","defined"]),cd=new Set;gd($h,cd),gd(Yh,cd),gd(Xh,cd);const hd={"_prelude_fog.vertex.glsl":Jh,"_prelude_terrain.vertex.glsl":Qh,"_prelude_shadow.vertex.glsl":od,"_prelude_material_table.vertex.glsl":"#ifdef HAS_SHADER_STORAGE_BLOCK_material_buffer\n#define MATERIAL_TABLE_DEBUG 0\nuniform int u_material_offset;uniform int u_vertex_offset;layout(std140,binding=0)readonly buffer material_buffer{uvec4 material_data[];};struct MaterialInfo{uint dataOffset;\n#if MATERIAL_TABLE_DEBUG\nvec4 colorDebug;\n#endif\n};uint read_buf_no_offset(uint iDword) {return material_data[iDword/4u][iDword % 4u];}uint read_buf(uint iDword) {iDword+=uint(u_material_offset/4);return read_buf_no_offset(iDword);}float read_buf_float(uint iDword){return uintBitsToFloat(read_buf(iDword));}uint read_buf_uint8(uint iDword,uint iUint8){uint dwordOffset=iDword+(iUint8/4u);uint byteOffset=iUint8 & 3u;uint bitOffset=8u*byteOffset;uint mask=0xffu << bitOffset;uint dwordVal=read_buf(dwordOffset);return (dwordVal & mask) >> bitOffset;}uint read_buf_uint16(uint iDword,uint iUint16){uint dwordOffset=iDword+(iUint16 >> 1u);uint bitOffset=(iUint16 & 1u)*16u;uint mask=0xffffu << bitOffset;uint dwordVal=read_buf(dwordOffset);return (dwordVal & mask) >> bitOffset;}uint nrDwordsForVertexIdEntries(uint nrMaterialLookupEntries) {return nrMaterialLookupEntries;}uint nrDwordsForMaterialIdEntries(uint nrMaterialLookupEntries) {return (nrMaterialLookupEntries*2u+3u)/4u;}uint findRangeBinarySearch(uint vertexId,uint numRanges,uint dwordOffset) {uint left=0u;uint right=numRanges-1u;for (uint i=0u; i < 16u; i++) { \nif (left > right) {break;}uint mid=(left+right)/2u;uint start=read_buf(dwordOffset+mid);uint nextStart=(mid+1u < numRanges) ? read_buf(dwordOffset+mid+1u) : 0xffffffffu;if (vertexId >=start && vertexId < nextStart) {return mid;} else if (vertexId < start) {if (mid==0u) {break;}right=mid-1u;} else {left=mid+1u;}}return 0u; \n}uint readVertexId(uint dwordOffset,uint iMaterialLookupEntry) {return read_buf(dwordOffset+iMaterialLookupEntry);}uint findRange(uint vertexId,uint numRanges,uint dwordOffset) {uint iRange;if(numRanges <=64u){uint vertexBegin;for(iRange=0u; iRange < numRanges;++iRange) {vertexBegin=readVertexId(dwordOffset,iRange);if(vertexBegin > vertexId) {break;}}iRange=iRange==0u? 0u : iRange-1u;} else { \niRange=findRangeBinarySearch(vertexId,numRanges,dwordOffset);}return iRange;}MaterialInfo read_material_info(uint vertex_id) {MaterialInfo info;\n#if MATERIAL_TABLE_DEBUG\nconst vec4 red=vec4(1.0,0.0,0.0,1.0);const vec4 orange=vec4(1.0,0.5,0.0,1.0);const vec4 yellow=vec4(1.0,1.0,0.0,1.0);const vec4 green=vec4(0.0,1.0,0.0,1.0);const vec4 indigo=vec4(0.294,0.0,0.510,1.0);const vec4 blue=vec4(0.0,0.0,1.0,1.0);const vec4 purple=vec4(0.5,0.0,0.5,1.0);const vec4 pink=vec4(1.0,0.0,1.0,1.0);info.colorDebug=green;\n#endif\nuint offset=0u;\n#if MATERIAL_TABLE_DEBUG\nbool keepFinding=true;uint magic=read_buf(offset);if(magic !=0xCAFEBABEu) {info.colorDebug=red;keepFinding=false;return info;}\n#endif\noffset++;\n#if MATERIAL_TABLE_DEBUG\nuint nrMaterials=read_buf(offset);uint nrVertices=read_buf(offset+1u);if(keepFinding && vertex_id >=nrVertices) {info.colorDebug=red;keepFinding=false;}\n#endif\noffset+=2u;uint nrMaterialLookupEntries=read_buf(offset++);uint perMaterialEntrySizeDwords=read_buf(offset++);\n#if MATERIAL_TABLE_DEBUG\nif(keepFinding && perMaterialEntrySizeDwords !=1u) {info.colorDebug=red;keepFinding=false;}\n#endif\nuint iMaterialLookup=findRange(vertex_id,nrMaterialLookupEntries,offset);\n#if MATERIAL_TABLE_DEBUG\nif(keepFinding)\n{uint vertexBeginCheck=readVertexId(offset,iMaterialLookup);if(vertexBeginCheck > vertex_id) {info.colorDebug=red;keepFinding=false;}if(iMaterialLookup < nrMaterialLookupEntries-1u) {uint vertexEndCheck=readVertexId(offset,iMaterialLookup+1u);if(vertexEndCheck <=vertex_id) {info.colorDebug=red;keepFinding=false;}}}\n#endif\noffset+=nrDwordsForVertexIdEntries(nrMaterialLookupEntries);uint materialId=iMaterialLookup;\n#if MATERIAL_TABLE_DEBUG\nif(keepFinding) {if(materialId >=nrMaterialLookupEntries) {info.colorDebug=red;}}\n#endif\ninfo.dataOffset=offset+materialId*perMaterialEntrySizeDwords;return info;}uint get_data_location(const MaterialInfo matInfo,uint attribOffsetBytes)\n{uint attribFieldOffsetDwords=attribOffsetBytes/4u;return matInfo.dataOffset+attribFieldOffsetDwords;}vec4 read_material_vec4(const MaterialInfo matInfo,uint attribOffsetBytes){uint loc=get_data_location(matInfo,attribOffsetBytes);return vec4(read_buf_float(loc),read_buf_float(loc+1u),read_buf_float(loc+2u),read_buf_float(loc+3u));}vec2 read_material_vec2(const MaterialInfo matInfo,uint attribOffsetBytes){uint loc=get_data_location(matInfo,attribOffsetBytes);return vec2(read_buf_float(loc),read_buf_float(loc+1u));}float read_material_float(const MaterialInfo matInfo,uint attribOffsetBytes){uint loc=get_data_location(matInfo,attribOffsetBytes);return read_buf_float(loc);}\n#define GET_ATTRIBUTE_float(attrib,matInfo,attrib_offset) read_material_float(matInfo,attrib_offset)\n#define GET_ATTRIBUTE_vec4(attrib,matInfo,attrib_offset) read_material_vec4(matInfo,attrib_offset)\n#define GET_ATTRIBUTE_vec2(attrib,matInfo,attrib_offset) read_material_vec2(matInfo,attrib_offset)\n#define DECLARE_MATERIAL_TABLE_INFO MaterialInfo materialInfo=read_material_info(uint(gl_VertexID));\n#define DECLARE_MATERIAL_TABLE_INFO_DEBUG(dbgColor) MaterialInfo materialInfo=read_material_info(uint(gl_VertexID)); dbgColor=materialInfo.colorDebug;\n#endif","_prelude_fog.fragment.glsl":ed,"_prelude_shadow.fragment.glsl":sd,"_prelude_lighting.glsl":"\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","_prelude_raster_array.glsl":td,"_prelude_raster_particle.glsl":id},dd={};vd("",Qh),vd(ed,Jh),vd(sd,od),vd(td,""),vd(id,"");const ud=vd(Xh,Yh),_d=$h,pd=["\n#if defined(GL_EXT_blend_func_extended) && defined(DUAL_SOURCE_BLENDING)\n#extension GL_EXT_blend_func_extended : require\n#endif","precision mediump float;",_d,ud.fragmentSource].join("\n"),fd=["precision highp float;",_d,ud.vertexSource].join("\n"),md={background:vd('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_lighting.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;\n#ifdef USE_MRT1\nout_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a);\n#endif\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}','#include "_prelude_fog.vertex.glsl"\n#include "_prelude_lighting.glsl"\nin vec2 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(a_pos);\n#endif\n}'),backgroundPattern:vd('#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;\n#ifdef USE_MRT1\nout_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a);\n#endif\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 vec2 a_pos;out highp vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_pattern_size,u_pattern_units_to_pixels,a_pos);\n#ifdef FOG\nv_fog_pos=fog_position(a_pos);\n#endif\n}'),building:vd('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_shadow.fragment.glsl"\n#include "_prelude_lighting.glsl"\nconst float window_depth=0.5;const float ao_radius=0.2;in vec4 v_color;in highp vec3 v_normal;in highp vec3 v_pos;\n#ifdef BUILDING_FAUX_FACADE\nin lowp float v_faux_facade;in highp float v_faux_facade_ed;in highp vec2 v_faux_facade_window;in highp vec2 v_faux_facade_floor;in highp vec2 v_faux_facade_range;in highp float v_aspect;in highp vec3 v_tbn_0;in highp vec3 v_tbn_1;in highp vec3 v_tbn_2;in highp vec4 v_faux_color_emissive;uniform float u_faux_facade_ao_intensity;\n#endif\n#ifdef RENDER_SHADOWS\nin highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;\n#endif\n#ifdef FLOOD_LIGHT\nin highp float v_flood_radius;in float v_has_flood_light;\n#endif\nuniform lowp float u_opacity;uniform vec3 u_camera_pos;uniform highp float u_tile_to_meter;uniform float u_facade_emissive_chance;uniform vec3 u_flood_light_color;uniform float u_flood_light_intensity;vec3 linearTosRGB(in vec3 color) {return pow(color,vec3(1./2.2));}\n#ifdef BUILDING_FAUX_FACADE\nfloat hash12(in vec2 p) {vec3 p3 =fract(vec3(p.xyx)*0.1031);p3+=dot(p3,p3.yzx+33.33);return fract((p3.x+p3.y)*p3.z);}float min3(in vec3 v) {return min(min(v.x,v.y),v.z);}vec2 get_uv_mask_id(in vec2 q,out float mask,out vec2 id) {vec2 p=q;mask=step(v_faux_facade_range.x,p.y)*step(p.y,v_faux_facade_range.y);p.y=p.y-v_faux_facade_range.x;vec2 uv=modf(p/v_faux_facade_floor,id);vec4 d=(v_faux_facade_floor.xyxy+vec4(-v_faux_facade_window,v_faux_facade_window))*0.5;vec4 edge=d/v_faux_facade_floor.xyxy;vec2 m=step(edge.xy,uv)*step(uv,edge.zw);mask*=m.x*m.y;uv-=vec2(0.5);uv*=vec2(0.5)/(vec2(0.5)-edge.xy);uv+=vec2(0.5);return uv;}float ray_unit_box(in vec3 ray_o,in vec3 ray_d,in vec3 bmin,in vec3 bmax) {vec3 planes=mix(bmin,bmax,step(0.0,ray_d));vec3 t=(planes-ray_o)/ray_d;return min3(t);}float get_emissive(in vec2 id) {if (u_facade_emissive_chance > 0.0) {return (step(hash12(id),u_facade_emissive_chance)+0.05)*v_faux_color_emissive.a;}return 0.0;}vec3 get_shade_info(in vec3 v,in vec3 v_normalized,in vec3 color,in vec2 id,in mat3 tbn,inout vec3 out_normal,inout float out_emissive) {vec3 out_color=color;vec3 abs_v=abs(v_normalized);bool x_major=abs_v.x >=abs_v.y && abs_v.x >=abs_v.z;bool y_major=abs_v.y >=abs_v.x && abs_v.y >=abs_v.z;bool z_major=abs_v.z >=abs_v.x && abs_v.z >=abs_v.y;\n#if 0\nif (x_major) {out_color=v.x > 0.0 ? vec3(1.0,0.0,0.0) : vec3(0.0,1.0,1.0);} else if (y_major) {out_color=v.y > 0.0 ? vec3(0.0,1.0,0.0) : vec3(1.0,0.0,1.0);} else if (z_major) {out_color=v.z > 0.0 ? vec3(0.0,0.0,1.0) : vec3(1.0,1.0,0.0);}out_emissive=1.0;\n#else\nif (x_major) {out_normal=sign(v.x)*tbn[0];} else if (y_major) {out_normal=vec3(0.0,0.0,-sign(v.y));} else if (z_major) {out_color=v_faux_color_emissive.rgb;out_emissive=v.z <=0.0 ? get_emissive(id) : out_emissive;}float ao=1.0;if (u_faux_facade_ao_intensity > 0.0) {vec4 ao_range=v_faux_facade_window.xxyy*0.5-vec4(0,ao_radius,0,ao_radius);vec2 ao_range_z=vec2(window_depth*0.5)-vec2(0.0,ao_radius);if (x_major || y_major) {ao*=smoothstep(-ao_range_z.x,-ao_range_z.y,v.z);} else if (z_major) {ao*=smoothstep(-ao_range.x,-ao_range.y,v.x)*(1.0-smoothstep(ao_range.y,ao_range.x,v.x));ao*=smoothstep(-ao_range.z,-ao_range.w,v.y)*(1.0-smoothstep(ao_range.w,ao_range.z,v.y));}ao=mix(1.0,min(1.0,ao+0.25),u_faux_facade_ao_intensity);}out_color*=ao;\n#endif\nreturn out_color;}\n#endif\nvec3 apply_lighting_linear(in vec3 color,in vec3 normal,in 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 color*(ambient_contrib+directional_contrib);}void main() {vec3 normal=normalize(v_normal);vec3 base_color=v_color.rgb;float emissive=v_color.a;\n#ifdef BUILDING_FAUX_FACADE\nif (v_faux_facade > 0.0) {mat3 tbn=mat3(v_tbn_0,v_tbn_1,v_tbn_2);vec3 v=vec3(v_pos.xy,v_pos.z/u_tile_to_meter)-u_camera_pos;vec3 view_tangent=transpose(tbn)*v;vec2 q=vec2(v_faux_facade_ed,v_pos.z);float mask=0.0;vec2 id=vec2(0.0);vec2 uv=get_uv_mask_id(q,mask,id);uv*=v_faux_facade_window;vec3 bmin=vec3(0.0,0.0,-window_depth);vec3 bmax=bmin+vec3(v_faux_facade_window,window_depth);vec3 ray_o=vec3(uv,0.0);vec3 ray_d=normalize(view_tangent);float t_min=ray_unit_box(ray_o,ray_d,bmin,bmax);vec3 hit=ray_o+t_min*ray_d;vec3 r=vec3(v_faux_facade_window,-window_depth);hit-=r*0.5;vec3 normalized=hit/r;vec3 out_normal=normal;float out_emissive=emissive;vec3 room_color=get_shade_info(hit,normalized,base_color,id,tbn,out_normal,out_emissive);base_color=mix(base_color,room_color,mask);normal=mix(normal,out_normal,mask);emissive=mix(emissive,out_emissive,mask);}\n#endif\nvec4 color=vec4(base_color,1.0);vec3 xy_flipped_normal=vec3(-normal.xy,normal.z);float shadowed_lighting_factor=0.0;\n#ifdef RENDER_SHADOWS\n#ifdef RENDER_CUTOFF\nshadowed_lighting_factor=shadowed_light_factor_normal_opacity(xy_flipped_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(xy_flipped_normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w);\n#endif\n#else\nshadowed_lighting_factor=dot(xy_flipped_normal,u_lighting_directional_dir);\n#endif\ncolor.rgb=apply_lighting_linear(color.rgb,xy_flipped_normal,shadowed_lighting_factor);color.rgb=linearTosRGB(color.rgb);\n#ifdef FLOOD_LIGHT\nfloat flood_radiance=(1.0-min(v_pos.z/v_flood_radius,1.0))*u_flood_light_intensity*v_has_flood_light;color.rgb=mix(color.rgb,u_flood_light_color,flood_radiance);\n#endif\ncolor.rgb=mix(color.rgb,linearTosRGB(base_color.rgb),emissive);\n#ifdef FOG\ncolor=fog_dither(fog_apply_premultiplied(color,v_fog_pos,v_pos.z));\n#endif\ncolor*=u_opacity;\n#ifdef INDICATOR_CUTOUT\ncolor=applyCutout(color,v_pos.z);\n#endif\n#ifdef FEATURE_CUTOUT\ncolor=apply_feature_cutout(color,gl_FragCoord);\n#endif\nglFragColor=color; \n#ifdef DEBUG_SHOW_NORMALS\ncolor.rgb=xy_flipped_normal*0.5+vec3(0.5,0.5,0.5);color.a=1.0;glFragColor=color;\n#endif\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 vec3 a_pos_3f;in vec3 a_normal_3;in vec3 a_centroid_3;in float a_flood_light_wall_radius_1i16;in vec4 a_faux_facade_data;in vec2 a_faux_facade_vertical_range;uniform mat4 u_matrix;uniform mat4 u_normal_matrix;uniform highp float u_tile_to_meter;out vec4 v_color;out vec3 v_normal;out highp vec3 v_pos;\n#ifdef BUILDING_FAUX_FACADE\nout lowp float v_faux_facade;out highp float v_faux_facade_ed;out highp vec2 v_faux_facade_window;out highp vec2 v_faux_facade_floor;out highp vec2 v_faux_facade_range;out highp float v_aspect;out highp vec3 v_tbn_0;out highp vec3 v_tbn_1;out highp vec3 v_tbn_2;out highp vec4 v_faux_color_emissive;\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;\n#endif\n#ifdef FLOOD_LIGHT\nout highp float v_flood_radius;out float v_has_flood_light;\n#endif\nconst float MAX_UINT_16=65535.0;const float MAX_INT_16=32767.0;const float MAX_UINT_8=255.0;const float TWO_POW_8=256.0;const float FLOOD_LIGHT_MAX_RADIUS_METER=2048.0;vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));}\n#ifdef BUILDING_FAUX_FACADE\nmat3 get_tbn(in vec3 normal) {const vec3 bitangent=vec3(0.0,0.0,1.0);vec3 tangent=normalize(vec3(normal.y,-normal.x,0.0));return mat3(tangent,bitangent,normal);}\n#endif\n#pragma mapbox: define-attribute-vertex-shader-only highp vec2 part_color_emissive\n#pragma mapbox: define-attribute-vertex-shader-only highp vec2 faux_facade_color_emissive\nvoid main() {\n#pragma mapbox: initialize-attribute-custom highp vec2 part_color_emissive\n#pragma mapbox: initialize-attribute-custom highp vec2 faux_facade_color_emissive\n#ifdef FLOOD_LIGHT\nv_flood_radius=(a_flood_light_wall_radius_1i16/MAX_INT_16*FLOOD_LIGHT_MAX_RADIUS_METER);v_has_flood_light=step(0.0,v_flood_radius);\n#endif\nvec4 color_emissive=decode_color(part_color_emissive);v_color=vec4(sRGBToLinear(color_emissive.rgb),color_emissive.a);vec3 a_normal_3f=a_normal_3/MAX_INT_16;v_normal=vec3(u_normal_matrix*vec4(a_normal_3f,0.0));float hidden=0.0;float depth_offset=0.0;\n#ifdef BUILDING_FAUX_FACADE\nv_faux_facade=a_faux_facade_data.x;if (v_faux_facade > 0.0) {v_faux_facade_ed=a_faux_facade_data.x *u_tile_to_meter;float window_x_perc=floor(a_faux_facade_data.y/TWO_POW_8);float window_y_perc=a_faux_facade_data.y-TWO_POW_8*window_x_perc;vec2 window_perc=vec2(window_x_perc,window_y_perc)/MAX_UINT_8;v_faux_facade_floor=(a_faux_facade_data.zw/MAX_UINT_16*EXTENT)*u_tile_to_meter;v_faux_facade_window=window_perc*v_faux_facade_floor;v_faux_facade_range=(a_faux_facade_vertical_range/MAX_UINT_16*EXTENT)*u_tile_to_meter;v_aspect=v_faux_facade_window.x/v_faux_facade_window.y;mat3 tbn=get_tbn(normalize(v_normal));v_tbn_0=tbn[0];v_tbn_1=tbn[1];v_tbn_2=tbn[2];v_faux_color_emissive=decode_color(faux_facade_color_emissive);v_faux_color_emissive.rgb=sRGBToLinear(v_faux_color_emissive.rgb);float height=a_centroid_3.z;depth_offset=min(1000.0,height)*0.0000002;}\n#endif\nv_pos=a_pos_3f;\n#ifdef RENDER_CUTOFF\nvec4 ground=u_matrix*vec4(a_centroid_3,1.0);v_cutoff_opacity=cutoff_opacity(u_cutoff_params,ground.z);hidden=float(v_cutoff_opacity==0.0);v_pos.z*=v_cutoff_opacity;\n#endif\n#ifdef RENDER_SHADOWS\nvec3 shadow_pos=v_pos;\n#ifdef NORMAL_OFFSET\nvec3 offset=shadow_normal_offset_model(v_normal);shadow_pos+=offset*shadow_normal_offset_multiplier0();\n#endif\nv_pos_light_view_0=u_light_matrix_0*vec4(shadow_pos,1.0);v_pos_light_view_1=u_light_matrix_1*vec4(shadow_pos,1.0);\n#endif\n#ifdef FOG\nv_fog_pos=fog_position(v_pos);\n#endif\ngl_Position=mix(u_matrix*vec4(v_pos,1),AWAY,hidden);gl_Position.z-=depth_offset*gl_Position.w;}'),buildingBloom:vd("in vec4 v_color_emissive;\n#pragma mapbox: define-attribute highp vec4 bloom_attenuation\n#pragma mapbox: initialize-attribute highp vec4 bloom_attenuation\nfloat saturate(float val) {return clamp(val,0.0,1.0);}void main() {float emission=v_color_emissive.a;float opacity=1.0;\n#ifdef HAS_ATTRIBUTE_a_bloom_attenuation\nfloat distance=length(vec2(1.3*max(0.0,abs(bloom_attenuation.x)-bloom_attenuation.z),bloom_attenuation.y));distance+= mix(0.5,0.0,clamp(emission-1.0,0.0,1.0));opacity*=saturate(1.0-distance*distance);\n#endif\n#ifdef RENDER_CUTOFF\nopacity*=v_cutoff_opacity;\n#endif\nglFragColor=vec4(v_color_emissive.rgb,1.0)*opacity;}","in vec3 a_pos_3f;\n#pragma mapbox: define-attribute-vertex-shader-only highp vec2 part_color_emissive\n#pragma mapbox: define-attribute highp vec4 bloom_attenuation\nout vec4 v_color_emissive;uniform mat4 u_matrix;vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));}void main() {\n#pragma mapbox: initialize-attribute-custom highp vec2 part_color_emissive\n#pragma mapbox: initialize-attribute highp vec4 bloom_attenuation\n#ifdef HAS_ATTRIBUTE_a_part_color_emissive\nvec4 color_emissive=decode_color(part_color_emissive);float part_emissive=color_emissive.a*5.0;v_color_emissive=vec4(sRGBToLinear(color_emissive.rgb),part_emissive);\n#else\nv_color_emissive=vec4(1.0);\n#endif\ngl_Position=u_matrix*vec4(a_pos_3f,1.0);\n#ifdef RENDER_CUTOFF\nv_cutoff_opacity=cutoff_opacity(u_cutoff_params,gl_Position.z);\n#endif\n}"),buildingDepth:vd("in highp float v_depth;void main() {\n#ifndef DEPTH_TEXTURE\nglFragColor=pack_depth(v_depth);\n#endif\n}","in vec3 a_pos_3f;uniform mat4 u_matrix;out highp float v_depth;void main() {gl_Position=u_matrix*vec4(a_pos_3f,1.0);v_depth=gl_Position.z/gl_Position.w;}"),circle:vd('#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_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 vec2 a_pos;\n#ifdef PROJECTION_GLOBE_VIEW\nin vec3 a_pos_3;in vec3 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 view_scale) {return extrusion*(radius+stroke_width)*u_extrude_scale*view_scale;}float cantilevered_elevation(vec2 pos,float radius,float stroke_width,float view_scale) {vec2 c1=pos+calc_offset(vec2(-1,-1),radius,stroke_width,view_scale);vec2 c2=pos+calc_offset(vec2(1,-1),radius,stroke_width,view_scale);vec2 c3=pos+calc_offset(vec2(1,1),radius,stroke_width,view_scale);vec2 c4=pos+calc_offset(vec2(-1,1),radius,stroke_width,view_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 view_scale,mat3 surface_vectors) {vec2 sample_offset=calc_offset(extrusion,radius,stroke_width,view_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}float get_sample_step() {\n#ifdef PITCH_WITH_MAP\nreturn 2.0*PI/float(NUM_SAMPLES_PER_RING);\n#else\nreturn PI/float(NUM_SAMPLES_PER_RING);\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 extrude=vec2(mod(a_pos,2.0)*2.0-1.0);vec2 circle_center=floor(a_pos*0.5);vec4 world_center;mat3 surface_vectors;\n#ifdef PROJECTION_GLOBE_VIEW\nvec3 pos_normal_3=a_pos_normal_3/16384.0;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(circle_center)*circle_elevation(circle_center);vec3 globe_pos=a_pos_3+surface_extrusion+globe_elevation;vec3 mercator_elevation=u_up_dir*u_tile_up_scale*circle_elevation(circle_center);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);float height=circle_elevation(circle_center);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 view_scale=0.0;\n#ifdef PITCH_WITH_MAP\n#ifdef SCALE_WITH_MAP\nview_scale=1.0;\n#else\nview_scale=projected_center.w/u_camera_to_center_distance;\n#endif\n#else\n#ifdef SCALE_WITH_MAP\nview_scale=u_camera_to_center_distance;\n#else\nview_scale=projected_center.w;\n#endif\n#endif\ngl_Position=project_vertex(extrude,world_center,projected_center,radius,stroke_width,view_scale,surface_vectors);float visibility=0.0;\n#ifdef TERRAIN\nfloat step=get_sample_step();vec4 occlusion_world_center;vec4 occlusion_projected_center;\n#ifdef PITCH_WITH_MAP\nfloat cantilevered_height=cantilevered_elevation(circle_center,radius,stroke_width,view_scale);occlusion_world_center=vec4(circle_center,cantilevered_height,1);occlusion_projected_center=u_matrix*occlusion_world_center;\n#else\nocclusion_world_center=world_center;occlusion_projected_center=projected_center;\n#endif\nfor(int ring=0; ring < NUM_VISIBILITY_RINGS; ring++) {float scale=(float(ring)+1.0)/float(NUM_VISIBILITY_RINGS);for(int i=0; i < NUM_SAMPLES_PER_RING; i++) {vec2 extrusion=vec2(cos(step*float(i)),-sin(step*float(i)))*scale;vec4 frag_pos=project_vertex(extrusion,occlusion_world_center,occlusion_projected_center,radius,stroke_width,view_scale,surface_vectors);visibility+=float(!isOccluded(frag_pos));}}visibility/=float(NUM_VISIBILITY_RINGS)*float(NUM_SAMPLES_PER_RING);\n#else\nvisibility=1.0;\n#endif\n#ifdef PROJECTION_GLOBE_VIEW\nvisibility=1.0;\n#endif\nv_visibility=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:vd("void main() {glFragColor=vec4(1.0);}","in vec2 a_pos;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);}"),heatmap:vd('#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_opacity;uniform float u_intensity;in vec2 a_pos;\n#ifdef PROJECTION_GLOBE_VIEW\nin vec3 a_pos_3;in vec3 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(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(a_pos*0.5);vec3 pos;\n#ifdef PROJECTION_GLOBE_VIEW\nvec3 pos_normal_3=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=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:vd("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 vec2 a_pos;out vec2 v_pos;void main() {gl_Position=vec4(a_pos,0,1);v_pos=a_pos*0.5+0.5;}"),collisionBox:vd("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 vec3 a_pos;in vec2 a_anchor_pos;in vec2 a_extrude;in vec2 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() {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(a_anchor_pos));vec3 proj_pos=a_pos+elevationVector(a_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,a_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+=(a_extrude*a_size_scale+a_shift+a_padding)*u_extrude_scale*gl_Position.w*collision_perspective_ratio;v_placed=a_placed.x;v_notUsed=a_placed.y;}'),collisionCircle:vd("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 vec2 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 quadCenterPos=a_pos_2f;float radius=a_radius;float collision=a_flags.x;float vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(\nmix(-1.0,1.0,float(vertexIdx >=2.0)),mix(-1.0,1.0,float(vertexIdx >=1.0 && vertexIdx <=2.0)));vec2 quadVertexExtent=quadVertexOffset*radius;vec3 tilePos=toTilePosition(quadCenterPos);vec4 clipPos=u_matrix*vec4(tilePos,1.0);highp float camera_to_anchor_distance=clipPos.w;highp float collision_perspective_ratio=clamp(\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=collision;gl_Position=vec4(clipPos.xyz/clipPos.w,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}"),debug:vd("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 vec2 a_pos;\n#ifdef PROJECTION_GLOBE_VIEW\nin vec3 a_pos_3;\n#endif\nout vec2 v_uv;uniform mat4 u_matrix;uniform float u_overlay_scale;void main() {float h=elevation(a_pos);v_uv=a_pos/8192.0;\n#ifdef PROJECTION_GLOBE_VIEW\ngl_Position=u_matrix*vec4(a_pos_3+elevationVector(a_pos)*h,1);\n#else\ngl_Position=u_matrix*vec4(a_pos*u_overlay_scale,h,1);\n#endif\n}'),elevatedStructuresDepth:vd("void main() {\n#ifndef DEPTH_TEXTURE\nglFragColor=vec4(0.);\n#endif\n}","in vec2 a_pos;in float a_height;uniform mat4 u_matrix;uniform float u_depth_bias;void main() {gl_Position=u_matrix*vec4(a_pos,a_height,1);gl_Position.z=gl_Position.z+u_depth_bias;}"),elevatedStructuresDepthReconstruct:vd("#ifdef DEPTH_RECONSTRUCTION\nin float v_height;\n#endif\nvoid main() {\n#ifdef DEPTH_RECONSTRUCTION\nif (v_height >=0.0)\ndiscard;\n#else\n#ifdef FEATURE_CUTOUT\napply_feature_cutout(vec4(0.0,0.0,0.0,1.0),gl_FragCoord);\n#endif\n#endif\nglFragColor=vec4(1.0,0.0,0.0,1.0);}","in vec2 a_pos;in float a_height;uniform mat4 u_matrix;uniform vec3 u_camera_pos;uniform highp float u_depth_bias;uniform lowp float u_height_scale;uniform lowp float u_reset_depth;\n#ifdef DEPTH_RECONSTRUCTION\nout float v_height;\n#endif\nvoid main() {vec3 vpos=vec3(a_pos,a_height*u_height_scale);\n#ifdef DEPTH_RECONSTRUCTION\nif (u_camera_pos.z > vpos.z) {vpos-=(u_camera_pos-vpos)*(vpos.z/(u_camera_pos.z-vpos.z));}v_height=a_height;\n#endif\ngl_Position=u_matrix*vec4(vpos,1);gl_Position.z=u_reset_depth==1.0 ? gl_Position.w : gl_Position.z+u_depth_bias;}"),elevatedStructures:vd('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_lighting.glsl"\n#include "_prelude_shadow.fragment.glsl"\nin vec3 v_normal;in float v_height;\n#ifdef RENDER_SHADOWS\nin highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in float v_depth;\n#endif\nvec3 linearTosRGB(vec3 color) {return pow(color,vec3(1./2.2));}vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));}vec3 compute_view_dependent_emissive_color(float ndotl,float emissive_strength,vec3 color)\n{color=sRGBToLinear(color);color=color*(ndotl+(1.0-min(ndotl*57.29,1.0))*emissive_strength);color=linearTosRGB(color.rgb);return color;}uniform float u_emissive_strength;\n#pragma mapbox: define highp vec4 structure_color\nvoid main() {\n#pragma mapbox: initialize highp vec4 structure_color\nvec3 color=structure_color.xyz;\n#ifdef LIGHTING_3D_MODE\nvec3 normal=normalize(v_normal);vec3 transformed_normal=vec3(-normal.xy,normal.z);float ndotl=calculate_NdotL(transformed_normal);float emissive_strength=u_emissive_strength;emissive_strength=0.0;vec3 emissive_color=compute_view_dependent_emissive_color(ndotl,emissive_strength,color.xyz);\n#ifdef RENDER_SHADOWS\nfloat shadowed_lighting_factor=shadowed_light_factor_normal(transformed_normal,v_pos_light_view_0,v_pos_light_view_1,v_depth);color.rgb=apply_lighting(color.rgb,transformed_normal,shadowed_lighting_factor);\n#else\ncolor=apply_lighting(color,transformed_normal);\n#endif\ncolor=mix(color,emissive_color,emissive_strength);if (v_height < 0.0) {float penetration=max(v_height+7.5,0.0);float occlusion=1.0-1.0/PI*acos(1.0-penetration/4.0);color=color*(1.0-pow(occlusion,2.0)*0.3);}\n#endif\n#ifdef FOG\ncolor=fog_apply(color,v_fog_pos);\n#endif\nvec4 out_color=vec4(color,1.0);\n#ifdef INDICATOR_CUTOUT\nout_color=applyCutout(out_color,v_height);\n#endif\n#ifdef FEATURE_CUTOUT\nout_color=apply_feature_cutout(out_color,gl_FragCoord);\n#endif\nglFragColor=out_color;HANDLE_WIREFRAME_DEBUG;}','#include "_prelude_fog.vertex.glsl"\n#include "_prelude_shadow.vertex.glsl"\nin vec2 a_pos;in float a_height;in vec3 a_pos_normal_3;uniform mat4 u_matrix;out vec3 v_normal;out float v_height;\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 float v_depth;\n#endif\n#pragma mapbox: define highp vec4 structure_color\nvoid main() {\n#pragma mapbox: initialize highp vec4 structure_color\nv_normal=a_pos_normal_3/16384.0;v_height=a_height;vec3 pos=vec3(a_pos,a_height);gl_Position=u_matrix*vec4(pos,1);\n#ifdef RENDER_SHADOWS\nvec3 shd_pos0=pos;vec3 shd_pos1=pos;\n#ifdef NORMAL_OFFSET\nvec3 offset=shadow_normal_offset(vec3(-v_normal.xy,v_normal.z));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(a_pos);\n#endif\n}'),fill:vd('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_lighting.glsl"\n#include "_prelude_shadow.fragment.glsl"\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nuniform float u_emissive_strength;\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 INDICATOR_CUTOUT\nin highp float v_z_offset;\n#endif\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\nvec4 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);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;\n#ifdef INDICATOR_CUTOUT\nif (v_z_offset >=0.0) {out_color=applyCutout(out_color,v_z_offset);}\n#endif\n#ifdef FEATURE_CUTOUT\nout_color=apply_feature_cutout(out_color,gl_FragCoord);\n#endif\nglFragColor=out_color;\n#ifdef USE_MRT1\nout_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a);\n#endif\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 vec2 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\n#ifdef INDICATOR_CUTOUT\nout highp float v_z_offset;\n#endif\nuniform mat4 u_matrix;\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(a_pos);\n#endif\n#ifdef INDICATOR_CUTOUT\nv_z_offset=z_offset;\n#endif\n}'),fillOutline:vd('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_lighting.glsl"\n#include "_prelude_shadow.fragment.glsl"\nin highp vec2 v_pos;uniform float u_emissive_strength;\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;\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);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\n#ifdef FEATURE_CUTOUT\nout_color=apply_feature_cutout(out_color,gl_FragCoord);\n#endif\nglFragColor=out_color*(alpha*opacity);\n#ifdef USE_MRT1\nout_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a);\n#endif\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 vec2 a_pos;\n#ifdef ELEVATED_ROADS\nin float a_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;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;\n#endif\nfloat hidden=float(opacity==0.0);gl_Position=mix(u_matrix*vec4(a_pos,z_offset,1),AWAY,hidden);\n#ifdef FLIP_Y\nv_pos=(vec2(gl_Position.x,-gl_Position.y)/gl_Position.w+1.0)/2.0*u_world;\n#else\nv_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\n#endif\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(a_pos);\n#endif\n}'),fillOutlinePattern:vd('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_lighting.glsl"\n#include "_prelude_shadow.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;\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\nin highp vec2 v_pos;in highp vec2 v_pos_world;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern\n#ifdef FILL_PATTERN_TRANSITION\n#pragma mapbox: define mediump vec4 pattern_b\n#endif\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern\n#ifdef FILL_PATTERN_TRANSITION\n#pragma mapbox: initialize mediump vec4 pattern_b\n#endif\nvec2 pattern_tl=pattern.xy;vec2 pattern_br=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=pattern_b.xy;vec2 pattern_b_br=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_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);out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light);\n#endif\n#endif\n#ifdef FEATURE_CUTOUT\nout_color=apply_feature_cutout(out_color,gl_FragCoord);\n#endif\n#ifdef FOG\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\n#endif\nglFragColor=out_color*(alpha*opacity);\n#ifdef USE_MRT1\nout_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a);\n#endif\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 vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_tile_units_to_pixels;in vec2 a_pos;\n#ifdef ELEVATED_ROADS\nin float a_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 vec4 pattern\n#ifdef FILL_PATTERN_TRANSITION\n#pragma mapbox: define mediump vec4 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 vec4 pattern\n#ifdef FILL_PATTERN_TRANSITION\n#pragma mapbox: initialize mediump vec4 pattern_b\n#endif\n#pragma mapbox: initialize lowp float pixel_ratio\n#pragma mapbox: initialize highp float z_offset\nvec2 pattern_tl=pattern.xy;vec2 pattern_br=pattern.zw;\n#ifdef ELEVATED_ROADS\nz_offset+=a_road_z_offset;\n#endif\nfloat hidden=float(opacity==0.0);gl_Position=mix(u_matrix*vec4(a_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,a_pos);\n#ifdef FLIP_Y\nv_pos_world=(vec2(gl_Position.x,-gl_Position.y)/gl_Position.w+1.0)/2.0*u_world;\n#else\nv_pos_world=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\n#endif\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(a_pos);\n#endif\n}'),fillPattern:vd('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_lighting.glsl"\n#include "_prelude_shadow.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;\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 vec4 pattern\n#ifdef FILL_PATTERN_TRANSITION\n#pragma mapbox: define mediump vec4 pattern_b\n#endif\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern\n#ifdef FILL_PATTERN_TRANSITION\n#pragma mapbox: initialize mediump vec4 pattern_b\n#endif\nvec2 pattern_tl=pattern.xy;vec2 pattern_br=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=pattern_b.xy;vec2 pattern_b_br=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_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);\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 FEATURE_CUTOUT\nout_color=apply_feature_cutout(out_color,gl_FragCoord);\n#endif\n#ifdef FOG\nout_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos));\n#endif\nglFragColor=out_color*opacity;\n#ifdef USE_MRT1\nout_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a);\n#endif\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_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_tile_units_to_pixels;in vec2 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 vec4 pattern\n#ifdef FILL_PATTERN_TRANSITION\n#pragma mapbox: define mediump vec4 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 vec4 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 vec4 pattern_b\n#endif\nvec2 pattern_tl=pattern.xy;vec2 pattern_br=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);gl_Position=mix(u_matrix*vec4(a_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,a_pos);\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(a_pos);\n#endif\n}'),fillExtrusion:vd('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_shadow.fragment.glsl"\n#include "_prelude_lighting.glsl"\nin vec4 v_color;in vec4 v_flat;\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#ifdef INDICATOR_CUTOUT\ncolor=applyCutout(color,h);\n#endif\n#ifdef FEATURE_CUTOUT\ncolor=apply_feature_cutout(color,gl_FragCoord);\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"\nuniform mat4 u_matrix;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform float u_edge_radius;uniform float u_width_scale;in vec4 a_pos_normal_ed;in vec2 a_centroid_pos;\n#ifdef RENDER_WALL_MODE\nin vec3 a_join_normal_inside;\n#endif\n#ifdef PROJECTION_GLOBE_VIEW\nin vec3 a_pos_3;in vec3 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;out 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;\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 pos_nx=floor(a_pos_normal_ed*0.5);vec4 top_up_ny_start=a_pos_normal_ed-2.0*pos_nx;vec3 top_up_ny=top_up_ny_start.xyz;float x_normal=pos_nx.z/8192.0;vec3 normal=top_up_ny.y==1.0 ? vec3(0.0,0.0,1.0) : normalize(vec3(x_normal,(2.0*top_up_ny.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.y==0.0 && top_up_ny.x==1.0 ? height-u_edge_radius : height);float t=top_up_ny.x;vec2 centroid_pos=vec2(0.0);\n#if defined(HAS_CENTROID) || defined(TERRAIN)\ncentroid_pos=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);c_ele=is_flat_height || is_flat_base ? (centroid_pos.y==0.0 ? 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;pos=vec3(pos_nx.xy,h);\n#else\nh=t > 0.0 ? height : base;pos=vec3(pos_nx.xy,h);\n#endif\n#ifdef PROJECTION_GLOBE_VIEW\nfloat lift=float((t+base) > 0.0)*u_height_lift;h+=lift;vec3 globe_normal=normalize(mix(a_pos_normal_3/16384.0,u_up_dir,u_zoom_transition));vec3 globe_pos=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#ifdef RENDER_CUTOFF\nvec3 centroid_random=vec3(centroid_pos.xy,centroid_pos.x+centroid_pos.y+1.0);vec3 ground_pos=centroid_pos.x==0.0 ? pos.xyz : (centroid_random/8.0);vec4 ground=u_matrix*vec4(ground_pos.xy,ele,1.0);\n#ifdef CLIP_ZERO_TO_ONE\ncutoff=cutoff_opacity(u_cutoff_params,ground.z*2.0-ground.w);\n#else\ncutoff=cutoff_opacity(u_cutoff_params,ground.z);\n#endif\nif (centroid_pos.y !=0.0 && centroid_pos.x !=0.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_WALL_MODE\nvec2 wall_offset=u_width_scale*line_width*(a_join_normal_inside.xy/EXTENT);scaled_pos.xy+=(1.0-a_join_normal_inside.z)*wall_offset*0.5;scaled_pos.xy-=a_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.y)*u_ao[0]);\n#ifdef PROJECTION_GLOBE_VIEW\ntop_height+=u_height_lift;\n#endif\ngl_Position.z-=(0.0000006*(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.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}'),fillExtrusionDepth:vd("in highp float v_depth;void main() {\n#ifndef DEPTH_TEXTURE\nglFragColor=pack_depth(v_depth);\n#endif\n}",'#include "_prelude_terrain.vertex.glsl"\n#include "_prelude_material_table.vertex.glsl"\nuniform mat4 u_matrix;uniform float u_edge_radius;uniform float u_width_scale;uniform float u_vertical_scale;\n#ifdef TERRAIN\nuniform int u_height_type;uniform int u_base_type;\n#endif\nin vec4 a_pos_normal_ed;in vec2 a_centroid_pos;\n#ifdef RENDER_WALL_MODE\nin vec3 a_join_normal_inside;\n#endif\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define highp float line_width\n#pragma mapbox: define highp vec4 color\nout highp float v_depth;void main() {DECLARE_MATERIAL_TABLE_INFO\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize highp float line_width\n#pragma mapbox: initialize highp vec4 color\nbase*=u_vertical_scale;height*=u_vertical_scale;vec3 pos_nx=floor(a_pos_normal_ed.xyz*0.5);mediump vec3 top_up_ny=a_pos_normal_ed.xyz-2.0*pos_nx;base=max(0.0,base);height=max(0.0,top_up_ny.y==0.0 && top_up_ny.x==1.0 ? height-u_edge_radius : height);float t=top_up_ny.x;vec2 centroid_pos=vec2(0.0);\n#if defined(HAS_CENTROID) || defined(TERRAIN)\ncentroid_pos=a_centroid_pos;\n#endif\nvec3 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;float ele=elevation(pos_nx.xy);float c_ele=is_flat_height || is_flat_base ? (centroid_pos.y==0.0 ? 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);float h=t > 0.0 ? max(h_base,h_height) : h_base;pos=vec3(pos_nx.xy,h);\n#else\npos=vec3(pos_nx.xy,t > 0.0 ? height : base);\n#endif\n#ifdef RENDER_WALL_MODE\nvec2 wall_offset=u_width_scale*line_width*(a_join_normal_inside.xy/EXTENT);pos.xy+=(1.0-a_join_normal_inside.z)*wall_offset*0.5;pos.xy-=a_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(pos,1),AWAY,hidden);v_depth=gl_Position.z/gl_Position.w;}'),fillExtrusionPattern:vd('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_lighting.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 vec4 pattern\n#ifdef FILL_EXTRUSION_PATTERN_TRANSITION\n#pragma mapbox: define mediump vec4 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 vec4 pattern\n#ifdef FILL_EXTRUSION_PATTERN_TRANSITION\n#pragma mapbox: initialize mediump vec4 pattern_b\n#endif\n#pragma mapbox: initialize highp float pixel_ratio\nvec2 pattern_tl=pattern.xy;vec2 pattern_br=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=pattern_b.xy;vec2 pattern_b_br=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\n#ifdef INDICATOR_CUTOUT\nout_color=applyCutout(out_color,height);\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;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;in vec4 a_pos_normal_ed;in vec2 a_centroid_pos;\n#ifdef RENDER_WALL_MODE\nin vec3 a_join_normal_inside;\n#endif\n#ifdef PROJECTION_GLOBE_VIEW\nin vec3 a_pos_3;in vec3 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;\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 vec4 pattern\n#ifdef FILL_EXTRUSION_PATTERN_TRANSITION\n#pragma mapbox: define mediump vec4 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 vec4 pattern\n#ifdef FILL_EXTRUSION_PATTERN_TRANSITION\n#pragma mapbox: initialize mediump vec4 pattern_b\n#endif\n#pragma mapbox: initialize highp float pixel_ratio\n#pragma mapbox: initialize highp float line_width\nvec2 pattern_tl=pattern.xy;vec2 pattern_br=pattern.zw;vec4 pos_nx=floor(a_pos_normal_ed*0.5);mediump vec4 top_up_ny_start=a_pos_normal_ed-2.0*pos_nx;mediump vec3 top_up_ny=top_up_ny_start.xyz;float x_normal=pos_nx.z/8192.0;vec3 normal=top_up_ny.y==1.0 ? vec3(0.0,0.0,1.0) : normalize(vec3(x_normal,(2.0*top_up_ny.z-1.0)*(1.0-abs(x_normal)),0.0));float edgedistance=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.x;float z=t > 0.0 ? height : base;vec2 centroid_pos=vec2(0.0);\n#if defined(HAS_CENTROID) || defined(TERRAIN)\ncentroid_pos=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);c_ele=is_flat_height || is_flat_base ? (centroid_pos.y==0.0 ? 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(a_pos_normal_3/16384.0,u_up_dir,u_zoom_transition));vec3 globe_pos=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\nvec2 wall_offset=u_width_scale*line_width*(a_join_normal_inside.xy/EXTENT);p.xy+=(1.0-a_join_normal_inside.z)*wall_offset*0.5;p.xy-=a_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.y)*u_ao[0]);\n#ifdef PROJECTION_GLOBE_VIEW\ntop_height+=u_height_lift;\n#endif\ngl_Position.z-=(0.0000006*(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}'),groundShadow:vd('#include "_prelude_shadow.fragment.glsl"\nprecision highp float;uniform vec3 u_ground_shadow_factor;in vec4 v_pos_light_view_0;in vec4 v_pos_light_view_1;\n#ifdef FOG\nin float v_fog_opacity;\n#endif\nvoid main() {float light=shadowed_light_factor_plane_bias(v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w);vec3 shadow=mix(u_ground_shadow_factor,vec3(1.0),light);\n#ifdef RENDER_CUTOFF\nshadow=mix(vec3(1.0),shadow,cutoff_opacity(u_cutoff_params,1.0/gl_FragCoord.w));\n#endif\n#ifdef FOG\nshadow=mix(shadow,vec3(1.0),v_fog_opacity);\n#endif\n#ifdef INDICATOR_CUTOUT\nshadow=mix(shadow,vec3(1.0),1.0-applyCutout(vec4(1.0),0.0).r);\n#endif\nglFragColor=vec4(shadow,1.0);}','#include "_prelude_fog.vertex.glsl"\nuniform mat4 u_matrix;uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;in vec2 a_pos;out vec4 v_pos_light_view_0;out vec4 v_pos_light_view_1;\n#ifdef FOG\nout float v_fog_opacity;\n#endif\nvoid main() {gl_Position=u_matrix*vec4(a_pos,0.0,1.0);v_pos_light_view_0=u_light_matrix_0*vec4(a_pos,0.0,1.0);v_pos_light_view_1=u_light_matrix_1*vec4(a_pos,0.0,1.0);\n#ifdef FOG\nv_fog_pos=fog_position(a_pos);v_fog_opacity=fog(v_fog_pos);\n#endif\n}'),fillExtrusionGroundEffect:vd("uniform highp float u_ao_pass;uniform highp float u_opacity;uniform highp float u_flood_light_intensity;uniform highp vec3 u_flood_light_color;uniform highp float u_attenuation;uniform sampler2D u_fb;uniform float u_fb_size;\n#ifdef SDF_SUBPASS\nin highp vec2 v_pos;in highp vec4 v_line_segment;in highp float v_flood_light_radius_tile;in highp vec2 v_ao;float line_df(highp vec2 a,highp vec2 b,highp vec2 p) {highp vec2 ba=b-a;highp vec2 pa=p-a;highp float r=clamp(dot(pa,ba)/dot(ba,ba),0.0,1.0);return length(pa-r*ba);}\n#ifdef FOG\nin highp float v_fog;\n#endif\n#endif\nvoid main() {\n#ifdef CLEAR_SUBPASS\nvec4 color=vec4(1.0);\n#ifdef CLEAR_FROM_TEXTURE\ncolor=texture(u_fb,gl_FragCoord.xy/vec2(u_fb_size));\n#endif\nglFragColor=color;\n#else\n#ifdef SDF_SUBPASS\nhighp float d=line_df(v_line_segment.xy,v_line_segment.zw,v_pos);highp float effect_radius=mix(v_flood_light_radius_tile,v_ao.y,u_ao_pass);d/=effect_radius;d=min(d,1.0);d=1.0-pow(1.0-d,u_attenuation);highp float effect_intensity=mix(u_flood_light_intensity,v_ao.x,u_ao_pass);highp float fog=1.0;\n#ifdef FOG\nfog=v_fog;\n#endif\n#ifdef RENDER_CUTOFF\nfog*=v_cutoff_opacity;\n#endif\nglFragColor=vec4(vec3(0.0),mix(1.0,d,effect_intensity*u_opacity*fog));\n#else\n#ifdef USE_MRT1\nout_Target1=vec4(1.0-texture(u_fb,gl_FragCoord.xy/vec2(u_fb_size)).a,0.0,0.0,0.0);\n#else\nvec4 color=mix(vec4(u_flood_light_color,1.0),vec4(vec3(0.0),1.0),u_ao_pass);\n#ifdef OVERDRAW_INSPECTOR\ncolor=vec4(1.0);\n#endif\nglFragColor=color;\n#endif\n#endif\nHANDLE_WIREFRAME_DEBUG;\n#endif\n}",'#include "_prelude_fog.vertex.glsl"\nin highp vec4 a_pos_end;in highp float a_angular_offset_factor;in highp float a_hidden_by_landmark;\n#ifdef SDF_SUBPASS\nout highp vec2 v_pos;out highp vec4 v_line_segment;out highp float v_flood_light_radius_tile;out highp vec2 v_ao;\n#ifdef FOG\nout highp float v_fog;\n#endif\n#endif\nuniform highp float u_flood_light_intensity;uniform highp mat4 u_matrix;uniform highp float u_ao_pass;uniform highp float u_meter_to_tile;uniform highp float u_edge_radius;uniform highp float u_dynamic_offset;uniform highp vec2 u_ao;\n#pragma mapbox: define highp float flood_light_ground_radius\nconst float TANGENT_CUTOFF=4.0;const float NORM=32767.0;void main() {\n#pragma mapbox: initialize highp float flood_light_ground_radius\nvec2 p=a_pos_end.xy;vec2 q=floor(a_pos_end.zw*0.5);vec2 start_bottom=a_pos_end.zw-q*2.0;float fl_ground_radius=flood_light_ground_radius;fl_ground_radius=abs(flood_light_ground_radius);float direction=flood_light_ground_radius < 0.0 ?-1.0 : 1.0;float flood_radius_tile=fl_ground_radius*u_meter_to_tile;vec2 v=normalize(q-p);float ao_radius=u_ao.y/3.5;float effect_radius=mix(flood_radius_tile,ao_radius,u_ao_pass)+u_edge_radius;float angular_offset_factor=a_angular_offset_factor/NORM*TANGENT_CUTOFF;float angular_offset=direction*angular_offset_factor*effect_radius;float top=1.0-start_bottom.y;float side=(0.5-start_bottom.x)*2.0;vec2 extrusion_parallel=v*side*mix(u_dynamic_offset,angular_offset,top);vec2 perp=vec2(v.y,-v.x);vec2 extrusion_perp=direction*perp*effect_radius*top;vec3 pos=vec3(mix(q,p,start_bottom.x),0.0);pos.xy+=extrusion_parallel+extrusion_perp;\n#ifdef SDF_SUBPASS\nv_pos=pos.xy;v_line_segment=vec4(p,q)+perp.xyxy*u_edge_radius;v_flood_light_radius_tile=flood_radius_tile;v_ao=vec2(u_ao.x,ao_radius);\n#ifdef FOG\nv_fog_pos=fog_position(pos);v_fog=1.0-fog(v_fog_pos);\n#endif\n#endif\nfloat hidden_by_landmark=0.0;\n#ifdef HAS_CENTROID\nhidden_by_landmark=a_hidden_by_landmark;\n#endif\nfloat isFloodlit=float(fl_ground_radius > 0.0 && u_flood_light_intensity > 0.0);float hidden=mix(1.0-isFloodlit,isFloodlit,u_ao_pass);hidden+=hidden_by_landmark;gl_Position=mix(u_matrix*vec4(pos,1.0),AWAY,float(hidden > 0.0));\n#ifdef RENDER_CUTOFF\nv_cutoff_opacity=cutoff_opacity(u_cutoff_params,gl_Position.z);\n#endif\n}'),hillshadePrepare:vd("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 vec2 a_pos;in vec2 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=(a_texture_pos/8192.0)*scale+epsilon;}"),hillshade:vd('#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\n#ifdef USE_MRT1\nout_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a);\n#endif\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}','#include "_prelude_fog.vertex.glsl"\nuniform mat4 u_matrix;in vec2 a_pos;in vec2 a_texture_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos=a_texture_pos/8192.0;\n#ifdef FOG\nv_fog_pos=fog_position(a_pos);\n#endif\n}'),line:vd('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_lighting.glsl"\n#include "_prelude_shadow.fragment.glsl"\nuniform lowp float u_device_pixel_ratio;uniform highp float u_width_scale;uniform highp float u_floor_width_scale;uniform float u_alpha_discard_threshold;uniform highp vec2 u_trim_offset;uniform highp vec2 u_trim_fade_range;uniform lowp vec4 u_trim_color;in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;in highp vec3 v_uv;\n#ifdef ELEVATED_ROADS\nin highp float v_road_z_offset;\n#endif\n#ifdef RENDER_LINE_DASH\nuniform sampler2D u_dash_image;in vec2 v_tex;\n#endif\n#ifdef RENDER_LINE_GRADIENT\nuniform sampler2D u_gradient_image;\n#endif\n#ifdef INDICATOR_CUTOUT\nin highp float v_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\nfloat luminance(vec3 c) {return (c.r+c.r+c.b+c.g+c.g+c.g)*0.1667;}\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float floorwidth\n#pragma mapbox: define lowp vec4 dash\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float side_z_offset\n#pragma mapbox: define lowp float border_width\n#pragma mapbox: define lowp vec4 border_color\n#pragma mapbox: define lowp float emissive_strength\nfloat linearstep(float edge0,float edge1,float x) {return clamp((x-edge0)/(edge1-edge0),0.0,1.0);}void main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float floorwidth\n#pragma mapbox: initialize lowp vec4 dash\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float side_z_offset\n#pragma mapbox: initialize lowp float border_width\n#pragma mapbox: initialize lowp vec4 border_color\n#pragma mapbox: initialize lowp float emissive_strength\nfloat 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);alpha=side_z_offset > 0.0 ? 1.0-alpha : alpha;\n#ifdef RENDER_LINE_DASH\nfloat sdfdist=texture(u_dash_image,v_tex).r;float sdfgamma=1.0/(2.0*u_device_pixel_ratio)/dash.z;float scaled_floorwidth=(floorwidth*u_floor_width_scale);alpha*=linearstep(0.5-sdfgamma/scaled_floorwidth,0.5+sdfgamma/scaled_floorwidth,sdfdist);\n#endif\nhighp vec4 out_color;\n#ifdef RENDER_LINE_GRADIENT\nout_color=texture(u_gradient_image,v_uv.xy);\n#ifdef MULTIPLY_LINE_GRADIENT_COLOR\nout_color*=color;\n#endif\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);out_color=mix(out_color,u_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 RENDER_LINE_BORDER\nfloat edgeBlur=((border_width*u_width_scale)+1.0/u_device_pixel_ratio);float alpha2=clamp(min(dist-(v_width2.t-edgeBlur),v_width2.s-dist)/edgeBlur,0.0,1.0);if (alpha2 < 1.) {float smoothAlpha=smoothstep(0.6,1.0,alpha2);if (border_color.a==0.0) {float 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-smoothAlpha));} else {out_color.rgb*=(0.6 +0.4*smoothAlpha);}} else {out_color=mix(border_color*trim_alpha,out_color,smoothAlpha);}}\n#endif\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);\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*opacity);\n#ifdef INDICATOR_CUTOUT\nout_color=applyCutout(out_color,v_z_offset);\n#endif\n#ifdef FEATURE_CUTOUT\nout_color=apply_feature_cutout(out_color,gl_FragCoord);\n#endif\nglFragColor=out_color;\n#ifdef DUAL_SOURCE_BLENDING\nglFragColorSrc1=vec4(vec3(0.0),emissive_strength);\n#else\n#ifdef USE_MRT1\nout_Target1=vec4(emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a);\n#endif\n#endif\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 EXTRUDE_SCALE 0.015873016\nin vec2 a_pos_normal;in vec4 a_data;\n#if defined(ELEVATED) || defined(ELEVATED_ROADS) || defined(VARIABLE_LINE_WIDTH)\nin vec3 a_z_offset_width;\n#endif\n#if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET)\nin highp vec3 a_packed;\n#endif\n#ifdef RENDER_LINE_DASH\nin float a_linesofar;\n#endif\nuniform 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 highp 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 float v_gamma_scale;out highp vec3 v_uv;\n#ifdef ELEVATED_ROADS\nout highp float v_road_z_offset;\n#endif\n#ifdef RENDER_LINE_DASH\nuniform vec2 u_texsize;uniform float u_tile_units_to_pixels;out vec2 v_tex;\n#endif\n#ifdef RENDER_LINE_GRADIENT\nuniform float u_image_height;\n#endif\n#ifdef INDICATOR_CUTOUT\nout highp float v_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 highp vec4 color\n#pragma mapbox: define lowp float floorwidth\n#pragma mapbox: define lowp vec4 dash\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define mediump float side_z_offset\n#pragma mapbox: define lowp float border_width\n#pragma mapbox: define lowp vec4 border_color\n#pragma mapbox: define lowp float emissive_strength\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float floorwidth\n#pragma mapbox: initialize lowp vec4 dash\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize mediump float side_z_offset\n#pragma mapbox: initialize lowp float border_width\n#pragma mapbox: initialize lowp vec4 border_color\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=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth;\n#ifdef VARIABLE_LINE_WIDTH\nbool left=normal.y==1.0;halfwidth=(u_width_scale*(left ? a_z_offset_width.y : a_z_offset_width.z))/2.0;a_z_offset+=left ? side_z_offset : 0.0;v_normal=side_z_offset > 0.0 && left ? vec2(0.0) : v_normal;\n#else\nhalfwidth=(u_width_scale*width)/2.0;\n#endif\noffset=-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);mediump 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;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;\n#ifdef CROSS_SLOPE_VERTICAL\nfloat top=a_pos_normal.y-2.0*floor(a_pos_normal.y*0.5);float line_height=2.0*u_tile_to_meter*outset*top*u_pixels_to_tile_units[1][1]+a_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+a_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+a_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 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_TRIM_OFFSET)\nhighp float a_uv_x=a_packed[0];float a_split_index=a_packed[1];highp float line_progress=a_packed[2];\n#ifdef RENDER_LINE_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\n#ifdef RENDER_LINE_DASH\nfloat scale=dash.z==0.0 ? 0.0 : u_tile_units_to_pixels/dash.z;float height=dash.y;v_tex=vec2(a_linesofar*scale/(floorwidth*u_floor_width_scale),(-normal.y*height+dash.x+0.5)/u_texsize.y);\n#endif\nv_width2=vec2(outset,inset);\n#ifdef FOG\nv_fog_pos=fog_position(pos);\n#endif\n#ifdef INDICATOR_CUTOUT\nv_z_offset=a_z_offset;\n#endif\n}'),linePattern:vd('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_lighting.glsl"\n#include "_prelude_shadow.fragment.glsl"\nuniform highp float u_device_pixel_ratio;uniform highp float u_width_scale;uniform highp float u_alpha_discard_threshold;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 INDICATOR_CUTOUT\nin highp float v_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 mediump vec4 pattern\n#ifdef LINE_PATTERN_TRANSITION\n#pragma mapbox: define mediump vec4 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 vec4 pattern\n#ifdef LINE_PATTERN_TRANSITION\n#pragma mapbox: initialize mediump vec4 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=pattern.xy;vec2 pattern_br=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=pattern_b.xy;vec2 pattern_b_br=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);if (u_alpha_discard_threshold !=0.0) {if (color.a < u_alpha_discard_threshold) {discard;}}\n#ifdef INDICATOR_CUTOUT\ncolor=applyCutout(color,v_z_offset);\n#endif\nglFragColor=color;\n#ifdef DUAL_SOURCE_BLENDING\nglFragColorSrc1=vec4(vec3(0.0),emissive_strength);\n#else\n#ifdef USE_MRT1\nout_Target1=vec4(emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a);\n#endif\n#endif\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 vec2 a_pos_normal;in vec4 a_data;\n#if defined(ELEVATED) || defined(ELEVATED_ROADS)\nin vec3 a_z_offset_width;\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\n#ifdef INDICATOR_CUTOUT\nout highp float v_z_offset;\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 vec4 pattern\n#ifdef LINE_PATTERN_TRANSITION\n#pragma mapbox: define mediump vec4 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 vec4 pattern\n#ifdef LINE_PATTERN_TRANSITION\n#pragma mapbox: initialize mediump vec4 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=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;vec2 pos=floor(a_pos_normal*0.5);vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=(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;\n#ifdef CROSS_SLOPE_VERTICAL\nfloat top=a_pos_normal.y-2.0*floor(a_pos_normal.y*0.5);float line_height=2.0*u_tile_to_meter*outset*top*u_pixels_to_tile_units[1][1]+a_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+a_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+a_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/((pattern.w-pattern.y)*pixel_ratio_inverse);highp float subt_multiple=(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#ifdef INDICATOR_CUTOUT\nv_z_offset=a_z_offset;\n#endif\n}'),raster:vd('#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;\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#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\n#ifdef USE_MRT1\nout_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a);\n#endif\nHANDLE_WIREFRAME_DEBUG;}','#include "_prelude_fog.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#define GLOBE_UPSCALE GLOBE_RADIUS/6371008.8\n#ifdef GLOBE_POLES\nin vec3 a_globe_pos;in vec2 a_uv;\n#else\nin vec2 a_pos;in vec2 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;globe_pos+=normalize(globe_pos)*u_raster_elevation*GLOBE_UPSCALE;gl_Position=u_matrix*u_globe_matrix*vec4(globe_pos ,1.0);uv=a_uv;\n#ifdef FOG\nv_fog_pos=fog_position((u_normalize_matrix*vec4(a_globe_pos,1.0)).xyz);\n#endif\n#else\nfloat w=1.0+dot(a_texture_pos,u_perspective_transform);uv=a_texture_pos/8192.0;\n#ifdef PROJECTION_GLOBE_VIEW\nvec3 decomposed_pos_and_skirt=decomposeToPosAndSkirt(a_pos);vec3 latLng=u_grid_matrix*vec3(decomposed_pos_and_skirt.xy,1.0);vec3 globe_pos=latLngToECEF(latLng.xy);globe_pos+=normalize(globe_pos)*u_raster_elevation*GLOBE_UPSCALE;vec4 globe_world_pos=u_globe_matrix*vec4(globe_pos,1.0);vec4 merc_world_pos=vec4(0.0);float mercatorY=mercatorYfromLat(latLng[0]);float mercatorX=mercatorXfromLng(latLng[1]); \nv_split_fade=0.0;if (u_zoom_transition > 0.0) {vec2 merc_pos=vec2(mercatorX,mercatorY);merc_world_pos=vec4(merc_pos,u_raster_elevation,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)));}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);}vec4 interpolated_pos=vec4(mix(globe_world_pos.xyz,merc_world_pos.xyz,u_zoom_transition)*w,w);gl_Position=u_matrix*interpolated_pos;\n#ifdef FOG\nv_fog_pos=fog_position((u_normalize_matrix*vec4(globe_pos,1.0)).xyz);\n#endif\n#else\ngl_Position=u_matrix*vec4(a_pos*w,u_raster_elevation*w,w);\n#ifdef FOG\nv_fog_pos=fog_position(a_pos);\n#endif\n#endif\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 RENDER_CUTOFF\nv_depth=gl_Position.z;\n#endif\n}'),rasterParticle:vd('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_lighting.glsl"\nuniform float u_fade_t;uniform float u_opacity;uniform highp float u_raster_elevation;in vec2 v_pos0;in vec2 v_pos1;uniform sampler2D u_image0;uniform sampler2D u_image1;void main() {vec4 color0,color1,color;color0=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);color.a*=u_opacity;vec3 out_color=color.rgb;\n#ifdef LIGHTING_3D_MODE\nout_color=apply_lighting_with_emission_ground(vec4(out_color,1.0),1.0).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 OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}','#include "_prelude_fog.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 float u_raster_elevation;uniform float u_zoom_transition;uniform vec2 u_merc_center;\n#define GLOBE_UPSCALE GLOBE_RADIUS/6371008.8\nin vec2 a_pos;in vec2 a_texture_pos;out vec2 v_pos0;out vec2 v_pos1;void main() {float w=1.0;vec2 uv;\n#ifdef PROJECTION_GLOBE_VIEW\nvec3 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];float idx=u_grid_matrix[1][2];float idy=u_grid_matrix[2][2];float uvX=mercatorX*tiles-idx;float uvY=mercatorY*tiles-idy;uv=vec2(uvX,uvY);vec3 globe_pos=latLngToECEF(latLng.xy);globe_pos+=normalize(globe_pos)*u_raster_elevation*GLOBE_UPSCALE;vec4 globe_world_pos=u_globe_matrix*vec4(globe_pos,1.0);vec4 merc_world_pos=vec4(0.0);if (u_zoom_transition > 0.0) {vec2 merc_pos=vec2(mercatorX,mercatorY);merc_world_pos=vec4(merc_pos,u_raster_elevation,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;}vec4 interpolated_pos=vec4(mix(globe_world_pos.xyz,merc_world_pos.xyz,u_zoom_transition)*w,w);gl_Position=u_matrix*interpolated_pos;\n#ifdef FOG\nv_fog_pos=fog_position((u_normalize_matrix*vec4(globe_pos,1.0)).xyz);\n#endif\n#else\nuv=a_texture_pos/8192.0;gl_Position=u_matrix*vec4(a_pos*w,u_raster_elevation*w,w);\n#ifdef FOG\nv_fog_pos=fog_position(a_pos);\n#endif\n#endif\nv_pos0=uv;v_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}'),rasterParticleDraw:vd("uniform sampler2D u_color_ramp;in float v_particle_speed;void main() {glFragColor=texture(u_color_ramp,vec2(v_particle_speed,0.5));}",'#include "_prelude_raster_particle.glsl"\nin float a_index;uniform sampler2D u_particle_texture;uniform float u_particle_texture_side_len;uniform vec2 u_tile_offset;out float v_particle_speed;void main() {ivec2 pixel_coord=ivec2(\nmod(a_index,u_particle_texture_side_len),a_index/u_particle_texture_side_len);vec4 pixel=texelFetch(u_particle_texture,pixel_coord,0);vec2 pos=unpack_pos_from_rgba(pixel)+u_tile_offset;vec2 tex_coord=fract(pos);vec2 velocity=lookup_velocity(tex_coord);if (velocity==INVALID_VELOCITY) {gl_Position=AWAY;v_particle_speed=0.0;} else {gl_Position=vec4(2.0*pos-1.0,0,1);v_particle_speed=length(velocity);}gl_PointSize=1.0;}'),rasterParticleTexture:vd("uniform sampler2D u_texture;uniform float u_opacity;in vec2 v_tex_pos;void main() {vec4 color=texture(u_texture,v_tex_pos);glFragColor=vec4(floor(255.0*color*u_opacity)/255.0);}","in vec2 a_pos;out vec2 v_tex_pos;void main() {vec2 uv=0.5*a_pos+vec2(0.5);v_tex_pos=uv;gl_Position=vec4(a_pos,0.0,1.0);}"),rasterParticleUpdate:vd('#include "_prelude_raster_particle.glsl"\nuniform sampler2D u_particle_texture;uniform mediump float u_particle_texture_side_len;uniform mediump float u_speed_factor;uniform highp float u_reset_rate;uniform highp float u_rand_seed;in highp vec2 v_tex_coord;vec2 linearstep(vec2 edge0,vec2 edge1,vec2 x) {return clamp((x-edge0)/(edge1-edge0),vec2(0),vec2(1));}const highp vec3 rand_constants=vec3(12.9898,78.233,4375.85453);highp float rand(const highp vec2 co) {highp float t=dot(rand_constants.xy,co);return fract(sin(t)*(rand_constants.z+t));}void main() {ivec2 pixel_coord=ivec2(v_tex_coord*u_particle_texture_side_len);highp vec4 pixel=texelFetch(u_particle_texture,pixel_coord,0);highp vec2 pos=unpack_pos_from_rgba(pixel);highp vec2 velocity=lookup_velocity(clamp(pos,0.0,1.0));highp vec2 dp=velocity==INVALID_VELOCITY ? vec2(0) : velocity*u_speed_factor;pos=pos+dp;highp vec2 seed=(pos+v_tex_coord)*u_rand_seed;highp vec2 random_pos=vec2(rand(seed+1.3),rand(seed+2.1));highp vec2 persist_rate=pow(\nlinearstep(vec2(-u_particle_pos_offset),vec2(0),pos)*linearstep(vec2(1.0+u_particle_pos_offset),vec2(1),pos),vec2(4)\n);highp vec2 per_frame_persist=pow(persist_rate,abs(dp)/u_particle_pos_offset);highp float drop_rate=1.0-per_frame_persist.x*per_frame_persist.y;drop_rate=any(greaterThanEqual(abs(pos-0.5),vec2(0.5+u_particle_pos_offset))) ? 1.0 : drop_rate;highp float drop=step(1.0-drop_rate-u_reset_rate,rand(seed));highp vec2 next_pos=mix(pos,random_pos,drop);glFragColor=pack_pos_to_rgba(next_pos);}',"in vec2 a_pos;out vec2 v_tex_coord;void main() {v_tex_coord=0.5*(a_pos+vec2(1.0));gl_Position=vec4(a_pos,0.0,1.0);}"),symbol:vd('#include "_prelude_lighting.glsl"\n#include "_prelude_shadow.fragment.glsl"\n#define SDF_PX 8.0\n#define SDF 1.0\n#define ICON 0.0\nuniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;uniform bool u_is_halo;uniform lowp float u_scale_factor;\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 INDICATOR_CUTOUT\nin highp float v_z_offset;\n#else\n#ifdef RENDER_SHADOWS\nin highp float v_z_offset;\n#endif\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\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\n#pragma mapbox: define lowp float emissive_strength\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\n#pragma mapbox: initialize lowp float emissive_strength\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;glFragColor=texture(u_texture_icon,tex_icon)*alpha;\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nreturn;}\n#endif\n#ifdef RENDER_SDF\nfloat 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;\n#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#endif\nout_color*=opacity*fade_opacity;\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);\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 INDICATOR_CUTOUT\nout_color=applyCutout(out_color,v_z_offset);\n#endif\n#ifdef FEATURE_CUTOUT\nout_color=apply_feature_cutout(out_color,gl_FragCoord);\n#endif\nglFragColor=out_color;\n#ifdef OVERDRAW_INSPECTOR\nglFragColor=vec4(1.0);\n#endif\nHANDLE_WIREFRAME_DEBUG;}','#include "_prelude_terrain.vertex.glsl"\n#include "_prelude_shadow.vertex.glsl"\n#define APPEARANCE_ICON 1.0\nin vec4 a_pos_offset;in vec4 a_tex_size;in vec4 a_pixeloffset;in vec4 a_projected_pos;in float a_fade_opacity;\n#ifdef Z_OFFSET\nin float a_auto_z_offset;\n#endif\n#ifdef PROJECTION_GLOBE_VIEW\nin vec3 a_globe_anchor;in vec3 a_globe_normal;\n#endif\n#ifdef ICON_TRANSITION\nin vec2 a_texb;\n#endif\n#ifdef OCCLUSION_QUERIES\nin float a_occlusion_query_opacity;\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 INDICATOR_CUTOUT\nout highp float v_z_offset;\n#else\n#ifdef RENDER_SHADOWS\nout highp float v_z_offset;\n#endif\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;uniform mat4 u_inv_matrix;uniform 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;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec3 u_up_vector;uniform vec2 u_texsize_icon;uniform 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#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\n#pragma mapbox: define lowp float emissive_strength\n#pragma mapbox: define lowp float occlusion_opacity\n#pragma mapbox: define lowp float z_offset\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\n#pragma mapbox: initialize lowp float emissive_strength\n#pragma mapbox: initialize lowp float occlusion_opacity\n#pragma mapbox: initialize lowp float z_offset\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_tex_size.xy;vec2 a_size=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_icon=a_size[1]-2.0*a_size_max;vec2 a_pxoffset=a_pixeloffset.xy;vec2 a_min_font_scale=a_pixeloffset.zw/256.0;highp float segment_angle=-a_projected_pos[3];float size;if (a_apperance_icon==APPEARANCE_ICON) {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=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(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;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float out_fade_opacity=max(0.0,min(occlusion_fade,fade_opacity[0]+fade_change));\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\n#ifdef OCCLUSION_QUERIES\nfloat occludedFadeMultiplier=mix(occlusion_opacity,1.0,a_occlusion_query_opacity);out_fade_opacity*=occludedFadeMultiplier;\n#endif\n#ifdef Z_TEST_OCCLUSION\nout_fade_opacity*=occlusion_opacity;\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);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=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 INDICATOR_CUTOUT\nv_z_offset=e;\n#else\n#ifdef RENDER_SHADOWS\nv_z_offset=e;\n#endif\n#endif\n}'),terrainRaster:vd('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_shadow.fragment.glsl"\n#include "_prelude_lighting.glsl"\nuniform sampler2D u_image0;\n#ifdef LIGHTING_3D_ALPHA_EMISSIVENESS\nuniform sampler2D u_image1;uniform float u_emissive_texture_available;\n#endif\nin vec2 v_pos0;\n#ifdef FOG\nin float v_fog_opacity;\n#endif\n#ifdef RENDER_SHADOWS\nin vec4 v_pos_light_view_0;in vec4 v_pos_light_view_1;\n#endif\nuniform vec3 u_ground_shadow_factor;void main() {vec4 image_color=texture(u_image0,v_pos0);vec4 color;\n#ifdef LIGHTING_3D_MODE\nconst vec3 normal=vec3(0.0,0.0,1.0);\n#ifdef RENDER_SHADOWS\nfloat cutoffOpacity=1.0;\n#ifdef RENDER_CUTOFF\ncutoffOpacity=cutoff_opacity(u_cutoff_params,1.0/gl_FragCoord.w);\n#endif\n#ifdef LIGHTING_3D_ALPHA_EMISSIVENESS\nfloat emissive_strength=u_emissive_texture_available > 0.5 ? texture(u_image1,v_pos0).r : image_color.a;vec3 unlit_base=image_color.rgb*(1.0-emissive_strength);vec3 emissive_base=image_color.rgb*emissive_strength;float ndotl=u_shadow_direction.z;float occlusion=ndotl < 0.0 ? 1.0 : shadow_occlusion(v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w,0.0);ndotl=max(0.0,ndotl);vec3 lit=apply_lighting(unlit_base,normal,mix(1.0,(1.0-(u_shadow_intensity*occlusion))*ndotl,cutoffOpacity));vec3 emissive=compute_emissive_draped(emissive_base,1.0-u_shadow_intensity,occlusion,u_ground_shadow_factor);color.rgb=lit+emissive;color.a=1.0;\n#else\nfloat lighting_factor=shadowed_light_factor_normal_unbiased(normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w);color=apply_lighting(image_color,normal,mix(1.0,lighting_factor,cutoffOpacity));\n#endif\n#else\nfloat lighting_factor=u_lighting_directional_dir.z;color=apply_lighting(image_color,normal,lighting_factor);\n#ifdef LIGHTING_3D_ALPHA_EMISSIVENESS\nfloat emissive_strength=u_emissive_texture_available > 0.5 ? texture(u_image1,v_pos0).r : image_color.a;color.rgb=mix(color.rgb,image_color.rgb,emissive_strength);color.a=1.0;\n#endif\n#endif\n#else\ncolor=image_color;\n#endif\n#ifdef FOG\n#ifdef ZERO_EXAGGERATION\ncolor=fog_dither(fog_apply_premultiplied(color,v_fog_pos));\n#else\ncolor=fog_dither(fog_apply_from_vert(color,v_fog_opacity));\n#endif\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"\nuniform mat4 u_matrix;uniform float u_skirt_height;in vec2 a_pos;out vec2 v_pos0;\n#ifdef FOG\nout float v_fog_opacity;\n#endif\n#ifdef RENDER_SHADOWS\nuniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out vec4 v_pos_light_view_0;out vec4 v_pos_light_view_1;\n#endif\nvoid main() {vec3 decomposedPosAndSkirt=decomposeToPosAndSkirt(a_pos);float skirt=decomposedPosAndSkirt.z;vec2 decodedPos=decomposedPosAndSkirt.xy;float elevation=elevation(decodedPos)-skirt*u_skirt_height;v_pos0=decodedPos/8192.0;gl_Position=u_matrix*vec4(decodedPos,elevation,1.0);\n#ifdef FOG\n#ifdef ZERO_EXAGGERATION\nv_fog_pos=fog_position(decodedPos);\n#else\nv_fog_opacity=fog(fog_position(vec3(decodedPos,elevation)));\n#endif\n#endif\n#ifdef RENDER_SHADOWS\nvec3 pos=vec3(decodedPos,elevation);v_pos_light_view_0=u_light_matrix_0*vec4(pos,1.);v_pos_light_view_1=u_light_matrix_1*vec4(pos,1.);\n#endif\n}'),terrainDepth:vd("precision highp float;in float v_depth;void main() {glFragColor=pack_depth(v_depth);}",'#include "_prelude_terrain.vertex.glsl"\nuniform mat4 u_matrix;in vec2 a_pos;out float v_depth;void main() {float elevation=elevation(a_pos);gl_Position=u_matrix*vec4(a_pos,elevation,1.0);v_depth=gl_Position.z/gl_Position.w;}'),skybox:vd('#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}',Kh),skyboxGradient:vd('#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}',Kh),skyboxCapture:vd("\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=pos.xyz;v_position.y*=-1.0;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);}"),globeRaster:vd('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_lighting.glsl"\nuniform sampler2D u_image0;\n#ifdef LIGHTING_3D_ALPHA_EMISSIVENESS\nuniform sampler2D u_image1;uniform float u_emissive_texture_available;\n#endif\nuniform float u_far_z_cutoff;in vec2 v_pos0;\n#ifndef FOG\nuniform 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 vec2 u_viewport;\n#endif\nvoid main() {vec4 color;\n#ifdef CUSTOM_ANTIALIASING\nhighp vec2 uv=gl_FragCoord.xy/u_viewport;\n#ifdef FLIP_Y\nuv.y=1.0-uv.y;\n#endif\nhighp 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 norm_dist_from_center=1.0-length(closest_point-u_globe_pos)/u_globe_radius;const float antialias_pixel=2.0;highp float antialias_factor=antialias_pixel*fwidth(norm_dist_from_center);highp float antialias=smoothstep(0.0,antialias_factor,norm_dist_from_center);vec4 raster=texture(u_image0,v_pos0);\n#ifdef LIGHTING_3D_MODE\n#ifdef LIGHTING_3D_ALPHA_EMISSIVENESS\nfloat emissive_strength=u_emissive_texture_available > 0.5 ? texture(u_image1,v_pos0).r : raster.a;raster=apply_lighting_with_emission_ground(raster,emissive_strength);color=vec4(clamp(raster.rgb,vec3(0),vec3(1))*antialias,antialias);\n#else\nraster=apply_lighting_ground(raster);color=vec4(raster.rgb*antialias,raster.a*antialias);\n#endif\n#else\ncolor=vec4(raster.rgb*antialias,raster.a*antialias);\n#endif\n#else\ncolor=texture(u_image0,v_pos0);\n#ifdef LIGHTING_3D_MODE\n#ifdef LIGHTING_3D_ALPHA_EMISSIVENESS\nfloat emissive_strength=u_emissive_texture_available > 0.5 ? texture(u_image1,v_pos0).r : color.a;color=apply_lighting_with_emission_ground(color,emissive_strength);color.a=1.0;\n#else\ncolor=apply_lighting_ground(color);\n#endif\n#endif\n#endif\n#ifdef FOG\ncolor=fog_dither(fog_apply_premultiplied(color,v_fog_pos));\n#endif\ncolor*=1.0-step(u_far_z_cutoff,1.0/gl_FragCoord.w);glFragColor=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"\nuniform mat4 u_proj_matrix;uniform mat4 u_normalize_matrix;uniform mat4 u_globe_matrix;uniform mat4 u_merc_matrix;uniform float u_zoom_transition;uniform vec2 u_merc_center;uniform mat3 u_grid_matrix;uniform float u_skirt_height;\n#ifdef GLOBE_POLES\nin vec3 a_globe_pos;in vec2 a_uv;\n#else\nin vec2 a_pos;\n#endif\nout vec2 v_pos0;void main() {\n#ifdef GLOBE_POLES\nvec3 globe_pos=a_globe_pos;vec2 uv=a_uv;\n#else\nfloat tiles=u_grid_matrix[0][2];float idx=u_grid_matrix[1][2];float idy=u_grid_matrix[2][2];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 uvY=mercatorY*tiles-idy;float mercatorX=mercatorXfromLng(latLng[1]);float uvX=mercatorX*tiles-idx;vec3 globe_pos=latLngToECEF(latLng.xy);vec2 merc_pos=vec2(mercatorX,mercatorY);vec2 uv=vec2(uvX,uvY);\n#endif\nv_pos0=uv;vec2 tile_pos=uv*EXTENT;vec3 globe_derived_up_vector=normalize(globe_pos)*u_tile_up_scale;\n#ifdef GLOBE_POLES\nvec3 up_vector=globe_derived_up_vector;\n#else\nvec3 up_vector=elevationVector(tile_pos);\n#endif\nfloat height=elevation(tile_pos);globe_pos+=up_vector*height;\n#ifndef GLOBE_POLES\nglobe_pos-=globe_derived_up_vector*u_skirt_height*decomposed_pos_and_skirt.z;\n#endif\n#ifdef GLOBE_POLES\nvec4 interpolated_pos=u_globe_matrix*vec4(globe_pos,1.0);\n#else\nvec4 globe_world_pos=u_globe_matrix*vec4(globe_pos,1.0);vec4 merc_world_pos=vec4(0.0);if (u_zoom_transition > 0.0) {merc_world_pos=vec4(merc_pos,height-u_skirt_height*decomposed_pos_and_skirt.z,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;}vec4 interpolated_pos=vec4(mix(globe_world_pos.xyz,merc_world_pos.xyz,u_zoom_transition),1.0);\n#endif\ngl_Position=u_proj_matrix*interpolated_pos;\n#ifdef FOG\nv_fog_pos=fog_position((u_normalize_matrix*vec4(globe_pos,1.0)).xyz);\n#endif\n}'),globeAtmosphere:vd('#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\n#ifdef NATIVE\nglFragColor=vec4(1,1,1,1);\n#else\nglFragColor=vec4(0,0,0,1);\n#endif\nreturn;\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);}"),model:vd('#include "_prelude_fog.fragment.glsl"\n#include "_prelude_shadow.fragment.glsl"\n#include "_prelude_lighting.glsl"\nuniform float u_opacity;uniform vec3 u_lightcolor;uniform vec3 u_lightpos;uniform float u_lightintensity;uniform vec4 u_baseColorFactor;uniform vec4 u_emissiveFactor;uniform float u_metallicFactor;uniform float u_roughnessFactor;uniform float u_emissive_strength;in highp vec4 v_position_height;in lowp vec4 v_color_mix;\n#ifdef RENDER_SHADOWS\nin highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in float v_depth_shadows;\n#endif\n#ifdef OCCLUSION_TEXTURE_TRANSFORM\nuniform vec4 u_occlusionTextureTransform;\n#endif\n#pragma mapbox: define-attribute highp vec3 normal_3f\n#pragma mapbox: define-attribute highp vec3 color_3f\n#pragma mapbox: define-attribute highp vec4 color_4f\n#pragma mapbox: define-attribute highp vec2 uv_2f\n#pragma mapbox: initialize-attribute highp vec3 normal_3f\n#pragma mapbox: initialize-attribute highp vec3 color_3f\n#pragma mapbox: initialize-attribute highp vec4 color_4f\n#pragma mapbox: initialize-attribute highp vec2 uv_2f\n#ifdef HAS_ATTRIBUTE_a_pbr\nin lowp vec4 v_roughness_metallic_emissive_alpha;in mediump vec4 v_height_based_emission_params;\n#endif\n#ifdef HAS_TEXTURE_u_baseColorTexture\nuniform sampler2D u_baseColorTexture;uniform bool u_baseTextureIsAlpha;uniform bool u_alphaMask;uniform float u_alphaCutoff;\n#endif\n#ifdef HAS_TEXTURE_u_metallicRoughnessTexture\nuniform sampler2D u_metallicRoughnessTexture;\n#endif\n#ifdef HAS_TEXTURE_u_occlusionTexture\nuniform sampler2D u_occlusionTexture;uniform float u_aoIntensity;\n#endif\n#ifdef HAS_TEXTURE_u_normalTexture\nuniform sampler2D u_normalTexture;\n#endif\n#ifdef HAS_TEXTURE_u_emissionTexture\nuniform sampler2D u_emissionTexture;\n#endif\n#ifdef APPLY_LUT_ON_GPU\nuniform highp sampler3D u_lutTexture;\n#endif\n#ifdef TERRAIN_FRAGMENT_OCCLUSION\nin highp float v_depth;uniform highp sampler2D u_depthTexture;uniform highp vec2 u_inv_depth_size;uniform highp vec2 u_depth_range_unpack;\n#ifdef DEPTH_D24\nhighp float unpack_depth(highp float depth) {return depth*u_depth_range_unpack.x+u_depth_range_unpack.y;}\n#else\nhighp float unpack_depth_rgba(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 dot(rgba_depth,bit_shift)*2.0-1.0;}\n#endif\nbool isOccluded() {highp vec2 coord=gl_FragCoord.xy*u_inv_depth_size;\n#ifdef FLIP_Y\ncoord.y=1.0-coord.y;\n#endif\n#ifdef DEPTH_D24\nhighp float depth=unpack_depth(texture(u_depthTexture,coord).r);\n#else\nhighp float depth=unpack_depth_rgba(texture(u_depthTexture,coord));\n#endif\nreturn v_depth > depth+0.0005;}\n#endif\n#define saturate(_x) clamp(_x,0.,1.)\nvec3 linearTosRGB(vec3 color) {return pow(color,vec3(1./2.2));}vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));}float calculate_NdotL(vec3 normal,vec3 lightDir) {const float ext=0.70710678118;return (clamp(dot(normal,lightDir),-ext,1.0)+ext)/(1.0+ext);}vec3 getDiffuseShadedColor(vec3 albedo,vec3 normal,vec3 lightDir,vec3 lightColor)\n{\n#ifdef LIGHTING_3D_MODE\nvec3 transformed_normal=vec3(-normal.xy,normal.z);float lighting_factor;\n#ifdef RENDER_SHADOWS\nlighting_factor=shadowed_light_factor_normal(transformed_normal,v_pos_light_view_0,v_pos_light_view_1,v_depth_shadows);\n#else\nlighting_factor=saturate(dot(transformed_normal,u_lighting_directional_dir));\n#endif\nreturn apply_lighting(albedo,transformed_normal,lighting_factor);\n#else\nvec3 n=normal;float colorvalue=((albedo.x*0.2126)+(albedo.y*0.7152))+(albedo.z*0.0722);vec3 c=vec3(0.03,0.03,0.03);float directional=clamp(dot(n,vec3(lightDir)),0.0,1.0);directional=mix(1.0-u_lightintensity,max((1.0-colorvalue)+u_lightintensity,1.0),directional);vec3 c3=c+clamp((albedo*directional)*lightColor,mix(vec3(0.0),vec3(0.3),vec3(1.0)-lightColor),vec3(1.0));return c3;\n#endif\n}vec4 getBaseColor() {vec4 albedo=u_baseColorFactor;\n#ifdef HAS_ATTRIBUTE_a_color_3f\nalbedo*=vec4(color_3f,1.0);\n#endif\n#ifdef HAS_ATTRIBUTE_a_pbr\n#else\n#ifdef HAS_ATTRIBUTE_a_color_4f\nalbedo*=color_4f;\n#endif\n#endif\n#if defined (HAS_TEXTURE_u_baseColorTexture) && defined (HAS_ATTRIBUTE_a_uv_2f)\nvec4 texColor=texture(u_baseColorTexture,uv_2f);if(u_alphaMask) {if (texColor.w < u_alphaCutoff) {discard;}}\n#ifdef UNPREMULT_TEXTURE_IN_SHADER\nif(texColor.w > 0.0) {texColor.rgb/=texColor.w;}texColor.w=1.0;\n#endif\nif(u_baseTextureIsAlpha) {if (texColor.r < 0.5) {discard;}} else {texColor.rgb=sRGBToLinear(texColor.rgb);albedo*=texColor;}\n#endif\nvec4 color=vec4(mix(albedo.rgb,v_color_mix.rgb,v_color_mix.a),albedo.a);\n#ifdef APPLY_LUT_ON_GPU\ncolor=applyLUT(u_lutTexture,color);\n#endif\nreturn color;}highp mat3 cotangentFrame(highp vec3 N,highp vec3 p,highp vec2 uv ) {\n#ifdef HAS_TEXTURE_u_normalTexture\nhighp vec3 dp1=vec3(dFdx(p.x),dFdx(p.y),dFdx(p.z));highp vec3 dp2=vec3(dFdy(p.x),dFdy(p.y),dFdy(p.z));highp vec2 duv1=vec2(dFdx(uv.x),dFdx(uv.y));highp vec2 duv2=vec2(dFdy(uv.x),dFdy(uv.y));highp vec3 dp2perp=cross( dp2,N );highp vec3 dp1perp=cross( N,dp1 );highp vec3 T=dp2perp*duv1.x+dp1perp*duv2.x;highp vec3 B=dp2perp*duv1.y+dp1perp*duv2.y;\n#ifdef FLIP_Y\nT=-T;B=-B;\n#endif\nhighp float lengthT=dot(T,T);highp float lengthB=dot(B,B);highp float maxLength=max(lengthT,lengthB);highp float invmax=inversesqrt( maxLength );highp mat3 res=mat3( T*invmax,B*invmax,N );return res;\n#else\nreturn mat3(1.0);\n#endif\n}highp vec3 getNormal(){highp vec3 n;\n#ifdef HAS_ATTRIBUTE_a_normal_3f\nn=normalize(normal_3f);\n#else\nhighp vec3 fdx=vec3(dFdx(v_position_height.x),dFdx(v_position_height.y),dFdx(v_position_height.z));highp vec3 fdy=vec3(dFdy(v_position_height.x),dFdy(v_position_height.y),dFdy(v_position_height.z));\n#ifdef FLIP_Y\nn=normalize(cross(fdx,fdy));\n#else\nn=normalize(cross(fdx,fdy))*-1.0;\n#endif\n#endif\n#if defined(HAS_TEXTURE_u_normalTexture) && defined(HAS_ATTRIBUTE_a_uv_2f)\nvec3 nMap=texture( u_normalTexture,uv_2f).xyz;nMap=normalize(2.0*nMap-vec3(1.0));highp vec3 v=normalize(-v_position_height.xyz);highp mat3 TBN=cotangentFrame(n,v,uv_2f);n=normalize(TBN*nMap);\n#endif\nreturn n;}struct Material {float perceptualRoughness;float alphaRoughness;float metallic;vec3 f90;vec4 baseColor;vec3 diffuseColor;vec3 specularColor;highp vec3 normal;};Material getPBRMaterial() {Material mat;mat.baseColor=getBaseColor();mat.perceptualRoughness=u_roughnessFactor;mat.metallic=u_metallicFactor;\n#ifdef HAS_ATTRIBUTE_a_pbr\nmat.perceptualRoughness=v_roughness_metallic_emissive_alpha.x;mat.metallic=v_roughness_metallic_emissive_alpha.y;mat.baseColor.w*=v_roughness_metallic_emissive_alpha.w;\n#endif\n#if defined(HAS_TEXTURE_u_metallicRoughnessTexture) && defined(HAS_ATTRIBUTE_a_uv_2f) \nvec4 mrSample=texture(u_metallicRoughnessTexture,uv_2f);mat.perceptualRoughness*=mrSample.g;mat.metallic*=mrSample.b;\n#endif\nconst float c_minRoughness=0.04;mat.perceptualRoughness=clamp(mat.perceptualRoughness,c_minRoughness,1.0);mat.metallic=saturate(mat.metallic);mat.alphaRoughness=mat.perceptualRoughness*mat.perceptualRoughness;const vec3 f0=vec3(0.04);mat.diffuseColor=mat.baseColor.rgb*(vec3(1.0)-f0);mat.diffuseColor*=1.0-mat.metallic;mat.specularColor=mix(f0,mat.baseColor.rgb,mat.metallic);highp float reflectance=max(max(mat.specularColor.r,mat.specularColor.g),mat.specularColor.b);highp float reflectance90=saturate(reflectance*25.0);mat.f90=vec3(reflectance90);mat.normal=getNormal();return mat;}float V_GGX(float NdotL,float NdotV,float roughness)\n{float a2=roughness*roughness;float GGXV=NdotL*sqrt(NdotV*NdotV*(1.0-a2)+a2);float GGXL=NdotV*sqrt(NdotL*NdotL*(1.0-a2)+a2);return 0.5/(GGXV+GGXL);}float V_GGXFast(float NdotL,float NdotV,float roughness) {float a=roughness;float GGXV=NdotL*(NdotV*(1.0-a)+a);float GGXL=NdotV*(NdotL*(1.0-a)+a);return 0.5/(GGXV+GGXL);}vec3 F_Schlick(vec3 specularColor,vec3 f90,float VdotH)\n{return specularColor+(f90-specularColor)*pow(clamp(1.0-VdotH,0.0,1.0),5.0);}vec3 F_SchlickFast(vec3 specularColor,float VdotH)\n{float x=1.0-VdotH;float x4=x*x*x*x;return specularColor+(1.0-specularColor)*x4*x;}float D_GGX(highp float NdotH,float alphaRoughness)\n{highp float a4=alphaRoughness*alphaRoughness;highp float f=(NdotH*a4-NdotH)*NdotH+1.0;return a4/(PI*f*f);}vec3 diffuseBurley(Material mat,float LdotH,float NdotL,float NdotV)\n{float f90=2.0*LdotH*LdotH*mat.alphaRoughness-0.5;return (mat.diffuseColor/PI)*(1.0+f90*pow((1.0-NdotL),5.0))*(1.0+f90*pow((1.0-NdotV),5.0));}vec3 diffuseLambertian(Material mat)\n{\n#ifdef LIGHTING_3D_MODE\nreturn mat.diffuseColor;\n#else\nreturn mat.diffuseColor/PI;\n#endif\n}vec3 EnvBRDFApprox(vec3 specularColor,float roughness,highp float NdotV)\n{vec4 c0=vec4(-1,-0.0275,-0.572,0.022);vec4 c1=vec4(1,0.0425,1.04,-0.04);highp vec4 r=roughness*c0+c1;highp float a004=min(r.x*r.x,exp2(-9.28*NdotV))*r.x+r.y;vec2 AB=vec2(-1.04,1.04)*a004+r.zw;return specularColor*AB.x+AB.y;}vec3 computeIndirectLightContribution(Material mat,float NdotV,vec3 normal)\n{vec3 env_light=vec3(0.65,0.65,0.65);\n#ifdef LIGHTING_3D_MODE\nfloat ambient_factor=calculate_ambient_directional_factor(normal);env_light=u_lighting_ambient_color*ambient_factor;\n#endif\nvec3 envBRDF=EnvBRDFApprox(mat.specularColor,mat.perceptualRoughness,NdotV);vec3 indirectSpecular= envBRDF*env_light;vec3 indirectDiffuse=mat.diffuseColor*env_light;return indirectSpecular+indirectDiffuse;}vec3 computeLightContribution(Material mat,vec3 lightPosition,vec3 lightColor)\n{highp vec3 n=mat.normal;highp vec3 v=normalize(-v_position_height.xyz);highp vec3 l=normalize(lightPosition);highp vec3 h=normalize(v+l);float NdotV=clamp(abs(dot(n,v)),0.001,1.0);float NdotL=saturate(dot(n,l));highp float NdotH=saturate(dot(n,h));float VdotH=saturate(dot(v,h));vec3 f=F_SchlickFast(mat.specularColor,VdotH);float g=V_GGXFast(NdotL,NdotV,mat.alphaRoughness);float d=D_GGX(NdotH,mat.alphaRoughness);vec3 diffuseTerm=(1.0-f)*diffuseLambertian(mat);vec3 specularTerm=f*g*d;vec3 transformed_normal=vec3(-n.xy,n.z);float lighting_factor;\n#ifdef RENDER_SHADOWS\nlighting_factor=shadowed_light_factor_normal(transformed_normal,v_pos_light_view_0,v_pos_light_view_1,v_depth_shadows);\n#else\nlighting_factor=NdotL;\n#endif\nvec3 directLightColor=(specularTerm+diffuseTerm)*lighting_factor*lightColor;vec3 indirectLightColor=computeIndirectLightContribution(mat,NdotV,transformed_normal);vec3 color=(saturate(directLightColor)+indirectLightColor);float intensityFactor=1.0;\n#if !defined(LIGHTING_3D_MODE)\nconst vec3 luminosityFactor=vec3(0.2126,0.7152,0.0722);float luminance=dot(diffuseTerm,luminosityFactor);intensityFactor=mix((1.0-u_lightintensity),max((1.0-luminance+u_lightintensity),1.0),NdotL);\n#endif\ncolor*=intensityFactor;return color;}void main() {\n#ifdef TERRAIN_FRAGMENT_OCCLUSION\nif (isOccluded()) {discard;}\n#endif\nvec3 lightDir=u_lightpos;vec3 lightColor=u_lightcolor;\n#ifdef LIGHTING_3D_MODE\nlightDir=u_lighting_directional_dir;lightDir.xy=-lightDir.xy;lightColor=u_lighting_directional_color;\n#endif\nvec4 finalColor;\n#ifdef DIFFUSE_SHADED\nvec3 N=getNormal();vec3 baseColor=getBaseColor().rgb;vec3 diffuse=getDiffuseShadedColor(baseColor,N,lightDir,lightColor);\n#ifdef HAS_TEXTURE_u_occlusionTexture\nfloat ao=(texture(u_occlusionTexture,uv_2f).r-1.0)*u_aoIntensity+1.0;diffuse*=ao;\n#endif\nfinalColor=vec4(mix(diffuse,baseColor,u_emissive_strength),1.0)*u_opacity;\n#else\nMaterial mat=getPBRMaterial();vec3 color=computeLightContribution(mat,lightDir,lightColor);float ao=1.0;\n#if defined (HAS_TEXTURE_u_occlusionTexture) && defined(HAS_ATTRIBUTE_a_uv_2f)\n#ifdef OCCLUSION_TEXTURE_TRANSFORM\nvec2 uv=uv_2f.xy*u_occlusionTextureTransform.zw+u_occlusionTextureTransform.xy;\n#else\nvec2 uv=uv_2f;\n#endif\nao=(texture(u_occlusionTexture,uv).x-1.0)*u_aoIntensity+1.0;color*=ao;\n#endif\nvec4 emissive=u_emissiveFactor;\n#if defined(HAS_TEXTURE_u_emissionTexture) && defined(HAS_ATTRIBUTE_a_uv_2f)\nemissive.rgb*=sRGBToLinear(texture(u_emissionTexture,uv_2f).rgb);\n#endif\n#ifdef APPLY_LUT_ON_GPU\nfloat emissiveFactorLength=max(length(u_emissiveFactor.rgb),0.001);emissive.rgb=sRGBToLinear(applyLUT(u_lutTexture,linearTosRGB(emissive.rgb/emissiveFactorLength).rbg))*emissiveFactorLength;\n#endif\ncolor+=emissive.rgb;float opacity=mat.baseColor.w*u_opacity;\n#ifdef HAS_ATTRIBUTE_a_pbr\nfloat resEmission=v_roughness_metallic_emissive_alpha.z;resEmission*=v_height_based_emission_params.z+v_height_based_emission_params.w*pow(clamp(v_height_based_emission_params.x,0.0,1.0),v_height_based_emission_params.y);vec3 color_mix=v_color_mix.rgb;\n#ifdef APPLY_LUT_ON_GPU\ncolor_mix=applyLUT(u_lutTexture,color_mix);\n#endif\ncolor=mix(color,color_mix,min(1.0,resEmission));\n#ifdef HAS_ATTRIBUTE_a_color_4f\nfloat distance=length(vec2(1.3*max(0.0,abs(color_4f.x)-color_4f.z),color_4f.y));distance+= mix(0.5,0.0,clamp(resEmission-1.0,0.0,1.0));opacity*=v_roughness_metallic_emissive_alpha.w*saturate(1.0-distance*distance);\n#endif\n#endif\nvec3 unlitColor=mat.baseColor.rgb*ao+emissive.rgb;color=mix(color,unlitColor,u_emissive_strength);color=linearTosRGB(color);color*=opacity;finalColor=vec4(color,opacity);\n#endif\n#ifdef FOG\nfinalColor=fog_dither(fog_apply_premultiplied(finalColor,v_fog_pos,v_position_height.w));\n#endif\n#ifdef RENDER_CUTOFF\nfinalColor*=v_cutoff_opacity;\n#endif\n#ifdef INDICATOR_CUTOUT\nfinalColor=applyCutout(finalColor,v_position_height.w);\n#endif\n#ifdef FEATURE_CUTOUT\nfinalColor=apply_feature_cutout(finalColor,gl_FragCoord);\n#endif\nglFragColor=finalColor;\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 vec3 a_pos_3f;\n#pragma mapbox: define-attribute highp vec3 normal_3f\n#pragma mapbox: define-attribute highp vec2 uv_2f\n#pragma mapbox: define-attribute highp vec3 color_3f\n#pragma mapbox: define-attribute highp vec4 color_4f\n#pragma mapbox: define-attribute-vertex-shader-only highp vec4 pbr\n#pragma mapbox: define-attribute-vertex-shader-only highp vec3 heightBasedEmissiveStrength\nuniform mat4 u_matrix;uniform mat4 u_node_matrix;uniform mat4 u_lighting_matrix;uniform vec3 u_camera_pos;uniform vec4 u_color_mix;\n#ifdef INSTANCED_ARRAYS\nin vec4 a_normal_matrix0;in vec4 a_normal_matrix1;in vec4 a_normal_matrix2;in vec4 a_normal_matrix3;\n#else\nuniform highp mat4 u_normal_matrix;\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 float v_depth_shadows;\n#endif\nout vec4 v_position_height;out lowp vec4 v_color_mix;\n#ifdef TERRAIN_FRAGMENT_OCCLUSION\nout highp float v_depth;\n#endif\n#ifdef HAS_ATTRIBUTE_a_pbr\nout lowp vec4 v_roughness_metallic_emissive_alpha;out mediump vec4 v_height_based_emission_params;\n#endif\nvec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));}void main() {\n#pragma mapbox: initialize-attribute highp vec3 normal_3f\n#pragma mapbox: initialize-attribute highp vec2 uv_2f\n#pragma mapbox: initialize-attribute highp vec3 color_3f\n#pragma mapbox: initialize-attribute highp vec4 color_4f\n#pragma mapbox: initialize-attribute-custom highp vec4 pbr\n#pragma mapbox: initialize-attribute-custom highp vec3 heightBasedEmissiveStrength\nhighp mat4 normal_matrix;\n#ifdef INSTANCED_ARRAYS\nnormal_matrix=mat4(a_normal_matrix0,a_normal_matrix1,a_normal_matrix2,a_normal_matrix3);\n#else\nnormal_matrix=u_normal_matrix;\n#endif\nvec3 local_pos;mat3 rs;\n#ifdef MODEL_POSITION_ON_GPU\nvec3 pos_color=normal_matrix[0].xyz;vec4 translate=normal_matrix[1];vec3 pos_a=floor(pos_color);vec3 rgb=1.05*(pos_color-pos_a);float hidden=float(pos_a.x > EXTENT);float color_mix=pos_a.z/100.0;v_color_mix=vec4(sRGBToLinear(rgb),color_mix);float meter_to_tile=normal_matrix[0].w;vec4 pos=vec4(pos_a.xy,translate.z,1.0);rs[0].x=normal_matrix[1].w;rs[0].yz=normal_matrix[2].xy;rs[1].xy=normal_matrix[2].zw;rs[1].z=normal_matrix[3].x;rs[2].xyz=normal_matrix[3].yzw;vec4 pos_node=u_lighting_matrix*vec4(a_pos_3f,1.0);vec3 rotated_pos_node=rs*pos_node.xyz;vec3 pos_model_tile=(rotated_pos_node+vec3(translate.xy,0.0))*vec3(meter_to_tile,meter_to_tile,1.0);pos.xyz+=pos_model_tile;local_pos=pos.xyz;gl_Position=mix(u_matrix*pos,AWAY,hidden);pos.z*=meter_to_tile;v_position_height.xyz=pos.xyz-u_camera_pos;\n#else\nlocal_pos=a_pos_3f;gl_Position=u_matrix*vec4(a_pos_3f,1);v_position_height.xyz=vec3(u_lighting_matrix*vec4(a_pos_3f,1));v_color_mix=vec4(sRGBToLinear(u_color_mix.rgb),u_color_mix.a);\n#endif\nv_position_height.w=a_pos_3f.z;\n#ifdef HAS_ATTRIBUTE_a_pbr\nvec4 albedo_c=decode_color(pbr.xy);vec2 e_r_m=unpack_float(pbr.z);vec2 r_m= unpack_float(e_r_m.y*16.0);r_m.r=r_m.r*16.0;v_color_mix=vec4(albedo_c.rgb,1.0);v_roughness_metallic_emissive_alpha=vec4(vec3(r_m,e_r_m.x)/255.0,albedo_c.a);v_roughness_metallic_emissive_alpha.z*=2.0;float heightBasedRelativeIntepolation=a_pos_3f.z*heightBasedEmissiveStrength.x+heightBasedEmissiveStrength.y;v_height_based_emission_params.x=heightBasedRelativeIntepolation;v_height_based_emission_params.y=heightBasedEmissiveStrength.z;vec2 emissionMultiplierValues=unpack_float(pbr.w)/256.0;v_height_based_emission_params.z=emissionMultiplierValues.x;v_height_based_emission_params.w=emissionMultiplierValues.y-emissionMultiplierValues.x;\n#endif\n#ifdef FOG\nv_fog_pos=fog_position(local_pos);\n#endif\n#ifdef RENDER_CUTOFF\nv_cutoff_opacity=cutoff_opacity(u_cutoff_params,gl_Position.z);\n#endif\n#ifdef TERRAIN_FRAGMENT_OCCLUSION\nv_depth=gl_Position.z/gl_Position.w;\n#ifdef CLIP_ZERO_TO_ONE\nv_depth=-1.0+2.0*v_depth; \n#endif\n#endif\n#ifdef HAS_ATTRIBUTE_a_normal_3f\n#ifdef MODEL_POSITION_ON_GPU\nfloat x_squared_scale=dot(rs[0],rs[0]);float y_squared_scale=dot(rs[1],rs[1]);float z_squared_scale=dot(rs[2],rs[2]);vec3 squared_scale=vec3(x_squared_scale,y_squared_scale,z_squared_scale);normal_3f=rs*((u_lighting_matrix*vec4(normal_3f,0.0)).xyz/squared_scale);normal_3f=normalize(normal_3f);\n#else\nnormal_3f=vec3(normal_matrix*vec4(normal_3f,0));\n#endif\n#endif\n#ifdef HAS_ATTRIBUTE_a_pbr\n#ifdef HAS_ATTRIBUTE_a_color_4f\nv_roughness_metallic_emissive_alpha.w=clamp(color_4f.a*v_roughness_metallic_emissive_alpha.w*(v_roughness_metallic_emissive_alpha.z-1.0),0.0,1.0);\n#endif\n#endif\n#ifdef RENDER_SHADOWS\nvec4 shadow_pos=u_node_matrix*vec4(local_pos,1.0);\n#ifdef NORMAL_OFFSET\n#ifdef HAS_ATTRIBUTE_a_normal_3f\n#ifdef MODEL_POSITION_ON_GPU\nvec3 offset=shadow_normal_offset(vec3(-normal_3f.xy,normal_3f.z));shadow_pos.xyz+=offset*shadow_normal_offset_multiplier0();\n#else\nvec3 offset=shadow_normal_offset_model(normal_3f);shadow_pos.xyz+=offset*shadow_normal_offset_multiplier0();\n#endif\n#endif\n#endif\nv_pos_light_view_0=u_light_matrix_0*shadow_pos;v_pos_light_view_1=u_light_matrix_1*shadow_pos;v_depth_shadows=gl_Position.w;\n#endif\n}'),modelDepth:vd("in highp float v_depth;void main() {\n#ifndef DEPTH_TEXTURE\nglFragColor=pack_depth(v_depth);\n#endif\n}","in vec3 a_pos_3f;uniform mat4 u_matrix;out highp float v_depth;\n#ifdef MODEL_POSITION_ON_GPU\n#ifdef INSTANCED_ARRAYS\nin vec4 a_normal_matrix0;in vec4 a_normal_matrix1;in vec4 a_normal_matrix2;in vec4 a_normal_matrix3;\n#else\nuniform highp mat4 u_instance;\n#endif\nuniform highp mat4 u_node_matrix;\n#endif\nvoid main() {\n#ifdef MODEL_POSITION_ON_GPU\nhighp mat4 instance;\n#ifdef INSTANCED_ARRAYS\ninstance=mat4(a_normal_matrix0,a_normal_matrix1,a_normal_matrix2,a_normal_matrix3);\n#else\ninstance=u_instance;\n#endif\nvec3 pos_color=instance[0].xyz;vec4 translate=instance[1];vec3 pos_a=floor(pos_color);float hidden=float(pos_a.x > EXTENT);float meter_to_tile=instance[0].w;vec4 pos=vec4(pos_a.xy,translate.z,1.0);mat3 rs;rs[0].x=instance[1].w;rs[0].yz=instance[2].xy;rs[1].xy=instance[2].zw;rs[1].z=instance[3].x;rs[2].xyz=instance[3].yzw;vec4 pos_node=u_node_matrix*vec4(a_pos_3f,1.0);vec3 rotated_pos_node=rs*pos_node.xyz;vec3 pos_model_tile=(rotated_pos_node+vec3(translate.xy,0.0))*vec3(meter_to_tile,meter_to_tile,1.0);pos.xyz+=pos_model_tile;gl_Position=mix(u_matrix*pos,AWAY,hidden);\n#else\ngl_Position=u_matrix*vec4(a_pos_3f,1);\n#endif\nv_depth=gl_Position.z/gl_Position.w;}"),stars:vd("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_fade_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_fade_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);}"),snowParticle:vd("in highp vec2 uv;in highp float alphaMultiplier;uniform vec4 u_particleColor;uniform vec2 u_simpleShapeParameters;void main() {float t=clamp((length(uv)-u_simpleShapeParameters.x)/(1.0-u_simpleShapeParameters.x),0.0,1.0);float alpha=1.0-pow(t,pow(10.0,u_simpleShapeParameters.y));alpha*=alphaMultiplier;alpha*=u_particleColor.a;vec3 color=u_particleColor.rgb*alpha;glFragColor=vec4(color,alpha) ;HANDLE_WIREFRAME_DEBUG;}","\nin highp vec3 a_pos_3f;in highp vec2 a_uv;in highp vec4 a_snowParticleData;in highp vec4 a_snowParticleDataHorizontalOscillation;uniform mat4 u_modelview;uniform mat4 u_projection;uniform vec3 u_cam_pos;uniform vec2 u_screenSize;uniform float u_time;uniform float u_boxSize;uniform float u_velocityConeAperture; \nuniform float u_velocity;uniform vec3 u_direction;uniform float u_horizontalOscillationRadius; \nuniform float u_horizontalOscillationRate; \nuniform float u_billboardSize;uniform vec2 u_thinningCenterPos;uniform vec3 u_thinningShape;uniform float u_thinningAffectedRatio;uniform float u_thinningParticleOffset;out highp vec2 uv;out highp float alphaMultiplier;void main() {vec3 pos=a_pos_3f;float halfBoxSize=0.5*u_boxSize;pos.xyz*=halfBoxSize;pos+=u_cam_pos;float velocityConeApertureRad=radians(u_velocityConeAperture*0.5);float coneAnglePichRad=velocityConeApertureRad*a_snowParticleData.z;float coneAngleHeadingRad=a_snowParticleData.w*radians(360.0);vec3 localZ=normalize(u_direction);vec3 localX=normalize(cross(localZ,vec3(1,0,0)));vec3 localY=normalize(cross(localZ,localX));vec3 direction;direction.x=cos(coneAngleHeadingRad)*sin(coneAnglePichRad);direction.y=sin(coneAngleHeadingRad)*sin(coneAnglePichRad);direction.z=cos(coneAnglePichRad);direction=normalize(direction);vec3 simPosLocal=vec3(0,0,0);float velocityScale=(1.0+3.0*a_snowParticleData.y)*u_velocity;simPosLocal+=direction*velocityScale*u_time;float horizontalOscillationRadius=u_horizontalOscillationRadius*a_snowParticleDataHorizontalOscillation.x;float horizontalOscillationAngle=u_horizontalOscillationRate*u_time*(-1.0+2.0*a_snowParticleDataHorizontalOscillation.y);simPosLocal.xy+=horizontalOscillationRadius*vec2(cos(horizontalOscillationAngle),sin(horizontalOscillationAngle));vec3 simPos=localX*simPosLocal.x+\nlocalY*simPosLocal.y+localZ*simPosLocal.z;pos+=simPos;pos=fract((pos+vec3(halfBoxSize))/vec3(u_boxSize))*u_boxSize-vec3(halfBoxSize);float clipZ=-u_cam_pos.z+pos.z;vec4 posView=u_modelview*vec4(pos,1.0);float size=u_billboardSize;alphaMultiplier=1.0;vec4 posScreen=u_projection*posView;posScreen/=posScreen.w;posScreen.xy=vec2(0.5)+posScreen.xy*0.5;posScreen.xy*=u_screenSize;vec2 thinningCenterPos=u_thinningCenterPos.xy;thinningCenterPos.y=u_screenSize.y-thinningCenterPos.y;float screenDist=length((thinningCenterPos-posScreen.xy)/(0.5*u_screenSize));screenDist+=a_snowParticleData.x*u_thinningParticleOffset;float scaleFactorMode=0.0;float thinningShapeDist=u_thinningShape.x+u_thinningShape.y;if (screenDist < thinningShapeDist) {float thinningFadeRatio=clamp((screenDist-u_thinningShape.x)/u_thinningShape.y,0.0,1.0);thinningFadeRatio=pow(thinningFadeRatio,u_thinningShape.z);if (a_snowParticleData.x < u_thinningAffectedRatio) {scaleFactorMode=1.0-thinningFadeRatio;alphaMultiplier=thinningFadeRatio;}}vec4 posScreen1=u_projection*vec4(posView.x-size,posView.yzw);posScreen1/=posScreen1.w;vec4 posScreen2=u_projection*vec4(posView.x+size,posView.yzw);posScreen2/=posScreen2.w;posScreen1.xy=vec2(0.5)+posScreen1.xy*0.5;posScreen1.xy*=u_screenSize;posScreen2.xy=vec2(0.5)+posScreen2.xy*0.5;posScreen2.xy*=u_screenSize;float screenLength=length(posScreen1.xy-posScreen2.xy);float screenEpsilon=3.0;float scaleFactor=1.0;if (screenLength < screenEpsilon) {scaleFactor=screenEpsilon/max(screenLength,0.01);scaleFactor=mix(scaleFactor,1.0,scaleFactorMode);}float screenEpsilon2=15.0;if (screenLength > screenEpsilon2) {scaleFactor=screenEpsilon2/max(screenLength,0.01);}size*=scaleFactor;vec2 right=size*vec2(1,0);vec2 up=size*vec2(0,1);posView.xy+=right*a_uv.x;posView.xy+=up*a_uv.y;uv=a_uv;gl_Position=u_projection*posView;}"),rainParticle:vd("in highp vec2 uv;in highp float particleRandomValue;uniform sampler2D u_texScreen;uniform float u_distortionStrength;uniform vec4 u_color;uniform vec2 u_thinningCenterPos;uniform vec3 u_thinningShape;uniform float u_thinningAffectedRatio;uniform float u_thinningParticleOffset;uniform float u_shapeDirectionalPower;uniform float u_mode;void main() {vec2 st=uv*0.5+vec2(0.5);vec2 uvm=uv;uvm.y=-1.0+2.0*pow(st.y,u_shapeDirectionalPower);float shape=clamp(1.0-length(uvm),0.0,1.0);float alpha=abs(shape)*u_color.a;vec2 screenSize=vec2(textureSize(u_texScreen,0));vec2 thinningCenterPos=u_thinningCenterPos.xy;thinningCenterPos.y=screenSize.y-thinningCenterPos.y;float screenDist=length((thinningCenterPos-gl_FragCoord.xy)/(0.5*screenSize));screenDist+=(0.5+0.5*particleRandomValue)*u_thinningParticleOffset;float thinningShapeDist=u_thinningShape.x+u_thinningShape.y;float thinningAlpha=1.0;if (screenDist < thinningShapeDist) {float thinningFadeRatio=clamp((screenDist-u_thinningShape.x)/u_thinningShape.y,0.0,1.0);thinningFadeRatio=pow(thinningFadeRatio,u_thinningShape.z);thinningAlpha*=thinningFadeRatio;}vec2 offsetXY=normalize(uvm)*abs(shape);vec2 stScreen=(gl_FragCoord.xy+offsetXY*u_distortionStrength*thinningAlpha)/screenSize;vec3 colorScreen=texture(u_texScreen,stScreen).rgb;alpha*=thinningAlpha;glFragColor=mix(vec4(colorScreen,1.0),vec4(u_color.rgb*alpha,alpha),u_mode);HANDLE_WIREFRAME_DEBUG;}","\nin highp vec3 a_pos_3f;in highp vec2 a_uv;in highp vec4 a_rainParticleData;uniform mat4 u_modelview;uniform mat4 u_projection;uniform vec3 u_cam_pos;uniform float u_time;uniform float u_boxSize;uniform float u_velocityConeAperture; \nuniform float u_velocity; \nuniform vec2 u_rainDropletSize;uniform vec3 u_rainDirection;out highp vec2 uv;out highp float particleRandomValue;void main() {vec3 pos=a_pos_3f;float halfBoxSize=0.5*u_boxSize;pos*=halfBoxSize; \npos+=u_cam_pos;float velocityConeApertureRad=radians(u_velocityConeAperture*0.5);float coneAnglePichRad=velocityConeApertureRad*a_rainParticleData.z;float coneAngleHeadingRad=a_rainParticleData.w*radians(360.0);vec3 localZ=normalize(u_rainDirection);vec3 localX=normalize(cross(localZ,vec3(1,0,0)));vec3 localY=normalize(cross(localZ,localX));vec3 directionLocal;directionLocal.x=cos(coneAngleHeadingRad)*sin(coneAnglePichRad);directionLocal.y=sin(coneAngleHeadingRad)*sin(coneAnglePichRad);directionLocal.z=cos(coneAnglePichRad);directionLocal=normalize(directionLocal);vec3 directionWorld=localX*directionLocal.x+localY*directionLocal.y+localZ*directionLocal.z;float velocityScale=(1.0+3.0*a_rainParticleData.y)*u_velocity;vec3 simPosLocal=vec3(0,0,0);simPosLocal+=directionLocal*velocityScale*u_time;vec3 simPos=localX*simPosLocal.x+\nlocalY*simPosLocal.y+localZ*simPosLocal.z;pos+=simPos;pos=fract((pos+vec3(halfBoxSize))/vec3(u_boxSize))*u_boxSize-vec3(halfBoxSize);vec4 posView=u_modelview*vec4(pos,1.0);vec3 directionView=normalize((u_modelview*vec4(directionWorld,0.0)).xyz);vec3 side=cross(directionView,normalize(posView.xyz));posView.xyz+=side*a_uv.x*u_rainDropletSize.x;posView.xyz+=directionView*a_uv.y*u_rainDropletSize.y;uv=a_uv;particleRandomValue=a_rainParticleData.x;gl_Position=u_projection*posView;}"),vignette:vd("uniform vec3 u_vignetteShape;uniform vec4 u_vignetteColor;in vec2 st;void main() {float screenDist=length(st);float alpha=clamp((screenDist-u_vignetteShape.x)/u_vignetteShape.y,0.0,1.0);alpha=pow(alpha,u_vignetteShape.z)*u_vignetteColor.a;vec3 color=u_vignetteColor.rgb;glFragColor=vec4(color*alpha,alpha) ;}","in vec2 a_pos_2f;out vec2 st;void main() {st=a_pos_2f;gl_Position=vec4(a_pos_2f,0,1);}"),occlusion:vd("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 gd(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(ad);if(i)for(const e of i)ld.has(e)||t.add(e)}}function vd(e,t){const i=new Set,o=[],s=[];e=e.replace(rd,((e,t)=>(s.push(t),""))),t=t.replace(rd,((e,t)=>(o.push(t),"")));let r=new Set(cd);gd(e,r),gd(t,r);for(const e of[...o,...s])dd[e]||(dd[e]=new Set,gd(hd[e],dd[e])),r=new Set([...r,...dd[e]]);return{fragmentSource:e=e.replace(nd,((e,t,o,s,r)=>(i.add(r),"define"===t?`\n#ifndef HAS_UNIFORM_u_${r}\nin ${o} ${s} ${r};\n#else\nuniform ${o} ${s} u_${r};\n#endif\n`:"initialize"===t?`\n#ifdef HAS_UNIFORM_u_${r}\n ${o} ${s} ${r} = u_${r};\n#endif\n`:"define-attribute"===t?`\n#ifdef HAS_ATTRIBUTE_a_${r}\n in ${o} ${s} ${r};\n#endif\n`:"initialize-attribute"===t?"":void 0))),vertexSource:t=t.replace(nd,((e,t,o,s,r)=>{const n=`MATERIAL_ATTRIBUTE_OFFSET_${r}`,a="float"===s?"vec2":s,l=`GET_ATTRIBUTE_${a}(a_${r}, materialInfo, ${n})`,c=r.match(/color/)?"color":a;return"define-attribute-vertex-shader-only"===t?`\n#ifdef HAS_ATTRIBUTE_a_${r}\nin ${o} ${s} 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 ${o} ${a} a_${r};\n #endif\nout ${o} ${s} ${r};\n#else\nuniform ${o} ${s} u_${r};\n#endif\n`:"initialize"===t?"vec4"===c?`\n#ifndef HAS_UNIFORM_u_${r}\n ${r} = a_${r};\n#else\n ${o} ${s} ${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 ${o} ${s} ${r} = u_${r};\n#endif\n`:"define-attribute"===t?`\n#ifdef HAS_ATTRIBUTE_a_${r}\n in ${o} ${s} a_${r};\n out ${o} ${s} ${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 ${o} ${a} a_${r};\n #endif\n#else\nuniform ${o} ${s} 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 ${o} ${s} u_${r};\n#endif\n`:`\n#ifdef INSTANCED_ARRAYS\nin ${o} ${a} a_${r};\n#else\nuniform ${o} ${s} u_${r};\n#endif\n`:"initialize-attribute-custom"===t?`\n#ifdef HAS_ATTRIBUTE_a_${r}\n ${o} ${s} ${r} = a_${r};\n#endif\n`:"vec4"===c?`\n#ifndef HAS_UNIFORM_u_${r}\n #ifdef ${n}\n ${o} ${s} ${r} = ${l};\n #else\n ${o} ${s} ${r} = a_${r};\n #endif\n#else\n ${o} ${s} ${r} = u_${r};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${r}\n #ifdef ${n}\n ${o} ${s} ${r} = unpack_mix_${c}(${l}, u_${r}_t);\n #else\n ${o} ${s} ${r} = unpack_mix_${c}(a_${r}, u_${r}_t);\n #endif\n#else\n ${o} ${s} ${r} = u_${r};\n#endif\n`})),usedDefines:r,vertexIncludes:o,fragmentIncludes:s}}class yd{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffers=[],this.vao=null}bind(e,t,i,o,s,r,n,a){this.context=e;let l=this.boundPaintVertexBuffers.length!==o.length;for(let e=0;!l&&e<o.length;e++)this.boundPaintVertexBuffers[e]!==o[e]&&(l=!0);let c=this.boundDynamicVertexBuffers.length!==n.length;for(let e=0;!c&&e<n.length;e++)this.boundDynamicVertexBuffers[e]!==n[e]&&(c=!0);if(!this.vao||this.boundProgram!==t||this.boundLayoutVertexBuffer!==i||l||c||this.boundIndexBuffer!==s||this.boundVertexOffset!==r)this.freshBind(t,i,o,s,r,n,a);else{e.bindVertexArrayOES.set(this.vao);for(const i of n)i&&(i.bind(),a&&i.instanceCount&&i.setVertexAttribDivisor(e.gl,t,a));s&&s.dynamicDraw&&s.bind()}}freshBind(e,t,i,o,s,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=o,this.boundVertexOffset=s,this.boundDynamicVertexBuffers=r,t.enableAttributes(l,e),t.bind(),t.setVertexAttribPointers(l,e,s);for(const t of i)t.enableAttributes(l,e),t.bind(),t.setVertexAttribPointers(l,e,s);for(const t of r)t&&(t.enableAttributes(l,e),t.bind(),t.setVertexAttribPointers(l,e,s),n&&t.instanceCount&&t.setVertexAttribDivisor(l,e,n));o&&o.bind()}destroy(){this.vao&&(this.context.gl.deleteVertexArray(this.vao),this.vao=null)}}function xd(e,t){const i=Math.pow(2,t.canonical.z),o=t.canonical.y;return[new pe(0,o/i).toLngLat().lat,new pe(0,(o+1)/i).toLngLat().lat]}function bd(e,t,i,o,s,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&&"mrt-fallback"===e.emissiveMode&&d.push("USE_MRT1");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,o)=>{const s=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=Ee(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=Go(t.x,t.y,t.z);d=Ee(i[1])}const u=!e.options.moving;return{u_matrix:o||e.transform.calculateProjMatrix(t.tileID.toUnwrapped(),u),u_image:0,u_latrange:xd(0,t.tileID),u_light:[i.paint.get("hillshade-exaggeration"),d],u_shadow:s.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,o,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,s,r,n,fh.disabled,_,o.id,p,f,m)}function wd(e,t,i){if(!t.needsDEMTextureUpload)return;const o=e.context,s=o.gl;o.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 z(o,r,s.R32F,{premultiply:!1}),t.needsDEMTextureUpload=!1}function Td(e,t,i){const o=e.context,s=o.gl;if(!t.dem)return;const r=t.dem;if(o.activeTexture.set(s.TEXTURE1),wd(e,t,r),!t.demTexture)return;t.demTexture.bind(s.NEAREST,s.CLAMP_TO_EDGE);const n=r.dim;o.activeTexture.set(s.TEXTURE0);let a=t.hillshadeFBO;if(!a){const e=new z(o,{width:n,height:n,data:null},s.RGBA8);e.bind(s.LINEAR,s.CLAMP_TO_EDGE),a=t.hillshadeFBO=o.createFramebuffer(n,n,1,"renderbuffer"),a.colorAttachment0.set(e.texture)}o.bindFramebuffer.set(a.framebuffer),o.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&&"mrt-fallback"===e.emissiveMode&&d.push("USE_MRT1"),e.getOrCreateProgram("hillshadePrepare",{defines:d}).draw(e,s.TRIANGLES,hh.disabled,uh.disabled,ch.unblended,fh.disabled,((e,t)=>{const i=t.stride,o=$t();return Mi(o,0,we,-we,0,0,1),Bt(o,o,[0,-we,0]),{u_matrix:o,u_image:1,u_dimension:[i,i],u_zoom:e.overscaledZ}})(t.tileID,r),i.id,l,c,h),t.needsHillshadePrepare=!1}class Ed{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 Sd extends Ed{getDefault(){return Te.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 Id extends Ed{getDefault(){return 1}set(e){(e!==this.current||this.dirty)&&(this.gl.clearDepth(e),this.current=e,this.dirty=!1)}}class Cd extends Ed{getDefault(){return 0}set(e){(e!==this.current||this.dirty)&&(this.gl.clearStencil(e),this.current=e,this.dirty=!1)}}class Rd extends Ed{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 Ad extends Ed{getDefault(){return!0}set(e){(e!==this.current||this.dirty)&&(this.gl.depthMask(e),this.current=e,this.dirty=!1)}}class Dd extends Ed{getDefault(){return 255}set(e){(e!==this.current||this.dirty)&&(this.gl.stencilMask(e),this.current=e,this.dirty=!1)}}class Ld extends Ed{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 Od extends Ed{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 Pd extends Ed{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 Md extends Ed{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 zd extends Ed{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 Fd extends Ed{getDefault(){return this.gl.LESS}set(e){(e!==this.current||this.dirty)&&(this.gl.depthFunc(e),this.current=e,this.dirty=!1)}}class Bd extends Ed{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 kd extends Ed{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 Nd extends Ed{getDefault(){return Te.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 Ud extends Ed{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 jd extends Ed{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 Gd extends Ed{getDefault(){return this.gl.BACK}set(e){(e!==this.current||this.dirty)&&(this.gl.cullFace(e),this.current=e,this.dirty=!1)}}class Vd extends Ed{getDefault(){return this.gl.CCW}set(e){(e!==this.current||this.dirty)&&(this.gl.frontFace(e),this.current=e,this.dirty=!1)}}let Hd=class extends Ed{getDefault(){return null}set(e){(e!==this.current||this.dirty)&&(this.gl.useProgram(e),this.current=e,this.dirty=!1)}};class qd extends Ed{getDefault(){return this.gl.TEXTURE0}set(e){(e!==this.current||this.dirty)&&(this.gl.activeTexture(e),this.current=e,this.dirty=!1)}}class Zd extends Ed{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 Wd extends Ed{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 $d extends Ed{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 Xd extends Ed{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 Yd extends Ed{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 Kd extends Ed{getDefault(){return null}set(e){const t=this.gl;t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,e),this.current=e,this.dirty=!1}}class Qd extends Ed{getDefault(){return null}set(e){this.gl&&(e!==this.current||this.dirty)&&(this.gl.bindVertexArray(e),this.current=e,this.dirty=!1)}}class Jd extends Ed{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 eu extends Ed{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 tu extends Ed{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 iu extends Ed{constructor(e,t){super(e),this.context=e,this.parent=t}getDefault(){return null}}class ou extends iu{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 su extends iu{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 ru extends iu{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 nu extends su{attachment(){return this.gl.DEPTH_STENCIL_ATTACHMENT}}const au=(e,t,i,o)=>({u_matrix:e,u_image0:0,u_image1:1,u_skirt_height:t,u_ground_shadow_factor:i,u_emissive_texture_available:o}),lu=(e,t,i,o,s,r,n,a,l,c,h,d,u,_,p,f,m)=>({u_proj_matrix:Float32Array.from(e),u_globe_matrix:t,u_normalize_matrix:Float32Array.from(o),u_merc_matrix:i,u_zoom_transition:s,u_merc_center:r,u_image0:0,u_image1:1,u_frustum_tl:n,u_frustum_tr:a,u_frustum_br:l,u_frustum_bl:c,u_globe_pos:h,u_globe_radius:d,u_viewport:u,u_grid_matrix:m?Float32Array.from(m):new Float32Array(9),u_skirt_height:_,u_far_z_cutoff:p,u_emissive_texture_available:f});function cu(e,t){return null!=e&&null!=t&&!(!e.hasData()||!t.hasData())&&null!=e.demTexture&&null!=t.demTexture&&e.tileID.key!==t.tileID.key}const hu=new class{constructor(){this.operations={}}newMorphing(e,t,i,o,s){if(e in this.operations){const t=this.operations[e];t.to.tileID.key!==i.tileID.key&&(t.queued=i)}else this.operations[e]={startTime:o,phase:0,duration:s,from:t,to:i,queued:null}}getMorphValuesForProxy(e){if(!(e in this.operations))return null;const t=this.operations[e];return{from:t.from,to:t.to,phase:t.phase}}update(e){for(const t in this.operations){const i=this.operations[t];for(i.phase=(e-i.startTime)/i.duration;i.phase>=1||!this._validOp(i);)if(!this._nextOp(i,e)){delete this.operations[t];break}}}_nextOp(e,t){return!!e.queued&&(e.from=e.to,e.to=e.queued,e.queued=null,e.phase=0,e.startTime=t,!0)}_validOp(e){return e.from.hasData()&&e.to.hasData()}},du={0:null,1:"TERRAIN_VERTEX_MORPHING"};function uu(e,t,i){if(0===t)return 0;const o=t<1&&514===i?.25/t:1;return 6*Math.pow(1.5,22-e)*Math.max(t,1)*o}function _u(e,t){const i=1<<e.z;return!t&&(0===e.x||e.x===i-1)||0===e.y||e.y===i-1}function pu(e,t){if(!e.style||!e.style.enable3dLights())return;const i=e.context,o=i.gl;i.activeTexture.set(o.TEXTURE1),t?t.bind(o.LINEAR,o.CLAMP_TO_EDGE):e.emptyTexture.bind(o.LINEAR,o.CLAMP_TO_EDGE)}const fu=e=>({u_matrix:e});function mu(e,t,i,o,s){if(s>0){const r=w.now(),n=(r-e.timeAdded)/s,a=t?(r-t.timeAdded)/s:-1,l=i.getSource(),c=o.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:Fe(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}}class gu extends Kl{constructor(e){const t=Ll("mock-dem",{type:"raster-dem",maxzoom:e.transform.maxZoom},e.style.dispatcher,e.style);super("mock-dem",t,!1),t.setEventedParent(this),this._sourceLoaded=!0}_loadTile(e,t){e.state="loaded",t(null)}}class vu extends Kl{constructor(e){const t=Ll("proxy",{type:"geojson",maxzoom:e.transform.maxZoom},e.style.dispatcher,e.style);super("proxy",t,!1),t.setEventedParent(this),this.map=this.getSource().map=e,this.used=this._sourceLoaded=!0,this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}update(e,t,i){if(e.freezeTileCoverage)return;this.transform=e;const o=e.coveringTiles({tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled}).reduce(((t,i)=>{if(t[i.key]="",!this._tiles[i.key]){const t=new Wl(i,this._source.tileSize*i.overscaleFactor(),e.tileZoom,void 0,void 0,this._source.worldview);t.state="loaded",this._tiles[i.key]=t}return t}),{});for(const e in this._tiles)e in o||(this.freeFBO(e),this._tiles[e].unloadVectorData(),delete this._tiles[e])}freeFBO(e){const t=this.proxyCachedFBO[e];if(void 0!==t){const i=Object.values(t);this.renderCachePool.push(...i),delete this.proxyCachedFBO[e]}}deallocRenderCache(){this.renderCache.forEach((e=>e.fb.destroy())),this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}}class yu extends Ke{constructor(e,t,i){super(e.overscaledZ,e.wrap,e.canonical.z,e.canonical.x,e.canonical.y),this.proxyTileKey=t,this.projMatrix=i}}class xu extends _i{constructor(e,t){super(),this._debugParams={sortTilesHiZFirst:!0,disableRenderCache:!1},this.painter=e,this.terrainTileForTile={},this.prevTerrainTileForTile={};const[i,o,s]=function(e){const t=new Tt,i=new ht,o=131;t.reserve(17161),i.reserve(33800);const s=we/128,r=we+s/2,n=r+s;for(let e=-s;e<n;e+=s)for(let i=-s;i<n;i+=s){const o=i<0||i>r||e<0||e>r?24575:0,s=Fe(Math.round(i),0,we),n=Fe(Math.round(e),0,we);t.emplaceBack(s+o,n)}const a=(e,t)=>{const s=t*o+e;i.emplaceBack(s+1,s,s+o),i.emplaceBack(s+o,s+o+1,s+1)};for(let e=1;e<129;e++)for(let t=1;t<129;t++)a(t,e);return[0,129].forEach((e=>{for(let t=0;t<130;t++)a(t,e),a(e,t)})),[t,i,32768]}(),r=e.context;this.gridBuffer=r.createVertexBuffer(i,St.members),this.gridIndexBuffer=r.createIndexBuffer(o),this.gridSegments=It.simpleSegment(0,0,i.length,o.length),this.gridNoSkirtSegments=It.simpleSegment(0,0,i.length,s),this.proxyCoords=[],this.proxiedCoords={},this._visibleDemTiles=[],this._drapedRenderBatches=[],this._sourceTilesOverlap={},this.proxySourceCache=new vu(t.map),this.orthoMatrix=$t(),Mi(this.orthoMatrix,"globe"===this.painter.transform.projection.name?.015:0,we,0,we,0,1);const n=r.gl;this._overlapStencilMode=new uh({func:n.GEQUAL,mask:255},0,255,n.KEEP,n.KEEP,n.REPLACE),this._previousZoom=e.transform.zoom,this.pool=[],this._findCoveringTileCache={},this._tilesDirty={},this.style=t,this._useVertexMorphing=!0,this._exaggeration=1,this._mockSourceCache=new gu(t.map),this._pendingGroundEffectLayers=[],this._emissiveTexture=!1}set style(e){e.on("data",this._onStyleDataEvent.bind(this)),this._style=e,this._style.map.on("moveend",(()=>{this._clearLineLayersFromRenderCache()}))}update(e,t,i){if(e&&e.terrain){this._style!==e&&(this.style=e,this._evaluationZoom=void 0);const o=e.terrain.properties,s=0===e.terrain.drapeRenderMode,r=e.terrain.isZoomDependent();this._previousUpdateTimestamp=this.enabled?this._updateTimestamp:void 0,this._updateTimestamp=w.now();const n=e.terrain&&e.terrain.scope,a=o.get("source"),l=s?this._mockSourceCache:e.getSourceCache(a,n);if(!l)return void u(`Couldn't find terrain source "${a}".`);if(this.sourceCache=l,this._attenuationRange=e.terrain.getAttenuationRange(),this._exaggeration=r?this.calculateExaggeration(t):o.get("exaggeration"),!t.projection.requiresDraping&&r&&0===this._exaggeration)return void this._disable();this.enabled=!0;const c=()=>{this.sourceCache.used&&u(`Raster DEM source '${this.sourceCache.id}' is used both for terrain and as layer source.\nThis leads to lower resolution of hillshade. For full hillshade resolution but higher memory consumption, define another raster DEM source.`);const e=this.getScaledDemTileSize();this.sourceCache.update(t,e,!0),this.resetTileLookupCache(this.sourceCache.id)};this.sourceCache.usedForTerrain||(this.resetTileLookupCache(this.sourceCache.id),this.sourceCache.usedForTerrain=!0,c(),this._initializing=!0),c(),t.updateElevation(!0,i),this.resetTileLookupCache(this.proxySourceCache.id),this.proxySourceCache.update(t),this._emptyDEMTextureDirty=!0,this._previousZoom=t.zoom}else this._disable()}calculateExaggeration(e){if(this._attenuationRange&&e.zoom>=Math.ceil(this._attenuationRange[1]))return this._style.terrain.getExaggeration(e.zoom);const t=this._previousCameraAltitude,i=e.getFreeCameraOptions().position.z/e.pixelsPerMeter*e.worldSize;this._previousCameraAltitude=i;const o=null!=t?i-t:Number.MAX_VALUE;if(Math.abs(o)<2)return this._exaggeration;const s=e.zoom,r=this._style.terrain;if(!this._previousUpdateTimestamp)return r.getExaggeration(s);let n=s-this._previousZoom;const a=this._previousUpdateTimestamp;let l=s;null!=this._evaluationZoom&&(l=this._evaluationZoom,Math.abs(s-l)>.5&&(n=.5*(s-l+n)),n*o<0&&(l+=n)),this._evaluationZoom=l;const c=r.getExaggeration(l),h=c===r.getExaggeration(Math.max(0,l-.1));if(h&&Math.abs(c-this._exaggeration)<.01)return c;let d=Math.min(.1,.00375*(this._updateTimestamp-a));return(h||c<.1||Math.abs(n)<1e-4)&&(d=Math.min(.2,4*d)),xe(this._exaggeration,c,d)}resetTileLookupCache(e){this._findCoveringTileCache[e]={}}attenuationRange(){return this._attenuationRange}getDemUpscale(){return this.proxySourceCache.getSource().tileSize/128}getScaledDemTileSize(){return this.sourceCache.getSource().tileSize/128*this.proxySourceCache.getSource().tileSize}_onStyleDataEvent(e){"source"===e.dataType&&e.coord?this._clearRenderCacheForTile(e.sourceCacheId,e.coord):"style"===e.dataType&&(this.invalidateRenderCache=!0,this._evaluationZoom=void 0,this._previousUpdateTimestamp=void 0,this._previousCameraAltitude=void 0)}_disable(){if(this.enabled&&(this.enabled=!1,this._emptyDEMTextureDirty=!0,this._sharedDepthStencil=void 0,this._evaluationZoom=void 0,this._previousUpdateTimestamp=void 0,this.proxySourceCache.deallocRenderCache(),this._style))for(const e in this._style._mergedSourceCaches)this._style._mergedSourceCaches[e].usedForTerrain=!1}destroy(){this._disable(),this._emptyDEMTexture&&this._emptyDEMTexture.destroy(),this.pool.forEach((e=>e.fb.destroy())),this.pool=[],this.framebufferCopyTexture&&this.framebufferCopyTexture.destroy()}_source(){return this.enabled?this.sourceCache:null}isUsingMockSource(){return this.sourceCache===this._mockSourceCache}exaggeration(){return this.enabled?this._exaggeration:0}get visibleDemTiles(){return this._visibleDemTiles}get drapeBufferSize(){const e=2*this.proxySourceCache.getSource().tileSize;return[e,e]}set useVertexMorphing(e){this._useVertexMorphing=e}updateTileBinding(e){if(!this.enabled)return;this.prevTerrainTileForTile=this.terrainTileForTile;const t=this.proxySourceCache,i=this.painter.transform;this._initializing&&(this._initializing=0===i._centerAltitude&&-1===this.getAtPointOrZero(pe.fromLngLat(i.center),-1),this._emptyDEMTextureDirty=!this._initializing);const o=this.proxyCoords=t.getIds().map((e=>{const o=t.getTileByID(e).tileID;return o.projMatrix=i.calculateProjMatrix(o.toUnwrapped()),o}));!function(e,t){const i=t.transform.pointCoordinate(t.transform.getCameraPoint()),o=new r(i.x,i.y);e.sort(((e,t)=>{if(t.overscaledZ-e.overscaledZ)return t.overscaledZ-e.overscaledZ;const i=new r(e.canonical.x+(1<<e.canonical.z)*e.wrap,e.canonical.y),s=new r(t.canonical.x+(1<<t.canonical.z)*t.wrap,t.canonical.y),n=o.mult(1<<e.canonical.z);return n.x-=.5,n.y-=.5,n.distSqr(i)-n.distSqr(s)}))}(o,this.painter);const s=this.proxyToSource||{};this.proxyToSource={},o.forEach((e=>{this.proxyToSource[e.key]={}})),this.terrainTileForTile={};const n=this._style._mergedSourceCaches;for(const t in n){const i=n[t];if(!i.used)continue;if(i!==this.sourceCache&&this.resetTileLookupCache(i.id),this._setupProxiedCoordsForOrtho(i,e[t],s),i.usedForTerrain)continue;const o=e[t];i.getSource().reparseOverscaled&&this._assignTerrainTiles(o)}this.proxiedCoords[t.id]=o.map((e=>new yu(e,e.key,this.orthoMatrix))),this._assignTerrainTiles(o),this._prepareDEMTextures(),this._setupDrapedRenderBatches(),this._initFBOPool(),this._setupRenderCache(s),this.renderingToTexture=!1;const a={};this._visibleDemTiles=[];for(const e of this.proxyCoords){const t=this.terrainTileForTile[e.key];if(!t)continue;const i=t.tileID.key;i in a||(this._visibleDemTiles.push(t),a[i]=i)}}_assignTerrainTiles(e){this._initializing||e.forEach((e=>{if(this.terrainTileForTile[e.key])return;const t=this._findTileCoveringTileID(e,this.sourceCache);t&&(this.terrainTileForTile[e.key]=t)}))}_prepareDEMTextures(){const e=this.painter.context,t=e.gl;for(const i in this.terrainTileForTile){const o=this.terrainTileForTile[i],s=o.dem;!s||o.demTexture&&!o.needsDEMTextureUpload||(e.activeTexture.set(t.TEXTURE1),wd(this.painter,o,s))}}_prepareDemTileUniforms(e,t,i,o){if(!t||null==t.demTexture)return!1;const s=e.tileID.canonical,r=Math.pow(2,t.tileID.canonical.z-s.z),n=o||"";return i[`u_dem_tl${n}`]=[s.x*r%1,s.y*r%1],i[`u_dem_scale${n}`]=r,!0}get emptyDEMTexture(){return!this._emptyDEMTextureDirty&&this._emptyDEMTexture?this._emptyDEMTexture:this._updateEmptyDEMTexture()}_getLoadedAreaMinimum(){if(!this.enabled)return 0;let e=0;const t=this._visibleDemTiles.reduce(((t,i)=>{if(!i.dem)return t;const o=i.dem.tree.minimums[0];return o>0&&e++,t+o}),0);return e?t/e:0}_updateEmptyDEMTexture(){const e=this.painter.context,t=e.gl;e.activeTexture.set(t.TEXTURE2);const i=this._getLoadedAreaMinimum(),o=new Ts({width:1,height:1},new Float32Array([i]));this._emptyDEMTextureDirty=!1;let s=this._emptyDEMTexture;return s?s.update(o,{premultiply:!1}):s=this._emptyDEMTexture=new z(e,o,t.R32F,{premultiply:!1}),s}setupElevationDraw(e,t,i){const o=this.painter.context,s=o.gl,r={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};r.u_exaggeration=this.exaggeration();let n=null,a=null,l=1;if(i&&i.morphing&&this._useVertexMorphing){const t=i.morphing.srcDemTile,o=i.morphing.dstDemTile;l=i.morphing.phase,t&&o&&(this._prepareDemTileUniforms(e,t,r,"_prev")&&(a=t),this._prepareDemTileUniforms(e,o,r)&&(n=o))}const c=e=>e&&e.demTexture&&this.painter.linearFloatFilteringSupported()?s.LINEAR:s.NEAREST;let h=null;var d;if(this.enabled?a&&n?(h=n.demTexture,o.activeTexture.set(s.TEXTURE4),a.demTexture.bind(c(a),s.CLAMP_TO_EDGE),r.u_dem_lerp=l):(n=this.terrainTileForTile[e.tileID.key],h=this._prepareDemTileUniforms(e,n,r)?n.demTexture:this.emptyDEMTexture):h=this.emptyDEMTexture,o.activeTexture.set(s.TEXTURE2),h&&(r.u_dem_size=1===(d=h).size[0]?1:d.size[0]-2,h.bind(c(n),s.CLAMP_TO_EDGE)),this.painter.setupDepthForOcclusion(i&&i.useDepthForOcclusion,t,r),i&&i.useMeterToDem&&n){const e=(1<<n.tileID.canonical.z)*zi(1,this.painter.transform.center.lat)*this.sourceCache.getSource().tileSize;r.u_meter_to_dem=e}if(i&&i.labelPlaneMatrixInv&&(r.u_label_plane_matrix_inv=i.labelPlaneMatrixInv),t.setTerrainUniformValues(o,r),"globe"===this.painter.transform.projection.name){const s=this.globeUniformValues(this.painter.transform,e.tileID.canonical,i&&i.useDenormalizedUpVectorScale);t.setGlobeUniformValues(o,s)}}globeUniformValues(e,t,i){const o=e.projection;return{u_tile_tl_up:o.upVector(t,0,0),u_tile_tr_up:o.upVector(t,we,0),u_tile_br_up:o.upVector(t,we,we),u_tile_bl_up:o.upVector(t,0,we),u_tile_up_scale:i?Es(1):o.upVectorScale(t,e.center.lat,e.worldSize).metersToTile}}renderToBackBuffer(e){const t=this.painter,i=this.painter.context;0!==e.length&&(i.bindFramebuffer.set(null),i.viewport.set([0,0,t.width,t.height]),t.gpuTimingDeferredRenderStart(),this.renderingToTexture=!1,function(e,t,i,o,s){if("globe"===e.transform.projection.name)!function(e,t,i,o,s){const r=e.context,n=r.gl;let a,l;const c=e.transform,h=fs(e,r,c),d=(t,i)=>{if(l===i)return;const o=[du[i],"PROJECTION_GLOBE_VIEW"];h&&o.push("CUSTOM_ANTIALIASING");const s=e.isTileAffectedByFog(t);a=e.getOrCreateProgram("globeRaster",{defines:o,overrideFog:s}),l=i},u=e.colorModeForRenderPass(),_=new hh(n.LEQUAL,hh.ReadWrite,e.depthRangeFor3D);hu.update(s);const p=ms(c),f=[Ge(c.center.lng),qe(c.center.lat)],m=e.globeSharedBuffers,g=[c.width*w.devicePixelRatio,c.height*w.devicePixelRatio],v=Float32Array.from(c.globeMatrix),y={useDenormalizedUpVectorScale:!0};{const c=e.transform,h=uu(c.zoom,t.exaggeration(),t.sourceCache._source.tileSize);l=-1;const x=n.TRIANGLES;for(const l of o){const o=i.getTile(l),b=uh.disabled,w=t.prevTerrainTileForTile[l.key],T=t.terrainTileForTile[l.key];cu(w,T)&&hu.newMorphing(l.key,w,T,s,250),pu(e,o.emissiveTexture),r.activeTexture.set(n.TEXTURE0),o.texture&&o.texture.bind(n.LINEAR,n.CLAMP_TO_EDGE);const E=hu.getMorphValuesForProxy(l.key),S=E?1:0;E&&Object.assign(y,{morphing:{srcDemTile:E.from,dstDemTile:E.to,phase:gs(E.phase)}});const I=vs(l.canonical),C=ys(I.getCenter().lat),R=xs(l.canonical,I,C,c.worldSize/c._pixelsPerMercatorPixel),A=Dt(bs(l.canonical)),D="mrt-fallback"===e.emissiveMode?1:0,L=lu(c.expandedFarZProjMatrix,v,p,A,ye(c.zoom),f,c.frustumCorners.TL,c.frustumCorners.TR,c.frustumCorners.BR,c.frustumCorners.BL,c.globeCenterInViewSpace,c.globeRadius,g,h,c._farZ,D,R);if(d(l,S),a&&(t.setupElevationDraw(o,a,y),e.uploadCommonUniforms(r,a,l.toUnwrapped()),m)){const[t,i,o]=m.getGridBuffers(C,0!==h);a.draw(e,x,_,b,u,fh.backCCW,L,"globe_raster",t,i,o)}}}if(m&&(e.renderDefaultNorthPole||e.renderDefaultSouthPole)){const s=["GLOBE_POLES","PROJECTION_GLOBE_VIEW"];h&&s.push("CUSTOM_ANTIALIASING"),a=e.getOrCreateProgram("globeRaster",{defines:s});for(const s of o){const{x:o,y:l,z:h}=s.canonical,d=0===l,p=l===(1<<h)-1,[v,x,b,w]=m.getPoleBuffers(h,!1);if(w&&(d||p)){const l=i.getTile(s);pu(e,l.emissiveTexture),r.activeTexture.set(n.TEXTURE0),l.texture&&l.texture.bind(n.LINEAR,n.CLAMP_TO_EDGE);let m=ws(h,o,c);const T=Dt(bs(s.canonical)),E="mrt-fallback"===e.emissiveMode?1:0,S=(t,i)=>t.draw(e,n.TRIANGLES,_,uh.disabled,u,fh.disabled,lu(c.expandedFarZProjMatrix,m,m,T,0,f,c.frustumCorners.TL,c.frustumCorners.TR,c.frustumCorners.BR,c.frustumCorners.BL,c.globeCenterInViewSpace,c.globeRadius,g,0,c._farZ,E),"globe_pole_raster",i,b,w);t.setupElevationDraw(l,a,y),e.uploadCommonUniforms(r,a,s.toUnwrapped()),d&&e.renderDefaultNorthPole&&S(a,v),p&&e.renderDefaultSouthPole&&(m=vo($t(),m,[1,-1,1]),S(a,x))}}}}(e,t,i,o,s);else{const r=e.context,n=r.gl;let a,l;const c=e.shadowRenderer,h=Sh(e,e.longestCutoffRange),d=t=>{if(l===t)return;const i=[];i.push(du[t]),h.shouldRenderCutoff&&i.push("RENDER_CUTOFF"),c&&(i.push("RENDER_SHADOWS","DEPTH_TEXTURE"),c.useNormalOffset&&i.push("NORMAL_OFFSET")),a=e.getOrCreateProgram("terrainRaster",{defines:i}),l=t},u=e.colorModeForRenderPass(),_=new hh(n.LEQUAL,hh.ReadWrite,e.depthRangeFor3D);hu.update(s);const p=e.transform,f=uu(p.zoom,t.exaggeration(),t.sourceCache._source.tileSize);let m=[0,0,0];if(c){const t=e.style.directionalLight,i=e.style.ambientLight;t&&i&&(m=Oh(e.style,t,i))}{l=-1;const g=n.TRIANGLES,[v,y]=[t.gridIndexBuffer,t.gridSegments];for(const l of o){const o=i.getTile(l),x=uh.disabled,b=t.prevTerrainTileForTile[l.key],w=t.terrainTileForTile[l.key];cu(b,w)&&hu.newMorphing(l.key,b,w,s,250),pu(e,o.emissiveTexture),r.activeTexture.set(n.TEXTURE0),o.texture&&o.texture.bind(n.LINEAR,n.CLAMP_TO_EDGE);const T=hu.getMorphValuesForProxy(l.key),E=T?1:0;let S;T&&(S={morphing:{srcDemTile:T.from,dstDemTile:T.to,phase:gs(T.phase)}});const I="mrt-fallback"===e.emissiveMode?1:0,C=au(l.projMatrix,_u(l.canonical,p.renderWorldCopies)?f/10:f,m,I);if(d(E),!a)continue;t.setupElevationDraw(o,a,S);const R=l.toUnwrapped();c&&c.setupShadows(R,a),e.uploadCommonUniforms(r,a,R,null,h),a.draw(e,g,_,x,u,fh.backCCW,C,"terrain_raster",t.gridBuffer,v,y)}}}}(t,this,this.proxySourceCache,e,this._updateTimestamp),this.renderingToTexture=!0,t.gpuTimingDeferredRenderEnd(),e.splice(0,e.length))}renderBatch(e){if(0===this._drapedRenderBatches.length)return e+1;this.renderingToTexture=!0;const t=this.painter,i=this.painter.context,o=this.proxySourceCache,s=this.proxiedCoords[o.id],r=this._drapedRenderBatches.shift(),n=t.style.order,a=[];this._updateFBOs("mrt-fallback"===t.emissiveMode);let l=0;for(const c of s){const s=o.getTileByID(c.proxyTileKey),h=o.proxyCachedFBO[c.key]?o.proxyCachedFBO[c.key][e]:void 0,d=void 0!==h?o.renderCache[h]:this.pool[l++],u=void 0!==h;if(s.texture=d.tex,s.emissiveTexture=d.emissiveTex,u&&!d.dirty){a.push(s.tileID);continue}i.bindFramebuffer.set(d.fb.framebuffer);const _=i.gl;let p;_.drawBuffers("mrt-fallback"===t.emissiveMode?[_.COLOR_ATTACHMENT0,_.COLOR_ATTACHMENT1]:[_.COLOR_ATTACHMENT0]),this.renderedToTile=!1,d.dirty&&(i.clear({color:Te.transparent,stencil:0}),d.dirty=!1);for(let e=r.start;e<=r.end;++e){const o=t.style._mergedLayers[n[e]];if(o.isHidden(t.transform.zoom))continue;const s=t.style.getLayerSourceCache(o),r=s?this.proxyToSource[c.key][s.id]:[c];if(!r)continue;const a=r;i.viewport.set([0,0,d.fb.width,d.fb.height]),p!==(s?s.id:null)&&(this._setupStencil(d,r,o,s),p=s?s.id:null),t.renderLayer(t,s,o,a)}if(_.drawBuffers([_.COLOR_ATTACHMENT0]),0===this._drapedRenderBatches.length)for(const e of this._pendingGroundEffectLayers){const o=t.style._mergedLayers[n[e]];if(o.isHidden(t.transform.zoom))continue;const s=t.style.getLayerSourceCache(o),r=s?this.proxyToSource[c.key][s.id]:[c];if(!r)continue;const a=r;i.viewport.set([0,0,d.fb.width,d.fb.height]),p!==(s?s.id:null)&&(this._setupStencil(d,r,o,s),p=s?s.id:null),t.renderLayer(t,s,o,a)}this.renderedToTile?(d.dirty=!0,a.push(s.tileID)):u||--l,5===l&&(l=0,this.renderToBackBuffer(a))}return this.renderToBackBuffer(a),this.renderingToTexture=!1,i.bindFramebuffer.set(null),i.viewport.set([0,0,t.width,t.height]),r.end+1}postRender(){}isLayerOrderingCorrect(e){const t=e.order.length;let i=-1,o=t;for(let s=0;s<t;++s)this._style.isLayerDraped(e._mergedLayers[e.order[s]])?i=Math.max(i,s):o=Math.min(o,s);return o>i}getMinElevationBelowMSL(){let e=0;return this._visibleDemTiles.filter((e=>e.dem)).forEach((t=>{e=Math.min(e,t.dem.tree.minimums[0])})),0===e?e:(e-30)*this._exaggeration}raycast(e,t,i){if(!this._visibleDemTiles)return null;const o=this._visibleDemTiles.filter((e=>e.dem)).map((o=>{const s=o.tileID,r=1<<s.overscaledZ,{x:n,y:a}=s.canonical,l=n/r,c=(n+1)/r,h=a/r,d=(a+1)/r;return{minx:l,miny:h,maxx:c,maxy:d,t:o.dem.tree.raycastRoot(l,h,c,d,e,t,i),tile:o}}));o.sort(((e,t)=>(null!==e.t?e.t:Number.MAX_VALUE)-(null!==t.t?t.t:Number.MAX_VALUE)));for(const s of o){if(null==s.t)return null;const o=s.tile.dem.tree.raycast(s.minx,s.miny,s.maxx,s.maxy,e,t,i);if(null!=o)return o}return null}_createFBO(){const e=this.painter.context,t=e.gl,i=this.drapeBufferSize;e.activeTexture.set(t.TEXTURE0);const o=new z(e,{width:i[0],height:i[1],data:null},t.RGBA8);o.bind(t.LINEAR,t.CLAMP_TO_EDGE);const s=e.createFramebuffer(i[0],i[1],1,null);let r;return s.colorAttachment0.set(o.texture),this._emissiveTexture&&(r=new z(e,{width:i[0],height:i[1],data:null},t.R8),r.bind(t.LINEAR,t.CLAMP_TO_EDGE),s.createColorAttachment(e,1),s.colorAttachment1.set(r.texture)),s.depthAttachment=new nu(e,s.framebuffer),void 0===this._sharedDepthStencil?(this._sharedDepthStencil=e.createRenderbuffer(e.gl.DEPTH_STENCIL,i[0],i[1]),this._stencilRef=0,s.depthAttachment.set(this._sharedDepthStencil),e.clear({stencil:0})):s.depthAttachment.set(this._sharedDepthStencil),e.extTextureFilterAnisotropic&&t.texParameterf(t.TEXTURE_2D,e.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,e.extTextureFilterAnisotropicMax),{fb:s,tex:o,emissiveTex:r,dirty:!1}}_updateFBOs(e){if(this._emissiveTexture!==e){for(const t of this.pool)this._updateFBO(t,e);for(const t of this.proxySourceCache.renderCache)this._updateFBO(t,e);this._emissiveTexture=e}}_updateFBO(e,t){const i=e.fb,o=this.painter.context,s=o.gl,r=this.drapeBufferSize;if(t){const t=new z(o,{width:r[0],height:r[1],data:null},s.R8);t.bind(s.LINEAR,s.CLAMP_TO_EDGE),e.emissiveTex=t,i.createColorAttachment(o,1),i.colorAttachment1.set(t.texture)}else e.emissiveTex=void 0,i.removeColorAttachment(o,1);e.dirty=!0}_initFBOPool(){for(;this.pool.length<Math.min(5,this.proxyCoords.length);)this.pool.push(this._createFBO())}_shouldDisableRenderCache(){if(this._debugParams.disableRenderCache)return!0;if(this._style.hasLightTransitions())return!0;for(const e in this._style._mergedSourceCaches)if(this._style._mergedSourceCaches[e].hasTransition())return!0;return this._style.order.some((e=>{const t=this._style._mergedLayers[e],i=t.isHidden(this.painter.transform.zoom);return"hillshade"===t.type||"custom"===t.type?!i&&t.shouldRedrape():!i&&t.hasTransition()}))}_clearLineLayersFromRenderCache(){let e=!1;for(const t of this._style.getSources())if(t instanceof Il){e=!0;break}if(!e)return;const t={};for(let e=0;e<this._style.order.length;++e){const i=this._style._mergedLayers[this._style.order[e]],o=this._style.getLayerSourceCache(i);if(!o||t[o.id])continue;if(i.isHidden(this.painter.transform.zoom)||"line"!==i.type)continue;const s=i.widthExpression(),r=i.emissiveStrengthExpression();if(s instanceof _e||r instanceof _e){t[o.id]=!0;for(const e of this.proxyCoords){const t=this.proxyToSource[e.key][o.id];if(t)for(const e of t)this._clearRenderCacheForTile(o.id,e)}}}}_clearRasterLayersFromRenderCache(){let e=!1;for(const t in this._style._mergedSourceCaches)if(this._style._mergedSourceCaches[t]._source instanceof Cl){e=!0;break}if(!e)return;const t={};for(let e=0;e<this._style.order.length;++e){const i=this._style._mergedLayers[this._style.order[e]],o=this._style.getLayerSourceCache(i);if(!o||t[o.id])continue;if(i.isHidden(this.painter.transform.zoom)||"raster"!==i.type)continue;const s=i.paint.get("raster-fade-duration");for(const e of this.proxyCoords){const t=this.proxyToSource[e.key][o.id];if(t)for(const e of t){const t=mu(o.getTile(e),o.findLoadedParent(e,0),o,this.painter.transform,s);(1!==t.opacity||0!==t.mix)&&this._clearRenderCacheForTile(o.id,e)}}}}_setupDrapedRenderBatches(){this._style.updateDrapeFirstLayers();const e=this._style.order,t=e.length;if(0===t)return;const i=[];this._pendingGroundEffectLayers=[];let o,s=0,r=this._style._mergedLayers[e[s]];for(;!this._style.isLayerDraped(r)&&r.isHidden(this.painter.transform.zoom)&&++s<t;)r=this._style._mergedLayers[e[s]];for(;s<t;++s){const t=this._style._mergedLayers[e[s]];t.isHidden(this.painter.transform.zoom)||(this._style.isLayerDraped(t)?void 0===o&&(o=s):("fill-extrusion"===t.type&&this._pendingGroundEffectLayers.push(s),void 0!==o&&(i.push({start:o,end:s-1}),o=void 0)))}if(void 0!==o&&i.push({start:o,end:s-1}),0!==i.length){const e=i[i.length-1];this._pendingGroundEffectLayers.every((t=>t>e.end))||u("fill-extrusion with flood lighting and/or ground ambient occlusion should be moved to be on top of all draped layers.")}this._drapedRenderBatches=i}_setupRenderCache(e){const t=this.proxySourceCache;if(this._shouldDisableRenderCache()||this.invalidateRenderCache){if(this.invalidateRenderCache=!1,t.renderCache.length>t.renderCachePool.length){const e=Object.values(t.proxyCachedFBO);t.proxyCachedFBO={};for(let i=0;i<e.length;++i){const o=Object.values(e[i]);t.renderCachePool.push(...o)}}return}this._clearRasterLayersFromRenderCache();const i=this.proxyCoords,o=this._tilesDirty;for(let s=i.length-1;s>=0;s--){const r=i[s];if(t.getTileByID(r.key),void 0!==t.proxyCachedFBO[r.key]){const i=e[r.key],s=this.proxyToSource[r.key];let n=0;for(const e in s){const t=s[e],r=i[e];if(!r||r.length!==t.length||t.some(((t,i)=>t!==r[i]||o[e]&&o[e].hasOwnProperty(t.key)))){n=-1;break}++n}for(const e in t.proxyCachedFBO[r.key])t.renderCache[t.proxyCachedFBO[r.key][e]].dirty=n<0||n!==Object.values(i).length}}const s=[...this._drapedRenderBatches];s.sort(((e,t)=>t.end-t.start-(e.end-e.start)));for(const e of s)for(const o of i){if(t.proxyCachedFBO[o.key])continue;let i=t.renderCachePool.pop();void 0===i&&t.renderCache.length<50&&(i=t.renderCache.length,t.renderCache.push(this._createFBO())),void 0!==i&&(t.proxyCachedFBO[o.key]={},t.proxyCachedFBO[o.key][e.start]=i,t.renderCache[i].dirty=!0)}this._tilesDirty={}}_setupStencil(e,t,i,o){if(!o||!this._sourceTilesOverlap[o.id])return void(this._overlapStencilType&&(this._overlapStencilType=!1));const s=this.painter.context,r=s.gl;if(t.length<=1)return void(this._overlapStencilType=!1);let n;if(i.isTileClipped())n=t.length,this._overlapStencilMode.test={func:r.EQUAL,mask:255},this._overlapStencilType="Clip";else{if(!(t[0].overscaledZ>t[t.length-1].overscaledZ))return void(this._overlapStencilType=!1);n=1,this._overlapStencilMode.test={func:r.GREATER,mask:255},this._overlapStencilType="Mask"}this._stencilRef+n>255&&(s.clear({stencil:0}),this._stencilRef=0),this._stencilRef+=n,this._overlapStencilMode.ref=this._stencilRef,i.isTileClipped()&&this._renderTileClippingMasks(t,this._overlapStencilMode.ref)}clipOrMaskOverlapStencilType(){return"Clip"===this._overlapStencilType||"Mask"===this._overlapStencilType}stencilModeForRTTOverlap(e){return this.renderingToTexture&&this._overlapStencilType?("Clip"===this._overlapStencilType&&(this._overlapStencilMode.ref=this.painter._tileClippingMaskIDs[e.key]),this._overlapStencilMode):uh.disabled}_renderTileClippingMasks(e,t){const i=this.painter,o=this.painter.context,s=o.gl;i._tileClippingMaskIDs={},o.setColorMode(ch.disabled),o.setDepthMode(hh.disabled);const r=i.getOrCreateProgram("clippingMask");for(const o of e){const e=i._tileClippingMaskIDs[o.key]=--t;r.draw(i,s.TRIANGLES,hh.disabled,new uh({func:s.ALWAYS,mask:0},e,255,s.KEEP,s.KEEP,s.REPLACE),ch.disabled,fh.disabled,fu(o.projMatrix),"$clipping",i.tileExtentBuffer,i.quadTriangleIndexBuffer,i.tileExtentSegments)}}pointCoordinate(e){const t=this.painter.transform;if(e.x<0||e.x>t.width||e.y<0||e.y>t.height)return null;const i=[e.x,e.y,1,1];ke(i,i,t.pixelMatrixInverse),lo(i,i,1/i[3]),i[0]/=t.worldSize,i[1]/=t.worldSize;const o=t._camera.position,s=zi(1,t.center.lat),r=[o[0],o[1],o[2]/s,0],n=Uo([],i.slice(0,3),r);Oe(n,n);const a=this.raycast(r,n,this._exaggeration);return null!==a&&a?(Jt(r,r,n,a),r[3]=r[2],r[2]*=s,r):null}_setupProxiedCoordsForOrtho(e,t,i){if(e.getSource()instanceof it)return this._setupProxiedCoordsForImageSource(e,t,i);this._findCoveringTileCache[e.id]=this._findCoveringTileCache[e.id]||{};const o=this.proxiedCoords[e.id]=[],s=this.proxyCoords;for(let t=0;t<s.length;t++){const r=s[t],n=this._findTileCoveringTileID(r,e);if(n){const t=this._createProxiedId(r,n,i[r.key]&&i[r.key][e.id]);o.push(t),this.proxyToSource[r.key][e.id]=[t]}}let r=!1;const n=new Set;for(let s=0;s<t.length;s++){const a=e.getTile(t[s]);if(!a||!a.hasData())continue;const l=this._findTileCoveringTileID(a.tileID,this.proxySourceCache);if(l&&l.tileID.canonical.z!==a.tileID.canonical.z){const t=this.proxyToSource[l.tileID.key][e.id],s=this._createProxiedId(l.tileID,a,i[l.tileID.key]&&i[l.tileID.key][e.id]);t?t.splice(t.length-1,0,s):this.proxyToSource[l.tileID.key][e.id]=[s];const c=this.proxyToSource[l.tileID.key][e.id];n.has(c)||n.add(c),o.push(s),r=!0}}if(this._sourceTilesOverlap[e.id]=r,r&&this._debugParams.sortTilesHiZFirst)for(const e of n)e.sort(((e,t)=>t.overscaledZ-e.overscaledZ))}_setupProxiedCoordsForImageSource(e,t,i){if(!e.getSource().loaded())return;const o=this.proxiedCoords[e.id]=[],s=this.proxyCoords,n=e.getSource(),a=n.tileID;if(!a)return;const l=new r(a.x,a.y)._div(1<<a.z),c=n.coordinates.map(pe.fromLngLat).reduce(((e,t)=>(e.min.x=Math.min(e.min.x,t.x-l.x),e.min.y=Math.min(e.min.y,t.y-l.y),e.max.x=Math.max(e.max.x,t.x-l.x),e.max.y=Math.max(e.max.y,t.y-l.y),e)),{min:new r(Number.MAX_VALUE,Number.MAX_VALUE),max:new r(-Number.MAX_VALUE,-Number.MAX_VALUE)}),h=(e,t)=>{const i=e.wrap+e.canonical.x/(1<<e.canonical.z),o=e.canonical.y/(1<<e.canonical.z),s=we/(1<<e.canonical.z),r=t.wrap+t.canonical.x/(1<<t.canonical.z),n=t.canonical.y/(1<<t.canonical.z);return i+s<r+c.min.x||i>r+c.max.x||o+s<n+c.min.y||o>n+c.max.y};for(let r=0;r<s.length;r++){const n=s[r];for(let s=0;s<t.length;s++){const r=e.getTile(t[s]);if(!r||!r.hasData())continue;if(h(n,r.tileID))continue;const a=this._createProxiedId(n,r,i[n.key]&&i[n.key][e.id]),l=this.proxyToSource[n.key][e.id];l?l.push(a):this.proxyToSource[n.key][e.id]=[a],o.push(a)}}}_createProxiedId(e,t,i){let o=this.orthoMatrix;if(i){const e=i.find((e=>e.key===t.tileID.key));if(e)return e}if(t.tileID.key!==e.key){const i=e.canonical.z-t.tileID.canonical.z;let s,r,n;o=$t();const a=t.tileID.wrap-e.wrap<<e.overscaledZ;i>0?(s=we>>i,r=s*((t.tileID.canonical.x<<i)-e.canonical.x+a),n=s*((t.tileID.canonical.y<<i)-e.canonical.y)):(s=we<<-i,r=we*(t.tileID.canonical.x-(e.canonical.x+a<<-i)),n=we*(t.tileID.canonical.y-(e.canonical.y<<-i))),Mi(o,0,s,0,s,0,1),Bt(o,o,[r,n,0])}return new yu(t.tileID,e.key,o)}_findTileCoveringTileID(e,t){let i=t.getTile(e);if(i&&i.hasData())return i;const o=this._findCoveringTileCache[t.id],s=o[e.key];if(i=s?t.getTileByID(s):null,i&&i.hasData()||null===s)return i;let r=i?i.tileID:e,n=r.overscaledZ;const a=t.getSource().minzoom,l=[];if(!s){const o=t.getSource().maxzoom;if(e.canonical.z>=o){const i=e.canonical.z-o;t.getSource().reparseOverscaled?(n=Math.max(e.canonical.z+2,t.transform.tileZoom),r=new Ke(n,e.wrap,o,e.canonical.x>>i,e.canonical.y>>i)):0!==i&&(n=o,r=new Ke(n,e.wrap,o,e.canonical.x>>i,e.canonical.y>>i))}r.key!==e.key&&(l.push(r.key),i=t.getTile(r))}const c=e=>{l.forEach((t=>{o[t]=e})),l.length=0};for(n-=1;n>=a&&(!i||!i.hasData());n--){i&&c(i.tileID.key);const e=r.calculateScaledKey(n);if(i=t.getTileByID(e),i&&i.hasData())break;const s=o[e];if(null===s)break;void 0===s?l.push(e):i=t.getTileByID(s)}return c(i?i.tileID.key:null),i&&i.hasData()?i:null}findDEMTileFor(e){return this.enabled?this._findTileCoveringTileID(e,this.sourceCache):null}prepareDrawTile(){this.renderedToTile=!0}_clearRenderCacheForTile(e,t){let i=this._tilesDirty[e];i||(i=this._tilesDirty[e]={}),i[t.key]=!0}}function bu(e,t,i){const o=function(e,t,i){const o=ni(t,e),s=ni(i,[.2126,.7152,.0722]),r=(e,t,i)=>(1-i)*e+i*t,n=r(1-.3*Math.min(s,1),1,Math.min(o+1,1));return r(.92,1,Math.asin(Fe(t[2],-1,1))/Math.PI+.5)*n}(e,[0,0,1],t),s=[0,0,0];Si(s,i.slice(0,3),o);const r=[0,0,0];Si(r,t.slice(0,3),e[2]);const n=[0,0,0];return ko(n,s,r),jo(n)}const wu=["fill","fillOutline","fillPattern","line","linePattern","background","backgroundPattern","hillshade","raster"],Tu=["stars","rainParticle","snowParticle","fillExtrusion","fillExtrusionGroundEffect","building","buildingBloom","elevatedStructures","model","symbol"];class Eu{static cacheKey(e,t,i,o){const s=[t];o&&s.push(o.cacheKey);for(const t of i)e.usedDefines.has(t)&&s.push(t);return s.join("/")}constructor(e,t,i,o,s,r){const n=e.gl;this.program=n.createProgram(),this.configuration=o,this.name=t,this.fixedDefines=[...r];const a=`#version 300 es\n${(o?o.defines():[]).concat(r.map((e=>`#define ${e}`))).join("\n")}`,l=[a,pd];for(const e of i.fragmentIncludes)l.push(hd[e]);l.push(i.fragmentSource);const c=l.join("\n"),h=[a,fd];for(const e of i.vertexIncludes)h.push(hd[e]);this.forceManualRenderingForInstanceIDShaders=e.forceManualRenderingForInstanceIDShaders&&i.vertexSource.includes("gl_InstanceID"),this.forceManualRenderingForInstanceIDShaders&&h.push("uniform int u_instanceID;"),h.push(i.vertexSource);let d=h.join("\n");this.forceManualRenderingForInstanceIDShaders&&(d=d.replaceAll("gl_InstanceID","u_instanceID"));const u=n.createShader(n.FRAGMENT_SHADER);if(n.isContextLost())return void(this.failedToCreate=!0);n.shaderSource(u,c),n.compileShader(u),n.attachShader(this.program,u);const _=n.createShader(n.VERTEX_SHADER);n.isContextLost()?this.failedToCreate=!0:(n.shaderSource(_,d),n.compileShader(_),n.attachShader(this.program,_),this.attributes={},n.linkProgram(this.program),n.deleteShader(_),n.deleteShader(u),this.fixedUniforms=s(e),this.fixedUniformsEntries=Object.entries(this.fixedUniforms),this.binderUniforms=o?o.getUniforms(e):[],this.forceManualRenderingForInstanceIDShaders&&(this.instancingUniforms=(e=>({u_instanceID:new Bi(e)}))(e)),(r.includes("TERRAIN")||t.includes("symbol")||t.includes("circle"))&&(this.terrainUniforms=(e=>({u_dem:new Bi(e),u_dem_prev:new Bi(e),u_dem_tl:new Ui(e),u_dem_scale:new Ni(e),u_dem_tl_prev:new Ui(e),u_dem_scale_prev:new Ni(e),u_dem_size:new Ni(e),u_dem_lerp:new Ni(e),u_exaggeration:new Ni(e),u_depth:new Bi(e),u_depth_size_inv:new Ui(e),u_depth_range_unpack:new Ui(e),u_occluder_half_size:new Ni(e),u_occlusion_depth_offset:new Ni(e),u_meter_to_dem:new Ni(e),u_label_plane_matrix_inv:new ji(e)}))(e)),r.includes("GLOBE")&&(this.globeUniforms=(e=>({u_tile_tl_up:new ki(e),u_tile_tr_up:new ki(e),u_tile_br_up:new ki(e),u_tile_bl_up:new ki(e),u_tile_up_scale:new Ni(e)}))(e)),r.includes("FOG")&&(this.fogUniforms=(e=>({u_fog_matrix:new ji(e),u_fog_range:new Ui(e),u_fog_color:new Mo(e),u_fog_horizon_blend:new Ni(e),u_fog_vertical_limit:new Ui(e),u_fog_temporal_offset:new Ni(e),u_frustum_tl:new ki(e),u_frustum_tr:new ki(e),u_frustum_br:new ki(e),u_frustum_bl:new ki(e),u_globe_pos:new ki(e),u_globe_radius:new Ni(e),u_globe_transition:new Ni(e),u_is_globe:new Bi(e),u_viewport:new Ui(e)}))(e)),r.includes("RENDER_CUTOFF")&&(this.cutoffUniforms=(e=>({u_cutoff_params:new Mo(e)}))(e)),r.includes("LIGHTING_3D_MODE")&&(this.lightsUniforms=(e=>({u_lighting_ambient_color:new ki(e),u_lighting_directional_dir:new ki(e),u_lighting_directional_color:new ki(e),u_ground_radiance:new ki(e)}))(e)),r.includes("RENDER_SHADOWS")&&(this.shadowUniforms=(e=>({u_light_matrix_0:new ji(e),u_light_matrix_1:new ji(e),u_fade_range:new Ui(e),u_shadow_normal_offset:new ki(e),u_shadow_intensity:new Ni(e),u_shadow_texel_size:new Ni(e),u_shadow_map_resolution:new Ni(e),u_shadow_direction:new ki(e),u_shadow_bias:new ki(e),u_shadowmap_0:new Bi(e),u_shadowmap_1:new Bi(e)}))(e)))}getAttributeLocation(e,t){let i=this.attributes[t];return void 0===i&&(i=this.attributes[t]=e.getAttribLocation(this.program,t)),i}setTerrainUniformValues(e,t){if(!this.terrainUniforms)return;const i=this.terrainUniforms;if(!this.failedToCreate){e.program.set(this.program);for(const e in t)i[e]&&i[e].set(this.program,e,t[e])}}setGlobeUniformValues(e,t){if(!this.globeUniforms)return;const i=this.globeUniforms;if(!this.failedToCreate){e.program.set(this.program);for(const e in t)i[e]&&i[e].set(this.program,e,t[e])}}setFogUniformValues(e,t){if(!this.fogUniforms)return;const i=this.fogUniforms;if(!this.failedToCreate){e.program.set(this.program);for(const e in t)i[e].set(this.program,e,t[e])}}setCutoffUniformValues(e,t){if(!this.cutoffUniforms)return;const i=this.cutoffUniforms;if(!this.failedToCreate){e.program.set(this.program);for(const e in t)i[e].set(this.program,e,t[e])}}setLightsUniformValues(e,t){if(!this.lightsUniforms)return;const i=this.lightsUniforms;if(!this.failedToCreate){e.program.set(this.program);for(const e in t)i[e].set(this.program,e,t[e])}}setShadowUniformValues(e,t){if(this.failedToCreate||!this.shadowUniforms)return;const i=this.shadowUniforms;e.program.set(this.program);for(const e in t)i[e].set(this.program,e,t[e])}_drawDebugWireframe(e,t,i,o,s,r,n,a,l,c){const h=e.options.wireframe;if(!1===h.terrain&&!1===h.layers2D&&!1===h.layers3D)return;const d=e.context;if(!(()=>!(!h.terrain||"terrainRaster"!==this.name&&"globeRaster"!==this.name)||!(!h.layers2D||e._terrain&&e._terrain.renderingToTexture||!wu.includes(this.name))||!(!h.layers3D||!Tu.includes(this.name)))())return;const u=d.gl,_=e.wireframeDebugCache.getLinesFromTrianglesBuffer(e.frameCounter,s,d);if(!_)return;const p=[...this.fixedDefines,"DEBUG_WIREFRAME"],f=e.getOrCreateProgram(this.name,{config:this.configuration,defines:p});d.program.set(f.program);const m=(e,t,i)=>{if(t[e]&&i[e])for(const o in t[e])i[e][o]&&i[e][o].set(i.program,o,t[e][o].current)};l&&l.setUniforms(f.program,d,f.binderUniforms,n,{zoom:a}),m("fixedUniforms",this,f),m("terrainUniforms",this,f),m("globeUniforms",this,f),m("fogUniforms",this,f),m("lightsUniforms",this,f),m("shadowUniforms",this,f),_.bind(),d.setColorMode(new ch([u.ONE,u.ONE_MINUS_SRC_ALPHA,u.ZERO,u.ONE],Te.transparent,[!0,!0,!0,!1])),d.setDepthMode(new hh(t.func===u.LESS?u.LEQUAL:t.func,hh.ReadOnly,t.range)),d.setStencilMode(uh.disabled);const g=3*r.primitiveLength*2,v=3*r.primitiveOffset*2*2;if(this.forceManualRenderingForInstanceIDShaders){const e=c||1;for(let t=0;t<e;++t)f.instancingUniforms.u_instanceID.set(this.program,"u_instanceID",t),u.drawElements(u.LINES,g,u.UNSIGNED_SHORT,v)}else c&&c>1?u.drawElementsInstanced(u.LINES,g,u.UNSIGNED_SHORT,v,c):u.drawElements(u.LINES,g,u.UNSIGNED_SHORT,v);s.bind(),d.program.set(this.program),d.setDepthMode(t),d.setStencilMode(i),d.setColorMode(o)}checkUniforms(e,t,i){if(this.fixedDefines.includes(t))for(const o of Object.keys(i))if(!i[o].initialized)throw new Error(`Program '${this.name}', from draw '${e}': uniform ${o} not set but required by ${t} being defined`)}draw(e,t,i,o,s,r,n,a,l,c,h,d,u,_,p,f){const m=e.context,g=m.gl;if(this.failedToCreate)return;m.program.set(this.program),m.setDepthMode(i),m.setStencilMode(o),m.setColorMode(s),m.setCullFace(r);for(const[e,t]of this.fixedUniformsEntries)t.set(this.program,e,n[e]);_&&_.setUniforms(this.program,m,this.binderUniforms,d,{zoom:u});const v={[g.POINTS]:1,[g.LINES]:2,[g.TRIANGLES]:3,[g.LINE_STRIP]:1}[t];this.checkUniforms(a,"RENDER_SHADOWS",this.shadowUniforms);const y=p||[],x=_?_.getPaintVertexBuffers():[],b=t===g.TRIANGLES&&c,w=f&&f>0?1:void 0;for(const r of h.get()){const n=r.vaos||(r.vaos={});if((n[a]||(n[a]=new yd)).bind(m,this,l,x,c,r.vertexOffset,y,w),this.forceManualRenderingForInstanceIDShaders){const e=f||1;for(let i=0;i<e;++i)this.instancingUniforms.u_instanceID.set(this.program,"u_instanceID",i),c?g.drawElements(t,r.primitiveLength*v,g.UNSIGNED_SHORT,r.primitiveOffset*v*2):g.drawArrays(t,r.vertexOffset,r.vertexLength)}else f&&f>1?g.drawElementsInstanced(t,r.primitiveLength*v,g.UNSIGNED_SHORT,r.primitiveOffset*v*2,f):c?g.drawElements(t,r.primitiveLength*v,g.UNSIGNED_SHORT,r.primitiveOffset*v*2):g.drawArrays(t,r.vertexOffset,r.vertexLength);b&&this._drawDebugWireframe(e,i,o,s,c,r,d,u,_,f)}}}function Su(e,t,i=0){const o=Math.pow(2,t.tileID.overscaledZ),s=t.tileSize*Math.pow(2,e.transform.tileZoom)/o,r=s*(t.tileID.canonical.x+t.tileID.wrap*o),n=s*t.tileID.canonical.y;return{u_image:0,u_texsize:t.imageAtlasTexture?t.imageAtlasTexture.size:[0,0],u_tile_units_to_pixels:1/ze(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 Iu={terrain:0,flat:1},Cu=$t(),Ru=(e,t,i,o,s,r,n,a,l,c,h,d,u,_,p,f,m,g)=>{const v=t.style.light,y=v.properties.get("position"),x=[y.x,y.y,y.z],b=Is();"viewport"===v.properties.get("anchor")&&(Cs(b,-t.transform.angle),Rs(x,x,b));const w=v.properties.get("color").toPremultipliedRenderColor(null),T=t.transform,E={u_matrix:e,u_lightpos:x,u_lightintensity:v.properties.get("intensity"),u_lightcolor:[w.r,w.g,w.b],u_vertical_gradient:+i,u_opacity:o,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:Cu,u_merc_center:[0,0],u_up_dir:[0,0,0],u_height_lift:0,u_height_type:Iu[c],u_base_type:Iu[h],u_ao:s,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};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 oo(0,0,0),u[0]*we,u[1]*we),E.u_height_lift=l),E},Au=(e,t,i,o,s,r)=>({u_matrix:e,u_edge_radius:t,u_width_scale:i,u_vertical_scale:o,u_height_type:Iu[s],u_base_type:Iu[r]}),Du=(e,t,i,o,s,r,n,a,l,c,h,d,u,_,p,f,m,g)=>{const v=Ru(e,t,i,o,s,r,n,a,c,h,d,u,_,p,f,m,1,[0,0,0]),y={u_height_factor:-Math.pow(2,a.overscaledZ)/l.tileSize/8};return Object.assign(v,Su(t,l,g),y)},Lu=(e,t,i,o,s,r,n,a,l,c,h)=>({u_matrix:t,u_opacity:i,u_ao_pass:o?1:0,u_meter_to_tile:s,u_ao:r,u_flood_light_intensity:n,u_flood_light_color:a,u_attenuation:l,u_edge_radius:c,u_fb:0,u_fb_size:h,u_dynamic_offset:1}),Ou=(e,t,i)=>({u_matrix:e,u_emissive_strength:t,u_ground_shadow_factor:i}),Pu=(e,t,i,o,s,r=0)=>Object.assign(Ou(e,t,s),Su(i,o,r)),Mu=(e,t,i,o)=>({u_matrix:e,u_world:i,u_emissive_strength:t,u_ground_shadow_factor:o}),zu=(e,t,i,o,s,r,n=0)=>Object.assign(Pu(e,t,i,o,r,n),{u_world:s}),Fu=(e,t)=>({u_matrix:e,u_ground_shadow_factor:t}),Bu=(e,t,i,o,s)=>({u_matrix:e,u_camera_pos:[t[0],t[1],t[2]],u_depth_bias:i,u_height_scale:o,u_reset_depth:s}),ku=(e,t,i,o,s,r,n,a,l)=>({u_matrix:e,u_normal_matrix:t,u_opacity:i,u_faux_facade_ao_intensity:o,u_camera_pos:s,u_tile_to_meter:r,u_facade_emissive_chance:n,u_flood_light_color:a,u_flood_light_intensity:l}),Nu=e=>({u_matrix:e}),Uu=e=>({u_matrix:e}),ju=(e,t,i,o,s,r,n,a)=>{const l=we/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:o,u_tile_id:n,u_merc_center:s}},Gu=(e,t,i=1)=>({u_matrix:e,u_color:t,u_overlay:0,u_overlay_scale:i}),Vu=$t(),Hu=(e,t,i,o,s,r,n)=>{const a=e.transform,l="globe"===a.projection.name,c=l?As(a.zoom,t.canonical)*a._pixelsPerMercatorPixel:ze(i,1,r),h={u_matrix:t.projMatrix,u_extrude_scale:c,u_intensity:n,u_inv_rot_matrix:Vu,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=o,h.u_merc_center=s,h.u_tile_id=[t.canonical.x,t.canonical.y,1<<t.canonical.z],h.u_zoom_transition=ye(a.zoom);const e=s[0]*we,i=s[1]*we;h.u_up_dir=a.projection.upVector(new oo(0,0,0),e,i)}return h};function qu(e,[t,i,o,s],[r,n]){if(r===n)return[0,0,0,0];const a=255*(e-1)/(e*(n-r));return[t*a,i*a,o*a,s*a]}function Zu(e,t,[i,o]){return i===o?0:.5/e+(t-i)*(e-1)/(e*(o-i))}const Wu=(e,t,i,o,s,r,n,a,l,c,h,d,u,_,p,f,m,g,v,y,x)=>({u_matrix:e,u_normalize_matrix:t,u_globe_matrix:i,u_merc_matrix:o,u_grid_matrix:s,u_tl_parent:r,u_scale_parent:c,u_fade_t:h.mix,u_opacity:h.opacity*d.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:d.paint.get("raster-brightness-min"),u_brightness_high:d.paint.get("raster-brightness-max"),u_saturation_factor:Ls(d.paint.get("raster-saturation")),u_contrast_factor:Ds(d.paint.get("raster-contrast")),u_spin_weights:$u(d.paint.get("raster-hue-rotate")),u_perspective_transform:u,u_raster_elevation:_,u_zoom_transition:n,u_merc_center:a,u_cutoff_params:l,u_colorization_mix:qu(Os,f,g),u_colorization_offset:Zu(Os,m,g),u_color_ramp:p,u_texture_offset:[y/(v+2*y),v/(v+2*y)],u_texture_res:[v+2*y,v+2*y],u_emissive_strength:x});function $u(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 Xu=.05,Yu=(e,t,i,o,s,r,n,a,l,c,h,d)=>({u_matrix:e,u_normalize_matrix:t,u_globe_matrix:i,u_merc_matrix:o,u_grid_matrix:s,u_tl_parent:r,u_scale_parent:c,u_fade_t:h.mix,u_opacity:h.opacity,u_image0:0,u_image1:1,u_raster_elevation:d,u_zoom_transition:n,u_merc_center:a,u_cutoff_params:l}),Ku=(e,t,i,o,s,r,n,a,l,c)=>({u_particle_texture:e,u_particle_texture_side_len:t,u_tile_offset:i,u_velocity:o,u_color_ramp:r,u_velocity_res:s,u_max_speed:n,u_uv_offset:a,u_data_scale:[255*l[0],255*l[1]],u_data_offset:c,u_particle_pos_scale:1.1,u_particle_pos_offset:[Xu,Xu]}),Qu=(e,t,i,o,s,r,n,a,l,c)=>({u_particle_texture:e,u_particle_texture_side_len:t,u_velocity:i,u_velocity_res:o,u_max_speed:s,u_speed_factor:r,u_reset_rate:n,u_rand_seed:Math.random(),u_uv_offset:a,u_data_scale:[255*l[0],255*l[1]],u_data_offset:c,u_particle_pos_scale:1.1,u_particle_pos_offset:[Xu,Xu]}),Ju=$t(),e_=(e,t,i,o,s,r,n,a,l,c,h,d,u,_,p,f,m,g,v,y,x,b,T,E)=>{const S=s.transform,I={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(v),u_rotate_symbol:+i,u_aspect_ratio:S.width/S.height,u_fade_change:s.options.fadeDuration?s.symbolFadeChange:1,u_matrix:r,u_label_plane_matrix:n,u_coord_matrix:a,u_is_text:+c,u_elevation_from_sea:l?1:0,u_pitch_with_map:+o,u_texsize:h,u_texsize_icon:d,u_texture:0,u_texture_icon:1,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:Ju,u_merc_center:[0,0],u_camera_forward:[0,0,0],u_ecef_origin:[0,0,0],u_tile_matrix:Ju,u_up_vector:[0,-1,0],u_color_adj_mat:b,u_icon_transition:T||0,u_gamma_scale:o?s.transform.getCameraToCenterDistance(v)*Math.cos(s.terrain?0:s.transform._pitch):1,u_device_pixel_ratio:w.devicePixelRatio,u_is_halo:1,u_scale_factor:E||1,u_ground_shadow_factor:y,u_inv_matrix:Lt($t(),n),u_normal_scale:x,u_lutTexture:bh.LUT};return"globe"===v.name&&(I.u_tile_id=[_.canonical.x,_.canonical.y,1<<_.canonical.z],I.u_zoom_transition=p,I.u_inv_rot_matrix=m,I.u_merc_center=f,I.u_camera_forward=S._camera.forward(),I.u_ecef_origin=Ps(S.globeMatrix,_.toUnwrapped()),I.u_tile_matrix=Float32Array.from(S.globeMatrix),I.u_up_vector=g),I},t_=(e,t,i,o)=>({u_matrix:e,u_emissive_strength:t,u_opacity:i,u_color:o}),i_=(e,t,i,o,s,r,n,a,l)=>Object.assign(function(e,t,i,o,s,r){const{width:n,height:a}=o.imageManager.getPixelSize(t),l=Math.pow(2,r.tileID.overscaledZ),c=r.tileSize*Math.pow(2,o.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:s?[o.transform.width,-1*o.transform.height]:[1/ze(r,1,o.transform.tileZoom),1/ze(r,1,o.transform.tileZoom)],u_pixel_coord_upper:[h>>16,d>>16],u_pixel_coord_lower:[65535&h,65535&d]}}(0,r,n,o,a,l),{u_matrix:e,u_emissive_strength:t,u_opacity:i}),o_=new Float32Array(Zt([])),s_=(e,t,i,o,s,r,n,a,l,c,h,d,u,_=[0,0,0],p,f,m)=>{const g=s.style.light,v=g.properties.get("position"),y=[-v.x,-v.y,v.z],x=Is();"viewport"===g.properties.get("anchor")&&(Cs(x,-s.transform.angle),Rs(y,y,x));const b="MASK"===h.alphaMode,w=g.properties.get("color").toNonPremultipliedRenderColor(null),T=u.paint.get("model-ambient-occlusion-intensity"),E=u.paint.get("model-color").constantOr(Te.white).toNonPremultipliedRenderColor(null);return E.a=u.paint.get("model-color-mix-intensity").constantOr(0),m&&(E.r=m[0],E.g=m[1],E.b=m[2],E.a=m[3]),f&&(E.r=f.color.r,E.g=f.color.g,E.b=f.color.b,E.a=f.colorMix,d=f.emissionStrength,r*=f.opacity),{u_matrix:e,u_lighting_matrix:t,u_normal_matrix:i,u_node_matrix:o||o_,u_lightpos:y,u_lightintensity:g.properties.get("intensity"),u_lightcolor:[w.r,w.g,w.b],u_camera_pos:_,u_opacity:r,u_baseTextureIsAlpha:0,u_alphaMask:+b,u_alphaCutoff:h.alphaCutoff,u_baseColorFactor:n.toNonPremultipliedRenderColor(null).toArray01(),u_emissiveFactor:a.toNonPremultipliedRenderColor(null).toArray01(),u_metallicFactor:l,u_roughnessFactor:c,u_baseColorTexture:bh.BaseColor,u_metallicRoughnessTexture:bh.MetallicRoughness,u_normalTexture:bh.Normal,u_occlusionTexture:bh.Occlusion,u_emissionTexture:bh.Emission,u_lutTexture:bh.LUT,u_color_mix:E.toArray01(),u_aoIntensity:T,u_emissive_strength:d,u_occlusionTextureTransform:p||[0,0,0,0]}},r_=(e,t=o_,i=o_)=>({u_matrix:e,u_instance:t,u_node_matrix:i}),n_={fillExtrusion:e=>({u_matrix:new ji(e),u_lightpos:new ki(e),u_lightintensity:new Ni(e),u_lightcolor:new ki(e),u_vertical_gradient:new Ni(e),u_opacity:new Ni(e),u_edge_radius:new Ni(e),u_width_scale:new Ni(e),u_ao:new Ui(e),u_height_type:new Bi(e),u_base_type:new Bi(e),u_tile_id:new ki(e),u_zoom_transition:new Ni(e),u_inv_rot_matrix:new ji(e),u_merc_center:new Ui(e),u_up_dir:new ki(e),u_height_lift:new Ni(e),u_flood_light_color:new ki(e),u_vertical_scale:new Ni(e),u_flood_light_intensity:new Ni(e),u_ground_shadow_factor:new ki(e)}),fillExtrusionDepth:e=>({u_matrix:new ji(e),u_edge_radius:new Ni(e),u_width_scale:new Ni(e),u_vertical_scale:new Ni(e),u_height_type:new Bi(e),u_base_type:new Bi(e)}),fillExtrusionPattern:e=>({u_matrix:new ji(e),u_lightpos:new ki(e),u_lightintensity:new Ni(e),u_lightcolor:new ki(e),u_vertical_gradient:new Ni(e),u_height_factor:new Ni(e),u_edge_radius:new Ni(e),u_width_scale:new Ni(e),u_ao:new Ui(e),u_height_type:new Bi(e),u_base_type:new Bi(e),u_tile_id:new ki(e),u_zoom_transition:new Ni(e),u_inv_rot_matrix:new ji(e),u_merc_center:new Ui(e),u_up_dir:new ki(e),u_height_lift:new Ni(e),u_image:new Bi(e),u_texsize:new Ui(e),u_pixel_coord_upper:new Ui(e),u_pixel_coord_lower:new Ui(e),u_tile_units_to_pixels:new Ni(e),u_opacity:new Ni(e),u_pattern_transition:new Ni(e)}),fillExtrusionGroundEffect:e=>({u_matrix:new ji(e),u_opacity:new Ni(e),u_ao_pass:new Ni(e),u_meter_to_tile:new Ni(e),u_ao:new Ui(e),u_flood_light_intensity:new Ni(e),u_flood_light_color:new ki(e),u_attenuation:new Ni(e),u_edge_radius:new Ni(e),u_fb:new Bi(e),u_fb_size:new Ni(e),u_dynamic_offset:new Ni(e)}),fill:e=>({u_matrix:new ji(e),u_emissive_strength:new Ni(e),u_ground_shadow_factor:new ki(e)}),fillPattern:e=>({u_matrix:new ji(e),u_emissive_strength:new Ni(e),u_image:new Bi(e),u_texsize:new Ui(e),u_pixel_coord_upper:new Ui(e),u_pixel_coord_lower:new Ui(e),u_tile_units_to_pixels:new Ni(e),u_ground_shadow_factor:new ki(e),u_pattern_transition:new Ni(e)}),fillOutline:e=>({u_matrix:new ji(e),u_emissive_strength:new Ni(e),u_world:new Ui(e),u_ground_shadow_factor:new ki(e)}),fillOutlinePattern:e=>({u_matrix:new ji(e),u_emissive_strength:new Ni(e),u_world:new Ui(e),u_image:new Bi(e),u_texsize:new Ui(e),u_pixel_coord_upper:new Ui(e),u_pixel_coord_lower:new Ui(e),u_tile_units_to_pixels:new Ni(e),u_ground_shadow_factor:new ki(e),u_pattern_transition:new Ni(e)}),building:e=>({u_matrix:new ji(e),u_normal_matrix:new ji(e),u_opacity:new Ni(e),u_faux_facade_ao_intensity:new Ni(e),u_camera_pos:new ki(e),u_tile_to_meter:new Ni(e),u_facade_emissive_chance:new Ni(e),u_flood_light_color:new ki(e),u_flood_light_intensity:new Ni(e)}),buildingBloom:e=>({u_matrix:new ji(e)}),buildingDepth:e=>({u_matrix:new ji(e)}),elevatedStructuresDepth:e=>({u_matrix:new ji(e),u_depth_bias:new Ni(e)}),elevatedStructures:e=>({u_matrix:new ji(e),u_ground_shadow_factor:new ki(e)}),elevatedStructuresDepthReconstruct:e=>({u_matrix:new ji(e),u_camera_pos:new ki(e),u_depth_bias:new Ni(e),u_height_scale:new Ni(e),u_reset_depth:new Ni(e)}),circle:Fs,collisionBox:e=>({u_matrix:new ji(e),u_inv_rot_matrix:new ji(e),u_camera_to_center_distance:new Ni(e),u_extrude_scale:new Ui(e),u_zoom_transition:new Ni(e),u_merc_center:new Ui(e),u_tile_id:new ki(e)}),collisionCircle:e=>({u_matrix:new ji(e),u_inv_matrix:new ji(e),u_camera_to_center_distance:new Ni(e),u_viewport_size:new Ui(e)}),debug:e=>({u_color:new _s(e),u_matrix:new ji(e),u_overlay:new Bi(e),u_overlay_scale:new Ni(e)}),clippingMask:e=>({u_matrix:new ji(e)}),heatmap:e=>({u_extrude_scale:new Ni(e),u_intensity:new Ni(e),u_matrix:new ji(e),u_inv_rot_matrix:new ji(e),u_merc_center:new Ui(e),u_tile_id:new ki(e),u_zoom_transition:new Ni(e),u_up_dir:new ki(e)}),heatmapTexture:e=>({u_image:new Bi(e),u_color_ramp:new Bi(e),u_opacity:new Ni(e)}),hillshade:e=>({u_matrix:new ji(e),u_image:new Bi(e),u_latrange:new Ui(e),u_light:new Ui(e),u_shadow:new _s(e),u_highlight:new _s(e),u_emissive_strength:new Ni(e),u_accent:new _s(e)}),hillshadePrepare:e=>({u_matrix:new ji(e),u_image:new Bi(e),u_dimension:new Ui(e),u_zoom:new Ni(e)}),line:zs,linePattern:Ms,raster:e=>({u_matrix:new ji(e),u_normalize_matrix:new ji(e),u_globe_matrix:new ji(e),u_merc_matrix:new ji(e),u_grid_matrix:new ps(e),u_tl_parent:new Ui(e),u_scale_parent:new Ni(e),u_fade_t:new Ni(e),u_opacity:new Ni(e),u_image0:new Bi(e),u_image1:new Bi(e),u_brightness_low:new Ni(e),u_brightness_high:new Ni(e),u_saturation_factor:new Ni(e),u_contrast_factor:new Ni(e),u_spin_weights:new ki(e),u_perspective_transform:new Ui(e),u_raster_elevation:new Ni(e),u_zoom_transition:new Ni(e),u_merc_center:new Ui(e),u_cutoff_params:new Mo(e),u_colorization_mix:new Mo(e),u_colorization_offset:new Ni(e),u_color_ramp:new Bi(e),u_texture_offset:new Ui(e),u_texture_res:new Ui(e),u_emissive_strength:new Ni(e)}),rasterParticle:e=>({u_matrix:new ji(e),u_normalize_matrix:new ji(e),u_globe_matrix:new ji(e),u_merc_matrix:new ji(e),u_grid_matrix:new ps(e),u_tl_parent:new Ui(e),u_scale_parent:new Ni(e),u_fade_t:new Ni(e),u_opacity:new Ni(e),u_image0:new Bi(e),u_image1:new Bi(e),u_raster_elevation:new Ni(e),u_zoom_transition:new Ni(e),u_merc_center:new Ui(e),u_cutoff_params:new Mo(e)}),rasterParticleTexture:e=>({u_texture:new Bi(e),u_opacity:new Ni(e)}),rasterParticleDraw:e=>({u_particle_texture:new Bi(e),u_particle_texture_side_len:new Ni(e),u_tile_offset:new Ui(e),u_velocity:new Bi(e),u_color_ramp:new Bi(e),u_velocity_res:new Ui(e),u_max_speed:new Ni(e),u_uv_offset:new Ui(e),u_data_scale:new Ui(e),u_data_offset:new Ni(e),u_particle_pos_scale:new Ni(e),u_particle_pos_offset:new Ui(e)}),rasterParticleUpdate:e=>({u_particle_texture:new Bi(e),u_particle_texture_side_len:new Ni(e),u_velocity:new Bi(e),u_velocity_res:new Ui(e),u_max_speed:new Ni(e),u_speed_factor:new Ni(e),u_reset_rate:new Ni(e),u_rand_seed:new Ni(e),u_uv_offset:new Ui(e),u_data_scale:new Ui(e),u_data_offset:new Ni(e),u_particle_pos_scale:new Ni(e),u_particle_pos_offset:new Ui(e)}),symbol:e=>({u_is_size_zoom_constant:new Bi(e),u_is_size_feature_constant:new Bi(e),u_size_t:new Ni(e),u_size:new Ni(e),u_camera_to_center_distance:new Ni(e),u_rotate_symbol:new Bi(e),u_aspect_ratio:new Ni(e),u_fade_change:new Ni(e),u_matrix:new ji(e),u_label_plane_matrix:new ji(e),u_coord_matrix:new ji(e),u_is_text:new Bi(e),u_elevation_from_sea:new Bi(e),u_pitch_with_map:new Bi(e),u_texsize:new Ui(e),u_texsize_icon:new Ui(e),u_texture:new Bi(e),u_texture_icon:new Bi(e),u_gamma_scale:new Ni(e),u_device_pixel_ratio:new Ni(e),u_tile_id:new ki(e),u_zoom_transition:new Ni(e),u_inv_rot_matrix:new ji(e),u_merc_center:new Ui(e),u_camera_forward:new ki(e),u_tile_matrix:new ji(e),u_up_vector:new ki(e),u_ecef_origin:new ki(e),u_is_halo:new Bi(e),u_icon_transition:new Ni(e),u_color_adj_mat:new ji(e),u_scale_factor:new Ni(e),u_ground_shadow_factor:new ki(e),u_inv_matrix:new ji(e),u_normal_scale:new Ni(e),u_lutTexture:new Bi(e)}),background:e=>({u_matrix:new ji(e),u_emissive_strength:new Ni(e),u_opacity:new Ni(e),u_color:new _s(e)}),backgroundPattern:e=>({u_matrix:new ji(e),u_emissive_strength:new Ni(e),u_opacity:new Ni(e),u_image:new Bi(e),u_pattern_tl:new Ui(e),u_pattern_br:new Ui(e),u_texsize:new Ui(e),u_pattern_size:new Ui(e),u_pixel_coord_upper:new Ui(e),u_pixel_coord_lower:new Ui(e),u_pattern_units_to_pixels:new Ui(e)}),terrainRaster:e=>({u_matrix:new ji(e),u_image0:new Bi(e),u_image1:new Bi(e),u_skirt_height:new Ni(e),u_ground_shadow_factor:new ki(e),u_emissive_texture_available:new Ni(e)}),skybox:e=>({u_matrix:new ji(e),u_sun_direction:new ki(e),u_cubemap:new Bi(e),u_opacity:new Ni(e),u_temporal_offset:new Ni(e)}),skyboxGradient:e=>({u_matrix:new ji(e),u_color_ramp:new Bi(e),u_center_direction:new ki(e),u_radius:new Ni(e),u_opacity:new Ni(e),u_temporal_offset:new Ni(e)}),skyboxCapture:e=>({u_matrix_3f:new ps(e),u_sun_direction:new ki(e),u_sun_intensity:new Ni(e),u_color_tint_r:new Mo(e),u_color_tint_m:new Mo(e),u_luminance:new Ni(e)}),globeRaster:e=>({u_proj_matrix:new ji(e),u_globe_matrix:new ji(e),u_normalize_matrix:new ji(e),u_merc_matrix:new ji(e),u_zoom_transition:new Ni(e),u_merc_center:new Ui(e),u_image0:new Bi(e),u_image1:new Bi(e),u_grid_matrix:new ps(e),u_skirt_height:new Ni(e),u_far_z_cutoff:new Ni(e),u_frustum_tl:new ki(e),u_frustum_tr:new ki(e),u_frustum_br:new ki(e),u_frustum_bl:new ki(e),u_globe_pos:new ki(e),u_globe_radius:new Ni(e),u_viewport:new Ui(e),u_emissive_texture_available:new Ni(e)}),globeAtmosphere:e=>({u_frustum_tl:new ki(e),u_frustum_tr:new ki(e),u_frustum_br:new ki(e),u_frustum_bl:new ki(e),u_horizon:new Ni(e),u_transition:new Ni(e),u_fadeout_range:new Ni(e),u_atmosphere_fog_color:new Mo(e),u_high_color:new Mo(e),u_space_color:new Mo(e),u_temporal_offset:new Ni(e),u_horizon_angle:new Ni(e)}),model:e=>({u_matrix:new ji(e),u_lighting_matrix:new ji(e),u_normal_matrix:new ji(e),u_node_matrix:new ji(e),u_lightpos:new ki(e),u_lightintensity:new Ni(e),u_lightcolor:new ki(e),u_camera_pos:new ki(e),u_opacity:new Ni(e),u_baseColorFactor:new Mo(e),u_emissiveFactor:new Mo(e),u_metallicFactor:new Ni(e),u_roughnessFactor:new Ni(e),u_baseTextureIsAlpha:new Bi(e),u_alphaMask:new Bi(e),u_alphaCutoff:new Ni(e),u_baseColorTexture:new Bi(e),u_metallicRoughnessTexture:new Bi(e),u_normalTexture:new Bi(e),u_occlusionTexture:new Bi(e),u_emissionTexture:new Bi(e),u_lutTexture:new Bi(e),u_color_mix:new Mo(e),u_aoIntensity:new Ni(e),u_emissive_strength:new Ni(e),u_occlusionTextureTransform:new Mo(e)}),modelDepth:e=>({u_matrix:new ji(e),u_instance:new ji(e),u_node_matrix:new ji(e)}),groundShadow:e=>({u_matrix:new ji(e),u_ground_shadow_factor:new ki(e)}),stars:e=>({u_matrix:new ji(e),u_up:new ki(e),u_right:new ki(e),u_intensity_multiplier:new Ni(e)}),snowParticle:e=>({u_modelview:new ji(e),u_projection:new ji(e),u_time:new Ni(e),u_cam_pos:new ki(e),u_velocityConeAperture:new Ni(e),u_velocity:new Ni(e),u_horizontalOscillationRadius:new Ni(e),u_horizontalOscillationRate:new Ni(e),u_boxSize:new Ni(e),u_billboardSize:new Ni(e),u_simpleShapeParameters:new Ui(e),u_screenSize:new Ui(e),u_thinningCenterPos:new Ui(e),u_thinningShape:new ki(e),u_thinningAffectedRatio:new Ni(e),u_thinningParticleOffset:new Ni(e),u_particleColor:new Mo(e),u_direction:new ki(e)}),rainParticle:e=>({u_modelview:new ji(e),u_projection:new ji(e),u_time:new Ni(e),u_cam_pos:new ki(e),u_texScreen:new Bi(e),u_velocityConeAperture:new Ni(e),u_velocity:new Ni(e),u_boxSize:new Ni(e),u_rainDropletSize:new Ui(e),u_distortionStrength:new Ni(e),u_rainDirection:new ki(e),u_color:new Mo(e),u_screenSize:new Ui(e),u_thinningCenterPos:new Ui(e),u_thinningShape:new ki(e),u_thinningAffectedRatio:new Ni(e),u_thinningParticleOffset:new Ni(e),u_shapeDirectionalPower:new Ni(e),u_shapeNormalPower:new Ni(e),u_mode:new Ni(e)}),vignette:e=>({u_vignetteShape:new ki(e),u_vignetteColor:new Mo(e)}),occlusion:e=>({u_matrix:new ji(e),u_anchorPos:new ki(e),u_screenSizePx:new Ui(e),u_occluderSizePx:new Ui(e),u_color:new Mo(e)})};class a_{constructor(e,t,i,o){this.id=a_.uniqueIdxCounter,a_.uniqueIdxCounter++,this.context=e;const s=e.gl;this.buffer=s.createBuffer(),this.dynamicDraw=Boolean(i),this.context.unbindVAO(),e.bindElementBuffer.set(this.buffer),s.bufferData(s.ELEMENT_ARRAY_BUFFER,t.arrayBuffer,this.dynamicDraw?s.DYNAMIC_DRAW:s.STATIC_DRAW),this.dynamicDraw||o||t.destroy()}bind(){this.context.bindElementBuffer.set(this.buffer)}updateData(e){this.id=a_.uniqueIdxCounter,a_.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)}}a_.uniqueIdxCounter=0;const l_={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class c_{constructor(e,t,i,o,s,r){this.length=t.length,this.attributes=i,this.itemSize=t.bytesPerElement,this.dynamicDraw=o,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||s||t.destroy()}bind(){this.context.bindVertexBuffer.set(this.buffer)}updateData(e){const t=this.context.gl;this.bind(),t.bufferSubData(t.ARRAY_BUFFER,0,e.arrayBuffer)}enableAttributes(e,t){for(let i=0;i<this.attributes.length;i++){const o=t.getAttributeLocation(e,this.attributes[i].name);-1!==o&&e.enableVertexAttribArray(o)}}setVertexAttribPointers(e,t,i){for(let o=0;o<this.attributes.length;o++){const s=this.attributes[o],r=t.getAttributeLocation(e,s.name);-1!==r&&e.vertexAttribPointer(r,s.components,e[l_[s.type]],!1,this.itemSize,s.offset+this.itemSize*(i||0))}}setVertexAttribDivisor(e,t,i){for(let o=0;o<this.attributes.length;o++){const s=t.getAttributeLocation(e,this.attributes[o].name);-1!==s&&this.instanceCount&&this.instanceCount>0&&e.vertexAttribDivisor(s,i)}}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}class h_{constructor(e,t,i,o,s){this.context=e,this.width=t,this.height=i;const r=this.framebuffer=e.gl.createFramebuffer();o>0&&(this.colorAttachment0=new ou(e,r,0)),o>1&&(this.colorAttachment1=new ou(e,r,1)),s&&(this.depthAttachmentType=s,this.depthAttachment="renderbuffer"===s?new su(e,r):new ru(e,r))}createColorAttachment(e,t){0===t?this.colorAttachment0=new ou(e,this.framebuffer,0):1===t&&(this.colorAttachment1=new ou(e,this.framebuffer,1))}removeColorAttachment(e,t){const i=this.context.gl;let o;0===t?(o=this.colorAttachment0.get(),this.colorAttachment0=void 0):1===t&&(o=this.colorAttachment1.get(),this.colorAttachment1=void 0),o&&i.deleteTexture(o)}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)}e.deleteFramebuffer(this.framebuffer)}}class d_{constructor(e,t){this.gl=e,this.clearColor=new Sd(this),this.clearDepth=new Id(this),this.clearStencil=new Cd(this),this.colorMask=new Rd(this),this.depthMask=new Ad(this),this.stencilMask=new Dd(this),this.stencilFunc=new Ld(this),this.stencilOp=new Od(this),this.stencilTest=new Pd(this),this.depthRange=new Md(this),this.depthTest=new zd(this),this.depthFunc=new Fd(this),this.blend=new Bd(this),this.blendFunc=new kd(this),this.blendColor=new Nd(this),this.blendEquation=new Ud(this),this.cullFace=new jd(this),this.cullFaceSide=new Gd(this),this.frontFace=new Vd(this),this.program=new Hd(this),this.activeTexture=new qd(this),this.viewport=new Zd(this),this.bindFramebuffer=new Wd(this),this.bindRenderbuffer=new $d(this),this.bindTexture=new Xd(this),this.bindVertexBuffer=new Yd(this),this.bindElementBuffer=new Kd(this),this.bindVertexArrayOES=new Qd(this),this.pixelStoreUnpack=new Jd(this),this.pixelStoreUnpackPremultiplyAlpha=new eu(this),this.pixelStoreUnpackFlipY=new tu(this),this.options=t?Object.assign({},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&&-1!==this.renderer.indexOf("PowerVR"),this.options.extTextureFloatLinearForceOff||(this.extTextureFloatLinear=e.getExtension("OES_texture_float_linear")),this.extRenderToTextureHalfFloat=e.getExtension("EXT_color_buffer_half_float"),this.extTimerQuery=e.getExtension("EXT_disjoint_timer_query_webgl2"),this.maxTextureSize=e.getParameter(e.MAX_TEXTURE_SIZE),this.extBlendFuncExtended=e.getExtension("WEBGL_blend_func_extended")}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 a_(this,e,t,i)}createVertexBuffer(e,t,i,o,s){return new c_(this,e,t,i,o,s)}createRenderbuffer(e,t,i){const o=this.gl,s=o.createRenderbuffer();return this.bindRenderbuffer.set(s),o.renderbufferStorage(o.RENDERBUFFER,e,t,i),this.bindRenderbuffer.set(null),s}createFramebuffer(e,t,i,o){return new h_(this,e,t,i,o)}clear({color:e,depth:t,stencil:i,colorMask:o}){const s=this.gl;let r=0;e&&(r|=s.COLOR_BUFFER_BIT,this.clearColor.set(e.toNonPremultipliedRenderColor(null)),this.colorMask.set(o||[!0,!0,!0,!0])),void 0!==t&&(r|=s.DEPTH_BUFFER_BIT,this.depthRange.set([0,1]),this.clearDepth.set(t),this.depthMask.set(!0)),void 0!==i&&(r|=s.STENCIL_BUFFER_BIT,this.clearStencil.set(i),this.stencilMask.set(255)),s.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){Ht(e.blendFunction,ch.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)}}let u_;function __(e,t,i,o,s,r,n){const a=e.context,l=a.gl,c=e.transform,h=[Ge(c.center.lng),qe(c.center.lat)],d=i.layout.get("symbol-placement"),u=i.layout.get("text-variable-anchor"),_="map"===i.layout.get("icon-rotation-alignment"),p="map"===i.layout.get("text-rotation-alignment"),f="point"!==d,m=[];let g=0,v=0;for(let a=0;a<o.length;a++){const d=o[a],y=t.getTile(d),x=y.getBucket(i);if(!x)continue;const b=x.getProjection().createInversionMatrix(c,d.canonical),w=[],T=_c(d,x,c),E=!n&&_&&f,S=n&&p&&f,I=u&&x.hasTextData(),C=x.hasIconTextFit()&&I&&x.hasIconData(),R=E||S||n&&I||C,A="globe"===x.projection.name,D=A?ye(c.zoom):0;A&&(w.push("PROJECTION_GLOBE_VIEW"),R&&w.push("PROJECTED_POS_ON_VIEWPORT"));const L=e.getOrCreateProgram("collisionBox",{defines:w});let O=T;0===s[0]&&0===s[1]||(O=e.translatePosMatrix(T,y,s,r));const P=n?x.textCollisionBox:x.iconCollisionBox,M=x.collisionCircleArray;if(M.length>0){const e=$t(),t=O;fo(e,x.placementInvProjMatrix,c.glCoordMatrix),fo(e,e,x.placementViewportMatrix),m.push({circleArray:M,circleOffset:v,transform:t,invTransform:e,projection:x.getProjection()}),g+=M.length/4,v=g}if(!P)continue;e.terrain&&e.terrain.setupElevationDraw(y,L);const z=A?[d.canonical.x,d.canonical.y,1<<d.canonical.z]:[0,0,0];L.draw(e,l.LINES,hh.disabled,uh.disabled,e.colorModeForRenderPass(),fh.disabled,ju(O,b,c,D,h,y,z,x.getProjection()),i.id,P.layoutVertexBuffer,P.indexBuffer,P.segments,null,c.zoom,null,[P.collisionVertexBuffer,P.collisionVertexBufferExt])}if(!n||!m.length)return;const y=e.getOrCreateProgram("collisionCircle"),x=new Bs;x.resize(4*g),x._trim();let b=0;for(const e of m)for(let t=0;t<e.circleArray.length/4;t++){const i=4*t,o=e.circleArray[i+0],s=e.circleArray[i+1],r=e.circleArray[i+2],n=e.circleArray[i+3];x.emplace(b++,o,s,r,n,0),x.emplace(b++,o,s,r,n,1),x.emplace(b++,o,s,r,n,2),x.emplace(b++,o,s,r,n,3)}(!u_||u_.length<2*g)&&(u_=function(e){const t=2*e,i=new ht;i.resize(t),i._trim();for(let e=0;e<t;e++){const t=6*e;i.uint16[t+0]=4*e+0,i.uint16[t+1]=4*e+1,i.uint16[t+2]=4*e+2,i.uint16[t+3]=4*e+2,i.uint16[t+4]=4*e+3,i.uint16[t+5]=4*e+0}return i}(g));const w=a.createIndexBuffer(u_,!0),T=a.createVertexBuffer(x,ks.members,!0);for(const t of m){const o={u_matrix:t.transform,u_inv_matrix:t.invTransform,u_camera_to_center_distance:(E=c).getCameraToCenterDistance(t.projection),u_viewport_size:[E.width,E.height]};y.draw(e,l.TRIANGLES,hh.disabled,uh.disabled,e.colorModeForRenderPass(),fh.disabled,o,i.id,T,w,It.simpleSegment(0,2*t.circleOffset,t.circleArray.length,t.circleArray.length/2),null,c.zoom)}var E;T.destroy(),w.destroy()}const p_=$t();function f_(e){const t=e._camera.getWorldToCamera(e.worldSize,1),i=Be([],t,e.globeMatrix);Lt(i,i);const o=[0,0,0],s=[0,1,0,0];return ke(s,s,i),o[0]=s[0],o[1]=s[1],o[2]=s[2],Oe(o,o),o}function m_({width:e,height:t,anchor:i,textOffset:o,textScale:s},n){const{horizontalAlign:a,verticalAlign:l}=bi(i),c=-(a-.5)*e,h=-(l-.5)*t,d=wi(i,o);return new r((c/s+d[0])*n,(h/s+d[1])*n)}function g_(e,t,i,o,s,n,a,l,c,h){const d=e.text.placedSymbolArray,u=e.text.dynamicLayoutVertexArray,_=e.icon.dynamicLayoutVertexArray,p={},f=e.getProjection(),m=pc(a,f,s),g=s.elevation,v=f.upVectorScale(a.canonical,s.center.lat,s.worldSize).metersToTile;u.clear();for(let _=0;_<d.length;_++){const y=d.get(_),{tileAnchorX:x,tileAnchorY:b,numGlyphs:w}=y,T=y.hidden||!y.crossTileID||e.allowVerticalPlacement&&!y.placedOrientation?null:o[y.crossTileID];if(T){let o=0,d=0,E=0;const S="road"===e.elevationType;if(g||S){const t=S?e.getElevationFeatureForText(_):null,i=_i.getAtTileOffset(a,new r(x,b),g,t),[s,n,l]=f.upVector(a.canonical,x,b);o=i*s*v,d=i*n*v,E=i*l*v}let[I,C,R,A]=wc(y.projectedAnchorX+o,y.projectedAnchorY+d,y.projectedAnchorZ+E,i?m:n);const D=Tc(s.getCameraToCenterDistance(f),A);let L=ri(e.textSizeData,c,y)*D/mi;i&&(L*=e.tilePixelRatio/l);const O=m_(T,L);i?(({x:I,y:C,z:R}=f.projectTilePoint(x+O.x,b+O.y,a.canonical)),[I,C,R]=wc(I+o,C+d,R+E,n)):(t&&O._rotate(-s.angle),I+=O.x,C+=O.y,R=0);const P=e.allowVerticalPlacement&&y.placedOrientation===ii.vertical?Math.PI/2:0;for(let e=0;e<w;e++)si(u,I,C,R,P);h&&y.associatedIconIndex>=0&&(p[y.associatedIconIndex]={x:I,y:C,z:R,angle:P})}else Oc(w,u)}if(h){_.clear();const t=e.icon.placedSymbolArray;for(let e=0;e<t.length;e++){const i=t.get(e),{numGlyphs:o}=i,s=p[e];if(i.hidden||!s)Oc(o,_);else{const{x:e,y:t,z:i,angle:r}=s;for(let s=0;s<o;s++)si(_,e,t,i,r)}}e.icon.dynamicLayoutVertexBuffer.updateData(_)}e.text.dynamicLayoutVertexBuffer.updateData(u)}function v_(e,t,i,o,s,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,S=e.transform,I="map"===d,C="map"===u,R="map"===_,A="map"===p,D=void 0!==i.layout.get("symbol-sort-key").constantOr(1);let L=!1;const O=e.depthModeForSublayer(0,hh.ReadOnly),P=new hh(e.context.gl.LEQUAL,hh.ReadOnly,e.depthRangeFor3D),M=[Ge(S.center.lng),qe(S.center.lat)],z=i.layout.get("text-variable-anchor"),F="globe"===S.projection.name,B=[],k=[0,-1,0];for(const s of o){const o=t.getTile(s),r=o.getBucket(i);if(!r)continue;if("mercator"===r.projection.name&&F)continue;if(r.fullyClipped)continue;const d="globe"===r.projection.name,u=d?ye(S.zoom):0,_=pc(s,r.getProjection(),S),p=S.calculatePixelsToTileUnitsMatrix(o),N=z&&r.hasTextData(),U=r.hasIconTextFit()&&N&&r.hasIconData(),j=r.getProjection().createInversionMatrix(S,s.canonical),G=(1<<o.tileID.canonical.z)*we/e.transform.worldSize,V=t=>{let i=[0,0,0];if(t){const t=e.style.directionalLight,o=e.style.ambientLight;t&&o&&(i=Oh(e.style,t,o))}return i},H=t=>{S.depthOcclusionForSymbolsAndCircles&&(i.hasOcclusionOpacityProperties||e.terrain)&&(t.push("DEPTH_D24"),t.push("DEPTH_OCCLUSION"))},q=t=>{i.lut&&!w&&(i.lut.texture||(i.lut.texture=new Ns(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+bh.LUT),i.lut.texture&&i.lut.texture.bind(T.gl.LINEAR,T.gl.CLAMP_TO_EDGE),t.push("APPLY_LUT_ON_GPU"))},Z=()=>{const t=I&&"point"!==i.layout.get("symbol-placement"),n=[];H(n),q(n);const l=t||U,h="road"===r.elevationType,m=e.shadowRenderer,w=h&&R&&!!m&&m.enabled,T=V(w),C=h&&R&&!e.terrain?P:O,A=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")),A>0&&r.hasAnySecondaryIcon&&n.push("ICON_TRANSITION"),!r.icon.zOffsetVertexBuffer||h&&e.terrain||n.push("Z_OFFSET"),0===g&&0===v&&0===y&&1===x||n.push("COLOR_ADJUSTMENT"),r.sdfIcons&&n.push("RENDER_SDF"),w&&n.push("RENDER_SHADOWS","DEPTH_TEXTURE","NORMAL_OFFSET"),h&&R&&!e.terrain&&r.icon.orientationVertexBuffer&&n.push("ELEVATED_ROADS");const D=r.icon.programConfigurations.get(i.id),L=e.getOrCreateProgram("symbol",{config:D,defines:n}),z=o.imageAtlasTexture?o.imageAtlasTexture.size:[0,0],B=r.iconSizeData,N=ti(B,S.zoom),Z=R||!S.isOrthographic,W=yc(_,o.tileID.canonical,R,I,S,r.getProjection(),p),$=bc(_,o.tileID.canonical,R,I,S,r.getProjection(),p),X=e.translatePosMatrix($,o,a,c,!0),Y=e.translatePosMatrix(_,o,a,c),K=l?p_:W,Q=I&&!R&&!t;let J=k;!F&&!S.mercatorFromTransition||I||(J=f_(S));const ee=d?J:k,te=i.getColorAdjustmentMatrix(g,v,y,x),ie=e_(B.kind,N,Q,R,e,Y,K,X,b,!1,z,[0,0],0,s,u,M,j,ee,r.getProjection(),T,G,te,A,null),oe=o.imageAtlasTexture?o.imageAtlasTexture:null,se=1!==i.layout.get("icon-size").constantOr(0)||r.iconsNeedLinear,re=r.sdfIcons||e.options.rotating||e.options.zooming||se||Z?E.LINEAR:E.NEAREST,ne=r.sdfIcons&&0!==i.paint.get("icon-halo-width").constantOr(1),ae=e.terrain&&R&&t?Lt($t(),W):p_;if(t&&r.icon){const t=_i.getAtTileOffsetFunc(s,S.center.lat,S.worldSize,r.getProjection()),n=xc(_,o.tileID.canonical,R,I,S,r.getProjection(),p),a=i.layout.get("icon-size-scale-range"),l=Fe(e.scaleFactor,a[0],a[1]);Sc(r,_,e,!1,n,$,R,f,t,s,l)}return{program:L,buffers:r.icon,uniformValues:ie,atlasTexture:oe,atlasTextureIcon:null,atlasInterpolation:re,atlasInterpolationIcon:null,isSDF:r.sdfIcons,hasHalo:ne,depthMode:C,tile:o,renderWithShadows:w,labelPlaneMatrixInv:ae}},W=()=>{const t=C&&"point"!==i.layout.get("symbol-placement"),n=[],a=t||z||U,c="road"===r.elevationType,f=e.shadowRenderer,g=c&&A&&!!f&&f.enabled,v=V(g),y=c&&A&&!e.terrain?P:O;e.terrainRenderModeElevated()&&A&&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"),r.iconsInText&&n.push("RENDER_TEXT_AND_SYMBOL"),n.push("RENDER_SDF"),g&&n.push("RENDER_SHADOWS","DEPTH_TEXTURE","NORMAL_OFFSET"),c&&A&&!e.terrain&&r.text.orientationVertexBuffer&&n.push("ELEVATED_ROADS"),H(n);const x=r.text.programConfigurations.get(i.id),w=e.getOrCreateProgram("symbol",{config:x,defines:n});let T,I=[0,0],R=null;const D=r.textSizeData;r.iconsInText&&(I=o.imageAtlasTexture?o.imageAtlasTexture.size:[0,0],R=o.imageAtlasTexture?o.imageAtlasTexture:null,T=A||!S.isOrthographic||e.options.rotating||e.options.zooming||"composite"===D.kind||"camera"===D.kind?E.LINEAR:E.NEAREST);const L=o.glyphAtlasTexture?o.glyphAtlasTexture.size:[0,0],B=i.layout.get("text-size-scale-range"),N=Fe(e.scaleFactor,B[0],B[1]),q=ti(D,S.zoom,N),Z=yc(_,o.tileID.canonical,A,C,S,r.getProjection(),p),W=bc(_,o.tileID.canonical,A,C,S,r.getProjection(),p),$=e.translatePosMatrix(W,o,l,h,!0),X=e.translatePosMatrix(_,o,l,h),Y=a?p_:Z,K=C&&!A&&!t;let Q=k;!F&&!S.mercatorFromTransition||C||(Q=f_(S));const J=e_(D.kind,q,K,A,e,X,Y,$,b,!0,L,I,0,s,u,M,j,d?Q:k,r.getProjection(),v,G,null,null,N),ee=o.glyphAtlasTexture?o.glyphAtlasTexture:null,te=E.LINEAR,ie=0!==i.paint.get("text-halo-width").constantOr(1),oe=e.terrain&&A&&t?Lt($t(),Z):p_;if(t&&r.text){const t=_i.getAtTileOffsetFunc(s,S.center.lat,S.worldSize,r.getProjection()),i=xc(_,o.tileID.canonical,A,C,S,r.getProjection(),p);Sc(r,_,e,!0,i,W,A,m,t,s,N)}return{program:w,buffers:r.text,uniformValues:J,atlasTexture:ee,atlasTextureIcon:R,atlasInterpolation:te,atlasInterpolationIcon:T,isSDF:!0,hasHalo:ie,depthMode:y,tile:o,renderWithShadows:g,labelPlaneMatrixInv:oe}},$=r.icon.segments.get().length,X=r.text.segments.get().length,Y=$&&!n.onlyText?Z():null,K=X&&!n.onlyIcons?W():null,Q=i.paint.get("icon-opacity").constantOr(1),J=i.paint.get("text-opacity").constantOr(1);if(D&&r.canOverlap){L=!0;const e=Q&&!n.onlyText?r.icon.segments.get():[],t=J&&!n.onlyIcons?r.text.segments.get():[];for(const t of e)B.push({segments:new It([t]),sortKey:t.sortKey,state:Y});for(const e of t)B.push({segments:new It([e]),sortKey:e.sortKey,state:K})}else n.onlyText||B.push({segments:Q?r.icon.segments:new It([]),sortKey:0,state:Y}),n.onlyIcons||B.push({segments:J?r.text.segments:new It([]),sortKey:0,state:K})}L&&B.sort(((e,t)=>e.sortKey-t.sortKey));for(const t of B){const o=t.state;if(o)if(e.terrain?e.terrain.setupElevationDraw(o.tile,o.program,{useDepthForOcclusion:S.depthOcclusionForSymbolsAndCircles,labelPlaneMatrixInv:o.labelPlaneMatrixInv}):e.setupDepthForOcclusion(S.depthOcclusionForSymbolsAndCircles,o.program),T.activeTexture.set(E.TEXTURE0),o.atlasTexture&&o.atlasTexture.bind(o.atlasInterpolation,E.CLAMP_TO_EDGE,!0),o.atlasTextureIcon&&(T.activeTexture.set(E.TEXTURE1),o.atlasTextureIcon&&o.atlasTextureIcon.bind(o.atlasInterpolationIcon,E.CLAMP_TO_EDGE,!0)),o.renderWithShadows&&e.shadowRenderer.setupShadows(o.tile.tileID.toUnwrapped(),o.program,"vector-tile"),e.uploadCommonLightUniforms(e.context,o.program),o.hasHalo){const n=o.uniformValues;n.u_is_halo=1,y_(o.buffers,t.segments,i,e,o.program,o.depthMode,s,r,n,2),n.u_is_halo=0}else{if(o.isSDF){const n=o.uniformValues;o.hasHalo&&(n.u_is_halo=1,y_(o.buffers,t.segments,i,e,o.program,o.depthMode,s,r,n,1)),n.u_is_halo=0}y_(o.buffers,t.segments,i,e,o.program,o.depthMode,s,r,o.uniformValues,1)}}}function y_(e,t,i,o,s,r,n,a,l,c){const h=[e.dynamicLayoutVertexBuffer,e.opacityVertexBuffer,e.iconTransitioningVertexBuffer,e.globeExtVertexBuffer,e.zOffsetVertexBuffer,e.orientationVertexBuffer];s.draw(o,o.context.gl.TRIANGLES,r,n,a,fh.disabled,l,i.id,e.layoutVertexBuffer,e.indexBuffer,t,i.paint,o.transform.zoom,e.programConfigurations.get(i.id),h,c)}function x_(e,t){const i=1<<e.canonical.z,o=(t.x*i-e.canonical.x-e.wrap*i)*we,s=(t.y*i-e.canonical.y)*we,r=$s(t.z,t.y);return zo(o,s,r)}function b_(e,t,i,o,s){if(!i.layout||"none"===i.layout.get("fill-elevation-reference")||0===i.paint.get("fill-opacity").constantOr(1))return;const r=e.context.gl,n=new hh(e.context.gl.LEQUAL,hh.ReadWrite,e.depthRangeFor3D),a=new hh(e.context.gl.GREATER,hh.ReadWrite,e.depthRangeFor3D),l=function(e){let t=.01;return e.isOrthographic&&(t=xe(1e-4,t,Lo(e.pitch>=Th?1:e.pitch/Th))),2*t}(e.transform),c=e.transform.getFreeCameraOptions().position,h="elevatedStructuresDepthReconstruct",d=e.getOrCreateProgram(h,{defines:["DEPTH_RECONSTRUCTION"]}),u=e.getOrCreateProgram(h);for(const h of o){const o=t.getTile(h),_=o.getBucket(i);if(!_)continue;const p=_.elevatedStructures;if(!p)continue;const f=_.elevationBufferData.heightRange,m=x_(h.toUnwrapped(),c),g=e.translatePosMatrix(h.projMatrix,o,i.paint.get("fill-translate"),i.paint.get("fill-translate-anchor"));let v,y,x,b;if("initialize"===s){if(!f||f.min>=1||0===p.depthSegments.segments[0].primitiveLength)continue;v=Bu(g,m,l,1,0),y=n,x=p.depthSegments,b=d}else if("reset"===s){if(!f||f.min>=0||0===p.maskSegments.segments[0].primitiveLength)continue;v=Bu(g,m,0,0,1),y=a,x=p.maskSegments,b=d}else if("geometry"===s){if(0===p.depthSegments.segments[0].primitiveLength)continue;v=Bu(g,m,l,1,0),y=n,x=p.depthSegments,b=u}b.draw(e,r.TRIANGLES,y,uh.disabled,ch.disabled,fh.disabled,v,i.id,p.vertexBuffer,p.indexBuffer,x,i.paint,e.transform.zoom)}}function w_(e,t,i,o){const{painter:s,sourceCache:r,layer:n,coords:a,colorMode:l,elevationType:c,terrainEnabled:h,pass:d}=e,u=s.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 hh(s.context.gl.LEQUAL,hh.ReadOnly,s.depthRangeFor3D);let b=[0,0,0];if(y){const e=s.style.directionalLight,t=s.style.ambientLight;e&&t&&(b=Oh(s.style,e,t))}const T=_&&_.constantOr(1),E=s.terrain&&s.terrain.renderingToTexture,S=(e,d)=>{let _,m,S,I,C;d?(_=T&&!n.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",S=u.LINES):(_=T?"fillPattern":"fill",S=u.TRIANGLES);for(const R of a){const a=r.getTile(R);if(T&&!a.patternsLoaded())continue;const A=a.getBucket(n);if(!A)continue;const D=t?A.elevationBufferData:A.bufferData;if(D.isEmpty())continue;s.prepareDrawTile();const L=D.programConfigurations.get(n.id),O=s.isTileAffectedByFog(R),P=[],M=[];g&&(P.push("ELEVATED_ROADS"),M.push(D.elevatedLayoutVertexBuffer)),y&&P.push("RENDER_SHADOWS","DEPTH_TEXTURE","NORMAL_OFFSET"),E&&i&&P.push("USE_MRT1"),T&&(s.context.activeTexture.set(u.TEXTURE0),a.imageAtlasTexture&&a.imageAtlasTexture.bind(u.LINEAR,u.CLAMP_TO_EDGE),L.updatePaintBuffers());let z=!1;if(f&&a.imageAtlas){const e=a.imageAtlas,t=Vs.from(f),i=t.getPrimary().scaleSelf(w.devicePixelRatio).toString(),o=t.getSecondary(),s=e.patternPositions.get(i),r=o?e.patternPositions.get(o.scaleSelf(w.devicePixelRatio).toString()):null;z=!!s&&!!r,s&&L.setConstantPatternPositions(s,r)}p>0&&(z||L.getPatternTransitionVertexBuffer("fill-pattern"))&&P.push("FILL_PATTERN_TRANSITION");const F=s.getOrCreateProgram(_,{config:L,overrideFog:O,defines:P}),B=s.translatePosMatrix(R.projMatrix,a,n.paint.get("fill-translate"),n.paint.get("fill-translate-anchor"));y&&v.setupShadows(a.tileID.toUnwrapped(),F,"vector-tile");const k=n.paint.get("fill-emissive-strength");if(d){I=D.lineIndexBuffer,C=D.lineSegments;const e=s.terrain&&s.terrain.renderingToTexture?s.terrain.drapeBufferSize:[u.drawingBufferWidth,u.drawingBufferHeight];m="fillOutlinePattern"===_&&T?zu(B,k,s,a,e,b,p):Mu(B,k,e,b)}else I=D.indexBuffer,C=D.triangleSegments,m=T?Pu(B,k,s,a,b,p):Ou(B,k,b);s.uploadCommonUniforms(s.context,F,R.toUnwrapped());let N=e;("road"===c&&!h||"offset"===c)&&(N=x),F.draw(s,S,N,o||s.stencilModeForClipping(R),l,fh.disabled,m,n.id,D.layoutVertexBuffer,I,C,n.paint,s.transform.zoom,L,M)}};s.renderPass===d&&S(s.depthModeForSublayer(1,"opaque"===s.renderPass?hh.ReadWrite:hh.ReadOnly),!1),"none"===m&&"translucent"===s.renderPass&&n.paint.get("fill-antialias")&&S(s.depthModeForSublayer(n.getPaintProperty("fill-outline-color")?2:0,hh.ReadOnly),!0)}function T_(e,t,i,o,s,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,T="globe"===h.projection.name?er():0,E="globe"===h.projection.name,S=E?ye(h.zoom):0,I=[Ge(h.center.lng),qe(h.center.lat)],C="none"===i.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default"),R=i.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(C?null:i.lut).toArray01().slice(0,3),A=i.paint.get("fill-extrusion-flood-light-intensity"),D=i.paint.get("fill-extrusion-vertical-scale"),L=0!==i.paint.get("fill-extrusion-line-width").constantOr(1),O=i.paint.get("fill-extrusion-height-alignment"),P=i.paint.get("fill-extrusion-base-alignment"),M=Sh(e,i.paint.get("fill-extrusion-cutoff-fade-range")),z=[];let F;E&&z.push("PROJECTION_GLOBE_VIEW"),v[0]>0&&z.push("FAUX_AO"),x&&z.push("ZERO_ROOF_RADIUS"),a&&z.push("HAS_CENTROID"),A>0&&z.push("FLOOD_LIGHT"),M.shouldRenderCutoff&&z.push("RENDER_CUTOFF"),L&&z.push("RENDER_WALL_MODE");const B="shadow"===e.renderPass,k=e.shadowRenderer,N=B&&!!k,U=B?fh.disabled:fh.backCCW;e.shadowRenderer&&(e.shadowRenderer.useNormalOffset=!0);let j=[0,0,0];if(k){const t=e.style.directionalLight,i=e.style.ambientLight;t&&i&&(j=Oh(e.style,t,i)),B||(z.push("RENDER_SHADOWS","DEPTH_TEXTURE"),k.useNormalOffset&&z.push("NORMAL_OFFSET")),F=z.concat(["SHADOWS_SINGLE_CASCADE"])}const G=N?"fillExtrusionDepth":p?"fillExtrusionPattern":"fillExtrusion",V=i.getLayerRenderingStats();for(const d of o){const o=t.getTile(d),m=o.getBucket(i);if(!m||m.projection.name!==h.projection.name)continue;let g=!1;k&&(g=0===k.getMaxCascadeForTile(d.toUnwrapped()));const y=e.isTileAffectedByFog(d),x=m.programConfigurations.get(i.id);let C=!1;if(_&&o.imageAtlas){const e=o.imageAtlas,t=Vs.from(_),i=t.getPrimary().scaleSelf(w.devicePixelRatio).toString(),s=t.getSecondary(),r=e.patternPositions.get(i),n=s?e.patternPositions.get(s.scaleSelf(w.devicePixelRatio).toString()):null;C=!!r&&!!n,r&&x.setConstantPatternPositions(r,n)}u>0&&(C||x.getPatternTransitionVertexBuffer("fill-extrusion-pattern"))&&z.push("FILL_EXTRUSION_PATTERN_TRANSITION");const N=e.getOrCreateProgram(G,{config:x,defines:g?F:z,overrideFog:y});if(e.terrain&&e.terrain.setupElevationDraw(o,N,{useMeterToDem:!0}),!m.centroidVertexBuffer){const e=N.getAttributeLocation(c,"a_centroid_pos");-1!==e&&c.vertexAttrib2f(e,0,0)}!B&&k&&k.setupShadows(o.tileID.toUnwrapped(),N,"vector-tile"),p&&(e.context.activeTexture.set(c.TEXTURE0),o.imageAtlasTexture&&o.imageAtlasTexture.bind(c.LINEAR,c.CLAMP_TO_EDGE),x.updatePaintBuffers());const H=i.paint.get("fill-extrusion-vertical-gradient"),q=1/m.tileToMeter;let Z;if(B&&k){if(D_(o.tileID,m.maxHeight,e))continue;const t=k.calculateShadowPassMatrixFromTile(o.tileID.toUnwrapped());Z=Au(t,b,q,D,O,P)}else{const t=e.translatePosMatrix(d.expandedProjMatrix,o,i.paint.get("fill-extrusion-translate"),i.paint.get("fill-extrusion-translate-anchor")),s=h.projection.createInversionMatrix(h,d.canonical);Z=p?Du(t,e,H,f,v,b,q,d,o,T,O,P,S,I,s,R,D,u):Ru(t,e,H,f,v,b,q,d,T,O,P,S,I,s,R,D,A,j)}e.uploadCommonUniforms(l,N,d.toUnwrapped(),null,M);let W=m.segments;if("mercator"===h.projection.name&&!B&&(W=m.getVisibleSegments(o.tileID,e.terrain,e.transform.getFrustum(0)),!W.get().length))continue;if(V)if(B)for(const e of W.get())V.numRenderedVerticesInShadowPass+=e.primitiveLength;else for(const e of W.get())V.numRenderedVerticesInTransparentPass+=e.primitiveLength;const $=[];(e.terrain||a)&&$.push(m.centroidVertexBuffer),E&&$.push(m.layoutVertexExtBuffer),L&&$.push(m.wallVertexBuffer),N.draw(e,l.gl.TRIANGLES,s,r,n,U,Z,i.id,m.layoutVertexBuffer,m.indexBuffer,W,i.paint,e.transform.zoom,x,$)}e.shadowRenderer&&(e.shadowRenderer.useNormalOffset=!1)}class E_{constructor(){this.translate=[0,0],this.translateAnchor="map",this.edgeRadius=0,this.cutoffFadeRange=0}}function S_(e,t,i,o,s,r,n,a,l,c,h,d,u,_,p,f,m,g,v,y){const x=t.context,b=x.gl,w=t.transform,T=t.transform.zoom,E=[],S=e.translate,I=e.translateAnchor,C=e.edgeRadius,R=Sh(t,e.cutoffFadeRange);"clear"===h?(E.push("CLEAR_SUBPASS"),y&&(E.push("CLEAR_FROM_TEXTURE"),x.activeTexture.set(b.TEXTURE0),y.bind(b.LINEAR,b.CLAMP_TO_EDGE))):"sdf"===h?E.push("SDF_SUBPASS"):"emissive"===h&&(E.push("USE_MRT1"),x.activeTexture.set(b.TEXTURE0),y.bind(b.LINEAR,b.CLAMP_TO_EDGE)),g&&E.push("HAS_CENTROID"),R.shouldRenderCutoff&&E.push("RENDER_CUTOFF");const A=(e,i,s,h,v)=>{let b=E;null!=i.groundRadiusBuffer&&(b=E.concat("HAS_ATTRIBUTE_a_flood_light_ground_radius"));const w=i.programConfigurations.get(o.id),S=t.isTileAffectedByFog(e),I=t.getOrCreateProgram("fillExtrusionGroundEffect",{config:w,defines:b,overrideFog:S}),A=Lu(t,h,d,c,v,[u,_*v],p,f,m,T>=17?0:C*v,y?y.size[0]:0),D=[];g&&D.push(i.hiddenByLandmarkVertexBuffer),null!=i.groundRadiusBuffer&&D.push(i.groundRadiusBuffer),t.uploadCommonUniforms(x,I,e.toUnwrapped(),null,R),I.draw(t,x.gl.TRIANGLES,r,n,a,l,A,o.id,i.vertexBuffer,i.indexBuffer,s,o.paint,T,w,D)};for(const e of s){const s=i.getTile(e),r=s.getBucket(o);if(!r||r.projection.name!==w.projection.name||!r.groundEffect||r.groundEffect&&!r.groundEffect.hasData())continue;const n=r.groundEffect,a=1/r.tileToMeter;{const i=t.translatePosMatrix(e.projMatrix,s,S,I),o=n.getDefaultSegment();A(e,n,o,i,a)}if(v)for(let r=0;r<4;r++){const n=Xs[r](e),l=i.getTile(n);if(!l)continue;const c=l.getBucket(o);if(!c||c.projection.name!==w.projection.name||!c.groundEffect||c.groundEffect&&!c.groundEffect.hasData())continue;const h=c.groundEffect;let d,u;0===r?(d=[-we,0,0],u=1):1===r?(d=[we,0,0],u=0):2===r?(d=[0,-we,0],u=3):(d=[0,we,0],u=2);const _=h.regionSegments[u];if(!_)continue;const p=new Float32Array(16);Bt(p,e.projMatrix,d),A(e,h,_,t.translatePosMatrix(p,s,S,I),a)}}}function I_(e,t,i,o,s,n,a){0===o.centroidVertexArray.length&&o.createCentroidsBuffer();const l=n?n.findDEMTileFor(i):null;if(!(l&&l.dem||a))return;n&&l&&l.dem&&o.selfDEMTileTimestamp!==l.dem._timestamp&&(o.borderDoneWithNeighborZ=[-1,-1,-1,-1],o.selfDEMTileTimestamp=l.dem._timestamp);const c=e=>new r(Math.ceil((e+Qs)*Js),0),h=e=>{const i=t.getSource().minzoom,o=e=>{const i=t.getTileByID(e);if(i&&i.hasData())return i.getBucket(s)},r=[0,-1,1];for(const t of r){if(e.overscaledZ+t<i)continue;const s=o(e.calculateScaledKey(e.overscaledZ+t));if(s)return s}},d=[0,0,0],u=(e,t)=>(d[0]=Math.min(e.min.y,t.min.y),d[1]=Math.max(e.max.y,t.max.y),d[2]=we-t.min.x>e.max.x?t.min.x-we:e.max.x,d),_=(e,t)=>(d[0]=Math.min(e.min.x,t.min.x),d[1]=Math.max(e.max.x,t.max.x),d[2]=we-t.min.y>e.max.y?t.min.y-we:e.max.y,d),p=[(e,t)=>u(e,t),(e,t)=>u(t,e),(e,t)=>_(e,t),(e,t)=>_(t,e)],f=(e,t,o,s,r,a,c)=>{if(!n)return 0;const h=[[a?o:e,a?e:o,0],[a?o:t,a?t:o,0]],d=c<0?we+c:c,u=[a?d:(e+t)/2,a?(e+t)/2:d,0];return 0===o&&c<0||0!==o&&c>0?n.getForTilePoints(r,[u],!0,s):h.push(u),n.getForTilePoints(i,h,!0,l),Math.max(h[0][2],h[1][2],u[2])/n.exaggeration()};for(let e=0;e<4;e++){const t=o.borderFeatureIndices[e];if(0===t.length)continue;const s=Xs[e](i),l=h(s);if(!(l&&l instanceof Ys))continue;const d=n?n.findDEMTileFor(s):null;if(!(d&&d.dem||a))continue;if(n&&d&&d.dem&&o.borderDEMTileTimestamp[e]!==d.dem._timestamp&&(o.borderDoneWithNeighborZ[e]=-1,o.borderDEMTileTimestamp[e]=d.dem._timestamp),o.borderDoneWithNeighborZ[e]===l.canonical.z)continue;0===l.centroidVertexArray.length&&l.createCentroidsBuffer();const u=(e<2?1:5)-e,_=l.borderDoneWithNeighborZ[u]!==o.canonical.z,v=l.borderFeatureIndices[u];let y=0;if(o.canonical.z!==l.canonical.z){for(const e of t)o.showCentroid(o.featuresOnBorder[e]);if(_)for(const e of v)l.showCentroid(l.featuresOnBorder[e]);o.borderDoneWithNeighborZ[e]=l.canonical.z,l.borderDoneWithNeighborZ[u]=o.canonical.z}for(const i of t){const t=o.featuresOnBorder[i],n=o.centroidData[t.centroidDataIndex],h=t.borders[e];let _;for(;y<v.length;){_=l.featuresOnBorder[v[y]];const e=_.borders[u];if(e[1]>h[0]+3||e[0]>h[0]-3)break;l.showCentroid(_),y++}if(_&&y<v.length){const i=y;let x=0;for(;!(_.borders[u][0]>h[1]-3)&&(x++,++y!==v.length);)_=l.featuresOnBorder[v[y]];_=l.featuresOnBorder[v[i]];let b=!1;if(x>=1){const e=_.borders[u];Math.abs(h[0]-e[0])<3&&Math.abs(h[1]-e[1])<3&&(x=1,b=!0,y=i+1)}else if(0===x){o.showCentroid(t);continue}const w=l.centroidData[_.centroidDataIndex];a&&b&&(((m=n).flags|(g=w).flags)&Ks?(m.flags|=Ks,g.flags|=Ks):(m.flags&=~Ks,g.flags&=~Ks));const T=t.intersectsCount()>1||_.intersectsCount()>1;if(x>1)y=i,n.centroidXY=w.centroidXY=new r(0,0);else if(d&&d.dem&&!T){const t=p[e](n,w),i=e%2?we-1:0,o=f(t[0],Math.min(we-1,t[1]),i,d,s,e<2,t[2]);n.centroidXY=w.centroidXY=c(o)}else T?n.centroidXY=w.centroidXY=new r(0,0):(n.centroidXY=o.encodeBorderCentroid(t),w.centroidXY=l.encodeBorderCentroid(_));o.writeCentroidToBuffer(n),l.writeCentroidToBuffer(w)}else o.showCentroid(t)}o.borderDoneWithNeighborZ[e]=l.canonical.z,l.borderDoneWithNeighborZ[u]=o.canonical.z}var m,g;(o.needsCentroidUpdate||!o.centroidVertexBuffer&&0!==o.centroidVertexArray.length)&&o.uploadCentroid(e)}const C_=[1,0,0],R_=[0,1,0],A_=[0,0,1];function D_(e,t,i){const o=i.transform,s=i.shadowRenderer;if(!s)return!0;const r=e.toUnwrapped(),n=o.tileSize*s._cascades[i.currentShadowCascade].scale;let a=t;if(o.elevation){const t=o.elevation.getMinMaxForTile(e);t&&(a+=t.max)}const l=[...s.shadowDirection];l[2]=-l[2];const c=s.computeSimplifiedTileShadowVolume(r,a,n,l);if(!c)return!1;const h=[C_,R_,A_,l,[l[0],0,l[2]],[0,l[1],l[2]]],d="globe"===o.projection.name,u=o.scaleZoom(n),_=to.fromInvProjectionMatrix(o.invProjMatrix,o.worldSize,u,!d),p=s.getCurrentCascadeFrustum();return 0===_.intersectsPrecise(c.vertices,c.planes,h)||0===p.intersectsPrecise(c.vertices,c.planes,h)}function L_(e){const{painter:t,source:i,layer:o,coords:s}=e;let r=e.defines;const n=t.context,a="shadow"===t.renderPass,l="light-beam"===t.renderPass,c=t.shadowRenderer,h=ir(t.transform.center.lat,t.transform.zoom),d=Sh(t,o.paint.get("building-cutoff-fade-range"));d.shouldRenderCutoff&&(r=r.concat("RENDER_CUTOFF")),e.floodLightIntensity>0&&(r=r.concat("FLOOD_LIGHT"));for(const u of s){const s=i.getTile(u),_=s.getBucket(o);if(!_)continue;c&&0===c.getMaxCascadeForTile(u.toUnwrapped())&&(r=r.concat("SHADOWS_SINGLE_CASCADE"));const p=_.programConfigurations.get(o.id);let f,m,g,v=t.translatePosMatrix(u.expandedProjMatrix,s,[0,0],"map");if(v=vo($t(),v,[1,1,e.verticalScale]),a&&c){if(D_(s.tileID,_.maxHeight*h,t))continue;let i=c.calculateShadowPassMatrixFromTile(s.tileID.toUnwrapped());i=vo($t(),i,[1,1,e.verticalScale]),g=Uu(i),f=m=t.getOrCreateProgram("buildingDepth",{config:p,defines:r,overrideFog:!1})}else if(l)f=m=t.getOrCreateProgram("buildingBloom",{config:p,defines:r,overrideFog:!1}),g=Nu(v);else{const i=t.transform.calculatePosMatrix(u.toUnwrapped(),t.transform.worldSize);vo(i,i,[1,1,e.verticalScale]);const o=$t();vo(o,i,[1,-1,1/h]),Lt(o,o),tr(o,o);const s=t.transform.getFreeCameraOptions().position,n=1<<u.canonical.z;if(g=ku(v,o,e.opacity,e.facadeAOIntensity,[((s.x-u.wrap)*n-u.canonical.x)*we,(s.y*n-u.canonical.y)*we,s.z*n*we],_.tileToMeter,e.facadeEmissiveChance,e.floodLightColor,e.floodLightIntensity),m=t.getOrCreateProgram("building",{config:p,defines:r,overrideFog:!1}),!0===e.depthOnly)f=m;else{const e=r.concat(["BUILDING_FAUX_FACADE","HAS_ATTRIBUTE_a_faux_facade_color_emissive"]);f=t.getOrCreateProgram("building",{config:p,defines:e,overrideFog:!1})}c&&(c.setupShadowsFromMatrix(i,m,!0),f!==m&&c.setupShadowsFromMatrix(i,f,!0))}const y=(i,s)=>{if(l){const r=i.entranceBloom;s.draw(t,n.gl.TRIANGLES,e.depthMode,uh.disabled,e.blendMode,fh.disabled,g,o.id,r.layoutVertexBuffer,r.indexBuffer,r.segmentsBucket,o.paint,t.transform.zoom,p,[r.layoutAttenuationBuffer,r.layoutColorBuffer])}else{const r=i.segmentsBucket;let l=[i.layoutNormalBuffer,i.layoutCentroidBuffer,i.layoutColorBuffer,i.layoutFloodLightDataBuffer];i.layoutFacadePaintBuffer&&(l=l.concat([i.layoutFacadeDataBuffer,i.layoutFacadeVerticalRangeBuffer,i.layoutFacadePaintBuffer])),s.draw(t,n.gl.TRIANGLES,e.depthMode,uh.disabled,e.blendMode,a?fh.disabled:fh.backCW,g,o.id,i.layoutVertexBuffer,i.indexBuffer,r,o.paint,t.transform.zoom,p,l)}};t.uploadCommonUniforms(n,m,u.toUnwrapped(),null,d),_.buildingWithoutFacade&&y(_.buildingWithoutFacade,m),_.buildingWithFacade&&(f!==m&&t.uploadCommonUniforms(n,f,u.toUnwrapped(),null,d),y(_.buildingWithFacade,f))}}function O_(e,t,i,o,s,r,n,a,l,c,h,d,u){const _=e.context.gl,p=e.depthModeForSublayer(1,hh.ReadOnly,_.LEQUAL,!0),f=.1*(1-(m=h))+3*m;var m;const g=e._showOverdrawInspector,v=d,y=new E_;g||S_(y,e,t,i,o,p,new uh({func:_.ALWAYS,mask:255},255,255,_.KEEP,_.KEEP,_.REPLACE),new ch([_.ONE,_.ONE,_.ONE,_.ONE],Te.transparent,[!1,!1,!1,!0],_.MIN),fh.disabled,s,"sdf",r,n,a,l,c,f,v,!1);{const h=g?uh.disabled:new uh({func:_.EQUAL,mask:255},255,255,_.KEEP,_.DECR,_.DECR),d=g?e.colorModeForRenderPass():new ch([_.ONE_MINUS_DST_ALPHA,_.DST_ALPHA,_.ONE,_.ONE],Te.transparent,[!0,!0,!0,!0]);S_(y,e,t,i,o,p,h,d,fh.disabled,s,"color",r,n,a,l,c,f,v,!1)}}function P_(e){return[e[0]*or,e[1]*or,e[2]*or,0]}function M_(e,t,i,o,s,r,n,a,l){const c=o.getSource(),h=i.globeSharedBuffers;if(!h)return;let d,u,_;if(t&&(d=o.getTile(t)),c instanceof it?(u=c.texture,_=ws(0,0,i.transform)):d&&t&&(u=d.texture,_=ws(t.canonical.z,t.canonical.x,i.transform)),!u||!_)return;e||(_=vo($t(),_,[1,-1,1]));const p=i.context,f=p.gl,m="nearest"===s.paint.get("raster-resampling")?f.NEAREST:f.LINEAR,g=i.colorModeForDrapableLayerRenderPass(r),v=n.defines;v.push("GLOBE_POLES");const y=new hh(f.LEQUAL,hh.ReadWrite,i.depthRangeFor3D),x=Float32Array.from(i.transform.expandedFarZProjMatrix),b=Float32Array.from(Dt(bs(new oo(0,0,0))));i.terrain&&i.terrain.prepareDrawTile(),p.activeTexture.set(f.TEXTURE0),u.bind(m,f.CLAMP_TO_EDGE),p.activeTexture.set(f.TEXTURE1),u.bind(m,f.CLAMP_TO_EDGE),"useMipmap"in u&&p.extTextureFilterAnisotropic&&i.transform.pitch>20&&f.texParameterf(f.TEXTURE_2D,p.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,p.extTextureFilterAnisotropicMax);const[w,T,E,S]=t?h.getPoleBuffers(t.canonical.z,!1):h.getPoleBuffers(0,!0),I=s.paint.get("raster-elevation");let C;e?(C=w,i.renderDefaultNorthPole=0!==I):(C=T,i.renderDefaultSouthPole=0!==I);const R=P_(n.mix),A=((e,t,i,o,s,r,n,a,l,c,h,d,u)=>Wu(e,t,i,new Float32Array(16),new Float32Array(9),[0,0],o,[0,0],[0,0,0,0],1,{opacity:1,mix:0},r,[0,0]||[0,0],a,2,c,h,d,1,0,u))(x,b,_,ye(i.transform.zoom),0,s,0,I,0,R,n.offset,n.range,r),D=i.getOrCreateProgram("raster",{defines:v});i.uploadCommonUniforms(p,D,null),D.draw(i,f.TRIANGLES,y,l,g,a,A,s.id,C,E,S)}function z_(e){const t=e._nearZ,i=e.projection.farthestPixelDistance(e),o=i-t,s=.2*e.height,r=t+s;return[t,i,(r-s-t)/o,(r-t)/o]}function F_(e,t,i,o){if(e)return t instanceof Al&&e instanceof $l?t.getTextureDescriptor(e,i,!0):{texture:e.texture,mix:P_(o.mix),offset:o.offset,buffer:0,tileSize:1}}const B_=sr([{name:"a_index",type:"Int16",components:1}]);class k_{constructor(e,t,i,o){const s={width:i[0],height:i[1],data:null},r=e.gl;this.targetColorTexture=new z(e,s,r.RGBA8,{useMipmap:!1}),this.backgroundColorTexture=new z(e,s,r.RGBA8,{useMipmap:!1}),this.context=e,this.updateParticleTexture(t,o),this.lastInvalidatedAt=0}updateParticleTexture(e,t){if(this.particleTextureDimension===t.width)return;(this.particleTexture0||this.particleTexture1||this.particleIndexBuffer||this.particleSegment)&&(this.particleTexture0.destroy(),this.particleTexture1.destroy(),this.particleIndexBuffer.destroy(),this.particleSegment.destroy());const i=this.context.gl,o=t.width*t.height;this.particleTexture0=new z(this.context,t,i.RGBA8,{premultiply:!1,useMipmap:!1}),this.particleTexture1=new z(this.context,t,i.RGBA8,{premultiply:!1,useMipmap:!1});const s=new rr;s.reserve(o);for(let e=0;e<o;e++)s.emplaceBack(e);this.particleIndexBuffer=this.context.createVertexBuffer(s,B_.members,!0),this.particleSegment=It.simpleSegment(0,0,this.particleIndexBuffer.length,0),this.particleTextureDimension=t.width}update(e){return!(this.lastInvalidatedAt<e&&(this.lastInvalidatedAt=w.now(),1))}destroy(){this.targetColorTexture.destroy(),this.backgroundColorTexture.destroy(),this.particleIndexBuffer.destroy(),this.particleTexture0.destroy(),this.particleTexture1.destroy(),this.particleSegment.destroy()}}function N_(e,t,i){if(!e)return null;const o=t.getTextureDescriptor(e,i,!0);if(!o)return null;let{texture:s,mix:r,offset:n,tileSize:a,buffer:l,format:c}=o;if(!s||!c)return null;let h=!1;return"uint32"===c&&(h=!0,r[3]=0,r=qu(nr,r,[0,i.paint.get("raster-particle-max-speed")]),n=Zu(nr,n,[0,i.paint.get("raster-particle-max-speed")])),{texture:s,textureOffset:[l/(a+2*l),a/(a+2*l)],tileSize:a,scalarData:h,scale:r,offset:n,defines:["RASTER_ARRAY",{uint8:"DATA_FORMAT_UINT8",uint16:"DATA_FORMAT_UINT16",uint32:"DATA_FORMAT_UINT32"}[c]]}}function U_(e){const t=e._nearZ,i=e.projection.farthestPixelDistance(e),o=i-t,s=.2*e.height,r=t+s;return[t,i,(r-s-t)/o,(r-t)/o]}const j_=new Te(1,0,0,1),G_=new Te(0,1,0,1),V_=new Te(0,0,1,1),H_=new Te(1,0,1,1),q_=new Te(0,1,1,1);function Z_(e,t,i,o,s,r){for(let n=0;n<i.length;n++)if(s){const s=1,a=.8,l=new Te(o.r*a,o.g*a,o.b*a,1);W_(e,t,i[n],o,-s,-s,r),W_(e,t,i[n],o,-s,s,r),W_(e,t,i[n],o,s,s,r),W_(e,t,i[n],o,s,-s,r),W_(e,t,i[n],l,0,0,r)}else W_(e,t,i[n],o,0,0,r)}function W_(e,t,i,o,s,r,n){const a=e.context,l=e.transform,c=a.gl,h="globe"===l.projection.name,d=h?["PROJECTION_GLOBE_VIEW"]:[];let u=qt(i.projMatrix);if(h&&ye(l.zoom)>0){const e=At(i.canonical,l),t=ar(e);u=Be(new Float32Array(16),l.globeMatrix,t),Be(u,l.projMatrix,u)}const _=$t();_[12]+=2*s/(w.devicePixelRatio*l.width),_[13]+=2*r/(w.devicePixelRatio*l.height),Be(u,_,u);const p=e.getOrCreateProgram("debug",{defines:d}),f=t.getTileByID(i.key);e.terrain&&e.terrain.setupElevationDraw(f,p);const m=hh.disabled,g=uh.disabled,v=e.colorModeForRenderPass(),y="$debug";a.activeTexture.set(c.TEXTURE0),e.emptyTexture.bind(c.LINEAR,c.CLAMP_TO_EDGE),h?f._makeGlobeTileDebugBuffers(e.context,l):f._makeDebugTileBoundsBuffers(e.context,l.projection);const x=f._tileDebugBuffer||e.debugBuffer,b=f._tileDebugIndexBuffer||e.debugIndexBuffer,T=f._tileDebugSegments||e.debugSegments;if(p.draw(e,c.LINE_STRIP,m,g,v,fh.disabled,Gu(u,o.toPremultipliedRenderColor(null)),y,x,b,T,null,null,null,[f._globeTileDebugBorderBuffer]),n){const t=f.latestRawTileData,o=Math.floor((t&&t.byteLength||0)/1024);let s=i.canonical.toString();i.overscaledZ!==i.canonical.z&&(s+=` => ${i.overscaledZ}`),s+=` ${f.state}`,s+=` ${o}kb`,function(e,t){e.initDebugOverlayCanvas();const i=e.debugOverlayCanvas,o=e.context.gl,s=e.debugOverlayCanvas.getContext("2d");s.clearRect(0,0,i.width,i.height),s.shadowColor="white",s.shadowBlur=2,s.lineWidth=1.5,s.strokeStyle="white",s.textBaseline="top",s.font="bold 36px Open Sans, sans-serif",s.fillText(t,5,5),s.strokeText(t,5,5),e.debugOverlayTexture.update(i),e.debugOverlayTexture.bind(o.LINEAR,o.CLAMP_TO_EDGE)}(e,s)}const E=t.getTile(i).tileSize,S=512/Math.min(E,512)*(i.overscaledZ/l.zoom)*.5,I=f._tileDebugTextBuffer||e.debugBuffer,C=f._tileDebugTextIndexBuffer||e.quadTriangleIndexBuffer,R=f._tileDebugTextSegments||e.debugSegments;p.draw(e,c.TRIANGLES,m,g,ch.alphaBlended,fh.disabled,Gu(u,Te.transparent.toPremultipliedRenderColor(null),S),y,I,C,R,null,null,null,[f._globeTileDebugTextBuffer])}function $_(e,t,i,o){Y_(e,0,t+i/2,e.transform.width,i,o)}function X_(e,t,i,o){Y_(e,t-i/2,0,i,e.transform.height,o)}function Y_(e,t,i,o,s,r){const n=e.context,a=n.gl;a.enable(a.SCISSOR_TEST),a.scissor(t*w.devicePixelRatio,i*w.devicePixelRatio,o*w.devicePixelRatio,s*w.devicePixelRatio),n.clear({color:r}),a.disable(a.SCISSOR_TEST)}const K_=sr([{name:"a_pos_3f",components:3,type:"Float32"}]),{members:Q_}=K_;function J_(e,t,i,o){e.emplaceBack(t,i,o)}class ep{constructor(e){this.vertexArray=new lr,this.indices=new ht,J_(this.vertexArray,-1,-1,1),J_(this.vertexArray,1,-1,1),J_(this.vertexArray,-1,1,1),J_(this.vertexArray,1,1,1),J_(this.vertexArray,-1,-1,-1),J_(this.vertexArray,1,-1,-1),J_(this.vertexArray,-1,1,-1),J_(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,Q_),this.indexBuffer=e.createIndexBuffer(this.indices),this.segment=It.simpleSegment(0,0,36,12)}}function tp(e,t,i,o,s,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,o,s)=>({u_matrix_3f:e,u_sun_direction:t,u_sun_intensity:i,u_color_tint_r:[o.r,o.g,o.b,o.a],u_color_tint_m:[s.r,s.g,s.b,s.a],u_luminance:5e-5}))(hr(Is(),o),s,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,hh.disabled,uh.disabled,ch.unblended,fh.frontCW,h,"skyboxCapture",t.skyboxGeometry.vertexBuffer,t.skyboxGeometry.indexBuffer,t.skyboxGeometry.segment)}const ip=sr([{type:"Float32",name:"a_pos",components:3},{type:"Float32",name:"a_uv",components:2}]);class op{constructor(e){const t=new dr;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 ht;i.emplaceBack(0,1,2),i.emplaceBack(2,3,0),this.vertexBuffer=e.createVertexBuffer(t,ip.members),this.indexBuffer=e.createIndexBuffer(i),this.segments=It.simpleSegment(0,0,4,2)}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy()}}const sp=sr([{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_fade_opacity",components:1}]);class rp{constructor(){this.starsCount=16e3,this.sizeMultiplier=.15,this.sizeRange=100,this.intensityRange=200}}class np{constructor(e){this.colorModeAlphaBlendedWriteRGB=new ch([1,lh,1,lh],Te.transparent,[!0,!0,!0,!1]),this.colorModeWriteAlpha=new ch([1,0,1,0],Te.transparent,[!1,!1,!1,!0]),this.params=new rp,this.updateNeeded=!0}update(e){const t=e.context;if(!this.atmosphereBuffer||this.updateNeeded){this.updateNeeded=!1,this.atmosphereBuffer=new op(t);const e=this.params.sizeRange,i=this.params.intensityRange,o=function(e){const t=ur(30),i=[];for(let o=0;o<e;++o){const e=2*Math.PI*t(),o=Math.acos(1-2*t())-.5*Math.PI;i.push(zo(Math.cos(o)*Math.cos(e),Math.cos(o)*Math.sin(e),Math.sin(o)))}return i}(this.params.starsCount),s=ur(300),r=new _r,n=new ht;let a=0;for(let t=0;t<o.length;++t){const l=Si([],o[t],200),c=Math.max(0,1+.01*e*(1*s()-.5)),h=Math.max(0,1+.01*i*(1*s()-.5));r.emplaceBack(l[0],l[1],l[2],-1,-1,c,h),r.emplaceBack(l[0],l[1],l[2],1,-1,c,h),r.emplaceBack(l[0],l[1],l[2],1,1,c,h),r.emplaceBack(l[0],l[1],l[2],-1,1,c,h),n.emplaceBack(a+0,a+1,a+2),n.emplaceBack(a+0,a+2,a+3),a+=4}this.starsVx=t.createVertexBuffer(r,sp.members),this.starsIdx=t.createIndexBuffer(n),this.starsSegments=It.simpleSegment(0,0,r.length,n.length)}}destroy(){this.atmosphereBuffer&&this.atmosphereBuffer.destroy(),this.starsVx&&this.starsVx.destroy(),this.starsIdx&&this.starsIdx.destroy()}drawAtmosphereGlow(e,t){const i=e.context,o=i.gl,s=e.transform,r=new hh(o.LEQUAL,hh.ReadOnly,[0,1]),n=ye(s.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=pr(t.properties.get("horizon-blend"),0,1,p,.25),m=fs(e,i,s)&&f===p?s.worldSize/(2*Math.PI*1.025)-1:s.globeRadius,g=e.frameCounter/1e3%1,v=ge(s.globeCenterInViewSpace),y=Math.sqrt(Math.pow(v,2)-Math.pow(m,2)),x=Math.acos(y/v),b=t=>{const a="globe"===s.projection.name?["PROJECTION_GLOBE_VIEW","FOG"]:["FOG"];t&&a.push("ALPHA_PASS");const l=e.getOrCreateProgram("globeAtmosphere",{defines:a}),h=((e,t,i,o,s,r,n,a,l,c,h,d)=>({u_frustum_tl:e,u_frustum_tr:t,u_frustum_br:i,u_frustum_bl:o,u_horizon:s,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}))(s.frustumCorners.TL,s.frustumCorners.TR,s.frustumCorners.BR,s.frustumCorners.BL,s.frustumCorners.horizon,n,f,c,d,_,g,x);e.uploadCommonUniforms(i,l);const u=this.atmosphereBuffer;u&&l.draw(e,o.TRIANGLES,r,uh.disabled,t?this.colorModeWriteAlpha:this.colorModeAlphaBlendedWriteRGB,fh.backCW,h,t?"atmosphere_glow_alpha":"atmosphere_glow",u.vertexBuffer,u.indexBuffer,u.segments)};b(!1),b(!0)}drawStars(e,t){const i=Fe(t.properties.get("star-intensity"),0,1);if(0===i)return;const o=e.context,s=o.gl,r=e.transform,n=e.getOrCreateProgram("stars"),a=Ci([]);Ai(a,a,-r._pitch),Ri(a,a,-r.angle),Ai(a,a,Ee(r._center.lat)),fr(a,a,-Ee(r._center.lng));const l=Oi(new Float32Array(16),a),c=Be([],r.starsProjMatrix,l),h=hr([],l),d=mr([],h),u=[0,1,0];Rs(u,u,d),Si(u,u,this.params.sizeMultiplier);const _=[1,0,0];Rs(_,_,d),Si(_,_,this.params.sizeMultiplier);const p=(f=u,m=_,g=i,{u_matrix:Float32Array.from(c),u_up:f,u_right:m,u_intensity_multiplier:g});var f,m,g;e.uploadCommonUniforms(o,n),this.starsVx&&this.starsIdx&&n.draw(e,s.TRIANGLES,hh.disabled,uh.disabled,this.colorModeAlphaBlendedWriteRGB,fh.disabled,p,"atmosphere_stars",this.starsVx,this.starsIdx,this.starsSegments)}}class ap{constructor(){this.visibleTiles=[]}updateBorders(e,t){const i=[],o=[],s=e._getRenderableCoordinates(!1,!0);for(const r of s){const s=e.getTile(r);if(!s.hasData())continue;const n=s.getBucket(t);n&&(n.isEmpty()||(i.push(r.key),o.push({bucket:n,tileID:r.canonical})))}let r=i.length!==this.visibleTiles.length;if(!r){i.sort();for(let e=0;e<i.length;e++)if(i[e]!==this.visibleTiles[e]){r=!0;break}}if(!r)return;const n=new Set;this.visibleTiles=i,o.sort(((e,t)=>e.tileID.z-t.tileID.z||e.tileID.x-t.tileID.x||e.tileID.y-t.tileID.y));for(const e of o){const t=new Array,i=new Array,o=e.bucket;for(const e of o.featuresOnBorder)n.has(e.featureId)?i.push(e.footprintIndex):(n.add(e.featureId),t.push(e.footprintIndex));o.updateFootprintHiddenFlags(t,gr,!1),o.updateFootprintHiddenFlags(i,gr,!0)}}}function lp(e,t){const i=[...e],o=t.cameraWorldSizeForFog/t.worldSize,s=Zt([]);return vo(s,s,[o,o,1]),Be(i,s,i),Be(i,t.worldToFogMatrix,i),i}function cp(e,t,i,o,s){const r=i.material,n=o.context,{baseColorTexture:a,metallicRoughnessTexture:l}=r.pbrMetallicRoughness,{normalTexture:c,occlusionTexture:h,emissionTexture:d}=r;function u(t,i,o){if(t&&(e.push(i),n.activeTexture.set(n.gl.TEXTURE0+o),t.gfxTexture)){const{minFilter:e,magFilter:i,wrapS:o,wrapT:s}=t.sampler;t.gfxTexture.bindExtraParam(e,i,o,s)}}u(a,"HAS_TEXTURE_u_baseColorTexture",bh.BaseColor),u(l,"HAS_TEXTURE_u_metallicRoughnessTexture",bh.MetallicRoughness),u(c,"HAS_TEXTURE_u_normalTexture",bh.Normal),u(h,"HAS_TEXTURE_u_occlusionTexture",bh.Occlusion),u(d,"HAS_TEXTURE_u_emissionTexture",bh.Emission),s&&(s.texture||(s.texture=new Ns(o.context,s.image,[s.image.height,s.image.height,s.image.height],n.gl.RGBA8)),n.activeTexture.set(n.gl.TEXTURE0+bh.LUT),s.texture&&s.texture.bind(n.gl.LINEAR,n.gl.CLAMP_TO_EDGE),e.push("APPLY_LUT_ON_GPU")),i.texcoordBuffer&&(e.push("HAS_ATTRIBUTE_a_uv_2f"),t.push(i.texcoordBuffer)),i.colorBuffer&&(e.push(12===i.colorBuffer.itemSize?"HAS_ATTRIBUTE_a_color_3f":"HAS_ATTRIBUTE_a_color_4f"),t.push(i.colorBuffer)),i.normalBuffer&&(e.push("HAS_ATTRIBUTE_a_normal_3f"),t.push(i.normalBuffer)),i.pbrBuffer&&(e.push("HAS_ATTRIBUTE_a_pbr"),e.push("HAS_ATTRIBUTE_a_heightBasedEmissiveStrength"),t.push(i.pbrBuffer)),"OPAQUE"!==r.alphaMode&&"MASK"!==r.alphaMode||e.push("UNPREMULT_TEXTURE_IN_SHADER"),r.defined||e.push("DIFFUSE_SHADED");const _=o.shadowRenderer;_&&(e.push("RENDER_SHADOWS","DEPTH_TEXTURE"),_.useNormalOffset&&e.push("NORMAL_OFFSET"))}function hp(e,t,i,o,s,r){const n=e.modelOpacity,a=t.context,l=new hh(t.context.gl.LEQUAL,e.isLightMesh?hh.ReadOnly:hh.ReadWrite,t.depthRangeFor3D),c=t.transform,h=e.mesh,d=h.material,u=d.pbrMetallicRoughness,_=t.style.fog;let p;p="pixels"===t.transform.projection.zAxisUnit?[...e.nodeModelMatrix]:Be([],o.zScaleMatrix,e.nodeModelMatrix),Be(p,o.negCameraPosMatrix,p);const f=Lt([],p);tr(f,f);const m="none"===i.paint.get("model-color-use-theme").constantOr("default"),g=i.paint.get("model-emissive-strength").constantOr(0),v=s_(new Float32Array(e.worldViewProjection),new Float32Array(p),new Float32Array(f),null,t,n,u.baseColorFactor,d.emissiveFactor,u.metallicFactor,u.roughnessFactor,d,g,i,void 0,void 0,e.materialOverride,e.modelColor),y={defines:[]},x=[],b=t.shadowRenderer;b&&(b.useNormalOffset=!1),cp(y.defines,x,h,t,m?null:i.lut);let w=null;if(_){const i=lp(e.nodeModelMatrix,t.transform);if(w=new Float32Array(i),"globe"!==c.projection.name){const e=h.aabb.min,t=h.aabb.max,[o,s]=_.getOpacityForBounds(i,e[0],e[1],t[0],t[1]);y.overrideFog=o>=rl||s>=rl}}const T=Sh(t,i.paint.get("model-cutoff-fade-range"));T.shouldRenderCutoff&&y.defines.push("RENDER_CUTOFF");const E=t.getOrCreateProgram("model",y);t.uploadCommonUniforms(a,E,null,w,T),"shadow"!==t.renderPass&&b&&b.setupShadowsFromMatrix(e.nodeModelMatrix,E),E.draw(t,a.gl.TRIANGLES,l,s,r,h.material.doubleSided?fh.disabled:fh.backCCW,v,i.id,h.vertexBuffer,h.indexBuffer,h.segments,i.paint,t.transform.zoom,void 0,x)}function dp(e,t){return e.style._importedAsBasemap?"basemap":t.scope}function up(e,t,i,o,s,r,n,a,l,c){const h=e.transform,d=!!t.isGeometryBloom&&t.isGeometryBloom;if(d&&"shadow"===e.renderPass)return;const u="globe"===h.projection.name?Sr(i,h):[...i];Be(u,u,t.globalMatrix);const _=Be([],o,u);if(t.meshes)for(const e of t.meshes){const t=a.get(e.material.name);if(t&&t.opacity<=0)continue;if("BLEND"!==e.material.alphaMode){n.push({mesh:e,depth:0,modelIndex:s,worldViewProjection:_,nodeModelMatrix:u,isLightMesh:d,materialOverride:t,modelOpacity:l,modelColor:c});continue}const i=fe([],e.centroid,_);!h.isOrthographic&&i[2]<=0||r.push({mesh:e,depth:i[2],modelIndex:s,worldViewProjection:_,nodeModelMatrix:u,isLightMesh:d,materialOverride:t,modelOpacity:l,modelColor:c})}if(t.children)for(const h of t.children)up(e,h,i,o,s,r,n,a,l,c)}function _p(e,t,i,o){const s=i.shadowRenderer;if(!s)return;const r=s.getShadowPassDepthMode(),n=s.getShadowPassColorMode(),a=s.calculateShadowPassMatrixFromMatrix(t),l=r_(a);i.getOrCreateProgram("modelDepth",{defines:i._shadowMapDebug?[]:["DEPTH_TEXTURE"]}).draw(i,i.context.gl.TRIANGLES,r,uh.disabled,n,fh.disabled,l,o.id,e.vertexBuffer,e.indexBuffer,e.segments,o.paint,i.transform.zoom,void 0,void 0)}function pp(e,t,i,o,s,r){for(const n of s){const s=Object.assign({},o);s.part=n;const a={type:"Unknown",id:t,properties:s},l={orientation:e.paint.get("model-rotation").evaluate(a,i)};r.set(n,l)}}function fp(e,t,i,o,s,r){for(const n of s){const s=Object.assign({},o);s.part=n;const a={type:"Unknown",id:t,properties:s},l={color:e.paint.get("model-color").evaluate(a,i),colorMix:e.paint.get("model-color-mix-intensity").evaluate(a,i),opacity:e.paint.get("model-opacity").evaluate(a,i),emissionStrength:e.paint.get("model-emissive-strength").evaluate(a,i)};r.set(n,l)}}function mp(e,t,i,o,s){let r=!1;for(const i of o)1!==i.modelOpacity&&(hp(i,e,t,s[i.modelIndex],uh.disabled,ch.disabled),r=!0);for(const i of o)hp(i,e,t,s[i.modelIndex],1!==i.modelOpacity?e.stencilModeFor3D():uh.disabled,e.colorModeForRenderPass());r&&e.resetStencilClippingMasks();const n=ch.additive;for(const o of i)hp(o,e,t,s[o.modelIndex],uh.disabled,o.isLightMesh?n:e.colorModeForRenderPass())}function gp(e,t,i){const o=t.updateZoomBasedPaintProperties(),s=function(e,t,i){let o,s,r,n=e.terrain?e.terrain.exaggeration():0;if(e.terrain&&n>0){const t=e.terrain,s=t.findDEMTileFor(i);s&&s.dem?o=Cr.create(t,i,s):n=0}if(0===n&&(t.terrainElevationMin=0,t.terrainElevationMax=0),n===t.validForExaggeration&&(0===n||o&&o._demTile&&o._demTile.tileID===t.validForDEMTile.id&&o._dem._timestamp===t.validForDEMTile.timestamp))return!1;for(const e in t.instancesPerModel){const i=t.instancesPerModel[e];for(let e=0;e<i.instancedDataArray.length;++e){const a=(o?n*o.getElevationAt(0|i.instancedDataArray.float32[16*e],0|i.instancedDataArray.float32[16*e+1],!0,!0):0)+i.instancesEvaluatedElevation[e];i.instancedDataArray.float32[16*e+6]=a,s=s?Math.min(t.terrainElevationMin,a):a,r=r?Math.max(t.terrainElevationMax,a):a}}return t.terrainElevationMin=s||0,t.terrainElevationMax=r||0,t.validForExaggeration=n,t.validForDEMTile=o&&o._demTile?{id:o._demTile.tileID,timestamp:o._dem._timestamp}:{id:void 0,timestamp:0},!0}(e,t,i);(o||s)&&(t.uploaded=!1,t.upload(e.context))}const vp={shadowUniformsInitialized:!1,useSingleShadowCascade:!1,tileMatrix:new Float64Array(16),shadowTileMatrix:new Float32Array(16),aabb:new No([0,0,0],[we,we,0])};function yp(e,t){const i=1<<e.canonical.z,o=t.getFreeCameraOptions().position,s=t.elevation,r=e.canonical.x/i,n=(e.canonical.x+1)/i,a=e.canonical.y/i,l=(e.canonical.y+1)/i;let c=t._centerAltitude;if(s){const t=s.getMinMaxForTile(e);t&&t.max>c&&(c=t.max)}const h=Fe(o.x,r,n)-o.x,d=Fe(o.y,a,l)-o.y,u=zi(c,t.center.lat)-o.z;return t._zoomFromMercatorZ(Math.sqrt(h*h+d*d+u*u))}function xp(e,t,i,o,s,r,n){const a=e.context,l="shadow"===e.renderPass,c=e.shadowRenderer,h=l&&c?c.getShadowPassDepthMode():new hh(a.gl.LEQUAL,hh.ReadWrite,e.depthRangeFor3D),d=e.isTileAffectedByFog(r),u="globe"===e.transform.projection.name;if(i.meshes)for(const _ of i.meshes){const p=u?[]:["MODEL_POSITION_ON_GPU"],f=[];let m,g,v;const y=!u&&o.instancedDataArray.length>20;y&&p.push("INSTANCED_ARRAYS");const x=Sh(e,t.paint.get("model-cutoff-fade-range"));if(x.shouldRenderCutoff&&p.push("RENDER_CUTOFF"),l&&c)m=e.getOrCreateProgram("modelDepth",{defines:p}),g=r_(n.shadowTileMatrix,n.shadowTileMatrix,Float32Array.from(i.globalMatrix)),v=c.getShadowPassColorMode();else{cp(p,f,_,e,"none"===t.paint.get("model-color-use-theme").constantOr("default")?null:t.lut),m=e.getOrCreateProgram("model",{defines:p,overrideFog:d});const o=_.material,l=o.pbrMetallicRoughness,h=t.paint.get("model-opacity").constantOr(1),u=t.paint.get("model-emissive-strength").constantOr(0);g=s_(r.expandedProjMatrix,Float32Array.from(i.globalMatrix),new Float32Array(16),null,e,h,l.baseColorFactor,o.emissiveFactor,l.metallicFactor,l.roughnessFactor,o,u,t,s),c&&(n.shadowUniformsInitialized?m.setShadowUniformValues(a,c.getShadowUniformValues()):(c.setupShadows(r.toUnwrapped(),m,"model-tile"),n.shadowUniformsInitialized=!0)),v=x.shouldRenderCutoff||h<1||"OPAQUE"!==o.alphaMode?ch.alphaBlended:ch.unblended}e.uploadCommonUniforms(a,m,r.toUnwrapped(),null,x);const b=_.material.doubleSided?fh.disabled:fh.backCCW;if(y)f.push(o.instancedDataBuffer),m.draw(e,a.gl.TRIANGLES,h,uh.disabled,v,b,g,t.id,_.vertexBuffer,_.indexBuffer,_.segments,t.paint,e.transform.zoom,void 0,f,o.instancedDataArray.length);else{const i=l?"u_instance":"u_normal_matrix";for(let s=0;s<o.instancedDataArray.length;++s)g[i]=new Float32Array(o.instancedDataArray.arrayBuffer,64*s,16),m.draw(e,a.gl.TRIANGLES,h,uh.disabled,v,b,g,t.id,_.vertexBuffer,_.indexBuffer,_.segments,t.paint,e.transform.zoom,void 0,f)}}if(i.children)for(const a of i.children)xp(e,t,a,o,s,r,n)}const bp=[1,-1,1];function wp(e,t,i,o){if(!i.modelManager)return!0;const s=i.modelManager;if(!i.shadowRenderer)return!0;const r=i.shadowRenderer,n=t.aabb;let a=!0,l=e.maxHeight;if(0===l){let t=0;for(const i in e.instancesPerModel){const e=s.getModel(i,o);e?t=Math.max(t,Math.max(Math.max(e.aabb.max[0],e.aabb.max[1]),e.aabb.max[2])):a=!1}l=e.maxScale*t*1.41+e.maxVerticalOffset,a&&(e.maxHeight=l)}n.max[2]=l,n.min[2]+=e.terrainElevationMin,n.max[2]+=e.terrainElevationMax,fe(n.min,n.min,t.tileMatrix),fe(n.max,n.max,t.tileMatrix);const c=n.intersects(r.getCurrentCascadeFrustum());return 0===i.currentShadowCascade&&(e.isInsideFirstShadowMapFrustum=2===c),0===c}function Tp(e,t){const i=e.uniformValues.u_cutoff_params[0],o=e.uniformValues.u_cutoff_params[1],s=e.uniformValues.u_cutoff_params[2],r=e.uniformValues.u_cutoff_params[3];return o===i||r===s?1:Fe(((t-i)/(o-i)-s)/(r-s),0,1)}function Ep(e,t,i,o){if(t.pitch<20)return 1;const s=t.getWorldToCameraMatrix();Be(s,s,e);const r=ui(i.min[0],i.min[1],i.min[2],1);let n=ke(Rr(),r,s),a=n,l=n;r[1]=i.max[1],n=ke(Rr(),r,s),a=n[1]<a[1]?n:a,l=n[1]>l[1]?n:l,r[0]=i.max[0],n=ke(Rr(),r,s),a=n[1]<a[1]?n:a,l=n[1]>l[1]?n:l,r[1]=i.min[1],n=ke(Rr(),r,s),a=n[1]<a[1]?n:a,l=n[1]>l[1]?n:l;const c=Fe(o[0],0,1),h=100*t.pixelsPerMeter*Fe(o[1],0,1),d=Fe(o[2],0,1),u=Ar(Rr(),a,l,c),_=Math.tan(.5*t.fovX),p=-u[2]*_;if(0===h)return u[1]<-Math.abs(p)?d:1;const f=(-Math.abs(p)-u[1])/h,m=(e,t,i)=>(1-i)*e+i*t,g=Fe(m(1,d,f),d,1);return m(1,g,Fe((t.pitch-20)/20,0,1))}class Sp{}class Ip{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 o=i.gl,s=o.getBufferParameter(o.ELEMENT_ARRAY_BUFFER,o.BUFFER_SIZE),r=new ArrayBuffer(s),n=new Int16Array(r);o.getBufferSubData(o.ELEMENT_ARRAY_BUFFER,0,new Int16Array(r));const a=new Lr;for(let e=0;e<s/2;e+=3){const t=n[e],i=n[e+1],o=n[e+2];a.emplaceBack(t,i),a.emplaceBack(i,o),a.emplaceBack(o,t)}const l=i.bindVertexArrayOES.current,c=new Sp;return c.buf=new a_(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 Cp{constructor(){this.occluderSize=30,this.depthOffset=-1e-4}}const Rp=sr([{type:"Float32",name:"a_pos_3f",components:3},{type:"Float32",name:"a_uv",components:2},{type:"Float32",name:"a_rainParticleData",components:4}]);class Ap{constructor(e){this.revealStart=11,this.revealRange=2}}const Dp=sr([{type:"Float32",name:"a_pos_2f",components:2}]);class Lp{destroy(){this.vignetteVx&&this.vignetteVx.destroy(),this.vignetteIdx&&this.vignetteIdx.destroy()}draw(e,t){const i=e.getOrCreateProgram("vignette");if(!this.vignetteVx||!this.vignetteIdx){const t=new Or,i=new ht;t.emplaceBack(-1,-1),t.emplaceBack(1,-1),t.emplaceBack(1,1),t.emplaceBack(-1,1),i.emplaceBack(0,1,2),i.emplaceBack(0,2,3),this.vignetteVx=e.context.createVertexBuffer(t,Dp.members),this.vignetteIdx=e.context.createIndexBuffer(i)}const o=It.simpleSegment(0,0,4,6);if(this.vignetteVx&&this.vignetteIdx){e.uploadCommonUniforms(e.context,i);const r={u_vignetteShape:(s={vignetteShape:[t.start,t.range,Math.pow(10,t.fadePower)],vignetteColor:[t.color.r,t.color.g,t.color.b,t.color.a*t.strength]}).vignetteShape,u_vignetteColor:s.vignetteColor};i.draw(e,e.context.gl.TRIANGLES,hh.disabled,uh.disabled,ch.alphaBlended,fh.disabled,r,"vignette",this.vignetteVx,this.vignetteIdx,o)}var s}}class Op{constructor(){this._accumulatedOffsetX=0,this._accumulatedOffsetY=0,this._accumulatedElevation=0}update(e,t){const i=e.getFreeCameraOptions().position,o=i.toAltitude(),s=i.toLngLat(),r=Ee(s.lng),n=Ee(s.lat),a=e.pixelsPerMeter/t,l=r*Mr,c=Mr*Math.log(Math.tan(Math.PI/4+n/2));if(void 0===this._offsetXPrev)this._offsetXPrev=0,this._offsetYPrev=0,this._elevationPrev=0,this._accumulatedOffsetX=0,this._accumulatedOffsetY=0,this._accumulatedElevation=0;else{const e=-this._offsetYPrev+c,t=-this._elevationPrev+o;this._accumulatedOffsetX+=(-this._offsetXPrev+l)*a,this._accumulatedOffsetY+=e*a,this._accumulatedElevation+=t*a,this._offsetXPrev=l,this._offsetYPrev=c,this._elevationPrev=o}}getPosition(){return[this._accumulatedOffsetX,this._accumulatedOffsetY,this._accumulatedElevation]}}function Pp(e,t){return[-(e[0]-Math.floor(e[0]/t)*t),-(e[1]-Math.floor(e[1]/t)*t),-(e[2]-Math.floor(e[2]/t)*t)]}function Mp(e){const t=ur(1323123451230),i=[];for(let o=0;o<e;++o){const e=2*t()-1,o=2*t()-1,s=2*t()-1;i.push(zo(e,o,s))}return i}function zp(e,t,i,o,s){const r=Fe((s-i)/(o-i),0,1);return(1-r)*e+r*t}class Fp{constructor(e){this._movement=new Op,this._accumulatedTimeFromStart=0,this._prevTime=Date.now()/1e3,this._vignette=new Lp,this._ppmScaleFactor=e}destroy(){this.particlesVx&&this.particlesVx.destroy(),this.particlesIdx&&this.particlesIdx.destroy(),this._vignette&&this._vignette.destroy()}updateOnRender(e,t){const i=e.transform;this._movement.update(i,this._ppmScaleFactor);const o=i.starsProjMatrix,s=Ci([]);Ai(s,s,Ee(90)-i._pitch),Ri(s,s,-i.angle);const r=Oi(new Float32Array(16),s),n=Pr(1,0,0,0,0,0,1,0,0,-1,0,0,0,0,0,1),a=tr([],n),l=Be([],a,r),c=Date.now()/1e3;return this._accumulatedTimeFromStart+=(c-this._prevTime)*t,this._prevTime=c,{projectionMatrix:o,modelviewMatrix:l}}}class Bp extends Fp{constructor(e){super(4.25),this._params={overrideStyleParameters:!1,intensity:.5,timeFactor:1,velocityConeAperture:0,velocity:300,boxSize:2500,dropletSizeX:1,dropletSizeYScale:10,distortionStrength:70,screenThinning:{intensity:.57,start:.46,range:1.17,fadePower:.17,affectedRatio:1,particleOffset:-.2},color:{r:.66,g:.68,b:.74,a:.7},direction:{x:-50,y:-35},shapeDirPower:2,shapeNormalPower:1},this._revealParams=new Ap("Precipitation > Rain"),this._vignetteParams={strength:1,start:.7,range:1,fadePower:.4,color:{r:.27,g:.27,b:.27,a:1}},this.particlesCount=16e3}update(e){const t=e.context;if(!this.particlesVx){const e=Mp(this.particlesCount),i=new zr,o=new ht;let s=0;const r=ur(1323123451230);for(let t=0;t<e.length;++t){const n=e[t],a=[2*r()-1,r(),r(),r()];i.emplaceBack(n[0],n[1],n[2],-1,-1,...a),i.emplaceBack(n[0],n[1],n[2],1,-1,...a),i.emplaceBack(n[0],n[1],n[2],1,1,...a),i.emplaceBack(n[0],n[1],n[2],-1,1,...a),o.emplaceBack(s+0,s+1,s+2),o.emplaceBack(s+0,s+2,s+3),s+=4}this.particlesVx=t.createVertexBuffer(i,Rp.members),this.particlesIdx=t.createIndexBuffer(o)}}draw(e){if(!this._params.overrideStyleParameters&&!e.style.rain)return;const t=this._params.overrideStyleParameters?this._revealParams:{revealStart:0,revealRange:.01},i=e.transform.zoom;if(t.revealStart>i)return;const o=zp(0,1,t.revealStart,t.revealStart+t.revealRange,i);if(!this.particlesVx||!this.particlesIdx)return;const s=structuredClone(this._params);let r=[-s.direction.x,s.direction.y,-100];Oe(r,r);const n=structuredClone(this._vignetteParams);n.strength*=o,s.overrideStyleParameters||(s.intensity=e.style.rain.state.density,s.timeFactor=e.style.rain.state.intensity,s.color=structuredClone(e.style.rain.state.color),r=structuredClone(e.style.rain.state.direction),s.screenThinning.intensity=e.style.rain.state.centerThinning,s.dropletSizeX=e.style.rain.state.dropletSize[0],s.dropletSizeYScale=e.style.rain.state.dropletSize[1]/e.style.rain.state.dropletSize[0],s.distortionStrength=100*e.style.rain.state.distortionStrength,n.strength=1,n.color=structuredClone(e.style.rain.state.vignetteColor));const a=this.updateOnRender(e,s.timeFactor),l=e.context,c=l.gl,h=e.transform;this.screenTexture&&this.screenTexture.size[0]===e.width&&this.screenTexture.size[1]===e.height||(this.screenTexture=new z(l,{width:e.width,height:e.height,data:null},c.RGBA8)),s.distortionStrength>0&&(l.activeTexture.set(c.TEXTURE0),this.screenTexture.bind(c.LINEAR,c.CLAMP_TO_EDGE),c.copyTexSubImage2D(c.TEXTURE_2D,0,0,0,0,0,e.width,e.height));const d=e.getOrCreateProgram("rainParticle");e.uploadCommonUniforms(l,d),l.activeTexture.set(c.TEXTURE0),this.screenTexture.bind(c.LINEAR,c.CLAMP_TO_EDGE);const u=[s.color.r,s.color.g,s.color.b,s.color.a],_=(t,i)=>{const o=Pp(this._movement.getPosition(),t),n=s.dropletSizeX,l=s.dropletSizeX*s.dropletSizeYScale,_=e.width/2,p=e.height/2,f=zp(0,s.screenThinning.start,0,1,s.screenThinning.intensity),m=zp(.001,s.screenThinning.range,0,1,s.screenThinning.intensity),g=zp(0,s.screenThinning.particleOffset,0,1,s.screenThinning.intensity),v=(y={modelview:a.modelviewMatrix,projection:a.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:o,velocityConeAperture:s.velocityConeAperture,velocity:s.velocity,boxSize:t,rainDropletSize:[n,l],distortionStrength:s.distortionStrength,rainDirection:r,color:u,screenSize:[h.width,h.height],thinningCenterPos:[_,p],thinningShape:[f,m,Math.pow(10,s.screenThinning.fadePower)],thinningAffectedRatio:s.screenThinning.affectedRatio,thinningParticleOffset:g,shapeDirectionalPower:s.shapeDirPower,shapeNormalPower:s.shapeNormalPower,mode:i?0:1},{u_modelview:Float32Array.from(y.modelview),u_projection:Float32Array.from(y.projection),u_time:y.time,u_cam_pos:y.camPos,u_texScreen:0,u_velocityConeAperture:y.velocityConeAperture,u_velocity:y.velocity,u_boxSize:y.boxSize,u_rainDropletSize:y.rainDropletSize,u_distortionStrength:y.distortionStrength,u_rainDirection:y.rainDirection,u_color:y.color,u_screenSize:y.screenSize,u_thinningCenterPos:y.thinningCenterPos,u_thinningShape:y.thinningShape,u_thinningAffectedRatio:y.thinningAffectedRatio,u_thinningParticleOffset:y.thinningParticleOffset,u_shapeDirectionalPower:y.shapeDirectionalPower,u_shapeNormalPower:y.shapeNormalPower,u_mode:y.mode});var y;const x=Math.round(s.intensity*this.particlesCount),b=It.simpleSegment(0,0,4*x,2*x);d.draw(e,c.TRIANGLES,hh.disabled,uh.disabled,ch.alphaBlended,fh.disabled,v,"rain_particles",this.particlesVx,this.particlesIdx,b)};s.distortionStrength>0&&_(s.boxSize,!0),_(s.boxSize,!1),this._vignette.draw(e,n)}}const kp=sr([{type:"Float32",name:"a_pos_3f",components:3},{type:"Float32",name:"a_uv",components:2},{type:"Float32",name:"a_snowParticleData",components:4},{type:"Float32",name:"a_snowParticleDataHorizontalOscillation",components:2}]);class Np extends Fp{constructor(e){super(2.25),this._params={overrideStyleParameters:!1,intensity:.85,timeFactor:.75,velocityConeAperture:70,velocity:40,horizontalOscillationRadius:4,horizontalOscillationRate:1.5,boxSize:2e3,billboardSize:2,shapeFadeStart:.27,shapeFadePower:.21,screenThinning:{intensity:.4,start:.15,range:1.4,fadePower:.24,affectedRatio:1,particleOffset:-.2},color:{r:1,g:1,b:1,a:1},direction:{x:-50,y:-35}},this._revealParams=new Ap("Precipitation > Snow"),this._vignetteParams={strength:.3,start:.78,range:.46,fadePower:.2,color:{r:1,g:1,b:1,a:1}},this.particlesCount=16e3}update(e){const t=e.context;if(!this.particlesVx){const e=Mp(this.particlesCount),i=new Fr,o=new ht;let s=0;const r=ur(1323123451230);for(let t=0;t<e.length;++t){const n=e[t],a=r(),l=r(),c=r(),h=[t/e.length,a,l,c],d=[r(),r()];i.emplaceBack(n[0],n[1],n[2],-1,-1,...h,...d),i.emplaceBack(n[0],n[1],n[2],1,-1,...h,...d),i.emplaceBack(n[0],n[1],n[2],1,1,...h,...d),i.emplaceBack(n[0],n[1],n[2],-1,1,...h,...d),o.emplaceBack(s+0,s+1,s+2),o.emplaceBack(s+0,s+2,s+3),s+=4}this.particlesVx=t.createVertexBuffer(i,kp.members),this.particlesIdx=t.createIndexBuffer(o)}}draw(e){if(!this._params.overrideStyleParameters&&!e.style.snow)return;const t=structuredClone(this._params);let i=[-t.direction.x,t.direction.y,-100];Oe(i,i);const o=structuredClone(this._vignetteParams),s=t.overrideStyleParameters?this._revealParams:{revealStart:0,revealRange:.01},r=e.transform.zoom;if(s.revealStart>r)return;const n=zp(0,1,s.revealStart,s.revealStart+s.revealRange,r);o.strength*=n,t.overrideStyleParameters||(t.intensity=e.style.snow.state.density,t.timeFactor=e.style.snow.state.intensity,t.color=structuredClone(e.style.snow.state.color),i=structuredClone(e.style.snow.state.direction),t.screenThinning.intensity=e.style.snow.state.centerThinning,t.billboardSize=2.79*e.style.snow.state.flakeSize,o.strength=1,o.color=structuredClone(e.style.snow.state.vignetteColor));const a=this.updateOnRender(e,t.timeFactor);if(!this.particlesVx||!this.particlesIdx)return;const l=e.context,c=l.gl,h=e.transform,d=e.getOrCreateProgram("snowParticle");e.uploadCommonUniforms(l,d),((t,o,s)=>{const r=Pp(this._movement.getPosition(),t),n=h.width/2,l=h.height/2,u=zp(0,s.screenThinning.start,0,1,s.screenThinning.intensity),_=zp(.001,s.screenThinning.range,0,1,s.screenThinning.intensity),p=zp(0,s.screenThinning.particleOffset,0,1,s.screenThinning.intensity),f=(m={modelview:a.modelviewMatrix,projection:a.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:r,velocityConeAperture:s.velocityConeAperture,velocity:s.velocity,horizontalOscillationRadius:s.horizontalOscillationRadius,horizontalOscillationRate:s.horizontalOscillationRate,boxSize:t,billboardSize:1*s.billboardSize,simpleShapeParameters:[s.shapeFadeStart,s.shapeFadePower],screenSize:[h.width,h.height],thinningCenterPos:[n,l],thinningShape:[u,_,Math.pow(10,s.screenThinning.fadePower)],thinningAffectedRatio:s.screenThinning.affectedRatio,thinningParticleOffset:p,color:[s.color.r,s.color.g,s.color.b,s.color.a],direction:i},{u_modelview:Float32Array.from(m.modelview),u_projection:Float32Array.from(m.projection),u_time:m.time,u_cam_pos:m.camPos,u_velocityConeAperture:m.velocityConeAperture,u_velocity:m.velocity,u_horizontalOscillationRadius:m.horizontalOscillationRadius,u_horizontalOscillationRate:m.horizontalOscillationRate,u_boxSize:m.boxSize,u_billboardSize:m.billboardSize,u_simpleShapeParameters:m.simpleShapeParameters,u_screenSize:m.screenSize,u_thinningCenterPos:m.thinningCenterPos,u_thinningShape:m.thinningShape,u_thinningAffectedRatio:m.thinningAffectedRatio,u_thinningParticleOffset:m.thinningParticleOffset,u_particleColor:m.color,u_direction:m.direction});var m;const g=Math.round(s.intensity*this.particlesCount),v=It.simpleSegment(0,0,4*g,2*g);this.particlesVx&&this.particlesIdx&&d.draw(e,c.TRIANGLES,hh.disabled,uh.disabled,ch.alphaBlended,fh.disabled,f,"snow_particles",this.particlesVx,this.particlesIdx,v)})(t.boxSize,0,t),this._vignette.draw(e,o)}}const Up={symbol:function(e,t,i,o,s){if("translucent"!==e.renderPass)return;const r=uh.disabled,n=e.colorModeForRenderPass(),a=i.layout.get("text-variable-anchor"),l=i.layout.get("text-size-scale-range"),c=Fe(e.scaleFactor,l[0],l[1]);a&&function(e,t,i,o,s,r,n,a){const l=t.transform,c="map"===s,h="map"===r;for(const t of e){const e=o.getTile(t),s=e.getBucket(i);if(!s||!s.text||!s.text.segments.get().length)continue;const r=ti(s.textSizeData,l.zoom,a),d=pc(t,s.getProjection(),l),u=l.calculatePixelsToTileUnitsMatrix(e),_=yc(d,e.tileID.canonical,h,c,l,s.getProjection(),u),p=s.hasIconTextFit()&&s.hasIconData();r&&g_(s,c,h,n,l,_,t,Math.pow(2,l.zoom-e.tileID.overscaledZ),r,p)}}(o,e,i,t,i.layout.get("text-rotation-alignment"),i.layout.get("text-pitch-alignment"),s,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)?v_(e,t,i,o,r,n):(h&&v_(e,t,i,o,r,n,{onlyIcons:!0}),d&&v_(e,t,i,o,r,n,{onlyText:!0})),t.map.showCollisionBoxes&&(__(e,t,i,o,i.paint.get("text-translate"),i.paint.get("text-translate-anchor"),!0),__(e,t,i,o,i.paint.get("icon-translate"),i.paint.get("icon-translate-anchor"),!1))},circle:function(e,t,i,o){if("translucent"!==e.renderPass)return;const s=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===s.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,hh.ReadOnly),f=new hh(e.context.gl.LEQUAL,hh.ReadOnly,e.depthRangeFor3D),m="none"===_||u?p:f,g=uh.disabled,v=e.colorModeForDrapableLayerRenderPass(l),y="globe"===d.projection.name,x=[Ge(d.center.lng),qe(d.center.lat)],b=[];for(let s=0;s<o.length;s++){const r=o[s],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=Us(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.hasElevation&&!e.terrain&&(p.push("ELEVATED_ROADS"),f.push(l.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:js(e,r,n,v,x,i),tile:n};if(a){const e=l.segments.get();for(const t of e)b.push({segments:new It([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:o,program:s,layoutVertexBuffer:r,dynamicBuffers:n,indexBuffer:a,uniformValues:l,tile:u}=t.state,_=t.segments;e.terrain&&e.terrain.setupElevationDraw(u,s,w),e.uploadCommonUniforms(c,s,u.tileID.toUnwrapped()),s.draw(e,h.TRIANGLES,m,g,v,fh.disabled,l,i.id,r,a,_,i.paint,d.zoom,o,n)}},heatmap:function(e,t,i,o){if(0!==i.paint.get("heatmap-opacity"))if("offscreen"===e.renderPass){const s=e.context,r=s.gl,n=uh.disabled,a=new ch([r.ONE,r.ONE,r.ONE,r.ONE],Te.transparent,[!0,!0,!0,!0]);!function(e,t,i,o){const s=e.gl,r=t.width*o,n=t.height*o;e.activeTexture.set(s.TEXTURE1),e.viewport.set([0,0,r,n]);let a=i.heatmapFbo;if(!a||a&&(a.width!==r||a.height!==n)){a&&a.destroy();const t=s.createTexture();s.bindTexture(s.TEXTURE_2D,t),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.LINEAR),a=i.heatmapFbo=e.createFramebuffer(r,n,1,null),function(e,t,i,o,s,r){const n=e.gl;n.texImage2D(n.TEXTURE_2D,0,e.extRenderToTextureHalfFloat?n.RGBA16F:n.RGBA,s,r,0,n.RGBA,e.extRenderToTextureHalfFloat?n.HALF_FLOAT:n.UNSIGNED_BYTE,null),o.colorAttachment0.set(i)}(e,0,t,a,r,n)}else s.bindTexture(s.TEXTURE_2D,a.colorAttachment0.get()),e.bindFramebuffer.set(a.framebuffer)}(s,e,i,"globe"===e.transform.projection.name?.5:.25),s.clear({color:Te.transparent});const l=e.transform,c="globe"===l.projection.name,h=c?["PROJECTION_GLOBE_VIEW"]:[],d=c?fh.frontCCW:fh.disabled,u=[Ge(l.center.lng),qe(l.center.lat)];for(let _=0;_<o.length;_++){const p=o[_];if(t.hasRenderableParent(p))continue;const f=t.getTile(p),m=f.getBucket(i);if(!m||m.projection.name!==l.projection.name)continue;const g=e.isTileAffectedByFog(p),v=m.programConfigurations.get(i.id),y=e.getOrCreateProgram("heatmap",{config:v,defines:h,overrideFog:g}),{zoom:x}=e.transform;e.terrain&&e.terrain.setupElevationDraw(f,y),e.uploadCommonUniforms(s,y,p.toUnwrapped());const b=l.projection.createInversionMatrix(l,p.canonical);y.draw(e,r.TRIANGLES,hh.disabled,n,a,d,Hu(e,p,f,b,u,x,i.paint.get("heatmap-intensity")),i.id,m.layoutVertexBuffer,m.indexBuffer,m.segments,i.paint,e.transform.zoom,v,c?[m.globeExtVertexBuffer]:null)}s.viewport.set([0,0,e.width,e.height])}else"translucent"===e.renderPass&&(e.context.setColorMode(e.colorModeForRenderPass()),function(e,t){const i=e.context,o=i.gl,s=t.heatmapFbo;if(!s)return;i.activeTexture.set(o.TEXTURE0),o.bindTexture(o.TEXTURE_2D,s.colorAttachment0.get()),i.activeTexture.set(o.TEXTURE1);let r=t.colorRampTexture;r||(r=t.colorRampTexture=new z(i,t.colorRamp,o.RGBA8)),r.bind(o.LINEAR,o.CLAMP_TO_EDGE),e.getOrCreateProgram("heatmapTexture").draw(e,o.TRIANGLES,hh.disabled,uh.disabled,e.colorModeForRenderPass(),fh.disabled,((e,t,i,o)=>({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,o){if("translucent"!==e.renderPass)return;const s=i.paint.get("line-opacity"),r=i.paint.get("line-width");if(0===s.constantOr(1)||0===r.constantOr(1))return;const n=i.paint.get("line-emissive-strength").isConstant(),a=i.paint.get("line-emissive-strength").constantOr(0),l=i.paint.get("line-occlusion-opacity"),c=i.layout.get("line-elevation-reference"),h="meters"===i.layout.get("line-width-unit"),d="sea"===c,_=!(!e.terrain||!e.terrain.enabled),p=e.context,f=p.gl;if(i.hasElevatedBuckets&&"globe"===e.transform.projection.name)return;const m=i.layout.get("line-cross-slope"),g=void 0!==m,v=m<1,y=e.colorModeForDrapableLayerRenderPass(n?a:null),x=e.terrain&&e.terrain.renderingToTexture,b=x?1:w.devicePixelRatio,T=i.paint.get("line-dasharray"),E=T.constantOr(1),S=i.layout.get("line-cap"),I=T.constantOr(null),C=S.constantOr(null),R=i.paint.get("line-pattern"),A=R.constantOr(1),D=i.paint.get("line-pattern-cross-fade"),L=R.constantOr(null),O=i.paint.get("line-opacity").constantOr(1);let P=!A&&1!==O||e.depthOcclusion&&l>0&&l<1;const M=i.paint.get("line-gradient"),F=A?"linePattern":"line",B=Gs(i);let k;if(x&&e.terrain&&e.terrain.clipOrMaskOverlapStencilType()&&(P=!1),0!==l&&e.depthOcclusion){const e=i.paint._values["line-opacity"];e&&e.value&&"constant"===e.value.kind?k=e.value:u(`Occlusion opacity for layer ${i.id} is supported only when line-opacity isn't data-driven.`)}"constant"!==r.value.kind&&!1===r.value.isLineProgressConstant&&B.push("VARIABLE_LINE_WIDTH"),x&&("dual-source-blending"!==e.emissiveMode||n?"mrt-fallback"===e.emissiveMode&&B.push("USE_MRT1"):B.push("DUAL_SOURCE_BLENDING"));const N=(o,s,r,n,a,c)=>{for(const u of o){const o=t.getTile(u);if(A&&!o.patternsLoaded())continue;const _=o.getBucket(i);if(!_)continue;if("none"!==_.elevationType&&!a||"none"===_.elevationType&&a)continue;e.prepareDrawTile();const m=[...s],g=e.shadowRenderer,v="road"===_.elevationType&&!!g&&g.enabled;let w=[0,0,0];if(v){const t=e.style.directionalLight,i=e.style.ambientLight;t&&i&&(w=Oh(e.style,t,i)),m.push("RENDER_SHADOWS","DEPTH_TEXTURE","NORMAL_OFFSET")}const T=_.programConfigurations.get(i.id);let S=!1;if(L&&o.imageAtlas){const e=Vs.from(L),t=e.getPrimary().scaleSelf(b).toString(),i=o.imageAtlas.patternPositions.get(t),s=e.getSecondary(),r=s?o.imageAtlas.patternPositions.get(s.scaleSelf(b).toString()):null;S=!!i&&!!r,i&&T.setConstantPatternPositions(i,r)}D>0&&(S||T.getPatternTransitionVertexBuffer("line-pattern"))&&m.push("LINE_PATTERN_TRANSITION");const R=e.isTileAffectedByFog(u),B=e.getOrCreateProgram(F,{config:T,defines:m,overrideFog:R});if(!A&&I&&C&&o.lineAtlas){const e=o.lineAtlas.getDash(I,C);e&&T.setConstantPatternPositions(e)}v&&g.setupShadows(o.tileID.toUnwrapped(),B,"vector-tile");let[N,U]=i.paint.get("line-trim-offset");if("round"===C||"square"===C){const e=1;N!==U&&(0===N&&(N-=e),1===U&&(U+=e))}const j=x?u.projMatrix:null,G=h?1/_.tileToMeter/ze(o,1,e.transform.zoom):1,V=h?1/_.tileToMeter/ze(o,1,Math.floor(e.transform.zoom)):1,H=A?Hs(e,o,i,j,b,G,V,[N,U],w,D):qs(e,o,i,j,_.lineClipsArray.length,b,G,V,[N,U],w);if(M){const o=_.gradients[i.id];let s=o.texture;if(i.gradientVersion!==o.version){let r=256;if(i.stepInterpolant){const i=t.getSource().maxzoom,o=u.canonical.z===i?Math.ceil(1<<e.transform.maxZoom-u.canonical.z):1;r=Fe(Ws(_.maxLineLength/we*1024*o),256,p.maxTextureSize)}o.gradient=Zs({expression:i.gradientExpression(),evaluationKey:"lineProgress",resolution:r,image:o.gradient||void 0,clips:_.lineClipsArray}),o.texture?o.texture.update(o.gradient):o.texture=new z(p,o.gradient,f.RGBA8),o.version=i.gradientVersion,s=o.texture}p.activeTexture.set(f.TEXTURE1),s.bind(i.stepInterpolant?f.NEAREST:f.LINEAR,f.CLAMP_TO_EDGE)}E&&(p.activeTexture.set(f.TEXTURE0),o.lineAtlasTexture&&o.lineAtlasTexture.bind(f.LINEAR,f.REPEAT),T.updatePaintBuffers()),A&&(p.activeTexture.set(f.TEXTURE0),o.imageAtlasTexture&&o.imageAtlasTexture.bind(f.LINEAR,f.CLAMP_TO_EDGE),T.updatePaintBuffers()),a&&!d&&e.terrain.setupElevationDraw(o,B),e.uploadCommonUniforms(p,B,u.toUnwrapped());const q=t=>{null!=k&&(k.value=O*l),B.draw(e,f.TRIANGLES,r,t,y,fh.disabled,H,i.id,_.layoutVertexBuffer,_.indexBuffer,_.segments,i.paint,e.transform.zoom,T,[_.layoutVertexBuffer2,_.patternVertexBuffer,_.zOffsetVertexBuffer]),null!=k&&(k.value=O)};if(P&&!a){const t=e.stencilModeForClipping(u).ref;0===t&&x&&p.clear({stencil:0});const i={func:f.EQUAL,mask:255};H.u_alpha_discard_threshold=.8,q(new uh(i,t,255,f.KEEP,f.KEEP,f.INVERT)),H.u_alpha_discard_threshold=0,q(new uh(i,t,255,f.KEEP,f.KEEP,f.KEEP))}else H.u_alpha_discard_threshold=P&&a&&c?.8:0,q(a?n:e.stencilModeForClipping(u))}};let U=e.depthModeForSublayer(0,hh.ReadOnly);const j=new hh(e.depthOcclusion?f.GREATER:f.LEQUAL,hh.ReadOnly,e.depthRangeFor3D);if(i.hasNonElevatedBuckets){const t=!x&&e.terrain;0!==l&&t?u(`Occlusion opacity for layer ${i.id} is supported on terrain only if the layer has line-z-offset enabled.`):t?u(`Cannot render non-elevated lines in immediate mode when terrain is enabled. Layer: ${i.id}.`):N(o,B,U,uh.disabled,!1,!0)}if(i.hasElevatedBuckets){"hd-road-markup"===c?_||(U=j,B.push("ELEVATED_ROADS")):(B.push("ELEVATED"),U=j,g&&B.push(v?"CROSS_SLOPE_HORIZONTAL":"CROSS_SLOPE_VERTICAL"),d&&B.push("ELEVATION_REFERENCE_SEA"));const t=P?e.stencilModeFor3D():uh.disabled;e.forceTerrainMode=!0,N(o,B,U,t,!0,!0),P&&N(o,B,U,t,!0,!1),e.forceTerrainMode=!1}P&&(e.resetStencilClippingMasks(),x&&p.clear({stencil:0})),0===l||e.depthOcclusion||x||e.layersWithOcclusionOpacity.push(e.currentLayer)},fill:function(e,t,i,o){const s=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===s.constantOr(Te.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:o,colorMode:a,elevationType:h,terrainEnabled:d,pass:c};if("shadow"===e.renderPass)return void(e.shadowRenderer&&"road"===h&&!d&&function(e){const{painter:t,sourceCache:i,layer:o,coords:s}=e,r=t.context.gl,n=e.painter.shadowRenderer;for(const e of s){const s=i.getTile(e),a=s.getBucket(o);if(!a)continue;const l=a.elevatedStructures;if(!l)continue;if(!l.shadowCasterSegments||0===l.shadowCasterSegments.segments[0].primitiveLength)continue;t.prepareDrawTile();const c=a.bufferData.programConfigurations.get(o.id),h=t.isTileAffectedByFog(e),d=t.getOrCreateProgram("elevatedStructuresDepth",{config:c,overrideFog:h}),u=n.calculateShadowPassMatrixFromTile(s.tileID.toUnwrapped());t.uploadCommonUniforms(t.context,d,e.toUnwrapped());const _={u_matrix:u,u_depth_bias:0};d.draw(t,r.TRIANGLES,n.getShadowPassDepthMode(),uh.disabled,n.getShadowPassColorMode(),fh.disabled,_,o.id,l.vertexBuffer,l.indexBuffer,l.shadowCasterSegments,o.paint,t.transform.zoom,c)}}(u));const _="mrt-fallback"===e.emissiveMode;if("offset"!==h){if(w_(u,!1,_),"road"===h){const s=!d&&"translucent"===e.renderPass;s&&b_(e,t,i,o,"geometry"),w_(u,!0,_,uh.disabled),s&&function(e){const{painter:t,sourceCache:i,layer:o,coords:s,colorMode:r}=e,n=t.context.gl,a=e.painter.shadowRenderer,l=!!a&&a.enabled,c=new hh(t.context.gl.LEQUAL,hh.ReadOnly,t.depthRangeFor3D);let h=[0,0,0];if(l){const e=t.style.directionalLight,i=t.style.ambientLight;e&&i&&(h=Oh(t.style,e,i))}const d=e=>{for(const d of s){const s=i.getTile(d),u=s.getBucket(o);if(!u)continue;const _=u.elevatedStructures;if(!_)continue;let p,f;if(e?(p=_.renderableBridgeSegments,f=_.bridgeProgramConfigurations.get(o.id)):(p=_.renderableTunnelSegments,f=_.tunnelProgramConfigurations.get(o.id)),!p||0===p.segments[0].primitiveLength)continue;f.updatePaintBuffers(),t.prepareDrawTile();const m=t.isTileAffectedByFog(d),g=[];l&&g.push("RENDER_SHADOWS","DEPTH_TEXTURE","NORMAL_OFFSET");const v=t.getOrCreateProgram("elevatedStructures",{config:f,overrideFog:m,defines:g}),y=t.translatePosMatrix(d.projMatrix,s,o.paint.get("fill-translate"),o.paint.get("fill-translate-anchor"));l&&a.setupShadows(s.tileID.toUnwrapped(),v,"vector-tile");const x=Fu(y,h);t.uploadCommonUniforms(t.context,v,d.toUnwrapped()),v.draw(t,n.TRIANGLES,c,uh.disabled,r,fh.backCCW,x,o.id,_.vertexBuffer,_.indexBuffer,p,o.paint,t.transform.zoom,f,[_.vertexBufferNormal])}};d(!0),d(!1)}(u)}}else w_(u,!1,_,e.stencilModeFor3D())},"fill-extrusion":function(e,t,i,o){const s=i.paint.get("fill-extrusion-opacity"),r=e.context,n=r.gl,a=e.terrain,l=a&&a.renderingToTexture;if(0===s)return;const c="mrt-fallback"===e.emissiveMode,h=e.conflationActive&&e.style.isLayerClipped(i,t.getSource()),d=e.style.order.indexOf(i.fqid);if(h&&function(e,t,i,o,s){for(const r of o){const o=t.getTile(r).getBucket(i);o&&(o.updateReplacement(r,e.replacementSource,s),o.uploadCentroid(e.context))}}(e,t,i,o,d),a||h)for(const s of o){const o=t.getTile(s).getBucket(i);o&&I_(e.context,t,s,o,i,a,h)}if("shadow"===e.renderPass&&e.shadowRenderer){const r=e.shadowRenderer;if(a&&s<.65&&i._transitionablePaint._values["fill-extrusion-opacity"].value.expression instanceof _e)return;const n=r.getShadowPassDepthMode(),l=r.getShadowPassColorMode();T_(e,t,i,o,n,uh.disabled,l,h)}else if("translucent"===e.renderPass){const d=!i.paint.get("fill-extrusion-pattern").constantOr(1),u=i.paint.get("fill-extrusion-color").constantOr(Te.white);if(!l&&0!==u.a){const r=new hh(e.context.gl.LEQUAL,hh.ReadWrite,e.depthRangeFor3D);1===s&&d?T_(e,t,i,o,r,uh.disabled,ch.unblended,h):(T_(e,t,i,o,r,uh.disabled,ch.disabled,h),T_(e,t,i,o,r,e.stencilModeFor3D(),e.colorModeForRenderPass(),h),e.resetStencilClippingMasks())}if(e.style.enable3dLights()&&d&&(!a&&"globe"!==e.transform.projection.name||l)){const s=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=(e,t,i)=>(1-i)*e+i*t,y=new E_;y.translate=i.paint.get("fill-extrusion-translate"),y.translateAnchor=i.paint.get("fill-extrusion-translate-anchor"),y.edgeRadius=i.layout.get("fill-extrusion-edge-radius"),y.cutoffFadeRange=i.paint.get("fill-extrusion-cutoff-fade-range");const x=r=>{const a=e.depthModeForSublayer(1,hh.ReadOnly,n.LEQUAL,!0),l=i.paint.get(r?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),c=v(.1,3,l),p=e._showOverdrawInspector;if(!p){const l=new uh({func:n.ALWAYS,mask:255},255,255,n.KEEP,n.KEEP,n.REPLACE),p=new ch([n.ONE,n.ONE,n.ONE,n.ONE],Te.transparent,[!1,!1,!1,!0],n.MIN);S_(y,e,t,i,o,a,l,p,fh.disabled,r,"sdf",s,d,u,_,f,c,h,!1)}{const l=p?uh.disabled:new uh({func:n.EQUAL,mask:255},255,255,n.KEEP,n.DECR,n.DECR),m=p?e.colorModeForRenderPass():new ch([n.ONE_MINUS_DST_ALPHA,n.DST_ALPHA,n.ONE,n.ONE],Te.transparent,[!0,!0,!0,!0]);S_(y,e,t,i,o,a,l,m,fh.disabled,r,"color",s,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 z(r,new T({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,hh.ReadOnly,n.LEQUAL,!1),g=i.paint.get(r?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),x=v(.1,3,g);{const l=new ch([n.ONE,n.ONE,n.ONE,n.ONE],Te.transparent,[!1,!1,!1,!0]);S_(y,e,t,i,o,m,uh.disabled,l,fh.disabled,r,"clear",s,d,u,_,f,x,h,a)}{const l=new uh({func:n.ALWAYS,mask:255},255,255,n.KEEP,n.KEEP,n.REPLACE),c=new ch([n.ONE,n.ONE,n.ONE,n.ONE],Te.transparent,[!1,!1,!1,!0],n.MIN);S_(y,e,t,i,o,m,l,c,fh.disabled,r,"sdf",s,d,u,_,f,x,h,a)}c&&!r&&(p=l());{const l=r?n.ZERO:n.ONE_MINUS_DST_ALPHA,c=new uh({func:n.EQUAL,mask:255},255,255,n.KEEP,n.DECR,n.DECR),p=new ch([l,n.DST_ALPHA,n.ONE_MINUS_DST_ALPHA,n.ZERO],Te.transparent,[!0,!0,!0,!0]);S_(y,e,t,i,o,m,c,p,fh.disabled,r,"color",s,d,u,_,f,x,h,a)}if(!c||r){const l=new ch([n.ONE,n.ONE,n.ONE,r?n.ZERO:n.ONE],Te.transparent,[!1,!1,!1,!0],r?n.FUNC_ADD:n.MAX);S_(y,e,t,i,o,m,uh.disabled,l,fh.disabled,r,"clear",s,d,u,_,f,x,h,a,p)}else{n.drawBuffers([n.NONE,n.COLOR_ATTACHMENT1]);const l=new uh({func:n.EQUAL,mask:255},254,255,n.KEEP,n.DECR,n.DECR),c=new ch([n.ONE,n.ONE,n.ONE,n.ONE],Te.transparent,[!0,!1,!1,!1],n.MAX);S_(y,e,t,i,o,m,l,c,fh.disabled,r,"emissive",s,d,u,_,f,x,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&&x(!0),g&&x(!1),(m||g)&&e.resetStencilClippingMasks()}}},building:function(e,t,i,o){e.currentLayer<e.firstLightBeamLayer&&(e.firstLightBeamLayer=e.currentLayer);const s=i.paint.get("building-ambient-occlusion-ground-intensity"),r=i.paint.get("building-ambient-occlusion-ground-radius"),n=i.paint.get("building-ambient-occlusion-ground-attenuation"),a=i.paint.get("building-opacity");if(a<=0)return;let l=s>0&&r>0,c=!0;const h=i.paint.get("building-vertical-scale");if(h<=0)return;e.shadowRenderer||(c=!1);const d=e.conflationActive&&e.style.isLayerClipped(i,t.getSource()),u=e.style.order.indexOf(i.fqid);if(function(e,t,i,o,s,r){for(const n of r){const r=t.getTile(n).getBucket(i);r&&(s&&r.updateReplacement(n,e.replacementSource,o),r.uploadUpdatedIndexBuffer(e.context))}}(e,t,i,u,d,o),function(e,t,i,o){for(const s of o){const o=t.getTile(s).getBucket(i);o&&o.needsEvaluation()&&o.uploadUpdatedColorBuffer(e.context)}}(e,t,i,o),i.resetLayerRenderingStats(e),e.shadowRenderer&&(e.shadowRenderer.useNormalOffset=!0),"shadow"===e.renderPass&&e.shadowRenderer){const s=e.shadowRenderer,r=[],n=s.getShadowPassDepthMode();L_({painter:e,source:t,layer:i,coords:o,defines:r,blendMode:s.getShadowPassColorMode(),depthMode:n,opacity:a,verticalScale:h,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}else if("translucent"===e.renderPass){let u=["HAS_ATTRIBUTE_a_part_color_emissive","LIGHTING_3D_MODE"];c&&(u=u.concat("RENDER_SHADOWS","DEPTH_TEXTURE")),e.shadowRenderer&&e.shadowRenderer.useNormalOffset&&(u=u.concat("NORMAL_OFFSET"));const _=i.paint.get("building-facade-emissive-chance"),p=i.paint.get("building-ambient-occlusion-intensity"),f=i.paint.get("building-flood-light-intensity"),m="none"===i.paint.get("building-flood-light-color-use-theme").constantOr("default"),g=i.paint.get("building-flood-light-color").toNonPremultipliedRenderColor(m?null:i.lut).toArray01().slice(0,3),v=i.paint.get("building-flood-light-ground-attenuation"),y=f>0,x=new hh(e.context.gl.LEQUAL,hh.ReadWrite,e.depthRangeFor3D);a<1&&L_({painter:e,source:t,layer:i,coords:o,defines:u,blendMode:ch.disabled,depthMode:x,opacity:a,verticalScale:h,facadeEmissiveChance:_,facadeAOIntensity:p,floodLightIntensity:f,floodLightColor:g,depthOnly:!0});const b=e.colorModeForRenderPass();L_({painter:e,source:t,layer:i,coords:o,defines:u,blendMode:b,depthMode:x,opacity:a,verticalScale:h,facadeEmissiveChance:_,facadeAOIntensity:p,floodLightIntensity:f,floodLightColor:g}),l&&O_(e,t,i,o,!0,a,s,r,f,g,n,d),y&&O_(e,t,i,o,!1,a,s,r,f,g,v,d)}else if("light-beam"===e.renderPass){const s=["HAS_ATTRIBUTE_a_part_color_emissive","HAS_ATTRIBUTE_a_bloom_attenuation"],r=new hh(e.context.gl.LEQUAL,hh.ReadOnly,e.depthRangeFor3D);L_({painter:e,source:t,layer:i,coords:o,defines:s,blendMode:ch.alphaBlended,depthMode:r,opacity:a,verticalScale:h,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}e.shadowRenderer&&(e.shadowRenderer.useNormalOffset=!1),e.resetStencilClippingMasks()},hillshade:function(e,t,i,o){if("offscreen"!==e.renderPass&&"translucent"!==e.renderPass)return;if(e.style.disableElevatedTerrain)return;const s=e.context,r=e.terrain&&e.terrain.renderingToTexture,[n,a]="translucent"!==e.renderPass||r?[{},o]:e.stencilConfigForOverlap(o);for(const o of a){const s=t.getTile(o);if(s.needsHillshadePrepare&&"offscreen"===e.renderPass)Td(e,s,i);else if("translucent"===e.renderPass){const t=e.depthModeForSublayer(0,hh.ReadOnly),a=i.paint.get("hillshade-emissive-strength"),l=e.colorModeForDrapableLayerRenderPass(a),c=r&&e.terrain?e.terrain.stencilModeForRTTOverlap(o):n[o.overscaledZ];bd(e,o,s,i,t,c,l)}}s.viewport.set([0,0,e.width,e.height]),e.resetStencilClippingMasks()},raster:function(e,t,i,o,s,r){if("translucent"!==e.renderPass)return;if(0===i.paint.get("raster-opacity"))return;const n="globe"===e.transform.projection.name,a=0!==i.paint.get("raster-elevation"),l=a&&n;if(e.renderElevatedRasterBackface&&!l)return;const c=e.context,h=c.gl,d=t.getSource(),u=function(e,t,i,o,s){const r=t.paint.get("raster-color"),n="raster-array"===e.type,a=[],l=t.paint.get("raster-resampling"),c=t.paint.get("raster-color-mix");let h=t.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,!h&&e.rasterLayers)){const i=e.rasterLayers.find((({id:e})=>e===t.sourceLayer));i&&i.fields&&i.fields.range&&(h=i.fields.range)}if(h=h||[0,1],r){a.push("RASTER_COLOR"),i.activeTexture.set(o.TEXTURE2),t.updateColorRamp(h);let e=t.colorRampTexture;e||(e=t.colorRampTexture=new z(i,t.colorRamp,o.RGBA8)),e.bind(o.LINEAR,o.CLAMP_TO_EDGE)}return s&&a.push("USE_MRT1"),{mix:d,range:h,offset:u,defines:a,resampling:_}}(d,i,c,h,e.terrain&&e.terrain.renderingToTexture&&"mrt-fallback"===e.emissiveMode);if(d instanceof it&&!o.length&&!n)return;const _=i.paint.get("raster-emissive-strength"),p=e.colorModeForDrapableLayerRenderPass(_),f=e.terrain&&e.terrain.renderingToTexture,m=!e.options.moving,g="nearest"===i.paint.get("raster-resampling")?h.NEAREST:h.LINEAR;if(d instanceof it&&!o.length&&(d.onNorthPole||d.onSouthPole)){const o=a?e.stencilModeFor3D():uh.disabled;return void M_(!!d.onNorthPole,null,e,t,i,_,u,fh.disabled,o)}if(!o.length)return;const[v,y]=d instanceof it||f?[{},o]:e.stencilConfigForOverlap(o),x=y[y.length-1].overscaledZ;l&&u.defines.push("PROJECTION_GLOBE_VIEW"),a&&u.defines.push("RENDER_CUTOFF");const b=(o,s,y)=>{for(const b of o){const o=b.toUnwrapped(),w=t.getTile(b);if(f&&(!w||!w.hasData()))continue;c.activeTexture.set(h.TEXTURE0);const T=F_(w,d,i,u);if(!T||!T.texture)continue;const{texture:E,mix:S,offset:I,tileSize:C,buffer:R}=T;let A,D;f?(A=hh.disabled,D=b.projMatrix):a?(A=new hh(h.LEQUAL,hh.ReadWrite,e.depthRangeFor3D),D=n?Float32Array.from(e.transform.expandedFarZProjMatrix):e.transform.calculateProjMatrix(o,m)):(A=e.depthModeForSublayer(b.overscaledZ-x,1===i.paint.get("raster-opacity")?hh.ReadWrite:hh.ReadOnly,h.LESS),D=e.transform.calculateProjMatrix(o,m));const L=e.terrain&&f?e.terrain.stencilModeForRTTOverlap(b):v[b.overscaledZ],O=r?0:i.paint.get("raster-fade-duration");w.registerFadeDuration(O);const P=t.findLoadedParent(b,0),M=mu(w,P,t,e.transform,O);let z,F;!M.isFading&&w.refreshedUponExpiration&&(w.refreshedUponExpiration=!1),e.terrain&&e.terrain.prepareDrawTile(),c.activeTexture.set(h.TEXTURE0),E.bind(g,h.CLAMP_TO_EDGE),c.activeTexture.set(h.TEXTURE1),P?(P.texture&&P.texture.bind(g,h.CLAMP_TO_EDGE),z=Math.pow(2,P.tileID.overscaledZ-w.tileID.overscaledZ),F=[w.tileID.canonical.x*z%1,w.tileID.canonical.y*z%1]):E.bind(g,h.CLAMP_TO_EDGE),"useMipmap"in E&&c.extTextureFilterAnisotropic&&e.transform.pitch>20&&h.texParameterf(h.TEXTURE_2D,c.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,c.extTextureFilterAnisotropicMax);const B=e.transform;let k;const N=a?z_(B):[0,0,0,0];let U,j,G,V,H,q=0;if(l&&d instanceof it&&d.coordinates.length>3)U=Float32Array.from(Dt(bs(new oo(0,0,0)))),j=Float32Array.from(B.globeMatrix),G=Float32Array.from(ms(B)),V=[Ge(B.center.lng),qe(B.center.lat)],k=d.elevatedGlobePerspectiveTransform,H=d.elevatedGlobeGridMatrix||new Float32Array(9);else if(l){const e=vs(b.canonical);q=ys(e.getCenter().lat),U=Float32Array.from(Dt(bs(b.canonical))),j=Float32Array.from(B.globeMatrix),G=Float32Array.from(ms(B)),V=[Ge(B.center.lng),qe(B.center.lat)],k=[0,0],H=Float32Array.from(xs(b.canonical,e,q,B.worldSize/B._pixelsPerMercatorPixel))}else k=d instanceof it?d.perspectiveTransform:[0,0],U=new Float32Array(16),j=new Float32Array(9),G=new Float32Array(16),V=[0,0],H=new Float32Array(9);const Z=Wu(D,U,j,G,H,F||[0,0],ye(e.transform.zoom),V,N,z||1,M,i,k,a?i.paint.get("raster-elevation"):0,2,S,I,u.range,C,R,_),W=e.isTileAffectedByFog(b),$=e.getOrCreateProgram("raster",{defines:u.defines,overrideFog:W});if(e.uploadCommonUniforms(c,$,o),d instanceof it){const t=d.elevatedGlobeVertexBuffer,o=d.elevatedGlobeIndexBuffer;if(f||!n)d.boundsBuffer&&d.boundsSegments&&$.draw(e,h.TRIANGLES,A,uh.disabled,p,fh.disabled,Z,i.id,d.boundsBuffer,e.quadTriangleIndexBuffer,d.boundsSegments);else if(t&&o){const r=B.zoom<=Ro?d.elevatedGlobeSegments:d.getSegmentsForLongitude(B.center.lng);r&&$.draw(e,h.TRIANGLES,A,uh.disabled,p,s,Z,i.id,t,o,r)}}else if(l){A=new hh(h.LEQUAL,hh.ReadOnly,e.depthRangeFor3D);const t=e.globeSharedBuffers;if(t){const[o,r,n]=t.getGridBuffers(q,!1);$.draw(e,h.TRIANGLES,A,y||L,e.colorModeForRenderPass(),s,Z,i.id,o,r,n)}}else{const{tileBoundsBuffer:t,tileBoundsIndexBuffer:o,tileBoundsSegments:s}=e.getTileBoundsBuffers(w);$.draw(e,h.TRIANGLES,A,L,p,fh.disabled,Z,i.id,t,o,s)}}if(!(d instanceof it)&&l)for(const r of o){const o=r.canonical.y===(1<<r.canonical.z)-1;0===r.canonical.y&&M_(!0,r,e,t,i,_,u,s,y||uh.disabled),o&&M_(!1,r,e,t,i,_,u,s===fh.frontCW?fh.backCW:fh.frontCW,y||uh.disabled)}};l?b(y,e.renderElevatedRasterBackface?fh.backCW:fh.frontCW,e.stencilModeFor3D()):b(y,fh.disabled,void 0),e.resetStencilClippingMasks()},"raster-particle":function(e,t,i,o,s,r){"offscreen"===e.renderPass&&function(e,t,i,o){if(!o.length)return;const s=e.context,r=s.gl,n=t.getSource();if(!(n instanceof Al))return;const a=Math.ceil(Math.sqrt(i.paint.get("raster-particle-count")));let l=i.particlePositionRGBAImage;if(!l||l.width!==a){const e=function(e){const t=e*e,i=new Uint8Array(4*t),o=function(e){return e|=0,e=Math.imul(2747636419^e,2654435769),e=Math.imul(e^e>>>16,2654435769),((e=Math.imul(e^e>>>16,2654435769))>>>0)/4294967296},s=1/1.1;for(let e=0;e<t;e++){const t=s*(o(2*e+0)+Xu),r=s*(o(2*e+1)+Xu),n=255*t%1,a=255*r%1,l=n,c=r-a/255,h=a;i[4*e+0]=255*(t-n/255),i[4*e+1]=255*l,i[4*e+2]=255*c,i[4*e+3]=255*h}return i}(a);l=i.particlePositionRGBAImage=new T({width:a,height:a},e)}let c=i.particleFramebuffer;c?c.width!==a&&(c.destroy(),c=i.particleFramebuffer=s.createFramebuffer(a,a,1,null)):c=i.particleFramebuffer=s.createFramebuffer(a,a,1,null);const h=[];for(const e of o){const o=t.getTile(e);if(!(o instanceof $l))continue;const r=N_(o,n,i);if(!r)continue;const c=[o.tileSize,o.tileSize];let d=i.tileFramebuffer;d||(d=i.tileFramebuffer=s.createFramebuffer(c[0],c[1],1,null));let u=o.rasterParticleState;u||(u=o.rasterParticleState=new k_(s,e,c,l));const _=u.update(i.lastInvalidatedAt);u.particleTextureDimension!==a&&u.updateParticleTexture(e,l);const p=u.targetColorTexture;u.targetColorTexture=u.backgroundColorTexture,u.backgroundColorTexture=p;const f=u.particleTexture0;u.particleTexture0=u.particleTexture1,u.particleTexture1=f,h.push([e,r,u,_])}if(0===h.length)return;const d=w.now(),u=i.previousDrawTimestamp?.001*(d-i.previousDrawTimestamp):.0167;if(i.previousDrawTimestamp=d,i.hasColorMap()){s.activeTexture.set(r.TEXTURE0+2);let e=i.colorRampTexture;e||(e=i.colorRampTexture=new z(s,i.colorRamp,r.RGBA8)),e.bind(r.LINEAR,r.CLAMP_TO_EDGE)}s.bindFramebuffer.set(i.tileFramebuffer.framebuffer),function(e,t,i){const o=e.context,s=o.gl,r=t.tileFramebuffer;o.activeTexture.set(s.TEXTURE0);const n={u_texture:0,u_opacity:1.05*(l=t.paint.get("raster-particle-fade-opacity-factor"))/(l+.05)},a=e.getOrCreateProgram("rasterParticleTexture",{defines:[],overrideFog:!1});var l;for(const l of i){const[,,i,c]=l;r.colorAttachment0.set(i.targetColorTexture.texture),o.viewport.set([0,0,r.width,r.height]),o.clear({color:Te.transparent}),c&&(i.backgroundColorTexture.bind(s.NEAREST,s.CLAMP_TO_EDGE),a.draw(e,s.TRIANGLES,hh.disabled,uh.disabled,ch.alphaBlended,fh.disabled,n,t.id,e.viewportBuffer,e.quadTriangleIndexBuffer,e.viewportSegments))}}(e,i,h),function(e,t,i,o){const s=e.context,r=s.gl,n=i.tileFramebuffer,a="globe"===e.transform.projection.name,l=i.paint.get("raster-particle-max-speed");for(const c of o){const[o,h,d]=c;s.activeTexture.set(r.TEXTURE0+0),h.texture.bind(r.LINEAR,r.CLAMP_TO_EDGE),n.colorAttachment0.set(d.targetColorTexture.texture);const u=e.getOrCreateProgram("rasterParticleDraw",{defines:h.defines,overrideFog:!1});s.activeTexture.set(r.TEXTURE0+1);const _=h.scalarData?[]:[0,1,2,3].map((e=>Xs[e](o)));_.push(o);const p=o.canonical.x,f=o.canonical.y;for(const s of _){const n=t.getTile(a?s.wrapped():s);if(!n)continue;const c=n.rasterParticleState;if(!c)continue;const d=s.canonical.x+(1<<s.canonical.z)*(s.wrap-o.wrap),_=s.canonical.y;c.particleTexture0.bind(r.NEAREST,r.CLAMP_TO_EDGE);const m=Ku(1,c.particleTexture0.size[0],[d-p,_-f],0,h.texture.size,2,l,h.textureOffset,h.scale,h.offset);u.draw(e,r.POINTS,hh.disabled,uh.disabled,ch.alphaBlended,fh.disabled,m,i.id,c.particleIndexBuffer,void 0,c.particleSegment)}}}(e,t,i,h),s.bindFramebuffer.set(i.particleFramebuffer.framebuffer),function(e,t,i,o){const s=e.context,r=s.gl,n=t.paint.get("raster-particle-max-speed"),a=o*t.paint.get("raster-particle-speed-factor")*.15,l=function(e){return Math.pow(e,6)}(.01+1*t.paint.get("raster-particle-reset-rate-factor")),c=t.particleFramebuffer;s.viewport.set([0,0,c.width,c.height]);for(const o of i){const[,i,h]=o;s.activeTexture.set(r.TEXTURE0+0),i.texture.bind(r.LINEAR,r.CLAMP_TO_EDGE),s.activeTexture.set(r.TEXTURE0+1);const d=h.particleTexture0;d.bind(r.NEAREST,r.CLAMP_TO_EDGE);const u=Qu(1,d.size[0],0,i.texture.size,n,a,l,i.textureOffset,i.scale,i.offset);c.colorAttachment0.set(h.particleTexture1.texture),s.clear({color:Te.transparent}),e.getOrCreateProgram("rasterParticleUpdate",{defines:i.defines}).draw(e,r.TRIANGLES,hh.disabled,uh.disabled,ch.unblended,fh.disabled,u,t.id,e.viewportBuffer,e.quadTriangleIndexBuffer,e.viewportSegments)}}(e,i,h,u)}(e,t,i,o),"translucent"===e.renderPass&&(function(e,t,i,o,s){const r=e.context,n=r.gl,a=t.getSource().tileSize,l=5*(1-me(co,co+1,e.transform.zoom))*a+i.paint.get("raster-particle-elevation"),c=!e.options.moving,h="globe"===e.transform.projection.name;if(!o.length)return;const[d,u]=e.stencilConfigForOverlap(o),_=[];h&&_.push("PROJECTION_GLOBE_VIEW");const p=e.stencilModeFor3D();for(const o of u){const s=o.toUnwrapped(),a=t.getTile(o);if(!a.rasterParticleState)continue;const u=a.rasterParticleState,f=100;a.registerFadeDuration(f);const m=t.findLoadedParent(o,0),g=mu(a,m,t,e.transform,f);let v,y;e.terrain&&e.terrain.prepareDrawTile(),r.activeTexture.set(n.TEXTURE0),u.targetColorTexture.bind(n.LINEAR,n.CLAMP_TO_EDGE),r.activeTexture.set(n.TEXTURE1),m&&m.rasterParticleState?(m.rasterParticleState.targetColorTexture.bind(n.LINEAR,n.CLAMP_TO_EDGE),v=Math.pow(2,m.tileID.overscaledZ-a.tileID.overscaledZ),y=[a.tileID.canonical.x*v%1,a.tileID.canonical.y*v%1]):u.targetColorTexture.bind(n.LINEAR,n.CLAMP_TO_EDGE);const x=h?Float32Array.from(e.transform.expandedFarZProjMatrix):e.transform.calculateProjMatrix(s,c),b=e.transform,w=U_(b),T=vs(o.canonical),E=ys(T.getCenter().lat);let S,I,C,R,A;h?(S=Float32Array.from(Dt(bs(o.canonical))),I=Float32Array.from(b.globeMatrix),C=Float32Array.from(ms(b)),R=[Ge(b.center.lng),qe(b.center.lat)],A=Float32Array.from(xs(o.canonical,T,E,b.worldSize/b._pixelsPerMercatorPixel))):(S=new Float32Array(16),I=new Float32Array(9),C=new Float32Array(16),R=[0,0],A=new Float32Array(9));const D=Yu(x,S,I,C,A,y||[0,0],ye(e.transform.zoom),R,w,v||1,g,l),L=e.isTileAffectedByFog(o),O=e.getOrCreateProgram("rasterParticle",{defines:_,overrideFog:L});if(e.uploadCommonUniforms(r,O,s),h){const t=new hh(n.LEQUAL,hh.ReadOnly,e.depthRangeFor3D),o=0,s=e.globeSharedBuffers;if(s){const[r,a,l]=s.getGridBuffers(E,0!==o);O.draw(e,n.TRIANGLES,t,p,ch.alphaBlended,e.renderElevatedRasterBackface?fh.frontCCW:fh.backCCW,D,i.id,r,a,l)}}else{const t=e.depthModeForSublayer(0,hh.ReadOnly),s=d[o.overscaledZ],{tileBoundsBuffer:r,tileBoundsIndexBuffer:l,tileBoundsSegments:c}=e.getTileBoundsBuffers(a);O.draw(e,n.TRIANGLES,t,s,ch.alphaBlended,fh.disabled,D,i.id,r,l,c)}}e.resetStencilClippingMasks()}(e,t,i,o),e.style.map.triggerRepaint())},background:function(e,t,i,o){const s=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(v.from(_.toString()),i.scope,e.style.getLut(i.scope)),!p)return}const f=!_&&1===s.a&&1===n&&e.opaquePassEnabledForLayer()?"opaque":"translucent";if(e.renderPass!==f)return;const m=uh.disabled,g=e.depthModeForSublayer(0,"opaque"===f?hh.ReadWrite:hh.ReadOnly),y=e.colorModeForDrapableLayerRenderPass(a),x=_?"backgroundPattern":"background";let b,w=o;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&&"mrt-fallback"===e.emissiveMode&&T.push("USE_MRT1"),l){const t=e.getOrCreateProgram(x,{overrideFog:!1,overrideRtt:!0,defines:T}),o=new Float32Array(Zt([])),c=new Ke(0,0,0,0,0),d=_?i_(o,a,n,e,0,i.scope,p,l,{tileID:c,tileSize:u}):t_(o,a,n,s.toPremultipliedRenderColor(r?null:i.lut));t.draw(e,h.TRIANGLES,g,m,y,fh.disabled,d,i.id,e.viewportBuffer,e.quadTriangleIndexBuffer,e.viewportSegments)}else for(const f of w){const v=e.isTileAffectedByFog(f),w=e.getOrCreateProgram(x,{overrideFog:v,defines:T}),E=f.toUnwrapped(),S=o?f.projMatrix:e.transform.calculateProjMatrix(E);e.prepareDrawTile();const I=t?t.getTile(f):b?b[f.key]:new Wl(f,u,d.zoom,e),C=_?i_(S,a,n,e,0,i.scope,p,l,{tileID:f,tileSize:u}):t_(S,a,n,s.toPremultipliedRenderColor(r?null:i.lut));e.uploadCommonUniforms(c,w,E);const{tileBoundsBuffer:R,tileBoundsIndexBuffer:A,tileBoundsSegments:D}=e.getTileBoundsBuffers(I);w.draw(e,h.TRIANGLES,g,m,y,fh.disabled,C,i.id,R,A,D)}},sky:function(e,t,i){const o=e._atmosphere?ye(e.transform.zoom):1,s=i.paint.get("sky-opacity")*o;if(0===s)return;const r=e.context,n=i.paint.get("sky-type"),a=new hh(r.gl.LEQUAL,hh.ReadOnly,[0,1]),l=e.frameCounter/1e3%1;"atmosphere"===n?"offscreen"===e.renderPass?i.needsSkyboxCapture(e)&&(function(e,t,i,o){const s=e.context,r=s.gl;let n=t.skyboxFbo;if(!n){n=t.skyboxFbo=s.createFramebuffer(32,32,1,null),t.skyboxGeometry=new ep(s),t.skyboxTexture=s.gl.createTexture(),r.bindTexture(r.TEXTURE_CUBE_MAP,t.skyboxTexture),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAG_FILTER,r.LINEAR);for(let e=0;e<6;++e)r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,r.RGBA,32,32,0,r.RGBA,r.UNSIGNED_BYTE,null)}s.bindFramebuffer.set(n.framebuffer),s.viewport.set([0,0,32,32]);const a=t.getCenter(e,!0),l=e.getOrCreateProgram("skyboxCapture"),c=new Float64Array(16);Zt(c),cr(c,c,.5*-Math.PI),tp(e,t,l,c,a,0),Zt(c),cr(c,c,.5*Math.PI),tp(e,t,l,c,a,1),Zt(c),xo(c,c,.5*-Math.PI),tp(e,t,l,c,a,2),Zt(c),xo(c,c,.5*Math.PI),tp(e,t,l,c,a,3),Zt(c),tp(e,t,l,c,a,4),Zt(c),cr(c,c,Math.PI),tp(e,t,l,c,a,5),s.viewport.set([0,0,e.width,e.height])}(e,i),i.markSkyboxValid(e)):"sky"===e.renderPass&&function(e,t,i,o,s){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,o,s)=>({u_matrix:e,u_sun_direction:t,u_cubemap:0,u_opacity:o,u_temporal_offset:s}))(a.skyboxMatrix,t.getCenter(e,!1),0,o,s);e.uploadCommonUniforms(r,l),l.draw(e,n.TRIANGLES,i,uh.disabled,e.colorModeForRenderPass(),fh.backCW,c,"skybox",t.skyboxGeometry.vertexBuffer,t.skyboxGeometry.indexBuffer,t.skyboxGeometry.segment)}(e,i,a,s,l):"gradient"===n&&"sky"===e.renderPass&&function(e,t,i,o,s){const r=e.context,n=r.gl,a=e.transform,l=e.getOrCreateProgram("skyboxGradient");t.skyboxGeometry||(t.skyboxGeometry=new ep(r)),r.activeTexture.set(n.TEXTURE0);let c=t.colorRampTexture;c||(c=t.colorRampTexture=new z(r,t.colorRamp,n.RGBA8)),c.bind(n.LINEAR,n.CLAMP_TO_EDGE);const h=((e,t,i,o,s)=>({u_matrix:e,u_color_ramp:0,u_center_direction:t,u_radius:Ee(i),u_opacity:o,u_temporal_offset:s}))(a.skyboxMatrix,t.getCenter(e,!1),t.paint.get("sky-gradient-radius"),o,s);e.uploadCommonUniforms(r,l),l.draw(e,n.TRIANGLES,i,uh.disabled,e.colorModeForRenderPass(),fh.backCW,h,"skyboxGradient",t.skyboxGeometry.vertexBuffer,t.skyboxGeometry.indexBuffer,t.skyboxGeometry.segment)}(e,i,a,s,l)},custom:function(e,t,i,o){const s=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)){if("offscreen"===e.renderPass){const t=r.prerender;if(t){if(e.setCustomLayerDefaults(),s.setColorMode(e.colorModeForRenderPass()),"globe"===e.transform.projection.name){const i=e.transform.pointMerc;t.call(r,s.gl,e.transform.customLayerMatrix(),e.transform.getProjection(),e.transform.globeToMercatorMatrix(),ye(e.transform.zoom),[i.x,i.y],e.transform.pixelsPerMeterRatio)}else t.call(r,s.gl,e.transform.customLayerMatrix());s.setDirty(),e.setBaseState()}}else if("translucent"===e.renderPass){if(e.terrain&&e.terrain.renderingToTexture){const t=r.renderToTile;if(t){const i=o[0].canonical,n={x:i.x+o[0].wrap*(r.wrapTileId?0:1<<i.z),y:i.y,z:i.z};s.setDepthMode(hh.disabled),s.setStencilMode(uh.disabled),s.setColorMode(e.colorModeForRenderPass()),e.setCustomLayerDefaults(),t.call(r,s.gl,n),s.setDirty(),e.setBaseState()}return}e.setCustomLayerDefaults(),s.setColorMode(e.colorModeForRenderPass()),s.setStencilMode(uh.disabled);const t="3d"===r.renderingMode?new hh(e.context.gl.LEQUAL,hh.ReadWrite,e.depthRangeFor3D):e.depthModeForSublayer(0,hh.ReadOnly);if(s.setDepthMode(t),"globe"===e.transform.projection.name){const t=e.transform.pointMerc;r.render(s.gl,e.transform.customLayerMatrix(),e.transform.getProjection(),e.transform.globeToMercatorMatrix(),ye(e.transform.zoom),[t.x,t.y],e.transform.pixelsPerMeterRatio)}else r.render(s.gl,e.transform.customLayerMatrix());s.setDirty(),e.setBaseState(),s.bindFramebuffer.set(null)}}else u("Custom layers are not yet supported with this projection. Use mercator or globe to enable usage of custom layers.")},model:function(e,t,i,o){if("opaque"===e.renderPass)return;const s=i.paint.get("model-opacity").constantOr(1),n=i.paint.get("model-elevation-reference"),a="ground"===n,l="ground"===n;if(0===s)return;const c=i.paint.get("model-cast-shadows");if("shadow"===e.renderPass){if(!c)return;if(e.terrain&&s<.65&&i._transitionablePaint._values["model-opacity"].value.expression instanceof _e)return}const h=e.shadowRenderer,d=i.paint.get("model-receive-shadows");h&&(h.useNormalOffset=!0,d||(h.enabled=!1));const _=()=>{h&&(h.useNormalOffset=!0,d||(h.enabled=!0))},p=t.getSource();if("light-beam"===e.renderPass&&"batched-model"!==p.type)return;if("vector"===p.type||"geojson"===p.type)return function(e,t,i,o,s){const r=e.transform,n="globe"===r.projection.name,a=r.getFreeCameraOptions().position;if(!e.modelManager)return;const l=e.modelManager;i.modelManager=l;const c=e.shadowRenderer;if(!i._unevaluatedLayout._values.hasOwnProperty("model-id"))return;const h=i._unevaluatedLayout._values["model-id"],d=Object.assign({},i.layout.get("model-id").parameters),u=e.style.order.indexOf(i.fqid),_=i.paint.get("model-opacity").constantOr(1);for(const p of o){const o=t.getTile(p).getBucket(i);if(!o||o.projection.name!==r.projection.name)continue;const f=o.getModelUris();if(f&&!o.modelsRequested&&(l.addModelsFromBucket(f,s),o.modelsRequested=!0),n)d.zoom=p.overscaledZ;else{const e=yp(p,r);d.zoom=e}const m=h.possiblyEvaluate(d);if(gp(e,o,p),vp.shadowUniformsInitialized=!1,vp.useSingleShadowCascade=!!c&&0===c.getMaxCascadeForTile(p.toUnwrapped()),"shadow"===e.renderPass&&c){if(1===e.currentShadowCascade&&o.isInsideFirstShadowMapFrustum)continue;const t=r.calculatePosMatrix(p.toUnwrapped(),r.worldSize);if(vp.tileMatrix.set(t),vp.shadowTileMatrix=Float32Array.from(c.calculateShadowPassMatrixFromMatrix(t)),vp.aabb.min=[0,0,0],vp.aabb.max[0]=vp.aabb.max[1]=we,vp.aabb.max[2]=0,wp(o,vp,e,i.scope))continue}const g=1<<p.canonical.z,v=[((a.x-p.wrap)*g-p.canonical.x)*we,(a.y*g-p.canonical.y)*we,a.z*g*we];e.conflationActive&&Object.keys(o.instancesPerModel).length>0&&e.style.isLayerClipped(i,t.getSource())&&o.updateReplacement(p,e.replacementSource,u,i.scope)&&(o.uploaded=!1,o.upload(e.context));let y=0;const x=new Array,b=new Array,w=new Array;for(let t in o.instancesPerModel){const r=o.instancesPerModel[t];r.features.length>0&&!n&&(t=m.evaluate(r.features[0].feature,{}));const c=l.getModel(t,s);if(c||l.hasURLBeenRequested(t)||o.modelUris.includes(t)||(o.modelUris.push(t),o.modelsRequested=!1),c&&c.uploaded)if(n){const t=Si([],[a.x,a.y,a.z],e.transform.worldSize);vr(t,t);for(let i=0;i<r.instancedDataArray.length;++i){const s=[0,0,0],n=[1,1,1],a=yr(),l=r.tileCoordinatesForInstance(i),h=r.transformForInstance(i);xr(n,h),br(a,h),wr(s,a);const d=r.translationForInstance(i),u=new tt(0,0);Tr(o.canonical,u,l.x,l.y);const p=$t();Er(p,c,e.transform,u,s,n,d,!0,!1,!1);const f=r.colorForInstance(i),m=Zt([]),g=ir(u.lat,e.transform.zoom),v=Ft([],[1,1,1/g]);Bt(m,m,t),w.push({zScaleMatrix:v,negCameraPosMatrix:m});for(const t of c.nodes)up(e,t,p,e.transform.expandedFarZProjMatrix,y,x,b,c.materialOverrides,_,f);++y}}else for(const t of c.nodes)xp(e,i,t,r,v,p,vp)}if(n)if("shadow"===e.renderPass){for(const t of b)_p(t.mesh,t.nodeModelMatrix,e,i);for(const t of x)_p(t.mesh,t.nodeModelMatrix,e,i)}else mp(e,i,x,b,w)}}(e,t,i,o,dp(e,i)),void _();if(!p.loaded())return;if("batched-model"===p.type)return function(e,t,i,o){i.resetLayerRenderingStats(e);const s=e.context,n=e.transform,a=e.style.fog,l=e.shadowRenderer;if("mercator"!==n.projection.name)return void u(`Drawing 3D landmark models for ${n.projection.name} projection is not yet implemented`);const c=e.transform.getFreeCameraOptions().position,h=Si([],[c.x,c.y,c.z],e.transform.worldSize),d=vr([],h),_=Zt([]),p=ir(n.center.lat,n.zoom),f=Ft([],[1,1,1/p]);Bt(_,_,d);const m=i.paint.get("model-opacity").constantOr(1),g=new hh(s.gl.LEQUAL,hh.ReadWrite,e.depthRangeFor3D),v=new hh(s.gl.LEQUAL,hh.ReadOnly,e.depthRangeFor3D),y=new No([1/0,1/0,1/0],[-1/0,-1/0,-1/0]),x="shadow"===e.renderPass,b=x&&l?l.getCurrentCascadeFrustum():n.getFrustum(n.scaleZoom(n.worldSize)),w=i.paint.get("model-front-cutoff"),T=w[2]<1,E=Sh(e,i.paint.get("model-cutoff-fade-range")),S=i.getLayerRenderingStats();(function(e,t,i,o){const s=e.terrain?e.terrain.exaggeration():0,r=e.transform.zoom;for(const n of o){const o=t.getTile(n).getBucket(i);o&&(o.setFilter(i.filter),e.conflationActive&&o.updateReplacement(n,e.replacementSource),o.evaluateTransform(e,i),e.terrain&&s>0&&o.elevationUpdate(e.terrain,s,n,i.source),o.needsReEvaluation(e,r,i)&&o.evaluate(i))}})(e,t,i,o),function(){let c,d,u;T?(c=o.length-1,d=-1,u=-1):(c=0,d=o.length,u=1);const I=new Float64Array(16),C=eo(),R=new r(0,0);for(let r=c;r!==d;r+=u){const c=o[r],d=t.getTile(c).getBucket(i);if(!d||!d.uploaded)continue;let u=!1;l&&(u=0===l.getMaxCascadeForTile(c.toUnwrapped()));const A=n.calculatePosMatrix(c.toUnwrapped(),n.worldSize),D=d.modelTraits;!x&&T&&(Lt(I,A),fe(C,h,I),R.x=C[0],R.y=C[1]);const L=[];d.setFilter(i.filter);for(const t of d.getNodesInfo()){if(t.hiddenByReplacement)continue;if(!t.node.meshes)continue;const i=t.node;let o=0;e.terrain&&i.elevation&&(o=i.elevation*e.terrain.exaggeration());const s=(()=>{const e=t.aabb;return y.min=[...e.min],y.max=[...e.max],y.min[2]+=o,y.max[2]+=o,fe(y.min,y.min,A),fe(y.max,y.max,A),y})(),r=t.evaluatedScale;if(r[0]<=1&&r[1]<=1&&r[2]<=1&&0===s.intersects(b))continue;if(!x&&T){const e=1/6;t.cameraCollisionOpacity=h[0]>s.min[0]&&h[0]<s.max[0]&&h[1]>s.min[1]&&h[1]<s.max[1]&&h[2]*p<s.max[2]&&i.footprint&&yi(R,i.footprint)?Math.max(t.cameraCollisionOpacity-e,0):Math.min(1,t.cameraCollisionOpacity+e)}const a=[...A],l=1/Bo(c.canonical),d=i.anchor?i.anchor[0]:0,u=i.anchor?i.anchor[1]:0;Bt(a,a,[d*(r[0]-1)+t.evaluatedTranslation[0]*l,u*(r[1]-1)+t.evaluatedTranslation[1]*l,o+t.evaluatedTranslation[2]]),Zi(r,Ir)||vo(a,a,r);const _=Be([],a,i.globalMatrix),f=Be([],n.expandedFarZProjMatrix,_),g=Be([],n.expandedFarZProjMatrix,a),v=ke([],[d,u,o,1],f)[2];i.hidden=!1;let S=m;x||(T&&(S*=t.cameraCollisionOpacity,S*=Ep(a,n,t.aabb,w)),S*=Tp(E,v)),0!==S?L.push({nodeInfo:t,depth:v,opacity:S,wvpForNode:f,wvpForTile:g,nodeModelMatrix:_,tileModelMatrix:a}):i.hidden=!0}x||L.sort(((e,t)=>!T||1===e.opacity&&1===t.opacity?e.depth<t.depth?-1:1:1===e.opacity?-1:1===t.opacity?1:e.depth>t.depth?-1:1));for(const t of L){const o=t.nodeInfo,r=o.node;let c=Be([],f,t.tileModelMatrix);Be(c,_,c);const h=Lt([],c);tr(h,h),vo(h,h,bp),c=Be(c,c,r.globalMatrix);const d="light-beam"===e.renderPass,p="none"===i.paint.get("model-color-use-theme").constantOr("default"),m=D&Dr.HasMapboxMeshFeatures,y=m?0:o.evaluatedRMEA[0][2];for(let _=0;_<r.meshes.length;++_){const f=r.meshes[_],b=_===r.lightMeshIndex;let w=t.wvpForNode;if(b){if(!d&&!e.terrain&&e.shadowRenderer){e.currentLayer<e.firstLightBeamLayer&&(e.firstLightBeamLayer=e.currentLayer);continue}w=t.wvpForTile}else if(d)continue;const T={defines:[]},E=[];if(!x&&l&&(l.useNormalOffset=!!f.normalBuffer),cp(T.defines,E,f,e,p?null:i.lut),m||T.defines.push("DIFFUSE_SHADED"),u&&T.defines.push("SHADOWS_SINGLE_CASCADE"),S&&(x?S.numRenderedVerticesInShadowPass+=f.vertexArray.length:S.numRenderedVerticesInTransparentPass+=f.vertexArray.length),x){_p(f,t.nodeModelMatrix,e,i);continue}let I=null;if(a){const i=lp(t.nodeModelMatrix,e.transform);if(I=new Float32Array(i),"globe"!==n.projection.name){const e=f.aabb.min,t=f.aabb.max,[o,s]=a.getOpacityForBounds(i,e[0],e[1],t[0],t[1]);T.overrideFog=o>=rl||s>=rl}}const C=f.material;let R;C.occlusionTexture&&C.occlusionTexture.offsetScale&&(R=C.occlusionTexture.offsetScale,T.defines.push("OCCLUSION_TEXTURE_TRANSFORM"));const A=e.getOrCreateProgram("model",T);!x&&l&&l.setupShadowsFromMatrix(t.tileModelMatrix,A,l.useNormalOffset),e.uploadCommonUniforms(s,A,null,I);const D=C.pbrMetallicRoughness;D.metallicFactor=.9,D.roughnessFactor=.5;const L=s_(new Float32Array(w),new Float32Array(c),new Float32Array(h),new Float32Array(r.globalMatrix),e,t.opacity,D.baseColorFactor,C.emissiveFactor,D.metallicFactor,D.roughnessFactor,C,y,i,[0,0,0],R);!b&&(o.hasTranslucentParts||t.opacity<1)&&A.draw(e,s.gl.TRIANGLES,g,uh.disabled,ch.disabled,fh.backCCW,L,i.id,f.vertexBuffer,f.indexBuffer,f.segments,i.paint,e.transform.zoom,void 0,E),A.draw(e,s.gl.TRIANGLES,b?v:g,uh.disabled,b||t.opacity<1||o.hasTranslucentParts?ch.alphaBlended:ch.unblended,fh.backCCW,L,i.id,f.vertexBuffer,f.indexBuffer,f.segments,i.paint,e.transform.zoom,void 0,E)}}}}()}(e,t,i,o),void _();if("model"!==p.type)return;const f=p.getModels(),m=[],g=e.transform.getFreeCameraOptions().position,v=Si([],[g.x,g.y,g.z],e.transform.worldSize);vr(v,v);const y=[],x=[];let b=0;for(const o of f){const s=t.getFeatureState("",o.id),r={type:"Unknown",id:o.id,properties:o.featureProperties},n=i.paint.get("model-rotation").evaluate(r,s),c=i.paint.get("model-scale").evaluate(r,s),h=i.paint.get("model-translation").evaluate(r,s),d=i.paint.get("model-opacity").evaluate(r,s);pp(i,o.id,s,o.featureProperties,o.nodeOverrideNames,o.nodeOverrides),fp(i,o.id,s,o.featureProperties,o.materialOverrideNames,o.materialOverrides),o.nodeOverrides.size>0&&o.computeBoundsAndApplyParent(),o.computeModelMatrix(e,n,c,h,l,a,!1);const u=Zt([]),_=ir(o.position.lat,e.transform.zoom),p=Ft([],[1,1,1/_]);Bt(u,u,v),m.push({zScaleMatrix:p,negCameraPosMatrix:u});for(const t of o.nodes)up(e,t,o.matrix,e.transform.expandedFarZProjMatrix,b,y,x,o.materialOverrides,d);b++}if(y.sort(((e,t)=>t.depth-e.depth)),"shadow"!==e.renderPass)mp(e,i,y,x,m),_();else{for(const t of x)_p(t.mesh,t.nodeModelMatrix,e,i);for(const t of y)_p(t.mesh,t.nodeModelMatrix,e,i);_()}}},jp={line:function(e,t,i){if(e.hasElevatedBuckets=!1,e.hasNonElevatedBuckets=!1,void 0!==e._unevaluatedLayout.getValue("line-elevation-reference")||void 0!==e._unevaluatedLayout.getValue("line-z-offset")){if(t){const i=t.getVisibleCoordinates();for(const o of i){const i=t.getTile(o).getBucket(e);if(i&&("none"!==i.elevationType?e.hasElevatedBuckets=!0:e.hasNonElevatedBuckets=!0,e.hasElevatedBuckets&&e.hasNonElevatedBuckets))break}}}else e.hasNonElevatedBuckets=!0},model:function(e,t,i){const o=t.getSource();if(!o.loaded())return;if("vector"===o.type||"geojson"===o.type)return void(i.modelManager&&i.modelManager.upload(i,dp(i,e)));if("batched-model"===o.type)return;if("model"!==o.type)return;const s=o.getModels();for(const e of s)e.upload(i.context)},raster:function(e,t,i){const o=t.getSource();if(!(o instanceof Al&&o.loaded()))return;const s=e.sourceLayer||o.rasterLayerIds&&o.rasterLayerIds[0];if(!s)return;const r=e.paint.get("raster-array-band")||o.getInitialBand(s);if(null==r)return;const n=t.getIds().map((e=>t.getTileByID(e)));for(const t of n)t.updateNeeded(e.id,r)&&o.prepareTile(t,s,e.id,r)},"raster-particle":function(e,t,i){const o=t.getSource();if(!(o instanceof Al&&o.loaded()))return;const s=e.sourceLayer||o.rasterLayerIds&&o.rasterLayerIds[0];if(!s)return;const r=e.paint.get("raster-particle-array-band")||o.getInitialBand(s);if(null==r)return;const n=t.getIds().map((e=>t.getTileByID(e)));for(const t of n)t.updateNeeded(e.id,r)&&o.prepareTile(t,s,e.id,r)}},Gp={fill:b_},Vp={fill:function(e,t,i,o){if(!i.layout||"none"===i.layout.get("fill-elevation-reference")||0===i.paint.get("fill-opacity").constantOr(1))return;const s=e.context.gl,r=new hh(s.LEQUAL,hh.ReadOnly,e.depthRangeFor3D),n=new uh({func:s.ALWAYS,mask:255},255,255,s.KEEP,s.KEEP,s.REPLACE),a=e.transform.getFreeCameraOptions().position,l=e.getOrCreateProgram("elevatedStructuresDepthReconstruct");for(const c of o){const o=t.getTile(c),h=o.getBucket(i);if(!h)continue;const d=h.elevatedStructures;if(!d||0===d.depthSegments.segments[0].primitiveLength)continue;const u=x_(c.toUnwrapped(),a),_=e.translatePosMatrix(c.projMatrix,o,i.paint.get("fill-translate"),i.paint.get("fill-translate-anchor")),p=Bu(_,u,0,1,0);l.draw(e,s.TRIANGLES,r,n,ch.disabled,fh.disabled,p,i.id,d.vertexBuffer,d.indexBuffer,d.depthSegments,i.paint,e.transform.zoom)}}};class Hp{constructor(e,t,i,o,s){this.context=new d_(e,t),this.transform=i,this._tileTextures={},this.frameCopies=[],this.loadTimeStamps=[],this._timeStamp=w.now(),this._averageFPS=0,this._fpsHistory=[],this._dt=0,this._debugParams={forceEnablePrecipitation:!1,showTerrainProxyTiles:!1,fpsWindow:30,continousRedraw:!1,enabledLayers:{}};const r=["fill","line","symbol","circle","heatmap","fill-extrusion","building","raster","raster-particle","hillshade","model","background","sky"];for(const e of r)this._debugParams.enabledLayers[e]=!0;for(const e of r);this.occlusionParams=new Cp,this.setup(),this.numSublayers=Kl.maxUnderzooming+Kl.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.deferredRenderGpuTimeQueries=[],this.gpuTimers={},this.frameCounter=0,this._backgroundTiles={},this.conflationActive=!1,this.replacementSource=new Br,this.longestCutoffRange=0,this.minCutoffZoom=0,this._fogVisible=!1,this._cachedTileFogOpacities={},this._shadowRenderer=new Ah(this),this._wireframeDebugCache=new Ip,this.renderDefaultNorthPole=!0,this.renderDefaultSouthPole=!0,this.layersWithOcclusionOpacity=[];const n=new T({width:1,height:1},Uint8Array.of(0,0,0,0));this.emptyDepthTexture=new z(this.context,n,e.RGBA8),this._clippingActiveLastFrame=!1,this.scaleFactor=o,this.worldview=s,this._forceEmissiveMode=!1,this.emissiveMode="constant"}updateTerrain(e,t){const i=!!e&&!!e.terrain&&this.transform.projection.supportsTerrain;if(!(i||this._terrain&&this._terrain.enabled))return;this._terrain||(this._terrain=new xu(this,e));const o=this._terrain;this.transform.elevation=i?o:null,o.update(e,this.transform,t),this.transform.elevation&&!o.enabled&&(this.transform.elevation=null)}_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,o]=t.getFovAdjustedRange(this.transform._fov);if(i>o)return void(this.transform.fogCullDistSq=null);const s=i+.78*(o-i);this.transform.fogCullDistSq=s*s}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=new xu(this,this.style)),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*w.devicePixelRatio,this.height=t*w.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 Tt;t.emplaceBack(0,0),t.emplaceBack(we,0),t.emplaceBack(0,we),t.emplaceBack(we,we),this.tileExtentBuffer=e.createVertexBuffer(t,St.members),this.tileExtentSegments=It.simpleSegment(0,0,4,2);const i=new Tt;i.emplaceBack(0,0),i.emplaceBack(we,0),i.emplaceBack(0,we),i.emplaceBack(we,we),this.debugBuffer=e.createVertexBuffer(i,St.members),this.debugSegments=It.simpleSegment(0,0,4,5);const o=new Tt;o.emplaceBack(-1,-1),o.emplaceBack(1,-1),o.emplaceBack(-1,1),o.emplaceBack(1,1),this.viewportBuffer=e.createVertexBuffer(o,St.members),this.viewportSegments=It.simpleSegment(0,0,4,2);const s=new dt;s.emplaceBack(0,0,0,0),s.emplaceBack(we,0,we,0),s.emplaceBack(0,we,0,we),s.emplaceBack(we,we,we,we),this.mercatorBoundsBuffer=e.createVertexBuffer(s,Rt.members),this.mercatorBoundsSegments=It.simpleSegment(0,0,4,2);const r=new ht;r.emplaceBack(0,1,2),r.emplaceBack(2,1,3),this.quadTriangleIndexBuffer=e.createIndexBuffer(r);const n=new Et;for(const e of[0,1,3,2,0])n.emplaceBack(e);this.debugIndexBuffer=e.createIndexBuffer(n),this.emptyTexture=new z(e,new T({width:1,height:1},Uint8Array.of(0,0,0,0)),e.gl.RGBA8),this.identityMat=$t();const a=this.context.gl;this.stencilClearMode=new uh({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={},this.getOrCreateProgram("clippingMask").draw(this,e.TRIANGLES,hh.disabled,this.stencilClearMode,ch.disabled,fh.disabled,fu(this.identityMat),"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments)}resetStencilClippingMasks(){this.terrain||(this.currentStencilSource=void 0,this._tileClippingMaskIDs={})}_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(void 0===this._tileClippingMaskIDs[t.key]){e=!0;break}if(!e)return}this.currentStencilSource=t.id;const o=this.context,s=o.gl;this.nextStencilID+i.length>256&&this.clearStencil(),o.setColorMode(ch.disabled),o.setDepthMode(hh.disabled);const r=this.getOrCreateProgram("clippingMask");this._tileClippingMaskIDs={};for(const e of i){const i=t.getTile(e),o=this._tileClippingMaskIDs[e.key]=this.nextStencilID++,{tileBoundsBuffer:n,tileBoundsIndexBuffer:a,tileBoundsSegments:l}=this.getTileBoundsBuffers(i);r.draw(this,s.TRIANGLES,hh.disabled,new uh({func:s.ALWAYS,mask:0},o,255,s.KEEP,s.KEEP,s.REPLACE),ch.disabled,fh.disabled,fu(e.projMatrix),"$clipping",n,a,l)}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();const e=this.nextStencilID++,t=this.context.gl;return new uh({func:t.NOTEQUAL,mask:255},e,255,t.KEEP,t.KEEP,t.REPLACE)}stencilModeForClipping(e){if(this.terrain)return this.terrain.stencilModeForRTTOverlap(e);const t=this.context.gl;return new uh({func:t.EQUAL,mask:255},this._tileClippingMaskIDs[e.key],0,t.KEEP,t.KEEP,t.REPLACE)}stencilConfigForOverlap(e){const t=this.context.gl,i=e.sort(((e,t)=>t.overscaledZ-e.overscaledZ)),o=i[i.length-1].overscaledZ,s=i[0].overscaledZ-o+1;if(s>1){this.currentStencilSource=void 0,this.nextStencilID+s>256&&this.clearStencil();const e={};for(let i=0;i<s;i++)e[i+o]=new uh({func:t.GEQUAL,mask:255},i+this.nextStencilID,255,t.KEEP,t.KEEP,t.REPLACE);return this.nextStencilID+=s,[e,i]}return[{[o]:uh.disabled},i]}colorModeForRenderPass(){const e=this.context.gl;if(this._showOverdrawInspector){const t=1/8;return new ch([e.CONSTANT_COLOR,e.ONE,e.CONSTANT_COLOR,e.ONE],new Te(t,t,t,0),[!0,!0,!0,!0])}return"opaque"===this.renderPass?ch.unblended:ch.alphaBlended}colorModeForDrapableLayerRenderPass(e){const t=this.context.gl;return(()=>this.style&&this.style.enable3dLights()&&this.terrain&&this.terrain.renderingToTexture)()&&"translucent"===this.renderPass?null!=e&&"mrt-fallback"!==this.emissiveMode||"constant"===this.emissiveMode?new ch([t.ONE,t.ONE_MINUS_SRC_ALPHA,t.CONSTANT_ALPHA,t.ONE_MINUS_SRC_ALPHA],new Te(0,0,0,null!=e?e:0),[!0,!0,!0,!0]):"dual-source-blending"===this.emissiveMode?new ch([t.ONE,t.ONE_MINUS_SRC_ALPHA,this.context.extBlendFuncExtended.SRC1_ALPHA_WEBGL,t.ONE_MINUS_SRC_ALPHA],Te.transparent,[!0,!0,!0,!0]):this.colorModeForRenderPass():this.colorModeForRenderPass()}depthModeForSublayer(e,t,i,o=!1){if(this.depthOcclusion)return new hh(this.context.gl.GREATER,hh.ReadOnly,this.depthRangeFor3D);if(!this.opaquePassEnabledForLayer()&&!o)return hh.disabled;const s=1-((1+this.currentLayer)*this.numSublayers+e)*this.depthEpsilon;return new hh(i||this.context.gl.LEQUAL,t,[s,s])}opaquePassEnabledForLayer(){return this.currentLayer<this.opaquePassCutoff}blitDepth(){const e=this.context.gl,t=Math.ceil(this.width),i=Math.ceil(this.height),o=this.context.bindFramebuffer.get(),s=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 h_(this.context,t,i,0,"texture"),this.depthTexture=new z(this.context,{width:t,height:i,data:null},e.DEPTH24_STENCIL8),this.depthFBO.depthAttachment.set(this.depthTexture.texture))),this.context.bindFramebuffer.set(o),e.bindTexture(e.TEXTURE_2D,s),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))}updateAverageFPS(){this._fpsHistory.push(0===this._dt?0:1e3/this._dt),this._fpsHistory.length>this._debugParams.fpsWindow&&this._fpsHistory.splice(0,this._fpsHistory.length-this._debugParams.fpsWindow),this._averageFPS=Math.round(this._fpsHistory.reduce(((e,t)=>e+t/this._fpsHistory.length),0))}render(e,t){const i=w.now();this._dt=i-this._timeStamp,this._timeStamp=i,this._wireframeDebugCache.update(this.frameCounter),this._debugParams.continousRedraw=e.map.repaint,this.style=e,this.options=t;const o=this.style._mergedLayers,s=!(!this.terrain||!this.terrain.enabled),r=()=>this.style._getOrder(s).filter((e=>{const t=o[e];return!(t.type in this._debugParams.enabledLayers)||this._debugParams.enabledLayers[t.type]}));let n=r(),a=!1,l=!1,c=null,h=0,d=!1;for(const e of n){const t=o[e];"none"!==t.visibility&&("circle"===t.type?a=!0:"building"===t.type?(c=t,++h):"symbol"===t.type&&(t.hasOcclusionOpacityProperties?l=!0:a=!0))}this.updateEmissiveMode();let u=n.map((e=>o[e]));const _=this.style._mergedSourceCaches;this.imageManager=e.imageManager,this.modelManager=e.modelManager,this.symbolFadeChange=e.placement.symbolFadeChange(w.now()),this.imageManager.beginFrame();for(const e in _){const t=_[e];t.used&&(t.prepare(this.context),t.getSource().usedInConflation&&++h)}let p=!1;for(const e of u)e.isHidden(this.transform.zoom)||("clip"===e.type&&(p=!0),this.prepareLayer(e));const f={},m={},g={},v={},y={};for(const e in _){const t=_[e];f[e]=t.getVisibleCoordinates(),m[e]=f[e].slice().reverse(),g[e]=t.getVisibleCoordinates(!0).reverse(),v[e]=t.getShadowCasterCoordinates(),y[e]=t.sortCoordinatesByDistance(f[e])}const x=e=>{const t=this.style.getLayerSourceCache(e);return t&&t.used?t.getSource():null};if(h||p||this._clippingActiveLastFrame){const e=[],t=[];let i=0;for(const o of u)this.isSourceForClippingOrConflation(o,x(o))&&(e.push(o),t.push(i)),i++;if(e&&(p||e.length>1)||this._clippingActiveLastFrame){p=!1;const i=[];for(let o=0;o<e.length;o++){const s=e[o],r=t[o],n=this.style.getLayerSourceCache(s);if(!n||!n.used||!n.getSource().usedInConflation&&"clip"!==s.type&&"building"!==s.type)continue;let a=Nr,l=vi.None;const c=[];let h=!0;if("building"===s.type)a=Ur;else if("clip"===s.type){a=r;for(const e of s.layout.get("clip-layer-types"))l|="model"===e?vi.Model:"symbol"===e?vi.Symbol:vi.FillExtrusion;for(const e of s.layout.get("clip-layer-scope"))c.push(e);s.isHidden(this.transform.zoom)?h=!1:p=!0}h&&i.push({layer:s.fqid,cache:n,order:a,clipMask:l,clipScope:c})}this.replacementSource.setSources(i),d=!0}}this._clippingActiveLastFrame=p,d||this.replacementSource.clear(),this.conflationActive=d,this.minCutoffZoom=0,this.longestCutoffRange=0,this.opaquePassCutoff=1/0,this._lastOcclusionLayer=-1,this.layersWithOcclusionOpacity=[];for(let e=0;e<u.length;e++){const t=u[e];if("none"===t.visibility)continue;const i=t.cutoffRange();if(this.longestCutoffRange=Math.max(i,this.longestCutoffRange),i>0){const e=x(t);e&&(this.minCutoffZoom=Math.max(e.minzoom,this.minCutoffZoom)),t.minzoom&&(this.minCutoffZoom=Math.max(t.minzoom,this.minCutoffZoom))}t.is3D(s)&&(this.opaquePassCutoff===1/0&&(this.opaquePassCutoff=e),this._lastOcclusionLayer=e)}const b=this.style&&this.style.fog;b?(this._fogVisible=0!==b.getOpacity(this.transform.pitch),this._fogVisible&&"globe"!==this.transform.projection.name&&(this._fogVisible=b.isVisibleOnFrustum(this.transform.cameraFrustum))):this._fogVisible=!1,this._cachedTileFogOpacities={},this.terrain&&(this.terrain.updateTileBinding(g),this.opaquePassCutoff=0,n=r(),u=n.map((e=>o[e])));const T=this._shadowRenderer;if(T){T.updateShadowParameters(this.transform,this.style.directionalLight);for(const e in _)for(const t of f[e]){let e={min:0,max:0};this.terrain&&(e=this.terrain.getMinMaxForTile(t)||e),T.addShadowReceiver(t.toUnwrapped(),e.min,e.max)}}"globe"!==this.transform.projection.name||this.globeSharedBuffers||(this.globeSharedBuffers=new kr(this.context)),this.style.fog&&this.transform.projection.supportsFog?(this._atmosphere||(this._atmosphere=new np(this)),this._atmosphere.update(this)):this._atmosphere&&(this._atmosphere.destroy(),this._atmosphere=void 0);const E=this._debugParams.forceEnablePrecipitation||!(!this.style||!this.style.snow),S=this._debugParams.forceEnablePrecipitation||!(!this.style||!this.style.rain);if(E&&!this._snow&&(this._snow=new Np(this)),!E&&this._snow&&(this._snow.destroy(),delete this._snow),S&&!this._rain&&(this._rain=new Bp(this)),!S&&this._rain&&(this._rain.destroy(),delete this._rain),this._snow&&this._snow.update(this),this._rain&&this._rain.update(this),c){this.buildingTileBorderManager||(this.buildingTileBorderManager=new ap);const e=this.style.getLayerSourceCache(c);this.buildingTileBorderManager.updateBorders(e,c)}if(!na.has(this.context.gl))return;this.renderPass="offscreen";for(const t of u){const i=e.getLayerSourceCache(t);if(!t.hasOffscreenPass()||t.isHidden(this.transform.zoom))continue;const o=i?m[i.id]:void 0;("custom"===t.type||"raster"===t.type||"raster-particle"===t.type||t.isSky()||o&&o.length)&&this.renderLayer(this,i,t,o)}this.depthRangeFor3D=[0,1-(u.length+2)*this.numSublayers*this.depthEpsilon],this._shadowRenderer&&(this.renderPass="shadow",this._shadowRenderer.drawShadowPass(this.style,v)),this.context.bindFramebuffer.set(null),this.context.viewport.set([0,0,this.width,this.height]);const I="globe"===this.transform.projection.name||this.transform.isHorizonVisible(),C=(()=>{if(t.showOverdrawInspector)return Te.black;const e=this.style.fog;if(e&&this.transform.projection.supportsFog){const t=this.style.getLut(e.scope);if(!I){const i="none"===e.properties.get("color-use-theme"),o=e.properties.get("color").toNonPremultipliedRenderColor(i?null:t).toArray01();return new Te(...o)}if(I){const i="none"===e.properties.get("space-color-use-theme"),o=e.properties.get("space-color").toNonPremultipliedRenderColor(i?null:t).toArray01();return new Te(...o)}}return Te.transparent})();if(this.context.clear({color:C,depth:1}),this.clearStencil(),this._showOverdrawInspector=t.showOverdrawInspector,this.renderPass="opaque",this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&I&&this._atmosphere.drawStars(this,this.style.fog),!this.terrain)for(this.currentLayer=n.length-1;this.currentLayer>=0;this.currentLayer--){const t=u[this.currentLayer],i=e.getLayerSourceCache(t);if(t.isSky())continue;const o=i?(t.is3D(s)?y:m)[i.id]:void 0;this._renderTileClippingMasks(t,i,o),this.renderLayer(this,i,t,o)}if(this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&I&&this._atmosphere.drawAtmosphereGlow(this,this.style.fog),this.renderPass="sky",(!this._atmosphere||ye(this.transform.zoom)>0)&&("globe"===this.transform.projection.name||this.transform.isHorizonVisible()))for(this.currentLayer=0;this.currentLayer<n.length;this.currentLayer++){const t=u[this.currentLayer],i=e.getLayerSourceCache(t);t.isSky()&&this.renderLayer(this,i,t,i?m[i.id]:void 0)}function R(e,t){let i;return t&&(i=("symbol"===e.type?g:e.is3D(s)?y:m)[t.id]),i}if(this.renderPass="translucent","globe"===this.transform.projection.name){for(this.renderElevatedRasterBackface=!0,this.currentLayer=0;this.currentLayer<n.length;){const t=u[this.currentLayer];if("raster"===t.type||"raster-particle"===t.type){const i=e.getLayerSourceCache(t);this.renderLayer(this,i,t,R(t,i))}++this.currentLayer}this.renderElevatedRasterBackface=!1}this.currentLayer=0,this.firstLightBeamLayer=Number.MAX_SAFE_INTEGER;let A=0;T&&(A=T.getShadowCastingLayerCount());let D=!1,L=-1;for(let e=0;e<n.length;++e){const t=u[e];t.isHidden(this.transform.zoom)||t.is3D(s)&&(L=e)}l&&-1===L&&(a=!0);let O=!1;for(;this.currentLayer<n.length;){const t=u[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(!O&&t.is3D(s)&&!s){const e=this.currentLayer,t=e=>{for(this.currentLayer=0;this.currentLayer<u.length;this.currentLayer++){const t=u[this.currentLayer];if(Gp[t.type]){const i=this.style.getLayerSourceCache(t);Gp[t.type](this,i,t,R(t,i),e)}}};t("initialize"),t("reset"),this.currentLayer=e,O=!0}if(a&&!D&&this.terrain&&!this.transform.isOrthographic&&(D=!0,this.blitDepth()),l&&-1!==L&&this.currentLayer===L+1&&!this.transform.isOrthographic&&this.blitDepth(),this.terrain||this._renderTileClippingMasks(t,i,i?f[i.id]:void 0),this.renderLayer(this,i,t,R(t,i)),!this.terrain&&T&&A>0&&t.hasShadowPass()&&0==--A){{this.clearStencil(),this.resetStencilClippingMasks();const e=this.currentLayer;for(this.currentLayer=0;this.currentLayer<u.length;this.currentLayer++){const e=u[this.currentLayer];if(Vp[e.type]){const t=this.style.getLayerSourceCache(e);Vp[e.type](this,t,e,R(e,t))}}this.currentLayer=e}if(T.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=u[this.currentLayer];if(!t.hasLightBeamPass())continue;const i=e.getLayerSourceCache(t);this.renderLayer(this,i,t,i?m[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=u[this.currentLayer],o=e.getLayerSourceCache(i),s=o?m[o.id]:void 0;this.terrain||this._renderTileClippingMasks(i,o,o?f[o.id]:void 0),this.renderLayer(this,o,i,s)}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;u.forEach((i=>{const o=e.getLayerSourceCache(i);o&&!i.isHidden(this.transform.zoom)&&o.getVisibleCoordinates().length&&(!t||t.getSource().maxzoom<o.getSource().maxzoom)&&(t=o)})),t&&this.options.showTileBoundaries&&Z_(this,t,t.getVisibleCoordinates(),Te.red,!1,this.options.showParseStatus)}this.terrain&&this._debugParams.showTerrainProxyTiles&&Z_(this,this.terrain.proxySourceCache,this.terrain.proxyCoords,new Te(1,.8,.1,1),!0,this.options.showParseStatus),this.options.showPadding&&function(e){const t=e.transform.padding;$_(e,e.transform.height-(t.top||0),3,j_),$_(e,t.bottom||0,3,G_),X_(e,t.left||0,3,V_),X_(e,e.transform.width-(t.right||0),3,H_);const i=e.transform.centerPoint;!function(e,t,i,o){Y_(e,t-1,i-10,2,20,o),Y_(e,t-10,i-1,20,2,o)}(e,i.x,e.transform.height-i.y,q_)}(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()),d||(this.conflationActive=!1)}prepareLayer(e){this.gpuTimingStart(e);const{unsupportedLayers:t}=this.transform.projection,i=!t||!t.includes(e.type);if(jp[e.type]&&(i||this.terrain&&"custom"===e.type)){const t=this.style.getLayerSourceCache(e);jp[e.type](e,t,this)}this.gpuTimingEnd()}renderLayer(e,t,i,o){i.isHidden(this.transform.zoom)||("background"===i.type||"sky"===i.type||"custom"===i.type||"model"===i.type||"raster"===i.type||"raster-particle"===i.type||o&&o.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||Up[i.type](e,t,i,o,this.style.placement.variableOffsets,this.options.isInitialLoad),this.gpuTimingEnd())}gpuTimingStart(e){if(!this.options.gpuTiming)return;const t=this.context.extTimerQuery,i=this.context.gl;let o=this.gpuTimers[e.id];o||(o=this.gpuTimers[e.id]={calls:0,cpuTime:0,query:i.createQuery()}),o.calls++,i.beginQuery(t.TIME_ELAPSED_EXT,o.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 o=e[i],s=this.context.extTimerQuery,r=s.getQueryParameter(o.query,this.context.gl.QUERY_RESULT)/1e6;s.deleteQueryEXT(o.query),t[i]=r}return t}queryGpuTimeDeferredRender(e){if(!this.options.gpuTimingDeferredRender)return 0;const t=this.context.gl;let i=0;for(const o of e)i+=t.getQueryParameter(o,t.QUERY_RESULT)/1e6,t.deleteQuery(o);return i}translatePosMatrix(e,t,i,o,s){if(!i[0]&&!i[1])return e;const r=s?"map"===o?this.transform.angle:0:"viewport"===o?-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=[s?i[0]:ze(t,i[0],this.transform.zoom),s?i[1]:ze(t,i[1],this.transform.zoom),0],a=new Float32Array(16);return Bt(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.getTerrain()&&!!this.terrain&&!this.terrain.renderingToTexture||this.forceTerrainMode}linearFloatFilteringSupported(){return null!=this.context.extTextureFloatLinear}currentGlobalDefines(e,t,i){const o=void 0===i?this.terrain&&this.terrain.renderingToTexture:i,s=[];return this.style&&this.style.enable3dLights()&&("globeRaster"===e||"terrainRaster"===e?(s.push("LIGHTING_3D_MODE"),s.push("LIGHTING_3D_ALPHA_EMISSIVENESS")):o||s.push("LIGHTING_3D_MODE")),"shadow"===this.renderPass&&(this._shadowMapDebug||s.push("DEPTH_TEXTURE")),this.terrainRenderModeElevated()&&(s.push("TERRAIN"),this.linearFloatFilteringSupported()&&s.push("TERRAIN_DEM_FLOAT_FORMAT")),"globe"===this.transform.projection.name&&s.push("GLOBE"),!this._fogVisible||o||void 0!==t&&!t||s.push("FOG","FOG_DITHERING"),o&&s.push("RENDER_TO_TEXTURE"),this._showOverdrawInspector&&s.push("OVERDRAW_INSPECTOR"),s}getOrCreateProgram(e,t){this.cache=this.cache||{};const i=t&&t.defines||[],o=t&&t.config,s=this.currentGlobalDefines(e,t&&t.overrideFog,t&&t.overrideRtt).concat(i),r=Eu.cacheKey(md[e],e,s,o);return this.cache[r]||(this.cache[r]=new Eu(this.context,e,md[e],o,n_[e],s)),this.cache[r]}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 z(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()}prepareDrawTile(){this.terrain&&this.terrain.prepareDrawTile()}uploadCommonLightUniforms(e,t){if(this.style.enable3dLights()){const i=this.style.directionalLight,o=this.style.ambientLight;if(i&&o){const s=((e,t,i)=>{const o=e.properties.get("direction"),s="none"===e.properties.get("color-use-theme"),r=e.properties.get("color").toNonPremultipliedRenderColor(s?null:i.getLut(e.scope)).toArray01(),n=e.properties.get("intensity"),a="none"===t.properties.get("color-use-theme"),l=t.properties.get("color").toNonPremultipliedRenderColor(a?null:i.getLut(t.scope)).toArray01(),c=t.properties.get("intensity"),h=[o.x,o.y,o.z],d=Ss(l,c),u=Ss(r,n);return{u_lighting_ambient_color:d,u_lighting_directional_dir:h,u_lighting_directional_color:u,u_ground_radiance:bu(h,u,d)}})(i,o,this.style);t.setLightsUniformValues(e,s)}}}uploadCommonUniforms(e,t,i,o,s){if(this.uploadCommonLightUniforms(e,t),this.terrain&&this.terrain.renderingToTexture)return;const r=this.style.fog;if(r){const s=r.getOpacity(this.transform.pitch),n=((e,t,i,o,s,r,n,a,l,c,h,d)=>{const u=e.transform,_="none"===t.properties.get("color-use-theme"),p=t.properties.get("color").toNonPremultipliedRenderColor(_?null:e.style.getLut(t.scope)).toArray01();p[3]=o;const f=e.frameCounter/1e3%1,[m,g]=t.properties.get("vertical-range");return{u_fog_matrix:i?u.calculateFogTileMatrix(i):d||e.identityMat,u_fog_range:t.getFovAdjustedRange(u._fov),u_fog_color:p,u_fog_horizon_blend:t.properties.get("horizon-blend"),u_fog_vertical_limit:[Math.min(m,g),g],u_fog_temporal_offset:f,u_frustum_tl:s,u_frustum_tr:r,u_frustum_br:n,u_frustum_bl:a,u_globe_pos:l,u_globe_radius:c,u_viewport:h,u_globe_transition:ye(u.zoom),u_is_globe:+("globe"===u.projection.name)}})(this,r,i,s,this.transform.frustumCorners.TL,this.transform.frustumCorners.TR,this.transform.frustumCorners.BR,this.transform.frustumCorners.BL,this.transform.globeCenterInViewSpace,this.transform.globeRadius,[this.transform.width*w.devicePixelRatio,this.transform.height*w.devicePixelRatio],o);t.setFogUniformValues(e,n)}s&&t.setCutoffUniformValues(e,s.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 o of i)t[o.key]=e[o.key]||new Wl(o,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.style||!this.style.fog)return!1;if("globe"===this.transform.projection.name)return!0;let t=this._cachedTileFogOpacities[e.key];return t||(this._cachedTileFogOpacities[e.key]=t=this.style.fog.getOpacityForTile(e)),t[0]>=rl||t[1]>=rl}setupDepthForOcclusion(e,t,i){const o=this.context,s=o.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}),o.activeTexture.set(s.TEXTURE3),e&&this.depthFBO&&this.depthTexture?(this.depthTexture.bind(s.NEAREST,s.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(s.NEAREST,s.CLAMP_TO_EDGE),o.activeTexture.set(s.TEXTURE0),r||t.setTerrainUniformValues(o,i)}updateEmissiveMode(){if(this._forceEmissiveMode)return;const e=this.style.hasDataDrivenEmissiveStrength();this.emissiveMode=e?this.context.extBlendFuncExtended?"dual-source-blending":"mrt-fallback":"constant"}}function qp(e,t){let i=!1,o=null;const s=()=>{o=null,i&&(e(),o=setTimeout(s,t),i=!1)};return()=>(i=!0,o||s(),o)}class Zp{constructor(e){this._hashName=e&&encodeURIComponent(e),nt(["_getCurrentHash","_onHashChange","_updateHash"],this),this._updateHash=qp(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=Wp(e);if(this._hashName){const e=this._hashName;let i=!1;const o=location.hash.slice(1).split("&").map((o=>{const s=o.split("=")[0];return s===e?(i=!0,`${s}=${t}`):o})).filter((e=>e));return i||o.push(`${e}=${t}`),`#${o.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(/(#.+)?$/,this.getHashString()))}}function Wp(e,t){const i=e.getCenter(),o=Math.round(100*e.getZoom())/100,s=Math.ceil((o*Math.LN2+Math.log(512/360/.5))/Math.LN10),r=Math.pow(10,s),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}/${o}`:`${o}/${a}/${n}`;return(l||c)&&(h+="/"+Math.round(10*l)/10),c&&(h+=`/${Math.round(c)}`),h}const $p={linearity:.3,easing:jr(0,0,.3,1)},Xp=Object.assign({deceleration:2500,maxSpeed:1400},$p),Yp=Object.assign({deceleration:20,maxSpeed:1400},$p),Kp=Object.assign({deceleration:1e3,maxSpeed:360},$p),Qp=Object.assign({deceleration:1e3,maxSpeed:90},$p);class Jp{constructor(e){this._map=e,this.clear()}clear(){this._inertiaBuffer=[]}record(e){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:w.now(),settings:e})}_drainInertiaBuffer(){const e=this._inertiaBuffer,t=w.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 r(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[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,o={};if(t.pan.mag()){const s=tf(t.pan.mag(),i,Object.assign({},Xp,e||{}));o.offset=t.pan.mult(s.amount/t.pan.mag()),o.center=this._map.transform.center,ef(o,s)}if(t.zoom){const e=tf(t.zoom,i,Yp);o.zoom=this._map.transform.zoom+e.amount,ef(o,e)}if(t.bearing){const e=tf(t.bearing,i,Kp);o.bearing=this._map.transform.bearing+Fe(e.amount,-179,179),ef(o,e)}if(t.pitch){const e=tf(t.pitch,i,Qp);o.pitch=this._map.transform.pitch+e.amount,ef(o,e)}if(o.zoom||o.bearing){const e=void 0===t.pinchAround?t.around:t.pinchAround;o.around=e?this._map.unproject(e):this._map.getCenter()}return this.clear(),o.noMoveStart=!0,o}}function ef(e,t){(!e.duration||e.duration<t.duration)&&(e.duration=t.duration,e.easing=t.easing)}function tf(e,t,i){const{maxSpeed:o,linearity:s,deceleration:r}=i,n=Fe(e*s/(t/1e3),-o,o),a=Math.abs(n)/(r*s);return{easing:i.easing,duration:1e3*a,amount:n*(a/2)}}class of extends D{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(e,t,i,o={}){const s=On(t.getCanvasContainer(),i),r=t.unproject(s);super(e,Object.assign({point:s,lngLat:r,originalEvent:i},o)),this._defaultPrevented=!1,this.target=t}}class sf extends D{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(e,t,i){const o="touchend"===e?i.changedTouches:i.touches,s=Pn(t.getCanvasContainer(),o),n=s.map((e=>t.unproject(e))),a=s.reduce(((e,t,i,o)=>e.add(t.div(o.length))),new r(0,0));super(e,{points:s,point:a,lngLats:n,lngLat:t.unproject(a),originalEvent:i}),this._defaultPrevented=!1}}class rf extends D{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(e,t){super("wheel",{originalEvent:t}),this._defaultPrevented=!1}}class nf{constructor(e,t){this._map=e,this._clickTolerance=t.clickTolerance}reset(){this._mousedownPos=void 0}wheel(e){return this._firePreventable(new rf(this._map,e))}mousedown(e,t){return this._mousedownPos=t,this._firePreventable(new of(e.type,this._map,e))}mouseup(e){this._map.fire(new of(e.type,this._map,e))}preclick(e){const t=new MouseEvent("preclick",e);this._map.fire(new of(t.type,this._map,t))}click(e,t){this._mousedownPos&&this._mousedownPos.dist(t)>=this._clickTolerance||(this.preclick(e),this._map.fire(new of(e.type,this._map,e)))}dblclick(e){return this._firePreventable(new of(e.type,this._map,e))}mouseover(e){this._map.fire(new of(e.type,this._map,e))}mouseout(e){this._map.fire(new of(e.type,this._map,e))}touchstart(e){return this._firePreventable(new sf(e.type,this._map,e))}touchmove(e){this._map.fire(new sf(e.type,this._map,e))}touchend(e){this._map.fire(new sf(e.type,this._map,e))}touchcancel(e){this._map.fire(new sf(e.type,this._map,e))}_firePreventable(e){if(this._map.fire(e),e.defaultPrevented)return{}}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class af{constructor(e){this._map=e}reset(){this._delayContextMenu=!1,this._contextMenuEvent=void 0}mousemove(e){this._map.fire(new of(e.type,this._map,e))}mousedown(){this._delayContextMenu=!0}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new of("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent)}contextmenu(e){this._delayContextMenu?this._contextMenuEvent=e:this._map.fire(new of(e.type,this._map,e)),this._map.listens("contextmenu")&&e.preventDefault()}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class lf{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,o=this._startPos,s=this._lastPos;if(!o||!s||s.equals(i)||!this._box&&i.dist(o)<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(o.x,i.x),n=Math.max(o.x,i.x),a=Math.min(o.y,i.y),l=Math.max(o.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,o=t;if(i&&0===e.button){if(this.reset(),Ln(),i.x!==o.x||i.y!==o.y)return this._map.fire(new D("boxzoomend",{originalEvent:e})),{cameraAnimation:e=>e.fitScreenCoordinates(i,o,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),An(),delete this._startPos,delete this._lastPos}_fireEvent(e,t){return this._map.fire(new D(e,{originalEvent:t}))}}function cf(e,t){const i={};for(let o=0;o<e.length;o++)i[e[o].identifier]=t[o];return i}class hf{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 r(0,0);for(const i of e)t._add(i);return t.div(e.length)}(t),this.touches=cf(i,t)))}touchmove(e,t,i){if(this.aborted||!this.centroid)return;const o=cf(i,t);for(const e in this.touches){const t=o[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 df{constructor(e){this.singleTap=new hf(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 o=this.singleTap.touchend(e,t,i);if(o){const t=e.timeStamp-this.lastTime<500,i=!this.lastTap||this.lastTap.dist(o)<30;if(t&&i||this.reset(),this.count++,this.lastTime=e.timeStamp,this.lastTap=o,this.count===this.numTaps)return this.reset(),o}}}class uf{constructor(){this._zoomIn=new df({numTouches:1,numTaps:2}),this._zoomOut=new df({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 o=this._zoomIn.touchend(e,t,i),s=this._zoomOut.touchend(e,t,i);return 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})}):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})}):void 0}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}const _f={0:1,2:2},pf={Control:"ctrlKey",Alt:"altKey",Shift:"shiftKey",Meta:"metaKey"};class ff{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=Mn(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=_f[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&&Mn(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 mf extends ff{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 gf extends ff{constructor(e){super(e),this._pitchRotateKey=e.pitchRotateKey?pf[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 vf extends ff{constructor(e){super(e),this._pitchRotateKey=e.pitchRotateKey?pf[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 yf{constructor(e,t){this._map=e,this._el=e.getCanvasContainer(),this._minTouches=1,this._clickTolerance=t.clickTolerance||1,this.reset(),nt(["_addTouchPanBlocker","_showTouchPanBlockerAlert"],this)}reset(){this._active=!1,this._touches={},this._sum=new r(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&&!Gr())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 o=cf(i,t),s=new r(0,0),n=new r(0,0);let a=0;for(const e in o){const t=o[e],i=this._touches[e];i&&(s._add(t),n._add(t.sub(i)),a++,o[e]=t)}if(this._touches=o,a<this._minTouches||!n.mag())return;const l=n.div(a);return this._sum._add(l),this._sum.mag()<this._clickTolerance?void 0:{around:s.div(a),panDelta:l}}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 xf{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 o=this._firstTwoTouches;if(!o)return;e.preventDefault();const[s,r]=o,n=bf(i,t,s),a=bf(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[o,s]=this._firstTwoTouches,r=bf(i,t,o),n=bf(i,t,s);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 bf(e,t,i){for(let o=0;o<e.length;o++)if(e[o].identifier===i)return t[o]}function wf(e,t){return Math.log2(e/t)}class Tf extends xf{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(wf(this._distance,this._startDistance))<.1))return this._active=!0,{zoomDelta:wf(this._distance,i),pinchAround:t}}}function Ef(e,t){return 180*e.angleWith(t)/Math.PI}class Sf extends xf{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:Ef(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 o=Ef(e,i);return Math.abs(o)<t}}function If(e){return Math.abs(e.y)>Math.abs(e.x)}class Cf extends xf{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,If(e[0].sub(e[1]))&&(this._valid=!1)}_move(e,t,i){const o=this._lastPoints;if(!o)return;const s=e[0].sub(o[0]),r=e[1].sub(o[1]);return this._map._cooperativeGestures&&!Gr()&&i.touches.length<3||(this._valid=this.gestureBeginsVertically(s,r,i.timeStamp),!this._valid)?void 0:(this._lastPoints=e,this._active=!0,{pitchDelta:(s.y+r.y)/2*-.5})}gestureBeginsVertically(e,t,i){if(void 0!==this._valid)return this._valid;const o=e.mag()>=2,s=t.mag()>=2;if(!o&&!s)return;if(!o||!s)return null==this._firstMove&&(this._firstMove=i),i-this._firstMove<100&&void 0;const r=e.y>0==t.y>0;return If(e)&&If(t)&&r}}const Rf={panStep:100,bearingStep:15,pitchStep:10};class Af{constructor(){const e=Rf;this._panStep=e.panStep,this._bearingStep=e.bearingStep,this._pitchStep=e.pitchStep,this._rotationDisabled=!1}blur(){this.reset()}reset(){this._active=!1}keydown(e){if(e.altKey||e.ctrlKey||e.metaKey)return;let t=0,i=0,o=0,s=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(),s=-1);break;case 39:e.shiftKey?i=1:(e.preventDefault(),s=1);break;case 38:e.shiftKey?o=1:(e.preventDefault(),r=-1);break;case 40:e.shiftKey?o=-1:(e.preventDefault(),r=1);break;default:return}return this._rotationDisabled&&(i=0,o=0),{cameraAnimation:n=>{const a=n.getZoom();n.easeTo({duration:300,easeId:"keyboardHandler",easing:Df,zoom:t?Math.round(a)+t*(e.shiftKey?2:1):a,bearing:n.getBearing()+i*this._bearingStep,pitch:n.getPitch()+o*this._pitchStep,offset:[-s*this._panStep,-r*this._panStep],center:n.getCenter()},{originalEvent:e})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}disableRotation(){this._rotationDisabled=!0}enableRotation(){this._rotationDisabled=!1}}function Df(e){return e*(2-e)}const Lf=4.000244140625,Of=1/450;class Pf{constructor(e,t){this._map=e,this._el=e.getCanvasContainer(),this._handler=t,this._delta=0,this._lastDelta=0,this._defaultZoomRate=.01,this._wheelZoomRate=Of,nt(["_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()||Gr()))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=w.now(),o=i-(this._lastWheelEventTime||0);this._lastWheelEventTime=i,0!==t&&t%Lf==0?this._type="wheel":0!==t&&Math.abs(t)<4?this._type="trackpad":o>400?(this._type=null,this._lastValue=t,this._timeout=window.setTimeout(this._onTimeout,40,e)):this._type||(this._type=Math.abs(o*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=On(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)>Lf?this._wheelZoomRate:this._defaultZoomRate;let o=2/(1+Math.exp(-Math.abs(this._delta*i)));this._delta<0&&0!==o&&(o=1/o);const s=t(),r=Math.pow(2,s),n="number"==typeof this._targetZoom?e.zoomScale(this._targetZoom):r;this._targetZoom=Math.min(e.maxZoom,Math.max(e.minZoom,e.scaleZoom(n*o))),"wheel"===this._type&&(this._startZoom=s,this._easing=this._smoothOutEasing(200)),this._lastDelta=this._delta,this._delta=0}const i="number"==typeof this._targetZoom?this._targetZoom:t(),o=this._startZoom,s=this._easing;let r,n=!1;if("wheel"===this._type&&o&&s){const e=Math.min((w.now()-this._lastWheelEventTime)/200,1),t=s(e);r=xe(o,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=Vr;if(this._prevEase){const e=this._prevEase,i=(w.now()-e.start)/e.duration,o=e.easing(i+.01)-e.easing(i),s=.27/Math.sqrt(o*o+1e-4)*.01,r=Math.sqrt(.0729-s*s);t=jr(s,r,.25,1)}return this._prevEase={start:w.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=/(Mac|iPad)/i.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 Mf{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 zf{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 Ff{constructor(){this._tap=new df({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 o=t[0],s=o.y-this._swipePoint.y;return this._swipePoint=o,e.preventDefault(),this._active=!0,{zoomDelta:s/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 Bf{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 kf{constructor(e,t,i){this._pitchWithRotate=e.pitchWithRotate,this._mouseRotate=t,this._mousePitch=i}enable(){this._mouseRotate.enable(),this._pitchWithRotate&&this._mousePitch.enable()}disable(){this._mouseRotate.disable(),this._mousePitch.disable()}isEnabled(){return this._mouseRotate.isEnabled()&&(!this._pitchWithRotate||this._mousePitch.isEnabled())}isActive(){return this._mouseRotate.isActive()||this._mousePitch.isActive()}}class Nf{constructor(e,t,i,o){this._el=e,this._touchZoom=t,this._touchRotate=i,this._tapDragZoom=o,this._rotationDisabled=!1,this._enabled=!0}enable(e){this._touchZoom.enable(e),this._rotationDisabled||this._touchRotate.enable(e),this._tapDragZoom.enable(),this._el.classList.add("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._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()}}const Uf=e=>e.zoom||e.drag||e.pitch||e.rotate;class jf extends D{}class Gf{constructor(){this.constants=[1,1,.01],this.radius=0}setup(e,t){const i=Le([],t,e);this.radius=ge(i[2]<0?qr([],i,this.constants):[i[0],i[1],0])}projectRay(e){qr(e,e,this.constants),Oe(e,e),Zr(e,e,this.constants);const t=Si([],e,this.radius);if(t[2]>0){const e=Si([],[0,0,1],ni(t,[0,0,1])),i=Si([],Oe([],[t[0],t[1],0]),this.radius),o=ko([],t,Si([],Le([],ko([],i,e),t),2));t[0]=o[0],t[1]=o[1]}return t}}function Vf(e){return e.panDelta&&e.panDelta.mag()||e.zoomDelta||e.bearingDelta||e.pitchDelta}class Hf{constructor(e,t){this._map=e,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new Jp(e),this._bearingSnap=t.bearingSnap,this._previousActiveHandlers={},this._trackingEllipsoid=new Gf,this._dragOrigin=null,this._eventsInProgress={},this._addDefaultHandlers(t),nt(["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 o=e===document?this.handleWindowEvent:this.handleEvent;e.addEventListener(t,o,i)}}destroy(){for(const[e,t,i]of this._listeners){const o=e===document?this.handleWindowEvent:this.handleEvent;e.removeEventListener(t,o,i)}}_addDefaultHandlers(e){const t=this._map,i=t.getCanvasContainer();this._add("mapEvent",new nf(t,e));const o=t.boxZoom=new lf(t,e);this._add("boxZoom",o);const s=new uf,r=new zf;t.doubleClickZoom=new Mf(r,s),this._add("tapZoom",s),this._add("clickZoom",r);const n=new Ff;this._add("tapDragZoom",n);const a=t.touchPitch=new Cf(t);this._add("touchPitch",a);const l=new gf(e),c=new vf(e);t.dragRotate=new kf(e,l,c),this._add("mouseRotate",l,["mousePitch"]),this._add("mousePitch",c,["mouseRotate"]);const h=new mf(e),d=new yf(t,e);t.dragPan=new Bf(i,h,d),this._add("mousePan",h),this._add("touchPan",d,["touchZoom","touchRotate"]);const u=new Sf,_=new Tf;t.touchZoomRotate=new Nf(i,_,u,n),this._add("touchRotate",u,["touchPan","touchZoom"]),this._add("touchZoom",_,["touchPan","touchRotate"]),this._add("blockableMapEvent",new af(t));const p=t.scrollZoom=new Pf(t,this);this._add("scrollZoom",p,["mousePan"]);const f=t.keyboard=new Af;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){if(!this._updatingCamera){for(const{handler:e}of this._handlers)e.reset();this._inertia.clear(),this._fireEvents({},{},e),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!!Uf(this._eventsInProgress)||this.isZooming()}_isDragging(){return!!this._eventsInProgress.drag}_blockedByActive(e,t,i){for(const o in e)if(o!==i&&(!t||t.indexOf(o)<0))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}handleEvent(e,t){this._updatingCamera=!0;const i="renderFrame"===e.type,o=i?void 0:e,s={needsRenderFrame:!1},r={},n={},a=e.touches?this._getMapTouches(e.touches):void 0,l=a?Pn(this._el,a):i?void 0:On(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(s,r,d,i,o),d&&d.needsRenderFrame&&this._triggerRenderFrame()),(d||c.isActive())&&(n[i]=c)}const c={};for(const e in this._previousActiveHandlers)n[e]||(c[e]=o);this._previousActiveHandlers=n,(Object.keys(c).length||Vf(s))&&(this._changes.push([s,r,c]),this._triggerRenderFrame()),(Object.keys(n).length||Vf(s))&&this._map._stop(!0),this._updatingCamera=!1;const{cameraAnimation:h}=s;h&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],h(this._map))}mergeHandlerResult(e,t,i,o,s){if(!i)return;Object.assign(e,i);const r={handlerName:o,originalEvent:i.originalEvent||s};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[o,s,n]of this._changes)o.panDelta&&(e.panDelta=(e.panDelta||new r(0,0))._add(o.panDelta)),o.zoomDelta&&(e.zoomDelta=(e.zoomDelta||0)+o.zoomDelta),o.bearingDelta&&(e.bearingDelta=(e.bearingDelta||0)+o.bearingDelta),o.pitchDelta&&(e.pitchDelta=(e.pitchDelta||0)+o.pitchDelta),void 0!==o.around&&(e.around=o.around),void 0!==o.aroundCoord&&(e.aroundCoord=o.aroundCoord),void 0!==o.pinchAround&&(e.pinchAround=o.pinchAround),o.noInertia&&(e.noInertia=o.noInertia),Object.assign(t,s),Object.assign(i,n);this._updateMapTransform(e,t,i),this._changes=[]}_updateMapTransform(e,t,i){const o=this._map,s=o.transform,r=e=>[e.x,e.y,e.z];if((e=>{const t=this._eventsInProgress.drag;return t&&!this._handlersById[t.handlerName].isActive()})()&&!Vf(e)){const e=s.zoom;s.cameraElevationReference="sea",null!=this._originalZoom&&s._orthographicProjectionAtLowPitch&&"globe"!==s.projection.name&&0===s.pitch?(s.cameraElevationReference="ground",s.zoom=this._originalZoom):(s.recenterOnTerrain(),s.cameraElevationReference="ground"),e!==s.zoom&&this._map._update(!0)}if(s._isCameraConstrained&&o._stop(!0),!Vf(e))return void this._fireEvents(t,i,!0);let{panDelta:n,zoomDelta:a,bearingDelta:l,pitchDelta:c,around:h,aroundCoord:d,pinchAround:u}=e;s._isCameraConstrained&&(a>0&&(a=0),s._isCameraConstrained=!1),void 0!==u&&(h=u),(a||(e=>t[e]&&!this._eventsInProgress[e])("drag"))&&h&&(this._dragOrigin=r(s.pointCoordinate3D(h)),this._originalZoom=s.zoom,this._trackingEllipsoid.setup(s._camera.position,this._dragOrigin)),s.cameraElevationReference="sea",o._stop(!0),h=h||o.transform.centerPoint,l&&(s.bearing+=l),c&&(s.pitch+=c),s._updateCameraState();const _=[0,0,0];if(n)if("mercator"===s.projection.name){const e=this._trackingEllipsoid.projectRay(s.screenPointToMercatorRay(h).dir),t=this._trackingEllipsoid.projectRay(s.screenPointToMercatorRay(h.sub(n)).dir);_[0]=t[0]-e[0],_[1]=t[1]-e[1]}else{const e=s.pointCoordinate(h);if("globe"===s.projection.name){n=n.rotate(-s.angle);const t=s._pixelsPerMercatorPixel/s.worldSize;_[0]=-n.x*Hr(ct(e.y))*t,_[1]=-n.y*Hr(s.center.lat)*t}else{const t=s.pointCoordinate(h.sub(n));e&&t&&(_[0]=t.x-e.x,_[1]=t.y-e.y)}}const p=s.zoom,f=[0,0,0];if(a){const e=r(d||s.pointCoordinate3D(h)),t={dir:Oe([],Le([],e,s._camera.position))};if(t.dir[2]<0){const i=s.zoomDeltaToMovement(e,a);Si(f,t.dir,i)}}const m=ko(_,_,f);s._translateCameraConstrained(m),a&&Math.abs(s.zoom-p)>1e-4&&s.recenterOnTerrain(),s.cameraElevationReference="ground",this._map._update(),e.noInertia||this._inertia.record(e),this._fireEvents(t,i,!0)}_fireEvents(e,t,i){const o=Uf(this._eventsInProgress),s=Uf(e),r={};for(const t in e){const{originalEvent:i}=e[t];this._eventsInProgress[t]||(r[`${t}start`]=i),this._eventsInProgress[t]=e[t]}!o&&s&&this._fireEvent("movestart",s.originalEvent);for(const e in r)this._fireEvent(e,r[e]);s&&this._fireEvent("move",s.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:o}=this._eventsInProgress[e];this._handlersById[i].isActive()||(delete this._eventsInProgress[e],a=t[i]||o,n[`${e}end`]=a)}for(const e in n)this._fireEvent(e,n[e]);const l=Uf(this._eventsInProgress);if(i&&(o||s)&&!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 D("moveend",{originalEvent:a})),t(this._map.getBearing())&&this._map.resetNorth()),this._updatingCamera=!1}}_fireEvent(e,t){this._map.fire(new D(e,t?{originalEvent:t}:{}))}_requestFrame(){return this._map.triggerRepaint(),this._map._renderTaskQueue.add((e=>{this._frameId=void 0,this.handleEvent(new jf("renderFrame",{timeStamp:e})),this._applyChanges()}))}_triggerRenderFrame(){void 0===this._frameId&&(this._frameId=this._requestFrame())}}const qf="map.setFreeCameraOptions(...) and map.getFreeCameraOptions() are not yet supported for non-mercator projections.";class Zf extends E{constructor(e,t){super(),this._moving=!1,this._zooming=!1,this.transform=e,this._bearingSnap=t.bearingSnap,this._respectPrefersReducedMotion=!1!==t.respectPrefersReducedMotion,nt(["_renderFrameCallback"],this)}getCenter(){return new tt(this.transform.center.lng,this.transform.center.lat)}setCenter(e,t){return this.jumpTo({center:e},t)}panBy(e,t,i){return e=r.convert(e).mult(-1),this.panTo(this.transform.center,Object.assign({offset:e},t),i)}panTo(e,t,i){return this.easeTo(Object.assign({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(Object.assign({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(Object.assign({bearing:e},t),i)}resetNorth(e,t){return this.rotateTo(0,Object.assign({duration:1e3},e),t),this}resetNorthPitch(e,t){return this.easeTo(Object.assign({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}cameraForBounds(e,t){e=He.convert(e);const i=t&&t.bearing||0,o=t&&t.pitch||0,s=e.getNorthWest(),r=e.getSouthEast();return this._cameraForBounds(this.transform,s,r,i,o,t)}_extendPadding(e){const t={top:0,right:0,bottom:0,left:0};return null==e?Object.assign({},t,this.transform.padding):"number"==typeof e?{top:e,bottom:e,right:e,left:e}:Object.assign({},t,e)}_extendCameraOptions(e){return(e=Object.assign({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],o=t.max[1]-t.min[1];return i/o>e.aspect?i/(2*Math.tan(.5*e.fovX)*e.aspect):o/(2*Math.tan(.5*e.fovY)*e.aspect)}_cameraForBoundsOnGlobe(e,t,i,o,s,r){const n=e.clone(),a=this._extendCameraOptions(r);n.bearing=o,n.pitch=s;const l=tt.convert(t),c=tt.convert(i),h=.5*(l.lat+c.lat),d=.5*(l.lng+c.lng),_=Wr(h,d),p=Oe([],_),f=Oe([],ei([],p,[0,1,0])),m=ei([],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=[_,Wr(l.lat,l.lng),Wr(c.lat,l.lng),Wr(c.lat,c.lng),Wr(l.lat,c.lng),Wr(h,l.lng),Wr(h,c.lng),Wr(l.lat,d),Wr(c.lat,d)];let y=No.fromPoints(v.map((e=>[ni(f,e),ni(m,e),ni(p,e)])));const x=fe([],y.center,g);0===$r(x)&&Xr(x,0,0,1),Oe(x,x),Si(x,x,Ne),n.center=Yr(x);const b=n.getWorldToCameraMatrix(),w=Lt(new Float64Array(16),b);y=No.applyTransform(y,Be([],b,g));const T=this._extendAABB(y,n,a,o);if(!T)return void u("Map cannot fit within canvas with the given bounds, padding, and/or offset.");y=T,fe(x,x,b);const E=.5*(y.max[2]-y.min[2]),S=this._minimumAABBFrustumDistance(n,y),I=Si([],[0,0,1],E),C=ko(I,x,I),R=S+(0===n.pitch?0:Qt(x,C)),A=n.globeCenterInViewSpace,D=Le([],x,[A[0],A[1],A[2]]);Oe(D,D),Si(D,D,R);const L=ko([],x,D);fe(L,L,w);const O=Mr/Ne,P=ge(L),M=zi(Math.max(P*O-Mr,Number.EPSILON),0),z=Math.min(n.zoomFromMercatorZAdjusted(M),a.maxZoom);return z>.5*(Ro+co)?(n.setProjection({name:"mercator"}),n.zoom=z,this._cameraForBounds(n,t,i,o,s,r)):{center:n.center,zoom:z,bearing:o,pitch:s}}_extendAABB(e,t,i,o){const s=.5*((i.padding.left||0)+(i.padding.right||0)),n=.5*((i.padding.top||0)+(i.padding.bottom||0)),a=n,l=s,c=s,h=n,d=t.width-(l+c),u=t.height-(a+h),_=Le([],e.max,e.min),p=Math.min(d/_[0],u/_[1]),f=Math.min(t.scaleZoom(t.scale*p),i.maxZoom);if(isNaN(f))return null;const m=t.scale/t.zoomScale(f),g=new No([e.min[0]-l*m,e.min[1]-h*m,e.min[2]],[e.max[0]+c*m,e.max[1]+a*m,e.max[2]]),v=("number"==typeof i.offset.x&&"number"==typeof i.offset.y?new r(i.offset.x,i.offset.y):r.convert(i.offset)).rotate(-Ee(o));return g.center[0]-=v.x*m,g.center[1]+=v.y*m,g}queryTerrainElevation(e,t){const i=this.transform.elevation;return i?(t=Object.assign({},{exaggerated:!0},t),i.getAtPoint(pe.fromLngLat(e),null,t.exaggerated)):null}_cameraForBounds(e,t,i,o,s,n){if("globe"===e.projection.name)return this._cameraForBoundsOnGlobe(e,t,i,o,s,n);const a=e.clone(),l=this._extendCameraOptions(n);a.bearing=o,a.pitch=s;const c=tt.convert(t),h=tt.convert(i),d=new tt(c.lng,h.lat),_=new tt(h.lng,c.lat),p=a.project(c),f=a.project(h),m=this.queryTerrainElevation(c),g=this.queryTerrainElevation(h),v=this.queryTerrainElevation(d),y=this.queryTerrainElevation(_),x=[[p.x,p.y,Math.min(m||0,g||0,v||0,y||0)],[f.x,f.y,Math.max(m||0,g||0,v||0,y||0)]];let b=No.fromPoints(x);const w=a.getWorldToCameraMatrix(),T=Lt(new Float64Array(16),w);b=No.applyTransform(b,w);const E=this._extendAABB(b,a,l,o);if(!E)return void u("Map cannot fit within canvas with the given bounds, padding, and/or offset.");b=E;const S=.5*Le([],b.max,b.min)[2],I=this._minimumAABBFrustumDistance(a,b),C=[0,0,1,0];ke(C,C,w),Kr(C,C);const R=Si([],C,I+S),A=ko([],b.center,R);fe(b.center,b.center,T),fe(A,A,T);const D=a.unproject(new r(b.center[0],b.center[1])),L=Qr(a.projection,D),O=Math.pow(2,L),P=Math.min(a._zoomFromMercatorZ(A[2]*a.pixelsPerMeter*O/a.worldSize),l.maxZoom);return a.mercatorFromTransition&&P<.5*(Ro+co)?(a.setProjection({name:"globe"}),a.zoom=P,this._cameraForBounds(a,t,i,o,s,n)):{center:D,zoom:P,bearing:o,pitch:s}}fitBounds(e,t,i){const o=this.cameraForBounds(e,t);return this._fitInternal(o,t,i)}fitScreenCoordinates(e,t,i,o,s){const n=r.convert(e),a=r.convert(t),l=new r(Math.min(n.x,a.x),Math.min(n.y,a.y)),c=new r(Math.max(n.x,a.x),Math.max(n.y,a.y));if("mercator"===this.transform.projection.name&&this.transform.anyCornerOffEdge(n,a))return this;const h=this.transform.pointLocation3D(l),d=this.transform.pointLocation3D(c),u=this.transform.pointLocation3D(new r(l.x,c.y)),_=this.transform.pointLocation3D(new r(c.x,l.y)),p=[Math.min(h.lng,d.lng,u.lng,_.lng),Math.min(h.lat,d.lat,u.lat,_.lat)],f=[Math.max(h.lng,d.lng,u.lng,_.lng),Math.max(h.lat,d.lat,u.lat,_.lat)],m=o&&o.pitch?o.pitch:this.getPitch(),g=this._cameraForBounds(this.transform,p,f,i,m,o);return this._fitInternal(g,o,s)}_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();const i=e.preloadOnly?this.transform.clone():this.transform;let o=!1,s=!1,r=!1;"zoom"in e&&i.zoom!==+e.zoom&&(o=!0,i.zoom=+e.zoom),void 0!==e.center&&(i.center=tt.convert(e.center)),"bearing"in e&&i.bearing!==+e.bearing&&(s=!0,i.bearing=+e.bearing),"pitch"in e&&i.pitch!==+e.pitch&&(r=!0,i.pitch=+e.pitch);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 D("movestart",t)).fire(new D("move",t)),o&&this.fire(new D("zoomstart",t)).fire(new D("zoom",t)).fire(new D("zoomend",t)),s&&this.fire(new D("rotatestart",t)).fire(new D("rotate",t)).fire(new D("rotateend",t)),r&&this.fire(new D("pitchstart",t)).fire(new D("pitch",t)).fire(new D("pitchend",t)),this.fire(new D("moveend",t)))}getFreeCameraOptions(){return this.transform.projection.supportsFreeCamera||u(qf),this.transform.getFreeCameraOptions()}setFreeCameraOptions(e,t){const i=this.transform;if(!i.projection.supportsFreeCamera)return u(qf),this;this.stop();const o=i.zoom,s=i.pitch,r=i.bearing;i.setFreeCameraOptions(e);const n=o!==i.zoom,a=s!==i.pitch,l=r!==i.bearing;return this.fire(new D("movestart",t)).fire(new D("move",t)),n&&this.fire(new D("zoomstart",t)).fire(new D("zoom",t)).fire(new D("zoomend",t)),l&&this.fire(new D("rotatestart",t)).fire(new D("rotate",t)).fire(new D("rotateend",t)),a&&this.fire(new D("pitchstart",t)).fire(new D("pitch",t)).fire(new D("pitchend",t)),this.fire(new D("moveend",t)),this}easeTo(e,t){this._stop(!1,e.easeId),(!1===(e=Object.assign({offset:[0,0],duration:500,easing:Vr},e)).animate||this._prefersReducedMotion(e))&&(e.duration=0);const i=this.transform,o=this.getZoom(),s=this.getBearing(),n=this.getPitch(),a=this.getPadding(),l="zoom"in e?+e.zoom:o,c="bearing"in e?this._normalizeBearing(e.bearing,s):s,h="pitch"in e?+e.pitch:n,d=this._extendPadding(e.padding),u=r.convert(e.offset);let _,p,f;if("globe"===i.projection.name){const t=pe.fromLngLat(i.center),o=u.rotate(-i.angle);t.x+=o.x/i.worldSize,t.y+=o.y/i.worldSize;const s=t.toLngLat(),n=tt.convert(e.center||s);this._normalizeCenter(n),_=i.centerPoint.add(o),p=new r(t.x,t.y).mult(i.worldSize),f=new r(Ge(n.lng),qe(n.lat)).mult(i.worldSize).sub(p)}else{_=i.centerPoint.add(u);const t=i.pointLocation(_),o=tt.convert(e.center||t);this._normalizeCenter(o),p=i.project(t),f=i.project(o).sub(p)}const m=i.zoomScale(l-o);let g,v;e.around&&(g=tt.convert(e.around),v=i.locationPoint(g));const y=this._zooming||l!==o,x=this._rotating||s!==c,b=this._pitching||h!==n,w=!i.isPaddingEqual(d),T=!1===e.retainPadding?i.clone():i,E=i=>r=>{if(y&&(i.zoom=xe(o,l,r)),x&&(i.bearing=xe(s,c,r)),b&&(i.pitch=xe(n,h,r)),w&&(T.interpolatePadding(a,d,r),_=T.centerPoint.add(u)),g)i.setLocationAtPoint(g,v);else{const e=i.zoomScale(i.zoom-o),t=l>o?Math.min(2,m):Math.max(.5,m),s=Math.pow(t,1-r),n=i.unproject(p.add(f.mult(r*s)).mult(e));i.setLocationAtPoint(i.renderWorldCopies?n.wrap():n,_)}return e.preloadOnly||this._fireMoveEvents(t),i};if(e.preloadOnly){const t=this._emulate(E,e.duration,i);return this._preloadTiles(t),this}const S={moving:this._moving,zooming:this._zooming,rotating:this._rotating,pitching:this._pitching};return this._zooming=y,this._rotating=x,this._pitching=b,this._padding=w,this._easeId=e.easeId,this._prepareEase(t,e.noMoveStart,S),this._ease(E(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 D("movestart",e)),this._zooming&&!i.zooming&&this.fire(new D("zoomstart",e)),this._rotating&&!i.rotating&&this.fire(new D("rotatestart",e)),this._pitching&&!i.pitching&&this.fire(new D("pitchstart",e))}_fireMoveEvents(e){this.fire(new D("move",e)),this._zooming&&this.fire(new D("zoom",e)),this._rotating&&this.fire(new D("rotate",e)),this._pitching&&this.fire(new D("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,o=this._rotating,s=this._pitching;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._padding=!1,i&&this.fire(new D("zoomend",e)),o&&this.fire(new D("rotateend",e)),s&&this.fire(new D("pitchend",e)),this.fire(new D("moveend",e))}flyTo(e,t){if(this._prefersReducedMotion(e)){const i=Ve(e,["center","zoom","bearing","pitch","around","padding","retainPadding"]);return this.jumpTo(i,t)}this.stop(),e=Object.assign({offset:[0,0],speed:1.2,curve:1.42,easing:Vr},e);const i=this.transform,o=this.getZoom(),s=this.getBearing(),n=this.getPitch(),a=this.getPadding(),l="zoom"in e?Fe(+e.zoom,i.minZoom,i.maxZoom):o,c="bearing"in e?this._normalizeBearing(e.bearing,s):s,h="pitch"in e?+e.pitch:n,d=this._extendPadding(e.padding),u=i.zoomScale(l-o),_=r.convert(e.offset);let p=i.centerPoint.add(_);const f=i.pointLocation(p),m=tt.convert(e.center||f);this._normalizeCenter(m);const g=i.project(f),v=i.project(m).sub(g);let y=e.curve;const x=Math.max(i.width,i.height),b=x/u,w=v.mag();if("minZoom"in e){const t=Fe(Math.min(e.minZoom,o,l),i.minZoom,i.maxZoom),s=x/i.zoomScale(t-o);y=Math.sqrt(s/w*2)}const T=y*y;function E(e){const t=(b*b-x*x+(e?-1:1)*T*T*w*w)/(2*(e?b:x)*T*w);return Math.log(Math.sqrt(t*t+1)-t)}function S(e){return(Math.exp(e)-Math.exp(-e))/2}function I(e){return(Math.exp(e)+Math.exp(-e))/2}const C=E(0);let R=function(e){return I(C)/I(C+y*e)},A=function(e){return x*((I(C)*(S(t=C+y*e)/I(t))-S(C))/T)/w;var t},D=(E(1)-C)/y;if(Math.abs(w)<1e-6||!isFinite(D)){if(Math.abs(x-b)<1e-6)return this.easeTo(e,t);const i=b<x?-1:1;D=Math.abs(Math.log(b/x))/y,A=function(){return 0},R=function(e){return Math.exp(i*y*e)}}e.duration="duration"in e?+e.duration:1e3*D/("screenSpeed"in e?+e.screenSpeed/y:+e.speed),e.maxDuration&&e.duration>e.maxDuration&&(e.duration=0);const L=s!==c,O=h!==n,P=!i.isPaddingEqual(d),M=!1===e.retainPadding?i.clone():i,z=i=>r=>{const u=r*D,f=1/R(u);i.zoom=1===r?l:o+i.scaleZoom(f),L&&(i.bearing=xe(s,c,r)),O&&(i.pitch=xe(n,h,r)),P&&(M.interpolatePadding(a,d,r),p=M.centerPoint.add(_));const y=1===r?m:i.unproject(g.add(v.mult(A(u))).mult(f));return i.setLocationAtPoint(i.renderWorldCopies?y.wrap():y,p),i._updateCameraOnTerrain(),e.preloadOnly||this._fireMoveEvents(t),i};if(e.preloadOnly){const t=this._emulate(z,e.duration,i);return this._preloadTiles(t),this}return this._zooming=!0,this._rotating=L,this._pitching=O,this._padding=P,this._prepareEase(t,!1),this._ease(z(i),(()=>this._afterEase(t)),e),this}isEasing(){return!!this._easeFrameId}stop(){return this._stop()}_requestRenderFrame(e){}_cancelRenderFrame(e){}_stop(e,t){if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),this._easeFrameId=void 0,this._onEaseFrame=void 0),this._onEaseEnd){const e=this._onEaseEnd;this._onEaseEnd=void 0,e.call(this,t)}if(!e){const e=this.handlers;e&&e.stop(!1)}return this}_ease(e,t,i){!1===i.animate||0===i.duration?(e(1),t()):(this._easeStart=w.now(),this._easeOptions=i,this._onEaseFrame=e,this._onEaseEnd=t,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback))}_renderFrameCallback(){const e=Math.min((w.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=di(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&&w.prefersReducedMotion&&!(e&&e.essential)}_emulate(e,t,i){const o=Math.ceil(15*t/1e3),s=[],r=e(i.clone());for(let e=0;e<=o;e++){const t=r(e/o);s.push(t.clone())}return s}_preloadTiles(e,t){}}class Wf{constructor(e={}){this.options=e,nt(["_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 o=Tn("span","mapboxgl-ctrl-icon",this._compactButton);return o.setAttribute("aria-hidden","true"),o.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||a.ACCESS_TOKEN}];if(e){const i=t.reduce(((e,i,o)=>(i.value&&(e+=`${i.key}=${i.value}${o<t.length-1?"&":""}`),e)),"?");e.href=`${a.FEEDBACK_URL}/${i}#${Wp(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 o=t[i];if(o.used){const t=o.getSource();t.attribution&&e.indexOf(t.attribution)<0&&e.push(t.attribution)}}e.sort(((e,t)=>e.length-t.length)),e=e.filter(((t,i)=>{for(let o=i+1;o<e.length;o++)if(e[o].indexOf(t)>=0)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("*")).forEach((e=>{const i=e.textContent||"";if("A"!==e.tagName)return void e.replaceWith(t.createTextNode(i));const o=e.getAttribute("href");if(!o||!/^(https?:|mailto:)/i.test(o))return void e.replaceWith(t.createTextNode(i));const s=t.createElement("a");s.href=o,s.textContent=i,s.rel="noopener nofollow";const r=e.getAttribute("class");r&&(s.className=r),e.replaceWith(s)})),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 $f{constructor(){nt(["_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._sourceCaches;if(0===Object.entries(e).length)return!0;for(const t in e){const i=e[t].getSource();if(i.hasOwnProperty("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 Xf{constructor(){nt(["_onIndoorUpdate"],this)}onAdd(e){return this._map=e,this._container=Tn("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._map.indoor.on("selector-update",(e=>this._onIndoorUpdate(e))),this._container}_createButton(e,t){const i=Tn("button",e,this._container);return i.type="button",i.addEventListener("click",t),i}_createSeparator(){return Tn("div","mapboxgl-ctrl-separator",this._container)}_setButtonTitle(e,t){this._map&&(e.setAttribute("aria-label",t),e.textContent=t)}onRemove(){this._container&&this._container.remove(),this._map&&this._map.indoor&&(this._map.indoor.off("selector-update",this._onIndoorUpdate),this._map=null)}getDefaultPosition(){return"right"}_onIndoorUpdate(e){if(!e||!e.floors)return this._model=e,void(this._container.style.display="none");const t=this._model;this._model=e,this._container.style.display="inline-block",this._container.style.borderRadius="8px",t&&Array.from(this._container.children).forEach((e=>e.remove())),e.floors.length>0&&(this.addBuildingsToggleButton(),this.addCurrentFloors(e.floors,e.activeFloorsVisible),this._updateBuildingsButtonState())}addBuildingsToggleButton(){const e=this._createButton("mapboxgl-ctrl-buildings-toggle",(()=>{const e=this._map;this._model&&e&&e._setIndoorActiveFloorsVisibility(!this._model.activeFloorsVisible)}));Tn("span","mapboxgl-ctrl-icon",e).setAttribute("aria-hidden","true"),e.classList.add("mapboxgl-ctrl-level-button","mapboxgl-ctrl-buildings-toggle"),this._model&&!this._model.activeFloorsVisible&&e.classList.add("mapboxgl-ctrl-level-button-selected"),this._container.append(e),this._createSeparator()}_updateBuildingsButtonState(){const e=this._container.querySelector(".mapboxgl-ctrl-buildings-toggle");e&&this._model&&(this._model.activeFloorsVisible?e.classList.remove("mapboxgl-ctrl-level-button-selected"):e.classList.add("mapboxgl-ctrl-level-button-selected"))}addCurrentFloors(e,t){for(let i=0;i<e.length;i++){const o=e[i],s=this._createButton("mapboxgl-ctrl-level-button",(()=>{this._map._selectIndoorFloor(o.id)}));this._setButtonTitle(s,o.zIndex.toString()),this._model&&o.id===this._model.selectedFloorId&&t&&s.classList.add("mapboxgl-ctrl-level-button-selected"),this._container.append(s),i<e.length-1&&this._createSeparator()}}}class Yf{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 Kf{constructor(e){this.jumpTo(e)}getValue(e){if(e<=this._startTime)return this._start;if(e>=this._endTime)return this._end;const t=gs((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 Qf={"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 D{constructor(e,t,i,o){const{point:s,lngLat:r,originalEvent:n,target:a}=e;super(e.type,{point:s,lngLat:r,originalEvent:n,target:a}),this.preventDefault=()=>{e.preventDefault()},this.id=t,this.interaction=i,this.feature=o}}class em{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 o=t.type;i&&this.filters.set(e,mt(i)),"mouseover"===o&&(o="mouseenter"),"mouseout"===o&&(o="mouseleave");const s=this.interactionsByType.get(o)||new Map;"mouseenter"===o||"mouseleave"===o?(0===this.delegatedInteractions.size&&(this.map.on("mousemove",this.handleMove),this.map.on("mouseout",this.handleOut)),this.delegatedInteractions.set(e,t)):0===s.size&&this.map.on(o,this.handleType),0===s.size&&this.interactionsByType.set(o,s),s.set(e,t),this.typeById.set(e,o)}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,o]of t)o.target&&i.push({targetId:e,target:o.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 u("mouseenter interaction required for mouseleave to work.");const o=Array.from(this.interactionsByType.get(e.type)).reverse(),s=!!t;t=t||this.queryTargets(e.point,o);let r=!1;const n=new Set;for(const a of t){for(const[t,l]of o){if(!l.target)continue;const o=a.variants?a.variants[t]:null;if(o){for(const c of o){if(Pl(c,a,n,t))continue;const o=new cs(a,c),h=Ol(c,a,t);s&&void 0!==o.id&&(o.state=this.map.getFeatureState(o));const d=i?this.prevHoveredFeatures.get(h):null,u=new Jf(e,t,l,o),_=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 o){const{handler:o,target:s}=i;if(!s&&!1!==o(new Jf(e,t,i,null)))break}}}function tm(e,t){if(Array.isArray(e)&&Array.isArray(t)){const i=new Set(e),o=new Set(t);return i.size===o.size&&e.every((e=>o.has(e)))}return Ht(e,t)}const im={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,transformRequest:null,accessToken:null,fadeDuration:300,respectPrefersReducedMotion:!0,crossSourceCollisions:!0,collectResourceTiming:!1,testMode:!1,precompilePrograms:!0,scaleFactor:1,spriteFormat:"auto"},om={showCompass:!0,showZoom:!0,visualizePitch:!1};class sm{constructor(e,t,i=!1){this._clickTolerance=10,this.element=t,this.mouseRotate=new gf({clickTolerance:e.dragRotate._mouseRotate._clickTolerance}),this.map=e,i&&(this.mousePitch=new vf({clickTolerance:e.dragRotate._mousePitch._clickTolerance})),nt(["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,o=this.mouseRotate.mousemoveWindow(e,t),s=o&&o.bearingDelta;if(s&&i.setBearing(i.getBearing()+s),this.mousePitch){const o=this.mousePitch.mousemoveWindow(e,t),s=o&&o.pitchDelta;s&&i.setPitch(i.getPitch()+s)}}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(){An(),window.removeEventListener("mousemove",this.mousemove),window.removeEventListener("mouseup",this.mouseup)}mousedown(e){this.down(Object.assign({},e,{ctrlKey:!0,preventDefault:()=>e.preventDefault()}),On(this.element,e)),window.addEventListener("mousemove",this.mousemove),window.addEventListener("mouseup",this.mouseup)}mousemove(e){this.move(e,On(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=Pn(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=Pn(this.element,e.targetTouches)[0],this.move({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 rm(e,t,i){if(e=new tt(e.lng,e.lat),t){const o=new tt(e.lng-360,e.lat),s=new tt(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(o).distSqr(t)<n&&(a||Math.abs(o.lng-i.center.lng)<r)?e=o:i.locationPoint3D(s).distSqr(t)<n&&(a||Math.abs(s.lng-i.center.lng)<r)&&(e=s)}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 nm={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%)"},am={rotation:0,rotationAlignment:"auto",pitchAlignment:"auto",occludedOpacity:.2,altitude:0};class lm extends E{constructor(e,t){super(),(e instanceof HTMLElement||t)&&(e=Object.assign({element:e},t)),nt(["_update","_onMove","_onUp","_addDragHandler","_onMapClick","_onKeyPress","_clearFadeTimer"],this);const{anchor:i="center",color:o="#3FB1CE",scale:s=1,draggable:n=!1,clickTolerance:a=0,rotation:l=am.rotation,rotationAlignment:c=am.rotationAlignment,pitchAlignment:h=am.pitchAlignment,occludedOpacity:d=am.occludedOpacity,altitude:u=am.altitude}=e||{};this._anchor=i,this._color=o,this._scale=s,this._draggable=n,this._clickTolerance=a,this._rotation=l,this._rotationAlignment=c,this._pitchAlignment=h,this._occludedOpacity=d,this._altitude=u,this._state="inactive",this._isDragging=!1,this._updateMoving=()=>this._update(!0),e&&e.element?(this._element=e.element,this._offset=r.convert(e&&e.offset||[0,0])):(this._defaultMarker=!0,this._element=this._createDefaultMarker(),this._offset=r.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 _=this._element.classList;for(const e in nm)_.remove(`mapboxgl-marker-anchor-${e}`);_.add(`mapboxgl-marker-anchor-${this._anchor}`);const p=e&&e.className?e.className.trim().split(/\s+/):[];_.add(...p),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);if(0===this._altitude){const e=En("radialGradient",{id:"shadowGradient"},En("defs",{},t));En("stop",{offset:"10%","stop-opacity":.4},e),En("stop",{offset:"100%","stop-opacity":.05},e),En("ellipse",{cx:13.5,cy:34.8,rx:10.5,ry:5.25,fill:"url(#shadowGradient)"},t)}return 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=tt.convert(e),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(!0),this}setAltitude(e){return e===this._altitude||(this._defaultMarker&&(0===this._altitude&&0!==e||0!==this._altitude&&0===e)&&(this._element=this._createDefaultMarker()),this._altitude=e||am.altitude,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,o=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":[o,-1*(t-i+o)],"bottom-right":[-o,-1*(t-i+o)],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),o=e.getFreeCameraOptions();if(!o.position)return!1;const s=o.position.toLngLat();return s.distanceTo(i)<.9*s.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 o;e._showingGlobe()&&tn(e.transform,this._lngLat)?o=0:(o=1-e._queryFogOpacity(i),e.transform._terrainEnabled()&&e.getTerrain()&&this._behindTerrain()&&(o*=this._occludedOpacity)),this._element.style.opacity=`${o}`,this._element.style.pointerEvents=o>0?"auto":"none",this._popup&&this._popup._setOpacity(o),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 ${nm[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 o=To(on(t.transform,this._lngLat)),s=e.sub(sn(t.transform)),r=Math.abs(s.x)+Math.abs(s.y);if(0===r)return"";const n=o/r;return`rotateX(${-s.y*n}deg) rotateY(${s.x*n}deg)`}_calculateZTransform(){const e=this._pos,t=this._map;if(!t||!e)return"";let i=0;const o=this.getRotationAlignment();if("map"===o)if(t._showingGlobe()){const e=t.project(new tt(this._lngLat.lng,this._lngLat.lat+.001),this._altitude),o=t.project(new tt(this._lngLat.lng,this._lngLat.lat-.001),this._altitude).sub(e);i=To(Math.atan2(o.y,o.x))-90}else i=-t.getBearing();else if("horizon"===o){const o=me(4,6,t.getZoom()),s=sn(t.transform);s.y+=o*t.transform.height;const r=e.sub(s),n=To(Math.atan2(r.y,r.x));i=(n>90?n-270:n+90)*(1-o)}return i+=this._rotation,i?`rotateZ(${i}deg)`:""}_update(e){cancelAnimationFrame(this._updateFrameId);const t=this._map;t&&(t.transform.renderWorldCopies&&(this._lngLat=rm(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.getTerrain()||t.getFog())&&!this._fadeTimer&&(this._fadeTimer=window.setTimeout(this._evaluateOpacity.bind(this),60)))})))}getOffset(){return this._offset}setOffset(e){return this._offset=r.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,o=this._positionDelta;if(i&&o){if(!this._isDragging){const o=this._clickTolerance||t._clickTolerance;if(e.point.dist(i)<o)return;this._isDragging=!0}this._pos=e.point.sub(o),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 D("dragstart"))),this.fire(new D("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 D("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||am.rotation,this._update(),this}getRotation(){return this._rotation}setRotationAlignment(e){return this._rotationAlignment=e||am.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||am.pitchAlignment,this._update(),this}getPitchAlignment(){return"auto"===this._pitchAlignment?this.getRotationAlignment():this._pitchAlignment}setOccludedOpacity(e){return this._occludedOpacity=e||am.occludedOpacity,this._update(),this}getOccludedOpacity(){return this._occludedOpacity}}const cm={positionOptions:{enableHighAccuracy:!1,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showAccuracyCircle:!0,showUserLocation:!0,showUserHeading:!1},hm={maxWidth:100,unit:"metric"},dm={kilometer:"km",meter:"m",mile:"mi",foot:"ft","nautical-mile":"nm"},um={closeButton:!0,closeOnClick:!0,focusAfterOpen:!0,className:"",maxWidth:"240px",altitude:0},_m=["a[href]","[tabindex]:not([tabindex='-1'])","[contenteditable]:not([contenteditable='false'])","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])"].join(", ");function pm(e=new r(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 r(0,e);case"top-left":return new r(i,i);case"top-right":return new r(-i,i);case"bottom":return new r(0,-e);case"bottom-left":return new r(i,-i);case"bottom-right":return new r(-i,-i);case"left":return new r(e,0);case"right":return new r(-e,0)}return new r(0,0)}return e instanceof r||Array.isArray(e)?r.convert(e):r.convert(e[t]||[0,0])}const fm={version:mn,supported:wn.supported,setRTLTextPlugin:ln,getRTLTextPluginStatus:an,Map:class extends Zf{constructor(e){vn.mark(gn.create);const t=e;if(null!=(e=Object.assign({},im,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");if(e.antialias&&Jr(window)&&(e.antialias=!1,u("Antialiasing is disabled for this WebGL context to avoid browser bug: https://github.com/mapbox/mapbox-gl-js/issues/11609")),super(new Eh(e.minZoom,e.maxZoom,e.minPitch,e.maxPitch,e.renderWorldCopies,null,null),e),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._isInitialLoad=!0,this._crossSourceCollisions=e.crossSourceCollisions,this._collectResourceTiming=e.collectResourceTiming,this._language=this._parseLanguage(e.language),this._worldview=e.worldview,this._renderTaskQueue=new Yf,this._domRenderTaskQueue=new Yf,this._controls=[],this._markers=[],this._popups=[],this._mapId=ut(),this._locale=Object.assign({},Qf,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._scaleFactorChanged=!1,this._averageElevationLastSampledAt=-1/0,this._averageElevationExaggeration=0,this._averageElevation=new Kf(0),this._interactionRange=[1/0,-1/0],this._visibilityHidden=0,this._useExplicitProjection=!1,this._frameId=0,this._scaleFactor=e.scaleFactor,this._requestManager=new kn(e.transformRequest,e.accessToken,e.testMode),this._silenceAuthErrors=!!e.testMode,this._contextCreateOptions=e.contextCreateOptions?Object.assign({},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&&u("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=e.spriteFormat,nt(["_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 Hf(this,e),this._localFontFamily=e.localFontFamily,this._localIdeographFontFamily=e.localIdeographFontFamily,(e.style||!e.testMode)&&this.setStyle(e.style||a.DEFAULT_STYLE,{config:e.config,localFontFamily:this._localFontFamily,localIdeographFontFamily:this._localIdeographFontFamily}),e.projection&&this.setProjection(e.projection),e.hash&&(this._hash=new Zp("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,Object.assign({},e.fitBoundsOptions,{duration:0})))}this.resize(),e.attributionControl&&this.addControl(new Wf({customAttribution:e.customAttribution})),this._logoControl=new $f,this.addControl(this._logoControl,e.logoPosition),this.on("style.load",(()=>{this.transform.unmodified&&this.jumpTo(this.style.stylesheet),this._postStyleLoadEvent(),this._postStyleWithAppearanceEvent(),this._setupIndoor()})),this.on("data",(e=>{this._update("style"===e.dataType),this.fire(new D(`${e.dataType}data`,e))})),this.on("dataloading",(e=>{this.fire(new D(`${e.dataType}dataloading`,e))})),this._interactions=new em(this)}_getMapId(){return this._mapId}addControl(e,t){if(void 0===t&&(t=e.getDefaultPosition?e.getDefaultPosition():"top-right"),!e||!e.onAdd)return this.fire(new A(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));const i=e.onAdd(this);this._controls.push(e);const o=this._controlPositions[t];return-1!==t.indexOf("bottom")?o.insertBefore(i,o.firstChild):o.appendChild(i),this}removeControl(e){if(!e||!e.onRemove)return this.fire(new A(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.indexOf(e)>-1}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 D("movestart",e)).fire(new D("move",e)),this.fire(new D("resize",e)),t&&this.fire(new D("moveend",e)),this}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()||null}setMaxBounds(e){return this.transform.setMaxBounds(He.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 D("zoomstart")).fire(new D("zoom")).fire(new D("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 D("zoomstart")).fire(new D("zoom")).fire(new D("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 D("pitchstart")).fire(new D("pitch")).fire(new D("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 D("pitchstart")).fire(new D("pitch")).fire(new D("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._scaleFactorChanged=!0,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.reloadSources(),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>=co?(e.setMercatorFromTransition(),i=!0):"mercator"===t&&e.zoom<co&&(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>=co?this.transform.setMercatorFromTransition():this.transform.setProjection(e),this.style.applyProjectionUpdate();const o="mercator"===this.transform.getProjection().name&&i!==this.transform.mercatorFromTransition;return(t||o)&&(this.painter.clearBackgroundTiles(),this.style.clearSources(),this._update(!0),this._forceMarkerAndPopupUpdate(!0)),this}project(e,t){return this.transform.locationPoint3D(tt.convert(e),t)}unproject(e,t){return this.transform.pointLocation3D(r.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 o=e=>{let i=[];if(Array.isArray(t)){const o=t.filter((e=>this.getLayer(e)));i=o.length?this.queryRenderedFeatures(e,{layers:o}):[]}else i=this.queryRenderedFeatures(e,{target:t});return i};if("mouseenter"===e||"mouseover"===e){let s=!1;const r=t=>{const r=o(t.point);r.length?s||(s=!0,i.call(this,new of(e,this,t.originalEvent,{features:r}))):s=!1};return{listener:i,targets:t,delegates:{mousemove:r,mouseout:()=>{s=!1}}}}if("mouseleave"===e||"mouseout"===e){let s=!1;const r=t=>{o(t.point).length?s=!0:s&&(s=!1,i.call(this,new of(e,this,t.originalEvent)))},n=t=>{s&&(s=!1,i.call(this,new of(e,this,t.originalEvent)))};return{listener:i,targets:t,delegates:{mousemove:r,mouseout:n}}}{const s=e=>{const t=o(e.point);t.length&&(e.features=t,i.call(this,e),delete e.features)};return{listener:i,targets:t,delegates:{[e]:s}}}}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 o=this._createDelegatedListener(e,t,i);this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[e]=this._delegatedListeners[e]||[],this._delegatedListeners[e].push(o);for(const e in o.delegates)this.on(e,o.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 o=this._createDelegatedListener(e,t,i);for(const e in o.delegates)this.once(e,o.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 o=this._delegatedListeners?this._delegatedListeners[e]:void 0;return o&&(e=>{for(let o=0;o<e.length;o++){const s=e[o];if(s.listener===i&&tm(s.targets,t)){for(const e in s.delegates)this.off(e,s.delegates[e]);return e.splice(o,1),this}}})(o),this}queryRenderedFeatures(e,t){if(!this.style)return[];if(void 0===e||e instanceof r||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 o=!0;if(t.layers&&Array.isArray(t.layers)){for(const e of t.layers)if(!this._isValidId(e)){o=!1;break}if(o&&!t.target)return this.style.queryRenderedFeatures(e,t,this.transform)}let s=[];return o&&(s=s.concat(this.style.queryRenderedFeatures(e,t,this.transform))),i&&(s=s.concat(this.style.queryRenderedFeatureset(e,t,this.transform))),s}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&&u(`${t} projection does not support isPointOnSurface, this API may behave unexpectedly.`),this.transform.isPointOnSurface(r.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=Object.assign({},{localIdeographFontFamily:this._localIdeographFontFamily,localFontFamily:this._localFontFamily},t),this.style&&e&&!1!==t.diff&&t.localFontFamily===this._localFontFamily&&t.localIdeographFontFamily===this._localIdeographFontFamily&&!t.config?(this.style._diffStyle(e,((i,o)=>{if(i){const o="string"==typeof i?i:i instanceof Error?i.message:i.error;u(`Unable to perform style diff: ${o}. Rebuilding the style from scratch.`),this._updateStyle(e,t)}else o&&this._update(!0)}),(()=>this._postStyleLoadEvent())),this):(this._localIdeographFontFamily=t.localIdeographFontFamily,this._localFontFamily=t.localFontFamily,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=Object.assign({},t);t&&t.config&&(i.initialConfig=t.config,delete i.config),this.style=new Zh(this,i).load(e),this.style.setEventedParent(this,{style:this.style})}return this._updateTerrain(),this}_lazyInitEmptyStyle(){this.style||(this.style=new Zh(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():(u("There is no style added to the map."),!1)}_isValidId(e){return null==e?(this.fire(new A(new Error("IDs can't be empty."))),!1):!os(e)||(this.fire(new A(new Error(`IDs can't contain special symbols: "${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()}addSourceType(e,t,i){this._lazyInitEmptyStyle(),this.style.addSourceType(e,t,i)}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:o=!1,stretchX:s,stretchY:r,content:n}={}){this._lazyInitEmptyStyle();const a=v.from(e);if(t instanceof HTMLImageElement||ImageBitmap&&t instanceof ImageBitmap){const{width:e,height:l,data:c}=w.getImageData(t);this.style.addImage(a,{data:new T({width:e,height:l},c),pixelRatio:i,stretchX:s,stretchY:r,content:n,sdf:o,version:0,usvg:!1})}else if(void 0===t.width||void 0===t.height)this.fire(new A(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 T({width:l,height:c},new Uint8Array(h.data)),pixelRatio:i,stretchX:s,stretchY:r,content:n,sdf:o,usvg:!1,version:0,userImage:h}),h.onAdd&&h.onAdd(this,e)}}updateImage(e,t){this._lazyInitEmptyStyle();const i=v.from(e),o=this.style.getImage(i);if(!o)return void this.fire(new A(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));const s=t instanceof HTMLImageElement||ImageBitmap&&t instanceof ImageBitmap?w.getImageData(t):t,{width:r,height:n,data:a}=s;if(void 0===r||void 0===n)return void this.fire(new A(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!==(o.usvg?o.icon.usvg_tree.width:o.data.width)||n!==(o.usvg?o.icon.usvg_tree.height:o.data.height))return void this.fire(new A(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 (${o.data.width}, ${o.data.height})`)));const l=!(t instanceof HTMLImageElement||ImageBitmap&&t instanceof ImageBitmap);let c=!1;o.usvg?(o.data=new T({width:r,height:n},new Uint8Array(a)),o.usvg=!1,o.icon=void 0,c=!0):o.data.replace(a,l),this.style.updateImage(i,o,c)}hasImage(e){return e?!!this.style&&!!this.style.getImage(v.from(e)):(this.fire(new A(new Error("Missing required image id"))),!1)}removeImage(e){this.style.removeImage(v.from(e))}loadImage(e,t){b(this._requestManager.transformRequest(e,x.Image),((e,i)=>{t(e,i instanceof HTMLImageElement?w.getImageData(i):i)}))}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 A(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.style.addImport(e,t).catch((e=>this.fire(new A(new Error("Failed to add import",e))))),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){return 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){return this._isValidId(e)?(this.style.removeLayer(e),this._update(!0)):this}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,o={}){return this._isValidId(e)?(this.style.setPaintProperty(e,t,i,o),this._update(!0)):this}getPaintProperty(e,t){return this._isValidId(e)?this.style.getPaintProperty(e,t):null}setLayoutProperty(e,t,i,o={}){return this._isValidId(e)?(this.style.setLayoutProperty(e,t,i,o),this._update(!0)):this}getLayoutProperty(e,t){return this._isValidId(e)?this.style.getLayoutProperty(e,t):null}setLayerProperty(e,t,i,o={}){return this._isValidId(e)?("appearances"===t&&this._postAddingAppearancesToStyleEvent(),this.style.setLayerProperty(e,t,i,o),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)}_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(tt.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)}_selectIndoorFloor(e){this.indoor.selectFloor(e)}_setIndoorActiveFloorsVisibility(e){this.indoor.setActiveFloorsVisibility(e)}_addIndoorControl(){this._indoorControl||(this._indoorControl=new Xf),this.addControl(this._indoorControl,"right")}_removeIndoorControl(){this._indoorControl&&this.removeControl(this._indoorControl)}_updateContainerDimensions(){if(!this._container)return;const e=this._container.getBoundingClientRect().width||400,t=this._container.getBoundingClientRect().height||300;let i,o,s,r=this._container;for(;r&&(!o||!s);){const e=window.getComputedStyle(r).transform;e&&"none"!==e&&(i=e.match(/matrix.*\((.+)\)/)[1].split(", "),i[0]&&"0"!==i[0]&&"1"!==i[0]&&(o=i[0]),i[3]&&"0"!==i[3]&&"1"!==i[3]&&(s=i[3])),r=r.parentElement}this._containerWidth=o?Math.abs(e/o):e,this._containerHeight=s?Math.abs(t/s):t}_detectMissingCSS(){"rgb(250, 128, 114)"!==window.getComputedStyle(this._missingCSSCanary).getPropertyValue("background-color")&&u("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/.")}_setupIndoor(){this.style.isIndoorEnabled()&&(this.indoor=new Wh(this.style),this.on("load",(()=>{this._addIndoorControl(),this.indoor._updateUI(this.transform.zoom,this.transform.center,this.transform.getBounds()),this.on("move",(()=>{this.indoor._updateUI(this.transform.zoom,this.transform.center,this.transform.getBounds())})),this.on("idle",(()=>{this.indoor._updateUI(this.transform.zoom,this.transform.center,this.transform.getBounds())}))})))}_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),o=this._controlPositions={};["top-left","top","top-right","right","bottom-right","bottom","bottom-left","left"].forEach((e=>{o[e]=Tn("div",`mapboxgl-ctrl-${e}`,i)})),this._container.addEventListener("scroll",this._onMapScroll,!1)}_resizeCanvas(e,t){const i=w.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=Object.assign({},wn.supported.webGLContextAttributes,{failIfMajorPerformanceCaveat:this._failIfMajorPerformanceCaveat,preserveDrawingBuffer:this._preserveDrawingBuffer,antialias:this._antialias||!1}),t=this._canvas.getContext("webgl2",e);t?(aa(t,!0),this.painter=new Hp(t,this._contextCreateOptions,this.transform,this._scaleFactor,this._worldview),this.on("data",(e=>{"source"===e.dataType&&this.painter.setTileLoadedFlag(!0)})),m.testSupport(t)):this.fire(new A(new Error("Failed to initialize WebGL")))}_contextLost(e){e.preventDefault(),this._frame&&(this._frame.cancel(),this._frame=null),this.fire(new D("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.reloadModels(),this.style.clearSources()),this._update(),this.fire(new D("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 D("renderstart")),++this._frameId;const i=this.painter.context.extTimerQuery,o=w.now(),s=this.painter.context.gl;if(this.listens("gpu-timing-frame")&&(t=s.createQuery(),s.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=w.now(),o=new ue(e,{now:i,fadeDuration:r,pitch:t,transition:this.style.transition,worldview:this._worldview});this.style.update(o)}this.style&&this.style.hasFogTransition()&&(this.style._markersNeedUpdate=!0,this._sourcesDirty=!0);let n=!1;this.style&&this._sourcesDirty?(this._sourcesDirty=!1,this.painter._updateFog(this.style),this._updateTerrain(),n=this._updateAverageElevation(o),this.style.updateSources(this.transform),this.style.updateImageProviders(),this.isMoving()||this._forceMarkerAndPopupUpdate()):n=this._updateAverageElevation(o);const a=this.style&&this.style._updatePlacement(this.painter,this.painter.transform,this.showCollisionBoxes,r,this._crossSourceCollisions,this.painter.replacementSource,this._scaleFactorChanged);if(this._scaleFactorChanged&&(this._scaleFactorChanged=!1),a&&(this._placementDirty=a.needsRerender),this.style&&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}),this.fire(new D("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,vn.mark(gn.load),this.fire(new D("load"))),this.style&&this.style.hasTransitions()&&(this._styleDirty=!0),this.style&&(this.style.snow||this.style.rain)&&(this._styleDirty=!0),this.style&&this.style.imageManager.hasPatternsInFlight()&&(this._styleDirty=!0),this.style&&!this.style.modelManager.isLoaded()&&(this._styleDirty=!0),this.style&&!this._placementDirty&&this.style._releaseSymbolFadeTiles(),t){const e=w.now()-o;s.endQuery(i.TIME_ELAPSED_EXT),setTimeout((()=>{const i=s.getQueryParameter(t,s.QUERY_RESULT)/1e6;s.deleteQuery(t),this.fire(new D("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 D("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 D("gpu-timing-deferred-render",{gpuTime:t}))}),50)}const l=this._sourcesDirty||this._styleDirty||this._placementDirty||n;if(l||this._repaint)this.triggerRepaint();else{const e=this.idle();if(e&&(n=this._updateAverageElevation(o,!0)),n)this.triggerRepaint();else if(this._triggerFrame(!1),e&&(this.fire(new D("idle")),this._isInitialLoad=!1,this.speedIndexTiming)){const e=this._calculateSpeedIndex();this.fire(new D("speedindexcompleted",{speedIndex:e})),this.speedIndexTiming=!1}}!this._loaded||this._fullyLoaded||l||(this._fullyLoaded=!0,vn.mark(gn.fullLoad),this._performanceMetricsCollection&&oa(this._requestManager._customAccessToken,{width:this.painter.width,height:this.painter.height,interactionRange:this._interactionRange,visibilityHidden:this._visibilityHidden,terrainEnabled:!!this.painter.style.getTerrain(),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 o=this.transform.elevation&&this.transform.elevation.exaggeration()!==this._averageElevationExaggeration;if(o||(t||e-this._averageElevationLastSampledAt>500)&&!this._averageElevation.isEasing(e)){const t=this.transform.averageElevation;let s=this.transform.sampleAverageElevation();null!=this.transform.elevation&&(this._averageElevationExaggeration=this.transform.elevation.exaggeration()),isNaN(s)?s=0:this._averageElevationLastSampledAt=e;const r=Math.abs(t-s);if(r>1){if(this._isInitialLoad||o)return this._averageElevation.jumpTo(s),i(s);this._averageElevation.easeTo(s,e,300)}else if(r>1e-4)return this._averageElevation.jumpTo(s),i(s)}return!!this._averageElevation.isEasing(e)&&i(this._averageElevation.getValue(e))}_authenticate(){ra(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,(e=>{if(e&&(e.message===Bn||401===e.status)){const e=this.painter.context.gl;aa(e,!1),this._logoControl instanceof $f&&this._logoControl._updateLogo(),e&&e.clear(e.DEPTH_BUFFER_BIT|e.COLOR_BUFFER_BIT|e.STENCIL_BUFFER_BIT),this._silenceAuthErrors||this.fire(new A(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/")))}})),Xn(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,(()=>{}))}_postStyleLoadEvent(){this.style.globalId&&Kn(this._requestManager._customAccessToken,{map:this,style:this.style.globalId,importedStyles:this.style.getImportGlobalIds()})}_postStyleWithAppearanceEvent(){this.style.globalId&&this.style.hasAppearances()&&Jn(this._requestManager._customAccessToken)}_postAddingAppearancesToStyleEvent(){ta(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,o=i.createFramebuffer();function s(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,o),this._canvasPixelComparison(s(e),t.canvasCopies.map(s),t.timeStamps)}_canvasPixelComparison(e,t,i){let o=i[1]-i[0];const s=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);o+=(i[r+2]-i[r+1])*(1-a/s)}return o}remove(){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.indoor&&this.indoor.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),na.delete(this.painter.context.gl),sa.remove(),$n.remove(),this._removed=!0,this.fire(new D("remove"))}triggerRepaint(){this._triggerFrame(!0)}_triggerFrame(e){this._renderNextFrame=this._renderNextFrame||e,this.style&&!this._frame&&(this._frame=w.frame((e=>{const t=!!this._renderNextFrame;this._frame=null,this._renderNextFrame=null,t&&this._render(e)})))}_preloadTiles(e){const t=this.style?this.style.getSourceCaches():[];return Gt(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,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 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,this._update())}get showCollisionBoxes(){return!!this._showCollisionBoxes}set showCollisionBoxes(e){this._showCollisionBoxes!==e&&(this._showCollisionBoxes=e,this.style&&e?this.style._generateCollisionBoxes():this._update())}get showOverdrawInspector(){return!!this._showOverdrawInspector}set showOverdrawInspector(e){this._showOverdrawInspector!==e&&(this._showOverdrawInspector=e,this._update())}get repaint(){return!!this._repaint}set repaint(e){this._repaint!==e&&(this._repaint=e,this.triggerRepaint())}get vertices(){return!!this._vertices}set vertices(e){this._vertices=e,this._update()}get showTileAABBs(){return!!this._showTileAABBs}set showTileAABBs(e){this._showTileAABBs!==e&&(this._showTileAABBs=e,e&&this._update())}_setCacheLimits(e,t){en(e,t)}get version(){return mn}},NavigationControl:class{constructor(e={}){this.options=Object.assign({},om,e),this._container=Tn("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.addEventListener("contextmenu",(e=>e.preventDefault())),this.options.showZoom&&(nt(["_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&&(nt(["_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(),o=t===e.getMinZoom();this._zoomInButton.disabled=i,this._zoomOutButton.disabled=o,this._zoomInButton.setAttribute("aria-disabled",i.toString()),this._zoomOutButton.setAttribute("aria-disabled",o.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 sm(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)}},GeolocateControl:class extends E{constructor(e={}){super();const t=navigator.geolocation;this.options=Object.assign({geolocation:t},cm,e),nt(["_onSuccess","_onError","_onZoom","_finish","_setupUI","_updateCamera","_updateMarker","_updateMarkerRotation","_onDeviceOrientation"],this),this._updateMarkerRotationThrottled=qp(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(){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())}_setErrorState(){switch(this._watchState){case"WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting");break;case"BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting")}}_onSuccess(e){if(this._map){if(this._isOutOfMapMaxBounds(e))return this._setErrorState(),this.fire(new D("outofmaxbounds",e)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=e,this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"BACKGROUND":case"BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background")}this.options.showUserLocation&&"OFF"!==this._watchState&&this._updateMarker(e),this.options.trackUserLocation&&"ACTIVE_LOCK"!==this._watchState||this._updateCamera(e),this.options.showUserLocation&&this._userLocationDotMarker.removeClassName("mapboxgl-user-location-dot-stale"),this.fire(new D("geolocate",Object.assign({coords:e.coords,timestamp:e.timestamp},e.toJSON?{toJSON:e.toJSON.bind(e)}:{}))),this._finish()}}_updateCamera(e){const t=new tt(e.coords.longitude,e.coords.latitude),i=e.coords.accuracy,o=this._map.getBearing(),s=Object.assign({bearing:o},this.options.fitBoundsOptions);this._map.fitBounds(t.toBounds(i),s,{geolocateSource:!0})}_updateMarker(e){if(e){const t=new tt(e.coords.longitude,e.coords.latitude);this._accuracyCircleMarker.setLngLat(t).addTo(this._map),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=zi(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.options.trackUserLocation)if(1===e.code){this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.disabled=!0;const e=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.setAttribute("aria-label",e),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",e),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 D("error",e)),this._finish()}}_finish(){this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0}_setupUI(e){if(void 0!==this._map){if(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){u("Geolocation support is not available so the GeolocateControl will be disabled.");const e=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=!0,this._geolocateButton.setAttribute("aria-label",e),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",e)}else{const e=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.setAttribute("aria-label",e),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",e)}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(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 lm({element:this._dotElement,rotationAlignment:"map",pitchAlignment:"map"}),this._circleElement=Tn("div","mapboxgl-user-location-accuracy-circle"),this._accuracyCircleMarker=new lm({element:this._circleElement,pitchAlignment:"map"}),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.trackUserLocation&&this._map.on("movestart",(e=>{e.geolocateSource||"ACTIVE_LOCK"!==this._watchState||e.originalEvent&&"resize"===e.originalEvent.type||(this._watchState="BACKGROUND",this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this.fire(new D("trackuserlocationend")))}))}}_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 u("Geolocate control triggered before added to a map"),!1;if(this.options.trackUserLocation){switch(this._watchState){case"OFF":this._watchState="WAITING_ACTIVE",this.fire(new D("trackuserlocationstart"));break;case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":case"BACKGROUND_ERROR":this._numberOfWatches--,this._noTimeout=!1,this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this.fire(new D("trackuserlocationend"));break;case"BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new D("trackuserlocationstart"))}switch(this._watchState){case"WAITING_ACTIVE":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_LOCK":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"BACKGROUND":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background");break;case"BACKGROUND_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error")}if("OFF"===this._watchState&&void 0!==this._geolocationWatchID)this._clearWatch();else if(void 0===this._geolocationWatchID){let e;this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-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.options.showUserHeading&&this._addDeviceOrientationListener()}}else this.options.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._timeoutId=window.setTimeout(this._finish,1e4);return!0}_addDeviceOrientationListener(){const e=()=>{"ondeviceorientationabsolute"in window?window.addEventListener("deviceorientationabsolute",this._onDeviceOrientation):window.addEventListener("deviceorientation",this._onDeviceOrientation)};"undefined"!=typeof DeviceMotionEvent&&"function"==typeof DeviceMotionEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((t=>{"granted"===t&&e()})).catch(console.error):e()}_clearWatch(){this.options.geolocation.clearWatch(this._geolocationWatchID),window.removeEventListener("deviceorientation",this._onDeviceOrientation),window.removeEventListener("deviceorientationabsolute",this._onDeviceOrientation),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null)}},AttributionControl:Wf,ScaleControl:class{constructor(e={}){this.options=Object.assign({},hm,e),nt(["_update","_setScale","setUnit"],this)}getDefaultPosition(){return"bottom-left"}_update(){const e=this.options.maxWidth||100,t=this._map,i=t._containerHeight/2,o=t._containerWidth/2-e/2,s=t.unproject([o,i]),r=t.unproject([o+e,i]),n=s.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 o=function(e){const t=Math.pow(10,`${Math.floor(e)}`.length-1);let i=e/t;return i=i>=10?10:i>=5?5:i>=3?3:i>=2?2:i>=1?1:function(e){const t=Math.pow(10,Math.ceil(-Math.log(e)/Math.LN10));return Math.round(e*t)/t}(i),t*i}(t),s=o/t;this._container.innerHTML="nautical-mile"!==i?new Intl.NumberFormat(this._language,{style:"unit",unitDisplay:"short",unit:i}).format(o):`${o} ${dm[i]}`,this._container.style.width=e*s+"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()}},FullscreenControl:class{constructor(e={}){this._fullscreen=!1,e&&e.container&&(e.container instanceof HTMLElement?this._container=e.container:u("Full screen control 'container' must be a DOM element.")),nt(["_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",u("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()}},IndoorControl:Xf,Popup:class extends E{constructor(e){super(),this.options=Object.assign(Object.create(um),e),this._altitude=this.options.altitude,nt(["_update","_onClose","remove","_onMouseEvent"],this),this._classList=new Set(e&&e.className?e.className.trim().split(/\s+/):[])}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 D("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 D("close")),this}getLngLat(){return this._lngLat}setLngLat(e){this._lngLat=tt.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 o;for(i.innerHTML=e;o=i.firstChild,o;)t.appendChild(o);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">×</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,o=this._pos;if(!t||!i||!o)return"bottom";const s=i.offsetWidth,r=i.offsetHeight,n=o.x<s/2,a=o.x>t.transform.width-s/2;if(o.y+e<r)return n?"top-left":a?"top-right":"top";if(o.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 o=this._container;if(o||(o=this._container=Tn("div","mapboxgl-popup",t.getContainer()),this._tip=Tn("div","mapboxgl-popup-tip",o),o.appendChild(i)),this.options.maxWidth&&o.style.maxWidth!==this.options.maxWidth&&(o.style.maxWidth=this.options.maxWidth),t.transform.renderWorldCopies&&!this._trackPointer&&(this._lngLat=rm(this._lngLat,this._pos,t.transform)),!this._trackPointer||e){const i=this._pos=this._trackPointer&&e instanceof r?e:t.project(this._lngLat,this._altitude),o=pm(this.options.offset),s=this._anchor=this._getAnchor(o.y),n=pm(this.options.offset,s),a=i.add(n).round();t._requestDomTask((()=>{this._container&&s&&(this._container.style.transform=`${nm[s]} translate(${a.x}px,${a.y}px)`)}))}if(!this._marker&&t._showingGlobe()){const e=tn(t.transform,this._lngLat)?0:1;this._setOpacity(e)}this._updateClassList()}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const e=this._container.querySelector(_m);e&&e.focus()}_onClose(){this.remove()}_setOpacity(e){this._container&&(this._container.style.opacity=`${e}`),this._content&&(this._content.style.pointerEvents=e?"auto":"none")}},Marker:lm,Style:Zh,LngLat:tt,LngLatBounds:He,Point:r,MercatorCoordinate:pe,FreeCameraOptions:yh,Evented:E,config:a,prewarm:nn,clearPrewarmedResources:rn,get accessToken(){return a.ACCESS_TOKEN},set accessToken(e){a.ACCESS_TOKEN=e},get baseApiUrl(){return a.API_URL},set baseApiUrl(e){a.API_URL=e},get workerCount(){return fn.workerCount},set workerCount(e){fn.workerCount=e},get maxParallelImageRequests(){return a.MAX_PARALLEL_IMAGE_REQUESTS},set maxParallelImageRequests(e){a.MAX_PARALLEL_IMAGE_REQUESTS=e},clearStorage(e){pn(e)},get workerUrl(){return _n.workerUrl},set workerUrl(e){_n.workerUrl=e},get workerClass(){return _n.workerClass},set workerClass(e){_n.workerClass=e},get workerParams(){return _n.workerParams},set workerParams(e){_n.workerParams=e},get dracoUrl(){return un()},set dracoUrl(e){dn(e)},get meshoptUrl(){return hn()},set meshoptUrl(e){cn(e)},setNow:w.setNow,restoreNow:w.restoreNow};export{fm as default};//# sourceMappingURL=mapbox-gl.js.map
|