(function(r){const e={},t={};function s(o,p,d){if(t[o]=d,o==="index"){var i="var sharedModule = {}; ("+t.shared+")(sharedModule); ("+t.worker+")(sharedModule);";typeof exports=="object"&&typeof module=="object"?module.exports=e:typeof exports=="object"?exports.mapgl=e:r.mapgl=e;var n={};return t.shared(n),t.index(e,n),typeof window<"u"&&e.setWorkerUrl(window.URL.createObjectURL(new Blob([i],{type:"text/javascript"}))),typeof System=="object"&&typeof System.register=="function"&&System.register([],f=>(f(e),{execute:function(){}})),e}}r._mapgl_d=s})(self);

_mapgl_d("shared",["exports"],(function(m){var fR=Object.defineProperty,uR=Object.defineProperties;var dR=Object.getOwnPropertyDescriptors;var Lc=Object.getOwnPropertySymbols;var _x=Object.prototype.hasOwnProperty,Cx=Object.prototype.propertyIsEnumerable;var Ch=(m,Ie)=>(Ie=Symbol[m])?Ie:Symbol.for("Symbol."+m),hR=m=>{throw TypeError(m)},$=Math.pow,Mx=(m,Ie,We)=>Ie in m?fR(m,Ie,{enumerable:!0,configurable:!0,writable:!0,value:We}):m[Ie]=We,V=(m,Ie)=>{for(var We in Ie||(Ie={}))_x.call(Ie,We)&&Mx(m,We,Ie[We]);if(Lc)for(var We of Lc(Ie))Cx.call(Ie,We)&&Mx(m,We,Ie[We]);return m},ie=(m,Ie)=>uR(m,dR(Ie));var Fx=(m,Ie)=>{var We={};for(var st in m)_x.call(m,st)&&Ie.indexOf(st)<0&&(We[st]=m[st]);if(m!=null&&Lc)for(var st of Lc(m))Ie.indexOf(st)<0&&Cx.call(m,st)&&(We[st]=m[st]);return We};var Fe=(m,Ie,We)=>new Promise((st,Sn)=>{var rn=sn=>{try{fr(We.next(sn))}catch(Ws){Sn(Ws)}},ni=sn=>{try{fr(We.throw(sn))}catch(Ws){Sn(Ws)}},fr=sn=>sn.done?st(sn.value):Promise.resolve(sn.value).then(rn,ni);fr((We=We.apply(m,Ie)).next())}),pR=function(m,Ie){this[0]=m,this[1]=Ie};var Lx=m=>{var Ie=m[Ch("asyncIterator")],We=!1,st,Sn={};return Ie==null?(Ie=m[Ch("iterator")](),st=rn=>Sn[rn]=ni=>Ie[rn](ni)):(Ie=Ie.call(m),st=rn=>Sn[rn]=ni=>{if(We){if(We=!1,rn==="throw")throw ni;return ni}return We=!0,{done:!1,value:new pR(new Promise(fr=>{var sn=Ie[rn](ni);sn instanceof Object||hR("Object expected"),fr(sn)}),1)}}),Sn[Ch("iterator")]=()=>Sn,st("next"),"throw"in Ie?st("throw"):Sn.throw=rn=>{throw rn},"return"in Ie&&st("return"),Sn};"use strict";const Ie="tile{subdomain}.maps.2gis.com",We="jam.api.2gis.com",st="https://styles.api.2gis.com",Sn="https://disk.2gis.com/styles/assets/icons",rn="https://disk.2gis.com/styles/assets/models",ni="https://mapgl.2gis.com/api/fonts",fr="https://keys.api.2gis.com/public/v1/keys/{keyID}/services/mapgl-js-api",sn="https://mapgl.2gis.com/api/js/plugins/rtl-v1.1.1.js",Ws="sha512-IyuCqmcNBfZyrExDMisGi0Xhp4PXupx6AMp4cjpKcAzJo+kSmOtRTLbL1xZsfxnsIqci9Q0piqY+kcwl1hCPyw==",Dx="https://mapgl.2gis.com/api/js/plugins",Ox=107.17318798131565,_i=$(2,20),ae=$(2,15),He=$(2,16)-1,ot=ae/He,W=16383,Fh=2.54,Hs=96,Lh=4294967296/(256/Hs*Fh),Ke=.7071067811865475,Rx=4294967295,zx=1175494351e-47,Nx=3402823466e29,Gx="Noto_Sans",Bh=1/2,Dh=-4,Bc=2147483647,kx="c080bb6a-8134-4993-93a1-5b4d8c36a59b",Oh=5,qo=4,Dc=40,Ux=65e3,Rh="byModel",Vx=65536,zh="empty",Wx=75,Hx=180/Math.PI,Oc={minZoom:2,maxZoom:20},ur={protocol:"https",server:Ie,subdomains:"0123",tileSet:"vector_a",tileKey:zh,appId:"empty",cacheRatio:2,maxUniverseZoom:8,maxRegionalZoom:15,maxDetailLevel:17},Rc={minZoom:10,maxZoom:14,tileSet:"com_poi_web",rasterSizes:[96,84,72,60,48,36,24]},Nh={minZoom:14,maxZoom:15,tileSet:"vector_immersive"},Gh={tileSet:"dem"},kh=100,zc=13.5,Yt=[2048,2048],Ko={tiles:"{protocol}://{host}/vt?r={request}&ts={tileSet}&key={tileKey}&appId={appId}&lang={lang}&default_lang={defaultLang}&dt={dt}",metatile:"{protocol}://{host}/metafiles/{hash}/metatile.json?ts={tileSet}",modelInfo:"{protocol}://{host}/metafiles/{regionId}/models.json?ts={tileSet}",model:"{protocol}://{host}/metafiles/{regionId}/{name}?ts={tileSet}",gltfModel:"{protocol}://{host}/metafiles/{modelSrc}?ts={tileSet}",convertData:"{protocol}://{host}/metafiles/{hash}/convert.json?ts={tileSet}",dynamicPoi:"{protocol}://{host}/metafiles/{regionId}/poi/{id}_{width}_{height}.png?ts={tileSet}",models:"{protocol}://{host}/v2/ald?ts={tileSet}&x={x}&y={y}&z={z}",commercialPoi:"{protocol}://{host}/v2/ald?ts={tileSet}&x={x}&y={y}&z={z}&lang={lang}",floorMeta:"{protocol}://{host}/metafiles/{regionId}/{floorComplexId}.json?ts={tileSet}"},Uh={protocol:"https",host:We,url:"{protocol}://{host}/tiles?tls={tiles}&reg={regions}&tm={time}&fmt=json&z={z}",timestampUrl:"{protocol}://{host}/meta?reg={regions}&time&score",updateInterval:120*1e3,minZoom:10,maxZoom:16,maxDetailLevel:17,fetchMetaRetryDelays:[2,5,25].map(e=>e*1e3)},on={defaultUrl:ni,gamma:.08,baseSize:24,baseLineHeight:1.2,bomCharCode:65279},Vh={defaultUrl:Sn},Wh={url:st,path:"styles/{id}"},Hh={doubleClickTime:185,dragThreshold:2,pitchWaitingTime:200,pitchThreshold:7},Yh=1e3,Ys={inAnimationTime:180,inAnimationType:"linear",outAnimationTime:800,outAnimationType:"linear"},Nc={time:300,type:"linear"},Xh={minStyleZoom:16,duration:500,easing:"easeOutQuint"},Zh={bounceType:"easeOutElastic",bounceTime:1200,growType:"easeInOutQuad",growTime:1200,stagger:0,iterationCount:1/0},Gc={pixelDensity:.5,sceneOpacity:0,cacheRefreshTime:300,pickDistance:3},Jo={interval:220,animationTime:200,animationType:"linear",tileMultiplier:1.5,axisAngleToleranceDeg:45,axisCheckDistancePx:13,commercialMargins:{default:{topBottom:60,leftRight:60},city:{topBottom:500,leftRight:500}},lineLabelsHidePitchDeg:40,screenLineLabelsHidePitchDeg:85,maxLabelLength:30},jh={0:Jo.commercialMargins.city,11:{topBottom:250,leftRight:250},12:{topBottom:170,leftRight:170}},Qh={alwaysRerender:!1,autoResizeInterval:50},qh="en",Kh={macWheelDeltaToZoomDelta:.0018,notMacTrackpadDeltaToZoomDelta:.0018*3,wheelZoomDelta:.65,animDuration:400,throttleDelay:100,mouseRotateDelta:2.5,mousePitchDelta:2.5,mobilePinchDelta:1,mobileTapDelta:10},kc={duration:1300,maxSpeed:8,minSpeed:.02,nonLinearity:5},En={fov:60*Math.PI/180,useDynamicNearFar:!1,near:1e3,far:$(2,34),viewportLimitRatio:2.1,minTrapezeHeight:2*131072,perspectiveDistanceLimitRatio:10,minFogDistance:2e4,fogHorizonPadFactor:.15,pitchInterStartZoom:17,pitchInterEndZoom:19},dr={globeMaxZoom:8,globeInterStartZoom:7,globeInterEndZoom:16},Jh=1e3,$h=16,Uc={enabled:!0,displayStyleZoom:{default:18,metro:16,uiPoi:17.5},detailLevel:16,wallMinBrightness:.8265,wallMaxBrightness:.95,viewportPadding:.2,maxStackHeight:40,commFloorsDefaultFloorLevel:7,commFloorsFly:{pitch:0,styleZoom:20.31,animation:{animate:!0,duration:1e3}}},ep={fpsCaveat:10},tp=3e4,Vc=["Commercial_poi_city"],Wc=["Commercial_poi_premium"],np=["Commercial_poi_default","Commercial_poi_custom","Commercial_poi_navi",...Vc,...Wc],ip=["Commercial_model","Commercial_model_animated","Commercial_model_on_click"],rp=["s_personal_poi"],sp=["Landmark_poi","Landmark_point"],op=[105,84,63,42,21],ap="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzBweCIgaGVpZ2h0PSI0OHB4IiB2aWV3Qm94PSIwIDAgMzAgNDgiIHZlcnNpb249IjEuMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayI+PCEtLSBHZW5lcmF0b3I6IFNrZXRjaCA1MS4yICg1NzUxOSkgLSBodHRwOi8vd3d3LmJvaGVtaWFuY29kaW5nLmNvbS9za2V0Y2ggLS0+PHRpdGxlPlBhZ2UgMSBDb3B5PC90aXRsZT48ZGVzYz5DcmVhdGVkIHdpdGggU2tldGNoLjwvZGVzYz48ZGVmcz48bGluZWFyR3JhZGllbnQgeDE9IjUwJSIgeTE9IjUwJSIgeDI9IjUwJSIgeTI9IjAlIiBpZD0ibGluZWFyR3JhZGllbnQtMSI+PHN0b3Agc3RvcC1jb2xvcj0iIzFCODlFRSIgb2Zmc2V0PSIwJSI+PC9zdG9wPjxzdG9wIHN0b3AtY29sb3I9IiMzMTk4RUMiIG9mZnNldD0iMTAwJSI+PC9zdG9wPjwvbGluZWFyR3JhZGllbnQ+PC9kZWZzPjxnIGlkPSJQYWdlLTEiIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGlkPSJSZWNvdmVyeS0wMSIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoLTgzOS4wMDAwMDAsIC00MjUuMDAwMDAwKSI+PGcgaWQ9IlBhZ2UtMS1Db3B5IiB0cmFuc2Zvcm09InRyYW5zbGF0ZSg4MzkuMDAwMDAwLCA0MjUuMDAwMDAwKSI+PGVsbGlwc2UgaWQ9Ik92YWwtMyIgZmlsbD0iIzAwMDAwMCIgb3BhY2l0eT0iMC4wMzYzODA1OTciIGN4PSIxNSIgY3k9IjQ1LjUiIHJ4PSIzIiByeT0iMS41Ij48L2VsbGlwc2U+PGVsbGlwc2UgaWQ9Ik92YWwtMy1Db3B5IiBmaWxsPSIjMDAwMDAwIiBvcGFjaXR5PSIwLjAzNjM4MDU5NyIgY3g9IjE1IiBjeT0iNDUuNSIgcng9IjQuNSIgcnk9IjIuNSI+PC9lbGxpcHNlPjxwYXRoIGQ9Ik0xNSw0NS44ODM2MzUzIEwxNS44ODIzNTI5LDQ1Ljg4MzYzNTMgQzE1Ljg4MjM1MjksMjkuMjE3NzUyOSAyMC43NzY3NjQ3LDIzLjc5NzQ1ODggMjcuOTg3MzUyOSwyMy43OTc0NTg4IEwyOC4zMjk3MDU5LDIzLjc5NzQ1ODggQzI5LjA3Nzk0MTIsMjEuNTkwNjk0MSAzMCwxNy45OTE1NzY1IDMwLDE1LjAwMDQgQzMwLDcuMTQzOTI5NDEgMjMuNzY3OTQxMiwwLjAwMDQgMTUsMC4wMDA0IEM2LjIzMjA1ODgyLDAuMDAwNCAwLDcuMTQzOTI5NDEgMCwxNS4wMDA0IEMwLDE3Ljk5MTU3NjUgMC45MjIwNTg4MjQsMjEuNTkwNjk0MSAxLjY3MDI5NDEyLDIzLjc5NzQ1ODggTDIuMDEyNjQ3MDYsMjMuNzk3NDU4OCBDOS4yMjQxMTc2NSwyMy43OTc0NTg4IDE0LjExNzY0NzEsMjkuMjE3NzUyOSAxNC4xMTc2NDcxLDQ1Ljg4MzYzNTMgTDE1LDQ1Ljg4MzYzNTMgWiIgaWQ9IkZpbGwtMSIgZmlsbD0idXJsKCNsaW5lYXJHcmFkaWVudC0xKSI+PC9wYXRoPjwvZz48L2c+PC9nPjwvc3ZnPg==",lp=[15,46],cp=16,fp={bias:100,textureSize:[2048,2048],shadowRadius:3},Hc=2048,Yx=Object.freeze(Object.defineProperty({__proto__:null,DEFAULT_MIN_TIERS_STYLE_ZOOM:cp,MAP_DEFAULTS:Oc,MAX_GUIDELINE_TEXTURE_SIZE:Hc,atlasSize:Yt,buildingAnimation:Xh,cityCommPoiLabelingConfig:jh,commercialCitySublayers:Vc,commercialModelSublayers:ip,commercialPoi:Rc,commercialPremiumSublayers:Wc,commercialSublayers:np,defaultCameraConfig:En,defaultLang:qh,defaultMarkerAnchor:lp,defaultMarkerIcon:ap,defaultShadowsSettings:fp,dem:Gh,entranceAnimation:Zh,events:Hh,floors:Uc,fonts:on,globeConfig:dr,houseHover:Ys,icons:Vh,identify:Gc,inertia:kc,labeling:Jo,landmarkPoiSublayers:sp,landmarkRasterSizes:op,loadModelsInfoStyleZoom:zc,maxZoomForDynamicNear:$h,metricsTimeout:tp,minCalculationScreenHeight:Jh,modelCacheSize:kh,models:Nh,performanceCheck:ep,personalSublayers:rp,render:Qh,styles:Wh,tileAnimation:Nc,tiles:ur,traffic:Uh,urls:Ko,workerResetInterval:Yh,zoom:Kh},Symbol.toStringTag,{value:"Module"}));function Ge(e,t,n){return e=Math.max(e,t),e=Math.min(e,n),e}function $o(e){return e===0||Number.isNaN(e)?e:e>0?1:-1}function Xx(e,t){return[t[0]/e[0]*2-1,-(t[1]/e[1])*2+1]}function Le(e){return e*Math.PI/180}function hr(e){return e/Math.PI*180}function up(e){return e=e>>>0,e=e-1,e=e|e>>1,e=e|e>>2,e=e|e>>4,e=e|e>>8,e=e|e>>16,e+1}function Ci(e,t){const n=V({},t);for(const i in e)e[i]!==void 0&&(n[i]=e[i]);return n}function Yc(e){const t={};for(const n in e){const i=e[n];t[i]=n}return t}function dp(e,t){const n=[];for(const i in e)t[i]||n.push(e[i]);return n}function Xc(e,t,n){return Ge((n-e)/(t-e),0,1)}function Zx(e){return e%1}function Zc(e,t,n){return e>=t&&e<=n}function jx(e,t){if(e.size!==t.size)return!1;for(const n of Array.from(e))if(!t.has(n))return!1;return!0}function Qx(e,t){return e===t?!0:e.length!==t.length?!1:!e.some((n,i)=>n!==t[i])}function Hr(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){const n=Array.isArray(e),i=Array.isArray(t);let r,s,o;if(n&&i){if(s=e.length,s!==t.length)return!1;for(r=s;r--!==0;)if(!Hr(e[r],t[r]))return!1;return!0}if(n!==i)return!1;const a=e instanceof Date,l=t instanceof Date;if(a!==l)return!1;if(a&&l)return e.getTime()===t.getTime();const c=e instanceof RegExp,f=t instanceof RegExp;if(c!==f)return!1;if(c&&f)return e.toString()===t.toString();const u=Object.keys(e);if(s=u.length,s!==Object.keys(t).length)return!1;for(r=s;r--!==0;)if(!Object.prototype.hasOwnProperty.call(t,u[r]))return!1;for(r=s;r--!==0;)if(o=u[r],!Hr(e[o],t[o]))return!1;return!0}return e!==e&&t!==t}function qx(e,t){const n=e.indexOf(t);return n!==-1?(e.splice(n,1),!0):!1}function Yr(e,t,n){return e+(t-e)*n}function Kx(e){return e==null}function ea(e,t){const n=t;typeof e=="number"?n.fill(e):Array.isArray(e)&&typeof e[0]=="number"&&typeof e[1]=="number"&&typeof e[2]=="number"&&(n[0]=e[0],n[1]=e[1],n[2]=e[2])}class hp{constructor(t,n){this.getNewValidFor=n,this.getNewValue=t,this.currentValue=NaN,this.currentValidFor=new Array(n().length).fill(NaN)}get value(){const t=this.getNewValidFor();return this.currentValidFor.some((i,r)=>i!==t[r])&&(this.currentValidFor=t,this.currentValue=this.getNewValue()),this.currentValue}}function Jx(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function jc(e,t=!1){const n=Ge((e>>24&255)/255,0,1),i=Ge((e>>16&255)/255,0,1),r=Ge((e>>8&255)/255,0,1),s=Ge((e&255)/255,0,1);return t?[s,r,i,n]:[n,i,r,s]}function $x(e,t,n){return e*(1-n)+t*n}const Xt=1e-6;let Zt=typeof Float64Array!="undefined"?Float64Array:Array;function Ye(){let e=new Zt(2);return e[0]=0,e[1]=0,e}function ew(e){let t=new Zt(2);return t[0]=e[0],t[1]=e[1],t}function Qc(e,t){let n=new Zt(2);return n[0]=e,n[1]=t,n}function ta(e,t){return e[0]=t[0],e[1]=t[1],e}function tt(e,t,n){return e[0]=t,e[1]=n,e}function Tn(e,t,n){return e[0]=t[0]+n[0],e[1]=t[1]+n[1],e}function qc(e,t,n){return e[0]=t[0]-n[0],e[1]=t[1]-n[1],e}function tw(e,t,n){return e[0]=Math.min(t[0],n[0]),e[1]=Math.min(t[1],n[1]),e}function nw(e,t,n){return e[0]=Math.max(t[0],n[0]),e[1]=Math.max(t[1],n[1]),e}function an(e,t,n){return e[0]=t[0]*n,e[1]=t[1]*n,e}function Xs(e,t){var n=t[0]-e[0],i=t[1]-e[1];return Math.sqrt(n*n+i*i)}function iw(e,t){var n=t[0]-e[0],i=t[1]-e[1];return n*n+i*i}function na(e){var t=e[0],n=e[1];return Math.sqrt(t*t+n*n)}function rw(e){var t=e[0],n=e[1];return t*t+n*n}function Fi(e,t){var n=t[0],i=t[1],r=n*n+i*i;return r>0&&(r=1/Math.sqrt(r),e[0]=t[0]*r,e[1]=t[1]*r),e}function Li(e,t){return e[0]*t[0]+e[1]*t[1]}function Kc(e,t,n,i){var r=t[0],s=t[1];return e[0]=r+i*(n[0]-r),e[1]=s+i*(n[1]-s),e}function ia(e,t){return e[0]===t[0]&&e[1]===t[1]}function sw(e,t){let n=e[0],i=e[1],r=t[0],s=t[1];return Math.abs(n-r)<=Xt*Math.max(1,Math.abs(n),Math.abs(r))&&Math.abs(i-s)<=Xt*Math.max(1,Math.abs(i),Math.abs(s))}const pp=na,ii=qc,Bi=Xs,ow=iw;(function(){let e=Ye();return function(t,n,i,r,s,o){let a,l;for(n||(n=2),i||(i=0),r?l=Math.min(r*n+i,t.length):l=t.length,a=i;a<l;a+=n)e[0]=t[a],e[1]=t[a+1],s(e,e,o),t[a]=e[0],t[a+1]=e[1];return t}})();function gp(){let e=new Zt(16);return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}function aw(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e}function lw(e,t,n,i,r,s,o,a,l,c,f,u,d,h,g,y){let p=new Zt(16);return p[0]=e,p[1]=t,p[2]=n,p[3]=i,p[4]=r,p[5]=s,p[6]=o,p[7]=a,p[8]=l,p[9]=c,p[10]=f,p[11]=u,p[12]=d,p[13]=h,p[14]=g,p[15]=y,p}function cw(e,t,n,i,r,s,o,a,l,c,f,u,d,h,g,y,p){return e[0]=t,e[1]=n,e[2]=i,e[3]=r,e[4]=s,e[5]=o,e[6]=a,e[7]=l,e[8]=c,e[9]=f,e[10]=u,e[11]=d,e[12]=h,e[13]=g,e[14]=y,e[15]=p,e}function Jc(e){return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}function fw(e,t){if(e===t){let n=t[1],i=t[2],r=t[3],s=t[6],o=t[7],a=t[11];e[1]=t[4],e[2]=t[8],e[3]=t[12],e[4]=n,e[6]=t[9],e[7]=t[13],e[8]=i,e[9]=s,e[11]=t[14],e[12]=r,e[13]=o,e[14]=a}else e[0]=t[0],e[1]=t[4],e[2]=t[8],e[3]=t[12],e[4]=t[1],e[5]=t[5],e[6]=t[9],e[7]=t[13],e[8]=t[2],e[9]=t[6],e[10]=t[10],e[11]=t[14],e[12]=t[3],e[13]=t[7],e[14]=t[11],e[15]=t[15];return e}function Zs(e,t){let n=t[0],i=t[1],r=t[2],s=t[3],o=t[4],a=t[5],l=t[6],c=t[7],f=t[8],u=t[9],d=t[10],h=t[11],g=t[12],y=t[13],p=t[14],v=t[15],A=n*a-i*o,w=n*l-r*o,S=n*c-s*o,T=i*l-r*a,I=i*c-s*a,C=r*c-s*l,M=f*y-u*g,B=f*p-d*g,D=f*v-h*g,F=u*p-d*y,z=u*v-h*y,N=d*v-h*p,H=A*N-w*z+S*F+T*D-I*B+C*M;return H?(H=1/H,e[0]=(a*N-l*z+c*F)*H,e[1]=(r*z-i*N-s*F)*H,e[2]=(y*C-p*I+v*T)*H,e[3]=(d*I-u*C-h*T)*H,e[4]=(l*D-o*N-c*B)*H,e[5]=(n*N-r*D+s*B)*H,e[6]=(p*S-g*C-v*w)*H,e[7]=(f*C-d*S+h*w)*H,e[8]=(o*z-a*D+c*M)*H,e[9]=(i*D-n*z-s*M)*H,e[10]=(g*I-y*S+v*A)*H,e[11]=(u*S-f*I-h*A)*H,e[12]=(a*B-o*F-l*M)*H,e[13]=(n*F-i*B+r*M)*H,e[14]=(y*w-g*T-p*A)*H,e[15]=(f*T-u*w+d*A)*H,e):null}function Di(e,t,n){let i=t[0],r=t[1],s=t[2],o=t[3],a=t[4],l=t[5],c=t[6],f=t[7],u=t[8],d=t[9],h=t[10],g=t[11],y=t[12],p=t[13],v=t[14],A=t[15],w=n[0],S=n[1],T=n[2],I=n[3];return e[0]=w*i+S*a+T*u+I*y,e[1]=w*r+S*l+T*d+I*p,e[2]=w*s+S*c+T*h+I*v,e[3]=w*o+S*f+T*g+I*A,w=n[4],S=n[5],T=n[6],I=n[7],e[4]=w*i+S*a+T*u+I*y,e[5]=w*r+S*l+T*d+I*p,e[6]=w*s+S*c+T*h+I*v,e[7]=w*o+S*f+T*g+I*A,w=n[8],S=n[9],T=n[10],I=n[11],e[8]=w*i+S*a+T*u+I*y,e[9]=w*r+S*l+T*d+I*p,e[10]=w*s+S*c+T*h+I*v,e[11]=w*o+S*f+T*g+I*A,w=n[12],S=n[13],T=n[14],I=n[15],e[12]=w*i+S*a+T*u+I*y,e[13]=w*r+S*l+T*d+I*p,e[14]=w*s+S*c+T*h+I*v,e[15]=w*o+S*f+T*g+I*A,e}function mp(e,t,n){let i=n[0],r=n[1],s=n[2],o,a,l,c,f,u,d,h,g,y,p,v;return t===e?(e[12]=t[0]*i+t[4]*r+t[8]*s+t[12],e[13]=t[1]*i+t[5]*r+t[9]*s+t[13],e[14]=t[2]*i+t[6]*r+t[10]*s+t[14],e[15]=t[3]*i+t[7]*r+t[11]*s+t[15]):(o=t[0],a=t[1],l=t[2],c=t[3],f=t[4],u=t[5],d=t[6],h=t[7],g=t[8],y=t[9],p=t[10],v=t[11],e[0]=o,e[1]=a,e[2]=l,e[3]=c,e[4]=f,e[5]=u,e[6]=d,e[7]=h,e[8]=g,e[9]=y,e[10]=p,e[11]=v,e[12]=o*i+f*r+g*s+t[12],e[13]=a*i+u*r+y*s+t[13],e[14]=l*i+d*r+p*s+t[14],e[15]=c*i+h*r+v*s+t[15]),e}function Xr(e,t,n){let i=n[0],r=n[1],s=n[2];return e[0]=t[0]*i,e[1]=t[1]*i,e[2]=t[2]*i,e[3]=t[3]*i,e[4]=t[4]*r,e[5]=t[5]*r,e[6]=t[6]*r,e[7]=t[7]*r,e[8]=t[8]*s,e[9]=t[9]*s,e[10]=t[10]*s,e[11]=t[11]*s,e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e}function $c(e,t,n){let i=Math.sin(n),r=Math.cos(n),s=t[4],o=t[5],a=t[6],l=t[7],c=t[8],f=t[9],u=t[10],d=t[11];return t!==e&&(e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15]),e[4]=s*r+c*i,e[5]=o*r+f*i,e[6]=a*r+u*i,e[7]=l*r+d*i,e[8]=c*r-s*i,e[9]=f*r-o*i,e[10]=u*r-a*i,e[11]=d*r-l*i,e}function vp(e,t,n){let i=Math.sin(n),r=Math.cos(n),s=t[0],o=t[1],a=t[2],l=t[3],c=t[8],f=t[9],u=t[10],d=t[11];return t!==e&&(e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15]),e[0]=s*r-c*i,e[1]=o*r-f*i,e[2]=a*r-u*i,e[3]=l*r-d*i,e[8]=s*i+c*r,e[9]=o*i+f*r,e[10]=a*i+u*r,e[11]=l*i+d*r,e}function ra(e,t,n){let i=Math.sin(n),r=Math.cos(n),s=t[0],o=t[1],a=t[2],l=t[3],c=t[4],f=t[5],u=t[6],d=t[7];return t!==e&&(e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15]),e[0]=s*r+c*i,e[1]=o*r+f*i,e[2]=a*r+u*i,e[3]=l*r+d*i,e[4]=c*r-s*i,e[5]=f*r-o*i,e[6]=u*r-a*i,e[7]=d*r-l*i,e}function uw(e,t){return e[0]=t[0],e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=t[1],e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=t[2],e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}function yp(e,t,n){let i=n[0],r=n[1],s=n[2],o=Math.sqrt(i*i+r*r+s*s),a,l,c;return Math.abs(o)<Xt?null:(o=1/o,i*=o,r*=o,s*=o,a=Math.sin(t),l=Math.cos(t),c=1-l,e[0]=i*i*c+l,e[1]=r*i*c+s*a,e[2]=s*i*c-r*a,e[3]=0,e[4]=i*r*c-s*a,e[5]=r*r*c+l,e[6]=s*r*c+i*a,e[7]=0,e[8]=i*s*c+r*a,e[9]=r*s*c-i*a,e[10]=s*s*c+l,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e)}function dw(e,t,n,i){let r=t[0],s=t[1],o=t[2],a=t[3],l=r+r,c=s+s,f=o+o,u=r*l,d=r*c,h=r*f,g=s*c,y=s*f,p=o*f,v=a*l,A=a*c,w=a*f,S=i[0],T=i[1],I=i[2];return e[0]=(1-(g+p))*S,e[1]=(d+w)*S,e[2]=(h-A)*S,e[3]=0,e[4]=(d-w)*T,e[5]=(1-(u+p))*T,e[6]=(y+v)*T,e[7]=0,e[8]=(h+A)*I,e[9]=(y-v)*I,e[10]=(1-(u+g))*I,e[11]=0,e[12]=n[0],e[13]=n[1],e[14]=n[2],e[15]=1,e}function hw(e,t,n,i,r,s,o){let a=1/(t-n),l=1/(i-r),c=1/(s-o);return e[0]=-2*a,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=-2*l,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=2*c,e[11]=0,e[12]=(t+n)*a,e[13]=(r+i)*l,e[14]=(o+s)*c,e[15]=1,e}function ef(e,t,n,i){let r,s,o,a,l,c,f,u,d,h,g=t[0],y=t[1],p=t[2],v=i[0],A=i[1],w=i[2],S=n[0],T=n[1],I=n[2];return Math.abs(g-S)<Xt&&Math.abs(y-T)<Xt&&Math.abs(p-I)<Xt?mat4.identity(e):(f=g-S,u=y-T,d=p-I,h=1/Math.sqrt(f*f+u*u+d*d),f*=h,u*=h,d*=h,r=A*d-w*u,s=w*f-v*d,o=v*u-A*f,h=Math.sqrt(r*r+s*s+o*o),h?(h=1/h,r*=h,s*=h,o*=h):(r=0,s=0,o=0),a=u*o-d*s,l=d*r-f*o,c=f*s-u*r,h=Math.sqrt(a*a+l*l+c*c),h?(h=1/h,a*=h,l*=h,c*=h):(a=0,l=0,c=0),e[0]=r,e[1]=a,e[2]=f,e[3]=0,e[4]=s,e[5]=l,e[6]=u,e[7]=0,e[8]=o,e[9]=c,e[10]=d,e[11]=0,e[12]=-(r*g+s*y+o*p),e[13]=-(a*g+l*y+c*p),e[14]=-(f*g+u*y+d*p),e[15]=1,e)}function pw(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]&&e[5]===t[5]&&e[6]===t[6]&&e[7]===t[7]&&e[8]===t[8]&&e[9]===t[9]&&e[10]===t[10]&&e[11]===t[11]&&e[12]===t[12]&&e[13]===t[13]&&e[14]===t[14]&&e[15]===t[15]}const Zr=Di;function sa(e,t,n){return e[0]=n[0],e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=n[1],e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=n[2],e[11]=0,e[12]=t[0],e[13]=t[1],e[14]=t[2],e[15]=1,e}const xp=6378137,tf=2*Math.PI*xp,Ee=4294967296/tf,gw=sa([],[-1,-1,0],[2,2,1]),mw=sa([],[.5,.5,0],[.5,.5,1]),Oi=xp*(Math.PI/2),vw=$(2,16)/4294967296;function nf(e){return Math.max(e,Jh)}function jr(e,t){const n=En,i=nf(t[1])/2,r=4294967296/$(2,e),s=i/256*r,o=Math.tan(n.fov/2);return s/o}function yw(e,t){const n=En;return Math.log(nf(t[1])*4294967296/(2*256*Math.tan(n.fov/2)*e))/Math.LN2}function xw(e){return Lh*Math.pow(2,-e)}function ww(e,t){return Fh*(e/Hs)/t}function rf(e,t){const i=Math.PI/180,r=e[1]*i,s=t[1]*i,o=Math.sin((t[1]-e[1])*i/2),a=Math.sin((t[0]-e[0])*i/2),l=o*o+Math.cos(r)*Math.cos(s)*a*a,c=2*Math.atan2(Math.sqrt(l),Math.sqrt(1-l));return Math.round(6371e3*c)}function Aw(e){let t=0;if(e.length>1)for(let n=0;n<e.length-1;n++)t+=rf(e[n],e[n+1]);return t}const bw={min:[-2147483648,-2147483648],max:[4294967296/2,4294967296/2]},Sw={min:[-214748364800,-2147483648],max:[4294967296*100/2,4294967296/2]};function js(e){let i=e[0];if(i>=-2147483648&&i<=2147483648)return;const r=4294967296;i=((i- -2147483648)%r+r)%r+-2147483648,e[0]=i}function wp(e,t){return e*Math.pow(2,-t)*4294967296/256}function Ew(e,t){return e*Math.pow(2,t)*256/4294967296}function Ap(e,t){return e===0?-1/0:-Math.log(t*256/(e*4294967296))/Math.LN2}const sf=Ye(),bp=Ye();function Tw(e,t,n){qc(sf,n,e),qc(bp,t,e);const i=Li(sf,bp)/na(sf);return Math.atan2(i,e[2])}function Pw(e){const t=e[0],n=e[1];return Zc(t,-2147483648,2147483648)&&Zc(n,-2147483648,2147483648)}function Iw(e){const t=[...e];return Pw(t)||(t[0]=(4294967296+(t[0]+2147483648)%4294967296)%4294967296-2147483648),t}function oa(e,t){const n=Math.cos(Le(t[0]-e[0])),i=Math.sin(Le(t[1])),r=Math.sin(Le(e[1])),s=Math.cos(Le(t[1])),o=Math.cos(Le(e[1]));return Math.acos(i*r+s*o*n)}function Mw(e,t,n){const i=Le(e[0]),r=Le(e[1]),s=[0,0];return s[1]=Math.asin(Math.sin(r)*Math.cos(n)+Math.cos(r)*Math.sin(n)*Math.cos(t)),s[0]=i+Math.atan2(Math.sin(t)*Math.sin(n)*Math.cos(r),Math.cos(n)-Math.sin(r)*Math.sin(s[1])),[hr(s[0]),hr(s[1])]}function nt(){let e=new Zt(3);return e[0]=0,e[1]=0,e[2]=0,e}function _w(e){var t=new Zt(3);return t[0]=e[0],t[1]=e[1],t[2]=e[2],t}function Pn(e){let t=e[0],n=e[1],i=e[2];return Math.sqrt(t*t+n*n+i*i)}function bt(e,t,n){let i=new Zt(3);return i[0]=e,i[1]=t,i[2]=n,i}function of(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e}function Be(e,t,n,i){return e[0]=t,e[1]=n,e[2]=i,e}function pr(e,t,n){return e[0]=t[0]+n[0],e[1]=t[1]+n[1],e[2]=t[2]+n[2],e}function Sp(e,t,n){return e[0]=t[0]-n[0],e[1]=t[1]-n[1],e[2]=t[2]-n[2],e}function Ri(e,t,n){return e[0]=t[0]*n,e[1]=t[1]*n,e[2]=t[2]*n,e}function af(e,t,n,i){return e[0]=t[0]+n[0]*i,e[1]=t[1]+n[1]*i,e[2]=t[2]+n[2]*i,e}function Ep(e,t){let n=t[0]-e[0],i=t[1]-e[1],r=t[2]-e[2];return Math.sqrt(n*n+i*i+r*r)}function Tp(e,t){let n=t[0]-e[0],i=t[1]-e[1],r=t[2]-e[2];return n*n+i*i+r*r}function Cw(e){let t=e[0],n=e[1],i=e[2];return t*t+n*n+i*i}function lf(e,t){return e[0]=-t[0],e[1]=-t[1],e[2]=-t[2],e}function jt(e,t){let n=t[0],i=t[1],r=t[2],s=n*n+i*i+r*r;return s>0&&(s=1/Math.sqrt(s),e[0]=t[0]*s,e[1]=t[1]*s,e[2]=t[2]*s),e}function cf(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function gr(e,t,n){let i=t[0],r=t[1],s=t[2],o=n[0],a=n[1],l=n[2];return e[0]=r*l-s*a,e[1]=s*o-i*l,e[2]=i*a-r*o,e}function mr(e,t,n,i){let r=t[0],s=t[1],o=t[2];return e[0]=r+i*(n[0]-r),e[1]=s+i*(n[1]-s),e[2]=o+i*(n[2]-o),e}function Qs(e,t,n){let i=t[0],r=t[1],s=t[2],o=n[3]*i+n[7]*r+n[11]*s+n[15];return o=o||1,e[0]=(n[0]*i+n[4]*r+n[8]*s+n[12])/o,e[1]=(n[1]*i+n[5]*r+n[9]*s+n[13])/o,e[2]=(n[2]*i+n[6]*r+n[10]*s+n[14])/o,e}function Fw(e,t,n){let i=t[0],r=t[1],s=t[2];return e[0]=i*n[0]+r*n[3]+s*n[6],e[1]=i*n[1]+r*n[4]+s*n[7],e[2]=i*n[2]+r*n[5]+s*n[8],e}function Lw(e,t,n){let i=t[0],r=t[1],s=t[2],o=n[0],a=n[1],l=n[2],c=n[3],f=c*i+a*s-l*r,u=c*r+l*i-o*s,d=c*s+o*r-a*i,h=-o*i-a*r-l*s;return e[0]=f*c+h*-o+u*-l-d*-a,e[1]=u*c+h*-a+d*-o-f*-l,e[2]=d*c+h*-l+f*-a-u*-o,e}function Bw(e,t,n,i){let r=[],s=[];return r[0]=t[0]-n[0],r[1]=t[1]-n[1],r[2]=t[2]-n[2],s[0]=r[0],s[1]=r[1]*Math.cos(i)-r[2]*Math.sin(i),s[2]=r[1]*Math.sin(i)+r[2]*Math.cos(i),e[0]=s[0]+n[0],e[1]=s[1]+n[1],e[2]=s[2]+n[2],e}function Dw(e,t,n,i){let r=[],s=[];return r[0]=t[0]-n[0],r[1]=t[1]-n[1],r[2]=t[2]-n[2],s[0]=r[2]*Math.sin(i)+r[0]*Math.cos(i),s[1]=r[1],s[2]=r[2]*Math.cos(i)-r[0]*Math.sin(i),e[0]=s[0]+n[0],e[1]=s[1]+n[1],e[2]=s[2]+n[2],e}function Ow(e,t,n,i){let r=[],s=[];return r[0]=t[0]-n[0],r[1]=t[1]-n[1],r[2]=t[2]-n[2],s[0]=r[0]*Math.cos(i)-r[1]*Math.sin(i),s[1]=r[0]*Math.sin(i)+r[1]*Math.cos(i),s[2]=r[2],e[0]=s[0]+n[0],e[1]=s[1]+n[1],e[2]=s[2]+n[2],e}function Rw(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]}function zw(e,t){let n=e[0],i=e[1],r=e[2],s=t[0],o=t[1],a=t[2];return Math.abs(n-s)<=Xt*Math.max(1,Math.abs(n),Math.abs(s))&&Math.abs(i-o)<=Xt*Math.max(1,Math.abs(i),Math.abs(o))&&Math.abs(r-a)<=Xt*Math.max(1,Math.abs(r),Math.abs(a))}const ln=Sp,ff=Ep,Nw=Tp,aa=Pn;(function(){let e=nt();return function(t,n,i,r,s,o){let a,l;for(n||(n=3),i||(i=0),r?l=Math.min(r*n+i,t.length):l=t.length,a=i;a<l;a+=n)e[0]=t[a],e[1]=t[a+1],e[2]=t[a+2],s(e,e,o),t[a]=e[0],t[a+1]=e[1],t[a+2]=e[2];return t}})();function qs(){let e=new Zt(4);return e[0]=0,e[1]=0,e[2]=0,e[3]=0,e}function Gw(e,t,n,i){let r=new Zt(4);return r[0]=e,r[1]=t,r[2]=n,r[3]=i,r}function kw(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e}function Uw(e,t,n,i,r){return e[0]=t,e[1]=n,e[2]=i,e[3]=r,e}function Vw(e,t,n){return e[0]=t[0]+n[0],e[1]=t[1]+n[1],e[2]=t[2]+n[2],e[3]=t[3]+n[3],e}function Ww(e,t,n){return e[0]=t[0]*n[0],e[1]=t[1]*n[1],e[2]=t[2]*n[2],e[3]=t[3]*n[3],e}function Hw(e,t,n){return e[0]=t[0]*n,e[1]=t[1]*n,e[2]=t[2]*n,e[3]=t[3]*n,e}function Yw(e,t){let n=t[0],i=t[1],r=t[2],s=t[3],o=n*n+i*i+r*r+s*s;return o>0&&(o=1/Math.sqrt(o),e[0]=n*o,e[1]=i*o,e[2]=r*o,e[3]=s*o),e}function Xw(e,t,n,i){let r=t[0],s=t[1],o=t[2],a=t[3];return e[0]=r+i*(n[0]-r),e[1]=s+i*(n[1]-s),e[2]=o+i*(n[2]-o),e[3]=a+i*(n[3]-a),e}function la(e,t,n){let i=t[0],r=t[1],s=t[2],o=t[3];return e[0]=n[0]*i+n[4]*r+n[8]*s+n[12]*o,e[1]=n[1]*i+n[5]*r+n[9]*s+n[13]*o,e[2]=n[2]*i+n[6]*r+n[10]*s+n[14]*o,e[3]=n[3]*i+n[7]*r+n[11]*s+n[15]*o,e}function Zw(e,t){let n=e[0],i=e[1],r=e[2],s=e[3],o=t[0],a=t[1],l=t[2],c=t[3];return Math.abs(n-o)<=Xt*Math.max(1,Math.abs(n),Math.abs(o))&&Math.abs(i-a)<=Xt*Math.max(1,Math.abs(i),Math.abs(a))&&Math.abs(r-l)<=Xt*Math.max(1,Math.abs(r),Math.abs(l))&&Math.abs(s-c)<=Xt*Math.max(1,Math.abs(s),Math.abs(c))}const jw=Ww;(function(){let e=qs();return function(t,n,i,r,s,o){let a,l;for(n||(n=4),i||(i=0),r?l=Math.min(r*n+i,t.length):l=t.length,a=i;a<l;a+=n)e[0]=t[a],e[1]=t[a+1],e[2]=t[a+2],e[3]=t[a+3],s(e,e,o),t[a]=e[0],t[a+1]=e[1],t[a+2]=e[2],t[a+3]=e[3];return t}})();const vr=qs();class me{constructor(t,n){this.state=t,this.camera=n,this.position=[0,0,0]}static fromGeo(t,n=[0,0]){var l;const r=Math.sin(Le(t[1])),s=t[0]*4294967296/360,o=Math.log((1+r)/(1-r))*4294967296/(4*Math.PI);let a=0;if(t.length>2){const c=me.scaleFactor(t[1]);a=((l=t[2])!=null?l:0)*Ee*c}return n[0]=s,n[1]=Ge(o,-2147483648,2147483648),n[2]=a,n}static toGeo(t,n=[0,0]){n[0]=t[0]*360/4294967296;const i=-2*Math.PI/4294967296;if(n[1]=90-2*hr(Math.atan(Math.exp(t[1]*i))),t[2]){const r=me.scaleFactor(n[1]);n[2]=t[2]/Ee/r}return n}static scaleFactor(t){return 1/Math.cos(Le(t))}update(){const{center:t,rotation:n,zoom:i,pitch:r,size:s}=this.state,o=jr(i,s),a=Math.max(o*Math.sin(r),1);this.position[0]=t[0]+Math.sin(n)*a,this.position[1]=t[1]-Math.cos(n)*a,this.position[2]=o*Math.cos(r)}project(t,n=!1,i=[NaN,NaN]){const{size:r,viewport:s}=this.state;vr[0]=t[0],vr[1]=t[1],vr[2]=t[2],vr[3]=1,la(vr,vr,this.camera.viewProjectionMatrix);const[o,a,l,c]=vr,f=c*2;if(n&&(l>f||l<-f||o>f||o<-f||a>f||a<-f))return i;const d=r[0]/2,h=r[1]/2;return i[0]=d+s.left+o*d/c,i[1]=h+s.top-a*h/c,i}unproject(t,n=[0,0,0]){const{size:i,viewport:r}=this.state;n[0]=(t[0]-r.left)/i[0]*2-1,n[1]=-((Math.max(this.camera.horizonPixelOffset,t[1])-r.top)/i[1])*2+1,n[2]=0,Qs(n,n,this.camera.viewProjectionMatrixInverse),n[0]-=this.position[0],n[1]-=this.position[1],n[2]-=this.position[2],jt(n,n);const s=-this.position[2]/n[2];return n[0]=this.position[0]+n[0]*s,n[1]=this.position[1]+n[1]*s,n[2]=this.position[2]+n[2]*s,n}setState(t){this.state=t}}const yr=qs();function Pp(e){return[e[2],e[0],e[1]]}class Lt{constructor(t,n){this.state=t,this.camera=n,this.position=[0,0,0],this.ivpMatrix=[],this.cachedVisibleArc=new hp(()=>{const i=jr(this.state.zoom,this.state.size)/Ee;return Math.acos(Oi/(Oi+i))},()=>[this.state.zoom]),this.cachedPixelRadius=new hp(()=>{const i=me.toGeo(this.state.center),r=Mw(i,0,this.visibleArc),s=this.project(Lt.fromGeo(r));return s[0]-=this.state.viewport.left+this.state.size[0]/2+(this.state.padding.left-this.state.padding.right)/2,s[1]-=this.state.viewport.top+this.state.size[1]/2+(this.state.padding.top-this.state.padding.bottom)/2,pp(s)},()=>[this.state.zoom,this.state.cameraConfig.fov,this.state.size[0],this.state.size[1],this.state.padding.bottom,this.state.padding.top,this.state.padding.left,this.state.padding.right,this.camera.globeMatrix[0]]),this.update()}get visibleArc(){return this.cachedVisibleArc.value}get pixelRadius(){return this.cachedPixelRadius.value}static fromGeo(t,n=[NaN,NaN,NaN]){const i=Le(t[0]),r=Le(t[1]),s=Math.cos(i),o=Math.sin(i),a=Math.cos(r),l=Math.sin(r),c=Oi*Ee;return n[0]=o*a*c,n[1]=l*c,n[2]=s*a*c,n}static toGeo(t,n=[NaN,NaN]){const i=t[0],r=t[1],s=t[2],o=Math.sqrt(i*i+r*r+s*s),a=Math.asin(s/o),l=Math.atan2(r,i);return n[0]=hr(l),n[1]=hr(a),n}update(){const{state:t}=this,n=me.toGeo(t.center),i=jr(t.zoom,t.size)+Oi*Ee,r=Le(n[0]),s=Le(n[1]),o=Math.cos(r),a=Math.sin(r),l=Math.cos(s),c=Math.sin(s);this.position=[a*l*i,c*i,o*l*i];const f=[0,0,1];ef(this.ivpMatrix,Pp(this.position),[0,0,0],f),Zr(this.ivpMatrix,this.camera.projectionMatrix,this.ivpMatrix),Zs(this.ivpMatrix,this.ivpMatrix)}project(t,n=!1,i=[NaN,NaN]){const{size:r,viewport:s}=this.state,o=qs();yr[0]=t[0],yr[1]=t[1],yr[2]=t[2],yr[3]=1,la(yr,yr,this.camera.globeMatrix),la(o,yr,this.camera.viewProjectionMatrix);const[a,l,c,f]=o,u=f*2;if(n&&(c>u||c<-u||a>u||a<-u||l>u||l<-u))return i[0]=NaN,i[1]=NaN,i;const h=r[0]/2,g=r[1]/2;return i[0]=h+s.left+a*h/f,i[1]=g+s.top-l*g/f,i}unproject(t,n,i=[NaN,NaN,NaN]){const{size:r,viewport:s}=this.state,o=[(t[0]-s.left)/r[0]*2-1,-((Math.max(0,t[1])-s.top)/r[1])*2+1,0],a=Pp(this.position),l=[0,0,0,1];Qs(l,o,this.ivpMatrix);const c=jt([],ln([],l,a)),f=lf([],a),u=cf(f,c),d=Cw(f)-$(u,2),h=$(Oi*Ee,2);if(d>h){if(n)return Lt.fromGeo(me.toGeo(this.state.center));const{left:A,bottom:w,top:S,right:T}=this.state.padding,I=t[0]-s.left-r[0]/2-(A-T)/2,C=t[1]-s.top-r[1]/2-(S-w)/2,M=an([],Fi([],[I,C]),this.pixelRadius-1);return M[0]=M[0]+s.left+r[0]/2+(A-T)/2,M[1]=M[1]+s.top+r[1]/2+(S-w)/2,this.unproject(M,!0,i)}const g=Math.sqrt(h-d),y=u-g,p=u+g,v=Math.min(y,p);return i[0]=a[0]+c[0]*v,i[1]=a[1]+c[1]*v,i[2]=a[2]+c[2]*v,i}setState(t){this.state=t}canSee(t){const n=me.toGeo(this.state.center);return oa(n,t)<this.visibleArc}}const Qw=[0,0,1],qw=nt(),cn=[0,0,0],Kw=1e-5,Jw=500;class Ks{constructor(t){this.state=t,this.position=[0,0,0],this.projectionMatrix=[],this.viewMatrix=[],this.viewMatrixTranspose=[],this.projectionMatrixInverse=[],this.viewProjectionMatrix=[],this.viewProjectionMatrixInverse=[],this.globeMatrix=[],this.ecefMvpMatrix=new Float32Array(16),this.globeRatio=0,this.fogDistance=0,this.correctedPitch=0,this.correctedRotation=0,this.horizonPixelOffset=0,this.prevZoom=0,this.prevTime=0,this.horizonPixelOffset=0,this.flat=new me(t,this),this.ecef=new Lt(t,this),this.update()}setState(t){this.state=t,this.flat.setState(t),this.ecef.setState(t),this.update()}update(){this.updateGlobeRatio(),this.limitPitchRotation(),this.updatePosition(),this.updateViewMatrix(),this.updateProjectionMatrices(),this.state.pitch=this.correctedPitch,this.state.rotation=this.correctedRotation,this.flat.update(),this.ecef.update(),Di(this.viewProjectionMatrix,this.projectionMatrix,this.viewMatrix),Zs(this.viewProjectionMatrixInverse,this.viewProjectionMatrix),Zs(this.projectionMatrixInverse,this.projectionMatrix),fw(this.viewMatrixTranspose,this.viewMatrix),this.globeRatio>Number.EPSILON&&this.updateGlobeMatrix(),Zr(this.ecefMvpMatrix,this.viewProjectionMatrix,this.globeMatrix),this.updateHorizonPixelOffset(),this.updateFogDistance()}project(t,n=!1,i=[NaN,NaN]){if(this.globeRatio<Number.EPSILON)return this.flat.project(me.fromGeo(t),n,i);if(this.globeRatio>1-Number.EPSILON)return this.ecef.project(Lt.fromGeo(t),n,i);{const r=this.flat.project(me.fromGeo(t),n),s=this.ecef.project(Lt.fromGeo(t),n);return Array.from(mr(i,r,s,this.globeRatio))}}unproject(t,n=[0,0],i=!1){if(this.globeRatio<Number.EPSILON){const r=[0,0,0];return this.flat.unproject(t,r),me.toGeo(r,n),n}else if(this.globeRatio>1-Number.EPSILON){const r=[0,0,0];return this.ecef.unproject(t,!1,r),Lt.toGeo(r,n),n}else{const r=[0,0,0],s=[0,0,0];return this.flat.unproject(t,r),me.toGeo(r,r),this.ecef.unproject(t,!1,s),Lt.toGeo(s,s),i?(uf(this,t,s,r,n,2),n[2]=0,n):(mr(n,r,s,this.globeRatio),n[2]=0,n)}}getViewportVertices(t){const{size:n,viewport:i}=this.state;let r={top:0,right:0,bottom:0,left:0};if(t!==void 0){const o=n[0]*t,a=n[1]*t;r={top:o,right:a,bottom:o,left:a}}return[this.flat.unproject([i.left+r.left,n[1]+i.top-r.bottom,0]),this.flat.unproject([n[0]+i.left-r.right,n[1]+i.top-r.bottom,0]),this.flat.unproject([n[0]+i.left-r.right,i.top+r.top,0]),this.flat.unproject([i.left+r.left,i.top+r.top,0])]}getHorizonPixelOffset(){return this.horizonPixelOffset}updatePosition(){const{center:t,zoom:n,size:i}=this.state,r=jr(n,i);this.prevZoom=n;const s=Math.max(r*Math.sin(this.correctedPitch),1);this.position[0]=t[0]+Math.sin(this.correctedRotation)*s,this.position[1]=t[1]-Math.cos(this.correctedRotation)*s,this.position[2]=r*Math.cos(this.correctedPitch)}limitPitchRotation(){const t=this.state,{zoom:n,pitch:i,rotation:r,cameraConfig:s,lowZoomMaxPitch:o,styleState:a,maxPitch:l}=t,{pitchInterStartZoom:c,pitchInterEndZoom:f}=s,{globeInterEndZoom:u,globeMaxZoom:d}=dr;if(this.correctedPitch=i,this.correctedRotation=r,n<f){const h=Math.max(0,n-c)/(f-c);this.correctedPitch=Math.min(i,Yr(o!=null?o:90,l!=null?l:90,h))}if(a.globeEnabled&&n<u){const h=Math.max(0,n-d)/(u-d);if(this.correctedPitch=Math.min(this.correctedPitch,Yr(0,l!=null?l:90,h)),n<=d)this.correctedRotation=0;else if(n!==this.prevZoom){const g=0-r,y=(this.prevZoom-n)/(n-d);y>0&&(this.correctedRotation+=g*y%360)}}}updateProjectionMatrices(){const t=this.state.cameraConfig,n=t.fov;t.useDynamicNearFar||this.state.globeMode?this.updateNearFarState():this.restoreFixedNearFar();const{near:i,far:r}=t,{size:s,view:o}=this.correctViewAndSize(),a=s[0]/s[1];let l=i*Math.tan(n/2),c=2*l,f=a*c,u=-f/2;u+=o.x*f/s[0],l-=o.y*c/s[1],f*=o.width/s[0],c*=o.height/s[1];const d=u+f,h=l-c,g=this.projectionMatrix;g[0]=2*i/(d-u),g[5]=2*i/(l-h),g[8]=(d+u)/(d-u),g[9]=(l+h)/(l-h),g[10]=-(r+i)/(r-i),g[11]=-1,g[14]=-2*r*i/(r-i),g[1]=g[2]=g[3]=g[4]=g[6]=g[7]=g[12]=g[13]=g[15]=0,Zs(this.projectionMatrixInverse,this.projectionMatrix)}updateNearFarState(){const{zoom:t,cameraConfig:n}=this.state,i=this.position;if(t>$h)n.near=En.near;else{const o=.25*i[2],a=Math.min(16-t,1);n.near=o*a+En.near*(1-a)}const r=$(1-Math.min(t,20.5)/21,2);n.far=En.far*r}restoreFixedNearFar(){const{cameraConfig:t}=this.state;t.near=En.near,t.far=En.far}correctViewAndSize(){const{size:t,padding:n}=this.state,i=Math.max(0,n.top-n.bottom)*Math.tan(this.correctedPitch),r=nf(t[1])+i,s={x:(n.right-n.left)/2,y:(n.bottom-n.top)/2,width:t[0],height:t[1]};s.y+=(r-t[1])/2;const o=[t[0],r];return{view:s,size:o}}updateFogDistance(){const{center:t}=this.state,n=this.state.cameraConfig,i=ff(this.position,t);this.fogDistance=Math.max(n.minFogDistance,i)}updateViewMatrix(){ef(this.viewMatrix,this.position,this.state.center,Qw)}updateGlobeMatrix(){const t=this.globeMatrix,n=[0,0,0];Jc(t);const i=me.toGeo(this.state.center);Be(n,this.state.center[0],this.state.center[1],-this.state.center[2]-Oi*Ee),mp(this.globeMatrix,t,n),$c(t,t,Le(i[1])),vp(t,t,-Le(i[0]))}updateHorizonPixelOffset(){const{viewport:t,size:n,zoom:i}=this.state,r=this.flat.unproject([t.left,n[1]+t.top,0]),s=this.flat.unproject([t.left+n[0]/2,n[1]+t.top,0]),o=this.flat.unproject([n[0]+t.left,n[1]+t.top,0]);ln(cn,o,r),Ow(cn,cn,qw,Le(90)),jt(cn,cn);const a=wp(n[1]*this.state.cameraConfig.perspectiveDistanceLimitRatio,i);Ri(cn,cn,a),pr(cn,s,cn),this.flat.project(cn,!1,cn),this.horizonPixelOffset=Math.max(0,Math.ceil(cn[1]))}updateGlobeRatio(){var s;const t=(s=this.state.globeRatioTarget)!=null?s:this.state.globeMode?1:0;if(!Number.isFinite(t)){this.globeRatio=0,this.prevTime=Date.now();return}const n=Date.now(),i=Math.max(0,n-this.prevTime);this.prevTime=n;const r=Math.min(1,Jw*i/1e3);this.globeRatio+=(t-this.globeRatio)*r,Math.abs(this.globeRatio-t)<Kw&&(this.globeRatio=t)}}function uf(e,t,n,i,r,s,o=0){r[0]=(n[0]+i[0])/2,r[1]=(n[1]+i[1])/2;const a=e.project(n),l=e.project(i),c=e.project(r),f=Bi(c,t),u=Bi(a,t),d=Bi(l,t);if(f<s)return r;if(u<s)return n;if(d<s)return i;if(o>=10)return r;const h=u+f,g=d+f;return h>g?uf(e,t,i,r,r,s,o+1):uf(e,t,n,r,r,s,o+1)}function $w(e,t,n){n.zoom!==void 0&&(n.zoom=Ge(n.zoom,e.minZoom,e.maxZoom));const i=V({},e);js(i.center);const r=new Ks(i),s=r.unproject(t),o=me.fromGeo(s);n.center&&js(n.center),r.setState(V(V({},e),n));const a=me.fromGeo(r.unproject(t));Math.abs(o[0]-a[0])>$(2,31)&&(a[0]+=(o[0]>0?1:-1)*$(2,32));const l=nt();if(ln(l,o,a),e.globeMode&&Math.abs(s[1])>70&&e.zoom>dr.globeInterStartZoom&&e.zoom<dr.globeMaxZoom){const c=Math.abs(e.zoom-n.zoom);if(c>1e-4){const f=Math.abs(o[0]-a[0]),u=Math.log10(f/c),d=Math.min(1,$(10,6-u));Number.isNaN(d)||Ri(l,l,d)}}return l}function Ip(e){const n=me.toGeo(e)[1],i=1/(2*Math.cos(Le(n)));return Math.log(i)/Math.log(2)}function eA(e,t){const n=me.scaleFactor(t[1]);return 1+e*(n-1)}function Mp(e,t){const n=Ip(t)*Xc(9,10,e);return e+Ge(n,-1,0)}function tA(e,t){const n=Ip(t),i=n*Xc(9,10+n,e);return e-Ge(i,-1,0)}function nA(e,t,n,i,r,s,o={top:0,right:0,bottom:0,left:0},a={top:0,right:0,bottom:0,left:0},l,c){const f=En,u=new Ks({center:me.fromGeo(e),zoom:t,rotation:Le(n),size:i,pitch:Le(r),viewport:o,padding:a,cameraConfig:f,globeMode:!1,styleState:{}}),d=me.toGeo(u.flat.unproject(s)),h=me.toGeo(u.flat.unproject([s[0]+l,s[1]+c]));return Math.max(1,rf(d,h))}function ca(e,t){return t*Ee*me.scaleFactor(e[1])}function Js(e,t){return{min:e||Qc(1/0,1/0),max:t||Qc(-1/0,-1/0)}}function iA(e){return Js(me.fromGeo(e.southWest),me.fromGeo(e.northEast))}function xr(e,t){tw(e.min,e.min,t),nw(e.max,e.max,t)}function _p(e,t){e.min[0]=t.min[0],e.max[0]=t.max[0],e.min[1]=t.min[1],e.max[1]=t.max[1]}function df(e){e.min[0]=1/0,e.max[0]=-1/0,e.min[1]=1/0,e.max[1]=-1/0}function fa(e,t){return e[0]=t.min[0]+(t.max[0]-t.min[0])/2,e[1]=t.min[1]+(t.max[1]-t.min[1])/2,e}function rA(e,t,n){e[0]=Ge(n[0],t.min[0],t.max[0]),e[1]=Ge(n[1],t.min[1],t.max[1])}function sA(e,t,n){e[1]=Ge(n[1],t.min[1],t.max[1])}function oA(e,t){return t[0]<=e.max[0]&&t[0]>=e.min[0]&&t[1]<=e.max[1]&&t[1]>=e.min[1]}function aA(e,t){return t[1]<=e.max[1]&&t[1]>=e.min[1]}function hf(e,t,n=0){const i=e.min[0]+n<=t.max[0]-n&&t.min[0]+n<=e.max[0]-n,r=e.min[1]+n<=t.max[1]-n&&t.min[1]+n<=e.max[1]-n;return i&&r}function lA(e,t){return{min:[Math.max(e.min[0],t.min[0]),Math.max(e.min[1],t.min[1])],max:[Math.min(e.max[0],t.max[0]),Math.min(e.max[1],t.max[1])]}}function cA(e,t){const n=fa([],e),i=(e.max[0]-e.min[0])/2*t,r=(e.max[1]-e.min[1])/2*t;e.min[0]=n[0]-i,e.min[1]=n[1]-r,e.max[0]=n[0]+i,e.max[1]=n[1]+r}function fA(e,t){return{min:bt(1/0,1/0,1/0),max:bt(-1/0,-1/0,-1/0)}}function uA(e,t){e.min[0]=Math.min(e.min[0],t[0]),e.min[1]=Math.min(e.min[1],t[1]),e.min[2]=Math.min(e.min[2],t[2]),e.max[0]=Math.max(e.max[0],t[0]),e.max[1]=Math.max(e.max[1],t[1]),e.max[2]=Math.max(e.max[2],t[2])}function dA(e){if(!hA(e))return;const t=e.max[0]-e.min[0],n=e.max[1]-e.min[1],i=e.max[2]-e.min[2];return Math.sqrt(t*t+n*n+i*i)}function hA(e){return e.min[0]!==1/0&&e.min[1]!==1/0&&e.min[2]!==1/0&&e.max[0]!==-1/0&&e.max[1]!==-1/0&&e.max[2]!==-1/0}function pf(){let e=new Zt(9);return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e}function pA(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[4],e[4]=t[5],e[5]=t[6],e[6]=t[8],e[7]=t[9],e[8]=t[10],e}function gA(e,t,n){let i=t[0],r=t[1],s=t[2],o=t[3],a=t[4],l=t[5],c=t[6],f=t[7],u=t[8],d=n[0],h=n[1],g=n[2],y=n[3],p=n[4],v=n[5],A=n[6],w=n[7],S=n[8];return e[0]=d*i+h*o+g*c,e[1]=d*r+h*a+g*f,e[2]=d*s+h*l+g*u,e[3]=y*i+p*o+v*c,e[4]=y*r+p*a+v*f,e[5]=y*s+p*l+v*u,e[6]=A*i+w*o+S*c,e[7]=A*r+w*a+S*f,e[8]=A*s+w*l+S*u,e}function ua(){let e=new Zt(4);return e[0]=0,e[1]=0,e[2]=0,e[3]=1,e}function mA(e){return e[0]=0,e[1]=0,e[2]=0,e[3]=1,e}function vA(e,t,n){n=n*.5;let i=Math.sin(n);return e[0]=i*t[0],e[1]=i*t[1],e[2]=i*t[2],e[3]=Math.cos(n),e}function yA(e,t,n){n*=.5;let i=t[0],r=t[1],s=t[2],o=t[3],a=Math.sin(n),l=Math.cos(n);return e[0]=i*l-s*a,e[1]=r*l+o*a,e[2]=s*l+i*a,e[3]=o*l-r*a,e}function xA(e,t,n){n*=.5;let i=t[0],r=t[1],s=t[2],o=t[3],a=Math.sin(n),l=Math.cos(n);return e[0]=i*l+r*a,e[1]=r*l-i*a,e[2]=s*l+o*a,e[3]=o*l-s*a,e}function da(e,t,n,i){let r=t[0],s=t[1],o=t[2],a=t[3],l=n[0],c=n[1],f=n[2],u=n[3],d,h,g,y,p;return h=r*l+s*c+o*f+a*u,h<0&&(h=-h,l=-l,c=-c,f=-f,u=-u),1-h>1e-6?(d=Math.acos(h),g=Math.sin(d),y=Math.sin((1-i)*d)/g,p=Math.sin(i*d)/g):(y=1-i,p=i),e[0]=y*r+p*l,e[1]=y*s+p*c,e[2]=y*o+p*f,e[3]=y*a+p*u,e}function wA(e,t){let n=t[0]+t[4]+t[8],i;if(n>0)i=Math.sqrt(n+1),e[3]=.5*i,i=.5/i,e[0]=(t[5]-t[7])*i,e[1]=(t[6]-t[2])*i,e[2]=(t[1]-t[3])*i;else{let r=0;t[4]>t[0]&&(r=1),t[8]>t[r*3+r]&&(r=2);let s=(r+1)%3,o=(r+2)%3;i=Math.sqrt(t[r*3+r]-t[s*3+s]-t[o*3+o]+1),e[r]=.5*i,i=.5/i,e[3]=(t[s*3+o]-t[o*3+s])*i,e[s]=(t[s*3+r]+t[r*3+s])*i,e[o]=(t[o*3+r]+t[r*3+o])*i}return e}const Cp=Yw;(function(){let e=nt(),t=bt(1,0,0),n=bt(0,1,0);return function(i,r,s){let o=cf(r,s);return o<-.999999?(gr(e,t,r),aa(e)<1e-6&&gr(e,n,r),jt(e,e),vA(i,e,Math.PI),i):o>.999999?(i[0]=0,i[1]=0,i[2]=0,i[3]=1,i):(gr(e,r,s),i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=1+o,Cp(i,i))}})(),(function(){let e=ua(),t=ua();return function(n,i,r,s,o,a){return da(e,i,o,a),da(t,r,s,a),da(n,e,t,2*a*(1-a)),n}})(),(function(){let e=pf();return function(t,n,i,r){return e[0]=i[0],e[3]=i[1],e[6]=i[2],e[1]=r[0],e[4]=r[1],e[7]=r[2],e[2]=-n[0],e[5]=-n[1],e[8]=-n[2],Cp(t,wA(t,e))}})();const Vn=[0,0,0],Wn=[0,0,0],gf=nt();pf();function In(e,t,n,i,r){if(t!==i||n!==r){const s=r-n,o=t-i,a=1/Math.sqrt(s*s+o*o);e[0]=s*a,e[1]=o*a}else e[0]=0,e[1]=0}function Fp(e,t,n,i){return ln(Vn,n,t),ln(Wn,n,i),gr(e,Wn,Vn),jt(e,e),e}function Hn(e,t,n,i,r){if(t!==i||n!==r){const s=i-t,o=r-n,a=1/Math.sqrt(s*s+o*o);e[0]=s*a,e[1]=o*a}else e[0]=0,e[1]=0}function Lp(e,t,n,i,r){const s=t+i,o=n+r,a=t*s+n*o,l=5;if(a!==0){const c=1/a;e[0]=s*c,e[1]=o*c,na(e)>l&&Fi(e,e)}else e[0]=0,e[1]=0}function at(e){return Ge(e*127,-127,127)}function mf(e,t=e){return e[0]=at(t[0]),e[1]=at(t[1]),e}function AA(e,t,n,i,r){e[0]=t*i+n*r,e[1]=n*i-t*r}function zi(e,t){const n=t[0];e[0]=-t[1],e[1]=n}function vf(e,t){const n=t[0];e[0]=t[1],e[1]=-n}function bA(e){return e[0]===0&&e[1]===0}function SA(e,t){return Math.atan2(t[1]-e[1],t[0]-e[0])}function EA(e,t){return[(e[0]+t[0])/2,(e[1]+t[1])/2]}function TA(e,t){const n=Math.sin(t),i=Math.cos(t),r=i*e[0]-n*e[1],s=n*e[0]+i*e[1];tt(e,r,s)}function PA(e,t,n,i,r=!0){if(ia(t,n)||ia(n,i)){tt(e,0,0);return}ii(Vn,n,t),ii(Wn,i,n),r?(zi(Vn,Vn),zi(Wn,Wn)):(vf(Vn,Vn),vf(Wn,Wn)),Fi(Vn,Vn),Fi(Wn,Wn),Tn(e,Vn,Wn),Fi(e,e)}function IA(e,t,n){t[0]=Pn(Be(gf,e[0],e[1],e[2])),t[1]=Pn(Be(gf,e[3],e[4],e[5])),t[2]=Pn(Be(gf,e[6],e[7],e[8]))}function MA(e,t,n,i){t[0]=Pn(bt(e[0],e[1],e[2])),t[1]=Pn(bt(e[4],e[5],e[6])),t[2]=Pn(bt(e[8],e[9],e[10])),n[0]=e[12],n[1]=e[13],n[2]=e[14]}function _A(e,t,n,i){const[r,s]=e,[o,a]=t,[l,c]=n;return i[0]=Math.min(Math.max(r,o),l),i[1]=Math.min(Math.max(s,a),c),i[2]=0,i}const yf=/\{(\w+)\}/g;function Qr(e,t){return e.replace(yf,(n,i)=>t[i])}function Bp(e){const[t,n]=e.split("?");if(!n)return t;const r=n.split("&").map(s=>s.split("=")).filter(([,s])=>s!=="undefined").map(s=>s.join("=")).join("&");return r.length?`${t}?${r}`:t}function CA(e,t){return(typeof e=="object"?e.url:Ko[e]).replace(yf,(n,i)=>{var r;return(r=t[i])!=null?r:n}).replace(yf,(n,i)=>{var r;return(r=t[i])!=null?r:n})}function $s(e,t){const n=Qr(t.host,{subdomain:t.subdomain}),i=Qr(typeof e=="object"?e.url:Ko[e],ie(V({},t),{host:n}));return Bp(i)}function eo(e,t){const n=Qr(e,t);return Bp(n)}function ha(e,t){let n=0;for(let i=0;i<t.length;i++)n+=t.charCodeAt(i);return e[n%e.length]}function FA(e,t){const n=new URL(t);return e.startsWith("//")?`${n.protocol}${e}`:e.startsWith("/")?`${n.origin}${e}`:e}for(var qr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",LA=typeof Uint8Array=="undefined"?[]:new Uint8Array(256),pa=0;pa<qr.length;pa++)LA[qr.charCodeAt(pa)]=pa;var Dp=function(e){var t=new Uint8Array(e),n,i=t.length,r="";for(n=0;n<i;n+=3)r+=qr[t[n]>>2],r+=qr[(t[n]&3)<<4|t[n+1]>>4],r+=qr[(t[n+1]&15)<<2|t[n+2]>>6],r+=qr[t[n+2]&63];return i%3===2?r=r.substring(0,r.length-1)+"=":i%3===1&&(r=r.substring(0,r.length-2)+"=="),r};function BA(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n]*$(256,e.length-1-n);return t}function Op(e){const t=new Uint8Array(6);for(let n=0;n<6;n++)t[n]=Math.floor(e/$(256,5-n))&255;return encodeURIComponent(Dp(t.buffer))}function DA(e,t){var r,s,o,a,l,c;const n={};e.forEach((f,u)=>{n[f]=u});let i=e.length;n.selected=(r=n.selected)!=null?r:i++,n.hovered=(s=n.hovered)!=null?s:i++,n.dpi=(o=n.dpi)!=null?o:i++,n.isRealtime=(a=n.isRealtime)!=null?a:i++,n.pixelDensityPreset=(l=n.pixelDensityPreset)!=null?l:i++,n.tier=(c=n.tier)!=null?c:i++;for(const f in t)n[f]===void 0&&(n[f]=i++);return n}function Rp(e){const t=DA(e.tileProps,e.defaultProps),n={};for(const i in e.defaultProps)n[i]={index:t[i],value:e.defaultProps[i]};return{version:e.version,dictionaries:e.enumerationValues,reverseDictionaries:Object.keys(e.enumerationValues).reduce((i,r)=>(i[r]=Yc(e.enumerationValues[r]),i),{}),tileProps:t,tilePropsByIndex:Yc(t),defaultProps:n,vertexPropsLegacy:wf(e.vertexProps)?OA(e):{},vertexProps:wf(e.vertexProps)?[]:e.vertexProps}}function OA(e){const t=e.vertexProps,n={point:["x","y","z"],polygon:["x","y","cut","signed_z"],polyline:["x","y"]};if(!t)return n;if(!wf(t))return console.warn(`Попытка сгенерировать vertexPropsLegacy для метатайла версии ${e.version}`),{};const i={0:"point",1:"polyline",2:"polygon"};return Object.keys(t).forEach(r=>{const s=i[r];if(typeof s=="undefined"){console.warn(`Неизвестный тип геометрии "${r}", нужно его поддержать`);return}n[s]=t[parseInt(r,10)]}),n}function zp(e,t){const n={};if(t)for(let i=0;i<t.length;i++)n[t[i]]=i;return Rp({enumerationValues:{db_sublayer:n},version:"7.0.0",defaultProps:{},tileProps:e,vertexProps:[]})}function Kr(e,t){const{tileProps:n}=e;let i=Object.keys(n).length;for(const r of t)n[r]===void 0&&(n[r]=i,i+=1)}let Se=0;const wr={beginningIsCut:Se++,class:Se++,componentDistanceEnd:Se++,componentDistanceStart:Se++,db_icon_priority:Se++,db_label_priority:Se++,db_label2_priority:Se++,dpi:Se++,endingIsCut:Se++,height:Se++,db_hidden_by_plan_building_id:Se++,db_hidden_by_plan_id:Se++,id:Se++,isRealtime:Se++,db_label:Se++,db_label2:Se++,nextPointX:Se++,nextPointY:Se++,db_object_class:Se++,objectLength:Se++,pixelDensityPreset:Se++,previousPointX:Se++,previousPointY:Se++,db_region:Se++,selected:Se++,hovered:Se++,db_sublayer:Se++,traffic_color:Se++,traffic_road_class:Se++,traffic_road_z_level:Se++,db_tiers:Se++,model_src:Se++,linkedIds:Se++,db_model_rotation_angle:Se++,db_plan_id:Se++,traffic_color2:Se++},RA={version:"5.0.0",tileProps:wr,tilePropsByIndex:Yc(wr),defaultProps:{},dictionaries:{},reverseDictionaries:{},vertexPropsLegacy:{},vertexProps:[]},Np=[],xf={},Gp={sourceName:"zenith"};function wf(e){return!Array.isArray(e)}class Af{constructor(){this.events={}}on(t,n){let i=this.events[t];return i||(i=this.events[t]=[]),i.push(n),this}once(t,n){const i=r=>{this.off(t,i),n.call(this,r)};return this.on(t,i),this}off(t,n){const i=this.events[t];if(!i)return this;const r=i.indexOf(n);return r!==-1&&i.splice(r,1),this}emit(t,n){const i=this.events[t];if(!i)return this;const r=i.slice();for(let s=0;s<r.length;s++)r[s].call(this,n);return this}}let zA=1;function ga(){return zA++}let NA=1;const ma=()=>++NA,GA=ma(),kA=ma(),UA=ma(),bf=65536*65536,kp=1/bf,VA=12,Up=typeof TextDecoder=="undefined"?null:new TextDecoder("utf-8"),Sf=0,va=1,to=2,ya=5;class xa{constructor(t=new Uint8Array(16)){this.buf=ArrayBuffer.isView(t)?t:new Uint8Array(t),this.dataView=new DataView(this.buf.buffer),this.pos=0,this.type=0,this.length=this.buf.length}readFields(t,n,i=this.length){for(;this.pos<i;){const r=this.readVarint(),s=r>>3,o=this.pos;this.type=r&7,t(s,n,this),this.pos===o&&this.skip(r)}return n}readMessage(t,n){return this.readFields(t,n,this.readVarint()+this.pos)}readFixed32(){const t=this.dataView.getUint32(this.pos,!0);return this.pos+=4,t}readSFixed32(){const t=this.dataView.getInt32(this.pos,!0);return this.pos+=4,t}readFixed64(){const t=this.dataView.getUint32(this.pos,!0)+this.dataView.getUint32(this.pos+4,!0)*bf;return this.pos+=8,t}readSFixed64(){const t=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*bf;return this.pos+=8,t}readFloat(){const t=this.dataView.getFloat32(this.pos,!0);return this.pos+=4,t}readDouble(){const t=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,t}readVarint(t){const n=this.buf;let i,r;return r=n[this.pos++],i=r&127,r<128||(r=n[this.pos++],i|=(r&127)<<7,r<128)||(r=n[this.pos++],i|=(r&127)<<14,r<128)||(r=n[this.pos++],i|=(r&127)<<21,r<128)?i:(r=n[this.pos],i|=(r&15)<<28,WA(i,t,this))}readVarint64(){return this.readVarint(!0)}readSVarint(){const t=this.readVarint();return t%2===1?(t+1)/-2:t/2}readBoolean(){return!!this.readVarint()}readString(){const t=this.readVarint()+this.pos,n=this.pos;return this.pos=t,t-n>=VA&&Up?Up.decode(this.buf.subarray(n,t)):nb(this.buf,n,t)}readBytes(){const t=this.readVarint()+this.pos,n=this.buf.subarray(this.pos,t);return this.pos=t,n}readPackedVarint(t=[],n){const i=this.readPackedEnd();for(;this.pos<i;)t.push(this.readVarint(n));return t}readPackedSVarint(t=[]){const n=this.readPackedEnd();for(;this.pos<n;)t.push(this.readSVarint());return t}readPackedBoolean(t=[]){const n=this.readPackedEnd();for(;this.pos<n;)t.push(this.readBoolean());return t}readPackedFloat(t=[]){const n=this.readPackedEnd();for(;this.pos<n;)t.push(this.readFloat());return t}readPackedDouble(t=[]){const n=this.readPackedEnd();for(;this.pos<n;)t.push(this.readDouble());return t}readPackedFixed32(t=[]){const n=this.readPackedEnd();for(;this.pos<n;)t.push(this.readFixed32());return t}readPackedSFixed32(t=[]){const n=this.readPackedEnd();for(;this.pos<n;)t.push(this.readSFixed32());return t}readPackedFixed64(t=[]){const n=this.readPackedEnd();for(;this.pos<n;)t.push(this.readFixed64());return t}readPackedSFixed64(t=[]){const n=this.readPackedEnd();for(;this.pos<n;)t.push(this.readSFixed64());return t}readPackedEnd(){return this.type===to?this.readVarint()+this.pos:this.pos+1}skip(t){const n=t&7;if(n===Sf)for(;this.buf[this.pos++]>127;);else if(n===to)this.pos=this.readVarint()+this.pos;else if(n===ya)this.pos+=4;else if(n===va)this.pos+=8;else throw new Error(`Unimplemented type: ${n}`)}writeTag(t,n){this.writeVarint(t<<3|n)}realloc(t){let n=this.length||16;for(;n<this.pos+t;)n*=2;if(n!==this.length){const i=new Uint8Array(n);i.set(this.buf),this.buf=i,this.dataView=new DataView(i.buffer),this.length=n}}finish(){return this.length=this.pos,this.pos=0,this.buf.subarray(0,this.length)}writeFixed32(t){this.realloc(4),this.dataView.setInt32(this.pos,t,!0),this.pos+=4}writeSFixed32(t){this.realloc(4),this.dataView.setInt32(this.pos,t,!0),this.pos+=4}writeFixed64(t){this.realloc(8),this.dataView.setInt32(this.pos,t&-1,!0),this.dataView.setInt32(this.pos+4,Math.floor(t*kp),!0),this.pos+=8}writeSFixed64(t){this.realloc(8),this.dataView.setInt32(this.pos,t&-1,!0),this.dataView.setInt32(this.pos+4,Math.floor(t*kp),!0),this.pos+=8}writeVarint(t){if(t=+t||0,t>268435455||t<0){HA(t,this);return}this.realloc(4),this.buf[this.pos++]=t&127|(t>127?128:0),!(t<=127)&&(this.buf[this.pos++]=(t>>>=7)&127|(t>127?128:0),!(t<=127)&&(this.buf[this.pos++]=(t>>>=7)&127|(t>127?128:0),!(t<=127)&&(this.buf[this.pos++]=t>>>7&127)))}writeSVarint(t){this.writeVarint(t<0?-t*2-1:t*2)}writeBoolean(t){this.writeVarint(+t)}writeString(t){t=String(t),this.realloc(t.length*4),this.pos++;const n=this.pos;this.pos=ib(this.buf,t,this.pos);const i=this.pos-n;i>=128&&Vp(n,i,this),this.pos=n-1,this.writeVarint(i),this.pos+=i}writeFloat(t){this.realloc(4),this.dataView.setFloat32(this.pos,t,!0),this.pos+=4}writeDouble(t){this.realloc(8),this.dataView.setFloat64(this.pos,t,!0),this.pos+=8}writeBytes(t){const n=t.length;this.writeVarint(n),this.realloc(n);for(let i=0;i<n;i++)this.buf[this.pos++]=t[i]}writeRawMessage(t,n){this.pos++;const i=this.pos;t(n,this);const r=this.pos-i;r>=128&&Vp(i,r,this),this.pos=i-1,this.writeVarint(r),this.pos+=r}writeMessage(t,n,i){this.writeTag(t,to),this.writeRawMessage(n,i)}writePackedVarint(t,n){n.length&&this.writeMessage(t,ZA,n)}writePackedSVarint(t,n){n.length&&this.writeMessage(t,jA,n)}writePackedBoolean(t,n){n.length&&this.writeMessage(t,KA,n)}writePackedFloat(t,n){n.length&&this.writeMessage(t,QA,n)}writePackedDouble(t,n){n.length&&this.writeMessage(t,qA,n)}writePackedFixed32(t,n){n.length&&this.writeMessage(t,JA,n)}writePackedSFixed32(t,n){n.length&&this.writeMessage(t,$A,n)}writePackedFixed64(t,n){n.length&&this.writeMessage(t,eb,n)}writePackedSFixed64(t,n){n.length&&this.writeMessage(t,tb,n)}writeBytesField(t,n){this.writeTag(t,to),this.writeBytes(n)}writeFixed32Field(t,n){this.writeTag(t,ya),this.writeFixed32(n)}writeSFixed32Field(t,n){this.writeTag(t,ya),this.writeSFixed32(n)}writeFixed64Field(t,n){this.writeTag(t,va),this.writeFixed64(n)}writeSFixed64Field(t,n){this.writeTag(t,va),this.writeSFixed64(n)}writeVarintField(t,n){this.writeTag(t,Sf),this.writeVarint(n)}writeSVarintField(t,n){this.writeTag(t,Sf),this.writeSVarint(n)}writeStringField(t,n){this.writeTag(t,to),this.writeString(n)}writeFloatField(t,n){this.writeTag(t,ya),this.writeFloat(n)}writeDoubleField(t,n){this.writeTag(t,va),this.writeDouble(n)}writeBooleanField(t,n){this.writeVarintField(t,+n)}}function WA(e,t,n){const i=n.buf;let r,s;if(s=i[n.pos++],r=(s&112)>>4,s<128||(s=i[n.pos++],r|=(s&127)<<3,s<128)||(s=i[n.pos++],r|=(s&127)<<10,s<128)||(s=i[n.pos++],r|=(s&127)<<17,s<128)||(s=i[n.pos++],r|=(s&127)<<24,s<128)||(s=i[n.pos++],r|=(s&1)<<31,s<128))return Jr(e,r,t);throw new Error("Expected varint not more than 10 bytes")}function Jr(e,t,n){return n?t*4294967296+(e>>>0):(t>>>0)*4294967296+(e>>>0)}function HA(e,t){let n,i;if(e>=0?(n=e%4294967296|0,i=e/4294967296|0):(n=~(-e%4294967296),i=~(-e/4294967296),n^4294967295?n=n+1|0:(n=0,i=i+1|0)),e>=18446744073709552e3||e<-18446744073709552e3)throw new Error("Given varint doesn't fit into 10 bytes");t.realloc(10),YA(n,i,t),XA(i,t)}function YA(e,t,n){n.buf[n.pos++]=e&127|128,e>>>=7,n.buf[n.pos++]=e&127|128,e>>>=7,n.buf[n.pos++]=e&127|128,e>>>=7,n.buf[n.pos++]=e&127|128,e>>>=7,n.buf[n.pos]=e&127}function XA(e,t){const n=(e&7)<<4;t.buf[t.pos++]|=n|((e>>>=3)?128:0),e&&(t.buf[t.pos++]=e&127|((e>>>=7)?128:0),e&&(t.buf[t.pos++]=e&127|((e>>>=7)?128:0),e&&(t.buf[t.pos++]=e&127|((e>>>=7)?128:0),e&&(t.buf[t.pos++]=e&127|((e>>>=7)?128:0),e&&(t.buf[t.pos++]=e&127)))))}function Vp(e,t,n){const i=t<=16383?1:t<=2097151?2:t<=268435455?3:Math.floor(Math.log(t)/(Math.LN2*7));n.realloc(i);for(let r=n.pos-1;r>=e;r--)n.buf[r+i]=n.buf[r]}function ZA(e,t){for(let n=0;n<e.length;n++)t.writeVarint(e[n])}function jA(e,t){for(let n=0;n<e.length;n++)t.writeSVarint(e[n])}function QA(e,t){for(let n=0;n<e.length;n++)t.writeFloat(e[n])}function qA(e,t){for(let n=0;n<e.length;n++)t.writeDouble(e[n])}function KA(e,t){for(let n=0;n<e.length;n++)t.writeBoolean(e[n])}function JA(e,t){for(let n=0;n<e.length;n++)t.writeFixed32(e[n])}function $A(e,t){for(let n=0;n<e.length;n++)t.writeSFixed32(e[n])}function eb(e,t){for(let n=0;n<e.length;n++)t.writeFixed64(e[n])}function tb(e,t){for(let n=0;n<e.length;n++)t.writeSFixed64(e[n])}function nb(e,t,n){let i="",r=t;for(;r<n;){const s=e[r];let o=null,a=s>239?4:s>223?3:s>191?2:1;if(r+a>n)break;let l,c,f;a===1?s<128&&(o=s):a===2?(l=e[r+1],(l&192)===128&&(o=(s&31)<<6|l&63,o<=127&&(o=null))):a===3?(l=e[r+1],c=e[r+2],(l&192)===128&&(c&192)===128&&(o=(s&15)<<12|(l&63)<<6|c&63,(o<=2047||o>=55296&&o<=57343)&&(o=null))):a===4&&(l=e[r+1],c=e[r+2],f=e[r+3],(l&192)===128&&(c&192)===128&&(f&192)===128&&(o=(s&15)<<18|(l&63)<<12|(c&63)<<6|f&63,(o<=65535||o>=1114112)&&(o=null))),o===null?(o=65533,a=1):o>65535&&(o-=65536,i+=String.fromCharCode(o>>>10&1023|55296),o=56320|o&1023),i+=String.fromCharCode(o),r+=a}return i}function ib(e,t,n){for(let i=0,r,s;i<t.length;i++){if(r=t.charCodeAt(i),r>55295&&r<57344)if(s)if(r<56320){e[n++]=239,e[n++]=191,e[n++]=189,s=r;continue}else r=s-55296<<10|r-56320|65536,s=null;else{r>56319||i+1===t.length?(e[n++]=239,e[n++]=191,e[n++]=189):s=r;continue}else s&&(e[n++]=239,e[n++]=191,e[n++]=189,s=null);r<128?e[n++]=r:(r<2048?e[n++]=r>>6|192:(r<65536?e[n++]=r>>12|224:(e[n++]=r>>18|240,e[n++]=r>>12&63|128),e[n++]=r>>6&63|128),e[n++]=r&63|128)}return n}Array(16);function Ar(e,t){return{a:e[1]-t[1],b:t[0]-e[0],c:e[0]*t[1]-t[0]*e[1]}}function rb(e,t){return Math.abs(Wp(e,t))}function Wp(e,t){return(t.a*e[0]+t.b*e[1]+t.c)/Math.sqrt(t.a*t.a+t.b*t.b)}function sb(e,t,n){const{a:i,b:r,c:s}=Ar(e,t);return bt(n,-(i*n+s)/r,0)}function ob(e,t,n){const{a:i,b:r,c:s}=Ar(e,t);return bt(-(r*n+s)/i,n,0)}const br=Js(),Vt=Js();function ab(e,t,n){const i=t[t.length-1]*n;let r=e[0],s=0;const o=[r];let a=1,l;for(;a<e.length&&!l;){const c=e[a],f=t[a];let u=c;if(f>i){if(!l){const d=(i-s)/(f-s);l=[],Kc(l,r,c,d)}u=l}o.push(u),r=u,s=t[a],a++}return o}function lb(e,t){let n=e[0];df(br),xr(br,n);let i=[n];const r=[i];let s=1;for(;s<e.length;){const o=e[s];let a=!1,l=o;if(_p(Vt,br),xr(Vt,l),Vt.max[0]-Vt.min[0]>t){const c=Vt.max[0]===l[0]?Vt.min[0]+t:Vt.max[0]-t;l=sb(n,l,c),a=!0}if(a&&(_p(Vt,br),xr(Vt,l)),Vt.max[1]-Vt.min[1]>t){const c=Vt.max[1]===l[1]?Vt.min[1]+t:Vt.max[1]-t;l=ob(n,l,c),a=!0}a?(i.push(l),df(br),xr(br,l),i=[l],r.push(i),n=l):(i.push(o),xr(br,o),n=o,s++)}return r}function cb(e,t,n){const i=e[0]-t[0],r=e[1]-t[1],s=n[0]-t[0],o=n[1]-t[1],a=i*s+r*o,l=s*s+o*o,c=l!==0?a/l:0;return c<0?t:c>1?n:[t[0]+c*s,t[1]+c*o]}function wa(e){const t=e[0][0],n=e[0][1],i=e[1][0],r=e[1][1],s=e[2][0],o=e[2][1],a=e[3][0],l=e[3][1];return{min:[Math.min(t,i,s,a),Math.min(n,r,o,l)],max:[Math.max(t,i,s,a),Math.max(n,r,o,l)]}}function fb(e){return[[e[0][0],e[0][1],e[0][2]],[e[1][0],e[1][1],e[1][2]],[e[2][0],e[2][1],e[2][2]],[e[3][0],e[3][1],e[3][2]]]}function Hp(e,t){const n=wa(e);if(!hf(t,n))return!1;const i=[Ar(e[3],e[2]),Ar(e[1],e[0]),Ar(e[0],e[3]),Ar(e[2],e[1])],r=[t.min,t.max,[t.min[0],t.max[1]],[t.max[0],t.min[1]]];for(const s of i){let o=!0;for(let a=0;a<r.length;a++){const l=r[a];if(s.a*l[0]+s.b*l[1]+s.c<0){o=!1;break}}if(o)return!1}return!0}function ub(e,t,n){e.forEach(i=>{const r=1+t/Ep(n,i);mr(i,n,i,r)})}function db(e,t){if(e.tiles)for(const n of e.tiles)t.writeMessage(1,hb,n)}function hb(e,t){e.x&&t.writeVarintField(1,e.x),e.y&&t.writeVarintField(2,e.y),e.zoom&&t.writeVarintField(3,e.zoom)}function pb(e,t){return e.readFields(gb,{tileGroups:[]},t)}function gb(e,t,n){e===1&&t.tileGroups.push(mb(n,n.readVarint()+n.pos))}function mb(e,t){return e.readFields(vb,{x:0,y:0,zoom:0,tiles:[]},t)}function vb(e,t,n){e===1?t.x=n.readVarint():e===2?t.y=n.readVarint():e===3?t.zoom=n.readVarint():e===4&&t.tiles.push(yb(n,n.readVarint()+n.pos))}function yb(e,t){return e.readFields(xb,{regionId:0,hash:void 0,data:void 0},t)}function xb(e,t,n){e===1?t.regionId=n.readVarint():e===2?t.hash=n.readBytes():e===3&&(t.data=n.readBytes())}const $r=[0,0,0];function Bt(e){return{coords:e,size:Mn(e[2]),offset:ts(e)}}function De(e){return Yp(e[0],e[1],e[2],e[3])}function Yp(e,t,n,i){return`${e}_${t}_${n}_${i}`}function wb(e,t){return`${De(e)}_${t.stringify()}`}function Ef(e){const t=e.split("_");return[parseInt(t[0],10),parseInt(t[1],10),parseInt(t[2],10),parseInt(t[3],10)]}function Xp(e){return ur.subdomains[Math.abs(e[0]+e[1])%ur.subdomains.length]}function Ab(e){const t=new xa(e),n=pb(t),{x:i,y:r,zoom:s,tiles:o}=n.tileGroups[0];return o.map(({regionId:a,hash:l,data:c})=>(c||(console.warn(`Tile ${s}_${i}_${r} from region ${a} is corrupt (has no data)`),c=new Uint8Array(0)),{data:c,regionId:a,metatileHash:BA(l)}))}function bb(e){return e.map(t=>({regionId:t.regionId,metatileHash:t.metatileHash}))}function Sb(e){const t=Math.ceil(e.byteLength/4)*4,n=new ArrayBuffer(t);return new Uint8Array(n).set(e),n}function Aa(e){const[t,n,i]=e;return{min:ts([t,n,i,i]),max:ts([t+1,n+1,i,i])}}function ba(e,t,n,i=0){const r=Aa(e);return r.min[0]-=i,r.min[1]-=i,r.max[0]+=i,r.max[1]+=i,n.environmentManager.isAABBInFog(r)?!1:Hp(t,r)}function Eb(e){return Math.trunc(e/2)*2+1}function Tf(e,t=1,n=3,i=!1){let r=1/Math.cos(Le(e));return i&&(r=Math.log2(r)),Ge(Math.ceil(r),t,n)-1}const Tb=(e,t)=>(isNaN(e[0])||e[0]===t[0])&&(isNaN(e[1])||e[1]===t[1])&&(isNaN(e[2])||e[2]===t[2])&&(isNaN(e[3])||e[3]===t[3]);function Pb(e,t,n){const i=Ib(t,e.size),r=Math.trunc(t),s=Array.from(e.center);js(s);const o=me.toGeo(s),a={min:[o[0]-Ge(i*2,0,90),Ge(o[1]-i,-85,85)],max:[o[0]+Ge(i*2,0,90),Ge(o[1]+i,-85,85)]},l=Math.max(Tf(a.min[1],2,4),Tf(a.max[1],2,4)),c=Math.max(n,r-l),f=Pf(s,c,!0);f[0]=Math.round(f[0]),f[1]=Math.round(f[1]);const u=new Ks(e),d=Zp(e,u,o),h=Wb(f,o,d,u,e),g=[];return h.forEach(y=>{Tb([NaN,2,2,NaN],y)?g.push(...qp(y,1)):g.push(y)}),g.filter(y=>Pa(e,u,y))}function Ib(e,t){const n=Oi*Ee,i=jr(e,t)+n,r=En.fov/2,s=Math.sin(r),o=Math.cos(r),a=n/i;let l=hr(Math.acos($(s,2)/a+o*Math.sqrt(1-$(s,2)/$(a,2))));return Number.isNaN(l)&&(l=90),l}function Zp(e,t,n){const i=Lt.toGeo(t.ecef.unproject([e.viewport.left,e.viewport.top]));return Math.min(3*Math.max(oa(i,n)),t.ecef.visibleArc)}function Mb(e,t,n,i,r,s){const[,,o]=e,a=Cb(e),l=i>=5?2:1,c=Tf((a.max[1]+a.min[1])/2,l,3,!0),f=Math.max(Math.abs(a.min[1]),Math.abs(a.max[1])),u=Math.max(n,i-c);return o>=u||f>70&&s>0||f>82||oa(t,[(a.max[0]+a.min[0])/2,(a.max[1]+a.min[1])/2])>.75*r}function _b(e,t){const i=Math.trunc(e.zoom),r=Array.from(e.center);js(r),me.toGeo(r,r);const s=[],o=new Ks(e),a=Zp(e,o,r);function l(c,f=0){if(eg(r,a,c)&&Pa(e,o,c))if(Mb(c,r,2,i,o.ecef.visibleArc,f))s.push(c);else for(const u of qp(c,1))l(u,f+1)}return Pb(e,Math.trunc(e.zoom),2).map(([c,f,u])=>{l([c,f,u,t])}),s}function Cb(e){return{min:jp(e),max:jp([e[0]+1,e[1]+1,e[2],e[3]])}}function jp(e){const t=ts(e);return me.toGeo(t)}function Qp(e,t,n,i,r,s=0,o=1/0,a=!1,l=!1){if(e.globeMode)return _b(e,r);a&&(n=Eb(n),n>o&&(n-=2));const c=wa(e.tilesBounds),f=Mn(n),u=$(2,n),d=Math.floor((c.min[0]+2147483648-s)/f),h=Math.floor((c.max[0]+2147483648+s)/f),g=Math.max(Math.floor((c.min[1]+2147483648-s)/f),0),y=Math.min(Math.floor((c.max[1]+2147483648+s)/f),u-1),p=[],v=new Set;for(let A=d;A<=h;A++)for(let w=g;w<=y;w++){const S=[A,w,n,r];if(ba(S,e.tilesBounds,t,s)){S[0]=(u+S[0]%u)%u;const T=De(S);v.has(T)||(v.add(T),p.push(S))}}return l===!0&&Fb(p,v,e,t,n,i,r),p}function Fb(e,t,n,i,r,s,o){const a=new Set,l=fb(n.tilesBounds);let c=e;for(let f=r;f>=s;f--){let u=0;const d=[];c.forEach(S=>{const T=Lb(S),I=De(T);a.has(I)||(d.push(T),a.add(I),Bb(T,C=>{const M=De(C);!t.has(M)&&!a.has(M)&&ba(C,n.extendedTilesBounds,i)&&(e.push(C),t.add(M),u++)}))});const h=Mn(f-1);ub(l,h,n.center);const g=wa(l),y=$(2,f-1),p=Math.floor((g.min[0]+2147483648)/h),v=Math.floor((g.max[0]+2147483648)/h),A=Math.max(Math.floor((g.min[1]+2147483648)/h),0),w=Math.min(Math.floor((g.max[1]+2147483648)/h),y-1);for(let S=p;S<=v;S++)for(let T=A;T<=w;T++){const I=[S,T,f-1,o];I[0]=(y+I[0]%y)%y;const C=De(I);!a.has(C)&&ba(I,l,i)&&(d.push(I),u++)}if(!u)break;c=d}}function Lb(e,t=1){const[n,i,r,s]=e,o=Math.pow(2,t);return[Math.trunc(n/o),Math.trunc(i/o),r-t,s]}function qp(e,t){const[n,i,r,s]=e,o=Math.pow(2,t),a=[];for(let l=0;l<o;l++)for(let c=0;c<o;c++)a.push([n*o+l,i*o+c,r+t,s]);return a}function Bb(e,t){let[n,i,r]=e;const s=e[3];n*=2,i*=2,r++,t([n,i,r,s]),t([n+1,i,r,s]),t([n,i+1,r,s]),t([n+1,i+1,r,s])}function Db(e,t,n,i,r,s,o,a,l,c,f){const u=new xa,d={tiles:[{x:r[0],y:r[1],zoom:r[2]}]};db(d,u);const h={x:r[0].toString(),y:r[1].toString(),z:r[2].toString(),protocol:n,host:e,subdomain:i[Math.abs(r[0]+r[1])%i.length],tileSet:t,lang:a,appId:o,tileKey:s,defaultLang:c,dt:f==null?void 0:f.join(","),request:encodeURIComponent(Dp(u.finish()))};return $s(l?{url:l}:"tiles",h)}function Ob(e,t){const n=e.coords,i=t.coords,r=n[2],s=i[2];return r===s?n[0]===i[0]&&n[1]===i[1]:r<s?Kp(e,t):Kp(t,e)}function Kp(e,t){if(t.zoomLevel<e.zoomLevel)return!1;if(t.zoomLevel===e.zoomLevel)return t.coords[0]===e.coords[0]&&t.coords[1]===e.coords[1]&&t.detailLevel>e.detailLevel;const n=Math.pow(2,t.coords[2]-e.coords[2]),i=e.coords[0]*n,r=i+n,s=e.coords[1]*n,o=s+n,a=t.coords[0],l=t.coords[1];return a>=i&&a<r&&l>=s&&l<o}function Sa(e,t,n){return Xs(e,$p(t.coords,$r))-Xs(e,$p(n.coords,$r))}function St(e,t,n){e[0]=t[0]*n.size/ae+n.offset[0],e[1]=t[1]*n.size/ae+n.offset[1],e[2]=t[2]}function Rb(e,t){e[0]=t.offset[0]/4294967296,e[1]=t.offset[1]/4294967296,e[2]=t.size/4294967296}const Ea=nt();function zb(e,t,n,i){var r;Ea[0]=t[0][n],Ea[1]=t[1][n],Ea[2]=((r=t[2])!=null?r:[])[n],St(e,Ea,i)}function Dt(e,t,n){e[0]=(t[0]-n.offset[0])*ae/n.size,e[1]=(t[1]-n.offset[1])*ae/n.size,e[2]=t[2]}function Mn(e){return $(2,32-e)}function no(e){return e[0]>=0&&e[0]<=ae&&e[1]>=0&&e[1]<=ae}function es(e,t){return e*4294967296/(ae*Math.pow(2,t))}function Wt(e){return Ge(e/_i*ae,0,He)}const io=ae/_i;function Jp(e){return e/ae*_i}function ts(e){const t=Mn(e[2]),n=2147483648;return bt(e[0]*t-n,e[1]*t-n,0)}function Nb(e){return[e[0]+2147483648,e[1]+2147483648,32,32]}function $p(e,t){const n=Mn(e[2]),i=2147483648;return Be(t,(e[0]+.5)*n-i,(e[1]+.5)*n-i,0)}function Pf(e,t,n=!1){const r=Mn(t),s=n?Math.min(2147483647,e[1]):e[1],o=e[0]-r/2,a=s-r/2;return[(o+2147483648)/r,(a+2147483648)/r,t,t]}function Gb(e,t=1){const n=Math.max(e.max[0]-e.min[0],e.max[1]-e.min[1],1)*t,i=32-Math.log(n)/Math.LN2,r=Ye();return fa(r,e),Pf(r,i)}const Ta=e=>{const[t,n,i,r]=e;return[t,$(2,i)-1-n,i,r]},fn=(e,t)=>{St($r,t,e);const n=me.toGeo($r);return me.scaleFactor(n[1])};function ro(e,t,n){return St($r,[e,t],n),me.toGeo($r)}function kb(e,t){const n=Math.min(e[0][0],e[1][0],e[2][0],e[3][0])+2147483648,i=Math.max(e[0][0],e[1][0],e[2][0],e[3][0])+2147483648,r=Math.floor(n/4294967296),s=Math.floor(i/4294967296);return t?[r]:Array.from({length:s-r+1},(o,a)=>a+r)}function Ub(e,t){return Lt.fromGeo(ro(t[0],t[1],e))}function Ni(e,t,n,i){const r=[];return St(r,i,n),oa(me.toGeo(r),e)<t}function eg(e,t,n){const i=Bt(n),r=ae;return Ni(e,t,i,[0,r/2,0])||Ni(e,t,i,[r,r/2,0])||Ni(e,t,i,[r/2,r,0])||Ni(e,t,i,[r/2,0,0])||Ni(e,t,i,[0,0,0])||Ni(e,t,i,[0,r,0])||Ni(e,t,i,[r,r,0])||Ni(e,t,i,[r,0,0])}const Xe={mapPoint:[0,0,0],geoPoint:[0,0],ecefPoint:[NaN,NaN,NaN],pixel:[NaN,NaN],corner:[0,0,0],bbox:{min:[0,0],max:[0,0]},viewport:{min:[0,0],max:[0,0]}};function Vb(e,t,n,i){const{mapPoint:r,geoPoint:s,ecefPoint:o}=Xe;St(r,n,t),me.toGeo(r,s),Lt.fromGeo(s,o),e.ecef.project(o,!1,i)}function Pa(e,t,n){const[,i,r]=n;if(i===0||i===$(2,r)-1)return!0;const s=Bt(n);let o=1/0,a=1/0,l=-1/0,c=-1/0;for(let f=0;f<4;f++)Xe.corner[0]=f>=2?ae:0,Xe.corner[1]=f===1||f===2?ae:0,Vb(t,s,Xe.corner,Xe.pixel),Xe.pixel[0]<o&&(o=Xe.pixel[0]),Xe.pixel[1]<a&&(a=Xe.pixel[1]),Xe.pixel[0]>l&&(l=Xe.pixel[0]),Xe.pixel[1]>c&&(c=Xe.pixel[1]);return Xe.bbox.min[0]=o,Xe.bbox.min[1]=a,Xe.bbox.max[0]=l,Xe.bbox.max[1]=c,Xe.viewport.min[0]=e.viewport.left,Xe.viewport.min[1]=e.viewport.top,Xe.viewport.max[0]=e.viewport.left+e.size[0],Xe.viewport.max[1]=e.viewport.top+e.size[1],hf(Xe.bbox,Xe.viewport)}function Wb(e,t,n,i,r){const a=new Map,l=[e],c=[];for(c.push(e);l.length;){if(c.length>300){console.warn("collectVisibleGlobeTiles: too many tiles",c.length);break}if(l.length>500){console.warn("collectVisibleGlobeTiles: queue overflow");break}const f=l.shift();if(f){const[u,d,h]=f;a.set(u+"."+d+"."+h,!0),Hb(f,a,t,n).filter(y=>Pa(r,i,y)).forEach(y=>{const[p,v,A]=y;a.set(p+"."+v+"."+A,!0),c.push(y),l.push(y)})}}return c}function Hb(e,t,n,i){const[r,s,o,a]=e,l=$(2,o)-1,c=p=>p>l?0:p<0?l:p,f=([p,v,A,w])=>((v>l||v<0)&&(v=v>l?l:0,p=A===0?p:(p+$(2,A-1))%$(2,A)),[p,v,A,w]),u=[c(r-1),s,o,a],d=[c(r+1),s,o,a],h=f([r,s-1,o,a]),g=f([r,s+1,o,a]);return[d,g,h,u].filter(p=>{const[v,A,w]=p;return!t.has(v+"."+A+"."+w)}).filter(p=>eg(n,i,p))}function Yb(e,t,n,i=0){return""}var If=(e=>(e[e.Tile=0]="Tile",e[e.Custom=1]="Custom",e))(If||{});class Xb{constructor(t){var n;this._enable=!1,this.name=t.name,this.index=t.index,this.location=t.location!==void 0?t.location:-1,this.locationsCount=(n=t.locationsCount)!=null?n:1,tg(this.locationsCount)}bindLocation(t,n){return this.location!==-1&&this.index!==!0&&t.bindAttribLocation(n,this.location,this.name),this}getLocation(t,n){return this.location===-1&&this.index!==!0&&(this.location=t.getAttribLocation(n,this.name)),this}bind(t,n){if(!this._enable&&this.index!==!0){for(let i=0;i<this.locationsCount;i++)t.enableVertexAttribArray(this.location+i);this._enable=!0}return n.bind(this.location,void 0),this}disable(t){if(this._enable&&this.index!==!0){for(let n=0;n<this.locationsCount;n++)t.disableVertexAttribArray(this.location+n);this._enable=!1}return this}}function tg(e){if(e<0||e>4)throw new Error("[WebGl] Invalid attribute location count. Must be 1, 2, 3 or 4")}const pe=class pe{constructor(t,n,i,r=!1,s=!1){var a;this.elementsType=null,this.isDirty=!0,this._glBuffer=null,this._gl=t,this._initData=n,this.byteLength=n.byteLength,this.type=r?pe.ElementArrayBuffer:pe.ArrayBuffer,this.options=Object.assign({},pe.defaultOptions,i),this.drawType=(a=i==null?void 0:i.drawType)!=null?a:pe.StaticDraw;const o=[pe.UnsignedByte,pe.UnsignedShort,pe.UnsignedInt];r&&!o.includes(this.options.dataType)&&(console.warn("Please provide dataType of one of the following values:Buffer.UnsignedByte, Buffer.UnsignedShort, Buffer.UnsignedInt. Defaulting to UnsignedInt"),this.options.dataType=pe.UnsignedInt),this._preserveData=s}static _dataTypeSize(t){switch(t){case pe.Byte:case pe.UnsignedByte:return 1;case pe.UnsignedShort:case pe.Short:return 2;case pe.Float:case pe.Int:case pe.UnsignedInt:return 4}throw new Error(`[WebGl] Unsupported Buffer data type: ${String(t)}`)}memSizeJs(){var t,n;return(n=(t=this._initData)==null?void 0:t.byteLength)!=null?n:0}memSizeGPU(){return this.byteLength}bind(t,n,i,r){const s=this._gl;if(this._glBuffer||this.prepare(),this.type===pe.ArrayBuffer){s.bindBuffer(s.ARRAY_BUFFER,this._glBuffer),t=t||0,n=n||this.options,r=r!=null?r:1,tg(r);const o=this._toGlParam(n.dataType)||s.FLOAT;if(r===1)s.vertexAttribPointer(t,n.itemSize,o,n.normalized,n.stride,n.offset),this.bindVertexAttribDivisor(t,n,i);else{const a=pe._dataTypeSize(n.dataType);for(let l=0;l<r;l++)s.vertexAttribPointer(t+l,r,o,n.normalized,n.stride,n.offset+l*r*a),this.bindVertexAttribDivisor(t+l,n,i)}}else this.type===pe.ElementArrayBuffer&&s.bindBuffer(s.ELEMENT_ARRAY_BUFFER,this._glBuffer);return this}remove(){return this._unprepare(),this}subData(t,n){const i=this._gl;this._glBuffer||this.prepare();const r=this._toGlParam(this.type)||i.ARRAY_BUFFER;return i.bindBuffer(r,this._glBuffer),i.bufferSubData(r,t,n),this}replaceData(t){t&&(this._initData=t),this.isDirty=!0}commitData(){const t=this._gl,n=this._toGlParam(this.type)||t.ARRAY_BUFFER,i=this._toGlParam(this.drawType)||t.STATIC_DRAW;t.bindBuffer(n,this._glBuffer),t.bufferData(n,this._initData,i),this.isDirty=!1}getGLType(){return this._toGlParam(this.options.dataType)}getData(){return this._initData}prepare(){return this._glBuffer=this._gl.createBuffer(),this.commitData(),this._preserveData||(this._initData=null),this}_unprepare(){this._glBuffer&&this._gl.deleteBuffer(this._glBuffer),this._glBuffer=null,this._initData=null,this.isDirty=!1}_toGlParam(t){const n=this._gl;return t===pe.ArrayBuffer?n.ARRAY_BUFFER:t===pe.ElementArrayBuffer?n.ELEMENT_ARRAY_BUFFER:t===pe.StaticDraw?n.STATIC_DRAW:t===pe.DynamicDraw?n.DYNAMIC_DRAW:t===pe.Byte?n.BYTE:t===pe.Short?n.SHORT:t===pe.Int?n.INT:t===pe.Float?n.FLOAT:t===pe.UnsignedByte?n.UNSIGNED_BYTE:t===pe.UnsignedShort?n.UNSIGNED_SHORT:t===pe.UnsignedInt?n.UNSIGNED_INT:null}_hasRealWebGLContext(){return typeof window!="undefined"&&("WebGLRenderingContext"in window||"WebGL2RenderingContext"in window)}bindVertexAttribDivisor(t,n,i){const r=this._gl;n.instanceDivisor&&this._hasRealWebGLContext()&&(r instanceof WebGLRenderingContext?i?i.vertexAttribDivisorANGLE(t,n.instanceDivisor):console.error("Can't set up instanced attribute divisor. Missing ANGLE_instanced_arrays extension"):r.vertexAttribDivisor(t,n.instanceDivisor))}};pe.ArrayBuffer=1,pe.ElementArrayBuffer=2,pe.StaticDraw=10,pe.DynamicDraw=11,pe.Float=20,pe.UnsignedByte=21,pe.UnsignedShort=22,pe.UnsignedInt=23,pe.Byte=24,pe.Short=25,pe.Int=26,pe.defaultOptions={itemSize:3,dataType:pe.Float,stride:0,offset:0,normalized:!1,instanceDivisor:0,drawType:pe.StaticDraw};let ht=pe;function Zb(e){if(e===void 0)return;const t=window.WebGLRenderingContext,i={[t.UNSIGNED_BYTE]:ht.UnsignedByte,[t.UNSIGNED_SHORT]:ht.UnsignedShort,[t.UNSIGNED_INT]:ht.UnsignedInt,[t.BYTE]:ht.Byte,[t.SHORT]:ht.Short,[t.INT]:ht.Int,[t.FLOAT]:ht.Float}[e];return i===void 0?(console.error(`Cannot translate ${e} gltf componentType`),NaN):i}function jb(e){return e}var Sr=(e=>(e[e.Striped=1]="Striped",e[e.Entrance=2]="Entrance",e[e.Patterned=3]="Patterned",e))(Sr||{}),so=(e=>(e[e.Line=0]="Line",e[e.Arrow=1]="Arrow",e[e.StartBorder=2]="StartBorder",e[e.LineEnding=3]="LineEnding",e))(so||{}),Te=(e=>(e[e.TileCut=0]="TileCut",e[e.Butt=1]="Butt",e[e.Round=2]="Round",e))(Te||{});const pt=Ye(),Ia=Ye(),ns=Ye(),Gi=Ye(),oo=Ye(),ri=Ye(),Mf=Ye(),un=Ye();let is=0,ki=0;function _f(e,t,n,i,r,s,o,a,l,c,f,u){var d,h,g,y;if(!(s<2)){if(Hn(pt,t[0],n[0],t[1],n[1]),is=0,o===Te.Round){const p=c!==void 0?c[0]:0,v=f!==void 0?f[0]:0;Cf(e,t[0],n[0],(d=i==null?void 0:i[0])!=null?d:0,(h=r==null?void 0:r[0])!=null?h:0,-pt[0],-pt[1],p,v,l,u)}for(let p=1;p<s;p++)Qb(e,t,n,i,r,p,s,l,c,f,u);if(a===Te.Round){const p=c!==void 0?c[s-1]:0,v=f!==void 0?f[s-1]:0;Cf(e,t[s-1],n[s-1],(g=i==null?void 0:i[s-1])!=null?g:0,(y=r==null?void 0:r[s-1])!=null?y:0,pt[0],pt[1],p,v,l,u)}}}function Qb(e,t,n,i,r,s,o,a,l,c,f){var g,y,p,v,A,w,S,T,I,C;const u=s===o-1;if(tt(oo,t[s-1],n[s-1]),tt(ri,t[s],n[s]),l!==void 0&&c!==void 0?(tt(ns,l[s-1],c[s-1]),tt(Gi,l[s],c[s])):(tt(ns,0,0),tt(Gi,0,0)),zi(un,pt),u)ki=0;else{tt(Mf,t[s+1],n[s+1]),Hn(Ia,ri[0],ri[1],Mf[0],Mf[1]);const M=Ge(Li(pt,Ia),-1,1);if(M<=0)ki=0,Cf(e,ri[0],ri[1],(g=i==null?void 0:i[s])!=null?g:0,(y=r==null?void 0:r[s])!=null?y:0,pt[0],pt[1],Gi[0],Gi[1],a,f);else{const D=Math.sqrt((1-M)/(1+M)),F=$o(Li(un,Ia));ki=D*F}}qb(e,0,1,3,3,1,2);const d=un[0]*Ke,h=un[1]*Ke;Er(e,oo[0],oo[1],(p=i==null?void 0:i[s-1])!=null?p:0,(v=r==null?void 0:r[s-1])!=null?v:0,(un[0]+pt[0]*is)*Ke,(un[1]+pt[1]*is)*Ke,d,h,ns[0],ns[1],a,f),Er(e,oo[0],oo[1],(A=i==null?void 0:i[s-1])!=null?A:0,(w=r==null?void 0:r[s-1])!=null?w:0,(-un[0]-pt[0]*is)*Ke,(-un[1]-pt[1]*is)*Ke,-d,-h,ns[0],ns[1],a,f),Er(e,ri[0],ri[1],(S=i==null?void 0:i[s])!=null?S:0,(T=r==null?void 0:r[s])!=null?T:0,(-un[0]+pt[0]*ki)*Ke,(-un[1]+pt[1]*ki)*Ke,-d,-h,Gi[0],Gi[1],a,f),Er(e,ri[0],ri[1],(I=i==null?void 0:i[s])!=null?I:0,(C=r==null?void 0:r[s])!=null?C:0,(un[0]-pt[0]*ki)*Ke,(un[1]-pt[1]*ki)*Ke,d,h,Gi[0],Gi[1],a,f),u||(ta(pt,Ia),is=ki)}function Cf(e,t,n,i,r,s,o,a,l,c,f){Kb(e,0,1,2);const u=-s*.01,d=-o*.01;Er(e,t,n,i,r,s+u,o+d,s,o,a,l,c,f),Er(e,t,n,i,r,-o+u,s+d,-o,s,a,l,c,f),Er(e,t,n,i,r,o+u,-s+d,o,-s,a,l,c,f)}function Er(e,t,n,i,r,s,o,a,l,c,f,u,d){const h=e.elements.offset*e.elements.stride,g=h>>1,y=h>>2;if(d){const{x:p,y:v,z:A}=d(t,n);e.views.position[g]=p,e.views.position[g+1]=v,e.views.position[g+2]=A}else e.views.position[g]=W+t,e.views.position[g+1]=W+n;e.views.extender[h]=s*127,e.views.extender[h+1]=o*127,e.views.normal[h]=a*127,e.views.normal[h+1]=l*127,"height"in e.views&&(e.views.height[y]=i),"absZ"in e.views&&(e.views.absZ[y]=r),"shift"in e.views&&(e.views.shift[y]=c,e.views.shift[y+1]=f),"localID"in e.views&&(e.views.localID[y]=u),e.elements.offset++}function qb(e,t,n,i,r,s,o){const a=e.indices.buffer,l=e.indices.offset,c=e.elements.offset;a[l]=c+t,a[l+1]=c+n,a[l+2]=c+i,a[l+3]=c+r,a[l+4]=c+s,a[l+5]=c+o,e.indices.offset=l+6}function Kb(e,t,n,i){const r=e.indices.buffer,s=e.indices.offset,o=e.elements.offset;r[s]=o+t,r[s+1]=o+n,r[s+2]=o+i,e.indices.offset=s+3}function Ff(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ma={exports:{}},ng;function Jb(){if(ng)return Ma.exports;ng=1,Ma.exports=e,Ma.exports.default=e;function e(P,b,E){E=E||2;var x=b&&b.length,L=x?b[0]*E:P.length,O=t(P,0,L,E,!0),R=[];if(!O||O.next===O.prev)return R;var G,Q,X,se,te,U,ne;if(x&&(O=l(P,b,O,E)),P.length>80*E){G=X=P[0],Q=se=P[1];for(var ee=E;ee<L;ee+=E)te=P[ee],U=P[ee+1],te<G&&(G=te),U<Q&&(Q=U),te>X&&(X=te),U>se&&(se=U);ne=Math.max(X-G,se-Q),ne=ne!==0?32767/ne:0}return i(O,R,E,G,Q,ne,0),R}function t(P,b,E,x,L){var O,R;if(L===K(P,b,E,x)>0)for(O=b;O<E;O+=x)R=z(O,P[O],P[O+1],R);else for(O=E-x;O>=b;O-=x)R=z(O,P[O],P[O+1],R);return R&&S(R,R.next)&&(N(R),R=R.next),R}function n(P,b){if(!P)return P;b||(b=P);var E=P,x;do if(x=!1,!E.steiner&&(S(E,E.next)||w(E.prev,E,E.next)===0)){if(N(E),E=b=E.prev,E===E.next)break;x=!0}else E=E.next;while(x||E!==b);return b}function i(P,b,E,x,L,O,R){if(P){!R&&O&&h(P,x,L,O);for(var G=P,Q,X;P.prev!==P.next;){if(Q=P.prev,X=P.next,O?s(P,x,L,O):r(P)){b.push(Q.i/E|0),b.push(P.i/E|0),b.push(X.i/E|0),N(P),P=X.next,G=X.next;continue}if(P=X,P===G){R?R===1?(P=o(n(P),b,E),i(P,b,E,x,L,O,2)):R===2&&a(P,b,E,x,L,O):i(n(P),b,E,x,L,O,1);break}}}}function r(P){var b=P.prev,E=P,x=P.next;if(w(b,E,x)>=0)return!1;for(var L=b.x,O=E.x,R=x.x,G=b.y,Q=E.y,X=x.y,se=L<O?L<R?L:R:O<R?O:R,te=G<Q?G<X?G:X:Q<X?Q:X,U=L>O?L>R?L:R:O>R?O:R,ne=G>Q?G>X?G:X:Q>X?Q:X,ee=x.next;ee!==b;){if(ee.x>=se&&ee.x<=U&&ee.y>=te&&ee.y<=ne&&v(L,G,O,Q,R,X,ee.x,ee.y)&&w(ee.prev,ee,ee.next)>=0)return!1;ee=ee.next}return!0}function s(P,b,E,x){var L=P.prev,O=P,R=P.next;if(w(L,O,R)>=0)return!1;for(var G=L.x,Q=O.x,X=R.x,se=L.y,te=O.y,U=R.y,ne=G<Q?G<X?G:X:Q<X?Q:X,ee=se<te?se<U?se:U:te<U?te:U,ge=G>Q?G>X?G:X:Q>X?Q:X,de=se>te?se>U?se:U:te>U?te:U,he=y(ne,ee,b,E,x),J=y(ge,de,b,E,x),j=P.prevZ,Y=P.nextZ;j&&j.z>=he&&Y&&Y.z<=J;){if(j.x>=ne&&j.x<=ge&&j.y>=ee&&j.y<=de&&j!==L&&j!==R&&v(G,se,Q,te,X,U,j.x,j.y)&&w(j.prev,j,j.next)>=0||(j=j.prevZ,Y.x>=ne&&Y.x<=ge&&Y.y>=ee&&Y.y<=de&&Y!==L&&Y!==R&&v(G,se,Q,te,X,U,Y.x,Y.y)&&w(Y.prev,Y,Y.next)>=0))return!1;Y=Y.nextZ}for(;j&&j.z>=he;){if(j.x>=ne&&j.x<=ge&&j.y>=ee&&j.y<=de&&j!==L&&j!==R&&v(G,se,Q,te,X,U,j.x,j.y)&&w(j.prev,j,j.next)>=0)return!1;j=j.prevZ}for(;Y&&Y.z<=J;){if(Y.x>=ne&&Y.x<=ge&&Y.y>=ee&&Y.y<=de&&Y!==L&&Y!==R&&v(G,se,Q,te,X,U,Y.x,Y.y)&&w(Y.prev,Y,Y.next)>=0)return!1;Y=Y.nextZ}return!0}function o(P,b,E){var x=P;do{var L=x.prev,O=x.next.next;!S(L,O)&&T(L,x,x.next,O)&&B(L,O)&&B(O,L)&&(b.push(L.i/E|0),b.push(x.i/E|0),b.push(O.i/E|0),N(x),N(x.next),x=P=O),x=x.next}while(x!==P);return n(x)}function a(P,b,E,x,L,O){var R=P;do{for(var G=R.next.next;G!==R.prev;){if(R.i!==G.i&&A(R,G)){var Q=F(R,G);R=n(R,R.next),Q=n(Q,Q.next),i(R,b,E,x,L,O,0),i(Q,b,E,x,L,O,0);return}G=G.next}R=R.next}while(R!==P)}function l(P,b,E,x){var L=[],O,R,G,Q,X;for(O=0,R=b.length;O<R;O++)G=b[O]*x,Q=O<R-1?b[O+1]*x:P.length,X=t(P,G,Q,x,!1),X===X.next&&(X.steiner=!0),L.push(p(X));for(L.sort(c),O=0;O<L.length;O++)E=f(L[O],E);return E}function c(P,b){return P.x-b.x}function f(P,b){var E=u(P,b);if(!E)return b;var x=F(E,P);return n(x,x.next),n(E,E.next)}function u(P,b){var E=b,x=P.x,L=P.y,O=-1/0,R;do{if(L<=E.y&&L>=E.next.y&&E.next.y!==E.y){var G=E.x+(L-E.y)*(E.next.x-E.x)/(E.next.y-E.y);if(G<=x&&G>O&&(O=G,R=E.x<E.next.x?E:E.next,G===x))return R}E=E.next}while(E!==b);if(!R)return null;var Q=R,X=R.x,se=R.y,te=1/0,U;E=R;do x>=E.x&&E.x>=X&&x!==E.x&&v(L<se?x:O,L,X,se,L<se?O:x,L,E.x,E.y)&&(U=Math.abs(L-E.y)/(x-E.x),B(E,P)&&(U<te||U===te&&(E.x>R.x||E.x===R.x&&d(R,E)))&&(R=E,te=U)),E=E.next;while(E!==Q);return R}function d(P,b){return w(P.prev,P,b.prev)<0&&w(b.next,P,P.next)<0}function h(P,b,E,x){var L=P;do L.z===0&&(L.z=y(L.x,L.y,b,E,x)),L.prevZ=L.prev,L.nextZ=L.next,L=L.next;while(L!==P);L.prevZ.nextZ=null,L.prevZ=null,g(L)}function g(P){var b,E,x,L,O,R,G,Q,X=1;do{for(E=P,P=null,O=null,R=0;E;){for(R++,x=E,G=0,b=0;b<X&&(G++,x=x.nextZ,!!x);b++);for(Q=X;G>0||Q>0&&x;)G!==0&&(Q===0||!x||E.z<=x.z)?(L=E,E=E.nextZ,G--):(L=x,x=x.nextZ,Q--),O?O.nextZ=L:P=L,L.prevZ=O,O=L;E=x}O.nextZ=null,X*=2}while(R>1);return P}function y(P,b,E,x,L){return P=(P-E)*L|0,b=(b-x)*L|0,P=(P|P<<8)&16711935,P=(P|P<<4)&252645135,P=(P|P<<2)&858993459,P=(P|P<<1)&1431655765,b=(b|b<<8)&16711935,b=(b|b<<4)&252645135,b=(b|b<<2)&858993459,b=(b|b<<1)&1431655765,P|b<<1}function p(P){var b=P,E=P;do(b.x<E.x||b.x===E.x&&b.y<E.y)&&(E=b),b=b.next;while(b!==P);return E}function v(P,b,E,x,L,O,R,G){return(L-R)*(b-G)>=(P-R)*(O-G)&&(P-R)*(x-G)>=(E-R)*(b-G)&&(E-R)*(O-G)>=(L-R)*(x-G)}function A(P,b){return P.next.i!==b.i&&P.prev.i!==b.i&&!M(P,b)&&(B(P,b)&&B(b,P)&&D(P,b)&&(w(P.prev,P,b.prev)||w(P,b.prev,b))||S(P,b)&&w(P.prev,P,P.next)>0&&w(b.prev,b,b.next)>0)}function w(P,b,E){return(b.y-P.y)*(E.x-b.x)-(b.x-P.x)*(E.y-b.y)}function S(P,b){return P.x===b.x&&P.y===b.y}function T(P,b,E,x){var L=C(w(P,b,E)),O=C(w(P,b,x)),R=C(w(E,x,P)),G=C(w(E,x,b));return!!(L!==O&&R!==G||L===0&&I(P,E,b)||O===0&&I(P,x,b)||R===0&&I(E,P,x)||G===0&&I(E,b,x))}function I(P,b,E){return b.x<=Math.max(P.x,E.x)&&b.x>=Math.min(P.x,E.x)&&b.y<=Math.max(P.y,E.y)&&b.y>=Math.min(P.y,E.y)}function C(P){return P>0?1:P<0?-1:0}function M(P,b){var E=P;do{if(E.i!==P.i&&E.next.i!==P.i&&E.i!==b.i&&E.next.i!==b.i&&T(E,E.next,P,b))return!0;E=E.next}while(E!==P);return!1}function B(P,b){return w(P.prev,P,P.next)<0?w(P,b,P.next)>=0&&w(P,P.prev,b)>=0:w(P,b,P.prev)<0||w(P,P.next,b)<0}function D(P,b){var E=P,x=!1,L=(P.x+b.x)/2,O=(P.y+b.y)/2;do E.y>O!=E.next.y>O&&E.next.y!==E.y&&L<(E.next.x-E.x)*(O-E.y)/(E.next.y-E.y)+E.x&&(x=!x),E=E.next;while(E!==P);return x}function F(P,b){var E=new H(P.i,P.x,P.y),x=new H(b.i,b.x,b.y),L=P.next,O=b.prev;return P.next=b,b.prev=P,E.next=L,L.prev=E,x.next=E,E.prev=x,O.next=x,x.prev=O,x}function z(P,b,E,x){var L=new H(P,b,E);return x?(L.next=x.next,L.prev=x,x.next.prev=L,x.next=L):(L.prev=L,L.next=L),L}function N(P){P.next.prev=P.prev,P.prev.next=P.next,P.prevZ&&(P.prevZ.nextZ=P.nextZ),P.nextZ&&(P.nextZ.prevZ=P.prevZ)}function H(P,b,E){this.i=P,this.x=b,this.y=E,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}e.deviation=function(P,b,E,x){var L=b&&b.length,O=L?b[0]*E:P.length,R=Math.abs(K(P,0,O,E));if(L)for(var G=0,Q=b.length;G<Q;G++){var X=b[G]*E,se=G<Q-1?b[G+1]*E:P.length;R-=Math.abs(K(P,X,se,E))}var te=0;for(G=0;G<x.length;G+=3){var U=x[G]*E,ne=x[G+1]*E,ee=x[G+2]*E;te+=Math.abs((P[U]-P[ee])*(P[ne+1]-P[U+1])-(P[U]-P[ne])*(P[ee+1]-P[U+1]))}return R===0&&te===0?0:Math.abs((te-R)/R)};function K(P,b,E,x){for(var L=0,O=b,R=E-x;O<E;O+=x)L+=(P[R]-P[O])*(P[O+1]+P[R+1]),R=O;return L}return e.flatten=function(P){for(var b=P[0][0].length,E={vertices:[],holes:[],dimensions:b},x=0,L=0;L<P.length;L++){for(var O=0;O<P[L].length;O++)for(var R=0;R<b;R++)E.vertices.push(P[L][O][R]);L>0&&(x+=P[L-1].length,E.holes.push(x))}return E},Ma.exports}var $b=Jb();const _a=Ff($b),Lf=$(2,15),rs=-32768,ao=32767;class e2{constructor(t,n){this._vertexBuffer=[],this._vertexDictionary=new Map,this._used=!1,this._granularity=t,this._granularityCellSize=Lf/t,this._canonical=n}subdividePolygonInternal(t,n){if(this._used)throw new Error("Subdivision: multiple use not allowed.");this._used=!0;const{flattened:i,holeIndices:r}=n2(t);this._initializeVertices(i);let s=[];try{const a=_a(i,r),l=this._convertIndices(i,a);s=this._subdivideTrianglesScanline(l)}catch(a){console.error(a)}let o=[];return n&&(o=this._generateOutline(t)),this._ensureNoPoleVertices(),this._handlePoles(s),{verticesFlattened:this._vertexBuffer,indicesTriangles:s,indicesLineList:o}}_getKey(t,n){return t=t+32768,n=n+32768,t<<16|n<<0}_vertexToIndex(t,n){if(t<-32768||n<-32768||t>32767||n>32767)throw new Error("Vertex coordinates are out of signed 16 bit integer range.");const i=Math.round(t)|0,r=Math.round(n)|0,s=this._getKey(i,r);if(this._vertexDictionary.has(s))return this._vertexDictionary.get(s);const o=this._vertexBuffer.length/2;return this._vertexDictionary.set(s,o),this._vertexBuffer.push(i,r),o}_subdivideTrianglesScanline(t){if(this._granularity<2)return i2(this._vertexBuffer,t);const n=[],i=t.length;for(let r=0;r<i;r+=3){const s=[t[r+0],t[r+1],t[r+2]],o=[this._vertexBuffer[t[r+0]*2+0],this._vertexBuffer[t[r+0]*2+1],this._vertexBuffer[t[r+1]*2+0],this._vertexBuffer[t[r+1]*2+1],this._vertexBuffer[t[r+2]*2+0],this._vertexBuffer[t[r+2]*2+1]];let a=1/0,l=1/0,c=-1/0,f=-1/0;for(let y=0;y<3;y++){const p=o[y*2],v=o[y*2+1];a=Math.min(a,p),c=Math.max(c,p),l=Math.min(l,v),f=Math.max(f,v)}if(a===c||l===f)continue;const u=Math.floor(a/this._granularityCellSize),d=Math.ceil(c/this._granularityCellSize),h=Math.floor(l/this._granularityCellSize),g=Math.ceil(f/this._granularityCellSize);if(u===d&&h===g){n.push(...s);continue}for(let y=h;y<g;y++){const p=this._scanlineGenerateVertexRingForCellRow(y,o,s);r2(this._vertexBuffer,p,n)}}return n}_scanlineGenerateVertexRingForCellRow(t,n,i){const r=t*this._granularityCellSize,s=r+this._granularityCellSize,o=[];for(let a=0;a<3;a++){const l=n[a*2],c=n[a*2+1],f=n[(a+1)*2%6],u=n[((a+1)*2+1)%6],d=n[(a+2)*2%6],h=n[((a+2)*2+1)%6],g=f-l,y=u-c,p=g===0,v=y===0,A=(r-c)/y,w=(s-c)/y,S=Math.min(A,w),T=Math.max(A,w);if(!v&&(S>=1||T<=0)||v&&(c<r||c>s)){u>=r&&u<=s&&o.push(i[(a+1)%3]);continue}if(!v&&S>0){const M=l+g*S,B=c+y*S;o.push(this._vertexToIndex(M,B))}const I=l+g*Math.max(S,0),C=l+g*Math.min(T,1);if(p||this._generateIntraEdgeVertices(o,l,c,f,u,I,C),!v&&T<1){const M=l+g*T,B=c+y*T;o.push(this._vertexToIndex(M,B))}(v||u>=r&&u<=s)&&o.push(i[(a+1)%3]),!v&&(u<=r||u>=s)&&this._generateInterEdgeVertices(o,l,c,f,u,d,h,C,r,s)}return o}_generateIntraEdgeVertices(t,n,i,r,s,o,a){const l=r-n,c=s-i,f=c===0,u=f?Math.min(n,r):Math.min(o,a),d=f?Math.max(n,r):Math.max(o,a),h=Math.floor(u/this._granularityCellSize)+1,g=Math.ceil(d/this._granularityCellSize)-1;if(f?n<r:o<a)for(let p=h;p<=g;p++){const v=p*this._granularityCellSize,A=i+c*(v-n)/l;t.push(this._vertexToIndex(v,A))}else for(let p=g;p>=h;p--){const v=p*this._granularityCellSize,A=i+c*(v-n)/l;t.push(this._vertexToIndex(v,A))}}_generateInterEdgeVertices(t,n,i,r,s,o,a,l,c,f){const u=s-i,d=o-r,h=a-s,g=(c-s)/h,y=(f-s)/h,p=Math.min(g,y),v=Math.max(g,y),A=r+d*p;let w=Math.floor(Math.min(A,l)/this._granularityCellSize)+1,S=Math.ceil(Math.max(A,l)/this._granularityCellSize)-1,T=l<A;const I=h===0;if(I&&(a===c||a===f))return;if(I||p>=1||v<=0){const M=n-o,B=i-a,D=(c-a)/B,F=(f-a)/B,z=Math.min(D,F),N=o+M*z;w=Math.floor(Math.min(N,l)/this._granularityCellSize)+1,S=Math.ceil(Math.max(N,l)/this._granularityCellSize)-1,T=l<N}const C=u>0?f:c;if(T)for(let M=w;M<=S;M++){const B=M*this._granularityCellSize;t.push(this._vertexToIndex(B,C))}else for(let M=S;M>=w;M--){const B=M*this._granularityCellSize;t.push(this._vertexToIndex(B,C))}}_generateOutline(t){const n=[];for(const i of t){const r=Bf(i,this._granularity,!0),s=this._pointArrayToIndices(r),o=[];for(let a=1;a<s.length;a++)o.push(s[a-1]),o.push(s[a]);n.push(o)}return n}_handlePoles(t){let n=!1,i=!1;this._canonical&&(this._canonical.y===0&&(n=!0),this._canonical.y===(1<<this._canonical.z)-1&&(i=!0)),(n||i)&&this._fillPoles(t,n,i)}_ensureNoPoleVertices(){const t=this._vertexBuffer;for(let n=0;n<t.length;n+=2){const i=t[n+1];i===rs&&(t[n+1]=rs+1),i===ao&&(t[n+1]=ao-1)}}_generatePoleQuad(t,n,i,r,s,o){r>s!=(o===rs)?(t.push(n),t.push(this._vertexToIndex(r,o)),t.push(i),t.push(i),t.push(this._vertexToIndex(r,o)),t.push(this._vertexToIndex(s,o))):(t.push(i),t.push(this._vertexToIndex(r,o)),t.push(n),t.push(this._vertexToIndex(s,o)),t.push(this._vertexToIndex(r,o)),t.push(i))}_fillPoles(t,n,i){const r=this._vertexBuffer,s=0,o=Lf,a=t.length;for(let l=2;l<a;l+=3){const c=t[l-2],f=t[l-1],u=t[l],d=r[c*2],h=r[c*2+1],g=r[f*2],y=r[f*2+1],p=r[u*2],v=r[u*2+1];n&&(h===s&&y===s&&this._generatePoleQuad(t,c,f,d,g,rs),y===s&&v===s&&this._generatePoleQuad(t,f,u,g,p,rs),v===s&&h===s&&this._generatePoleQuad(t,u,c,p,d,rs)),i&&(h===o&&y===o&&this._generatePoleQuad(t,c,f,d,g,ao),y===o&&v===o&&this._generatePoleQuad(t,f,u,g,p,ao),v===o&&h===o&&this._generatePoleQuad(t,u,c,p,d,ao))}}_initializeVertices(t){for(let n=0;n<t.length;n+=2)this._vertexToIndex(t[n],t[n+1])}_convertIndices(t,n){const i=[];for(let r=0;r<n.length;r++){const s=t[n[r]*2],o=t[n[r]*2+1];i.push(this._vertexToIndex(s,o))}return i}_pointArrayToIndices(t){const n=[];for(let i=0;i<t.length;i++){const r=t[i];n.push(this._vertexToIndex(r[0],r[1]))}return n}}function t2(e,t,n,i=!0){return new e2(n,t).subdividePolygonInternal(e,i)}function Bf(e,t,n=!1){if(!e||e.length<1)return[];if(e.length<2)return[];const i=e[0],r=e[e.length-1],s=n&&(i[0]!==r[0]||i[1]!==r[1]);if(t<2)return s?[...e,e[0]]:[...e];const o=Math.floor(Lf/t),a=[];a.push([e[0][0],e[0][1]]);const l=e.length,c=s?l:l-1;for(let f=0;f<c;f++){const u=e[f],d=f<l-1?e[f+1]:e[0],h=u[0],g=u[1],y=d[0],p=d[1],v=h!==y,A=g!==p;if(!v&&!A)continue;const w=y-h,S=p-g,T=Math.abs(w),I=Math.abs(S);let C=h,M=g;for(;;){const D=w>0?(Math.floor(C/o)+1)*o:(Math.ceil(C/o)-1)*o,F=S>0?(Math.floor(M/o)+1)*o:(Math.ceil(M/o)-1)*o,z=Math.abs(C-D),N=Math.abs(M-F),H=Math.abs(C-y),K=Math.abs(M-p),P=v?z/T:Number.POSITIVE_INFINITY,b=A?N/I:Number.POSITIVE_INFINITY;if((H<=z||!v)&&(K<=N||!A))break;if(P<b&&v||!A){C=D,M=M+S*P;const E=[C,Math.round(M)];(a[a.length-1][0]!==E[0]||a[a.length-1][1]!==E[1])&&a.push(E)}else{C=C+w*b,M=F;const E=[Math.round(C),M];(a[a.length-1][0]!==E[0]||a[a.length-1][1]!==E[1])&&a.push(E)}}const B=[y,p];(a[a.length-1][0]!==B[0]||a[a.length-1][1]!==B[1])&&a.push(B)}return a}function n2(e){const t=[],n=[];for(const i of e)if(i.length!==0){i!==e[0]&&t.push(n.length/2);for(let r=0;r<i.length;r++)n.push(i[r][0]),n.push(i[r][1])}return{flattened:n,holeIndices:t}}function i2(e,t){const n=[];for(let i=0;i<t.length;i+=3){const r=t[i],s=t[i+1],o=t[i+2],a=e[r*2],l=e[r*2+1],c=e[s*2],f=e[s*2+1],u=e[o*2],d=e[o*2+1],h=c-a,g=f-l,y=u-a,p=d-l;h*p-g*y>0?(n.push(r),n.push(s),n.push(o)):(n.push(r),n.push(o),n.push(s))}return n}function r2(e,t,n){if(t.length===0)throw new Error("Subdivision vertex ring is empty.");let i=0,r=e[t[0]*2];for(let l=1;l<t.length;l++){const c=e[t[l]*2];c<r&&(r=c,i=l)}const s=t.length;let o=i,a=(o+1)%s;for(;;){const l=o-1>=0?o-1:s-1,c=(a+1)%s,f=e[t[l]*2],u=e[t[l]*2+1],d=e[t[c]*2],h=e[t[c]*2+1],g=e[t[o]*2],y=e[t[o]*2+1],p=e[t[a]*2],v=e[t[a]*2+1];let A=!1;if(f<d)A=!0;else if(f>d)A=!1;else{const w=p-g,T=v-y,I=-w,C=y<v?1:-1,M=((f-g)*T+(u-y)*I)*C,B=((d-g)*T+(h-y)*I)*C;M>B&&(A=!0)}if(A){const w=t[l],S=t[o],T=t[a];w!==S&&w!==T&&S!==T&&n.push(T,w,S),o--,o<0&&(o=s-1)}else{const w=t[c],S=t[o],T=t[a];w!==S&&w!==T&&S!==T&&n.push(T,w,S),a++,a>=s&&(a=0)}if(l===c)break}}function Ze(e,t,n){return t.precomputes.forEach((i,r)=>{e.push(n.tileData[r])}),e}function Tr(e,t){for(let n=0,i=t.length;n<i;n++)e.push(t[n]);return e}const s2={x:0,y:1};function o2(e){const t={};for(const n in e)e[n]&&(t[n]=Array.from(e[n]));return t}function lo(e,t){for(const n in e){const i=s2[n];i!==void 0?e[n].push(t[i]):e[n].push(NaN)}}const a2=new Set(["bottomCenter","bottomRight","bottomLeft","topCenter","topRight","topLeft","rightBottom","rightCenter","rightTop","leftBottom","leftCenter","leftTop","centerCenter"]);function l2(e){return a2.has(e)}function c2(e){return typeof e=="number"||typeof e=="boolean"||typeof e=="string"||e===null}function Pr(e){if(Array.isArray(e)){const t=e;if(!t.length)return!1;if({zoom:!0,height:!0,coalesce:!0,"heatmap-density":!0,"shading-intensity":!0,"object-attr":!0,step:!0,interpolate:!0,all:!0,get:!0,"source-attr":!0,"feature-state":!0,global:!0,match:!0,in:!0,any:!0,when:!0,"!":!0,"==":!0,"!=":!0,">=":!0,">":!0,"<=":!0,"<":!0,"to-boolean":!0,"to-color":!0,"+":!0,"*":!0,"^":!0,"%":!0,log10:!0,random:!0,clamp:!0,literal:!0,"is-behind-objects":!0,"mappoints-to-meters":!0,"meters-to-pixels":!0,uint64:!0,"geometry-modifier":!0,pattern:!0,precompute:!0,"gltf-animation":!0,distance:!0,time:!0,"local-time":!0,"utc-time":!0,"texture-animation":!0,easing:!0,schedule:!0,mix:!0,"read-from-target":!0,"vertex-attribute":!0,has:!0,"vertex-color":!0,"color-desaturate":!0,"color-grayscale":!0,"color-lighten":!0,"color-lightness":!0,"color-darken":!0,"color-whiten":!0,"color-blacken":!0,"color-saturate":!0,"color-opacity":!0,concat:!0,format:!0,"color-effect":!0,pitch:!0}[t[0]])return!0}return!1}function ig(e){return Pr(e)&&e[0]==="literal"}function Qt(e){return!Array.isArray(e)&&typeof e=="object"&&e!==null&&e.type!==void 0&&e.type!=="color"}function f2(e){return!Array.isArray(e)&&typeof e=="object"&&e!==null&&e.type==="color"}function rg(e,t){return Array.isArray(e)?e.length>0&&e.every(n=>typeof n===t):!1}function u2(e){return rg(e,"string")}function Yn(e){return rg(e,"number")}function sg(e){return!Array.isArray(e)&&typeof e=="object"&&e!==null&&e.type==="object"}function d2(e){const t=typeof e;return e===null||t==="string"||t==="number"||t==="boolean"||u2(e)||Yn(e)}function og(e){return d2(e)||f2(e)||sg(e)}function h2(e){return Qt(e)&&e.type==="get"}function ag(e){return Qt(e)&&e.type==="interpolate"}function Ot(e,t){return t!==void 0?{type:"color",value:e,mixFactor:t}:{type:"color",value:e}}function p2(e){return{type:"mix-color",color1:e.value1,color2:e.value2,factor:e.factor,factorInterpolate:e.factorInterpolate}}function ss(e,t,n){return`${e}_${t}_${n}`}function Ca(e){return`texture-${e}`}function Df(e,t){return e+"-"+t}function It(e){return ig(e)&&Array.isArray(e[1])?e[1][0]:Array.isArray(e)?Pr(e)?e:e[0]:e}function Ui(e){if(ig(e)&&Array.isArray(e[1]))return e[1][1];if(Array.isArray(e)&&!Pr(e)&&e[1]!==void 0)return e[1]}function si(e){if(typeof e=="number"||Yn(e))return e;if(e.type==="literal-array"&&Yn(e.array))return e.array;throw new Error("Unsupported simple literal expression. Can't resolve.")}function Vi(e){return Yn(e)?[e]:e&&typeof e=="object"&&!Array.isArray(e)&&e.type==="literal-array"?Vi(e.array):Array.isArray(e)?e.map(t=>Vi(t)[0]):[[.5,.5]]}function co(e){return Vi(e)[0]}function fo(e,t=0){const n=Number(e);return isNaN(n)?t:n}function lg(e){return!!e&&typeof e=="object"&&e.type==="mix-options"}var Ir=(e=>(e[e.Static=0]="Static",e[e.Unique=1]="Unique",e[e.Loaded=2]="Loaded",e))(Ir||{});let cg=1e4+1;const g2={w:0,h:0,x:0,y:0,atlasIndex:0,isPacked:!1},Of={};function m2(e,t,n,i,r,s){const o=Df(e,r);if(!Of[o]){const a=cg++;Of[o]={type:Ir.Unique,isSvg:!1,index:a,key:o,name:"",fileName:"",id:e,regionId:n,url:s,rasters:t.map((l,c)=>ie(V({},g2),{rasterSetIndex:a,rasterIndex:c,w:l,h:l,anchorX:i[0],anchorY:i[1]}))}}return Of[o]}function v2(e){const t=cg++;return{type:Ir.Loaded,isSvg:!1,index:t,key:`loaded-${t}`,name:"",fileName:"",rasters:e.map((n,i)=>ie(V({},n),{rasterIndex:i,rasterSetIndex:t}))}}function os(e,t,n){let i,r=1/0;for(let s=0;s<e.length;s++){const o=e[s];if(!o||n&&!o.isPacked)continue;const a=Math.abs(o.w-t);a<r&&(i=s,r=a)}return i}const fg=32,ug=512;function y2(e,t,n,i,r){const s=[e[0][0],e[1][0]],o=Le(90+i),a=[];St(a,s,r);const l=me.toGeo(a),c=ca(l,t),f=ca(l,n),u=Math.sqrt($(c,2)+$(f,2))/2,d=Math.atan(c/-f)+Math.PI+o,h=u*Math.cos(d),g=u*Math.sin(d),y=Math.atan(-c/-f)+Math.PI+o,p=u*Math.cos(y),v=u*Math.sin(y),A=Math.atan(-c/f)+2*Math.PI+o,w=u*Math.cos(A),S=u*Math.sin(A),T=Math.atan(c/f)+o,I=u*Math.cos(T),C=u*Math.sin(T),M=[],B=[],D=[],F=[];return Dt(M,[a[0]+h,a[1]+g],r),Dt(B,[a[0]+p,a[1]+v],r),Dt(D,[a[0]+w,a[1]+S],r),Dt(F,[a[0]+I,a[1]+C],r),[[M[0],B[0],D[0],F[0]],[M[1],B[1],D[1],F[1]]]}function uo(e,t){const n=Math.max(e,t);return n*fg>ug?ug/n:fg}function x2(e,t,n,i){const r=uo(t,n),s=t*r,o=n*r;if(s<=0||o<=0)return;const a=os(e,s*i,!0);if(a===void 0)return;const l=e[a];return{raster:l,spriteCoords:[(l.x+.5)/Yt[0],(l.y+l.h-1)/Yt[1],(l.x+l.w-1)/Yt[0],(l.y+.5)/Yt[1]]}}function dg(e){const t=fn(e,[0,0]);return ae/Mn(e.coords[2])*Ee*t}function w2(e,t,n,i){if(isNaN(e.step)||isNaN(e.width))return n;const{tileProps:r,tileAttrs:s}=i,o=dg(t);let a=e.step*o;if(isNaN(a)&&(a=0),a===0)return n;const l=e.width*o,c={},f=n.x,u=n.y,d=f.length;for(const C in n)c[C]=[];let h=0;const g=[h];for(let C=1;C<d;C++)h+=Bi([f[C-1],u[C-1]],[f[C],u[C]]),g.push(h);const y=Ye(),p=Ye(),v=[0,0],A=Math.abs(h/Math.trunc(h/a)),w=[f[0],u[0]];let S=(e.stopLines?1:-1)*Math.sign(e.width),T=0,I=0;for(lo(c,w),e.stopLines&&!s[r.beginningIsCut]&&(Hn(y,f[I],u[I],f[I+1],u[I+1]),zi(p,y),an(v,p,S*l),Tn(w,w,v),lo(c,w),T+=A/2,S=-S);T<=h;){for(;T>g[I+1];)I++;if(Hn(y,f[I],u[I],f[I+1],u[I+1]),zi(p,y),S>0)an(v,p,S*l),Tn(w,w,v),an(v,y,A/2),Tn(w,w,v),lo(c,w);else{const C=Math.min(1,(T-g[I])/(g[I+1]-g[I]));Kc(w,[f[I],u[I]],[f[I+1],u[I+1]],C),lo(c,w)}S=-S,T+=A/2}return e.stopLines&&!s[r.endingIsCut]&&(an(v,p,S*l),Tn(w,w,v),lo(c,w)),c}function A2(e,t,n,i){const r=dg(t),s=fn(t,[0,0]),{tileProps:o,tileAttrs:a}=i,l=n.x.length,c=r*e.modelLength,f=r*(e.edgeMarging||0),u={x:[],y:[],xScaleDirection:[],yScaleDirection:[],scaleCorrection:[]};for(let d=1;d<l;d++){const h=[n.x[d],n.y[d]],g=[n.x[d-1],n.y[d-1]];d===1&&f>0&&!a[o.beginningIsCut]&&hg(g,h,f),d===l-1&&f>0&&!a[o.endingIsCut]&&hg(h,g,f),b2(u,g,h,c,s)}return u}function hg(e,t,n){const i=Bi(t,e),r=t[0]-e[0],s=t[1]-e[1],o=r/i,a=s/i;e[0]=e[0]+o*n,e[1]=e[1]+a*n}function b2(e,t,n,i,r){const[s,o]=t,[a,l]=n,c=Bi(t,n),f=Math.max(Math.round(c/i),1),u=c/(f*i),d=a-s,h=l-o,g=d/c,y=h/c,p=c/f/2;for(let v=1;v<=f;v++){const A=v*(c/f),w=s+g*(A-p),S=o+y*(A-p),T=s+g*A,I=o+y*A;e.x.push(w),e.y.push(S),e.xScaleDirection.push(T),e.yScaleDirection.push(I),e.scaleCorrection.push(u*r)}return e}function Fa(e,t,n,i){if(!S2(e)||e.length===0)return n;let r=o2(n);for(const s of e){if(typeof s!="object"||!s)return console.warn(`Wrong value ${s} in modifiers list.`),null;if(!("type"in s))return console.warn(`Wrong value ${s} in modifiers list.`),null;switch(s.type){case"zigzag-modifier":r=w2(s,t,r,i);break;case"to-points-modifier":r=A2(s,t,r,i);break;default:return console.warn(`Expression with type ${s.type} cannot be used as geometry modifier.`),null}if(r===null)return null}return r}function S2(e){return!!e&&Array.isArray(e)}function E2(){return{zoomMin:-1/0,zoomMax:1/0,pitch:!1,time:!1,stateKeys:[],resources:[]}}let je;function T2(e){const t=je;return je=e,t}function pg(){return je!==void 0}function La(e,t){je&&je.zoomMin!==je.zoomMax&&(je.zoomMin=Math.max(je.zoomMin,e),je.zoomMax=Math.min(je.zoomMax,t))}function Ba(e){je&&(je.zoomMin=e,je.zoomMax=e)}function P2(){je&&(je.pitch=!0)}function ho(){je&&(je.time=!0)}function Da(e){je&&!je.stateKeys.includes(e)&&je.stateKeys.push(e)}function gg(e){je&&!je.resources.includes(e)&&je.resources.push(e)}function I2(e,t){return e.zoomMin===e.zoomMax?t===e.zoomMin:t>=e.zoomMin&&t<e.zoomMax}const mg=Ot([0,0,0,0]);function vg(e){return typeof e!="string"?!1:/(#(?:[0-9a-f]{2}){2,4}|#[0-9a-f]{3}|(?:rgba?|hsla?)\((?:\d+%?(?:,|\s)+){2,3}[\s\/]*[\d\.]+%?\))/i.test(e)}function _n(e){return!!e&&typeof e=="object"&&e.type==="color"}function M2(e){return!!e&&typeof e=="object"&&e.type==="mix-color"}function Oa(e){return!!e&&typeof e=="object"&&e.type==="gradient-color"}function Mr(e){const t=e.toLowerCase();let n=mg;switch(t[0]){case"#":n=C2(t);break;case"h":n=as(t);break;case"r":n=F2(t);break}return n}function _2(e){return e.length<7?e[0]+e[1]+e[1]+e[2]+e[2]+e[3]+e[3]+(e.length===5?e[4]+e[4]:"ff"):e.length===7?e+"ff":e}function C2(e){if(!new RegExp(`^#[a-f0-9]{${e.length-1}}$`).test(e)||![4,5,7,9].includes(e.length))return mg;const n=_2(e),i=parseInt(n[1]+n[2],16),r=parseInt(n[3]+n[4],16),s=parseInt(n[5]+n[6],16),o=parseInt(n[7]+n[8],16);return Ot([i,r,s,o])}function as(e,t){const n=yg(e);n[0]/=360,n[1]/=100,n[2]/=100;const[i,r,s]=L2(n[0],n[1],n[2]),o=t!==void 0?t:n[3]!==void 0?n[3]*255:255;return Ot([Math.round(i),Math.round(r),Math.round(s),Math.round(o)])}function F2(e){const[t,n,i,r]=yg(e),s=r!==void 0?r*255:255;return Ot([Math.round(t),Math.round(n),Math.round(i),Math.round(s)])}function yg(e){return e.split("(")[1].split(")")[0].split(",").map(n=>parseFloat(n))}function Rf(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e}function L2(e,t,n){if(t===0)return[n*255,n*255,n*255];const i=n<.5?n*(1+t):n+t-n*t,r=2*n-i;return[Rf(r,i,e+1/3)*255,Rf(r,i,e)*255,Rf(r,i,e-1/3)*255]}function xg(e){const t=e[0],n=e[1];let i=e[2];const r=ls(e)[0],s=1/255*Math.min(t,Math.min(n,i));return i=1-1/255*Math.max(t,Math.max(n,i)),[r,s*100,i*100]}function ls(e){const t=e[0]/255,n=e[1]/255,i=e[2]/255,r=Math.min(t,n,i),s=Math.max(t,n,i),o=s-r;let a,l;s===r?a=0:t===s?a=(n-i)/o:n===s?a=2+(i-t)/o:i===s&&(a=4+(t-n)/o),a=Math.min((a||0)*60,360),a<0&&(a+=360);const c=(r+s)/2;return s===r?l=0:c<=.5?l=o/(s+r):l=o/(2-s-r),[a,l*100,c*100]}function wg(e){const t=e[1]/100,i=1-e[2]/100,r=i-t;let s=0;return r<1&&(s=(i-r)/(1-r)),[e[0],r*100,s*100]}function Ag(e){const t=e[0]/360,n=e[1]/100,i=e[2]/100;if(n===0)return[i*255,i*255,i*255];const r=[0,0,0],s=t%1*6,o=s%1,a=1-o;let l=0;switch(Math.floor(s)){case 0:r[0]=1,r[1]=o,r[2]=0;break;case 1:r[0]=a,r[1]=1,r[2]=0;break;case 2:r[0]=0,r[1]=1,r[2]=o;break;case 3:r[0]=0,r[1]=a,r[2]=1;break;case 4:r[0]=o,r[1]=0,r[2]=1;break;default:r[0]=1,r[1]=0,r[2]=a}return l=(1-n)*i,[(n*r[0]+l)*255,(n*r[1]+l)*255,(n*r[2]+l)*255]}function B2(e,t){const n=ls(e.value);return n[2]+=n[2]*t,as(`hsl(${n[0]}, ${n[1]}%, ${n[2]}%)`,e.value[3])}function D2(e,t){const n=ls(e.value);return n[2]-=n[2]*t,as(`hsl(${n[0]}, ${n[1]}%, ${n[2]}%)`,e.value[3])}function O2(e,t){const n=ls(e.value);return n[1]+=n[1]*t,as(`hsl(${n[0]}, ${n[1]}%, ${n[2]}%)`,e.value[3])}function R2(e,t){const n=ls(e.value);return n[1]-=n[1]*t,as(`hsl(${n[0]}, ${n[1]}%, ${n[2]}%)`,e.value[3])}function z2(e,t){const n=ls(e.value);return n[2]=Math.min(100,Math.max(0,100*t)),as(`hsl(${n[0]}, ${n[1]}%, ${n[2]}%)`,e.value[3])}function N2(e,t){const n=xg(e.value);n[1]+=n[1]*t;const i=Ag(wg(n));return{type:"color",value:[i[0],i[1],i[2],e.value[3]||255]}}function G2(e,t){const n=xg(e.value);n[2]+=n[2]*t;const i=Ag(wg(n));return{type:"color",value:[i[0],i[1],i[2],e.value[3]||255]}}function k2(e){const t=e.value,n=t[0]*.3+t[1]*.59+t[2]*.11;return{type:"color",value:[n,n,n,e.value[3]||255]}}function Ra(e){let t="",n=0;for(;n<e.length;){let i=e[n++];if(i>127){if(i>191&&i<224){if(n>=e.length)return console.error("Incomplete 2-byte sequence"),t;i=(i&31)<<6|e[n]&63}else if(i>223&&i<240){if(n+1>=e.length)return console.error("Incomplete 3-byte sequence"),t;i=(i&15)<<12|(e[n]&63)<<6|e[++n]&63}else if(i>239&&i<248){if(n+2>=e.length)return console.error("Incomplete 4-byte sequence"),t;i=(i&7)<<18|(e[n]&63)<<12|(e[++n]&63)<<6|e[++n]&63}else return console.error(`Unknown multibyte start 0x${i.toString(16)} at index ${n-1}`),t;++n}if(i<=65535)t+=String.fromCharCode(i);else if(i<=1114111)i-=65536,t+=String.fromCharCode(i>>10|55296),t+=String.fromCharCode(i&1023|56320);else return console.error(`Code point 0x${i.toString(16)} exceeds UTF-16 reach`),t}return t}function zf(e,t){if(e.length<=t||e.indexOf(`
`)!==-1)return e;const n=[];return e.split(" ").forEach(i=>{const r=n.length-1;n.length===0||n[r].length+i.length>=t?n.push(i):n[r]+=" "+i}),n.join(`
`)}function Nf(e){return Math.floor(e/256)}function U2(e){const t=new Set;return e.forEach(n=>{if(n!==void 0)for(let i=0;i<n.length;i++){const r=n.charCodeAt(i);r!==on.bomCharCode&&t.add(Nf(r))}}),Array.from(t)}function V2(e,t,n=1,i="…"){if(e.length<=t)return e;const r=t-i.length;switch(n){case 2:return e.substring(0,r)+i;case 1:{const s=Math.ceil(r/2);return e.substring(0,s)+i+e.substring(e.length-(r-s),e.length)}}}function W2(e){return typeof e!="string"?e:e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function H2(e,t){ke(`No glyph for character ${e} (code = ${t}, range = ${Nf(t)})`)}const bg=new Set;function Y2(e){console.group("Gltf model error"),console.warn("Stage:",e.layer),e.message&&console.warn("Message:",e.message),e.originalError&&(console.groupCollapsed("Original error"),console.warn(e.originalError),console.groupEnd()),console.groupEnd()}function Sg(e){ke(`Got an empty response from the "${e}" tile generation.`)}function ke(e){bg.has(e)||(console.log(e),bg.add(e))}const X2=2166136261,Z2=16777619;function Eg(e,t){let n=X2;for(const i of t)n=n^i,n=n*Z2;e.randomSeed=Math.abs(n)}function cs(e,t,n){let i=.5;return e.randomSeed?(e.randomSeed=e.randomSeed*16807%2147483647,i=(e.randomSeed-1)/2147483646):ke("Resolve 'random': random seed is absent, the mean value between start and end will be used."),i*(n-t)+t}function j2(e=128){const t=[],n=[];for(let i=0;i<e;i++)t.push(Tg(i,2)),n.push(Tg(i,3));return{base2:t,base3:n}}function Tg(e,t){let n=0,i=1/t;for(;e>0;)n=n+i*(e%t),e=Math.floor(e/t),i=i/t;return n}function Pg(e,t){const n=[];for(let i=0;i<t;i++){const r=cs(e,0,2*Math.PI),s=Math.acos(cs(e,0,2)-1),o=Math.sin(s)*Math.cos(r),a=Math.sin(s)*Math.sin(r),l=Math.cos(s);n.push(bt(o,a,l))}return n}var Qe=(e=>(e[e.Uniform=1]="Uniform",e[e.Labeling=2]="Labeling",e[e.Generator=3]="Generator",e))(Qe||{});const za=-1;var po=(e=>(e.global="global",e.none="none",e))(po||{}),Wi=(e=>(e[e.Pixels=0]="Pixels",e[e.Meters=1]="Meters",e))(Wi||{});const Ig="bottomCenter";function lt(e,t){for(const n in t)t[n]!==void 0&&(e[n]=t[n])}function Q2(e){const n={color:"#000000",textureImage:"",textureSize:16,textureOpacity:1,strokeColor:"#00000000",strokeWidth:1,visibility:"visible",metallic:1,roughness:0,normalMapTextureImage:"",normalMapTextureSize:16,normalMapTextureAnimation:null,colorEffect:null,floorCulling:"all-floors"};if(lt(n,e),e.strokeColor===void 0&&!n.textureImage&&(n.strokeColor=n.color),!Array.isArray(n.textureSize)||n.textureSize[0]==="step"||n.textureSize[0]==="literal")return n;if(!n.textureSize.length)n.textureSize=16;else if(Yn(n.textureSize))n.textureSize.length===1&&(n.textureSize=n.textureSize[0]);else return n;return n}function q2(e){const n={color:"#000000",textureImage:"",textureSize:16,textureOpacity:1,strokeColor:"#00000000",strokeWidth:1,nearCameraFade:2500,visibility:"visible",elevation:0};if(lt(n,e),e.strokeColor===void 0&&!n.textureImage&&(n.strokeColor=n.color),!Array.isArray(n.textureSize)||n.textureSize[0]==="step"||n.textureSize[0]==="literal")return n;if(!n.textureSize.length)n.textureSize=16;else if(Yn(n.textureSize))n.textureSize.length===1&&(n.textureSize=n.textureSize[0]);else return n;return n}function K2(e){const t={iconImage:"",color:"#FFFFFF",rotation:0,width:1,visibility:"visible"};return lt(t,e),e.height===void 0&&(t.height=t.width),t}function J2(e){const t={topColor:"#000000",strokeColor:"#000000",strokeWidth:1,sideColor:"#000000",sideStrokeColor:"#000000",height:["mappoints-to-meters",["get","db_height"]],nearCameraFade:2500,visibility:"visible",sideTextures:[],colorEffect:null,floorCulling:"all-floors"};return lt(t,e),e.strokeColor===void 0&&(t.strokeColor=t.topColor),e.sideColor===void 0&&(t.sideColor=t.topColor),e.sideStrokeColor===void 0&&(t.sideStrokeColor=t.sideColor),t}function $2(e){const t={color:"#000000",width:1,shift:0,geometryModifier:["geometry-modifier"],pattern:["pattern","none"],startCap:"round",endCap:"round",mode:"2d",visibility:"visible",floorCulling:"all-floors"};return lt(t,e),t}function eS(e){const t={color:"#000000",strokeColor:"#000000",strokeWidth:1,nearCameraFade:2500,visibility:"visible"};return lt(t,e),e.strokeColor===void 0&&(t.strokeColor=t.color),t}function tS(e){const t={sideColor:"#000000",strokeColor:"#000000",strokeWidth:1,sideStrokeColor:"#000000",height:0,visibility:"visible",nearCameraFade:2500};return lt(t,e),e.strokeColor===void 0&&(t.strokeColor=t.sideColor),e.sideStrokeColor===void 0&&(t.sideStrokeColor=t.sideColor),t}function nS(e){const t={textField:["get","db_label"],textFont:"Noto_Sans",textColor:"#000000",textFontSize:16,textLetterSpacing:0,textHaloColor:"rgba(0, 0, 0, 0)",textHaloWidth:0,textPriority:0,textLabelingSideMargin:0,textDuplicationSpacing:0,lineEndingOffsets:0,visibility:"visible",labelingGroup:Yi,colorEffect:null,floorCulling:"all-floors",mode:"map"};return lt(t,e),t}function iS(e){const t={color:"#000000",lineWidth:2,lineLength:10,tipWidth:1.5,tipHeight:2,roundingRadius:0,priority:0,duplicationSpacing:0,endingOffsets:0,visibility:"visible",labelingGroup:Yi,colorEffect:null,floorCulling:"all-floors",mode:"map"};return lt(t,e),t}function rS(e){const t={color:"#000000",gapColor:"#00000000",width:1,shift:0,gapLength:1,dashLength:1,gapTurnsOnly:!1,geometryModifier:["geometry-modifier"],mode:"2d",visibility:"visible",floorCulling:"all-floors"};return lt(t,e),t}function sS(e){const t={color:"#000000",width:1,shift:0,visibility:"visible"};return lt(t,e),t}function oS(e){const t={color:"#ffffff",strokeColor:"#3388ff",strokeColor2:"#00000000",width:20,strokeWidth:3,strokeWidth2:0,visibility:"visible"};return lt(t,e),t}function aS(e){const t={allowOverlap:!1,allowElevation:!1,elevation:NaN,iconOpacity:1,iconImage:"",iconAnchor:[.5,.5],iconOffset:[0,0],iconWidth:16,iconTextField:["get","db_label2"],iconTextFont:"",iconTextAnchor:[.5,.5],iconTextOffset:[0,0],iconTextColor:"#000000",iconTextFontSize:16,iconTextLineHeight:1.2,iconTextLetterSpacing:0,iconTextPadding:[0,0,0,0],iconTextHaloWidth:0,iconTextHaloColor:"rgba(0, 0, 0, 0)",iconPriority:0,iconRotation:0,iconLabelingGroup:Yi,iconLabelingMargin:{topBottom:0,leftRight:0},textField:[["get","db_label"],["get","db_label2"]],textFont:"",textColor:"#000000",textFontSize:16,textLineHeight:1.2,textLetterSpacing:0,textPlacement:Ig,textOffset:0,textHaloColor:"rgba(0, 0, 0, 0)",textHaloWidth:0,textLabelingMargin:{topBottom:0,leftRight:0},textPriority:0,textMaxLengthPerLine:30,visibility:"visible",textLabelingGroup:Yi,duplicationSpacing:100,endingOffsets:0,floorCulling:"active-floor"};return lt(t,e),t}function lS(e){const t={color:"#000000",strokeColor:"#000000",lineWidth:1,strokeWidth:0,tipWidth:1,tipHeight:1,roundingRadius:3,animation:{type:"appearance",tipMovementAmplitude:0},visibility:"visible"};return e.strokeColor===void 0&&(t.strokeColor=t.color),lt(t,e),t}function cS(e){const t={opacity:1,visibility:"visible"};return lt(t,e),t}function fS(e){return Ci(e,{color:["interpolate",["linear"],["heatmap-density"],0,"rgba(53, 136, 253, 0)",.2,"rgba(53, 136, 253, 0.2)",.4,"rgb(255, 201, 77)",.6,"rgb(255, 202, 20)",.75,"rgb(245, 0, 7)",1,"rgb(255, 0, 0)"],radius:30,opacity:1,intensity:1,weight:1,downscale:1,visibility:"visible"})}const Mg={minorColor:"#996633cc",majorColor:"#804d1aff",indexColor:"#66400dff",minorWidth:1,majorWidth:2,indexWidth:2.6,interval:0,minorLabelFontSize:10,minorLabelFont:"Noto_Sans",minorLabelColor:"#7a5a3a",minorLabelHaloRadius:1,minorLabelHaloColor:"#ffffffaa",majorLabelFontSize:11,majorLabelFont:"Noto_Sans",majorLabelColor:"#5a3a1a",majorLabelHaloRadius:1.5,majorLabelHaloColor:"#ffffffcc",indexLabelFontSize:13,indexLabelFont:"Noto_Sans",indexLabelColor:"#3a2010",indexLabelHaloRadius:2,indexLabelHaloColor:"#ffffffdd"};function uS(e){return Ci(e,Mg)}function dS(e){return Ci(e,{shadingIntensity:["interpolate",["linear"],["zoom"],12,0,14.5,.7],verticalScale:1,shadingPalette:["interpolate",["linear"],["shading-intensity"],0,0,1,1],lightingDirection:322})}function hS(e){return Ci(e,{modelSrc:"",offset:0,scale:1,rotation:0,color:"#fff",linkedIds:"",visibility:"visible",colorTextureUvIndex:0,nearCameraFade:2500,ignoreGlobalLighting:!1,showRatio:1,metallic:NaN,roughness:NaN,preventObjectsHiding:!1,lightingModel:"phong",playAnimation:-1,scene:NaN,geometryModifier:["geometry-modifier"],colorEffect:null,floorCulling:"all-floors"})}function pS(e){const t={visibility:"visible",sideColor:"#000000",borderTopColor:"#000000",bottomColor:"#000000",strokeColor:"#000000",strokeWidth:1,debug:!1,thickness:1,borderHeight:0,borderWidth:.3,color:"#000000",nearCameraFade:0,tunnelHeight:5};return lt(t,e),e.borderTopColor===void 0&&(t.borderTopColor=t.color),e.strokeColor===void 0&&(t.strokeColor=t.color),e.sideColor===void 0&&(t.sideColor=t.color),e.bottomColor===void 0&&(t.bottomColor=t.color),t}function gS(e){const t={visibility:"visible",sideColor:"#000000",topColor:"#000000",bottomColor:"#000000",strokeColor:"#000000",strokeWidth:1,color:"#ffffff",nearCameraFade:0};return lt(t,e),t}function mS(e){return Ci(e,{skyColor:"#6EC0FF00",fogColor:"#FAFDFF00",starsIntensity:1})}function vS(e){const t={sources:{sun:{type:"directional",altitude:50,azimuth:230,color:"#FFFFFF",intensity:.2},atmosphere:{type:"ambient",color:"#FFFFFF",intensity:.85}},lightingModes:{[po.global]:["sun","atmosphere"]},defaultLightingMode:"global"},n=Ci(e!=null?e:{},t);return n.lightingModes[po.none]=[],n}function _g(e){var i,r,s;const t={shadowsOff:!0,modelsOff:!0};lt(t,(i=e==null?void 0:e.light)!=null?i:{});const n={shadowsOff:!0};return lt(n,(r=e==null?void 0:e.normal)!=null?r:{}),{light:ie(V({},t),{transparentBuildingsOff:!0,AALinesOff:!0}),normal:n,immersive:(s=e==null?void 0:e.immersive)!=null?s:{}}}const Hi="__overlapped",Cg="__commercial",Yi="default",Gf={groups:[Yi,Hi,Cg],overlay:[[Yi,Hi]],intersect:[[]]},yS="#F5F2E0",xS=3.5,wS=5,_r=e=>{e&&Object.entries(e).forEach(([t,n])=>{n===void 0&&delete e[t]})},AS=e=>{var t;_r(e),e.type==="group"||e.type==="slot"?"commonDefaults"in e&&(_r(e.commonDefaults),_r((t=e.commonDefaults)==null?void 0:t.style),_r(e.layerTypeDefaults),e.layerTypeDefaults&&Object.values(e.layerTypeDefaults).forEach(n=>{_r(n),_r(n==null?void 0:n.style)})):e.type!=="custom"&&_r(e.style)},Na=(e,t=!1)=>{t||console.warn("assertUnreachable: ",e)},oi=null,Fg=[0,0,0];function k(e,t){var n,i,r;if(!Qt(e))return e;if(t.allowedExpressions&&!t.allowedExpressions.has(e.type))return ke(`Expression of type ${e.type} is not allowed here`),oi;switch(e.type){case"schedule":return ho(),WS(e,t);case"time":return IS(e,t);case"object-attr":return OS(e,t);case"coalesce":return Bg(e,t);case"concat":return MS(e,t);case"format":return FS(e,t);case"all":return SS(e,t);case"any":return PS(e,t);case"feature-state":return zS(e,t);case"get":return zg(e,t);case"global":return NS(e,t);case"source-attr":return DS(e,t);case"in":return qS(e,t);case"has":return KS(e,t);case"interpolate":return GS(e,t);case"match":return kS(e,t);case"when":return bS(e,t);case"step":return US(e,t);case"to-boolean":return XS(e,t);case"to-color":return Gg(e,t);case"mappoints-to-meters":return HS(e,t);case"meters-to-pixels":return YS(e,t);case"!":return ZS(e,t);case"==":case"!=":return jS(e,t);case">":case"<":case">=":case"<=":return QS(e,t);case"zoom":{if(t.type==="binder"||t.type==="labeling")return Ba(t.styleZoom),t.styleZoom;if(t.type==="generator")return(i=(n=t.tileInfo)==null?void 0:n.coords[3])!=null?i:0;const{type:o}=t;return Na(o),oi}case"pitch":{if(t.type==="binder"||t.type==="labeling")return P2(),t.pitch*Hx;if(t.type==="generator")return oi;const{type:o}=t;return Na(o),oi}case"distance":if(t.type==="binder"){const o=me.toGeo(t.objectCenter),a=me.scaleFactor(o[1])*Ee;return ff(t.objectCenter,t.cameraCenter)/a}else return ke(`Distance expression can't be resolved in the ${t.type} context`),oi;case"height":return 1;case"+":return JS(e,t);case"*":return $S(e,t);case"^":return eE(e,t);case"%":return tE(e,t);case"log10":return iE(e,t);case"clamp":return nE(e,t);case"random":return rE(e,t);case"literal-array":return sE(e,t);case"literal-object":return{type:"object",value:e.object};case"is-behind-objects":return t.type==="binder"?t.isBehind:(ke(`is-behind-objects expression cannot be used in ${t.type} context`),oi);case"geometry-modifier":return e.modifiers;case"line-pattern":return[e.patternType,...e.parameters.map(o=>k(o,t))];case"precompute":return(r=t.tileData[e.precomputeIndex])!=null?r:null;case"gltf-animation":return ho(),Og(e,t);case"local-time":return ho(),Lg(e,t);case"utc-time":return ho(),Lg(e,t);case"texture-animation":return ho(),Rg(e,t);case"easing":return e.options;case"mix":return RS(e,t);case"vertex-color":return ES(e,t);case"color-saturate":return ai(e,t,"saturate");case"color-desaturate":return ai(e,t,"desaturate");case"color-grayscale":return ai(e,t,"grayscale");case"color-lighten":return ai(e,t,"lighten");case"color-lightness":return ai(e,t,"lightness");case"color-darken":return ai(e,t,"darken");case"color-whiten":return ai(e,t,"whiten");case"color-blacken":return ai(e,t,"blacken");case"color-opacity":return ai(e,t,"opacity");case"color-effect":return TS(e,t);default:return ke(`Not supported expression type <<${e.type}>> in ${JSON.stringify(e)}`),oi}}function bS(e,t){for(const n of e.conditions)if(k(n.predicate,t)===!0)return k(n.output,t);return k(e.defaultOutput,t)}function SS(e,t){return e.array.every(n=>k(n,t)===!0)}function ES(e,t){if(t.type==="generator"){const i=k(e.vertexValue,t);if(_n(i))return i.isVertexColor=!0,i;const r=Ot([0,0,0,0]);return r.isVertexColor=!0,r}const n=k(e.uniformValue,t);return _n(n)||Oa(n)?(n.mixFactor=e.mixValue?k(e.mixValue,t):1,n):Ot([0,0,0,255],1)}function TS(e,t){if(e.effect.type==="mix")return{type:"color-effect-options",effect:{type:e.effect.type,color:li(e.effect.color,t),factor:ce(e.effect.factor,t)}}}function PS(e,t){return e.array.some(n=>k(n,t)===!0)}function Lg(e,t){const n=Date.now()+ +(t.styleState._customUserTimeOffset||0);if(e.type==="local-time"){const i=e.offset?+(k(e.offset,t)||0)*6e4:0;return n+i}if(e.type==="utc-time"){const i=e.offset?+(k(e.offset,t)||0)*6e4:0;return n+new Date().getTimezoneOffset()*6e4+i}return n}function IS(e,t){const n=i=>{const r=k(e.timeSource,t),s=new Date(+(r||0));return i==="day-minutes"?s.getHours()*60+s.getMinutes():i==="day-minutes-720"?(s.getHours()%12||0)*60+s.getMinutes():s.getTime()};if(t.type==="binder"){if(t.callBackFn){const i=Date.now()+ +(t.styleState._customUserTimeOffset||0),r=Math.floor(i/6e4)*6e4+6e4;t.callBackFn(r)}return Array.isArray(e.format)?e.format.map(i=>n(i)):n(e.format)}return n("timestamp")}function Bg(e,t){for(const n of e.array){const i=k(n,t);if(i!==null)return i}return null}function MS(e,t){const n=[];for(const i of e.array){const r=k(i,t);if(typeof r=="string")n.push(r);else if(typeof r=="boolean")n.push(String(r));else if(typeof r=="number"&&!Number.isNaN(r))n.push(String(r));else return null}return n.join("")}const _S={dateStyle:"short",timeStyle:"short"},CS=/%%|%s|%d|%fc?(?:\.\d+)?|%t[rd]?(?:\{[^}]*\})?|%x./gu;function FS(e,t){Da("lang");const n=t.styleState.lang||void 0;let i=0;return e.template.replace(CS,r=>{switch(r[1]){case"%":return"%";case"s":{const s=k(e.args[i++],t);return s==null?"":String(s)}case"d":{const s=k(e.args[i++],t);return typeof s!="number"||Number.isNaN(s)?"":String(Math.trunc(s))}case"f":{const s=k(e.args[i++],t);let o=!1,a=2;r[a]==="c"&&(o=!0,a++);let l=NaN;return r[a]==="."&&(l=Number(r.slice(a+1))),typeof s!="number"||Number.isNaN(s)?"":s.toLocaleString(n,{minimumFractionDigits:o?0:l||0,maximumFractionDigits:l||50})}case"t":{const s=k(e.args[i++],t);let o="-",a,l=2;if((r[l]==="r"||r[l]==="d")&&(o=r[l],l++),r[l]==="{"&&(a=r.slice(l+1,-1)),typeof s!="number"||Number.isNaN(s))return"";switch(o){case"-":try{return new Intl.DateTimeFormat(n,a?Dg(a):_S).format(s)}catch(c){return""}case"r":{if(!a)return"";const{unit:c,options:f}=LS(a);if(!c)return"";try{return new Intl.RelativeTimeFormat(n,f).format(s,c)}catch(u){return""}}case"d":return BS(s,a,n);default:return""}}case"x":{const s=k(e.args[i++],t),o=r.slice(2);return!o||typeof s!="number"||Number.isNaN(s)?"":o.repeat(s)}default:return""}})}function Dg(e){const t={};if(!e)return t;for(const n of e.split(",")){const i=n.indexOf(":");if(i===-1)continue;const r=n.slice(0,i).trim(),s=n.slice(i+1).trim();t[r]=s}return t}function LS(e){const t=e.split(","),n=t[0].trim(),i={};for(let r=1;r<t.length;r++){const s=t[r].indexOf(":");if(s===-1)continue;const o=t[r].slice(0,s).trim(),a=t[r].slice(s+1).trim();i[o]=a}return{unit:n,options:i}}function BS(e,t,n){const i=Math.trunc(Math.abs(e)/1e3),r=Math.trunc(i/3600),s=Math.trunc(i%3600/60),o=i%60,a={};r>0&&(a.hours=r),(s>0||r>0)&&(a.minutes=s),a.seconds=o;const l=t!==void 0?Dg(t):{style:"short"};try{return new Intl.DurationFormat(n,l).format(a)}catch(c){return r>0?`${r}:${String(s).padStart(2,"0")}:${String(o).padStart(2,"0")}`:`${s}:${String(o).padStart(2,"0")}`}}function DS(e,t){var n;return t.type==="generator"&&(n=t.sourceAttrs[e.property])!=null?n:null}function OS(e,t){return t.type==="binder"&&t.dynamicObject&&t.dynamicObject[e.property]||null}function Og(e,t){const n={type:"animation-options"};return e.options?e.options.forEach((i,r)=>n[r]=k(i,t)):Qt(e)||(n[0]=e),n}function Rg(e,t){const n={type:"texture-animation-options"};return e.options?e.options.forEach((i,r)=>n[r]=k(i,t)):Qt(e)||(n[0]=e),n}function RS(e,t){const{factorInterpolate:n}=e,i={type:"mix-options",value1:k(e.value1,t),value2:k(e.value2,t),factor:e.factor};if(n){const{steps:r,base:s}=n;i.factorInterpolate={base:s,steps:[ce(r[0].key,t,0),ce(r[0].value,t,0),ce(r[1].key,t,1),ce(r[1].value,t,1)]}}return i}function zS(e,t){var n;if(t.type==="generator"){const i=(n=t.featureAttrs[t.tileProps[e.property]])!=null?n:null;return Number.isNaN(i)?null:i}else throw new Error("Feature state expression can be resolved only in generator context")}function zg(e,t){var n;if(t.type==="generator"){let i=(n=t.tileAttrs[t.tileProps[e.property]])!=null?n:null;return typeof i=="object"&&i!==null&&!Array.isArray(i)&&(i={type:"object",value:i}),Number.isNaN(i)?null:i}else throw new Error("Get expression can be resolved only in generator context")}function NS(e,t){Da(e.property);const n=t.styleState[e.property];return n==null?null:typeof n=="object"&&!Array.isArray(n)?{type:"object",value:n}:n}function GS(e,t){if(e.steps.length===0)return ke("Interpolate expression contains 0 steps, cannot interpolate"),oi;const n=k(e.steps[0].value,t),i=Ng(e.argument,t),r=i?t.styleZoom:k(e.argument,t);if(typeof r!="number")return ke(`Interpolate value resolved to non-number value: ${r} ${e.argument}`),0;if(i&&pg()&&VS(e,r,t,!Array.isArray(n)&&!_n(n)),Array.isArray(n))return oE(e,r,t);if(_n(n)){if(Qt(e.argument)&&e.argument.type==="height"){const s={type:"gradient-color",values:[],steps:[]};return e.steps.forEach(o=>{const a=ce(o.key,t),l=k(o.value,t);_n(l)&&!Number.isNaN(a)&&(s.values.push({type:"color",value:l.value}),s.steps.push(a))}),s.steps.length!==2?(ke("Gradient expression must resolve 2 steps"),oi):s}return Ug(e,r,t)}return kg(e,r,t)}function kS(e,t){var r;const n=k(e.input,t),i=e.cases.find(s=>s.values.has(n));return k((r=i==null?void 0:i.output)!=null?r:e.defaultOutput,t)}function US(e,t){const n=Ng(e.value,t),i=Number(n?t.styleZoom:k(e.value,t)),r=Cr(e,i,t);return n&&pg()&&La(r>0?ce(e.steps[r-1].key,t):-1/0,r<e.steps.length?ce(e.steps[r].key,t):1/0),k(e.steps[r-1].value,t)}function Ng(e,t){return(t.type==="binder"||t.type==="labeling")&&Qt(e)&&e.type==="zoom"}function VS(e,t,n,i){const r=Cr(e,t,n),s=e.steps.length;r===0?La(-1/0,ce(e.steps[0].key,n)):r===s&&i&&e.base===1?La(ce(e.steps[s-1].key,n),1/0):r<s&&i&&n.type==="labeling"&&n.interpolateExpressionAsStep?La(ce(e.steps[r-1].key,n),ce(e.steps[r].key,n)):Ba(t)}function WS(e,t){var y,p;const r=(v,A)=>{const w=Date.now()+ +(A.styleState._customUserTimeOffset||0);return Math.floor(w/6e4)*6e4+v*6e4},s=e.detailResult||!1,o=v=>{if(t.type==="binder"&&t.callBackFn){const A=r(v,t);t.callBackFn(A)}};let a=k(e.steps,t);typeof a=="string"&&(a=JSON.parse(a));const l=new Array,c=new Array;if(Array.isArray(a)){l.push({key:0,value:a[0]});for(let v=1;v<a.length;v+=3){const w={key:Math.trunc(a[v]/1440)*1440,value:a[0]};c.push(w);const S={key:a[v],value:a[v+2]};l.push(S);const T={key:a[v+1],value:a[0]};l.push(T)}}for(const v of c)l.find(A=>A.key===v.key)||l.push(v);l.sort((v,A)=>v.key<A.key?-1:1);const f=Number(k(e.time,t)),u=new Date(f),d=u.getHours()*60+u.getMinutes()+(u.getDay()||7)*1440,h=Cr({steps:l},d%1440,t)-1,g=Cr({steps:l},d,t)-1;if(l[g]&&Math.trunc(l[g]&&l[g].key/1440)===Math.trunc(d/1440)){const v=Math.min((((y=l[g+1])==null?void 0:y.key)||11519)-d,1439-d%1440);o(v);const A=k(l[g].value,t)||NaN;return s?{type:"schedule-detailed-result",value:A,nextStepStartsAt:r(v,t),currentStepElapsed:(d-l[g].key)*6e4}:A}if(l[h]){const v=Math.min(((p=l[h+1])==null?void 0:p.key)||1439,1439)-d%1440;o(v);const A=k(l[h].value,t)||NaN;return s?{type:"schedule-detailed-result",value:A,nextStepStartsAt:r(v,t),currentStepElapsed:(d%1440-l[h].key)*6e4}:A}return s?{type:"schedule-detailed-result",value:NaN,nextStepStartsAt:NaN,currentStepElapsed:NaN}:NaN}function Gg(e,t){const n=k(e.value,t);if(vg(n))return Mr(n);if(_n(n))return n;if(typeof n=="number"&&Number.isInteger(n)){const i=n>>>24&255,r=n>>>16&255,s=n>>>8&255,o=n&255;return Ot([r,s,o,i])}return n&&console.warn(`Can't resolve expression. Must be color, but got ${n}`),Ot([0,0,0,0])}function ai(e,t,n){const i=k(e.color,t),r=Gg({value:i},t);return fE(r,n,e.value)}function HS(e,t){if(t.type!=="generator"||!t.tileInfo)throw new Error("Выражение `mappoints-to-meters` можно резолвить только в контексте генератора");return k(e.value,t)/(Ee*fn(t.tileInfo,[0,0]))}function YS(e,t){const n=ce(e.value,t);let i,r=n*256/tf;if(t.type==="generator"){if(!t.tileInfo)return null;i=t.tileInfo.coords[3],r*=fn(t.tileInfo,[0,0])}else Ba(t.styleZoom),i=t.styleZoom;return r*$(2,i+1)}function XS(e,t){return!!k(e.value,t)}function ZS(e,t){return!k(e.value,t)}function jS(e,t){const n=k(e.leftValue,t),i=k(e.rightValue,t);switch(e.type){case"==":return n===i;case"!=":return n!==i}}function QS(e,t){const n=k(e.leftValue,t);if(n===null)return null;const i=k(e.rightValue,t);if(i===null)return null;switch(e.type){case"<":return n<i;case">":return n>i;case"<=":return n<=i;case">=":return n>=i}}function qS(e,t){const n=k(e.item,t),i=k(e.collection,t);return i===null?!1:typeof i!="object"?(ke(`InExpression second argument resolved to non-object/non-array value: ${i}`),null):Array.isArray(i)?i.some(r=>r===n):sg(i)?Object.prototype.hasOwnProperty.call(i.value,n):(ke(`InExpression second argument resolved incorrectly: ${i}`),null)}function KS(e,t){if(t.type==="generator"){const n=t.tileProps[e.property];return n===void 0||!(n in t.tileAttrs)?!1:!Number.isNaN(t.tileAttrs[n])}else throw new Error("Has expression can be resolved only in generator context")}function JS(e,t){const n=e.array.map(i=>k(i,t));return Yn(n)?n.reduce((i,r)=>i+r,0):(ke(`Resolve AdditionExpression: arguments are not resolved as an array of numbers: ${n}`),null)}function $S(e,t){const n=e.array.map(i=>k(i,t));return Yn(n)?n.reduce((i,r)=>i*r,1):(ke(`Resolve MultiplicationExpression: arguments are not resolved as an array of numbers: ${n}`),null)}function eE(e,t){const n=k(e.base,t);if(typeof n!="number")return ke(`Resolve PowExpression: base resolved as non-number value: ${n}`),null;const i=k(e.exponent,t);return typeof i!="number"?(ke(`Resolve PowExpression: exponent resolved as non-number value: ${i}`),null):Math.pow(n,i)}function tE(e,t){const n=k(e.leftValue,t);if(typeof n!="number")return ke(`Resolve ModuloExpression: leftValue resolved as non-number value: ${n}`),null;const i=k(e.rightValue,t);return typeof i!="number"?(ke(`Resolve ModuloExpression: rightValue resolved as non-number value: ${i}`),null):i===0?(ke("Resolve ModuloExpression: rightValue is zero, cannot modulo"),null):n%i}function nE(e,t){const n=k(e.value,t);if(typeof n!="number")return ke(`Resolve ClampExpression: value resolved as non-number value: ${n}`),null;const i=k(e.min,t);if(typeof i!="number")return ke(`Resolve ClampExpression: min resolved as non-number value: ${i}`),null;const r=k(e.max,t);return typeof r!="number"?(ke(`Resolve ClampExpression: max resolved as non-number value: ${r}`),null):Math.max(i,Math.min(r,n))}function iE(e,t){const n=k(e.value,t);return typeof n!="number"?(ke(`Resolve Log10Expression: value resolved as non-number value: ${n}`),null):Math.log10(n)}function rE(e,t){const n=k(e.start,t);if(typeof n!="number")return ke(`Resolve RandomizationExpression: start resolved as non-number value: ${n}`),null;const i=k(e.end,t);return typeof i!="number"?(ke(`Resolve RandomizationExpression: end resolved as non-number value: ${i}`),null):i<n?(ke("Resolve RandomizationExpression: end cannot be less than start."),null):cs(t,n,i)}function sE(e,t){return e.array.map(n=>k(n,t))}function oE(e,t,n){const i=Cr(e,t,n);if(i===0)return k(e.steps[0].value,n);if(i===e.steps.length)return k(e.steps[e.steps.length-1].value,n);const r=kf(e,t,i,n),s=k(e.steps[i-1].value,n),o=k(e.steps[i].value,n);return s.map((a,l)=>a*(1-r)+o[l]*r)}function kg(e,t,n){const i=Cr(e,t,n);if(i===0)return Number(k(e.steps[0].value,n));if(i===e.steps.length)return lE(e,n,t);const r=Number(k(e.steps[i-1].value,n));if(n.type==="labeling"&&n.interpolateExpressionAsStep)return r;const s=kf(e,t,i,n),o=Number(k(e.steps[i].value,n));return(1-s)*r+s*o}function li(e,t,n=!1){const i=k(e,t);return _n(i)?i:Oa(i)?i.values[1]:lg(i)?_n(i.value1)&&_n(i.value2)?n?p2(i):(console.warn("Mixing color is not supported here."),Ot([0,0,0,0])):(console.warn(`Mix values cannot be converted to colors in ${JSON.stringify(i)}`),Ot([0,0,0,0])):(console.warn(`Can't resolve expression. Must be color, but got ${i}`),Ot([0,0,0,0]))}function aE(e,t){const n=k(e,t);return Oa(n)?n:null}function ce(e,t,n=NaN){const i=k(e,t);return typeof i=="number"?i:n}function Mt(e,t,n=""){const i=k(e,t);return typeof i=="string"?i:n}function Ga(e,t,n=Ig){const i=k(e,t);return l2(i)?i:n}function Ug(e,t,n){const i=Cr(e,t,n);if(i===0)return li(e.steps[0].value,n);if(i===e.steps.length)return li(e.steps[e.steps.length-1].value,n);const r=kf(e,t,i,n),s=li(e.steps[i-1].value,n).value,o=li(e.steps[i].value,n).value;return Ot([s[0]*(1-r)+o[0]*r,s[1]*(1-r)+o[1]*r,s[2]*(1-r)+o[2]*r,s[3]*(1-r)+o[3]*r])}function lE(e,t,n){const i=e.steps[e.steps.length-1],r=e.base;return r===1?ce(i.value,t):ce(i.value,t)*Math.pow(r,n-ce(i.key,t))}function Vg(e,t,n,i,r=!1,s,o,a){return{type:"binder",styleZoom:e,pitch:t,styleState:n,tileData:i,randomSeed:0,isBehind:r,dynamicObject:s,cameraCenter:o!=null?o:Fg,objectCenter:a!=null?a:Fg}}function dn(e,t,n,i,r){return{type:"labeling",styleZoom:e,pitch:t,styleState:n,interpolateExpressionAsStep:i,randomSeed:0,tileData:r}}function go(e,t,n,i,r,s,o,a,l){return{type:"generator",styleState:e,tileProps:n,tileAttrs:i,id:o,tileData:[],featureAttrs:r,sourceAttrs:t,randomSeed:0,tileInfo:a,ecefDataState:l,needFallbackScreenLabels:s}}function Cr(e,t,n){let i=0;for(;i<e.steps.length&&!(t<ce(e.steps[i].key,n));)i++;return i}function kf(e,t,n,i){const r=e.base,s=ce(e.steps[n].key,i)-ce(e.steps[n-1].key,i),o=t-ce(e.steps[n-1].key,i);return r===1?o/s:(Math.pow(r,o)-1)/(Math.pow(r,s)-1)}function cE(e){const[t,n,i,r]=e.value;return[((t*r+127)/255>>>0)/255,((n*r+127)/255>>>0)/255,((i*r+127)/255>>>0)/255,r/255]}function fE(e,t="",n){const[i,r,s,o]=e.value;switch(t){case"opacity":return Ot([i,r,s,n]);case"saturate":return O2(e,n);case"desaturate":return R2(e,n);case"grayscale":return k2(e);case"lighten":return B2(e,n);case"darken":return D2(e,n);case"whiten":return N2(e,n);case"blacken":return G2(e,n);case"lightness":return z2(e,n)}return{type:"color",value:[i,r,s,o]}}function ka(e){const[t,n,i,r]=e.value;return r<<24|i<<16|n<<8|t}function Fr(e,t,n,i=!1){const r=[];return Lr(r,e,t,n),i?r:Array.from(new Set(r))}function uE(e,t){const n={};return Object.keys(e).forEach(i=>{n[i]=dE(e[i],t)}),n}const fs=ua();function Wg(e,t){const n=new Float32Array(3);return Be(n,1,0,0),mA(fs),xA(fs,fs,-Le(t-90)),yA(fs,fs,-Le(e)),Lw(n,n,fs),jt(n,n),lf(n,n),n}function dE(e,t){var i,r;const n={ambientColorIntensity:new Float32Array(li(e.ambientColor,t).value.map(s=>s/255)),dir1ColorIntensity:new Float32Array(li(e.dir1Color,t).value.map(s=>s/255)),dir1Direction:Wg(k(e.dir1Altitude,t),k(e.dir1Azimuth,t)),dir2ColorIntensity:new Float32Array(li(e.dir2Color,t).value.map(s=>s/255)),dir2Direction:Wg(k(e.dir2Altitude,t),k(e.dir2Azimuth,t)),shadowLightIndex:(i=e.shadowLightIndex)!=null?i:-1,shadowRadius:(r=e.shadowRadius)!=null?r:1};return n.ambientColorIntensity[3]=k(e.ambientIntensity,t),n.dir1ColorIntensity[3]=k(e.dir1Intensity,t),n.dir2ColorIntensity[3]=k(e.dir2Intensity,t),n}function Lr(e,t,n,i){if(!Qt(t)){e.push(t);return}switch(t.type){case"all":return hE(e,t,n,i);case"match":return pE(e,t,n,i);case"step":return gE(e,t,n,i);case"interpolate":return mE(e,t,n,i);case"coalesce":{if(!n){console.error("There is no context to resolve the expression. The value from data will not be added to the result.");return}const r=Bg(t,n);e.push(r);return}case"precompute":if(i){const r=i.precomputes[t.precomputeIndex].expr;Lr(e,r,n,i);return}break;case"get":{if(!n){console.error("There is no context to resolve the expression. The value from data will not be added to the result.");return}const r=zg(t,n);e.push(r);return}}}function hE(e,t,n,i){t.array.forEach(r=>Lr(e,r,n,i))}function pE(e,t,n,i){Lr(e,t.defaultOutput),t.cases.forEach(r=>Lr(e,r.output,n,i))}function gE(e,t,n,i){t.steps.forEach(r=>Lr(e,r.value,n,i))}function mE(e,t,n,i){t.steps.forEach(r=>Lr(e,r.value,n,i))}function Uf(e,t){const n=k(e,t);if(typeof n=="number")return[n,n,n,n];if(Array.isArray(n)&&n.every(i=>typeof i=="number")){if(n.length===1)return[n[0],n[0],n[0],n[0]];if(n.length===2)return[n[0],n[1],n[0],n[1]];if(n.length===4)return n}return[0,0,0,0]}function Vf(e){return Hs*e}function Wf(e){return e/Hs}function vE(e){return!!e.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$/i)}const yE={arrow:!0,buildingModel:!0,custom:!0,dashedLine:!0,embankment:!0,group:!0,heatmap:!0,labelLine:!0,line:!0,lineExtrusion:!0,metricPoint:!0,model:!0,oneWayLine:!0,overpass:!0,point:!0,polygon:!0,polygon3d:!0,polygonExtrusion:!0,raster:!0,shiftedLine:!0,slot:!0,tunnel:!0};function xE(e){return yE[e]}function wE(e){return e!=="group"&&e!=="slot"&&e!=="custom"}function AE(e){return e==="model"?"gltfModel":e!=="group"&&e!=="slot"?e:void 0}function bE(){let e=new Zt(4);return e[0]=1,e[1]=0,e[2]=0,e[3]=1,e}function SE(e,t,n,i,r){return e[0]=t,e[1]=n,e[2]=i,e[3]=r,e}function EE(e){return e[0]*e[3]-e[2]*e[1]}var Ua={exports:{}},Va={exports:{}},TE=Va.exports,Hg;function PE(){return Hg||(Hg=1,(function(e,t){(function(n,i){e.exports=i()})(TE,(function(){function n(o,a,l,c,f){i(o,a,l||0,c||o.length-1,f||s)}function i(o,a,l,c,f){for(;c>l;){if(c-l>600){var u=c-l+1,d=a-l+1,h=Math.log(u),g=.5*Math.exp(2*h/3),y=.5*Math.sqrt(h*g*(u-g)/u)*(d-u/2<0?-1:1),p=Math.max(l,Math.floor(a-d*g/u+y)),v=Math.min(c,Math.floor(a+(u-d)*g/u+y));i(o,a,p,v,f)}var A=o[a],w=l,S=c;for(r(o,l,a),f(o[c],A)>0&&r(o,l,c);w<S;){for(r(o,w,S),w++,S--;f(o[w],A)<0;)w++;for(;f(o[S],A)>0;)S--}f(o[l],A)===0?r(o,l,S):(S++,r(o,S,c)),S<=a&&(l=S+1),a<=S&&(c=S-1)}}function r(o,a,l){var c=o[a];o[a]=o[l],o[l]=c}function s(o,a){return o<a?-1:o>a?1:0}return n}))})(Va)),Va.exports}var Yg;function IE(){if(Yg)return Ua.exports;Yg=1,Ua.exports=t,Ua.exports.default=t;var e=PE();function t(p,v){if(!(this instanceof t))return new t(p,v);this._maxEntries=Math.max(4,p||9),this._minEntries=Math.max(2,Math.ceil(this._maxEntries*.4)),v&&this._initFormat(v),this.clear()}t.prototype={all:function(){return this._all(this.data,[])},search:function(p){var v=this.data,A=[],w=this.toBBox;if(!h(p,v))return A;for(var S=[],T,I,C,M;v;){for(T=0,I=v.children.length;T<I;T++)C=v.children[T],M=v.leaf?w(C):C,h(p,M)&&(v.leaf?A.push(C):d(p,M)?this._all(C,A):S.push(C));v=S.pop()}return A},collides:function(p){var v=this.data,A=this.toBBox;if(!h(p,v))return!1;for(var w=[],S,T,I,C;v;){for(S=0,T=v.children.length;S<T;S++)if(I=v.children[S],C=v.leaf?A(I):I,h(p,C)){if(v.leaf||d(p,C))return!0;w.push(I)}v=w.pop()}return!1},load:function(p){if(!(p&&p.length))return this;if(p.length<this._minEntries){for(var v=0,A=p.length;v<A;v++)this.insert(p[v]);return this}var w=this._build(p.slice(),0,p.length-1,0);if(!this.data.children.length)this.data=w;else if(this.data.height===w.height)this._splitRoot(this.data,w);else{if(this.data.height<w.height){var S=this.data;this.data=w,w=S}this._insert(w,this.data.height-w.height-1,!0)}return this},insert:function(p){return p&&this._insert(p,this.data.height-1),this},clear:function(){return this.data=g([]),this},remove:function(p,v){if(!p)return this;for(var A=this.data,w=this.toBBox(p),S=[],T=[],I,C,M,B;A||S.length;){if(A||(A=S.pop(),C=S[S.length-1],I=T.pop(),B=!0),A.leaf&&(M=n(p,A.children,v),M!==-1))return A.children.splice(M,1),S.push(A),this._condense(S),this;!B&&!A.leaf&&d(A,w)?(S.push(A),T.push(I),I=0,C=A,A=A.children[0]):C?(I++,A=C.children[I],B=!1):A=null}return this},toBBox:function(p){return p},compareMinX:o,compareMinY:a,toJSON:function(){return this.data},fromJSON:function(p){return this.data=p,this},_all:function(p,v){for(var A=[];p;)p.leaf?v.push.apply(v,p.children):A.push.apply(A,p.children),p=A.pop();return v},_build:function(p,v,A,w){var S=A-v+1,T=this._maxEntries,I;if(S<=T)return I=g(p.slice(v,A+1)),i(I,this.toBBox),I;w||(w=Math.ceil(Math.log(S)/Math.log(T)),T=Math.ceil(S/Math.pow(T,w-1))),I=g([]),I.leaf=!1,I.height=w;var C=Math.ceil(S/T),M=C*Math.ceil(Math.sqrt(T)),B,D,F,z;for(y(p,v,A,M,this.compareMinX),B=v;B<=A;B+=M)for(F=Math.min(B+M-1,A),y(p,B,F,C,this.compareMinY),D=B;D<=F;D+=C)z=Math.min(D+C-1,F),I.children.push(this._build(p,D,z,w-1));return i(I,this.toBBox),I},_chooseSubtree:function(p,v,A,w){for(var S,T,I,C,M,B,D,F;w.push(v),!(v.leaf||w.length-1===A);){for(D=F=1/0,S=0,T=v.children.length;S<T;S++)I=v.children[S],M=l(I),B=f(p,I)-M,B<F?(F=B,D=M<D?M:D,C=I):B===F&&M<D&&(D=M,C=I);v=C||v.children[0]}return v},_insert:function(p,v,A){var w=this.toBBox,S=A?p:w(p),T=[],I=this._chooseSubtree(S,this.data,v,T);for(I.children.push(p),s(I,S);v>=0&&T[v].children.length>this._maxEntries;)this._split(T,v),v--;this._adjustParentBBoxes(S,T,v)},_split:function(p,v){var A=p[v],w=A.children.length,S=this._minEntries;this._chooseSplitAxis(A,S,w);var T=this._chooseSplitIndex(A,S,w),I=g(A.children.splice(T,A.children.length-T));I.height=A.height,I.leaf=A.leaf,i(A,this.toBBox),i(I,this.toBBox),v?p[v-1].children.push(I):this._splitRoot(A,I)},_splitRoot:function(p,v){this.data=g([p,v]),this.data.height=p.height+1,this.data.leaf=!1,i(this.data,this.toBBox)},_chooseSplitIndex:function(p,v,A){var w,S,T,I,C,M,B,D;for(M=B=1/0,w=v;w<=A-v;w++)S=r(p,0,w,this.toBBox),T=r(p,w,A,this.toBBox),I=u(S,T),C=l(S)+l(T),I<M?(M=I,D=w,B=C<B?C:B):I===M&&C<B&&(B=C,D=w);return D},_chooseSplitAxis:function(p,v,A){var w=p.leaf?this.compareMinX:o,S=p.leaf?this.compareMinY:a,T=this._allDistMargin(p,v,A,w),I=this._allDistMargin(p,v,A,S);T<I&&p.children.sort(w)},_allDistMargin:function(p,v,A,w){p.children.sort(w);var S=this.toBBox,T=r(p,0,v,S),I=r(p,A-v,A,S),C=c(T)+c(I),M,B;for(M=v;M<A-v;M++)B=p.children[M],s(T,p.leaf?S(B):B),C+=c(T);for(M=A-v-1;M>=v;M--)B=p.children[M],s(I,p.leaf?S(B):B),C+=c(I);return C},_adjustParentBBoxes:function(p,v,A){for(var w=A;w>=0;w--)s(v[w],p)},_condense:function(p){for(var v=p.length-1,A;v>=0;v--)p[v].children.length===0?v>0?(A=p[v-1].children,A.splice(A.indexOf(p[v]),1)):this.clear():i(p[v],this.toBBox)},_initFormat:function(p){var v=["return a"," - b",";"];this.compareMinX=new Function("a","b",v.join(p[0])),this.compareMinY=new Function("a","b",v.join(p[1])),this.toBBox=new Function("a","return {minX: a"+p[0]+", minY: a"+p[1]+", maxX: a"+p[2]+", maxY: a"+p[3]+"};")}};function n(p,v,A){if(!A)return v.indexOf(p);for(var w=0;w<v.length;w++)if(A(p,v[w]))return w;return-1}function i(p,v){r(p,0,p.children.length,v,p)}function r(p,v,A,w,S){S||(S=g(null)),S.minX=1/0,S.minY=1/0,S.maxX=-1/0,S.maxY=-1/0;for(var T=v,I;T<A;T++)I=p.children[T],s(S,p.leaf?w(I):I);return S}function s(p,v){return p.minX=Math.min(p.minX,v.minX),p.minY=Math.min(p.minY,v.minY),p.maxX=Math.max(p.maxX,v.maxX),p.maxY=Math.max(p.maxY,v.maxY),p}function o(p,v){return p.minX-v.minX}function a(p,v){return p.minY-v.minY}function l(p){return(p.maxX-p.minX)*(p.maxY-p.minY)}function c(p){return p.maxX-p.minX+(p.maxY-p.minY)}function f(p,v){return(Math.max(v.maxX,p.maxX)-Math.min(v.minX,p.minX))*(Math.max(v.maxY,p.maxY)-Math.min(v.minY,p.minY))}function u(p,v){var A=Math.max(p.minX,v.minX),w=Math.max(p.minY,v.minY),S=Math.min(p.maxX,v.maxX),T=Math.min(p.maxY,v.maxY);return Math.max(0,S-A)*Math.max(0,T-w)}function d(p,v){return p.minX<=v.minX&&p.minY<=v.minY&&v.maxX<=p.maxX&&v.maxY<=p.maxY}function h(p,v){return v.minX<=p.maxX&&v.minY<=p.maxY&&v.maxX>=p.minX&&v.maxY>=p.minY}function g(p){return{children:p,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function y(p,v,A,w,S){for(var T=[v,A],I;T.length;)A=T.pop(),v=T.pop(),!(A-v<=w)&&(I=v+Math.ceil((A-v)/w/2)*w,e(p,I,v,A,S),T.push(v,I,I,A))}return Ua.exports}var ME=IE();const mo=Ff(ME);var Hf,Xg;function _E(){if(Xg)return Hf;Xg=1,Hf=i;var e=128,t=-128,n=Math.pow(2,31);function i(r,s,o){if(Number.MAX_SAFE_INTEGER&&r>Number.MAX_SAFE_INTEGER)throw i.bytes=0,new RangeError("Could not encode varint");s=s||[],o=o||0;for(var a=o;r>=n;)s[o++]=r&255|e,r/=128;for(;r&t;)s[o++]=r&255|e,r>>>=7;return s[o]=r|0,i.bytes=o-a+1,s}return Hf}var Yf,Zg;function CE(){if(Zg)return Yf;Zg=1,Yf=n;var e=128,t=127;function n(i,o){var s=0,o=o||0,a=0,l=o,c,f=i.length;do{if(l>=f||a>49)throw n.bytes=0,new RangeError("Could not decode varint");c=i[l++],s+=a<28?(c&t)<<a:(c&t)*Math.pow(2,a),a+=7}while(c>=e);return n.bytes=l-o,s}return Yf}var Xf,jg;function FE(){if(jg)return Xf;jg=1;var e=Math.pow(2,7),t=Math.pow(2,14),n=Math.pow(2,21),i=Math.pow(2,28),r=Math.pow(2,35),s=Math.pow(2,42),o=Math.pow(2,49),a=Math.pow(2,56),l=Math.pow(2,63);return Xf=function(c){return c<e?1:c<t?2:c<n?3:c<i?4:c<r?5:c<s?6:c<o?7:c<a?8:c<l?9:10},Xf}var Zf,Qg;function LE(){return Qg||(Qg=1,Zf={encode:_E(),decode:CE(),encodingLength:FE()}),Zf}var BE=LE();const qg=Ff(BE);class Kg{constructor(t){const n=ArrayBuffer.isView(t)?t.buffer:t;this.buf=new Uint8Array(n),this.view=new DataView(n),this.pos=0}readBytes(t){const n=this.buf.subarray(this.pos,this.pos+t);return this.pos+=t,n}readUint8(){const t=this.view.getUint8(this.pos);return this.pos+=Uint8Array.BYTES_PER_ELEMENT,t}readInt8(){const t=this.view.getInt8(this.pos);return this.pos+=Int8Array.BYTES_PER_ELEMENT,t}readUint16(){const t=this.view.getUint16(this.pos,!0);return this.pos+=Uint16Array.BYTES_PER_ELEMENT,t}readUint32(){const t=this.view.getUint32(this.pos,!0);return this.pos+=Uint32Array.BYTES_PER_ELEMENT,t}readInt32(){const t=this.view.getInt32(this.pos,!0);return this.pos+=Int32Array.BYTES_PER_ELEMENT,t}readVarint(){var n;const t=qg.decode(this.buf,this.pos);return this.pos+=(n=qg.decode.bytes)!=null?n:0,t}readSVarint(){const t=this.readVarint();return t%2===1?(t+1)/-2:t/2}skip(t){this.pos+=t}}function DE(e){const t=new Kg(e);t.readUint32(),t.readUint16(),t.readUint16(),t.readUint16(),t.readUint16();const n=jf(t.readInt32()),i=jf(t.readInt32()),r=t.readUint32(),s=[];for(let o=0;o<r;o++){const a=t.readUint32(),l=new Uint16Array(a*2);for(let y=0;y<a;y++)l[y*2]=t.readUint16(),l[y*2+1]=t.readUint16();const c=new Float32Array(a);Jg(t,c,a,jf);const f=t.readUint32(),u=a>He?new Uint32Array(f):new Uint16Array(f);Jg(t,u,f);const d={positions:l,heights:c,indices:u},h=t.readUint32();if(h>0){const y=[];new Int8Array(t.readBytes(h*3)).forEach(p=>y.push(OE(p)))}const g=t.readUint32();if(g>0){const y={};for(let p=0;p<g;p++){const v=t.readUint16(),A=t.readInt32();y[v]=A}d.attributes=y}s.push(d)}return{dataGroups:s,minZ:n,maxZ:i}}function Jg(e,t,n,i){let r=0;for(let s=0;s<n;s++){const a=e.readSVarint()+r;t[s]=i?i(a):a,r=a}}function jf(e){return e/Ee}function OE(e){return e/127}function RE(e){const t=new xa(e),n=Qf(t.readFixed32()),i=Qf(t.readFixed32()),r=t.readFixed32(),s=t.readBytes(),o=new Uint16Array(s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength)),a=new Float32Array(r);for(let u=0;u<r;u++)a[u]=Qf(t.readSVarint());let l=0;const c=t.readFixed32(),f=r>He?new Uint32Array(c):new Uint16Array(c);for(let u=0;u<c;u++){const d=t.readSVarint(),h=l+d;l+=d,f[u]=h}return{dataGroups:[{positions:o,heights:a,indices:f}],minZ:n,maxZ:i}}function Qf(e){return e/100}function zE(e){const t=Math.log(e)*256;return t+(t<0?-.5:.5)<<16>>16}function qt(e){return e*32768+.5<<16>>>16}function NE(e){return Math.log(e)*256+.5<<16>>16}let qf=0;function Kf(){return qf++}function GE(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Invalid layer ID reservation size");const t=qf;return qf+=e,t}const vo=Kf(),Jf=Kf(),$g=128,Kt={symbol:"dem",sinks:{mesh:{stride:4,binder:(e,t)=>{},packObjectAttributes(e,t){return[e,t]},unpackObjectAttributes(e){return{styleId:e[0],layerId:e[1],tileData:e.slice(3)}}},mesh2:{stride:8,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.height=new Float32Array(t,4)},packObjectAttributes(e,t){return[e,t]},unpackObjectAttributes(e){return{styleId:e[0],layerId:e[1],tileData:e.slice(2)}}},hillshade:{stride:8,binder:(e,t)=>{},packObjectAttributes(e,t){return[e,t]},unpackObjectAttributes(e){return{styleId:e[0],layerId:e[1],tileData:e.slice(2)}}},flatBottom:{stride:12,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.demPosition=new Int16Array(t,4),e.views.extender=new Int8Array(t,8)},packObjectAttributes(e,t,n){return n?[e,t,n]:[e,t]},unpackObjectAttributes(e){return{styleId:e[0],layerId:e[1],matrix:e[2]?e[2]:void 0,tileData:e.slice(3)}}}},generateMeshElevation(e,t,n,i){const r=e.getBucket("dem","mesh2",Kt.sinks.mesh2.packObjectAttributes(n,i),Kt.sinks.mesh2.binder);VE(r,t)},generateHillshade(e,t,n,i){const r=new Uint16Array(t.reduce((o,a)=>{const[l,c,f,u]=a;return o.push(l*ae,c*ae,qt(f),qt(u)),o},[]));return{symbol:Kt.symbol,sink:"hillshade",buffer:r.buffer,generatedObjects:[{drawMode:qo,attributes:Kt.sinks.hillshade.packObjectAttributes(n,i),rangeStart:0,rangeEnd:r.buffer.byteLength,extents:new Float32Array(6)}]}},generateFloorsBottomFill(e,t,n,i,r,s){const o=n[0],a=n[1],l=n[0].length,c=Kt.sinks.flatBottom.packObjectAttributes(t,vo,s),f=e.getBucket("dem","flatBottom",c,Kt.sinks.flatBottom.binder);kE(f,l,o,a,i,r,!!s)}};function kE(e,t,n,i,r,s,o){let a=e.elements.offset;const l=a;if(!(t<3)){$f(e,a++,n[0],i[0],s,r[0],o),$f(e,a++,n[1],i[1],s,r[1],o);for(let c=2;c<t;c++)UE(e,l,c),$f(e,a++,n[c],i[c],s,r[c],o);e.elements.offset=a}}function $f(e,t,n,i,r,s,o){const a=t*(e.elements.stride/e.views.position.BYTES_PER_ELEMENT),l=t*(e.elements.stride/e.views.extender.BYTES_PER_ELEMENT);e.views.position[a]=o?n:W+n,e.views.position[a+1]=o?i:W+i,e.views.demPosition[a]=(o?r[0]:W+r[0])/8,e.views.demPosition[a+1]=(o?r[1]:W+r[1])/8,e.views.extender[l]=s[0]*127,e.views.extender[l+1]=s[1]*127}function UE(e,t,n){const i=e.indices.buffer;let r=e.indices.offset;n%2===0?(i[r++]=t+n-2,i[r++]=t+n-1,i[r++]=t+n):(i[r++]=t+n-1,i[r++]=t+n-2,i[r++]=t+n),e.indices.offset=r}function VE(e,t,n=!1){for(let i=0;i<t.indices.length;i++){const r=t.indices[i],s=e.elements.offset*(e.elements.stride/e.views.position.BYTES_PER_ELEMENT),o=t.positions[r*2],a=t.positions[r*2+1];e.views.position[s]=W+(n?em(o):o),e.views.position[s+1]=W+(n?em(a):a);const l=e.elements.offset*(e.elements.stride/e.views.height.BYTES_PER_ELEMENT);e.views.height[l]=t.heights[r],e.elements.offset++,e.indices.buffer[e.indices.offset]=i,e.indices.offset++}}function em(e){return e===0?e-=$g:e===ae&&(e+=$g),e}const tm=[0,0,0],nm=[0,0,0],im=[0,0,0],Wa=[0,0,0],WE=(e,t,n,i,r)=>Ze([e,t.innerId,n,i],t,r),HE=e=>({styleId:e[0],layerId:e[1],meshTier:e[2],absZ:e[3],tileData:e.slice(4)}),us=16,Ha=24,Xn={symbol:"mapMesh",sinks:{fill:{stride:28,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.height=new Float32Array(t,4),e.views.extender=new Int16Array(t,8),e.views.normal=new Int8Array(t,12),e.views.gradient=new Int8Array(t,15),e.views.demPosition=new Int16Array(t,16),e.views.absZ=new Float32Array(t,us),e.views.labelingTextureID=new Uint32Array(t,20),e.views.isPivot=new Uint8Array(t,Ha)},packObjectAttributes:WE,unpackObjectAttributes:HE}},generate(e,t,n,i,r,s,o,a){var C;const l=r.x,c=r.y,f=(C=r.signed_z)!=null?C:[],u=r.gradient,d=r.is_pivot,h=r.abs_z,g=l.length,y=a==null?void 0:a[0],p=a==null?void 0:a[1];if(g<3)return;const v=e.pointIndexer.getIndexByTier(s),A=ae/o.size,w=e.getBucket("mapMesh","fill",Xn.sinks.fill.packObjectAttributes(t,n,s,!!h,i),Xn.sinks.fill.binder),S=w.indices.buffer;let T=w.indices.offset;const I=w.elements.offset;for(let M=2;M<g;M++){const B=!(M%2),D=B?M-2:M-1,F=B?M-1:M-2;YE(S,T,I,(M-2)*3+2),Be(im,l[D],c[D],f[D]*A),Be(nm,l[F],c[F],f[F]*A),Be(tm,l[M],c[M],f[M]*A),Fp(Wa,im,nm,tm),eu(w,l[D],c[D],f[D],v,u==null?void 0:u[D],d==null?void 0:d[D],h==null?void 0:h[D],Wa,y,p),eu(w,l[F],c[F],f[F],v,u==null?void 0:u[F],d==null?void 0:d[F],h==null?void 0:h[F],Wa,y,p),eu(w,l[M],c[M],f[M],v,u==null?void 0:u[M],d==null?void 0:d[M],h==null?void 0:h[M],Wa,y,p),T+=3}w.indices.offset=T}};function YE(e,t,n,i){e[t]=n+i-2,e[t+1]=n+i-1,e[t+2]=n+i}function eu(e,t,n,i,r,s,o,a,l,c=t,f=n){const u=e.elements.offset*e.elements.stride,d=u/e.views.position.BYTES_PER_ELEMENT,h=u/e.views.normal.BYTES_PER_ELEMENT,g=u/e.views.demPosition.BYTES_PER_ELEMENT;e.views.position[d]=W+t,e.views.position[d+1]=W+n,e.views.height[u/e.views.height.BYTES_PER_ELEMENT]=i,e.views.normal[h]=at(l[0]),e.views.normal[h+1]=at(l[1]),e.views.normal[h+2]=at(l[2]),e.views.gradient[u/e.views.gradient.BYTES_PER_ELEMENT]=s!=null?s:0,e.views.isPivot[u/e.views.isPivot.BYTES_PER_ELEMENT]=o!=null?o:0,e.views.demPosition[g]=(W+c)/8,e.views.demPosition[g+1]=(W+f)/8,a!==void 0&&(e.views.absZ[u/e.views.absZ.BYTES_PER_ELEMENT]=a),e.views.labelingTextureID[u/e.views.labelingTextureID.BYTES_PER_ELEMENT]=r,e.elements.offset++}const rm=(()=>{let e=new DataView(new ArrayBuffer(1025));return function(r){const s=r.toJSON(),o=t(s,0);return e.buffer.slice(0,o)};function t(r,s){i(s),e.setUint16(s,r.minX,!0),s+=2,e.setUint16(s,r.minY,!0),s+=2,e.setUint16(s,r.maxX,!0),s+=2,e.setUint16(s,r.maxY,!0),s+=2;const o=s;if(s+=4,r.children.length>127)throw new Error("Too many children in RBush node to serialize");return e.setUint8(s,(r.leaf?1:0)|r.children.length<<1),s+=1,r.children.forEach(a=>{r.leaf?s=n(a,s):s=t(a,s)}),e.setUint32(o,s-o-4,!0),s}function n(r,s){if(i(s),e.setUint16(s,r.minX,!0),s+=2,e.setUint16(s,r.minY,!0),s+=2,e.setUint16(s,r.maxX,!0),s+=2,e.setUint16(s,r.maxY,!0),s+=2,e.setUint32(s,r.posOffset,!0),s+=4,r.bucketIndex>255)throw new Error("[RTreeBin] Bucket index too large to serialize");if(e.setUint8(s,r.bucketIndex),s+=1,r.batchIndex>255)throw new Error("[RTreeBin] Batch index too large to serialize");return e.setUint8(s,r.batchIndex),s+=1,s}function i(r){if(e.buffer.byteLength<=r+256){const s=new ArrayBuffer(e.buffer.byteLength*2);new Uint8Array(s).set(new Uint8Array(e.buffer),0),e=new DataView(s)}}})();function sm(e,t){const n=new Kg(e),i=[];return om(n,t,i),i}function om(e,t,n){const i=e.readUint16(),r=e.readUint16(),s=e.readUint16(),o=e.readUint16(),a=e.readUint32();if(t[0]<i||t[0]>s||t[1]<r||t[1]>o){e.skip(a);return}const l=e.readUint8(),c=(l&1)===1,f=l>>1;for(let u=0;u<f;u++)c?XE(e,t,n):om(e,t,n)}function XE(e,t,n){const i=e.readUint16(),r=e.readUint16(),s=e.readUint16(),o=e.readUint16();if(i>t[0]||s<t[0]||r>t[1]||o<t[1]){e.skip(6);return}const a=e.readUint32(),l=e.readUint8(),c=e.readUint8();n.push({posOffset:a,bucketIndex:l,batchIndex:c,minX:i,minY:r,maxX:s,maxY:o})}const ci=nt(),Ya=nt(),Xa=nt(),_t=nt(),Xi=nt(),am=nt(),lm=nt(),hn=nt(),ZE=Ye(),jE=Ye(),cm=bE(),QE=64,tu=9,fm=(e,t,n,i,r)=>{const s=eo(e.tileServer,{subdomain:e.subdomains[Math.abs(t+n)%e.subdomains.length]});return`${e.tileProtocol}://${s}/v2/ald?ts=${r}&x=${t}&y=${n}&z=${i}`};function qE(e){const t=[];return e.forEach((n,i)=>{n.symbol!=="dem"||n.sink!=="mesh2"||n.generatedObjects.forEach((r,s)=>{const o=Kt.sinks.mesh2.stride/Uint16Array.BYTES_PER_ELEMENT,a=new Uint16Array(n.buffer,r.rangeStart,(r.rangeEnd-r.rangeStart)/Uint16Array.BYTES_PER_ELEMENT);for(let l=0;l<a.length;l+=o*3){const c=l,f=l+o,u=l+o*2;t.push({minX:Math.min(a[c],a[f],a[u])-W,maxX:Math.max(a[c],a[f],a[u])-W,minY:Math.min(a[c+1],a[f+1],a[u+1])-W,maxY:Math.max(a[c+1],a[f+1],a[u+1])-W,posOffset:l,bucketIndex:i,batchIndex:s})}})}),t.length?rm(mo(tu).load(t)):null}function KE(e){return Array.from(JE(e),([t,n])=>({tier:t,tree:rm(mo(tu).load(n))}))}function JE(e){const t=new Map;return e.forEach((n,i)=>{n.symbol!=="mapMesh"||n.sink!=="fill"||n.generatedObjects.forEach((r,s)=>{const{meshTier:o}=Xn.sinks.fill.unpackObjectAttributes(r.attributes);if(o===0||o===void 0)return;let a=t.get(o);a||(a=[],t.set(o,a));const l=Xn.sinks.fill.stride/Uint16Array.BYTES_PER_ELEMENT,c=new Uint16Array(n.buffer,r.rangeStart,(r.rangeEnd-r.rangeStart)/Uint16Array.BYTES_PER_ELEMENT);for(let f=0;f<c.length;f+=l*3){const u=f,d=f+l,h=f+l*2;a.push({minX:Math.min(c[u],c[d],c[h])-W,maxX:Math.max(c[u],c[d],c[h])-W,minY:Math.min(c[u+1],c[d+1],c[h+1])-W,maxY:Math.max(c[u+1],c[d+1],c[h+1])-W,posOffset:f,bucketIndex:i,batchIndex:s})}})}),t}function ds(e,t,n){const i=n/(Float32Array.BYTES_PER_ELEMENT/Uint16Array.BYTES_PER_ELEMENT);return[e[n]-W,e[n+1]-W,t[i]]}function um(e,t){var n;return(n=t==null?void 0:t.tileCoords)!=null?n:Ef(e.key)}function $E(e,t,n,i){const r=e[t]*8-W,s=e[t+1]*8-W;return Be(i,r,s,0),St(i,i,n),i}function nu(e,t,n,i,r){const s=$E(e,t,n,r),o=i(s);return o===void 0?void 0:o*Ee}function iu(e,t,n,i){Za(t,e,0,i);const r=n(i);return r===void 0?void 0:r*Ee}function eT(e,t,n){var i;return(i=dm(e,t,n))==null?void 0:i.elevation}function dm(e,t,n){var d,h,g,y;if(!e.tree)return;const i=(d=n==null?void 0:n.vertexStride)!=null?d:Kt.sinks.mesh2.stride,r=(h=n==null?void 0:n.heightOffset)!=null?h:4,s=(g=n==null?void 0:n.bucketSink)!=null?g:"mesh2",o=Be(ci,t[0],t[1],0),a=um(e,n),l=Bt(a),c=new Uint16Array(3),f=i/Uint16Array.BYTES_PER_ELEMENT;Dt(c,o,l);const u=sm(e.tree,c);for(const p of u){const v=(y=e.generated[0])==null?void 0:y.collectorOutput.data[p.bucketIndex];if(!v||v.sink!==s)continue;const A=v.generatedObjects[p.batchIndex],w=new Uint16Array(v.buffer,A.rangeStart,(A.rangeEnd-A.rangeStart)/Uint16Array.BYTES_PER_ELEMENT),S=new Float32Array(v.buffer,A.rangeStart+r,(A.rangeEnd-A.rangeStart)/Float32Array.BYTES_PER_ELEMENT-1),T=ds(w,S,p.posOffset),I=ds(w,S,p.posOffset+f),C=ds(w,S,p.posOffset+f*2),M=ru(T,I,C,c,ci);if(!M)continue;const B={elevation:T[2]*M[0]+I[2]*M[1]+C[2]*M[2]};return n!=null&&n.includeSurfaceTangents&&(B.surfaceTangents=pm(l,T,I,C,T[2]*Ee,I[2]*Ee,C[2]*Ee)),B}}function tT(e,t,n){var w,S,T,I,C,M,B;if(!e.tree)return;const i=(w=n==null?void 0:n.vertexStride)!=null?w:Kt.sinks.mesh2.stride,r=(S=n==null?void 0:n.heightOffset)!=null?S:4,s=(T=n==null?void 0:n.bucketSink)!=null?T:"mesh2",o=(I=n==null?void 0:n.includeAbsoluteZ)!=null?I:!0,a=(C=n==null?void 0:n.includeSurfaceTangents)!=null?C:!1,l=(M=n==null?void 0:n.tryToGetAbsZFirst)!=null?M:!1,c=o||a||l,f=Be(ci,t[0],t[1],0),u=um(e,n),d=Bt(u),h=new Uint16Array(3),g=i/Uint16Array.BYTES_PER_ELEMENT,y=i/Float32Array.BYTES_PER_ELEMENT;Dt(h,f,d);const p=D=>{var ge;const F=(ge=e.generated[0])==null?void 0:ge.collectorOutput.data[D.bucketIndex];if(!F||F.sink!==s)return;const z=F.generatedObjects[D.batchIndex],N=new Uint16Array(F.buffer,z.rangeStart,(z.rangeEnd-z.rangeStart)/Uint16Array.BYTES_PER_ELEMENT),H=new Float32Array(F.buffer,z.rangeStart+r,(z.rangeEnd-z.rangeStart)/Float32Array.BYTES_PER_ELEMENT-1),K=F.symbol==="mapMesh"&&F.sink==="fill",P=K?Xn.sinks.fill.unpackObjectAttributes(z.attributes).absZ:!0,b=ds(N,H,D.posOffset),E=ds(N,H,D.posOffset+g),x=ds(N,H,D.posOffset+g*2),L=ru(b,E,x,h,ci);if(!L)return;const O=L[0],R=L[1],G=L[2],Q=b[2]*O+E[2]*R+x[2]*G;if(!c)return{relativeZ:Q};const X=D.posOffset/(Float32Array.BYTES_PER_ELEMENT/Uint16Array.BYTES_PER_ELEMENT);let se,te,U;if(!l&&K&&(n==null?void 0:n.mapMeshBaseZ)!==void 0)se=n.mapMeshBaseZ,te=n.mapMeshBaseZ,U=n.mapMeshBaseZ;else if(P){const de=new Float32Array(F.buffer,z.rangeStart+us,(z.rangeEnd-z.rangeStart-us)/Float32Array.BYTES_PER_ELEMENT),he=K?new Uint8Array(F.buffer,z.rangeStart+Ha,z.rangeEnd-z.rangeStart-Ha):void 0,J=D.posOffset*Uint16Array.BYTES_PER_ELEMENT,j=(he==null?void 0:he[J])===1,Y=(he==null?void 0:he[J+i])===1,oe=(he==null?void 0:he[J+i*2])===1;se=j?n!=null&&n.getDemElevation?iu(b,d,n.getDemElevation,Xa):void 0:de[X],te=Y?n!=null&&n.getDemElevation?iu(E,d,n.getDemElevation,_t):void 0:de[X+y],U=oe?n!=null&&n.getDemElevation?iu(x,d,n.getDemElevation,Xi):void 0:de[X+y*2]}else if(n!=null&&n.getDemElevation){const de=new Int16Array(F.buffer,z.rangeStart+us,(z.rangeEnd-z.rangeStart-us)/Int16Array.BYTES_PER_ELEMENT);se=nu(de,D.posOffset,d,n.getDemElevation,Xa),te=nu(de,D.posOffset+g,d,n.getDemElevation,_t),U=nu(de,D.posOffset+g*2,d,n.getDemElevation,Xi)}if(se===void 0||te===void 0||U===void 0){if(!l)return;se=te=U=0}const ne=se*O+te*R+U*G,ee={relativeZ:Q};return(o||l)&&(ee.absoluteZ=ne),a&&(ee.surfaceTangents=pm(d,b,E,x,b[2]+se,E[2]+te,x[2]+U)),ee},v=(B=n==null?void 0:n.triangleCache)==null?void 0:B.triangle;if(v){const D=p(v);if(D)return D;n!=null&&n.triangleCache&&(n.triangleCache.triangle=void 0)}const A=sm(e.tree,h);for(const D of A){const F=p(D);if(F)return n!=null&&n.triangleCache&&(n.triangleCache.triangle=D),F}}function hm(e,t,n){if(ln(am,t,e),ln(lm,n,e),gr(hn,am,lm),Pn(hn)!==0&&(jt(hn,hn),hn[2]<0&&lf(hn,hn),Be(_t,1,0,0),af(_t,_t,hn,-hn[0]),Pn(_t)===0&&(Be(_t,0,1,0),af(_t,_t,hn,-hn[1])),Pn(_t)!==0))return jt(_t,_t),gr(Xi,hn,_t),jt(Xi,Xi),{tangent:[_t[0],_t[1],_t[2]],bitangent:[Xi[0],Xi[1],Xi[2]]}}function pm(e,t,n,i,r=t[2],s=n[2],o=i[2]){return Za(e,t,r,ci),Za(e,n,s,Ya),Za(e,i,o,Xa),hm(ci,Ya,Xa)}function Za(e,t,n,i){return Be(i,t[0],t[1],0),St(i,i,e),i[2]=n,i}function ru(e,t,n,i,r){const s=su(e,t,n);if(s===0){if(e[0]===t[0]&&t[0]===n[0]&&e[1]===t[1]&&t[1]===n[1])return e[0]===i[0]&&e[1]===i[1]?(r[0]=1,r[1]=0,r[2]=0,r):null;let f=null;if(ou(e,t,i)){const u=ja(e,t,i);f=mr(ci,e,t,u),r[0]=1-u,r[1]=u,r[2]=0}if(ou(t,n,i)){const u=ja(t,n,i),d=mr(Ya,t,n,u);(!f||d[2]>f[2])&&(r[0]=0,r[1]=1-u,r[2]=u,f||(f=ci),of(f,d))}if(ou(n,e,i)){const u=ja(n,e,i),d=mr(Ya,n,e,u);(!f||d[2]>f[2])&&(r[0]=u,r[1]=0,r[2]=1-u,f||(f=ci),of(f,d))}if(f)return r}const o=su(i,t,n)/s,a=su(i,n,e)/s,l=1-o-a,c=.01;return o<-c||a<-c||l<-c||o>1+c||a>1+c||l>1+c?null:(r[0]=o,r[1]=a,r[2]=l,r)}function su(e,t,n){return SE(cm,t[0]-e[0],n[0]-e[0],t[1]-e[1],n[1]-e[1]),EE(cm)}function ou(e,t,n){const i=(t[0]-e[0])*(n[1]-e[1])-(t[1]-e[1])*(n[0]-e[0]);return Math.abs(i)>1e-8?!1:(n[0]-e[0])*(n[0]-t[0])+(n[1]-e[1])*(n[1]-t[1])<=0}function ja(e,t,n){const i=ii(ZE,t,e),r=ii(jE,n,e);return Li(r,i)/rw(i)}function nT(e){if(e.byteLength===0)return{positions:new Uint16Array,heights:new Float32Array,indices:new Uint16Array,maxZ:0,minZ:0};const t=new Uint32Array(e.slice(0,4))[0]===777275726,{dataGroups:n,minZ:i,maxZ:r}=t?DE(e):RE(e),{positions:s,heights:o,indices:a}=n[0];return{positions:s,heights:o,indices:a,maxZ:r,minZ:i}}function au(e,t,n,i,r){const s=Wf(r);Fr(i.textureImage).forEach(o=>{if(!o.length)return;const a=n.byKey[Ca(o)];if(!a){console.error(`Not found raster set with texture ${o}`);return}const l=iT(i.textureSize),c=i.lengthUnits===Wi.Meters;l.forEach(f=>{let[u,d]=Array.isArray(f)?f:[f,f];c&&(u=u*uo(u,u),d=d*uo(d,d)),a.isSvg?e.atlasPacker.packSvg(a,[{w:u,h:d}],s):e.atlasPacker.packPng(a,[{w:u,h:d}],s),a.rasters.forEach(h=>e.atlasPacker.addRastersToLoad(t,h))})})}function iT(e){return Qt(e)?e.type==="step"?e.steps.map(t=>Array.isArray(t.value)||typeof t.value=="number"?t.value:t.value.type==="literal-array"?t.value.array:(console.warn("textureSize only supports shallow step expression"),[0])):e.type==="literal-array"?[si(e)]:(ke(`Unsupported texture size expression of type "${e.type}". Can't resovle.`),[0]):[e]}function lu(e,t){var g,y,p,v,A;const{tileAttrs:n,tileProps:i}=e,r=Number.isNaN(n[i.db_begin_nominal_height])?0:(g=n[i.db_begin_nominal_height])!=null?g:0,s=Number.isNaN(n[i.db_end_nominal_height])?0:(y=n[i.db_end_nominal_height])!=null?y:0,o=(p=n[i.objectLength])!=null?p:1,a=(v=n[i.componentDistanceStart])!=null?v:0,l=(A=n[i.componentDistanceEnd])!=null?A:0,c=Yr(r,s,a/o),f=Yr(r,s,l/o),u=e.tileInfo?fn(e.tileInfo,[0,0]):1,d=Array.from({length:t.x.length});if(c===f)return d.fill(c*Ee*u),d;const h=t.x.length;for(let w=0;w<h;w++)d[w]=Ee*u*Yr(c,f,ja([t.x[0],t.y[0]],[t.x[h-1],t.y[h-1]],[t.x[w],t.y[w]]));return d}const cu=e=>{for(let t=0;t<e.length;t++)if(e[t]!==0)return!0;return!1},yo=(e,t,n)=>!!e.globeEnabled&&n!==!0&&t!==void 0&&t.coords[2]<dr.globeMaxZoom,gm=(e,t,n)=>e&&yo(t,n),fi=e=>$(2,15)+e*vw,Zn=(e,t,n)=>{const[i,r,s]=Ub(e,[t,n]);return{x:fi(i),y:fi(r),z:fi(s)}};function hs(e){return e-32768}function ps(e){return e+32768}function mm(e){return Math.max(-32768,Math.min(32767,Math.round(e)))}const Cn=1,Fn=-1,Ln=[.5,.5],pn=[.5,.5],Oe=[.5,.5],gs=[.5,.5],fu=[0,0];let Jt,Me,_e,Re=0,$t=0,gt=0,Ct=0;const rT={x:0,y:0,z:0,xn2:0,yn2:0,xn1:0,yn1:0,patternedLine:!1,noTurn:!0,leftTurn:!1,sharpTurn:!1,reverseTurn:!1,extender:[.5,.5],faExtender:[.5,.5],saExtender:[.5,.5]},sT=1-1e-4,oT=0,vm=-.9;function aT(e,t,n,i,r,s,o,a){const l=rT;l.x=e,l.y=t,l.z=n,l.xn2=i,l.yn2=r,l.xn1=s,l.yn1=o,l.patternedLine=a;const c=i*s+r*o;return _e.globeMode?l.noTurn=!1:l.noTurn=c>sT,l.leftTurn=i*-o+r*s<0,l.sharpTurn=c<oT&&c>vm,l.reverseTurn=c<vm,l}function Qa(e,t,n,i,r,s,o,a,l,c,f,u,d=!1){var D,F,z,N,H,K,P;let h,g,y,p,v,A,w,S,T,I,C,M,B;if(i!==0)if(_e=f,Me=u,Jt=Me.indices,$t=Me.elements.offset,Re=0,gt=0,Ct=0,e[0],t[0],i===1)h=e[0],g=t[0],y=(D=n==null?void 0:n[0])!=null?D:0,B=0,ui(Jt,$t,0,2,1,1,2,3),Ue(Me,_e,0,h,g,y,1,-1,1,-1,B,!1,Fn),Ue(Me,_e,0,h,g,y,-1,-1,-1,-1,B,!1,Cn),Ue(Me,_e,0,h,g,y,1,1,1,1,B,!1,Fn),Ue(Me,_e,0,h,g,y,-1,1,-1,1,B,!1,Cn),Re=Re+4;else{switch(p=e[0],v=t[0],A=(F=n==null?void 0:n[0])!=null?F:0,w=e[1],S=t[1],T=(z=n==null?void 0:n[1])!=null?z:0,B=d?_e.cDist:0,r){case Te.TileCut:In(Ln,p,v,o,a),In(Oe,w,S,p,v),M=uu(w,S,T,Ln[0],Ln[1],Oe[0],Oe[1],d),M.noTurn?ym(p,v,A,Oe[0],Oe[1],B):qa(0,p,v,A,Ln[0],Ln[1],Oe[0],Oe[1],B,d);break;case Te.Butt:case Te.Round:In(Oe,w,S,p,v),ym(p,v,A,Oe[0],Oe[1],B),r===Te.Round&&qa(0,p,v,A,Oe[0],Oe[1],Oe[0],Oe[1],B,d);break;default:throw new Error("LoftedLine: unknown Ending Type")}const b=i-1;for(let L=1;L<b;L++){p=e[L-1],v=t[L-1],A=(N=n==null?void 0:n[L-1])!=null?N:0,w=e[L],S=t[L],T=(H=n==null?void 0:n[L])!=null?H:0,I=e[L+1],C=t[L+1];const O=w-p,R=S-v;B+=Math.sqrt(O*O+R*R)/ae,In(Ln,w,S,p,v),In(Oe,I,C,w,S),qa(L,w,S,T,Ln[0],Ln[1],Oe[0],Oe[1],B,d)}p=e[i-2],v=t[i-2],A=(K=n==null?void 0:n[i-2])!=null?K:0,w=e[b],S=t[b],T=(P=n==null?void 0:n[b])!=null?P:0;const E=w-p,x=S-v;switch(B+=Math.sqrt(E*E+x*x)/ae,s){case Te.TileCut:In(Ln,w,S,p,v),In(Oe,l,c,w,S),M=uu(w,S,T,Ln[0],Ln[1],Oe[0],Oe[1],d),M.noTurn?xm(b,w,S,T,Oe[0],Oe[1],B):wm(b,B,M);break;case Te.Butt:case Te.Round:In(Oe,w,S,p,v),xm(b,w,S,T,Oe[0],Oe[1],B),s===Te.Round&&qa(b,w,S,T,Oe[0],Oe[1],-Oe[0],-Oe[1],B,d);break;default:throw new Error("LoftedLine: unknown Ending Type")}}}function uu(e,t,n,i,r,s,o,a){const l=aT(e,t,n,i,r,s,o,a);if(!l.noTurn&&!l.reverseTurn){Lp(pn,i,r,s,o);const c=pn[0],f=pn[1];l.extender[0]=c,l.extender[1]=f,l.faExtender[0]=c-i*2,l.faExtender[1]=f-r*2,l.saExtender[0]=c-s*2,l.saExtender[1]=f-o*2}else l.extender[0]=0,l.extender[1]=0,l.faExtender[0]=0,l.faExtender[1]=0,l.saExtender[0]=0,l.saExtender[1]=0;return l}function du(e,t,n,i,r,s,o,a,l,c){Lp(pn,r,s,o,a),r*-a+s*o<0?Ue(Me,_e,e,t,n,i,-pn[0],-pn[1],-pn[0],-pn[1],l,!1,c):Ue(Me,_e,e,t,n,i,pn[0],pn[1],pn[0],pn[1],l,!1,c),Re++}function qa(e,t,n,i,r,s,o,a,l,c){const f=uu(t,n,i,r,s,o,a,c);wm(e,l,f),lT(e,l,f),cT(e,l,f)}function ym(e,t,n,i,r,s){Ue(Me,_e,0,e,t,n,-i,-r,-i,-r,s,!1,Cn),Ue(Me,_e,0,e,t,n,i,r,i,r,s,!1,Fn),Re=Re+2,gt=1,Ct=0}function xm(e,t,n,i,r,s,o){const a=Re+1,l=Re;Ue(Me,_e,e,t,n,i,-r,-s,-r,-s,o,!1,Cn),Ue(Me,_e,e,t,n,i,r,s,r,s,o,!1,Fn),Re=Re+2,ui(Jt,$t,Ct,l,gt,gt,l,a),gt=a,Ct=l}function lT(e,t,n){if(n.noTurn||n.patternedLine&&n.sharpTurn)return;const i=n.sharpTurn?2:1;let r,s;n.reverseTurn||n.patternedLine&&n.sharpTurn?(r=Ct,s=gt):n.leftTurn?(r=gt,s=Re+i):(r=Re+i,s=Ct);const o=Re;if(hu(Jt,$t,gt,Ct,o),n.sharpTurn){const l=Re+1;n.leftTurn?ui(Jt,$t,o,l,r,r,l,s):ui(Jt,$t,o,s,l,l,s,r)}else n.leftTurn,hu(Jt,$t,o,s,r);const a=n.leftTurn?Cn:Fn;n.sharpTurn?(n.leftTurn?In(gs,n.xn2,n.yn2,n.xn1,n.yn1):In(gs,n.xn1,n.yn1,n.xn2,n.yn2),du(e,n.x,n.y,n.z,n.xn2,n.yn2,gs[0],gs[1],t,a),du(e,n.x,n.y,n.z,gs[0],gs[1],n.xn1,n.yn1,t,a)):du(e,n.x,n.y,n.z,n.xn2,n.yn2,n.xn1,n.yn1,t,a),n.reverseTurn||(n.leftTurn?Ue(Me,_e,e,n.x,n.y,n.z,-n.xn1,-n.yn1,-n.xn1,-n.yn1,t,!1,a):Ue(Me,_e,e,n.x,n.y,n.z,n.xn1,n.yn1,n.xn1,n.yn1,t,!1,a),Re++),Ct=s,gt=r}function wm(e,t,n){if(n.noTurn)return;const i=Re+1,r=Re;if(n.reverseTurn||n.patternedLine&&n.sharpTurn?(Ue(Me,_e,e,n.x,n.y,n.z,-n.xn2,-n.yn2,-n.xn2,-n.yn2,t,!1,Cn),Ue(Me,_e,e,n.x,n.y,n.z,n.xn2,n.yn2,n.xn2,n.yn2,t,!1,Fn)):n.leftTurn?(Ue(Me,_e,e,n.x,n.y,n.z,-n.xn2,-n.yn2,n.faExtender[0],n.faExtender[1],t,!0,Cn),Ue(Me,_e,e,n.x,n.y,n.z,n.xn2,n.yn2,n.extender[0],n.extender[1],t,!0,Fn)):(Ue(Me,_e,e,n.x,n.y,n.z,-n.xn2,-n.yn2,-n.extender[0],-n.extender[1],t,!0,Cn),Ue(Me,_e,e,n.x,n.y,n.z,n.xn2,n.yn2,-n.faExtender[0],-n.faExtender[1],t,!0,Fn)),Re=Re+2,ui(Jt,$t,Ct,r,gt,gt,r,i),Ct=r,gt=i,!n.patternedLine&&!n.reverseTurn){const s=Re+1,o=Re;n.leftTurn?(Ue(Me,_e,e,n.x,n.y,n.z,-n.xn2,-n.yn2,-n.xn2,-n.yn2,t,!1,0),Ue(Me,_e,e,n.x,n.y,n.z,0,0,0,0,t,!1,0),ui(Jt,$t,i,r,s,s,r,o)):(Ue(Me,_e,e,n.x,n.y,n.z,0,0,0,0,t,!1,0),Ue(Me,_e,e,n.x,n.y,n.z,n.xn2,n.yn2,n.xn2,n.yn2,t,!1,0),ui(Jt,$t,r,o,i,i,o,s)),Re=Re+2,Ct=o,gt=s}}function cT(e,t,n){if(n.noTurn||n.reverseTurn)return;const i=Re+1,r=Re;if(n.patternedLine&&n.sharpTurn){Ue(Me,_e,e,n.x,n.y,n.z,-n.xn1,-n.yn1,-n.xn1,-n.yn1,t,!1,Cn),Ue(Me,_e,e,n.x,n.y,n.z,n.xn1,n.yn1,n.xn1,n.yn1,t,!1,Fn),Re=Re+2,Ct=r,gt=i;return}else n.leftTurn?(Ue(Me,_e,e,n.x,n.y,n.z,-n.xn1,-n.yn1,n.saExtender[0],n.saExtender[1],t,!1,Cn),Ue(Me,_e,e,n.x,n.y,n.z,n.xn1,n.yn1,n.extender[0],n.extender[1],t,!1,Fn)):(Ue(Me,_e,e,n.x,n.y,n.z,-n.xn1,-n.yn1,-n.extender[0],-n.extender[1],t,!1,Cn),Ue(Me,_e,e,n.x,n.y,n.z,n.xn1,n.yn1,-n.saExtender[0],-n.saExtender[1],t,!1,Fn));Re=Re+2,n.leftTurn?ui(Jt,$t,Ct,r,gt,gt,r,i):ui(Jt,$t,gt,Ct,i,i,Ct,r),Ct=r,gt=i}function Ue(e,t,n,i,r,s,o,a,l,c,f,u,d){const h=e.elements.offset*t.offsetMultiplier,g=h>>1,y=h<<1;if(t.globeMode&&t.tileInfo){const{x:p,y:v,z:A}=Zn(t.tileInfo,i,r);e.views.position[h]=p,e.views.position[h+1]=v,e.views.position[h+2]=A}else e.views.position[h]=W+i,e.views.position[h+1]=W+r;if(e.views.extender[h]=Math.floor(l*Ke*127+.5),e.views.extender[h+1]=Math.floor(c*Ke*127+.5),t.type===Sr.Patterned){const p=e,v=1e-5;p.views.texture[g]=(v+f)*Math.sign(d)}else if(t.type===Sr.Striped){const p=e;p.views.texExtender[y]=at(o*Ke),p.views.texExtender[y+1]=at(a*Ke),p.views.vertexDistance[g]=f,p.views.objectLength[g]=t.oLen,"componentDistance"in e.views&&(e.views.componentDistance[g]=t.cDist)}else if(t.type===Sr.Entrance){const p=e,{px:v,py:A,count:w}=t,S=n===0,T=n===w-1,I=S?n:n-1,C=S?n+1:n;Hn(fu,v[I],A[I],v[C],A[C]),p.views.direction[h]=Math.round(fu[0]*127),p.views.direction[h+1]=Math.round(fu[1]*127),p.views.type[g]=T?so.LineEnding:so.Line,p.views.texExtender[y]=at(o*(u||T?-1:1)*Ke),p.views.texExtender[y+1]=at(a*(u||T?-1:1)*Ke),p.views.vertexDistance[g]=f,p.views.objectLength[g]=t.oLen}e.views.localID[g]=t.localID,"height"in e.views&&(e.views.height[g]=s),e.elements.offset++}function hu(e,t,n,i,r){const s=e.buffer,o=e.offset;s[o]=t+n,s[o+1]=t+i,s[o+2]=t+r,e.offset=o+3}function ui(e,t,n,i,r,s,o,a){const l=e.buffer,c=e.offset;l[c]=t+n,l[c+1]=t+i,l[c+2]=t+r,l[c+3]=t+s,l[c+4]=t+o,l[c+5]=t+a,e.offset=c+6}const fT=8,Rt={symbol:"line",sinks:{solid:{stride:16,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.extender=new Int8Array(t,8),e.views.normal=new Int8Array(t,10),e.views.localID=new Uint32Array(t,12)},packObjectAttributes(e,t,n,i,r,s){return Ze([e,t.innerId,n,i,r],t,s)},unpackObjectAttributes(e){return{styleId:e[0],layerId:e[1],tiers:e[2],hiddenByFloorComplexId:e[3],floorId:e[4],tileData:e.slice(5)}}},solid3d:{stride:20,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.extender=new Int8Array(t,4),e.views.normal=new Int8Array(t,6),e.views.height=new Float32Array(t,8),e.views.absZ=new Float32Array(t,12),e.views.localID=new Uint32Array(t,16)},packObjectAttributes(e,t,n,i){return Ze([e,t.innerId,n],t,i)},unpackObjectAttributes(e){return{styleId:e[0],layerId:e[1],absZ:e[2],tileData:e.slice(3)}}},patterned:{stride:16,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.extender=new Int16Array(t,4),e.views.texture=new Float32Array(t,8),e.views.localID=new Uint32Array(t,12)},packObjectAttributes(e,t,n,i,r){return Ze([e,t.innerId,n,i],t,r)},unpackObjectAttributes(e){return{styleId:e[0],layerId:e[1],tiers:e[2],hiddenByFloorComplexId:e[3],tileData:e.slice(3)}}},patterned3d:{stride:20,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.extender=new Int16Array(t,4),e.views.texture=new Float32Array(t,8),e.views.height=new Float32Array(t,12),e.views.localID=new Uint32Array(t,16)},packObjectAttributes(e,t,n){return Ze([e,t.innerId],t,n)},unpackObjectAttributes(e){return{styleId:e[0],layerId:e[1],tileData:e.slice(2)}}}},generate(e,t,n,i,r,s){var w,S;const o=Fa(k(n.style.geometryModifier,i),r,s,i);if(o===null)return;const{tileAttrs:a,tileProps:l}=i;let c=n.style.mode==="3d";const f=c?(w=o.z)!=null?w:lu(i,o):void 0;c&&(!f||!cu(f))&&(c=!1);const u=e.idIndexer.getIndex(i,t,n),d=k(n.ignoreTier,i)?null:i.tileAttrs[l.db_tiers],h=a[l.db_hidden_by_metro_building_id]||"",g=c?e.getBucket(n.type,"solid3d",Rt.sinks.solid3d.packObjectAttributes(t,n,!!o.abs_z,i),Rt.sinks.solid3d.binder):e.getBucket(n.type,"solid",Rt.sinks.solid.packObjectAttributes(t,n,d,h,(S=a[l.floorId])!=null?S:"",i),Rt.sinks.solid.binder),y=Number.isNaN(a[l.beginningIsCut])?!1:a[l.beginningIsCut]!==0,p=Number.isNaN(a[l.endingIsCut])?!1:a[l.endingIsCut]!==0,v=Mt(n.style.startCap,i),A=Mt(n.style.endCap,i);!c&&(yo(i.styleState,i.tileInfo,i.globeOff)||i.ecefDataState===kl.Present)&&i.tileInfo!==void 0?dT(g,o.x,o.y,i.tileInfo,y?Te.TileCut:vs(v),p?Te.TileCut:vs(A),u):_f(g,o.x,o.y,f,o.abs_z,o.x.length,y?Te.TileCut:vs(v),p?Te.TileCut:vs(A),u)},generatePatterned(e,t,n,i,r,s){var S,T;const o=Fa(k(n.style.geometryModifier,i),r,s,i);if(o===null)return;const{tileAttrs:a,tileProps:l}=i,c=k(n.ignoreTier,i)?null:i.tileAttrs[l.db_tiers],f=(S=a[l.db_hidden_by_metro_building_id])!=null?S:"";let u=n.style.mode==="3d";const d=u?(T=o.z)!=null?T:lu(i,o):void 0;u&&(!d||!cu(d))&&(u=!1);const h=u?e.getBucket("line","patterned3d",Rt.sinks.patterned3d.packObjectAttributes(t,n,i),Rt.sinks.patterned3d.binder):e.getBucket("line","patterned",Rt.sinks.patterned.packObjectAttributes(t,n,c,f,i),Rt.sinks.patterned.binder),g=e.idIndexer.getIndex(i,t,n),y=uT(a[l.componentDistanceStart]/ae,a[l.componentDistanceEnd]/ae,a[l.objectLength]/ae,g,u?Rt.sinks.patterned3d.stride/2:Rt.sinks.patterned.stride/2),p=Number.isNaN(a[l.beginningIsCut])?!1:a[l.beginningIsCut]!==0,v=Number.isNaN(a[l.endingIsCut])?!1:a[l.endingIsCut]!==0,A=Mt(n.style.startCap,i),w=Mt(n.style.endCap,i);Qa(o.x,o.y,d,o.x.length,p?Te.TileCut:vs(A),v?Te.TileCut:vs(w),a[l.previousPointX],a[l.previousPointY],a[l.nextPointX],a[l.nextPointY],y,h,!0)}},ms={type:Sr.Patterned,cDist:0,sLen:0,oLen:0,localID:0,offsetMultiplier:8,px:[],py:[],count:0};function uT(e,t,n,i,r){return ms.cDist=e,ms.sLen=t-e,ms.oLen=n,ms.localID=i,ms.offsetMultiplier=r,ms}function vs(e){switch(e){case"round":return Te.Round;case"tilecut":return Te.TileCut;default:return Te.Butt}}function dT(e,t,n,i,r,s,o){if(t.length<2)return;const a=[];for(let u=0;u<t.length;u++)a.push([hs(t[u]),hs(n[u])]);const l=Bf(a,fT,!1),c=new Uint16Array(l.length),f=new Uint16Array(l.length);for(let u=0;u<l.length;u++)c[u]=ps(l[u][0]),f[u]=ps(l[u][1]);_f(e,c,f,void 0,void 0,c.length,r,s,o,void 0,void 0,(u,d)=>Zn(i,u,d))}const xo={symbol:"shiftedLine",sinks:{solid:{stride:20,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.extender=new Int8Array(t,8),e.views.normal=new Int8Array(t,10),e.views.shift=new Float32Array(t,12)},packObjectAttributes(e,t,n,i){return Ze([e,t.innerId,n],t,i)},unpackObjectAttributes(e){return{styleId:e[0],layerId:e[1],tiers:e[2],tileData:e.slice(3)}}}},generate(e,t,n,i,r){const{tileAttrs:s,tileProps:o,styleState:a,tileInfo:l}=i,c=Number.isNaN(s[o.beginningIsCut])?!1:s[o.beginningIsCut]!==0,f=Number.isNaN(s[o.endingIsCut])?!1:s[o.endingIsCut]!==0,u=k(n.ignoreTier,i)?null:i.tileAttrs[o.db_tiers],d=e.getBucket(n.type,"solid",xo.sinks.solid.packObjectAttributes(t,n,u,i),xo.sinks.solid.binder),h=yo(a,l,i.globeOff)?(g,y)=>Zn(l,g,y):void 0;_f(d,r.x,r.y,void 0,void 0,r.x.length,c?Te.TileCut:Te.Round,f?Te.TileCut:Te.Round,0,r.normal_x,r.normal_y,h)}};function mt(e,t){return e===0?0:Math.min(e*2-1,(t-e)*2)}function Ka(e,t,n,i,r,s,o=0,a,l,c,f,u,d=!1){let h=e.elements.offset;for(let g=0;g<t;g++){const y=mt(g,t),p=g===t-1;if((!r||r[y]!==1)&&(r||p))continue;const v=n[y],A=i[y],w=(g+1)%t,S=mt(w,t),T=n[S],I=i[S];if(f){const C=Math.hypot(T-v,I-A)*f.tileSizeMapPoints/ae;if(C<f.wallPaddingMapPoints[1]+f.wallPaddingMapPoints[3]+f.textureWidthMapPoints)continue;switch(f.config.horizontal.mode){case"repeat-with-stretch":{const M=f.config.horizontal.slicesCount,B=(C-(f.wallPaddingMapPoints[1]+f.wallPaddingMapPoints[3]))/f.textureWidthMapPoints,D=Math.round(B*M);if(D<f.config.horizontal.minSliceRepeats)continue;const z=D/M/B;if(f.config.horizontal.maxResizeFactor&&z>f.config.horizontal.maxResizeFactor||f.config.horizontal.minResizeFactor&&z<f.config.horizontal.minResizeFactor)continue;break}case"repeat-with-max-interval":break;default:continue}switch(f.config.vertical.mode){case"repeat-with-stretch":{const M=f.config.vertical.slicesCount,B=(s-(f.wallPaddingMapPoints[0]+f.wallPaddingMapPoints[2]))/f.textureHeightMapPoints,D=Math.round(B*M);if(D<f.config.vertical.minSliceRepeats)continue;const z=D/M/B;if(z>f.config.vertical.maxResizeFactor||z<f.config.vertical.minResizeFactor)continue;break}case"repeat-with-max-interval":break;case"stripe-top":break;default:continue}Em(e,h),Am(e,h,v,A,T,I,s,o),pT(e,h,s-o,C)}else Em(e,h,d),Am(e,h,v,A,T,I,s,o);c?bm(e,h,c[0],c[1],c[0],c[1]):bm(e,h,v,A,T,I),a!==void 0&&"localID"in e.views&&e.views.localID!==void 0&&Sm(e.views.localID,h,a,e.elements.stride),l!==void 0&&"labelingTextureID"in e.views&&e.views.labelingTextureID!==void 0&&Sm(e.views.labelingTextureID,h,l,e.elements.stride),u!==void 0&&hT(e.views.innerColor,h,u,e.elements.stride),h=h+4}e.elements.offset=h}function hT(e,t,n,i){const r=i/e.BYTES_PER_ELEMENT;t=t*r,e[t]=n,t+=r,e[t]=n,t+=r,e[t]=n,t+=r,e[t]=n}function Am(e,t,n,i,r,s,o,a){const l=e.views.position,c=e.views.height,f=e.elements.stride/l.BYTES_PER_ELEMENT,u="elevation"in e.views?e.views.elevation:void 0,d=u?e.elements.stride/u.BYTES_PER_ELEMENT:0;let h=t*d,g=t*f;const y=o<0,p=Wt(Math.abs(o)),v=(y?-p:p)/He,A=Wt(a)/He;l[g]=W+n,l[g+1]=W+i,c[g>>1]=y?v:A,u&&(u[h]=a/o),g+=f,l[g]=W+n,l[g+1]=W+i,c[g>>1]=y?A:v,u&&(h+=d,u[h]=1),g+=f,l[g]=W+r,l[g+1]=W+s,c[g>>1]=y?v:A,u&&(h+=d,u[h]=a/o),g+=f,l[g]=W+r,l[g+1]=W+s,c[g>>1]=y?A:v,u&&(h+=d,u[h]=1)}function pT(e,t,n,i){const r=e.views.fillIndices,s=e.views.fillRect,o=e.elements.stride/r.BYTES_PER_ELEMENT,a=e.elements.stride/s.BYTES_PER_ELEMENT;let l=t*o,c=t*a;r[l]=0,r[l+1]=1,s[c]=i,s[c+1]=n,l+=o,c+=a,r[l]=0,r[l+1]=0,s[c]=i,s[c+1]=n,l+=o,c+=a,r[l]=1,r[l+1]=1,s[c]=i,s[c+1]=n,l+=o,c+=a,r[l]=1,r[l+1]=0,s[c]=i,s[c+1]=n}function bm(e,t,n,i,r,s){const o=e.views.demPosition,a=e.elements.stride/o.BYTES_PER_ELEMENT;t=t*a,n=(n+W)/8,i=(i+W)/8,r=(r+W)/8,s=(s+W)/8,o[t]=n,o[t+1]=i,t+=a,o[t]=n,o[t+1]=i,t+=a,o[t]=r,o[t+1]=s,t+=a,o[t]=r,o[t+1]=s}function Sm(e,t,n,i){const r=i/e.BYTES_PER_ELEMENT;t=t*r,e[t]=n,e[t+=r]=n,e[t+=r]=n,e[t+=r]=n}function Em(e,t,n=!1){const i=e.indices.buffer;let r=e.indices.offset;i[r++]=t,i[r++]=t+(n?1:3),i[r++]=t+(n?3:1),i[r++]=t,i[r++]=t+(n?3:2),i[r++]=t+(n?2:3),e.indices.offset=r}const di=[.5,.5],hi=[.5,.5];function pu(e,t,n,i,r,s){let o=e.elements.offset;const a=mt(t-1,t);let l=n[a],c=i[a],f=r?r[a]:0;const u=o;for(let d=0;d<t;d++){const h=mt(d,t),g=d===t-1,y=n[h],p=i[h],v=r?r[h]:g?0:1;f!==0&&(Hn(hi,l,c,y,p),Pm(e,o,v,g?u:o+4),mT(e,o,l,c,y,p),s?Tm(e,o,s[0],s[1],s[0],s[1]):Tm(e,o,l,c,y,p),mf(hi),vT(e,o,hi),yT(e,o,hi),o=o+4),l=y,c=p,f=v}e.elements.offset=o}function gu(e,t,n,i,r,s,o,a){let l=e.elements.offset;const c=mt(t-2,t),f=mt(t-1,t);let u=n[f],d=i[f],h=r?r[c]:1,g=r?r[f]:0;In(di,n[c],i[c],u,d);let y=di[0],p=di[1];for(let v=0;v<t;v++){const A=mt(v,t),w=v===t-1,S=n[A],T=i[A],I=r?r[A]:w?0:1;Hn(hi,u,d,S,T);const C=hi[1],M=-hi[0];h!==0&&(g===0?(di[0]=y,di[1]=p):gT(di,y,p,C,M),AA(hi,y,p,di[0],di[1]),Pm(e,l,0,0),xT(e,l,u,d,s,o!=null?o:[u,d]),wT(e,l,mf(di),mf(hi)),AT(e,l),l=l+4),u=S,d=T,h=g,g=I,y=C,p=M}e.elements.offset=l}function gT(e,t,n,i,r){let s,o,a;t*i+n*r>0?(s=t+i,o=n+r,a=1/Math.sqrt(s*s+o*o),e[0]=s*a,e[1]=o*a):(s=r-n,o=t-i,s!==0&&o!==0?(a=1/Math.sqrt(s*s+o*o),e[0]=s*a,e[1]=o*a):(e[0]=0,e[1]=0))}function Tm(e,t,n,i,r,s){const o=e.views.demPosition,a=e.elements.stride/o.BYTES_PER_ELEMENT;t=t*a,n=(n+W)/8,i=(i+W)/8,r=(r+W)/8,s=(s+W)/8,o[t]=n,o[t+1]=i,t+=a,o[t]=n,o[t+1]=i,t+=a,o[t]=r,o[t+1]=s,t+=a,o[t]=r,o[t+1]=s}function mT(e,t,n,i,r,s){const{position:o,distance:a,height:l}=e.views,c=e.elements.stride/o.BYTES_PER_ELEMENT;t=t*c,o[t]=W+n,o[t+1]=W+i,l[t>>1]=0,a[t<<1]=0,t+=c,o[t]=W+n,o[t+1]=W+i,l[t>>1]=0,a[t<<1]=-1,t+=c,o[t]=W+r,o[t+1]=W+s,l[t>>1]=0,a[t<<1]=-1,t+=c,o[t]=W+r,o[t+1]=W+s,l[t>>1]=0,a[t<<1]=0}function vT(e,t,n){const i=e.elements.stride/e.views.normals.BYTES_PER_ELEMENT;t=t*i;for(let r=0;r<4;r++)e.views.normals[t]=n[0],e.views.normals[t+1]=n[1],e.views.normals[t+2]=0,e.views.normals[t+3]=0,t+=i}function yT(e,t,n){const i=e.elements.stride/e.views.direction.BYTES_PER_ELEMENT;t=t*i;for(let r=0;r<4;r++)e.views.direction[t]=n[0],e.views.direction[t+1]=n[1],e.views.direction[t+2]=0,t+=i}function xT(e,t,n,i,r,s){const o=e.elements.stride/e.views.position.BYTES_PER_ELEMENT;t=t*o,e.views.position[t]=W+n,e.views.position[t+1]=W+i,e.views.height[t>>1]=0,e.views.distance[t<<1]=1,e.views.demPosition[t]=(W+s[0])/8,e.views.demPosition[t+1]=(W+s[1])/8,t+=o,e.views.position[t]=W+n,e.views.position[t+1]=W+i,e.views.height[t>>1]=0,e.views.distance[t<<1]=-1,e.views.demPosition[t]=(W+s[0])/8,e.views.demPosition[t+1]=(W+s[1])/8,t+=o,e.views.position[t]=W+n,e.views.position[t+1]=W+i,e.views.height[t>>1]=Wt(r)/He,e.views.distance[t<<1]=-1,e.views.demPosition[t]=(W+s[0])/8,e.views.demPosition[t+1]=(W+s[1])/8,t+=o,e.views.position[t]=W+n,e.views.position[t+1]=W+i,e.views.height[t>>1]=Wt(r)/He,e.views.distance[t<<1]=1,e.views.demPosition[t]=(W+s[0])/8,e.views.demPosition[t+1]=(W+s[1])/8}function wT(e,t,n,i){const r=e.elements.stride/e.views.normals.BYTES_PER_ELEMENT;t=t*r;for(let s=0;s<4;s++)e.views.normals[t]=n[0],e.views.normals[t+1]=n[1],e.views.normals[t+2]=i[0],e.views.normals[t+3]=i[1],t+=r}function AT(e,t){const n=e.elements.stride/e.views.direction.BYTES_PER_ELEMENT;t=t*n;for(let i=0;i<4;i++)e.views.direction[t]=0,e.views.direction[t+2]=127,t+=n}function Pm(e,t,n,i){const r=e.indices.buffer;let s=e.indices.offset;r[s++]=t,r[s++]=t+1,r[s++]=t+3,r[s++]=t+3,r[s++]=t+1,r[s++]=t+2,n!==0&&(r[s++]=t+2,r[s++]=i+1,r[s++]=i+0),e.indices.offset=s}const wo=nt(),Ao=nt(),pi=nt();function ys(e,t,n,i,r,s,o,a){Be(wo,t,n,i),Be(Ao,r,s,o),ln(pi,Ao,wo),zw(Ao,wo)||(jt(pi,pi),Ri(pi,pi,127)),bT(e,0,1,3,3,1,2);const l=a==null?void 0:a.absZCurr,c=a==null?void 0:a.absZNext,f=a==null?void 0:a.isPivotCurr,u=a==null?void 0:a.isPivotNext;Ja(e,wo,pi,1,a,l,f),Ja(e,wo,pi,-1,a,l,f),Ja(e,Ao,pi,-1,a,c,u),Ja(e,Ao,pi,1,a,c,u)}function Ja(e,t,n,i,r,s,o){const a=r==null?void 0:r.demPosition,l=r==null?void 0:r.isModel,c=r==null?void 0:r.isMesh,f=r==null?void 0:r.isEcef,u=r==null?void 0:r.innerColor,d=e.elements.offset*e.elements.stride,h=d/e.views.position.BYTES_PER_ELEMENT;if(f?(e.views.position[h]=t[0],e.views.position[h+1]=t[1],e.views.position[h+2]=t[2]):(e.views.position[h]=l?t[0]:W+t[0],e.views.position[h+1]=l?t[1]:W+t[1]),"height"in e.views){const g=d/e.views.height.BYTES_PER_ELEMENT;e.views.height[g]=(l?t[2]:c?t[2]*io:Wt(t[2]))/He}if(e.views.directionDistance[d]=n[0],e.views.directionDistance[d+1]=n[1],e.views.directionDistance[d+2]=n[2],e.views.directionDistance[d+3]=i,"demPosition"in e.views){const g=d/e.views.demPosition.BYTES_PER_ELEMENT,y=a!=null?a:t;e.views.demPosition[g]=(l?y[0]:W+y[0])/8,e.views.demPosition[g+1]=(l?y[1]:W+y[1])/8}"absZ"in e.views&&s!==void 0&&(e.views.absZ[d/e.views.absZ.BYTES_PER_ELEMENT]=s),"isPivot"in e.views&&(e.views.isPivot[d/e.views.isPivot.BYTES_PER_ELEMENT]=o!=null?o:0),"innerColor"in e.views&&u!==void 0&&(e.views.innerColor[d/e.views.innerColor.BYTES_PER_ELEMENT]=u),e.elements.offset++}function bT(e,t,n,i,r,s,o){const a=e.indices.buffer,l=e.indices.offset,c=e.elements.offset;a[l]=c+t,a[l+1]=c+n,a[l+2]=c+i,a[l+3]=c+r,a[l+4]=c+s,a[l+5]=c+o,e.indices.offset=l+6}const ST=/\.png$/i;function ET(e){return!!e&&e.type==="polygon"}function TT(e){return!!e&&e.type==="line"}function PT(e){return!(e!=null&&e.url.match(ST))}function Im(e,t){return Hr(k(e.style.sideColor,t),k(e.style.sideStrokeColor,t))}const Ft=4294967295,Bn=4294967040,IT=Bn-1,mu={},MT=1e6,Mm=["main","parser","labeling","models"];let vu=0;Mm.forEach(e=>{const t=vu+Math.floor(IT/Mm.length);mu[e]={min:vu,max:t-MT},vu=t});class _T{constructor(t){this.ids=[],this.orphanIds=[],this.phases=[],this.sublayers=[],this.styleIds=[],this.layerIds=[],this.instanceIds=[],this.objectClasses=[],this.floorIds=[],this.center=[],this.strings={},this.forceInteractivity=!1,this.minIdentifyIndex=mu[t].min,this.maxIdentifyIndex=mu[t].max,this.index=this.minIdentifyIndex}getIndex(t,n,i,r={}){const{id:s,tileProps:o,tileAttrs:a}=t,l=i.interactive,c=r.ignoreHover?!1:a[o.hovered],f=c&&i.type!=="polygon3d"||i.type==="embankment";return(!!s||this.forceInteractivity)&&l&&!c&&!f?this.getIndexInternal(V({id:s!=null?s:"",styleId:n,layer:i,sublayer:a[o.db_sublayer]},r)):Ft}setForceInteractivity(t){this.forceInteractivity=t}getIndexInternal(t){var s,o,a,l,c,f,u;const n=this.index+this.ids.length;this.ids.push(t.id),this.floorIds.push((s=t.floorId)!=null?s:""),this.phases.push(t.layer.renderIndex),this.sublayers.push((l=(a=(o=t.metatile)==null?void 0:o.dictionaries.db_sublayer)==null?void 0:a[t.sublayer])!=null?l:NaN),this.styleIds.push(t.styleId),this.layerIds.push(t.layer.innerId),this.instanceIds.push((c=t.instanceId)!=null?c:0);const{center:i,objectClass:r}=t;if(i?this.center.push(Math.round(i[0]),Math.round(i[1])):this.center.push(Bc,Bc),typeof r=="string"){const d=(u=(f=t.metatile)==null?void 0:f.dictionaries.db_object_class)==null?void 0:u[r];d?this.objectClasses.push(d):(this.objectClasses.push(0),this.strings[n]={objectClass:r})}else this.objectClasses.push(Ft);return n}addOrphanId(t){this.orphanIds.push(t)}getIndexerStats(){return{ids:this.ids.length,orphanIds:this.orphanIds.length,floorIds:this.floorIds.length,phases:this.phases.length,sublayers:this.sublayers.length,styleIds:this.styleIds.length,layerIds:this.layerIds.length,instanceIds:this.instanceIds.length,objectClasses:this.objectClasses.length,strings:Object.keys(this.strings).length,center:this.center.length}}getPacked(){const t=this.ids,n=this.orphanIds,i=this.floorIds,r=new Float32Array(this.phases).buffer,s=new Uint32Array(this.sublayers).buffer,o=new Uint16Array(this.styleIds).buffer,a=new Uint32Array(this.layerIds).buffer,l=new Uint8Array(this.instanceIds).buffer,c=new Uint32Array(this.objectClasses).buffer,f=new Int32Array(this.center).buffer,u=this.index,d=this.index+this.ids.length-1;this.index=this.index+this.ids.length,this.index>this.maxIdentifyIndex&&(this.index=this.minIdentifyIndex);const h=this.strings;return this.ids=[],this.orphanIds=[],this.floorIds=[],this.phases=[],this.sublayers=[],this.styleIds=[],this.layerIds=[],this.instanceIds=[],this.objectClasses=[],this.strings={},this.center=[],{idBuffer:t,orphanIds:n,floorIdBuffer:i,startIndex:u,endIndex:d,phaseBuffer:r,sublayerBuffer:s,styleIdBuffer:o,layerIdBuffer:a,instanceIdBuffer:l,objectClassBuffer:c,centerBuffer:f,strings:h}}}var le=(e=>(e[e.side=0]="side",e[e.top=1]="top",e[e.bottom=2]="bottom",e))(le||{});const bo=[0,0,0],So=[0,0,0],Eo=[0,0,0],$a=[0,0,0],_m=(e,t,n,i,r)=>Ze([e,t.innerId,n,i],t,r),Cm=(e,t,n,i,r,s)=>Ze([e,t.innerId,n,i,r],t,s),Fm=e=>({styleId:e[0],layerId:e[1],side:e[2],absZ:e[3],tileData:e.slice(4)}),Lm=e=>({styleId:e[0],layerId:e[1],absZ:e[2],floorId:e[3],isHole:e[4],tileData:e.slice(5)}),re={symbol:"mesh",sinks:{fill:{stride:32,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.height=new Float32Array(t,4),e.views.normal=new Int8Array(t,8),e.views.gradient=new Int8Array(t,11),e.views.localID=new Uint32Array(t,12),e.views.demPosition=new Int16Array(t,16),e.views.absZ=new Float32Array(t,16),e.views.isPivot=new Uint8Array(t,20),e.views.labelingTextureID=new Uint32Array(t,24),e.views.innerColor=new Uint32Array(t,28)},packObjectAttributes:_m,unpackObjectAttributes:Fm},inverse:{stride:20,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.height=new Float32Array(t,4),e.views.demPosition=new Int16Array(t,8),e.views.absZ=new Float32Array(t,8),e.views.isPivot=new Uint8Array(t,12),e.views.labelingTextureID=new Uint32Array(t,16)},packObjectAttributes:Cm,unpackObjectAttributes:Lm},depthClear:{stride:16,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.height=new Float32Array(t,4),e.views.demPosition=new Int16Array(t,8),e.views.absZ=new Float32Array(t,8),e.views.isPivot=new Uint8Array(t,12)},packObjectAttributes:Cm,unpackObjectAttributes:Lm},stroke:{stride:20,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.height=new Float32Array(t,4),e.views.directionDistance=new Int8Array(t,8),e.views.demPosition=new Int16Array(t,12),e.views.absZ=new Float32Array(t,12),e.views.isPivot=new Uint8Array(t,16)},packObjectAttributes:_m,unpackObjectAttributes:Fm}},generate(e){var H,K,P,b;const{collector:t,styleId:n,layer:i,side:r,ctx:s,vertices:o,tileInfo:a,dpi:l,rasterSets:c,demPosition:f,sink:u="fill",reverseTriangles:d=!1,innerColor:h,floorId:g,isHole:y=!1,tier:p}=e,v=o.x,A=o.y,w=o.signed_z;let S=0;if(i.type==="polygon3d"||i.type==="embankment"){const E=k(i.style.elevation,s),x=s.tileInfo?fn(s.tileInfo,[0,0]):1;S=E*Ee*x}const T=o.gradient,I=o.abs_z,C=o.is_pivot,M=v.length,B=s.tileAttrs[s.tileProps.hovered],D=(H=s.id)!=null?H:"",F=i.type==="overpass"?t.pointIndexer.getIndexByTier(p):t.pointIndexer.getIndexById(g||D);let z=Bn;switch(i.type){case"polygon3d":{i.interactive?(z=B?Ft:t.idIndexer.getIndex(s,n,i),!B&&z===Ft&&(z=Bn)):z=i.interactiveOcclusion?Bn:Ft;break}case"overpass":case"tunnel":{z=t.idIndexer.getIndex(s,n,i),z===Ft&&(z=Bn);break}case"polygon":case"polygonExtrusion":case"embankment":{z=Bn;break}default:{const{type:E}=i}}(i.type==="embankment"||i.type==="polygon3d")&&c&&l!==void 0&&au(t,n,c,i.style,l);let N;if(u==="inverse")N=t.getBucket("mesh","inverse",re.sinks.inverse.packObjectAttributes(n,i,!!I,g!=null?g:"",!!y,s),re.sinks.inverse.binder);else if(u==="fill")N=t.getBucket("mesh","fill",re.sinks.fill.packObjectAttributes(n,i,r,!!I,s),re.sinks.fill.binder);else if(u==="depthClear")N=t.getBucket("mesh","depthClear",re.sinks.depthClear.packObjectAttributes(n,i,!!I,"",!!y,s),re.sinks.depthClear.binder);else return;for(let E=0;E<M-2;E++){const x=!(E%2);CT(N);const L=d?2:1,O=d?1:2,R=x?E+L:E+O,G=x?E+O:E+L,Q=ae/a.size;Be(bo,v[E],A[E],((K=w==null?void 0:w[E])!=null?K:0)*Q),Be(So,v[R],A[R],((P=w==null?void 0:w[R])!=null?P:0)*Q),Be(Eo,v[G],A[G],((b=w==null?void 0:w[G])!=null?b:0)*Q),Fp($a,bo,So,Eo),bo[2]/=Q,So[2]/=Q,Eo[2]/=Q,bo[2]+=S,So[2]+=S,Eo[2]+=S;const X=N.elements.offset;yu(N,bo,$a,T==null?void 0:T[E],z,F,f,I==null?void 0:I[E],C==null?void 0:C[E],h),yu(N,So,$a,T==null?void 0:T[R],z,F,f,I==null?void 0:I[R],C==null?void 0:C[R],h),yu(N,Eo,$a,T==null?void 0:T[G],z,F,f,I==null?void 0:I[G],C==null?void 0:C[G],h),N.objectsData[X]={objectId:D,size:N.elements.offset-X}}}};function yu(e,t,n,i,r,s,o,a,l,c){var h,g;const f=e.elements.stride*e.elements.offset,u=f/e.views.position.BYTES_PER_ELEMENT;e.views.position[u]=W+t[0],e.views.position[u+1]=W+t[1],e.views.height[f/e.views.height.BYTES_PER_ELEMENT]=t[2];const d=f/e.views.demPosition.BYTES_PER_ELEMENT;if(e.views.demPosition[d]=(((h=o==null?void 0:o[0])!=null?h:t[0])+W)/8,e.views.demPosition[d+1]=(((g=o==null?void 0:o[1])!=null?g:t[1])+W)/8,a!==void 0&&(e.views.absZ[f/e.views.absZ.BYTES_PER_ELEMENT]=a),e.views.isPivot[f/e.views.isPivot.BYTES_PER_ELEMENT]=l!=null?l:0,"normal"in e.views){const y=f/e.views.normal.BYTES_PER_ELEMENT,p=f/e.views.localID.BYTES_PER_ELEMENT,v=f/e.views.gradient.BYTES_PER_ELEMENT;e.views.normal[y]=at(n[0]),e.views.normal[y+1]=at(n[1]),e.views.normal[y+2]=at(n[2]),e.views.gradient[v]=at(i!=null?i:0),e.views.localID[p]=r,e.views.labelingTextureID[p]=s}else"labelingTextureID"in e.views&&(e.views.labelingTextureID[f/e.views.labelingTextureID.BYTES_PER_ELEMENT]=s);if("innerColor"in e.views&&c!==void 0){const y=f/e.views.innerColor.BYTES_PER_ELEMENT;e.views.innerColor[y]=c}e.elements.offset++}function CT(e){const t=e.indices.buffer,n=e.indices.offset,i=e.elements.offset;t[n]=i,t[n+1]=i+1,t[n+2]=i+2,e.indices.offset+=3}const el=ae/2,FT=1/Wt(1),Zi=(e,t,n,i,r,s,o,a)=>Ze([e,t.innerId,n,i,r,s,o],t,a),To=e=>({styleId:e[0],layerId:e[1],hiddenByFloorComplexId:e[2],floorId:e[3],isFloorStack:e[4],textureIndex:e[5],isHole:e[6],tileData:e.slice(7)}),jn={symbol:"polygonExtrusion",sinks:{sideFill:{stride:28,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.height=new Float32Array(t,4),e.views.localID=new Uint32Array(t,8),e.views.demPosition=new Int16Array(t,12),e.views.labelingTextureID=new Uint32Array(t,16),e.views.innerColor=new Uint32Array(t,20),e.views.elevation=new Float32Array(t,24)},packObjectAttributes:Zi,unpackObjectAttributes:To},sideTexture:{stride:28,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.height=new Float32Array(t,4),e.views.demPosition=new Int16Array(t,8),e.views.fillRect=new Float32Array(t,12),e.views.fillIndices=new Uint8Array(t,20),e.views.innerColor=new Uint32Array(t,24)},packObjectAttributes:Zi,unpackObjectAttributes:To},topFill:{stride:24,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.height=new Float32Array(t,4),e.views.localID=new Uint32Array(t,8),e.views.demPosition=new Int16Array(t,12),e.views.labelingTextureID=new Uint32Array(t,16),e.views.innerColor=new Uint32Array(t,20)},packObjectAttributes:Zi,unpackObjectAttributes:To},sideStroke:{stride:24,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.height=new Float32Array(t,4),e.views.normals=new Int8Array(t,8),e.views.direction=new Int8Array(t,12),e.views.distance=new Int8Array(t,15),e.views.demPosition=new Int16Array(t,16),e.views.innerColor=new Uint32Array(t,20)},packObjectAttributes:Zi,unpackObjectAttributes:To},topStroke:{stride:20,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.height=new Float32Array(t,4),e.views.directionDistance=new Int8Array(t,8),e.views.demPosition=new Int16Array(t,12),e.views.innerColor=new Uint32Array(t,16)},packObjectAttributes:Zi,unpackObjectAttributes:To}},generate(e,t,n,i,r,s,o){var N,H;const a=r.x,l=r.y,c=(N=r.cut)!=null?N:[],f=i.tileAttrs[i.tileProps.db_plan_id]||"",u=i.tileAttrs[i.tileProps.db_hidden_by_plan_building_id]||"",d=i.tileAttrs[i.tileProps.db_sublayer]==="Floor_half_walls_width_extended_ground",h=a.length,g=(H=i.id)!=null?H:"";let y;i.tileProps.db_centroid_x!==void 0&&i.tileProps.db_centroid_y!==void 0&&!Number.isNaN(i.tileAttrs[i.tileProps.db_centroid_x])&&!Number.isNaN(i.tileAttrs[i.tileProps.db_centroid_y])?y=[i.tileAttrs[i.tileProps.db_centroid_x],i.tileAttrs[i.tileProps.db_centroid_y]]:y=OT(a,l,c);const p=k(n.style.height,i),v=Number.isNaN(i.tileAttrs[i.tileProps.db_basis_height])?0:i.tileAttrs[i.tileProps.db_basis_height],A=i.tileInfo?fn(i.tileInfo,[0,0]):1,w=p<0;let S=Math.max(Math.abs(p)*Ee*A,FT);w&&(S=-S);const T=e.idIndexer.getIndex(i,t,n,{floorId:Number.isNaN(f)?void 0:f}),I=e.pointIndexer.getIndexById(g),C=k(n.style.topColor,i),M=k(n.style.strokeColor,i),B=k(n.style.sideColor,i),D=B&&B.isVertexColor?ka(B):void 0,F=M&&M.isVertexColor?ka(M):void 0,z=C&&C.isVertexColor?ka(C):void 0;if(w){const K=Zi(t,n,u,f,!1,NaN,!0,i);re.generate({collector:e,styleId:t,layer:n,side:le.top,ctx:i,vertices:r,tileInfo:o,sink:"depthClear"});const P=e.getBucket("polygonExtrusion","sideFill",K,jn.sinks.sideFill.binder);Ka(P,h,a,l,c,S,0,Bn,I,y,void 0,void 0,!0),i.styleState.terrainEnabled!==!0&&RT(r,S).forEach(E=>re.generate({collector:e,styleId:t,layer:n,side:le.side,ctx:i,vertices:E,tileInfo:o,sink:"inverse",reverseTriangles:!1,isHole:!0}));const b=e.getBucket("polygonExtrusion","topFill",K,jn.sinks.topFill.binder);Bm(b,h,a,l,S,Bn,I,y)}else{const K=Zi(t,n,u,f,d,NaN,!1,i);if(S>0){const x=e.getBucket("polygonExtrusion","sideFill",K,jn.sinks.sideFill.binder);let L=x.indices.offset;if(Ka(x,h,a,l,c,S,v,T,I,y,void 0,D),x.objectsData[L]={objectId:g,size:x.indices.offset-L},n.style.sideTextures.forEach((O,R)=>{var ge,de;if(p<O.minWallHeight)return;const G=O.sliceSize[0]*Ee*A,Q=O.sliceSize[1]*Ee*A,X=O.wallPadding.map(he=>he*Ee*A),se=Mn((de=(ge=i.tileInfo)==null?void 0:ge.coords[2])!=null?de:15),te=Zi(t,n,u,f,d,R,!1,i),U=e.getBucket("polygonExtrusion","sideTexture",te,jn.sinks.sideTexture.binder),ne=U.indices.offset,ee=O.vertical.mode==="stripe-top"?S-Q:0;Ka(U,h,a,l,c,S,ee,void 0,void 0,y,{config:O,textureWidthMapPoints:G,textureHeightMapPoints:Q,wallPaddingMapPoints:X,tileSizeMapPoints:se},D),U.objectsData[ne]={objectId:g,size:U.indices.offset-ne}}),!f&&(!s.AALinesOff||!Im(n,i))){const O=e.getBucket("polygonExtrusion","sideStroke",K,jn.sinks.sideStroke.binder);L=O.indices.offset,pu(O,h,a,l,c,y),gu(O,h,a,l,c,S,y),O.objectsData[L]={objectId:g,size:O.indices.offset-L}}}const P=e.getBucket("polygonExtrusion","topFill",K,jn.sinks.topFill.binder);let b=P.indices.offset;Bm(P,h,a,l,S,T,I,y,z),P.objectsData[b]={objectId:g,size:P.indices.offset-b};const E=e.getBucket("polygonExtrusion","topStroke",K,jn.sinks.topStroke.binder);b=E.indices.offset,LT(E,h,a,l,c,S,y,F),E.objectsData[b]={objectId:g,size:E.indices.offset-b}}}};function Bm(e,t,n,i,r,s,o,a,l){let c=e.elements.offset;const f=c;xu(e,c++,n[0],i[0],r,s,o,a,l),xu(e,c++,n[1],i[1],r,s,o,a,l);for(let u=2;u<t;u++)BT(e,f,u),xu(e,c++,n[u],i[u],r,s,o,a,l);e.elements.offset=c}function LT(e,t,n,i,r,s,o,a){const l={demPosition:o,innerColor:a};for(let c=0;c<t;c++){const f=mt(c,t);if(r&&r[f]===1){const u=mt((c+1)%t,t);ys(e,n[f],i[f],s,n[u],i[u],s,l)}}}function xu(e,t,n,i,r,s,o,a,l){const c=e.elements.stride,f=t*(c/e.views.position.BYTES_PER_ELEMENT),u=f>>1,d=r<0,h=Wt(Math.abs(r)),g=(d?-h:h)/He;e.views.position[f]=W+n,e.views.position[f+1]=W+i,e.views.height[u]=g,e.views.demPosition[f]=(W+a[0])/8,e.views.demPosition[f+1]=(W+a[1])/8,"localID"in e.views&&(e.views.localID[u]=s),"labelingTextureID"in e.views&&(e.views.labelingTextureID[u]=o),l!==void 0&&(e.views.innerColor[u]=l)}function BT(e,t,n){const i=e.indices.buffer;let r=e.indices.offset;n%2===0?(i[r++]=t+n-2,i[r++]=t+n-1,i[r++]=t+n):(i[r++]=t+n-1,i[r++]=t+n-2,i[r++]=t+n),e.indices.offset=r}function Dm(e){return $(el-Math.abs(e[0]-el),2)+$(el-Math.abs(e[1]-el),2)}function DT(e){return e[0]===0||e[0]===ae||e[1]===0||e[1]===ae}function OT(e,t,n){let i,r=$(ae,2);const s=e.length,o=Js();for(let a=0;a<s;a++){i||xr(o,[e[a],t[a]]);const l=mt(a,s);if(n[l]===0){const c=[e[l],t[l]],f=mt((a+1)%s,s),u=[e[f],t[f]];if(DT(c)){const d=Dm(c);d<r&&(i=c,r=d);const h=Dm(u);h<r&&(i=u,r=h)}else i=[(e[l]+e[f])/2,(t[l]+t[f])/2]}}return i||(i=[],fa(i,o)),i}function RT(e,t){const n=e.x,i=e.y,r=e.cut,s=n.length,o=[];for(let a=0;a<s;a++){const l=mt(a,s),c=a===s-1;if((!r||r[l]!==1)&&(r||c))continue;const f=n[l],u=i[l],d=(a+1)%s,h=mt(d,s),g=n[h],y=i[h];o.push({x:[f,f,g,g],y:[u,u,y,y],signed_z:[0,t,0,t]})}return o}const xs={type:Sr.Striped,cDist:0,oLen:0,sLen:0,localID:0,offsetMultiplier:14,px:[],py:[],count:0};function zT(e,t,n,i){return xs.cDist=e,xs.oLen=t,xs.localID=n,xs.offsetMultiplier=i,xs.globeMode=!1,xs}const gi={symbol:"dashedLine",sinks:{stroke:{stride:28,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.texExtender=new Int8Array(t,6),e.views.extender=new Int16Array(t,8),e.views.vertexDistance=new Float32Array(t,12),e.views.componentDistance=new Float32Array(t,16),e.views.objectLength=new Float32Array(t,20),e.views.localID=new Uint32Array(t,24)},packObjectAttributes(e,t,n,i,r,s){return Ze([e,t.innerId,n,i,r],t,s)},unpackObjectAttributes(e){return{styleId:e[0],layerId:e[1],tiers:e[2],hiddenByFloorComplexId:e[3],floorId:e[4],tileData:e.slice(5)}}},stroke3d:{stride:32,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.extender=new Int16Array(t,4),e.views.texExtender=new Int8Array(t,8),e.views.vertexDistance=new Float32Array(t,12),e.views.componentDistance=new Float32Array(t,16),e.views.objectLength=new Float32Array(t,20),e.views.height=new Float32Array(t,24),e.views.localID=new Uint32Array(t,28)},packObjectAttributes(e,t,n){return Ze([e,t.innerId],t,n)},unpackObjectAttributes(e){return{styleId:e[0],layerId:e[1],tileData:e.slice(2)}}}},generate(e,t,n,i,r){var A,w;const s=i.tileInfo;if(!s)return;const o=Fa(k(n.style.geometryModifier,i),s,r,i);if(o===null)return;const{tileAttrs:a,tileProps:l}=i,c=k(n.ignoreTier,i)?null:i.tileAttrs[l.db_tiers],f=a[l.db_hidden_by_metro_building_id]||"";let u=n.style.mode==="3d";const d=u?(A=o.z)!=null?A:lu(i,o):void 0;u&&(!d||!cu(d))&&(u=!1);const h=u?e.getBucket(n.type,"stroke3d",gi.sinks.stroke3d.packObjectAttributes(t,n,i),gi.sinks.stroke3d.binder):e.getBucket(n.type,"stroke",gi.sinks.stroke.packObjectAttributes(t,n,c,f,(w=a[l.floorId])!=null?w:"",i),gi.sinks.stroke.binder),g=e.idIndexer.getIndex(i,t,n),y=zT(a[l.componentDistanceStart]/ae,a[l.objectLength]/ae,g,u?gi.sinks.stroke3d.stride/2:gi.sinks.stroke.stride/2),p=Number.isNaN(a[l.beginningIsCut])?!1:a[l.beginningIsCut]!==0,v=Number.isNaN(a[l.endingIsCut])?!1:a[l.endingIsCut]!==0;!u&&yo(i.styleState,s,i.globeOff)?GT(h,o.x,o.y,s,p?Te.TileCut:Te.Butt,v?Te.TileCut:Te.Butt,a[l.previousPointX],a[l.previousPointY],a[l.nextPointX],a[l.nextPointY],y):Qa(o.x,o.y,d,o.x.length,p?Te.TileCut:Te.Butt,v?Te.TileCut:Te.Butt,a[l.previousPointX],a[l.previousPointY],a[l.nextPointX],a[l.nextPointY],y,h)}},NT=32;function GT(e,t,n,i,r,s,o,a,l,c,f){if(t.length<2)return;const u=[];for(let y=0;y<t.length;y++)u.push([hs(t[y]),hs(n[y])]);const d=Bf(u,NT,!1),h=new Uint16Array(d.length),g=new Uint16Array(d.length);for(let y=0;y<d.length;y++)h[y]=ps(d[y][0]),g[y]=ps(d[y][1]);f.globeMode=!0,f.tileInfo=i,Qa(h,g,void 0,h.length,r,s,o,a,l,c,f,e,!1)}const tl=[He/2,He/2],mi={symbol:"buildingModel",sinks:{fill:{stride:24,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.height=new Float32Array(t,4),e.views.texCoords=new Uint16Array(t,8),e.views.localID=new Uint32Array(t,12),e.views.demPosition=new Int16Array(t,16),e.views.labelingTextureID=new Uint32Array(t,20)},packObjectAttributes:(e,t,n,i,r,s)=>Ze([e,t.innerId,n,r,i],t,s),unpackObjectAttributes:e=>({styleId:e[0],layerId:e[1],texture:e[2],id:e[3],matrix:e[4],tileData:e.slice(5)})},stroke:{stride:20,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.height=new Float32Array(t,4),e.views.directionDistance=new Int8Array(t,8),e.views.demPosition=new Int16Array(t,12)},packObjectAttributes:(e,t,n,i,r)=>Ze([e,t.innerId,i,n],t,r),unpackObjectAttributes:e=>({styleId:e[0],layerId:e[1],id:e[2],matrix:e[3],tileData:e.slice(4)})}},processSubmesh(e,t,n,i,r,s,o,a,l){var h;const c=(h=n.id)!=null?h:"",f=i.idIndexer.getIndex(n,e,t),u=i.pointIndexer.getIndexById(c),d=i.getBucket(t.type,"fill",mi.sinks.fill.packObjectAttributes(e,t,a,l,c,n),mi.sinks.fill.binder,o);UT(d,s);for(let g=0;g<r.length;g++)kT(d,r,g,f,u)},processOuterEdge(e,t,n,i,r,s,o){var c;const a=(c=n.id)!=null?c:"",l=i.getBucket(t.type,"stroke",mi.sinks.stroke.packObjectAttributes(e,t,o,a,n),mi.sinks.stroke.binder);for(let f=0;f<s.length;f+=2){const u=s[f]*5,d=s[f+1]*5;ys(l,r[u],r[u+1],r[u+2],r[d],r[d+1],r[d+2],{demPosition:tl,isModel:!0})}}};function kT(e,t,n,i,r){const s=e.elements.offset,o=mi.sinks.fill.stride,a=n*5,l=s*(o/e.views.position.BYTES_PER_ELEMENT),c=s*(o/e.views.localID.BYTES_PER_ELEMENT);e.views.position[l]=t[a],e.views.position[l+1]=t[a+1],e.views.height[c]=t[a+2]/He,e.views.texCoords[l]=t[a+3],e.views.texCoords[l+1]=t[a+4],e.views.localID[c]=i,e.views.demPosition[l]=tl[0]/8,e.views.demPosition[l+1]=tl[1]/8,e.views.labelingTextureID[c]=r,e.elements.offset++}function UT(e,t){const n=e.elements.offset;let i=e.indices.offset;for(let r=0;r<t.length;r++)e.indices.buffer[i++]=n+t[r];e.indices.offset=i}const ws=Ye(),Po=Ye(),As={type:Sr.Entrance,offsetMultiplier:18,cDist:0,oLen:0,sLen:0,px:[],py:[],count:0,localID:0};function VT(e,t,n,i){return As.px=e.x,As.py=e.y,As.oLen=n/ae,As.count=t,As.localID=i,As}const Io={symbol:"arrow",sinks:{stroke:{stride:36,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.segmentEnd=new Uint16Array(t,4),e.views.texExtender=new Int8Array(t,8),e.views.arrowExtender=new Int8Array(t,10),e.views.extender=new Int16Array(t,12),e.views.direction=new Int16Array(t,16),e.views.vertexDistance=new Float32Array(t,20),e.views.objectLength=new Float32Array(t,24),e.views.type=new Float32Array(t,28),e.views.localID=new Uint32Array(t,32)},packObjectAttributes(e,t,n,i){return Ze([e,t.innerId,n>2?1:0],t,i)},unpackObjectAttributes(e){return{styleId:e[0],layerId:e[1],isLongArrow:e[2],tileData:e.slice(3)}}}},generate:(e,t,n,i,r)=>{const s=r.x,o=r.y,a=r.x.length,l=WT(s,o,a),c=e.getBucket(n.type,"stroke",Io.sinks.stroke.packObjectAttributes(t,n,a,i),Io.sinks.stroke.binder),f=e.idIndexer.getIndex(i,t,n),u=VT(r,a,l,f);Qa(r.x,r.y,void 0,a,Te.Butt,Te.Butt,0,0,0,0,u,c);let d=0;Om(c,so.StartBorder,s[0],o[0],s[1],o[1],0,0,d,l,f);for(let h=0;h<a-1;h++){if(h!==0){const g=s[h]-s[h-1],y=o[h]-o[h-1];d+=Math.sqrt(g*g+y*y)}Om(c,so.Arrow,s[h],o[h],s[h+1],o[h+1],-1,0,d,l,f)}}};function WT(e,t,n){let i=0;for(let r=1;r<n;r++){const s=e[r]-e[r-1],o=t[r]-t[r-1];i+=Math.sqrt(s*s+o*o)}return i}function Om(e,t,n,i,r,s,o,a,l,c,f){HT(e,1,2,0,0,2,3),nl(e,t,n,i,r,s,o,a,-1,-1,l,c,!0,f),nl(e,t,n,i,r,s,o,a,1,-1,l,c,!1,f),nl(e,t,n,i,r,s,o,a,1,1,l,c,!1,f),nl(e,t,n,i,r,s,o,a,-1,1,l,c,!0,f)}function nl(e,t,n,i,r,s,o,a,l,c,f,u,d,h){const g=e.elements,y=g.stride*g.offset,p=y>>1,v=p>>1;Hn(ws,n,i,r,s),zi(Po,ws),e.views.position[p]=W+n,e.views.position[p+1]=W+i,e.views.segmentEnd[p]=W+r,e.views.segmentEnd[p+1]=W+s,e.views.texExtender[y]=at(Po[0]*c*(d?-1:1)*Ke),e.views.texExtender[y+1]=at(Po[1]*c*(d?-1:1)*Ke),e.views.arrowExtender[y]=at(l*Ke),e.views.arrowExtender[y+1]=at(c*Ke);const A=l+o,w=c+a,S=ws[0]*A+Po[0]*w,T=ws[1]*A+Po[1]*w;e.views.extender[p]=Math.round(S*Ke*127),e.views.extender[p+1]=Math.round(T*Ke*127),e.views.direction[p]=Math.round(ws[0]*127),e.views.direction[p+1]=Math.round(ws[1]*127),e.views.vertexDistance[v]=f/He,e.views.objectLength[v]=u/He,e.views.type[v]=t,e.views.localID[v]=h,e.elements.offset++}function HT(e,t,n,i,r,s,o){const{elements:a,indices:l}=e,{buffer:c,offset:f}=l,u=a.offset;c[f]=u+t,c[f+1]=u+n,c[f+2]=u+i,c[f+3]=u+r,c[f+4]=u+s,c[f+5]=u+o,l.offset=f+6}const il={symbol:"circle",sinks:{fill:{stride:16,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.extender=new Int16Array(t,8),e.views.localID=new Uint32Array(t,12)},packObjectAttributes:(e,t,n)=>Ze([e,t.innerId],t,n),unpackObjectAttributes:e=>({styleId:e[0],layerId:e[1],tileData:e.slice(2)})}},generate(e,t,n,i,r){const s=e.getBucket(n.type,"fill",il.sinks.fill.packObjectAttributes(t,n,i),il.sinks.fill.binder),o=e.idIndexer.getIndex(i,t,n),a=[r.x[0],r.y[0],r.z?r.z[0]:0];let l,c,f;if(i.styleState.globeEnabled&&i.tileInfo!==void 0){const u=Zn(i.tileInfo,a[0],a[1]);l=u.x,c=u.y,f=u.z}else l=W+a[0],c=W+a[1],f=Wt(a[2]);YT(s,0,2,1,0,3,2),rl(s,l,c,f,-1,-1,o),rl(s,l,c,f,-1,1,o),rl(s,l,c,f,1,1,o),rl(s,l,c,f,1,-1,o)}};function rl(e,t,n,i,r,s,o){const l=e.elements.offset*e.elements.stride>>1,c=l>>1;e.views.position[l]=t,e.views.position[l+1]=n,e.views.position[l+2]=i,e.views.extender[l]=r,e.views.extender[l+1]=s,e.views.localID[c]=o,e.elements.offset++}function YT(e,t,n,i,r,s,o){const{elements:a,indices:l}=e,{buffer:c,offset:f}=l,u=a.offset;c[f]=u+t,c[f+1]=u+n,c[f+2]=u+i,c[f+3]=u+r,c[f+4]=u+s,c[f+5]=u+o,l.offset=f+6}const bs=Ye(),Ss=Ye(),Rm=Ye(),zm=Ye(),wu=(e,t,n,i)=>Ze([e,t.innerId,n],t,i),Au=e=>({styleId:e[0],layerId:e[1],hiddenByFloorComplexId:e[2],tileData:e.slice(3)}),Mo=Jp(1),vi={symbol:"lineExtrusion",sinks:{fill:{stride:16,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.height=new Float32Array(t,4),e.views.demPosition=new Int16Array(t,8),e.views.innerColor=new Uint32Array(t,12)},packObjectAttributes:wu,unpackObjectAttributes:Au},topStroke:{stride:20,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.height=new Float32Array(t,4),e.views.directionDistance=new Int8Array(t,8),e.views.demPosition=new Int16Array(t,12),e.views.innerColor=new Uint32Array(t,16)},packObjectAttributes:wu,unpackObjectAttributes:Au},sideStroke:{stride:24,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.height=new Float32Array(t,4),e.views.normals=new Int8Array(t,8),e.views.direction=new Int8Array(t,12),e.views.distance=new Int8Array(t,15),e.views.demPosition=new Int16Array(t,16)},packObjectAttributes:wu,unpackObjectAttributes:Au}},generate(e,t,n,i,r,s){const o=r.x,a=r.y,l=o.length,c=i.tileAttrs[i.tileProps.db_hidden_by_metro_building_id]||"",f=e.getBucket(n.type,"fill",vi.sinks.fill.packObjectAttributes(t,n,c,i),vi.sinks.fill.binder),u=e.getBucket(n.type,"topStroke",vi.sinks.topStroke.packObjectAttributes(t,n,c,i),vi.sinks.topStroke.binder),d=e.getBucket(n.type,"sideStroke",vi.sinks.sideStroke.packObjectAttributes(t,n,c,i),vi.sinks.sideStroke.binder),h=!s.AALinesOff||!Im(n,i);for(let g=0;g<l-1;g++){const y=o[g],p=a[g],v=o[g+1],A=a[g+1];tt(bs,y,v),tt(Ss,p,A),tt(Rm,v,y),tt(zm,A,p),Ka(f,2,bs,Ss,void 0,Mo,void 0,void 0,void 0,void 0,void 0,0),ys(u,y,p,Mo,v,A,Mo),h&&(pu(d,2,bs,Ss,void 0),pu(d,2,Rm,zm,void 0),gu(d,2,bs,Ss,void 0,Mo))}h&&(tt(bs,o[l-1],o[0]),tt(Ss,a[l-1],a[0]),gu(d,2,bs,Ss,void 0,Mo))}},sl={symbol:"raster",sinks:{fill:{stride:8,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.txtrCoords=new Uint16Array(t,4)},packObjectAttributes(e,t,n,i,r){return Ze([e,t.innerId,i,r],t,n)},unpackObjectAttributes(e){return{styleId:e[0],layerId:e[1],textureIndex:e[2],tiers:e[3],tileData:e.slice(4)}}}},generate(e,t,n,i,r,s,o){const a=t.x,l=t.y,c=e.getBucket(r.type,"fill",sl.sinks.fill.packObjectAttributes(n,r,i,s,o),sl.sinks.fill.binder);let f=c.elements.offset;XT(c.indices,f,0,1,2,2,1,3),ol(c,f++,a[0],l[0],0,1),ol(c,f++,a[1],l[1],1,1),ol(c,f++,a[2],l[2],0,0),ol(c,f++,a[3],l[3],1,0),c.elements.offset=f}};function ol(e,t,n,i,r,s){t=t*4,e.views.position[t]=W+n,e.views.position[t+1]=W+i,e.views.txtrCoords[t]=qt(r),e.views.txtrCoords[t+1]=qt(s)}function XT(e,t,n,i,r,s,o,a){const l=e.buffer,c=e.offset;l[c]=t+n,l[c+1]=t+i,l[c+2]=t+r,l[c+3]=t+s,l[c+4]=t+o,l[c+5]=t+a,e.offset=c+6}const ZT=8;function bu(e,t,n,i,r,s){return Ze([e,t.innerId,n,i,r],t,s)}const jT=(e,t,n,i,r)=>Ze([e,t.innerId,n,i],t,r),Su=e=>({styleId:e[0],layerId:e[1],tiers:e[2],floorId:e[3],hiddenByFloorComplexId:e[4],tileData:e.slice(5)}),QT=e=>({styleId:e[0],layerId:e[1],tiers:e[2],floorId:e[3],tileData:e.slice(4)}),qT=(e,t)=>{const n=e.type==="polygon"&&k(e.style.color,t),i=lg(n)&&n.factor.type==="vertex-attribute";return i?{withMixFactor:i,mixFactorAttributeName:n.factor.name}:{withMixFactor:i,mixFactorAttributeName:void 0}},Dn={symbol:"polygon",sinks:{fill:{stride:12,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.localID=new Uint32Array(t,8)},packObjectAttributes:bu,unpackObjectAttributes:Su},stroke:{stride:12,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.directionDistance=new Int8Array(t,8)},packObjectAttributes:bu,unpackObjectAttributes:Su},shadow:{stride:8,binder:(e,t)=>{e.views.position=new Uint16Array(t)},packObjectAttributes:jT,unpackObjectAttributes:QT},fillWithMixFactor:{stride:12,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.mixFactor=new Uint16Array(t,8)},packObjectAttributes:bu,unpackObjectAttributes:Su}},generate(e,t,n,i,r,s,o,a){var D;if(i.tileAttrs[i.tileProps.db_geometry_type]==="polyline")return;const{withMixFactor:c,mixFactorAttributeName:f}=qT(n,i),u=r.x,d=r.y,h=r.cut,g=i.tileAttrs[i.tileProps.db_plan_id]||"",y=i.tileAttrs[i.tileProps.db_sublayer];Array.isArray(i.styleState._backgroundFloorIds)&&i.styleState._backgroundFloorIds.length>0&&(y==="Hall_ground"||y==="Hall_underground_ground")&&re.generate({collector:e,styleId:t,layer:n,side:le.top,ctx:i,vertices:r,tileInfo:o,dpi:s,rasterSets:a,sink:"inverse",reverseTriangles:!1,floorId:g});const v=c?r[f]:void 0;if(ET(n)&&a&&(au(e,t,a,n.style,s),n.style.normalMapTextureImage)){const F={textureImage:n.style.normalMapTextureImage,textureSize:n.style.normalMapTextureSize,lengthUnits:n.style.normalMapTextureLengthUnits};au(e,t,a,F,s)}const A=e.idIndexer.getIndex(i,t,n,{floorId:g||void 0}),w=(D=i.id)!=null?D:"",S=n.type==="polygon"&&!k(n.ignoreTier,i)?i.tileAttrs[i.tileProps.db_tiers]:null,T=i.tileAttrs[i.tileProps.db_hidden_by_metro_building_id]||"",I=c?e.getBucket("polygon","fillWithMixFactor",Dn.sinks.fillWithMixFactor.packObjectAttributes(t,n,S,g,T,i),Dn.sinks.fillWithMixFactor.binder):e.getBucket("polygon","fill",Dn.sinks.fill.packObjectAttributes(t,n,S,g,T,i),Dn.sinks.fill.binder),C=I.indices.offset,M=(yo(i.styleState,i.tileInfo,i.globeOff)||i.ecefDataState===kl.Present)&&i.tileInfo!==void 0;M?nP(I,u,d,i.tileInfo,A):Nm(I,u.length,u,d,A,v),I.objectsData[C]={objectId:w,size:I.indices.offset-C};const B=e.getBucket("polygon","stroke",Dn.sinks.stroke.packObjectAttributes(t,n,S,g,T,i),Dn.sinks.stroke.binder);if(h){const F=B.indices.offset;KT(B,u.length,u,d,h,M?i.tileInfo:void 0),B.objectsData[F]={objectId:w,size:B.indices.offset-F}}}};function Nm(e,t,n,i,r,s){const o=e.indices.buffer;let a=e.indices.offset,l=e.elements.offset;const c=l;Eu(e,l++,n[0],i[0],r,s==null?void 0:s[0]),Eu(e,l++,n[1],i[1],r,s==null?void 0:s[1]);for(let f=2;f<t;f++)$T(o,a,c,f),Eu(e,l++,n[f],i[f],r,s==null?void 0:s[f]),a=a+3;e.elements.offset=l,e.indices.offset=a}function KT(e,t,n,i,r,s){const o=s!==void 0?{isEcef:!0}:void 0;for(let a=0;a<t;a++){const l=mt(a,t);if(r[l]===1){const c=mt((a+1)%t,t);if(s){const f=Zn(s,n[l],i[l]),u=Zn(s,n[c],i[c]);ys(e,f.x,f.y,f.z,u.x,u.y,u.z,o)}else ys(e,n[l],i[l],0,n[c],i[c],0)}}}function JT(e,t,n,i,r,s,o){t=t*e.elements.stride/e.views.position.BYTES_PER_ELEMENT,e.views.position[t]=n,e.views.position[t+1]=i,e.views.position[t+2]=r,t=t>>1,"localID"in e.views&&(e.views.localID[t]=s)}function Eu(e,t,n,i,r,s){t=t*e.elements.stride/e.views.position.BYTES_PER_ELEMENT,e.views.position[t]=W+n,e.views.position[t+1]=W+i,s!==void 0&&"mixFactor"in e.views&&(e.views.mixFactor[t]=s),t=t>>1,"localID"in e.views&&(e.views.localID[t]=r)}function $T(e,t,n,i){i%2===0?(e[t]=n+i-2,e[t+1]=n+i-1,e[t+2]=n+i):(e[t]=n+i-1,e[t+1]=n+i-2,e[t+2]=n+i)}const Tu=Lt.fromGeo([0,90]),Pu=Lt.fromGeo([0,-90]),eP={x:fi(Tu[0]),y:fi(Tu[1]),z:fi(Tu[2])},tP={x:fi(Pu[0]),y:fi(Pu[1]),z:fi(Pu[2])};function nP(e,t,n,i,r,s){if(t.length<3)return;const o=i.coords,a=o[1]===$(2,o[2])-1,l=o[1]===0,c=[],f=[],u=t.length;for(let w=0;w<u;w++){const S=mt(w,u);f.push([mm(hs(t[S])),mm(hs(n[S]))])}c.push(f);const d=t2(c,{x:2,y:2,z:2},ZT*$(2,o[3]-o[2]),!1),h=e.indices.buffer;let g=e.indices.offset,y=e.elements.offset;const p=y,v=d.verticesFlattened,A=d.indicesTriangles;for(let w=0;w<v.length;w+=2){const S=ps(v[w]),T=ps(v[w+1]);let I;a&&T>=$(2,15)-10?I=eP:l&&T<=10?I=tP:I=Zn(i,S,T),JT(e,y,I.x,I.y,I.z,r),y++}for(let w=0;w<A.length;w++)h[g]=p+A[w],g++;e.elements.offset=y,e.indices.offset=g}function iP(e,t,n=[],i=[]){return{x:Gm(n,e),y:Gm(i,t)}}function Gm(e,t){const n=e.reduce((r,s)=>r.concat(s),[0]).concat(t),i=n.length-1;return{coords:n.slice(n[0]===n[1]?1:0,n[i-1]===n[i]?i:i+1),isOddStretchable:rP(e)}}function rP(e){var t;return!((t=e==null?void 0:e[0])!=null&&t[0])}function sP(e,t,n,i,r){return[km(e.x,t,i[0],r),km(e.y,n,i[1],r)]}function km(e,t,n,i){if(e.coords.length<2)throw new Error("The source coords array must have at least two coordinates");return e.coords.map((r,s)=>(t+r+i*(s===0?-1:s===e.coords.length-1?1:0))/n)}function oP(e,t,n,i,r=0,s=0){return[Vm(Um(e.x,t),i,r),Vm(Um(e.y,n),i,s)]}function Um(e,t){const{stretchSize:n,fixSize:i}=aP(e),{coords:r,isOddStretchable:s}=e,o=t<i?i:t,a=[r[0]];for(let l=1;l<r.length;l++){const c=r[l-1],f=r[l],u=l%2===(s?1:0),d=a[a.length-1];if(!u){a.push(d+f-c);continue}a.push(Math.round((o-i)*(f-c)/n)+d)}return a}function aP({coords:e,isOddStretchable:t}){if(e.length<2)throw new Error("An axis must have at least two coordinates");if(e.length===2)return{stretchSize:e[e.length-1],fixSize:0};let n=0;for(let i=t?0:1;i<e.length-1;i=i+2)n+=e[i+1]-e[i];return{stretchSize:n,fixSize:e[e.length-1]-n}}function Vm(e,t,n=0){const i=e[e.length-1]-e[0],r=e.map(s=>Math.round(s-i/2+n));return r.length===2?r[r.length-1]+=2*t:(r[0]-=t,r[r.length-1]+=t),r}function lP(e,t,n,i,r,s,o,a,l){const c=iP(n.w,n.h,a,l),f=sP(c,n.x,n.y,t,Bh),u=oP(c,i,r,Bh,s,o);e.set(u,f)}function cP(e,t,n,i,r,s,o,a,l,c,f,u){const{textureX:d,textureY:h,stretchedX:g,stretchedY:y,countX:p,countY:v}=i,A=s!==-1/0?s:zx,w=o!==1/0?o:Nx,[S,T]=f;for(let I=0;I<p-1;I++){const C=d[I],M=d[I+1],B=g[I],D=g[I+1];for(let F=0;F<v-1;F++){const z=h[F],N=h[F+1],H=y[F],K=y[F+1];Wm(r,0,2,1,1,2,3),al(r,e,t,n,B,H,C,z,S,T,A,w,a,l,c,u),al(r,e,t,n,D,H,M,z,S,T,A,w,a,l,c,u),al(r,e,t,n,B,K,C,N,S,T,A,w,a,l,c,u),al(r,e,t,n,D,K,M,N,S,T,A,w,a,l,c,u)}}}function fP(e,t,n,i,r,s,o,a){const{stretchedX:l,stretchedY:c}=i,f=Math.ceil((l[l.length-1]-l[0])/2),u=Math.ceil((c[c.length-1]-c[0])/2),d=s*Dc/2;a[0]=l[0]+f,a[1]=c[0]+u;const h=a[0]-d,g=a[0]+d,y=a[1]-d,p=a[1]+d;Wm(r,0,2,1,1,2,3),ll(r,e,t,n,h,y,o),ll(r,e,t,n,g,y,o),ll(r,e,t,n,h,p,o),ll(r,e,t,n,g,p,o)}function al(e,t,n,i,r,s,o,a,l,c,f,u,d,h,g,y){let p=e.elements.offset*18;if(y!==void 0){const{x:v,y:A,z:w}=y(t,n);e.views.position[p]=v,e.views.position[p+1]=A,e.views.position[p+2]=w}else e.views.position[p]=W+t,e.views.position[p+1]=W+n,e.views.position[p+2]=Wt(i);e.views.cornerOffset[p]=r,e.views.cornerOffset[p+1]=-s,e.views.checkPointOffset[p]=l,e.views.checkPointOffset[p+1]=c,e.views.texCoords[p]=qt(o),e.views.texCoords[p+1]=qt(a),e.views.scales[p]=NE(f),e.views.scales[p+1]=zE(u),p=p>>1,e.views.localID[p]=d,e.views.labelingTextureID[p]=h,e.views.spritePointTextureID[p]=g,e.elements.offset++}function ll(e,t,n,i,r,s,o){const a=e.elements,l=a.stride*a.offset>>1;e.views.position[l]=W+t,e.views.position[l+1]=W+n,e.views.position[l+2]=Wt(i),e.views.cornerOffset[l]=r,e.views.cornerOffset[l+1]=-s,e.views.labelingTextureID[l>>1]=o,a.offset++}function Wm(e,t,n,i,r,s,o){const{elements:a,indices:l}=e,{buffer:c,offset:f}=l,u=a.offset;c[f]=u+t,c[f+1]=u+n,c[f+2]=u+i,c[f+3]=u+r,c[f+4]=u+s,c[f+5]=u+o,l.offset=f+6}class uP{constructor(){this.countX=0,this.countY=0,this.textureX=[],this.textureY=[],this.stretchedX=[],this.stretchedY=[]}reset(){this.countX=0,this.countY=0}set(t,n){this.countX=n[0].length,this.countY=n[1].length,this.textureX=n[0],this.textureY=n[1],this.stretchedX=t[0],this.stretchedY=t[1]}isEmpty(){return this.countX===0||this.countY===0}}var zt=(e=>(e[e.Common=0]="Common",e[e.Commercial=1]="Commercial",e[e.CommercialCity=2]="CommercialCity",e[e.CommercialPremium=3]="CommercialPremium",e[e.Landmark=4]="Landmark",e))(zt||{}),ji=(e=>(e[e.Point=0]="Point",e[e.Line=1]="Line",e))(ji||{}),_o=(e=>(e[e.Tile=0]="Tile",e[e.Floor=1]="Floor",e[e.DynamicObject=2]="DynamicObject",e[e.PersonalPoi=3]="PersonalPoi",e))(_o||{}),gn=(e=>(e[e.Dead=0]="Dead",e[e.Alive=1]="Alive",e[e.Unused=2]="Unused",e[e.CommercialAlive=3]="CommercialAlive",e[e.CommercialDead=4]="CommercialDead",e))(gn||{}),Je=(e=>(e[e.Text=0]="Text",e[e.Icon=1]="Icon",e[e.PoiText=2]="PoiText",e[e.PoiText2=3]="PoiText2",e[e.OneWayLine=4]="OneWayLine",e[e.LineText=5]="LineText",e[e.Box=6]="Box",e))(Je||{});let Hm=Math.random;const dP=e=>{const t={randomSeed:0};Eg(t,[e]),Hm=()=>cs(t,0,1)};function hP(e,t,n,i){const r=Ym(e,n,i),s=Ym(t,n,i);return r===void 0&&s===void 0?!0:r===void 0?s!==void 0?s:!0:s===void 0?r!==void 0?r:!0:r||s}function Ym(e,t,n){const i=e[t];if(i!==void 0)return i[n]}var Qn=(e=>(e[e.Point=0]="Point",e[e.Line=1]="Line",e[e.OneWayLine=2]="OneWayLine",e))(Qn||{});function Nt(e,t){return Number.isNaN(e)?t:e}function cl(e,t){if(!e)return"";const n=k(e,t);return!Number.isNaN(n)&&(n||n===0)?String(n):""}function pP(e){return e.type==="labelLine"||e.type==="point"||e.type==="oneWayLine"}function gP(e,t,n,i,r,s){const o=[];for(const a of e)for(const l of a.labels){const c=n.getStyle(l.styleId);if(!c){console.error(`Not found style ${l.styleId} in unpackPreLabelingResult`);continue}const f=c.layersById[l.layerId];if(!f||!pP(f)){console.error(`Not found layer: ${l.layerId} in style ${l.styleId} in unpackPreLabelingResult`);continue}const u=new Zm(l,f,t,a.metatileHash,!!i.floorStackOn||!!i._activeFloorIsMetro);switch(l.type){case Qn.Point:u.setSpecificPointAttributes(l,i,r,s);break;case Qn.Line:u.setSpecificLineAttributes(l,i,r,s);break;case Qn.OneWayLine:u.setSpecificOneWayAttributes(l);break}o.push(u)}return o}const mP=/^\d+$/;function Xm(e){return mP.test(e)?+("0."+e):NaN}class Zm{constructor(t,n,i,r,s){this.rtlProcessed=!1,this.labelingElements=[],this.id="",this.idSortKey=NaN,this.floorId="",this.planLevel=NaN,this.detailLevel=0,this.labelPriority=0,this.label="",this.ranges=[],this.pointType=zt.Common,this.iconPriority=0,this.styleIconPriority=0,this.styleTextPriority=0,this.identifyIndex=Ft,this.identifyPoiLabelIndex=Ft,this.labelingTextureIndex=Ft,this.spritePointTextureIndex=Ft,this.hovered=0,this.label2Priority=0,this.mapPointVertices=[0,0,0,0],this.geoPoint=[NaN,NaN],this.demElevation=0,this.elevation=0,this.componentDistanceStartWorld=0,this.componentDistanceEnd=0,this.componentDistanceStart=0,this.objectLengthWorld=0,this.checkPointOffset=[0,0],this.layer=n,this.styleId=t.styleId,this.source=i,this.sourceId=t.sourceId,this.metatileHash=r,this.geometryType=t.type===Qn.Point?t.geometryType:ji.Line,this.tileData=t.tileData,this.labelPriority=t.labelPriority,this.detailLevel=t.tileCoords[2],this.styleIconPriority=t.styleIconPriority,this.styleTextPriority=t.styleTextPriority,this.id=t.id,this.idSortKey=Xm(t.id),this.floorId=t.floorId,this.planLevel=s?Math.max(0,t.planLevel):0}setSpecificPointAttributes(t,n,i,r){var f,u,d,h;if(this.layer.type!=="point")throw new Error("Label: layer type is not a point");const s=this.layer.style;this.pointType=t.pointType,this.label2Priority=t.label2Priority,this.iconPriority=t.iconPriority,this.identifyIndex=t.identifyIndex,this.identifyPoiLabelIndex=t.identifyPoiLabelIndex,this.labelingTextureIndex=t.labelingTextureIndex,this.spritePointTextureIndex=t.spritePointTextureIndex,this.hovered=t.hovered,this.demElevation=t.demElevation;const o=dn(i,r,n,!0,t.tileData);this.label=zf(cl(s.textField,o),s.textMaxLengthPerLine),s.textField2&&(this.label2=zf(cl(s.textField2,o),s.textMaxLengthPerLine)),this.layer.type==="point"&&s.iconTextField&&(this.iconLabel=zf(cl(s.iconTextField,o),s.textMaxLengthPerLine));const a=Bt(t.tileCoords);this.mapPointVertices=[];const l=[0,0,0],c=[0,0,0];for(let g=0;g<t.vertices[0].length;g++)l[0]=t.vertices[0][g],l[1]=t.vertices[1][g],l[2]=(u=(f=t.vertices[2])==null?void 0:f[g])!=null?u:0,St(c,l,a),this.mapPointVertices.push(c[0],c[1],c[2],(h=(d=t.vertices[3])==null?void 0:d[g])!=null?h:0);t.geometryType===ji.Point?(this.geoPoint=me.toGeo(this.mapPointVertices),this.layer.style.allowElevation||(this.mapPointVertices[2]=0)):(this.componentDistanceStart=t.componentDistanceStart,this.componentDistanceEnd=t.componentDistanceEnd,this.componentDistanceStartWorld=es(this.componentDistanceStart,t.tileCoords[2]),this.objectLengthWorld=es(t.objectLength,t.tileCoords[2]))}setSpecificLineAttributes(t,n,i,r){var c,f,u,d;if(this.layer.type!=="labelLine")throw new Error("Label: layer type is not a labelLine");const s=dn(i,r,n,!0,t.tileData);this.label=cl(this.layer.style.textField,s);const o=Bt(t.tileCoords);this.labelingTextureIndex=t.labelingTextureIndex,this.screenSpace=t.screenSpace,this.mapPointVertices=[];const a=[0,0,0],l=[0,0,0];for(let h=0;h<t.vertices[0].length;h++)a[0]=t.vertices[0][h],a[1]=t.vertices[1][h],a[2]=(f=(c=t.vertices[2])==null?void 0:c[h])!=null?f:0,St(l,a,o),this.mapPointVertices.push(l[0],l[1],l[2],(d=(u=t.vertices[3])==null?void 0:u[h])!=null?d:0);this.componentDistanceStart=t.componentDistanceStart,this.componentDistanceEnd=t.componentDistanceEnd,this.componentDistanceStartWorld=es(this.componentDistanceStart,t.tileCoords[2]),this.objectLengthWorld=es(t.objectLength,t.tileCoords[2]),this.tiers=k(this.layer.ignoreTier,s)?void 0:t.tiers}setSpecificOneWayAttributes(t){var s,o,a,l;const n=Bt(t.tileCoords);this.labelingTextureIndex=t.labelingTextureIndex,this.screenSpace=t.screenSpace,this.mapPointVertices=[];const i=[0,0,0],r=[0,0,0];for(let c=0;c<t.vertices[0].length;c++)i[0]=t.vertices[0][c],i[1]=t.vertices[1][c],i[2]=(o=(s=t.vertices[2])==null?void 0:s[c])!=null?o:0,St(r,i,n),this.mapPointVertices.push(r[0],r[1],r[2],(l=(a=t.vertices[3])==null?void 0:a[c])!=null?l:0);this.componentDistanceStart=t.componentDistanceStart,this.componentDistanceEnd=t.componentDistanceEnd,this.componentDistanceStartWorld=es(this.componentDistanceStart,t.tileCoords[2]),this.objectLengthWorld=es(t.objectLength,t.tileCoords[2]),this.tiers=t.tiers}updateRanges(){this.ranges=U2([this.label,this.label2,this.iconLabel])}}function Qi(e,t,n){const{minX:i,maxX:r,minY:s,maxY:o}=n;e.push(i,s,r-i,o-s,t)}function yi(e,t){const n=e.anchorScreen,i=e.boxes[t];return{element:e,minX:n[0]+i[0]-e.marginLeft,maxX:n[0]+i[2]+e.marginRight,minY:n[1]+i[1]-e.marginTop,maxY:n[1]+i[3]+e.marginBottom}}function vP(e,t){if(e.parent===t||e.firstLabel===t||t.parent===e||t.firstLabel===e)return!1;const n=e.labelingGroup,i=t.labelingGroup,r=e.labelingGroupTable,s=t.labelingGroupTable;return hP(r,s,n,i)}function Iu(e,t,n,i){const r=yi(t,n);if(r.minX>i.maxX||r.maxX<i.minX||r.minY>i.maxY||r.maxY<i.minY)return!0;const s=e.search(r);for(let o=0;o<s.length;o++)if(vP(t,s[o].element))return!0;return!1}function jm(e,t,n,i,r){if(e.marginTop=i.topBottom,e.marginRight=i.leftRight,e.marginBottom=i.topBottom,e.marginLeft=i.leftRight,e.placementIndex===-1){r&&Qi(r,gn.CommercialDead,yi(e,0));return}if(Iu(t,e,0,n))e.placementIndex=-1,r&&Qi(r,gn.CommercialDead,yi(e,0));else{e.placementIndex=0;const o=yi(e,0);t.insert(o),r&&Qi(r,gn.CommercialAlive,o)}}function Mu(e,t,n,i){let r=!0;for(let s=0;s<e.boxes.length;s++)if(Iu(t,e,s,n)){if(r=!1,i)for(let o=0;o<e.boxes.length;o++){const a=yi(e,o);let l;o===s?l=gn.Dead:o<s?l=gn.Alive:l=gn.Unused,Qi(i,l,a)}break}if(r)for(let s=0;s<e.boxes.length;s++){const o=yi(e,s);t.insert(o),i&&Qi(i,gn.Alive,o)}e.placementIndex=r?0:-1}function Qm(e,t,n,i){e.placementIndex=-1;for(let r=0;r<e.boxes.length;r++)if(!(e.firstLabel&&e.firstLabel.placementIndex!==r)&&!(e.parent&&e.parent.boxes.length>1&&e.parent.placementIndex!==r))if(Iu(t,e,r,n))i&&Qi(i,gn.Dead,yi(e,r));else{const s=yi(e,r);if(t.insert(s),e.placementIndex=r,i){Qi(i,gn.Alive,s);for(let o=r+1;o<e.boxes.length;o++)Qi(i,gn.Unused,yi(e,o))}break}}function qm(e,t){return e.sort((n,i)=>i.groupPriority-n.groupPriority||(t.has(i.id)?1:0)-(t.has(n.id)?1:0)||i.commPriorityRandomFactor-n.commPriorityRandomFactor)}function Es(e){return e.type!==Je.Box&&!Number.isNaN(e.commPriorityRandomFactor)}function Km(e){return e.label.pointType===zt.CommercialCity}function yP(e){return Es(e)&&Km(e)}function xP(e){return Es(e)&&e.label.pointType===zt.CommercialPremium}function Co(e){return e.pointType===zt.Commercial||e.pointType===zt.CommercialCity||e.pointType===zt.CommercialPremium}function wP(e){return e.label.pointType!==zt.CommercialCity||e.placementIndex!==-1&&e.label.pointType===zt.CommercialCity}function AP(e,t){return t.size===0?!1:e.filter(i=>bP(i,t)?(i.adsType=0,!0):!1).length>0}function bP(e,t){return e.type===Je.Icon&&t.has(e.label.id)}function SP(e){return e.type===Je.Box&&e.labelingGroup==="markerText"&&e.parent!==void 0}function EP(e,t,n,i,r){const s=mo();qm(e.filter(Km),n).forEach(a=>{jm(a,s,t,i.city,r)}),s.clear(),qm(e.filter(wP),n).forEach(a=>{jm(a,s,t,i.default,r)})}function Jm(e,t,n,i,r){switch(e.type){case Je.LineText:case Je.Icon:if(e.placementIndex===-1&&Es(e))break;if(e.boxes.length>1&&e.type===Je.Icon?Qm(e,n,i,r):Mu(e,n,i,r),e.adsType===0){const o=t.get(e.label.id);if(!o)break;e.placementIndex!==-1&&(o.parent=e,Mu(o,n,i,r),t.delete(e.label.id))}break;case Je.Box:if(!e.parent){Mu(e,n,i,r);break}e.placementIndex=-1;break;case Je.PoiText:case Je.PoiText2:(!e.parent||e.parent.placementIndex!==-1)&&(!e.firstLabel||e.firstLabel.placementIndex!==-1)?Qm(e,n,i,r):e.placementIndex=-1;break}}function TP(e,t){return e.idKey!==t.idKey&&e.idKey===e.idKey&&t.idKey===t.idKey?t.idKey>e.idKey?1:-1:t.id>e.id?1:t.id===e.id?0:-1}function PP(e,t,n,i,r,s,o){const a=[],l=new Map;t.forEach(F=>{if(SP(F)){l.set(F.parent.label.id,F),F.placementIndex=-1;return}a.push(F)});const c=new Set(l.keys());let f=[];if(n.globeMode){for(const F of e)s.ecef.canSee(F.anchorGeo)?f.push(F):F.placementIndex=-1;for(const F of a)s.ecef.canSee(F.anchorGeo)?f.push(F):F.placementIndex=-1}else f=e.concat(a);const u=n.debugLabels?[]:void 0,{size:d,viewport:h}=n,g=d[0],y=d[1],p=(Jo.tileMultiplier-1)/2,v=Math.round(g*p),A=Math.round(y*p),w={minX:h.left-v,maxX:h.left+g+v,minY:h.top-A,maxY:h.top+y+A},S=mo(),T=performance.now(),I=AP(f,c),C=f.map(F=>{const z=i.has(F.id)?1:0;return{el:F,group:F.groupPriority,commercial:Es(F)?F.commPriorityRandomFactor+z:0,zmkDonor:I&&F.adsType===0?1:0,survived:n.disableSurvivedPoiPrevalence?0:z,hovered:F.label instanceof Zm?F.label.hovered:0,item:F.itemPriority,idKey:F.label.idSortKey,id:F.label.id,layer:F.label.layer.innerId,x:F.anchorWorld[0],y:F.anchorWorld[1],type:F.type}}).sort((F,z)=>z.group-F.group||z.commercial-F.commercial||z.zmkDonor-F.zmkDonor||z.survived-F.survived||z.hovered-F.hovered||z.item-F.item||TP(F,z)||z.layer-F.layer||z.x-F.x||z.y-F.y||F.type-z.type).map(F=>F.el),M=performance.now();let B=-1;const D=C.filter((F,z)=>Es(F)?(B=z,!0):!1);if(B!==-1){for(let F=0;F<=B;F++)Jm(C[F],l,S,w,u);S.clear(),EP(D,w,i,r,u)}for(let F=0;F<C.length;F++)Jm(C[F],l,S,w,u);return o&&(o.sortMs+=M-T,o.placeMs+=performance.now()-M),u}const _u=new Map;class fl{constructor(t,n,i,r,s,o,a,l,c){switch(this.anchorWorld=[0,0,0,0,0],this.anchorGeo=[0,0],this.groupPriority=0,this.labelingGroup=Yi,this.marginTop=0,this.marginRight=0,this.marginBottom=0,this.marginLeft=0,this.elevation=0,this.layoutMargins=[0,0,0,0],this.type=n,this.label=t,this.layer=t.layer,this.id=t.id+"_"+n+"_"+Math.floor(i[0]/1e3)+"_"+Math.floor(i[1]/1e3)+this.getIconLabelPriorityToId(t),IP(this.anchorWorld,i,5),this.anchorBaseZ=i[2],this.anchorGeo=t.geoPoint,this.anchorPosition=0,this.anchorSegmentIndex=0,this.halfLabelWidth=0,this.commPriorityRandomFactor=NaN,this.itemPriority=n===Je.Icon?t.iconPriority:t.labelPriority,this.layer.type){case"labelLine":this.labelingGroup=this.layer.style.labelingGroup,this.groupPriority=t.styleTextPriority;break;case"oneWayLine":this.labelingGroup=this.layer.style.labelingGroup,this.groupPriority=this.layer.style.priority;break;case"point":{if(Co(t))if(_u.has(this.label.id))this.commPriorityRandomFactor=_u.get(this.label.id);else{const f=Hm();this.commPriorityRandomFactor=f,_u.set(this.label.id,f)}n===Je.PoiText?(this.labelingGroup=this.layer.style.allowOverlap?Hi:this.layer.style.textLabelingGroup,this.groupPriority=this.layer.style.iconImage?Math.min(t.styleTextPriority,t.styleIconPriority):t.styleTextPriority,this.layoutMargins=Uf(this.layer.style.textLabelingMargin,c)):n===Je.PoiText2?(this.labelingGroup=this.layer.style.allowOverlap?Hi:this.layer.style.textLabelingGroup2,this.groupPriority=Math.min(t.styleTextPriority,t.styleIconPriority),this.layoutMargins=Uf(this.layer.style.textLabelingMargin2,c)):(this.labelingGroup=this.layer.style.allowOverlap?Hi:this.layer.style.iconLabelingGroup,this.groupPriority=t.styleIconPriority,this.layoutMargins=Uf(this.layer.style.iconLabelingMargin,c));break}}this.labelingGroupTable=o.labelingGroups.table,this.overflowStyleZoom=-1/0,this.boxes=[],this.placementIndex=0,this.refresh(r,s,a,l)}refresh(t,n,i,r){const{label:s}=this;if(this.elevation=s.elevation,s.planLevel&&(this.elevation+=s.planLevel*ca(s.geoPoint,r)),this.anchorWorld[2]=this.anchorBaseZ,t!==0&&(this.anchorWorld[2]*=t),i){const a=Lt.fromGeo(this.anchorGeo);this.anchorScreen=n.ecef.project(a,!1)}else this.anchorScreen=n.flat.project([this.anchorWorld[0],this.anchorWorld[1],this.anchorWorld[2]+this.elevation,0]);this.placementIndex=0;const o=this.layoutMargins;this.marginTop=o[0],this.marginRight=o[1],this.marginBottom=o[2],this.marginLeft=o[3],this.adsType=void 0}getIconLabelPriorityToId(t){if(Co(t))return"";const{layer:n}=t;if(n.type==="point"){const i=t.styleIconPriority.toFixed(0),r=t.styleTextPriority.toFixed(0);return"_"+i+"_"+r}return""}}function IP(e,t,n){for(let i=0;i<n;i++)e[i]=t[i]}function $m(e,t,n,i,r,s){if(!e||r&&!s)return[0,0];if(!s)return[e.w/t,e.h/t];const o=Cu(n,i,s),a=si(n.style.iconTextPadding);return[a[3]+a[1]+o[0],a[0]+a[2]+o[1]]}function ul(e,t,n){return Fu(ce(e.style.textFontSize,t),e.style.textLineHeight,n)}function e0(e,t,n){return Fu(ce(e.style.textFontSize2,t),e.style.textLineHeight,n)}function Cu(e,t,n){return Fu(ce(e.style.iconTextFontSize,t),e.style.iconTextLineHeight,n)}function Fu(e,t,n){const r=e/on.baseSize*n.maxWidth,s=e*t*n.lines.length;return[r,s]}function t0(e,t,n,i){var l,c,f,u;const r=(l=i==null?void 0:i[0])!=null?l:e.anchorX,s=(c=i==null?void 0:i[1])!=null?c:e.anchorY,o=(f=n[0])!=null?f:0,a=(u=n[1])!=null?u:0;return[(.5-r)*t[0]+o,(.5-s)*t[1]+a]}function MP(e,t,n){var a,l,c,f;const i=(a=t[0])!=null?a:.5,r=(l=t[1])!=null?l:.5,s=(c=n[0])!=null?c:0,o=(f=n[1])!=null?f:0;return[(.5-i)*e[0]+s,(.5-r)*e[1]+o]}function n0(e,t,n,i,r){var c,f,u,d;const s=(c=n[0])!=null?c:.5,o=(f=n[1])!=null?f:.5,a=(u=r[0])!=null?u:0,l=(d=r[1])!=null?d:0;return[e[0]/2-s*t[0]-i[3]+a,e[1]/2-o*t[1]-i[0]+l]}function dl(e,t,n,i,r){const s=t[0],o=t[1],a=n[0],l=n[1];let c=0,f=0;const u=l/2+o/2,d=l/2-o/2,h=-u,g=-d,y=a/2+s/2,p=a/2-s/2,v=-y,A=-p;switch(e){case"bottomCenter":f=u+r;break;case"rightCenter":c=y+r;break;case"topCenter":f=h-r;break;case"leftCenter":c=v-r;break;case"bottomRight":c=p,f=u+r;break;case"topRight":c=p,f=h-r;break;case"bottomLeft":c=A,f=u+r;break;case"rightBottom":c=y+r,f=g;break;case"rightTop":c=y+r,f=d;break;case"topLeft":c=A,f=h-r;break;case"leftTop":c=v-r,f=d;break;case"leftBottom":c=v-r,f=g;break}return[c+i[0],f+i[1]]}function Lu(e){return!!e&&"stretchX"in e&&Array.isArray(e.stretchX)&&"stretchY"in e&&Array.isArray(e.stretchY)&&"width"in e&&typeof e.width=="number"&&"height"in e&&typeof e.height=="number"}function hl(e,t){const n=t.precomputes;return e.map((i,r)=>{const s=n[r];return s&&s.usage===Qe.Uniform?i:null})}function i0(e){return"raster:"+e}function _P(e){let t=r0.get(e);return t===void 0&&(t="font:"+e,r0.set(e,t)),t}const r0=new Map;function Bu(e,t){var n;return(n=e.resourceVersions.get(t))!=null?n:0}var s0=(e=>(e[e.None=0]="None",e[e.Epoch=1]="Epoch",e[e.Resource=2]="Resource",e[e.Time=3]="Time",e[e.ZoomTiny=4]="ZoomTiny",e[e.Zoom=5]="Zoom",e[e.Pitch=6]="Pitch",e[e.State=7]="State",e))(s0||{});const CP=.001;function FP(e,t){return{deps:e,pitch:t.pitch,state:e.stateKeys.map(n=>[n,t.styleState[n]]),pixelRatio:t.pixelRatio,epoch:t.epoch,resources:e.resources.map(n=>[n,Bu(t,n)]),resourceStamp:t.resourceStamp}}function LP(e,t){const{deps:n}=e;if(e.epoch!==t.epoch||e.pixelRatio!==t.pixelRatio)return 1;if(e.resourceStamp!==t.resourceStamp){for(const[i,r]of e.resources)if(Bu(t,i)!==r)return 2;e.resourceStamp=t.resourceStamp}if(n.time)return 3;if(!I2(n,t.styleZoom))return n.zoomMin===n.zoomMax&&Math.abs(t.styleZoom-n.zoomMin)<CP?4:5;if(n.pitch&&e.pitch!==t.pitch)return 6;for(const[i,r]of e.state)if(!Object.is(r,t.styleState[i]))return 7;return 0}function BP(){return{metricsComputed:0,metricsReused:0,metricsMs:0,axesBuilt:0,axesReused:0,mergeMs:0,pointLayoutsBuilt:0,pointLayoutsReused:0,pointLayoutMs:0,lineLayoutsBuilt:0,lineLayoutsReused:0,lineLayoutMs:0,generationsBuilt:0,generationsReused:0,generationMs:0}}function DP(e,t){if(t!==void 0)for(const n in e){const i=e[n],r=t[n];i!==r&&typeof i=="object"&&typeof r=="object"&&i!==null&&r!==null&&JSON.stringify(i)===JSON.stringify(r)&&(e[n]=r)}}var Du=(e=>(e[e.Icon=0]="Icon",e[e.First=1]="First",e[e.Second=2]="Second",e))(Du||{});const Ou=new uP,Ts=[0,0,0],qn={symbol:"point",sinks:{raster:{stride:36,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.cornerOffset=new Int16Array(t,8),e.views.texCoords=new Uint16Array(t,12),e.views.scales=new Int16Array(t,16),e.views.checkPointOffset=new Int16Array(t,20),e.views.localID=new Uint32Array(t,24),e.views.labelingTextureID=new Uint32Array(t,28),e.views.spritePointTextureID=new Uint32Array(t,32)},packObjectAttributes:(e,t,n,i,r,s)=>Tr([e.styleId,e.layer.innerId,t,n,i,r],s),unpackObjectAttributes:e=>({styleId:e[0],layerId:e[1],animDirection:e[2],atlasIndex:e[3],labelTest:e[4],floorId:e[5],tileData:e.slice(6)})},text:{stride:32,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.cornerOffset=new Int16Array(t,8),e.views.texCoords=new Uint16Array(t,12),e.views.checkPointOffset=new Int16Array(t,16),e.views.localID=new Uint32Array(t,20),e.views.labelingTextureID=new Uint32Array(t,24),e.views.spritePointTextureID=new Uint32Array(t,28)},packObjectAttributes:(e,t,n,i,r,s,o,a)=>Tr([e.styleId,e.layer.innerId,t,n,i[0],-i[1],r,s,o],a),unpackObjectAttributes:e=>({styleId:e[0],layerId:e[1],animDirection:e[2],range:e[3],offsetX:e[4],offsetY:e[5],labelIndex:e[6],fontName:e[7],floorId:e[8],tileData:e.slice(9)})},labelingTexture:{stride:16,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.cornerOffset=new Int16Array(t,8),e.views.labelingTextureID=new Uint32Array(t,12)},packObjectAttributes:(e,t=[0,0])=>Tr([e.styleId,e.layer.innerId,t[0],-t[1],e.floorId],[]),unpackObjectAttributes:e=>({styleId:e[0],layerId:e[1],offsetX:e[2],offsetY:e[3],floorId:e[4],tileData:e.slice(5)})}},processElement(e,t,n,i,r,s,o,a){var D;const{layer:l,label:c}=n;if(l.type!=="point")return;const f=dn(s.styleZoom,s.pitch,s.styleState,!0,c.tileData);Da("_activeFloorIds");const u=s.styleState._activeFloorIds.length>0,d=Co(c)&&!u?"":c.floorId,h=o0(f,e,r,c),g=e.icons[Mt(l.style.iconImage,f)],y=Lu(g),p=$m(h,r,l,f,y,c.iconTextMetrics),v=si(l.style.iconTextOffset),A=si(l.style.iconTextPadding);let w,S=[0,0],T=[S];if(h)if(c.iconTextMetrics){const F=Vi(l.style.iconTextAnchor);w=Cu(l,f,c.iconTextMetrics),T=[];for(const z of F)T.push(n0(p,w,z,A,v));S=T[0]}else{const F=si(l.style.iconOffset);T=Vi(l.style.iconAnchor).map(N=>t0(h,p,F,N)),S=T[0]}Dt(Ts,n.anchorWorld,o);const{globeInterStartZoom:I}=dr;if(!(s.globeMode&&s.zoom<I)&&!no(Ts))return;const M=gm(s.globeMode,s.styleState,o)?(F,z)=>Zn(o,F,z):void 0;let B=[0,0];if(T.length>1&&n.placementIndex>0){const F=n.type===Je.Icon?n:n.parent;if(F&&F.boxes.length>1){const z=F.boxes[0],N=F.boxes[n.type===Je.Icon?n.placementIndex:F.placementIndex];N&&(B=[(N[0]+N[2])/2-(z[0]+z[2])/2,(N[1]+N[3])/2-(z[1]+z[3])/2],S=[T[0][0]+B[0],T[0][1]+B[1]])}}switch(n.type){case Je.Icon:if(!h||y&&!c.iconTextMetrics)return;const F=y?g.stretchX:void 0,z=y?g.stretchY:void 0;if(Ru(t,c,d,Ts,i,h,p[0]*r,p[1]*r,S[0]*r,S[1]*r,r,F==null?void 0:F.map(([P,b])=>[P*r,b*r]),z==null?void 0:z.map(([P,b])=>[P*r,b*r]),M),!w)return;const N=Vi(l.style.iconTextAnchor),H=(D=N[n.placementIndex])!=null?D:N[0],K=MP(w,H,v);OP(e,t,c,d,Ts,s,i,K,l,r,M);return;case Je.PoiText:RP(e,t,n,d,Ts,p,s,i,S,l,r,M);return;case Je.PoiText2:zP(e,t,n,d,Ts,p,s,i,S,l,r,M);return}},getLabelingInfo(e,t,n,i,r,s){const{layer:o}=e;if(o.type!=="point")return;e.labelingElements=[];const a=dn(i.styleZoom,i.pitch,i.styleState,!0,e.tileData),l=o0(a,n,s,e),c=n.icons[Mt(o.style.iconImage,a)],f=Lu(c),u=$m(l,s,o,a,f,e.iconTextMetrics);let d,h=[0,0],g=[h];if(l&&(!f||e.iconTextMetrics)){if(e.iconTextMetrics){const A=Vi(o.style.iconTextAnchor),w=si(o.style.iconTextOffset),S=si(o.style.iconTextPadding);d=Cu(o,a,e.iconTextMetrics),g=[];for(const T of A)g.push(n0(u,d,T,S,w));h=g[0]}else{const A=si(o.style.iconOffset);g=Vi(o.style.iconAnchor).map(S=>t0(l,u,A,S)),h=g[0]}const v=new fl(e,Je.Icon,t,i.buildingHeight,r,n,i.globeMode,i.styleState._floorHeight,a);for(const[A,w]of g)v.boxes.push([-u[0]/2+A,-u[1]/2+w,u[0]/2+A,u[1]/2+w]);e.labelingElements.push(v)}const y=Mt(o.style.textFont,a);e.label.length>0&&y.length&&(GP(e,t,n,u,i,r,g,o),e.label2&&kP(e,t,n,u,i,r,g,o))}};function OP(e,t,n,i,r,s,o,a,l,c,f){const{iconTextMetrics:u}=n;if(!u||!l.style.iconTextFont)return;const d=dn(s.styleZoom,s.pitch,s.styleState,!1,n.tileData),h=Mt(l.style.iconTextFont,d);pl(t,n,i,0,u,r,o,a,l,h,c,f)}function RP(e,t,n,i,r,s,o,a,l,c,f,u){const{label:d}=n,{textMetrics:h}=d,g=dn(o.styleZoom,o.pitch,o.styleState,!1,d.tileData),y=Mt(c.style.textFont,g);if(!y.length)return;const p=ul(c,g,h),v=n.parent?Ga(c.style.textPlacement,g):"centerCenter",A=ce(c.style.textOffset,g),w=dl(v,s,p,l,A);pl(t,d,i,1,d.textMetrics,r,a,w,c,y,f,u)}function zP(e,t,n,i,r,s,o,a,l,c,f,u){var I;const{label:d}=n,{textMetrics:h,textMetrics2:g}=d;if(!g||!c.style.textFont2)return;const y=dn(o.styleZoom,o.pitch,o.styleState,!1,d.tileData),p=Mt(c.style.textFont2,y);if(!p.length)return;const v=ul(c,y,h),A=e0(c,y,g),w=ce(c.style.textOffset,y),S=ce((I=c.style.textOffset2)!=null?I:0,y,0),T=dl(Ga(c.style.textPlacement,y),s,[A[0],v[1]],l,w);T[1]+=(v[1]+A[1])/2+S,pl(t,d,i,2,g,r,a,T,c,p,f,u)}function pl(e,t,n,i,r,s,o,a,l,c,f,u){if(i===1&&t.labelingElements.length===1){const h=e.getBucket("point","labelingTexture",qn.sinks.labelingTexture.packObjectAttributes(t),qn.sinks.labelingTexture.binder);VP(h,s,r,l,f,t.labelingTextureIndex,t.checkPointOffset)}const d={};for(const h of t.ranges)d[h]=e.getBucket("point","text",qn.sinks.text.packObjectAttributes(t,o,h,a,i,c,n,hl(t.tileData,l)),qn.sinks.text.binder);UP(d,t,s,r,l,i,t.checkPointOffset,u)}function NP(e,t,n,i,r,s,o,a){return Ru(e,t,n,i,r,s,s.w,s.h,s.w*(.5-s.anchorX),s.h*(.5-s.anchorY),o,void 0,void 0,a)}function Ru(e,t,n,i,r,s,o,a,l,c,f,u,d,h){if(o<=0||a<=0)return;const g=t.layer;if(g.type!=="point")return;lP(Ou,Yt,s,o,a,l,c,u,d),e.atlasPacker.addRastersToLoad(t.styleId,s);const y=e.getBucket("point","labelingTexture",qn.sinks.labelingTexture.packObjectAttributes(t),qn.sinks.labelingTexture.binder);fP(i[0],i[1],i[2],Ou,y,f,t.labelingTextureIndex,t.checkPointOffset);const p=e.getBucket("point","raster",qn.sinks.raster.packObjectAttributes(t,r,s.atlasIndex,u!==void 0||d!==void 0,n,hl(t.tileData,g)),qn.sinks.raster.binder);cP(i[0],i[1],i[2],Ou,p,-1/0,1/0,t.identifyIndex,t.labelingTextureIndex,t.spritePointTextureIndex,t.checkPointOffset,h)}function GP(e,t,n,i,r,s,o,a){const{textMetrics:l}=e;if(!l)return;const c=dn(r.styleZoom,r.pitch,r.styleState,!1,e.tileData),f=ce(a.style.textOffset,c),u=ul(a,c,l),d=new fl(e,Je.PoiText,t,r.buildingHeight,s,n,r.globeMode,r.styleState._floorHeight,c);e.labelingElements.length>0&&(d.parent=e.labelingElements[0]);const h=d.parent?Ga(a.style.textPlacement,c):"centerCenter";for(const g of o){const y=dl(h,i,u,g,f);d.boxes.push([y[0]-u[0]/2,y[1]-u[1]/2,y[0]+u[0]/2,y[1]+u[1]/2])}e.labelingElements.push(d)}function kP(e,t,n,i,r,s,o,a){var v;const{textMetrics:l,textMetrics2:c}=e;if(!c)return;const f=dn(r.styleZoom,r.pitch,r.styleState,!1,e.tileData),u=ul(a,f,l),d=e0(a,f,c),h=ce(a.style.textOffset,f),g=ce((v=a.style.textOffset2)!=null?v:0,f,0),y=new fl(e,Je.PoiText2,t,r.buildingHeight,s,n,r.globeMode,r.styleState._floorHeight,f);e.labelingElements.length>1?(y.parent=e.labelingElements[0],y.firstLabel=e.labelingElements[1]):e.labelingElements.length>0&&(y.parent=e.labelingElements[0],y.firstLabel=e.labelingElements[0]);const p=Ga(a.style.textPlacement,f);for(const A of o){const w=dl(p,i,[d[0],u[1]],A,h);w[1]+=(u[1]+d[1])/2+g,y.boxes.push([w[0]-d[0]/2,w[1]-d[1]/2,w[0]+d[0]/2,w[1]+d[1]/2])}e.labelingElements.push(y)}function o0(e,t,n,i){const{rasterSets:r}=t,{layer:s}=i;if(s.type!=="point")return;let o;const a=Co(i);if(a||i.pointType===zt.Landmark)o=Df(i.id,a?"commercial":"landmark");else{const c=Mt(s.style.iconImage,e);if(c.length){const f=co(s.style.iconAnchor);o=ss(c,f[0],f[1])}}if(o===void 0)return;gg(i0(o));const l=r.byKey[o];if(l){const c=ce(s.style.iconWidth,e),f=os(l.rasters,c*n,!0);if(f!==void 0)return l.rasters[f]}}const gl=[0,0];function UP(e,t,n,i,r,s,o,a){let{textLineHeight:f,textLetterSpacing:u}=r.style;s===Du.Icon&&(f=r.style.iconTextLineHeight,u=r.style.iconTextLetterSpacing);const{identifyPoiLabelIndex:d,labelingTextureIndex:h,spritePointTextureIndex:g}=t,{lines:y,maxWidth:p}=i,v=f*on.baseSize;let A=a0(1,v,y.length);for(let w=0;w<y.length;w++){const S=y[w].width;let T=0;T=-S/2,gl[0]=T,gl[1]=A;const I=y[w].glyphs;for(let C=0;C<I.length;C++){const M=I[C];M.bitmap!==void 0&&XP(e[M.range],n,gl,M,d,h,g,o,a),gl[0]+=M.advance+on.baseSize*u}A-=v}}function VP(e,t,n,i,r,s,o){const{lines:a,maxWidth:l}=n;if(!a.length){o[0]=0,o[1]=0;return}const{textLineHeight:c}=i.style,f=c*on.baseSize,u=-l/2,d=a0(1,f,a.length),h=l/2,g=d-(a.length-1)*f;o[0]=r*(u+h)/2,o[1]=r*(d+g)/2;const y=r*Dc/2,p=o[0]-y,v=o[0]+y,A=o[1]+y,w=o[1]-y,S=e.elements.offset;Fo(e.indices,S,1,0,3,2,3,0),vl(e,t,p,A,s),vl(e,t,v,A,s),vl(e,t,p,w,s),vl(e,t,v,w,s)}function WP(e,t,n,i,r,s,o){const a=n[1]+i.top,l=n[0]+i.left,c=a-i.height,f=l+i.width,u=Math.sin(r),d=Math.cos(r),h=l*d-a*u,g=l*u+a*d,y=f*d-a*u,p=f*u+a*d,v=l*d-c*u,A=l*u+c*d,w=f*d-c*u,S=f*u+c*d,T=e.elements.offset;yl(e,t,h,g,i.texLeft,i.texTop,s,o),yl(e,t,y,p,i.texRight,i.texTop,s,o),yl(e,t,v,A,i.texLeft,i.texBottom,s,o),yl(e,t,w,S,i.texRight,i.texBottom,s,o),Fo(e.indices,T,1,0,3,2,3,0)}function HP(e,t,n,i,r){const s=e.elements.offset,o=at(Math.cos(i)),a=at(Math.sin(i));xl(e,t,n,o,a,-1,-1,r),xl(e,t,n,o,a,1,-1,r),xl(e,t,n,o,a,1,1,r),xl(e,t,n,o,a,-1,1,r),Fo(e.indices,s,0,1,2,2,3,0)}function YP(e,t,n,i,r,s,o,a){const l=s.top,c=-s.width/2,f=l-s.height,u=s.width/2,d=e.elements.offset;wl(e,t,n,i,r,c,l,-s.height,s.texLeft,s.texTop,o,a),wl(e,t,n,i,r,u,l,-s.height,s.texRight,s.texTop,o,a),wl(e,t,n,i,r,c,f,s.height,s.texLeft,s.texBottom,o,a),wl(e,t,n,i,r,u,f,s.height,s.texRight,s.texBottom,o,a),Fo(e.indices,d,1,0,3,2,3,0)}function a0(e,t,n){let i;switch(e){case 0:i=t/2+t*(n-1);break;case 2:i=-t/2;break;default:i=n&1?t*(n>>1):t/2+t*(n-1>>1)}return i}function XP(e,t,n,i,r,s,o,a,l){const c=n[1]+i.top,f=n[0]+i.left,u=c-i.height,d=f+i.width,[h,g]=a,y=e.elements.offset;ml(e,t,f,c,i.texLeft,i.texTop,h,g,r,s,o,l),ml(e,t,d,c,i.texRight,i.texTop,h,g,r,s,o,l),ml(e,t,f,u,i.texLeft,i.texBottom,h,g,r,s,o,l),ml(e,t,d,u,i.texRight,i.texBottom,h,g,r,s,o,l),Fo(e.indices,y,1,0,3,2,3,0)}function ml(e,t,n,i,r,s,o,a,l,c,f,u){const d=e.elements,h=d.stride*d.offset>>1,g=h>>1;if(u!==void 0){const{x:y,y:p,z:v}=u(t[0],t[1]);e.views.position[h]=y,e.views.position[h+1]=p,e.views.position[h+2]=v}else e.views.position[h]=W+t[0],e.views.position[h+1]=W+t[1],e.views.position[h+2]=Wt(t[2]);e.views.cornerOffset[h]=n,e.views.cornerOffset[h+1]=i,e.views.checkPointOffset[h]=o,e.views.checkPointOffset[h+1]=a,e.views.texCoords[h]=r,e.views.texCoords[h+1]=s,e.views.localID[g]=l,e.views.labelingTextureID[g]=c,e.views.spritePointTextureID[g]=f,d.offset++}function vl(e,t,n,i,r){const s=e.elements,o=s.stride*s.offset>>1;e.views.position[o]=W+t[0],e.views.position[o+1]=W+t[1],e.views.position[o+2]=Wt(t[2]),e.views.cornerOffset[o]=n,e.views.cornerOffset[o+1]=i,e.views.labelingTextureID[o>>1]=r,s.offset++}function yl(e,t,n,i,r,s,o,a){const l=e.elements;let c=l.stride*l.offset>>1;e.views.position[c]=W+t[0],e.views.position[c+1]=W+t[1],e.views.position[c+2]=Wt(t[2]),e.views.texCoords[c]=r,e.views.texCoords[c+1]=s,c=c>>1,e.views.cornerOffset[c]=n,e.views.cornerOffset[c+1]=i,e.views.styleZoomLimits[c]=o,e.views.styleZoomLimits[c+1]=a,l.offset++}function xl(e,t,n,i,r,s,o,a){let c=e.elements.stride*e.elements.offset/e.views.direction.BYTES_PER_ELEMENT;e.views.direction[c]=i,e.views.direction[c+1]=r,e.views.widenDirection[c]=s,e.views.widenDirection[c+1]=o,c>>=1,e.views.position[c]=W+t[0],e.views.position[c+1]=W+t[1],c>>=1,"height"in e.views&&(e.views.height[c]=t[2]*io/He),"absZ"in e.views&&(e.views.absZ[c]=n),"labelingTextureID"in e.views&&(e.views.labelingTextureID[c]=a),e.elements.offset++}function wl(e,t,n,i,r,s,o,a,l,c,f,u){const d=e.elements;let h=d.stride*d.offset>>1;e.views.texCoords[h]=l,e.views.texCoords[h+1]=c,e.views.anchorParams[h]=t*He,e.views.anchorParams[h+1]=r,e.views.guidelineParams[h]=n,e.views.guidelineParams[h+1]=i,h=h>>1,e.views.centerOffset[h]=f,e.views.cornerOffset[h]=s,e.views.cornerOffset[h+1]=o,e.views.glyphHeightOffset[h]=a,e.views.labelingTextureID[h]=u,d.offset++}function Fo(e,t,n,i,r,s,o,a){const l=e.buffer,c=e.offset;l[c]=t+n,l[c+1]=t+i,l[c+2]=t+r,l[c+3]=t+s,l[c+4]=t+o,l[c+5]=t+a,e.offset=c+6}const Lo=[0,0,0],xi=[0,0],Br={symbol:"labelLine",sinks:{raster:{stride:28,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.texCoords=new Uint16Array(t,8),e.views.cornerOffset=new Float32Array(t,12),e.views.styleZoomLimits=new Float32Array(t,20)},packObjectAttributes:(e,t,n,i,r,s)=>Tr([e.styleId,e.layer.innerId,t,n,i,r],s),unpackObjectAttributes(e){return{styleId:e[0],layerId:e[1],animDirection:e[2],range:e[3],fontName:e[4],tiers:e[5],tileData:e.slice(6)}}},billboard:{stride:32,binder:(e,t)=>{e.views.texCoords=new Uint16Array(t),e.views.anchorParams=new Uint16Array(t,4),e.views.guidelineParams=new Uint16Array(t,8),e.views.centerOffset=new Float32Array(t,12),e.views.cornerOffset=new Float32Array(t,16),e.views.labelingTextureID=new Uint32Array(t,24),e.views.glyphHeightOffset=new Float32Array(t,28)},packObjectAttributes:(e,t,n,i,r,s,o)=>Tr([e.styleId,e.layer.innerId,t,n,i,r,s],o),unpackObjectAttributes(e){return{styleId:e[0],layerId:e[1],animDirection:e[2],range:e[3],fontName:e[4],replicaIndex:e[5],subIndex:e[6],tileData:e.slice(7)}}}},processElement(e,t,n,i,r,s,o,a){n.label.screenSpace?QP(t,n,i,s,o,a):jP(t,n,i,s,o)},getLabelingInfo(){}};function ZP(e,t,n,i){const r=e.interpolate(t-n,e.getSegmentIndex(t-n)),s=e.interpolate(t+n,e.getSegmentIndex(t+n)),o=Math.atan2(s[1]-r[1],s[0]-r[0])-i;return Math.cos(o)<0}function jP(e,t,n,i,r){if(t.layer.type!=="labelLine")return;const{label:s,anchorPosition:o,anchorSegmentIndex:a,halfLabelWidth:l,layer:c}=t,{axis:f}=s,{center:u,styleZoom:d,pitch:h}=i,g=dn(d,h,i.styleState,!1,s.tileData),y=Mt(c.style.textFont,g),p={},v=k(c.ignoreTier,g)?null:s.tiers;for(const I of s.ranges)p[I]=e.getBucket("labelLine","raster",Br.sinks.raster.packObjectAttributes(s,n,I,y,v!=null?v:null,hl(s.tileData,c)),Br.sinks.raster.binder);const A=s.textMetrics.lines[0],w=ce(c.style.textFontSize,g)/on.baseSize,S=A.glyphs,T=ZP(f,o,l,i.rotation);xi[0]=-A.width/2,xi[1]=0;for(let I=0;I<S.length;I++){const C=S[I],M=(xi[0]+C.left+C.width/2)*w*(T?-1:1),B=$o(M)||1;let D=-1/0,F=1/0;for(let z=a;z>=1&&z<f.vertexCount&&!(F<t.overflowStyleZoom);z+=B,F=D){const N=B===1?z:z-1;D=Mp(Ap(M,f.lengths[N]-o),u);const H=f.interpolate(o,z);Dt(Lo,H,r),no(Lo)&&C.bitmap!==void 0&&WP(p[C.range],Lo,xi,C,H[4]+(T?Math.PI:0),Math.max(D,t.overflowStyleZoom),F)}xi[0]+=C.advance+on.baseSize*c.style.textLetterSpacing}}function QP(e,t,n,i,r,s){var C,M;if(t.layer.type!=="labelLine")return;const{label:o,anchorPosition:a,anchorSegmentIndex:l,layer:c}=t,{axis:f}=o,{styleZoom:u,pitch:d}=i,h=dn(u,d,i.styleState,!1,o.tileData),g=Mt(c.style.textFont,h),y=KP(e,o,n,g,s,c),p=f.interpolate(a,l);if(Dt(Lo,p,r),!no(Lo))return;const v=o.textMetrics.lines[0],A=v.glyphs;xi[0]=-v.width/2,xi[1]=0;const w=f.lengths[l-1],T=f.lengths[l]-w,I=T>0?(a-w)/T:0;for(let B=0;B<A.length;B++){const D=A[B];if(D.bitmap!==void 0){const F=y(D.range,t.label.axis),z=xi[0]+D.left+D.width/2;let N=F.meta;N||(N=F.meta={});let H=N.guidelines;H||(H=N.guidelines=[]);let K=F.utils;K||(K=F.utils={});let P=K.guidelineStorage;P||(P=K.guidelineStorage=new Map);let b=P.get(t.label.axis);if(b===void 0){const x=qP(f,r);b=H.push(x)-1,P.set(t.label.axis,b)}const E=((M=(C=H[b])==null?void 0:C.length)!=null?M:0)/4;YP(F,I,b,E,l,D,z,o.labelingTextureIndex)}xi[0]+=D.advance+on.baseSize*c.style.textLetterSpacing}}const Al=[0,0,0],bl=[0,0,0];function qP(e,t){const n=new Float32Array(e.line.length);for(let i=0;i<e.vertexCount;i++){const r=i*4;Al[0]=e.line[r],Al[1]=e.line[r+1],Al[2]=e.line[r+2],Dt(bl,Al,t),n[r]=(W+bl[0])/He,n[r+1]=(W+bl[1])/He,n[r+2]=bl[2]*io/He,n[r+3]=e.line[r+3]}return n}function KP(e,t,n,i,r,s){const o={};return(a,l)=>{var u;if(o[a]!==void 0)return o[a];let c=0,f;do{const d=e.getBucket("labelLine","billboard",Br.sinks.billboard.packObjectAttributes(t,n,a,i,r,c,hl(t.tileData,s)),Br.sinks.billboard.binder),h=(u=d.utils)==null?void 0:u.guidelineStorage;if(!h||h.has(l)||h.size<Hc){f=d;break}c++}while(!f);return o[a]=f,f}}const zu=[0,0,0],Dr={symbol:"oneWayLine",sinks:{raster:{stride:12,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.direction=new Int8Array(t,8),e.views.widenDirection=new Int8Array(t,10)},packObjectAttributes:(e,t,n)=>Tr([e.styleId,e.layer.innerId,t,n],e.tileData),unpackObjectAttributes:e=>({styleId:e[0],layerId:e[1],animDirection:e[2],tiers:e[3],tileData:e.slice(4)})},billboard:{stride:20,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.height=new Float32Array(t,4),e.views.absZ=new Float32Array(t,8),e.views.direction=new Int8Array(t,12),e.views.widenDirection=new Int8Array(t,14),e.views.labelingTextureID=new Uint32Array(t,16)},packObjectAttributes:(e,t)=>Tr([e.styleId,e.layer.innerId,t],e.tileData),unpackObjectAttributes:e=>({styleId:e[0],layerId:e[1],animDirection:e[2],tileData:e.slice(3)})}},processElement(e,t,n,i,r,s,o,a){var u;const{label:l,anchorWorld:c}=n;if(Dt(zu,c,o),!no(zu))return;const f=l.screenSpace?t.getBucket("oneWayLine","billboard",Dr.sinks.billboard.packObjectAttributes(l,i),Dr.sinks.billboard.binder):t.getBucket("oneWayLine","raster",Dr.sinks.raster.packObjectAttributes(l,i,(u=l.tiers)!=null?u:null),Dr.sinks.raster.binder);HP(f,zu,c[3],c[4],l.labelingTextureIndex)},getLabelingInfo(){}},Or={symbol:"heatmap",sinks:{fill:{stride:8,binder:(e,t)=>{e.views.position=new Float32Array(t)},packObjectAttributes:(e,t,n,i)=>[e,t.innerId,n,i],unpackObjectAttributes:e=>({styleId:e[0],layerId:e[1],textureIndex:e[2],rampTextureIndex:e[3],tileData:e.slice(4)})},framebuffer:{stride:12,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.weight=new Float32Array(t,4),e.views.widen=new Int8Array(t,8)},packObjectAttributes:(e,t)=>[e,t],unpackObjectAttributes:e=>({styleId:e[0],layerId:e[1],tileData:e.slice(2)})}},generate(e,t,n,i,r){const s=i.x,o=i.y,a=Number(k(n.style.weight,r));if(Number.isNaN(a)){console.error("Can't resolve style.weight to number");return}const l=e.getBucket(n.type,"framebuffer",Or.sinks.framebuffer.packObjectAttributes(t,n.innerId),Or.sinks.framebuffer.binder);for(let c=0;c<s.length;c++)$P(l,0,1,2,2,1,3),El(l,s[c],o[c],-1,-1,a),El(l,s[c],o[c],1,-1,a),El(l,s[c],o[c],-1,1,a),El(l,s[c],o[c],1,1,a)},generateTexture(e,t,n,i,r){const s=[-1,1,1,-1],o=[-1,-1,1,1],a=e.getBucket(n.type,"fill",Or.sinks.fill.packObjectAttributes(t,n,i,r),Or.sinks.fill.binder);let l=a.elements.offset;JP(a.indices,l,0,1,2,0,2,3),Sl(a,l++,s[0],o[0]),Sl(a,l++,s[1],o[1]),Sl(a,l++,s[2],o[2]),Sl(a,l++,s[3],o[3]),a.elements.offset=l}};function Sl(e,t,n,i){const r=t*2;e.views.position[r]=n,e.views.position[r+1]=i}function JP(e,t,n,i,r,s,o,a){const l=e.buffer,c=e.offset;l[c]=t+n,l[c+1]=t+i,l[c+2]=t+r,l[c+3]=t+s,l[c+4]=t+o,l[c+5]=t+a,e.offset=c+6}function El(e,t,n,i,r,s){const o=e.elements.offset*e.elements.stride,a=o>>1,l=a>>1;e.views.position[a]=W+t,e.views.position[a+1]=W+n,e.views.weight[l]=s,e.views.widen[o]=i,e.views.widen[o+1]=r,e.elements.offset++}function $P(e,t,n,i,r,s,o){const{elements:a,indices:l}=e,{buffer:c,offset:f}=l,u=a.offset;c[f]=u+t,c[f+1]=u+n,c[f+2]=u+i,c[f+3]=u+r,c[f+4]=u+s,c[f+5]=u+o,l.offset=f+6}const eI=new Set(np),tI=new Set(Vc),nI=new Set(Wc),iI=new Set(rp),rI=new Set(sp),sI=new Set(ip);function Tl(e){return eI.has(e)}function l0(e){return tI.has(e)}function c0(e){return nI.has(e)}function oI(e){return iI.has(e)}function f0(e){return rI.has(e)}function u0(e){return sI.has(e)}const d0=(e,t,n,i,r,s,o,a,l,c,f)=>{var F,z,N,H;const{tileProps:u,tileAttrs:d}=i;if(aI(e,t,n,i,c,f),f)return;let h=zt.Common;const g=d[u.db_sublayer];l0(g)?h=zt.CommercialCity:c0(g)?h=zt.CommercialPremium:Tl(g)?h=zt.Commercial:f0(g)&&(h=zt.Landmark);const y=l.x.length===1?ji.Point:ji.Line;let p=[],v;if(y===ji.Point){if(i&&n.style.allowElevation){const K=ce(n.style.elevation,i);if(Number.isNaN(K))typeof l.z!="undefined"&&(l.z=[s<4?Jp(l.z[0]):l.z[0]]);else{const P=K*Ee*fn(Bt(o),[l.x[0],l.y[0]]);l.z=[P]}}p=[[l.x[0]],[l.y[0]],typeof l.z!="undefined"?[l.z[0]]:[0]],v=[0,0,0],St(v,[p[0][0],p[1][0],p[2][0]],Bt(o))}else p=[l.x,l.y];const A=(F=i.id)!=null?F:"",w=(z=d[u.db_plan_id])!=null?z:"",S=(N=d[u.db_plan_level])!=null?N:NaN;let T=Ft,I=Ft;Number.isNaN(A)||(T=e.idIndexer.getIndex(i,t.id,n,{objectClass:d[u.db_object_class],instanceId:0,metatile:r,center:v,floorId:w,ignoreHover:!0}),I=e.idIndexer.getIndex(i,t.id,n,{objectClass:d[u.db_object_class],instanceId:1,metatile:r,center:v,floorId:w,ignoreHover:!0}));const C=d[u.db_point_building_id],M=e.pointIndexer.getIndexById(w||C),B=e.pointIndexer.getIndexById(A),D={type:Qn.Point,pointType:h,geometryType:y,styleId:t.id,layerId:n.innerId,sourceId:a,tileCoords:o,id:(H=i.id)!=null?H:"",floorId:w,planLevel:S,identifyIndex:T,identifyPoiLabelIndex:I,labelingTextureIndex:M,spritePointTextureIndex:B,labelPriority:Nt(d[u.db_label_priority],0),label2Priority:Nt(d[u.db_label2_priority],0),styleIconPriority:ce(n.style.iconPriority,i),styleTextPriority:ce(n.style.textPriority,i),iconPriority:Nt(d[u.db_icon_priority],0),hovered:Nt(d[u.hovered],0),componentDistanceStart:Nt(d[u.componentDistanceStart],0),componentDistanceEnd:Nt(d[u.componentDistanceEnd],0),objectLength:Nt(d[u.objectLength],0),vertices:p,demElevation:NaN,tileData:[...i.tileData]};e.addLabel(D)};function aI(e,t,n,i,r,s){var y;const{tileProps:o,tileAttrs:a}=i,{rasterSets:l,icons:c}=t,f=Wf(r),u=Fr(n.style.iconWidth),d=Tl(a[o.db_sublayer]),h=f0(a[o.db_sublayer]),g=co(n.style.iconAnchor);if(d||h){if(s)return;const p=d?Rc.rasterSizes:op,v=m2((y=i.id)!=null?y:"",p,a[o.db_region],g,d?"commercial":"landmark",o.url_src?a[o.url_src]:void 0);e.atlasPacker.addNewRasterSet(t.id,v),e.atlasPacker.pack(v,u,f)}else Fr(n.style.iconImage).forEach(p=>{if(!p.length)return;const v=l.byKey[ss(p,g[0],g[1])];if(!v){console.error(`Not found raster set with image ${p}, anchorX: ${g[0]}, anchorY: ${g[1]}`);return}if(!v.isSvg)return;const A=c[p],w=A&&Lu(A)?[{w:A.width,h:A.height}]:u.map(S=>({w:S,h:S}));e.atlasPacker.packSvg(v,w,f),s&&v.rasters.forEach(S=>e.atlasPacker.addRastersToLoad(t.id,S))})}const lI=(e,t,n,i,r,s,o)=>{var d;const a=k(n.ignoreTier,s)?void 0:s.tileAttrs[s.tileProps.db_tiers],l=(d=s.id)!=null?d:"",f=k(n.style.mode,s)==="viewport"&&s.styleState.terrainEnabled!==!0&&!s.needFallbackScreenLabels,u={type:Qn.Line,styleId:t,layerId:n.innerId,sourceId:r,tileCoords:i,id:l,floorId:s.tileAttrs[s.tileProps.db_plan_id]||"",planLevel:s.tileAttrs[s.tileProps.db_plan_level]||NaN,componentDistanceStart:Nt(s.tileAttrs[s.tileProps.componentDistanceStart],0),componentDistanceEnd:Nt(s.tileAttrs[s.tileProps.componentDistanceEnd],0),objectLength:Nt(s.tileAttrs[s.tileProps.objectLength],0),labelPriority:Nt(s.tileAttrs[s.tileProps.db_label_priority],0),styleIconPriority:ce(n.style.textPriority,s),styleTextPriority:ce(n.style.textPriority,s),vertices:[o.x,o.y],tileData:[...s.tileData],tiers:a,screenSpace:f,labelingTextureIndex:e.pointIndexer.getIndexById(l)};if(!f||!a||!a.length||s.styleState.immersiveRoadsOn!==!0){e.addLabel(u);return}a.forEach(h=>{e.addLabel(ie(V({},u),{tiers:[h],vertices:[...u.vertices],labelingTextureIndex:e.pointIndexer.getIndexByTier(h)}))})},cI=(e,t,n,i,r,s,o)=>{var g;const{tileProps:a,tileAttrs:l}=s,c=(g=s.id)!=null?g:"",f=k(n.ignoreTier,s)?null:l[a.db_tiers],d=k(n.style.mode,s)==="viewport"&&s.styleState.terrainEnabled!==!0&&!s.needFallbackScreenLabels,h={type:Qn.OneWayLine,styleId:t,layerId:n.innerId,sourceId:r,tileCoords:i,id:c,floorId:s.tileAttrs[s.tileProps.db_plan_id]||"",planLevel:s.tileAttrs[s.tileProps.db_plan_level]||NaN,componentDistanceStart:Nt(s.tileAttrs[s.tileProps.componentDistanceStart],0),componentDistanceEnd:Nt(s.tileAttrs[s.tileProps.componentDistanceEnd],0),objectLength:Nt(s.tileAttrs[s.tileProps.objectLength],0),labelPriority:Nt(s.tileAttrs[s.tileProps.db_label_priority],0),styleIconPriority:ce(n.style.priority,s),styleTextPriority:0,vertices:[o.x,o.y],tileData:[...s.tileData],tiers:f,screenSpace:d,labelingTextureIndex:e.pointIndexer.getIndexById(c)};if(!d||!f||!f.length||s.styleState.immersiveRoadsOn!==!0){e.addLabel(h);return}f.forEach(y=>{e.addLabel(ie(V({},h),{tiers:[y],vertices:[...h.vertices],labelingTextureIndex:e.pointIndexer.getIndexByTier(y)}))})};function fI(e,t,n){return eo(n.fontUrlTemplate,{name:e,range:String(t)})}function Pl(e,t,n){const i=wi(e)?e:qi(t.iconBaseUrl,e);return eo(i,{subdomain:n,appHost:window.location.host})}function uI(e,t){return wi(e)?e:qi(t.modelsBaseUrl,e)}function dI(e,t,n,i){return wi(e)?e:m0(e)?n?Qr(e,{sharedModelsPath:n}):"":t?m0(t)?Qr(t,{modelSrc:e,subdomain:Xp(i)}):qi(t,e):e}function h0(e,t,n){return e.replace("image",`image_${t}x${n}`)}const p0=/_i$/;function hI(e){return p0.test(e)}function g0(e){return e.replace(p0,"")}function pI(e,t){const n=wi(t.fontsPath)?t.fontsPath:qi(t.rootUrl,t.fontsPath),i="{name}_{range}.pbf";e.fontUrlTemplate=qi(n,i),e.iconBaseUrl=wi(t.iconsPath)?t.iconsPath:qi(t.rootUrl,t.iconsPath),e.modelsBaseUrl=wi(t.modelsPath)?t.modelsPath:qi(t.rootUrl,t.modelsPath)}function gI(e){return wi(e.stylePath)?e.stylePath:qi(e.rootUrl,e.stylePath)}const mI=new RegExp("^(?:(?:[a-z]+:)?(?:[a-z]+:)?//|data:)","i");function wi(e){return mI.test(e)}function m0(e){return/{\w+}/g.test(e)}function qi(...e){const t=e.filter(i=>i.length>0);let n=t[0];for(let i=1;i<t.length;i++){n[n.length-1]!=="/"&&(n+="/");const r=t[i];r[0]==="/"?n+=r.slice(1):n+=r}return n}function v0(e,t,n){const i=co(n.style.iconAnchor),r=ss(e,i[0],i[1]);return t.rasterSets.byKey[r]}function vI(e,t,n,i){const r=t.icons[n.name];if(!r)return;const s=os(n.rasters,i*window.devicePixelRatio,!0);if(s===void 0)return;const o=Pl(r.url,t,ha(e.map.state.subdomains,n.name)),{w:a,h:l}=n.rasters[s];return{fullUrl:o,name:n.name,width:a,height:l}}function yI(e,t,n,i){const r=g0(i),s=v0(r,t,n);if(!s)return;const o=t.icons[s.name];if(o)return Pl(o.url,t,ha(e.map.state.subdomains,s.name))}function y0(e,t,n,i,r){const s=n.style.iconMetaphorImage;if(s!==void 0){const o=Mt(s,i);if(o){const a=t.icons[o];a&&(r.iconMetaphorImage=Pl(a.url,t,ha(e.map.state.subdomains,o)))}}n.metadata!==void 0&&(r.metaData=n.metadata)}function xI(e,t,n){const i=e.styleManager.getStyle(e.map.state.handyStyleId);if(!i)return;const r=i.layersById[t.layerId];if(!r)return;const s=Vg(e.map.state.styleZoom,e.map.state.pitch,e.map.state.styleState,[]);let o;const a=r.style.iconWidth,l=ce(a,s);if(n.isCommercial){o=i.rasterSets.byKey[Df(t.id,"commercial")];const d=o.url;if(!d)return;const h=os(o.rasters,l*window.devicePixelRatio,!0);if(h===void 0)return;const{w:g,h:y}=o.rasters[h],p=h0(d,g,y),v={baseUrl:d,fullUrl:p,width:g,height:y};return y0(e,i,r,s,v),v}const c=r.style.iconImage;if(!c)return;const f=Mt(c,s);if(o=v0(f,i,r),!o)return;const u=vI(e,i,o,l);if(u){if(hI(f)){const d=yI(e,i,r,f);d!==void 0&&(u.fullUrlUnhovered=d,u.nameUnhovered=g0(f))}return y0(e,i,r,s,u),u}}function wI(e){return Array.isArray(e)?e:[e]}function AI(e){return e&&e.buffer instanceof ArrayBuffer}function bI(e){let n=2166136261;n^=e.length,n=Math.imul(n,16777619);for(const i of e){n^=i.length,n=Math.imul(n,16777619);const r=new Uint32Array(i.buffer,i.byteOffset,i.length);for(let s=0;s<r.length;s++)n^=r[s],n=Math.imul(n,16777619)}return n>>>0}var Rr=(e=>(e[e.None=0]="None",e[e.Zoom=1]="Zoom",e[e.Distance=2]="Distance",e))(Rr||{}),x0=(e=>(e[e.default=0]="default",e[e.flat=1]="flat",e[e.axis=2]="axis",e[e.centroid=3]="centroid",e[e.polygonDemAnchor=4]="polygonDemAnchor",e))(x0||{});const Ai=[0,0,0],qe=new Array(16),Nu=new Float32Array(9),bi=[0,0,0],Gu=[0,0,0],ku=[0,0,0],zr=[0,0,0],Il=[0,0,0],w0=[0,0,0],Uu=[0,0,0],SI=nt(),EI=aa([1,1,1]),Ki={symbol:"gltfModel",sinks:{instances:{stride:64,binder:(e,t)=>{e.views.position=new Uint16Array(t,0),e.views.matrix=new Float32Array(t,8),e.views.absZ=new Float32Array(t,44),e.views.flatHeight=new Float32Array(t,48),e.views.localID=new Uint32Array(t,52),e.views.labelingTextureID=new Uint32Array(t,56)},packObjectAttributes(e,t,n,i,r,s,o,a,l,c=[],f,u,d,h,g,y,p,v,A){return Ze([e,t.innerId,n,c,l,s,o,i,r,f,u,d,h,g,y,p,v,A!=null?A:[]],t,a)},unpackObjectAttributes(e){return{styleId:e[0],layerId:e[1],modelIndices:e[2],lngLat:e[3],emitShowHideEvents:e[4],sourceId:e[5],sourceName:e[6],modelStepValues:e[7],modelStepSource:e[8],parentId:e[9],absZ:e[10],floorId:e[11],hiddenByFloorComplexId:e[12],subkey:e[13],extToReliefNeeded:e[14],collapseHeightNeeded:e[15],scene:e[16],polygonDemAnchor:e[17].length?e[17]:void 0,tileData:e.slice(18)}}}},generateInstances(e,t,n,i,r,s,o,a,l,c,f=0,u){var ne,ee,ge,de,he;let d=Fa(k(n.style.geometryModifier,i),s,r,i);if(d===null)return;const{tileAttrs:h,tileProps:g}=i;let y;if(h[g.db_geometry_type]==="polygon"){if(isNaN(h[g.tech_db_model_pos_x])||isNaN(h[g.tech_db_model_pos_y]))return;const J=h[g.db_max_abs_z];(J===void 0||isNaN(J))&&g.db_centroid_x!==void 0&&g.db_centroid_y!==void 0&&!isNaN(h[g.db_centroid_x])&&!isNaN(h[g.db_centroid_y])&&(y=[h[g.db_centroid_x],h[g.db_centroid_y]]),d={x:[h[g.tech_db_model_pos_x]],y:[h[g.tech_db_model_pos_y]],z:[0],abs_z:J!==void 0&&!isNaN(J)?[J]:void 0}}const p=k(n.style.linkedIds,i),v=p===""?[]:wI(p),A=n.style.modelSrc,w=[];let S=Rr.None;const T=Fr(A,i,n,!0),I=k(n.style.scene,i);if(T.length===1)w.push(0);else if(T.length>1){if(!Qt(A)||A.type!=="step"||!Qt(A.value)){console.error(`Only step-expression is allowed as 'modelSrc' style property. Models won't be displayed for layer ${n.id}`);return}switch(A.value.type){case"zoom":S=Rr.Zoom;break;case"distance":S=Rr.Distance;break;default:console.error(`'${A.value.type}' type in 'modelSrc' step expression is not supported. Only 'zoom' and 'distance' are supported. Models won't be displayed for layer ${n.id}`);return}A.steps.forEach(({key:J})=>{w.push(J)})}S===Rr.Distance&&T.reverse(),T.forEach((J,j)=>{J===null&&j!==0&&(T[j]=T[j-1])}),S===Rr.Distance&&T.reverse();const C=T.map(J=>J===null?"":J).map(J=>{let j=t.modelIndex[J];return j===void 0&&(J=dI(J,a!=null?a:"",u!=null?u:"",s.coords),j=e.addUsedModelByUrl(J)),e.addUsedModel(j),j});let M=Bn;n.interactive?i.id&&(M=h[g.hovered]?Ft:e.idIndexer.getIndex(i,t.id,n,{metatile:c,objectClass:h[g.db_object_class]})):M=n.interactiveOcclusion?Bn:Ft;const B=(ne=i.id)!=null?ne:"-1",D=h[g.db_point_building_id],F=u0(h[g.db_sublayer])?h[g.building_id]:void 0,z=h[g.db_hidden_by_metro_building_id]||"",N=h[g.db_plan_id];let H=Bn;i.id&&(H=e.pointIndexer.getIndexById((ge=(ee=N!=null?N:D)!=null?ee:F)!=null?ge:i.id));const K=l!=null&&l.has(h[g.db_sublayer])&&B!=="-1"?1:0,P=d.abs_z!==void 0&&Array.from(d.abs_z).some(J=>J)?d.abs_z:void 0,b=i.styleState.terrainEnabled===!0,E=i.tileAttrs[i.tileProps.db_extension_to_relief_surface],x=b&&!!P&&!Number.isNaN(E),L=!!i.tileAttrs[i.tileProps.db_ignore_z]&&!!P&&b,O=typeof i.sourceAttrs.sourceName=="string"?i.sourceAttrs.sourceName:"",R=e.getBucket("gltfModel","instances",Ki.sinks.instances.packObjectAttributes(t.id,n,C,w,S,o,O,i,K,K?ro(d.x[0],d.y[0],s):void 0,D,!!P,h[g.db_plan_id]||"",z,Yb(s,d.x[0],d.y[0],f),x,L,I,y),Ki.sinks.instances.binder);let G=R.meta;if(G)G.linkedIds.push(...v);else{const J=g.db_plan_id?h[g.db_plan_id]:void 0;St(Uu,[d.x[0],d.y[0]],s),G=R.meta={linkedIds:v.slice(),modelsPath:a!=null?a:"",sharedModelsPath:u!=null?u:"",buildingId:B,planId:J,anchor:[Uu[0],Uu[1]]}}K&&(G.sublayer=h[g.db_sublayer]),D&&(G.childrenIds||(G.childrenIds=[]),G.childrenIds.push(B));let Q;const X=II(h,i);if(X){const J=d.x[0],j=d.y[0];St(Il,[J,j],s),Q=[Il,me.fromGeo(X)]}const se=MI(h,i),te=_I(h,i);let U=0;for(let J=0;J<d.x.length;J++){if(Be(Gu,0,0,0),ea(k(n.style.rotation,i),Gu),Be(bi,1,1,1),ag(n.style.scale)||ea(k(n.style.scale,i),bi),Be(ku,0,0,0),ea(k(n.style.offset,i),ku),d.xScaleDirection&&d.yScaleDirection&&d.scaleCorrection){const j=d.x[J],Y=d.y[J];St(Il,[j,Y],s);const oe=d.xScaleDirection[J],Ne=d.yScaleDirection[J];St(w0,[oe,Ne],s),Q=[Il,w0],U=d.scaleCorrection[J]}A0(d.x[J],d.y[J],(he=(de=d.z)==null?void 0:de[J])!=null?he:0,ku,bi,Gu,Q,U,se,te,s),CI(R,Ai,Nu,M,H,P==null?void 0:P[J])}},patchBuffer(e,t,n,i,r,s,o,a){const l=Ki.sinks.instances.stride*t;if(A0(i[0],i[1],i[2],r,s,o,void 0,void 0,void 0,void 0,n),a){const f=Zn(n,Ai[0],Ai[1]);e.subData(l+0,new Uint16Array([f.x,f.y,f.z]))}else{const f=Ai[0]+W,u=Ai[1]+W;e.subData(l+0,new Uint16Array([f,u,0]))}e.subData(l+8,Nu);const c=Ai[2]/(32*He);e.subData(l+48,new Float32Array([c]))}};function TI(e,t,n,i){const r=n*ae/Mn(i.coords[2]);an(t,t,r),t[2]*=n,pr(e,e,t)}function A0(e,t,n,i,r,s,o,a,l,c,f){Be(Ai,e,t,n);const u=fn(f,Ai)*Ee;if(Jc(qe),ra(qe,qe,Le(s[2])),vp(qe,qe,Le(s[1])),$c(qe,qe,Le(s[0])),Xr(qe,qe,r),o)if(a)PI(qe,o[0],o[1]),Be(bi,a*Ee,a*Ee,u),Xr(qe,qe,bi);else{ii(zr,o[1],o[0]),l?ra(qe,qe,l):ra(qe,qe,Math.atan2(zr[1],zr[0]));const d=c!=null?c:na(zr);Be(bi,d,d,d),Xr(qe,qe,bi)}else Be(bi,u,u,u),Xr(qe,qe,bi);$c(qe,qe,Math.PI/2),pA(Nu,qe),TI(Ai,i,u,f)}function PI(e,t,n){ii(zr,n,t),ra(e,e,Math.atan2(zr[1],zr[0]))}function II(e,t){const n=e[t.tileProps.direction];return n===void 0?null:Array.isArray(n)?n:n.type==="Point"?n.coordinates:null}function MI(e,t){return e[t.tileProps.angle]}function _I(e,t){return e[t.tileProps.scale]}function CI(e,t,n,i,r,s){const o=e.elements.offset*Ki.sinks.instances.stride,a=e.views,l=o/a.position.BYTES_PER_ELEMENT,c=W+t[0],f=W+t[1],u=t[2]*io;if(a.position[l]=c,a.position[l+1]=f,a.position[l+2]=0,a.flatHeight[o/a.flatHeight.BYTES_PER_ELEMENT]=u/He,e.elements.offset>e.elements.maximum-1)return;a.matrix.set(n,o/a.matrix.BYTES_PER_ELEMENT),a.localID[o/a.localID.BYTES_PER_ELEMENT]=i,a.labelingTextureID[o/a.labelingTextureID.BYTES_PER_ELEMENT]=r,a.absZ[o/a.absZ.BYTES_PER_ELEMENT]=s!=null?s:0,FI(e,c,f,u,n);const d=e.indices;d.buffer[d.offset]=e.elements.offset,d.offset++,e.elements.offset++}function FI(e,t,n,i,r){const s=e.extents;t<s[0]&&(s[0]=t),n<s[1]&&(s[1]=n),i<s[2]&&(s[2]=i),t>s[3]&&(s[3]=t),n>s[4]&&(s[4]=n),i>s[5]&&(s[5]=i);const o=SI;IA(r,o);const a=aa(o)/EI;a>e.maxDiag&&(e.maxDiag=a)}const LI=1,Vu=-1,BI=1.3,b0=-200,S0=-300,DI=Math.tan(Le(175/2)),mn=[0,0,0],Ji=[0,0,0],OI=[0,0,0],Bo=[0,0,0],Wu=[0,0,0],$e=[0,0,0];let Ml=0,Do=0;const RI=(e,t)=>e<0||t<0?Math.floor(Math.min(e,t)):Math.ceil(Math.max(e,t)),E0={symbol:"overpass",sinks:{},generate(e,t,n,i,r,s,o,a){var E,x,L,O;let l=r.signed_z;if(!l)return;const c=r.abs_z!==void 0&&Array.from(r.abs_z).some(R=>R)?r.abs_z:void 0,f=i.styleState.terrainEnabled===!0,u=!c,d=i.tileAttrs[i.tileProps.db_road_part],h=i.tileAttrs[i.tileProps.db_geometry_type],g=(E=i.tileAttrs[i.tileProps.db_tiers])==null?void 0:E[0],y=!1;if(d==="roadbed_flat"||d==="border_tunnel_descent"&&y)return;const v=i.tileProps,A=i.tileAttrs.slice();i.id=void 0,A[v.db_tiers]=void 0;const w=t.id,S=r.x.length,T=r.x,I=r.y,C=(x=r.cut)!=null?x:[],M=new Uint8Array(S);l.forEach((R,G)=>{M[G]=R?0:1});const B=d==="roadbed_tunnel"||d==="roadbed_tunnel_descent"||d==="border_tunnel"||d==="border_tunnel_descent";let D=!1;B?D=!1:D=!!i.tileAttrs[i.tileProps.db_ignore_z]&&!!c&&f,D&&(l=new Int32Array(l.length));const F=u?BI:1;f&&B&&(l=new Int32Array(l).map(R=>R*F)),tt(Bo,0,0);const N=fn(s,Bo)*Ee,H=ae/s.size*N,K=Math.max(ce(n.style.borderWidth,i,0),0)*H,P=Math.max(ce(n.style.thickness,i,0),0)*N,b=K>0?Math.max(-P,ce(n.style.borderHeight,i,0)*N):0;if(Math.max(ce(n.style.tunnelHeight,i,0),0)*N,h==="polygon"){if(g===void 0)return;const R=[T,I,C,l,new Int8Array(S),M];c&&R.push(c);const G=d==="roadbed_tunnel_descent",Q=d==="roadbed_tunnel"||G;Xn.generate(e,w,n,i,ye(R),g,s,void 0);const X=R.map(U=>Array.from(U));for(let U=0;U<X[3].length;U++)G?X[3][U]-=P*.01:X[3][U]-=P,X[4][U]=0;re.generate({collector:e,styleId:w,layer:n,side:le.bottom,ctx:i,vertices:ye(X),tileInfo:s,dpi:o,rasterSets:a,sink:Q?"inverse":"fill",reverseTriangles:!0,tier:g});const se=[];for(let U=0;U<g;U++)se.push(U);const te=e.getBucket("polygon","shadow",Dn.sinks.shadow.packObjectAttributes(w,n,se,"",i),Dn.sinks.shadow.binder);if(Nm(te,R[0].length,R[0],R[1],Ft),Q&&!G){const U=R.slice();U[3]=Array.from(R[3]).map(ne=>ne+Math.abs(ne/F)-1),U.length=4,re.generate({collector:e,styleId:w,layer:n,side:le.top,ctx:i,vertices:ye(U),tileInfo:s,dpi:o,rasterSets:a,sink:"inverse",tier:void 0})}if(G&&f&&!y){const U=R.slice();U[3]=new Array(R[0].length).fill(Math.max(0,b)),U[5]=new Array(R[0].length).fill(1),re.generate({collector:e,styleId:w,layer:n,side:le.top,ctx:i,vertices:ye(U),tileInfo:s,dpi:o,rasterSets:a,sink:"depthClear",tier:g})}}else if(h==="polyline"){const R=re.sinks.stroke.packObjectAttributes(w,n,le.top,!!c,i),G=re.sinks.stroke.packObjectAttributes(w,n,le.side,!!c,i),Q=re.sinks.stroke.packObjectAttributes(w,n,le.bottom,!!c,i),X=zI({x:T,y:I,cut:C,signed_z:l,is_pivot:M,abs_z:c});if(d==="tunnel_arch"&&!y){const se=Math.max(b,0),te=_l(X),U=kI(X,K),ne=X.map(Y=>{const oe=Y.slice();return oe[2]=u?S0:b0,c&&(oe[5]=0),oe[4]=0,oe});ve(e,Q,ne);const ee=vn(U,te,K).map(Y=>(Y[2]=se,Y[4]=1,Y)),ge=U.map(Y=>{const oe=Y.slice();return oe[2]=se,oe[4]=1,oe}),de=ze(ee,ge);do re.generate({collector:e,styleId:w,layer:n,side:le.top,ctx:i,vertices:ye(de),tileInfo:s,dpi:o,rasterSets:a,sink:se?"fill":"inverse",tier:g});while(e.isOverloaded());const he=X.map(Y=>{const oe=Y.slice();return oe[2]=se,oe[4]=1,oe});ve(e,R,he);const J=ze(he,ne);do re.generate({collector:e,styleId:w,layer:n,side:le.side,ctx:i,vertices:ye(J),tileInfo:s,dpi:o,rasterSets:a,tier:g});while(e.isOverloaded());const j=ze(he.map(Y=>{const oe=Y.slice();return oe[2]=u?S0:b0,oe[4]=0,c&&(oe[5]=0),oe}),he.map(Y=>{const oe=Y.slice();return oe[2]=0,oe}));do re.generate({collector:e,styleId:w,layer:n,side:le.side,ctx:i,vertices:ye(j),tileInfo:s,dpi:o,rasterSets:a,sink:"inverse",tier:g});while(e.isOverloaded());if(se){const Y=vn(U,te,K).map(Pt=>(Pt[2]=0,Pt[4]=0,Pt));ve(e,Q,Y),ve(e,R,ee);const oe=ze(Y,ee);do re.generate({collector:e,styleId:w,layer:n,side:le.side,ctx:i,vertices:ye(oe),tileInfo:s,dpi:o,rasterSets:a,sink:"fill",tier:g});while(e.isOverloaded());const Ne=U.map(Pt=>{const Ut=Pt.slice();return Ut[2]=0,Ut[4]=0,Ut}),xe=ze([ge[0],Ne[0]],[ee[0],Y[0]]);do re.generate({collector:e,styleId:w,layer:n,side:le.side,ctx:i,vertices:ye(xe),tileInfo:s,dpi:o,rasterSets:a,sink:"fill",tier:g});while(e.isOverloaded());ve(e,R,[ge[0],ee[0]]),ve(e,G,[ee[0],Y[0]]),ve(e,Q,[Y[0],Ne[0]]);const Ae=ge.length-1,Un=ze([Ne[Ae],ge[Ae]],[Y[Ae],ee[Ae]]);do re.generate({collector:e,styleId:w,layer:n,side:le.side,ctx:i,vertices:ye(Un),tileInfo:s,dpi:o,rasterSets:a,sink:"fill",tier:g});while(e.isOverloaded());if(ve(e,R,[ge[Ae],ee[Ae]]),ve(e,G,[ee[Ae],Y[Ae]]),ve(e,Q,[Y[Ae],Ne[Ae]]),f){do re.generate({collector:e,styleId:w,layer:n,side:le.top,ctx:i,vertices:ye(de),tileInfo:s,dpi:o,rasterSets:a,sink:"depthClear",tier:g});while(e.isOverloaded());do re.generate({collector:e,styleId:w,layer:n,side:le.side,ctx:i,vertices:ye(oe),tileInfo:s,dpi:o,rasterSets:a,sink:"depthClear",tier:g});while(e.isOverloaded());do re.generate({collector:e,styleId:w,layer:n,side:le.side,ctx:i,vertices:ye(xe),tileInfo:s,dpi:o,rasterSets:a,sink:"depthClear",tier:g});while(e.isOverloaded());do re.generate({collector:e,styleId:w,layer:n,side:le.side,ctx:i,vertices:ye(Un),tileInfo:s,dpi:o,rasterSets:a,sink:"depthClear",tier:g});while(e.isOverloaded())}}}else if(d==="border_overpass"||d==="border_flat"){const se=[A[v.previousPointX],A[v.previousPointY],(L=l[0])!=null?L:0,0],te=!!A[v.beginningIsCut]&&T0(X[1],X[0],se);te&&X.splice(0,0,se);const U=X.length-1,ne=[A[v.nextPointX],A[v.nextPointY],(O=l[l.length-1])!=null?O:0,0],ee=!!A[v.endingIsCut]&&T0(X[U-1],X[U],ne);ee&&X.push(ne);const ge=_l(X);te&&(ge.shift(),X.shift()),ee&&(ge.pop(),X.pop());const de=X.map(xe=>{const Ae=xe.slice();return Ae[2]=Math.max(Ae[2]-P,0),Ae[4]=0,Ae});ve(e,G,X);const he=vn(X,ge,K).map(xe=>{const Ae=xe.slice();return Ae[2]=Math.max(xe[2]-P,0),Ae[4]=0,Ae}),J=vn(X,ge,K).map(xe=>{const Ae=xe.slice();return Ae[2]=Math.max(xe[2]+b,0),Ae[4]=1,Ae}),j=X.map(xe=>{const Ae=xe.slice();return b>0&&(Ae[2]=Math.max(Ae[2]+b,0)),Ae[4]=1,Ae});if(b>0){ve(e,R,j);const xe=ze(j,X.map(Ae=>{const Un=Ae.slice();return Un[4]=0,Un}));do re.generate({collector:e,styleId:w,layer:n,side:le.side,ctx:i,vertices:ye(xe),tileInfo:s,dpi:o,rasterSets:a,tier:g});while(e.isOverloaded())}ve(e,Q,he),ve(e,R,J);const Y=ze(J,j);do re.generate({collector:e,styleId:w,layer:n,side:le.top,ctx:i,vertices:ye(Y),tileInfo:s,dpi:o,rasterSets:a,tier:g});while(e.isOverloaded());const oe=ze(de,he);do re.generate({collector:e,styleId:w,layer:n,side:le.bottom,ctx:i,vertices:ye(oe),tileInfo:s,dpi:o,rasterSets:a,sink:"fill",tier:g});while(e.isOverloaded());const Ne=ze(he,J);do re.generate({collector:e,styleId:w,layer:n,side:le.side,ctx:i,vertices:ye(Ne),tileInfo:s,dpi:o,rasterSets:a,sink:"fill",tier:g});while(e.isOverloaded());if(l[0]===0){const xe=ze([j[0],de[0]],[J[0],he[0]]);do re.generate({collector:e,styleId:w,layer:n,side:le.side,ctx:i,vertices:ye(xe),tileInfo:s,dpi:o,rasterSets:a,sink:"fill",tier:g});while(e.isOverloaded());ve(e,R,[J[0],j[0]]),ve(e,G,[j[0],de[0]]),ve(e,G,[he[0],J[0]]),ve(e,Q,[de[0],he[0]])}if(l[l.length-1]===0){const xe=de.length-1,Ae=ze([de[xe],j[xe]],[he[xe],J[xe]]);do re.generate({collector:e,styleId:w,layer:n,side:le.side,ctx:i,vertices:ye(Ae),tileInfo:s,dpi:o,rasterSets:a,sink:"fill",tier:g});while(e.isOverloaded());ve(e,R,[j[xe],J[xe]]),ve(e,G,[de[xe],j[xe]]),ve(e,G,[J[xe],he[xe]]),ve(e,Q,[he[xe],de[xe]])}}else{const se=_l(X),te=d==="border_tunnel_descent",U=d==="border_tunnel"||te,ne=U?Math.max(b,0):b,ee=X.map(J=>{const j=J.slice();return j[2]-=P,te?(j[2]=0,j[5]=1):U&&(j[2]=Math.max(j[2],Vu)),j[4]=0,j}),ge=vn(X,se,K).map(J=>(J[2]-=P,te&&(J[2]=0,J[5]=1),J[4]=0,J)),de=vn(X,se,K).map(J=>(J[2]+=ne,te?(J[2]=ne,J[5]=1):U&&(J[2]=Math.max(J[2],Vu)),J[4]=1,J)),he=X.map(J=>{const j=J.slice();if(j[4]=1,te)j[2]=ne,j[5]=1;else if(U){const Y=Math.abs(j[2]/F),oe=ne-j[2],Ne=j[2]+Y-1;j[4]=(Ne+Math.abs(j[2]))/oe,j[2]=Ne}else j[2]+=ne;return j});if(U){te&&ve(e,R,he);const J=ze(he,X.map(oe=>{const Ne=oe.slice();return Ne[4]=0,Ne}));do re.generate({collector:e,styleId:w,layer:n,side:le.side,ctx:i,vertices:ye(J),tileInfo:s,dpi:o,rasterSets:a,tier:g});while(e.isOverloaded());const j=he.map(oe=>{const Ne=oe.slice();return Ne[2]=Math.min(oe[2],Vu),Ne}),Y=ze(j,X);do re.generate({collector:e,styleId:w,layer:n,side:le.side,ctx:i,vertices:ye(Y),tileInfo:s,dpi:o,rasterSets:a,sink:"inverse",reverseTriangles:!0,tier:void 0});while(e.isOverloaded())}if(b>0&&(!U||te)){ve(e,Q,ge),ve(e,R,de);const J=ze(de,he);do re.generate({collector:e,styleId:w,layer:n,side:le.top,ctx:i,vertices:ye(J),tileInfo:s,dpi:o,rasterSets:a,tier:g});while(e.isOverloaded());if(te&&f)do re.generate({collector:e,styleId:w,layer:n,side:le.top,ctx:i,vertices:ye(J),tileInfo:s,dpi:o,rasterSets:a,sink:"depthClear",tier:g});while(e.isOverloaded())}if(!U||te){const J=ze(ee,ge);do re.generate({collector:e,styleId:w,layer:n,side:le.bottom,ctx:i,vertices:ye(J),tileInfo:s,dpi:o,rasterSets:a,sink:"fill",tier:g});while(e.isOverloaded());const j=ze(ge,de);do re.generate({collector:e,styleId:w,layer:n,side:le.side,ctx:i,vertices:ye(j),tileInfo:s,dpi:o,rasterSets:a,sink:"fill",tier:g});while(e.isOverloaded());if(te&&f)do re.generate({collector:e,styleId:w,layer:n,side:le.side,ctx:i,vertices:ye(j),tileInfo:s,dpi:o,rasterSets:a,sink:"depthClear",tier:g});while(e.isOverloaded());if(l[0]===0){const Y=ze([he[0],ee[0]],[de[0],ge[0]]);do re.generate({collector:e,styleId:w,layer:n,side:le.side,ctx:i,vertices:ye(Y),tileInfo:s,dpi:o,rasterSets:a,sink:"fill",tier:g});while(e.isOverloaded());if(te&&f)do re.generate({collector:e,styleId:w,layer:n,side:le.side,ctx:i,vertices:ye(Y),tileInfo:s,dpi:o,rasterSets:a,sink:"depthClear",tier:g});while(e.isOverloaded());ve(e,R,[de[0],he[0]]),ve(e,G,[he[0],ee[0]]),ve(e,G,[ge[0],de[0]]),ve(e,Q,[ee[0],ge[0]])}if(l[l.length-1]===0){const Y=ee.length-1,oe=ze([ee[Y],he[Y]],[ge[Y],de[Y]]);do re.generate({collector:e,styleId:w,layer:n,side:le.side,ctx:i,vertices:ye(oe),tileInfo:s,dpi:o,rasterSets:a,sink:"fill",tier:g});while(e.isOverloaded());if(te&&f)do re.generate({collector:e,styleId:w,layer:n,side:le.side,ctx:i,vertices:ye(oe),tileInfo:s,dpi:o,rasterSets:a,sink:"depthClear",tier:g});while(e.isOverloaded());ve(e,R,[he[Y],de[Y]]),ve(e,G,[ee[Y],he[Y]]),ve(e,G,[de[Y],ge[Y]]),ve(e,Q,[ge[Y],ee[Y]])}}}}}};function zI(e){var i,r,s,o,a,l;const t=[],n=e.x.length;for(let c=0;c<n;c++){const f=[e.x[c],e.y[c],(r=(i=e.signed_z)==null?void 0:i[c])!=null?r:0,(o=(s=e.cut)==null?void 0:s[c])!=null?o:0,0,(l=(a=e.is_pivot)==null?void 0:a[c])!=null?l:0];e.abs_z&&f.push(e.abs_z[c]),t.push(f)}return t}function _l(e){const t=[];Hn(mn,e[0][0],e[0][1],e[1][0],e[1][1]),Ml=0;for(let n=1;n<e.length;n++)NI(t,e,n);return t}function NI(e,t,n){const i=n===t.length-1;if(tt(OI,t[n-1][0],t[n-1][1]),tt(Bo,t[n][0],t[n][1]),vf($e,mn),i)Do=0;else{tt(Wu,t[n+1][0],t[n+1][1]),Hn(Ji,Bo[0],Bo[1],Wu[0],Wu[1]);const o=Ge(Li(mn,Ji),-1,1),a=Math.min(Math.sqrt((1-o)/(1+o)),DI),l=$o(Li($e,Ji));Do=a*l}let r=$e[0]+mn[0]*Ml,s=$e[1]+mn[1]*Ml;e.push([r,s]),i&&(r=$e[0]+mn[0]*Do,s=$e[1]+mn[1]*Do,e.push([r,s])),i||(ta(mn,Ji),Ml=Do)}function vn(e,t,n){const i=[];for(let r=0;r<e.length;r++){const s=e[r].slice();ta($e,t[r]),an($e,$e,n),Tn(s,s,$e),i.push(s)}return i}function ve(e,t,n){do{const i=e.getBucket("mesh","stroke",t,re.sinks.stroke.binder),r=n.length,s={isMesh:!0,isModel:!1,absZCurr:0,absZNext:0,isPivotCurr:0,isPivotNext:0};for(let o=0;o<r-1;o++){const a=o+1;s.absZCurr=n[o][6],s.absZNext=n[a][6],s.isPivotCurr=n[o][5],s.isPivotNext=n[a][5],ys(i,n[o][0],n[o][1],n[o][2],n[a][0],n[a][1],n[a][2],s)}}while(e.isOverloaded())}function ze(e,t){return GI([e[0]].concat(e,t.slice().reverse()))}function GI(e){var i,r,s;const t=e.length,n=[[],[],[],[],[],[]];e[0][6]!==void 0&&n.push([]);for(let o=0;o<t;o++){const a=mt(o,t),l=e[o];n[0][a]=l[0],n[1][a]=l[1],n[2][a]=l[3],n[3][a]=l[2],n[4][a]=(i=l[4])!=null?i:0,n[5][a]=(r=l[5])!=null?r:0,n[6]&&(n[6][a]=(s=l[6])!=null?s:0)}return n}function ye(e){return{x:e[0],y:e[1],cut:e[2],signed_z:e[3],gradient:e[4],is_pivot:e[5],abs_z:e[6]}}function kI(e,t){return e=e.map(n=>n.slice()),ln($e,e[0],e[1]),jt($e,$e),Ri($e,$e,t),pr(e[0],e[0],$e),ln($e,e[e.length-1],e[e.length-2]),jt($e,$e),Ri($e,$e,t),pr(e[e.length-1],e[e.length-1],$e),e}const T0=(function(){const e=Math.cos(Le(LI));return(t,n,i)=>(ii(mn,n,t),Fi(mn,mn),ii(Ji,n,i),Fi(Ji,Ji),Li(mn,Ji)<=e)})();function UI(e,t,n,i){return Ze([e,t.innerId,n],t,i)}const Cl={symbol:"metricPoint",sinks:{fill:{stride:8,binder:(e,t)=>{e.views.position=new Uint16Array(t),e.views.texCoords=new Uint16Array(t,4)},packObjectAttributes:UI,unpackObjectAttributes:e=>({styleId:e[0],layerId:e[1],tiers:e[2],tileData:e.slice(3)})}},generate(e,t,n,i,r,s,o){WI(e,i,r,n,s);const a=ce(r.style.width,s),l=ce(r.style.height,s),c=ce(r.style.rotation,s),[f,u]=y2([t.x,t.y],a,l,c,o),d=k(r.ignoreTier,s)?null:s.tileAttrs[s.tileProps.db_tiers],h=e.getBucket("metricPoint","fill",Cl.sinks.fill.packObjectAttributes(i.id,r,d,s),Cl.sinks.fill.binder);let g=h.elements.offset;VI(h.indices,g,0,1,2,0,2,3),Fl(h,g++,f[0],u[0],0,0),Fl(h,g++,f[1],u[1],1,0),Fl(h,g++,f[2],u[2],1,1),Fl(h,g++,f[3],u[3],0,1),h.elements.offset=g}};function Fl(e,t,n,i,r,s){t=t*4,e.views.position[t]=W+n,e.views.position[t+1]=W+i,e.views.texCoords[t]=qt(r),e.views.texCoords[t+1]=qt(s)}function VI(e,t,n,i,r,s,o,a){const l=e.buffer,c=e.offset;l[c]=t+n,l[c+1]=t+i,l[c+2]=t+r,l[c+3]=t+s,l[c+4]=t+o,l[c+5]=t+a,e.offset=c+6}function WI(e,t,n,i,r){const{rasterSets:s}=t,o=Wf(i);Fr(n.style.iconImage).forEach(a=>{if(!a.length)return;const l=s.byKey[Ca(a)];if(!l){console.error(`Not found raster set with texture ${a}`);return}if(!l.isSvg)return;const c=ce(n.style.width,r),f=ce(n.style.height,r),u=uo(c,f),d=c*u,h=f*u;e.atlasPacker.packSvg(l,[{w:d,h}],o),l.rasters.forEach(g=>e.atlasPacker.addRastersToLoad(t.id,g))})}const HI=64,Nr=1e5,Hu=4;function YI(e){return e!==null&&typeof e=="object"&&e.type===HI}function P0(e){return M0(e.lo,e.hi)}function I0(e){return[e%Nr,Math.floor(e/Nr)%Nr,0,0]}function XI(e){let n=0;for(let i=0;i<Hu;i++){const r=e[i]*4294967296+n;n=Math.floor(r/Nr),e[i]=r%Nr}}function ZI(e,t){let n=0;for(let i=0;i<Hu;i++){const r=e[i]+t[i]+n;n=Math.floor(r/Nr),e[i]=r%Nr}}function jI(e){const t="00000";let n=!0,i=Hu,r="";for(;--i>=0;){const s=String(e[i]);n?e[i]!==0&&(r+=s,n=!1):r+=t.slice(s.length)+s}return r.length||(r="0"),r}function M0(e,t){const n=I0(e),i=I0(t);return XI(i),ZI(i,n),jI(i)}const vt=[0,0,0],Ll=[0,0,0],Bl=new Float64Array(16),_0={symbol:"tunnel",sinks:{},generate(e,t,n,i,r,s,o,a){var X,se,te;const{tileProps:l,tileAttrs:c}=i,f=(X=c[l.db_tiers])==null?void 0:X[0];if(P0(c[l.id])!=="70030076221371399"||!f)return;const d=t.id;tt(vt,0,0);const g=fn(s,vt)*Ee,y=ae/s.size*g,p=1/(ae/s.size),v=c[l.objectLength],A=(se=c[l.componentDistanceStart])!=null?se:0,w=(te=c[l.componentDistanceEnd])!=null?te:0,S=A===0?0:-5,T=175,I=243,C=w===v?0:-5;if(Number.isNaN(v)||Number.isNaN(A)||v===0)return;const M=I-T,B=T+M*A/v,D=T+M*w/v,F=3.5*y,z=5*y,N=[];let H=0;for(let U=0;U<r.x.length;U++){const ne=[r.x[U],r.y[U],0];U>0&&(H+=Bi(ne,N[U-1]),ne[2]=H),N.push(ne)}const K=QI(N),P=_l(N);N.forEach(U=>{const ne=U[2]/K;U[2]=(S+ne*(C-S))*g,U[5]=(B+ne*(D-B))*g});const b=re.sinks.stroke.packObjectAttributes(d,n,le.side,!0,i),E=vn(N,P,F),x=vn(N,P,-F),L=ze(E,x),O=vn(N,P,z),R=O.map(U=>{const ne=U.slice();return ne[2]=Math.max(0,ne[2]),ne});re.generate({collector:e,styleId:d,layer:n,side:le.side,ctx:i,vertices:ye(ze(O,R)),tileInfo:s,dpi:o,rasterSets:a,sink:"inverse"});const G=vn(N,P,-z),Q=G.map(U=>{const ne=U.slice();return ne[2]=Math.max(0,ne[2]),ne});re.generate({collector:e,styleId:d,layer:n,side:le.side,ctx:i,vertices:ye(ze(Q,G)),tileInfo:s,dpi:o,rasterSets:a,sink:"inverse"}),N[0][2]!==0&&N[N.length-1][2]!==0&&re.generate({collector:e,styleId:d,layer:n,side:le.side,ctx:i,vertices:ye(ze(R,Q)),tileInfo:s,dpi:o,rasterSets:a,sink:"inverse"});do Xn.generate(e,d,n,i,ye(L),f,s,void 0);while(e.isOverloaded());for(let U=1;U<N.length;U++){const ne=[],ee=[],ge=N[U-1],de=N[U],he=P[U-1],J=P[U];for(let Y=0;Y<=181;Y+=15){const oe=Le(Y),Ne=ge.slice();Be(vt,he[0],he[1],0),Ri(vt,vt,F),zi(Ll,vt),yp(Bl,-oe,Ll),Qs(vt,vt,Bl),vt[2]*=p,pr(Ne,Ne,vt),ne.push(Ne);const xe=de.slice();Be(vt,J[0],J[1],0),Ri(vt,vt,F),zi(Ll,vt),yp(Bl,-oe,Ll),Qs(vt,vt,Bl),vt[2]*=p,pr(xe,xe,vt),ee.push(xe)}const j=ze(ne,ee);if(re.generate({collector:e,styleId:d,layer:n,side:le.side,ctx:i,vertices:ye(j),tileInfo:s,dpi:o,rasterSets:a,sink:"fill"}),U===1&&N[0][2]===0){ve(e,b,ne);const Y=N[0].slice(),oe=N[0].slice(),Ne=P[0].slice(),xe=P[0].slice();an(Ne,Ne,z),an(xe,xe,-z),Tn(Y,Y,Ne),Tn(oe,oe,xe);const Ae=Y.slice(),Un=oe.slice();Ae[2]+=z*p,Un[2]+=z*p;const Pt=[Y];for(let Ut=0;Ut<5;Ut++)Pt.push(Ae);for(let Ut=0;Ut<5;Ut++)Pt.push(Un);Pt.push(oe),ve(e,b,Pt),re.generate({collector:e,styleId:d,layer:n,side:le.side,ctx:i,vertices:ye(ze(Pt,ne)),tileInfo:s,dpi:o,rasterSets:a,sink:"fill"})}else if(U===N.length-1&&N[N.length-1][2]===0){ve(e,b,ee);const Y=N[N.length-1].slice(),oe=N[N.length-1].slice(),Ne=P[N.length-1].slice(),xe=P[N.length-1].slice();an(Ne,Ne,z),an(xe,xe,-z),Tn(Y,Y,Ne),Tn(oe,oe,xe);const Ae=Y.slice(),Un=oe.slice();Ae[2]+=z*p,Un[2]+=z*p;const Pt=[Y];for(let Ut=0;Ut<5;Ut++)Pt.push(Ae);for(let Ut=0;Ut<5;Ut++)Pt.push(Un);Pt.push(oe),ve(e,b,Pt),re.generate({collector:e,styleId:d,layer:n,side:le.side,ctx:i,vertices:ye(ze(ee,Pt)),tileInfo:s,dpi:o,rasterSets:a,sink:"fill"})}}if(N[0][2]===0||N[N.length-1][2]===0){const U=vn(N,P,z),ne=vn(N,P,-z),ee=U.map(j=>{const Y=j.slice();return Y[2]=Math.max(0,Y[2]+z*p),Y}),ge=ne.map(j=>{const Y=j.slice();return Y[2]=Math.max(0,Y[2]+z*p),Y});U.forEach(j=>{j[2]=Math.max(0,j[2])}),ne.forEach(j=>{j[2]=Math.max(0,j[2])});const de=ze(U,ee),he=ze(ge,ne);ve(e,b,U),ve(e,b,ne),ve(e,b,ee),ve(e,b,ge),re.generate({collector:e,styleId:d,layer:n,side:le.side,ctx:i,vertices:ye(de),tileInfo:s,dpi:o,rasterSets:a,sink:"fill"}),re.generate({collector:e,styleId:d,layer:n,side:le.side,ctx:i,vertices:ye(he),tileInfo:s,dpi:o,rasterSets:a,sink:"fill"});const J=ze(ee,ge);re.generate({collector:e,styleId:d,layer:n,side:le.top,ctx:i,vertices:ye(J),tileInfo:s,dpi:o,rasterSets:a,sink:"fill"})}}};function QI(e){let t=0;for(let n=0;n<e.length-1;n++)t+=Xs(e[n],e[n+1]);return t}var Yu=(e=>(e[e.Chess=1]="Chess",e[e.DoubleDash=2]="DoubleDash",e[e.Stripe=3]="Stripe",e[e.Triangles=4]="Triangles",e[e.Circle=5]="Circle",e[e.Chevron=6]="Chevron",e[e.None=-1]="None",e))(Yu||{});function C0(e){switch(e){case"chess":return 1;case"doubledash":return 2;case"triangles":return 4;case"circle":return 5;case"heart":return 6;case"stripe":return 3;default:return-1}}const qI={symbol:"simpleMesh",sinks:{fill:{stride:24,binder:()=>{},packObjectAttributes(e,t,n){return Ze([e,t.innerId],t,n)},unpackObjectAttributes(e){return{styleId:e[0],layerId:e[1],tileData:e.slice(2)}}}}},Xu={symbol:"polygon3d",sinks:{},generate(e,t,n,i,r,s,o,a){let l;i.tileProps.db_centroid_x!==void 0&&i.tileProps.db_centroid_y!==void 0&&!Number.isNaN(i.tileAttrs[i.tileProps.db_centroid_x])&&!Number.isNaN(i.tileAttrs[i.tileProps.db_centroid_y])&&(l=[i.tileAttrs[i.tileProps.db_centroid_x],i.tileAttrs[i.tileProps.db_centroid_y]]);const c=k(n.style.color,i),f=c&&c.isVertexColor?ka(c):void 0;re.generate({collector:e,styleId:t,layer:n,side:le.top,ctx:i,vertices:r,tileInfo:s,dpi:o,rasterSets:a,demPosition:l,sink:"fill",innerColor:f})}};var F0=(e=>(e[e.none=0]="none",e[e.fadeIn=1]="fadeIn",e[e.fadeOut=-1]="fadeOut",e))(F0||{});function L0({collector:e,generator:t,args:n}){do t(e,...n);while(e.isOverloaded())}const B0={arrow:Io,line:Rt,polygon:Dn,embankment:Xu,polygon3d:Xu,metricPoint:Cl,labelLine:Br,lineExtrusion:vi,polygonExtrusion:jn,oneWayLine:Dr,dashedLine:gi,shiftedLine:xo,circle:il,buildingModel:mi,gltfModel:Ki,point:qn,raster:sl,heatmap:Or,dem:Kt,mesh:re,mapMesh:Xn,overpass:E0,tunnel:_0,simpleMesh:qI},D0={labelLine:Br,oneWayLine:Dr,point:qn};function Oo(e,t){const n=B0[e];return n?n.sinks[t].stride:0}function Zu(e,t){e.precomputes.forEach((n,i)=>{t.tileData[i]=k(n.expr,t)})}function ju(e,t,n,i,r,s,o,a,l,c,f,u,d,h,g){const y=i.styleState.graphicsPreset?t.graphicsPresets[i.styleState.graphicsPreset]||{}:{};i.globeOff=y.globeOff,n.forEach(p=>{if(Eg(i,[f.x[0],f.y[0]]),!(o!==void 0&&(p.maxzoom<=o||p.minzoom>=o+1&&o!==ur.maxDetailLevel))&&!(i.tileProps.hovered&&!Number.isNaN(i.tileAttrs[i.tileProps.hovered])&&i.tileAttrs[i.tileProps.hovered]===1&&p.type!=="polygon"&&p.type!=="polygonExtrusion"&&p.type!=="point"&&p.type!=="polygon3d")){Zu(p,i);do switch(p.type){case"line":const v=k(p.style.pattern,i);v&&v[0]!==Yu.None?Rt.generatePatterned(e,t.id,p,i,l,f):Rt.generate(e,t.id,p,i,l,f);break;case"dashedLine":gi.generate(e,t.id,p,i,f);break;case"shiftedLine":xo.generate(e,t.id,p,i,f);break;case"polygon":Dn.generate(e,t.id,p,i,f,c,l,t.rasterSets);break;case"polygon3d":case"embankment":Xu.generate(e,t.id,p,i,f,l,c,t.rasterSets);break;case"metricPoint":{Cl.generate(e,f,c,t,p,i,l);break}case"polygonExtrusion":jn.generate(e,t.id,p,i,f,y,l);break;case"labelLine":lI(e,t.id,p,l.coords,a,i,f);break;case"oneWayLine":cI(e,t.id,p,l.coords,a,i,f);break;case"point":{d0(e,t,p,i,r,s,l.coords,a,f,c,u);break}case"lineExtrusion":vi.generate(e,t.id,p,i,f,y);break;case"arrow":Io.generate(e,t.id,p,i,f);break;case"heatmap":{Or.generate(e,t.id,p,f,i);break}case"gltfModel":{Ki.generateInstances(e,t,p,i,f,l,a,d,h,r,2,g);break}case"overpass":E0.generate(e,t,p,i,f,l,c,t.rasterSets);break;case"tunnel":_0.generate(e,t,p,i,f,l,c,t.rasterSets);break}while(e.isOverloaded())}})}function KI(e,t,n,i,r,s,o,a,l){const c=D0[t.type];if(c)do c.processElement(e,n,i,r,s,o,a,l);while(n.isOverloaded())}function JI(e,t,n,i,r,s,o){const a=D0[i.type];a&&a.getLabelingInfo(e,t,n,r,s,o)}const O0={polygon:{fill:"polygon",stroke:"polygon"},line:{solid:"line",solid3d:"line",patterned:"patternedLine",patterned3d:"patternedLine"},shiftedLine:{solid:"line"},dashedLine:{stroke:"dashedLine",stroke3d:"dashedLine"},oneWayLine:{raster:"oneWayLine"},point:{raster:"pointSprite",text:"labelPoint",labelingTexture:"pointAnchor"},labelLine:{raster:"labelLine"},arrow:{stroke:"arrow"},metricPoint:{fill:"metricPoint"},circle:{fill:"circleMarker"},dem:{mesh2:null},mapMesh:{fill:"mapMesh"},polygonExtrusion:{sideFill:"extrusion",topFill:"extrusion",sideTexture:"extrusionTexture",topStroke:"wallStroke",sideStroke:"wallStroke"},lineExtrusion:{fill:"lineExtrusion",topStroke:"wallStroke",sideStroke:"wallStroke"},mesh:{fill:"meshFill",inverse:"meshInverse",depthClear:"meshDepthClear",stroke:"wallStroke"}};function $I(e,t){var n;return((n=O0[e])==null?void 0:n[t])!==void 0}function R0(e,t,n,i,r){const s=ga();return t.uploadBuffer(s,i,!1,n.getSundaTileKey(),r),n.registerSundaBuffer(s,o=>{var a;return(a=e.sunda.ledger)==null?void 0:a.deleteTileBuffers(o)}),s}function eM(e,t,n,i){const{symbol:r,sink:s,buffer:o,elementsBuffer:a}=n,l=e.sunda.ledger;return!l||!e.map.state.sunda||a||!$I(r,s)?void 0:R0(e,l,t,o,i)}function tM(e,t,n,i){const r=e.sunda.ledger;!r||!e.map.state.sunda||n.symbol!=="gltfModel"||n.sink!=="instances"||(t.sundaInstanceBufferId=R0(e,r,t,n.buffer,i))}class z0{constructor(t,n={}){this._buffer=t,this.options=Object.assign({},ht.defaultOptions,n)}get isDirty(){return this._buffer.isDirty}set isDirty(t){this._buffer.isDirty=t}bind(t,n,i,r){this._buffer.bind(t,n||this.options,i,r)}replaceData(t){this._buffer.replaceData(t)}commitData(){this._buffer.commitData()}getData(){return this._buffer.getData()}}function nM(e,t){const n=new Set;return e.forEach(i=>{t.has(i)||n.add(i)}),n}function iM(e,t){if(!e||!t)return e===t;if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function rM(e,t){const n=new Set;for(const i of t)e.has(i)&&n.add(i);return n}function sM(e,t){if(!e||!t)return e===t;if(e.size!==t.size)return!1;for(const[n,i]of e)if(!t.has(n)||!iM(i,t.get(n)))return!1;return!0}const Qu="default",oM="floor",aM="dynamicModel";var Ps=(e=>(e[e.PolygonExtrusion=1]="PolygonExtrusion",e[e.FloorPolygons=2]="FloorPolygons",e[e.All=3]="All",e))(Ps||{});class lM{constructor(t){this.identifier=t,this.tileLayers=[],this.selected=[],this.hidden=new Map,this.parentChildrenMap=new Map,this.childParentMap=new Map,this.parentChildrenMapByTile=new Map,this.selectedIdsByApi=[]}registerTileLayer(t){this.tileLayers.push(t)}unregisterTileLayer(t){this.tileLayers=this.tileLayers.filter(n=>n!==t)}select(t){this.selectedIdsByApi=t.slice(),this.selected=this.getIdsToSelect(t),this.selected.sort();for(const n of this.tileLayers)n.setSelectedIds(this.selected);this.identifier.queryFillCache()}getSelected(){return this.selected}show(t){for(const n of t)this.hidden.delete(n);this.triggerIdUpdate(t)}hide(t,n=3){for(const i of t)this.hidden.set(i,n);this.triggerIdUpdate(t)}isHidden(t,n=3){var r;return((r=this.hidden.get(t))!=null?r:0)>=n}getHidden(t=3){const n=new Set;return this.hidden.forEach((i,r)=>{i>=t&&n.add(r)}),n}triggerIdUpdate(t){if(t.length!==0)for(const n of this.tileLayers)n.pushIdsToUpdate(t)}getRelatedChildrenIds(t){const n=new Set;return t.forEach(i=>{const r=this.parentChildrenMap.get(i);r!=null&&r.size&&r.forEach(n.add,n)}),Array.from(n)}removeParentChildrenData(t){let n=!1;t.forEach(i=>{const r=this.parentChildrenMapByTile.delete(i);!n&&r&&(n=!0)}),n&&this.rebuildMaps()}updateParentChildrenData(t,n){this.updateTileParentChildrenData(t,n)&&(this.addParentChildrenData(n),this.select(this.selectedIdsByApi))}addParentChildrenData(t){t&&t.size&&t.forEach((n,i)=>{const r=this.parentChildrenMap.get(i);r?n.forEach(s=>{r.add(s),this.childParentMap.set(s,i)}):(this.parentChildrenMap.set(i,new Set(n)),n.forEach(s=>{this.childParentMap.set(s,i)}))})}rebuildMaps(){this.parentChildrenMap.clear(),this.childParentMap.clear(),this.parentChildrenMapByTile.forEach(t=>this.addParentChildrenData(t))}updateTileParentChildrenData(t,n){const i=this.parentChildrenMapByTile.get(t);return sM(i,n)?!1:(i&&i.forEach((r,s)=>{const o=this.parentChildrenMap.get(s);r.forEach(a=>{o==null||o.delete(a),this.childParentMap.delete(a)})}),this.parentChildrenMapByTile.delete(t),n&&this.parentChildrenMapByTile.set(t,n),!0)}getIdsToSelect(t){const n=new Set(t);return t.forEach(i=>{if(this.parentChildrenMap.has(i)){const s=this.parentChildrenMap.get(i);s!=null&&s.size&&s.forEach(n.add,n)}}),Array.from(n)}}class N0{constructor(t=0){this.index=t,this.keysMap={}}getIndex(){const t=this.index;return this.index+=1,t}getUniqueIndex(t){return this.keysMap[t]===void 0&&(this.keysMap[t]=this.index,this.index+=1),this.keysMap[t]}getIndexedKeys(){return this.keysMap}}function cM(e){const t=fM(e),{groups:n,table:i}=uM(t),r={};for(let o=0;o<i.length;o++){const a=i[o],l=n[o];r[l]={};for(let c=0;c<a.length;c++){const f=n[c];r[l][f]=i[o][c]}}const s=n.reduce((o,a,l)=>(o[a]=l,o),{});return{indexToGroup:n,groupToIndex:s,table:r}}function fM(e){const t=(e.groups||[]).concat(Gf.groups).reduce((i,r)=>(i.includes(r)||i.push(r),i),[]),n=(e.overlay||[]).concat(Gf.overlay).concat(t.reduce((i,r)=>(r===Yi||r===Hi||r===Cg||i.push([r,Hi]),i),[])).reduce((i,r)=>{const s=[];for(const o of r)t.includes(o)&&s.push(o);return s.length>1&&i.push(s),r.length===1&&s.length===1&&i.push(s),i},[]);return{groups:t,overlay:n,intersect:Gf.intersect}}function uM(e){const{groups:t,overlay:n,intersect:i}=e,r=t.reduce((o,a,l)=>(o[a]=l,o),{}),s=[];for(let o=0;o<t.length;o++){const a=[];for(let l=0;l<t.length;l++)a.push(!0);s.push(a)}for(let o=0;o<n.length;o++){const a=n[o];for(let l=0;l<a.length;l++)for(let c=l+1;c<a.length;c++){const f=r[a[l]],u=r[a[c]];s[f][u]=!1,s[u][f]=!1}}for(let o=0;o<i.length;o++){const a=i[o];for(let l=0;l<a.length;l++)for(let c=l+1;c<a.length;c++){const f=r[a[l]],u=r[a[c]];s[f][u]=!0,s[u][f]=!0}}return{groups:t,table:s}}function Dl(e,t){const n=new XMLHttpRequest;if(n.open("GET",e.url,!0),n.responseType="arraybuffer",e.headers)for(const i in e.headers)n.setRequestHeader(i,e.headers[i]);return n.onerror=function(){t({status:0,message:"Network error"},new ArrayBuffer(0))},n.onload=function(){n.status>=200&&n.status<300&&n.response?t(void 0,n.response):t({status:n.status,message:n.statusText},new ArrayBuffer(0))},n.send(),n}function G0(e,t){const n=new XMLHttpRequest;if(n.open("GET",e.url,!0),e.headers)for(const i in e.headers)n.setRequestHeader(i,e.headers[i]);return n.onerror=function(){t({status:0,message:"Network error"},{})},n.onload=function(){if(n.status>=200&&n.status<300){if(!n.response||!n.response.length)return t({status:204,message:"No content"},{});let i;try{i=JSON.parse(n.response),t(void 0,i)}catch(r){t({status:0,message:`Json parse data error from url ${e.url}`},{})}}else t({status:n.status,message:n.statusText},{})},n.send(),n}function k0(e){return e===void 0?!1:e===0||e>=500&&e<=599}const dM="X-Session-ID";function hM(e){if(e)return{[dM]:e}}const pM={db_id:"id",tech_db_beginning_is_cut:"beginningIsCut",tech_db_ending_is_cut:"endingIsCut",tech_db_previous_point_x:"previousPointX",tech_db_previous_point_y:"previousPointY",tech_db_next_point_x:"nextPointX",tech_db_next_point_y:"nextPointY",tech_db_object_length:"objectLength",tech_db_component_distance_start:"componentDistanceStart",tech_db_component_distance_end:"componentDistanceEnd",tech_db_geometry_type:"db_geometry_type"},gM=e=>{var t;return(t=pM[e])!=null?t:e},mM={objectClass:"db_object_class",sublayer:"db_sublayer",db_id:"id"};function vM(e){var t;return(t=mM[e])!=null?t:e}const yM={Class:"db_class",DisputePosition:"db_dispute_position",ObjectClass:"db_object_class",ParkingType:"db_parking_type",Sublayer:"db_sublayer",Subsublayer:"db_subsublayer",Icon:"db_icon",GeometryType:"db_geometry_type",ModelType:"db_model_type",RoadSupportTypes:"tech_db_road_support_type",RoadMarkingColorType:"db_road_marking_color_type",PoiCategory:"L1_Poi_category",RoadPart:"db_road_part",TriangulationMethod:"db_triangulation_method",RequireAbsZFromReliefSurface:"db_require_abs_z_from_relief_surface",TouristRouteColor:"db_tourist_route_color",TouristRouteSportTrackType:"db_tourist_route_sport_track_type",TouristRouteType:"db_tourist_route_type"},xM=e=>{var t;e.enumerationValues=Object.keys((t=e.enumerationValues)!=null?t:{}).reduce((n,i)=>{const r=yM[i];return r&&(n[r]=e.enumerationValues[i]),n},{})};class wM{constructor(t,n,i){var r;this.id=t,this.modules=n,this.options=i,this.type="zenith",this.worker=new n.workers.parser.ZenithSource,this.sourceAttrs=Ci((r=i.sourceAttributes)!=null?r:{},Gp),this.objectAttributes={},this.dataFilter=i.dataFilter}fetchTiles(t,n){const{assetManager:i,map:r}=this.modules,s=t.map(a=>({coords:a,tileUrl:this.constructTileUrl(a,n),headers:hM(this.options.sessionId)}));return this.worker.fetchTiles(s).map((a,l)=>a.catch(()=>Promise.resolve()).then(c=>{if(!c)return;const{metadata:f,err:u}=c;return f.forEach(d=>{const h=this.constructMetaTileUrl(d);i.loadMetatile(h,d.metatileHash,d.regionId),r.emit("tileload",{tileCoords:s[l].coords,regionId:d.regionId}),n.shownRegionIds.add(d.regionId)}),(u==null?void 0:u.status)===403&&r.emit("error",{type:"invalidtilekey"}),f}))}generateTile(f,u,d,h,g){return Fe(this,arguments,function*(t,n,i,r,s,o={},a,l=this.id,c){const y=yield this.worker.generateTile(ie(V({styleId:i,tileInfo:Bt(n),pixelRatio:s,selectedIds:r,styleState:t.styleState,floorsEnabled:t.floorsEnabled,sourceAttrs:this.sourceAttrs,hoverId:a,sourceId:l,needFallbackScreenLabels:!t.isFloatTextureSupported||!t.isVertexTextureFetchSupported,isDefaultSource:this.options.isDefaultSource,modelsPath:this.options.modelsPath,sharedModelsPath:this.options.sharedModelsPath,promoteAttributes:this.options.promoteAttributes,promoteId:this.options.promoteId,isCustomZenithSource:!this.options.isDefaultSource,dataFilter:this.dataFilter},o),{modelShowHideEventsSublayers:t.modelShowHideEventsSublayers}),c);return y.promotedAttrs&&(this.objectAttributes[De(n)]=y.promotedAttrs),y})}getObjectAttributes(t,n){var i;return(i=this.objectAttributes[t])==null?void 0:i[n]}generateModel(t){return this.worker.generateModel(t)}abortTileFetches(t){const n=t.map(De);this.worker.abortTileRequests(n)}deleteTiles(t){const n=t.map(De);for(const i of n)this.objectAttributes[i]=void 0;this.worker.deleteTiles(n)}setAttributes(t){this.sourceAttrs=t}getAttributes(){return this.sourceAttrs}destroy(){this.worker.destroy(),this.sourceAttrs={},this.objectAttributes={}}setFeatureStateMap(t){this.worker.setFeatureStateMap(t)}setDataFilter(t){if(t){const n={layer:{},usage:Qe.Generator,globals:{},precomputes:[]};this.dataFilter=_(t,n)}else this.dataFilter=void 0}constructTileUrl(t,n){return Db(this.options.tileServer,this.options.tileSet,this.options.tileProtocol,this.options.subdomains,t,this.options.tileKey,this.options.appId,n.lang,this.options.tileTemplateUrl,this.options.defaultLang,this.options.dt)}constructMetaTileUrl(t){const n=this.options.metatileTemplateUrl,i={host:this.options.tileServer,tileSet:this.options.tileSet,protocol:this.options.tileProtocol,subdomain:this.options.subdomains[0],hash:Op(t.metatileHash)};return $s(n?{url:n}:"metatile",i)}}function AM(e){const t={};let n=0;for(const i in e)t[i]=n,n+=1;return t}let bM=Number.MIN_SAFE_INTEGER;function U0(){return bM++}const SM=U0(),EM=U0(),V0={NEVER:512,LESS:513,EQUAL:514,LEQUAL:515,GREATER:516,NOTEQUAL:517,GEQUAL:518,ALWAYS:519},TM={FRONT:1028,BACK:1029,FRONT_AND_BACK:1032},PM={ZERO:0,ONE:1,SRC_COLOR:768,ONE_MINUS_SRC_COLOR:769,SRC_ALPHA:770,ONE_MINUS_SRC_ALPHA:771,DST_ALPHA:772,ONE_MINUS_DST_ALPHA:773,DST_COLOR:774,ONE_MINUS_DST_COLOR:775,SRC_ALPHA_SATURATE:776},IM={FUNC_ADD:32774,FUNC_SUBTRACT:32778,FUNC_REVERSE_SUBTRACT:32779,MIN:32775,MAX:32776},W0={type:"color-effect",effect:{type:"mix",color:Ot([0,0,0,0]),factor:0}},qu="__JAKARTA__DEM__LIGHTING__";class Ku extends Error{constructor(t){super(`Unknown expression type '${t[0]}' in '${JSON.stringify(t)}'`),this.name="UnknownExpressionTypeError",Object.setPrototypeOf(this,new.target.prototype)}}const Ju="_customUserTimeOffset";function Ol(e){e.globals[Ju]||(e.globals[Ju]=new Set),e.globals[Ju].add(e.usage)}function _(e,t){if(c2(e))return vg(e)?Mr(e):e;switch(e[0]=W2(e[0]),e[0]){case"coalesce":return ZM(e,t);case"concat":return jM(e,t);case"format":return QM(e,t);case"all":return XM(e,t);case"any":return qM(e,t);case"match":return MM(e,t);case"when":return FM(e,t);case"in":return GM(e,t);case"interpolate":return X0(e,t);case"step":return YM(e,t);case"feature-state":case"get":case"source-attr":case"has":return Z0(e,t);case"object-attr":return{type:"object-attr",property:e[1]};case"global":const n=e[1];return t.globals[n]||(t.globals[n]=new Set),t.globals[n].add(t.usage),{type:"global",property:n};case"zoom":return{type:"zoom"};case"pitch":return{type:"pitch"};case"distance":return{type:"distance"};case"local-time":return Ol(t),{type:"local-time",offset:_(e[1]||0,t)};case"utc-time":return Ol(t),{type:"utc-time",offset:_(e[1]||0,t)};case"time":return Ol(t),$M(e,t);case"schedule":return Ol(t),e_(e,t);case"height":return{type:"height"};case"heatmap-density":return{type:"heatmap-density"};case"shading-intensity":return{type:"shading-intensity"};case"to-boolean":case"to-color":case"!":case"log10":case"mappoints-to-meters":case"meters-to-pixels":return LM(e,t);case"uint64":return _(e[1],t);case"==":case"!=":case"<":case"<=":case">":case">=":return BM(e,t);case"+":return DM(e,t);case"*":return OM(e,t);case"^":return RM(e,t);case"%":return zM(e,t);case"random":return t_(e,t);case"clamp":return NM(e,t);case"literal":return Array.isArray(e[1])?n_(e,t):typeof e[1]=="object"&&e[1]!==null?i_(e):e[1];case"is-behind-objects":return{type:"is-behind-objects"};case"geometry-modifier":const i=[];return e.slice(1).forEach(r=>{const s=r_(r);s&&i.push(s)}),{type:"geometry-modifier",modifiers:i};case"pattern":return{type:"line-pattern",patternType:C0(e[1]),parameters:e.slice(2).map(r=>_(r,t))};case"precompute":{if(!t.layer)throw new Ku(e);const r=t.precomputes.length;return t.precomputes.push({expr:_(e[1],ie(V({},t),{layer:void 0})),usage:t.usage}),{type:"precompute",precomputeIndex:r}}case"color-saturate":case"color-desaturate":case"color-grayscale":case"color-lighten":case"color-lightness":case"color-darken":case"color-whiten":case"color-blacken":case"color-opacity":return kM(e,t);case"gltf-animation":return UM(e,t);case"texture-animation":return VM(e,t);case"easing":return WM(e);case"mix":return HM(e,t);case"read-from-target":return{type:"read-from-target",name:e[1]};case"vertex-attribute":return{type:"vertex-attribute",name:e[1]};case"vertex-color":return KM(e,ie(V({},t),{usage:Qe.Generator}));case"color-effect":return JM(e,t);default:throw new Ku(e)}}function $i(e,t){return Yn(e)||Array.isArray(e)&&e.length===0?e:_(e,t)}function er(e,t){return e===void 0?e:_(e,t)}function MM(e,t){const n={type:"match",input:_(e[1],t),cases:[],defaultOutput:_(e[e.length-1],t)},i=e.slice(2,-1);for(let r=0;r<i.length;r+=2){const s=i[r].reduce((a,l)=>{typeof l=="boolean"&&a.push(Number(l));const c=_(l,t);return og(c)?a.push(c):console.warn("MatchExpression supports only simple types: string, number, boolean or null",l),a},[]),o={values:new Set(s),output:_(i[r+1],t)};n.cases.push(o)}return n}function _M(e){return e.length===1?[e[0],e[0],e[0],e[0]]:e.length===2?[e[0],e[1],e[0],e[1]]:e.length===4?e:[0,0,0,0]}function H0(e,t,n,i,r){if(n in e||i in e)r in e&&console.warn(`Margin: одновременно заданы "${r}" и "${n}"/"${i}" — используются более конкретные значения "${n}"/"${i}", "${r}" игнорируется. Значение: ${JSON.stringify(e)}`),t[n]=typeof e[n]=="number"?e[n]:0,t[i]=typeof e[i]=="number"?e[i]:0;else{const s=typeof e[r]=="number"?e[r]:0;t[n]=s,t[i]=s}}function $u(e){if(typeof e=="number")return["literal",[e,e,e,e]];if(typeof e=="object"&&e!==null&&!Array.isArray(e)){if(typeof e.all=="number")return["literal",[e.all,e.all,e.all,e.all]];const t={};return H0(e,t,"top","bottom","topBottom"),H0(e,t,"left","right","leftRight"),["literal",[t.top,t.right,t.bottom,t.left]]}return e}function ed(e){if(!Array.isArray(e))return e;const t=e[0];if(t==="literal"&&Array.isArray(e[1]))return["literal",_M(e[1])];if(t==="interpolate"){const n=e.slice();for(let i=4;i<n.length;i+=2)n[i]=ed($u(n[i]));return n}if(t==="step"){const n=e.slice();for(let i=2;i<n.length;i+=2)n[i]=ed($u(n[i]));return n}return e}function td(e,t){if(Pr(e)){const i=ed(e);return _(i,t)}const n=$u(e);return Pr(n)?_(n,t):(console.warn(`Unknown margin value: ${JSON.stringify(e)}. Fallback to 0.`),{type:"literal-array",array:[0,0,0,0]})}function Y0(e){return Array.isArray(e)&&!Pr(e)?e[0]:e}function CM(e){if(Array.isArray(e)&&!Pr(e)&&e[1]!==void 0)return e[1]}function FM(e,t){const n=[];for(let i=1;i<e.length-1;i+=2)n.push({predicate:_(e[i],t),output:_(e[i+1],t)});return{type:"when",conditions:n,defaultOutput:_(e[e.length-1],t)}}function X0(e,t){const n={type:"interpolate",base:1,argument:_(e[2],t),steps:[]};e[1][0]==="exponential"&&e[1][1]!==void 0&&(n.base=e[1][1]);const i=e.slice(3);for(let r=0;r<i.length;r+=2){const s={key:_(i[r],t),value:_(i[r+1],t)};n.steps.push(s)}return n}function LM(e,t){return{type:e[0],value:_(e[1],t)}}function BM(e,t){const n=_(e[1],t),i=_(e[2],t);return{type:e[0],leftValue:n,rightValue:i}}function DM(e,t){return{type:"+",array:e.slice(1).map(n=>_(n,t))}}function OM(e,t){return{type:"*",array:e.slice(1).map(n=>_(n,t))}}function RM(e,t){const n=_(e[1],t),i=_(e[2],t);return{type:"^",base:n,exponent:i}}function zM(e,t){const n=_(e[1],t),i=_(e[2],t);return{type:"%",leftValue:n,rightValue:i}}function NM(e,t){const n=_(e[1],t),i=_(e[2],t),r=_(e[3],t);return{type:"clamp",value:n,min:i,max:r}}function GM(e,t){const n=_(e[1],t),i=e[2][0];if(i!=="get"&&i!=="global"&&i!=="source-attr"&&i!=="literal")throw new Error("InExpression supports only the get, global, source attr and literal expressions as a second argument");const r=_(e[2],t);return{type:"in",item:n,collection:r}}function kM(e,t){return{type:e[0],color:_(e[1],t),value:_(e[2],t)}}function UM(e,t){const n={type:"gltf-animation",options:[]},i=e.slice(1);for(let r=0;r<i.length;r++)n.options.push(_(i[r],t));return n}function VM(e,t){const n={type:"texture-animation",options:[]},i=e.slice(1);for(let r=0;r<i.length;r++)n.options.push(_(i[r],t));return n}function WM(e){const t={type:"easing",options:["linear"]},n=e.slice(1),i=n.slice(1);try{switch(n[0]){case"cubic-bezier":{if(i.length!==4||i.some(r=>typeof r!="number"))throw new Error;t.options=[n[0],...i];break}case"exponential":{if(i.length!==1||typeof i[0]!="number"||i[0]===1||i[0]<=0)throw new Error;t.options=[n[0],i[0]];break}case"ease":case"ease-in":case"ease-out":case"ease-in-out":case"linear":{t.options[0]=n[0];break}default:throw new Error}}catch(r){console.warn("Invalid texture animation easing expression:",e),console.warn('Fallback to ["easing", "linear"].')}return t}function HM(e,t){const n=e.slice(1),i=_(n[2],t);if(i.type==="interpolate"){const{argument:r}=i;return i.argument.type==="read-from-target"?{type:"mix",value1:_(n[0],t),value2:_(n[1],t),factor:r,factorInterpolate:i}:(console.warn(`Unknown expression in mix < interpolation chain: ${JSON.stringify(r)}`),null)}else return{type:"mix",value1:_(n[0],t),value2:_(n[1],t),factor:i}}function YM(e,t){const n={type:"step",steps:[],value:_(e[1],t)},i={key:0,value:_(e[2],t)};n.steps.push(i);const r=e.slice(3);for(let s=0;s<r.length;s+=2){const o={key:r[s],value:_(r[s+1],t)};n.steps.push(o)}return n}function Z0(e,t){var s;const n=e[0],i=vM(e[1]),r={type:n,property:i};if(t.usage!==Qe.Generator&&t.layer){const o=(s=t.precomputes.length)!=null?s:NaN;return t.precomputes.push({expr:r,usage:t.usage}),i==="selected"&&"selectedIdx"in t.layer&&(t.layer.selectedIdx=o),{type:"precompute",precomputeIndex:o}}else return r}function XM(e,t){return{type:"all",array:e.slice(1).map(n=>_(n,t))}}function ZM(e,t){return{type:"coalesce",array:e.slice(1).map(n=>{try{return _(n,t)}catch(i){return console.debug(`Unknown expression in coalesce: ${i}`),null}})}}function jM(e,t){return{type:"concat",array:e.slice(1).map(n=>_(n,t))}}function QM(e,t){return{type:"format",template:e[1],args:e.slice(2).map(n=>_(n,t))}}function qM(e,t){return{type:"any",array:e.slice(1).map(n=>_(n,t))}}function KM(e,t){return{type:"vertex-color",vertexValue:_(e[1],t),uniformValue:_(e[2],t),mixValue:_(e[3]||1,t)}}function JM(e,t){return e?e[1]==="mix"?{type:"color-effect",effect:{type:"mix",color:_(e[2],t),factor:_(e[3],t)}}:(Na(e[1]),W0):W0}function $M(e,t){return{type:"time",timeSource:_(e[1],t),format:e[2]}}function e_(e,t){return{type:"schedule",time:_(e[1],t),steps:_(e[2],t),detailResult:e[3]}}function t_(e,t){const n=_(e[1],t),i=_(e[2],t);return{type:"random",start:n,end:i}}function n_(e,t){return{type:"literal-array",array:e[1].map(n=>_(n,t))}}function i_(e){return{type:"literal-object",object:{type:"object",value:e[1]}}}function r_(e){if(!(e===void 0||!Array.isArray(e)))switch(e[0]){case"line-to-zigzag":return{type:"zigzag-modifier",step:e[1],width:e[2],stopLines:Number(e[3])};case"to-points":return{type:"to-points-modifier",modelLength:e[1],edgeMarging:e[2]}}}function s_(e){return e?e.map(t=>{var o,a,l,c,f,u,d,h,g,y,p,v,A,w,S,T,I,C,M,B,D,F,z,N,H,K,P;const n=(o=t.wallPadding)!=null?o:0,i=(a=t.texturePadding)!=null?a:0,r=t.sliceSize,s={image:t.image,minWallHeight:(l=t.minWallHeight)!=null?l:0,wallPadding:Array.isArray(n)?n:[n,n,n,n],texturePadding:Array.isArray(i)?i:[i,i,i,i],sliceSize:r?Array.isArray(r)?r:[r,r]:Array.isArray(t.size)?t.size:[t.size,t.size],vertical:{mode:(f=(c=t.vertical)==null?void 0:c.mode)!=null?f:"stripe-top",slicesCount:(d=(u=t.vertical)==null?void 0:u.slicesCount)!=null?d:1,minSliceRepeats:(g=(h=t.vertical)==null?void 0:h.minSliceRepeats)!=null?g:1,minResizeFactor:(p=(y=t.vertical)==null?void 0:y.minResizeFactor)!=null?p:0,maxResizeFactor:(A=(v=t.vertical)==null?void 0:v.maxResizeFactor)!=null?A:9999,maxInterval:(S=(w=t.vertical)==null?void 0:w.maxInterval)!=null?S:0},horizontal:{mode:(I=(T=t.horizontal)==null?void 0:T.mode)!=null?I:"repeat-with-stretch",slicesCount:(M=(C=t.horizontal)==null?void 0:C.slicesCount)!=null?M:1,minSliceRepeats:(D=(B=t.horizontal)==null?void 0:B.minSliceRepeats)!=null?D:1,minResizeFactor:(z=(F=t.horizontal)==null?void 0:F.minResizeFactor)!=null?z:0,maxResizeFactor:(H=(N=t.horizontal)==null?void 0:N.maxResizeFactor)!=null?H:9999,maxInterval:(P=(K=t.horizontal)==null?void 0:K.maxInterval)!=null?P:0}};return s.sliceSize[0]<=0||s.sliceSize[1]<=0?null:s}).filter(t=>t!==null):[]}function*o_(e,t,n){var d,h,g,y,p,v,A,w;const i=n?f_(n):id,r={},s=od((d=e.terrain)!=null?d:{},r,e.contours),o=J0((h=e.environment)!=null?h:{},r),a=$0(e.light,s,r),l=p_(e.graphicsPresets),c={id:t,revision:0,background:{color:Mr((y=(g=e.background)==null?void 0:g.color)!=null?y:yS)},light:a,layers:[],layersById:{[vo]:s,[Jf]:o},layerIdToInnerId:{},groupsById:{},iconBaseUrl:"",fontUrlTemplate:"",modelsBaseUrl:"",rasterSets:{byIndex:{},byKey:{}},icons:e.icons||{},models:Object.values((p=e.models)!=null?p:{}),modelIndex:AM(e.models||{}),labelingGroups:cM((v=e.labelingGroups)!=null?v:{}),dem:s,graphicsPresets:l,environment:o,targets:{_TMP_SHORELINE_GRADIENT:{channels:{r:!0},title:"Градиент береговой линии"}},globals:r},f=new N0,u=(A=e.layers)!=null?A:[];for(const S of u){const T=S.type==="group"||S.type==="slot"?yield*Lx(K0(S,i,r)):sd(S,r,void 0,i);if(!T){yield;continue}T.type==="group"&&(c.groupsById[T.innerId]=T,c.layerIdToInnerId[T.id]=T.innerId);const I=T.type==="group"?T.layers:[T];for(const C of I){const M=(w=C.lightingMode)!=null?w:a.defaultLightMode;a.lightingModes[M]||console.warn(`Не найден режим освещения ${M} для слоя ${C.type}. Будет использован режим освещения по умолчанию.`),c.layers.push(C),c.layersById[C.innerId]=C,c.layerIdToInnerId[C.id]=C.innerId,(C.type==="point"||C.type==="polygon"||C.type==="metricPoint"||C.type==="embankment"||C.type==="polygon3d")&&j0(C,f,c.icons).forEach(F=>{c.rasterSets.byKey[F.key]||(c.rasterSets.byIndex[F.index]=F,c.rasterSets.byKey[F.key]=F)}),yield}I.length||(yield)}return c}function a_(e,t={}){return e.type==="group"||e.type==="slot"?d_(e,t):rd(e,t)}function j0(e,t,n){const i=[];return q0(e).forEach(({image:r,imageType:s,anchor:o})=>{r&&Fr(r).forEach(a=>{typeof a!="string"||!a.length||i.push(Q0(a,s,t,o,n))})}),i}function Q0(e,t,n,i,r){const s=t==="icon"?ss(e,i[0],i[1]):Ca(e);return{type:Ir.Static,index:n.getUniqueIndex(s),key:s,isSvg:PT(r[e]),name:e,fileName:e,anchorX:i[0],anchorY:i[1],rasters:[]}}function q0(e){if(e.type==="point"){const n=co(e.style.iconAnchor);return[{image:e.style.iconImage,imageType:"icon",anchor:n}]}if(e.type==="metricPoint")return[{image:e.style.iconImage,imageType:"texture",anchor:[0,0]}];const t=[{image:e.style.textureImage,imageType:"texture",anchor:[0,0]}];return e.type==="polygon"&&t.push({image:e.style.normalMapTextureImage,imageType:"texture",anchor:[0,0]}),t}let nd=0;const id={next:()=>({innerId:Kf(),renderIndex:nd++})};function l_(e){var n;let t=0;for(const i of(n=e.layers)!=null?n:[])i.type==="group"?(t+=1,i.layers.forEach(r=>{(r.type==="custom"||r.style&&r.style.visibility!=="none")&&(t+=1)})):(i.type==="slot"||i.type==="custom"||i.style&&i.style.visibility!=="none")&&(t+=1);return t}function c_(e){const t=GE(e),n=nd;return nd+=e,{innerIdStart:t,renderIndexStart:n,count:e}}function f_(e){let t=0;return{next:()=>{if(t>=e.count)throw new Error("Handy style ID reservation exhausted");const n={innerId:e.innerIdStart+t,renderIndex:e.renderIndexStart+t};return t+=1,n}}}function u_(e,t){return e.type==="appearance"?{type:e.type,tipMovementAmplitude:_(e.tipMovementAmplitude,t)}:e.type==="repeat"?{type:e.type,tipMovementAmplitude:_(e.tipMovementAmplitude,t),iterationCount:e.iterationCount}:e}function rd(e,t={},n){return sd(e,t,n)}function sd(e,t={},n,i=id){var s,o,a,l,c,f,u,d,h,g,y,p,v,A,w,S,T,I,C,M,B,D,F,z,N,H,K;if(e.type==="custom")return ie(V({type:"custom",id:e.id},i.next()),{filter:!1,minzoom:-1/0,maxzoom:1/0,precomputes:[],style:{}});if(!e.style||e.style.visibility==="none")return;let r;try{const P=n?n.precomputes.slice(0):[],b={layer:e,usage:Qe.Generator,precomputes:P,globals:t},E=ie(V({id:e.id},i.next()),{filter:_(e.filter||!1,b),minzoom:ev(e.minzoom,-1/0),maxzoom:ev(e.maxzoom,1/0),precomputes:P,gpuState:e.gpuState,lightingMode:e.lightingMode,castShadows:(s=e.castShadows)!=null?s:!0,receiveShadows:(o=e.receiveShadows)!=null?o:!0,drawToTarget:e.drawToTarget,metadata:e.metadata});switch(b.usage=Qe.Uniform,e.type){case"line":{const x=$2(e.style);r=ie(V({},E),{type:e.type,interactive:(a=e.interactive)!=null?a:!0,ignoreTier:_((l=e.ignoreTier)!=null?l:!1,b),style:{visibility:ct(x.visibility),color:_(x.color,b),width:_(x.width,b),shift:_(x.shift,b),pattern:_(x.pattern,b),startCap:_(x.startCap,b),endCap:_(x.endCap,b),geometryModifier:_(x.geometryModifier,b),mode:x.mode,lengthUnits:g_(e.style.pattern),floorCulling:x.floorCulling}});break}case"lineExtrusion":{const x=tS(e.style);r=ie(V({},E),{type:e.type,style:{visibility:ct(x.visibility),sideColor:_(x.sideColor,b),strokeWidth:_(x.strokeWidth,b),strokeColor:_(x.strokeColor,b),sideStrokeColor:_(x.sideStrokeColor,b),height:_(x.height,b),nearCameraFade:_(x.nearCameraFade,b)}});break}case"polygon":{const x=Q2(e.style),L=Ro(x.textureSize)?nv(x.textureSize):x.textureSize,O=Ro(x.normalMapTextureSize)?nv(x.normalMapTextureSize):x.normalMapTextureSize;E.drawToTarget==="_TMP_SHORELINE_GRADIENT"&&(x.strokeWidth=0,x.strokeColor="#00000000",x.color=["mix","#000000","#FF0000",["vertexAttribute","denormalized_distance_to_line"]]),r=ie(V({},E),{type:e.type,interactive:(c=e.interactive)!=null?c:!0,ignoreTier:_((f=e.ignoreTier)!=null?f:!1,b),style:{visibility:ct(x.visibility),color:_(x.color,b),textureImage:_(x.textureImage,b),textureSize:$i(L,b),textureOpacity:_(x.textureOpacity,b),strokeColor:_(x.strokeColor,b),strokeWidth:_(x.strokeWidth,b),lengthUnits:tv(x.textureSize),metallic:_(x.metallic,b),roughness:_(x.roughness,b),normalMapTextureImage:_(x.normalMapTextureImage,b),normalMapTextureSize:$i(O,b),normalMapTextureAnimation:_(x.normalMapTextureAnimation,b),normalMapTextureLengthUnits:tv(x.normalMapTextureSize),colorEffect:_(x.colorEffect,b),floorCulling:x.floorCulling}});break}case"polygon3d":case"embankment":{const x=q2(e.style),L=e.type==="polygon3d"?{depthFunc:V0.LEQUAL}:{};r=ie(V({},E),{type:e.type,interactive:(u=e.interactive)!=null?u:!0,style:{visibility:ct(x.visibility),color:_(x.color,b),textureImage:_(x.textureImage,b),textureSize:$i(x.textureSize,b),textureOpacity:_(x.textureOpacity,b),strokeColor:_(x.strokeColor,b),strokeWidth:_(x.strokeWidth,b),nearCameraFade:_(x.nearCameraFade,b),elevation:_(x.elevation,b)},gpuState:V(V({},L),E.gpuState)}),e.type==="polygon3d"&&(r.interactiveOcclusion=(d=e.interactiveOcclusion)!=null?d:!0);break}case"metricPoint":{const x=K2(e.style);r=ie(V({},E),{type:e.type,interactive:(h=e.interactive)!=null?h:!0,ignoreTier:_((g=e.ignoreTier)!=null?g:!1,b),style:{visibility:ct(x.visibility),iconImage:_(x.iconImage,b),color:_(x.color,b),rotation:_(x.rotation,b),width:_(x.width,b),height:_(x.height,b)}});break}case"polygonExtrusion":{const x=J2(e.style);r=ie(V({},E),{type:e.type,interactive:(y=e.interactive)!=null?y:!0,sideTextureIndices:[],style:{visibility:ct(x.visibility),topColor:_(x.topColor,b),sideColor:_(x.sideColor,b),strokeColor:_(x.strokeColor,b),strokeWidth:_(x.strokeWidth,b),sideStrokeColor:_(x.sideStrokeColor,b),height:_(x.height,ie(V({},b),{usage:Qe.Generator})),nearCameraFade:_(x.nearCameraFade,b),sideTextures:s_(x.sideTextures),colorEffect:_(x.colorEffect,b),floorCulling:x.floorCulling}});break}case"dashedLine":{const x=rS(e.style);r=ie(V({},E),{type:e.type,interactive:(p=e.interactive)!=null?p:!0,ignoreTier:_((v=e.ignoreTier)!=null?v:!1,b),style:{visibility:ct(x.visibility),color:_(x.color,b),gapColor:_(x.gapColor,b),width:_(x.width,b),shift:_(x.shift,b),gapLength:_(x.gapLength,b),dashLength:_(x.dashLength,b),gapTurnsOnly:x.gapTurnsOnly,geometryModifier:_(x.geometryModifier,b),mode:x.mode,floorCulling:x.floorCulling}});break}case"shiftedLine":{const x=sS(e.style);r=ie(V({},E),{type:e.type,interactive:(A=e.interactive)!=null?A:!0,ignoreTier:_((w=e.ignoreTier)!=null?w:!1,b),style:{visibility:ct(x.visibility),color:_(x.color,b),width:_(x.width,b),shift:_(x.shift,b)}});break}case"oneWayLine":{const x=iS(e.style);r=ie(V({},E),{type:e.type,ignoreTier:_((S=e.ignoreTier)!=null?S:!1,b),interactive:(T=e.interactive)!=null?T:!1,style:{visibility:ct(x.visibility),color:_(x.color,b),lineWidth:_(x.lineWidth,b),lineLength:_(x.lineLength,b),tipWidth:x.tipWidth,tipHeight:x.tipHeight,roundingRadius:_(x.roundingRadius,b),priority:x.priority,duplicationSpacing:_(x.duplicationSpacing,b),endingOffsets:x.endingOffsets,labelingGroup:x.labelingGroup,colorEffect:_(x.colorEffect,b),floorCulling:x.floorCulling,mode:_(x.mode,b)}});break}case"buildingModel":{const x=eS(e.style);r=ie(V({},E),{type:e.type,interactive:(I=e.interactive)!=null?I:!0,style:{visibility:ct(x.visibility),color:_(x.color,b),strokeColor:_(x.strokeColor,b),strokeWidth:_(x.strokeWidth,b),nearCameraFade:_(x.nearCameraFade,b)}});break}case"labelLine":{const x=nS(e.style);r=ie(V({},E),{type:e.type,interactive:(C=e.interactive)!=null?C:!1,ignoreTier:_((M=e.ignoreTier)!=null?M:!1,b),style:{visibility:ct(x.visibility),textField:_(x.textField,ie(V({},b),{usage:Qe.Labeling})),textFont:x.textFont,textColor:_(x.textColor,b),textFontSize:_(x.textFontSize,b),textLetterSpacing:x.textLetterSpacing,textHaloColor:_(x.textHaloColor,b),textHaloWidth:x.textHaloWidth,textPriority:_(x.textPriority,b),textLabelingSideMargin:x.textLabelingSideMargin,textDuplicationSpacing:_(x.textDuplicationSpacing,b),labelingGroup:x.labelingGroup,lineEndingOffsets:x.lineEndingOffsets,colorEffect:_(x.colorEffect,b),floorCulling:x.floorCulling,mode:_(x.mode,b)}});break}case"point":{const x=aS(e.style);r=ie(V({},E),{type:e.type,interactive:(B=e.interactive)!=null?B:!0,style:{visibility:ct(x.visibility),allowOverlap:x.allowOverlap,allowElevation:x.allowElevation,elevation:_(x.elevation,b),iconImage:_(x.iconImage,b),iconAnchor:$i(x.iconAnchor,b),iconOffset:$i(x.iconOffset,b),iconWidth:_(x.iconWidth,b),iconTextField:_(x.iconTextField,ie(V({},b),{usage:Qe.Labeling})),iconTextFont:er(x.iconTextFont,b),iconTextAnchor:$i(x.iconTextAnchor,b),iconTextOffset:$i(x.iconTextOffset,b),iconTextColor:_(x.iconTextColor,b),iconTextFontSize:_(x.iconTextFontSize,b),iconTextLineHeight:x.iconTextLineHeight,iconTextLetterSpacing:x.iconTextLetterSpacing,iconTextPadding:$i(x.iconTextPadding,b),iconTextHaloWidth:fo(It(x.iconTextHaloWidth)),iconTextHaloColor:_(x.iconTextHaloColor,b),iconOpacity:_(x.iconOpacity,b),iconPriority:_(x.iconPriority,b),iconLabelingMargin:td(x.iconLabelingMargin,b),iconLabelingGroup:x.iconLabelingGroup,iconRotation:_(x.iconRotation,b),textField:_(It(x.textField),ie(V({},b),{usage:Qe.Labeling})),textFont:_(It(x.textFont),b),textColor:_(It(x.textColor),b),textFontSize:_(It(x.textFontSize),b),textLineHeight:fo(It(x.textLineHeight),1.2),textLetterSpacing:fo(It(x.textLetterSpacing)),textField2:er(Ui(x.textField),ie(V({},b),{usage:Qe.Labeling})),textFont2:er(Ui(x.textFont),b),textColor2:er(Ui(x.textColor),b)||_(It(x.textColor),b),textFontSize2:er(Ui(x.textFontSize),b)||_(It(x.textFontSize),b),textMaxLengthPerLine:x.textMaxLengthPerLine,textPlacement:_(x.textPlacement,b),textPriority:_(x.textPriority,b),textOffset:_(It(x.textOffset),b),textOffset2:er(Ui(x.textOffset),b),textHaloColor:_(It(x.textHaloColor),b),textHaloColor2:er(Ui(x.textHaloColor),b)||_(It(x.textHaloColor),b),textHaloWidth:fo(It(x.textHaloWidth)),textHaloWidth2:fo(Ui(x.textHaloWidth)||It(x.textHaloWidth)),textLabelingMargin:td(Y0(x.textLabelingMargin),b),textLabelingMargin2:td(CM(x.textLabelingMargin)||Y0(x.textLabelingMargin),b),textLabelingGroup:It(x.textLabelingGroup),textLabelingGroup2:Ui(x.textLabelingGroup)||It(x.textLabelingGroup),duplicationSpacing:_(x.duplicationSpacing,b),endingOffsets:x.endingOffsets,floorCulling:x.floorCulling,iconMetaphorImage:er(x.iconMetaphorImage,b)}});break}case"arrow":{const x=lS(e.style);r=ie(V({},E),{type:e.type,interactive:(D=e.interactive)!=null?D:!1,ignoreTier:_((F=e.ignoreTier)!=null?F:!1,b),style:{visibility:ct(x.visibility),color:_(x.color,b),strokeColor:_(x.strokeColor,b),lineWidth:_(x.lineWidth,b),strokeWidth:_(x.strokeWidth,b),tipWidth:_(x.tipWidth,b),tipHeight:_(x.tipHeight,b),roundingRadius:_(x.roundingRadius,b),animation:u_(x.animation,b)}});break}case"raster":{const x=cS(e.style);r=ie(V({},E),{type:e.type,ignoreTier:_((z=e.ignoreTier)!=null?z:!1,b),style:{visibility:ct(x.visibility),opacity:_(x.opacity,b)}});break}case"circle":{const x=oS(e.style);r=ie(V({},E),{type:e.type,interactive:(N=e.interactive)!=null?N:!0,style:{visibility:ct(x.visibility),color:_(x.color,b),strokeColor:_(x.strokeColor,b),strokeColor2:_(x.strokeColor2,b),width:_(x.width,b),strokeWidth:_(x.strokeWidth,b),strokeWidth2:_(x.strokeWidth2,b)}});break}case"heatmap":{const x=fS(e.style);r=ie(V({},E),{type:e.type,style:{visibility:ct(x.visibility),color:_(x.color,b),radius:_(x.radius,b),opacity:_(x.opacity,b),intensity:_(x.intensity,b),weight:_(x.weight,b),downscale:x.downscale},framebufferId:{framebuffer:za}});break}case"model":{const x=hS(e.style);r=ie(V({},E),{interactive:(H=e.interactive)!=null?H:!0,interactiveOcclusion:(K=e.interactiveOcclusion)!=null?K:!0,type:"gltfModel",style:{visibility:ct(x.visibility),modelSrc:_(x.modelSrc,b),offset:_(x.offset,ie(V({},b),{usage:Qe.Generator})),scale:_(x.scale,ie(V({},b),{usage:Qe.Generator})),rotation:_(x.rotation,ie(V({},b),{usage:Qe.Generator})),scene:_(x.scene,b),color:_(x.color,b),linkedIds:_(x.linkedIds,b),colorTextureUvIndex:x.colorTextureUvIndex,roughness:x.roughness,metallic:x.metallic,preventObjectsHiding:x.preventObjectsHiding,nearCameraFade:_(x.nearCameraFade,b),ignoreGlobalLighting:x.ignoreGlobalLighting,showRatio:_(x.showRatio,b),lightingModel:x.lightingModel,playAnimation:_(x.playAnimation,b),geometryModifier:_(x.geometryModifier,b),colorEffect:_(x.colorEffect,b),floorCulling:x.floorCulling}});break}case"overpass":{const x=pS(e.style);r=ie(V({},E),{type:e.type,style:{visibility:ct(x.visibility),debug:x.debug,sideColor:_(x.sideColor,b),bottomColor:_(x.bottomColor,b),topColor:_(x.borderTopColor,b),strokeColor:_(x.strokeColor,b),strokeWidth:_(x.strokeWidth,b),thickness:_(x.thickness,b),borderHeight:_(x.borderHeight,b),borderWidth:_(x.borderWidth,b),color:_(x.color,b),nearCameraFade:_(x.nearCameraFade,b),tunnelHeight:_(x.tunnelHeight,b)}});break}case"tunnel":{const x=gS(e.style);r=ie(V({},E),{type:e.type,style:{visibility:ct(x.visibility),sideColor:_(x.sideColor,b),bottomColor:_(x.bottomColor,b),topColor:_(x.topColor,b),strokeColor:_(x.strokeColor,b),strokeWidth:_(x.strokeWidth,b),color:_(x.color,b),nearCameraFade:_(x.nearCameraFade,b)}});break}}}catch(P){if(P instanceof Ku){console.warn(`Problem with layer #${e.id}: ${P}`);return}throw P}return r}function d_(e,t={}){const n=K0(e,id,t);let i=n.next();for(;!i.done;)i=n.next();return i.value}function*K0(e,t,n={}){var o,a;if(e.type==="slot")return ie(V({id:e.id},t.next()),{type:"group",layers:[],orderBy:[],precomputes:[]});const i=ie(V({id:e.id},t.next()),{type:e.type,layers:[],orderBy:[],precomputes:[]}),r={layer:e,usage:Qe.Uniform,precomputes:i.precomputes};i.orderBy=(a=(o=e.orderBy)==null?void 0:o.map(l=>Z0(l,r)))!=null?a:[];const s=e.layers.length;for(let l=0;l<s;l+=1){if(!(l in e.layers)){yield;continue}const c=sd(e.layers[l],n,i,t);c&&(c.groupId=i.innerId,c.groupIndex=l,c.renderIndex=i.renderIndex,i.layers.push(c)),yield}return i}function od(e,t={},n){const i=dS(e),r={id:"dem",type:"dem",innerId:vo,filter:!0,precomputes:[],minzoom:-1/0,maxzoom:1/0,renderIndex:SM,style:{},framebufferId:{hillshade:za,flatBottom:za},lightingMode:qu},s={layer:e,usage:Qe.Uniform,globals:t,precomputes:r.precomputes};if(r.style={visibility:"visible",lightingDirection:typeof i.lightingDirection!="undefined"?_(i.lightingDirection,s):null,shadingIntensity:_(i.shadingIntensity,s),shadingPalette:X0(i.shadingPalette,s),verticalScale:_(i.verticalScale,s)},n&&Object.keys(n).length>0){const o={layer:n,usage:Qe.Uniform,globals:t,precomputes:r.precomputes},a=uS(n);r.style.contours={interval:_(a.interval,o),minorColor:_(a.minorColor,o),majorColor:_(a.majorColor,o),indexColor:_(a.indexColor,o),minorWidth:_(a.minorWidth,o),majorWidth:_(a.majorWidth,o),indexWidth:_(a.indexWidth,o),minorLabelFontSize:_(a.minorLabelFontSize,o),minorLabelFont:_(a.minorLabelFont,o),minorLabelColor:_(a.minorLabelColor,o),minorLabelHaloRadius:_(a.minorLabelHaloRadius,o),minorLabelHaloColor:_(a.minorLabelHaloColor,o),majorLabelFontSize:_(a.majorLabelFontSize,o),majorLabelFont:_(a.majorLabelFont,o),majorLabelColor:_(a.majorLabelColor,o),majorLabelHaloRadius:_(a.majorLabelHaloRadius,o),majorLabelHaloColor:_(a.majorLabelHaloColor,o),indexLabelFontSize:_(a.indexLabelFontSize,o),indexLabelFont:_(a.indexLabelFont,o),indexLabelColor:_(a.indexLabelColor,o),indexLabelHaloRadius:_(a.indexLabelHaloRadius,o),indexLabelHaloColor:_(a.indexLabelHaloColor,o)}}return r}function h_(e){let t=e;if(Array.isArray(t)&&t[0]==="literal"&&(t=t[1]),!Array.isArray(t)||t.length!==3)return;const[n,i,r]=t;if(typeof n!="string"||typeof i!="string")return;const s=Mr(n),o=Mr(i),a=Number(r);if(Number.isFinite(a))return{color1:s,color2:o,mid:Math.min(1,Math.max(0,a))}}function ad(e,t){if(_n(e))return e;const n=e;if(n!==void 0&&Qt(n))return n;const i=h_(e);return i?ie(V({},i.color1),{gradientValue:i.color2.value,gradientMid:i.mid}):_(e!=null?e:"#FAFDFF00",t)}function J0(e,t={}){const n=mS(e),i={layer:e,usage:Qe.Uniform,globals:t,precomputes:[]},r={id:"sky",type:"custom",innerId:Jf,filter:!0,precomputes:[],minzoom:-1/0,maxzoom:1/0,renderIndex:EM,style:{}};return r.style={visibility:"visible",skyColor:ad(n.skyColor,i),fogColor:ad(n.fogColor,i),starsIntensity:_(n.starsIntensity,i)},r}function $0(e,t,n={}){var a,l;const i=vS(e),r={},s={layer:i,usage:Qe.Uniform,globals:n,precomputes:[]},o={ambientColor:{type:"color",value:[255,255,255,255]},ambientIntensity:0,dir1Color:{type:"color",value:[255,255,255,255]},dir1Altitude:0,dir1Azimuth:0,dir1Intensity:0,dir2Color:{type:"color",value:[255,255,255,255]},dir2Altitude:0,dir2Azimuth:0,dir2Intensity:0,shadowRadius:(a=i.shadows)==null?void 0:a.radius};for(const c in i.lightingModes){const f={ambientColor:{type:"color",value:[255,255,255,255]},ambientIntensity:0,dir1Color:{type:"color",value:[255,255,255,255]},dir1Altitude:0,dir1Azimuth:0,dir1Intensity:0,dir2Color:{type:"color",value:[255,255,255,255]},dir2Altitude:0,dir2Azimuth:0,dir2Intensity:0,shadowRadius:(l=i.shadows)==null?void 0:l.radius},u=i.lightingModes[c].map(g=>i.sources[g]).filter(Boolean),d=i.shadows?i.sources[i.shadows.source]:void 0;let h=0;u.forEach(g=>{g.color||(g.color="#FFFFFF"),g.type==="ambient"?(f.ambientColor=_(g.color,s),f.ambientIntensity=_(g.intensity,s),c===i.defaultLightingMode&&(o.ambientColor=f.ambientColor,o.ambientIntensity=f.ambientIntensity)):g.type==="directional"&&(g===d&&(f.shadowLightIndex=h),h===0?(h++,f.dir1Color=_(g.color,s),f.dir1Altitude=_(g.altitude,s),f.dir1Azimuth=_(g.azimuth,s),f.dir1Intensity=_(g.intensity,s),c===i.defaultLightingMode&&(o.dir1Color=f.dir1Color,o.dir1Intensity=f.dir1Intensity,o.dir1Azimuth=t.style.lightingDirection===null?f.dir1Azimuth:t.style.lightingDirection,o.dir1Intensity=_(g.intensity,s),o.dir1Altitude=f.dir1Altitude)):h===1&&(h++,f.dir2Color=_(g.color,s),f.dir2Altitude=_(g.altitude,s),f.dir2Azimuth=_(g.azimuth,s),f.dir2Intensity=_(g.intensity,s)))}),r[c]=f}return r[qu]=o,{defaultLightMode:i.defaultLightingMode,lightingModes:r}}function p_(e){return _g(e)}function ev(e,t){return typeof e=="number"&&!Number.isNaN(e)?e:t}function g_(e){return e&&Ro(e[2])?Wi.Meters:Wi.Pixels}function tv(e){return Ro(e)?Wi.Meters:Wi.Pixels}function Ro(e,t=!1){return Array.isArray(e)&&(e[0]==="meters-to-pixels"||e[0]==="literal"&&!t&&Array.isArray(e[1])&&e[1].some(n=>Ro(n,!0)))}function nv(e){if(Array.isArray(e)){if(e[0]==="meters-to-pixels"){if(typeof e[1]=="number"&&!Number.isNaN(e[1]))return e[1]}else if(e[0]==="literal"&&Array.isArray(e[1])){const[t,n]=e[1];if([t,n].every(i=>Array.isArray(i)&&i[0]==="meters-to-pixels"&&typeof i[1]=="number"&&!Number.isNaN(i[1])))return[t[1],n[1]]}}return console.warn(`Can't extract meter-to-pixels values from expression ${JSON.stringify(e)}. Size set to 0.`),0}function ct(e){return e==="none"?"hidden":e}const Rl=0,m_=1,v_={type:Ir.Loaded,index:-1,key:ss("",.5,.5),isSvg:!1,name:"",fileName:"",rasters:[]},y_=["default","marker","markerText","htmlLabel"],x_={default:0,marker:1,markerText:2,htmlLabel:3,pointLabel:4},w_={default:{default:!0,marker:!1,markerText:!0,htmlLabel:!0,pointLabel:!1},marker:{default:!1,marker:!1,markerText:!0,htmlLabel:!1,pointLabel:!1},markerText:{default:!0,marker:!0,markerText:!0,htmlLabel:!1,pointLabel:!1},htmlLabel:{default:!0,marker:!1,markerText:!1,htmlLabel:!1,pointLabel:!1},pointLabel:{default:!1,marker:!1,markerText:!1,htmlLabel:!1,pointLabel:!0}};function iv(e){const t=[],n=Object.keys(wr).length;for(let i=0;i<n;i++)t[i]=NaN;for(const i in e){if(wr[i]===void 0)throw new Error(`No such tile prop '${i}'`);t[wr[i]]=e[i]}return t}class A_{constructor(){this.needRenderIndexRebuild=!1,this.style={id:Rl,revision:0,background:{color:Mr("#f6f2de")},light:{defaultLightMode:"global",lightingModes:{}},layers:[],layersById:{},layerIdToInnerId:{},groupsById:{},iconBaseUrl:"",fontUrlTemplate:"",modelsBaseUrl:"",rasterSets:{byIndex:{},byKey:{}},labelingGroups:{indexToGroup:y_,groupToIndex:x_,table:w_},icons:{},models:[],modelIndex:{},dem:od({}),environment:J0({}),graphicsPresets:{light:{},normal:{},immersive:{}},targets:{},globals:{}},this.zIndexById={};const t=rd({type:"line",id:"debug-tile-bounds",minzoom:-1/0,maxzoom:1/0,style:{color:"#ff0000",width:1}},this.style.globals);t&&this.addLayer(t,0)}get hasDynamicObjects(){return this.style.layers.length>1}getRenderIndexById(t){var n;return((n=this.style.layersById[t])==null?void 0:n.renderIndex)||0}getStyle(){return this.style}appendRasterSet(t,n){this.style.rasterSets.byIndex[t.index]=t,n!==void 0&&(this.style.rasterSets.byKey[n]=t)}removeRasterSet(t){this.style.rasterSets.byIndex[t]=v_}getLabelingGroupIndex(t){const{groupToIndex:n}=this.style.labelingGroups;return n[t]!==void 0?n[t]:n.default}addLayer(t,n){this.style.layersById[t.innerId]||(this.style.layers.push(t),this.style.layersById[t.innerId]=t,n!==void 0&&(this.zIndexById[t.innerId]=n),this.needRenderIndexRebuild=!0)}removeLayer(t){const n=this.style.layersById[t];if(!n)return;const i=this.style.layers.indexOf(n);i!==-1&&this.style.layers.splice(i,1),delete this.style.layersById[t],delete this.zIndexById[t]}updateLayerStyle(t,{style:n,precomputes:i}){const r=this.style.layersById[t];r&&(r.style=n,r.precomputes=i)}update(){this.needRenderIndexRebuild&&(this.rebuildRenderIndex(),this.needRenderIndexRebuild=!1)}rebuildRenderIndex(){this.style.layers.sort((t,n)=>{var s,o;const i=(s=this.zIndexById[t.innerId])!=null?s:0,r=(o=this.zIndexById[n.innerId])!=null?o:0;return i-r});for(let t=0;t<this.style.layers.length;t++)this.style.layers[t].renderIndex=t}}function b_(e,t,n){const i="identify-scene",r=document.getElementById(i),s=parseInt(Gc.sceneOpacity.toString(),10);if(s===0){r&&r.parentNode&&r.parentNode.removeChild(r);return}const o=t[0],a=t[1],l=document.createElement("canvas");l.id=i,l.width=o,l.height=a;const c=l.style;c.imageRendering="pixelated",c.pointerEvents="none",c.position="absolute",c.width=n.size[0]+"px",c.height=n.size[1]+"px",c.top=`${n.viewport.top}px`,c.left=`${n.viewport.left}px`;const f=l.getContext("2d");f.clearRect(0,0,o,a);const u=f.createImageData(o,a);for(let d=0;d<o;d++)for(let h=0;h<a;h++)for(let g=0;g<4;g++){const y=(d+h*o)*4+g,p=(d+(a-1-h)*o)*4+g;u.data[y]=g===3?s:e[p]}f.putImageData(u,0,0),r&&r.parentNode?r.parentNode.replaceChild(l,r):document.body.appendChild(l)}function rv(e,t,n){const r=ae,s={x:new Uint16Array([0,r,r,0,0]),y:new Uint16Array([0,0,r,r,0])},o=iv({}),a=go(n,xf,wr,o,Np,!0);L0({collector:e,generator:Rt.generate,args:[Rl,t,a,Bt([0,0,0,0]),s]})}function sv(){try{return!!localStorage.getItem("debugStatusCompile")}catch(e){return console.warn("Error accessing localStorage in forceGlStatusCheck:",e),!1}}const ld={defines:[],hash:""},Wr=class Wr{constructor(t,n,i=ld,r=ld){this.shader=null,this.type=t==="vertex"?Wr.Vertex:Wr.Fragment,this.sourceCode=n,this.commonDefinitions=i,this.definitions=r}static createShaderDefinitions(t){return{defines:t,hash:t.map(i=>{var r;return`${i.type}:${(r=i.value)!=null?r:""}`}).join("")}}get(t,n=!0){return this.shader||this.compile(t,n),this.shader}remove(t){this.shader&&(t.deleteShader(this.shader),this.shader=null)}getCode(){return this.assembleShaderText().slice()}compile(t,n){const i=this.type===Wr.Vertex?t.VERTEX_SHADER:t.FRAGMENT_SHADER,r=this.shader=t.createShader(i);if(!r||t.isContextLost())throw new Error(`[WebGl] Failed to create shader. Shader is null: ${String(!r)}. Context is lost: ${String(t.isContextLost())}`);const s=this.assembleShaderText();if(t.shaderSource(r,s),t.compileShader(r),n&&sv()&&!t.getShaderParameter(r,t.COMPILE_STATUS)){const o=t.getShaderInfoLog(r),a=(s||"").split(`
`);throw new Error(o?o.replace(/^ERROR:\s*(\d+):(\d+):\s*(.*?)\n/,function(l,c,f,u){const d=a[Number(f)-1];return d?`ERROR ${c}:${f}: ${u}
Erroneous line: <<${d}>>
`:l}):"Unknown shader compilation error")}}assembleShaderText(){const t=this.sourceCode,n=[...this.commonDefinitions.defines,...this.definitions.defines].map(s=>s.value!==void 0?"#define "+s.type+" "+s.value:"#define "+s.type),i=Array.isArray(t)?t:[t||""];let r=!0;for(const s of i)r&&s.indexOf("#version")!==-1?n.unshift(s):n.push(s),r=!1;return n.join(`
`)}};Wr.Vertex=1,Wr.Fragment=2;let zl=Wr;function ov(e,t,n,i){for(const r of t)T_(e,n,r,i)}function S_(e,t,n){var s;const i=t.buffer,r=[];for(const o of t.generatedObjects){let a=o.rangeEnd-o.rangeStart===n;if(!a&&((s=o.meta)==null?void 0:s.buildingId)>0&&o.attributes.includes(String(o.meta.buildingId))){const f=(o.rangeEnd-o.rangeStart)/n,u=new Set,d=[],h=new DataView(i);for(let g=0;g<f;g++){const y=o.rangeStart+g*n,p=h.getUint16(y,!0),v=h.getUint16(y+2,!0),A=h.getUint16(y+4,!0),w=`${p},${v},${A}`;u.has(w)||(u.add(w),d.push(g))}if(d.length<f){const g=new Uint8Array(i);for(let y=0;y<d.length;y++){const p=o.rangeStart+d[y]*n,v=o.rangeStart+y*n;p!==v&&g.copyWithin(v,p,p+n)}o.rangeEnd=o.rangeStart+d.length*n,a=d.length===1}}const l=new DataView(i,o.rangeStart,o.rangeEnd-o.rangeStart),c=e.createBuffer(l);c.purpose="instanced",c.drawType=ht.StaticDraw,o.buffer=c,a&&(o.tMatrix3x3=new Float32Array(l.buffer,o.rangeStart+8,9)),r.push(c)}return r}function E_(e,t,n,i,r){const s=e.createBuffer(n);s.purpose="attributes",s.drawType=ht.StaticDraw;const o=[];let a,l,c;return r&&(c=e.createBuffer(r,{itemSize:1,dataType:ht.UnsignedShort},!0),c.elementsType=ht.UnsignedShort),t.forEach(f=>{const u=e.getShaderProgram(f.programName),d=f.vaoCreator(s,u,c);if(f.needsVisibilityBuffer){if(!a||!l){const h=new Uint8Array(new Array(i).fill(1));a=e.createBuffer(h,void 0,!1,!0),a.purpose="visibility",l=new z0(a,{itemSize:1,dataType:ht.UnsignedByte})}d.setAttribute("a_float_visibility",l)}o.push(d)}),{buffer:s,visibilityBuffer:a,vaos:o}}function T_(e,t,n,i){const{renderer:r,instanceLinker:s,map:o,labeler:a}=e,{symbol:l,sink:c,generatedObjects:f,buffer:u,elementsBuffer:d,elementSize:h}=n;if(r.symbolSettingsList[l]===void 0)return;const y=av(r,l,c);if(y.length===0)return;const p=Oo(l,c);if(y[0].instanceBinder){const M=S_(r,n,p);t.buffers.push(...M),tM(e,t,n,p),s.enqueue(n,t);return}let v=0;d&&h?v=d.byteLength/h:v=u.byteLength/p;const{buffer:A,vaos:w,visibilityBuffer:S}=E_(r,y,u,v,d);t.pushBuffer(A),S&&t.pushBuffer(S);const T=eM(e,t,n,p),I=l==="polygonExtrusion"&&!o.getFeatureFlag("transparentBuildingsOff")||l==="lineExtrusion",C=c==="billboard"&&l==="labelLine";for(let M=0;M<f.length;M++){const{rangeStart:B,rangeEnd:D,attributes:F,drawMode:z,meta:N,objectsData:H}=f[M];let K;C&&N&&Array.isArray(N.guidelines)&&N.guidelines.length&&typeof N.guidelinesHash=="number"&&!Number.isNaN(N.guidelinesHash)&&(K=a.addGuidelineTexture(N.guidelinesHash,N.guidelines));const P=B0[l].sinks[c].unpackObjectAttributes(F),b=[];for(let E=0;E<y.length;E++){const x=y[E],L=w[E],O=x.uniformSet||"fill",R={id:ga(),type:If.Tile,layerSettings:x,start:B/p,count:(D-B)/p,attributes:P,renderingProperties:{},attributesHash:JSON.stringify(F)+"_"+O+"_"+t.detailLevel,guidelineTextureKey:K,vao:L,drawMode:z,tile:t,symbol:l,sink:c,meta:N,canRender:!0};I&&(R.shaderDefinitions=zl.createShaderDefinitions([{type:"BLEND"}])),r.requestAsyncShaderProgramLink(x.programName,R.shaderDefinitions),t.push(R),T!==void 0&&t.registerSundaVertexBufferId(R.id,T),x.needsVisibilityBuffer&&b.push(L)}i&&b.length>0&&H&&t instanceof Ul&&P_(H,t,b,i,!!P.floorId)}}function P_(e,t,n,i,r){const s=r?t.floorObjectsMap:t.objectsMap,o=[];for(const a in e){const l=e[a];let c=s[a];c||(c=new Map,s[a]=c);let f=c.get(n);f||(f=[],c.set(n,f));for(const u of l)f.push(u);i.isHidden(a,Ps.PolygonExtrusion)&&o.push(a)}i.triggerIdUpdate(o)}function av(e,t,n){const i=e.symbolSettingsList[t];if(i===void 0)return[];const r=i[n];return r==null||r.length===0?[]:r}const I_=4,M_=.001,__=1e-7,C_=10,zo=11,Nl=1/(zo-1),F_=typeof Float32Array=="function";function lv(e,t){return 1-3*t+3*e}function cv(e,t){return 3*t-6*e}function fv(e){return 3*e}function Gl(e,t,n){return((lv(t,n)*e+cv(t,n))*e+fv(t))*e}function uv(e,t,n){return 3*lv(t,n)*e*e+2*cv(t,n)*e+fv(t)}function L_(e,t,n,i,r){let s,o,a=0;do o=t+(n-t)/2,s=Gl(o,i,r)-e,s>0?n=o:t=o;while(Math.abs(s)>__&&++a<C_);return o}function B_(e,t,n,i){for(let r=0;r<I_;++r){const s=uv(t,n,i);if(s===0)return t;const o=Gl(t,n,i)-e;t-=o/s}return t}function D_(e){return e}function dv(e,t,n,i){if(!(0<=e&&e<=1&&0<=n&&n<=1))throw new Error("bezier x values must be in [0, 1] range");if(e===t&&n===i)return D_;const r=F_?new Float32Array(zo):new Array(zo);for(let o=0;o<zo;++o)r[o]=Gl(o*Nl,e,n);function s(o){let a=0,l=1;const c=zo-1;for(;l!==c&&r[l]<=o;++l)a+=Nl;--l;const f=(o-r[l])/(r[l+1]-r[l]),u=a+f*Nl,d=uv(u,e,n);return d>=M_?B_(o,u,e,n):d===0?u:L_(o,a,a+Nl,e,n)}return function(a){return a===0?0:a===1?1:Gl(s(a),t,i)}}function hv(e,t,n,i){return t+n/i*e}const O_=dv(.25,.1,.25,1);function pv(e,t,n,i){return t+n*O_(e/i)}function R_(e,t,n,i){return n*(e/=i)*e+t}function z_(e,t,n,i){return-n*(e/=i)*(e-2)+t}function N_(e,t,n,i){return(e/=i/2)<1?n/2*e*e+t:-n/2*(--e*(e-2)-1)+t}function G_(e,t,n,i){return n*(e/=i)*e*e+t}function k_(e,t,n,i){return n*((e=e/i-1)*e*e+1)+t}function U_(e,t,n,i){return(e/=i/2)<1?n/2*e*e*e+t:n/2*((e-=2)*e*e+2)+t}function V_(e,t,n,i){return n*(e/=i)*e*e*e+t}function W_(e,t,n,i){return-n*((e=e/i-1)*e*e*e-1)+t}function H_(e,t,n,i){return(e/=i/2)<1?n/2*e*e*e*e+t:-n/2*((e-=2)*e*e*e-2)+t}function Y_(e,t,n,i){return n*(e/=i)*e*e*e*e+t}function X_(e,t,n,i){return n*((e=e/i-1)*e*e*e*e+1)+t}function Z_(e,t,n,i){return(e/=i/2)<1?n/2*e*e*e*e*e+t:n/2*((e-=2)*e*e*e*e+2)+t}function j_(e,t,n,i){return-n*Math.cos(e/i*(Math.PI/2))+n+t}function Q_(e,t,n,i){return n*Math.sin(e/i*(Math.PI/2))+t}function q_(e,t,n,i){return-n/2*(Math.cos(Math.PI*e/i)-1)+t}function K_(e,t,n,i){return e==0?t:n*Math.pow(2,10*(e/i-1))+t}function J_(e,t,n,i){return e==i?t+n:n*(-Math.pow(2,-10*e/i)+1)+t}function $_(e,t,n,i){return e==0?t:e==i?t+n:(e/=i/2)<1?n/2*Math.pow(2,10*(e-1))+t:n/2*(-Math.pow(2,-10*--e)+2)+t}function eC(e,t,n,i){return-n*(Math.sqrt(1-(e/=i)*e)-1)+t}function tC(e,t,n,i){return n*Math.sqrt(1-(e=e/i-1)*e)+t}function nC(e,t,n,i){return(e/=i/2)<1?-n/2*(Math.sqrt(1-e*e)-1)+t:n/2*(Math.sqrt(1-(e-=2)*e)+1)+t}function iC(e,t,n,i){var o=1.70158,r=0,s=n;if(e==0)return t;if((e/=i)==1)return t+n;if(r||(r=i*.3),s<Math.abs(n)){s=n;var o=r/4}else var o=r/(2*Math.PI)*Math.asin(n/s);return-(s*Math.pow(2,10*(e-=1))*Math.sin((e*i-o)*(2*Math.PI)/r))+t}function rC(e,t,n,i){var o=1.70158,r=0,s=n;if(e==0)return t;if((e/=i)==1)return t+n;if(r||(r=i*.3),s<Math.abs(n)){s=n;var o=r/4}else var o=r/(2*Math.PI)*Math.asin(n/s);return s*Math.pow(2,-10*e)*Math.sin((e*i-o)*(2*Math.PI)/r)+n+t}function sC(e,t,n,i){var o=1.70158,r=0,s=n;if(e==0)return t;if((e/=i/2)==2)return t+n;if(r||(r=i*(.3*1.5)),s<Math.abs(n)){s=n;var o=r/4}else var o=r/(2*Math.PI)*Math.asin(n/s);return e<1?-.5*(s*Math.pow(2,10*(e-=1))*Math.sin((e*i-o)*(2*Math.PI)/r))+t:s*Math.pow(2,-10*(e-=1))*Math.sin((e*i-o)*(2*Math.PI)/r)*.5+n+t}function oC(e,t,n,i,r){return r==null&&(r=1.70158),n*(e/=i)*e*((r+1)*e-r)+t}function aC(e,t,n,i,r){return r==null&&(r=1.70158),n*((e=e/i-1)*e*((r+1)*e+r)+1)+t}function lC(e,t,n,i,r){return r==null&&(r=1.70158),(e/=i/2)<1?n/2*(e*e*(((r*=1.525)+1)*e-r))+t:n/2*((e-=2)*e*(((r*=1.525)+1)*e+r)+2)+t}function cC(e,t,n,i){return(e/=i)<1/2.75?n*(7.5625*e*e)+t:e<2/2.75?n*(7.5625*(e-=1.5/2.75)*e+.75)+t:e<2.5/2.75?n*(7.5625*(e-=2.25/2.75)*e+.9375)+t:n*(7.5625*(e-=2.625/2.75)*e+.984375)+t}function fC(e,t,n,i){return n*(1-Math.pow(1-e/i,kc.nonLinearity+1))+t}const uC=Object.freeze(Object.defineProperty({__proto__:null,ease:pv,easeInBack:oC,easeInCirc:eC,easeInCubic:G_,easeInElastic:iC,easeInExpo:K_,easeInOutBack:lC,easeInOutCirc:nC,easeInOutCubic:U_,easeInOutElastic:sC,easeInOutExpo:$_,easeInOutQuad:N_,easeInOutQuart:H_,easeInOutQuint:Z_,easeInOutSine:q_,easeInQuad:R_,easeInQuart:V_,easeInQuint:Y_,easeInSine:j_,easeOutBack:aC,easeOutBounce:cC,easeOutCirc:tC,easeOutCubic:k_,easeOutElastic:rC,easeOutExpo:J_,easeOutQuad:z_,easeOutQuart:W_,easeOutQuint:X_,easeOutSine:Q_,inertia:fC,linear:hv},Symbol.toStringTag,{value:"Module"})),cd=new WeakMap;function dC(e,t,n){if(e===void 0){cd.delete(t);return}if(!Number.isFinite(e)||e<0)throw new RangeError("Fixed elapsed time must be a finite non-negative number");cd.set(t,{elapsedTime:e,nameIncludes:n})}const hC={easing:"easeInOutQuad",forceFinalValue:!0,renderAfterUpdate:!0};function pC(e,t){return t.tickers[e]}function gv(e,t,n,i,r,s,o,a){let l;t.animationGroup&&(l=Object.keys(n.tickers).filter(c=>n.tickers[c].animationGroup===t.animationGroup)),n.tickers[e]=ie(V(V({},hC),t),{from:i,to:r,duration:s,attributes:a,startTime:n.time,alreadyStartedGroupTickers:l,iterationCount:o})}function fd(e,t){delete t.tickers[e]}function mv(e,t){return!!t.tickers[e]}function gC(e,t){const n=t.tickers[e];if(!n)return 0;const i=cd.get(t);return i&&(i.nameIncludes===void 0||e.includes(i.nameIncludes))?i.elapsedTime:t.time-n.startTime}function vv(e,t,n){var l;const i=n.tickers[e];if(!i)return;if(i.alreadyStartedGroupTickers&&i.alreadyStartedGroupTickers.some(c=>!!n.tickers[c])){i.startTime=n.time;return}let r=gC(e,n);if(i.iterationCount>1){const c=r;r=c%i.duration,i.iterationCount!==1/0&&c>=i.duration*i.iterationCount&&(r=i.duration)}let s;if(i.from.length){s=[];for(let c=0;c<i.from.length;c++){const f=yv(i.easing,i.from[c],i.to[c],i.duration,r);s.push(f)}}else s=yv(i.easing,i.from,i.to,i.duration,r);let o=!1;r>=i.duration&&(i.forceFinalValue&&(s=i.to),o=!0),t.step&&t.step(n,s,i.attributes,o),o&&(t.keepFinished||fd(e,n),t.complete&&t.complete(n)),(typeof i.renderAfterUpdate=="function"?i.renderAfterUpdate():i.renderAfterUpdate)&&((l=i.attributes)!=null&&l.layerId?n.rerenderEvents.push({type:"layerAnimationTicker",layerId:i.attributes.layerId,styleId:i.attributes.styleId}):n.rerenderEvents.push({type:"coreAnimationTicker"}))}function yv(e,t,n,i,r){return typeof e=="string"?uC[e](r,t,n-t,i):e(r,t,n-t,i)}var kl=(e=>(e[e.DerivedFromTile=0]="DerivedFromTile",e[e.Present=1]="Present",e[e.Absent=2]="Absent",e))(kl||{});function mC(e){return e?1:2}let vC=0;class xv{constructor(t,n){this.isDestroyed=!1,this.sundaBufferIds=[],this.sundaVertexBufferIdsBySceneObjectId=new Map,this.id=vC++,this.ids=n,this.tickerName=`tile-fade-${t}-${this.id}`,this.readiness=1,this.needSync=!1,this.ecefDataState=0,this.modelMatrices=new Map,this.coords=[0,0,0,0],this.bounds=new Map,this.mvpMatrices=new Map,this.demMatrices=new Map,this.flatMapTexMatrices=new Map,this.purpose=t,this.buffers=[],this.children=[],this.identifyChildren=[],this.depthTestChildren=[],this.shadowChildren=[],this.labelTestChildren=[],this.demChildren=[],this.demGroundChildren=[]}get destroyed(){return this.isDestroyed}get empty(){return this.children.length===0}updateMvpMatrix(t,n,i){this.modelMatrices.forEach((r,s)=>{var a,l,c;const o=(a=this.mvpMatrices.get(s))!=null?a:new Float32Array(16);if(Zr(o,t,r),this.mvpMatrices.set(s,o),n){const f=(l=this.demMatrices.get(s))!=null?l:new Float32Array(16);Zr(f,n,r),this.demMatrices.set(s,f)}if(i){const f=(c=this.flatMapTexMatrices.get(s))!=null?c:new Float32Array(16);Zr(f,i,r),this.flatMapTexMatrices.set(s,f)}})}setMvpMatrix(t){this.modelMatrices.forEach((n,i)=>{this.mvpMatrices.set(i,new Float32Array(t))})}registerSundaBuffer(t,n){var i;this.sundaBufferIds.push(t),(i=this.sundaDeleteBuffers)!=null||(this.sundaDeleteBuffers=n)}registerSundaVertexBufferId(t,n){this.sundaVertexBufferIdsBySceneObjectId.set(t,n)}getSundaVertexBufferId(t){return this.sundaVertexBufferIdsBySceneObjectId.get(t)}getSundaTileKey(){var t;return`${(t=this.sourceId)!=null?t:-1}:${De(this.coords)}`}clearSundaRegistrations(){this.sundaBufferIds=[],this.sundaVertexBufferIdsBySceneObjectId.clear(),this.sundaInstanceBufferId=void 0,this.sundaDeleteBuffers=void 0;for(const t of[...this.children,...this.identifyChildren,...this.shadowChildren])t.sundaGltf=void 0,t.sundaInstance=void 0}clean(t){var n;this.sundaBufferIds.length>0&&((n=this.sundaDeleteBuffers)==null||n.call(this,this.sundaBufferIds),this.sundaBufferIds=[],this.sundaVertexBufferIdsBySceneObjectId.clear(),this.sundaInstanceBufferId=void 0);for(const i of this.buffers)i.remove();this.buffers=[],this.children=[],this.labelTestChildren=[],this.identifyChildren=[],this.depthTestChildren=[],this.shadowChildren=[],this.demChildren=[],this.demGroundChildren=[],fd(this.tickerName,t),this.isDestroyed=!0}updateTicker(t){vv(this.tickerName,{step:(n,i)=>{this.readiness=i}},t)}startTicker(t,n,i,r,s){gv(this.tickerName,{easing:n},t,r,s,i,1)}tickerFinished(t){return!mv(this.tickerName,t)}push(t){const n=t.layerSettings;n.identify?this.identifyChildren.push(t):n.depthTest?this.depthTestChildren.push(t):n.labelTest?t.sink==="raster"&&t.symbol==="point"&&this.labelTestChildren.push(t):n.dem?this.demChildren.push(t):n.demGround?this.demGroundChildren.push(t):n.shadow?this.shadowChildren.push(t):this.children.push(t)}pushBuffer(t){this.buffers.push(t)}}class Ul extends xv{constructor(t,n,i,r,s=[0,0,0,0],o,a,l){super(t,a),this.objectsMap={},this.floorObjectsMap={},this.dynamicObject=o,this.sourceId=l,ov(i,n,this,a),this.setTileCoords(s,r)}setTileCoords(t,n){const i=t[2],r=t[3],s=Mn(i);this.coords=t,this.size=s,this.zoomLevel=i,this.detailLevel=r,this.mvpMatrices.clear(),this.demMatrices.clear(),this.flatMapTexMatrices.clear(),this.syncReplicas(n)}syncReplicas(t){const n=[...t.visibleMapReplicas];if(this.dynamicObject&&this.dynamicObject.isOutOfMainReplica()){const s=n[0],o=n[n.length-1];n.push(s-1,o+1)}const i=W/ae*this.size,r=Math.pow(2,this.coords[2]);this.bounds.clear(),this.modelMatrices.clear(),n.forEach(s=>{const o=[this.coords[0]+s*r,this.coords[1],this.coords[2],this.coords[3]],a=ts(o);this.bounds.set(s,{min:[a[0],a[1]],max:[a[0]+this.size,a[1]+this.size]});const l=gp();sa(l,[a[0]-i,a[1]-i,0],bt(this.size/ot,this.size/ot,_i/ot)),this.modelMatrices.set(s,l)}),this.needSync=!1}updateObjVisibility(t,n,i){const r=i?this.floorObjectsMap[t]:this.objectsMap[t];if(!r)return!1;let s=!1;return r.forEach((o,a)=>{const l=a[0].getBuffer("a_float_visibility");if(!l)return;const c=l.getData();if(!(c instanceof Uint8Array))return;let f=!1;for(const{offset:u,size:d}of o)if(c[u]!==n){for(let h=u;h<u+d;++h)c[h]=n;f=!0}if(f){a[0].rewriteData("a_float_visibility");for(const u of a)u.isDirty=!0;s=!0}}),s}clean(t){for(const n in this.objectsMap)this.objectsMap[n].forEach((i,r)=>{r.forEach(s=>{s.unbind(),s.remove()})});for(const n in this.floorObjectsMap)this.floorObjectsMap[n].forEach((i,r)=>{r.forEach(s=>{s.unbind(),s.remove()})});super.clean(t)}}var yn=(e=>(e[e.Stationary=0]="Stationary",e[e.ZoomingIn=1]="ZoomingIn",e[e.ZoomingOut=2]="ZoomingOut",e))(yn||{}),en=(e=>(e[e.ByOne=0]="ByOne",e[e.WaitingLayer=1]="WaitingLayer",e[e.GlobalWaiting=2]="GlobalWaiting",e))(en||{});function yC(e,t,n){return{key:t,labelsKey:`${e.labelsKey}_${t}`,useful:!0,ready:!1,needGenerate:!1,tile:e,status:0,params:n.clone()}}function wv(e,t,n){e.generatedData=t,n&&e.params.setTileIds(n)}function Av(e){const t=e.generatedData,n=[];if(!t)return n;for(let i=0;i<t.length;i++){const r=t[i];r.collectorOutput.labels&&n.push({metatileHash:r.metatileHash,labels:r.collectorOutput.labels,styleId:r.styleId})}return n}function ud(e,t){e.status=0,e.generatedData=void 0,e.objects!==void 0&&e.objects.forEach(n=>n.clean(t)),e.objects=void 0,e.ready=!1,e.tile.currentMod===e&&(e.tile.currentMod=void 0)}function bv(e){return e.status===0}function Sv(e,t,n,i,r){switch(e.status){case 0:e.useful&&(e.status=1);break;case 1:e.useful?e.tile.serverMetadata&&(e.status=2):e.status=0;break;case 2:xC(e,n,i)&&(e.status=3,e.needGenerate=!0);break;case 3:e.generatedData&&(e.status=4,e.ready=!0,e.objects=e.generatedData.map(s=>{const{collectorOutput:{data:o}}=s;return new Ul(e.tile.type,o,i,n,e.tile.coords,void 0,r,e.tile.sourceId)}),t.add(e.key,e));break}}function xC(e,t,n){switch(e.tile.type){case"zenith":return!!(e.useful&&e.tile.serverMetadata&&wC(e.tile.serverMetadata,t,n));case"traffic":return!!(e.useful&&e.tile.serverMetadata);case"raster":case"geojson":case"dem":return!!e.useful;default:return!1}}function wC(e,t,n){const{assetManager:i,modelLayer:r}=n;for(let s=0;s<e.length;s++){const{regionId:o,metatileHash:a}=e[s];if(!i.getMetatile(a)||t.styleZoom>zc&&!r.isModelsInfoLoaded(o))return!1}return!0}class No{constructor(t,n,i,r,s,o){this.selectedIds=t.slice(),this.styleState=V({},n),this.tileRevision=i,this.styleRevision=s,this.styleId=r,this.globeMode=o}static equal(t,n){return t.globeMode===n.globeMode&&t.tileRevision===n.tileRevision&&t.styleId===n.styleId&&t.styleRevision===n.styleRevision&&Hr(t.getSelectedIds(),n.getSelectedIds())&&Hr(t.styleState,n.styleState)}clone(){return new No(this.selectedIds,this.styleState,this.tileRevision,this.styleId,this.styleRevision,this.globeMode)}stringify(){const t=this.selectedIds.join("|");return`sId=${this.styleId}_sRev=${this.styleRevision}_tRev=${this.tileRevision}_sel=${t}_sSt=${JSON.stringify(this.styleState)}_globe=${this.globeMode}`}getSelectedIds(){return this.tileIds?this.selectedIds.filter(t=>{var n;return(n=this.tileIds)==null?void 0:n.has(t)}):this.selectedIds.slice()}setTileIds(t){this.tileIds=t}}var dd=(e=>(e[e.Initial=0]="Initial",e[e.Loading=1]="Loading",e[e.Loaded=2]="Loaded",e))(dd||{});function AC(e,t,n,i){return{type:e,sourceId:n,key:De(t),labelsKey:`${e}_${n}_${i}`,coords:t,zoomLevel:t[2],detailLevel:t[3],needFetch:!1,revision:0,needAbortFetch:!1,needGenerate:!1,status:0,oldHoverTileObjects:[]}}function Ev(e,t,n,i,r,s){const o=[];if(n.oldHoverTileObjects.forEach(a=>{a.tickerFinished(t)?(e.tileManager.removeObject(a),a.clean(t)):o.push(a)}),n.oldHoverTileObjects=o,r===void 0){hd(e,n,t);return}t.performanceCaveatEmitted||(s||!n.hover||n.hover.id===r)&&SC(e,t,n,r,i)}function bC(e,t){const n=Math.min(Math.floor(e.styleZoom),ur.maxDetailLevel),i=t.coords[3];return n===i}function SC(e,t,n,i,r){if(!n.idSet||!n.idSet.has(i)||!bC(t,n)){hd(e,n,t);return}const s=e.identifier.getIdScope(Qu);s.isHidden(i,Ps.PolygonExtrusion)||EC(e,n,i,r).then(o=>{hd(e,n,t);const a={id:i,tileObjects:[],generatedData:[]},l=[];o.results.forEach(c=>{const f=new Ul("hover",c.collectorOutput.data,e,t,n.coords,void 0,s),{packedRasters:u,rastersToLoad:d}=c.collectorOutput;u!==void 0&&e.assetManager.prepareRasters(c.styleId,u),e.assetManager.loadRasters(d),a.tileObjects.push(f),e.tileManager.addObject(f),f.startTicker(t,Ys.inAnimationType,Ys.inAnimationTime,0,1),c.collectorOutput.labels.length&&l.push({metatileHash:c.metatileHash,labels:c.collectorOutput.labels,styleId:c.styleId})}),a.generatedData=o.results,e.labeler.addLabels("label_hover",_o.Tile,l),e.identifier.queryFillCache(),n.hover=a})}function hd(e,t,n){t.hover&&(t.hover.tileObjects.forEach(i=>{t.oldHoverTileObjects.push(i),i.startTicker(n,Ys.outAnimationType,Ys.outAnimationTime,1,0)}),t.hover=void 0,e.labeler.removeLabels("label_hover"),e.identifier.queryFillCache())}function EC(e,t,n,i){const r=t.newMod||t.currentMod,s=(r==null?void 0:r.params.getSelectedIds())||[],o=e.map.state;return e.defaultSource.generateHoverTile(o,t.coords,o.handyStyleId,s,self.devicePixelRatio,{},n,i)}function Tv(e){if(e.newMod&&e.newMod.needGenerate)return e.newMod.needGenerate=!1,e.newMod}function TC(e){return(!e.currentMod||bv(e.currentMod))&&(!e.newMod||bv(e.newMod))}function PC(e,t){e.currentMod&&ud(e.currentMod,t),e.newMod&&ud(e.newMod,t)}function IC(e){e.currentMod=void 0}function Vl(e){if(e.currentMod&&e.currentMod.useful)return e.currentMod;if(e.newMod&&e.newMod.useful)return e.newMod}function MC(e){e.currentMod&&(e.currentMod.useful=!1),e.newMod&&(e.newMod.useful=!1)}function _C(e,t,n){if(e.idSet&&t.setTileIds(e.idSet),!e.currentMod&&!e.newMod){pd(e,t,n);return}if(e.currentMod&&No.equal(e.currentMod.params,t)){e.currentMod.useful=!0,e.newMod=void 0;return}if(e.newMod){No.equal(e.newMod.params,t)?e.newMod.useful=!0:pd(e,t,n);return}pd(e,t,n)}function pd(e,t,n){const i=wb(e.coords,t),r=n.get(i);r?(e.newMod=r,e.newMod.useful=!0):(e.newMod=yC(e,i,t),e.idSet&&e.newMod.params.setTileIds(e.idSet))}function CC(e,t,n,i,r){switch(e.status){case 0:e.newMod&&e.newMod.useful&&(e.status=1,e.needFetch=!0);break;case 1:e.newMod&&e.newMod.useful?e.serverMetadata&&(e.status=2):(e.status=0,e.needAbortFetch=!0);break}e.currentMod&&Sv(e.currentMod,t,n,i,r),e.newMod&&(Sv(e.newMod,t,n,i,r),e.newMod.needGenerate&&(e.needGenerate=!0))}function FC(e){e.newMod&&e.newMod.ready&&(e.currentMod=e.newMod,e.newMod=void 0)}function LC(e){const t=new Set;return e.forEach(n=>{const{idBuffer:i,orphanIds:r}=n.collectorOutput.identifyIds;for(const s of i)t.add(s);for(const s of r)t.add(s)}),t}function BC(e){e.status===1&&(e.needAbortFetch=!0),e.status=0,e.serverMetadata=void 0,e.revision++}function DC(e){e.revision++}const OC=()=>{};class Pv{constructor(t,n=OC){this.size=t,this.onRemove=n,this.map=new Map,this._length=0}add(t,n){if(this.map.has(t))return;const i={key:t,value:n};this.map.set(t,i),this._addToFront(i),this._length++,this._length>this.size&&this._removeLRU()}remove(t){const n=this.map.get(t);n&&(this._removeNode(n),this.map.delete(t),this._length--)}get(t){const n=this.map.get(t);if(n)return this._moveToFront(n),n.value}reset(){for(const[t,n]of this.map)this.onRemove(t,n.value);this.map.clear(),this.head=void 0,this.tail=void 0,this._length=0}setSize(t){for(this.size=t;this._length>this.size;)this._removeLRU()}getSize(){return this.size}keys(){return Array.from(this.map.keys())}getData(){return Array.from(this.map.values()).map(t=>t.value)}_addToFront(t){t.next=this.head,t.prev=void 0,this.head&&(this.head.prev=t),this.head=t,this.tail||(this.tail=t)}_removeNode(t){t.prev?t.prev.next=t.next:this.head=t.next,t.next?t.next.prev=t.prev:this.tail=t.prev,t.next=void 0,t.prev=void 0}_moveToFront(t){this._removeNode(t),this._addToFront(t)}_removeLRU(){if(!this.tail)return;const t=this.tail.key,n=this.tail.value;this._removeNode(this.tail),this.map.delete(t),this._length--,this.onRemove(t,n)}}function Is(e,t){const n=e.viewportTiles;for(const s in e.tiles)MC(e.tiles[s]);const i=t.styleManager.getStyle(e.styleId),r=RC(i,e.styleState);for(const s of n){let o=e.tiles[s];o||(o=e.tiles[s]=AC(e.type,Ef(s),e.sourceId,e.tileLayerId));const a=new No(e.selectedIds,r,o.revision,e.styleId,e.styleRevision,e.globeMode);_C(o,a,e.tileModsCache)}}function RC(e,t){if(!e)return t;const n={};for(const i in t){const r=e.globals[i];r&&!r.has(Qe.Generator)||(n[i]=t[i])}return n}function gd(e,t){for(const n of t){const i=e[n],r=Vl(i);if(!r||!r.ready)return!1}return!0}function Iv(e){const t=[];for(const n in e.tiles){const i=e.tiles[n];i.needFetch&&(i.needFetch=!1,t.push(i))}return t}function Mv(e){const t=[];for(const n in e.tiles){const i=e.tiles[n];i.needAbortFetch&&(i.needAbortFetch=!1,t.push(i))}return t}function _v(e){const t=[];for(const n in e.tiles){const i=e.tiles[n];i.needGenerate&&(i.needGenerate=!1,t.push(i))}return t}function Cv(e){const t=e.viewportTiles,n=new Set(e.tileModsCache.getData().map(r=>r.tile)),i=[];for(const r in e.tiles){const s=e.tiles[r];TC(s)&&!t.has(r)&&e.zoomDirection===yn.Stationary&&!n.has(s)&&i.push(s)}return i}function Fv(e,t,n,i,r,s,o,a,l,c,f=0,u=!1,d=!1){return{type:e,sourceId:t,tileLayerId:n,styleId:l.handyStyleId,styleRevision:a.styleManager.getStyleRevision(l.handyStyleId),styleState:l.styleState,minZoomLevel:i,maxZoomLevel:r,minDetailLevel:s,maxDetailLevel:o,tiles:{},viewportTiles:new Set,zoomLevel:Lv(e,l.zoom,l.styleZoom),zoomDirection:yn.Stationary,zoomStartZoom:0,tileModsCache:new Pv(0,(h,g)=>{var y;a.labeler.removeLabels(g.labelsKey),(y=g.objects)==null||y.forEach(p=>a.tileManager.removeObject(p)),ud(g,l)}),tileModsCacheMaxCount:0,selectedIds:[],displayedMods:{},tilesAppearance:en.ByOne,mapState:l,stopLabelAnimation:!1,viewportPadding:f,displayStats:{matched:0,shifted:0,parent:0,children:0},requestOddTiles:u,ids:c,useExtendedTilesBounds:d,globeMode:l.globeMode}}function Lv(e,t,n){return e==="raster"?Math.round(t):Math.floor(n)}function md(e){for(const t in e.tiles)PC(e.tiles[t],e.mapState);e.tiles={},e.viewportTiles=new Set,e.zoomDirection=yn.Stationary,e.tileModsCache.reset(),e.displayedMods={},e.tilesAppearance=en.ByOne}function Bv(e,t,n,i,r=!1){const{tileManager:s,renderer:o}=e,a=n.displayedMods,l=dp(a,i);l.forEach(u=>{if(u.objects!==void 0){let d=!r;for(const h in i)if(Ob(u.tile,i[h].tile)){d=!1;break}u.objects.forEach(h=>{s.addObject(h),d&&h.startTicker(t,Nc.type,Nc.time,0,1)})}});const c=dp(i,a);c.forEach(u=>{var d;u.objects!==void 0&&(u.objects.forEach(h=>{s.removeObject(h)}),(d=u.tile.hover)==null||d.tileObjects.forEach(h=>s.removeObject(h)))});const f=l.length>0||c.length>0;return f&&(t.needLabeling=!0,o.addRerenderEvent(),e.identifier.queryFillCache()),f}function vd(e){e.viewportTiles.forEach(t=>FC(e.tiles[t]))}function zC(e){switch(e){case"geojson":return 3;case"raster":return 1/0;case"dem":return 1}return 2}function yd(e,t,n){NC(e,t.styleZoom,t.zoom),GC(e,t,n),kC(e),Is(e,n)}function NC(e,t,n){const i=Lv(e.type,n,t),r=i-e.zoomLevel;e.zoomDirection===yn.Stationary&&(r>0?(e.zoomDirection=yn.ZoomingIn,e.zoomStartZoom=e.zoomLevel):r<0&&(e.zoomDirection=yn.ZoomingOut,e.zoomStartZoom=e.zoomLevel)),e.zoomLevel=i}function GC(e,t,n){if(e.zoomLevel<e.minZoomLevel){e.viewportTiles=new Set;return}const i=Ge(e.zoomLevel,e.minZoomLevel,e.maxZoomLevel),r=Ge(e.zoomLevel,e.minDetailLevel,e.maxDetailLevel);let s;switch(e.type){default:s=Qp(t,n,i,e.minZoomLevel,r,e.viewportPadding,e.maxZoomLevel,e.requestOddTiles,e.useExtendedTilesBounds).map(De),t.stats.foundVisibleTilesCount=e.viewportTiles.size}e.viewportTiles=new Set(s)}function kC(e){const t=Math.round((Object.keys(e.displayedMods).length+e.viewportTiles.size)*ur.cacheRatio);e.tileModsCacheMaxCount<t&&(e.tileModsCacheMaxCount=t),t>e.tileModsCacheMaxCount/2&&e.tileModsCache.setSize(t)}function UC(e,t){const n={};for(const i in e){const r=e[i];let s=Math.floor(r.coords[0]/2),o=Math.floor(r.coords[1]/2);for(let a=r.coords[2]-1;a>=t;a--){const l=Hl(s,o,a),c=n[l];c?c.push(r):n[l]=[r],s=Math.floor(s/2),o=Math.floor(o/2)}}return n}function VC(e,t,n){const i=YC(e),r=Object.keys(i).reduce((u,d)=>{const h=i[d],g=Hl(h.coords[0],h.coords[1],h.coords[2]);return u[g]=h,u},{}),s=Math.min(...Object.values(i).map(u=>u.coords[2])),o=Math.min(...Array.from(t).map(u=>e[u].coords[2])),a=UC(i,o),l={},c=new Set;for(const u of t){const d=i[u];if(d){Wl(l,d),n.matched++;continue}const h=e[u],g=WC(h,i,3);if(g){n.shifted++,Wl(l,g);continue}const y=Hl(h.coords[0],h.coords[1],h.coords[2]),p=Dv(h,s,r);if(p){n.parent++,Wl(l,p),c.add(p);continue}const v=a[y];if(v)for(const A of v)n.children++,Wl(l,A)}function f(u){const d=Dv(u,s,r);d&&c.has(d)&&(delete l[u.currentMod.key],f(d))}for(const u in l)f(l[u].tile);return l}function WC(e,t,n){const{coords:i}=e,r=Math.min(i[3]+n,32),s=Math.max(i[3]-n,0);for(let o=s;o<=r;o+=1){if(o===i[3])continue;const a=Yp(i[0],i[1],i[2],o),l=t[a];if(l)return l}}function HC(e){const t=e.currentMod;return t===void 0?!1:t.ready}function Wl(e,t){const n=t.currentMod;e[n.key]=n}function YC(e){const t={};for(const n in e){const i=e[n];HC(i)&&(t[n]=i)}return t}function Dv(e,t,n){let[i,r,s]=e.coords;for(;s-->=t;){i=Math.floor(i/2),r=Math.floor(r/2);const o=Hl(i,r,s);if(n[o])return n[o]}}function Hl(e,t,n){return`${e}_${t}_${n}`}function Ov(e,t,n){XC(e,t,n),ZC(e),jC(e);for(const i in e.displayedMods)e.tileModsCache.get(i);QC(e),qC(e)}function XC(e,t,n){for(const i in e.tiles)CC(e.tiles[i],e.tileModsCache,t,n,e.ids)}function ZC(e){switch(e.tilesAppearance){case en.ByOne:vd(e);break;case en.WaitingLayer:gd(e.tiles,e.viewportTiles)&&(e.tilesAppearance=en.ByOne,vd(e));break;case en.GlobalWaiting:break}}function jC(e){const{tiles:t,viewportTiles:n,displayStats:i}=e;e.displayedMods=VC(t,n,i)}function QC({tiles:e,displayedMods:t,viewportTiles:n}){for(const i in e){if(n.has(i))continue;const r=e[i],s=r.currentMod;s&&!t[s.key]&&IC(r)}}function qC(e){switch(e.zoomDirection){case yn.ZoomingIn:(e.zoomLevel<=e.zoomStartZoom||Rv(e))&&(e.zoomDirection=yn.Stationary,e.zoomStartZoom=e.zoomLevel);break;case yn.ZoomingOut:(e.zoomLevel>=e.zoomStartZoom||Rv(e))&&(e.zoomDirection=yn.Stationary,e.zoomStartZoom=e.zoomLevel);break}}function Rv(e){const{tiles:t,viewportTiles:n,displayedMods:i}=e;for(const r of n){const s=t[r],o=Vl(s);if(!o||i[o.key]===void 0)return!1}return!0}function KC(e,t,n,i){var r;n.selectedIds=i,n.tilesAppearance=en.WaitingLayer,Is(n,e);for(const s in n.tiles){const o=n.tiles[s];Ev(e,t,o,n.sourceId,(r=o.hover)==null?void 0:r.id,!0)}}function zv(e,t,n,i){if(!t.disableHoverStyles){for(const r in n.tiles){const s=n.tiles[r];Ev(e,t,s,n.sourceId,i)}e.labeler.disableThrottleUpdateOnce()}}function JC(e,t,n){t.styleState=n,Is(t,e)}function Nv(e,t,n,i,r){r?t.tilesAppearance=en.ByOne:t.tilesAppearance=en.GlobalWaiting,t.styleId=n,t.styleRevision=i,Is(t,e)}function Gv(e){e.tilesAppearance=en.ByOne,vd(e)}function $C(e,t){e.tilesAppearance=en.WaitingLayer,e.stopLabelAnimation=!0,Object.keys(e.tiles).forEach(n=>{BC(e.tiles[n])}),Is(e,t)}function e3(e,t){e.tilesAppearance=en.WaitingLayer,Object.keys(e.tiles).forEach(n=>{DC(e.tiles[n])}),Is(e,t)}function t3(e,t){for(const n of e.viewportTiles){const i=e.tiles[n],r=Vl(i);if(!r)continue;const s=Av(r);if(s.length===0)continue;let o=!1;const a=t.demManager.getLabelsDemKey(s);r.demKey!==a&&(r.demKey=a,o=!0);const l=t.modelsScene.getTieredModelsKey(Aa(i.coords));r.tierKey!==l&&(r.tierKey=l,o=!0),o&&t.labeler.addTileLabels(r.labelsKey,_o.Tile,s)}}function xd(e){return{_src:e.memSizeJs()}}function n3(e){return{_texture:e.memSizeGPU()}}function kv(e){return{[String(e.purpose)]:{_initData:e.memSizeJs()}}}function i3(e){return{[String(e.purpose)]:{_glBuffer:e.memSizeGPU()}}}function wd(e){var n;const t={};return e.generatedData&&(t.generatedData={collectorOutput:(n=e.generatedData)==null?void 0:n.map(i=>o3(i.collectorOutput))}),e.objects&&(t.objects=e.objects.map(i=>Uv(i))),t}function Ad(e){return{objects:e.objects?e.objects.map(t=>Vv(t)):0}}function Uv(e){return{buffers:e.buffers.map(kv)}}function Vv(e){return{children:e.children.map(t=>{var n;return{[`${t.symbol}_${t.sink}`]:((n=t.instanceCount)!=null?n:t.count)*Oo(t.symbol,t.sink)}}),buffers:e.buffers.filter(t=>t.purpose!=="attributes"&&t.purpose!=="instanced").map(t=>({[String(t.purpose)]:t.byteLength}))}}function r3(e){return{buffers:e.buffers.filter(t=>t instanceof ht).map(kv).filter(t=>t._initData),textures:e.textures.map(xd)}}function s3(e){return{buffers:e.buffers.filter(t=>t instanceof ht).map(i3),textures:e.textures.map(xd)}}function bd(e){if(typeof e=="number")return e;let t=0;if(Array.isArray(e))for(const n of e)t+=bd(n);else for(const n in e){const i=e[n];typeof i=="number"?t+=i:t+=bd(i)}return t}function o3(e){return{data:e.data.reduce((n,i)=>(n[`${i.symbol}_${i.sink}`]=i.buffer.byteLength,n),{}),identifyIds:{centerBuffer:e.identifyIds.centerBuffer.byteLength,instanceIdBuffer:e.identifyIds.instanceIdBuffer.byteLength,layerIdBuffer:e.identifyIds.layerIdBuffer.byteLength,objectClassBuffer:e.identifyIds.objectClassBuffer.byteLength,phaseBuffer:e.identifyIds.phaseBuffer.byteLength,styleIdBuffer:e.identifyIds.styleIdBuffer.byteLength,sublayerBuffer:e.identifyIds.sublayerBuffer.byteLength}}}function a3(e){return Fe(this,null,function*(){return{defaultSource:e.defaultSource.getMemoryFootprint(),tileManager:e.tileManager.getMemoryFootprint(t=>!e.defaultSource.hasLayer(t)),identifier:e.identifier.getMemoryFootprint(),assetManager:e.assetManager.getMemoryFootprint(),trafficTileLayer:e.trafficTileLayer.getMemoryFootprint(),imageManager:e.imageManager.getMemoryFootprint(),parserThread:yield e.workers.parser.getMemoryFootprint(),labelingThread:yield e.workers.labeling.getMemoryFootprint(),renderer:e.renderer.getMemoryFootprint(),labeler:e.labeler.getMemoryFootprint(),postEffectsManager:e.postEffectsManager.getMemoryFootprint(),shadowManager:e.shadowManager.getMemoryFootprint()}})}class Wv{constructor(t,n,i,r,s,o,a,l={}){var c;this.disabledRegions=null,this.generatingCount=0,this.tilesGenerationQueue=[],this.disableTilesAnimation=!1,this.idsToUpdate=new Set,this.registeredTierKeys=new Map,this.destroyed=!1,l=Object.assign({viewportPadding:0,disableTilesAnimation:!1,requestOddTiles:!1},l),this.ids=s.identifier.getIdScope((c=l.idScope)!=null?c:Qu),this.ids.registerTileLayer(this),this.modules=s,this.mapState=o,this.prevStyleState=o.styleState,this.sourceCore=a,this.id=ga(),this.disableTilesAnimation=!!l.disableTilesAnimation,this.gridState=Fv(a.type,a.id,this.id,t,n,i,r,s,this.mapState,this.ids,l.viewportPadding,l.requestOddTiles,l.useExtendedTilesBounds),this.maxGeneratingCount=zC(a.type)}memSizeJs(){const t=this.gridState;return{gridState:{displayedMods:Object.keys(t.displayedMods).map(n=>wd(t.displayedMods[n])),tileModsCache:t.tileModsCache.keys().filter(n=>!t.displayedMods[n]).map(n=>wd(t.tileModsCache.get(n)))}}}memSizeGpu(){const t=this.gridState;return{gridState:{displayedMods:Object.keys(t.displayedMods).map(n=>Ad(t.displayedMods[n])),tileModsCache:t.tileModsCache.keys().filter(n=>!t.displayedMods[n]).map(n=>Ad(t.tileModsCache.get(n)))}}}destroy(){this.destroyed=!0,this.unregisterAllTierTrees(),md(this.gridState),this.modules.modelsScene.clearSourceTileMapBySource(this.sourceCore.id),this.ids.unregisterTileLayer(this)}redraw(){this.unregisterAllTierTrees(),md(this.gridState),this.modules.modelsScene.clearSourceTileMapBySource(this.sourceCore.id),yd(this.gridState,this.mapState,this.modules)}getZoomDirection(){return this.gridState.zoomDirection}getDisplayedTileObjects(){const t=[];for(const n in this.gridState.displayedMods){const i=this.gridState.displayedMods[n];i.objects&&t.push(...i.objects)}return t}getDisplayedIdentifyData(){var n,i;const t=[];for(const r in this.gridState.displayedMods){const s=this.gridState.displayedMods[r];(i=s.generatedData)==null||i.concat(((n=s.tile.hover)==null?void 0:n.generatedData)||[]).forEach(o=>t.push({ids:o.collectorOutput.identifyIds,metatileHash:o.metatileHash,sourceId:s.tile.sourceId,tileKey:s.tile.key}))}return t}getLabelingData(){const t={sourceId:this.gridState.sourceId,animate:!this.gridState.stopLabelAnimation,labelsKeys:[]};for(const n in this.gridState.displayedMods){const i=this.gridState.displayedMods[n];t.labelsKeys.push(i.labelsKey)}return this.gridState.stopLabelAnimation&&this.viewportTilesReady()&&(this.gridState.stopLabelAnimation=!1),t}getViewportTiles(){const t=[],n=this.gridState.viewportTiles;for(const i of n){const r=this.gridState.tiles[i];r&&t.push(r)}return t}getViewportTileCount(){return this.gridState.viewportTiles.size}getDisplayedTileCount(){return Object.keys(this.gridState.displayedMods).length}viewportTilesReady(){return gd(this.gridState.tiles,this.gridState.viewportTiles)}isEmpty(){return this.gridState.viewportTiles.size===0}displayedTilesAnimationFinished(){for(const t in this.gridState.displayedMods){const n=this.gridState.displayedMods[t];if(n.objects){for(const i of n.objects)if(!i.tickerFinished(this.mapState))return!1}}return!0}activateStyleUpdating(){Nv(this.modules,this.gridState,this.mapState.handyStyleId,this.modules.styleManager.getStyleRevision(this.mapState.handyStyleId),this.modules.map.core.getIsFirstStyleUpdate())}finishStyleUpdating(){Gv(this.gridState)}setSelectedIds(t){KC(this.modules,this.mapState,this.gridState,t)}setHoverId(t){zv(this.modules,this.mapState,this.gridState,t)}resetHoverId(){zv(this.modules,this.mapState,this.gridState)}onSourceDataChange(){$C(this.gridState,this.modules)}onFeatureStateMapChange(){e3(this.gridState,this.modules)}getTileCount(){let t=0;for(const n in this.gridState.displayedMods){const i=this.gridState.displayedMods[n].objects;i!==void 0&&(t+=i.length)}return t}isBlank(){for(const t of this.gridState.viewportTiles){const n=this.gridState.tiles[t],{serverMetadata:i}=n;if(i===void 0||i.length===0)continue;const r=Vl(n);if(r&&r.ready)return!1}return!0}updateViewport(){yd(this.gridState,this.mapState,this.modules)}update(){this.mapState.needReplicasUpdate&&this.setModObjectsSyncNecessity();const t=V({},this.gridState.displayedMods);this.mapState.styleState!==this.prevStyleState&&(JC(this.modules,this.gridState,this.mapState.styleState),this.prevStyleState=this.mapState.styleState,this.modules.identifier.queryFillCache()),this.gridState.globeMode=this.mapState.globeMode,Ov(this.gridState,this.mapState,this.modules),t3(this.gridState,this.modules),this.fetch(Iv(this.gridState)),this.abortFetch(Mv(this.gridState)),this.generate(_v(this.gridState)),this.clearTiles(Cv(this.gridState)),Bv(this.modules,this.mapState,this.gridState,t,this.disableTilesAnimation),this.updateVisibility()}pushIdsToUpdate(t){t.forEach(n=>this.idsToUpdate.add(n))}getSourceType(){return this.sourceCore.type}getSource(){return this.sourceCore}fetch(t){if(t.length===0)return;const n=t.sort((r,s)=>Sa(this.mapState.center,r,s)).map(r=>r.coords);this.sourceCore.fetchTiles(n,this.mapState).forEach((r,s)=>{r.then(o=>{const a=t[s];a.status===dd.Loading&&(a.serverMetadata=o)},o=>{console.error(o)})})}abortFetch(t){t.length!==0&&this.sourceCore.abortTileFetches(t.map(n=>n.coords))}updateGenerationQueue(){if(this.destroyed||this.generatingCount>this.maxGeneratingCount)return;const t=this.getTileToGenerate();if(!t)return;++this.generatingCount;const{tile:n,mod:i}=t,r={tileCoords:n.coords,selectedIds:i.params.getSelectedIds(),styleId:i.params.styleId},s=this.disabledRegions,o={areTileBoundsVisible:this.mapState.showDefaultTileBounds};this.sourceCore.generateTile(this.mapState,r.tileCoords,r.styleId,r.selectedIds,devicePixelRatio,o).then(a=>{if(!a){Sg(this.sourceCore.type);return}if(!Array.isArray(a.results))return;let{results:l}=a;if(l.forEach(({styleId:f,collectorOutput:u})=>{const{packedRasters:d,rastersToLoad:h,dataModelsUrls:g}=u;d!==void 0&&this.modules.assetManager.prepareRasters(f,d),this.modules.assetManager.fillDataModelUrlMap(g),this.modules.assetManager.loadRasters(h)}),n.newMod!==i&&n.currentMod!==i)return;s&&(l=l.filter(f=>!s.includes(f.regionId)));const c=new Map;if(l.forEach(f=>{f.collectorOutput.data.forEach(u=>{u.symbol!=="gltfModel"||u.sink!=="instances"||u.generatedObjects.forEach(d=>{var v;const h=Ki.sinks.instances.unpackObjectAttributes(d.attributes),g=(v=d.meta)==null?void 0:v.childrenIds,y=h.parentId;if(!g||!y)return;let p=c.get(y);p||(p=new Set,c.set(y,p));for(const A of g)p.add(A)})})}),c.size){const f=De(r.tileCoords);this.ids.updateParentChildrenData(f,c)}l.forEach(({metatileHash:f,regionId:u,collectorOutput:d})=>{this.modules.floorManager.prepareFloors(u,f,d.floorHidingMap,this.sourceCore.type)}),n.idSet=LC(l),wv(i,l,n.idSet),this.registerTierTrees(n,r.tileCoords,l),this.modules.labeler.addTileLabels(i.labelsKey,_o.Tile,Av(i))}).catch(a=>{console.error(a)}).finally(()=>{this.generatingCount=this.generatingCount-1,this.updateGenerationQueue()})}getTileToGenerate(){this.tilesGenerationQueue.sort((n,i)=>Sa(this.mapState.center,n,i));let t=this.tilesGenerationQueue.shift();for(;t;){const n=Tv(t);if(n){if(n.useful)return{mod:n,tile:t};t.newMod=void 0}t=this.tilesGenerationQueue.shift()}return null}addTileToGenerationQueue(t){this.tilesGenerationQueue.push(t)}generate(t){let n=!1;t.sort((i,r)=>Sa(this.mapState.center,i,r)).forEach(i=>{var r;(r=i.newMod)!=null&&r.needGenerate&&!this.tilesGenerationQueue.includes(i)&&(this.addTileToGenerationQueue(i),n=!0)}),n&&this.updateGenerationQueue()}clearTiles(t){if(!t.length)return;const n=[];this.modules.modelsScene.clearSourceTileMapByTiles(this.sourceCore.id,t),this.sourceCore.deleteTiles(t.map(i=>i.coords));for(const i of t)this.unregisterTierTrees(i),n.push(i.key),delete this.gridState.tiles[i.key];this.ids.removeParentChildrenData(n)}registerTierTrees(t,n,i){if(this.unregisterTierTrees(t),!i.some(a=>{var l;return(l=a.collectorOutput.tierTrees)==null?void 0:l.length}))return;const s=Aa(n),o=[];i.forEach(a=>{var c;((c=a.collectorOutput.tierTrees)!=null?c:[]).forEach(({tier:f,tree:u})=>{const d=`${De(n)}:tier:${f}:${a.regionId}`,h={sourceId:this.sourceCore.id,key:d,tileCoords:n,kind:"tier",surfaceTier:f,tree:u,generated:[a],vertexStride:Xn.sinks.fill.stride,heightOffset:4,bucketSink:"fill",minX:s.min[0],minY:s.min[1],maxX:s.max[0],maxY:s.max[1]};this.modules.elevationIndex.register(h),o.push(d)})}),o.length&&this.registeredTierKeys.set(t.key,o)}unregisterTierTrees(t){const n=this.registeredTierKeys.get(t.key);if(n){for(const i of n)this.modules.elevationIndex.unregister(this.sourceCore.id,i);this.registeredTierKeys.delete(t.key)}}unregisterAllTierTrees(){for(const t of this.registeredTierKeys.values())for(const n of t)this.modules.elevationIndex.unregister(this.sourceCore.id,n);this.registeredTierKeys.clear()}updateVisibility(){if(this.idsToUpdate.size===0)return;const t=[];this.gridState.tileModsCache.getData().forEach(i=>{i.objects&&i.objects.forEach(r=>{t.push(r)})}),t.length!==0&&this.updateObjectsVisibility(t)}updateObjectsVisibility(t){let n=!1;for(const i of this.idsToUpdate){const r=+!this.ids.isHidden(i,Ps.PolygonExtrusion),s=+!this.ids.isHidden(i,Ps.FloorPolygons);for(const o of t)o.updateObjVisibility(i,r,!1)&&(n=!0),o.updateObjVisibility(i,s,!0)&&(n=!0)}this.idsToUpdate.clear(),n&&(this.modules.renderer.addRerenderEvent(),this.modules.identifier.queryFillCache(),this.mapState.needLabeling=!0)}setModObjectsSyncNecessity(){this.gridState.tileModsCache.getData().forEach(n=>{var i;(i=n.objects)==null||i.forEach(r=>{r.needSync=!0})})}}class Hv{constructor(t,n,i,r){var s;this.id=t,this.modules=n,this.options=i,this.type="geojson",this.idToIndex={},this.worker=new this.modules.workers.parser.GeoJsonSource(this.options,this.id,Array.from((s=r==null?void 0:r.modelShowHideEventsSublayers)!=null?s:new Set)),this.attributes=i.attributes||{},this.dataFilter=i.dataFilter}fetchTiles(t){return this.worker.fetchTiles(t).map(n=>n.catch(()=>Promise.resolve()).then(()=>[{regionId:0,metatileHash:-2}]))}generateTile(t,n,i,r,s){return Fe(this,null,function*(){const o=this.options.modelsPath,a=yield this.worker.generateTile(t.styleState,n,i,r,s,!t.isFloatTextureSupported||!t.isVertexTextureFetchSupported,o,this.dataFilter,t.modelShowHideEventsSublayers);return Array.isArray(a.results)?(a.results[0]&&a.results[0].idToIndex&&(this.idToIndex[De(n)]=a.results[0].idToIndex),a):{results:[],transferable:[]}})}getObjectAttributes(t,n){return Promise.resolve(this.worker.getObjectAttributes(t,n))}abortTileFetches(t){this.worker.abortTileFetches(t)}deleteTiles(t){for(const n of t)delete this.idToIndex[De(n)];this.worker.deleteTiles(t)}setAttributes(t){this.worker.setSourceAttrs(t),this.attributes=t}getAttributes(){return this.attributes}destroy(){this.idToIndex={},this.worker.destroy()}setFeatureStateMap(t){this.worker.setFeatureStateMap(t)}setData(t){return Fe(this,null,function*(){return this.idToIndex={},this.options=typeof t=="string"?this.options=ie(V({},this.options),{url:t}):this.options=ie(V({},this.options),{data:t}),yield this.worker.setData(t)})}getComponentIndex(t,n){var i;return n?(i=this.idToIndex[n])==null?void 0:i[t]:(console.warn("Нет tileKey при идентификации объекта из GeoJsonSource. Пытаемся получить index из id по-старому."),Number.isNaN(+t)?void 0:+t%$(2,32))}setDataFilter(t){if(t){const n={layer:{},usage:Qe.Generator,globals:{},precomputes:[]};this.dataFilter=_(t,n)}else this.dataFilter=void 0}}let l3=1;function Yv(){return l3++}class Xv{constructor(t){this.defs=t.map(n=>new c3(n))}check(t){const n=this.defs;let i=!1;for(let r=0;r<n.length;r++)i?n[r].update(t):i=!n[r].equal(t);return i}}class c3{constructor(t){this.path=Array.isArray(t.path)?t.path:[t.path],this.type=t.type,this.type==="number"?(this.last=NaN,this.compare=this.primitive,this.updateFn=this.primitiveUpdate):this.type==="boolean"?(this.last=void 0,this.compare=this.primitive,this.updateFn=this.primitiveUpdate):this.type==="vec2"?(this.last=[NaN,NaN],this.compare=this.vec2,this.updateFn=this.vec2Update):this.type==="vec3"?(this.last=[NaN,NaN,NaN],this.compare=this.vec3,this.updateFn=this.vec3Update):this.type==="string"?(this.last="",this.compare=this.primitive,this.updateFn=this.primitiveUpdate):this.type==="padding"?(this.last={left:0,right:0,bottom:0,top:0},this.compare=this.padding,this.updateFn=this.paddingUpdate):this.type==="replicas"&&(this.last={min:0,max:0},this.compare=this.replicas,this.updateFn=this.replicasUpdate)}equal(t){const n=this.take(t),i=this.compare(this.last,n);return this.updateFn(n),i}update(t){this.updateFn(this.take(t))}take(t){const n=this.path;let i=0;do t=t[n[i++]];while(i<n.length);return t}primitive(t,n){return t===n}padding(t,n){return t.top===n.top&&t.bottom===n.bottom&&t.left===n.left&&t.right===n.right}paddingUpdate(t){this.last.top=t.top,this.last.bottom=t.bottom,this.last.right=t.right,this.last.left=t.left}vec2(t,n){return t[0]===n[0]&&t[1]===n[1]}vec3(t,n){return t[0]===n[0]&&t[1]===n[1]&&t[2]===n[2]}primitiveUpdate(t){this.last=t}vec2Update(t){this.last[0]=t[0],this.last[1]=t[1]}vec3Update(t){this.last[0]=t[0],this.last[1]=t[1],this.last[2]=t[2]}replicas(t,n){const i=n[0],r=n[n.length-1];return t.min===i&&t.max===r}replicasUpdate(t){this.last.min=t[0],this.last.max=t[t.length-1]}}function Zv(e,t,n){let i,r,s,o;const a=function(){const f=Date.now()-s;f<t&&f>=0?i=setTimeout(a,t-f):(i=null,n||(o=e(...r),i||(r=null)))};function l(){i!==void 0&&(clearTimeout(i),i=null)}function c(...f){r=f,s=Date.now();const u=n&&!i;return i||(i=setTimeout(a,t)),u&&(o=e(...r),r=null),o}return c.cancel=l,c}const jv=15,Sd=17;class Qv{constructor(t,n,i){var o,a,l;this.type="geojson",this.isCustomPromoteId=!1,this.id=Yv(),this.modelsAppearStrategy=(o=n.modelsAppearStrategy)!=null?o:Rh,this.modules=t.modules,this.mapglApiSource=i,this.identifiedAsDefault=!!n.identifyAsDefaultSource,n.promoteId&&(this.isCustomPromoteId=!0),this.identifiedAsDefault&&!n.promoteId&&(n.promoteId="db_id"),"generateId"in n&&n.promoteId&&(n.generateId=!1),this.sourceCore=new Hv(this.id,this.modules,n);const r=(a=n.minZoom)!=null?a:Oc.minZoom,s=Math.min((l=n.maxZoom)!=null?l:jv,Sd);this.layer=new Wv(r,s,r,Sd,this.modules,t.state,this.sourceCore,n),this.modules.tileManager.addTileLayer(this.layer)}destroy(){this.modules.tileManager.removeTileLayer(this.layer),this.layer.destroy(),this.modules.sourceStorage.removeSource(this.getId()),this.sourceCore.destroy()}setAttributes(t){this.sourceCore.setAttributes(t),this.layer.redraw(),this.modules.identifier.resetCache()}getAttributes(){return this.sourceCore.getAttributes()}getZoomDirection(){return this.layer.getZoomDirection()}getId(){return this.sourceCore.id}isIdentifiedAsDefault(){return this.identifiedAsDefault}}const Yl={type:"FeatureCollection",features:[]};let qv=class Bx extends Qv{constructor(t,n,i){n.generateId=!0,super(t,n,i),this.subtype="internal",this.data=n.data,this instanceof Bx&&this.modules.sourceStorage.addSource(this)}getFeatureById(t,n){if(this.data.type==="FeatureCollection"){let i;const r=this.sourceCore.getComponentIndex(t,n);return r===void 0?(this.isCustomPromoteId&&(i=this.data.features.find(s=>s.id===t)),i):this.data.features[r]}return this.data}destroy(){super.destroy(),this.data=Yl}setData(t){return Fe(this,null,function*(){(yield this.sourceCore.setData(t))&&(this.data=t,this.layer.onSourceDataChange(),this.modules.identifier.resetCache())})}setDataFilter(t){this.sourceCore.setDataFilter(t)}};class f3 extends Qv{constructor(t,n,i){super(t,n,i),this.subtype="external",n.preventInteractions&&(n.promoteId=void 0),this.modules.sourceStorage.addSource(this)}getObjectAttributes(t,n){return this.sourceCore.getObjectAttributes(t,n)}setDataUrl(t){return Fe(this,null,function*(){(yield this.sourceCore.setData(t))&&(this.layer.onSourceDataChange(),this.modules.identifier.resetCache())})}}let u3=class extends qv{constructor(t,n,i){super(t,n,i),this.subtype="viewport-internal",this.destroyed=!1,this.viewportDiffer=new Xv([{path:"center",type:"vec3"},{path:"zoom",type:"number"},{path:"size",type:"vec2"},{path:"rotation",type:"number"},{path:"pitch",type:"number"},{path:"padding",type:"padding"},{path:"demMode",type:"boolean"},{path:"elevation",type:"number"},{path:"minElevation",type:"number"}]),this._map=t,this.viewportPadding=n.viewportPadding,this.modules.sourceStorage.addSource(this)}setDataFn(t){return Fe(this,null,function*(){this.setViewportHandler(t)})}setViewportPadding(t){this.viewportPadding=t,this.viewportHandler&&this.viewportHandler()}update(){this.viewportDiffer.check(this._map.state)&&this.viewportHandler&&this.viewportHandler()}destroy(){this.destroyed=!0,this.viewportHandler&&(this.viewportHandler.cancel(),this.viewportHandler=void 0),super.destroy()}setViewportHandler(t){if(!t){this.setData(Yl),this.viewportHandler=void 0;return}this.viewportHandler=Zv(()=>Fe(this,null,function*(){const n=this._map.getBounds({sizeExtension:this.viewportPadding}),i=n.southWest,r=n.northEast,s=[i[0],i[1],r[0],r[1]],o=t(s);let a=Yl;try{const l=yield fetch(o);l.ok||console.error(`Failed to fetch a tile by url "${o}", status: ${l.status}`);const c=l.headers.get("content-type");(!c||!c.includes("application/json"))&&console.error(`Failed to fetch a tile by url "${o}", expected the "application/json" data but got "${c}"`),a=yield l.json()}catch(l){console.error(`Failed to fetch a tile by url "${o}", message: ${l.message}`)}this.destroyed||this.setData(a)}),500),this.viewportHandler()}};function Kv(e){return new Promise(t=>setTimeout(t,e))}class d3{constructor(){this.cache=new Map,this.pendingRequests=new Map}fetch(t,n=3,i=300){return Fe(this,null,function*(){var o;let r=0,s;for(;r<=n;)try{if(s=yield this.fetchAttempt(t),!s)return;if(!s.err||!k0((o=s.err)==null?void 0:o.status))return s;throw new Error(`Fetching ${JSON.stringify(t.coords)} attempt ${r} failed.`)}catch(a){if(r>=n)return{metadata:[]};yield Kv(Math.pow(2,r)*i),r++}})}get(t){return this.cache.get(t)||[]}delete(t){this.cache.delete(t)}abortRequest(t){const n=this.pendingRequests.get(t);n!==void 0&&(n.xhr.abort(),n.resolve(),this.pendingRequests.delete(t))}destroy(){this.cache.clear(),this.pendingRequests.clear()}fetchAttempt({tileUrl:t,coords:n,headers:i}){return new Promise(r=>{const s=De(n),o=Dl({url:t,headers:i},(a,l)=>{if(this.pendingRequests.delete(s),a||l.byteLength===0){a!==void 0&&console.error(a),this.cache.set(s,[]),r({metadata:[],err:a});return}const c=Ab(l),f=bb(c);this.cache.set(s,c),r({metadata:f,err:a})});this.pendingRequests.set(s,{xhr:o,resolve:r})})}}class Ed extends Map{constructor(t){super(t),this.featureAttrs=(t==null?void 0:t.featureAttrs)||new Set,this.clearAttrs=!0}set(t,n){return super.set(t,n),Object.keys(n).forEach(i=>this.featureAttrs.add(i)),this}}function Td(e){for(let t=1;t<e.length;t++)e[t]=e[t]+e[t-1]}function h3(e){let t=0,n=0,i=0;for(let r=0;r<e.length;r+=2)i=n+e[r],n=i>>>0,e[r]=n,t=t+e[r+1]+(i>4294967295?1:0)>>>0,e[r+1]=t}const Jv={1:Td,2:Td,4:Td,8:h3};class $v{constructor(t){this.offset=0,this.buffer=t,this.u8=new Uint8Array(t),this.u16=new Uint16Array(t),this.u32=new Uint32Array(t),this.s8=new Int8Array(t),this.s16=new Int16Array(t),this.s32=new Int32Array(t),this.f32=new Float32Array(t)}readS8(){return this.s8[this.offset++]}readU16(){const t=this.u16[this.offset>>1];return this.offset+=2,t}readU32(){const t=this.u32[this.offset>>2];return this.offset+=4,t}readF32(){const t=this.f32[this.offset>>2];return this.offset+=4,t}readU8Vector(t=1){const i=this.readU32()*t,r=-i&3,s=this.u8.subarray(this.offset,this.offset+i);return this.offset+=i+r,s}readU16Vector(t=1){const i=this.readU32()*t*2,r=-i&3,s=this.u16.subarray(this.offset>>1,this.offset+i>>1);return this.offset+=i+r,s}}function et(e,t,n,i){const r=t.BYTES_PER_ELEMENT;e.offset+=-e.offset&r-1;const s=new t(e.buffer,e.offset,n);return e.offset+=r*n,i&&Jv[r](s),s}function Xl(e,t,n){e.offset+=-e.offset&7;const i=new Uint32Array(e.buffer,e.offset,t*2);return e.offset+=8*t,n&&Jv[8](i),i}function ey(e,t,n){e.offset+=-e.offset&3;const i=new Uint32Array(e.buffer,e.offset,t),r=new Float32Array(e.buffer,e.offset,t);e.offset+=4*t;let s;if(n){let o=0;for(s=0;s<t;s++)o=o+i[s]>>>0,r[s]=o/1e3}else for(s=0;s<t;s++)r[s]=i[s]/1e3;return r}function ty(e,t,n){e.offset+=-e.offset&3;const i=new Int32Array(e.buffer,e.offset,t),r=new Float32Array(e.buffer,e.offset,t);e.offset+=4*t;let s;if(n){let o=0;for(s=0;s<t;s++)o=o+i[s]>>>0,r[s]=(o|0)/1e3}else for(s=0;s<t;s++)r[s]=i[s]/1e3;return r}function p3(e,t){let n=e.offset;const i=e.u8,r=e.buffer,s=[];for(;t--;)s.push(i[n++]|0);const o=[];for(;++t<s.length;){let a=s[t];a===255&&(a=i[n++]|i[n++]<<8|i[n++]<<16|0),o.push(new Uint8Array(r,n,a)),n=n+a}return e.offset=n,o}function g3(e,t){e.offset+=-e.offset&3;let n=e.offset;const i=e.u32,r=e.buffer,s=[];for(let a=0;a<t;a++)s.push(i[n>>2]),n+=4;const o=[];for(let a=0;a<t;a++){const l=s[a];n+=-n&7,o.push(new Uint8Array(r,n,l)),n+=l}return e.offset=n,o}function m3(e,t,n){switch(n){case 2:return et(e,Uint8Array,t);case 3:return et(e,Uint8Array,t,!0);case 4:return et(e,Uint16Array,t);case 5:return et(e,Uint16Array,t,!0);case 6:return et(e,Uint32Array,t);case 7:return et(e,Uint32Array,t,!0);case 8:return Xl(e,t);case 9:return Xl(e,t,!0);case 10:return et(e,Uint8Array,t);case 11:return p3(e,t);case 12:return g3(e,t);case 13:return et(e,Int8Array,t);case 14:return et(e,Int8Array,t,!0);case 15:return et(e,Int16Array,t);case 16:return et(e,Int16Array,t,!0);case 17:return et(e,Int32Array,t);case 18:return et(e,Int32Array,t,!0);case 19:return Xl(e,t);case 20:return Xl(e,t,!0);case 21:return ey(e,t);case 22:return ey(e,t,!0);case 23:return ty(e,t);case 24:return ty(e,t,!0);case 25:return et(e,Uint32Array,t);default:throw new Error("Unknown stream type "+n)}}function Pd(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t}function v3(e,t,n){return new e.constructor(e.buffer,e.byteOffset+t*e.BYTES_PER_ELEMENT,n)}let tr;const Ms=[],On=new Int32Array(256);let Id;const Md=[],ny=[],iy=[],_d=[0,0,0,0,0];let ry=0,Cd=0,Fd=0,_s={};function y3(e,t,n,i,r,s,o,a,l=!1,c,f,u,d){const{styleState:h,sourceId:g,sourceAttrs:y,tileInfo:p,pixelRatio:v,selectedIds:A,dataFilter:w,floorsEnabled:S,hoverId:T,generateOnlySelectedPoi:I,generateOnlyHoveredPoi:C,modelsPath:M,sharedModelsPath:B,needFallbackScreenLabels:D}=r,{data:F}=s,z=new Set(A),N=Sb(F);if(N.byteLength<8)return i.getAccumulatedData();Ms.length=0;const H=new $v(N);if(H.readU32()!==1279676242)return i.getAccumulatedData();const P=H.readU16();if(P!==2&&P!==3&&P!==4)return console.error(`Unsupported tile format version: "${P}"`),i.getAccumulatedData();tr=P,H.readU16();const b=Vf(v);x3(H),w3(H),A3(tr,e,t,h,n,i,H,p,b,z,w,o,a,S,g,D,y,l,T,I,C,M,c,f,u,d,B);const E=i.getAccumulatedData(),x=KE(E.data);return x.length&&(E.tierTrees=x,x.forEach(({tree:L})=>E.transferable.push(L))),E}function x3(e){const t=tr===4?2:1,n=e.u8;let i=e.offset,r=e.u32[i>>2];for(i+=4,ry=r,Cd=i;r--;)i=n[i++]*2+i,i=n[i++]*t+i;e.offset=i+(-i&3)}function w3(e){const t=e.u32[e.offset>>2];e.offset+=4,Id=et(e,Uint8Array,t);const n=et(e,Uint32Array,t);for(let i=0;i<t;i++){const r=Id[i];Ms[i]=m3(e,n[i],r),On[i]=0}}function A3(e,t,n,i,r,s,o,a,l,c,f,u,d,h,g,y,p,v=!1,A,w,S,T,I,C,M,B,D){const F=Array.from(r.featureAttrs);Kr(u,F);const z=ry,N=et(o,Int32Array,z),H=Pd(N),K=et(o,Uint8Array,H,!0),P=et(o,Uint8Array,Pd(K),!0),b=et(o,Uint8Array,H,!0),E=et(o,Uint8Array,Pd(b),!0),x=et(o,Uint16Array,H,!0);let L=0,O=0,R=0,G=!0;for(let Q=0;Q<z;Q++){const X=N[Q];T3(o,u,d);for(let se=0;se<X;se++){const te=K[L];te>0&&(b3(d,te,P,O,u,e,v),O+=te);const U=b[L];if(U>0&&(S3(d,U,E,R),R+=U),!d[u.tileProps.db_geometry_type]){console.error(`Geometry type not specified for data source ${g}. Metatile version ${u.version}`);return}G=te>0||U>0;const ne=u.tileProps;let ee=d[ne[M!=null?M:""]];Number.isNaN(ee)&&(ee=void 0);const ge=go(i,p,ne,d,[],y,ee,a),de=x[L];de>0&&E3(e,t,n,i,ge,r,s,de,a,l,c,f,u,h,g,A,w,S,T,I,G,C,B,D),L++}}sy()}function b3(e,t,n,i,r,s,o=!1){var a,l;for(;t--;){const c=n[i++],f=ny[c],u=Md[c],d=Id[f];if(d===8||d===9||d===19||d===20)e[u]=M0(Ms[f][On[f]],Ms[f][On[f]+1]),On[f]+=2;else{const h=Ms[f][On[f]];switch(u){case r.tileProps.objectLength:case r.tileProps.db_centroid_x:case r.tileProps.db_centroid_y:case r.tileProps.componentDistanceEnd:case r.tileProps.componentDistanceStart:case r.tileProps.previousPointX:case r.tileProps.previousPointY:case r.tileProps.nextPointX:case r.tileProps.nextPointY:e[u]=s===2?h*ot:h;break;case r.tileProps.db_label:e[u]=Ra(h);break;case r.tileProps.db_label2:e[u]=Ra(h);break;case r.tileProps.db_schedule:e[u]=JSON.parse(Ra(h));break;case r.tileProps.db_tiers:const g=h.byteLength/Int32Array.BYTES_PER_ELEMENT,y=new DataView(h.buffer,h.byteOffset,h.byteLength),p=y.getInt32(0,!0);if(g===1&&!p)e[u]=void 0;else{const v=new Array(g);v[0]=p;for(let A=1;A<g;A++)v[A]=y.getInt32(A*Int32Array.BYTES_PER_ELEMENT,!0);e[u]=v}break;case r.tileProps.db_shared_model_id:Kr(r,["db_model_theme1_src","db_model_theme2_src"]),e[r.tileProps.db_model_theme1_src]=`{sharedModelsPath}${h}_d.glb`,e[r.tileProps.db_model_theme2_src]=`{sharedModelsPath}${h}_n.glb`;break;default:if(o&&d===11)e[u]=Ra(h);else{const v=r.tilePropsByIndex[u];e[u]=(l=(a=r.reverseDictionaries[v])==null?void 0:a[h])!=null?l:h}}On[f]++}}}function S3(e,t,n,i){for(;t--;){const r=n[i++],s=Md[r];e[s]=NaN}}let Zl=[];function E3(e,t,n,i,r,s,o,a,l,c,f,u,d,h,g,y,p,v,A,w=[],S,T,I,C){var b;const{tileProps:M,defaultProps:B}=d,{tileAttrs:D,featureAttrs:F,id:z}=r,N=l.coords[3],H=M.db_hidden_by_plan_id!==void 0;if(!S&&Zl.length===0){for(let E=0;E<Fd;E++){const x=_d[E];On[x]=On[x]+a}return}const K=D[M.db_geometry_type],P=tr===4?d.vertexProps:d.vertexPropsLegacy[K];if(!P){console.error(`Couldn't get vertex keys for tile ${De(l.coords)} source ${g}. Metatile version ${d.version}`);return}for(let E=0;E<Fd;E++){const x=tr===4?iy[E]:E,L=_d[E],O=(b=P[x])!=null?b:"signed_z";_s[O]=P3(v3(Ms[L],On[L],a),E,e),tr===4&&O==="z"&&(_s.signed_z=_s.z),On[L]=On[L]+a}if(!(M.db_sublayer!==void 0&&!Number.isNaN(D[M.db_sublayer])&&Tl(D[M.db_sublayer]))&&!(H&&i._activeFloorIds&&D[M.db_hidden_by_plan_id]&&(i._activeFloorIds.includes(D[M.db_hidden_by_plan_id])||i._backgroundFloorIds.includes(D[M.db_hidden_by_plan_id])))){for(const E in B){const x=B[E];Number.isNaN(D[x.index])&&(D[x.index]=x.value)}if(!(y&&y!==z)){if(z!==void 0){let E=f.has(z);p&&(E=!0);const x=!!v||!!y&&y===z;if(D[M.selected]=E?1:0,D[M.hovered]=x?1:0,w.length>0){const L={};w.forEach(O=>{L[O]=D[M[O]]}),o.addPromotedObjectAttributes(z,L)}h&&N>=Uc.detailLevel&&(D[M.db_hidden_by_plan_building_id]&&o.addFloorHidingMap(z,D[M.db_hidden_by_plan_building_id]),D[M.db_hidden_by_metro_building_id]&&o.addFloorHidingMap(z,D[M.db_hidden_by_metro_building_id]))}else D[M.selected]=0,D[M.hovered]=0;if(s.featureAttrs.size>0){const E=z!==void 0&&s.get(z);if(E)for(const x of s.featureAttrs)s.clearAttrs=!1,F[M[x]]=E[x];else if(s.clearAttrs===!1){s.clearAttrs=!0;for(const x in M)F[M[x]]!==void 0&&(F[M[x]]=void 0)}}if(T){const E=I3(_s,K,l);if(E){const x=M3(r,De(l.coords));o.addFeature({type:"Feature",properties:x,geometry:E})}return}S&&(Zl=n.getLayers(t.id,M,D).filter(E=>k(E.filter,r)&&(u?k(u,r):!0))),Zl.length===0&&r.id&&o.idIndexer.addOrphanId(r.id),ju(o,t,Zl,r,d,tr,N,g,l,c,_s,p||v,A,I,C)}}}function T3(e,t,n){const i=Object.keys(t.tileProps).length,r=e.u8;let s,o,a=Cd;for(o=1;o<i;o++)n[o]=NaN;for(s=r[a++],o=0;o<s;o++)Md[o]=r[a++],ny[o]=r[a++];for(s=r[a++],o=0;o<s;o++)tr===4&&(iy[o]=r[a++]),_d[o]=r[a++];Fd=s,Cd=a,sy()}function sy(){_s={}}function P3(e,t,n){if(n===2&&t<3&&e instanceof Uint16Array)for(let i=0;i<e.length;i++)e[i]*=ot;return e}function I3(e,t,n){var l;const i=[],{x:r,y:s,z:o,signed_z:a}=e;for(let c=0;c<e.x.length;c++){const f=ro(r[c],s[c],n),u=me.scaleFactor(f[1]),d=o?o[c]*32:void 0;f[2]=(l=d!=null?d:a==null?void 0:a[c])!=null?l:0,f[2]/=Ee*u,i.push(f)}if(i.length)switch(t){case"point":return{type:"MultiPoint",coordinates:i};case"polyline":return{type:"LineString",coordinates:i};case"polygon":return{type:"Polygon",coordinates:[i.map((c,f)=>i[mt(f,i.length)])]};default:return}}function M3(e,t){const n={tile:t};return Object.keys(e.tileProps).forEach(i=>{const r=e.tileAttrs[e.tileProps[i]];!Number.isNaN(r)&&r!==void 0&&(n[i]=r)}),n}const _3=e=>{if(e.length>2){let t=0;for(let n=e.length-1,i=n,r=0;r<=n;r++){const s=e[i],o=e[r];t+=(s[0]+o[0])*(s[1]-o[1]),i=r}return t/2}else return 0},C3=e=>_3(e)>0;function F3(e){e=e.slice().sort(L3);const t=e.length,n=new Array(t*2);let i=0;for(let s=0;s<t;s++){const o=e[s];for(;i>=2&&oy(n[i-2],n[i-1],o)<=0;)i--;n[i++]=o}const r=i+1;for(let s=t-2;s>=0;s--){const o=e[s];for(;i>=r&&oy(n[i-2],n[i-1],o)<=0;)i--;n[i++]=o}return n.slice(0,i-1)}function oy(e,t,n){return(t[1]-e[1])*(n[0]-e[0])-(t[0]-e[0])*(n[1]-e[1])}function L3(e,t){return e[0]===t[0]?e[1]-t[1]:e[0]-t[0]}function B3(e){const t=[],n=C3(e),i=ia(e[0],e[e.length-1]),r=i?e.length-1:e.length;for(let s=r-1,o=0,a=1;o<r;o++,s=o-1,a=(o+1)%r){const l=[];PA(l,e[s],e[o],e[a],n),t.push(l)}return i&&t.push(t[0]),t}const jl=[[0],[0],[0]],ay=[];function D3(e,t,n,i,r,s,o,a,l){const{matrix:c,offset:f,id:u,selected:d}=s,h=new $v(r),g=[];if(!e)return{objects:i.getAccumulatedData(),textures:g};if(h.readU32()!==1296191066||h.readU16()!==1)return{objects:i.getAccumulatedData(),textures:[]};h.readU16();const y=h.readU32();for(let M=0;M<y;M++)g.push(h.readU8Vector());const{tileProps:p}=o,v=[],A=Object.keys(p).length;for(let M=0;M<A;M++)v[M]=NaN;if(v[p.db_sublayer]="Building_model",v[p.selected]=d?1:0,v[p.db_region]=a,l.featureAttrs.size>0){const M=Array.from(l.featureAttrs);Kr(o,M)}const w=[],S=typeof u!="number"&&l.get(u);if(S)for(const M of l.featureAttrs)l.clearAttrs=!1,w[p[M]]=S[M];else if(l.clearAttrs===!1){l.clearAttrs=!0;for(const M in p)w[p[M]]!==void 0&&(w[p[M]]=void 0)}const T=h.offset,I=go(n,xf,p,v,w,!0,u),C=t.getLayers(e.id,p,v).filter(M=>k(M.filter,I));return C.length===0&&I.id&&i.idIndexer.addOrphanId(I.id),C.forEach(M=>{M.type!=="buildingModel"||(Zu(M,I),!k(M.filter,I))||(h.offset=T,O3(e,M,I,i,h,c,f))}),{objects:i.getAccumulatedData(),textures:g}}function O3(e,t,n,i,r,s,o){const a=r.readU32();for(let l=0;l<a;l++){const c=r.readU32(),f=bt(r.readF32(),r.readF32(),r.readF32()),u=bt(r.readF32(),r.readF32(),r.readF32()),d=ln(nt(),u,f),h=[];mp(h,s,f),Xr(h,h,d),h[12]+=o[0],h[13]+=o[1];const g=r.readU16Vector(5),y=r.readU32();for(let w=0;w<y;w++){const S=r.readU32()===1?Oh:qo,T=r.readU16Vector();do mi.processSubmesh(e.id,t,n,i,g,T,S,c,h);while(i.isOverloaded())}const p=r.readU16Vector();do mi.processOuterEdge(e.id,t,n,i,g,p,h);while(i.isOverloaded());const v=F3(R3(g)),A=B3(v);for(let w=0;w<v.length-2;w++){for(let S=0;S<3;S++){const T=z3(w+S,v.length);jl[0][S]=v[T][0],jl[1][S]=v[T][1],jl[2][S]=0,ay[S]=A[T]}do Kt.generateFloorsBottomFill(i,e.id,jl,ay,tl,h);while(i.isOverloaded())}}}function R3(e){const t=[];for(let n=0;n<e.length;n+=5)t.push([e[n],e[n+1]]);return t}function z3(e,t){return e===0?0:e%2?(e+1)/2:t-e/2}function N3(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ld={};Ld.read=function(e,t,n,i,r){var s,o,a=r*8-i-1,l=(1<<a)-1,c=l>>1,f=-7,u=n?r-1:0,d=n?-1:1,h=e[t+u];for(u+=d,s=h&(1<<-f)-1,h>>=-f,f+=a;f>0;s=s*256+e[t+u],u+=d,f-=8);for(o=s&(1<<-f)-1,s>>=-f,f+=i;f>0;o=o*256+e[t+u],u+=d,f-=8);if(s===0)s=1-c;else{if(s===l)return o?NaN:(h?-1:1)*(1/0);o=o+Math.pow(2,i),s=s-c}return(h?-1:1)*o*Math.pow(2,s-i)},Ld.write=function(e,t,n,i,r,s){var o,a,l,c=s*8-r-1,f=(1<<c)-1,u=f>>1,d=r===23?Math.pow(2,-24)-Math.pow(2,-77):0,h=i?0:s-1,g=i?1:-1,y=t<0||t===0&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,o=f):(o=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-o))<1&&(o--,l*=2),o+u>=1?t+=d/l:t+=d*Math.pow(2,1-u),t*l>=2&&(o++,l/=2),o+u>=f?(a=0,o=f):o+u>=1?(a=(t*l-1)*Math.pow(2,r),o=o+u):(a=t*Math.pow(2,u-1)*Math.pow(2,r),o=0));r>=8;e[n+h]=a&255,h+=g,a/=256,r-=8);for(o=o<<r|a,c+=r;c>0;e[n+h]=o&255,h+=g,o/=256,c-=8);e[n+h-g]|=y*128};var G3=Ce,Ql=Ld;function Ce(e){this.buf=ArrayBuffer.isView&&ArrayBuffer.isView(e)?e:new Uint8Array(e||0),this.pos=0,this.type=0,this.length=this.buf.length}Ce.Varint=0,Ce.Fixed64=1,Ce.Bytes=2,Ce.Fixed32=5;var Bd=65536*65536,ly=1/Bd,k3=12,cy=typeof TextDecoder>"u"?null:new TextDecoder("utf8");Ce.prototype={destroy:function(){this.buf=null},readFields:function(e,t,n){for(n=n||this.length;this.pos<n;){var i=this.readVarint(),r=i>>3,s=this.pos;this.type=i&7,e(r,t,this),this.pos===s&&this.skip(i)}return t},readMessage:function(e,t){return this.readFields(e,t,this.readVarint()+this.pos)},readFixed32:function(){var e=ql(this.buf,this.pos);return this.pos+=4,e},readSFixed32:function(){var e=uy(this.buf,this.pos);return this.pos+=4,e},readFixed64:function(){var e=ql(this.buf,this.pos)+ql(this.buf,this.pos+4)*Bd;return this.pos+=8,e},readSFixed64:function(){var e=ql(this.buf,this.pos)+uy(this.buf,this.pos+4)*Bd;return this.pos+=8,e},readFloat:function(){var e=Ql.read(this.buf,this.pos,!0,23,4);return this.pos+=4,e},readDouble:function(){var e=Ql.read(this.buf,this.pos,!0,52,8);return this.pos+=8,e},readVarint:function(e){var t=this.buf,n,i;return i=t[this.pos++],n=i&127,i<128||(i=t[this.pos++],n|=(i&127)<<7,i<128)||(i=t[this.pos++],n|=(i&127)<<14,i<128)||(i=t[this.pos++],n|=(i&127)<<21,i<128)?n:(i=t[this.pos],n|=(i&15)<<28,U3(n,e,this))},readVarint64:function(){return this.readVarint(!0)},readSVarint:function(){var e=this.readVarint();return e%2===1?(e+1)/-2:e/2},readBoolean:function(){return!!this.readVarint()},readString:function(){var e=this.readVarint()+this.pos,t=this.pos;return this.pos=e,e-t>=k3&&cy?nF(this.buf,t,e):tF(this.buf,t,e)},readBytes:function(){var e=this.readVarint()+this.pos,t=this.buf.subarray(this.pos,e);return this.pos=e,t},readPackedVarint:function(e,t){if(this.type!==Ce.Bytes)return e.push(this.readVarint(t));var n=Si(this);for(e=e||[];this.pos<n;)e.push(this.readVarint(t));return e},readPackedSVarint:function(e){if(this.type!==Ce.Bytes)return e.push(this.readSVarint());var t=Si(this);for(e=e||[];this.pos<t;)e.push(this.readSVarint());return e},readPackedBoolean:function(e){if(this.type!==Ce.Bytes)return e.push(this.readBoolean());var t=Si(this);for(e=e||[];this.pos<t;)e.push(this.readBoolean());return e},readPackedFloat:function(e){if(this.type!==Ce.Bytes)return e.push(this.readFloat());var t=Si(this);for(e=e||[];this.pos<t;)e.push(this.readFloat());return e},readPackedDouble:function(e){if(this.type!==Ce.Bytes)return e.push(this.readDouble());var t=Si(this);for(e=e||[];this.pos<t;)e.push(this.readDouble());return e},readPackedFixed32:function(e){if(this.type!==Ce.Bytes)return e.push(this.readFixed32());var t=Si(this);for(e=e||[];this.pos<t;)e.push(this.readFixed32());return e},readPackedSFixed32:function(e){if(this.type!==Ce.Bytes)return e.push(this.readSFixed32());var t=Si(this);for(e=e||[];this.pos<t;)e.push(this.readSFixed32());return e},readPackedFixed64:function(e){if(this.type!==Ce.Bytes)return e.push(this.readFixed64());var t=Si(this);for(e=e||[];this.pos<t;)e.push(this.readFixed64());return e},readPackedSFixed64:function(e){if(this.type!==Ce.Bytes)return e.push(this.readSFixed64());var t=Si(this);for(e=e||[];this.pos<t;)e.push(this.readSFixed64());return e},skip:function(e){var t=e&7;if(t===Ce.Varint)for(;this.buf[this.pos++]>127;);else if(t===Ce.Bytes)this.pos=this.readVarint()+this.pos;else if(t===Ce.Fixed32)this.pos+=4;else if(t===Ce.Fixed64)this.pos+=8;else throw new Error("Unimplemented type: "+t)},writeTag:function(e,t){this.writeVarint(e<<3|t)},realloc:function(e){for(var t=this.length||16;t<this.pos+e;)t*=2;if(t!==this.length){var n=new Uint8Array(t);n.set(this.buf),this.buf=n,this.length=t}},finish:function(){return this.length=this.pos,this.pos=0,this.buf.subarray(0,this.length)},writeFixed32:function(e){this.realloc(4),Cs(this.buf,e,this.pos),this.pos+=4},writeSFixed32:function(e){this.realloc(4),Cs(this.buf,e,this.pos),this.pos+=4},writeFixed64:function(e){this.realloc(8),Cs(this.buf,e&-1,this.pos),Cs(this.buf,Math.floor(e*ly),this.pos+4),this.pos+=8},writeSFixed64:function(e){this.realloc(8),Cs(this.buf,e&-1,this.pos),Cs(this.buf,Math.floor(e*ly),this.pos+4),this.pos+=8},writeVarint:function(e){if(e=+e||0,e>268435455||e<0){W3(e,this);return}this.realloc(4),this.buf[this.pos++]=e&127|(e>127?128:0),!(e<=127)&&(this.buf[this.pos++]=(e>>>=7)&127|(e>127?128:0),!(e<=127)&&(this.buf[this.pos++]=(e>>>=7)&127|(e>127?128:0),!(e<=127)&&(this.buf[this.pos++]=e>>>7&127)))},writeSVarint:function(e){this.writeVarint(e<0?-e*2-1:e*2)},writeBoolean:function(e){this.writeVarint(!!e)},writeString:function(e){e=String(e),this.realloc(e.length*4),this.pos++;var t=this.pos;this.pos=iF(this.buf,e,this.pos);var n=this.pos-t;n>=128&&fy(t,n,this),this.pos=t-1,this.writeVarint(n),this.pos+=n},writeFloat:function(e){this.realloc(4),Ql.write(this.buf,e,this.pos,!0,23,4),this.pos+=4},writeDouble:function(e){this.realloc(8),Ql.write(this.buf,e,this.pos,!0,52,8),this.pos+=8},writeBytes:function(e){var t=e.length;this.writeVarint(t),this.realloc(t);for(var n=0;n<t;n++)this.buf[this.pos++]=e[n]},writeRawMessage:function(e,t){this.pos++;var n=this.pos;e(t,this);var i=this.pos-n;i>=128&&fy(n,i,this),this.pos=n-1,this.writeVarint(i),this.pos+=i},writeMessage:function(e,t,n){this.writeTag(e,Ce.Bytes),this.writeRawMessage(t,n)},writePackedVarint:function(e,t){t.length&&this.writeMessage(e,X3,t)},writePackedSVarint:function(e,t){t.length&&this.writeMessage(e,Z3,t)},writePackedBoolean:function(e,t){t.length&&this.writeMessage(e,q3,t)},writePackedFloat:function(e,t){t.length&&this.writeMessage(e,j3,t)},writePackedDouble:function(e,t){t.length&&this.writeMessage(e,Q3,t)},writePackedFixed32:function(e,t){t.length&&this.writeMessage(e,K3,t)},writePackedSFixed32:function(e,t){t.length&&this.writeMessage(e,J3,t)},writePackedFixed64:function(e,t){t.length&&this.writeMessage(e,$3,t)},writePackedSFixed64:function(e,t){t.length&&this.writeMessage(e,eF,t)},writeBytesField:function(e,t){this.writeTag(e,Ce.Bytes),this.writeBytes(t)},writeFixed32Field:function(e,t){this.writeTag(e,Ce.Fixed32),this.writeFixed32(t)},writeSFixed32Field:function(e,t){this.writeTag(e,Ce.Fixed32),this.writeSFixed32(t)},writeFixed64Field:function(e,t){this.writeTag(e,Ce.Fixed64),this.writeFixed64(t)},writeSFixed64Field:function(e,t){this.writeTag(e,Ce.Fixed64),this.writeSFixed64(t)},writeVarintField:function(e,t){this.writeTag(e,Ce.Varint),this.writeVarint(t)},writeSVarintField:function(e,t){this.writeTag(e,Ce.Varint),this.writeSVarint(t)},writeStringField:function(e,t){this.writeTag(e,Ce.Bytes),this.writeString(t)},writeFloatField:function(e,t){this.writeTag(e,Ce.Fixed32),this.writeFloat(t)},writeDoubleField:function(e,t){this.writeTag(e,Ce.Fixed64),this.writeDouble(t)},writeBooleanField:function(e,t){this.writeVarintField(e,!!t)}};function U3(e,t,n){var i=n.buf,r,s;if(s=i[n.pos++],r=(s&112)>>4,s<128||(s=i[n.pos++],r|=(s&127)<<3,s<128)||(s=i[n.pos++],r|=(s&127)<<10,s<128)||(s=i[n.pos++],r|=(s&127)<<17,s<128)||(s=i[n.pos++],r|=(s&127)<<24,s<128)||(s=i[n.pos++],r|=(s&1)<<31,s<128))return V3(e,r,t);throw new Error("Expected varint not more than 10 bytes")}function Si(e){return e.type===Ce.Bytes?e.readVarint()+e.pos:e.pos+1}function V3(e,t,n){return n?t*4294967296+(e>>>0):(t>>>0)*4294967296+(e>>>0)}function W3(e,t){var n,i;if(e>=0?(n=e%4294967296|0,i=e/4294967296|0):(n=~(-e%4294967296),i=~(-e/4294967296),n^4294967295?n=n+1|0:(n=0,i=i+1|0)),e>=18446744073709552e3||e<-18446744073709552e3)throw new Error("Given varint doesn't fit into 10 bytes");t.realloc(10),H3(n,i,t),Y3(i,t)}function H3(e,t,n){n.buf[n.pos++]=e&127|128,e>>>=7,n.buf[n.pos++]=e&127|128,e>>>=7,n.buf[n.pos++]=e&127|128,e>>>=7,n.buf[n.pos++]=e&127|128,e>>>=7,n.buf[n.pos]=e&127}function Y3(e,t){var n=(e&7)<<4;t.buf[t.pos++]|=n|((e>>>=3)?128:0),e&&(t.buf[t.pos++]=e&127|((e>>>=7)?128:0),e&&(t.buf[t.pos++]=e&127|((e>>>=7)?128:0),e&&(t.buf[t.pos++]=e&127|((e>>>=7)?128:0),e&&(t.buf[t.pos++]=e&127|((e>>>=7)?128:0),e&&(t.buf[t.pos++]=e&127)))))}function fy(e,t,n){var i=t<=16383?1:t<=2097151?2:t<=268435455?3:Math.floor(Math.log(t)/(Math.LN2*7));n.realloc(i);for(var r=n.pos-1;r>=e;r--)n.buf[r+i]=n.buf[r]}function X3(e,t){for(var n=0;n<e.length;n++)t.writeVarint(e[n])}function Z3(e,t){for(var n=0;n<e.length;n++)t.writeSVarint(e[n])}function j3(e,t){for(var n=0;n<e.length;n++)t.writeFloat(e[n])}function Q3(e,t){for(var n=0;n<e.length;n++)t.writeDouble(e[n])}function q3(e,t){for(var n=0;n<e.length;n++)t.writeBoolean(e[n])}function K3(e,t){for(var n=0;n<e.length;n++)t.writeFixed32(e[n])}function J3(e,t){for(var n=0;n<e.length;n++)t.writeSFixed32(e[n])}function $3(e,t){for(var n=0;n<e.length;n++)t.writeFixed64(e[n])}function eF(e,t){for(var n=0;n<e.length;n++)t.writeSFixed64(e[n])}function ql(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16)+e[t+3]*16777216}function Cs(e,t,n){e[n]=t,e[n+1]=t>>>8,e[n+2]=t>>>16,e[n+3]=t>>>24}function uy(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16)+(e[t+3]<<24)}function tF(e,t,n){for(var i="",r=t;r<n;){var s=e[r],o=null,a=s>239?4:s>223?3:s>191?2:1;if(r+a>n)break;var l,c,f;a===1?s<128&&(o=s):a===2?(l=e[r+1],(l&192)===128&&(o=(s&31)<<6|l&63,o<=127&&(o=null))):a===3?(l=e[r+1],c=e[r+2],(l&192)===128&&(c&192)===128&&(o=(s&15)<<12|(l&63)<<6|c&63,(o<=2047||o>=55296&&o<=57343)&&(o=null))):a===4&&(l=e[r+1],c=e[r+2],f=e[r+3],(l&192)===128&&(c&192)===128&&(f&192)===128&&(o=(s&15)<<18|(l&63)<<12|(c&63)<<6|f&63,(o<=65535||o>=1114112)&&(o=null))),o===null?(o=65533,a=1):o>65535&&(o-=65536,i+=String.fromCharCode(o>>>10&1023|55296),o=56320|o&1023),i+=String.fromCharCode(o),r+=a}return i}function nF(e,t,n){return cy.decode(e.subarray(t,n))}function iF(e,t,n){for(var i=0,r,s;i<t.length;i++){if(r=t.charCodeAt(i),r>55295&&r<57344)if(s)if(r<56320){e[n++]=239,e[n++]=191,e[n++]=189,s=r;continue}else r=s-55296<<10|r-56320|65536,s=null;else{r>56319||i+1===t.length?(e[n++]=239,e[n++]=191,e[n++]=189):s=r;continue}else s&&(e[n++]=239,e[n++]=191,e[n++]=189,s=null);r<128?e[n++]=r:(r<2048?e[n++]=r>>6|192:(r<65536?e[n++]=r>>12|224:(e[n++]=r>>18|240,e[n++]=r>>12&63|128),e[n++]=r>>6&63|128),e[n++]=r&63|128)}return n}const rF=N3(G3),sF=1,Dd={1:({pbf:e})=>e.readBoolean(),2:({pbf:e})=>e.readDouble(),3:({pbf:e})=>e.readString(),5:e=>{const{pbf:t}=e,n=t.readVarint(),i=new Array(n);for(let r=0;r<n;r++)i[r]=Od(e,t.readVarint());return i},4:e=>{const{pbf:t}=e,n=t.readVarint(),i={};for(let s=0;s<n;s++){var r=t.readVarint();i[e.keys[r>>3]]=Od(e,r&7)}return i},6:e=>null};function Od(e,t){const n=e.pbf;if(n.pos<n.length){const i=Dd[t];if(!i)throw new Error(`Type ${t} is not supported`);return i(e)}}function dy(e){const t=e.readVarint(),n=[];for(let i=0;i<t;i++){const r=e.readString(),s=e.readVarint();n.push({key:r,type:s})}return n}function oF(e,t){if(!e||!e.byteLength||e.byteLength<4)throw new Error("Bad array or insufficient array length.");const n=new rF(e),i=n.readFixed32(),r=i>>24&255;if(r>sF)throw new Error(`Version ${r} is not supported`);const s=i>>16&255,o=s;if(s===1&&o!==1)throw new Error("Packed with PackMethod.Generic cannot be unpacked with anything than UnpackMethod.Generic");switch(o){case 1:const a=n.readFixed32();if(a>=e.byteLength)return;const l=n.pos;n.pos=a;const c=n.readVarint(),f=new Array(c);for(let d=0;d<c;d++)f[d]=n.readString();n.pos=l;const u=n.readVarint();return Od({keys:f,pbf:n},u);case 2:{const d={keys:[],pbf:n},h=n.readFixed32(),g=dy(n),y={};for(const{key:p,type:v}of g){const A=Dd[v],w=[];for(let S=0;S<h;S++)w.push(A(d));y[p]=w}return y}case 3:{const d={keys:[],pbf:n},h=n.readFixed32(),g=dy(n),y=new Array(h);for(let p=0;p<h;p++)y[p]={};for(const{key:p,type:v}of g){const A=Dd[v];for(let w=0;w<h;w++)y[w][p]=A(d)}return y}default:throw new Error(`Method ${o} is not supported`)}}function hy(e){const t=new Ed;if(e instanceof ArrayBuffer){const r=oF(e);if(Array.isArray(r))for(const n of r){const i=n,{id:s}=i,o=Fx(i,["id"]);t.set(s,o)}else for(const s in r)t.set(s,r[s])}else for(const r in e)t.set(r,e[r]);return t}class aF{constructor(t){this.scope=t,this.tileLoader=new d3,this.tileAttrs=[],this.models={},this.featureStateMap=new Ed}fetchTiles(t,n=3){const i=[];for(const r of t)i.push(this.tileLoader.fetch(r,n));return i}abortTileRequests(t){t.forEach(n=>this.tileLoader.abortRequest(n))}generateTile(t,n){const{styleManager:i,collector:r,metatiles:s}=this.scope,{tileInfo:o,promoteAttributes:a,promoteId:l,isCustomZenithSource:c,modelShowHideEventsSublayers:f}=t,u=De(o.coords),d=this.tileLoader.get(u),h=[],g=[],y=[],p={};return d.forEach(v=>{var I;const{regionId:A,metatileHash:w}=v,S=this.scope.styleManager.getStyle(t.styleId);if(!S)return;if(t.areTileBoundsVisible&&t.isDefaultSource){const M=i.getStyle(Rl).layers.find(B=>B.id==="debug-tile-bounds");rv(r,M,t.styleState)}const T=y3(S,i,this.featureStateMap,r,t,v,s[w],this.tileAttrs,c,a,n,l,f);Object.assign(p,T.promotedObjectAttributes),h.push({regionId:A,metatileHash:w,collectorOutput:T,styleId:S.id}),y.push(...T.transferable),(I=T.debugGeoJsonData)==null||I.forEach(C=>g.push(C))}),this.scope.resetCollector(),this.scope.syncRasterSets(),Promise.resolve({results:h,transferable:y,promotedAttrs:Object.keys(p).length>0?p:void 0,geoJsonData:n?g:void 0})}deleteTiles(t){for(const n of t)this.tileLoader.delete(n)}setFeatureStateMap(t){this.featureStateMap=hy(t)}generateModel(t){const{regionId:n,metatileHash:i,styleId:r,url:s,id:o}=t,{styleManager:a}=this.scope;return new Promise(l=>{const c=this.models[o];(c?Promise.resolve(c):new Promise(u=>{Dl({url:s},(d,h)=>{if(d||h.byteLength===0){const g=this.models[o]=new ArrayBuffer(0);u(g)}else this.models[o]=h,u(h)})})).then(u=>{if(u.byteLength===0){l({objects:this.scope.collector.getAccumulatedData(),textures:{isBitmap:!1,data:[]}});return}const d=this.scope.styleManager.getStyle(r);if(!d){l({objects:this.scope.collector.getAccumulatedData(),textures:{isBitmap:!1,data:[]}});return}const{objects:h,textures:g}=D3(d,a,t.styleState,this.scope.collector,u,t,this.scope.metatiles[i],n,this.featureStateMap);if(this.scope.createImageBitmap){const y=g.map(p=>{const v=new Blob([p],{type:"image/png"});return createImageBitmap(v)});Promise.all(y).then(p=>{l({objects:h,textures:{isBitmap:!0,data:p},transferable:[...h.transferable,...p]}),this.scope.resetCollector()})}else l({objects:h,textures:{isBitmap:!1,data:g},transferable:[...h.transferable,u]}),this.scope.resetCollector()})})}destroy(){this.tileLoader.destroy(),this.tileAttrs=[],this.models={}}}function lF(e,t){let n=!1,i;function r(){n=!1,i&&(s(...i),i=!1)}function s(...o){n?i=o:(e(...o),setTimeout(r,t),n=!0)}return s}const Kl=.8;class cF{constructor(t,n){this.offset=0,this.stride=n,this.buffer=new ArrayBuffer(t),this.view=new Int32Array(this.buffer),this.comittedOffsets=0,this.maximum=t/n,this.watermark=this.maximum*Kl}extend(){const t=this.buffer.byteLength*2;this.maximum=t/this.stride,this.watermark=this.maximum*Kl;const n=new ArrayBuffer(t),i=new Int32Array(n);return i.set(this.view),this.buffer=n,this.view=i,n}}class fF{constructor(t){this.offset=0,this.buffer=new Int32Array(t),this.comittedOffsets=0,this.watermark=t*Kl}extend(){const t=this.buffer.length*2;this.watermark=t*Kl;const n=new Int32Array(t);n.set(this.buffer),this.buffer=n}}class Rd{constructor(t,n,i,r,s,o){this.objectsData={},this.extents=new Float32Array([1/0,1/0,1/0,-1/0,-1/0,-1/0]),this.maxDiag=0,this.drawMode=s;const a=t!=="buildingModel"?67200:67200*5,l=Oo(t,n);this.elements=new cF(a,l),this.indices=new fF(a*2/l),this.views={},this.binder=r,r(this,this.elements.buffer),this.attributes=i,this.key=o}static generateKey(t){return JSON.stringify(t)}resetOffsets(){this.elements.offset=0,this.elements.comittedOffsets=0,this.indices.offset=0,this.indices.comittedOffsets=0}resetBuildingsData(){this.objectsData={}}resetInstancesExtents(){this.extents[0]=1/0,this.extents[1]=1/0,this.extents[2]=1/0,this.extents[3]=-1/0,this.extents[4]=-1/0,this.extents[5]=-1/0,this.maxDiag=0}commit(){this.elements.comittedOffsets=this.elements.offset,this.indices.comittedOffsets=this.indices.offset}rollback(){this.elements.offset=this.elements.comittedOffsets,this.indices.offset=this.indices.comittedOffsets}appendRaw(t,n,i){const r=this.elements;for(;r.offset+n>=r.maximum;)this.binder(this,r.extend());r.view.set(t,r.offset*r.stride>>2);const s=this.indices;for(;s.offset+i.length>=s.buffer.length;)s.extend();const o=s.buffer,a=r.offset;let l=s.offset;for(let c=0;c<i.length;c++)o[l++]=i[c]+a;s.offset=l,r.offset+=n}checkWatermarks(){let t=0;const n=this.elements;n.offset>n.watermark&&(n.offset>=n.buffer.byteLength/n.stride&&(t=1),this.binder(this,n.extend()));const i=this.indices;return i.offset>i.watermark&&(i.offset>=i.buffer.length&&(t=1),i.extend()),t}}function Ht(e,t,n){n=n||{},this.w=e||64,this.h=t||64,this.autoResize=!!n.autoResize,this.shelves=[],this.freebins=[],this.stats={},this.bins={},this.maxId=0}Ht.prototype.pack=function(e,t){e=[].concat(e),t=t||{};for(var n=[],i,r,s,o,a=0;a<e.length;a++)if(i=e[a].w||e[a].width,r=e[a].h||e[a].height,s=e[a].id,i&&r){if(o=this.packOne(i,r,s),!o)continue;t.inPlace&&(e[a].x=o.x,e[a].y=o.y,e[a].id=o.id),n.push(o)}return this.shrink(),n},Ht.prototype.packOne=function(e,t,n){var i={freebin:-1,shelf:-1,waste:1/0},r=0,s,o,a,l;if(typeof n=="string"||typeof n=="number"){if(s=this.getBin(n),s)return this.ref(s),s;typeof n=="number"&&(this.maxId=Math.max(n,this.maxId))}else n=++this.maxId;for(l=0;l<this.freebins.length;l++){if(s=this.freebins[l],t===s.maxh&&e===s.maxw)return this.allocFreebin(l,e,t,n);t>s.maxh||e>s.maxw||t<=s.maxh&&e<=s.maxw&&(a=s.maxw*s.maxh-e*t,a<i.waste&&(i.waste=a,i.freebin=l))}for(l=0;l<this.shelves.length;l++)if(o=this.shelves[l],r+=o.h,!(e>o.free)){if(t===o.h)return this.allocShelf(l,e,t,n);t>o.h||t<o.h&&(a=(o.h-t)*e,a<i.waste&&(i.freebin=-1,i.waste=a,i.shelf=l))}if(i.freebin!==-1)return this.allocFreebin(i.freebin,e,t,n);if(i.shelf!==-1)return this.allocShelf(i.shelf,e,t,n);if(t<=this.h-r&&e<=this.w)return o=new zd(r,this.w,t),this.allocShelf(this.shelves.push(o)-1,e,t,n);if(this.autoResize){var c,f,u,d;return c=f=this.h,u=d=this.w,(u<=c||e>u)&&(d=Math.max(e,u)*2),(c<u||t>c)&&(f=Math.max(t,c)*2),this.resize(d,f),this.packOne(e,t,n)}return null},Ht.prototype.allocFreebin=function(e,t,n,i){var r=this.freebins.splice(e,1)[0];return r.id=i,r.w=t,r.h=n,r.refcount=0,this.bins[i]=r,this.ref(r),r},Ht.prototype.allocShelf=function(e,t,n,i){var r=this.shelves[e],s=r.alloc(t,n,i);return this.bins[i]=s,this.ref(s),s},Ht.prototype.shrink=function(){if(this.shelves.length>0){for(var e=0,t=0,n=0;n<this.shelves.length;n++){var i=this.shelves[n];t+=i.h,e=Math.max(i.w-i.free,e)}this.resize(e,t)}},Ht.prototype.getBin=function(e){return this.bins[e]},Ht.prototype.ref=function(e){if(++e.refcount===1){var t=e.h;this.stats[t]=(this.stats[t]|0)+1}return e.refcount},Ht.prototype.unref=function(e){return e.refcount===0?0:(--e.refcount===0&&(this.stats[e.h]--,delete this.bins[e.id],this.freebins.push(e)),e.refcount)},Ht.prototype.clear=function(){this.shelves=[],this.freebins=[],this.stats={},this.bins={},this.maxId=0},Ht.prototype.resize=function(e,t){this.w=e,this.h=t;for(var n=0;n<this.shelves.length;n++)this.shelves[n].resize(e);return!0};function zd(e,t,n){this.x=0,this.y=e,this.w=this.free=t,this.h=n}zd.prototype.alloc=function(e,t,n){if(e>this.free||t>this.h)return null;var i=this.x;return this.x+=e,this.free-=e,new uF(n,i,this.y,e,t,e,this.h)},zd.prototype.resize=function(e){return this.free+=e-this.w,this.w=e,!0};function uF(e,t,n,i,r,s,o){this.id=e,this.x=t,this.y=n,this.w=i,this.h=r,this.maxw=s||i,this.maxh=o||r,this.refcount=0}class dF{constructor(){this.recordingCommitted=0,this.packer=new Ht(Yt[0],Yt[1]),this.currentAtlasIndex=0,this.packedRasters=[],this.rastersToLoad=[],this.newRasterSets=new Map}addNewRasterSet(t,n){let i=this.newRasterSets.get(t);i||(i=[],this.newRasterSets.set(t,i)),i.push(n)}pack(t,n,i){t.isSvg?this.packSvg(t,n.map(r=>({w:r,h:r})),i):this.packPng(t,n.map(r=>({w:r,h:r})),i)}packSvg(t,n,i){const{rasters:r}=t,s=new Set;for(const o of r)o&&s.add(`${o.w}_${o.h}`);for(const o of n){const a=o.w*i,l=o.h*i;if(s.has(`${a}_${l}`))continue;let c=this.packer.packOne(a+2,l+2);c===null&&(this.packer=new Ht(Yt[0],Yt[1]),this.currentAtlasIndex++,c=this.packer.packOne(a+2,l+2));const f=r.length,u={rasterSetIndex:t.index,rasterIndex:f,w:a,h:l,x:c.x+1,y:c.y+1,anchorX:t.anchorX,anchorY:t.anchorY,atlasIndex:this.currentAtlasIndex,isPacked:!0};r.push(u),this.packedRasters.push(t.index,f,u.x,u.y,u.w,u.h,this.currentAtlasIndex)}}addRastersToLoad(t,n){var i;this.rastersToLoad.push(t,n.rasterSetIndex,n.rasterIndex),(i=this.recording)==null||i.push(t,n.rasterSetIndex,n.rasterIndex)}beginRecording(){this.recording=[],this.recordingCommitted=0}commitRecording(){this.recording&&(this.recordingCommitted=this.recording.length)}rollbackRecording(){this.recording&&(this.recording.length=this.recordingCommitted)}endRecording(){var n;const t=(n=this.recording)!=null?n:[];return this.recording=void 0,t}addRecordedRastersToLoad(t){for(let n=0;n<t.length;n++)this.rastersToLoad.push(t[n])}getNewRasterSets(){const t=this.newRasterSets;return this.newRasterSets=new Map,t}getPackedRasters(){if(this.packedRasters.length===0)return;const t=new Uint16Array(this.packedRasters);return this.packedRasters=[],t}getRastersToLoad(){const t=new Float64Array(this.rastersToLoad);return this.rastersToLoad=[],t}packPng(t,n,i){const{rasters:r}=t,s=new Set;for(const o of r)o&&s.add(`${o.w}_${o.h}`);for(const o of n){if(s.has(`${o.w}_${o.h}`)&&t.type===Ir.Static)continue;const a=o.w*i,l=o.h*i;let c=os(r,a,!1),f;if(c===void 0)c=r.length,f={rasterSetIndex:t.index,rasterIndex:c,w:a,h:l,x:0,y:0,anchorX:0,anchorY:0,atlasIndex:this.currentAtlasIndex,isPacked:!1},r.push(f);else if(f=t.rasters[c],f.isPacked)continue;let u=this.packer.packOne(f.w+2,f.h+2);u===null&&(this.packer=new Ht(Yt[0],Yt[1]),this.currentAtlasIndex++,u=this.packer.packOne(f.w+2,f.h+2)),f.x=u.x+1,f.y=u.y+1,f.atlasIndex=this.currentAtlasIndex,f.isPacked=!0,this.packedRasters.push(t.index,c,f.x,f.y,f.w,f.h,this.currentAtlasIndex)}}}const hF=$(2,32)-17,pF=jc($(2,32)-1),gF=jc($(2,32)-2,!0),py={7:$(2,32)-3,6:$(2,32)-4,5:$(2,32)-5,4:$(2,32)-6,3:$(2,32)-7,2:$(2,32)-8,1:$(2,32)-9,0:$(2,32)-10,"-1":$(2,32)-11,"-2":$(2,32)-12,"-3":$(2,32)-13,"-4":$(2,32)-14,"-5":$(2,32)-15,"-6":$(2,32)-16,"-7":$(2,32)-17};class mF{constructor(){this.colorById=new Map,this.colorByTier=new Map,this.index=0}getIndexById(t){if(!t)return this.nextIndex();const n=this.colorById.get(t);if(n!==void 0)return n;const i=this.nextIndex();return this.colorById.set(t,i),i}getIndexByTier(t){if(typeof t!="number"||Number.isNaN(t))return this.nextIndex();const n=py[t];if(n!==void 0)return n;const i=this.colorByTier.get(t);if(i!==void 0)return i;const r=this.nextIndex();return this.colorByTier.set(t,r),r}nextIndex(){return++this.index%hF}}function vF(e){if(e.every(Nd))return[];const t=new Map,n=new Map;let i=0;for(const s of e)if(!Nd(s))for(let o=0;o<s.vertices.length;o++){const a=s.vertices[o];if(t.has(a))continue;let l,c;const f=ArrayBuffer.isView(a)?a.constructor:Float64Array;if(ArrayBuffer.isView(a)){l=n.get(a.buffer),l||(l=new Map,n.set(a.buffer,l)),c=`${a.constructor.name}:${a.byteOffset}:${a.byteLength}`;const h=l.get(c);if(h!==void 0){t.set(a,h);continue}}const u=f.BYTES_PER_ELEMENT;i=Math.ceil(i/u)*u;const d={source:a,byteOffset:i,ArrayType:f};t.set(a,d),l&&c!==void 0&&l.set(c,d),i+=a.length*u}const r=new ArrayBuffer(i);for(const s of t.values())if(!s.view){const{source:o,byteOffset:a,ArrayType:l}=s;s.view=new l(r,a,o.length),s.view.set(o)}for(const s of e){if(Nd(s))continue;const o=Array.from(s.vertices,a=>t.get(a).view);s.vertices=o}return[r]}function Nd(e){return e.type===Qn.Point&&e.geometryType===ji.Point}const gy=$(2,20),my=["main","parser","labeling","models"],Gd={};for(let e=0;e<my.length;e++){const t=my[e];Gd[t]={min:1+e*gy,max:(e+1)*gy}}class yF{constructor(t){this.atlasPacker=new dF,this.pointIndexer=new mF,this.innerColors=new Map,this.floorHidingMap=new Map,this.usedModels=new Set,this.dataModels={},this.promotedObjectAttributes={},this.addedBuckets=[],this.labels=[],this.idIndexer=new _T(t),this.workerName=t,this.dataModelsIndex=Gd[t].min,this.buckets={},this.geoJsonData=[],this.reset()}reset(){this.buckets={},this.geoJsonData=[],this.addedBuckets=[],this.floorHidingMap.clear(),this.labels=[],this.usedModels.clear()}getStatsAfterReset(){return{buckets:Object.keys(this.buckets).length,geoJsonData:this.geoJsonData.length,addedBuckets:this.addedBuckets.length,floorHidingMap:this.floorHidingMap.size,labels:this.labels.length,usedModels:this.usedModels.size}}addLabel(t){this.labels.push(t)}addUsedModel(t){this.usedModels.add(t)}setForceInteractivity(t){this.idIndexer.setForceInteractivity(t)}getIndexerStats(){return this.idIndexer.getIndexerStats()}getBucketsMemoryFootprint(){return Object.keys(this.buckets).map(t=>{const n=t,i=this.buckets[n];return i?{[t]:Object.keys(i).map(r=>{const s=i[r];if(s&&typeof s=="object"){const o=Object.keys(s).map(a=>{const l=s[a];if(l&&l.elements&&l.elements.buffer)return{elementsBuffer:l.elements.buffer.byteLength,indices:l.indices.buffer.byteLength}});return{[r]:o}}return{[r]:0}})}:{[t]:[]}})}addPromotedObjectAttributes(t,n){this.promotedObjectAttributes[t]=n}addFeature(t){this.geoJsonData.push(t)}addUsedModelByUrl(t){const n=this.dataModels[t];if(n!==void 0)return n;const{min:i,max:r}=Gd[this.workerName];this.dataModelsIndex=i+(this.dataModelsIndex+1-i)%(r-i);const s=-this.dataModelsIndex;return this.dataModels[t]=s,s}getDataModelsUrls(){const t={};for(const n in this.dataModels)this.usedModels.has(this.dataModels[n])&&(t[n]=this.dataModels[n]);return t}getBucket(t,n,i,r,s=qo){return this.getBucketWithKey(t,n,Rd.generateKey(i),i,r,s)}beginRecording(){this.recording=new Map,this.atlasPacker.beginRecording()}endRecording(){var n;const t=[];for(const[i,r]of(n=this.recording)!=null?n:[]){const{elements:s,indices:o}=i,a=s.stride>>2,l=s.offset-r.vertexStart,c=o.buffer.slice(r.indexStart,o.offset);for(let f=0;f<c.length;f++)c[f]-=r.vertexStart;t.push({styleLayer:r.styleLayer,sink:r.sink,key:i.key,attributes:i.attributes,binder:r.binder,drawMode:r.drawMode,vertices:s.view.slice(r.vertexStart*a,s.offset*a),vertexCount:l,indices:c})}return this.recording=void 0,{writes:t,rastersToLoad:this.atlasPacker.endRecording()}}replayRecording(t,n,i){for(const r of t.writes){const s=n==null?void 0:n(r),o=this.getBucketWithKey(r.styleLayer,r.sink,s?Rd.generateKey(s):r.key,s!=null?s:r.attributes,r.binder,r.drawMode),a=o.elements.offset;o.appendRaw(r.vertices,r.vertexCount,r.indices),i==null||i(o,a)}this.atlasPacker.addRecordedRastersToLoad(t.rastersToLoad),this.isOverloaded()}isOverloaded(){const t=this.addedBuckets;let n=0,i=0;for(;i<t.length;)n=n+t[i++].checkWatermarks();const r=n>0;if(r){for(;i--;)t[i].rollback();this.atlasPacker.rollbackRecording()}else{for(;i--;)t[i].commit();this.atlasPacker.commitRecording()}return t.length=0,r}addFloorHidingMap(t,n){let i=this.floorHidingMap.get(n);i===void 0&&(i=[],this.floorHidingMap.set(n,i)),i.push(t)}getAccumulatedData(){const t=this.buckets,n=[],i=[];for(const d in t){const h=d,g=t[h];for(const y in g){const p=y,v=g[p],A=Oo(h,p)/4;let w=0;for(const M in v)w+=v[M].indices.offset;if(w===0)continue;const S=[],T=new Int32Array(w*A),I=p==="billboard"&&d==="labelLine";let C=0;for(const M in v){const B=v[M],{elements:D,indices:F,attributes:z,meta:N,objectsData:H,extents:K,maxDiag:P}=B,{view:b}=D,{buffer:E}=F;if(D.offset===0)continue;const x=C,L={};for(let O=0;O<F.offset;O++){const R=H?H[O]:null;if(R){const Q=C/A;xF(R,Q,L)}const G=E[O]*A;for(let Q=0;Q<A;Q++)T[C++]=b[G+Q]}I&&N&&Array.isArray(N.guidelines)&&(N.guidelines.forEach(O=>{ArrayBuffer.isView(O)&&O.buffer instanceof ArrayBuffer&&i.push(O.buffer)}),N.guidelinesHash=bI(N.guidelines)),S.push({attributes:z,drawMode:B.drawMode,rangeStart:x*4,rangeEnd:C*4,meta:N,objectsData:Object.keys(L).length>0?L:void 0,extents:new Float32Array(K),maxDiag:P}),B.resetOffsets(),B.resetBuildingsData(),B.resetInstancesExtents(),B.meta=void 0,B.utils=void 0}n.push({symbol:h,sink:p,buffer:T.buffer,generatedObjects:S}),i.push(T.buffer)}}const r=this.idIndexer.getPacked();i.push(r.centerBuffer),i.push(r.instanceIdBuffer),i.push(r.layerIdBuffer),i.push(r.objectClassBuffer),i.push(r.phaseBuffer),i.push(r.styleIdBuffer),i.push(r.sublayerBuffer);const s=this.atlasPacker.getPackedRasters();s!==void 0&&i.push(s.buffer);const o=this.atlasPacker.getRastersToLoad();i.push(o.buffer);const a=this.getDataModelsUrls();this.usedModels=new Set;const l=this.floorHidingMap;this.floorHidingMap=new Map,this.innerColors=new Map;const c=this.labels;this.labels=[],this.workerName!=="main"&&i.push(...vF(c));const f=this.promotedObjectAttributes;this.promotedObjectAttributes={};const u=this.geoJsonData.length?this.geoJsonData:void 0;return this.geoJsonData=[],{data:n,labels:c,floorHidingMap:l,packedRasters:s,rastersToLoad:o,dataModelsUrls:a,identifyIds:r,transferable:i,promotedObjectAttributes:f,debugGeoJsonData:u}}getBucketWithKey(t,n,i,r,s,o){let a=this.buckets[t];a===void 0&&(a={},this.buckets[t]=a);let l=a[n];l===void 0&&(l=a[n]={});let c=l[i];return c||(c=new Rd(t,n,r,s,o,i),l[i]=c),this.addedBuckets.push(c),this.recording&&!this.recording.has(c)&&this.recording.set(c,{styleLayer:t,sink:n,binder:s,drawMode:o,vertexStart:c.elements.offset,indexStart:c.indices.offset}),c}}function xF(e,t,n){const i=e.objectId;n[i]||(n[i]=[]);let r=!1;for(const s of n[i]){const o=s.offset+s.size,a=t+e.size;(s.offset<=t&&o>=t||t<=s.offset&&a>=s.offset)&&(s.offset=Math.min(t,s.offset),s.size=Math.max(o,a)-s.offset,r=!0)}r||n[i].push({offset:t,size:e.size})}const wF={[po.none]:{ambientColorIntensity:new Float32Array([1,1,1,0]),dir1ColorIntensity:new Float32Array([1,1,1,0]),dir1Direction:new Float32Array([0,-1,0]),dir2ColorIntensity:new Float32Array([1,1,1,0]),dir2Direction:new Float32Array([0,-1,0]),shadowLightIndex:-1,shadowRadius:1}},AF=2;class kd{constructor(t,n=!1){this.dataType=t,this.pendingRequests=new Map,this.ignoredStatusCodes=n?[204,404]:[204]}fetch(t,n,i=3,r=1e3){return Fe(this,null,function*(){var o;let s=0;for(;s<=i;)try{const a=yield this.fetchAttempt(t,n);if(!a.error||!k0((o=a.error)==null?void 0:o.status))return a;throw new Error(`Fetching ${t} attempt ${s} failed.`)}catch(a){if(s>=i)return{rejected:!0};yield Kv(Math.pow(2,s)*r),s++}return{rejected:!0}})}destroy(){const t=Array.from(this.pendingRequests.keys());this.abortRequests(t)}abortRequests(t){for(const n of t){const i=this.pendingRequests.get(n);if(i===void 0)return;i.xhr.abort(),i.resolve({rejected:!0}),this.pendingRequests.delete(n)}}fetchAttempt(t,n){return new Promise(i=>{const r=n(t),s=De(t),a=(this.dataType==="json"?G0:Dl)({url:r},(l,c)=>{if(this.pendingRequests.delete(s),l!==void 0){this.ignoredStatusCodes.includes(l.status)||console.error(`Failed to fetch a tile by url "${r}" Error: status "${l.status}", message: ${l.message}`),i({error:l});return}i({data:c})});this.pendingRequests.set(s,{xhr:a,resolve:i})})}}const bF=17,Jl=6;class SF{constructor(){this.name="",this.range="",this.glyphs={}}}class EF{constructor(){this.id=0,this.range=0,this.bitmap=null,this.top=0,this.left=0,this.advance=0,this.x=0,this.y=0,this.width=0,this.height=0,this.texTop=0,this.texLeft=0,this.texRight=0,this.texBottom=0}}class TF{constructor(t,n){this.stacks=t.readFields(PF,[],n)}}function PF(e,t,n){if(e===1){const i=n.readMessage(IF,new SF);t.push(i)}}function IF(e,t,n){switch(e){case 1:t.name=n.readString();break;case 2:t.range=n.readString();break;case 3:{const i=n.readMessage(MF,new EF);t.glyphs[i.id]=i;break}}}function MF(e,t,n){switch(e){case 1:t.id=n.readVarint(),t.range=Nf(t.id);break;case 2:t.bitmap=n.readBytes();break;case 3:t.width=n.readVarint()+Jl;break;case 4:t.height=n.readVarint()+Jl;break;case 5:t.left=n.readSVarint()-Jl/2;break;case 6:t.top=n.readSVarint()+bF+Jl/2;break;case 7:t.advance=n.readVarint();break}}class _F{constructor(t,n,i,r){const s=[];let o=0;for(let a=0;a<t.length;a++){const l=t.charCodeAt(a);let c=n&&n[l];!c&&i&&(c=i[l]),c?(s.push(c),o=o+c.advance):l!==on.bomCharCode&&H2(t[a],l)}this.glyphs=s,this.width=o+on.baseSize*r*(t.length-1)}}function CF(e,t,n,i){const r={lines:[],maxWidth:0},s=e.split(`
`);for(let o=0;o<s.length;o++){const a=new _F(s[o],n,i,t);r.lines.push(a),a.width>r.maxWidth&&(r.maxWidth=a.width)}return r}function FF(e,t,n){for(const i of t)if(!n.has(e,i))return!1;return!0}function LF(e){const t=new TF(new xa(new Uint8Array(e))).stacks[0].glyphs,{width:n,height:i}=DF(t);OF(t,n,i);const r=RF(t,n,i);return{glyphData:t,bitmap:r,width:n,height:i}}function BF(e){const t={};for(const n in e){const i=e[n];t[n]={id:i.id,range:i.range,bitmap:i.bitmap===null||i.bitmap===void 0?i.bitmap:!0,top:i.top,left:i.left,advance:i.advance,x:i.x,y:i.y,width:i.width,height:i.height,texTop:i.texTop,texLeft:i.texLeft,texRight:i.texRight,texBottom:i.texBottom}}return t}function DF(e){const t=[],n=new Ht(512,512,{autoResize:!0}),i=Object.keys(e);for(let r=0;r<i.length;r++){const s=e[Number(i[r])];s.bitmap&&t.push({glyph:s,width:s.width,height:s.height})}n.pack(t,{inPlace:!0}),n.shrink();for(let r=0;r<t.length;r++){const s=t[r].glyph;s.x=t[r].x,s.y=t[r].y}return{width:up(n.w),height:up(n.h)}}function OF(e,t,n){const i=Object.keys(e);for(let r=0;r<i.length;r++){const s=e[Number(i[r])];s.bitmap&&(s.texTop=qt(s.y/n),s.texLeft=qt(s.x/t),s.texBottom=qt((s.y+s.height)/n),s.texRight=qt((s.x+s.width)/t))}}function RF(e,t,n){const i=new Uint8Array(t*n),r=Object.keys(e);for(let s=0;s<r.length;s++){const o=e[Number(r[s])];if(o.bitmap)for(let a=0;a<o.height;a++){const l=t*(o.y+a)+o.x,c=o.width*a;for(let f=0;f<o.width;f++)i[l+f]=o.bitmap[c+f]}}return i.buffer}function zF(e){let t=!1,n;return function(...i){return t||(t=!0,n=e.apply(this,i)),n}}m.processRTLTextIfNeeded=e=>e,m.markAsReady=null,m.rtlAdapterReady=!1;const NF=new Promise(e=>{m.markAsReady=()=>{m.rtlAdapterReady=!0,e()}}),GF=new Set(["ar"]);function vy(e,t){return e==="always-on"||e==="depends-on-language"&&GF.has(t)}function kF(e,t,n){const i=t.workers.labeling;function r(){i.markRtlPluginLoaded().then(()=>{m.markAsReady!==null&&m.markAsReady()})}return vy(e.scenario,n)?fetch(e.url,{integrity:e.hash}).then(s=>s.text()).then(s=>Promise.all([i.loadRtlPlugin(s),Promise.resolve(yy(s))])).catch(s=>{r();const o=new Error,a="[RTL Plugin]: loading failed.";throw o.message=UF(s)?`${a} ${s.message}`:a,o}):(r(),Promise.resolve())}const yy=zF(function(e){new Function(e)(),m.processRTLTextIfNeeded=self.mapglRtlPlugin.processRtl,m.markAsReady&&m.markAsReady()});function UF(e){return typeof e=="object"&&!!e&&"message"in e}const xy=4,wy="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKAAAAIwCAYAAAABNmBHAAAgAElEQVR4Xuy9CbhlV1ktOvbpq09DkiIkUBI6kxASIH0DlAQiIK1wRfSJTx+i4JX7vKIigs8HXpXvqVcvrcC9agQ7IDTSSWgqCQQliDRBJKkkhDSkqVPNqVOnP+8b//rH3P+eZ+199tlznVTlvVrft7+1T7OaueZY42/m37QALKNk2wHg1pITlB17mC+Pp11W3X/LHyT32vhg48/5SOv+PnwpsHA70JoGlueB1iKApeqzvOzn44GatTB76Xzhd7suBR7+WWADgDEAwwCG/L54b/poDLrHuvvm70Z2Avhsc+PVcxscBU8F8C8ADg5+ipIjD/PlGwfgju8B924E5seARUfLsiNmqQW0IjL8+7L2NYD/7COBzfcCm+aB8SVgdAkYIRCXKyDax4EdAanL5PuNPllNvXDlAHwFgP8AcC2AhRIoDXbsYb48dl5WkVFTE3LGDcC9m4CZCWBuFFgeAZaGAYJQQCRqDHT+McJrVb8zwATUXH02MHYfMHEIGFsAxgjApQqACYQORjtd/B7Axt/z79sC0+cMPgjjlwPwVwHcA+DfAHzTxcVgWBroqMN8+cYBeM71wH0TwKExYHYUWCIAHYRLTlkCYgcIBcAgU/n3qy8GRu4HRgnAOWBkERhddPAJhGJDBxkvw7cqimr+zFM/ZLnZF64cgL8BYD+AWwB8x/dlWuWagHiYL984AJ/0RWBy1AE4AizyM1yxYAcTigW55xMbAkxEiwEdkJ/ZCQxPAiOHgBECcKEC4TBZcKkSv+mTieNcNPNC26mLNsj45QD8LQDTAO4GcJt/7iw2bfoG4WG+vAGwm9ExiEg69zpg/wgwPQLMjgALzn4E4aIzoJjQ9g4024uygkj+pyuAoX0VAIfngOH5NgCHMhAm8Sv2y3XDZeBhNIp8OzJE8OsBzAKYBHAXgDt8/4O+MVT0j4f58o0D8Pxrgf3DwMwIMEPQEYRkNwfgsuuDZLskip0No0gWMD/9HGDoADAkAC4Aw/wsAgZAgs2Z0ABI0GU6IVmKv+f28KDnHxkA/G0A8y6G73N9kOCjXnh/Ebb6OvgwX75xAF5wLTA1VIHPADgMLDj4yIA5AAm6aCUnv4oz46eeDwxNAUMzwJAz4BABSNDFTwSfg7DDKHE23MG5PqIY8A1u/dINs9dBdy8AgnGPM2NfUBrsnw7z5RsH4IXXAAcJviFgluAbygBINnSLWOAjGxJ4pgOKDV0v/OSLKp8iGXBovhLBBOCQM2ACoTOhnYrAdItYbCij5JFzRyIAqRccAnDAQUjg6UNQ7hsMXP0cRQAexss3DsCLCECCLwCQzMcPwUi2MwAScAKbfnY/YRLFQ8DHX+IAJAMSfDkAF13kLvleIjhjQQHxUVS3jjgGpKeeNzYVQEjgUS8k+PghONdhIwAP4+XXBYCHKIJbwJyDTgaIAdCBJx3Q2M8tYAHP9m4df/ylQOsQ0JqtRLCx30K1wtLBggScQOgsKBGcWHAJeOwRC0BSM1mQIKRbhh+Bj98JQP6t4U0APEyXXxcAEnxkQAFwoVUxID9kvQg+c1C7vidRbIDkc24B//hTQGumDcCWA5DgMxASdNIFBUI5pCML8v8API5zfEQx4BudgqiczviSnJhQwCP4BMCGl+wO8+U7AJi/W4O4YS6+pmK/2ciADsAOBhTIIiAJnPB7AvNjP+0AnANaYkAHX2JBAc+tYaJXOqBZv24Vc386XW5dtkHGW+4HFAJonpOe+YYQZAShgKjv3PNvPQaxVoI8zJdfFwASfPzMUwS3Kt1v0UFIlos6oDFdAGFcliMAP/ryAEAGNwQRnDOgLbdlIEwrIs6AZ/QgkMMHQF6ZAKQcJAsSYPwIeAIk9wJgoPK1gi7+PwF4GC/fOAAvIQPSs0URTPBJ/Pp3GSEGRHfBCIQ0xowBtUbcAj7ys5X4Jfu1HIAGQrIgQRXEsAFQIORDFhiDY/rMHmrU4QUgR08AkgUjCAW6CD6CkwBsAIQC4GG6fPMA3OXiNzCg2I9gNCMksmAAoemDzoimFwL48M85AKkiuQVMAAp8CYRRDAt8GQiJ67N6GJODAXAHlsGguscA2AJg1IPGYmxOpBxFWkRN9LsATgIwXnNs/v/5z/9XCf8BO3YAtxbc/46/KDt+5+ea1Yku2VUxHz/z0v24FwMGK1gWsK2OUUxHHdCBeRUB6OxHABr4ZICIBd0QWSF+XRdMTAjgCdTrG9cBNwE4F8CpDkICyYLGsuhFt6zs+gISwUen8zEAjgMw4cfx2H6O/90yAFo84Cbg4ID3/9TfLTt+5+ebnRABkODjx0SwPi5ec/FrYpmqSAxM8Dn60CsqAFI6GfhqAMiDE/gokmvEr0C4PgDkBQm40wE8zMFEUDKEVoxIMLl/KS73mE7H9d+vcKHQQcjwW0Yu9nP8m8sAmOIBuWY6wP2/4s0ezjjg8TuvaR6ABJ70vxUApGrm7EbGE+i472BAB+WHfqHS/eoAaEwY2E9+wLSXTqhI7CXgnB6LCoOJ4BiST+hTnG0HcCwAglCx3ARoZEVFXnBPp/O/A/hXACc7CPs9/i1lAOyIB+RDX+P9/+pbQjjjAMfv/PL6AFDs1wFAgs/9fgKfgdE/ZEpuiQlbwAde6QAMBgiRmsSwA9BY0JfjovGRDBMH4TlcXGhcBOc6HkF0gjPhZgchxTLZMAci/04W/B6Ab3t09EPXcPyflgFwRTwgJ2MN9/8bf5qFM67x+B/aW4XQz42FeL0YrRyikztUFw0704mf9kXgxhOAqc3AAsPyRxxQCs/PdXOFY0W1KHy3QIUGtx+6vdnx1vsB+dsTncm2AogglFgVEAlUWrOMB2RyEmMCGQ/Y7/HvKns6tfGAnJQ+r/9b76oJZ1zD8WdyQjYBh8aBhVEHjELouQ8ukQ7VRSCJAALwkr+sALhnGzDD3JAJYJHg9uhoi4bx8ytkWUtvHT/7+Zc4dw1uZ3612fH2dkQf7yxIEEockwkJQn4IQoq8unhAhmPRKKFx0uv4K8ueTs94wD7u//VX9ghn7OP4c+4G7h8HpseB+dF2AKlFLwuAIZ8jD6NPrOhAffmfA9/ZBuzZCkyRWSeqBCWyoYGQ5yQrBpDbum/ME1HoPo0XEkSD2zlfbna8q6+EUJcTCxKEtHL5EQjP6BEPyIgYAZBvYt3xHyx7OqvGA65y/7/9wVXCGVc5/sl7qxD66dEqiYgRzAqhN1A4CBNAAlDyAFI+iZ9/N3DLJuC+jcDUBmCWyUnOrmTYCMIOkNclLg0B8/RsNLg9+UvNjnd1APLmmQpFHyEBROuWACQT8nN+H/GAvY7/VNnT6SsesMf13/CpahGnZzhjj+PPmwX2MYdDIfQexWyBAwEUOQDrRDN/98p3A7dvAO6fAA5sqHJDBEAyoUVGkwEd6HR12XU4kwzfl6fCXTZzjy57vvnR513X7Hj7AyDvggAUi9EyFgiZqNxPQF6345nOWbD1HQ/Y5fpvuLa/2+82/vNHgAPDFQDnhoF5j2C2qBWCI8bw1eRw5CL5l94L3DEOTI4DB8Y9OWmsEu/zBJ3rgsaybqBob/7A4C7jtWcooRrczr+u2fH2D0AOQgAUCxKEP7aGgLy64+m6KdjWFA9Yc/03/Osa4glrjr+AupqHz1sEs0cxG0BC9HIePLoit9eNkVf9L+DuUWByDJgaq4ybGYLPAWgiXmLedUE7dwC7saL7CqfPKXi4NYdaykCD410bAHlDEsNiwZ9wAPYbkJcfz6T2gm3N8YDZ9d/wHxUA+739fPwXPrSKYGb+BuP3jAFDElFH9HIWwbzCIGkBr/or4J4RYO8oMOW6ZVcAuvi1Cgoha04BCwT5gfMKHm7NoRde2+x41w5A3hQZkADk5+cGiAeMx3+/7AENFA8Yrv/G71cAXFM4Yzj+otOAaQLQA0gZxaIIZtMDFTigKJV8H9Iq6aZ59ZXAvSPAvpEKgBTtBODcSCWCZeRYtpzrmLyeGNCAyFl1v+Hei8qeb370Rdc2O97BAMi7EgB/2QG41nhAHU9LuWAbOB7Qr//GPRUA13r7Gv9FZwIMoVcEswEwfDoimEP0shKKtIphaZQAXv1+YM+wA3DEdcvRKkGJADQQEsQuhi1Tjt95vBsh5nx2IO59SsHDrTmUOStNjndwAAqEry0IyCMICkOyiuIBNwBvPFQQT7gBuPjc9oRYAIHyOEL4vIFEYVNaOou5vCGE/tV/A0wOVcnpzI47NOri3QFIBpSeaSDUdYLOSWvYImSGgftpJDa4MWJbAGxivGUA5MAOc0Be6eVLj7/4Mk+hzCOYPYpZDBiNkLh+G/M3yFyv/ltgL3W3YQfgcFUhgRY2PwY+Z7/EhAR1SFyXCOb57r28QfQBsJQBMn5D4y0HYLPje9Cd7RIC0PM3EiMofF4gVCBp1P840ix/gyz56r+vAMjk9Gl375iB4+CzveuZdLkkEPJ8ZEfX/6R73vOjzT5Si9hucLxHAVg4PwJgRwh9CKOXK8YA4ZEqKZXSQWh5P+5AftXfA/uGKvYjCKn72cctbFrZNECka5L5CPwIPtMH3TVz17MLB5gdLgA2Nd6jACycHwLQxFEUSR5ASvARDB0h9AQb9bXIgCGk6lUfAPYTgEPAITKgg1BObk58srTJgG58WMkWMaAbQQT1nc8rHGANAJsc71EAFs4PAagQestgC1lsBJ4BMCSOK6dDUcwqqaFiQr/0QeAAAdjy+jBiQQeeMSBZT3nCPUDIa9z+/MIB1gCwyfEeBWDh/BCAeQSzgkjFfGLBBD5nxQ4DxN0wv3hVxX5TBGDwL5obxvVA5YqYL5BeMLd66YYxJpRB0gK+96LCAdYAsMnxHgVg4fwIgMrhUPKQ2C+Bz0PmBTqBMQehAbDlIjj4F80KJguSVZ0FuXpjoCOgXawLjALhbT9eOMAuAGxqvEcBWDg/l1IE05Ed0ygZnyHdz0VwCqEPIfNyx0QQvvLDFQCp+8nfZk5und8tXwIgWcHSNX0N2CJmnAl3v6RwgNnhl17T7HiPArBwfghAS7mV/hey2JS9FvM3BLpUUi1YwDRMXvkRYJoAlAh2l0dcZ04s6JUTDIjyBcrl4yDc/dLCAdYAsMnxHgVg4fxwKVwJgGEJNmWtxpQMpX9on2eRhVA+O56AjMfnP+e3Xvf3NwG4xIPTleiY55bpGh6UbafNU0l0z0p+5Jh5HqYJ6b51nP6XP8cx12XNHQVgIQB/bFPVg2OC7Q+WgVFWng/FvtWLI06uWh5oguKEcXVS/9sEAF//VGD7t4ETDgJbF4CNi8CGZWBs2fPL/H6Vwp2KEtVk4fJ+v/EIYPN9wKa5qu+IncfPwXHVZe/aOL3EbwS7xv8A1rQvnO0j8PArTgTGZ4BxFv9mIxhOCGsv+0OPYDRghcLfkWkEuq0+G00x4OtfDGz+d2DbHmDLjL8si8AYP/7CGIAiEEMTG92zXqSbH+d9R2aA0XnvO+JjthiIrOVDHHPOkBrzUQAWAPsZp3oPDpa/Xag6EVkLBK+5rAnJC3/nYk/APD704WiEAV8OTHwX2LQH2DgFbJgFNrBhjd8r79deGoEwsllgNBOzy8CdjweG9wBj08AIAci2D6HafmyAk4/Z7SJ72hGYRwFYAMDLTwOGp4FRFgD3HhzqRGQiyeurqOdG6r0Rm8IEZjzRlkiqCWoEgK8Axm4BJu4HJhyAbFhDxmbDGnZO4j0SgLGDkpibgEq66TJw/1nA0F5gdLpq+zDqFfd5LMeWqu5HNST0uJOIllg+qgMWgI+HPv0xwLA3gWHpW2sC441gCECbmKziaGrnUdMO4aHeh6MxAP4SMHI7ML4HGD8AjHvHJGNAgpDgY/ck3stipRemvVhc+uASMPUEYGh/9dIRgGx8Y+MNbR/00uVtH0wEx94j/v0oAxaA8Ed+GBieAYZZg5kADC0QWGOFzGJlcGPzl1BxNLXD8sk4xftwNAbA/wwM3wGMUmxOOQBnHXzetIYvibonmSiuYTNjriVg7glAiwBk0fNZH6+PmX9P6kfNmCXGpftJ7TgKwBIAnln14BAAYxMYm5C6RjCyCoOyr0qkD/c+HI0B8DXA8N3AyCQwesD1VQKH7EcASm1Q+y4CkN9pUKiVF5nLvy+fBbTUd8QBaH1HvNBROiZvfsNnrF4kcvPwpdsBLBeU18Nf7AB23Dp4ecHC8oBgUlJJecLS+7+WOpE3gbE+HKw+yoevCYkMGKqPJrdEKARutaFYRs1fiEZ0wP8CDN8LDO8FRqYq3W10pgKgfYLaYCzootgA6KXaTA90y374TKB1sBozy77xHFZ536utRgAmEaw6g5kUSFZwSXnA330qsOlfgHMPDlZesLA8IOjoLypPWHj/11EnCiVwkz7kAExtsGraYUWdSDX5TmsagL8KDBGA7Bd30JsW0oWivnEOQNP7yGTSBR101AlZSUtGyfgZDkCWY1HnJdcBVe6325hTvelg2CQjZNDygG/2An0j1wKnL6y9vGBheUC8prQ8YeH9X39OVQSc7Mc6fCaKvAeHdCIVf4yMYCynTpX+nb97NJmlSQb8r8DQHm9YOFUZTKOzoXGhs6AxF0HIexcLBvWBuiHN8s2ne98R3qc6L4Vyb2oBVjfm9MIFHbjDCh6kPOBbQoG+oW8CO5bWVl6wsDwgfr20PGHh/X/1iaEIuDcCTIW/1Q4rFv8OnYiW3c+W2iKwUjKbyjQNwL1uuR6sAEgDgq1brXOmV81PxhNB6DUDBSYzQJwFtz623XcktX1Q1VWKaTF/zZhVazBVYA1tX5MazsGvobwe/jQr0Ne6BTh5uf/ygoXlAfG60vKEhff/rSe1i4DnTWDUACY1guFTDqLYdCBvf6DJYSMYATBfOx1kLfj1v1axH10nQ3Sd0GUkBnTfpemtBJgseIKQAHLQcVxa2TnuMW0Aqui5es8xBIegVdVVE8VhzHnLh65WMB9An+X18K6aAn2tO4ETl6vqbKuVFywsDwhevqg8YeH93/Rk70JE90nowxZbIJjvS3WYNSGUwGHJTpPxwwcbBuBrgRYBeKACn7VtpdUu/c0NJxO9BIxcKu4TTODzbkonPLoaL0vyUQRb2y8HsL1ckfWzMeuFi40Qezqi+yiPhyt7FOjr6/gCFwgP7Xb5vssTFt7/nQRg6MGRWmDRoeyTlpgw68GRTwgZgo1gGmXAX6/8dtaylSKY/koyID9BhzML3q1gAos2AcOrZYSoq/pJp1VtODRm9Z3LS/7WjVkvXOzEtOpKyGrlAT+4SoG+VY8vBGCvy/dVnrDw/vee65NBJiAjBIVcAJQjOm+DkCZEeiGAMw6sAwDZsJrAdhFM9rPGhd4904Co5oVuCZPV6kD40Ec6+9W8dBTBsfdc3nkpvnB82fp2RPcs79dHgb51LA9ofsDV6vut5/3PnxcAmLVBiDqgevDaJLkYrpuQxzcNwN8AWgIgRbB8loEBzXDwl4cGiDGft58SCOWGedgjvOJ+bPvgRkiuA+ZjzhnQQOiFNVbloa7l/fos0LdO5QENgEXlCfs8Qbf7HyMA3QVjYihYhLENgjX9y/qwxQmRU/asfd0ZcLU2CHVGyusJQLKfVi98CS12T5f7iECkHpsMkAhCF8+nshWH2I/jXsOYO144GV/9ApAIrS3vt4YCfetQHtAA2G+/4PW4/2PPbzMgmUMi2NoeSCRxIt2/FvuxWURIWCXg357gfTjEDNIHnTRXRCpH5ugKwGl3HpMBXQc0v6WLYVm/5limj04rG762K2uYY9jBkr9+rI03NL5ZbczS/dJ+LQyoga4o77fGAn0NlwdMAOy3vl/T938KAcj121z8Bn+Y9eWQJRz8Y6kNagDh2ey5EvxjxQD8TWdAuneCCO4An1vw5vdzQMmdktwq7pLZQR+dM34+ZumAxvY1Y04uqOAJ6FsExzeto7zfAAX6GiwPaLWR1lrfr8n7f/Rl3QGzmsis+/uO71V9OFgP2gpPhgr7TGRqRUT6dyvr4aIs/pm/2zVUNbBSv6G8e5pEv0Cvec7Po7+bTtjlBRlkvAMBkDeQyvsNWKCvofKACYBrre/X1P0/oWEAnnFD1YdjhtXxR73mX10FfCHHE9pVWcGAI/S0gKsfA2y+twrFZw6Hxf/F0Pk8Ri/kpGSnMuDx5T0iACgQHioo0NdAecBUHW6QdsV2/cL7v/Cyqr5gnc42CCOcfX1VIZ/V8We9IDmTzVXwPDJiXuKXPxtDBma8+lzP4WAgKkPxCUAPE4v5GzEuMX0PYJPLhB6FJsc7MAMmkVxaYC/K9gG+F1++8AQ7Gwbgk78I7GFpXgIwFiRXOwaJZPUbiR0yCUDRk+cHf+YpwMj9HgfI8ClGPyvsSiH0WSKRuYlitLb/zHM/JOSs5C/YIC9cMQDZr/dwxgOW9gtGYUBi0wA8l304vDQvAchilFbpIBQhZ7Ejq6ZQ0/Yhil8y4j89Axie9DAsD6FX9HOK3QtROTFkviN83kG4felIY8DCeLrSeMDSfsEovAECUFsTjHD+tcB+tkFgcXKvBRir7qtFl9owmO4Xy/1G3bAFfPrZHorFNWBFwHjQAFctIghj2kBarw06If/+MM9ZqTN6DgsDojCerjQesLRfMApvoGkAWh8Ob/tgAPSKWCp8ngNQtadjmTdltvNvn3peFYhgQQgh+iUmEaUAUoXM1yRLmWuFLaE9Z+XIAWBhPF1pPGBpv2AU3kDTALzwmqo6qtVh9kJErAudABia38TC5wJgS2xIhAwBn3yhByL4EhzXfRXxYsDTJ4IvrNN2JFMxZcBzVo4cABbG05XGA5b2C0bhDTQNQLZBYH1AVsQSAAU+imI1obHyblnjG/kJk3U8BHz8xVUQAhnQIl5CyNgKAGp5LKSSCoAySh5Jj79vTagcxUaIBeRNe79g9gq+DXig4wGzy+PONfT7RWFA4noAkGXZVAhcBckJQgNgrLiaNb3paIDo1vHHX+oA9LQBi4DxJcOUPJUnTgU2NJUyROs8irGARxQAC+PpCtsFd40H/AEf0gMQkLgeACT41PiGoLOKqyrJq3K/Ya9mNyr5FusN/uPLPIeDa8Bc+w3rtyl4VFHaMZc3i9RWBM9jjzgAFsbTFbYLRmm/YBTeQNMAtD4cBKDXBTQGdAB2MGBo8SCLmEuS1AFVAJ3A/NhPt0PoCcA8bSDG76XI7aySg6JYuGfKwJHFgH0E5B3ueMCe/Y4L+xVHAOZ+9EHcEgQgwbeiEYx6jwTdz4qfu7EhEJqxGqruf/RnHIAEnxgwBM0aC8aUAYWNBRCmoIll4HTqO122QcZbrgMWxtMVtgvuOx6wa7/jwhtoGoDWh4MBJ16WN4lfr8AqI0TVV1O1fa9BbQzovkAy4Ed+NgCQUSxZCFWvCOaOFREXyUwZOPIA2GdA3uGOB6wPaOz+QPv5S+MA3OXiN9aclghW+d3IgupBF2pPqxcxGenDPxfSRh2ASiKKiVP2PaZScvAKoA0VDc6cOlIB2GdA3uGOB1zR77iwX/F6AFB9ONSOQW0frA50sILVcckWJyIDSgwPAVcJgFbYuZ3FJvAlEHbJ3IsgJLGedeBIA+AAAXmHOx6wo99xYb/i9QKg2iAIfDJEJHqj4SExbEty0gkdhB/6P9oZbBZIGiKYVb9GKaN50lRHBLOvhDxh/5EKwDUG5B3ueMB2QGM/grb7/6wHAPNGMAY+GSGUjC52VX2f2CD4+HO0gqkZfegXKgBaHkcWtS0AWii9xG1ImrLlN5XR8L8fmQD05BVrmEENmpYSP9QX+KHiqj2/82+HqqDWwnbBRfGATdzAegGwru2DpRq7Mzq2fpAf0Nq0Rl2wBXzglZ4yUAPAmDSVWDBPHQjLcgTqOZ6zUvdKHh4ruDCerox/Dnu7YqwXAC1NI/QcEQuK6WK/kdgCTGC0PYAP/KIDMBgglq+hIkrOfsaCviLSofcJgJ5AdM7kkSaCj/HqQKVIGvD4swF8bcBjmzjsaQ2H5D/6acBd9wALB4DFWWB5AVherMp4GKIYEOp7+26UF0aSfT/xYuDG7wDjrIpAERytXf2vajj7ueryQXSFl10K/ON3gIWDwCLvjfGB8Z54O+Ee4ve6513uB2R1yzsqC+twbC8HcNVhfAeaBuDP/TvwtS3A/ePAIfYFVlPq2HHTuyulZCTlhbjhETF5yxTQGgPGhoHhIWC4VSXGD3n0tLkMHXHxu+YyB+MlPwDuZs5K6FlsbCzdVO9DuKfkHM8AEkP7B8fOkwDcD+B7np42+JkGOvKdAL4E4K8P0zvQdET0b14D3DgB3D0B7B8HZka9WzrD88N6sFm+YcUjrn7E1ZDvMtF9DBgeAYaHgSGB0PNHCD4BLwLRsByAyX/ij0/dDUxuqlIG5hix7eFhvLcOVUAtyPSydAFmOQNe6EYGV/9ZESiKgIEgtbaD/gHALQC4ovY5r5KwtjOU/XfTAHzzLuCmIeDuMWDvKHBwpMoN0WQzNtAaYSs0K4ZlOSAjGG9kPjCBRwZ0ABKEBJexYAZEAU3A7Oi1BeDym4EDnjQ1TwCGWMW8MXcKks0YOyZNlQOQjcgYIUHllEzYQ0ktm+r6oz8G4F4AXwXwRd8/kO9A0wB8y65KmPxgGJgcqYJTKYpTv2CCzyddQJRDOjKivn+Deh8BF8BnwBtaCUA+YYEyAU8h+c6Az9gNHHRmrgOgmDA3jHQ+iWupCeUAvNSrA9HNwqx+muk9nJVNg/CTfrmbAPwbgK8D+PcHkIibjob5o13A3XypWsAkG1cPA9PDFQDZM1id0i1KxsWfOrKnAFXlifCFFMMRcASigOcs2MGAIfE9iWXplS6On7UbmPaUUTXQrgsVMzcRj5Folg2V5ayUA5BWYKwOxKUafnosWjcJwk+7W5F2EKvlE3xcXaNYfiCYsGkA/smuqug6hcleAnAImPbO6YwRpMgjCAVAm/yQmKTv5hNsAf/i7SyNBSl2a8Qv/4/M1yF+BZSYlNQCnnVrpbC+mToAACAASURBVJcaI7sOSEY2NpaDXLqpR+vE/OVksDgImgGgghHoYJbTWc7oJtFWc65/cg2AYvh2ALsB3AzgVv95nS/f4QdsIkT9T3cBrGtITWZfC5hqtQHInsEGQn3UDDvEDEY/ICf7SxMOrAg8T+c00JGkvHGd2DABUYZIAONzCUDppCFhSukCBsLQrFtZe/IixYQpSyEoJoqnuPWrVRAubQh83HNlZB23z7j1ywmj6CIIqUPxw2Xeu9bx2jx10wz4Z7sqTYZaDD8EIDuoE3hMVEphWg66JIp90k0sBxBcy+iPIIaT1RtEsHS/yIAqw+VSNPWQfe5tlVEk8auXgVa5BUsEJuT5uoliAbE5AGotmIAjCPnR9xDG3TQernYAUupTdBGEFMf83OkApHG+XlvTAPwfuyrgSZOhas3u6cwTsUBVn2gTwyFMi8wjHZAA1M9fYGHDULJD1m8Cpa8fRxDad+l+Ykf/3XNvd11U+qiL39SxXevSsshdDFvgbI1O2AwAtRZMZzTBRuDFjxe1Xg8QEIB8yyj5yYIUxfQIkfkIRnmHCM712JoG4FsdgHHp3ACoMH2G6jM4lWzoQarSvwQ6MSB/vporVaFkh+mCLlpVR8Z+dqDZLoDOpHSiQeAFDkBjPrlgCHgCUaFifg67H/9uYjn4Ai1vpTERTAASBaoQJBAKeNqHlL6mwPDZYAOROag/EYRkPX34MwHIvzW9rQcA+TLpI22G7EcQKlJGsYIJhC6ClUMiXfBTbFUQAej6nPS/OuAl9pOOqIc2BLzg++3VmWgIEUz82cRuCAtLIHQQm0gO52uOAb22sC3JEWgRfPpZf2sQBQIgLydPEIFGwPEj8MlF2bSbsulghLftqsCXq9HGgHysznrGgi5qzTUTFH8FLhAUn3hIJwCN0HLncw37qaF2zoYvuKNivmQIuUNc7GvWt6sHNs26twA6vhyq8NEMAHlyntFrDCcQehyaPTl+FwAbXDcmAKMRThakEk8Q8kPg8SPL0qzLBl+A9QCgR6uZGs3vfHz8TtBZvkgGQrEPBVAUg2Sij50QAOjiVKI3saADJRm7dSLYWfSFDkCem/dhZeMy9pPY5QvSDYQyUJoDIK8qMezh3wY6fSL49PcGgCAA8pScJLIgAUYQEmz8RPA17StvGoBv39W24eREiBoNQSgWNI1HBkdgxJSw1AI+dFIbgOYmkjimQ1r6XXC3rAbCHycAgytohf8vsB/r2KRaRq7zpZ+D37HMX0s3DDcCUGLYaw53MJ4YUODzusqlGCQAOQCejuxA8UULUkxIwAmMAp8Wa3qkN/R9W+sBwOhIEPjk5SLr8HeKFbTQfb77csPIMHGl/4MPbReslPhNe4+MiTpi9AFGV4nI7MfvagNQLh/pfrYnDAS8aJQ42A2w4em2cAyWQUuJVQTGWLs1uL7DG9J1RjhA+jvYk4t3KXeMqijpzrud4At9z3XtP16yGfjKZmCGooYh1tZzvv8xXPFl4PoJYC97k9FlwZWD+Azi/deMZWeP13eQCGEyoERudChIjbb3mJYwH7V0QIKuCwj/gfMj0asn2I0FXRSHXfL/iRkNgLyeVj8ccMY//J1fyxzTAXT2+xoQViKYD/1hDqLxPiYxTgSvQrphphG97tz4Slqafnj7uk1kIQDZrvWTw8B3jwEW+RLxPgSiCERdPwPR7+wCPg/gulFgfruDkOMQkFc5x84e708JAMmCuRNBXi4TIg5CGRzGiBGE/D4E/C2r2vcAYJoify62i0aJSMhB+2IHoNwu0fkcjQ85pu3ack5nIBREqneYFyWLkAXIJHESe00Cyx5QyeL6F/tyEcDcrOW2n7fX8df0mME+/vQ/PQjhoy3gzo3AISYf80MQaQx1peH9wb7v2mrtmCBkIMMejp3jIJD1MsaxaMZ8v5N/67INAsB3BAYU4JL4DSo1J15AFPAEwuQHZJzkKfUAtOHLJSOQRWndBYQvCQA01cfnNopfsaCJaD2baBn79QjSTiOEP1EcawIpkq2kegBTNgHWEpOKF8Uwq2NRFPM4AqCf46/rA2U9/uVDvurB01zvAJpiiwOl3fEeciCGF+Ij11f+QkbSfMPfIzqw57mEFZ9Dl3Ps5HXWAYByHJAJKV7N+s0cCQQhwSlfm4lGZ0KB8C/rABgZUS6ZHITBSEhCowUYAAksF7cStWREyxRwtuPpOlgw+5s9sq6OaIJIIlUgEhA1edoTgHxa9HVw5jibZNF+j/9yGQA/7pbujZ4bwv2+cWB6tFo0NzYnkxFA+cvEAo43VBoEo2e+48EMXEOmD9F6xhCE8RwZEJ80VblKvDlmzwicfqy93/o+8K8TwB2jVSgW138FrJQTXBNlnJgmrjZwanow9CBP/rL9wF0jwAGWDtFyoN9PHutnIHT05mPXz93dMGQAPniJsjiBXiTbxDZFMF9NLUPQxKR5qezz1Y6/YZDH0D6GkdAkYJIvRalAdHAMmPZoYhb6NhDWvEyf/ma737CXN7R1ZC7hUbPgcFgqt/ZZjADnM1xqEVhYBpb4CUk5UsL7jQvj///5buDrLeCOEeD+YQchYwG9VIfyg1NaZszFiCH6DkRGLze5/dgk8IMWcMCjdCiCzR8od1B8OTwvJM8JEShFut1fzMhi+eRJr6LI7hYP2M/xVLwKNoZjUTwRMAQQmYyhWGQxsSADOflZ4kukj7PhZ75bETjBpkAGahMkcrGgwhsXeCyBHBj1wmOBQwvAwqKzoFeRV8ZaerjKYAuirmPY/o9X7q5Cyr7fAvYMAftCPGAEoYlBiVtFwLjtp2U4irj7yOANbi+crHyrfCbTquJV44O0F1FrwQGIMZFqdQDyP/gGSZ8TC0ZRRsOlVzzgasd/u+zpMByLehAfCgMQCDyGZJHFCCgLZ2f8mgI5qauEcVx9e5vACTgCTwEMWr5TdIpWKJb5MvrnoocDswvAPAG4VLGg6UKeqmi4iuDz4er30oX0FP7u5moMvIf7W8B+jwlUNAzFnlZCIhvGFRCeWzrgXSSIBreXTFZSgVLHAp4UHOFuociEEsn2PJwl/XEk0dzfSojeerFg1IOo5BKAveIBex1P67lgUzgWQaJwLAKRH04i14ItgDKEtGsRnWx49b2Vkk9wUefTGrKCF7R0JxZMqxN8cmPAxWcAcxGABKEAKPA5u9lEaAbCmKMI+sDN1X3z+ro24wEZFc0VEE64ABgT180PF9ZdBcDb6JpqcPtPk+1ACbmKjJnllwyuILunEAWjZHkBsrsRUnfD0qEiC5IJfyisgMhzWhcP2O14Ro4WbASgAMQJ48SJwchmBCDFa8qpyBbSP7OvU4PQ0p2W7+LSnSJUFOrI4V7w5IoBTQQTfJ6oTSYk2mQcpGRyH2syGjIF6EM3V/fM++C1CfwUExhCsmzCaQT43lZC3e1hBpEHh36XEqrB7Scmq5dV0XZxmV8WuDFzAF9iwhow9seAGoBcGtKjqAc+1l9rLb/1igesO55ysmCrC8ei6IxRMAKTWNBi6Xw98xNTFUi0jEcmpYgRAPhddpVi9OIEPP5cYD4CcLkCooHPwaW9kV+iwWrQHT8uA1fd3F7DFvgUHUP2k8jTiogAqLoxFpDgbMj9jXSuN7i9dLIdaxzBp5XVBMIMgFEnFAPKT9qPd6A9BIGI7MfPmf4U+40HzI8nWgq2PBxL4FEkjKJixGRRFyQQPzzd1iAUzCAQas1YOmAEoFjwkecDC/PAwhKw6CxIkCXwOdVJLxTobMjBdyIgfvimNvNJ7Evf4jWtdnRYD1YNGVuG93VWuWs4Jf+mlZCCZxwP/cnJ6mXVKk2+tK8lQQVHRTGc64SDAZB3Ey3JcxyACkToJx4wHl+YwqloGDICmYmTFgMQFBET8yyYzyAG/AfWX8mCGQg0BTRoHwt9KVaPE/HQ890AIfgWK+CRAaMRYnVdxHbhdY8Wslw1V93UDsmPIj9GxgiAioRRMIJNvoti+SW/Ikd0gwAU8+XxJcbGITJPDvI6XdCFREFSknTB83xka40H1PGF9dnycCxFwygkK0bASJQSVAbAYeD98xUAe5U3jKIwBosSgNsuABYogl3/IwgFPrOIg1Xc4ZrpAsSrvruykl2ucykapkMMh4CExD5DwJfWAYAxwk4MKPAJgOIjGSEGwuCakRhemw6Yv0UUwRf7L00L9pnsNx6Qx4feY4O8pDEcixOjsoTKKpMYjSFYYjOC8Eq3Wnnr0YYS+0Tmi2HysrPGLqwASNYzBnT2Mz2QD91laxLB0gs12GAh81cf/o/OcHyJ+qj0S/zxnhUZbSyYWaL8+Rq2S29wowiWkJPan4MvgrDDGAlRe7KIywDIgR3meEDWg9HbJgApNTkXo8o0i7oVgxnEgFr8F7jEdnU5GvqfJQKQKyEOPlsNIQvyvupAGHS/Okv4qv9oh+PHxMLk8ggBCRxvAmEN+AiEzz2iQfQBeNmkh4K52hJBKOaNe/FSLobLRXCz43rQnu2yi9oMSMDxs2jo8303ERz1wsCGZECF4kd3DwEYYwJjhoNlQrgIjlYodbBPrwMAZfEmyzcIv27gs6XDzC/IR1DOgA9a6DRz4wZAsZ+LYXvQYsHoD4ziOFklna6YD3+nnU6dZ7bGDAcBUImIAmEUw/zbJ1i/scGNDJiLXmle3RhQ+l/aq57gUQCWzwwBKPeLsZ/LFrGg/ShRXAe64Ajkv30kALAjF8R11Dy3K7KRwJcsUTaqWScARou3w/INVnCH+A36n8RvM3nB5XP4oD6DATBYwGb5ajlOLOh6X8JaBKRG77+7ygGYp1bn+V25/01AzBnwQ1ypanD7KWfA1QDYC3zJIj7KgOUzc9nFbetX/r+O5biwNhyX5uSEDr5o0xsJwLp8/m4A7GaJUv/j3/5+HQFYJ3oFPPkho/hNeqBcMkcB2BAA6XrxmMBkfFAci/m0JpwzXw0TXvXtzrz+PKc/Ml/ugzM9MDqCAbz/keVjjGcQA/YLvjoguo1mRslRI6RwfsiA5nqhL5D6nscF8gfTdfxpS+/hLzvWfzMQCoB1Fq/8b3VWaPIDZqsRV64DALsZHVHs1gEvsqFAeBSApQC8pHK90Oql4UEAyvCwNeGcBXNLOPMLftgZsI75ouUr9ousp2TEyIJ/sU4AzC1e+WIFshyAHPZREVwItrrD3wGAhibTYBhxVpe/xePyrNBuWaoNp3DgFwC81O+RAepK/a5Lfe51jxr7JwA83nPXYgq1asl0yX5N48+f4VEGLATlK1vAo5YB1gBSRmsM+NFE57lcfPD5pPFWCJImtyvGgGfOAacBYO59zFglgHgPefZsXV6/gPXBYeC0RVgyJNOGYuJjPka9eHWgjL9bWzhWk0/n/wPn+k8bgFNmgYcsVflZnBRmIShtJM/m7JGibGBoOIIez9wKPP4AcNpylfbNlGfdI+9NjBjz8JVzppckZuJ+dBw4aQ44drk6j1LIY9JkPD7P4s2lwVEGLHwJnncscNIh4Nh5YMsSsHm5ndOu1BGFThJ8/K6JrZtoslST2+XHA6ftB05ZAE5crgAups5TfaL6EF+UyIif3gAcOwtsXep82eIYY9JkXpMgMp/AeZQBC2b8OduBYw8C2+aALQvARgJwGZhY7swEzbNa88IRvAVO1qkF91J36DNOBE7eD2yfB45fqphLnevzdGeBKBfL8UX5/CZgyyyweRHYsFwxYHzRNK6oetSBMDLjUQAWTPqPngpsnQK2zgKbCMAlYMMSME4ALrcnR6JYQIwsoUnjpDRstOLy7cBJB4CHUGwuAtuW2nUDVH1EFUhycSwWjGD64mZg0xywcaECoI0z5P3X5P6nWlHdgHgUgAUAfOYOYMtBYNMssHEe2LgITBCADkIzSJZXpCOnIg25uPrhgnupO/TyhwLHHwSOmwW2LVSik2pCrDsQskzNIBGIpBdGI+VfNgMb5oENCxX4yPRjPj4xaJ0+WGeEHRXBDUz2Mx4FbDoIbJypADixUAFwzAFI8KUJChMV2SUaAGc1cE/xFJef3FYRti64nkqWDrqqEhbrsm5zvZCdPCd8nHzJOLZuABRz9hTHZwPL7LnLnoNMIY2VyaKcjtZLHOAbNgNPngKe4BacfGF1pnydD+hphQ/8XV5UiEueLGnDN1tWXj/3/4cTwAUzwGPcRcFJiDpPt3FLmf5vjwE2HAQ2zPrEzDv7OQg5OSM+ScYQy5Xbo8465u/ZfLTJ7fKHAdumKxVh8wKwealSE6inEoSy2MWCdbUHIghv3AqMzwHji9VLZuDzD8cXxxWZs5c7apmW0fMBnIHKn5X7d6I5npvRz94O7LgXuGIReJSb+Xl1tzqflybwRwqf9i97BQRWomWJQ7oZVFtJoqDX/b/oGODsvcBTATB9gsfGqmzdjtVz+G+PAyamgYmZCoDjFE2anCVg1CeJwOMnTRB/DmUINVkkgia3y08BtkwDW+YqAFJFMD1VAAw6XG61R31O9/fdrcDYPDDmY0zjc1UjivBuAMx1QdMB+WAYXU8dhEU16dOSkppbcHFSrng8MHwnsGMPcN5ypURHp2xMIa7zDz2z8Gn/kVe0YomO0wEwBYKujL7v/zHA6C3AxfOVh58g5AsZxx4fZM7sf3h6BcDxWWeGBZ+cMEFiwGEHHRnDzun7ONHs/djkRgBunql0VDOSHIDU3cxSD4aEajhFXS4H4S1bgVGN0V8we7E0Fh9jVDG6Obr1LJMRwn+kOCaTEYT0dsfqZHXl/p7PrLi9wIY7gO0H2yAgCAWCWCowKrYE8nMLn/a7PQn9X7zIJPPkCcK+758y7x7guNsB6l98gZjLLYet3Ay5n0sv4R+fCYxPA2MOwLEAQLIDPyP8uBg2cRYmzFweAYilKkn+OC8/Fdh0CNhEA4nGA40kd6FES13WLO8v1qHKAfh9B+DoYjU2Ak/js/8NAIwg7OUb7LCC+WAfB4CpBJoIiTRNRmS1l13kqWh3Adv2A8cdqqp1MB+aIOSxWv6pq5D2kkIAvt8rF7BLJksN/jMqfa7v+7/Ak4B3A6ceqpasKMq5akAmlLWY37t8ZW97PDB2qALg2BxgAFwANEGcnI5JcrDZRPlkaXL4u1KJUAfAjbTQ59x6dSvdLPXAgGYshZWR6JIRaXB/NwFI8C1WwLMXzMeSwLfcXuKrA2G+wrLCDcN/IIg4ERRn0qvyySAQX6mG1XuA4fuAbTOVwktRRr2MLCoQyvEZ/UY/WwjAj3jtFJZkU79g1ghkgEBf98+0Umb/3A2M3lkBl/fOcdMok2EjkZyv8773LAfgHDDKjwNwxEUw9yailpwdxBAEYhBbAuGzG3aKkQEJwAkCkOCjlb7Y6SYyf2UwlAS+vKYnAXjfNmDEX7DEfA5CjUcsnzvbu1nDtUMmCDkRZEEyGdlAk6G6lQTSa6m0MP6HuY73AxNTlcJLZ6WOJYC5/CNxLpHMgdKIKNl69Qvu6/75AjHOiTU87gKOOViJb748BKCWrnK/maTA+58AjM0Ao7PA6Lx/xBAupoYDC9okBRAmPdBZ47lNA/DhwMRsxX7mPgl+SrmK5EaRNRslXFQ9CKB9DkADn79cZtkHFkysJ103eBbqlh97DpmTQTYgk9VNxu+xYbXKU3lhFoJPOgdFGY+lPkgQxokkgF9Xgj4AvfoFs84eX4Ke9x9fIC+tRfDxvvniif358sSir2LCj5wNjBKAc8CIi2AxxLCzIAGY9L7AhGIKgpATw4l8wToB0JjPrfTkp+SLQbHrOqm5jNyajS6VCMIpApDAWwQ4LrGgXqzIfnq5cv0vN0ZXHTInME5GBNLb1DGdOYQsI7AfGKFjlgqve8wJwG4T+fuFAFytXzCLb+VgWnH/fIGYfc46Hs7iHC8ZkPcdXx4VfVXJw8+cA4wIgM6AHSLKWZCTESfLfg7WsIyRF3ckiRQ+HACXkwHptyP4KHrpJvKVGnOhRF9eBF9wE0mUEogz2wC+WGI/vVxiQQIxAs9+rmHA6E1YFYB8DJwQMZl0OrLZ++i7sfT8zroYHLS9df4RACWKxSZvLXzG/fQLZqk2gqn2/vUCUQ9UZaM9wDaPeSPrC4A5C1KV+NITKwCS/SiCR/jRBDlLmP7nHynsxno1IPwJSyRpbiMADXzuPDYfZfBTEoAmcuVQdiaW0zwXwQsCYDYmMaDA1wG8TBSvaoR0G77EcGSET6hjOvVApfRPAUN0zjr45JzVcSqiTxD+VeGzXku/4Nr7JwDJOkxFIwt6j6+RqUrlkO4bXzp1gCAAv04AzgLDDsBhKugLFUvQUhTwCEKbnKCw14HwJ9cDgGQ9WegRgDI8XEcVEDvAl7lVlglAgi+I4CR+Zf1mLGgMmDFhBGFfDCicRJFERviSABjLS7FC0MFKMU+07wOPE0kGvaoQgGvtF9z1/iODkwn3VWoEXxres5ib9xx1wZufBAwLgAQexbAD0JiQwJOuJBA68/H3Zhk6+3CifqqwWNMKN8wjKgbk6gWJgC+FMaBb5vJVmsUbV2vCqo3cRWZcCIACoax53+ulkqNd7iqOcU1WcC9cxEm5kQBUdZ+sTnSL/jEtTWngi21jhJNJBivZBukXvOL+yYBkcOqxKjJ4AGgxzMrBVwdAMmHrZOAYF2l6y/mwV6xD17zmWo6MbRyeWtOHwxJ91IIhr6rqZS70DPPLXDVUrfBwzHKr1EUp6/h0T/6L/GcCqslt4IhoTcwdAqDSs7I60WQH6R329pHuFyuXDJmEjuOSbdB+wSvuP5bGUjmsA5XoUvcvBXKKAQnApUdXwah0b8jXR2YzJTsC0ZHB33FL+2yiX3h/1YeD1fFZGT81g/H6yqkVa9YEpqMhTADle8erHA6t7Mh6j4ZBXdBGjFyO4CSIm9wGBiBvgqxwIAJQlXIyEJLyI/i0SkAG/FbhaEr6BXfcv+5dLKhCg4z1C1HEBJ8+BODQGZXfk/quAZC6ketAZEQCTWAU8PIJt0fgwHzZvVWNaKqi7JLOmtDWFy42g1FxH/XfqGkII0C+a0tnDkfsGxQjn3VPsk7tXmuy+Xp0JhtoJosAaFcUAJUYKiYJxcqHqKAH9rPlG2cMrmCUbMX9guMLpGTcCMKDlZGhMK8IPnPIn1X5PA2AwegwEEYmDGBMjOI5whGQP3NPBT7VJlRNaKvF4t2IWHbDErtDlSk1p4lJ7/zd246tglGZryIfrFhQ7pU8WCAX0ZENG+57U14Z4YrCeLrSxXdev6TfLwrbxT7znMrfKQXfHLQCnyvmRIv0Q3430ezMmL98P393G3wqz6am1NYzzoGn+svqRmTAU2citctqAX/2EI8F9ACEmLHXLZGoFxtSl2xyK2bAYwrj6Xr12+1noL/jUTCD9vvFrn6u0v1/nvGkaoVBAQi0eummMAuXQHMWJAA7gCixG8U0gFfcXdlBKk4Z6zELgAJfZEKrxpC1xOIl/+Sk7jkcdYlSco90y9+gK6vJrRiADD0piad7RuFo3udNCgft94vCdrGXn+tujgV3QAcHLcFnroelivHkchEL8ue0uQ74S3eubAITS3IQhKkMRjBMokgWG3L//2z3VSnP4VDgQWxUEEUxAZFHL0eR3HDfm3IRbDHkBfF0zy4EIKNhSvr9goGEBdvTz/MIYQLQdVsTwRTFDj5jQmdArRDYJQNDSs961R3tPhx5NXoVgoxleHnarjohgLec3D2HI492yQNvIwvqO9fJm9zKGbAwnu6FhaP5pFuMg/b7tTbpBdvTz68cz/zI8azVj8iAHTqgmFHXDUB89R2dtaC7tUGw4kDOgFb0R2wYRDGZ8g9O8aU4XwPOczhiwGlMjqqLWiFYGu570wADFsbTvaxg8nkow7E8nM/atfKzln6/1mS4YHv6BQ4+Z0BbqHcd0NwwYbVD3+1yWhXJxPBrbq8AqE/XApSqAxiBV2MZ/54DMOZwKE00rnDUWcR5KiV/brjtSAMALIyn+/mCyeehjIYp6fdrvVELth8RAClyHXxmhPi6r1m8FM0ucgk8+y4RHC1kAK/5XgW+2hZYofafWcPq1B5AqDqEYsQ3nepR2gqhV2yiol1COkD0C+aOaoGx4aL7DQCwMJ7uVwomn4fm7VrX2u/XAlELth+5sHPtN+l/Ap6sX2dCsZ/phZkIJgv9l++1wbcq+2WFv2NXIjNKAPzuw7MUAV8DTuynFIEsQy83RgTAhiv+NgBABaQOGE/3mwWTLwAqHnaQfr9GnwUbARgDNBUlkpzQboyYCyYDYdILdf0l4NduW9kGoa4geNdazLElKoA3Prx7DofiETtC6XvE7hGEzJlpcis3Qgrj6d5UOJoYDcMglrX2+y0NPtl5UZUjkfx/Hqbecoe0OZzdF1gHQrln9Bhee4s3f3Zxm4MvAk9VSFdUIw0i+Q2PaBtISiBSSFgCYMjMW00MP7pwvvLDmwFgQTzdHxcOSGvBg/b7ZRZByWYAlOERluKM3Ra9CKWc0q73dTBhMFT4ZwIw9l5Lrpes+HjeBiGCUOKXeuBvPcKTiEIOR0f+RhDBMYi0Lhea4GTaa5NbOQAVDzhgPB1La5RssV3rIP1+7yy5OAADoAchEHBkFbKfGRpiweAPtMs5IFNokyOGk/7rAYC9OhBFwNXVY1at5tftCBHaWVS2AJdEcEinrDNC+Lumiyc1B8AB4+muLARAXTDCWvr93lR4/Z0Xt6ODFQkj8WtumEwHTKDLQejAfN3uds/dfjoQdatGLxb8jQBAYz6/boxiFgAVudzNIc2/s3xLk1szAORoB4yn+2DhaATAGJCtbpkCYq9+v4V+aBgAQ4i66XtaC85YkDog/zdZvzUgfN1N7a633Xqv6fe9msDIHfNaB6Ay2JRE1AHAEDIfI5nzZCLeN4Nbm9yaA+CA8XSsul6yqV0rJ2WQfr+splCyCYBR/HJyKX4phs0PKBZ0lqOYTpvniAiUAmAd+HKjo1cvDjHgr+3wPJQsVCymUZrPMuRsRBDG4AQCsunyJtFGHwAAIABJREFUcc0BUJlxQoH62q8ST8cggpKNAFRGwCD9fkuvbwAkyGgJE3C+Nz1P1q9/T3F1EZBxvZh50s6AEYC5yyUHXt5/Q8zI5/KrAmAIkkipkyGPYwXz1aRT8v5ZO6jJrRyAvKOvNXlLazsXs9bo/ztc29Pohgotp5J49Rcj/pzfIwGS//3OM4CNd1dpntQpFUmjEH4LYIgnyn/OLjL8FeDGhwJbNgFjI8DIEDA8BAy1PFK7FSKf43cNKrvHx+8C/vmxwMgmYHgEaA35J0StpvvzL/nP8RbLAfhyT207TChgDRiu/ZL9DsfWNABvYzbhCDBKoBAk/pEobGWTqp819hzQ1/0k0PoaMDEJbJjxVZFgDad0SaUO5LksWVj+XScDmw5UEUDJ6U4d0nVbC91S3ovfVHp5al64cgC+k7mZAP768KCA0WD3A/ieLz090CDceVmlAuhBljLgrfcAw6PAyDAwPFwBkCAbItM4a/FiNtERjBl76W9ffD2AbwJDdwFj+6syImRXrd5Y2FjIYcnzWPLEqnsfC0zsr6qBMQmfIDR/pyJ6xMhKyMrSDiKD2xja6TADTt0/AGAs1KcAUCFrOLF6tbtiRVFavT/wuMCa7MfVTlH098YBeBcwNAIMEYAUlS4uBULOmK3LCnwOPANlEIOSoF9+C4DvVoWXhvdWZVOYqWgi3vOXDUQhgieB0EElViMYJ08HxqeqnG8D4IIDkAzo51DKQQJvBKUmKACzbM4+5hUivwrgiwC4LzvjmgCh6nBcgiMTcv9Abo0D8E6g5eCjfpUA6AxoQIzgi8ALmWwC4z//DxcPPwBak8DQFDB8yJPpPZHeGCyC0KN5DFCByfh9/+OAsekKgEzCTwD047X0SCPM1IYQjCv2E/MJoGVwUUQoPboq0MdqkWVn7RtDDMahB4g+P6qhXFpjVtkDtRGA2nKjos7IyOyHFUbIrXe0FXsTuzIYfNb4O2M3ATGIYQOmPn6hG6gi3eUkQQAeAIYOAUOzALMVh2pAlESqGFBAXAYOMQVjxll03iO/yYKRAT0FQXkwZkjp1pz51LO2XAT3KtD3AIAwj4Wg05kfiuUHYlsXAJLVnP0INLM0OYFx78AzcRySeTsw2AJueI+Dj2Fne4EWKz5MA0MzDkCCkAByUWqsJzarEanzj2zXwjEGFHuGY+pYsMojzZL1G9EBexXou339IRBrC3lJGmNDuSHX+w7WC4Cm6wWxm8DngLTImgC8pBcGBuTXf/1fXnyTugnFwxTQOgi0CECyIFlsvvJfEnh0mhsYI/s5uxFYi1xZof7oOqSAawwYjRGBzYGXbtWXaCIrlvHUagX6SP/ruMVYCEbEqECXAMjfree2HgA0ESur1/0vtnNwGSsG0RsZME20/+/XWH6Mugk/yngPAGy5GDYALjiIHIgRUIrsZjM7Ax+BSx1S4pfffQVIep8dL7dMDsTGjJB+CvQxTHmdtrw4l0CovFruC2NOe975egDQsCXRK/eK634JhBK90q2C7I1i+Gt0jxF40k1cPJAB7UP2m3MGJAAFQrGei9iUTH9yBUDTHfU3B5+BOIKQ43BWtNtPcWIOzEZE8FoK9K0DCGNxLi3FqaKA9gTgeoFwPQAoI0OulWT11oEwiFz7cwbErzNxWtEYBB+VY76Vh4DWrH8IOoGQ7Ocg1CqMRLPltmxvs1/SHaP4dcAJePYyyUCRIzrTB8tE8FoL9DUMwl61kQQ87Rmy2PS2rgB0a1ci18RudEJH57OsY02y/+83/sZdBKr4FXQTApBvprGgQCg9UEAM+h9F6ugJDkC3gJPBEvRGrYoYCBX9IxEcS5K4i6cZAHIw8oXQ4mLBb35YH5d7OekadtTV1UZSjaEIPH4nQzYNwgjAHNwDuWGYpZc7lzPfX1cQur5oBorfzDf+zi0yVTuSkuxBI2Q+PhQDIUEnMLo1TBCZLufGw/ixbQa0KB8CTODjPohdY78IQmfDjmW7Yo/doAX6GqIiAtDHaYswSmeMubV81kp11L6hy2PdAcgblfslOKC1IiKRmyRxZgV/8++DS8BFrxXi5Hd/U6MeSKdqEsEKhpBRsgRMbAtuG4KU/+9ry5brzP/lPVMv1EPOQegharrVcgZUhVHFxNPcp9VFtlOWkL437C0WABWypFRGsV0sb5Hn2zYBwvUGoKl10v1knDgo0y7XA8Pfv0UACnjaK33Co9gJQAOe64FkNvtZAHQdjz9v2Nz2GSa3jYej2W3KGuZ9ixGdIVSoKT13B2s5AHkGheST6qn0erHv5AIgAAU+LVfw/wq3CEAV7clBKDDGZG9/5oVXx/oyYARczcqH5GyH8eFplTawFvAtrtXLGpNrQDGbejupB3omlIHQGc/ErzOcGSRs8zrhAbbuL1Tco/JfbLlNwHOmi2kIcs3owbdwNpYtynDQhsFcgvuG9/YapGFvYX22zZcAU0/GwA2LJ/4AmGF9mwEbBu98Y3cMF+uAGQCj2HVp3BbPuo3IlqxAy5wHAq4OfARmEBXGfNIBa0BIsG0ecwC67merHgRpZLwocrWaovuTxew/V0txJQ2DWeae3WAGbdhb2DB4+wRw7w5g8Qpv88liyGtoWHzMi4C9fAEHbBi8kwUKu2xNAdBxaGBLbJdZux1LwAGECYAEm6wyfpelJrEgFnRDxESwgyUxIUsVMwjVy5AYO0bG89Auu1/5BF38KqjBHlUAYXsteNCGwTeWNuwtk4JMkrlzGNizA1hm69g1Nix+zDOBW0aBeRZZGqBh8M4emfWNADDT+zqMjQyESdQFHfDbZECCLRgdHeCTe8CBaKJY1rDnBRCIAuGW4TYAZeFG8ZuMkGiQ1IEwGCJtHZBmy1obBsvVMnDD3jIAerti3LEBOMjGcOpa3WfD4ic9t6oveDtLfw7QMHjnH6wPAybW6yaG4+8D4HIQfvtDIVtLejpBFsVvUI7NIBHw3DUjRzL3rDVtsYPOkAScuX3coNDynT2VYJCkn+PjqvUD8hVbS8NgjphGxcANe8sAGNoVY/824BCBtIaGxRe8pLKZdpMkTvXiJ2toGHzSNHDPScAyq3er4qPyGaNc7JCRXWLT2TjwGmCOeQashq6+qSpZmp8vojQpheF58ncdZVjLnjWPHr4VWKTKxrHGUqq97qXu3jp0wPy+eEC/DYNZsZAO6IEb9pY9lNCuGPcNV830ZmkM9dmw+OKfbdcXvJMPdY0Ng0/7GnDXKcDMccBS7MwdKz8KCAKQIgY0MWGCtr4TOHAasMwOkTqf6unyuLykfd254nkb7qsw/iVg7jhgmSX31Vpd9yRHeLx+zRhjEGRbB6wDYT8NdymyubzDzCCGfpMJWfSRYfr9HP/aMgBm7YoxNQHMbQHm+ID6aFh8yS93tAvGQb7da2gYfPoXgbtPAqaPA+a3AEubgGU1RM6B060fgkRoCzj+TcD+04CFE4BldZdRc4/YxlxgjJMewSiwN1zWfsOngdljq3EmY08vm5i/7j5yIMqpvupKyGoNg9lngYosl9wY/0dZdrMzYl8Ne8sAWNOu2MA3zw/F2CoNiy99XbvftrcLriz6PhsGn3U9cM9xMODObQYWCMANwPJ49UliuW6SaqqBn/gGYP8pwPyJwNIxwDK76ahDeN6uXYCuYyABkEza4LbpY5WEWdSLxjF26/dQB0SJ6r4ByAN6NQxmkWcqrnQ00x1DEDJFjR8CcNWGvWVPp6ZdMQ6OVOCb3wAscPJ6NCy+7PerkP5Q3tBY1PrT9tEw+JwbgPu2AlNbgVkCcCOwtAFYcgAuiwWlM/XqDjMEbP9t4MB2YO54YJFMo/5gHIcALV1TRZ17FXOhPtvgtvkqf9H4kvHDlyKK4l6VzvVSBF22uwjOb7pbw+CfcwBSkyeFEHAUx/yw9JTyEbo27C17Ol3aFWNuAlgIn9QxO2tYfNlbK6MvaxeMRYquvL9rTcPgJ30TuH8LcHAzMOugX3QALo21WXBZLEHwRF1OgHS2eOgbgIPHA7PHAezNu7QFWFZ7JnXJ5rnqxHEulvlzwyVNN3+wern5Yovl7SXLGwvn4riLWO4fgMRJXcPd/+pmOymELEhRzBxJAo9gVL4kwVnbsLccgHEpWi3epocCAMeBRU5eTcPiy/6qtl0wpvhA+2gYfO7NwOQm4OBGYGaDs+5ExYDGgqP+ccAkINaVpB8GTv4d4OBxwNw2YGFrxYCmV0YxLNYheCXau7EhV3ga3Lb8g4+R45uoGLADgHWqhsBXA8K1AZADyRvuvtkBSArh+i9DsQhCOtf0UUgW/7aiYW/Z0+nRrhizoxXwFhyAi5y4rGHxU66qAFhT3rDSIVdpGHzencDejcDBDcDsBDBP1uX1CMJRwFiQIBzxieL3KIY1YW5MPOxNwLRb8gs0aghAss1GZ1O+SFHsdRPt0i/PLHu++dFb/x4mXfhcbWxhfCtYMFr/uWvKxfDaAcg7ipPCvFOVpuo3HrCjYW/ZA+rRrti6TS6MVQ+L4NPH2nx698GnXF0BsKa8Iab4dFZpGHz+JLBvApieqAA4J8CPOQuOBBAOV0CUYbIskRkAecrvAdNbXc/aDCxSpyT4CEIyTgRgneiLIp3nP6fs+a4A4N8B8/48CUC+ZGJA29fpuLmxJW+5h5kNFg2jiWHSi0r0Uv4pCoZsxw8DUfnhd4Vk0XGdGvaWPaBV2hVjdjgA0BlpkQ/K9bmn/HOVqtClvKEBqlfD4AtmgP3jDsBxB6DA7tdbcvYzJvQJkii2n4NOeMpbgJktbYPGACiF3wFoEx1ZMNe/4jnPLXu+KwD4t/5SO/iMBcXuesHylyACMBPDgzGg7opM8mEHIGdwrfGA1rC37AH10a64Yr4APvvOSdwEPOVbKxu+K2pdKRTmdI3dqkPPVgbSTBGAY8AsATjWniBdx0QxJylOFCcr6HBiw1P/CDgU3EgEIMW52M8YkLolQRddIN1AyKWiBretf9MJQN6HsaCPxe4rvgDdHOcOxDIAcmDFDXvLnk4f7Yqt63gEIB/Yoj+4p9xaAbBHeUPM8qF2aRh84QQwNQYcGgdmx4C50WqCFngNsgSvQ+Dxu4MuiawhwIAXVk1O+e/A7CZgThY1dcno1nHL2oDIyZULpBsAFTBZ9pjT0QQgn2V6ufRicS8QRgbs5ZYpEsENDejBfpoLrwAOjgIzZMBRZ0AHoUC+SOA56xJwNlEyTFw5FxBPeWvlzpnbANCdQ1eSGTRybMuydgMggVBsKmtYoC6Mt8znZxsZMLzAxoAOvsh+ydDqtXx4FIDl8L/omQ7A0QqA82S/ERdTI22mNfaTuBIIxR4BhKe+y61punQC+MytI/Zz/c9EuvyBeetLAfGZ5WOMZ9j2/gqABB1fMLsHAVBqhfTcyH5d9MByEdzs+B50Z7voGZX+NzNSsd8cwUcG5ASRKYbdHRNYwhhDIHRgGmO0gFP+HJh15jOXjnyKblVT5Cbfoq+yJOszF8P8+VnNPlICkMAzds/YLxlYznrJwIpO6egTPMqA5ZNDAB6iCCYAyYBcBqTRQ0e4630SxZyQJQIvMJ8mSeLrYe+p/GzGfnTpEIBy6US/out+K1wg+brs88rHmDOgAVCMnrEfxxMte1Mt6j7u9zzKgIXzczEBOJIB0BnCJoqgIfDEhM58SWzJEPGJe9hfVH42un/Mfxl9bgSiBySIBWnAJBDGEDAB8QWFA8wO3/a+wH4+rg4RLPYLul8tCI8CsJmJMQAOuwFC9qMI9g9Z0CxhZz65K0wfFBPqu7PEyVdWAOTHVlTcpxhXHZLz1w0ZA6EDLhkCskRf0sw4dRYC0PQ/vVSRAYPo7QCdj7GqVOSMeBSAzUzMxZcDMwLgcKX/zbv45SQlHXDIgagJc+bjZBqAWhUoH/Y+B2D0J7rFa6LYDRmzomsAaOeKqxEvbWacHQB08JkRIteSXiSBLYJOLB+X4xrzAzY7vgfd2S4RAKkDDgPzNEAIxMASSWF38WsgkuXLyXTRSRCe/DduSZMBMwe6ObTd8JBj24Aot07uDObPP9XsIzUGFPs5+JJ/M6oT4buxHv9X7BeY8KgOWDg/Z58GTC9Xq5FxTXOw9c3Cm6k5fPcjgbHbgAlvVG2tH1T3Oavoq6BlniZ+12n5u/2sDbOvasqoFg8x2Lnbcd1GdhSAhXN+7qMrAC4sA8sORJ6yHwD28z+Ft4fdv8UyqUDrDmCEBcpZ39kLS6aq9l4D2rLb/KYsFTPWdfbvh86vQu2s1K/K+zIjTsXIVQ9a59Egs4Y6sZfIA/EcSp/jEXv8BWcAhxaA+SVgSQAkGAMICcwVlNLlqTc9Gbv/HAA7MrL4+f1VlXwrUq7SvCoyGcrrWpGhuur2fNGYwM8YT67hT3s1LaZvqn5MLM0bzmHMmIFSgdFNj/mIBct63NhFZwEzDsBFgpDPeanNgATfCtGsX9TIKwNrg9tuVkhlng7TI/YArX1VkXKrEe1l2SynN1RCsFJsqnQv3UIMxhwIRjU5AGN9QUteVz3BUAvahuNgjC3HxLAND7nBp/cgONXF5wCz8xUDGgCjKPbvevlzcKUHH2ag6cnYzepYBB9Zi2FxDJdjoXJv1WDFiLJ6MKqKZUzoQFTfj2HmwTKcTpVWvcxHKm6kKgoORAEvVclPD6NdzLXpMT8IYNPcLV7yJGB2AVhYrAC4SNA5AxKM9ryDPE5fs6eeVKWGZ2M3S3MQfEyJUKV8L1ZpJXpVJ9pLilmlAxWkVJHKwIhjjD9TtVXVm1HdOy/pJiaMFRWM+bo0rWl4yM1N7oPhTJecC8wRgAttBjQWdBBGESwgSiV0Pb9DRgu0TY19N+M1mRKh8niqFx3rRDsLqjgl9yaGXT80vcL1wnE252PAZCzAHQCoiqoW3yYWFIt664fUpKaREr1NPakH6XkuOQ+YDwy4FMSwgU8GSRSz0UJx3Vx/5vFNbrs/EiLRY+v4ACITww6iJEodQKwBIyBRv9vwhKzUW6z66TUGEwhDS3ezqusAyNxnJn8xa1KRPSFts9YfFB/QDZcAm78CnDBT5U8rCqjfc3yh8Gn/hGd/MsKf1+QzYJ4891Jye13iy1cAE9cDJ+6FpYrEkidxDN3OtXR+FwBGMezoMmxJLOumAuD4J4rxJrfdH/XCoLGFVKiUbw+LAPQqWWaMMLrd6/+JycSIm85w9lOpt1j1MwAwFTiqAWEUxeYH5ENn/jInUVHeMXQ/f/jRePvCa4DhTwLHfBc4frGqqaNJzLPw6iZxV+HTplFGvZrXZT45N39+HW3TujlZv8D6fp8HRq8Dts9XIOR5YtakgBgdrrrt5Qsq8Ssd0BhQ4HMwmVitAWHAY/LbLDQNQDaTVJ8Q6W4qVB51OOqDZDPVB3TLOBepW5jmqaLbec3jGgBGMSxvvemDYkQ9GoKF1ShUCSKCqBeQrvmfVZPC1keBjXcCmw911tTJ8q5XgOLaQgA+x/OdWA2EGZ98gbjleTHdQHQN+2iwls3nK3/Zhj3VeQhovYzdxmArSwQgDRA3QiSCJUrTnjfl4KozRCSCCeYmt90EoJJbVCk/1+FiCwFZxLk4dRfLFia6x8LbYkD9v9cXtLG6+O4AYQRfrgPygVIcqyhTXcWFOJH8fh3rz7EKwnUArq8mcGwK2MCC1i7WY7Zenh56feHT/jE3yliE4TZncd636gPFCKWavGhcRx2J+cvs9MlSw0Ty3cCm+c7n0G0MExdW4BMIbTXE9UCynvyCCX+Ovm4gbByA/xisVgJPpXrzLj4EoRJjJIZrWHArS9iprK+KcefgiyB0XVKGjOmCmW9xhRVMUSyRFnNeFGEdI2q+/HFXclkp9WsAbgTG9wGj08CI64WxRk/OTDcUAvBHXSLQxcVCDMQSWbzv+1e7WVbz+k5w2tJtsbcCYV6WJY7hmAsDA7r1Sz3OgOgoM+KTOJbcjSI5yGIaNE1uuwlAAU/MF+tF5/0sIghVLdVdM2S0bSzHx2Mi+FTxXf8X925NC4BycK8QwfmgVX1LlcFiykEMcL2BndJJ7aQfijKfxLGDwAhByM7aC5U4qwPzNwufNnNuOH4VZaCPlPo2AahqFqoPVFc14ga2m+WEEL0cAz9kdPrOmMu8r1o/rTsXz7f9oswFs+jO6LAqkvC3Ggg5Fg6mwW03CUI6X12h8lyfcz3QHqr3DIl64DbqaQKc9mI87QXACD6vpJqY0EVxz2CEyCI5eMSGX2e7VtI5J4yTRyZhscrvt1nQuivOAaNLlYESwcySgiVbr37Bfd0/u31yEgg2FVaiPCeVOguqAfGov0iR0R9JABJ0bnwk9nMxw+fOh55EbgRhzozrBUA1polN9CLwok5HEEUQBjFMQB7D+j656PW+IrJ8O/bBCo4sGFdGejqiyYCx3mKe9/JtTiBvmI5OFiTisg9LtJFF7gZGDrUbHKs79+hyu5hSaUvh1foFr3r/6vZJCiXgCDwVVFJ7MVmRLsrGltuFCc68yFdACMDAflwR4QM3HPoKgIExt4gz42SuaQb8hBOE2oZmlu+KFlKR3QSssMJxDPWbbjpfLoJrxG8CYT8MKGZSVTCxYFTIb84nkCxCIPLDiby30gXFghaF4c2ReR466Uu2fvoFr3r/fKAEFxvpqMcd9yonIrkuK5LLV7MVCM+/uDJCyIC2J8a0z1iwqyESgMl15Sa33QKgmtPEBnp11mwuXgO70Ud4DHWzfgDYC3zBEOk7HlA6XKyHQzb8HgGoCSQLqsxorIy1Bxie7Wx0rFaf+wr9Xv32C+56/7HbJ5VHtRYT+GJrsehHcya57PyKAQk6+vBkBZPpjPEExlwU59awg3C24W6KBsC6tqHR+MidyVG3i3rdAnAsH2T093XT+zLr197MTA80h3SfsZP2UqpCrPQ46oF317VrpeiKXTJ9MhMLkgGdCacKG/mupV9w1/vnwyGgCDCKWzJe3lqsyzLWZWe6/kc/oKzgKH4jC7oolhdC4jiuzM0WPo+cPQ2AsX1obFCTO5Jzn566PwbReiwnfTWjI4KvDoh1juh+aT+WKSYD3i8Aql2rJk+VsVQly5kkddv2FvHT61icqO7Fr71/IkLNXOi0FQjV0046oBy6wZ922Q95ICqDEaL4XWw3COcf9Mw73DFB9AqE6wZAAS8XuzGQIDKf+oVkqxt00ttAc+YT0PJ9qRFSB8xoye5Xu1ZVeCSgCLbYLVNswoncHxoeLwCzBGjBNki/4BX3z9lXgUCyIIGmhova83cRgO5Te9yLgP3MfmsBS8xs8/U67ePQOqy9umBUruDchqo8sHSd3PMfT5ifo+ack8eFHI6QEcnT5GvdOnVdXof+ptJ+BVPWceiaRHA8Us/nkACo8mzqlqmWrbFDppT5A5UIZm7CPA2Vgm3QfsEd909kKIqB1qJAKCBG8ZstZz3xHOAAiwmpDIdng1maZQAkZzsHZ537YfQrwNyxoQ+HakrnS0h1mUA1C96TdJTmORyhC3oeqdwROi+GDhkFI6bYNrcNDEDeAkXwQizPRpmnIs3OdqZPSaRFUcbchHlgie6agq2kX7Dd/+d8lUJVXuUzk8ERmS+2vfd4uvN2VOV5rSwb0y3JhgIh9wJeN3YMQCIgR78Q+nDEVYBYZUrUpbXFnM7COSdf7N4IPvtDnT2BY/h8Chh10MXQeYGS+7GGjaQiABpuNIFiECnzdWJMIUHcazLptC7YivsF8/7FgLFMqpiQL5TuNbKfA/DC46rqqAbAwIKWK+timRUBEiNGsOQsyQm+Gpjd4n046hbT84KPuYjOmHHyp92gcgDS2OoIuVIeh/xyUkaVwyEWdLrewHE3uBUDcKIwnq40HpDXL+n3CzbaKdguel5VnFJl2awaghLQBTzteZ0cjLq2A2n0M6EPh2pC57Wg41poLzZsAZNso0Hw6eVR/J8bF9YjWGmVCpGKwQLBRCcrbiSxNLgVAxCF8XSl8YDHHFPW7xeFBRwv/rGqOKUBkODzqgdWPYAM53vTASMQu4Bx9J+69OHIF+N71F1O1gUB+AsBfFqKC+4Wi4BWX+CYgOTAU36wdMVNVKka3MoBWBhPxyiuko3xkSX9fvGMkqsDlzzHC1N6SQ4DoINOe7KelWWTheziObeKCdARApD1AdVnRH048gKUAmAEYi6Oh4DJV4VoGDWqjq4XLbO5o1jBoimEPhPJmwu9FvnTLgdgYTwd2wyXbMyRKen3i2eXXB245FlVYUpVxUpGiLtmGBlrTEhVUwV8dEkVKAq3MHJ1uzRbRx+OOgDWFX6MsXJU/36lJoEoA2AKvw8+uwTEDIBbStdOs8ddDsDCeDom7ZdszBIs6fcL9ror2C75US9IxJJsEsHdGFBil4yYuUwknofJgF4XcEUfjrz+X7fKo4EJJ//PkMORO6FrVjQMeL5kJhZMMXzLwNZCt1nzDFgYT8cQwpLt4hDON0i/X7ys5OrAJVe0S/ISgFY7j9ZvnQ7I3+lyqpYaL98CWp/N+nDkZdhi6bW8An1kP3fRTLKVWlwF6RZCH2L4zDDR0k1IqeTNb2OQSYNbOQMWxtMxeqtkY6I+ny9VEz6btfb7xc+XXB249AoXv85+tIBVgJJ6n4lf6oV+mfjdDJNMH0wAVFX90GMk1f5TxlS3Fggh92DyN0IORy5665KIfCktsl+K3VsGtpVOWOMiuDCerlSnjQ2rB+n3C+pIBdulz8wqonrNPLKgwKaC5B3s53qhXVq6oDNg6sOhqvqhEr3V2VNLBjmnSSNdrOLJ1zkAu6VPRjFcFz4fXDJ8i45hG94Gt3IGjOFYA8TTlQZ/qGH1oP1+8ZtlT1MAtHK8mQg25zOZUSCLIliWcbw8wfW5Ln04ssqnHX04euiCk6/3de66MPpuAQVZAEFkw2MKFw6a1wEL4+lSBvmAOMhD8vkOkFX77feLNw14YT/ssmc4A6oOdHBEkwXlgjH2k4Nal6wB4fIuX9LzZjAmorNeHMo5Tc0OewHwDTUh9HXxfGJsYkAbAAAgAElEQVS/uvCpoAcew6zBBrdyBlQwwoDxdLZWXLDFkHyF8xGE/fb7xR8XXByAAVC1oB18HQYIT+8uGfP75SCUs1o64he8v4j6cIQ+IqkPhxrBCHjdjBH6AblQkAeY1ondukSiELmsUPpjbyp7XuvDgAXxdNZVvWCLIfmKg6Bbhrjup98v3lVwcQLw8gqA5v9zC9jErutltg8gMxDWWMBaMVkmANWFyEV6R0uH2I1IzW7ypbkQOTP5f2ch9KsFkwp0kQlDAOmxzHpscGuGAQvi6VD4RgmAg/b7xZVlT5MATNXwqQc6KGwf2U2uGV2uzg3D4ua7fDnPwZcKgIdq9GaIBPZb0YdD7hgyIFWMXiH0eQ5vXS5HcMkc++9lz2t9GLAgns7KxxZsCkgdtN8vWD+vYDMAUpcja7lOR9eLVcIP4tcuob/3AOHCdW02VTX62ApB4Mv1v24gnPy9HiH03fJ366KYHYTHsgBBg1s5AxbG0+HLZaOp65i+ln6/YM5EwdYBwGj1cmUkE7+8THLNdAHhwrUOXtcrO/pwhF4cct2oN68BMDCfmsJM/n6PEPoYPp8bH3kCkbtjji2tJJA962YAWBBPZ0WBCrbYsFoOf9pDAiENk179fkuvf9nTXewKcBSjsn7ldonWbgQpx+26otaLIwAlfi2QQSJY3Yjy5i9dmsFM/oEDMM/Z7Uf0RiYUA7J+ToNbOQC3e0WBBm9qLad6HICG1ZK1XB5PoxnuOOIcxSXe/Of8xHV/P+FpwN47gKUpYHmuSve0pKZgCKSq5wqniWE1WZz/xouBm74KTMwBI17lVBXwtWSs+8/vL45Ff3vhpcAnvwos8d48DZX3M2hx9XIAnu0IIO0chu35AOgLL0yuG/jOmwbg028G/mNz1YWdETbm4I5BrFlov+EtD2wIo7l+Atg8D2xY7iw3V5diEqO54mnj6XdMAYcU+6gon7A3NSO2qFjlyZYDkAX6uD5Iam44YaUfVNDNxaJcLIPXcGGpfi6PnZdVD1wPspQBX/wl4OaNwN6Jqg+xwrxslcVFuYJblehkcYYZGPS3L20BxueBcS8nwg5H5kZkx6TQSbXFZcCQKadx5Cz5mPurAFxrRaa17pAR2PFC+ElSHKQ/0QjQcgCyGyM9v3SnsDBRJgL6msWCf6IfWeUJac8UFlpY8500DcCfvgb43hiwZwyYVhd2D/VSrKGAmIDnBkiafEcN9cprHgKMzgNjS1V7rRjRlceyrqif6KAkMgXIM+6tAnDl+zSL36O9+U8p9jGHQo285/2XA/AnXeNnKAorDXH/AILwbSvLEz6Ql2+cAf/3XcCdw8DkKHBwpOpFbE2wadzIdyh3jjNQirYWEwYq+/zJwMh8pf+xKNSwM6DZMmzNRRbM2K+2Ii6TlFrAWfd5V3i/F7IgT2LBF5LbIdkqxLPWvtzlAGQ3RpU3Y7AiixMxLOUB2t7pKQ8M0qCTnp8HkojJgNqaMEJesQv4AR3Iw8DB4QqAs+6SWRiqgJgY0HVDAdBA4Ba4xN7ndlSFAAjAYX4IPO5dBDMAdS2i+Jx7XTf1eEdTDfgAQnR34p/wQkRmjNAoByDT/ugFphXAmjAEn8qaPQAgZCs0lSckCNmVigEbFMsPBBE3DcBX7gLuawH7hoAD7EM8DMw48AhATrjtQwiXoqkTEwWd7LOneXNCbz6Tiq/TInb2M8ZzIFrTQbGiy92oGz7pXl/7jvdAJnb2470IbB3T77Sai+hyAP5voTqW6sKwFAc/TAdc5+3dvcsTrvPVYSK4SQb8xV3+6IaAqSHg0FDVh3iOIFTIFxtit9orL5Z/LD1Q4s+B8OnHVuXwhhdd5DoLGsgCCJ04q66X/Ju/vSaeAxDPvbdtmdtKDV90gVEPIl/xySkviOhmAEjrlzSkwj40SlQZYZ39I+8JBMx8mZryhOsKwqYB+KpdVSDFvhYwPVR9BD7uyX4SwRS59nNI+bRck/DzJ05v12M0nY8fAk8iWL5BB5qASPGRCi8EVjzv3mqpkC9ACrrwhKukB67GhpqRRowQMqCiYbj8oOoHeUWpdYIBAUj8c8WjrjyhNIJ1unzjDPjqXdUjJAAP8TMEzLYq9uOHICQALe/EwWe+QgddAqCzzD8+vgIgg0qp+5nYjaDzCgjmnCYone0klqP4JSgvvK+6LoFPoFMlkPGh+0rPWta4RHTNJJQz4M8EAGoNTPVU8opS64CC9zoAWTFChcq7lCdch6s3L4J/2QFIEBKA1P9mHIBmhPh3Ai354RyAAmWsR/PRs6vOR8Z8FMPS97yxtIlYgVB/I7jC0rIKSfLXF1EEB+BFFjQ3jCLA49OWsRTTEPzvzQEwry7VrZ5KwzAQAPssT9jw1dcHgCrORQCS/bgn+1HsCYQSveaHkzvGv1scgU/6R55Y1YIxhvOm1EZekQWl8wVDxJgwc88QiJc6AKX/meHDawX9z16M/Em7bO8Q08GBP/jEkAEVjMBoAFWXUjRA3KtNwOBXW3EkAZhrALktpC6lKtTV4OU7RHB+3kHWgv/zrnYZl2kCkF4uF8MGQGc+MqEYUCA0n1tkwxbw4ScHAHr71Q7W4++c8czwcBAmHVB/c7Bcek9b3FuwbdD/kjGWgzJjQ3thGmVA3jhfOyU+RxB6FamOFp8NrhsTgLy8Cpzm5QlVptAU+6CiNgXCaIQ0BcDYV8b0P4pi30vfIxD5+w72C9aliegW8MHzqrmh/meuFhYi0pKbs6D9fsh/n1XFMrYMbPgUByCZz6J+uEknDA9AornWFRb01WZEsACoHhOqyC7wdetT0QAK2KqOb5MCUvPyhLE0oQxzqaYNXL5xBvyVXe12vByLADjXAvgxBvSPGFGMIjCmJbEW8HfntxtQmxT0cmxp9UPAdKAZ1upA6EB7qgDo6oCUxXRtPVSpAwJpnUhuxAqWCCYK1MBExZljY5S8SYr+pxAFAuBayhNG26jw8usCQLX0SAAkwwcAEngyQizaXoziIli+Oe7/9kJvNk1LmBMe9ECO3XRB7aPeF0EYHNVPdT8gj016YBcWtBfBVYJuz7mF7VgGY/pO8f5WdQ1/7U67nIKNS7j0wIbDPFZsyNHHY7od/xdlEHj8CcC3TgCWHgGAPSxiSdt4312u/8SPAl8/Dlh4pDeZW2PD4J1c9+uyDaIDkgEJQKnTfG/N8nUAmu5HUnMW5ARbPfEuIHy/ACjRK7FL5pOR4RaxgTHofKl8r/S1ZWBnAGDKefbn3AFIPRPXB7sFiVQimKVgGdl5ooNwLQ1/1U+DQGSXQ9r5Evy1q9rZbP1lGQDZsPpzI8APHgXgod7qUx11YtBbFzC+/C+BL7SAWwhgdoLkONSLqy5oLogYft3ZI1F7EAC+phsAnekokhP4HIzml/PvthQWmPB9LJ7jxkcSr14jWj4/0wFlgJD5eoDw6fe4DzAYPHokWhHJZ3TFSkn4h7YOSOBwEtiMTv1aY0uktFYTmI2/43EMQmCuAJmUE0gmVD8EFdPpdnxhVhqzDr8F4NMtYM9Jfg98EVTeNu9Q2OFZBX7vr9vtgm/lcezczZ61ZNN8DCvilYCdPXqNDQpAlfGTKm0M6AA0PTAyoMSx64cRfPQHXsniOTI+fEWDFGp+Qb9BeySRBV2kpl0QxxGAlHDmkI56X6z+EP7UDYSdRgh/IouwIZ36lHabBE0GJ0r10Rgb/xA/tt/j/6aMAf+7R4CxzuBXWRGULwBfIrY6UNfpvLae7n0I+LO/reoLMqiVMbW38oUhkNkQIzZO7tIweGePcmWlAFTjAYHPVGwXxWoLYblEDkLuTT8MDPhXLJ4jALpaJB+ggU6xfgJknT7IKXIQXh4Y0FZCog+wxiUTwSkXUbSMV1rB/A31OXWuFpPUda/mRHKi1e6U+hA7Zq7l+A+UAfDtHg/LrptkQpZ727cRWOL9542Pa3rOvuOqagUltgtmJM08j4/PILbIDKz6w5PAHsbraTnMGdZWIwIzxIfeK0rn578J3LAVuH8CODRahV/FFQ/1IumIvXP1QudNfyNT8oVqcHviPcBd48A0g2RDuoDqHdb2SalZAdG9dnfDkAE0gXnH5ijWCDbKCq5/MRiV0QD8HgHQ63jG0hdsLGxA3x9Bw1Asli7hO3BwApgng/Gjvq01IHrXJ7q3Cz7E++YziF2rs1ZLZ+8H9jJsSoECWXj6igmR87aLgfbGq4GvbgLu2gjsHwdmCEIPSI1h+SkCRjpfUC3iNWcpoRrcnrYbuGsUOMBo7QBCxSTG/igxVcBIVGPWM1h1JYQPnyKNExGZMDIJ9b66eEBGxPDY1Y5nv+GCjfGAxD+DDpiawphABWZPjwNzNLAEIH4XCH0M7/5c93bBfI8Yk2cgVAdvdT10ifDkBWC/r9lGH51NhIsnsWHOfPmEUKT94WeAG8eAO8aAfWPAwVEHISNQlKQUglJjJExqC+H6Nq93kOpUg9szbwLuHa66QzFWkaFieXxi6hgVHOMCYGRuJ+5V4jYJIDKI9KlsAvFDq8QDrnb8NWVPh9EwdFkQ79TlSMIsN0Mi5s9MoOGno4U6f3YAvefL7Y7rvdoFLxOANSA8f7xSgWmd0kCQbmZ6mTLEnJ0UqWLhUkxlrBn6n3wWuGkYuGukCsufGq2iojnRFpafsU7MDxErJuZhYCsJosHtWTcBe1oeq+hxigJgXBrMmTBPnJKLrr+VED54ibHYvZos8sO+DNcrHrDX8YVVyglAKud0LtMjFPtNMz6QLDY7VomLJd671AEH4Xu+3g7nWq28ISvX58/hguOBg8vtFQvV/hEzxfqOevuTfpjri8vAWz8L3NYCfjBc6ZYHmBcitnFd06pxyb8W4gPlgonBqffTtdTg9pybqiVNBssyUsdUD7eGO9amnf3sXtxQipl7Wg/sD4A8AwHIyZMYky50Tp/xgN2OL8y051qw2hXzwRCEdT2nmck1RxHG+w5jeO9NFQBpR6ldMIMXlFWgVndqF2dVFsJzuOgRwMElB6DcI6rznemD0RnbwQiSRS3g7Z+tVIl7PC9kahiYZm6IizuLigliT/VoUog+p8P9l3wJ7qGEanB77k3VczroUToWLCsABud4ypaLCUoxf9i/9w9ADiICULrQRWuIB6w7nuZrwaZwLBGwClSqSyz3AhHbaRGEFGOmC44D72UVgjW2C2Z4lIF4ArjodODQcqUGqAxfcpG4mJVuVqcL5tbs2z/veV0tYK/nhTAqesYNHdO5PCJZos+WuzxHJIViuXFyJxupNLg976ZK2lizUKodilGUgzyGhokF8yw5Mf+qRkjdjfuDtwkkm7DTkNaBaQ2ox1q3eMD8+B6O3H6em8Kx1Ccx9ptWl9iYIUAAWrI3I3nHgPdOtsO5eOuxXXBdj0V1vOL/so3Cxef60tlSpYwveKf0pAu6ohfdJ8k4CUqgvr5jV6VGTBKALeCAh+VbZLTnh5gu6D44A6H8cVlkNK95O1WkBrfn31R5HSy+JCwPplAxRegE/2T+AloGncNmbQyogUQx/KwB4gHj8YWNTwRAOW0FIIIndoqNkTAxz/bd09XDGLBdMM6/pLKi5whAX60gCK2ujxzEAqGL2pQ1Jis5AJEAFHvTujYAKjRf+SEugm1d2COQLU/DAwQ44caEw8AtZzSIPgAvuKkdrWMM6M7xCMBoiBn4YpCE2NCfxWAA5MEuwvCCEICwlnhAHV+YORfDsWJGgPpMKwg1b9QpFnzHbD2BK2JGul9s8KkYW17vLALQRTCBpzXZpS4gtCXXMAkduuAy8E7PijPWprXJ5CR38ygw1fJDohh2BlRAgq2OeN7uTWc1D0AFNtmL54ESBsCaJcLkDajxj5ZXRiCIGA0waDwgjy8sk5+HY+X9ppUbJSCp6TnFCMXwny1WAFQ8rUAc2wUrRL6mXTAefWnFfnz3FpbagQKLAqAzoZjAKkkpXkNO5GCEvOMLFXOnnC4xIKOjnQGNdWSM+GqHQGd7JSsxUf+JzQLwhTdV4je1nQvr1MkPGtlf9yP2Dy+gAqZ6rQytfvdHSDxgLwBF8AmAYjHWluEDiKGMiqOVvtejXTBOuRSYJwDJAARgZAGWL9Nk+IM3SzgTydE4eec1nZHbtDaNAf1Dpd/SMx2END6kD0oXtFhBXmcY+OY6AFChnKnzl7NfdMR3qCAae2B+VVMYXASvDs3/X/zHJZcB84vuiqABEo0QPnhnwqQLyRURmZBPytnwHde0M1vN2lR6picoKULaxHDIEdHkW2iWg4/7b5zb7DSQAVd0/griV2JYojfpwRGEYsGBrOBmx/OgP5sAKANkcbFzNWTRnX/GSGImMYH/LYlk+gGvdT+bW+SWH+Ig1GqL5QeTtR2EYj5LVHfjw/ZDwL8yJ6TB7UU3VVoTjTYxYDK+Ivv7dzNAZIxpZSiU8jjKgIWTcykZkBawDBBnQdMr5QeTKI5iWCB09AmEb7+ucnOQ/aTPWn6wuzyS4u+R0Ob6CUGqJpIDA97AdqINbgRgBJ69CG4Jp6q/ckjXqB/RKla4WpkO2ODgHoynigA0JiLwaNiEt95YQKJ4FRC+7brKzRH9jZbN6iJYuSHm9I5iOAOhHNJfZkh+gxsBKPbLu3+JgaWDdojhMO5kkDWSlNTg4B6MpyIAjf3IggJgMD4MCARjFMU9QCgAykhSKnUCYHB9JB0wy5aTRUxmup4h+Q1uAmDs+hpXgFLnB6ULONOn5xACNJqxghsc3IPxVBGAiQG9aLeilWUJW1FvVXEN0TKp1C6At19TMSCBpz1dHtT/JH7N9yaxp6QkF73KBxYIr10nAMproB44qQGTj6sjUrtOFPtLeFQHLES9AdDFrq1E6M13MaxVCTNAXNFThIylLcor40zxtgDAPKuVwDMrOKw+SBTbtR2MND7sZwC7Qvm4wqHa4T/uIrhb+7n0EgbQdTijoyg+agWXT8llDsAFWr/B8qP1K7bT0pvtVwHhW6+t2C/m8svvZlawi2CKe37nhFtapkDnILRqBQA+v04AjMyn79EIkXO/DnzyCBwVweX4wxs9B4rRZgyPVFqykgDd+5JSpBU5r0vHyHz+jsc3ub0KABsZMCyQgeExKyFPVIz3lmcM6OfPAGCADYPE67Jfs6h7G0o+xvi7oyK4cLZfOgpsXwC2Lq9MwuuVERonKn4nSJrcXnQKcM7dwMMXgYcsVxkSebJgzOWPqdB1ad2f3gpsnwK2LXWeR9m3danUIV1lBSCPArBwtp+7DThuBti6UDWDmWA/DvXk8LRptfPtNUlihYZTOPCi04GH3wFsnwGOW6iAs5n3GeJJ+KLoE+9VDClQ8R6vOQHYegDYwuY3S6H/iJ8jb11ck0q9Qhoc9QMWgPBZJwFbpoFN88DGRWBiqQIgWyJY3lPozaGJ1KTEPh36zpTkJrcXPRE44S7g+Cng2DlgyyKwaclfFoIwvCwx9Zn3Q1DmIPx/2/sSaMuusszvjfXq1ZRUElJkKsBEGQyYhJCBSkUqAW1tsBdpuxEVaBzowXZqe1g90G2LotjQdmMjKqtBxQERdAWUAkUlZNBGkQRNyIAEMAkxpFKpqjfUG3t9//m/c/+737njPq9uVeqcte66b7jnnn32/s6///3v//++Tz0dmD0KzC4DM6vAFpd/0L3Gh6yTDgnvLwKzAWDGiH/ThcC2OWDrErB1pRgQisIQhAa+AED+HEEY6uNLyrRnZLSl6tSbrgLOeBQ44yiw8ziwfaV4UGbdegmA5QMTLFlqsfn7XecDW+eAmePAltXiXnkuZSBkRcm4UGXtU2uo3xsAZgz6y54JzMwDWzkgBOAqMMVBCSAUObh8QuN/CiTgcWAuyWhL1amvvBbY+VgxbW477paa7gIBqCnUrbUBiQuhAKDUot13IbBlDtiyBEyvtO5VDxvvVfxW/JkWNFrCeK8NAGsY7BsvKQC4hQCkJNaKy2LRIsg6SJ3IQSe1onKKC2CsOYMeN+0Dtj0ObDsGbFsEZmWp5S74g2Ir2uA22BScAJGA+dJFwPQ8ML0ETAUAkgDTPq9zdK/+sMWpPF19NxYwA4g3PtsHxAE4SQC6FdSgmGWRRIJLZJll8EGKjHiX1jwaN10HzD4BbD0GzC4WrsKMW2pNobZoCu6CLCDfCTqzgg6sr+wFphaAKQfgZHKvpRSYg7HN5XCL2AbAZwPrZGaj6ippXhgn0kqmU1woxnHedg5AATuWHig2FE1uVRwoxoX+Wcbg89S3AqCKPONcCi8oPtVP+9++G3j+oSK2xRBFDElUxbTS+3nvc4FpDsjxllXQoJg8FgdCQoGJJTTicLcQ6vPL6wbg9cDM4cJv27oAzFA5ky9/UOSvmg8oP86n0dICBn25JwjARWDSAUgBHN6vfdbv10AbARh8X91vDM2ss+NvAECKPVLCsHoyUgRqrlbnRwB933OBc+4DXrIC0IEmiLnE75di8HsyAcjzWUVGUi6uICMpVwwJVMXdeOk3XAxc+Hng+vV2esAYw+sWoP31r3eLcLwQBeQUrEHh4Jo2h4vDmJPuAyMLGAeEn7uqbgB+I7DlSWBGCwe31Gb9aL20kGDb/EGRxY6WTz8f2wtM8l4pgL1SgM8esHCvsuylME4nn9cfQLtldg6TZ0kUKorAfij23vAPCmqp3fcCl60XFINid1PlZrf41/dnApB6wSQjutUfIDJR8CGIQOwWEH7DywpKrWc8CFzqRLHkVYrB2jS2FQH5vkuBycXCAlIUUAAkCM2iRBA6+ARCe7DjYmQduLYTleiQ/XTTS4DpI+6nLhZW2nzVCEBaMLd+soIGqjD1ampdugiYWCpeBKA9bBJC9ActAk8LES26SqsftInLZ44dQif4Igdhym5WLrPDyuYH/7HTCNwDnPko8LXrBccjQaioe6BiKad3+QY/MGTH6rS3OBvCnQDuAIyqhiDkQ9RX+29yE3on8IwjxQPI8zkTiApGU3oVkD/4fGDieAuAdMw5MFQjEgg1DYsUku+a3uI0TGBfV7PotwHwaOEmbHEATvuDIutni6UAQoFRIFRYhfe/dhEw7tbe9Of0Si1g8HkrwRcevDajz07gIJ7n05rYyWIpb4ya/7vv8PRdFpj/LXDmkQLAnA4jCCOlTBRN/rFMAJKgkkVHpGUjySSBSFeg7/azqk8EgbSEq8UDRACLKDXSyaQ7Br//DcA4LSCtwnKhTEkQcmAIQhtM+Uaajl0uS9NatITXWzpzfcdNB4DpY+6nBgDaCtanYLN6fCj4u1ay0QIqtML/EYC61wSA9tAJeP6eWsAoDysFpg1eB0HIQRCIIkVeCqQf/05P3WCB+UPA+CPAzvmCaFWDKEuYcl1yMN+Y2dckqGTeHPEvvWDSNhOAfbefX0A6rS8CUw8X9066bFIfdqMHJID++DJgLACQumyc3gyAEYRRKFCLD1eu5ODLF6QvXedx0w3A1BwwxdAJLTXjd8seQnGrZ9bPFxLyA7WIKON63tYtCQBN/sv9QPm6BkLp0vl9t/m6ietR6fbyBA4gnXtORwRRpNnTtPpW6gWLH83lKqcOFTEnDiKtoHwy8RNFhrefyeztbnrBfbWfgttsP+kIyO32ELD1cHHvInrlvWs6TsnB7qAUlg/suFtAWkE55zYQ0QpqcALoNCXTEt7A3KoaDwGQfqoAOEUBa7fUbKctltwCajVbxvSiyvoasM0BaBKwwdKb9fN7NfcqBWGiSWykWXER0umeacUEonQgCKRfIgDFjya5yq8Wfsfs8dYgiuMxgpAg/vnMzu6mF0z6Zj5APdvPQec0TEosnvQosGOhaLuIYvnwEYSithE52F1XFAA0p5yigD4otCqygFKnpHUpLYP0OcKURYv6Mj4MNR433QhM0gL6QongawOg+6rl9CswKoSkEIxPyTsuAPigCYBmAXVfYcVf+n0SRYw6dP1YwNgHsgSajiJP429RrpWOM6cxDiJB6NINM4w7LbUGMQUwB/M9mZ3dSy+YVG0EoBiDBST5ddZ+PkCsAiIlQZDa3LVatJ0WXG2PbL98AB+4omB3oP/HgTUhmGgBfRqWf2TTrUSjExDSP/qWzQDgfAFAWyzR8rkFtDAKX75jo6nUguZxZ8NByHbvvqBQ36T1swcsBaBAGGRg40Ir+rt9WUDhQ5ZAU7Es2e9LLzglqHRxNkbeuW+oQRRls5jaMjnK0a9ecNf2R4LAwO829kQB3LTtEYQPUwzQAWgW0AGo8AQH0ljp/V17pm0KRcEifGuNOnocO1rACQbKPXhs8TtNwVr5uh+n6Zf3wDgu29g2FdMtOc8B6PdpFj08ZFrplw+ZA5FTvAQQ0/BT36FPDkRqBT9Jag7xYlQItY0f88j78sZzCcKPZlrAQfSCK9uvB4h577SCotUiEJ8opq8IQFl/PUBPEoBLxbRE62LSqG4dFB8r5bHcOtiOQSqT5T7RKzYDgJx+BUCCTxZQCwhaQc9oKcEnEBKknj5FsJ1LAPo9xoWWPWDy+6IIoqbeaO0VA+zHB0zxIQDKkn1GgtXiRxMIAx0Vn0Db+lkuFjLRCt5WEwD71Qvu2H5OfekD5FaciQay/GIbFgBXriwAyGmJADR1ck3DwTE3TQ4B0LetzBJErTYAr2BBSI3HTS8tLKBZPo/fWQDZp197Z3scjGb5BDp/L3+njMweB6B83Gj9wj3atOsPWin9WgXCFlVO/3ctf4iD8XkBkH5USlAZlNPZAQqARr5vxu1yjmH0givbX0UQKI63o0Wun/xHuR8E4VnPK5JQLd4VNttTBvK2uoiKOUf/f+GjwMNBh0NMV6J0c0NpcRv7mrYv3kh8/uHxYp+bVpwLp3R7sts2YzouSq3KGa+q7+x7Co4nazAerRKsVlV1QitF59dyyFZaYY0HMu9mWL3gtvZXMbymBIFMZ1ov2h0B+LTLisxgW+Eq5uU92iZ72ud9vvR+4JFp4NjkRh2ONi0OB1/UBCkvEYRhfuNs4OmhhiPKnFQlx6aAjMnSXJUAACAASURBVPjmz1w41nnwO4cCIBvBwZgTAOUHRq3gyDExD4zRGVYEnpm5LqmQc0M5esFt7acFl0SlHiBxuTkYxxdaihUC4QVXFu5FCUD5QtJl85sjGA0ziQxqeu/fem+hw0F2fLLQGxFlYMRvo7v1WmIVtpt1DFkXvOR7LwJ2HSkyoZmEypoVVe8p7b6qEMnidGG/Vl/L2aPOIwuA1pAIQE3DAmFa4j9f7CPaFpCHKujr5xzZesGdHqAqKz5X+FLRAl58le+jui+kTBALMcgZ73CDBkpN2/7+bfcWOhwUyCEAjQTcAVhKdjkPc2RajewKyu/n1//qJcA2uhBMRGXQOcn9U6JIOjXHQqSYOsVoQp1HNgAvz8yny80H5PVz9H6RqVd849WtXQ/zA0Ow2ayGLJ474L0G79vvbulwkJi8BGCg4S01SKqofoNvSIC+5zkhFUupV8rUTpJN06KpaBkFQm5M1HlkA3AyM5/u9Zl38zrk6f0iU6/4hmscgK5ISUtCTowyDqb7UxwsqFJW3fo/vbuIBJEZ1YRgyHwQKNi0KEl1OKTCZJdxtPDn//v8ooaDaVgqFyiTD2IKfcjZS4Fo+7g+HXOPv84jG4DIzKfLzQf8KVfI/FNKrQ6h94tfz+vOA9cGAAbrpylY2SDlVTTt+uCnV3/V3a7DQQAysJAwobZJgUXi78Qayhd812WeiOAZzEyUiAkHMeu5BF5FwZQAWLPwknkLQy9CrPMy8+lIHZFzvN3T+YbV+8X7c64OHHix74V6zIxB+RJ0wQ+UU992tYoFy3fcXcTDxQkoPsCUhFIczKVCegSg5B8A/PILN9ZwxBSxtiKiUAOi7JW0dLTustF8AGbm0/1o3vjjnSGdj+lYlGwdRO8XN+c1wABIoHk6k61yuSCJITq3jDY9Vx0BqK++uwAfX6JkI/hME0SC1EGguiQ+isqcQRLrF6/0jO2w+6FMnZhyZYsQ1W50qOHgPX1NXndtODsfgMwHzMin+0+ZN0S9YOllMzWfLwKQSS396P3iY3kNOLDPM1y065H4gOW3p4uTDkB8zWdb7FgbdDhEgJkCUDRvogTmd/vPv3BVAUBuvylNzAAYi4hisVQnEHoIqWblrxqm4Mx8ujfljT+YjsWBYgIOc0oJPsq1slCpH71fKybJOEoAuuVTRSCnYlmU6P/Z4iSJEcbLv+Yu9/1EAh7JKEXDKxq4ChUiKymRbwjgHdcUWTARgLYXHSr2LOU+BV7MVwzxwOfkOWybYAGZD5iRT0edjpxD6VhcOQ6j94tP51wdOHBdMeXa9OqWRcmWXA1XLUIUH6zyCwlAs3z+YBkfs1u+VIejJEF3ckrjI9T0y/aMA2+/tgAg08VURKT8vbKMUgAMIGzzAcOi5HknHQAz8+l+MW/829KxhtH7tTz+jIMAJPCYMULAWd6fvi+EY9ouoZBM/Kx/4LUBgFLgNC5o16FrE8JJVJgkiFhaQQBv3+dVbMrWVsC8UxFRkjjaVsW2DtRdOJ/vAyohVYK7A+bTvTdj8HlqTMcaRu/XxHkzjgNkIOWuDr8jnYYDKDutgpUhra0uAlAyCCUAK8BXcjBXgLCk/h0D/hcByDxFAdAzoFUqUBYRJTUcMWdPP7ONL6i5bLQeALJRQ+bT/W7G4AuAOXq/lsGdcRgAY+glLkYclJVTsa6ptCX3uQjAKINQstFrAZKIwWxQIhIJuovB/Nx+r2LzFCwlj8Y0evl/MYk0kieVtcvrwGUnHQCVjjVkPl3mItQsIPuElx9G79dOzDgMgGkAWlNyBJn8xKprBRC+zgEo4LWRgcdVcOCjjlNvmx84DrzNAahaFZWLygKWxUNibIhTcPD9BMLLa65bzreAMSGVoXvJ/Cgh1WUfO+XTZS5CDYDs9GH1fnOrIDcAkABTTDCCLYK0Cwi/586WcKJUiEpC8CCBYDsiiSplqUIUmOjf+o2tIiKVUJbgU5uSWl4DWwX4+PcXnrQATBNS+8yny1yEopdcay+930y5YhgAg+9n2OoUeI5TdQer+32fdhmGoOBZanBo+g1yEKU4dYgFSvqB//vZBIBt9RshkTbW8ZZZ2hUgvDL3iU3uux4LSBM0ZD7dPRnTH08VAIfV+2XAOucQAMuVcKfFSD/+IAABsEoGwYAoHZIKEEYxRIHwLS8pUuhjFVs6/ZZhIVWyxVKBBIRXnbQATBNS+8ynI4tBzkEACv+chlUVIKE/5cRGsWmlKfIzudc3APLQSlg3E2OCyVRc1kpU3DgBmKoQsWtlBcswjPu+nfTYtBL+GQdgOf16GCZW6pXlBCqWSgqJypoOAFfXXDifbwFJLvi5HAjlnUsiIe6AjOp4iQNQHRlT2PlgJCUbbc2s+v/hFwFb/q7gm6HlYpBbmTV2sscQyy/qFBj2v0/cAdz/HGD7NDA1AUyOOU+1CwWOewNjKj6/O03F1/WuugW4/XJgfBoYmwDGdH7IxB5kLPIB+I8AfNwZgga5ck2fJbEm8V9zNWPfrasbgMuPAcuseJ8Exsb9FdBhA+7gaQNKB6TfcgCYug+YJT+g89aoBDMmIMScP12uTKj13uDv8zsKig/uJ1uQOsnojm3qB5P5ACRBH3OhPuzzRN9DV88HqQLEWPJnvTy5nm/t/1s4BcuSpRZtGAu4fi+wtBVYEyccrYwn6hF8/FkJp9bKxAKVFsn/d8urgbHPA9NPOEOWl4+2cfoFHhfVrJTZPKHSj5daOtup6JyCpPx8rHWRVQ7WOlrYCMx8AHIzlxkALPD9c0VB+x/A3E/+E2fUYHXdF7KTGwdvTd0AHP9r4PgWYG0KWBdfsBdsMPfPrKKsoL9XAVLAvO2fFylCE4cKliyrDVZNcGS1CqEYhWFiAZV+XntaURdTLmpCEbpchTYLqi6NrkMCzLzt5Xc4HwyJmmkJ+Z73jQOh4NWeDUZiK1K08f0EXt7CMHVawIk7gaVpYJUA9LI1Ao8bzKX1cytoFtFfpdCIWz7rgzHgth8u0oPGDwETc8CEMySUzFaikgtlpW1Ta8JqNba7lVljSRgW+Q6ZP/57WQvj6fydBjXfAjKbgEvMLwWCvhNoipgNpnQshlS4IGFWzIk6ylWwAz93ETLxGWB5ClidLABoIOS7pmGfG+33YAG5mND0G8F4678vkiPJczNOAC4UyQm2N8w94kirFlfIAl7i402d6dbPWWAtrsjOFiuCvAJZOQE0pHTFsckHYDeCvhNgipQNxoAz8/8IPr5nbvH2jd+6AThJAE4AqwTdZKEBLDoDgU4+YVkPHIBoPwareOt/BkDexsMFAFnbzNJYm0IDnVwbt4uyur1kwL7Tp+iZM/08WT9Rc7DHUmuYTr/x+6o4ovvu9fjBbgR9JyA+omwwxvZI5ULg6ZW7y9FPf9QNwKm/CgCcKABovh8ByVy/UCtJq2f+X1yYJPGU27lIZLbuEWDsWBHesZeDz4iURLUWa1TE47LqK12fZmd3OXidFctqm92KatVs1jAEsNv6sdymaa2g8+xUL4I+Pn2beCgbLGWHI/h8G3oTr45iK86POlbBU9yKI/AcfLR+ouQwH9BfmmbLlTHboOnZ/T9+5vaf8FUaAThXsFOQ45mUcgZCWTAxe0UQ+urYMO1/37GtxQmoLCBtRSp30LrDp2SFdzYMgk/R+VNwvwR9mwQDsaspGSfJgYDYNTbp8psCQFJxEIBkQjDrxt8dXCUIY+COH5MVFPi8SOn2n/QYLZ9Gp0cxANIP5IvAkzVzxivRydnKNzBa8fddM84b6AFyAriMF2pajk9kYIeoClXmA3AQgr5NQEHMBqMVFMNaIOayNRL/vhlH3RZwmhbQQUcAasrVVGz4EtjCu/3dfb/ID3PbT7uKAZ/MhcIC0vqRTo4W0IBIEAmEtFwCYqjW03bcmdwBYeoWgetUbrR8snrloiR2drpACf+rD4D9EvTVjIJu7HBV+781X752Czj9lwUZkTEgcPoNPp5Nv4oBRhCG6dd+1DkMz1JIhR1BAHJ7zwqO3fIRRM5tmDK5CoQKsSgOeBYBKFZULTqcB9r6Ni5KYmd3WKDUA0BlhNLM8EbT1QBXBU72aI5ZjUcVOxz7WLkQ8d37vsart/uA6RcPsxNSAtAXHDYNC1AEpf9s01kKwuBwGU7HgVt/1jtD1e60fgQigSe/j5bQp+KYpGB+H62jT7P8/ZypBIC8Dhcx8eY9wF015abhmnoAyJ5WSrKeNgKO9SHxnT/LSasJBim5lRjWBEIVeROInKL1qunybRawLgASdEy74qjaNNzJCgqEEYzBGvK0297mAFSHEIB6ebKDgc8J1ksmV8t29f1en6L5v6cxIK5iK6Xne/5jCTiFcTqVn/r/tWDPWwXnEPTVgIKUHU7ljASawKefIwDpMdRxRB+wFgD+RREDJABpwSzz2c0LfxczVjkVKwaYgtBBezu3SvX08d39P5uO3QKahXMQciourZRAGKZWar/YZ1xXRPe8wQr2AUK7TvbOVTZBXx4MBECRnConUBSFEXT6mf/TK+/qmzAF/0UBOPqBZYF52HrTFCw2LH5G8UCzJEko5nZqmRnPh/uCXmpnVpDTsIPPwKApOaSA2QLDLSHf97iPx0tpISLfz7bl4iFfsUsnj+HZWEeOYDCDnDmCvZkEgedcCjxGseIhBYt3vx049HwMLRh8gA9gh2MoH9ABqKJzxf0McO7XlSAU4HzhYYFq+5D7hwBu/98OQLlIBCKnW39SlXNY+nqeiq2dkQg+gnGPb9/ZpT0lq6MV5D96gLCwgDmCwbdnCvZmCgY/dxy47xxg5SWuUjigYPHFbwA+fyGwfr2rXrMvPB+vp3L3GHCgi9JOHQCkRVPppeUBigXLFymyejYTB4YsgfA20ofRAlYB0FfAlvQqP0/TsX5PLOB5DNu471cmIwiBaRww/F01J+mz2pqChxUMZvpJlmBv3iTocsW4dzewfhkGFix+2febXDAeJO/YEILBB7pU1g8LQFo98QASVGYNQ6DZfEG3fnEqrgLhbf/HV15anbkFNCvohWSl9XPQ2XTM/2s3I4DwPIZwBEDfgitH0Ek6N6x+u/iD7T4g/YdBBYPpWHEaHlqwNw+AQa4Yj54JrJO+aQDB4pt+oCAyYvOPEIQDCgYfeF/9U3AbAMX7ItAlVtAspKZdz5SOlvA2pstxjES3wJ+92NgAGK2gwi78QoVfEhBeQACqNNP1RdoA18kKdgDhxkUI/zKIYDCnqyzB3jwAJnLFOEIW7QEEi1/1Y21ywVglCAcQDD5/Efj7M4CVrZ5AKlkhxeQUaxBI4nvFzxf8IfCVC4HV7cC6ZEX5nen3VX1vAGLZq8ysrvHY+QBwbGfI2E6JpLvdX+ksthpUvQrmX/sVDGZVUJZgb17vJHLFeGQcmCdVb5+Cxd/5xjZ6QzzMLOQBBIOfTV2Ps4HFHQ7CLQUQmUrV0rgKJMsCjsxGAqTn/hzw0EXA4tnAyg5gbTYBorKkUyLnkB9YVhTxu+kT13iccwtwdBewPAus+b2ar9xJAafqfgMQO4dh+J9+BHe5gqZZZzYok1JJUcpaR6bp93P+W/N6p0KuGIemgEWKgPQhWPxdP7NBLhiHKYHUp2DwpZ8rLOD8tmJQVplOLxAqmbRKC6EDYC7/CeCRPcCx3cDSrsISrs04CPm9ArZk55UvKAspYLqPaPdR4/H0g8DRHcDyVr/X6VabLHk2PhjpPVZY7d5xwF6CwS9y/4LbbVyQsEKIufGiKe0p2JvXOx3kinF0GjhOQY+oNRtljji9TQPf/fOV9IZY4Gq4D8Hgy/4W+Oo2YG5bUUy04vUcLCqSJVRWszJbNgxSmMau+q/Ao2cBR88EjtOqbgNWWaTkIFz3YiWrF4nAjtN0nBZrJnU+/8PA3CxwfMYB6LUra3oglL0tps6wlVha5rLiqd9AdDfB4Je6U0s/0BXTDYh80Sr2FOzNA2AXuWIszABL1JaKWq1R+nwGeM17OsoFY5XTVw/B4Cv+Djg0C8xvLYqJCECzgsxmZlq9T8e0XGUyaUizavPtxoFr/zvw2BnA0Z3A8e2FVV3x6c4sqwObckeyhiXAowUSADhD1XhceDMwx37lvU4XxVN2n3rJIocygkr/Vbs7fe+EdBLcfaXXQ3IPWIrpBB6XlnwpR76jYG9e7/SQKzarxM7qJFj8mg8UarMV9IZ4gvNDD8HgKx8HDs8A8zMFAFnPYQPDl0Co2g4fpDZLqKCxT0/7fhJ4fCdwbFvhRiwRgJruCOwUgCpeCvUjZmEFxhfk9W969kW/B8xvKQqnVgg+B6CB0MsI7P70AHgmd2n1NQ0rv7FvALIlVYK73MnQCDLThSGZoDpuP7uCeuX5n8zroB5yxThGnQ0CgyBMxY63Aq/5aBHG6EBviDlOLV0Eg1+0AByZLgbl+HRxnZXJoqqttA4ODovlJZVuSjTQFtq+NwNPbHMAzramdVpVs6wEoPtdNg37wJfvsYiJP9NFqvHY+7vAwjSwxAeNxVO8T6aNVRRRlT6hHrJ0Ovaw0WDJCKng7g86APvNB9wg2JvXO33IFWOBgn8EIf2nRLD4tbe1+AU7yAWbZeskGHwVdd2mgAUCcNKnJgLQrZ/V9/Jnn5JUYmnAE3hCmv3+t8AWQfSzyPK/POOgJgDdsgqA5nfJAvLdLV+bz0kK4RqPZ3wQWJxyAPqDVhZQyQr7gyaXI9axWCFVAGLvRUhV46PgLnUWBs0HbBPszeudPuWKsTRZAJDTo8l8ui/42juL5veQC7ZpsEow+OrZQlqVVuH4FLA8WVyDAOTAmHUQCAWQkOlsQAwDt/9/AE8SgPQpNa07+AhAA6HLXbb5Xr4IaAMfv/eGvP5NzyYA7UGjBWTWjh40v9fSyscHLtaxhJWxFVsNNAXH1khw983+DYPmA5aCvXkdNIBccemfceooAfhAAcA+6A2xLuAGucxrzgKOMexDfV9OwbS2BB/BEoqLSrBoYGgJ3E8qLcIEsP/ngCPuUy7S13L3wb6PU56/m/Xj4Ps0TKCXQA6AXuNeZY3HMz5QANAeND1kwcKXlj6wOZQ+b7R+Pi0PD0DeFAfk590CKg8qncfoFzIRVWVqfFfBhgn25vXOAHLFWCDbvPstBsJZ4LUPt+jdesgFg+qVptWq11bg2gtgfuLiRAAgQeg+oEmsOujsXb5SsAoCIN/3vx04OlNM6Yv0tdx1MKvK7/TFjVmeCD4HQQQhf159eV7/pmc/kwCcKABoeYvR0oept7SEoZQ0Tr1lPuPQFlAtO0nyAcWhpzw/FSjFzGjLx+RGvxzoSeC1hwsA9klvaFN5FAy+9mJgnhaQ0qqagglADo4c9AhCDpJPl5ZommQ8738HcGw6AJBW1VecZv0cePwOY0/wl1lAD/WUCx0mMlDLr8bjmb+Dwp3x4nkDYbD0thIO5aNtfmDi/xGEeRawxhs7Vb/q2huABQJwAlhyy2cC0xoggjAAUCWWAkksOiIY978TmOOqeqqwqAx3WGhHK06n7TDwOcAV/iipPAKjwgrZm2o8nkUA0gKmAHTrp+o9MTrEYvq44o9pZIOtgmu8mafCV72YAKT/RwAy5OPOuVlAAk9Oule6xQRTWUKlWtkU/IvAHAHti5oIwDK841ZPFtCmdr0U8PaC9hVultd4CIC8P2Ztt/m5/qC11TJXlJDGGpfGAmYODgFoCxACkLpuWh3KCgqE8gNVZK4KtxgjJAB/2X1Krao1rfN7CWZf3LSBT4uAEIyWBVpipL7GgwA0AW25GbGENBTRx3rm1M2w39mmrFVwjTd1Kn+VAZALEE5LtIDyMWUBvbLNLGHgd5H/V07BDp7r3uU+Jadgn3ptxekA5MBri0/Wp4wzBjDbCnkMWMqVpE8GJwLQqvfc0pqbkVj5aNk7gbCxgJno30cAjntowtXNaZ1suvSKNhsYTcVKmw9F5xGE+94dfEoP+JYhD/8OC8eIPUsUHokVVKB78XszbzAF4Pvd//PCKVGIpOAr78mn4DZOm8YC1jco+w6EFTDDPJqeCEBZBa5GffVbhmQ8DtZW5TYOvPhXip0GTuu22lTMLSw+aAVl9QhEWjurI/aQiLJkTMLsX9R3r/ymZ73fp1+37OU9hunXSkdl7T3QrhKCtlCM59k2i5CMMSIAGdqxEIwrmptzTsCEut5yilKoJLAcxCq3fe8tLCDBFwO+tKjyuxSCMdYEXoeDrHcHvu0tTwLzmwHA4N/Gh6zNCqqeOSxC2lb8tQSiMwbuqXIqAcjFh2JjBKGJyShQG6ygVbfJegULWBYcMR3rvb6oCRaQwFPgl1M5rR7/JtBZOIZWx/0+s4QeY5z/1/X2tFnAxPpFELaVkdLN8MWGVr4pCBsfMHN8bmTKfCjZ0Ncp456/x58zLzfw6Qf3ABd8pUgEYmqk5bGyek06IQl1bkXScnlN/u8L24Gdx1qVq91KQvrpgwaAAw9p+wnXPw1YjyWMGtDo2ASOFGMU7SIEUzdYD34vMPmXwLbHgdkFYAtlGiim6DpxJtvq9LtlVr/aWKEB8pUXAOOPAFPzwBTZ9r04vdQ9Ts4pAZ3cd+yHxgfMAOH+vcA69/9Uxijmz/AerYpdar1lNSMYzV+vWY/34I8DY58Gph8Bpo8A04vAFEFIknIHohGVR62QhFRSYjQE6qFri2z3iaPAhHNNlxKwArI0Q1IAxwfReacbC5gBPp66/5ICgLKCtqnsrKKlrFZUFPKOr7osMTtdsxzqQRZ93Q1MPARMPllohUxRqkEK6gShOP0S+dY2hlRv99y+ovRi7IiTnTvLqmg6xDPYpqAUgRgsoR7MxgJmgHD/c4E1FXu7FRRbvEgd7evXWlbPpp9EgUjiJpwe6zwOMlvpAWCMVusJYPIYMOlSDZRpoGiNxKzbdIQlXONMWJbGtw4svdgz3El47nzTRvPrrKptAJT6ZrzfintvAJgx4vsvdQvIXK5VYF3sUZxmJUvgA1FOvwF8spKyBtM1y6EepI4LqVMedbEaTp0EIKdPKh5FqYYqSxgo2jgFr13j6XXHnOiSZOeBVSvyC8qC2r05FVvVw9cAMAOA178AWPMp2LJaaekiCPXExwHw660n1oB/niGQazwOkkSepbJ/72I1x4CJ+cJ6lYI1riccrVicUuVSmIW82pkwnHHVOKbFsOozQGkFkwewnBES37ABYMaAX39ZAUCCb82nIlo+40p2gNnvsoKunxH1xGwA/LOzdQOQJPIuHzV2GBg7Cow7AI0l33XfjOsv6oVodes6ISbBsAZMX+kJxU56KY7pkmFVhOciuvTzSt05v0+ryuT/9gDrZNe4wPMsI7VJP3GcP7gUOOdvgL1rRYJ0ZI5IV3hV4/wrGYPPU3/AiRhYusy2K7mU999P+z90ObD7LuBZK0Xdkeq9NSX2+o4HLwfWlopFCC0fgciBMtAFC8CGrYXVoVjnU2G7rTXrzh4kfRzLY1kyGwBoeiGcPiXb5eAzdXWnazPCSScb4j3xfmav8Cx2p50lAMW0VXINitCogl2r9H2dcctWwQxQsn6ZTBbMNtcgdKIbiZj51VcBk38CXPxoQcfCUg8pjcYgZScw/momACnXyr4leBhs5QaBTHpf7X8dMPYJYO8XgAv9e8QJlAZZq8D4xSuANYKPJQn0AR2AHKy1MACKe9nfFI6IEqduEWoHIJ9wlsVKLekoMCa9EAegSTYQeM4TXco2SEMkAHEbBZoj4bbYtdyCVrFqGXgTSxgXYTZeHLi9AMjEQRCVUXP/n4KUaaT8vVTi+Rtg7GPAuYcAWlMCgUVkQfJ2Q12yBvPXMwHImhDWwf81imsTiLSEvHZkr+jY/p9CQRD4p8DOBwteItai05qn31FFdfLlFxYWgCDUIkRkj/TxbCEi/89jfPZ3X2VqYSJQbmUNQY3HQT7hbv2sLoerVwKQHNEEoCsm8R4MhPRjXUGzVEIKIoY7yaEYuY4dgGb5RXruoSgtSCLLarkICQ9f6QNykGjFdjsIBaI4kGlt8W+Rg5g0HJ8qAp47nihAzFpuWtPIMBZJlASILvR6fQ0DCVbJCkJOJCqnk4pGpb99tZ8MopyiKDX7WWDiwYKXiEQOehCrgKh+eJQ+EQHo1Lby/zRlyf8TIbf9XS5ftIb8I92YugH4ay2pLusorl7dAoonWtMwQSTdOFuQSLTGHyIC8kxSIQuA4hwU2WUAoO4/grBcDbsfWElSzg+JCoYDoEGM1ixSkHzgF/wG7y8sIa3J7JPAGWuFJSQIaU01iJHUiYP4e33BrPOHmG/JMaOfTZVYRhwGav87vWKPJ9/rSH4IOGO5sITqg/ggxXs4TOaBAECbeoOsgfl+DrQShFqcEIhyyt0MbMusEkx76iAZXKM8BvXiZAGlF+KaIbaadYpem4aDgpJZQz6YJABV5VcHAJZ0v4FxX6KG5UpYs0KnqjhRuagEVgPglYAl9ciHf8mdUrJh0Qx9vkDBzBywfbkYQIGwahA/kglATsHsDzKA0BATiPyZ4NEDwIeoa/uFYKKXL2f24nQoIgd9R3yQCMTFqwIAfdBWI7+yB5ZLECYLETd85YJl+2YAUNosLIel/xYlu4Jsl6bhNhD6it4WJCvA2Zc4Gxo73RcgJeOqFmGR6rcChLYACyGojmEYdj59KnZ+tIQRhH9IvWA2hiREjDeRI9Cly7fMF3EtWRFawhQIf5IJwE56wdTIYdt7tp9ys1K8JnoJvod9Wn682PNkP4hUy1ndWgstAtBDMLYN5/6PAc5DGNoF4SrZfN+4+IhT8jqwg2Cp8ThIJ5vfSWBXAVCrWN9SMxDK+skaOvhoAc8me654pmUB3f0wyt+E8FyRAGmPlOEoiSD2qgvmAKoOm52fAuiTDHSyIRxx+lI0QxxADubfF5vffMmSajrWlP7nmZ3dSy+4r/ZzAUEHnQ8R70HsXlK+PgJsW68G4XYGZj0EY2EYATCAT6tAhmE0DXcC4faapcwMgAIfLb0kuzT9Qmw5uwAAIABJREFUSi+EfeALkSrpBovbrQDnkm8wAo8/E3i+CCsZ98NCpAp8cUekZyBavI4ET/TnaAk/RQCyAXy6uNSPA0i+wMeB6ePA5HFgZq2wpNGK3FUDAHmv3fSCe7afX8CB4UNEEOolVi/3obastNwJ9cO5BOBKEQMsAcifHWzRAigWWAlCn5K2bQYAOe1KMjTIR2kRUhKVS7IrLia0v+3xwHMZMCbYNP0KfG79zAqK5DxOvyEuWu6VD5KSHy2YAEQAfpaRdl5UkuUctIpBnCIIl4psD03FtIIP1ADAlBuJM47EqqUX3LX9kSBQcuuyftK78xUkHyQ+RLqHZ3Fv1KcgLj5kAQ1s0Qo6IA1nHhNLQzA8ZxvBXuNx8DcS5UYpNnoYxsCnUIqvZo0F3wPTMa7Hv53HOJVbS/l+5bumX7d+5WLE44hxIRJB2NMCqj9ixwuE90svWCaIA6bAp959EKeWChAyA0PTOV2unGMQveCO7bfqHbcS4rJR7Ewqnw5AWhLuImg2uFQAXAVs8RGmntW4+g2hB3P79L/EJ9zGvqrxOPibiVihAOgrWQOf/EBfBcsPNBBqW9Hv6zzGqFzmoXz3B9AePgXiq6bgiv4YOB9QHS8AfpkAFMMjrWAcQA0iO9XJiQyAnos2vV7ESHOOQfWCO7Zf7F40mZFQScRKAYBaSU6vAVcTgN7xXHiUFpDTMK2dFh56912BTiDcvpkATIXzCL4g3WXTZ4jpGfjoF/oihL+fx+0yWUABLwIwtYKKIabgCzHQvi2ggBKn0McEQDaKT5cGkIOo6SuyYzEfjQB0EM5nZgAPoxe8of3sgSqCQM3jkdFLvpRvR13+7UVRuhUFSavNO6otwp88ZZ3+t4M6HLtch6OT9AG/q9cmtf//gV1JDYcnQ2zY6/YakfSrU+Pg1M45NqPt3IEtoM7WFHokyrWKkooglCMWLYjiUXMtK3g8Uzd1WL3gDe3vRRCoUEYCwGtYFxxqgA2E/jI20F5hhmQod98BHNnlxOTig1aGiDanO21yV4DygWuB8YeB6fnC9WEtiKVVKeE0ZGiXWczeJoWMIig5a9V5DA1ANoKDeDylZ9NSXxyAsiKawrQqmCv2HVf5e8aRoxfc1n7xs+khItAUvojvyWryxVcWJZksVSyZoQRA3dcAoHzax4Gj2wtu6FVKM7gMgti02jbV476oUJJs1j/AbA1mQ3Pm8eTRsoZDtR+xZKCiEKmMXTIeXHPGdhYArX8FwG4DGMEnAHIK4yvT58nWC2b73cexaZgWWaEKgU1gjNbPP7PvOYGsUSBkv3hBtmRWNzxjTk9RWktvxp6POj0vARjY9sWkFel8RWxegjIF4RjwAOnZWMPBTGjqvHmszxJOBUD3xyznL2bqROvoP3N3q84jG4C7M/PpcvMBef0cvV9k6hXv+2Yno5QfGArRbaCC0mWv2YtF3ecerNDhkNZIIsXQRv5dlTtGADJSz2gEE1EJQM//026HdIEZLC8B6A0tk0g1Ja8DuzJdphS82QBEZj5dbj7gxZN5er/IZI+67pscgE7QaDOUMyC0Wb8+gXjuR4F5J6YsaXnFhBoAGEVvUhb60jISgCQnoh/OLBgvIrL8v7DdFkEYM5dtNg97tvz5zJqzdfIBmJlPl5sP+DJP5xtW7xffnzeh7H+Z+3+RpkyWT1YxuURJYVtx6T0fCTocouQV85VkHRIGegEuEv/YKpkA/JceVmL8kv6t5/9pu62tfiPWcFQVEa0DZ9WcLJEPwMx8uvfnjT9IgZyj94t/ldeA/S9tMaGa9SNdmsIxbvVscVJ1GScoMt4UPwhAsmMZ0aXzQBsvdGRBjQz0FUpEJRAJQOq4KAnBdz+sfiPJ3bOYn8fsykyVWMfiN3BOzckS+QDMzKe7OW/88aqQzsfE5kH1fvGjeQ0wADodmVGwOeiMsUqHrGOnS4UFy9P/wAEojkEnI+IqOIJQNLgpCXhcmLAtD/D+kgQE235L93tj+YBqgTX9BiCeW/NedT4AmQ+YkU/3sbzxBymQuZhm8g1T+QbV+wWFdjKO/Te2mEFNlCb6gPF708VJ1TXHgKd91GnZpDfi1k/gM2vqU3DUnCuBmNQe3P9vw6pe229KOvB0K1k+ZS+rnrfM2AlA3JMZtah/EZKZT3drxuDz1O/yxAwu9JgJxr3lQfR+8aa8Buy/wdWQZAVl+ZzCrG3q9c/YrkmHy3IRYryAAqAkEBIlopJxNNUbER+fA/H+/+AAdP9PmS9dazicJybm7mlB8nR2dI1HvgVkOlZGPt2nM29GCamcGZjAwlQ+vvrV+8X/zGsAAUiLVPp/wd+zaTMFWw+/kAA0GQQnpCw5mDsAMIrcRB5mC/+MAffTwgfwKY2KfmCZ6ZIkUShrxXxBX4yYaV8Hzmcn13jUA8CMfDqWYeQcSkhVOl8U6uxH7xekrsg49h8oiCENgC5TUG5vKxxT8f2aRtOtcAKQ1s8soPuOVUIwpchNlEEIOyNSIrrvv3hwnckWIZPZsnbcDyzTpvg3lU8mpZQqozyfK74aj3wAKh1LgrsD5tMxiz/nkGD1sHq/YNFOxkEAcuW7oqmXlisuQOT7VV2jwi/kTgj1RkoZhBje8Z83SCAEEJZW0C3gff8tADCt4VASaWIBK0HI9q8BF5yUAMzIp8tNx5Jg9bB6v/jdDPSRns0BWIZeUitIo9IhHmhXTvzCPQddccnZ76U1V/IvC4SBCFyg26DFNg7c++Mhhb6qiCikT7WVUmr6lYn2nRKyrdZ51GMBlZIc07GUBdMjny6XCiUmpA6j94vMZbgBMFo552pu27PXAqXTyAUQcitOQjAm9xX0N9pIwIPmSCmH5QuPqER0L4kDYgp9zOUL6fYxkbZcFceyAreAF3GlV+NRDwAz8uksnT3jiILVSmpWNlhMze+k94vMZfgGAPJeHDjpCrgM01Tdry9OzvmYAzAqLVWIwEShwzbRwwSEn+MqP6bQK5tZlWyhjCCCsC19Xv7gOnBRbgp7cu/5AOyVjqVMmA75dJZ9nHF0yohWNlhMxKnS+0XmMtwAmFq4imnYbrEqNJPc+9kfd62RKh0On8qV9hXZ9askEPgAfI56ziocUgVbzGT28lEtRMoKtg7lBHtznfZNA+CQ+XQWM8k4uglWK/NLYKzS+8U9GReXD0g/Tyvh4Ne17Yb4Zbr6g6y7/aNWcoPpjKRTsJIags5IJwkEAv6en05S6GUBfRWsUExZyVZVQCQwrgN7Wfdd41GPBczIp8ODeXfTSbBa6YYxlY8/p3q/udc3C+jTbtvqt2oadnB2m4oNgMn0W0p+hYWHWbwg9yU/0Kb9EIy+5y2hiCit4UgKyTeAkN8Valk4Le/ldlONRz4AWWBRM6fdIPfHstw/G+SE5rMnVQ/kA5AkLHS0ak7V7reXfhgACaBqDtD3e/nmc5k9kA/A80JReq+U38zGVp3ObJo/BvAOD3dtwiWar9zEHsgHIGlFubqSx7+Jja36anLLcDvvgwA+NDpDfILv+qlzuXwAXuSjrkKemlO2e3U1uWUYnL8dwB/5e2apca9LNv+vsQfyAUheX4VguB+mzIsaG9ntqxhF4Xbe3QD+n7/uHLAW9wQ1tblMRQ/UA0CaHC7plXEh+q4T0OWcfhleYTSHBK0EH/mi+fcRuKQn4I6fWpeoB4AevCz3HOOm9yb3F5mBlZBNclYCj1aRfyfrbgPCTR6AzK+vD4CyglX7jpmN7HY66d1E0ctdIrEEE4wEIMlam+Pk7YF6AMj7EwAVbU82vTerCwhAXopJN9zVI+AYrOeULLZgErY2x8nZA/kAJGWr0naUWdFpy2cT+oCWjpdjLFxE5UzYIBBpEUX5nLnlvAktb76SPVAfAOUHpiAMm96bsVtCAMaKALICMyxDq6cXfycA+b/mOLl6oF4AiqBRIEzBp7/X2Af0+fi1XIioMIlAI+AIPIGPmeROWV3j1Zuvyu2B+gHoFfZiDS2lC0LiY52WUADkQoTTMH1BFSYRdHoRfKSu5v9qrizMHYPT+vx6ARhSuDcAzzmDo5ZGHT1PAKYMwQxME2jiSo/gEwBrrq+u41ZOy++oD4BaCcsXTPiSI3ey8s4KGoG8QwCMFM+0ggQhLR0BF19SXuD/ayakz7uR0/TsMcxg3SjfqWNA0hsrga/ojaq/8WPcC+YIk4Ke4CMSuB2XVht1Oj8zIfXlU8BtU8DhmYRXWdfrdF1fgr3+S8At48CD04DVjXQSDO70PTUnaJ5uOCwsIIFHSSFy1pKPWCDsZxCpw8UVgKSPxLXM937OzxxAljzcPAbcswU4Qh4V3UN8mKoeKm/bu78IfKJQa8VD48CylHQiL3O3/qg5Rf30BKACMtJXjXKQcfBSK8Dfqc3KVCwuN2VFGRnm/yKZtq4Re5ifyQQgM2A+BeB3GHaZBo5MAIue0l7Kt3cC4xhw+5eL7TuCkJk1jBtyerbUfYG5ExjZ/pqrxE5fAOrOq5SmowVIrRp1IyT2R6+fg0bgVYG4CsyZe2UsaiOGKXr4Sfp9k8CxCYAFSKyvXeY1o1BxQux91yMtfsHPutgnnyUuUvhc0ZsgUXib+nVkq6+ZKaABIHsgVZnuwD9sVo66rrR4ImdhLGSQ8zPL/JgBQxeU1ouWkO9PTgDzbgmXxrzMkatl3keivfG5x4r4IRcz5BfkO5vEZ0kgpIfBZ8yKjlL17syy0tMNcOn9dl4Fy6dLFabj1Mpvow9Ify+I4Nlo9Xt+ZqU9VdJpqZh4QDDyxUyYOYJwHDg+DhgI/WUVZl7aSEt93+GO9Ia2iuZKOfA7lhp9JpvAVy61w2mOwO5hmCgMHC1H9O24gu6UD9jP+ZmbtLRaSsei9SL4XDPbAEh/kGQ/pSUcc0lbApFWb67lQUhpVnLBsoKqqZclFMmUtrxPcwxl3X7vOCAtYLSCcugFQmqhdssH7HU+RznjiOlYXA8wqkOfkItTAom+oKygca4ES8jY+N3z7fSG4hfUtp3ihUHruVSsFy1iRvNP+1N7A5BdJACmVpAgZPhGOyCigEjlPLudn7kvFtOxuB4g6OjD8UWLRkCZFRwrLCEXJQQhp2K+37lQeBCRX1A7KPQto1prFEmSYn2mB9EAsO+kYfk8KQhZF8yjVz5gp/MztyOUjiW9bCUhEBhKRCCgSis45uQ/PhX/xfFWMgOnWu2gxB0TF/o0kEZ/kCDM1Ts+3RHYnwVUL6XhDFrAswfIB6w6P1MrTulY0sum1VICglKwCEACqvQFCUK3gHcsFQCM/ILayqP1k9JshVqrncMalOYYvgcGAyCvIwuod8YBJQmZpmGJeyRwkGw4n8jJOJQNw3idLFhMRNB0SgASTJyKoy/4ieXCeFfJBUeV2SoAclFyR0bbm1OHTUiN0/DTAwD7zQeM52dqj8VsGEkVE2jKetG7AEhQ0frJAv6RC0trC1skl+IWlNinGLbSaZg7Mc0xfA8MbgF1LQV1z08A2G8+oM7PVF9Ms2GUE0gQyp+Lwu2yagLgR9ZaYpkSypQ6a6Q2DCqzpkvietXIFdoZfuieGmcOD0DeP0HEbBhNwYPmA/L8zJQsATAKnguEqS+XTqkE4YfWWwCUFZTksYAYwZfIBeN9Tw0cjOwu8gDIZqsoSSvhEeQDiiGYFoyWiSDRypWgi69UP5sc5fIcquSCNeXqe2X9ZAHfM7Khe2pcOB+AT41+aO5iRD3QAHBEHd9ctuiBBoANEkbaAw0AR9r9zcUbADYYGGkPNAAcafc3F28A2GBgpD3QAHCk3d9cvAFgg4GR9kADwJF2f3PxBoANBkbaAw0AR9r9zcUbADYYGGkPNAAcafc3F28A2GBgpD3QAHCk3d9cfOxqYJ2au9RdPtdp/khoEOlglDYT39V1PzQFXLsMXAlgt9PCxJKPbufyf8/KHIPfBPAZABf79Xc5XQ0ZQ1Q7360NbxoHrlsDvs5ZRsgo0une06by6X1mZvtP99PNAp4F4LsBXA5gjw8EGTeqaGF4QhzQF80CX7cAvGIdeDYAfhdZ2sTKUcVrpE7nd31N5gj8e2dIo2osk7NZpMdK0Z19tv+bJ4F9K8D1ACj8yfNSikHeg+5Z969m57Y/8/ZP+dPLKZhP/rcA+AYAF7g1oRUhEMUzFMt6eSJfX78b2DkPfM0i8GIAX+uWlAMppreUUErn8p2gzTl+2flg/sDbTkvIOik+CP20//mzwAXzwDcCuNTPJeFXpEpM6QEjIHm/zTF8D7T5gATYNQCe69aAloRTGulfBESBSYNyxR5g/Bhw7hKwZwl4vk9LnM5JmsBzUyDGAX3B8G23Mz/g9BuUa/0IiutfMkj7zwKmngAuXSvOpUvAWYBtF4BTnspIj/O8zPaf7qdvWITw6eZA0JLQEhKEGgxZhUj/dz3NzSKwbR44exnYvVKcy+mM5Km0JhxInUtrGkmzCPicg3W5LMGkQiZZTm9xS9Z3+4m2o8C5c4X15pTKW2Lb+fCx7WLtjYxzqiql29Icw/dA5SqYf6RTTilg+lYCIXmICKQ4IK9wxfSJY8AZK8CuFWDnanEua9ZTAMsaCog3Dt92O/MvnRGBtGwkqKRmMEkqCaa+2k+0LQDTh4rP88UHj74kF1WaATo9QHQ7mmP4HugYhtEKj4PB6ZQ+FS0hQahpldPya1kXTOqNY8DscgG+HavAttUCvBxInitrkgL4lcO33c7spBdM3kAuSnq2nx9gQfAh4JyVwvrxwel2z3p4aMlzH6DM2z/lT+8aB+Q/OT4EEqckWQSBkGD6EQKQnDCLwBSnYgcf32fXioGUFawC4esyu7CXXnDP9tOCsyD4KLB1rmgvX7zfbu2WG/Jtme0/3U/vKxBNAMoi0KcjkATCN3HOEr3UAjDrwOP71rXixYEkeKMFlSX8ocwR6KUXTJ7AaNE2tF8WfA4Ye7Kw1mwvX/yZn+eKnvcrfzC6IK/ObP/pfnpfAGQnySoISBqUXyAASS1AK0JfagWYcRDOrAF66TxZQU7jBOEbM0egH71gcgXSFZAV54NQtj9YcNIpbONCyh8Ygi8CVospApDuB63g92W2/3Q/vW8AsqM4gLIKBBIH8bcJwMCNMX68BTqBb8s6sGWtsIA6jwDk662ZI9CvXjA5A6NVa2t/IAicnC/aGV+8T74IQPm/AmGuBc+8/VP+9IEAyLslAKMV/LgAyIUInfnjwPQqMOOgI/DstQ5Mr7UAqMF8V2YXDqoXXNl+EQQ6N9v29aKdesUpWJZbAPyPme0/3U8fGIDssDid/pUASCvCaXgJmFguAEfgEXT27gDkuwaUg/nbmSMwjF7whvbLhSDL5TwwvdRqo9oqHzACkCB8U2b7T/fThwIgO01T1IMCoAZxGRhbKoAXQUcQTjkI+a4B5e5FzjGsXvCG9gdqrLGFYrpVG/UuHzBOw2/LaXxzbh43DKeoJwlAHqLndSs4udoCoIBHQE45EPk3DuitmYOQoxdctp8+rFwIWsGFYiFFoLGNchcEQC6e+OJC5J2Z7T/dTx/aApYdJ37AyJK/DIwvFxYvWr0IwEn/H1Opco5sveDUhSAAF4HJpQJkWixp6k2n4IYfMGf0amDHev2I8+l4/UbvNw8Eozw72wJePOJ8und7EkKj9ztKGA1/7WwATo44n45pWI3e7/AAGPWZ2QBkYHCU+XTMfGGQmYIxjd7vqOE0+PXzATjifDrKtTZ6v4MP/MlyRj4AR5xPF+VaqZLJF1UzKdPV6P2eLDDr3I58AI44n07ZMARbo/d78gMubWE+AEecT8e9YOn2Uheu0fs9tUCYD8AR59MpG6bR+z21gKfW1gNAz4geRT5dTEZo9H5PPRDmAzBmRM8BJzqfLiYjSKKr0fs9dYBYDwBHmE9XtRfMsIz04aQZ1+j9npygrA+Akqs8wfl0BCCTWRq935MTYL1aVQ8Ao1zlAnAi8+kEQGZTNXq/vYb75Pt/fQAcUT5dBGCj93vyAaxXi+oDoFLyT3A+3Rcavd9eY3xS/z8fgCQX/LPR3SOzkon55jg1eyAfgD8M4NcAPD6aDmBtB1e4NMDNcer1QD4AbwbwxwDe4UvRE9wHZG1gNSXDLlwLNcep1QP5APxzzwj9IIAPnXhT5ORc5EYCA9HNcWr1QD4AmRH6FQBMTSZZH98ZmD5Bh5g1FopiNns1x6nTA/kAvAfAEwDudnI+EvQxPfkEzYfaCXRSBluQMB7YHKdGD+QDsBNBH/9+AkAobqTADGK7Inw1x8nfA/kA7EXQt8kgrGAGMfBxZ5Cv5ji5eyAfgL0I+r68uR0QmUFoBQU8vfNvzXHy9kA9AORoMw7CdGQCjoUZDwL4kv/+8OZ1gJhBIjGDgMh3vTavBc035/RAPgD7JegjODfhiMwgoqeJwNPPTaB6Ezq/hq+sB4AcXeXEP+ZhGVo9vRimIQD5v5oPAZCupgDI9wg8/qz/1Xz55usyeyAfgMMQ9GU2Op4eAchpOIJQQEz/VuPlm6/K7IH6AMjgGzdl6QtyX5jWjpQFevF3lq3xf6yhrOlIAUgQCojR8gmE+l9Nl2++JrMH6gEgR5UA5KYsc+AZmCbQCDi+IvgEQMob1XBEAHIajgBMLV+0kCdws6aGu3zqfkV9AGTwjftg3JRVVRAtHQEXX/wbAcoXP5d5CID8GoJKvqDAloKOoIz/y7x8c3pmD4zhaqwjRzCYyQg5gr2ZgsFTLweWr8XQgsXjbwLWrnNtMlKgNoLBmZAa7PTCAuYIBlMvlWQswwr2UlUw45jdDSx8HbD+Ctd+HVCwePKbgJV9aASDM8Yg59TWFDysYPBtmYK91IbNOHaPA/M7gUXKXA4hWDz79cA8+W0aweCMURj+1HYfcBjBYO54MMY3tGDv8I3nmWSHOzYOLJ0LLPGXAQWLz3oB8MQUsEa16kYwOG8whjh74yJkUMFgbsNlCfYO0epwissVY34bsHw2sEIRkAEEi/dcU0SP5qhF1ggG5w3GEGdXr4L5134Fg4kAjuDQgr1DtDqcUmZETwArZwAru4BVqsv0KVh8/o3F4v0QXZBGMDhvMIY4u3MYhv95Zh+Cu1xBcxuOU/HfeDIq5cv7FuwdotXhlCBXjOXZAnyrO4BV6in0IVh8wStLuWCsUAyvEQzOG5ABz+4eB+R/ewnu/kOP/3G/l4kJTERlljQtIot2e53/IwO2OPl4FLtcnCqAp9cahT56CBZf+LpSLhhz1N5qBIPzBmTAs/sLRHcTDKbiNHdBGGymOC/3hglEvgjAnoK9A7Y4+XgiV4zVWYDAs/etxaubYPFFP1QkLtCIP8neaASD8wZkwLP7AyC/tJNg8L/xLNBu+YBdBXsHbHEFAINcMVamgdWZAoRrfPdXm8KitLdmgYveWAq+2y7iMqfuRjA4b1AGOLt/APJLqwSD3+y5T1yI0AoSbAxMMzGV1o8/My2ro2DvAK2t+GgiV4zj4+3AIwDXtwBrVJeuECze+9aW4Dut4PxkIhYsdetGMDhvoDqcPRgA+SWp4O4veQ5Uv/mAGwR78+6rQq4Yq9PAOi2fA4/vBkKudKVU7VZw77uKvWFuZbtcMNb5v0YwOG9g+jx7cADyi6Pg7gccgIxlcA5TKhaD01yYKBmVFpBZMfx/m2Bvny3t8LGqoqTliZbVI+gMgHwnMAnCIFi897cLAAZ6QyzFzzSCwXkD1OPs4QDIL5XgLmk5JHk/SD5gKdibd38VcsVYGmuBTaAzEHLHgyCcaokB7/1IkUET5IKxwF5pBIPzBqbPs4cHIC/AaeqvPL9pmHxAE+zts6VdLCD/lcgVY3UyWD0Bj1ZwqgCggXA7sPfWAoAJvaEtZBrB4Lyx6efsPADyCtmCvf00s/NnOsgVY3m8BTRZPZuGBUACdArY+5lWDqGmYbIrLHEx0ggG5w1OH2fnA7CPizQfaXqgUw80AGywMdIeaAA40u5vLt4AsMHASHugAeBIu7+5eAPABgMj7YEGgCPt/ubiDQAbDIy0BxoAjrT7m4s3AGwwMNIeaAA40u5vLt4AsMHASHugAeBIu7+5eAPABgMj7YEGgCPt/ubiDQAbDIy0B8ZYNMbkX+ZekpuIiOQrPar+xs889HJg6jZg5jAwvVZ8B+ll9PlO5/Fc/o+ECjnHfi8zYfkvM5ulmp4qJXVqx5deD4zfAkw/CGxdAZgoHfuh131QkaI5hu8Bs4Ds8B0AWLnIRGCBsFfn87JffDMwdjOw5R5g8giwZa34jnQQUwDo99wBfJ4TM7COiNdlaj2rA/jeV/vfDeATAP4UGH8I2Lrc6gc+SHqY4oMZ74VSKM0xfA+UUzB/oBUUCKMl6zSQ/PsXqZD5KQC/A0w/DEwcAcYXgYnVwppwADuBkefnCim90FmBWXwnK87Uen53BI8sbuwqaz9p5UgnQhBS+ZN1zE8Ak0utviCwq8DI8/nx5hi+Bzb4gJzKZE1SEFZZgS9/2pWR/gTAJ4HJQ8DEMWB8ARhfBsaWCwDquwQKvvNgHXvOcYVbPFJPkw+dDxC/W1Y4tWDpw/Rlgo4lo1T4/KxTihDNpJwj3/UiMLXemprjffC7eWpzDN8DlYsQDiKtVxzEqoHkyX9HRizW+nIgaQnvAiaeBCbmC0s4tgSMu2rMePAR9X252jXklaTFU108K0MHav/nvJ6ZxVVk9OI7GR2IZoGQNc/HgbHgIwqILIVujuF7oOMqWFawCoRxkfEIB5CWgkREBCNf9wMTc8A4QciBWyoGz16rwNgaML5eWKpctYZL3N+TWLX0gvtuP0HHk2n16JDyxXmVhfU0qywbJbr5GSuXKxA/sV5Y9UYWdnjwyS3qKKgarWA69Wg6fjQOIK0HadnIjPVFB+AiME4AuiUkCFnESyCSkmAuU7Cjm15wX+2X2ifBRn9A8mKcW2UFjULVQcgVDl80u40SYh763FfvquhLCxitoBYUsoJfjXKttByMq9CKcHn4sPuCbgXNJwyWkECcz5Q376UX3LNncZyQAAADEklEQVT9fFgIJs6lBBwtn3Tt6FpIz4RWnuQxPh2XIGzm4CwQ9hWIFgBTK0gQHiIAJddKq0ELQh+KL1qUR4MvSEsoENIKrgALHNiMox+94K7tl9qnnMio8MSf6SNwGpYVjCDk/Ju7isq496fCqX0BkDeqlWwKwic1gAQSpzGREnFgREz01eALLvvq2Kfi45m6cf3qBXdsfxRbJMho8dimqOhEK8cXQRr9QVpvPoDNMXQP9A3ACELFxPh+jACkP0fLIKFCCRRqKuPUdqjlC9o07JZwKVNHeBC94DQcZO0XAAkmgotAk9QYrR9f/BvByYfMSATDVMzwTXMM3QMDAVAgVHCZ7/MaQK4QZUHiNCbBQlqUw74YCb7gcmYkelC9YFlwvVv7RRAorTuBkECU9asCID9/x9B935zYzyKkqpfiNHxcA0gLQgvBAaPVkCqm3h2AtC5m/RyEqzw/4xhGL3hD++MmslgqCbgUfLKAcRrmTlBzDN0DA1tAXUlWcDm1IOIIJAjlT/Fd05lbFQFwjdtgGcewesFt7Rc/Gx8iWjUCjGCT1YvWT1MwgUqrf3NG45tTbcu0aximWx9xENcEQHGbcYAEwtSXSqY0gnCdgeuMI0cvuGx/FUGgFhwEYrR80QckWN+X0fjm1DwAWv8RgJFilJZBznz0pQg+AZAAlVWh1GvGka0XzB0cCQi30aSGVa9AF62fLOB7MhrfnJoPwPER59Px+o3e76mL5Kwp2G57xPl0kxc3er+nLvyKtLmhfUC78RHn081ONnq/pzcAR5xPR9mRRu/31IVgvgUccT4dNaobvd/TGYAjzqejumqj93s6A3DE+XRUg2VSCjdaGr3fUw+I+VPwiPPpqJjO8J1Nw43e7ymHwHoAKMFd7QErAeEE5NNJMb3R+z3lsGcNzgfgiPPpomJ6o/d76oGwPgCOKJ8uKqY3er+nKwBHmE+noqRG7/fUA199U/AI8+kEwEbv93QHoEhZTnA+nYqSGr3fBoAtaiqBUImdm5hPJwA2er+nKwBHnE+X1gUzSbnR+z11wPj/AeCpPDD3t7rvAAAAAElFTkSuQmCC",Ay="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAAAQCAYAAACm53kpAAAAeElEQVRYR+2XSwqAMAxEJ168ePEqwRSKhIIiuHjJqiU0gWE+1CQdApcVAMUAuARaMGCX1MIL/Ow13++9lW2s3mW9MWvsnWc/2fvGygwPAN4E8QzAA4CXAB6AHjG4JTHYI1ey3pcx6FHnEfhLDOIBKAmUBK6/ANUDTlROXAHd9EC1AAAAAElFTkSuQmCC",$l=6;var we=(e=>(e[e.FrameId=0]="FrameId",e[e.CreateTime=8]="CreateTime",e[e.SubmitTime=16]="SubmitTime",e[e.MaterialOffset=24]="MaterialOffset",e[e.MaterialCount=28]="MaterialCount",e[e.CommandOffset=32]="CommandOffset",e[e.CommandCount=36]="CommandCount",e[e.ViewProjectionMatrix=40]="ViewProjectionMatrix",e[e.CameraPosition=168]="CameraPosition",e[e.Flags=192]="Flags",e[e.DemTextureSize=196]="DemTextureSize",e[e.DemScale=200]="DemScale",e[e.DemCenterElevation=204]="DemCenterElevation",e[e.DemMinElevation=208]="DemMinElevation",e[e.FlatLevelCount=212]="FlatLevelCount",e[e.BackgroundColor=216]="BackgroundColor",e[e.ReplicaMin=232]="ReplicaMin",e[e.ReplicaMax=236]="ReplicaMax",e[e.DemTextureMatrix=240]="DemTextureMatrix",e[e.FlatLevels=368]="FlatLevels",e[e.MapMeshVpMatrix=1904]="MapMeshVpMatrix",e[e.MapMeshScaleX=2032]="MapMeshScaleX",e[e.MapMeshScaleY=2036]="MapMeshScaleY",e[e.MapMeshTexShift=2040]="MapMeshTexShift",e[e.DemShadingIntensity=2044]="DemShadingIntensity",e[e.EcefViewProjection=2048]="EcefViewProjection",e[e.GlobeCrossfade=2176]="GlobeCrossfade",e[e.CameraMercator=2184]="CameraMercator",e[e.VpAtCenter=2200]="VpAtCenter",e[e.RequiredSeq=2232]="RequiredSeq",e[e.GlobeCameraEcef=2236]="GlobeCameraEcef",e[e.ShadowViewProjection=2256]="ShadowViewProjection",e[e.IdentifyRequestId=2384]="IdentifyRequestId",e[e.IdentifyWidth=2388]="IdentifyWidth",e[e.IdentifyHeight=2392]="IdentifyHeight",e[e.IdentifyFlatLevelMask=2396]="IdentifyFlatLevelMask",e[e._Size=2400]="_Size",e))(we||{}),Go=(e=>(e[e.DemMode=1]="DemMode",e[e.GlobeMode=2]="GlobeMode",e[e.LabelingDepthTestDisabled=8]="LabelingDepthTestDisabled",e))(Go||{}),ko=(e=>(e[e.Mvp=0]="Mvp",e[e.Tex=128]="Tex",e[e._Size=256]="_Size",e))(ko||{}),Ve=(e=>(e[e.PolygonColorFill=0]="PolygonColorFill",e[e.LineColor=1]="LineColor",e[e.MapMeshSurface=2]="MapMeshSurface",e[e.PolygonExtrusionFill=3]="PolygonExtrusionFill",e[e.PolygonExtrusionGradient=4]="PolygonExtrusionGradient",e[e.GltfModel=5]="GltfModel",e[e.WallTexture=6]="WallTexture",e[e.LineStripe=7]="LineStripe",e[e.LinePattern=8]="LinePattern",e[e.LineOneWay=9]="LineOneWay",e[e.LineArrow=10]="LineArrow",e[e.PointSprite=11]="PointSprite",e[e.LabelPoint=12]="LabelPoint",e[e.EnvLight=13]="EnvLight",e[e.EnvStars=14]="EnvStars",e[e.EnvGlobeHalo=15]="EnvGlobeHalo",e[e.PolygonTexture=16]="PolygonTexture",e[e.EnvDemLight=17]="EnvDemLight",e[e.EnvFog=18]="EnvFog",e[e.EnvSky=19]="EnvSky",e[e.EnvShadow=20]="EnvShadow",e))(Ve||{}),ec=(e=>(e[e.UseFactorInterpolate=1]="UseFactorInterpolate",e[e.LineGapTurnsOnly=2]="LineGapTurnsOnly",e))(ec||{}),fe=(e=>(e[e.Id=0]="Id",e[e.Kind=4]="Kind",e[e.ByteSize=8]="ByteSize",e[e.Flags=12]="Flags",e[e._HeaderSize=16]="_HeaderSize",e[e.Color1R=16]="Color1R",e[e.Color1G=20]="Color1G",e[e.Color1B=24]="Color1B",e[e.Color1A=28]="Color1A",e[e.Color2R=32]="Color2R",e[e.Color2G=36]="Color2G",e[e.Color2B=40]="Color2B",e[e.Color2A=44]="Color2A",e[e.FactorBase=48]="FactorBase",e[e.FactorInMin=52]="FactorInMin",e[e.FactorOutMin=56]="FactorOutMin",e[e.FactorInMax=60]="FactorInMax",e[e.FactorOutMax=64]="FactorOutMax",e[e._ColorSize=68]="_ColorSize",e))(fe||{}),Fs=(e=>(e[e.TextureId=68]="TextureId",e[e.SpriteX1=72]="SpriteX1",e[e.SpriteY1=76]="SpriteY1",e[e.SpriteX2=80]="SpriteX2",e[e.SpriteY2=84]="SpriteY2",e[e.Opacity=88]="Opacity",e[e._Size=92]="_Size",e))(Fs||{}),tc=(e=>(e[e.Data=16]="Data",e[e._Size=96]="_Size",e))(tc||{}),nc=(e=>(e[e.Matrix=16]="Matrix",e[e.Intensity=80]="Intensity",e[e._Size=84]="_Size",e))(nc||{}),Ud=(e=>(e[e.Data=16]="Data",e[e._Size=96]="_Size",e))(Ud||{}),Vd=(e=>(e[e.Data=16]="Data",e[e._Size=80]="_Size",e))(Vd||{}),ic=(e=>(e[e.ViewTransposed=16]="ViewTransposed",e[e.ProjInverted=80]="ProjInverted",e[e._Size=144]="_Size",e))(ic||{}),Wd=(e=>(e[e.Data=16]="Data",e[e._Size=112]="_Size",e))(Wd||{}),xn=(e=>(e[e.ColorR=16]="ColorR",e[e.ColorG=20]="ColorG",e[e.ColorB=24]="ColorB",e[e.ColorA=28]="ColorA",e[e.ColorTextureId=32]="ColorTextureId",e[e.AoTextureId=36]="AoTextureId",e[e.PbrTextureId=40]="PbrTextureId",e[e.Metallic=44]="Metallic",e[e.Roughness=48]="Roughness",e[e.LightingModel=52]="LightingModel",e[e._Size=56]="_Size",e))(xn||{}),ft=(e=>(e[e.TextureId=16]="TextureId",e[e.WallPadL=20]="WallPadL",e[e.WallPadT=24]="WallPadT",e[e.WallPadR=28]="WallPadR",e[e.WallPadB=32]="WallPadB",e[e.TexPadL=36]="TexPadL",e[e.TexPadT=40]="TexPadT",e[e.TexPadR=44]="TexPadR",e[e.TexPadB=48]="TexPadB",e[e.PartCountX=52]="PartCountX",e[e.PartCountY=56]="PartCountY",e[e.MaxIntervalX=60]="MaxIntervalX",e[e.MaxIntervalY=64]="MaxIntervalY",e[e.SliceSizeX=68]="SliceSizeX",e[e.SliceSizeY=72]="SliceSizeY",e[e.LayoutModeH=76]="LayoutModeH",e[e.LayoutModeV=80]="LayoutModeV",e[e._Size=84]="_Size",e))(ft||{}),Ls=(e=>(e[e.DashColorR=16]="DashColorR",e[e.DashColorG=20]="DashColorG",e[e.DashColorB=24]="DashColorB",e[e.DashColorA=28]="DashColorA",e[e.SpaceColorR=32]="SpaceColorR",e[e.SpaceColorG=36]="SpaceColorG",e[e.SpaceColorB=40]="SpaceColorB",e[e.SpaceColorA=44]="SpaceColorA",e[e.BorderColorR=48]="BorderColorR",e[e.BorderColorG=52]="BorderColorG",e[e.BorderColorB=56]="BorderColorB",e[e.BorderColorA=60]="BorderColorA",e[e.DashLength=64]="DashLength",e[e.SpaceLength=68]="SpaceLength",e[e._Size=72]="_Size",e))(Ls||{}),Gr=(e=>(e[e.ColorR=16]="ColorR",e[e.ColorG=20]="ColorG",e[e.ColorB=24]="ColorB",e[e.ColorA=28]="ColorA",e[e.PatternType=32]="PatternType",e[e.ParamX=36]="ParamX",e[e.ParamY=40]="ParamY",e[e.ParamZ=44]="ParamZ",e[e.ParamW=48]="ParamW",e[e._Size=52]="_Size",e))(Gr||{}),nr=(e=>(e[e.ColorR=16]="ColorR",e[e.ColorG=20]="ColorG",e[e.ColorB=24]="ColorB",e[e.ColorA=28]="ColorA",e[e.Width=32]="Width",e[e.Length=36]="Length",e[e.TipWidth=40]="TipWidth",e[e.TipHeight=44]="TipHeight",e[e._Size=48]="_Size",e))(nr||{}),Ei=(e=>(e[e.ColorR=16]="ColorR",e[e.ColorG=20]="ColorG",e[e.ColorB=24]="ColorB",e[e.ColorA=28]="ColorA",e[e.BorderColorR=32]="BorderColorR",e[e.BorderColorG=36]="BorderColorG",e[e.BorderColorB=40]="BorderColorB",e[e.BorderColorA=44]="BorderColorA",e[e.LineWidth=48]="LineWidth",e[e.StrokeWidth=52]="StrokeWidth",e[e.TipWidth=56]="TipWidth",e[e.TipHeight=60]="TipHeight",e[e.RoundingRadius=64]="RoundingRadius",e[e._Size=68]="_Size",e))(Ei||{}),rc=(e=>(e[e.TextureId=16]="TextureId",e[e._Size=20]="_Size",e))(rc||{}),sc=(e=>(e[e.TextureId=16]="TextureId",e[e._Size=20]="_Size",e))(sc||{}),be=(e=>(e[e.DrawPolygon=0]="DrawPolygon",e[e.DrawLine=1]="DrawLine",e[e.DrawDemElevation=2]="DrawDemElevation",e[e.DrawDemTerrain=3]="DrawDemTerrain",e[e.DrawMapMesh=4]="DrawMapMesh",e[e.DrawPolygon3d=5]="DrawPolygon3d",e[e.DrawPolygon3dTexture=6]="DrawPolygon3dTexture",e[e.DrawGltfModel=7]="DrawGltfModel",e[e.DrawLineParameterized=8]="DrawLineParameterized",e[e.DrawLineSprite=9]="DrawLineSprite",e[e.DrawPointSprite=10]="DrawPointSprite",e[e.DrawLabelPoint=11]="DrawLabelPoint",e[e.DrawLabelLine=12]="DrawLabelLine",e[e.DrawPointAnchor=13]="DrawPointAnchor",e[e.DrawMetricPoint=14]="DrawMetricPoint",e[e.DrawCircleMarker=15]="DrawCircleMarker",e[e.DrawPolygonTextured=16]="DrawPolygonTextured",e[e.DrawMesh=17]="DrawMesh",e))(be||{}),wn=(e=>(e[e.Type=0]="Type",e[e.MaterialId=4]="MaterialId",e[e.VertexBuffer=8]="VertexBuffer",e[e.SourceId=12]="SourceId",e[e.TileX=16]="TileX",e[e.TileY=24]="TileY",e[e.TileZ=32]="TileZ",e[e.Flags=40]="Flags",e[e._Size=44]="_Size",e))(wn||{}),Rn=(e=>(e[e.HasEcef=1]="HasEcef",e[e.CastShadows=2]="CastShadows",e[e.ReceiveShadows=4]="ReceiveShadows",e[e.UseLight=8]="UseLight",e[e.CastOnly=16]="CastOnly",e[e.DepthTest=32]="DepthTest",e[e.DepthGreater=64]="DepthGreater",e[e.IdentifyOnly=128]="IdentifyOnly",e))(Rn||{});const by=8,VF=65280,Sy=128,Hd=new Float64Array(1),oc=new Int32Array(Hd.buffer);function WF(e,t,n){Hd[0]=n,e[t]=oc[0],e[t+1]=oc[1]}function Yd(e,t){return oc[0]=e[t],oc[1]=e[t+1],Hd[0]}var Xd=(e=>(e[e.VertexOffset=44]="VertexOffset",e[e.VertexCount=48]="VertexCount",e))(Xd||{}),Zd=(e=>(e[e.VertexOffset=44]="VertexOffset",e[e.VertexCount=48]="VertexCount",e[e.FloorElevation=52]="FloorElevation",e[e._Size=56]="_Size",e))(Zd||{}),kr=(e=>(e[e.VertexOffset=44]="VertexOffset",e[e.VertexCount=48]="VertexCount",e[e.TexOffsetX=52]="TexOffsetX",e[e.TexOffsetY=56]="TexOffsetY",e[e.TexMulX=60]="TexMulX",e[e.TexMulY=64]="TexMulY",e[e.FloorElevation=68]="FloorElevation",e[e._Size=72]="_Size",e))(kr||{}),ue=(e=>(e[e.Solid12=0]="Solid12",e[e.Solid16=1]="Solid16",e[e.Shifted20=2]="Shifted20",e[e.Dashed28=3]="Dashed28",e[e.Patterned16=4]="Patterned16",e[e.Solid3d20=5]="Solid3d20",e[e.Dashed3d32=6]="Dashed3d32",e[e.Patterned3d20=7]="Patterned3d20",e[e.TopStroke20=8]="TopStroke20",e[e.SideStroke24=9]="SideStroke24",e[e.OneWay12=10]="OneWay12",e[e.Arrow36=11]="Arrow36",e))(ue||{}),An=(e=>(e[e.VertexOffset=44]="VertexOffset",e[e.VertexCount=48]="VertexCount",e[e.Width=52]="Width",e[e.TileToPixelRatio=56]="TileToPixelRatio",e[e.Shift=60]="Shift",e[e.Geometry=64]="Geometry",e[e.AbsZ=68]="AbsZ",e[e.EcefScale=72]="EcefScale",e[e.FloorElevation=76]="FloorElevation",e[e._Size=80]="_Size",e))(An||{}),Kn=(e=>(e[e.VertexOffset=44]="VertexOffset",e[e.VertexCount=48]="VertexCount",e[e.Width=52]="Width",e[e.LengthScale=56]="LengthScale",e[e.CircleFactor=60]="CircleFactor",e[e.TileToPixelRatio=64]="TileToPixelRatio",e[e.Geometry=68]="Geometry",e[e.EcefScale=72]="EcefScale",e[e.FloorElevation=76]="FloorElevation",e[e._Size=80]="_Size",e))(Kn||{}),zn=(e=>(e[e.VertexOffset=44]="VertexOffset",e[e.VertexCount=48]="VertexCount",e[e.Opacity=52]="Opacity",e[e.SizeFactor=56]="SizeFactor",e[e.CalcScale=60]="CalcScale",e[e.ScaleRatio=64]="ScaleRatio",e[e.BorderWidthOffset=68]="BorderWidthOffset",e[e.Geometry=72]="Geometry",e[e.VertexShift=76]="VertexShift",e[e.EndPosition=80]="EndPosition",e[e.TipAmplitude=84]="TipAmplitude",e[e._Size=88]="_Size",e))(zn||{}),yt=(e=>(e[e.VertexOffset=44]="VertexOffset",e[e.VertexCount=48]="VertexCount",e[e.OpacityVisible=52]="OpacityVisible",e[e.OpacityHidden=56]="OpacityHidden",e[e.RotationCos=60]="RotationCos",e[e.RotationSin=64]="RotationSin",e[e.HeightFactor=68]="HeightFactor",e[e.FloorElevation=72]="FloorElevation",e[e.StyleScale=76]="StyleScale",e[e.Dpi=80]="Dpi",e[e.RoundingFactor=84]="RoundingFactor",e[e.Flags=88]="Flags",e[e.SurfaceRelZNorm=92]="SurfaceRelZNorm",e[e.SurfaceAbsZ=96]="SurfaceAbsZ",e[e.IdentifyOpacity=100]="IdentifyOpacity",e[e.HalfPointSizeX=104]="HalfPointSizeX",e[e.HalfPointSizeY=108]="HalfPointSizeY",e[e._Size=112]="_Size",e))(yt||{}),Bs=(e=>(e[e.SkipHeightFactor=1]="SkipHeightFactor",e[e.SurfaceUseAbsZ=2]="SurfaceUseAbsZ",e[e.LabelTest=4]="LabelTest",e))(Bs||{}),ut=(e=>(e[e.VertexOffset=44]="VertexOffset",e[e.VertexCount=48]="VertexCount",e[e.Opacity=52]="Opacity",e[e.Scale=56]="Scale",e[e.OffsetX=60]="OffsetX",e[e.OffsetY=64]="OffsetY",e[e.Gamma=68]="Gamma",e[e.HaloBuffer=72]="HaloBuffer",e[e.FillBuffer=76]="FillBuffer",e[e.HeightFactor=80]="HeightFactor",e[e.FloorElevation=84]="FloorElevation",e[e.Flags=88]="Flags",e[e.SurfaceRelZNorm=92]="SurfaceRelZNorm",e[e.SurfaceAbsZ=96]="SurfaceAbsZ",e[e.HaloColorR=100]="HaloColorR",e[e.HaloColorG=104]="HaloColorG",e[e.HaloColorB=108]="HaloColorB",e[e.HaloColorA=112]="HaloColorA",e[e.FillColorR=116]="FillColorR",e[e.FillColorG=120]="FillColorG",e[e.FillColorB=124]="FillColorB",e[e.FillColorA=128]="FillColorA",e[e.HaloHiddenColorR=132]="HaloHiddenColorR",e[e.HaloHiddenColorG=136]="HaloHiddenColorG",e[e.HaloHiddenColorB=140]="HaloHiddenColorB",e[e.HaloHiddenColorA=144]="HaloHiddenColorA",e[e.FillHiddenColorR=148]="FillHiddenColorR",e[e.FillHiddenColorG=152]="FillHiddenColorG",e[e.FillHiddenColorB=156]="FillHiddenColorB",e[e.FillHiddenColorA=160]="FillHiddenColorA",e[e.HalfPointSizeX=164]="HalfPointSizeX",e[e.HalfPointSizeY=168]="HalfPointSizeY",e[e._Size=172]="_Size",e))(ut||{}),Ur=(e=>(e[e.SkipHeightFactor=1]="SkipHeightFactor",e[e.SurfaceUseAbsZ=2]="SurfaceUseAbsZ",e[e.HasHalo=4]="HasHalo",e[e.LabelIndexIcon=8]="LabelIndexIcon",e))(Ur||{}),bn=(e=>(e[e.VertexOffset=44]="VertexOffset",e[e.VertexCount=48]="VertexCount",e[e.Opacity=52]="Opacity",e[e.Scale=56]="Scale",e[e.Gamma=60]="Gamma",e[e.HaloBuffer=64]="HaloBuffer",e[e.FillBuffer=68]="FillBuffer",e[e.TileToPixelRatio=72]="TileToPixelRatio",e[e.StyleZoom=76]="StyleZoom",e[e.Flags=80]="Flags",e[e.HaloColorR=84]="HaloColorR",e[e.HaloColorG=88]="HaloColorG",e[e.HaloColorB=92]="HaloColorB",e[e.HaloColorA=96]="HaloColorA",e[e.FillColorR=100]="FillColorR",e[e.FillColorG=104]="FillColorG",e[e.FillColorB=108]="FillColorB",e[e.FillColorA=112]="FillColorA",e[e._Size=116]="_Size",e))(bn||{}),ir=(e=>(e[e.VertexOffset=44]="VertexOffset",e[e.VertexCount=48]="VertexCount",e[e.OffsetX=52]="OffsetX",e[e.OffsetY=56]="OffsetY",e[e.FloorElevation=60]="FloorElevation",e[e.Flags=64]="Flags",e[e.SurfaceRelZNorm=68]="SurfaceRelZNorm",e[e.SurfaceAbsZ=72]="SurfaceAbsZ",e[e._Size=76]="_Size",e))(ir||{}),Uo=(e=>(e[e.VertexOffset=44]="VertexOffset",e[e.VertexCount=48]="VertexCount",e[e.FloorElevation=52]="FloorElevation",e[e.ColorR=56]="ColorR",e[e.ColorG=60]="ColorG",e[e.ColorB=64]="ColorB",e[e.ColorA=68]="ColorA",e[e.Sprite0X=72]="Sprite0X",e[e.Sprite0Y=76]="Sprite0Y",e[e.Sprite1X=80]="Sprite1X",e[e.Sprite1Y=84]="Sprite1Y",e[e._Size=88]="_Size",e))(Uo||{}),Vo=(e=>(e[e.VertexOffset=44]="VertexOffset",e[e.VertexCount=48]="VertexCount",e[e.ColorR=52]="ColorR",e[e.ColorG=56]="ColorG",e[e.ColorB=60]="ColorB",e[e.ColorA=64]="ColorA",e[e.Width=68]="Width",e[e._Size=72]="_Size",e))(Vo||{}),Ey=(e=>(e[e.VertexOffset=44]="VertexOffset",e[e.VertexCount=48]="VertexCount",e[e._Size=52]="_Size",e))(Ey||{}),Wo=(e=>(e[e.VertexOffset=44]="VertexOffset",e[e.VertexCount=48]="VertexCount",e[e.HeightFactor=52]="HeightFactor",e[e.Tier=56]="Tier",e[e.Flags=60]="Flags",e[e._Size=64]="_Size",e))(Wo||{}),jd=(e=>(e[e.AbsZ=1]="AbsZ",e))(jd||{}),Ds=(e=>(e[e.VertexOffset=44]="VertexOffset",e[e.VertexCount=48]="VertexCount",e[e.HeightFactor=52]="HeightFactor",e[e.FloorElevation=56]="FloorElevation",e[e.Mode=60]="Mode",e[e.Flags=64]="Flags",e[e._Size=68]="_Size",e))(Ds||{}),rr=(e=>(e[e.Fill=0]="Fill",e[e.DepthOnly=1]="DepthOnly",e[e.DepthClear=2]="DepthClear",e))(rr||{}),ac=(e=>(e[e.AbsZ=1]="AbsZ",e[e.Labeling=2]="Labeling",e))(ac||{}),Jn=(e=>(e[e.VertexOffset=44]="VertexOffset",e[e.VertexCount=48]="VertexCount",e[e.HeightFactor=52]="HeightFactor",e[e.FloorElevation=56]="FloorElevation",e[e.IsHole=60]="IsHole",e[e.IsVertexColor=64]="IsVertexColor",e[e.NearCameraFade=68]="NearCameraFade",e[e.RunSeq=72]="RunSeq",e[e.FloorStackOffset=76]="FloorStackOffset",e[e.FloorStackTotal=80]="FloorStackTotal",e[e._Size=84]="_Size",e))(Jn||{}),Ho=(e=>(e[e.VertexOffset=44]="VertexOffset",e[e.VertexCount=48]="VertexCount",e[e.HeightFactor=52]="HeightFactor",e[e.FloorElevation=56]="FloorElevation",e[e.NearCameraFade=60]="NearCameraFade",e[e._Size=64]="_Size",e))(Ho||{}),dt=(e=>(e[e.IndexBuffer=44]="IndexBuffer",e[e.IndexCount=48]="IndexCount",e[e.InstanceBuffer=52]="InstanceBuffer",e[e.InstanceOffset=56]="InstanceOffset",e[e.InstanceCount=60]="InstanceCount",e[e.Flags=64]="Flags",e[e.NearCameraFade=68]="NearCameraFade",e[e.LightDirX=72]="LightDirX",e[e.LightDirY=76]="LightDirY",e[e.LightDirZ=80]="LightDirZ",e[e.LightUse=84]="LightUse",e[e.LightColorR=88]="LightColorR",e[e.LightColorG=92]="LightColorG",e[e.LightColorB=96]="LightColorB",e[e.LightColorA=100]="LightColorA",e[e.LightAmbientR=104]="LightAmbientR",e[e.LightAmbientG=108]="LightAmbientG",e[e.LightAmbientB=112]="LightAmbientB",e[e.LightAmbientA=116]="LightAmbientA",e[e.DemPos=120]="DemPos",e[e.AnchorX=124]="AnchorX",e[e.AnchorY=128]="AnchorY",e[e.AnchorZ=132]="AnchorZ",e[e.AxisStartX=136]="AxisStartX",e[e.AxisStartY=140]="AxisStartY",e[e.AxisStartZ=144]="AxisStartZ",e[e.AxisEndX=148]="AxisEndX",e[e.AxisEndY=152]="AxisEndY",e[e.AxisEndZ=156]="AxisEndZ",e[e.SurfaceRelZ=160]="SurfaceRelZ",e[e.SurfaceAbsZ=164]="SurfaceAbsZ",e[e.ScaleX=168]="ScaleX",e[e.ScaleY=172]="ScaleY",e[e.ScaleZ=176]="ScaleZ",e[e._Size=180]="_Size",e))(dt||{}),Qd=(e=>(e[e.IndexU32=1]="IndexU32",e[e.UseAbsZ=2]="UseAbsZ",e[e.ExtToRelief=4]="ExtToRelief",e[e.CollapseHeight=8]="CollapseHeight",e[e.ReliefFoundation=16]="ReliefFoundation",e[e.SurfaceUseAbsZ=32]="SurfaceUseAbsZ",e))(Qd||{});function Ty(e){switch(e){case 0:return 56;case 16:return 72;case 1:return 80;case 8:return 80;case 9:return 88;case 10:return 112;case 11:return 172;case 12:return 116;case 13:return 76;case 14:return 88;case 15:return 72;case 2:case 3:return 52;case 4:return 64;case 17:return 68;case 5:return 84;case 6:return 64;case 7:return 180;default:return 0}}function HF(e,t,n){n.sourceId=e[t+3],n.tileX=Yd(e,t+4),n.tileY=Yd(e,t+6),n.tileZ=Yd(e,t+8)}function YF(e,t,n,i){i.add(e[t+2]),n===7&&(i.add(e[t+11]),i.add(e[t+13]))}function XF(e,t,n){switch(e[t+1]){case 5:{const r=e[t+8];r!==0&&n.add(r);const s=e[t+9];s!==0&&n.add(s);const o=e[t+10];o!==0&&n.add(o);break}case 6:n.add(e[t+4]);break;case 11:n.add(e[t+4]);break;case 12:n.add(e[t+4]);break;case 16:n.add(e[t+17]);break}}const Py=3,ZF=1246122573,jF=0,lc=2048*1024,cc=16*1024*1024,qd=4*1024*1024;var tn=(e=>(e[e.Magic=0]="Magic",e[e.Version=4]="Version",e[e.FrameMailbox=8]="FrameMailbox",e[e.RingWritePos=64]="RingWritePos",e[e.LedgerSeq=68]="LedgerSeq",e[e.RingReadPos=128]="RingReadPos",e[e._Size=256]="_Size",e))(tn||{});const fc=256+Py*lc,QF=fc+cc;function qF(e){e[0]=ZF,e[1]=jF}const Iy=Symbol("Comlink.proxy"),KF=Symbol("Comlink.endpoint"),JF=Symbol("Comlink.releaseProxy"),Kd=Symbol("Comlink.finalizer"),uc=Symbol("Comlink.thrown"),My=e=>typeof e=="object"&&e!==null||typeof e=="function",$F={canHandle:e=>My(e)&&e[Iy],serialize(e){const{port1:t,port2:n}=new MessageChannel;return Jd(e,t),[n,[n]]},deserialize(e){return e.start(),Fy(e)}},eL={canHandle:e=>My(e)&&uc in e,serialize({value:e}){let t;return e instanceof Error?t={isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:t={isError:!1,value:e},[t,[]]},deserialize(e){throw e.isError?Object.assign(new Error(e.value.message),e.value):e.value}},_y=new Map([["proxy",$F],["throw",eL]]);function tL(e,t){for(const n of e)if(t===n||n==="*"||n instanceof RegExp&&n.test(t))return!0;return!1}function Jd(e,t=globalThis,n=["*"]){t.addEventListener("message",function i(r){if(!r||!r.data)return;if(!tL(n,r.origin)){console.warn(`Invalid origin '${r.origin}' for comlink proxy`);return}const{id:s,type:o,path:a}=Object.assign({path:[]},r.data),l=(r.data.argumentList||[]).map(Vr);let c;try{const f=a.slice(0,-1).reduce((d,h)=>d[h],e),u=a.reduce((d,h)=>d[h],e);switch(o){case"GET":c=u;break;case"SET":f[a.slice(-1)[0]]=Vr(r.data.value),c=!0;break;case"APPLY":c=u.apply(f,l);break;case"CONSTRUCT":{const d=new u(...l);c=Oy(d)}break;case"ENDPOINT":{const{port1:d,port2:h}=new MessageChannel;Jd(e,h),c=eh(d,[d])}break;case"RELEASE":c=void 0;break;default:return}}catch(f){c={value:f,[uc]:0}}Promise.resolve(c).catch(f=>({value:f,[uc]:0})).then(f=>{const[u,d]=gc(f);t.postMessage(Object.assign(Object.assign({},u),{id:s}),d),o==="RELEASE"&&(t.removeEventListener("message",i),Cy(t),Kd in e&&typeof e[Kd]=="function"&&e[Kd]())}).catch(f=>{const[u,d]=gc({value:new TypeError("Unserializable return value"),[uc]:0});t.postMessage(Object.assign(Object.assign({},u),{id:s}),d)})}),t.start&&t.start()}function nL(e){return e.constructor.name==="MessagePort"}function Cy(e){nL(e)&&e.close()}function Fy(e,t){const n=new Map;return e.addEventListener("message",function(r){const{data:s}=r;if(!s||!s.id)return;const o=n.get(s.id);if(o)try{o(s)}finally{n.delete(s.id)}}),$d(e,n,[],t)}function dc(e){if(e)throw new Error("Proxy has been released and is not useable")}function Ly(e){return Os(e,new Map,{type:"RELEASE"}).then(()=>{Cy(e)})}const hc=new WeakMap,pc="FinalizationRegistry"in globalThis&&new FinalizationRegistry(e=>{const t=(hc.get(e)||0)-1;hc.set(e,t),t===0&&Ly(e)});function iL(e,t){const n=(hc.get(t)||0)+1;hc.set(t,n),pc&&pc.register(e,t,e)}function rL(e){pc&&pc.unregister(e)}function $d(e,t,n=[],i=function(){}){let r=!1;const s=new Proxy(i,{get(o,a){if(dc(r),a===JF)return()=>{rL(s),Ly(e),t.clear(),r=!0};if(a==="then"){if(n.length===0)return{then:()=>s};const l=Os(e,t,{type:"GET",path:n.map(c=>c.toString())}).then(Vr);return l.then.bind(l)}return $d(e,t,[...n,a])},set(o,a,l){dc(r);const[c,f]=gc(l);return Os(e,t,{type:"SET",path:[...n,a].map(u=>u.toString()),value:c},f).then(Vr)},apply(o,a,l){dc(r);const c=n[n.length-1];if(c===KF)return Os(e,t,{type:"ENDPOINT"}).then(Vr);if(c==="bind")return $d(e,t,n.slice(0,-1));const[f,u]=By(l);return Os(e,t,{type:"APPLY",path:n.map(d=>d.toString()),argumentList:f},u).then(Vr)},construct(o,a){dc(r);const[l,c]=By(a);return Os(e,t,{type:"CONSTRUCT",path:n.map(f=>f.toString()),argumentList:l},c).then(Vr)}});return iL(s,e),s}function sL(e){return Array.prototype.concat.apply([],e)}function By(e){const t=e.map(gc);return[t.map(n=>n[0]),sL(t.map(n=>n[1]))]}const Dy=new WeakMap;function eh(e,t){return Dy.set(e,t),e}function Oy(e){return Object.assign(e,{[Iy]:!0})}function gc(e){for(const[t,n]of _y)if(n.canHandle(e)){const[i,r]=n.serialize(e);return[{type:"HANDLER",name:t,value:i},r]}return[{type:"RAW",value:e},Dy.get(e)||[]]}function Vr(e){switch(e.type){case"HANDLER":return _y.get(e.name).deserialize(e.value);case"RAW":return e.value}}function Os(e,t,n,i){return new Promise(r=>{const s=oL();t.set(s,r),e.start&&e.start(),e.postMessage(Object.assign({id:s},n),i)})}function oL(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}var sr=(e=>(e[e.Main=0]="Main",e[e.Parser=1]="Parser",e[e.Labeling=2]="Labeling",e[e.Models=3]="Models",e[e.All=4]="All",e))(sr||{}),Rs=(e=>(e[e.FunctionUse=0]="FunctionUse",e[e.FunctionResult=1]="FunctionResult",e))(Rs||{});class aL extends Af{constructor(){super(),this.workers=new Map}addWorker(t,n){this.workers.set(t,n),n.addEventListener("message",i=>{const{to:r,msg:s,transferable:o}=i.data,a={from:t,to:r,msg:s,transferable:o};this.routeMessage(a)})}send(t,n,i){const r=this.workers.get(t);if(r){const s={to:t,from:sr.Main,msg:n,transferable:i};i!==void 0?r.postMessage(s,i):r.postMessage(s)}}broadcast(t){this.workers.forEach((n,i)=>{const r={to:i,from:sr.Main,msg:t};n.postMessage(r)})}routeMessage(t){const{from:n,to:i,transferable:r,msg:{type:s}}=t;if(i===sr.Main)this.emit("message",t);else if(i===sr.All)n!==sr.Main&&this.emit(s,t),this.workers.forEach((o,a)=>{a!==n&&(r!==void 0?o.postMessage(t,r):o.postMessage(t))});else{const o=this.workers.get(i);o&&(r!==void 0?o.postMessage(t,r):o.postMessage(t))}}}class lL extends Af{constructor(t){super(),this.worker=t,t.addEventListener("message",n=>{const i=n.data;this.emit("message",i)})}send(t,n,i){const r={to:t,msg:n,transferable:i};this.worker.postMessage(r,i)}broadcast(t){const n={to:sr.All,msg:t};this.worker.postMessage(n)}}class cL{constructor(t){this.onMessage=n=>{const{from:i,msg:r}=n;switch(r.type){case Rs.FunctionUse:this.onFunctionUse(r,i);break;case Rs.FunctionResult:this.onFunctionResult(r);break}},this.connector=t,this.functions=new Map,this.functionIdCounter=0,this.pendingFunctions=new Map,t.on("message",this.onMessage)}set(t,n){this.functions.set(t,n)}get(t,n,i){return(...r)=>{const s=this.functionIdCounter++,o={type:Rs.FunctionUse,data:{id:s,name:n,args:r,subids:i}};let a;return i?a=i.map(l=>new Promise((c,f)=>{this.pendingFunctions.set(String(s)+`-${l}`,{resolve:c,reject:f})})):a=new Promise((l,c)=>{this.pendingFunctions.set(String(s),{resolve:l,reject:c})}),this.connector.send(t,o),a}}onFunctionUse(t,n){const{data:{name:i,args:r,id:s,subids:o}}=t;let a;try{const c=this.functions.get(i);if(!c)throw new Error(`FnRegistry#onFunctionUse: function ${i} not found`);a=c(...r)}catch(c){console.error(c),a=Promise.reject(c instanceof Error?c:new Error(String(c)))}const l=(c,f)=>{Promise.resolve(c).then(u=>this.sendFunctionResult(n,s,u,f),u=>{console.error(u),this.sendFunctionError(n,s,Ry(u),f)})};if(o)if(Array.isArray(a))o.forEach(c=>l(a[c],c));else{const c=Promise.resolve(a).then(()=>{throw new Error(`FnRegistry#onFunctionUse: function ${i} must return an array when called with subids`)});o.forEach(f=>l(c,f))}else l(a)}sendFunctionResult(t,n,i,r){const s={type:Rs.FunctionResult,data:{id:n,result:i,subid:r}};try{i&&i.transferable?this.connector.send(t,s,i.transferable):this.connector.send(t,s)}catch(o){console.error(o),this.sendFunctionError(t,n,Ry(o),r)}}sendFunctionError(t,n,i,r){const s={type:Rs.FunctionResult,data:{id:n,error:i,subid:r}};try{this.connector.send(t,s)}catch(o){console.error(o)}}onFunctionResult(t){const{data:{id:n,result:i,error:r,subid:s}}=t,o=String(n)+(s!==void 0?`-${s}`:""),a=this.pendingFunctions.get(o);if(!a){console.error(`FnRegistry#onFunctionResult: pending function ${o} not found`);return}this.pendingFunctions.delete(o),r!==void 0?a.reject(new Error(r)):a.resolve(i)}}function Ry(e){return e instanceof Error?e.message:String(e)}class fL{constructor(t){this.fnRegistry=t,this.onClassCreate=({id:n,name:i,args:r})=>{const s=this.classes.get(i);if(!s){console.error(`ClassRegistry#onClassCreate: class ${i} not found`);return}const o=s.scope?new s.ClassConstructor(s.scope,...r):new s.ClassConstructor(...r);s.hosts.set(n,o)},this.onMethodUse=({id:n,name:i,method:r,args:s})=>{const o=this.classes.get(i);if(!o){console.error(`ClassRegistry#onMethodUse: class ${i} not found`);return}const a=o.hosts.get(n);if(!a){console.error(`ClassRegistry#onMethodUse: instance ${n} in class ${i} not found when calling the ${r} method`);return}if(!a[r]){console.error(`ClassRegistry#onMethodUse: method ${r} in instance ${n} in class ${i} not found`);return}return r==="destroy"&&o.hosts.delete(n),a[r](...s)},this.classes=new Map,this.idCounter=0,this.fnRegistry.set("createClass",this.onClassCreate),this.fnRegistry.set("classMethodUse",this.onMethodUse)}set(t,n,i,r){const s=this,o={ClassConstructor:n,hosts:new Map,proxies:new Map,scope:i};return this.classes.set(t,o),{get:a=>{class l{constructor(...u){this.id=s.idCounter++,s.fnRegistry.get(a,"createClass")({id:this.id,args:u,name:t})}}return Object.getOwnPropertyNames(n.prototype).forEach(f=>{f!=="constructor"&&typeof n.prototype[f]=="function"&&(l.prototype[f]=function(...u){const d=r&&r.includes(f)&&Array.isArray(u[0])?[...Array(u[0].length).keys()].map(h=>h):void 0;return s.fnRegistry.get(a,"classMethodUse",d)({id:this.id,name:t,method:f,args:u})})}),l}}}}const uL={point:{point:!0,heatmap:!0,gltfModel:!0,metricPoint:!0},polygon:{polygon:!0,polygonExtrusion:!0,mesh:!0,embankment:!0,polygon3d:!0,overpass:!0,gltfModel:!0},line:{line:!0,lineExtrusion:!0,labelLine:!0,dashedLine:!0,oneWayLine:!0,metricPoint:!0,overpass:!0}};function dL(e,t){return!!uL[e][t]}function hL(e){const t=e.vertices.x,n=e.vertices.y;let i=0;for(let r=0;r<t.length-1;r++)i+=Math.hypot(t[r]-t[r+1],n[r]-n[r+1]);return i}function th(e,t){const n=new Set(t[0].map((i,r)=>t[0][r]===e[0]&&e[1]===t[1][r]?r:-1));return Array.from(n)}function pL(e,t,n,i){t>=0&&n>=0&&Math.abs(t-n)===1&&(e[2][0]=1),n>=0&&i>=0&&Math.abs(n-i)===1&&(e[2][1]=1),t>=0&&i>=0&&Math.abs(t-i)===1&&(e[2][2]=1)}function zy(e,t){const n=th([e[0][0],e[1][0]],t),i=th([e[0][1],e[1][1]],t),r=th([e[0][2],e[1][2]],t);n.forEach(s=>i.forEach(o=>r.forEach(a=>{pL(e,s,o,a)})))}function Ny(e){const t=["GEOJSON_METATILE_UNKNOWN_SUBLAYER","Commercial_poi_default","Commercial_poi_city","Commercial_poi_premium","Commercial_model","Commercial_model_animated","Commercial_model_on_click","Immersive_model","Immersive_model_multipart","Animated_immersive_model","Landmark_model"],n=Array.from(new Set([...t,...e])).filter(i=>typeof i=="string"&&i.length>0);return zp(["id","db_label","db_label2","selected","hovered","componentDistanceStart","componentDistanceEnd","objectLength","beginningIsCut","endingIsCut","db_geometry_type","db_plan_id"],n)}function nh(e,t,n,i,r=2){const s=r+2;let o=i;const a=n-t>>1;let l=n-t,c;const f=e[t],u=e[t+1],d=e[n],h=e[n+1];for(let g=t+s;g<n;g+=s){const y=gL(e[g],e[g+1],f,u,d,h);if(y>o)c=g,o=y;else if(y===o){const p=Math.abs(g-a);p<l&&(c=g,l=p)}}o>i&&(c-t>s&&nh(e,t,c,i,r),e[c+2]=o,n-c>s&&nh(e,c,n,i,r))}function gL(e,t,n,i,r,s){let o=r-n,a=s-i;if(o!==0||a!==0){const l=((e-n)*o+(t-i)*a)/(o*o+a*a);l>1?(n=r,i=s):l>0&&(n+=o*l,i+=a*l)}return o=e-n,a=t-i,o*o+a*a}function Yo(e,t,n,i,r,s=4){const o={id:e==null?null:e,index:r,type:t,geometry:n,tags:i,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if(t==="Point"||t==="MultiPoint"||t==="LineString")mc(o,n,s);else if(t==="Polygon")mc(o,n[0],s);else if(t==="MultiLineString")for(const a of n)mc(o,a,s);else if(t==="MultiPolygon")for(const a of n)mc(o,a[0],s);return o}function mc(e,t,n=4){for(let i=0;i<t.length;i+=n)e.minX=Math.min(e.minX,t[i]),e.minY=Math.min(e.minY,t[i+1]),e.maxX=Math.max(e.maxX,t[i]),e.maxY=Math.max(e.maxY,t[i+1])}function mL(e,t){const n=[];if(e.type==="FeatureCollection")for(let i=0;i<e.features.length;i++)vc(n,e.features[i],t,i);else e.type==="Feature"?vc(n,e,t,0):vc(n,{geometry:e},t,0);return n}function vc(e,t,n,i){if(!t.geometry)return;const r=t.geometry.coordinates,s=t.geometry.type,o=Math.pow(n.tolerance/((1<<n.maxZoom)*n.extent),2);let a=[],l=t.id;if(n.promoteId?l=t.properties[n.promoteId]:n.generateId&&(l=i||0),s==="Point")Gy(r,a,n.dimensions);else if(s==="MultiPoint")for(const c of r)Gy(c,a,n.dimensions);else if(s==="LineString")ih(r,a,o,!1,n.dimensions);else if(s==="MultiLineString")if(n.lineMetrics){for(const c of r)a=[],ih(c,a,o,!1,n.dimensions),e.push(Yo(l,"LineString",a,t.properties,i,n.dimensions+2));return}else rh(r,a,o,!1,n.dimensions);else if(s==="Polygon")rh(r,a,o,!0,n.dimensions);else if(s==="MultiPolygon")for(const c of r){const f=[];rh(c,f,o,!0,n.dimensions),a.push(f)}else if(s==="GeometryCollection"){for(const c of t.geometry.geometries)vc(e,{id:l,geometry:c,properties:t.properties},n,i);return}else throw new Error("Input data is not a valid GeoJSON object.");e.push(Yo(l,s,a,t.properties,i,n.dimensions+2))}function Gy(e,t,n=2){t.push(ky(e[0]),Uy(e[1]),0,1);for(let i=2;i<n;i++)t.push(e[i])}function ih(e,t,n,i,r=2){let s,o,a=0;for(let c=0;c<e.length;c++){const f=ky(e[c][0]),u=Uy(e[c][1]);t.push(f,u,0,1);for(let d=2;d<r;d++)t.push(e[c][d]);c>0&&(i?a+=(s*u-f*o)/2:a+=Math.sqrt(Math.pow(f-s,2)+Math.pow(u-o,2))),s=f,o=u}const l=t.length-(r+2);t[2]=1,nh(t,0,l,n,r),t[l+2]=1,t.size=Math.abs(a),t.start=0,t.end=t.size}function rh(e,t,n,i,r=2){for(let s=0;s<e.length;s++){const o=[];ih(e[s],o,n,i,r),t.push(o)}}function ky(e){return e/360+.5}function Uy(e){const t=Math.sin(e*Math.PI/180),n=.5-.25*Math.log((1+t)/(1-t))/Math.PI;return n<0?0:n>1?1:n}function Ti(e,t,n,i,r,s,o,a){const l=(a.dimensions===void 0?2:a.dimensions)+2;if(n/=t,i/=t,s>=n&&o<i)return e;if(o<n||s>=i)return null;const c=[];for(const f of e){const u=f.geometry;let d=f.type;const h=r===0?f.minX:f.minY,g=r===0?f.maxX:f.maxY;if(h>=n&&g<i){c.push(f);continue}else if(g<n||h>=i)continue;let y=[];if(d==="Point"||d==="MultiPoint")vL(u,y,n,i,r,l);else if(d==="LineString")Vy(u,y,n,i,r,!1,a.lineMetrics,l);else if(d==="MultiLineString")sh(u,y,n,i,r,!1,l);else if(d==="Polygon")sh(u,y,n,i,r,!0,l);else if(d==="MultiPolygon")for(const p of u){const v=[];sh(p,v,n,i,r,!0,l),v.length&&y.push(v)}if(y.length){if(a.lineMetrics&&d==="LineString"){for(const p of y)c.push(Yo(f.id,d,p,f.tags,f.index,l));continue}(d==="LineString"||d==="MultiLineString")&&(y.length===1?(d="LineString",y=y[0]):d="MultiLineString"),(d==="Point"||d==="MultiPoint")&&(d=y.length===l?"Point":"MultiPoint"),c.push(Yo(f.id,d,y,f.tags,f.index,l))}}return c.length?c:null}function vL(e,t,n,i,r,s=4){for(let o=0;o<e.length;o+=s){const a=e[o+r];if(a>=n&&a<=i){zs(t,e[o],e[o+1],e[o+2]);for(let l=3;l<s;l++)t.push(e[o+l])}}}function Vy(e,t,n,i,r,s,o,a=4){let l=Wy(e);const c=r===0?yL:xL;let f=e.start,u,d;for(let A=0;A<e.length-a;A+=a){const w=e[A],S=e[A+1],T=e[A+2],I=e[A+a],C=e[A+a+1],M=r===0?w:S,B=r===0?I:C;let D=!1;if(o&&(u=Math.sqrt(Math.pow(w-I,2)+Math.pow(S-C,2))),M<n){if(B>n){d=c(l,w,S,I,C,n),l.push(0);for(let F=4;F<a;F++){const z=e[A+F];l.push((e[A+a+F]-z)*d+z)}o&&(l.start=f+u*d)}}else if(M>i){if(B<i){d=c(l,w,S,I,C,i),l.push(0);for(let F=4;F<a;F++){const z=e[A+F];l.push((e[A+a+F]-z)*d+z)}o&&(l.start=f+u*d)}}else{zs(l,w,S,T);for(let F=3;F<a;F++)l.push(e[A+F])}if(B<n&&M>=n){d=c(l,w,S,I,C,n),l.push(0);for(let F=4;F<a;F++){const z=e[A+F];l.push((e[A+a+F]-z)*d+z)}D=!0}if(B>i&&M<=i){d=c(l,w,S,I,C,i),l.push(0);for(let F=4;F<a;F++){const z=e[A+F];l.push((e[A+a+F]-z)*d+z)}D=!0}!s&&D&&(o&&(l.end=f+u*d),t.push(l),l=Wy(e)),o&&(f+=u)}let h=e.length-a;const g=e[h],y=e[h+1],p=e[h+2],v=r===0?g:y;if(v>=n&&v<=i){zs(l,g,y,p);for(let A=3;A<a;A++)l.push(e[h+A])}if(h=l.length-a,s&&h>=3&&(l[h]!==l[0]||l[h+1]!==l[1])){zs(l,l[0],l[1],l[2]);for(let A=3;A<a;A++)l.push(l[A])}l.length&&t.push(l)}function Wy(e){const t=[];return t.size=e.size,t.start=e.start,t.end=e.end,t}function sh(e,t,n,i,r,s,o){for(const a of e)Vy(a,t,n,i,r,s,!1,o)}function zs(e,t,n,i){e.push(t,n,i)}function yL(e,t,n,i,r,s){const o=(s-t)/(i-t);return zs(e,s,n+(r-n)*o,1),o}function xL(e,t,n,i,r,s){const o=(s-n)/(r-n);return zs(e,t+(i-t)*o,s,1),o}function wL(e,t){const n=t.buffer/t.extent,i=t.dimensions+2;let r=e;const s=Ti(e,1,-1-n,n,0,-1,2,t),o=Ti(e,1,1-n,2+n,0,-1,2,t);return(s||o)&&(r=Ti(e,1,-n,1+n,0,-1,2,t)||[],s&&(r=Hy(s,1,i).concat(r)),o&&(r=r.concat(Hy(o,-1,i)))),r}function Hy(e,t,n=4){const i=[];for(let r=0;r<e.length;r++){const s=e[r],o=s.type;let a;if(o==="Point"||o==="MultiPoint"||o==="LineString")a=oh(s.geometry,t,n);else if(o==="MultiLineString"||o==="Polygon"){a=[];for(const l of s.geometry)a.push(oh(l,t,n))}else if(o==="MultiPolygon"){a=[];for(const l of s.geometry){const c=[];for(const f of l)c.push(oh(f,t,n));a.push(c)}}i.push(Yo(s.id,o,a,s.tags,s.index,n))}return i}function oh(e,t,n=4){const i=[];i.size=e.size,e.start!==void 0&&(i.start=e.start,i.end=e.end);for(let r=0;r<e.length;r+=n){i.push(e[r]+t,e[r+1],e[r+2],e[r+3]);for(let s=4;s<n;s++)i.push(e[r+s])}return i}function Yy(e,t,n){if(e.transformed)return e;const i=1<<e.z,r=e.x,s=e.y;for(const o of e.features){const a=o.geometry,l=o.type;o.geometry=[];const c=n.cuts&&l!==1?1:0,f=n.dimensions+c;if(l===1)for(let u=0;u<a.length;u+=f)o.geometry.push(Zy(a,u,f,t,i,r,s));else if(l===2)o.geometry=Xy(a,t,i,r,s,f);else for(let u=0;u<a.length;u++)o.geometry.push(Xy(a[u],t,i,r,s,f))}return e.transformed=!0,e}function Xy(e,t,n,i,r,s=3){const o=[];for(let a=0;a<e.length;a++){const l=[];for(let c=0;c<e[a].length;c+=s)l.push(Zy(e[a],c,s,t,n,i,r));o.push(l)}return o}function Zy(e,t,n,i,r,s,o){const a=[Math.round(i*(e[t]*r-s)),Math.round(i*(e[t+1]*r-o))];for(let l=2;l<n;l++)a.push(e[t+l]);return a}function AL(e,t,n,i,r){const s=t===r.maxZoom?0:r.tolerance/((1<<t)*r.extent),o={features:[],numPoints:0,numSimplified:0,numFeatures:e.length,source:null,x:n,y:i,z:t,transformed:!1,minX:2,minY:1,maxX:-1,maxY:0};for(const a of e)bL(o,a,s,r);return o}function bL(e,t,n,i){const r=t.geometry,s=t.type,o=i.dimensions+2;let a=[];if(e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),s==="Point"||s==="MultiPoint")for(let l=0;l<r.length;l+=o){a.push(r[l],r[l+1]);for(let c=4;c<o;c++)a.push(r[l+c]);e.numPoints++,e.numSimplified++}else if(s==="LineString")ah(a,r,e,n,!1,!1,i);else if(s==="MultiLineString"||s==="Polygon"){for(let l=0;l<r.length;l++)ah(a,r[l],e,n,s==="Polygon",l===0,i);s==="Polygon"&&a.length&&(a=[a])}else if(s==="MultiPolygon")for(let l=0;l<r.length;l++){const c=r[l],f=[];for(let u=0;u<c.length;u++)ah(f,c[u],e,n,!0,u===0,i);f.length&&a.push(f)}if(a.length){let l=t.tags||null;if(s==="LineString"&&i.lineMetrics){l={};for(const f in t.tags)l[f]=t.tags[f];l.mapbox_clip_start=r.start/r.size,l.mapbox_clip_end=r.end/r.size}const c={geometry:a,type:s==="Polygon"||s==="MultiPolygon"?3:s==="LineString"||s==="MultiLineString"?2:1,tags:l};t.id!==null&&(c.id=t.id),i.generateIndex&&(c.index=t.index),e.features.push(c)}}function ah(e,t,n,i,r,s,o){const a=i*i,l=o&&!!o.cuts,c=o.dimensions+2;if(i>0&&t.size<(r?a:i)){n.numPoints+=t.length/c;return}const f=[];for(let u=0;u<t.length;u+=c){if(i===0||t[u+2]>a){n.numSimplified++,f.push(t[u],t[u+1]);for(let d=4;d<c;d++)f.push(t[u+d]);l&&f.push(t[u+3])}n.numPoints++}r&&SL(f,s,c-(l?1:2)),e.push(f)}function SL(e,t,n=3){let i=0;for(let r=0,s=e.length,o=s-n;r<s;o=r,r+=n)i+=(e[r]-e[o])*(e[r+1]+e[o+1]);if(i>0===t)for(let r=0,s=e.length;r<s/2;r+=n)for(let o=0;o<n;o++){const a=e[r+o],l=s-r-(n-o);e[r+o]=e[l],e[l]=a}return e}const EL={maxZoom:14,indexMaxZoom:5,indexMaxPoints:1e5,tolerance:3,extent:4096,buffer:64,lineMetrics:!1,promoteId:null,generateId:!1,generateIndex:!1,debug:0,dimensions:2,cuts:!1};class TL{constructor(t,n){n=this.options=PL(Object.create(EL),n);const i=n.debug;if(i&&console.time("preprocess data"),n.maxZoom<0||n.maxZoom>24)throw new Error("maxZoom should be in the 0-24 range");if(n.promoteId&&n.generateId)throw new Error("promoteId and generateId cannot be used together.");let r=mL(t,n);this.tiles={},this.tileCoords=[],i&&(console.timeEnd("preprocess data"),console.log("index: maxZoom: %d, maxPoints: %d",n.indexMaxZoom,n.indexMaxPoints),console.time("generate tiles"),this.stats={},this.total=0),r=wL(r,n),r.length&&this.splitTile(r,0,0,0),i&&(r.length&&console.log("features: %d, points: %d",this.tiles[0].numFeatures,this.tiles[0].numPoints),console.timeEnd("generate tiles"),console.log("tiles generated:",this.total,JSON.stringify(this.stats)))}splitTile(t,n,i,r,s,o,a){const l=[t,n,i,r],c=this.options,f=c.debug;for(;l.length;){r=l.pop(),i=l.pop(),n=l.pop(),t=l.pop();const u=1<<n,d=lh(n,i,r);let h=this.tiles[d];if(!h&&(f>1&&console.time("creation"),h=this.tiles[d]=AL(t,n,i,r,c),this.tileCoords.push({z:n,x:i,y:r}),f)){f>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",n,i,r,h.numFeatures,h.numPoints,h.numSimplified),console.timeEnd("creation"));const M=`z${n}`;this.stats[M]=(this.stats[M]||0)+1,this.total++}if(h.source=t,s==null){if(n===c.indexMaxZoom||h.numPoints<=c.indexMaxPoints)continue}else{if(n===c.maxZoom||n===s)continue;if(s!=null){const M=s-n;if(i!==o>>M||r!==a>>M)continue}}if(h.source=null,t.length===0)continue;f>1&&console.time("clipping");const g=.5*c.buffer/c.extent,y=.5-g,p=.5+g,v=1+g;let A=null,w=null,S=null,T=null,I=Ti(t,u,i-g,i+p,0,h.minX,h.maxX,c),C=Ti(t,u,i+y,i+v,0,h.minX,h.maxX,c);t=null,I&&(A=Ti(I,u,r-g,r+p,1,h.minY,h.maxY,c),w=Ti(I,u,r+y,r+v,1,h.minY,h.maxY,c),I=null),C&&(S=Ti(C,u,r-g,r+p,1,h.minY,h.maxY,c),T=Ti(C,u,r+y,r+v,1,h.minY,h.maxY,c),C=null),f>1&&console.timeEnd("clipping"),l.push(A||[],n+1,i*2,r*2),l.push(w||[],n+1,i*2,r*2+1),l.push(S||[],n+1,i*2+1,r*2),l.push(T||[],n+1,i*2+1,r*2+1)}}getTile(t,n,i){t=+t,n=+n,i=+i;const r=this.options,{extent:s,debug:o}=r;if(t<0||t>24)return null;const a=1<<t;n=n+a&a-1;const l=lh(t,n,i);if(this.tiles[l])return Yy(this.tiles[l],s,r);o>1&&console.log("drilling down to z%d-%d-%d",t,n,i);let c=t,f=n,u=i,d;for(;!d&&c>0;)c--,f=f>>1,u=u>>1,d=this.tiles[lh(c,f,u)];return!d||!d.source?null:(o>1&&(console.log("found parent tile z%d-%d-%d",c,f,u),console.time("drilling down")),this.splitTile(d.source,c,f,u,t,n,i),o>1&&console.timeEnd("drilling down"),this.tiles[l]?Yy(this.tiles[l],s,r):null)}}function lh(e,t,n){return((1<<e)*n+t)*32+e}function PL(e,t){for(const n in t)e[n]=t[n];return e}function IL(e,t){return new TL(e,t)}function ML(e){const t=Bt(e),n=me.scaleFactor(ro(0,0,t)[1]),i=me.scaleFactor(ro(0,ae,t)[1]);return{min:n,max:i,range:i-n}}function _L(e,t,n,i){const r=[];return e.geometry.forEach(s=>{const o=[],a=[],l=[];s.forEach(d=>{l.push(...DL(d,t)),o.length&&a.push(o.length),o.push(...d)});const c=[];for(let d=0;d<o.length;d++)for(let h=0;h<n;h++)c.push(o[d][h]);const f=_a(c,a,n),u=new Array(n);for(let d=0;d<f.length;d+=3){const h=[];for(let g=0;g<n+1;g++)h.push([]);for(let g=0;g<3;g++)ch(u,o[f[d+2-g]],t,i),h[0][g]=u[0],h[1][g]=u[1],h[2][g]=0,n>2&&(h[3][g]=u[2]),n>3&&(h[4][g]=u[3]);l.forEach(g=>{const y=[[],[],[]];g.forEach((p,v)=>{y[0][v]=p[0],y[1][v]=p[1]}),zy(h,y)}),r.push({tags:e.tags,id:e.id,index:e.index,type:"polygon",vertices:{x:h[0],y:h[1],cut:h[2],signed_z:h[3],abs_z:h[4]}})}}),r}function CL(e,t,n,i){const r=Array(n);return e.geometry.map(s=>{const o=[];for(let a=0;a<n;a++)o.push([]);return s.forEach((a,l)=>{ch(r,a,t,i),o[0][l]=r[0],o[1][l]=r[1],n>2&&(o[2][l]=r[2]),n>3&&(o[3][l]=r[3])}),{tags:e.tags,id:e.id,index:e.index,type:"line",vertices:{x:o[0],y:o[1],z:o[2],signed_z:o[2],abs_z:o[3]}}})}function FL(e,t,n,i){const r=Array(n);return e.geometry.map(s=>{var a;ch(r,s,t,i);const o={x:[r[0]],y:[r[1]],z:n>2?[(a=r[2])!=null?a:0]:void 0,abs_z:n>3&&r[3]!==void 0?[r[3]]:void 0};return{tags:e.tags,id:e.id,index:e.index,type:"point",vertices:o}})}function ch(e,t,n,i){const r=jy(t,n);e[0]=r[0],e[1]=r[1];const s=i.min+r[1]/ae*i.range;t[2]===void 0||isNaN(t[2])?e[2]=0:e[2]=t[2]*Ee*s,t[3]!==void 0&&(e[3]=t[3]*Ee*s)}function jy(e,t){return[Ge(e[0]/t*ae,0,ae),Ge((t-e[1])/t*ae,0,ae)]}function LL(e,t){return e[0]<0||e[0]>t||e[1]<0||e[1]>t}function BL(e,t,n){return e[0]>n&&t[0]>n||e[0]<0&&t[0]<0||e[1]>n&&t[1]>n||e[1]<0&&t[1]<0}function DL(e,t){const n=[];let i=[];for(let r=0;r<e.length;r++){const s=e[r];if(i.push(jy(s,t)),!LL(s,t))continue;const o=e[r+1];if(!o)break;BL(s,o,t)&&(i.length>1&&n.push(i),i=[])}return i.length>1&&n.push(i),n}const Qy=4096,qy=2,Ns={maxZoom:jv,tolerance:3,extent:Qy,buffer:1,debug:0,lineMetrics:!1,promoteId:null,generateId:!1,generateIndex:!0,indexMaxZoom:0,indexMaxPoints:1e5,dimensions:qy};class fh{constructor(t){this.options=t}get geoJsonVtInstance(){var t,n,i,r,s;return this.geoJsonVT||(this.geoJsonVT=IL(this.options.data,ie(V({},Ns),{maxZoom:(t=this.options.maxZoom)!=null?t:Ns.maxZoom,dimensions:(n=this.options.dimensions)!=null?n:Ns.dimensions,extent:(i=this.options.extent)!=null?i:Ns.extent,buffer:(r=this.options.buffer)!=null?r:Ns.buffer,promoteId:this.options.promoteId,tolerance:(s=this.options.tolerance)!=null?s:Ns.tolerance}))),this.geoJsonVT}fetchTile(t){var f,u;const[n,i,r]=Ta(t),s={components:[],byId:new Map},o=this.geoJsonVtInstance.getTile(r,n,i),a=(f=this.options.dimensions)!=null?f:qy,l=(u=this.options.extent)!=null?u:Qy,c=ML(t);if(!o)return Promise.resolve(s);for(const d of o.features)switch(d.type){case 1:s.components=s.components.concat(FL(d,l,a,c));break;case 2:s.components=s.components.concat(CL(d,l,a,c));break;case 3:s.components=s.components.concat(_L(d,l,a,c));break;default:console.warn("unsupported type ",o);break}return Promise.resolve(s)}destroy(){this.geoJsonVT=void 0}}function OL(e,t,n){const i={components:[],byId:new Map};return e.features.forEach((r,s)=>{i.components.push(...Ky(r.geometry,t).map(o=>ie(V({},o),{index:s,id:r.id,tags:r.properties||{}})))}),i}function Ky(e,t,n){switch(e.type){case"GeometryCollection":{let i=[];return e.geometries.forEach(r=>{i=i.concat(Ky(r,t))}),i}case"Point":case"MultiPoint":return RL(e,t);case"LineString":case"MultiLineString":return zL(e,t);case"Polygon":case"MultiPolygon":return NL(e,t)}}function RL(e,t){return e.type==="Point"?[Jy(e.coordinates,t)]:e.coordinates.map(n=>Jy(n,t))}function zL(e,t){return e.type==="LineString"?[$y(e.coordinates,t)]:e.coordinates.map(n=>$y(n,t))}function NL(e,t,n){return e.type==="Polygon"?e1(e.coordinates,t):e.coordinates.reduce((i,r)=>i.concat(e1(r,t)),[])}function Jy(e,t){const n=[0,0,0];return Dt(n,me.fromGeo(e),t),{type:"point",vertices:{x:[n[0]],y:[n[1]]}}}function $y(e,t){const n=[[],[]],i=[0,0,0];return e.forEach((r,s)=>{Dt(i,me.fromGeo(r),t),n[0][s]=i[0],n[1][s]=i[1]}),{type:"line",vertices:{x:n[0],y:n[1]}}}function e1(e,t,n){const i=[],r=[],s=[],o=[],a=[];e.forEach(f=>{const u=f.map(d=>(Dt(a,me.fromGeo(d),t),[Ge(a[0],0,ae),Ge(a[1],0,ae)]));o.push(u),r.length&&s.push(r.length),r.push(...u)});const l=[];for(let f=0;f<r.length;f++)l.push(r[f][0]),l.push(r[f][1]);const c=_a(l,s);for(let f=0;f<c.length;f+=3){const u=[[],[],[],[]];for(let h=0;h<3;h++)u[0][h]=r[c[f+h]][0],u[1][h]=r[c[f+h]][1],u[2][h]=0,u[3][h]=r[c[f+h]][2];o.forEach(h=>{const g=[[],[],[]];h.forEach((y,p)=>{g[0][p]=y[0],g[1][p]=y[1]}),zy(u,g)});const d={type:"polygon",vertices:{x:u[0],y:u[1],cut:u[2]}};i.push(d)}return i}const GL=[204,404];class yc{constructor(t){this.tileLoader=new kd("json",t.ignoreMissingTiles),this.options=t,this.url=n=>{const i=this.options.flipY?n:Ta(n);return eo(this.options.url,{x:i[0].toString(),y:i[1].toString(),z:i[2].toString(),subdomain:Xp(i)})}}fetchTile(t){return this.tileLoader.fetch(t,this.url).then(n=>{if(n.data)return OL(n.data,Bt(t));const i=n.error!==void 0&&GL.includes(n.error.status);return{components:[],byId:new Map,failed:!i}})}abortTile(t){this.tileLoader.abortRequests([De(t)])}destroy(){this.tileLoader.destroy()}}class kL{constructor(t,n,i,r){this.scope=t,this.options=n,this.id=i,this.featureStateMap=new Ed,t.sources[i]=this,this.tileData={},this.styleManager=t.styleManager,this.collector=t.collector,this.sourceAttrs=this.options.attributes||{},this.metatile=Ny(r),this.tileServer="url"in n?new yc(n):new fh(n)}fetchTiles(t){const n=[];for(const i of t)n.push(this.fetchTile(i));return n}abortTileFetches(t){if(this.tileServer instanceof yc)for(const n of t)this.tileServer.abortTile(n)}generateTile(t,n,i,r,s,o,a,l,c){const f=De(n),u=this.tileData[f],d=Bt(n),h=[],g=[],y=this.styleManager.getStyle(i),p=new Set(r),{promoteId:v}=this.options,A={},w="generateId"in this.options?this.options.generateId:!1;if(!y)return Promise.resolve({results:h,transferable:g});u&&u.components.forEach((C,M)=>{const{tileProps:B}=this.metatile,D=[],F=[];if(C.tags){const O=Object.keys(C.tags);Kr(this.metatile,O);for(const R of O)D[B[R]]=C.tags[R]}const z=Object.keys(this.sourceAttrs);Kr(this.metatile,z);const N=Array.from(this.featureStateMap.featureAttrs);Kr(this.metatile,N);for(const O of z)D[B[O]]=this.sourceAttrs[O];const H=D[B.db_hidden_by_plan_id];if(H&&(t._activeFloorIds.includes(H)||t._backgroundFloorIds.includes(H)))return;const K=w?String(C.index+this.id*$(2,32)):v?D[B[v]]:void 0;if(K!==void 0){const O=p.has(K);if(D[B.selected]=O?1:0,u.byId.set(K,M),A[K]=C.index,this.featureStateMap.featureAttrs.size>0){const R=K!==void 0&&this.featureStateMap.get(K);if(R)for(const G of this.featureStateMap.featureAttrs)this.featureStateMap.clearAttrs=!1,F[B[G]]=R[G];else if(this.featureStateMap.clearAttrs===!1){this.featureStateMap.clearAttrs=!0;for(const G in B)F[B[G]]!==void 0&&(F[B[G]]=void 0)}}}const{coords:P}=d,b=P[3],E=Vf(s),x=go(t,this.sourceAttrs,B,D,F,o,K,d),L=this.styleManager.getLayers(y.id,B,D).filter(O=>dL(C.type,O.type)&&k(O.filter,x)&&(l?k(l,x):!0));if(L.length===0&&x.id&&this.collector.idIndexer.addOrphanId(x.id),D[B.db_geometry_type]=C.type==="line"?"polyline":C.type,(C.type==="point"||C.type==="line")&&(D[B.db_label]===void 0&&(D[B.db_label]=NaN),D[B.db_label2]===void 0&&(D[B.db_label2]=NaN)),C.type==="line"){const O=hL(C);D[B.componentDistanceStart]=0,D[B.componentDistanceEnd]=O,D[B.objectLength]=O,typeof D[B.beginningIsCut]!="number"&&(D[B.beginningIsCut]=0),typeof D[B.endingIsCut]!="number"&&(D[B.endingIsCut]=0)}ju(this.collector,y,L,x,this.metatile,xy,b,this.id,d,E,C.vertices,void 0,a,c)});const S=this.collector.getAccumulatedData(),T={regionId:0,metatileHash:Dh,collectorOutput:S,styleId:y.id};Object.keys(A).length>0&&(T.idToIndex=A),h.push(T),g.push(...S.transferable),this.scope.debouncedResetCollector(),this.scope.syncNewRasterSets();const I={results:h,transferable:g};return Promise.resolve(I)}getObjectAttributes(t,n){const i=this.tileData[n];if(i){const r=i.byId.get(t);if(r===void 0)return;const s=i.components[r];return s===void 0?void 0:s.tags}}deleteTiles(t){for(const n of t)delete this.tileData[De(n)]}setSourceAttrs(t){this.sourceAttrs=t}destroy(){delete this.scope.sources[this.id],this.tileData={},this.sourceAttrs={},this.tileServer.destroy()}setFeatureStateMap(t){this.featureStateMap=hy(t)}setData(t){if(typeof t=="string"){if(this.tileServer instanceof yc)return this.tileServer.destroy(),this.options=ie(V({},this.options),{url:t}),this.tileServer=new yc(this.options),this.tileData={},Promise.resolve(!0)}else if(this.tileServer instanceof fh)return this.tileServer.destroy(),this.options=ie(V({},this.options),{data:t}),this.tileServer=new fh(this.options),this.tileData={},Promise.resolve(!0);return Promise.resolve(!1)}fetchTile(t){const n=De(t);return this.tileData[n]?Promise.resolve():this.tileServer.fetchTile(t).then(i=>{i.failed||(this.tileData[n]=i)})}}function UL(e,t){var n,i,r;return{path:t,extensions:e.extensions,extensionsRequired:(n=e.extensionsRequired)!=null?n:[],extensionsUsed:(i=e.extensionsUsed)!=null?i:[],extras:e.extras,accessors:WL(e.accessors),buffers:YL(e.buffers),bufferViews:XL(e.bufferViews),cameras:ZL(e.cameras),scene:(r=e.scene)!=null?r:0,scenes:qL(e.scenes),nodes:KL(e.nodes),materials:QL(e.materials),meshes:jL(e.meshes),asset:VL(e.asset),animations:HL(e.animations),images:JL(e.images),textures:$L(e.textures),samplers:e4(e.samplers),skins:t4(e.skins)}}function VL(e){return{copyright:e.copyright,generator:e.generator,version:e.version,minVersion:e.minVersion}}function WL(e=[]){return e.map(t=>{var n;return{bufferView:t.bufferView,byteOffset:(n=t.byteOffset)!=null?n:0,componentType:t.componentType,normalized:t.normalized,count:t.count,type:t.type,max:t.max,min:t.min,sparse:t.sparse,name:t.name,extensions:t.extensions,extras:t.extras}})}function HL(e=[]){return e.map(t=>({channels:t.channels,samplers:t.samplers,name:t.name,extensions:t.extensions,extras:t.extras}))}function YL(e=[]){return e.map(t=>({uri:t.uri,byteLength:t.byteLength,name:t.name,extensions:t.extensions,extras:t.extras,buffer:void 0}))}function XL(e=[]){return e.map(t=>({buffer:t.buffer,byteOffset:t.byteOffset,byteLength:t.byteLength,byteStride:t.byteStride,target:t.target,name:t.name,extensions:t.extensions,extras:t.extras}))}function ZL(e=[]){return e.map(t=>({type:t.type,orthographic:t.orthographic,perspective:t.perspective,name:t.name,extensions:t.extensions,extras:t.extras}))}function jL(e=[]){return e.map(t=>({primitives:t.primitives,name:t.name,weights:t.weights,extensions:t.extensions,extras:t.extras}))}function QL(e=[]){return e.map(t=>({alphaCutoff:t.alphaCutoff,alphaMode:t.alphaMode,doubleSided:t.doubleSided,emissiveFactor:t.emissiveFactor,emissiveTexture:t.emissiveTexture,normalTexture:t.normalTexture,occlusionTexture:t.occlusionTexture,pbrMetallicRoughness:t.pbrMetallicRoughness,name:t.name,extras:t.extras,extensions:t.extensions}))}function qL(e=[]){return e.map(t=>({nodes:t.nodes,extensions:t.extensions,extras:t.extras,name:t.name}))}function KL(e=[]){return e.map(t=>{var s,o,a;const n=(s=t.rotation)!=null?s:[0,0,0,1],i=(o=t.scale)!=null?o:[1,1,1],r=(a=t.translation)!=null?a:[0,0,0];return{camera:t.camera,children:t.children,matrix:t.matrix?lw(...t.matrix):void 0,rotation:Gw(...n),scale:bt(...i),translation:bt(...r),name:t.name,mesh:t.mesh,skin:t.skin,extras:t.extras,extensions:t.extensions}})}function JL(e=[]){return e.map(t=>({bufferView:t.bufferView,mimeType:t.mimeType,name:t.name,uri:t.uri,extensions:t.extensions,extras:t.extras,image:void 0}))}function $L(e=[]){return e.map(t=>({extensions:t.extensions,extras:t.extras,name:t.name,sampler:t.sampler,source:t.source}))}function e4(e=[]){return e.map(t=>({extensions:t.extensions,extras:t.extras,name:t.name,magFilter:t.magFilter,minFilter:t.minFilter,wrapS:t.wrapS,wrapT:t.wrapT}))}function t4(e=[]){return e.map(t=>({joints:t.joints,extensions:t.extensions,extras:t.extras,inverseBindMatrices:t.inverseBindMatrices,name:t.name,skeleton:t.skeleton}))}const Xo={JPEG:"image/jpeg",PNG:"image/png",GLTEXTURE:"image/texture"};function t1(e){return e.substring(0,e.lastIndexOf("/")+1)}function n4(e){return e.startsWith("data:image")?e.split(";")[0].split(":")[1]:e.substring(e.lastIndexOf("."))===".png"?Xo.PNG:Xo.JPEG}function n1(e){const t=atob(e.split(",")[1]),n=new ArrayBuffer(t.length),i=new Uint8Array(n);for(let r=0;r<t.length;r++)i[r]=t.charCodeAt(r);return n}const rt=class rt{constructor(t){this.data=t}static isGlb(t){const n=new Uint32Array(t,0,rt.glbHeaderInts),i=n[0],r=n[1];return i===this.glbMagic&&r===this.glbVersion}extractGlbData(){if(this.getCheckedGlbInfo()===void 0)return{json:hh,buffers:[]};let n;const i=[],r=this.getAllChunkInfos();for(const s of r)s.type===rt.jsonChunkType&&!n?n=this.getJsonFromChunk(s):s.type===rt.binaryChunkType&&i.push(this.getBufferFromChunk(s));return{json:n||hh,buffers:i}}getCheckedGlbInfo(){const t=new Uint32Array(this.data,0,rt.glbHeaderInts),n=t[0],i=t[1],r=t[2];if(!(!this.checkEquality(n,rt.glbMagic,"glb magic")||!this.checkEquality(i,rt.glbVersion,"glb header version")||!this.checkEquality(r,this.data.byteLength,"glb byte length")))return{magic:n,version:i,length:r}}getAllChunkInfos(){const t=[];let n=rt.glbHeaderInts*4;for(;n<this.data.byteLength;){const i=this.getChunkInfo(n);t.push(i),n+=i.length+rt.glbChunkHeaderInts*4}return t}getChunkInfo(t){const n=new Uint32Array(this.data,t,rt.glbChunkHeaderInts),i=t+rt.glbChunkHeaderInts*4,r=n[0],s=n[1];return{start:i,length:r,type:s}}getJsonFromChunk(t){const n=t.length,i=(rt.glbHeaderInts+rt.glbChunkHeaderInts)*4,r=new Uint8Array(this.data,i,n),s=new TextDecoder("utf-8").decode(r);return JSON.parse(s)}getBufferFromChunk(t){return this.data.slice(t.start,t.start+t.length)}checkEquality(t,n,i){return t===n?!0:(console.error(`[GLB MODEL PARSING ERROR] Found invalid/unsupported ${i}, expected: ${n}, but was: ${t}`),!1)}};rt.glbHeaderInts=3,rt.glbChunkHeaderInts=2,rt.glbMagic=1179937895,rt.glbVersion=2,rt.jsonChunkType=1313821514,rt.binaryChunkType=5130562;let xc=rt;const i1=5120,i4=5121,r4=5122,s4=5123,o4=5124,r1=5125,a4=5126,l4=4,c4="draco_decoder_gltf.js",f4="draco_wasm_wrapper_gltf.js",s1="draco_decoder_gltf.wasm";let uh;function u4(e){uh=p4(e).catch(t=>{const n="Draco decoder module failed to initialize"+(t!=null&&t.message?` with the following error: ${t.message}`:".");throw new Error(n)})}function d4(e){return Fe(this,null,function*(){let t=yield fetch(e).then(r=>r.text());const i=t.indexOf("if (typeof exports === 'object' && typeof module === 'object')");return i!==0&&(t=t.slice(0,i),t=t+"return DracoDecoderModule;"),t})}function h4(e){return Fe(this,null,function*(){return fetch(e).then(t=>t.text()).then(t=>t+`
return DracoDecoderModule;`)})}function p4(e){return Fe(this,null,function*(){if(typeof WebAssembly!="object"){const t=yield d4(`${e}/${c4}`);return new Function(t)()()}else return h4(`${e}/${f4}`).then(t=>{const n=new Function(t)();return fetch(`${e}/${s1}`).then(i=>i.arrayBuffer()).then(i=>n({wasmBinary:i,wasmBinaryFile:s1}))})})}function g4(e){switch(e){case i1:return"Int8Array";case i4:return"Uint8Array";case r4:return"Int16Array";case s4:return"Uint16Array";case o4:return"Int32Array";case r1:return"Uint32Array";case a4:return"Float32Array";default:return"Float32Array"}}function m4(e,t,n,i,r,s){const o=r.num_components(),l=n.num_points()*o;let c,f,u;switch(s){case"Float32Array":u=l*4,c=e._malloc(u),t.GetAttributeDataArrayForAllPoints(n,r,e.DT_FLOAT32,u,c),f=new Float32Array(e.HEAPF32.buffer,c,l).slice(),e._free(c);break;case"Int8Array":c=e._malloc(l),t.GetAttributeDataArrayForAllPoints(n,r,e.DT_INT8,l,c),f=new Int8Array(e.HEAP8.buffer,c,l).slice(),e._free(c);break;case"Int16Array":u=l*2,c=e._malloc(u),t.GetAttributeDataArrayForAllPoints(n,r,e.DT_INT16,u,c),f=new Int16Array(e.HEAP16.buffer,c,l).slice(),e._free(c);break;case"Int32Array":u=l*4,c=e._malloc(u),t.GetAttributeDataArrayForAllPoints(n,r,e.DT_INT32,u,c),f=new Int32Array(e.HEAP32.buffer,c,l).slice(),e._free(c);break;case"Uint8Array":c=e._malloc(l),t.GetAttributeDataArrayForAllPoints(n,r,e.DT_UINT8,l,c),f=new Uint8Array(e.HEAPU8.buffer,c,l).slice(),e._free(c);break;case"Uint16Array":u=l*2,c=e._malloc(u),t.GetAttributeDataArrayForAllPoints(n,r,e.DT_UINT16,u,c),f=new Uint16Array(e.HEAPU16.buffer,c,l).slice(),e._free(c);break;case"Uint32Array":u=l*4,c=e._malloc(u),t.GetAttributeDataArrayForAllPoints(n,r,e.DT_UINT32,u,c),f=new Uint32Array(e.HEAPU32.buffer,c,l).slice(),e._free(c);break;default:throw new Error("DRACOLoader: Unexpected attribute type.")}return{name:i,array:f,itemSize:o,componentType:s}}function v4(e,t,n,i,r,s){let o,a;const l=t.GetEncodedGeometryType(n);if(l===e.TRIANGULAR_MESH)o=new e.Mesh,a=t.DecodeBufferToMesh(n,o);else throw new Error("DRACOLoader: Unexpected geometry type.");if(!a.ok()||o.ptr===0)throw new Error("DRACOLoader: Decoding failed: "+a.error_msg());const c={index:null,attributes:{}},f=o.num_points();for(const u in i){let d=i1,h;for(const[p,v]of Object.entries(s))if(p===u){d=r.accessors[v].componentType,h=r.accessors[v].count;break}if(f!==h)throw new Error(`DRACOLoader: Accessor vertex count ${h} does not match draco decoder vertex count  ${f}`);d=g4(d);const g=t.GetAttributeByUniqueId(o,i[u]),y=m4(e,t,o,u,g,d);c.attributes[y.name]=y}if(l===e.TRIANGULAR_MESH){const d=o.num_faces()*3,h=d*4,g=e._malloc(h);t.GetTrianglesUInt32Array(o,h,g);const y=new Uint32Array(e.HEAPU32.buffer,g,d).slice();e._free(g),c.index={array:y,itemSize:1}}return e.destroy(o),c}function y4(e,t,n,i){const r=e.bufferView,s=t.bufferViews[r],o=t.buffers[s.buffer],l=new Int8Array(o.buffer).slice(s.byteOffset,s.byteOffset+s.byteLength),c=new n.Decoder,f=new n.DecoderBuffer;f.Init(l,s.byteLength);const u=v4(n,c,f,e.attributes,t,i);return n.destroy(f),u}function $n(e,t,n,i,r){const s={buffer:e,byteLength:e.byteLength,extensions:void 0,extras:void 0,name:void 0,uri:void 0};t.buffers.push(s);const o={buffer:t.buffers.length-1,byteLength:e.byteLength,byteOffset:0,byteStride:0,extensions:void 0,extras:void 0,name:r,target:i};t.bufferViews.push(o),t.accessors[n].byteOffset=0,t.accessors[n].bufferView=t.bufferViews.length-1}function Pi(e,t){let n;switch(t){case"Int8Array":n=new ArrayBuffer(e.length),new Int8Array(n).set(e);break;case"Uint8Array":n=new ArrayBuffer(e.length),new Uint8Array(n).set(e);break;case"Int16Array":n=new ArrayBuffer(e.length*2),new Int16Array(n).set(e);break;case"Uint16Array":n=new ArrayBuffer(e.length*2),new Uint16Array(n).set(e);break;case"Int32Array":n=new ArrayBuffer(e.length*4),new Int32Array(n).set(e);break;case"Uint32Array":n=new ArrayBuffer(e.length*4),new Uint32Array(n).set(e);break;default:case"Float32Array":n=new ArrayBuffer(e.length*4),new Float32Array(n).set(e);break}return n}function x4(e,t,n,i){const r=t.index.array;if(i!==void 0&&($n(r.buffer,e,i,34963,"index buffer view"),e.accessors[i].componentType=r1),t.attributes.POSITION!==void 0){const s=Pi(t.attributes.POSITION.array,t.attributes.POSITION.componentType);$n(s,e,n.POSITION,34962,"position buffer view")}if(t.attributes.NORMAL!==void 0){const s=Pi(t.attributes.NORMAL.array,t.attributes.NORMAL.componentType);$n(s,e,n.NORMAL,34962,"normal buffer view")}for(let s=0;s<l4;++s){const o=`TEXCOORD_${s}`;if(t.attributes[o]!==void 0){const a=Pi(t.attributes[o].array,t.attributes[o].componentType);$n(a,e,n[o],34962,`${o} buffer view`)}}if(t.attributes.TANGENT!==void 0){const s=Pi(t.attributes.TANGENT.array,t.attributes.TANGENT.componentType);$n(s,e,n.TANGENT,34962,"Tangent buffer view")}if(t.attributes.COLOR_0!==void 0){const s=Pi(t.attributes.COLOR_0.array,t.attributes.COLOR_0.componentType);$n(s,e,n.COLOR_0,34962,"color buffer view")}if(t.attributes.JOINTS_0!==void 0){const s=Pi(t.attributes.JOINTS_0.array,t.attributes.JOINTS_0.componentType);$n(s,e,n.JOINTS_0,34963,"JOINTS_0 buffer view")}if(t.attributes.WEIGHTS_0!==void 0){const s=Pi(t.attributes.WEIGHTS_0.array,t.attributes.WEIGHTS_0.componentType);$n(s,e,n.WEIGHTS_0,34963,"WEIGHTS_0 buffer view")}if(t.attributes.JOINTS_1!==void 0){const s=Pi(t.attributes.JOINTS_1.array,t.attributes.JOINTS_1.componentType);$n(s,e,n.JOINTS_1,34963,"JOINTS_1 buffer view")}if(t.attributes.WEIGHTS_1!==void 0){const s=Pi(t.attributes.WEIGHTS_1.array,t.attributes.WEIGHTS_1.componentType);$n(s,e,n.WEIGHTS_1,34963,"WEIGHTS_1 buffer view")}}function w4(e,t){return Fe(this,null,function*(){var n;if(!Array.isArray(e.meshes))return Promise.resolve();for(const i of e.meshes)if(Array.isArray(i.primitives))for(const r of i.primitives){if(((n=r.extensions)==null?void 0:n.KHR_draco_mesh_compression)===void 0)continue;uh||u4(t);const s=yield uh;if(!s)continue;const o=y4(r.extensions.KHR_draco_mesh_compression,e,s,r.attributes);x4(e,o,r.attributes,r.indices)}})}function dh(e){return Fe(this,null,function*(){const t=yield self.fetch(e);if(!t.ok)throw new Error(`${t.status} ${t.statusText}: ${t.url}`);return t})}const hh={asset:{version:""}};function A4(e,t){return Fe(this,null,function*(){if(t){e.buffers[0].buffer=t[0]||[];return}yield Promise.all(e.buffers.map(n=>Fe(null,null,function*(){if(n.buffer){console.error("Buffer is already loaded");return}if(!n.uri){console.error("Buffer can not be loaded. No uri");return}if(n.uri.startsWith("data:"))n.buffer=n1(n.uri);else{const i=wi(n.uri)?n.uri:t1(e.path)+n.uri,r=yield dh(i).then(s=>s.arrayBuffer());n.buffer=r}})))})}function b4(e,t,n){return Fe(this,null,function*(){var o;if(!t.bufferView)return!1;const i=e.bufferViews[t.bufferView];if(i===void 0)return!1;yield n;const r=e.buffers[i.buffer].buffer;if(!r)return!1;const s=new Uint8Array(r,i.byteOffset,i.byteLength);if(typeof createImageBitmap!="undefined")if(P4(s)){const a=new Blob([s],{type:t.mimeType});t.image=yield createImageBitmap(a)}else return console.error(`Unsupported image type ${(o=t.mimeType)!=null?o:""}`),!1;else return!1;return!0})}function S4(e,t){return Fe(this,null,function*(){if(t.uri===void 0)return!1;const n=t.mimeType||n4(t.uri);if(t.mimeType=n,typeof createImageBitmap!="undefined"&&(n===Xo.JPEG||n===Xo.PNG))if(t.uri.startsWith("data:image")){const i=n1(t.uri);t.image=yield createImageBitmap(new Blob([i],{type:n}))}else{const i=wi(t.uri)?t.uri:`${t1(e.path)}${t.uri}`,s=yield(yield dh(i)).arrayBuffer();t.image=yield createImageBitmap(new Blob([s],{type:n}))}else return console.error(`Unsupported image type ${n}`),!1;return!0})}function E4(e,t){return Fe(this,null,function*(){yield Promise.all(e.images.map(n=>Fe(null,null,function*(){if(n.image){n.mimeType!==Xo.GLTEXTURE&&console.error("Image has already been loaded");return}(yield b4(e,n,t))||(yield S4(e,n))||console.error(`Was not able to resolve image with uri ${n.uri}`)})))})}function T4(e,t){return Fe(this,null,function*(){const n=FA(e,self.origin);try{const i=yield dh(n);let r=hh,s;try{const o=yield i.arrayBuffer();if(xc.isGlb(o)){const d=new xc(o).extractGlbData();r=d.json,s=d.buffers}else{const u=new TextDecoder("utf-8"),d=new Uint8Array(o);r=JSON.parse(u.decode(d))}const a=UL(r,n),l=A4(a,s),c=E4(a,l),f=w4(a,t);return yield Promise.all([l,c,f]),{type:"ok",result:a}}catch(o){return{type:"error",layer:"parsing",originalError:o}}}catch(i){return{type:"error",layer:"network",originalError:i}}})}function P4(e){const t=e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71&&e[4]===13&&e[5]===10&&e[6]===26&&e[7]===10,n=e[0]===255&&e[1]===216&&e[2]===255;return t||n}function I4(e){const t=new Set;for(const{buffer:n}of e.buffers)n instanceof ArrayBuffer&&t.add(n);if(typeof ImageBitmap!="undefined")for(const{image:n}of e.images)n instanceof ImageBitmap&&t.add(n);return Array.from(t)}function M4(e){return ie(V({},e),{buffers:e.buffers.map(t=>{var n;if(t.buffer instanceof ArrayBuffer&&((n=t.uri)!=null&&n.startsWith("data:"))){const i=V({},t);return delete i.uri,i}return t}),images:e.images.map(t=>{var n;if(t.image&&((n=t.uri)!=null&&n.startsWith("data:"))){const i=V({},t);return delete i.uri,i}return t})})}class _4{loadModel(t,n){return Fe(this,null,function*(){const i=yield T4(t,n);return i.type!=="ok"?i:ie(V({},i),{result:M4(i.result),transferable:I4(i.result)})})}}class C4{constructor(t,n){this.scope=t,this.options=n,this.tileLoader=new kd("arrayBuffer"),this.tiles=new Map,this.url=i=>{const[r,s,o]=Ta(i);return fm(this.options,r,s,o,this.options.tileSet)}}abortTileFetches(t){this.tileLoader.abortRequests(t.map(De))}deleteTiles(t){t.forEach(n=>this.tiles.delete(De(n)))}generateTile(t,n){return Fe(this,null,function*(){const i=[],r=[],s=De(n),o=this.tiles.get(s);if(!o||!o.byteLength)return Promise.resolve({results:i,transferable:r,minZ:0,maxZ:0,tree:null,empty:!!(o&&!o.byteLength)});const a=nT(o);do Kt.generateMeshElevation(this.scope.collector,a,t,vo);while(this.scope.collector.isOverloaded());const l=this.scope.collector.getAccumulatedData();this.scope.resetCollector();const c=qE(l.data);return i.push({regionId:0,metatileHash:-1,styleId:t,collectorOutput:l}),r.push(...l.transferable),c&&r.push(c),Promise.resolve({results:i,tree:c,transferable:r,minZ:a.minZ,maxZ:a.maxZ,empty:!1})})}fetchTiles(t){return t.map(n=>this.fetchTile(n))}setOptions(t){this.options=t}fetchTile(t){const n=De(t),i=[{regionId:0,metatileHash:-1}];if(this.tiles.has(n))return Promise.resolve(i);const r=this.url(t);return this.tileLoader.fetch(t,()=>r).then(s=>(s.rejected||this.tiles.set(n,s.data?s.data:void 0),i),()=>Promise.resolve(void 0))}}function F4(e,t,n){var r;const i=(r=e[t])!=null?r:e[t]={count:0,total:0,max:0};i.count++,i.total+=n,i.max=Math.max(i.max,n)}function L4(e){if(e!=null&&e.aborted)throw new DOMException("Style preparation cancelled","AbortError")}class B4{constructor(t,n){this.port=t,this.handle=n,this.nextId=0,this.closed=!1,this.pending=new Map,t.onmessage=r=>Fe(this,[r],function*({data:i}){if("method"in i)try{const s=yield this.handle(i.method,i.data);this.closed||this.port.postMessage({id:i.id,result:s})}catch(s){this.closed||this.port.postMessage({id:i.id,error:String(s)})}else{const s=this.pending.get(i.id);this.pending.delete(i.id),i.error!==void 0?s==null||s.reject(new Error(i.error)):s==null||s.resolve(i.result)}})}request(t,n,i){if(this.closed)return Promise.reject(new Error("Style port closed"));const r=this.nextId++;return new Promise((s,o)=>{this.pending.set(r,{resolve:s,reject:o});try{const a=performance.now();this.port.postMessage({id:r,method:t,data:n}),i==null||i(performance.now()-a)}catch(a){this.pending.delete(r),o(a)}})}close(){this.closed=!0,this.port.close();for(const t of this.pending.values())t.reject(new Error("Style port closed"));this.pending.clear()}}function ph(e){return typeof SharedArrayBuffer!="undefined"&&e.buffer instanceof SharedArrayBuffer}function wc(e,t){return ph(e)?Atomics.load(e,t>>2):e[t>>2]}function Zo(e,t,n){ph(e)?Atomics.store(e,t>>2,n):e[t>>2]=n}function o1(e,t,n){if(ph(e))return Atomics.exchange(e,t>>2,n);const i=t>>2,r=e[i];return e[i]=n,r}function gh(e,t){return(e-t|0)>0}var a1=(e=>(e[e.WebGPU=0]="WebGPU",e))(a1||{}),mh=(e=>(e[e.WebGPU=0]="WebGPU",e))(mh||{});function l1(){return{showTileBounds:!1,aaMode:"msaa",waitForResources:!1,vramBudgetBytes:300*1024*1024}}const vh=cc-1;function or(e){return e+15&-16}var c1=(e=>(e[e.Pad=0]="Pad",e[e.UploadBuffer=1]="UploadBuffer",e[e.UploadTexture=2]="UploadTexture",e[e.DeleteBuffers=3]="DeleteBuffers",e[e.DeleteTextures=4]="DeleteTextures",e[e.SetConfig=5]="SetConfig",e[e.ClearAll=6]="ClearAll",e[e.CreateTexture=7]="CreateTexture",e[e.PatchTexture=8]="PatchTexture",e[e.CreateBuffer=9]="CreateBuffer",e[e.PatchBuffer=10]="PatchBuffer",e))(c1||{}),f1=(e=>(e[e.Id=16]="Id",e[e.Flags=20]="Flags",e[e.Stride=24]="Stride",e[e.ByteLength=28]="ByteLength",e[e.Data=32]="Data",e))(f1||{}),u1=(e=>(e[e.Id=16]="Id",e[e.Width=20]="Width",e[e.Height=24]="Height",e[e.ByteLength=28]="ByteLength",e[e.Data=32]="Data",e))(u1||{}),d1=(e=>(e[e.Id=16]="Id",e[e.X=20]="X",e[e.Y=24]="Y",e[e.W=28]="W",e[e.H=32]="H",e[e.ByteLength=36]="ByteLength",e[e.Data=40]="Data",e))(d1||{}),h1=(e=>(e[e.Id=16]="Id",e[e.ByteOffset=20]="ByteOffset",e[e.ByteLength=24]="ByteLength",e[e.Data=28]="Data",e))(h1||{});const D4=new TextEncoder,O4=new TextDecoder;class R4{constructor(t){this.u32=new Uint32Array(t),this.u8=new Uint8Array(t),this.writePos=wc(this.u32,tn.RingWritePos)}tryWriteUploadBuffer(t,n,i,r,s){const o=or(32+i.byteLength),a=this.reserve(o);return a<0?!1:(this.writeHeader(a,1,o,t),this.u32[a+16>>2]=n,this.u32[a+20>>2]=r?1:0,this.u32[a+24>>2]=s,this.u32[a+28>>2]=i.byteLength,this.u8.set(i,a+32),this.commit(o,t),!0)}tryWriteUploadTexture(t,n,i,r,s){const o=or(32+i.byteLength),a=this.reserve(o);return a<0?!1:(this.writeHeader(a,2,o,t),this.u32[a+16>>2]=n,this.u32[a+20>>2]=r,this.u32[a+24>>2]=s,this.u32[a+28>>2]=i.byteLength,this.u8.set(i,a+32),this.commit(o,t),!0)}tryWriteCreateTexture(t,n,i,r){const s=or(28),o=this.reserve(s);return o<0?!1:(this.writeHeader(o,7,s,t),this.u32[o+16>>2]=n,this.u32[o+20>>2]=i,this.u32[o+24>>2]=r,this.commit(s,t),!0)}tryWritePatchTexture(t,n,i,r,s,o,a){const l=or(40+i.byteLength),c=this.reserve(l);return c<0?!1:(this.writeHeader(c,8,l,t),this.u32[c+16>>2]=n,this.u32[c+20>>2]=r,this.u32[c+24>>2]=s,this.u32[c+28>>2]=o,this.u32[c+32>>2]=a,this.u32[c+36>>2]=i.byteLength,this.u8.set(i,c+40),this.commit(l,t),!0)}tryWriteCreateBuffer(t,n,i,r,s){const o=or(32),a=this.reserve(o);return a<0?!1:(this.writeHeader(a,9,o,t),this.u32[a+16>>2]=n,this.u32[a+20>>2]=i?1:0,this.u32[a+24>>2]=r,this.u32[a+28>>2]=s,this.commit(o,t),!0)}tryWritePatchBuffer(t,n,i,r){const s=or(28+i.byteLength),o=this.reserve(s);return o<0?!1:(this.writeHeader(o,10,s,t),this.u32[o+16>>2]=n,this.u32[o+20>>2]=r,this.u32[o+24>>2]=i.byteLength,this.u8.set(i,o+28),this.commit(s,t),!0)}tryWriteDeleteIds(t,n,i,r){const s=or(24+i.length*4),o=this.reserve(s);if(o<0)return!1;this.writeHeader(o,t,s,n),this.u32[o+16>>2]=r,this.u32[o+20>>2]=i.length;for(let a=0;a<i.length;a++)this.u32[(o+24>>2)+a]=i[a];return this.commit(s,n),!0}tryWriteSetConfig(t,n){const i=D4.encode(JSON.stringify(n)),r=or(20+i.byteLength),s=this.reserve(r);return s<0?!1:(this.writeHeader(s,5,r,t),this.u32[s+16>>2]=i.byteLength,this.u8.set(i,s+20),this.commit(r,t),!0)}tryWriteClearAll(t){const i=this.reserve(16);return i<0?!1:(this.writeHeader(i,6,16,t),this.commit(16,t),!0)}writeHeader(t,n,i,r){this.u32[t+0>>2]=n,this.u32[t+4>>2]=i,this.u32[t+8>>2]=r,this.u32[t+12>>2]=0}reserve(t){if(t>qd)return console.error(`[render][ring] record too big: ${t}`),-1;const n=this.writePos&vh,i=cc-n,r=t>i?i:0,s=wc(this.u32,tn.RingReadPos),o=cc-(this.writePos-s>>>0);if(r+t>o)return-1;if(r>0){const a=fc+n;this.writeHeader(a,0,r,0),this.writePos=this.writePos+r>>>0}return fc+(this.writePos&vh)}commit(t,n){this.writePos=this.writePos+t>>>0,Zo(this.u32,tn.RingWritePos,this.writePos),Zo(this.u32,tn.LedgerSeq,n)}}class z4{constructor(t){this._appliedSeq=0,this._blockedOnFence=!1,this.corrupted=!1,this.u32=new Uint32Array(t),this.u8=new Uint8Array(t),this.readPos=wc(this.u32,tn.RingReadPos)}get appliedSeq(){return this._appliedSeq}get blockedOnFence(){return this._blockedOnFence}drain(t,n=1/0,i=0){var l,c;if(this._blockedOnFence=!1,this.corrupted)return 0;const r=wc(this.u32,tn.RingWritePos);if(r===this.readPos)return 0;const s=n!==1/0?performance.now()+n:1/0,o=this.u32;let a=0;for(;this.readPos!==r&&!(s!==1/0&&performance.now()>=s);){const f=fc+(this.readPos&vh),u=o[f+0>>2],d=o[f+4>>2];if(d===0||d>qd||(d&15)!==0)return this.corrupted=!0,console.error(`[render][ring] corrupted record: type=${u}, size=${d}`),Zo(o,tn.RingReadPos,this.readPos),a;const h=o[f+8>>2];switch(u){case 0:break;case 1:t.uploadBuffer(o[f+16>>2],(o[f+20>>2]&1)!==0,o[f+24>>2],f+32,o[f+28>>2]);break;case 2:t.uploadTexture(o[f+16>>2],o[f+20>>2],o[f+24>>2],f+32,o[f+28>>2]);break;case 7:t.createTexture(o[f+16>>2],o[f+20>>2],o[f+24>>2]);break;case 8:t.patchTexture(o[f+16>>2],o[f+20>>2],o[f+24>>2],o[f+28>>2],o[f+32>>2],f+40,o[f+36>>2]);break;case 9:t.createBuffer(o[f+16>>2],(o[f+20>>2]&1)!==0,o[f+24>>2],o[f+28>>2]);break;case 10:t.patchBuffer(o[f+16>>2],o[f+20>>2],f+28,o[f+24>>2]);break;case 3:case 4:{const g=o[f+16>>2];if(g!==0&&gh(g,i))return this._blockedOnFence=!0,Zo(o,tn.RingReadPos,this.readPos),a;const y=o[f+20>>2],p=new Array(y);for(let v=0;v<y;v++)p[v]=o[(f+24>>2)+v];u===3?t.deleteBuffers(p):t.deleteTextures(p);break}case 5:{const g=o[f+16>>2],y=this.u8.slice(f+20,f+20+g);try{const p=JSON.parse(O4.decode(y));(l=t.setConfig)==null||l.call(t,V(V({},l1()),p))}catch(p){console.error("[render][ring] bad SetConfig payload",p)}break}case 6:(c=t.clearAll)==null||c.call(t);break}this.readPos=this.readPos+d>>>0,u!==0&&(a++,this._appliedSeq=h)}return Zo(o,tn.RingReadPos,this.readPos),a}}class N4{constructor(t){this.onIdentify=t}}const yh={r:.08,g:.1,b:.09,a:1},Gs=4,G4=new Float32Array([0,1,.5,.8]),p1=128,k4=8,Ac=3,g1=p1*k4*Ac,m1=20,U4=m1*Float32Array.BYTES_PER_ELEMENT,v1=40,V4=v1*Float32Array.BYTES_PER_ELEMENT,y1=36,W4=y1*Float32Array.BYTES_PER_ELEMENT,x1=44,ar=x1*Float32Array.BYTES_PER_ELEMENT,H4=8,Y4=1e-4,w1=52,X4=w1*Float32Array.BYTES_PER_ELEMENT,A1=60,Z4=A1*Float32Array.BYTES_PER_ELEMENT,b1=48,j4=b1*Float32Array.BYTES_PER_ELEMENT,S1=60,Q4=S1*Float32Array.BYTES_PER_ELEMENT,E1=80,q4=E1*Float32Array.BYTES_PER_ELEMENT,K4=512,T1=44,J4=T1*Float32Array.BYTES_PER_ELEMENT,Ii="rgba8unorm",P1=32,$4=P1*Float32Array.BYTES_PER_ELEMENT,I1=48,eB=I1*Float32Array.BYTES_PER_ELEMENT,M1=36,tB=M1*Float32Array.BYTES_PER_ELEMENT,nB=256,Gt="depth24plus",jo="rgba16float",_1=16,iB=_1*Float32Array.BYTES_PER_ELEMENT,C1=48,rB=C1*Float32Array.BYTES_PER_ELEMENT,F1=56,sB=F1*Float32Array.BYTES_PER_ELEMENT,L1=72,oB=L1*Float32Array.BYTES_PER_ELEMENT,aB=512,B1=60,lB=B1*Float32Array.BYTES_PER_ELEMENT,xh=20,Nn=xh*Float32Array.BYTES_PER_ELEMENT,D1=12,xt=D1*Float32Array.BYTES_PER_ELEMENT,cB=16,O1=12,R1=28,z1=R1*Float32Array.BYTES_PER_ELEMENT,wh=24,fB=wh,N1=2048,G1=1e-6,uB=1e-7,dB=2,bc=4*Float32Array.BYTES_PER_ELEMENT,k1=36,U1=k1*Float32Array.BYTES_PER_ELEMENT,Sc=2e4,hB=12345,pB=16,V1=20,W1=V1*Float32Array.BYTES_PER_ELEMENT,Ah=20,H1=Ah*Float32Array.BYTES_PER_ELEMENT,Y1=80,gB=Y1*Float32Array.BYTES_PER_ELEMENT,mB=512,vB=48,yB=64,xB=_i/ot,X1=44,wB=X1*Float32Array.BYTES_PER_ELEMENT,AB=new Float64Array([2,0,0,0,0,2,0,0,0,0,1,0,-1,-1,0,1]),Z1=1.7,j1=1,Ec=1.3,Tc=2;function Q1(e){return Math.max(1,Math.trunc(e.width*Z1))}function q1(e){return Math.max(1,Math.trunc(e.height*j1))}function nn(e,t,n){const i=typeof n=="function"?n:()=>n;let r=null,s=-1,o=null;for(const a of t){a.pipeline!==r&&(e.setPipeline(a.pipeline),r=a.pipeline);const l=i(a);l&&e.setBindGroup(0,l,[a.uniformOffset]),a.textureBindGroup&&a.textureBindGroup!==o&&(e.setBindGroup(1,a.textureBindGroup),o=a.textureBindGroup),s!==a.vertexBufferId&&(e.setVertexBuffer(0,a.vertexBuffer),s=a.vertexBufferId),e.draw(a.vertexCount,1,a.vertexOffset,0)}}function bh(e,t,n,i,r){K1(e,t,n,i,r,s=>{var o;return(o=s.haloPipeline)!=null?o:null}),K1(e,t,n,i,r,s=>s.pipeline)}function K1(e,t,n,i,r,s){let o=null,a=-1;for(let l=n;l<i;l++){const c=t[l],f=s(c);f&&(f!==o&&(e.setPipeline(f),o=f),r&&e.setBindGroup(0,r,[c.uniformOffset]),c.textureBindGroup&&e.setBindGroup(1,c.textureBindGroup),a!==c.vertexBufferId&&(e.setVertexBuffer(0,c.vertexBuffer),a=c.vertexBufferId),e.draw(c.vertexCount,1,c.vertexOffset,0))}}function J1(e,t,n){const i=typeof n=="function"?n:()=>n;let r=null,s=null;for(const o of t){o.pipeline!==r&&(e.setPipeline(o.pipeline),r=o.pipeline);const a=i(o);a&&e.setBindGroup(0,a,[o.uniformOffset]),o.colorBindGroup&&o.colorBindGroup!==s&&(e.setBindGroup(2,o.colorBindGroup),s=o.colorBindGroup),e.setVertexBuffer(0,o.vertexBuffer),e.setVertexBuffer(1,o.instanceBuffer,o.instanceOffset),e.setIndexBuffer(o.indexBuffer,o.indexFormat),e.drawIndexed(o.indexCount,o.instanceCount,0,0,0)}}function $1(e,t){return{draws:[],flatDrawsByLevel:Array.from({length:e},()=>[]),terrainDrawsByLevel:Array.from({length:e},()=>[]),flatLevelMask:t,tierDraws:new Map,hiddenTierDraws:new Map,hasMapMesh:!1,mapMeshTiers:new Set}}function ex(e){if(!e.hasMapMesh)return new Set;const t=new Set(e.mapMeshTiers);for(const n of e.tierDraws.keys())t.add(n);return t.size===0&&t.add(0),t}function bB(e,t){let n=e.get(t);return n||(n=[],e.set(t,n)),n}const tx=256,SB={r:1,g:1,b:1,a:1};function EB(e,t,n,i){const r=t*4,s=new Uint8Array(r*n);for(let o=0;o<n;o++){const a=o*i;s.set(e.subarray(a,a+r),(n-1-o)*r)}return s}function nx(e,t,n,i){const r={width:Math.max(1,Math.trunc(t)),height:Math.max(1,Math.trunc(n))},s=e.createTexture({size:r,format:Ii,usage:GPUTextureUsage.RENDER_ATTACHMENT|i}),o=e.createTexture({size:r,format:Gt,usage:GPUTextureUsage.RENDER_ATTACHMENT});return{texture:s,view:s.createView(),depthTexture:o,depthView:o.createView()}}function TB(e){e.texture.destroy(),e.depthTexture.destroy()}function Sh(e,t){return e.beginRenderPass({colorAttachments:[{view:t.view,clearValue:SB,loadOp:"clear",storeOp:"store"}],depthStencilAttachment:{view:t.depthView,depthClearValue:1,depthLoadOp:"clear",depthStoreOp:"discard"}})}class PB{constructor(t){this.deps=t,this.target=null,this.readBuffer=null,this.width=0,this.height=0,this.bytesPerRow=0,this.tierTargets=new Map,this.flatTargets=new Map,this.lastServedId=0,this.busy=!1}wants(t){return t&&t.id!==this.lastServedId&&!this.busy?t:null}encode(t,n,i,r){var c,f,u,d;this.lastServedId=r.id;const s=this.ensure(n,r.width,r.height),{deps:o}=this;for(const h of ex(i)){const g=Sh(t,this.tierTarget(n,h));o.drawCanvasContent(g,(c=i.tierDraws.get(h))!=null?c:[]),g.end()}for(const h of i.draws)h.kind==="mapMesh"&&(h.textureBindGroup=o.mapMeshTierBindGroup(n,this.tierTarget(n,(f=h.tier)!=null?f:0).view));const a=[];for(let h=0;h<i.flatDrawsByLevel.length;h++){const g=i.flatDrawsByLevel[h];if(g.length===0&&i.terrainDrawsByLevel[h].length===0)continue;a.push(h);const y=Sh(t,this.flatTarget(n,h));o.drawCanvasContent(y,g),y.end()}const l=Sh(t,s);for(const h of a){const g=i.terrainDrawsByLevel[h],y=g.length>0?o.demTerrainPass.getIdentifyTextureBindGroup(n,this.flatTarget(n,h).view):null;y&&(l.setBindGroup(1,y),nn(l,g,(d=(u=o.demTerrainPass.batch)==null?void 0:u.bindGroup)!=null?d:null))}o.drawCanvasContent(l,i.draws),l.end(),t.copyTextureToBuffer({texture:s.texture},{buffer:this.readBuffer,bytesPerRow:this.bytesPerRow},[this.width,this.height]),this.busy=!0}read(){return Fe(this,null,function*(){const t=this.readBuffer,{width:n,height:i,bytesPerRow:r}=this;try{yield t.mapAsync(GPUMapMode.READ);const s=EB(new Uint8Array(t.getMappedRange()),n,i,r);return t.unmap(),{width:n,height:i,pixels:s}}finally{this.busy=!1}})}ensure(t,n,i){var r;if(this.target&&this.width===n&&this.height===i)return this.target;for(const s of[...this.target?[this.target]:[],...this.tierTargets.values(),...this.flatTargets.values()])TB(s);return this.tierTargets.clear(),this.flatTargets.clear(),(r=this.readBuffer)==null||r.destroy(),this.width=n,this.height=i,this.bytesPerRow=Math.ceil(n*4/tx)*tx,this.readBuffer=t.createBuffer({size:this.bytesPerRow*i,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.target=nx(t,n,i,GPUTextureUsage.COPY_SRC),this.target}tierTarget(t,n){return this.scaledTarget(t,this.tierTargets,n,Ec,Tc)}flatTarget(t,n){return this.scaledTarget(t,this.flatTargets,n,Z1,j1)}scaledTarget(t,n,i,r,s){let o=n.get(i);return o||(o=nx(t,this.width*r,this.height*s,GPUTextureUsage.TEXTURE_BINDING),n.set(i,o)),o}}function Pc(e,t,n,i){let r=null,s=-1;for(const o of t){if(o.kind!==n)continue;const{labelingPipeline:a}=o;a&&(a!==r&&(e.setPipeline(a),r=a),i&&e.setBindGroup(0,i,[o.uniformOffset]),s!==o.vertexBufferId&&(e.setVertexBuffer(0,o.vertexBuffer),s=o.vertexBufferId),e.draw(o.vertexCount,1,o.vertexOffset,0))}}class IB{constructor(){this.views={color:null,depth:null,sprite:null,revision:0},this.colorTexture=null,this.depthTexture=null,this.spriteTexture=null,this.width=0,this.height=0}get created(){return this.colorTexture!==null}ensure(t){var o,a,l;const n=Math.max(1,t.canvas.width),i=Math.max(1,t.canvas.height);if(this.colorTexture&&this.width===n&&this.height===i)return this.views;const{device:r}=t;(o=this.colorTexture)==null||o.destroy(),(a=this.depthTexture)==null||a.destroy(),(l=this.spriteTexture)==null||l.destroy();const s=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING;return this.colorTexture=r.createTexture({size:{width:n,height:i},format:Ii,usage:s}),this.depthTexture=r.createTexture({size:{width:n,height:i},format:Gt,usage:s}),this.spriteTexture=r.createTexture({size:{width:n,height:i},format:Ii,usage:s}),this.views.color=this.colorTexture.createView(),this.views.depth=this.depthTexture.createView(),this.views.sprite=this.spriteTexture.createView(),this.views.revision++,this.width=n,this.height=i,this.views}drawOcclusionPass(t,n,i,r,s){var f,u,d,h,g,y;if(!this.views.color||!this.views.depth)return;const o=t.beginRenderPass({colorAttachments:[{view:this.views.color,clearValue:{r:1,g:1,b:1,a:1},loadOp:"clear",storeOp:"store"}],depthStencilAttachment:{view:this.views.depth,depthClearValue:1,depthLoadOp:"clear",depthStoreOp:"store"}}),a=(u=(f=i.batch)==null?void 0:f.bindGroup)!=null?u:null,l=i.demGroup.bindGroup;l&&o.setBindGroup(1,l),Pc(o,n.draws,"extrusion",a),Pc(o,n.extrusion,"extrusion",a);const c=(h=(d=r.batch)==null?void 0:d.bindGroup)!=null?h:null;if(r.demGroup.bindGroup&&o.setBindGroup(1,r.demGroup.bindGroup),Pc(o,n.draws,"mesh",c),Pc(o,n.meshDraws,"mesh",c),n.labelingAnchors.length>0){const p=s.demGroup.bindGroup;p&&o.setBindGroup(1,p),nn(o,n.labelingAnchors,(y=(g=s.batch)==null?void 0:g.bindGroup)!=null?y:null)}o.end()}drawSpritePass(t,n,i){var o,a;if(!this.views.sprite)return;const r=t.beginRenderPass({colorAttachments:[{view:this.views.sprite,clearValue:{r:1,g:1,b:1,a:1},loadOp:"clear",storeOp:"store"}]}),s=i.demGroup.bindGroup;s&&r.setBindGroup(2,s),nn(r,n.spriteOcclusion,(a=(o=i.batch)==null?void 0:o.bindGroup)!=null?a:null),r.end()}}var Z=(e=>(e[e.TileBounds=0]="TileBounds",e[e.PolygonFill=1]="PolygonFill",e[e.LineColor=2]="LineColor",e[e.LineSolid=3]="LineSolid",e[e.LineShifted=4]="LineShifted",e[e.LineStripe=5]="LineStripe",e[e.LinePattern=6]="LinePattern",e[e.LineSolid3d=7]="LineSolid3d",e[e.LineStripe3d=8]="LineStripe3d",e[e.LinePattern3d=9]="LinePattern3d",e[e.LineTopStroke=10]="LineTopStroke",e[e.LineSideStroke=11]="LineSideStroke",e[e.LineOneWay=12]="LineOneWay",e[e.LineArrow=13]="LineArrow",e[e.PointSprite=14]="PointSprite",e[e.LabelPoint=15]="LabelPoint",e[e.LabelLine=16]="LabelLine",e[e.PolygonExtrusionLabeling=17]="PolygonExtrusionLabeling",e[e.PointAnchor=18]="PointAnchor",e[e.PointSpriteLabeling=19]="PointSpriteLabeling",e[e.MetricPoint=20]="MetricPoint",e[e.CircleMarker=21]="CircleMarker",e[e.DemElevation=22]="DemElevation",e[e.DemTerrain=23]="DemTerrain",e[e.MapMesh=24]="MapMesh",e[e.PolygonExtrusion=25]="PolygonExtrusion",e[e.PolygonExtrusionGradient=26]="PolygonExtrusionGradient",e[e.PolygonExtrusionTexture=27]="PolygonExtrusionTexture",e[e.GltfModel=28]="GltfModel",e[e.PolygonExtrusionDepth=29]="PolygonExtrusionDepth",e[e.PolygonExtrusionGradientWall=30]="PolygonExtrusionGradientWall",e[e.Stars=31]="Stars",e[e.GlobeHalo=32]="GlobeHalo",e[e.GlobeHaloBackground=33]="GlobeHaloBackground",e[e.PolygonFillTexture=34]="PolygonFillTexture",e[e.Sky=35]="Sky",e[e.Fxaa=36]="Fxaa",e[e.SmaaEdge=37]="SmaaEdge",e[e.SmaaWeight=38]="SmaaWeight",e[e.SmaaBlend=39]="SmaaBlend",e[e.Mesh=40]="Mesh",e))(Z||{}),kt=(e=>(e[e.Plain=0]="Plain",e[e.LineSolid=1]="LineSolid",e[e.LineArrow=2]="LineArrow",e[e.MapMeshTexel=3]="MapMeshTexel",e[e.DemTerrainTexel=4]="DemTerrainTexel",e))(kt||{}),q=(e=>(e[e.Vertex=0]="Vertex",e[e.Fragment=1]="Fragment",e))(q||{});function ix(e,t,n){const i=JSON.stringify(n!=null?n:{});return`${e}:${t}:${i}`}const MB=`struct Uniforms {
    mvpMatrix: mat4x4f,
    color: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;

@vertex
fn main(@location(0) position: vec3f) -> @builtin(position) vec4f {
    return uniforms.mvpMatrix * vec4f(position, 1.0);
}
`,_B=`struct Uniforms {
    mvpMatrix: mat4x4f,
    color: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;

@fragment
fn main() -> @location(0) vec4f {
    return uniforms.color;
}
`,CB=`struct Uniforms {
    mvpMatrix: mat4x4f,
    color1: vec4f,
    color2: vec4f,
    factorParams: vec4f,
    factorRange: vec4f,
    // x = crossfade глобуса (0 = плоско, ECEF-путь не активен); y = подъём этажа
    // (маппоинты, порт u_float_floor_elevation); z/w — резерв
    globeParams: vec4f,
    // xyz = (тайл − камера)/fogDistance, w = масштаб тайла/fogDistance; нули = туман выключен
    fogOrigin: vec4f,
};

struct VertexOutput {
    @builtin(position) position: vec4f,
    // Порт v_fog_pos: (world_pos − cam_pos)/fog_distance
    @location(0) fogPos: vec3f,
    // id объекта (localID) — читает только identify.frag; основной фрагментник игнорирует
    @location(15) @interpolate(flat) identifier: vec4f,
};

// Общий на кадр uniform глобуса (порт include/ecef_mvp_mat.vsh).
struct GlobeUniforms {
    ecefMvp: mat4x4f,
    vp: mat4x4f,
    // xy = [lng (рад), mercatorY] центра камеры
    cameraMercator: vec4f,
    // viewProjection × центр карты, посчитанный в f64 на CPU (якорь flat-реконструкции)
    vpAtCenter: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
// binding 1 — свет (LightBlock), используется только фрагментом; здесь не объявляем.
@group(0) @binding(2) var<uniform> globe: GlobeUniforms;

const ECEF_CF_NEAR: f32 = 0.01;
const ECEF_WORLD: f32 = 4294967296.0; // 2^32 = worldSize: нормировка ECEF
const ECEF_PI: f32 = 3.141592653589793;
const ECEF_TWO_PI: f32 = 6.283185307179586;
const ECEF_MAX_LAT: f32 = 1.4844222; // ~85.05° (web-mercator clamp)

fn ecefWrapPi(a: f32) -> f32 {
    return ((a + ECEF_PI) % ECEF_TWO_PI) - ECEF_PI;
}

// Origin-relative flat clip из нормализованной ECEF-позиции [-0.5..0.5]. Считает
// смещение от центра камеры (мелкое — точность f32) и добавляет f64-якорь vpAtCenter.
fn ecefFlatClip(epos: vec3f) -> vec4f {
    let en = normalize(epos);
    let lng = atan2(en.x, en.z);
    let lat = clamp(asin(clamp(en.y, -1.0, 1.0)), -ECEF_MAX_LAT, ECEF_MAX_LAT);
    let mercY = log(tan(ECEF_PI / 4.0 + lat / 2.0));
    let dLng = ecefWrapPi(lng - globe.cameraMercator.x);
    let relX = dLng / ECEF_TWO_PI * ECEF_WORLD;
    let relY = (mercY - globe.cameraMercator.y) / ECEF_TWO_PI * ECEF_WORLD;
    return globe.vp * vec4f(relX, relY, 0.0, 0.0) + globe.vpAtCenter;
}

// Кроссфейд flat↔globe из нормализованной ECEF-позиции (vertex - 0.5). Гистерезис
// ECEF_CF_NEAR: близко к 0 — чистый flat, близко к 1 — чистый ECEF, иначе mix.
fn ecefClip(epos: vec3f, crossfade: f32) -> vec4f {
    if (crossfade > 1.0 - ECEF_CF_NEAR) {
        return globe.ecefMvp * vec4f(epos * ECEF_WORLD, 1.0);
    }
    if (crossfade < ECEF_CF_NEAR) {
        return ecefFlatClip(epos);
    }
    let fclip = ecefFlatClip(epos);
    let eclip = globe.ecefMvp * vec4f(epos * ECEF_WORLD, 1.0);
    return mix(fclip, eclip, crossfade);
}

@vertex
fn main(@location(0) pos: vec4f, @location(1) identifier: vec4f) -> VertexOutput {
    var out: VertexOutput;
    out.identifier = identifier;
    let crossfade = uniforms.globeParams.x;
    if (crossfade > 0.0) {
        // ECEF-тайл: позиция закодирована как u16-ECEF (DECODE_ECEF = pos - 0.5).
        // Туман на глобусе выключен (fogOrigin нулевой) — fogPos не считаем.
        out.position = ecefClip(pos.xyz - vec3f(0.5), crossfade);
        out.fogPos = vec3f(0.0);
        return out;
    }
    // Плоская карта: позиция — нормализованные тайловые координаты (xy)
    out.position = uniforms.mvpMatrix * vec4f(pos.x, pos.y, uniforms.globeParams.y, 1.0);
    out.fogPos = uniforms.fogOrigin.xyz + vec3f(pos.xy, 0.0) * uniforms.fogOrigin.w;
    return out;
}
`,FB=`struct Uniforms {
    mvpMatrix: mat4x4f,
    color1: vec4f,
    color2: vec4f,
    factorParams: vec4f,
    factorRange: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(0) @binding(1) var<uniform> light: LightBlock;
// binding 2 — глобус, только вершинная стадия; FogBlock — chunk fog.wgsl
@group(0) @binding(3) var<uniform> fog: FogBlock;
// Тени кадра — chunk shadow.wgsl (ShadowBlock + карта теней + comparison-сэмплер)
@group(0) @binding(4) var<uniform> shadow: ShadowBlock;
@group(0) @binding(5) var shadowTex: texture_depth_2d;
@group(0) @binding(6) var shadowSampler: sampler_comparison;

@fragment
fn main(@builtin(position) fragCoord: vec4f, @location(0) fogPos: vec3f) -> @location(0) vec4f {
    // color1 premultiplied — свет множит только rgb (как у extrusion)
    let color = vec4f(uniforms.color1.rgb * surfaceLight(fragCoord), uniforms.color1.a);
    // Порт apply_fog из color.fsh
    return applyFog(fog, color, fogPos);
}
`,LB=`// Текстурированная заливка полигона (style.textureImage) — вершинник polygonFill
// + текстурная координата (порт color.vsh v_vec2_texcoord). ECEF/глобус — chunk ecef.

struct Uniforms {
    mvpMatrix: mat4x4f,
    color1: vec4f,
    // Пер-тайловые offset/mul текстурных координат (порт u_float_texture_params)
    texParams: vec4f,
    // uv-прямоугольник растра в атласе (порт u_float_sprite_texture_coords)
    spriteCoords: vec4f,
    // x = textureOpacity, y = crossfade глобуса (0 = плоско), z = подъём этажа (маппоинты);
    // w — резерв
    miscParams: vec4f,
    // xyz = (тайл − камера)/fogDistance, w = масштаб тайла/fogDistance; нули = туман выключен
    fogOrigin: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
// binding 1 — свет (LightBlock), используется только фрагментом; здесь не объявляем.
@group(0) @binding(2) var<uniform> globe: GlobeUniforms;

struct VertexOutput {
    @builtin(position) position: vec4f,
    @location(0) texcoord: vec2f,
    // Порт v_fog_pos: (world_pos − cam_pos)/fog_distance
    @location(1) fogPos: vec3f,
};

@vertex
fn main(@location(0) pos: vec4f) -> VertexOutput {
    var out: VertexOutput;
    let crossfade = uniforms.miscParams.y;
    if (crossfade > 0.0) {
        // ECEF-тайл: позиция закодирована как u16-ECEF (DECODE_ECEF = pos - 0.5)
        out.position = ecefClip(pos.xyz - vec3f(0.5), crossfade);
        // Туман на глобусе выключен (fogOrigin нулевой)
        out.fogPos = vec3f(0.0);
    } else {
        // Плоская карта: позиция — нормализованные тайловые координаты (xy)
        out.position = uniforms.mvpMatrix * vec4f(pos.x, pos.y, uniforms.miscParams.z, 1.0);
        out.fogPos = uniforms.fogOrigin.xyz + vec3f(pos.xy, 0.0) * uniforms.fogOrigin.w;
    }
    // Порт color.vsh: тайловые координаты [0..1] → текстурные с учётом 2^15-адресации
    // (0.25 → 0.0, 0.5 → 0.5, 0.75 → 0.0 — модуль и дробная часть)
    out.texcoord = fract(abs((pos.xy - vec2f(0.25)) * 2.0));
    return out;
}
`,BB=`// Текстурированная заливка полигона — порт textured_color.fsh (ветка
// u_int_is_textured == 1, без карты нормалей): тайлящийся спрайт из атласа
// блендится поверх базового цвета, затем свет плоской поверхности.

struct Uniforms {
    mvpMatrix: mat4x4f,
    color1: vec4f,
    texParams: vec4f,
    spriteCoords: vec4f,
    // x = textureOpacity, y = crossfade глобуса
    miscParams: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(0) @binding(1) var<uniform> light: LightBlock;
// binding 2 — глобус, только вершинная стадия; FogBlock — chunk fog.wgsl
@group(0) @binding(3) var<uniform> fog: FogBlock;
// Тени кадра — chunk shadow.wgsl (ShadowBlock + карта теней + comparison-сэмплер)
@group(0) @binding(4) var<uniform> shadow: ShadowBlock;
@group(0) @binding(5) var shadowTex: texture_depth_2d;
@group(0) @binding(6) var shadowSampler: sampler_comparison;
@group(1) @binding(0) var atlasSampler: sampler;
@group(1) @binding(1) var atlasTex: texture_2d<f32>;

@fragment
fn main(
    @builtin(position) fragCoord: vec4f,
    @location(0) texcoord: vec2f,
    @location(1) fogPos: vec3f,
) -> @location(0) vec4f {
    // Тайлинг + перевод в uv атласа (порт textured_color.fsh)
    let tiled = fract(texcoord * uniforms.texParams.zw + uniforms.texParams.xy);
    let spritecoord = mix(uniforms.spriteCoords.xy, uniforms.spriteCoords.zw, tiled);
    // Атлас-зеркало заливается со straight-альфой — премультипликация здесь
    // (WebGL заливает премультиплицированную текстуру), затем apply_opacity
    let raw = textureSample(atlasTex, atlasSampler, spritecoord);
    let texcolor = vec4f(raw.rgb * raw.a, raw.a) * uniforms.miscParams.x;
    // Блендинг текстуры поверх базового цвета (оба premultiplied)
    let color = texcolor + uniforms.color1 * (1.0 - texcolor.a);
    // Порт apply_fog из textured_color.fsh
    return applyFog(fog, vec4f(color.rgb * surfaceLight(fragCoord), color.a), fogPos);
}
`,DB=`// Порт simple_line_2d.vsh (polygon.stroke, Solid12): экструзия в screen-space
// по direction/distance + ecef-ветка глобуса (include/ecef_mvp_mat.vsh) —
// на ECEF-тайлах позиция закодирована как u16-ECEF, направление — 3D в ECEF.
// Jitter/shadow исходника не портированы.
struct Uniforms {
    mvpMatrix: mat4x4f,
    color: vec4f,
    params: vec4f,
    // x = crossfade глобуса (0 = плоско, ECEF-путь не активен), y = ecefScale (не используется
    // Solid12 — экструзия целиком экранная), z = подъём этажа (маппоинты); w — резерв
    globeParams: vec4f,
    // xyz = (тайл − камера)/fogDistance, w = масштаб тайла/fogDistance; нули = туман выключен
    fogOrigin: vec4f,
};

// Общий на кадр uniform глобуса (порт include/ecef_mvp_mat.vsh, см. polygonFill.vert).
struct GlobeUniforms {
    ecefMvp: mat4x4f,
    vp: mat4x4f,
    // xy = [lng (рад), mercatorY] центра камеры
    cameraMercator: vec4f,
    // viewProjection × центр карты, посчитанный в f64 на CPU (якорь flat-реконструкции)
    vpAtCenter: vec4f,
    // xyz = позиция камеры в ECEF-единицах радиуса сферы (горизонт-тест)
    cameraEcef: vec4f,
};

struct VertexOutput {
    @builtin(position) position: vec4f,
    @location(0) distance: f32,
    @location(1) distanceOffset: f32,
    // Порт v_fog_pos: (world_pos − cam_pos)/fog_distance
    @location(2) fogPos: vec3f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
// binding 1 — свет (LightBlock), используется только фрагментом; здесь не объявляем.
@group(0) @binding(2) var<uniform> globe: GlobeUniforms;

const NORMAL_UNPACK_MULTIPLIER = 0.011135539861205473;
const SMOOTH_WIDTH = 1.0;
const MIN_DENOMINATOR = 1e-4;
const W_FACTOR = 1e-6;

const ECEF_CF_NEAR: f32 = 0.01;
const ECEF_WORLD: f32 = 4294967296.0; // 2^32 = worldSize: нормировка ECEF
const ECEF_PI: f32 = 3.141592653589793;
const ECEF_TWO_PI: f32 = 6.283185307179586;
const ECEF_MAX_LAT: f32 = 1.4844222; // ~85.05° (web-mercator clamp)

fn ecefWrapPi(a: f32) -> f32 {
    return ((a + ECEF_PI) % ECEF_TWO_PI) - ECEF_PI;
}

// Origin-relative flat clip из нормализованной ECEF-позиции [-0.5..0.5]. Считает
// смещение от центра камеры (мелкое — точность f32) и добавляет f64-якорь vpAtCenter.
fn ecefFlatClip(epos: vec3f) -> vec4f {
    let en = normalize(epos);
    let lng = atan2(en.x, en.z);
    let lat = clamp(asin(clamp(en.y, -1.0, 1.0)), -ECEF_MAX_LAT, ECEF_MAX_LAT);
    let mercY = log(tan(ECEF_PI / 4.0 + lat / 2.0));
    let dLng = ecefWrapPi(lng - globe.cameraMercator.x);
    let relX = dLng / ECEF_TWO_PI * ECEF_WORLD;
    let relY = (mercY - globe.cameraMercator.y) / ECEF_TWO_PI * ECEF_WORLD;
    return globe.vp * vec4f(relX, relY, 0.0, 0.0) + globe.vpAtCenter;
}

// Кроссфейд flat↔globe из нормализованной ECEF-позиции (vertex - 0.5). Гистерезис
// ECEF_CF_NEAR: близко к 0 — чистый flat, близко к 1 — чистый ECEF, иначе mix.
fn ecefClip(epos: vec3f, crossfade: f32) -> vec4f {
    if (crossfade > 1.0 - ECEF_CF_NEAR) {
        return globe.ecefMvp * vec4f(epos * ECEF_WORLD, 1.0);
    }
    if (crossfade < ECEF_CF_NEAR) {
        return ecefFlatClip(epos);
    }
    let fclip = ecefFlatClip(epos);
    let eclip = globe.ecefMvp * vec4f(epos * ECEF_WORLD, 1.0);
    return mix(fclip, eclip, crossfade);
}

fn safeNormalize4(value: vec4f) -> vec4f {
    let len = length(value);
    if (len > 0.0) {
        return value / len;
    }
    return vec4f(0.0);
}

@vertex
fn main(@location(0) pos: vec4f, @location(1) directionDistance: vec4i) -> VertexOutput {
    let width = uniforms.params.z;
    let shiftPixels = 0.5 * max(width - 1.0, 0.0);
    let shiftPixelsAdded = shiftPixels + SMOOTH_WIDTH;
    let distance = f32(directionDistance.w);

    let halfViewport = max(uniforms.params.xy * 0.5, vec2f(1.0));
    let direction = vec3f(directionDistance.xyz) * NORMAL_UNPACK_MULTIPLIER;

    // Порт simple_line_2d.vsh: на ECEF-тайле вершина — u16-ECEF (crossfade-микс),
    // направление 3D — через чистый ecef_mvp (mvp = is_flat ? flat : ecef)
    let crossfade = uniforms.globeParams.x;
    var clipSpaceVertex: vec4f;
    var clipSpaceDirection: vec4f;
    // Порт calc_fog_pos: на глобусе fogOrigin нулевой (туман выключен); экранную
    // экструзию не учитываем — субпиксельная поправка для тумана незначима
    var fogPos = uniforms.fogOrigin.xyz + vec3f(pos.xy, 0.0) * uniforms.fogOrigin.w;
    if (crossfade > 0.0) {
        fogPos = vec3f(0.0);
        let epos = pos.xyz - vec3f(0.5);
        // Горизонт-тест задней полусферы: экструзия Solid12 экранная, винтаж треугольников
        // на обратной стороне сферы НЕ переворачивается (back-cull бессилен) — коллапсируем
        // вершины за горизонтом (точка сферы видима ⇔ dot(p̂, camera) > 1 в единицах радиуса).
        // Только чистый ECEF: во время crossfade-перехода карта ещё плоская.
        if (crossfade > 1.0 - ECEF_CF_NEAR && dot(normalize(epos), globe.cameraEcef.xyz) < 1.0) {
            var hidden: VertexOutput;
            hidden.position = vec4f(0.0, 0.0, 1.0, 1.0);
            hidden.distance = 0.0;
            hidden.distanceOffset = 0.0;
            return hidden;
        }
        clipSpaceVertex = ecefClip(epos, crossfade);
        clipSpaceDirection = safeNormalize4(globe.ecefMvp * vec4f(direction, 0.0));
    } else {
        clipSpaceVertex = uniforms.mvpMatrix * vec4f(pos.xy, uniforms.globeParams.z, 1.0);
        clipSpaceDirection = safeNormalize4(uniforms.mvpMatrix * vec4f(direction, 0.0));
    }

    let screenSpaceDirection =
        (clipSpaceDirection.xy * clipSpaceVertex.w - clipSpaceVertex.xy * clipSpaceDirection.w) *
        halfViewport;
    let screenSpacePerp = vec2f(-screenSpaceDirection.y, screenSpaceDirection.x);
    let denominator = max(MIN_DENOMINATOR, length(screenSpacePerp));

    var output: VertexOutput;
    output.position =
        W_FACTOR *
        (clipSpaceVertex +
            vec4f(screenSpacePerp / halfViewport, 0.0, 0.0) *
                distance *
                shiftPixelsAdded /
                denominator *
                clipSpaceVertex.w);
    output.position.z += uniforms.params.w;
    output.distance = shiftPixelsAdded * distance * output.position.w;
    output.distanceOffset = shiftPixels;
    output.fogPos = fogPos;
    return output;
}
`,OB=`struct Uniforms {
    mvpMatrix: mat4x4f,
    color: vec4f,
    params: vec4f,
};

struct FragmentInput {
    @builtin(position) fragCoord: vec4f,
    @location(0) distance: f32,
    @location(1) distanceOffset: f32,
    @location(2) fogPos: vec3f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(0) @binding(1) var<uniform> light: LightBlock;
// binding 2 — глобус, только вершинная стадия; FogBlock — chunk fog.wgsl
@group(0) @binding(3) var<uniform> fog: FogBlock;
// Тени кадра — chunk shadow.wgsl (ShadowBlock + карта теней + comparison-сэмплер)
@group(0) @binding(4) var<uniform> shadow: ShadowBlock;
@group(0) @binding(5) var shadowTex: texture_depth_2d;
@group(0) @binding(6) var shadowSampler: sampler_comparison;

@fragment
fn main(input: FragmentInput) -> @location(0) vec4f {
    let opacity = clamp(1.0 + input.distanceOffset - abs(input.distance * input.fragCoord.w), 0.0, 1.0);
    // color premultiplied; opacity множит всё, свет — только rgb
    let color = uniforms.color * opacity;
    // Порт apply_fog из simple_line_2d.fsh
    return applyFog(fog, vec4f(color.rgb * surfaceLight(input.fragCoord), color.a), input.fogPos);
}
`,RB=`// Порт road.vsh (line.solid): экструзия в tile-space по extender с переводом
// пикселей ширины в нормализованные координаты тайла через tile-to-pixel ratio.
// ECEF-ветка глобуса (ecef_tangent_frame + u_float_ecef_scale) портирована:
// на ECEF-тайле смещение строится в касательном базисе сферы per-vertex.
// DEM/jitter/shadow-ветки исходника не портированы.
struct Uniforms {
    mvpMatrix: mat4x4f,
    color: vec4f,
    // x: ширина линии в px, y: tile-to-pixel ratio (нормализованные единицы тайла на px)
    params: vec4f,
    // x = crossfade глобуса (0 = плоско), y = ecefScale (ECEF-смещение на 1 u16-единицу тайла),
    // z = подъём этажа (маппоинты)
    globeParams: vec4f,
    // xyz = (тайл − камера)/fogDistance, w = масштаб тайла/fogDistance; нули = туман выключен
    fogOrigin: vec4f,
};

// Общий на кадр uniform глобуса (порт include/ecef_mvp_mat.vsh, см. polygonFill.vert).
struct GlobeUniforms {
    ecefMvp: mat4x4f,
    vp: mat4x4f,
    // xy = [lng (рад), mercatorY] центра камеры
    cameraMercator: vec4f,
    // viewProjection × центр карты, посчитанный в f64 на CPU (якорь flat-реконструкции)
    vpAtCenter: vec4f,
};

struct VertexOutput {
    @builtin(position) position: vec4f,
    @location(0) lineNormal: vec2f,
    @location(1) halfWidth: f32,
    // Порт v_fog_pos: (world_pos − cam_pos)/fog_distance
    @location(2) fogPos: vec3f,
    // id объекта (localID) — читает только identify.frag; основной фрагментник игнорирует
    @location(15) @interpolate(flat) identifier: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
// binding 1 — свет (LightBlock), используется только фрагментом; здесь не объявляем.
@group(0) @binding(2) var<uniform> globe: GlobeUniforms;

// Коэффициент распаковки нормалей: sqrt(2) / 127 (см. simpleLoftedLine, invSqrt2 * 127)
const NORMAL_UNPACK_MULTIPLIER = 0.011135539861205473;
const W_FACTOR = 1e-6;

const ECEF_CF_NEAR: f32 = 0.01;
const ECEF_WORLD: f32 = 4294967296.0; // 2^32 = worldSize: нормировка ECEF
const ECEF_PI: f32 = 3.141592653589793;
const ECEF_TWO_PI: f32 = 6.283185307179586;
const ECEF_MAX_LAT: f32 = 1.4844222; // ~85.05° (web-mercator clamp)
// Масштаб u16-единиц тайла (порт множителя 65535 из road.vsh)
const ECEF_U16_MAX: f32 = 65535.0;

fn ecefWrapPi(a: f32) -> f32 {
    return ((a + ECEF_PI) % ECEF_TWO_PI) - ECEF_PI;
}

// Origin-relative flat clip из нормализованной ECEF-позиции [-0.5..0.5]. Считает
// смещение от центра камеры (мелкое — точность f32) и добавляет f64-якорь vpAtCenter.
fn ecefFlatClip(epos: vec3f) -> vec4f {
    let en = normalize(epos);
    let lng = atan2(en.x, en.z);
    let lat = clamp(asin(clamp(en.y, -1.0, 1.0)), -ECEF_MAX_LAT, ECEF_MAX_LAT);
    let mercY = log(tan(ECEF_PI / 4.0 + lat / 2.0));
    let dLng = ecefWrapPi(lng - globe.cameraMercator.x);
    let relX = dLng / ECEF_TWO_PI * ECEF_WORLD;
    let relY = (mercY - globe.cameraMercator.y) / ECEF_TWO_PI * ECEF_WORLD;
    return globe.vp * vec4f(relX, relY, 0.0, 0.0) + globe.vpAtCenter;
}

// Кроссфейд flat↔globe из нормализованной ECEF-позиции (vertex - 0.5). Гистерезис
// ECEF_CF_NEAR: близко к 0 — чистый flat, близко к 1 — чистый ECEF, иначе mix.
fn ecefClip(epos: vec3f, crossfade: f32) -> vec4f {
    if (crossfade > 1.0 - ECEF_CF_NEAR) {
        return globe.ecefMvp * vec4f(epos * ECEF_WORLD, 1.0);
    }
    if (crossfade < ECEF_CF_NEAR) {
        return ecefFlatClip(epos);
    }
    let fclip = ecefFlatClip(epos);
    let eclip = globe.ecefMvp * vec4f(epos * ECEF_WORLD, 1.0);
    return mix(fclip, eclip, crossfade);
}

// Восточное направление касательного базиса сферы (порт ecef_tangent_frame);
// north = cross(up, east) считается на месте использования.
fn ecefEast(up: vec3f) -> vec3f {
    var rawEast = cross(vec3f(0.0, 1.0, 0.0), up);
    if (dot(rawEast, rawEast) <= 1e-12) {
        rawEast = cross(vec3f(1.0, 0.0, 0.0), up);
    }
    return normalize(rawEast);
}

@vertex
fn main(
    @location(0) pos: vec4f,
    @location(1) normals: vec4i,
    @location(2) identifier: vec4f,
) -> VertexOutput {
    // Прибавляем к общей ширине 1 пиксель для сглаживания
    let halfWidth = 0.5 * (uniforms.params.x + 1.0);

    // extender (xy) и normal (zw) в пиксельных координатах
    let unpacked = vec4f(normals) * NORMAL_UNPACK_MULTIPLIER * halfWidth;
    let offsetPixels = unpacked.xy;

    var output: VertexOutput;
    output.identifier = identifier;
    let crossfade = uniforms.globeParams.x;
    if (crossfade > 0.0) {
        // ECEF-тайл: позиция — u16-ECEF; смещение в касательном базисе сферы
        // (порт else-ветки road.vsh)
        let center = pos.xyz - vec3f(0.5);
        let up = normalize(center);
        let east = ecefEast(up);
        let north = cross(up, east);
        let offsetTilePoints = offsetPixels * uniforms.params.y * ECEF_U16_MAX;
        let shiftedEcef = center +
            (east * offsetTilePoints.x + north * offsetTilePoints.y) * uniforms.globeParams.y;
        output.position = W_FACTOR * ecefClip(shiftedEcef, crossfade);
        // Туман на глобусе выключен (fogOrigin нулевой)
        output.fogPos = vec3f(0.0);
    } else {
        let shiftedVertex = pos.xy + offsetPixels * uniforms.params.y;
        // globeParams.z — подъём этажа в маппоинтах (порт u_float_floor_elevation)
        output.position =
            W_FACTOR * (uniforms.mvpMatrix * vec4f(shiftedVertex, uniforms.globeParams.z, 1.0));
        // Порт calc_fog_pos: (world_pos − cam_pos)/fog_distance, f64-часть на CPU
        output.fogPos = uniforms.fogOrigin.xyz + vec3f(shiftedVertex, 0.0) * uniforms.fogOrigin.w;
    }
    output.lineNormal = unpacked.zw;
    output.halfWidth = halfWidth;
    return output;
}
`,Eh=`// Порт road.fsh: сглаживание по длине нормали (affine_step от края минус fwidth
// до края) + свет плоской поверхности + туман. Shadow исходника не портирован.
struct Uniforms {
    mvpMatrix: mat4x4f,
    color: vec4f,
    params: vec4f,
};

struct FragmentInput {
    @builtin(position) fragCoord: vec4f,
    @location(0) lineNormal: vec2f,
    @location(1) halfWidth: f32,
    @location(2) fogPos: vec3f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(0) @binding(1) var<uniform> light: LightBlock;
// binding 2 — глобус, только вершинная стадия; FogBlock — chunk fog.wgsl
@group(0) @binding(3) var<uniform> fog: FogBlock;
// Тени кадра — chunk shadow.wgsl (ShadowBlock + карта теней + comparison-сэмплер)
@group(0) @binding(4) var<uniform> shadow: ShadowBlock;
@group(0) @binding(5) var shadowTex: texture_depth_2d;
@group(0) @binding(6) var shadowSampler: sampler_comparison;

@fragment
fn main(input: FragmentInput) -> @location(0) vec4f {
    // Порт affine_step(half_width - length(fwidth(normal)), half_width, length(normal))
    let aa = max(length(fwidth(input.lineNormal)), 1e-6);
    let opacity = 1.0 - clamp(
        (length(input.lineNormal) - (input.halfWidth - aa)) / aa,
        0.0,
        1.0,
    );

    // color premultiplied; opacity множит всё, свет — только rgb
    let color = uniforms.color * opacity;
    // Порт apply_fog из road.fsh
    return applyFog(fog, vec4f(color.rgb * surfaceLight(input.fragCoord), color.a), input.fogPos);
}
`,zB=`// Порт road.vsh (shiftedLine): экструзия в tile-space по extender плюс параллельный
// сдвиг вдоль per-vertex направления a_vec2_shift, оба в пикселях, перевод в
// нормализованные координаты тайла через tile-to-pixel ratio. ECEF-ветка глобуса
// (ecef_tangent_frame + u_float_ecef_scale) портирована — суммарное пиксельное
// смещение (shift + extender) строится в касательном базисе сферы.
// Jitter/shadow/floorElevation исходника не портированы.
struct Uniforms {
    mvpMatrix: mat4x4f,
    color: vec4f,
    // x: ширина линии в px, y: tile-to-pixel ratio, z: сдвиг линии в px
    params: vec4f,
    // x = crossfade глобуса (0 = плоско), y = ecefScale (ECEF-смещение на 1 u16-единицу тайла)
    globeParams: vec4f,
    // xyz = (тайл − камера)/fogDistance, w = масштаб тайла/fogDistance; нули = туман выключен
    fogOrigin: vec4f,
};

// Общий на кадр uniform глобуса (порт include/ecef_mvp_mat.vsh, см. polygonFill.vert).
struct GlobeUniforms {
    ecefMvp: mat4x4f,
    vp: mat4x4f,
    // xy = [lng (рад), mercatorY] центра камеры
    cameraMercator: vec4f,
    // viewProjection × центр карты, посчитанный в f64 на CPU (якорь flat-реконструкции)
    vpAtCenter: vec4f,
};

struct VertexOutput {
    @builtin(position) position: vec4f,
    @location(0) lineNormal: vec2f,
    @location(1) halfWidth: f32,
    // Порт v_fog_pos: (world_pos − cam_pos)/fog_distance
    @location(2) fogPos: vec3f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
// binding 1 — свет (LightBlock), используется только фрагментом; здесь не объявляем.
@group(0) @binding(2) var<uniform> globe: GlobeUniforms;

// Коэффициент распаковки нормалей: sqrt(2) / 127 (см. simpleLoftedLine, invSqrt2 * 127)
const NORMAL_UNPACK_MULTIPLIER = 0.011135539861205473;
const W_FACTOR = 1e-6;

const ECEF_CF_NEAR: f32 = 0.01;
const ECEF_WORLD: f32 = 4294967296.0; // 2^32 = worldSize: нормировка ECEF
const ECEF_PI: f32 = 3.141592653589793;
const ECEF_TWO_PI: f32 = 6.283185307179586;
const ECEF_MAX_LAT: f32 = 1.4844222; // ~85.05° (web-mercator clamp)
// Масштаб u16-единиц тайла (порт множителя 65535 из road.vsh)
const ECEF_U16_MAX: f32 = 65535.0;

fn ecefWrapPi(a: f32) -> f32 {
    return ((a + ECEF_PI) % ECEF_TWO_PI) - ECEF_PI;
}

// Origin-relative flat clip из нормализованной ECEF-позиции [-0.5..0.5]. Считает
// смещение от центра камеры (мелкое — точность f32) и добавляет f64-якорь vpAtCenter.
fn ecefFlatClip(epos: vec3f) -> vec4f {
    let en = normalize(epos);
    let lng = atan2(en.x, en.z);
    let lat = clamp(asin(clamp(en.y, -1.0, 1.0)), -ECEF_MAX_LAT, ECEF_MAX_LAT);
    let mercY = log(tan(ECEF_PI / 4.0 + lat / 2.0));
    let dLng = ecefWrapPi(lng - globe.cameraMercator.x);
    let relX = dLng / ECEF_TWO_PI * ECEF_WORLD;
    let relY = (mercY - globe.cameraMercator.y) / ECEF_TWO_PI * ECEF_WORLD;
    return globe.vp * vec4f(relX, relY, 0.0, 0.0) + globe.vpAtCenter;
}

// Кроссфейд flat↔globe из нормализованной ECEF-позиции (vertex - 0.5). Гистерезис
// ECEF_CF_NEAR: близко к 0 — чистый flat, близко к 1 — чистый ECEF, иначе mix.
fn ecefClip(epos: vec3f, crossfade: f32) -> vec4f {
    if (crossfade > 1.0 - ECEF_CF_NEAR) {
        return globe.ecefMvp * vec4f(epos * ECEF_WORLD, 1.0);
    }
    if (crossfade < ECEF_CF_NEAR) {
        return ecefFlatClip(epos);
    }
    let fclip = ecefFlatClip(epos);
    let eclip = globe.ecefMvp * vec4f(epos * ECEF_WORLD, 1.0);
    return mix(fclip, eclip, crossfade);
}

// Восточное направление касательного базиса сферы (порт ecef_tangent_frame);
// north = cross(up, east) считается на месте использования.
fn ecefEast(up: vec3f) -> vec3f {
    var rawEast = cross(vec3f(0.0, 1.0, 0.0), up);
    if (dot(rawEast, rawEast) <= 1e-12) {
        rawEast = cross(vec3f(1.0, 0.0, 0.0), up);
    }
    return normalize(rawEast);
}

@vertex
fn main(
    @location(0) pos: vec4f,
    @location(1) normals: vec4i,
    @location(2) shift: vec2f,
) -> VertexOutput {
    // Прибавляем к общей ширине 1 пиксель для сглаживания
    let halfWidth = 0.5 * (uniforms.params.x + 1.0);

    // extender (xy) и normal (zw) в пиксельных координатах
    let unpacked = vec4f(normals) * NORMAL_UNPACK_MULTIPLIER * halfWidth;
    let offsetPixels = shift * uniforms.params.z + unpacked.xy;

    var output: VertexOutput;
    let crossfade = uniforms.globeParams.x;
    if (crossfade > 0.0) {
        // ECEF-тайл: позиция — u16-ECEF; смещение в касательном базисе сферы
        // (порт else-ветки road.vsh)
        let center = pos.xyz - vec3f(0.5);
        let up = normalize(center);
        let east = ecefEast(up);
        let north = cross(up, east);
        let offsetTilePoints = offsetPixels * uniforms.params.y * ECEF_U16_MAX;
        let shiftedEcef = center +
            (east * offsetTilePoints.x + north * offsetTilePoints.y) * uniforms.globeParams.y;
        output.position = W_FACTOR * ecefClip(shiftedEcef, crossfade);
        // Туман на глобусе выключен (fogOrigin нулевой)
        output.fogPos = vec3f(0.0);
    } else {
        let shiftedVertex = pos.xy + offsetPixels * uniforms.params.y;
        output.position = W_FACTOR * (uniforms.mvpMatrix * vec4f(shiftedVertex, 0.0, 1.0));
        // Порт calc_fog_pos: (world_pos − cam_pos)/fog_distance, f64-часть на CPU
        output.fogPos = uniforms.fogOrigin.xyz + vec3f(shiftedVertex, 0.0) * uniforms.fogOrigin.w;
    }
    output.lineNormal = unpacked.zw;
    output.halfWidth = halfWidth;
    return output;
}
`,NB=`// Порт striped_line.vsh (2d-путь, dashedLine.stroke): экструзия в clip-space
// по widen с экранным доводом на g_shift_pixels (решение уравнения из pixel_offset.vsh)
// + параметризация штриховки вдоль длины (striped_line_functions.vsh).
// Ширина/длины уже отмасштабированы на CPU (порт calculate_scale/line_width в билдере
// и декоде). ECEF-ветка глобуса (get_clip_direction + u_float_ecef_scale) портирована.
// DEM/fog/jitter/shadow исходника не портированы.
struct Uniforms {
    mvpMatrix: mat4x4f,
    dashColor: vec4f,
    spaceColor: vec4f,
    borderColor: vec4f,
    // x: полуширина (норм. коорд.), y: длина штриха, z: длина пропуска (тайловые единицы),
    // w: circle factor (precision-масштаб кружочков)
    params: vec4f,
    // x, y: разрешение таргета в px; z: gap_turns_only (0/1)
    resolution: vec4f,
    // x = crossfade глобуса (0 = плоско), y = ecefScale (ECEF-смещение на 1 u16-единицу тайла),
    // z = подъём этажа (маппоинты)
    globeParams: vec4f,
    // xyz = (тайл − камера)/fogDistance, w = масштаб тайла/fogDistance; нули = туман выключен
    fogOrigin: vec4f,
};

// Общий на кадр uniform глобуса (порт include/ecef_mvp_mat.vsh, см. polygonFill.vert).
struct GlobeUniforms {
    ecefMvp: mat4x4f,
    vp: mat4x4f,
    // xy = [lng (рад), mercatorY] центра камеры
    cameraMercator: vec4f,
    // viewProjection × центр карты, посчитанный в f64 на CPU (якорь flat-реконструкции)
    vpAtCenter: vec4f,
};

struct VertexOutput {
    @builtin(position) position: vec4f,
    @location(0) circle: vec2f,
    @location(1) width: f32,
    // x: порог смены цвета в долях куска, y: нормированная длина в вершине (в кусках)
    @location(2) lineParams: vec2f,
    // Порт v_fog_pos: (world_pos − cam_pos)/fog_distance
    @location(3) fogPos: vec3f,
    // id объекта — читает только identify.frag (порт stripedLineIdentify)
    @location(15) @interpolate(flat) identifier: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
// binding 1 — свет (LightBlock), используется только фрагментом; здесь не объявляем.
@group(0) @binding(2) var<uniform> globe: GlobeUniforms;

// Распаковка widen: normalize_s08 · sqrt(2) (packed_attributes.vsh, unpack_widen)
const WIDEN_UNPACK_MULTIPLIER = 0.011135539861205473;
// Количество пикселей экранного довода (g_shift_pixels)
const SHIFT_PIXELS = 2.0;
// Коэффициент перед w (g_w_factor striped_line.vsh)
const W_FACTOR = 1e-7;
const MIN_DENOMINATOR = 1e-7;
const MAX_FACTOR = 10000.0;

const ECEF_CF_NEAR: f32 = 0.01;
const ECEF_WORLD: f32 = 4294967296.0; // 2^32 = worldSize: нормировка ECEF
const ECEF_PI: f32 = 3.141592653589793;
const ECEF_TWO_PI: f32 = 6.283185307179586;
const ECEF_MAX_LAT: f32 = 1.4844222; // ~85.05° (web-mercator clamp)
// Масштаб u16-единиц тайла (порт множителя 65535 из striped_line.vsh)
const ECEF_U16_MAX: f32 = 65535.0;

fn ecefWrapPi(a: f32) -> f32 {
    return ((a + ECEF_PI) % ECEF_TWO_PI) - ECEF_PI;
}

// Origin-relative flat clip из нормализованной ECEF-позиции [-0.5..0.5]. Считает
// смещение от центра камеры (мелкое — точность f32) и добавляет f64-якорь vpAtCenter.
fn ecefFlatClip(epos: vec3f) -> vec4f {
    let en = normalize(epos);
    let lng = atan2(en.x, en.z);
    let lat = clamp(asin(clamp(en.y, -1.0, 1.0)), -ECEF_MAX_LAT, ECEF_MAX_LAT);
    let mercY = log(tan(ECEF_PI / 4.0 + lat / 2.0));
    let dLng = ecefWrapPi(lng - globe.cameraMercator.x);
    let relX = dLng / ECEF_TWO_PI * ECEF_WORLD;
    let relY = (mercY - globe.cameraMercator.y) / ECEF_TWO_PI * ECEF_WORLD;
    return globe.vp * vec4f(relX, relY, 0.0, 0.0) + globe.vpAtCenter;
}

// Кроссфейд flat↔globe из нормализованной ECEF-позиции (vertex - 0.5). Гистерезис
// ECEF_CF_NEAR: близко к 0 — чистый flat, близко к 1 — чистый ECEF, иначе mix.
fn ecefClip(epos: vec3f, crossfade: f32) -> vec4f {
    if (crossfade > 1.0 - ECEF_CF_NEAR) {
        return globe.ecefMvp * vec4f(epos * ECEF_WORLD, 1.0);
    }
    if (crossfade < ECEF_CF_NEAR) {
        return ecefFlatClip(epos);
    }
    let fclip = ecefFlatClip(epos);
    let eclip = globe.ecefMvp * vec4f(epos * ECEF_WORLD, 1.0);
    return mix(fclip, eclip, crossfade);
}

// Порт get_clip_direction (striped_line.vsh): clip-space вектор направления
// с crossfade-миксом между flat и ECEF (направление — в касательном базисе сферы).
fn ecefClipDirection(dir: vec2f, east: vec3f, north: vec3f) -> vec4f {
    let flatClip = uniforms.mvpMatrix * vec4f(dir, 0.0, 0.0);
    let ecefScale = uniforms.globeParams.y;
    if (ecefScale <= 0.0) {
        return flatClip;
    }
    let ecefDir = (east * dir.x + north * dir.y) * ecefScale * ECEF_U16_MAX;
    let ecefClipDir = globe.ecefMvp * vec4f(ecefDir * ECEF_WORLD, 0.0);
    return mix(flatClip, ecefClipDir, uniforms.globeParams.x);
}

// Порт calculate_multiplication_factor (pixel_offset.vsh): k, на который домножается
// нормаль, чтобы экранное смещение вершины составило shiftPixels пикселей.
fn calcMultiplicationFactor(
    halfViewport: vec2f,
    clipWiden: vec4f,
    clipWidenPerp: vec4f,
    clipVertex: vec4f,
    shiftPixels: f32,
) -> f32 {
    var limitedFactor = 0.0;

    let screenWiden =
        (clipWiden.xy * clipVertex.w - clipVertex.xy * clipWiden.w) * halfViewport;
    let screenWidenPerp =
        (clipWidenPerp.xy * clipVertex.w - clipVertex.xy * clipWidenPerp.w) * halfViewport;
    let perp = vec2f(screenWidenPerp.y, -screenWidenPerp.x);
    let perpLength = length(perp);

    let denominator =
        dot(perp, screenWiden) / shiftPixels - clipWiden.w * clipVertex.w * perpLength;
    if (abs(denominator) > MIN_DENOMINATOR) {
        let factor = clipVertex.w * clipVertex.w * perpLength / denominator;
        // NaN-гард исходника (factor == factor)
        if (factor == factor) {
            limitedFactor = sign(factor) * min(MAX_FACTOR, abs(factor));
        }
    }

    // Фолбэк при потере точности на мелких масштабах (ниже ~6.5 зума)
    if (limitedFactor == 0.0) {
        let screenWidenFallback = clipWiden.xy / clipVertex.w * halfViewport;
        let screenWidenLength = length(screenWidenFallback);
        if (screenWidenLength > 1e-4) {
            limitedFactor = shiftPixels / screenWidenLength;
        }
    }

    return limitedFactor;
}

@vertex
fn main(
    @location(0) pos: vec4f,
    @location(1) textureWidenPacked: vec2i,
    @location(2) widenPacked: vec2i,
    @location(3) vertexDistance: f32,
    @location(4) componentDistance: f32,
    @location(5) objectLength: f32,
    @location(7) identifier: vec4f,
) -> VertexOutput {
    let lineWidth = uniforms.params.x;
    let widen = vec2f(widenPacked) * WIDEN_UNPACK_MULTIPLIER;
    let widenPerp = vec2f(-widen.y, widen.x);

    // Per-vertex касательный базис на сфере (только в ECEF-режиме, порт striped_line.vsh)
    let crossfade = uniforms.globeParams.x;
    var east = vec3f(0.0);
    var north = vec3f(0.0);
    if (crossfade > 0.0) {
        let up = normalize(pos.xyz - vec3f(0.5));
        var rawEast = cross(vec3f(0.0, 1.0, 0.0), up);
        if (dot(rawEast, rawEast) <= 1e-12) {
            rawEast = cross(vec3f(1.0, 0.0, 0.0), up);
        }
        east = normalize(rawEast);
        north = cross(up, east);
    }

    // n и v1 из уравнения pixel_offset.vsh
    let clipWiden = ecefClipDirection(widen, east, north);
    let clipWidenPerp = ecefClipDirection(widenPerp, east, north);
    var clipBase: vec4f;
    if (crossfade > 0.0) {
        // ECEF-тайл: позиция закодирована как u16-ECEF
        clipBase = ecefClip(pos.xyz - vec3f(0.5), crossfade);
    } else {
        // globeParams.z — подъём этажа в маппоинтах (порт u_float_floor_elevation)
        clipBase = uniforms.mvpMatrix * vec4f(pos.xy, uniforms.globeParams.z, 1.0);
    }
    let clipVertex = clipBase + clipWiden * lineWidth;

    let halfViewport = 0.5 * uniforms.resolution.xy;
    let limitedFactor =
        calcMultiplicationFactor(halfViewport, clipWiden, clipWidenPerp, clipVertex, SHIFT_PIXELS);

    // Порт calculate_line_params (striped_line_functions.vsh); dash2 == dash
    let requestedPartLength = uniforms.params.y + uniforms.params.z;
    let partCount = max(floor(objectLength / requestedPartLength + 0.5), 1.0);
    let partLength = objectLength / partCount;
    let dashLength = (partLength / requestedPartLength) * uniforms.params.y;
    let threshold = dashLength / partLength;
    // Линия начинается и заканчивается половиной штриха
    let segmentStart = fract((componentDistance + 0.5 * dashLength) / partLength);
    let distanceInParts = segmentStart + vertexDistance / partLength;

    // В texture_widen закодировано направление сдвига вдоль направляющей:
    // при сдвиге к началу вектор перевёрнут на 180°
    let textureWidenWithShiftSign = vec2f(textureWidenPacked) * WIDEN_UNPACK_MULTIPLIER;
    let shiftSign = sign(dot(widen, textureWidenWithShiftSign));
    let textureWiden = shiftSign * textureWidenWithShiftSign;

    let circleFactor = uniforms.params.w;

    var output: VertexOutput;
    output.circle = textureWiden * (lineWidth + limitedFactor) * circleFactor;
    output.width = lineWidth * circleFactor;
    output.lineParams = vec2f(threshold, distanceInParts);
    output.identifier = identifier;
    output.position = (clipVertex + clipWiden * limitedFactor) * W_FACTOR;
    // Порт calc_fog_pos: на глобусе fogOrigin нулевой (туман выключен)
    if (crossfade > 0.0) {
        output.fogPos = vec3f(0.0);
    } else {
        output.fogPos = uniforms.fogOrigin.xyz + vec3f(pos.xy, 0.0) * uniforms.fogOrigin.w;
    }
    return output;
}
`,rx=`// Порт striped_line.fsh: fract-штриховка (calculate_segment_color_factor) +
// сглаженный кружочек/бордер по аналитической производной (distance_func_smooth)
// + свет плоской поверхности. Fog/shadow исходника не портированы.
struct Uniforms {
    mvpMatrix: mat4x4f,
    dashColor: vec4f,
    spaceColor: vec4f,
    borderColor: vec4f,
    params: vec4f,
    // x, y: разрешение; z: gap_turns_only (0/1)
    resolution: vec4f,
};

struct FragmentInput {
    @builtin(position) fragCoord: vec4f,
    @location(0) circle: vec2f,
    @location(1) width: f32,
    @location(2) lineParams: vec2f,
    @location(3) fogPos: vec3f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(0) @binding(1) var<uniform> light: LightBlock;
// binding 2 — глобус, только вершинная стадия; FogBlock — chunk fog.wgsl
@group(0) @binding(3) var<uniform> fog: FogBlock;
// Тени кадра — chunk shadow.wgsl (ShadowBlock + карта теней + comparison-сэмплер)
@group(0) @binding(4) var<uniform> shadow: ShadowBlock;
@group(0) @binding(5) var shadowTex: texture_depth_2d;
@group(0) @binding(6) var shadowSampler: sampler_comparison;

fn affineStep(edge0: f32, edge1: f32, x: f32) -> f32 {
    return clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0);
}

// Порт distance_func_smooth: переход main → border → прозрачность по расстоянию
// от оси; производные от distance считаются аналитически через производные circle
// (производная вдоль сегмента занулена осознанно — см. комментарий исходника).
fn distanceFuncSmooth(
    mainColor: vec4f,
    borderColor: vec4f,
    circle: vec2f,
    circleDx: vec2f,
    circleDy: vec2f,
    width: f32,
) -> vec4f {
    let circleLength = length(circle);
    let signedDistance = circleLength - width;

    let distanceDx = dot(circle, circleDx);
    let distanceDy = dot(circle, circleDy);
    // Знаменатель производной вынесен умножением в аргументы affine_step
    let derivativeDenominator = circleLength;

    let derivativeWidth = max(abs(distanceDx), abs(distanceDy));
    let fromMainToBorder = mix(
        mainColor,
        borderColor,
        affineStep(-derivativeWidth, 0.0, signedDistance * derivativeDenominator),
    );
    return mix(
        fromMainToBorder,
        vec4f(0.0),
        affineStep(0.0, derivativeWidth, signedDistance * derivativeDenominator),
    );
}

// Порт calculate_segment_color_factor: 0 — штрих, 1 — пропуск, сглаженная граница
fn segmentColorFactor(distanceInParts: f32, threshold: f32, partsAffineStepWidth: f32) -> f32 {
    let colorFactor = abs(fract(distanceInParts + 0.5 - 0.5 * threshold) - 0.5);

    // Костыль против моргающих участков на поворотах лестниц (TILES-8356)
    if (uniforms.resolution.z > 0.5 && partsAffineStepWidth < threshold * 0.0001) {
        return 1.0;
    }

    return affineStep(
        0.5 * threshold - 0.5 * partsAffineStepWidth,
        0.5 * threshold + 0.5 * partsAffineStepWidth,
        colorFactor,
    );
}

@fragment
fn main(input: FragmentInput) -> @location(0) vec4f {
    // Производные — до ветвлений (uniform control flow)
    let circleDx = dpdx(input.circle);
    let circleDy = dpdy(input.circle);
    let partsAffineStepWidth = fwidth(input.lineParams.y);

    let currentSegmentColor = mix(
        uniforms.dashColor,
        uniforms.spaceColor,
        segmentColorFactor(input.lineParams.y, input.lineParams.x, partsAffineStepWidth),
    );
    // Смешиваем через альфу, оба цвета уже предумноженные
    let finalBorderColor =
        (1.0 - uniforms.borderColor.a) * currentSegmentColor + uniforms.borderColor;
    let color = distanceFuncSmooth(
        currentSegmentColor,
        finalBorderColor,
        input.circle,
        circleDx,
        circleDy,
        input.width,
    );
    // Порт apply_fog из striped_line.fsh
    return applyFog(fog, vec4f(color.rgb * surfaceLight(input.fragCoord), color.a), input.fogPos);
}
`,GB=`// Порт patterned_line.vsh (плоский 2d-путь, line.patterned): tile-space экструзия
// по widen на полную ширину + декод параметризации вдоль длины из одного флоата
// (магнитуда — нормированная дистанция, знак — сторона линии; хак генератора).
// Масштабы u_vec2_scales посчитаны на CPU (порт patternScales в билдере).
// ECEF/DEM/fog/jitter/shadow/3d-высота исходника не портированы.
struct Uniforms {
    mvpMatrix: mat4x4f,
    // Цвет паттерна, premultiplied (u_vec4_color с apply_opacity(., 1.))
    color: vec4f,
    // u_vec4_pattern_params (x — период в логических px)
    patternParams: vec4f,
    // x: ширина линии в физ. px (u_float_width), y: scales.x (норм. длина → лог. px),
    // z: scales.y (физ. px → нормализованные координаты тайла), w: pattern_type (1..6)
    params: vec4f,
    // xyz = (тайл − камера)/fogDistance, w = масштаб тайла/fogDistance; нули = туман выключен
    fogOrigin: vec4f,
};

struct VertexOutput {
    @builtin(position) position: vec4f,
    @location(0) uv: vec2f,
    // Порт v_fog_pos: (world_pos − cam_pos)/fog_distance
    @location(1) fogPos: vec3f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;

// Распаковка widen: normalize_s08 · sqrt(2) (packed_attributes.vsh, unpack_widen);
// значения ±127-масштаба лежат в s16 (миллиметровые митры длиннее s8)
const WIDEN_UNPACK_MULTIPLIER = 0.011135539861205473;
// Коэффициент перед w, чтоб не взрывалось на mediump (g_w_factor patterned_line.vsh)
const W_FACTOR = 1e-6;

@vertex
fn main(
    @location(0) pos: vec2f,
    @location(1) widenPacked: vec2i,
    @location(2) textureCoord: f32,
) -> VertexOutput {
    let lineWidth = uniforms.params.x;

    // Декод «текстурной координаты» из одного флоата: u — магнитуда, v — знак (±0.5)
    var uv = vec2f(abs(textureCoord), sign(textureCoord) * 0.5);
    uv.x *= uniforms.params.y / uniforms.patternParams.x;

    // Прибавляем к общей ширине 1 пиксель для сглаживания
    let fullWidth = lineWidth + 1.0;
    let widen = vec2f(widenPacked) * WIDEN_UNPACK_MULTIPLIER;
    let extender = widen * fullWidth * 0.5;
    let shiftedVertex = vec4f(pos + extender * uniforms.params.z, 0.0, 1.0);

    var output: VertexOutput;
    output.uv = uv;
    output.position = (uniforms.mvpMatrix * shiftedVertex) * W_FACTOR;
    // Порт calc_fog_pos
    output.fogPos = uniforms.fogOrigin.xyz + vec3f(shiftedVertex.xy, 0.0) * uniforms.fogOrigin.w;
    return output;
}
`,sx=`// Порт patterned_line.fsh: процедурный SDF-паттерн вдоль линии (chess/doubledash/
// stripe/triangles/circle/chevron из signed_distance_functions.vfsh) + свет плоской
// поверхности. Fog/shadow/pack_depth исходника не портированы.
struct Uniforms {
    mvpMatrix: mat4x4f,
    color: vec4f,
    patternParams: vec4f,
    // x: ширина линии в физ. px, y/z: масштабы (не нужны фрагментнику), w: pattern_type
    params: vec4f,
};

struct FragmentInput {
    @builtin(position) fragCoord: vec4f,
    @location(0) uv: vec2f,
    @location(1) fogPos: vec3f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(0) @binding(1) var<uniform> light: LightBlock;
// binding 2 — глобус, только вершинная стадия; FogBlock — chunk fog.wgsl
@group(0) @binding(3) var<uniform> fog: FogBlock;
// Тени кадра — chunk shadow.wgsl (ShadowBlock + карта теней + comparison-сэмплер)
@group(0) @binding(4) var<uniform> shadow: ShadowBlock;
@group(0) @binding(5) var shadowTex: texture_depth_2d;
@group(0) @binding(6) var shadowSampler: sampler_comparison;

const EPSILON = 0.0001;

fn affineStep(edge0: f32, edge1: f32, x: f32) -> f32 {
    return clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0);
}

fn sdfBox(p: vec2f, b: vec2f) -> f32 {
    let d = abs(p) - b;
    return length(max(d, vec2f(0.0))) + min(max(d.x, d.y), 0.0);
}

fn sdfCircle(p: vec2f, radius: f32) -> f32 {
    return length(p) - radius;
}

fn sdfTriangle(p: vec2f, width: f32) -> f32 {
    return abs(p.x) - (p.y + 0.5) * width * 0.5;
}

fn dot2(p: vec2f) -> f32 {
    return dot(p, p);
}

fn sdfChevron(pIn: vec2f) -> f32 {
    var p = vec2f(abs(pIn.x), pIn.y);

    if (p.y + p.x > 1.0) {
        return sqrt(dot2(p - vec2f(0.25, 0.75))) - sqrt(2.0) / 4.0;
    }

    return sqrt(min(dot2(p - vec2f(0.0, 1.0)),
                    dot2(p - 0.5 * max(p.x + p.y, 0.0)))) * sign(p.x - p.y);
}

// В uv по ширине линии координаты меняются от -0.5 к 0.5, по длине постоянно прирастают.
// Из них делаем циклическое пространство [-0.5..0.5]² и рисуем SDF-фигуру с коррекцией
// на масштаб (стандартные лайфхаки штриховых линий, чтобы штрихи не бегали).
@fragment
fn main(input: FragmentInput) -> @location(0) vec4f {
    let patternType = i32(uniforms.params.w + 0.5);
    let lineWidth = uniforms.params.x;
    let patternLength = uniforms.patternParams.x;

    // Параметры сглаживания для фигур SDF
    let smoothBase = max(15.0, max(lineWidth, patternLength));
    let smoothScale = (smoothBase + 1.0) / smoothBase;
    let smoothFactor = smoothScale - 1.0;

    // Готовим uv-координаты для работы с SDF
    let sdfPos = vec2f(fract(input.uv.x) - 0.5, input.uv.y * smoothScale);

    var sdf = 1.0;

    // 1 — chess, 2 — doubledash, 3 — stripe
    if (patternType < 4) {
        let boxWidth = uniforms.patternParams.y;
        let left = uniforms.patternParams.z;
        let right = uniforms.patternParams.w;

        // В шахматном паттерне right отрицательный — штрихи сдвинуты друг относительно друга
        var offset = vec2f(0.0, 0.5);
        if (right < 0.0) {
            offset = vec2f(0.25, 0.5);
        }

        // Если ширина == 0, не рисуем
        if (boxWidth > EPSILON) {
            var leftSdf = 1.0;
            if (left > EPSILON) {
                leftSdf = sdfBox(sdfPos + offset, vec2f(left, boxWidth));
            }

            var rightSdf = 1.0;
            if (abs(right) > EPSILON) {
                rightSdf = sdfBox(sdfPos - offset, vec2f(abs(right), boxWidth));
            }

            sdf = min(leftSdf, rightSdf);
        }
    } else if (patternType == 5) {
        // Паттерн кружок (circle)
        let radius = uniforms.patternParams.y;
        if (radius > EPSILON) {
            sdf = sdfCircle(sdfPos, radius);
        }
    } else if (patternType == 4) {
        // Паттерн треугольник (triangles)
        let triWidth = uniforms.patternParams.y;
        let orientation = uniforms.patternParams.z;
        if (triWidth > EPSILON) {
            sdf = sdfTriangle(sdfPos * vec2f(1.0, orientation), triWidth);
        }
    } else if (patternType == 6) {
        // Паттерн шеврон aka сердечко (chevron)
        sdf = sdfChevron(sdfPos.yx);
    }

    // Сглаживаем края линии
    sdf = max(sdf, abs(sdfPos.y) - 0.5);

    // Сглаживаем фигуру SDF
    let color = mix(
        uniforms.color,
        vec4f(0.0),
        affineStep(-smoothFactor, smoothFactor, sdf),
    );

    // Порт apply_fog из patterned_line.fsh
    return applyFog(fog, vec4f(color.rgb * surfaceLight(input.fragCoord), color.a), input.fogPos);
}
`,kB=`// Порт line3d.vsh (line.solid3d): «настоящие» 3d-линии с высотами из данных
// (провода, канатки, 3d-маршруты). Billboard-расширение: extender поворачивается
// к камере (формула Родрига), затем ширина нормируется по фактическому экранному
// расстоянию. Высота вершины: DEM + относительная a_float_height, либо абсолютная
// a_float_abs_z (флаг demParams.z — порт u_int_abs_z). Corrected-DEM/jitter/shadow
// исходника не портированы (как в extrusion-порте).

// Маппоинтов в одном метре веб-меркатора (include/dem.vsh)
const MAP_POINTS_IN_METER: f32 = 107.17318796639701;
// Маппоинты → нормализованный tile-z (= 1/zScale модели WebGL, см. polygonExtrusion.vert.wgsl)
const VERTICAL_SCALE: f32 = (32768.0 / 65535.0) / 1048576.0;
// Обратный множитель: нормализованный tile-z → маппоинты. Модель тайла Sunda имеет m[10] = 1
// (в отличие от WebGL, где z-scale сидит в модели), поэтому расчёт ведём в нормализованных
// z-координатах WebGL, а перед MVP разнормируем этим множителем (= 65535·32 = 2097120).
const Z_SCALE: f32 = 1048576.0 / (32768.0 / 65535.0);

// Коэффициент распаковки нормалей: sqrt(2) / 127 (см. simpleLoftedLine, invSqrt2 * 127)
const NORMAL_UNPACK_MULTIPLIER = 0.011135539861205473;
const W_FACTOR = 1e-6;
const EPSILON = 1e-3;

struct Uniforms {
    mvpMatrix: mat4x4f,
    color: vec4f,
    // x: ширина линии в px, y: tile-to-pixel ratio, z/w: разрешение канваса в px
    params: vec4f,
    // тайловые координаты → текстура высот рельефа
    demTexMvp: mat4x4f,
    // x = demScale (0 — рельеф выключен), y = centerElevation (м),
    // z = флаг abs_z (0/1), w = xy-масштаб модели тайла (норм. коорд. → маппоинты)
    demParams: vec4f,
    // xyz: (origin тайла − камера) в маппоинтах — precision-safe вектор на камеру;
    // w: 1/fogDistance (0 = туман выключен) — fogPos = worldRel · w
    camOriginRel: vec4f,
};

struct VertexOutput {
    @builtin(position) position: vec4f,
    @location(0) lineNormal: vec2f,
    @location(1) halfWidth: f32,
    // Порт v_fog_pos: (world_pos − cam_pos)/fog_distance
    @location(2) fogPos: vec3f,
    // id объекта (localID) — читает только lineSolidIdentify.frag (порт line3DIdentify)
    @location(15) @interpolate(flat) identifier: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(1) @binding(0) var demTex: texture_2d<f32>;
@group(1) @binding(1) var demSampler: sampler;

// Высота рельефа в нормализованном tile-z по тайловым координатам (порт dem_height,
// копия polygonExtrusion.vert.wgsl). 0 при выключенном рельефе; без данных — уровень моря.
fn demHeight(coords: vec2f) -> f32 {
    let demScale = uniforms.demParams.x;
    if (demScale == 0.0) {
        return 0.0;
    }
    let texPos = (uniforms.demTexMvp * vec4f(coords, 0.0, 1.0)).xy;
    // V переворачивается: текстура высот записана в WebGPU матрицами WebGL-конвенции
    let elevation = textureSampleLevel(demTex, demSampler, vec2f(texPos.x, 1.0 - texPos.y), 0.0);
    // Порт dem_height_direct_meters: без данных рельефа — 0 м (уровень моря), как в WebGL
    var meters = elevation.r;
    if (elevation.a < 1.0) {
        meters = 0.0;
    }
    return (meters - uniforms.demParams.y) * MAP_POINTS_IN_METER * VERTICAL_SCALE * demScale;
}

// Абсолютная высота из данных (маппоинты) → нормализованный tile-z (порт abs_height,
// include/dem.vsh:113-115). При demScale == 0 (рельеф выключен) даёт 0 — как WebGL.
fn absHeight(height: f32) -> f32 {
    return (height - uniforms.demParams.y * MAP_POINTS_IN_METER) *
        uniforms.demParams.x * VERTICAL_SCALE;
}

@vertex
fn main(
    @location(0) pos: vec2f,
    @location(1) normals: vec4i,
    @location(2) height: f32,
    @location(3) absZ: f32,
    @location(4) identifier: vec4f,
) -> VertexOutput {
    var terrain = 0.0;
    if (uniforms.demParams.z == 0.0) {
        terrain = demHeight(pos);
    } else {
        terrain = absHeight(absZ);
    }

    // Прибавляем к общей ширине 1 пиксель для сглаживания
    let halfWidth = 0.5 * (uniforms.params.x + 1.0);

    // extender (xy) и normal (zw) в пиксельных координатах
    let unpacked = vec4f(normals) * NORMAL_UNPACK_MULTIPLIER * halfWidth;
    let extender = unpacked.xy;
    let lineNormal = unpacked.zw;

    // Вершина в координатах WebGL-модели: xy нормализованные, z нормализованный tile-z
    let baseVertex = vec3f(pos, terrain + height * VERTICAL_SCALE);
    // MVP c разнормировкой z (m[10] модели Sunda = 1, z подаём в маппоинтах)
    let m = uniforms.mvpMatrix;
    let zMvp = mat4x4f(m[0], m[1], m[2] * Z_SCALE, m[3]);

    // Вектор на камеру в мировых маппоинтах (порт calc_pos_world + u_cam_pos):
    // pos_world − cam = camOriginRel + (масштабированная позиция вершины)
    let worldRel = vec3f(
        uniforms.camOriginRel.xy + pos * uniforms.demParams.w,
        uniforms.camOriginRel.z + baseVertex.z * Z_SCALE,
    );
    let v = normalize(-worldRel);

    let extenderVector = vec3f(extender * uniforms.params.y, 0.0);
    let baseNormal = vec3f(0.0, 0.0, 1.0);

    // Строим поворот: вращаем base_normal (0,0,1) для выравнивания с направлением на камеру
    let rotationAxis = cross(baseNormal, v);
    let sinAngle = length(rotationAxis);
    let cosAngle = dot(baseNormal, v);

    var rotatedExtender: vec3f;
    if (sinAngle < EPSILON) {
        rotatedExtender = extenderVector * sign(cosAngle);
    } else {
        let k = rotationAxis / sinAngle;
        rotatedExtender = extenderVector * cosAngle +
            cross(k, extenderVector) * sinAngle +
            k * dot(k, extenderVector) * (1.0 - cosAngle);
    }

    let rotatedVertex = baseVertex + rotatedExtender;

    let baseClip = zMvp * vec4f(baseVertex, 1.0);
    let baseNdc = baseClip.xyz / baseClip.w;
    let rotatedClip = zMvp * vec4f(rotatedVertex, 1.0);
    let rotatedNdc = rotatedClip.xyz / rotatedClip.w;

    // Преобразуем NDC в экранные координаты (0 до viewport_size)
    let baseScreen = (baseNdc.xy + 1.0) * 0.5 * uniforms.params.zw;
    let rotatedScreen = (rotatedNdc.xy + 1.0) * 0.5 * uniforms.params.zw;

    let pixelDistance = length(baseScreen - rotatedScreen);
    var scaleFactor = halfWidth / pixelDistance;

    // hack: против артефактного изменения толщины, когда вершина за плоскостью проекции
    if (baseClip.w < 0.0) {
        scaleFactor = 0.0;
    }

    let finalVertex = baseVertex + rotatedExtender * scaleFactor;
    let clipPos = zMvp * vec4f(finalVertex, 1.0);

    var output: VertexOutput;
    output.position = W_FACTOR * clipPos;
    output.lineNormal = lineNormal;
    output.halfWidth = halfWidth;
    output.identifier = identifier;
    // Порт calc_fog_pos: worldRel уже (world_pos − cam_pos) в маппоинтах
    output.fogPos = worldRel * uniforms.camOriginRel.w;
    return output;
}
`,UB=`// Порт simple_line_3d.vsh: экранная окантовка верха стены (lineExtrusion.topStroke)
// и строуки тоннелей/эстакад (mesh.stroke). Экструзия по направлению сегмента,
// повёрнутому в экранную нормаль; высота вершины = z × heightFactor + DEM (или
// абсолютная высота из данных при abs_z). Fog/jitter/shadow исходника не портированы.

// Маппоинтов в одном метре веб-меркатора (include/dem.vsh)
const MAP_POINTS_IN_METER: f32 = 107.17318796639701;
// Распаковка demPosition: pos * 8 / 65535 (UNPACK_CENTROID из include/dem.vsh)
const UNPACK_CENTROID: f32 = 8.0 / 65535.0;
// Маппоинты → нормализованный tile-z (= 1/zScale модели WebGL, см. polygonExtrusion.vert.wgsl)
const VERTICAL_SCALE: f32 = (32768.0 / 65535.0) / 1048576.0;
// Нормализованный tile-z → маппоинты; модель тайла Sunda имеет m[10] = 1 (в отличие от WebGL,
// где z-scale сидит в модели), поэтому z-столбец MVP разнормируем этим множителем.
const Z_SCALE: f32 = 1048576.0 / (32768.0 / 65535.0);

// Коеффициент перед w, чтобы влезть в mediump во фрагментном шейдере (порт g_w_factor)
const W_FACTOR = 1e-6;
// Минимальное абсолютное значение знаменателя (порт g_min_denominator)
const MIN_DENOMINATOR = 1e-4;
// Количество пикселей сглаживания (порт g_smooth_width)
const SMOOTH_WIDTH = 1.0;

struct Uniforms {
    mvpMatrix: mat4x4f,
    color: vec4f,
    // x: ширина строука в физ. px, y/z: разрешение канваса в px, w: height factor
    params: vec4f,
    // тайловые координаты → текстура высот рельефа
    demTexMvp: mat4x4f,
    // x = demScale (0 — рельеф выключен), y = centerElevation (м), z = флаг abs_z (0/1),
    // w = z-offset клип-позиции (порт u_float_z_offset: контур крыш polygonExtrusion)
    demParams: vec4f,
    // xyz = (тайл − камера)/fogDistance, w = 1/fogDistance; нули = туман выключен
    fogOrigin: vec4f,
    // x = XY-масштаб модели тайла (маппоинты на единицу pos), y = подъём этажа (tile-z)
    fogParams: vec4f,
};

struct VertexOutput {
    @builtin(position) position: vec4f,
    @location(0) distance: f32,
    @location(1) distanceOffset: f32,
    // Порт v_fog_pos: (world_pos − cam_pos)/fog_distance
    @location(2) fogPos: vec3f,
    // Порт v_vec2_dem_tex_pos / v_float_dem_invalid — для check_dem_invalid во фрагменте
    @location(3) demTexPos: vec2f,
    @location(4) demInvalid: f32,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(1) @binding(0) var demTex: texture_2d<f32>;
@group(1) @binding(1) var demSampler: sampler;

// Как DEM-varyings в WebGL: значения последнего вызова demHeight
var<private> demTexPos: vec2f;
var<private> demInvalid: f32;

// Высота рельефа в нормализованном tile-z по тайловым координатам (порт dem_height,
// копия lineSolid3d.vert.wgsl). 0 при выключенном рельефе; без данных — уровень моря.
fn demHeight(coords: vec2f) -> f32 {
    let demScale = uniforms.demParams.x;
    if (demScale == 0.0) {
        return 0.0;
    }
    let texPos = (uniforms.demTexMvp * vec4f(coords, 0.0, 1.0)).xy;
    demTexPos = texPos;
    demInvalid = 0.0;
    // V переворачивается: текстура высот записана в WebGPU матрицами WebGL-конвенции
    let elevation = textureSampleLevel(demTex, demSampler, vec2f(texPos.x, 1.0 - texPos.y), 0.0);
    // Порт dem_height_direct_meters: без данных рельефа — 0 м (уровень моря), как в WebGL
    var meters = elevation.r;
    if (elevation.a < 1.0) {
        demInvalid = 1.0;
        meters = 0.0;
    }
    return (meters - uniforms.demParams.y) * MAP_POINTS_IN_METER * VERTICAL_SCALE * demScale;
}

// Абсолютная высота из данных (маппоинты) → нормализованный tile-z (порт abs_height)
fn absHeight(height: f32) -> f32 {
    return (height - uniforms.demParams.y * MAP_POINTS_IN_METER) *
        uniforms.demParams.x * VERTICAL_SCALE;
}

@vertex
fn main(
    @location(0) pos: vec2f,
    @location(1) dirDist: vec4i,
    @location(2) z: f32,
    @location(3) demPos: vec2i,
    // тот же offset, что demPos: mesh.stroke хранит там f32 abs_z (union, как WebGL vao)
    @location(4) absZ: f32,
    // байт @16: mesh.stroke — is_pivot; lineExtrusion.topStroke — innerColor (не используется)
    @location(5) pivot: vec4f,
) -> VertexOutput {
    var height = 0.0;
    if (uniforms.demParams.z == 0.0) {
        height = demHeight(vec2f(demPos) * UNPACK_CENTROID);
        // притягиваем к рельефу основание (порт simple_line_3d.vsh:48-54)
        if (z == 0.0) {
            let posHeight = demHeight(pos);
            if (height > posHeight) {
                height = posHeight;
            }
        }
    } else {
        if (pivot.x > 0.0) {
            height = demHeight(pos);
        } else {
            height = absHeight(absZ);
        }
    }
    // Порт \`height += u_float_floor_elevation\` (simple_line_3d.vsh:73)
    height += uniforms.fogParams.y;

    let shiftPixels = 0.5 * max(uniforms.params.x - 1.0, 0.0);
    let shiftAdded = shiftPixels + SMOOTH_WIDTH;

    // MVP c разнормировкой z (m[10] модели Sunda = 1, расчёт в нормализованных tile-z)
    let m = uniforms.mvpMatrix;
    let zMvp = mat4x4f(m[0], m[1], m[2] * Z_SCALE, m[3]);

    let halfViewport = uniforms.params.yz * 0.5;

    // Нормализуем вектор направления после умножения на матрицу проекции (порт :85)
    let direction = vec3f(dirDist.xyz) / 127.0;
    let dist = f32(dirDist.w);
    let clipDirection = normalize(zMvp * vec4f(direction, 0.0));

    let vertexZ = z * uniforms.params.w + height;
    let clipVertex = zMvp * vec4f(pos, vertexZ, 1.0);

    let screenDirection =
        (clipDirection.xy * clipVertex.w - clipVertex.xy * clipDirection.w) * halfViewport;
    let screenPerp = vec2f(-screenDirection.y, screenDirection.x);
    let denominator = max(MIN_DENOMINATOR, length(screenPerp));

    let position = W_FACTOR * (clipVertex +
        vec4f(screenPerp / halfViewport, 0.0, 0.0) * dist * shiftAdded / denominator * clipVertex.w);

    var output: VertexOutput;
    // Порт \`gl_Position.z += u_float_z_offset\` (simple_line_3d.vsh:100): контур крыши
    // приподнимается над её заливкой, иначе depth-тест LESS режет его на самой крыше
    output.position = position + vec4f(0.0, 0.0, uniforms.demParams.w, 0.0);
    output.distance = shiftAdded * dist * position.w;
    output.distanceOffset = shiftPixels;
    // Порт calc_fog_pos: xy в маппоинтах через масштаб модели (fogParams.x),
    // z — нормализованный tile-z → маппоинты (Z_SCALE)
    output.fogPos = uniforms.fogOrigin.xyz +
        vec3f(pos * uniforms.fogParams.x, vertexZ * Z_SCALE) * uniforms.fogOrigin.w;
    output.demTexPos = demTexPos;
    output.demInvalid = demInvalid;
    return output;
}
`,VB=`// Порт simple_line_3d.fsh: затухание по экранной дистанции от оси строука +
// свет плоской поверхности. Fog/color-effect исходника не портированы.
struct Uniforms {
    mvpMatrix: mat4x4f,
    color: vec4f,
    params: vec4f,
};

struct FragmentInput {
    @builtin(position) fragCoord: vec4f,
    @location(0) distance: f32,
    @location(1) distanceOffset: f32,
    @location(2) fogPos: vec3f,
    @location(3) demTexPos: vec2f,
    @location(4) demInvalid: f32,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(0) @binding(1) var<uniform> light: LightBlock;
// binding 2 — глобус, только вершинная стадия; FogBlock — chunk fog.wgsl
@group(0) @binding(3) var<uniform> fog: FogBlock;
// Тени кадра — chunk shadow.wgsl (ShadowBlock + карта теней + comparison-сэмплер)
@group(0) @binding(4) var<uniform> shadow: ShadowBlock;
@group(0) @binding(5) var shadowTex: texture_depth_2d;
@group(0) @binding(6) var shadowSampler: sampler_comparison;

@fragment
fn main(input: FragmentInput) -> @location(0) vec4f {
    // Порт check_dem_invalid: строук тоннеля над точкой без рельефа не рисуется
    if (input.demInvalid != 0.0 ||
        input.demTexPos.x < 0.0 || input.demTexPos.x > 1.0 ||
        input.demTexPos.y < 0.0 || input.demTexPos.y > 1.0) {
        discard;
    }
    // fragCoord.w = 1/clip.w — как gl_FragCoord.w
    let opacity = clamp(
        1.0 + input.distanceOffset - abs(input.distance * input.fragCoord.w),
        0.0,
        1.0,
    );
    // color premultiplied; свет — только rgb
    let color = uniforms.color * opacity;
    // Порт apply_fog из simple_line_3d.fsh
    return applyFog(fog, vec4f(color.rgb * surfaceLight(input.fragCoord), color.a), input.fogPos);
}
`,WB=`// Порт line.vsh: боковая AA-окантовка стены lineExtrusion (sideStroke, stride 24) —
// 1px экранная экструзия контура стены по направлению ребра; нормаль стены для света
// строится поворотом bevel-нормали комплексным умножением на normal_delta.
// Градиент sideStrokeColor, fog/jitter/shadow и ECEF-путь исходника не портированы.

const MAP_POINTS_IN_METER: f32 = 107.17318796639701;
const UNPACK_CENTROID: f32 = 8.0 / 65535.0;
const VERTICAL_SCALE: f32 = (32768.0 / 65535.0) / 1048576.0;
const Z_SCALE: f32 = 1048576.0 / (32768.0 / 65535.0);

// Коеффициент перед w, чтобы влезть в mediump во фрагментном шейдере (порт g_w_factor)
const W_FACTOR = 1e-6;
const MIN_DENOMINATOR = 1e-4;
// Количество пикселей, на которое смещаемся (порт g_shift_pixels)
const SHIFT_PIXELS = 1.0;

struct Uniforms {
    mvpMatrix: mat4x4f,
    color: vec4f,
    // y/z: разрешение канваса в px, w: height factor (x не используется — сдвиг фиксирован 1px)
    params: vec4f,
    demTexMvp: mat4x4f,
    // x = demScale (0 — рельеф выключен), y = centerElevation (м)
    demParams: vec4f,
    // xyz = (тайл − камера)/fogDistance, w = 1/fogDistance; нули = туман выключен
    fogOrigin: vec4f,
    // x = XY-масштаб модели тайла (маппоинты на единицу pos), y = подъём этажа (tile-z)
    fogParams: vec4f,
};

struct VertexOutput {
    @builtin(position) position: vec4f,
    @location(0) normal: vec3f,
    @location(1) distance: f32,
    // Порт v_fog_pos: (world_pos − cam_pos)/fog_distance
    @location(2) fogPos: vec3f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(1) @binding(0) var demTex: texture_2d<f32>;
@group(1) @binding(1) var demSampler: sampler;

fn demHeight(coords: vec2f) -> f32 {
    let demScale = uniforms.demParams.x;
    if (demScale == 0.0) {
        return 0.0;
    }
    let texPos = (uniforms.demTexMvp * vec4f(coords, 0.0, 1.0)).xy;
    let elevation = textureSampleLevel(demTex, demSampler, vec2f(texPos.x, 1.0 - texPos.y), 0.0);
    // Порт dem_height_direct_meters: без данных рельефа — 0 м (уровень моря), как в WebGL
    var meters = elevation.r;
    if (elevation.a < 1.0) {
        meters = 0.0;
    }
    return (meters - uniforms.demParams.y) * MAP_POINTS_IN_METER * VERTICAL_SCALE * demScale;
}

// Перемножение двух комплексных чисел (порт multiply_complex)
fn multiplyComplex(lhs: vec2f, rhs: vec2f) -> vec2f {
    return vec2f(lhs.x * rhs.x - lhs.y * rhs.y, lhs.x * rhs.y + lhs.y * rhs.x);
}

@vertex
fn main(
    @location(0) pos: vec2f,
    // direction s8×3 @12 + distance s8 @15 одним атрибутом (в WebGPU нет sint8x3)
    @location(1) dirDist: vec4i,
    @location(2) z: f32,
    @location(3) demPos: vec2i,
    // normal s8×2 @8 + normal_delta s8×2 @10 одним атрибутом
    @location(5) normals: vec4i,
) -> VertexOutput {
    var height = demHeight(vec2f(demPos) * UNPACK_CENTROID);
    // притягиваем к рельефу основание стены (порт line.vsh:61-66)
    if (z == 0.0) {
        let posHeight = demHeight(pos);
        if (height > posHeight) {
            height = posHeight;
        }
    }
    // Порт \`height += u_float_floor_elevation\` (line.vsh:68)
    height += uniforms.fogParams.y;

    let m = uniforms.mvpMatrix;
    let zMvp = mat4x4f(m[0], m[1], m[2] * Z_SCALE, m[3]);
    let halfViewport = uniforms.params.yz * 0.5;

    // Направление ребра: к z-компоненте прибавляется высота рельефа (порт line.vsh:80)
    let direction = vec3f(dirDist.xyz);
    let clipDirection = zMvp *
        vec4f(vec3f(direction.xy, direction.z + height) / 127.0, 0.0);

    // height factor до clip-space; вершину не пускаем ниже рельефа (порт :89-91)
    var vertexZ = z * uniforms.params.w + height;
    vertexZ = max(vertexZ, height);
    let clipVertex = zMvp * vec4f(pos, vertexZ, 1.0);

    let screenDirection =
        (clipDirection.xy * clipVertex.w - clipVertex.xy * clipDirection.w) * halfViewport;
    let screenPerp = vec2f(-screenDirection.y, screenDirection.x);
    let denominator = max(MIN_DENOMINATOR, length(screenPerp));

    let bevelNormal = vec2f(normals.xy) / 127.0;
    let normalDelta = vec2f(normals.zw) / 127.0;

    let clipBevelNormal = zMvp * vec4f(bevelNormal, 0.0, 0.0);
    let screenBevelNormal =
        (clipBevelNormal.xy * clipVertex.w - clipVertex.xy * clipBevelNormal.w) * halfViewport;
    let bevelDenominator = max(MIN_DENOMINATOR, length(screenBevelNormal));

    // Экранная проекция нормали решает, в какую сторону крутить bevel-нормаль (порт :109-110)
    let normalFactor = -dot(screenBevelNormal, screenPerp) / denominator / bevelDenominator;
    let wallNormal = multiplyComplex(
        bevelNormal,
        vec2f(normalDelta.x, sign(normalFactor) * normalDelta.y),
    );

    let dist = f32(dirDist.w);
    let position = W_FACTOR * (clipVertex +
        vec4f(screenPerp / halfViewport, 0.0, 0.0) * SHIFT_PIXELS * dist / denominator * clipVertex.w);

    var output: VertexOutput;
    output.position = position;
    output.normal = vec3f(wallNormal, 0.0);
    output.distance = dist * position.w;
    // Порт calc_fog_pos: xy в маппоинтах через масштаб модели (fogParams.x),
    // z — нормализованный tile-z → маппоинты (Z_SCALE)
    output.fogPos = uniforms.fogOrigin.xyz +
        vec3f(pos * uniforms.fogParams.x, vertexZ * Z_SCALE) * uniforms.fogOrigin.w;
    return output;
}
`,HB=`// Порт line.fsh: затухание по экранной дистанции от контура + направленный свет
// по нормали стены. Градиент (u_mat4_gradient), fog/color-effect не портированы.
struct Uniforms {
    mvpMatrix: mat4x4f,
    color: vec4f,
    params: vec4f,
};

struct FragmentInput {
    @builtin(position) fragCoord: vec4f,
    @location(0) normal: vec3f,
    @location(1) distance: f32,
    @location(2) fogPos: vec3f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(0) @binding(1) var<uniform> light: LightBlock;
// binding 2 — глобус, только вершинная стадия; FogBlock — chunk fog.wgsl
@group(0) @binding(3) var<uniform> fog: FogBlock;
// Тени кадра — chunk shadow.wgsl (ShadowBlock + карта теней + comparison-сэмплер)
@group(0) @binding(4) var<uniform> shadow: ShadowBlock;
@group(0) @binding(5) var shadowTex: texture_depth_2d;
@group(0) @binding(6) var shadowSampler: sampler_comparison;

@fragment
fn main(input: FragmentInput) -> @location(0) vec4f {
    // Порт line.fsh:28: color *= (1 - abs(distance * gl_FragCoord.w))
    let fade = clamp(1.0 - abs(input.distance * input.fragCoord.w), 0.0, 1.0);
    let color = uniforms.color * fade;
    // Нормаль без normalize — как WebGL light_factor (длина ≈ 1 после s8-распаковки)
    // Порт apply_fog из line.fsh
    return applyFog(fog, vec4f(color.rgb * lightFactor(input.normal, input.fragCoord), color.a), input.fogPos);
}
`,YB=`// Порт one_way_line.vsh (oneWayLine.raster, OneWay12): квад по direction+widen_direction,
// экранный довод на g_shift_pixels (pixel_offset.vsh). border_width в WebGL всегда 0
// (oneWayLineUniforms) — бордер не носим. Fog/jitter исходника не портированы.
// Общие функции стрелки — chunk lineSpriteArrow.wgsl.
struct Uniforms {
    mvpMatrix: mat4x4f,
    // Цвет стрелки (premultiplied)
    color: vec4f,
    borderColor: vec4f,
    // x: width_zpt, y: border_width_zpt (= 0), z: length_zpt, w: size_factor
    params: vec4f,
    // x: tip_height_multiplier, y: wing_height_multiplier, z: wing_width_multiplier, w: opacity
    params2: vec4f,
    // x: calculation_scale, y: style/style_clamped, z: border_width_offset, w: rounding_radius
    scaleParams: vec4f,
    // x, y: разрешение таргета в px
    resolution: vec4f,
    // x: vertex_shift, y: tip_movement_amplitude, z: relative_end_position (только arrow)
    animParams: vec4f,
};

struct VertexOutput {
    @builtin(position) position: vec4f,
    @location(0) texcoord: vec2f,
    // x: zpt_to_texcoord_factor, y: outer_width
    @location(1) arrowFactors: vec2f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;

// Количество пикселей, на которое смещаемся (g_shift_pixels one_way_line.vsh)
const SHIFT_PIXELS = 2.0;

@vertex
fn main(
    @location(0) pos: vec2f,
    @location(1) directionPacked: vec2i,
    @location(2) widenDirectionPacked: vec2i,
) -> VertexOutput {
    let arrowParams = calcArrowParams(
        uniforms.scaleParams.x,
        uniforms.params.x,
        uniforms.params.y,
        uniforms.params.z,
        uniforms.params2.z,
        uniforms.params2.y,
        uniforms.params2.x,
        uniforms.params.w,
    );

    let direction = vec2f(directionPacked) * (1.0 / 127.0);
    let untransformedWiden = vec2f(widenDirectionPacked) * arrowParams.widenSize;
    let widen = multiplyComplex(untransformedWiden * arrowParams.finalSize, direction);

    let shiftPixels =
        SHIFT_PIXELS * sqrt(2.0) / min(abs(untransformedWiden.x), abs(untransformedWiden.y));
    let shift = calcSpriteVertexShift(
        uniforms.mvpMatrix,
        uniforms.resolution.xy,
        pos,
        widen,
        shiftPixels,
    );

    var output: VertexOutput;
    // Деление позиции на размер вместо домножения производных — не переполнить mediump
    output.position = shift.clipVertex / arrowParams.finalSize * SPRITE_W_FACTOR;
    output.texcoord = untransformedWiden * (1.0 + shift.limitedFactor);
    output.arrowFactors = vec2f(arrowParams.zptToTexcoordFactor, arrowParams.outerWidth);
    return output;
}
`,XB=`// Порт one_way_line.fsh (oneWayLine.raster): SDF-стрелка одностороннего движения.
// border_width в WebGL всегда 0 (oneWayLineUniforms) — fill- и border-дистанции совпадают.
// Fog исходника не портирован. Общие функции стрелки — chunk lineSpriteArrow.wgsl.
struct Uniforms {
    mvpMatrix: mat4x4f,
    color: vec4f,
    borderColor: vec4f,
    // x: width_zpt, y: border_width_zpt (= 0), z: length_zpt, w: size_factor
    params: vec4f,
    // x: tip_height_multiplier, y: wing_height_multiplier, z: wing_width_multiplier, w: opacity
    params2: vec4f,
    scaleParams: vec4f,
    resolution: vec4f,
    animParams: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;

// Порт one_way_line_distance (one_way_line.fsh)
fn oneWayLineDistance(d: ArrowDistances) -> f32 {
    return max(
        max(max(d.topTipCut, d.bottomTipCut), max(d.topLeftWing, d.topRightWing)),
        min(d.lineDist, min(d.bottomLeftWing, d.bottomRightWing)),
    );
}

@fragment
fn main(
    @location(0) texcoord: vec2f,
    @location(1) arrowFactors: vec2f,
) -> @location(0) vec4f {
    let derivatives = mat2x2f(dpdx(texcoord), dpdy(texcoord));
    let zptToTexcoordFactor = arrowFactors.x;

    let wingNormal = -normalize(vec2f(uniforms.params2.z, uniforms.params2.y));
    let tipNormal = normalize(vec2f(uniforms.params2.z, uniforms.params2.x));
    let arrowParams = calcArrowDistParams(
        wingNormal,
        tipNormal,
        uniforms.params.x * zptToTexcoordFactor,
        uniforms.params.z * zptToTexcoordFactor,
        uniforms.params2.x,
        uniforms.params2.y,
        0.0,
        0.0,
        0.0,
        vec2f(0.0),
        vec2f(0.0),
    );

    // Срезаем окантовку крыльев стрелки, чтоб не торчала при больших углах
    let borderClipping = (abs(texcoord.y) - arrowFactors.y) /
        max(abs(derivatives[0].y), abs(derivatives[1].y));

    // border_width = 0 → у fill- и border-проходов одна дистанция
    let dist = oneWayLineDistance(calcArrowDistances(arrowParams, texcoord, 0.0, derivatives));
    let fillFactor = affineStep(-1.0, 0.0, dist);
    let borderFactor = max(borderClipping, affineStep(0.0, 1.0, dist));

    // apply_opacity дважды — как в исходнике (vsh к цветам + fsh к результату)
    let opacity = uniforms.params2.w;
    let fillColor = uniforms.color * opacity;
    let borderColor = uniforms.borderColor * opacity;
    return mix(mix(fillColor, borderColor, fillFactor), vec4f(0.0), borderFactor) * opacity;
}
`,ZB=`// Порт arrow_line_entrance.vsh (arrow.stroke, Arrow36): линия + стрелочка входа
// с анимацией bounce/grow (u_float_vertex_shift / u_float_relative_end_position)
// и скруглением ENTRANCE_ARROWS_ROUNDING (в WebGL включено на не-deprecated системах).
// Fog исходника не портирован. Общие функции стрелки — chunk lineSpriteArrow.wgsl.
struct Uniforms {
    mvpMatrix: mat4x4f,
    // Цвет стрелки (premultiplied)
    color: vec4f,
    // Цвет окантовки (premultiplied)
    borderColor: vec4f,
    // x: width_zpt, y: border_width_zpt, z: length_zpt (не используется arrow), w: size_factor
    params: vec4f,
    // x: tip_height_multiplier, y: wing_height_multiplier, z: wing_width_multiplier, w: opacity
    params2: vec4f,
    // x: calculation_scale, y: style/style_clamped, z: border_width_offset, w: rounding_radius
    scaleParams: vec4f,
    // x, y: разрешение таргета в px
    resolution: vec4f,
    // x: vertex_shift, y: tip_movement_amplitude (scene), z: relative_end_position
    animParams: vec4f,
    // xyz = (тайл − камера)/fogDistance, w = масштаб тайла/fogDistance; нули = туман выключен
    fogOrigin: vec4f,
};

struct VertexOutput {
    @builtin(position) position: vec4f,
    // x: тип вершины, y: часть хвоста стрелки, которую нужно скрыть
    @location(0) lineTypeArrowTail: vec2f,
    // Ширина, длина, окантовка и внешняя граница обрезки крыльев (текстурные координаты)
    @location(1) arrowWidthLengthBorderOuter: vec4f,
    // xy: текстурные координаты стрелочки, zw: линии
    @location(2) texcoordArrowLine: vec4f,
    // Порт v_vec4_distance_vertex_hiding (см. arrow_line_entrance.vsh)
    @location(3) distanceVertexHiding: vec4f,
    // Радиусы скругления кончика/крыльев/хвоста (текстурные координаты)
    @location(4) radiusTipWingTail: vec3f,
    // Центры окружностей скругления кончика (xy) и крыла (zw)
    @location(5) circleCenterTipWing: vec4f,
    // Порт v_fog_pos: (world_pos − cam_pos)/fog_distance
    @location(6) fogPos: vec3f,
    // id объекта — читает только lineArrowIdentify.frag (порт entranceIdentify)
    @location(15) @interpolate(flat) identifier: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;

// Типы вершин (arrow_line_entrance.vsh)
const TYPE_ARROW = 1.0;
const TYPE_START_BORDER = 2.0;
const TYPE_LINE_ENDING = 3.0;
const TYPE_LINE_CUT = 4.0;

// Количество пикселей, на которое смещаемся (g_shift_pixels)
const SHIFT_PIXELS = 2.0;
// Размер пересечения сегмента линии и стрелочки (g_line_overlapping_part)
const LINE_OVERLAPPING_PART = 0.2;

@vertex
fn main(
    @location(0) pos: vec2f,
    @location(1) segmentEnd: vec2f,
    // xy: texture_widen (линии), zw: arrow_widen (стрелочки), упаковка s8·invSqrt2·127
    @location(2) textureWidenArrowWiden: vec4i,
    @location(3) widenPacked: vec2i,
    @location(4) directionPacked: vec2i,
    @location(5) distanceFromStart: f32,
    @location(6) objectLength: f32,
    @location(7) vertexType: f32,
    @location(8) identifier: vec4f,
) -> VertexOutput {
    let calculationScale = uniforms.scaleParams.x;
    let widthZpt = uniforms.params.x;
    let borderWidthZpt = uniforms.params.y;
    let sizeFactor = uniforms.params.w;
    let arrowSegmentLengthZpt = widthZpt * uniforms.params2.x + borderWidthZpt;

    // Направление текущего сегмента линии
    let isReversed = vertexType == TYPE_LINE_ENDING || vertexType == TYPE_LINE_CUT;
    let segmentDirection =
        select(normalize(segmentEnd - pos), normalize(pos - segmentEnd), isReversed);
    let segmentLength = length(segmentEnd - pos);

    // erase_length_end(): скрываемая часть конца линии (grow-анимация)
    let eraseLengthEnd = clamp(uniforms.animParams.z, 0.0, 1.0) * objectLength;
    let distanceToEnd = eraseLengthEnd - distanceFromStart;

    let arrowParams = calcArrowParams(
        calculationScale,
        widthZpt,
        borderWidthZpt,
        arrowSegmentLengthZpt,
        uniforms.params2.z,
        uniforms.params2.y,
        uniforms.params2.x,
        sizeFactor,
    );

    let vertexWiden = vec2f(widenPacked) * SPRITE_WIDEN_UNPACK;
    let textureWidenWithSign = vec2f(textureWidenArrowWiden.xy) * SPRITE_WIDEN_UNPACK;
    let arrowTextureWiden = vec2f(textureWidenArrowWiden.zw) * SPRITE_WIDEN_UNPACK;

    // В texture_widen закодировано направление сдвига вдоль направляющей:
    // при сдвиге к началу вектор перевёрнут на 180°
    let shiftSign = sign(dot(vertexWiden, textureWidenWithSign));
    let lineTextureWiden = shiftSign * textureWidenWithSign;

    let isArrow = vertexType == TYPE_ARROW;
    let lineFinalSize = (widthZpt + 2.0 * borderWidthZpt) * sizeFactor * calculationScale;
    let finalSize = select(lineFinalSize, arrowParams.finalSize, isArrow);

    // Ограничиваем смещение вершины половиной длины сегмента (см. комментарий исходника)
    let lineTextureWidenPerp = vec2f(-lineTextureWiden.y, lineTextureWiden.x);
    let shiftDistance = abs(dot(vertexWiden, lineTextureWidenPerp)) * finalSize;
    let shiftDirection = lineTextureWidenPerp * sign(dot(vertexWiden, lineTextureWidenPerp));
    let lineVertexShift =
        vertexWiden * finalSize - shiftDirection * max(0.0, shiftDistance - 0.5 * segmentLength);

    let arrowVertexWiden = vertexWiden * arrowParams.finalSize;
    let sceneVertexShift = select(lineVertexShift, arrowVertexWiden, isArrow);
    // Копия стрелочки в каждом сегменте сдвигается к границе скрытия (arrow_shift)
    let arrowPositionShift = select(vec2f(0.0), segmentDirection * distanceToEnd, isArrow);

    // vertex_shift(scale): bounce-анимация вдоль a_vec2_direction
    let bounceShift = uniforms.animParams.x * uniforms.animParams.y *
        (vec2f(directionPacked) * (1.0 / 127.0)) * calculationScale;

    let shift = calcSpriteVertexShift(
        uniforms.mvpMatrix,
        uniforms.resolution.xy,
        pos + bounceShift + arrowPositionShift,
        sceneVertexShift,
        SHIFT_PIXELS * sqrt(2.0),
    );

    let arrowLineTexcoordScale = lineFinalSize / arrowParams.finalSize;
    let lineTexcoordScale = select(1.0, arrowLineTexcoordScale, !isArrow);
    let lineTexcoord = lineTextureWiden * (1.0 + shift.limitedFactor) * lineTexcoordScale;

    // Прямоугольник окантовки начала линии совпадает с размером линии
    let arrowTexcoordScale = select(1.0, arrowLineTexcoordScale, vertexType == TYPE_START_BORDER);
    let arrowTexcoord = arrowTextureWiden * (1.0 + shift.limitedFactor) * arrowTexcoordScale;

    let zptToTexcoord = arrowParams.zptToTexcoordFactor;
    let arrowWidth = widthZpt * zptToTexcoord;
    let arrowLength = arrowSegmentLengthZpt * zptToTexcoord;
    let roundingRadius = uniforms.scaleParams.w * zptToTexcoord;

    // Уменьшаем окантовку на 1 псевдопиксель (в пиксельном шейдере добавляется 1 экранный px)
    let texcoordBorderWidth = borderWidthZpt * zptToTexcoord;
    let borderWidthTexcoordOffset = uniforms.scaleParams.z * zptToTexcoord;
    let arrowBorder =
        max(0.0, texcoordBorderWidth - uniforms.scaleParams.y * borderWidthTexcoordOffset);

    // Часть хвоста стрелки/начала линии, скрываемая, чтобы не выйти за соседнюю вершину
    let tailShiftDirection =
        select(-1.0, 1.0, vertexType == TYPE_LINE_ENDING || vertexType == TYPE_START_BORDER);
    let tailHideShift = dot(arrowVertexWiden, tailShiftDirection * segmentDirection);
    let arrowTailHidePart = (distanceToEnd - tailHideShift) * zptToTexcoord / sizeFactor;

    // Центры окружностей скругления — формула Крамера (см. исходник)
    let halfLength = arrowLength / 2.0;
    let arrowHeight = arrowWidth * (uniforms.params2.x - uniforms.params2.y);
    let a1 = arrowParams.tipNormal.x;
    let b1 = arrowParams.tipNormal.y;
    let c1 = -halfLength * a1 - arrowBorder + roundingRadius;
    let a2 = arrowParams.wingNormal.x;
    let b2 = arrowParams.wingNormal.y;
    let c2 = (arrowHeight - halfLength) * a2 - arrowBorder + roundingRadius;
    let denominator = a1 * b2 - a2 * b1;
    let wingCircleCenter =
        vec2f((c2 * b1 - c1 * b2) / denominator, (a2 * c1 - a1 * c2) / denominator);
    let tipCircleCenter = vec2f(halfLength - (roundingRadius - arrowBorder) / a1, 0.0);

    // set_distance_varyings: видимость дубликата стрелочки + скрытие начала/конца линии
    let entranceArrowDistanceShift = arrowParams.finalSize * (2.0 - LINE_OVERLAPPING_PART);
    var distanceShift = shiftSign * shiftDistance + entranceArrowDistanceShift;
    var invisible = false;
    if (isArrow) {
        // Сдвиг стрелочки больше длины сегмента / сегмент за границей скрытия конца
        let outsideOfCurrentSegment = distanceToEnd > segmentLength + entranceArrowDistanceShift;
        let insideEndHide = distanceFromStart + entranceArrowDistanceShift > eraseLengthEnd;
        distanceShift = distanceShift + distanceToEnd;
        invisible = outsideOfCurrentSegment || insideEndHide;
    }
    let distanceVertexHiding = vec4f(
        distanceFromStart + distanceShift,
        0.0,
        eraseLengthEnd,
        select(0.0, objectLength, invisible),
    ) / objectLength;

    var output: VertexOutput;
    // Деление позиции на размер вместо домножения производных — не переполнить mediump
    output.position = shift.clipVertex / finalSize * SPRITE_W_FACTOR;
    output.lineTypeArrowTail = vec2f(vertexType, arrowTailHidePart);
    output.arrowWidthLengthBorderOuter =
        vec4f(arrowWidth, arrowLength, arrowBorder, arrowParams.outerWidth);
    output.texcoordArrowLine = vec4f(arrowTexcoord, lineTexcoord);
    output.distanceVertexHiding = distanceVertexHiding;
    output.radiusTipWingTail = vec3f(roundingRadius, roundingRadius, roundingRadius);
    output.circleCenterTipWing = vec4f(tipCircleCenter, wingCircleCenter);
    output.identifier = identifier;
    // Порт calc_fog_pos (arrow_line_entrance.vsh) — по якорной позиции квада
    output.fogPos = uniforms.fogOrigin.xyz + vec3f(pos, 0.0) * uniforms.fogOrigin.w;
    return output;
}
`,jB=`// Порт arrow_line.fsh (arrow.stroke): SDF линии + стрелочки входа со скруглением
// (ENTRANCE_ARROWS_ROUNDING включён — как WebGL на не-deprecated системах).
// Fog исходника не портирован. Все производные подняты в main (uniformity-анализ WGSL
// запрещает dpdx под неоднородным ветвлением). Общие функции — chunk lineSpriteArrow.wgsl.
struct Uniforms {
    mvpMatrix: mat4x4f,
    color: vec4f,
    borderColor: vec4f,
    // x: width_zpt, y: border_width_zpt, z: length_zpt, w: size_factor
    params: vec4f,
    // x: tip_height_multiplier, y: wing_height_multiplier, z: wing_width_multiplier, w: opacity
    params2: vec4f,
    scaleParams: vec4f,
    resolution: vec4f,
    animParams: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
// FogBlock — chunk fog.wgsl
@group(0) @binding(1) var<uniform> fog: FogBlock;

const TYPE_ARROW = 1.0;
const TYPE_START_BORDER = 2.0;

fn lookalike(a: f32, b: f32) -> bool {
    return abs(a - b) < 1e-4;
}

// Отфильтрованное сглаживание: [-1, 0] — заливка→окантовка, [0, 1] — окантовка→прозрачный
fn filterBorder(start: f32, value: f32) -> f32 {
    return step(start, value) * 2.0 - 1.0;
}

// Порт arrow_distance (arrow_line.fsh): расстояние до границы стрелочки со скрытием хвоста
fn arrowDistance(
    p: ArrowDistParams,
    texcoord: vec2f,
    offset: f32,
    derivatives: mat2x2f,
    lineDistance: f32,
    lineDistanceNoOffset: f32,
    hideTail: bool,
    tailHidePart: f32,
) -> f32 {
    let ad = calcArrowDistances(p, texcoord, offset, derivatives);
    let derivativesXMultiplier = 1.0 / max(abs(derivatives[0].x), abs(derivatives[1].x));

    // Хвост полностью скрыт → граница между точками пересечения нижних крыльев с линией
    let intersectionPoint = p.fullLength - p.arrowHeight -
        p.halfWidth * p.wingNormal.y / p.wingNormal.x;
    let tailArrowIntersection =
        filterBorder(-1.0, (texcoord.x - intersectionPoint) * derivativesXMultiplier);

    // Соединение всех элементов стрелочки (ветка ENTRANCE_ARROWS_ROUNDING)
    var topWings = max(max(ad.topLeftWing, ad.topRightWing), ad.tipCircleCut);
    topWings = min(topWings, ad.tipCircle);
    topWings = max(topWings, ad.topTipCut);

    let wingsCircles = min(ad.leftWingCircle, ad.rightWingCircle);
    let wingsRadiusCut = max(ad.leftWingCircleCut, ad.rightWingCircleCut);
    var bottomWings = min(ad.bottomLeftWing, ad.bottomRightWing);
    bottomWings = max(bottomWings, wingsRadiusCut);
    bottomWings = min(bottomWings, wingsCircles);

    let lineWithoutOffset = filterBorder(0.0, lineDistanceNoOffset);
    let bottomWingsWithTail = min(bottomWings, lineWithoutOffset);
    let wingsWithTail = max(bottomWingsWithTail, topWings);

    // Маска скрытия хвоста стрелки
    let tailHideMask = (-texcoord.x - tailHidePart) * derivativesXMultiplier;
    let clippedTail = max(tailHideMask, max(lineDistance, topWings));

    let hiddenTailDistance = max(-max(tailArrowIntersection, lineWithoutOffset), wingsWithTail);
    return select(min(clippedTail, hiddenTailDistance), hiddenTailDistance, hideTail);
}

// Порт line_start_distance (arrow_line.fsh): окантовка начала линии со скруглением
fn lineStartDistance(
    texcoord: vec2f,
    offset: f32,
    derivatives: mat2x2f,
    lineDistance: f32,
    halfWidth: f32,
    borderWidth: f32,
    tailRadius: f32,
    tailHidePart: f32,
) -> f32 {
    let derivativesXMultiplier = 1.0 / max(abs(derivatives[0].x), abs(derivatives[1].x));

    // Основной прямоугольник хвоста
    let d0 = (-texcoord.x - offset) * derivativesXMultiplier;
    let dh = (texcoord.x - tailHidePart) * derivativesXMultiplier;
    var rect = max(d0, max(lineDistance, dh));

    // Вырезание областей и вставка окружностей скругления
    let radiusOffset = tailRadius - borderWidth;
    let circleRadius = radiusOffset + offset;
    let leftCircleCenter = vec2f(radiusOffset, halfWidth - radiusOffset);
    let rightCircleCenter = vec2f(radiusOffset, -halfWidth + radiusOffset);
    let leftCircleNormal = normalize(texcoord - leftCircleCenter);
    let rightCircleNormal = normalize(texcoord - rightCircleCenter);

    let cutX = (-texcoord.x + radiusOffset) * derivativesXMultiplier;
    let cutY = (abs(texcoord.y) - halfWidth + radiusOffset) /
        max(abs(derivatives[0].y), abs(derivatives[1].y));
    let circlesCut = min(cutX, cutY);

    let leftCircle = (length(texcoord - leftCircleCenter) - circleRadius) /
        max(abs(dot(derivatives[0], leftCircleNormal)), abs(dot(derivatives[1], leftCircleNormal)));
    let rightCircle = (length(texcoord - rightCircleCenter) - circleRadius) /
        max(abs(dot(derivatives[0], rightCircleNormal)), abs(dot(derivatives[1], rightCircleNormal)));
    let circles = min(leftCircle, rightCircle);

    rect = min(max(rect, circlesCut), circles);
    return rect;
}

@fragment
fn main(
    @location(0) lineTypeArrowTail: vec2f,
    @location(1) arrowWidthLengthBorderOuter: vec4f,
    @location(2) texcoordArrowLine: vec4f,
    @location(3) distanceVertexHiding: vec4f,
    @location(4) radiusTipWingTail: vec3f,
    @location(5) circleCenterTipWing: vec4f,
    @location(6) fogPos: vec3f,
) -> @location(0) vec4f {
    // Производные обеих texcoord — до любых неоднородных ветвлений (uniformity-анализ)
    let arrowTexcoord = texcoordArrowLine.xy;
    let lineTexcoord = texcoordArrowLine.zw;
    let arrowDerivatives = mat2x2f(dpdx(arrowTexcoord), dpdy(arrowTexcoord));
    let lineDerivatives = mat2x2f(dpdx(lineTexcoord), dpdy(lineTexcoord));

    let dvh = distanceVertexHiding;
    let vertexType = lineTypeArrowTail.x;
    if (lookalike(min(dvh.y, 1.0), 1.0) ||
        lookalike(dvh.w, 1.0) ||
        (!lookalike(vertexType, TYPE_ARROW) && (dvh.x < dvh.y || dvh.x > dvh.z))) {
        discard;
    }

    let wingNormal = -normalize(vec2f(uniforms.params2.z, uniforms.params2.y));
    let tipNormal = normalize(vec2f(uniforms.params2.z, uniforms.params2.x));

    let arrowParams = calcArrowDistParams(
        wingNormal,
        tipNormal,
        arrowWidthLengthBorderOuter.x,
        arrowWidthLengthBorderOuter.y,
        uniforms.params2.x,
        uniforms.params2.y,
        radiusTipWingTail.x,
        radiusTipWingTail.y,
        arrowWidthLengthBorderOuter.z,
        circleCenterTipWing.xy,
        circleCenterTipWing.zw,
    );

    let lineWidth = arrowParams.halfWidth;
    let lineBorder = arrowWidthLengthBorderOuter.z;

    // Расстояния до границы линии и её окантовки
    let circleFillDistance = circleColorDistance(lineDerivatives, lineTexcoord, lineWidth);
    let circleBorderDistance =
        circleColorDistance(lineDerivatives, lineTexcoord, lineWidth + lineBorder);
    let lineFillDistance =
        affineStep(-1.0, 0.0, circleFillDistance.dist / circleFillDistance.width) - 1.0;
    let lineBorderDistance =
        affineStep(0.0, circleBorderDistance.width, circleBorderDistance.dist);

    let opacity = uniforms.params2.w;
    let fillColor = uniforms.color * opacity;
    let borderColor = uniforms.borderColor * opacity;
    let hideTail = dvh.x < dvh.y;
    let tailHidePart = lineTypeArrowTail.y;

    if (lookalike(vertexType, TYPE_ARROW)) {
        // Срезаем окантовку крыльев стрелки, чтоб не торчала при больших углах
        let borderClipping = (abs(arrowTexcoord.y) - arrowWidthLengthBorderOuter.w) /
            max(abs(arrowDerivatives[0].y), abs(arrowDerivatives[1].y));

        let arrowBorderDistance = arrowDistance(
            arrowParams,
            arrowTexcoord,
            lineBorder,
            arrowDerivatives,
            lineBorderDistance,
            lineFillDistance,
            hideTail,
            tailHidePart,
        );
        let borderFactor = max(borderClipping, affineStep(0.0, 1.0, arrowBorderDistance));
        let arrowFillDistance = arrowDistance(
            arrowParams,
            arrowTexcoord,
            0.0,
            arrowDerivatives,
            lineFillDistance,
            lineFillDistance,
            hideTail,
            tailHidePart,
        );
        // Порт apply_fog из arrow_line.fsh
        return applyFog(
            fog,
            spriteDistanceToColor(arrowFillDistance, borderFactor, fillColor, borderColor),
            fogPos,
        );
    }

    // Линия; в начале — окантовка со скруглением (TYPE_START_BORDER)
    var fillDistance = lineFillDistance;
    var borderDistance = lineBorderDistance;
    if (lookalike(vertexType, TYPE_START_BORDER)) {
        fillDistance = lineStartDistance(
            arrowTexcoord,
            0.0,
            arrowDerivatives,
            lineFillDistance,
            lineWidth,
            lineBorder,
            radiusTipWingTail.z,
            tailHidePart,
        );
        borderDistance = lineStartDistance(
            arrowTexcoord,
            lineBorder,
            arrowDerivatives,
            lineBorderDistance,
            lineWidth,
            lineBorder,
            radiusTipWingTail.z,
            tailHidePart,
        );
    }
    // Порт apply_fog из arrow_line.fsh
    return applyFog(
        fog,
        spriteDistanceToColor(fillDistance, borderDistance, fillColor, borderColor),
        fogPos,
    );
}
`,Ic=`// Общие функции sprite-линий (oneWayLine/arrow) — порт include/arrow_functions.vsh/.fsh,
// pixel_offset.vsh, signed_distance_functions.vfsh, circle_functions.fsh, affine_step.fsh.
// Подключается chunk'ом к lineOneWay.*/lineArrow.* (см. shaderFactory/webgpu.ts, withChunks).

// Распаковка widen: normalize_s08 · sqrt(2) (packed_attributes.vsh, unpack_widen)
const SPRITE_WIDEN_UNPACK = 0.011135539861205473;
// Коэффициент перед w (g_w_factor one_way_line.vsh / arrow_line_entrance.vsh)
const SPRITE_W_FACTOR = 1e-7;
const SPRITE_MIN_DENOMINATOR = 1e-7;
const SPRITE_MAX_FACTOR = 10000.0;

// Аффинный переход от 0 до 1 (affine_step.fsh)
fn affineStep(edge0: f32, edge1: f32, x: f32) -> f32 {
    return clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0);
}

// Перемножение двух комплексных чисел (arrow_functions.vsh)
fn multiplyComplex(lhs: vec2f, rhs: vec2f) -> vec2f {
    return vec2f(lhs.x * rhs.x - lhs.y * rhs.y, lhs.x * rhs.y + lhs.y * rhs.x);
}

struct SpriteArrowParams {
    zptToTexcoordFactor: f32,
    finalSize: f32,
    outerWidth: f32,
    widenSize: vec2f,
    wingNormal: vec2f,
    tipNormal: vec2f,
};

// Порт calculate_arrow_parameters (arrow_functions.vsh)
fn calcArrowParams(
    calculationScale: f32,
    widthZpt: f32,
    borderWidthZpt: f32,
    segmentLengthZpt: f32,
    wingWidthMultiplier: f32,
    wingHeightMultiplier: f32,
    tipHeightMultiplier: f32,
    sizeFactor: f32,
) -> SpriteArrowParams {
    let quadWidth = 2.0 * borderWidthZpt + 2.0 * wingWidthMultiplier * widthZpt;
    let quadHeight = 2.0 * borderWidthZpt + segmentLengthZpt;

    let maxQuadDimension = max(quadWidth, quadHeight);
    let zptToTexcoordFactor = 2.0 / maxQuadDimension;

    var result: SpriteArrowParams;
    result.zptToTexcoordFactor = zptToTexcoordFactor;
    result.finalSize = calculationScale * sizeFactor * maxQuadDimension;
    result.outerWidth = (widthZpt * wingWidthMultiplier + borderWidthZpt) * zptToTexcoordFactor;
    result.widenSize = 0.5 * vec2f(quadHeight, quadWidth) * zptToTexcoordFactor;
    result.wingNormal = -normalize(vec2f(wingWidthMultiplier, wingHeightMultiplier));
    result.tipNormal = normalize(vec2f(wingWidthMultiplier, tipHeightMultiplier));
    return result;
}

// Порт calculate_multiplication_factor (pixel_offset.vsh): k, на который домножается
// нормаль, чтобы экранное смещение вершины составило shiftPixels пикселей.
fn spriteMultiplicationFactor(
    halfViewport: vec2f,
    clipWiden: vec4f,
    clipWidenPerp: vec4f,
    clipVertex: vec4f,
    shiftPixels: f32,
) -> f32 {
    var limitedFactor = 0.0;

    let screenWiden =
        (clipWiden.xy * clipVertex.w - clipVertex.xy * clipWiden.w) * halfViewport;
    let screenWidenPerp =
        (clipWidenPerp.xy * clipVertex.w - clipVertex.xy * clipWidenPerp.w) * halfViewport;
    let perp = vec2f(screenWidenPerp.y, -screenWidenPerp.x);
    let perpLength = length(perp);

    let denominator =
        dot(perp, screenWiden) / shiftPixels - clipWiden.w * clipVertex.w * perpLength;
    if (abs(denominator) > SPRITE_MIN_DENOMINATOR) {
        let factor = clipVertex.w * clipVertex.w * perpLength / denominator;
        // NaN-гард исходника (factor == factor)
        if (factor == factor) {
            limitedFactor = sign(factor) * min(SPRITE_MAX_FACTOR, abs(factor));
        }
    }

    // Фолбэк при потере точности на мелких масштабах (ниже ~6.5 зума)
    if (limitedFactor == 0.0) {
        let screenWidenFallback = clipWiden.xy / clipVertex.w * halfViewport;
        let screenWidenLength = length(screenWidenFallback);
        if (screenWidenLength > 1e-4) {
            limitedFactor = shiftPixels / screenWidenLength;
        }
    }

    return limitedFactor;
}

struct SpriteVertexShift {
    clipVertex: vec4f,
    limitedFactor: f32,
};

// Порт calculate_vertex_shift_parameters (arrow_functions.vsh)
fn calcSpriteVertexShift(
    mvp: mat4x4f,
    vptSize: vec2f,
    vertex: vec2f,
    widen: vec2f,
    shiftPixels: f32,
) -> SpriteVertexShift {
    let widenPerp = vec2f(-widen.y, widen.x);

    let clipWiden = mvp * vec4f(widen, 0.0, 0.0);
    let clipWidenPerp = mvp * vec4f(widenPerp, 0.0, 0.0);
    let clipVertex = mvp * vec4f(vertex, 0.0, 1.0) + clipWiden;

    let limitedFactor = spriteMultiplicationFactor(
        vptSize / 2.0,
        clipWiden,
        clipWidenPerp,
        clipVertex,
        shiftPixels,
    );

    var result: SpriteVertexShift;
    result.clipVertex = clipVertex + clipWiden * limitedFactor;
    result.limitedFactor = limitedFactor;
    return result;
}

// ── Фрагментная часть: поля знаковых расстояний стрелки ────────────────────

fn sdfCircle(coords: vec2f, radius: f32) -> f32 {
    return length(coords) - radius;
}

// Порт sdf_half_planes_cut (signed_distance_functions.vfsh)
fn sdfHalfPlanesCut(
    coords: vec2f,
    normal1: vec2f,
    normal2: vec2f,
    cutPoint: vec2f,
    derivatives: mat2x2f,
) -> f32 {
    let cutNormal1 = vec2f(normal1.y, -normal1.x);
    let cut1 = dot(coords - cutPoint, cutNormal1) /
        max(abs(dot(derivatives[0], cutNormal1)), abs(dot(derivatives[1], cutNormal1)));
    let cutNormal2 = vec2f(normal2.y, -normal2.x);
    let cut2 = dot(coords - cutPoint, cutNormal2) /
        max(abs(dot(derivatives[0], cutNormal2)), abs(dot(derivatives[1], cutNormal2)));
    return min(cut1, cut2);
}

struct ArrowDistParams {
    wingNormal: vec2f,
    tipNormal: vec2f,
    mirroredWingNormal: vec2f,
    mirroredTipNormal: vec2f,
    halfWidth: f32,
    fullLength: f32,
    arrowHeight: f32,
    tipRadius: f32,
    tipCircleCenter: vec2f,
    wingRadius: f32,
    wingCircleCenter: vec2f,
    borderWidth: f32,
};

// Порт calculate_arrow_distance_parameters (arrow_functions.fsh)
fn calcArrowDistParams(
    wingNormal: vec2f,
    tipNormal: vec2f,
    widthZpt: f32,
    lengthZpt: f32,
    tipHeightMultiplier: f32,
    wingHeightMultiplier: f32,
    tipRadiusZpt: f32,
    wingRadiusZpt: f32,
    borderWidthZpt: f32,
    tipCircleCenter: vec2f,
    wingCircleCenter: vec2f,
) -> ArrowDistParams {
    var result: ArrowDistParams;
    result.wingNormal = wingNormal;
    result.tipNormal = tipNormal;
    result.mirroredWingNormal = vec2f(wingNormal.x, -wingNormal.y);
    result.mirroredTipNormal = vec2f(tipNormal.x, -tipNormal.y);
    result.halfWidth = 0.5 * widthZpt;
    result.fullLength = 0.5 * lengthZpt;
    result.arrowHeight = widthZpt * (tipHeightMultiplier - wingHeightMultiplier);
    result.tipRadius = tipRadiusZpt;
    result.tipCircleCenter = tipCircleCenter;
    result.wingRadius = wingRadiusZpt;
    result.wingCircleCenter = wingCircleCenter;
    result.borderWidth = borderWidthZpt;
    return result;
}

struct ArrowDistances {
    topTipCut: f32,
    bottomTipCut: f32,
    lineDist: f32,
    bottomLeftWing: f32,
    bottomRightWing: f32,
    topLeftWing: f32,
    topRightWing: f32,
    tipCircle: f32,
    tipCircleCut: f32,
    leftWingCircle: f32,
    leftWingCircleCut: f32,
    rightWingCircle: f32,
    rightWingCircleCut: f32,
};

// Порт calculate_arrow_distances (arrow_functions.fsh); что за расстояния —
// https://confluence.2gis.ru/pages/viewpage.action?pageId=239780625
fn calcArrowDistances(
    p: ArrowDistParams,
    texcoord: vec2f,
    offset: f32,
    derivatives: mat2x2f,
) -> ArrowDistances {
    let derivativesXMultiplier = 1.0 / max(abs(derivatives[0].x), abs(derivatives[1].x));
    var d: ArrowDistances;
    d.topTipCut = (texcoord.x - p.fullLength - offset) * derivativesXMultiplier;
    d.bottomTipCut = (-texcoord.x - p.fullLength - offset) * derivativesXMultiplier;
    d.lineDist = (abs(texcoord.y) - p.halfWidth - offset) /
        max(abs(derivatives[0].y), abs(derivatives[1].y));

    let wingAnchor = texcoord - vec2f(p.fullLength - p.arrowHeight, 0.0);
    d.bottomLeftWing = (dot(wingAnchor, p.wingNormal) - offset) /
        max(abs(dot(derivatives[0], p.wingNormal)), abs(dot(derivatives[1], p.wingNormal)));
    d.bottomRightWing = (dot(wingAnchor, p.mirroredWingNormal) - offset) /
        max(abs(dot(derivatives[0], p.mirroredWingNormal)), abs(dot(derivatives[1], p.mirroredWingNormal)));

    let tipAnchor = texcoord - vec2f(p.fullLength, 0.0);
    d.topLeftWing = (dot(tipAnchor, p.tipNormal) - offset) /
        max(abs(dot(derivatives[0], p.tipNormal)), abs(dot(derivatives[1], p.tipNormal)));
    d.topRightWing = (dot(tipAnchor, p.mirroredTipNormal) - offset) /
        max(abs(dot(derivatives[0], p.mirroredTipNormal)), abs(dot(derivatives[1], p.mirroredTipNormal)));

    // Скругление кончика стрелки
    d.tipCircleCut = sdfHalfPlanesCut(
        texcoord,
        p.tipNormal,
        -p.mirroredTipNormal,
        p.tipCircleCenter,
        derivatives,
    );
    let tipCircleRaw = sdfCircle(texcoord - p.tipCircleCenter, p.tipRadius + offset - p.borderWidth);
    let tipCircleNormal = normalize(texcoord - p.tipCircleCenter);
    d.tipCircle = tipCircleRaw /
        max(abs(dot(derivatives[0], tipCircleNormal)), abs(dot(derivatives[1], tipCircleNormal)));

    // Скругление кончиков крыльев
    let rightWingCircleCenter = vec2f(p.wingCircleCenter.x, -p.wingCircleCenter.y);
    let leftWingCircleNormal = normalize(texcoord - p.wingCircleCenter);
    let rightWingCircleNormal = normalize(texcoord - rightWingCircleCenter);

    let wingCircleRadius = p.wingRadius + offset - p.borderWidth;
    d.leftWingCircle = sdfCircle(texcoord - p.wingCircleCenter, wingCircleRadius) /
        max(abs(dot(derivatives[0], leftWingCircleNormal)), abs(dot(derivatives[1], leftWingCircleNormal)));
    d.rightWingCircle = sdfCircle(texcoord - rightWingCircleCenter, wingCircleRadius) /
        max(abs(dot(derivatives[0], rightWingCircleNormal)), abs(dot(derivatives[1], rightWingCircleNormal)));

    d.leftWingCircleCut = sdfHalfPlanesCut(
        texcoord,
        -p.tipNormal,
        p.wingNormal,
        p.wingCircleCenter,
        derivatives,
    );
    d.rightWingCircleCut = sdfHalfPlanesCut(
        texcoord,
        p.mirroredTipNormal,
        -p.mirroredWingNormal,
        rightWingCircleCenter,
        derivatives,
    );
    return d;
}

struct SpriteCircleDistance {
    dist: f32,
    width: f32,
};

// Порт circle_color_distance (circle_functions.fsh)
fn circleColorDistance(
    derivatives: mat2x2f,
    circle: vec2f,
    circleWidth: f32,
) -> SpriteCircleDistance {
    let circleLength = length(circle);
    let distanceValue = circleLength - circleWidth;

    let distanceDx = dot(circle, derivatives[0]);
    let distanceDy = dot(circle, derivatives[1]);

    var result: SpriteCircleDistance;
    result.dist = distanceValue * circleLength;
    result.width = max(abs(distanceDx), abs(distanceDy));
    return result;
}

// Порт distance_to_color (circle_functions.fsh)
fn spriteDistanceToColor(
    fillDistance: f32,
    borderDistance: f32,
    fillColor: vec4f,
    borderColor: vec4f,
) -> vec4f {
    let fillFactor = affineStep(-1.0, 0.0, fillDistance);
    let borderFactor = affineStep(0.0, 1.0, borderDistance);
    return mix(mix(fillColor, borderColor, fillFactor), vec4f(0.0), borderFactor);
}
`,Qo=`// ECEF/глобус (порт include/ecef_mvp_mat.vsh + get_clipspace) — общий chunk
// labeling-шейдеров (склейка через withChunks в shaderFactory/webgpu.ts).
// Объявляет структуру GlobeUniforms и ССЫЛАЕТСЯ на module-scope binding \`globe\` —
// его объявляет основной файл (@group/@binding свои у каждого пасса; module-scope
// имена в WGSL порядконезависимы, поэтому chunk может идти первым).

// Общий на кадр uniform глобуса
struct GlobeUniforms {
    ecefMvp: mat4x4f,
    vp: mat4x4f,
    // xy = [lng (рад), mercatorY] центра камеры
    cameraMercator: vec4f,
    // viewProjection × центр карты, посчитанная в f64 на CPU (якорь flat-реконструкции)
    vpAtCenter: vec4f,
};

const ECEF_CF_NEAR: f32 = 0.01;
const ECEF_WORLD: f32 = 4294967296.0; // 2^32 = worldSize: нормировка ECEF
const ECEF_PI: f32 = 3.141592653589793;
const ECEF_TWO_PI: f32 = 6.283185307179586;
const ECEF_MAX_LAT: f32 = 1.4844222; // ~85.05° (web-mercator clamp)

// Нормализованный tile-z → z-масштаб модели WebGL (m[10]); модель Sunda имеет m[10] = 1
const Z_SCALE: f32 = 1048576.0 / (32768.0 / 65535.0);

fn ecefWrapPi(a: f32) -> f32 {
    return ((a + ECEF_PI) % ECEF_TWO_PI) - ECEF_PI;
}

// Origin-relative flat clip из нормализованной ECEF-позиции (см. polygonFill.vert.wgsl)
fn ecefFlatClip(epos: vec3f) -> vec4f {
    let en = normalize(epos);
    let lng = atan2(en.x, en.z);
    let lat = clamp(asin(clamp(en.y, -1.0, 1.0)), -ECEF_MAX_LAT, ECEF_MAX_LAT);
    let mercY = log(tan(ECEF_PI / 4.0 + lat / 2.0));
    let dLng = ecefWrapPi(lng - globe.cameraMercator.x);
    let relX = dLng / ECEF_TWO_PI * ECEF_WORLD;
    let relY = (mercY - globe.cameraMercator.y) / ECEF_TWO_PI * ECEF_WORLD;
    return globe.vp * vec4f(relX, relY, 0.0, 0.0) + globe.vpAtCenter;
}

// Кроссфейд flat↔globe из нормализованной ECEF-позиции (vertex − 0.5)
fn ecefClip(epos: vec3f, crossfade: f32) -> vec4f {
    if (crossfade > 1.0 - ECEF_CF_NEAR) {
        return globe.ecefMvp * vec4f(epos * ECEF_WORLD, 1.0);
    }
    if (crossfade < ECEF_CF_NEAR) {
        return ecefFlatClip(epos);
    }
    let fclip = ecefFlatClip(epos);
    let eclip = globe.ecefMvp * vec4f(epos * ECEF_WORLD, 1.0);
    return mix(fclip, eclip, crossfade);
}

// Клип якоря лейбла — порт get_clipspace(vertex, flat_z): flat — MVP по тайловым
// координатам (с разнормировкой z); ECEF — декод (pos − 0.5) + кроссфейд, высота
// якоря игнорируется (как в WebGL)
fn anchorClip(mvp: mat4x4f, crossfade: f32, pos: vec4f, anchorZ: f32) -> vec4f {
    if (crossfade > 0.0) {
        return ecefClip(pos.xyz - vec3f(0.5), crossfade);
    }
    let zMvp = mat4x4f(mvp[0], mvp[1], mvp[2] * Z_SCALE, mvp[3]);
    return zMvp * vec4f(pos.xy, anchorZ, 1.0);
}
`,lr=`// Туман (порт include/fog.fsh, FOG_EQUATION = LINEAR). Общий на кадр блок
// FogBlock — биндинг объявляет шейдер-потребитель; fogPos приезжает варингом
// из вершинника: fogOrigin.xyz + pos · fogOrigin.w (порт calc_fog_pos:
// (world_pos − cam_pos) / fog_distance, f64-вычитание сделано на CPU).
// Отсутствие тумана (глобус, fogOff, стиль без fogColor) — нулевой блок:
// fogColor.a ≤ 0.01 выключает обе apply-функции.

struct FogBlock {
    // Цвета premultiplied (как в WebGL-биндере)
    fogColor: vec4f,
    skyColor: vec4f,
    // x = limitStart, y = limitEnd (в единицах fogDistance), z = horizonBlend, w = horizonLevel
    fogParams: vec4f,
};

const FOG_EPSILON: f32 = 0.0001;

// Порт fog_horizon_blending: предполагает z up и нормализованный camera_dir
fn fogHorizonBlending(cameraDirZ: f32, blend: f32) -> f32 {
    let b = FOG_EPSILON + blend;
    let t = max(cameraDirZ / b, 0.0);
    // Степень 3 — примерное соответствие smoothstep (см. fog.fsh)
    return exp(-3.0 * t * t);
}

// Порт fog_depth (линейное распределение): доля тумана по глубине
fn fogDepthFactor(fb: FogBlock, depth: f32) -> f32 {
    let start = fb.fogParams.x;
    let end = fb.fogParams.y;
    return clamp((depth - start) / (end - start), 0.0, 1.0);
}

// Порт calc_fog_color: примесь неба у горизонта (оба цвета де-премультиплицируются)
fn fogMixColor(fb: FogBlock, dir: vec3f) -> vec3f {
    let dz = dir.z - fb.fogParams.w;
    let fogBlend = fogHorizonBlending(dz, fb.fogParams.z);
    if (fb.skyColor.a <= 0.01) {
        return fb.fogColor.rgb / fb.fogColor.a;
    }
    return mix(
        fb.skyColor.rgb / fb.skyColor.a,
        fb.fogColor.rgb / fb.fogColor.a,
        min(fogBlend + (1.0 - fb.skyColor.a), 1.0),
    );
}

// Порт apply_fog: убираем premultiply, подмешиваем туман, умножаем обратно
fn applyFog(fb: FogBlock, color: vec4f, fogPos: vec3f) -> vec4f {
    if (fb.fogColor.a <= 0.01) {
        return color;
    }
    let depth = length(fogPos);
    let fac = fogDepthFactor(fb, depth);
    let dir = fogPos / max(depth, FOG_EPSILON);
    let alpha = FOG_EPSILON + color.a;
    var rgb = color.rgb / alpha;
    rgb = mix(rgb, fogMixColor(fb, dir), fac * fb.fogColor.a);
    return vec4f(rgb * alpha, color.a);
}

// Порт apply_fog_alpha: контент растворяется в тумане (лейблы/иконки/маркеры)
fn applyFogAlpha(fb: FogBlock, color: vec4f, fogPos: vec3f) -> vec4f {
    if (fb.fogColor.a <= 0.01) {
        return color;
    }
    return color * (1.0 - fogDepthFactor(fb, length(fogPos)));
}

// Порт apply_fog_sky: только блэнд с горизонтом, без глубины (небо)
fn applyFogSky(fb: FogBlock, color: vec4f, fogPos: vec3f) -> vec4f {
    if (fb.fogColor.a <= 0.01) {
        return color;
    }
    let depth = length(fogPos);
    let dir = fogPos / max(depth, FOG_EPSILON);
    let dz = dir.z - fb.fogParams.w;
    let fac = fogHorizonBlending(dz, fb.fogParams.z);
    let alpha = FOG_EPSILON + color.a;
    var rgb = color.rgb / alpha;
    // Как в WebGL: fogColor.rgb без де-premultiply (calc_fog_color делит, apply_fog_sky — нет)
    rgb = mix(rgb, fb.fogColor.rgb, fac * fb.fogColor.a);
    return vec4f(rgb * alpha, color.a);
}
`,ox=`// Тени (порт include/shadow.vsh/.fsh + main_shadow: PCF-чтение карты теней) — общий
// chunk приёмников теней. ССЫЛАЕТСЯ на module-scope биндинги \`shadow: ShadowBlock\`,
// \`shadowTex: texture_depth_2d\`, \`shadowSampler: sampler_comparison\` — их объявляет
// основной файл (@group(0), номера биндингов свои у каждого пасса).
//
// В отличие от WebGL (v_pos_from_light из вершинника) позиция в clip источника
// теней восстанавливается во фрагменте из fragCoord (viewport основного пасса):
// ни один вершинник менять не нужно. Нормальный bias — по производным восстановленной
// позиции (порт ветки FRAGMENT_NORMAL: calc_fragment_normal(light_pos)). Отличие от
// WebGL: там bias по производным только у зданий/mapMesh/terrain, плоские приёмники
// (заливки/дороги) идут без него, glTF берёт нормаль вершины — здесь единый путь.

struct ShadowBlock {
    // Clip камеры (WebGPU) → clip источника теней (GL, z ∈ [-1,1]·w)
    clipToShadow: mat4x4f,
    // xy = размер карты теней (px), z = радиус PCF (тексели), w = normal bias (NDC)
    mapParams: vec4f,
    // x = bias по z (NDC), y = индекс света с тенью + 1 (0 = тени выключены),
    // zw = анизотропия орто-фрустума источника (ySize/xSize, zSize/xSize)
    params: vec4f,
    // xy = origin вьюпорта основного пасса (px), zw = его размер (px)
    viewport: vec4f,
};

// Пайплайны flat-каскада/tier-контента (clip не камерный — реконструкция неверна) и
// слоёв без ReceiveShadows собираются с receiveShadows = 0 (ShadowMode 'none')
override receiveShadows: bool = true;
// Обратный множитель clip-позиции вершинника (W_FACTOR линий = 1e-6/1e-7 → 1e6/1e7):
// bias'ы порта заданы в единицах немасштабированного clip и вычитаются до деления на w,
// поэтому w восстанавливаем как у камеры (WebGL передаёт в compute_shadow_vertex clip
// до умножения на g_w_factor)
override shadowClipWScale: f32 = 1.0;

// Clip-позиция фрагмента в пространстве источника теней (GL clip) из fragCoord:
// NDC ← вьюпорт, clip.w = 1/fragCoord.w (порт u_mat4_clip_to_shadow * clip_pos)
fn shadowClipPos(fragCoord: vec4f) -> vec4f {
    let ndcX = (fragCoord.x - shadow.viewport.x) / shadow.viewport.z * 2.0 - 1.0;
    let ndcY = 1.0 - (fragCoord.y - shadow.viewport.y) / shadow.viewport.w * 2.0;
    let w = shadowClipWScale / fragCoord.w;
    return shadow.clipToShadow * vec4f(ndcX * w, ndcY * w, fragCoord.z * w, w);
}

// Порт get_shadow (WebGL2 + sampler2DShadow): сравнение с билинейной фильтрацией
fn shadowTap(uv: vec2f, depthRef: f32) -> f32 {
    return textureSampleCompareLevel(shadowTex, shadowSampler, uv, depthRef);
}

// Порт sample_shadow_texture: 17 выборок по кресту/квадрату радиуса radius
fn sampleShadowTexture(uv: vec2f, depthRef: f32) -> f32 {
    let texelSize = vec2f(1.0) / shadow.mapParams.xy;
    let radius = shadow.mapParams.z;
    let dx0 = -texelSize.x * radius;
    let dy0 = -texelSize.y * radius;
    let dx1 = texelSize.x * radius;
    let dy1 = texelSize.y * radius;
    let dx2 = dx0 / 2.0;
    let dy2 = dy0 / 2.0;
    let dx3 = dx1 / 2.0;
    let dy3 = dy1 / 2.0;

    return (
        shadowTap(uv + vec2f(dx0, dy0), depthRef) +
        shadowTap(uv + vec2f(0.0, dy0), depthRef) +
        shadowTap(uv + vec2f(dx1, dy0), depthRef) +
        shadowTap(uv + vec2f(dx2, dy2), depthRef) +
        shadowTap(uv + vec2f(0.0, dy2), depthRef) +
        shadowTap(uv + vec2f(dx3, dy2), depthRef) +
        shadowTap(uv + vec2f(dx0, 0.0), depthRef) +
        shadowTap(uv + vec2f(dx2, 0.0), depthRef) +
        shadowTap(uv, depthRef) +
        shadowTap(uv + vec2f(dx3, 0.0), depthRef) +
        shadowTap(uv + vec2f(dx1, 0.0), depthRef) +
        shadowTap(uv + vec2f(dx2, dy3), depthRef) +
        shadowTap(uv + vec2f(0.0, dy3), depthRef) +
        shadowTap(uv + vec2f(dx3, dy3), depthRef) +
        shadowTap(uv + vec2f(dx0, dy1), depthRef) +
        shadowTap(uv + vec2f(0.0, dy1), depthRef) +
        shadowTap(uv + vec2f(dx1, dy1), depthRef)
    ) * (1.0 / 17.0);
}

// Порт compute_shadow_factor: 1 — фрагмент освещён, 0 — полностью в тени.
// derivative_uniformity: у mapMesh перед вызовом стоит неравномерный return (фрагмент
// вне текстуры ярусов) — анализ uniformity WGSL производные после него не пропускает
@diagnostic(off, derivative_uniformity)
fn shadowFactor(fragCoord: vec4f) -> f32 {
    if (!receiveShadows || shadow.params.y < 0.5) {
        return 1.0;
    }

    var lightPos = shadowClipPos(fragCoord);
    // Normal bias по производным позиции в пространстве источника (порт FRAGMENT_NORMAL:
    // cross(dpdy, dpdx) в WGSL == cross(dFdx, dFdy) в GLSL — ось Y фреймбуфера перевёрнута).
    // cross производных — ковектор (L⁻ᵀ·n): в анизотропном орто-clip источника (z в 3–6 раз
    // шире xy) он почти целиком ложится в глубину, и bias отрывает тень от основания тонких
    // кастеров (заборы). Домножаем на S² = (1, 1/yF², 1/zM²) — получаем направление
    // вершинной нормали WebGL (L·n = S²·L⁻ᵀ·n), как у заливок color.vsh
    let aniso = shadow.params.zw;
    let cof = cross(dpdy(lightPos.xyz), dpdx(lightPos.xyz));
    let normalFromLight = normalize(
        cof * vec3f(1.0, 1.0 / (aniso.x * aniso.x), 1.0 / (aniso.y * aniso.y)),
    );
    lightPos = vec4f(lightPos.xyz - shadow.mapParams.w * normalFromLight, lightPos.w);
    lightPos.z -= shadow.params.x;

    let clip = lightPos.xyz / lightPos.w;
    // Гасим тени у краёв карты теней, чтобы они не появлялись резко
    let clipFactor = smoothstep(0.5, 1.0, length(clip));
    if (clipFactor >= 1.0) {
        return 1.0;
    }

    // Карта теней рисуется WebGPU: строка 0 — верх (NDC y = +1), z уже в [0,1]
    let uv = vec2f(0.5 * clip.x + 0.5, 0.5 - 0.5 * clip.y);
    let depthRef = 0.5 * clip.z + 0.5;
    let factor = sampleShadowTexture(uv, depthRef);
    return mix(factor, 1.0, clipFactor);
}
`,QB=`// Свет стиля (порт include/light.fsh) — общий chunk освещаемых фрагментников.
// ССЫЛАЕТСЯ на module-scope биндинг \`light: LightBlock\` (объявляет основной файл,
// @group(0) @binding(1) у всех пассов) и на chunk shadow.wgsl (shadowFactor + \`shadow\`).
// Тень накладывается на направленный свет с индексом shadowLight − 1 (порт флагов
// SHADOW_FOR_FIRST/SECOND_LIGHT; per-layer receiveShadows — override receiveShadows).
// Контент передаёт кадровый shadow.params.y; рельеф (demTerrain.frag) — всегда первый свет,
// как хардкод WebGL для слоя dem: у служебного режима DEM_LIGHTING_MODE второго света нет
// (dir2Intensity = 0), и тень на нём умножалась бы на нулевой вклад.

// Разрешённый свет стиля (LightBlock env-записи EnvLight / EnvDemLight)
struct LightBlock {
    // xyz — направление, w — свет включён (0/1)
    dir1Direction: vec4f,
    // rgb + интенсивность (.a)
    dir1Color: vec4f,
    dir2Direction: vec4f,
    dir2Color: vec4f,
    ambientColor: vec4f,
};

// Порт light_factor_dem2: ambient + два Lambert'а с тенью, без проверки use_light.
// shadowLight — индекс затеняемого света + 1 (0 = без тени)
fn lightFactorShadowed(normal: vec3f, fragCoord: vec4f, shadowLight: f32) -> vec3f {
    var f1 = max(dot(normal, -light.dir1Direction.xyz), 0.0);
    var f2 = max(dot(normal, -light.dir2Direction.xyz), 0.0);

    if (shadowLight > 0.5 && shadowLight < 1.5) {
        f1 *= shadowFactor(fragCoord);
    } else if (shadowLight > 1.5) {
        f2 *= shadowFactor(fragCoord);
    }

    return light.ambientColor.rgb * light.ambientColor.a +
        light.dir1Color.rgb * light.dir1Color.a * f1 +
        light.dir2Color.rgb * light.dir2Color.a * f2;
}

// Слой без освещения (режим none, порт USE_LIGHT_FLAG; ShadowMode 'unlit') — плоский цвет
override useLight: bool = true;

// Порт light_factor: слой без освещения (use_light = 0) — плоский цвет и без теней
fn lightFactor(normal: vec3f, fragCoord: vec4f) -> vec3f {
    if (!useLight || light.dir1Direction.w < 0.5) {
        return vec3f(1.0);
    }
    return lightFactorShadowed(normal, fragCoord, shadow.params.y);
}

// Порт light_factor_surface: плоская поверхность (нормаль вверх) — заливки/дороги
fn surfaceLight(fragCoord: vec4f) -> vec3f {
    return lightFactor(vec3f(0.0, 0.0, 1.0), fragCoord);
}
`,Mc=`// Высоты DEM/поверхности (порт include/dem.vsh + resolved_surface_height) — общий
// chunk labeling-шейдеров. ССЫЛАЕТСЯ на module-scope биндинги demTex/demSampler —
// их объявляет основной файл (@group/@binding свои у каждого пасса).
// demParams: x — demScale (0 — рельеф выключен), y — centerElevation (м).

// Маппоинтов в одном метре веб-меркатора (include/dem.vsh)
const MAP_POINTS_IN_METER: f32 = 107.17318796639701;
// Маппоинты → нормализованный tile-z (см. lineTopStroke.vert.wgsl)
const VERTICAL_SCALE: f32 = (32768.0 / 65535.0) / 1048576.0;

// Высота рельефа в нормализованном tile-z (порт dem_height)
fn demHeight(demTexMvp: mat4x4f, demParams: vec4f, coords: vec2f) -> f32 {
    let demScale = demParams.x;
    if (demScale == 0.0) {
        return 0.0;
    }
    let texPos = (demTexMvp * vec4f(coords, 0.0, 1.0)).xy;
    let elevation = textureSampleLevel(demTex, demSampler, vec2f(texPos.x, 1.0 - texPos.y), 0.0);
    if (elevation.a < 1.0) {
        return 0.0;
    }
    return (elevation.r - demParams.y) * MAP_POINTS_IN_METER * VERTICAL_SCALE * demScale;
}

// Абсолютная высота (маппоинты) → нормализованный tile-z (порт abs_height)
fn absHeight(demParams: vec4f, height: f32) -> f32 {
    return (height - demParams.y * MAP_POINTS_IN_METER) * demParams.x * VERTICAL_SCALE;
}

// Высота поверхности под якорем (порт resolved_surface_height): абсолютная база
// или DEM + relativeZ. surfaceParams: x — useAbsZ (0/1), y — relativeZ (норм.
// tile-z), z — absZ (маппоинты)
fn surfaceHeight(demTexMvp: mat4x4f, demParams: vec4f, surfaceParams: vec4f, coords: vec2f) -> f32 {
    var height: f32;
    if (surfaceParams.x != 0.0) {
        height = absHeight(demParams, surfaceParams.z);
    } else {
        height = demHeight(demTexMvp, demParams, coords);
    }
    return height + surfaceParams.y;
}
`,ax=`// Occlusion-тест лейблов за геометрией (порт include/depth_test.vsh) — общий chunk
// labeling-шейдеров. ССЫЛАЕТСЯ на module-scope биндинги labelingSampler/
// labelingColorTex/labelingDepthTex occlusion-таргета — их объявляет основной файл.

// NDC → uv occlusion-таргета (таргет рисуется WebGPU: строка 0 — верх)
fn labelingUv(ndc: vec2f) -> vec2f {
    return vec2f(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5);
}

// Порт color_test (depth_test.vsh): id-цвет якоря в 4 угловых точках; свой объект
// (например, здание лейбла) не должен скрывать лейбл. Совпадение ≥ 3 точек.
// halfPointSize — cb.labelingTextureDepthTestHalfPointSize (нормирован на вьюпорт).
fn colorTest(halfPointSize: vec2f, ndc: vec2f, color: vec4f) -> f32 {
    let hps = halfPointSize;
    var result = 0.0;
    for (var corner = 0u; corner < 4u; corner++) {
        var delta = hps;
        if (corner == 0u) { delta = vec2f(-hps.x, hps.y); }
        if (corner == 2u) { delta = -hps; }
        if (corner == 3u) { delta = vec2f(hps.x, -hps.y); }
        let sample = textureSampleLevel(labelingColorTex, labelingSampler, labelingUv(ndc + delta), 0.0);
        // Сравнение rgba8-текстуры с unorm8-атрибутом: точность 1/255, порог — полшага
        if (all(abs(sample - color) < vec4f(1.0 / 510.0))) {
            result += 1.0;
        }
    }
    return step(3.0, result);
}

// Порт depth_test (depth_test.vsh): фактор «лейбл перед геометрией» [0..1];
// disabled != 0 — depth-тест лейблов выключен (behind = 1)
fn depthTest(halfPointSize: vec2f, disabled: f32, ndc: vec2f, depth01: f32, color: vec4f) -> f32 {
    if (disabled != 0.0) {
        return 1.0;
    }
    if (colorTest(halfPointSize, ndc, color) == 1.0) {
        return 1.0;
    }
    let texDepth = textureSampleLevel(labelingDepthTex, labelingSampler, labelingUv(ndc), 0u);
    // Ширина переходной зоны behind-фактора — та же, что в WebGL (depth_test.vsh)
    let delta = 0.0001;
    if (depth01 <= texDepth) {
        return 1.0;
    }
    if (depth01 - texDepth > delta) {
        return 0.0;
    }
    return 1.0 - (depth01 - texDepth) / delta;
}
`,lx=`// Функции спрайт-квадов (порт include/raster_functions.vsh) — общий chunk
// иконок POI (pointSprite/pointSpriteLabeling). Чистые функции без биндингов.

// Распаковка масштаба из s16 (порт unpack_scale)
fn unpackScale(value: f32) -> f32 {
    return exp(abs(value) / 256.0) * sign(value);
}

// Распаковка положительного числа из s16 (порт unpack_positive_value)
fn unpackPositiveValue(value: f32) -> f32 {
    return exp(value / 256.0);
}

// Клиппинг w-координаты по границам масштаба (порт clipw)
fn clipw(w: f32, range: vec2f, scale: f32) -> f32 {
    return w * (step(unpackScale(range.x), scale) - step(unpackPositiveValue(range.y), scale));
}

// Авто-перемасштабирование растра (порт rescale). Атрибут a_vec2_rescale в WebGL
// не привязан к VAO (константа 0) → оба unpack дают 1.
fn rescaleCorner(corner: vec2f, scaleRange: vec2f, styleScale: f32) -> vec2f {
    if (scaleRange.x < 0.0) {
        let minScale = unpackPositiveValue(-scaleRange.x);
        let stretchExponent = floor(0.5 + log2(
            max(1.0, 1.0 + (1.0 / max(minScale, styleScale) - 1.0))));
        return corner * exp2(stretchExponent);
    }
    return corner;
}

// Вычисление позиции для точного попадания в пиксель (порт make_position)
fn makePosition(position: vec2f, w: f32, invHalfSize: vec2f, roundingFactor: f32) -> vec2f {
    let nonRounded = (position + w) / (w * invHalfSize);
    let rounded = floor(nonRounded + 0.5);
    let roundingDelta = rounded - nonRounded;
    let pixelCoord = nonRounded + roundingFactor * roundingDelta - 0.5;
    return (pixelCoord * invHalfSize) * w - w;
}
`,qB=`// Порт pointsprite.vsh (point.raster: иконки POI из лейблинга и динамические маркеры).\r
// Экранный квад по якорю: якорь проецируется MVP, угловое смещение — в физических px\r
// с авто-перемасштабированием растра (rescale) и пиксельным округлением (make_position).\r
// Общие функции — chunks ecef/dem/labelingOcclusion/rasterFunctions (склейка в\r
// shaderFactory/webgpu.ts через withChunks). Не портировано (паритет с остальными\r
// Sunda-пассами): fog.\r
\r
struct Uniforms {\r
    mvpMatrix: mat4x4f,\r
    // x: opacity видимой иконки, y: opacity скрытой (за зданием), z: cos угла, w: sin угла\r
    opacityRotation: vec4f,\r
    // x: height factor (рост зданий), y: skip height factor (0/1),\r
    // z: floor elevation (tile-z), w: styleScale (zoomToScale(styleZoom))\r
    heightParams: vec4f,\r
    // x: dpi (zptPerInch × devicePixelRatio), y: rounding factor (stillness),\r
    // z, w: разрешение таргета в px\r
    screenParams: vec4f,\r
    // x: база — абсолютная высота (0/1), y: relativeZ (норм. tile-z), z: absZ (маппоинты)\r
    surfaceParams: vec4f,\r
    // x, y: halfPointSize / размер вьюпорта (порт cb.labelingTextureDepthTestHalfPointSize),\r
    // z: depth-test отключён (0/1), w: identifyOpacity (только sprite-labeling проход)\r
    occlusionParams: vec4f,\r
    demTexMvp: mat4x4f,\r
    // x: demScale (0 — рельеф выключен), y: centerElevation (м),\r
    // z: эффективный crossfade глобуса (0 = flat-путь)\r
    demParams: vec4f,\r
    // xyz = (тайл − камера)/fogDistance, w = масштаб тайла/fogDistance; нули = туман выключен\r
    fogOrigin: vec4f,\r
};\r
\r
struct VertexOutput {\r
    @builtin(position) position: vec4f,\r
    @location(0) texcoord: vec2f,\r
    @location(1) behindFactor: f32,\r
    // Порт v_fog_pos: (world_pos − cam_pos)/fog_distance\r
    @location(2) fogPos: vec3f,\r
};\r
\r
@group(0) @binding(0) var<uniform> uniforms: Uniforms;\r
@group(0) @binding(1) var<uniform> globe: GlobeUniforms;\r
@group(2) @binding(0) var demTex: texture_2d<f32>;\r
@group(2) @binding(1) var demSampler: sampler;\r
// Occlusion-таргет лейблов: id-цвета + depth (порт u_color_tex_labeling / u_depth_tex_labeling)\r
@group(3) @binding(0) var labelingSampler: sampler;\r
@group(3) @binding(1) var labelingColorTex: texture_2d<f32>;\r
@group(3) @binding(2) var labelingDepthTex: texture_depth_2d;\r
\r
@vertex\r
fn main(\r
    @location(0) pos: vec4f,\r
    @location(1) cornerOffset: vec2i,\r
    @location(2) texcoordPacked: vec2u,\r
    @location(3) scaleRange: vec2i,\r
    @location(4) checkOffset: vec2i,\r
    @location(5) texIdentifier: vec4f,\r
) -> VertexOutput {\r
    // resolved_surface_height: база (DEM или абсолютная) + relativeZ + этаж\r
    let height = surfaceHeight(uniforms.demTexMvp, uniforms.demParams, uniforms.surfaceParams, pos.xy) +\r
        uniforms.heightParams.z;\r
\r
    // Высота якоря: рост зданиями, если её не задали стиль/surface-height\r
    var anchorZ = pos.z;\r
    if (uniforms.heightParams.y == 0.0) {\r
        anchorZ = pos.z * uniforms.heightParams.x;\r
    }\r
    anchorZ += height;\r
\r
    // MVP c разнормировкой z / ECEF-ветка глобуса (порт get_clipspace)\r
    let anchor = anchorClip(uniforms.mvpMatrix, uniforms.demParams.z, pos, anchorZ);\r
\r
    let styleScale = uniforms.heightParams.w;\r
    let range = vec2f(scaleRange);\r
    let invHalfSize = 2.0 / uniforms.screenParams.zw;\r
\r
    // Поворот иконки + авто-перемасштабирование углового смещения (в физических px)\r
    let c = uniforms.opacityRotation.z;\r
    let s = uniforms.opacityRotation.w;\r
    let rotation = mat2x2f(vec2f(c, -s), vec2f(s, c));\r
    let offset = rescaleCorner(rotation * vec2f(cornerOffset), range, styleScale);\r
\r
    let pos2d = anchor.xy + offset * invHalfSize * anchor.w;\r
    let corner = makePosition(pos2d, anchor.w, invHalfSize, uniforms.screenParams.y);\r
\r
    var output: VertexOutput;\r
    output.position = vec4f(corner, anchor.z, clipw(anchor.w, range, styleScale));\r
    output.texcoord = vec2f(texcoordPacked) * (1.0 / 32768.0);\r
    // Порт depth_test(anchor.xy/w + check_offset/vpt_size, anchor.z/w, tex_identifier)\r
    output.behindFactor = depthTest(\r
        uniforms.occlusionParams.xy,\r
        uniforms.occlusionParams.z,\r
        anchor.xy / anchor.w + vec2f(checkOffset) / uniforms.screenParams.zw,\r
        anchor.z / anchor.w,\r
        texIdentifier,\r
    );\r
    // Порт calc_fog_pos — по якорю (на глобусе fogOrigin нулевой)\r
    output.fogPos = uniforms.fogOrigin.xyz + vec3f(pos.xy, 0.0) * uniforms.fogOrigin.w;\r
    return output;\r
}\r
`,KB=`// Порт pointsprite.fsh (point.raster: иконки POI). Атлас заливается из canvas-зеркала\r
// со straight-альфой — премультипликация здесь (WebGL заливает премультиплицированную\r
// текстуру). Иконка за зданием тускнеет до opacityHidden (v_float_behind_factor из\r
// depth_test в вершиннике). Fog исходника не портирован.\r
struct Uniforms {\r
    mvpMatrix: mat4x4f,\r
    // x: opacity видимой иконки, y: opacity скрытой (за зданием), z/w: cos/sin поворота\r
    opacityRotation: vec4f,\r
    heightParams: vec4f,\r
    screenParams: vec4f,\r
    surfaceParams: vec4f,\r
    occlusionParams: vec4f,\r
    demTexMvp: mat4x4f,\r
    demParams: vec4f,\r
};\r
\r
@group(0) @binding(0) var<uniform> uniforms: Uniforms;\r
// FogBlock — chunk fog.wgsl\r
@group(0) @binding(2) var<uniform> fog: FogBlock;\r
@group(1) @binding(0) var atlasSampler: sampler;\r
@group(1) @binding(1) var atlasTex: texture_2d<f32>;\r
\r
@fragment\r
fn main(\r
    @location(0) texcoord: vec2f,\r
    @location(1) behindFactor: f32,\r
    @location(2) fogPos: vec3f,\r
) -> @location(0) vec4f {\r
    let raw = textureSample(atlasTex, atlasSampler, texcoord);\r
    // straight → premultiplied (blend ONE / ONE_MINUS_SRC_ALPHA)\r
    let color = vec4f(raw.rgb * raw.a, raw.a);\r
    let opacity = mix(uniforms.opacityRotation.y, uniforms.opacityRotation.x, behindFactor);\r
    // Порт apply_fog_alpha из pointsprite.fsh\r
    return applyFogAlpha(fog, color * opacity, fogPos);\r
}\r
`,JB=`// Порт label_fixed_anchor.vsh (point.text: SDF-текст точечной подписи). Якорь\r
// проецируется MVP и нормализуется в NDC (w = 1), угловое смещение глифа — в px.\r
// Occlusion: behind-фактор (depth_test) + labeling-texcoord и sprite-идентификатор\r
// для дискарда текста поверх чужих иконок (label.fsh). Общие функции — chunks\r
// ecef/dem/labelingOcclusion. Не портировано: fog.\r
\r
struct Uniforms {\r
    mvpMatrix: mat4x4f,\r
    // x: labeling-opacity, y: масштаб глифов, z/w: смещение подписи в физ. px\r
    textParams: vec4f,\r
    // x: gamma (ширина SDF-перехода), y: SDF-граница halo, z: SDF-граница fill\r
    sdfParams: vec4f,\r
    // x: height factor, y: skip height factor (0/1), z: floor elevation (tile-z)\r
    heightParams: vec4f,\r
    // x, y: разрешение таргета в px\r
    screenParams: vec4f,\r
    // x: база — абсолютная высота (0/1), y: relativeZ (норм. tile-z), z: absZ (маппоинты)\r
    surfaceParams: vec4f,\r
    haloColor: vec4f,\r
    fillColor: vec4f,\r
    // Цвета «за зданием» (ctx.isBehind, порт u_vec4_hidden_color)\r
    haloHiddenColor: vec4f,\r
    fillHiddenColor: vec4f,\r
    // x, y: halfPointSize / размер вьюпорта, z: depth-test отключён (0/1),\r
    // w: подпись на иконке (labelIndex == Icon → sprite-дискард активен)\r
    occlusionParams: vec4f,\r
    demTexMvp: mat4x4f,\r
    // x: demScale (0 — рельеф выключен), y: centerElevation (м),\r
    // z: эффективный crossfade глобуса (0 = flat-путь)\r
    demParams: vec4f,\r
    // xyz = (тайл − камера)/fogDistance, w = масштаб тайла/fogDistance; нули = туман выключен\r
    fogOrigin: vec4f,\r
};\r
\r
struct VertexOutput {\r
    @builtin(position) position: vec4f,\r
    @location(0) texcoord: vec2f,\r
    @location(1) behindFactor: f32,\r
    // uv sprite-occlusion-таргета (порт v_vec2_labeling_texcoord)\r
    @location(2) labelingTexcoord: vec2f,\r
    // sprite-идентификатор подписи (порт v_vec4_text_identifier)\r
    @location(3) spriteIdentifier: vec4f,\r
    // Порт v_fog_pos: (world_pos − cam_pos)/fog_distance\r
    @location(4) fogPos: vec3f,\r
    // id объекта — читает только identify.frag (порт labelPointIdentify)\r
    @location(15) @interpolate(flat) identifier: vec4f,\r
};\r
\r
@group(0) @binding(0) var<uniform> uniforms: Uniforms;\r
@group(0) @binding(1) var<uniform> globe: GlobeUniforms;\r
@group(2) @binding(0) var demTex: texture_2d<f32>;\r
@group(2) @binding(1) var demSampler: sampler;\r
@group(3) @binding(0) var labelingSampler: sampler;\r
@group(3) @binding(1) var labelingColorTex: texture_2d<f32>;\r
@group(3) @binding(2) var labelingDepthTex: texture_depth_2d;\r
\r
@vertex\r
fn main(\r
    @location(0) pos: vec4f,\r
    @location(1) glyphOffset: vec2i,\r
    @location(2) texcoordPacked: vec2u,\r
    @location(3) checkOffset: vec2i,\r
    @location(4) texIdentifier: vec4f,\r
    @location(5) spriteIdentifier: vec4f,\r
    @location(6) identifier: vec4f,\r
) -> VertexOutput {\r
    let height = surfaceHeight(uniforms.demTexMvp, uniforms.demParams, uniforms.surfaceParams, pos.xy) +\r
        uniforms.heightParams.z;\r
\r
    var anchorZ = pos.z;\r
    if (uniforms.heightParams.y == 0.0) {\r
        anchorZ = pos.z * uniforms.heightParams.x;\r
    }\r
    anchorZ += height;\r
\r
    var clip = anchorClip(uniforms.mvpMatrix, uniforms.demParams.z, pos, anchorZ);\r
\r
    // Нормализация в NDC (w = 1) — как label_fixed_anchor.vsh: экранные смещения\r
    // глифов добавляются уже после деления\r
    clip = vec4f(clip.xyz / clip.w, 1.0);\r
\r
    var output: VertexOutput;\r
    output.behindFactor = depthTest(\r
        uniforms.occlusionParams.xy,\r
        uniforms.occlusionParams.z,\r
        clip.xy + vec2f(checkOffset) / uniforms.screenParams.xy,\r
        clip.z,\r
        texIdentifier,\r
    );\r
\r
    let screenOffset =\r
        (vec2f(glyphOffset) * uniforms.textParams.y + uniforms.textParams.zw) /\r
        uniforms.screenParams.xy * 2.0;\r
\r
    let finalXy = clip.xy + screenOffset;\r
    output.position = vec4f(finalXy, clip.z, 1.0);\r
    output.texcoord = vec2f(texcoordPacked) * (1.0 / 32768.0);\r
    // Порт v_vec2_labeling_texcoord = (pos.xy + 1) / 2 — в WebGPU uv с v-флипом\r
    output.labelingTexcoord = labelingUv(finalXy);\r
    output.spriteIdentifier = spriteIdentifier;\r
    output.identifier = identifier;\r
    // Порт calc_fog_pos — по якорю (на глобусе fogOrigin нулевой)\r
    output.fogPos = uniforms.fogOrigin.xyz + vec3f(pos.xy, 0.0) * uniforms.fogOrigin.w;\r
    return output;\r
}\r
`,$B=`// Порт label.fsh (point.text): SDF-текст. Один шейдер на оба прохода — halo/fill\r
// выбираются pipeline-константой isHalo (в WebGL это два uniform-набора fontHalo/fontFill).\r
// Occlusion: цвет «за зданием» (hidden) миксуется по behind-фактору; подпись на иконке\r
// (labelIndex == Icon) дискардится поверх ЧУЖИХ иконок по sprite-occlusion-таргету.\r
// Fog исходника не портирован.\r
struct Uniforms {\r
    mvpMatrix: mat4x4f,\r
    // x: labeling-opacity\r
    textParams: vec4f,\r
    // x: gamma, y: SDF-граница halo, z: SDF-граница fill\r
    sdfParams: vec4f,\r
    heightParams: vec4f,\r
    screenParams: vec4f,\r
    surfaceParams: vec4f,\r
    // premultiplied RGBA\r
    haloColor: vec4f,\r
    fillColor: vec4f,\r
    haloHiddenColor: vec4f,\r
    fillHiddenColor: vec4f,\r
    // w: подпись на иконке (sprite-дискард активен)\r
    occlusionParams: vec4f,\r
    demTexMvp: mat4x4f,\r
    demParams: vec4f,\r
};\r
\r
override isHalo: bool = false;\r
\r
@group(0) @binding(0) var<uniform> uniforms: Uniforms;\r
// FogBlock — chunk fog.wgsl\r
@group(0) @binding(2) var<uniform> fog: FogBlock;\r
@group(1) @binding(0) var fontSampler: sampler;\r
@group(1) @binding(1) var fontTex: texture_2d<f32>;\r
@group(3) @binding(0) var labelingSampler: sampler;\r
// Sprite-occlusion-таргет (порт u_color_text_sprite_labeling)\r
@group(3) @binding(3) var spriteColorTex: texture_2d<f32>;\r
\r
// Порог сравнения id-цветов (порт F16_EPSILON label.fsh)\r
const F16_EPSILON: f32 = 0.0009765625;\r
\r
@fragment\r
fn main(\r
    @location(0) texcoord: vec2f,\r
    @location(1) behindFactor: f32,\r
    @location(2) labelingTexcoord: vec2f,\r
    @location(3) spriteIdentifier: vec4f,\r
    @location(4) fogPos: vec3f,\r
) -> @location(0) vec4f {\r
    let dist = textureSample(fontTex, fontSampler, texcoord).a;\r
    let gamma = uniforms.sdfParams.x;\r
    var buffer: f32;\r
    var color: vec4f;\r
    var hiddenColor: vec4f;\r
    if (isHalo) {\r
        buffer = uniforms.sdfParams.y;\r
        color = uniforms.haloColor;\r
        hiddenColor = uniforms.haloHiddenColor;\r
    } else {\r
        buffer = uniforms.sdfParams.z;\r
        color = uniforms.fillColor;\r
        hiddenColor = uniforms.fillHiddenColor;\r
    }\r
    let alpha = smoothstep(buffer - gamma, buffer + gamma, dist);\r
    let mixed = mix(hiddenColor, color, behindFactor);\r
\r
    // Порт sprite-дискарда label.fsh: подпись на иконке не рисуется поверх ЧУЖОЙ иконки\r
    // (пиксель не фоновый (1,1,1,1) и не совпадает со своим sprite-идентификатором)\r
    if (uniforms.occlusionParams.w != 0.0) {\r
        let spriteColor = textureSampleLevel(spriteColorTex, labelingSampler, labelingTexcoord, 0.0);\r
        let clearDiff = any(abs(spriteColor - vec4f(1.0)) > vec4f(F16_EPSILON));\r
        let idDiff = any(abs(spriteColor - spriteIdentifier) > vec4f(F16_EPSILON));\r
        if (clearDiff && idDiff) {\r
            discard;\r
        }\r
    }\r
\r
    // Порт apply_fog_alpha из label.fsh\r
    return applyFogAlpha(fog, mixed * alpha * uniforms.textParams.x, fogPos);\r
}\r
`,eD=`// Порт label_directional.vsh (labelLine.raster: текст вдоль дорог). Глиф экструдируется\r
// в tile-space по per-vertex offset (уже повёрнут вдоль линии генератором); клип по\r
// per-vertex диапазону styleZoom. Fog исходника не портирован (паритет с остальными\r
// Sunda-пассами), ECEF-ветки у labelLine нет и в WebGL.\r
\r
// Нормализованный tile-z → z-масштаб модели WebGL (m[10]); модель Sunda имеет m[10] = 1\r
const Z_SCALE: f32 = 1048576.0 / (32768.0 / 65535.0);\r
\r
struct Uniforms {\r
    mvpMatrix: mat4x4f,\r
    // x: labeling-opacity, y: масштаб глифов, z: tile-units на физ. px, w: styleZoom\r
    params: vec4f,\r
    // x: gamma, y: SDF-граница halo, z: SDF-граница fill\r
    sdfParams: vec4f,\r
    haloColor: vec4f,\r
    fillColor: vec4f,\r
    // xyz = (тайл − камера)/fogDistance, w = масштаб тайла/fogDistance; нули = туман выключен\r
    fogOrigin: vec4f,\r
};\r
\r
struct VertexOutput {\r
    @builtin(position) position: vec4f,\r
    @location(0) texcoord: vec2f,\r
    // Порт v_fog_pos: (world_pos − cam_pos)/fog_distance\r
    @location(1) fogPos: vec3f,\r
};\r
\r
@group(0) @binding(0) var<uniform> uniforms: Uniforms;\r
\r
// Клиппинг w-координаты по границам зума (порт clipw label_directional.vsh)\r
fn clipw(w: f32, range: vec2f, zoom: f32) -> f32 {\r
    return w * (step(range.x, zoom) - step(range.y, zoom));\r
}\r
\r
@vertex\r
fn main(\r
    @location(0) pos: vec4f,\r
    @location(1) glyphOffset: vec2f,\r
    @location(2) texcoordPacked: vec2u,\r
    @location(3) styleZoomLimits: vec2f,\r
) -> VertexOutput {\r
    let xy = pos.xy + glyphOffset * uniforms.params.y * uniforms.params.z;\r
\r
    let m = uniforms.mvpMatrix;\r
    let zMvp = mat4x4f(m[0], m[1], m[2] * Z_SCALE, m[3]);\r
    let clip = zMvp * vec4f(xy, pos.z, 1.0);\r
\r
    var output: VertexOutput;\r
    output.position = vec4f(\r
        clip.xyz,\r
        clipw(clip.w, styleZoomLimits, uniforms.params.w),\r
    );\r
    output.texcoord = vec2f(texcoordPacked) * (1.0 / 32768.0);\r
    // Порт calc_fog_pos — по якорю глифа\r
    output.fogPos = uniforms.fogOrigin.xyz + vec3f(pos.xy, 0.0) * uniforms.fogOrigin.w;\r
    return output;\r
}\r
`,tD=`// Порт label_directional.fsh (labelLine.raster): SDF-текст вдоль дорог. Halo/fill —\r
// pipeline-константа isHalo (в WebGL — uniform-наборы fontHalo/fontFill). Fog не портирован.\r
struct Uniforms {\r
    mvpMatrix: mat4x4f,\r
    // x: labeling-opacity\r
    params: vec4f,\r
    // x: gamma, y: SDF-граница halo, z: SDF-граница fill\r
    sdfParams: vec4f,\r
    // premultiplied RGBA\r
    haloColor: vec4f,\r
    fillColor: vec4f,\r
};\r
\r
override isHalo: bool = false;\r
\r
@group(0) @binding(0) var<uniform> uniforms: Uniforms;\r
// FogBlock — chunk fog.wgsl\r
@group(0) @binding(1) var<uniform> fog: FogBlock;\r
@group(1) @binding(0) var fontSampler: sampler;\r
@group(1) @binding(1) var fontTex: texture_2d<f32>;\r
\r
@fragment\r
fn main(@location(0) texcoord: vec2f, @location(1) fogPos: vec3f) -> @location(0) vec4f {\r
    let dist = textureSample(fontTex, fontSampler, texcoord).a;\r
    let gamma = uniforms.sdfParams.x;\r
    var buffer: f32;\r
    var color: vec4f;\r
    if (isHalo) {\r
        buffer = uniforms.sdfParams.y;\r
        color = uniforms.haloColor;\r
    } else {\r
        buffer = uniforms.sdfParams.z;\r
        color = uniforms.fillColor;\r
    }\r
    let alpha = smoothstep(buffer - gamma, buffer + gamma, dist);\r
    // Порт apply_fog_alpha из label.fsh\r
    return applyFogAlpha(fog, color * alpha * uniforms.params.x, fogPos);\r
}\r
`,nD=`// Labeling-проход 3D-здания (порт diffuse-пути buildingIdentify + color_identify.fsh):
// пишет id-цвет здания и depth в occlusion-таргет лейблов. Позиционная математика —
// копия polygonExtrusionDepth.vert (тот же mvp + DEM-lift). Screendoor не портирован —
// у WebGL labeling-прохода его нет.

const MAP_POINTS_IN_METER: f32 = 107.17318796639701;
const UNPACK_CENTROID: f32 = 8.0 / 65535.0;
const VERTICAL_SCALE: f32 = (32768.0 / 65535.0) / 1048576.0;

struct Uniforms {
    mvpMatrix: mat4x4f,
    modelMatrix: mat4x4f,
    color: vec4f,
    _pad0: vec4f,
    _pad1: vec4f,
    demTexMvp: mat4x4f,
    // x = demScale, y = centerElevation (м), z = heightFactor, w = floorElevation
    demParams: vec4f,
    fadeParams: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(1) @binding(0) var demTex: texture_2d<f32>;
@group(1) @binding(1) var demSampler: sampler;

struct VertexOutput {
    @builtin(position) position: vec4f,
    @location(0) identifier: vec4f,
};

fn demHeight(coords: vec2f) -> f32 {
    let demScale = uniforms.demParams.x;
    if (demScale == 0.0) {
        return 0.0;
    }
    let texPos = (uniforms.demTexMvp * vec4f(coords, 0.0, 1.0)).xy;
    let elevation = textureSampleLevel(demTex, demSampler, vec2f(texPos.x, 1.0 - texPos.y), 0.0);
    // Порт dem_height_direct_meters: без данных рельефа — 0 м (уровень моря), как в WebGL
    var meters = elevation.r;
    if (elevation.a < 1.0) {
        meters = 0.0;
    }
    return (meters - uniforms.demParams.y) * MAP_POINTS_IN_METER * VERTICAL_SCALE * demScale;
}

@vertex
fn main(
    @location(0) pos: vec2f,
    @location(1) z: f32,
    @location(3) demPos: vec2i,
    @location(5) identifier: vec4f,
) -> VertexOutput {
    let heightFactor = uniforms.demParams.z;
    let floorElevation = uniforms.demParams.w;
    let isHole = uniforms._pad1.z;

    // isHole-ветки — как в polygonExtrusionDepth.vert: без них z выемок в occlusion-таргете
    // расходился бы с видимой геометрией и лейблы у дыр гасли бы/мигали
    var base = demHeight(vec2f(demPos) * UNPACK_CENTROID);
    if (z == 0.0) {
        let posTerrain = demHeight(pos);
        if (isHole > 0.5 || base > posTerrain) {
            base = posTerrain;
        }
    }
    base = base + floorElevation;

    var finalZ = z * heightFactor + base;
    if (isHole < 0.5) {
        finalZ = max(finalZ, base);
    }

    var out: VertexOutput;
    out.position = uniforms.mvpMatrix * vec4f(pos, finalZ, 1.0);
    out.identifier = identifier;
    return out;
}
`,iD=`// Порт color_identify.fsh: чистый id-цвет объекта в occlusion-таргет лейблов.
@fragment
fn main(@location(0) identifier: vec4f) -> @location(0) vec4f {
    return identifier;
}
`,rD=`// Порт point_anchor.vsh + color_identify.fsh (point.labelingTexture): якорный квад
// POI пишет id-цвет в occlusion-таргет лейблов (depth-тест LESS без записи) — чтобы
// color_test в depth_test позволял лейблу не скрываться за «своим» зданием.
// Общие функции — chunks ecef/dem.

struct Uniforms {
    mvpMatrix: mat4x4f,
    // x, y: смещение подписи в физ. px (порт u_vec2_offset), z, w: разрешение таргета
    params: vec4f,
    // x: база — абсолютная высота (0/1), y: relativeZ (норм. tile-z), z: absZ (маппоинты),
    // w: floor elevation (tile-z)
    surfaceParams: vec4f,
    demTexMvp: mat4x4f,
    // x: demScale, y: centerElevation (м), z: эффективный crossfade глобуса (0 = flat)
    demParams: vec4f,
};

struct VertexOutput {
    @builtin(position) position: vec4f,
    @location(0) identifier: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(0) @binding(1) var<uniform> globe: GlobeUniforms;
@group(1) @binding(0) var demTex: texture_2d<f32>;
@group(1) @binding(1) var demSampler: sampler;

@vertex
fn main(
    @location(0) pos: vec4f,
    @location(1) anchorOffset: vec2i,
    @location(2) identifier: vec4f,
) -> VertexOutput {
    let height = surfaceHeight(uniforms.demTexMvp, uniforms.demParams, uniforms.surfaceParams, pos.xy) +
        uniforms.surfaceParams.w;

    var clip = anchorClip(uniforms.mvpMatrix, uniforms.demParams.z, pos, pos.z + height);
    clip = vec4f(clip.xyz / clip.w, 1.0);

    var out: VertexOutput;
    out.position = vec4f(
        clip.xy + (vec2f(anchorOffset) + uniforms.params.xy) / uniforms.params.zw * 2.0,
        clip.z,
        1.0,
    );
    out.identifier = identifier;
    return out;
}
`,sD=`// Порт color_identify.fsh: id-цвет якоря POI в occlusion-таргет лейблов.
@fragment
fn main(@location(0) identifier: vec4f) -> @location(0) vec4f {
    return identifier;
}
`,oD=`// Порт pointsprite_identify.vsh для labelTest-прохода (point.raster): квад иконки в
// sprite-occlusion-таргет с per-vertex sprite-идентификатором. Геометрия — как у
// pointSprite.vert (без depth_test и с rounding factor = 1, как в WebGL-исходнике).
// Вершины с идентификатором (1,1,1,1) вырождаются (не рисуются). Общие функции —
// chunks ecef/dem/rasterFunctions.

struct Uniforms {
    mvpMatrix: mat4x4f,
    // x: opacity видимой иконки, y: opacity скрытой, z/w: cos/sin поворота
    opacityRotation: vec4f,
    // x: height factor, y: skip height factor, z: floor elevation, w: styleScale
    heightParams: vec4f,
    // x: dpi, y: rounding factor, z, w: разрешение таргета в px
    screenParams: vec4f,
    // x: useAbsZ, y: relativeZ (норм. tile-z), z: absZ (маппоинты)
    surfaceParams: vec4f,
    // x, y: halfPointSize/size, z: depthTestDisable, w: identifyOpacity
    occlusionParams: vec4f,
    demTexMvp: mat4x4f,
    // x: demScale, y: centerElevation, z: эффективный crossfade глобуса (0 = flat)
    demParams: vec4f,
};

struct VertexOutput {
    @builtin(position) position: vec4f,
    @location(0) texcoord: vec2f,
    @location(1) identifier: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(0) @binding(1) var<uniform> globe: GlobeUniforms;
@group(2) @binding(0) var demTex: texture_2d<f32>;
@group(2) @binding(1) var demSampler: sampler;

@vertex
fn main(
    @location(0) pos: vec4f,
    @location(1) cornerOffset: vec2i,
    @location(2) texcoordPacked: vec2u,
    @location(3) scaleRange: vec2i,
    @location(4) identifier: vec4f,
) -> VertexOutput {
    var output: VertexOutput;
    output.texcoord = vec2f(texcoordPacked) * (1.0 / 32768.0);
    output.identifier = identifier;

    // Идентификатор (1,1,1,1) = фон — квад вырождается (порт ветки else исходника)
    if (all(identifier == vec4f(1.0))) {
        output.position = vec4f(1.0, 1.0, 1.0, 1.0);
        return output;
    }

    let height = surfaceHeight(uniforms.demTexMvp, uniforms.demParams, uniforms.surfaceParams, pos.xy) +
        uniforms.heightParams.z;

    var anchorZ = pos.z;
    if (uniforms.heightParams.y == 0.0) {
        anchorZ = pos.z * uniforms.heightParams.x;
    }
    anchorZ += height;

    let anchor = anchorClip(uniforms.mvpMatrix, uniforms.demParams.z, pos, anchorZ);

    let styleScale = uniforms.heightParams.w;
    let range = vec2f(scaleRange);
    let invHalfSize = 2.0 / uniforms.screenParams.zw;

    let c = uniforms.opacityRotation.z;
    let s = uniforms.opacityRotation.w;
    let rotation = mat2x2f(vec2f(c, -s), vec2f(s, c));
    let offset = rescaleCorner(rotation * vec2f(cornerOffset), range, styleScale);

    let pos2d = anchor.xy + offset * invHalfSize * anchor.w;
    // rounding factor = 1 — как в pointsprite_identify.vsh
    let corner = makePosition(pos2d, anchor.w, invHalfSize, 1.0);

    output.position = vec4f(corner, anchor.z, clipw(anchor.w, range, styleScale));
    return output;
}
`,aD=`// Порт pointsprite_identify.fsh: sprite-идентификатор иконки в sprite-occlusion-таргет.
// Пиксели прозрачнее identifyOpacity отбрасываются (круглая иконка → круглая маска).
struct Uniforms {
    mvpMatrix: mat4x4f,
    opacityRotation: vec4f,
    heightParams: vec4f,
    screenParams: vec4f,
    surfaceParams: vec4f,
    // w: identifyOpacity (порог альфы)
    occlusionParams: vec4f,
    demTexMvp: mat4x4f,
    demParams: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(1) @binding(0) var atlasSampler: sampler;
@group(1) @binding(1) var atlasTex: texture_2d<f32>;

@fragment
fn main(
    @location(0) texcoord: vec2f,
    @location(1) identifier: vec4f,
) -> @location(0) vec4f {
    let color = textureSample(atlasTex, atlasSampler, texcoord);
    if (color.a < uniforms.occlusionParams.w) {
        discard;
    }
    return identifier;
}
`,lD=`// Порт metric_point.vsh (metricPoint.fill): текстурированный квад метрического знака.\r
// Геометрия лежит в тайловых координатах (квад построен генератором), высота — только\r
// этажный подъём. Fog/shadow исходника не портированы (паритет с остальными Sunda-пассами).\r
\r
// Нормализованный tile-z → z-масштаб модели WebGL (m[10]); модель Sunda имеет m[10] = 1\r
const Z_SCALE: f32 = 1048576.0 / (32768.0 / 65535.0);\r
\r
struct Uniforms {\r
    mvpMatrix: mat4x4f,\r
    // premultiplied RGBA (порт u_vec4_color)\r
    color: vec4f,\r
    // uv-прямоугольник растра в атласе (порт u_float_sprite_texture_coords)\r
    spriteCoords: vec4f,\r
    // x: floor elevation (tile-z)\r
    params: vec4f,\r
    // xyz = (тайл − камера)/fogDistance, w = масштаб тайла/fogDistance; нули = туман выключен\r
    fogOrigin: vec4f,\r
};\r
\r
struct VertexOutput {\r
    @builtin(position) position: vec4f,\r
    @location(0) texcoord: vec2f,\r
    // Порт v_fog_pos: (world_pos − cam_pos)/fog_distance\r
    @location(1) fogPos: vec3f,\r
};\r
\r
@group(0) @binding(0) var<uniform> uniforms: Uniforms;\r
\r
@vertex\r
fn main(\r
    @location(0) pos: vec2f,\r
    @location(1) texcoordPacked: vec2u,\r
) -> VertexOutput {\r
    let m = uniforms.mvpMatrix;\r
    let zMvp = mat4x4f(m[0], m[1], m[2] * Z_SCALE, m[3]);\r
\r
    var output: VertexOutput;\r
    output.position = zMvp * vec4f(pos, uniforms.params.x, 1.0);\r
    output.texcoord = vec2f(texcoordPacked) * (1.0 / 32768.0);\r
    // Порт calc_fog_pos — по якорю знака\r
    output.fogPos = uniforms.fogOrigin.xyz + vec3f(pos, 0.0) * uniforms.fogOrigin.w;\r
    return output;\r
}\r
`,cD=`// Порт metric_point.fsh: тексель растра знака × цвет слоя × свет плоской поверхности
// (с тенью, chunks light/shadow) + туман. Атлас заливается из canvas-зеркала со
// straight-альфой — премультипликация здесь.
struct Uniforms {
    mvpMatrix: mat4x4f,
    color: vec4f,
    spriteCoords: vec4f,
    params: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(0) @binding(1) var<uniform> light: LightBlock;
// FogBlock — chunk fog.wgsl
@group(0) @binding(2) var<uniform> fog: FogBlock;
// Тени кадра — chunk shadow.wgsl (ShadowBlock + карта теней + comparison-сэмплер)
@group(0) @binding(3) var<uniform> shadow: ShadowBlock;
@group(0) @binding(4) var shadowTex: texture_depth_2d;
@group(0) @binding(5) var shadowSampler: sampler_comparison;
@group(1) @binding(0) var atlasSampler: sampler;
@group(1) @binding(1) var atlasTex: texture_2d<f32>;

@fragment
fn main(
    @builtin(position) fragCoord: vec4f,
    @location(0) texcoord: vec2f,
    @location(1) fogPos: vec3f,
) -> @location(0) vec4f {
    let spriteCoord = mix(uniforms.spriteCoords.xy, uniforms.spriteCoords.zw, texcoord);
    let raw = textureSample(atlasTex, atlasSampler, spriteCoord);
    // straight → premultiplied (blend ONE / ONE_MINUS_SRC_ALPHA)
    let color = vec4f(raw.rgb * raw.a, raw.a) * uniforms.color;
    // Порт color * light_factor_surface() + apply_fog из metric_point.fsh
    return applyFog(fog, vec4f(color.rgb * surfaceLight(fragCoord), color.a), fogPos);
}
`,fD=`// Порт circle_marker.vsh (circle.fill): экранный квад круга по якорю. Экструзия
// на per-vertex widen × диаметр в px в clip с сохранением clip.w (тени читаются во
// фрагменте из fragCoord). DEM-подъём якоря; ECEF-ветка исходника не портирована.

const MAP_POINTS_IN_METER: f32 = 107.17318796639701;
const VERTICAL_SCALE: f32 = (32768.0 / 65535.0) / 1048576.0;
const Z_SCALE: f32 = 1048576.0 / (32768.0 / 65535.0);

struct Uniforms {
    mvpMatrix: mat4x4f,
    // premultiplied RGBA
    color: vec4f,
    // x: диаметр круга в физических px, y, z: разрешение таргета в px
    params: vec4f,
    demTexMvp: mat4x4f,
    // x: demScale (0 — рельеф выключен), y: centerElevation (м)
    demParams: vec4f,
    // xyz = (тайл − камера)/fogDistance, w = масштаб тайла/fogDistance; нули = туман выключен
    fogOrigin: vec4f,
};

struct VertexOutput {
    @builtin(position) position: vec4f,
    @location(0) circle: vec2f,
    // Порт v_fog_pos: (world_pos − cam_pos)/fog_distance
    @location(1) fogPos: vec3f,
    // id объекта — читает только identify.frag (порт circleMarkerIdentify)
    @location(15) @interpolate(flat) identifier: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(1) @binding(0) var demTex: texture_2d<f32>;
@group(1) @binding(1) var demSampler: sampler;

// Высота рельефа в нормализованном tile-z (порт dem_height, копия lineTopStroke.vert.wgsl)
fn demHeight(coords: vec2f) -> f32 {
    let demScale = uniforms.demParams.x;
    if (demScale == 0.0) {
        return 0.0;
    }
    let texPos = (uniforms.demTexMvp * vec4f(coords, 0.0, 1.0)).xy;
    let elevation = textureSampleLevel(demTex, demSampler, vec2f(texPos.x, 1.0 - texPos.y), 0.0);
    // Порт dem_height_direct_meters: без данных рельефа — 0 м (уровень моря), как в WebGL
    var meters = elevation.r;
    if (elevation.a < 1.0) {
        meters = 0.0;
    }
    return (meters - uniforms.demParams.y) * MAP_POINTS_IN_METER * VERTICAL_SCALE * demScale;
}

@vertex
fn main(
    @location(0) pos: vec4f,
    @location(1) widen: vec2i,
    @location(2) identifier: vec4f,
) -> VertexOutput {
    let m = uniforms.mvpMatrix;
    let zMvp = mat4x4f(m[0], m[1], m[2] * Z_SCALE, m[3]);

    let clip = zMvp * vec4f(pos.xy, pos.z + demHeight(pos.xy), 1.0);
    let w = vec2f(widen);
    // Экранное смещение widen задано в NDC — переводим в clip умножением на clip.w, сам
    // clip.w сохраняем (исходник делит на w заранее). Иначе fragCoord.w = 1 и
    // shadowClipPos (chunk shadow.wgsl) восстанавливает clip без камерного w: bias'ы
    // теней масштабируются на w камеры (≥ near ≈ 1000) и гасят тень на маркере целиком
    let clipXY = clip.xy + w * uniforms.params.x / uniforms.params.yz * clip.w;

    var output: VertexOutput;
    output.position = vec4f(clipXY, clip.z, clip.w);
    output.circle = w;
    output.identifier = identifier;
    // Порт calc_fog_pos — по якорю маркера
    output.fogPos = uniforms.fogOrigin.xyz + vec3f(pos.xy, 0.0) * uniforms.fogOrigin.w;
    return output;
}
`,uD=`// Порт circle_marker.fsh: SDF-круг с аффинным AA-краем × свет плоской поверхности
// (с тенью, chunks light/shadow) + туман.
struct Uniforms {
    mvpMatrix: mat4x4f,
    color: vec4f,
    // x: диаметр круга в физических px
    params: vec4f,
    demTexMvp: mat4x4f,
    demParams: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(0) @binding(1) var<uniform> light: LightBlock;
// FogBlock — chunk fog.wgsl
@group(0) @binding(2) var<uniform> fog: FogBlock;
// Тени кадра — chunk shadow.wgsl (ShadowBlock + карта теней + comparison-сэмплер)
@group(0) @binding(3) var<uniform> shadow: ShadowBlock;
@group(0) @binding(4) var shadowTex: texture_depth_2d;
@group(0) @binding(5) var shadowSampler: sampler_comparison;

// Аффинный переход от 0 до 1 (порт affine_step)
fn affineStep(edge0: f32, edge1: f32, x: f32) -> f32 {
    return clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0);
}

@fragment
fn main(
    @builtin(position) fragCoord: vec4f,
    @location(0) circle: vec2f,
    @location(1) fogPos: vec3f,
) -> @location(0) vec4f {
    let centerDistance = dot(circle, circle);
    // Порт color * light_factor_surface() + apply_fog_alpha из circle_marker.fsh
    let color = uniforms.color * affineStep(1.0, 1.0 - 4.0 / uniforms.params.x, centerDistance);
    return applyFogAlpha(fog, vec4f(color.rgb * surfaceLight(fragCoord), color.a), fogPos);
}
`,dD=`// Порт striped_line.vsh (3d-путь, dashedLine.stroke3d): та же экструзия в clip-space
// по widen + параметризация штриховки, что в lineStripe.vert.wgsl, но высота вершины =
// DEM + относительная a_float_height (u_bool_is_3d_line-ветка исходника).
// ECEF/fog/jitter/shadow/floorElevation исходника не портированы (как в 2d-порте).

// Маппоинтов в одном метре веб-меркатора (include/dem.vsh)
const MAP_POINTS_IN_METER: f32 = 107.17318796639701;
// Маппоинты → нормализованный tile-z (= 1/zScale модели WebGL, см. polygonExtrusion.vert.wgsl)
const VERTICAL_SCALE: f32 = (32768.0 / 65535.0) / 1048576.0;
// Нормализованный tile-z → маппоинты: модель тайла Sunda имеет m[10] = 1 (z сразу в маппоинтах)
const Z_SCALE: f32 = 1048576.0 / (32768.0 / 65535.0);

struct Uniforms {
    mvpMatrix: mat4x4f,
    dashColor: vec4f,
    spaceColor: vec4f,
    borderColor: vec4f,
    // x: полуширина (норм. коорд.), y: длина штриха, z: длина пропуска (тайловые единицы),
    // w: circle factor (precision-масштаб кружочков)
    params: vec4f,
    // x, y: разрешение таргета в px; z: gap_turns_only (0/1)
    resolution: vec4f,
    // тайловые координаты → текстура высот рельефа
    demTexMvp: mat4x4f,
    // x = demScale (0 — рельеф выключен), y = centerElevation (м),
    // z = 1/fogDistance (0 = туман выключен), w = XY-масштаб модели тайла
    demParams: vec4f,
    // xyz = (тайл − камера)/fogDistance; w не используется (масштабы в demParams)
    fogOrigin: vec4f,
};

struct VertexOutput {
    @builtin(position) position: vec4f,
    @location(0) circle: vec2f,
    @location(1) width: f32,
    // x: порог смены цвета в долях куска, y: нормированная длина в вершине (в кусках)
    @location(2) lineParams: vec2f,
    // Порт v_fog_pos: (world_pos − cam_pos)/fog_distance
    @location(3) fogPos: vec3f,
    // id объекта — читает только identify.frag (порт stripedLineIdentify)
    @location(15) @interpolate(flat) identifier: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(1) @binding(0) var demTex: texture_2d<f32>;
@group(1) @binding(1) var demSampler: sampler;

// Распаковка widen: normalize_s08 · sqrt(2) (packed_attributes.vsh, unpack_widen)
const WIDEN_UNPACK_MULTIPLIER = 0.011135539861205473;
// Количество пикселей экранного довода (g_shift_pixels)
const SHIFT_PIXELS = 2.0;
// Коэффициент перед w (g_w_factor striped_line.vsh)
const W_FACTOR = 1e-7;
const MIN_DENOMINATOR = 1e-7;
const MAX_FACTOR = 10000.0;

// Высота рельефа в нормализованном tile-z по тайловым координатам (порт dem_height).
// 0 при выключенном рельефе (demScale == 0); без данных рельефа — уровень моря.
fn demHeight(coords: vec2f) -> f32 {
    let demScale = uniforms.demParams.x;
    if (demScale == 0.0) {
        return 0.0;
    }
    let texPos = (uniforms.demTexMvp * vec4f(coords, 0.0, 1.0)).xy;
    // V переворачивается: текстура высот записана в WebGPU матрицами WebGL-конвенции
    let elevation = textureSampleLevel(demTex, demSampler, vec2f(texPos.x, 1.0 - texPos.y), 0.0);
    // Порт dem_height_direct_meters: без данных рельефа — 0 м (уровень моря), как в WebGL
    var meters = elevation.r;
    if (elevation.a < 1.0) {
        meters = 0.0;
    }
    return (meters - uniforms.demParams.y) * MAP_POINTS_IN_METER * VERTICAL_SCALE * demScale;
}

// Порт calculate_multiplication_factor (pixel_offset.vsh): k, на который домножается
// нормаль, чтобы экранное смещение вершины составило shiftPixels пикселей.
fn calcMultiplicationFactor(
    halfViewport: vec2f,
    clipWiden: vec4f,
    clipWidenPerp: vec4f,
    clipVertex: vec4f,
    shiftPixels: f32,
) -> f32 {
    var limitedFactor = 0.0;

    let screenWiden =
        (clipWiden.xy * clipVertex.w - clipVertex.xy * clipWiden.w) * halfViewport;
    let screenWidenPerp =
        (clipWidenPerp.xy * clipVertex.w - clipVertex.xy * clipWidenPerp.w) * halfViewport;
    let perp = vec2f(screenWidenPerp.y, -screenWidenPerp.x);
    let perpLength = length(perp);

    let denominator =
        dot(perp, screenWiden) / shiftPixels - clipWiden.w * clipVertex.w * perpLength;
    if (abs(denominator) > MIN_DENOMINATOR) {
        let factor = clipVertex.w * clipVertex.w * perpLength / denominator;
        // NaN-гард исходника (factor == factor)
        if (factor == factor) {
            limitedFactor = sign(factor) * min(MAX_FACTOR, abs(factor));
        }
    }

    // Фолбэк при потере точности на мелких масштабах (ниже ~6.5 зума)
    if (limitedFactor == 0.0) {
        let screenWidenFallback = clipWiden.xy / clipVertex.w * halfViewport;
        let screenWidenLength = length(screenWidenFallback);
        if (screenWidenLength > 1e-4) {
            limitedFactor = shiftPixels / screenWidenLength;
        }
    }

    return limitedFactor;
}

@vertex
fn main(
    @location(0) pos: vec2f,
    @location(1) textureWidenPacked: vec2i,
    @location(2) widenPacked: vec2i,
    @location(3) vertexDistance: f32,
    @location(4) componentDistance: f32,
    @location(5) objectLength: f32,
    @location(6) height: f32,
    @location(7) identifier: vec4f,
) -> VertexOutput {
    let lineWidth = uniforms.params.x;
    let widen = vec2f(widenPacked) * WIDEN_UNPACK_MULTIPLIER;
    let widenPerp = vec2f(-widen.y, widen.x);

    // Высота вершины: DEM + относительная высота из данных (в маппоинтах, m[10] модели = 1)
    let vertexZ = (demHeight(pos) + height * VERTICAL_SCALE) * Z_SCALE;

    // n и v1 из уравнения pixel_offset.vsh
    let clipWiden = uniforms.mvpMatrix * vec4f(widen, 0.0, 0.0);
    let clipWidenPerp = uniforms.mvpMatrix * vec4f(widenPerp, 0.0, 0.0);
    let clipVertex = uniforms.mvpMatrix * vec4f(pos, vertexZ, 1.0) + clipWiden * lineWidth;

    let halfViewport = 0.5 * uniforms.resolution.xy;
    let limitedFactor =
        calcMultiplicationFactor(halfViewport, clipWiden, clipWidenPerp, clipVertex, SHIFT_PIXELS);

    // Порт calculate_line_params (striped_line_functions.vsh); dash2 == dash
    let requestedPartLength = uniforms.params.y + uniforms.params.z;
    let partCount = max(floor(objectLength / requestedPartLength + 0.5), 1.0);
    let partLength = objectLength / partCount;
    let dashLength = (partLength / requestedPartLength) * uniforms.params.y;
    let threshold = dashLength / partLength;
    // Линия начинается и заканчивается половиной штриха
    let segmentStart = fract((componentDistance + 0.5 * dashLength) / partLength);
    let distanceInParts = segmentStart + vertexDistance / partLength;

    // В texture_widen закодировано направление сдвига вдоль направляющей:
    // при сдвиге к началу вектор перевёрнут на 180°
    let textureWidenWithShiftSign = vec2f(textureWidenPacked) * WIDEN_UNPACK_MULTIPLIER;
    let shiftSign = sign(dot(widen, textureWidenWithShiftSign));
    let textureWiden = shiftSign * textureWidenWithShiftSign;

    let circleFactor = uniforms.params.w;

    var output: VertexOutput;
    output.circle = textureWiden * (lineWidth + limitedFactor) * circleFactor;
    output.width = lineWidth * circleFactor;
    output.lineParams = vec2f(threshold, distanceInParts);
    output.identifier = identifier;
    output.position = (clipVertex + clipWiden * limitedFactor) * W_FACTOR;
    // Порт calc_fog_pos: xy в маппоинтах через масштаб модели (demParams.w), vertexZ уже в маппоинтах
    output.fogPos = uniforms.fogOrigin.xyz +
        vec3f(pos * uniforms.demParams.w, vertexZ) * uniforms.demParams.z;
    return output;
}
`,hD=`// Порт patterned_line.vsh (3d-путь, line.patterned3d): та же tile-space экструзия
// по widen + декод параметризации, что в linePattern.vert.wgsl, но высота вершины =
// DEM + относительная a_float_height (u_bool_is_3d_line-ветка исходника).
// ECEF/fog/jitter/shadow исходника не портированы (как в 2d-порте).

// Маппоинтов в одном метре веб-меркатора (include/dem.vsh)
const MAP_POINTS_IN_METER: f32 = 107.17318796639701;
// Маппоинты → нормализованный tile-z (= 1/zScale модели WebGL, см. polygonExtrusion.vert.wgsl)
const VERTICAL_SCALE: f32 = (32768.0 / 65535.0) / 1048576.0;
// Нормализованный tile-z → маппоинты: модель тайла Sunda имеет m[10] = 1 (z сразу в маппоинтах)
const Z_SCALE: f32 = 1048576.0 / (32768.0 / 65535.0);

struct Uniforms {
    mvpMatrix: mat4x4f,
    // Цвет паттерна, premultiplied (u_vec4_color с apply_opacity(., 1.))
    color: vec4f,
    // u_vec4_pattern_params (x — период в логических px)
    patternParams: vec4f,
    // x: ширина линии в физ. px (u_float_width), y: scales.x (норм. длина → лог. px),
    // z: scales.y (физ. px → нормализованные координаты тайла), w: pattern_type (1..6)
    params: vec4f,
    // тайловые координаты → текстура высот рельефа
    demTexMvp: mat4x4f,
    // x = demScale (0 — рельеф выключен), y = centerElevation (м),
    // z = 1/fogDistance (0 = туман выключен), w = XY-масштаб модели тайла
    demParams: vec4f,
    // xyz = (тайл − камера)/fogDistance; w не используется (масштабы в demParams)
    fogOrigin: vec4f,
};

struct VertexOutput {
    @builtin(position) position: vec4f,
    @location(0) uv: vec2f,
    // Порт v_fog_pos: (world_pos − cam_pos)/fog_distance
    @location(1) fogPos: vec3f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(1) @binding(0) var demTex: texture_2d<f32>;
@group(1) @binding(1) var demSampler: sampler;

// Распаковка widen: normalize_s08 · sqrt(2) (packed_attributes.vsh, unpack_widen);
// значения ±127-масштаба лежат в s16 (миллиметровые митры длиннее s8)
const WIDEN_UNPACK_MULTIPLIER = 0.011135539861205473;
// Коэффициент перед w, чтоб не взрывалось на mediump (g_w_factor patterned_line.vsh)
const W_FACTOR = 1e-6;

// Высота рельефа в нормализованном tile-z по тайловым координатам (порт dem_height).
// 0 при выключенном рельефе (demScale == 0); без данных рельефа — уровень моря.
fn demHeight(coords: vec2f) -> f32 {
    let demScale = uniforms.demParams.x;
    if (demScale == 0.0) {
        return 0.0;
    }
    let texPos = (uniforms.demTexMvp * vec4f(coords, 0.0, 1.0)).xy;
    // V переворачивается: текстура высот записана в WebGPU матрицами WebGL-конвенции
    let elevation = textureSampleLevel(demTex, demSampler, vec2f(texPos.x, 1.0 - texPos.y), 0.0);
    // Порт dem_height_direct_meters: без данных рельефа — 0 м (уровень моря), как в WebGL
    var meters = elevation.r;
    if (elevation.a < 1.0) {
        meters = 0.0;
    }
    return (meters - uniforms.demParams.y) * MAP_POINTS_IN_METER * VERTICAL_SCALE * demScale;
}

@vertex
fn main(
    @location(0) pos: vec2f,
    @location(1) widenPacked: vec2i,
    @location(2) textureCoord: f32,
    @location(3) height: f32,
) -> VertexOutput {
    let lineWidth = uniforms.params.x;

    // Декод «текстурной координаты» из одного флоата: u — магнитуда, v — знак (±0.5)
    var uv = vec2f(abs(textureCoord), sign(textureCoord) * 0.5);
    uv.x *= uniforms.params.y / uniforms.patternParams.x;

    // Высота вершины: DEM + относительная высота из данных (в маппоинтах, m[10] модели = 1)
    let vertexZ = (demHeight(pos) + height * VERTICAL_SCALE) * Z_SCALE;

    // Прибавляем к общей ширине 1 пиксель для сглаживания
    let fullWidth = lineWidth + 1.0;
    let widen = vec2f(widenPacked) * WIDEN_UNPACK_MULTIPLIER;
    let extender = widen * fullWidth * 0.5;
    let shiftedVertex = vec4f(pos + extender * uniforms.params.z, vertexZ, 1.0);

    var output: VertexOutput;
    output.uv = uv;
    output.position = (uniforms.mvpMatrix * shiftedVertex) * W_FACTOR;
    // Порт calc_fog_pos: xy в маппоинтах через масштаб модели (demParams.w), vertexZ уже в маппоинтах
    output.fogPos = uniforms.fogOrigin.xyz +
        vec3f(shiftedVertex.xy * uniforms.demParams.w, vertexZ) * uniforms.demParams.z;
    return output;
}
`,pD=`// Запись TIN-меша рельефа в текстуру высот (порт dem_elevation.vsh).
// mvpMatrix = demFbVp (орто-проекция в текстуру рельефа) × модельная матрица тайла.

struct Uniforms {
    mvpMatrix: mat4x4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;

struct VertexOutput {
    @builtin(position) position: vec4f,
    @location(0) height: f32,
};

@vertex
fn main(@location(0) pos: vec2f, @location(1) height: f32) -> VertexOutput {
    var out: VertexOutput;
    out.position = uniforms.mvpMatrix * vec4f(pos.x, pos.y, 0.0, 1.0);
    out.height = height;
    return out;
}
`,gD=`// Запись TIN-меша рельефа в текстуру высот (порт dem_elevation.fsh).
// R = высота в метрах, A = валидность (1 — есть данные рельефа).

@fragment
fn main(@location(0) height: f32) -> @location(0) vec4f {
    return vec4f(height, 0.0, 0.0, 1.0);
}
`,mD=`// 3D-отрисовка TIN-меша рельефа (порт dem_mesh2.vsh).
// На рельеф проецируется текстура flat-карты: texcoord считается матрицей
// flatTexMvp = FlatLevels[L].Tex × модель тайла, деление на w — во фрагменте.

// Маппоинтов в одном метре веб-меркатора (utils/geo.ts MAP_POINTS_IN_METER)
const MAP_POINTS_IN_METER: f32 = 107.17318796639701;

struct Uniforms {
    mvpMatrix: mat4x4f,
    // map coords → текстурные координаты flat-карты текущего уровня каскада
    flatTexMvpMatrix: mat4x4f,
    // x = demScale, y = высота центра карты (м), z = мин. высота вьюпорта (м)
    demParams: vec4f,
    // x = XY-масштаб модели тайла, y = интенсивность затенения рельефа
    params: vec4f,
    // xyz = (тайл − камера)/fogDistance, w = 1/fogDistance; нули = туман выключен
    fogOrigin: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;

struct VertexOutput {
    @builtin(position) position: vec4f,
    @location(0) height: f32,
    @location(1) texcoord: vec4f,
    @location(2) worldPos: vec3f,
    // Порт v_fog_pos: (world_pos − cam_pos)/fog_distance
    @location(3) fogPos: vec3f,
};

@vertex
fn main(
    @location(0) pos: vec2f,
    @location(1) height: f32,
) -> VertexOutput {
    // Аналог meters_to_tile_height: у Sunda модельная матрица тайла имеет Z-scale = 1,
    // поэтому u_float_vertical_scale не нужен — высота сразу в маппоинтах
    let heightMp = (height - uniforms.demParams.y) * MAP_POINTS_IN_METER * uniforms.demParams.x;

    var out: VertexOutput;
    out.position = uniforms.mvpMatrix * vec4f(pos.x, pos.y, heightMp, 1.0);
    out.height = height;
    out.texcoord = uniforms.flatTexMvpMatrix * vec4f(pos.x, pos.y, 0.0, 1.0);
    // Позиция в маппоинтах без трансляции — только ориентация для нормалей
    // по производным (аналог mat3(u_mat4_model) × pos в dem_mesh2.vsh)
    out.worldPos = vec3f(pos.xy * uniforms.params.x, heightMp);
    // Порт calc_fog_pos: worldPos уже (world − tileMin) в маппоинтах
    out.fogPos = uniforms.fogOrigin.xyz + out.worldPos * uniforms.fogOrigin.w;
    return out;
}
`,vD=`// 3D-отрисовка TIN-меша рельефа: проекция текстуры flat-карты + освещение +
// туман (порт dem_mesh2.fsh без теней). Фрагменты вне текстуры уровня
// каскада отбрасываются — их закроет следующий, более «дальний» уровень.

struct Uniforms {
    mvpMatrix: mat4x4f,
    flatTexMvpMatrix: mat4x4f,
    demParams: vec4f,
    // x = XY-масштаб модели тайла, y = интенсивность затенения рельефа
    params: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(0) @binding(1) var<uniform> light: LightBlock;
// FogBlock — chunk fog.wgsl
@group(0) @binding(2) var<uniform> fog: FogBlock;
// Тени кадра — chunk shadow.wgsl (ShadowBlock + карта теней + comparison-сэмплер)
@group(0) @binding(3) var<uniform> shadow: ShadowBlock;
@group(0) @binding(4) var shadowTex: texture_depth_2d;
@group(0) @binding(5) var shadowSampler: sampler_comparison;
@group(1) @binding(0) var flatTex: texture_2d<f32>;
@group(1) @binding(1) var flatSampler: sampler;

@fragment
fn main(
    @builtin(position) fragCoord: vec4f,
    @location(0) height: f32,
    @location(1) texcoord: vec4f,
    @location(2) worldPos: vec3f,
    @location(3) fogPos: vec3f,
) -> @location(0) vec4f {
    // Перспективное деление текстурных координат
    let tc = texcoord.xy / texcoord.w;
    if (tc.x < 0.0 || tc.x > 1.0 || tc.y < 0.0 || tc.y > 1.0) {
        discard;
    }

    // V переворачивается: flat-текстура записана в WebGPU с матрицами WebGL-конвенции
    let color = textureSample(flatTex, flatSampler, vec2f(tc.x, 1.0 - tc.y));

    // Нормаль из экранных производных (порт calc_fragment_normal). Порядок
    // аргументов cross обратный GLSL-версии: ось Y фреймбуфера WebGPU
    // направлена вниз, и dpdy имеет знак, противоположный dFdy
    let normal = normalize(cross(dpdy(worldPos), dpdx(worldPos)));
    // Тень — всегда на первый свет (порт хардкода SHADOW_FOR_FIRST_LIGHT_FLAG для слоя dem):
    // у режима DEM_LIGHTING_MODE второго света нет, кадровый индекс к нему неприменим
    let lf = lightFactorShadowed(normal, fragCoord, min(shadow.params.y, 1.0));
    // Порт apply_fog из dem_mesh2.fsh
    return applyFog(fog, vec4f(color.rgb * lf, 1.0), fogPos);
}
`,yD=`// 3D-меш развязки/тоннеля (порт map_mesh.vsh без света/теней/тумана).
// Высота вершины: собственный Z меша × heightFactor + привязка к рельефу
// (dem_height по demPosition / позиции опоры) либо абсолютная высота absZ.
// Экстендеры, нормали и градиент не подключены — освещение вне скоупа.

// Маппоинтов в одном метре веб-меркатора (include/dem.vsh)
const MAP_POINTS_IN_METER: f32 = 107.17318796639701;
// Множитель распаковки demPosition: в генераторе координату делили на 8,
// тайловые координаты нормализованы на 65535 (UNPACK_CENTROID из include/dem.vsh)
const UNPACK_CENTROID: f32 = 8.0 / 65535.0;

struct Uniforms {
    // Камера × модель тайла (с Z-remap под WebGPU)
    mvpMatrix: mat4x4f,
    // demTextureMatrix × модель тайла — тайловые координаты → текстура рельефа
    demTexMvpMatrix: mat4x4f,
    // x = texScaleX, y = texScaleY, z = texShift (1 - cos(pitch)), w = heightFactor
    params: vec4f,
    // x = absZ (0/1), y = demScale (0 при выключенном рельефе), z = высота центра карты (м),
    // w = XY-масштаб модели тайла (маппоинты на единицу pos)
    params2: vec4f,
    // xyz = (тайл − камера)/fogDistance, w = 1/fogDistance; нули = туман выключен
    fogOrigin: vec4f,
    // Цвет поверхности слоя (без премультипликации) — читает фрагментник
    surfaceColor: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(1) @binding(1) var demTex: texture_2d<f32>;
@group(1) @binding(2) var meshSampler: sampler;

struct VertexOutput {
    @builtin(position) position: vec4f,
    @location(0) texcoord: vec4f,
    @location(1) demTexPos: vec2f,
    @location(2) demInvalid: f32,
    @location(3) normal: vec3f,
    // Порт v_fog_pos: (world_pos − cam_pos)/fog_distance
    @location(4) fogPos: vec3f,
};

struct DemSample {
    height: f32,
    texPos: vec2f,
    invalid: f32,
};

// Порт dem_height: высота в маппоинтах из текстуры рельефа по тайловым координатам.
// При выключенном рельефе (demScale == 0) возвращает нули — как reset_dem_varyings.
fn demHeight(coords: vec2f) -> DemSample {
    var result = DemSample(0.0, vec2f(0.0), 0.0);
    if (uniforms.params2.y == 0.0) {
        return result;
    }

    let texPos = (uniforms.demTexMvpMatrix * vec4f(coords, 0.0, 1.0)).xy;
    result.texPos = texPos;

    // V переворачивается: текстура высот записана в WebGPU матрицами WebGL-конвенции
    let elevation = textureSampleLevel(demTex, meshSampler, vec2f(texPos.x, 1.0 - texPos.y), 0.0);
    // Порт dem_height_direct_meters: без данных рельефа — 0 м (уровень моря), как в WebGL
    var meters = elevation.r;
    if (elevation.a < 1.0) {
        result.invalid = 1.0;
        meters = 0.0;
    }

    result.height = (meters - uniforms.params2.z) * MAP_POINTS_IN_METER * uniforms.params2.y;
    return result;
}

@vertex
fn main(
    @location(0) pos: vec2f,
    @location(1) z: f32,
    @location(2) raw16: u32,
    @location(3) pivotWord: u32,
    // xyz — нормаль (int8), w — градиент (в WebGL не используется: юниформа не биндится)
    @location(4) normalGradient: vec4i,
) -> VertexOutput {
    var dem = DemSample(0.0, vec2f(0.0), 0.0);

    if (uniforms.params2.x == 0.0) {
        // Меш привязан к рельефу: байты 16..19 — координата demPosition (два int16)
        let demX = f32(bitcast<i32>(raw16 << 16u) >> 16);
        let demY = f32(bitcast<i32>(raw16) >> 16);
        dem = demHeight(vec2f(demX, demY) * UNPACK_CENTROID);
    } else if ((pivotWord & 0xffu) == 1u) {
        // Опора (pivot) прижимается к рельефу по позиции вершины
        dem = demHeight(pos);
    } else {
        // Фиксированная абсолютная высота: байты 16..19 — float32 в маппоинтах.
        // Порт abs_height: u_float_vertical_scale сокращается с Z-scale модели
        let absZ = bitcast<f32>(raw16);
        dem.height = (absZ - uniforms.params2.z * MAP_POINTS_IN_METER) * uniforms.params2.y;
    }

    // Нормализация a_float_z и Z-scale модели тайла в WebGL сокращаются точно:
    // собственная высота меша сразу в маппоинтах
    let worldZ = z * uniforms.params.w + dem.height;

    var out: VertexOutput;
    out.position = uniforms.mvpMatrix * vec4f(pos.x, pos.y, worldZ, 1.0);
    // Клип-координаты «плоской» вершины — для проекции текстуры ярусов во фрагменте
    out.texcoord = uniforms.mvpMatrix * vec4f(pos.x, pos.y, 0.0, 1.0);
    out.demTexPos = dem.texPos;
    out.demInvalid = dem.invalid;
    // Порт normalize_s08: int8 → [-1, 1]
    out.normal = normalize(vec3f(normalGradient.xyz) / 127.0);
    // Порт calc_fog_pos: xy в маппоинтах через масштаб модели (params2.w), worldZ уже в маппоинтах
    out.fogPos = uniforms.fogOrigin.xyz +
        vec3f(pos * uniforms.params2.w, worldZ) * uniforms.fogOrigin.w;
    return out;
}
`,xD=`// Текстурирование меша развязки текстурой ярусов + освещение по нормали
// (порт map_mesh.fsh без тумана/screendoor; gradient darkening пропущен —
// в WebGL его юниформа не биндится и эффект не работает).
// Фрагменты с невалидной высотой рельефа отбрасываются (порт check_dem_invalid).

struct Uniforms {
    mvpMatrix: mat4x4f,
    demTexMvpMatrix: mat4x4f,
    params: vec4f,
    params2: vec4f,
    fogOrigin: vec4f,
    // Цвет поверхности слоя overpass/tunnel (без премультипликации)
    surfaceColor: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(0) @binding(1) var<uniform> light: LightBlock;
// FogBlock — chunk fog.wgsl
@group(0) @binding(2) var<uniform> fog: FogBlock;
// Тени кадра — chunk shadow.wgsl (ShadowBlock + карта теней + comparison-сэмплер)
@group(0) @binding(3) var<uniform> shadow: ShadowBlock;
@group(0) @binding(4) var shadowTex: texture_depth_2d;
@group(0) @binding(5) var shadowSampler: sampler_comparison;
@group(1) @binding(0) var mapMeshTex: texture_2d<f32>;
@group(1) @binding(2) var meshSampler: sampler;

// 1 — подложить цвет поверхности слоя под текстуру яруса (в WebGL им очищается текстура
// яруса, свой цвет на каждый слой); 0 — hidden-проход (текстура очищена ZERO_RGBA)
override surfaceFill: u32 = 1u;

@fragment
fn main(
    @builtin(position) fragCoord: vec4f,
    @location(0) texcoord: vec4f,
    @location(1) demTexPos: vec2f,
    @location(2) demInvalid: f32,
    @location(3) normal: vec3f,
    @location(4) fogPos: vec3f,
) -> @location(0) vec4f {
    // Порт check_dem_invalid: высота некорректна или точка вне текстуры рельефа
    if (demInvalid != 0.0 ||
        demTexPos.x < 0.0 || demTexPos.x > 1.0 ||
        demTexPos.y < 0.0 || demTexPos.y > 1.0) {
        discard;
    }

    // Перспективное деление, затем переход из клип-координат камеры
    // в текстурные координаты текстуры ярусов: масштаб и сдвиг при наклоне
    var coord = texcoord.xy / texcoord.w;
    coord = coord / uniforms.params.xy;
    coord.y += uniforms.params.z / uniforms.params.y;
    coord = coord * 0.5 + vec2f(0.5, 0.5);

    if (coord.x < 0.0 || coord.x > 1.0 || coord.y < 0.0 || coord.y > 1.0) {
        return vec4f(0.0);
    }

    // V переворачивается: текстура ярусов записана матрицами WebGL-конвенции.
    // textureSampleLevel вместо textureSample: после раннего return выше поток
    // управления неравномерный, а у текстуры ярусов всё равно один мип-уровень
    var color = textureSampleLevel(mapMeshTex, meshSampler, vec2f(coord.x, 1.0 - coord.y), 0.0);
    if (surfaceFill != 0u) {
        // Контент яруса (премультиплай) поверх цвета слоя = то же, что очистка им текстуры
        color = color + uniforms.surfaceColor * (1.0 - color.a);
    }

    // Порт apply_fog из map_mesh.fsh (в legacy — только в текстурированной ветке)
    return applyFog(fog, vec4f(color.rgb * lightFactor(normal, fragCoord), color.a), fogPos);
}
`,wD=`// Меш тоннеля/эстакады/метроямы/зала метро (порт mesh.vsh) — общий вершинник всех режимов
// DrawMesh (fill / depth-only / depth-clear / labeling / shadow-кастер). Высотная математика —
// как у mapMesh.vert: собственная высота меша сразу в маппоинтах (нормализация a_float_z и
// Z-scale модели тайла сокращаются) × heightFactor + рельеф либо absZ + подъём этажа.
//
// Раскладки sink'ов различаются (fill stride 32, inverse 20, depthClear 16): пайплайн всегда
// подаёт все атрибуты, у depth-раскладок нормаль/id указывают на чужие байты — их режимы эти
// входы не читают.

const MAP_POINTS_IN_METER: f32 = 107.17318796639701;
const UNPACK_CENTROID: f32 = 8.0 / 65535.0;

struct Uniforms {
    // Камера × модель тайла (с Z-remap под WebGPU)
    mvpMatrix: mat4x4f,
    // demTextureMatrix × модель тайла — тайловые координаты → текстура рельефа
    demTexMvpMatrix: mat4x4f,
    // Цвет заливки (premult) либо низ градиента
    color: vec4f,
    // Верх градиента (premult)
    color2: vec4f,
    // x = heightFactor, y = floorElevation (маппоинты), z/w = края градиента (edge0/edge1)
    params: vec4f,
    // x = absZ (0/1), y = demScale (0 при выключенном рельефе), z = высота центра карты (м),
    // w = XY-масштаб модели тайла (маппоинты на единицу pos)
    params2: vec4f,
    // x = градиент (0/1)
    params3: vec4f,
    // xyz = (тайл − камера)/fogDistance, w = 1/fogDistance; нули = туман выключен
    fogOrigin: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(1) @binding(0) var demTex: texture_2d<f32>;
@group(1) @binding(1) var demSampler: sampler;

struct VertexOutput {
    @builtin(position) position: vec4f,
    // xyz — нормаль, w — фактор градиента (порт v_vec4_normal_gradient)
    @location(0) normalGradient: vec4f,
    @location(1) demTexPos: vec2f,
    @location(2) demInvalid: f32,
    @location(3) fogPos: vec3f,
    // id-цвет для occlusion-таргета лейблов (labelingTextureID)
    @location(4) identifier: vec4f,
};

struct DemSample {
    height: f32,
    texPos: vec2f,
    invalid: f32,
};

// Порт dem_height: высота в маппоинтах (как mapMesh.vert)
fn demHeight(coords: vec2f) -> DemSample {
    var result = DemSample(0.0, vec2f(0.0), 0.0);
    if (uniforms.params2.y == 0.0) {
        return result;
    }

    let texPos = (uniforms.demTexMvpMatrix * vec4f(coords, 0.0, 1.0)).xy;
    result.texPos = texPos;

    let elevation = textureSampleLevel(demTex, demSampler, vec2f(texPos.x, 1.0 - texPos.y), 0.0);
    // Порт dem_height_direct_meters: невалидная точка — 0 м (уровень моря), а не высота центра
    // карты. Заливку такой вершины отбросит check_dem_invalid, но depthClear не отбрасывается —
    // его покрытие на экране зависит от этой высоты
    var meters = elevation.r;
    if (elevation.a < 1.0) {
        result.invalid = 1.0;
        meters = 0.0;
    }

    result.height = (meters - uniforms.params2.z) * MAP_POINTS_IN_METER * uniforms.params2.y;
    return result;
}

@vertex
fn main(
    @location(0) pos: vec2f,
    @location(1) z: f32,
    @location(2) raw: u32,
    @location(3) pivotWord: u32,
    @location(4) normalGradient: vec4i,
    @location(5) identifier: vec4f,
) -> VertexOutput {
    var dem = DemSample(0.0, vec2f(0.0), 0.0);

    if (uniforms.params2.x == 0.0) {
        // demPosition (два int16) — точка привязки к рельефу
        let demX = f32(bitcast<i32>(raw << 16u) >> 16);
        let demY = f32(bitcast<i32>(raw) >> 16);
        dem = demHeight(vec2f(demX, demY) * UNPACK_CENTROID);
    } else if ((pivotWord & 0xffu) == 1u) {
        dem = demHeight(pos);
    } else {
        // Порт abs_height: float32 в маппоинтах
        let absZ = bitcast<f32>(raw);
        dem.height = (absZ - uniforms.params2.z * MAP_POINTS_IN_METER) * uniforms.params2.y;
    }

    let worldZ = z * uniforms.params.x + dem.height + uniforms.params.y;

    var out: VertexOutput;
    out.position = uniforms.mvpMatrix * vec4f(pos.x, pos.y, worldZ, 1.0);
    // Порт normalize(a_vec3_normal) + a_float_gradient / 127
    out.normalGradient = vec4f(
        normalize(vec3f(normalGradient.xyz) / 127.0),
        f32(normalGradient.w) / 127.0,
    );
    out.demTexPos = dem.texPos;
    out.demInvalid = dem.invalid;
    out.fogPos = uniforms.fogOrigin.xyz +
        vec3f(pos * uniforms.params2.w, worldZ) * uniforms.fogOrigin.w;
    out.identifier = identifier;
    return out;
}
`,AD=`// Фрагмент DrawMesh (порт mesh.fsh / inverse.fsh / depth_clear.fsh). Режим — override
// meshMode (pipeline-константа): 0 — заливка (цвет/градиент × свет + туман), 1 — только
// глубина (цвет замаскирован writeMask 0), 2 — глубина = 1 (пробойник: depthCompare always),
// 3 — id-цвет в occlusion-таргет лейблов. Текстурная ветка и screendoor mesh.fsh не портированы.

struct Uniforms {
    mvpMatrix: mat4x4f,
    demTexMvpMatrix: mat4x4f,
    color: vec4f,
    color2: vec4f,
    params: vec4f,
    params2: vec4f,
    params3: vec4f,
    fogOrigin: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(0) @binding(1) var<uniform> light: LightBlock;
// FogBlock — chunk fog.wgsl
@group(0) @binding(2) var<uniform> fog: FogBlock;
// Тени кадра — chunk shadow.wgsl
@group(0) @binding(3) var<uniform> shadow: ShadowBlock;
@group(0) @binding(4) var shadowTex: texture_depth_2d;
@group(0) @binding(5) var shadowSampler: sampler_comparison;

override meshMode: u32 = 0u;

struct FragmentOutput {
    @location(0) color: vec4f,
    @builtin(frag_depth) depth: f32,
};

@fragment
fn main(
    @builtin(position) fragCoord: vec4f,
    @location(0) normalGradient: vec4f,
    @location(1) demTexPos: vec2f,
    @location(2) demInvalid: f32,
    @location(3) fogPos: vec3f,
    @location(4) identifier: vec4f,
) -> FragmentOutput {
    var out: FragmentOutput;
    out.depth = fragCoord.z;

    if (meshMode == 2u) {
        // Порт depth_clear.fsh: глубина «на бесконечность» — дальше под крышкой видно
        // то, что рельеф/земля закрыли бы
        out.depth = 1.0;
        out.color = vec4f(0.0);
        return out;
    }

    // Порт check_dem_invalid
    if (demInvalid != 0.0 ||
        demTexPos.x < 0.0 || demTexPos.x > 1.0 ||
        demTexPos.y < 0.0 || demTexPos.y > 1.0) {
        discard;
    }

    if (meshMode == 1u) {
        out.color = vec4f(0.0);
        return out;
    }
    if (meshMode == 3u) {
        out.color = identifier;
        return out;
    }

    var color = uniforms.color;
    if (uniforms.params3.x != 0.0) {
        color = mix(
            uniforms.color,
            uniforms.color2,
            smoothstep(uniforms.params.z, uniforms.params.w, normalGradient.w),
        );
    }
    out.color = applyFog(
        fog,
        vec4f(color.rgb * lightFactor(normalGradient.xyz, fragCoord), color.a),
        fogPos,
    );
    return out;
}
`,bD=`// 3D-здание (polygonExtrusion): footprint xy + нормализованная tile-height z → 3D-вершина,
// поднятая на рельеф (DEM). Порт diffuse.vsh:46-64 + include/dem.vsh.
//
// Высота z — нормализованная tile-координата [0,1]; модель тайла несёт z-scale
// (tileHeight/uint16ToTileCoords, см. TileMatrix.composeExtrusion), поэтому finalZ идёт в mvp/model
// напрямую. Высота рельефа считается в тех же tile-z единицах (через VERTICAL_SCALE = 1/zScale),
// складывается с z и масштабируется тем же m[10]. Нормаль не передаётся — flat, во фрагменте.

// Маппоинтов в одном метре веб-меркатора (include/dem.vsh)
const MAP_POINTS_IN_METER: f32 = 107.17318796639701;
// Распаковка demPosition (центроид): pos * 8 / 65535 (UNPACK_CENTROID из include/dem.vsh)
const UNPACK_CENTROID: f32 = 8.0 / 65535.0;
// Маппоинты → tile-z = 1 / zScale = uint16ToTileCoords / tileHeight = (2^15/(2^16-1)) / 2^20.
// Сокращается с m[10] модели (zScale ≈ 2097120), оставляя высоту рельефа в маппоинтах мира.
const VERTICAL_SCALE: f32 = (32768.0 / 65535.0) / 1048576.0;

struct Uniforms {
    // Камера × модель тайла (с Z-remap под WebGPU)
    mvpMatrix: mat4x4f,
    // Модель тайла; во фрагменте берём её mat3 (без мировой трансляции) для flat-нормали
    modelMatrix: mat4x4f,
    // Цвет грани (premultiplied RGBA)
    color: vec4f,
    // Резерв под раскладку gradient-варианта (color2 + gradientParams) — плоским не используется
    _pad0: vec4f,
    _pad1: vec4f,
    // footprint (tile-координаты) → текстура высот рельефа
    demTexMvp: mat4x4f,
    // x = demScale (0 при выключенном рельефе), y = centerElevation (м), z = heightFactor, w = floorElevation
    demParams: vec4f,
    // x = near-camera fade distance (clip-z); 0 — выключено
    fadeParams: vec4f,
    // xyz = (тайл − камера)/fogDistance, w = 1/fogDistance; нули = туман выключен
    fogOrigin: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(1) @binding(0) var demTex: texture_2d<f32>;
@group(1) @binding(1) var demSampler: sampler;

struct VertexOutput {
    @builtin(position) position: vec4f,
    // Позиция через mat3(model) — масштаб+ориентация БЕЗ мировой трансляции тайла (float32-точность
    // для производных flat-нормали). Приём из WebGL (v_vec4_rotated_scaled_vertex = mat3(model)*vertex).
    @location(0) rotatedScaledPos: vec3f,
    @location(1) color: vec4f,
    // Клип-позиция (для near-camera screendoor) + дистанция фейда (константа на дроу)
    @location(2) clipPos: vec4f,
    @location(3) nearCameraFade: f32,
    // Порт v_fog_pos: (world_pos − cam_pos)/fog_distance
    @location(4) fogPos: vec3f,
};

// Высота рельефа в tile-z по тайловым координатам (порт dem_height). 0 при выключенном рельефе
// (demScale == 0); без данных рельефа — уровень моря (как WebGL: здание уходит под землю).
fn demHeight(coords: vec2f) -> f32 {
    let demScale = uniforms.demParams.x;
    if (demScale == 0.0) {
        return 0.0;
    }
    let texPos = (uniforms.demTexMvp * vec4f(coords, 0.0, 1.0)).xy;
    // V переворачивается: текстура высот записана в WebGPU матрицами WebGL-конвенции (как mapMesh)
    let elevation = textureSampleLevel(demTex, demSampler, vec2f(texPos.x, 1.0 - texPos.y), 0.0);
    // Порт dem_height_direct_meters: без данных рельефа — 0 м (уровень моря), как в WebGL
    var meters = elevation.r;
    if (elevation.a < 1.0) {
        meters = 0.0;
    }
    return (meters - uniforms.demParams.y) * MAP_POINTS_IN_METER * VERTICAL_SCALE * demScale;
}

@vertex
fn main(
    @location(0) pos: vec2f,
    @location(1) z: f32,
    @location(3) demPos: vec2i,
    // per-vertex цвет грани (innerColor, unorm8x4 straight-alpha) — используется при isVertexColor
    @location(5) innerColor: vec4f,
) -> VertexOutput {
    let heightFactor = uniforms.demParams.z;
    let floorElevation = uniforms.demParams.w;
    // Флаг подземной выемки (hole) во @42 = _pad1.z, isVertexColor во @43 = _pad1.w
    // (общие offset'ы с gradient-вариантом)
    let isHole = uniforms._pad1.z;
    let isVertexColor = uniforms._pad1.w;

    // Основание — по центроиду здания (один сэмпл на всё здание, чтобы оно не рвалось на склоне).
    var base = demHeight(vec2f(demPos) * UNPACK_CENTROID);
    if (z == 0.0) {
        // Кольцо основания: НИЖНЯЯ из центроида и попозиционной высоты (у выемки — всегда попозиционная)
        let posTerrain = demHeight(pos);
        if (isHole > 0.5 || base > posTerrain) {
            base = posTerrain;
        }
    }
    base = base + floorElevation;

    // Растим высоту (heightFactor) и поднимаем на рельеф; обычное здание не пускаем ниже основания,
    // выемка (hole) уходит вниз — без прижатия.
    var finalZ = z * heightFactor + base;
    if (isHole < 0.5) {
        finalZ = max(finalZ, base);
    }

    let local = vec4f(pos, finalZ, 1.0);
    let rotationScale = mat3x3f(
        uniforms.modelMatrix[0].xyz,
        uniforms.modelMatrix[1].xyz,
        uniforms.modelMatrix[2].xyz,
    );

    var out: VertexOutput;
    out.position = uniforms.mvpMatrix * local;
    out.rotatedScaledPos = rotationScale * local.xyz;
    // isVertexColor: цвет из атрибута (premultiplied из straight-alpha), иначе материальный
    let vtxColor = vec4f(innerColor.rgb * innerColor.a, innerColor.a);
    out.color = select(uniforms.color, vtxColor, isVertexColor > 0.5);
    out.clipPos = out.position;
    out.nearCameraFade = uniforms.fadeParams.x;
    // Порт calc_fog_pos: rotatedScaledPos уже (world − tileMin) в маппоинтах
    out.fogPos = uniforms.fogOrigin.xyz + out.rotatedScaledPos * uniforms.fogOrigin.w;
    return out;
}
`,SD=`// Фрагмент 3D-зданий/заборов (плоский цвет): flat-нормаль по производным позиции +
// свет стиля и тень (chunks light/shadow), screendoor near-camera fade, туман.
@group(0) @binding(1) var<uniform> light: LightBlock;
// FogBlock — chunk fog.wgsl
@group(0) @binding(2) var<uniform> fog: FogBlock;
// Тени кадра — chunk shadow.wgsl (ShadowBlock + карта теней + comparison-сэмплер)
@group(0) @binding(3) var<uniform> shadow: ShadowBlock;
@group(0) @binding(4) var shadowTex: texture_depth_2d;
@group(0) @binding(5) var shadowSampler: sampler_comparison;

@fragment
fn main(
    @builtin(position) fragCoord: vec4f,
    @location(0) rotatedScaledPos: vec3f,
    @location(1) color: vec4f,
    @location(2) clipPos: vec4f,
    @location(3) nearCameraFade: f32,
    @location(4) fogPos: vec3f,
) -> @location(0) vec4f {
    // Нормаль внешней грани (back-face culling рисует только внешние). cross(dpdy,dpdx) даёт
    // наружу — выверено визуализацией нормали: E=+X, W=−X, N=+Y, S=−Y, крыша=+Z все корректны.
    // Производные считаем ДО возможного discard (требование uniform control flow).
    let normal = normalize(cross(dpdy(rotatedScaledPos), dpdx(rotatedScaledPos)));
    let lit = vec4f(color.rgb * lightFactor(normal, fragCoord), color.a);
    if (screendoorDiscard(nearCameraFade, clipPos, fragCoord.xy)) {
        discard;
    }
    // Порт apply_fog из color_with_z_fade.fsh
    return applyFog(fog, lit, fogPos);
}
`,ED=`// Градиентная стена 3D-здания (polygonExtrusion sideFill): как polygonExtrusion.vert (подъём на
// рельеф), но дополнительно тащит per-vertex elevation (атрибут @24, z0/z1: 0 у основания, 1 у верха)
// — ось вертикального градиента. Цвет считается во фрагменте.

const MAP_POINTS_IN_METER: f32 = 107.17318796639701;
const UNPACK_CENTROID: f32 = 8.0 / 65535.0;
const VERTICAL_SCALE: f32 = (32768.0 / 65535.0) / 1048576.0;

struct Uniforms {
    mvpMatrix: mat4x4f,
    // Модель тайла; берём mat3 (без мировой трансляции) для flat-нормали — см. polygonExtrusion.vert
    modelMatrix: mat4x4f,
    bottomColor: vec4f,
    topColor: vec4f,
    // x = edge0, y = edge1 (границы smoothstep по elevation)
    gradientParams: vec4f,
    // footprint (tile-координаты) → текстура высот рельефа
    demTexMvp: mat4x4f,
    // x = demScale, y = centerElevation (м), z = heightFactor, w = floorElevation
    demParams: vec4f,
    // x = near-camera fade distance (clip-z); 0 — выключено
    fadeParams: vec4f,
    // xyz = (тайл − камера)/fogDistance, w = 1/fogDistance; нули = туман выключен
    fogOrigin: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(1) @binding(0) var demTex: texture_2d<f32>;
@group(1) @binding(1) var demSampler: sampler;

struct VertexOutput {
    @builtin(position) position: vec4f,
    @location(0) rotatedScaledPos: vec3f,
    @location(1) elevation: f32,
    @location(2) clipPos: vec4f,
    @location(3) nearCameraFade: f32,
    // Порт v_fog_pos: (world_pos − cam_pos)/fog_distance
    @location(4) fogPos: vec3f,
};

fn demHeight(coords: vec2f) -> f32 {
    let demScale = uniforms.demParams.x;
    if (demScale == 0.0) {
        return 0.0;
    }
    let texPos = (uniforms.demTexMvp * vec4f(coords, 0.0, 1.0)).xy;
    let elevation = textureSampleLevel(demTex, demSampler, vec2f(texPos.x, 1.0 - texPos.y), 0.0);
    // Порт dem_height_direct_meters: без данных рельефа — 0 м (уровень моря), как в WebGL
    var meters = elevation.r;
    if (elevation.a < 1.0) {
        meters = 0.0;
    }
    return (meters - uniforms.demParams.y) * MAP_POINTS_IN_METER * VERTICAL_SCALE * demScale;
}

@vertex
fn main(
    @location(0) pos: vec2f,
    @location(1) z: f32,
    @location(2) elevation: f32,
    @location(3) demPos: vec2i,
) -> VertexOutput {
    let heightFactor = uniforms.demParams.z;
    let floorElevation = uniforms.demParams.w;
    // Флаг hole во @42 = gradientParams.z (общий offset с плоским вариантом — см. polygonExtrusion.vert)
    let isHole = uniforms.gradientParams.z;

    var base = demHeight(vec2f(demPos) * UNPACK_CENTROID);
    if (z == 0.0) {
        let posTerrain = demHeight(pos);
        if (isHole > 0.5 || base > posTerrain) {
            base = posTerrain;
        }
    }
    base = base + floorElevation;

    var finalZ = z * heightFactor + base;
    if (isHole < 0.5) {
        finalZ = max(finalZ, base);
    }

    let local = vec4f(pos, finalZ, 1.0);
    let rotationScale = mat3x3f(
        uniforms.modelMatrix[0].xyz,
        uniforms.modelMatrix[1].xyz,
        uniforms.modelMatrix[2].xyz,
    );

    var out: VertexOutput;
    out.position = uniforms.mvpMatrix * local;
    out.rotatedScaledPos = rotationScale * local.xyz;
    out.elevation = elevation;
    out.clipPos = out.position;
    out.nearCameraFade = uniforms.fadeParams.x;
    // Порт calc_fog_pos: rotatedScaledPos уже (world − tileMin) в маппоинтах
    out.fogPos = uniforms.fogOrigin.xyz + out.rotatedScaledPos * uniforms.fogOrigin.w;
    return out;
}
`,TD=`// Градиентная стена lineExtrusion.fill (stride 16): как polygonExtrusionGradient.vert,
// но per-vertex elevation-атрибута в бакете нет — ось градиента берётся фолбэком
// z > 0 → 1 (порт diffuse.vsh:115-119). Фрагментник общий (polygonExtrusionGradient.frag).

const MAP_POINTS_IN_METER: f32 = 107.17318796639701;
const UNPACK_CENTROID: f32 = 8.0 / 65535.0;
const VERTICAL_SCALE: f32 = (32768.0 / 65535.0) / 1048576.0;

struct Uniforms {
    mvpMatrix: mat4x4f,
    // Модель тайла; берём mat3 (без мировой трансляции) для flat-нормали — см. polygonExtrusion.vert
    modelMatrix: mat4x4f,
    bottomColor: vec4f,
    topColor: vec4f,
    // x = edge0, y = edge1 (границы smoothstep по elevation)
    gradientParams: vec4f,
    // footprint (tile-координаты) → текстура высот рельефа
    demTexMvp: mat4x4f,
    // x = demScale, y = centerElevation (м), z = heightFactor, w = floorElevation
    demParams: vec4f,
    // x = near-camera fade distance (clip-z); 0 — выключено
    fadeParams: vec4f,
    // xyz = (тайл − камера)/fogDistance, w = 1/fogDistance; нули = туман выключен
    fogOrigin: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(1) @binding(0) var demTex: texture_2d<f32>;
@group(1) @binding(1) var demSampler: sampler;

struct VertexOutput {
    @builtin(position) position: vec4f,
    @location(0) rotatedScaledPos: vec3f,
    @location(1) elevation: f32,
    @location(2) clipPos: vec4f,
    @location(3) nearCameraFade: f32,
    // Порт v_fog_pos: (world_pos − cam_pos)/fog_distance
    @location(4) fogPos: vec3f,
};

fn demHeight(coords: vec2f) -> f32 {
    let demScale = uniforms.demParams.x;
    if (demScale == 0.0) {
        return 0.0;
    }
    let texPos = (uniforms.demTexMvp * vec4f(coords, 0.0, 1.0)).xy;
    let elevation = textureSampleLevel(demTex, demSampler, vec2f(texPos.x, 1.0 - texPos.y), 0.0);
    // Порт dem_height_direct_meters: без данных рельефа — 0 м (уровень моря), как в WebGL
    var meters = elevation.r;
    if (elevation.a < 1.0) {
        meters = 0.0;
    }
    return (meters - uniforms.demParams.y) * MAP_POINTS_IN_METER * VERTICAL_SCALE * demScale;
}

@vertex
fn main(
    @location(0) pos: vec2f,
    @location(1) z: f32,
    @location(3) demPos: vec2i,
) -> VertexOutput {
    let heightFactor = uniforms.demParams.z;
    let floorElevation = uniforms.demParams.w;
    let isHole = uniforms.gradientParams.z;

    var base = demHeight(vec2f(demPos) * UNPACK_CENTROID);
    if (z == 0.0) {
        let posTerrain = demHeight(pos);
        if (isHole > 0.5 || base > posTerrain) {
            base = posTerrain;
        }
    }
    base = base + floorElevation;

    var finalZ = z * heightFactor + base;
    if (isHole < 0.5) {
        finalZ = max(finalZ, base);
    }

    let local = vec4f(pos, finalZ, 1.0);
    let rotationScale = mat3x3f(
        uniforms.modelMatrix[0].xyz,
        uniforms.modelMatrix[1].xyz,
        uniforms.modelMatrix[2].xyz,
    );

    var out: VertexOutput;
    out.position = uniforms.mvpMatrix * local;
    out.rotatedScaledPos = rotationScale * local.xyz;
    // Фолбэк оси градиента: атрибута elevation нет — верх стены (z > 0) даёт 1
    out.elevation = select(0.0, 1.0, z > 0.0);
    out.clipPos = out.position;
    out.nearCameraFade = uniforms.fadeParams.x;
    // Порт calc_fog_pos: rotatedScaledPos уже (world − tileMin) в маппоинтах
    out.fogPos = uniforms.fogOrigin.xyz + out.rotatedScaledPos * uniforms.fogOrigin.w;
    return out;
}
`,cx=`// Градиентная стена 3D-здания: вертикальный градиент bottomColor→topColor по elevation
// (порт gradient_with_z_fade.fsh: mix(bottom, top, smoothstep(edge0, edge1, pos))) +
// тот же flat-нормаль + Lambert/ambient, что и у плоского варианта. Стопка этажей — порт
// u_vec2_floor_level: pos = (offset + elevation) / total (fadeParams.yz; не стопка — (0, 1)).

struct Uniforms {
    mvpMatrix: mat4x4f,
    modelMatrix: mat4x4f,
    bottomColor: vec4f,
    topColor: vec4f,
    gradientParams: vec4f,
    demTexMvp: mat4x4f,
    demParams: vec4f,
    // x = near-camera fade (вершинник), yz = floor level стопки этажей (offset, total)
    fadeParams: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(0) @binding(1) var<uniform> light: LightBlock;
// FogBlock — chunk fog.wgsl
@group(0) @binding(2) var<uniform> fog: FogBlock;
// Тени кадра — chunk shadow.wgsl (ShadowBlock + карта теней + comparison-сэмплер)
@group(0) @binding(3) var<uniform> shadow: ShadowBlock;
@group(0) @binding(4) var shadowTex: texture_depth_2d;
@group(0) @binding(5) var shadowSampler: sampler_comparison;

@fragment
fn main(
    @builtin(position) fragCoord: vec4f,
    @location(0) rotatedScaledPos: vec3f,
    @location(1) elevation: f32,
    @location(2) clipPos: vec4f,
    @location(3) nearCameraFade: f32,
    @location(4) fogPos: vec3f,
) -> @location(0) vec4f {
    let gradientPos = (uniforms.fadeParams.y + elevation) / uniforms.fadeParams.z;
    let t = smoothstep(uniforms.gradientParams.x, uniforms.gradientParams.y, gradientPos);
    let color = mix(uniforms.bottomColor, uniforms.topColor, t);

    // Та же нормаль, что и в polygonExtrusion.frag: cross(dpdy,dpdx) наружу (выверено визуализацией).
    // Производные — до возможного discard (uniform control flow).
    let normal = normalize(cross(dpdy(rotatedScaledPos), dpdx(rotatedScaledPos)));
    let lit = vec4f(color.rgb * lightFactor(normal, fragCoord), color.a);
    if (screendoorDiscard(nearCameraFade, clipPos, fragCoord.xy)) {
        discard;
    }
    // Порт apply_fog из gradient_with_z_fade.fsh
    return applyFog(fog, lit, fogPos);
}
`,PD=`// Текстурированная стена 3D-здания (polygonExtrusion sideTexture): footprint xy + tile-height z,
// поднятые на рельеф (DEM) — как polygonExtrusion.vert. Во фрагмент отдаёт quadFraction (доля угла,
// интерполируется) и wallSize (размер стены в map-points) для раскладки текстуры.

const MAP_POINTS_IN_METER: f32 = 107.17318796639701;
const UNPACK_CENTROID: f32 = 8.0 / 65535.0;
// Маппоинты → tile-z = 1/zScale; сокращается с m[10] модели — см. polygonExtrusion.vert
const VERTICAL_SCALE: f32 = (32768.0 / 65535.0) / 1048576.0;

struct Uniforms {
    mvpMatrix: mat4x4f,
    wallPadding: vec4f,
    texturePadding: vec4f,
    partCountInterval: vec4f,
    sliceSizeMode: vec4f,
    // footprint → текстура высот; demParams = (demScale, centerElevation, heightFactor, floorElevation)
    demTexMvp: mat4x4f,
    demParams: vec4f,
    // x = near-camera fade distance (clip-z; 0 — выключено), y = XY-масштаб модели тайла
    fadeParams: vec4f,
    // xyz = (тайл − камера)/fogDistance, w = 1/fogDistance; нули = туман выключен
    fogOrigin: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
// group 1 — текстура стены (см. фрагмент); group 2 — текстура высот рельефа
@group(2) @binding(0) var demTex: texture_2d<f32>;
@group(2) @binding(1) var demSampler: sampler;

struct VertexOutput {
    @builtin(position) position: vec4f,
    @location(0) quadFraction: vec2f,
    @location(1) wallSize: vec2f,
    @location(2) clipPos: vec4f,
    @location(3) nearCameraFade: f32,
    // Порт v_fog_pos: (world_pos − cam_pos)/fog_distance
    @location(4) fogPos: vec3f,
};

fn demHeight(coords: vec2f) -> f32 {
    let demScale = uniforms.demParams.x;
    if (demScale == 0.0) {
        return 0.0;
    }
    let texPos = (uniforms.demTexMvp * vec4f(coords, 0.0, 1.0)).xy;
    let elevation = textureSampleLevel(demTex, demSampler, vec2f(texPos.x, 1.0 - texPos.y), 0.0);
    // Порт dem_height_direct_meters: без данных рельефа — 0 м (уровень моря), как в WebGL
    var meters = elevation.r;
    if (elevation.a < 1.0) {
        meters = 0.0;
    }
    return (meters - uniforms.demParams.y) * MAP_POINTS_IN_METER * VERTICAL_SCALE * demScale;
}

@vertex
fn main(
    @location(0) pos: vec2f,
    @location(1) z: f32,
    @location(2) quadFraction: vec2u,
    @location(3) wallSize: vec2f,
    @location(4) demPos: vec2i,
) -> VertexOutput {
    let heightFactor = uniforms.demParams.z;
    let floorElevation = uniforms.demParams.w;

    var base = demHeight(vec2f(demPos) * UNPACK_CENTROID);
    if (z == 0.0) {
        let posTerrain = demHeight(pos);
        if (base > posTerrain) {
            base = posTerrain;
        }
    }
    base = base + floorElevation;

    var finalZ = z * heightFactor + base;
    finalZ = max(finalZ, base);

    var out: VertexOutput;
    out.position = uniforms.mvpMatrix * vec4f(pos, finalZ, 1.0);
    out.quadFraction = vec2f(quadFraction);
    out.wallSize = wallSize;
    out.clipPos = out.position;
    out.nearCameraFade = uniforms.fadeParams.x;
    // Порт calc_fog_pos: xy в маппоинтах через масштаб модели (fadeParams.y),
    // z — нормализованный tile-z → маппоинты (1/VERTICAL_SCALE)
    out.fogPos = uniforms.fogOrigin.xyz +
        vec3f(pos * uniforms.fadeParams.y, finalZ / VERTICAL_SCALE) * uniforms.fogOrigin.w;
    return out;
}
`,ID=`// Фрагмент текстурированной стены: раскладка текстуры окна/фасада по стене + сэмпл + премультипликация.
// Порт wall_texture.fsh (layout_image): три режима раскладки по каждой оси — STRETCH, REPEAT_WITH_STRETCH,
// REPEAT_WITH_MAX_INTERVAL — плюс паддинги стены/текстуры. GLSL out-параметры свёрнуты в структуры.
// Опущено относительно WebGL: свет/тень/нормаль (их вывод там не используется), туман, трилинейные
// мипы (textureGrad) — у Sunda пока один мип, поэтому обычный textureSample. Премультипликация здесь:
// текстура залита straight-alpha (writeTexture), блендинг прохода — premultiplied-over.

struct Uniforms {
    mvpMatrix: mat4x4f,
    // паддинги стены [L,T,R,B] в map-points
    wallPadding: vec4f,
    // паддинги текстуры [L,T,R,B], нормализованные к размеру текстуры
    texturePadding: vec4f,
    // (partCount.x, partCount.y, maxInterval.x, maxInterval.y)
    partCountInterval: vec4f,
    // (sliceSize.x, sliceSize.y, layoutMode.x, layoutMode.y); режим как f32 (1/2/3)
    sliceSizeMode: vec4f,
    // подъём на рельеф — используются вершинным шейдером, фрагменту не нужны (паритет структуры)
    demTexMvp: mat4x4f,
    demParams: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
// FogBlock — chunk fog.wgsl
@group(0) @binding(1) var<uniform> fog: FogBlock;
@group(1) @binding(0) var wallSampler: sampler;
@group(1) @binding(1) var wallTexture: texture_2d<f32>;

// Режимы раскладки (общие для обеих осей): 1 repeat-with-stretch, 2 stretch/stripe-top,
// 3 repeat-with-max-interval (см. textureModeToInt + #define в wall_texture.fsh).
const MODE_REPEAT_WITH_STRETCH: i32 = 1;
const MODE_STRETCH: i32 = 2;
const MODE_REPEAT_WITH_MAX_INTERVAL: i32 = 3;

// Результат раскладки одной оси: годен ли фрагмент (ok), текстурная координата (tc),
// итоговый размер сегмента (finalSlice — масштаб производных для мипов; здесь не используется).
struct AxisResult {
    ok: bool,
    tc: f32,
    finalSlice: f32,
}

struct LayoutResult {
    ok: bool,
    tc: vec2f,
    finalSlice: vec2f,
}

// GLSL mod(x,y) = x - y*floor(x/y) (отличается от WGSL '%' по знаку — нужен точный порт).
fn glslMod(x: f32, y: f32) -> f32 {
    return x - y * floor(x / y);
}

fn layoutStretch(currPoint: f32, wallSize: f32) -> AxisResult {
    return AxisResult(true, currPoint / wallSize, wallSize);
}

fn layoutRepeatWithStretch(
    currPoint: f32,
    wallSize: f32,
    sliceSize: f32,
    sliceCount: f32,
) -> AxisResult {
    let rawSliceRepeats = wallSize / sliceSize;
    let repeatedSliceCount = round(rawSliceRepeats * sliceCount);
    let roundedImageRepeats = repeatedSliceCount / sliceCount;
    let finalSlice = sliceSize * (repeatedSliceCount / rawSliceRepeats);

    // Целое число текстур по центру, по краям — кусочки
    let leftoverPartCount = i32(glslMod(repeatedSliceCount, sliceCount));
    let startImageTc = (sliceCount - f32((leftoverPartCount + 1) / 2)) / sliceCount;
    let tc = mix(startImageTc, startImageTc + roundedImageRepeats, currPoint / wallSize);
    return AxisResult(true, tc, finalSlice);
}

fn layoutRepeatWithMaxInterval(
    currPoint: f32,
    wallSize: f32,
    sliceSize: f32,
    maxInterval: f32,
) -> AxisResult {
    let rawBlockRepeats = (wallSize - sliceSize) / (sliceSize + maxInterval);
    let intervalCount = ceil(rawBlockRepeats);
    let windowCount = intervalCount + 1.0;
    let intervalSize = (wallSize - (windowCount * sliceSize)) / intervalCount;

    // Не помещается вторая на полном интервале — одна текстура по центру
    if (rawBlockRepeats < 1.0) {
        let tc = (currPoint - (wallSize - sliceSize) * 0.5) / sliceSize;
        return AxisResult(tc >= 0.0 && tc <= 1.0, tc, sliceSize);
    }
    // Первая текстура
    if (currPoint < sliceSize) {
        return AxisResult(true, currPoint / sliceSize, sliceSize);
    }
    let blockSize = sliceSize + intervalSize;
    let blockCoverage = fract((currPoint - sliceSize) / blockSize);
    // Текстура или интервал (в интервале фрагмент отбрасывается → прозрачный зазор между окнами)
    let tc = (blockCoverage * blockSize - intervalSize) / sliceSize;
    return AxisResult(blockCoverage * blockSize >= intervalSize, tc, sliceSize);
}

fn layoutAxis(
    currPoint: f32,
    wallSize: f32,
    mode: i32,
    sliceSize: f32,
    partCount: f32,
    maxInterval: f32,
) -> AxisResult {
    if (mode == MODE_STRETCH) {
        return layoutStretch(currPoint, wallSize);
    }
    if (mode == MODE_REPEAT_WITH_STRETCH) {
        return layoutRepeatWithStretch(currPoint, wallSize, sliceSize, partCount);
    }
    if (mode == MODE_REPEAT_WITH_MAX_INTERVAL) {
        return layoutRepeatWithMaxInterval(currPoint, wallSize, sliceSize, maxInterval);
    }
    return AxisResult(false, 0.0, sliceSize);
}

fn layoutInternal(currPoint: vec2f, wallSize: vec2f) -> LayoutResult {
    let sliceSize = uniforms.sliceSizeMode.xy;
    let partCount = uniforms.partCountInterval.xy;
    let maxInterval = uniforms.partCountInterval.zw;
    let modeH = i32(uniforms.sliceSizeMode.z);
    let modeV = i32(uniforms.sliceSizeMode.w);

    let v = layoutAxis(currPoint.y, wallSize.y, modeV, sliceSize.y, partCount.y, maxInterval.y);
    if (!v.ok) {
        return LayoutResult(false, vec2f(0.0), vec2f(0.0));
    }
    let h = layoutAxis(currPoint.x, wallSize.x, modeH, sliceSize.x, partCount.x, maxInterval.x);
    if (!h.ok) {
        return LayoutResult(false, vec2f(0.0), vec2f(0.0));
    }
    return LayoutResult(true, vec2f(h.tc, v.tc), vec2f(h.finalSlice, v.finalSlice));
}

fn layoutImage(quadFraction: vec2f, wallSize: vec2f) -> LayoutResult {
    // clamp доли квада до 0..1 (quad overdraw может дать отрицательные барицентрики)
    let currPoint = clamp(quadFraction, vec2f(0.0), vec2f(1.0)) * wallSize;
    let wp = uniforms.wallPadding; // L,T,R,B
    let tp = uniforms.texturePadding; // L,T,R,B

    // Скобки обязательны: голые '<' ... '>' с запятыми WGSL парсит как template-список (vec4<...>).
    let isPad = vec4<bool>(
        (currPoint.x < wp.x),
        (currPoint.y < wp.y),
        (currPoint.x > (wallSize.x - wp.z)),
        (currPoint.y > (wallSize.y - wp.w)),
    );

    if (any(isPad)) {
        let leftTopOffset = currPoint / wp.xy;
        let rightBottomOffset = (currPoint - wallSize + wp.zw) / wp.zw;
        let leftTopUv = leftTopOffset * tp.xy;
        let rightBottomUv = (vec2f(1.0) - tp.zw) + rightBottomOffset * tp.zw;

        // При попадании сразу в вертикальное и горизонтальное поле — считаем горизонтальным
        var tc: vec2f;
        if (isPad.x) {
            tc = vec2f(leftTopUv.x, quadFraction.y);
        } else if (isPad.z) {
            tc = vec2f(rightBottomUv.x, quadFraction.y);
        } else if (isPad.y) {
            tc = vec2f(quadFraction.x, leftTopUv.y);
        } else {
            tc = vec2f(quadFraction.x, rightBottomUv.y);
        }
        return LayoutResult(true, tc, vec2f(99999.0));
    }

    // Не на полях — центральная область
    let currCenter = currPoint - wp.xy;
    let wallCenter = wallSize - wp.xy - wp.zw;
    var res = layoutInternal(currCenter, wallCenter);
    if (res.ok) {
        let denom = vec2f(1.0) - tp.xy - tp.zw;
        res.tc = fract(res.tc) * denom + tp.xy;
        res.finalSlice = res.finalSlice / denom;
    }
    return res;
}

@fragment
fn main(
    @builtin(position) fragCoord: vec4f,
    @location(0) quadFraction: vec2f,
    @location(1) wallSize: vec2f,
    @location(2) clipPos: vec4f,
    @location(3) nearCameraFade: f32,
    @location(4) fogPos: vec3f,
) -> @location(0) vec4f {
    let result = layoutImage(quadFraction, wallSize);

    // V не инвертируем: quad_fraction.y и сэмплинг текстуры совпадают по ориентации с WebGL
    // (выверено визуально — инверсия давала перевёрнутую текстуру). Сэмпл — до discard (uniform flow).
    let moduloCoords = fract(result.tc);
    let texel = textureSample(wallTexture, wallSampler, moduloCoords);

    if (!result.ok || screendoorDiscard(nearCameraFade, clipPos, fragCoord.xy)) {
        discard;
    }
    // Порт apply_fog из wall_texture.fsh
    return applyFog(fog, vec4f(texel.rgb * texel.a, texel.a), fogPos);
}
`,MD=`// Depth-prepass 3D-здания (polygonExtrusion): только позиция + near-camera screendoor, без цвета и
// нормали. Позиционная математика — ТОЧНАЯ копия polygonExtrusion.vert (тот же mvp + DEM-lift), чтобы
// глубина совпала с цветовым проходом (depthCompare equal). Отдельный depth-only шейдер избавляет
// prepass от лишнего innerColor-атрибута и фрагментного освещения. См. polygonExtrusion.vert.

// Маппоинтов в одном метре веб-меркатора (include/dem.vsh)
const MAP_POINTS_IN_METER: f32 = 107.17318796639701;
// Распаковка demPosition (центроид): pos * 8 / 65535 (UNPACK_CENTROID из include/dem.vsh)
const UNPACK_CENTROID: f32 = 8.0 / 65535.0;
// Маппоинты → tile-z = 1 / zScale (сокращается с m[10] модели), см. polygonExtrusion.vert
const VERTICAL_SCALE: f32 = (32768.0 / 65535.0) / 1048576.0;

struct Uniforms {
    // Камера × модель тайла (с Z-remap под WebGPU)
    mvpMatrix: mat4x4f,
    // Модель тайла (depth-проходу не нужна, но layout общий с цветовым)
    modelMatrix: mat4x4f,
    color: vec4f,
    _pad0: vec4f,
    _pad1: vec4f,
    // footprint (tile-координаты) → текстура высот рельефа
    demTexMvp: mat4x4f,
    // x = demScale (0 при выключенном рельефе), y = centerElevation (м), z = heightFactor, w = floorElevation
    demParams: vec4f,
    // x = near-camera fade distance (clip-z); 0 — выключено
    fadeParams: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(1) @binding(0) var demTex: texture_2d<f32>;
@group(1) @binding(1) var demSampler: sampler;

struct VertexOutput {
    @builtin(position) position: vec4f,
    // Клип-позиция (для near-camera screendoor) + дистанция фейда (константа на дроу)
    @location(0) clipPos: vec4f,
    @location(1) nearCameraFade: f32,
};

// Высота рельефа в tile-z по тайловым координатам (порт dem_height). Идентична polygonExtrusion.vert.
fn demHeight(coords: vec2f) -> f32 {
    let demScale = uniforms.demParams.x;
    if (demScale == 0.0) {
        return 0.0;
    }
    let texPos = (uniforms.demTexMvp * vec4f(coords, 0.0, 1.0)).xy;
    let elevation = textureSampleLevel(demTex, demSampler, vec2f(texPos.x, 1.0 - texPos.y), 0.0);
    // Порт dem_height_direct_meters: без данных рельефа — 0 м (уровень моря), как в WebGL
    var meters = elevation.r;
    if (elevation.a < 1.0) {
        meters = 0.0;
    }
    return (meters - uniforms.demParams.y) * MAP_POINTS_IN_METER * VERTICAL_SCALE * demScale;
}

@vertex
fn main(
    @location(0) pos: vec2f,
    @location(1) z: f32,
    @location(3) demPos: vec2i,
) -> VertexOutput {
    let heightFactor = uniforms.demParams.z;
    let floorElevation = uniforms.demParams.w;
    let isHole = uniforms._pad1.z;

    // Основание — по центроиду здания (один сэмпл на всё здание, чтобы оно не рвалось на склоне).
    var base = demHeight(vec2f(demPos) * UNPACK_CENTROID);
    if (z == 0.0) {
        let posTerrain = demHeight(pos);
        if (isHole > 0.5 || base > posTerrain) {
            base = posTerrain;
        }
    }
    base = base + floorElevation;

    var finalZ = z * heightFactor + base;
    if (isHole < 0.5) {
        finalZ = max(finalZ, base);
    }

    let local = vec4f(pos, finalZ, 1.0);

    var out: VertexOutput;
    out.position = uniforms.mvpMatrix * local;
    out.clipPos = out.position;
    out.nearCameraFade = uniforms.fadeParams.x;
    return out;
}
`,_D=`// Depth-prepass фрагмент 3D-зданий: цвет замаскирован (writeMask 0), пишется только depth.
// Сохраняет near-camera screendoor (порт apply_screendoor), чтобы выброшенные фрагменты совпали с
// цветовым проходом и depth-«дырки» были одинаковыми. screendoorDiscard идентичен polygonExtrusion.frag.

@fragment
fn main(
    @builtin(position) fragCoord: vec4f,
    @location(0) clipPos: vec4f,
    @location(1) nearCameraFade: f32,
) -> @location(0) vec4f {
    if (screendoorDiscard(nearCameraFade, clipPos, fragCoord.xy)) {
        discard;
    }
    // Цвет замаскирован (writeMask 0) — значение не используется, важен лишь записанный depth.
    return vec4f(0.0);
}
`,ks=`// Near-camera screendoor (порт apply_screendoor): ближние к камере фрагменты выбрасываются по
// дизер-паттерну (interleaved gradient noise), чтобы близкие здания «просвечивали». Чистая функция
// без биндингов — общий чанк для всех extrusion-фрагментов (склейка в shaderFactory/webgpu.ts
// через withChunks; чанк идёт первым, поэтому объявлен до вызова в main).
fn screendoorDiscard(nearCameraFade: f32, clipPos: vec4f, fragCoord: vec2f) -> bool {
    if (nearCameraFade <= 0.0) {
        return false;
    }
    // WebGL-клип-z из WebGPU-ремапнутого: z(GL) = 2*z' - w (composeExtrusion: z' = z*0.5 + w*0.5)
    let webglClipZ = 2.0 * clipPos.z - clipPos.w;
    let factor = smoothstep(0.0, nearCameraFade, webglClipZ);
    let m = vec3f(0.06711056, 0.00583715, 52.9829189);
    let pattern = fract(m.z * fract(dot(fragCoord, m.xy)));
    return factor - pattern <= 0.0;
}
`,CD=`// Инстансная отрисовка glTF-примитива (порт gltf_model.vsh; все режимы привязки к рельефу
// u_int_gltf_dem_pos: instance/flat/axis/centroid/polygon-anchor). Геометрия меша — slot 0,
// инстансные атрибуты тайла — slot 1.
// PBR/анимации — позже; baseColor-текстура (uv) пробрасывается, но во фрагменте Phase 1 не сэмплится.
//
// Соглашение координат (порт u_mat4_instance из instanced.ts): instanceMatrix переводит метры
// модели → маппоинты; XY возвращаем в нормализованные тайл-координаты (× invTileScaleXY), Z держим
// в маппоинтах — модель тайла Sunda имеет Z-scale 1 (см. TileMatrix.fillModel).

// Маппоинтов в одном метре веб-меркатора (include/dem.vsh)
const MAP_POINTS_IN_METER: f32 = 107.17318796639701;

struct Uniforms {
    // Камера × модель тайла (с Z-remap под WebGPU)
    mvpMatrix: mat4x4f,
    // demTextureMatrix × модель тайла — тайловые координаты → текстура рельефа
    demTexMvpMatrix: mat4x4f,
    // baseColorFactor (premultiplied RGBA)
    color: vec4f,
    // x = demScale (0 при выключенном рельефе), y = высота центра карты (м),
    // z = invTileScaleXY (маппоинты→норм. тайл XY), w = heightUnFactor (норм.→маппоинты Z)
    params: vec4f,
    // x = metallic, y = roughness, z = lightingModel (1 Phong / 2 PBR),
    // w = nearCameraFade (clip-z дистанция screendoor'а, 0 = выключен)
    params2: vec4f,
    // (трансляция тайла − камера) в маппоинтах: позиция фрагмента относительно камеры (view-вектор)
    camOriginRel: vec4f,
    // Свет слоя (per-draw, порт per-layer lb.light); в vertex не используется
    lightDir1: vec4f,
    lightColor1: vec4f,
    lightAmbient: vec4f,
    // Привязка к рельефу (порт u_int_gltf_dem_pos): x — режим GltfDemPosition
    // (0 instance, 1 flat, 2 axis, 3 centroid, 4 polygon-anchor),
    // y — битмаска GltfModelFlags (abs_z/фундамент/surface-override),
    // z — surfaceRelZ (маппоинты), w — surfaceAbsZ (маппоинты)
    demPosParams: vec4f,
    // Якорь: centroid в model-координатах (запечён localMatrix, режим 3) либо
    // нормализованные тайловые координаты якоря полигона (xy, режим 4)
    demAnchor: vec4f,
    // Ось (режим 2): концы в model-координатах, запечённые localMatrix
    demAxisStart: vec4f,
    demAxisEnd: vec4f,
    // x = есть metallicRoughness-текстура (фрагментная стадия),
    // yzw = зум-зависимый стилевой scale (порт u_vec3_scale_factor)
    texFlags: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(1) @binding(0) var demTex: texture_2d<f32>;
@group(1) @binding(1) var demSampler: sampler;

// Битовая маска GltfModelFlags (frameLayout.ts); IndexU32 (1) шейдеру безразличен
const FLAG_USE_ABS_Z: u32 = 2u;
const FLAG_EXT_TO_RELIEF: u32 = 4u;
const FLAG_COLLAPSE_HEIGHT: u32 = 8u;
const FLAG_RELIEF_FOUNDATION: u32 = 16u;
const FLAG_SURFACE_USE_ABS_Z: u32 = 32u;

// Пороги «вершина — основание модели» (порт EPSILON/EPSILON2 gltf_model.vsh,
// но в маппоинтах: Z Sunda-модели тайла в маппоинтах, не в tile-z)
const BASE_EPS_MP: f32 = 0.01;

struct VertexOutput {
    @builtin(position) position: vec4f,
    @location(0) normal: vec3f,
    @location(1) uv: vec2f,
    // Позиция фрагмента относительно камеры (маппоинты) для view-вектора PBR/Phong
    @location(2) viewPos: vec3f,
    // Clip-space позиция для near-camera screendoor'а (порт v_clipspace_pos)
    @location(3) clipPos: vec4f,
    // UV текстур AO и metallicRoughness (свои texCoord-каналы)
    @location(4) uvAo: vec2f,
    @location(5) uvPbr: vec2f,
    // id объекта (instance localID) — читает только identify.frag (порт gltfModelIdentify)
    @location(15) @interpolate(flat) identifier: vec4f,
};

// Порт dem_height: высота рельефа в маппоинтах по тайловым координатам [0..1].
fn demHeight(coords: vec2f) -> f32 {
    if (uniforms.params.x == 0.0) {
        return 0.0;
    }

    let texPos = (uniforms.demTexMvpMatrix * vec4f(coords, 0.0, 1.0)).xy;
    // V переворачивается: текстура высот записана матрицами WebGL-конвенции
    let elevation = textureSampleLevel(demTex, demSampler, vec2f(texPos.x, 1.0 - texPos.y), 0.0);
    // Порт dem_height_direct_meters: без данных рельефа — 0 м (уровень моря), как в WebGL
    var meters = elevation.r;
    if (elevation.a < 1.0) {
        meters = 0.0;
    }

    return (meters - uniforms.params.y) * MAP_POINTS_IN_METER * uniforms.params.x;
}

// Порт abs_height: абсолютная высота из данных (маппоинты) → высота относительно
// центра карты. У Sunda vertical_scale = 1 (Z модели тайла в маппоинтах).
fn absHeightMp(heightMp: f32) -> f32 {
    return (heightMp - uniforms.params.y * MAP_POINTS_IN_METER) * uniforms.params.x;
}

@vertex
fn main(
    // slot 0 — геометрия примитива (репак: pos.xyz + normal.xyz + uv.xy)
    @location(0) position: vec3f,
    @location(1) normal: vec3f,
    @location(2) uv: vec2f,
    // slot 1 — инстанс тайла (stride 64). Позиция xyz в unorm16x4 (4-й компонент — паддинг)
    @location(3) instancePosRaw: vec4f,
    @location(4) matCol0: vec3f,
    @location(5) matCol1: vec3f,
    @location(6) matCol2: vec3f,
    @location(7) instanceHeight: f32,
    // Абсолютная высота инстанса из данных, маппоинты (порт a_float_abs_z)
    @location(8) absZ: f32,
    // UV текстур AO / metallicRoughness (слот 0 геометрии)
    @location(9) uvAo: vec2f,
    @location(10) uvPbr: vec2f,
    // slot 1 — id объекта инстанса (порт a_vec4_instance_localid)
    @location(11) identifier: vec4f,
) -> VertexOutput {
    let instanceMatrix = mat3x3f(matCol0, matCol1, matCol2);
    let invTileScaleXY = uniforms.params.z;
    let heightUnFactor = uniforms.params.w;

    // instanceMatrix уже переводит метры модели → маппоинты (статический стилевой scale
    // запечён генератором); зум-зависимый interpolate-scale приезжает юниформой
    // (порт vertex.xyz *= u_vec3_scale_factor). XY возвращаем в нормализованные
    // тайл-координаты (порт u_mat4_instance), т.к. модель тайла (mvp) масштабирует XY на
    // tileSize/uint16ToTileCoords. По Z модель тайла единична — Z держим в маппоинтах.
    // instancePosRaw.xy — нормализованные тайл-координаты.
    let meshMpRaw = instanceMatrix * position;
    let meshMp = meshMpRaw * uniforms.texFlags.yzw;
    let worldXy = vec2f(
        meshMp.x * invTileScaleXY + instancePosRaw.x,
        meshMp.y * invTileScaleXY + instancePosRaw.y,
    );
    // Точка семплинга рельефа (flat/фундамент) — по НЕмасштабированной вершине,
    // как в WebGL (pos без u_vec3_scale_factor)
    let demXy = vec2f(
        meshMpRaw.x * invTileScaleXY + instancePosRaw.x,
        meshMpRaw.y * invTileScaleXY + instancePosRaw.y,
    );

    // Выбор точки сэмплирования рельефа (порт веток u_int_gltf_dem_pos)
    let demPos = u32(uniforms.demPosParams.x + 0.5);
    let flags = u32(uniforms.demPosParams.y + 0.5);
    var ground: f32;
    if ((flags & FLAG_SURFACE_USE_ABS_Z) != 0u) {
        // Surface-override ярусов задаёт базу явно — dem_pos/abs_z не участвуют
        // (порт resolved_surface_uses_abs_z)
        ground = absHeightMp(uniforms.demPosParams.w);
    } else if (demPos == 1u) {
        // flat («намазывание»): высота независимо в каждой вершине
        ground = demHeight(demXy);
    } else if (demPos == 2u) {
        // axis: линейная интерполяция высоты вдоль оси. Коэффициент проекции считаем в
        // запечённых model-координатах (WebGL — в сырых a_position; совпадает при rigid localMatrix)
        let bs = uniforms.demAxisStart.xyz;
        let be = uniforms.demAxisEnd.xyz;
        let bv = be.xz - bs.xz;
        let bl = max(length(bv), 0.000001);
        let coef = clamp(dot((position.xz - bs.xz) / bl, bv / bl), 0.0, 1.0);
        let ws = instanceMatrix * bs;
        let we = instanceMatrix * be;
        let hs = demHeight(ws.xy * invTileScaleXY + instancePosRaw.xy);
        let he = demHeight(we.xy * invTileScaleXY + instancePosRaw.xy);
        ground = mix(hs, he, coef);
    } else if (demPos == 3u) {
        // centroid: высота в запечённом центроиде модели
        let c = instanceMatrix * uniforms.demAnchor.xyz;
        ground = demHeight(c.xy * invTileScaleXY + instancePosRaw.xy);
    } else if (demPos == 4u) {
        // polygon-anchor: якорь уже в нормализованных тайловых координатах
        ground = demHeight(uniforms.demAnchor.xy);
    } else if ((flags & FLAG_USE_ABS_Z) != 0u) {
        // instance с абсолютной высотой из данных (порт u_int_abs_z == 1)
        ground = absHeightMp(absZ);
    } else {
        // instance (дефолт): точка привязки инстанса
        ground = demHeight(instancePosRaw.xy);
    }
    // relativeZ поверхности добавляется к любой базе (порт add_resolved_surface_relative_height)
    ground += uniforms.demPosParams.z;

    var meshZ = meshMp.z;
    // Дотяжка фундамента: нижние вершины (z < 0) опускаем на разницу между локальным
    // рельефом и базой — только вниз (порт u_int_is_extendable_to_relief_foundation)
    if ((flags & FLAG_RELIEF_FOUNDATION) != 0u && meshZ < -BASE_EPS_MP) {
        let localRelief = demHeight(demXy);
        meshZ += min(localRelief - ground, 0.0);
    }
    if ((flags & FLAG_USE_ABS_Z) != 0u) {
        if (meshZ < BASE_EPS_MP) {
            // Основание при abs_z: дотяжка до рельефа — опускаем на разницу
            // абсолютной высоты и рельефа (порт u_int_extention_to_relief_needed)
            if ((flags & FLAG_EXT_TO_RELIEF) != 0u) {
                meshZ -= absHeightMp(absZ) - demHeight(instancePosRaw.xy);
            }
        } else if ((flags & FLAG_COLLAPSE_HEIGHT) != 0u) {
            // Схлопывание физической высоты модели (порт u_int_collapse_height_needed)
            meshZ = 0.0;
        }
    }

    var world: vec3f;
    world.x = worldXy.x;
    world.y = worldXy.y;
    world.z = meshZ + instanceHeight * heightUnFactor + ground;

    var out: VertexOutput;
    out.position = uniforms.mvpMatrix * vec4f(world, 1.0);
    // Нормаль вращает только инстанс (модель тайла — scale/translate без вращения)
    out.normal = normalize(instanceMatrix * normal);
    out.uv = uv;
    // Позиция фрагмента в маппоинтах относительно камеры: model·world − camera. vp-пространство ==
    // маппоинты (scale = 1/invTileScaleXY), camOriginRel = трансляция тайла − камера (origin-relative).
    let scale = 1.0 / invTileScaleXY;
    out.viewPos = vec3f(
        scale * world.x + uniforms.camOriginRel.x,
        scale * world.y + uniforms.camOriginRel.y,
        world.z + uniforms.camOriginRel.z,
    );
    out.clipPos = out.position;
    out.uvAo = uvAo;
    out.uvPbr = uvPbr;
    out.identifier = identifier;
    return out;
}
`,FD=`// glTF: baseColorFactor × baseColor-текстура × AO-текстура × PBR/Phong-освещение (порт
// light_phong.fsh / light_pbr.fsh; metallicRoughness-текстура — каналы g/b). Только dir1
// (солнце) + ambient — без dir2 (паритет с WebGL glTF). Тень — chunk shadow.wgsl.

const PI: f32 = 3.14159265359;

struct Uniforms {
    mvpMatrix: mat4x4f,
    demTexMvpMatrix: mat4x4f,
    // baseColorFactor (premultiplied RGBA)
    color: vec4f,
    params: vec4f,
    // x = metallic, y = roughness, z = lightingModel (1 = Phong, 2 = PBR),
    // w = nearCameraFade (clip-z дистанция screendoor'а, 0 = выключен)
    params2: vec4f,
    // (трансляция тайла − камера) в маппоинтах; viewPos фрагмента считает вершина
    camOriginRel: vec4f,
    // Свет слоя модели (per-draw, порт per-layer lb.light: layer.lightingMode ??
    // defaultLightMode). glTF использует только dir1 + ambient (как WebGL light_phong/pbr).
    // lightDir1: xyz — направление, w — свет включён (0/1); lightColor1/lightAmbient: rgb + интенсивность.
    lightDir1: vec4f,
    lightColor1: vec4f,
    lightAmbient: vec4f,
    // Привязка к рельефу + флаги abs_z/фундамента/surface (vertex-стадия);
    // во фрагменте не используется
    demPosParams: vec4f,
    demAnchor: vec4f,
    demAxisStart: vec4f,
    demAxisEnd: vec4f,
    // x = есть metallicRoughness-текстура (roughness/metallic из каналов g/b),
    // yzw = зум-зависимый стилевой scale (vertex-стадия)
    texFlags: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
// FogBlock — chunk fog.wgsl
@group(0) @binding(1) var<uniform> fog: FogBlock;
// Тени кадра — chunk shadow.wgsl (ShadowBlock + карта теней + comparison-сэмплер)
@group(0) @binding(2) var<uniform> shadow: ShadowBlock;
@group(0) @binding(3) var shadowTex: texture_depth_2d;
@group(0) @binding(4) var shadowSampler: sampler_comparison;
// Текстуры материала (белая заглушка 1×1, если текстуры нет): baseColor (sample == 1),
// AO (множитель 1), metallicRoughness (гейтится texFlags.x — заглушка не применяется)
@group(2) @binding(0) var colorTex: texture_2d<f32>;
@group(2) @binding(1) var colorSampler: sampler;
@group(2) @binding(2) var aoTex: texture_2d<f32>;
@group(2) @binding(3) var pbrTex: texture_2d<f32>;

// ── Phong (дефолтная модель glTF, порт light_phong.fsh) ───────────────────────
// albedo·(ambient + diffuse) + спекуляр. Только dir1. specular_strength = metallic,
// specular_power = roughness·(2−32)+32. viewDir смотрит из фрагмента в камеру.
fn colorPhong(
    fragCoord: vec4f,
    normal: vec3f,
    viewDir: vec3f,
    albedo: vec3f,
    roughness: f32,
    metallic: f32,
    alpha: f32,
) -> vec3f {
    let specularStrength = metallic;
    let specularPower = roughness * (2.0 - 32.0) + 32.0;

    let ambient = uniforms.lightAmbient.rgb * uniforms.lightAmbient.a;
    let diff = max(dot(normal, -uniforms.lightDir1.xyz), 0.0);
    // Тень гасит диффуз и блик (порт light_phong.fsh)
    let sf = shadowFactor(fragCoord);
    let diffuse = uniforms.lightColor1.rgb * uniforms.lightColor1.a * diff * sf;

    let reflectDir = reflect(uniforms.lightDir1.xyz, normal);
    let spec = pow(max(dot(viewDir, reflectDir), 0.0), specularPower);
    // ×alpha — ослабляем блик для premultiplied-alpha (прозрачных) цветов
    let specular = uniforms.lightColor1.rgb * uniforms.lightColor1.a * spec * specularStrength * sf * alpha;

    return albedo * (ambient + diffuse) + specular;
}

// ── PBR (порт light_pbr.fsh, Cook-Torrance metallic-roughness) ────────────────
// GGX/Trowbridge-Reitz NDF
fn distributionGgx(alpha: f32, n: vec3f, h: vec3f) -> f32 {
    let a2 = alpha * alpha;
    let nDotH = max(dot(n, h), 0.0);
    let denom = PI * pow(nDotH * nDotH * (a2 - 1.0) + 1.0, 2.0);
    return a2 / max(denom, 0.000001);
}

// Schlick-Beckmann geometry shadowing
fn geometrySchlick(alpha: f32, n: vec3f, x: vec3f) -> f32 {
    let nDotX = max(dot(n, x), 0.0);
    let k = alpha / 2.0;
    return nDotX / max(nDotX * (1.0 - k) + k, 0.000001);
}

// Smith model
fn geometrySmith(alpha: f32, n: vec3f, v: vec3f, l: vec3f) -> f32 {
    return geometrySchlick(alpha, n, v) * geometrySchlick(alpha, n, l);
}

// Fresnel-Schlick
fn fresnelSchlick(f0: vec3f, v: vec3f, h: vec3f) -> vec3f {
    return f0 + (vec3f(1.0) - f0) * pow(1.0 - max(dot(v, h), 0.0), 5.0);
}

fn colorPbr(
    fragCoord: vec4f,
    normal: vec3f,
    viewDir: vec3f,
    albedo: vec3f,
    roughness: f32,
    metallic: f32,
) -> vec3f {
    let alpha = roughness * roughness;
    let f0 = mix(vec3f(0.04), vec3f(1.0), metallic);

    let n = normal;
    let v = viewDir;
    let l = -uniforms.lightDir1.xyz;
    let h = normalize(v + l);

    let ks = fresnelSchlick(f0, v, h);
    let kd = (vec3f(1.0) - ks) * (1.0 - metallic);

    let lambert = albedo / PI;
    let ctNum = distributionGgx(alpha, n, h) * geometrySmith(alpha, n, v, l) * ks;
    let ctDen = max(4.0 * max(dot(v, n), 0.0) * max(dot(l, n), 0.0), 0.000001);
    let cookTorrance = ctNum / ctDen;

    let brdf = kd * lambert + cookTorrance;
    let outgoing = brdf * uniforms.lightColor1.rgb * uniforms.lightColor1.a * max(dot(l, n), 0.0);
    let ambient = uniforms.lightAmbient.rgb * uniforms.lightAmbient.a * albedo;
    // Порт light_pbr.fsh: тень гасит только прямой свет
    return ambient + outgoing * shadowFactor(fragCoord);
}

@fragment
fn main(
    @builtin(position) fragCoord: vec4f,
    @location(0) normal: vec3f,
    @location(1) uv: vec2f,
    @location(2) viewPos: vec3f,
    @location(3) clipPos: vec4f,
    @location(4) uvAo: vec2f,
    @location(5) uvPbr: vec2f,
) -> @location(0) vec4f {
    let n = normalize(normal);
    // color = baseColorFactor (premult) × baseColor-текстура (straight alpha)
    // × AO-текстура (порт AO_TEXTURE: color *= ao_tex_color; без текстуры sample == 1)
    let color = uniforms.color *
        textureSample(colorTex, colorSampler, uv) *
        textureSample(aoTex, colorSampler, uvAo);
    // metallicRoughness-текстура (порт PBR_TEXTURE): roughness = g, metallic = b
    let pbrSample = textureSample(pbrTex, colorSampler, uvPbr);

    // Near-camera screendoor (порт apply_screendoor gltf_model.fsh) — после сэмплинга
    // (uniform control flow), общий чанк с extrusion-пассами
    if (screendoorDiscard(uniforms.params2.w, clipPos, fragCoord.xy)) {
        discard;
    }

    // Порт v_fog_pos: viewPos = фрагмент − камера (маппоинты), camOriginRel.w = 1/fogDistance
    let fogPos = viewPos * uniforms.camOriginRel.w;

    // Слой игнорирует освещение (lightDir1.w < 0.5) → плоский цвет
    if (uniforms.lightDir1.w < 0.5) {
        // Порт apply_fog из gltf_model.fsh
        return applyFog(fog, color, fogPos);
    }

    // viewDir — из фрагмента в камеру. viewPos = фрагмент − камера (вершина), поэтому −viewPos.
    let viewDir = normalize(-viewPos);
    // WebGL поднимает металличность/шероховатость до 0.1 (иначе артефакты)
    var metallic = max(uniforms.params2.x, 0.1);
    var roughness = max(uniforms.params2.y, 0.1);
    if (uniforms.texFlags.x > 0.5) {
        roughness = max(pbrSample.g, 0.1);
        metallic = max(pbrSample.b, 0.1);
    }

    var rgb: vec3f;
    if (uniforms.params2.z > 1.5) {
        rgb = colorPbr(fragCoord, n, viewDir, color.rgb, roughness, metallic);
    } else {
        rgb = colorPhong(fragCoord, n, viewDir, color.rgb, roughness, metallic, color.a);
    }
    // Порт apply_fog из gltf_model.fsh
    return applyFog(fog, vec4f(rgb, color.a), fogPos);
}
`,LD=`// Небо (порт sky.vsh): полноэкранный квад на дальней плоскости (z = 1).
// Направление луча восстанавливается из clip-позиции (порт calc_fog_pos_sky):
// fogPos = mat3(viewTransposed) × (projInverted × clipPos).xyz.

struct SkyUniforms {
    viewTransposed: mat4x4f,
    projInverted: mat4x4f,
    // x = horizonPad (порт u_fog_horizon_pad); yzw — резерв
    params: vec4f,
};

@group(0) @binding(0) var<uniform> sky: SkyUniforms;

struct VertexOutput {
    @builtin(position) position: vec4f,
    // Порт v_fog_pos (SKY-ветка): направление луча в мировых осях
    @location(0) fogPos: vec3f,
};

@vertex
fn main(@location(0) pos: vec2f) -> VertexOutput {
    var out: VertexOutput;
    out.position = vec4f(pos, 1.0, 1.0);
    let unprojected = sky.projInverted * vec4f(pos, 1.0, 1.0);
    let viewRotation = mat3x3f(
        sky.viewTransposed[0].xyz,
        sky.viewTransposed[1].xyz,
        sky.viewTransposed[2].xyz,
    );
    out.fogPos = viewRotation * unprojected.xyz;
    return out;
}
`,BD=`// Небо (порт sky.fsh): цвет неба из FogBlock, прозрачность под горизонтом
// (SKY_ALPHA_HORIZON_BLEND) + примесь тумана у горизонта (applyFogSky).

// Порт SKY_ALPHA_HORIZON_BLEND
const SKY_ALPHA_HORIZON_BLEND: f32 = 6.0;

struct SkyUniforms {
    viewTransposed: mat4x4f,
    projInverted: mat4x4f,
    // x = horizonPad (порт u_fog_horizon_pad)
    params: vec4f,
};

@group(0) @binding(0) var<uniform> sky: SkyUniforms;
// FogBlock — chunk fog.wgsl (skyColor/fogColor/параметры горизонта)
@group(0) @binding(1) var<uniform> fog: FogBlock;

@fragment
fn main(@location(0) fogPos: vec3f) -> @location(0) vec4f {
    // Порт add_sky_alpha_blend: небо прозрачно под горизонтом (граница чуть ниже — horizonPad)
    let depth = length(fogPos);
    let dir = fogPos / max(depth, FOG_EPSILON);
    let alphaDir = dir.z + sky.params.x;
    let alpha = clamp(1.0 + SKY_ALPHA_HORIZON_BLEND * alphaDir, 0.0, 1.0);
    let color = fog.skyColor * alpha;
    return applyFogSky(fog, color, fogPos);
}
`,DD=`// Звёздное небо: точки на единичной сфере, спроецированные ortho-матрицей небесной сферы
// (порт stars.vsh). Интенсивность = per-star opacity × общая яркость (starsIntensity).
struct Uniforms {
    starsMatrix: mat4x4f,
    // x = общая яркость звёзд (starsIntensity); yzw — резерв
    params: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;

struct VertexOutput {
    @builtin(position) position: vec4f,
    @location(0) intensity: f32,
};

@vertex
fn main(@location(0) position: vec3f, @location(1) opacity: f32) -> VertexOutput {
    var out: VertexOutput;
    // Звёзды — фоновый слой без глубины (depthCompare always, depth write off). Ortho-матрица
    // небесной сферы задаёт near/far = [0.001, 1] — z-клип отсекает переднюю полусферу неба
    // (как в WebGL): матрица даёт GL-clip z ∈ [-1, 1], переводим в WebGPU-диапазон [0, 1].
    let p = uniforms.starsMatrix * vec4f(position, 1.0);
    out.position = vec4f(p.x, p.y, p.z * 0.5 + 0.5, 1.0);
    out.intensity = opacity * uniforms.params.x;
    return out;
}
`,OD=`// Звезда: premultiplied белый, альфа = интенсивность (порт stars.fsh: gl_FragColor = vec4(v_intensity)).
// Блендинг прохода — premultiplied-over, поэтому звезда подмешивает белый поверх фона по своей яркости.
@fragment
fn main(@location(0) intensity: f32) -> @location(0) vec4f {
    return vec4f(intensity);
}
`,fx=`// Атмосферное гало глобуса (порт globe_halo.vsh): квад вокруг экранного центра глобуса,
// размер — до внешнего стопа гало с запасом под экспоненциальное затухание. v_uv — позиция
// внутри гало в NDC-радиусах (нормировка на высоту вьюпорта, как у стопов).
struct Uniforms {
    haloColor: vec4f,
    // стопы радиусов в NDC (нормированы на высоту вьюпорта): x=r0, y=r1(радиус сферы), z=r2, w=r3
    radiusStops: vec4f,
    // (ширина, высота, сдвиг центра X, сдвиг центра Y) в пикселях буфера
    viewport: vec4f,
    // x = коэффициент экспоненты затухания; yzw — резерв
    params: vec4f,
    // цвет фона стиля (premultiplied) — подложка глобуса
    backgroundColor: vec4f,
};

@group(0) @binding(0) var<uniform> u: Uniforms;

struct VertexOutput {
    @builtin(position) position: vec4f,
    @location(0) uv: vec2f,
};

@vertex
fn main(@location(0) vertex: vec2f) -> VertexOutput {
    var out: VertexOutput;
    let viewportSize = u.viewport.xy;
    let centerShift = u.viewport.zw;
    let expFactor = u.params.x;

    // Запас геометрии под экспоненту: решаем 1 - exp(expFactor·t) = 0.995 → почти нулевая alpha.
    let paddingFactor = log(0.005) / expFactor;
    let pixelStops = u.radiusStops * viewportSize.y;
    let maxR = pixelStops.y + (pixelStops.w - pixelStops.y) * paddingFactor;

    let scale = maxR / viewportSize.y;
    out.uv = vertex * scale;

    let center = viewportSize / 2.0 + centerShift;
    let p = center - vertex * maxR;
    let pResult = 2.0 * (p - 0.5 * viewportSize) / viewportSize;
    out.position = vec4f(pResult, 0.0, 1.0);
    return out;
}
`,RD=`// Атмосферное гало глобуса (порт globe_halo.fsh): центральный вырез (глобус виден), белая окантовка
// на радиусе сферы и наружный экспоненциальный glow в цвете тумана. Блендинг прохода — аддитивный
// (src-alpha, one): фрагмент ДОБАВЛЯет свечение поверх сцены (прозрачный центр ничего не добавляет).
struct Uniforms {
    haloColor: vec4f,
    radiusStops: vec4f,
    viewport: vec4f,
    params: vec4f,
    backgroundColor: vec4f,
};

@group(0) @binding(0) var<uniform> u: Uniforms;

@fragment
fn main(@location(0) uv: vec2f) -> @location(0) vec4f {
    let dist = length(uv);

    let haloAlpha = u.haloColor.a;
    let haloColor = vec4f(u.haloColor.rgb, 0.0);
    let emptyColor = vec4f(0.0);
    let whiteColor1 = vec4f(1.0, 1.0, 1.0, haloAlpha);
    let whiteColor2 = vec4f(whiteColor1.rgb, haloAlpha * 0.9);

    let r0 = u.radiusStops.x;
    let r1 = u.radiusStops.y;
    let r2 = u.radiusStops.z;
    let r3 = u.radiusStops.w;

    let t0 = max(0.0, (dist - r1) / (r3 - r1));
    let t0e = 1.0 - exp(u.params.x * t0);

    // наружное гало: белый → цвет тумана с экспоненциальным затуханием
    var color = mix(whiteColor2, haloColor, t0e);
    // белая окантовка на радиусе сферы (r1..r2)
    color = mix(whiteColor1, color, smoothstep(r1, r2, dist));
    // центральный вырез (r0..r1) — глобус виден
    color = mix(emptyColor, color, smoothstep(r0, r1, dist));

    return color;
}
`,zD=`// Подложка глобуса (порт globe_halo_background.fsh): диск радиуса сферы (r1 = radiusStops.y),
// залитый цветом фона стиля. Рисуется ДО тайлов — фон просвечивает в суб-пиксельных швах
// и там, где тайлы ещё не доехали. Вершинник общий с гало (globeHalo.vert.wgsl).
struct Uniforms {
    haloColor: vec4f,
    radiusStops: vec4f,
    viewport: vec4f,
    params: vec4f,
    backgroundColor: vec4f,
};

@group(0) @binding(0) var<uniform> u: Uniforms;

@fragment
fn main(@location(0) uv: vec2f) -> @location(0) vec4f {
    if (length(uv) > u.radiusStops.y) {
        discard;
    }
    return u.backgroundColor;
}
`,_c=`// Полноэкранный квад постэффектов (порт posteffect.vsh): triangle-strip из 4 вершин.
// uv — в конвенции WebGL (v = 0 внизу экрана), как в legacy-шейдерах; при сэмплинге
// экранных текстур WebGPU фрагментники флипают v (см. sampleScreen в *.frag).

struct VertexOutput {
    @builtin(position) position: vec4f,
    @location(0) uv: vec2f,
};

@vertex
fn main(@location(0) pos: vec2f) -> VertexOutput {
    var out: VertexOutput;
    out.position = vec4f(pos, 0.0, 1.0);
    out.uv = 0.5 * pos + vec2f(0.5, 0.5);
    return out;
}
`,ND=`// FXAA (порт fxaa.fsh): сглаживание по люме 3×3-окрестности.
// Математика скопирована 1:1; uv — WebGL-конвенция (v вверх), экранная
// текстура WebGPU хранится v-вниз — сэмплинг через flip (sampleScreen).

struct PostUniforms {
    // xy = размер канваса в пикселях, zw = 1/размер
    size: vec4f,
};

@group(0) @binding(0) var<uniform> post: PostUniforms;
@group(0) @binding(1) var colorTexture: texture_2d<f32>;
@group(0) @binding(2) var linearSampler: sampler;

const FXAA_REDUCE_MIN: f32 = 1.0 / 128.0;
const FXAA_REDUCE_MUL: f32 = 1.0 / 8.0;
const FXAA_SPAN_MAX: f32 = 8.0;

fn sampleScreen(uv: vec2f) -> vec4f {
    return textureSampleLevel(colorTexture, linearSampler, vec2f(uv.x, 1.0 - uv.y), 0.0);
}

@fragment
fn main(@location(0) uv: vec2f) -> @location(0) vec4f {
    let resolution = post.size.xy;
    let inverseVP = post.size.zw;
    let fragCoord = uv * resolution;

    let rgbNW = sampleScreen((fragCoord + vec2f(-1.0, -1.0)) * inverseVP).xyz;
    let rgbNE = sampleScreen((fragCoord + vec2f(1.0, -1.0)) * inverseVP).xyz;
    let rgbSW = sampleScreen((fragCoord + vec2f(-1.0, 1.0)) * inverseVP).xyz;
    let rgbSE = sampleScreen((fragCoord + vec2f(1.0, 1.0)) * inverseVP).xyz;
    let texColor = sampleScreen(fragCoord * inverseVP);
    let rgbM = texColor.xyz;

    let luma = vec3f(0.299, 0.587, 0.114);
    let lumaNW = dot(rgbNW, luma);
    let lumaNE = dot(rgbNE, luma);
    let lumaSW = dot(rgbSW, luma);
    let lumaSE = dot(rgbSE, luma);
    let lumaM = dot(rgbM, luma);
    let lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));
    let lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));

    var dir: vec2f;
    dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));
    dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));

    let dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);
    let rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);
    dir = min(vec2f(FXAA_SPAN_MAX), max(vec2f(-FXAA_SPAN_MAX), dir * rcpDirMin)) * inverseVP;

    let rgbA = 0.5 * (
        sampleScreen(fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +
        sampleScreen(fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);
    let rgbB = rgbA * 0.5 + 0.25 * (
        sampleScreen(fragCoord * inverseVP + dir * -0.5).xyz +
        sampleScreen(fragCoord * inverseVP + dir * 0.5).xyz);

    let lumaB = dot(rgbB, luma);
    if (lumaB < lumaMin || lumaB > lumaMax) {
        return vec4f(rgbA, texColor.a);
    }
    return vec4f(rgbB, texColor.a);
}
`,GD=`// SMAA, пасс 1 — edge detection (порт smaa_edge.fsh, ветка SMAA_EDGES_COLOR,
// пресет SMAA_PRESET_ULTRA). Пишет rg-маску рёбер в edge-таргет.
// uv — WebGL-конвенция; экранная текстура сэмплится через flip (sampleScreen).

struct PostUniforms {
    // xy = размер канваса в пикселях, zw = 1/размер
    size: vec4f,
};

@group(0) @binding(0) var<uniform> post: PostUniforms;
@group(0) @binding(1) var colorTexture: texture_2d<f32>;
@group(0) @binding(2) var linearSampler: sampler;

// SMAA_PRESET_ULTRA
const SMAA_THRESHOLD: f32 = 0.05;
const SMAA_LOCAL_CONTRAST_ADAPTATION_FACTOR: f32 = 2.0;

fn sampleScreen(uv: vec2f) -> vec4f {
    return textureSampleLevel(colorTexture, linearSampler, vec2f(uv.x, 1.0 - uv.y), 0.0);
}

fn maxComponent(v: vec3f) -> f32 {
    return max(max(v.r, v.g), v.b);
}

@fragment
fn main(@location(0) uv: vec2f) -> @location(0) vec4f {
    let texelSize = post.size.zw;

    // vOffset[0..2] как в GLSL: сосед слева/сверху, справа/снизу, через один
    let offset0 = vec4f(texelSize, texelSize) * vec4f(-1.0, 0.0, 0.0, -1.0) + uv.xyxy;
    let offset1 = vec4f(texelSize, texelSize) * vec4f(1.0, 0.0, 0.0, 1.0) + uv.xyxy;
    let offset2 = vec4f(texelSize, texelSize) * vec4f(-2.0, 0.0, 0.0, -2.0) + uv.xyxy;

    let threshold = vec2f(SMAA_THRESHOLD);

    var delta: vec4f;
    let c = sampleScreen(uv).rgb;

    let cLeft = sampleScreen(offset0.xy).rgb;
    delta.x = maxComponent(abs(c - cLeft));

    let cTop = sampleScreen(offset0.zw).rgb;
    delta.y = maxComponent(abs(c - cTop));

    var edges = step(threshold, delta.xy);
    if (dot(edges, vec2f(1.0, 1.0)) == 0.0) {
        discard;
    }

    let cRight = sampleScreen(offset1.xy).rgb;
    delta.z = maxComponent(abs(c - cRight));

    let cBottom = sampleScreen(offset1.zw).rgb;
    delta.w = maxComponent(abs(c - cBottom));

    var maxDelta = max(delta.xy, delta.zw);

    let cLeftLeft = sampleScreen(offset2.xy).rgb;
    delta.z = maxComponent(abs(c - cLeftLeft));

    let cTopTop = sampleScreen(offset2.zw).rgb;
    delta.w = maxComponent(abs(c - cTopTop));

    maxDelta = max(maxDelta.xy, delta.zw);
    let finalDelta = max(maxDelta.x, maxDelta.y);

    // Local contrast adaptation
    edges = edges * step(vec2f(finalDelta), SMAA_LOCAL_CONTRAST_ADAPTATION_FACTOR * delta.xy);

    return vec4f(edges, 0.0, 0.0);
}
`,kD=`// SMAA, пасс 2 — blending weights (порт smaa_weight.fsh, пресет ULTRA).
// Вход: edge-таргет (rg-маска рёбер) + LUT-текстуры area (160×560) и search (64×16).
// Математика скопирована 1:1 с WebGL-порта (включая его знаковые правки);
// uv — WebGL-конвенция, экранный edge-таргет сэмплится через flip (sampleEdges),
// LUT — напрямую (ориентация выровнена при загрузке, см. postEffectsPass).

struct PostUniforms {
    // xy = размер канваса в пикселях, zw = 1/размер
    size: vec4f,
};

@group(0) @binding(0) var<uniform> post: PostUniforms;
@group(0) @binding(1) var edgesTexture: texture_2d<f32>;
@group(0) @binding(2) var linearSampler: sampler;
@group(0) @binding(3) var areaTexture: texture_2d<f32>;
@group(0) @binding(4) var searchTexture: texture_2d<f32>;
@group(0) @binding(5) var nearestSampler: sampler;

// SMAA_PRESET_ULTRA (как в smaa_edge.fsh legacy: единый пресет обоих пассов)
const SMAA_MAX_SEARCH_STEPS: i32 = 32;
const SMAA_MAX_SEARCH_STEPS_DIAG: i32 = 16;
const SMAA_CORNER_ROUNDING: f32 = 25.0;

const SMAA_AREATEX_MAX_DISTANCE: f32 = 16.0;
const SMAA_AREATEX_MAX_DISTANCE_DIAG: f32 = 20.0;
const SMAA_AREATEX_PIXEL_SIZE: vec2f = vec2f(1.0 / 160.0, 1.0 / 560.0);
const SMAA_AREATEX_SUBTEX_SIZE: f32 = 1.0 / 7.0;
const SMAA_SEARCHTEX_SIZE: vec2f = vec2f(66.0, 33.0);
const SMAA_SEARCHTEX_PACKED_SIZE: vec2f = vec2f(64.0, 16.0);
const SMAA_CORNER_ROUNDING_NORM: f32 = SMAA_CORNER_ROUNDING / 100.0;

fn texelSize() -> vec2f {
    return post.size.zw;
}

fn sampleEdges(uv: vec2f) -> vec4f {
    return textureSampleLevel(edgesTexture, linearSampler, vec2f(uv.x, 1.0 - uv.y), 0.0);
}

// SMAASampleLevelZeroOffset
fn sampleEdgesOffset(uv: vec2f, offset: vec2f) -> vec4f {
    return sampleEdges(uv + offset * texelSize());
}

fn sampleArea(uv: vec2f) -> vec4f {
    return textureSampleLevel(areaTexture, nearestSampler, uv, 0.0);
}

fn sampleSearch(uv: vec2f) -> vec4f {
    return textureSampleLevel(searchTexture, nearestSampler, uv, 0.0);
}

fn roundv2(v: vec2f) -> vec2f {
    return floor(v + vec2f(0.5));
}

// Распаковка двух бинарных значений из билинейной выборки (см. GLSL-комментарий)
fn SMAADecodeDiagBilinearAccess2(eIn: vec2f) -> vec2f {
    var e = eIn;
    e.r = e.r * abs(5.0 * e.r - 5.0 * 0.75);
    return roundv2(e);
}

fn SMAADecodeDiagBilinearAccess4(eIn: vec4f) -> vec4f {
    var e = eIn;
    let rb = e.rb * abs(5.0 * e.rb - 5.0 * 0.75);
    e.r = rb.x;
    e.b = rb.y;
    return floor(e + vec4f(0.5));
}

struct DiagSearchResult {
    zw: vec2f,
    e: vec2f,
};

fn SMAASearchDiag1(texcoord: vec2f, dir: vec2f) -> DiagSearchResult {
    var coord = vec4f(texcoord, -1.0, 1.0);
    let t = vec3f(texelSize(), 1.0);
    var e = vec2f(0.0);
    for (var i = 0; i < SMAA_MAX_SEARCH_STEPS; i++) {
        if (!(coord.z < f32(SMAA_MAX_SEARCH_STEPS_DIAG - 1) && coord.w > 0.9)) {
            break;
        }
        let xyz = t * vec3f(dir, 1.0) + coord.xyz;
        coord = vec4f(xyz, coord.w);
        e = sampleEdges(coord.xy).rg;
        coord.w = dot(e, vec2f(0.5, 0.5));
    }
    return DiagSearchResult(coord.zw, e);
}

fn SMAASearchDiag2(texcoord: vec2f, dir: vec2f) -> DiagSearchResult {
    var coord = vec4f(texcoord, -1.0, 1.0);
    coord.x += 0.25 * texelSize().x; // @SearchDiag2Optimization
    let t = vec3f(texelSize(), 1.0);
    var e = vec2f(0.0);
    for (var i = 0; i < SMAA_MAX_SEARCH_STEPS; i++) {
        if (!(coord.z < f32(SMAA_MAX_SEARCH_STEPS_DIAG - 1) && coord.w > 0.9)) {
            break;
        }
        let xyz = t * vec3f(dir, 1.0) + coord.xyz;
        coord = vec4f(xyz, coord.w);
        // Обе кромки одной билинейной выборкой
        e = SMAADecodeDiagBilinearAccess2(sampleEdges(coord.xy).rg);
        coord.w = dot(e, vec2f(0.5, 0.5));
    }
    return DiagSearchResult(coord.zw, e);
}

fn SMAAAreaDiag(dist: vec2f, e: vec2f, offset: f32) -> vec2f {
    var texcoord = vec2f(SMAA_AREATEX_MAX_DISTANCE_DIAG) * e + dist;
    texcoord = SMAA_AREATEX_PIXEL_SIZE * texcoord + 0.5 * SMAA_AREATEX_PIXEL_SIZE;
    // Диагональные area — во второй половине текстуры
    texcoord.x += 0.5;
    texcoord.y += SMAA_AREATEX_SUBTEX_SIZE * offset;
    return sampleArea(texcoord).rg;
}

fn SMAACalculateDiagWeights(texcoord: vec2f, e: vec2f, subsampleIndices: vec4f) -> vec2f {
    var weights = vec2f(0.0);
    let ts = texelSize();

    var d: vec4f;
    if (e.r > 0.0) {
        let r1 = SMAASearchDiag1(texcoord, vec2f(-1.0, 1.0));
        d.x = r1.zw.x + f32(r1.e.y > 0.9);
        d.z = r1.zw.y;
    } else {
        d.x = 0.0;
        d.z = 0.0;
    }
    let r2 = SMAASearchDiag1(texcoord, vec2f(1.0, -1.0));
    d.y = r2.zw.x;
    d.w = r2.zw.y;

    if (d.x + d.y > 2.0) { // d.x + d.y + 1 > 3
        let coords = vec4f(-d.x + 0.25, d.x, d.y, -d.y - 0.25) * vec4f(ts, ts) + texcoord.xyxy;
        var c: vec4f;
        let cxy = sampleEdgesOffset(coords.xy, vec2f(-1.0, 0.0)).rg;
        let czw = sampleEdgesOffset(coords.zw, vec2f(1.0, 0.0)).rg;
        c = vec4f(cxy, czw);
        let dec = SMAADecodeDiagBilinearAccess4(c);
        // GLSL: c.yxwz = dec.xyzw
        c = vec4f(dec.y, dec.x, dec.w, dec.z);

        var cc = vec2f(2.0) * c.xz + c.yw;
        // Убираем crossing edge, если конец линии не найден
        cc = select(cc, vec2f(0.0), vec2<bool>(step(vec2f(0.9), d.zw)));

        weights += SMAAAreaDiag(d.xy, cc, subsampleIndices.z);
    }

    let r3 = SMAASearchDiag2(texcoord, vec2f(-1.0, -1.0));
    d.x = r3.zw.x;
    d.z = r3.zw.y;
    if (sampleEdgesOffset(texcoord, vec2f(1.0, 0.0)).r > 0.0) {
        let r4 = SMAASearchDiag2(texcoord, vec2f(1.0, 1.0));
        d.y = r4.zw.x + f32(r4.e.y > 0.9);
        d.w = r4.zw.y;
    } else {
        d.y = 0.0;
        d.w = 0.0;
    }

    if (d.x + d.y > 2.0) { // d.x + d.y + 1 > 3
        let coords = vec4f(-d.x, -d.x, d.y, d.y) * vec4f(ts, ts) + texcoord.xyxy;
        var c: vec4f;
        c.x = sampleEdgesOffset(coords.xy, vec2f(-1.0, 0.0)).g;
        c.y = sampleEdgesOffset(coords.xy, vec2f(0.0, -1.0)).r;
        let zw = sampleEdgesOffset(coords.zw, vec2f(1.0, 0.0)).gr;
        c.z = zw.x;
        c.w = zw.y;
        var cc = vec2f(2.0) * c.xz + c.yw;
        cc = select(cc, vec2f(0.0), vec2<bool>(step(vec2f(0.9), d.zw)));

        weights += SMAAAreaDiag(d.xy, cc, subsampleIndices.w).gr;
    }

    return weights;
}

fn SMAASearchLength(e: vec2f, offset: f32) -> f32 {
    // Текстура флипнута вертикально, left/right делят её пополам по горизонтали
    var scale = SMAA_SEARCHTEX_SIZE * vec2f(0.5, -1.0);
    var bias = SMAA_SEARCHTEX_SIZE * vec2f(offset, 1.0);

    scale += vec2f(-1.0, 1.0);
    bias += vec2f(0.5, -0.5);

    scale *= 1.0 / SMAA_SEARCHTEX_PACKED_SIZE;
    bias *= 1.0 / SMAA_SEARCHTEX_PACKED_SIZE;

    return sampleSearch(scale * e + bias).r;
}

fn SMAASearchXLeft(texcoordIn: vec2f, end: f32) -> f32 {
    // @PSEUDO_GATHER4: texcoord смещён на (-0.25, -0.125), билинейная выборка
    // берёт 4 кромки за раз
    var texcoord = texcoordIn;
    var e = vec2f(0.0, 1.0);
    for (var i = 0; i < SMAA_MAX_SEARCH_STEPS; i++) {
        if (!(texcoord.x > end && e.g > 0.8281 && e.r == 0.0)) {
            break;
        }
        e = sampleEdges(texcoord).rg;
        texcoord = -vec2f(2.0, 0.0) * texelSize() + texcoord;
    }
    let offset = -(255.0 / 127.0) * SMAASearchLength(e, 0.0) + 3.25;
    return texelSize().x * offset + texcoord.x;
}

fn SMAASearchXRight(texcoordIn: vec2f, end: f32) -> f32 {
    var texcoord = texcoordIn;
    var e = vec2f(0.0, 1.0);
    for (var i = 0; i < SMAA_MAX_SEARCH_STEPS; i++) {
        if (!(texcoord.x < end && e.g > 0.8281 && e.r == 0.0)) {
            break;
        }
        e = sampleEdges(texcoord).rg;
        texcoord = vec2f(2.0, 0.0) * texelSize() + texcoord;
    }
    let offset = -(255.0 / 127.0) * SMAASearchLength(e, 0.5) + 3.25;
    return -texelSize().x * offset + texcoord.x;
}

fn SMAASearchYUp(texcoordIn: vec2f, end: f32) -> f32 {
    var texcoord = texcoordIn;
    var e = vec2f(1.0, 0.0);
    for (var i = 0; i < SMAA_MAX_SEARCH_STEPS; i++) {
        if (!(texcoord.y > end && e.r > 0.8281 && e.g == 0.0)) {
            break;
        }
        e = sampleEdges(texcoord).rg;
        texcoord = -vec2f(0.0, 2.0) * texelSize() + texcoord;
    }
    let offset = -(255.0 / 127.0) * SMAASearchLength(e.gr, 0.0) + 3.25;
    return texelSize().y * offset + texcoord.y;
}

fn SMAASearchYDown(texcoordIn: vec2f, end: f32) -> f32 {
    var texcoord = texcoordIn;
    var e = vec2f(1.0, 0.0);
    for (var i = 0; i < SMAA_MAX_SEARCH_STEPS; i++) {
        if (!(texcoord.y < end && e.r > 0.8281 && e.g == 0.0)) {
            break;
        }
        e = sampleEdges(texcoord).rg;
        texcoord = vec2f(0.0, 2.0) * texelSize() + texcoord;
    }
    let offset = -(255.0 / 127.0) * SMAASearchLength(e.gr, 0.5) + 3.25;
    return -texelSize().y * offset + texcoord.y;
}

fn SMAAArea(dist: vec2f, e1: f32, e2: f32, offset: f32) -> vec2f {
    // Округление против ошибок точности билинейной фильтрации
    var texcoord = vec2f(SMAA_AREATEX_MAX_DISTANCE) * roundv2(4.0 * vec2f(e1, e2)) + dist;
    texcoord = SMAA_AREATEX_PIXEL_SIZE * texcoord + 0.5 * SMAA_AREATEX_PIXEL_SIZE;
    texcoord.y = SMAA_AREATEX_SUBTEX_SIZE * offset + texcoord.y;
    return sampleArea(texcoord).rg;
}

fn SMAADetectHorizontalCornerPattern(weightsIn: vec2f, texcoord: vec4f, d: vec2f) -> vec2f {
    let leftRight = step(d.xy, d.yx);
    var rounding = (1.0 - SMAA_CORNER_ROUNDING_NORM) * leftRight;
    rounding /= leftRight.x + leftRight.y; // меньше блендинга в центре линии

    var factor = vec2f(1.0, 1.0);
    factor.x -= rounding.x * sampleEdgesOffset(texcoord.xy, vec2f(0.0, 1.0)).r;
    factor.x -= rounding.y * sampleEdgesOffset(texcoord.zw, vec2f(1.0, 1.0)).r;
    factor.y -= rounding.x * sampleEdgesOffset(texcoord.xy, vec2f(0.0, -2.0)).r;
    factor.y -= rounding.y * sampleEdgesOffset(texcoord.zw, vec2f(1.0, -2.0)).r;

    return weightsIn * saturate(factor);
}

fn SMAADetectVerticalCornerPattern(weightsIn: vec2f, texcoord: vec4f, d: vec2f) -> vec2f {
    let leftRight = step(d.xy, d.yx);
    var rounding = (1.0 - SMAA_CORNER_ROUNDING_NORM) * leftRight;
    rounding /= leftRight.x + leftRight.y;

    var factor = vec2f(1.0, 1.0);
    factor.x -= rounding.x * sampleEdgesOffset(texcoord.xy, vec2f(1.0, 0.0)).g;
    factor.x -= rounding.y * sampleEdgesOffset(texcoord.zw, vec2f(1.0, 1.0)).g;
    factor.y -= rounding.x * sampleEdgesOffset(texcoord.xy, vec2f(-2.0, 0.0)).g;
    factor.y -= rounding.y * sampleEdgesOffset(texcoord.zw, vec2f(-2.0, 1.0)).g;

    return weightsIn * saturate(factor);
}

@fragment
fn main(@location(0) uv: vec2f) -> @location(0) vec4f {
    let ts = texelSize();
    let pixCoord = uv * post.size.xy;

    // Смещения поисков (@PSEUDO_GATHER4)
    let offset0 = vec4f(ts, ts) * vec4f(-0.25, -0.125, 1.25, -0.125) + uv.xyxy;
    let offset1 = vec4f(ts, ts) * vec4f(-0.125, -0.25, -0.125, 1.25) + uv.xyxy;
    // Границы циклов поиска
    let offset2 = vec4f(ts.x, ts.x, ts.y, ts.y) * vec4f(-2.0, 2.0, -2.0, 2.0) * f32(SMAA_MAX_SEARCH_STEPS)
        + vec4f(offset0.xz, offset1.yw);

    let subsampleIndices = vec4f(0.0); // SMAA 1x
    var weights = vec4f(0.0);
    var e = sampleEdges(uv).rg;

    if (e.g > 0.0) { // Edge at north
        // Диагонали имеют и северную, и западную кромку — приоритет диагоналям
        weights = vec4f(SMAACalculateDiagWeights(uv, e, subsampleIndices), weights.ba);

        if (weights.r == -weights.g) { // weights.r + weights.g == 0.0
            var d: vec2f;

            var coords: vec3f;
            coords.x = SMAASearchXLeft(offset0.xy, offset2.x);
            coords.y = offset1.y; // @CROSSING_OFFSET
            d.x = coords.x;

            let e1 = sampleEdges(coords.xy).r;

            coords.z = SMAASearchXRight(offset0.zw, offset2.y);
            d.y = coords.z;

            d = abs(roundv2(post.size.xx * d + -pixCoord.xx));
            let sqrt_d = sqrt(d);

            let e2 = sampleEdgesOffset(coords.zy, vec2f(1.0, 0.0)).r;

            weights = vec4f(SMAAArea(sqrt_d, e1, e2, subsampleIndices.y), weights.ba);

            coords.y = uv.y;
            weights = vec4f(
                SMAADetectHorizontalCornerPattern(weights.rg, vec4f(coords.xy, coords.zy), d),
                weights.ba,
            );
        } else {
            e.r = 0.0; // диагональ найдена — вертикальную обработку пропускаем
        }
    }

    if (e.r > 0.0) { // Edge at west
        var d: vec2f;

        var coords: vec3f;
        coords.y = SMAASearchYUp(offset1.xy, offset2.z);
        coords.x = offset0.x;
        d.x = coords.y;

        let e1 = sampleEdges(coords.xy).g;

        coords.z = SMAASearchYDown(offset1.zw, offset2.w);
        d.y = coords.z;

        d = abs(roundv2(post.size.yy * d + -pixCoord.yy));
        let sqrt_d = sqrt(d);

        let e2 = sampleEdgesOffset(coords.xz, vec2f(0.0, 1.0)).g;

        weights = vec4f(weights.rg, SMAAArea(sqrt_d, e1, e2, subsampleIndices.x));

        coords.x = uv.x;
        weights = vec4f(
            weights.rg,
            SMAADetectVerticalCornerPattern(weights.ba, vec4f(coords.xy, coords.xz), d),
        );
    }

    return weights;
}
`,UD=`// SMAA, пасс 3 — neighborhood blending (порт smaa_blend.fsh): финальное
// смешение исходного изображения по весам из weight-таргета (включая
// гамма-коррекцию WebGL-порта). Экранные текстуры — через flip.

struct PostUniforms {
    // xy = размер канваса в пикселях, zw = 1/размер
    size: vec4f,
};

@group(0) @binding(0) var<uniform> post: PostUniforms;
@group(0) @binding(1) var colorTexture: texture_2d<f32>;
@group(0) @binding(2) var weightsTexture: texture_2d<f32>;
@group(0) @binding(3) var linearSampler: sampler;

fn sampleColor(uv: vec2f) -> vec4f {
    return textureSampleLevel(colorTexture, linearSampler, vec2f(uv.x, 1.0 - uv.y), 0.0);
}

fn sampleWeights(uv: vec2f) -> vec4f {
    return textureSampleLevel(weightsTexture, linearSampler, vec2f(uv.x, 1.0 - uv.y), 0.0);
}

@fragment
fn main(@location(0) uv: vec2f) -> @location(0) vec4f {
    let texel = post.size.zw;

    // Знаки в w — как в WebGL-порте (см. комментарии в smaa_blend.fsh)
    let offset1 = uv.xyxy + texel.xyxy * vec4f(1.0, 0.0, 0.0, -1.0);

    // Веса блендинга текущего пикселя
    var a: vec4f;
    let center = sampleWeights(uv);
    a.x = center.x;
    a.z = center.z;
    a.y = sampleWeights(offset1.zw).g;
    a.w = sampleWeights(offset1.xy).a;

    if (dot(a, vec4f(1.0)) < 1e-5) {
        return sampleColor(uv);
    }

    // До 4 линий могут пересекать пиксель — берём направление с максимальным весом
    var offset: vec2f;
    offset.x = select(-a.b, a.a, a.a > a.b); // left vs. right
    offset.y = select(a.r, -a.g, a.g > a.r); // top vs. bottom (знаки WebGL-порта)

    if (abs(offset.x) > abs(offset.y)) { // horizontal vs. vertical
        offset.y = 0.0;
    } else {
        offset.x = 0.0;
    }

    let c = sampleColor(uv);
    let cop = sampleColor(uv + sign(offset) * texel);
    let s = select(abs(offset.y), abs(offset.x), abs(offset.x) > abs(offset.y));

    // Гамма-коррекция WebGL-порта
    let cLin = vec4f(pow(c.xyz, vec3f(2.2)), c.w);
    let copLin = vec4f(pow(cop.xyz, vec3f(2.2)), cop.w);
    let mixed = mix(cLin, copLin, s);
    return vec4f(pow(mixed.xyz, vec3f(1.0 / 2.2)), mixed.w);
}
`,VD=`// Порт color_identify.fsh: id-цвет объекта в identify-таргет. Идентификатор приходит из
// вершинника основного пайплайна вида (@location(15), flat — значение точное, без
// интерполяции). (1,1,1,1) — объект без id (фон): отбрасываем, как вырожденные вершины
// color_identify.vsh, иначе он затёр бы id объекта под собой.
@fragment
fn main(@location(15) @interpolate(flat) identifier: vec4f) -> @location(0) vec4f {
    if (all(identifier == vec4f(1.0))) {
        discard;
    }
    return identifier;
}
`,WD=`// Порт arrow_line_identify.fsh (arrow.stroke, entranceIdentify): id-цвет квада стрелки
// входа с тем же отсевом, что у цветового lineArrow.frag — скрытые вершины и хвост
// за пределами видимого диапазона дистанций не кликаются.
const TYPE_ARROW = 1.0;

fn lookalike(a: f32, b: f32) -> bool {
    return abs(a - b) < 1e-5;
}

@fragment
fn main(
    @location(0) lineTypeArrowTail: vec2f,
    @location(3) distanceVertexHiding: vec4f,
    @location(15) @interpolate(flat) identifier: vec4f,
) -> @location(0) vec4f {
    let dvh = distanceVertexHiding;
    if (lookalike(min(dvh.y, 1.0), 1.0) ||
        lookalike(dvh.w, 1.0) ||
        (!lookalike(lineTypeArrowTail.x, TYPE_ARROW) && (dvh.x < dvh.y || dvh.x > dvh.z))) {
        discard;
    }
    return identifier;
}
`,HD=`// Порт road_identify.fsh (line.solid / line.solid3d): id-цвет линии без AA-каймы и
// углов скруглённых концов — пиксели дальше полуширины от оси отбрасываются.
@fragment
fn main(
    @location(0) lineNormal: vec2f,
    @location(1) halfWidth: f32,
    @location(15) @interpolate(flat) identifier: vec4f,
) -> @location(0) vec4f {
    if (dot(lineNormal, lineNormal) > halfWidth * halfWidth || all(identifier == vec4f(1.0))) {
        discard;
    }
    return identifier;
}
`,YD=`// Порт identify-ветки map_mesh.fsh (u_int_identify): меш развязки выводит тексел
// identify-текстуры своего яруса (там id tier-контента — дорог/разметки на развязке,
// белый — пустая поверхность: меш перекрывает объекты под собой). Без света/тумана.
// Тексел читается точно (textureLoad, порт NearestFilter identify-фреймбуфера) —
// фильтрация смешала бы id соседей в мусор.

struct Uniforms {
    mvpMatrix: mat4x4f,
    demTexMvpMatrix: mat4x4f,
    params: vec4f,
    params2: vec4f,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(1) @binding(0) var mapMeshTex: texture_2d<f32>;

@fragment
fn main(
    @location(0) texcoord: vec4f,
    @location(1) demTexPos: vec2f,
    @location(2) demInvalid: f32,
) -> @location(0) vec4f {
    if (demInvalid != 0.0 ||
        demTexPos.x < 0.0 || demTexPos.x > 1.0 ||
        demTexPos.y < 0.0 || demTexPos.y > 1.0) {
        discard;
    }

    var coord = texcoord.xy / texcoord.w;
    coord = coord / uniforms.params.xy;
    coord.y += uniforms.params.z / uniforms.params.y;
    coord = coord * 0.5 + vec2f(0.5, 0.5);

    // Вне текстуры ярусов — vec4(0), как legacy
    if (coord.x < 0.0 || coord.x > 1.0 || coord.y < 0.0 || coord.y > 1.0) {
        return vec4f(0.0);
    }

    // V переворачивается: текстура ярусов записана матрицами WebGL-конвенции
    let dims = vec2f(textureDimensions(mapMeshTex));
    let texel = vec2i(min(vec2f(coord.x, 1.0 - coord.y) * dims, dims - vec2f(1.0)));
    return textureLoad(mapMeshTex, texel, 0);
}
`,XD=`// Порт identify-ветки dem_mesh2.fsh (u_int_identify): рельеф выводит тексел identify-
// текстуры плоской карты (id 2d-объектов уровня каскада 0; белый — пусто), без света и
// тумана. Тексел читается точно (textureLoad, порт NearestFilter identify-фреймбуфера
// плоской карты). Вне текстуры — discard, как в основном проходе.

@group(1) @binding(0) var flatTex: texture_2d<f32>;

@fragment
fn main(@location(1) texcoord: vec4f) -> @location(0) vec4f {
    let tc = texcoord.xy / texcoord.w;
    if (tc.x < 0.0 || tc.x > 1.0 || tc.y < 0.0 || tc.y > 1.0) {
        discard;
    }
    // V переворачивается: flat-текстура записана матрицами WebGL-конвенции
    let dims = vec2f(textureDimensions(flatTex));
    let texel = vec2i(min(vec2f(tc.x, 1.0 - tc.y) * dims, dims - vec2f(1.0)));
    return textureLoad(flatTex, texel, 0);
}
`,ux=new WeakMap;function Th(e){let t=ux.get(e);return t||(t=new Map,ux.set(e,t)),t}function Et(e,...t){return[...t,e].join(`

`)}function it(e,...t){return Et(e,ox,QB,...t,lr)}const ZD={[Z.TileBounds]:{[q.Vertex]:MB,[q.Fragment]:_B},[Z.PolygonFill]:{[q.Vertex]:CB,[q.Fragment]:it(FB)},[Z.PolygonFillTexture]:{[q.Vertex]:Et(LB,Qo),[q.Fragment]:it(BB)},[Z.LineColor]:{[q.Vertex]:DB,[q.Fragment]:it(OB)},[Z.LineSolid]:{[q.Vertex]:RB,[q.Fragment]:it(Eh)},[Z.LineShifted]:{[q.Vertex]:zB,[q.Fragment]:it(Eh)},[Z.LineStripe]:{[q.Vertex]:NB,[q.Fragment]:it(rx)},[Z.LinePattern]:{[q.Vertex]:GB,[q.Fragment]:it(sx)},[Z.LineSolid3d]:{[q.Vertex]:kB,[q.Fragment]:it(Eh)},[Z.LineStripe3d]:{[q.Vertex]:dD,[q.Fragment]:it(rx)},[Z.LinePattern3d]:{[q.Vertex]:hD,[q.Fragment]:it(sx)},[Z.LineTopStroke]:{[q.Vertex]:UB,[q.Fragment]:it(VB)},[Z.LineSideStroke]:{[q.Vertex]:WB,[q.Fragment]:it(HB)},[Z.LineOneWay]:{[q.Vertex]:Et(YB,Ic),[q.Fragment]:Et(XB,Ic)},[Z.LineArrow]:{[q.Vertex]:Et(ZB,Ic),[q.Fragment]:Et(jB,Ic,lr)},[Z.PointSprite]:{[q.Vertex]:Et(qB,Qo,Mc,ax,lx),[q.Fragment]:Et(KB,lr)},[Z.LabelPoint]:{[q.Vertex]:Et(JB,Qo,Mc,ax),[q.Fragment]:Et($B,lr)},[Z.LabelLine]:{[q.Vertex]:eD,[q.Fragment]:Et(tD,lr)},[Z.PolygonExtrusionLabeling]:{[q.Vertex]:nD,[q.Fragment]:iD},[Z.PointAnchor]:{[q.Vertex]:Et(rD,Qo,Mc),[q.Fragment]:sD},[Z.PointSpriteLabeling]:{[q.Vertex]:Et(oD,Qo,Mc,lx),[q.Fragment]:aD},[Z.MetricPoint]:{[q.Vertex]:lD,[q.Fragment]:it(cD)},[Z.CircleMarker]:{[q.Vertex]:fD,[q.Fragment]:it(uD)},[Z.DemElevation]:{[q.Vertex]:pD,[q.Fragment]:gD},[Z.DemTerrain]:{[q.Vertex]:mD,[q.Fragment]:it(vD)},[Z.MapMesh]:{[q.Vertex]:yD,[q.Fragment]:it(xD)},[Z.Mesh]:{[q.Vertex]:wD,[q.Fragment]:it(AD)},[Z.PolygonExtrusion]:{[q.Vertex]:bD,[q.Fragment]:it(SD,ks)},[Z.PolygonExtrusionGradient]:{[q.Vertex]:ED,[q.Fragment]:it(cx,ks)},[Z.PolygonExtrusionGradientWall]:{[q.Vertex]:TD,[q.Fragment]:it(cx,ks)},[Z.PolygonExtrusionTexture]:{[q.Vertex]:PD,[q.Fragment]:Et(ID,ks,lr)},[Z.GltfModel]:{[q.Vertex]:CD,[q.Fragment]:Et(FD,ox,ks,lr)},[Z.PolygonExtrusionDepth]:{[q.Vertex]:MD,[q.Fragment]:Et(_D,ks)},[Z.Sky]:{[q.Vertex]:LD,[q.Fragment]:Et(BD,lr)},[Z.Stars]:{[q.Vertex]:DD,[q.Fragment]:OD},[Z.GlobeHalo]:{[q.Vertex]:fx,[q.Fragment]:RD},[Z.GlobeHaloBackground]:{[q.Vertex]:fx,[q.Fragment]:zD},[Z.Fxaa]:{[q.Vertex]:_c,[q.Fragment]:ND},[Z.SmaaEdge]:{[q.Vertex]:_c,[q.Fragment]:GD},[Z.SmaaWeight]:{[q.Vertex]:_c,[q.Fragment]:kD},[Z.SmaaBlend]:{[q.Vertex]:_c,[q.Fragment]:UD}},jD={[kt.Plain]:VD,[kt.LineSolid]:HD,[kt.LineArrow]:WD,[kt.MapMeshTexel]:YD,[kt.DemTerrainTexel]:XD};function dx(e,t,n){const i=ZD[e];if(!i)throw new Error(`No shaders registered for material type: ${e}`);const r=i[t];if(!r)throw new Error(`No ${t} shader for material type: ${e}`);return r}function Ph(e,t,n){return e.createShaderModule({label:n,code:t})}function hx(e,t,n={}){const i=Th(e),r=ix(t,q.Vertex,n);let s=i.get(r);if(!s){const o=dx(t,q.Vertex);s=Ph(e,o,`${t} vertex shader`),i.set(r,s)}return s}function px(e,t,n={}){const i=Th(e),r=ix(t,q.Fragment,n);let s=i.get(r);if(!s){const o=dx(t,q.Fragment);s=Ph(e,o,`${t} fragment shader`),i.set(r,s)}return s}function QD(e,t){const n=Th(e),i=`identify:${t}`;let r=n.get(i);return r||(r=Ph(e,jD[t],`identify ${t} fragment shader`),n.set(i,r)),r}class qD{constructor(){this.pipeline=null,this.uniformBuffer=null,this.bindGroup=null,this.vertexBuffer=null,this.uniformData=new Float32Array(m1),this.vertices=new Float32Array(g1),this.model=new Float64Array(16),this.mvp=new Float64Array(16)}ensureResources(t){if(this.pipeline)return;const{device:n,format:i}=t,r=hx(n,Z.TileBounds),s=px(n,Z.TileBounds);this.pipeline=n.createRenderPipeline({layout:"auto",vertex:{module:r,entryPoint:"main",buffers:[{arrayStride:Ac*Float32Array.BYTES_PER_ELEMENT,attributes:[{shaderLocation:0,offset:0,format:"float32x3"}]}]},fragment:{module:s,entryPoint:"main",targets:[{format:i}]},primitive:{topology:"line-list"},depthStencil:{format:Gt,depthWriteEnabled:!1,depthCompare:"always"},multisample:{count:Gs}}),this.uniformBuffer=n.createBuffer({size:U4,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.bindGroup=n.createBindGroup({layout:this.pipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:this.uniformBuffer}}]}),this.vertexBuffer=n.createBuffer({size:g1*Float32Array.BYTES_PER_ELEMENT,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST})}draw(t,n,i,r,s){if(i.size===0||!this.pipeline||!this.uniformBuffer||!this.bindGroup||!this.vertexBuffer)return;const o=Array.from(i.values()),a=r[0],l=r[1],c=this.generateVertices(o,a,l);c!==0&&(this.computeMvp(s,a,l),n.queue.writeBuffer(this.uniformBuffer,0,this.uniformData),n.queue.writeBuffer(this.vertexBuffer,0,this.vertices.subarray(0,c*Ac)),t.setPipeline(this.pipeline),t.setBindGroup(0,this.bindGroup),t.setVertexBuffer(0,this.vertexBuffer),t.draw(c))}generateVertices(t,n,i){let r=0;const s=this.vertices,o=Math.min(t.length,p1);for(let a=0;a<o;a++){const{x:l,y:c,z:f}=t[a],u=$(2,32-f),d=l*u-2147483648-n,h=c*u-2147483648-i,g=d+u,y=h+u;s[r++]=d,s[r++]=h,s[r++]=0,s[r++]=g,s[r++]=h,s[r++]=0,s[r++]=g,s[r++]=h,s[r++]=0,s[r++]=g,s[r++]=y,s[r++]=0,s[r++]=g,s[r++]=y,s[r++]=0,s[r++]=d,s[r++]=y,s[r++]=0,s[r++]=d,s[r++]=y,s[r++]=0,s[r++]=d,s[r++]=h,s[r++]=0}return r/Ac}computeMvp(t,n,i){const r=this.model;r[0]=1,r[1]=0,r[2]=0,r[3]=0,r[4]=0,r[5]=1,r[6]=0,r[7]=0,r[8]=0,r[9]=0,r[10]=1,r[11]=0,r[12]=n,r[13]=i,r[14]=0,r[15]=1,Di(this.mvp,t,r);const s=this.mvp;s[2]=s[2]*.5+s[3]*.5,s[6]=s[6]*.5+s[7]*.5,s[10]=s[10]*.5+s[11]*.5,s[14]=s[14]*.5+s[15]*.5;for(let o=0;o<16;o++)this.uniformData[o]=s[o];this.uniformData.set(G4,16)}}function gx(){return{color:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}}}function Tt(e){return{format:e,blend:gx()}}function ei(e){return{targets:[{format:Ii}],sampleCount:1,identifyFragment:e}}function wt(){return{format:Gt,depthWriteEnabled:!1,depthCompare:"always"}}function Ih(){return{format:Gt,depthWriteEnabled:!1,depthCompare:"less"}}function Us(e){switch(e){case"test":return Ih();case"greater":return{format:Gt,depthWriteEnabled:!1,depthCompare:"greater"};default:return wt()}}function Cc(e){return e==="overlay"?"":`:${e}`}function ti(){return{format:Gt,depthWriteEnabled:!0,depthCompare:"less"}}function Gn(e){return e==="receive"?"":`:${e}`}function kn(e,t=1){if(e==="caster")return{depthOnly:!0,sampleCount:1};const n={};return e!=="receive"&&(n.receiveShadows=0),e==="unlit"&&(n.useLight=0),t!==1&&(n.shadowClipWScale=t),Object.keys(n).length>0?{fragmentConstants:n}:{}}function Pe(e,t){const{materialType:n,bindGroupLayouts:i,targets:r,buffers:s,depthStencil:o,cull:a,topology:l,fragmentConstants:c,sampleCount:f,depthOnly:u,identifyFragment:d}=t;return e.createRenderPipeline(ie(V(ie(V({layout:e.createPipelineLayout({bindGroupLayouts:[...i]}),vertex:V({module:hx(e,n),entryPoint:"main"},s===void 0?{}:{buffers:[...s]})},u?{}:{fragment:V({module:d===void 0?px(e,n):QD(e,d),entryPoint:"main",targets:[...r]},c===void 0?{}:{constants:c})}),{primitive:V({topology:l!=null?l:"triangle-list"},a?{cullMode:"back",frontFace:"ccw"}:{})}),o===void 0?{}:{depthStencil:o}),{multisample:{count:f!=null?f:Gs}}))}function KD(e,t,n){if(e.length>=t)return e;let i=Math.max(e.length,n);for(;i<t;)i<<=1;const r=new Float32Array(i);return r.set(e),r}class JD{constructor(t){var n;this.staging=new Float32Array(0),this.buffer=null,this.group=null,this.shadowGroup=null,this.capacityDraws=0,this.drawCount=0,this.device=t.device,this.stride=(n=t.stride)!=null?n:nB,this.strideFloats=this.stride>>2,this.build=t.buildBindGroup,this.buildShadow=t.buildShadowBindGroup,this.ensureCapacity(1)}get count(){return this.drawCount}get bindGroup(){return this.group}get shadowBindGroup(){return this.shadowGroup}reset(){this.drawCount=0}push(t){this.staging=KD(this.staging,(this.drawCount+1)*this.strideFloats,this.strideFloats),this.staging.set(t,this.drawCount*this.strideFloats);const n=this.drawCount*this.stride;return this.drawCount++,n}upload(){this.drawCount!==0&&(this.ensureCapacity(this.drawCount),this.buffer&&this.device.queue.writeBuffer(this.buffer,0,this.staging.subarray(0,this.drawCount*this.strideFloats)))}ensureCapacity(t){var i;if(this.buffer&&this.group&&t<=this.capacityDraws)return;let n=Math.max(1,this.capacityDraws);for(;n<t;)n<<=1;(i=this.buffer)==null||i.destroy(),this.buffer=this.device.createBuffer({size:n*this.stride,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.capacityDraws=n,this.group=this.build(this.buffer),this.shadowGroup=this.buildShadow(this.buffer)}}class At{constructor(t){this.batchRef=null,this.pipelines=new Map,this.uniformLayout=null,this.casterLayout=null,this.uniformData=new Float32Array(t)}get batch(){return this.batchRef}reset(){var t;(t=this.batchRef)==null||t.reset()}upload(){var t;(t=this.batchRef)==null||t.upload()}pushShadowCopy(t){return this.uniformData.set(t,0),this.batchRef.push(this.uniformData)}group0Layout(t){return t==="caster"?this.casterLayout:this.uniformLayout}setupUniformBatch(t,{size:n,stride:i,extras:r=[]}){const s=f=>r.map((u,d)=>({extra:u,binding:d+1})).filter(({extra:u})=>!f||"buffer"in u),o=f=>t.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform",hasDynamicOffset:!0,minBindingSize:n}},...s(f).map(({extra:u,binding:d})=>V({binding:d,visibility:u.visibility},"buffer"in u?{buffer:{type:"uniform",minBindingSize:u.size}}:"texture"in u?{texture:{sampleType:u.sampleType}}:{sampler:{type:u.samplerType}}))]}),a=(f,u)=>d=>t.createBindGroup({layout:f,entries:[{binding:0,resource:{buffer:d,offset:0,size:n}},...s(u).map(({extra:h,binding:g})=>({binding:g,resource:"buffer"in h?{buffer:h.buffer}:"texture"in h?h.texture:h.sampler}))]}),l=o(!1),c=r.some(f=>!("buffer"in f));return this.uniformLayout=l,this.casterLayout=c?o(!0):l,this.batchRef=new JD(ie(V({device:t},i===void 0?{}:{stride:i}),{buildBindGroup:a(l,!1),buildShadowBindGroup:a(this.casterLayout,c)})),l}getOrCreatePipeline(t,n){const i=this.pipelines.get(t);if(i)return i;const r=n();return r&&this.pipelines.set(t,r),r}pushUniform(t){return this.batchRef.push(t)}}class $D extends At{constructor(){super(v1)}ensureResources(t,n,i,r,s){this.uniformLayout||this.setupUniformBatch(t.device,{size:V4,extras:[{buffer:n,size:Nn,visibility:GPUShaderStage.FRAGMENT},{buffer:i,size:ar,visibility:GPUShaderStage.VERTEX},{buffer:r,size:xt,visibility:GPUShaderStage.FRAGMENT},...s.extras()]})}getPipeline(t,n,i,r=!1,s=!1,o=r?"unlit":"receive",a="overlay"){const l=n>0?n:12,c=`${i}:${l}${r?":noDepth":""}${s?":cull":""}${Gn(o)}${Cc(a)}`;return this.getOrCreatePipeline(c,()=>{if(!this.uniformLayout)return null;const f=this.getMaterialType(i),u=this.getVertexBufferLayout(i,l);if(f===null||u===null)return null;const{device:d,format:h}=t;return Pe(d,V(V({materialType:f,bindGroupLayouts:[this.uniformLayout],buffers:[u],targets:[Tt(h)],cull:s},r?{sampleCount:1}:{depthStencil:Us(a)}),kn(o)))})}getIdentifyPipeline(t,n,i){const r=n>0?n:12;return this.getOrCreatePipeline(`identify:${r}${i?":cull":""}`,()=>{const s=this.getVertexBufferLayout(Ve.PolygonColorFill,r);return!this.uniformLayout||!s?null:Pe(t.device,V({materialType:Z.PolygonFill,bindGroupLayouts:[this.uniformLayout],buffers:[s],cull:i,depthStencil:wt()},ei(kt.Plain)))})}pushDraw(t,n,i,r,s,o,a=0){const l=this.uniformData;l.set(t,0),l.set(n.subarray(r+(fe.Color1R>>2),r+(fe.Color2A>>2)+1),16);const c=i[r+(fe.Flags>>2)];return l[24]=c&ec.UseFactorInterpolate?1:0,l[25]=n[r+(fe.FactorBase>>2)],l[26]=0,l[27]=0,l.set(n.subarray(r+(fe.FactorInMin>>2),r+(fe.FactorOutMax>>2)+1),28),l[32]=s,l[33]=a,l[34]=0,l[35]=0,l.set(o,36),this.pushUniform(l)}getMaterialType(t){return t===Ve.PolygonColorFill?Z.PolygonFill:null}getVertexBufferLayout(t,n){return t===Ve.PolygonColorFill?{arrayStride:n,attributes:[{shaderLocation:0,offset:0,format:"unorm16x4"},{shaderLocation:1,offset:8,format:"unorm8x4"}]}:null}}class Vs{constructor(){this.layoutRef=null,this.sampler=null,this.bindGroups=new WeakMap}get layout(){return this.layoutRef}ensureResources(t){this.layoutRef||(this.layoutRef=t.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}}]}),this.sampler=t.createSampler({magFilter:"linear",minFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}))}getBindGroup(t,n){const i=this.bindGroups.get(n);if(i)return i;if(!this.layoutRef||!this.sampler)return null;const r=t.createBindGroup({layout:this.layoutRef,entries:[{binding:0,resource:this.sampler},{binding:1,resource:n.createView()}]});return this.bindGroups.set(n,r),r}}class eO extends At{constructor(){super(y1),this.textureGroup=new Vs}ensureResources(t,n,i,r,s){if(this.uniformLayout)return;const{device:o}=t;this.textureGroup.ensureResources(o),this.setupUniformBatch(o,{size:W4,extras:[{buffer:n,size:Nn,visibility:GPUShaderStage.FRAGMENT},{buffer:i,size:ar,visibility:GPUShaderStage.VERTEX},{buffer:r,size:xt,visibility:GPUShaderStage.FRAGMENT},...s.extras()]})}getPipeline(t,n,i=!1,r=!1,s=i?"unlit":"receive",o="overlay"){const a=n>0?n:8,l=`${a}${i?":noDepth":""}${r?":cull":""}${Gn(s)}${Cc(o)}`;return this.getOrCreatePipeline(l,()=>{const c=this.textureGroup.layout;if(!this.uniformLayout||!c)return null;const{device:f,format:u}=t;return Pe(f,V(V({materialType:Z.PolygonFillTexture,bindGroupLayouts:[this.uniformLayout,c],buffers:[{arrayStride:a,attributes:[{shaderLocation:0,offset:0,format:"unorm16x4"}]}],targets:[Tt(u)],cull:r},i?{sampleCount:1}:{depthStencil:Us(o)}),kn(s)))})}getTextureBindGroup(t,n){return this.textureGroup.getBindGroup(t.device,n)}pushDraw(t,n,i,r,s,o,a,l,c,f=0){const u=this.uniformData;return u.set(t,0),u.set(n.subarray(i+(fe.Color1R>>2),i+(fe.Color1A>>2)+1),16),u[20]=r,u[21]=s,u[22]=o,u[23]=a,u.set(n.subarray(i+(Fs.SpriteX1>>2),i+(Fs.SpriteY2>>2)+1),24),u[28]=n[i+(Fs.Opacity>>2)],u[29]=l,u[30]=f,u[31]=0,u.set(c,32),this.pushUniform(u)}}class Mi{constructor(){this.layoutRef=null,this.sampler=null,this.bindGroupRef=null,this.boundView=null,this.placeholderTexture=null,this.placeholderView=null}get layout(){return this.layoutRef}get bindGroup(){return this.bindGroupRef}ensureResources(t){this.layoutRef||(this.layoutRef=t.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.VERTEX,sampler:{type:"filtering"}}]}),this.sampler=t.createSampler({magFilter:"linear",minFilter:"linear"}))}ensureBindGroup(t,n){if(!this.layoutRef||!this.sampler)return;const i=n!=null?n:this.ensurePlaceholder(t);this.bindGroupRef&&this.boundView===i||(this.bindGroupRef=t.createBindGroup({layout:this.layoutRef,entries:[{binding:0,resource:i},{binding:1,resource:this.sampler}]}),this.boundView=i)}ensurePlaceholder(t){return(!this.placeholderTexture||!this.placeholderView)&&(this.placeholderTexture=t.createTexture({size:{width:1,height:1},format:jo,usage:GPUTextureUsage.TEXTURE_BINDING}),this.placeholderView=this.placeholderTexture.createView()),this.placeholderView}}class tO extends At{constructor(){super(w1),this.demGroup=new Mi}ensureResources(t,n,i,r,s){if(this.uniformLayout)return;const{device:o}=t;this.setupUniformBatch(o,{size:X4,extras:[{buffer:n,size:Nn,visibility:GPUShaderStage.FRAGMENT},{buffer:i,size:ar,visibility:GPUShaderStage.VERTEX},{buffer:r,size:xt,visibility:GPUShaderStage.FRAGMENT},...s.extras()]}),this.demGroup.ensureResources(o)}getPipeline(t,n,i,r,s=!1,o=!1,a=s?"unlit":"receive",l="overlay"){const c=n>0?n:8,f=r===ue.TopStroke20||r===ue.SideStroke24,u=r===ue.Solid3d20||f,d=o&&!u,h=`${i}:${r}:${c}${s?":noDepth":""}${d?":cull":""}${Gn(a)}${Cc(l)}`;return this.getOrCreatePipeline(h,()=>{if(!this.uniformLayout)return null;const g=this.getMaterialType(i,r),y=this.getVertexBufferLayout(r,c);if(g===null||y===null)return null;const p=this.demGroup.layout;if(u&&!p)return null;let v;l==="greater"&&!s?v=Us(l):f?v=Ih():u?v=ti():s||(v=Us(l));const{device:A,format:w}=t;return Pe(A,V(V(V({materialType:g,bindGroupLayouts:u&&p?[this.uniformLayout,p]:[this.uniformLayout],buffers:[y],targets:[Tt(w)],cull:d},v===void 0?{}:{depthStencil:v}),s?{sampleCount:1}:{}),kn(a,1/G1)))})}getIdentifyPipeline(t,n,i,r){const s=i===ue.Solid3d20;if(!s&&i!==ue.Solid16)return null;const o=n>0?n:s?20:16,a=r&&!s,l=`identify:${i}:${o}${a?":cull":""}`;return this.getOrCreatePipeline(l,()=>{const c=this.getVertexBufferLayout(i,o),f=this.demGroup.layout;return!this.uniformLayout||!c||s&&!f?null:Pe(t.device,V({materialType:s?Z.LineSolid3d:Z.LineSolid,bindGroupLayouts:s&&f?[this.uniformLayout,f]:[this.uniformLayout],buffers:[c],cull:a,depthStencil:s?ti():wt()},ei(kt.LineSolid)))})}pushDraw(t,n,i,r,s,o,a,l,c,f,u=0,d=0,h=0){const g=this.uniformData;switch(g.set(t,0),g.set(n.subarray(i+(fe.Color1R>>2),i+(fe.Color1A>>2)+1),16),r){case ue.Solid16:case ue.Shifted20:g[20]=s,g[21]=o,g[22]=a,g[23]=0;break;default:g[20]=l,g[21]=c,g[22]=s,g[23]=0;break}return g[24]=u,g[25]=d,g[26]=h,g[27]=0,g.set(f,28),this.pushUniform(g)}pushDraw3d(t,n,i,r,s,o,a,l,c,f,u,d,h,g){const y=this.uniformData;return y.set(t,0),y.set(n.subarray(i+(fe.Color1R>>2),i+(fe.Color1A>>2)+1),16),y[20]=r,y[21]=s,y[22]=o,y[23]=a,y.set(l,24),y[40]=c,y[41]=f,y[42]=u,y[43]=d,y[44]=h[0],y[45]=h[1],y[46]=h[2],y[47]=g,this.pushUniform(y)}pushDrawStroke(t,n,i,r,s,o,a,l,c,f,u,d,h,g,y,p=0){const v=this.uniformData;return v.set(t,0),v.set(n.subarray(i+(fe.Color1R>>2),i+(fe.Color1A>>2)+1),16),v[20]=r,v[21]=s,v[22]=o,v[23]=a,v.set(l,24),v[40]=c,v[41]=f,v[42]=u,v[43]=d,v[44]=h[0],v[45]=h[1],v[46]=h[2],v[47]=g,v[48]=y,v[49]=p,v.fill(0,50,52),this.pushUniform(v)}getMaterialType(t,n){if(t!==Ve.LineColor)return null;switch(n){case ue.Solid12:return Z.LineColor;case ue.Solid16:return Z.LineSolid;case ue.Shifted20:return Z.LineShifted;case ue.Solid3d20:return Z.LineSolid3d;case ue.TopStroke20:return Z.LineTopStroke;case ue.SideStroke24:return Z.LineSideStroke;default:return null}}getVertexBufferLayout(t,n){switch(t){case ue.Solid12:return{arrayStride:n,attributes:[{shaderLocation:0,offset:0,format:"unorm16x4"},{shaderLocation:1,offset:8,format:"sint8x4"}]};case ue.Solid16:return{arrayStride:n,attributes:[{shaderLocation:0,offset:0,format:"unorm16x4"},{shaderLocation:1,offset:8,format:"sint8x4"},{shaderLocation:2,offset:12,format:"unorm8x4"}]};case ue.Shifted20:return{arrayStride:n,attributes:[{shaderLocation:0,offset:0,format:"unorm16x4"},{shaderLocation:1,offset:8,format:"sint8x4"},{shaderLocation:2,offset:12,format:"float32x2"}]};case ue.Solid3d20:return{arrayStride:n,attributes:[{shaderLocation:0,offset:0,format:"unorm16x2"},{shaderLocation:1,offset:4,format:"sint8x4"},{shaderLocation:2,offset:8,format:"float32"},{shaderLocation:3,offset:12,format:"float32"},{shaderLocation:4,offset:16,format:"unorm8x4"}]};case ue.TopStroke20:return{arrayStride:n,attributes:[{shaderLocation:0,offset:0,format:"unorm16x2"},{shaderLocation:1,offset:8,format:"sint8x4"},{shaderLocation:2,offset:4,format:"float32"},{shaderLocation:3,offset:12,format:"sint16x2"},{shaderLocation:4,offset:12,format:"float32"},{shaderLocation:5,offset:16,format:"unorm8x4"}]};case ue.SideStroke24:return{arrayStride:n,attributes:[{shaderLocation:0,offset:0,format:"unorm16x2"},{shaderLocation:1,offset:12,format:"sint8x4"},{shaderLocation:2,offset:4,format:"float32"},{shaderLocation:3,offset:16,format:"sint16x2"},{shaderLocation:5,offset:8,format:"sint8x4"}]};default:return null}}}class nO extends At{constructor(){super(A1),this.demGroup=new Mi}ensureResources(t,n,i,r,s){if(this.uniformLayout)return;const{device:o}=t;this.setupUniformBatch(o,{size:Z4,extras:[{buffer:n,size:Nn,visibility:GPUShaderStage.FRAGMENT},{buffer:i,size:ar,visibility:GPUShaderStage.VERTEX},{buffer:r,size:xt,visibility:GPUShaderStage.FRAGMENT},...s.extras()]}),this.demGroup.ensureResources(o)}getPipeline(t,n,i,r,s=!1,o=!1,a=s?"unlit":"receive",l="overlay"){const c=n>0?n:28,f=r===ue.Dashed3d32||r===ue.Patterned3d20,u=o&&!f,d=`${i}:${r}:${c}${s?":noDepth":""}${u?":cull":""}${Gn(a)}${Cc(l)}`;return this.getOrCreatePipeline(d,()=>{if(!this.uniformLayout)return null;const h=this.getMaterialType(i,r),g=this.getVertexBufferLayout(r,c);if(h===null||g===null)return null;const y=this.demGroup.layout;if(f&&!y)return null;let p;l==="greater"&&!s?p=Us(l):f?p=ti():s||(p=Us(l));const{device:v,format:A}=t;return Pe(v,V(V(V({materialType:h,bindGroupLayouts:f&&y?[this.uniformLayout,y]:[this.uniformLayout],buffers:[g],targets:[Tt(A)],cull:u},p===void 0?{}:{depthStencil:p}),s?{sampleCount:1}:{}),kn(a,1/(i===Ve.LineStripe?uB:G1))))})}getIdentifyPipeline(t,n,i,r){const s=i===ue.Dashed3d32;if(!s&&i!==ue.Dashed28)return null;const o=n>0?n:s?32:28,a=r&&!s,l=`identify:${i}:${o}${a?":cull":""}`;return this.getOrCreatePipeline(l,()=>{const c=this.getVertexBufferLayout(i,o),f=this.demGroup.layout;return!this.uniformLayout||!c||s&&!f?null:Pe(t.device,V({materialType:s?Z.LineStripe3d:Z.LineStripe,bindGroupLayouts:s&&f?[this.uniformLayout,f]:[this.uniformLayout],buffers:[c],cull:a,depthStencil:s?ti():wt()},ei(kt.Plain)))})}pushDraw(t,n,i,r,s,o,a,l,c,f,u,d,h,g=0,y=0,p=0,v=0,A=0){const w=this.uniformData;return w.set(t,0),w.set(n.subarray(r+(Ls.DashColorR>>2),r+(Ls.BorderColorA>>2)+1),16),w[28]=s,w[29]=n[r+(Ls.DashLength>>2)]*o,w[30]=n[r+(Ls.SpaceLength>>2)]*o,w[31]=a,w[32]=l,w[33]=c,w[34]=(i[r+(fe.Flags>>2)]&ec.LineGapTurnsOnly)!==0?1:0,w[35]=0,h?(this.setDemTail(36,h,g,y,u,d),w.set(f,56)):(w[36]=p,w[37]=v,w[38]=A,w[39]=0,w.set(f,40)),this.pushUniform(w)}pushPatternDraw(t,n,i,r,s,o,a,l,c,f,u,d=0,h=0){const g=this.uniformData;return g.set(t,0),g.set(n.subarray(r+(Gr.ColorR>>2),r+(Gr.ColorA>>2)+1),16),g.set(n.subarray(r+(Gr.ParamX>>2),r+(Gr.ParamW>>2)+1),20),g[24]=s,g[25]=o,g[26]=a,g[27]=i[r+(Gr.PatternType>>2)],u?(this.setDemTail(28,u,d,h,c,f),g.set(l,48)):g.set(l,28),this.pushUniform(g)}setDemTail(t,n,i,r,s,o){const a=this.uniformData;a.set(n,t),a[t+16]=i,a[t+17]=r,a[t+18]=s,a[t+19]=o}getMaterialType(t,n){return t===Ve.LineStripe&&n===ue.Dashed28?Z.LineStripe:t===Ve.LinePattern&&n===ue.Patterned16?Z.LinePattern:t===Ve.LineStripe&&n===ue.Dashed3d32?Z.LineStripe3d:t===Ve.LinePattern&&n===ue.Patterned3d20?Z.LinePattern3d:null}getVertexBufferLayout(t,n){switch(t){case ue.Dashed28:return{arrayStride:n,attributes:[{shaderLocation:0,offset:0,format:"unorm16x4"},{shaderLocation:1,offset:6,format:"sint8x2"},{shaderLocation:2,offset:8,format:"sint16x2"},{shaderLocation:3,offset:12,format:"float32"},{shaderLocation:4,offset:16,format:"float32"},{shaderLocation:5,offset:20,format:"float32"},{shaderLocation:7,offset:24,format:"unorm8x4"}]};case ue.Patterned16:return{arrayStride:n,attributes:[{shaderLocation:0,offset:0,format:"unorm16x2"},{shaderLocation:1,offset:4,format:"sint16x2"},{shaderLocation:2,offset:8,format:"float32"}]};case ue.Dashed3d32:return{arrayStride:n,attributes:[{shaderLocation:0,offset:0,format:"unorm16x2"},{shaderLocation:1,offset:8,format:"sint8x2"},{shaderLocation:2,offset:4,format:"sint16x2"},{shaderLocation:3,offset:12,format:"float32"},{shaderLocation:4,offset:16,format:"float32"},{shaderLocation:5,offset:20,format:"float32"},{shaderLocation:6,offset:24,format:"float32"},{shaderLocation:7,offset:28,format:"unorm8x4"}]};case ue.Patterned3d20:return{arrayStride:n,attributes:[{shaderLocation:0,offset:0,format:"unorm16x2"},{shaderLocation:1,offset:4,format:"sint16x2"},{shaderLocation:2,offset:8,format:"float32"},{shaderLocation:3,offset:12,format:"float32"}]};default:return null}}}class iO extends At{constructor(){super(b1)}ensureResources(t,n){this.uniformLayout||this.setupUniformBatch(t.device,{size:j4,extras:[{buffer:n,size:xt,visibility:GPUShaderStage.FRAGMENT}]})}getPipeline(t,n,i,r){const s=n>0?n:12,o=`${i}:${r}:${s}`;return this.getOrCreatePipeline(o,()=>{if(!this.uniformLayout)return null;const a=this.getMaterialType(i,r),l=this.getVertexBufferLayout(r,s);if(a===null||l===null)return null;const{device:c,format:f}=t;return Pe(c,{materialType:a,bindGroupLayouts:[this.uniformLayout],buffers:[l],targets:[Tt(f)],depthStencil:wt()})})}getIdentifyPipeline(t,n,i){if(i!==ue.Arrow36)return null;const r=n>0?n:36;return this.getOrCreatePipeline(`identify:${r}`,()=>{const s=this.getVertexBufferLayout(ue.Arrow36,r);return!this.uniformLayout||!s?null:Pe(t.device,V({materialType:Z.LineArrow,bindGroupLayouts:[this.uniformLayout],buffers:[s],depthStencil:wt()},ei(kt.LineArrow)))})}pushDraw(t,n,i,r,s,o,a,l,c,f,u,d,h,g,y){const p=this.uniformData;p.set(t,0),r===Ve.LineArrow?(p.set(n.subarray(i+(Ei.ColorR>>2),i+(Ei.BorderColorA>>2)+1),16),p[24]=n[i+(Ei.LineWidth>>2)],p[25]=n[i+(Ei.StrokeWidth>>2)],p[26]=0,p[35]=n[i+(Ei.RoundingRadius>>2)]):(p.set(n.subarray(i+(nr.ColorR>>2),i+(nr.ColorA>>2)+1),16),p.fill(0,20,24),p[24]=n[i+(nr.Width>>2)],p[25]=0,p[26]=n[i+(nr.Length>>2)],p[35]=0),p[27]=o;const v=r===Ve.LineArrow?Ei.TipWidth:nr.TipWidth,A=r===Ve.LineArrow?Ei.TipHeight:nr.TipHeight;return p[28]=n[i+(A>>2)],p[29]=0,p[30]=n[i+(v>>2)],p[31]=s,p[32]=a,p[33]=l,p[34]=c,p[36]=h,p[37]=g,p[38]=0,p[39]=0,p[40]=f,p[41]=d,p[42]=u,p[43]=0,p.set(y,44),this.pushUniform(p)}getMaterialType(t,n){return t===Ve.LineOneWay&&n===ue.OneWay12?Z.LineOneWay:t===Ve.LineArrow&&n===ue.Arrow36?Z.LineArrow:null}getVertexBufferLayout(t,n){switch(t){case ue.OneWay12:return{arrayStride:n,attributes:[{shaderLocation:0,offset:0,format:"unorm16x2"},{shaderLocation:1,offset:8,format:"sint8x2"},{shaderLocation:2,offset:10,format:"sint8x2"}]};case ue.Arrow36:return{arrayStride:n,attributes:[{shaderLocation:0,offset:0,format:"unorm16x2"},{shaderLocation:1,offset:4,format:"unorm16x2"},{shaderLocation:2,offset:8,format:"sint8x4"},{shaderLocation:3,offset:12,format:"sint16x2"},{shaderLocation:4,offset:16,format:"sint16x2"},{shaderLocation:5,offset:20,format:"float32"},{shaderLocation:6,offset:24,format:"float32"},{shaderLocation:7,offset:28,format:"float32"},{shaderLocation:8,offset:32,format:"unorm8x4"}]};default:return null}}}class mx{constructor(){this.layoutRef=null,this.sampler=null,this.bindGroupRef=null,this.boundKey=null,this.placeholderColor=null,this.placeholderDepth=null}get layout(){return this.layoutRef}get bindGroup(){return this.bindGroupRef}ensureResources(t){if(this.layoutRef)return;const n=GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT;this.layoutRef=t.createBindGroupLayout({entries:[{binding:0,visibility:n,sampler:{type:"non-filtering"}},{binding:1,visibility:n,texture:{sampleType:"unfilterable-float"}},{binding:2,visibility:n,texture:{sampleType:"depth"}},{binding:3,visibility:n,texture:{sampleType:"unfilterable-float"}}]}),this.sampler=t.createSampler({magFilter:"nearest",minFilter:"nearest"})}ensureBindGroup(t,n,i,r,s){if(!this.layoutRef||!this.sampler)return;const o=`${s}|${n?1:0}${i?1:0}${r?1:0}`;if(this.bindGroupRef&&this.boundKey===o)return;const a=this.ensureColorPlaceholder(t).createView();this.bindGroupRef=t.createBindGroup({layout:this.layoutRef,entries:[{binding:0,resource:this.sampler},{binding:1,resource:n!=null?n:a},{binding:2,resource:i!=null?i:this.ensureDepthPlaceholder(t).createView()},{binding:3,resource:r!=null?r:a}]}),this.boundKey=o}ensureColorPlaceholder(t){return this.placeholderColor||(this.placeholderColor=t.createTexture({size:{width:1,height:1},format:Ii,usage:GPUTextureUsage.TEXTURE_BINDING})),this.placeholderColor}ensureDepthPlaceholder(t){return this.placeholderDepth||(this.placeholderDepth=t.createTexture({size:{width:1,height:1},format:Gt,usage:GPUTextureUsage.TEXTURE_BINDING})),this.placeholderDepth}}class rO extends At{constructor(){super(S1),this.demGroup=new Mi,this.occlusionGroup=new mx,this.textureGroup=new Vs}ensureResources(t,n,i){if(this.uniformLayout)return;const{device:r}=t;this.setupUniformBatch(r,{size:Q4,extras:[{buffer:n,size:ar,visibility:GPUShaderStage.VERTEX},{buffer:i,size:xt,visibility:GPUShaderStage.FRAGMENT}]}),this.textureGroup.ensureResources(r),this.demGroup.ensureResources(r),this.occlusionGroup.ensureResources(r)}getPipeline(t,n){const i=n>0?n:36;return this.getOrCreatePipeline(`main:${i}`,()=>{const r=this.textureGroup.layout,s=this.demGroup.layout,o=this.occlusionGroup.layout;if(!this.uniformLayout||!r||!s||!o)return null;const{device:a,format:l}=t;return Pe(a,{materialType:Z.PointSprite,bindGroupLayouts:[this.uniformLayout,r,s,o],buffers:[{arrayStride:i,attributes:[{shaderLocation:0,offset:0,format:"unorm16x4"},{shaderLocation:1,offset:8,format:"sint16x2"},{shaderLocation:2,offset:12,format:"uint16x2"},{shaderLocation:3,offset:16,format:"sint16x2"},{shaderLocation:4,offset:20,format:"sint16x2"},{shaderLocation:5,offset:28,format:"unorm8x4"}]}],targets:[Tt(l)],depthStencil:wt()})})}getSpritePipeline(t,n){const i=n>0?n:36;return this.getOrCreatePipeline(`sprite:${i}`,()=>{const r=this.textureGroup.layout,s=this.demGroup.layout;return!this.uniformLayout||!r||!s?null:Pe(t.device,{materialType:Z.PointSpriteLabeling,bindGroupLayouts:[this.uniformLayout,r,s],buffers:[{arrayStride:i,attributes:[{shaderLocation:0,offset:0,format:"unorm16x4"},{shaderLocation:1,offset:8,format:"sint16x2"},{shaderLocation:2,offset:12,format:"uint16x2"},{shaderLocation:3,offset:16,format:"sint16x2"},{shaderLocation:4,offset:32,format:"unorm8x4"}]}],targets:[{format:Ii}],sampleCount:1})})}getIdentifyPipeline(t,n){const i=n>0?n:36;return this.getOrCreatePipeline(`identify:${i}`,()=>{const r=this.textureGroup.layout,s=this.demGroup.layout,o=this.occlusionGroup.layout;return!this.uniformLayout||!r||!s||!o?null:Pe(t.device,V({materialType:Z.PointSpriteLabeling,bindGroupLayouts:[this.uniformLayout,r,s,o],buffers:[{arrayStride:i,attributes:[{shaderLocation:0,offset:0,format:"unorm16x4"},{shaderLocation:1,offset:8,format:"sint16x2"},{shaderLocation:2,offset:12,format:"uint16x2"},{shaderLocation:3,offset:16,format:"sint16x2"},{shaderLocation:4,offset:24,format:"unorm8x4"}]}],depthStencil:wt()},ei()))})}getTextureBindGroup(t,n){return this.textureGroup.getBindGroup(t.device,n)}pushDraw(t,n,i,r,s,o,a,l,c,f,u,d){const h=this.uniformData,g=i[r+(yt.Flags>>2)];return h.set(t,0),h[16]=n[r+(yt.OpacityVisible>>2)],h[17]=n[r+(yt.OpacityHidden>>2)],h[18]=n[r+(yt.RotationCos>>2)],h[19]=n[r+(yt.RotationSin>>2)],h[20]=n[r+(yt.HeightFactor>>2)],h[21]=(g&Bs.SkipHeightFactor)!==0?1:0,h[22]=n[r+(yt.FloorElevation>>2)],h[23]=n[r+(yt.StyleScale>>2)],h[24]=n[r+(yt.Dpi>>2)],h[25]=n[r+(yt.RoundingFactor>>2)],h[26]=s,h[27]=o,h[28]=(g&Bs.SurfaceUseAbsZ)!==0?1:0,h[29]=n[r+(yt.SurfaceRelZNorm>>2)],h[30]=n[r+(yt.SurfaceAbsZ>>2)],h[31]=0,h[32]=n[r+(yt.HalfPointSizeX>>2)],h[33]=n[r+(yt.HalfPointSizeY>>2)],h[34]=a?1:0,h[35]=n[r+(yt.IdentifyOpacity>>2)],h.set(l,36),h[52]=c,h[53]=f,h[54]=u,h[55]=0,h.set(d,56),this.pushUniform(h)}}function vx(e){return{arrayStride:e,attributes:[{shaderLocation:0,offset:0,format:"unorm16x4"},{shaderLocation:1,offset:8,format:"sint16x2"},{shaderLocation:2,offset:12,format:"uint16x2"},{shaderLocation:3,offset:16,format:"sint16x2"},{shaderLocation:4,offset:24,format:"unorm8x4"},{shaderLocation:5,offset:28,format:"unorm8x4"},{shaderLocation:6,offset:20,format:"unorm8x4"}]}}class sO extends At{constructor(){super(E1),this.demGroup=new Mi,this.occlusionGroup=new mx,this.textureGroup=new Vs}ensureResources(t,n,i){if(this.uniformLayout)return;const{device:r}=t;this.setupUniformBatch(r,{size:q4,stride:K4,extras:[{buffer:n,size:ar,visibility:GPUShaderStage.VERTEX},{buffer:i,size:xt,visibility:GPUShaderStage.FRAGMENT}]}),this.textureGroup.ensureResources(r),this.demGroup.ensureResources(r),this.occlusionGroup.ensureResources(r)}getPipeline(t,n,i){const r=n>0?n:32;return this.getOrCreatePipeline(`${r}:${i}`,()=>{const s=this.textureGroup.layout,o=this.demGroup.layout,a=this.occlusionGroup.layout;if(!this.uniformLayout||!s||!o||!a)return null;const{device:l,format:c}=t;return Pe(l,{materialType:Z.LabelPoint,bindGroupLayouts:[this.uniformLayout,s,o,a],buffers:[vx(r)],fragmentConstants:{isHalo:i==="halo"?1:0},targets:[Tt(c)],depthStencil:wt()})})}getIdentifyPipeline(t,n){const i=n>0?n:32;return this.getOrCreatePipeline(`identify:${i}`,()=>{const r=this.textureGroup.layout,s=this.demGroup.layout,o=this.occlusionGroup.layout;return!this.uniformLayout||!r||!s||!o?null:Pe(t.device,V({materialType:Z.LabelPoint,bindGroupLayouts:[this.uniformLayout,r,s,o],buffers:[vx(i)],depthStencil:wt()},ei(kt.Plain)))})}getTextureBindGroup(t,n){return this.textureGroup.getBindGroup(t.device,n)}pushDraw(t,n,i,r,s,o,a,l,c,f,u,d){const h=this.uniformData,g=i[r+(ut.Flags>>2)];return h.set(t,0),h[16]=n[r+(ut.Opacity>>2)],h[17]=n[r+(ut.Scale>>2)],h[18]=n[r+(ut.OffsetX>>2)],h[19]=n[r+(ut.OffsetY>>2)],h[20]=n[r+(ut.Gamma>>2)],h[21]=n[r+(ut.HaloBuffer>>2)],h[22]=n[r+(ut.FillBuffer>>2)],h[23]=0,h[24]=n[r+(ut.HeightFactor>>2)],h[25]=(g&Ur.SkipHeightFactor)!==0?1:0,h[26]=n[r+(ut.FloorElevation>>2)],h[27]=0,h[28]=s,h[29]=o,h[30]=0,h[31]=0,h[32]=(g&Ur.SurfaceUseAbsZ)!==0?1:0,h[33]=n[r+(ut.SurfaceRelZNorm>>2)],h[34]=n[r+(ut.SurfaceAbsZ>>2)],h[35]=0,h.set(n.subarray(r+(ut.HaloColorR>>2),r+(ut.FillHiddenColorA>>2)+1),36),h[52]=n[r+(ut.HalfPointSizeX>>2)],h[53]=n[r+(ut.HalfPointSizeY>>2)],h[54]=a?1:0,h[55]=(g&Ur.LabelIndexIcon)!==0?1:0,h.set(l,56),h[72]=c,h[73]=f,h[74]=u,h[75]=0,h.set(d,76),this.pushUniform(h)}}class oO extends At{constructor(){super(M1),this.textureGroup=new Vs}ensureResources(t,n){if(this.uniformLayout)return;const{device:i}=t;this.setupUniformBatch(i,{size:tB,extras:[{buffer:n,size:xt,visibility:GPUShaderStage.FRAGMENT}]}),this.textureGroup.ensureResources(i)}getPipeline(t,n,i,r=!1){const s=n>0?n:28;return this.getOrCreatePipeline(`${s}:${i}${r?":flat":""}`,()=>{const o=this.textureGroup.layout;if(!this.uniformLayout||!o)return null;const{device:a,format:l}=t;return Pe(a,V({materialType:Z.LabelLine,bindGroupLayouts:[this.uniformLayout,o],buffers:[{arrayStride:s,attributes:[{shaderLocation:0,offset:0,format:"unorm16x4"},{shaderLocation:2,offset:8,format:"uint16x2"},{shaderLocation:1,offset:12,format:"float32x2"},{shaderLocation:3,offset:20,format:"float32x2"}]}],fragmentConstants:{isHalo:i==="halo"?1:0},targets:[Tt(l)]},r?{sampleCount:1}:{depthStencil:wt()}))})}getTextureBindGroup(t,n){return this.textureGroup.getBindGroup(t.device,n)}pushDraw(t,n,i,r){const s=this.uniformData;return s.set(t,0),s[16]=n[i+(bn.Opacity>>2)],s[17]=n[i+(bn.Scale>>2)],s[18]=n[i+(bn.TileToPixelRatio>>2)],s[19]=n[i+(bn.StyleZoom>>2)],s[20]=n[i+(bn.Gamma>>2)],s[21]=n[i+(bn.HaloBuffer>>2)],s[22]=n[i+(bn.FillBuffer>>2)],s[23]=0,s.set(n.subarray(i+(bn.HaloColorR>>2),i+(bn.FillColorA>>2)+1),24),s.set(r,32),this.pushUniform(s)}}class aO extends At{constructor(){super(T1),this.demGroup=new Mi}ensureResources(t,n){if(this.uniformLayout)return;const{device:i}=t;this.setupUniformBatch(i,{size:J4,extras:[{buffer:n,size:ar,visibility:GPUShaderStage.VERTEX}]}),this.demGroup.ensureResources(i)}getPipeline(t,n){const i=n>0?n:16;return this.getOrCreatePipeline(`${i}`,()=>{const r=this.demGroup.layout;return!this.uniformLayout||!r?null:Pe(t.device,{materialType:Z.PointAnchor,bindGroupLayouts:[this.uniformLayout,r],buffers:[{arrayStride:i,attributes:[{shaderLocation:0,offset:0,format:"unorm16x4"},{shaderLocation:1,offset:8,format:"sint16x2"},{shaderLocation:2,offset:12,format:"unorm8x4"}]}],targets:[{format:Ii}],sampleCount:1,depthStencil:Ih()})})}pushDraw(t,n,i,r,s,o,a,l,c,f){const u=this.uniformData,d=i[r+(ir.Flags>>2)];return u.set(t,0),u[16]=n[r+(ir.OffsetX>>2)],u[17]=n[r+(ir.OffsetY>>2)],u[18]=s,u[19]=o,u[20]=(d&Bs.SurfaceUseAbsZ)!==0?1:0,u[21]=n[r+(ir.SurfaceRelZNorm>>2)],u[22]=n[r+(ir.SurfaceAbsZ>>2)],u[23]=n[r+(ir.FloorElevation>>2)],u.set(a,24),u[40]=l,u[41]=c,u[42]=f,u[43]=0,this.pushUniform(u)}}class lO extends At{constructor(){super(P1),this.textureGroup=new Vs}ensureResources(t,n,i,r){if(this.uniformLayout)return;const{device:s}=t;this.setupUniformBatch(s,{size:$4,extras:[{buffer:n,size:Nn,visibility:GPUShaderStage.FRAGMENT},{buffer:i,size:xt,visibility:GPUShaderStage.FRAGMENT},...r.extras()]}),this.textureGroup.ensureResources(s)}getPipeline(t,n,i="receive"){const r=n>0?n:8;return this.getOrCreatePipeline(`${r}${Gn(i)}`,()=>{const s=this.textureGroup.layout;if(!this.uniformLayout||!s)return null;const{device:o,format:a}=t;return Pe(o,V({materialType:Z.MetricPoint,bindGroupLayouts:[this.uniformLayout,s],buffers:[{arrayStride:r,attributes:[{shaderLocation:0,offset:0,format:"unorm16x2"},{shaderLocation:1,offset:4,format:"uint16x2"}]}],targets:[Tt(a)],depthStencil:wt()},kn(i)))})}getTextureBindGroup(t,n){return this.textureGroup.getBindGroup(t.device,n)}pushDraw(t,n,i,r){const s=this.uniformData;return s.set(t,0),s.set(n.subarray(i+(Uo.ColorR>>2),i+(Uo.Sprite1Y>>2)+1),16),s[24]=n[i+(Uo.FloorElevation>>2)],s[25]=0,s[26]=0,s[27]=0,s.set(r,28),this.pushUniform(s)}}function yx(e){return{arrayStride:e,attributes:[{shaderLocation:0,offset:0,format:"unorm16x4"},{shaderLocation:1,offset:8,format:"sint16x2"},{shaderLocation:2,offset:12,format:"unorm8x4"}]}}class cO extends At{constructor(){super(I1),this.demGroup=new Mi}ensureResources(t,n,i,r){if(this.uniformLayout)return;const{device:s}=t;this.setupUniformBatch(s,{size:eB,extras:[{buffer:n,size:Nn,visibility:GPUShaderStage.FRAGMENT},{buffer:i,size:xt,visibility:GPUShaderStage.FRAGMENT},...r.extras()]}),this.demGroup.ensureResources(s)}getPipeline(t,n,i="receive"){const r=n>0?n:16;return this.getOrCreatePipeline(`${r}${Gn(i)}`,()=>{const s=this.demGroup.layout;if(!this.uniformLayout||!s)return null;const{device:o,format:a}=t;return Pe(o,V({materialType:Z.CircleMarker,bindGroupLayouts:[this.uniformLayout,s],buffers:[yx(r)],targets:[Tt(a)],depthStencil:wt()},kn(i)))})}getIdentifyPipeline(t,n){const i=n>0?n:16;return this.getOrCreatePipeline(`identify:${i}`,()=>{const r=this.demGroup.layout;return!this.uniformLayout||!r?null:Pe(t.device,V({materialType:Z.CircleMarker,bindGroupLayouts:[this.uniformLayout,r],buffers:[yx(i)],depthStencil:wt()},ei(kt.Plain)))})}pushDraw(t,n,i,r,s,o,a,l,c){const f=this.uniformData;return f.set(t,0),f.set(n.subarray(i+(Vo.ColorR>>2),i+(Vo.ColorA>>2)+1),16),f[20]=n[i+(Vo.Width>>2)],f[21]=r,f[22]=s,f[23]=0,f.set(o,24),f[40]=a,f[41]=l,f[42]=0,f[43]=0,f.set(c,44),this.pushUniform(f)}}class fO extends At{constructor(){super(_1)}ensureResources(t){this.uniformLayout||this.setupUniformBatch(t.device,{size:iB})}getPipeline(t,n){const i=n>0?n:8;return this.getOrCreatePipeline(`${i}`,()=>this.uniformLayout?Pe(t.device,{materialType:Z.DemElevation,bindGroupLayouts:[this.uniformLayout],buffers:[{arrayStride:i,attributes:[{shaderLocation:0,offset:0,format:"unorm16x2"},{shaderLocation:1,offset:4,format:"float32"}]}],targets:[{format:jo}],sampleCount:1}):null)}pushDraw(t){return this.pushUniform(t)}}function xx(e){return{arrayStride:e,attributes:[{shaderLocation:0,offset:0,format:"unorm16x2"},{shaderLocation:1,offset:4,format:"float32"}]}}class uO extends At{constructor(){super(X1),this.textureLayout=null,this.sampler=null,this.textureBindGroupRef=null,this.boundFlatView=null,this.identifyBindGroups=new WeakMap}get textureBindGroup(){return this.textureBindGroupRef}ensureResources(t,n,i,r){if(this.uniformLayout)return;const{device:s}=t;this.setupUniformBatch(s,{size:wB,extras:[{buffer:n,size:Nn,visibility:GPUShaderStage.FRAGMENT},{buffer:i,size:xt,visibility:GPUShaderStage.FRAGMENT},...r.extras()]}),this.textureLayout=s.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]}),this.sampler=s.createSampler({magFilter:"linear",minFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"})}ensureTextureBindGroup(t,n){!this.textureLayout||!this.sampler||!n||this.textureBindGroupRef&&this.boundFlatView===n||(this.textureBindGroupRef=t.createBindGroup({layout:this.textureLayout,entries:[{binding:0,resource:n},{binding:1,resource:this.sampler}]}),this.boundFlatView=n)}getPipeline(t,n,i="receive"){const r=n>0?n:8;return this.getOrCreatePipeline(`${r}${Gn(i)}`,()=>{const s=this.group0Layout(i);if(!s||!this.textureLayout)return null;const{device:o,format:a}=t;return Pe(o,V({materialType:Z.DemTerrain,bindGroupLayouts:[s,this.textureLayout],buffers:[xx(r)],targets:[{format:a}],depthStencil:ti()},kn(i)))})}getIdentifyPipeline(t,n){const i=n>0?n:8;return this.getOrCreatePipeline(`identify:${i}`,()=>{const r=this.group0Layout("receive");return!r||!this.textureLayout?null:Pe(t.device,V({materialType:Z.DemTerrain,bindGroupLayouts:[r,this.textureLayout],buffers:[xx(i)],depthStencil:ti()},ei(kt.DemTerrainTexel)))})}getIdentifyTextureBindGroup(t,n){if(!this.textureLayout||!this.sampler)return null;let i=this.identifyBindGroups.get(n);return i||(i=t.createBindGroup({layout:this.textureLayout,entries:[{binding:0,resource:n},{binding:1,resource:this.sampler}]}),this.identifyBindGroups.set(n,i)),i}pushDraw(t,n,i,r,s){const o=this.uniformData;return o.set(t,0),o.set(n,16),o[32]=i.demScale,o[33]=i.demCenterElevation,o[34]=i.demMinElevation,o[35]=0,o[36]=i.modelScale,o[37]=i.demShadingIntensity,o[38]=0,o[39]=0,o[40]=r[0],o[41]=r[1],o[42]=r[2],o[43]=s,this.pushUniform(o)}}function wx(e){return{arrayStride:e,attributes:[{shaderLocation:0,offset:0,format:"unorm16x2"},{shaderLocation:1,offset:4,format:"float32"},{shaderLocation:2,offset:16,format:"uint32"},{shaderLocation:3,offset:20,format:"uint32"},{shaderLocation:4,offset:12,format:"sint8x4"}]}}class dO extends At{constructor(){super(C1),this.textureLayout=null,this.sampler=null,this.tierBindGroups=new WeakMap,this.cachedDemView=null,this.placeholderTexture=null,this.placeholderView=null}ensureResources(t,n,i,r){if(this.uniformLayout)return;const{device:s}=t;this.setupUniformBatch(s,{size:rB,extras:[{buffer:n,size:Nn,visibility:GPUShaderStage.FRAGMENT},{buffer:i,size:xt,visibility:GPUShaderStage.FRAGMENT},...r.extras()]}),this.textureLayout=s.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.VERTEX,texture:{sampleType:"float"}},{binding:2,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]}),this.sampler=s.createSampler({magFilter:"linear",minFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"})}getTierBindGroup(t,n,i){if(!this.textureLayout||!this.sampler||!n)return null;const r=i!=null?i:this.ensurePlaceholder(t);this.cachedDemView!==r&&(this.tierBindGroups=new WeakMap,this.cachedDemView=r);let s=this.tierBindGroups.get(n);return s||(s=t.createBindGroup({layout:this.textureLayout,entries:[{binding:0,resource:n},{binding:1,resource:r},{binding:2,resource:this.sampler}]}),this.tierBindGroups.set(n,s),s)}getPipeline(t,n,i="receive",r=!1){const s=n>0?n:24,o=`${s}${Gn(i)}${r?":hidden":""}`;return this.getOrCreatePipeline(o,()=>{const a=this.group0Layout(i);if(!a||!this.textureLayout)return null;const{device:l,format:c}=t,f=kn(i);return Pe(l,ie(V({materialType:Z.MapMesh,bindGroupLayouts:[a,this.textureLayout],buffers:[wx(s)],targets:[Tt(c)],depthStencil:r?{format:Gt,depthWriteEnabled:!1,depthCompare:"greater",depthBias:2,depthBiasSlopeScale:1}:ti(),cull:!r},f),{fragmentConstants:ie(V({},f.fragmentConstants),{surfaceFill:r?0:1})}))})}getIdentifyPipeline(t,n){const i=n>0?n:24;return this.getOrCreatePipeline(`identify:${i}`,()=>{const r=this.group0Layout("receive");return!r||!this.textureLayout?null:Pe(t.device,V({materialType:Z.MapMesh,bindGroupLayouts:[r,this.textureLayout],buffers:[wx(i)],depthStencil:ti()},ei(kt.MapMeshTexel)))})}pushDraw(t,n,i,r,s){var a;const o=this.uniformData;o.set(t,0),o.set(n,16),o[32]=i.scaleX,o[33]=i.scaleY,o[34]=i.texShift,o[35]=i.heightFactor,o[36]=i.absZ?1:0,o[37]=i.demMode?i.demScale:0,o[38]=i.demCenterElevation,o[39]=i.modelScale,o[40]=r[0],o[41]=r[1],o[42]=r[2],o[43]=s;for(let l=0;l<4;l++)o[44+l]=(a=i.surfaceColor[l])!=null?a:0;return this.pushUniform(o)}ensurePlaceholder(t){return(!this.placeholderTexture||!this.placeholderView)&&(this.placeholderTexture=t.createTexture({size:{width:1,height:1},format:jo,usage:GPUTextureUsage.TEXTURE_BINDING}),this.placeholderView=this.placeholderTexture.createView()),this.placeholderView}}const hO={fill:0,depth:1,depthClear:2,labeling:3};function pO(e){const t={shaderLocation:0,offset:0,format:"unorm16x2"},n={shaderLocation:1,offset:4,format:"float32"};return e>=32?[t,n,{shaderLocation:2,offset:16,format:"uint32"},{shaderLocation:3,offset:20,format:"uint32"},{shaderLocation:4,offset:8,format:"sint8x4"},{shaderLocation:5,offset:24,format:"unorm8x4"}]:[t,n,{shaderLocation:2,offset:8,format:"uint32"},{shaderLocation:3,offset:12,format:"uint32"},{shaderLocation:4,offset:0,format:"sint8x4"},{shaderLocation:5,offset:e>=20?16:12,format:"unorm8x4"}]}class gO extends At{constructor(){super(F1),this.demGroup=new Mi}ensureResources(t,n,i,r){if(this.uniformLayout)return;const{device:s}=t;this.setupUniformBatch(s,{size:sB,extras:[{buffer:n,size:Nn,visibility:GPUShaderStage.FRAGMENT},{buffer:i,size:xt,visibility:GPUShaderStage.FRAGMENT},...r.extras()]}),this.demGroup.ensureResources(s)}getPipeline(t,n,i,r="receive"){const s=n>0?n:32;return this.getOrCreatePipeline(`${s}|${i}${Gn(r)}`,()=>{const o=this.group0Layout(r),a=this.demGroup.layout;if(!o||!a)return null;const{device:l,format:c}=t,f=r==="caster",u=kn(r),d=i==="labeling"?{format:Ii}:i==="fill"?Tt(c):{format:c,writeMask:0};return Pe(l,V(ie(V({materialType:Z.Mesh,bindGroupLayouts:[o,a],buffers:[{arrayStride:s,attributes:pO(s)}],targets:[d],depthStencil:V({format:Gt,depthWriteEnabled:!0,depthCompare:i==="depthClear"?"always":"less"},i==="depth"?{depthBias:1,depthBiasSlopeScale:1}:{}),cull:!f},u),{fragmentConstants:ie(V({},u.fragmentConstants),{meshMode:hO[i]})}),i==="labeling"?{sampleCount:1}:{}))})}pushDraw(t,n,i,r,s){var a,l;const o=this.uniformData;o.set(t,0),o.set(n,16);for(let c=0;c<4;c++)o[32+c]=(a=i.color[c])!=null?a:0,o[36+c]=(l=i.color2[c])!=null?l:0;return o[40]=i.heightFactor,o[41]=i.floorElevation,o[42]=i.gradientEdge0,o[43]=i.gradientEdge1,o[44]=i.absZ?1:0,o[45]=i.demScale,o[46]=i.demCenterElevation,o[47]=i.modelScale,o[48]=i.gradient?1:0,o.fill(0,49,52),o[52]=r[0],o[53]=r[1],o[54]=r[2],o[55]=s,this.pushUniform(o)}}const mO={labeling:16,identify:8};class vO extends At{constructor(){super(L1),this.demGroup=new Mi}ensureResources(t,n,i,r){if(this.uniformLayout)return;const{device:s}=t;this.setupUniformBatch(s,{size:oB,stride:aB,extras:[{buffer:n,size:Nn,visibility:GPUShaderStage.FRAGMENT},{buffer:i,size:xt,visibility:GPUShaderStage.FRAGMENT},...r.extras()]}),this.demGroup.ensureResources(s)}getPipeline(t,n,i,r="receive"){const s=n>0?n:24,o=`${s}|${i}${Gn(r)}`;return this.getOrCreatePipeline(o,()=>{const a=this.group0Layout(r),l=this.demGroup.layout;if(!a||!l)return null;const{device:c,format:f}=t,u=s===16,d=i==="prepass",h=i==="gradientColor",g=mO[i],y=g!==void 0;let p;y?p=Z.PolygonExtrusionLabeling:d?p=Z.PolygonExtrusionDepth:h?p=u?Z.PolygonExtrusionGradientWall:Z.PolygonExtrusionGradient:p=Z.PolygonExtrusion;const v=[{shaderLocation:0,offset:0,format:"unorm16x2"},{shaderLocation:1,offset:4,format:"float32"},{shaderLocation:3,offset:u?8:12,format:"sint16x2"}];return y?v.push({shaderLocation:5,offset:g,format:"unorm8x4"}):d||(h?u||v.push({shaderLocation:2,offset:24,format:"float32"}):v.push({shaderLocation:5,offset:u?12:20,format:"unorm8x4"})),Pe(c,V(V({materialType:p,bindGroupLayouts:[a,l],buffers:[{arrayStride:s,attributes:v}],targets:[y?{format:Ii}:{format:f,writeMask:d?0:GPUColorWrite.ALL,blend:d?void 0:gx()}],cull:!u,depthStencil:{format:Gt,depthWriteEnabled:d||y,depthCompare:d||y?"less":"equal"}},y?{sampleCount:1}:{}),kn(r)))})}getIdentifyPipeline(t,n){return n===16?null:this.getPipeline(t,n,"identify")}pushDraw(t,n,i,r,s,o,a,l,c,f){const u=this.uniformData;return u.set(t,0),u.set(n,16),u[32]=i[0],u[33]=i[1],u[34]=i[2],u[35]=i[3],u.fill(0,36,44),u[42]=o,u[43]=a,u.set(r,44),u[60]=s[0],u[61]=s[1],u[62]=s[2],u[63]=s[3],u[64]=l,u.fill(0,65,68),u[68]=c[0],u[69]=c[1],u[70]=c[2],u[71]=f,this.pushUniform(u)}pushDrawGradient(t,n,i,r,s,o,a,l,c,f,u,d,h,g=0,y=1){const p=this.uniformData;return p.set(t,0),p.set(n,16),p[32]=i[0],p[33]=i[1],p[34]=i[2],p[35]=i[3],p[36]=r[0],p[37]=r[1],p[38]=r[2],p[39]=r[3],p[40]=s,p[41]=o,p[42]=c,p[43]=f,p.set(a,44),p[60]=l[0],p[61]=l[1],p[62]=l[2],p[63]=l[3],p[64]=u,p[65]=g,p[66]=y,p[67]=0,p[68]=d[0],p[69]=d[1],p[70]=d[2],p[71]=h,this.pushUniform(p)}}class yO extends At{constructor(){super(B1),this.demGroup=new Mi,this.textureGroup=new Vs}ensureResources(t,n){if(this.uniformLayout)return;const{device:i}=t;this.setupUniformBatch(i,{size:lB,extras:[{buffer:n,size:xt,visibility:GPUShaderStage.FRAGMENT}]}),this.textureGroup.ensureResources(i),this.demGroup.ensureResources(i)}getPipeline(t,n){const i=n>0?n:28;return this.getOrCreatePipeline(`${i}`,()=>{const r=this.textureGroup.layout,s=this.demGroup.layout;if(!this.uniformLayout||!r||!s)return null;const{device:o,format:a}=t;return Pe(o,{materialType:Z.PolygonExtrusionTexture,bindGroupLayouts:[this.uniformLayout,r,s],buffers:[{arrayStride:i,attributes:[{shaderLocation:0,offset:0,format:"unorm16x2"},{shaderLocation:1,offset:4,format:"float32"},{shaderLocation:4,offset:8,format:"sint16x2"},{shaderLocation:3,offset:12,format:"float32x2"},{shaderLocation:2,offset:20,format:"uint8x2"}]}],targets:[Tt(a)],cull:!0,depthStencil:{format:Gt,depthWriteEnabled:!1,depthCompare:"less-equal"}})})}getTextureBindGroup(t,n){return this.textureGroup.getBindGroup(t.device,n)}pushDraw(t,n,i,r,s,o,a,l){const c=this.uniformData;return c.set(t,0),c[16]=n.wallPadding[0],c[17]=n.wallPadding[1],c[18]=n.wallPadding[2],c[19]=n.wallPadding[3],c[20]=n.texturePadding[0],c[21]=n.texturePadding[1],c[22]=n.texturePadding[2],c[23]=n.texturePadding[3],c[24]=n.partCount[0],c[25]=n.partCount[1],c[26]=n.maxInterval[0],c[27]=n.maxInterval[1],c[28]=n.sliceSize[0],c[29]=n.sliceSize[1],c[30]=n.layoutMode[0],c[31]=n.layoutMode[1],c.set(i,32),c[48]=r[0],c[49]=r[1],c[50]=r[2],c[51]=r[3],c[52]=s,c[53]=o,c[54]=0,c[55]=0,c[56]=a[0],c[57]=a[1],c[58]=a[2],c[59]=l,this.pushUniform(c)}}function Ax(){return[{arrayStride:vB,stepMode:"vertex",attributes:[{shaderLocation:0,offset:0,format:"float32x3"},{shaderLocation:1,offset:12,format:"float32x3"},{shaderLocation:2,offset:24,format:"float32x2"},{shaderLocation:9,offset:32,format:"float32x2"},{shaderLocation:10,offset:40,format:"float32x2"}]},{arrayStride:yB,stepMode:"instance",attributes:[{shaderLocation:3,offset:0,format:"unorm16x4"},{shaderLocation:4,offset:8,format:"float32x3"},{shaderLocation:5,offset:20,format:"float32x3"},{shaderLocation:6,offset:32,format:"float32x3"},{shaderLocation:7,offset:48,format:"float32"},{shaderLocation:8,offset:44,format:"float32"},{shaderLocation:11,offset:52,format:"unorm8x4"}]}]}class xO extends At{constructor(){super(Y1),this.textureLayout=null,this.sampler=null,this.textureBindGroupRef=null,this.boundDemView=null,this.placeholderTexture=null,this.placeholderView=null,this.colorTextureLayout=null,this.colorSampler=null,this.whiteTexture=null,this.whiteView=null,this.colorBindGroups=new Map}get textureBindGroup(){return this.textureBindGroupRef}ensureResources(t,n,i){if(this.uniformLayout)return;const{device:r}=t;this.setupUniformBatch(r,{size:gB,stride:mB,extras:[{buffer:n,size:xt,visibility:GPUShaderStage.FRAGMENT},...i.extras()]}),this.textureLayout=r.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.VERTEX,sampler:{type:"filtering"}}]}),this.sampler=r.createSampler({magFilter:"linear",minFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}),this.colorTextureLayout=r.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:2,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:3,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}}]}),this.colorSampler=r.createSampler({magFilter:"linear",minFilter:"linear",mipmapFilter:"linear",addressModeU:"repeat",addressModeV:"repeat"})}ensureTextureBindGroup(t,n){if(!this.textureLayout||!this.sampler)return;const i=n!=null?n:this.ensurePlaceholder(t);this.textureBindGroupRef&&this.boundDemView===i||(this.textureBindGroupRef=t.createBindGroup({layout:this.textureLayout,entries:[{binding:0,resource:i},{binding:1,resource:this.sampler}]}),this.boundDemView=i)}getPipeline(t,n="receive"){return this.getOrCreatePipeline(`main${Gn(n)}`,()=>{const i=this.group0Layout(n);if(!i||!this.textureLayout||!this.colorTextureLayout)return null;const{device:r,format:s}=t;return Pe(r,V({materialType:Z.GltfModel,bindGroupLayouts:[i,this.textureLayout,this.colorTextureLayout],buffers:Ax(),targets:[Tt(s)],depthStencil:ti()},kn(n)))})}getIdentifyPipeline(t){return this.getOrCreatePipeline("identify",()=>{const n=this.group0Layout("receive");return!n||!this.textureLayout||!this.colorTextureLayout?null:Pe(t.device,V({materialType:Z.GltfModel,bindGroupLayouts:[n,this.textureLayout,this.colorTextureLayout],buffers:Ax(),depthStencil:ti()},ei(kt.Plain)))})}pushDraw(t,n,i,r,s,o){const a=this.uniformData;return a.set(t,0),a.set(n,16),a[32]=o.color[0],a[33]=o.color[1],a[34]=o.color[2],a[35]=o.color[3],a[36]=o.demScale,a[37]=o.demCenterElevation,a[38]=o.invTileScaleXY,a[39]=o.heightUnFactor,a[40]=o.metallic,a[41]=o.roughness,a[42]=o.lightingModel,a[43]=o.nearCameraFade,a[44]=o.camOriginRel[0],a[45]=o.camOriginRel[1],a[46]=o.camOriginRel[2],a[47]=o.fogInvDistance,a.set(i,48),a[60]=r,a[61]=o.gltfFlags,a[62]=o.surfaceRelZ,a[63]=o.surfaceAbsZ,a[64]=s[0],a[65]=s[1],a[66]=s[2],a[67]=0,a[68]=s[3],a[69]=s[4],a[70]=s[5],a[71]=0,a[72]=s[6],a[73]=s[7],a[74]=s[8],a[75]=0,a[76]=o.hasPbrTexture?1:0,a[77]=o.scaleX,a[78]=o.scaleY,a[79]=o.scaleZ,this.pushUniform(a)}getColorBindGroup(t,n,i,r,s,o,a){if(!this.colorTextureLayout||!this.colorSampler)return null;const{device:l}=t,c=`${i?n:0}:${s?r:0}:${a?o:0}`;let f=this.colorBindGroups.get(c);if(!f){const u=this.ensureWhite(l);f=l.createBindGroup({layout:this.colorTextureLayout,entries:[{binding:0,resource:i?i.createView():u},{binding:1,resource:this.colorSampler},{binding:2,resource:s?s.createView():u},{binding:3,resource:a?a.createView():u}]}),this.colorBindGroups.set(c,f)}return f}invalidateTextures(){this.colorBindGroups.clear()}ensureWhite(t){return(!this.whiteTexture||!this.whiteView)&&(this.whiteTexture=t.createTexture({size:{width:1,height:1},format:"rgba8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST}),t.queue.writeTexture({texture:this.whiteTexture},new Uint8Array([255,255,255,255]),{bytesPerRow:4,rowsPerImage:1},{width:1,height:1}),this.whiteView=this.whiteTexture.createView()),this.whiteView}ensurePlaceholder(t){return(!this.placeholderTexture||!this.placeholderView)&&(this.placeholderTexture=t.createTexture({size:{width:1,height:1},format:jo,usage:GPUTextureUsage.TEXTURE_BINDING}),this.placeholderView=this.placeholderTexture.createView()),this.placeholderView}}const bx=new Float32Array([-1,-1,1,-1,-1,1,1,1]);class wO{constructor(){this.pipeline=null,this.vertexBuffer=null,this.uniformBuffer=null,this.bindGroup=null,this.uniformData=new Float32Array(k1)}ensureResources(t,n){if(this.pipeline)return;const{device:i,format:r}=t,s=i.createBuffer({size:bx.byteLength,usage:GPUBufferUsage.VERTEX,mappedAtCreation:!0});new Float32Array(s.getMappedRange()).set(bx),s.unmap(),this.vertexBuffer=s,this.uniformBuffer=i.createBuffer({size:U1,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});const o=i.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform",minBindingSize:U1}},{binding:1,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform",minBindingSize:xt}}]});this.bindGroup=i.createBindGroup({layout:o,entries:[{binding:0,resource:{buffer:this.uniformBuffer}},{binding:1,resource:{buffer:n}}]}),this.pipeline=Pe(i,{materialType:Z.Sky,bindGroupLayouts:[o],buffers:[{arrayStride:8,attributes:[{shaderLocation:0,offset:0,format:"float32x2"}]}],targets:[Tt(r)],topology:"triangle-strip",depthStencil:wt()})}setUniform(t,n,i,r){if(!this.uniformBuffer)return;const s=this.uniformData;s.set(n,0),s.set(i,16),s[32]=r,s[33]=0,s[34]=0,s[35]=0,t.queue.writeBuffer(this.uniformBuffer,0,s)}draw(t){!this.pipeline||!this.vertexBuffer||!this.bindGroup||(t.setPipeline(this.pipeline),t.setBindGroup(0,this.bindGroup),t.setVertexBuffer(0,this.vertexBuffer),t.draw(4))}}const Sx=new Float32Array([-1,-1,1,-1,-1,1,1,1]),Fc="rgba8unorm";class AO{constructor(){this.vertexBuffer=null,this.uniformBuffer=null,this.uniformData=new Float32Array(4),this.linearSampler=null,this.nearestSampler=null,this.sceneTexture=null,this.sceneTextureView=null,this.edgeTexture=null,this.edgeTextureView=null,this.weightTexture=null,this.weightTextureView=null,this.areaTexture=null,this.searchTexture=null,this.lutRequested=!1,this.fxaaPipeline=null,this.fxaaLayout=null,this.fxaaBindGroup=null,this.smaaEdgePipeline=null,this.smaaEdgeLayout=null,this.smaaEdgeBindGroup=null,this.smaaWeightPipeline=null,this.smaaWeightLayout=null,this.smaaWeightBindGroup=null,this.smaaBlendPipeline=null,this.smaaBlendLayout=null,this.smaaBlendBindGroup=null,this.width=0,this.height=0}get sceneView(){return this.sceneTextureView}ensureReady(t,n){return n==="msaa"?!1:(this.ensureCommon(t),this.ensureTargets(t),n==="fxaa"?(this.ensureFxaa(t),this.fxaaBindGroup!==null):(this.requestLuts(t.device),!this.areaTexture||!this.searchTexture?!1:(this.ensureSmaa(t),this.smaaBlendBindGroup!==null)))}draw(t,n,i,r){const{device:s,canvas:o}=n;if(!this.uniformBuffer||!this.vertexBuffer)return;const a=this.uniformData;if(a[0]=o.width,a[1]=o.height,a[2]=1/o.width,a[3]=1/o.height,s.queue.writeBuffer(this.uniformBuffer,0,a),i==="fxaa"){this.drawQuadPass(t,r,this.fxaaPipeline,this.fxaaBindGroup);return}this.drawQuadPass(t,this.edgeTextureView,this.smaaEdgePipeline,this.smaaEdgeBindGroup),this.drawQuadPass(t,this.weightTextureView,this.smaaWeightPipeline,this.smaaWeightBindGroup),this.drawQuadPass(t,r,this.smaaBlendPipeline,this.smaaBlendBindGroup)}drawQuadPass(t,n,i,r){if(!n||!i||!r||!this.vertexBuffer)return;const s=t.beginRenderPass({colorAttachments:[{view:n,clearValue:{r:0,g:0,b:0,a:0},loadOp:"clear",storeOp:"store"}]});s.setPipeline(i),s.setBindGroup(0,r),s.setVertexBuffer(0,this.vertexBuffer),s.draw(4),s.end()}ensureCommon(t){const{device:n}=t;if(this.vertexBuffer)return;const i=n.createBuffer({size:Sx.byteLength,usage:GPUBufferUsage.VERTEX,mappedAtCreation:!0});new Float32Array(i.getMappedRange()).set(Sx),i.unmap(),this.vertexBuffer=i,this.uniformBuffer=n.createBuffer({size:bc,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.linearSampler=n.createSampler({magFilter:"linear",minFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}),this.nearestSampler=n.createSampler({magFilter:"nearest",minFilter:"nearest",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"})}ensureTargets(t){var a,l,c;const n=Math.max(1,t.canvas.width),i=Math.max(1,t.canvas.height);if(this.sceneTexture&&this.width===n&&this.height===i)return;const{device:r}=t,s={width:n,height:i},o=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING;(a=this.sceneTexture)==null||a.destroy(),this.sceneTexture=r.createTexture({size:s,format:t.format,usage:o}),this.sceneTextureView=this.sceneTexture.createView(),(l=this.edgeTexture)==null||l.destroy(),this.edgeTexture=r.createTexture({size:s,format:Fc,usage:o}),this.edgeTextureView=this.edgeTexture.createView(),(c=this.weightTexture)==null||c.destroy(),this.weightTexture=r.createTexture({size:s,format:Fc,usage:o}),this.weightTextureView=this.weightTexture.createView(),this.width=n,this.height=i,this.fxaaBindGroup=null,this.smaaEdgeBindGroup=null,this.smaaWeightBindGroup=null,this.smaaBlendBindGroup=null}requestLuts(t){if(this.lutRequested)return;this.lutRequested=!0;const n=(i,r,s,o)=>Fe(this,null,function*(){const a=yield(yield fetch(i)).blob(),l=yield createImageBitmap(a,{premultiplyAlpha:"none",colorSpaceConversion:"none"}),c=t.createTexture({size:{width:r,height:s},format:"rgba8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT});return t.queue.copyExternalImageToTexture({source:l,flipY:o},{texture:c},{width:r,height:s}),l.close(),c});n(wy,160,560,!1).then(i=>{this.areaTexture=i,this.smaaWeightBindGroup=null}).catch(i=>console.error("[render] SMAA area LUT load failed",i)),n(Ay,64,16,!0).then(i=>{this.searchTexture=i,this.smaaWeightBindGroup=null}).catch(i=>console.error("[render] SMAA search LUT load failed",i))}createSingleTextureLayout(t){return t.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform",minBindingSize:bc}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:2,visibility:GPUShaderStage.FRAGMENT,sampler:{}}]})}quadPipeline(t,n,i,r){return Pe(t.device,{materialType:n,bindGroupLayouts:[i],buffers:[{arrayStride:8,attributes:[{shaderLocation:0,offset:0,format:"float32x2"}]}],targets:[{format:r}],topology:"triangle-strip",sampleCount:1})}ensureFxaa(t){const{device:n}=t;this.fxaaPipeline||(this.fxaaLayout=this.createSingleTextureLayout(n),this.fxaaPipeline=this.quadPipeline(t,Z.Fxaa,this.fxaaLayout,t.format)),!this.fxaaBindGroup&&this.fxaaLayout&&this.sceneTextureView&&(this.fxaaBindGroup=n.createBindGroup({layout:this.fxaaLayout,entries:[{binding:0,resource:{buffer:this.uniformBuffer}},{binding:1,resource:this.sceneTextureView},{binding:2,resource:this.linearSampler}]}))}ensureSmaa(t){const{device:n}=t;this.smaaEdgePipeline||(this.smaaEdgeLayout=this.createSingleTextureLayout(n),this.smaaEdgePipeline=this.quadPipeline(t,Z.SmaaEdge,this.smaaEdgeLayout,Fc),this.smaaWeightLayout=n.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform",minBindingSize:bc}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:2,visibility:GPUShaderStage.FRAGMENT,sampler:{}},{binding:3,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:4,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:5,visibility:GPUShaderStage.FRAGMENT,sampler:{}}]}),this.smaaWeightPipeline=this.quadPipeline(t,Z.SmaaWeight,this.smaaWeightLayout,Fc),this.smaaBlendLayout=n.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform",minBindingSize:bc}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:2,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:3,visibility:GPUShaderStage.FRAGMENT,sampler:{}}]}),this.smaaBlendPipeline=this.quadPipeline(t,Z.SmaaBlend,this.smaaBlendLayout,t.format)),!this.smaaEdgeBindGroup&&this.smaaEdgeLayout&&this.sceneTextureView&&(this.smaaEdgeBindGroup=n.createBindGroup({layout:this.smaaEdgeLayout,entries:[{binding:0,resource:{buffer:this.uniformBuffer}},{binding:1,resource:this.sceneTextureView},{binding:2,resource:this.linearSampler}]})),!this.smaaWeightBindGroup&&this.smaaWeightLayout&&this.edgeTextureView&&this.areaTexture&&this.searchTexture&&(this.smaaWeightBindGroup=n.createBindGroup({layout:this.smaaWeightLayout,entries:[{binding:0,resource:{buffer:this.uniformBuffer}},{binding:1,resource:this.edgeTextureView},{binding:2,resource:this.linearSampler},{binding:3,resource:this.areaTexture.createView()},{binding:4,resource:this.searchTexture.createView()},{binding:5,resource:this.nearestSampler}]})),!this.smaaBlendBindGroup&&this.smaaBlendLayout&&this.sceneTextureView&&this.weightTextureView&&(this.smaaBlendBindGroup=n.createBindGroup({layout:this.smaaBlendLayout,entries:[{binding:0,resource:{buffer:this.uniformBuffer}},{binding:1,resource:this.sceneTextureView},{binding:2,resource:this.weightTextureView},{binding:3,resource:this.linearSampler}]}))}}class bO{constructor(){this.pipeline=null,this.vertexBuffer=null,this.uniformBuffer=null,this.bindGroup=null,this.uniformData=new Float32Array(V1)}ensureResources(t){if(this.pipeline)return;const{device:n,format:i}=t,r={randomSeed:hB},s=Pg(r,Sc),o=new Float32Array(Sc*4);for(let f=0;f<Sc;f++){const u=s[f];o[f*4]=u[0],o[f*4+1]=u[1],o[f*4+2]=u[2],o[f*4+3]=cs(r,0,1)}const a=n.createBuffer({size:o.byteLength,usage:GPUBufferUsage.VERTEX,mappedAtCreation:!0});new Float32Array(a.getMappedRange()).set(o),a.unmap(),this.vertexBuffer=a;const l=n.createBuffer({size:W1,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});this.uniformBuffer=l;const c=n.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform",minBindingSize:W1}}]});this.bindGroup=n.createBindGroup({layout:c,entries:[{binding:0,resource:{buffer:l}}]}),this.pipeline=Pe(n,{materialType:Z.Stars,bindGroupLayouts:[c],buffers:[{arrayStride:pB,attributes:[{shaderLocation:0,offset:0,format:"float32x3"},{shaderLocation:1,offset:12,format:"float32"}]}],targets:[Tt(i)],topology:"point-list",depthStencil:wt()})}setUniform(t,n,i){if(!this.uniformBuffer)return;const r=this.uniformData;r.set(n,0),r[16]=i,r[17]=0,r[18]=0,r[19]=0,t.queue.writeBuffer(this.uniformBuffer,0,r)}draw(t){!this.pipeline||!this.vertexBuffer||!this.bindGroup||(t.setPipeline(this.pipeline),t.setBindGroup(0,this.bindGroup),t.setVertexBuffer(0,this.vertexBuffer),t.draw(Sc))}}const Ex=new Float32Array([-1,-1,1,-1,-1,1,1,1]);class SO{constructor(){this.pipeline=null,this.backgroundPipeline=null,this.vertexBuffer=null,this.uniformBuffer=null,this.bindGroup=null}ensureResources(t){if(this.pipeline)return;const{device:n,format:i}=t,r=n.createBuffer({size:Ex.byteLength,usage:GPUBufferUsage.VERTEX,mappedAtCreation:!0});new Float32Array(r.getMappedRange()).set(Ex),r.unmap(),this.vertexBuffer=r;const s=n.createBuffer({size:H1,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});this.uniformBuffer=s;const o=n.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform",minBindingSize:H1}}]});this.bindGroup=n.createBindGroup({layout:o,entries:[{binding:0,resource:{buffer:s}}]});const a=[{arrayStride:8,attributes:[{shaderLocation:0,offset:0,format:"float32x2"}]}];this.pipeline=Pe(n,{materialType:Z.GlobeHalo,bindGroupLayouts:[o],buffers:a,targets:[{format:i,blend:{color:{srcFactor:"src-alpha",dstFactor:"one",operation:"add"},alpha:{srcFactor:"src-alpha",dstFactor:"one",operation:"add"}}}],topology:"triangle-strip",depthStencil:wt()}),this.backgroundPipeline=Pe(n,{materialType:Z.GlobeHaloBackground,bindGroupLayouts:[o],buffers:a,targets:[Tt(i)],topology:"triangle-strip",depthStencil:wt()})}setUniform(t,n){!this.uniformBuffer||n.length<Ah||t.queue.writeBuffer(this.uniformBuffer,0,n,0,Ah)}draw(t){!this.pipeline||!this.vertexBuffer||!this.bindGroup||(t.setPipeline(this.pipeline),t.setBindGroup(0,this.bindGroup),t.setVertexBuffer(0,this.vertexBuffer),t.draw(4))}drawBackground(t){!this.backgroundPipeline||!this.vertexBuffer||!this.bindGroup||(t.setPipeline(this.backgroundPipeline),t.setBindGroup(0,this.bindGroup),t.setVertexBuffer(0,this.vertexBuffer),t.draw(4))}}class EO{constructor(){this.bufferRef=null,this.texture=null,this.viewRef=null,this.samplerRef=null,this.data=new Float32Array(R1)}get view(){return this.viewRef}ensure(t){return this.bufferRef?this:(this.bufferRef=t.createBuffer({size:z1,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.texture=t.createTexture({size:{width:N1,height:N1},format:Gt,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),this.viewRef=this.texture.createView(),this.samplerRef=t.createSampler({compare:"less-equal",magFilter:"linear",minFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}),this)}extras(){return[{buffer:this.bufferRef,size:z1,visibility:GPUShaderStage.FRAGMENT},{texture:this.viewRef,sampleType:"depth",visibility:GPUShaderStage.FRAGMENT},{sampler:this.samplerRef,samplerType:"comparison",visibility:GPUShaderStage.FRAGMENT}]}write(t,n,i,r){if(!this.bufferRef)return;const s=this.data;i?s.set(n,0):s.fill(0,0,wh);const o=fB;s[o]=r.x,s[o+1]=r.y,s[o+2]=r.width,s[o+3]=r.height,t.queue.writeBuffer(this.bufferRef,0,s)}draw(t,n,i){var f,u,d,h,g,y,p,v,A,w;if(!this.viewRef)return;const r=t.beginRenderPass({colorAttachments:[],depthStencilAttachment:{view:this.viewRef,depthClearValue:1,depthLoadOp:"clear",depthStoreOp:"store"}}),{extrusion:s,mapMesh:o,mesh:a,gltf:l,terrain:c}=n.shadow;if(s.length>0){const S=i.extrusion.demGroup.bindGroup;S&&r.setBindGroup(1,S),nn(r,s,(u=(f=i.extrusion.batch)==null?void 0:f.shadowBindGroup)!=null?u:null)}if(o.length>0&&nn(r,o,(h=(d=i.mapMesh.batch)==null?void 0:d.shadowBindGroup)!=null?h:null),a.length>0){const S=i.mesh.demGroup.bindGroup;S&&r.setBindGroup(1,S),nn(r,a,(y=(g=i.mesh.batch)==null?void 0:g.shadowBindGroup)!=null?y:null)}if(l.length>0){const S=i.gltf.textureBindGroup;S&&r.setBindGroup(1,S),J1(r,l,(v=(p=i.gltf.batch)==null?void 0:p.shadowBindGroup)!=null?v:null)}c.length>0&&i.terrain.textureBindGroup&&(r.setBindGroup(1,i.terrain.textureBindGroup),nn(r,c,(w=(A=i.terrain.batch)==null?void 0:A.shadowBindGroup)!=null?w:null)),r.end()}}const TO=1/64;function Mh(e,t){return t?Math.max(e.globeRatio,Y4):0}function Tx(e){e[2]=(e[2]+e[3])*.5,e[6]=(e[6]+e[7])*.5,e[10]=(e[10]+e[11])*.5,e[14]=(e[14]+e[15])*.5}function PO(e){const t=e[we.IdentifyRequestId>>2],n=e[we.IdentifyWidth>>2],i=e[we.IdentifyHeight>>2];return t!==0&&n>0&&i>0?{id:t,width:n,height:i}:null}class IO{constructor(){this.state={vpF64:new Float64Array(16),cameraF64:new Float64Array(3),replicaMin:0,replicaMax:0,labelingDepthTestDisabled:!1,demMode:!1,demTextureSizePx:0,demScale:1,demCenterElevation:0,demMinElevation:0,demShadingIntensity:0,demTextureMatrixF64:new Float64Array(16),demFbVpF64:new Float64Array(16),lightData:new Float32Array(xh),demLightData:new Float32Array(xh),fogData:new Float32Array(cB),skyEnabled:!1,skyViewTransposedF32:new Float32Array(16),skyProjInvertedF32:new Float32Array(16),shadowEnabled:!1,shadowData:new Float32Array(wh),shadowVpF64:new Float64Array(16),backgroundColor:{r:0,g:0,b:0,a:0},identifyRequest:null,flatLevelCount:0,identifyFlatLevelMask:0,flatLevelMvpF64:Array.from({length:$l},()=>new Float64Array(16)),flatLevelTexF64:Array.from({length:$l},()=>new Float64Array(16)),mapMeshScaleX:Ec,mapMeshScaleY:Tc,mapMeshTexShift:0,mapMeshVpF64:new Float64Array(16),globeMode:!1,globeRatio:0,globeEcefMvpF32:new Float32Array(16),globeVpF32:new Float32Array(16),globeCameraMerc:new Float64Array(2),globeVpAtCenterF32:new Float32Array(4),globeCameraEcef:new Float32Array(3),starsMatrixF32:new Float32Array(16),starsIntensity:0,globeHaloData:new Float32Array(20),materialOffsets:[]}}read(t){const{u32:n,i32:i,f32:r,f64:s}=t,o=this.state;return this.readCamera(s),o.replicaMin=i[we.ReplicaMin>>2],o.replicaMax=i[we.ReplicaMax>>2],o.identifyRequest=PO(n),this.readDemState(n,r,s),this.readGlobeState(n,r,s),this.readMaterialsAndEnv(n,r),o}readMaterialsAndEnv(t,n){const i=this.state;i.lightData.fill(0),i.demLightData.fill(0),i.fogData.fill(0),i.skyEnabled=!1,i.shadowEnabled=!1,i.starsIntensity=0,i.globeHaloData.fill(0);const r=[],s=t[we.MaterialCount>>2];let o=t[we.MaterialOffset>>2];for(let a=0;a<s;a++){const l=o>>2;switch(t[l+(fe.Kind>>2)]){case Ve.EnvLight:cr(n,l+(tc.Data>>2),i.lightData);break;case Ve.EnvDemLight:cr(n,l+(tc.Data>>2),i.demLightData);break;case Ve.EnvStars:cr(n,l+(nc.Matrix>>2),i.starsMatrixF32),i.starsIntensity=n[l+(nc.Intensity>>2)];break;case Ve.EnvGlobeHalo:cr(n,l+(Ud.Data>>2),i.globeHaloData);break;case Ve.EnvFog:cr(n,l+(Vd.Data>>2),i.fogData);break;case Ve.EnvSky:cr(n,l+(ic.ViewTransposed>>2),i.skyViewTransposedF32),cr(n,l+(ic.ProjInverted>>2),i.skyProjInvertedF32),i.skyEnabled=!0;break;case Ve.EnvShadow:cr(n,l+(Wd.Data>>2),i.shadowData),MO(i.shadowData),i.shadowEnabled=!0;break;default:r[t[l+(fe.Id>>2)]]=l;break}const f=t[l+(fe.ByteSize>>2)];if(f===0)break;o+=f}i.materialOffsets=r}readCamera(t){const n=this.state,i=we.ViewProjectionMatrix>>3;for(let o=0;o<16;o++)n.vpF64[o]=t[i+o];const r=we.CameraPosition>>3;n.cameraF64[0]=t[r],n.cameraF64[1]=t[r+1],n.cameraF64[2]=t[r+2];const s=we.ShadowViewProjection>>3;for(let o=0;o<16;o++)n.shadowVpF64[o]=t[s+o]}readDemState(t,n,i){const r=this.state,s=t[we.Flags>>2];r.demMode=(s&Go.DemMode)!==0,r.labelingDepthTestDisabled=(s&Go.LabelingDepthTestDisabled)!==0,r.demTextureSizePx=t[we.DemTextureSize>>2],r.demScale=n[we.DemScale>>2],r.demCenterElevation=n[we.DemCenterElevation>>2],r.demMinElevation=n[we.DemMinElevation>>2],r.demShadingIntensity=n[we.DemShadingIntensity>>2];const o=we.BackgroundColor>>2;r.backgroundColor.r=n[o],r.backgroundColor.g=n[o+1],r.backgroundColor.b=n[o+2],r.backgroundColor.a=n[o+3];const a=we.DemTextureMatrix>>3;for(let c=0;c<16;c++)r.demTextureMatrixF64[c]=i[a+c];if(Di(r.demFbVpF64,AB,r.demTextureMatrixF64),r.demTextureSizePx>0){const c=2*TO/r.demTextureSizePx;for(let f=0;f<4;f++)r.demFbVpF64[f*4+1]-=c*r.demFbVpF64[f*4+3]}r.flatLevelCount=Math.min(t[we.FlatLevelCount>>2],$l),r.identifyFlatLevelMask=t[we.IdentifyFlatLevelMask>>2];for(let c=0;c<r.flatLevelCount;c++){const f=we.FlatLevels+c*ko._Size>>3,u=r.flatLevelMvpF64[c],d=r.flatLevelTexF64[c];for(let h=0;h<16;h++)u[h]=i[f+(ko.Mvp>>3)+h],d[h]=i[f+(ko.Tex>>3)+h]}r.mapMeshScaleX=n[we.MapMeshScaleX>>2]||Ec,r.mapMeshScaleY=n[we.MapMeshScaleY>>2]||Tc,r.mapMeshTexShift=n[we.MapMeshTexShift>>2];const l=we.MapMeshVpMatrix>>3;for(let c=0;c<16;c++)r.mapMeshVpF64[c]=i[l+c]}readGlobeState(t,n,i){const r=this.state,s=t[we.Flags>>2];r.globeMode=(s&Go.GlobeMode)!==0,r.globeRatio=n[we.GlobeCrossfade>>2];const o=we.EcefViewProjection>>3;for(let d=0;d<16;d++)r.globeEcefMvpF32[d]=i[o+d];Tx(r.globeEcefMvpF32);for(let d=0;d<16;d++)r.globeVpF32[d]=r.vpF64[d];Tx(r.globeVpF32);const a=we.CameraMercator>>3;r.globeCameraMerc[0]=i[a],r.globeCameraMerc[1]=i[a+1];const l=we.VpAtCenter>>3,c=i[l+2],f=i[l+3];r.globeVpAtCenterF32[0]=i[l],r.globeVpAtCenterF32[1]=i[l+1],r.globeVpAtCenterF32[2]=(c+f)*.5,r.globeVpAtCenterF32[3]=f;const u=we.GlobeCameraEcef>>2;r.globeCameraEcef[0]=n[u],r.globeCameraEcef[1]=n[u+1],r.globeCameraEcef[2]=n[u+2]}}function MO(e){for(let t=0;t<4;t++){const n=e[8+t];e[12+t]-=n,e[8+t]=n*2}}function cr(e,t,n){for(let i=0;i<n.length;i++)n[i]=e[t+i]}class _O{constructor(){this.model=new Float64Array(16),this.product=new Float64Array(16),this.replica=0}setReplica(t){this.replica=t}composeMvp(t,n,i,r,s){this.fillModel(i,r,s);const o=this.product;Di(o,n,this.model),o[2]=o[2]*.5+o[3]*.5,o[6]=o[6]*.5+o[7]*.5,o[10]=o[10]*.5+o[11]*.5,o[14]=o[14]*.5+o[15]*.5;for(let a=0;a<16;a++)t[a]=o[a]}composeTex(t,n,i,r,s){this.fillModel(i,r,s),Di(this.product,n,this.model);for(let o=0;o<16;o++)t[o]=this.product[o]}composeExtrusion(t,n,i,r,s,o){this.fillModel(r,s,o,_i/ot);for(let l=0;l<16;l++)n[l]=this.model[l];const a=this.product;Di(a,i,this.model),a[2]=a[2]*.5+a[3]*.5,a[6]=a[6]*.5+a[7]*.5,a[10]=a[10]*.5+a[11]*.5,a[14]=a[14]*.5+a[15]*.5;for(let l=0;l<16;l++)t[l]=a[l]}originRelToCamera(t,n,i,r,s){const o=$(2,32-s),a=W/ae*o;t[0]=i*o-2147483648-a-n[0]+this.replica*4294967296,t[1]=r*o-2147483648-a-n[1],t[2]=-n[2]}fillModel(t,n,i,r=1){const s=$(2,32-i),o=W/ae*s,a=t*s-2147483648+this.replica*4294967296,l=n*s-2147483648,c=s/ot,f=this.model;f[0]=c,f[1]=0,f[2]=0,f[3]=0,f[4]=0,f[5]=c,f[6]=0,f[7]=0,f[8]=0,f[9]=0,f[10]=r,f[11]=0,f[12]=a-o,f[13]=l-o,f[14]=0,f[15]=1}}function CO(e){const t=e.ctx,n=e.deps;if(e.registerCommandTile(),t.matOff===void 0)return;const i=t.u32[t.matOff+(fe.Kind>>2)],r=e.readVertexDraw(t.u32,t.off,t.resources);if(!r)return;const s=e.commandCrossfade();if(e.ensureLitPass(n.polygonPass),e.onFlatCascade()&&e.flatDepthMode()==="greater")return;const o=t.identifyOnly?n.polygonPass.getIdentifyPipeline(t.state,r.vertexStride,s>0):e.onFlatCascade()?n.polygonPass.getPipeline(t.state,r.vertexStride,i,!0):n.polygonPass.getPipeline(t.state,r.vertexStride,i,!1,s>0,e.shadowMode(),e.flatDepthMode());o&&e.emit2d(a=>e.item("polygon",o,n.polygonPass.pushDraw(e.mvpF32,t.f32,t.u32,t.matOff,a?0:s,e.computeFogOrigin(),a?0:t.f32[t.off+(Zd.FloorElevation>>2)])))}function FO(e){const t=e.ctx,n=e.deps,{u32:i,f32:r,off:s}=t;if(e.registerCommandTile(),t.matOff===void 0)return;const o=i[t.matOff+(fe.Kind>>2)],a=e.readVertexDraw(i,s,t.resources);if(!a)return;e.ensureLitPass(n.linePass);const l=i[s+(An.Geometry>>2)],c=r[s+(An.EcefScale>>2)],f=Mh(t.fs,c>0),u=t.identifyOnly?n.linePass.getIdentifyPipeline(t.state,a.vertexStride,l,f>0):n.linePass.getPipeline(t.state,a.vertexStride,o,l,!1,f>0,e.shadowMode(),e.flatDepthMode());if(!u)return;const d=r[s+(An.Width>>2)],h=r[s+(An.TileToPixelRatio>>2)],g=r[s+(An.Shift>>2)];if(l===ue.TopStroke20||l===ue.SideStroke24){e.ensureDem(n.linePass),e.composeMvpFor(t.fs.vpF64),e.composeTexFor(e.demTexMvpF32,t.fs.demTextureMatrixF64),t.scene.draws.push(e.item("line",u,n.linePass.pushDrawStroke(e.mvpF32,r,t.matOff,d,t.canvasW,t.canvasH,g,e.demTexMvpF32,t.fs.demMode?t.fs.demScale:0,t.fs.demCenterElevation,i[s+(An.AbsZ>>2)],h,e.computeFogOrigin(),e.fogInvDistance(),$(2,32-t.tz)/ot,r[s+(An.FloorElevation>>2)]/(_i/ot))));return}if(l===ue.Solid3d20){e.ensureDem(n.linePass),e.composeMvpFor(t.fs.vpF64),e.composeTexFor(e.demTexMvpF32,t.fs.demTextureMatrixF64),e.tileMatrix.originRelToCamera(e.lineCamOriginRel,t.fs.cameraF64,t.tx,t.ty,t.tz),t.scene.draws.push(e.item("line",u,n.linePass.pushDraw3d(e.mvpF32,r,t.matOff,d,h,t.canvasW,t.canvasH,e.demTexMvpF32,t.fs.demMode?t.fs.demScale:0,t.fs.demCenterElevation,i[s+(An.AbsZ>>2)],$(2,32-t.tz)/ot,e.lineCamOriginRel,e.fogInvDistance())));return}if(e.onFlatCascade()&&e.flatDepthMode()==="greater")return;const y=t.identifyOnly||!e.onFlatCascade()?u:n.linePass.getPipeline(t.state,a.vertexStride,o,l,!0);y&&e.emit2d(p=>e.item("line",y,n.linePass.pushDraw(e.mvpF32,r,t.matOff,l,d,h,g,p?t.flatW:t.canvasW,p?t.flatH:t.canvasH,e.computeFogOrigin(),p?0:f,p?0:c,p?0:r[s+(An.FloorElevation>>2)])))}function LO(e){const t=e.ctx,n=e.deps,{f32:i,off:r}=t;if(e.registerCommandTile(),t.matOff===void 0)return;const s=e.materialTexture(Fs.TextureId);if(!s)return;const o=e.readVertexDraw(t.u32,r,t.resources);if(!o)return;const a=e.commandCrossfade();e.ensureLitPass(n.polygonTexturePass);const l=n.polygonTexturePass.getTextureBindGroup(t.state,s),c=i[r+(kr.TexOffsetX>>2)],f=i[r+(kr.TexOffsetY>>2)],u=i[r+(kr.TexMulX>>2)],d=i[r+(kr.TexMulY>>2)];if(!t.useFlatPass||t.tier!==void 0){const g=n.polygonTexturePass.getPipeline(t.state,o.vertexStride,!1,a>0,e.shadowMode(),e.flatDepthMode());if(!g)return;e.composeMvpFor(t.drawVp),e.targetList().push(e.item("polygonTextured",g,n.polygonTexturePass.pushDraw(e.mvpF32,i,t.matOff,c,f,u,d,a,e.computeFogOrigin(),i[r+(kr.FloorElevation>>2)]),l));return}if(e.flatDepthMode()==="greater")return;const h=n.polygonTexturePass.getPipeline(t.state,o.vertexStride,!0);if(h)for(let g=0;g<t.fs.flatLevelCount;g++)e.composeFlatMvp(g),t.out.flatDrawsByLevel[g].push(e.item("polygonTextured",h,n.polygonTexturePass.pushDraw(e.mvpF32,i,t.matOff,c,f,u,d,0,e.computeFogOrigin()),l))}function BO(e){const t=e.ctx,n=e.deps,{u32:i,f32:r,off:s}=t;if(e.registerCommandTile(),t.matOff===void 0)return;const o=i[t.matOff+(fe.Kind>>2)],a=e.readVertexDraw(i,s,t.resources);if(!a)return;e.ensureLitPass(n.lineParameterizedPass);const l=i[s+(Kn.Geometry>>2)],c=r[s+(Kn.EcefScale>>2)],f=Mh(t.fs,c>0),u=t.identifyOnly?n.lineParameterizedPass.getIdentifyPipeline(t.state,a.vertexStride,l,f>0):n.lineParameterizedPass.getPipeline(t.state,a.vertexStride,o,l,!1,f>0,e.shadowMode(),e.flatDepthMode());if(!u)return;const d=e.paramLine;if(d.kind=o,d.width=r[s+(Kn.Width>>2)],d.lengthScale=r[s+(Kn.LengthScale>>2)],d.circleFactor=r[s+(Kn.CircleFactor>>2)],d.tileToPixelRatio=r[s+(Kn.TileToPixelRatio>>2)],d.is3d=l===ue.Dashed3d32||l===ue.Patterned3d20,d.stripeCrossfade=f,d.stripeEcefScale=c,d.floorElevation=r[s+(Kn.FloorElevation>>2)],d.is3d){e.ensureDem(n.lineParameterizedPass),e.composeMvpFor(t.fs.vpF64),e.composeTexFor(e.demTexMvpF32,t.fs.demTextureMatrixF64),t.scene.draws.push(e.item("lineParameterized",u,_h(e,t.canvasW,t.canvasH)));return}if(e.onFlatCascade()&&e.flatDepthMode()==="greater")return;const h=t.identifyOnly||!e.onFlatCascade()?u:n.lineParameterizedPass.getPipeline(t.state,a.vertexStride,o,l,!0);h&&e.emit2d(g=>e.item("lineParameterized",h,g?_h(e,t.flatW,t.flatH):_h(e,t.canvasW,t.canvasH,!0)))}function _h(e,t,n,i=!1){const r=e.ctx,s=e.paramLine,o=s.is3d?e.demTexMvpF32:void 0,a=s.is3d&&r.fs.demMode?r.fs.demScale:0,l=$(2,32-r.tz)/ot;return s.kind===Ve.LinePattern?e.deps.lineParameterizedPass.pushPatternDraw(e.mvpF32,r.f32,r.u32,r.matOff,s.width,s.lengthScale,s.tileToPixelRatio,e.computeFogOrigin(),e.fogInvDistance(),l,o,a,r.fs.demCenterElevation):e.deps.lineParameterizedPass.pushDraw(e.mvpF32,r.f32,r.u32,r.matOff,s.width,s.lengthScale,s.circleFactor,t,n,e.computeFogOrigin(),e.fogInvDistance(),l,o,a,r.fs.demCenterElevation,i?s.stripeCrossfade:0,i?s.stripeEcefScale:0,i?s.floorElevation:0)}function DO(e){const t=e.ctx,n=e.deps,{u32:i,f32:r,off:s}=t;if(e.registerCommandTile(),t.matOff===void 0)return;const o=i[t.matOff+(fe.Kind>>2)],a=e.readVertexDraw(i,s,t.resources);if(!a)return;n.lineSpritePass.ensureResources(t.state,n.ensureFogUniformBuffer(t.state.device));const l=i[s+(zn.Geometry>>2)],c=t.identifyOnly?n.lineSpritePass.getIdentifyPipeline(t.state,a.vertexStride,l):n.lineSpritePass.getPipeline(t.state,a.vertexStride,o,l);c&&(e.composeMvpFor(t.drawVp),e.targetList().push(e.item("lineSprite",c,n.lineSpritePass.pushDraw(e.mvpF32,r,t.matOff,o,r[s+(zn.Opacity>>2)],r[s+(zn.SizeFactor>>2)],r[s+(zn.CalcScale>>2)],r[s+(zn.ScaleRatio>>2)],r[s+(zn.BorderWidthOffset>>2)],r[s+(zn.VertexShift>>2)],r[s+(zn.EndPosition>>2)],r[s+(zn.TipAmplitude>>2)],t.canvasW,t.canvasH,e.computeFogOrigin()))))}function OO(e){const t=e.ctx,n=e.deps,{u32:i,f32:r,off:s}=t;if(e.registerCommandTile(),t.matOff===void 0)return;const o=e.materialTexture(rc.TextureId);if(!o)return;const a=e.readVertexDraw(i,s,t.resources);if(!a)return;n.pointSpritePass.ensureResources(t.state,n.ensureGlobeUniformBuffer(t.state.device),n.ensureFogUniformBuffer(t.state.device)),e.ensureDem(n.pointSpritePass),e.ensureOcclusion(n.pointSpritePass);const l=n.pointSpritePass.getPipeline(t.state,a.vertexStride);if(!l)return;const c=n.pointSpritePass.getTextureBindGroup(t.state,o);e.composeMvpFor(t.fs.vpF64),e.composeTexFor(e.demTexMvpF32,t.fs.demTextureMatrixF64);const f=i[s+(yt.Flags>>2)],u=n.pointSpritePass.pushDraw(e.mvpF32,r,i,s,t.canvasW,t.canvasH,t.fs.labelingDepthTestDisabled,e.demTexMvpF32,t.fs.demMode?t.fs.demScale:0,t.fs.demCenterElevation,e.commandCrossfade(),e.computeFogOrigin());if(t.identifyOnly){const d=n.pointSpritePass.getIdentifyPipeline(t.state,a.vertexStride);d&&t.scene.draws.push(e.item("pointSprite",d,u,c));return}if(t.out.draws.push(e.item("pointSprite",l,u,c)),(f&Bs.LabelTest)!==0){const d=n.pointSpritePass.getSpritePipeline(t.state,a.vertexStride);d&&t.out.spriteOcclusion.push(e.item("pointSprite",d,u,c))}}function RO(e){const t=e.ctx,n=e.deps,{u32:i,f32:r,off:s}=t;if(e.registerCommandTile(),t.matOff===void 0)return;const o=e.materialTexture(sc.TextureId);if(!o)return;const a=e.readVertexDraw(i,s,t.resources);if(!a)return;n.labelPointPass.ensureResources(t.state,n.ensureGlobeUniformBuffer(t.state.device),n.ensureFogUniformBuffer(t.state.device)),e.ensureDem(n.labelPointPass),e.ensureOcclusion(n.labelPointPass);const l=i[s+(ut.Flags>>2)],c=n.labelPointPass.getPipeline(t.state,a.vertexStride,"fill"),f=(l&Ur.HasHalo)!==0?n.labelPointPass.getPipeline(t.state,a.vertexStride,"halo"):null;if(!c)return;const u=n.labelPointPass.getTextureBindGroup(t.state,o);e.composeMvpFor(t.fs.vpF64),e.composeTexFor(e.demTexMvpF32,t.fs.demTextureMatrixF64);const d=n.labelPointPass.pushDraw(e.mvpF32,r,i,s,t.canvasW,t.canvasH,t.fs.labelingDepthTestDisabled,e.demTexMvpF32,t.fs.demMode?t.fs.demScale:0,t.fs.demCenterElevation,e.commandCrossfade(),e.computeFogOrigin());if(t.identifyOnly){const h=n.labelPointPass.getIdentifyPipeline(t.state,a.vertexStride);h&&t.scene.draws.push(e.item("labelPoint",h,d,u));return}t.out.draws.push(e.item("labelPoint",c,d,u,f))}function zO(e){const t=e.ctx,n=e.deps,{u32:i,off:r}=t;if(e.registerCommandTile(),t.matOff===void 0)return;const s=e.materialTexture(sc.TextureId);if(!s)return;const o=e.readVertexDraw(i,r,t.resources);if(!o)return;n.labelLinePass.ensureResources(t.state,n.ensureFogUniformBuffer(t.state.device));const a=i[r+(bn.Flags>>2)],l=n.labelLinePass.getPipeline(t.state,o.vertexStride,"fill"),c=(a&Ur.HasHalo)!==0?n.labelLinePass.getPipeline(t.state,o.vertexStride,"halo"):null;if(!l)return;const f=n.labelLinePass.getTextureBindGroup(t.state,s);if(!t.useFlatPass||t.tier!==void 0){e.composeMvpFor(t.fs.vpF64),t.out.draws.push(e.item("labelLine",l,n.labelLinePass.pushDraw(e.mvpF32,t.f32,r,e.computeFogOrigin()),f,c));return}const u=n.labelLinePass.getPipeline(t.state,o.vertexStride,"fill",!0),d=c?n.labelLinePass.getPipeline(t.state,o.vertexStride,"halo",!0):null;if(u)for(let h=0;h<t.fs.flatLevelCount;h++)e.composeFlatMvp(h),t.out.flatDrawsByLevel[h].push(e.item("labelLine",u,n.labelLinePass.pushDraw(e.mvpF32,t.f32,r,e.computeFogOrigin()),f,d))}function NO(e){const t=e.ctx,n=e.deps;if(t.fs.labelingDepthTestDisabled)return;const i=e.readVertexDraw(t.u32,t.off,t.resources);if(!i)return;n.pointAnchorPass.ensureResources(t.state,n.ensureGlobeUniformBuffer(t.state.device)),e.ensureDem(n.pointAnchorPass);const r=n.pointAnchorPass.getPipeline(t.state,i.vertexStride);r&&(e.composeMvpFor(t.fs.vpF64),e.composeTexFor(e.demTexMvpF32,t.fs.demTextureMatrixF64),t.out.labelingAnchors.push(e.plainItem(r,n.pointAnchorPass.pushDraw(e.mvpF32,t.f32,t.u32,t.off,t.canvasW,t.canvasH,e.demTexMvpF32,t.fs.demMode?t.fs.demScale:0,t.fs.demCenterElevation,e.commandCrossfade()))))}function GO(e){const t=e.ctx,n=e.deps;if(e.registerCommandTile(),t.matOff===void 0)return;const i=e.materialTexture(rc.TextureId);if(!i)return;const r=e.readVertexDraw(t.u32,t.off,t.resources);if(!r)return;n.metricPointPass.ensureResources(t.state,n.ensureLightUniformBuffer(t.state.device),n.ensureFogUniformBuffer(t.state.device),n.ensureShadowResources(t.state.device));const s=n.metricPointPass.getPipeline(t.state,r.vertexStride,e.shadowMode());if(!s)return;const o=n.metricPointPass.getTextureBindGroup(t.state,i);e.composeMvpFor(t.drawVp),e.targetList().push(e.item("metricPoint",s,n.metricPointPass.pushDraw(e.mvpF32,t.f32,t.off,e.computeFogOrigin()),o))}function kO(e){const t=e.ctx,n=e.deps;e.registerCommandTile();const i=e.readVertexDraw(t.u32,t.off,t.resources);if(!i)return;n.circleMarkerPass.ensureResources(t.state,n.ensureLightUniformBuffer(t.state.device),n.ensureFogUniformBuffer(t.state.device),n.ensureShadowResources(t.state.device)),e.ensureDem(n.circleMarkerPass);const r=t.identifyOnly?n.circleMarkerPass.getIdentifyPipeline(t.state,i.vertexStride):n.circleMarkerPass.getPipeline(t.state,i.vertexStride,e.shadowMode());r&&(e.composeMvpFor(t.fs.vpF64),e.composeTexFor(e.demTexMvpF32,t.fs.demTextureMatrixF64),t.scene.draws.push(e.item("circleMarker",r,n.circleMarkerPass.pushDraw(e.mvpF32,t.f32,t.off,t.canvasW,t.canvasH,e.demTexMvpF32,t.fs.demMode?t.fs.demScale:0,t.fs.demCenterElevation,e.computeFogOrigin()))))}const UO=16;function VO(e){const t=e.ctx,n=e.deps;if(!t.fs.demMode)return;const i=e.readVertexDraw(t.u32,t.off,t.resources);if(!i)return;n.demElevationPass.ensureResources(t.state);const r=n.demElevationPass.getPipeline(t.state,i.vertexStride);r&&(e.registerCommandTile(),e.composeMvpFor(t.fs.demFbVpF64),t.out.demDraws.push(e.plainItem(r,n.demElevationPass.pushDraw(e.mvpF32))))}function WO(e){const t=e.ctx,n=e.deps;if(!t.useFlatPass)return;const i=e.readVertexDraw(t.u32,t.off,t.resources);if(!i)return;n.demTerrainPass.ensureResources(t.state,n.ensureDemLightUniformBuffer(t.state.device),n.ensureFogUniformBuffer(t.state.device),n.ensureShadowResources(t.state.device));const r=n.demTerrainPass.getPipeline(t.state,i.vertexStride);if(!r)return;e.registerCommandTile();const s=$(2,32-t.tz)/ot;e.composeMvpFor(t.fs.vpF64);for(let a=0;a<t.fs.flatLevelCount;a++){e.composeTexFor(e.flatTexF32,t.fs.flatLevelTexF64[a]);const l=e.plainItem(r,n.demTerrainPass.pushDraw(e.mvpF32,e.flatTexF32,{demScale:t.fs.demScale,demCenterElevation:t.fs.demCenterElevation,demMinElevation:t.fs.demMinElevation,modelScale:s,demShadingIntensity:t.fs.demShadingIntensity},e.computeFogOrigin(),e.fogInvDistance()));t.out.terrainDrawsByLevel[a].push(l);const c=t.out.identify;if(t.servesIdentify&&(c.flatLevelMask&1<<a)!==0){const f=n.demTerrainPass.getIdentifyPipeline(t.state,i.vertexStride);f&&c.terrainDrawsByLevel[a].push(ie(V({},l),{pipeline:f}))}}const o=e.shadowCasterMvp();if(o){const a=n.demTerrainPass.getPipeline(t.state,i.vertexStride,"caster");a&&t.out.shadow.terrain.push(e.plainItem(a,n.demTerrainPass.pushShadowCopy(o)))}}const HO=new Float32Array(4);function YO(e){const t=e.ctx,n=e.deps,{u32:i,f32:r,off:s,matOff:o}=t;e.registerCommandTile();const a=i[s+(Wo.Tier>>2)]|0;t.scene.hasMapMesh=!0;const l=e.readVertexDraw(i,s,t.resources);if(!l)return;n.mapMeshPass.ensureResources(t.state,n.ensureLightUniformBuffer(t.state.device),n.ensureFogUniformBuffer(t.state.device),n.ensureShadowResources(t.state.device));const c=t.identifyOnly?n.mapMeshPass.getIdentifyPipeline(t.state,l.vertexStride):n.mapMeshPass.getPipeline(t.state,l.vertexStride,e.shadowMode());if(!c)return;const f=r[s+(Wo.HeightFactor>>2)],u=i[s+(Wo.Flags>>2)];t.scene.mapMeshTiers.add(a),e.composeMvpFor(t.fs.vpF64),e.composeTexFor(e.flatTexF32,t.fs.demTextureMatrixF64);const d={pipeline:c,uniformOffset:n.mapMeshPass.pushDraw(e.mvpF32,e.flatTexF32,{scaleX:t.fs.mapMeshScaleX,scaleY:t.fs.mapMeshScaleY,texShift:t.fs.mapMeshTexShift,heightFactor:f,absZ:(u&jd.AbsZ)!==0,demMode:t.fs.demMode,demScale:t.fs.demScale,demCenterElevation:t.fs.demCenterElevation,modelScale:$(2,32-t.tz)/ot,surfaceColor:o!==void 0?r.subarray(o+(fe.Color1R>>2),o+(fe.Color1A>>2)+1):HO},e.computeFogOrigin(),e.fogInvDistance()),vertexBufferId:l.vertexBufferId,vertexBuffer:l.vertexBuffer,vertexOffset:l.vertexOffset,vertexCount:l.vertexCount,tier:a,hiddenPipeline:n.mapMeshPass.getPipeline(t.state,l.vertexStride,e.shadowMode(),!0)};if(t.identifyOnly){t.scene.draws.push(ie(V({},d),{kind:"mapMesh"}));return}t.useFlatPass?t.out.mapMeshDraws.push(d):t.out.draws.push(ie(V({},d),{kind:"mapMesh"}));const h=e.shadowCasterMvp();if(h){const g=n.mapMeshPass.getPipeline(t.state,l.vertexStride,"caster");g&&t.out.shadow.mapMesh.push(ie(V({},e.plainItem(g,n.mapMeshPass.pushShadowCopy(h))),{tier:a}))}}const XO={[rr.Fill]:"fill",[rr.DepthOnly]:"depth",[rr.DepthClear]:"depthClear"},Px=[0,0,0,0];function ZO(e){const t=e.ctx,n=e.deps,{u32:i,f32:r,off:s,matOff:o}=t;e.registerCommandTile();const a=e.readVertexDraw(i,s,t.resources);if(!a)return;n.meshPass.ensureResources(t.state,n.ensureLightUniformBuffer(t.state.device),n.ensureFogUniformBuffer(t.state.device),n.ensureShadowResources(t.state.device)),e.ensureDem(n.meshPass);const l=i[s+(Ds.Mode>>2)],c=XO[l];if(c===void 0)return;const f=n.meshPass.getPipeline(t.state,a.vertexStride,c,l===rr.Fill?e.shadowMode():"receive");if(!f)return;const u=l===rr.Fill&&o!==void 0,d=u&&i[o+(fe.Kind>>2)]===Ve.PolygonExtrusionGradient,h=i[s+(Ds.Flags>>2)];e.composeMvpFor(t.fs.vpF64),e.composeTexFor(e.demTexMvpF32,t.fs.demTextureMatrixF64);const g=n.meshPass.pushDraw(e.mvpF32,e.demTexMvpF32,{color:u?r.subarray(o+(fe.Color1R>>2),o+(fe.Color1A>>2)+1):Px,color2:d?r.subarray(o+(fe.Color2R>>2),o+(fe.Color2A>>2)+1):Px,gradient:d,gradientEdge0:d?r[o+(fe.FactorInMin>>2)]:0,gradientEdge1:d?r[o+(fe.FactorInMax>>2)]:0,heightFactor:r[s+(Ds.HeightFactor>>2)],floorElevation:r[s+(Ds.FloorElevation>>2)],absZ:(h&ac.AbsZ)!==0,demScale:t.fs.demMode?t.fs.demScale:0,demCenterElevation:t.fs.demCenterElevation,modelScale:$(2,32-t.tz)/ot},e.computeFogOrigin(),e.fogInvDistance()),y=!t.fs.labelingDepthTestDisabled&&(h&ac.Labeling)!==0,p=ie(V({},e.item("mesh",f,g)),{labelingPipeline:y?n.meshPass.getPipeline(t.state,a.vertexStride,"labeling"):null});(t.useFlatPass?t.out.meshDraws:t.out.draws).push(p);const v=l===rr.DepthClear?null:e.shadowCasterMvp();if(v){const A=n.meshPass.getPipeline(t.state,a.vertexStride,c,"caster");A&&t.out.shadow.mesh.push(e.plainItem(A,n.meshPass.pushShadowCopy(v)))}}function jO(e){const t=e.ctx,n=e.deps,{u32:i,f32:r,off:s,matOff:o}=t;e.registerCommandTile();const a=e.readVertexDraw(i,s,t.resources);if(!a)return;n.polygonExtrusionPass.ensureResources(t.state,n.ensureLightUniformBuffer(t.state.device),n.ensureFogUniformBuffer(t.state.device),n.ensureShadowResources(t.state.device)),e.ensureDem(n.polygonExtrusionPass);const l=o!==void 0&&i[o+(fe.Kind>>2)]===Ve.PolygonExtrusionGradient,c=n.polygonExtrusionPass.getPipeline(t.state,a.vertexStride,"prepass"),f=n.polygonExtrusionPass.getPipeline(t.state,a.vertexStride,l?"gradientColor":"color",e.shadowMode());if(!c||!f)return;e.tileMatrix.composeExtrusion(e.mvpF32,e.modelF32,t.fs.vpF64,t.tx,t.ty,t.tz),e.composeTexFor(e.demTexMvpF32,t.fs.demTextureMatrixF64);const u=[t.fs.demMode?t.fs.demScale:0,t.fs.demCenterElevation,r[s+(Jn.HeightFactor>>2)],r[s+(Jn.FloorElevation>>2)]],d=i[s+(Jn.IsHole>>2)],h=i[s+(Jn.IsVertexColor>>2)],g=r[s+(Jn.NearCameraFade>>2)],y=r[s+(Jn.FloorStackOffset>>2)],p=r[s+(Jn.FloorStackTotal>>2)];let v;if(l&&o!==void 0){const T=[r[o+(fe.Color1R>>2)],r[o+(fe.Color1G>>2)],r[o+(fe.Color1B>>2)],r[o+(fe.Color1A>>2)]],I=[r[o+(fe.Color2R>>2)],r[o+(fe.Color2G>>2)],r[o+(fe.Color2B>>2)],r[o+(fe.Color2A>>2)]];v=n.polygonExtrusionPass.pushDrawGradient(e.mvpF32,e.modelF32,T,I,r[o+(fe.FactorInMin>>2)],r[o+(fe.FactorInMax>>2)],e.demTexMvpF32,u,d,h,g,e.computeFogOrigin(),e.fogInvDistance(),y,p)}else{const T=o!==void 0?[r[o+(fe.Color1R>>2)],r[o+(fe.Color1G>>2)],r[o+(fe.Color1B>>2)],r[o+(fe.Color1A>>2)]]:[0,0,0,1];v=n.polygonExtrusionPass.pushDraw(e.mvpF32,e.modelF32,T,e.demTexMvpF32,u,d,h,g,e.computeFogOrigin(),e.fogInvDistance())}if(t.identifyOnly){const T=n.polygonExtrusionPass.getIdentifyPipeline(t.state,a.vertexStride);T&&t.scene.draws.push({kind:"extrusion",pipeline:T,prepassPipeline:null,labelingPipeline:null,uniformOffset:v,vertexBufferId:a.vertexBufferId,vertexBuffer:a.vertexBuffer,vertexOffset:a.vertexOffset,vertexCount:a.vertexCount,runSeq:0});return}const A=!t.fs.labelingDepthTestDisabled&&a.vertexStride!==UO&&d===0,w={kind:"extrusion",pipeline:f,prepassPipeline:c,labelingPipeline:A?n.polygonExtrusionPass.getPipeline(t.state,a.vertexStride,"labeling"):null,uniformOffset:v,vertexBufferId:a.vertexBufferId,vertexBuffer:a.vertexBuffer,vertexOffset:a.vertexOffset,vertexCount:a.vertexCount,runSeq:i[s+(Jn.RunSeq>>2)]};(t.useFlatPass?t.out.extrusion:t.out.draws).push(w);const S=e.shadowCasterMvp(!0);if(S){const T=n.polygonExtrusionPass.getPipeline(t.state,a.vertexStride,"prepass","caster");T&&t.out.shadow.extrusion.push(e.plainItem(T,n.polygonExtrusionPass.pushShadowCopy(S)))}}function QO(e){const t=e.ctx,n=e.deps,{i32:i,f32:r,off:s,matOff:o}=t;e.registerCommandTile();const a=e.readVertexDraw(t.u32,s,t.resources);if(!a||o===void 0)return;const l=e.materialTexture(ft.TextureId);if(!l)return;n.polygonExtrusionTexturePass.ensureResources(t.state,n.ensureFogUniformBuffer(t.state.device)),e.ensureDem(n.polygonExtrusionTexturePass);const c=n.polygonExtrusionTexturePass.getPipeline(t.state,a.vertexStride);if(!c)return;const f=n.polygonExtrusionTexturePass.getTextureBindGroup(t.state,l);e.tileMatrix.composeExtrusion(e.mvpF32,e.modelF32,t.fs.vpF64,t.tx,t.ty,t.tz),e.composeTexFor(e.demTexMvpF32,t.fs.demTextureMatrixF64);const u=[t.fs.demMode?t.fs.demScale:0,t.fs.demCenterElevation,r[s+(Ho.HeightFactor>>2)],r[s+(Ho.FloorElevation>>2)]],d=r[s+(Ho.NearCameraFade>>2)],h=n.polygonExtrusionTexturePass.pushDraw(e.mvpF32,{wallPadding:[r[o+(ft.WallPadL>>2)],r[o+(ft.WallPadT>>2)],r[o+(ft.WallPadR>>2)],r[o+(ft.WallPadB>>2)]],texturePadding:[r[o+(ft.TexPadL>>2)],r[o+(ft.TexPadT>>2)],r[o+(ft.TexPadR>>2)],r[o+(ft.TexPadB>>2)]],partCount:[r[o+(ft.PartCountX>>2)],r[o+(ft.PartCountY>>2)]],maxInterval:[r[o+(ft.MaxIntervalX>>2)],r[o+(ft.MaxIntervalY>>2)]],sliceSize:[r[o+(ft.SliceSizeX>>2)],r[o+(ft.SliceSizeY>>2)]],layoutMode:[i[o+(ft.LayoutModeH>>2)],i[o+(ft.LayoutModeV>>2)]]},e.demTexMvpF32,u,d,$(2,32-t.tz)/ot,e.computeFogOrigin(),e.fogInvDistance());t.out.extrusionTexture.push(e.item("extrusionTexture",c,h,f))}function qO(e){var P,b,E;const t=e.ctx,n=e.deps,{u32:i,f32:r,off:s,matOff:o}=t;e.registerCommandTile();const a=i[s+(dt.IndexCount>>2)],l=i[s+(dt.InstanceCount>>2)];if(a===0||l===0||o===void 0)return;const c=i[s+(wn.VertexBuffer>>2)],f=i[s+(dt.IndexBuffer>>2)],u=i[s+(dt.InstanceBuffer>>2)],d=t.resources.getBuffer(c),h=t.resources.getBuffer(f),g=t.resources.getBuffer(u);if(!d||!h||!g)return;n.gltfModelPass.ensureResources(t.state,n.ensureFogUniformBuffer(t.state.device),n.ensureShadowResources(t.state.device));const y=e.shadowMode(),p=n.gltfModelPass.getPipeline(t.state,y==="unlit"?"none":y);if(!p)return;const v=i[s+(dt.Flags>>2)],A=[r[o+(xn.ColorR>>2)],r[o+(xn.ColorG>>2)],r[o+(xn.ColorB>>2)],r[o+(xn.ColorA>>2)]],w=i[o+(xn.ColorTextureId>>2)],S=w!==0&&(P=t.resources.getTextureOptional(w))!=null?P:null,T=i[o+(xn.AoTextureId>>2)],I=T!==0&&(b=t.resources.getTextureOptional(T))!=null?b:null,C=i[o+(xn.PbrTextureId>>2)],M=C!==0&&(E=t.resources.getTextureOptional(C))!=null?E:null,B=n.gltfModelPass.getColorBindGroup(t.state,w,S,T,I,C,M),D=r[o+(xn.Metallic>>2)],F=r[o+(xn.Roughness>>2)],z=i[o+(xn.LightingModel>>2)];e.composeMvpFor(t.fs.vpF64),e.composeTexFor(e.demTexMvpF32,t.fs.demTextureMatrixF64),e.tileMatrix.originRelToCamera(e.gltfCamOriginRel,t.fs.cameraF64,t.tx,t.ty,t.tz);const N=n.gltfModelPass.pushDraw(e.mvpF32,e.demTexMvpF32,r.subarray(s+(dt.LightDirX>>2),s+(dt.LightAmbientA>>2)+1),i[s+(dt.DemPos>>2)],r.subarray(s+(dt.AnchorX>>2),s+(dt.AxisEndZ>>2)+1),{color:A,demScale:t.fs.demMode?t.fs.demScale:0,demCenterElevation:t.fs.demCenterElevation,invTileScaleXY:ot/$(2,32-t.tz),heightUnFactor:xB,metallic:D,roughness:F,lightingModel:z,nearCameraFade:r[s+(dt.NearCameraFade>>2)],gltfFlags:v,hasPbrTexture:M!==null,surfaceRelZ:r[s+(dt.SurfaceRelZ>>2)],surfaceAbsZ:r[s+(dt.SurfaceAbsZ>>2)],scaleX:r[s+(dt.ScaleX>>2)],scaleY:r[s+(dt.ScaleY>>2)],scaleZ:r[s+(dt.ScaleZ>>2)],camOriginRel:e.gltfCamOriginRel,fogInvDistance:e.fogInvDistance()}),H={kind:"gltf",pipeline:p,uniformOffset:N,vertexBuffer:d,instanceBuffer:g,instanceOffset:i[s+(dt.InstanceOffset>>2)],instanceCount:l,indexBuffer:h,indexFormat:(v&Qd.IndexU32)!==0?"uint32":"uint16",indexCount:a,colorBindGroup:B};if(t.identifyOnly){const x=n.gltfModelPass.getIdentifyPipeline(t.state);x&&t.scene.draws.push(ie(V({},H),{pipeline:x}));return}(i[s+(wn.Flags>>2)]&Rn.CastOnly)===0&&(t.useFlatPass?t.out.gltfDraws:t.out.draws).push(H);const K=e.shadowCasterMvp();if(K){const x=n.gltfModelPass.getPipeline(t.state,"caster");x&&t.out.shadow.gltf.push(ie(V({},H),{pipeline:x,uniformOffset:n.gltfModelPass.pushShadowCopy(K)}))}}const KO=new Set([be.DrawPolygon,be.DrawLine,be.DrawPolygon3d,be.DrawPointSprite,be.DrawLabelPoint,be.DrawCircleMarker,be.DrawLineSprite,be.DrawLineParameterized,be.DrawGltfModel,be.DrawMapMesh]);class JO{constructor(t){this.deps=t,this.tileMatrix=new _O,this.mvpF32=new Float32Array(16),this.modelF32=new Float32Array(16),this.shadowMvpF32=new Float32Array(16),this.demTexMvpF32=new Float32Array(16),this.flatTexF32=new Float32Array(16),this.gltfCamOriginRel=new Float32Array(3),this.lineCamOriginRel=new Float32Array(3),this.fogOriginF32=new Float32Array(4),this.fogOriginOff=new Float32Array(4),this.ctx={u32:null,i32:null,f32:null,fs:null,resources:null,state:null,useFlatPass:!1,canvasW:1,canvasH:1,flatW:1,flatH:1,collectTiles:!1,servesIdentify:!1,out:null,off:0,matOff:void 0,tier:void 0,identifyOnly:!1,scene:null,drawVp:null,tx:0,ty:0,tz:0},this.paramLine={kind:0,width:0,lengthScale:0,circleFactor:0,tileToPixelRatio:0,is3d:!1,stripeCrossfade:0,stripeEcefScale:0,floorElevation:0},this.commandTile={sourceId:-1,tileX:0,tileY:0,tileZ:0},this.vertexDraw={vertexBufferId:0,vertexBuffer:null,vertexStride:0,vertexOffset:0,vertexCount:0},this.commandDecoders={[be.DrawPolygon]:()=>CO(this),[be.DrawLine]:()=>FO(this),[be.DrawPolygonTextured]:()=>LO(this),[be.DrawLineParameterized]:()=>BO(this),[be.DrawLineSprite]:()=>DO(this),[be.DrawPointSprite]:()=>OO(this),[be.DrawLabelPoint]:()=>RO(this),[be.DrawLabelLine]:()=>zO(this),[be.DrawPointAnchor]:()=>NO(this),[be.DrawMetricPoint]:()=>GO(this),[be.DrawCircleMarker]:()=>kO(this),[be.DrawDemElevation]:()=>VO(this),[be.DrawDemTerrain]:()=>WO(this),[be.DrawMapMesh]:()=>YO(this),[be.DrawMesh]:()=>ZO(this),[be.DrawPolygon3d]:()=>jO(this),[be.DrawPolygon3dTexture]:()=>QO(this),[be.DrawGltfModel]:()=>qO(this)}}decode(t,n,i,r,s){const{u32:o,i32:a}=t,l=this.ctx;l.u32=o,l.i32=a,l.f32=t.f32,l.fs=n,l.resources=i,l.state=r,l.useFlatPass=n.demMode&&n.flatLevelCount>0,l.canvasW=Math.max(1,r.canvas.width),l.canvasH=Math.max(1,r.canvas.height),l.flatW=Q1(r.canvas),l.flatH=q1(r.canvas),l.collectTiles=this.deps.collectTiles(),l.servesIdentify=s;const c=ie(V({},$1(n.flatLevelCount,-1)),{useFlatPass:l.useFlatPass,tileMap:new Map,demDraws:[],mapMeshDraws:[],meshDraws:[],extrusion:[],extrusionTexture:[],gltfDraws:[],labelingAnchors:[],spriteOcclusion:[],identify:$1(n.flatLevelCount,n.identifyFlatLevelMask),shadow:{extrusion:[],mapMesh:[],mesh:[],gltf:[],terrain:[]}});c.identify.hiddenTierDraws=c.identify.tierDraws,l.out=c;for(const d of this.deps.uniformPasses)d.reset();const f=o[we.CommandCount>>2],u=o[we.CommandOffset>>2];for(let d=n.replicaMin;d<=n.replicaMax;d++){this.tileMatrix.setReplica(d);let h=u;for(let g=0;g<f;g++){const y=h>>2,p=o[y],v=Ty(p),A=this.commandDecoders[p];if(v===0||A===void 0)break;if(HF(a,y,this.commandTile),l.off=y,l.tx=this.commandTile.tileX,l.ty=this.commandTile.tileY,l.tz=this.commandTile.tileZ,n.globeMode&&l.tz<H4&&!this.commandSupportsEcef(p,o,y)){h+=v;continue}const w=o[y+(wn.Flags>>2)];if(l.identifyOnly=(w&Rn.IdentifyOnly)!==0,l.identifyOnly&&!this.acceptIdentifyCommand(p)){h+=v;continue}l.scene=l.identifyOnly?c.identify:c,l.matOff=n.materialOffsets[o[y+(wn.MaterialId>>2)]];const S=(w&VF)>>>by;l.tier=S===0?void 0:S-Sy,l.drawVp=l.tier!==void 0?n.mapMeshVpF64:n.vpF64,A(),h+=v}}return c}registerCommandTile(){const t=this.ctx;t.collectTiles&&$O(t.out.tileMap,t.tx,t.ty,t.tz)}targetList(){const t=this.ctx,{scene:n,tier:i}=t;if(i===void 0)return n.draws;const r=(t.u32[t.off+(wn.Flags>>2)]&Rn.DepthGreater)!==0;return bB(r?n.hiddenTierDraws:n.tierDraws,i)}onFlatCascade(){const t=this.ctx;return t.useFlatPass&&t.tier===void 0}emit2d(t){const n=this.ctx;if(!this.onFlatCascade()){this.composeMvpFor(n.drawVp),this.targetList().push(t(!1));return}for(let i=0;i<n.fs.flatLevelCount;i++)(n.scene.flatLevelMask&1<<i)!==0&&(this.composeFlatMvp(i),n.scene.flatDrawsByLevel[i].push(t(!0)))}composeMvpFor(t){const n=this.ctx;this.tileMatrix.composeMvp(this.mvpF32,t,n.tx,n.ty,n.tz)}shadowMode(){const t=this.ctx,n=t.u32[t.off+(wn.Flags>>2)];return t.tier!==void 0||(n&Rn.UseLight)===0?"unlit":(n&Rn.ReceiveShadows)!==0?"receive":"none"}flatDepthMode(){const t=this.ctx,n=t.u32[t.off+(wn.Flags>>2)];return(n&Rn.DepthGreater)!==0?"greater":(n&Rn.DepthTest)!==0?"test":"overlay"}shadowCasterMvp(t=!1){const n=this.ctx;if(!n.fs.shadowEnabled||n.tier!==void 0||(n.u32[n.off+(wn.Flags>>2)]&Rn.CastShadows)===0)return null;const i=this.shadowMvpF32;t?this.tileMatrix.composeExtrusion(i,this.modelF32,n.fs.shadowVpF64,n.tx,n.ty,n.tz):this.tileMatrix.composeMvp(i,n.fs.shadowVpF64,n.tx,n.ty,n.tz);let r=1/0,s=-1/0,o=1/0,a=-1/0;for(let f=0;f<4;f++){const u=f&1,d=f>>1,h=i[0]*u+i[4]*d+i[12],g=i[1]*u+i[5]*d+i[13];r=Math.min(r,h),s=Math.max(s,h),o=Math.min(o,g),a=Math.max(a,g)}const l=dB;return s<-l||r>l||a<-l||o>l?null:i}composeFlatMvp(t){this.composeMvpFor(this.ctx.fs.flatLevelMvpF64[t])}composeTexFor(t,n){const i=this.ctx;this.tileMatrix.composeTex(t,n,i.tx,i.ty,i.tz)}computeFogOrigin(){const t=this.ctx,n=t.fs.fogData[O1];if(n<=0)return this.fogOriginOff;const i=this.fogOriginF32;this.tileMatrix.originRelToCamera(i,t.fs.cameraF64,t.tx,t.ty,t.tz);const r=1/n;return i[0]*=r,i[1]*=r,i[2]*=r,i[3]=$(2,32-t.tz)/ot*r,i}fogInvDistance(){const t=this.ctx.fs.fogData[O1];return t>0?1/t:0}commandCrossfade(){const t=this.ctx;return Mh(t.fs,(t.u32[t.off+(wn.Flags>>2)]&Rn.HasEcef)!==0)}materialTexture(t){const n=this.ctx;return n.resources.getTexture(n.u32[n.matOff+(t>>2)])}ensureLitPass(t){const n=this.ctx;t.ensureResources(n.state,this.deps.ensureLightUniformBuffer(n.state.device),this.deps.ensureGlobeUniformBuffer(n.state.device),this.deps.ensureFogUniformBuffer(n.state.device),this.deps.ensureShadowResources(n.state.device))}ensureDem(t){t.demGroup.ensureBindGroup(this.ctx.state.device,this.deps.getDemTextureView())}ensureOcclusion(t){const n=this.ctx,i=this.deps.ensureLabelingViews(n.state);t.occlusionGroup.ensureBindGroup(n.state.device,i.color,i.depth,i.sprite,i.revision)}item(t,n,i,r=null,s=null){const o=this.vertexDraw;return{kind:t,pipeline:n,haloPipeline:s,uniformOffset:i,vertexBufferId:o.vertexBufferId,vertexBuffer:o.vertexBuffer,vertexOffset:o.vertexOffset,vertexCount:o.vertexCount,textureBindGroup:r}}plainItem(t,n){const i=this.vertexDraw;return{pipeline:t,uniformOffset:n,vertexBufferId:i.vertexBufferId,vertexBuffer:i.vertexBuffer,vertexOffset:i.vertexOffset,vertexCount:i.vertexCount}}readVertexDraw(t,n,i){const r=t[n+(Xd.VertexCount>>2)];if(r===0)return null;const s=t[n+(wn.VertexBuffer>>2)],o=i.getVertexBuffer(s);if(!o)return null;const a=this.vertexDraw;return a.vertexBufferId=s,a.vertexBuffer=o.buffer,a.vertexStride=o.stride,a.vertexOffset=t[n+(Xd.VertexOffset>>2)],a.vertexCount=r,a}acceptIdentifyCommand(t){return!(!this.ctx.servesIdentify||!KO.has(t))}commandSupportsEcef(t,n,i){switch(t){case be.DrawPolygon:case be.DrawPolygonTextured:return!0;case be.DrawLine:{const r=n[i+(An.Geometry>>2)];return r===ue.Solid12||r===ue.Solid16||r===ue.Shifted20}case be.DrawLineParameterized:return n[i+(Kn.Geometry>>2)]===ue.Dashed28;case be.DrawPointSprite:case be.DrawLabelPoint:case be.DrawPointAnchor:return!0;default:return!1}}}function $O(e,t,n,i){const r=`${t},${n},${i}`;e.has(r)||e.set(r,{x:t,y:n,z:i})}const eR={r:0,g:0,b:0,a:0},tR=new Set(["pointSprite","labelPoint","labelLine","metricPoint","circleMarker"]);class nR extends N4{constructor(){super(...arguments),this.renderFamily=a1.WebGPU,this.showTileBounds=!1,this.aaMode="msaa",this.viewportTop=0,this.viewportBottom=0,this.viewportLeft=0,this.viewportRight=0,this.viewportPixelRatio=1,this.viewportLogicalWidth=0,this.viewportLogicalHeight=0,this.tileBounds=new qD,this.polygonPass=new $D,this.polygonTexturePass=new eO,this.linePass=new tO,this.lineParameterizedPass=new nO,this.lineSpritePass=new iO,this.pointSpritePass=new rO,this.labelPointPass=new sO,this.labelLinePass=new oO,this.pointAnchorPass=new aO,this.metricPointPass=new lO,this.circleMarkerPass=new cO,this.demElevationPass=new fO,this.demTerrainPass=new uO,this.mapMeshPass=new dO,this.meshPass=new gO,this.polygonExtrusionPass=new vO,this.polygonExtrusionTexturePass=new yO,this.gltfModelPass=new xO,this.skyPass=new wO,this.postEffectsPass=new AO,this.starsPass=new bO,this.globeHaloPass=new SO,this.shadowResources=new EO,this.uniformPasses=[this.polygonPass,this.polygonTexturePass,this.linePass,this.lineParameterizedPass,this.lineSpritePass,this.pointSpritePass,this.labelPointPass,this.labelLinePass,this.pointAnchorPass,this.metricPointPass,this.circleMarkerPass,this.demElevationPass,this.demTerrainPass,this.mapMeshPass,this.meshPass,this.polygonExtrusionPass,this.polygonExtrusionTexturePass,this.gltfModelPass],this.depthTexture=null,this.depthTextureView=null,this.depthTextureWidth=0,this.depthTextureHeight=0,this.msaaTexture=null,this.msaaTextureView=null,this.lightUniformBuffer=null,this.demLightUniformBuffer=null,this.fogUniformBuffer=null,this.globeUniformBuffer=null,this.globeUniformData=new Float32Array(x1),this.flatTexture=null,this.flatTextureView=null,this.flatTextureWidth=0,this.flatTextureHeight=0,this.demTexture=null,this.demTextureView=null,this.demTextureSize=0,this.labelingTargets=new IB,this.identifyPass=new PB({drawCanvasContent:(t,n)=>this.drawCanvasContent(t,n),mapMeshTierBindGroup:(t,n)=>this.mapMeshPass.getTierBindGroup(t,n,this.demTextureView),demTerrainPass:this.demTerrainPass}),this.mapMeshTierTextures=new Map,this.mapMeshTierBindGroups=new Map,this.mapMeshHiddenTierTextures=new Map,this.mapMeshHiddenTierBindGroups=new Map,this.mapMeshDepthTexture=null,this.mapMeshDepthTextureView=null,this.mapMeshMsaaTexture=null,this.mapMeshMsaaTextureView=null,this.mapMeshTextureWidth=0,this.mapMeshTextureHeight=0,this.frameState=new IO,this.decoder=new JO({polygonPass:this.polygonPass,polygonTexturePass:this.polygonTexturePass,linePass:this.linePass,lineParameterizedPass:this.lineParameterizedPass,lineSpritePass:this.lineSpritePass,pointSpritePass:this.pointSpritePass,labelPointPass:this.labelPointPass,labelLinePass:this.labelLinePass,pointAnchorPass:this.pointAnchorPass,metricPointPass:this.metricPointPass,circleMarkerPass:this.circleMarkerPass,demElevationPass:this.demElevationPass,demTerrainPass:this.demTerrainPass,mapMeshPass:this.mapMeshPass,meshPass:this.meshPass,polygonExtrusionPass:this.polygonExtrusionPass,polygonExtrusionTexturePass:this.polygonExtrusionTexturePass,gltfModelPass:this.gltfModelPass,uniformPasses:this.uniformPasses,ensureLightUniformBuffer:t=>this.ensureLightUniformBuffer(t),ensureDemLightUniformBuffer:t=>this.ensureDemLightUniformBuffer(t),ensureGlobeUniformBuffer:t=>this.ensureGlobeUniformBuffer(t),ensureFogUniformBuffer:t=>this.ensureFogUniformBuffer(t),ensureShadowResources:t=>this.shadowResources.ensure(t),getDemTextureView:()=>this.demTextureView,ensureLabelingViews:t=>this.labelingTargets.ensure(t),collectTiles:()=>this.showTileBounds})}drawFrame(t,n,i){const{device:r,context:s}=n;if(t.u32[we.FrameId>>2]===0)return this.submitClear(r,s),0;const o=this.frameState.read(t);i.resetMisses();const a=this.identifyPass.wants(o.identifyRequest),l=this.decoder.decode(t,o,i,n,a!==null),c=i.missCount===0?a:null;this.writeGlobeUniform(r,o);for(const f of this.uniformPasses)f.upload();return this.lightUniformBuffer&&r.queue.writeBuffer(this.lightUniformBuffer,0,o.lightData),this.demLightUniformBuffer&&r.queue.writeBuffer(this.demLightUniformBuffer,0,o.demLightData),r.queue.writeBuffer(this.ensureFogUniformBuffer(r),0,o.fogData,0,D1),this.shadowResources.write(r,o.shadowData,o.shadowEnabled,this.computeCanvasViewport(n)),this.encodeFrame(n,o,l,c),i.missCount}setViewport(t,n,i,r){this.viewportTop=t.top,this.viewportBottom=t.bottom,this.viewportLeft=t.left,this.viewportRight=t.right,this.viewportPixelRatio=n,this.viewportLogicalWidth=i,this.viewportLogicalHeight=r}encodeFrame(t,n,i,r){var w,S,T,I,C,M,B,D,F,z,N,H,K,P,b;const{useFlatPass:s,hasMapMesh:o,tileMap:a,draws:l,flatDrawsByLevel:c,demDraws:f,extrusionTexture:u,gltfDraws:d}=i,{device:h,context:g}=t;this.tileBounds.ensureResources(t),this.ensureDepthResources(t),(d.length>0||l.some(E=>E.kind==="gltf")||i.identify.draws.some(E=>E.kind==="gltf"))&&this.gltfModelPass.ensureTextureBindGroup(h,this.demTextureView);const y=h.createCommandEncoder();if(n.demMode&&n.demTextureSizePx>0&&(this.ensureDemTexture(h,n.demTextureSizePx),this.drawDemElevationPass(y,f)),this.labelingTargets.created&&(n.labelingDepthTestDisabled||this.labelingTargets.drawOcclusionPass(y,i,this.polygonExtrusionPass,this.meshPass,this.pointAnchorPass),this.labelingTargets.drawSpritePass(y,i,this.pointSpritePass)),o){const E=ex(i);this.ensureMapMeshTargets(t,E,this.mapMeshTierTextures);for(const L of E)this.drawMapMeshTierPass(y,(w=this.mapMeshTierTextures.get(L))==null?void 0:w.view,1,i.tierDraws.get(L));const x=new Set(i.hiddenTierDraws.keys());this.ensureMapMeshTargets(t,x,this.mapMeshHiddenTierTextures),this.mapMeshHiddenTierBindGroups.clear();for(const L of x){const O=(S=this.mapMeshHiddenTierTextures.get(L))==null?void 0:S.view;this.drawMapMeshTierPass(y,O,0,i.hiddenTierDraws.get(L));const R=this.mapMeshPass.getTierBindGroup(h,O!=null?O:null,this.demTextureView);R&&this.mapMeshHiddenTierBindGroups.set(L,R)}this.mapMeshTierBindGroups.clear();for(const L of E){const O=this.mapMeshPass.getTierBindGroup(h,(I=(T=this.mapMeshTierTextures.get(L))==null?void 0:T.view)!=null?I:null,this.demTextureView);O&&this.mapMeshTierBindGroups.set(L,O)}for(const L of i.mapMeshDraws)L.textureBindGroup=(M=this.mapMeshTierBindGroups.get((C=L.tier)!=null?C:0))!=null?M:null,L.hiddenTextureBindGroup=(D=this.mapMeshHiddenTierBindGroups.get((B=L.tier)!=null?B:0))!=null?D:null;for(const L of l)L.kind==="mapMesh"&&(L.textureBindGroup=(z=this.mapMeshTierBindGroups.get((F=L.tier)!=null?F:0))!=null?z:null,L.hiddenTextureBindGroup=(H=this.mapMeshHiddenTierBindGroups.get((N=L.tier)!=null?N:0))!=null?H:null);for(const L of i.shadow.mapMesh)L.textureBindGroup=(P=this.mapMeshTierBindGroups.get((K=L.tier)!=null?K:0))!=null?P:null}s&&(this.ensureFlatTexture(t),this.demTerrainPass.ensureTextureBindGroup(h,this.flatTextureView)),n.shadowEnabled&&this.shadowResources.draw(y,i,{extrusion:this.polygonExtrusionPass,mapMesh:this.mapMeshPass,mesh:this.meshPass,gltf:this.gltfModelPass,terrain:this.demTerrainPass});const p=g.getCurrentTexture().createView(),v=this.postEffectsPass.ensureReady(t,this.aaMode),A=v&&(b=this.postEffectsPass.sceneView)!=null?b:p;if(s)for(let E=0;E<n.flatLevelCount;E++)this.drawFlatPass(y,c[E],n),this.drawCanvasSegment(y,t,n,A,E===0,E===n.flatLevelCount-1,i.terrainDrawsByLevel[E],i);else{const E=n.globeMode?n.backgroundColor:yh,x={colorAttachments:[{view:this.msaaTextureView,resolveTarget:A,clearValue:E,loadOp:"clear",storeOp:"discard"}]};this.depthTextureView&&(x.depthStencilAttachment={view:this.depthTextureView,depthClearValue:1,depthLoadOp:"clear",depthStoreOp:"store"});const L=y.beginRenderPass(x);this.applyCanvasViewport(L,t),this.drawSky(L,h,t,n),n.globeMode&&n.starsIntensity>0&&(this.starsPass.ensureResources(t),this.starsPass.setUniform(h,n.starsMatrixF32,n.starsIntensity),this.starsPass.draw(L)),n.globeMode&&n.globeHaloData[5]>0&&(this.globeHaloPass.ensureResources(t),this.globeHaloPass.setUniform(h,n.globeHaloData),this.globeHaloPass.drawBackground(L));const O=[],R=[];for(const G of l)(tR.has(G.kind)?R:O).push(G);this.drawCanvasContent(L,O),this.drawExtrusionTextures(L,u),n.globeMode&&n.globeHaloData[3]>0&&(this.globeHaloPass.ensureResources(t),this.globeHaloPass.setUniform(h,n.globeHaloData),this.globeHaloPass.draw(L)),R.length>0&&this.drawCanvasContent(L,R),this.showTileBounds&&this.tileBounds.draw(L,h,a,n.cameraF64,n.vpF64),L.end()}v&&this.postEffectsPass.draw(y,t,this.aaMode,p),r&&this.identifyPass.encode(y,h,i.identify,r),h.queue.submit([y.finish()]),r&&this.identifyPass.read().then(E=>this.onIdentify(r.id,E)).catch(()=>{})}drawCanvasSegment(t,n,i,r,s,o,a,l){var d,h;const{device:c}=n,f={colorAttachments:[ie(V({view:this.msaaTextureView},o?{resolveTarget:r}:{}),{clearValue:yh,loadOp:s?"clear":"load",storeOp:o?"discard":"store"})]};this.depthTextureView&&(f.depthStencilAttachment={view:this.depthTextureView,depthClearValue:1,depthLoadOp:s?"clear":"load",depthStoreOp:"store"});const u=t.beginRenderPass(f);this.applyCanvasViewport(u,n),s&&this.drawSky(u,c,n,i),a.length>0&&this.demTerrainPass.textureBindGroup&&(u.setBindGroup(1,this.demTerrainPass.textureBindGroup),nn(u,a,(h=(d=this.demTerrainPass.batch)==null?void 0:d.bindGroup)!=null?h:null)),o&&(this.drawMeshGeometry(u,l.meshDraws),l.mapMeshDraws.length>0&&this.drawMapMeshGeometry(u,l.mapMeshDraws),this.drawGltfGeometry(u,l.gltfDraws),this.drawExtrusionRun(u,l.extrusion),this.drawExtrusionTextures(u,l.extrusionTexture),this.drawCanvasContent(u,l.draws),this.showTileBounds&&this.tileBounds.draw(u,c,l.tileMap,i.cameraF64,i.vpF64)),u.end()}applyCanvasViewport(t,n){const i=this.computeCanvasViewport(n);t.setViewport(i.x,i.y,i.width,i.height,0,1)}computeCanvasViewport(t){const n=this.viewportPixelRatio,i=t.canvas.width,r=t.canvas.height,s={x:this.viewportLeft*n,y:this.viewportTop*n,width:Math.max(1,i-(this.viewportLeft+this.viewportRight)*n),height:Math.max(1,r-(this.viewportTop+this.viewportBottom)*n)};return this.quantizeViewportAsWebGL(s,i,r),s}quantizeViewportAsWebGL(t,n,i){if(this.viewportLogicalWidth<=0||this.viewportLogicalHeight<=0)return;const r=Math.round(this.viewportLogicalWidth),s=Math.round(this.viewportLogicalHeight),o=this.viewportPixelRatio,a=Math.trunc(this.viewportLeft*o);let l=Math.max(1,Math.trunc((r-this.viewportLeft-this.viewportRight)*o)),c=Math.max(1,Math.trunc((s-this.viewportTop-this.viewportBottom)*o));const f=Math.max(0,Math.trunc(s*o)-Math.trunc(this.viewportBottom*o)-c);l=Math.min(l,n-a),c=Math.min(c,i-f),t.x=a,t.y=f,t.width=l,t.height=c}ensureDemTexture(t,n){var i;this.demTexture&&this.demTextureView&&this.demTextureSize===n||((i=this.demTexture)==null||i.destroy(),this.demTexture=t.createTexture({size:{width:n,height:n},format:jo,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),this.demTextureView=this.demTexture.createView(),this.demTextureSize=n)}drawDemElevationPass(t,n){var r,s;if(!this.demTextureView)return;const i=t.beginRenderPass({colorAttachments:[{view:this.demTextureView,clearValue:{r:0,g:0,b:0,a:0},loadOp:"clear",storeOp:"store"}]});nn(i,n,(s=(r=this.demElevationPass.batch)==null?void 0:r.bindGroup)!=null?s:null),i.end()}ensureFlatTexture(t){var r;const n=Q1(t.canvas),i=q1(t.canvas);this.flatTexture&&this.flatTextureView&&this.flatTextureWidth===n&&this.flatTextureHeight===i||((r=this.flatTexture)==null||r.destroy(),this.flatTexture=t.device.createTexture({size:{width:n,height:i},format:t.format,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),this.flatTextureView=this.flatTexture.createView(),this.flatTextureWidth=n,this.flatTextureHeight=i)}drawFlatPass(t,n,i){var l,c;if(!this.flatTextureView)return;const r=t.beginRenderPass({colorAttachments:[{view:this.flatTextureView,clearValue:i.backgroundColor,loadOp:"clear",storeOp:"store"}]}),s=f=>{var u,d,h,g,y,p,v,A;return f.kind==="polygon"?(d=(u=this.polygonPass.batch)==null?void 0:u.bindGroup)!=null?d:null:f.kind==="polygonTextured"?(g=(h=this.polygonTexturePass.batch)==null?void 0:h.bindGroup)!=null?g:null:f.kind==="lineParameterized"?(p=(y=this.lineParameterizedPass.batch)==null?void 0:y.bindGroup)!=null?p:null:(A=(v=this.linePass.batch)==null?void 0:v.bindGroup)!=null?A:null},o=n;let a=0;for(;a<o.length;){const f=o[a].kind==="labelLine";let u=a;for(;u<o.length&&o[u].kind==="labelLine"===f;)u++;f?bh(r,o,a,u,(c=(l=this.labelLinePass.batch)==null?void 0:l.bindGroup)!=null?c:null):nn(r,o.slice(a,u),s),a=u}r.end()}createLightBuffer(t){return t.createBuffer({size:Nn,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST})}ensureGlobeUniformBuffer(t){return this.globeUniformBuffer||(this.globeUniformBuffer=t.createBuffer({size:ar,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST})),this.globeUniformBuffer}writeGlobeUniform(t,n){var r,s;if(!this.globeUniformBuffer)return;const i=this.globeUniformData;i.set(n.globeEcefMvpF32,0),i.set(n.globeVpF32,16),i[32]=(r=n.globeCameraMerc[0])!=null?r:0,i[33]=(s=n.globeCameraMerc[1])!=null?s:0,i[34]=0,i[35]=0,i.set(n.globeVpAtCenterF32,36),i.set(n.globeCameraEcef,40),i[43]=0,t.queue.writeBuffer(this.globeUniformBuffer,0,i)}ensureLightUniformBuffer(t){return this.lightUniformBuffer||(this.lightUniformBuffer=this.createLightBuffer(t)),this.lightUniformBuffer}drawSky(t,n,i,r){r.skyEnabled&&(this.skyPass.ensureResources(i,this.ensureFogUniformBuffer(n)),this.skyPass.setUniform(n,r.skyViewTransposedF32,r.skyProjInvertedF32,r.fogData[13]),this.skyPass.draw(t))}ensureFogUniformBuffer(t){return this.fogUniformBuffer||(this.fogUniformBuffer=t.createBuffer({size:xt,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST})),this.fogUniformBuffer}ensureDemLightUniformBuffer(t){return this.demLightUniformBuffer||(this.demLightUniformBuffer=this.createLightBuffer(t)),this.demLightUniformBuffer}ensureMapMeshTargets(t,n,i){var a,l;const r=Math.max(1,Math.trunc(t.canvas.width*Ec)),s=Math.max(1,Math.trunc(t.canvas.height*Tc)),{device:o}=t;if(this.mapMeshTextureWidth!==r||this.mapMeshTextureHeight!==s){for(const c of this.mapMeshTierTextures.values())c.texture.destroy();this.mapMeshTierTextures.clear(),this.mapMeshTierBindGroups.clear();for(const c of this.mapMeshHiddenTierTextures.values())c.texture.destroy();this.mapMeshHiddenTierTextures.clear(),this.mapMeshHiddenTierBindGroups.clear(),(a=this.mapMeshDepthTexture)==null||a.destroy(),this.mapMeshDepthTexture=o.createTexture({size:{width:r,height:s},format:Gt,sampleCount:Gs,usage:GPUTextureUsage.RENDER_ATTACHMENT}),this.mapMeshDepthTextureView=this.mapMeshDepthTexture.createView(),(l=this.mapMeshMsaaTexture)==null||l.destroy(),this.mapMeshMsaaTexture=o.createTexture({size:{width:r,height:s},format:t.format,sampleCount:Gs,usage:GPUTextureUsage.RENDER_ATTACHMENT}),this.mapMeshMsaaTextureView=this.mapMeshMsaaTexture.createView(),this.mapMeshTextureWidth=r,this.mapMeshTextureHeight=s}for(const c of n)if(!i.has(c)){const f=o.createTexture({size:{width:r,height:s},format:t.format,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING});i.set(c,{texture:f,view:f.createView()})}}drawMapMeshTierPass(t,n,i,r){if(!n||!this.mapMeshDepthTextureView||!this.mapMeshMsaaTextureView)return;const s=t.beginRenderPass({colorAttachments:[{view:this.mapMeshMsaaTextureView,resolveTarget:n,clearValue:eR,loadOp:"clear",storeOp:"discard"}],depthStencilAttachment:{view:this.mapMeshDepthTextureView,depthClearValue:i,depthLoadOp:"clear",depthStoreOp:"store"}});r&&r.length>0&&this.drawCanvasContent(s,r),s.end()}drawMapMeshGeometry(t,n){var r,s;const i=(s=(r=this.mapMeshPass.batch)==null?void 0:r.bindGroup)!=null?s:null;for(const o of n)nn(t,[o],i),this.drawMapMeshHidden(t,o,i)}drawMapMeshHidden(t,n,i){!n.hiddenPipeline||!n.hiddenTextureBindGroup||(t.setPipeline(n.hiddenPipeline),i&&t.setBindGroup(0,i,[n.uniformOffset]),t.setBindGroup(1,n.hiddenTextureBindGroup),t.setVertexBuffer(0,n.vertexBuffer),t.draw(n.vertexCount,1,n.vertexOffset,0))}drawMeshGeometry(t,n){var r,s;if(n.length===0)return;const i=this.meshPass.demGroup.bindGroup;i&&t.setBindGroup(1,i),nn(t,n,(s=(r=this.meshPass.batch)==null?void 0:r.bindGroup)!=null?s:null)}drawGltfGeometry(t,n){var r,s;if(n.length===0)return;const i=this.gltfModelPass.textureBindGroup;i&&t.setBindGroup(1,i),J1(t,n,(s=(r=this.gltfModelPass.batch)==null?void 0:r.bindGroup)!=null?s:null)}drawExtrusionRun(t,n,i=0,r=n.length){var l,c;if(r<=i)return;const s=(c=(l=this.polygonExtrusionPass.batch)==null?void 0:l.bindGroup)!=null?c:null,o=this.polygonExtrusionPass.demGroup.bindGroup;o&&t.setBindGroup(1,o);let a=i;for(;a<r;){let f=a+1;for(;f<r&&n[f].runSeq===n[a].runSeq;)f++;let u=null,d=-1;for(let h=a;h<f;h++){const g=n[h];g.prepassPipeline&&(g.prepassPipeline!==u&&(t.setPipeline(g.prepassPipeline),u=g.prepassPipeline),s&&t.setBindGroup(0,s,[g.uniformOffset]),d!==g.vertexBufferId&&(t.setVertexBuffer(0,g.vertexBuffer),d=g.vertexBufferId),t.draw(g.vertexCount,1,g.vertexOffset,0))}u=null,d=-1;for(let h=a;h<f;h++){const g=n[h];g.pipeline!==u&&(t.setPipeline(g.pipeline),u=g.pipeline),s&&t.setBindGroup(0,s,[g.uniformOffset]),d!==g.vertexBufferId&&(t.setVertexBuffer(0,g.vertexBuffer),d=g.vertexBufferId),t.draw(g.vertexCount,1,g.vertexOffset,0)}a=f}}drawExtrusionTextures(t,n){var r,s;if(n.length===0)return;const i=this.polygonExtrusionTexturePass.demGroup.bindGroup;i&&t.setBindGroup(2,i),nn(t,n,(s=(r=this.polygonExtrusionTexturePass.batch)==null?void 0:r.bindGroup)!=null?s:null)}drawCanvasContent(t,n){var f,u,d,h,g,y,p,v,A,w,S,T,I,C,M,B,D,F,z,N,H,K,P,b;const i=(u=(f=this.polygonPass.batch)==null?void 0:f.bindGroup)!=null?u:null,r=(h=(d=this.linePass.batch)==null?void 0:d.bindGroup)!=null?h:null,s=(y=(g=this.lineParameterizedPass.batch)==null?void 0:g.bindGroup)!=null?y:null,o=(v=(p=this.lineSpritePass.batch)==null?void 0:p.bindGroup)!=null?v:null,a=(w=(A=this.pointSpritePass.batch)==null?void 0:A.bindGroup)!=null?w:null,l=(T=(S=this.mapMeshPass.batch)==null?void 0:S.bindGroup)!=null?T:null;let c=0;for(;c<n.length;){const E=n[c];if(E.kind==="labelPoint"||E.kind==="labelLine"){const x=E.kind;let L=c;for(;L<n.length&&n[L].kind===x;)L++;x==="labelPoint"?(this.labelPointPass.occlusionGroup.bindGroup&&t.setBindGroup(3,this.labelPointPass.occlusionGroup.bindGroup),this.labelPointPass.demGroup.bindGroup&&t.setBindGroup(2,this.labelPointPass.demGroup.bindGroup),bh(t,n,c,L,(C=(I=this.labelPointPass.batch)==null?void 0:I.bindGroup)!=null?C:null)):bh(t,n,c,L,(B=(M=this.labelLinePass.batch)==null?void 0:M.bindGroup)!=null?B:null),c=L;continue}if(E.kind==="extrusion"){let x=c;for(;x<n.length&&n[x].kind==="extrusion";)x++;this.drawExtrusionRun(t,n,c,x),c=x;continue}if(E.kind==="gltf"){let x=c;for(;x<n.length&&n[x].kind==="gltf";)x++;this.drawGltfGeometry(t,n.slice(c,x)),c=x;continue}if(t.setPipeline(E.pipeline),E.kind==="polygonTextured"){const x=(F=(D=this.polygonTexturePass.batch)==null?void 0:D.bindGroup)!=null?F:null;x&&t.setBindGroup(0,x,[E.uniformOffset]),E.textureBindGroup&&t.setBindGroup(1,E.textureBindGroup)}else if(E.kind==="metricPoint"){const x=(N=(z=this.metricPointPass.batch)==null?void 0:z.bindGroup)!=null?N:null;x&&t.setBindGroup(0,x,[E.uniformOffset]),E.textureBindGroup&&t.setBindGroup(1,E.textureBindGroup)}else if(E.kind==="circleMarker"){const x=(K=(H=this.circleMarkerPass.batch)==null?void 0:H.bindGroup)!=null?K:null;x&&t.setBindGroup(0,x,[E.uniformOffset]),this.circleMarkerPass.demGroup.bindGroup&&t.setBindGroup(1,this.circleMarkerPass.demGroup.bindGroup)}else if(E.kind==="pointSprite")a&&t.setBindGroup(0,a,[E.uniformOffset]),E.textureBindGroup&&t.setBindGroup(1,E.textureBindGroup),this.pointSpritePass.demGroup.bindGroup&&t.setBindGroup(2,this.pointSpritePass.demGroup.bindGroup),this.pointSpritePass.occlusionGroup.bindGroup&&t.setBindGroup(3,this.pointSpritePass.occlusionGroup.bindGroup);else if(E.kind==="mesh"){const x=(b=(P=this.meshPass.batch)==null?void 0:P.bindGroup)!=null?b:null;x&&t.setBindGroup(0,x,[E.uniformOffset]),this.meshPass.demGroup.bindGroup&&t.setBindGroup(1,this.meshPass.demGroup.bindGroup)}else if(E.kind==="mapMesh")E.textureBindGroup&&t.setBindGroup(1,E.textureBindGroup),l&&t.setBindGroup(0,l,[E.uniformOffset]);else{const x=E.kind==="polygon"?i:E.kind==="lineParameterized"?s:E.kind==="lineSprite"?o:r;x&&t.setBindGroup(0,x,[E.uniformOffset]),E.kind==="line"&&this.linePass.demGroup.bindGroup?t.setBindGroup(1,this.linePass.demGroup.bindGroup):E.kind==="lineParameterized"&&this.lineParameterizedPass.demGroup.bindGroup&&t.setBindGroup(1,this.lineParameterizedPass.demGroup.bindGroup)}t.setVertexBuffer(0,E.vertexBuffer),t.draw(E.vertexCount,1,E.vertexOffset,0),E.kind==="mapMesh"&&this.drawMapMeshHidden(t,E,l),c++}}ensureDepthResources(t){var r,s;const n=Math.max(1,t.canvas.width),i=Math.max(1,t.canvas.height);this.depthTexture&&this.depthTextureView&&this.depthTextureWidth===n&&this.depthTextureHeight===i||((r=this.depthTexture)==null||r.destroy(),this.depthTexture=t.device.createTexture({size:{width:n,height:i},format:Gt,sampleCount:Gs,usage:GPUTextureUsage.RENDER_ATTACHMENT}),this.depthTextureView=this.depthTexture.createView(),(s=this.msaaTexture)==null||s.destroy(),this.msaaTexture=t.device.createTexture({size:{width:n,height:i},format:t.format,sampleCount:Gs,usage:GPUTextureUsage.RENDER_ATTACHMENT}),this.msaaTextureView=this.msaaTexture.createView(),this.depthTextureWidth=n,this.depthTextureHeight=i)}submitClear(t,n){const i=t.createCommandEncoder();i.beginRenderPass({colorAttachments:[{view:n.getCurrentTexture().createView(),clearValue:yh,loadOp:"clear",storeOp:"store"}]}).end(),t.queue.submit([i.finish()])}}function iR(e,t,n){return{u32:new Uint32Array(e,t,n>>2),i32:new Int32Array(e,t,n>>2),f32:new Float32Array(e,t,n>>2),f64:new Float64Array(e,t,n>>3)}}const rR=4,sR=5;class oR{constructor(){this.buffers=new Map,this.textures=new Map,this.stagingBuffers=new Map,this.stagingTextures=new Map,this._missCount=0}get missCount(){return this._missCount}resetMisses(){this._missCount=0}getBuffer(t){const n=this.buffers.get(t);if(!n){this._missCount++;return}return n.buffer}getVertexBuffer(t){const n=this.buffers.get(t);if(!n||n.stride===void 0){this._missCount++;return}return n}getTexture(t){const n=this.textures.get(t);return n||this._missCount++,n}getTextureOptional(t){return this.textures.get(t)}getBufferOptional(t){var n;return(n=this.buffers.get(t))==null?void 0:n.buffer}setBuffer(t,n,i){this.deleteBuffer(t),this.buffers.set(t,i!==void 0&&i>0?{buffer:n,stride:i}:{buffer:n})}deleteBuffer(t){this.dropStagedBuffer(t);const n=this.buffers.get(t);n&&(n.buffer.destroy(),this.buffers.delete(t))}setTexture(t,n){this.deleteTexture(t),this.textures.set(t,n)}deleteTexture(t){this.dropStagedTexture(t);const n=this.textures.get(t);n&&(n.destroy(),this.textures.delete(t))}stageBuffer(t,n,i,r){this.dropStagedBuffer(t),this.stagingBuffers.set(t,{slot:i!==void 0&&i>0?{buffer:n,stride:i}:{buffer:n},remaining:r})}getStagedBuffer(t){var n;return(n=this.stagingBuffers.get(t))==null?void 0:n.slot.buffer}coverStagedBuffer(t,n){const i=this.stagingBuffers.get(t);i&&(i.remaining-=n,i.remaining<=0&&(this.stagingBuffers.delete(t),this.deleteBuffer(t),this.buffers.set(t,i.slot)))}stageTexture(t,n,i){this.dropStagedTexture(t),this.stagingTextures.set(t,{texture:n,remaining:i})}getStagedTexture(t){var n;return(n=this.stagingTextures.get(t))==null?void 0:n.texture}coverStagedTexture(t,n){const i=this.stagingTextures.get(t);i&&(i.remaining-=n,i.remaining<=0&&(this.stagingTextures.delete(t),this.deleteTexture(t),this.textures.set(t,i.texture)))}clearAll(){this.buffers.forEach(t=>t.buffer.destroy()),this.buffers.clear(),this.textures.forEach(t=>t.destroy()),this.textures.clear(),this.stagingBuffers.forEach(t=>t.slot.buffer.destroy()),this.stagingBuffers.clear(),this.stagingTextures.forEach(t=>t.texture.destroy()),this.stagingTextures.clear()}clearWithoutDestroy(){this.buffers.clear(),this.textures.clear(),this.stagingBuffers.clear(),this.stagingTextures.clear()}dropStagedBuffer(t){const n=this.stagingBuffers.get(t);n&&(n.slot.buffer.destroy(),this.stagingBuffers.delete(t))}dropStagedTexture(t){const n=this.stagingTextures.get(t);n&&(n.texture.destroy(),this.stagingTextures.delete(t))}}class aR{constructor(t,n,i,r){this.onEvent=r,this.lastFrameComplete=!1,this.generation=0,this.recoveringDevice=!1,this.destroyed=!1,this.resources=new oR,this.stagingScratch=new Uint8Array(0),this.frameReadSlot=2,this.lastFrameId=0,this.waitForResources=!1,this.resourceWaiting=!1,this.needsRedraw=!1,this.frameInvalidatedByDelete=!1,this.renderLoop=()=>{const s=this.resourceWaiting?1/0:rR;this.ringReader.drain(this.ringHandlers,s,this.lastFrameId)>0&&(this.needsRedraw=!0),this.resourceWaiting||(this.frameReadSlot=o1(this.transportI32,tn.FrameMailbox,this.frameReadSlot));const o=this.frameViews[this.frameReadSlot],a=o.u32[we.FrameId>>2];if(gh(a,this.lastFrameId))if(!!gh(o.u32[we.RequiredSeq>>2],this.ringReader.appliedSeq)&&this.waitForResources&&!this.ringReader.blockedOnFence)this.resourceWaiting=!0;else{this.resourceWaiting=!1,this.lastFrameId=a,this.needsRedraw=!1,this.frameInvalidatedByDelete=!1;const c=this.render.drawFrame(o,this.webGPUState,this.resources);this.lastFrameComplete=c===0}else if(this.needsRedraw&&!this.frameInvalidatedByDelete&&this.lastFrameId!==0&&a===this.lastFrameId){this.needsRedraw=!1;const l=this.render.drawFrame(o,this.webGPUState,this.resources);this.lastFrameComplete=l===0}this.rAFHandle=self.requestAnimationFrame(this.renderLoop)},this.backendType=t,this.webGPUState=n,this.rAFHandle=0,this.render=this.createRender(t),this.attachDeviceHandlers(),this.transportBuffer=i,this.transportI32=new Int32Array(i),this.frameViews=Array.from({length:Py},(s,o)=>iR(i,tn._Size+o*lc,lc)),this.ringReader=new z4(i),this.ringHandlers={uploadBuffer:(s,o,a,l,c)=>this.applyUploadBuffer(s,o,a,l,c),uploadTexture:(s,o,a,l,c)=>this.applyUploadTexture(s,o,a,l,c),createTexture:(s,o,a)=>this.applyCreateTexture(s,o,a),patchTexture:(s,o,a,l,c,f,u)=>this.applyPatchTexture(s,o,a,l,c,f,u),createBuffer:(s,o,a,l)=>this.applyCreateBuffer(s,o,a,l),patchBuffer:(s,o,a,l)=>this.applyPatchBuffer(s,o,a,l),deleteBuffers:s=>{this.frameInvalidatedByDelete=!0;for(const o of s)this.resources.deleteBuffer(o)},deleteTextures:s=>{this.frameInvalidatedByDelete=!0;for(const o of s)this.resources.deleteTexture(o)},setConfig:s=>{this.render.showTileBounds=s.showTileBounds,this.render.aaMode=s.aaMode,this.waitForResources=s.waitForResources},clearAll:()=>{this.frameInvalidatedByDelete=!0,this.resources.clearAll()}}}resize(t,n,i,r){const s=Math.floor(t*i),o=Math.floor(n*i),a=this.webGPUState.canvas;a.width!==s&&(a.width=s),a.height!==o&&(a.height=o),this.render.setViewport(r,i,t,n),this.needsRedraw=!0}start(){this.rAFHandle!==0||this.destroyed||(this.rAFHandle=self.requestAnimationFrame(this.renderLoop))}stop(){this.rAFHandle!==0&&(self.cancelAnimationFrame(this.rAFHandle),this.rAFHandle=0)}destroy(){this.destroyed=!0,this.stop(),this.resources.clearAll(),this.webGPUState.device.destroy()}applyUploadBuffer(t,n,i,r,s){if(s===0){this.resources.deleteBuffer(t);return}const{device:o}=this.webGPUState,a=n?GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST,l=o.createBuffer({size:s,usage:a,mappedAtCreation:!0});new Uint8Array(l.getMappedRange()).set(new Uint8Array(this.transportBuffer,r,s)),l.unmap(),this.resources.setBuffer(t,l,n?void 0:i)}applyUploadTexture(t,n,i,r,s){if(n<=0||i<=0||s<n*i*4){this.resources.deleteTexture(t);return}this.stagingScratch.length<s&&(this.stagingScratch=new Uint8Array(s)),this.stagingScratch.set(new Uint8Array(this.transportBuffer,r,s));const{device:o}=this.webGPUState,a=o.createTexture({size:[n,i,1],format:"rgba8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST});o.queue.writeTexture({texture:a},this.stagingScratch,{bytesPerRow:n*4,rowsPerImage:i},[n,i,1]),this.resources.setTexture(t,a)}applyCreateTexture(t,n,i){if(n<=0||i<=0){this.resources.deleteTexture(t);return}const{device:r}=this.webGPUState,s=r.createTexture({size:[n,i,1],format:"rgba8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST});this.resources.stageTexture(t,s,n*i*4)}applyPatchTexture(t,n,i,r,s,o,a){const l=this.resources.getStagedTexture(t),c=l!=null?l:this.resources.getTextureOptional(t);!c||r<=0||s<=0||a<r*s*4||(this.stagingScratch.length<a&&(this.stagingScratch=new Uint8Array(a)),this.stagingScratch.set(new Uint8Array(this.transportBuffer,o,a)),this.webGPUState.device.queue.writeTexture({texture:c,origin:[n,i,0]},this.stagingScratch,{bytesPerRow:r*4,rowsPerImage:s},[r,s,1]),l&&this.resources.coverStagedTexture(t,r*s*4))}applyCreateBuffer(t,n,i,r){if(r<=0){this.resources.deleteBuffer(t);return}const{device:s}=this.webGPUState,o=s.createBuffer({size:r+3&-4,usage:(n?GPUBufferUsage.INDEX:GPUBufferUsage.VERTEX)|GPUBufferUsage.COPY_DST});this.resources.stageBuffer(t,o,n?void 0:i,r)}applyPatchBuffer(t,n,i,r){const s=this.resources.getStagedBuffer(t),o=s!=null?s:this.resources.getBufferOptional(t);if(!o||r<=0)return;const a=r+3&-4;this.stagingScratch.length<a&&(this.stagingScratch=new Uint8Array(a)),this.stagingScratch.set(new Uint8Array(this.transportBuffer,i,r)),this.stagingScratch.fill(0,r,a),this.webGPUState.device.queue.writeBuffer(o,n,this.stagingScratch,0,a),s&&this.resources.coverStagedBuffer(t,r)}createRender(t){if(t===mh.WebGPU)return new nR((n,i)=>{var r;return(r=this.onEvent)==null?void 0:r.call(this,eh(V({type:"identify",requestId:n},i),[i.pixels.buffer]))});{const n=t;throw new Error(`Unknown backend: ${String(n)}`)}}attachDeviceHandlers(){this.webGPUState.device.lost.then(t=>{t.reason==="destroyed"||this.recoveringDevice||this.destroyed||(console.warn(`[render][webgpu] device lost (${t.message}), recovering`),this.recoverDevice())}),this.webGPUState.device.onuncapturederror=t=>{var n;(n=this.onEvent)==null||n.call(this,{type:"error",message:t.error.message})}}recoverDevice(){return Fe(this,null,function*(){var t,n;this.recoveringDevice=!0,this.stop(),this.resources.clearWithoutDestroy();for(let i=0;i<sR;i++){try{const r=yield Ix(this.webGPUState.canvas);if(this.destroyed){r.device.destroy();return}this.webGPUState=r}catch(r){if(console.error("[render][webgpu] device recovery attempt failed",r),yield new Promise(s=>setTimeout(s,Math.min(1e3*$(2,i),1e4))),this.destroyed)return;continue}this.render=this.createRender(this.backendType),this.attachDeviceHandlers(),this.generation=this.generation+1>>>0,this.resourceWaiting=!1,this.needsRedraw=!0,this.recoveringDevice=!1,this.start(),(t=this.onEvent)==null||t.call(this,{type:"deviceLost",generation:this.generation});return}this.recoveringDevice=!1,(n=this.onEvent)==null||n.call(this,{type:"recoveryFailed"})})}}function Ix(e){return Fe(this,null,function*(){if(!navigator.gpu)throw new Error("WebGPU is not available in this environment");const t=yield navigator.gpu.requestAdapter({powerPreference:"high-performance"});if(!t)throw new Error("Failed to acquire WebGPU adapter");const n=yield t.requestDevice(),i=e.getContext("webgpu");if(!i)throw new Error("Failed to acquire WebGPU canvas context");const r=navigator.gpu.getPreferredCanvasFormat();return i.configure({device:n,format:r}),{canvas:e,device:n,context:i,format:r}})}function lR(e,t,n,i){return Fe(this,null,function*(){const r=yield Ix(t);return new aR(e,r,n,i)})}class cR{constructor(t){this.map=(t==null?void 0:t.map)||{}}set(t,n,i){this.map[t]===void 0&&(this.map[t]={}),this.map[t][n]=i}get(t,n){const i=this.map[t];if(i!==void 0)return i[n]}has(t,n){const i=this.map[t];return i===void 0?!1:i[n]!==void 0}reduce(t,n){return Object.values(this.map).reduce((i,r)=>Object.values(r).reduce((s,o,a,l)=>t(s,o,a,l),i),n)}}m.ArrowGenerator=Io,m.BBoxType=gn,m.BLEND_EQUATION=IM,m.BLEND_FUNC=PM,m.BaseTileLoader=kd,m.Buffer=ht,m.BufferChannel=z0,m.BuildingModelGenerator=mi,m.COMMAND_TIER_BIAS=Sy,m.COMMAND_TIER_SHIFT=by,m.CULL_FACE_MODE=TM,m.Camera=Ks,m.CircleMarkerGenerator=il,m.ClassRegistry=fL,m.Collector=yF,m.CommandCommon=wn,m.CommandDrawCircleMarker=Vo,m.CommandDrawDemMesh=Ey,m.CommandDrawGltfModel=dt,m.CommandDrawLabelLine=bn,m.CommandDrawLabelPoint=ut,m.CommandDrawLine=An,m.CommandDrawLineParameterized=Kn,m.CommandDrawLineSprite=zn,m.CommandDrawMapMesh=Wo,m.CommandDrawMesh=Ds,m.CommandDrawMetricPoint=Uo,m.CommandDrawPointAnchor=ir,m.CommandDrawPointSprite=yt,m.CommandDrawPolygon=Zd,m.CommandDrawPolygon3d=Jn,m.CommandDrawPolygon3dTexture=Ho,m.CommandDrawPolygonTextured=kr,m.CommandFlags=Rn,m.CommandType=be,m.DEFAULT_CONTOUR_STYLE=Mg,m.DEFAULT_EMPTY_KEY=zh,m.DEFAULT_FLOORS_FLOOR_HEIGHT=xS,m.DEFAULT_FLOORS_METRO_FLOOR_HEIGHT=wS,m.DEFAULT_FONT=Gx,m.DEFAULT_FRAME_SIZE=lc,m.DEFAULT_ID_SCOPE=Qu,m.DEFAULT_LIGHTING_MODES=wF,m.DEFAULT_MAPGL_STYLE=kx,m.DEFAULT_MIN_TIERS_STYLE_ZOOM=cp,m.DEFAULT_MODELS_APPEAR_STRATEGY=Rh,m.DEM_ELEVATION_TILE_SIZE=QE,m.DEM_LIGHTING_MODE=qu,m.DEM_STYLE_LAYER_ID=vo,m.DEM_TILE_URL_FUNCTION=fm,m.DEM_TREE_SIZE=tu,m.DEPTH_FUNC=V0,m.DYNAMIC_MODEL_ID_SCOPE=aM,m.DYNAMIC_STYLE_ID=Rl,m.DashedLineGenerator=gi,m.DataKeyUsage=Qe,m.DemGenerator=Kt,m.Differ=Xv,m.DynamicStyle=A_,m.EARTH_CIRCUMFERENCE=tf,m.ECEF_EARTH_RADIUS=Oi,m.EMPTY_FEATURE_COLLECTION=Yl,m.EMPTY_SHADER_DEFINITIONS=ld,m.ENVIRONMENT_STYLE_LAYER_ID=Jf,m.Ecef=Lt,m.EcefDataState=kl,m.Evented=Af,m.FLAT_LEVEL_MAX=$l,m.FLOOR_ID_SCOPE=oM,m.FlatLevelRecord=ko,m.FnRegistry=cL,m.FrameFlags=Go,m.FrameHeader=we,m.GEOJSON_DEFAULT_MAX_DETAIL_LEVEL=Sd,m.GL_TRIANGLES=qo,m.GL_TRIANGLE_STRIP=Oh,m.GeoJsonSource=qv,m.GeoJsonSourceCore=Hv,m.GeoJsonSourceWorker=kL,m.GeoJsonTileSource=f3,m.GeoJsonViewportSource=u3,m.GltfDemPosition=x0,m.GltfModelFlags=Qd,m.GltfModelGenerator=Ki,m.HALF_WORLD_SIZE=2147483648,m.HandyIndexer=N0,m.HeatmapGenerator=Or,m.HideLevel=Ps,m.INVALID_FRAMEBUFFER_ID=za,m.INVALID_IDENTIFY_CENTER_COORD=Bc,m.IdScope=lM,m.LABELING_TEXTURE_BACKGROUND_COLOR=pF,m.LABELING_TEXTURE_DEM_MESH_COLOR=gF,m.LATEST_TILE_VERSION=xy,m.LRU=Pv,m.LabelGeometryType=ji,m.LabelIndex=Du,m.LabelLineGenerator=Br,m.LabelPointFlags=Ur,m.LabelSource=_o,m.LabelingAnimation=F0,m.LabelingElementType=Je,m.LabelingTileElement=fl,m.LayoutMiss=s0,m.LengthUnits=Wi,m.LineExtrusionGenerator=vi,m.LineGenerator=Rt,m.LineGeometry=ue,m.LinePatternType=Yu,m.MAP_DEFAULTS=Oc,m.MAP_HEIGHT_TO_TILE_HEIGHT=io,m.MAP_MESH_ABS_Z_BYTE_OFFSET=us,m.MAP_MESH_IS_PIVOT_BYTE_OFFSET=Ha,m.MAP_MESH_TEXTURE_INDEX=kA,m.MAP_POINTS_IN_METER=Ee,m.MAX_GUIDELINE_TEXTURE_SIZE=Hc,m.MAX_RECORD_SIZE=qd,m.MAX_UNDERGROUND_DEPTH=Wx,m.MODELS_TILES_VIEWPORT_PADDING=Ux,m.MainConnector=aL,m.MapMeshFlags=jd,m.MapMeshGenerator=Xn,m.MaterialCmd=fe,m.MaterialEnvFog=Vd,m.MaterialEnvGlobeHalo=Ud,m.MaterialEnvLight=tc,m.MaterialEnvShadow=Wd,m.MaterialEnvSky=ic,m.MaterialEnvStars=nc,m.MaterialFlags=ec,m.MaterialGltf=xn,m.MaterialKind=Ve,m.MaterialLabelPoint=sc,m.MaterialLineArrow=Ei,m.MaterialLineOneWay=nr,m.MaterialLinePattern=Gr,m.MaterialLineStripe=Ls,m.MaterialPointSprite=rc,m.MaterialPolygonTexture=Fs,m.MaterialWallTexture=ft,m.Mercator=me,m.MeshElevationWorker=C4,m.MeshFillSide=le,m.MeshFlags=ac,m.MeshGenerator=re,m.MeshMode=rr,m.ModelStepSource=Rr,m.ModelsWorker=_4,m.NAN_INDEX=Ft,m.OneWayLineGenerator=Dr,m.PBR_TEXTURE_INDEX=GA,m.POINT_CENTER_SIZE=Dc,m.PointSpriteFlags=Bs,m.PolygonExtrusionGenerator=jn,m.PolygonGenerator=Dn,m.PreLabelType=Qn,m.RasterGenerator=sl,m.RasterSetType=Ir,m.RenderBackendType=mh,m.ReservedLightingMode=po,m.RingPatchBuffer=h1,m.RingPatchTexture=d1,m.RingRecordType=c1,m.RingUploadBuffer=f1,m.RingUploadTexture=u1,m.RingWriter=R4,m.SIMPLE_MESH_STYLE_LAYER_ID=m_,m.SMAA_AREA_PNG_BASE64=wy,m.SMAA_SEARCH_PNG_BASE64=Ay,m.SUNDA_SINK_KINDS=O0,m.SceneObjectType=If,m.Shader=zl,m.ShaderAttribute=Xb,m.ShiftedLineGenerator=xo,m.StylePort=B4,m.TEXTURE_COORDS_TO_WEBGL=gw,m.TIER_TO_COLOR_INDEX=py,m.TRANSPORT_SIZE=QF,m.ThreadName=sr,m.TileLayer=Wv,m.TileObject=Ul,m.TileObjectBase=xv,m.TileStatus=dd,m.TransportHeader=tn,m.TwoKeyMap=cR,m.UNIVERSE_REGION_ID=Vx,m.UNUSED_STYLE_ID_SHIFT=AF,m.VAT_TEXTURE_INDEX=UA,m.WEBGL_COORDS_TO_TEXTURE=mw,m.WEB_MERCATOR_TO_WORLD_SIZE_MULTIPLIER=Ox,m.WorkerConnector=lL,m.ZenithSourceCore=wM,m.ZenithWorker=aF,m.ZoomDirection=yn,m.add=Tn,m.add$1=pr,m.add$2=Vw,m.addGeneratedDataToTileMod=wv,m.adjustGlobeDragSpeed=eA,m.affineStep=Xc,m.allFontGlyphsLoaded=FF,m.applyDefaultGraphicsPresets=_g,m.applyDefaults=Ci,m.applyStyleOptions=pI,m.assertUnreachable=Na,m.atlasSize=Yt,m.bezier=dv,m.bindUrl=CA,m.buildingAnimation=Xh,m.calcAngle=SA,m.calcBarycentricXY=ru,m.calcMidpoint=EA,m.calcSurfaceTangents=hm,m.calculateBox3DDiag=dA,m.captureLayoutKey=FP,m.center=fa,m.checkLayoutKey=LP,m.checkStyleAbort=L4,m.cityCommPoiLabelingConfig=jh,m.clamp=Ge,m.clampLat=sA,m.clampPoint=rA,m.clone=ew,m.clone$1=_w,m.commercialPoi=Rc,m.compare=Sa,m.compileRtlPlugin=yy,m.componentTypeToWebGl=Zb,m.contains=oA,m.convertStyleLayerTypeToHandy=AE,m.coordsToKey=De,m.copy=aw,m.copy$1=of,m.copy$2=kw,m.copy$3=ta,m.countHandyStyleIds=l_,m.create=Js,m.create$1=nt,m.create$2=gp,m.create$3=qs,m.create$4=pf,m.create$5=ua,m.create$6=Ye,m.createBox3D=fA,m.createExpressionDeps=E2,m.createGeoJsonMetatile=Ny,m.createGridState=Fv,m.createLayoutWorkStats=BP,m.createLoadedRasterSet=v2,m.createMetatile=zp,m.createObjectAttributesArray=Ze,m.createRenderRunner=lR,m.createTileInfo=Bt,m.cross=gr,m.debounce=Zv,m.decomposeMat4=MA,m.deepEqual=Hr,m.defaultCameraConfig=En,m.defaultLang=qh,m.defaultMarkerAnchor=lp,m.defaultMarkerIcon=ap,m.defaultModelsPath=rn,m.defaultShadowsSettings=fp,m.defaultSundaRenderConfig=l1,m.degToRad=Le,m.dem=Gh,m.dist=Bi,m.dist$1=ff,m.distance=Xs,m.dot=cf,m.dot$1=Li,m.dracoDecoderUrl=Dx,m.drawIdentifyScene=b_,m.earcut=_a,m.ease=pv,m.ecefDataStateFromBool=mC,m.emptyFeatureAttrs=Np,m.emptySourceAttrs=xf,m.encodeTilePointToEcefU16=Zn,m.entranceAnimation=Zh,m.equalArrays=Qx,m.equalSets=jx,m.equals=Zw,m.equals$1=sw,m.events=Hh,m.exactEquals=pw,m.exactEquals$1=ia,m.exactEquals$2=Rw,m.excludeItemFromArray=qx,m.exist=mv,m.expandBox3DByPoint=uA,m.expandByPoint=xr,m.expose=Jd,m.expressionValues=Fr,m.findVisibleTiles=Qp,m.finishStyleUpdatingAction=Gv,m.fixedMetatile=RA,m.fixedTileProps=wr,m.floors=Uc,m.fontResource=_P,m.fonts=on,m.forceGlStatusCheck=sv,m.fromGeo=iA,m.fromRotationTranslationScale=dw,m.fromScaling=uw,m.fromTranslationScale=sa,m.fromValues=bt,m.fromValues$1=Qc,m.generalize=PP,m.generateHaltonSequence=j2,m.generateHandyLayers=ju,m.generateIconElement=Ru,m.generateNotStretchableIconElement=NP,m.generatePointsOnSphere=Pg,m.generateSafely=L0,m.generateTextElement=pl,m.generateTileBounds=rv,m.geoJsonMetatileHash=Dh,m.geoLineDistance=Aw,m.geoPointsDistance=rf,m.geoToMapDistance=ca,m.get=pC,m.getArrayBuffer=Dl,m.getBoundsTileCoords=Gb,m.getCenterCorrection=$w,m.getClosestPointOnLineSegment=cb,m.getColorForShaders=cE,m.getCommandSize=Ty,m.getElevationFromTile=eT,m.getElevationFromTileSplit=tT,m.getElevationSampleFromTile=dm,m.getFontUrl=fI,m.getFractionalPart=Zx,m.getGlyphMetrics=BF,m.getIntermediateValue=$x,m.getJson=G0,m.getLabelingInfo=JI,m.getLayerImageProps=q0,m.getLineConstants=Ar,m.getMetersFromPixelsXY=nA,m.getModelUrl=uI,m.getPixelsPerMeter=uo,m.getPoiIconData=xI,m.getRandomValue=cs,m.getRawMemoryStats=a3,m.getResourceVersion=Bu,m.getSizeDependentImageUrl=h0,m.getStaticIconRasterSetKey=ss,m.getStaticTextureRasterSetKey=Ca,m.getStyleUrl=gI,m.getStyleZoom=Mp,m.getSubdomainFromString=ha,m.getSymbolLayers=av,m.getTextMetrics=CF,m.getTierFromLevels=RI,m.getTileBounds=Aa,m.getTileCoordsByCenterAndZoom=Pf,m.getTileModToGenerate=Tv,m.getTilesToAbortFetch=Mv,m.getTilesToFetch=Iv,m.getTilesToGenerate=_v,m.getTilesToRemove=Cv,m.getTotalMemory=bd,m.getTriple=ea,m.getUrl=$s,m.getUrlForIconMapIcon=Pl,m.getUrlFromTemplate=eo,m.getVisibleMapReplicas=kb,m.getZoomFromStyleZoom=tA,m.globeConfig=dr,m.handyColor=Mr,m.hashToString=Op,m.heightToZoom=yw,m.icons=Vh,m.identify=Gc,m.identity=Jc,m.index=Yx,m.inertia=kc,m.inferGeneratorType=jb,m.initTransportHeader=qF,m.int64ToString=P0,m.intersection=lA,m.intersection$1=rM,m.intersects=hf,m.invert=Zs,m.isArrayOfNumbers=Yn,m.isBetween=Zc,m.isCommercialCityPoi=l0,m.isCommercialModel=u0,m.isCommercialPoi=Tl,m.isCommercialPoi$1=Es,m.isCommercialPoiCity=yP,m.isCommercialPoiLabel=Co,m.isCommercialPoiPremium=xP,m.isCommercialPremiumPoi=c0,m.isExtractableHandyExpression=h2,m.isHandyExpression=Qt,m.isHandySimpleType=og,m.isInt64=YI,m.isInterpolateExpression=ag,m.isLabelingEcef=gm,m.isLatValid=aA,m.isLineStyleLayer=TT,m.isNullVector=bA,m.isNullish=Kx,m.isObject=Jx,m.isPersonalPoi=oI,m.isRtlPluginRequired=vy,m.isStyleColor=_n,m.isStyleGradient=Oa,m.isStyleId=vE,m.isStyleLayerHidable=wE,m.isStyleLayerType=xE,m.isStyleMixColor=M2,m.isTileOnSphereInViewport=Pa,m.isTileVisible=ba,m.isTypedArray=AI,m.keyServerPath=fr,m.keyToCoords=Ef,m.labeling=Jo,m.len=pp,m.len$1=aa,m.length=Pn,m.lerp=mr,m.lerp$1=Kc,m.lerp$2=Yr,m.lerp$3=Xw,m.limitString=V2,m.linePatternFromString=C0,m.linear=hv,m.loadModelsInfoStyleZoom=zc,m.log=ke,m.logEmptyTileGenerationResponse=Sg,m.logGltfError=Y2,m.lookAt=ef,m.mailboxSwap=o1,m.makeBinderContext=Vg,m.makeEnvironmentColor=ad,m.makeGeneratorContext=go,m.makeHandyDemLayer=od,m.makeHandyGroupOrLayer=a_,m.makeHandyLightStyle=$0,m.makeHandyRasterSet=Q0,m.makeHandyRasterSets=j0,m.makeHandyStyleLayer=rd,m.makeHandyStyleSteps=o_,m.makeLabelingContext=dn,m.mapHeightToTileHeight=Wt,m.mapPointPitch=Tw,m.mapPointTo32ZoomTileCoords=Nb,m.mapPointToTilePoint=Dt,m.mapToPixelDistance=Ew,m.maxTilePoint=ae,m.maxU32=Rx,m.maxUint16Value=He,m.measureStyle=F4,m.metricsTimeout=tp,m.modStatsGpu=Ad,m.modStatsJs=wd,m.modelCacheSize=kh,m.modelSizeGpu=s3,m.modelSizeJs=r3,m.models=Nh,m.mul=jw,m.mul$1=Zr,m.multiply=Di,m.multiply$1=gA,m.newFrameAction=Ov,m.normalize=jt,m.normalize$1=Fi,m.normalizeMapPoint=Iw,m.normalizeMousePosition=Xx,m.noteResource=gg,m.noteStateKey=Da,m.noteZoomPoint=Ba,m.numberToRgba=jc,m.optionsToTileAttrs=iv,m.ortho=hw,m.overlappedGroupName=Hi,m.packTexCoords=qt,m.performanceCheck=ep,m.pixelRatioToDpi=Vf,m.pixelToMapDistance=wp,m.pixelsAndMapDistanceToZoom=Ap,m.pointToLineDistance=rb,m.pointToLineSignedDistance=Wp,m.pointWithinTilePoints=no,m.preLabelingPoint=d0,m.prepareMetatile=Rp,m.processElement=KI,m.processFont=LF,m.projectToXyRect=_A,m.proxy=Oy,m.radToDeg=hr,m.rasterSetResource=i0,m.rbush=mo,m.readCommandRefs=YF,m.readMaterialRefs=XF,m.removeUndefined=AS,m.renameZenithEnumerationValues=xM,m.render=Qh,m.reserveHandyStyleIds=c_,m.reserveTextureIndex=ma,m.reset=df,m.resetGridState=md,m.resolveAnimationExpression=Og,m.resolveColor=li,m.resolveExpression=k,m.resolveFirstAnchorExpression=co,m.resolveGradient=aE,m.resolveLightingModes=uE,m.resolveNumber=ce,m.resolveSimpleLiteralExpression=si,m.resolveString=Mt,m.resolveTextureAnimationExpression=Rg,m.rotateVec2=TA,m.rotateX=Bw,m.rotateY=Dw,m.rtlAdapterPromise=NF,m.rtlPluginHash=Ws,m.rtlPluginUrl=sn,m.runPrecomputes=Zu,m.sample=kg,m.sampleColor=Ug,m.scale=Ri,m.scale$1=cA,m.scale$2=an,m.scale$3=Xr,m.scale$4=Hw,m.scaleAndAdd=af,m.selectMetricPointRaster=x2,m.selectRaster=os,m.set=Be,m.set$1=Uw,m.set$2=cw,m.setFixedElapsedTime=dC,m.setSeed=dP,m.setupMapboxRtlAdapterIfNeeded=kF,m.sign=$o,m.slerp=da,m.sourceUuid=Yv,m.splitPolylineByLength=ab,m.splitPolylineByMaxSize=lb,m.spreadTileObjects=ov,m.sqrDist=ow,m.sqrDist$1=Nw,m.squaredDistance=Tp,m.stabilizeStyleState=DP,m.start=gv,m.startStyleUpdatingAction=Nv,m.stop=fd,m.stride=Oo,m.styles=Wh,m.sub=ii,m.sub$1=ln,m.subtract=nM,m.subtract$1=Sp,m.template=Qr,m.tetragonBounds=wa,m.tetragonIntersectsBounds=Hp,m.textureSizeGpu=n3,m.textureSizeJs=xd,m.throttle=lF,m.tileCoordOffset=W,m.tileCoordsToMapPoint=ts,m.tileCoordsToOSM=Ta,m.tileHeight=_i,m.tileObjectStatsGpu=Vv,m.tileObjectStatsJS=Uv,m.tilePointScaleFactor=fn,m.tilePointToMapPoint=St,m.tilePointToOffsetSize=Rb,m.tileSizeZpt=256,m.tileZoomToSize=Mn,m.tiles=ur,m.toIdSortKey=Xm,m.toStyleColor=Ot,m.trackExpressionDeps=T2,m.traffic=Uh,m.transfer=eh,m.transformMat3=Fw,m.transformMat4=la,m.transformMat4$1=Qs,m.uint16ToTileCoords=ot,m.uniqId=ga,m.unpackPreLabelingResult=gP,m.update=vv,m.updateScene=Bv,m.urls=Ko,m.vertexTilePointToMapPoint=zb,m.viewportChangeAction=yd,m.viewportTilesReady=gd,m.workerResetInterval=Yh,m.worldBounds=bw,m.worldLoopBounds=Sw,m.worldSize=4294967296,m.worldWrapX=js,m.wrap=Fy,m.writeTileCoord=WF,m.z0Scale=Lh,m.zenithSourceAttrs=Gp,m.zenithToJakartaPropKey=gM,m.zoom=Kh,m.zoomToHeight=jr,m.zoomToScale=xw,m.zptPerInch=Hs,m.zptToSceneDistance=ww}));

_mapgl_d("worker",["./shared"],(function(n){var _n=Object.defineProperty,Dn=Object.defineProperties;var On=Object.getOwnPropertyDescriptors;var zt=Object.getOwnPropertySymbols;var Bn=Object.prototype.hasOwnProperty,Vn=Object.prototype.propertyIsEnumerable;var jt=Math.pow,Gt=(n,Y,Z)=>Y in n?_n(n,Y,{enumerable:!0,configurable:!0,writable:!0,value:Z}):n[Y]=Z,te=(n,Y)=>{for(var Z in Y||(Y={}))Bn.call(Y,Z)&&Gt(n,Z,Y[Z]);if(zt)for(var Z of zt(Y))Vn.call(Y,Z)&&Gt(n,Z,Y[Z]);return n},ge=(n,Y)=>Dn(n,On(Y));var Ht=(n,Y,Z)=>new Promise((Oe,ke)=>{var Be=w=>{try{me(Z.next(w))}catch(pe){ke(pe)}},Ve=w=>{try{me(Z.throw(w))}catch(pe){ke(pe)}},me=w=>w.done?Oe(w.value):Promise.resolve(w.value).then(Be,Ve);me((Z=Z.apply(n,Y)).next())});"use strict";function Y(s,e,t,r,o,i,l,c){var S;const{label:a}=r;if(!s.enabled||l.globeMode||t.type!=="point"||!((S=a.layoutElements)!=null&&S.includes(r))){n.processElement(e,t,s.collector,r,o,i,l,l.tileInfo,c);return}n.mapPointToTilePoint(Z,r.anchorWorld,l.tileInfo);const d=n.pointWithinTilePoints(Z),f=Be(r),h=r.generation;if(h!==void 0&&h.withinTile===d&&w(h.extras,f)&&me(h.checkPointBefore,a.checkPointOffset)&&n.checkLayoutKey(h.key,s.inputs)===n.LayoutMiss.None){if(!d){s.work.generationsReused++;return}const b=n.tileCoordOffset+Z[0],E=n.tileCoordOffset+Z[1],z=n.mapHeightToTileHeight(Z[2]);s.collector.replayRecording(h.recording,h.animDirection===o?void 0:D=>ke(D,o),(D,P)=>Ve(D,P,b,E,z)),a.checkPointOffset[0]=h.checkPointAfter[0],a.checkPointOffset[1]=h.checkPointAfter[1],s.work.generationsReused++;return}const u=performance.now(),g=a.checkPointOffset,v=[g[0],g[1]],m=n.createExpressionDeps(),x=n.trackExpressionDeps(m);s.collector.beginRecording();let L;try{n.processElement(e,t,s.collector,r,o,i,l,l.tileInfo,c)}finally{L=s.collector.endRecording(),n.trackExpressionDeps(x)}r.generation={key:n.captureLayoutKey(m,s.inputs),extras:f,recording:L,animDirection:o,withinTile:d,checkPointBefore:v,checkPointAfter:[g[0],g[1]]},s.work.generationsBuilt++,s.work.generationMs+=performance.now()-u}const Z=[0,0,0],Oe={raster:2,text:2};function ke(s,e){const t=s.styleLayer==="point"?Oe[s.sink]:void 0;if(t===void 0)return;const r=s.attributes.slice();return r[t]=e,r}function Be(s){var r,o,i;const{label:e,parent:t}=s;return[s.placementIndex,t?t.placementIndex:NaN,(r=e.textMetricsCache)==null?void 0:r.text,(o=e.textMetricsCache)==null?void 0:o.icon,(i=e.textMetricsCache)==null?void 0:i.text2,e.labelingElements.length]}function Ve(s,e,t,r,o){const i=s.views.position,l=s.elements.stride>>1;for(let c=e;c<s.elements.offset;c++){const a=c*l;i[a]=t,i[a+1]=r,i[a+2]=o}}function me(s,e){return Object.is(s[0],e[0])&&Object.is(s[1],e[1])}function w(s,e){for(let t=0;t<s.length;t++)if(!Object.is(s[t],e[t]))return!1;return!0}function pe(s){var t,r;let e=0;for(const o of s.values())for(const i of o)for(const l of i.labelingElements)for(const c of(r=(t=l.generation)==null?void 0:t.recording.writes)!=null?r:[])e+=c.vertices.byteLength+c.indices.byteLength;return e}class rt{constructor(e,t,r){this.line=new Int32Array(e);const o=this.line.length/4,{tiersOn:i,demMode:l}=r;if(t.screenSpace&&(!i||!l))for(let f=0;f<o;f++)i||(this.line[f*4+2]=0),l||(this.line[f*4+3]=0);this.lengths=[],this.angles=[];let c=t.componentDistanceStartWorld,a=this.line[0],d=this.line[1];for(let f=0;f<o;f++){const h=this.line[f*4]-a,u=this.line[f*4+1]-d;c+=Math.sqrt(h*h+u*u),this.lengths.push(c),a+=h,d+=u}this.finishLength=this.lengths[this.lengths.length-1],this.startLength=this.lengths[0],this.midLength=t.objectLengthWorld/2,this.vertexCount=o,this.angles.push(0);for(let f=1;f<o;f++){const h=this.line[(f-1)*4],u=this.line[f*4],g=this.line[(f-1)*4+1],v=this.line[f*4+1];this.angles.push(Math.atan2(v-g,u-h))}}resetHeights(){for(let e=0;e<this.vertexCount;e++)this.line[e*4+2]=0,this.line[e*4+3]=0}interpolate(e,t){const r=t,o=r-1,i=this.lengths[o],l=this.lengths[r],c=this.line[o*4],a=this.line[r*4],d=this.line[o*4+1],f=this.line[r*4+1],h=this.line[o*4+2],u=this.line[r*4+2],g=this.line[o*4+3],v=this.line[r*4+3],m=(e-i)/(l-i);return[(1-m)*c+m*a,(1-m)*d+m*f,(1-m)*h+m*u,(1-m)*g+m*v,this.angles[t]]}getSegmentIndex(e){for(let t=0;t<this.lengths.length;t++)if(e<this.lengths[t])return t;return this.lengths.length}}const Se=[0,0,0],le=[0,0,0,1],Fe=[NaN,NaN],Te=[0,0],Ee=[0,0],ne=1e3;class ot{constructor(e,t,r){const o=e.vertexCount;this.vertexCount=o,this.clip=new Array(o*4),this.screen=new Array(o*2).fill(NaN),this.segmentScreen=new Array(o*4).fill(NaN),this.segmentValid=new Array(o).fill(!1);for(let i=0;i<o;i++)Se[0]=e.line[i*4],Se[1]=e.line[i*4+1],Se[2]=e.line[i*4+2],it(le,Se,1,t),this.clip[i*4]=le[0],this.clip[i*4+1]=le[1],this.clip[i*4+2]=le[2],this.clip[i*4+3]=le[3],!(le[3]<=ne)&&(t.flat.project(Se,!1,Fe),this.screen[i*2]=Fe[0],this.screen[i*2+1]=Fe[1]);for(let i=1;i<o;i++){const l=this.mayGetVertexScreen(i-1,Te),c=this.mayGetVertexScreen(i,Ee);!l&&!c||(!l||!c)&&!this.mayFixScreenVertex(l?i-1:i,l?i:i-1,r,l?Ee:Te)||(this.segmentScreen[i*4]=Te[0],this.segmentScreen[i*4+1]=Te[1],this.segmentScreen[i*4+2]=Ee[0],this.segmentScreen[i*4+3]=Ee[1],this.segmentValid[i]=!0)}}mayGetSegmentDirection(e,t,r,o){if(t<1||t>this.vertexCount-1)return!1;const i=t*4,l=i-4,c=this.clip[i]-this.clip[l],a=this.clip[i+1]-this.clip[l+1],d=this.clip[i+3]-this.clip[l+3],f=e[3],h=(c*f-e[0]*d)*r[0],u=-(a*f-e[1]*d)*r[1],g=Math.sqrt(h*h+u*u);return g===0?!1:(o[0]=h/g,o[1]=u/g,!0)}getOffsetPoint(e,t,r,o,i){const l=r<0?-1:1;let c=Math.abs(r),a=e[0],d=e[1],f=o[0],h=o[1],u=t;for(;u>=1&&u<=this.vertexCount-1&&this.segmentValid[u];){const g=u*4,v=this.segmentScreen[g],m=this.segmentScreen[g+1],x=this.segmentScreen[g+2],L=this.segmentScreen[g+3],S=x-v,b=L-m,E=Math.sqrt(S*S+b*b);if(E===0){u+=l;continue}f=S/E,h=b/E;const z=l>0?x:v,D=l>0?L:m,P=z-a,T=D-d,y=Math.sqrt(P*P+T*T);if(c<=y)break;c-=y,a=z,d=D,u+=l}i[0]=a+f*l*c,i[1]=d+h*l*c}getOffsetSegmentIndex(e,t,r){const o=r<0?-1:1;let i=Math.abs(r),l=e[0],c=e[1],a=t;for(;a>=1&&a<=this.vertexCount-1&&this.segmentValid[a];){const d=a*4,f=this.segmentScreen[d],h=this.segmentScreen[d+1],u=this.segmentScreen[d+2],g=this.segmentScreen[d+3];if(u===f&&g===h){a+=o;continue}const v=o>0?u:f,m=o>0?g:h,x=v-l,L=m-c,S=Math.sqrt(x*x+L*L);if(i<=S)break;i-=S,l=v,c=m,a+=o}return a}getSegmentScreenAngle(e){if(e<1||e>this.vertexCount-1)return NaN;if(!this.segmentValid[e])return NaN;const t=e*4,r=this.segmentScreen[t+2]-this.segmentScreen[t],o=this.segmentScreen[t+3]-this.segmentScreen[t+1];return r===0&&o===0?NaN:Math.atan2(o,r)}mayGetSegmentVertexScreen(e,t){if(!this.segmentValid[e])return!1;const r=this.segmentScreen[e*4+2],o=this.segmentScreen[e*4+3];return Number.isNaN(r)||Number.isNaN(o)?!1:(t[0]=r,t[1]=o,!0)}mayGetVertexScreen(e,t){const r=this.screen[e*2];return Number.isNaN(r)?!1:(t[0]=r,t[1]=this.screen[e*2+1],!0)}mayFixScreenVertex(e,t,r,o){const i=this.clip[e*4+3];if(i<=ne)return!1;const l=this.clip[t*4+3];if(l>ne)return!1;const c=(ne-l)/(i-l),a=n.getIntermediateValue(this.clip[t*4],this.clip[e*4],c)/ne,d=n.getIntermediateValue(this.clip[t*4+1],this.clip[e*4+1],c)/ne;return o[0]=(a*.5+.5)*r[0],o[1]=r[1]-(d*.5+.5)*r[1],!0}}function it(s,e,t,r){s[0]=e[0],s[1]=e[1],s[2]=e[2],s[3]=t,n.transformMat4(s,s,r.viewProjectionMatrix)}function Yt(s,e){return s.length===e.length&&s.every((t,r)=>t===e[r])}function ct(s,e,t){return!s.screenSpace&&e!==void 0&&e.tiersOn===t.tiersOn&&e.demMode===t.demMode}class Xt{constructor(){this.axesBuilt=0,this.axesReused=0,this.labelsByTiers={}}add(e){const t=e.id,r=e.componentDistanceStart,o=e.tiers,l=e.screenSpace&&o&&o[0]?o[0]:0;this.labelsByTiers[l]===void 0&&(this.labelsByTiers[l]={});const c=this.labelsByTiers[l];c[t]===void 0&&(c[t]={});const a=c[t];a[r]===void 0&&(a[r]=[]),a[r].push(e)}merge(e,t,r,o=!1){const i=[],{tiersOn:l,demMode:c,globeMode:a}=r,d=Object.keys(this.labelsByTiers).map(f=>this.labelsByTiers[f]);for(const f of d)for(const h in f){const u=f[h],g=Object.keys(u).sort((m,x)=>Number(m)-Number(x));let v=0;for(;v<g.length;){const m=g[v];if(u[m].length===0){v++;continue}const x=[];let L=u[m].pop();for(;L!==void 0;)if(x.push(L),(L.componentDistanceStart!==0||L.componentDistanceEnd!==0)&&u[L.componentDistanceEnd]!==void 0){const S=L;if(L=u[L.componentDistanceEnd].pop(),L){const b=S.mapPointVertices.length;(S.mapPointVertices[b-4]!==L.mapPointVertices[0]||S.mapPointVertices[b-3]!==L.mapPointVertices[1])&&(L=void 0)}}else L=void 0;if(x.length===1){const S=x[0],b=S.ownAxis;if(o&&ct(S,b,r))S.axis=b.axis,this.axesReused++;else{this.axesBuilt++;const E=o&&!S.screenSpace;S.axis=new rt(S.mapPointVertices,S,{tiersOn:l,demMode:c}),E&&(S.ownAxis={axis:S.axis,tiersOn:l,demMode:c})}lt(S,a),S.screenSpace&&(S.clipAxis=new ot(S.axis,e,t)),i.push(S)}else if(x.length>1){const S=x[0],b=S.stitchedAxis;if(o&&ct(S,b,r)&&Yt(b.members,x))S.axis=b.axis,this.axesReused++,i.push(S);else{this.axesBuilt++;const E=o&&!S.screenSpace;i.push(this.stitch(x,e,t,r)),E&&(S.stitchedAxis={members:x,axis:S.axis,tiersOn:l,demMode:c})}}}}return i}stitch(e,t,r,o){const{tiersOn:i,demMode:l,globeMode:c}=o;let a=0;for(let u=0;u<e.length;u++)a+=e[u].mapPointVertices.length;a-=(e.length-1)*4;const d=new Int32Array(a);let f=0;for(let u=0;u<e.length;u++){const g=e[u].mapPointVertices,v=u>0?4:0;for(let m=v;m<g.length;m++)d[f++]=g[m]}const h=e[0];return h.axis=new rt(d,h,{tiersOn:i,demMode:l}),lt(h,c),h.screenSpace&&(h.clipAxis=new ot(h.axis,t,r)),e[0]}}function lt(s,e){s.screenSpace&&(s.axis.vertexCount<=n.MAX_GUIDELINE_TEXTURE_SIZE&&!e||(s.screenSpace=!1,s.axis.resetHeights()))}class Ut{constructor(e,t,r,o,i,l,c,a,d,f,h,u){this.type=n.LabelingElementType.Box,this.marginTop=0,this.marginRight=0,this.marginBottom=0,this.marginLeft=0,this.id=e,this.label={layer:{innerId:0},styleId:-100,id:this.id,idSortKey:n.toIdSortKey(this.id),symbol:"nevermind",phase:NaN},this.groupPriority=u!=null?u:n.maxU32,this.itemPriority=h!=null?h:1,this.parent=f,this.placementIndex=0,this.labelingGroup=d,this.labelingGroupTable=a.labelingGroups.table,this.anchorWorld=n.create$3(),n.copy$1(this.anchorWorld,o),l!==0&&(this.anchorWorld[2]*=l),this.anchorGeo=n.Mercator.toGeo(this.anchorWorld),this.anchorScreen=c.project(this.anchorGeo),n.add(this.anchorScreen,this.anchorScreen,i),this.boxes=[[0,0,t,r]]}}const We=n.degToRad(n.labeling.lineLabelsHidePitchDeg);function Ze(s,e,t,r,o,i,l,c){var x,L;const{inputs:a}=c,d=n.fontResource(r),f=n.fontResource(n.DEFAULT_FONT);n.noteResource(d),n.noteResource(f);const h=n.getResourceVersion(a,d),u=n.getResourceVersion(a,f),g=(x=s.textMetricsCache)==null?void 0:x[e];if(c.cachesEnabled&&g!==void 0&&g.fontName===r&&g.fontVersion===h&&g.defaultFontVersion===u&&g.epoch===a.epoch)return c.work.metricsReused++,g.metrics;const v=performance.now(),m=n.allFontGlyphsLoaded(r,s.ranges,l)?n.getTextMetrics(t,o,i[r],i[n.DEFAULT_FONT]):void 0;return c.work.metricsMs+=performance.now()-v,c.work.metricsComputed++,c.cachesEnabled&&((L=s.textMetricsCache)!=null||(s.textMetricsCache={}),s.textMetricsCache[e]={fontName:r,fontVersion:h,defaultFontVersion:u,epoch:a.epoch,metrics:m}),m}function at(s,e){Number.isNaN(s.demElevation)?s.elevation=0:s.elevation=(s.demElevation-(e!=null?e:0))*n.MAP_POINTS_IN_METER}function ft(s){var t;const e={collidable:[],overlapped:[],icons:[]};for(let r=0;r<s.length;r++){const o=s[r];if(o.labelingGroup===n.overlappedGroupName||((t=o.parent)==null?void 0:t.labelingGroup)===n.overlappedGroupName){e.overlapped.push(o);continue}e.collidable.push(o),o.type===n.LabelingElementType.Icon&&e.icons.push(o)}return e}function Ie(s,e,t,r){for(let o=0;o<s.collidable.length;o++)e.push(s.collidable[o]);for(let o=0;o<s.overlapped.length;o++)t.push(s.overlapped[o]);for(let o=0;o<s.icons.length;o++){const i=s.icons[o];r.set(i.label.id,i)}}function dt(s,e,t,r){const o=t.flat.project(e);ut(s,o[0]-s.anchorScreen[0],o[1]-s.anchorScreen[1],r)}function ut(s,e,t,r){s.boxes.push([e-r,t-r,e+r,t+r])}function qt(s,e,t,r,o,i,l,c,a){const d=e.layer.type==="oneWayLine"?t:r;for(const f of s.candidates){if(f.kind==="point"){e.labelingElements=f.elements;for(const g of f.elements)g.refresh(c.buildingHeight,l,c.globeMode,a);Ie(f.partition,r,o,i);continue}if(n.mapPointPitch(l.position,f.anchorWorld,c.center)>We)continue;const{element:u}=f;if(u.refresh(c.buildingHeight,l,c.globeMode,a),f.boxWorld.length>0){u.boxes=[];for(const g of f.boxWorld)dt(u,g,l,f.halfFontSize)}d.push(u)}}const Pe=n.degToRad(n.labeling.axisAngleToleranceDeg),ht=n.labeling.axisCheckDistancePx,$t=n.degToRad(n.labeling.screenLineLabelsHidePitchDeg),ze=[0,0,0,0],Ge=[0,0],je=[0,0],He=[NaN,NaN],Ye=[0,0],Jt=.5,Qt=.5,gt=1.5;function wt(s,e,t){if(t<=ne)return gt;const r=Math.hypot(s[0]-e[0],s[1]-e[1],s[2]-e[2]);return n.clamp(n.getIntermediateValue(1,r/t,Jt),Qt,gt)}function Mt(s,e,t,r,o,i,l,c,a,d,f,h,u){var P;n.trackExpressionDeps(void 0);const g=[],v=[],m=[],x=[],L=new Map,S=Kt(s,o),b=new Xt,E=e.styleState._floorHeight;for(let T=0;T<s.length;T++){const y=s[T],I=o.get(y);if(I===void 0)continue;const R=e.styleState._activeFloorIds,C=e.styleState._backgroundFloorIds;for(let N=0;N<I.length;N++){const p=I[N];if(p.source===n.LabelSource.Tile&&d.has(p.id)&&!p.floorId||p.floorId&&(p.planLevel=h[p.floorId],!n.isCommercialPoiLabel(p)&&(R.length===0||!R.includes(p.floorId))&&!(p.layer.type==="point"&&p.layer.style.floorCulling==="all-floors"&&C.includes(p.floorId))))continue;const O=r.getStyle(p.styleId);if(!O){console.error(`Not found style ${p.styleId} in labeling#collectLabelingElements`);continue}if(p.source!==n.LabelSource.PersonalPoi&&S.personalPoi.has(p.id)&&!n.isCommercialPoiLabel(p)||p.source===n.LabelSource.PersonalPoi&&S.commercialPoi.has(p.id))continue;if(u.reuseLayouts&&p.layoutElements!==void 0&&p.layoutKey!==void 0&&n.checkLayoutKey(p.layoutKey,u.inputs)===n.LayoutMiss.None){if(Ce(p,e.styleZoom)){at(p,e.elevation),p.labelingElements=p.layoutElements;for(const J of p.labelingElements)J.refresh(e.buildingHeight,t,e.globeMode,E);u.work.pointLayoutsReused++,Ie(p.layoutPartition,x,m,L)}continue}const G=n.createExpressionDeps(),B=n.trackExpressionDeps(G);switch(p.planLevel&&n.noteStateKey("_floorHeight"),p.layer.type){case"point":{if(mt(p,l,c,e.styleState,e.styleZoom,e.pitch,O,f,e.elevation,u)&&Ce(p,e.styleZoom))if(p.geometryType===n.LabelGeometryType.Line)p.prepareDeps=G,b.add(p);else{const M=[p.mapPointVertices[0],p.mapPointVertices[1],p.mapPointVertices[2],p.mapPointVertices[3],0],ae=performance.now();n.getLabelingInfo(p,M,O,p.layer,e,t,a),u.work.pointLayoutMs+=performance.now()-ae,u.work.pointLayoutsBuilt++;const k=ft(p.labelingElements);u.cachesEnabled&&(p.layoutKey=n.captureLayoutKey(G,u.inputs),p.layoutElements=p.labelingElements,p.layoutPartition=k),Ie(k,x,m,L)}break}case"labelLine":{mt(p,l,c,e.styleState,e.styleZoom,e.pitch,O,f,e.elevation,u)&&Ce(p,e.styleZoom)&&(p.prepareDeps=G,b.add(p));break}case"oneWayLine":Ce(p,e.styleZoom)&&(p.prepareDeps=G,b.add(p));break}n.trackExpressionDeps(B)}}const z=performance.now(),D=b.merge(t,e.size,{tiersOn:e.tiersOn,demMode:e.demMode,globeMode:e.globeMode},u.cachesEnabled);u.work.mergeMs+=performance.now()-z,u.work.axesBuilt+=b.axesBuilt,u.work.axesReused+=b.axesReused;for(let T=0;T<D.length;T++){const y=D[T],I=r.getStyle(y.styleId);if(!I){console.error(`Not found style ${y.styleId} in labeling#collectLabelingElements`);continue}const R=y.lineLayout;if(u.reuseLayouts&&y.layoutKey!==void 0&&n.checkLayoutKey(y.layoutKey,u.inputs)===n.LayoutMiss.None&&R!==void 0&&R.axis===y.axis&&R.zoom===e.zoom){qt(R,y,v,x,m,L,t,e,E),u.work.lineLayoutsReused++;continue}const C=(P=y.prepareDeps)!=null?P:n.createExpressionDeps(),N=n.trackExpressionDeps(C),p=u.cachesEnabled&&!y.screenSpace?[]:void 0,O=performance.now();y.layer.type==="point"?en(x,m,L,y,I,t,e,a,p):tn(v,x,y,I,t,e,p),n.trackExpressionDeps(N),u.work.lineLayoutMs+=performance.now()-O,u.work.lineLayoutsBuilt++,p&&(y.layoutKey=n.captureLayoutKey(C,u.inputs),y.lineLayout={axis:y.axis,zoom:e.zoom,candidates:p})}return i.forEach(({id:T,width:y,height:I,position:R,offset:C,labelingGroup:N,parentPoiId:p})=>{let O;if(p&&(O=L.get(p),!O))return;const G=r.getStyle(n.DYNAMIC_STYLE_ID);if(!G){console.error(`Not found style ${n.DYNAMIC_STYLE_ID} in labeling#collectLabelingElements`);return}const B=new Ut(T,y,I,R,C,e.buildingHeight,t,G,N,O,O==null?void 0:O.itemPriority,O==null?void 0:O.groupPriority);g.push(B)}),{boxElements:g,oneWayTileElements:v,noLabelingElements:m,otherTileElements:x}}function Kt(s,e){const t={personalPoi:new Set,commercialPoi:new Set};for(const r of s){const o=e.get(r);if(o!==void 0)for(const i of o)i.source===n.LabelSource.PersonalPoi?t.personalPoi.add(i.id):n.isCommercialPoiLabel(i)&&t.commercialPoi.add(i.id)}return t}function mt(s,e,t,r,o,i,l,c,a,d){var x,L,S;const{layer:f}=s;if(f.type!=="point"&&f.type!=="labelLine")return!1;at(s,a);const h=n.makeLabelingContext(o,i,r,!1,s.tileData);if(n.rtlAdapterReady&&!s.rtlProcessed&&(s.label=(x=n.processRTLTextIfNeeded(s.label))!=null?x:"",s.label2=n.processRTLTextIfNeeded(s.label2),s.iconLabel=n.processRTLTextIfNeeded(s.iconLabel),s.updateRanges(),n.expressionValues(f.style.textFont).forEach(b=>{b.length&&c(b,s.ranges)}),f.type==="point"&&f.style.textFont2&&n.expressionValues(f.style.textFont2).forEach(b=>{b.length&&c(b,s.ranges)}),f.type==="point"&&f.style.iconTextFont&&n.expressionValues(f.style.iconTextFont).forEach(b=>{b.length&&c(b,s.ranges)}),s.rtlProcessed=!0),!s.rtlProcessed)return!1;const u=n.resolveString(f.style.textFont,h);let g;if(u&&s.label&&(g=Ze(s,"text",s.label,u,f.style.textLetterSpacing,e,t,d),g&&(s.textMetrics=g)),f.type==="labelLine")return!u||!!g;const v=n.resolveString((L=f.style.iconTextFont)!=null?L:"",h);if(v&&s.iconLabel){const b=Ze(s,"icon",s.iconLabel,v,f.style.iconTextLetterSpacing,e,t,d);b&&(s.iconTextMetrics=b)}const m=n.resolveString((S=f.style.textFont2)!=null?S:"",h);if(u&&s.label&&m&&s.label2){const b=Ze(s,"text2",s.label2,m,f.style.textLetterSpacing,e,t,d);b&&(s.textMetrics2=b)}return!u||!s.label?!v||!s.iconLabel||!!s.iconTextMetrics:!!g&&(!v||!s.iconLabel||!!s.iconTextMetrics)&&(!m||!s.label2||!!s.textMetrics2)}function en(s,e,t,r,o,i,l,c,a){const{layer:d}=r;if(d.type!=="point")return;const{zoom:f,styleZoom:h}=l,u=Math.floor(h),g=f+(u-h),{startLength:v,midLength:m,finishLength:x}=r.axis,L=n.makeLabelingContext(u,l.pitch,l.styleState,!1,r.tileData);n.noteZoomPoint(h);const S=Math.max(n.pixelToMapDistance(n.resolveNumber(d.style.duplicationSpacing,L),g),1),b=n.pixelToMapDistance(d.style.endingOffsets,f),E=v+(m-v)%S,z=v+b,D=x-b;for(let P=E;P<D;P+=S)if(P>z){const T=r.axis,y=P,I=T.getSegmentIndex(y),R=T.interpolate(y,I);n.getLabelingInfo(r,R,o,r.layer,l,i,c);const C=ft(r.labelingElements);a==null||a.push({kind:"point",elements:r.labelingElements,partition:C}),Ie(C,s,e,t)}}function tn(s,e,t,r,o,i,l){const{layer:c}=t;if(c.type!=="labelLine"&&c.type!=="oneWayLine")return;const{zoom:a,styleZoom:d}=i,f=Math.floor(d),h=a+(f-d),{startLength:u,midLength:g,finishLength:v}=t.axis,m=n.makeLabelingContext(d,i.pitch,i.styleState,!1,t.tileData),x=n.makeLabelingContext(f,i.pitch,i.styleState,!1,t.tileData);n.noteZoomPoint(d);let L,S,b,E;if(c.type==="labelLine"){const N=n.resolveNumber(c.style.textFontSize,m)/n.fonts.baseSize,p=n.resolveNumber(c.style.textFontSize,x)/n.fonts.baseSize;L=t.textMetrics.maxWidth*N,S=t.textMetrics.maxWidth*p,b=n.pixelToMapDistance(n.resolveNumber(c.style.textDuplicationSpacing,x),h),E=n.pixelToMapDistance(Math.max(c.style.lineEndingOffsets,c.style.textLabelingSideMargin),a)}else L=n.resolveNumber(c.style.lineLength,m),S=n.resolveNumber(c.style.lineLength,x),b=n.pixelToMapDistance(n.resolveNumber(c.style.duplicationSpacing,x),h),E=n.pixelToMapDistance(c.style.endingOffsets,a);const z=n.pixelToMapDistance(S,h),P=n.pixelToMapDistance(L,a)/2,T=b+z,y=u+(g-u)%T,I=u+P+E,R=v-P-E,C=c.type!=="labelLine"?s:e;for(let N=y;N<R;N+=T)N>I&&nn(C,t,N,P,L,o,i,r,l)}function nn(s,e,t,r,o,i,l,c,a){const d=e.axis,{zoom:f,styleZoom:h,pitch:u}=l,{startLength:g,finishLength:v}=d,m=d.getSegmentIndex(t),x=d.interpolate(t,m),L=n.mapPointPitch(i.position,x,l.center);it(ze,x,1,i);const S=wt(i.position,l.center,ze[3]);if(e.screenSpace?L>$t||!rn(e,x,m,o/2,i,l,S):a===void 0&&L>We||!sn(e,t,r,f,h,u,l.styleState))return;const b=e.layer.type==="oneWayLine",E=b?n.LabelingElementType.OneWayLine:n.LabelingElementType.LineText,z=n.makeLabelingContext(h,u,l.styleState,!1,e.tileData),D=new n.LabelingTileElement(e,E,x,l.buildingHeight,i,c,l.globeMode,l.styleState._floorHeight,z);D.anchorPosition=t,D.anchorSegmentIndex=m,D.halfLabelWidth=r;const P=[];let T=0;!b&&(D.overflowStyleZoom=n.getStyleZoom(n.pixelsAndMapDistanceToZoom(o,v-g),x),e.screenSpace?cn(D,ze,o/2,l,S):T=on(D,e,t,r,l,i,P),D.boxes.length===0)||(a==null||a.push({kind:"line",element:D,anchorWorld:x,boxWorld:P,halfFontSize:T}),!(!e.screenSpace&&L>We)&&s.push(D))}function sn(s,e,t,r,o,i,l){if(s.layer.type==="oneWayLine")return!0;const c=s.axis,a=n.makeLabelingContext(o,i,l,!1,s.tileData),d=n.resolveNumber(s.layer.style.textFontSize,a)/n.fonts.baseSize,f=c.getSegmentIndex(e-t),h=c.getSegmentIndex(e+t),u=n.pixelToMapDistance(ht*d,r);for(let g=f;g<h;g++){if(g>1&&Ne(c.angles[g-1],c.angles[g])>Pe)return!1;const v=c.getSegmentIndex(c.lengths[g]-u);if(v!==0){const m=c.angles[v],x=c.angles[c.getSegmentIndex(c.lengths[g]+u)];if(Ne(m,x)>Pe)return!1}}return!0}function Ne(s,e){const t=Math.abs(s-e);return t>Math.PI?2*Math.PI-t:t}function rn(s,e,t,r,o,i,l){const{clipAxis:c,layer:a}=s;if(a.type!=="labelLine"||!c)return!0;const d=n.makeLabelingContext(i.styleZoom,i.pitch,i.styleState,!1,s.tileData),f=n.resolveNumber(a.style.textFontSize,d)/n.fonts.baseSize,h=ht*f*l;o.flat.project(e,!1,He);const u=r*l,g=c.getOffsetSegmentIndex(He,t,-u);if(g<1)return!1;const v=c.getOffsetSegmentIndex(He,t,u);if(v>c.vertexCount-1)return!1;for(let m=g;m<v;m++){const x=c.getSegmentScreenAngle(m);if(Number.isNaN(x))continue;const L=c.getSegmentScreenAngle(m-1);if(!Number.isNaN(L)&&Ne(L,x)>Pe)return!1;if(!c.mayGetSegmentVertexScreen(m,Ye))continue;const S=c.getOffsetSegmentIndex(Ye,m,-h);if(S===0)continue;const b=c.getSegmentScreenAngle(S),E=c.getSegmentScreenAngle(c.getOffsetSegmentIndex(Ye,m,h));if(!Number.isNaN(b)&&!Number.isNaN(E)&&Ne(b,E)>Pe)return!1}return!0}function on(s,e,t,r,o,i,l){const{axis:c,layer:a}=e;if(a.type!=="labelLine")return 0;const{zoom:d,styleZoom:f,pitch:h}=o,u=n.makeLabelingContext(f,h,o.styleState,!1,e.tileData),g=n.resolveNumber(a.style.textFontSize,u),v=g/2,m=n.pixelToMapDistance(g,d),x=n.pixelToMapDistance(a.style.textLabelingSideMargin,d),L=Math.max(0,t-r+m/2-x),S=Math.min(c.lengths[c.lengths.length-1],t+r-m/2+x);let b=c.getSegmentIndex(L);for(let E=L;E<S;E+=m){for(;c.lengths[b]<E;)b++;l.push(c.interpolate(E,b))}for(;c.lengths[b]<S;)b++;l.push(c.interpolate(S,b));for(const E of l)dt(s,E,i,v);return v}function cn(s,e,t,r,o){const{label:i}=s;if(i.layer.type!=="labelLine")return;const{clipAxis:l,layer:c}=i;if(!l)return;const{anchorSegmentIndex:a}=s;if(e[3]<=ne||!l.mayGetSegmentDirection(e,a,r.size,Ge))return;const d=n.makeLabelingContext(r.styleZoom,r.pitch,r.styleState,!1,i.tileData),f=n.resolveNumber(c.style.textFontSize,d)*o,h=f/2,u=c.style.textLabelingSideMargin,g=-(t*o)+h-u,v=t*o-h+u;for(let m=g;m<v;m+=f)pt(s,l,m,h,Ge);pt(s,l,v,h,Ge)}function pt(s,e,t,r,o){const{anchorScreen:i,anchorSegmentIndex:l}=s;e.getOffsetPoint(i,l,t,o,je),ut(s,je[0]-i[0],je[1]-i[1],r)}function Ce(s,e){const{source:t,detailLevel:r,layer:{minzoom:o,maxzoom:i}}=s,l=t===n.LabelSource.PersonalPoi,c=l||o>r,a=l||i<r+1||r===n.tiles.maxDetailLevel;return(!c||e>=o)&&(!a||e<i)}function be(s){return typeof s!="boolean"&&s.type==="attrs"}function St(s){return typeof s!="boolean"&&s.type==="unextractable"}function Ae(s){if(!n.isHandyExpression(s))return[!!s];let e=[];const t=[];switch(s.type){case"all":const o=s.array.map(Ae);for(const c of o){const a=[];for(const d of c){if(d===!1)return[!1];be(d)?a.push(d):St(d)&&t.push(d)}a.length>0&&(e.length===0?e=a:e=bt(e,a))}break;case"match":if(!n.isExtractableHandyExpression(s.input))return[{type:"unextractable",exp:s}];if(s.input.type==="precompute")return[{type:"unextractable",exp:s}];const i=s.input.property,l=s.defaultOutput;for(const c of s.cases){const a=Ae(c.output),d=[];c.values.forEach(f=>{d.push({type:"attrs",attrs:{[i]:f}})});for(const f of a)if(be(f))for(const h of bt([f],d))e.push(h);else if(St(f)){t.push(f);for(const h of d)e.push(h)}else if(f===!0&&!l)for(const h of d)e.push(h)}break;case"==":{let c,a;if(n.isExtractableHandyExpression(s.leftValue)&&n.isHandySimpleType(s.rightValue))c=s.leftValue.property,a=s.rightValue;else if(n.isExtractableHandyExpression(s.rightValue)&&n.isHandySimpleType(s.leftValue))c=s.rightValue.property,a=s.leftValue;else return[{type:"unextractable",exp:s}];e.push({type:"attrs",attrs:{[c]:a}});break}default:return[{type:"unextractable",exp:s}]}return e.concat(t)}function bt(s,e){const t=[];for(const r of s)for(const o of e)t.push({type:"attrs",attrs:te(te({},r.attrs),o.attrs)});return t}class yt{constructor(){this.layers=[],this.keyStat={},this.orderedKeys=[],this.tree=null,this.treeNodesCount=0,this.traverseCount=0,this.traverseIterations=0}addLayers(e){for(const t of e)t.type==="custom"||!t.filter||(this.layers.push(t),this.statLayerKeys(t));this.buildTree()}getLayers(e,t){const r=[],o=(i,l)=>{if(this.traverseIterations+=1,!i)return;for(const f of i.leafs)r.push(f);const c=this.orderedKeys[l];if(!c)return;const a=t[e[c]],d=n.isInt64(a)?n.int64ToString(a):a;d!==void 0&&o(i.children[d],l+1),o(i.novalue,l+1)};return this.traverseCount+=1,o(this.tree,0),r}stat(){const e=this.traverseIterations/this.traverseCount||0;return{tree:this.tree,treeNodes:this.treeNodesCount,layers:this.layers.length,keyStat:this.keyStat,itersPerTraverse:e}}statLayerKeys(e){const r=Ae(e.filter).filter(o=>be(o))[0];if(!(!r||!be(r)))for(const o in r.attrs)this.keyStat[o]===void 0&&(this.keyStat[o]=0),this.keyStat[o]+=1}getOrderedKeys(){return Object.entries(this.keyStat).sort(([t,r],[o,i])=>i-r).map(([t,r])=>t)}buildTree(){this.orderedKeys=this.getOrderedKeys();const e=[];for(const t of this.layers){const o=Ae(t.filter).filter(be);o.length===0&&e.push(t);for(const i of o){const l=new Set(Object.keys(i.attrs));let c=0;const a=i.attrs;let d=this.tree;for(let f=0;f<=this.orderedKeys.length;f++){if(c===l.size){d==null||d.leafs.push(t);break}const h=this.orderedKeys[f],u=this.orderedKeys[f+1]||"";if(d||(d=this.makeTreeNode(h),this.tree===null&&(this.tree=d)),l.has(h)){const g=a[h];d.children[g]||(d.children[g]=this.makeTreeNode(u)),d=d.children[g],c+=1}else d.novalue||(d.novalue=this.makeTreeNode(u)),d=d.novalue}}}e.length>0&&(this.tree||(this.tree=this.makeTreeNode("")),this.tree.leafs=e)}makeTreeNode(e){return this.treeNodesCount+=1,{key:e,children:{},novalue:null,leafs:[]}}}class xt{constructor(){this.preparedStyles=new Map,this.installedStyleIds=[],this.metaStyles=new Map,this.layerTrees=new Map}proxySyncStyle(e){const t=this.metaStyles.get(e.id);if(t)for(const o in t.rasterSets.byKey){const i=t.rasterSets.byKey[o];i.type===n.RasterSetType.Unique&&!e.rasterSets.byKey[o]&&(e.rasterSets.byKey[o]=i,e.rasterSets.byIndex[i.index]=i)}const r=new yt;r.addLayers(e.layers),this.layerTrees.set(e.id,r),this.metaStyles.set(e.id,e),this.retainStyle(e.id)}prepareStyle(e,t){const r=new yt;r.addLayers(t.layers),this.preparedStyles.set(e,{style:t,tree:r})}commitPreparedStyle(e){const t=this.preparedStyles.get(e);if(!t)throw new Error("Unknown prepared style");this.metaStyles.set(t.style.id,t.style),this.layerTrees.set(t.style.id,t.tree)}releasePreparedStyle(e){const t=this.preparedStyles.get(e);t&&(this.preparedStyles.delete(e),this.metaStyles.get(t.style.id)===t.style&&this.retainStyle(t.style.id))}abortPreparedStyle(e){const t=this.preparedStyles.get(e);this.preparedStyles.delete(e),t&&this.metaStyles.get(t.style.id)===t.style&&this.removeUnusedStyle(t.style.id)}getStyle(e){return this.metaStyles.get(e)}getLayers(e,t,r){const o=this.layerTrees.get(e);return o?o.getLayers(t,r):[]}removeUnusedStyle(e){e<1||(this.metaStyles.delete(e),this.layerTrees.delete(e))}retainStyle(e){e<1||this.installedStyleIds.includes(e)||(this.installedStyleIds.push(e),this.installedStyleIds.length>n.UNUSED_STYLE_ID_SHIFT&&this.removeUnusedStyle(this.installedStyleIds.shift()))}}function Lt(s,e){const t=new Map;let r;const o=(i,l)=>{var d;const{request:c}=l,a=(d=t.get(c))!=null?d:{};switch(i){case"prepare-raw":{const{raw:f,id:h,allocation:u,options:g}=l;t.set(c,a);const v=performance.now(),m=n.makeHandyStyleSteps(f,h,u);let x=m.next();for(;!x.done;)x=m.next();const L=x.value;n.measureStyle(a,"build",performance.now()-v),n.applyStyleOptions(L,g);const S=performance.now();return e.prepareStyle(c,L),n.measureStyle(a,"tree",performance.now()-S),a}case"commit":e.commitPreparedStyle(c);return;case"release":e.releasePreparedStyle(c),t.delete(c);return;case"abort":e.abortPreparedStyle(c),t.delete(c);return;default:throw new Error(`Unknown style preparation method: ${i}`)}};s.addEventListener("message",({data:i})=>{var l;(l=i.msg)!=null&&l.stylePreparationPort&&(r==null||r.close(),r=new n.StylePort(i.msg.port,o))})}function vt(s){return{collector:s,prevLabelingElements:[],prevSurvivedElements:new Map,prevPlacements:new Map}}function Xe(s,e){var t;return(t=s.prevPlacements.get(e))!=null?t:e.placementIndex}function kt(s){let e=2166136261;const t=JSON.stringify(s.data.map(({symbol:r,sink:o,generatedObjects:i})=>[r,o,i.map(({attributes:l,rangeStart:c,rangeEnd:a})=>[l,c,a])]));for(let r=0;r<t.length;r++)e=Math.imul(e^t.charCodeAt(r),16777619);for(const r of s.transferable){if(!(r instanceof ArrayBuffer))continue;const o=new Uint8Array(r);for(let i=0;i<o.length;i++)e=Math.imul(e^o[i],16777619)}return e>>>0}function ln(s){const e=new Map;for(const t of[s.noLabelingElements,s.oneWayTileElements,s.otherTileElements])for(const r of t)r.placementIndex!==-1&&e.set(r.id,r);return e}function Tt(s){let e=2166136261;for(const[t,r]of s){const o=t+":"+r.placementIndex+";";for(let i=0;i<o.length;i++)e=Math.imul(e^o.charCodeAt(i),16777619)}return e>>>0}function an(s,e,t){return s?{shadowChecked:1,shadowMismatch:+(Tt(s.survivedElements)!==e),shadowGeometryMismatch:+(kt(s.collectorOutput)!==kt(t))}:{shadowChecked:0,shadowMismatch:0,shadowGeometryMismatch:0}}const fn=new Map;function dn(s){const e=new n.WorkerConnector(s),t=new n.FnRegistry(e),r=new n.Collector("labeling"),o=new xt;Lt(s,o);const i=t.get(n.ThreadName.Main,"loadFont"),l=new Map,c=new Map,a=vt(r);let d;const f=new n.TwoKeyMap,h=new n.TwoKeyMap,u={};let g=0;const v=new Map,m=()=>{g++};let x=0;const L=k=>{var _;v.set(k,((_=v.get(k))!=null?_:0)+1),x++};let S,b="on";const E=k=>{b=k};t.set("setLayoutCacheMode",E);const z=n.throttle(()=>{r.reset(),d==null||d.collector.reset()},n.workerResetInterval),D=k=>{n.setSeed(k)};t.set("setComPoiRandomSeed",D);const P=()=>{const k=r.getBucketsMemoryFootprint(),_=[];let V=0;Array.from(l.keys()).forEach(j=>{const H=l.get(j);H&&(V+=H.length,_.push({label:{[j]:H.map(()=>({label:1}))}}))});const W=ge(te({collector:{buckets:k}},d&&{shadowCollector:{buckets:d.collector.getBucketsMemoryFootprint()}}),{generationCache:pe(l),labeling:_});return{js:ge(te({},W),{"--labelsCount":V,"--sum":n.getTotalMemory(W)})}};t.set("getMemoryFootprint",P);const T=(k,_,V,W,j,H)=>{const ye=n.unpackPreLabelingResult(V,_,o,W,j,H);l.set(k,ye)};t.set("appendLabels",T);function y(k,_){for(const V of _)f.has(k,V)||(i(k,V),f.set(k,V,!0))}const I=(k,_)=>{c.set(k,_)};t.set("appendLabelBox",I);const R=k=>{c.delete(k)};t.set("removeEmptyBoxLabel",R);const C=k=>{l.delete(k),c.delete(k)};t.set("removeLabels",C);function N(k,_,V){if(k.has(V.label.sourceId))return n.LabelingAnimation.none;const W=_.prevSurvivedElements.get(V.id),j=H=>Xe(_,H);return W===void 0||j(W)===void 0||W.type===n.LabelingElementType.Icon&&W.layer.innerId!==V.layer.innerId?n.LabelingAnimation.fadeIn:j(W)===V.placementIndex?n.LabelingAnimation.none:n.LabelingAnimation.fadeIn}const p=(k,_,V,W,j,H,ye,Re,Q)=>{const fe=performance.timeOrigin+performance.now(),re=new Set(j),de=[],oe=new Set;b==="shadow"?d!=null||(d=vt(new n.Collector("labeling"))):d=void 0;const xe=d?[a,d]:[a],ue=new Map(xe.map(F=>[F,{labelingElements:[],survivedElements:new Map}]));V.forEach((F,X)=>{const $=new n.Camera(F),qe=new Set,_e=[..._];k.forEach(({sourceId:A,animate:q,labelsKeys:ie})=>{q||qe.add(A);for(const K of ie)_e.push(K)}),_e.sort(),n.stabilizeStyleState(F.styleState,S),S=F.styleState;const Et={styleZoom:F.styleZoom,pitch:F.pitch,styleState:F.styleState,pixelRatio:W,epoch:g,resourceVersions:v,resourceStamp:x},It=(A,q)=>{const ie=performance.now(),K={inputs:Et,cachesEnabled:q,reuseLayouts:q&&V.length===1,work:n.createLayoutWorkStats()},ce=Mt(_e,F,$,o,l,c,u,h,W,re,y,Re,K),{noLabelingElements:En,oneWayTileElements:In,otherTileElements:Rt}=ce,_t=performance.now(),Dt={sortMs:0,placeMs:0},Pn=n.generalize(Rt,ce.boxElements,F,ye?fn:A.prevSurvivedElements,H,$,Dt),Ot=performance.now(),Bt={collector:A.collector,enabled:K.reuseLayouts,inputs:Et,work:K.work},Ke=[...En,...In,...Rt],et=ln(ce);for(let ee=0;ee<Ke.length;ee++){const U=Ke[ee],{label:{styleId:De,layer:nt}}=U;if(U.placementIndex===-1)continue;const Le=N(qe,A,U),ve=o.getStyle(De);if(!ve){console.error(`Not found style ${De} in labeling#processLabels`);continue}Y(Bt,ve,nt,U,Le,W,F,X)}const Vt=performance.now(),{prevLabelingElements:Ft}=A;for(let ee=0;ee<Ft.length;ee++){const U=Ft[ee],{id:De,label:nt,layer:Le}=U,{styleId:ve}=nt,Zt=o.getStyle(ve);if(!Zt){console.error(`Not found style ${ve} in labeling#processLabels`);continue}if(qe.has(U.label.sourceId))continue;const st=Xe(A,U),he=et.get(De);if(st===-1||st===(he==null?void 0:he.placementIndex)&&(U.type!==n.LabelingElementType.Icon||U.layer.innerId===(he==null?void 0:he.layer.innerId))||F.styleZoom<U.overflowStyleZoom||F.styleZoom<Le.minzoom||F.styleZoom>=Le.maxzoom)continue;const{parent:se}=U,An=U.placementIndex,Rn=se==null?void 0:se.placementIndex;U.placementIndex=st,se&&(se.placementIndex=Xe(A,se));try{Y(Bt,Zt,Le,U,n.LabelingAnimation.fadeOut,W,F,X)}finally{U.placementIndex=An,se&&(se.placementIndex=Rn)}}const tt=ue.get(A);for(const ee of Ke)tt.labelingElements.push(ee);tt.survivedElements=new Map([...tt.survivedElements,...et]);const Wt=performance.now(),Nn=A.collector.getAccumulatedData(),Cn=performance.now();return{collected:ce,survivedElements:et,debugStorage:Pn,collectorOutput:Nn,layout:K,timings:te({collectMs:_t-ie,generalizeMs:Ot-_t,generateMs:Vt-Ot,fadeOutMs:Wt-Vt,packMs:Cn-Wt},Dt)}},bn=d&&It(d,!1),{collected:yn,survivedElements:Pt,debugStorage:$e,collectorOutput:Je,layout:xn,timings:Ln}=It(a,b!=="off"),{boxElements:Qe,oneWayTileElements:vn,otherTileElements:we,noLabelingElements:kn}=yn;let Nt=0;for(const A of Je.transferable)oe.add(A),A instanceof ArrayBuffer&&(Nt+=A.byteLength);const Ct=[];for(const A of Qe)A.placementIndex!==-1&&Ct.push(A.label.id);const At=new Map,Tn=n.tetragonBounds(F.tilesBounds);for(const A of we)if(A.placementIndex!==-1&&n.isCommercialPoi$1(A)&&n.contains(Tn,A.anchorWorld)){const q={};n.isCommercialPoiCity(A)?q.adsPriority="city":n.isCommercialPoiPremium(A)&&(q.adsPriority="premium"),At.set(A.label.id,q)}const Me={survivedLabelBoxIds:Ct,survivedCommPois:Array.from(At).map(A=>{const q={id:A[0]};return A[1].adsPriority!==void 0&&(q.adsPriority=A[1].adsPriority),q}),collectorOutput:Je};if(Q){const A=Tt(Pt);Me.stats=ge(te(ge(te({},Ln),{labels:_e.reduce((q,ie)=>{var K,ce;return q+((ce=(K=l.get(ie))==null?void 0:K.length)!=null?ce:0)},0),elements:we.length+Qe.length,boxes:we.reduce((q,ie)=>q+ie.boxes.length,0)+Qe.length,noCollisionElements:kn.length+vn.length,survived:Pt.size,bytes:Nt,placementHash:A}),an(bn,A,Je)),{layoutWork:xn.work})}if($e){const A=new Int32Array($e.length);A.set($e),Me.labels=A.buffer,oe.add(A.buffer)}de.push(Me)});for(const[F,X]of ue)F.prevLabelingElements=X.labelingElements,F.prevSurvivedElements=X.survivedElements,F.prevPlacements=new Map(X.labelingElements.map($=>[$,$.placementIndex]));return z(),{results:de,transferable:Array.from(oe),startAt:fe,endAt:performance.timeOrigin+performance.now()}};t.set("processLabels",p);const O=(k,_)=>{u[k]||(u[k]={}),L(n.fontResource(k));const V=u[k];for(const W in _)V[W]=_[W]};t.set("appendFont",O);const G=(k,_)=>{h.set(k,_,!0),L(n.fontResource(k))};t.set("markFontAsLoaded",G);const B=(k,_)=>{const V=o.getStyle(k);if(!V){console.error(`Not found style ${k} in labeling#addNewRasterSets`);return}const{rasterSets:W}=V;_.forEach(j=>{L(n.rasterSetResource(j.key)),W.byIndex[j.index]=j,W.byKey[j.key]=j})};t.set("addNewRasterSets",B);const J=(k,_)=>{var Re;const V=o.getStyle(k);if(!V){console.error(`Not found style ${k} in labeling#updatePackingInfo`);return}const{rasterSets:W}=V,j=new Set,H=7,ye=_.length/H;for(let Q=0;Q<ye;Q++){const fe=_[Q*H],re=_[Q*H+1],de=_[Q*H+6],oe=_[Q*H+2],xe=_[Q*H+3],ue=_[Q*H+4],F=_[Q*H+5],X=W.byIndex[fe];if(X===void 0){console.error(`Not found raster set with index ${fe}`);continue}if(j.has(X.key)||(j.add(X.key),L(n.rasterSetResource(X.key))),X.isSvg)X.rasters[re]={rasterIndex:re,rasterSetIndex:fe,x:oe,y:xe,w:ue,h:F,anchorX:X.anchorX,anchorY:X.anchorY,atlasIndex:de,isPacked:!0};else{const $=(Re=X.rasters[re])!=null?Re:{rasterIndex:re,rasterSetIndex:fe,x:oe,y:xe,w:ue,h:F,anchorX:0,anchorY:0,atlasIndex:de,isPacked:!0};X.rasters[re]=$,$.x=oe,$.y=xe,$.w=ue,$.h=F,$.atlasIndex=de,$.isPacked=!0}}};t.set("updatePackingInfo",J);const M=()=>{for(const k of[a,d])k&&(k.prevLabelingElements=[],k.prevSurvivedElements=new Map,k.prevPlacements=new Map)};t.set("clearPreviousLabels",M);const ae=(...k)=>(m(),o.proxySyncStyle(...k));t.set("syncStyle",ae),t.set("loadRtlPlugin",n.compileRtlPlugin),t.set("markRtlPluginLoaded",()=>{m(),n.markAsReady&&n.markAsReady()})}function un(s){const e=new n.WorkerConnector(s),t=new n.FnRegistry(e);new n.ClassRegistry(t).set("ModelsWorker",n.ModelsWorker)}function hn(s,e,t,r,o,i,l,c,a){if(!t)return s.getAccumulatedData();const d=c.coords[3],{tileProps:f}=e,h=Object.keys(f).length,u=[],g=n.pixelRatioToDpi(i),v=n.makeGeneratorContext(o,n.emptySourceAttrs,f,u,n.emptyFeatureAttrs,!0,void 0,c);for(const m of l.tile){const{color:x=0,color2:L=0,geo:S,road:b,normals:E,zLevel:z=0,is_immersive:D,logicalLevels:P}=m;for(let T=0;T<h;T++)u[T]=NaN;u[f.db_sublayer]="Traffic_jams",u[f.traffic_color]=x,u[f.traffic_color2]=L,u[f.traffic_road_class]=b,u[f.traffic_road_z_level]=z,u[f.db_tiers]=P?[n.getTierFromLevels(P.begin,P.end)]:void 0,u[f.db_has_immersive_counterpart]=Number(D),u[f.beginningIsCut]=0,u[f.endingIsCut]=0;for(let T=0;T<S.length;T++){const y=S[T],I=E[T],R=[],C=[],N=[],p=[];for(let B=0;B<y.length;B++)R[B]=y[B][0]*n.uint16ToTileCoords,C[B]=y[B][1]*n.uint16ToTileCoords,N[B]=I[B][0],p[B]=I[B][1];const O={x:R,y:C,normal_x:N,normal_y:p},G=r.getLayers(t.id,f,u).filter(B=>n.resolveExpression(B.filter,v));G.length===0&&v.id&&s.idIndexer.addOrphanId(v.id),n.generateHandyLayers(s,t,G,v,e,n.LATEST_TILE_VERSION,d,a,c,g,O)}}return s.getAccumulatedData()}let Ue=[];function gn(s,e,t,r,o,i,l,c,a){var E,z,D;const{tileProps:d,dictionaries:f}=r,h=Object.keys(d).length,u=new Set(l),g=[];if(((E=f.db_sublayer)==null?void 0:E.s_personal_poi)===void 0)return s.getAccumulatedData();for(let P=0;P<h;P++)g[P]=NaN;const v=n.pixelRatioToDpi(i),m=n.create(),x=[];for(const P of c){const T=n.Mercator.fromGeo(P.point);n.expandByPoint(m,T),x.push(T)}const L=n.getBoundsTileCoords(m),S=n.createTileInfo(L),b=n.makeGeneratorContext(t,n.emptySourceAttrs,d,g,n.emptyFeatureAttrs,!0,void 0,S);for(let P=0;P<c.length;P++){const T=c[P],y=n.create$1();n.mapPointToTilePoint(y,x[P],S);const I=T.id;b.id=I;const R={x:[y[0]],y:[y[1]]};for(let N=0;N<h;N++)g[N]=NaN;g[d.db_sublayer]="s_personal_poi",g[d.db_object_class]=(D=T.humanReadableClassId)!=null?D:(z=r.reverseDictionaries.db_object_class)==null?void 0:z[T.classId],g[d.db_label]=T.name,g[d.db_icon_priority]=1,g[d.db_label_priority]=0,g[d.selected]=u.has(I)?1:0,g[d.db_region]=o,Ue=e.layers.filter(N=>n.resolveExpression(N.filter,b)),Ue.length===0&&b.id&&s.idIndexer.addOrphanId(b.id),n.generateHandyLayers(s,e,Ue,b,r,n.LATEST_TILE_VERSION,void 0,a,S,v,R)}return s.getAccumulatedData()}class mn{constructor(){this.cache=new Map,this.pendingRequests=new Map}fetch(e,t,r,o,i){return new Promise(l=>{const c=pn(e,o,i,t,r),a=n.coordsToKey(e),d=n.getJson({url:c},(f,h)=>{if(this.pendingRequests.delete(a),f!==void 0){f.status!==204&&console.error(f),this.cache.set(a,void 0),l();return}const u=h[0];u?this.cache.set(a,u):this.cache.set(a,void 0),l()});this.pendingRequests.set(a,{xhr:d,resolve:l})})}get(e){return this.cache.get(e)}delete(e){this.cache.delete(e)}abortRequest(e){const t=this.pendingRequests.get(e);t!==void 0&&(t.xhr.abort(),t.resolve(),this.pendingRequests.delete(e))}}function pn(s,e,t,r,o){const i=jt(2,s[2])-1,l=s[0],a=(i-s[1]&16777215)*(1<<24)+(l&16777215);return n.template(n.traffic.url,{protocol:o,host:r,z:String(s[2]),tiles:String(a),regions:e.join(","),time:String(t)})}function Sn(s){const e=new n.WorkerConnector(s),t=new n.FnRegistry(e),r=new n.ClassRegistry(t),o=new mn,i=new xt;Lt(s,i);const l={main:{addNewRasterSets:t.get(n.ThreadName.Main,"addNewRasterSets")},labeling:{addNewRasterSets:t.get(n.ThreadName.Labeling,"addNewRasterSets")}},c={},a=new n.Collector("parser"),d=n.throttle(()=>a.reset(),n.workerResetInterval),f=()=>{const y=a.atlasPacker.getNewRasterSets();y.size&&y.forEach((I,R)=>{l.main.addNewRasterSets(R,I),l.labeling.addNewRasterSets(R,I)})},h={sources:{},collector:a,styleManager:i,syncNewRasterSets:f,debouncedResetCollector:d};r.set("GeoJsonSource",n.GeoJsonSourceWorker,h,["fetchTiles"]);const u={collector:a,metatiles:c,styleManager:i,syncRasterSets:f,resetCollector:d,createImageBitmap:s.createImageBitmap?s.createImageBitmap.bind(s):void 0};r.set("ZenithWorker",n.ZenithWorker,u,["fetchTiles"]);const g={collector:a,resetCollector:d};r.set("MeshElevationWorker",n.MeshElevationWorker,g,["fetchTiles"]);const v=(y,I)=>{c[y]=I};t.set("setMetatile",v);const m=()=>{var p;const y=a.getIndexerStats(),I=a.getStatsAfterReset(),R=a.getBucketsMemoryFootprint(),C=[];(p=r.classes.get("ZenithWorker"))==null||p.hosts.forEach(O=>{O.tileLoader&&O.tileLoader.cache.size>0&&O.tileLoader.cache.forEach((G,B)=>{C.push({[B]:O.tileLoader.cache.get(B).reduce((J,M)=>J+M.data.byteLength,0)})})});const N={collector:{buckets:R,reset:I,idIndexer:y},zenit:{cache:C}};return{js:ge(te({},N),{"--sum":n.getTotalMemory(N)})}};t.set("getMemoryFootprint",m),t.set("setForceInteractivity",y=>{a.setForceInteractivity(y)});const x=(...y)=>i.proxySyncStyle(...y);t.set("syncStyle",x);const L=y=>new Promise(I=>{n.getArrayBuffer({url:y},(R,C)=>{if(R||C.byteLength===0){I(void 0);return}if(s.createImageBitmap){const N=new Blob([C],{type:"image/png"});createImageBitmap(N).then(p=>{I({isBitmap:!0,data:[p],transferable:[p]})})}else I({isBitmap:!1,data:[C],transferable:[C]})})});t.set("prepareAtlas",L);const S=y=>{for(let C=0;C<y.length;C+=3){const N=y[C+2],p={type:n.RasterSetType.Loaded,isSvg:!1,index:N,key:`loaded-${N}`,name:"",fileName:"",rasters:[{rasterSetIndex:N,rasterIndex:0,w:y[C],h:y[C+1],atlasIndex:0,x:0,y:0,isPacked:!1,anchorX:0,anchorY:0}]};a.atlasPacker.pack(p,[y[C]],1)}const I=a.atlasPacker.getPackedRasters(),R=[];return I!==void 0&&R.push(I.buffer),{packedRasters:I,transferable:R}};t.set("packRasters",S);const b=y=>o.fetch(y.coords,y.tileServer,y.tileProtocol,y.regionIds,y.timestamp);t.set("fetchTrafficTile",b);const E=y=>{o.delete(y)};t.set("deleteTrafficTile",E);const z=y=>{o.abortRequest(y)};t.set("abortTrafficTileRequest",z);const D=n.createMetatile(["db_sublayer","traffic_road_class","traffic_color","traffic_road_z_level","db_tiers","db_has_immersive_counterpart","beginningIsCut","endingIsCut","traffic_color2"],["Traffic_jams"]),P=({coords:y,pixelRatio:I,styleState:R,styleId:C,sourceId:N})=>{const p=n.coordsToKey(y),O=n.createTileInfo(y),G=[],B=[],J=1,M=i.getStyle(C);if(!M)return Promise.resolve({results:G,transferable:B});const ae=o.get(p);if(ae){const k=hn(a,D,M,i,R,I,ae,O,N);G.push({regionId:J,metatileHash:0,styleId:M.id,collectorOutput:k}),B.push(...k.transferable)}return Promise.resolve({results:G,transferable:B})};t.set("generateTrafficTile",P);const T=(y,I,R,C,N,p,O,G)=>{const B=i.getStyle(p);if(!B)return;const J=gn(a,B,O,c[R],I,C,N,y,G);return d(),f(),{collectorOutput:J,transferable:J.transferable,styleId:B.id}};t.set("generatePersonalPoi",T)}if(self.name==="render"){const s=(e,t,r,o)=>Ht(null,null,function*(){return n.proxy(yield n.createRenderRunner(e,t,r,o))});n.expose(s)}else self.addEventListener("message",s=>{const{msg:e}=s.data;if("youare"in e)switch(e.youare){case"labeling":dn(self);break;case"models":un(self);break;case"parser":Sn(self);break;default:throw new Error("Unknown worker type")}})}));

_mapgl_d("index",["exports","./shared"],(function(ie,n){var YP=Object.defineProperty,QP=Object.defineProperties;var JP=Object.getOwnPropertyDescriptors;var J_=Object.getOwnPropertySymbols;var KP=Object.prototype.hasOwnProperty,eA=Object.prototype.propertyIsEnumerable;var Re=Math.pow,K_=(ie,n,We)=>n in ie?YP(ie,n,{enumerable:!0,configurable:!0,writable:!0,value:We}):ie[n]=We,I=(ie,n)=>{for(var We in n||(n={}))KP.call(n,We)&&K_(ie,We,n[We]);if(J_)for(var We of J_(n))eA.call(n,We)&&K_(ie,We,n[We]);return ie},V=(ie,n)=>QP(ie,JP(n));var q=(ie,n,We)=>new Promise((Jn,Kn)=>{var Js=Ot=>{try{Bt(We.next(Ot))}catch(vn){Kn(vn)}},ze=Ot=>{try{Bt(We.throw(Ot))}catch(vn){Kn(vn)}},Bt=Ot=>Ot.done?Jn(Ot.value):Promise.resolve(Ot.value).then(Js,ze);Bt((We=We.apply(ie,n)).next())});"use strict";var ri,ji;var We=document.createElement("style");We.textContent=`.mapgl-hover{cursor:pointer}.mapgl-dragging{cursor:grabbing}.mapgl-rotating{cursor:move}.mapgl_QEdaFvncPWE-{width:32px;box-shadow:0 1px 3px #26262680;border-radius:4px;display:flex;flex-direction:column;overflow:hidden;background:#fff}.mapgl_mjx-K8iaDdc-{all:revert;padding:0;outline:0;border:none;cursor:pointer;background:#fff;width:32px;height:32px;color:#262626;box-sizing:border-box}.mapgl_mjx-K8iaDdc-:hover{opacity:.7}.mapgl_mjx-K8iaDdc-:active{color:#028eff}.mapgl_mjx-K8iaDdc-:disabled{background:#f2f2f2;color:#929292;cursor:default}.mapgl_zKZCVsRur9c-{border-bottom:1px solid #e6e6e6}.mapgl_3t-wJELDATg-{border-bottom:none}.mapgl_ON-gf73kIU0-{background:#fff;box-shadow:0 1px 3px #26262680;border-radius:4px;width:32px;overflow:hidden}.mapgl_mWyZxMObEi8-{all:revert;padding:0;outline:0;border:none;cursor:pointer;box-sizing:border-box;font-size:18px;font-weight:400;width:32px;height:32px;color:#262626;background:#fff}.mapgl_FwnEmRmDBLg-:hover{opacity:.7}.mapgl_uSuUHuf71nM-{background:#299400;color:#fff}.mapgl_LdqAv9Ly624-{background:#ffb81c;color:#fff}.mapgl_udRZCM1quWE-{background:#fe5000;color:#fff}.mapgl_uSuUHuf71nM-:hover,.mapgl_LdqAv9Ly624-:hover,.mapgl_udRZCM1quWE-:hover{color:#262626b3}.mapgl_K-1Yb8HCVpQ-{display:block!important}.mapgl_K-1Yb8HCVpQ- .mapgl_CLps5xx6CNs-{height:20px!important;display:block!important}.mapgl_r8Wn2E5pGh0-{pointer-events:none;position:absolute;top:0;left:0;width:100%;height:100%;display:flex;justify-content:center;align-items:center;padding:10px;background-color:#0003;cursor:default}.mapgl_ir0vRf5QXrk-{text-align:center;font-size:24px;font-family:Helvetica,Arial,sans-serif;font-weight:700;color:#fff}.mapgl_h2pl79nAYpk-{position:relative}.mapgl_64D1bmNQN3Q-{display:flex;max-height:40vh;background:#fff;width:32px;overflow:hidden;border-radius:4px;box-shadow:0 1px 3px #26262680}.mapgl_jdJbkjpLO7k-{width:100%;overflow-x:hidden;overflow-y:auto;-moz-padding-end:17px;-webkit-padding-end:17px;-webkit-margin-end:-17px}.mapgl_54Rmy50n6Fw-{display:flex;flex-direction:column-reverse}.mapgl_3i1QoGerxio-{all:revert;padding:0;border:none;background:#fff;height:32px;width:32px;color:#262626;cursor:pointer;border-bottom:1px solid #e6e6e6;box-sizing:border-box;flex-shrink:0}.mapgl_3i1QoGerxio-:focus{outline:0}.mapgl_3i1QoGerxio-:first-child{border-bottom:none}.mapgl_3i1QoGerxio-:hover{color:#262626b3}.mapgl_3i1QoGerxio-:active{color:#028eff}.mapgl_3i1QoGerxio-:disabled{background:#f2f2f2;color:#929292;fill:#929292;cursor:default}.mapgl_wGplqJ4hHPc-{font-size:18px;line-height:32px;font-weight:400;overflow-wrap:break-word;position:relative;text-align:center;height:100%}.mapgl_wGplqJ4hHPc- svg{margin-top:3px}.mapgl_PkWXKxsq1Kc-:after{content:"";position:absolute;top:4px;bottom:4px;width:4px;height:4px;border-radius:50%;background:#028eff}.mapgl_GbM3JIwbvBI-{overflow:hidden;display:flex}.mapgl_GbM3JIwbvBI- .mapgl_MX6K1s-5thI-{transform:scale(.7);margin-top:10px}.mapgl_GbM3JIwbvBI- .mapgl_aMwUNIDCavU-{transform:scale(.6);margin-left:-10px;margin-top:-10px;width:100%}.mapgl_z0m6n5pr5no-{position:absolute;pointer-events:none;inset:0}.mapgl_ITPUswrhaGk-{position:absolute;display:flex;z-index:50;pointer-events:none;width:100%;height:100%}.mapgl_ITPUswrhaGk->div>*{pointer-events:auto}.mapgl_Px-KwzXdVa0-{flex-direction:column;align-items:flex-start}.mapgl_SCX3EYsS-Cw-{flex-direction:row;justify-content:center;align-items:flex-start}.mapgl_i42TyWqpCPk-{flex-direction:column;align-items:flex-end}.mapgl_-zKby6nN-nU-{flex-direction:column;justify-content:center;align-items:flex-start}.mapgl_SlQM4-ZNKF0-{flex-direction:column;justify-content:center;align-items:flex-end}.mapgl_lNg3h7Hg-Mo-{flex-direction:column-reverse;align-items:flex-start}.mapgl_grOepPBwilk-{flex-direction:row;justify-content:center;align-items:flex-end}.mapgl_CiHYefDPhI0-{flex-direction:column-reverse;align-items:flex-end}.mapgl_Px-KwzXdVa0->div+div,.mapgl_i42TyWqpCPk->div+div,.mapgl_-zKby6nN-nU->div+div,.mapgl_SlQM4-ZNKF0->div+div{margin-top:10px}.mapgl_lNg3h7Hg-Mo->div+div,.mapgl_CiHYefDPhI0->div+div{margin-bottom:10px}.mapgl_SCX3EYsS-Cw->div+div,.mapgl_grOepPBwilk->div+div{margin-left:10px}.mapgl_9m2ynAxdBT0-{background:#ffffffad;border-width:0 1px 1px 1px;border-color:#7a7a7a;border-style:solid;border-radius:0;min-width:64px;height:16px;overflow:hidden;pointer-events:none!important}.mapgl_sR4nXEQ3L2M-{min-width:50px;height:12px;margin-top:2px;margin-left:6px;font-family:Helvetica,Arial,sans-serif!important;font-style:normal;font-weight:400;font-size:9px;line-height:12px;color:#262626}.mapgl_54Xq9OUdARA-{font-family:Helvetica,Arial,sans-serif!important;font-size:8px!important;line-height:8px!important;text-align:right!important;display:flex;align-items:flex-start;color:#6d7173!important}.mapgl_qYE18V9u8c0-{display:block}a.mapgl_wYSwIqldiqU-{color:#6d7173!important;text-decoration:none!important}a.mapgl_wYSwIqldiqU-:hover{color:#929292!important}
/*$vite$:1*/`,document.head.appendChild(We);function Jn(s,e,t){if(s.length===0)return;const i=n.degToRad(e),r=n.create();for(const a of s){const l=n.Mercator.fromGeo(a);n.rotateVec2(l,-i),n.expandByPoint(r,l)}const o=n.create$1();return n.center(o,r),n.rotateVec2(o,i),{center:o,zoom:Kn(r,t)}}function Kn(s,e){return Math.min(n.pixelsAndMapDistanceToZoom(e[0],Math.abs(s.max[0]-s.min[0])),n.pixelsAndMapDistanceToZoom(e[1],Math.abs(s.max[1]-s.min[1])))}function Js(s,e,t){const i=Jn(s,e,t);if(i)return{zoom:i.zoom,center:n.Mercator.toGeo(i.center)}}function ze(s,e,t){const i=s.getBoundingClientRect();return[e-i.left-s.clientLeft,t-i.top-s.clientTop]}function Bt(s,e){const t=[];for(let i=0;i<s.length;i++)t[i]=ze(e,s[i].clientX,s[i].clientY);return t}function Ot(s){return s.touches.length>1}const vn=n.Mercator.fromGeo,ef=n.Mercator.toGeo;function tf(s,e,t,i,r,o,a={top:0,right:0,bottom:0,left:0},l={top:0,right:0,bottom:0,left:0},c=!1){return new n.Camera({center:n.Mercator.fromGeo(s),zoom:e,rotation:n.degToRad(t),size:i,pitch:n.degToRad(r),viewport:a,padding:l,cameraConfig:n.defaultCameraConfig,globeMode:c,styleState:{}}).project(o)}function nf(s,e,t,i,r,o,a={top:0,right:0,bottom:0,left:0},l={top:0,right:0,bottom:0,left:0},c=!1){return new n.Camera({center:n.Mercator.fromGeo(s),zoom:e,rotation:n.degToRad(t),size:i,pitch:n.degToRad(r),viewport:a,padding:l,cameraConfig:n.defaultCameraConfig,globeMode:c,styleState:{}}).unproject(o)}function rf(s,e,t,i,r,o,a={top:0,right:0,bottom:0,left:0},l={top:0,right:0,bottom:0,left:0},c){return n.getMetersFromPixelsXY(s,e,t,i,r,o,a,l,c,c)}function sf(s,e){return new n.Camera(s).project(n.Mercator.toGeo(e))}const of=Object.freeze(Object.defineProperty({__proto__:null,geoLineDistance:n.geoLineDistance,geoToMapDistance:n.geoToMapDistance,getCenterZoomByPoints:Js,getMetersFromPixels:rf,getMousePositionInContainer:ze,projectGeoToMap:vn,projectGeoToScreen:tf,projectMapToGeo:ef,projectMapToScreen:sf,projectScreenToGeo:nf},Symbol.toStringTag,{value:"Module"})),af=Object.freeze(Object.defineProperty({__proto__:null,getMetersFromPixelsXY:n.getMetersFromPixelsXY,getUrl:n.getUrl,hashToString:n.hashToString},Symbol.toStringTag,{value:"Module"}));var ut=(s=>(s.NonCritical="non-critical",s.Critical="critical",s))(ut||{}),wt=(s=>(s.Init="init",s.Input="input",s.MapState="mapState",s.Update="update",s.PreDraw="preDraw",s.Draw="draw",s.Cleanup="cleanup",s))(wt||{});const Ks=["init","input","mapState","update","preDraw","draw","cleanup"];function lf(s,e,t){for(const i of Ks){const r=s[i];for(const o of r){const a={entityId:o.name,update:()=>o.updater.update(e,t),criticality:o.criticality};t.scheduler.register(a,i)}}}class cf{constructor(){this.phases={init:[],input:[],mapState:[],update:[],preDraw:[],draw:[],cleanup:[]},this.entityState=new WeakMap,this.entityToPhases=new WeakMap,this.loggedKeys=new WeakMap,this.pendingCleanup=[]}register(e,t){var i;this.entityState.has(e)||(this.entityState.set(e,{state:"valid",criticality:(i=e.criticality)!=null?i:"non-critical"}),this.entityToPhases.set(e,[]),this.loggedKeys.set(e,new Set)),this.entityToPhases.get(e).push(t),this.phases[t].push(e)}unregister(e){this.entityToPhases.has(e)&&this.pendingCleanup.push(e)}getState(e){var t;return(t=this.entityState.get(e))==null?void 0:t.state}markInvalid(e,t,i){const r=this.entityState.get(e);if(!(r===void 0||r.state==="destroyed"||r.state==="invalid"))if(this.logOnce(e,t,i),r.criticality==="non-critical")r.state="invalid";else throw i instanceof Error?i:new Error(String(i))}markDestroyed(e){const t=this.entityState.get(e);t!==void 0&&(t.state="destroyed",this.unregister(e))}runFrame(){for(let e=0;e<Ks.length;e++)this.runPhase(Ks[e])}runPhase(e){const t=this.phases[e];for(let i=0;i<t.length;i++){const r=t[i],o=this.entityState.get(r);if(!(o===void 0||o.state!=="valid"))try{r.update()}catch(a){this.markInvalid(r,`throw in phase '${e}'`,a)}}this.performCleanup()}destroy(){this.phases={init:[],input:[],mapState:[],update:[],preDraw:[],draw:[],cleanup:[]},this.entityState=new WeakMap,this.entityToPhases=new WeakMap,this.loggedKeys=new WeakMap,this.pendingCleanup=[]}performCleanup(){for(const e of this.pendingCleanup){const t=this.entityToPhases.get(e);if(t!==void 0){for(const i of t){const r=this.phases[i],o=r.indexOf(e);o!==-1&&r.splice(o,1)}this.entityToPhases.delete(e),this.entityState.delete(e),this.loggedKeys.delete(e)}}this.pendingCleanup=[]}logOnce(e,t,i){const r=this.loggedKeys.get(e);r===void 0||r.has(t)||(r.add(t),console.warn(`[PipelineScheduler] entity marked invalid: ${t}`,e.entityId,i))}}class ht extends n.Evented{constructor(e,t,i){var r;super(),this.criticality=ut.NonCritical,this.visibleOnGlobe=!0,this.interactive=(r=t.interactive)!=null?r:!0,this.uniqId=String(n.uniqId()),this.parentObject=i,this.modules=e.modules,this.mapState=e.state,this.tileObjects=[],this.identifyIds=[],this.modules.scheduler.register(this,wt.Update)}get entityId(){return this}update(){this.mapState.needReplicasUpdate&&this.tileObjects.forEach(e=>{e.needSync=!0})}destroy(){const e=this.modules;this.tileObjects.forEach(t=>{t.clean(this.mapState),e.tileManager.removeObject(t)}),this.tileObjects=[],e.layers.removeLayer(this),e.scheduler.markDestroyed(this),e.renderer.addRerenderEvent()}getIdentifyData(){return this.identifyIds.map(e=>({dynamicObjectId:this.uniqId,metatileHash:-1,ids:e}))}getWorldTransform(){return{position:[0,0,0],rotation:[0,0,0]}}isInteractive(){return this.interactive}updateGlobeVisibility(e){if(this.mapState.globeMode){const t=this.modules.camera.ecef.canSee(e);return this.visibleOnGlobe&&!t?this.tileObjects.forEach(i=>this.modules.tileManager.removeObject(i)):!this.visibleOnGlobe&&t&&this.tileObjects.forEach(i=>this.modules.tileManager.addObject(i)),this.visibleOnGlobe=t,t}return this.visibleOnGlobe||(this.tileObjects.forEach(t=>this.modules.tileManager.addObject(t)),this.visibleOnGlobe=!0),!0}}function ye(s){return!!s.styleState.globeEnabled&&s.globeMode}const Ll=["disableDragging","enableTrackResize","loopWorld","disableHidingPois","enableTwoFingerDragging"];let eo=class{constructor(e,t,i){var r,o,a,l,c,d;this.options=t,this.type="zenith",this.id=n.sourceUuid(),this.identifyAsDefaultSource=(r=t.identifyAsDefaultSource)!=null?r:!0,this.identifyAsDefaultSource&&!t.promoteId&&(t.promoteId="id"),this.sourceOptions=t,this.modelsAppearStrategy=(o=t.modelsAppearStrategy)!=null?o:n.DEFAULT_MODELS_APPEAR_STRATEGY,this.state=e.state,this.modules=e.modules,this.sourceCore=new n.ZenithSourceCore(this.id,this.modules,this.options),this.tileLayer=new n.TileLayer((a=t.minZoom)!=null?a:n.tiles.maxUniverseZoom+1,(l=t.maxZoom)!=null?l:n.tiles.maxRegionalZoom,(c=t.minZoom)!=null?c:n.tiles.maxUniverseZoom+1,(d=t.maxDetailLevel)!=null?d:n.tiles.maxDetailLevel,this.modules,this.state,this.sourceCore,this.options),this.modules.tileManager.addTileLayer(this.tileLayer),this.modules.sourceStorage.addSource(this),this.mapglApiSource=i}getObjectAttributes(e,t){return this.sourceCore.getObjectAttributes(e,t)}getId(){return this.id}getOptions(){return this.sourceOptions}getAttributes(){return this.sourceCore.getAttributes()}getZoomDirection(){return this.tileLayer.getZoomDirection()}setAttributes(e){this.sourceCore.setAttributes(e),this.tileLayer.redraw()}getUrl(e,t){return n.getUrl(e,I({host:this.options.tileServer,tileSet:this.options.tileSet,protocol:this.options.tileProtocol,subdomain:this.options.subdomains[0]},t))}destroy(){this.modules.tileManager.removeTileLayer(this.tileLayer),this.tileLayer.destroy(),this.modules.sourceStorage.removeSource(this.id),this.sourceCore.destroy()}setFeatureStateMap(e){this.sourceCore.setFeatureStateMap(e),this.tileLayer.onFeatureStateMapChange()}isIdentifiedAsDefault(){return this.identifyAsDefaultSource}};const Ii=[0,0,0];function Rl(s,e){if(e===void 0)return;if(e.sourceId){const i=s.getSourceById(e.sourceId);if(!(i!=null&&i.isIdentifiedAsDefault()))return}const t={id:e.id,symbol:e.symbol};return e.symbol==="point"&&(t.isText=e.instanceId===1),e.sublayer&&(t.isCityCommercial=n.isCommercialCityPoi(e.sublayer),t.isPremiumCommercial=n.isCommercialPremiumPoi(e.sublayer),t.isCommercial=n.isCommercialPoi(e.sublayer),t.isPersonal=n.isPersonalPoi(e.sublayer),(e.symbol==="point"&&!t.isCommercial||e.symbol==="gltfModel")&&(t.sysCode=e.objectClass)),e.center&&(t.center=n.Mercator.toGeo(e.center)),e.symbol==="gltfModel"&&(t.sublayer=e.sublayer,t.isCommercial=!!e.sublayer&&n.isCommercialModel(e.sublayer)),t}function df(s,e){var i;if(e===void 0)return;if(e.sourceId){const r=s.getSourceById(e.sourceId);if(r)switch(r.type){case"geojson":{if(r.subtype==="internal"&&r instanceof n.GeoJsonSource||r.subtype==="viewport-internal"&&r instanceof n.GeoJsonViewportSource)return{type:"geojson",id:e.id,feature:r.getFeatureById(e.id,e.tileKey),source:r};if(r.subtype==="external"&&r instanceof n.GeoJsonTileSource)return{type:"geojsonTile",getFeatureProperties:()=>e.tileKey===void 0?Promise.resolve():r.getObjectAttributes(e.id,e.tileKey),source:r}}case"zenith":if(r instanceof eo)return{type:"zenith",id:e.id,source:r,attributes:r.getObjectAttributes((i=e.tileKey)!=null?i:"",e.id)}}}const t={type:"default",id:e.id};return e.floorId&&(t.floorId=e.floorId),t}function Nt(s,e,t,i,r){const o=r.camera,a=[0,0];if(o.unproject(i,a,!0),r.floorManager.visibleComplexIsMetro&&(e!=null&&e.floorId)&&s==="click"&&uf(a,i,e.floorId,r),s==="click"&&(e!=null&&e.sourceId)&&e.id&&r.uiPoiSource.getSourceId()!==null&&r.uiPoiSource.getSourceId()===e.sourceId){r.uiPoiSource.handleClick(e.id);return}if(e&&e.dynamicObjectId!==void 0){const f=s;let m=r.layers.getDynamicObjectLayers().find(g=>g.uniqId===e.dynamicObjectId);if(m!=null&&m.parentObject&&(m=m==null?void 0:m.parentObject),!m)return;const v={lngLat:a,originalEvent:t,point:i,targetData:m};m.emit(f,v);return}const l=Rl(r.sourceStorage,e),c=df(r.sourceStorage,e);if((s==="mousedown"||s==="click"||s==="touchstart"||s==="mouseover")&&e!==void 0&&(l==null?void 0:l.symbol)==="point"&&c!==void 0){const f=n.getPoiIconData(r,e,l)||{};f!==void 0&&(c.poiIcon=f)}if((s==="mousedown"||s==="click"||s==="touchstart")&&(e!=null&&e.floorId)&&(c==null?void 0:c.type)==="default"&&r.floorManager.isApartmentFloor(e.floorId)&&(c.isApartmentFloor=!0),e){const f=r.styleManager.getStyleLayer(e.styleId,e.layerId);f&&c&&(c.layerId=f.id)}const h={lngLat:a,originalEvent:t,point:i,target:l,targetData:c},_=s;r.map.emit(_,h)}function uf(s,e,t,i){const r=i.floorManager.getFloorObjectElevation(t),o=[0,0,0];i.camera.flat.unproject(e,o);const a=i.camera.position;o.forEach((c,d)=>Ii[d]=c-a[d]),n.normalize(Ii,Ii);const l=r;if(Math.abs(Ii[2])>=1e-4){const c=(l-a[2])/Ii[2],d=[a[0]+Ii[0]*c,a[1]+Ii[1]*c,l];n.Mercator.toGeo(d,s)}}class Fl extends ht{constructor(e,t,i){super(e,t),this.start=r=>{const{modules:o,container:a}=this,{camera:l}=o;if(r.button!==0)return;const c=ze(a,r.clientX,r.clientY);this.contains(c)&&(o.handler.block(),o.mouseMoveHandler.block(),this.dragStartCursorPoint=c,this.dragStartAnchorPoint=l.project(n.Mercator.toGeo(this.getPosition())),document.addEventListener("mouseup",this.stop),document.addEventListener("mousemove",this.move),this.emitEvent("dragstart",r))},this.move=r=>{const{camera:o}=this.modules,{dragStartAnchorPoint:a,dragStartCursorPoint:l,container:c}=this;if(a===void 0||l===void 0)return;const d=ze(c,r.clientX,r.clientY),u=n.clone(a);n.add(u,u,d),n.sub(u,u,l),this.setPosition(n.Mercator.fromGeo(o.unproject(u))),this.emitEvent("drag",r)},this.stop=r=>{if(r.button!==0)return;this.dragStartCursorPoint=void 0,this.dragStartAnchorPoint=void 0,document.removeEventListener("mouseup",this.stop),document.removeEventListener("mousemove",this.move);const{modules:o}=this;o.handler.unblock(),o.mouseMoveHandler.unblock(),this.emitEvent("dragend",r),this.interactive&&o.identifier.resetCache()},this.container=e.modules.layout.mapContainer,i&&this.container.addEventListener("mousedown",this.start,!0)}destroy(){super.destroy(),this.container.removeEventListener("mousedown",this.start,!0),document.removeEventListener("mouseup",this.stop),document.removeEventListener("mousemove",this.move)}emitEvent(e,t){const i=this.getPosition(),r=n.Mercator.toGeo(i),o=this.modules.camera.flat.project(i),a=this.modules.identifier.searchSync(o),l=a!==void 0&&a.dynamicObjectId===void 0?Rl(this.modules.sourceStorage,a):void 0;this.emit(e,{originalEvent:t,target:l,targetData:this,lngLat:r,point:o})}}const hf=!1;let Dl=class extends Fl{constructor(e,t){var a;super(e,t,(a=t.draggable)!=null?a:hf),this.generatedAsEcef=!1,this.options=t;const i=n.Mercator.fromGeo(this.options.coordinates);this.position={userValue:i,normalizedValue:n.normalizeMapPoint(i)};const{dynamicStyle:r,layers:o}=this.modules;this.layer=n.makeHandyStyleLayer({type:"circle",id:`dynamic-circleMarker-${this.uniqId}`,minzoom:this.options.minZoom,maxzoom:this.options.maxZoom,style:{color:this.options.color,strokeColor:this.options.borderColor,strokeColor2:this.options.border2Color,width:this.options.width,strokeWidth:this.options.borderWidth,strokeWidth2:this.options.border2Width}},r.getStyle().globals),this.layer&&(r.addLayer(this.layer,this.options.zIndex),this.generate(),o.addLayer(this))}remove(){this.layer&&this.modules.dynamicStyle.removeLayer(this.layer.innerId),this.interactive&&this.modules.identifier.resetCache(),super.destroy()}update(){super.update();const e=ye(this.mapState);e!==this.generatedAsEcef&&(this.regenerate(),this.generatedAsEcef=e),this.updateGlobeVisibility(this.options.coordinates)}isOutOfMainReplica(){return!1}setPosition(e){const t=this.tileObjects[0];t!==void 0&&(this.position={userValue:e,normalizedValue:n.normalizeMapPoint(e)},t.setTileCoords(n.mapPointTo32ZoomTileCoords(this.position.normalizedValue),this.mapState),this.modules.renderer.addRerenderEvent())}getPosition(){return this.position.userValue}contains(e){if(!this.layer)return!1;const{layer:t}=this,{camera:i}=this.modules,r=i.project(n.Mercator.toGeo(this.position.normalizedValue)),o=n.resolveNumber(t.style.width,n.makeBinderContext(this.mapState.styleZoom,this.mapState.pitch,this.mapState.styleState,[])),a=n.resolveNumber(t.style.strokeWidth,n.makeBinderContext(this.mapState.styleZoom,this.mapState.pitch,this.mapState.styleState,[])),l=o/2+a;return n.dist(r,e)<=l}generate(){var v;if(!this.layer)return;const{dynamicStyle:e,collector:t,tileManager:i,identifier:r}=this.modules,a=(v=this.position.userValue[2])!=null?v:0,l=n.mapPointTo32ZoomTileCoords(this.position.normalizedValue),c=n.optionsToTileAttrs({}),d={x:[0],y:[0],z:[a]},u=n.createTileInfo(l),h=ye(this.mapState),_=n.makeGeneratorContext(this.mapState.styleState,n.emptySourceAttrs,n.fixedTileProps,c,n.emptyFeatureAttrs,!0,this.interactive?"0":"",h?u:void 0);n.runPrecomputes(this.layer,_),n.generateSafely({collector:t,generator:n.CircleMarkerGenerator.generate,args:[e.getStyle().id,this.layer,_,d]});const f=t.getAccumulatedData(),m=new n.TileObject("dynamicObject",f.data,this.modules,this.mapState,l);m.ecefDataState=n.ecefDataStateFromBool(h),i.addObject(m),this.tileObjects.push(m),this.interactive&&this.identifyIds.push(f.identifyIds),t.reset(),this.modules.renderer.addRerenderEvent(),this.interactive&&r.resetCache()}regenerate(){const{tileManager:e}=this.modules;for(const t of this.tileObjects)t.clean(this.mapState),e.removeObject(t);this.tileObjects=[],this.identifyIds=[],this.generate()}};function zl(s,e,t){const{top:i,right:r,bottom:o,left:a}=s.viewport,{clientWidth:l,clientHeight:c}=e;s.size=[Math.max(1,l-a-r),Math.max(1,c-i-o)],t.updateFrameBuffersSize()}const Bl=(s,e,t,i,r={})=>{const o=I({top:0,right:0,bottom:0,left:0},i);if(r.animate===!1||r.duration===0)s.viewport=o,zl(s,e,t);else{const a=s.viewport,l=r.easing!==void 0?r.easing:"easeOutCubic",c=r.duration!==void 0?r.duration:300;n.start("viewport",{easing:l},s,[a.top,a.right,a.bottom,a.left],[o.top,o.right,o.bottom,o.left],c,1)}},_f=Object.freeze(Object.defineProperty({__proto__:null,set:Bl,update:(s,e)=>{n.update("viewport",{step:(t,i)=>{t.viewport={top:i[0],right:i[1],bottom:i[2],left:i[3]},zl(t,e.layout.rootContainer,e.renderer)}},s)}},Symbol.toStringTag,{value:"Module"}));function ff(s,e){return{top:s.top+e.top,bottom:s.bottom+e.bottom,left:s.left+e.left,right:s.right+e.right}}function mf(s){return{top:Math.max(s.top,0),bottom:Math.max(s.bottom,0),left:Math.max(s.left,0),right:Math.max(s.right,0)}}function vf(s,e){return{top:Math.min(s.top,e[1]),bottom:Math.min(s.bottom,e[1]),left:Math.min(s.left,e[0]),right:Math.min(s.right,e[0])}}function gf(s,e){return vf(mf(s),e)}function Ol(s,e){const{top:t,right:i,bottom:r,left:o}=s.padding;s.padding={top:t,right:i,bottom:r,left:o},e.addRerenderEvent(),e.updateFrameBuffersSize()}const wl=(s,e,t,i={})=>{const r=gf(t,s.size);if(i.animate===!1||i.duration===0)s.padding=r,Ol(s,e);else{const o=s.padding,a=i.easing!==void 0?i.easing:"easeOutCubic",l=i.duration!==void 0?i.duration:300;n.start("padding",{easing:a},s,[o.top,o.right,o.bottom,o.left],[r.top,r.right,r.bottom,r.left],l,1)}},pf=Object.freeze(Object.defineProperty({__proto__:null,set:wl,update:(s,e)=>{n.update("padding",{step:(t,i)=>{t.padding={top:i[0],right:i[1],bottom:i[2],left:i[3]},Ol(t,e.renderer)}},s)}},Symbol.toStringTag,{value:"Module"})),er="inertia",xf=(s,e,t)=>s*Math.pow(1-(t-e)/n.inertia.duration,n.inertia.nonLinearity),Nl=(s,e,t,i,r)=>{n.start(er,{easing:"inertia"},s,0,r,n.inertia.duration,1,{startPoint:e,startSpeed:t,direction:i,startTime:s.time})},tr=n.stop.bind(null,er),bf=(s,e)=>{n.update(er,{step:(t,i,r)=>{const{startPoint:o,startSpeed:a,startTime:l,direction:c}=r,d=n.clone$1(c);n.scale(d,d,i),n.add$1(d,d,o),t.loopWorld||t.styleState.globeEnabled?n.isLatValid(t.maxBounds,d)||(to(e.layout.rootContainer,t),n.clampLat(d,t.maxBounds,d)):n.contains(t.maxBounds,d)||(to(e.layout.rootContainer,t),n.clampPoint(d,t.maxBounds,d)),t.center=d,t.zoomTypePreserving==="zoom"?t.styleZoom=n.getStyleZoom(t.zoom,d):t.zoom=n.getZoomFromStyleZoom(t.styleZoom,d);const u=xf(a,l,t.time);n.mapToPixelDistance(u,t.zoom)<n.inertia.minSpeed&&to(e.layout.rootContainer,t)}},s)},to=(s,e)=>{n.stop(er,e),s.classList.remove("mapgl-inertia")},Sf=Object.freeze(Object.defineProperty({__proto__:null,set:Nl,stop:tr,update:bf},Symbol.toStringTag,{value:"Module"})),ir="center",hi=(s,e,t={})=>{if(n.stop(ir,s),tr(s),s.styleState.globeEnabled?n.clampLat(e,s.maxBounds,e):n.clampPoint(e,s.maxBounds,e),t.animate===!1||t.duration===0)s.center=e,s.zoomTypePreserving==="zoom"?s.styleZoom=n.getStyleZoom(s.zoom,e):s.zoom=n.getZoomFromStyleZoom(s.styleZoom,e);else{const i=t.easing!==void 0?t.easing:"linear",r=t.duration!==void 0?t.duration:250;n.start(ir,{easing:i},s,s.center,e,r,1)}},kl=n.stop.bind(null,ir),yf=n.update.bind(null,ir,{step:(s,e)=>{s.center=e,s.zoomTypePreserving==="zoom"?s.styleZoom=n.getStyleZoom(s.zoom,e):s.zoom=n.getZoomFromStyleZoom(s.styleZoom,e)}}),Tf=Object.freeze(Object.defineProperty({__proto__:null,set:hi,stop:kl,update:yf},Symbol.toStringTag,{value:"Module"})),nr="rotation";function io(s,e){return s=s-e,s>=Math.PI?s=(s+Math.PI)%(Math.PI*2)-Math.PI:s<-Math.PI&&(s=Math.PI-(Math.PI-s)%(Math.PI*2)),s=s+e,s}function Xi(s,e,t={}){if(n.stop(nr,s),t.animate===!1||t.duration===0)s.rotation=io(e,0);else{const i=t.normalize!==void 0?t.normalize:!0;n.start(nr,{easing:t.easing||"linear"},s,s.rotation,i?io(e,s.rotation):e,t.duration||250,1)}}const Ul=n.stop.bind(null,nr),Ef=n.update.bind(null,nr,{step:(s,e)=>s.rotation=io(e,0)}),Cf=Object.freeze(Object.defineProperty({__proto__:null,set:Xi,stop:Ul,update:Ef},Symbol.toStringTag,{value:"Module"})),rr="pitch";function gn(s,e,t={}){n.stop(rr,s);const i=n.clamp(e,s.minPitch,s.maxPitch);t.animate===!1||t.duration===0?s.pitch=i:n.start(rr,{easing:t.easing||"linear"},s,s.pitch,i,t.duration||300,1)}const Ml=n.stop.bind(null,rr),If=n.update.bind(null,rr,{step:(s,e)=>s.pitch=e}),Pf=Object.freeze(Object.defineProperty({__proto__:null,set:gn,stop:Ml,update:If},Symbol.toStringTag,{value:"Module"}));function Hl(s){s.styleState.globeEnabled?n.clampLat(s.center,s.maxBounds,s.center):n.clampPoint(s.center,s.maxBounds,s.center)}const sr="zoom",Qt=(s,e,t={})=>{n.stop(sr,s);const i=n.clamp(e,s.minZoom,s.maxZoom);if(i!==s.zoom)if(t.animate===!1||t.duration===0)t.zoomPoint&&(n.add$1(s.center,s.center,n.getCenterCorrection(s,t.zoomPoint,{zoom:i})),Hl(s)),s.zoom=i,s.styleZoom=n.getStyleZoom(i,s.center);else{const r=t.useHeightForAnimation?n.zoomToHeight(s.zoom,s.size):s.zoom,o=t.useHeightForAnimation?n.zoomToHeight(i,s.size):i,a=t.easing!==void 0?t.easing:"easeOutCubic",l=t.duration!==void 0?t.duration:250;n.start(sr,{easing:a},s,r,o,l,1,{zoomPoint:t.zoomPoint,useHeightForAnimation:!!t.useHeightForAnimation})}},no=n.stop.bind(null,sr),Af=n.update.bind(null,sr,{step:(s,e,t={})=>{const i=t&&t.useHeightForAnimation?n.heightToZoom(e,s.size):e;t&&t.zoomPoint&&(n.add$1(s.center,s.center,n.getCenterCorrection(s,t.zoomPoint,{zoom:i})),Hl(s)),s.zoom=i,s.styleZoom=n.getStyleZoom(i,s.center)}}),Lf=Object.freeze(Object.defineProperty({__proto__:null,set:Qt,stop:no,update:Af},Symbol.toStringTag,{value:"Module"})),Rf=navigator.msPointerEnabled&&navigator.msMaxTouchPoints&&!window.PointerEvent,Ff=window.PointerEvent&&navigator.pointerEnabled&&navigator.maxTouchPoints||Rf||"ontouchstart"in window||window.DocumentTouch&&document instanceof window.DocumentTouch,Df=Pi("webkit"),zf=Pi("chrome")||Pi("crios"),Bf="ActiveXObject"in window,Of=!zf&&Pi("safari");Pi("gecko")&&!Df&&window.opera;const or=navigator.platform.toUpperCase().indexOf("MAC")>=0,wf=Pi("windows"),Nf=Pi("firefox");function Pi(s){return navigator.userAgent.toLowerCase().indexOf(s)>=0}function Jt(s){no(s),kl(s),Ul(s),Ml(s),tr(s)}class kf{constructor(e,t){this.onWheelScroll=i=>{this.isBlocked||(i.preventDefault(),!(i.deltaMode===void 0&&i.deltaY===void 0)&&(this.state.userHasInteracted=!0,this.screenPoint=ze(this.container,i.clientX,i.clientY),i.ctrlKey?this.deltaAccumulator-=i.deltaY*10:i.deltaMode===1?this.deltaAccumulator-=i.deltaY*20:this.deltaAccumulator-=i.deltaY,this.eventCount+=1))},this.startZooming=()=>{const i=this.state;let r=this.getDelta();or?r*=n.zoom.macWheelDeltaToZoomDelta:Number.isInteger(r)?r=n.sign(r)*n.zoom.wheelZoomDelta:r*=n.zoom.notMacTrackpadDeltaToZoomDelta;const o=i.zoom+r,a=n.clamp(o,i.minZoom,i.maxZoom);a!==i.zoom&&(Jt(i),Qt(i,a,{duration:n.zoom.animDuration,animate:!or,zoomPoint:i.keepCenterWhileUserZoomRotate?void 0:this.screenPoint}))},this.stop=()=>{this.state.userHasInteracted=!0,no(this.state)},this.state=e,this.container=t,or||(this.startZooming=n.throttle(this.startZooming,n.zoom.throttleDelay)),this.deltaAccumulator=0,this.eventCount=0,this.screenPoint=[0,0],this.isBlocked=!1,this.container.addEventListener("wheel",this.onWheelScroll),this.container.addEventListener("mousedown",this.stop)}destroy(){this.container.removeEventListener("wheel",this.onWheelScroll),this.container.removeEventListener("mousedown",this.stop)}update(){this.eventCount!==0&&(this.startZooming(),this.state.rerenderEvents.push({type:"coreNeedRerender"}))}block(){this.isBlocked=!0}unblock(){this.isBlocked=!1}getDelta(){const e=this.deltaAccumulator/this.eventCount;return this.deltaAccumulator=0,this.eventCount=0,e}}class Uf{constructor(e,t){this.onMouseUp=i=>{this.isBlocked||i.which===1&&this.start()},this.onTouchEnd=i=>{this.isBlocked||i.touches.length===0&&this.start()},this.start=()=>{const i=this.state;i.userHasInteracted=!0;const r=this.getCurrentSpeed(i.time),o=n.length(r);if(n.mapToPixelDistance(o,i.zoom)<=n.inertia.minSpeed)return;const l=n.pixelToMapDistance(n.inertia.maxSpeed,i.zoom),c=Math.min(o,l),d=this.calcDistanceByStartSpeed(c),u=n.clone$1(i.center),h=n.create$1();n.normalize(h,r),Nl(i,u,c,h,d),this.container.classList.add("mapgl-inertia")},this.stop=()=>{tr(this.state),this.container.classList.remove("mapgl-inertia"),this.times=[],this.positions=[]},this.state=e,this.container=t,this.isBlocked=!1,this.container.addEventListener("mouseup",this.onMouseUp),this.container.addEventListener("mousedown",this.stop),Ff&&(this.container.addEventListener("touchend",this.onTouchEnd),this.container.addEventListener("touchstart",this.stop)),this.zoomDiffer=new n.Differ([{path:"zoom",type:"number"}]),this.styleZoomDiffer=new n.Differ([{path:"styleZoom",type:"number"}]),this.centerDiffer=new n.Differ([{path:"center",type:"vec2"}]),this.times=[],this.positions=[]}destroy(){this.container.removeEventListener("mouseup",this.onMouseUp),this.container.removeEventListener("mousedown",this.stop),this.container.removeEventListener("touchend",this.onTouchEnd),this.container.removeEventListener("touchstart",this.stop)}update(){const e=this.state;this.centerDiffer.check(e)&&this.rememberTimeAndPosition(e),(e.zoomTypePreserving==="zoom"?this.zoomDiffer.check(e):this.styleZoomDiffer.check(e))&&this.stop()}block(){this.isBlocked=!0}unblock(){this.isBlocked=!1}removeOldRecords(e){for(;e-this.times[0]>100&&this.times.length;)this.times.shift(),this.positions.shift()}rememberTimeAndPosition(e){const t=e.time;this.removeOldRecords(t),this.times.push(t),this.positions.push(n.clone$1(e.center))}getCurrentSpeed(e){if(this.removeOldRecords(e),this.times.length<2)return n.create$1();const t=n.clone$1(this.positions[this.positions.length-1]);return n.sub$1(t,t,this.positions[0]),n.scale(t,t,1/(this.times[this.times.length-1]-this.times[0])),t}calcDistanceByStartSpeed(e){return e*n.inertia.duration/(n.inertia.nonLinearity+1)}}class Mf{constructor(e){this.emitMouseEvent=t=>{if(this.isBlocked)return;const i=ze(this.container,t.clientX,t.clientY);this.emitEvent(t,i)},this.emitTouchEvent=t=>{if(this.isBlocked)return;const i=ze(this.container,t.changedTouches[0].clientX,t.changedTouches[0].clientY);this.emitEvent(t,i)},this.container=e.layout.mapContainer,this.modules=e,this.isBlocked=!1,this.container.addEventListener("mouseup",this.emitMouseEvent),this.container.addEventListener("touchend",this.emitTouchEvent)}destroy(){this.container.removeEventListener("mouseup",this.emitMouseEvent),this.container.removeEventListener("touchend",this.emitTouchEvent)}update(){}block(){this.isBlocked=!0}unblock(){this.isBlocked=!1}emitEvent(e,t){if(!this.modules.layout.isActionWithCanvas(e))return;const i=e.type;this.modules.identifier.search(i,t).then(r=>{Nt(i,r,e,t,this.modules)})}}class Hf{constructor(e,t,i){this.rotationDetected=!1,this.onGestureStart=r=>{this.isBlocked||(r.preventDefault(),this.startRotation=this.state.rotation,this.rotationDetected=!1,this.gestureRotation=0,this.isGestureStart=!0,this.startZoom=this.state.zoom,this.screenPoint=ze(this.container,r.clientX,r.clientY),this.state.userHasInteracted=!0,this.state.disableRotationByUserInteraction||this.container.classList.add("mapgl-rotating"),this.map.emit("interactionstart",{target:"zoom/rotation"}))},this.onGestureEnd=r=>{r.preventDefault(),this.isGestureStart&&(this.isGestureStart=!1,this.state.userHasInteracted=!0,this.container.classList.remove("mapgl-rotating"),this.map.emit("interactionend",{target:"zoom/rotation"}))},this.onGestureChange=r=>{if(r.preventDefault(),this.state.userHasInteracted=!0,r.scale>1?this.gestureZoom=r.scale-1:this.gestureZoom=-1/r.scale+1,this.state.disableRotationByUserInteraction)return;const o=n.degToRad(r.rotation);!this.rotationDetected&&Math.abs(o)>this.state.touchRotationThreshold&&(this.rotationDetected=!0,this.startRotation=this.state.rotation-o),this.rotationDetected&&(this.gestureRotation=o)},this.state=e,this.container=t,this.map=i,this.isBlocked=!1,this.isGestureStart=!1,this.gestureRotation=0,this.gestureZoom=0,this.screenPoint=[0,0],this.startRotation=0,this.startZoom=0,this.container.addEventListener("gesturestart",this.onGestureStart),this.container.addEventListener("gestureend",this.onGestureEnd),this.container.addEventListener("gesturechange",this.onGestureChange)}destroy(){this.container.removeEventListener("gesturestart",this.onGestureStart),this.container.removeEventListener("gestureend",this.onGestureEnd),this.container.removeEventListener("gesturechange",this.onGestureChange)}update(){if(this.gestureRotation===0&&this.gestureZoom===0)return;const e=this.state,t=this.startZoom+this.gestureZoom,i=this.startRotation+this.gestureRotation,r=n.create$1(),o=e.keepCenterWhileUserZoomRotate?n.create$1():n.getCenterCorrection(e,this.screenPoint,{zoom:t,rotation:i});n.add$1(r,e.center,o),Jt(e),hi(e,r,{animate:!1}),Qt(e,t,{animate:!1}),e.disableRotationByUserInteraction||Xi(e,i,{animate:!1}),this.gestureRotation=0,this.gestureZoom=0}block(){this.isBlocked=!0}unblock(){this.isBlocked=!1}}class Gf{constructor(e){this.onTouchStart=()=>{this.isTouchStartEmitted=!0},this.onMouseOut=t=>{if(!this.prevGeo)return;const i=ze(this.container,t.clientX,t.clientY);Nt("mouseout",this.prevGeo,t,i,this.modules),this.prevGeo=void 0,this.skipIdentifyEvents=!0,this.modules.defaultSource.resetHoverId(),this.container.classList.remove("mapgl-hover")},this.onMouseMove=t=>{if(this.isTouchStartEmitted){this.isTouchStartEmitted=!1;return}if(this.skipIdentifyEvents=!1,this.isBlocked)return;const i=ze(this.container,t.clientX,t.clientY);Promise.resolve().then(()=>this.modules.layout.isActionWithCanvas(t)?this.modules.identifier.search("mouseMove",i):void 0).then(r=>{if(this.skipIdentifyEvents)return;const o=r&&this.prevGeo&&(r.id!==this.prevGeo.id||r.instanceId!==this.prevGeo.instanceId||r.dynamicObjectId!==this.prevGeo.dynamicObjectId||r.symbol!==this.prevGeo.symbol);this.prevGeo&&(!r||o)&&(Nt("mouseout",this.prevGeo,t,i,this.modules),this.prevGeo=void 0,this.container.classList.remove("mapgl-hover"),this.modules.defaultSource.resetHoverId()),r&&(!this.prevGeo||o)&&(this.prevGeo=r,this.container.classList.add("mapgl-hover"),Nt("mouseover",r,t,i,this.modules),this.modules.defaultSource.setHoverId(r.id)),Nt("mousemove",r,t,i,this.modules)})},this.modules=e,this.isTouchStartEmitted=!1,this.skipIdentifyEvents=!1,this.isBlocked=!1,this.prevGeo=void 0,this.container=this.modules.layout.mapContainer,this.container.addEventListener("touchstart",this.onTouchStart),this.container.addEventListener("mousemove",this.onMouseMove),this.container.addEventListener("mouseout",this.onMouseOut)}destroy(){this.container.removeEventListener("touchstart",this.onTouchStart),this.container.removeEventListener("mousemove",this.onMouseMove),this.container.removeEventListener("mouseout",this.onMouseOut)}update(){}block(){this.isBlocked=!0}unblock(){this.isBlocked=!1}}const Gl=(s,e,t,i)=>{n.stop("buildingHeight"+i,s),t.animate===!1||t.duration===0?(e.set(i,t.to),s.needLabeling=!0):n.start("buildingHeight"+i,{easing:t.easing},s,t.from,t.to,t.duration,1)},Vf=(s,e,t)=>n.update.call(null,"buildingHeight"+t,{step:(i,r)=>e.set(t,r),complete:i=>i.needLabeling=!0},s),Zf=16;class Wf{constructor(e,t){this.state=e,this.modules=t,this.buildingHeights=new Map,this.minZoomBuildingHeight=1/0}getBuildingHeight(e){return e===-1/0?1:e!==void 0?(this.buildingHeights.has(e)||this.addBuildingHeightZoom(e),this.buildingHeights.get(e)||0):this.getDefaultBuildingHeight()}update(){this.buildingHeights.forEach((e,t)=>{this.updateByZoom(t,e),this.isAnimating()&&Vf(this.state,this.buildingHeights,t)})}isAnimating(){return Array.from(this.buildingHeights.keys()).some(e=>n.get("buildingHeight"+e,this.state)!==void 0)}clearBuildingHeights(){this.buildingHeights.clear(),this.minZoomBuildingHeight=1/0}getDefaultBuildingHeight(){const e=this.minZoomBuildingHeight!==1/0?this.minZoomBuildingHeight:Zf;return this.state.styleZoom<e?0:1}updateByZoom(e,t){const i=this.state,r=n.get("buildingHeight"+e,i),o=r!==void 0?r.to:t;i.styleZoom>=e&&this.modules.tileManager.viewportTilesReady()&&o!==1?Gl(i,this.buildingHeights,{animate:!0,easing:n.buildingAnimation.easing,from:t,to:1,duration:n.buildingAnimation.duration*(1-t)},e):i.styleZoom<e&&o!==0&&Gl(i,this.buildingHeights,{animate:!1,to:0},e)}addBuildingHeightZoom(e){const t=e<this.state.styleZoom?0:1;this.buildingHeights.set(e,t),this.minZoomBuildingHeight>e&&(this.minZoomBuildingHeight=e)}}const j=class j{constructor(e=null,t={}){this._src=null,this._glContext=null,this._texture=null,this._src=e,this.options=Object.assign({},j.defaultOptions,t)}enable(e,t){return e.activeTexture(e.TEXTURE0+t),this._texture||this.prepare(e),e.bindTexture(e.TEXTURE_2D,this._texture),this}remove(){return this._texture&&this._glContext&&this._glContext.deleteTexture(this._texture),this._glContext=null,this._texture=null,this._src=null,this}getTexture(){return this._texture}getSource(){return this._src}subImage(e,t,i){var l;const r=this._glContext;if(!r)return console.warn("Texture is not prepared, cannot update sub-image"),this;r.bindTexture(r.TEXTURE_2D,this._texture),r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,this.options.flipY),r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.options.premultiplyAlpha);const o=this._toGlParam(r,this.options.format),a=this._toGlParam(r,(l=this.options.type)!=null?l:j.UnsignedByte);return o===null||a===null?this:(r.texSubImage2D(r.TEXTURE_2D,0,t,i,o,a,e),this.options.generateMipmaps&&this.options.minFilter!==j.NearestFilter&&this.options.minFilter!==j.LinearFilter&&(console.warn("[WebGL] Generating mipmaps for texture after subImage update"),r.generateMipmap(r.TEXTURE_2D)),this)}prepare(e){var d,u,h;this._glContext=e,this._texture=e.createTexture(),e.bindTexture(e.TEXTURE_2D,this._texture),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,this.options.flipY),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.options.premultiplyAlpha);const t=this._toGlParam(e,this.options.format),i=this._toGlParam(e,(d=this.options.type)!=null?d:j.UnsignedByte),r=this._toGlParam(e,this.options.wrapS),o=this._toGlParam(e,this.options.wrapT),a=this._toGlParam(e,(u=this.options.magFilter)!=null?u:j.LinearFilter),l=this._toGlParam(e,(h=this.options.minFilter)!=null?h:j.LinearMipMapLinearFilter),c=this.options.compareFunc?this._toGlParam(e,this.options.compareFunc):null;if(t!==null&&i!==null){const _=this.hookInternalFormat(t,i,e);ArrayBuffer.isView(this._src)||this._src===null?this.options.size&&e.texImage2D(e.TEXTURE_2D,0,_,this.options.size[0],this.options.size[1],0,t,i,this._src):this._src&&e.texImage2D(e.TEXTURE_2D,0,t,t,i,this._src)}return r!==null&&o!==null&&(e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,r),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,o)),a!==null&&l!==null&&(e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,a),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,l)),c&&!(e instanceof WebGLRenderingContext)&&e.texParameteri(e.TEXTURE_2D,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE),this.options.generateMipmaps&&this.options.minFilter!==j.NearestFilter&&this.options.minFilter!==j.LinearFilter&&e.generateMipmap(e.TEXTURE_2D),e.bindTexture(e.TEXTURE_2D,null),this}memSizeJs(){const e=this._src;return e===null?0:ArrayBuffer.isView(e)?e.byteLength:e instanceof ImageBitmap?e.height*e.width*4:(console.warn("[Stats] Untracked texture _src size"),0)}memSizeGPU(){var t,i,r,o;if(!this._texture)return 0;const e=((i=(t=this.options.size)==null?void 0:t[0])!=null?i:0)*((o=(r=this.options.size)==null?void 0:r[1])!=null?o:0)*4;return e>0?e:this._src!==null?this.memSizeJs():0}_toGlParam(e,t){return t===j.ClampToEdgeWrapping?e.CLAMP_TO_EDGE:t===j.Repeat?e.REPEAT:t===j.MirroredRepeat?e.MIRRORED_REPEAT:t===j.NearestFilter?e.NEAREST:t===j.NearestMipMapNearestFilter?e.NEAREST_MIPMAP_NEAREST:t===j.NearestMipMapLinearFilter?e.NEAREST_MIPMAP_LINEAR:t===j.LinearFilter?e.LINEAR:t===j.LinearMipMapNearestFilter?e.LINEAR_MIPMAP_NEAREST:t===j.LinearMipMapLinearFilter?e.LINEAR_MIPMAP_LINEAR:t===j.RgbaFormat?e.RGBA:t===j.AlphaFormat?e.ALPHA:t===j.RgbFormat?e.RGB:t===j.DepthComponentFormat?e.DEPTH_COMPONENT:t===j.UnsignedByte?e.UNSIGNED_BYTE:t===j.UnsignedShort?e.UNSIGNED_SHORT:t===j.Float?e.FLOAT:t===j.UnsignedInt?e.UNSIGNED_INT:e instanceof WebGLRenderingContext?null:t===j.RedFormat?e.RED:t===j.CompareRefToTexture?e.COMPARE_REF_TO_TEXTURE:t===j.CompareNone?e.NONE:t===j.DepthComponentFormat32?e.DEPTH_COMPONENT32F:null}hookInternalFormat(e,t,i){return i instanceof WebGLRenderingContext?e:e===i.DEPTH_COMPONENT?i.DEPTH_COMPONENT24:t===i.FLOAT&&e===i.RGBA?i.RGBA32F:t===i.FLOAT&&e===i.RED?i.R32F:t!==i.FLOAT&&e===i.RED?i.R8:e}};j.ClampToEdgeWrapping=1,j.Repeat=2,j.MirroredRepeat=3,j.NearestFilter=4,j.NearestMipMapNearestFilter=5,j.NearestMipMapLinearFilter=6,j.LinearFilter=7,j.LinearMipMapNearestFilter=8,j.LinearMipMapLinearFilter=9,j.DepthComponentFormat=10,j.DepthComponentFormat32=11,j.RgbaFormat=14,j.AlphaFormat=15,j.RgbFormat=16,j.UnsignedByte=17,j.Float=18,j.UnsignedShort=19,j.UnsignedInt=20,j.RedFormat=21,j.CompareNone=22,j.CompareRefToTexture=23,j.defaultOptions={magFilter:j.LinearFilter,minFilter:j.LinearMipMapLinearFilter,wrapS:j.ClampToEdgeWrapping,wrapT:j.ClampToEdgeWrapping,format:j.RgbaFormat,generateMipmaps:!0,flipY:!0,premultiplyAlpha:!0,type:j.UnsignedByte};let C=j;function ar(s){if(s===void 0)return;const e=window.WebGLRenderingContext,i={[e.CLAMP_TO_EDGE]:C.ClampToEdgeWrapping,[e.REPEAT]:C.Repeat,[e.MIRRORED_REPEAT]:C.MirroredRepeat,[e.NEAREST]:C.NearestFilter,[e.NEAREST_MIPMAP_NEAREST]:C.NearestMipMapNearestFilter,[e.NEAREST_MIPMAP_LINEAR]:C.NearestMipMapLinearFilter,[e.LINEAR]:C.LinearFilter,[e.LINEAR_MIPMAP_NEAREST]:C.LinearMipMapNearestFilter,[e.LINEAR_MIPMAP_LINEAR]:C.LinearMipMapLinearFilter,[e.RGBA]:C.RgbaFormat,[e.ALPHA]:C.AlphaFormat,[e.RGB]:C.RgbFormat,[e.UNSIGNED_BYTE]:C.UnsignedByte,[e.FLOAT]:C.Float}[s];return i===void 0?(console.error(`Failed to translate texture parameter ${s}`),NaN):i}const Ys=class Ys{constructor(e={}){this._texture=null,this._glContext=null,this._frameBuffer=null,this._depthAttachment=null,this.options=Object.assign({},Ys.defaultOptions,e),this.options.hasColorOutput&&(this._texture=new C(null,this.options))}bind(e,t){return this._frameBuffer||this._prepare(e),t?e.bindFramebuffer(t,this._frameBuffer):e.bindFramebuffer(e.FRAMEBUFFER,this._frameBuffer),this}unbind(e){return e.bindFramebuffer(e.FRAMEBUFFER,null),this}remove(){return this._unprepare(),this}setSize(e){return this.options.size=e,this._unprepare(),this}getTexture(){return this._texture}getDepthAttachment(){return this._depthAttachment}memSizeGPU(){const{_texture:e,_depthAttachment:t}=this;let i=0;if(this.options.depthTexture||this.options.useHighDepthPrecision)i=4;else switch(this.options.depthInternalFormat){case WebGLRenderingContext.DEPTH_STENCIL:i=1;break;case WebGLRenderingContext.DEPTH_COMPONENT16:i=2;break;default:!(this._glContext instanceof WebGLRenderingContext)&&WebGL2RenderingContext.DEPTH_COMPONENT24&&(i=3)}return{_texture:e?n.textureSizeGpu(e):{_texture:0},_depthAttachment:t===null?0:this.options.size[0]*this.options.size[1]*i}}_prepare(e){var t,i;if(this._glContext=e,!this._texture&&this.options.hasColorOutput&&(this._texture=new C(null,this.options)),this._frameBuffer=e.createFramebuffer(),e.bindFramebuffer(e.FRAMEBUFFER,this._frameBuffer),this._texture&&(this._texture.prepare(e),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this._texture.getTexture(),0)),this.options.depthTexture){const r=this._depthAttachment=new C(null,{magFilter:(t=this.options.magFilter)!=null?t:C.NearestFilter,minFilter:(i=this.options.minFilter)!=null?i:C.NearestFilter,format:C.DepthComponentFormat,size:this.options.size,premultiplyAlpha:!1,generateMipmaps:!1,type:C.UnsignedInt,compareFunc:this.options.compareFunc});r.prepare(e),e.framebufferTexture2D(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.TEXTURE_2D,r.getTexture(),0)}else{const r=this.options.useHighDepthPrecision?e.DEPTH_STENCIL:this.options.depthInternalFormat,o=this.options.useHighDepthPrecision?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;this._depthAttachment=e.createRenderbuffer(),e.bindRenderbuffer(e.RENDERBUFFER,this._depthAttachment),e.renderbufferStorage(e.RENDERBUFFER,r,this.options.size[0],this.options.size[1]),e.framebufferRenderbuffer(e.FRAMEBUFFER,o,e.RENDERBUFFER,this._depthAttachment)}this._checkComplete(e),e.bindRenderbuffer(e.RENDERBUFFER,null),e.bindFramebuffer(e.FRAMEBUFFER,null)}_unprepare(){this._texture&&(this._texture.remove(),this._texture=null),this._glContext&&this._depthAttachment&&(this._depthAttachment instanceof C?this._depthAttachment.remove():this._glContext.deleteRenderbuffer(this._depthAttachment),this._depthAttachment=null),this._glContext&&this._frameBuffer&&(this._glContext.deleteFramebuffer(this._frameBuffer),this._frameBuffer=null)}_checkComplete(e){if(n.forceGlStatusCheck()){const t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t===e.FRAMEBUFFER_COMPLETE)return;t===e.FRAMEBUFFER_UNSUPPORTED?console.log("Framebuffer is unsupported"):t===e.FRAMEBUFFER_INCOMPLETE_ATTACHMENT?console.log("Framebuffer incomplete attachment"):t===e.FRAMEBUFFER_INCOMPLETE_DIMENSIONS?console.log("Framebuffer incomplete dimensions"):t===e.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT?console.log("Framebuffer incomplete missing attachment"):console.log(`Unexpected framebuffer status: ${t}`)}}};Ys.defaultOptions=Object.assign({},C.defaultOptions,{size:[0,0],generateMipmaps:!1,depthTexture:!1,hasColorOutput:!0,useHighDepthPrecision:!1,depthInternalFormat:WebGLRenderingContext.DEPTH_COMPONENT16});let Pe=Ys;function lr(s){const e=document.createElement("canvas"),t={antialias:!1,stencil:!0,failIfMajorPerformanceCaveat:s};return"WebGLRenderingContext"in window?e.getContext("webgl",t)||e.getContext("experimental-webgl",t):null}const ro={};function jf(s){const e=String(s);return ro[e]===void 0&&(ro[e]=Xf(s)),ro[e]}function Xf(s){const e=lr(s);if(!e)return{ok:!1,msg:"error on get context"};for(const i of["OES_element_index_uint","OES_standard_derivatives","OES_vertex_array_object"])if(!e.getExtension(i))return{ok:!1,msg:`${i} extension is not supported`};try{const i=new Uint8Array(4);e.readPixels(0,0,1,1,e.RGBA,e.UNSIGNED_BYTE,i)}catch(i){return{ok:!1,msg:"readPixels is not supported"}}let t;try{t=e.createShader(e.VERTEX_SHADER)}catch(i){return{ok:!1,msg:"browser block shader API"}}return!t||e.isContextLost()?{ok:!1}:(e.shaderSource(t,"void main() {}"),e.compileShader(t),{ok:e.getShaderParameter(t,e.COMPILE_STATUS)===!0})}let Ai;function Vl(){Ai=void 0;const s=new Float32Array([-1,-1,1,-1,-1,1]),e=2,t=lr(!1);if(!t)return Ai="Failed to obtain WebGL context",!1;for(const m of["OES_element_index_uint","OES_standard_derivatives","OES_vertex_array_object","OES_texture_float","OES_texture_float_linear"])if(!t.getExtension(m))return Ai=`Absent ${m} extension`,!1;const i=new Pe({size:[e,e]});i.bind(t);const r=new C(new Float32Array([1,0,1,0]),{size:[2,2],format:C.AlphaFormat,type:C.Float,magFilter:C.LinearFilter,minFilter:C.LinearFilter}).prepare(t),o=`attribute vec2 pos;
    void main () {
        gl_Position = vec4(pos, 0, 1);
    }`,a=`precision mediump float;
    uniform sampler2D tex;
    void main () {
        gl_FragColor = vec4(texture2D(tex, vec2(0.4, 0.4)).a, 0, 0, 0);
    }`,l=t.createShader(t.VERTEX_SHADER),c=t.createShader(t.FRAGMENT_SHADER);if(!l||!c||t.isContextLost())return Ai="Cannot create shaders",!1;t.shaderSource(l,o),t.compileShader(l),t.shaderSource(c,a),t.compileShader(c);const d=t.createProgram();if(!d)return Ai="Cannot compile shader program",!1;t.attachShader(d,l),t.attachShader(d,c),t.linkProgram(d),t.useProgram(d);const u=t.createBuffer();if(!u)return Ai="Cannot create buffer",!1;t.bindBuffer(t.ARRAY_BUFFER,u),t.bufferData(t.ARRAY_BUFFER,s,t.STATIC_DRAW);const h=t.getAttribLocation(d,"pos");t.vertexAttribPointer(h,2,t.FLOAT,!1,0,0),t.enableVertexAttribArray(h),r.enable(t,0);const _=t.getUniformLocation(d,"tex");t.uniform1i(_,0),t.viewport(0,0,e,e),t.drawArrays(t.TRIANGLES,0,3);const f=new Uint8Array(4);return t.readPixels(0,0,1,1,t.RGBA,t.UNSIGNED_BYTE,f),i.unbind(t),f[0]!==255}function $f(){return Ai}let Tt=null;function cr(){if(Tt!==null)return Tt;const s=lr(!1);if(!s)return Tt=!0,Tt;const e=`
    attribute vec2 pos;
    varying float v1, v2, v3, v4, v5, v6, v7, v8, v9, v10;
    void main () {
        v1 = pos.x;
        v2 = pos.y;
        v3 = pos.x * 2.0;
        v4 = pos.y * 2.0;
        v5 = pos.x + pos.y;
        v6 = pos.x - pos.y;
        v7 = pos.x * pos.x;
        v8 = pos.y * pos.y;
        v9 = pos.x * pos.y;
        v10 = (pos.x + pos.y) / 2.0;

        gl_Position = vec4(pos, 0, 1);
    }`,t=`
    precision mediump float;
    varying float v1, v2, v3, v4, v5, v6, v7, v8, v9, v10;
    void main () {
        float result = v1 + v2 + v3 + v4 + v5 + v6 + v7 + v8 + v9 + v10;
        gl_FragColor = vec4(result / 10.0, 0, 0, 1); // усредняем результат
    }`,i=s.createShader(s.VERTEX_SHADER),r=s.createShader(s.FRAGMENT_SHADER);if(!i||!r||s.isContextLost())return Tt=!0,Tt;s.shaderSource(i,e),s.compileShader(i),s.shaderSource(r,t),s.compileShader(r);const o=s.createProgram();return!o||(s.attachShader(o,i),s.attachShader(o,r),s.linkProgram(o),!o||!s.getProgramParameter(o,s.LINK_STATUS))?(Tt=!0,Tt):(Tt=!1,Tt)}function qf(){const s=lr(!1);if(!s)return!1;if(!wf)return!0;const e=s.getExtension("WEBGL_debug_renderer_info");if(!e)return!1;const t=e?s.getParameter(e.UNMASKED_RENDERER_WEBGL):null;return t&&typeof t=="string"?!t.toUpperCase().includes("INTEL"):!1}function Yf(s){return s instanceof WebGLRenderingContext?!!s.getExtension("OES_texture_float"):!0}function Qf(s){return s.getParameter(s.MAX_VERTEX_TEXTURE_IMAGE_UNITS)>0}function Zl(s){return s instanceof WebGLRenderingContext?!!s.getExtension("WEBGL_depth_texture"):!0}function Jf(s){return!Wl(s)}function Wl(s){if(!Kf())return"not a browser";if(!tm())return"insufficient Function support";if(!nm())return"insufficient JSON support";if(!rm())return"insufficient worker support";if(!om())return"insufficient ArrayBuffer support";if(!am())return"insufficient Canvas/getImageData support";const e=jf(s&&s.failIfMajorPerformanceCaveat||!1);if(!e.ok)return`insufficient WebGL support${e.msg?`: ${e.msg}`:""}`;if(!em())return"insufficient Array support";if(!im())return"insufficient Object support";if(!sm())return"insufficient DOM support";if(!lm())return"insufficient ECMAScript 6 support"}function Kf(){return typeof window!="undefined"&&typeof document!="undefined"}function em(){return Array.prototype&&Array.prototype.every&&Array.prototype.filter&&Array.prototype.forEach&&Array.prototype.indexOf&&Array.prototype.map&&Array.prototype.some&&Array.prototype.reduce&&Array.isArray}function tm(){var s;return typeof((s=Function.prototype)==null?void 0:s.bind)=="function"}function im(){return!!(Object.keys&&Object.assign&&Object.create&&Object.getPrototypeOf&&Object.getOwnPropertyNames&&Object.getOwnPropertyDescriptor&&Object.defineProperty&&Object.freeze)}function nm(){return"JSON"in window&&"parse"in JSON&&"stringify"in JSON}function rm(){if(!("Worker"in window&&"Blob"in window&&"URL"in window))return!1;const s=new Blob([""],{type:"text/javascript"}),e=URL.createObjectURL(s);let t,i=null;try{i=new Worker(e),t=!0}catch(r){t=!1}return i&&i.terminate(),URL.revokeObjectURL(e),t}function sm(){const s=document.createElement("div");return s&&typeof s.after=="function"}function om(){return!!ArrayBuffer.isView}function am(){const s=document.createElement("canvas");s.width=s.height=1;const e=s.getContext("2d");if(!e)return!1;const t=e.getImageData(0,0,1,1);return t&&t.width===s.width}function lm(){return!("documentMode"in document)}function cm(){return $f()}const dm=qf,um=()=>q(null,null,function*(){if(!navigator)return!1;try{const s=navigator.gpu;if(typeof(s==null?void 0:s.requestAdapter)!="function"||!(yield s.requestAdapter({powerPreference:"high-performance"}))||!document.createElement("canvas").getContext("webgpu",{}))return!1}catch(s){return!1}return!0});class kt{static depthFuncToWebGL(e,t){switch(t){case n.DEPTH_FUNC.NEVER:return e.NEVER;case n.DEPTH_FUNC.LESS:return e.LESS;case n.DEPTH_FUNC.EQUAL:return e.EQUAL;case n.DEPTH_FUNC.LEQUAL:return e.LEQUAL;case n.DEPTH_FUNC.GREATER:return e.GREATER;case n.DEPTH_FUNC.NOTEQUAL:return e.NOTEQUAL;case n.DEPTH_FUNC.GEQUAL:return e.GEQUAL;case n.DEPTH_FUNC.ALWAYS:return e.ALWAYS;default:throw new Error(`Неизвестная функция теста глубины: ${t}`)}}static cullFaceModeToWebGL(e,t){switch(t){case n.CULL_FACE_MODE.FRONT:return e.FRONT;case n.CULL_FACE_MODE.BACK:return e.BACK;case n.CULL_FACE_MODE.FRONT_AND_BACK:return e.FRONT_AND_BACK;default:throw new Error(`Неизвестный режим отбрасывания: ${t}`)}}static blendFuncToWebGL(e,t){switch(t){case n.BLEND_FUNC.ZERO:return e.ZERO;case n.BLEND_FUNC.ONE:return e.ONE;case n.BLEND_FUNC.SRC_COLOR:return e.SRC_COLOR;case n.BLEND_FUNC.ONE_MINUS_SRC_COLOR:return e.ONE_MINUS_SRC_COLOR;case n.BLEND_FUNC.SRC_ALPHA:return e.SRC_ALPHA;case n.BLEND_FUNC.ONE_MINUS_SRC_ALPHA:return e.ONE_MINUS_SRC_ALPHA;case n.BLEND_FUNC.DST_ALPHA:return e.DST_ALPHA;case n.BLEND_FUNC.ONE_MINUS_DST_ALPHA:return e.ONE_MINUS_DST_ALPHA;case n.BLEND_FUNC.DST_COLOR:return e.DST_COLOR;case n.BLEND_FUNC.ONE_MINUS_DST_COLOR:return e.ONE_MINUS_DST_COLOR;case n.BLEND_FUNC.SRC_ALPHA_SATURATE:return e.SRC_ALPHA_SATURATE;default:throw new Error(`Неизвестная функция смешивания: ${t}`)}}static blendEquationToWebGL(e,t){switch(t){case n.BLEND_EQUATION.FUNC_ADD:return e.FUNC_ADD;case n.BLEND_EQUATION.FUNC_SUBTRACT:return e.FUNC_SUBTRACT;case n.BLEND_EQUATION.FUNC_REVERSE_SUBTRACT:return e.FUNC_REVERSE_SUBTRACT;case n.BLEND_EQUATION.MIN:return n.BLEND_EQUATION.MIN;case n.BLEND_EQUATION.MAX:return n.BLEND_EQUATION.MAX;default:throw new Error(`Неизвестное уравнение смешивания: ${t}`)}}static webGLToDepthFunc(e,t){switch(t){case e.NEVER:return n.DEPTH_FUNC.NEVER;case e.LESS:return n.DEPTH_FUNC.LESS;case e.EQUAL:return n.DEPTH_FUNC.EQUAL;case e.LEQUAL:return n.DEPTH_FUNC.LEQUAL;case e.GREATER:return n.DEPTH_FUNC.GREATER;case e.NOTEQUAL:return n.DEPTH_FUNC.NOTEQUAL;case e.GEQUAL:return n.DEPTH_FUNC.GEQUAL;case e.ALWAYS:return n.DEPTH_FUNC.ALWAYS;default:throw new Error(`Неизвестная WebGL константа функции глубины: ${t}`)}}static webGLToCullFaceMode(e,t){switch(t){case e.FRONT:return n.CULL_FACE_MODE.FRONT;case e.BACK:return n.CULL_FACE_MODE.BACK;case e.FRONT_AND_BACK:return n.CULL_FACE_MODE.FRONT_AND_BACK;default:throw new Error(`Неизвестная WebGL константа режима отбрасывания: ${t}`)}}}class hm{constructor(e){this.location=null,this.hasLastValue=!1,this.name=e.name,this.type=e.type}getLocation(e,t){return this.location=e.getUniformLocation(t,this.name),this.hasLastValue=!1,this}bind(e,t,i=!0){if(this.location===null)return this;if(i===!1)this.hasLastValue=!1;else{if(this.isSameAsLast(t))return this;this.rememberValue(t)}switch(this.type){case"1i":e.uniform1i(this.location,t);break;case"1f":e.uniform1f(this.location,t);break;case"2i":e.uniform2i(this.location,t[0],t[1]);break;case"2f":e.uniform2f(this.location,t[0],t[1]);break;case"3i":e.uniform3i(this.location,t[0],t[1],t[2]);break;case"3f":e.uniform3f(this.location,t[0],t[1],t[2]);break;case"4i":e.uniform4i(this.location,t[0],t[1],t[2],t[3]);break;case"4f":e.uniform4f(this.location,t[0],t[1],t[2],t[3]);break;case"1iv":e.uniform1iv(this.location,t);break;case"1fv":e.uniform1fv(this.location,t);break;case"2iv":e.uniform2iv(this.location,t);break;case"2fv":e.uniform2fv(this.location,t);break;case"3iv":e.uniform3iv(this.location,t);break;case"3fv":e.uniform3fv(this.location,t);break;case"4iv":e.uniform4iv(this.location,t);break;case"4fv":e.uniform4fv(this.location,t);break;case"mat2":e.uniformMatrix2fv(this.location,!1,t);break;case"mat3":e.uniformMatrix3fv(this.location,!1,t);break;case"mat4":e.uniformMatrix4fv(this.location,!1,t);break;default:throw new Error(`[WebGl] Unsupported uniform type: '${this.type}'`)}return this}isNonFloatType(){return this.type.includes("i")}isSameAsLast(e){if(!this.hasLastValue)return!1;const t=this.lastValue;if(!Xl(e))return jl(t,e);if(!Array.isArray(t)||t.length!==e.length)return!1;for(let i=t.length-1;i>=0;i--)if(!jl(t[i],e[i]))return!1;return!0}rememberValue(e){if(this.hasLastValue=!0,!Xl(e)){this.lastValue=e;return}const t=Array.isArray(this.lastValue)?this.lastValue:[];t.length=e.length;for(let i=0;i<e.length;i++)t[i]=e[i];this.lastValue=t}}function jl(s,e){return s===e||Object.is(s,e)}function Xl(s){return Array.isArray(s)||ArrayBuffer.isView(s)}const so=new WeakMap;function _m(s){so.delete(s)}const Qn=class Qn{constructor(e,t,i){this._gl=e,this.uniforms={},this.attributes={},this._webglProgram=null,this._linked=!1,this._linkComplete=!1,this._located=!1,this._error=!1,this._uniformBlocksIndices={},this._uboBindings={},this._uniformBlocksMap=null,t=t||{},t.uniforms=t.uniforms||[],t.uniforms.forEach(r=>{this.uniforms[r.name]=new hm(r)}),t.attributes=t.attributes||[],t.attributes.forEach(r=>{this.attributes[r.name]=new n.ShaderAttribute(r)}),i=i!=null?i:n.EMPTY_SHADER_DEFINITIONS,this._vertexShader=t.buildVertex(i),this._fragmentShader=t.buildFragment(i)}static getStableUboBinding(e){const t=Qn.fixedUboBindings[e];if(t!==void 0)return t;console.error(`Unknown UBO block "${e}". Add a fixed binding for it.`)}enable(){const e=this._gl;return this._error?this:(this.link(),this.locate(),this._error?this:(e.useProgram(this._webglProgram),so.set(e,this),this))}bind(e,t){if(this._error)return this;if(e){const i=so.get(this._gl)===this;for(const r in e)this.uniforms[r].bind(this._gl,e[r],i)}if(t)for(const i in t)this.attributes[i].bind(this._gl,t[i]);return this}disable(){if(this._error)return this;for(const e in this.attributes)this.attributes[e].disable(this._gl);return this}link(){return this.linkInternal(!0)}linkWithoutStatusCheck(){return this.linkInternal(!1)}locate(){const e=this._webglProgram;if(this._located||this._error||!e)return this;const t=this._gl;for(const i in this.attributes)this.attributes[i].getLocation(t,e);for(const i in this.uniforms)this.uniforms[i].getLocation(t,e);return this.locateUniformBlocks(e),this._located=!0,this}getUniformBlockIndex(e){return this._uniformBlocksIndices[e]}isLinked(){return this._linked}isLinkComplete(e){return!this._webglProgram||!this._linked||this._error?!1:this._linkComplete?!0:e&&!this._gl.getProgramParameter(this._webglProgram,e.COMPLETION_STATUS_KHR)?!1:(this.checkLinkStatus(),!this._error)}isReady(){return this._located&&!this._error}getUboBinding(e){return this._uboBindings[e]}getUniformBlockSize(e){if(this._gl instanceof WebGLRenderingContext)return null;const t=this._gl;let i=this._webglProgram;if(i||(this.link(),this.locate()),i=this._webglProgram,!i)return null;const r=this.getUniformBlockIndex(e);return r===void 0?null:t.getActiveUniformBlockParameter(i,r,t.UNIFORM_BLOCK_DATA_SIZE)}getUniformsIndicesOffsetsInBlock(e){if(this._gl instanceof WebGLRenderingContext)return null;const t=this._gl;let i=this._webglProgram;if(i||(this.link(),this.locate()),i=this._webglProgram,!i)return null;const r=t.getUniformIndices(i,e);if(!r)return console.error("Couldn't get UBO uniforms indices."),null;const o=r.filter(c=>c!==t.INVALID_INDEX),a=t.getActiveUniforms(i,o,t.UNIFORM_OFFSET);if(a===null)return console.error("Couldn't get active UBO uniform offsets."),null;const l={};for(let c=0;c<e.length;++c){const d=r[c];if(d!==t.INVALID_INDEX){const u=o.indexOf(d);l[e[c]]=a[u]}}return l}getUniformBlocksMap(){if(this._uniformBlocksMap)return this._uniformBlocksMap;if(this._gl instanceof WebGLRenderingContext)return null;const e=this._gl;let t=this._webglProgram;if(t||(this.link(),this.locate()),t=this._webglProgram,!t)return null;this._uniformBlocksMap={};const i=e.getProgramParameter(t,e.ACTIVE_UNIFORM_BLOCKS);for(let r=0;r<i;r++){const o=e.getActiveUniformBlockName(t,r);if(!o)continue;const a=e.getActiveUniformBlockParameter(t,r,e.UNIFORM_BLOCK_ACTIVE_UNIFORMS);if(a===null){console.error("Couldn't get number of uniforms in UBO.");continue}const l=e.getActiveUniformBlockParameter(t,r,e.UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES);if(!l){console.error("Couldn't get uniforms indices in UBO.");continue}const c=[];for(let d=0;d<a;d++){const u=e.getActiveUniform(t,l[d]);u&&c.push(u.name)}this._uniformBlocksMap[o]=c}return this._uniformBlocksMap}linkInternal(e){if(this._linked||this._error)return this;const t=this._gl;try{if(this._webglProgram=t.createProgram(),!this._webglProgram)throw new Error("Failed to create shader program");const i=this._webglProgram,r=this._vertexShader.get(t,e),o=this._fragmentShader.get(t,e);r&&t.attachShader(i,r),o&&t.attachShader(i,o);for(const a in this.attributes)this.attributes[a].bindLocation(t,i);t.linkProgram(i),this._linked=!0,e&&this.checkLinkStatus()}catch(i){throw this._error=!0,i}return this}checkLinkStatus(){if(!(this._linkComplete||this._error||!this._webglProgram))try{if(n.forceGlStatusCheck()&&!this._gl.getProgramParameter(this._webglProgram,this._gl.LINK_STATUS))throw new Error(this._gl.getProgramInfoLog(this._webglProgram)||"Couldn't get shader program Info Log");this._linkComplete=!0}catch(e){throw this._error=!0,e}}locateUniformBlocks(e){const t=this._gl;if(t instanceof WebGLRenderingContext)return;const i=this.getUniformBlocksMap();if(i)for(const r in i){const o=t.getUniformBlockIndex(e,r);if(o!==t.INVALID_INDEX){const a=Qn.getStableUboBinding(r);if(a===void 0)continue;this._uniformBlocksIndices[r]=o,this._uboBindings[r]=a,t.uniformBlockBinding(e,o,a)}}}};Qn.fixedUboBindings={CommonSettings:0,LightSettings:1};let oo=Qn;class fm{constructor(e){if(this.webGlExtensions={},this._canvasElement=null,this._size=[1,1],this._glStateCache=new Map,this._glCapCache=new Map,this._glTextureCache=new Map,this._storedStates={},e=e||{},"canvas"in e){this._canvasElement=typeof e.canvas=="string"?document.getElementById(e.canvas):e.canvas;const t={antialias:e.antialias!==void 0?e.antialias:!0,stencil:e.stencil!==void 0?e.stencil:!1,failIfMajorPerformanceCaveat:e.failIfMajorPerformanceCaveat!==void 0?e.failIfMajorPerformanceCaveat:!1,preserveDrawingBuffer:e.preserveDrawingBuffer!==void 0?e.preserveDrawingBuffer:!1};this._gl=e.version===2?this._canvasElement.getContext("webgl2",t):this._canvasElement.getContext("webgl",t)||this._canvasElement.getContext("experimental-webgl",t)}else this._gl=e.gl;this._pixelRatio=e.pixelRatio||1,this.clearColor=e.clearColor||[1,1,1,1],this.webGlExtensions={},this.overrideStateMethods()}setPixelRatio(e){return this._pixelRatio=e,this}getPixelRatio(){return this._pixelRatio}setSize(e,t){return this._size=[e*this._pixelRatio,t*this._pixelRatio],this._canvasElement&&(this._canvasElement.width=this._size[0],this._canvasElement.height=this._size[1],this._canvasElement.style.width=`${e}px`,this._canvasElement.style.height=`${t}px`),this.setViewport(),this}setViewport(e=0,t=0,i,r){return i!==void 0&&r!==void 0?this._gl.viewport(e,t,i,r):this._gl.viewport(e,t,this._size[0],this._size[1]),this}getSize(){return this._size}addExtension(e){return this.webGlExtensions[e]=this._gl.getExtension(e),this}prepareTexture(e){return e.prepare(this._gl),this}bindVao(e){return e.bind({gl:this._gl,extensions:this.webGlExtensions}),this}enableTexture(e,t){return e.enable(this._gl,t),this}disableTexture(e){const t=this._gl;return t.activeTexture(t.TEXTURE0+e),t.bindTexture(t.TEXTURE_2D,null),this}isDepthTextureSupported(){return Zl(this._gl)}isShadowSamplerSupported(){return!(this._gl instanceof WebGLRenderingContext)&&this.isDepthTextureSupported()}isContextLost(){return this._gl.isContextLost()}storeGpuState(e){var r,o,a,l;const t=this._gl,i=this._glStateCache;this._storedStates[e]={depthMask:(r=i.get("depthMask"))!=null?r:t.getParameter(t.DEPTH_WRITEMASK),depthTest:(o=this._glCapCache.get(t.DEPTH_TEST))!=null?o:t.getParameter(t.DEPTH_TEST),depthFunc:(a=i.get("depthFunc"))!=null?a:t.getParameter(t.DEPTH_FUNC),clearDepth:(l=i.get("clearDepth"))!=null?l:t.getParameter(t.DEPTH_CLEAR_VALUE)}}restoreGpuState(e){const t=this._storedStates[e];if(t){const i=this._gl;i.depthMask(t.depthMask),t.depthTest?i.enable(i.DEPTH_TEST):i.disable(i.DEPTH_TEST),i.depthFunc(t.depthFunc),i.clearDepth(t.clearDepth)}}drawPoints(e,t){this._gl.drawArrays(this._gl.POINTS,e,t)}drawTriangles(e,t){this._gl.drawArrays(this._gl.TRIANGLES,e,t)}drawTrianglesFan(e,t){this._gl.drawArrays(this._gl.TRIANGLE_FAN,e,t)}drawArrays(e,t,i){this._gl.drawArrays(e,t,i)}drawElements(e,t,i,r){this._gl.drawElements(e,t,i,r)}drawInstancedElements(e,t,i,r,o){const a=this._gl,l=this.webGlExtensions.ANGLE_instanced_arrays;if(a instanceof WebGLRenderingContext){if(!l)return;l.drawElementsInstancedANGLE(e,t,i,r,o)}else a.drawElementsInstanced(e,t,i,r,o)}drawInstancedArrays(e,t,i,r){const o=this._gl,a=this.webGlExtensions.ANGLE_instanced_arrays;if(o instanceof WebGLRenderingContext){if(!a)return;a.drawArraysInstancedANGLE(e,t,i,r)}else o.drawArraysInstanced(e,t,i,r)}triangleCountByDrawMode(e,t){const i=this._gl;switch(e){case i.TRIANGLES:return t/3;case i.TRIANGLE_FAN:case i.TRIANGLE_STRIP:return t-2;default:return 0}}createBuffer(e,t,i,r){return new n.Buffer(this._gl,e,t,i,r)}applyState(e,t){var o,a,l,c,d,u,h,_,f,m,v,g,p,x,S,b,T,y;const i=this._gl;if(i.depthMask((o=t==null?void 0:t.depthMask)!=null?o:e.depthMask),((a=t==null?void 0:t.depthTest)!=null?a:e.depthTest)?(i.enable(i.DEPTH_TEST),this.setDepthFunc((l=t==null?void 0:t.depthFunc)!=null?l:e.depthFunc)):i.disable(i.DEPTH_TEST),((c=t==null?void 0:t.cullFace)!=null?c:e.cullFace)?(i.enable(i.CULL_FACE),this.setCullFaceMode((d=t==null?void 0:t.cullFaceMode)!=null?d:e.cullFaceMode)):i.disable(i.CULL_FACE),(u=t==null?void 0:t.blend)!=null?u:e.blend){i.enable(i.BLEND),this.setBlendEquation((h=t==null?void 0:t.blendEquation)!=null?h:e.blendEquation);const E=(_=t==null?void 0:t.blendFuncSeparate)!=null?_:e.blendFuncSeparate;E?this.setBlendFuncSeparate(E.srcRgb,E.dstRgb,E.srcAlpha,E.dstAlpha):this.setBlendFunc((m=(f=t==null?void 0:t.blendFunc)==null?void 0:f.sfactor)!=null?m:e.blendFunc.sfactor,(g=(v=t==null?void 0:t.blendFunc)==null?void 0:v.dfactor)!=null?g:e.blendFunc.dfactor)}else i.disable(i.BLEND);const r=(p=t==null?void 0:t.colorMask)!=null?p:e.colorMask;i.colorMask(r[0],r[1],r[2],r[3]),((x=t==null?void 0:t.polygonOffsetFill)!=null?x:e.polygonOffsetFill)?(i.enable(i.POLYGON_OFFSET_FILL),i.polygonOffset((b=(S=t==null?void 0:t.polygonOffset)==null?void 0:S.factor)!=null?b:e.polygonOffset.factor,(y=(T=t==null?void 0:t.polygonOffset)==null?void 0:T.units)!=null?y:e.polygonOffset.units)):i.disable(i.POLYGON_OFFSET_FILL)}setDepthFunc(e){const t=kt.depthFuncToWebGL(this._gl,e);this._gl.depthFunc(t)}setCullFaceMode(e){const t=kt.cullFaceModeToWebGL(this._gl,e);this._gl.cullFace(t)}setBlendFunc(e,t){const i=kt.blendFuncToWebGL(this._gl,e),r=kt.blendFuncToWebGL(this._gl,t);this._gl.blendFunc(i,r)}setBlendFuncSeparate(e,t,i,r){const o=kt.blendFuncToWebGL(this._gl,e),a=kt.blendFuncToWebGL(this._gl,t),l=kt.blendFuncToWebGL(this._gl,i),c=kt.blendFuncToWebGL(this._gl,r);this._gl.blendFuncSeparate(o,a,l,c)}setBlendEquation(e){const t=kt.blendEquationToWebGL(this._gl,e);this._gl.blendEquation(t)}setBlendEquationSeparate(e,t){const i=kt.blendEquationToWebGL(this._gl,e),r=kt.blendEquationToWebGL(this._gl,t);this._gl.blendEquationSeparate(i,r)}setDepthMask(e){this._gl.depthMask(e)}invalidateGlStateCache(){this._glStateCache.clear(),this._glCapCache.clear(),this._glTextureCache.clear(),_m(this._gl)}overrideStateMethods(){const e=this._gl,t=this._glStateCache,i=(y,E,P)=>y.get(E)===P&&y.has(E)?!0:(y.set(E,P),!1),r=(y,E)=>i(t,y,E),o=this._glCapCache,a=this._glTextureCache,l=e.depthMask.bind(e);e.depthMask=y=>{r("depthMask",y)||l(y)};const c=e.enable.bind(e);e.enable=y=>{i(o,y,!0)||c(y)};const d=e.disable.bind(e);e.disable=y=>{i(o,y,!1)||d(y)};const u=e.depthFunc.bind(e);e.depthFunc=y=>{r("depthFunc",y)||u(y)};const h=e.cullFace.bind(e);e.cullFace=y=>{r("cullFace",y)||h(y)};const _=e.colorMask.bind(e);e.colorMask=(y,E,P,A)=>{r("colorMask",`${y},${E},${P},${A}`)||_(y,E,P,A)};const f=e.blendFunc.bind(e);e.blendFunc=(y,E)=>{r("blendFunc",`${y},${E},${y},${E}`)||f(y,E)};const m=e.blendFuncSeparate.bind(e);e.blendFuncSeparate=(y,E,P,A)=>{r("blendFunc",`${y},${E},${P},${A}`)||m(y,E,P,A)};const v=e.blendEquation.bind(e);e.blendEquation=y=>{r("blendEquation",`${y},${y}`)||v(y)};const g=e.blendEquationSeparate.bind(e);e.blendEquationSeparate=(y,E)=>{r("blendEquation",`${y},${E}`)||g(y,E)};const p=e.polygonOffset.bind(e);e.polygonOffset=(y,E)=>{r("polygonOffset",`${y},${E}`)||p(y,E)};const x=e.useProgram.bind(e);e.useProgram=y=>{r("program",y)||x(y)};const S=e.activeTexture.bind(e);e.activeTexture=y=>{r("activeTexture",y)||S(y)};const b=e.bindTexture.bind(e);if(e.bindTexture=(y,E)=>{const P=t.get("activeTexture");if(P===void 0){b(y,E);return}i(a,(P-e.TEXTURE0)*65536+y,E)||b(y,E)},e instanceof WebGL2RenderingContext){const y=e.bindVertexArray.bind(e);e.bindVertexArray=E=>{r("vao",E)||y(E)}}const T=e.clearDepth.bind(e);e.clearDepth=y=>{r("clearDepth",y)||T(y)}}}const dr=[1,1,1,1],ao=[.5,0];function mm(s){return s.type==="color"&&s.gradientValue&&s.gradientMid!==void 0?[n.getColorForShaders({value:s.gradientValue}),[s.gradientMid,1]]:[dr,ao]}const $l=3.7,vm=n.create$1(),gm=n.create$1(),ql=n.create$2(),pm=n.create$2(),xm=n.create$1(),bm=n.fromValues(0,1,0),Yl=(s,e,t,i)=>{Ut(t,s,{u_float_rounding_factor:e.stillness},i)},Li=(s,e,t,i)=>{Ut(t,s,{u_float_border_width_offset:1/window.devicePixelRatio},i)},ur=(s,e,t,i)=>{const r=(n.POINT_CENTER_SIZE-.5)/2,{size:o}=e;Ut(t,s,{u_vec2_depth_test_half_point_size:[r/o[0],r/o[1]]},i)},X=(s,e,t,i)=>{if(!t.environmentManager.isFogEnabled())return;const r=t.styleManager.getStyle(e.handyStyleId);let o=dr,a=dr,l=dr,c=ao;if(r){const _=n.makeBinderContext(e.styleZoom,e.pitch,e.styleState,[]);o=n.getColorForShaders(n.resolveColor(r.environment.style.skyColor,_));const f=n.resolveColor(r.environment.style.fogColor,_);a=n.getColorForShaders(f),[l,c]=mm(f)}const d=t.camera,u=!e.demMode||!e.elevation||Number.isNaN(e.elevation)?0:e.elevation*n.MAP_POINTS_IN_METER,h=Math.min(1+Math.max(u/n.zoomToHeight(e.zoom,e.size),0),$l);Ut(t,s,{u_sky_color:e.globeMode?[0,0,0,0]:o,u_fog_color:e.globeMode?[0,0,0,0]:a,u_fog_color2:e.globeMode?[0,0,0,0]:l,u_fog_gradient:e.globeMode?ao:c,u_fog_distance:e.globeMode?0:d.fogDistance,u_fog_limits:t.environmentManager.fogLimits,u_fog_horizon_blend:t.environmentManager.fogHorizonBlend,u_fog_horizon_level:t.environmentManager.fogHorizonLevel,u_fog_horizon_pad:e.cameraConfig.fogHorizonPadFactor*h},i)},W=(s,e,t,i)=>{Ut(t,s,{u_cam_pos:t.camera.position},i)},ae=(s,e,t,i)=>{t.shadowManager.texture&&Ut(t,s,{u_shadow_map_params:t.shadowManager.shadowMapParams,u_shadow_bias:t.shadowManager.bias,u_mat4_clip_to_shadow:t.shadowManager.clipToShadowMatrix},i)},pn=(s,e,t,i)=>{Ut(t,s,{u_vec2_scale_limits:[0,n.z0Scale]},i)},Ql=(s,e,t,i)=>{const r=t.camera.viewMatrixTranspose,o=t.camera.projectionMatrixInverse;Ut(t,s,{u_mat4_view_transposed:r,u_mat4_proj_inverted:o},i)},lo=(s,e,t,i)=>{const r=window.devicePixelRatio,o=t.camera.ecef.pixelRadius*r,{left:a,bottom:l,top:c,right:d}=e.padding,[u,h]=e.size,_=[u*r,h*r],f=[(a-d)*r/2,(l-c)*r/2],m=t.environmentManager.globHaloStops.map(b=>(o+b*r)/_[1]),v=t.styleManager.getStyle(e.handyStyleId);if(!v)return;const g=v==null?void 0:v.environment;if(!g)return;const p=n.makeBinderContext(e.styleZoom,e.pitch,e.styleState,[]),x=n.resolveColor(g.style.fogColor,p),S=n.resolveColor(v.background.color,p);Ut(t,s,{u_vec2_halo_viewport_size:_,u_vec2_halo_viewport_center_shift:f,u_vec4_halo_radius_stops:m,u_vec4_halo_color:n.getColorForShaders(x),u_float_halo_exp_factor:t.environmentManager.globeHaloExpFactor,u_vec4_default_background_color:n.getColorForShaders(S)},i)},Jl=(s,e,t,i)=>{const r=e.size,o=Math.max(r[0],r[1]),a=r[0]/o,l=r[1]/o;n.ortho(ql,-a/2,a/2,-l/2,l/2,.001,1);const c=n.Mercator.toGeo(e.center),d=n.set(gm,0,0,0),u=n.set(vm,0,0,1);n.rotateX(u,u,d,n.degToRad(c[1])),n.rotateY(u,u,d,n.degToRad(c[0]));const h=n.lookAt(pm,xm,u,bm);n.multiply(h,ql,h);const _=t.styleManager.getStyle(e.handyStyleId);if(!_)return;const f=_==null?void 0:_.environment;if(!f)return;const m=n.makeBinderContext(e.styleZoom,e.pitch,e.styleState,[]),v=n.resolveNumber(f.style.starsIntensity,m);Ut(t,s,{u_float_pixelratio:window.devicePixelRatio,u_float_stars_intensity:v,u_mat4_stars:h},i)},ne=(s,e,t,i)=>{const{size:r}=e,o=window.devicePixelRatio;Ut(t,s,{u_vec2_vpt_size:[r[0]*o,r[1]*o]},i)};function Ut(s,e,t,i){i?i.updateData(e,t):s.renderer.bindShaderProgram(e,t)}function Y(...s){return(e,t,i,r)=>{s.forEach(o=>o(e,t,i,r))}}const Sm=Y(Yl,Li,ur,X,W,ae,pn,Ql,lo,Jl,ne),Kl=Y(W,X),ec=(s,e,t)=>{const{size:i}=e,r=window.devicePixelRatio;if(e.demMode){const o=t.renderer.getFramebuffer(t.demManager.getFlatFramebufferId());if(!o)return;t.renderer.bindShaderProgram(s,{u_vec2_vpt_size:[Math.trunc(o.renderTarget.options.size[0]),Math.trunc(o.renderTarget.options.size[1])]})}else t.renderer.bindShaderProgram(s,{u_vec2_vpt_size:[i[0]*r,i[1]*r]})},$i=(s,e,t)=>{const i=n.zoomToScale(e.zoom);t.renderer.bindShaderProgram(s,{u_vec3_projection_scale_style_scale_dpi:[i,i,n.zptPerInch*window.devicePixelRatio]})},tc=(s,e,t)=>{t.renderer.bindShaderProgram(s,{u_float_pixel_ratio:window.devicePixelRatio})},ic=(s,e,t)=>{const i=n.zoomToScale(e.styleZoom);t.renderer.bindShaderProgram(s,{u_vec3_projection_scale_style_scale_dpi:[i,i,n.zptPerInch*window.devicePixelRatio]})},hr=(s,e,t)=>{t.renderer.bindShaderProgram(s,{u_float_height_factor:t.buildingHeightAnimator.getDefaultBuildingHeight()})},_r=(s,e,t)=>{t.renderer.bindShaderProgram(s,{u_float_z_offset:0})},ym=(s,e,t)=>{t.renderer.bindShaderProgram(s,{u_float_z_offset:-1e-5})},Mt=(s,e,t)=>{t.renderer.bindShaderProgram(s,{u_sr2d_texture:0})},xn=(s,e,t)=>{t.renderer.bindShaderProgram(s,{u_sr2d_texture1:1})},bn=(s,e,t)=>{const{position:i}=t.camera,{center:r}=e;t.renderer.bindShaderProgram(s,{u_float_center_distance:Math.hypot(i[0]-r[0],i[1]-r[1],i[2]-r[2])})},nc=(s,e,t)=>{t.renderer.bindShaderProgram(s,{u_vec4_border_color:[0,0,0,0]})},rc=(s,e,t)=>{t.renderer.bindShaderProgram(s,{u_vec4_space_color:[0,0,0,0]})},Tm=(s,e,t)=>{t.renderer.bindShaderProgram(s,{u_float_identify_opacity:e.iconIdentifyOpacity})},Em=(s,e,t)=>{const{renderer:i}=t,{spriteLabelingTextureBuffer:r}=i,o=r.getTexture();o&&(t.renderer.enableTexture(o,ih),t.renderer.bindShaderProgram(s,{u_color_text_sprite_labeling:ih}))},Sn=(s,e,t)=>{const{renderer:i}=t,{labelingTextureBuffer:r}=i;let o=e.isLabelingDepthTestDisabled;if(!o){const a=r.getDepthAttachment(),l=r.getTexture();!(a instanceof C)||!l?o=!0:(t.renderer.enableTexture(l,Za),t.renderer.enableTexture(a,Wa))}t.renderer.bindShaderProgram(s,{u_bool_depth_test_disable:o}),o||t.renderer.bindShaderProgram(s,{u_color_tex_labeling:Za,u_depth_tex_labeling:Wa})},sc=(s,e,t)=>{const{renderer:i}=t;i.disableTexture(Za),i.disableTexture(Wa),t.renderer.bindShaderProgram(s,{u_bool_depth_test_disable:!0})};function yn(...s){return(e,t,i)=>{s.forEach(r=>r(e,t,i))}}function Ne(...s){return(e,t,i,r,o)=>{s.forEach(a=>a(e,t,i,r,o))}}const Cm=1,oc=2,Im=4,_e=(s,e,t,i,r)=>{let o=n.ReservedLightingMode.none,a=n.DEFAULT_LIGHTING_MODES[o],l=0;const c=mr(i,t,e);c&&(a=c.lightConfig,o=c.lightingMode,l=(o===n.ReservedLightingMode.none||r?0:Cm)+(i.receiveShadows!==!1&&a.shadowLightIndex===0?oc:0)+(i.receiveShadows!==!1&&a.shadowLightIndex===1?Im:0),i.id==="dem"&&(l=oc));const d=t.renderer.getUbo(o);if(d&&t.renderer.isUboSupported()){d.bind(s),t.renderer.bindShaderProgram(s,{u_int_light_flags:l});return}t.renderer.bindShaderProgram(s,{u_int_light_flags:l,u_vec3_light_dir1_direction:a.dir1Direction,u_vec4_light_dir1_color:a.dir1ColorIntensity,u_vec3_light_dir2_direction:a.dir2Direction,u_vec4_light_dir2_color:a.dir2ColorIntensity,u_vec4_ambient_color:a.ambientColorIntensity})},Ht=(s,e,t,i)=>{const r=n.makeBinderContext(e.styleZoom,e.pitch,e.styleState,[],!1),o=n.resolveNumber(i.style.nearCameraFade,r);t.renderer.bindShaderProgram(s,{u_sdtr_distance:o})},fr=(s,e,t,i)=>{const r=n.makeBinderContext(e.styleZoom,e.pitch,e.styleState,[],!1),o=i.style.showRatio,a=n.resolveExpression(o,r);t.renderer.bindShaderProgram(s,{u_float_show_ratio:a})};function mr(s,e,t){var a;const i=e.styleManager.getStyle(t.handyStyleId);if(!i||!i.light.lightingModesResolved)return null;let r=(a=s.lightingMode)!=null?a:i.light.defaultLightMode;s.type==="gltfModel"&&s.style.ignoreGlobalLighting&&(r=n.ReservedLightingMode.none);let o=i.light.lightingModesResolved[r];return o||(o=i.light.lightingModesResolved[i.light.defaultLightMode]),{lightingMode:r,lightConfig:o}}class M{constructor(e,t,i=null){this.isDirty=!1,this._vao=null,this._vaoExt=null,this._gl=null,this.attributesAliases={},this._attributes=t,this._shaderProgram=e,this.indicesBuffer=i}static merge(e){const t=e[0],i={},r={};for(const a of e)Object.assign(i,a._attributes),Object.assign(r,a.attributesAliases);const o=new M(t._shaderProgram,i,t.indicesBuffer);return o.setAttributesAliases(r),o}copy(){const e=new M(this._shaderProgram,I({},this._attributes),this.indicesBuffer);return e.setAttributesAliases(this.attributesAliases),e}bind(e){const t=e.extensions.OES_vertex_array_object,i=e.extensions.ANGLE_instanced_arrays;return this._bind(e.gl,t,i),this}unbind(){return this._glBindVertexArray(null),this}setAttribute(e,t){this._attributes[e]=t,this.remove()}remove(){return this._vao&&(this._glDeleteVertexArray(this._vao),this._vao=null),this}getElementsGLType(){return this.indicesBuffer?this.indicesBuffer.getGLType():null}getBuffer(e){return this._attributes[e]}rewriteData(e,t){this._attributes[e].replaceData(t),this.isDirty=!0}setAttributesAliases(e){Object.assign(this.attributesAliases,e),this.remove()}setAttributes(e,t){const i=this._shaderProgram.attributes,r=this._attributes;for(const o in i){const l=this.attributesAliases[o]||o,c=r[l];if(!c)continue;const d=i[o];if(d.index!==!0)for(let u=0;u<d.locationsCount;u++)e.enableVertexAttribArray(d.location+u);c.bind(d.location,void 0,t,d.locationsCount)}this.indicesBuffer&&this.indicesBuffer.bind()}_bind(e,t,i){this._vao?(this.isDirty&&this.updateDirtyBuffers(),this._glBindVertexArray(this._vao)):this._prepare(e,t,i)}_prepare(e,t,i){this._gl=e,t&&(this._vaoExt=t),this._vao=this._glCreateVertexArray(),this._glBindVertexArray(this._vao),this.setAttributes(e,i)}_glCreateVertexArray(){const e=this._gl,t=this._vaoExt;return e&&this._isWebGL2(e)?e.createVertexArray():t?t.createVertexArrayOES():null}_glBindVertexArray(e){const t=this._gl,i=this._vaoExt;t&&this._isWebGL2(t)?t.bindVertexArray(e):i?i.bindVertexArrayOES(e):t&&this._shaderProgram.bind(void 0,this._attributes)}_glDeleteVertexArray(e){const t=this._gl,i=this._vaoExt;t&&this._isWebGL2(t)?t.deleteVertexArray(e):i&&i.deleteVertexArrayOES(e)}_isWebGL2(e){return typeof window!="undefined"&&"WebGL2RenderingContext"in window&&e instanceof WebGL2RenderingContext}updateDirtyBuffers(){const e=this._shaderProgram.attributes,t=this._attributes,i=this.attributesAliases;for(const r in e){const o=i[r]||r,a=t[o];a!=null&&a.isDirty&&a.commitData()}this.isDirty=!1}}const Pm=(s,e)=>{const t=n.PolygonGenerator.sinks.fill.stride,i=new n.BufferChannel(s,{itemSize:3,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0});return new M(e,{a_vec3_vertex:i})},Am=(s,e)=>{const t=n.PolygonGenerator.sinks.fill.stride,i=new n.BufferChannel(s,{itemSize:3,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.UnsignedShort,stride:t,offset:8,normalized:!1});return new M(e,{a_vec3_vertex:i,a_float_mix_factor:r})},Lm=(s,e)=>{const t=n.PolygonGenerator.sinks.shadow.stride,i=new n.BufferChannel(s,{itemSize:3,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0});return new M(e,{a_vec3_vertex:i})},Rm=(s,e)=>{const i=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:8,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:8,offset:4,normalized:!1});return new M(e,{a_vec2_vertex:i,a_vec2_texcoord:r})},Fm=(s,e)=>{const t=n.PolygonGenerator.sinks.fill.stride,i=new n.BufferChannel(s,{itemSize:3,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.UnsignedByte,stride:t,offset:8,normalized:!0});return new M(e,{a_vec3_vertex:i,a_vec4_identifier:r})},Dm=(s,e)=>{const t=n.LineGenerator.sinks.solid.stride,i=new n.BufferChannel(s,{itemSize:3,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.Byte,stride:t,offset:8,normalized:!1});return new M(e,{a_vec3_vertex:i,a_vec4_normals:r})},zm=(s,e)=>{const t=n.LineGenerator.sinks.solid3d.stride,i=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.Byte,stride:t,offset:4,normalized:!1}),o=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:8,normalized:!1}),a=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:12,normalized:!1});return new M(e,{a_vec2_vertex:i,a_vec4_normals:r,a_float_height:o,a_float_abs_z:a})},Bm=(s,e)=>{const t=n.LineGenerator.sinks.solid3d.stride,i=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.Byte,stride:t,offset:4,normalized:!1}),o=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:8,normalized:!1}),a=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:12,normalized:!1}),l=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.UnsignedByte,stride:t,offset:16,normalized:!0});return new M(e,{a_vec2_vertex:i,a_vec4_normals:r,a_float_height:o,a_float_abs_z:a,a_vec4_identifier:l})},Om=(s,e)=>{const t=n.ShiftedLineGenerator.sinks.solid.stride,i=new n.BufferChannel(s,{itemSize:3,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.Byte,stride:t,offset:8,normalized:!1}),o=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Float,stride:t,offset:12,normalized:!1});return new M(e,{a_vec3_vertex:i,a_vec4_normals:r,a_vec2_shift:o})},wm=(s,e)=>{const t=n.LineGenerator.sinks.solid.stride,i=new n.BufferChannel(s,{itemSize:3,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.Byte,stride:t,offset:8,normalized:!1}),o=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.UnsignedByte,stride:t,offset:12,normalized:!0});return new M(e,{a_vec3_vertex:i,a_vec4_normals:r,a_vec4_identifier:o})},Nm=(s,e)=>{const t=n.LineGenerator.sinks.patterned.stride,i=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:t,offset:4,normalized:!1}),o=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:8}),a=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.UnsignedByte,stride:t,offset:12,normalized:!0});return new M(e,{a_vec2_vertex:i,a_vec2_widen:r,a_float_texture:o,a_vec4_identifier:a})},km=(s,e)=>{const t=n.LineGenerator.sinks.patterned3d.stride,i=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:t,offset:4,normalized:!1}),o=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:8}),a=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:12,normalized:!1}),l=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.UnsignedByte,stride:t,offset:16,normalized:!0});return new M(e,{a_vec2_vertex:i,a_vec2_widen:r,a_float_texture:o,a_float_height:a,a_vec4_identifier:l})},ac=(s,e)=>{const t=n.DashedLineGenerator.sinks.stroke.stride,i=new n.BufferChannel(s,{itemSize:3,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Byte,stride:t,offset:6,normalized:!1}),o=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:t,offset:8,normalized:!1}),a=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:12,normalized:!1}),l=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:16,normalized:!1}),c=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:20,normalized:!1}),d=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.UnsignedByte,stride:t,offset:24,normalized:!0});return new M(e,{a_vec3_vertex:i,a_vec2_texture_widen:r,a_vec2_widen:o,a_float_vertex_distance:a,a_float_component_distance:l,a_float_object_length:c,a_vec4_identifier:d})},lc=(s,e)=>{const t=n.DashedLineGenerator.sinks.stroke3d.stride,i=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:t,offset:4,normalized:!1}),o=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Byte,stride:t,offset:8,normalized:!1}),a=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:12,normalized:!1}),l=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:16,normalized:!1}),c=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:20,normalized:!1}),d=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:24,normalized:!1}),u=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.UnsignedByte,stride:t,offset:28,normalized:!0});return new M(e,{a_vec3_vertex:i,a_vec2_texture_widen:o,a_vec2_widen:r,a_float_vertex_distance:a,a_float_component_distance:l,a_float_object_length:c,a_float_height:d,a_vec4_identifier:u})},cc=(s,e)=>{const i=new n.BufferChannel(s,{itemSize:3,dataType:n.Buffer.UnsignedShort,stride:32,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:32,offset:8,normalized:!1}),o=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:32,offset:12,normalized:!1}),a=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:32,offset:16,normalized:!1}),l=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.UnsignedByte,stride:32,offset:24,normalized:!0}),c=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.UnsignedByte,stride:32,offset:28,normalized:!0});return new M(e,{a_vec3_vertex:i,a_vec2_offset:r,a_vec2_texcoord:o,a_vec2_check_offset:a,a_vec4_tex_identifier:l,a_vec4_sprite_identifier:c})},Um=(s,e)=>{const i=new n.BufferChannel(s,{itemSize:3,dataType:n.Buffer.UnsignedShort,stride:32,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:32,offset:8,normalized:!1}),o=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.UnsignedByte,stride:32,offset:20,normalized:!0});return new M(e,{a_vec3_vertex:i,a_vec2_offset:r,a_vec4_identifier:o})},vr=(s,e)=>{const t=n.LabelLineGenerator.sinks.raster.stride,i=new n.BufferChannel(s,{itemSize:3,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:t,offset:8,normalized:!1}),o=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Float,stride:t,offset:12,normalized:!1}),a=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Float,stride:t,offset:20,normalized:!1});return new M(e,{a_vec4_position:i,a_vec2_offset:o,a_vec2_texcoord:r,a_vec2_style_zoom_limits:a})},co=(s,e)=>{const t=n.LabelLineGenerator.sinks.billboard.stride,i=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!1}),r=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:t,offset:4,normalized:!1}),o=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:t,offset:8,normalized:!1}),a=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:12,normalized:!1}),l=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Float,stride:t,offset:16,normalized:!1}),c=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.UnsignedByte,stride:t,offset:24,normalized:!0}),d=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:28,normalized:!1});return new M(e,{a_vec2_texcoord:i,a_vec2_anchor_params:r,a_vec2_guideline_params:o,a_float_center_offset:a,a_vec2_corner_offset:l,a_vec4_identifier:c,a_float_glyph_height_offset:d})},dc=(s,e)=>{const t=n.MeshGenerator.sinks.fill.stride,i=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:4,normalized:!1}),o=new n.BufferChannel(s,{itemSize:3,dataType:n.Buffer.Byte,stride:t,offset:8,normalized:!1}),a=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Byte,stride:t,offset:11,normalized:!1}),l=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:t,offset:16,normalized:!1}),c=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:16,normalized:!1}),d=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.UnsignedByte,stride:t,offset:12,normalized:!0}),u=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.UnsignedByte,stride:t,offset:20,normalized:!1}),h=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.UnsignedByte,stride:t,offset:28,normalized:!0});return new M(e,{a_vec2_vertex:i,a_float_z:r,a_vec3_normal:o,a_float_gradient:a,a_vec2_dem_position:l,a_float_abs_z:c,a_vec4_identifier:d,a_float_is_pivot:u,a_vec4_color:h})},Mm=(s,e)=>{const t=n.MeshGenerator.sinks.fill.stride,i=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:4,normalized:!1}),o=new n.BufferChannel(s,{itemSize:3,dataType:n.Buffer.Byte,stride:t,offset:8,normalized:!1}),a=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Byte,stride:t,offset:11,normalized:!1}),l=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:t,offset:16,normalized:!1}),c=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:16,normalized:!1}),d=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.UnsignedByte,stride:t,offset:20,normalized:!1}),u=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.UnsignedByte,stride:t,offset:24,normalized:!0});return new M(e,{a_vec2_vertex:i,a_float_z:r,a_vec3_normal:o,a_float_gradient:a,a_vec2_dem_position:l,a_float_abs_z:c,a_vec4_identifier:u,a_float_is_pivot:d})},uc=(s,e)=>{const t=n.MeshGenerator.sinks.fill.stride,i=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:4,normalized:!1}),o=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:t,offset:16,normalized:!1}),a=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:16,normalized:!1}),l=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.UnsignedByte,stride:t,offset:20,normalized:!1});return new M(e,{a_vec2_vertex:i,a_float_z:r,a_vec2_dem_position:o,a_float_abs_z:a,a_float_is_pivot:l})},gr=(s,e)=>{const t=n.MeshGenerator.sinks.inverse.stride,i=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:4,normalized:!1}),o=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:t,offset:8,normalized:!1}),a=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:8,normalized:!1}),l=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.UnsignedByte,stride:t,offset:12,normalized:!1}),c=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.UnsignedByte,stride:t,offset:16,normalized:!0});return new M(e,{a_vec2_vertex:i,a_float_z:r,a_vec2_dem_position:o,a_float_abs_z:a,a_float_is_pivot:l,a_vec4_identifier:c})},Hm=(s,e)=>{const t=n.MeshGenerator.sinks.depthClear.stride,i=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:4,normalized:!1}),o=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:t,offset:8,normalized:!1}),a=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:8,normalized:!1}),l=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.UnsignedByte,stride:t,offset:12,normalized:!1});return new M(e,{a_vec2_vertex:i,a_float_z:r,a_vec2_dem_position:o,a_float_abs_z:a,a_float_is_pivot:l})},Gm=(s,e)=>{const t=n.MeshGenerator.sinks.stroke.stride,i=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:4,normalized:!1}),o=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.Byte,stride:t,offset:8,normalized:!1}),a=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:t,offset:12,normalized:!1}),l=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:12,normalized:!1}),c=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.UnsignedByte,stride:t,offset:16,normalized:!1});return new M(e,{a_vec2_vertex:i,a_float_z:r,a_vec4_direction_distance:o,a_vec2_dem_position:a,a_float_abs_z:l,a_float_is_pivot:c})},hc=(s,e)=>{const t=n.PolygonExtrusionGenerator.sinks.sideFill.stride,i=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:4,normalized:!1}),o=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:t,offset:12,normalized:!1}),a=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:24,normalized:!1}),l=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.UnsignedByte,stride:t,offset:20,normalized:!0});return new M(e,{a_vec2_vertex:i,a_float_z:r,a_vec2_dem_position:o,a_vec4_color:l,a_float_elevation:a})},Vm=(s,e)=>{const t=n.PolygonExtrusionGenerator.sinks.sideTexture.stride,i=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:4,normalized:!1}),o=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:t,offset:8,normalized:!1}),a=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Float,stride:t,offset:12,normalized:!1}),l=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedByte,stride:t,offset:20,normalized:!1}),c=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.UnsignedByte,stride:t,offset:24,normalized:!0});return new M(e,{a_vec2_vertex:i,a_float_z:r,a_vec2_dem_position:o,a_vec2_wall_size:a,a_vec2_quad_fraction:l,a_vec4_color:c})},_c=(s,e)=>{const t=n.PolygonExtrusionGenerator.sinks.topFill.stride,i=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:4,normalized:!1}),o=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:t,offset:12,normalized:!1}),a=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.UnsignedByte,stride:t,offset:20,normalized:!0});return new M(e,{a_vec2_vertex:i,a_float_z:r,a_vec2_dem_position:o,a_vec4_color:a})},fc=s=>(e,t)=>{const i=new n.BufferChannel(e,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:s,offset:0,normalized:!0}),r=new n.BufferChannel(e,{itemSize:1,dataType:n.Buffer.Float,stride:s,offset:4,normalized:!1}),o=new n.BufferChannel(e,{itemSize:4,dataType:n.Buffer.UnsignedByte,stride:s,offset:8,normalized:!0}),a=new n.BufferChannel(e,{itemSize:2,dataType:n.Buffer.Short,stride:s,offset:12,normalized:!1});return new M(t,{a_vec2_vertex:i,a_float_z:r,a_vec4_identifier:o,a_vec2_dem_position:a})},mc=s=>(e,t)=>{const i=new n.BufferChannel(e,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:s,offset:0,normalized:!0}),r=new n.BufferChannel(e,{itemSize:1,dataType:n.Buffer.Float,stride:s,offset:4,normalized:!1}),o=new n.BufferChannel(e,{itemSize:2,dataType:n.Buffer.Short,stride:s,offset:12,normalized:!1}),a=new n.BufferChannel(e,{itemSize:4,dataType:n.Buffer.UnsignedByte,stride:s,offset:16,normalized:!0});return new M(t,{a_vec2_vertex:i,a_float_z:r,a_vec4_identifier:a,a_vec2_dem_position:o})},vc=s=>(e,t)=>{const i=new n.BufferChannel(e,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:s,offset:0,normalized:!0}),r=new n.BufferChannel(e,{itemSize:1,dataType:n.Buffer.Float,stride:s,offset:4,normalized:!1}),o=new n.BufferChannel(e,{itemSize:2,dataType:n.Buffer.Short,stride:s,offset:12,normalized:!1});return new M(t,{a_vec2_vertex:i,a_float_z:r,a_vec2_dem_position:o})},Zm=(s,e)=>{const t=n.LineExtrusionGenerator.sinks.fill.stride,i=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:4,normalized:!1}),o=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:t,offset:8,normalized:!1}),a=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.UnsignedByte,stride:t,offset:12,normalized:!0});return new M(e,{a_vec2_vertex:i,a_float_z:r,a_vec2_dem_position:o,a_vec4_color:a})},Wm=(s,e)=>{const t=n.LineExtrusionGenerator.sinks.fill.stride,i=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:4,normalized:!1}),o=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:t,offset:8,normalized:!1});return new M(e,{a_vec2_vertex:i,a_float_z:r,a_vec2_dem_position:o})},gc=(s,e)=>{const i=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:24,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:24,offset:4,normalized:!1}),o=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Byte,stride:24,offset:8,normalized:!1}),a=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Byte,stride:24,offset:10,normalized:!1}),l=new n.BufferChannel(s,{itemSize:3,dataType:n.Buffer.Byte,stride:24,offset:12,normalized:!1}),c=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Byte,stride:24,offset:15,normalized:!1}),d=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:24,offset:16,normalized:!1}),u=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.UnsignedByte,stride:24,offset:20,normalized:!0});return new M(e,{a_vec3_vertex:i,a_float_z:r,a_vec2_normal:o,a_vec2_normal_delta:a,a_vec3_direction:l,a_float_distance:c,a_vec2_dem_position:d,a_vec4_color:u})},jm=(s,e)=>{const i=new n.BufferChannel(s,{itemSize:3,dataType:n.Buffer.UnsignedShort,stride:36,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:36,offset:8,normalized:!1}),o=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:36,offset:12,normalized:!1}),a=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:36,offset:16,normalized:!1}),l=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:36,offset:20,normalized:!1}),c=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.UnsignedByte,stride:36,offset:28,normalized:!0});return new M(e,{a_vec3_vertex:i,a_vec2_offset:r,a_vec2_texcoord:o,a_vec2_range:a,a_vec2_check_offset:l,a_vec4_tex_identifier:c})},Xm=(s,e)=>{const i=new n.BufferChannel(s,{itemSize:3,dataType:n.Buffer.UnsignedShort,stride:36,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:36,offset:8,normalized:!1}),o=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:36,offset:12,normalized:!1}),a=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:36,offset:16,normalized:!1}),l=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.UnsignedByte,stride:36,offset:32,normalized:!0});return new M(e,{a_vec3_vertex:i,a_vec2_offset:r,a_vec2_texcoord:o,a_vec2_range:a,a_vec4_identifier:l})},$m=(s,e)=>{const i=new n.BufferChannel(s,{itemSize:3,dataType:n.Buffer.UnsignedShort,stride:36,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:36,offset:8,normalized:!1}),o=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:36,offset:12,normalized:!1}),a=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:36,offset:16,normalized:!1}),l=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.UnsignedByte,stride:36,offset:24,normalized:!0});return new M(e,{a_vec3_vertex:i,a_vec2_offset:r,a_vec2_texcoord:o,a_vec2_range:a,a_vec4_identifier:l})},qm=(s,e)=>{const i=new n.BufferChannel(s,{itemSize:3,dataType:n.Buffer.UnsignedShort,stride:16,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:16,offset:8,normalized:!1}),o=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.UnsignedByte,stride:16,offset:12,normalized:!0});return new M(e,{a_vec4_position:i,a_vec2_offset:r,a_vec4_identifier:o})},pc=(s,e)=>{const t=n.OneWayLineGenerator.sinks.raster.stride,i=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Byte,stride:t,offset:8,normalized:!1}),o=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Byte,stride:t,offset:10,normalized:!1});return new M(e,{a_vec2_position:i,a_vec2_direction:r,a_vec2_widen_direction:o})},xc=(s,e)=>{const t=n.OneWayLineGenerator.sinks.billboard.stride,i=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:4,normalized:!1}),o=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:8,normalized:!1}),a=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Byte,stride:t,offset:12,normalized:!1}),l=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Byte,stride:t,offset:14,normalized:!1}),c=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.UnsignedByte,stride:t,offset:16,normalized:!0});return new M(e,{a_vec2_position:i,a_float_z:r,a_float_abs_z:o,a_vec2_direction:a,a_vec2_widen_direction:l,a_vec4_identifier:c})},Ym=(s,e)=>{const t=n.BuildingModelGenerator.sinks.fill.stride,i=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:4,normalized:!1}),o=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:t,offset:8,normalized:!1}),a=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:t,offset:16,normalized:!1});return new M(e,{a_vec2_vertex:i,a_float_z:r,a_vec2_texcoord:o,a_vec2_dem_position:a})},Qm=(s,e)=>{const t=n.BuildingModelGenerator.sinks.fill.stride,i=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:4,normalized:!1}),o=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.UnsignedByte,stride:t,offset:12,normalized:!0}),a=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:t,offset:16,normalized:!1});return new M(e,{a_vec2_vertex:i,a_float_z:r,a_vec4_identifier:o,a_vec2_dem_position:a})},Jm=(s,e)=>{const t=n.BuildingModelGenerator.sinks.fill.stride,i=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:4,normalized:!1}),o=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:t,offset:16,normalized:!1}),a=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.UnsignedByte,stride:t,offset:20,normalized:!0});return new M(e,{a_vec2_vertex:i,a_float_z:r,a_vec4_identifier:a,a_vec2_dem_position:o})},Km=(s,e)=>{const t=n.BuildingModelGenerator.sinks.fill.stride,i=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:4,normalized:!1}),o=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:t,offset:16,normalized:!1});return new M(e,{a_vec2_vertex:i,a_float_z:r,a_vec2_dem_position:o})},ev=(s,e)=>{const t=n.PolygonGenerator.sinks.stroke.stride,i=new n.BufferChannel(s,{itemSize:3,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.Byte,stride:t,offset:8,normalized:!1});return new M(e,{a_vec3_vertex:i,a_vec4_direction_distance:r})},uo=(s,e)=>{const i=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:20,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:20,offset:4,normalized:!1}),o=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.Byte,stride:20,offset:8,normalized:!1}),a=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:20,offset:12,normalized:!1}),l=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.UnsignedByte,stride:20,offset:16,normalized:!0});return new M(e,{a_vec2_vertex:i,a_float_z:r,a_vec4_direction_distance:o,a_vec2_dem_position:a,a_vec4_color:l})},bc=(s,e)=>{const i=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:36,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:36,offset:4,normalized:!0}),o=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.Byte,stride:36,offset:8,normalized:!1}),a=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:36,offset:12,normalized:!1}),l=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:36,offset:16,normalized:!1}),c=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:36,offset:20,normalized:!1}),d=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:36,offset:24,normalized:!1}),u=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:36,offset:28,normalized:!1}),h=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.UnsignedByte,stride:36,offset:32,normalized:!0});return new M(e,{a_vec2_vertex:i,a_vec2_segment_end:r,a_vec4_texture_widen_arrow_widen:o,a_vec2_widen:a,a_vec2_direction:l,a_float_distance_from_start:c,a_float_object_length:d,a_float_type:u,a_vec4_identifier:h})},ho=(s,e)=>{const t=n.CircleMarkerGenerator.sinks.fill.stride,i=new n.BufferChannel(s,{itemSize:3,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:t,offset:8,normalized:!1});return new M(e,{a_vec3_vertex:i,a_vec2_widen:r})},tv=(s,e)=>{const t=n.CircleMarkerGenerator.sinks.fill.stride,i=new n.BufferChannel(s,{itemSize:3,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:t,offset:8,normalized:!1}),o=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.UnsignedByte,stride:t,offset:12,normalized:!0});return new M(e,{a_vec3_vertex:i,a_vec2_widen:r,a_vec4_identifier:o})},iv=(s,e)=>{const t=n.RasterGenerator.sinks.fill.stride,i=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:t,offset:4,normalized:!1});return new M(e,{a_vec2_vertex:i,a_vec2_texcoord:r})},nv=(s,e)=>{const t=n.HeatmapGenerator.sinks.framebuffer.stride,i=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:4,normalized:!1}),o=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Byte,stride:t,offset:8,normalized:!1});return new M(e,{a_vec2_position:i,a_vec2_widen:o,a_float_weight:r})},rv=(s,e)=>{const t=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Float,stride:0,offset:0,normalized:!1});return new M(e,{a_vec2_position:t})},Sc=(s,e)=>{const i=new n.BufferChannel(s,{itemSize:3,dataType:n.Buffer.Float,stride:12,offset:0});return new M(e,{a_vec3_position:i})},pr=(s,e)=>new M(e,{a_vec2_position:s}),qi=(s,e)=>{const t=n.DemGenerator.sinks.mesh2.stride,i=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:4,normalized:!1});return new M(e,{a_vec2_vertex:i,a_float_height:r})},sv=(s,e)=>{const t=n.DemGenerator.sinks.flatBottom.stride,i=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:t,offset:4,normalized:!1}),o=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Byte,stride:t,offset:8,normalized:!0});return new M(e,{a_vec2_vertex:i,a_vec2_centroid:r,a_vec2_extender:o})},_o=(s,e)=>{const t=n.DemGenerator.sinks.hillshade.stride,i=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:t,offset:4,normalized:!1});return new M(e,{a_vec2_vertex:i,a_vec2_texcoord:r})},xr=s=>(e,t,i,r)=>{const o=n.GltfModelGenerator.sinks.instances.stride,a=new n.BufferChannel(e,{itemSize:3,dataType:n.Buffer.UnsignedShort,stride:o,offset:0,normalized:!0,instanceDivisor:1}),l=new n.BufferChannel(e,{itemSize:9,dataType:n.Buffer.Float,stride:o,offset:8,instanceDivisor:1}),c=new n.BufferChannel(e,{itemSize:1,dataType:n.Buffer.Float,stride:o,offset:44,normalized:!1,instanceDivisor:1}),d=new n.BufferChannel(e,{itemSize:1,dataType:n.Buffer.Float,stride:o,offset:48,normalized:!1,instanceDivisor:1}),u=new n.BufferChannel(e,{itemSize:4,dataType:n.Buffer.UnsignedByte,stride:o,offset:s?56:52,normalized:!0,instanceDivisor:1});return new M(t,I({a_vec3_instance_position:a,a_float_instance_height:d,a_mat3_instance_matrix:l,a_vec4_instance_localid:u,a_float_abs_z:c},r),i)},fo=(s,e)=>{const t=n.MapMeshGenerator.sinks.fill.stride,i=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:t,offset:0,normalized:!0}),r=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:4,normalized:!1}),o=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:t,offset:8,normalized:!1}),a=new n.BufferChannel(s,{itemSize:3,dataType:n.Buffer.Byte,stride:t,offset:12,normalized:!1}),l=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Byte,stride:t,offset:15,normalized:!1}),c=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Short,stride:t,offset:16,normalized:!1}),d=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:t,offset:n.MAP_MESH_ABS_Z_BYTE_OFFSET,normalized:!1}),u=new n.BufferChannel(s,{itemSize:4,dataType:n.Buffer.UnsignedByte,stride:t,offset:20,normalized:!0}),h=new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.UnsignedByte,stride:t,offset:n.MAP_MESH_IS_PIVOT_BYTE_OFFSET,normalized:!1});return new M(e,{a_vec2_vertex:i,a_float_z:r,a_vec2_extender:o,a_vec3_normal:a,a_float_gradient:l,a_vec2_dem_position:c,a_float_abs_z:d,a_vec4_identifier:u,a_float_is_pivot:h})},ov=(s,e)=>{const t=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Float,stride:0,offset:0,normalized:!1});return new M(e,{a_vec2_vertex:t})},_i=(s,e)=>{const t=new n.BufferChannel(s,{itemSize:2,dataType:n.Buffer.Byte,stride:0,offset:0,normalized:!1});return new M(e,{a_vec2_vertex:t})},av=(s,e)=>new M(e,{a_vec3_position:new n.BufferChannel(s,{itemSize:3,dataType:n.Buffer.Float,stride:16,offset:0,normalized:!0}),a_fade_opacity:new n.BufferChannel(s,{itemSize:1,dataType:n.Buffer.Float,stride:16,offset:12,normalized:!1})}),Yi=32,yc=1/0,lv="raster";class Tc extends n.TileObjectBase{constructor(e,t,i){var o;super(lv),this.children=[],this.identifyChildren=[];const r=this;this.setTileCoords(e,t.map.state),(o=t.renderer.symbolSettingsList.dem.mesh)==null||o.forEach(a=>{const l={id:n.uniqId(),type:n.SceneObjectType.Tile,symbol:"dem",sink:"mesh",tile:this,attributes:{layerId:n.DEM_STYLE_LAYER_ID,styleId:t.map.state.handyStyleId,tileData:[]},start:0,count:Yi*Yi*6,attributesHash:"",layerSettings:a,vao:i.mesh,canRender:!0,renderingProperties:{flatTexture:null,hillshadeTexture:null,flatIdentifyTexture:null}};a.identify?r.identifyChildren.push(l):a.depthTest?r.depthTestChildren.push(l):a.shadow?r.shadowChildren.push(l):a.dem?r.demChildren.push(l):a.demGround?r.demGroundChildren.push(l):r.children.push(l)})}setTileCoords(e,t){const i=e[2],r=e[3],o=n.tileZoomToSize(i);this.coords=e,this.size=o,this.zoomLevel=i,this.detailLevel=r,this.mvpMatrices.clear(),this.demMatrices.clear(),this.flatMapTexMatrices.clear(),this.syncReplicas(t)}syncReplicas({visibleMapReplicas:e}){const t=Math.pow(2,this.coords[2]),i=this.size/Yi;this.bounds.clear(),this.modelMatrices.clear(),e.forEach(r=>{const o=[this.coords[0]+r*t,this.coords[1],this.coords[2],this.coords[3]],a=n.tileCoordsToMapPoint(o);a[0]-=i,a[1]-=i,this.bounds.set(r,{min:[a[0],a[1]],max:[a[0]+this.size,a[1]+this.size]});const l=n.create$2();n.fromTranslationScale(l,a,n.fromValues(this.size+i,this.size+i,n.tileHeight)),this.modelMatrices.set(r,l)}),this.needSync=!1}}class cv{constructor(e,t){var o;this.meshTiles=new Map,this.destroyed=!1,this.modules=e.modules,this.maxZoom=(o=t==null?void 0:t.maxZoom)!=null?o:yc;const i=[];for(let a=0;a<Yi;a++)for(let l=0;l<Yi;l++)i.push(l,a,l+1,a,l,a+1),i.push(l,a+1,l+1,a,l+1,a+1);const r=n.maxUint16Value/Yi;for(let a=0;a<i.length;a++)i[a]*=r;this.buffer=this.modules.renderer.createBuffer(new Uint16Array(i),{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:0,offset:0,normalized:!0}),this.buffer.drawType=n.Buffer.StaticDraw,this.vaos={mesh:pr(this.buffer,this.modules.renderer.getShaderProgram("demMesh"))},this.update()}destroy(){this.destroyed||(this.meshTiles=new Map,Object.values(this.vaos).forEach(e=>{e.unbind(),e.remove()}),this.buffer.remove(),this.destroyed=!0)}setMaxZoom(e=yc){e!==this.maxZoom&&(this.maxZoom=e,this.update())}update(){if(this.destroyed)return;const e=this.modules.map.state;e.needReplicasUpdate&&this.meshTiles.forEach(o=>{o.needSync=!0});const t=Math.trunc(e.styleZoom),i=Math.min(t,Math.min(this.maxZoom,t)),r=n.findVisibleTiles(this.modules.map.state,this.modules,i,0,i,void 0,void 0,void 0,!0).reduce((o,a)=>(o.set(n.coordsToKey(a),a),o),new Map);this.meshTiles.forEach((o,a)=>{r.has(a)||this.meshTiles.delete(a)}),r.forEach((o,a)=>{this.meshTiles.has(a)||this.meshTiles.set(a,new Tc(o,this.modules,this.vaos))})}updateStyleId(){this.meshTiles.forEach(e=>this.updateTileStyleId(e))}updateTileStyleId(e){e.children.forEach(t=>{t.attributes.styleId=this.modules.map.state.handyStyleId}),e.identifyChildren.forEach(t=>{t.attributes.styleId=this.modules.map.state.handyStyleId}),e.depthTestChildren.forEach(t=>{t.attributes.styleId=this.modules.map.state.handyStyleId}),e.shadowChildren.forEach(t=>{t.attributes.styleId=this.modules.map.state.handyStyleId}),e.demChildren.forEach(t=>{t.attributes.styleId=this.modules.map.state.handyStyleId}),e.demGroundChildren.forEach(t=>{t.attributes.styleId=this.modules.map.state.handyStyleId})}}class dv{constructor(e,t,i){this.id=e,this.modules=t,this.options=i,this.type="dem",this.tree=n.rbush(n.DEM_TREE_SIZE),this.tileSize=n.DEM_ELEVATION_TILE_SIZE,this.minElevation=0,this.revision=0,this.tileLoader=new n.BaseTileLoader("arrayBuffer"),this.attributes={},this.tiles=new Map,this.textureIndices=new Map,this.url=r=>{const[o,a,l]=n.tileCoordsToOSM(r);return this.options.url(o,a,l)}}abortTileFetches(e){this.tileLoader.abortRequests(e.map(n.coordsToKey))}deleteTiles(e){for(const t of e){const i=n.coordsToKey(t);if(this.tiles.get(i)){const o=n.getTileBounds(t);this.tree.remove({minX:o.min[0],minY:o.min[1],maxX:o.max[0],maxY:o.max[1]},(a,l)=>i===l.key),this.updateRevision()}this.tiles.delete(i);const r=this.textureIndices.get(i);r!==void 0&&this.modules.imageManager.deleteTexture(r),this.updateMinElevation()}}fetchTiles(e){return e.map(t=>this.fetchTile(t))}generateTile(e,t){return q(this,null,function*(){const i=[],r=[],o=n.coordsToKey(t),a=this.tiles.get(o);if(!a)return Promise.resolve({results:i,transferable:r});const l=this.modules.map.state.handyStyleId,{collector:c}=this.modules,d=n.tileZoomToSize(t[2]),u=a.bounds;this.tree.insert(V(I({key:o,minX:u.min[0],minY:u.min[1],maxX:u.max[0],maxY:u.max[1],cellSize:d/n.DEM_ELEVATION_TILE_SIZE},a),{tree:null,bounds:u,generated:i,empty:!1})),this.updateMinElevation(),this.updateRevision();do n.DemGenerator.generateMeshElevation(c,a.mesh,l,n.DEM_STYLE_LAYER_ID);while(c.isOverloaded());const h=c.getAccumulatedData();return i.push({regionId:0,metatileHash:-1,styleId:l,collectorOutput:h}),r.push(...h.transferable),Promise.resolve({results:i,transferable:r})})}unpackRaw(e,t){const[i,r,o,a]=t,l=new Uint8Array(e),c=new Float32Array(Re(this.tileSize,2));let d=1/0,u=-1/0;const h=this.tileSize;for(let f=0;f<h;f++){const m=n.Mercator.toGeo(n.tileCoordsToMapPoint([i,r+f*(1/n.DEM_ELEVATION_TILE_SIZE),o,a])),v=n.Mercator.scaleFactor(m[1]);for(let g=0;g<h;g++){const p=g+f*h,x=(l[p]+l[Re(h,2)+p]*256-1e4)*v;d=Math.min(x,d),u=Math.max(x,u),c[p]=x}}const _=this.getMesh(c);return{data:c,mesh:_,minZ:d,maxZ:u,bounds:{min:n.tileCoordsToMapPoint(t),max:n.tileCoordsToMapPoint([i+1,r+1,o,a])}}}getAttributes(){return this.attributes}setAttributes(e){this.attributes=e}getId(){return this.id}destroy(){const{imageManager:e}=this.modules;this.tileLoader.destroy(),this.tiles.clear(),this.tree.clear(),this.textureIndices.forEach(t=>e.deleteTexture(t)),this.textureIndices.clear()}getElevation(e){const t=this.getElevationTile(e);if(t)return n.getElevationFromTile(t,e)}getElevationTile(e){const t=n.normalizeMapPoint(e);return this.tree.search({minX:t[0],minY:t[1],maxX:t[0],maxY:t[1]}).reduce((r,o)=>!r||r.cellSize>o.cellSize?o:r,void 0)}getMinElevation(){return this.minElevation}updateMinElevation(){const e=this.modules.map.state;if(!e.demMode)return;const t=this.modules.camera.position[2],i=n.tetragonBounds(e.tilesBounds);if(e.elevation!==void 0){const o=e.elevation*n.MAP_POINTS_IN_METER/t+1,a=Math.max(e.pitch/e.maxPitch*30,4);n.scale$1(i,Math.min(o,a))}const r=this.tree.search({minX:i.min[0],minY:i.min[1],maxX:i.max[0],maxY:i.max[1]});e.styleZoom-Vo>1?this.minElevation=r.reduce((o,a)=>{if(a.data){const l=n.intersection(i,a.bounds);n.sub(l.min,l.min,a.bounds.min),n.sub(l.max,l.max,a.bounds.min),n.scale$2(l.min,l.min,1/a.cellSize),n.scale$2(l.max,l.max,1/a.cellSize);for(let c=Math.trunc(l.min[0]);c<l.max[0];c++)for(let d=Math.trunc(l.min[1]);d<l.max[1];d++){const u=c+(n.DEM_ELEVATION_TILE_SIZE-1-d)*n.DEM_ELEVATION_TILE_SIZE,h=a.data[u];o=o===void 0?h:Math.min(o,h)}}return o},void 0):this.minElevation=r.reduce((o,a)=>o===void 0?a.minZ:Math.min(o,a.minZ),void 0)}getRevision(){return this.revision}fetchTile(e){const t=n.coordsToKey(e),i=[{regionId:0,metatileHash:-1}];if(this.tiles.has(t))return Promise.resolve(i);const r=this.url(e);return this.tileLoader.fetch(e,()=>r).then(o=>(o.rejected||this.tiles.set(t,o.data&&o.data.byteLength?this.unpackRaw(o.data,e):void 0),i),()=>Promise.resolve(void 0))}updateRevision(){this.revision++}getMesh(e){const t=this.tileSize,i=t*t,r=new Uint16Array(i*2),o=new Uint16Array(i*6);let a=0;for(let l=0;l<t;l++)for(let c=0;c<t;c++){const d=l*t+c;r[2*d+0]=c/(t-1)*n.maxTilePoint,r[2*d+1]=(1-l/(t-1))*n.maxTilePoint,c<t-1&&l<t-1&&(o[a++]=d+1,o[a++]=d,o[a++]=d+t,o[a++]=d+1,o[a++]=d+t,o[a++]=d+t+1)}return{positions:r,heights:e,indices:o}}}class Ec{constructor(e,t,i){this.id=e,this.modules=t,this.options=i,this.type="dem",this.worker=new t.workers.parser.MeshElevationSource(this.options),this.attributes={},this.tiles=new Map}isTileEmpty(e){const t=this.tiles.get(e);return t?t.empty:!1}abortTileFetches(e){this.worker.abortTileFetches(e)}deleteTiles(e){this.worker.deleteTiles(e);for(const t of e){const i=n.coordsToKey(t);this.tiles.get(i)&&(this.modules.elevationIndex.unregister(this.id,i),this.tiles.delete(i))}this.updateMinElevation()}fetchTiles(e){return this.worker.fetchTiles(e)}generateTile(e,t){return q(this,null,function*(){const i=n.coordsToKey(t),{tree:r,results:o,minZ:a,maxZ:l,empty:c}=yield this.worker.generateTile(e.handyStyleId,t),d=n.getTileBounds(t),u={generated:o,key:i,minX:d.min[0],minY:d.min[1],maxX:d.max[0],maxY:d.max[1],cellSize:n.tileZoomToSize(t[2])/n.DEM_ELEVATION_TILE_SIZE,bounds:d,minZ:a,maxZ:l,tree:r,empty:c};this.tiles.set(i,u);const h={sourceId:this.id,key:i,tileCoords:t,kind:"dem",tree:r,generated:o,vertexStride:n.DemGenerator.sinks.mesh2.stride,heightOffset:4,bucketSink:"mesh2",cellSize:u.cellSize,minZ:a,maxZ:l,minX:u.minX,minY:u.minY,maxX:u.maxX,maxY:u.maxY};return this.modules.elevationIndex.register(h),this.updateMinElevation(),{results:o}})}getAttributes(){return this.attributes}setAttributes(e){this.attributes=e}getId(){return this.id}destroy(){for(const e of this.tiles.keys())this.modules.elevationIndex.unregister(this.id,e);this.tiles.clear()}getElevation(e){return this.modules.elevationIndex.getElevation(e)}getElevationTile(e){const t=this.modules.elevationIndex.getElevationTile(e,"dem");return t?this.tiles.get(n.coordsToKey(t.tileCoords)):void 0}getMinElevation(){return this.modules.elevationIndex.getMinElevation()}updateMinElevation(){const e=this.modules.map.state;if(!e.demMode)return;const t=n.tetragonBounds(e.tilesBounds);this.modules.elevationIndex.updateMinElevation(t)}getRevision(){return this.modules.elevationIndex.getDemRevision()}}const at=new Float64Array(16);class mo{constructor(e,t,i){this.detailLevel=0,this.mvpMatrix=new Float64Array(16),this.texMatrix=new Float64Array(16),n.copy(this.mvpMatrix,e),n.multiply(this.texMatrix,n.WEBGL_COORDS_TO_TEXTURE,e),this.detailLevel=i,this.viewport=[[0,0,0,1],[1,0,0,1],[1,1,0,1],[0,1,0,1]],n.invert(at,this.texMatrix),this.viewport.forEach(r=>{n.transformMat4$1(r,r,at),r[0]-=t[0],r[1]-=t[1],r[2]-=t[2],r[2]>=0&&(r[2]=-1),n.normalize(r,r);const o=-t[2]/r[2];r[0]=t[0]+r[0]*o,r[1]=t[1]+r[1]*o,r[2]=t[2]+r[2]*o})}}class uv{constructor(e){this.destroyed=!1,this.modules=e.modules,this.textures=[]}update(){if(this.destroyed)return;const{center:e,padding:t,rotation:i,size:r,viewport:o,extendedTilesBounds:a,zoom:l,cameraConfig:c,globeMode:d}=this.modules.map.state,u=n.getLineConstants(a[0],a[1]),h=n.pointToLineDistance(a[2],u);this.textures=[];const _=n.degToRad(45),f=Math.min(this.modules.map.state.pitch,_),m=new n.Camera({pitch:f,center:e,padding:t,rotation:i,size:r,viewport:o,zoom:l,cameraConfig:c,globeMode:d,styleState:{}}),v=n.clamp(Math.pow(this.modules.map.state.pitch/_,3),0,1),[g,p]=this.modules.camera.position,x=n.transformMat4([],[g,p,0,1],m.viewProjectionMatrix),S=Math.min(x[1]/x[3]+1,-.5);let b=Math.max(S,-1);if(n.fromTranslationScale(at,[0,-b,0],[1/je[0],1/je[1],1]),n.multiply(at,at,m.viewProjectionMatrix),this.textures.push(new mo(at,m.position,0)),n.pointToLineDistance(this.textures[0].viewport[2],u)>=h)return!0;if(S<b){const y=Math.max(Math.abs(S-b)/2,1);n.fromTranslationScale(at,[0,2/y+1,0],[1/je[0],je[1]/y,1]),n.multiply(at,at,m.viewProjectionMatrix),this.textures.push(new mo(at,m.position,1))}b+=1;const T=Math.pow(r[1]/749,2);[1.4,3.2,12,31].some((y,E)=>{y=(y-1)*v*T+1,n.fromTranslationScale(at,[0,-(b*y+1),0],[1/je[0],y/je[1],1]),n.multiply(at,at,m.viewProjectionMatrix),b+=2/y;const P=this.textures.push(new mo(at,m.position,E));if(n.pointToLineDistance(this.textures[P-1].viewport[2],u)>=h)return!0})}destroy(){this.textures=[]}}const Cc={depthMask:!0,depthTest:!0,depthFunc:n.DEPTH_FUNC.LESS,cullFace:!0,cullFaceMode:n.CULL_FACE_MODE.BACK,blend:!1,blendFunc:{sfactor:n.BLEND_FUNC.ONE,dfactor:n.BLEND_FUNC.ZERO},blendEquation:n.BLEND_EQUATION.FUNC_ADD,colorMask:[!0,!0,!0,!0],polygonOffsetFill:!1,polygonOffset:{factor:1,units:2}},de=s=>{const e=Object.assign({},Cc,s);return()=>e};function Ic(s,e){const{_activeFloorIsMetro:t}=s.map.getStyleState();return!!(t&&(e!=null&&e.attributes.floorId))}const Fe=de({}),vo=de({blend:!0,blendFunc:{sfactor:n.BLEND_FUNC.ONE,dfactor:n.BLEND_FUNC.ONE_MINUS_SRC_ALPHA}}),hv=de({blend:!0,blendFunc:{sfactor:n.BLEND_FUNC.ONE,dfactor:n.BLEND_FUNC.ONE_MINUS_SRC_ALPHA},depthFunc:n.DEPTH_FUNC.GREATER,depthMask:!1,cullFace:!1,polygonOffsetFill:!0,polygonOffset:{factor:1,units:2}}),Ri=de({depthMask:!1,blend:!0,blendFunc:{sfactor:n.BLEND_FUNC.ONE,dfactor:n.BLEND_FUNC.ONE_MINUS_SRC_ALPHA}}),Pc=de({blend:!0,blendFunc:{sfactor:n.BLEND_FUNC.ONE,dfactor:n.BLEND_FUNC.ONE_MINUS_SRC_ALPHA},cullFace:!1}),qe=de({depthMask:!1,depthTest:!1,blend:!0,blendFunc:{sfactor:n.BLEND_FUNC.ONE,dfactor:n.BLEND_FUNC.ONE_MINUS_SRC_ALPHA}}),_v=de({depthMask:!1,depthTest:!0,blend:!0,blendFunc:{sfactor:n.BLEND_FUNC.ONE,dfactor:n.BLEND_FUNC.ONE_MINUS_SRC_ALPHA}}),br=(s,e)=>Ic(s,e)?_v(s):qe(s),fv=de({depthMask:!1,depthTest:!1,blend:!0,blendFunc:{sfactor:n.BLEND_FUNC.ONE,dfactor:n.BLEND_FUNC.ONE_MINUS_SRC_ALPHA},blendEquation:n.BLEND_EQUATION.MAX}),mv=de({depthMask:!1,depthTest:!1,blend:!0,blendFunc:{sfactor:n.BLEND_FUNC.SRC_ALPHA,dfactor:n.BLEND_FUNC.ONE}}),Ac=de({depthMask:!1,depthTest:!1,colorMask:[!0,!1,!1,!0]}),vv=de({depthMask:!1,depthTest:!1}),si=de({depthMask:!1,depthTest:!1}),gv=de({depthMask:!1,depthTest:!0}),go=(s,e)=>Ic(s,e)?gv(s):si(s),po=de({depthMask:!1}),Sr=de({colorMask:[!1,!1,!1,!1]}),Lc={polygonOffsetFill:!0,polygonOffset:{factor:1,units:3}};function Rc(s){const e=s==null?void 0:s.attributes;return!!(e!=null&&e.floorId)&&!(e!=null&&e.isHole)}const pv=de(I({colorMask:[!1,!1,!1,!1]},Lc)),xv=de(Lc),Fc=(s,e)=>Rc(e)?pv(s):Sr(s),bv=(s,e)=>Rc(e)?xv(s):Fe(s),Sv=de({colorMask:[!1,!1,!1,!1],depthFunc:n.DEPTH_FUNC.ALWAYS}),xo=de({blend:!0,blendFunc:{sfactor:n.BLEND_FUNC.ONE,dfactor:n.BLEND_FUNC.ONE_MINUS_SRC_ALPHA}}),yv=de({depthFunc:n.DEPTH_FUNC.EQUAL,blend:!0,blendFunc:{sfactor:n.BLEND_FUNC.ONE,dfactor:n.BLEND_FUNC.ONE_MINUS_SRC_ALPHA}}),fi=de({depthMask:!1,depthTest:!1,blend:!0,blendFunc:{sfactor:n.BLEND_FUNC.ONE,dfactor:n.BLEND_FUNC.ONE_MINUS_SRC_ALPHA}}),Tn=de({depthMask:!1,depthTest:!0,depthFunc:n.DEPTH_FUNC.LEQUAL,blend:!0,blendFunc:{sfactor:n.BLEND_FUNC.ONE,dfactor:n.BLEND_FUNC.ONE_MINUS_SRC_ALPHA}}),bo=de({depthMask:!1,depthTest:!0,depthFunc:n.DEPTH_FUNC.GREATER,blend:!0,blendFunc:{sfactor:n.BLEND_FUNC.ONE,dfactor:n.BLEND_FUNC.ONE_MINUS_SRC_ALPHA}}),Dc=de({polygonOffsetFill:!0,polygonOffset:{factor:1,units:2},blend:!0,blendFunc:{sfactor:n.BLEND_FUNC.ONE,dfactor:n.BLEND_FUNC.ONE_MINUS_SRC_ALPHA}}),yr=de({cullFaceMode:n.CULL_FACE_MODE.BACK}),En=de({cullFace:!1}),zc=de({depthMask:!1,depthTest:!1,blend:!0,blendFunc:{sfactor:n.BLEND_FUNC.ONE,dfactor:n.BLEND_FUNC.ONE}}),Tv=de({depthTest:!1,cullFace:!1}),Bc=de({depthTest:!1,depthMask:!1,blend:!0,blendFuncSeparate:{srcRgb:n.BLEND_FUNC.SRC_ALPHA,dstRgb:n.BLEND_FUNC.ONE_MINUS_SRC_ALPHA,srcAlpha:n.BLEND_FUNC.ONE,dstAlpha:n.BLEND_FUNC.ONE_MINUS_SRC_ALPHA}}),Oc=de({colorMask:[!0,!0,!0,!0],depthMask:!0}),Ev=de({colorMask:[!0,!0,!0,!0],depthMask:!1}),Cv=de({depthMask:!0,depthTest:!0,depthFunc:n.DEPTH_FUNC.LEQUAL,blend:!0,blendFunc:{sfactor:n.BLEND_FUNC.ONE,dfactor:n.BLEND_FUNC.ONE_MINUS_SRC_ALPHA}}),Iv=de({depthMask:!0,depthTest:!0,depthFunc:n.DEPTH_FUNC.LEQUAL,blend:!0,blendFunc:{sfactor:n.BLEND_FUNC.SRC_ALPHA_SATURATE,dfactor:n.BLEND_FUNC.ONE_MINUS_SRC_COLOR}}),Pv=de({depthMask:!0,depthTest:!0}),So=s=>s.map.getFeatureFlag("transparentBuildingsOff")?Fe(s):yv(s),wc=de({depthFunc:n.DEPTH_FUNC.LEQUAL,depthMask:!1,blend:!0,blendFunc:{sfactor:n.BLEND_FUNC.ONE,dfactor:n.BLEND_FUNC.ONE_MINUS_SRC_ALPHA}}),yo=150;function Av(s,e,t){return!t&&e!==0&&s.immersiveLevel.tiers}class Tr{constructor(e,t,i,r,o,a){var l,c;this.modules=e,this.mapState=t,this.getPosition=i,this.getTier=r,this.hasExplicitZ=o,this.lastSurfaceRevision=-1,this.lastDemRevision=-1,this.lastResolveNeedsAbsoluteZ=!1,this.hasResolved=!1,this.queryCache={},this.lastProbeX=NaN,this.lastProbeY=NaN,this.alwaysRequireAbsoluteZ=(l=a==null?void 0:a.alwaysRequireAbsoluteZ)!=null?l:!1,this.trackPositionChanges=(c=a==null?void 0:a.trackPositionChanges)!=null?c:!1}getResolvedHeight(){if(!this.shouldUseTierHeight())return Nc;const e=this.shouldUseAbsoluteZ();return!this.resolvedHeight||e&&this.resolvedHeight.absoluteZ===void 0?Nc:this.resolvedHeight}shouldUseTierHeight(){return Av(this.mapState,this.getTier(),this.hasExplicitZ())}needsResolve(){if(!this.shouldUseTierHeight())return!1;const e=this.shouldUseAbsoluteZ();return!(this.hasResolved&&(!this.resolvedHeight||!e||this.resolvedHeight.absoluteZ!==void 0)&&!this.isStale(e))}resolve(){if(!this.shouldUseTierHeight())return this.reset(),!1;const e=this.shouldUseAbsoluteZ();if(this.hasResolved&&(!this.resolvedHeight||!e||this.resolvedHeight.absoluteZ!==void 0)&&!this.isStale(e))return!1;const t=this.resolvedHeight,i=this.lastResolveNeedsAbsoluteZ,r=this.hasResolved;if(this.lastSurfaceRevision=this.modules.elevationIndex.getSurfaceRevision(this.getTier()),this.lastDemRevision=this.getNeededDemRevision(e),this.lastResolveNeedsAbsoluteZ=e,this.hasResolved=!0,this.trackPositionChanges){const o=this.getPosition();this.lastProbeX=o[0],this.lastProbeY=o[1]}return this.computeResolvedHeight(e),r&&i!==e||!Lv(t,this.resolvedHeight)}reset(e=!1){const t=this.hasResolved||this.lastSurfaceRevision!==-1||this.lastDemRevision!==-1||this.lastResolveNeedsAbsoluteZ||this.resolvedHeight!==void 0;return this.lastSurfaceRevision=-1,this.lastDemRevision=-1,this.lastResolveNeedsAbsoluteZ=!1,this.hasResolved=!1,this.resolvedHeight=void 0,this.lastProbeX=NaN,this.lastProbeY=NaN,e||(this.queryCache={}),t}shouldUseAbsoluteZ(){return this.alwaysRequireAbsoluteZ||this.mapState.demMode}isStale(e){if(this.modules.elevationIndex.getSurfaceRevision(this.getTier())!==this.lastSurfaceRevision||this.getNeededDemRevision(e)!==this.lastDemRevision||this.lastResolveNeedsAbsoluteZ!==e)return!0;if(this.trackPositionChanges){const t=this.getPosition();if(t[0]!==this.lastProbeX||t[1]!==this.lastProbeY)return!0}return!1}getNeededDemRevision(e){return e?this.modules.elevationIndex.getDemRevision():-1}computeResolvedHeight(e){const t=this.modules.elevationIndex.getElevationAtTier(this.getPosition(),this.getTier(),{includeAbsoluteZ:e,cache:this.queryCache});if(!t){this.resolvedHeight=void 0;return}const i={relativeZ:t.relativeZ*n.MAP_POINTS_IN_METER};t.absoluteZ!==void 0&&(i.absoluteZ=t.absoluteZ*n.MAP_POINTS_IN_METER),this.resolvedHeight=i}}const Nc={};function Lv(s,e){return(s==null?void 0:s.relativeZ)===(e==null?void 0:e.relativeZ)&&(s==null?void 0:s.absoluteZ)===(e==null?void 0:e.absoluteZ)}const kc="#000000",Uc=0,Mc="#ffffff",Hc=0,Er=[0,0],Rv=0,Fv=[0,0,0,0],To=-1;class Cr extends ht{constructor(e,t,i){var L,D,B,Q,Z,$,J,ge,Ce,tt;super(e,{interactive:(L=t.interactive)!=null?L:!1},i),this.hovered=!1,this.lastLabelingRevision=To,this.imageLabelBoxAdjusted=!1,this.generationId=0,this.styleUpdateId=0,this.hasExplicitZ=!1,this.throttledResolveTierData=n.throttle(()=>{if(this.status==="destroyed")return;this.resolveTierData()&&this.modules.renderer.addRerenderEvent()},yo),this.status="visible",this.labelingStatus=0,this.options=t,this.hasExplicitZ=t.coordinates.length===3,this.labelKey=`point-label-${this.uniqId}`;const r=(D=t.font)!=null?D:n.DEFAULT_FONT,o=(B=t.fontSize)!=null?B:n.fonts.baseSize,a=(Q=t.letterSpacing)!=null?Q:Hc,l=(Z=t.lineHeight)!=null?Z:n.fonts.baseLineHeight,c=[(J=($=this.options.offset)==null?void 0:$[0])!=null?J:Er[0],(Ce=(ge=this.options.offset)==null?void 0:ge[1])!=null?Ce:Er[1]],d=this.createTextStyleLayer(`dynamic-pointLabel-${this.uniqId}`,r,o,t.color,t.haloRadius,t.haloColor,a,l,c),u=n.Mercator.fromGeo(this.options.coordinates);if(this.position={userValue:u,normalizedValue:n.normalizeMapPoint(u)},this.tierHeightResolver=new Tr(this.modules,this.mapState,()=>this.position.normalizedValue,()=>{var Ie;return(Ie=this.options.tier)!=null?Ie:0},()=>this.hasExplicitZ),!d)return;const{dynamicStyle:h,collector:_,assetManager:f,styleManager:m,tileManager:v,layers:g,defaultSource:p}=this.modules,x=(tt=this.options.zIndex)!=null?tt:Rv;h.addLayer(d,x);const S=n.optionsToTileAttrs({db_label:this.options.text}),b=n.mapPointTo32ZoomTileCoords(this.position.normalizedValue),T={x:[0],y:[0]},y=n.makeGeneratorContext(this.mapState.styleState,n.emptySourceAttrs,n.fixedMetatile.tileProps,S,n.emptyFeatureAttrs,!0,this.interactive?"0":"");n.runPrecomputes(d,y),n.generateSafely({collector:_,generator:n.preLabelingPoint,args:[h.getStyle(),d,y,n.fixedMetatile,n.LATEST_TILE_VERSION,b,p.getId(),T,n.pixelRatioToDpi(window.devicePixelRatio)]});const E=_.getAccumulatedData();if(!E.labels.length)return;const P=[{metatileHash:-1,labels:E.labels,styleId:h.getStyle().id}],A=n.unpackPreLabelingResult(P,n.LabelSource.DynamicObject,m,this.mapState.styleState,this.mapState.styleZoom,this.mapState.pitch);if(A.length!==1)return;const F=A[0];n.rtlAdapterPromise.then(()=>{var Ie;F.label=(Ie=n.processRTLTextIfNeeded(F.label))!=null?Ie:"",F.updateRanges()}).then(()=>Promise.all(F.ranges.map(Ie=>f.loadFont(r,Ie)))).then(()=>{if(this.status==="destroyed")return;F.textMetrics=n.getTextMetrics(F.label,a,f.getFontGlyphs(r),f.getFontGlyphs(n.DEFAULT_FONT));const{labelHeightInPx:Ie,labelMaxWidthInPx:it,anchorOffset:Xt,elementOffset:$t,anchor:xt}=Vc(o,l,F.textMetrics,t.anchor,c);this.generationState={label:F,styleLayer:d,elementOffset:$t,textFont:r,textOffset:c,anchorOffset:Xt,labelMaxWidthInPx:it,labelHeightInPx:Ie,asEcef:ye(this.mapState)};const Ze=this.generateTextTileObject(this.generationState);if(g.addLayer(this),this.interactive&&(this.identifyIds.push(E.identifyIds),this.modules.identifier.resetCache()),this.options.labeling&&this.options.labeling.type!=="none"?(this.labelBox={id:this.uniqId,width:it,height:Ie,position:this.position.normalizedValue,offset:[$t[0]-xt[0]*it,$t[1]-xt[1]*Ie],labelingGroup:"pointLabel"},this.addLabelToLabeler(),this.update()):this.status==="visible"&&v.addObject(Ze),this.modules.renderer.addRerenderEvent(),this.initImageIfNeed(),this.pendingStyleUpdate!==void 0){const bt=this.pendingStyleUpdate;this.pendingStyleUpdate=void 0,this.updateStyleLayer(bt)}})}hide(){this.status==="visible"&&(this.status="hidden",this.removeLabelFromLabeler(),this.removeTilesFromMap(),this.labelingStatus=1)}show(){this.status==="hidden"&&(this.status="visible",this.labelBox||this.addTilesToMap(),this.labelingStatus=0,this.addLabelToLabeler(),this.update())}isOutOfMainReplica(){return!1}remove(){this.status!=="destroyed"&&(this.interactive&&this.modules.identifier.resetCache(),this.removeLabelFromLabeler(),super.destroy(),this.status="destroyed")}setCoordinates(e){if(this.status==="destroyed")return;this.hasExplicitZ=e.length===3,this.tierHeightResolver.reset(!0);const t=n.Mercator.fromGeo(e);this.position={userValue:t,normalizedValue:n.normalizeMapPoint(t)},this.tileObjects.forEach(i=>{i.setTileCoords(n.mapPointTo32ZoomTileCoords(this.position.normalizedValue),this.mapState),Eo(i,this.position.userValue[2])}),this.labelBox&&(this.labelBox.position=this.position.normalizedValue,this.addLabelToLabeler()),this.tileObjects.length!==0&&this.status==="visible"&&this.modules.renderer.addRerenderEvent()}getCoordinates(){return n.Mercator.toGeo(this.position.userValue)}getText(){return this.options.text}getFont(){var e;return(e=this.options.font)!=null?e:n.DEFAULT_FONT}getFontSize(){var e;return(e=this.options.fontSize)!=null?e:n.fonts.baseSize}getTextDimensions(){if(this.generationState!==void 0)return{width:this.generationState.labelMaxWidthInPx,height:this.generationState.labelHeightInPx}}getResolvedHeight(){return this.tierHeightResolver.getResolvedHeight()}update(){if(this.status==="destroyed"||(super.update(),!this.updateGlobeVisibility(this.options.coordinates)))return;const e=ye(this.mapState);if(this.generationState!==void 0&&e!==this.generationState.asEcef&&(this.regenerateGeometry(),this.generationState.asEcef=e),this.refreshTierData(),this.status!=="visible"||!this.labelBox||this.lastLabelingRevision===this.modules.labeler.getLabelingRevision())return;this.lastLabelingRevision=this.modules.labeler.getLabelingRevision();const t=this.modules.labeler.isLabelBoxSurvived(this.uniqId),i=this.labelingStatus;let r=n.LabelingAnimation.none;switch(this.labelingStatus){case 0:t?(this.addTilesToMap(),r=n.LabelingAnimation.none,this.labelingStatus=3):this.labelingStatus=1;break;case 1:t&&(this.addTilesToMap(),r=n.LabelingAnimation.fadeIn,this.labelingStatus=2);break;case 2:t?this.labelingStatus=3:(this.labelingStatus=4,r=n.LabelingAnimation.fadeOut);break;case 3:t||(r=n.LabelingAnimation.fadeOut,this.labelingStatus=4);break;case 4:t?(r=n.LabelingAnimation.fadeIn,this.labelingStatus=2):(this.removeTilesFromMap(),this.labelingStatus=1);break}i!==this.labelingStatus&&this.labelingStatus!==1&&this.tileObjects.forEach(o=>o.children.forEach(a=>{a.attributes.animDirection=r}))}updateStyleLayer(e){return q(this,null,function*(){var r,o;if(this.generationState===void 0){this.status!=="destroyed"&&(this.pendingStyleUpdate=I(I({},this.pendingStyleUpdate),e));return}const t=(o=(r=e.font)!=null?r:this.options.font)!=null?o:n.DEFAULT_FONT;if(e.font!==void 0&&e.font!==this.generationState.textFont){const a=++this.styleUpdateId;if(yield Promise.all(this.generationState.label.ranges.map(l=>this.modules.assetManager.loadFont(t,l))),this.styleUpdateId!==a||this.status==="destroyed")return}this.applyStyleUpdate(e)})}regenerateGeometry(){if(this.generationState===void 0)return;const{tileManager:e}=this.modules,t=this.status==="visible"&&(!this.labelBox||this.labelingStatus===3||this.labelingStatus===2||this.labelingStatus===4),i=this.tileObjects.slice();this.tileObjects.length=0,this.imageLabelBoxAdjusted=!1;const r=++this.generationId,o=this.generateTextTileObject(this.generationState);t&&e.addObject(o);for(const a of i)e.removeObject(a);this.initImageIfNeed(r),this.modules.renderer.addRerenderEvent()}postProcessGeneratedData(e){}applyStyleUpdate(e){var p,x,S,b,T,y,E,P,A,F,L,D,B,Q,Z,$;if(this.generationState===void 0)return;const t=this.generationState.textFont,i=(p=this.options.fontSize)!=null?p:n.fonts.baseSize,r=(S=(x=e.font)!=null?x:this.options.font)!=null?S:n.DEFAULT_FONT,o=(T=(b=e.fontSize)!=null?b:this.options.fontSize)!=null?T:n.fonts.baseSize,a=(y=this.options.letterSpacing)!=null?y:Hc,l=(E=this.options.lineHeight)!=null?E:n.fonts.baseLineHeight,c=[(A=(P=this.options.offset)==null?void 0:P[0])!=null?A:Er[0],(L=(F=this.options.offset)==null?void 0:F[1])!=null?L:Er[1]],d=(D=e.haloRadius)!=null?D:this.options.haloRadius,u=Gc(e.color,this.options.color,kc),h=Gc(e.haloColor,this.options.haloColor,Mc);this.options=V(I({},this.options),{font:(B=e.font)!=null?B:this.options.font,fontSize:(Q=e.fontSize)!=null?Q:this.options.fontSize,color:(Z=e.color)!=null?Z:this.options.color,haloRadius:d,haloColor:($=e.haloColor)!=null?$:this.options.haloColor});const _=this.generationState.styleLayer.style;_.textFont=r,_.textFontSize=o,u!==void 0&&(_.textColor=n.handyColor(u)),_.textHaloWidth=d!=null?d:Uc,h!==void 0&&(_.textHaloColor=n.handyColor(h)),this.modules.renderer.addRerenderEvent();const f=r!==t;if(!f&&!(o!==i))return;const{label:v}=this.generationState;f&&(v.textMetrics=n.getTextMetrics(v.label,a,this.modules.assetManager.getFontGlyphs(r),this.modules.assetManager.getFontGlyphs(n.DEFAULT_FONT)));const g=Vc(o,l,v.textMetrics,this.options.anchor,c);this.generationState=V(I({},this.generationState),{textFont:r,elementOffset:g.elementOffset,anchorOffset:g.anchorOffset,labelMaxWidthInPx:g.labelMaxWidthInPx,labelHeightInPx:g.labelHeightInPx}),f&&this.regenerateGeometry()}createTextStyleLayer(e,t,i,r,o,a,l,c,d){return n.makeHandyStyleLayer({type:"point",id:e,minzoom:this.options.minZoom,maxzoom:this.options.maxZoom,interactive:this.interactive,style:{textFont:t,textFontSize:i,textColor:r!=null?r:kc,textHaloWidth:o!=null?o:Uc,textHaloColor:a!=null?a:Mc,textLetterSpacing:l,textLineHeight:c,textOffset:d,allowElevation:!0}},this.modules.dynamicStyle.getStyle().globals)}generateTextTileObject(e){const{collector:t}=this.modules,{label:i,elementOffset:r,styleLayer:o,textFont:a}=e;i.layer=o;const l=this.getTransformPosition();n.generateSafely({collector:t,generator:n.generateTextElement,args:[i,"",1,i.textMetrics,[0,0,0],0,r,o,a,window.devicePixelRatio,l]});const c=t.getAccumulatedData();this.postProcessGeneratedData(c.data);const d=n.mapPointTo32ZoomTileCoords(this.position.normalizedValue),u=new n.TileObject("dynamicObject",c.data,this.modules,this.mapState,d,this);return u.ecefDataState=n.ecefDataStateFromBool(ye(this.mapState)),Eo(u,this.position.userValue[2]),this.resolveTierData(),this.tileObjects.push(u),t.reset(),u}getTransformPosition(){if(!ye(this.mapState))return;const e=n.mapPointTo32ZoomTileCoords(this.position.normalizedValue),t=n.createTileInfo(e);return(i,r)=>n.encodeTilePointToEcefU16(t,i,r)}initImageIfNeed(e){return q(this,null,function*(){var L,D;if(!this.options.image||this.generationState===void 0)return;const{imageCache:t,dynamicStyle:i,collector:r,tileManager:o}=this.modules,a=window.devicePixelRatio,l=yield t.getRasterSet(this.options.image.url,void 0,this.options.image.size,[0,0]);if(!l||this.status==="destroyed"||e!==void 0&&e!==this.generationId)return;const c=l.rasters[0];i.appendRasterSet(l,n.getStaticIconRasterSetKey(this.options.image.url,0,0));const{labelMaxWidthInPx:d,labelHeightInPx:u,textOffset:h,anchorOffset:_,label:f}=this.generationState,[m,v,g,p]=this.options.image.padding||Fv,x=(d+p+v)*a,S=(u+m+g)*a,b=((v-p)/2+h[0]+_[0])*a,T=((g-m)/2+h[1]+_[1])*a,y=(L=this.options.image.stretchX)==null?void 0:L.map(([B,Q])=>[B*a,Q*a]),E=(D=this.options.image.stretchY)==null?void 0:D.map(([B,Q])=>[B*a,Q*a]),P=this.getTransformPosition();n.generateSafely({collector:r,generator:n.generateIconElement,args:[f,"",[0,0,0],0,c,x,S,b,T,window.devicePixelRatio,y,E,P]});const A=r.getAccumulatedData();r.reset();const F=new n.TileObject("dynamicObject",A.data,this.modules,this.mapState,n.mapPointTo32ZoomTileCoords(this.position.normalizedValue),this);F.ecefDataState=n.ecefDataStateFromBool(ye(this.mapState)),Eo(F,this.position.userValue[2]),this.tileObjects.push(F),this.status!=="hidden"&&!this.labelBox&&o.addObject(F),this.labelBox&&(this.imageLabelBoxAdjusted||(this.imageLabelBoxAdjusted=!0,this.labelBox.height=u+m+g,this.labelBox.width=d+p+v,this.labelBox.offset[0]-=p,this.labelBox.offset[1]-=m,this.addLabelToLabeler()),this.labelingStatus!==1&&this.labelingStatus!==0&&(o.addObject(F),this.mapState.needRerender=!0),this.lastLabelingRevision=To)})}addTilesToMap(){this.tileObjects.forEach(e=>{this.modules.tileManager.addObject(e)})}removeTilesFromMap(){this.tileObjects.forEach(e=>{this.modules.tileManager.removeObject(e)})}addLabelToLabeler(){this.removeLabelFromLabeler(),this.labelBox&&(this.modules.labeler.addLabelBox(this.labelKey,this.labelBox),this.lastLabelingRevision=To)}removeLabelFromLabeler(){this.labelBox&&this.modules.labeler.removeLabels(this.labelKey)}refreshTierData(){if(!this.tierHeightResolver.shouldUseTierHeight()){this.tierHeightResolver.reset()&&this.modules.renderer.addRerenderEvent();return}this.tierHeightResolver.needsResolve()&&this.throttledResolveTierData()}resolveTierData(){return this.tierHeightResolver.resolve()}}function Gc(s,e,t){return s!==void 0?s:e===void 0?t:typeof e=="string"?e:void 0}function Dv(s){return[s&&s[0]!==void 0?n.clamp(s[0],0,1):.5,s&&s[1]!==void 0?n.clamp(s[1],0,1):.5]}function Vc(s,e,t,i,r){const o=Dv(i),a=s/n.fonts.baseSize,l=s*e*t.lines.length,c=a*t.maxWidth,d=[-c*(o[0]-.5),-l*(o[1]-.5)];return{anchor:o,labelHeightInPx:l,labelMaxWidthInPx:c,anchorOffset:d,elementOffset:[r[0]+d[0],r[1]+d[1]]}}function Eo(s,e){s.modelMatrices.forEach(t=>{t[14]=e})}const Zc=32,zv=8,Bv="contour-label-fade";function Wc(s){return[(s[0][0]+s[1][0])/2,(s[0][1]+s[1][1])/2]}class Ov extends Cr{constructor(e,t){super(e,{coordinates:Wc(t.path),text:t.text,font:t.font,fontSize:t.fontSize,color:t.color,haloRadius:t.haloRadius,haloColor:t.haloColor,zIndex:t.zIndex,interactive:!1}),this.fadeOpacity=1,this.path=t.path}setPath(e){this.path=e;const t=Wc(e);this.setCoordinates(t),this.regenerateGeometry()}refreshOrientation(){this.regenerateGeometry()}fadeIn(e){this.startFade(0,1,e)}fadeOut(e,t){this.startFade(this.fadeOpacity,0,e,t)}clearFade(){this.stopFadeTicker(),this.fadeComplete=void 0,this.setFadeOpacity(1)}show(){super.show(),this.applyFadeOpacity()}update(){super.update(),this.updateFadeTicker(),(this.fadeTickerName!==void 0||this.fadeOpacity!==1)&&this.applyFadeOpacity()}remove(){this.stopFadeTicker(),this.fadeComplete=void 0,super.remove()}regenerateGeometry(){super.regenerateGeometry(),this.applyFadeOpacity()}postProcessGeneratedData(e){const t=this.computePathAngle();this.rotateCornerOffsets(e,t)}startFade(e,t,i,r){if(this.stopFadeTicker(),this.fadeComplete=r,this.setFadeOpacity(e),i<=0||e===t){this.setFadeOpacity(t);const a=this.fadeComplete;this.fadeComplete=void 0,a==null||a();return}const o=`${Bv}-${this.uniqId}`;this.fadeTickerName=o,n.start(o,{easing:"linear"},this.mapState,e,t,i,1),this.modules.renderer.addRerenderEvent()}updateFadeTicker(){this.fadeTickerName!==void 0&&n.update(this.fadeTickerName,{step:(e,t)=>{this.setFadeOpacity(t)},complete:()=>{this.fadeTickerName=void 0;const e=this.fadeComplete;this.fadeComplete=void 0,e==null||e()}},this.mapState)}stopFadeTicker(){this.fadeTickerName!==void 0&&(n.stop(this.fadeTickerName,this.mapState),this.fadeTickerName=void 0)}setFadeOpacity(e){this.fadeOpacity!==e&&(this.fadeOpacity=e,this.applyFadeOpacity(),this.modules.renderer.addRerenderEvent())}applyFadeOpacity(){for(const e of this.tileObjects)for(const t of e.children)t.attributes.fadeOpacity=this.fadeOpacity}computePathAngle(){if(this.path.length<2)return 0;const e=this.modules.camera,t=e.project(this.path[0]),i=e.project(this.path[1]);return!Number.isFinite(t[0])||!Number.isFinite(t[1])||!Number.isFinite(i[0])||!Number.isFinite(i[1])?0:Math.atan2(t[1]-i[1],i[0]-t[0])}rotateCornerOffsets(e,t){const i=Math.sin(t),r=Math.cos(t);for(const o of e){if(!o.buffer||o.symbol!=="point"||o.sink!=="text")continue;const a=o.buffer,l=a.byteLength/Zc,c=new DataView(a);for(let d=0;d<l;d++){const u=d*Zc+zv,h=c.getInt16(u,!0),_=c.getInt16(u+2,!0);c.setInt16(u,Math.round(h*r-_*i),!0),c.setInt16(u+2,Math.round(h*i+_*r),!0)}}}}var Ye=(s=>(s.Minor="minor",s.Major="major",s.Index="index",s))(Ye||{}),Ir=(s=>(s.Strict="strict",s.Relaxed="relaxed",s))(Ir||{});const wv=1.5,Nv=.25,kv=.1,Pr=.3,Uv=.4,Mv=.1,jc=1.5,Hv=1.2,Gv=1.2,Vv=.6,Xc=2,Co=100,Zv=1,Wv=1e3,jv=.005,Xv=4,$v=.5,Io=220,qv=50,Yv=50,Qv=150,Jv=40,Kv=50,eg=[Ye.Index,Ye.Major,Ye.Minor],Ar={[Ye.Index]:0,[Ye.Major]:1,[Ye.Minor]:2};function Po(s,e){return e===Ye.Minor?s.minorColor[3]>0&&s.minorWidth>0:e===Ye.Major?s.majorColor[3]>0&&s.majorWidth>0:e===Ye.Index?s.indexColor[3]>0&&s.indexWidth>0:!1}function tg(s){const e=[];return Po(s.lines,Ye.Minor)&&e.push({tier:Ye.Minor,interval:s.lines.minorInterval,style:{fontSize:s.labels.minorLabelFontSize,font:s.labels.minorLabelFont,color:s.labels.minorLabelColor,haloRadius:s.labels.minorLabelHaloRadius,haloColor:s.labels.minorLabelHaloColor}}),Po(s.lines,Ye.Major)&&e.push({tier:Ye.Major,interval:s.lines.majorInterval,style:{fontSize:s.labels.majorLabelFontSize,font:s.labels.majorLabelFont,color:s.labels.majorLabelColor,haloRadius:s.labels.majorLabelHaloRadius,haloColor:s.labels.majorLabelHaloColor}}),Po(s.lines,Ye.Index)&&e.push({tier:Ye.Index,interval:s.lines.indexInterval,style:{fontSize:s.labels.indexLabelFontSize,font:s.labels.indexLabelFont,color:s.labels.indexLabelColor,haloRadius:s.labels.indexLabelHaloRadius,haloColor:s.labels.indexLabelHaloColor}}),e}function ig(s,e){const t=e[e.length-1],i=Math.round(s/t.interval)*t.interval;for(const r of e){const o=Math.abs(i%r.interval);if(o<Number.EPSILON*r.interval||Math.abs(o-r.interval)<Number.EPSILON*r.interval)return r}return t}const ng=70,$c=12,rg=15,sg=10,qc=20,og=35;function ag(s,e){if(s<$c)return-1;const t=e===Ir.Strict?qc:og;return s>=rg?t:ng-(s-$c)*sg+(t-qc)}function lg(s,e){const t=s>=0?2*s:-2*s-1,i=e>=0?2*e:-2*e-1;return(t+i)*(t+i+1)/2+i}const Yc=46e3;function cg(s,e){return(s*2654435769|0)^(e*2246822507|0)}function Cn(s,e){return Math.abs(s)<Yc&&Math.abs(e)<Yc?lg(s,e):cg(s,e)}const dg=64;class ug{constructor(){this.grid=new Map,this.nextId=0,this.visited=new Set}clear(){this.grid.clear(),this.nextId=0}insert(e,t,i,r){const o=this.getCell(e-i/2),a=this.getCell(e+i/2),l=this.getCell(t-r/2),c=this.getCell(t+r/2),d=this.nextId++;for(let u=l;u<=c;u++)for(let h=o;h<=a;h++){const _=Cn(h,u);let f=this.grid.get(_);f===void 0&&(f=[],this.grid.set(_,f)),f.push({id:d,x:e,y:t,w:i,h:r})}}hasCollision(e,t,i,r){this.visited.clear();const o=this.getCell(e-i/2),a=this.getCell(e+i/2),l=this.getCell(t-r/2),c=this.getCell(t+r/2);for(let d=l;d<=c;d++)for(let u=o;u<=a;u++){const h=this.grid.get(Cn(u,d));if(h!==void 0){for(const _ of h)if(!this.visited.has(_.id)&&(this.visited.add(_.id),Math.abs(e-_.x)*2<i+_.w&&Math.abs(t-_.y)*2<r+_.h))return!0}}return!1}getCell(e){return Math.floor(e/dg)}}class hg{constructor(e){this.hashes=new Map,this.spacingMap=e}hasNearby(e,t,i){const r=this.hashes.get(i);if(r===void 0)return!1;const o=this.getCell(e),a=this.getCell(t);for(let l=-1;l<=1;l++)for(let c=-1;c<=1;c++)if(r.has(Cn(o+c,a+l)))return!0;return!1}record(e,t,i){let r=this.hashes.get(i);r===void 0&&(r=new Set,this.hashes.set(i,r)),r.add(Cn(this.getCell(e),this.getCell(t)))}getCell(e){return Math.floor(e/this.spacingMap)}}class _g{constructor(e,t){this.base=e,this.quantStep=t,this.cache=new Map}getElevation(e){if(this.quantStep<=0||!Number.isFinite(this.quantStep))return this.base.getElevation(e);const t=Math.round(e[0]/this.quantStep),i=Math.round(e[1]/this.quantStep),r=Cn(t,i),o=this.cache.get(r);if(o!==void 0)return o;const a=this.base.getElevation(e);return a!==void 0&&this.cache.set(r,a),a}clear(){this.cache.clear()}}class fg{constructor(){this.cache=new Map,this.labels=null}setLabels(e){this.labels=e}measure(e,t,i=n.DEFAULT_FONT){var a,l;const r=`${i}|${t}|${e}`,o=this.cache.get(r);if(o!==void 0)return o;for(const c of(l=(a=this.labels)==null?void 0:a.values())!=null?l:[]){if(c.getText()!==e||c.getFont()!==i||c.getFontSize()!==t)continue;const d=c.getTextDimensions();if(d!==void 0)return this.cache.set(r,d.width),d.width}return e.length*t*Vv}clear(){this.cache.clear()}}function mg(s,e){let t=-1/0,i=null,r=null;const o=()=>{i!==null&&(clearTimeout(i),i=null),r=null};return{trigger:(...l)=>{const c=performance.now(),d=c-t;if(d>=e){o(),t=c,s(...l);return}if(r=l,i===null){const u=e-d;i=setTimeout(()=>{if(i=null,r===null)return;const h=r;r=null,t=performance.now(),s(...h)},u)}},cancel:o}}class vg{constructor(e){this.maxSize=e,this.buckets=new Map,this.currentSize=0}release(e){if(this.currentSize>=this.maxSize)return!1;const t=e.getText();e.hide();let i=this.buckets.get(t);return i===void 0&&(i=[],this.buckets.set(t,i)),i.push(e),this.currentSize++,!0}acquire(e){const t=this.buckets.get(e);if(t===void 0||t.length===0)return null;const i=t.pop();return this.currentSize--,t.length===0&&this.buckets.delete(e),i}clear(){for(const e of this.buckets.values())for(const t of e)t.remove();this.buckets.clear(),this.currentSize=0}size(){return this.currentSize}}function Qc(s,e,t){let i=s*374761393+e*668265263+t*1274126177|0;return i=(i^i>>13)*1103515245|0,(i&2147483647)/2147483647}const Ao=1e-10,gg=1e-6,Lo=[0,0,0],Ro=[0,0,0],Fo=[0,0,0],Do=[0,0,0];function Lr(s,e,t){Lo[0]=e[0]+t,Lo[1]=e[1],Ro[0]=e[0]-t,Ro[1]=e[1],Fo[0]=e[0],Fo[1]=e[1]+t,Do[0]=e[0],Do[1]=e[1]-t;const i=s.getElevation(Lo),r=s.getElevation(Ro),o=s.getElevation(Fo),a=s.getElevation(Do);if(i===void 0||r===void 0||o===void 0||a===void 0)return null;const l=(i-r)/(2*t),c=(o-a)/(2*t);return[l,c]}const Gt=[0,0,0];function Jc(s,e,t,i,r){Gt[0]=e[0],Gt[1]=e[1],Gt[2]=0;for(let o=0;o<Xv;o++){const a=s.getElevation(Gt);if(a===void 0)return null;const l=a-t;if(Math.abs(l)<gg)return[Gt[0],Gt[1],0];const c=Lr(s,Gt,i);if(c===null)return null;const[d,u]=c,h=d*d+u*u;if(h<Ao)return null;const _=l/h,f=Math.abs(_)*Math.sqrt(h);if(Gt[0]-=_*d,Gt[1]-=_*u,f<r)return[Gt[0],Gt[1],0]}return null}const Rr=[0,0,0];function pg(s,e,t,i){const r=Lr(s,e,i);if(r===null)return null;const[o,a]=r,l=Math.sqrt(o*o+a*a);if(l<Ao)return null;const c=-a/l,d=o/l;Rr[0]=e[0]+c*t,Rr[1]=e[1]+d*t,Rr[2]=0;const u=Lr(s,Rr,i);if(u===null)return null;const h=Math.hypot(u[0],u[1]);return h<Ao?null:{straightness:(o*u[0]+a*u[1])/(l*h),gradient:r}}function zo(s,e,t,i){const[r,o]=e,a=Math.hypot(r,o),l=[o/a,-r/a],c=t/2*i*Gv,d=n.Mercator.toGeo([s[0]-l[0]*c,s[1]-l[1]*c]),u=n.Mercator.toGeo([s[0]+l[0]*c,s[1]+l[1]*c]);return[d,u]}function Kc(s,e,t){const i=e[0]-s[0],r=e[1]-s[1];return i*t[0]+r*t[1]<0}function Fr(s){return Math.round(Math.max(0,Math.min(1,s))*255).toString(16).padStart(2,"0")}const xg=[0,0];function bg(s){const e=n.Mercator.toGeo(s,xg);return n.Mercator.scaleFactor(e[1])}const Bo=[0,0];function Oo(s,e,t){let i=s.elevationHashes.get(e);return i===void 0&&(i=new hg(t),s.elevationHashes.set(e,i)),i}function Sg(s,e=[]){const{rows:t,cols:i,cameraPos:r,unproject:o,cellSizePx:a}=s;let l=0;for(let c=0;c<t;c++)for(let d=0;d<i;d++){const u=Qc(d,c,0)*(Pr*2)-Pr,h=Qc(d,c,1)*(Pr*2)-Pr;Bo[0]=(d+.5+u)*a,Bo[1]=(c+.5+h)*a;const _=o(Bo);if(_===null||!isFinite(_[0])||!isFinite(_[1]))continue;const f=n.Mercator.fromGeo(_),m=n.sqrDist(f,r);let v=e[l];v===void 0?(v={mapPos:[f[0],f[1],0],distSqToCamera:m},e[l]=v):(v.mapPos[0]=f[0],v.mapPos[1]=f[1],v.mapPos[2]=0,v.distSqToCamera=m),l++}return e.length=l,e}function yg(s,e,t,i,r,o=[]){var _;if(o.length=0,t.length===0)return o;const a=r!=null?r:[...t].sort((f,m)=>m.interval-f.interval),l=1/i,c=t[0];if(c===void 0)return o;const d=t.find(f=>f.tier===Ye.Minor),u=((_=d==null?void 0:d.interval)!=null?_:c.interval)*i;let h=0;for(const f of s){const m=e.getElevation(f.mapPos);if(m===void 0||m<Number.EPSILON)continue;const v=ig(m*l,a),g=v.interval*i,p=Math.round(m/g)*g;if(p<Number.EPSILON)continue;const x=Math.abs(m-p);if(x>u*Uv)continue;const S=g/2,b=1-x/S;let T=o[h];T===void 0?(T={seed:[f.mapPos[0],f.mapPos[1],0],elevation:m,closeness:b,nearestLevel:p,distSqToCamera:f.distSqToCamera,tier:v.tier},o[h]=T):(T.seed[0]=f.mapPos[0],T.seed[1]=f.mapPos[1],T.seed[2]=0,T.elevation=m,T.closeness=b,T.nearestLevel=p,T.distSqToCamera=f.distSqToCamera,T.tier=v.tier),h++}return o.length=h,o}function Tg(s,e){const t=Re(e*Mv,2);s.sort((i,r)=>{const o=Ar[i.tier]-Ar[r.tier];if(o!==0)return o;const a=i.nearExisting===!0?1:0,l=r.nearExisting===!0?1:0;if(a!==l)return l-a;const c=i.distSqToCamera-r.distSqToCamera;return Math.abs(c)>t?c:r.closeness-i.closeness})}function Eg(s,e,t,i){if(e.size===0||s.length===0){for(const o of s)o.nearExisting=!1;return}const r=new Map;for(const o of e.values()){let a=r.get(o.level);a===void 0&&(a=[],r.set(o.level,a)),a.push(o)}for(const o of s){const a=i(o.tier);if(a<=0){o.nearExisting=!1;continue}const l=No(o.nearestLevel,t),c=r.get(l);if(c===void 0){o.nearExisting=!1;continue}const d=a*a;let u=!1;for(const h of c)if(n.sqrDist(h.mapPos,o.seed)<=d){u=!0;break}o.nearExisting=u}}function ed(s,e,t){return s[0]<-t||s[0]>e[0]+t||s[1]<-t||s[1]>e[1]+t}function wo(s,e,t,i){return i?{w:Math.max(s,t),h:Math.max(e,t)}:{w:s,h:e}}function Cg(s,e,t,i,r,o,a,l){return Math.abs(s-r)*2<t+a&&Math.abs(e-o)*2<i+l}function No(s,e){return Math.round(s/e)}function Ig(s,e,t,i){const r=Rg(s,t,i);return r===null?null:Lg(r,s,e)}function Pg(s,e,t){return Oo(t,e.tier,s.tierCtx.minLabelSpacingMap).hasNearby(s.snapped[0],s.snapped[1],s.displayLevel)}function Ag(s,e){return e.screenHash.hasCollision(s.screenPos[0],s.screenPos[1],s.collisionW,s.collisionH)}function Lg(s,e,t){return Pg(s,e,t)||Ag(s,t)?null:Fg(s,e,t)}function Rg(s,e,t){const i=e.tierContexts.get(s.tier);if(i===void 0)return null;const r=Jc(e.field,s.seed,s.nearestLevel,e.gradientEpsMap,e.newtonStopSnapMap);if(r===null)return null;const o=No(s.nearestLevel,e.scaleFactor),a=n.Mercator.toGeo(r),l=e.projectGeo(a);if(ed(l,e.screenSizePx,Yv))return null;const c=`${o}`,d=i.measureWidth(c)+2*i.haloRadius+Xc,{w:u,h}=wo(d,i.labelHeight,i.labelSpacingPx,!0),_=pg(e.field,r,e.curvatureOffsetMap,e.gradientEpsMap);return _===null||t.cosThreshold!==-1&&_.straightness<t.cosThreshold||e.cameraPitch!==0&&Kc(e.cameraPosition,r,_.gradient)?null:{snapped:r,geo:a,screenPos:l,displayLevel:o,text:c,labelWidth:d,collisionW:u,collisionH:h,gradient:_.gradient,tierCtx:i}}function Fg(s,e,t){return Oo(t,e.tier,s.tierCtx.minLabelSpacingMap).record(s.snapped[0],s.snapped[1],s.displayLevel),t.screenHash.insert(s.screenPos[0],s.screenPos[1],s.collisionW,s.collisionH),{key:Dg(s.snapped,s.displayLevel,s.tierCtx.minLabelSpacingMap*jc,t.existingLabels),geo:s.geo,text:s.text,mapPos:s.snapped,level:s.displayLevel,nearestLevel:e.nearestLevel,gradient:s.gradient,labelWidth:s.labelWidth,tier:e.tier}}function Dg(s,e,t,i){const r=t*t;for(const[l,c]of i)if(c.level===e&&n.sqrDist(c.mapPos,s)<=r)return l;const o=Math.round(s[0]/t)*t,a=Math.round(s[1]/t)*t;return`${e}_${Math.round(o)}_${Math.round(a)}`}function zg(s,e,t){const i=s.level*e.scaleFactor,r=Jc(e.field,s.mapPos,i,e.gradientEpsMap,e.newtonStopSnapMap);if(r===null)return null;const o=r[0]-s.mapPos[0],a=r[1]-s.mapPos[1],l=o*o+a*a;if(t>0&&l>t*t)return null;if(i===s.nearestLevel&&o===0&&a===0)return s;const c=Lr(e.field,r,e.gradientEpsMap);return c===null?null:V(I({},s),{mapPos:r,nearestLevel:i,geo:n.Mercator.toGeo(r),gradient:c})}function Bg(s,e,t,i=[]){var d,u;const r=[],o=new Map;for(const h of i)o.set(h.level,((d=o.get(h.level))!=null?d:0)+1);e.screenHash.clear();for(const h of i)td(e,t,h,!0);const a=[...s.values()].sort((h,_)=>Ar[h.tier]-Ar[_.tier]),l=[],c=[];for(const h of a){const _=t.tierContexts.get(h.tier);if(_===void 0||_.maxLabelsPerLevel<=0)continue;const f=(u=o.get(h.level))!=null?u:0;if(f>=_.maxLabelsPerLevel)continue;let m=zg(h,t,_.minLabelSpacingMap);if(m===null)continue;const v=_.measureWidth(m.text)+2*_.haloRadius+Xc;v!==m.labelWidth&&(m=V(I({},m),{labelWidth:v}));const g=t.projectGeo(m.geo);if(ed(g,t.screenSizePx,Qv)||t.cameraPitch!==0&&Kc(t.cameraPosition,m.mapPos,m.gradient))continue;const{w:p,h:x}=wo(m.labelWidth,_.labelHeight,_.labelSpacingPx,!1),S=g[0],b=g[1];if(e.screenHash.hasCollision(S,b,p,x))continue;let T=!1;for(const E of l)if(Cg(S,b,p,x,E.x,E.y,E.w,E.h)){T=!0;break}if(T)continue;Oo(e,m.tier,_.minLabelSpacingMap).record(m.mapPos[0],m.mapPos[1],m.level),l.push({x:S,y:b,w:p,h:x}),r.push(m),c.push(g),o.set(m.level,f+1)}for(let h=0;h<r.length;h++){const _=r[h],f=c[h];_===void 0||f===void 0||td(e,t,_,!0,f)}return r}function td(s,e,t,i,r){const o=e.tierContexts.get(t.tier);if(o===void 0)return;const a=r!=null?r:e.projectGeo(t.geo),{w:l,h:c}=wo(t.labelWidth,o.labelHeight,o.labelSpacingPx,i);s.screenHash.insert(a[0],a[1],l,c)}function Og(s,e,t,i,r){t.screenHash.clear(),t.elevationHashes.clear();const o=new Map;t.existingLabels=o;let a=[];for(const l of eg){if(!i.tierContexts.has(l))continue;const c=new Map;for(const[_,f]of s)f.tier===l&&c.set(_,f);const d=Bg(c,t,i,a);for(const _ of d)o.set(_.key,_);a.push(...d);const u=e.filter(_=>_.tier===l);if(u.length===0)continue;const h=a.length;a=Ng(u,t,i,r,a);for(let _=h;_<a.length;_++){const f=a[_];f!==void 0&&o.set(f.key,f)}}return a}function wg(s,e){const t=new Set(e.map(o=>o.key)),i=[];for(const o of s.keys())t.has(o)||i.push(o);const r=[];for(let o=0;o<e.length;o++){const a=e[o];a!==void 0&&(s.has(a.key)||r.push(o))}return{toRemove:i,toAdd:r}}function Ng(s,e,t,i,r=[]){var l,c;const o=new Map;for(const d of r)o.set(d.level,((l=o.get(d.level))!=null?l:0)+1);const a=[...r];for(let d=0;d<i.length;d++){const u=i[d];if(u!==void 0)for(const h of s){const _=t.tierContexts.get(h.tier);if(_===void 0||_.maxLabelsPerLevel<=0)continue;const f=No(h.nearestLevel,t.scaleFactor),m=(c=o.get(f))!=null?c:0;if(m>=_.maxLabelsPerLevel)continue;const v=Ig(h,e,t,u);v!==null&&(a.push(v),e.existingLabels.set(v.key,v),o.set(f,m+1))}}return a}function id(s){return s.map(e=>`${e.tier}:${e.interval}`).join("_")}function kg(s){return s.map(e=>[e.tier,e.style.font,e.style.fontSize,e.style.haloRadius,e.style.color.join(","),e.style.haloColor.join(",")].join(":")).join("_")}var ko=(s=>(s.None="none",s.Regenerate="regenerate",s.RefineKeep="refineKeep",s))(ko||{});function Ug(s,e,t){return s?"regenerate":e&&t?"refineKeep":"none"}function Mg(s,e,t){return t||s===void 0?!0:s.labelWidth!==e.labelWidth||s.gradient[0]!==e.gradient[0]||s.gradient[1]!==e.gradient[1]||s.mapPos[0]!==e.mapPos[0]||s.mapPos[1]!==e.mapPos[1]}function nd(s,e){return s[0]===e[0]&&s[1]===e[1]&&s[2]===e[2]&&s[3]===e[3]}function rd(s,e){for(const t of s)if(t.tier===e)return t.style}class Hg{constructor(e){this.labels=new Map,this.acceptedLabels=new Map,this.labelStyleByInstance=new WeakMap,this.cacheKey="",this.cachedField=null,this.cacheQuantStep=0,this.cachedDemRevision=-1,this.screenHash=new ug,this.labelPool=new vg(Kv),this.resolvedPlacementHash="",this.resolvedAppearanceHash="",this.cachedAppearanceHash="",this.cachedIntervalHash="",this.cachedActiveTiers=[],this.cachedSortedTiersDesc=[],this.seedsBuf=[],this.candidatesBuf=[],this.placementElevationHashes=new Map,this.lastOrientRotation=NaN,this.lastOrientPitch=NaN,this.lastPathMapPointsPerPx=NaN,this.pendingRemovals=new Map,this.unproject=t=>this.modules.camera.unproject(t),this.project=t=>this.modules.camera.project(t),this.modules=e,this.widthCache=new fg,this.throttled=mg(()=>this.runUpdate(),Wv)}update(){if(!this.modules.demManager.isContoursEnabled()){this.destroy();return}this.refreshLabelOrientations(),this.refreshAppearance(),this.throttled.trigger()}refresh(){if(!this.modules.demManager.isContoursEnabled()){this.destroy();return}this.throttled.cancel(),this.refreshAppearance().then(()=>{this.modules.demManager.isContoursEnabled()&&this.runUpdate()})}destroy(){var e;this.throttled.cancel(),this.clearLabels(),(e=this.cachedField)==null||e.clear(),this.widthCache.clear()}refreshLabelOrientations(){if(this.labels.size===0)return;const{rotation:e,pitch:t}=this.modules.map.state;if(!(Number.isFinite(this.lastOrientRotation)&&e===this.lastOrientRotation&&t===this.lastOrientPitch)){this.lastOrientRotation=e,this.lastOrientPitch=t;for(const i of this.labels.values())i.refreshOrientation()}}refreshAppearance(){return q(this,null,function*(){if(this.labels.size===0)return;const{activeTiers:e,appearanceHash:t}=this.resolveActiveTiers();t!==this.cachedAppearanceHash&&(yield this.applyAppearance(e),this.cachedAppearanceHash=t)})}runUpdate(){var l;if(this.modules.demManager.getTilesRevision()===0){this.destroy();return}const e=this.modules.demManager.getTilesRevision(),t=e!==this.cachedDemRevision;t&&((l=this.cachedField)==null||l.clear(),this.cachedDemRevision=e);const{activeTiers:i,placementHash:r}=this.resolveActiveTiers(),o=this.computeCacheKey(r),a=Ug(o!==this.cacheKey,t,this.acceptedLabels.size>0);if(a!==ko.None){if(a===ko.Regenerate){this.cacheKey=o,this.regenerate(i),this.cachedAppearanceHash=this.resolvedAppearanceHash;return}this.regenerate(i,{fill:!1})}}resolveActiveTiers(){const e=this.modules.demManager.getResolvedContourParams();if(e===this.cachedContourParams&&this.resolvedPlacementHash!=="")return{activeTiers:this.cachedActiveTiers,placementHash:this.resolvedPlacementHash,appearanceHash:this.resolvedAppearanceHash};const t=tg(e),i=id(t),r=kg(t);return this.cachedContourParams=e,this.cachedActiveTiers=t,this.cachedSortedTiersDesc=[...t].sort((o,a)=>a.interval-o.interval),this.resolvedPlacementHash=i,this.resolvedAppearanceHash=r,{activeTiers:t,placementHash:i,appearanceHash:r}}computeCacheKey(e){const{center:t,zoom:i,size:r,rotation:o,pitch:a}=this.modules.map.state;return[t[0].toFixed(1),t[1].toFixed(1),i.toFixed(2),r[0],r[1],Math.floor(o),Math.floor(a),e].join("_")}buildCandidates(e,t,i,r,o,a,l){if(this.cachedField===null)return[];const c=Co,d=Sg({rows:Math.max(1,Math.ceil(t/c)),cols:Math.max(1,Math.ceil(e/c)),cameraPos:this.modules.camera.position,unproject:this.unproject,cellSizePx:c},this.seedsBuf),u=yg(d,this.cachedField,i,r,this.cachedSortedTiersDesc,this.candidatesBuf);return l!==void 0&&l.size>0&&Eg(u,l,r,h=>{const _=a.get(h);return _===void 0?0:_.minLabelSpacingMap*jc}),Tg(u,o),u}regenerate(e,t){const{camera:i,map:{state:{size:r}}}=this.modules;if(e.length===0){this.clearLabels();return}const o=i.getViewportVertices(),a=n.tetragonBounds(o),l=Math.max(1,r[0]),c=Math.max(1,r[1]),d=(a.max[0]-a.min[0])/l,u=(a.max[1]-a.min[1])/c,h=Math.max(d,u);if(!isFinite(h)||h<=0){this.clearLabels();return}const _=wv*h;if(this.updateCacheQuant(_),this.cachedField===null)return;const f=this.buildTierContexts(e,h),m=[{cosThreshold:this.getCosThresholdForPass(Ir.Strict)},{cosThreshold:this.getCosThresholdForPass(Ir.Relaxed)}];this.widthCache.setLabels(this.labels),this.screenHash.clear();const v={field:this.cachedField,gradientEpsMap:_,curvatureOffsetMap:Jv*h,newtonStopSnapMap:$v*h,screenSizePx:r,cameraPitch:i.correctedPitch,cameraPosition:i.position,projectGeo:this.project,tierContexts:f,scaleFactor:bg(i.position)},g={elevationHashes:this.placementElevationHashes,screenHash:this.screenHash,existingLabels:new Map},p=this.acceptedLabels,x=id(e),S=x!==this.cachedIntervalHash;this.cachedIntervalHash=x;const b=S?new Map:p,T=Math.hypot(a.max[0]-a.min[0],a.max[1]-a.min[1]),E=(t==null?void 0:t.fill)!==!1?this.buildCandidates(l,c,e,v.scaleFactor,T,f,S?void 0:p):[],P=Og(b,E,g,v,m);this.applyDiff(P,h,e)}applyAppearance(e){return q(this,null,function*(){if(this.labels.size===0)return;this.widthCache.clear(),this.widthCache.setLabels(this.labels);const t=[];for(const[i,r]of this.labels){const o=this.acceptedLabels.get(i);if(o===void 0)continue;const a=rd(e,o.tier);a===void 0||this.labelMatchesStyle(r,o.tier,a)||t.push(this.applyLabelStyle(r,o.tier,a))}yield Promise.all(t)})}applyDiff(e,t,i){const r=wg(this.labels,e),o=new Uint8Array(e.length);for(const l of r.toAdd)o[l]=1;for(const l of r.toRemove){const c=this.labels.get(l);c!==void 0&&this.scheduleFadeRemove(l,c),this.labels.delete(l),this.acceptedLabels.delete(l)}const a=!Number.isFinite(this.lastPathMapPointsPerPx)||Math.abs(t-this.lastPathMapPointsPerPx)/this.lastPathMapPointsPerPx>jv;for(let l=0;l<e.length;l++){if(o[l]!==0)continue;const c=e[l];if(c===void 0)continue;const d=this.labels.get(c.key);if(d===void 0)continue;const u=this.acceptedLabels.get(c.key);if(Mg(u,c,a)){const h=zo(c.mapPos,c.gradient,c.labelWidth,t);d.setPath(h)}this.acceptedLabels.set(c.key,c)}this.lastPathMapPointsPerPx=t;for(const l of r.toAdd){const c=e[l];if(c===void 0)continue;const d=rd(i,c.tier);if(d===void 0)continue;this.cancelPendingRemoval(c.key);let u=this.labelPool.acquire(c.text);if(u!==null){this.labelMatchesStyle(u,c.tier,d)||this.applyLabelStyle(u,c.tier,d);const h=zo(c.mapPos,c.gradient,c.labelWidth,t);u.setPath(h),u.clearFade(),u.fadeIn(Io),u.show()}else u=this.createLineLabel(c,t,d),u.fadeIn(Io),u.show();this.labelStyleByInstance.set(u,{tier:c.tier,style:d}),this.labels.set(c.key,u),this.acceptedLabels.set(c.key,c)}}scheduleFadeRemove(e,t){this.cancelPendingRemoval(e),this.pendingRemovals.set(e,t),t.fadeOut(Io,()=>{this.pendingRemovals.get(e)===t&&(this.pendingRemovals.delete(e),this.releaseOrRemove(t))})}cancelPendingRemoval(e){const t=this.pendingRemovals.get(e);t!==void 0&&(this.pendingRemovals.delete(e),t.clearFade(),this.releaseOrRemove(t))}clearPendingRemovals(){for(const e of[...this.pendingRemovals.keys()])this.cancelPendingRemoval(e)}releaseOrRemove(e){e.clearFade(),this.labelPool.release(e)||e.remove()}applyLabelStyle(e,t,i){return this.labelStyleByInstance.set(e,{tier:t,style:i}),e.updateStyleLayer({font:i.font,fontSize:i.fontSize,color:this.colorArrayToHex(i.color),haloRadius:i.haloRadius,haloColor:this.colorArrayToHex(i.haloColor)})}labelMatchesStyle(e,t,i){const r=this.labelStyleByInstance.get(e);return r===void 0||r.tier!==t?!1:r.style.font===i.font&&r.style.fontSize===i.fontSize&&r.style.haloRadius===i.haloRadius&&nd(r.style.color,i.color)&&nd(r.style.haloColor,i.haloColor)}createLineLabel(e,t,i){const r=zo(e.mapPos,e.gradient,e.labelWidth,t);return new Ov(this.modules.map,{path:r,text:e.text,font:i.font,fontSize:i.fontSize,color:this.colorArrayToHex(i.color),haloRadius:i.haloRadius,haloColor:this.colorArrayToHex(i.haloColor),zIndex:qv})}clearLabels(){this.clearPendingRemovals();for(const e of this.labels.values())e.remove();this.labels.clear(),this.acceptedLabels.clear(),this.labelPool.clear(),this.cacheKey="",this.resolvedPlacementHash="",this.resolvedAppearanceHash="",this.cachedAppearanceHash="",this.cachedIntervalHash="",this.cachedContourParams=void 0,this.cachedActiveTiers=[],this.cachedSortedTiersDesc=[],this.cachedDemRevision=-1,this.placementElevationHashes.clear(),this.seedsBuf.length=0,this.candidatesBuf.length=0,this.lastOrientRotation=NaN,this.lastOrientPitch=NaN,this.lastPathMapPointsPerPx=NaN}updateCacheQuant(e){const t=e*Nv;(this.cacheQuantStep<=0||Math.abs(t-this.cacheQuantStep)/this.cacheQuantStep>kv)&&(this.cachedField=new _g({getElevation:r=>this.modules.demManager.getElevation(r)},t)),this.cacheQuantStep=t}colorArrayToHex(e){return`#${Fr(e[0])}${Fr(e[1])}${Fr(e[2])}${Fr(e[3])}`}getCosThresholdForPass(e){const{zoom:t}=this.modules.map.state,i=ag(t,e);return i===-1?-1:Math.cos(i*Math.PI/180)}buildTierContexts(e,t){const i=new Map;for(const r of e){const o=r.style;i.set(r.tier,{haloRadius:o.haloRadius,labelHeight:o.fontSize*Hv+2*o.haloRadius,measureWidth:a=>this.widthCache.measure(a,o.fontSize,o.font),labelSpacingPx:Co,minLabelSpacingMap:Co*t,maxLabelsPerLevel:Zv})}return i}}const sd=5,od=25;class Gg{constructor(e){this.contourParamsZoom=NaN,this.contourParamsStyleId=NaN,this.modules=e}enable(){this.contourLabelsManager=new Hg(this.modules)}disable(){var e;(e=this.contourLabelsManager)==null||e.destroy(),this.contourLabelsManager=void 0,this.invalidateParamsCache()}update(){var e;(e=this.contourLabelsManager)==null||e.update()}onStyleChange(){var e;this.invalidateParamsCache(),(e=this.contourLabelsManager)==null||e.refresh()}isContoursEnabled(){var i;if(!this.modules.map.state.demMode)return!1;const e=this.modules.styleManager.getStyle(this.modules.map.state.handyStyleId);return e!=null&&e.dem.style.contours?n.resolveNumber((i=e==null?void 0:e.dem.style.contours)==null?void 0:i.interval,n.makeBinderContext(this.modules.map.state.styleZoom,this.modules.map.state.pitch,this.modules.map.state.styleState,[]),0)>0:!1}getContourLabelsManager(){return this.contourLabelsManager}getResolvedContourParams(){const e=this.modules.map.state.styleZoom,t=this.modules.map.state.handyStyleId;return(this.contourParams===void 0||this.contourParamsZoom!==e||this.contourParamsStyleId!==t)&&(this.contourParams=this.resolveContourParams(),this.contourParamsZoom=e,this.contourParamsStyleId=t),this.contourParams}invalidateParamsCache(){this.contourParams=void 0,this.contourParamsZoom=NaN,this.contourParamsStyleId=NaN}resolveContourParams(){const e=this.modules.map.state,t=this.modules.styleManager.getStyle(e.handyStyleId),i=n.makeBinderContext(e.styleZoom,e.pitch,e.styleState,[]),r=t==null?void 0:t.dem.style.contours;if(r===void 0){const c=n.DEFAULT_CONTOUR_STYLE;return{lines:{minorInterval:c.interval,majorInterval:c.interval*sd,indexInterval:c.interval*od,minorColor:n.getColorForShaders(n.handyColor(c.minorColor)),majorColor:n.getColorForShaders(n.handyColor(c.majorColor)),indexColor:n.getColorForShaders(n.handyColor(c.indexColor)),minorWidth:c.minorWidth,majorWidth:c.majorWidth,indexWidth:c.indexWidth},labels:{minorLabelFontSize:c.minorLabelFontSize,minorLabelFont:c.minorLabelFont,minorLabelColor:n.getColorForShaders(n.handyColor(c.minorLabelColor)),minorLabelHaloRadius:c.minorLabelHaloRadius,minorLabelHaloColor:n.getColorForShaders(n.handyColor(c.minorLabelHaloColor)),majorLabelFontSize:c.majorLabelFontSize,majorLabelFont:c.majorLabelFont,majorLabelColor:n.getColorForShaders(n.handyColor(c.majorLabelColor)),majorLabelHaloRadius:c.majorLabelHaloRadius,majorLabelHaloColor:n.getColorForShaders(n.handyColor(c.majorLabelHaloColor)),indexLabelFontSize:c.indexLabelFontSize,indexLabelFont:c.indexLabelFont,indexLabelColor:n.getColorForShaders(n.handyColor(c.indexLabelColor)),indexLabelHaloRadius:c.indexLabelHaloRadius,indexLabelHaloColor:n.getColorForShaders(n.handyColor(c.indexLabelHaloColor))}}}const o=n.resolveNumber(r.interval,i,n.DEFAULT_CONTOUR_STYLE.interval),a={minorInterval:o,majorInterval:o*sd,indexInterval:o*od,minorColor:n.getColorForShaders(n.resolveColor(r.minorColor,i)),majorColor:n.getColorForShaders(n.resolveColor(r.majorColor,i)),indexColor:n.getColorForShaders(n.resolveColor(r.indexColor,i)),minorWidth:n.resolveNumber(r.minorWidth,i,n.DEFAULT_CONTOUR_STYLE.minorWidth),majorWidth:n.resolveNumber(r.majorWidth,i,n.DEFAULT_CONTOUR_STYLE.majorWidth),indexWidth:n.resolveNumber(r.indexWidth,i,n.DEFAULT_CONTOUR_STYLE.indexWidth)},l={minorLabelFontSize:n.resolveNumber(r.minorLabelFontSize,i,n.DEFAULT_CONTOUR_STYLE.minorLabelFontSize),minorLabelFont:n.resolveString(r.minorLabelFont,i,n.DEFAULT_CONTOUR_STYLE.minorLabelFont),minorLabelColor:n.getColorForShaders(n.resolveColor(r.minorLabelColor,i)),minorLabelHaloRadius:n.resolveNumber(r.minorLabelHaloRadius,i,n.DEFAULT_CONTOUR_STYLE.minorLabelHaloRadius),minorLabelHaloColor:n.getColorForShaders(n.resolveColor(r.minorLabelHaloColor,i)),majorLabelFontSize:n.resolveNumber(r.majorLabelFontSize,i,n.DEFAULT_CONTOUR_STYLE.majorLabelFontSize),majorLabelFont:n.resolveString(r.majorLabelFont,i,n.DEFAULT_CONTOUR_STYLE.majorLabelFont),majorLabelColor:n.getColorForShaders(n.resolveColor(r.majorLabelColor,i)),majorLabelHaloRadius:n.resolveNumber(r.majorLabelHaloRadius,i,n.DEFAULT_CONTOUR_STYLE.majorLabelHaloRadius),majorLabelHaloColor:n.getColorForShaders(n.resolveColor(r.majorLabelHaloColor,i)),indexLabelFontSize:n.resolveNumber(r.indexLabelFontSize,i,n.DEFAULT_CONTOUR_STYLE.indexLabelFontSize),indexLabelFont:n.resolveString(r.indexLabelFont,i,n.DEFAULT_CONTOUR_STYLE.indexLabelFont),indexLabelColor:n.getColorForShaders(n.resolveColor(r.indexLabelColor,i)),indexLabelHaloRadius:n.resolveNumber(r.indexLabelHaloRadius,i,n.DEFAULT_CONTOUR_STYLE.indexLabelHaloRadius),indexLabelHaloColor:n.getColorForShaders(n.resolveColor(r.indexLabelHaloColor,i))};return{lines:a,labels:l}}}const Uo=n.reserveTextureIndex(),Mo=n.reserveTextureIndex(),Ho=n.reserveTextureIndex(),Go=n.reserveTextureIndex(),Kt=64,ad=5,Vo=12,ld=5,cd=15,Vg=18,Zg=12,Wg=18,jg=.1,Xg=.3,je=[1.7,1],$g=300,Zo=.001,dd=1,qg=n.tileZoomToSize(n.tiles.maxRegionalZoom),Yg={localhost:{tileServer:"127.0.0.1:8181",tileProtocol:"http",subdomains:[]},relief_test:{tileServer:"tileserver.web-staging.2gis.ru",tileProtocol:"https",subdomains:["0","1","2"]},relief_test2:{tileServer:"tileserver.web-staging.2gis.ru",tileProtocol:"https",subdomains:["0","1","2"]},dem_pre_prod:{tileServer:"tileserver.web-staging.2gis.ru",tileProtocol:"https",subdomains:["0","1","2"]},dem_staging:{tileServer:"tileserver.web-staging.2gis.ru",tileProtocol:"https",subdomains:["0","1","2"]}},Dr=n.create$1(),Je=new Float64Array(16),Qi="changeScale",oi="negateScale",Qg=400,Jg=200;class Kg{constructor(e){this.demTextureMatrix=new Float64Array(16),this.demCorrectedFbVpToDemTex=new Float32Array(16),this.demTexToCorrectedTex=new Float32Array(16),this.correctedTexToDemTex=new Float32Array(16),this.isDemCorrectionEnabled=!1,this.demCorrectedScale=1,this.demFbVpMatrix=new Float64Array(16),this.demCorrectedFbVpMatrix=new Float64Array(16),this.demFramebufferId=n.INVALID_FRAMEBUFFER_ID,this.correctedDemFramebufferId=n.INVALID_FRAMEBUFFER_ID,this.flatFramebufferId=n.INVALID_FRAMEBUFFER_ID,this.identifyFlatFramebufferId=n.INVALID_FRAMEBUFFER_ID,this.hillshadeRampTextureId=NaN,this.hillshadeFramebufferId=n.INVALID_FRAMEBUFFER_ID,this.groundFramebufferId=n.INVALID_FRAMEBUFFER_ID,this.isGroundBufferValid=!1,this.lastStyleId=NaN,this.disableAnimation=!1,this.isAnimationStarted=!1,this.tilesRevision=0,this.tileSet=n.dem.tileSet,this.isEmptyTileVisible=!1,this.negateScaleMultiplier=1,this.modules=e,this.enabled=!1,this.sources=[],this.sourcesRevision=[],this.tileLayers=[],this.terrainAnimationScaleCoef=Zo,this.reliefTileType="vector",this.elevationSourceType="irregular",this.groundBuffer=new Float32Array,this.viewportDiffer=new n.Differ([]),this.demDiffer=new n.Differ([]),this.contoursManager=new Gg(this.modules)}enable(){if(this.isTerrainSupported===void 0&&(this.isTerrainSupported=Vl()),this.enabled||!this.isTerrainSupported)return;this.enabled=!0,this.viewportDiffer=new n.Differ([{path:"center",type:"vec2"},{path:"zoom",type:"number"},{path:"size",type:"vec2"},{path:"rotation",type:"number"},{path:"pitch",type:"number"}]),this.demDiffer=new n.Differ([{path:"demMode",type:"boolean"},{path:"elevation",type:"number"},{path:"minElevation",type:"number"}]),this.demFramebufferId=this.createDemFramebuffer(),this.correctedDemFramebufferId=this.createCorrectedDemFramebuffer(),this.hillshadeFramebufferId=this.createHillshadeFramebuffer(),this.flatFramebufferId=this.createFlatFramebuffer(),this.identifyFlatFramebufferId=this.createFlatIdentifyFramebuffer(),this.groundFramebufferId=this.createGroundFramebuffer(),this.fullscreenBuffer=this.modules.renderer.createBuffer(new Uint16Array([[0,0,0,0],[1,0,1,0],[0,1,0,1],[0,1,0,1],[1,0,1,0],[1,1,1,1]].reduce((t,i)=>{const[r,o,a,l]=i;return t.push(r*n.maxUint16Value,o*n.maxUint16Value,n.packTexCoords(a),n.packTexCoords(l)),t},[]))),this.hillshadeVao=_o(this.fullscreenBuffer,this.modules.renderer.getShaderProgram("demHillshade"));const e=this.modules.renderer.getShaderProgram("demElevationCopy");this.copyDemVao=_o(this.fullscreenBuffer,e),this.addDefaultSources(),this.modules.styleManager.setFramebufferId(this.modules.map.state.handyStyleId,n.DEM_STYLE_LAYER_ID,{hillshade:this.hillshadeFramebufferId,flatBottom:this.correctedDemFramebufferId}),this.updateRampTextureId(),this.contoursManager.enable(),this.startVerticalScaleAnimation()}setAnimationTerrain(e){this.modules.demManager.disableAnimation=!e}getAnimationTerrainStatus(){return this.modules.demManager.disableAnimation}onTerrainStyleChange(){this.updateRampTextureId(),this.contoursManager.onStyleChange()}getContourLabelManager(){return this.contoursManager.getContourLabelsManager()}disable(){var t,i,r,o;if(!this.enabled)return;this.dangerouslyDestroySourcesAndLayers(),(t=this.flatMapSource)==null||t.destroy(),this.flatMapSource=void 0,this.contoursManager.disable(),(i=this.hillshadeVao)==null||i.unbind(),(r=this.hillshadeVao)==null||r.remove(),(o=this.fullscreenBuffer)==null||o.remove(),this.modules.styleManager.setFramebufferId(this.modules.map.state.handyStyleId,n.DEM_STYLE_LAYER_ID,{hillshade:n.INVALID_FRAMEBUFFER_ID,flatBottom:n.INVALID_FRAMEBUFFER_ID}),this.modules.renderer.removeFramebuffer(this.hillshadeFramebufferId),this.modules.renderer.removeFramebuffer(this.demFramebufferId),this.modules.renderer.removeFramebuffer(this.correctedDemFramebufferId),this.modules.renderer.removeFramebuffer(this.flatFramebufferId),this.modules.renderer.removeFramebuffer(this.groundFramebufferId),this.enabled=!1;const e=this.modules.map.state;this.terrainAnimationScaleCoef=Zo,this.isAnimationStarted=!1,n.exist(Qi,e)&&n.stop(Qi,e),this.isEmptyTileVisible=!1,this.negateScaleMultiplier=1,this.emptyTileTimeout!==void 0&&(clearTimeout(this.emptyTileTimeout),this.emptyTileTimeout=void 0),n.exist(oi,e)&&n.stop(oi,e)}update(){var o,a,l,c;if(!this.enabled)return;const e=this.modules.map.state;this.lastStyleId!==e.handyStyleId&&(this.updateRampTextureId(),(o=this.meshSource)==null||o.updateStyleId(),(a=this.hillshadeTile)==null||a.children.forEach(d=>{d.attributes.styleId=e.handyStyleId}),this.modules.styleManager.setFramebufferId(e.handyStyleId,n.DEM_STYLE_LAYER_ID,{hillshade:this.hillshadeFramebufferId,flatBottom:this.correctedDemFramebufferId}),this.updateClearColor(),this.contoursManager.onStyleChange(),this.lastStyleId=e.handyStyleId);const t=this.updateTilesRevision(),i=this.viewportDiffer.check(e),r=this.demDiffer.check(e);if((t||i||r)&&(this.isGroundBufferValid=!1),(i||r)&&(this.updateMinElevation(),(l=this.flatMapSource)==null||l.update(),(c=this.meshSource)==null||c.update(),this.updateDemFramebufferMatrix(),this.modules.renderer.addRerenderEvent()),(t||i||r)&&this.contoursManager.update(),i||t){const d=this.isAnyEmptyTileVisible();d!==this.isEmptyTileVisible&&(this.emptyTileTimeout!==void 0&&clearTimeout(this.emptyTileTimeout),this.emptyTileTimeout=window.setTimeout(()=>{this.emptyTileTimeout=void 0,n.exist(oi,e)&&n.stop(oi,e);const u=this.negateScaleMultiplier,h=d?1:0,_=d?0:1;if(this.disableAnimation){this.negateScaleMultiplier=_;return}if(u===_)return;const f=Jg*(1-n.getIntermediateValue(h,_,u));n.start(oi,{easing:"linear"},e,u,_,f,1)},Qg),this.isEmptyTileVisible=d)}n.exist(oi,e)&&n.update(oi,{step:(d,u)=>{this.negateScaleMultiplier=u},complete:()=>{n.stop(oi,e)}},e),this.disableAnimation||(this.isAnimationStarted?n.update(Qi,{step:(d,u)=>{u===dd&&n.stop(Qi,e),this.terrainAnimationScaleCoef=u}},e):this.startVerticalScaleAnimation())}isIdle(){const e=this.modules.map.state;return(this.disableAnimation||!n.exist(Qi,e)&&!n.exist(oi,e))&&this.emptyTileTimeout===void 0}isEnabled(){return this.enabled}getDemFramebufferId(){return this.demFramebufferId}getGroundFramebufferId(){return this.groundFramebufferId}getCorrectedDemFramebufferId(){return this.correctedDemFramebufferId}getFlatFramebufferId(){return this.flatFramebufferId}getIdentifyFlatFramebufferId(){return this.identifyFlatFramebufferId}getHillshadeFramebufferId(){return this.hillshadeFramebufferId}getResolvedContourParams(){return this.contoursManager.getResolvedContourParams()}isContoursEnabled(){return this.contoursManager.isContoursEnabled()}getHillshadeRampTextureId(){return this.hillshadeRampTextureId}getElevation(e){if(this.enabled)for(let t=this.sources.length-1;t>=0;t--){const r=this.sources[t].getElevation(e);if(r!==void 0)return r}}getLabelsDemKey(e){if(!this.enabled||e.length===0)return;const t=new Set;for(const i of e){let r=null;for(const o of i.labels){if(o.type!==n.PreLabelType.Point)continue;r||(r=n.createTileInfo(o.tileCoords)),n.vertexTilePointToMapPoint(Dr,o.vertices,0,r);let a;for(let l=this.sources.length-1;l>=0;l--){const c=this.sources[l].getElevationTile(Dr);if(c!==void 0){a=c;break}}if(!a)return;t.add(a.key)}}if(t.size!==0)return Array.from(t).sort().join("|")}enrichWithElevation(e){var t;if(this.enabled)for(const i of e){let r=null;for(const o of i.labels)o.type===n.PreLabelType.Point&&(r||(r=n.createTileInfo(o.tileCoords)),n.vertexTilePointToMapPoint(Dr,o.vertices,0,r),o.demElevation=(t=this.getElevation(Dr))!=null?t:0)}}getMinElevation(){return this.sources.reduce((e,t)=>{const i=t.getMinElevation();return i===void 0?e:e===void 0?i:Math.min(e,i)},void 0)}updateMinElevation(){this.sources.forEach(e=>e.updateMinElevation())}getDemTextureSizePx(){return this.getDemTextureSize()*Kt}getMeshTiles(){return this.reliefTileType==="raster"?this.elevationSourceType==="regular"&&this.meshSource?Array.from(this.meshSource.meshTiles.values()):[]:this.tileLayers.reduce((e,t)=>{const i=t.getDisplayedTileObjects();return e.push(...i),e},[])}getReliefTileType(){return this.reliefTileType}getElevationSourceType(){return this.elevationSourceType}setReliefTileType(e){this.reliefTileType!==e&&(this.reliefTileType=e,this.enabled&&(this.dangerouslyDestroySourcesAndLayers(),this.elevationSourceType==="regular"?this.addRegularElevationSources():this.addIrregularElevationSources(),this.modules.renderer.addRerenderEvent()))}setElevationSourceType(e){this.elevationSourceType!==e&&(this.elevationSourceType=e,this.enabled&&(this.dangerouslyDestroySourcesAndLayers(),this.elevationSourceType==="regular"?this.addRegularElevationSources():this.addIrregularElevationSources(),this.modules.renderer.addRerenderEvent()))}getFlatMapTextures(){return this.flatMapSource?this.flatMapSource.textures.slice():[]}clearTextureBindings(){this.modules.renderer.disableTexture(0),this.modules.renderer.disableTexture(Uo),this.modules.renderer.disableTexture(Go),this.modules.renderer.disableTexture(Mo),this.modules.renderer.disableTexture(Ho)}setMeshMaxZoom(e){var t;this.meshMaxZoom=e,(t=this.meshSource)==null||t.setMaxZoom(e)}getVerticalScale(){const e=this.modules.map.state,t=this.modules.styleManager.getStyle(e.handyStyleId);if(!t)return 0;const i=t.dem.style,r=n.makeBinderContext(e.styleZoom,e.pitch,e.styleState,[]);return this.disableAnimation?n.resolveNumber(i.verticalScale,r)*this.negateScaleMultiplier:n.resolveNumber(i.verticalScale,r)*this.terrainAnimationScaleCoef*this.negateScaleMultiplier}getTilesRevision(){return this.tilesRevision}setTileSet(e){this.tileSet=e,this.enabled&&(this.disable(),this.enable())}getGroundPoint(e){if(!this.enabled||(this.updateGround(),!this.isGroundBufferValid))return;const t=this.modules.renderer.getFramebuffer(this.groundFramebufferId);if(!t)return;const i=t.renderTarget.options.size,r=e[0]-this.modules.map.state.viewport.left,o=e[1]-this.modules.map.state.viewport.top;if(r<0||r>i[0]-1||o<0||o>i[1]-1)return;const l=((i[1]-o-1)*i[0]+r)*4;if(this.groundBuffer[l+3]===0)return;const[d,u]=n.Mercator.toGeo([this.groundBuffer[l],this.groundBuffer[l+1]]);return[d,u,this.groundBuffer[l+2]]}startVerticalScaleAnimation(){const e=this.modules.map.state;this.modules.styleManager.getStyle(e.handyStyleId)&&(this.isAnimationStarted=!0,n.start(Qi,{easing:"linear"},e,Zo,dd,$g,1))}dangerouslyDestroySourcesAndLayers(){var e;this.sources.forEach(t=>t.destroy()),this.sources=[],this.sourcesRevision=[],(e=this.meshSource)==null||e.destroy(),this.meshSource=void 0,this.tileLayers.forEach(t=>{this.modules.tileManager.removeTileLayer(t),t.destroy()}),this.tileLayers=[],this.hillshadeTile&&(this.modules.tileManager.removeObject(this.hillshadeTile),this.hillshadeTile=void 0)}updateRampTextureId(){const e=this.modules.styleManager.getStyle(this.modules.map.state.handyStyleId);if(e!=null&&e.dem){const t=ep(this.modules.map.state,e.dem.style.shadingPalette,256);Number.isNaN(this.hillshadeRampTextureId)?this.hillshadeRampTextureId=this.modules.imageManager.addPreparedTexture(t):this.modules.imageManager.updatePreparedTexture(this.hillshadeRampTextureId,t)}}updateClearColor(){const e=this.modules.styleManager.getStyle(this.modules.map.state.handyStyleId);if(e!=null&&e.dem){const t=this.modules.renderer.getFramebuffer(this.flatFramebufferId);t&&(t.clearColor=n.getColorForShaders(e.background.color))}}updateGround(){if(this.enabled&&!this.isGroundBufferValid){const e=this.modules.tileManager.getTileObjects();this.modules.renderer.renderGround(e);const t=this.modules.renderer.getFramebuffer(this.groundFramebufferId);if(!t)return;const i=t.renderTarget.options.size;this.validateGroundBufferSize(i),this.modules.renderer.bindRenderTarget(t.renderTarget),this.modules.renderer.readPixelsFloat(0,0,i[0],i[1],this.groundBuffer),this.modules.renderer.bindRenderTarget(null),this.isGroundBufferValid=!0}}addDefaultSources(){this.dangerouslyDestroySourcesAndLayers(),this.elevationSourceType==="irregular"?this.addIrregularElevationSources():this.addRegularElevationSources(),this.flatMapSource=new uv(this.modules.map)}addRegularElevationSources(){var a;const e=this.modules.map.state,t=(l,c,d)=>n.DEM_TILE_URL_FUNCTION(e,l,c,d,this.tileSet==="dem"?"relief":this.tileSet),i=this.reliefTileType==="raster";i&&this.addElevationSource({url:t,minZoom:ad,maxZoom:8,attributes:{}}),this.addElevationSource({url:t,minZoom:i?9:ad,maxZoom:Vo,attributes:{}}),this.meshSource=new cv(this.modules.map,{maxZoom:this.meshMaxZoom});const r=this.hillshadeVao,o=(a=this.modules.renderer.symbolSettingsList.dem.hillshade)==null?void 0:a[0];if(r&&o){this.hillshadeTile=new n.TileObject("raster",[],this.modules,this.modules.map.state);const l={id:n.uniqId(),type:n.SceneObjectType.Tile,symbol:"dem",sink:"hillshade",tile:this.hillshadeTile,attributes:{layerId:n.DEM_STYLE_LAYER_ID,styleId:this.modules.map.state.handyStyleId,tileData:[]},start:0,count:6,attributesHash:"",layerSettings:o,vao:r,canRender:!0,renderingProperties:{}};this.hillshadeTile.children.push(l),this.modules.tileManager.addObject(this.hillshadeTile)}}addIrregularElevationSources(){var r;const{tileServer:e,tileProtocol:t,subdomains:i}=(r=Yg[this.tileSet])!=null?r:this.modules.map.state;this.addIrregularElevationSource({tileServer:e,tileProtocol:t,subdomains:i,tileSet:this.tileSet,minZoom:ld,maxZoom:cd})}updateTilesRevision(){let e=!1;return this.sources.forEach((t,i)=>{const r=t.getRevision();r!==this.sourcesRevision[i]&&(this.sourcesRevision[i]=r,e=!0)}),e&&this.tilesRevision++,e}addElevationSource(e){const t=new dv(n.sourceUuid(),this.modules,e);this.sources.push(t),this.sourcesRevision.push(t.getRevision());const{minZoom:i,maxZoom:r}=e,o=new n.TileLayer(i,r,i,r,this.modules,this.modules.map.state,t);this.modules.tileManager.addTileLayer(o),this.tileLayers.push(o)}addIrregularElevationSource(e){const t=new Ec(n.sourceUuid(),this.modules,e);this.sources.push(t),this.sourcesRevision.push(t.getRevision());const{minZoom:i,maxZoom:r}=e,o=new n.TileLayer(i,r,i,r,this.modules,this.modules.map.state,t,{useExtendedTilesBounds:!0});this.modules.tileManager.addTileLayer(o),this.tileLayers.push(o)}getDemTextureSize(){const e=this.modules.map.state.cameraConfig,t=this.modules.map.state.size[1]*e.viewportLimitRatio;return Math.min(Math.ceil(Math.hypot(t,t)/n.tileSizeZpt),Kt)}createGroundFramebuffer(){const e=this.modules.map.state.size,t=[0,0,0,0],i=new Pe({size:e,magFilter:C.NearestFilter,minFilter:C.NearestFilter,wrapS:C.ClampToEdgeWrapping,wrapT:C.ClampToEdgeWrapping,flipY:!0,type:C.Float});return this.modules.renderer.bindRenderTarget(i),this.modules.renderer.clearWithColor(t,!0),this.modules.renderer.bindRenderTarget(null),this.modules.renderer.addFramebuffer({clearColor:t,useDem:!0,clearDepth:!0,onResize:()=>{const r=this.modules.map.state.size;i.setSize(r),this.modules.renderer.bindRenderTarget(i),this.modules.renderer.clearWithColor(t,!0),this.modules.renderer.bindRenderTarget(null)},renderTarget:i,renderIndex:5,onRenderStart:()=>{},onRenderEnd:()=>{}})}createDemFramebuffer(){let e=this.getDemTextureSize()*Kt;const t=new Pe({size:[e,e],magFilter:C.LinearFilter,minFilter:C.LinearFilter,wrapS:C.ClampToEdgeWrapping,wrapT:C.ClampToEdgeWrapping,flipY:!0,type:C.Float,format:C.RgbaFormat}),i=[0,0,0,0];return this.modules.renderer.bindRenderTarget(t),this.modules.renderer.clearWithColor(i),this.modules.renderer.bindRenderTarget(null),this.modules.renderer.addFramebuffer({clearColor:i,onResize:()=>{const r=this.getDemTextureSize()*Kt;r!==e&&(e=r,t.setSize([e,e]),this.modules.renderer.bindRenderTarget(t),this.modules.renderer.clearWithColor(i),this.modules.renderer.bindRenderTarget(null))},renderTarget:t,getViewProjectionMatrix:()=>this.demFbVpMatrix,renderIndex:0,onRenderStart:()=>{this.clearTextureBindings()},onRenderEnd:()=>{this.isDemCorrectionEnabled=!1}})}createCorrectedDemFramebuffer(){const e=this.modules.renderer;let t=this.getDemTextureSize()*Kt;const i=new Pe({size:[t,t],magFilter:C.LinearFilter,minFilter:C.LinearFilter,wrapS:C.ClampToEdgeWrapping,wrapT:C.ClampToEdgeWrapping,flipY:!0,type:C.Float});return e.bindRenderTarget(i),e.clearWithColor([0,0,0,1]),e.bindRenderTarget(null),this.modules.renderer.addFramebuffer({onResize:()=>{const r=this.getDemTextureSize()*Kt;r!==t&&(t=r,i.setSize([t,t]),this.modules.renderer.bindRenderTarget(i),this.modules.renderer.clearWithColor([0,0,0,1]),this.modules.renderer.bindRenderTarget(null))},renderTarget:i,getViewProjectionMatrix:()=>this.demCorrectedFbVpMatrix,renderIndex:1,onRenderStart:()=>{var l;const r=(l=this.modules.renderer.getFramebuffer(this.demFramebufferId))==null?void 0:l.renderTarget.getTexture();if(!r||!this.copyDemVao)return;this.clearTextureBindings(),this.modules.renderer.bindRenderTarget(i),this.modules.renderer.setViewport(0,0,i.options.size[0],i.options.size[1]),this.modules.renderer.applyGpuState(Ac);const o=0;this.modules.renderer.enableTexture(r,o);const a=this.modules.renderer.getShaderProgram("demElevationCopy");this.modules.renderer.enableShaderProgram(a),this.modules.renderer.bindShaderProgram(a,{u_mat4_mvp:n.TEXTURE_COORDS_TO_WEBGL,u_sr2d_texture:o,u_mat4_dem_corrected:this.correctedTexToDemTex}),this.modules.renderer.bindVao(this.copyDemVao),this.modules.renderer.drawTriangles(0,6),this.modules.renderer.bindRenderTarget(null),this.isDemCorrectionEnabled=!0},useDem:!0})}createHillshadeFramebuffer(){let e=this.getDemTextureSize()*Kt;const t=new Pe({size:[e,e],magFilter:C.LinearFilter,minFilter:C.LinearFilter,wrapS:C.ClampToEdgeWrapping,wrapT:C.ClampToEdgeWrapping,format:C.RgbFormat,flipY:!0});return this.modules.renderer.addFramebuffer({clearColor:[0,0,0,0],onResize:()=>{const i=this.getDemTextureSize()*Kt;i!==e&&(e=i,t.setSize([e,e]),this.modules.renderer.bindRenderTarget(t),this.modules.renderer.bindRenderTarget(null))},renderTarget:t,getViewProjectionMatrix:()=>this.demFbVpMatrix,renderIndex:2,onRenderStart:()=>{this.clearTextureBindings()},useDem:!0})}createFlatFramebuffer(){const e=this.modules.renderer.getPixelRatio(),t=this.modules.map.state.size,i=new Pe({size:[Math.trunc(t[0]*je[0]*e),Math.trunc(t[1]*je[1]*e)],magFilter:C.LinearFilter,minFilter:C.LinearFilter,wrapS:C.ClampToEdgeWrapping,wrapT:C.ClampToEdgeWrapping});return this.modules.renderer.addFramebuffer({clearColor:this.modules.renderer.clearColor,onResize:()=>{const r=this.modules.map.state.size;i.setSize([Math.trunc(r[0]*je[0]*e),Math.trunc(r[1]*je[1]*e)]),this.modules.renderer.bindRenderTarget(i),this.modules.renderer.bindRenderTarget(null)},renderTarget:i,renderIndex:3,onRenderStart:()=>{this.modules.renderer.disableTexture(0)}})}createFlatIdentifyFramebuffer(){const e=this.modules.map.state.size,t=new Pe({size:[Math.trunc(e[0]*je[0]*n.identify.pixelDensity),Math.trunc(e[1]*je[1]*n.identify.pixelDensity)],magFilter:C.NearestFilter,minFilter:C.NearestFilter,wrapS:C.ClampToEdgeWrapping,wrapT:C.ClampToEdgeWrapping});return this.modules.renderer.addFramebuffer({clearColor:Ui,onResize:()=>{const i=this.modules.map.state.size;t.setSize([Math.trunc(i[0]*je[0]*n.identify.pixelDensity),Math.trunc(i[1]*je[1]*n.identify.pixelDensity)]),this.modules.renderer.bindRenderTarget(t),this.modules.renderer.bindRenderTarget(null)},renderTarget:t,renderIndex:4,onRenderStart:()=>{this.modules.renderer.disableTexture(0)}})}updateDemFramebufferMatrix(){const e=this.modules.map.state,t=Math.trunc(e.styleZoom),i=Math.min(t,this.getReliefTileType()==="raster"?Zg:Vg),r=n.tileZoomToSize(i),o=r*this.getDemTextureSize(),a=r/Kt,l=[Math.trunc(e.center[0]/a)*a+a/2,Math.trunc(e.center[1]/a)*a+a/2],c=[l[0]-o/2,l[1]-o/2,0],d=[];n.sub(d,this.modules.camera.position,e.center);const u=n.len(d);n.normalize$1(d,d);const h=Math.max(o/2-u-a-qg/2,0),_=Math.min(h,(o/2-u-a)*Math.sin(e.pitch/e.maxPitch*(Math.PI/2)));_>0&&(n.scale$2(d,d,_),d[0]=Math.trunc(d[0]/a)*a,d[1]=Math.trunc(d[1]/a)*a,n.sub(c,c,d)),n.fromTranslationScale(Je,c,[o,o,n.tileHeight]),n.invert(this.demTextureMatrix,Je),n.multiply(this.demFbVpMatrix,n.TEXTURE_COORDS_TO_WEBGL,this.demTextureMatrix);const f=Math.min(t,Wg);this.demCorrectedScale=Re(2,f-i);const v=n.tileZoomToSize(f)*this.getDemTextureSize(),g=[l[0]-v/2,l[1]-v/2,0];n.fromTranslationScale(Je,g,[v,v,n.tileHeight]),n.invert(Je,Je),n.multiply(this.demCorrectedFbVpMatrix,n.TEXTURE_COORDS_TO_WEBGL,Je),n.fromScaling(Je,[1/this.demCorrectedScale,1/this.demCorrectedScale,1]),n.multiply(this.demCorrectedFbVpToDemTex,n.WEBGL_COORDS_TO_TEXTURE,Je),n.fromScaling(Je,[1/this.demCorrectedScale,1/this.demCorrectedScale,1]),n.multiply(Je,Je,n.TEXTURE_COORDS_TO_WEBGL),n.multiply(this.correctedTexToDemTex,n.WEBGL_COORDS_TO_TEXTURE,Je),n.fromScaling(Je,[this.demCorrectedScale,this.demCorrectedScale,1]),n.multiply(Je,Je,n.TEXTURE_COORDS_TO_WEBGL),n.multiply(this.demTexToCorrectedTex,n.WEBGL_COORDS_TO_TEXTURE,Je)}validateGroundBufferSize(e){const t=e[0]*e[1]*4;this.groundBuffer.length!==t&&(this.groundBuffer=new Float32Array(t))}isAnyEmptyTileVisible(){for(const e of this.tileLayers){const t=e.getSource();if(t instanceof Ec){for(const i of e.gridState.viewportTiles)if(t.isTileEmpty(i))return!0}}return!1}}function ep(s,e,t){const i=n.makeBinderContext(s.styleZoom,s.pitch,s.styleState,[]),r=[],o=t-1;for(let a=0;a<t;a++){const l=a/o,c=n.sample(e,l,i)*256;r.push(c)}return new C(new Uint8Array(r),{size:[t,1],format:C.AlphaFormat,magFilter:C.LinearFilter,minFilter:C.LinearFilter,wrapS:C.ClampToEdgeWrapping,wrapT:C.ClampToEdgeWrapping})}const ai=(s,e,t,i)=>{t=qo(t,s,e),t.length>0&&s.metrics.firstcontent===void 0&&(s.metrics.firstcontent=performance.now()-s.metrics.start);const{environmentManager:r}=e;_d(t,i),s.globeMode&&(r.renderStars(),r.renderGlobeHaloBackground()),jo(s,e,t,i)};let Wo=!1;const jo=(s,e,t,i)=>{Wo=!1,lp(t,s,e).forEach(r=>tp(s,e,r,i))},tp=(s,e,t,i)=>{hp(e.styleManager,t,s,e).forEach(r=>{hd(e.styleManager,r[0])?ip(s,e,r,i):ud(s,e,r,i)})},ip=(s,e,t,i)=>{const r=hd(e.styleManager,t[0]);if(!r)return;const o=(a,l)=>{l>=r.orderBy.length?ud(s,e,a,i):mp(r.orderBy[l],a,s,e).forEach(c=>o(c,l+1))};o(t,0)},ud=(s,e,t,i)=>{t.sort((r,o)=>r.tile.zoomLevel-o.tile.zoomLevel),up(e.styleManager,t,s,e).forEach(r=>np(s,e,r,i))},np=(s,e,t,i)=>{fp(t,i)&&_p(t,s,e).forEach(r=>rp(s,e,r,i))},rp=(s,e,t,i)=>{var l;const r=t[0],o=bp(e.styleManager,r);if(!o||((l=o==null?void 0:o.style)==null?void 0:l.visibility)==="hidden")return;const a=o.selectedIdx;a!==void 0&&t.sort((c,d)=>{var _,f;const u=Number((_=c.attributes.tileData[a])!=null?_:0),h=Number((f=d.attributes.tileData[a])!=null?f:0);return u-h}),r.type===n.SceneObjectType.Custom?(i.useCustomLayerState(o),e.styleManager.callCustomLayerRender(r.attributes.layerId),i.resetAfterCustomLayer()):vp(t,s,e).forEach(c=>sp(s,e,c,i,o))},sp=(s,e,t,i,r)=>{r.type==="point"&&!Wo&&s.globeMode&&(Wo=!0,e.environmentManager.renderGlobeHalo()),i.useProgram(t[0],r)&&gp(t,s,e).forEach(o=>{op(s,e,o,i,r)})},op=(s,e,t,i,r)=>{i.useState(t[0],r),pp(t,s,e).forEach(o=>{i.drawSymbol(o,r,s,e)})};function hd(s,e){const t=s.getStyle(e.attributes.styleId);if(!t)return;const i=t.layersById[e.attributes.layerId];if(!i||i.groupId===void 0)return;const r=t.groupsById[i.groupId];if(r&&r.type!=="group"){n.log(`Expecting layer with type 'group' but got '${r.type}'`);return}return r}const ap=(s,e)=>Number(s)-Number(e),Ji=s=>(e,t,i)=>{const r={};for(let l=0;l<e.length;l++){const c=e[l],d=s(c,t,i),u=r[d];u===void 0?r[d]=[c]:u.push(c)}const o=Object.keys(r);o.sort(ap);const a=[];for(let l=0;l<o.length;l++)a.push(r[o[l]]);return a},Xo=s=>(e,t,i)=>{const r=new Map;for(let o=0;o<e.length;o++){const a=e[o],l=s(a,t,i);r.has(l)?r.get(l).push(a):r.set(l,[a])}return r},lp=Ji(s=>{const{styleId:e}=s.attributes;return e===n.DYNAMIC_STYLE_ID?1:-e}),cp=(s,e,t)=>{const i=s.getStyle(e);if(!i)return n.log(`Cannot get style with id=${e} for renderIndex`),NaN;const r=i.layersById[t];return r?r.renderIndex:NaN},dp=(s,e,t)=>{const i=s.getStyle(e);if(!i)return n.log(`Cannot get style with id=${e} for renderIndex`),NaN;const r=i.layersById[t];return r?r.groupIndex||0:NaN},up=(s,e,t,i)=>Ji(r=>dp(s,r.attributes.styleId,r.attributes.layerId))(e,t,i),hp=(s,e,t,i)=>Ji(r=>cp(s,r.attributes.styleId,r.attributes.layerId))(e,t,i),_p=Ji(s=>s.type===n.SceneObjectType.Custom?0:s.layerSettings.subRenderIndex||0),_d=(s,e)=>{const t=new Set;s.forEach(i=>{if(i.type===n.SceneObjectType.Custom)return;const r=$o(i);t.has(r)||(t.add(r),e.setProgramBinder(i))})},fp=(s,e)=>{const t=new Set;let i=!0;for(const r of s){if(r.type===n.SceneObjectType.Custom)continue;const o=$o(r);t.has(o)||(t.add(o),e.prepareProgram(r)||(i=!1))}return i},mp=(s,e,t,i)=>Ji((r,o)=>{const a=n.makeBinderContext(o.styleZoom,o.pitch,o.styleState,r.attributes.tileData);return n.resolveNumber(s,a,0)})(e,t,i),$o=s=>{var e;return(e=s.shaderDefinitions)!=null&&e.hash?s.layerSettings.programName+"_"+s.shaderDefinitions.hash:s.layerSettings.programName},vp=Xo($o),gp=Xo(s=>s.layerSettings.stateBinder),pp=Xo(s=>{var t;const e=(t=s.uniformGroupKey)!=null?t:s.uniformGroupKey=s.sink+"_"+s.attributesHash;return s.tile.readiness===1?e:e+"_"+s.tile.readiness}),xp=Ji(s=>s.tile.zoomLevel);function bp(s,e){const t=s.getStyle(e.attributes.styleId);if(t)return t.layersById[e.attributes.layerId]}function qo(s,e,t){for(const i of s)i.type!==n.SceneObjectType.Custom&&(i.canRender=Yo(i,t,e));return s.filter(i=>i.canRender)}function Yo(s,e,t){var r;if(!s.layerSettings.cullMethod)return!0;const i=e.styleManager.getStyleLayerForObject(s);return!(!i||((r=i==null?void 0:i.style)==null?void 0:r.visibility)==="hidden"||!s.layerSettings.cullMethod(s,e,t,i))}const fd=[0,0,0,0],ei=(s,e,t,i,r,o)=>{let a;const l={terrain3d:!!r,noEffects:!!o,drawSymbol:(c,d,u,h)=>{const _=c[0];if(_)if(Sp(_)&&(d.type==="overpass"||d.type==="tunnel"||d.type==="gltfModel")&&!_.layerSettings.shadow&&!_.layerSettings.depthTest){let f;if(d.type==="gltfModel"&&(f=fd),l.renderTierTexture(_,d,!1,f),!l.useProgram(_,d))return;if(l.useState(_),Qo(c,d,u,h,l),u.hiddenImmersiveRoutesEnabled&&!_.layerSettings.identify&&d.type!=="gltfModel"){if(l.renderTierTexture(_,d,!0),!l.useProgram(_,d))return;h.renderer.applyGpuState(hv,d),Qo(c,d,u,h,l)}}else Qo(c,d,u,h,l)},prepareProgram:c=>!!e.renderer.getReadyShaderProgram(c.layerSettings.programName,c.shaderDefinitions),useProgram:(c,d)=>{const{layerBinder:u,programName:h,programBinder:_,commonBinder:f}=c.layerSettings,m=e.renderer.getReadyShaderProgram(h,c.shaderDefinitions);return m?(e.renderer.enableShaderProgram(m),f&&!e.renderer.isUboSupported()&&f(m,s,e),_==null||_(m,s,e,r,o),u==null||u(m,s,e,d,o),!0):!1},setProgramBinder:c=>{const d=c.layerSettings.programBinder,u=e.renderer.isUboSupported()?void 0:c.layerSettings.commonBinder,h=e.renderer.getShaderProgramIfReady(c.layerSettings.programName,c.shaderDefinitions);return h?((d||u)&&(e.renderer.enableShaderProgram(h),u==null||u(h,s,e),d==null||d(h,s,e,r,o)),!0):!1},useState:(c,d)=>{e.renderer.applyGpuState(c.layerSettings.stateBinder,d,c)},useCustomLayerState:c=>{e.renderer.applyGpuState(Tv,c)},resetAfterCustomLayer:()=>{e.renderer.resetStateAfterExternalRender(),e.renderer.setRenderTarget(i)},useCanvas:()=>{e.renderer.setRenderTarget(i)},renderTierTexture:(c,d,u,h)=>{const{viewport:_,size:f}=s,m=window.devicePixelRatio,v=!!c.layerSettings.identify,g=c.attributes.meshTier,p=u?"hidden":"visible";let x="depth",S;if(u)v&&(x="identify-depth");else if(v)x="identify";else{const A=n.makeBinderContext(s.styleZoom,s.pitch,s.styleState,c.attributes.tileData);S=h!=null?h:n.resolveColor(d.style.color,A).value,x=S.join(":")}const b=v?e.renderer.getMapMeshIdFramebufferId():e.renderer.getMapMeshFramebufferId(),T=e.renderer.getFramebuffer(b),y=`${p}|tier:${g}|fb:${b}|clear:${x}|${i?"target":"canvas"}`;if(!T||y===a)return;a=y;const E=ei(s,e,void 0,i,!1,!0);if(e.renderer.disableTexture(0),e.renderer.bindRenderTarget(T.renderTarget),e.renderer.setViewport(0,0,T.renderTarget.options.size[0],T.renderTarget.options.size[1]),u){const A=v?Ui:fd;e.renderer.clearWithColor(A,!0,-1)}else if(v)e.renderer.clearWithColor(Ui,!0);else{const A=S;e.renderer.clearWithColor([A[0]/255,A[1]/255,A[2]/255,A[3]/255],!0)}const P=t==null?void 0:t[g];if(P){P.tileObjects.forEach(L=>{var D,B;L.updateMvpMatrix((B=(D=T.getViewProjectionMatrix)==null?void 0:D.call(T))!=null?B:e.camera.viewProjectionMatrix,void 0)});const A=u?P.objects.filter(L=>{var D;if(L.type!==n.SceneObjectType.Custom){if(L.layerSettings.stateBinder(e,L).depthTest&&!L.layerSettings.isOverlappedObject)return!0;const B=e.styleManager.getStyleLayer(L.attributes.styleId,L.attributes.layerId);if(B)return((D=B.gpuState)==null?void 0:D.depthTest)===!0}return!1}):P.objects,F=qo(A,s,e);jo(s,e,F,E),P.tileObjects.forEach(L=>L.updateMvpMatrix(e.camera.viewProjectionMatrix)),_d(P.objects,l)}i?(e.renderer.bindRenderTarget(i),e.renderer.setViewport(0,0,i.options.size[0],i.options.size[1])):(e.renderer.bindRenderTarget(null),e.renderer.setViewport(_.left*m,_.bottom*m,f[0]*m,f[1]*m))},copy:(c,d,u)=>ei(s,e,t,c,d,u)};return l},Qo=(s,e,t,i,r)=>{const o=s[0],a=o.layerSettings,l=i.renderer.getShaderProgram(a.programName,o.shaderDefinitions);a.objectBinder(l,t,i,o,e,r.terrain3d),o.layerSettings.zoomBinder?xp(s,t,i).forEach(c=>{var d,u;l&&((u=(d=o.layerSettings).zoomBinder)==null||u.call(d,l,t,i,c[0],e,r.terrain3d)),c.forEach(h=>md(h,i,l,t,r,e))}):s.forEach(c=>md(c,i,l,t,r,e))},md=(s,e,t,i,r,o)=>{var c;const{renderer:a}=e,l=s.tile;for(const d of l.modelMatrices.keys()){if(l.renderModelMatrix=l.modelMatrices.get(d),l.renderMvpMatrix=l.mvpMatrices.get(d),l.renderDemMatrix=l.demMatrices.get(d),l.renderFlatMapTexMatrix=l.flatMapTexMatrices.get(d),!s.layerSettings.tileBinder(t,i,e,s,o,r))continue;a.bindVao(s.vao);const{start:h,count:_,instanceCount:f}=s,m=(c=s.drawMode)!=null?c:n.GL_TRIANGLES,v=s.vao.getElementsGLType();if(v!==null?f?a.drawInstancedElements(m,_,v,h,f):a.drawElements(m,_,v,h):f?a.drawInstancedArrays(m,h,_,f):a.drawArrays(m,h,_),i.collectStats){i.stats.drawCount++,i.stats.vertexCount+=(f!=null?f:1)*_,i.stats.drawCountBySymbol[s.symbol]?i.stats.drawCountBySymbol[s.symbol]++:i.stats.drawCountBySymbol[s.symbol]=1;const g=a.triangleCountByDrawMode(m,_);i.stats.triangleCount+=(f!=null?f:1)*g}}};function Sp(s){return s.symbol==="mapMesh"||s.symbol==="gltfModel"&&s.attributes.meshTier!==void 0}const vd=n.create$1(),yp=n.create$1(),gd=n.create$2(),Jo=n.create$1(),Tp=n.fromValues(0,0,1),Ep=n.create$1(),Cp=.3,Ip=1/2e7,Pp=.01,Ap=1e-8,Lp=[1,1,1,1],pd=n.reserveTextureIndex();class Rp{constructor(e,t){this.clipToShadowMatrix=new Float32Array(16),this.baseBias=n.defaultShadowsSettings.bias,this.bias=0,this.orthoAnisotropy=[1,3],this.shadowMapParams=new Float32Array([n.defaultShadowsSettings.textureSize[0],n.defaultShadowsSettings.textureSize[1],n.defaultShadowsSettings.shadowRadius,1]),this.volumeMultiplier=2.5,this.volumeMinSize=25e3,this.discreteVolume=!1,this.volumeSizeStep=Re(2,15),this.adaptiveVerticalSize=!0,this.debugDraw=!1,this.shadowMatrix=new Float64Array(16),this.shadowLightIndex=-1,this.orthoMath=new Float64Array(16),this.renderTarget=null,this.copyProgram=null,this.debugVao=null,this.debugSize=400,this.shadowLightDir=null,this.prevShadowLightDir=n.create$1(),this.modules=t,this.mapState=e}get texture(){if(!this.renderTarget)return null;const e=this.renderTarget.getDepthAttachment();return e instanceof C?e:this.renderTarget.getTexture()}setShadowResolution(e,t){this.shadowMapParams[0]=e,this.shadowMapParams[1]=t,this.renderTarget&&this.renderTarget.setSize([e,t])}update(){if(cr())return;this.shadowLightDir=null,this.shadowLightIndex=-1;const{handyStyleId:e}=this.mapState,t=this.modules.styleManager.getStyle(e);if(!t||!t.light.lightingModesResolved){this.renderTarget&&this.renderTarget.remove();return}const i=t.light.lightingModesResolved;for(const A in i){const F=i[A],L=F.shadowLightIndex;if(L===0||L===1){this.shadowLightDir=L===0?F.dir1Direction:F.dir2Direction,this.shadowMapParams[2]=F.shadowRadius,this.shadowLightIndex=L;break}}const r=this.shadowLightDir&&!this.modules.map.getFeatureFlag("shadowsOff");if(r||(this.shadowLightIndex=-1),r?this.renderTarget||(this.renderTarget=this.createRenderTarget()):this.renderTarget&&this.renderTarget.remove(),!r||!this.shadowLightDir||!this.renderTarget)return;const o=n.squaredDistance(this.shadowLightDir,this.prevShadowLightDir)>Ap;if(n.copy$1(this.prevShadowLightDir,this.shadowLightDir),this.modules.renderCacheManager.hasReadyCache()){if(!o)return;this.modules.renderer.addRerenderEvent()}const a=this.modules.map.state.center,l=this.modules.camera.position[2];let c=Math.max(this.volumeMultiplier*l);this.discreteVolume&&(c=c-c%this.volumeSizeStep),c=Math.max(c,this.volumeMinSize);let d=this.baseBias;this.modules.renderer.isShadowSamplerSupported()&&(d*=.5),this.shadowMapParams[3]=d/c,this.bias=d*Ip*Math.sqrt(c),this.bias=Math.min(this.bias,Pp);let u=1;if(this.adaptiveVerticalSize){const A=Math.abs(n.dot(this.shadowLightDir,Tp));u=Math.max(A,Cp)}const h=c,_=u*c,f=this.mapState.demMode?6:3,m=f*c;this.orthoAnisotropy[0]=u,this.orthoAnisotropy[1]=f,n.ortho(this.orthoMath,-h,h,-_,_,-m,m);const v=n.fromValues(this.shadowLightDir[1],-this.shadowLightDir[0],0);n.normalize(v,v),n.cross(Jo,v,this.shadowLightDir);const g=gd;n.lookAt(g,Ep,this.shadowLightDir,Jo);const p=n.transformMat4$1(vd,a,g),x=2*h/this.shadowMapParams[0],S=2*_/this.shadowMapParams[1],b=n.fromValues(p[0]-p[0]%x,p[1]-p[1]%S,p[2]),T=n.invert(g,g),y=n.transformMat4$1(yp,b,T!=null?T:n.identity(gd)),E=n.add$1(vd,y,this.shadowLightDir);n.lookAt(this.shadowMatrix,y,E,Jo),n.multiply(this.shadowMatrix,this.orthoMath,this.shadowMatrix);const P=this.modules.camera.viewProjectionMatrixInverse;n.multiply(this.clipToShadowMatrix,this.shadowMatrix,P)}drawShadowMap(e){if(!this.shadowLightDir||!this.renderTarget||this.modules.renderCacheManager.hasReadyCache())return;this.modules.renderer.resetStateAfterExternalRender();const t=this.modules.map.state.demMode,i=ei(this.mapState,this.modules,void 0,this.renderTarget,t),r=new Set,o=[];for(const l of e)for(const c of l.shadowChildren){const d=this.modules.styleManager.getStyleLayerForObject(c);if(!d||d.castShadows===!1)continue;const u=mr(d,this.modules,this.mapState);!u||u.lightConfig.shadowLightIndex===-1||(o.push(c),r.add(l))}if(t){const l=this.modules.demManager.getMeshTiles();for(const c of l)for(const d of c.shadowChildren)o.push(d),r.add(c)}const a=t?this.modules.demManager.demTextureMatrix:void 0;r.forEach(l=>{l.updateMvpMatrix(this.shadowMatrix,a)}),this.modules.renderer.bindRenderTarget(this.renderTarget),this.modules.renderer.applyGpuState(Oc),this.modules.renderer.clearWithColor(Lp,!0),this.modules.renderer.setViewport(0,0,this.renderTarget.options.size[0],this.renderTarget.options.size[1]),ai(this.mapState,this.modules,o,i),this.modules.renderer.bindRenderTarget(null)}drawDebugFbIfNeeded(){if(!this.debugDraw){this.copyProgram&&(this.copyProgram=null),this.debugVao&&(this.debugVao.remove(),this.debugVao=null);return}if(!this.texture)return;if(this.modules.renderer.resetStateAfterExternalRender(),(!this.copyProgram||!this.debugVao)&&(this.copyProgram||(this.copyProgram=this.createDebugProgram()),!this.debugVao)){const r=this.modules.renderer.createBuffer(new Uint8Array([-1,-1,1,-1,1,1,-1,1]));this.debugVao=_i(r,this.copyProgram)}const e=this.mapState.viewport,t=this.modules.renderer.getViewportSize(),i=this.debugSize;this.modules.renderer.bindRenderTarget(null),this.modules.renderer.setViewport(t[0]+e.left-i,e.bottom,i,i),this.modules.renderer.applyGpuState(si),this.modules.renderer.enableShaderProgram(this.copyProgram),this.modules.renderer.bindShaderProgram(this.copyProgram,{u_texture:1}),this.modules.renderer.enableTexture(this.texture,1),this.modules.renderer.bindVao(this.debugVao),this.modules.renderer.drawTrianglesFan(0,4)}getMemoryFootprint(){var t,i;const e={renderTarget:(i=(t=this.renderTarget)==null?void 0:t.memSizeGPU())!=null?i:0};return{gpu:V(I({},e),{"--sum":n.getTotalMemory(e)})}}createRenderTarget(){const e=[this.shadowMapParams[0],this.shadowMapParams[1]];return this.modules.renderer.isDepthTextureSupported()?new Pe({size:e,magFilter:C.LinearFilter,minFilter:C.LinearFilter,depthTexture:!0,hasColorOutput:!1,compareFunc:C.CompareRefToTexture}):new Pe({size:e,magFilter:C.NearestFilter,minFilter:C.NearestFilter,wrapS:C.ClampToEdgeWrapping,wrapT:C.ClampToEdgeWrapping,flipY:!1,type:C.UnsignedByte,useHighDepthPrecision:!0})}createDebugProgram(){const e=[];this.modules.renderer.isDepthTextureSupported()&&e.push({type:"IS_DEPTH_TEXTURE"});const t=n.Shader.createShaderDefinitions(e);return this.modules.renderer.getShaderProgram("copy",t)}}class Ko{constructor(e,t,i){this.output=e,this.input=t,this.modules=i,this.enabled=!0}}class Fp extends Ko{constructor(e,t,i,r){super(e,t,i),this.name=Fi.TAA,this.jitter=[0,0],this.numMixedFrames=0,this.samples=16,this.vao=null,this.buffer=r,this.jitterSequence=this.generateJitterSequence(this.samples)}onBeforeRender(e){if(this.jitter[0]=0,this.jitter[1]=0,e.aaMode!==Et.TAA||e.globeMode||!this.canRender()){this.enabled=!1,this.numMixedFrames=0;return}if(this.numMixedFrames>=this.samples)return;this.modules.renderer.addRerenderEvent(),this.enabled=!0;const t=window.devicePixelRatio,i=e.size,r=this.jitterSequence[this.numMixedFrames];this.jitter[0]=r[0]/Math.ceil(i[0]*t),this.jitter[1]=r[1]/Math.ceil(i[1]*t)}render(){var r;const e=1/(this.numMixedFrames+1),t=this.modules.renderer.getShaderProgram("taa");this.vao||(this.vao=_i(this.buffer,t)),this.modules.renderer.bindRenderTarget(this.output),this.modules.renderer.bindVao(this.vao);const i=(r=this.input)==null?void 0:r.getTexture();i&&this.modules.renderer.enableTexture(i,0),this.modules.renderer.enableShaderProgram(t),this.modules.renderer.bindShaderProgram(t,{u_texture:0,u_float_mix_coef:e}),this.modules.renderer.drawTrianglesFan(0,4),this.numMixedFrames++}onAfterRender(){}resize(e){this.output.setSize(e),this.numMixedFrames=0}isReady(e){return e!=null&&e.ignoreLayerAnimation&&this.modules.map.core.hasActiveLayerAnimation()?!0:this.numMixedFrames>=this.samples}canRender(){return!this.modules.renderer.isNeedRerender()}generateJitterSequence(e){const t=[],i=n.generateHaltonSequence(e),r=i.base2,o=i.base3;t.push([0,0]);for(let a=0;a<r.length;++a)t.push([2*r[a]-1,2*o[a]-1]);return t}}class Dp extends Ko{constructor(e,t,i,r){super(e,t,i),this.name=Fi.FXAA,this.vao=null,this.buffer=r}onBeforeRender(e){this.enabled=e.aaMode===Et.FXAA&&e.stillness>0}render(){var i;const e=(i=this.input)==null?void 0:i.getTexture();if(e)this.modules.renderer.enableTexture(e,0);else throw new Error("FXAA: input texture is not available");const t=this.modules.renderer.getShaderProgram("fxaa");if(this.vao||(this.vao=_i(this.buffer,t)),this.modules.renderer.bindRenderTarget(this.output),this.modules.renderer.bindVao(this.vao),this.modules.renderer.enableShaderProgram(t),this.modules.renderer.bindShaderProgram(t,{u_texture:0}),!this.modules.renderer.isUboSupported()){const r=this.modules.map.state;ne(t,r,this.modules)}this.modules.renderer.drawTrianglesFan(0,4)}onAfterRender(){}resize(e){this.output.setSize(e)}isReady(){return!0}}class zp extends Ko{constructor(e,t,i,r){super(e,t,i),this.name=Fi.SMAA,this.edgeTarget=null,this.weightTarget=null,this.areaTexture=null,this.searchTexture=null,this.numMixedFrames=0,this.samples=2,this.buffer=r;const a={size:this.modules.renderer.getViewportSize(),magFilter:C.LinearFilter,minFilter:C.LinearFilter,wrapS:C.ClampToEdgeWrapping,wrapT:C.ClampToEdgeWrapping,flipY:!1,depthTexture:!1};this.edgeTarget=new Pe(a),this.weightTarget=new Pe(a),this.initializeLUTs()}onBeforeRender(e){if(e.aaMode!==Et.SMAA){this.enabled=!1,this.numMixedFrames=0;return}this.numMixedFrames>=this.samples||(this.modules.renderer.addRerenderEvent(),this.enabled=!0)}render(){var t;if(!this.enabled||!this.areaTexture||!this.searchTexture)return;const e=(t=this.input)==null?void 0:t.getTexture();e&&(this.modules.renderer.applyGpuState(si),this.renderEdgeDetection(this.edgeTarget,e),this.renderWeightCalculation(this.weightTarget),this.modules.renderer.applyGpuState(Bc),this.renderNeighborhoodBlending(),this.numMixedFrames++)}onAfterRender(){}resize(e){this.output.setSize(e),this.edgeTarget&&this.edgeTarget.setSize(e),this.weightTarget&&this.weightTarget.setSize(e),this.numMixedFrames=0}isReady(){return this.areaTexture!==null&&this.searchTexture!==null&&this.numMixedFrames>=this.samples}dispose(){this.edgeTarget=null,this.weightTarget=null,this.areaTexture=null,this.searchTexture=null}base64ToFloat32RGBA(e){return new Promise((t,i)=>{const r=new Image;r.src=e,r.onload=()=>{const o=document.createElement("canvas");o.width=r.width,o.height=r.height;const a=o.getContext("2d");if(!a){i(new Error("Could not get canvas context"));return}a.drawImage(r,0,0);const c=a.getImageData(0,0,r.width,r.height).data,d=new Float32Array(c.length);for(let u=0;u<c.length;u++)d[u]=c[u]/255;t(d)},r.onerror=()=>i(new Error("Image loading error"))})}initializeLUTs(){this.base64ToFloat32RGBA(n.SMAA_AREA_PNG_BASE64).then(e=>{this.areaTexture=new C(e,{size:[160,560],format:C.RgbaFormat,type:C.Float,magFilter:C.NearestFilter,minFilter:C.LinearFilter,wrapS:C.ClampToEdgeWrapping,wrapT:C.ClampToEdgeWrapping,generateMipmaps:!1,flipY:!1})}),this.base64ToFloat32RGBA(n.SMAA_SEARCH_PNG_BASE64).then(e=>{this.searchTexture=new C(e,{size:[64,16],format:C.RgbaFormat,type:C.Float,magFilter:C.NearestFilter,minFilter:C.NearestFilter,wrapS:C.ClampToEdgeWrapping,wrapT:C.ClampToEdgeWrapping,generateMipmaps:!1,flipY:!0})})}renderEdgeDetection(e,t){const i=this.modules.renderer.getShaderProgram("smaa_edge");if(!i)return;const r=_i(this.buffer,i);if(this.modules.renderer.bindRenderTarget(e),this.modules.renderer.clearWithColor([0,0,0,0],!1),this.modules.renderer.bindVao(r),this.modules.renderer.enableShaderProgram(i),this.modules.renderer.enableTexture(t,0),!this.modules.renderer.isUboSupported()){const o=this.modules.map.state;ne(i,o,this.modules)}this.modules.renderer.bindShaderProgram(i,{u_texture:0}),this.modules.renderer.drawTrianglesFan(0,4)}renderWeightCalculation(e){const t=this.modules.renderer.getShaderProgram("smaa_weight");if(!t)return;const i=this.edgeTarget.getTexture();if(!i||!this.areaTexture||!this.searchTexture)return;const r=_i(this.buffer,t);if(this.modules.renderer.bindRenderTarget(e),this.modules.renderer.clearWithColor([0,0,0,0],!1),this.modules.renderer.bindVao(r),this.modules.renderer.enableShaderProgram(t),this.modules.renderer.enableTexture(i,0),this.modules.renderer.enableTexture(this.areaTexture,1),this.modules.renderer.enableTexture(this.searchTexture,2),!this.modules.renderer.isUboSupported()){const o=this.modules.map.state;ne(t,o,this.modules)}this.modules.renderer.bindShaderProgram(t,{u_edgesTex:0,u_areaTex:1,u_searchTex:2}),this.modules.renderer.drawTrianglesFan(0,4)}renderNeighborhoodBlending(){var o;const e=this.modules.renderer.getShaderProgram("smaa_blend");if(!e)return;const t=(o=this.input)==null?void 0:o.getTexture(),i=this.weightTarget.getTexture();if(!t||!i)return;const r=_i(this.buffer,e);if(this.modules.renderer.bindRenderTarget(this.output),this.modules.renderer.bindVao(r),this.modules.renderer.enableShaderProgram(e),this.modules.renderer.enableTexture(t,0),this.modules.renderer.enableTexture(i,1),!this.modules.renderer.isUboSupported()){const a=this.modules.map.state;ne(e,a,this.modules)}this.modules.renderer.bindShaderProgram(e,{u_texture:0,u_weightsTex:1}),this.modules.renderer.drawTrianglesFan(0,4)}}var Fi=(s=>(s.TAA="TAA",s.FXAA="FXAA",s.SMAA="SMAA",s))(Fi||{}),Et=(s=>(s[s.TAA=0]="TAA",s[s.FXAA=1]="FXAA",s[s.MSAA=2]="MSAA",s[s.SMAA=3]="SMAA",s))(Et||{});class Bp{constructor(e,t){this.renderGraph=[],this.effectsByType={},this.copyColorVao=null,this.copyColorDepthVao=null,this.copyColorProgram=null,this.copyColorDepthProgram=null,this.state=e,this.modules=t,this.renderTargetSize=this.modules.renderer.getViewportSize();const i=t.renderer.webglContextState.MAX_TEXTURE_SIZE;if(Math.max(...this.renderTargetSize)>i){n.log(`Disabling post-effects as viewport size ${this.renderTargetSize[0]}x${this.renderTargetSize[1]} exceeds hardware limits of ${i}x${i}`);return}const o=this.modules.renderer.createBuffer(new Uint8Array([-1,-1,1,-1,1,1,-1,1]));this.copyColorProgram=this.modules.renderer.getShaderProgram("copy"),this.copyColorDepthProgram=this.modules.renderer.getShaderProgram("copy",n.Shader.createShaderDefinitions([{type:"COPY_DEPTH",value:"1"},...!this.modules.renderer.isWebgl2Context()&&this.modules.renderer.fragDepthSupported()?[{type:"HAS_FRAG_DEPTH_EXT"}]:[]])),this.copyColorVao=_i(o,this.copyColorProgram),this.copyColorDepthVao=_i(o,this.copyColorDepthProgram);const a=this.createRenderTarget(this.renderTargetSize,{useHighDepthPrecision:!0});this.mainFrameBufferWrapper={renderTarget:a,onResize:()=>{},clearColor:n.getColorForShaders(e.defaultBackgroundColor),clearDepth:!0};const l=e.aaMode===0,c=e.aaMode===1,d=e.aaMode===3,u=l?Fp:c?Dp:d?zp:null;if(u){const h=this.createRenderTarget(this.renderTargetSize),_=new u(h,a,t,o),f=l?"TAA":c?"FXAA":"SMAA";this.effectsByType[f]=_,this.renderGraph.push(_)}}update(){this.renderGraph.forEach(e=>e.onBeforeRender(this.state))}render(){this.modules.renderer.applyGpuState(Bc),this.renderGraph.forEach(t=>t.render());const e=this.renderGraph[this.renderGraph.length-1].output;this.copyRenderTargetToCanvas(e),this.renderGraph.forEach(t=>t.onAfterRender(this.state))}invalidateSize(){this.mainFrameBufferWrapper&&(this.renderTargetSize=this.modules.renderer.getViewportSize(),this.mainFrameBufferWrapper.renderTarget.setSize(this.renderTargetSize),this.renderGraph.forEach(e=>e.resize(this.renderTargetSize)))}getEffectByName(e){return this.effectsByType[e]}setClearColor(e){this.mainFrameBufferWrapper&&(this.mainFrameBufferWrapper.clearColor=n.getColorForShaders(e))}hasActiveEffects(){if(!this.modules.postEffectsManager.mainFrameBufferWrapper)return!1;for(const e of this.renderGraph)if(e.enabled)return!0;return!1}isReady(e=!1){for(const t of this.renderGraph)if(!t.isReady({ignoreLayerAnimation:e}))return!1;return!0}getMemoryFootprint(){var t,i;const e={mainFrameBufferWrapper:{renderTarget:(i=(t=this.mainFrameBufferWrapper)==null?void 0:t.renderTarget.memSizeGPU())!=null?i:0}};return{gpu:V(I({},e),{"--sum":n.getTotalMemory(e)})}}copyRenderTargetToCanvas(e,t=!1,i=!0){if(!this.copyColorVao||!this.copyColorProgram||!this.copyColorDepthVao||!this.copyColorDepthProgram){n.log("PostEffectsManager: copyRenderTargetToCanvas called without vao or copyProgram");return}const{viewport:r}=this.state,o=window.devicePixelRatio,a=this.modules.renderer.getViewportSize();this.modules.renderer.bindRenderTarget(null),this.modules.renderer.setViewport(r.left*o,r.bottom*o,a[0],a[1]),i&&this.modules.renderer.clear(!1),this.copyRenderTargetContent(e,t)}copyRenderTargetTo(e,t,i=!1,r=!1){if(!this.copyColorVao||!this.copyColorProgram||!this.copyColorDepthVao||!this.copyColorDepthProgram){n.log("PostEffectsManager: copyRenderTargetTo called without vao or copyProgram");return}this.modules.renderer.bindRenderTarget(t),this.modules.renderer.setViewport(0,0,t.options.size[0],t.options.size[1]),r&&this.modules.renderer.clear(!1),this.copyRenderTargetContent(e,i)}copyRenderTargetContent(e,t){if(!this.copyColorVao||!this.copyColorProgram||!this.copyColorDepthVao||!this.copyColorDepthProgram)return;const i=t?this.copyColorDepthProgram:this.copyColorProgram,r=t?this.copyColorDepthVao:this.copyColorVao;this.modules.renderer.bindVao(r);const o=e.getTexture();if(o&&this.modules.renderer.enableTexture(o,0),this.modules.renderer.enableShaderProgram(i),this.modules.renderer.bindShaderProgram(i,{u_texture:0}),t){const a=e.getDepthAttachment();a instanceof C&&(this.modules.renderer.enableTexture(a,1),this.modules.renderer.bindShaderProgram(i,{u_depth:1}))}this.modules.renderer.drawTrianglesFan(0,4),this.modules.renderer.disableTexture(0),this.modules.renderer.disableTexture(1)}createRenderTarget(e,t){return new Pe(Object.assign({minFilter:C.NearestFilter,magFilter:C.NearestFilter,size:e},t))}}const Op=[0,0];function ve(...s){return(e,t,i,r,o)=>{s.forEach(a=>a(e,t,i,r,o))}}const re=(s,e,t,i)=>{var m,v,g;if(!i){bd(s,e,t);return}const r=(m=t.renderer.getFramebuffer(t.demManager.getDemFramebufferId()))==null?void 0:m.renderTarget.getTexture(),o=(v=t.renderer.getFramebuffer(t.demManager.getCorrectedDemFramebufferId()))==null?void 0:v.renderTarget.getTexture(),a=t.imageManager.getTexture(t.demManager.getHillshadeRampTextureId()),l=r==null?void 0:r.options.size,c=t.styleManager.getStyle(e.handyStyleId);if(!r||!o||!a||!c||!l){bd(s,e,t);return}const d=n.makeBinderContext(e.styleZoom,e.pitch,e.styleState,[],!1),u=n.clamp(n.resolveNumber(c.dem.style.shadingIntensity,d),0,1),h=t.demManager.getElevationSourceType(),_=n.EARTH_CIRCUMFERENCE/(Math.pow(2,Math.min(Math.trunc(e.styleZoom),h==="regular"?Vo:cd))*Kt);t.renderer.enableTexture(r,Uo),t.renderer.enableTexture(a,Ho),t.renderer.enableTexture(o,Go);const f=t.demManager.demCorrectedScale;t.renderer.bindShaderProgram(s,{u_float_dem_resolution:l[0],u_float_dem_cell_size:_,u_float_dem_shading_intensity:u,u_tex_dem:Uo,u_tex_corrected_dem:Go,u_tex_hillshade_ramp:Ho,u_float_corrected_interval:t.demManager.isDemCorrectionEnabled&&f!==1?.5/f:0,u_mat4_dem_corrected:t.demManager.demTexToCorrectedTex,u_float_map_center_elevation:e.demMode&&(g=e.elevation)!=null?g:0})},xd=(s,e,t)=>{t.renderer.bindShaderProgram(s,{u_float_dem_shading_intensity:0})},bd=(s,e,t)=>{t.renderer.bindShaderProgram(s,{u_float_dem_scale:0})},zr=re,Di=ve(Mt,hr),wp=ve(ic,hr,Mt,Sn,re),Sd=ve(ic,hr,Tm,re),yd=ve(Mt,hr,Em,Sn,re),Np=$i,Ct=(s,e,t,i,r)=>{const o=t.postEffectsManager.getEffectByName(Fi.TAA),a=!r&&(o!=null&&o.jitter)?o.jitter:Op;t.renderer.bindShaderProgram(s,{u_vec2_camera_jitter:a})},rt=(s,e,t)=>{const i=t.shadowManager.texture;i&&(t.renderer.enableTexture(i,pd),t.renderer.bindShaderProgram(s,{u_texture_shadow:pd}))},kp=(s,e,t)=>{if(!t.benchmark)return;const i=n.create$2(),r=t.benchmark.getScale();t.renderer.bindShaderProgram(s,{u_mat4_mvp:n.scale$3(i,i,r),u_vec3_transform:n.fromValues(0,0,0)})},Up=ve(re,Ct,rt),Mp=ve(Ct,rt),Br=ve(re,Ct,rt),Hp=$i,Gp=ve(re,Ct,rt),Td=ve(Ct,rt),It=ve(re,Ct,rt),Ed=ve(re,rt),Ki=ve(re,Ct,rt),Cd=ve($i,nc,rc),Id=ve($i,nc,rc,rt),Vp=ve(re,Id),Zp=ve(re,Cd),ea=ve(rt,re),Wp=ve(re,Ct,rt),jp=ve(Ct,rt),Pd=ve(Ct,rt),Xp=ve(re,Pd),In=new Float32Array(2),Pn=new Float32Array(2),An=[1,1,1],$p=[0,0],qp=[0,0],Ad=[0,0,0,0],en=.01,ke=(s,e,{renderer:t})=>{t.bindShaderProgram(s,{u_float_opacity:1})},ta=(s,e,{renderer:t},i,r)=>{const o=Ue(e,i),a=n.resolveNumber(r.style.textureOpacity,o);t.bindShaderProgram(s,{u_float_texture_opacity:i.tile.readiness*a})},li=(s,e,{renderer:t},i)=>{i.renderingProperties.mixFactorColor&&t.bindShaderProgram(s,{u_float_mix_color:i.renderingProperties.mixFactorColor})},be=(s,e,{renderer:t},i)=>{if(!i.renderingProperties.color)return;const r=n.getColorForShaders(i.renderingProperties.color);n.scale$4(r,r,i.tile.readiness),t.bindShaderProgram(s,{u_vec4_color:r})},Yp=(s,e,{renderer:t},i,r)=>{const o=n.makeBinderContext(e.styleZoom,e.pitch,e.styleState,i.attributes.tileData,!0),{color:a}=r.style,l=n.getColorForShaders(n.resolveColor(a,o));n.scale$4(l,l,i.tile.readiness),t.bindShaderProgram(s,{u_vec4_hidden_color:l})},Ld=(s,e,{renderer:t},i)=>{var c;if(!i.renderingProperties.mixColor)return;const{color2:r,factor:o,factorInterpolate:a}=i.renderingProperties.mixColor,l=n.getColorForShaders(r);switch(n.scale$4(l,l,i.tile.readiness),o.type){case"read-from-target":{const d=(c=t.getDrawTargetFramebuffer(o.name))==null?void 0:c.renderTarget.getTexture();if(!d)return;t.enableTexture(d,2),a?t.bindShaderProgram(s,{u_vec4_color2:l,u_sr2d_read_from_target_texture:2,u_int_factor_use_interpolate:1,u_float_factor_interpolate_base:a.base,u_vec4_factor_interpolate_ranges:a.steps}):t.bindShaderProgram(s,{u_vec4_color2:l,u_sr2d_read_from_target_texture:2,u_int_factor_use_interpolate:0});break}case"vertex-attribute":{t.bindShaderProgram(s,{u_vec4_color2:l});break}default:{const{type:d}=o;n.assertUnreachable(d)}}},Ln=(s,e,{renderer:t},i)=>{t.bindShaderProgram(s,{u_mat4_gradient:i.renderingProperties.mat4_gradient})},Qp=(s,e,{renderer:t},i,r)=>{const o=n.getColorForShaders(n.resolveColor(r.style.strokeColor,Ue(e,i)));n.scale$4(o,o,i.tile.readiness),t.bindShaderProgram(s,{u_vec4_border_color:o})},Ke=(s,e,{renderer:t},i)=>{const r=i.renderingProperties.widthResolved||0;t.bindShaderProgram(s,{u_float_width:r*window.devicePixelRatio})},Rd=(s,e,{renderer:t},i,r)=>{t.bindShaderProgram(s,{u_float_shift:n.resolveNumber(r.style.shift,Ue(e,i))*window.devicePixelRatio})},Jp=(s,e,{renderer:t},i,r)=>{const o=i.renderingProperties.opacityResolved||0,a=n.makeBinderContext(e.styleZoom,e.pitch,e.styleState,i.attributes.tileData,!1),l=r.style.iconOpacity,c=n.resolveNumber(l,a);a.isBehind=!0;const d=e.styleState.graphicsPreset==="light"?1:n.resolveNumber(l,a);t.bindShaderProgram(s,{u_vec2_opacity:[o*c,o*d]})},Vt=(s,e,{renderer:t},i)=>{const r=i.renderingProperties.opacityResolved||0;t.bindShaderProgram(s,{u_float_opacity:r})},ia=(s,e,{renderer:t},i,r)=>{const o=n.resolveNumber(r.style.iconRotation,Ue(e,i));t.bindShaderProgram(s,{u_vec2_rotation:[Math.cos(o),Math.sin(o)]})},Kp=(s,e,{renderer:t},i,r)=>{const o=n.resolveNumber(r.style.opacity,Ue(e,i));t.bindShaderProgram(s,{u_float_opacity:i.tile.readiness*o})},ex=(s,e,{renderer:t},i,r)=>{const o=n.resolveNumber(r.style.opacity,Ue(e,i));t.bindShaderProgram(s,{u_float_opacity:o})},na=(s,e,{assetManager:t,renderer:i},r)=>{const o=t.textures[r.attributes.atlasIndex];i.enableTexture(o,0)},mi=(s,e,{renderer:t},i)=>{const r=i.renderingProperties.fontTexture;r&&t.enableTexture(r,0)},ra=(s,e,{renderer:t},i)=>{const r=i.renderingProperties.guidelineTexture;if(!r)return;const o=r.options.size;o&&(t.bindShaderProgram(s,{u_vec2_guideline_tex_size:o}),t.enableTexture(r,1))},Fd=(s,e,{renderer:t},i)=>{const r=i.renderingProperties.texture;r&&t.enableTexture(r,0)},tx=(s,e,{renderer:t},i)=>{const r=i.renderingProperties.rampTexture;r&&(t.enableTexture(r,1),t.bindShaderProgram(s,{u_sr2d_ramp_texture:1}))},Or=(s,e,{renderer:t},i,r)=>{const{tile:o}=i,a=n.resolveColor(r.style.gapColor,Ue(e,i));if(!a)return;const l=n.getColorForShaders(n.resolveColor(a,Ue(e,i)));n.scale$4(l,l,o.readiness),t.bindShaderProgram(s,{u_vec4_space_color:l})},wr=(s,e,{renderer:t},i,r)=>{const{styleZoom:o}=e,a=Ue(e,i),{tile:l}=i,c=n.getColorForShaders(n.resolveColor(r.style.color,a));n.scale$4(c,c,l.readiness),a.styleZoom=Math.floor(o);const d=Math.pow(2,n.getFractionalPart(o)),u=n.resolveNumber(r.style.dashLength,a)*d,h=n.resolveNumber(r.style.gapLength,a)*d;t.bindShaderProgram(s,{u_vec4_dash_color:c,u_vec2_scaler_params:[0,n.z0Scale],u_float_dash_length:n.zptToSceneDistance(u,l.size),u_float_dash2_length:n.zptToSceneDistance(u,l.size),u_float_space_length:n.zptToSceneDistance(h,l.size),u_int_gap_turns_only:r.style.gapTurnsOnly?1:0})},pe=n.create$3(),Dd=(s,e,{renderer:t},i,r)=>{const o=Ue(e,i),{tile:a}=i,{pattern:l,width:c}=i.renderingProperties;if(!l||!c)return;const d=n.getColorForShaders(n.resolveColor(r.style.color,o));switch(n.scale$4(d,d,a.readiness),l[0]){case n.LinePatternType.Chess:{const u=l[1];pe[0]=u,pe[1]=.5,pe[2]=.25,pe[3]=-.25;break}case n.LinePatternType.DoubleDash:{const u=l[1];pe[0]=u,pe[1]=l[2]/c,pe[2]=.5*l[3]/u,pe[3]=.5*l[4]/u,pe[2]>=.5-Number.EPSILON&&(pe[2]=.6),pe[3]>=.5-Number.EPSILON&&(pe[3]=.6);break}case n.LinePatternType.Stripe:{const u=l[1]+l[2];pe[0]=u,pe[1]=.55,pe[2]=.5*l[1]/u,pe[3]=.5*l[1]/u,pe[2]>=.5-Number.EPSILON&&(pe[2]=.6),pe[3]>=.5-Number.EPSILON&&(pe[3]=.6);break}case n.LinePatternType.Circle:{const u=l[1]+l[2];pe[0]=u,pe[1]=.5*l[1]/u;break}case n.LinePatternType.Triangles:{const u=l[1]+l[2];pe[0]=u,pe[1]=l[1]/u,pe[2]=String(l[3])==="right"?-1:1;break}case n.LinePatternType.Chevron:{const u=l[1]+l[2];pe[0]=u,pe[1]=l[1]/u,pe[2]=l[3]/u,pe[3]=l[4]/c;break}}t.bindShaderProgram(s,{u_vec4_color:d,u_int_pattern_type:l[0],u_vec4_pattern_params:pe})},tn=(s,e,{renderer:t},i,r)=>{const o=Ue(e,i),a=n.resolveNumber(r.style.tipWidth,o),l=n.resolveNumber(r.style.tipHeight,o),c=a,d=0;In[0]=-c,In[1]=-d,n.normalize$1(In,In),Pn[0]=a,Pn[1]=l,n.normalize$1(Pn,Pn);const u=n.resolveNumber(r.style.roundingRadius,o);t.bindShaderProgram(s,{u_vec2_wing_normal:In,u_vec2_tip_normal:Pn,u_float_tip_height_multiplier:l,u_float_wing_height_multiplier:d,u_float_wing_width_multiplier:c,u_float_size_factor:n.zptToSceneDistance(n.uint16ToTileCoords,i.tile.size)/2,u_float_tip_radius_zpt:u,u_float_wing_radius_zpt:u,u_float_tail_radius_zpt:u})},Nr=(s,e,{renderer:t},i,r)=>{const o=Ue(e,i),a=n.resolveNumber(r.style.lineLength,o),l=n.resolveNumber(r.style.lineWidth,o);t.bindShaderProgram(s,{u_float_length:a,u_float_width:l,u_float_border_width:0})},zd=(s,e,{renderer:t},i,r)=>{const o=Ue(e,i),{tile:a,attributes:l}=i,c=l.isLongArrow,d=i.tile.dynamicObject;let u=0,h=1;d&&(c?h=d.growPosition:u=d.bouncePosition);let _=0;const f=r.style.animation.type;(f==="appearance"||f==="repeat")&&(_=n.resolveNumber(r.style.animation.tipMovementAmplitude,o));const m=n.resolveNumber(r.style.roundingRadius,o);t.bindShaderProgram(s,{u_float_width_zpt:n.resolveNumber(r.style.lineWidth,o),u_float_border_width_zpt:n.resolveNumber(r.style.strokeWidth,o),u_float_tip_movement_amplitude:n.zptToSceneDistance(_,a.size),u_float_vertex_shift:u,u_float_relative_end_position:h,u_float_tip_radius_zpt:m,u_float_wing_radius_zpt:m,u_float_tail_radius_zpt:m})},ix=(s,e,{renderer:t},i)=>{const r=i.renderingProperties.modelTexture;r&&t.enableTexture(r,0)},kr=(s,e,{renderer:t},i,r)=>{var o,a;if(i.attributes.polygonDemAnchor&&i.attributes.hasFoundation){const l=i.attributes.polygonDemAnchor;t.bindShaderProgram(s,{u_int_gltf_dem_pos:n.GltfDemPosition.polygonDemAnchor,u_vec2_anchor:[(l[0]+n.tileCoordOffset)/n.maxUint16Value,(l[1]+n.tileCoordOffset)/n.maxUint16Value],u_vec4_axis:Ad})}else t.bindShaderProgram(s,{u_int_gltf_dem_pos:i.attributes.demPosition,u_vec2_anchor:(o=i.attributes.centroid)!=null?o:qp,u_vec4_axis:(a=i.attributes.axis)!=null?a:Ad});return!0},nx=(s,e,{assetManager:t,renderer:i},r)=>{const{styleId:o}=r.attributes,{renderingProperties:a}=r,{resolvedColorTexture:l,resolvedAoTexture:c,resolvedPbrTexture:d,resolvedMetallic:u,resolvedRoughness:h}=a,{modelId:_}=a,f=t.getModel(_!=null?_:NaN,o);if(!f)return;const m={},v=l!==void 0&&f.textures[l];v&&(i.enableTexture(v,0),m.u_sr2d_texture_0=0);const g=c!==void 0&&f.textures[c];g&&(i.enableTexture(g,1),m.u_ao_texture=1);const p=d!==void 0&&f.textures[d];p?(i.enableTexture(p,n.PBR_TEXTURE_INDEX),m.u_pbr_texture=n.PBR_TEXTURE_INDEX):(m.u_float_metallic=u,m.u_float_roughness=h),i.bindShaderProgram(s,m)},Ur=(s,e,{assetManager:t,renderer:i},r)=>{const{styleId:o}=r.attributes,{useVat:a,vatTexture:l,modelId:c}=r.renderingProperties;if(!a||l===void 0||c===void 0)return;const d=t.getModel(c,o),u=d==null?void 0:d.textures[l];u&&(i.enableTexture(u,n.VAT_TEXTURE_INDEX),i.bindShaderProgram(s,{u_sampler_vat:n.VAT_TEXTURE_INDEX}))},Mr=(s,e,{renderer:t},i,r)=>{let o=i.renderingProperties.resolvedHeightFactor||0;o=en+(1-en)*o,t.bindShaderProgram(s,{u_float_height_factor:o})},Hr=(s,e,{renderer:t},i,r)=>{t.bindShaderProgram(s,{u_int_extention_to_relief_needed:i.attributes.extToReliefNeeded?1:0,u_int_is_extendable_to_relief_foundation:e.styleState.terrainEnabled===!0&&i.attributes.isFoundation?1:0,u_int_collapse_height_needed:i.attributes.collapseHeightNeeded?1:0})},Gr=(s,e,{renderer:t},i,r)=>{if(An[0]=1,An[1]=1,An[2]=1,n.isInterpolateExpression(r.style.scale)){const o=Ue(e,i);n.getTriple(n.resolveExpression(r.style.scale,o),An)}t.bindShaderProgram(s,{u_vec3_scale_factor:An})},sa=(s,e,{modelLayer:t,renderer:i},r,o)=>{if(r.attributes.id===void 0)return;const a=t.getOpacity(r.attributes.id,o.minzoom),c=t.getBuildingHeight(r.attributes.id)===1?1:a;i.bindShaderProgram(s,{u_float_height_factor:c})},Vr=(s,e,{renderer:t},i,r)=>{const o=Ue(e,i),a=n.resolveNumber(r.style.height,o);t.bindShaderProgram(s,{u_float_height_factor:n.mapHeightToTileHeight(a)})},_t=(s,e,t,i,r)=>{const{floorManager:o,buildingHeightAnimator:a,modelsScene:l,modelLayer:c,renderer:d}=t;if(i.symbol==="polygonExtrusion"&&i.attributes.floorId&&"isFloorStack"in i.attributes&&i.attributes.isFloorStack){d.bindShaderProgram(s,{u_float_height_factor:o.getFloorStackObjectHeight(i.attributes.floorId)});return}if(i.symbol==="polygonExtrusion"&&i.attributes.isHole){d.bindShaderProgram(s,{u_float_height_factor:1});return}let u=a.getBuildingHeight(r.minzoom);u=en+(1-en)*u;const h=l.objectIdToKey(i.id);h&&c.setBuildingHeight(h,u),d.bindShaderProgram(s,{u_float_height_factor:u})};function Ue(s,e){return n.makeBinderContext(s.styleZoom,s.pitch,s.styleState,e.attributes.tileData,!1,e.tile.dynamicObject)}const Zr=(s,e,{renderer:t},i)=>{const{tile:r}=i,o=i.renderingProperties.widthResolved||0;t.bindShaderProgram(s,{u_float_width:n.zptToSceneDistance(o,r.size)/2*n.uint16ToTileCoords,u_float_width_offset:n.zptToSceneDistance(n.uint16ToTileCoords/window.devicePixelRatio,r.size)/2})},rx=(s,e,{renderer:t},i)=>{const r=i.renderingProperties.resolvedRadius;t.bindShaderProgram(s,{u_float_radius:r*window.devicePixelRatio})},sx=(s,e,{renderer:t},i,r)=>{const o=n.resolveNumber(r.style.intensity,Ue(e,i));t.bindShaderProgram(s,{u_float_intensity:o})},ti=(s,e,{renderer:t},i,r)=>{const o=Ue(e,i);let a=n.resolveNumber(r.style.textFontSize,o);if(i.symbol==="point"){const l=i.attributes.labelIndex;l===n.LabelIndex.Second&&r.style.textFontSize2?a=n.resolveNumber(r.style.textFontSize2,o):l===n.LabelIndex.Icon&&r.style.iconTextFontSize&&(a=n.resolveNumber(r.style.iconTextFontSize,o))}t.bindShaderProgram(s,{u_float_scale:a*window.devicePixelRatio/n.fonts.baseSize})},Wr=(s,e,{renderer:t},i,r)=>{const o=n.makeBinderContext(e.styleZoom,e.pitch,e.styleState,i.attributes.tileData,!!i.layerSettings.isOverlappedObject),{textFontSize:a,textColor:l,textHaloWidth:c,textHaloColor:d}=r.style,u=n.resolveNumber(a,o)/n.fonts.baseSize,h=u*window.devicePixelRatio,_=n.fonts.gamma/h,f=i.layerSettings.uniformSet,m=f==="fontHalo"?(6-n.resolveNumber(c,o)/u)/8:.75;let v;f==="fontHalo"?v=n.getColorForShaders(n.resolveColor(d,o)):v=n.getColorForShaders(n.resolveColor(l,o)),t.bindShaderProgram(s,{u_float_buffer:m,u_float_gamma:_,u_vec4_color:v})},Bd=(s,e,{renderer:t},i,r)=>{const o=n.makeBinderContext(e.styleZoom,e.pitch,e.styleState,i.attributes.tileData,!1),{textFontSize:a,textColor:l,textHaloWidth:c,textHaloColor:d}=r.style,u=n.resolveNumber(a,o)/n.fonts.baseSize,h=u*window.devicePixelRatio,_=n.fonts.gamma/h,f=i.layerSettings.uniformSet,m=f==="fontHalo"?(6-n.resolveNumber(c,o)/u)/8:.75;let v,g;f==="fontHalo"?(v=n.getColorForShaders(n.resolveColor(d,o)),o.isBehind=!0,g=n.getColorForShaders(n.resolveColor(d,o))):(v=n.getColorForShaders(n.resolveColor(l,o)),o.isBehind=!0,g=n.getColorForShaders(n.resolveColor(l,o))),t.bindShaderProgram(s,{u_float_buffer:m,u_float_gamma:_,u_vec4_color:v,u_vec4_hidden_color:g})},Od=(s,e,{renderer:t},i,r)=>{const{layerSettings:o}=i,{uniformSet:a}=o,l=i.attributes.labelIndex,c=r.style;let{textFontSize:d,textHaloWidth:u,textColor:h,textHaloColor:_}=c;switch(l){case n.LabelIndex.Icon:d=c.iconTextFontSize,u=c.iconTextHaloWidth,h=c.iconTextColor,_=c.iconTextHaloColor;break;case n.LabelIndex.Second:d=c.textFontSize2,u=c.textHaloWidth2,h=c.textColor2,_=c.textHaloColor2;break}ox(s,t,e,i,d,h,u,_,l,a)},ox=(s,e,t,i,r,o,a,l,c,d)=>{const u=n.makeBinderContext(t.styleZoom,t.pitch,t.styleState,i.attributes.tileData,!1,i.tile.dynamicObject),h=n.resolveNumber(r,u)/n.fonts.baseSize,_=h*window.devicePixelRatio,f=n.fonts.gamma/_,m=d==="fontHalo"?(6-n.resolveNumber(a,u)/h)/8:.75;let v,g;d==="fontHalo"?(v=n.getColorForShaders(n.resolveColor(l,u)),u.isBehind=!0,g=n.getColorForShaders(n.resolveColor(l,u))):(v=n.getColorForShaders(n.resolveColor(o,u)),u.isBehind=!0,g=n.getColorForShaders(n.resolveColor(o,u))),e.bindShaderProgram(s,{u_float_buffer:m,u_float_gamma:f,u_vec4_color:v,u_vec4_hidden_color:g,u_float_label_index:c})},jr=(s,e,{renderer:t},i)=>{const{attributes:r}=i,{offsetX:o,offsetY:a}=r,l=window.devicePixelRatio;t.bindShaderProgram(s,{u_vec2_offset:[o*l,a*l]})},Xr=(s,e,{renderer:t})=>{t.bindShaderProgram(s,{u_float_style_zoom:e.styleZoom})},ii=(s,e,{renderer:t},i)=>{const{tile:r}=i,{zoom:o}=e,a=n.tileSizeZpt*Math.pow(2,o-r.zoomLevel)*window.devicePixelRatio;t.bindShaderProgram(s,{u_float_tile_to_pixel_ratio:n.uint16ToTileCoords/a})},wd=(s,e,{renderer:t},i,r)=>{const{tile:o}=i,{zoom:a,styleZoom:l}=e,c=r.style.lengthUnits===n.LengthUnits.Meters,d=n.tilePointScaleFactor(n.createTileInfo(o.coords),[n.maxTilePoint/2,n.maxTilePoint/2]),u=n.uint16ToTileCoords/(n.tileSizeZpt*Math.pow(2,a-o.zoomLevel)*window.devicePixelRatio),h=c?l:Math.floor(l),_=n.tileSizeZpt*Math.pow(2,h-o.zoomLevel)*window.devicePixelRatio/(n.uint16ToTileCoords*d);t.bindShaderProgram(s,{u_vec2_scales:[_,u]})},Nd=(s,e,{renderer:t},i)=>{const r=i.renderingProperties.flatTexture;r&&t.enableTexture(r,0),t.bindShaderProgram(s,{u_flat_tex:0})},kd=(s,e,{renderer:t},i)=>{const r=i.renderingProperties.flatIdentifyTexture;r&&t.enableTexture(r,0),t.bindShaderProgram(s,{u_flat_tex:0})},Ud=(s,e,{renderer:t},i)=>{const r=i.renderingProperties.hillshadeTexture;r&&(t.enableTexture(r,Mo),t.bindShaderProgram(s,{u_hillshade_tex:Mo}))},ax=(s,e,{demManager:t,renderer:i,camera:r})=>{if(!t.isContoursEnabled()){i.bindShaderProgram(s,{u_int_inline_contour_enabled:0});return}const a=t.getResolvedContourParams().lines,l=n.Mercator.toGeo(r.position,$p),c=n.Mercator.scaleFactor(l[1]);i.bindShaderProgram(s,{u_int_inline_contour_enabled:1,u_float_contour_minor_interval:a.minorInterval*c,u_float_contour_major_interval:a.majorInterval*c,u_float_contour_index_interval:a.indexInterval*c,u_vec4_contour_minor_color:a.minorColor,u_vec4_contour_major_color:a.majorColor,u_vec4_contour_index_color:a.indexColor,u_float_contour_minor_width:a.minorWidth,u_float_contour_major_width:a.majorWidth,u_float_contour_index_width:a.indexWidth})},lx=(s,e,t,i)=>{const{renderer:r,demManager:o}=t,a=i.renderingProperties.demTexture;a&&(r.enableTexture(a,0),r.bindShaderProgram(s,{u_tex_dem:0,u_mat4_dem_corrected:o.demCorrectedFbVpToDemTex}))},Rn=(s,e,{renderer:t},i,r)=>{let o=!0;e.globeMode||(o=!!n.resolveNumber(r.style.elevation,Ue(e,i)));const a=i.renderingProperties;t.bindShaderProgram(s,{u_bool_skip_height_factor:o||(a==null?void 0:a.surfaceRelativeZ)!==void 0})},Zt=(s,e,{renderer:t},i)=>{var l,c;const r=i.renderingProperties,o=(l=r.surfaceRelativeZ)!=null?l:0,a=r.surfaceAbsoluteZ!==void 0;t.bindShaderProgram(s,{u_bool_surface_use_abs_z:a?1:0,u_float_surface_relative_z_norm:o/(65535*32),u_float_surface_abs_z:(c=r.surfaceAbsoluteZ)!=null?c:0})},lt=(s,e,{buildingHeightAnimator:t,renderer:i},r,o)=>{if(r.attributes.floorId||"isHole"in r.attributes&&r.attributes.isHole){i.bindShaderProgram(s,{u_float_height_factor:1});return}let a=t.getBuildingHeight(o.minzoom);a=en+(1-en)*a,i.bindShaderProgram(s,{u_float_height_factor:a})},ft=(s,e,{renderer:t},i)=>{const r=i.renderingProperties,o=(r==null?void 0:r.gltfHasExplicitZ)===!1?!1:!!i.attributes.absZ;t.bindShaderProgram(s,{u_int_abs_z:o?1:0})},oa=(s,e,{renderer:t})=>{t.bindShaderProgram(s,{u_int_abs_z:!1})},aa=(s,e,{renderer:t},i)=>{t.bindShaderProgram(s,{u_float_tile_size:n.tileZoomToSize(i.tile.zoomLevel)})},cx=(s,e,{renderer:t})=>{t.bindShaderProgram(s,{u_vec4_color:n.LABELING_TEXTURE_DEM_MESH_COLOR})},w=(s,e,{renderer:t},i,r,o)=>{t.bindShaderProgram(s,{u_float_dem_scale:o?e.elevationScale:0})},la=(s,e,{renderer:t},i)=>{if(!i.attributes.meshTier)return;const r=i.layerSettings.identify?t.getMapMeshIdFramebufferId():t.getMapMeshFramebufferId(),o=t.getFramebuffer(r),a=o==null?void 0:o.renderTarget.getTexture(),l=o==null?void 0:o.scale;a&&(t.enableTexture(a,n.MAP_MESH_TEXTURE_INDEX),t.bindShaderProgram(s,{u_sampler_map_tex:n.MAP_MESH_TEXTURE_INDEX,u_vec2_tex_scale:l,u_float_tex_shift_scale:1-Math.cos(e.pitch)}))},ci=(s,e,{renderer:t},i)=>{t.bindShaderProgram(s,{u_int_identify:i.layerSettings.identify||i.layerSettings.depthTest?1:0})},Fn=(s,e,{renderer:t},i)=>{t.bindShaderProgram(s,{u_int_identify:i.layerSettings.identify?1:0})},Md=(s,e,{renderer:t},i)=>{var a;const r=i.attributes.meshTier,o=r!==void 0&&(a=n.TIER_TO_COLOR_INDEX[r])!=null?a:n.NAN_INDEX;t.bindShaderProgram(s,{u_int_is_tiered:r!==void 0?1:0,u_vec4_tier_color:n.numberToRgba(o,!0)})},vi=(s,e,{renderer:t},i)=>{t.bindShaderProgram(s,{u_int_depth_test:i.layerSettings.depthTest?1:0})},dx=(s,e,{renderer:t},i)=>{t.bindShaderProgram(s,{u_float_scale:i.meta.scale,u_vec3_transform:i.meta.transform})};function R(...s){return(e,t,i,r,o,a)=>{s.forEach(l=>l(e,t,i,r,o,a))}}const nn=(s,e,{renderer:t},i)=>(t.bindShaderProgram(s,{u_bool_is_3d_line:i.symbol==="line"&&i.sink==="solid3d"||i.symbol==="line"&&i.sink==="patterned3d"||i.symbol==="dashedLine"&&i.sink==="stroke3d"}),!0),ux=(s,e,{renderer:t},i)=>{const r=!!i.attributes.floorId,o=Array.isArray(e.styleState._backgroundFloorIds)&&e.styleState._backgroundFloorIds.length>0;t.bindShaderProgram(s,{u_int_is_3dfloor_object:r&&o})},le=(s,e,{floorManager:t,renderer:i},r)=>{if(!r.attributes.floorId||!r.tile.renderModelMatrix){i.bindShaderProgram(s,{u_float_floor_elevation:0});return}if(r.symbol==="polygonExtrusion"&&"isFloorStack"in r.attributes&&r.attributes.isFloorStack){i.bindShaderProgram(s,{u_float_floor_elevation:t.getFloorStackObjectElevation(r.attributes.floorId)/r.tile.renderModelMatrix[10]});return}const o=r.symbol==="mesh"&&r.sink==="inverse",a=(t.getFloorObjectElevation(r.attributes.floorId)-(o?e.zoom>=17?1:3:0))/r.tile.renderModelMatrix[10];i.bindShaderProgram(s,{u_float_floor_elevation:a})},Wt=(s,e,{renderer:t})=>{t.bindShaderProgram(s,{u_float_floor_elevation:0})},Dn=(s,e,t,i)=>{t.renderer.bindShaderProgram(s,{u_int_is_roof:i.symbol==="polygonExtrusion"&&i.sink==="topFill"?1:0})},di=(s,e,t,i)=>{t.renderer.bindShaderProgram(s,{u_int_is_hole:i.attributes.isHole?1:0})},$r=(s,e,t)=>{t.renderer.bindShaderProgram(s,{u_float_color_effect_mix_factor:0})},gi=(s,e,t,i,r)=>{if(r.style.colorEffect){const o=Ue(e,i),a=n.resolveExpression(r.style.colorEffect,o);if(a.effect.type==="mix"){const l=a.effect.factor;if(l>0){const c=n.getColorForShaders(a.effect.color);t.renderer.bindShaderProgram(s,{u_vec4_color_effect_mix_rgba:c,u_float_color_effect_mix_factor:l});return}}}t.renderer.bindShaderProgram(s,{u_float_color_effect_mix_factor:0})},Hd=(s,e,t,i)=>{if("isFloorStack"in i.attributes&&i.attributes.isFloorStack){const r=t.floorManager.getFloorsStackObjectOffsets(i.attributes.floorId);t.renderer.bindShaderProgram(s,{u_vec2_floor_level:[r.current,r.total]})}else t.renderer.bindShaderProgram(s,{u_vec2_floor_level:[0,1]})},hx=(s,e,t,i,r)=>{var v;const o=i.attributes.textureIndex,a=(v=r.style.sideTextures)==null?void 0:v[o],l=t.imageManager.getTexture(r.sideTextureIndices[o]),c=n.MAP_POINTS_IN_METER*n.tilePointScaleFactor(n.createTileInfo(i.tile.coords),[0,0]),d=l.options.size,u=[a.texturePadding[3]/d[0],a.texturePadding[0]/d[1],a.texturePadding[1]/d[0],a.texturePadding[2]/d[1]],h=a.wallPadding.map(g=>g*c),_=a.sliceSize.map(g=>g*c),f=[a.horizontal.maxInterval*c,a.vertical.maxInterval*c],m=[Gd(a.horizontal.mode),Gd(a.vertical.mode)];t.renderer.enableTexture(l,0),t.renderer.bindShaderProgram(s,{u_sr2d_texture:0,u_vec4_wall_padding_su:[h[3],h[0],h[1],h[2]],u_vec4_texture_padding_un:u,u_vec2_texture_part_count:[a.horizontal.slicesCount,a.vertical.slicesCount],u_vec2_max_interval_su:f,u_vec2_texture_slice_size_su:_,u_ivec2_layout_mode:m,u_int_texture_index:i.attributes.textureIndex})};function Gd(s){switch(s){case"repeat-with-stretch":return 1;case"stripe-top":return 2;case"repeat-with-max-interval":return 3;default:return 1}}const _x="FRAGMENT",fx="VERTEX",mx="FOG",vx="SKY",gx="METALLIC_ROUGHNESS_DEBUG",px="PBR_TEXTURE",xx="AO_TEXTURE",bx="MAP_MESH_TEXTURE",Sx="COLOR_TEXTURE",yx="VAT_TEXTURE",Vd="ALPHA_MODE",Tx="1",Ex="2",Zd="LIGHT_MODEL",Cx="1",Ix="2",Px="DEPTH_TEXTURE_SHADOW",Ax="RENDER_SHADOWS",Lx="UBO",Rx="SCREENDOOR",Fx="ENTRANCE_ARROWS_ROUNDING",Dx="MALI_GPU",zx="VARYINGS_LIMIT_9",ca="MIX_COLOR_MODE",Bx="1",Wd="2",Ox="MIX_COLOR_MODE_VERTEX_ATTRIBUTE_NAME",wx="1",Nx=n.Shader.createShaderDefinitions([{type:ca,value:Bx}]),kx=n.Shader.createShaderDefinitions([{type:ca,value:Wd}]),Ux=n.Shader.createShaderDefinitions([{type:ca,value:Wd},{type:Ox,value:wx}]),Mx={value:[0,0,0]};function Ee(s,e){return n.makeBinderContext(s.styleZoom,s.pitch,s.styleState,e.attributes.tileData,!1,e.tile.dynamicObject)}const Hx=(s,e,t,i)=>{switch(s.attributes.side){case n.MeshFillSide.top:if(!i.style.strokeColor)return!1;break;case n.MeshFillSide.side:if(!i.style.sideColor)return!1;break;case n.MeshFillSide.bottom:if(!i.style.bottomColor)return!1;break;default:return!1}return!0},da=(s,e)=>{const t=e.assetManager.textures[s.attributes.atlasIndex];return t?(s.renderingProperties.atlasTexture=t,!0):!1},jd=(s,e)=>{const t=e.imageManager.getTexture(s.attributes.textureIndex);return t?(s.renderingProperties.texture=t,!0):!1},pi=(s,e)=>{const{range:t,fontName:i,styleId:r}=s.attributes;if(!e.styleManager.getStyle(r))return!1;let a=e.assetManager.getFontTexture(i,t);return a||(a=e.assetManager.getFontTexture(n.DEFAULT_FONT,t)),a?(s.renderingProperties.fontTexture=a,!0):!1},ua=(s,e)=>{const{guidelineTextureKey:t}=s;if(!t)return!1;const i=e.labeler.getGuidelineTexture(t);return i?(s.renderingProperties.guidelineTexture=i,!0):!1},ha=(s,e)=>{const t=s.layerSettings.identify?e.renderer.getMapMeshIdFramebufferId():e.renderer.getMapMeshFramebufferId(),i=e.renderer.getFramebuffer(t),r=i==null?void 0:i.renderTarget.getTexture(),o=i==null?void 0:i.scale;return!(!r||!o)},Gx=(s,{imageManager:e})=>{const t=e.getTexture(s.attributes.rampTextureIndex);return t?(s.renderingProperties.rampTexture=t,!0):!1},Vx=(s,e)=>{var r;const t=e.demManager.getDemFramebufferId(),i=(r=e.renderer.getFramebuffer(t))==null?void 0:r.renderTarget.getTexture();return i?(s.renderingProperties.demTexture=i,!0):!1},Xd=(s,{demManager:e,renderer:t,map:i})=>{var a;if(!i.state.demMode)return!1;const r=e.getHillshadeFramebufferId(),o=(a=t.getFramebuffer(r))==null?void 0:a.renderTarget.getTexture();return o?(s.renderingProperties.hillshadeTexture=o,!0):!1},$d=(s,{demManager:e,renderer:t,map:i})=>{if(!i.state.demMode)return!1;const r=e.getFlatFramebufferId(),o=t.getFramebuffer(r);if(!o)return!1;const a=o.renderTarget.getTexture();return a?(s.renderingProperties.flatTexture=a,!0):!1},qd=(s,{demManager:e,renderer:t,map:i})=>{if(!i.state.demMode)return!1;const r=e.getIdentifyFlatFramebufferId(),o=t.getFramebuffer(r);if(!o)return!1;const a=o.renderTarget.getTexture();return a?(s.renderingProperties.flatIdentifyTexture=a,!0):!1},Zx=(s,e,t,i)=>{var l,c;const{renderingProperties:r}=s,{resolvedUvIndex:o}=r,{colorTextureUvIndex:a}=i.style;return a!==void 0&&o!==a&&(((c=(l=s.meta)==null?void 0:l.availableTextureCoords)!=null?c:[])[a]&&s.vao.setAttributesAliases({texcoord_color:`texcoord_${a}`}),r.resolvedUvIndex=a),!0},Wx=(s,e,t,i)=>{var _,f;const{styleId:r,colorTexture:o,aoTexture:a,pbrTexture:l,meshTier:c}=s.attributes,{renderingProperties:d}=s,{modelId:u}=d,h=e.assetManager.getModel(u!=null?u:NaN,r);return!h||(o!==void 0&&h.textures[o]&&(d.resolvedColorTexture=o),a!==void 0&&h.textures[a]&&(d.resolvedAoTexture=a),l!==void 0&&h.textures[l]?d.resolvedPbrTexture=l:(d.resolvedMetallic=(_=s.attributes.metallic)!=null?_:i.style.metallic,d.resolvedRoughness=(f=s.attributes.roughness)!=null?f:i.style.roughness),!d.resolvedColorTexture&&!d.color)?!1:c?ha(s,e):!0},Yd=(s,{modelsScene:e})=>{const t=e.getModelOpacity(s);return s.renderingProperties.resolvedOpacity=t,t!==0},Qd=(s,{modelsScene:e})=>{const t=e.getModelHeightFactor(s);return s.renderingProperties.resolvedHeightFactor=t,t!==0};function Jd(s){return typeof(s==null?void 0:s.getResolvedHeight)=="function"}function jx(s){return typeof(s==null?void 0:s.hasExplicitZ)=="boolean"}const zi=s=>{const e=s.tile.dynamicObject;if(Jd(e)){const t=e.getResolvedHeight(),i=s.renderingProperties;t.relativeZ===void 0?(delete i.surfaceRelativeZ,delete i.surfaceAbsoluteZ):(i.surfaceRelativeZ=t.relativeZ,t.absoluteZ===void 0?delete i.surfaceAbsoluteZ:i.surfaceAbsoluteZ=t.absoluteZ)}return!0},qr=s=>{const e=s.tile.dynamicObject;if(Jd(e)){const t=e.getResolvedHeight(),i=s.renderingProperties;t.relativeZ===void 0||t.absoluteZ===void 0?(delete i.surfaceRelativeZ,delete i.surfaceAbsoluteZ):(i.surfaceRelativeZ=t.relativeZ,i.surfaceAbsoluteZ=t.absoluteZ),jx(t)?i.gltfHasExplicitZ=t.hasExplicitZ:delete i.gltfHasExplicitZ}return!0},Kd=(s,e,t,i)=>{const r=Ee(t,s),o=n.resolveNumber(i.style.width,r);if(o===0)return!1;const a=n.resolveExpression(i.style.pattern,r);return!a||a[0]===n.LinePatternType.None?!1:(s.renderingProperties.width=o,s.renderingProperties.pattern=a,!0)},Xx=(s,e,t)=>Bi(t,s.attributes.animDirection)!==0,eu=(s,e,t,i)=>{const r=Ee(t,s);return n.resolveNumber(i.style.iconOpacity,r)*Bi(t,s.attributes.animDirection)!==0},tu=(s,e)=>!e.map.getFeatureFlag("transparentBuildingsOff")||s.attributes.isHole,G=(s,e,t,i)=>ru(s.tile,t,i),iu=(s,e,t,i)=>!!s.renderingProperties.holdVisible||ru(s.tile,t,i),nu=(s,e,t)=>{var r,o,a,l,c,d;if((r=s.meta)!=null&&r.planId&&(!t.styleState._activeFloorIds||!(t.styleState._activeFloorIds.includes(s.meta.planId)||t.styleState._backgroundFloorIds.includes(s.meta.planId)))||(a=(o=s.meta)==null?void 0:o.linkedIds)!=null&&a.length&&!((l=s.meta)!=null&&l.planId)&&e.floorManager.hasDisplayedFloorBuilding(s.meta.linkedIds))return!1;const i=(c=s.meta)==null?void 0:c.buildingId;return!(i&&((d=s.tile.ids)!=null&&d.isHidden(i)))},ru=(s,e,t)=>{const{purpose:i,detailLevel:r}=s,{styleZoom:o}=e;switch(i){case"zenith":case"traffic":case"geojson":const a=r<a0(i)?n.clamp(o,r,r+.99999):o;return t.minzoom<=a&&a<t.maxzoom;case"dynamicObject":return t.minzoom<=o&&o<=t.maxzoom;default:return t.minzoom<=o&&o<t.maxzoom}},$x=(s,e,t)=>{var a;const{styleZoom:i}=t,{tile:r}=s;if(r.purpose!=="zenith"||i>n.tiles.maxUniverseZoom)return!0;let o=n.tiles.maxUniverseZoom;if(r.sourceId){const l=e.sourceStorage.getSourceById(r.sourceId);o=(l==null?void 0:l.type)==="zenith"&&(a=l.getOptions().strokeMinZoom)!=null?a:n.tiles.maxUniverseZoom}return i>o},Xe=(s,e,t,i)=>{const{styleZoom:r}=t;return r>=i.minzoom&&r<i.maxzoom},Yr=s=>!s.attributes.isHole,_a=(s,e)=>s.attributes.id===void 0?!0:!e.modelLayer.isHidden(s.attributes.id),fa=(s,e,t,i)=>{const r=Ee(t,s);return n.resolveNumber(i.style.iconWidth,r)>0},su=(s,e,t,i)=>{const{layerSettings:r}=s,{uniformSet:o}=r,a=s.attributes.labelIndex,l=i.style;if(o==="fontHalo"){let{textHaloColor:c}=l;switch(a){case n.LabelIndex.Icon:c=l.iconTextHaloColor;break;case n.LabelIndex.Second:c=l.textHaloColor2;break}if(!c)return!1}return!0},rn=(s,e,t,i)=>!(s.layerSettings.uniformSet==="fontHalo"&&!i.style.textHaloColor),Qr=(s,e,t,i)=>{var l,c,d,u,h,_;const r=Ee(t,s),o=i.style;if(s.symbol==="point")switch(s.attributes.labelIndex){case n.LabelIndex.Second:return((c=n.resolveNumber((l=o.textHaloWidth2)!=null?l:null,r))!=null?c:0)>0&&!!o.textHaloColor2;case n.LabelIndex.Icon:return((u=n.resolveNumber((d=o.iconTextHaloWidth)!=null?d:null,r))!=null?u:0)>0&&!!o.iconTextHaloColor;case n.LabelIndex.First:break}return((_=n.resolveNumber((h=o.textHaloWidth)!=null?h:null,r))!=null?_:0)>0&&!!o.textHaloColor},ou=(s,{modelLayer:e})=>{const{texture:t,id:i}=s.attributes;if(i===void 0)return!1;const r=e.getTexture(i,t);return r?(s.renderingProperties.modelTexture=r,!0):!1},Pt=(s,e,t,i)=>{const r=n.resolveNumber(i.style.width,Ee(t,s));return s.renderingProperties.widthResolved=r,r!==0},zn=(s,e,t,i)=>{const r=Ee(t,s),o=n.resolveNumber(i.style.strokeWidth,r);return s.renderingProperties.widthResolved=o,o!==0},qx=(s,e,t,i)=>{const r=Ee(t,s),o=n.resolveNumber(i.style.strokeWidth,r);if(o===0)return!1;const a=n.resolveNumber(i.style.width,r);return s.renderingProperties.widthResolved=a+o*2,!0},Yx=(s,e,t,i)=>{const r=Ee(t,s),o=n.resolveNumber(i.style.strokeWidth2,r);if(o===0)return!1;const a=n.resolveNumber(i.style.width,r),l=n.resolveNumber(i.style.strokeWidth,r);return s.renderingProperties.widthResolved=a+l*2+o*2,!0},Qx=(s,e,t,i)=>{const r=Ee(t,s),o=n.resolveNumber(i.style.width,r),a=n.resolveNumber(i.style.strokeWidth,r),l=n.resolveNumber(i.style.strokeWidth2,r),c=o+a*2+l*2;return s.renderingProperties.widthResolved=c,c!==0},ct=(s,e,t)=>{const i=s.attributes.fadeOpacity;if(i!==void 0)return s.renderingProperties.opacityResolved=i,i!==0;const r=Bi(t,s.attributes.animDirection);return s.renderingProperties.opacityResolved=r,r!==0},Jx=(s,e,t,i)=>(s.renderingProperties.resolvedRadius=n.resolveNumber(i.style.radius,Ee(t,s)),s.renderingProperties.resolvedRadius>0),au=(s,e,t,i)=>{var l;s.renderingProperties.mat4_gradient||(s.renderingProperties.mat4_gradient=new Float32Array(16));let r;switch(s.attributes.side){case n.MeshFillSide.top:r=(l=i.style.topColor)!=null?l:i.style.color;break;case n.MeshFillSide.side:r=i.style.sideColor;break;case n.MeshFillSide.bottom:r=i.style.bottomColor;break}const o=Ee(t,s),a=n.resolveExpression(r,o);return s.renderingProperties.mat4_gradient[0]=0,n.isStyleColor(a)?vt(s,a):n.isStyleGradient(a)&&(xa(a,s.tile.readiness,s.renderingProperties.mat4_gradient),a.mixFactor&&(s.renderingProperties.mixFactorColor=a.mixFactor)),!0},ma=(s,e,t,i)=>{if(s.renderingProperties.mat4_gradient||(s.renderingProperties.mat4_gradient=new Float32Array(16)),!s.renderingProperties.color)return!1;const r=n.resolveGradient(i.style.sideColor,Ee(t,s));return r?(n.copy$2(s.renderingProperties.color.value,r.values[0].value),xa(r,s.tile.readiness,s.renderingProperties.mat4_gradient),r.mixFactor&&(s.renderingProperties.mixFactorColor=r.mixFactor),s.renderingProperties.color.value[3]!==0):(s.renderingProperties.mat4_gradient[0]=0,!0)},lu=(s,e,t,i)=>{const r=s.renderingProperties.color;if(!r)return!1;s.renderingProperties.mat4_gradient||(s.renderingProperties.mat4_gradient=new Float32Array(16));const o=Ee(t,s),a=n.resolveColor(i.style.sideColor,o).value,l=n.equals(r.value,a),c=l?i.style.sideColor:i.style.sideStrokeColor,d=n.resolveGradient(c,Ee(t,s));return d?(n.copy$2(r.value,d.values[0].value),s.renderingProperties.mixFactorColor=d.mixFactor,xa(d,s.tile.readiness,s.renderingProperties.mat4_gradient)):s.renderingProperties.mat4_gradient[0]=0,l&&(r.value[3]*=t.stillness),r.value[3]!==0},Se=(s,e)=>!("hiddenByFloorComplexId"in s.attributes)||!s.attributes.hiddenByFloorComplexId?!0:!e.floorManager.hasDisplayedFloorBuilding([s.attributes.hiddenByFloorComplexId]),te=(s,e,t,i)=>{if(!s.attributes.floorId)return!0;if(s.symbol==="polygonExtrusion"&&"isFloorStack"in s.attributes&&s.attributes.isFloorStack)return e.floorManager.isVisibleFloorStackObject(s.attributes.floorId);const r=s.symbol==="mesh"?"all-floors":String(i.style.floorCulling);return e.floorManager.isVisibleFloorObject(s.attributes.floorId,r)},Kx=s=>{const e=s.renderingProperties.color;return e?n.set$1(e.value,0,0,0,.05*255):s.renderingProperties.color=n.toStyleColor([0,0,0,.05*255]),!0},Jr=(s,e,t,i)=>{const r=n.makeBinderContext(t.styleZoom,t.pitch,t.styleState,s.attributes.tileData,!!s.layerSettings.isOverlappedObject);return vt(s,n.resolveColor(i.style.color,r)),s.renderingProperties.color.value[3]!==0},va=(s,e,t,i)=>(vt(s,n.resolveColor(i.style.topColor,Ee(t,s))),s.renderingProperties.color.value[3]!==0),Kr=(s,e,t,i)=>(vt(s,n.resolveColor(i.style.sideColor,Ee(t,s))),s.renderingProperties.color.value[3]!==0),Bn=(s,e,t,i)=>(vt(s,n.resolveColor(i.style.strokeColor,Ee(t,s))),s.renderingProperties.color.value[3]!==0),e0=(s,e,t,i)=>{switch(s.attributes.side){case n.MeshFillSide.top:vt(s,n.resolveColor(i.style.strokeColor,Ee(t,s)));break;case n.MeshFillSide.side:vt(s,n.resolveColor(i.style.sideColor,Ee(t,s)));break;case n.MeshFillSide.bottom:vt(s,n.resolveColor(i.style.bottomColor,Ee(t,s)));break;default:vt(s,Mx);break}return s.renderingProperties.color.value[3]!==0},t0=(s,e,t,i)=>(vt(s,n.resolveColor(i.style.strokeColor2,Ee(t,s))),s.renderingProperties.color.value[3]!==0),ga=(s,e,t,i)=>{if(s.attributes.id===void 0)return!1;const r=s.renderingProperties.color;return r?(r.value[3]*=e.modelLayer.getOpacity(s.attributes.id,i.minzoom),r.value[3]!==0):!1},cu=(s,e,t,i)=>{const r=s.renderingProperties.color;if(!r)return!1;const o=Ee(t,s),a=n.resolveColor(i.style.strokeColor,o).value,l=n.resolveNumber(i.style.strokeWidth,o);return n.equals(r.value,a)&&r.value[3]===1&&l<=1&&(r.value[3]*=t.stillness),r.value[3]!==0},i0=(s,e,t,i)=>{const r=s.renderingProperties.color;if(!r)return!1;const o=Ee(t,s),a=n.resolveColor(i.style.topColor,o).value,l=n.resolveNumber(i.style.strokeWidth,o);return n.equals(r.value,a)&&r.value[3]===1&&l<=1&&(r.value[3]*=t.stillness),r.value[3]!==0},du=(s,e,t,i)=>{const r=n.resolveColor(i.style.sideStrokeColor,Ee(t,s));return vt(s,r),s.renderingProperties.color.value[3]!==0},mt=(s,e,t,i)=>{const r=n.resolveColor(i.style.color,Ee(t,s),!0),o=n.isStyleMixColor(r)?r.color1:r;if(vt(s,o),n.isStyleMixColor(r))if(r.factor.type==="read-from-target"&&!e.renderer.doesDrawTargetFramebufferExist(r.factor.name))s.shaderDefinitions=void 0;else{if(l0(s,r),s.renderingProperties.color.value[3]===0&&s.renderingProperties.mixColor.color2.value[3]===0)return!1;const{factor:{type:a,name:l}}=s.renderingProperties.mixColor;switch(a){case"read-from-target":{s.shaderDefinitions=Nx;break}case"vertex-attribute":{l==="denormalized_distance_to_line"?s.shaderDefinitions=Ux:s.shaderDefinitions=kx;break}default:n.assertUnreachable(a)}return!0}return s.renderingProperties.color.value[3]!==0},n0=(s,e,t,i)=>{vt(s,n.resolveColor(i.style.color,Ee(t,s)));const{color:r,resolvedOpacity:o}=s.renderingProperties;return n.mul(r.value,r.value,s.attributes.colorFactor),r.value[3]*=o!=null?o:0,r.value[3]!==0},uu=(s,e)=>{const t=s==null?void 0:s.attributes.parentId;if(!t)return!0;const{floorManager:i}=e;if(i.hasDisplayedFloorBuilding([t])&&s.attributes.floorId)return!0;const o=s==null?void 0:s.tile.ids;return!(o!=null&&o.isHidden(t,n.HideLevel.PolygonExtrusion))},r0=(s,e)=>{if(!s.bboxWorld||s.tile.dynamicObject||s.renderingProperties.useVat||s.renderingProperties.animationStack&&s.renderingProperties.animationStack.length>0||s.attributes.floorId&&e.floorManager.visibleComplexIsMetro)return!0;if(e.environmentManager.isAABBInFog(s.bboxWorld))return!1;const t=e.camera.getViewportVertices();return n.tetragonIntersectsBounds(t,s.bboxWorld)},hu=(s,e,t)=>!!t.styleState.terrainEnabled||!s.attributes.isFoundation,pa=O(iu,uu,Se,r0,te,nu,Yd,Qd,n0,hu),s0=O(iu,uu,Se,nu,Yd,Qd,hu),_u=O(Zx,Wx),o0=(s,e,t,i)=>{var l;const r=s.attributes.textureIndex,o=(l=i.style.sideTextures)==null?void 0:l[r],a=e.imageManager.getTexture(i.sideTextureIndices[r]);return!!o&&!!a};function O(...s){return(e,t,i,r)=>{for(const o of s)if(!o(e,t,i,r))return!1;return!0}}function a0(s){switch(s){case"zenith":return n.tiles.maxDetailLevel;case"traffic":return n.traffic.maxDetailLevel;case"geojson":return n.GEOJSON_DEFAULT_MAX_DETAIL_LEVEL}}function Bi(s,e){return e===n.LabelingAnimation.none?1:e===n.LabelingAnimation.fadeIn?s.labelingOpacity:1-s.labelingOpacity}function xa(s,e,t){if(!s.steps.length){t[0]=0;return}t[0]=n.clamp(s.values.length,0,3);for(let i=0;i<t[0];i++){const r=s.values[i],o=n.getColorForShaders(r);n.scale$4(o,o,e),t[i+1]=s.steps[i];const a=(i+1)*4;t[a]=o[0],t[a+1]=o[1],t[a+2]=o[2],t[a+3]=o[3]}}function vt(s,e){s.renderingProperties.color||(s.renderingProperties.color=n.toStyleColor([255,255,255,255])),n.copy$2(s.renderingProperties.color.value,e.value),e.mixFactor&&(s.renderingProperties.mixFactorColor=e.mixFactor)}function l0(s,e){s.renderingProperties.mixColor=e}function c0(s,e=void 0,t=void 0){const i=document.createElement("img");return e!==void 0&&(i.width=e),t!==void 0&&(i.height=t),new Promise(r=>{i.onload=()=>r(i),i.src=s})}function d0(s){let e;try{e={url:`data:image/svg+xml;base64,${btoa(s)}`}}catch(t){const i=URL.createObjectURL(new Blob([s],{type:"image/svg+xml"}));e={url:i,revokeURL:()=>URL.revokeObjectURL(i)}}return e}function es(s,e="image/png"){const t=new Blob([s],{type:e}),i=URL.createObjectURL(t),r=document.createElement("img");return new Promise(o=>{r.onload=()=>{URL.revokeObjectURL(i),o(r)},s.byteLength===0?r.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII=":r.src=i})}function fu(s,e){if(e[0]===s.width&&e[1]===s.height)return s;const t=document.createElement("canvas"),i=t.getContext("2d");return t.width=e[0],t.height=e[1],i.shadowColor="transparent",i.shadowBlur=0,i.drawImage(s,0,0,e[0],e[1]),t}function mu(s,e,t,i=!1){if(!e||!t||typeof OffscreenCanvas=="undefined")return null;const o=new OffscreenCanvas(e,t).getContext("2d",i?{willReadFrequently:!0}:void 0);return o?(o.drawImage(s,0,0),o.getImageData(0,0,e,t).data.buffer):null}function vu(s,e,t){var u;const i=e[s.outputBufferView],r=(u=t.get(s.actionId))!=null?u:-1,o=Math.ceil(r),a=Math.floor(r),l=(r||1)%1,c=Math.round(r);return!i||t.size<=0||a<0||o<0||c<0?void 0:{outputTransforms:new Float32Array(ss(i),s.outputBufferOffset,s.outputBufferLength),selfKeyFrame:c,selfKeyFrameMin:a,selfKeyFrameMax:o,keyFrameLerp:l}}const u0={SCALAR:1,VEC2:2,VEC3:3,VEC4:4};function gu(s,e,t){const{outputTransforms:i,selfKeyFrame:r,selfKeyFrameMin:o,selfKeyFrameMax:a,keyFrameLerp:l}=t,c=u0[s];if(e==="STEP")return ba(i,r,c);const d=ba(i,o,c),u=ba(i,a,c);switch(s){case"SCALAR":return[n.lerp$2(d[0]||0,u[0]||0,l)];case"VEC2":{const h=n.create$6();return n.lerp$1(h,d,u,l),Array.from(h)}case"VEC3":{const h=n.create$1();return n.lerp(h,d,u,l),Array.from(h)}case"VEC4":{const h=n.create$5();return n.slerp(h,d,u,l),Array.from(h)}}}function pu(s,e,t,i){let r=[0,0],o=[1,1],a=0;i&&e.forEach(h=>{if(!h.targetPointerExtension)return;const _=vu(h,t,i);if(!_)return;const f=gu(h.outputType,h.interpolation,_);h.outputType==="SCALAR"?h.targetPointerExtension==="KHR_texture_transform/rotation"&&(a=f[0]):h.outputType==="VEC2"&&(h.targetPointerExtension==="KHR_texture_transform/offset"&&(r=f),h.targetPointerExtension==="KHR_texture_transform/scale"&&(o=f))});const l=[1,0,0,0,1,0,r[0],r[1],1],c=[Math.cos(a),Math.sin(a),0,-Math.sin(a),Math.cos(a),0,0,0,1],d=[o[0],0,0,0,o[1],0,0,0,1],u=n.multiply$1(n.create$4(),l,c);s=n.multiply$1(s,u,d)}function xu(s,e,t,i,r){const o=Array();r&&e.forEach(a=>{if(a.targetPointerExtension)return;const l=vu(a,i,r);if(!l)return;const c=gu(a.outputType,a.interpolation,l);(a.outputType==="VEC4"||a.outputType==="VEC3")&&(t[a.targetMatIndex[0]][a.targetMatIndex[1]]=c)});for(let a=0;a<t.length;a++){const l=t[a];if(l.length===3){const c=n.create$2();n.fromRotationTranslationScale(c,l[1],l[0],l[2]),o.push(c)}else o.push(l)}Z0(s,o)}function ba(s,e,t){if(t!==3&&t!==4&&t!==2&&t!==1)return console.warn("Invalid animation transform size"),[];const i=[];for(let r=0;r<t;r++)i.push(s[e*t+r]);return i}function h0(s,e,t,i){s.animations.forEach((r,o)=>{r.channels.forEach((a,l)=>{var d,u;const c=(u=(d=a.target)==null?void 0:d.extensions)==null?void 0:u.KHR_animation_pointer;if(c){const h=c.pointer,_=f0(h);if(!_){console.warn(`Unsupported pointer target "${h}" in animation "${r.name}". Skip this animation channel.`);return}const f=h.split("/");if(f[1]==="materials"&&+f[2]===i){const m=r.samplers[a.sampler],v=r.name||"default",g=s.accessors[m.input];if(g.bufferView===void 0||s.bufferViews[g.bufferView]===void 0)return;ts(e,s,g.bufferView,g.componentType);const x=s.accessors[m.output];if(x.bufferView===void 0)return;const S=s.bufferViews[x.bufferView];if(S===void 0)return;ts(e,s,x.bufferView,x.componentType),(m.interpolation||"LINEAR")!=="LINEAR"&&(m.interpolation||"LINEAR")!=="STEP"&&console.warn(`Unsupported interpolation type "${m.interpolation}" in animation "${v}". Fall back to LINEAR interpolation.`);const b=bu(_);t.push({min:g.min,max:g.max,frameCount:g.count,keyFrameType:"SCALAR",interpolation:m.interpolation||"LINEAR",outputType:b.outputType,outputBufferView:x.bufferView,outputBufferOffset:S.byteOffset||0,outputBufferLength:S.byteLength/b.bufferStride,targetMatIndex:[],actionId:`${r.name}_${o}_${l}`,animationIndex:o,animationName:v,targetPointerExtension:_})}}})})}function _0(s,e,t,i,r){s.animations.forEach((o,a)=>{o.channels.forEach((l,c)=>{if(l.target.node===t){const d=o.samplers[l.sampler],u=o.name||"default",h=s.accessors[d.input];if(h.bufferView===void 0||s.bufferViews[h.bufferView]===void 0)return;ts(e,s,h.bufferView,h.componentType);const f=s.accessors[d.output];if(f.bufferView===void 0)return;const m=s.bufferViews[f.bufferView];if(m===void 0)return;ts(e,s,f.bufferView,f.componentType),(d.interpolation||"LINEAR")!=="LINEAR"&&(d.interpolation||"LINEAR")!=="STEP"&&console.warn(`Unsupported interpolation type "${d.interpolation}" in animation "${u}". Fall back to LINEAR interpolation.`);const v=bu(l.target.path);i.push({min:h.min,max:h.max,frameCount:h.count,keyFrameType:"SCALAR",interpolation:d.interpolation||"LINEAR",outputType:v.outputType,outputBufferView:f.bufferView,outputBufferOffset:m.byteOffset||0,outputBufferLength:m.byteLength/v.bufferStride,targetMatIndex:[r.length-1,v.targetindex],actionId:`${o.name}_${a}_${c}`,animationIndex:a,animationName:u})}})})}function f0(s){if(s.includes("KHR_texture_transform/offset"))return"KHR_texture_transform/offset";if(s.includes("KHR_texture_transform/rotation"))return"KHR_texture_transform/rotation";if(s.includes("KHR_texture_transform/scale"))return"KHR_texture_transform/scale"}function bu(s){let e=0,t="VEC3";const i=4;switch(s){case"translation":e=0;break;case"rotation":e=1,t="VEC4";break;case"scale":e=2;break;case"weights":e=3;break;case"KHR_texture_transform/offset":e=-1,t="VEC2";break;case"KHR_texture_transform/rotation":e=-1,t="SCALAR";break;case"KHR_texture_transform/scale":e=-1,t="VEC2";break}return{targetindex:e,outputType:t,bufferStride:i}}function ts(s,e,t,i){const r=e.bufferViews[t];if(r===void 0)return;if(!s.buffers[t]){const a=e.buffers[r.buffer].buffer;if(!a)return;s.buffers[t]=ss(a)}const o=s.buffers[t];if(!(o instanceof n.Buffer))return o}function m0(s,e){for(let t=s.length-1;t>=0;t--){const i=s[t];if(e(i,t,s))return i}}const Sa=5120,ya=5121,Ta=5122,Ea=5123,Ca=5125,Su=5126,v0=6;function Ia(s){switch(s){case Sa:case ya:return 1;case Ta:case Ea:return 2;case Ca:case Su:return 4}return 0}const g0=0,p0=8,x0=44,b0=48,S0=5,sn=Number.NaN,yu=n.create$1(),Tu=n.create$1(),Eu=n.create$1(),is=n.create$1(),On=n.create$1(),Cu=n.create$1(),Iu=n.create$1(),y0=n.create$1();function T0(s){var v;const{geometry:e,descriptor:t,sourceBuffer:i,instanceStride:r}=s,o=Au(e.position);if(!o||e.position.itemSize<3)return;const a=e.indices?Au(e.indices):void 0;if(e.indices&&!a)return;const l=(v=e.drawMode)!=null?v:n.GL_TRIANGLES;if(l!==n.GL_TRIANGLES&&l!==n.GL_TRIANGLE_STRIP&&l!==v0)return;const c=n.createTileInfo(s.tileCoords),d=[],u=[],h=s.absZ?[]:void 0,_=[],f=n.create$1(),m=n.create$1();for(let g=t.rangeStart;g<t.rangeEnd;g+=r){const p=new Uint16Array(i,g+g0,3),x=new Float32Array(i,g+p0,9),S=new Float32Array(i,g+b0,1)[0],b=s.absZ?new Float32Array(i,g+x0,1)[0]:void 0;n.set(f,p[0]-n.tileCoordOffset,p[1]-n.tileCoordOffset,0),n.tilePointToMapPoint(m,f,c);const T=S*n.maxUint16Value/n.MAP_HEIGHT_TO_TILE_HEIGHT,y=s.centroid?Ra(y0,s.centroid[0],s.centroid[1],s,x,m):void 0,E=s.axis&&s.axis.length>=4?Ra(Cu,s.axis[0],s.axis[1],s,x,m):void 0,P=s.axis&&s.axis.length>=4?Ra(Iu,s.axis[2],s.axis[3],s,x,m):void 0;P0(e,a,l,(A,F,L)=>{const D=d.length/3,B=Pa(d,u,h,o,A,s,x,m,T,b,y,E,P,Eu),Q=Pa(d,u,h,o,F,s,x,m,T,b,y,E,P,is),Z=Pa(d,u,h,o,L,s,x,m,T,b,y,E,P,On);_.push({key:s.key,tier:s.tier,vertexOffset:D,minX:Math.min(B[0],Q[0],Z[0]),minY:Math.min(B[1],Q[1],Z[1]),maxX:Math.max(B[0],Q[0],Z[0]),maxY:Math.max(B[1],Q[1],Z[1])})})}if(_.length!==0)return{key:s.key,linkId:s.linkId,tier:s.tier,triangles:_,vertices:new Float64Array(d),demAnchors:new Float64Array(u),absZ:h?new Float64Array(h):void 0}}function E0(s,e,t,i,r){var T,y,E,P,A;const o=e.vertexOffset,a=La(s,o,yu),l=La(s,o+1,Tu),c=La(s,o+2,Eu),d=n.calcBarycentricXY(a,l,c,t,is);if(!d)return;const u=d[0],h=d[1],_=d[2],f=a[2]*u+l[2]*h+c[2]*_,m=(T=r==null?void 0:r.includeAbsoluteZ)!=null?T:!0,v=(y=r==null?void 0:r.includeSurfaceTangents)!=null?y:!1;if(!(m||v))return{relativeZ:f};const p=(E=r==null?void 0:r.baseZ)!=null?E:Aa(s,o,i,On),x=(P=r==null?void 0:r.baseZ)!=null?P:Aa(s,o+1,i,On),S=(A=r==null?void 0:r.baseZ)!=null?A:Aa(s,o+2,i,On);if(p===void 0||x===void 0||S===void 0)return;const b={relativeZ:f};if(m&&(b.absoluteZ=p*u+x*h+S*_),v){const F=n.set(On,a[0],a[1],a[2]+p),L=n.set(Cu,l[0],l[1],l[2]+x),D=n.set(Iu,c[0],c[1],c[2]+S);b.surfaceTangents=n.calcSurfaceTangents(F,L,D)}return b}function Pa(s,e,t,i,r,o,a,l,c,d,u,h,_,f){const m=L0(i,r,yu),v=Pu(Tu,m,o.localMatrix,a),g=C0(v,c,o),p=n.set(f,l[0]+v[0],l[1]+v[1],g);return s.push(p[0],p[1],p[2]),I0(e,p,v,m,o,l,u,h,_),t&&t.push(o.extToReliefNeeded&&Fa(v)?Number.NaN:d!=null?d:0),p}function C0(s,e,t){return t.absZ&&t.collapseHeightNeeded&&!Fa(s)?e:e+s[2]}function I0(s,e,t,i,r,o,a,l,c){if(r.extToReliefNeeded&&Fa(t)){s.push(o[0],o[1],0,0,sn);return}switch(r.demPosition){case n.GltfDemPosition.flat:s.push(e[0],e[1],0,0,sn);break;case n.GltfDemPosition.axis:if(r.axis&&l&&c){const d=A0(r.axis,i);s.push(l[0],l[1],c[0],c[1],d);break}s.push(o[0],o[1],0,0,sn);break;case n.GltfDemPosition.centroid:if(a){s.push(a[0],a[1],0,0,sn);break}s.push(o[0],o[1],0,0,sn);break;default:s.push(o[0],o[1],0,0,sn)}}function Aa(s,e,t,i){var f;const r=(f=s.absZ)==null?void 0:f[e];if(r!==void 0&&!Number.isNaN(r))return r;const o=e*S0,a=s.demAnchors[o],l=s.demAnchors[o+1],c=s.demAnchors[o+2],d=s.demAnchors[o+3],u=s.demAnchors[o+4];n.set(i,a,l,0);const h=t(i);if(h===void 0)return;if(Number.isNaN(u))return h*n.MAP_POINTS_IN_METER;n.set(i,c,d,0);const _=t(i);if(_!==void 0)return(h*(1-u)+_*u)*n.MAP_POINTS_IN_METER}function La(s,e,t){const i=e*3;return t[0]=s.vertices[i],t[1]=s.vertices[i+1],t[2]=s.vertices[i+2],t}function P0(s,e,t,i){var a,l;const r=(l=(a=s.indices)==null?void 0:a.count)!=null?l:s.position.count,o=c=>e?R0(e,c):c;if(t===n.GL_TRIANGLES){for(let c=0;c+2<r;c+=3)i(o(c),o(c+1),o(c+2));return}if(t===n.GL_TRIANGLE_STRIP){for(let c=0;c+2<r;c++)i(o(c),o(c+1),o(c+2));return}for(let c=1;c+1<r;c++)i(o(0),o(c),o(c+1))}function Ra(s,e,t,i,r,o){n.set(is,e,0,t);const a=Pu(s,is,i.localMatrix,r);return s[0]=o[0]+a[0],s[1]=o[1]+a[1],s[2]=0,s}function Pu(s,e,t,i){return t&&t.length===16?n.transformMat4$1(s,e,t):n.copy$1(s,e),n.transformMat3(s,s,i),s}function A0(s,e){const t=s[2]-s[0],i=s[3]-s[1],r=Math.hypot(t,i);if(r===0)return 0;const o=(e[0]-s[0])/r,a=(e[2]-s[1])/r;return n.clamp(o*(t/r)+a*(i/r),0,1)}function Fa(s){return s[2]<1e-4}function Au(s){const e=Ia(s.componentType);if(e!==0)return{source:s,view:new DataView(s.buffer),componentSize:e,byteStride:s.byteStride||s.itemSize*e}}function L0(s,e,t){return t[0]=ns(s,e,0),t[1]=ns(s,e,1),t[2]=ns(s,e,2),t}function R0(s,e){return ns(s,e,0)}function ns(s,e,t){const{source:i,view:r,componentSize:o,byteStride:a}=s,l=i.byteOffset+e*a+t*o;let c;switch(i.componentType){case Sa:c=r.getInt8(l);break;case ya:c=r.getUint8(l);break;case Ta:c=r.getInt16(l,!0);break;case Ea:c=r.getUint16(l,!0);break;case Ca:c=r.getUint32(l,!0);break;case Su:c=r.getFloat32(l,!0);break;default:c=0}return i.normalized?Lu(c,i.componentType):c}function Lu(s,e){switch(e){case Sa:return Math.max(s/127,-1);case ya:return s/255;case Ta:return Math.max(s/32767,-1);case Ea:return s/65535;case Ca:return s/4294967295}return s}const F0=24,D0=new Set(["position","texcoord_0","texcoord_1","texcoord_2","texcoord_3","normal","tangent"]),z0=Array.from(n.create$2()),B0={pbrMetallicRoughness:{baseColorFactor:[1,1,1,1],metallicFactor:1,roughnessFactor:1},emissiveFactor:[0,0,0],alphaMode:"OPAQUE",alphaCutoff:.5,doubleSided:!1};function O0(s){return Ru(s,B0),s}function Ru(s,e){for(const t in e)s[t]===void 0?s[t]=e[t]:typeof s[t]=="object"&&Ru(s[t],e[t])}var gt=(s=>(s[s.Pending=1]="Pending",s[s.Loaded=2]="Loaded",s[s.Failed=3]="Failed",s))(gt||{});function w0(s){return{buffers:[],textures:[],status:1,scenes:[],defaultScene:0,preserve:s,isTiered:!1}}function N0(s){const e=n.createBox3D();for(const t of s){const i=t.bbox;i&&(n.expandBox3DByPoint(e,i.min),n.expandBox3DByPoint(e,i.max))}return n.calculateBox3DDiag(e)}function k0(s,e,t,i,r,o,a){var u;const l=[],c=[],d=t.nodes.some(h=>n.isObject(h.extras)&&h.extras.foundation===!0);for(const h of t.scenes){const _=[];Fu(_,s,h.nodes,t,l,c,e,i,r,o,d,a);const f=N0(_);if(f!==void 0)for(const m of _)m.attributes.bboxDiag=f;s.scenes.push({id:n.uniqId(),name:h.name,objects:_})}return s.defaultScene=(u=t.scene)!=null?u:0,s}function Fu(s,e,t,i,r,o,a,l,c,d,u,h){var f,m,v,g,p,x,S,b,T;if(!t)return;const _=a.symbolSettingsList.gltfModel.instances;if(!(!_||_.length===0))for(const y of t){const E=i.nodes[y];if(n.isObject(E.extras)&&E.extras.ignore)continue;const P=[...r],A=[...o];if(E.matrix&&P.push(E.matrix),E.translation&&E.rotation&&E.scale){const F=[];F.push(E.translation,E.rotation,E.scale),P.push(F),_0(i,e,y,A,P)}if(E.mesh!==void 0){const F=i.meshes[E.mesh];let L=d?n.GltfDemPosition.flat:n.GltfDemPosition.default;n.isObject(E.extras)&&(E.extras.dem==="flat"?L=n.GltfDemPosition.flat:E.extras.dem==="instance"&&(L=n.GltfDemPosition.default));const D=new Float32Array(16),B=new Float32Array(9);pu(B,A,e.buffers),xu(D,A,P,e.buffers);let Q,Z;if(E.children){const $=[];for(const J of E.children){const ge=i.nodes[J];j0(ge)&&$.push(ge)}if($.length){const J=$[0];if(J.extras.dem==="centroid")L=n.GltfDemPosition.centroid,Q=[J.translation[0],J.translation[2]];else if(J.extras.dem==="axis"){L=n.GltfDemPosition.axis;const ge=m0($,Ce=>Ce.extras.dem==="axis");Z=[J.translation[0],J.translation[2],(ge!=null?ge:J).translation[0],(ge!=null?ge:J).translation[2]]}}}for(const $ of F.primitives){const J=[],ge={};let Ce=0,tt,Ie,it;for(const xe in $.attributes){const Be=/TEXCOORD_(\d+)/.exec(xe);Be&&(J[parseInt(Be[1],10)]=!0);const Oe=xe.toLowerCase();if(!D0.has(Oe))continue;const qt=$.attributes[xe],fe=i.accessors[qt];if(fe.bufferView===void 0)continue;const yt=i.bufferViews[fe.bufferView];if(yt===void 0)continue;const Yt=wu(a,e,i,fe.bufferView,fe.componentType);if(Yt){if(Oe==="position"&&(Ie=fe.min,it=fe.max,tt=Nu(i,fe,yt,ku(fe.type))),Yt.purpose="gltfMesh",ge[xe.toLowerCase()]=new n.BufferChannel(Yt,{itemSize:ku(fe.type),dataType:n.componentTypeToWebGl(fe.componentType),stride:(f=yt.byteStride)!=null?f:0,offset:(m=fe.byteOffset)!=null?m:0,normalized:!!fe.normalized}),!Q&&xe.toLowerCase()==="position"){const zt=fe.min,mn=fe.max;zt&&mn&&(Q=[(mn[0]+zt[0])/2,(mn[2]+zt[2])/2])}Ce===0&&(Ce=fe.count)}}Ie||(Ie=[0,0,0]),it||(it=[0,0,0]);let Xt,$t;if($.indices!==void 0){const xe=i.accessors[$.indices];if(xe.bufferView===void 0)continue;const Be=i.bufferViews[xe.bufferView];if(Be===void 0||(Xt=wu(a,e,i,xe.bufferView,xe.componentType,!0),!Xt))continue;$t=Nu(i,xe,Be,1),Xt.purpose="gltfIndices",Ce=xe.count}const xt=$.material!==void 0?i.materials[$.material]:{},Ze=O0(xt),bt={},ee={localMatrix:D,textureTransformMatrix:B,animationStack:A,transformStack:P,availableTextureCoords:J,attributesAliases:bt,colorFactor:[...Ze.pbrMetallicRoughness.baseColorFactor],colorTexture:NaN,aoTexture:NaN,pbrTexture:NaN,centroid:Q,axis:Z,demPosition:L,isFoundation:n.isObject(E.extras)&&E.extras.foundation===!0,hasFoundation:u},me=[];Ze.alphaMode==="OPAQUE"?me.push({type:Vd,value:Tx}):Ze.alphaMode==="BLEND"&&me.push({type:Vd,value:Ex});const dt=n.isObject(Ze.extras)?Ze.extras.vatTexture:void 0;if(n.isObject(dt)&&dt.index!==void 0){const xe=dt.texCoord;if(typeof xe!="number"||!Number.isInteger(xe)||xe<0||!ge[`texcoord_${xe}`])continue;const Be=i.textures[dt.index],Oe=n.isObject(Be==null?void 0:Be.extras)?(v=Be.extras.remap_info)==null?void 0:v["os-remap"]:void 0,qt=Oe==null?void 0:Oe.Min,fe=Oe==null?void 0:Oe.Max,yt=Oe==null?void 0:Oe.Frames,Yt=n.isObject(Be==null?void 0:Be.extras)?Be.extras.height:void 0,zt=(g=Oe==null?void 0:Oe.duration)!=null?g:yt?yt/F0:void 0;qt&&fe&&yt&&Yt&&zt!==void 0&&(ee.useVat=!0,ee.vatTexture=dt.index,ee.vatMin=qt,ee.vatMax=fe,ee.vatFrameCount=yt,ee.vatTextureHeight=Yt,ee.vatDuration=zt,ee.vatAnimationIndex=i.animations.length,ee.vatAnimationName=typeof Be.name=="string"?Be.name:void 0,bt.texcoord_vat=`texcoord_${xe}`,rs(e,i,{index:dt.index,texCoord:dt.texCoord}),me.push({type:yx}))}const St=Ze.pbrMetallicRoughness.baseColorTexture;St&&(me.push({type:Sx}),bt.texcoord_color=`texcoord_${(p=St.texCoord)!=null?p:0}`,rs(e,i,St),ee.colorTexture=St.index);const nt=Ze.pbrMetallicRoughness.metallicRoughnessTexture;if(nt){me.push({type:px}),rs(e,i,nt),ee.pbrTexture=nt.index;const xe=typeof nt.texCoord=="number"?nt.texCoord:0;bt.texcoord_pbr=`texcoord_${xe}`,J[xe]=!1}else ee.roughness=(x=Ze.pbrMetallicRoughness.roughnessFactor)!=null?x:1,ee.metallic=(S=Ze.pbrMetallicRoughness.metallicFactor)!=null?S:1;Number.isNaN(c.style.roughness)||me.push({type:gx}),((b=E.extras)==null?void 0:b.tier)!==void 0&&(e.isTiered=!0,ee.meshTier=E.extras.tier,me.push({type:bx})),c.style.lightingModel==="pbr"?me.push({type:Zd,value:Ix}):me.push({type:Zd,value:Cx});const ot=Ze.occlusionTexture;if(ot){me.push({type:xx}),rs(e,i,ot),ee.aoTexture=ot.index;const xe=typeof ot.texCoord=="number"?ot.texCoord:0;bt.texcoord_ao=`texcoord_${xe}`,J[xe]=!1}h0(i,e,A,$.material);const Dt={start:0,count:Ce,attributes:ee,drawMode:$.mode,accessors:ge,elementsBuffer:Xt,gltfGeometry:tt?{position:tt,indices:$t,drawMode:(T=$.mode)!=null?T:n.GL_TRIANGLES}:void 0,shaderDefinitions:me,bbox:{min:Ie,max:it}};h.map.state.sunda&&V0(h,i,$.attributes,$.indices,D,ee.colorFactor,Ze,c.style.lightingModel==="pbr"?2:1,Dt,`model:${l}`),s.push(Dt)}}E.children&&Fu(s,e,E.children,i,P,A,a,l,c,d,u,h)}}const U0=5120,Du=5121,M0=5122,zu=5123,Bu=5125;function H0(s,e,t){switch(t){case U0:return s.getInt8(e);case Du:return s.getUint8(e);case M0:return s.getInt16(e,!0);case zu:return s.getUint16(e,!0);case Bu:return s.getUint32(e,!0);default:return s.getFloat32(e,!0)}}function Ou(s){return s instanceof ArrayBuffer?new DataView(s):new DataView(s.buffer,s.byteOffset,s.byteLength)}function wn(s,e,t){var v,g,p,x;if(e===void 0)return null;const i=s.accessors[e];if(!i||i.bufferView===void 0)return null;const r=s.bufferViews[i.bufferView],o=(v=s.buffers[r.buffer])==null?void 0:v.buffer;if(!o)return null;const a=Ia(i.componentType);if(a===0)return null;const l=Ou(o),c=((g=r.byteOffset)!=null?g:0)+((p=i.byteOffset)!=null?p:0),d=t*a,u=(x=r.byteStride)!=null?x:0,h=u>0?u:d,_=!!i.normalized,f=i.count,m=new Float32Array(f*t);for(let S=0;S<f;S++){const b=c+S*h;for(let T=0;T<t;T++){const y=H0(l,b+T*a,i.componentType);m[S*t+T]=_?Lu(y,i.componentType):y}}return m}function G0(s,e){var d,u,h;const t=s.accessors[e];if(!t||t.bufferView===void 0)return null;const i=s.bufferViews[t.bufferView],r=(d=s.buffers[i.buffer])==null?void 0:d.buffer;if(!r)return null;const o=Ou(r),a=((u=i.byteOffset)!=null?u:0)+((h=t.byteOffset)!=null?h:0),l=t.count;if(t.componentType===Bu){const _=new Uint32Array(l);for(let f=0;f<l;f++)_[f]=o.getUint32(a+f*4,!0);return{data:_.buffer,count:l,u32:!0}}const c=new Uint16Array(l+(l&1));if(t.componentType===Du)for(let _=0;_<l;_++)c[_]=o.getUint8(a+_);else if(t.componentType===zu)for(let _=0;_<l;_++)c[_]=o.getUint16(a+_*2,!0);else return null;return{data:c.buffer,count:l,u32:!1}}function V0(s,e,t,i,r,o,a,l,c,d){var tt,Ie,it,Xt,$t,xt,Ze,bt;const u=s.sunda.ledger;if(!u)return;const h=wn(e,t.POSITION,3);if(!h)return;const _=wn(e,t.NORMAL,3),f=Da(e,a.pbrMetallicRoughness.baseColorTexture),m=Da(e,a.occlusionTexture),v=Da(e,a.pbrMetallicRoughness.metallicRoughnessTexture),g=wn(e,t[`TEXCOORD_${(tt=f==null?void 0:f.texCoord)!=null?tt:0}`],2),p=wn(e,t[`TEXCOORD_${(Ie=m==null?void 0:m.texCoord)!=null?Ie:0}`],2),x=wn(e,t[`TEXCOORD_${(it=v==null?void 0:v.texCoord)!=null?it:0}`],2),S=h.length/3,b=r,T=!!b&&b.length===16,y=new Float32Array(S*12);for(let ee=0;ee<S;ee++){const me=h[ee*3],dt=h[ee*3+1],St=h[ee*3+2];let nt=_?_[ee*3]:0,ot=_?_[ee*3+1]:0,Dt=_?_[ee*3+2]:1,xe=me,Be=dt,Oe=St;if(T){xe=b[0]*me+b[4]*dt+b[8]*St+b[12],Be=b[1]*me+b[5]*dt+b[9]*St+b[13],Oe=b[2]*me+b[6]*dt+b[10]*St+b[14];const yt=b[0]*nt+b[4]*ot+b[8]*Dt,Yt=b[1]*nt+b[5]*ot+b[9]*Dt,zt=b[2]*nt+b[6]*ot+b[10]*Dt;nt=yt,ot=Yt,Dt=zt}const qt=Math.hypot(nt,ot,Dt)||1,fe=ee*12;y[fe]=xe,y[fe+1]=Be,y[fe+2]=Oe,y[fe+3]=nt/qt,y[fe+4]=ot/qt,y[fe+5]=Dt/qt,y[fe+6]=g?g[ee*2]:0,y[fe+7]=g?g[ee*2+1]:0,y[fe+8]=p?p[ee*2]:0,y[fe+9]=p?p[ee*2+1]:0,y[fe+10]=x?x[ee*2]:0,y[fe+11]=x?x[ee*2+1]:0}let E,P,A;if(i!==void 0){const ee=G0(e,i);if(!ee)return;E=ee.data,P=ee.count,A=ee.u32}else if(P=S,A=S>65535,A){const ee=new Uint32Array(S);for(let me=0;me<S;me++)ee[me]=me;E=ee.buffer}else{const ee=new Uint16Array(S+(S&1));for(let me=0;me<S;me++)ee[me]=me;E=ee.buffer}const F=n.uniqId(),L=n.uniqId();u.uploadBuffer(F,y.buffer,!1,d,48),u.uploadBuffer(L,E,!0,d);const D=(Xt=o[3])!=null?Xt:1;let B;f&&(B=n.uniqId(),u.uploadTexture(B,f.data,f.width,f.height));let Q;m&&(Q=n.uniqId(),u.uploadTexture(Q,m.data,m.width,m.height));let Z;v&&(Z=n.uniqId(),u.uploadTexture(Z,v.data,v.width,v.height));const $=(ee,me)=>T?[b[0]*ee+b[8]*me+b[12],b[1]*ee+b[9]*me+b[13],b[2]*ee+b[10]*me+b[14]]:[ee,0,me],J=c.attributes,ge=J.centroid,Ce=J.axis;c.sundaGltf={vertexBufferId:F,indexBufferId:L,indexCount:P,indexU32:A,color:[(($t=o[0])!=null?$t:1)*D,((xt=o[1])!=null?xt:1)*D,((Ze=o[2])!=null?Ze:1)*D,D],colorTextureId:B,aoTextureId:Q,pbrTextureId:Z,metallic:a.pbrMetallicRoughness.metallicFactor,roughness:a.pbrMetallicRoughness.roughnessFactor,lightingModel:l,demPosition:(bt=J.demPosition)!=null?bt:n.GltfDemPosition.default,demAnchorBaked:ge?$(ge[0],ge[1]):void 0,demAxisBakedStart:Ce?$(Ce[0],Ce[1]):void 0,demAxisBakedEnd:Ce?$(Ce[2],Ce[3]):void 0}}function Da(s,e){var c,d,u,h,_;const t=e;if(!t)return null;const i=s.textures[(c=t.index)!=null?c:0];if(!i||i.source===void 0)return null;const r=(d=s.images[i.source])==null?void 0:d.image,o=(u=r==null?void 0:r.width)!=null?u:0,a=(h=r==null?void 0:r.height)!=null?h:0;if(!r)return null;const l=mu(r,o,a,!0);return l?{data:l,width:o,height:a,texCoord:(_=t.texCoord)!=null?_:0}:null}function rs(s,e,t){var c;const i=(c=t.index)!=null?c:0,r=e.textures[i];if(!r||r.source===void 0||r.sampler===void 0)return;const o=e.images[r.source],a=e.samplers[r.sampler];if(!a||!o)return;const l={flipY:!1};if(a.magFilter&&(l.magFilter=ar(a.magFilter)),a.minFilter&&(l.minFilter=ar(a.minFilter)),a.wrapS&&(l.wrapS=ar(a.wrapS)),a.wrapT&&(l.wrapT=ar(a.wrapT)),t.texCoord!==void 0&&(l.texcoord=t.texCoord),!o.image&&o.bufferView){W0(e,o).then(d=>{d&&(o.image=d,s.textures[i]=new C(o.image,l))});return}s.textures[i]=new C(o.image,l)}function wu(s,e,t,i,r,o=!1){const a=t.bufferViews[i];if(a===void 0)return;if(!e.buffers[i]){const c=t.buffers[a.buffer].buffer;if(!c)return;const d=new DataView(ss(c),a.byteOffset,a.byteLength),u=s.createBuffer(d,{dataType:n.componentTypeToWebGl(r)},o);e.buffers[i]=u}const l=e.buffers[i];if(!(l instanceof ArrayBuffer))return l}function Nu(s,e,t,i){var a,l;const r=s.buffers[t.buffer].buffer;if(!r)return;const o=Ia(e.componentType);if(o!==0)return{buffer:ss(r),byteOffset:((a=t.byteOffset)!=null?a:0)+((l=e.byteOffset)!=null?l:0),byteStride:t.byteStride||i*o,componentType:e.componentType,normalized:e.normalized,count:e.count,itemSize:i}}function Z0(s=[],e){if(e.length===0)return Array.from(z0);n.copy(s,e[0]);for(let t=1;t<e.length;t++)n.mul$1(s,s,e[t]);return s}function ku(s){switch(s[0]){case"S":return 1;case"V":return Number(s[3]);case"M":return Re(Number(s[3]),2)}return console.error(`Failed to determine channels count from accessor type = ${s}`),0}function ss(s){return s instanceof ArrayBuffer?s:s.buffer}function W0(s,e){return q(this,null,function*(){if(!e.bufferView)return!1;const t=s.bufferViews[e.bufferView];if(t===void 0)return!1;const i=s.buffers[t.buffer].buffer;return i?es(new Uint8Array(i,t.byteOffset,t.byteLength),e.mimeType):!1})}function j0(s){return s.mesh===void 0&&n.isObject(s.extras)&&(s.extras.dem==="centroid"||s.extras.dem==="axis")}const X0=n.len$1([1,1,1]),Oi=n.create$1(),za=n.create$1(),$0=n.create$2();function q0(s,e){n.invert(s,e);const t=n.create$2();t[12]+=s[12],t[13]+=s[13],n.mul$1(s,s,t)}function Ba(s){return s.symbol==="gltfModel"&&s.sink==="instances"}function Y0(s,e,t,i,r){var d;const o=s.modelMatrices.get(0);if(!o)return;const a=[t[0]/n.maxUint16Value,t[1]/n.maxUint16Value,t[2]/n.maxUint16Value],l=[t[3]/n.maxUint16Value,t[4]/n.maxUint16Value,t[5]/n.maxUint16Value],c={min:[0,0,0],max:[0,0,0]};if(n.transformMat4$1(c.min,a,o),n.transformMat4$1(c.max,l,o),r)if(i.tMatrix3x3){const u=Q0(r,i.tMatrix3x3,e);n.add$1(c.min,c.min,u.min),n.add$1(c.max,c.max,u.max)}else{let u=Math.max(n.len$1(r.max),n.len$1(r.min));if(e){const h=Oi,_=za;n.decomposeMat4(e,h,_);const f=n.len$1(h)/X0;u*=f,u+=n.len$1(_)}u*=(d=i.maxDiag)!=null?d:1,n.set(Oi,-u,-u,-u),n.add$1(c.min,c.min,Oi),n.set(Oi,u,u,u),n.add$1(c.max,c.max,Oi)}return c}function Q0(s,e,t){const i=n.set$2($0,e[0],e[1],e[2],0,e[3],e[4],e[5],0,e[6],e[7],e[8],0,0,0,0,1);t&&n.mul$1(i,i,t);const r=n.lerp(Oi,s.min,s.max,.5),o=n.scale(za,n.sub$1(za,s.max,s.min),.5),a=n.transformMat4$1(Oi,r,i),l=n.fromValues(Math.abs(i[0])*o[0]+Math.abs(i[4])*o[1]+Math.abs(i[8])*o[2],Math.abs(i[1])*o[0]+Math.abs(i[5])*o[1]+Math.abs(i[9])*o[2],Math.abs(i[2])*o[0]+Math.abs(i[6])*o[1]+Math.abs(i[10])*o[2]),c=n.sub$1(n.create$1(),a,l),d=n.add$1(n.create$1(),a,l);return{min:c,max:d}}class J0{constructor(e){this.modules=e,this.queue=new Map}enqueue(e,t){this.queue.set(t.id,{batch:e,tile:t,state:void 0})}update(){const{renderer:e,tileManager:t}=this.modules;for(const i of t.getTileObjects()){const r=this.queue.get(i.id);if(!r)continue;const{batch:o}=r,{symbol:a,sink:l}=o,c=n.getSymbolLayers(e,a,l);if(!c){console.error(`Cannot happen! Symbol ${a} does not have sink ${l}!`);continue}const d=c[0].instanceBinder;if(!d){console.error("Cannot happen! No instanceBinder for batch inside instanceLinker queue.");continue}const u=d(this.modules,o,i,r.state);if(!u){this.queue.delete(i.id);continue}r.state=u}}}function K0(s,e,t,i,r,o,a,l,c,d,u,h){const _=n.stride(o,a),f=n.getSymbolLayers(e,o,a),{accessors:m,elementsBuffer:v,count:g,drawMode:p,bbox:x}=i,S=n.Shader.createShaderDefinitions(i.shaderDefinitions);u.linkId=t;for(const b of f){const T=b.uniformSet||"fill",y=JSON.stringify(Object.values(c))+"_"+T+"_"+r.detailLevel,E=e.requestAsyncShaderProgramLink(b.programName,S),P=l.buffer;if(!P){console.error(`Expected existing buffer while linking instance, but ${P} found.`);continue}const A=b.vaoCreator(P,E,v,m);u.attributesAliases&&A.setAttributesAliases(u.attributesAliases);const F={id:n.uniqId(),type:n.SceneObjectType.Tile,layerSettings:b,start:0,count:g,attributes:c,shaderDefinitions:S,renderingProperties:d,meta:u,attributesHash:y,vao:A,drawMode:p,tile:r,bbox:x,bboxWorld:h,symbol:o,sink:a,canRender:!0,instanceCount:(l.rangeEnd-l.rangeStart)/_,sundaGltf:i.sundaGltf,sundaInstance:r.sundaInstanceBufferId!==void 0?{bufferId:r.sundaInstanceBufferId,offset:l.rangeStart}:void 0};r.push(F),s.push(F)}s.length&&e.addRerenderEvent({type:"instanceLink"})}function Uu(s,e,t){eb(e,i=>{var o;const r=((o=i.meta)==null?void 0:o.linkId)===t;return r&&s.push(i),!r})}function eb(s,e){s.children=s.children.filter(e),s.identifyChildren=s.identifyChildren.filter(e),s.depthTestChildren=s.depthTestChildren.filter(e),s.labelTestChildren=s.labelTestChildren.filter(e),s.shadowChildren=s.shadowChildren.filter(e)}const tb={min:[0,0,0],max:[0,0,0]},os=(s,e,t,i)=>{var c,d;const{assetManager:r,modelsScene:o,renderer:a}=s;if(i||(i={}),t.destroyed){const u=[];for(const h in i){const _=i[+h];Number.isNaN(_.linkId)||Uu(u,t,_.linkId)}for(const h of u)o.removeSceneObject(h.id);return}const l=[];for(let u=0;u<e.generatedObjects.length;u++){const h=e.generatedObjects[u],_=n.GltfModelGenerator.sinks.instances.unpackObjectAttributes(h.attributes),{extents:f}=h;i[u]||(i[u]={modelId:NaN,linkId:NaN});const m=i[u];let v;const g=!!m.referenceBbox;m.referenceBbox?v=m.referenceBbox:(v=tb,v.min[0]=f[0]/n.maxUint16Value,v.min[1]=f[1]/n.maxUint16Value,v.min[2]=f[2]/n.maxUint16Value,v.max[0]=f[3]/n.maxUint16Value,v.max[1]=f[4]/n.maxUint16Value,v.max[2]=f[5]/n.maxUint16Value);const{styleId:p}=_,x=m.modelId,S=m.sceneId;o.updateModelId(m,_,v,t,g);const b=m.modelId;if(b===void 0||Number.isNaN(b))continue;const T=m.sceneId;if(T===void 0||Number.isNaN(T)||x===b&&S===T)continue;const y=r.getModel(b,p);if(!y||y.status!==gt.Loaded)continue;const E=(d=(c=y==null?void 0:y.scenes.find(F=>F.id===m.sceneId))==null?void 0:c.objects)!=null?d:[];if(E.length===0)continue;const P=m.linkId;if(!Number.isNaN(P)){const F=[];Uu(F,t,P);for(const L of F)o.removeSceneObject(L.id)}const A=n.uniqId();m.linkId=A;for(let F=0;F<E.length;F++){const L=E[F],D=t.modelMatrices.get(0),B=new Float32Array(16);q0(B,D);const{attributesAliases:Q,availableTextureCoords:Z,colorTexture:$,colorFactor:J,aoTexture:ge,pbrTexture:Ce,metallic:tt,roughness:Ie,meshTier:it,animationStack:Xt,transformStack:$t,localMatrix:xt,demPosition:Ze,axis:bt,centroid:ee,isFoundation:me,hasFoundation:dt,textureTransformMatrix:St,bboxDiag:nt,useVat:ot,vatTexture:Dt,vatMin:xe,vatMax:Be,vatFrameCount:Oe,vatTextureHeight:qt,vatDuration:fe,vatAnimationIndex:yt,vatAnimationName:Yt}=L.attributes,zt=Y0(t,xt,f,h,L.bbox);!m.referenceBbox&&zt&&(m.referenceBbox=zt);const mn=I({colorTexture:$,colorFactor:J,aoTexture:ge,pbrTexture:Ce,metallic:tt,roughness:Ie,meshTier:it,demPosition:Ze,axis:bt,centroid:ee,isFoundation:me,hasFoundation:dt,bboxDiag:nt,useVat:ot,vatTexture:Dt,vatMin:xe,vatMax:Be,vatFrameCount:Oe,vatTextureHeight:qt,vatDuration:fe,vatAnimationIndex:yt,vatAnimationName:Yt},_);nt!==void 0&&ib(s,_.styleId,_.layerId,mn.tileData,nt);const $P={modelId:b,animationStack:Xt,transformStack:$t,localMatrix:new Float32Array(xt!=null?xt:[]),textureTransformMatrix:new Float32Array(St!=null?St:[]),transformMatrix:B,useVat:ot,vatTexture:Dt,vatMin:xe,vatMax:Be,vatFrameCount:Oe,vatTextureHeight:qt,vatDuration:fe,vatAnimationIndex:yt,vatAnimationName:Yt,vatFrame:0},qP=l.length;if(K0(l,a,A,L,t,e.symbol,e.sink,h,mn,$P,V(I({},h.meta),{attributesAliases:Q,availableTextureCoords:Z}),zt),l.length>qP&&it!==void 0&&it!==0&&L.gltfGeometry){const Q_=T0({key:`gltf:${A}:${F}`,linkId:A,tier:it,tileCoords:t.coords,sourceBuffer:e.buffer,descriptor:h,instanceStride:n.GltfModelGenerator.sinks.instances.stride,geometry:L.gltfGeometry,absZ:!!_.absZ,demPosition:Ze,centroid:ee,axis:bt,localMatrix:xt,extToReliefNeeded:_.extToReliefNeeded,collapseHeightNeeded:_.collapseHeightNeeded});Q_&&s.elevationIndex.registerGltfTierSurface(Q_)}}}return l.forEach(u=>{o.addSceneObject(u)}),i};function ib(s,e,t,i,r){const o=s.styleManager.getStyleLayer(e,t);if(o)for(let a=0;a<o.precomputes.length;a++){if(i[a]!==null)continue;const l=o.precomputes[a].expr;typeof l=="object"&&l!==null&&l.type==="get"&&l.property==="bboxDiag"&&(i[a]=r)}}const as=new Float32Array(16),Mu=1e-4;let Me,He;function z(...s){return(t,i,r,o,a,l)=>{for(const c of s)if(!c(t,i,r,o,a,l))return!1;return!0}}const H=(s,e,t,i)=>(t.renderer.bindShaderProgram(s,{u_mat4_mvp:i.tile.renderMvpMatrix}),!0);function wi(s,e,t){return!!s.styleState.globeEnabled&&!t&&(e.coords[2]<n.globeConfig.globeMaxZoom&&e.ecefDataState===n.EcefDataState.DerivedFromTile||e.ecefDataState===n.EcefDataState.Present)}const Oa=[0,0],Hu=new Float32Array(4),Gu=n.create$3(),wa=[0,0],Na=new Float64Array([0,0,0,1]),Te=(s,e,t,i)=>{const{camera:{globeRatio:r,ecefMvpMatrix:o,viewProjectionMatrix:a},styleManager:l,renderer:c}=t,d=l.getStyle(e.handyStyleId);if(!(d==null?void 0:d.environment))return!1;const h=i.tile;if(!h.renderModelMatrix)return!1;const f=wi(e,h,t.map.getFeatureFlag("globeOff"));let m=r;return f&&r<Mu?m=Mu:!f&&r>0&&(m=0),m===0?(c.bindShaderProgram(s,{u_mat4_flat_mvp:i.tile.renderMvpMatrix,u_float_crossfade:m}),!0):m===1?(c.bindShaderProgram(s,{u_mat4_flat_mvp:i.tile.renderMvpMatrix,u_mat4_ecef_mvp:o,u_float_crossfade:m}),!0):(n.Mercator.toGeo(e.center,wa),Oa[0]=n.degToRad(wa[0]),Oa[1]=Math.log(Math.tan(Math.PI/4+n.degToRad(wa[1])/2)),Na[0]=e.center[0],Na[1]=e.center[1],n.transformMat4(Gu,Na,a),Hu.set(Gu),c.bindShaderProgram(s,{u_mat4_flat_mvp:i.tile.renderMvpMatrix,u_mat4_ecef_mvp:o,u_mat4_vp:a,u_vec2_camera_merc:Oa,u_vec4_vp_at_center:Hu,u_float_crossfade:m}),!0)},ls=n.maxTilePoint/2,nb=[ls,ls,0],rb=[ls+1,ls,0],ui=[0,0,0],xi=[0,0,0],Vu=new WeakMap,sb=16;function Zu(s){let e=Vu.get(s);if(e===void 0){const t=n.createTileInfo(s.coords);n.tilePointToMapPoint(ui,nb,t),n.tilePointToMapPoint(xi,rb,t),n.Mercator.toGeo(ui,ui);const i=ui[1];n.Mercator.toGeo(xi,xi),n.Ecef.fromGeo(ui,ui),n.Ecef.fromGeo(xi,xi);const r=xi[0]-ui[0],o=xi[1]-ui[1],a=xi[2]-ui[2],l=Math.sqrt(r*r+o*o+a*a),c=Math.min(n.Mercator.scaleFactor(i),sb)/(Math.PI/2);e=l/n.worldSize*c,Vu.set(s,e)}return e}const Ni=(s,e,{renderer:t,map:i},r)=>(t.bindShaderProgram(s,{u_float_ecef_scale:wi(e,r.tile,i.getFeatureFlag("globeOff"))?Zu(r.tile):0}),!0),cs=(s,e,t,i)=>(t.renderer.bindShaderProgram(s,{u_mat4_flat_map_mvp:i.tile.renderFlatMapTexMatrix}),!0),K=(s,e,t,i)=>i.tile.renderModelMatrix?(n.copy(as,i.tile.renderModelMatrix),t.renderer.bindShaderProgram(s,{u_mat4_model:as}),!0):!1,ds=(s,e,t,i)=>(t.renderer.bindShaderProgram(s,{u_int_abs_z:i.attributes.absZ?1:0}),!0),N=(s,e,{renderer:t},i,r,o)=>{if(o.terrain3d){if(!i.tile.renderModelMatrix)return!1;t.bindShaderProgram(s,{u_mat4_dem_mvp:i.tile.renderDemMatrix,u_float_vertical_scale:1/i.tile.renderModelMatrix[10]})}return!0};function on(s,e){return n.makeBinderContext(s.styleZoom,s.pitch,s.styleState,e.attributes.tileData)}const ka=(s,e,t,i,r)=>{var m;Me=void 0;const o=on(e,i),a=n.resolveString(r.style.textureImage,o);let l=!1;r.type==="polygon"&&(l=r.style.lengthUnits===n.LengthUnits.Meters);const c=t.styleManager.getStyle(i.attributes.styleId);if(!c)return!0;const d=(m=c.rasterSets.byKey[n.getStaticTextureRasterSetKey(a)])==null?void 0:m.rasters;if(!d)return!0;const u=n.resolveExpression(r.style.textureSize,o);let[h,_]=Array.isArray(u)?u:[u,u];if(l&&(h=h*n.getPixelsPerMeter(h,h),_=_*n.getPixelsPerMeter(_,_)),h<=0||_<=0)return!0;const f=n.selectRaster(d,h*window.devicePixelRatio,!0);return f===void 0||(Me=d[f]),!0},Wu=(s,e,t,i,r)=>{var m;He=void 0;const o=on(e,i),a=n.resolveString(r.style.normalMapTextureImage,o),l=r.style.normalMapTextureLengthUnits===n.LengthUnits.Meters,c=t.styleManager.getStyle(i.attributes.styleId);if(!c)return!0;const d=(m=c.rasterSets.byKey[n.getStaticTextureRasterSetKey(a)])==null?void 0:m.rasters;if(!d)return!0;const u=n.resolveExpression(r.style.normalMapTextureSize,o);let[h,_]=Array.isArray(u)?u:[u,u];if(l&&(h=h*n.getPixelsPerMeter(h,h),_=_*n.getPixelsPerMeter(_,_)),h<=0||_<=0)return!0;const f=n.selectRaster(d,h*window.devicePixelRatio,!0);return f===void 0||(He=d[f]),!0},Ua=(s,e,{assetManager:t,renderer:i},r,o)=>{if(!Me)return i.bindShaderProgram(s,{u_int_is_textured:0}),!0;let a,l,c,d;const{tile:u}=r,{zoom:h}=e,_=t.textures[Me.atlasIndex];let f=!1;if(!_)return i.bindShaderProgram(s,{u_int_is_textured:0}),!0;o.type==="polygon"&&(f=o.style.lengthUnits===n.LengthUnits.Meters),i.enableTexture(_,0);let m;if(f){const v=on(e,r),g=n.resolveExpression(o.style.textureSize,v),[p,x]=Array.isArray(g)?g:[g,g],S=n.Mercator.toGeo(n.tileCoordsToMapPoint(u.coords)),b=n.Mercator.scaleFactor(S[1]),T=n.tileZoomToSize(u.zoomLevel)/n.MAP_POINTS_IN_METER/b,y=T/p,E=T/x,P=Math.trunc(n.atlasSize[0]/y),A=Math.trunc(n.atlasSize[1]/E);a=u.coords[0]*n.atlasSize[0]%P/P,l=u.coords[1]*n.atlasSize[1]%A/A,c=n.atlasSize[0]/P,d=n.atlasSize[1]/A}else m=n.tileSizeZpt*Math.pow(2,Math.round(h)-u.zoomLevel)*window.devicePixelRatio,a=u.coords[0]*m%Me.w/Me.w,l=u.coords[1]*m%Me.h/Me.h,c=m/Me.w,d=m/Me.h;return i.bindShaderProgram(s,{u_int_is_textured:1,u_float_texture_params:[a,l,c,d],u_float_sprite_texture_coords:[(Me.x+.5)/n.atlasSize[0],(Me.y+Me.h-1)/n.atlasSize[1],(Me.x+Me.w-1)/n.atlasSize[0],(Me.y+.5)/n.atlasSize[1]]}),!0},ju=(s,e,t,i,r)=>{var x;const{assetManager:o,styleManager:a,renderer:l}=t;if(!He)return l.bindShaderProgram(s,{u_int_is_normal_map_textured:0}),!0;let c,d,u,h;const{tile:_}=i,{zoom:f}=e,m=o.textures[He.atlasIndex],v=r.style.normalMapTextureLengthUnits===n.LengthUnits.Meters;if(!m)return l.bindShaderProgram(s,{u_int_is_normal_map_textured:0}),!0;l.enableTexture(m,1);let g;if(v){const S=on(e,i),b=n.resolveExpression(r.style.normalMapTextureSize,S),[T,y]=Array.isArray(b)?b:[b,b],E=n.Mercator.toGeo(n.tileCoordsToMapPoint(_.coords)),P=n.Mercator.scaleFactor(E[1]),A=n.tileZoomToSize(_.zoomLevel)/n.MAP_POINTS_IN_METER/P,F=A/T,L=A/y,D=Math.trunc(n.atlasSize[0]/F),B=Math.trunc(n.atlasSize[1]/L);c=_.coords[0]*n.atlasSize[0]%D/D,d=_.coords[1]*n.atlasSize[1]%B/B,u=n.atlasSize[0]/D,h=n.atlasSize[1]/B}else g=n.tileSizeZpt*Math.pow(2,Math.round(f)-_.zoomLevel)*window.devicePixelRatio,c=_.coords[0]*g%He.w/He.w,d=_.coords[1]*g%He.h/He.h,u=g/He.w,h=g/He.h;const p=(x=a.getStyle(i.attributes.styleId))==null?void 0:x.rasterSets.byIndex[He.rasterSetIndex];return!p||!p.isReady?(l.bindShaderProgram(s,{u_int_is_normal_map_textured:0}),!0):(l.bindShaderProgram(s,{u_int_is_normal_map_textured:1,u_vec4_normal_map_texture_params:[c,d,u,h],u_vec4_normal_map_sprite_texture_coords:[(He.x+.5)/n.atlasSize[0],(He.y+He.h-1)/n.atlasSize[1],(He.x+He.w-1)/n.atlasSize[0],(He.y+.5)/n.atlasSize[1]]}),!0)},ob=(s,e,{renderer:t})=>(t.bindShaderProgram(s,{u_int_is_textured:0,u_int_is_normal_map_textured:0}),!0),Xu=(s,e,{renderer:t},i,r)=>{if(!He)return!0;const o=on(e,i),a=n.resolveExpression(r.style.metallic,o),l=n.resolveExpression(r.style.roughness,o);return t.bindShaderProgram(s,{u_float_metallic:a,u_float_roughness:l}),!0},Ma=[0,0,0,0],ab=(s,e,{renderer:t},i)=>(n.tilePointToOffsetSize(Ma,n.createTileInfo(i.tile.coords)),Ma[3]=Number(e.globeMode),t.bindShaderProgram(s,{u_vec4_tilecoords:Ma}),!0),lb=(s,e,t,i)=>{if(!Me)return t.renderer.bindShaderProgram(s,{u_int_is_textured:0}),!0;const{tile:r}=i,{zoom:o}=e,a=t.assetManager.textures[Me.atlasIndex];if(!a)return t.renderer.bindShaderProgram(s,{u_int_is_textured:0}),!0;t.renderer.enableTexture(a,0);const l=n.tileSizeZpt*Math.pow(2,Math.round(o)-r.zoomLevel)*window.devicePixelRatio;return t.renderer.bindShaderProgram(s,{u_int_is_textured:1,u_float_texture_vertical_scale:Me.h*r.size/l}),!0},cb=(s,e,{styleManager:t,assetManager:i,renderer:r},o,a)=>{var v;const l=on(e,o),c=n.resolveString(a.style.iconImage,l),d=t.getStyle(o.attributes.styleId);if(!d)return!1;const u=(v=d.rasterSets.byKey[n.getStaticTextureRasterSetKey(c)])==null?void 0:v.rasters;if(!u)return!1;const h=n.resolveNumber(a.style.width,l),_=n.resolveNumber(a.style.height,l),f=n.selectMetricPointRaster(u,h,_,window.devicePixelRatio);if(!f)return!1;const m=i.textures[f.raster.atlasIndex];return m?(r.enableTexture(m,0),r.bindShaderProgram(s,{u_float_sprite_texture_coords:f.spriteCoords}),!0):!1},$u=new Float32Array(16);n.fromScaling($u,[1/n.worldSize,1/n.worldSize,1/n.worldSize]);const us=(s,e,{animationManager:t,assetManager:i,renderer:r},o,a)=>{var S;const{styleId:l}=o.attributes,{localMatrix:c,transformMatrix:d,modelId:u,textureTransformMatrix:h,useVat:_,vatFrameCount:f,vatTextureHeight:m,vatMin:v,vatMax:g}=o.renderingProperties;if(u===void 0)return!1;const p=i.getModel(u,l);if(p===void 0)return!1;t.animateGltfObject(o,a,p),t.animateGltfVat(o,a);const x={u_mat4_localmatrix:c,u_mat3_transform_tex_matrix:h,u_mat4_instance:e.globeMode?$u:d};return _&&f&&m&&(x.u_float_vat_frame=(S=o.renderingProperties.vatFrame)!=null?S:0,x.u_float_vat_texture_height=m,x.u_vec3_vat_min=v,x.u_vec3_vat_max=g),r.bindShaderProgram(s,x),!0},db=(s,e,{renderer:t},i)=>i.tile.renderModelMatrix?(n.copy(as,i.tile.renderModelMatrix),t.bindShaderProgram(s,{u_mat4_model:as}),!0):!1,qu=(s,e,{animationManager:t,renderer:i},r,o)=>{if(!He)return!0;let a=[0,0,0,0],l=0;const[c,d]=t.animatePolygonNormalMapTexture(r,o);return a=d,l=c?1:0,i.bindShaderProgram(s,{u_vec4_normal_map_animated_offsets:a,u_int_normal_map_is_animated:l}),!0},ub=(s,e,t)=>!t.shadowManager.texture;function hb(){return{line:{solid:[{programName:"road",vaoCreator:Dm,stateBinder:br,needsVisibilityBuffer:!1,commonBinder:Y(W,X,ae),programBinder:jp,objectBinder:R(Rd,be,Ke,le),layerBinder:_e,zoomBinder:ii,tileBinder:z(K,Te,Ni),cullMethod:O(G,Se,Pt,mt,te)},{identify:!0,programName:"roadIdentify",vaoCreator:wm,stateBinder:go,needsVisibilityBuffer:!1,objectBinder:R(Ke,le),zoomBinder:ii,tileBinder:z(Te,Ni),cullMethod:O(G,Se,Pt,mt,te)}],patterned:[{programName:"patternedLine",vaoCreator:Nm,stateBinder:qe,needsVisibilityBuffer:!1,commonBinder:Y(W,X,ae),programBinder:Pd,layerBinder:_e,objectBinder:R(Dd,Ke,ke,nn),zoomBinder:wd,tileBinder:z(K,H),cullMethod:O(G,Se,Pt,Kd)}],solid3d:[{programName:"line3D",vaoCreator:zm,stateBinder:vo,needsVisibilityBuffer:!1,commonBinder:Y(ne,W,X,ae),programBinder:Up,objectBinder:R(be,Ke,ft,w),layerBinder:_e,zoomBinder:ii,tileBinder:z(K,H,N),cullMethod:O(G,Pt,mt),is3dMapAware:!0},{identify:!0,programName:"line3DIdentify",vaoCreator:Bm,stateBinder:Fe,needsVisibilityBuffer:!1,programBinder:re,objectBinder:R(Ke,ft,w),zoomBinder:ii,tileBinder:z(H,N),cullMethod:O(G,Pt,mt),is3dMapAware:!0}],patterned3d:[{programName:"patternedLine3D",vaoCreator:km,stateBinder:vo,needsVisibilityBuffer:!1,commonBinder:Y(W,X,ae),programBinder:Xp,layerBinder:_e,objectBinder:R(Dd,Ke,ke,nn,w),zoomBinder:wd,tileBinder:z(K,H,N),cullMethod:O(G,Pt,Kd),is3dMapAware:!0}]},polygon:{fill:[{programName:"vtxColor",vaoCreator:Pm,stateBinder:br,needsVisibilityBuffer:!0,commonBinder:Y(W,X,ae),programBinder:Td,layerBinder:Ne(_e,Mt,xn),objectBinder:R(be,Ld,ke,ta,le,gi),tileBinder:z(ka,Ua,Wu,ju,Te,K,qu,Xu,ab),cullMethod:O(G,te,Se,mt)},{identify:!0,programName:"vtxColorIdentify",vaoCreator:Fm,stateBinder:go,needsVisibilityBuffer:!0,programBinder:ec,objectBinder:R(le,ux),tileBinder:Te,cullMethod:O(G,te,Se)}],fillWithMixFactor:[{programName:"vtxColor",vaoCreator:Am,stateBinder:fv,needsVisibilityBuffer:!0,commonBinder:Y(W,X,ae),programBinder:Td,layerBinder:Ne(_e,Mt,xn),objectBinder:R(be,Ld,ke,ta,le),tileBinder:z(ka,Ua,Wu,ju,Te,K,qu,Xu),cullMethod:O(G,te,Se,mt)}],stroke:[{programName:"simpleLine2d",vaoCreator:ev,stateBinder:br,needsVisibilityBuffer:!0,commonBinder:Y(W,X,ae),programBinder:Mp,layerBinder:Ne(ec,_r,_e),objectBinder:R(be,Ke,le,gi),tileBinder:z(K,Te),cullMethod:O($x,G,te,Se,zn,Bn,cu),subRenderIndex:1}],shadow:[{programName:"vtxColor",vaoCreator:Lm,stateBinder:qe,needsVisibilityBuffer:!0,commonBinder:Y(W,X),programBinder:Ct,layerBinder:Mt,objectBinder:R(be,ke,le),tileBinder:z(ub,ob,Te,K),cullMethod:O(G,te,Se,Kx)}]},metricPoint:{fill:[{programName:"metricPoint",vaoCreator:Rm,stateBinder:qe,needsVisibilityBuffer:!1,commonBinder:Y(W,ae,X),programBinder:rt,layerBinder:Ne(_e,Mt),objectBinder:R(be,le),tileBinder:z(cb,H,K),cullMethod:O(G,te,mt)}]},mesh:{fill:[{programName:"mesh",vaoCreator:dc,stateBinder:xo,needsVisibilityBuffer:!0,commonBinder:Y(W,X,ae),programBinder:It,layerBinder:Ne(_e,Ht),objectBinder:R(be,li,Ln,ke,lt,Wt,w,ft,ci,ta),tileBinder:z(ka,Ua,lb,K,H,N),cullMethod:O(G,au),subRenderIndex:1,is3dMapAware:!0},{identify:!0,programName:"mesh",vaoCreator:dc,stateBinder:Fe,needsVisibilityBuffer:!0,commonBinder:Y(W,X,ae),programBinder:It,objectBinder:R(lt,Wt,w,ft,ci),tileBinder:z(H,N),cullMethod:O(G,au),subRenderIndex:1,is3dMapAware:!0},{depthTest:!0,programName:"mesh",vaoCreator:Mm,stateBinder:Fe,needsVisibilityBuffer:!0,commonBinder:Y(W,X,ae),programBinder:It,objectBinder:R(lt,Wt,w,ft,ci),tileBinder:z(H,N),cullMethod:G,subRenderIndex:1,is3dMapAware:!0},{programName:"meshShadow",shadow:!0,vaoCreator:uc,stateBinder:En,needsVisibilityBuffer:!0,programBinder:re,objectBinder:R(lt,Wt,w,ft),tileBinder:z(H,N),cullMethod:G,is3dMapAware:!0}],inverse:[{programName:"inverse",vaoCreator:gr,stateBinder:Fc,needsVisibilityBuffer:!0,commonBinder:W,programBinder:It,objectBinder:R(lt,le,w,ci),tileBinder:z(H,N),cullMethod:O(G,te),subRenderIndex:-1,is3dMapAware:!0},{depthTest:!0,programName:"inverse",vaoCreator:gr,stateBinder:bv,needsVisibilityBuffer:!0,commonBinder:W,programBinder:It,objectBinder:R(lt,le,w,ci),tileBinder:z(H,N),cullMethod:O(G,te),subRenderIndex:-1,is3dMapAware:!0},{identify:!0,programName:"inverse",vaoCreator:gr,stateBinder:Fc,needsVisibilityBuffer:!0,commonBinder:W,programBinder:It,objectBinder:R(lt,le,w,ci),tileBinder:z(H,N),cullMethod:O(G,te),subRenderIndex:-1,is3dMapAware:!0},{programName:"meshShadow",shadow:!0,vaoCreator:gr,stateBinder:En,needsVisibilityBuffer:!0,programBinder:re,objectBinder:R(lt,le,w,ft),tileBinder:z(H,N),cullMethod:O(G,te),is3dMapAware:!0}],depthClear:[{programName:"meshDepthClear",vaoCreator:Hm,stateBinder:Sv,needsVisibilityBuffer:!0,commonBinder:Y(W,X,ae),programBinder:It,objectBinder:R(lt,Wt,w,ci,ft),tileBinder:z(H,N),cullMethod:G,subRenderIndex:-2,is3dMapAware:!0,forceRenderUnderCacheInDemMode:!0}],stroke:[{programName:"simpleLine3d",vaoCreator:Gm,stateBinder:Ri,needsVisibilityBuffer:!0,commonBinder:Y(ne,W,X,ae),programBinder:Br,layerBinder:Ne(_r,_e),objectBinder:R(be,Ke,lt,Wt,w,ft),tileBinder:z(K,H,N),cullMethod:O(G,zn,Hx,e0,cu),subRenderIndex:2,is3dMapAware:!0}]},polygonExtrusion:{sideFill:[{programName:"diffuse",vaoCreator:hc,stateBinder:Sr,needsVisibilityBuffer:!0,commonBinder:Y(W,X,ae),programBinder:Ki,tileBinder:z(K,H,N),layerBinder:Ne(_e,Ht),objectBinder:R(be,li,_t,ke,w,le,Dn,di,gi),cullMethod:O(tu,G,te,Kr,Se),is3dMapAware:!0},{programName:"gradientDiffuse",vaoCreator:hc,stateBinder:So,needsVisibilityBuffer:!0,commonBinder:Y(W,X,ae),programBinder:Ki,layerBinder:Ne(_e,Ht),objectBinder:R(be,Ln,li,_t,ke,w,le,Hd,Dn,di,gi),tileBinder:z(K,H,N),cullMethod:O(G,te,Se,Kr,ma),is3dMapAware:!0},{identify:!0,programName:"buildingIdentify",vaoCreator:fc(n.PolygonExtrusionGenerator.sinks.sideFill.stride),stateBinder:Fe,needsVisibilityBuffer:!0,commonBinder:ne,programBinder:zr,objectBinder:R(di,_t,w,le),tileBinder:z(H,N),cullMethod:O(G,te,Se,Kr,ma),is3dMapAware:!0},{depthTest:!0,programName:"buildingIdentify",vaoCreator:mc(n.PolygonExtrusionGenerator.sinks.sideFill.stride),stateBinder:Fe,needsVisibilityBuffer:!0,commonBinder:ne,programBinder:zr,objectBinder:R(di,_t,w,le),tileBinder:z(H,N),cullMethod:O(G,Yr,te,Se),is3dMapAware:!0},{programName:"buildingShadow",shadow:!0,vaoCreator:vc(n.PolygonExtrusionGenerator.sinks.sideFill.stride),stateBinder:yr,needsVisibilityBuffer:!0,programBinder:re,objectBinder:R(_t,w,le),tileBinder:z(H,N),cullMethod:O(G,Yr,te,Se),is3dMapAware:!0}],sideTexture:[{programName:"wallTexture",vaoCreator:Vm,stateBinder:wc,needsVisibilityBuffer:!0,commonBinder:Y(W,X,ae),programBinder:Ki,layerBinder:Ne(_e,Ht),objectBinder:R(_t,w,le,hx,li),tileBinder:z(K,H,N),cullMethod:O(G,te,Se,o0),is3dMapAware:!0}],topFill:[{programName:"diffuse",vaoCreator:_c,stateBinder:Sr,needsVisibilityBuffer:!0,commonBinder:Y(W,X,ae),programBinder:Ki,layerBinder:_e,objectBinder:R(be,li,_t,ke,w,le,Dn,di),tileBinder:z(K,H,N),cullMethod:O(tu,G,te,Se,va),is3dMapAware:!0},{programName:"diffuse",vaoCreator:_c,stateBinder:So,needsVisibilityBuffer:!0,commonBinder:Y(W,X,ae),programBinder:Ki,layerBinder:Ne(_e,Ht),objectBinder:R(be,li,_t,ke,w,le,Dn,di,gi),tileBinder:z(K,H,N),cullMethod:O(G,te,Se,va),is3dMapAware:!0},{identify:!0,programName:"buildingIdentify",vaoCreator:fc(n.PolygonExtrusionGenerator.sinks.topFill.stride),stateBinder:Fe,needsVisibilityBuffer:!0,commonBinder:ne,programBinder:zr,objectBinder:R(di,_t,w,le),tileBinder:z(H,N),cullMethod:O(G,te,Se,va),is3dMapAware:!0},{depthTest:!0,programName:"buildingIdentify",vaoCreator:mc(n.PolygonExtrusionGenerator.sinks.topFill.stride),stateBinder:Fe,needsVisibilityBuffer:!0,commonBinder:ne,programBinder:zr,objectBinder:R(di,_t,w,le),tileBinder:z(H,N),cullMethod:O(G,Yr,te,Se),is3dMapAware:!0},{programName:"buildingShadow",shadow:!0,vaoCreator:vc(n.PolygonExtrusionGenerator.sinks.topFill.stride),stateBinder:yr,needsVisibilityBuffer:!0,programBinder:re,objectBinder:R(_t,w,le),tileBinder:z(H,N),cullMethod:O(G,Yr,te,Se),is3dMapAware:!0}],sideStroke:[{programName:"line",vaoCreator:gc,stateBinder:Ri,needsVisibilityBuffer:!0,commonBinder:Y(W,ae,X,ne),programBinder:Ed,layerBinder:_e,objectBinder:R(be,Ln,li,_t,ke,w,le,gi),tileBinder:z(K,Te,N),cullMethod:O(G,te,Se,du,lu),is3dMapAware:!0}],topStroke:[{programName:"simpleLine3d",vaoCreator:uo,stateBinder:Ri,needsVisibilityBuffer:!0,commonBinder:Y(ne,W,X,ae),programBinder:Br,layerBinder:Ne(_e,ym),objectBinder:R(be,li,Ke,_t,w,le,oa,gi),tileBinder:z(K,H,N),cullMethod:O(G,te,Se,zn,Bn,i0),is3dMapAware:!0}]},labelLine:{raster:[{programName:"labelLine",vaoCreator:vr,stateBinder:Tn,needsVisibilityBuffer:!1,commonBinder:Y(W,X),programBinder:Di,objectBinder:R(Vt,mi,ti,Wr,Xr),tileBinder:z(H,K),zoomBinder:ii,cullMethod:O(te,ct,Xe,pi,rn,Qr),uniformSet:"fontHalo"},{programName:"labelLine",vaoCreator:vr,stateBinder:bo,needsVisibilityBuffer:!1,commonBinder:Y(W,X),programBinder:Di,objectBinder:R(Vt,mi,ti,Wr,Xr),tileBinder:z(H,K),zoomBinder:ii,cullMethod:O(te,ct,Qr,Xe,pi,rn),uniformSet:"fontHalo",isOverlappedObject:!0},{programName:"labelLine",vaoCreator:vr,stateBinder:Tn,needsVisibilityBuffer:!1,commonBinder:Y(W,X),programBinder:Di,objectBinder:R(Vt,mi,ti,Wr,Xr),zoomBinder:ii,tileBinder:z(H,K),cullMethod:O(te,ct,Xe,pi,rn),uniformSet:"fontFill",subRenderIndex:1},{programName:"labelLine",vaoCreator:vr,stateBinder:bo,needsVisibilityBuffer:!1,commonBinder:Y(W,X),programBinder:Di,objectBinder:R(Vt,mi,ti,Wr,Xr),zoomBinder:ii,tileBinder:z(H,K),cullMethod:O(te,ct,Xe,pi,rn),uniformSet:"fontFill",subRenderIndex:1,isOverlappedObject:!0}],billboard:[{programName:"labelLineBillboard",vaoCreator:co,stateBinder:fi,needsVisibilityBuffer:!1,commonBinder:Y(W,X,ne),programBinder:ve(Di,xn,bn,re,Sn),objectBinder:R(Vt,mi,ra,ti,Bd,w,vi),tileBinder:z(H,K,N),cullMethod:O(te,ct,Xe,pi,ua,rn,Qr),uniformSet:"fontHalo",is3dMapAware:!0},{programName:"labelLineBillboard",vaoCreator:co,stateBinder:fi,needsVisibilityBuffer:!1,commonBinder:Y(W,X,ne),programBinder:ve(Di,xn,bn,re,Sn),objectBinder:R(Vt,mi,ra,ti,Bd,w,vi),tileBinder:z(H,K,N),cullMethod:O(te,ct,Xe,pi,ua,rn),uniformSet:"fontFill",subRenderIndex:1,is3dMapAware:!0},{depthTest:!0,programName:"labelLineBillboard",vaoCreator:co,stateBinder:po,needsVisibilityBuffer:!1,commonBinder:Y(W,X,ne),programBinder:ve(Di,xn,bn,re,sc),objectBinder:R(ra,ti,w,vi),tileBinder:z(H,K,N),cullMethod:O(te,ct,Xe,ua),is3dMapAware:!0}]},dashedLine:{stroke:[{programName:"stripedLine",vaoCreator:ac,stateBinder:br,needsVisibilityBuffer:!1,commonBinder:Y(ae,W,X,ne),programBinder:Id,layerBinder:_e,objectBinder:R(wr,Or,ke,nn,le),zoomBinder:Zr,tileBinder:z(K,Te,Ni),cullMethod:O(G,Pt,Se,te)},{identify:!0,programName:"stripedLineIdentify",vaoCreator:ac,stateBinder:go,needsVisibilityBuffer:!1,commonBinder:ne,programBinder:Cd,objectBinder:R(wr,ke,Or,nn,le),zoomBinder:Zr,tileBinder:z(Te,Ni),cullMethod:O(G,Pt,Se,te)}],stroke3d:[{programName:"stripedLine3D",vaoCreator:lc,stateBinder:vo,needsVisibilityBuffer:!1,commonBinder:Y(ne,ae,W,X),programBinder:Vp,layerBinder:_e,objectBinder:R(wr,Or,ke,nn,w),zoomBinder:Zr,tileBinder:z(K,Te,Ni,N),cullMethod:O(G,Pt),is3dMapAware:!0},{identify:!0,programName:"stripedLine3DIdentify",vaoCreator:lc,stateBinder:Fe,needsVisibilityBuffer:!1,commonBinder:ne,programBinder:Zp,objectBinder:R(wr,ke,Or,nn,w),zoomBinder:Zr,tileBinder:z(Te,Ni,N),cullMethod:O(G,Pt),is3dMapAware:!0}]},oneWayLine:{raster:[{programName:"oneWayLine",vaoCreator:pc,stateBinder:Tn,needsVisibilityBuffer:!1,commonBinder:Y(pn,Li,ne),programBinder:$i,objectBinder:R(Vt,be,tn,Nr),tileBinder:z(H,K),cullMethod:O(ct,Xe,Jr)},{programName:"oneWayLine",vaoCreator:pc,stateBinder:bo,commonBinder:Y(pn,Li,ne),programBinder:$i,needsVisibilityBuffer:!1,objectBinder:R(Vt,be,tn,Nr),tileBinder:z(H,K),cullMethod:O(ct,Xe,Jr),isOverlappedObject:!0}],billboard:[{programName:"oneWayLineBillboard",vaoCreator:xc,stateBinder:fi,needsVisibilityBuffer:!1,commonBinder:Y(Li,X,W,ne),programBinder:ve(tc,bn,re,Sn),objectBinder:R(Vt,be,Yp,tn,Nr,w,vi),tileBinder:z(H,K,N),cullMethod:O(ct,Xe,Jr),is3dMapAware:!0},{depthTest:!0,programName:"oneWayLineBillboard",vaoCreator:xc,stateBinder:po,needsVisibilityBuffer:!1,commonBinder:Y(Li,W,ne),programBinder:ve(tc,bn,re,sc),objectBinder:R(tn,Nr,w,vi),tileBinder:z(H,K,N),cullMethod:O(ct,Xe,Jr),is3dMapAware:!0}]},point:{raster:[{programName:"pointSprite",vaoCreator:jm,stateBinder:fi,needsVisibilityBuffer:!1,commonBinder:yn(W,X,Yl,ur,ne),programBinder:wp,layerBinder:Mt,objectBinder:R(Jp,na,ia,Rn,Zt,w,le),cullMethod:O(Xe,te,fa,da,ct,zi),tileBinder:z(Te,K,N),is3dMapAware:!0,forcePrerenderUnderCacheInDemMode:!0},{identify:!0,programName:"pointSpriteIdentify",vaoCreator:$m,stateBinder:si,needsVisibilityBuffer:!1,commonBinder:ne,programBinder:Sd,objectBinder:R(na,ia,Rn,Zt,w,le),tileBinder:z(Te,N),cullMethod:O(Xe,te,fa,da,eu,zi),is3dMapAware:!0},{labelTest:!0,programName:"pointSpriteIdentify",vaoCreator:Xm,stateBinder:si,needsVisibilityBuffer:!1,commonBinder:ne,programBinder:Sd,objectBinder:R(na,ia,Rn,Zt,w,le),tileBinder:z(Te,N),cullMethod:O(Xe,te,fa,da,eu,zi),is3dMapAware:!0}],text:[{programName:"labelPoint",vaoCreator:cc,stateBinder:fi,needsVisibilityBuffer:!1,commonBinder:yn(W,X,ur,ne),programBinder:yd,objectBinder:R(Vt,mi,ti,Od,jr,Rn,Zt,w,le),tileBinder:z(Te,K,N),cullMethod:O(Xe,te,ct,pi,su,Qr,zi),uniformSet:"fontHalo",subRenderIndex:1,is3dMapAware:!0,forcePrerenderUnderCacheInDemMode:!0},{programName:"labelPoint",vaoCreator:cc,stateBinder:fi,needsVisibilityBuffer:!1,commonBinder:Y(W,X,ur,ne),programBinder:yd,objectBinder:R(Vt,mi,ti,Od,jr,Rn,Zt,w,le),tileBinder:z(Te,K,N),cullMethod:O(Xe,te,ct,pi,su,zi),uniformSet:"fontFill",subRenderIndex:2,is3dMapAware:!0,forcePrerenderUnderCacheInDemMode:!0},{identify:!0,programName:"labelPointIdentify",vaoCreator:Um,stateBinder:si,needsVisibilityBuffer:!1,commonBinder:ne,programBinder:ve(re),objectBinder:R(ti,jr,Zt,w,le),tileBinder:z(Te,N),cullMethod:O(Xe,te,Xx,zi),subRenderIndex:1,is3dMapAware:!0}],labelingTexture:[{depthTest:!0,programName:"pointDepthTest",vaoCreator:qm,stateBinder:po,needsVisibilityBuffer:!1,commonBinder:ne,programBinder:re,objectBinder:R(jr,Zt,w,le),tileBinder:z(H,N),cullMethod:O(Xe,te,zi),is3dMapAware:!0}]},buildingModel:{fill:[{programName:"zbmModel",vaoCreator:Ym,stateBinder:Dc,needsVisibilityBuffer:!1,commonBinder:Y(W,X,ae),programBinder:Wp,layerBinder:Ne(_e,Mt,Ht),objectBinder:R(be,sa,ix,w),tileBinder:z(K,H,N),cullMethod:O(_a,G,ou,mt,ga),subRenderIndex:2,is3dMapAware:!0},{programName:"zbmModelIdentify",vaoCreator:Qm,stateBinder:Fe,needsVisibilityBuffer:!1,commonBinder:ne,objectBinder:R(w),tileBinder:z(H,N),cullMethod:O(_a,G,ou,mt,ga),subRenderIndex:2,identify:!0,is3dMapAware:!0},{programName:"zbmModelIdentify",vaoCreator:Jm,stateBinder:Fe,needsVisibilityBuffer:!1,commonBinder:ne,objectBinder:R(w),tileBinder:z(H,N),cullMethod:G,depthTest:!0,is3dMapAware:!0},{programName:"zbmShadow",vaoCreator:Km,stateBinder:yr,needsVisibilityBuffer:!1,programBinder:re,objectBinder:R(sa,w),tileBinder:z(H,N),cullMethod:G,shadow:!0,is3dMapAware:!0}],stroke:[{programName:"simpleLine3d",vaoCreator:uo,stateBinder:Ri,needsVisibilityBuffer:!0,commonBinder:Y(ne,W,X,ae),programBinder:Br,layerBinder:Ne(_e,_r),objectBinder:R(be,Ke,sa,Wt,w,oa,$r),tileBinder:z(H,K,N),cullMethod:O(G,_a,zn,Bn,ga),subRenderIndex:5,is3dMapAware:!0}]},shiftedLine:{solid:[{programName:"road",commonBinder:Y(W,X,ae),programBinder:ve(Ct,rt),vaoCreator:Om,stateBinder:qe,needsVisibilityBuffer:!1,layerBinder:_e,objectBinder:R(be,Ke,Rd),tileBinder:z(K,Te,Ni),zoomBinder:ii,cullMethod:O(G,Pt,mt)}]},circle:{fill:[{programName:"circleMarker",vaoCreator:ho,stateBinder:qe,needsVisibilityBuffer:!1,commonBinder:Y(W,ae,X,ne),programBinder:ea,layerBinder:_e,objectBinder:R(be,Ke,w),cullMethod:O(G,Pt,mt),tileBinder:z(Te,K,N),subRenderIndex:2,is3dMapAware:!0},{programName:"circleMarker",vaoCreator:ho,stateBinder:qe,needsVisibilityBuffer:!1,commonBinder:Y(W,ae,X,ne),programBinder:ea,layerBinder:_e,objectBinder:R(be,Ke,w),cullMethod:O(G,qx,Bn),tileBinder:z(Te,K,N),subRenderIndex:1,is3dMapAware:!0},{programName:"circleMarker",vaoCreator:ho,stateBinder:qe,needsVisibilityBuffer:!1,commonBinder:Y(W,ae,X,ne),programBinder:ea,layerBinder:_e,objectBinder:R(be,Ke,w),cullMethod:O(G,Yx,t0),tileBinder:z(Te,K,N),is3dMapAware:!0},{identify:!0,programName:"circleMarkerIdentify",vaoCreator:tv,stateBinder:si,programBinder:re,needsVisibilityBuffer:!1,commonBinder:ne,objectBinder:R(Ke,w),cullMethod:O(G,Qx),tileBinder:z(Te,N),is3dMapAware:!0}]},arrow:{stroke:[{programName:"entrance",vaoCreator:bc,stateBinder:qe,needsVisibilityBuffer:!1,commonBinder:Y(pn,Li,W,X,ne),programBinder:Hp,objectBinder:R(be,tn,Qp,zd,ke),tileBinder:z(H,K),cullMethod:O(G,mt)},{identify:!0,programName:"entranceIdentify",vaoCreator:bc,stateBinder:si,needsVisibilityBuffer:!1,commonBinder:Y(pn,Li,ne),programBinder:Np,objectBinder:R(tn,zd,ke),tileBinder:H,cullMethod:O(G,mt)}]},lineExtrusion:{fill:[{programName:"gradientDiffuse",vaoCreator:Zm,stateBinder:Pc,needsVisibilityBuffer:!0,commonBinder:Y(W,X,ae),programBinder:Ki,layerBinder:Ne(_e,Ht),objectBinder:R(Vr,be,li,Ln,ke,w,Wt,Hd,Dn,di,$r),tileBinder:z(K,H,N),cullMethod:O(G,te,Se,Kr,ma),subRenderIndex:9,is3dMapAware:!0},{programName:"buildingShadow",shadow:!0,vaoCreator:Wm,stateBinder:En,needsVisibilityBuffer:!0,programBinder:re,objectBinder:R(Vr,w,Wt),tileBinder:z(H,N),cullMethod:O(G,te,Se),is3dMapAware:!0}],sideStroke:[{programName:"line",vaoCreator:gc,stateBinder:Ri,needsVisibilityBuffer:!0,commonBinder:Y(W,ae,X,ne),programBinder:Ed,layerBinder:_e,objectBinder:R(Vr,be,Ln,ke,w,Wt,$r),tileBinder:z(K,Te,N),cullMethod:O(G,te,Se,du,lu),subRenderIndex:10,is3dMapAware:!0}],topStroke:[{programName:"simpleLine3d",vaoCreator:uo,stateBinder:Ri,needsVisibilityBuffer:!0,commonBinder:Y(ne,W,X,ae),programBinder:Br,layerBinder:Ne(_e,_r),objectBinder:R(Vr,be,Ke,w,Wt,oa,$r),tileBinder:z(K,H,N),cullMethod:O(G,te,Se,zn,Bn),subRenderIndex:11,is3dMapAware:!0}]},gltfModel:{instances:[{programName:"gltfModel",vaoCreator:xr(!1),instanceBinder:os,commonBinder:Y(W,X,ae),programBinder:Gp,layerBinder:Ne(_e,Ht,fr),stateBinder:Dc,needsVisibilityBuffer:!1,objectBinder:R(be,nx,Ur,la,kr,w,Mr,Zt,le,Hr,gi,Gr),tileBinder:z(Te,us,db,N,ds),cullMethod:O(pa,_u,qr),is3dMapAware:!0},{identify:!0,programName:"gltfModelIdentify",instanceBinder:os,vaoCreator:xr(!1),stateBinder:Fe,needsVisibilityBuffer:!1,layerBinder:fr,commonBinder:yn(W,X),programBinder:re,objectBinder:R(w,Mr,Zt,Fn,kr,Ur,le,Hr,Gr,Md),tileBinder:z(Te,us,N,ds),cullMethod:O(pa,_u,qr),is3dMapAware:!0},{depthTest:!0,programName:"gltfModelIdentify",instanceBinder:os,vaoCreator:xr(!0),stateBinder:Fe,needsVisibilityBuffer:!1,commonBinder:yn(W,X),programBinder:re,layerBinder:fr,objectBinder:R(w,Mr,Zt,kr,Ur,le,Hr,Gr,Fn,Md),tileBinder:z(Te,us,N,ds),cullMethod:O(pa,qr),is3dMapAware:!0},{shadow:!0,programName:"gltfModelShadow",instanceBinder:os,vaoCreator:xr(!1),stateBinder:yr,needsVisibilityBuffer:!1,programBinder:re,layerBinder:fr,objectBinder:R(w,Mr,Zt,kr,Ur,le,Hr,Gr),tileBinder:z(Te,us,N,ds),cullMethod:O(s0,qr),is3dMapAware:!0}]},raster:{fill:[{programName:"rectWithTexture",vaoCreator:iv,stateBinder:qe,needsVisibilityBuffer:!1,commonBinder:yn(W,X),layerBinder:Mt,objectBinder:R(Fd,Kp),tileBinder:z(H,K),cullMethod:O(jd,G)}]},heatmap:{framebuffer:[{programName:"heatmap",vaoCreator:nv,stateBinder:zc,needsVisibilityBuffer:!1,commonBinder:Kl,objectBinder:R(rx,sx),zoomBinder:ii,tileBinder:z(H,K),cullMethod:O(G,Jx)}],fill:[{programName:"heatmapTexture",vaoCreator:rv,stateBinder:qe,needsVisibilityBuffer:!1,layerBinder:Mt,objectBinder:R(Fd,tx,ex),tileBinder:K,cullMethod:O(G,jd,Gx),subRenderIndex:1}]},dem:{mesh:[{programName:"demMesh",vaoCreator:pr,commonBinder:Y(W,X,ae),programBinder:It,layerBinder:_e,stateBinder:Fe,needsVisibilityBuffer:!1,objectBinder:R(w,Nd,Ud),tileBinder:z(H,K,cs,N),cullMethod:O(Xd,$d),is3dMapAware:!0},{programName:"demGround",demGround:!0,vaoCreator:pr,programBinder:re,tileBinder:z(H,K,N),stateBinder:Fe,needsVisibilityBuffer:!1,objectBinder:R(w)},{identify:!0,programName:"demMesh",vaoCreator:pr,programBinder:ve(re,xd),stateBinder:Fe,needsVisibilityBuffer:!1,objectBinder:R(kd,w),tileBinder:z(H,cs,N),cullMethod:qd,is3dMapAware:!0}],mesh2:[{dem:!0,programName:"demElevation",vaoCreator:qi,stateBinder:vv,needsVisibilityBuffer:!1,tileBinder:H,objectBinder:R()},{programName:"demGround2",demGround:!0,vaoCreator:qi,programBinder:re,tileBinder:z(H,K,N),stateBinder:Fe,needsVisibilityBuffer:!1,objectBinder:R(w)},{programName:"demMesh2",vaoCreator:qi,commonBinder:Y(W,X,ae),programBinder:It,layerBinder:_e,stateBinder:Fe,needsVisibilityBuffer:!1,objectBinder:R(ci,Nd,Ud,ax,w),tileBinder:z(H,K,cs,N),cullMethod:O(Xd,$d)},{identify:!0,programName:"demMesh2",vaoCreator:qi,programBinder:ve(re,xd),stateBinder:Fe,needsVisibilityBuffer:!1,objectBinder:R(ci,kd,w),tileBinder:z(H,cs,N),cullMethod:qd},{depthTest:!0,programName:"demMesh2DepthTest",vaoCreator:qi,programBinder:ve(re),stateBinder:Fe,needsVisibilityBuffer:!1,objectBinder:R(cx,w),tileBinder:z(H,N)},{shadow:!0,programName:"demMesh2Shadow",vaoCreator:qi,programBinder:re,stateBinder:En,needsVisibilityBuffer:!1,objectBinder:R(w),tileBinder:z(H,N)}],hillshade:[{programName:"demHillshade",vaoCreator:_o,stateBinder:si,needsVisibilityBuffer:!1,programBinder:re,objectBinder:R(w),tileBinder:z(H,N)}],flatBottom:[{programName:"demFlatBottom",vaoCreator:sv,stateBinder:Ac,needsVisibilityBuffer:!1,objectBinder:R(lx,w),tileBinder:z(H,N),cullMethod:Vx}]},mapMesh:{fill:[{programName:"mapMesh",vaoCreator:fo,stateBinder:xo,needsVisibilityBuffer:!1,zoomBinder:R(aa),commonBinder:Y(W,X,ae),programBinder:It,layerBinder:Ne(_e,Ht),objectBinder:R(la,lt,w,ft,Fn,vi),tileBinder:z(K,H,N),cullMethod:O(G,ha),subRenderIndex:Number.MAX_SAFE_INTEGER,is3dMapAware:!0},{identify:!0,programName:"mapMesh",vaoCreator:fo,stateBinder:Fe,needsVisibilityBuffer:!1,zoomBinder:R(aa),commonBinder:Y(W,X,ae),programBinder:It,layerBinder:Ne(_e,Ht),objectBinder:R(la,lt,w,ft,Fn,vi),tileBinder:z(H,N),cullMethod:O(G,ha),subRenderIndex:Number.MAX_SAFE_INTEGER,is3dMapAware:!0},{depthTest:!0,programName:"mapMesh",vaoCreator:fo,stateBinder:Fe,needsVisibilityBuffer:!1,zoomBinder:R(aa),commonBinder:Y(W,X,ae),programBinder:It,layerBinder:Ne(_e,Ht),objectBinder:R(lt,w,ft,Fn,vi),tileBinder:z(H,N),cullMethod:G,subRenderIndex:Number.MAX_SAFE_INTEGER,is3dMapAware:!0},{programName:"meshShadow",shadow:!0,vaoCreator:uc,stateBinder:En,needsVisibilityBuffer:!1,programBinder:re,objectBinder:R(lt,w,ft),tileBinder:z(H,N),cullMethod:G,is3dMapAware:!0}]}}}class _b{constructor(e){this.gl=e,this.ext1=e.getExtension("EXT_disjoint_timer_query"),this.ext2=e instanceof WebGL2RenderingContext?e.getExtension("EXT_disjoint_timer_query_webgl2"):null,this.queries=[]}addTimer(){if(this.ext2&&this.gl instanceof WebGL2RenderingContext){const e=this.gl.createQuery();return e?(this.queries.push({query:e}),this.gl.beginQuery(this.ext2.TIME_ELAPSED_EXT,e),!0):!1}if(this.ext1){const e=this.ext1.createQueryEXT();return this.queries.push({query:e}),this.ext1.beginQueryEXT(this.ext1.TIME_ELAPSED_EXT,e),!0}return!1}stopTimer(){if(this.queries.length){if(this.ext2&&this.gl instanceof WebGL2RenderingContext){this.gl.endQuery(this.ext2.TIME_ELAPSED_EXT);return}this.ext1&&this.ext1.endQueryEXT(this.ext1.TIME_ELAPSED_EXT)}}tryToGetFirstTimerValue(){const e=this.queries[0];if(e){if(this.ext2&&this.gl instanceof WebGL2RenderingContext){const t=this.gl;if(t.getParameter(this.ext2.GPU_DISJOINT_EXT)){this.flushAll();return}if(!t.getQueryParameter(e.query,t.QUERY_RESULT_AVAILABLE))return;const o=t.getQueryParameter(e.query,t.QUERY_RESULT);return t.deleteQuery(e.query),this.queries.shift(),{durationMs:Number(o)/1e6}}if(this.ext1){const t=this.ext1;if(this.gl.getParameter(t.GPU_DISJOINT_EXT)){this.flushAll();return}if(!t.getQueryObjectEXT(e.query,t.QUERY_RESULT_AVAILABLE_EXT))return;const o=t.getQueryObjectEXT(e.query,t.QUERY_RESULT_EXT);return t.deleteQueryEXT(e.query),this.queries.shift(),{durationMs:Number(o)/1e6}}}}destroy(){this.flushAll()}flushAll(){if(this.ext2&&this.gl instanceof WebGL2RenderingContext)for(const e of this.queries)this.gl.deleteQuery(e.query);else if(this.ext1)for(const e of this.queries)this.ext1.deleteQueryEXT(e.query);this.queries.length=0}}const fb=`
float affine_step(const float edge0, const float edge1, const float x)
{
    return clamp((x - edge0) / (edge1 - edge0), 0., 1.);
}
`,mb=`#define ALPHA_MODE_OPAQUE 1
#define ALPHA_MODE_BLEND 2
`,vb=`uniform vec4 u_vec4_color_effect_mix_rgba;
uniform float u_float_color_effect_mix_factor;
vec4 apply_color_effect(vec4 color) {
    return mix(color, u_vec4_color_effect_mix_rgba, clamp(u_float_color_effect_mix_factor, 0.0, 1.0));
}
`,Yu=`
vec4 apply_opacity(const vec4 color, const float opacity)
{
return color * opacity;
}
`,gb=`struct ArrowDistanceParameters
{
    vec2 wing_normal;
    vec2 tip_normal;
    vec2 mirrored_wing_normal;
    vec2 mirrored_tip_normal;
    float width;
    float full_length;
    float arrow_height;
    float tip_radius;
    vec2 tip_circle_center;
    float wing_radius;
    vec2 wing_circle_center;
    float border_width;
};
ArrowDistanceParameters calculate_arrow_distance_parameters(
    const vec2 wing_normal,
    const vec2 tip_normal,
    const float width_zpt,
    const float length_zpt,
    const float tip_height_multiplier,
    const float wing_height_multiplier,
    const float tip_radius_zpt,
    const float wing_radius_zpt,
    const float border_width_zpt,
    const vec2 tip_circle_center,
    const vec2 wing_circle_center)
{
    vec2 mirrored_wing_normal = vec2(wing_normal.x, -wing_normal.y);
    vec2 mirrored_tip_normal = vec2(tip_normal.x, -tip_normal.y);
    float width = 0.5 * width_zpt;
    float length = 0.5 * length_zpt;
    float arrow_height = width_zpt * (tip_height_multiplier - wing_height_multiplier);
    return ArrowDistanceParameters(
        wing_normal,
        tip_normal,
        mirrored_wing_normal,
        mirrored_tip_normal,
        width,
        length,
        arrow_height,
        tip_radius_zpt,
        tip_circle_center,
        wing_radius_zpt,
        wing_circle_center,
        border_width_zpt);
}
struct ArrowDistances
{
    float top_tip_cut;
    float bottom_tip_cut;
    float line;
    float bottom_left_wing;
    float bottom_right_wing;
    float top_left_wing;
    float top_right_wing;
    float tip_circle;
    float tip_circle_cut;
    float left_wing_circle;
    float left_wing_circle_cut;
    float right_wing_circle;
    float right_wing_circle_cut;
};
ArrowDistances calculate_arrow_distances(
    const ArrowDistanceParameters arrow_parameters,
    const vec2 texcoord,
    const float offset,
    const mat2 derivatives)
{
    float derivatives_x_multiplier = 1. / max(abs(derivatives[0].x), abs(derivatives[1].x));
    float dt = ( texcoord.x - arrow_parameters.full_length - offset) * derivatives_x_multiplier;
    float d0 = (-texcoord.x - arrow_parameters.full_length - offset) * derivatives_x_multiplier;
    float d1 = (abs(texcoord.y) - arrow_parameters.width - offset) / max(abs(derivatives[0].y), abs(derivatives[1].y));
    float d2 = (dot(texcoord - vec2(arrow_parameters.full_length - arrow_parameters.arrow_height, 0.), arrow_parameters.wing_normal) - offset) / max(abs(dot(derivatives[0], arrow_parameters.wing_normal)), abs(dot(derivatives[1], arrow_parameters.wing_normal)));
    float d3 = (dot(texcoord - vec2(arrow_parameters.full_length - arrow_parameters.arrow_height, 0.), arrow_parameters.mirrored_wing_normal) - offset) / max(abs(dot(derivatives[0], arrow_parameters.mirrored_wing_normal)), abs(dot(derivatives[1], arrow_parameters.mirrored_wing_normal)));
    float d4 = (dot(texcoord - vec2(arrow_parameters.full_length, 0.), arrow_parameters.tip_normal) - offset) / max(abs(dot(derivatives[0], arrow_parameters.tip_normal)), abs(dot(derivatives[1], arrow_parameters.tip_normal)));
    float d5 = (dot(texcoord - vec2(arrow_parameters.full_length, 0.), arrow_parameters.mirrored_tip_normal) - offset) / max(abs(dot(derivatives[0], arrow_parameters.mirrored_tip_normal)), abs(dot(derivatives[1], arrow_parameters.mirrored_tip_normal)));
    
    float tip_circle_cut = sdf_half_planes_cut(
        texcoord,
        arrow_parameters.tip_normal,
        -arrow_parameters.mirrored_tip_normal,
        arrow_parameters.tip_circle_center,
        derivatives);
    float tip_circle = sdf_circle(
        texcoord - arrow_parameters.tip_circle_center,
        arrow_parameters.tip_radius + offset - arrow_parameters.border_width);
    vec2 tip_circle_normal = normalize(texcoord - arrow_parameters.tip_circle_center);
    tip_circle = tip_circle / max(abs(dot(derivatives[0], tip_circle_normal)), abs(dot(derivatives[1], tip_circle_normal)));
    
    vec2 right_wing_circle_center = vec2(arrow_parameters.wing_circle_center.x, -arrow_parameters.wing_circle_center.y);
    vec2 left_wing_circle_normal = normalize(texcoord - arrow_parameters.wing_circle_center);
    vec2 right_wing_circle_normal = normalize(texcoord - right_wing_circle_center);
    float left_wing_circle = sdf_circle(texcoord - arrow_parameters.wing_circle_center,
        arrow_parameters.wing_radius + offset - arrow_parameters.border_width);
        left_wing_circle = left_wing_circle / max(abs(dot(derivatives[0], left_wing_circle_normal)), abs(dot(derivatives[1], left_wing_circle_normal)));
    float right_wing_circle = sdf_circle(texcoord - right_wing_circle_center,
        arrow_parameters.wing_radius + offset - arrow_parameters.border_width);
        right_wing_circle = right_wing_circle / max(abs(dot(derivatives[0], right_wing_circle_normal)), abs(dot(derivatives[1], right_wing_circle_normal)));
    float left_wing_circle_cut = sdf_half_planes_cut(
        texcoord,
        -arrow_parameters.tip_normal,
        arrow_parameters.wing_normal,
        arrow_parameters.wing_circle_center,
        derivatives);
    float right_wing_circle_cut = sdf_half_planes_cut(
        texcoord,
        arrow_parameters.mirrored_tip_normal,
        -arrow_parameters.mirrored_wing_normal,
        right_wing_circle_center,
        derivatives);
    return ArrowDistances(
        dt,
        d0,
        d1,
        d2,
        d3,
        d4,
        d5,
        tip_circle,
        tip_circle_cut,
        left_wing_circle,
        left_wing_circle_cut,
        right_wing_circle,
        right_wing_circle_cut);
}
`,pb=`
#ifdef WEBGL2
#define UNPACK_BOOL1(packedValue) ((packedValue & 0x1) != 0)
#define UNPACK_BOOL2(packedValue) ((packedValue & 0x2) != 0)
#define UNPACK_BOOL3(packedValue) ((packedValue & 0x4) != 0)
#else
#define UNPACK_BOOL1(packedValue) (int(mod(float(packedValue), 2.0)) == 1)
#define UNPACK_BOOL2(packedValue) (int(mod(float(packedValue) / 2.0, 2.0)) == 1)
#define UNPACK_BOOL3(packedValue) (int(mod(float(packedValue) / 4.0, 2.0)) == 1)
#endif
`,Qu=`#ifndef UBO
uniform highp vec3 u_cam_pos;
#endif
`,xb=`
const float g_distance_precision_limit = 1e-4;
struct CircleDistance
{
    float distance;
    float width;
};
CircleDistance circle_color_distance(
    const mat2 derivatives,
    const vec2 circle,
    const float circle_width)
{
    float circle_length = length(circle);
    float distance = circle_length - circle_width;
    
    
    
    vec2 circle_dx = derivatives[0];
    vec2 circle_dy = derivatives[1];
    
    float distance_dx = dot(circle, circle_dx);
    float distance_dy = dot(circle, circle_dy);
    
    float derivative_denominator = circle_length;
    float width = max(abs(distance_dx), abs(distance_dy));
    return CircleDistance(
        distance * derivative_denominator,
        width);
}
vec4 distance_to_color(
    const float fill_distance,
    const float border_distance,
    const vec4 fill_color,
    const vec4 border_color)
{
    float fill_factor = affine_step(-1., 0., fill_distance);
    float border_factor = affine_step(0., 1., border_distance);
    return
        mix(mix(fill_color, border_color, fill_factor), vec4(.0), border_factor);
}
vec4 distance_to_color(
    const CircleDistance circle_distance,
    const vec4 fill_color)
{
    
    
    float fill_factor = circle_distance.distance < g_distance_precision_limit
        ? 0.
        : affine_step(0., circle_distance.width, circle_distance.distance);
    return mix(fill_color, vec4(0.), fill_factor);
}
`,bb=`
#ifndef VARYINGS_LIMIT_9
    varying vec2 v_vec2_dem_tex_pos;
    varying float v_float_dem_invalid;
#endif
int check_dem_invalid() {
    #ifndef VARYINGS_LIMIT_9
    if (v_float_dem_invalid != 0. || v_vec2_dem_tex_pos.x < 0. || v_vec2_dem_tex_pos.x > 1. || v_vec2_dem_tex_pos.y < 0. || v_vec2_dem_tex_pos.y > 1.) {
        return 1;
    }
    #endif
    return 0;
}
`,Sb=`#ifdef WEBGL1
#extension GL_OES_standard_derivatives: enable
#endif
`,yb=`
#define LINEAR 0
#define EXP 1
#define FOG_EQUATION (LINEAR)
#define EPSILON (0.0001)
#ifndef UBO
# ifdef FOG
uniform vec4 u_fog_color;
uniform vec4 u_fog_color2;
uniform vec2 u_fog_gradient;
uniform vec2 u_fog_limits;
uniform float u_fog_horizon_blend;
uniform float u_fog_horizon_level;
# endif
#endif 
#if defined(FOG) || defined(SKY)
# ifndef UBO
uniform vec4 u_sky_color;
uniform float u_fog_horizon_pad;
# endif
varying vec3 v_fog_pos;
#endif
#ifdef FOG
float fog_gradient_shaped(float t, float mid) {
    if (t < mid) {
        return 0.5 * t / max(mid, EPSILON);
    }
    return 0.5 + 0.5 * (t - mid) / max(1.0 - mid, EPSILON);
}
float fog_gradient_factor(vec3 dir, vec2 gradient) {
    float t = clamp(dir.z - u_fog_horizon_level, 0.0, 1.0);
    return fog_gradient_shaped(t, gradient.x) * gradient.y;
}
#endif
#ifdef FOG
float fog_horizon_blending(vec3 camera_dir, float blend) {
    blend = EPSILON + blend;
    float t = max(camera_dir.z / blend, 0.0);
    
    return exp(-3.0 * t * t);
}
float fog_exponential(float t) {
    const float decay = 6.0;
    float falloff = 1.0 - min(1.0, exp(-decay * t));
    
    falloff *= falloff * falloff;
    
    return min(1.0, 1.00747 * falloff);
}
float fog_depth(float depth) {
    float start = u_fog_limits.x;
    float end = u_fog_limits.y;
    float range = end - start;
    float fac = (depth - start) / range;
#if (FOG_EQUATION == LINEAR)
    
    fac = clamp(fac, 0.0, 1.0);
#elif (FOG_EQUATION == EXP)
    fac = fog_exponential(fac);
#endif
    return fac;
}
float calc_depth_fog() {
    float depth = length(v_fog_pos);
    float fac = fog_depth(depth);
    return fac;
}
vec3 calc_fog_color() {
    float depth = length(v_fog_pos);
    vec3 dir = v_fog_pos / depth;
    
    dir.z -= u_fog_horizon_level;
    float fog_blend = fog_horizon_blending(dir, u_fog_horizon_blend);
    if (u_sky_color.a <= 0.01) {
        return mix(
            u_fog_color.rgb / u_fog_color.a,
            u_fog_color2.rgb / max(u_fog_color2.a, EPSILON),
            fog_gradient_factor(dir, u_fog_gradient)
        );
    } else {
        
        return mix(
            u_sky_color.rgb / u_sky_color.a,
            mix(
                u_fog_color.rgb / u_fog_color.a,
                u_fog_color2.rgb / max(u_fog_color2.a, EPSILON),
                fog_gradient_factor(dir, u_fog_gradient)
            ),
            min(fog_blend + (1.0 - u_sky_color.a), 1.0)
        );
    }
}
#endif 
vec4 apply_fog(vec4 color) {
#ifdef FOG
    if (u_fog_color.a <= 0.01) {
        return color;
    }
    float alpha = EPSILON + color.a;
    float fac = calc_depth_fog();
    vec3 fog_color = calc_fog_color();
    color.rgb /= alpha;
    color.rgb = mix(color.rgb, fog_color, fac * u_fog_color.a);
    color.rgb *= alpha;
#endif
    return color;
}
vec4 apply_fog_alpha(vec4 color) {
#ifdef FOG
    if (u_fog_color.a <= 0.01) {
        return color;
    }
    color *= 1.0 - calc_depth_fog();
#endif
    return color;
}
vec4 apply_fog_sky(vec4 color) {
#ifdef FOG
    float alpha = EPSILON + color.a;
    float depth = length(v_fog_pos);
    vec3 dir = v_fog_pos / depth;
    
    dir.z -= u_fog_horizon_level;
    float fac = fog_horizon_blending(dir, u_fog_horizon_blend);
    
    
    
    
    
    vec3 fog_color_rgb = mix(
        u_fog_color.rgb,
        u_fog_color2.rgb,
        fog_gradient_factor(dir, u_fog_gradient)
    );
    color.rgb /= alpha;
    color.rgb = mix(color.rgb, fog_color_rgb, fac * u_fog_color.a);
    color.rgb *= alpha;
#endif
    return color;
}`,Tb=`#define FRAGMENT_NORMAL
vec3 calc_fragment_normal(vec3 vertex) {
    vec3 dx = dFdx(vertex);
    vec3 dy = dFdy(vertex);
    return normalize(cross(dx, dy));
}`,Eb=`precision highp float;
`,Cb=`#ifdef UBO
uniform LightSettings
{
    vec3 u_vec3_light_dir1_direction;
    vec4 u_vec4_light_dir1_color;
    vec3 u_vec3_light_dir2_direction;
    vec4 u_vec4_light_dir2_color;
    vec4 u_vec4_ambient_color;
};
#else
uniform vec3 u_vec3_light_dir1_direction;
uniform vec4 u_vec4_light_dir1_color;
uniform vec3 u_vec3_light_dir2_direction;
uniform vec4 u_vec4_light_dir2_color;
uniform vec4 u_vec4_ambient_color;
#endif
uniform int u_int_light_flags;
vec4 light_factor(vec3 normal) {
    bool use_light = UNPACK_BOOL1(u_int_light_flags);
    if (!use_light) { 
        return vec4(1.);
    }
    float light_1_factor = max(dot(normal, -u_vec3_light_dir1_direction), 0.0);
    float light_2_factor = max(dot(normal, -u_vec3_light_dir2_direction), 0.0);
    if (UNPACK_BOOL2(u_int_light_flags)) {
        light_1_factor *= compute_shadow_factor();
    } else if (UNPACK_BOOL3(u_int_light_flags)) {
        light_2_factor *= compute_shadow_factor();
    }
    vec3 direct_light_contrib = u_vec4_light_dir1_color[3] * light_1_factor * u_vec4_light_dir1_color.rgb;
    vec3 shading_light_contrib = u_vec4_light_dir2_color[3] * light_2_factor * u_vec4_light_dir2_color.rgb;
    return vec4(u_vec4_ambient_color[3] * u_vec4_ambient_color.rgb + direct_light_contrib + shading_light_contrib, 1.0);
}
float light_factor_dem(vec3 normal) {
    bool use_light = UNPACK_BOOL1(u_int_light_flags);
    if (!use_light) { 
        return 1.;
    }
    float light_1_factor = dot(normal, -u_vec3_light_dir1_direction);
    
    
    
    
    return light_1_factor;
}
vec4 light_factor(vec3 normal, vec3 pos_world) {
    
    if (dot(u_cam_pos - pos_world, normal) < 0.) {
        normal *= vec3(-1.);
    }
    return light_factor(normal);
}
vec4 light_factor_surface() {
    bool use_light = UNPACK_BOOL1(u_int_light_flags);
    if (!use_light) {
        return vec4(1.);
    }
    vec3 normal = vec3(0., 0., 1.);
    float light_1_factor = max(dot(normal, -u_vec3_light_dir1_direction), 0.0);
    float light_2_factor = max(dot(normal, -u_vec3_light_dir2_direction), 0.0);
    if (UNPACK_BOOL2(u_int_light_flags)) {
        light_1_factor *= compute_shadow_factor();
    } else if (UNPACK_BOOL3(u_int_light_flags)) {
        light_2_factor *= compute_shadow_factor();
    }
     return vec4(u_vec4_ambient_color[3] * u_vec4_ambient_color.rgb
         + u_vec4_light_dir1_color[3] * light_1_factor * u_vec4_light_dir1_color.rgb
         + u_vec4_light_dir2_color[3] * light_2_factor * u_vec4_light_dir2_color.rgb, 1.0);
}
vec4 light_factor_dem2(vec3 normal) {
    float light_1_factor = max(dot(normal, -u_vec3_light_dir1_direction), 0.0);
    float light_2_factor = max(dot(normal, -u_vec3_light_dir2_direction), 0.0);
    if (UNPACK_BOOL2(u_int_light_flags)) {
        light_1_factor *= compute_shadow_factor();
    } else if (UNPACK_BOOL3(u_int_light_flags)) {
        light_2_factor *= compute_shadow_factor();
    }
    vec3 direct_light_contrib = u_vec4_light_dir1_color[3] * light_1_factor * u_vec4_light_dir1_color.rgb;
    vec3 shading_light_contrib = u_vec4_light_dir2_color[3] * light_2_factor * u_vec4_light_dir2_color.rgb;
    return vec4(u_vec4_ambient_color[3] * u_vec4_ambient_color.rgb + direct_light_contrib + shading_light_contrib, 1.0);
}
`,Ib=`
#define LIGHT_MODEL_PBR 2
#ifdef LIGHT_MODEL
#if LIGHT_MODEL == LIGHT_MODEL_PBR
    const float PI = 3.14159265359;
    
    float D(float alpha, vec3 N, vec3 H) {
        float numerator = alpha * alpha;
        float NdotH = max(dot(N, H), 0.);
        float denominator = PI * pow(
            NdotH * NdotH * (alpha * alpha - 1.) + 1.,
            2.
        );
        return numerator / max(denominator, 0.000001);
    }
    
    float G1(float alpha, vec3 N, vec3 X) {
        float numerator = max(dot(N, X), 0.);
        float k = alpha / 2.;
        float denominator = max(dot(N, X), 0.) * (1. - k) + k;
        return numerator / max(denominator, 0.000001);
    }
    
    float G(float alpha, vec3 N, vec3 V, vec3 L) {
        return G1(alpha, N, V) * G1(alpha, N, L);
    }
    
    vec3 F(vec3 F0, vec3 V, vec3 H) {
        return F0 + (vec3(1.) - F0) * pow(1. - max(dot(V, H), 0.), 5.);
    }
    vec3 color_pbr(vec3 fragment_normal, vec3 fragment_pos_world, vec3 albedo, float roughness, float metallic) {
        float alpha = roughness * roughness;
        vec3 F0 = vec3(0.04);
        F0 = mix(F0, vec3(1.), metallic);
        
        vec3 emitted_light = u_vec4_ambient_color.rgb * u_vec4_ambient_color[3];
        vec3 N = fragment_normal;
        
        vec3 V = normalize(u_cam_pos - fragment_pos_world);
        
        vec3 L = -u_vec3_light_dir1_direction;
        
        vec3 H = normalize(V + L);
        float shadow_factor = compute_shadow_factor();
        vec3 Ks = F(F0, V, H);
        vec3 Kd = (vec3(1.0) - Ks) * (1. - metallic);
        vec3 lambert = albedo / PI;
        vec3 cookTorranceNumerator = D(alpha, N, H) * G(alpha, N, V, L) * Ks;
        float cookTorranceDenominator = 4.0 * max(dot(V, N), 0.) * max(dot(L, N), 0.);
        cookTorranceDenominator = max(cookTorranceDenominator, 0.000001);
        vec3 cookTorrance = cookTorranceNumerator / cookTorranceDenominator;
        vec3 BRDF = Kd * lambert + cookTorrance;
        vec3 outgoingLight = BRDF * u_vec4_light_dir1_color.rgb * u_vec4_light_dir1_color[3] * max(dot(L, N), 0.);
        vec3 ambient = u_vec4_ambient_color.rgb * u_vec4_ambient_color[3] * albedo;
        return ambient + outgoingLight * shadow_factor;
    }
#endif
#endif
`,Pb=`#define LIGHT_MODEL_PHONG 1
#ifdef LIGHT_MODEL
#if LIGHT_MODEL == LIGHT_MODEL_PHONG
const float g_specular_power_max = 32.0;
const float g_specular_power_min = 2.0;
vec2 pbr_to_gloss(vec3 material_attributes)
{
    float weight = material_attributes.x;
    float roughness = material_attributes.y;
    float metallic = material_attributes.z;
    
    
    float specular_strength = weight * metallic;
    float specular_power = roughness * (g_specular_power_min - g_specular_power_max) + g_specular_power_max;
    return vec2(specular_strength, specular_power);
}
vec3 color_phong(vec3 fragment_normal, highp vec3 fragment_pos_world, vec3 albedo, float roughness, float metallic, float alpha) {
    vec2 specular_values = pbr_to_gloss(vec3(1., roughness, metallic));
    float specular_strength = specular_values.x;
    float specular_power = specular_values.y;
    
    
    bool use_light = UNPACK_BOOL1(u_int_light_flags);
    float shadow_factor = 1.0;
    if (use_light && (UNPACK_BOOL2(u_int_light_flags) || UNPACK_BOOL3(u_int_light_flags))) {
        shadow_factor = compute_shadow_factor();
    }
    
    vec3 ambient = u_vec4_ambient_color.rgb * u_vec4_ambient_color[3];
    
    float diff = max(dot(fragment_normal, -u_vec3_light_dir1_direction), 0.0);
    vec3 diffuse = u_vec4_light_dir1_color.rgb * u_vec4_light_dir1_color[3] * diff * shadow_factor;
    
    
    vec3 view_dir = normalize(u_cam_pos - fragment_pos_world);
    
    vec3 reflect_dir = reflect(u_vec3_light_dir1_direction, fragment_normal);
    float spec = pow(max(dot(view_dir, reflect_dir), 0.0), specular_power);
    
    
    vec3 specular = u_vec4_light_dir1_color.rgb * u_vec4_light_dir1_color[3] * spec * specular_strength * shadow_factor * alpha;
    return albedo * (ambient + diffuse) + specular;
}
#endif
#endif
`,Ab=`precision lowp float;
`,Lb=`precision mediump float;
`,Ju=`#define MIX_COLOR_MODE_READ_FROM_TARGET 1
#define MIX_COLOR_MODE_VERTEX_ATTRIBUTE 2
#define VERTEX_ATTRIBUTE_NAME_DENORMALIZED_DISTANCE_TO_LINE 1
`,Rb=`vec4 pack_float_to_vec4(float depth)
{
    const vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);
    const vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);
    vec4 res = fract(depth * bit_shift);
    res -= res.xxyz * bit_mask;
    return res;
}
float unpack_float_from_vec4(vec4 color)
{
    const 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(color, bit_shift);
}`,Fb=`#ifdef WEBGL2
#define varying in
#define attribute in
#define texture2D texture
#define gl_FragColor fragColor
out vec4 gl_FragColor;
#endif
#ifdef UBO
uniform CommonSettings
{
    mediump float u_float_rounding_factor;
    mediump float u_float_border_width_offset;
    mediump vec2 u_vec2_scale_limits;
    mediump vec2 u_vec2_depth_test_half_point_size;
    mediump vec2 u_vec2_vpt_size;
    
    mediump vec4 u_fog_color;
    mediump vec4 u_fog_color2;
    mediump vec2 u_fog_gradient;
    mediump vec2 u_fog_limits;
    mediump float u_fog_horizon_blend;
    mediump float u_fog_horizon_level;
    mediump float u_fog_horizon_pad;
    mediump float u_fog_distance;
    mediump vec4 u_sky_color;
    highp vec3 u_cam_pos; 
    
    
    
    
    
    
    mediump vec4 u_shadow_map_params; 
    highp mat4 u_mat4_clip_to_shadow;
    mediump float u_shadow_bias;
    mediump mat4 u_mat4_view_transposed;
    mediump mat4 u_mat4_proj_inverted;
    
    mediump vec2 u_vec2_halo_viewport_size;
    mediump vec2 u_vec2_halo_viewport_center_shift;
    mediump vec4 u_vec4_halo_radius_stops;
    mediump vec4 u_vec4_halo_color;
    mediump float u_float_halo_exp_factor;
    mediump vec4 u_vec4_default_background_color;
    
    mediump mat4 u_mat4_stars;
    mediump float u_float_pixelratio;
    mediump float u_float_stars_intensity;
};
#endif
`,Db=`#ifdef HAS_FRAG_DEPTH_EXT
#extension GL_EXT_frag_depth : require
#endif
`,zb=`uniform float u_sdtr_distance;
#ifdef SCREENDOOR
varying vec3 v_clipspace_pos;
#endif
float interleaved_gradient_noise()
{
    const vec3 m = vec3(0.06711056, 0.00583715, 52.9829189);
    return fract(m.z * fract(dot(gl_FragCoord.xy, m.xy)));
}
void apply_screendoor() {
    #ifdef SCREENDOOR
    if (u_sdtr_distance == 0.) {
        return;
    }
    float factor = smoothstep(0., u_sdtr_distance, v_clipspace_pos.z);
    float patternValue = interleaved_gradient_noise();
    float shaped = factor - patternValue;
    if (shaped <= 0.) {
        discard;
    }
    #endif
    return;
}
`,Bb=`#ifdef RENDER_SHADOWS
# if defined(WEBGL2) && defined(DEPTH_TEXTURE_SHADOW)
uniform mediump sampler2DShadow u_texture_shadow;
# else
uniform sampler2D u_texture_shadow;
# endif
# ifndef UBO
uniform mediump vec4 u_shadow_map_params;
# endif 
varying float v_depth_metric;
varying vec4 v_pos_from_light;
float get_shadow(vec3 coords) {
# if defined(WEBGL2) && defined(DEPTH_TEXTURE_SHADOW)
    
    return texture2D( u_texture_shadow, coords );
# else
# ifdef DEPTH_TEXTURE_SHADOW
    
    float shadow_depth = texture2D(u_texture_shadow, coords.xy, 0.).r;
# else
    
    
    float shadow_depth = unpack_float_from_vec4(texture2D(u_texture_shadow, coords.xy, 0.));
# endif
    float depth_diff = v_depth_metric - shadow_depth;
    if (depth_diff <= 0.) {
        return 1.0;
    }
    return 0.0;
# endif
}
float sample_shadow_texture(vec3 shadow_coord) {
    vec2 shadow_map_size = u_shadow_map_params.xy;
    float radius = u_shadow_map_params.z;
    vec2 texelSize = vec2( 1.0 ) / shadow_map_size;
    float dx0 = - texelSize.x * radius;
    float dy0 = - texelSize.y * radius;
    float dx1 = + texelSize.x * radius;
    float dy1 = + texelSize.y * radius;
    float dx2 = dx0 / 2.0;
    float dy2 = dy0 / 2.0;
    float dx3 = dx1 / 2.0;
    float dy3 = dy1 / 2.0;
    
    
    return (
        get_shadow( shadow_coord + vec3( dx0, dy0, 0.0 ) ) +
        get_shadow( shadow_coord + vec3( 0.0, dy0, 0.0 ) ) +
        get_shadow( shadow_coord + vec3( dx1, dy0, 0.0 ) ) +
        get_shadow( shadow_coord + vec3( dx2, dy2, 0.0 ) ) +
        get_shadow( shadow_coord + vec3( 0.0, dy2, 0.0 ) ) +
        get_shadow( shadow_coord + vec3( dx3, dy2, 0.0 ) ) +
        get_shadow( shadow_coord + vec3( dx0, 0.0, 0.0 ) ) +
        get_shadow( shadow_coord + vec3( dx2, 0.0, 0.0 ) ) +
        get_shadow( shadow_coord) +
        get_shadow( shadow_coord + vec3( dx3, 0.0, 0.0 ) ) +
        get_shadow( shadow_coord + vec3( dx1, 0.0, 0.0 ) ) +
        get_shadow( shadow_coord + vec3( dx2, dy3, 0.0 ) ) +
        get_shadow( shadow_coord + vec3( 0.0, dy3, 0.0 ) ) +
        get_shadow( shadow_coord + vec3( dx3, dy3, 0.0 ) ) +
        get_shadow( shadow_coord + vec3( dx0, dy1, 0.0 ) ) +
        get_shadow( shadow_coord + vec3( 0.0, dy1, 0.0 ) ) +
        get_shadow( shadow_coord + vec3( dx1, dy1, 0.0 ) )
    ) * ( 1.0 / 17.0 );
}
float compute_shadow_factor()
{
    vec4 light_pos = v_pos_from_light;
# ifdef FRAGMENT_NORMAL
    
    
    float normal_bias = u_shadow_map_params[3];
    vec3 norm_from_light = calc_fragment_normal(light_pos.xyz);
    light_pos.xyz -= normal_bias * norm_from_light;
# endif
    vec3 clip_space = light_pos.xyz / light_pos.w;
    
    float clip_factor = smoothstep(0.5, 1.0, length(clip_space));
    if (clip_factor >= 1.0) {
        return 1.0;
    }
# if defined(DEPTH_TEXTURE_SHADOW) && defined(WEBGL2)
    vec3 lightPovPositionInTexture = 0.5 * light_pos.xyz + 0.5;
    float shadow_factor = sample_shadow_texture(lightPovPositionInTexture);
# else
    vec3 uv = 0.5 * clip_space + vec3(0.5);
    float shadow_factor = sample_shadow_texture(uv);
# endif
    
    shadow_factor = mix(shadow_factor, 1.0, clip_factor);
    return shadow_factor;
}
#else  
float compute_shadow_factor()
{
    return 1.0;
}
#endif `,Ku=`#ifndef SIGNED_DISTANCE_FUNCTIONS_FSH
#define SIGNED_DISTANCE_FUNCTIONS_FSH
float sdf_intersect(const float distance1, const float distance2)
{
    return max(distance1, distance2);
}
float sdf_merge(const float distance1, const float distance2)
{
    return min(distance1, distance2);
}
float sdf_difference(const float distance1, const float distance2)
{
    return max(distance1, -distance2);
}
float sdf_half_plane(const vec2 coords, const vec2 normal)
{
    return dot(coords, normal);
}
float sdf_circle(const vec2 coords, const float radius)
{
    return length(coords) - radius;
}
float sdf_half_planes_cut(const vec2 coords, const vec2 normal1, const vec2 normal2, const vec2 cut_point, const mat2 derivatives)
{
    vec2 cut_normal1 = vec2(normal1.y, -normal1.x);
    float cut1 = sdf_half_plane(coords - cut_point, cut_normal1) /
        max(abs(dot(derivatives[0], cut_normal1)), abs(dot(derivatives[1], cut_normal1)));
    vec2 cut_normal2 = vec2(normal2.y, -normal2.x);
    float cut2 = sdf_half_plane(coords - cut_point, cut_normal2) /
        max(abs(dot(derivatives[0], cut_normal2)), abs(dot(derivatives[1], cut_normal2)));
    return sdf_merge(cut1, cut2);
}
float sdf_box( in vec2 p, in vec2 b )
{
    vec2 d = abs(p)-b;
    return length(max(d,0.0)) + min(max(d.x,d.y),0.0);
}
float sdf_triangle(in vec2 p, in float width) {
    return abs(p.x) - (p.y + .5) * width * .5;
}
float dot2(in vec2 p) {
    return dot(p, p);
}
float sdf_chevron(in vec2 p, float width, float skew, float rounding)
{
    p.x = abs(p.x);
    if (p.y + p.x > 1.0) {
        return sqrt(dot2(p - vec2(0.25, 0.75))) - sqrt(2.0)/4.0;
    }
    return sqrt(min(dot2(p - vec2(0.00, 1.00)),
                    dot2(p - 0.5 * max(p.x + p.y, 0.0)))) * sign(p.x - p.y);
}
#endif
`,Ob=`#include <enable_standard_derivatives>
#include <highp_float>
#include <prelude>
#include <affine_step>
#include <signed_distance_functions>
#include <arrow_functions>
#include <circle_functions>
#include <fog>
uniform float u_float_tip_height_multiplier;
uniform float u_float_wing_height_multiplier;
uniform float u_float_wing_width_multiplier;
varying vec2 v_vec2_line_type_arrow_tail;
varying vec4 v_vec4_arrow_width_length_border_outer;
varying vec4 v_vec4_texcoord_arrow_line;
varying vec4 v_vec4_distance_vertex_hiding;
#ifdef ENTRANCE_ARROWS_ROUNDING
varying vec3 v_vec3_radius_tip_wing_tail;
#endif
varying vec4 v_vec4_circle_center_tip_wing;
varying vec4 v_vec4_color;
varying vec4 v_vec4_border_color;
const float g_type_arrow = 1.;
const float g_type_start_border = 2.;
bool lookalike(const float a, const float b)
{
    return abs(a - b) < 1e-4;
}
float filter_border(const float start, const float value)
{
    return step(start, value) * 2. - 1.;
}
float arrow_distance(
    const ArrowDistanceParameters arrow_parameters,
    const vec2 texcoord,
    const float offset,
    const mat2 derivatives,
    const float line_distance,
    const float line_distance_no_offset,
    
    
    const float border_width,
    const vec2 wing_normal)
{
    ArrowDistances ad = calculate_arrow_distances(arrow_parameters, texcoord, offset, derivatives);
    float derivatives_x_multiplier = 1. / max(abs(derivatives[0].x), abs(derivatives[1].x));
    
    
    float intersection_point = arrow_parameters.full_length - arrow_parameters.arrow_height
        - arrow_parameters.width * wing_normal.y / wing_normal.x;
    float tail_arrow_intersection = filter_border(-1., (texcoord.x - intersection_point) * derivatives_x_multiplier);
    
    float top_wings;
    float bottom_wings;
    #ifdef ENTRANCE_ARROWS_ROUNDING
    top_wings = sdf_intersect(sdf_intersect(ad.top_left_wing, ad.top_right_wing), ad.tip_circle_cut);
    top_wings = sdf_merge(top_wings, ad.tip_circle);
    top_wings = sdf_intersect(top_wings, ad.top_tip_cut);
    float wings_circles = sdf_merge(ad.left_wing_circle, ad.right_wing_circle);
    float wings_radius_cut = sdf_intersect(ad.left_wing_circle_cut, ad.right_wing_circle_cut);
    bottom_wings = sdf_merge(ad.bottom_left_wing, ad.bottom_right_wing);
    bottom_wings = sdf_intersect(bottom_wings, wings_radius_cut);
    bottom_wings = sdf_merge(bottom_wings, wings_circles);
    #else
    top_wings = sdf_intersect(ad.top_left_wing, ad.top_right_wing);
    bottom_wings = sdf_merge(ad.bottom_left_wing, ad.bottom_right_wing);
    #endif
    float line_without_offset = filter_border(0., line_distance_no_offset);
    float bottom_wings_with_tail = sdf_merge(bottom_wings, line_without_offset);
    float wings_with_tail = sdf_intersect(bottom_wings_with_tail, top_wings);
    
    float tail_hide_part = v_vec2_line_type_arrow_tail.y;
    float tail_hide_mask = (-texcoord.x - tail_hide_part) * derivatives_x_multiplier;
    float clipped_tail = sdf_intersect(tail_hide_mask, sdf_intersect(line_distance, top_wings));
    return (v_vec4_distance_vertex_hiding.x < v_vec4_distance_vertex_hiding.y)
        ? sdf_intersect(-sdf_intersect(tail_arrow_intersection, line_without_offset), wings_with_tail)
        : sdf_merge(clipped_tail, sdf_intersect(-sdf_intersect(tail_arrow_intersection, line_without_offset), wings_with_tail));
}
vec4 distance_to_arrow_line_color(
    const float fill_distance,
    const float border_distance)
{
    return distance_to_color(fill_distance, border_distance, v_vec4_color, v_vec4_border_color);
}
vec4 arrow_color(
    const vec2 texcoord,
    const ArrowDistanceParameters arrow_parameters,
    const float line_fill_distance,
    const float line_border_distance,
    const vec2 wing_normal)
{
    mat2 derivatives = mat2(dFdx(texcoord), dFdy(texcoord));
    
    float border_clipping = (abs(texcoord.y) - v_vec4_arrow_width_length_border_outer.w) / max(abs(derivatives[0].y), abs(derivatives[1].y));
    float border_width = v_vec4_arrow_width_length_border_outer.z;
    float arrow_border_distance = arrow_distance(
        arrow_parameters,
        texcoord,
        v_vec4_arrow_width_length_border_outer.z,
        derivatives,
        line_border_distance,
        line_fill_distance,
        border_width,
        wing_normal);
    float border_factor = max(border_clipping, affine_step(0., 1., arrow_border_distance));
    return distance_to_arrow_line_color(
        arrow_distance(arrow_parameters, texcoord, 0., derivatives, line_fill_distance, line_fill_distance, border_width, wing_normal),
        border_factor);
}
float line_start_distance(
    const vec2 texcoord,
    const float offset,
    const mat2 derivatives,
    const float line_distance,
    const float half_width,
    const float border_width,
    const float tail_radius)
{
    float derivatives_x_multiplier = 1. / max(abs(derivatives[0].x), abs(derivatives[1].x));
    
    float tail_hide_part = v_vec2_line_type_arrow_tail.y;
    float d0 = (-texcoord.x - offset) * derivatives_x_multiplier;
    float dh = (texcoord.x - tail_hide_part) * derivatives_x_multiplier;
    float rect = max(d0, max(line_distance, dh));
    
    float radius_offset = tail_radius - border_width;
    float circle_radius = radius_offset + offset;
    vec2 left_circle_center = vec2(radius_offset, half_width - radius_offset);
    vec2 right_circle_center = vec2(radius_offset, -half_width + radius_offset);
    vec2 left_circle_normal = normalize(texcoord - left_circle_center);
    vec2 right_circle_normal = normalize(texcoord - right_circle_center);
    float cut_x = (-texcoord.x + radius_offset) * derivatives_x_multiplier;
    float cut_y = (abs(texcoord.y) - half_width + radius_offset) / max(abs(derivatives[0].y), abs(derivatives[1].y));
    float circles_cut = min(cut_x, cut_y);
    float left_circle = length(texcoord - left_circle_center) - circle_radius;
    left_circle = left_circle / max(abs(dot(derivatives[0], left_circle_normal)), abs(dot(derivatives[1], left_circle_normal)));
    float right_circle = length(texcoord - right_circle_center) - circle_radius;
    right_circle = right_circle / max(abs(dot(derivatives[0], right_circle_normal)), abs(dot(derivatives[1], right_circle_normal)));
    float circles = min(left_circle, right_circle);
    rect = min(max(rect, circles_cut), circles);
    return rect;
}
vec4 line_color(
    const float line_fill_distance,
    const float line_border_distance,
    const float line_half_width,
    const float border_width,
    const float tail_radius)
{
    float type = v_vec2_line_type_arrow_tail.x;
    float fill_distance = line_fill_distance;
    float border_distance = line_border_distance;
    if (lookalike(type, g_type_start_border))
    {
        vec2 texcoord = v_vec4_texcoord_arrow_line.xy;
        mat2 derivatives = mat2(dFdx(texcoord), dFdy(texcoord));
        fill_distance = line_start_distance(
            texcoord, 0.,
            derivatives,
            line_fill_distance,
            line_half_width,
            border_width,
            tail_radius);
        border_distance = line_start_distance(
            texcoord,
            v_vec4_arrow_width_length_border_outer.z,
            derivatives,
            line_border_distance,
            line_half_width,
            border_width,
            tail_radius);
    }
    return distance_to_arrow_line_color(fill_distance, border_distance);
}
vec4 arrow_line_color()
{
    if (lookalike(min(v_vec4_distance_vertex_hiding.y, 1.), 1.)
        || lookalike(v_vec4_distance_vertex_hiding.w, 1.)
        || !lookalike(v_vec2_line_type_arrow_tail.x, g_type_arrow) && (v_vec4_distance_vertex_hiding.x < v_vec4_distance_vertex_hiding.y || v_vec4_distance_vertex_hiding.x > v_vec4_distance_vertex_hiding.z))
    {
        discard;
    }
    vec2 wing_normal = -normalize(vec2(u_float_wing_width_multiplier, u_float_wing_height_multiplier));
    vec2 tip_normal = normalize(vec2(u_float_wing_width_multiplier, u_float_tip_height_multiplier));
    float tip_radius;
    float wing_radius;
    float tail_radius;
    #ifdef ENTRANCE_ARROWS_ROUNDING
    tip_radius = v_vec3_radius_tip_wing_tail.x;
    wing_radius = v_vec3_radius_tip_wing_tail.y;
    tail_radius = v_vec3_radius_tip_wing_tail.z;
    #else
    tip_radius = 0.;
    wing_radius = 0.;
    tail_radius = 0.;
    #endif
    ArrowDistanceParameters arrow_parameters = calculate_arrow_distance_parameters(
        wing_normal,
        tip_normal,
        v_vec4_arrow_width_length_border_outer.x,
        v_vec4_arrow_width_length_border_outer.y,
        u_float_tip_height_multiplier,
        u_float_wing_height_multiplier,
        tip_radius,
        wing_radius,
        v_vec4_arrow_width_length_border_outer.z,
        v_vec4_circle_center_tip_wing.xy,
        v_vec4_circle_center_tip_wing.zw);
    float line_width = arrow_parameters.width;
    float line_border = v_vec4_arrow_width_length_border_outer.z;
    
    vec2 line_texcoord = v_vec4_texcoord_arrow_line.zw;
    mat2 line_derivatives = mat2(dFdx(line_texcoord), dFdy(line_texcoord));
    CircleDistance circle_fill_distance = circle_color_distance(line_derivatives, line_texcoord, line_width);
    CircleDistance circle_border_distance = circle_color_distance(line_derivatives, line_texcoord, line_width + line_border);
    float line_fill_distance = affine_step(-1., 0., circle_fill_distance.distance / circle_fill_distance.width) - 1.;
    float line_border_distance = affine_step(0., circle_border_distance.width, circle_border_distance.distance);
    return lookalike(v_vec2_line_type_arrow_tail.x, g_type_arrow)
        ? arrow_color(v_vec4_texcoord_arrow_line.xy, arrow_parameters, line_fill_distance, line_border_distance, wing_normal)
        : line_color(line_fill_distance, line_border_distance, line_width, line_border, tail_radius);
}
void main()
{
    vec4 color = arrow_line_color();
    gl_FragColor = apply_fog(color);
}
`,wb=`#include <highp_float>
#include <prelude>
varying vec2 v_vec2_line_type_arrow_tail;
varying vec4 v_vec4_distance_vertex_hiding;
varying vec4 v_vec4_identifier;
const float g_type_arrow = 1.;
bool lookalike(const float a, const float b)
{
    return abs(a - b) < 1e-5;
}
void main()
{
    if (lookalike(min(v_vec4_distance_vertex_hiding.y, 1.), 1.)
        || lookalike(v_vec4_distance_vertex_hiding.w, 1.)
        || !lookalike(v_vec2_line_type_arrow_tail.x, g_type_arrow) && (v_vec4_distance_vertex_hiding.x < v_vec4_distance_vertex_hiding.y || v_vec4_distance_vertex_hiding.x > v_vec4_distance_vertex_hiding.z))
    {
        discard;
    }
    gl_FragColor = v_vec4_identifier;
}
`,Nb=`#include <highp_float>
#include <prelude>
#include <cam_pos>
#include <affine_step>
#include <fog>
#include <bit_mask>
#include <pack_depth>
#include <shadow>
#include <light>
uniform vec4 u_vec4_color;
varying vec2 v_vec2_circle;
varying float v_float_width;
void main() {
    float center_distance = dot(v_vec2_circle, v_vec2_circle);
    vec4 light = light_factor_surface();
    vec4 color = u_vec4_color * affine_step(1.0, 1.0 - 4.0 / v_float_width, center_distance) * light;
    gl_FragColor = apply_fog_alpha(color);
}
`,kb=`#include <lowp_float>
#include <prelude>
#include <fog>
varying vec4 v_vec4_color;
void main()
{
    gl_FragColor = apply_fog(v_vec4_color);
}
`,Ub=`#include <lowp_float>
#include <prelude>
varying vec4 v_vec4_identifier;
void main()
{
    gl_FragColor = v_vec4_identifier;
}
`,Mb=`#include <enable_standard_derivatives>
#include <highp_float>
#include <prelude>
#include <cam_pos>
#include <fog>
#include <screendoor_transparency>
#include <fragment_normal>
#include <bit_mask>
#include <pack_depth>
#include <shadow>
#include <light>
#include <dem>
#include <apply_color_effect>
varying vec4 v_vec4_color;
varying vec4 v_vec4_rotated_scaled_vertex;
void main()
{
    if (check_dem_invalid() != 0) {
        discard;
    }
    apply_screendoor();
    vec3 normal = calc_fragment_normal(v_vec4_rotated_scaled_vertex.xyz);
    vec4 light = light_factor(normal);
    vec4 color = v_vec4_color * light;
    gl_FragColor = apply_fog(apply_color_effect(color));
# ifndef BLEND
    
    gl_FragColor /= gl_FragColor.a;
# endif
}
`,Hb=`#ifdef COPY_DEPTH
#include <require_frag_depth>
#endif
#include <mediump_float>
#include <prelude>
#if defined(IS_DEPTH_TEXTURE) && defined(WEBGL2)
uniform mediump sampler2DShadow u_texture;
#else
uniform sampler2D u_texture;
#endif
#ifdef COPY_DEPTH
uniform sampler2D u_depth;
#endif
varying vec2 v_vec2_texcoord;
void main()
{
#if defined(IS_DEPTH_TEXTURE) && defined(WEBGL2)
    gl_FragColor = vec4(vec3(texture2D(u_texture, vec3(v_vec2_texcoord, 1.0))), 1.0);
#else
    gl_FragColor = texture2D(u_texture, v_vec2_texcoord);
#endif
#ifdef COPY_DEPTH
    float depthR = texture2D(u_depth, v_vec2_texcoord).r;
# ifdef WEBGL1
#  ifdef HAS_FRAG_DEPTH_EXT
     gl_FragDepthEXT = depthR;
#  else 
     discard;
#  endif 
# else 
     gl_FragDepth = depthR;
# endif 
#endif 
}
`,Gb=`#include <mediump_float>
#include <prelude>
varying float v_float_height;
void main()
{
  gl_FragColor = vec4(v_float_height, 0., 0., 1.);
}
`,Vb=`#include <mediump_float>
#include <prelude>
uniform sampler2D u_sr2d_texture;
varying vec2 v_vec2_texcoord;
void main()
{
  gl_FragColor = texture2D(u_sr2d_texture, v_vec2_texcoord);
}
`,Zb=`#include <mediump_float>
#include <prelude>
varying vec4 v_vec4_color;
void main()
{
    gl_FragColor = v_vec4_color;
}
`,Wb=`#include <mediump_float>
#include <prelude>
#include <dem>
varying vec4 v_vec4_coords;
void main()
{
    if (check_dem_invalid() != 0) {
discard;
}
    gl_FragColor = v_vec4_coords;
}
`,jb=`#include <mediump_float>
#include <prelude>
varying vec4 v_vec4_coords;
void main()
{
    gl_FragColor = v_vec4_coords;
}
`,Xb=`#include <enable_standard_derivatives>
#include <mediump_float>
#include <prelude>
#include <cam_pos>
#include <fog>
#include <bit_mask>
#include <pack_depth>
#include <shadow>
#include <light>
uniform sampler2D u_flat_tex;
uniform sampler2D u_hillshade_tex;
uniform sampler2D u_tex_hillshade_ramp;
uniform float u_float_dem_shading_intensity;
varying vec4 v_vec4_texcoord;
varying vec2 hs_tex_pos;
void main()
{
    
    if (v_vec4_texcoord.z > 0.) {
        discard;
    }
    vec4 vec4_texcoord = v_vec4_texcoord / v_vec4_texcoord.w;
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
     
    if (vec4_texcoord.x < 0. || vec4_texcoord.x > 1. || vec4_texcoord.y < 0. || vec4_texcoord.y > 1.) {
        discard;
    } else {
        vec4 flatMapColor = texture2D(u_flat_tex, vec4_texcoord.xy);
        
        if (u_float_dem_shading_intensity > 0.) {
            
            vec3 normal = texture2D(u_hillshade_tex, hs_tex_pos).rgb * 2. - vec3(1.);
            
            float light_raw = light_factor_dem(normal);
            float dir1_intensity = u_vec4_light_dir1_color[3];
            float amb_intensity = u_vec4_ambient_color[3];
            float total_intensity = dir1_intensity + amb_intensity;
            
            
            float amb_intensity_shifted = u_vec4_ambient_color[3];
            float dir_intensity_shifted = dir1_intensity;
            
            float horizonatal_surface_light_dir_dot = light_factor_dem(vec3(0, 0, 1));
            float horizonatal_surface_light_intensity = amb_intensity + dir1_intensity * horizonatal_surface_light_dir_dot;
            if (u_float_dem_shading_intensity > 0.5) { 
                amb_intensity_shifted = mix(amb_intensity, 0., (u_float_dem_shading_intensity - 0.5) / 0.5);
                dir_intensity_shifted = (horizonatal_surface_light_intensity - amb_intensity_shifted) / horizonatal_surface_light_dir_dot;
            } else if (u_float_dem_shading_intensity < 0.5) { 
                dir_intensity_shifted = mix(0., dir1_intensity, u_float_dem_shading_intensity / 0.5);
                amb_intensity_shifted = horizonatal_surface_light_intensity - dir_intensity_shifted * horizonatal_surface_light_dir_dot;
            } 
            
            float tex_coord = clamp(dir_intensity_shifted * light_raw * 0.5 + 0.5, 0., 0.99);
            
            float dir_light_factor = 2. * (texture2D(u_tex_hillshade_ramp, vec2(tex_coord, 0.5)).a - 0.5);
            vec3 light_color = amb_intensity_shifted * u_vec4_ambient_color.rgb + dir_light_factor * u_vec4_light_dir1_color.rgb;
            
            gl_FragColor.rgb = light_color * flatMapColor.rgb;
            
            
            gl_FragColor.a = flatMapColor.a;
        } else {
            gl_FragColor = flatMapColor * light_factor_surface();
        }
        gl_FragColor = apply_fog(gl_FragColor);
    }
}
`,$b=`#include <enable_standard_derivatives>
#include <mediump_float>
#include <prelude>
#include <cam_pos>
#include <fog>
#include <bit_mask>
#include <pack_depth>
#include <shadow>
#include <light>
#include <fragment_normal>
uniform sampler2D u_flat_tex;
uniform sampler2D u_hillshade_tex;
uniform sampler2D u_tex_hillshade_ramp;
uniform int u_int_inline_contour_enabled;
uniform float u_float_contour_minor_interval;
uniform float u_float_contour_major_interval;
uniform float u_float_contour_index_interval;
uniform vec4 u_vec4_contour_minor_color;
uniform vec4 u_vec4_contour_major_color;
uniform vec4 u_vec4_contour_index_color;
uniform float u_float_contour_minor_width;
uniform float u_float_contour_major_width;
uniform float u_float_contour_index_width;
uniform int u_int_identify;
uniform float u_float_dem_shading_intensity;
varying vec4 v_vec4_texcoord;
varying float v_height;
varying vec3 v_vec3_position;
vec3 computeContourCoverage(float h, out float out_fw, out float out_d, out float out_nonZero) {
    float minorInterval = u_float_contour_minor_interval;
    if (minorInterval < EPSILON) {
        out_fw = 0.0;
        out_d = 0.0;
        out_nonZero = 0.0;
        return vec3(0.0);
    }
    
    float halfMinor = minorInterval * 0.5;
    out_d = abs(mod(h + halfMinor, minorInterval) - halfMinor);
    
    out_fw = fwidth(h);
    
    float level = floor(h / minorInterval + 0.5) * minorInterval;
    
    out_nonZero = step(EPSILON, abs(h)) * step(EPSILON, abs(level));
    
    float majorInterval = u_float_contour_major_interval;
    float indexInterval = u_float_contour_index_interval;
    float tolerance = max(minorInterval * 0.01, 1e-3);
    float majorRemainder = step(tolerance, majorInterval) * abs(mod(level + majorInterval * 0.5, majorInterval) - majorInterval * 0.5);
    float indexRemainder = step(tolerance, indexInterval) * abs(mod(level + indexInterval * 0.5, indexInterval) - indexInterval * 0.5);
    
    float isIndex = step(indexRemainder, tolerance) * step(tolerance, indexInterval);
    float isMajor = step(majorRemainder, tolerance) * step(tolerance, majorInterval) * (1.0 - isIndex);
    float isMinor = (1.0 - isIndex) * (1.0 - isMajor);
    return vec3(isMinor, isMajor, isIndex);
}
void main() {
    vec4 vec4_texcoord = v_vec4_texcoord / v_vec4_texcoord.w;
    if(vec4_texcoord.x < 0. || vec4_texcoord.x > 1. || vec4_texcoord.y < 0. || vec4_texcoord.y > 1.) {
        discard;
    }
    vec4 flatMapColor = texture2D(u_flat_tex, vec4_texcoord.xy);
    if (u_int_identify == 1) {
        gl_FragColor = flatMapColor;
        return;
    }
    vec4 lf = light_factor_dem2(calc_fragment_normal(v_vec3_position));
    gl_FragColor = vec4(lf.rgb * flatMapColor.rgb, flatMapColor.a);
    if (u_int_inline_contour_enabled == 1) {
        float fw, d, nonZero;
        vec3 contour = computeContourCoverage(v_height, fw, d, nonZero);
        float isMinor = contour.r;
        float isMajor = contour.g;
        float isIndex = contour.b;
        
        float idxEnabled = step(EPSILON, u_vec4_contour_index_color.a) * step(EPSILON, u_float_contour_index_width);
        float majorEnabled = step(EPSILON, u_vec4_contour_major_color.a) * step(EPSILON, u_float_contour_major_width);
        float minorEnabled = step(EPSILON, u_vec4_contour_minor_color.a) * step(EPSILON, u_float_contour_minor_width);
        
        float pickIdx   = isIndex * idxEnabled;
        float pickMajor = max(isIndex, isMajor) * (1.0 - pickIdx) * majorEnabled;
        float pickMinor = (1.0 - pickIdx - pickMajor) * minorEnabled;
        
        float width = pickIdx * u_float_contour_index_width +
                      pickMajor * u_float_contour_major_width +
                      pickMinor * u_float_contour_minor_width;
        float finalCoverage = smoothstep(max(fw * width, EPSILON), 0.0, d) * nonZero;
        vec3 contourColor = pickIdx * u_vec4_contour_index_color.rgb +
                            pickMajor * u_vec4_contour_major_color.rgb +
                            pickMinor * u_vec4_contour_minor_color.rgb;
        float userAlpha = pickIdx * u_vec4_contour_index_color.a +
                          pickMajor * u_vec4_contour_major_color.a +
                          pickMinor * u_vec4_contour_minor_color.a;
        float srcAlpha = finalCoverage * userAlpha;
        gl_FragColor.rgb = gl_FragColor.rgb * (1.0 - srcAlpha) + contourColor * finalCoverage;
    }
    gl_FragColor = apply_fog(gl_FragColor);
}
`,qb=`#include <lowp_float>
#include <prelude>
uniform sampler2D u_tex_dem;
uniform float u_float_dem_resolution;
uniform float u_float_dem_cell_size;
uniform float u_float_dem_scale;
const float M_PI = 3.1415926535897932384626433832795;
varying vec2 v_vec2_texcoord;
mat3 get_kernel(vec2 pos, float step, float defval) {
    mat3 kernel;
    for (int x = 0; x < 3; x++) {
        vec3 col;
        for (int y = 0; y < 3; y++) {
            vec4 val = texture2D(u_tex_dem, vec2(pos.x + float(x - 1) * step, pos.y + float(y - 1) * step));
            col[y] = val.r;
            if (val.a < 1.) {
                col[y] = defval;
            }
        }
        kernel[x] = col;
    }
    return kernel;
}
float calc_aspect(mat3 kernel) {
    float dzdx = ((kernel[2].z + 2.0 * kernel[2].y + kernel[2].x) - (kernel[0].z + 2.0 * kernel[0].y + kernel[0].x)) / 8.;
    float dzdy = ((kernel[0].x + 2.0 * kernel[1].x + kernel[2].x) - (kernel[0].z + 2.0 * kernel[1].z + kernel[2].z)) / 8.;
    
    if (dzdx == 0. && dzdy == 0.) {
        return 0.;
    }
    
    return atan(-dzdx, dzdy);
}
float calc_slope(mat3 kernel, float cell_size) {
    float dzdx = ((kernel[2].z + 2. * kernel[2].y + kernel[2].x) - (kernel[0].z + 2. * kernel[0].y + kernel[0].x)) / (8. * cell_size);
    float dzdy = ((kernel[0].x + 2. * kernel[1].x + kernel[2].x) - (kernel[0].z + 2. * kernel[1].z + kernel[2].z)) / (8. * cell_size);
    float rise_run = sqrt(dzdx * dzdx + dzdy * dzdy);
    return atan(rise_run);
}
vec3 dem_normal(const vec2 tex_pos)
{
    
    float tex_step = 1. / u_float_dem_resolution;
    
    if (u_float_dem_scale == 0.) {
        return vec3(0.);
    }
    
    vec4 e = texture2D(u_tex_dem, tex_pos);
    if (e.a < 1.) {
        
        return vec3(0.);
    }
    mat3 kernel = get_kernel(tex_pos.xy, tex_step, e.r);
    
    float aspect = calc_aspect(kernel);
    
    
    float slope = calc_slope(kernel, u_float_dem_cell_size);
    
    slope = M_PI * 0.5 - slope; 
    aspect = aspect - M_PI * 0.5; 
    float cosSlope = cos(slope);
    vec3 normal = normalize(vec3(cosSlope * cos(aspect), -1. * cosSlope * sin(aspect), sin(slope)));
    
    return normal * 0.5 + vec3(0.5);
}
void main() {
    gl_FragColor = vec4(dem_normal(v_vec2_texcoord), 1);
}
`,Yb=`#include <require_frag_depth>
#include <highp_float>
void main()
{
    
    
    
    #ifdef WEBGL1
    #ifdef HAS_FRAG_DEPTH_EXT
    gl_FragDepthEXT = 1.0;
    #else 
    discard;
    #endif 
    #else 
    gl_FragDepth = 1.0;
    #endif 
}
`,Qb=`#include <mediump_float>
#include <prelude>
#ifndef UBO
uniform vec2 u_vec2_vpt_size;
#endif
uniform sampler2D u_texture;
varying vec2 v_vec2_texcoord;
#ifndef FXAA_REDUCE_MIN
    #define FXAA_REDUCE_MIN   (1.0/ 128.0)
#endif
#ifndef FXAA_REDUCE_MUL
    #define FXAA_REDUCE_MUL   (1.0 / 8.0)
#endif
#ifndef FXAA_SPAN_MAX
    #define FXAA_SPAN_MAX     8.0
#endif
void texcoords(vec2 fragCoord, vec2 resolution,
            out vec2 v_rgbNW, out vec2 v_rgbNE,
            out vec2 v_rgbSW, out vec2 v_rgbSE,
            out vec2 v_rgbM) {
    vec2 inverseVP = 1.0 / resolution.xy;
    v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;
    v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;
    v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;
    v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;
    v_rgbM = vec2(fragCoord * inverseVP);
}
vec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 resolution,
            vec2 v_rgbNW, vec2 v_rgbNE,
            vec2 v_rgbSW, vec2 v_rgbSE,
            vec2 v_rgbM) {
    vec4 color;
    mediump vec2 inverseVP = vec2(1.0 / resolution.x, 1.0 / resolution.y);
    vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;
    vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;
    vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;
    vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;
    vec4 texColor = texture2D(tex, v_rgbM);
    vec3 rgbM  = texColor.xyz;
    vec3 luma = vec3(0.299, 0.587, 0.114);
    float lumaNW = dot(rgbNW, luma);
    float lumaNE = dot(rgbNE, luma);
    float lumaSW = dot(rgbSW, luma);
    float lumaSE = dot(rgbSE, luma);
    float lumaM  = dot(rgbM,  luma);
    float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));
    float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));
    mediump vec2 dir;
    dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));
    dir.y =  ((lumaNW + lumaSW) - (lumaNE + lumaSE));
    float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *
                          (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);
    float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);
    dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),
              max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),
              dir * rcpDirMin)) * inverseVP;
    vec3 rgbA = 0.5 * (
        texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +
        texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);
    vec3 rgbB = rgbA * 0.5 + 0.25 * (
        texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +
        texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);
    float lumaB = dot(rgbB, luma);
    if ((lumaB < lumaMin) || (lumaB > lumaMax))
        color = vec4(rgbA, texColor.a);
    else
        color = vec4(rgbB, texColor.a);
    return color;
}
void main()
{
    mediump vec2 v_rgbNW;
    mediump vec2 v_rgbNE;
    mediump vec2 v_rgbSW;
    mediump vec2 v_rgbSE;
    mediump vec2 v_rgbM;
    vec2 fragCoord = v_vec2_texcoord * u_vec2_vpt_size;
    texcoords(fragCoord, u_vec2_vpt_size, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);
    gl_FragColor = fxaa(u_texture, fragCoord, u_vec2_vpt_size, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);
}
`,Jb=`#include <mediump_float>
#include <prelude>
#ifndef UBO
uniform mediump vec4 u_vec4_halo_color;
uniform mediump vec2 u_vec2_halo_viewport_size;
uniform mediump vec2 u_vec2_halo_viewport_center_shift;
uniform mediump vec4 u_vec4_halo_radius_stops;
uniform mediump float u_float_halo_exp_factor;
#endif
varying vec2 v_vec2_uv;
void main() {
    float dist = length(v_vec2_uv);
    float halo_alpha = u_vec4_halo_color.a;
    vec4 halo_color = vec4(u_vec4_halo_color.rgb, 0.);
    vec4 empty_color = vec4(0.0);
    vec4 white_color1 = vec4(1., 1., 1., halo_alpha);
    vec4 white_color2 = vec4(white_color1.rgb, halo_alpha * 0.9);
    float r0 = u_vec4_halo_radius_stops[0];
    float r1 = u_vec4_halo_radius_stops[1];
    float r2 = u_vec4_halo_radius_stops[2];
    float r3 = u_vec4_halo_radius_stops[3];
    float t0 = max(0.0, (dist - r1) / (r3 - r1));
    float t0e = 1.0 - exp(u_float_halo_exp_factor * t0);
    
    vec4 color = mix(white_color2, halo_color, t0e);
    
    color = mix(white_color1, color, smoothstep(r1, r2, dist));
    
    color = mix(empty_color, color, smoothstep(r0, r1, dist));
    gl_FragColor = color;
}
`,Kb=`#include <mediump_float>
#include <prelude>
#ifndef UBO
uniform mediump vec4 u_vec4_default_background_color;
uniform mediump vec4 u_vec4_halo_radius_stops;
#endif
varying vec2 v_vec2_uv;
void main() {
    float dist = length(v_vec2_uv);
    float r1 = u_vec4_halo_radius_stops[1];
    if(dist > r1) {
        discard;
    }
    gl_FragColor = u_vec4_default_background_color;
}
`,eS=`#include <enable_standard_derivatives>
#include <highp_float>
#include <prelude>
#include <cam_pos>
#include <fog>
#include <screendoor_transparency>
#include <bit_mask>
#include <pack_depth>
#include <shadow>
#include <light>
#include <light_pbr>
#include <light_phong>
#include <dem>
#include <alpha_mode_defs>
#include <apply_color_effect>
uniform vec4 u_vec4_color;
#ifdef MAP_MESH_TEXTURE
uniform sampler2D u_sampler_map_tex;
#endif
#ifdef COLOR_TEXTURE
uniform sampler2D u_sr2d_texture_0;
#endif
#ifdef AO_TEXTURE
uniform sampler2D u_ao_texture;
#endif
#ifdef PBR_TEXTURE
uniform sampler2D u_pbr_texture;
#endif
#ifdef LIGHT_MODEL
#if  (LIGHT_MODEL == LIGHT_MODEL_PBR || LIGHT_MODEL == LIGHT_MODEL_PHONG)
uniform float u_float_metallic;
uniform float u_float_roughness;
#endif
#endif
varying vec3 v_vec3_normal;
varying vec3 v_vec3_fragment_pos_world;
#ifdef MAP_MESH_TEXTURE
uniform vec2 u_vec2_tex_scale;
uniform float u_float_tex_shift_scale;
varying vec4 v_tex_coord;
#endif
#ifdef COLOR_TEXTURE
varying vec2 v_vec2_texcoord_color;
#endif
#ifdef AO_TEXTURE
varying vec2 v_vec2_texcoord_ao;
#endif
#ifdef PBR_TEXTURE
varying vec2 v_vec2_texcoord_pbr;
#endif
varying float v_float_opacity;
void main()
{
    if (check_dem_invalid() != 0) {
        discard;
    }
    vec4 color = u_vec4_color;
    #ifdef COLOR_TEXTURE
        color *= texture2D(u_sr2d_texture_0, v_vec2_texcoord_color);
    #endif
    #ifdef MAP_MESH_TEXTURE
        
        vec2 coord = v_tex_coord.xy / v_tex_coord.w;
        
        coord = coord / u_vec2_tex_scale;
        
        coord.y += u_float_tex_shift_scale / u_vec2_tex_scale.y;
        
        coord = (coord / 2.) + vec2(0.5, 0.5);
        vec4 texture_color = texture2D(u_sampler_map_tex, coord);
        
        color.rgb = mix(color.rgb, texture_color.rgb, texture_color.a);
    #endif
    #ifdef AO_TEXTURE
        
        
        vec4 ao_tex_color = texture2D(u_ao_texture, v_vec2_texcoord_ao);
        color *= ao_tex_color;
    #endif
    vec3 fragment_normal = normalize(v_vec3_normal);
    color *= v_float_opacity;
    bool use_light = UNPACK_BOOL1(u_int_light_flags);
    if (!use_light) {
        apply_screendoor();
        gl_FragColor = apply_fog(apply_color_effect(color));
        return;
    }
    bool skip_screendoor = false;
    #ifdef LIGHT_MODEL
        float metallic = max(u_float_metallic, 0.1);
        float roughness = max(u_float_roughness, 0.1);
        #ifndef METALLIC_ROUGHNESS_DEBUG
            #ifdef PBR_TEXTURE
                vec4 pbr_tex_color = texture2D(u_pbr_texture, v_vec2_texcoord_pbr);
                roughness = max(pbr_tex_color.g, 0.1);
                metallic = max(pbr_tex_color.b, 0.1);
            #endif
        #endif
        #if (LIGHT_MODEL == LIGHT_MODEL_PBR)
            color.rgb = color_pbr(fragment_normal, v_vec3_fragment_pos_world, color.rgb, roughness, metallic);
        #elif (LIGHT_MODEL == LIGHT_MODEL_PHONG)
            #if defined(ALPHA_MODE) && ALPHA_MODE == ALPHA_MODE_OPAQUE
                
                
                
                
                color.rgb = color_phong(fragment_normal, v_vec3_fragment_pos_world, color.rgb, roughness, metallic, color.a);
                if (color.a == 0.0) {
                    skip_screendoor = true;
                }
            #else
                color.rgb = color_phong(fragment_normal, v_vec3_fragment_pos_world, color.rgb, roughness, metallic, 1.0);
            #endif
        #endif
    #endif
    if (!skip_screendoor){
        apply_screendoor();
    }
    gl_FragColor = apply_fog(apply_color_effect(color));
}
`,tS=`#include <enable_standard_derivatives>
#include <highp_float>
#include <prelude>
#include <cam_pos>
#include <fog>
#include <screendoor_transparency>
#include <fragment_normal>
#include <bit_mask>
#include <pack_depth>
#include <shadow>
#include <light>
#include <dem>
#include <apply_color_effect>
varying mat4 v_mat4_gradient;
varying vec4 v_vec4_color;
varying vec4 v_vec4_rotated_scaled_vertex;
uniform vec2 u_vec2_floor_level;
void main()
{
    if (check_dem_invalid() != 0) {
        discard;
    }
    apply_screendoor();
    vec4 color = v_vec4_color;
    if (v_mat4_gradient[0][0] != 0.) {
        float height_gradient = v_vec4_rotated_scaled_vertex.w;
        float gradient_position = (float(u_vec2_floor_level.x) + height_gradient) / float(u_vec2_floor_level.y);
        color = mix(v_mat4_gradient[1], v_mat4_gradient[2], smoothstep(v_mat4_gradient[0][1], v_mat4_gradient[0][2], gradient_position));
    }
    vec3 normal = calc_fragment_normal(v_vec4_rotated_scaled_vertex.xyz);
    color *= light_factor(normal);
    gl_FragColor = apply_fog(apply_color_effect(color));
# ifndef BLEND
    
    gl_FragColor /= gl_FragColor.a;
# endif
}
`,iS=`#include <mediump_float>
#include <prelude>
#include <fog>
uniform highp float u_float_intensity;
varying float v_float_weight;
varying vec2 v_vec2_extrude;
#define GAUSS_COEF 0.3989422804014327
void main() {
    float d = -0.5 * 3.0 * 3.0 * dot(v_vec2_extrude, v_vec2_extrude);
    float val = v_float_weight * u_float_intensity * GAUSS_COEF * exp(d);
    float fog_alpha = apply_fog_alpha(vec4(1)).r;
    gl_FragColor = vec4(val, fog_alpha, 1.0, 1.0);
}
`,nS=`#include <mediump_float>
#include <prelude>
#include <cam_pos>
uniform sampler2D u_sr2d_texture;
uniform sampler2D u_sr2d_ramp_texture;
uniform float u_float_opacity;
varying vec2 v_vec2_position;
void main() {
    vec2 color_and_alpha = texture2D(u_sr2d_texture, v_vec2_position).rg;
    vec4 color = texture2D(u_sr2d_ramp_texture, vec2(color_and_alpha.r, 0.5));
    gl_FragColor = color * u_float_opacity;
    
    
    #ifdef FOG
        gl_FragColor *= color_and_alpha.g;
    #endif
}
`,rS=`#include <highp_float>
#include <prelude>
#include <cam_pos>
#include <dem>
uniform mediump int u_int_identify;
varying vec4 v_vec4_identifier;
void main()
{
    if (check_dem_invalid() != 0) {
        discard;
    }
    if (u_int_identify != 0) {
        gl_FragColor = v_vec4_identifier;
    } else {
        gl_FragColor = vec4(0., 0., 0., 0.);
    }
}
`,sS=`#include <mediump_float>
#include <prelude>
#include <apply_opacity>
#include <fog>
#include <dem>
uniform sampler2D u_sr2d_texture;
uniform float u_float_buffer;
uniform float u_float_gamma;
uniform vec4 u_vec4_color;
uniform vec4 u_vec4_hidden_color;
uniform float u_float_opacity;
uniform sampler2D u_color_text_sprite_labeling;
uniform float u_float_label_index;
varying vec2 v_vec2_texcoord;
varying float v_float_behind_factor;
varying vec4 v_vec4_text_identifier;
varying vec2 v_vec2_labeling_texcoord;
const float F16_EPSILON = 0.0009765625;
void main() {
    if (check_dem_invalid() != 0) {
discard;
}
    float dist = texture2D(u_sr2d_texture, v_vec2_texcoord).a;
    float alpha = smoothstep(
        u_float_buffer - u_float_gamma,
        u_float_buffer + u_float_gamma,
        dist
    );
    vec4 color = mix(u_vec4_hidden_color, u_vec4_color, v_float_behind_factor);
    color = apply_fog_alpha(color);
    vec4 clearColor = vec4(1, 1, 1, 1);
    vec4 text_sprite_color = texture2D(u_color_text_sprite_labeling, v_vec2_labeling_texcoord);
    bvec4 clearColorDiff = bvec4(
        abs(text_sprite_color.r - clearColor.r) > F16_EPSILON,
        abs(text_sprite_color.g - clearColor.g) > F16_EPSILON,
        abs(text_sprite_color.b - clearColor.b) > F16_EPSILON,
        abs(text_sprite_color.a - clearColor.a) > F16_EPSILON
    );
    bvec4 identifierDiff = bvec4(
        abs(text_sprite_color.r - v_vec4_text_identifier.r) > F16_EPSILON,
        abs(text_sprite_color.g - v_vec4_text_identifier.g) > F16_EPSILON,
        abs(text_sprite_color.b - v_vec4_text_identifier.b) > F16_EPSILON,
        abs(text_sprite_color.a - v_vec4_text_identifier.a) > F16_EPSILON
    );
    if (u_float_label_index < F16_EPSILON && any(identifierDiff)  && any(clearColorDiff) ) {
        discard;
    }
    gl_FragColor = apply_opacity(color * alpha, u_float_opacity);
}
`,oS=`#include <highp_float>
#include <prelude>
#include <apply_opacity>
#include <fog>
uniform sampler2D u_sr2d_texture;
uniform float u_float_buffer;
uniform float u_float_gamma;
uniform vec4 u_vec4_color;
uniform float u_float_opacity;
varying vec2 v_vec2_texcoord;
void main() {
    float dist = texture2D(u_sr2d_texture, v_vec2_texcoord).a;
    float alpha = smoothstep(
        u_float_buffer - u_float_gamma,
        u_float_buffer + u_float_gamma,
        dist
    );
    vec4 color = apply_fog_alpha(u_vec4_color);
    gl_FragColor = apply_opacity(color * alpha, u_float_opacity);
}
`,aS=`#include <highp_float>
#include <prelude>
#include <apply_opacity>
#include <fog>
uniform int u_int_depth_test;
uniform sampler2D u_sr2d_texture;
uniform float u_float_buffer;
uniform float u_float_gamma;
uniform vec4 u_vec4_color;
uniform vec4 u_vec4_hidden_color;
uniform float u_float_opacity;
varying float v_float_behind_factor;
varying vec4 v_vec4_identifier;
varying vec2 v_vec2_texcoord;
varying float v_float_perspective_scale;
void main() {
    if (u_int_depth_test != 0) {
        gl_FragColor = v_vec4_identifier;
        return;
    }
    
    
    
    float gamma = u_float_gamma / v_float_perspective_scale;
    float dist = texture2D(u_sr2d_texture, v_vec2_texcoord).a;
    float alpha = smoothstep(
        u_float_buffer - gamma,
        u_float_buffer + gamma,
        dist
    );
    vec4 color = apply_fog_alpha(mix(u_vec4_hidden_color, u_vec4_color, v_float_behind_factor));
    gl_FragColor = apply_opacity(color * alpha, u_float_opacity);
}
`,lS=`#include <mediump_float>
#include <prelude>
#include <cam_pos>
#include <fog>
#include <bit_mask>
#include <pack_depth>
#include <shadow>
#include <light>
#include <dem>
#include <apply_color_effect>
varying vec4 v_vec4_color;
varying mat4 v_mat4_gradient;
varying vec3 v_vec3_normal;
varying vec2 v_vec2_height_gradient;
uniform mat4 u_mat4_gradient;
void main()
{
    if (check_dem_invalid() != 0) {
        discard;
    }
    vec4 color = v_vec4_color;
    if (u_mat4_gradient[0][0] != 0.) {
        color = mix(v_mat4_gradient[1], v_mat4_gradient[2], smoothstep(v_mat4_gradient[0][1], v_mat4_gradient[0][2], v_vec2_height_gradient[0]));
    }
    color *= (1. - abs(v_vec2_height_gradient[1] * gl_FragCoord.w));
    gl_FragColor = apply_fog(apply_color_effect(color * light_factor(v_vec3_normal)));
}
`,cS=`#include <highp_float>
#include <prelude>
#include <pack_depth>
#include <dem>
varying float v_depth_metric;
void main()
{
if (check_dem_invalid() != 0) {
discard;
}
#ifdef DEPTH_TEXTURE_SHADOW
return;
#endif
gl_FragColor = pack_float_to_vec4(v_depth_metric);
}`,dS=`#include <highp_float>
#include <prelude>
#include <cam_pos>
#include <fog>
#include <screendoor_transparency>
#include <bit_mask>
#include <pack_depth>
#include <shadow>
#include <light>
#include <dem>
uniform sampler2D u_sampler_map_tex;
uniform vec2 u_vec2_tex_scale;
uniform float u_float_tex_shift_scale;
uniform mediump float u_float_light_intensity;
uniform int u_int_identify;
uniform int u_int_depth_test;
varying vec4 v_tex_coord;
varying vec4 v_vec4_normal_gradient;
varying vec4 v_vec4_identifier;
void main()
{
if (check_dem_invalid() != 0) {
        discard;
    }
if (u_int_depth_test != 0) {
gl_FragColor = v_vec4_identifier;
return;
}
vec2 coord = v_tex_coord.xy / v_tex_coord.w;
coord = coord / u_vec2_tex_scale;
coord.y += u_float_tex_shift_scale / u_vec2_tex_scale.y;
coord = (coord / 2.) + vec2(0.5, 0.5);
if (coord.x < 0. || coord.x > 1. || coord.y < 0. || coord.y > 1.) {
gl_FragColor = vec4(0, 0, 0, 0);
} else {
gl_FragColor = texture2D(u_sampler_map_tex, coord);
if (u_int_identify == 0) {
apply_screendoor();
gl_FragColor.rgb *= 1. - u_float_light_intensity * smoothstep(0.85, 1., abs(v_vec4_normal_gradient.w));
gl_FragColor *= light_factor(v_vec4_normal_gradient.xyz);
gl_FragColor = apply_fog(gl_FragColor);
}
}
}
`,uS=`#include <highp_float>
#include <prelude>
#include <cam_pos>
#include <apply_opacity>
#include <fog>
#include <screendoor_transparency>
#include <bit_mask>
#include <pack_depth>
#include <shadow>
#include <light>
#include <dem>
uniform sampler2D u_sr2d_texture;
uniform float u_float_texture_opacity;
uniform vec4 u_float_sprite_texture_coords;
uniform lowp int u_int_is_textured;
uniform mediump vec4 u_vec4_color;
uniform mediump mat4 u_mat4_gradient;
uniform mediump float u_float_opacity;
uniform mediump int u_int_identify;
varying vec4 v_vec4_color;
varying mat4 v_mat4_gradient;
varying vec2 v_vec2_tex_coord;
varying vec4 v_vec4_normal_gradient;
varying vec4 v_vec4_identifier;
void main()
{   
    if (check_dem_invalid() != 0) {
        discard;
    }
    if (u_int_identify != 0) {
        gl_FragColor = v_vec4_identifier;
    } else {
        apply_screendoor();
        vec4 light = light_factor(v_vec4_normal_gradient.xyz);
        if (u_int_is_textured != 0)  {
            vec2 spritecoord = mix(u_float_sprite_texture_coords.xy, u_float_sprite_texture_coords.zw, fract(v_vec2_tex_coord));
            vec4 color = texture2D(u_sr2d_texture, spritecoord);
            vec4 texcolor = apply_opacity(color, u_float_texture_opacity);
            gl_FragColor = texcolor + v_vec4_color * (1. - texcolor.a);
        } else if (u_mat4_gradient[0][0] != 0.) {
    gl_FragColor = mix(v_mat4_gradient[1], v_mat4_gradient[2], smoothstep(v_mat4_gradient[0][1], v_mat4_gradient[0][2], v_vec4_normal_gradient.w));
        } else {
            gl_FragColor = v_vec4_color;
        }
        gl_FragColor = apply_fog(gl_FragColor * light);
    }
}
`,hS=`#include <mediump_float>
#include <prelude>
#include <cam_pos>
#include <apply_opacity>
#include <fog>
#include <bit_mask>
#include <pack_depth>
#include <shadow>
#include <light>
uniform vec4 u_vec4_color;
uniform sampler2D u_sr2d_texture;
uniform vec4 u_float_sprite_texture_coords;
varying vec2 v_vec2_texcoord;
void main()
{
    vec2 spritecoord = mix(u_float_sprite_texture_coords.xy, u_float_sprite_texture_coords.zw, v_vec2_texcoord);
    vec4 color = texture2D(u_sr2d_texture, spritecoord) * u_vec4_color;
    gl_FragColor = apply_fog(color * light_factor_surface());
}
`,_S=`#include <enable_standard_derivatives>
#include <highp_float>
#include <prelude>
#include <affine_step>
#include <apply_opacity>
#include <signed_distance_functions>
#include <arrow_functions>
#include <fog>
#ifndef UBO
uniform mediump vec2 u_vec2_vpt_size;
#endif
uniform vec2 u_vec2_wing_normal;
uniform vec2 u_vec2_tip_normal;
uniform mediump float u_float_width;
uniform mediump float u_float_length;
uniform float u_float_tip_height_multiplier;
uniform float u_float_wing_height_multiplier;
varying vec4 v_vec4_color;
varying vec2 v_vec2_texcoord;
varying float v_float_border_width;
varying float v_float_zpt_to_texcoord_factor;
varying float v_float_outer_width;
varying float v_float_opacity;
float one_way_line_distance(const ArrowDistances ad)
{
    return max(max(max(ad.top_tip_cut, ad.bottom_tip_cut), max(ad.top_left_wing, ad.top_right_wing)), min(ad.line, min(ad.bottom_left_wing, ad.bottom_right_wing)));
}
void main()
{
    mat2 derivatives = mat2(dFdx(v_vec2_texcoord), dFdy(v_vec2_texcoord));
    ArrowDistanceParameters arrow_parameters = calculate_arrow_distance_parameters(
        u_vec2_wing_normal,
        u_vec2_tip_normal,
        u_float_width * v_float_zpt_to_texcoord_factor,
        u_float_length * v_float_zpt_to_texcoord_factor,
        u_float_tip_height_multiplier,
        u_float_wing_height_multiplier,
        0.,
        0.,
        0.,
        vec2(0., 0.),
        vec2(0., 0.));
    
    float border_clipping = (abs(v_vec2_texcoord.y) - v_float_outer_width) / max(abs(derivatives[0].y), abs(derivatives[1].y));
    float fill_factor = affine_step(-1., 0., one_way_line_distance(calculate_arrow_distances(arrow_parameters, v_vec2_texcoord, 0., derivatives)));
    float border_factor = max(border_clipping, affine_step(0., 1., one_way_line_distance(calculate_arrow_distances(arrow_parameters, v_vec2_texcoord, v_float_border_width, derivatives))));
    gl_FragColor = apply_opacity(mix(mix(v_vec4_color, vec4(0.), fill_factor), vec4(0.), border_factor), v_float_opacity);
}
`,fS=`#include <enable_standard_derivatives>
#include <highp_float>
#include <prelude>
#include <affine_step>
#include <apply_opacity>
#include <signed_distance_functions>
#include <arrow_functions>
#include <fog>
#ifndef UBO
uniform mediump vec2 u_vec2_vpt_size;
#endif
uniform vec2 u_vec2_wing_normal;
uniform vec2 u_vec2_tip_normal;
uniform mediump float u_float_width;
uniform mediump float u_float_length;
uniform float u_float_tip_height_multiplier;
uniform float u_float_wing_height_multiplier;
uniform int u_int_depth_test;
varying vec4 v_vec4_color;
varying vec4 v_vec4_hidden_color;
varying vec2 v_vec2_texcoord;
varying vec4 v_vec4_identifier;
varying float v_float_behind_factor;
varying vec4 v_vec4_params;
float one_way_line_distance(const ArrowDistances ad)
{
    return max(max(max(ad.top_tip_cut, ad.bottom_tip_cut), max(ad.top_left_wing, ad.top_right_wing)), min(ad.line, min(ad.bottom_left_wing, ad.bottom_right_wing)));
}
void main()
{
    if (u_int_depth_test == 1) {
        gl_FragColor = v_vec4_identifier;
        return;
    }
    float border_width = v_vec4_params.x;
    float zpt_to_texcoord_factor = v_vec4_params.y;
    float outer_width = v_vec4_params.z;
    float opacity = v_vec4_params.w;
    mat2 derivatives = mat2(dFdx(v_vec2_texcoord), dFdy(v_vec2_texcoord));
    ArrowDistanceParameters arrow_parameters = calculate_arrow_distance_parameters(
        u_vec2_wing_normal,
        u_vec2_tip_normal,
        u_float_width * zpt_to_texcoord_factor,
        u_float_length * zpt_to_texcoord_factor,
        u_float_tip_height_multiplier,
        u_float_wing_height_multiplier,
        0.,
        0.,
        0.,
        vec2(0., 0.),
        vec2(0., 0.));
    
    float border_clipping = (abs(v_vec2_texcoord.y) - outer_width) / max(abs(derivatives[0].y), abs(derivatives[1].y));
    float fill_factor = affine_step(-1., 0., one_way_line_distance(calculate_arrow_distances(arrow_parameters, v_vec2_texcoord, 0., derivatives)));
    float border_factor = max(border_clipping, affine_step(0., 1., one_way_line_distance(calculate_arrow_distances(arrow_parameters, v_vec2_texcoord, border_width, derivatives))));
    vec4 color = apply_fog_alpha(mix(mix(mix(v_vec4_hidden_color, v_vec4_color, v_float_behind_factor), vec4(0.), fill_factor), vec4(0.), border_factor));
    gl_FragColor = apply_opacity(color, opacity);
}
`,mS=`#include <mediump_float>
#include <prelude>
varying vec4 v_color;
varying vec2 v_uv;
varying float v_stretch;
uniform sampler2D u_texture;
uniform float u_useTexture;
uniform float u_softness;
float hash(vec2 p) {
    return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453);
}
float noise(vec2 p) {
    vec2 i = floor(p);
    vec2 f = fract(p);
    f = f * f * (3.0 - 2.0 * f);
    float a = hash(i);
    float b = hash(i + vec2(1.0, 0.0));
    float c = hash(i + vec2(0.0, 1.0));
    float d = hash(i + vec2(1.0, 1.0));
    return mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
}
float fbm(vec2 p) {
    float v = 0.0;
    v += 0.5 * noise(p); p *= 2.01;
    v += 0.25 * noise(p); p *= 2.02;
    v += 0.125 * noise(p); p *= 2.03;
    v += 0.0625 * noise(p);
    return v;
}
void main() {
    float alpha;
    if (v_stretch < 0.5) {
        float dist = length(v_uv - 0.5) * 2.0;
        if (u_softness < 0.01) {
            alpha = 1.0 - smoothstep(0.0, 1.0, dist);
        } else {
            float gauss = exp(-dist * dist * 2.0);
            float n = fbm(v_uv * 5.0 + v_color.rg * 7.0);
            float edgeNoise = mix(1.0, n, u_softness * 0.45);
            alpha = gauss * edgeNoise;
            alpha *= smoothstep(1.0, 0.7, dist);
        }
    } else {
        float dx = abs(v_uv.x - 0.5) * 2.0;
        float dy = abs(v_uv.y - 0.5) * 2.0;
        alpha = (1.0 - smoothstep(0.75, 1.0, dx)) * (1.0 - smoothstep(0.5, 1.0, dy));
    }
    vec4 texColor = mix(vec4(1.0), texture2D(u_texture, v_uv), u_useTexture);
    float finalAlpha = v_color.a * texColor.a * mix(alpha, 1.0, u_useTexture);
    if (finalAlpha < 0.001) discard;
    gl_FragColor = vec4(v_color.rgb * texColor.rgb * finalAlpha, finalAlpha);
}`,vS=`#include <highp_float>
#include <prelude>
#include <cam_pos>
#include <affine_step>
#include <fog>
#include <bit_mask>
#include <pack_depth>
#include <shadow>
#include <light>
#include <signed_distance_functions>
uniform int u_int_pattern_type;
varying vec4 v_vec4_color;
varying vec2 v_vec2_uv;
varying float v_float_width;
varying vec4 v_vec4_pattern_parameters;
void main()
{
    float pattern_length = v_vec4_pattern_parameters.x;
    float full_width = v_float_width + 1.;
    
    float smooth_base = max(15., max(v_float_width, pattern_length));
    float smooth_scale = (smooth_base + 1.) / smooth_base;
    float smooth_factor = smooth_scale - 1.;
    
    vec2 sdf_pos = vec2(mod(v_vec2_uv.x, 1.) - 0.5, v_vec2_uv.y * smooth_scale);
float sdf = 1.;
    
    if (u_int_pattern_type < 4) {
        
        float width = v_vec4_pattern_parameters.y;
        float left  = v_vec4_pattern_parameters.z;
        float right = v_vec4_pattern_parameters.w;
        
        
        vec2 offset;
        if (right < 0.) {
            offset = vec2(.25, .5);
        } else {
            offset = vec2(.0, .5);
        }
        
        if (width > EPSILON) {
            float leftSdf = 1.;
            if (left > EPSILON) {
                leftSdf = sdf_box(sdf_pos + offset, vec2(left, width));
            }
            float rightSdf = 1.;
            if (abs(right) > EPSILON) {
                rightSdf = sdf_box(sdf_pos - offset, vec2(abs(right), width));
            }
            sdf = min(leftSdf, rightSdf);
        }
    } else if (u_int_pattern_type == 5) {
        
        float radius = v_vec4_pattern_parameters.y;
        
        if (radius > EPSILON) {
            sdf = sdf_circle(sdf_pos, radius);
        }
    } else if (u_int_pattern_type == 4) {
        
        float width = v_vec4_pattern_parameters.y;
        float orientation = v_vec4_pattern_parameters.z;
        
        if (width > EPSILON) {
            sdf = sdf_triangle(sdf_pos * vec2(1., orientation), width);
        }
    } else if (u_int_pattern_type == 6) {
        
        sdf = sdf_chevron(sdf_pos.yx, 0., 0., 0.);
    }
    
    sdf = max(sdf, abs(sdf_pos.y) - 0.5);
    
    vec4 color = mix(
        v_vec4_color,
        vec4(0.),
        affine_step(-smooth_factor, smooth_factor, sdf)
    );
    color *= light_factor_surface();
    gl_FragColor = apply_fog(color);
}
`,gS=`#include <mediump_float>
#include <prelude>
#include <apply_opacity>
#include <fog>
#include <dem>
uniform sampler2D u_sr2d_texture;
uniform vec2 u_vec2_opacity;
varying vec2 v_vec2_texcoord;
varying float v_float_behind_factor;
void main()
{
    if (check_dem_invalid() != 0) {
        discard;
    }
    vec4 color = texture2D(u_sr2d_texture, v_vec2_texcoord);
    float opacity = mix(u_vec2_opacity[1], u_vec2_opacity[0], v_float_behind_factor);
    color = apply_fog_alpha(color);
    gl_FragColor = apply_opacity(color, opacity);
}
`,pS=`#include <mediump_float>
#include <prelude>
#include <dem>
uniform sampler2D u_sr2d_texture;
uniform float u_float_identify_opacity;
varying vec2 v_vec2_texcoord;
varying vec4 v_vec4_identifier;
void main()
{
    if (check_dem_invalid() != 0) {
        discard;
    }
    vec4 color = texture2D(u_sr2d_texture, v_vec2_texcoord);
    
    
    if (color.a < u_float_identify_opacity) {
        discard;
    } else {
        gl_FragColor = v_vec4_identifier;
    }
}
`,xS=`#include <mediump_float>
#include <prelude>
#include <apply_opacity>
#include <fog>
uniform sampler2D u_sr2d_texture;
uniform float u_float_opacity;
varying vec2 v_vec2_texcoord;
void main()
{
    vec4 color = texture2D(u_sr2d_texture, v_vec2_texcoord);
    color = apply_fog_alpha(color);
    gl_FragColor = apply_opacity(color, u_float_opacity);
}
`,bS=`#include <enable_standard_derivatives>
#include <highp_float>
#include <prelude>
#include <cam_pos>
#include <affine_step>
#include <fog>
#include <bit_mask>
#include <pack_depth>
#include <shadow>
#include <light>
uniform vec4 u_vec4_color;
varying vec2 v_vec2_normal;
varying float v_float_half_width;
void main()
{
    
    float opacity = 1.0 - affine_step(
        v_float_half_width - length(fwidth(v_vec2_normal)),
        v_float_half_width,
        length(v_vec2_normal)
    );
    vec4 color = light_factor_surface() * u_vec4_color;
    color = apply_fog(color);
    gl_FragColor = color * opacity;
}
`,SS=`#include <enable_standard_derivatives>
#include <lowp_float>
#include <prelude>
varying vec4 v_vec4_identifier;
varying vec2 v_vec2_normal;
varying float v_float_half_width;
void main()
{
    if (dot(v_vec2_normal, v_vec2_normal) > v_float_half_width * v_float_half_width) {
        discard;
    }
    gl_FragColor = v_vec4_identifier;
}
`,yS=`#include <lowp_float>
#include <prelude>
#include <cam_pos>
#include <fog>
#include <bit_mask>
#include <pack_depth>
#include <shadow>
#include <light>
#include <apply_color_effect>
uniform vec4 u_vec4_color;
varying float v_float_distance;
varying float v_float_distance_offset;
void main()
{
    vec4 light = light_factor_surface();
    vec4 color = apply_color_effect(u_vec4_color) * clamp(
        1. + v_float_distance_offset - abs(v_float_distance * gl_FragCoord.w),
        0.,
        1.) * light;
    gl_FragColor = apply_fog(color);
}
`,TS=`#include <lowp_float>
#include <prelude>
#include <cam_pos>
#include <fog>
#include <bit_mask>
#include <pack_depth>
#include <shadow>
#include <light>
#include <dem>
#include <apply_color_effect>
varying vec4 v_vec4_color;
varying float v_float_distance;
varying float v_float_distance_offset;
void main()
{
    if (check_dem_invalid() != 0) {
        discard;
    }
    vec4 light = light_factor_surface();
    vec4 color = apply_color_effect(v_vec4_color) * clamp(
        1. + v_float_distance_offset - abs(v_float_distance * gl_FragCoord.w),
        0.,
        1.) * light;
    gl_FragColor = apply_fog(color);
}
`,ES=`#include <highp_float>
#include <prelude>
#include <enable_standard_derivatives>
varying vec3 v_position;
void main() {
    vec3 dx = dFdx(v_position);
    vec3 dy = dFdy(v_position);
    vec3 normal = normalize(cross(dx, dy));
    vec3 lightDir = normalize(vec3(1.0, 1.0, 1.0));
    float diffuse = max(dot(normal, lightDir), 0.0);
    
    gl_FragColor = vec4(normal * (0.2 + 0.8 * diffuse), 1.0);
}
`,CS=`#include <mediump_float>
#include <prelude>
#include <fog>
#define SKY_ALPHA_HORIZON_BLEND (6.0)
#define DEFAULT_SKY_COLOR (vec4(0.0))
vec4 add_sky_alpha_blend(vec4 color) {
#ifdef SKY
    
    float depth = length(v_fog_pos);
    vec3 dir = v_fog_pos / depth;
    float alpha_dir = dir.z + u_fog_horizon_pad; 
    float alpha = clamp(1.0 + SKY_ALPHA_HORIZON_BLEND * alpha_dir, 0.0, 1.0);
    color *= alpha;
#endif
    return color;
}
void main() {
#ifdef SKY
    vec4 color = add_sky_alpha_blend(u_sky_color);
#else
    vec4 color = DEFAULT_SKY_COLOR;
#endif
    gl_FragColor = apply_fog_sky(color);
}
`,IS=`#include <mediump_float>
#include <prelude>
#ifndef UBO
uniform vec2 u_vec2_vpt_size;
#endif
#define resolution (1.0 / u_vec2_vpt_size)
uniform sampler2D u_texture;     
uniform sampler2D u_weightsTex;  
varying vec2 v_vec2_texcoord;
vec4 SMAANeighborhoodBlendingPS( vec2 texcoord, vec4 offset[ 2 ], sampler2D colorTex, sampler2D blendTex ) {
    
    vec4 a;
    a.xz = texture2D( blendTex, texcoord ).xz;
    a.y = texture2D( blendTex, offset[ 1 ].zw ).g;
    a.w = texture2D( blendTex, offset[ 1 ].xy ).a;
    
    if ( dot(a, vec4( 1.0, 1.0, 1.0, 1.0 )) < 1e-5 ) {
        return texture2D( colorTex, texcoord, 0.0 );
    } else {
        
        
        
        vec2 offset;
        offset.x = a.a > a.b ? a.a : -a.b; 
        offset.y = a.g > a.r ? -a.g : a.r; 
        
        if ( abs( offset.x ) > abs( offset.y )) { 
            offset.y = 0.0;
        } else {
            offset.x = 0.0;
        }
        
        vec4 C = texture2D( colorTex, texcoord, 0.0 );
        texcoord += sign( offset ) * resolution;
        vec4 Cop = texture2D( colorTex, texcoord, 0.0 );
        float s = abs( offset.x ) > abs( offset.y ) ? abs( offset.x ) : abs( offset.y );
        
        C.xyz = pow(C.xyz, vec3(2.2));
        Cop.xyz = pow(Cop.xyz, vec3(2.2));
        vec4 mixed = mix(C, Cop, s);
        mixed.xyz = pow(mixed.xyz, vec3(1.0 / 2.2));
        return mixed;
    }
}
void main() {
    vec4 offset[ 2 ];
    offset[ 0 ] = v_vec2_texcoord.xyxy + resolution.xyxy * vec4( -1.0, 0.0, 0.0, 1.0 ); 
    offset[ 1 ] = v_vec2_texcoord.xyxy + resolution.xyxy * vec4( 1.0, 0.0, 0.0, -1.0 ); 
    gl_FragColor = SMAANeighborhoodBlendingPS( v_vec2_texcoord, offset, u_texture, u_weightsTex );
}`,PS=`precision highp float;
#include <prelude>
#ifndef UBO
uniform vec2 u_vec2_vpt_size;
#endif
varying vec2 v_vec2_texcoord;
#define mad(a, b, c) (a * b + c)
#define SMAA_EDGES_COLOR
#define SMAA_PRESET_ULTRA
#if defined(SMAA_PRESET_LOW)
#define SMAA_THRESHOLD 0.15
#define SMAA_MAX_SEARCH_STEPS 4
#define SMAA_DISABLE_DIAG_DETECTION
#define SMAA_DISABLE_CORNER_DETECTION
#elif defined(SMAA_PRESET_MEDIUM)
#define SMAA_THRESHOLD 0.1
#define SMAA_MAX_SEARCH_STEPS 8
#define SMAA_DISABLE_DIAG_DETECTION
#define SMAA_DISABLE_CORNER_DETECTION
#elif defined(SMAA_PRESET_HIGH)
#define SMAA_THRESHOLD 0.1
#define SMAA_MAX_SEARCH_STEPS 16
#define SMAA_MAX_SEARCH_STEPS_DIAG 8
#define SMAA_CORNER_ROUNDING 25
#elif defined(SMAA_PRESET_ULTRA)
#define SMAA_THRESHOLD 0.05
#define SMAA_MAX_SEARCH_STEPS 32
#define SMAA_MAX_SEARCH_STEPS_DIAG 16
#define SMAA_CORNER_ROUNDING 25
#endif
#ifndef SMAA_THRESHOLD
  #define SMAA_THRESHOLD 0.1
#endif
#ifndef SMAA_PREDICATION
  #define SMAA_PREDICATION 0
#endif
#ifndef SMAA_PREDICATION_THRESHOLD
  #define SMAA_PREDICATION_THRESHOLD 0.01
#endif
#ifndef SMAA_PREDICATION_SCALE
  #define SMAA_PREDICATION_SCALE 2.0
#endif
#ifndef SMAA_PREDICATION_STRENGTH
  #define SMAA_PREDICATION_STRENGTH 0.4
#endif
#if defined(SMAA_EDGES_DEPTH) || SMAA_PREDICATION
  uniform sampler2D uDepthTexture;
#endif
#ifdef SMAA_EDGES_DEPTH
  #ifndef SMAA_DEPTH_THRESHOLD
    #define SMAA_DEPTH_THRESHOLD (0.1 * SMAA_THRESHOLD)
  #endif
#else
  #ifndef SMAA_LOCAL_CONTRAST_ADAPTATION_FACTOR
    #define SMAA_LOCAL_CONTRAST_ADAPTATION_FACTOR 2.0
  #endif
  uniform sampler2D u_texture;
#endif
#if defined(SMAA_EDGES_DEPTH) || SMAA_PREDICATION
  
  vec3 SMAAGatherNeighbours(vec2 texcoord, vec4 offset[3], sampler2D tex) {
    float P = texture2D(tex, texcoord).r;
    float Pleft = texture2D(tex, offset[0].xy).r;
    float Ptop  = texture2D(tex, offset[0].zw).r;
    return vec3(P, Pleft, Ptop);
  }
#endif
#if SMAA_PREDICATION
  vec2 SMAACalculatePredicatedThreshold(vec2 texcoord, vec4 offset[3], sampler2D predicationTex) {
    vec3 neighbours = SMAAGatherNeighbours(texcoord, offset, predicationTex);
    vec2 delta = abs(neighbours.xx - neighbours.yz);
    vec2 edges = step(SMAA_PREDICATION_THRESHOLD, delta);
    return SMAA_PREDICATION_SCALE * SMAA_THRESHOLD * (1.0 - SMAA_PREDICATION_STRENGTH * edges);
  }
#endif
#ifdef SMAA_EDGES_DEPTH
  vec2 SMAADepthEdgeDetection(vec2 texcoord, vec4 offset[3], sampler2D depthTex) {
    vec3 neighbours = SMAAGatherNeighbours(texcoord, offset, depthTex);
    vec2 delta = abs(neighbours.xx - vec2(neighbours.y, neighbours.z));
    vec2 edges = step(SMAA_DEPTH_THRESHOLD, delta);
    if (dot(edges, vec2(1.0, 1.0)) == 0.0)
        discard;
    return edges;
  }
#endif
#ifdef SMAA_EDGES_LUMA
  vec2 SMAALumaEdgeDetection(vec2 texcoord, vec4 offset[3], sampler2D colorTex
  #if SMAA_PREDICATION
  , sampler2D predicationTex
  #endif
  ) {
    #if SMAA_PREDICATION
    vec2 threshold = SMAACalculatePredicatedThreshold(texcoord, offset, predicationTex);
    #else
    vec2 threshold = vec2(SMAA_THRESHOLD);
    #endif
    
    vec3 weights = vec3(0.2126, 0.7152, 0.0722);
    float L = dot(texture2D(colorTex, texcoord).rgb, weights);
    float Lleft = dot(texture2D(colorTex, offset[0].xy).rgb, weights);
    float Ltop  = dot(texture2D(colorTex, offset[0].zw).rgb, weights);
    
    vec4 delta;
    delta.xy = abs(L - vec2(Lleft, Ltop));
    vec2 edges = step(threshold, delta.xy);
    
    if (dot(edges, vec2(1.0, 1.0)) == 0.0)
        discard;
    
    float Lright = dot(texture2D(colorTex, offset[1].xy).rgb, weights);
    float Lbottom  = dot(texture2D(colorTex, offset[1].zw).rgb, weights);
    delta.zw = abs(L - vec2(Lright, Lbottom));
    
    vec2 maxDelta = max(delta.xy, delta.zw);
    
    float Lleftleft = dot(texture2D(colorTex, offset[2].xy).rgb, weights);
    float Ltoptop = dot(texture2D(colorTex, offset[2].zw).rgb, weights);
    delta.zw = abs(vec2(Lleft, Ltop) - vec2(Lleftleft, Ltoptop));
    
    maxDelta = max(maxDelta.xy, delta.zw);
    float finalDelta = max(maxDelta.x, maxDelta.y);
    
    edges.xy *= step(finalDelta, SMAA_LOCAL_CONTRAST_ADAPTATION_FACTOR * delta.xy);
    return edges;
  }
#endif
#ifdef SMAA_EDGES_COLOR
  vec2 SMAAColorEdgeDetection(vec2 texcoord, vec4 offset[3], sampler2D colorTex
  #if SMAA_PREDICATION
  , sampler2D predicationTex
  #endif
  ) {
    
    #if SMAA_PREDICATION
    vec2 threshold = SMAACalculatePredicatedThreshold(texcoord, offset, predicationTex);
    #else
    vec2 threshold = vec2(SMAA_THRESHOLD);
    #endif
    
    vec4 delta;
    vec3 c = texture2D(colorTex, texcoord).rgb;
    vec3 cLeft = texture2D(colorTex, offset[0].xy).rgb;
    vec3 t = abs(c - cLeft);
    delta.x = max(max(t.r, t.g), t.b);
    vec3 cTop  = texture2D(colorTex, offset[0].zw).rgb;
    t = abs(c - cTop);
    delta.y = max(max(t.r, t.g), t.b);
    
    vec2 edges = step(threshold, delta.xy);
    
    if (dot(edges, vec2(1.0, 1.0)) == 0.0)
        discard;
    
    vec3 cRight = texture2D(colorTex, offset[1].xy).rgb;
    t = abs(c - cRight);
    delta.z = max(max(t.r, t.g), t.b);
    vec3 cBottom  = texture2D(colorTex, offset[1].zw).rgb;
    t = abs(c - cBottom);
    delta.w = max(max(t.r, t.g), t.b);
    
    vec2 maxDelta = max(delta.xy, delta.zw);
    
    vec3 cLeftLeft  = texture2D(colorTex, offset[2].xy).rgb;
    t = abs(c - cLeftLeft);
    delta.z = max(max(t.r, t.g), t.b);
    vec3 cTopTop = texture2D(colorTex, offset[2].zw).rgb;
    t = abs(c - cTopTop);
    delta.w = max(max(t.r, t.g), t.b);
    
    maxDelta = max(maxDelta.xy, delta.zw);
    float finalDelta = max(maxDelta.x, maxDelta.y);
    
    edges.xy *= step(finalDelta, SMAA_LOCAL_CONTRAST_ADAPTATION_FACTOR * delta.xy);
    return edges;
  }
#endif
void main() {
  vec4 color;
  vec2 texelSize = (1.0 / u_vec2_vpt_size);
  vec4 vOffset[3];
  vOffset[0] = mad(vec4(texelSize, texelSize), vec4(-1.0, 0.0, 0.0, -1.0), v_vec2_texcoord.xyxy);
  vOffset[1] = mad(vec4(texelSize, texelSize), vec4( 1.0, 0.0, 0.0,  1.0), v_vec2_texcoord.xyxy);
  vOffset[2] = mad(vec4(texelSize, texelSize), vec4(-2.0, 0.0, 0.0, -2.0), v_vec2_texcoord.xyxy);
  #ifdef SMAA_EDGES_DEPTH
    color.xy = SMAADepthEdgeDetection(v_vec2_texcoord, vOffset, uDepthTexture);
  #elif defined(SMAA_EDGES_LUMA)
    color.xy = SMAALumaEdgeDetection(v_vec2_texcoord, vOffset, u_texture
      #if SMAA_PREDICATION
      , uDepthTexture
      #endif
    );
  #elif defined(SMAA_EDGES_COLOR)
    color.xy = SMAAColorEdgeDetection(v_vec2_texcoord, vOffset, u_texture
      #if SMAA_PREDICATION
      , uDepthTexture
      #endif
    );
  #endif
  gl_FragColor = color;
}`,AS=`precision highp float;
precision highp int;
#include <prelude>
#ifndef UBO
uniform vec2 u_vec2_vpt_size;
#endif
varying vec2 v_vec2_texcoord;
#ifndef SMAA_THRESHOLD
#define SMAA_THRESHOLD 0.1
#endif
#ifndef SMAA_MAX_SEARCH_STEPS
#define SMAA_MAX_SEARCH_STEPS 16
#endif
#ifndef SMAA_MAX_SEARCH_STEPS_DIAG
#define SMAA_MAX_SEARCH_STEPS_DIAG 8
#endif
#ifndef SMAA_CORNER_ROUNDING
#define SMAA_CORNER_ROUNDING 25
#endif
#define SMAA_AREATEX_MAX_DISTANCE 16
#define SMAA_AREATEX_MAX_DISTANCE_DIAG 20
#define SMAA_AREATEX_PIXEL_SIZE (1.0 / vec2(160.0, 560.0))
#define SMAA_AREATEX_SUBTEX_SIZE (1.0 / 7.0)
#define SMAA_SEARCHTEX_SIZE vec2(66.0, 33.0)
#define SMAA_SEARCHTEX_PACKED_SIZE vec2(64.0, 16.0)
#define SMAA_CORNER_ROUNDING_NORM (float(SMAA_CORNER_ROUNDING) / 100.0)
#ifndef SMAA_AREATEX_SELECT
#define SMAA_AREATEX_SELECT(sample) sample.rg
#endif
#ifndef SMAA_SEARCHTEX_SELECT
#define SMAA_SEARCHTEX_SELECT(sample) sample.r
#endif
uniform sampler2D u_edgesTex;
uniform sampler2D u_areaTex;
uniform sampler2D u_searchTex;
#define texelSize (1.0 / u_vec2_vpt_size)
#define pixCoord (v_vec2_texcoord * u_vec2_vpt_size)
#define mad(a, b, c) (a * b + c)
#define saturate(a) clamp(a, 0.0, 1.0)
#define round(v) floor(v + 0.5)
#define SMAASampleLevelZeroOffset(tex, coord, offset) texture2D(tex, coord + offset * texelSize)
void SMAAMovc(bvec2 cond, inout vec2 variable, vec2 value) {
  if (cond.x) variable.x = value.x;
  if (cond.y) variable.y = value.y;
}
void SMAAMovc(bvec4 cond, inout vec4 variable, vec4 value) {
  SMAAMovc(cond.xy, variable.xy, value.xy);
  SMAAMovc(cond.zw, variable.zw, value.zw);
}
vec2 SMAADecodeDiagBilinearAccess(vec2 e) {
  
  
  
  
  
  
  
  
  
  
  
  
  
  e.r = e.r * abs(5.0 * e.r - 5.0 * 0.75);
  return round(e);
}
vec4 SMAADecodeDiagBilinearAccess(vec4 e) {
  e.rb = e.rb * abs(5.0 * e.rb - 5.0 * 0.75);
  return round(e);
}
vec2 SMAASearchDiag1(sampler2D edgesTex, vec2 texcoord, vec2 dir, out vec2 e) {
  vec4 coord = vec4(texcoord, -1.0, 1.0);
  vec3 t = vec3(texelSize, 1.0);
  for (int i = 0; i < SMAA_MAX_SEARCH_STEPS; i++) {
    if (!(coord.z < float(SMAA_MAX_SEARCH_STEPS_DIAG - 1) && coord.w > 0.9)) break;
    coord.xyz = mad(t, vec3(dir, 1.0), coord.xyz);
    e = texture2D(edgesTex, coord.xy).rg; 
    coord.w = dot(e, vec2(0.5, 0.5));
  }
  return coord.zw;
}
vec2 SMAASearchDiag2(sampler2D edgesTex, vec2 texcoord, vec2 dir, out vec2 e) {
  vec4 coord = vec4(texcoord, -1.0, 1.0);
  coord.x += 0.25 * texelSize.x; 
  vec3 t = vec3(texelSize, 1.0);
  for (int i = 0; i < SMAA_MAX_SEARCH_STEPS; i++) {
    if (!(coord.z < float(SMAA_MAX_SEARCH_STEPS_DIAG - 1) && coord.w > 0.9)) break;
    coord.xyz = mad(t, vec3(dir, 1.0), coord.xyz);
    
    
    e = texture2D(edgesTex, coord.xy).rg; 
    e = SMAADecodeDiagBilinearAccess(e);
    
    
    
    coord.w = dot(e, vec2(0.5, 0.5));
  }
  return coord.zw;
}
vec2 SMAAAreaDiag(sampler2D areaTex, vec2 dist, vec2 e, float offset) {
  vec2 texcoord = mad(vec2(SMAA_AREATEX_MAX_DISTANCE_DIAG, SMAA_AREATEX_MAX_DISTANCE_DIAG), e, dist);
  
  texcoord = mad(SMAA_AREATEX_PIXEL_SIZE, texcoord, 0.5 * SMAA_AREATEX_PIXEL_SIZE);
  
  texcoord.x += 0.5;
  
  texcoord.y += SMAA_AREATEX_SUBTEX_SIZE * offset;
  
  return SMAA_AREATEX_SELECT(texture2D(areaTex, texcoord)); 
}
vec2 SMAACalculateDiagWeights(sampler2D edgesTex, sampler2D areaTex, vec2 texcoord, vec2 e, vec4 subsampleIndices) {
  vec2 weights = vec2(0.0, 0.0);
  
  vec4 d;
  vec2 end;
  if (e.r > 0.0) {
      d.xz = SMAASearchDiag1(edgesTex, texcoord, vec2(-1.0,  1.0), end);
      d.x += float(end.y > 0.9);
  } else
      d.xz = vec2(0.0, 0.0);
  d.yw = SMAASearchDiag1(edgesTex, texcoord, vec2(1.0, -1.0), end);
  if (d.x + d.y > 2.0) { 
    
    vec4 coords = mad(vec4(-d.x + 0.25, d.x, d.y, -d.y - 0.25), vec4(texelSize, texelSize), texcoord.xyxy);
    vec4 c;
    c.xy = SMAASampleLevelZeroOffset(edgesTex, coords.xy, vec2(-1,  0)).rg;
    c.zw = SMAASampleLevelZeroOffset(edgesTex, coords.zw, vec2( 1,  0)).rg;
    c.yxwz = SMAADecodeDiagBilinearAccess(c.xyzw);
    
    
    
    
    
    
    
    
    vec2 cc = mad(vec2(2.0, 2.0), c.xz, c.yw);
    
    SMAAMovc(bvec2(step(0.9, d.zw)), cc, vec2(0.0, 0.0));
    
    weights += SMAAAreaDiag(areaTex, d.xy, cc, subsampleIndices.z);
  }
  
  d.xz = SMAASearchDiag2(edgesTex, texcoord, vec2(-1.0, -1.0), end);
  if (SMAASampleLevelZeroOffset(edgesTex, texcoord, vec2(1, 0)).r > 0.0) {
    d.yw = SMAASearchDiag2(edgesTex, texcoord, vec2(1.0, 1.0), end);
    d.y += float(end.y > 0.9);
  } else {
    d.yw = vec2(0.0, 0.0);
  }
  if (d.x + d.y > 2.0) { 
    
    vec4 coords = mad(vec4(-d.x, -d.x, d.y, d.y), vec4(texelSize, texelSize), texcoord.xyxy);
    vec4 c;
    c.x  = SMAASampleLevelZeroOffset(edgesTex, coords.xy, vec2(-1,  0)).g;
    c.y  = SMAASampleLevelZeroOffset(edgesTex, coords.xy, vec2( 0, -1)).r;
    c.zw = SMAASampleLevelZeroOffset(edgesTex, coords.zw, vec2( 1,  0)).gr;
    vec2 cc = mad(vec2(2.0, 2.0), c.xz, c.yw);
    
    SMAAMovc(bvec2(step(0.9, d.zw)), cc, vec2(0.0, 0.0));
    
    weights += SMAAAreaDiag(areaTex, d.xy, cc, subsampleIndices.w).gr;
  }
  return weights;
}
float SMAASearchLength(sampler2D searchTex, vec2 e, float offset) {
  
  
  vec2 scale = SMAA_SEARCHTEX_SIZE * vec2(0.5, -1.0);
  vec2 bias = SMAA_SEARCHTEX_SIZE * vec2(offset, 1.0);
  
  scale += vec2(-1.0,  1.0);
  bias  += vec2( 0.5, -0.5);
  
  
  scale *= 1.0 / SMAA_SEARCHTEX_PACKED_SIZE;
  bias *= 1.0 / SMAA_SEARCHTEX_PACKED_SIZE;
  
  return SMAA_SEARCHTEX_SELECT(texture2D(searchTex, mad(scale, e, bias))); 
}
float SMAASearchXLeft(sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end) {
  
  vec2 e = vec2(0.0, 1.0);
  for (int i = 0; i < SMAA_MAX_SEARCH_STEPS; i++) {
    if (!(texcoord.x > end && e.g > 0.8281 && e.r == 0.0)) break;
    e = texture2D(edgesTex, texcoord).rg; 
    texcoord = mad(-vec2(2.0, 0.0), texelSize, texcoord);
  }
  float offset = mad(-(255.0 / 127.0), SMAASearchLength(searchTex, e, 0.0), 3.25);
  return mad(texelSize.x, offset, texcoord.x);
  
  
  
  
  
  
  
  
  
}
float SMAASearchXRight(sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end) {
  vec2 e = vec2(0.0, 1.0);
  for (int i = 0; i < SMAA_MAX_SEARCH_STEPS; i++) { if (!(texcoord.x < end && e.g > 0.8281 && e.r == 0.0)) break;
    e = texture2D(edgesTex, texcoord).rg; 
    texcoord = mad(vec2(2.0, 0.0), texelSize, texcoord);
  }
  float offset = mad(-(255.0 / 127.0), SMAASearchLength(searchTex, e, 0.5), 3.25);
  return mad(-texelSize.x, offset, texcoord.x);
}
float SMAASearchYUp(sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end) {
  vec2 e = vec2(1.0, 0.0);
  for (int i = 0; i < SMAA_MAX_SEARCH_STEPS; i++) { if (!(texcoord.y > end && e.r > 0.8281 && e.g == 0.0)) break;
    e = texture2D(edgesTex, texcoord).rg; 
    texcoord = mad(-vec2(0.0, 2.0), texelSize, texcoord);
  }
  float offset = mad(-(255.0 / 127.0), SMAASearchLength(searchTex, e.gr, 0.0), 3.25);
  return mad(texelSize.y, offset, texcoord.y);
}
float SMAASearchYDown(sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end) {
  vec2 e = vec2(1.0, 0.0);
  for (int i = 0; i < SMAA_MAX_SEARCH_STEPS; i++) { if (!(texcoord.y < end && e.r > 0.8281 && e.g == 0.0)) break;
    e = texture2D(edgesTex, texcoord).rg; 
    texcoord = mad(vec2(0.0, 2.0), texelSize, texcoord);
  }
  float offset = mad(-(255.0 / 127.0), SMAASearchLength(searchTex, e.gr, 0.5), 3.25);
  return mad(-texelSize.y, offset, texcoord.y);
}
vec2 SMAAArea(sampler2D areaTex, vec2 dist, float e1, float e2, float offset) {
  
  vec2 texcoord = mad(vec2(SMAA_AREATEX_MAX_DISTANCE, SMAA_AREATEX_MAX_DISTANCE), round(4.0 * vec2(e1, e2)), dist);
  
  texcoord = mad(SMAA_AREATEX_PIXEL_SIZE, texcoord, 0.5 * SMAA_AREATEX_PIXEL_SIZE);
  
  texcoord.y = mad(SMAA_AREATEX_SUBTEX_SIZE, offset, texcoord.y);
  
  return SMAA_AREATEX_SELECT(texture2D(areaTex, texcoord)); 
}
void SMAADetectHorizontalCornerPattern(sampler2D edgesTex, inout vec2 weights, vec4 texcoord, vec2 d) {
  #if !defined(SMAA_DISABLE_CORNER_DETECTION)
  vec2 leftRight = step(d.xy, d.yx);
  vec2 rounding = (1.0 - SMAA_CORNER_ROUNDING_NORM) * leftRight;
  rounding /= leftRight.x + leftRight.y; 
  vec2 factor = vec2(1.0, 1.0);
  factor.x -= rounding.x * SMAASampleLevelZeroOffset(edgesTex, texcoord.xy, vec2(0,  1)).r;
  factor.x -= rounding.y * SMAASampleLevelZeroOffset(edgesTex, texcoord.zw, vec2(1,  1)).r;
  factor.y -= rounding.x * SMAASampleLevelZeroOffset(edgesTex, texcoord.xy, vec2(0, -2)).r;
  factor.y -= rounding.y * SMAASampleLevelZeroOffset(edgesTex, texcoord.zw, vec2(1, -2)).r;
  weights *= saturate(factor);
  #endif
}
void SMAADetectVerticalCornerPattern(sampler2D edgesTex, inout vec2 weights, vec4 texcoord, vec2 d) {
  #if !defined(SMAA_DISABLE_CORNER_DETECTION)
  vec2 leftRight = step(d.xy, d.yx);
  vec2 rounding = (1.0 - SMAA_CORNER_ROUNDING_NORM) * leftRight;
  rounding /= leftRight.x + leftRight.y;
  vec2 factor = vec2(1.0, 1.0);
  factor.x -= rounding.x * SMAASampleLevelZeroOffset(edgesTex, texcoord.xy, vec2( 1, 0)).g;
  factor.x -= rounding.y * SMAASampleLevelZeroOffset(edgesTex, texcoord.zw, vec2( 1, 1)).g;
  factor.y -= rounding.x * SMAASampleLevelZeroOffset(edgesTex, texcoord.xy, vec2(-2, 0)).g;
  factor.y -= rounding.y * SMAASampleLevelZeroOffset(edgesTex, texcoord.zw, vec2(-2, 1)).g;
  weights *= saturate(factor);
  #endif
}
void main() {
  vec4 vOffset[3];
  
  vOffset[0] = mad(vec4(texelSize, texelSize), vec4(-0.25, -0.125,  1.25, -0.125), v_vec2_texcoord.xyxy);
  vOffset[1] = mad(vec4(texelSize, texelSize), vec4(-0.125, -0.25, -0.125,  1.25), v_vec2_texcoord.xyxy);
  
  vOffset[2] = mad(
    vec4(texelSize.x, texelSize.x, texelSize.y, texelSize.y),
    vec4(-2.0, 2.0, -2.0, 2.0) * float(SMAA_MAX_SEARCH_STEPS),
    vec4(vOffset[0].xz, vOffset[1].yw)
  );
  vec4 subsampleIndices = vec4(0.0); 
  
  vec4 weights = vec4(0.0, 0.0, 0.0, 0.0);
  vec2 e = texture2D(u_edgesTex, v_vec2_texcoord).rg;
  if (e.g > 0.0) { 
    #if !defined(SMAA_DISABLE_DIAG_DETECTION)
    
    
    weights.rg = SMAACalculateDiagWeights(u_edgesTex, u_areaTex, v_vec2_texcoord, e, subsampleIndices);
    
    
    if (weights.r == -weights.g) { 
    #endif
    vec2 d;
    
    vec3 coords;
    coords.x = SMAASearchXLeft(u_edgesTex, u_searchTex, vOffset[0].xy, vOffset[2].x);
    coords.y = vOffset[1].y; 
    d.x = coords.x;
    
    
    
    float e1 = texture2D(u_edgesTex, coords.xy).r; 
    
    coords.z = SMAASearchXRight(u_edgesTex, u_searchTex, vOffset[0].zw, vOffset[2].y);
    d.y = coords.z;
    
    
    d = abs(round(mad(u_vec2_vpt_size.xx, d, -pixCoord.xx)));
    
    
    vec2 sqrt_d = sqrt(d);
    
    float e2 = SMAASampleLevelZeroOffset(u_edgesTex, coords.zy, vec2(1, 0)).r;
    
    
    weights.rg = SMAAArea(u_areaTex, sqrt_d, e1, e2, subsampleIndices.y);
    
    coords.y = v_vec2_texcoord.y;
    SMAADetectHorizontalCornerPattern(u_edgesTex, weights.rg, coords.xyzy, d);
    #if !defined(SMAA_DISABLE_DIAG_DETECTION)
    } else
    e.r = 0.0; 
    #endif
  }
  if (e.r > 0.0) { 
    vec2 d;
    
    vec3 coords;
    coords.y = SMAASearchYUp(u_edgesTex, u_searchTex, vOffset[1].xy, vOffset[2].z);
    coords.x = vOffset[0].x; 
    d.x = coords.y;
    
    float e1 = texture2D(u_edgesTex, coords.xy).g; 
    
    coords.z = SMAASearchYDown(u_edgesTex, u_searchTex, vOffset[1].zw, vOffset[2].w);
    d.y = coords.z;
    
    d = abs(round(mad(u_vec2_vpt_size.yy, d, -pixCoord.yy)));
    
    
    vec2 sqrt_d = sqrt(d);
    
    float e2 = SMAASampleLevelZeroOffset(u_edgesTex, coords.xz, vec2(0, 1)).g;
    
    weights.ba = SMAAArea(u_areaTex, sqrt_d, e1, e2, subsampleIndices.x);
    
    coords.x = v_vec2_texcoord.x;
    SMAADetectVerticalCornerPattern(u_edgesTex, weights.ba, coords.xyxz, d);
  }
  gl_FragColor = weights;
}`,LS=`#include <mediump_float>
#include <prelude>
varying mediump float v_intensity;
void main() {
    gl_FragColor = vec4(v_intensity);
}
`,RS=`#include <enable_standard_derivatives>
#include <highp_float>
#include <prelude>
#include <cam_pos>
#include <affine_step>
#include <fog>
#include <bit_mask>
#include <pack_depth>
#include <shadow>
#include <light>
uniform int u_int_gap_turns_only;
varying vec4 v_vec4_dash_color;
varying vec4 v_vec4_space_color;
varying vec4 v_vec4_border_color;
varying vec2 v_vec2_circle;
varying float v_float_width;
varying vec2 v_vec2_line_params;
vec4 distance_func_smooth(in vec4 main_color, in vec4 border_color, in vec2 circle)
{
    float circle_length = length(circle);
    float distance = circle_length - v_float_width;
    mat2 derivatives = mat2(dFdx(v_vec2_circle), dFdy(v_vec2_circle));
    
    
    
    vec2 circle_dx = derivatives[0];
    vec2 circle_dy = derivatives[1];
    
    float distance_dx = dot(v_vec2_circle, circle_dx);
    float distance_dy = dot(v_vec2_circle, circle_dy);
    
    float derivative_denominator = circle_length;
    float width = max(abs(distance_dx), abs(distance_dy));
    vec4 from_main_to_border = mix(
        main_color,
        border_color,
        affine_step(-width, 0., distance * derivative_denominator));
    vec4 from_color_to_fade = mix(
        from_main_to_border,
        vec4(0.),
        affine_step(0., +width, distance * derivative_denominator));
    return from_color_to_fade;
}
float calculate_segment_color_factor(in float distance_in_parts, in float threshold)
{
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    float color_factor = abs(fract(distance_in_parts + 0.5 - 0.5 * threshold) - 0.5);
    
    float parts_affine_step_width = fwidth(distance_in_parts);
    
    
    if (u_int_gap_turns_only == 1 && parts_affine_step_width < threshold * 0.0001) {
        return 1.0;
    }
    
    float smoothed_color_factor = affine_step(
        0.5 * threshold - 0.5 * parts_affine_step_width,
        0.5 * threshold + 0.5 * parts_affine_step_width,
        color_factor);
    return smoothed_color_factor;
}
void main()
{
    vec4 current_segment_color = mix(
        v_vec4_dash_color,
        v_vec4_space_color,
        calculate_segment_color_factor(
            v_vec2_line_params[1],
            v_vec2_line_params[0]));
    
    vec4 final_border_color = (1.0 - v_vec4_border_color.a) * current_segment_color + v_vec4_border_color;
    vec4 color = distance_func_smooth(current_segment_color, final_border_color, v_vec2_circle);
    vec4 light = light_factor_surface();
    gl_FragColor = apply_fog(light * color);
}
`,FS=`#include <mediump_float>
#include <prelude>
uniform sampler2D u_texture;
uniform float u_float_mix_coef;
varying vec2 v_vec2_texcoord;
void main()
{
    vec4 texColor = texture2D(u_texture, v_vec2_texcoord);
    gl_FragColor = vec4(texColor.rgb, texColor.a * u_float_mix_coef);
}
`,DS=`#include <mediump_float>
#include <prelude>
#include <cam_pos>
#include <apply_opacity>
#include <fog>
#include <bit_mask>
#include <pack_depth>
#include <shadow>
#include <light>
#define LIGHT_MODEL LIGHT_MODEL_PHONG
#include <light_phong>
#include <mix_color_defs>
#include <apply_color_effect>
uniform sampler2D u_sr2d_texture;
uniform float u_float_texture_opacity;
uniform vec4 u_float_texture_params;
uniform vec4 u_float_sprite_texture_coords;
uniform int u_int_is_textured;
uniform int u_int_is_normal_map_textured; 
uniform sampler2D u_sr2d_texture1;
uniform vec4 u_vec4_normal_map_texture_params;
uniform vec4 u_vec4_normal_map_sprite_texture_coords;
uniform vec4 u_vec4_normal_map_animated_offsets;
uniform int u_int_normal_map_is_animated;
uniform float u_float_metallic;
uniform float u_float_roughness;
varying vec4 v_vec4_color;
varying highp vec2 v_vec2_texcoord;
varying highp vec3 v_vec3_fragment_pos_world;
uniform int u_int_factor_use_interpolate;
uniform float u_float_factor_interpolate_base;
uniform vec4 u_vec4_factor_interpolate_ranges;
#ifdef MIX_COLOR_MODE
varying vec4 v_vec4_color2;
# if MIX_COLOR_MODE == MIX_COLOR_MODE_READ_FROM_TARGET
varying vec4 v_vec4_pos;
uniform sampler2D u_sr2d_read_from_target_texture;
# elif MIX_COLOR_MODE == MIX_COLOR_MODE_VERTEX_ATTRIBUTE
varying float v_float_mix_color_factor;
# endif
#endif
float interpolate(float x, float base, vec4 ranges) {
    float inMin = ranges.x;
    float outMin = ranges.y;
    float inMax = ranges.z;
    float outMax = ranges.w;
    float t = clamp(outMin + (outMax - outMin) * ((x - inMin) / (inMax - inMin)), outMin, outMax);
    return base == 1. ? t : (pow(base, t) - 1.) / (base - 1.);
}
void main() {
#ifdef MIX_COLOR_MODE
    float mix_color_factor = 0.;
# if MIX_COLOR_MODE == MIX_COLOR_MODE_READ_FROM_TARGET
    vec3 clip_space = v_vec4_pos.xyz / v_vec4_pos.w;
    vec3 uv = 0.5 * clip_space + vec3(0.5);
    
    
    
    mix_color_factor = texture2D(u_sr2d_read_from_target_texture, uv.xy).r;
# elif MIX_COLOR_MODE == MIX_COLOR_MODE_VERTEX_ATTRIBUTE
    mix_color_factor = v_float_mix_color_factor;
# endif
#endif
    bool use_normal_map = u_int_is_normal_map_textured == 1;
    vec3 normal;
    
    if(use_normal_map) {
        vec2 texcoord1 = fract(v_vec2_texcoord * u_vec4_normal_map_texture_params.zw + u_vec4_normal_map_texture_params.xy + u_vec4_normal_map_animated_offsets.xy);
        vec2 spritecoord1 = mix(u_vec4_normal_map_sprite_texture_coords.xy, u_vec4_normal_map_sprite_texture_coords.zw, texcoord1);
        vec4 texcolor1 = texture2D(u_sr2d_texture1, spritecoord1);
        
        if(u_int_normal_map_is_animated == 1) {
            vec2 texcoord2 = fract(v_vec2_texcoord * u_vec4_normal_map_texture_params.zw + u_vec4_normal_map_texture_params.xy + u_vec4_normal_map_animated_offsets.zw);
            vec2 spritecoord2 = mix(u_vec4_normal_map_sprite_texture_coords.xy, u_vec4_normal_map_sprite_texture_coords.zw, texcoord2);
            vec4 texcolor2 = texture2D(u_sr2d_texture1, spritecoord2);
            normal = normalize((texcolor1.xyz * 2.0 - 1.0) + (texcolor2.xyz * 2.0 - 1.0));
        } else {
            normal = normalize((texcolor1.xyz * 2.0 - 1.0));
        }
    }
    
    vec4 color = v_vec4_color;
    
    if(u_int_is_textured == 1) {
        vec2 texcoord = fract(v_vec2_texcoord * u_float_texture_params.zw + u_float_texture_params.xy);
        vec2 spritecoord = mix(u_float_sprite_texture_coords.xy, u_float_sprite_texture_coords.zw, texcoord);
        vec4 texcolor = apply_opacity(texture2D(u_sr2d_texture, spritecoord), u_float_texture_opacity);
        color = texcolor + color * (1. - texcolor.a);
    }
#ifdef MIX_COLOR_MODE
    
    if(u_int_factor_use_interpolate == 1) {
        mix_color_factor = interpolate(mix_color_factor, u_float_factor_interpolate_base, u_vec4_factor_interpolate_ranges);
    }
    
    color = mix(color, v_vec4_color2, mix_color_factor);
#endif
    
    if(use_normal_map) {
        color.rgb = color_phong(normal, v_vec3_fragment_pos_world, color.rgb, u_float_roughness, u_float_metallic, 1.0);
    } else {
        color = color * light_factor_surface();
    }
    gl_FragColor = apply_fog(apply_color_effect(color));
}
`,zS=`#include <lowp_float>
#include <prelude>
uniform vec4 u_vec4_color;
void main()
{
    gl_FragColor = u_vec4_color;
}
`,BS=`#include <enable_standard_derivatives>
#include <highp_float>
#include <prelude>
#include <cam_pos>
#include <fog>
#include <screendoor_transparency>
#include <fragment_normal>
#include <bit_mask>
#include <pack_depth>
#include <shadow>
#include <light>
#include <dem>
#ifdef WEBGL1
float round(float x) {
    return floor(x + 0.5);
}
#endif
uniform sampler2D u_sr2d_texture;
uniform vec4 u_vec4_wall_padding_su; 
uniform vec4 u_vec4_texture_padding_un; 
uniform vec2 u_vec2_texture_part_count;
uniform vec2 u_vec2_max_interval_su;
uniform vec2 u_vec2_texture_slice_size_su; 
uniform ivec2 u_ivec2_layout_mode;
varying vec4 v_vec4_rotated_scaled_vertex;
varying vec2 v_vec2_quad_fraction;
varying vec2 v_vec2_wall_size_su;
#define VL_REPEAT_WITH_STRETCH 1
#define VL_STRETCH 2
#define VL_REPEAT_WITH_MAX_INTERVAL 3
#define HL_REPEAT_WITH_STRETCH 1
#define HL_STRETCH 2
#define HL_REPEAT_WITH_MAX_INTERVAL 3
bool layout_mode_stretch(float curr_point_su, float wall_size_su, out float out_tc)
{
    out_tc = curr_point_su / wall_size_su;
    return true;
}
bool layout_mode_repeat_with_stretch(float curr_point_su, float wall_size_su, float slice_size_su, float slice_count, out float out_tc, out float out_final_slice_size_su)
{
    float raw_slice_repeats = wall_size_su / slice_size_su;
    float repeated_slice_count = round(raw_slice_repeats * slice_count);
    float rounded_image_repeats = repeated_slice_count / slice_count;
    
    out_final_slice_size_su = slice_size_su * (repeated_slice_count / raw_slice_repeats);
    
    int leftover_part_count = int(mod(repeated_slice_count, slice_count));
    float start_image_tc = (slice_count - float((leftover_part_count + 1) / 2)) / slice_count;
    out_tc = mix(start_image_tc, start_image_tc + rounded_image_repeats, curr_point_su / wall_size_su);
    return true;
}
bool layout_mode_repeat_with_max_interval(float curr_point_su, float wall_size_su, float slice_size_su, float max_interval_size_su, out float out_tc)
{
    float raw_block_repeats = (wall_size_su - slice_size_su) / (slice_size_su + max_interval_size_su);
    float interval_count = ceil(raw_block_repeats);
    float window_count = interval_count + 1.0;
    float interval_size_su = (wall_size_su - (window_count * slice_size_su)) / interval_count;
    
    
    if (raw_block_repeats < 1.0)
    {
        out_tc = (curr_point_su - (wall_size_su - slice_size_su) * 0.5) / slice_size_su;
        return out_tc >= 0.0 && out_tc <= 1.0;
    }
    
    if (curr_point_su < slice_size_su)
    {
        out_tc = curr_point_su / slice_size_su;
        return true;
    }
    float block_size_su = slice_size_su + interval_size_su;
    float block_coverege_un = (curr_point_su - slice_size_su) / block_size_su;
    block_coverege_un = fract(block_coverege_un);
    
    out_tc = (block_coverege_un * block_size_su - interval_size_su) / slice_size_su;
    return block_coverege_un * block_size_su >= interval_size_su;
}
bool layout_vertical(vec2 curr_point_su, float wall_size_su, out float out_tc_y, out float out_final_slice_size_su)
{
    if (u_ivec2_layout_mode.y == VL_STRETCH)
    {
        out_final_slice_size_su = wall_size_su;
        return layout_mode_stretch(
            curr_point_su.y,
            wall_size_su,
            out_tc_y
        );
    }
    else if (u_ivec2_layout_mode.y == VL_REPEAT_WITH_STRETCH)
    {
        return layout_mode_repeat_with_stretch(
            curr_point_su.y,
            wall_size_su,
            u_vec2_texture_slice_size_su.y,
            u_vec2_texture_part_count.y,
            out_tc_y,
            out_final_slice_size_su
        );
    }
    else if (u_ivec2_layout_mode.y == VL_REPEAT_WITH_MAX_INTERVAL)
    {
        out_final_slice_size_su = u_vec2_texture_slice_size_su.y;
        return layout_mode_repeat_with_max_interval(
            curr_point_su.y,
            wall_size_su,
            u_vec2_texture_slice_size_su.y,
            u_vec2_max_interval_su.y,
            out_tc_y
        );
    }
    return false;
}
bool layout_horizontal(vec2 curr_point_su, float wall_size_su, out float out_tc_x, out float out_final_slice_size_su)
{
    if (u_ivec2_layout_mode.x == HL_STRETCH)
    {
        out_final_slice_size_su = wall_size_su;
        return layout_mode_stretch(
            curr_point_su.x,
            wall_size_su,
            out_tc_x
        );
    }
    else if (u_ivec2_layout_mode.x == HL_REPEAT_WITH_STRETCH)
    {
        return layout_mode_repeat_with_stretch(
            curr_point_su.x,
            wall_size_su,
            u_vec2_texture_slice_size_su.x,
            u_vec2_texture_part_count.x,
            out_tc_x,
            out_final_slice_size_su
        );
    }
    else if (u_ivec2_layout_mode.x == HL_REPEAT_WITH_MAX_INTERVAL)
    {
        out_final_slice_size_su = u_vec2_texture_slice_size_su.x;
        return layout_mode_repeat_with_max_interval(
            curr_point_su.x,
            wall_size_su,
            u_vec2_texture_slice_size_su.x,
            u_vec2_max_interval_su.x,
            out_tc_x
        );
    }
    return false;
}
bool layout_internal_image(vec2 curr_point_su, vec2 wall_size_su, out vec2 out_tc, out vec2 out_final_slice_size_su)
{
    float x = 0.;
    float y = 0.;
    if (!layout_vertical(curr_point_su, wall_size_su.y, y, out_final_slice_size_su.y))
    {
        return false;
    }
    if (!layout_horizontal(curr_point_su, wall_size_su.x, x, out_final_slice_size_su.x))
    {
        return false;
    }
    out_tc = vec2(x, y);
    return true;
}
bool layout_image(out vec2 out_tc, out vec2 out_final_slice_size_su)
{
    
    
    
    
    
    
    
    
    vec2 curr_point_su = clamp(v_vec2_quad_fraction, vec2(0.0), vec2(1.0)) * v_vec2_wall_size_su;
    
    bvec4 is_in_padding_zone = bvec4(
        curr_point_su.x < u_vec4_wall_padding_su.x, 
        curr_point_su.y < u_vec4_wall_padding_su.y, 
        curr_point_su.x > (v_vec2_wall_size_su.x - u_vec4_wall_padding_su.z), 
        curr_point_su.y > (v_vec2_wall_size_su.y - u_vec4_wall_padding_su.w) 
    );
    if (any(is_in_padding_zone))
    {
        vec2 left_top_offset_un = curr_point_su / u_vec4_wall_padding_su.xy;
        vec2 right_bottom_offset_un = (curr_point_su - v_vec2_wall_size_su + u_vec4_wall_padding_su.zw) / u_vec4_wall_padding_su.zw;
        vec2 left_top_uv = left_top_offset_un * u_vec4_texture_padding_un.xy;
        vec2 right_bottom_uv = (vec2(1.0) - u_vec4_texture_padding_un.zw) + right_bottom_offset_un * u_vec4_texture_padding_un.zw;
        
        out_tc = is_in_padding_zone.x ? vec2(left_top_uv.x, v_vec2_quad_fraction.y) :
                 is_in_padding_zone.z ? vec2(right_bottom_uv.x, v_vec2_quad_fraction.y) :
                 is_in_padding_zone.y ? vec2(v_vec2_quad_fraction.x, left_top_uv.y) :
                  vec2(v_vec2_quad_fraction.x, right_bottom_uv.y);
        
        
        out_final_slice_size_su = vec2(99999.0);
        return true;
    }
    
    vec2 curr_point_in_center_image_su = curr_point_su - u_vec4_wall_padding_su.xy;
    vec2 wall_size_in_center_image_su = v_vec2_wall_size_su - u_vec4_wall_padding_su.xy - u_vec4_wall_padding_su.zw;
    bool res = layout_internal_image(curr_point_in_center_image_su, wall_size_in_center_image_su, out_tc, out_final_slice_size_su);
    if (res)
    {
        out_tc = fract(out_tc);
        
        out_tc = out_tc * (vec2(1.0) - u_vec4_texture_padding_un.xy - u_vec4_texture_padding_un.zw) + u_vec4_texture_padding_un.xy;
        
        
        
        
        out_final_slice_size_su /= vec2(1.0) - u_vec4_texture_padding_un.xy - u_vec4_texture_padding_un.zw;
    }
    return res;
}
void main()
{
    if (check_dem_invalid() != 0) {
        discard;
    }
    apply_screendoor();
    vec4 color = vec4(0.);
    vec2 raw_tc = vec2(0.);
    vec2 final_slice_size_su = vec2(0.);
    bool should_render_texture = layout_image(raw_tc, final_slice_size_su);
    vec3 normal = calc_fragment_normal(v_vec4_rotated_scaled_vertex.xyz);
    vec2 modulo_coords = fract(raw_tc);
    vec4 texture_color;
#ifdef WEBGL1
    texture_color = texture2D(u_sr2d_texture, modulo_coords);
#else
    vec2 tc_dfdx = dFdx(v_vec2_quad_fraction);
    vec2 tc_dfdy = dFdy(v_vec2_quad_fraction);
    vec2 final_texture_size_su = final_slice_size_su * u_vec2_texture_part_count;
    vec2 derivative_scale = v_vec2_wall_size_su / final_texture_size_su;
    tc_dfdx *= derivative_scale;
    tc_dfdy *= derivative_scale;
    texture_color = textureGrad(u_sr2d_texture, modulo_coords, tc_dfdx, tc_dfdy);
#endif
    if (!should_render_texture) {
        discard;
    }
    color = texture_color;
    gl_FragColor = apply_fog(color);
}
`,OS=`#include <enable_standard_derivatives>
#include <highp_float>
#include <prelude>
#include <cam_pos>
#include <fog>
#include <screendoor_transparency>
#include <fragment_normal>
#include <bit_mask>
#include <pack_depth>
#include <shadow>
#include <light>
#include <dem>
uniform sampler2D u_sr2d_texture;
uniform vec4 u_vec4_color;
varying vec3 v_vec3_rotated_scaled_vertex;
varying vec2 v_vec2_texcoord;
void main()
{
    if (check_dem_invalid() != 0) {
        discard;
    }
    apply_screendoor();
    vec3 normal = calc_fragment_normal(v_vec3_rotated_scaled_vertex);
    vec4 light = light_factor(normal);
    vec4 color = texture2D(u_sr2d_texture, v_vec2_texcoord) * u_vec4_color * light;
    gl_FragColor = apply_fog(color);
}
`,wS={affine_step:fb,alpha_mode_defs:mb,apply_color_effect:vb,apply_opacity:Yu,arrow_functions:gb,bit_mask:pb,cam_pos:Qu,circle_functions:xb,dem:bb,enable_standard_derivatives:Sb,fog:yb,fragment_normal:Tb,highp_float:Eb,light:Cb,light_pbr:Ib,light_phong:Pb,lowp_float:Ab,mediump_float:Lb,mix_color_defs:Ju,pack_depth:Rb,prelude:Fb,require_frag_depth:Db,screendoor_transparency:zb,shadow:Bb,signed_distance_functions:Ku},NS={arrow_line:Ob,arrow_line_identify:wb,circle_marker:Nb,color:kb,color_identify:Ub,color_with_z_fade:Mb,copy:Hb,dem_elevation:Gb,dem_elevation_copy:Vb,dem_flat_bottom:Zb,dem_ground:Wb,dem_ground2:jb,dem_mesh:Xb,dem_mesh2:$b,dem_normal:qb,depth_clear:Yb,fxaa:Qb,globe_halo:Jb,globe_halo_background:Kb,gltf_model:eS,gradient_with_z_fade:tS,heatmap:iS,heatmap_texture:nS,inverse:rS,label:sS,label_directional:oS,label_directional_screen:aS,line:lS,main_shadow:cS,map_mesh:dS,mesh:uS,metric_point:hS,one_way_line:_S,one_way_line_screen:fS,particle:mS,patterned_line:vS,pointsprite:gS,pointsprite_identify:pS,rect_with_texture:xS,road:bS,road_identify:SS,simple_line_2d:yS,simple_line_3d:TS,simple_mesh:ES,sky:CS,smaa_blend:IS,smaa_edge:PS,smaa_weight:AS,stars:LS,striped_line:RS,taa:FS,textured_color:DS,uniform_color:zS,wall_texture:BS,zbm_model:OS},kS=`vec4 apply_height_factor(in vec3 vertex, const float height_factor)
{
    vertex.z *= height_factor;
    return vec4(vertex, 1.0);
}
`,US=`
vec2 multiply_complex(const vec2 lhs, const vec2 rhs)
{
    return vec2(lhs.x * rhs.x - lhs.y * rhs.y, lhs.x * rhs.y + lhs.y * rhs.x);
}
struct ArrowParameters
{
    float zpt_to_texcoord_factor;
    float final_size;
    float outer_width;
    vec2 widen_size;
    vec2 wing_normal;
    vec2 tip_normal;
};
ArrowParameters calculate_arrow_parameters(
    const float calculation_scale,
    const float width_zpt,
    const float border_width_zpt,
    const float segment_length_zpt,
    const float wing_width_multiplier,
    const float wing_height_multiplier,
    const float tip_height_multiplier,
    const float size_factor)
{
    float quad_width = 2.0 * border_width_zpt + 2.0 * wing_width_multiplier * width_zpt;
    float quad_height = 2.0 * border_width_zpt + segment_length_zpt;
    float max_quad_dimension = max(quad_width, quad_height);
    float zpt_to_texcoord_factor = 2.0 / max_quad_dimension;
    float final_size = calculation_scale * size_factor * max_quad_dimension;
    vec2 widen_size = 0.5 * vec2(quad_height, quad_width) * zpt_to_texcoord_factor;
    float outer_width = (width_zpt * wing_width_multiplier + border_width_zpt) * zpt_to_texcoord_factor;
    vec2 wing_normal = -normalize(vec2(wing_width_multiplier, wing_height_multiplier));
    vec2 tip_normal = normalize(vec2(wing_width_multiplier, tip_height_multiplier));
    return ArrowParameters(
        zpt_to_texcoord_factor,
        final_size,
        outer_width,
        widen_size,
        wing_normal,
        tip_normal);
}
struct VertexShiftParameters
{
    vec4 clip_space_vertex;
    float limited_factor;
};
VertexShiftParameters calculate_vertex_shift_parameters(
    const mat4 mvp,
    const vec2 vpt_size,
    const vec2 vertex,
    const vec2 widen,
    const float shift_pixels)
{
    vec2 widen_perp = vec2(-widen.y, widen.x);
    
    vec4 clip_space_widen = mvp * vec4(widen, 0., 0.);
    vec4 clip_space_widen_perp = mvp * vec4(widen_perp, 0., 0.);
    vec2 half_viewport = vpt_size / 2.;
    
    vec4 clip_space_vertex = mvp * vec4(vertex, 0.0, 1.0) + clip_space_widen;
    
    float limited_factor = calculate_multiplication_factor(
        half_viewport,
        clip_space_widen,
        clip_space_widen_perp,
        clip_space_vertex,
        shift_pixels);
    return VertexShiftParameters(
        clip_space_vertex + clip_space_widen * limited_factor,
        limited_factor);
}
`,MS=`struct Scale
{
    float projection;
    float style;
    float style_clamped;
    float calculation;
};
Scale calculate_scale(const vec3 projection_scale_style_scale_dpi, const vec2 scale_limits)
{
    float style_scale_clamped = clamp(projection_scale_style_scale_dpi.y, scale_limits.x, scale_limits.y);
    float scale_ratio = projection_scale_style_scale_dpi.x / projection_scale_style_scale_dpi.y;
    float calculation_scale = style_scale_clamped * scale_ratio;
    return Scale(
        projection_scale_style_scale_dpi.x,
        projection_scale_style_scale_dpi.y,
        style_scale_clamped,
        calculation_scale);
}
const float g_min_scale_factor = 1e-2;
const float g_max_scale_factor = 1e2;
const float g_base_scale_numerator = 1e2;
float normalize_scale_to_tile(const float scale, const float tile_size)
{
    return clamp(
        (scale - g_min_scale_factor) / (tile_size - g_min_scale_factor),
        g_min_scale_factor,
        g_max_scale_factor);
}
`,HS=`
#ifdef SCREENDOOR
varying vec3 v_clipspace_pos;
#endif
void save_clipspace_pos () {
    #ifdef SCREENDOOR
    v_clipspace_pos = gl_Position.xyz;
    #endif
}
`,GS=`
uniform sampler2D u_tex_dem;
uniform sampler2D u_tex_corrected_dem;
uniform float u_float_dem_resolution;
uniform float u_float_corrected_interval;
uniform mat4 u_mat4_dem_corrected;
uniform mat4 u_mat4_dem_mvp;
uniform float u_float_dem_scale;
uniform float u_float_map_center_elevation;
uniform float u_float_vertical_scale;
const float UNPACK_CENTROID = 8. / 65535.;
const float MAP_POINTS_IN_METER = 107.17318796639701;
#ifndef VARYINGS_LIMIT_9
    
    varying vec2 v_vec2_dem_tex_pos;
    
    varying float v_float_dem_invalid;
#endif
void reset_dem_varyings() {
    #ifndef VARYINGS_LIMIT_9
    v_vec2_dem_tex_pos = vec2(0, 0);
    v_float_dem_invalid = 0.;
    #endif
}
float dem_height_direct_meters(vec2 tex_pos) {
    
    if (u_float_dem_scale == 0.) {
        reset_dem_varyings();
        return 0.;
    }
    #ifndef VARYINGS_LIMIT_9
    v_vec2_dem_tex_pos = tex_pos;
    v_float_dem_invalid = 0.;
    #endif
    vec4 elevation;
    
    if (u_float_corrected_interval == 0.) {
        elevation = texture2D(u_tex_dem, tex_pos);
    }
    else {
        vec2 test_tex_pos = abs(tex_pos - vec2(0.5, 0.5));
        if (test_tex_pos.x < u_float_corrected_interval && test_tex_pos.y < u_float_corrected_interval) {
            elevation = texture2D(u_tex_corrected_dem, (u_mat4_dem_corrected * vec4(tex_pos, 0, 1)).xy);
        } else {
            elevation = texture2D(u_tex_dem, tex_pos);
        }
    }
    
    if (elevation.a < 1.) {
        #ifndef VARYINGS_LIMIT_9
        v_float_dem_invalid = 1.;
        #endif
        
        return 0.;
    } else {
        return elevation.r;
    }
}
float meters_to_tile_height(float height) {
    return (height - u_float_map_center_elevation) * MAP_POINTS_IN_METER * u_float_vertical_scale * u_float_dem_scale;
}
float dem_height_direct(vec2 tex_pos) {
    float height = dem_height_direct_meters(tex_pos);
    return meters_to_tile_height(height);
}
float dem_height(const vec2 coords) {
    
    if (u_float_dem_scale == 0.) {
        reset_dem_varyings();
        return 0.;
    }
    vec4 tex_pos = u_mat4_dem_mvp * vec4(coords, 0.0, 1.0);
    return dem_height_direct(tex_pos.xy);
}
float abs_height(float height) {
    return (height - u_float_map_center_elevation * MAP_POINTS_IN_METER) * u_float_dem_scale * u_float_vertical_scale;
}
vec2 unpack_dem_position(const vec2 pos) {
    return pos * UNPACK_CENTROID;
}
`,VS=`uniform bool u_bool_depth_test_disable;
uniform sampler2D u_color_tex_labeling;
uniform sampler2D u_depth_tex_labeling;
float color_test(
    const vec2 pos,
    const vec4 color,
    const vec2 corner_0,
    const vec2 corner_1,
    const vec2 corner_2,
    const vec2 corner_3,
    float check_edge)
{
    float result = 0.;
    
    if (texture2D(u_color_tex_labeling, (pos + corner_0 + 1.) / 2.) == color) {
        result++;
    }
    if (texture2D(u_color_tex_labeling, (pos + corner_1 + 1.) / 2.) == color) {
        result++;
    }
    if (texture2D(u_color_tex_labeling, (pos + corner_2 + 1.) / 2.) == color) {
        result++;
    }
    if (texture2D(u_color_tex_labeling, (pos + corner_3 + 1.) / 2.) == color) {
        result++;
    }
    
    return step(check_edge, result);
}
float depth_point_test(
    const vec2 pos,
    const float depth,
    const vec4 color,
    const vec2 corner_0,
    const vec2 corner_1,
    const vec2 corner_2,
    const vec2 corner_3)
{
    if (u_bool_depth_test_disable == true) {
        return 1.;
    }
    float colorCheck = color_test(pos, color, corner_0, corner_1, corner_2, corner_3, 3.);
    if (colorCheck == 1.) {
        return 1.;
    }
    float d = (depth + 1.) / 2.;
    float delta = 0.0001;
    float texDepth = texture2D(u_depth_tex_labeling, (pos + 1.) / 2.).r;
    if (d <= texDepth) {
        return 1.;
    }
    if (d - texDepth > delta) {
        return 0.;
    }
    return 1. - (d - texDepth) / delta;
}
float depth_line_test(
    const vec2 color_pos,
    const vec2 depth_pos,
    const float depth,
    const vec4 color,
    const vec2 corner_0,
    const vec2 corner_1,
    const vec2 corner_2,
    const vec2 corner_3)
{
    if (u_bool_depth_test_disable == true) {
        return 1.;
    }
    
    bool sameColor = texture2D(u_color_tex_labeling, (depth_pos + 1.) / 2.) == color;
    float colorCheck = color_test(color_pos, color, corner_0, corner_1, corner_2, corner_3, 2.);
    if (colorCheck == 1. && sameColor) {
        return 1.;
    }
    float d = (depth + 1.) / 2.;
    float delta = 0.0001;
    float texDepth = texture2D(u_depth_tex_labeling, (depth_pos + 1.) / 2.).r;
    if (d <= texDepth) {
        return 1.;
    }
    if (d - texDepth > delta) {
        return 0.;
    }
    return 1. - (d - texDepth) / delta;
}
`,ZS=`uniform mat4 u_mat4_flat_mvp;
uniform mat4 u_mat4_ecef_mvp;
uniform float u_float_crossfade;
uniform mat4 u_mat4_vp;
uniform vec2 u_vec2_camera_merc;      
uniform vec4 u_vec4_vp_at_center;     
const float ECEF_CF_E = 2e-8;
const float ECEF_CF_NEAR = 0.01;
const float ECEF_WORLD = 4294967296.;
const float ECEF_PI = 3.14159265358979;
const float ECEF_TWO_PI = 6.28318530717959;
const float ECEF_MAX_LAT = 1.4844222;
#define DECODE_ECEF(v) ((v) - 0.5)
float ecef_wrap_pi(float angle) {
    return mod(angle + ECEF_PI, ECEF_TWO_PI) - ECEF_PI;
}
vec4 ecef_flat_clip_from_epos(const vec3 epos, const float elevation) {
    vec3 en = normalize(epos);
    float lng = atan(en.x, en.z);
    float lat = clamp(asin(clamp(en.y, -1.0, 1.0)), -ECEF_MAX_LAT, ECEF_MAX_LAT);
    float mercY = log(tan(ECEF_PI / 4.0 + lat / 2.0));
    float dLng = ecef_wrap_pi(lng - u_vec2_camera_merc.x);
    float relX = dLng / ECEF_TWO_PI * ECEF_WORLD;
    float relY = (mercY - u_vec2_camera_merc.y) / ECEF_TWO_PI * ECEF_WORLD;
    return u_mat4_vp * vec4(relX, relY, elevation, 0.0) + u_vec4_vp_at_center;
}
bool is_flat_mode() {
    return u_float_crossfade < ECEF_CF_E;
}
vec4 _get_clipspace_impl(const vec3 epos, const float elevation) {
    float R = ECEF_WORLD + elevation;
    if (u_float_crossfade < ECEF_CF_NEAR) {
        return ecef_flat_clip_from_epos(epos, elevation);
    } else if (u_float_crossfade > (1. - ECEF_CF_NEAR)) {
        return u_mat4_ecef_mvp * vec4(epos * R, 1.);
    }
    vec4 fclip = ecef_flat_clip_from_epos(epos, elevation);
    vec4 eclip = u_mat4_ecef_mvp * vec4(epos * R, 1.);
    return mix(fclip, eclip, u_float_crossfade);
}
vec4 get_clipspace(const vec3 pos) {
    if (is_flat_mode()) {
        return u_mat4_flat_mvp * vec4(pos, 1.);
    }
    return _get_clipspace_impl(pos, 0.0);
}
vec4 get_clipspace(const vec3 vertex, const float flat_z) {
    vec3 pos = is_flat_mode() ? vec3(vertex.xy, flat_z) : DECODE_ECEF(vertex);
    return get_clipspace(pos);
}
struct EcefTangentFrame {
    vec3 center; 
    vec3 up;
    vec3 east;
    vec3 north;
};
EcefTangentFrame ecef_tangent_frame(const vec3 ecef_u16) {
    EcefTangentFrame f;
    f.center = DECODE_ECEF(ecef_u16);
    f.up = normalize(f.center);
    vec3 raw_east = cross(vec3(0., 1., 0.), f.up);
    raw_east = dot(raw_east, raw_east) > 1e-12 ? raw_east : cross(vec3(1., 0., 0.), f.up);
    f.east = normalize(raw_east);
    f.north = cross(f.up, f.east);
    return f;
}
vec4 get_clipspace_from_ecef_u16(const vec3 ecef_u16, const vec3 local_vertex, const float elevation) {
    EcefTangentFrame f = ecef_tangent_frame(ecef_u16);
    vec3 ecef_vertex = f.east * local_vertex.x + f.north * local_vertex.y + f.up * local_vertex.z;
    ecef_vertex *= (ECEF_PI / 2.0);
    return _get_clipspace_impl(f.center + ecef_vertex, elevation);
}
`,WS=`#ifndef UBO
# ifdef FOG
uniform float u_fog_distance;
# endif
# ifdef SKY
uniform mat4 u_mat4_view_transposed;
uniform mat4 u_mat4_proj_inverted;
# endif
#endif 
#if defined(FOG) || defined(SKY)
varying vec3 v_fog_pos;
#endif
void calc_fog_pos(vec3 world_pos) {
#ifdef FOG
    v_fog_pos = (world_pos - u_cam_pos) / u_fog_distance;
#endif
}
void calc_fog_pos_sky(vec4 pos) {
#ifdef SKY
    v_fog_pos = mat3(u_mat4_view_transposed) * (u_mat4_proj_inverted * pos).xyz;
#endif
}`,jS=`#ifdef TAA
uniform vec2 u_vec2_camera_jitter;
void apply_vertex_jitter(inout vec4 clipPos) {
    clipPos.xy += clipPos.w * u_vec2_camera_jitter;
}
#endif`,XS=`float calculate_final_width(
    const Scale scale,
    const float width,
    const float width_offset)
{
    
    float final_width = max(0., scale.calculation * width - scale.projection * width_offset);
    return final_width;
}
`,$S=`uniform mat4 u_mat4_mvp;
`,qS=`
vec2 normalize_s08(vec2 value)
{
    return value * (1. / 127.);
}
vec3 normalize_s08(vec3 value)
{
    return value * (1. / 127.);
}
float normalize_s16(float value)
{
    return value * (1. / 32767.);
}
vec2 normalize_s16(vec2 value)
{
    return value * (1. / 32767.);
}
vec3 normalize_s16(vec3 value)
{
    return value * (1. / 32767.);
}
vec2 unpack_widen(vec2 widen_packed)
{
    
    return normalize_s08(widen_packed) * sqrt(2.);
}
vec2 unpack_texcoord(vec2 texcoord)
{
    return texcoord * (1. / 32768.);
}
vec2 unpack_model_texcoord(vec2 texcoord)
{
    const float min_value = -3.0;
    const float max_value = 5.0;
    return texcoord * (max_value - min_value) / 65536.0 + min_value;
}
float normalize_u16(float value)
{
    return value * (1. / 65535.);
}
float unpack_denormalized_distance_to_line(float value)
{
    return 1. - normalize_u16(value);
}
`,YS=`
const float g_min_denominator = 1e-7;
const float g_max_factor = 10000.;
float calculate_multiplication_factor(
    vec2 half_viewport,
    
    vec4 clip_space_widen,
    vec4 clip_space_widen_perp,
    
    vec4 clip_space_vertex,
    float shift_pixels)
{
    float limited_factor = 0.;
    {
        
        vec2 screen_space_widen = (clip_space_widen.xy * clip_space_vertex.w - clip_space_vertex.xy * clip_space_widen.w) * half_viewport;
        vec2 screen_space_widen_perp = (clip_space_widen_perp.xy * clip_space_vertex.w - clip_space_vertex.xy * clip_space_widen_perp.w) * half_viewport;
        
        vec2 perp = vec2(screen_space_widen_perp.y, -screen_space_widen_perp.x);
        
        float perp_length = length(perp);
        vec4 v = clip_space_vertex;
        vec4 n = clip_space_widen;
        float denominator = dot(perp, screen_space_widen) / shift_pixels - n.w * v.w * perp_length;
        if (abs(denominator) > g_min_denominator)
        {
            float factor = v.w * v.w * perp_length / denominator;
            
            
            
            
            
            
            
            
            
            if (factor == factor){
                limited_factor = sign(factor) * min(g_max_factor, abs(factor));
            }
        }
    }
    
    
    if (limited_factor == 0.) {
        vec2 screen_widen = clip_space_widen.xy / clip_space_vertex.w * half_viewport;
        float screen_widen_len = length(screen_widen);
        if (screen_widen_len > 1e-4) {
            limited_factor = shift_pixels / screen_widen_len;
        }
    }
    return limited_factor;
}
`,QS=`uniform mat4 u_mat4_model;
vec3 calc_pos_world(vec4 pos) {
    
    
    
    return (u_mat4_model * pos).xyz;
}
vec3 calc_pos_world(vec3 pos) {
    return calc_pos_world(vec4(pos, 1.0));
}
vec3 calc_pos_world(vec2 pos) {
    return calc_pos_world(vec4(pos, 0.0, 1.0));
}`,JS=`
const float g_circle_scale_precision_factor = 1e8;
`,KS=`#ifdef WEBGL2
#define varying out
#define attribute in
#define texture2D texture
#endif
#ifdef UBO
uniform CommonSettings
{
    mediump float u_float_rounding_factor;
    mediump float u_float_border_width_offset;
    mediump vec2 u_vec2_scale_limits;
    mediump vec2 u_vec2_depth_test_half_point_size;
    mediump vec2 u_vec2_vpt_size;
    
    mediump vec4 u_fog_color;
    mediump vec4 u_fog_color2;
    mediump vec2 u_fog_gradient;
    mediump vec2 u_fog_limits;
    mediump float u_fog_horizon_blend;
    mediump float u_fog_horizon_level;
    mediump float u_fog_horizon_pad;
    mediump float u_fog_distance;
    mediump vec4 u_sky_color;
    highp vec3 u_cam_pos;
    
    
    
    
    
    
    mediump vec4 u_shadow_map_params;
    highp mat4 u_mat4_clip_to_shadow;
    mediump float u_shadow_bias;
    mediump mat4 u_mat4_view_transposed;
    mediump mat4 u_mat4_proj_inverted;
    
    mediump vec2 u_vec2_halo_viewport_size;
    mediump vec2 u_vec2_halo_viewport_center_shift;
    mediump vec4 u_vec4_halo_radius_stops;
    mediump vec4 u_vec4_halo_color;
    mediump float u_float_halo_exp_factor;
    mediump vec4 u_vec4_default_background_color;
    
    mediump mat4 u_mat4_stars;
    mediump float u_float_pixelratio;
    mediump float u_float_stars_intensity;
};
#endif
`,ey=`
float unpack_scale(float value)
{
    return exp(abs(value) / 256.) * sign(value);
}
float unpack_positive_value(float value)
{
    return exp(value / 256.);
}
vec2 make_position(const vec2 position, const float w, const vec2 inv_half_size, const float rounding_factor)
{
    vec2 non_rounded_position = (position + w) / (w * inv_half_size);
    vec2 rounded_position = floor(non_rounded_position + 0.5);
    vec2 rounding_delta = rounded_position - non_rounded_position;
    vec2 pixel_coord = non_rounded_position + rounding_factor * rounding_delta - 0.5;
    return (pixel_coord * inv_half_size) * w - w;
}
vec2 overlay_transform(const vec2 position, const vec2 inv_half_size)
{
    
    
    return position * inv_half_size;
}
float clipw(const float w, const vec2 range, const float scale)
{
    return w * (step(unpack_scale(range.x), scale) - step(unpack_positive_value(range.y), scale));
}
vec2 rescale(const vec2 corner, const vec2 rescale, const vec2 scale_range, const float style_scale)
{
    
    
    if (scale_range.x < 0.)
    {
        float default_scale_denominator = unpack_positive_value(rescale.x);
        float rescale_coeff = unpack_positive_value(rescale.y);
        float min_scale = unpack_positive_value(-scale_range.x);
        float stretch_exponent = floor(0.5 + log2(
            max(1., 1. + rescale_coeff * (1. / max(min_scale, style_scale) - default_scale_denominator))));
        return corner.xy * exp2(stretch_exponent);
    }
    return corner;
}
`,ty=`
vec4 round_position(const vec4 position, const vec2 half_viewport)
{
    if (
        position.w < 0.
        || position.x < -position.w
        || position.x > position.w
        || position.y < -position.w
        || position.y > position.w
        || position.z < -position.w
        || position.z > position.w)
    {
        return position;
    }
    else
    {
        
        return vec4(
            sign(position.xy) * floor(abs(position.xy) * half_viewport / position.w + .5)
                * position.w / half_viewport,
            position.zw);
    }
}
`,iy=`#ifdef RENDER_SHADOWS
varying vec4 v_pos_from_light;
varying float v_depth_metric;
#ifndef UBO
uniform mat4 u_mat4_clip_to_shadow;
uniform mediump vec4 u_shadow_map_params;
uniform mediump float u_shadow_bias;
#endif
void compute_shadow_vertex(vec4 clip_pos)
{
    v_pos_from_light = u_mat4_clip_to_shadow * clip_pos;
    v_pos_from_light.z -= u_shadow_bias;
    v_depth_metric = 0.5 * v_pos_from_light.z + 0.5;
}
void compute_shadow_vertex(vec4 clip_pos, vec3 normal, mat4 mvp_mat)
{
    
    float normal_bias = u_shadow_map_params[3];
    vec3 norm_from_light = (u_mat4_clip_to_shadow * mvp_mat * vec4(normal, 0.0)).xyz;
    v_pos_from_light = u_mat4_clip_to_shadow * clip_pos;
    v_pos_from_light.xyz += normal_bias * normalize(norm_from_light);
    v_pos_from_light.z -= u_shadow_bias;
    v_depth_metric = 0.5 * v_pos_from_light.z + 0.5;
}
#else 
void compute_shadow_vertex(vec4 clip_pos) { }
void compute_shadow_vertex(vec4 clip_pos, vec3 normal, mat4 mvp_mat) { }
#endif `,ny=`
const float FADE_THRESHOLD = 0.06;
float interleaved_gradient_noise(vec3 coords)
{
    const vec3 m = vec3(0.06711056, 0.00583715, 52.9829189);
    return fract(m.z * fract(dot(coords.xy, m.xy)));
}
float apply_show_ratio(const float show_ratio, const vec3 instance_wp) {
    float noise = interleaved_gradient_noise(instance_wp);
    float threshold_range = 1. - FADE_THRESHOLD * 2.;
    float adjusted_noise = FADE_THRESHOLD + noise * threshold_range;
    float opacity = (show_ratio - adjusted_noise + FADE_THRESHOLD) / (FADE_THRESHOLD * 2.);
    return clamp(opacity, 0.0, 1.0); 
}
`,ry=`struct PolylineDistance
{
    
    float vertex_distance_from_start;
    
    float segment_distance_from_start;
    
    float total_length;
};
struct StripedLineInParams
{
    float dash_length;
    float space_length;
    float dash2_length;
    float line_width;
};
struct StripedLineOutParams
{
    
    float part_color_swap_threshold;
    float distance_in_parts;
};
void calculate_line_params(in PolylineDistance polyline_distance, in StripedLineInParams striped_line_params, out StripedLineOutParams line_params)
{
    
    float requested_part_length =
        striped_line_params.dash_length
        + striped_line_params.space_length;
    
    float space2_length = requested_part_length - striped_line_params.dash2_length;
    
    float part_count = max(
        floor(polyline_distance.total_length / requested_part_length + 0.5),
        1.0);
    
    float part_length = polyline_distance.total_length / part_count;
    
    float dash_length = (part_length / requested_part_length) * striped_line_params.dash2_length;
    float part_color_swap_threshold = dash_length / part_length;
    
    
    float segment_start = fract((polyline_distance.segment_distance_from_start + 0.5 * dash_length) / part_length);
    float vertex_normalized_distance = segment_start + polyline_distance.vertex_distance_from_start / part_length;
    line_params = StripedLineOutParams(
        part_color_swap_threshold,
        vertex_normalized_distance);
}
`,sy=`uniform bool u_bool_surface_use_abs_z;
uniform float u_float_surface_relative_z_norm;
uniform float u_float_surface_abs_z;
bool resolved_surface_uses_abs_z() {
    return u_bool_surface_use_abs_z;
}
float resolved_surface_abs_height() {
    return abs_height(u_float_surface_abs_z);
}
float resolved_surface_height(vec2 dem_position) {
    float base = resolved_surface_uses_abs_z() ? resolved_surface_abs_height()
                                               : dem_height(dem_position);
    return base + u_float_surface_relative_z_norm;
}
float add_resolved_surface_relative_height(float base) {
    return base + u_float_surface_relative_z_norm;
}
`,oy=`#include <prelude>
#include <mvp_mat>
#include <packed_attributes>
#include <pixel_offset>
#include <signed_distance_functions>
#include <arrow_functions>
#include <calculate_scale>
#include <apply_opacity>
#include <pos_world>
#include <cam_pos>
#include <fog>
#ifndef UBO
uniform float u_float_border_width_offset;
uniform vec2 u_vec2_scale_limits;
uniform mediump vec2 u_vec2_vpt_size;
#endif
uniform vec4 u_vec4_color;
uniform vec4 u_vec4_border_color;
uniform vec3 u_vec3_projection_scale_style_scale_dpi;
uniform float u_float_width_zpt;
uniform float u_float_wing_height_multiplier;
uniform float u_float_wing_width_multiplier;
uniform float u_float_border_width_zpt;
uniform float u_float_size_factor;
uniform float u_float_tip_height_multiplier;
uniform float u_float_relative_end_position;
uniform float u_float_tip_movement_amplitude;
uniform float u_float_vertex_shift; 
uniform float u_float_opacity;
uniform float u_float_tip_radius_zpt;
uniform float u_float_wing_radius_zpt;
uniform float u_float_tail_radius_zpt;
attribute vec2 a_vec2_vertex;
attribute vec2 a_vec2_segment_end;
attribute vec4 a_vec4_texture_widen_arrow_widen;
attribute vec2 a_vec2_widen;
attribute vec2 a_vec2_direction; 
attribute float a_float_distance_from_start;
attribute float a_float_object_length;
attribute float a_float_type;
attribute vec4 a_vec4_identifier; 
varying vec2 v_vec2_line_type_arrow_tail;
varying vec4 v_vec4_arrow_width_length_border_outer;
varying vec4 v_vec4_texcoord_arrow_line;
varying vec4 v_vec4_distance_vertex_hiding;
varying vec4 v_vec4_identifier;
varying vec4 v_vec4_color;
varying vec4 v_vec4_border_color;
#ifdef ENTRANCE_ARROWS_ROUNDING
varying vec3 v_vec3_radius_tip_wing_tail;
#endif
varying vec4 v_vec4_circle_center_tip_wing;
const float g_w_factor = 1e-7;
const float g_type_line = 0.;
const float g_type_arrow = 1.;
const float g_type_start_border = 2.;
const float g_type_line_ending = 3.;
const float g_type_line_cut = 4.;
const float g_shift_pixels = 2.;
const float g_line_overlapping_part = .2;
struct ArrowLineViewParameters
{
    float vertex_type;
    float width_zpt;
    float border_width_zpt;
    float border_width_offset;
    float tip_radius_zpt;
    float wing_radius_zpt;
    float tail_radius_zpt;
    float arrow_segment_length_zpt;
    float tip_height_multiplier;
    float wing_height_multiplier;
    float wing_width_multiplier;
    float size_factor;
    vec2 vertex_position;
    vec2 vertex_widen;
    vec2 line_texture_widen;
    vec2 arrow_texture_widen;
    vec2 segment_direction;
    float segment_length;
    float distance_to_end;
};
struct DistanceShiftParameters
{
    float shift;
    bool invisible;
};
vec2 perp(const vec2 vector)
{
    return vec2(-vector.y, vector.x);
}
vec2 vertex_shift(const Scale scale)
{
    return u_float_vertex_shift * u_float_tip_movement_amplitude * normalize_s08(a_vec2_direction) * scale.calculation;
}
vec2 arrow_shift(const ArrowLineViewParameters view)
{
    
    
    
    return view.segment_direction * view.distance_to_end;
}
float erase_length_end()
{
    return clamp(u_float_relative_end_position, 0., 1.) * a_float_object_length;
}
void set_texcoord_varyings(const vec2 arrow_texcoord, const vec2 line_texcoord)
{
    v_vec4_texcoord_arrow_line = vec4(arrow_texcoord, line_texcoord);
}
void set_arrow_varyings(
    const float arrow_width,
    const float arrow_length,
    const float arrow_border,
    const float arrow_outer_width,
    const float arrow_tail_hide_part,
    const float arrow_tip_radius,
    const float arrow_wing_radius,
    const float tail_radius,
    const vec2 tip_circle_center,
    const vec2 wing_circle_center)
{
    v_vec4_arrow_width_length_border_outer = vec4(
        arrow_width,
        arrow_length,
        arrow_border,
        arrow_outer_width);
    v_vec2_line_type_arrow_tail = vec2(
        a_float_type,
        arrow_tail_hide_part);
    #ifdef ENTRANCE_ARROWS_ROUNDING
    v_vec3_radius_tip_wing_tail = vec3(
        arrow_tip_radius,
        arrow_wing_radius,
        tail_radius);
    #endif
    v_vec4_circle_center_tip_wing = vec4(tip_circle_center.xy, wing_circle_center.xy);
}
DistanceShiftParameters calculate_entrance_arrow_distances(
    const ArrowLineViewParameters view,
    const float signed_distance_shift,
    const float arrow_final_size,
    const float entrance_arrow_distance_shift)
{
    DistanceShiftParameters line_distance_parameters = DistanceShiftParameters(
        signed_distance_shift + entrance_arrow_distance_shift,
        false);
    if (a_float_type == g_type_arrow)
    {
        
        
        bool outside_of_current_segment = view.distance_to_end > view.segment_length + entrance_arrow_distance_shift;
        
        bool inside_end_hide = a_float_distance_from_start + entrance_arrow_distance_shift > erase_length_end();
        return DistanceShiftParameters(
            
            line_distance_parameters.shift + view.distance_to_end,
            outside_of_current_segment || inside_end_hide
        );
    }
    else
    {
        return line_distance_parameters;
    }
}
void set_distance_varyings(
    const ArrowLineViewParameters view,
    const float arrow_final_size,
    const float signed_shift_distance)
{
    float entrance_arrow_distance_shift = arrow_final_size * (2. - g_line_overlapping_part);
    DistanceShiftParameters distance_shift_parameters = calculate_entrance_arrow_distances(
        view,
        signed_shift_distance,
        arrow_final_size,
        entrance_arrow_distance_shift);
    v_vec4_distance_vertex_hiding =
        vec4(
            a_float_distance_from_start + distance_shift_parameters.shift,
            0.,
            erase_length_end(),
            distance_shift_parameters.invisible
                ? a_float_object_length
                : 0.
        ) / a_float_object_length;
}
ArrowLineViewParameters decode_arrow_line_view_parameters()
{
    float width_zpt = u_float_width_zpt;
    float border_width_zpt = u_float_border_width_zpt;
    float arrow_segment_length_zpt = width_zpt * u_float_tip_height_multiplier + border_width_zpt;
    float vertex_type = a_float_type;
    
    vec2 segment_direction = (vertex_type == g_type_line_ending || vertex_type == g_type_line_cut)
        ? normalize(a_vec2_vertex - a_vec2_segment_end)
        : normalize(a_vec2_segment_end - a_vec2_vertex);
    float segment_length = length(a_vec2_segment_end - a_vec2_vertex);
    float distance_to_end = erase_length_end() - a_float_distance_from_start;
    return ArrowLineViewParameters(
        vertex_type,
        width_zpt,
        border_width_zpt,
        u_float_border_width_offset,
        u_float_tip_radius_zpt,
        u_float_wing_radius_zpt,
        u_float_tail_radius_zpt,
        arrow_segment_length_zpt,
        u_float_tip_height_multiplier,
        u_float_wing_height_multiplier,
        u_float_wing_width_multiplier,
        u_float_size_factor,
        a_vec2_vertex,
        unpack_widen(a_vec2_widen),
        unpack_widen(a_vec4_texture_widen_arrow_widen.xy),
        unpack_widen(a_vec4_texture_widen_arrow_widen.zw),
        segment_direction,
        segment_length,
        distance_to_end);
}
vec4 process_arrow_line_vertex(const Scale scale, const mat4 mvp, const vec2 vpt_size)
{
    ArrowLineViewParameters view = decode_arrow_line_view_parameters();
    
    ArrowParameters arrow_parameters = calculate_arrow_parameters(
        scale.calculation,
        view.width_zpt,
        view.border_width_zpt,
        view.arrow_segment_length_zpt,
        view.wing_width_multiplier,
        view.wing_height_multiplier,
        view.tip_height_multiplier,
        view.size_factor);
    vec2 vertex_widen = view.vertex_widen;
    vec2 texture_widen_with_sign = view.line_texture_widen;
    
    
    float shift_sign = sign(dot(vertex_widen, texture_widen_with_sign));
    vec2 line_texture_widen = shift_sign * texture_widen_with_sign;
    
    float line_final_size = (view.width_zpt + 2. * view.border_width_zpt) * view.size_factor * scale.calculation;
    float final_size = (view.vertex_type == g_type_arrow)
        ? arrow_parameters.final_size
        : line_final_size;
    
    
    
    
    vec2 line_texture_widen_perp = perp(line_texture_widen);
    float shift_distance = abs(dot(vertex_widen, line_texture_widen_perp)) * final_size;
    vec2 shift_direction = line_texture_widen_perp * sign(dot(vertex_widen, line_texture_widen_perp));
    vec2 line_vertex_shift = vertex_widen * final_size - shift_direction * max(0., shift_distance - .5 * view.segment_length);
    
    vec2 arrow_vertex_widen = vertex_widen * arrow_parameters.final_size;
    vec2 scene_vertex_shift = (view.vertex_type == g_type_arrow)
        ? arrow_vertex_widen
        : line_vertex_shift;
    vec2 arrow_position_shift = (view.vertex_type == g_type_arrow)
        ? arrow_shift(view)
        : vec2(0.);
    
    float shift_pixels = g_shift_pixels * sqrt(2.);
    VertexShiftParameters line_shift_parameters = calculate_vertex_shift_parameters(
        mvp,
        vpt_size,
        view.vertex_position + (vertex_shift(scale) + arrow_position_shift),
        scene_vertex_shift,
        shift_pixels);
    float arrow_line_texcoord_scale = line_final_size / arrow_parameters.final_size;
    float line_texcoord_scale = (view.vertex_type != g_type_arrow)
        ? arrow_line_texcoord_scale
        : 1.;
    vec2 line_texcoord = line_texture_widen * (1. + line_shift_parameters.limited_factor) * line_texcoord_scale;
    
    float arrow_texcoord_scale = (view.vertex_type == g_type_start_border)
        ? arrow_line_texcoord_scale
        : 1.;
    vec2 arrow_texcoord = view.arrow_texture_widen * (1. + line_shift_parameters.limited_factor) * arrow_texcoord_scale;
    set_texcoord_varyings(arrow_texcoord, line_texcoord);
    float arrow_width = view.width_zpt * arrow_parameters.zpt_to_texcoord_factor;
    float arrow_length = view.arrow_segment_length_zpt * arrow_parameters.zpt_to_texcoord_factor;
    float arrow_tip_radius = view.tip_radius_zpt * arrow_parameters.zpt_to_texcoord_factor;
    float arrow_wing_radius = view.wing_radius_zpt * arrow_parameters.zpt_to_texcoord_factor;
    float tail_radius = view.tail_radius_zpt * arrow_parameters.zpt_to_texcoord_factor;
    
    float texcoord_border_width = view.border_width_zpt * arrow_parameters.zpt_to_texcoord_factor;
    float border_width_texcoord_offset = view.border_width_offset * arrow_parameters.zpt_to_texcoord_factor;
    float arrow_border = max(0., texcoord_border_width - scale.style / scale.style_clamped * border_width_texcoord_offset);
    
    float tail_shift_direction = (view.vertex_type == g_type_line_ending || view.vertex_type == g_type_start_border) ? 1. : -1.;
    float tail_hide_shift = dot(arrow_vertex_widen, tail_shift_direction * view.segment_direction);
    float arrow_tail_hide_part = (view.distance_to_end - tail_hide_shift) * arrow_parameters.zpt_to_texcoord_factor / view.size_factor;
    
    
    float half_length = arrow_length / 2.;
    float arrow_height = arrow_width * (view.tip_height_multiplier - view.wing_height_multiplier);
    float A1 = arrow_parameters.tip_normal.x;
    float B1 = arrow_parameters.tip_normal.y;
    float C1 = -half_length * A1 - arrow_border + arrow_wing_radius;
    float A2 = arrow_parameters.wing_normal.x;
    float B2 = arrow_parameters.wing_normal.y;
    float C2 = (arrow_height - half_length) * A2 - arrow_border + arrow_wing_radius;
    float denominator = A1 * B2 - A2 * B1;
    float wing_circle_center_x = (C2 * B1 - C1 * B2) / denominator;
    float wing_circle_center_y = (A2 * C1 - A1 * C2) / denominator;
    vec2 wing_circle_center = vec2(wing_circle_center_x, wing_circle_center_y);
    vec2 tip_circle_center = vec2(half_length - (arrow_tip_radius - arrow_border) / arrow_parameters.tip_normal.x, 0.);
    set_arrow_varyings(
        arrow_width,
        arrow_length,
        arrow_border,
        arrow_parameters.outer_width,
        arrow_tail_hide_part,
        arrow_tip_radius,
        arrow_wing_radius,
        tail_radius,
        tip_circle_center,
        wing_circle_center);
    set_distance_varyings(
        view,
        arrow_parameters.final_size,
        shift_sign * shift_distance);
    
    
    return line_shift_parameters.clip_space_vertex / final_size;
}
void main()
{
    v_vec4_identifier = a_vec4_identifier; 
    Scale scale = calculate_scale(u_vec3_projection_scale_style_scale_dpi, u_vec2_scale_limits);
    vec4 processed_vertex = process_arrow_line_vertex(scale, u_mat4_mvp, u_vec2_vpt_size);
    gl_Position = processed_vertex * g_w_factor;
    v_vec4_color = apply_opacity(u_vec4_color, u_float_opacity);
    v_vec4_border_color = apply_opacity(u_vec4_border_color, u_float_opacity);
    
    vec3 pos_world = calc_pos_world(a_vec2_vertex);
    calc_fog_pos(pos_world);
}
`,ay=`#include <prelude>
#include <mvp_mat>
#include <dem>
#include <apply_height_factor>
uniform float u_float_height_factor;
uniform float u_float_floor_elevation;
attribute vec2 a_vec2_vertex;
attribute float a_float_z;
attribute vec2 a_vec2_dem_position;
attribute float a_float_visibility;
varying float v_depth_metric;
void main()
{
    
    if (a_float_visibility == 0.0) {
        gl_Position = vec4(0, 0, 1, 1);
        return;
    }
    
    float height = dem_height(unpack_dem_position(a_vec2_dem_position));
    
    if (a_float_z == 0.) {
        float posHeight = dem_height(a_vec2_vertex);
        if (height > posHeight) {
            height = posHeight;
        }
    }
    height += u_float_floor_elevation;
    vec4 vertex_hf = apply_height_factor(vec3(a_vec2_vertex, a_float_z), u_float_height_factor);
    vertex_hf.z += height;
    
    vertex_hf.z = max(vertex_hf.z, height);
    gl_Position = u_mat4_mvp * vertex_hf;
    v_depth_metric = (gl_Position.z + 1.0) / 2.0;
}`,ly=`#include <prelude>
#include <ecef_mvp_mat>
#include <pos_world>
#include <cam_pos>
#include <shadow>
#include <fog>
#include <dem>
attribute vec3 a_vec3_vertex;
attribute vec2 a_vec2_widen;
#ifndef UBO
uniform vec2 u_vec2_vpt_size;
#endif
uniform float u_float_width;
varying vec2 v_vec2_circle;
varying float v_float_width;
void main() {
    float height = dem_height(a_vec3_vertex.xy);
    vec4 pos = get_clipspace(a_vec3_vertex, a_vec3_vertex.z + height);
    vec4 ndc_position = pos / pos.w;
    ndc_position.xy += a_vec2_widen * u_float_width / u_vec2_vpt_size;
    gl_Position = ndc_position;
    v_vec2_circle = a_vec2_widen;
    v_float_width = u_float_width;
    vec3 pos_world = calc_pos_world(vec3(a_vec3_vertex.xy, a_vec3_vertex.z + height));
    calc_fog_pos(pos_world);
}
`,cy=`#include <prelude>
#include <ecef_mvp_mat>
#include <dem>
attribute vec3 a_vec3_vertex;
attribute vec2 a_vec2_widen;
attribute vec4 a_vec4_identifier;
#ifndef UBO
uniform vec2 u_vec2_vpt_size;
#endif
uniform float u_float_width;
varying vec2 v_vec2_circle;
varying vec4 v_vec4_identifier;
void main() {
    float height = dem_height(a_vec3_vertex.xy);
    v_vec2_circle = a_vec2_widen;
    v_vec4_identifier = a_vec4_identifier;
    if (vec4(1., 1., 1., 1.) != a_vec4_identifier)
    {
        vec4 pos = get_clipspace(a_vec3_vertex, a_vec3_vertex.z + height);
        vec4 ndc_position = pos / pos.w;
        ndc_position.xy += a_vec2_widen * u_float_width / u_vec2_vpt_size;
        gl_Position = ndc_position;
    }
    else
    {
        gl_Position = vec4(1., 1., 1., 1.);
    }
}
`,dy=`#include <prelude>
#include <ecef_mvp_mat>
#include <apply_opacity>
#include <pos_world>
#include <cam_pos>
#include <fog>
#include <jitter>
#include <shadow>
#include <mix_color_defs>
#include <packed_attributes>
uniform vec4 u_vec4_color;
uniform float u_float_opacity;
uniform float u_float_floor_elevation;
uniform vec4 u_vec4_tilecoords;
attribute vec3 a_vec3_vertex;
attribute float a_float_visibility;
varying vec4 v_vec4_color;
varying vec2 v_vec2_texcoord;
#ifdef MIX_COLOR_MODE
uniform vec4 u_vec4_color2;
varying vec4 v_vec4_color2;
# if MIX_COLOR_MODE == MIX_COLOR_MODE_READ_FROM_TARGET
varying vec4 v_vec4_pos;
# elif MIX_COLOR_MODE == MIX_COLOR_MODE_VERTEX_ATTRIBUTE
varying float v_float_mix_color_factor;
attribute float a_float_mix_factor;
# endif
#endif
varying vec3 v_vec3_fragment_pos_world;
void main()
{
#ifdef MIX_COLOR_MODE
# if MIX_COLOR_MODE == MIX_COLOR_MODE_READ_FROM_TARGET
    v_vec4_pos = vec4(0, 0, 0, 1);
# elif MIX_COLOR_MODE == MIX_COLOR_MODE_VERTEX_ATTRIBUTE
    v_float_mix_color_factor = a_float_mix_factor;
#  ifdef MIX_COLOR_MODE_VERTEX_ATTRIBUTE_NAME
#   if MIX_COLOR_MODE_VERTEX_ATTRIBUTE_NAME == VERTEX_ATTRIBUTE_NAME_DENORMALIZED_DISTANCE_TO_LINE
    v_float_mix_color_factor = unpack_denormalized_distance_to_line(a_float_mix_factor);
#   endif
#  endif
# endif
#endif
    if (a_float_visibility == 0.0) {
        gl_Position = vec4(0, 0, 0, 1);
        return;
    }
    v_vec4_color = apply_opacity(u_vec4_color, u_float_opacity);
#ifdef MIX_COLOR_MODE
    v_vec4_color2 = apply_opacity(u_vec4_color2, u_float_opacity);
#endif
    gl_Position = get_clipspace(a_vec3_vertex, u_float_floor_elevation);
    vec3 pos_world = calc_pos_world(vec3(a_vec3_vertex.xy, u_float_floor_elevation));
    calc_fog_pos(pos_world);
    
    
    
    
    
    
    
    v_vec2_texcoord = fract(abs((a_vec3_vertex.xy - 0.25) * 2.));
    v_vec3_fragment_pos_world = pos_world;
#ifdef TAA
    apply_vertex_jitter(gl_Position);
#endif
    compute_shadow_vertex(gl_Position, vec3(0.0, 0.0, 1.0), u_mat4_flat_mvp);
#ifdef MIX_COLOR_MODE
# if MIX_COLOR_MODE == MIX_COLOR_MODE_READ_FROM_TARGET
    v_vec4_pos = gl_Position;
# endif
#endif
}
`,uy=`#include <prelude>
#include <ecef_mvp_mat>
#include <round_position>
#ifndef UBO
uniform vec2 u_vec2_vpt_size;
#endif
uniform float u_float_floor_elevation;
uniform int u_int_is_3dfloor_object;
attribute vec3 a_vec3_vertex;
attribute vec4 a_vec4_identifier;
attribute float a_float_visibility;
varying vec4 v_vec4_identifier;
void main()
{
    v_vec4_identifier = a_vec4_identifier;
    if (vec4(1., 1., 1., 1.) != a_vec4_identifier && a_float_visibility != 0.0) {
        
        if (u_int_is_3dfloor_object == 0) {
            gl_Position = round_position(get_clipspace(a_vec3_vertex, u_float_floor_elevation), .5 * u_vec2_vpt_size);
        } else {
            gl_Position = get_clipspace(a_vec3_vertex, u_float_floor_elevation);
        }
    } else {
        gl_Position = vec4(1., 1., 1., 1.);
    }
}
`,hy=`#include <prelude>
#include <mvp_mat>
#include <packed_attributes>
attribute vec2 a_vec2_vertex;
attribute float a_float_height;
varying float v_float_height;
void main()
{
    gl_Position = u_mat4_mvp * vec4(a_vec2_vertex, 0.0, 1.0);
    v_float_height = a_float_height;
}
`,_y=`#include <prelude>
#include <mvp_mat>
#include <packed_attributes>
uniform mat4 u_mat4_dem_corrected;
attribute vec2 a_vec2_vertex;
attribute vec2 a_vec2_texcoord;
varying vec2 v_vec2_texcoord;
void main()
{
    gl_Position = u_mat4_mvp * vec4(a_vec2_vertex, 0.0, 1.0);
    v_vec2_texcoord = (u_mat4_dem_corrected * vec4(unpack_texcoord(a_vec2_texcoord), 0, 1)).xy;
}
`,fy=`#include <prelude>
#include <mvp_mat>
#include <dem>
attribute vec2 a_vec2_vertex;
attribute vec2 a_vec2_centroid;
attribute vec2 a_vec2_extender;
varying vec4 v_vec4_color;
void main()
{
    vec4 tex_pos = u_mat4_dem_corrected * u_mat4_mvp * vec4(unpack_dem_position(a_vec2_centroid), 0.0, 1.0);
    v_vec4_color = texture2D(u_tex_dem, tex_pos.xy);
    gl_Position = u_mat4_mvp * vec4(a_vec2_vertex + a_vec2_extender * 1./64., 0.0, 1.0);
}
`,my=`#include <prelude>
#include <mvp_mat>
#include <dem>
uniform mat4 u_mat4_model;
attribute vec2 a_vec2_position;
varying vec4 v_vec4_coords;
void main()
{
    vec4 tex_pos = u_mat4_dem_mvp * vec4(a_vec2_position, 0.0, 1.0);
    float height = dem_height_direct_meters(tex_pos.xy / tex_pos.w);
    float tile_height = meters_to_tile_height(height);
    gl_Position = u_mat4_mvp * vec4(a_vec2_position, tile_height, 1.0);
    v_vec4_coords = u_mat4_model * vec4(a_vec2_position, 0, 1.0);
    
    v_vec4_coords[2] = height;
}
`,vy=`#include <prelude>
#include <mvp_mat>
#include <dem>
uniform mat4 u_mat4_model;
attribute vec2 a_vec2_vertex;
attribute float a_float_height;
varying vec4 v_vec4_coords;
void main()
{
    float tile_height = meters_to_tile_height(a_float_height);
    gl_Position = u_mat4_mvp * vec4(a_vec2_vertex, tile_height, 1.0);
    v_vec4_coords = u_mat4_model * vec4(a_vec2_vertex, 0, 1.0);
    
    v_vec4_coords[2] = a_float_height;
}
`,gy=`#include <prelude>
#include <mvp_mat>
#include <dem>
#include <pos_world>
#include <cam_pos>
#include <shadow>
#include <fog>
#include <jitter>
uniform mat4 u_mat4_flat_map_mvp;
attribute vec2 a_vec2_position;
varying vec4 v_vec4_texcoord;
varying vec2 hs_tex_pos;
void main()
{
    vec4 coords = u_mat4_mvp * vec4(a_vec2_position, 0.0, 1.0);
    vec4 tex_pos = u_mat4_dem_mvp * vec4(a_vec2_position, 0.0, 1.0);
    float height = dem_height_direct(tex_pos.xy / tex_pos.w);
    gl_Position = u_mat4_mvp * vec4(a_vec2_position, height, 1.0);
    vec4 flat_coord = u_mat4_flat_map_mvp * vec4(a_vec2_position, 0.0, 1.0);
    v_vec4_texcoord = vec4(flat_coord.xy, 0., flat_coord.w);
    hs_tex_pos = tex_pos.xy;
    vec3 pos_world = calc_pos_world(vec4(a_vec2_position, height, 1.0));
    calc_fog_pos(pos_world);
#ifdef TAA
    apply_vertex_jitter(gl_Position);
#endif
    float eps = 1.0 / u_float_dem_resolution;
    float invW = 1.0 / tex_pos.w;
    vec2 uv = tex_pos.xy * invW;
    vec2 e = vec2(eps * invW, 0.0);
    float hL = dem_height_direct(uv - e.xy);
    float hR = dem_height_direct(uv + e.xy);
    float hD = dem_height_direct(uv - e.yx);
    float hU = dem_height_direct(uv + e.yx);
    vec3 dem_normal = normalize(vec3(hL - hR, hD - hU, 2.0 * eps));
    compute_shadow_vertex(gl_Position, dem_normal, u_mat4_mvp);
}
`,py=`#include <prelude>
#include <mvp_mat>
#include <dem>
#include <pos_world>
#include <cam_pos>
#include <shadow>
#include <fog>
#include <jitter>
uniform mat4 u_mat4_flat_map_mvp;
attribute vec2 a_vec2_vertex;
attribute float a_float_height;
varying vec4 v_vec4_texcoord;
varying vec3 v_vec3_position;
varying float v_height;
void main() {
    float height_tile = meters_to_tile_height(a_float_height);
    vec4 tex_pos = u_mat4_dem_mvp * vec4(a_vec2_vertex, 0.0, 1.0);
    gl_Position = u_mat4_mvp * vec4(a_vec2_vertex, height_tile, 1.0);
    vec4 flat_coord = u_mat4_flat_map_mvp * vec4(a_vec2_vertex, 0., 1.0);
    v_vec4_texcoord = vec4(flat_coord.xy, 1., flat_coord.w);
    vec3 pos_world = calc_pos_world(vec4(a_vec2_vertex, height_tile, 1.0));
    
    
    mat3 rotation_scale_mat = mat3(u_mat4_model);
    v_vec3_position = rotation_scale_mat * vec3(a_vec2_vertex, height_tile);
    calc_fog_pos(pos_world);
#ifdef TAA
    apply_vertex_jitter(gl_Position);
#endif
    float eps = 1.0 / u_float_dem_resolution;
    float invW = 1.0 / tex_pos.w;
    vec2 uv = tex_pos.xy * invW;
    vec2 e = vec2(eps * invW, 0.0);
    float hL = dem_height_direct(uv - e.xy);
    float hR = dem_height_direct(uv + e.xy);
    float hD = dem_height_direct(uv - e.yx);
    float hU = dem_height_direct(uv + e.yx);
    vec3 dem_normal = normalize(vec3(hL - hR, hD - hU, 2.0 * eps));
    compute_shadow_vertex(gl_Position, dem_normal, u_mat4_mvp);
    v_height = a_float_height;
}
`,xy=`#include <prelude>
#include <mvp_mat>
#include <dem>
attribute vec2 a_vec2_vertex;
attribute float a_float_height;
void main() {
    float height_tile = meters_to_tile_height(a_float_height);
    gl_Position = u_mat4_mvp * vec4(a_vec2_vertex, height_tile, 1.0);
}
`,by=`#include <prelude>
#include <mvp_mat>
#include <dem>
attribute vec2 a_vec2_vertex;
attribute float a_float_height;
varying float v_depth_metric;
void main()
{
    
    
    
    reset_dem_varyings();
    float height_tile = meters_to_tile_height(a_float_height);
    gl_Position = u_mat4_mvp * vec4(a_vec2_vertex, height_tile, 1.0);
    v_depth_metric = 0.5 * gl_Position.z + 0.5;
}
`,Sy=`#include <prelude>
#include <mvp_mat>
#include <packed_attributes>
attribute vec2 a_vec2_vertex;
attribute vec2 a_vec2_texcoord;
varying vec2 v_vec2_texcoord;
void main()
{
    gl_Position = vec4((a_vec2_vertex * 2. - vec2(1, 1)), 0.0, 1.0);
    v_vec2_texcoord = unpack_texcoord(a_vec2_texcoord);
}
`,yy=`#include <prelude>
#include <mvp_mat>
#include <dem>
#include <packed_attributes>
#include <apply_height_factor>
#include <apply_opacity>
#include <pos_world>
#include <cam_pos>
#include <fog>
#include <clipspace_pos>
#include <jitter>
#include <shadow>
uniform vec4 u_vec4_color;
uniform mat4 u_mat4_gradient;
uniform float u_float_height_factor;
uniform float u_float_opacity;
uniform float u_float_mix_color;
uniform float u_float_floor_elevation;
uniform int u_int_is_roof;
uniform int u_int_is_hole;
attribute vec2 a_vec2_vertex;
attribute float a_float_z;
attribute float a_float_elevation;
attribute vec2 a_vec2_dem_position;
attribute float a_float_visibility;
attribute vec4 a_vec4_color;
varying vec4 v_vec4_color;
varying mat4 v_mat4_gradient;
varying vec4 v_vec4_rotated_scaled_vertex;
const float g_wall_offset_isometric = .001;
const float g_wall_offset_perspective = 8.;
void main()
{
    
    if (a_float_visibility == 0.0) {
        gl_Position = vec4(0, 0, 1, 1);
        return;
    }
    float height = dem_height(unpack_dem_position(a_vec2_dem_position));
    
    if (a_float_z == 0.) {
        float posHeight = dem_height(a_vec2_vertex);
        if (u_int_is_hole == 1 || height > posHeight) {
            height = posHeight;
        }
    }
    height += u_float_floor_elevation;
    vec3 vertex = vec3(a_vec2_vertex, a_float_z);
    vec4 vertex_hf = apply_height_factor(vertex, u_float_height_factor);
    vertex_hf.z += height;
    if (u_int_is_hole == 0)
    {
        
        vertex_hf.z = max(vertex_hf.z, height);
    }
    vec4 clip_pos = u_mat4_mvp * vertex_hf;
    gl_Position = clip_pos;
    if (u_int_is_roof == 0 && u_int_is_hole == 0)
    {
        
        if ((u_mat4_mvp[0][3] == 0.) && (u_mat4_mvp[1][3] == 0.) && (u_mat4_mvp[2][3] == 0.))
        {
            gl_Position.z += g_wall_offset_isometric;
        }
        else
        {
            
            
            
            if (height == 0.) {
                gl_Position.z += g_wall_offset_perspective;
            } else {
                gl_Position.z += g_wall_offset_isometric;
            }
        }
    }
    vec3 pos_world = calc_pos_world(vertex_hf);
    calc_fog_pos(pos_world);
    save_clipspace_pos();
#ifdef TAA
    apply_vertex_jitter(gl_Position);
#endif
    
    
    mat3 rotation_scale_mat = mat3(u_mat4_model);
    v_vec4_rotated_scaled_vertex.xyz = rotation_scale_mat * vertex;
    v_vec4_color = apply_opacity(u_vec4_color, u_float_opacity);
    if (a_vec4_color[3] > 0. ) {
        v_vec4_color = apply_opacity( mix(v_vec4_color, a_vec4_color, u_float_mix_color), u_float_opacity);
    }
    if (u_mat4_gradient[0][0] !=0.)
    {
        
        
        if (u_int_is_hole == 1)
        {
            v_vec4_rotated_scaled_vertex.w = a_float_z < 0.0 ? 0. : 1.;
        }
            else
        {
            if (a_float_z > 0. && a_float_elevation == 0.) {
                v_vec4_rotated_scaled_vertex.w = 1.;
            } else {
                v_vec4_rotated_scaled_vertex.w = a_float_elevation;
            }
        }
        v_mat4_gradient = u_mat4_gradient;
        if (a_vec4_color[3] > 0. ) {
            v_mat4_gradient[1] = mix(v_mat4_gradient[1], a_vec4_color, u_float_mix_color);
            v_mat4_gradient[2] = mix(v_mat4_gradient[2], a_vec4_color, u_float_mix_color);
        }
        for (int i = 1; i <= 2; i++) {
            v_mat4_gradient[i] = apply_opacity(v_mat4_gradient[i], u_float_opacity);
        }
    }
    
    compute_shadow_vertex(clip_pos);
}
`,Ty=`#include <prelude>
#include <mvp_mat>
#include <dem>
#include <round_position>
#include <apply_height_factor>
#ifndef UBO
uniform vec2 u_vec2_vpt_size;
#endif
uniform float u_float_height_factor;
uniform float u_float_floor_elevation;
uniform int u_int_is_hole;
attribute vec2 a_vec2_vertex;
attribute float a_float_z;
attribute vec4 a_vec4_identifier;
attribute vec2 a_vec2_dem_position;
attribute float a_float_visibility;
varying vec4 v_vec4_identifier;
void main()
{
    
    
    
    if (a_float_visibility == 0.0 || a_vec4_identifier == vec4(1., 1., 1., 1.)) {
        gl_Position = vec4(0, 0, 1, 1);
        return;
    }
    float height = dem_height(unpack_dem_position(a_vec2_dem_position));
    
    if (a_float_z == 0.) {
        float posHeight = dem_height(a_vec2_vertex);
        if (u_int_is_hole == 1 || height > posHeight) {
            height = posHeight;
        }
    }
    height += u_float_floor_elevation;
    v_vec4_identifier = a_vec4_identifier;
    vec4 vertex_hf = apply_height_factor(vec3(a_vec2_vertex, a_float_z), u_float_height_factor);
    vertex_hf.z += height;
    if (u_int_is_hole == 0)
    {
        
        vertex_hf.z = max(vertex_hf.z, height);
    }
    gl_Position = round_position(
        u_mat4_mvp * vertex_hf,
        .5 * u_vec2_vpt_size);
}
`,Ey=`#include <prelude>
#ifndef UBO
uniform mediump vec2 u_vec2_halo_viewport_size;
uniform mediump vec2 u_vec2_halo_viewport_center_shift;
uniform mediump vec4 u_vec4_halo_radius_stops;
uniform mediump float u_float_halo_exp_factor;
#endif
attribute vec2 a_vec2_vertex;
varying vec2 v_vec2_uv;
void main() {
    
    
    
    
    
    
    
    float globe_halo_padding_factor = log(0.005) / u_float_halo_exp_factor;
    
    vec4 pixel_radius_stops = u_vec4_halo_radius_stops * u_vec2_halo_viewport_size.y;
    
    
    
    
    float maxR = pixel_radius_stops[1] + (pixel_radius_stops[3] - pixel_radius_stops[1]) * globe_halo_padding_factor;
    
    float scale = maxR / u_vec2_halo_viewport_size.y;
    v_vec2_uv = a_vec2_vertex * scale;
    vec2 center = u_vec2_halo_viewport_size / 2.0 + u_vec2_halo_viewport_center_shift;
    vec2 p = center - a_vec2_vertex * maxR;
    vec2 p_result = 2.0 * (p - 0.5 * u_vec2_halo_viewport_size) / u_vec2_halo_viewport_size;
    gl_Position = vec4(p_result, 0.0, 1.0);
}
`,Cy=`#include <prelude>
#include <ecef_mvp_mat>
#include <dem>
#include <surface_height>
#include <packed_attributes>
#include <pos_world>
#include <cam_pos>
#include <fog>
#include <clipspace_pos>
#include <jitter>
#include <shadow>
#include <show_ratio>
#define EPSILON (0.0001)
#define EPSILON2 (-0.000001)
#define DEM_POS_INSTANCE 0
#define DEM_POS_FLAT 1
#define DEM_POS_AXIS 2
#define DEM_POS_CENTROID 3
#define DEM_POS_POLYGON_ANCHOR 4
uniform mat4 u_mat4_instance;
uniform vec2 u_vec2_anchor;
uniform vec4 u_vec4_axis;
uniform int u_int_gltf_dem_pos;
uniform mat4 u_mat4_localmatrix;
uniform mat3 u_mat3_transform_tex_matrix;
uniform float u_float_height_factor;
uniform float u_float_show_ratio;
uniform vec3 u_vec3_scale_factor;
uniform mediump int u_int_identify;
uniform mediump int u_int_is_tiered;
uniform vec4 u_vec4_tier_color;
uniform float u_float_floor_elevation;
uniform int u_int_abs_z;
uniform int u_int_extention_to_relief_needed;
uniform int u_int_collapse_height_needed;
uniform int u_int_is_extendable_to_relief_foundation;
#ifdef VAT_TEXTURE
uniform sampler2D u_sampler_vat;
uniform float u_float_vat_frame;
uniform float u_float_vat_texture_height;
uniform vec3 u_vec3_vat_min;
uniform vec3 u_vec3_vat_max;
#endif
attribute vec3 a_position;
attribute vec3 a_normal;
attribute vec2 a_tangent;
#ifdef VAT_TEXTURE
attribute vec2 texcoord_vat;
#endif
attribute vec3 a_vec3_instance_position;
attribute float a_float_instance_height;
#ifndef MALI_GPU
attribute float a_float_abs_z;
#endif
attribute mat3 a_mat3_instance_matrix;
attribute vec4 a_vec4_instance_localid;
#ifdef COLOR_TEXTURE
attribute vec2 texcoord_color;
#endif
#ifdef AO_TEXTURE
attribute vec2 texcoord_ao;
#endif
#ifdef PBR_TEXTURE
attribute vec2 texcoord_pbr;
#endif
varying vec4 v_vec4_identifier;
varying vec3 v_vec3_normal;
varying vec3 v_vec3_fragment_pos_world;
#ifdef MAP_MESH_TEXTURE
varying vec4 v_tex_coord;
#endif
#ifdef COLOR_TEXTURE
varying vec2 v_vec2_texcoord_color;
#endif
#ifdef AO_TEXTURE
varying vec2 v_vec2_texcoord_ao;
#endif
#ifdef PBR_TEXTURE
varying vec2 v_vec2_texcoord_pbr;
#endif
varying float v_float_opacity;
void calc_texcoords(mat4 instance_matrix, float height) {
    #ifdef MAP_MESH_TEXTURE
    
    vec4 vertexTier = instance_matrix * vec4(a_position, 1.);
    vertexTier *= u_mat4_instance;
    vertexTier.xyz *= u_vec3_scale_factor;
    vertexTier.z *= u_float_height_factor;
    vertexTier.xyz *= v_float_opacity;
    vec4 vflatTier = vec4(a_vec3_instance_position.xy,a_float_instance_height, 1.);
    vflatTier.z += height;
    vflatTier.xyz += vertexTier.xyz;
    v_tex_coord = u_mat4_flat_mvp * vec4(vflatTier.xy, 0, 1.0);
    #endif
    #if defined(COLOR_TEXTURE)
    vec2 uvTransformed = ( u_mat3_transform_tex_matrix * vec3(texcoord_color, 1) ).xy;
    v_vec2_texcoord_color = uvTransformed;
    #endif
    #ifdef AO_TEXTURE
    v_vec2_texcoord_ao = texcoord_ao;
    #endif
    #ifdef PBR_TEXTURE
    v_vec2_texcoord_pbr = texcoord_pbr;
    #endif
}
void main()
{
    if (u_int_identify != 0 && a_vec4_instance_localid == vec4(1., 1., 1., 1.)) {
        gl_Position = vec4(0, 0, 0, 0);
        return;
    }
#ifdef VAT_TEXTURE
    
    
    
    
    vec2 vat_uv = vec2(texcoord_vat.x, texcoord_vat.y + u_float_vat_frame / u_float_vat_texture_height);
    vec3 vat_sample = texture2D(u_sampler_vat, vat_uv).xyz;
    vec3 vat_delta = u_vec3_vat_min + vat_sample * (u_vec3_vat_max - u_vec3_vat_min);
    vec3 position = a_position + vec3(vat_delta.x, vat_delta.z, -vat_delta.y);
    vec3 vat_raw_nrm = texture2D(u_sampler_vat, vat_uv + vec2(0., 0.5)).xyz * 2.0 - 1.0;
    vec3 normal = normalize(vec3(vat_raw_nrm.x, vat_raw_nrm.z, -vat_raw_nrm.y));
#else
    vec3 position = a_position;
    vec3 normal = a_normal;
#endif
    mat4 instance_matrix = mat4(
        vec4(a_mat3_instance_matrix[0], 0),
        vec4(a_mat3_instance_matrix[1], 0),
        vec4(a_mat3_instance_matrix[2], 0),
        vec4(0, 0, 0, 1)
    );
    mat4 instance_model_matrix = instance_matrix * u_mat4_localmatrix;
    float height = 0.;
    if (resolved_surface_uses_abs_z()) {
        
        
        height = resolved_surface_abs_height();
    } else if (u_int_gltf_dem_pos == DEM_POS_CENTROID) {
        vec4 center = instance_model_matrix * vec4(u_vec2_anchor.x, 0, u_vec2_anchor.y, 1);
        center *= u_mat4_instance;
        center.xy += a_vec3_instance_position.xy;
        height = dem_height(center.xy);
    } else if (u_int_gltf_dem_pos == DEM_POS_AXIS)  {
        vec2 a = position.xz - u_vec4_axis.xy;
        vec2 b = u_vec4_axis.zw - u_vec4_axis.xy;
        float b_length = length(b);
        a /= b_length;
        b /= b_length;
        float coef = clamp(dot(a, b), 0., 1.);
        vec4 axis_start = instance_model_matrix * vec4(u_vec4_axis.x, 0, u_vec4_axis.y, 1);
        axis_start *= u_mat4_instance;
        axis_start.xy += a_vec3_instance_position.xy;
        float height_start = dem_height(axis_start.xy);
        vec4 axis_end = instance_model_matrix * vec4(u_vec4_axis.z, 0, u_vec4_axis.w, 1);
        axis_end *= u_mat4_instance;
        axis_end.xy += a_vec3_instance_position.xy;
        float height_end = dem_height(axis_end.xy);
        height = mix(height_start, height_end, coef);
    } else if (u_int_gltf_dem_pos == DEM_POS_FLAT) {
        vec4 pos = instance_model_matrix * vec4(position, 1);
        pos *= u_mat4_instance;
        pos.xy += a_vec3_instance_position.xy;
        height = dem_height(pos.xy);
    } else if (u_int_gltf_dem_pos == DEM_POS_POLYGON_ANCHOR) {
        
        height = dem_height(u_vec2_anchor);
    } else {
#ifdef MALI_GPU
        
        
        height = dem_height(a_vec3_instance_position.xy);
#else
        if (u_int_abs_z == 0) {
            height = dem_height(a_vec3_instance_position.xy);
        } else {
            height = abs_height(a_float_abs_z);
        }
#endif
    }
    
    height = add_resolved_surface_relative_height(height);
    height += u_float_floor_elevation;
    vec3 instance_position = vec3(a_vec3_instance_position.xy, a_float_instance_height);
    if (u_float_show_ratio < 1.0) {
        vec3 instance_wp = a_mat3_instance_matrix * instance_position;
        v_float_opacity = apply_show_ratio(u_float_show_ratio, instance_wp);
    } else {
        v_float_opacity = 1.;
    }
    if (u_int_identify == 1) {
        v_vec4_identifier = a_vec4_instance_localid;
    } else {
        v_vec4_identifier = u_int_is_tiered == 1 ? u_vec4_tier_color : a_vec4_instance_localid;
    }
    vec4 vertex = instance_model_matrix * vec4(position, 1.);
    vertex *= u_mat4_instance;
    vertex.xyz *= u_vec3_scale_factor;
    vertex.xyz *= v_float_opacity;
    vertex.z *= u_float_height_factor;
#ifndef MALI_GPU
    if (u_int_is_extendable_to_relief_foundation == 1) {
        
        
        
        vec4 pos = instance_model_matrix * vec4(position, 1);
        pos *= u_mat4_instance;
        pos.xy += a_vec3_instance_position.xy;
        float local_relief = dem_height(pos.xy);
        
        
        
        
        if (vertex.z < EPSILON2) {
            float delta = local_relief - height;
            vertex.z += min(delta, 0.0);
        }
    }
    if (u_int_abs_z == 1) {
        bool is_base = vertex.z < EPSILON;
        if (is_base) {
            
            
            if (u_int_extention_to_relief_needed == 1) {
                float relief_height = dem_height(a_vec3_instance_position.xy);
                vertex.z -= abs_height(a_float_abs_z) - relief_height;
            }
        } else {
            
            
            if (u_int_collapse_height_needed == 1) {
                vertex.z = 0.;
            }
        }
    }
#endif
    vec4 vflat = vec4(instance_position, 1.);
    vflat.z += height;
    vflat.xyz += vertex.xyz;
    vec3 pos_world = calc_pos_world(vflat);
    calc_fog_pos(pos_world);
#ifdef MALI_GPU
    
    
    
    gl_Position = u_mat4_flat_mvp * vec4(vflat.xyz, 1.);
#else
    
    if (is_flat_mode()) {
        gl_Position = get_clipspace(vflat.xyz);
    } else {
        gl_Position = get_clipspace_from_ecef_u16(a_vec3_instance_position, vertex.xyz, a_float_abs_z);
    }
#endif
    calc_texcoords(instance_matrix, height);
    
    v_vec3_normal = (instance_model_matrix * vec4(normal, 0)).xyz;
    v_vec3_fragment_pos_world = pos_world;
#ifdef TAA
    apply_vertex_jitter(gl_Position);
#endif
    save_clipspace_pos();
    compute_shadow_vertex(gl_Position, v_vec3_normal, u_mat4_flat_mvp);
}
`,Iy=`#include <prelude>
#include <ecef_mvp_mat>
#include <dem>
#include <surface_height>
#include <packed_attributes>
#include <show_ratio>
#define EPSILON (0.0001)
#define EPSILON2 (-0.000001)
#define DEM_POS_FLAT 1
#define DEM_POS_AXIS 2
#define DEM_POS_CENTROID 3
#define DEM_POS_POLYGON_ANCHOR 4
uniform mat4 u_mat4_instance;
uniform mat4 u_mat4_localmatrix;
uniform float u_float_height_factor;
uniform float u_float_show_ratio;
uniform vec3 u_vec3_scale_factor;
uniform int u_int_abs_z;
uniform int u_int_extention_to_relief_needed;
uniform int u_int_collapse_height_needed;
uniform int u_int_is_extendable_to_relief_foundation;
uniform int u_int_gltf_dem_pos;
uniform vec2 u_vec2_anchor;
uniform vec4 u_vec4_axis;
uniform float u_float_floor_elevation;
#ifdef VAT_TEXTURE
uniform sampler2D u_sampler_vat;
uniform float u_float_vat_frame;
uniform float u_float_vat_texture_height;
uniform vec3 u_vec3_vat_min;
uniform vec3 u_vec3_vat_max;
#endif
attribute vec3 a_position;
#ifdef VAT_TEXTURE
attribute vec2 texcoord_vat;
#endif
attribute vec3 a_vec3_instance_position;
attribute float a_float_instance_height;
#ifndef MALI_GPU
attribute float a_float_abs_z;
#endif
attribute mat3 a_mat3_instance_matrix;
varying float v_depth_metric;
void main()
{
#ifdef VAT_TEXTURE
    
    vec2 vat_uv = vec2(texcoord_vat.x, texcoord_vat.y + u_float_vat_frame / u_float_vat_texture_height);
    vec3 vat_sample = texture2D(u_sampler_vat, vat_uv).xyz;
    vec3 vat_delta = u_vec3_vat_min + vat_sample * (u_vec3_vat_max - u_vec3_vat_min);
    vec3 position = a_position + vec3(vat_delta.x, vat_delta.z, -vat_delta.y);
#else
    vec3 position = a_position;
#endif
    mat4 instance_matrix = mat4(
        vec4(a_mat3_instance_matrix[0], 0),
        vec4(a_mat3_instance_matrix[1], 0),
        vec4(a_mat3_instance_matrix[2], 0),
        vec4(0, 0, 0, 1)
    );
    mat4 instance_model_matrix = instance_matrix * u_mat4_localmatrix;
    float height = 0.;
    if (resolved_surface_uses_abs_z()) {
        
        
        height = resolved_surface_abs_height();
    } else if (u_int_gltf_dem_pos == DEM_POS_CENTROID) {
       vec4 center = instance_model_matrix * vec4(u_vec2_anchor.x, 0, u_vec2_anchor.y, 1);
       center *= u_mat4_instance;
       center.xy += a_vec3_instance_position.xy;
       height = dem_height(center.xy);
    } else if (u_int_gltf_dem_pos == DEM_POS_AXIS)  {
       vec2 a = position.xz - u_vec4_axis.xy;
       vec2 b = u_vec4_axis.zw - u_vec4_axis.xy;
       float b_length = length(b);
       a /= b_length;
       b /= b_length;
       float coef = clamp(dot(a, b), 0., 1.);
       vec4 axis_start = instance_model_matrix * vec4(u_vec4_axis.x, 0, u_vec4_axis.y, 1);
       axis_start *= u_mat4_instance;
       axis_start.xy += a_vec3_instance_position.xy;
       float height_start = dem_height(axis_start.xy);
       vec4 axis_end = instance_model_matrix * vec4(u_vec4_axis.z, 0, u_vec4_axis.w, 1);
       axis_end *= u_mat4_instance;
       axis_end.xy += a_vec3_instance_position.xy;
       float height_end = dem_height(axis_end.xy);
       height = mix(height_start, height_end, coef);
    } else if (u_int_gltf_dem_pos == DEM_POS_FLAT) {
       vec4 pos = instance_model_matrix * vec4(position, 1);
       pos *= u_mat4_instance;
       pos.xy += a_vec3_instance_position.xy;
       height = dem_height(pos.xy);
    } else if (u_int_gltf_dem_pos == DEM_POS_POLYGON_ANCHOR) {
       
       height = dem_height(u_vec2_anchor);
    } else {
#ifdef MALI_GPU
        height = dem_height(a_vec3_instance_position.xy);
#else
        if (u_int_abs_z == 0) {
            height = dem_height(a_vec3_instance_position.xy);
        } else {
            height = abs_height(a_float_abs_z);
        }
#endif
    }
    
    height = add_resolved_surface_relative_height(height);
    height += u_float_floor_elevation;
    vec3 instance_position = vec3(a_vec3_instance_position.xy, a_float_instance_height);
    float opacity = 1.0;
    if (u_float_show_ratio < 1.0) {
        vec3 instance_wp = a_mat3_instance_matrix * instance_position;
        opacity = apply_show_ratio(u_float_show_ratio, instance_wp);
    }
    vec4 vertex = instance_model_matrix * vec4(position, 1.);
    vertex *= u_mat4_instance;
    vertex.xyz *= u_vec3_scale_factor;
    vertex.xyz *= opacity;
    vertex.z *= u_float_height_factor;
#ifndef MALI_GPU
    if (u_int_is_extendable_to_relief_foundation == 1) {
        
        
        
        vec4 pos = (instance_matrix * u_mat4_localmatrix) * vec4(position, 1);
        pos *= u_mat4_instance;
        pos.xy += a_vec3_instance_position.xy;
        float local_relief = dem_height(pos.xy);
        
        
        
        
        if (vertex.z < EPSILON2) {
            float delta = local_relief - height;
            vertex.z += min(delta, 0.0);
        }
    }
    if (u_int_abs_z == 1) {
        bool is_base = vertex.z < EPSILON;
        if (is_base) {
            
            
            if (u_int_extention_to_relief_needed == 1) {
                float relief_height = dem_height(a_vec3_instance_position.xy);
                vertex.z -= abs_height(a_float_abs_z) - relief_height;
            }
        } else {
            
            
            if (u_int_collapse_height_needed == 1) {
                vertex.z = 0.;
            }
        }
    }
#endif
    vec4 vflat = vec4(instance_position, 1.);
    vflat.z += height;
    vflat.xyz += vertex.xyz;
#ifdef MALI_GPU
    
    
    
    gl_Position = u_mat4_flat_mvp * vec4(vflat.xyz, 1.);
#else
    
    if (is_flat_mode()) {
        gl_Position = get_clipspace(vflat.xyz);
    } else {
        gl_Position = get_clipspace_from_ecef_u16(a_vec3_instance_position, vertex.xyz, a_float_abs_z);
    }
#endif
    v_depth_metric = (gl_Position.z + 1.0) / 2.0;
}
`,Py=`#include <prelude>
#include <mvp_mat>
#include <pos_world>
#include <cam_pos>
#include <fog>
attribute vec2 a_vec2_position;
attribute vec2 a_vec2_widen;
attribute float a_float_weight;
varying vec2 v_vec2_extrude;
varying float v_float_weight;
uniform float u_float_radius;
uniform float u_float_intensity;
uniform float u_float_tile_to_pixel_ratio;
const highp float ZERO = 1.0 / 255.0 / 16.0;
#define GAUSS_COEF 0.3989422804014327
void main(void) {
    float S = sqrt(-2.0 * log(ZERO / a_float_weight / u_float_intensity / GAUSS_COEF)) / 3.0;
    v_vec2_extrude = S * a_vec2_widen;
    v_float_weight = a_float_weight;
    vec2 pos = a_vec2_position + a_vec2_widen * u_float_radius * u_float_tile_to_pixel_ratio;
    calc_fog_pos(calc_pos_world(pos));
    gl_Position = u_mat4_mvp * vec4(pos, 0.0, 1.0);
}
`,Ay=`#include <prelude>
#include <pos_world>
#include <cam_pos>
#include <fog>
attribute vec2 a_vec2_position;
varying vec2 v_vec2_position;
void main() {
    gl_Position = vec4(a_vec2_position, 0.0, 1.0);
    v_vec2_position = clamp(a_vec2_position, vec2(0,0), vec2(1,1));
}
`,Ly=`#include <prelude>
#include <mvp_mat>
#include <packed_attributes>
#include <pos_world>
#include <cam_pos>
#include <fog>
attribute vec4 a_vec4_position;
attribute vec2 a_vec2_offset;
attribute vec2 a_vec2_texcoord;
attribute vec2 a_vec2_style_zoom_limits;
uniform float u_float_style_zoom;
uniform float u_float_scale;
uniform float u_float_tile_to_pixel_ratio;
varying vec2 v_vec2_texcoord;
float clipw(const float w, const vec2 range, const float zoom) {
    return w * (step(range.x, zoom) - step(range.y, zoom));
}
void main() {
    vec4 newPosition = a_vec4_position;
    newPosition.xy += a_vec2_offset * u_float_scale * u_float_tile_to_pixel_ratio;
    vec3 pos_world = calc_pos_world(newPosition);
    calc_fog_pos(pos_world);
    newPosition = u_mat4_mvp * newPosition;
    gl_Position = vec4(newPosition.xyz, clipw(newPosition.w, a_vec2_style_zoom_limits, u_float_style_zoom));
    v_vec2_texcoord = unpack_texcoord(a_vec2_texcoord);
}
`,Ry=`#include <prelude>
#include <mvp_mat>
#include <packed_attributes>
#include <pos_world>
#include <cam_pos>
#include <fog>
#include <dem>
#include <depth_test>
attribute float a_float_center_offset;
attribute vec2 a_vec2_texcoord;
attribute vec2 a_vec2_corner_offset;
attribute float a_float_glyph_height_offset;
attribute vec2 a_vec2_anchor_params;
attribute vec2 a_vec2_guideline_params;
attribute vec4 a_vec4_identifier;
#ifndef UBO
uniform vec2 u_vec2_vpt_size;
#endif
uniform mediump int u_int_depth_test;
uniform float u_float_scale;
uniform float u_float_center_distance;
uniform highp sampler2D u_sr2d_texture1;
uniform vec2 u_vec2_guideline_tex_size;
varying float v_float_behind_factor;
varying vec4 v_vec4_identifier;
varying vec2 v_vec2_texcoord;
varying float v_float_perspective_scale;
const int MAX_GUIDELINE_STEPS = 2048;
const float MIN_CLIP_W = 1000.;
const float MIN_INV_W = 1e-12;
const float PERSPECTIVE_STRENGTH = 0.5;
const float MIN_PERSPECTIVE_SCALE = 0.5;
const float MAX_PERSPECTIVE_SCALE = 1.5;
const float DEPTH_TEST_INSET = 0.5;
vec3 read_guideline_vertex(const float vertex_index) {
    vec2 texcoord = (vec2(vertex_index, a_vec2_guideline_params.x) + 0.5) / u_vec2_guideline_tex_size;
    vec4 texel = texture2D(u_sr2d_texture1, texcoord);
    
    
    return vec3(texel.xy, texel.z + abs_height(texel.w));
}
vec2 clip_to_screen(const vec2 clip_xy, const float inv_w) {
    return (clip_xy * inv_w * 0.5 + 0.5) * u_vec2_vpt_size;
}
struct ProjectedVertex {
    
    vec4 clip;
    
    vec3 vertex;
    
    vec2 screen;
    
    
    float inv_w;
    
    float ndc_z;
    
    bool valid;
};
ProjectedVertex project_vertex(const vec3 vertex) {
    vec4 clip = u_mat4_mvp * vec4(vertex, 1.0);
    bool valid = clip.w > MIN_CLIP_W;
    float inv_w = valid ? 1.0 / clip.w : 0.0;
    return ProjectedVertex(
        clip,
        vertex,
        valid ? clip_to_screen(clip.xy, inv_w) : vec2(0.0),
        inv_w,
        clip.z * inv_w,
        valid);
}
ProjectedVertex project_guideline_vertex(const float vertex_index) {
    return project_vertex(read_guideline_vertex(vertex_index));
}
ProjectedVertex interpolate_vertex(ProjectedVertex valid_vertex, ProjectedVertex invalid_vertex) {
    float delta = (MIN_CLIP_W - invalid_vertex.clip.w) / (valid_vertex.clip.w - invalid_vertex.clip.w);
    vec4 clip = mix(invalid_vertex.clip, valid_vertex.clip, delta);
    vec3 vertex = mix(invalid_vertex.vertex, valid_vertex.vertex, delta);
    float inv_w = 1.0 / clip.w;
    return ProjectedVertex(
        clip,
        vertex,
        clip_to_screen(clip.xy, inv_w),
        inv_w,
        clip.z * inv_w,
        true);
}
vec2 world_dir_to_screen_dir(const vec4 clip, const vec3 world_dir) {
    
    vec4 dir_clip = u_mat4_mvp * vec4(world_dir, 0.0);
    return (dir_clip.xy * clip.w - clip.xy * dir_clip.w) * u_vec2_vpt_size;
}
void main() {
    float guideline_length = a_vec2_guideline_params.y;
    
    float segment = a_vec2_anchor_params.y;
    
    
    if (segment < 1.0 || segment > guideline_length - 1.0) {
        gl_Position = vec4(0, 0, 1, 1);
        return;
    }
    
    ProjectedVertex anchor_segment_start = project_guideline_vertex(segment - 1.0);
    ProjectedVertex anchor_segment_end = project_guideline_vertex(segment);
    
    
    vec4 anchor = vec4(
        mix(anchor_segment_start.vertex,
            anchor_segment_end.vertex,
            normalize_u16(a_vec2_anchor_params.x)),
        1.0);
    vec4 anchor_clip = u_mat4_mvp * anchor;
    
    if (anchor_clip.w <= MIN_CLIP_W) {
        gl_Position = vec4(0, 0, 1, 1);
        return;
    }
    float anchor_inv_w = 1.0 / anchor_clip.w;
    
    
    float perspective_scale = clamp(
        mix(1.0, u_float_center_distance * anchor_inv_w, PERSPECTIVE_STRENGTH),
        MIN_PERSPECTIVE_SCALE,
        MAX_PERSPECTIVE_SCALE);
    float scale = u_float_scale * perspective_scale;
    v_float_perspective_scale = perspective_scale;
    vec2 anchor_screen = clip_to_screen(anchor_clip.xy, anchor_inv_w);
    
    
    vec2 dir = world_dir_to_screen_dir(
        anchor_clip, anchor_segment_end.vertex - anchor_segment_start.vertex);
    float dir_length = length(dir);
    
    vec2 anchor_forward = dir_length > 0.0 ? dir / dir_length : vec2(1.0, 0.0);
    
    
    
    float flip = anchor_forward.x < 0.0 ? -1.0 : 1.0;
    
    float offset = a_float_center_offset * scale * flip;
    
    float direction = offset < 0.0 ? -1.0 : 1.0;
    float remaining = abs(offset);
    
    vec2 entry = anchor_screen;
    vec2 glyph_screen = anchor_screen;
    
    
    
    vec2 forward = anchor_forward;
    
    
    
    ProjectedVertex depth_start = anchor_segment_start;
    ProjectedVertex depth_end = anchor_segment_end;
    
    
    float depth_screen_length = 0.0;
    for (int i = 0; i < MAX_GUIDELINE_STEPS; i++) {
        
        
        if (float(i) > guideline_length || segment < 1.0 || segment > guideline_length - 1.0) {
            break;
        }
        ProjectedVertex start = anchor_segment_start;
        ProjectedVertex end = anchor_segment_end;
        
        
        
        
        if (i > 0) {
            start = project_guideline_vertex(segment - 1.0);
            end = project_guideline_vertex(segment);
        }
        if (!start.valid && !end.valid) {
            break;
        }
        if (!start.valid) {
            start = interpolate_vertex(end, start);
        } else if (!end.valid) {
            end = interpolate_vertex(start, end);
        }
        
        vec2 delta = end.screen - start.screen;
        float segment_screen_length = length(delta);
        
        
        
        if (segment_screen_length == 0.0) {
            segment += direction;
            continue;
        }
        forward = delta / segment_screen_length;
        depth_start = start;
        depth_end = end;
        depth_screen_length = segment_screen_length;
        
        vec2 exit_screen = direction > 0.0 ? end.screen : start.screen;
        float distance_to_exit = distance(entry, exit_screen);
        
        if (remaining <= distance_to_exit) {
            glyph_screen = entry + forward * direction * remaining;
            remaining = 0.0;
            break;
        }
        remaining -= distance_to_exit;
        entry = exit_screen;
        glyph_screen = exit_screen;
        segment += direction;
    }
    
    
    glyph_screen += forward * direction * remaining;
    
    
    float screen_t = depth_screen_length > 0.0
        ? dot(glyph_screen - depth_start.screen, forward) / depth_screen_length
        : 0.0;
    
    
    float glyph_inv_w = mix(depth_start.inv_w, depth_end.inv_w, screen_t);
    float glyph_ndc_z = mix(depth_start.ndc_z, depth_end.ndc_z, screen_t);
    
    
    bool has_glyph_depth = depth_screen_length > 0.0 && glyph_inv_w > MIN_INV_W;
    float safe_inv_w = max(glyph_inv_w, MIN_INV_W);
    
    
    float world_t = screen_t * depth_end.inv_w / safe_inv_w;
    
    
    
    float glyph_w = has_glyph_depth ? 1.0 / safe_inv_w : anchor_clip.w;
    float glyph_z = has_glyph_depth ? glyph_ndc_z * glyph_w : anchor_clip.z;
    vec4 glyph_vertex = has_glyph_depth
        ? vec4(mix(depth_start.vertex, depth_end.vertex, world_t), 1.0)
        : anchor;
    calc_fog_pos(calc_pos_world(glyph_vertex));
    
    
    
    vec2 up = vec2(-forward.y, forward.x);
    vec2 corner = a_vec2_corner_offset * scale;
    vec2 corner_offset = (forward * corner.x + up * corner.y) * flip;
    vec2 screen = glyph_screen + corner_offset;
    
    
    
    vec2 px_to_ndc = 2.0 / u_vec2_vpt_size;
    vec2 ndc = screen * px_to_ndc - 1.0;
    gl_Position = vec4(ndc * glyph_w, glyph_z, glyph_w);
    v_vec2_texcoord = unpack_texcoord(a_vec2_texcoord);
    v_vec4_identifier = a_vec4_identifier;
    if (u_int_depth_test != 0) {
        v_float_behind_factor = 1.;
        return;
    }
    
    
    float half_height = -a_float_glyph_height_offset * scale * 0.5;
    float center_y = corner.y - half_height;
    vec2 center_screen = glyph_screen + up * center_y * flip;
    
    float shrunk_x = max(abs(corner.x) - DEPTH_TEST_INSET, 0.) * sign(corner.x);
    float shrunk_y = max(abs(half_height) - DEPTH_TEST_INSET, 0.) * sign(half_height);
    vec2 probe_x = forward * shrunk_x * flip;
    vec2 probe_y = up * shrunk_y * flip;
    
    
    v_float_behind_factor = depth_line_test(
        center_screen * px_to_ndc - 1.0, 
        glyph_screen * px_to_ndc - 1.0, 
        glyph_z / glyph_w,
        a_vec4_identifier,
        (probe_x + probe_y) * px_to_ndc,
        (-probe_x + probe_y) * px_to_ndc,
        (probe_x - probe_y) * px_to_ndc,
        (-probe_x - probe_y) * px_to_ndc);
}
`,Fy=`#include <prelude>
#include <ecef_mvp_mat>
#include <dem>
#include <packed_attributes>
#include <apply_height_factor>
#include <depth_test>
#include <pos_world>
#include <cam_pos>
#include <fog>
#include <surface_height>
attribute vec3 a_vec3_vertex;
attribute vec2 a_vec2_offset;
attribute vec2 a_vec2_texcoord;
attribute vec2 a_vec2_check_offset;
attribute vec4 a_vec4_tex_identifier;
attribute vec4 a_vec4_sprite_identifier;
#ifndef UBO
uniform vec2 u_vec2_depth_test_half_point_size;
uniform vec2 u_vec2_vpt_size;
#endif
uniform vec2 u_vec2_offset;
uniform float u_float_scale;
uniform float u_float_height_factor;
uniform bool u_bool_skip_height_factor;
uniform float u_float_floor_elevation;
varying vec2 v_vec2_texcoord;
varying vec2 v_vec2_labeling_texcoord;
varying float v_float_behind_factor;
varying vec4 v_vec4_text_identifier;
void main() {
    float height = resolved_surface_height(a_vec3_vertex.xy);
    height += u_float_floor_elevation;
    vec4 pos;
    
    
    if (u_bool_skip_height_factor == true) {
        pos = vec4(a_vec3_vertex, 1.0);
    } else {
        pos = apply_height_factor(a_vec3_vertex, u_float_height_factor);
    }
    pos.z += height;
    vec3 pos_world = calc_pos_world(vec3(a_vec3_vertex.xy, 0.0));
    calc_fog_pos(pos_world);
    pos = get_clipspace(a_vec3_vertex, pos.z);
    pos.xyz = pos.xyz / pos.w;
    pos.w = 1.0;
    vec2 half_point_size = u_vec2_depth_test_half_point_size;
    v_float_behind_factor = depth_point_test(
        pos.xy + a_vec2_check_offset / u_vec2_vpt_size,
        pos.z,
        a_vec4_tex_identifier,
        vec2(-half_point_size.x, half_point_size.y),
        half_point_size,
        vec2(half_point_size.x, -half_point_size.y),
        -half_point_size);
    pos.xy += (a_vec2_offset * u_float_scale + u_vec2_offset) / u_vec2_vpt_size * 2.0;
    gl_Position = pos;
    v_vec2_texcoord = unpack_texcoord(a_vec2_texcoord);
    v_vec4_text_identifier = a_vec4_sprite_identifier;
    v_vec2_labeling_texcoord = (pos.xy + 1.) / 2.;
}
`,Dy=`#include <prelude>
#include <ecef_mvp_mat>
#include <dem>
#include <surface_height>
attribute vec3 a_vec3_vertex;
attribute vec2 a_vec2_offset;
attribute vec4 a_vec4_identifier;
#ifndef UBO
uniform vec2 u_vec2_vpt_size;
#endif
uniform vec2 u_vec2_offset;
uniform float u_float_scale;
uniform float u_float_floor_elevation;
varying vec4 v_vec4_identifier;
void main() {
    float height = resolved_surface_height(a_vec3_vertex.xy);
    height += u_float_floor_elevation;
    v_vec4_identifier = a_vec4_identifier;
    if (vec4(1., 1., 1., 1.) != a_vec4_identifier)
    {
        vec4 pos = get_clipspace(a_vec3_vertex, a_vec3_vertex.z + height);
        pos.xyz = pos.xyz / pos.w;
        pos.w = 1.0;
        pos.xy += (a_vec2_offset * u_float_scale + u_vec2_offset) / u_vec2_vpt_size * 2.0;
        gl_Position = pos;
    }
    else
    {
        gl_Position = vec4(1., 1., 1., 1.);
    }
}
`,zy=`#include <prelude>
#include <ecef_mvp_mat>
#include <dem>
#include <packed_attributes>
#include <apply_height_factor>
#include <apply_opacity>
#include <pos_world>
#include <cam_pos>
#include <fog>
#include <jitter>
#include <shadow>
#ifndef UBO
uniform vec2 u_vec2_vpt_size;
#endif
uniform vec4 u_vec4_color;
uniform float u_float_mix_color;
uniform float u_float_height_factor;
uniform float u_float_opacity;
uniform mediump mat4 u_mat4_gradient;
uniform float u_float_floor_elevation;
attribute vec3 a_vec3_vertex;
attribute float a_float_z;
attribute vec2 a_vec2_normal;
attribute vec2 a_vec2_normal_delta;
attribute vec3 a_vec3_direction;
attribute float a_float_distance;
attribute vec2 a_vec2_dem_position;
attribute float a_float_visibility;
attribute vec4 a_vec4_color;
varying vec4 v_vec4_color;
varying mat4 v_mat4_gradient;
varying vec3 v_vec3_normal;
varying vec2 v_vec2_height_gradient;
const float g_shift_pixels = 1.;
const float g_min_denominator = 1e-4;
const float g_w_factor = 1e-6;
vec2 multiply_complex(vec2 lhs, vec2 rhs)
{
    return vec2(lhs.x * rhs.x - lhs.y * rhs.y, lhs.x * rhs.y + lhs.y * rhs.x);
}
void main()
{
    
    if (a_float_visibility == 0.0) {
        gl_Position = vec4(0, 0, 1, 1);
        return;
    }
    float height = dem_height(unpack_dem_position(a_vec2_dem_position));
    
    if (a_float_z == 0.) {
        float posHeight = dem_height(a_vec3_vertex.xy);
        if (height > posHeight) {
            height = posHeight;
        }
    }
    height += u_float_floor_elevation;
    vec2 half_viewport = u_vec2_vpt_size / vec2(2.);
    
    if (a_float_z > 0.0)
    {
        v_vec2_height_gradient[0] = 1.;
    } else {
        v_vec2_height_gradient[0] = 0.;
    }
    vec4 clip_space_direction = u_mat4_flat_mvp * vec4(normalize_s08(vec3(a_vec3_direction.xy, a_vec3_direction.z + height)), 0.);
    
    vec3 flat_vertex = vec3(a_vec3_vertex.xy, a_float_z);
    
    
    
    
    
    
    vec4 vertex_hf = apply_height_factor(flat_vertex, u_float_height_factor);
    vertex_hf.z += height;
    vertex_hf.z = max(vertex_hf.z, height);
    vec4 clip_space_vertex = get_clipspace(a_vec3_vertex, vertex_hf.z);
    vec2 screen_space_direction = (clip_space_direction.xy * clip_space_vertex.w - clip_space_vertex.xy * clip_space_direction.w) * half_viewport;
    vec2 screen_space_perp = vec2(-screen_space_direction.y, screen_space_direction.x);
    float denominator = max(g_min_denominator, length(screen_space_perp));
    vec2 bevel_normal = normalize_s08(a_vec2_normal);
    vec2 normal_delta = normalize_s08(a_vec2_normal_delta);
    vec4 clip_space_bevel_normal = u_mat4_flat_mvp * vec4(bevel_normal, 0., 0.);
    vec2 screen_space_bevel_normal = (clip_space_bevel_normal.xy * clip_space_vertex.w - clip_space_vertex.xy * clip_space_bevel_normal.w) * half_viewport;
    float bevel_denominator = max(g_min_denominator, length(screen_space_bevel_normal));
    
    float normal_factor = -dot(screen_space_bevel_normal, screen_space_perp) / denominator / bevel_denominator;
    vec2 wall_normal = multiply_complex(bevel_normal, vec2(normal_delta.x, sign(normal_factor) * normal_delta.y));
    gl_Position = g_w_factor * (clip_space_vertex + vec4(screen_space_perp / half_viewport, 0., 0.) * g_shift_pixels * a_float_distance / denominator * clip_space_vertex.w);
    vec3 pos_world = calc_pos_world(vertex_hf.xyz);
    v_vec4_color = u_vec4_color;
    if (a_vec4_color[3] > 0. ) {
        v_vec4_color =  mix(v_vec4_color, a_vec4_color, u_float_mix_color);
    }
    v_vec3_normal = vec3(wall_normal, 0.0);
    if (u_mat4_gradient[0][0] !=0.)
    {
        v_mat4_gradient = u_mat4_gradient;
    
        if (a_vec4_color[3] > 0. ) {
            v_mat4_gradient[1] = mix(v_mat4_gradient[1], a_vec4_color, u_float_mix_color);
            v_mat4_gradient[2] = mix(v_mat4_gradient[2], a_vec4_color, u_float_mix_color);
        }
        for (int i = 1; i <= 2; i++) {
            v_mat4_gradient[i] = apply_opacity(v_mat4_gradient[i], u_float_opacity);
        }
    }
    v_vec2_height_gradient.y = a_float_distance * gl_Position.w;
    calc_fog_pos(pos_world);
#ifdef TAA
    apply_vertex_jitter(gl_Position);
#endif
    
    
    compute_shadow_vertex(clip_space_vertex);
}
`,By=`#include <prelude>
#include <mvp_mat>
#include <pos_world>
#include <cam_pos>
#include <fog>
#include <jitter>
#include <shadow>
#include <dem>
attribute vec2 a_vec2_vertex;
attribute vec4 a_vec4_normals;
attribute float a_float_height;
attribute float a_float_abs_z;
#ifndef UBO
uniform vec2 u_vec2_vpt_size;
#endif
uniform float u_float_width;
uniform float u_float_tile_to_pixel_ratio;
uniform int u_int_abs_z;
varying vec2 v_vec2_normal;
varying float v_float_half_width;
const float g_w_factor = 1e-6;
const float normal_unpack_multiplier = 0.011135539861205473;
void main()
{
    float height = 0.;
    if (u_int_abs_z == 0) {
        height = dem_height(a_vec2_vertex);
    } else {
        height = abs_height(a_float_abs_z);
    }
    
    float half_width = 0.5 * (u_float_width + 1.0);
    
    vec4 normals = a_vec4_normals * normal_unpack_multiplier * half_width;
    vec2 extender = normals.xy;
    vec2 normal = normals.zw;
    vec4 base_vertex = vec4(
        a_vec2_vertex.x,
        a_vec2_vertex.y,
        height + a_float_height / (65535. * 32.),
        1.0
    );
    vec3 pos_world = calc_pos_world(base_vertex);
    vec3 base_normal = vec3(0.0, 0.0, 1.0);
    vec3 extender_vector = vec3(extender * u_float_tile_to_pixel_ratio, 0.0);
    vec3 V = normalize(u_cam_pos - pos_world);
    vec3 rotated_extender;
    
    vec3 rotation_axis = cross(base_normal, V);
    float sin_angle = length(rotation_axis);
    float cos_angle = dot(base_normal, V);
    const float EPSILON = 1e-3;
    if (sin_angle < EPSILON) {
        rotated_extender = extender_vector * sign(cos_angle);
    } else {
        vec3 k = rotation_axis / sin_angle;
        rotated_extender = extender_vector * cos_angle + 
                        cross(k, extender_vector) * sin_angle + 
                        k * dot(k, extender_vector) * (1.0 - cos_angle);
    }
    vec4 rotated_vertex = vec4(base_vertex.xyz + rotated_extender, 1.0);
    vec4 base_clip = u_mat4_mvp * base_vertex;
    vec3 base_ndc = base_clip.xyz / base_clip.w;
    vec4 rotated_clip = u_mat4_mvp * rotated_vertex;
    vec3 rotated_ndc = rotated_clip.xyz / rotated_clip.w;
    
    vec2 base_screen = (base_ndc.xy + 1.0) * 0.5 * u_vec2_vpt_size;
    vec2 rotated_screen = (rotated_ndc.xy + 1.0) * 0.5 * u_vec2_vpt_size;
    float pixel_distance = length(base_screen - rotated_screen);
    float scale_factor = half_width / pixel_distance;
    
    if (base_clip.w < 0.0) {
        scale_factor = 0.;
    }
    rotated_extender = rotated_extender * scale_factor;
    rotated_vertex = vec4(base_vertex.xyz + rotated_extender, 1.0);
    vec4 clip_pos = u_mat4_mvp * rotated_vertex;
    gl_Position = g_w_factor * clip_pos;
    v_vec2_normal = normal;
    v_float_half_width = half_width;
    calc_fog_pos(pos_world);
#ifdef TAA
    apply_vertex_jitter(gl_Position);
#endif
    compute_shadow_vertex(clip_pos, vec3(0.0, 0.0, 1.0), u_mat4_mvp);
}
`,Oy=`#include <prelude>
#include <mvp_mat>
#include <dem>
attribute vec2 a_vec2_vertex;
attribute vec4 a_vec4_normals;
attribute float a_float_height;
attribute float a_float_abs_z;
attribute vec4 a_vec4_identifier;
uniform float u_float_width;
uniform float u_float_tile_to_pixel_ratio;
uniform int u_int_abs_z;
varying vec2 v_vec2_normal;
varying vec4 v_vec4_identifier;
varying float v_float_half_width;
const float g_w_factor = 1e-6;
const float normal_unpack_multiplier = 0.011135539861205473;
void main()
{
    float height = 0.;
    if (u_int_abs_z == 0) {
        height = dem_height(a_vec2_vertex);
    } else {
        height = abs_height(a_float_abs_z);
    }
    
    float half_width = 0.5 * (u_float_width + 1.0);
    
    vec4 normals = a_vec4_normals * normal_unpack_multiplier * half_width;
    vec2 extender = normals.xy;
    vec2 normal = normals.zw;
    if (vec4(1., 1., 1., 1.) != a_vec4_identifier) {
        
        vec4 shifted_vertex = vec4(
            a_vec2_vertex + extender * u_float_tile_to_pixel_ratio,
            height + a_float_height / (65535. * 32.),
            1.0
        );
        gl_Position = g_w_factor * u_mat4_mvp * shifted_vertex;
    } else {
        gl_Position = vec4(1., 1., 1., 1.);
    }
    v_vec2_normal = normal;
    v_vec4_identifier = a_vec4_identifier;
    v_float_half_width = half_width;
}
`,wy=`#include <prelude>
#include <mvp_mat>
#include <dem>
#include <packed_attributes>
#include <pos_world>
#include <cam_pos>
#include <shadow>
#include <fog>
#include <clipspace_pos>
#include <jitter>
attribute vec2 a_vec2_vertex;
attribute float a_float_z;
attribute vec2 a_vec2_extender;
attribute vec3 a_vec3_normal;
attribute float a_float_gradient;
attribute vec2 a_vec2_dem_position;
attribute float a_float_abs_z;
attribute vec4 a_vec4_identifier;
attribute float a_float_is_pivot;
uniform float u_float_tile_size;
uniform float u_float_height_factor;
uniform int u_int_abs_z;
varying vec4 v_tex_coord;
varying vec4 v_vec4_normal_gradient;
varying vec4 v_vec4_identifier;
void main()
{
#ifndef VARYINGS_LIMIT_9
    v_float_dem_invalid = 0.;
#endif
    float height = 0.;
    if (u_int_abs_z == 0) {
        height = dem_height(unpack_dem_position(a_vec2_dem_position));
    } else {
        if (a_float_is_pivot == 1.) {
            height = dem_height(a_vec2_vertex);
        } else {
            height = abs_height(a_float_abs_z);
        }
    }
    
    vec3 vec3_vertex = vec3(a_vec2_vertex, a_float_z / (65535. * 32.));
    v_vec4_identifier = a_vec4_identifier;
    v_tex_coord = u_mat4_mvp * vec4(vec3_vertex.xy, 0, 1.0);
    v_vec4_normal_gradient.xyz = normalize_s08(a_vec3_normal);
    v_vec4_normal_gradient.w = a_float_gradient;
    vec4 pos = vec4(vec3_vertex.xy, vec3_vertex.z * u_float_height_factor + height, 1.0);
    vec3 world_pos = calc_pos_world(pos);
    calc_fog_pos(world_pos);
    gl_Position = u_mat4_mvp * pos;
#ifdef TAA
    apply_vertex_jitter(gl_Position);
#endif
    save_clipspace_pos();
    compute_shadow_vertex(gl_Position, v_vec4_normal_gradient.xyz, u_mat4_mvp);
}
`,Ny=`#include <prelude>
#include <mvp_mat>
#include <dem>
#include <packed_attributes>
#include <apply_height_factor>
#include <apply_opacity>
#include <pos_world>
#include <cam_pos>
#include <shadow>
#include <fog>
#include <clipspace_pos>
#include <jitter>
uniform mediump vec4 u_vec4_color;
uniform float u_float_mix_color;
uniform mediump mat4 u_mat4_gradient;
uniform float u_float_height_factor;
uniform int u_int_abs_z;
uniform lowp int u_int_is_textured;
uniform mediump float u_float_opacity;
uniform float u_float_floor_elevation;
uniform vec4 u_float_texture_params;
uniform float u_float_texture_vertical_scale;
uniform mediump int u_int_identify;
attribute vec2 a_vec2_vertex;
attribute float a_float_z;
attribute vec3 a_vec3_normal;
attribute float a_float_gradient;
attribute vec2 a_vec2_dem_position;
attribute float a_float_abs_z;
attribute vec4 a_vec4_identifier;
attribute float a_float_visibility;
attribute float a_float_is_pivot;
attribute vec4 a_vec4_color;
varying vec4 v_vec4_color;
varying mat4 v_mat4_gradient;
varying vec2 v_vec2_tex_coord;
varying vec4 v_vec4_normal_gradient;
varying vec4 v_vec4_identifier;
void main()
{
    if (u_int_identify != 0 && a_vec4_identifier == vec4(1., 1., 1., 1.)) {
        gl_Position = vec4(0, 0, 0, 0);
        return;
    }
    float height = 0.;
    if (u_int_abs_z == 0) {
        height = dem_height(unpack_dem_position(a_vec2_dem_position));
    } else {
        if (a_float_is_pivot == 1.) {
            height = dem_height(a_vec2_vertex);
        } else {
            height = abs_height(a_float_abs_z);
        }
    }
    if (a_float_visibility == 0.0) {
        gl_Position = vec4(0, 0, 1, 1);
        return;
    }
    vec4 t_vec4_color = u_vec4_color;
    if (a_vec4_color[3] > 0. ) {
        t_vec4_color =  mix(u_vec4_color, a_vec4_color, u_float_mix_color);
    }
    height += u_float_floor_elevation;
    v_vec4_identifier = a_vec4_identifier;
    
    vec4 vec4_pos = apply_height_factor(vec3(a_vec2_vertex.xy, a_float_z / (65535. * 32.)), u_float_height_factor);
    vec4_pos.z += height;
    vec3 pos_world = calc_pos_world(vec4_pos);
    calc_fog_pos(pos_world);
    gl_Position = u_mat4_mvp * vec4_pos;
    vec3 vec3_normal = normalize(a_vec3_normal);
    v_vec4_normal_gradient.xyz = vec3_normal;
    v_vec4_normal_gradient.w = a_float_gradient / 127.; 
    if (u_int_is_textured != 0) {
        
        vec2 vec2_vertex = a_vec2_vertex * 2. - 0.5;
        
        
        vec3 tex_coord = abs(vec3(
            vec2_vertex * u_float_texture_params.zw + u_float_texture_params.xy,
            a_float_z / u_float_texture_vertical_scale
        ));
        
        if (vec3_normal.x == 0. && vec3_normal.y == 0.) {
            v_vec2_tex_coord = tex_coord.xy;
        } else {
            float scale = abs(vec3_normal.z);
            tex_coord.z /= sqrt(1.0 - vec3_normal.z * vec3_normal.z);;
            if (abs(vec3_normal).y > abs(vec3_normal).x) {
                v_vec2_tex_coord = tex_coord.xz;
            } else {
                v_vec2_tex_coord = tex_coord.yz;
            }
        }
        v_vec4_color = apply_opacity(t_vec4_color, u_float_opacity);
    }
    
    else if (u_mat4_gradient[0][0] != 0.)
    {
        v_mat4_gradient = u_mat4_gradient;
        for (int i = 1; i <= 2; i++) {
            v_mat4_gradient[i] = apply_opacity(v_mat4_gradient[i], u_float_opacity);
        }
    } else {
        v_vec4_color = apply_opacity(t_vec4_color, u_float_opacity);
    }
#ifdef TAA
    apply_vertex_jitter(gl_Position);
#endif
    save_clipspace_pos();
    compute_shadow_vertex(gl_Position, vec3_normal, u_mat4_mvp);
}
`,ky=`#include <prelude>
#include <mvp_mat>
#include <dem>
#include <apply_height_factor>
attribute vec2 a_vec2_vertex;
attribute float a_float_z;
attribute vec2 a_vec2_dem_position;
attribute float a_float_abs_z;
attribute float a_float_visibility;
attribute float a_float_is_pivot;
uniform float u_float_height_factor;
uniform int u_int_abs_z;
uniform float u_float_floor_elevation;
varying float v_depth_metric;
void main()
{
    float height = 0.;
    if (u_int_abs_z == 0) {
        height = dem_height(unpack_dem_position(a_vec2_dem_position));
    } else {
        if (a_float_is_pivot == 1.) {
            height = dem_height(a_vec2_vertex);
        } else {
            height = abs_height(a_float_abs_z);
        }
    }
    if (a_float_visibility == 0.0) {
        gl_Position = vec4(0, 0, 1, 1);
        return;
    }
    height += u_float_floor_elevation;
    
    vec4 vec4_pos = apply_height_factor(vec3(a_vec2_vertex.xy, a_float_z / (65535. * 32.)), u_float_height_factor);
    vec4_pos.z += height;
    gl_Position = u_mat4_mvp * vec4_pos;
    v_depth_metric = 0.5 * gl_Position.z + 0.5;
}`,Uy=`#include <prelude>
#include <mvp_mat>
#include <apply_opacity>
#include <packed_attributes>
#include <pos_world>
#include <cam_pos>
#include <shadow>
#include <fog>
uniform float u_float_floor_elevation;
attribute vec2 a_vec2_vertex;
attribute vec2 a_vec2_texcoord;
varying vec2 v_vec2_texcoord;
void main()
{
    gl_Position = u_mat4_mvp * vec4(a_vec2_vertex, u_float_floor_elevation, 1.0);
    vec3 pos_world = calc_pos_world(a_vec2_vertex);
    calc_fog_pos(pos_world);
    compute_shadow_vertex(gl_Position, vec3(0,0,1), u_mat4_mvp);
    v_vec2_texcoord = unpack_texcoord(a_vec2_texcoord);
}
`,My=`#include <prelude>
#include <mvp_mat>
#include <packed_attributes>
#include <pixel_offset>
#include <signed_distance_functions>
#include <arrow_functions>
#include <apply_opacity>
#include <pos_world>
#include <cam_pos>
#include <fog>
#include <jitter>
#ifndef UBO
uniform float u_float_border_width_offset;
uniform vec2 u_vec2_scale_limits;
uniform mediump vec2 u_vec2_vpt_size;
#endif
uniform vec4 u_vec4_color;
uniform vec3 u_vec3_projection_scale_style_scale_dpi;
uniform float u_float_border_width;
uniform float u_float_size_factor;
uniform mediump float u_float_width;
uniform mediump float u_float_length;
uniform float u_float_wing_width_multiplier;
uniform float u_float_wing_height_multiplier;
uniform float u_float_tip_height_multiplier;
uniform float u_float_opacity;
attribute vec2 a_vec2_position;
attribute vec2 a_vec2_direction;
attribute vec2 a_vec2_widen_direction;
varying vec4 v_vec4_color;
varying vec2 v_vec2_texcoord;
varying float v_float_border_width;
varying float v_float_zpt_to_texcoord_factor;
varying float v_float_outer_width;
varying float v_float_opacity;
const float g_shift_pixels = 2.;
const float g_w_factor = 1e-7;
void main()
{
    float style_scale_clamped = clamp(u_vec3_projection_scale_style_scale_dpi.y, u_vec2_scale_limits.x, u_vec2_scale_limits.y);
    float scale_ratio = u_vec3_projection_scale_style_scale_dpi.x / u_vec3_projection_scale_style_scale_dpi.y;
    float calculation_scale = style_scale_clamped * scale_ratio;
    ArrowParameters arrow_parameters = calculate_arrow_parameters(
        calculation_scale,
        u_float_width,
        u_float_border_width,
        u_float_length,
        u_float_wing_width_multiplier,
        u_float_wing_height_multiplier,
        u_float_tip_height_multiplier,
        u_float_size_factor);
    v_float_zpt_to_texcoord_factor = arrow_parameters.zpt_to_texcoord_factor;
    v_float_outer_width = arrow_parameters.outer_width;
    vec2 direction = normalize_s08(a_vec2_direction);
    vec2 untransformed_widen = a_vec2_widen_direction * arrow_parameters.widen_size;
    vec2 widen = multiply_complex(untransformed_widen * arrow_parameters.final_size, direction);
    
    float shift_pixels = g_shift_pixels * sqrt(2.) / min(abs(untransformed_widen.x), abs(untransformed_widen.y));
    VertexShiftParameters shift_parameters = calculate_vertex_shift_parameters(
        u_mat4_mvp,
        u_vec2_vpt_size,
        a_vec2_position,
        widen,
        shift_pixels);
    
    
    gl_Position = shift_parameters.clip_space_vertex / arrow_parameters.final_size * g_w_factor;
    v_vec2_texcoord = untransformed_widen * (1. + shift_parameters.limited_factor);
    
    float border_width = u_float_border_width * v_float_zpt_to_texcoord_factor;
    float border_width_offset = u_float_border_width_offset * v_float_zpt_to_texcoord_factor;
    v_float_border_width = max(0., border_width - u_vec3_projection_scale_style_scale_dpi.y / style_scale_clamped * border_width_offset);
    v_vec4_color = apply_opacity(u_vec4_color, u_float_opacity);
    v_float_opacity = u_float_opacity;
    vec3 pos_world = calc_pos_world(a_vec2_position);
    calc_fog_pos(pos_world);
}
`,Hy=`#include <prelude>
attribute vec2 a_quadVertex;
attribute vec3 a_position;
attribute float a_frame;
attribute vec4 a_params;
attribute vec4 a_color;
uniform mat4 u_mvp;
uniform vec2 u_viewport;
uniform vec2 u_atlasGrid;
varying vec4 v_color;
varying vec2 v_uv;
varying float v_stretch;
void main() {
    float size = a_params.x;
    float rotation = a_params.y;
    vec4 clipPos = u_mvp * vec4(a_position, 1.0);
    float pixelSize = size * u_viewport.y / clipPos.w;
    float c = cos(rotation);
    float s = sin(rotation);
    vec2 rotated = vec2(
        a_quadVertex.x * c - a_quadVertex.y * s,
        a_quadVertex.x * s + a_quadVertex.y * c
    );
    vec2 offset = rotated * pixelSize;
    clipPos.xy += offset * (2.0 / u_viewport) * clipPos.w;
    gl_Position = clipPos;
    v_color = a_color;
    
    vec2 localUV = a_quadVertex * 0.5 + 0.5;
    if (u_atlasGrid.x > 0.0) {
        float col = mod(a_frame, u_atlasGrid.x);
        float row = floor(a_frame / u_atlasGrid.x);
        vec2 frameSize = 1.0 / u_atlasGrid;
        v_uv = (vec2(col, row) + localUV) * frameSize;
    } else {
        v_uv = localUV;
    }
    v_stretch = 0.0;
}`,Gy=`#include <prelude>
attribute vec2 a_quadVertex;
attribute vec3 a_position;
attribute vec3 a_velocity;
attribute float a_frame;
attribute vec4 a_params;
attribute vec4 a_color;
uniform mat4 u_mvp;
uniform vec2 u_viewport;
uniform vec2 u_atlasGrid;
varying vec4 v_color;
varying vec2 v_uv;
varying float v_stretch;
void main() {
    float size = a_params.x;
    vec4 clipPos = u_mvp * vec4(a_position, 1.0);
    
    
    
    vec2 projVel = (u_mvp * vec4(a_velocity, 0.0)).xy;
    float projLen = length(projVel);
    vec2 dir;
    if (projLen > 0.0001) {
        dir = projVel / projLen;
    } else {
        dir = vec2(0.0, -1.0);
    }
    float pixelVelLen = projLen * u_viewport.y / (2.0 * clipPos.w);
    float halfLength = clamp(pixelVelLen * 0.06, 0.5, 40.0);
    float basePixelSize = size * u_viewport.y / clipPos.w;
    float halfWidth = max(1.0, basePixelSize * 0.15);
    vec2 normal = vec2(-dir.y, dir.x);
    vec2 offset = dir * a_quadVertex.x * halfLength + normal * a_quadVertex.y * halfWidth;
    clipPos.xy += offset * (2.0 / u_viewport) * clipPos.w;
    gl_Position = clipPos;
    v_color = a_color;
    vec2 localUV = a_quadVertex * 0.5 + 0.5;
    if (u_atlasGrid.x > 0.0) {
        float col = mod(a_frame, u_atlasGrid.x);
        float row = floor(a_frame / u_atlasGrid.x);
        vec2 frameSize = 1.0 / u_atlasGrid;
        v_uv = (vec2(col, row) + localUV) * frameSize;
    } else {
        v_uv = localUV;
    }
    v_stretch = 1.0;
}`,Vy=`#include <prelude>
#include <mvp_mat>
#include <packed_attributes>
#include <pixel_offset>
#include <signed_distance_functions>
#include <arrow_functions>
#include <apply_opacity>
#include <pos_world>
#include <cam_pos>
#include <fog>
#include <jitter>
#include <dem>
#include <depth_test>
#ifndef UBO
uniform float u_float_border_width_offset;
uniform mediump vec2 u_vec2_vpt_size;
#endif
uniform vec4 u_vec4_color;
uniform vec4 u_vec4_hidden_color;
uniform float u_float_border_width;
uniform float u_float_pixel_ratio;
uniform float u_float_center_distance;
uniform mediump float u_float_width;
uniform mediump float u_float_length;
uniform float u_float_wing_width_multiplier;
uniform float u_float_wing_height_multiplier;
uniform float u_float_tip_height_multiplier;
uniform float u_float_opacity;
uniform mediump int u_int_depth_test;
attribute vec2 a_vec2_position;
attribute float a_float_z;
attribute float a_float_abs_z;
attribute vec2 a_vec2_direction;
attribute vec2 a_vec2_widen_direction;
attribute vec4 a_vec4_identifier;
varying vec4 v_vec4_color;
varying vec4 v_vec4_hidden_color;
varying vec2 v_vec2_texcoord;
varying vec4 v_vec4_identifier;
varying float v_float_behind_factor;
varying vec4 v_vec4_params;
const float g_shift_pixels = 2.;
const float g_w_factor = 1e-7;
const float PERSPECTIVE_STRENGTH = 0.5;
const float MIN_PERSPECTIVE_SCALE = 0.5;
const float MAX_PERSPECTIVE_SCALE = 1.5;
const float DEPTH_TEST_INSET = 0.5;
void main()
{
    
    ArrowParameters arrow_parameters = calculate_arrow_parameters(
        1.,
        u_float_width,
        u_float_border_width,
        u_float_length,
        u_float_wing_width_multiplier,
        u_float_wing_height_multiplier,
        u_float_tip_height_multiplier,
        1.
    );
    v_vec4_params.y = arrow_parameters.zpt_to_texcoord_factor;
    v_vec4_params.z = arrow_parameters.outer_width;
    vec2 direction = normalize_s08(a_vec2_direction);
    vec2 half_viewport = u_vec2_vpt_size / 2.;
    float height = a_float_z + abs_height(a_float_abs_z);
    vec4 position = vec4(a_vec2_position, height, 1.);
    vec4 clip_space_anchor = u_mat4_mvp * position;
    
    
    vec4 clip_space_direction = u_mat4_mvp * vec4(direction, 0., 0.);
    
    vec2 screen_direction =
        (clip_space_direction.xy * clip_space_anchor.w - clip_space_anchor.xy * clip_space_direction.w) * half_viewport;
    float screen_direction_length = length(screen_direction);
    
    
    if (screen_direction_length == 0.) {
        gl_Position = vec4(0, 0, 1, 1);
        return;
    }
    vec2 screen_space_direction = screen_direction / screen_direction_length;
    
    float perspective_scale = clamp(
        mix(1., u_float_center_distance / clip_space_anchor.w, PERSPECTIVE_STRENGTH),
        MIN_PERSPECTIVE_SCALE,
        MAX_PERSPECTIVE_SCALE);
    
    float texcoord_to_pixels =
        u_float_pixel_ratio * perspective_scale / arrow_parameters.zpt_to_texcoord_factor;
    vec2 untransformed_widen = a_vec2_widen_direction * arrow_parameters.widen_size;
    
    v_vec2_texcoord =
        untransformed_widen + a_vec2_widen_direction * (g_shift_pixels / texcoord_to_pixels);
    vec2 screen_space_widen = multiply_complex(v_vec2_texcoord * texcoord_to_pixels, screen_space_direction);
    vec2 ndc_widen = screen_space_widen / half_viewport;
    gl_Position = clip_space_anchor;
    gl_Position.xy += ndc_widen * clip_space_anchor.w;
    gl_Position *= g_w_factor;
    
    float border_width = u_float_border_width * v_vec4_params.y;
    float border_width_offset = u_float_border_width_offset * v_vec4_params.y;
    v_vec4_params.x = max(0., border_width - border_width_offset);
    v_vec4_identifier = a_vec4_identifier;
    v_vec4_color = apply_opacity(u_vec4_color, u_float_opacity);
    v_vec4_hidden_color = apply_opacity(u_vec4_hidden_color, u_float_opacity);
    v_vec4_params.w = u_float_opacity;
    vec3 pos_world = calc_pos_world(position);
    calc_fog_pos(pos_world);
    if (u_int_depth_test == 1) {
        v_float_behind_factor = 1.;
        return;
    }
    
    
    vec2 half_size = max(arrow_parameters.widen_size * texcoord_to_pixels - DEPTH_TEST_INSET, 0.);
    
    
    vec2 probe_x = multiply_complex(vec2(half_size.x, 0.), screen_space_direction) / half_viewport;
    vec2 probe_y = multiply_complex(vec2(0., half_size.y), screen_space_direction) / half_viewport;
    vec2 anchor_ndc = clip_space_anchor.xy / clip_space_anchor.w;
    v_float_behind_factor = depth_line_test(
        anchor_ndc,
        anchor_ndc,
        clip_space_anchor.z / clip_space_anchor.w,
        a_vec4_identifier,
        probe_x + probe_y,
        -probe_x + probe_y,
        probe_x - probe_y,
        -probe_x - probe_y);
}
`,Zy=`#include <prelude>
#include <mvp_mat>
#include <packed_attributes>
#include <pixel_offset>
#include <calculate_scale>
#include <line_width>
#include <apply_opacity>
#include <precision_constants>
#include <striped_line_functions>
#include <pos_world>
#include <cam_pos>
#include <shadow>
#include <fog>
#include <jitter>
#include <dem>
attribute vec2 a_vec2_vertex;
attribute vec2 a_vec2_widen;
attribute float a_float_texture;
attribute float a_float_height;
uniform vec2 u_vec2_scales;
uniform float u_float_width;
uniform vec4 u_vec4_color;
uniform float u_float_opacity;
uniform vec4 u_vec4_pattern_params;
uniform bool u_bool_is_3d_line;
varying vec2 v_vec2_uv;
varying float v_float_period;
varying float v_float_width;
varying vec4 v_vec4_color;
varying vec4 v_vec4_pattern_parameters;
const float g_w_factor = 1e-6;
void main() {
    float height = 0.;
    if (u_bool_is_3d_line == true) {
        height = dem_height(a_vec2_vertex);
    }
    if (u_bool_is_3d_line == true) {
        height += a_float_height / (65535. * 32.);
    }
    
    v_float_width = u_float_width;
    v_vec4_color = apply_opacity(u_vec4_color, u_float_opacity);
    v_vec2_uv = vec2(abs(a_float_texture), sign(a_float_texture) / 2.);
    v_vec2_uv.x *= u_vec2_scales.x / u_vec4_pattern_params.x;
    v_vec4_pattern_parameters = u_vec4_pattern_params;
    
    float full_width = u_float_width + 1.;
    
    vec2 widen = unpack_widen(a_vec2_widen);
    vec2 extender = widen * full_width * 0.5;
    
    
    vec2 shift = vec2(0.);
    vec4 shifted_vertex = vec4(a_vec2_vertex + (shift + extender) * u_vec2_scales.y, height, 1.0);
    vec3 pos_world = calc_pos_world(shifted_vertex); 
    calc_fog_pos(pos_world);
    gl_Position = u_mat4_mvp * shifted_vertex;
#ifdef TAA
    apply_vertex_jitter(gl_Position);
#endif
    compute_shadow_vertex(gl_Position, vec3(0.0, 0.0, 1.0), u_mat4_mvp);
    gl_Position *= g_w_factor;
}
`,Wy=`#include <prelude>
#include <mvp_mat>
#include <dem>
#include <surface_height>
attribute vec4 a_vec4_position;
attribute vec2 a_vec2_offset;
attribute vec4 a_vec4_identifier;
#ifndef UBO
uniform vec2 u_vec2_vpt_size;
#endif
uniform vec2 u_vec2_offset;
uniform float u_float_floor_elevation;
varying vec4 v_vec4_identifier;
void main() {
    float height = resolved_surface_height(a_vec4_position.xy);
    height += u_float_floor_elevation;
    vec4 ndcPosition = u_mat4_mvp * vec4(a_vec4_position.xy, a_vec4_position.z + height, a_vec4_position.w);
    ndcPosition.xyz = ndcPosition.xyz / ndcPosition.w;
    ndcPosition.w = 1.0;
    ndcPosition.xy += (a_vec2_offset + u_vec2_offset) / u_vec2_vpt_size * 2.0;
    gl_Position = ndcPosition;
    v_vec4_identifier = a_vec4_identifier;
}
`,jy=`#include <prelude>
#include <ecef_mvp_mat>
#include <pos_world>
#include <cam_pos>
#include <fog>
#include <dem>
#include <packed_attributes>
#include <apply_height_factor>
#include <raster_functions>
#include <depth_test>
#include <surface_height>
#ifndef UBO
uniform vec2 u_vec2_depth_test_half_point_size;
uniform float u_float_rounding_factor;
uniform vec2 u_vec2_vpt_size;
#endif
uniform vec3 u_vec3_projection_scale_style_scale_dpi;
uniform float u_float_height_factor;
uniform vec2 u_vec2_rotation; 
uniform bool u_bool_skip_height_factor;
uniform float u_float_floor_elevation;
attribute vec3 a_vec3_vertex;
attribute vec2 a_vec2_offset;
attribute vec2 a_vec2_check_offset;
attribute vec2 a_vec2_texcoord;
attribute vec2 a_vec2_range;
attribute vec2 a_vec2_rescale;
attribute vec4 a_vec4_tex_identifier;
varying vec2 v_vec2_texcoord;
varying float v_float_behind_factor;
void main()
{
    float height = resolved_surface_height(a_vec3_vertex.xy);
    height += u_float_floor_elevation;
    mat2 rotation_matrix = mat2(
        u_vec2_rotation.x, -u_vec2_rotation.y,
        u_vec2_rotation.y, u_vec2_rotation.x
    );
    vec2 inv_half_size = 2.0 / u_vec2_vpt_size;
    vec4 anchor;
    
    
    if (u_bool_skip_height_factor == true) {
        anchor = vec4(a_vec3_vertex, 1.0);
    } else {
        anchor = apply_height_factor(a_vec3_vertex, u_float_height_factor);
    }
    anchor.z += height;
    vec3 pos_world = calc_pos_world(vec3(a_vec3_vertex.xy, 0.0));
    calc_fog_pos(pos_world);
    anchor = get_clipspace(a_vec3_vertex, anchor.z);
    vec2 offset = rescale(rotation_matrix * a_vec2_offset, a_vec2_rescale, a_vec2_range, u_vec3_projection_scale_style_scale_dpi.y);
    vec2 pos_2d = anchor.xy + overlay_transform(offset, inv_half_size) * anchor.w;
    vec2 corner = make_position(pos_2d, anchor.w, inv_half_size, u_float_rounding_factor);
    vec2 half_point_size = u_vec2_depth_test_half_point_size;
    v_float_behind_factor = depth_point_test(
        anchor.xy / anchor.w + a_vec2_check_offset / u_vec2_vpt_size,
        anchor.z / anchor.w,
        a_vec4_tex_identifier,
        vec2(-half_point_size.x, half_point_size.y),
        half_point_size,
        vec2(half_point_size.x, -half_point_size.y),
        -half_point_size);
    gl_Position = vec4(corner, anchor.z, clipw(anchor.w, a_vec2_range, u_vec3_projection_scale_style_scale_dpi.y));
    v_vec2_texcoord = unpack_texcoord(a_vec2_texcoord);
}
`,Xy=`#include <prelude>
#include <ecef_mvp_mat>
#include <dem>
#include <packed_attributes>
#include <apply_height_factor>
#include <raster_functions>
#include <surface_height>
#ifndef UBO
uniform vec2 u_vec2_vpt_size;
#endif
uniform vec3 u_vec3_projection_scale_style_scale_dpi;
uniform float u_float_height_factor;
uniform vec2 u_vec2_rotation; 
uniform bool u_bool_skip_height_factor;
uniform float u_float_floor_elevation;
attribute vec3 a_vec3_vertex;
attribute vec2 a_vec2_offset;
attribute vec2 a_vec2_texcoord;
attribute vec2 a_vec2_range;
attribute vec2 a_vec2_rescale;
attribute vec4 a_vec4_identifier;
varying vec2 v_vec2_texcoord;
varying vec4 v_vec4_identifier;
void main()
{
    if (vec4(1., 1., 1., 1.) != a_vec4_identifier)
    {
        float height = resolved_surface_height(a_vec3_vertex.xy);
        height += u_float_floor_elevation;
        mat2 rotation_matrix = mat2(
            u_vec2_rotation.x, -u_vec2_rotation.y,
            u_vec2_rotation.y, u_vec2_rotation.x
        );
        vec2 inv_half_size = 2.0 / u_vec2_vpt_size;
        vec4 anchor;
        
        
        if (u_bool_skip_height_factor == true) {
            anchor = vec4(a_vec3_vertex, 1.0);
        } else {
            anchor = apply_height_factor(a_vec3_vertex, u_float_height_factor);
        }
        anchor.z += height;
        anchor = get_clipspace(a_vec3_vertex, anchor.z);
        vec2 offset = rescale(rotation_matrix * a_vec2_offset, a_vec2_rescale, a_vec2_range, u_vec3_projection_scale_style_scale_dpi.y);
        vec2 pos_2d = anchor.xy + overlay_transform(offset, inv_half_size) * anchor.w;
        vec2 corner = make_position(pos_2d, anchor.w, inv_half_size, 1.0);
        gl_Position = vec4(corner, anchor.z, clipw(anchor.w, a_vec2_range, u_vec3_projection_scale_style_scale_dpi.y));
    }
    else
    {
        gl_Position = vec4(1., 1., 1., 1.);
    }
    v_vec2_texcoord = unpack_texcoord(a_vec2_texcoord);
    v_vec4_identifier = a_vec4_identifier;
}
`,$y=`#include <prelude>
attribute vec2 a_vec2_vertex;
varying vec2 v_vec2_texcoord;
void main()
{
    gl_Position = vec4(a_vec2_vertex, 0.0, 1.0);
    v_vec2_texcoord = 0.5 * a_vec2_vertex + 0.5;
}
`,qy=`#include <prelude>
#include <mvp_mat>
#include <packed_attributes>
#include <apply_opacity>
#include <raster_functions>
#include <pos_world>
#include <cam_pos>
#include <fog>
attribute vec2 a_vec2_vertex;
attribute vec2 a_vec2_texcoord;
varying vec2 v_vec2_texcoord;
void main()
{
    gl_Position = u_mat4_mvp * vec4(a_vec2_vertex, 0.0, 1.0);
    calc_fog_pos(calc_pos_world(a_vec2_vertex));
    v_vec2_texcoord = unpack_texcoord(a_vec2_texcoord);
}
`,Yy=`#include <prelude>
#include <ecef_mvp_mat>
#include <pos_world>
#include <cam_pos>
#include <fog>
#include <jitter>
#include <shadow>
attribute vec3 a_vec3_vertex;
attribute vec4 a_vec4_normals;
attribute vec2 a_vec2_shift;
uniform float u_float_width;
uniform float u_float_tile_to_pixel_ratio;
uniform float u_float_shift;
uniform float u_float_floor_elevation;
uniform float u_float_ecef_scale;
varying vec2 v_vec2_normal;
varying float v_float_half_width;
const float g_w_factor = 1e-6;
const float normal_unpack_multiplier = 0.011135539861205473;
void main()
{
    
    float half_width = 0.5 * (u_float_width + 1.0);
    
    vec4 normals = a_vec4_normals * normal_unpack_multiplier * half_width;
    vec2 extender = normals.xy;
    vec2 normal = normals.zw;
    vec2 shift = a_vec2_shift * u_float_shift;
    vec2 offset_pixels = shift + extender;
    vec3 shifted_vertex_flat = vec3(a_vec3_vertex.xy + offset_pixels * u_float_tile_to_pixel_ratio, u_float_floor_elevation);
    vec4 clip_space_vertex;
    if (is_flat_mode()) {
        clip_space_vertex = get_clipspace(shifted_vertex_flat);
    } else {
        EcefTangentFrame ef = ecef_tangent_frame(a_vec3_vertex);
        vec2 offset_tile_points = offset_pixels * u_float_tile_to_pixel_ratio * 65535.0;
        vec3 shifted_vertex_ecef = ef.center +
            (ef.east * offset_tile_points.x + ef.north * offset_tile_points.y) * u_float_ecef_scale;
        clip_space_vertex = get_clipspace(shifted_vertex_ecef);
    }
    gl_Position = g_w_factor * clip_space_vertex;
    v_vec2_normal = normal;
    v_float_half_width = half_width;
    vec3 pos_world = calc_pos_world(shifted_vertex_flat);
    calc_fog_pos(pos_world);
#ifdef TAA
    apply_vertex_jitter(gl_Position);
#endif
    compute_shadow_vertex(clip_space_vertex, vec3(0.0, 0.0, 1.0), u_mat4_flat_mvp);
}
`,Qy=`#include <prelude>
#include <ecef_mvp_mat>
attribute vec3 a_vec3_vertex;
attribute vec4 a_vec4_normals;
attribute vec4 a_vec4_identifier;
uniform float u_float_width;
uniform float u_float_tile_to_pixel_ratio;
uniform float u_float_floor_elevation;
uniform float u_float_ecef_scale;
varying vec2 v_vec2_normal;
varying vec4 v_vec4_identifier;
varying float v_float_half_width;
const float g_w_factor = 1e-6;
const float normal_unpack_multiplier = 0.011135539861205473;
void main()
{
    
    float half_width = 0.5 * (u_float_width + 1.0);
    
    vec4 normals = a_vec4_normals * normal_unpack_multiplier * half_width;
    vec2 extender = normals.xy;
    vec2 normal = normals.zw;
    if (vec4(1., 1., 1., 1.) != a_vec4_identifier) {
        vec2 offset_pixels = extender;
        
        vec3 shifted_vertex_flat = vec3(a_vec3_vertex.xy + offset_pixels * u_float_tile_to_pixel_ratio, u_float_floor_elevation);
        vec4 clip_space_vertex;
        if (is_flat_mode()) {
            clip_space_vertex = get_clipspace(shifted_vertex_flat);
        } else {
            EcefTangentFrame ef = ecef_tangent_frame(a_vec3_vertex);
            vec2 offset_tile_points = offset_pixels * u_float_tile_to_pixel_ratio * 65535.0;
            vec3 shifted_vertex_ecef = ef.center +
                (ef.east * offset_tile_points.x + ef.north * offset_tile_points.y) * u_float_ecef_scale;
            clip_space_vertex = get_clipspace(shifted_vertex_ecef);
        }
        gl_Position = g_w_factor * clip_space_vertex;
    } else {
        gl_Position = vec4(1., 1., 1., 1.);
    }
    v_vec2_normal = normal;
    v_vec4_identifier = a_vec4_identifier;
    v_float_half_width = half_width;
}
`,Jy=`#include <prelude>
#include <ecef_mvp_mat>
#include <packed_attributes>
#include <pos_world>
#include <cam_pos>
#include <fog>
#include <jitter>
#include <shadow>
#ifndef UBO
uniform vec2 u_vec2_vpt_size;
#endif
uniform float u_float_width;
uniform float u_float_z_offset;
uniform float u_float_floor_elevation;
attribute vec3 a_vec3_vertex;
attribute vec4 a_vec4_direction_distance;
attribute float a_float_visibility;
varying float v_float_distance;
varying float v_float_distance_offset;
const float g_smooth_width = 1.;
const float g_min_denominator = 1e-4;
const float g_w_factor = 1e-6;
void main()
{
    
    if (a_float_visibility == 0.0) {
        gl_Position = vec4(0, 0, 1, 1);
        return;
    }
    float shift_pixels = 0.5 * max(u_float_width - 1., 0.);
    float shift_pixels_added = shift_pixels + g_smooth_width;
    vec3 direction = a_vec4_direction_distance.xyz;
    float distance = a_vec4_direction_distance.w;
    vec2 half_viewport = u_vec2_vpt_size / vec2(2.);
    vec4 clip_space_vertex = get_clipspace(a_vec3_vertex, u_float_floor_elevation);
    mat4 mvp = is_flat_mode() ? u_mat4_flat_mvp : u_mat4_ecef_mvp;
    vec4 clip_space_direction = normalize(mvp * vec4(normalize_s08(direction), 0.));
    vec2 screen_space_direction =
        (clip_space_direction.xy * clip_space_vertex.w - clip_space_vertex.xy * clip_space_direction.w) * half_viewport;
    vec2 screen_space_perp = vec2(-screen_space_direction.y, screen_space_direction.x);
    float denominator = max(g_min_denominator, length(screen_space_perp));
    gl_Position = g_w_factor * (clip_space_vertex + vec4(screen_space_perp / half_viewport, 0., 0.)
        * distance * shift_pixels_added / denominator * clip_space_vertex.w);
    gl_Position.z += u_float_z_offset;
    v_float_distance = shift_pixels_added * distance * gl_Position.w;
    v_float_distance_offset = shift_pixels;
    vec3 pos_world = calc_pos_world(vec3(a_vec3_vertex.xy, 0.));
    calc_fog_pos(pos_world);
#ifdef TAA
    apply_vertex_jitter(gl_Position);
#endif
    
    
    compute_shadow_vertex(clip_space_vertex);
}
`,Ky=`#include <prelude>
#include <mvp_mat>
#include <dem>
#include <packed_attributes>
#include <apply_height_factor>
#include <pos_world>
#include <cam_pos>
#include <fog>
#include <jitter>
#include <shadow>
#ifndef UBO
uniform vec2 u_vec2_vpt_size;
#endif
uniform float u_float_width;
uniform float u_float_height_factor;
uniform int u_int_abs_z;
uniform float u_float_z_offset;
uniform float u_float_floor_elevation;
uniform vec4 u_vec4_color;
uniform float u_float_mix_color;
attribute vec2 a_vec2_vertex;
attribute float a_float_z;
attribute vec4 a_vec4_direction_distance;
attribute vec2 a_vec2_dem_position;
attribute float a_float_abs_z;
attribute float a_float_is_pivot;
attribute float a_float_visibility;
attribute vec4 a_vec4_color;
varying float v_float_distance;
varying float v_float_distance_offset;
varying vec4 v_vec4_color;
const float g_smooth_width = 1.;
const float g_min_denominator = 1e-4;
const float g_w_factor = 1e-6;
void main()
{
    float height = 0.;
    if (u_int_abs_z == 0) {
        height = dem_height(unpack_dem_position(a_vec2_dem_position));
        
        if (a_float_z == 0.) {
            float posHeight = dem_height(a_vec2_vertex);
            if (height > posHeight) {
                height = posHeight;
            }
        }
    } else {
        if (a_float_is_pivot == 1.) {
            height = dem_height(a_vec2_vertex);
        } else {
            height = abs_height(a_float_abs_z);
        }
    }
    
    if (a_float_visibility == 0.0) {
        gl_Position = vec4(0, 0, 1, 1);
        return;
    }
    v_vec4_color = u_vec4_color;
    if (a_vec4_color[3] > 0. ) {
        v_vec4_color =  mix(v_vec4_color, a_vec4_color, u_float_mix_color);
    }
    height += u_float_floor_elevation;
    float shift_pixels = 0.5 * max(u_float_width - 1., 0.);
    float shift_pixels_added = shift_pixels + g_smooth_width;
    vec3 direction = a_vec4_direction_distance.xyz;
    float distance = a_vec4_direction_distance.w;
    vec2 half_viewport = u_vec2_vpt_size / vec2(2.);
    
    
    vec4 clip_space_direction = normalize(u_mat4_mvp * vec4(normalize_s08(direction), 0.));
    
    vec4 vertex_hf = apply_height_factor(vec3(a_vec2_vertex, a_float_z), u_float_height_factor);
    vertex_hf.z += height;
    vec4 clip_space_vertex = u_mat4_mvp * vertex_hf;
    vec2 screen_space_direction =
        (clip_space_direction.xy * clip_space_vertex.w - clip_space_vertex.xy * clip_space_direction.w) * half_viewport;
    vec2 screen_space_perp = vec2(-screen_space_direction.y, screen_space_direction.x);
    float denominator = max(g_min_denominator, length(screen_space_perp));
    gl_Position = g_w_factor * (clip_space_vertex + vec4(screen_space_perp / half_viewport, 0., 0.)
        * distance * shift_pixels_added / denominator * clip_space_vertex.w);
    gl_Position.z += u_float_z_offset;
    v_float_distance = shift_pixels_added * distance * gl_Position.w;
    v_float_distance_offset = shift_pixels;
    vec3 pos_world = calc_pos_world(vertex_hf.xyz);
    calc_fog_pos(pos_world);
#ifdef TAA
    apply_vertex_jitter(gl_Position);
#endif
    
    
    compute_shadow_vertex(clip_space_vertex);
}
`,eT=`#include <prelude>
#include <mvp_mat>
uniform float u_float_scale;
uniform vec3 u_vec3_transform;
attribute vec3 a_vec3_position;
varying vec3 v_position;
void main() {
    vec3 scaled_transformed = u_vec3_transform + a_vec3_position * u_float_scale;
    v_position = scaled_transformed;
    gl_Position = u_mat4_mvp * vec4(scaled_transformed, 1.0);
}
`,tT=`#include <prelude>
#include <pos_world>
#include <cam_pos>
#include <fog>
attribute vec2 a_vec2_vertex;
void main()
{
    gl_Position = vec4(a_vec2_vertex, 1.0, 1.0);
    calc_fog_pos_sky(gl_Position);
}
`,iT=`#include <prelude>
attribute vec3 a_vec3_position;
attribute float a_fade_opacity;
#ifndef UBO
uniform mat4 u_mat4_stars;
uniform float u_float_stars_intensity;
uniform float u_float_pixelratio;
#endif
varying mediump float v_intensity;
void main() {
    v_intensity = a_fade_opacity * u_float_stars_intensity;
    gl_PointSize = u_float_pixelratio;
    gl_Position = u_mat4_stars * vec4(a_vec3_position, 1.0);
}
`,nT=`#include <prelude>
#include <ecef_mvp_mat>
#include <packed_attributes>
#include <pixel_offset>
#include <calculate_scale>
#include <line_width>
#include <apply_opacity>
#include <precision_constants>
#include <striped_line_functions>
#include <pos_world>
#include <cam_pos>
#include <fog>
#include <jitter>
#include <shadow>
#include <dem>
#ifndef UBO
uniform mediump vec2 u_vec2_vpt_size;
#endif
uniform vec4 u_vec4_dash_color;
uniform vec4 u_vec4_space_color;
uniform vec4 u_vec4_border_color;
uniform vec3 u_vec3_projection_scale_style_scale_dpi;
uniform float u_float_width;
uniform float u_float_width_offset;
uniform vec2 u_vec2_scaler_params;
uniform float u_float_dash_length;
uniform float u_float_space_length;
uniform float u_float_dash2_length;
uniform float u_float_opacity;
uniform bool u_bool_is_3d_line;
uniform float u_float_floor_elevation;
uniform float u_float_ecef_scale;
attribute vec3 a_vec3_vertex;
attribute vec2 a_vec2_texture_widen;
attribute vec2 a_vec2_widen;
attribute float a_float_vertex_distance;
attribute float a_float_component_distance;
attribute float a_float_object_length;
attribute float a_float_height;
varying vec4 v_vec4_dash_color;
varying vec4 v_vec4_space_color;
varying vec4 v_vec4_border_color;
varying vec2 v_vec2_circle;
varying float v_float_width;
varying vec2 v_vec2_line_params;
const float g_shift_pixels = 2.;
const float g_w_factor = 1e-7;
PolylineDistance decode_line_distance()
{
    return PolylineDistance(
        a_float_vertex_distance,
        a_float_component_distance,
        a_float_object_length);
}
StripedLineInParams decode_line_params(const Scale scale)
{
    float width = calculate_final_width(scale, u_float_width, u_float_width_offset);
    float dash_length  = scale.calculation * u_float_dash_length;
    float space_length = scale.calculation * u_float_space_length;
    float dash2_length = scale.calculation * u_float_dash2_length;
    return StripedLineInParams(
        dash_length,
        space_length,
        dash2_length,
        width);
}
vec4 get_clip_direction(const vec2 dir, const vec3 east, const vec3 north)
{
    vec4 flat_clip = u_mat4_flat_mvp * vec4(dir, 0., 0.);
    if (u_float_ecef_scale <= 0.) {
        return flat_clip;
    }
    vec3 ecef_dir = (east * dir.x + north * dir.y) * u_float_ecef_scale * 65535.;
    vec4 ecef_clip = u_mat4_ecef_mvp * vec4(ecef_dir * ECEF_WORLD, 0.);
    return mix(flat_clip, ecef_clip, u_float_crossfade);
}
void main()
{
    float height = 0.;
    if (u_bool_is_3d_line == true) {
        height = dem_height(a_vec3_vertex.xy);
    }
    if (u_bool_is_3d_line == true) {
        height += a_float_height / (65535. * 32.);
    }
    
    vec3 east = vec3(0.);
    vec3 north = vec3(0.);
    if (!is_flat_mode()) {
        vec3 ecef_pos = DECODE_ECEF(a_vec3_vertex);
        vec3 n = normalize(ecef_pos);
        vec3 raw_east = cross(vec3(0., 1., 0.), n);
        raw_east = dot(raw_east, raw_east) > 1e-12 ? raw_east : cross(vec3(1., 0., 0.), n);
        east = normalize(raw_east);
        north = cross(n, east);
    }
    Scale scale = calculate_scale(u_vec3_projection_scale_style_scale_dpi, u_vec2_scaler_params);
    StripedLineInParams params = decode_line_params(scale);
    vec2 widen = unpack_widen(a_vec2_widen);
    vec2 widen_perp = vec2(-widen.y, widen.x);
    
    vec4 clip_space_widen = get_clip_direction(widen, east, north);
    vec4 clip_space_widen_perp = get_clip_direction(widen_perp, east, north);
    
    vec4 clip_space_vertex = get_clipspace(a_vec3_vertex, height + u_float_floor_elevation) + clip_space_widen * params.line_width;
    vec2 half_viewport = 0.5 * u_vec2_vpt_size;
    
    float limited_factor = calculate_multiplication_factor(
        half_viewport,
        clip_space_widen,
        clip_space_widen_perp,
        clip_space_vertex,
        g_shift_pixels);
    PolylineDistance distance_decoded = decode_line_distance();
    StripedLineOutParams output_params;
    calculate_line_params(distance_decoded, params, output_params);
    
    
    vec2 texture_widen_with_shift_sign = unpack_widen(a_vec2_texture_widen);
    float shift_sign = sign(dot(widen, texture_widen_with_shift_sign));
    vec2 texture_widen = shift_sign * texture_widen_with_shift_sign;
    vec2 texture_widen_perp = vec2(-texture_widen.y, texture_widen.x);
    float distance_shift = shift_sign * abs(dot(widen, texture_widen_perp)) * params.line_width;
    float circle_factor = g_circle_scale_precision_factor / scale.calculation;
    v_vec2_circle = texture_widen * (params.line_width + limited_factor) * circle_factor;
    v_float_width = params.line_width * circle_factor;
    v_vec2_line_params[0] = output_params.part_color_swap_threshold;
    v_vec2_line_params[1] = output_params.distance_in_parts;
    v_vec4_dash_color = apply_opacity(u_vec4_dash_color, u_float_opacity);
    v_vec4_space_color = apply_opacity(u_vec4_space_color, u_float_opacity);
    v_vec4_border_color = apply_opacity(u_vec4_border_color, u_float_opacity);
    gl_Position = clip_space_vertex + clip_space_widen * limited_factor;
    vec3 pos_world = calc_pos_world(vec3(a_vec3_vertex.xy, 0.));
    calc_fog_pos(pos_world);
#ifdef TAA
    apply_vertex_jitter(gl_Position);
#endif
    gl_Position *= g_w_factor;
    compute_shadow_vertex(clip_space_vertex, vec3(0.0, 0.0, 1.0), u_mat4_flat_mvp);
}
`,rT=`#include <prelude>
#include <ecef_mvp_mat>
#include <packed_attributes>
#include <pixel_offset>
#include <calculate_scale>
#include <line_width>
#include <apply_opacity>
#include <precision_constants>
#include <striped_line_functions>
#include <dem>
#ifndef UBO
uniform mediump vec2 u_vec2_vpt_size;
#endif
uniform vec4 u_vec4_dash_color;
uniform vec4 u_vec4_space_color;
uniform vec4 u_vec4_border_color;
uniform vec3 u_vec3_projection_scale_style_scale_dpi;
uniform float u_float_width;
uniform float u_float_width_offset;
uniform vec2 u_vec2_scaler_params;
uniform float u_float_dash_length;
uniform float u_float_space_length;
uniform float u_float_dash2_length;
uniform float u_float_opacity;
uniform bool u_bool_is_3d_line;
uniform float u_float_ecef_scale;
attribute vec3 a_vec3_vertex;
attribute vec2 a_vec2_texture_widen;
attribute vec2 a_vec2_widen;
attribute float a_float_vertex_distance;
attribute float a_float_component_distance;
attribute float a_float_object_length;
attribute vec4 a_vec4_identifier;
attribute float a_float_height;
varying vec4 v_vec4_identifier;
const float g_shift_pixels = 2.;
const float g_w_factor = 1e-7;
PolylineDistance decode_line_distance()
{
    return PolylineDistance(
        a_float_vertex_distance,
        a_float_component_distance,
        a_float_object_length);
}
StripedLineInParams decode_line_params(const Scale scale)
{
    float width = calculate_final_width(scale, u_float_width, u_float_width_offset);
    float dash_length  = scale.calculation * u_float_dash_length;
    float space_length = scale.calculation * u_float_space_length;
    float dash2_length = scale.calculation * u_float_dash2_length;
    return StripedLineInParams(
        dash_length,
        space_length,
        dash2_length,
        width);
}
vec4 get_clip_direction(const vec2 dir, const vec3 east, const vec3 north)
{
    vec4 flat_clip = u_mat4_flat_mvp * vec4(dir, 0., 0.);
    if (u_float_ecef_scale <= 0.) {
        return flat_clip;
    }
    vec3 ecef_dir = (east * dir.x + north * dir.y) * u_float_ecef_scale * 65535.;
    vec4 ecef_clip = u_mat4_ecef_mvp * vec4(ecef_dir * ECEF_WORLD, 0.);
    return mix(flat_clip, ecef_clip, u_float_crossfade);
}
void main()
{
    float height = 0.;
    if (u_bool_is_3d_line == true) {
        height = dem_height(a_vec3_vertex.xy);
    }
    if (u_bool_is_3d_line == true) {
        height += a_float_height / (65535. * 32.);
    }
    
    vec3 east = vec3(0.);
    vec3 north = vec3(0.);
    if (!is_flat_mode()) {
        vec3 ecef_pos = DECODE_ECEF(a_vec3_vertex);
        vec3 n = normalize(ecef_pos);
        vec3 raw_east = cross(vec3(0., 1., 0.), n);
        raw_east = dot(raw_east, raw_east) > 1e-12 ? raw_east : cross(vec3(1., 0., 0.), n);
        east = normalize(raw_east);
        north = cross(n, east);
    }
    Scale scale = calculate_scale(u_vec3_projection_scale_style_scale_dpi, u_vec2_scaler_params);
    StripedLineInParams params = decode_line_params(scale);
    vec2 widen = unpack_widen(a_vec2_widen);
    vec2 widen_perp = vec2(-widen.y, widen.x);
    
    vec4 clip_space_widen = get_clip_direction(widen, east, north);
    vec4 clip_space_widen_perp = get_clip_direction(widen_perp, east, north);
    
    vec4 clip_space_vertex = get_clipspace(a_vec3_vertex, height) + clip_space_widen * params.line_width;
    vec2 half_viewport = 0.5 * u_vec2_vpt_size;
    
    float limited_factor = calculate_multiplication_factor(
        half_viewport,
        clip_space_widen,
        clip_space_widen_perp,
        clip_space_vertex,
        g_shift_pixels);
    PolylineDistance distance_decoded = decode_line_distance();
    StripedLineOutParams output_params;
    calculate_line_params(distance_decoded, params, output_params);
    v_vec4_identifier = a_vec4_identifier;
    if (vec4(1., 1., 1., 1.) != a_vec4_identifier)
    {
        gl_Position = (clip_space_vertex + clip_space_widen * limited_factor) * g_w_factor;
    }
    else
    {
        gl_Position = vec4(1., 1., 1., 1.);
    }
}
`,sT=`#include <prelude>
#include <mvp_mat>
#include <dem>
#include <packed_attributes>
#include <apply_height_factor>
#include <apply_opacity>
#include <pos_world>
#include <cam_pos>
#include <fog>
#include <clipspace_pos>
#include <jitter>
#include <shadow>
uniform float u_float_height_factor;
uniform float u_float_floor_elevation;
uniform int u_int_texture_index;
attribute vec2 a_vec2_vertex;
attribute float a_float_z;
attribute vec2 a_vec2_dem_position;
attribute float a_float_visibility;
attribute vec2 a_vec2_wall_size; 
attribute vec2 a_vec2_quad_fraction; 
varying vec4 v_vec4_rotated_scaled_vertex;
varying vec2 v_vec2_quad_fraction;
varying vec2 v_vec2_wall_size_su;
const float g_wall_offset_isometric = 0.001;
const float g_wall_offset_perspective = 8.;
const float g_wall_texture_offset = 0.0000000005;
void main()
{
    
    if (a_float_visibility == 0.0) {
        gl_Position = vec4(0, 0, 1, 1);
        return;
    }
    float height = dem_height(unpack_dem_position(a_vec2_dem_position));
    
    if (a_float_z == 0.) {
        float posHeight = dem_height(a_vec2_vertex);
        if (height > posHeight) {
            height = posHeight;
        }
    }
    height += u_float_floor_elevation;
    vec3 vertex = vec3(a_vec2_vertex, a_float_z);
    vec4 vertex_hf = apply_height_factor(vertex, u_float_height_factor);
    vertex_hf.z += height;
    
    vertex_hf.z = max(vertex_hf.z, height);
    
    
    vec3 cam_dir = normalize(u_cam_pos - calc_pos_world(vertex_hf));
    float dist = length(u_cam_pos - calc_pos_world(vertex_hf));
    float scaled_offset = (g_wall_texture_offset + 0.0000000001 * float(u_int_texture_index)) * dist;
    vertex_hf.xyz += cam_dir * scaled_offset;
    vec4 clip_pos = u_mat4_mvp * vertex_hf;
    gl_Position = clip_pos;
    
    
    if ((u_mat4_mvp[0][3] == 0.) && (u_mat4_mvp[1][3] == 0.) && (u_mat4_mvp[2][3] == 0.))
    {
        gl_Position.z += g_wall_offset_isometric;
    }
    else
    {
        
        
        
        if (height == 0.) {
            gl_Position.z += g_wall_offset_perspective;
        } else {
            gl_Position.z += g_wall_offset_isometric;
        }
    }
    vec3 pos_world = calc_pos_world(vertex_hf);
    calc_fog_pos(pos_world);
    save_clipspace_pos();
#ifdef TAA
    apply_vertex_jitter(gl_Position);
#endif
    
    
    mat3 rotation_scale_mat = mat3(u_mat4_model);
    v_vec4_rotated_scaled_vertex.xyz = rotation_scale_mat * vertex;
    
    compute_shadow_vertex(clip_pos);
    v_vec2_quad_fraction = a_vec2_quad_fraction;
    v_vec2_wall_size_su = a_vec2_wall_size;
}
`,oT=`#include <prelude>
#include <mvp_mat>
#include <dem>
#include <packed_attributes>
#include <apply_height_factor>
#include <pos_world>
#include <cam_pos>
#include <fog>
#include <clipspace_pos>
#include <jitter>
#include <shadow>
uniform float u_float_height_factor;
attribute vec2 a_vec2_vertex;
attribute float a_float_z;
attribute vec2 a_vec2_texcoord;
attribute vec2 a_vec2_dem_position;
varying vec2 v_vec2_texcoord;
varying vec3 v_vec3_rotated_scaled_vertex;
void main()
{
    float height = dem_height(unpack_dem_position(a_vec2_dem_position));
    v_vec2_texcoord = unpack_model_texcoord(a_vec2_texcoord);
    vec3 vertex = vec3(a_vec2_vertex, a_float_z);
    vec4 vh = apply_height_factor(vertex, u_float_height_factor);
    vh.z += height;
    vec3 pos_world = calc_pos_world(vh);
    calc_fog_pos(pos_world);
    gl_Position = u_mat4_mvp * vh;
    
    
    mat3 rotation_scale_mat = mat3(u_mat4_model);
    v_vec3_rotated_scaled_vertex = rotation_scale_mat * vertex;
    save_clipspace_pos();
#ifdef TAA
    apply_vertex_jitter(gl_Position);
#endif
    
    compute_shadow_vertex(gl_Position);
}
`,aT=`#include <prelude>
#include <mvp_mat>
#include <dem>
#include <round_position>
#ifndef UBO
uniform vec2 u_vec2_vpt_size;
#endif
attribute vec2 a_vec2_vertex;
attribute float a_float_z;
attribute vec4 a_vec4_identifier;
attribute vec2 a_vec2_dem_position;
varying vec4 v_vec4_identifier;
void main()
{
    float height = dem_height(unpack_dem_position(a_vec2_dem_position));
    v_vec4_identifier = a_vec4_identifier;
    if (vec4(1., 1., 1., 1.) != a_vec4_identifier)
    {
        gl_Position = round_position(u_mat4_mvp * vec4(a_vec2_vertex, a_float_z + height, 1.), .5 * u_vec2_vpt_size);
    }
    else
    {
        gl_Position = vec4(1., 1., 1., 1.);
    }
}
`,lT=`#include <prelude>
#include <mvp_mat>
#include <dem>
#include <apply_height_factor>
uniform float u_float_height_factor;
attribute vec2 a_vec2_vertex;
attribute float a_float_z;
attribute vec2 a_vec2_dem_position;
varying float v_depth_metric;
void main()
{
    float height = dem_height(unpack_dem_position(a_vec2_dem_position));
    vec4 vh = apply_height_factor(vec3(a_vec2_vertex, a_float_z), u_float_height_factor);
    vh.z += height;
    gl_Position = u_mat4_mvp * vh;
    v_depth_metric = (gl_Position.z + 1.0) / 2.0;
}
`,cT={apply_height_factor:kS,apply_opacity:Yu,arrow_functions:US,calculate_scale:MS,cam_pos:Qu,clipspace_pos:HS,dem:GS,depth_test:VS,ecef_mvp_mat:ZS,fog:WS,jitter:jS,line_width:XS,mix_color_defs:Ju,mvp_mat:$S,packed_attributes:qS,pixel_offset:YS,pos_world:QS,precision_constants:JS,prelude:KS,raster_functions:ey,round_position:ty,shadow:iy,show_ratio:ny,signed_distance_functions:Ku,striped_line_functions:ry,surface_height:sy},dT={arrow_line_entrance:oy,building_shadow:ay,circle_marker:ly,circle_marker_identify:cy,color:dy,color_identify:uy,dem_elevation:hy,dem_elevation_copy:_y,dem_flat_bottom:fy,dem_ground:my,dem_ground2:vy,dem_mesh:gy,dem_mesh2:py,dem_mesh2_depthtest:xy,dem_mesh2_shadow:by,dem_normal:Sy,diffuse:yy,diffuse_identify:Ty,globe_halo:Ey,gltf_model:Cy,gltf_shadow:Iy,heatmap:Py,heatmap_texture:Ay,label_directional:Ly,label_directional_screen:Ry,label_fixed_anchor:Fy,label_fixed_anchor_identify:Dy,line:zy,line3d:By,line3d_identify:Oy,map_mesh:wy,mesh:Ny,mesh_shadow:ky,metric_point:Uy,one_way_line:My,particle_billboard:Hy,particle_stretch:Gy,one_way_line_screen:Vy,patterned_line:Zy,point_anchor:Wy,pointsprite:jy,pointsprite_identify:Xy,posteffect:$y,rect_with_texture:qy,road:Yy,road_identify:Qy,simple_line_2d:Jy,simple_line_3d:Ky,simple_mesh:eT,sky:tT,stars:iT,striped_line:nT,striped_line_identify:rT,wall_texture:sT,zbm_model:oT,zbm_model_identify:aT,zbm_shadow:lT},uT=/^\s*#include\s+<(.+)>.*$/gim,hT=(s,e)=>(t,i)=>{const r=i.trim(),o=s==="vertex"?cT[r]:wS[r];if(!o)throw new Error(`Cannot resolve "include <${r}>" in ${s} shader "${e}"`);return o+`
`};function eh(s,e){return[(s==="vertex"?dT[e]:NS[e]).replace(uT,hT(s,e))]}function k(s){const e=kn.webglVersion===2?["#version 300 es"]:[],t=n.Shader.createShaderDefinitions([{type:`WEBGL${kn.webglVersion}`,value:""},{type:fx,value:""}]);return i=>new n.Shader("vertex",e.concat(eh("vertex",s)),t,i)}function U(s){const e=kn.webglVersion===2?["#version 300 es"]:[],t=n.Shader.createShaderDefinitions([{type:`WEBGL${kn.webglVersion}`,value:""},{type:_x,value:""}]);return i=>new n.Shader("fragment",e.concat(eh("fragment",s)),t,i)}const oe={name:"u_mat4_mvp",type:"mat4"},Ge=[{name:"u_mat4_flat_mvp",type:"mat4"},{name:"u_mat4_ecef_mvp",type:"mat4"},{name:"u_mat4_vp",type:"mat4"},{name:"u_vec2_camera_merc",type:"2f"},{name:"u_vec4_vp_at_center",type:"4f"},{name:"u_float_crossfade",type:"1f"}],ce={name:"u_mat4_model",type:"mat4"},Ha=[{name:"u_vec2_anchor",type:"2f"},{name:"u_vec4_axis",type:"4f"},{name:"u_int_gltf_dem_pos",type:"1i"}],se=[{name:"u_tex_dem",type:"1i"},{name:"u_tex_corrected_dem",type:"1i"},{name:"u_float_corrected_interval",type:"1f"},{name:"u_mat4_dem_corrected",type:"mat4"},{name:"u_tex_hillshade_ramp",type:"1i"},{name:"u_mat4_dem_mvp",type:"mat4"},{name:"u_float_dem_scale",type:"1f"},{name:"u_float_vertical_scale",type:"1f"},{name:"u_float_dem_resolution",type:"1f"},{name:"u_float_dem_cell_size",type:"1f"},{name:"u_float_dem_shading_intensity",type:"1f"},{name:"u_float_map_center_elevation",type:"1f"}],jt=[{name:"u_int_abs_z",type:"1i"}],bi=[{name:"u_bool_surface_use_abs_z",type:"1i"},{name:"u_float_surface_relative_z_norm",type:"1f"},{name:"u_float_surface_abs_z",type:"1f"}],ue=[{name:"u_cam_pos",type:"3f"}],Ae=[{name:"u_int_light_flags",type:"1i"},{name:"u_vec4_ambient_color",type:"4fv"},{name:"u_vec3_light_dir1_direction",type:"3fv"},{name:"u_vec4_light_dir1_color",type:"4fv"},{name:"u_vec3_light_dir2_direction",type:"3fv"},{name:"u_vec4_light_dir2_color",type:"4fv"}],Le=[{name:"u_texture_shadow",type:"1i"},{name:"u_mat4_clip_to_shadow",type:"mat4"},{name:"u_shadow_map_params",type:"4f"},{name:"u_shadow_bias",type:"1f"}],he=[{name:"u_fog_color",type:"4f"},{name:"u_fog_color2",type:"4f"},{name:"u_fog_gradient",type:"2f"},{name:"u_sky_color",type:"4f"},{name:"u_fog_limits",type:"2f"},{name:"u_fog_horizon_blend",type:"1f"},{name:"u_fog_horizon_level",type:"1f"},{name:"u_fog_horizon_pad",type:"1f"},{name:"u_mat4_model",type:"mat4"},{name:"u_fog_distance",type:"1f"},{name:"u_mat4_proj_inverted",type:"mat4"},{name:"u_mat4_view_transposed",type:"mat4"}],De=[{name:"u_vec2_camera_jitter",type:"2f"}],ki=[{name:"u_vec4_color_effect_mix_rgba",type:"4f"},{name:"u_float_color_effect_mix_factor",type:"1f"}];function _T(){return{simpleMesh:{buildFragment:U("simple_mesh"),buildVertex:k("simple_mesh"),attributes:[{name:"a_vec3_position",location:0},{name:"a_vec3_normal",location:1}],uniforms:[oe,{name:"u_float_scale",type:"1f"},{name:"u_vec3_transform",type:"3fv"}]},diffuse:{buildVertex:k("diffuse"),buildFragment:U("color_with_z_fade"),uniforms:[oe,ce,{name:"u_vec4_color",type:"4fv"},{name:"u_float_mix_color",type:"1f"},{name:"u_float_height_factor",type:"1f"},{name:"u_float_opacity",type:"1f"},{name:"u_sdtr_distance",type:"1f"},{name:"u_float_floor_elevation",type:"1f"},{name:"u_int_is_roof",type:"1i"},{name:"u_int_is_hole",type:"1i"},...ue,...Ae,...Le,...se,...he,...De,...ki],attributes:[{name:"a_vec2_vertex",location:0},{name:"a_float_z",location:1},{name:"a_vec2_dem_position",location:2},{name:"a_float_visibility",location:3},{name:"a_vec2_tex_coords",location:4},{name:"a_vec4_color",location:5}]},gradientDiffuse:{buildVertex:k("diffuse"),buildFragment:U("gradient_with_z_fade"),uniforms:[oe,ce,{name:"u_vec4_color",type:"4fv"},{name:"u_float_mix_color",type:"1f"},{name:"u_float_height_factor",type:"1f"},{name:"u_float_opacity",type:"1f"},{name:"u_mat4_gradient",type:"mat4"},{name:"u_sdtr_distance",type:"1f"},{name:"u_float_floor_elevation",type:"1f"},{name:"u_vec2_floor_level",type:"2fv"},{name:"u_int_is_roof",type:"1i"},{name:"u_int_is_hole",type:"1i"},...ue,...Ae,...Le,...se,...he,...De,...ki],attributes:[{name:"a_vec2_vertex",location:0},{name:"a_float_z",location:1},{name:"a_vec2_dem_position",location:2},{name:"a_float_visibility",location:3},{name:"a_vec4_color",location:4},{name:"a_float_elevation",location:5}]},wallTexture:{buildVertex:k("wall_texture"),buildFragment:U("wall_texture"),uniforms:[oe,ce,{name:"u_float_height_factor",type:"1f"},{name:"u_float_mix_color",type:"1f"},{name:"u_sdtr_distance",type:"1f"},{name:"u_float_floor_elevation",type:"1f"},{name:"u_sr2d_texture",type:"1i"},{name:"u_vec4_wall_padding_su",type:"4fv"},{name:"u_vec4_texture_padding_un",type:"4fv"},{name:"u_vec2_texture_part_count",type:"2fv"},{name:"u_vec2_max_interval_su",type:"2fv"},{name:"u_vec2_texture_slice_size_su",type:"2fv"},{name:"u_ivec2_layout_mode",type:"2iv"},{name:"u_int_texture_index",type:"1i"},...ue,...Ae,...Le,...se,...he,...De],attributes:[{name:"a_vec2_vertex",location:0},{name:"a_float_z",location:1},{name:"a_vec2_dem_position",location:2},{name:"a_float_visibility",location:3},{name:"a_vec2_wall_size",location:4},{name:"a_vec2_quad_fraction",location:5},{name:"a_vec4_color",location:6}]},labelLine:{buildVertex:k("label_directional"),buildFragment:U("label_directional"),uniforms:[oe,ce,{name:"u_float_tile_to_pixel_ratio",type:"1f"},{name:"u_sr2d_texture",type:"1i"},{name:"u_float_buffer",type:"1f"},{name:"u_float_gamma",type:"1f"},{name:"u_float_scale",type:"1f"},{name:"u_vec4_color",type:"4fv"},{name:"u_float_style_zoom",type:"1f"},{name:"u_float_height_factor",type:"1f"},{name:"u_float_opacity",type:"1f"},...ue,...he],attributes:[{name:"a_vec4_position",location:0},{name:"a_vec2_offset",location:1},{name:"a_vec2_texcoord",location:2},{name:"a_vec2_style_zoom_limits",location:3}]},labelLineBillboard:{buildVertex:k("label_directional_screen"),buildFragment:U("label_directional_screen"),uniforms:[oe,ce,{name:"u_vec2_vpt_size",type:"2fv"},{name:"u_sr2d_texture",type:"1i"},{name:"u_sr2d_texture1",type:"1i"},{name:"u_vec2_guideline_tex_size",type:"2fv"},{name:"u_float_center_distance",type:"1f"},{name:"u_float_buffer",type:"1f"},{name:"u_float_gamma",type:"1f"},{name:"u_float_scale",type:"1f"},{name:"u_vec4_color",type:"4fv"},{name:"u_vec4_hidden_color",type:"4fv"},{name:"u_float_height_factor",type:"1f"},{name:"u_float_opacity",type:"1f"},{name:"u_int_depth_test",type:"1i"},{name:"u_bool_depth_test_disable",type:"1i"},{name:"u_depth_tex_labeling",type:"1i"},{name:"u_color_tex_labeling",type:"1i"},...se,...ue,...he],attributes:[{name:"a_vec2_texcoord",location:0},{name:"a_vec2_anchor_params",location:1},{name:"a_vec2_guideline_params",location:2},{name:"a_float_center_offset",location:3},{name:"a_vec2_corner_offset",location:4},{name:"a_vec4_identifier",location:5},{name:"a_float_glyph_height_offset",location:6}]},labelPoint:{buildVertex:k("label_fixed_anchor"),buildFragment:U("label"),uniforms:[...Ge,ce,{name:"u_vec2_vpt_size",type:"2f"},{name:"u_sr2d_texture",type:"1i"},{name:"u_float_buffer",type:"1f"},{name:"u_float_gamma",type:"1f"},{name:"u_float_scale",type:"1f"},{name:"u_vec4_color",type:"4fv"},{name:"u_vec4_hidden_color",type:"4fv"},{name:"u_float_label_index",type:"1f"},{name:"u_float_opacity",type:"1f"},{name:"u_vec2_offset",type:"2f"},{name:"u_float_height_factor",type:"1f"},{name:"u_depth_tex_labeling",type:"1i"},{name:"u_color_tex_labeling",type:"1i"},{name:"u_color_text_sprite_labeling",type:"1i"},{name:"u_vec2_depth_test_half_point_size",type:"2f"},{name:"u_bool_skip_height_factor",type:"1i"},{name:"u_bool_depth_test_disable",type:"1i"},{name:"u_float_floor_elevation",type:"1f"},...bi,...ue,...se,...he],attributes:[{name:"a_vec3_vertex",location:0},{name:"a_vec2_offset",location:1},{name:"a_vec2_texcoord",location:2},{name:"a_vec2_check_offset",location:3},{name:"a_vec4_tex_identifier",location:4},{name:"a_vec4_sprite_identifier",location:5}]},labelPointIdentify:{buildVertex:k("label_fixed_anchor_identify"),buildFragment:U("color_identify"),uniforms:[...Ge,{name:"u_vec2_vpt_size",type:"2f"},{name:"u_float_scale",type:"1f"},{name:"u_vec2_offset",type:"2f"},{name:"u_float_floor_elevation",type:"1f"},...bi,...se],attributes:[{name:"a_vec3_vertex",location:0},{name:"a_vec2_offset",location:1},{name:"a_vec4_identifier",location:2}]},line:{buildVertex:k("line"),buildFragment:U("line"),uniforms:[...Ge,ce,{name:"u_vec2_vpt_size",type:"2fv"},{name:"u_vec4_color",type:"4fv"},{name:"u_float_mix_color",type:"1f"},{name:"u_float_height_factor",type:"1f"},{name:"u_float_opacity",type:"1f"},{name:"u_mat4_gradient",type:"mat4"},{name:"u_float_floor_elevation",type:"1f"},...ue,...Ae,...Le,...se,...he,...De,...ki],attributes:[{name:"a_vec3_vertex",location:0},{name:"a_float_z",location:1},{name:"a_vec2_normal",location:2},{name:"a_vec2_normal_delta",location:3},{name:"a_vec3_direction",location:4},{name:"a_float_distance",location:5},{name:"a_vec2_dem_position",location:6},{name:"a_float_visibility",location:7},{name:"a_vec4_color",location:8}]},pointSprite:{buildVertex:k("pointsprite"),buildFragment:U("pointsprite"),uniforms:[...Ge,ce,{name:"u_vec2_vpt_size",type:"2fv"},{name:"u_vec3_projection_scale_style_scale_dpi",type:"3fv"},{name:"u_sr2d_texture",type:"1i"},{name:"u_float_rounding_factor",type:"1f"},{name:"u_float_height_factor",type:"1f"},{name:"u_vec2_opacity",type:"2f"},{name:"u_vec2_rotation",type:"2fv"},{name:"u_depth_tex_labeling",type:"1i"},{name:"u_color_tex_labeling",type:"1i"},{name:"u_vec2_depth_test_half_point_size",type:"2f"},{name:"u_bool_skip_height_factor",type:"1i"},{name:"u_bool_depth_test_disable",type:"1i"},{name:"u_float_floor_elevation",type:"1f"},...bi,...ue,...se,...he],attributes:[{name:"a_vec3_vertex",location:0},{name:"a_vec2_offset",location:1},{name:"a_vec2_check_offset",location:2},{name:"a_vec2_texcoord",location:3},{name:"a_vec2_range",location:4},{name:"a_vec2_rescale",location:5},{name:"a_vec4_tex_identifier",location:6}]},pointSpriteIdentify:{buildVertex:k("pointsprite_identify"),buildFragment:U("pointsprite_identify"),uniforms:[...Ge,{name:"u_vec2_vpt_size",type:"2fv"},{name:"u_vec3_projection_scale_style_scale_dpi",type:"3fv"},{name:"u_sr2d_texture",type:"1i"},{name:"u_float_height_factor",type:"1f"},{name:"u_vec2_rotation",type:"2fv"},{name:"u_bool_skip_height_factor",type:"1i"},{name:"u_float_floor_elevation",type:"1f"},{name:"u_float_identify_opacity",type:"1f"},...bi,...se],attributes:[{name:"a_vec3_vertex",location:0},{name:"a_vec2_offset",location:1},{name:"a_vec2_texcoord",location:2},{name:"a_vec2_range",location:3},{name:"a_vec2_rescale",location:4},{name:"a_vec4_identifier",location:5}]},pointDepthTest:{buildVertex:k("point_anchor"),buildFragment:U("color_identify"),uniforms:[oe,{name:"u_vec2_vpt_size",type:"2f"},{name:"u_vec2_offset",type:"2f"},{name:"u_float_floor_elevation",type:"1f"},...bi,...se],attributes:[{name:"a_vec4_position",location:0},{name:"a_vec2_offset",location:1},{name:"a_vec4_identifier",location:2}]},stripedLine:{buildVertex:k("striped_line"),buildFragment:U("striped_line"),uniforms:[...Ge,ce,{name:"u_float_ecef_scale",type:"1f"},{name:"u_vec2_vpt_size",type:"2fv"},{name:"u_vec3_projection_scale_style_scale_dpi",type:"3fv"},{name:"u_vec2_scaler_params",type:"2fv"},{name:"u_float_dash_length",type:"1f"},{name:"u_float_space_length",type:"1f"},{name:"u_float_dash2_length",type:"1f"},{name:"u_vec4_dash_color",type:"4fv"},{name:"u_vec4_space_color",type:"4fv"},{name:"u_vec4_border_color",type:"4fv"},{name:"u_float_width",type:"1f"},{name:"u_float_width_offset",type:"1f"},{name:"u_int_gap_turns_only",type:"1i"},{name:"u_float_opacity",type:"1f"},{name:"u_bool_is_3d_line",type:"1i"},{name:"u_float_floor_elevation",type:"1f"},...ue,...he,...De,...Ae,...Le],attributes:[{name:"a_vec3_vertex",location:0},{name:"a_vec2_texture_widen",location:1},{name:"a_vec2_widen",location:2},{name:"a_float_vertex_distance",location:3},{name:"a_float_component_distance",location:4},{name:"a_float_object_length",location:5},{name:"a_vec4_identifier",location:6}]},stripedLine3D:{buildVertex:k("striped_line"),buildFragment:U("striped_line"),uniforms:[...Ge,ce,{name:"u_float_ecef_scale",type:"1f"},{name:"u_vec2_vpt_size",type:"2fv"},{name:"u_vec3_projection_scale_style_scale_dpi",type:"3fv"},{name:"u_vec2_scaler_params",type:"2fv"},{name:"u_float_dash_length",type:"1f"},{name:"u_float_space_length",type:"1f"},{name:"u_float_dash2_length",type:"1f"},{name:"u_vec4_dash_color",type:"4fv"},{name:"u_vec4_space_color",type:"4fv"},{name:"u_vec4_border_color",type:"4fv"},{name:"u_float_width",type:"1f"},{name:"u_float_width_offset",type:"1f"},{name:"u_int_gap_turns_only",type:"1i"},{name:"u_float_opacity",type:"1f"},{name:"u_bool_is_3d_line",type:"1i"},...se,...ue,...he,...De,...Ae,...Le],attributes:[{name:"a_vec3_vertex",location:0},{name:"a_vec2_texture_widen",location:1},{name:"a_vec2_widen",location:2},{name:"a_float_vertex_distance",location:3},{name:"a_float_component_distance",location:4},{name:"a_float_object_length",location:5},{name:"a_vec4_identifier",location:6},{name:"a_float_height",location:7}]},patternedLine:{buildVertex:k("patterned_line"),buildFragment:U("patterned_line"),uniforms:[oe,{name:"u_vec2_scales",type:"2fv"},{name:"u_vec4_color",type:"4fv"},{name:"u_float_width",type:"1f"},{name:"u_float_opacity",type:"1f"},{name:"u_int_pattern_type",type:"1i"},{name:"u_vec4_pattern_params",type:"4fv"},{name:"u_bool_is_3d_line",type:"1i"},ce,...ue,...he,...De,...Ae,...Le],attributes:[{name:"a_vec2_vertex",location:0},{name:"a_vec2_widen",location:1},{name:"a_float_texture",location:2},{name:"a_vec4_identifier",location:3}]},patternedLine3D:{buildVertex:k("patterned_line"),buildFragment:U("patterned_line"),uniforms:[oe,{name:"u_vec2_scales",type:"2fv"},{name:"u_vec4_color",type:"4fv"},{name:"u_float_width",type:"1f"},{name:"u_float_opacity",type:"1f"},{name:"u_int_pattern_type",type:"1i"},{name:"u_vec4_pattern_params",type:"4fv"},{name:"u_bool_is_3d_line",type:"1i"},ce,...se,...ue,...he,...De,...Ae,...Le],attributes:[{name:"a_vec2_vertex",location:0},{name:"a_vec2_widen",location:1},{name:"a_float_texture",location:2},{name:"a_vec4_identifier",location:3},{name:"a_float_height",location:4}]},stripedLineIdentify:{buildVertex:k("striped_line_identify"),buildFragment:U("color_identify"),uniforms:[...Ge,{name:"u_float_ecef_scale",type:"1f"},{name:"u_vec2_vpt_size",type:"2fv"},{name:"u_vec3_projection_scale_style_scale_dpi",type:"3fv"},{name:"u_vec2_scaler_params",type:"2fv"},{name:"u_float_dash_length",type:"1f"},{name:"u_float_space_length",type:"1f"},{name:"u_float_dash2_length",type:"1f"},{name:"u_vec4_dash_color",type:"4fv"},{name:"u_vec4_space_color",type:"4fv"},{name:"u_vec4_border_color",type:"4fv"},{name:"u_float_width",type:"1f"},{name:"u_float_width_offset",type:"1f"},{name:"u_int_gap_turns_only",type:"1i"},{name:"u_float_opacity",type:"1f"},{name:"u_bool_is_3d_line",type:"1i"},{name:"u_float_floor_elevation",type:"1f"}],attributes:[{name:"a_vec3_vertex",location:0},{name:"a_vec2_texture_widen",location:1},{name:"a_vec2_widen",location:2},{name:"a_float_vertex_distance",location:3},{name:"a_float_component_distance",location:4},{name:"a_float_object_length",location:5},{name:"a_vec4_identifier",location:6}]},stripedLine3DIdentify:{buildVertex:k("striped_line_identify"),buildFragment:U("color_identify"),uniforms:[...Ge,{name:"u_float_ecef_scale",type:"1f"},{name:"u_vec2_vpt_size",type:"2fv"},{name:"u_vec3_projection_scale_style_scale_dpi",type:"3fv"},{name:"u_vec2_scaler_params",type:"2fv"},{name:"u_float_dash_length",type:"1f"},{name:"u_float_space_length",type:"1f"},{name:"u_float_dash2_length",type:"1f"},{name:"u_vec4_dash_color",type:"4fv"},{name:"u_vec4_space_color",type:"4fv"},{name:"u_vec4_border_color",type:"4fv"},{name:"u_float_width",type:"1f"},{name:"u_float_width_offset",type:"1f"},{name:"u_int_gap_turns_only",type:"1i"},{name:"u_float_opacity",type:"1f"},{name:"u_bool_is_3d_line",type:"1i"},...se],attributes:[{name:"a_vec3_vertex",location:0},{name:"a_vec2_texture_widen",location:1},{name:"a_vec2_widen",location:2},{name:"a_float_vertex_distance",location:3},{name:"a_float_component_distance",location:4},{name:"a_float_object_length",location:5},{name:"a_vec4_identifier",location:6},{name:"a_float_height",location:7}]},vtxColor:{buildVertex:k("color"),buildFragment:U("textured_color"),uniforms:[...Ge,ce,{name:"u_vec4_color",type:"4fv"},{name:"u_float_opacity",type:"1f"},{name:"u_sr2d_texture",type:"1i"},{name:"u_float_texture_opacity",type:"1f"},{name:"u_float_texture_params",type:"4fv"},{name:"u_float_sprite_texture_coords",type:"4fv"},{name:"u_int_is_textured",type:"1i"},{name:"u_float_floor_elevation",type:"1f"},{name:"u_int_is_normal_map_textured",type:"1i"},{name:"u_sr2d_texture1",type:"1i"},{name:"u_vec4_normal_map_texture_params",type:"4fv"},{name:"u_vec4_normal_map_sprite_texture_coords",type:"4fv"},{name:"u_int_normal_map_is_animated",type:"1i"},{name:"u_vec4_normal_map_animated_offsets",type:"4fv"},{name:"u_float_metallic",type:"1f"},{name:"u_float_roughness",type:"1f"},{name:"u_vec4_color2",type:"4fv"},{name:"u_sr2d_read_from_target_texture",type:"1i"},{name:"u_float_factor_interpolate_base",type:"1f"},{name:"u_vec4_factor_interpolate_ranges",type:"4f"},{name:"u_int_factor_use_interpolate",type:"1i"},{name:"u_vec4_tilecoords",type:"4f"},...ue,...Ae,...Le,...he,...De,...ki],attributes:[{name:"a_vec3_vertex",location:0},{name:"a_float_visibility",location:1},{name:"a_float_mix_factor",location:2}]},vtxColorIdentify:{buildVertex:k("color_identify"),buildFragment:U("color_identify"),uniforms:[...Ge,{name:"u_vec2_vpt_size",type:"2fv"},{name:"u_float_floor_elevation",type:"1f"},{name:"u_int_is_3dfloor_object",type:"1i"}],attributes:[{name:"a_vec3_vertex",location:0},{name:"a_vec4_identifier",location:1},{name:"a_float_visibility",location:2}]},metricPoint:{buildVertex:k("metric_point"),buildFragment:U("metric_point"),uniforms:[oe,ce,{name:"u_vec4_color",type:"4fv"},{name:"u_sr2d_texture",type:"1i"},{name:"u_float_sprite_texture_coords",type:"4fv"},{name:"u_float_floor_elevation",type:"1f"},...ue,...he,...Ae,...Le],attributes:[{name:"a_vec2_vertex",location:0},{name:"a_vec2_texcoord",location:1}]},zbmModelIdentify:{buildVertex:k("zbm_model_identify"),buildFragment:U("color_identify"),uniforms:[oe,{name:"u_vec2_vpt_size",type:"2fv"},...se],attributes:[{name:"a_vec2_vertex",location:0},{name:"a_float_z",location:1},{name:"a_vec4_identifier",location:2},{name:"a_vec2_dem_position",location:3}]},buildingIdentify:{buildVertex:k("diffuse_identify"),buildFragment:U("color_identify"),uniforms:[oe,{name:"u_vec2_vpt_size",type:"2fv"},{name:"u_float_height_factor",type:"1f"},{name:"u_float_floor_elevation",type:"1f"},{name:"u_int_is_hole",type:"1i"},...se],attributes:[{name:"a_vec2_vertex",location:0},{name:"a_float_z",location:1},{name:"a_vec4_identifier",location:2},{name:"a_vec2_dem_position",location:3},{name:"a_float_visibility",location:4}]},oneWayLine:{buildVertex:k("one_way_line"),buildFragment:U("one_way_line"),uniforms:[oe,ce,{name:"u_vec2_vpt_size",type:"2f"},{name:"u_vec3_projection_scale_style_scale_dpi",type:"3fv"},{name:"u_vec4_color",type:"4f"},{name:"u_vec2_wing_normal",type:"2f"},{name:"u_vec2_tip_normal",type:"2f"},{name:"u_float_width",type:"1f"},{name:"u_float_length",type:"1f"},{name:"u_float_tip_radius_zpt",type:"1f"},{name:"u_float_wing_radius_zpt",type:"1f"},{name:"u_float_tail_radius_zpt",type:"1f"},{name:"u_float_border_width",type:"1f"},{name:"u_float_border_width_offset",type:"1f"},{name:"u_float_size_factor",type:"1f"},{name:"u_vec2_scale_limits",type:"2fv"},{name:"u_float_tip_height_multiplier",type:"1f"},{name:"u_float_wing_height_multiplier",type:"1f"},{name:"u_float_wing_width_multiplier",type:"1f"},{name:"u_float_opacity",type:"1f"},...ue,...he,...De],attributes:[{name:"a_vec2_position",location:0},{name:"a_vec2_direction",location:1},{name:"a_vec2_widen_direction",location:2}]},oneWayLineBillboard:{buildVertex:k("one_way_line_screen"),buildFragment:U("one_way_line_screen"),uniforms:[oe,ce,{name:"u_vec2_vpt_size",type:"2f"},{name:"u_vec4_color",type:"4f"},{name:"u_vec4_hidden_color",type:"4fv"},{name:"u_vec2_wing_normal",type:"2f"},{name:"u_vec2_tip_normal",type:"2f"},{name:"u_float_width",type:"1f"},{name:"u_float_length",type:"1f"},{name:"u_float_tip_radius_zpt",type:"1f"},{name:"u_float_wing_radius_zpt",type:"1f"},{name:"u_float_tail_radius_zpt",type:"1f"},{name:"u_float_border_width",type:"1f"},{name:"u_float_border_width_offset",type:"1f"},{name:"u_float_size_factor",type:"1f"},{name:"u_float_pixel_ratio",type:"1f"},{name:"u_float_center_distance",type:"1f"},{name:"u_float_tip_height_multiplier",type:"1f"},{name:"u_float_wing_height_multiplier",type:"1f"},{name:"u_float_wing_width_multiplier",type:"1f"},{name:"u_float_opacity",type:"1f"},{name:"u_int_depth_test",type:"1i"},{name:"u_bool_depth_test_disable",type:"1i"},{name:"u_depth_tex_labeling",type:"1i"},{name:"u_color_tex_labeling",type:"1i"},...se,...ue,...he,...De],attributes:[{name:"a_vec2_position",location:0},{name:"a_float_z",location:1},{name:"a_float_abs_z",location:2},{name:"a_vec2_direction",location:3},{name:"a_vec2_widen_direction",location:4},{name:"a_vec4_identifier",location:5}]},zbmModel:{buildVertex:k("zbm_model"),buildFragment:U("zbm_model"),uniforms:[oe,ce,{name:"u_vec4_color",type:"4fv"},{name:"u_sr2d_texture",type:"1i"},{name:"u_float_height_factor",type:"1f"},{name:"u_sdtr_distance",type:"1f"},...ue,...se,...he,...De,...Ae,...Le],attributes:[{name:"a_vec2_vertex",location:0},{name:"a_float_z",location:1},{name:"a_vec2_texcoord",location:2},{name:"a_vec2_dem_position",location:3}]},zbmShadow:{buildVertex:k("zbm_shadow"),buildFragment:U("main_shadow"),uniforms:[oe,{name:"u_float_height_factor",type:"1f"},...se],attributes:[{name:"a_vec2_vertex",location:0},{name:"a_float_z",location:1},{name:"a_vec2_dem_position",location:2}]},gltfModel:{buildVertex:k("gltf_model"),buildFragment:U("gltf_model"),uniforms:[...Ge,ce,{name:"u_mat4_instance",type:"mat4"},{name:"u_mat4_localmatrix",type:"mat4"},{name:"u_mat3_transform_tex_matrix",type:"mat3"},{name:"u_vec4_color",type:"4fv"},{name:"u_sr2d_texture_0",type:"1i"},{name:"u_ao_texture",type:"1i"},{name:"u_pbr_texture",type:"1i"},{name:"u_sdtr_distance",type:"1f"},{name:"u_float_height_factor",type:"1f"},{name:"u_float_show_ratio",type:"1f"},{name:"u_vec3_scale_factor",type:"3fv"},{name:"u_float_metallic",type:"1f"},{name:"u_float_roughness",type:"1f"},{name:"u_sampler_map_tex",type:"1i"},{name:"u_vec2_tex_scale",type:"2f"},{name:"u_float_tex_shift_scale",type:"1f"},{name:"u_float_floor_elevation",type:"1f"},{name:"u_int_extention_to_relief_needed",type:"1i"},{name:"u_int_is_extendable_to_relief_foundation",type:"1i"},{name:"u_int_collapse_height_needed",type:"1i"},{name:"u_sampler_vat",type:"1i"},{name:"u_float_vat_frame",type:"1f"},{name:"u_float_vat_texture_height",type:"1f"},{name:"u_vec3_vat_min",type:"3fv"},{name:"u_vec3_vat_max",type:"3fv"},...bi,...ue,...De,...he,...se,...Ae,...Le,...jt,...Ha,...ki],attributes:[{name:"position",location:0},{name:"normal",location:1},{name:"tangent",location:2},{name:"a_vec3_instance_position",location:3},{name:"a_mat3_instance_matrix",location:5,locationsCount:3},{name:"a_vec4_instance_localid",location:8},{name:"texcoord_color",location:9},{name:"texcoord_ao",location:10},{name:"texcoord_pbr",location:11},{name:"a_float_abs_z",location:12},{name:"a_float_instance_height",location:13},{name:"texcoord_vat",location:14}]},gltfModelIdentify:{buildVertex:k("gltf_model"),buildFragment:U("color_identify"),uniforms:[...Ge,ce,{name:"u_mat4_instance",type:"mat4"},{name:"u_mat4_localmatrix",type:"mat4"},{name:"u_mat3_transform_tex_matrix",type:"mat3"},{name:"u_vec4_color",type:"4fv"},{name:"u_sr2d_texture_0",type:"1i"},{name:"u_float_height_factor",type:"1f"},{name:"u_float_show_ratio",type:"1f"},{name:"u_vec3_scale_factor",type:"3fv"},{name:"u_int_identify",type:"1i"},{name:"u_int_is_tiered",type:"1i"},{name:"u_vec4_tier_color",type:"4fv"},{name:"u_float_floor_elevation",type:"1f"},{name:"u_int_extention_to_relief_needed",type:"1i"},{name:"u_int_is_extendable_to_relief_foundation",type:"1i"},{name:"u_int_collapse_height_needed",type:"1i"},{name:"u_sampler_vat",type:"1i"},{name:"u_float_vat_frame",type:"1f"},{name:"u_float_vat_texture_height",type:"1f"},{name:"u_vec3_vat_min",type:"3fv"},{name:"u_vec3_vat_max",type:"3fv"},...bi,...ue,...he,...se,...jt,...Ha],attributes:[{name:"position",location:0},{name:"normal",location:1},{name:"tangent",location:2},{name:"a_vec3_instance_position",location:3},{name:"a_mat3_instance_matrix",location:5,locationsCount:3},{name:"a_vec4_instance_localid",location:8},{name:"a_float_abs_z",location:12},{name:"a_float_instance_height",location:13},{name:"texcoord_vat",location:14},{name:"texcoord_color",location:9},{name:"texcoord_ao",location:10},{name:"texcoord_pbr",location:11}]},gltfModelShadow:{buildVertex:k("gltf_shadow"),buildFragment:U("main_shadow"),uniforms:[...Ge,{name:"u_mat4_instance",type:"mat4"},{name:"u_mat4_localmatrix",type:"mat4"},{name:"u_mat3_transform_tex_matrix",type:"mat3"},{name:"u_float_height_factor",type:"1f"},{name:"u_float_show_ratio",type:"1f"},{name:"u_vec3_scale_factor",type:"3fv"},{name:"u_int_extention_to_relief_needed",type:"1i"},{name:"u_int_is_extendable_to_relief_foundation",type:"1i"},{name:"u_int_collapse_height_needed",type:"1i"},{name:"u_sampler_vat",type:"1i"},{name:"u_float_vat_frame",type:"1f"},{name:"u_float_vat_texture_height",type:"1f"},{name:"u_vec3_vat_min",type:"3fv"},{name:"u_vec3_vat_max",type:"3fv"},...bi,{name:"u_float_floor_elevation",type:"1f"},...se,...jt,...Ha],attributes:[{name:"position",location:0},{name:"a_vec3_instance_position",location:3},{name:"a_mat3_instance_matrix",location:5,locationsCount:3},{name:"a_float_abs_z",location:12},{name:"a_float_instance_height",location:13},{name:"texcoord_vat",location:14}]},simpleLine2d:{buildVertex:k("simple_line_2d"),buildFragment:U("simple_line_2d"),uniforms:[...Ge,ce,{name:"u_vec2_vpt_size",type:"2fv"},{name:"u_vec4_color",type:"4fv"},{name:"u_float_width",type:"1f"},{name:"u_float_z_offset",type:"1f"},{name:"u_float_floor_elevation",type:"1f"},...ue,...De,...Ae,...he,...Le,...ki],attributes:[{name:"a_vec3_vertex",location:0},{name:"a_vec4_direction_distance",location:1},{name:"a_float_visibility",location:2}]},simpleLine3d:{buildVertex:k("simple_line_3d"),buildFragment:U("simple_line_3d"),uniforms:[oe,ce,{name:"u_vec2_vpt_size",type:"2fv"},{name:"u_vec4_color",type:"4fv"},{name:"u_float_mix_color",type:"1f"},{name:"u_float_width",type:"1f"},{name:"u_float_height_factor",type:"1f"},{name:"u_float_z_offset",type:"1f"},{name:"u_float_floor_elevation",type:"1f"},...ue,...De,...Ae,...he,...Le,...se,...jt,...ki],attributes:[{name:"a_vec2_vertex",location:0},{name:"a_float_z",location:1},{name:"a_vec4_direction_distance",location:2},{name:"a_vec2_dem_position",location:3},{name:"a_float_abs_z",location:4},{name:"a_float_is_pivot",location:5},{name:"a_float_visibility",location:6},{name:"a_vec4_color",location:7}]},road:{buildVertex:k("road"),buildFragment:U("road"),uniforms:[...Ge,ce,{name:"u_float_ecef_scale",type:"1f"},{name:"u_vec4_color",type:"4fv"},{name:"u_float_width",type:"1f"},{name:"u_float_tile_to_pixel_ratio",type:"1f"},{name:"u_float_shift",type:"1f"},{name:"u_float_floor_elevation",type:"1f"},...ue,...Ae,...he,...De,...Le],attributes:[{name:"a_vec3_vertex",location:0},{name:"a_vec4_normals",location:1},{name:"a_vec2_shift",location:2}]},roadIdentify:{buildVertex:k("road_identify"),buildFragment:U("road_identify"),uniforms:[...Ge,{name:"u_float_ecef_scale",type:"1f"},{name:"u_float_width",type:"1f"},{name:"u_float_tile_to_pixel_ratio",type:"1f"},{name:"u_float_floor_elevation",type:"1f"}],attributes:[{name:"a_vec3_vertex",location:0},{name:"a_vec4_normals",location:1},{name:"a_vec4_identifier",location:2}]},line3D:{buildVertex:k("line3d"),buildFragment:U("road"),uniforms:[oe,ce,{name:"u_vec2_vpt_size",type:"2fv"},{name:"u_vec4_color",type:"4fv"},{name:"u_float_width",type:"1f"},{name:"u_float_tile_to_pixel_ratio",type:"1f"},...se,...ue,...Ae,...he,...De,...Le,...jt],attributes:[{name:"a_vec2_vertex",location:0},{name:"a_vec4_normals",location:1},{name:"a_float_height",location:2},{name:"a_float_abs_z",location:3}]},line3DIdentify:{buildVertex:k("line3d_identify"),buildFragment:U("road_identify"),uniforms:[oe,{name:"u_float_width",type:"1f"},{name:"u_float_tile_to_pixel_ratio",type:"1f"},...se,...jt],attributes:[{name:"a_vec2_vertex",location:0},{name:"a_vec4_normals",location:1},{name:"a_float_height",location:2},{name:"a_float_abs_z",location:3},{name:"a_vec4_identifier",location:4}]},entrance:{buildVertex:k("arrow_line_entrance"),buildFragment:U("arrow_line"),uniforms:[oe,ce,{name:"u_vec2_vpt_size",type:"2f"},{name:"u_vec3_projection_scale_style_scale_dpi",type:"3fv"},{name:"u_vec2_scale_limits",type:"2fv"},{name:"u_vec4_color",type:"4f"},{name:"u_vec4_border_color",type:"4f"},{name:"u_vec2_wing_normal",type:"2f"},{name:"u_vec2_tip_normal",type:"2f"},{name:"u_float_width_zpt",type:"1f"},{name:"u_float_tip_radius_zpt",type:"1f"},{name:"u_float_wing_radius_zpt",type:"1f"},{name:"u_float_tail_radius_zpt",type:"1f"},{name:"u_float_tip_height_multiplier",type:"1f"},{name:"u_float_wing_width_multiplier",type:"1f"},{name:"u_float_wing_height_multiplier",type:"1f"},{name:"u_float_border_width_zpt",type:"1f"},{name:"u_float_size_factor",type:"1f"},{name:"u_float_border_width_offset",type:"1f"},{name:"u_float_total_line_length",type:"1f"},{name:"u_float_relative_end_position",type:"1f"},{name:"u_float_vertex_shift",type:"1f"},{name:"u_float_tip_movement_amplitude",type:"1f"},{name:"u_vec2_bounce_direction",type:"2f"},{name:"u_float_opacity",type:"1f"},...ue,...he],attributes:[{name:"a_vec2_vertex",location:0},{name:"a_vec2_segment_end",location:1},{name:"a_vec4_texture_widen_arrow_widen",location:2},{name:"a_vec2_widen",location:3},{name:"a_vec2_direction",location:4},{name:"a_float_distance_from_start",location:5},{name:"a_float_object_length",location:6},{name:"a_float_type",location:7},{name:"a_vec4_identifier",location:8}]},entranceIdentify:{buildVertex:k("arrow_line_entrance"),buildFragment:U("arrow_line_identify"),uniforms:[oe,ce,{name:"u_vec2_vpt_size",type:"2f"},{name:"u_vec3_projection_scale_style_scale_dpi",type:"3fv"},{name:"u_vec2_scale_limits",type:"2fv"},{name:"u_vec4_color",type:"4f"},{name:"u_vec4_border_color",type:"4f"},{name:"u_vec2_wing_normal",type:"2f"},{name:"u_vec2_tip_normal",type:"2f"},{name:"u_float_width_zpt",type:"1f"},{name:"u_float_tip_radius_zpt",type:"1f"},{name:"u_float_wing_radius_zpt",type:"1f"},{name:"u_float_tail_radius_zpt",type:"1f"},{name:"u_float_tip_height_multiplier",type:"1f"},{name:"u_float_wing_width_multiplier",type:"1f"},{name:"u_float_wing_height_multiplier",type:"1f"},{name:"u_float_border_width_zpt",type:"1f"},{name:"u_float_size_factor",type:"1f"},{name:"u_float_border_width_offset",type:"1f"},{name:"u_float_total_line_length",type:"1f"},{name:"u_float_relative_end_position",type:"1f"},{name:"u_float_vertex_shift",type:"1f"},{name:"u_float_tip_movement_amplitude",type:"1f"},{name:"u_vec2_bounce_direction",type:"2f"},{name:"u_float_opacity",type:"1f"}],attributes:[{name:"a_vec2_vertex",location:0},{name:"a_vec2_segment_end",location:1},{name:"a_vec4_texture_widen_arrow_widen",location:2},{name:"a_vec2_widen",location:3},{name:"a_vec2_direction",location:4},{name:"a_float_distance_from_start",location:5},{name:"a_float_object_length",location:6},{name:"a_float_type",location:7},{name:"a_vec4_identifier",location:8}]},circleMarker:{buildVertex:k("circle_marker"),buildFragment:U("circle_marker"),uniforms:[...Ge,ce,{name:"u_vec2_vpt_size",type:"2fv"},{name:"u_vec4_color",type:"4fv"},{name:"u_float_width",type:"1f"},...ue,...he,...Ae,...Le,...se],attributes:[{name:"a_vec3_vertex",location:0},{name:"a_vec2_widen",location:1}]},rectWithTexture:{buildVertex:k("rect_with_texture"),buildFragment:U("rect_with_texture"),uniforms:[oe,ce,{name:"u_sr2d_texture",type:"1i"},{name:"u_float_opacity",type:"1f"},...he,...ue],attributes:[{name:"a_vec2_vertex",location:0},{name:"a_vec2_texcoord",location:1}]},circleMarkerIdentify:{buildVertex:k("circle_marker_identify"),buildFragment:U("color_identify"),uniforms:[...Ge,{name:"u_vec2_vpt_size",type:"2fv"},{name:"u_float_width",type:"1f"},...se],attributes:[{name:"a_vec3_vertex",location:0},{name:"a_vec2_widen",location:1},{name:"a_vec4_identifier",location:2}]},heatmap:{buildVertex:k("heatmap"),buildFragment:U("heatmap"),uniforms:[oe,ce,...ue,{name:"u_float_radius",type:"1f"},{name:"u_float_intensity",type:"1f"},{name:"u_float_tile_to_pixel_ratio",type:"1f"},...he],attributes:[{name:"a_vec2_position",location:0},{name:"a_vec2_widen",location:1},{name:"a_float_weight",location:2}]},heatmapTexture:{buildVertex:k("heatmap_texture"),buildFragment:U("heatmap_texture"),uniforms:[ce,{name:"u_sr2d_texture",type:"1i"},{name:"u_sr2d_ramp_texture",type:"1i"},{name:"u_float_opacity",type:"1f"},...ue,...he],attributes:[{name:"a_vec2_position",location:0}]},demMesh:{buildVertex:k("dem_mesh"),buildFragment:U("dem_mesh"),uniforms:[oe,ce,{name:"u_mat4_flat_map_mvp",type:"mat4"},{name:"u_flat_tex",type:"1i"},{name:"u_hillshade_tex",type:"1i"},...ue,...se,...he,...De,...Ae,...Le],attributes:[{name:"a_vec2_position",location:0}]},demGround:{buildVertex:k("dem_ground"),buildFragment:U("dem_ground"),uniforms:[oe,ce,...se],attributes:[{name:"a_vec2_position",location:0}]},demMesh2:{buildVertex:k("dem_mesh2"),buildFragment:U("dem_mesh2"),uniforms:[oe,ce,{name:"u_mat4_flat_map_mvp",type:"mat4"},{name:"u_flat_tex",type:"1i"},{name:"u_hillshade_tex",type:"1i"},...ue,...se,...he,...De,...Ae,...Le,{name:"u_int_identify",type:"1i"},{name:"u_int_inline_contour_enabled",type:"1i"},{name:"u_float_contour_minor_interval",type:"1f"},{name:"u_float_contour_major_interval",type:"1f"},{name:"u_float_contour_index_interval",type:"1f"},{name:"u_vec4_contour_minor_color",type:"4fv"},{name:"u_vec4_contour_major_color",type:"4fv"},{name:"u_vec4_contour_index_color",type:"4fv"},{name:"u_float_contour_minor_width",type:"1f"},{name:"u_float_contour_major_width",type:"1f"},{name:"u_float_contour_index_width",type:"1f"}],attributes:[{name:"a_vec2_vertex",location:0},{name:"a_float_height",location:1}]},demMesh2DepthTest:{buildVertex:k("dem_mesh2_depthtest"),buildFragment:U("uniform_color"),uniforms:[oe,...se,{name:"u_vec4_color",type:"4fv"}],attributes:[{name:"a_vec2_vertex",location:0},{name:"a_float_height",location:1}]},demMesh2Shadow:{buildVertex:k("dem_mesh2_shadow"),buildFragment:U("main_shadow"),uniforms:[oe,...se],attributes:[{name:"a_vec2_vertex",location:0},{name:"a_float_height",location:1}]},demGround2:{buildVertex:k("dem_ground2"),buildFragment:U("dem_ground2"),uniforms:[oe,ce,...se],attributes:[{name:"a_vec2_vertex",location:0},{name:"a_float_height",location:1}]},demElevationCopy:{buildVertex:k("dem_elevation_copy"),buildFragment:U("dem_elevation_copy"),uniforms:[oe,{name:"u_sr2d_texture",type:"1i"},{name:"u_mat4_dem_corrected",type:"mat4"}],attributes:[{name:"a_vec2_vertex",location:0},{name:"a_vec2_texcoord",location:1}]},demElevation:{buildVertex:k("dem_elevation"),buildFragment:U("dem_elevation"),uniforms:[oe],attributes:[{name:"a_vec2_vertex",location:0},{name:"a_float_height",location:1}]},demHillshade:{buildVertex:k("dem_normal"),buildFragment:U("dem_normal"),uniforms:[...se,...Ae,...Le,oe,{name:"u_sr2d_texture",type:"1i"}],attributes:[{name:"a_vec2_vertex",location:0},{name:"a_vec2_texcoord",location:1}]},demFlatBottom:{buildVertex:k("dem_flat_bottom"),buildFragment:U("dem_flat_bottom"),uniforms:[oe,...se],attributes:[{name:"a_vec2_vertex",location:0},{name:"a_vec2_centroid",location:1},{name:"a_vec2_extender",location:2}]},mesh:{buildVertex:k("mesh"),buildFragment:U("mesh"),uniforms:[oe,ce,...ue,...se,...jt,...Ae,...Le,...he,...De,{name:"u_float_opacity",type:"1f"},{name:"u_vec4_color",type:"4fv"},{name:"u_float_mix_color",type:"1f"},{name:"u_float_height_factor",type:"1f"},{name:"u_sdtr_distance",type:"1f"},{name:"u_mat4_gradient",type:"mat4"},{name:"u_int_identify",type:"1i"},{name:"u_sr2d_texture",type:"1i"},{name:"u_float_texture_opacity",type:"1f"},{name:"u_float_texture_params",type:"4fv"},{name:"u_float_sprite_texture_coords",type:"4fv"},{name:"u_int_is_textured",type:"1i"},{name:"u_float_texture_vertical_scale",type:"1f"},{name:"u_float_floor_elevation",type:"1f"}],attributes:[{name:"a_vec2_vertex",location:0},{name:"a_float_z",location:1},{name:"a_vec3_normal",location:2},{name:"a_float_gradient",location:3},{name:"a_vec2_dem_position",location:4},{name:"a_float_abs_z",location:5},{name:"a_vec4_identifier",location:6},{name:"a_float_visibility",location:7},{name:"a_float_is_pivot",location:8},{name:"a_vec4_color",location:9}]},inverse:{buildVertex:k("mesh"),buildFragment:U("inverse"),uniforms:[oe,ce,...ue,...se,...jt,...Ae,...Le,...he,...De,{name:"u_float_opacity",type:"1f"},{name:"u_vec4_color",type:"4fv"},{name:"u_float_height_factor",type:"1f"},{name:"u_mat4_gradient",type:"mat4"},{name:"u_int_identify",type:"1i"},{name:"u_float_texture_params",type:"4fv"},{name:"u_int_is_textured",type:"1i"},{name:"u_float_texture_vertical_scale",type:"1f"},{name:"u_float_floor_elevation",type:"1f"}],attributes:[{name:"a_vec2_vertex",location:0},{name:"a_float_z",location:1},{name:"a_vec3_normal",location:2},{name:"a_float_gradient",location:3},{name:"a_vec2_dem_position",location:4},{name:"a_float_abs_z",location:5},{name:"a_vec4_identifier",location:6},{name:"a_float_visibility",location:7},{name:"a_float_is_pivot",location:8}]},meshDepthClear:{buildVertex:k("mesh"),buildFragment:U("depth_clear"),uniforms:[oe,ce,...ue,...se,...jt,...Ae,...Le,...he,...De,{name:"u_float_opacity",type:"1f"},{name:"u_vec4_color",type:"4fv"},{name:"u_float_height_factor",type:"1f"},{name:"u_sdtr_distance",type:"1f"},{name:"u_mat4_gradient",type:"mat4"},{name:"u_int_identify",type:"1i"},{name:"u_float_texture_params",type:"4fv"},{name:"u_int_is_textured",type:"1i"},{name:"u_float_texture_vertical_scale",type:"1f"},{name:"u_float_floor_elevation",type:"1f"}],attributes:[{name:"a_vec2_vertex",location:0},{name:"a_float_z",location:1},{name:"a_vec3_normal",location:2},{name:"a_float_gradient",location:3},{name:"a_vec2_dem_position",location:4},{name:"a_float_abs_z",location:5},{name:"a_vec4_identifier",location:6},{name:"a_float_visibility",location:7},{name:"a_float_is_pivot",location:8}]},mapMesh:{buildVertex:k("map_mesh"),buildFragment:U("map_mesh"),uniforms:[oe,ce,...ue,...se,...Ae,...Le,...jt,...he,...De,{name:"u_float_tile_size",type:"1f"},{name:"u_sampler_map_tex",type:"1i"},{name:"u_vec2_tex_scale",type:"2f"},{name:"u_float_tex_shift_scale",type:"1f"},{name:"u_float_height_factor",type:"1f"},{name:"u_sdtr_distance",type:"1f"},{name:"u_int_identify",type:"1i"},{name:"u_int_depth_test",type:"1i"}],attributes:[{name:"a_vec2_vertex",location:0},{name:"a_float_z",location:1},{name:"a_vec2_extender",location:2},{name:"a_vec3_normal",location:3},{name:"a_float_gradient",location:4},{name:"a_vec2_dem_position",location:5},{name:"a_float_abs_z",location:6},{name:"a_vec4_identifier",location:7},{name:"a_float_is_pivot",location:8}]},sky:{buildVertex:k("sky"),buildFragment:U("sky"),uniforms:[ce,...ue,...he],attributes:[{name:"a_vec2_vertex",location:0}]},taa:{buildVertex:k("posteffect"),buildFragment:U("taa"),uniforms:[{name:"u_texture",type:"1i"},{name:"u_float_mix_coef",type:"1f"}],attributes:[{name:"a_vec2_vertex",location:0}]},fxaa:{buildVertex:k("posteffect"),buildFragment:U("fxaa"),uniforms:[{name:"u_texture",type:"1i"},{name:"u_vec2_vpt_size",type:"2f"}],attributes:[{name:"a_vec2_vertex",location:0}]},smaa_edge:{buildVertex:k("posteffect"),buildFragment:U("smaa_edge"),uniforms:[{name:"u_texture",type:"1i"},{name:"u_vec2_vpt_size",type:"2f"}],attributes:[{name:"a_vec2_vertex",location:0}]},smaa_weight:{buildVertex:k("posteffect"),buildFragment:U("smaa_weight"),uniforms:[{name:"u_edgesTex",type:"1i"},{name:"u_areaTex",type:"1i"},{name:"u_searchTex",type:"1i"},{name:"u_vec2_vpt_size",type:"2f"}],attributes:[{name:"a_vec2_vertex",location:0}]},smaa_blend:{buildVertex:k("posteffect"),buildFragment:U("smaa_blend"),uniforms:[{name:"u_texture",type:"1i"},{name:"u_weightsTex",type:"1i"},{name:"u_vec2_vpt_size",type:"2f"}],attributes:[{name:"a_vec2_vertex",location:0}]},copy:{buildVertex:k("posteffect"),buildFragment:U("copy"),uniforms:[{name:"u_texture",type:"1i"},{name:"u_depth",type:"1i"}],attributes:[{name:"a_vec2_vertex",location:0}]},buildingShadow:{buildVertex:k("building_shadow"),buildFragment:U("main_shadow"),uniforms:[...se,oe,{name:"u_float_height_factor",type:"1f"},{name:"u_float_floor_elevation",type:"1f"}],attributes:[{name:"a_vec2_vertex",location:0},{name:"a_float_z",location:1},{name:"a_vec2_dem_position",location:2},{name:"a_float_visibility",location:3}]},meshShadow:{buildVertex:k("mesh_shadow"),buildFragment:U("main_shadow"),uniforms:[oe,{name:"u_float_height_factor",type:"1f"},...se,...jt,{name:"u_float_floor_elevation",type:"1f"}],attributes:[{name:"a_vec2_vertex",location:0},{name:"a_float_z",location:1},{name:"a_vec2_dem_position",location:2},{name:"a_float_abs_z",location:3},{name:"a_float_visibility",location:4},{name:"a_float_is_pivot",location:5}]},globeHalo:{buildVertex:k("globe_halo"),buildFragment:U("globe_halo"),uniforms:[{name:"u_vec2_halo_viewport_size",type:"2f"},{name:"u_vec2_halo_viewport_center_shift",type:"2f"},{name:"u_vec4_halo_radius_stops",type:"4f"},{name:"u_vec4_halo_color",type:"4f"},{name:"u_float_halo_exp_factor",type:"1f"},{name:"u_vec4_default_background_color",type:"4f"}],attributes:[{name:"a_vec2_vertex",location:0}]},stars:{buildVertex:k("stars"),buildFragment:U("stars"),uniforms:[{name:"u_mat4_stars",type:"mat4"},{name:"u_float_pixelratio",type:"1f"},{name:"u_float_stars_intensity",type:"1f"}],attributes:[{name:"a_vec3_position",location:0},{name:"a_fade_opacity",location:1}]},globeHaloBackground:{buildVertex:k("globe_halo"),buildFragment:U("globe_halo_background"),uniforms:[{name:"u_vec2_halo_viewport_size",type:"2f"},{name:"u_vec2_halo_viewport_center_shift",type:"2f"},{name:"u_vec4_halo_radius_stops",type:"4f"},{name:"u_vec4_halo_color",type:"4f"},{name:"u_float_halo_exp_factor",type:"1f"},{name:"u_vec4_default_background_color",type:"4f"}],attributes:[{name:"a_vec2_vertex",location:0}]},particleBillboard:{buildVertex:k("particle_billboard"),buildFragment:U("particle"),uniforms:[{name:"u_mvp",type:"mat4"},{name:"u_viewport",type:"2fv"},{name:"u_useTexture",type:"1f"},{name:"u_texture",type:"1i"},{name:"u_softness",type:"1f"},{name:"u_atlasGrid",type:"2fv"}],attributes:[{name:"a_quadVertex"},{name:"a_position"},{name:"a_frame"},{name:"a_params"},{name:"a_color"}]},particleStretch:{buildVertex:k("particle_stretch"),buildFragment:U("particle"),uniforms:[{name:"u_mvp",type:"mat4"},{name:"u_viewport",type:"2fv"},{name:"u_useTexture",type:"1f"},{name:"u_texture",type:"1i"},{name:"u_softness",type:"1f"},{name:"u_atlasGrid",type:"2fv"}],attributes:[{name:"a_quadVertex"},{name:"a_position"},{name:"a_velocity"},{name:"a_frame"},{name:"a_params"},{name:"a_color"}]}}}function fT(s,e){if(window.requestIdleCallback)for(const t in e){const i=t;window.requestIdleCallback(()=>{if(s.isContextLost())return;const r=s.getShaderProgram(i);r.link(),setTimeout(()=>{window.requestIdleCallback(()=>{s.isContextLost()||r.locate()})},2e3)})}}class th{constructor(e){this.params=e,this._uniformsMap={},this._buffer=null,this._data=null,this._gl=e.gl}bind(e){const t=this._gl,i=e.getUboBinding(this.params.blockName);i!==void 0&&(this._buffer||this.prepare(e),this._lastBinding=i,t.bindBufferBase(t.UNIFORM_BUFFER,i,this._buffer))}rebind(){this._lastBinding===void 0||!this._buffer||this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,this._lastBinding,this._buffer)}updateData(e,t){this._buffer||this.prepare(e);const i=this._data;for(const r in t)if(r in this._uniformsMap){const o=t[r],a=this._uniformsMap[r]/4,l=e.uniforms[r];if(l!=null&&l.isNonFloatType()&&n.log(`[UBO Warn]: Currenty only float uniform types are supported. Uniform "${r}" has unsupported type`),n.isTypedArray(o)||n.isArrayOfNumbers(o))for(let c=0;c<o.length;++c)i[a+c]=o[c];else i[a]=o}}commitData(){if(!this._data)return;const e=this._gl;e.bindBuffer(e.UNIFORM_BUFFER,this._buffer),e.bufferData(e.UNIFORM_BUFFER,this._data,e.DYNAMIC_DRAW),e.bindBuffer(e.UNIFORM_BUFFER,null)}cleanup(){this._buffer&&this._gl.deleteBuffer(this._buffer)}prepare(e){const t=this._gl;this._buffer=t.createBuffer();const i=e.getUniformBlocksMap();if(!i){console.error("Failed to initialize UBO. Uniform blocks are not supported.");return}const r=e.getUniformBlockSize(this.params.blockName);if(r===null){console.error("Failed to initialize UBO. Invalid UBO block is provided.");return}this._data=new Float32Array(new ArrayBuffer(r));const o=i[this.params.blockName];o||console.error(`UBO block "${this.params.blockName}" not found in shader program.`);const a=e.getUniformsIndicesOffsetsInBlock(o);if(!a){console.error("Failed to initialize UBO. Couldn't retrieve uniforms information.");return}this._uniformsMap=a}}class mT extends Pe{constructor(e={},t=4){super(V(I({},e),{hasColorOutput:!1})),this.msaaFramebuffer=null,this.resolveFramebuffer=null,this.msaaColorRenderbuffer=null,this.msaaDepthRenderbuffer=null,this.resolveTexture=null,this.resolveDepthTexture=null,this.gl2=null,this.needsResolve=!1,this.samples=t}bind(e,t){if(!(e instanceof WebGL2RenderingContext))return super.bind(e,t);this.msaaFramebuffer||this._prepareMSAA(e);const i=t!=null?t:e.FRAMEBUFFER;return e.bindFramebuffer(i,this.msaaFramebuffer),this.needsResolve=!0,this}unbind(e){return!(e instanceof WebGL2RenderingContext)||!this.msaaFramebuffer?super.unbind(e):(this.resolve(e),e.bindFramebuffer(e.FRAMEBUFFER,null),this)}resolve(e){if(!this.needsResolve||!this.msaaFramebuffer||!this.resolveFramebuffer)return;const[t,i]=this.options.size;e.bindFramebuffer(e.READ_FRAMEBUFFER,this.msaaFramebuffer),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,this.resolveFramebuffer),e.blitFramebuffer(0,0,t,i,0,0,t,i,e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT,e.NEAREST),e.bindFramebuffer(e.READ_FRAMEBUFFER,null),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),this.needsResolve=!1}getTexture(){return this.resolveTexture}getDepthAttachment(){return this.resolveDepthTexture}setSize(e){return this.options.size=e,this._unprepareMSAA(),this}remove(){return this._unprepareMSAA(),this}memSizeGPU(){const[e,t]=this.options.size,i=e*t*4*this.samples,r=e*t*4*this.samples,o=e*t*4,a=e*t*4;return{_texture:{_texture:o},_depthAttachment:a+i+r}}_prepareMSAA(e){var a,l,c,d;this.gl2=e;const[t,i]=this.options.size,r=e.getParameter(e.MAX_SAMPLES),o=Math.min(this.samples,r);this.msaaFramebuffer=e.createFramebuffer(),e.bindFramebuffer(e.FRAMEBUFFER,this.msaaFramebuffer),this.msaaColorRenderbuffer=e.createRenderbuffer(),e.bindRenderbuffer(e.RENDERBUFFER,this.msaaColorRenderbuffer),e.renderbufferStorageMultisample(e.RENDERBUFFER,o,e.RGBA8,t,i),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.RENDERBUFFER,this.msaaColorRenderbuffer),this.msaaDepthRenderbuffer=e.createRenderbuffer(),e.bindRenderbuffer(e.RENDERBUFFER,this.msaaDepthRenderbuffer),e.renderbufferStorageMultisample(e.RENDERBUFFER,o,e.DEPTH_COMPONENT24,t,i),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.RENDERBUFFER,this.msaaDepthRenderbuffer),this._checkCompleteMSAA(e,"MSAA"),this.resolveFramebuffer=e.createFramebuffer(),e.bindFramebuffer(e.FRAMEBUFFER,this.resolveFramebuffer),this.resolveTexture=new C(null,{magFilter:(a=this.options.magFilter)!=null?a:C.NearestFilter,minFilter:(l=this.options.minFilter)!=null?l:C.NearestFilter,wrapS:(c=this.options.wrapS)!=null?c:C.ClampToEdgeWrapping,wrapT:(d=this.options.wrapT)!=null?d:C.ClampToEdgeWrapping,format:C.RgbaFormat,size:[t,i],premultiplyAlpha:!1,generateMipmaps:!1,flipY:!1}),this.resolveTexture.prepare(e),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.resolveTexture.getTexture(),0),this.options.depthTexture&&(this.resolveDepthTexture=new C(null,{magFilter:C.NearestFilter,minFilter:C.NearestFilter,format:C.DepthComponentFormat,size:[t,i],premultiplyAlpha:!1,generateMipmaps:!1,type:C.UnsignedInt,flipY:!1}),this.resolveDepthTexture.prepare(e),e.framebufferTexture2D(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.TEXTURE_2D,this.resolveDepthTexture.getTexture(),0)),this._checkCompleteMSAA(e,"Resolve"),e.bindRenderbuffer(e.RENDERBUFFER,null),e.bindFramebuffer(e.FRAMEBUFFER,null)}_unprepareMSAA(){const e=this.gl2;e&&(this.msaaColorRenderbuffer&&(e.deleteRenderbuffer(this.msaaColorRenderbuffer),this.msaaColorRenderbuffer=null),this.msaaDepthRenderbuffer&&(e.deleteRenderbuffer(this.msaaDepthRenderbuffer),this.msaaDepthRenderbuffer=null),this.resolveTexture&&(this.resolveTexture.remove(),this.resolveTexture=null),this.resolveDepthTexture&&(this.resolveDepthTexture.remove(),this.resolveDepthTexture=null),this.msaaFramebuffer&&(e.deleteFramebuffer(this.msaaFramebuffer),this.msaaFramebuffer=null),this.resolveFramebuffer&&(e.deleteFramebuffer(this.resolveFramebuffer),this.resolveFramebuffer=null))}_checkCompleteMSAA(e,t){if(n.forceGlStatusCheck()){const i=e.checkFramebufferStatus(e.FRAMEBUFFER);i!==e.FRAMEBUFFER_COMPLETE&&console.warn(`${t} framebuffer incomplete: ${i}`)}}}var Ga=(s=>(s[s.CACHED=0]="CACHED",s[s.RENDER_UNDER_CACHE=1]="RENDER_UNDER_CACHE",s[s.RENDER_OVER_CACHE=2]="RENDER_OVER_CACHE",s))(Ga||{});const Nn=1/0,hs=-1/0,_s="renderCacheManager",vT=[0,0,0,0];class gT{constructor(e,t){this.prevFrameAnimationLayerOverCacheIndex=void 0,this.prevFrameAnimationLayerUnderCacheIndex=void 0,this.cacheObjectsCount=0,this.cacheBuiltWithPendingShaderPrograms=!1,this.animationLayersOverCacheMinIndex=Nn,this.animationLayersUnderCacheMaxIndex=hs,this.state=e,this.modules=t,this.cacheFramebufferId=void 0,this.isReadyCache=!1,this.isLowZoom=this.state.zoom<6,this.cacheDisabled=this.state.disableRenderingCache,this.animationLayersUniqueIds=new Set,this.debugMode=!1,this.debugSkipRenderToCanvas=!1,this.cachedLayersMap=new Map}isLayerAnimated(e,t){const i=this.getUniqueRenderIndex(e,t);return!!this.animationLayersUniqueIds.has(i)}isLayerInCache(e,t){if(!this.isReadyCache)return!1;const i=this.cachedLayersMap.get(e);return!!i&&i.has(t)}frameEnd(){}initInDebugMode(){this.debugMode=!0}setDebugSkipRenderToCanvas(e){this.debugSkipRenderToCanvas=e,this.modules.renderer.addRerenderEvent()}isDisabled(){return this.cacheDisabled}setDisabled(e){this.cacheDisabled!==e&&(this.cacheDisabled=e,this.state.disableRenderingCache=e,this.isReadyCache=!1,this.cacheObjectsCount=0,this.cachedLayersMap=new Map,this.animationLayersUniqueIds.clear(),this.prevFrameAnimationLayerOverCacheIndex=void 0,this.prevFrameAnimationLayerUnderCacheIndex=void 0,this.modules.renderer.addRerenderEvent())}frameStart(){this.cachedLayersMap=new Map,this.cacheObjectsCount=0,this.isLowZoom=this.state.zoom<6,this.isReadyCache=!1;let e=!1;this.cacheDisabled||(this.animationLayersUniqueIds.clear(),this.cacheFramebufferId===void 0&&(this.cacheFramebufferId=this.createCacheFramebuffer()),this.animationLayersOverCacheMinIndex=Nn,this.animationLayersUnderCacheMaxIndex=hs,this.state.rerenderEvents.forEach(t=>{if(t.type==="layerAnimationTicker"){const i=this.getUniqueRenderIndex(t.styleId,t.layerId,t.underCache);this.animationLayersUniqueIds.add(i),t.underCache?this.animationLayersUnderCacheMaxIndex=Math.max(this.animationLayersUnderCacheMaxIndex,i):this.animationLayersOverCacheMinIndex=Math.min(this.animationLayersOverCacheMinIndex,i)}else e=!0}),this.isReadyCache=!0,(this.animationLayersOverCacheMinIndex!==this.prevFrameAnimationLayerOverCacheIndex||this.animationLayersUnderCacheMaxIndex!==this.prevFrameAnimationLayerUnderCacheIndex)&&(this.isReadyCache=!1),(this.state.needRerender||e)&&(this.prevFrameAnimationLayerOverCacheIndex=void 0,this.prevFrameAnimationLayerUnderCacheIndex=void 0,this.isReadyCache=!1),this.cacheBuiltWithPendingShaderPrograms&&(this.isReadyCache=!1))}tryToCacheObjects(e,t,i,r){if(this.modules.renderer.hasAnimatedFlatObjectInDemMode||this.cacheDisabled||this.modules.renderer.hasPendingShaderPrograms()||this.cacheFramebufferId===void 0||this.animationLayersOverCacheMinIndex===Nn&&this.animationLayersUnderCacheMaxIndex===hs||this.isLowZoom||this.animationLayersUnderCacheMaxIndex>=this.animationLayersOverCacheMinIndex||r&&this.modules.renderer.hasAnimatedFlatObjectInDemMode&&t.layerSettings.forceRenderUnderCacheInDemMode)return 1;const o=this.getUniqueRenderIndex(t.attributes.styleId,t.attributes.layerId);return o>=this.animationLayersOverCacheMinIndex?2:o<=this.animationLayersUnderCacheMaxIndex||(e[this.cacheFramebufferId]||(e[this.cacheFramebufferId]={framebuffer:this.modules.renderer.getFramebuffer(this.cacheFramebufferId),objects:[],tileObjects:new Set}),this.isReadyCache||(e[this.cacheFramebufferId].objects.push(t),e[this.cacheFramebufferId].tileObjects.add(i)),this.cacheObjectsCount++,this.markLayerInCache(t.attributes.styleId,t.attributes.layerId),r&&this.modules.renderer.hasAnimatedFlatObjectInDemMode&&t.layerSettings.forcePrerenderUnderCacheInDemMode)?1:0}hasReadyCache(){return this.isReadyCache&&!this.cacheDisabled}markCachePassResult(e){this.cacheBuiltWithPendingShaderPrograms=e}hasCachedObjects(){return!!this.cacheObjectsCount}render(){var t,i;if(this.cacheDisabled)return!1;if(this.cacheFramebufferId===void 0||this.cacheObjectsCount===0||this.isLowZoom)return;this.prevFrameAnimationLayerOverCacheIndex=this.animationLayersOverCacheMinIndex,this.prevFrameAnimationLayerUnderCacheIndex=this.animationLayersUnderCacheMaxIndex;const e=(t=this.modules.renderer.getFramebuffer(this.cacheFramebufferId))==null?void 0:t.renderTarget;if(e&&!this.debugSkipRenderToCanvas){this.modules.renderer.storeGpuState(_s),this.debugMode?this.modules.renderer.applyGpuState(Iv,void 0,void 0,!1):this.modules.renderer.applyGpuState(Cv,void 0,void 0,!1);const r=(i=this.modules.postEffectsManager.mainFrameBufferWrapper)==null?void 0:i.renderTarget;this.modules.postEffectsManager.hasActiveEffects()&&r?this.modules.postEffectsManager.copyRenderTargetTo(e,r,!0,!1):this.modules.postEffectsManager.copyRenderTargetToCanvas(e,!0,!1),this.modules.renderer.restoreGpuState(_s)}}destroy(){this.cacheFramebufferId=void 0}markLayerInCache(e,t){let i=this.cachedLayersMap.get(e);i||(i=new Set,this.cachedLayersMap.set(e,i)),i.add(t)}getUniqueRenderIndex(e,t,i){const r=this.modules.styleManager.getStyleLayer(e,t);if(!r)return i?hs:Nn;const o=this.modules.styleManager.getMaxLayersCount();return-e*o+r.renderIndex}createCacheFramebuffer(){if(!this.modules.renderer.fragDepthSupported()){console.warn("Render cache disabled - Fragment Depth write not supported"),this.cacheDisabled=!0;return}const e=this.modules.renderer.getViewportSize(),t=this.modules.renderer.webglContextState.MAX_TEXTURE_SIZE;if(Math.max(...e)>t){n.log(`Render cache disabled as viewport size ${e[0]}x${e[1]} exceeds hardware limits of ${t}x${t}`),this.cacheDisabled=!0;return}const r=C.NearestFilter,o=this.modules.renderer.getViewportSize(),l=this.state.aaMode===Et.MSAA&&this.modules.renderer.isWebgl2Context()?new mT({size:[o[0],o[1]],magFilter:r,minFilter:r,wrapS:C.ClampToEdgeWrapping,wrapT:C.ClampToEdgeWrapping,depthTexture:!0,format:C.RgbaFormat},4):new Pe({size:[o[0],o[1]],magFilter:r,minFilter:r,wrapS:C.ClampToEdgeWrapping,wrapT:C.ClampToEdgeWrapping,depthTexture:!0,format:C.RgbaFormat});return this.modules.renderer.addFramebuffer({onResize:()=>{const c=this.modules.renderer.getViewportSize();l.setSize([c[0],c[1]])},renderTarget:l,onRenderStart:()=>{if(this.isReadyCache||this.cacheFramebufferId===void 0)return;const c=this.modules.renderer.getFramebuffer(this.cacheFramebufferId);c&&(this.modules.renderer.bindRenderTarget(c.renderTarget),this.modules.renderer.storeGpuState(_s),this.modules.renderer.applyGpuState(Pv,void 0,void 0,!1),this.modules.renderer.clearWithColor(vT,!0),this.modules.renderer.bindRenderTarget(null),this.modules.renderer.restoreGpuState(_s))},onRenderEnd:()=>{},isCacheFramebuffer:!0,useDem:!0,renderIndex:Nn})}}const Va=1.3,fs=2,Za=n.reserveTextureIndex(),Wa=n.reserveTextureIndex(),ih=n.reserveTextureIndex(),nh=14,rh=0,Ui=[1,1,1,1],sh=new Float64Array(16);let kn=(ri=class extends fm{constructor(e,t){const i=t.layout.canvas,r=e.webglVersion,o={antialias:e.aaMode===Et.MSAA,stencil:r!==2,failIfMajorPerformanceCaveat:!1,preserveDrawingBuffer:e.preserveDrawingBuffer};let a=null;if((!r||r===2)&&(a=i.getContext("webgl2",o),ri.webglVersion=2),(a===null||r===1)&&(a=i.getContext("webgl",o)||i.getContext("experimental-webgl",o),ri.webglVersion=1),a===null||!(a instanceof WebGLRenderingContext||a instanceof WebGL2RenderingContext))throw new Error("Failed to obtain WebGL context");super({gl:a,clearColor:n.getColorForShaders(e.defaultBackgroundColor)}),this.commonShaderDefines=n.EMPTY_SHADER_DEFINITIONS,this.hasAnimatedFlatObjectInDemMode=!1,this.destroyed=!1,this.parallelShaderCompile=null,this.pendingShaderPrograms=new Set,this.hasPendingShaderProgram=!1,this.shaderProgramPendingVersion=0,this.framebuffers=[],this.lastRenderedFramebuffers=[],this.mapMeshMvpMatrix=new Float64Array(16),this.drawTargetsFramebufferIds=new Map,this.ubosMap={},this.lastAppliedGpuState={state:null},this.applyGpuState=(c,d,u,h=!0)=>{const _=c(this.modules,u),f=this.lastAppliedGpuState,m=d==null?void 0:d.gpuState;f.state===_&&f.layerState===(d==null?void 0:d.gpuState)||(this.applyState(_,m),h&&(f.state=_,f.layerState=d==null?void 0:d.gpuState))},this.trackContextLost=c=>{this.destroyed||(c.preventDefault(),this.modules.map.emit("error",{type:"webglcontextlost"}),this.modules.map.destroy())},this.debugRenderOnlyCache=!1,this.state=e,this.modules=t;const l=a.getExtension("WEBGL_debug_renderer_info");this.webglContextState={MAX_TEXTURE_SIZE:a.getParameter(a.MAX_TEXTURE_SIZE),MAX_VIEWPORT_DIMS:a.getParameter(a.MAX_VIEWPORT_DIMS),MAX_UNIFORM_BUFFER_BINDINGS:a instanceof WebGLRenderingContext?0:a.getParameter(a.MAX_UNIFORM_BUFFER_BINDINGS),MAX_COMBINED_UNIFORM_BLOCKS:a instanceof WebGLRenderingContext?0:a.getParameter(a.MAX_COMBINED_UNIFORM_BLOCKS),RENDERER:l?a.getParameter(l.UNMASKED_RENDERER_WEBGL):a.getParameter(a.RENDERER),VENDOR:l?a.getParameter(l.UNMASKED_VENDOR_WEBGL):a.getParameter(a.VENDOR)},this.identifyBuffer=new Pe({minFilter:C.NearestFilter,magFilter:C.NearestFilter,useHighDepthPrecision:!0}),this.labelingTextureBuffer=new Pe({size:this.getViewportSize(),magFilter:C.NearestFilter,minFilter:C.NearestFilter,depthTexture:!0}),this.spriteLabelingTextureBuffer=new Pe({size:this.getViewportSize(),magFilter:C.NearestFilter,minFilter:C.NearestFilter,depthTexture:!1}),this.shaderProgramOptions=_T(),this.shaderPrograms={},this.symbolSettingsList=hb(),this.addExtension("OES_vertex_array_object").addExtension("OES_element_index_uint").addExtension("OES_standard_derivatives").addExtension("OES_texture_float").addExtension("OES_texture_float_linear").addExtension("ANGLE_instanced_arrays").addExtension("WEBGL_depth_texture").addExtension("EXT_frag_depth").addExtension("EXT_blend_minmax"),this.parallelShaderCompile=this._gl.getExtension("KHR_parallel_shader_compile"),this.parallelShaderCompile||t.map.once("idle",()=>fT(this,this.shaderProgramOptions)),ri.webglVersion===2&&this.addExtension("EXT_color_buffer_float"),this.setPixelRatio(window.devicePixelRatio).setSize(t.layout.mapContainer.clientWidth,t.layout.mapContainer.clientHeight),e.collectStats&&(this.timers=new _b(this._gl)),t.layout.canvas.addEventListener("webglcontextlost",this.trackContextLost)}get isDestroyed(){return this.destroyed}setDebugRenderOnlyCache(e){this.debugRenderOnlyCache=e,this.modules.renderer.addRerenderEvent()}getViewportSize(e=1){const t=this.getPixelRatio();return this.state.size.map(i=>Math.floor(i*t/e))}setClearColor(e){const t=n.getColorForShaders(e);if(!n.deepEqual(t,this.clearColor))return this.clearColor=t,this.addRerenderEvent(),this}setSize(e,t){return this.modules.layout.setCanvasSize(e,t),this.updateFrameBuffersSize(),this}updateFrameBuffersSize(){var i;this.framebuffers.forEach(r=>{r&&r.onResize()});const e=this.getPixelRatio(),t=this.state.size.map(r=>Math.ceil(r*e));(i=this.modules.postEffectsManager)==null||i.invalidateSize(),this.identifyBuffer.setSize(t.map(r=>Math.ceil(r*n.identify.pixelDensity))),this.labelingTextureBuffer.setSize(t),this.spriteLabelingTextureBuffer.setSize(t)}clear(e=!0){return this.clearWithColor(this.clearColor,e),this}addRerenderEvent(e){this.state.rerenderEvents.push(e||{type:"coreNeedRerender"})}isNeedRerender(e=!1){return this.hasPendingShaderProgram||this.state.needRerender||(e?this.state.rerenderEvents.filter(t=>t.type!=="layerAnimationTicker"):this.state.rerenderEvents).length>0}clearWithColor(e,t=!0,i=1){const r=this._gl,o=t===!0?r.COLOR_BUFFER_BIT|r.DEPTH_BUFFER_BIT:r.COLOR_BUFFER_BIT,a=t?Oc:Ev;this.applyGpuState(a),r.clearDepth(i),r.clearColor(e[0],e[1],e[2],e[3]),r.clear(o)}renderTileObjects(e){this.resetStateAfterExternalRender(),this.drawTargetsFramebufferIds.forEach(a=>{const l=this.getFramebuffer(a);l&&(l.requestedInCurrentFrame=!1)}),this.state.collectStats&&this.timers&&this.timers.addTimer();let t=!1,i=!1,r=!1;const o=this.getRenderObjectsByGroups(e,!1);if(this.lastRenderedFramebuffers.forEach(a=>{o.groups.some(l=>l.framebuffer===a)||this.clearFramebuffer(a)}),this.lastRenderedFramebuffers=[],o.groups.forEach(a=>{var g,p,x,S;const{objects:l,tileObjects:c,isUnderCache:d}=a;let{framebuffer:u}=a;const h=this.modules.map.state.demMode&&(u===void 0||u.useDem===!0),_=!u,f=(u==null?void 0:u.isCacheFramebuffer)&&!this.modules.renderCacheManager.hasReadyCache(),m=!u&&this.modules.postEffectsManager.hasActiveEffects();m&&(u=this.modules.postEffectsManager.mainFrameBufferWrapper);const v=ei(this.state,this.modules,o.tiers,u==null?void 0:u.renderTarget,h);if(u)(g=u.onRenderStart)==null||g.call(u),this.lastRenderedFramebuffers.push(u),u.renderTarget.bind(this._gl),this._gl.viewport(0,0,u.renderTarget.options.size[0],u.renderTarget.options.size[1]),u.clearColor&&(!m||m&&d)&&this.clearWithColor(u.clearColor,!!u.clearDepth);else{const{size:b,viewport:T}=this.state,y=window.devicePixelRatio;this._gl.bindFramebuffer(this._gl.FRAMEBUFFER,null),this._gl.viewport(T.left*y,T.bottom*y,b[0]*y,b[1]*y),_&&d&&this.clear(!0)}if(_||f){_&&d&&this.modules.environmentManager.renderSky();const b=h&&_&&(!this.modules.renderCacheManager.hasCachedObjects()||this.hasAnimatedFlatObjectInDemMode)&&!t,T=h&&f&&this.modules.renderCacheManager.hasCachedObjects()&&!this.hasAnimatedFlatObjectInDemMode&&!i;if(o.flatObjectsGroup&&(b||T)){T&&(i=!0),b&&(t=!0);const y=this.shaderProgramPendingVersion;this.renderDemMesh(v,o.flatObjectsGroup,!1,u),f&&this.hasShaderProgramPendingSince(y)&&(r=!0)}}if(l.length){const b=(x=(p=u==null?void 0:u.getViewProjectionMatrix)==null?void 0:p.call(u))!=null?x:this.modules.camera.viewProjectionMatrix,T=h?this.modules.demManager.demTextureMatrix:void 0;c.forEach(E=>{E.updateMvpMatrix(b,T)});const y=this.shaderProgramPendingVersion;ai(this.state,this.modules,l,v),f&&this.hasShaderProgramPendingSince(y)&&(r=!0)}_&&d&&!r&&this.modules.renderCacheManager.render(),f&&this.modules.renderCacheManager.markCachePassResult(r),u==null||u.renderTarget.unbind(this._gl),(S=u==null?void 0:u.onRenderEnd)==null||S.call(u),m&&!d&&this.modules.postEffectsManager.render(),this.debugRenderOnlyCache&&_&&!d&&!r&&(this.clearWithColor([1,0,1,1],!0),this.modules.renderCacheManager.render())}),this.state.collectStats&&this.timers){this.timers.stopTimer();const a=this.timers.tryToGetFirstTimerValue();a&&this.modules.map.emit("gpuRenderTime",a.durationMs*1e6)}for(const[a,l]of this.drawTargetsFramebufferIds){const c=this.getFramebuffer(l);(!c||!c.requestedInCurrentFrame)&&(this.drawTargetsFramebufferIds.delete(a),this.removeFramebuffer(l))}return this}renderElevation(e){var l,c,d,u;if(!this.state.demMode)return;this.resetStateAfterExternalRender();const t=[];if(e.forEach(h=>h.demChildren.forEach(_=>t.push(_))),!t.length)return;const i=this.modules.demManager.getDemFramebufferId();if(i===n.INVALID_FRAMEBUFFER_ID)return;const r=this.getFramebuffer(i);if(!r)return;const o=ei(this.state,this.modules,void 0,r.renderTarget);(l=r.onRenderStart)==null||l.call(r),r.renderTarget.bind(this._gl),this._gl.viewport(0,0,r.renderTarget.options.size[0],r.renderTarget.options.size[1]),r.clearColor&&this.clearWithColor(r.clearColor,!!r.clearDepth);const a=(d=(c=r.getViewProjectionMatrix)==null?void 0:c.call(r))!=null?d:this.modules.camera.viewProjectionMatrix;e.forEach(h=>{h.updateMvpMatrix(a)}),ai(this.state,this.modules,t,o),r.renderTarget.unbind(this._gl),(u=r.onRenderEnd)==null||u.call(r)}renderGround(e){var l,c,d,u;if(!this.state.demMode)return;const t=[];if(e.forEach(h=>h.demGroundChildren.forEach(_=>t.push(_))),!t.length)return;const i=this.modules.demManager.getGroundFramebufferId();if(i===n.INVALID_FRAMEBUFFER_ID)return;const r=this.getFramebuffer(i);if(!r)return;const o=ei(this.state,this.modules,void 0,r.renderTarget,!0,!0);(l=r.onRenderStart)==null||l.call(r),r.renderTarget.bind(this._gl),this._gl.viewport(0,0,r.renderTarget.options.size[0],r.renderTarget.options.size[1]),r.clearColor&&this.clearWithColor(r.clearColor,!!r.clearDepth);const a=(d=(c=r.getViewProjectionMatrix)==null?void 0:c.call(r))!=null?d:this.modules.camera.viewProjectionMatrix;e.forEach(h=>{h.updateMvpMatrix(a,this.modules.demManager.demTextureMatrix)}),ai(this.state,this.modules,t,o),r.renderTarget.unbind(this._gl),(u=r.onRenderEnd)==null||u.call(r)}renderSpriteLabelingTexture(e){if(this.modules.renderCacheManager.hasReadyCache())return;this.resetStateAfterExternalRender();const t=this._gl,i=[],r=ei(this.state,this.modules,void 0,this.spriteLabelingTextureBuffer,this.modules.map.state.demMode),o=e.filter(a=>a.labelTestChildren[0]);o.forEach(a=>{a.updateMvpMatrix(this.modules.camera.viewProjectionMatrix,this.modules.demManager.demTextureMatrix)}),o.forEach(a=>{a.labelTestChildren.forEach(l=>{l.attributes.labelTest===!0&&i.push(l)})}),this.spriteLabelingTextureBuffer.bind(t),this.clearWithColor([1,1,1,1]),t.viewport(0,0,this.spriteLabelingTextureBuffer.options.size[0],this.spriteLabelingTextureBuffer.options.size[1]),ai(this.state,this.modules,i,r),this.spriteLabelingTextureBuffer.unbind(t)}renderLabelingTexture(e){var a;if(this.modules.renderCacheManager.hasReadyCache()||(this.resetStateAfterExternalRender(),this.state.isLabelingDepthTestDisabled=!0,this.state.styleZoom<nh||this.state.pitch===rh&&!((a=this.modules.floorManager)!=null&&a.hasActiveFloorOrMetro())&&this.state.styleState.immersiveRoadsOn!==!0||this.state.disableHidingPois))return;const t=this._gl,i=[],r=ei(this.state,this.modules,void 0,this.labelingTextureBuffer,this.modules.map.state.demMode),o=e.filter(l=>l.depthTestChildren[0]);o.forEach(l=>{l.updateMvpMatrix(this.modules.camera.viewProjectionMatrix,this.modules.demManager.demTextureMatrix)}),o.forEach(l=>{l.depthTestChildren.forEach(c=>{const d=this.modules.styleManager.getStyleLayer(c.attributes.styleId,c.attributes.layerId);(d&&d.type!=="gltfModel"||!(d!=null&&d.style.preventObjectsHiding))&&i.push(c)})}),this.state.isLabelingDepthTestDisabled=!1,this.labelingTextureBuffer.bind(t),this.clearWithColor(n.LABELING_TEXTURE_BACKGROUND_COLOR),t.viewport(0,0,this.labelingTextureBuffer.options.size[0],this.labelingTextureBuffer.options.size[1]),ai(this.state,this.modules,i,r),this.labelingTextureBuffer.unbind(t)}renderIdentify(e){const t=this._gl,i=this.shaderProgramPendingVersion,r=this.getRenderObjectsByGroups(e,!0);return r.groups.forEach(({objects:o,tileObjects:a,framebuffer:l,isUnderCache:c})=>{var _,f,m;const d=this.modules.map.state.demMode&&(l===void 0||l.useDem===!0),u=l?l.renderTarget:this.identifyBuffer,h=ei(this.state,this.modules,r.tiers,u,d);if(u.bind(t),(u!==this.identifyBuffer||c)&&this.clearIdentify(),d&&r.flatObjectsGroup&&this.renderDemMesh(h,r.flatObjectsGroup,!0),u.bind(t),t.viewport(0,0,u.options.size[0],u.options.size[1]),o.length){const v=(f=(_=l==null?void 0:l.getViewProjectionMatrix)==null?void 0:_.call(l))!=null?f:this.modules.camera.viewProjectionMatrix,g=d?this.modules.demManager.demTextureMatrix:void 0;a.forEach(p=>{p.updateMvpMatrix(v,g)}),ai(this.state,this.modules,o,h)}u.unbind(t),l==null||l.renderTarget.unbind(this._gl),(m=l==null?void 0:l.onRenderEnd)==null||m.call(l)}),!this.hasShaderProgramPendingSince(i)}waitForGpuCommandsToFinish(){const e=new Float32Array(4);this.readPixelsFloat(0,0,1,1,e)}readPixelsFloat(e,t,i,r,o){const a=this._gl;a.readPixels(e,t,i,r,a.RGBA,a.FLOAT,o)}getRenderingContext(){return this._gl}getShaderProgram(e,t){var c,d;let i=this.shaderPrograms[e];i||(i={},this.shaderPrograms[e]=i);let r=i[this.commonShaderDefines.hash];r||(r={},i[this.commonShaderDefines.hash]=r);const o=(c=t==null?void 0:t.hash)!=null?c:"",a=(d=t==null?void 0:t.defines)!=null?d:[];let l=r[o];return l||(l=new oo(this._gl,this.shaderProgramOptions[e],n.Shader.createShaderDefinitions([...this.commonShaderDefines.defines,...a])),r[o]=l),l}getReadyShaderProgram(e,t){const i=this.getShaderProgram(e,t);return i.isReady()?i:this.prepareShaderProgramInFrame(i)}requestAsyncShaderProgramLink(e,t){const i=this.getShaderProgram(e,t);return!this.parallelShaderCompile||i.isLinked()||i.isReady()||(i.linkWithoutStatusCheck(),this.pendingShaderPrograms.add(i),this.markShaderProgramPending()),i}getShaderProgramIfReady(e,t){const i=this.getShaderProgram(e,t);return i.isReady()?i:null}hasPendingShaderPrograms(){return this.hasPendingShaderProgram}enableShaderProgram(e){var t;e.enable(),this.isUboSupported()&&((t=this.ubosMap.CommonSettings)==null||t.bind(e))}bindShaderProgram(e,t,i){e.bind(t,i)}destroy(){var t;if(this.destroyed)return;this.lastRenderedFramebuffers=[],this.framebuffers.forEach(i=>{i==null||i.renderTarget.remove()}),this.modules.layout.canvas.removeEventListener("webglcontextlost",this.trackContextLost),(t=this.timers)==null||t.destroy(),this.timers=void 0;const e=this._gl.getExtension("WEBGL_lose_context");e&&e.loseContext(),this.modules.layout.destroy(),this.mapMeshFramebufferId=void 0,this.mapMeshIdFramebufferId=void 0,this.destroyed=!0}addFramebuffer(e){return this.framebuffers.push(e),this.framebuffers.length-1}getFramebuffer(e){if(e!==n.INVALID_FRAMEBUFFER_ID)return this.framebuffers[e]}removeFramebuffer(e){var t;(t=this.framebuffers[e])==null||t.renderTarget.remove(),this.framebuffers[e]=void 0}setRenderTarget(e){this.currentTarget=e;const t=this._gl;if(e)e.bind(t),t.viewport(0,0,e.options.size[0],e.options.size[1]);else{t.bindFramebuffer(t.FRAMEBUFFER,null);const{size:i,viewport:r}=this.state,o=window.devicePixelRatio;t.viewport(r.left*o,r.bottom*o,i[0]*o,i[1]*o)}}getRenderTarget(){return this.currentTarget}getDrawTargetFramebuffer(e){const t=this.drawTargetsFramebufferIds.get(e);if(t!==void 0)return this.getFramebuffer(t)}doesDrawTargetFramebufferExist(e){const t=this.drawTargetsFramebufferIds.get(e);if(t!==void 0){const i=this.getFramebuffer(t);return i&&i.requestedInCurrentFrame}return!1}getDrawTargetFramebufferId(e){let t=this.drawTargetsFramebufferIds.get(e);if(t!==void 0){const c=this.getFramebuffer(t);return c&&(c.requestedInCurrentFrame=!0),t}const i=this.modules.map.state.demMode,r=this.modules.renderer.getPixelRatio(),o=this.modules.map.state.size,a=new Pe({size:i?[Math.trunc(o[0]*je[0]*r),Math.trunc(o[1]*je[1]*r)]:this.getViewportSize(),magFilter:C.LinearFilter,minFilter:C.LinearFilter,depthTexture:!0,wrapS:C.ClampToEdgeWrapping,wrapT:C.ClampToEdgeWrapping,generateMipmaps:!1,format:ri.webglVersion===2?C.RedFormat:C.RgbFormat}),l={renderTarget:a,clearColor:[0,0,0,0],clearDepth:!0,onResize:()=>{const c=this.modules.map.state.demMode,d=this.modules.map.state.size;a.setSize(c?[Math.trunc(d[0]*je[0]*r),Math.trunc(d[1]*je[1]*r)]:this.getViewportSize()),this.modules.renderer.bindRenderTarget(a),this.modules.renderer.bindRenderTarget(null)},renderIndex:-1/0,useDem:!1,requestedInCurrentFrame:!0};return t=this.modules.renderer.addFramebuffer(l),this.drawTargetsFramebufferIds.set(e,t),t}renderDemMesh(e,t,i=!1,r){const{framebuffer:o,tiles:a}=t;if(!o)return;let l=this.modules.demManager.getFlatMapTextures();if(i&&(l=l.filter(P=>P.detailLevel===0)),!l.length)return;const c=this.modules.demManager.getMeshTiles();if(!c.length)return;const d=c[0],h=(i?d.identifyChildren:d.children).filter(({sink:P})=>P==="mesh"||P==="mesh2")[0];if(!h)return;const _=this.state.handyStyleId,f=this.modules.styleManager.getStyleLayer(_,n.DEM_STYLE_LAYER_ID);if(!f||Ba(h))return;const{size:m,viewport:v}=this.state,g=window.devicePixelRatio,{commonBinder:p,programBinder:x,layerBinder:S,programName:b}=h.layerSettings,T=this.getShaderProgram(b),y=[];a.forEach((P,A)=>{y.push({objects:P,tile:A})});const E=e.copy(o.renderTarget,!1,!0);l.forEach(P=>{var B,Q;const F=y.filter(Z=>oh(P.viewport,Z.tile.bounds.values())).reduce((Z,$)=>($.tile.updateMvpMatrix(P.mvpMatrix,this.modules.demManager.demTextureMatrix),Z.concat($.objects)),[]),L=[],D=new Map;if(F.forEach(({obj:Z,framebufferId:$})=>{if($===void 0)L.push(Z);else{const J=D.get($);J?J.push(Z):D.set($,[Z])}}),D.forEach((Z,$)=>{var ge,Ce;const J=this.getFramebuffer($);J&&((ge=J.onRenderStart)==null||ge.call(J),J.renderTarget.bind(this._gl),this._gl.viewport(0,0,J.renderTarget.options.size[0],J.renderTarget.options.size[1]),J.clearColor&&this.clearWithColor(J.clearColor,!1),ai(this.state,this.modules,Z,E),J.renderTarget.unbind(this._gl),(Ce=J.onRenderEnd)==null||Ce.call(J))}),(B=o.onRenderStart)==null||B.call(o),o.renderTarget.bind(this._gl),this._gl.viewport(0,0,o.renderTarget.options.size[0],o.renderTarget.options.size[1]),o.clearColor&&this.clearWithColor(o.clearColor,!1),ai(this.state,this.modules,L,E),o.renderTarget.unbind(this._gl),(Q=o.onRenderEnd)==null||Q.call(o),i){this.identifyBuffer.bind(this._gl);const Z=this.identifyBuffer.options.size;this._gl.viewport(0,0,Z[0],Z[1])}else r?(this._gl.viewport(0,0,r.renderTarget.options.size[0],r.renderTarget.options.size[1]),r.renderTarget.bind(this._gl)):this._gl.viewport(v.left*g,v.bottom*g,m[0]*g,m[1]*g);this.enableShaderProgram(T),this._gl instanceof WebGLRenderingContext&&(p==null||p(T,this.state,this.modules)),x==null||x(T,this.state,this.modules,!0),S==null||S(T,this.state,this.modules,f),e.useState(h,f),c.forEach(Z=>{if(Z instanceof Tc&&Z.needSync&&Z.syncReplicas(this.state),oh(P.viewport,Z.bounds.values())){Z.updateMvpMatrix(this.modules.camera.viewProjectionMatrix,this.modules.demManager.demTextureMatrix,P.texMatrix);const $=(i?Z.identifyChildren:Z.children).filter(({sink:J})=>J==="mesh"||J==="mesh2");qo($,this.state,this.modules),e.drawSymbol($,f,this.state,this.modules)}}),i&&this.identifyBuffer.unbind(this._gl)})}getMapMeshFramebufferId(){return this.mapMeshFramebufferId===void 0&&(this.mapMeshFramebufferId=this.createMapMeshFramebuffer()),this.mapMeshFramebufferId}getMapMeshIdFramebufferId(){return this.mapMeshIdFramebufferId===void 0&&(this.mapMeshIdFramebufferId=this.createMapMeshFramebuffer(!0)),this.mapMeshIdFramebufferId}prerenderUpdate(){this.hasPendingShaderProgram=!1,this.pollPendingShaderPrograms();const e=this.rebuildExternalShaderDefinitions();this.updateUbos(e)}getRenderObjectsByGroups(e,t){const{demManager:i,map:r}=this.modules,{demMode:o}=r.state,a={},l={framebuffer:void 0,objects:[],tileObjects:new Set},c={framebuffer:void 0,objects:[],tileObjects:new Set,isUnderCache:!0},d={};let u;if(o){const _=t?i.getIdentifyFlatFramebufferId():i.getFlatFramebufferId(),f=this.getFramebuffer(_);f&&(u={framebuffer:f,tiles:new Map})}this.hasAnimatedFlatObjectInDemMode=!t&&o&&e.some(_=>_.children.some(f=>!f.layerSettings.is3dMapAware&&this.modules.renderCacheManager.isLayerAnimated(f.attributes.styleId,f.attributes.layerId))),e.forEach(_=>{(t?_.identifyChildren:_.children).forEach(m=>{var b;if(m.sink==="mesh2")return;const{ids:v,defaultId:g,isDrawTarget:p}=this.modules.styleManager.getFramebufferId(m.attributes.styleId,m.attributes.layerId),x=v?v[m.sink]:g;if(x===n.INVALID_FRAMEBUFFER_ID)return;if(x===void 0||o&&p){const T=m.attributes.tiers;if(this.state.immersiveLevel.tiers&&T){let y=!1;if(T.forEach(E=>{if(!E){y=!0;return}d[E]||(d[E]={objects:[],tileObjects:new Set}),d[E].objects.push(m),d[E].tileObjects.add(_)}),!y)return}if(o&&!m.layerSettings.is3dMapAware)u!=null&&u.tiles.has(_)?(b=u==null?void 0:u.tiles.get(_))==null||b.push({obj:m,framebufferId:x}):u==null||u.tiles.set(_,[{obj:m,framebufferId:x}]),this.hasAnimatedFlatObjectInDemMode||this.modules.renderCacheManager.markLayerInCache(m.attributes.styleId,m.attributes.layerId);else if(t)c.objects.push(m),c.tileObjects.add(_);else{const y=this.modules.renderCacheManager.tryToCacheObjects(a,m,_,o);if(y===Ga.CACHED)return;y===Ga.RENDER_OVER_CACHE?(l.objects.push(m),l.tileObjects.add(_)):(c.objects.push(m),c.tileObjects.add(_))}return}a[x]||(a[x]={framebuffer:this.getFramebuffer(x),objects:[],tileObjects:new Set}),a[x].objects.push(m),a[x].tileObjects.add(_)})});const h=Object.values(a).filter(_=>!!_.framebuffer);return h.sort((_,f)=>{var g,p,x,S;const m=(p=(g=_.framebuffer)==null?void 0:g.renderIndex)!=null?p:0,v=(S=(x=f.framebuffer)==null?void 0:x.renderIndex)!=null?S:0;return m-v}),h.push(c),t||(h.findIndex(f=>{var m;return(m=f.framebuffer)==null?void 0:m.isCacheFramebuffer})>=0?l.objects.push(...this.modules.styleManager.getCustomSceneObjects()):c.objects.push(...this.modules.styleManager.getCustomSceneObjects())),h.push(l),{flatObjectsGroup:u,groups:h,tiers:d}}getUbo(e){return this.ubosMap[e]}getMemoryFootprint(){const e={framebuffers:this.framebuffers.filter(t=>t!==void 0).map(t=>t.renderTarget.memSizeGPU()),identifyBuffer:this.identifyBuffer.memSizeGPU(),labelingTextureBuffer:this.labelingTextureBuffer.memSizeGPU()};return{gpu:V(I({},e),{"--sum":n.getTotalMemory(e)})}}bindRenderTarget(e){const t=this._gl;e?e.bind(t):t.bindFramebuffer(t.FRAMEBUFFER,null)}isUboSupported(){return!(this._gl instanceof WebGLRenderingContext)}resetStateAfterExternalRender(){if(this.modules.styleManager.hasCustomLayers()){const e=this._gl;if(this.invalidateGlStateCache(),e instanceof WebGL2RenderingContext)e.bindVertexArray(null),e.bindBuffer(e.PIXEL_PACK_BUFFER,null),e.bindBuffer(e.PIXEL_UNPACK_BUFFER,null),e.bindBuffer(e.TRANSFORM_FEEDBACK_BUFFER,null),e.disable(e.RASTERIZER_DISCARD),e.bindSampler(0,null);else{const t=this.webGlExtensions.OES_vertex_array_object;t==null||t.bindVertexArrayOES(null)}if(e.useProgram(null),e.bindBuffer(e.ARRAY_BUFFER,null),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,null),e.bindTexture(e.TEXTURE_CUBE_MAP,null),e.depthRange(0,1),e.frontFace(e.CCW),e.disable(e.SCISSOR_TEST),e.disable(e.STENCIL_TEST),e instanceof WebGL2RenderingContext)for(const t in this.ubosMap)this.ubosMap[t].rebind();this.lastAppliedGpuState={state:null}}}isWebgl2Context(){return!(this._gl instanceof WebGLRenderingContext)}fragDepthSupported(){return this.isWebgl2Context()||!!this.modules.renderer.webGlExtensions.EXT_frag_depth}updateUbos(e=!1){var c;const t=this._gl;if(t instanceof WebGLRenderingContext)return;e&&this.cleanupUbos(t);const i=this.getShaderProgram("diffuse");i.link(),i.locate();let r=this.ubosMap.CommonSettings;(!r||e)&&(r=new th({gl:t,blockName:"CommonSettings"}),this.ubosMap.CommonSettings=r,r.bind(i)),Sm(i,this.state,this.modules,r),r.commitData();const o=this.modules.map.state,a=!isNaN(o.handyStyleId)&&this.modules.styleManager.getStyle(o.handyStyleId)||void 0,l=(c=a==null?void 0:a.light.lightingModesResolved)!=null?c:n.DEFAULT_LIGHTING_MODES;for(const d in l){let u=this.ubosMap[d];(!u||e)&&(u=new th({gl:t,blockName:"LightSettings"}));const h=l[d];u.updateData(i,{u_vec3_light_dir1_direction:h.dir1Direction,u_vec4_light_dir1_color:h.dir1ColorIntensity,u_vec3_light_dir2_direction:h.dir2Direction,u_vec4_light_dir2_color:h.dir2ColorIntensity,u_vec4_ambient_color:h.ambientColorIntensity}),this.ubosMap[d]=u,u.commitData()}}cleanupUbos(e){for(const t in this.ubosMap)this.ubosMap[t].cleanup();this.ubosMap={};for(let t=0;t<this.webglContextState.MAX_UNIFORM_BUFFER_BINDINGS;t++)e.bindBufferBase(e.UNIFORM_BUFFER,t,null)}rebuildExternalShaderDefinitions(){const e=this.prepareExternalShaderDefinitions();return this.commonShaderDefines.hash!==e.hash?(this.commonShaderDefines=e,!0):!1}clearIdentify(){const e=this._gl;e.depthMask(!0),e.clearColor(Ui[0],Ui[1],Ui[2],Ui[3]),e.clearDepth(1),e.clearStencil(0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT|e.STENCIL_BUFFER_BIT)}clearFramebuffer(e){e.clearColor&&(e.renderTarget.bind(this._gl),this._gl.viewport(0,0,e.renderTarget.options.size[0],e.renderTarget.options.size[1]),this.clearWithColor(e.clearColor,!1),e.renderTarget.unbind(this._gl))}createMapMeshFramebuffer(e){const t=this.getRenderingContext(),i=e?C.NearestFilter:C.LinearFilter,{scale:r,size:o}=this.calculateMapMeshParams(e),a=new Pe({size:o,magFilter:i,minFilter:i,wrapS:C.ClampToEdgeWrapping,wrapT:C.ClampToEdgeWrapping}),l={getViewProjectionMatrix:()=>{var u;const c=1-Math.cos(this.modules.map.state.pitch),d=(u=l.scale)!=null?u:this.calculateMapMeshParams(e).scale;return n.fromTranslationScale(sh,[0,c/d[1],0],[1/d[0],1/d[1],1]),n.multiply(this.mapMeshMvpMatrix,sh,this.modules.camera.viewProjectionMatrix),this.mapMeshMvpMatrix},onResize:()=>{const c=this.calculateMapMeshParams(e);l.scale=c.scale,a.setSize(c.size),a.bind(t),a.unbind(t)},renderTarget:a,scale:r};return this.addFramebuffer(l)}prepareShaderProgramInFrame(e){return e.isReady()?e:this.parallelShaderCompile?(e.isLinked()||(e.linkWithoutStatusCheck(),this.pendingShaderPrograms.add(e)),e.isLinkComplete(this.parallelShaderCompile)?(this.pendingShaderPrograms.delete(e),e.locate(),e):(this.pendingShaderPrograms.add(e),this.markShaderProgramPending(),null)):(e.isLinked()||e.link(),e.locate(),e)}markShaderProgramPending(){this.hasPendingShaderProgram=!0,this.shaderProgramPendingVersion++}hasShaderProgramPendingSince(e){return this.shaderProgramPendingVersion!==e}pollPendingShaderPrograms(){if(!(!this.parallelShaderCompile||!this.pendingShaderPrograms.size)){for(const e of Array.from(this.pendingShaderPrograms)){if(e.isReady()){this.pendingShaderPrograms.delete(e);continue}if(!e.isLinkComplete(this.parallelShaderCompile)){this.hasPendingShaderProgram=!0;continue}e.locate(),this.pendingShaderPrograms.delete(e)}this.pendingShaderPrograms.size&&(this.hasPendingShaderProgram=!0)}}calculateMapMeshParams(e){const t=e?n.identify.pixelDensity:1,i=window.devicePixelRatio,r=n.scale$2([],this.modules.map.state.size,i),o=Math.min(Va,Math.min(this.webglContextState.MAX_TEXTURE_SIZE,this.webglContextState.MAX_VIEWPORT_DIMS[0])/r[0]),a=Math.min(fs,Math.min(this.webglContextState.MAX_TEXTURE_SIZE,this.webglContextState.MAX_VIEWPORT_DIMS[1])/r[1]),l=[Math.trunc(r[0]*t*o),Math.trunc(r[1]*t*a)];return{scale:[o,a],size:l}}prepareExternalShaderDefinitions(){const e=[];return this.webGlExtensions.EXT_frag_depth&&e.push({type:"HAS_FRAG_DEPTH_EXT"}),this.modules.environmentManager.isFogEnabled()&&e.push({type:mx}),this.modules.environmentManager.isSkyEnabled()&&e.push({type:vx}),this.modules.shadowManager.texture&&e.push({type:Ax}),this.state.aaMode===Et.FXAA?e.push({type:Fi.FXAA}):this.state.aaMode===Et.TAA&&e.push({type:Fi.TAA}),Zl(this._gl)&&e.push({type:Px}),this.webglContextState.MAX_UNIFORM_BUFFER_BINDINGS>0&&e.push({type:Lx}),this.state.isDeprecatedSystem?e.push({type:zx}):(e.push({type:Rx}),e.push({type:Fx})),this.webglContextState.RENDERER.toLowerCase().includes("mali")&&this.webglContextState.VENDOR.toLowerCase().includes("arm")&&e.push({type:Dx}),n.Shader.createShaderDefinitions(e)}},ri.webglVersion=NaN,ri);function oh(s,e){for(const t of e)if(n.tetragonIntersectsBounds(s,t))return!0;return!1}function Un(s,e,t,i){var r,o,a;s[e]=(r=t[0])!=null?r:0,s[e+1]=(o=t[1])!=null?o:0,s[e+2]=(a=t[2])!=null?a:0,s[e+3]=i}class pT{constructor(e){this._buffer=new ArrayBuffer(e),this.i32=new Int32Array(this._buffer),this.f32=new Float32Array(this._buffer),this.u32=new Uint32Array(this._buffer),this.f64=new Float64Array(this._buffer),this.writeOffset=n.FrameHeader._Size,this.clear()}get buffer(){return this._buffer}get commandCount(){return this.u32[n.FrameHeader.CommandCount>>2]}get materialCount(){return this.u32[n.FrameHeader.MaterialCount>>2]}get bytesUsed(){return this.writeOffset}get bytesAvailable(){return this._buffer.byteLength-this.writeOffset}clear(){this.writeOffset=n.FrameHeader._Size,this.u32[n.FrameHeader.FrameId>>2]=0,this.u32[n.FrameHeader.MaterialOffset>>2]=n.FrameHeader._Size,this.u32[n.FrameHeader.MaterialCount>>2]=0,this.u32[n.FrameHeader.CommandOffset>>2]=n.FrameHeader._Size,this.u32[n.FrameHeader.CommandCount>>2]=0,this.f64.fill(0,n.FrameHeader.ViewProjectionMatrix>>3,n.FrameHeader._Size>>3)}collectResourceRefs(e,t){const i=this.u32[n.FrameHeader.CommandCount>>2];let r=this.u32[n.FrameHeader.CommandOffset>>2];for(let l=0;l<i;l++){const c=r>>2,d=this.u32[c],u=n.getCommandSize(d);if(u===0)break;n.readCommandRefs(this.u32,c,d,e),r+=u}const o=this.u32[n.FrameHeader.MaterialCount>>2];let a=this.u32[n.FrameHeader.MaterialOffset>>2];for(let l=0;l<o;l++){const c=a>>2;n.readMaterialRefs(this.u32,c,t);const d=this.u32[c+(n.MaterialCmd.ByteSize>>2)];if(d===0)break;a+=d}}setViewProjectionMatrix(e){this.f64.set(e,n.FrameHeader.ViewProjectionMatrix>>3)}setIdentifyRequest(e,t,i){this.u32[n.FrameHeader.IdentifyRequestId>>2]=e,this.u32[n.FrameHeader.IdentifyWidth>>2]=t,this.u32[n.FrameHeader.IdentifyHeight>>2]=i}setCameraPosition(e){var i,r,o;const t=n.FrameHeader.CameraPosition>>3;this.f64[t]=(i=e[0])!=null?i:0,this.f64[t+1]=(r=e[1])!=null?r:0,this.f64[t+2]=(o=e[2])!=null?o:0}setReplicaRange(e,t){this.i32[n.FrameHeader.ReplicaMin>>2]=e,this.i32[n.FrameHeader.ReplicaMax>>2]=t}setDemState(e){const t=this.u32[n.FrameHeader.Flags>>2];this.u32[n.FrameHeader.Flags>>2]=e.demMode?t|n.FrameFlags.DemMode:t&~n.FrameFlags.DemMode,this.u32[n.FrameHeader.DemTextureSize>>2]=e.demTextureSize,this.f32[n.FrameHeader.DemScale>>2]=e.demScale,this.f32[n.FrameHeader.DemCenterElevation>>2]=e.centerElevation,this.f32[n.FrameHeader.DemMinElevation>>2]=e.minElevation,this.f32[n.FrameHeader.DemShadingIntensity>>2]=e.shadingIntensity,this.f32.set(e.backgroundColor,n.FrameHeader.BackgroundColor>>2),this.f64.set(e.demTextureMatrix,n.FrameHeader.DemTextureMatrix>>3)}setLightState(e){const t=this.beginMaterial(n.MaterialKind.EnvLight,n.MaterialEnvLight._Size,0);t<0||(this.writeLightBlock(t+n.MaterialEnvLight.Data>>2,e),this.commitMaterial(n.MaterialEnvLight._Size))}setDemLightState(e){const t=this.beginMaterial(n.MaterialKind.EnvDemLight,n.MaterialEnvLight._Size,0);t<0||(this.writeLightBlock(t+n.MaterialEnvLight.Data>>2,e),this.commitMaterial(n.MaterialEnvLight._Size))}setFlatLevels(e){const t=Math.min(e.length,n.FLAT_LEVEL_MAX);this.u32[n.FrameHeader.FlatLevelCount>>2]=t;for(let i=0;i<t;i++){const r=n.FrameHeader.FlatLevels+i*n.FlatLevelRecord._Size>>3;this.f64.set(e[i].mvpMatrix,r+(n.FlatLevelRecord.Mvp>>3)),this.f64.set(e[i].texMatrix,r+(n.FlatLevelRecord.Tex>>3))}}setIdentifyFlatLevelMask(e){this.u32[n.FrameHeader.IdentifyFlatLevelMask>>2]=e}setMapMeshState(e){this.f64.set(e.vpMatrix,n.FrameHeader.MapMeshVpMatrix>>3),this.f32[n.FrameHeader.MapMeshScaleX>>2]=e.scaleX,this.f32[n.FrameHeader.MapMeshScaleY>>2]=e.scaleY,this.f32[n.FrameHeader.MapMeshTexShift>>2]=e.texShift}setGlobeState(e){var o,a,l,c,d;const t=this.u32[n.FrameHeader.Flags>>2];this.u32[n.FrameHeader.Flags>>2]=e.globeMode?t|n.FrameFlags.GlobeMode:t&~n.FrameFlags.GlobeMode,this.f64.set(e.ecefViewProjection,n.FrameHeader.EcefViewProjection>>3),this.f32[n.FrameHeader.GlobeCrossfade>>2]=e.crossfade;const i=n.FrameHeader.CameraMercator>>3;this.f64[i]=(o=e.cameraMercator[0])!=null?o:0,this.f64[i+1]=(a=e.cameraMercator[1])!=null?a:0,this.f64.set(e.vpAtCenter,n.FrameHeader.VpAtCenter>>3);const r=n.FrameHeader.GlobeCameraEcef>>2;this.f32[r]=(l=e.cameraEcef[0])!=null?l:0,this.f32[r+1]=(c=e.cameraEcef[1])!=null?c:0,this.f32[r+2]=(d=e.cameraEcef[2])!=null?d:0}setStarsState(e){const t=this.beginMaterial(n.MaterialKind.EnvStars,n.MaterialEnvStars._Size,0);t<0||(this.f32.set(e.starsMatrix,t+n.MaterialEnvStars.Matrix>>2),this.f32[t+n.MaterialEnvStars.Intensity>>2]=e.intensity,this.commitMaterial(n.MaterialEnvStars._Size))}setRequiredSeq(e){this.u32[n.FrameHeader.RequiredSeq>>2]=e}setFogState(e){var r,o;const t=this.beginMaterial(n.MaterialKind.EnvFog,n.MaterialEnvFog._Size,0);if(t<0)return;const i=t+n.MaterialEnvFog.Data>>2;this.f32.set(e.fogColor,i),this.f32.set(e.skyColor,i+4),this.f32[i+8]=(r=e.limits[0])!=null?r:0,this.f32[i+9]=(o=e.limits[1])!=null?o:0,this.f32[i+10]=e.horizonBlend,this.f32[i+11]=e.horizonLevel,this.f32[i+12]=e.fogDistance,this.f32[i+13]=e.horizonPad,this.f32[i+14]=0,this.f32[i+15]=0,this.commitMaterial(n.MaterialEnvFog._Size)}setSkyState(e){const t=this.beginMaterial(n.MaterialKind.EnvSky,n.MaterialEnvSky._Size,0);t<0||(this.f32.set(e.viewTransposed,t+n.MaterialEnvSky.ViewTransposed>>2),this.f32.set(e.projInverted,t+n.MaterialEnvSky.ProjInverted>>2),this.commitMaterial(n.MaterialEnvSky._Size))}setShadowState(e){const t=this.beginMaterial(n.MaterialKind.EnvShadow,n.MaterialEnvShadow._Size,0);if(t<0)return;const i=t+n.MaterialEnvShadow.Data>>2;this.f32.set(e.clipToShadow,i),this.f32.set(e.mapParams,i+16),this.f32[i+20]=e.bias,this.f32[i+21]=e.shadowLightIndex+1,this.f32[i+22]=e.orthoAnisotropy[0],this.f32[i+23]=e.orthoAnisotropy[1],this.commitMaterial(n.MaterialEnvShadow._Size),this.f64.set(e.shadowViewProjection,n.FrameHeader.ShadowViewProjection>>3)}setGlobeHaloState(e){const t=this.beginMaterial(n.MaterialKind.EnvGlobeHalo,n.MaterialEnvGlobeHalo._Size,0);if(t<0)return;const i=t+n.MaterialEnvGlobeHalo.Data>>2;this.f32.set(e.haloColor,i),this.f32.set(e.radiusStops,i+4),this.f32.set(e.viewport,i+8),this.f32[i+12]=e.expFactor,this.f32[i+13]=0,this.f32[i+14]=0,this.f32[i+15]=0,this.f32.set(e.backgroundColor,i+16),this.commitMaterial(n.MaterialEnvGlobeHalo._Size)}writeMaterial(e){var r,o,a,l,c,d;const t=this.beginMaterial(e.kind,n.MaterialCmd._ColorSize,(r=e.flags)!=null?r:0);if(t<0)return-1;this.f32[t+n.MaterialCmd.Color1R>>2]=e.color1[0],this.f32[t+n.MaterialCmd.Color1G>>2]=e.color1[1],this.f32[t+n.MaterialCmd.Color1B>>2]=e.color1[2],this.f32[t+n.MaterialCmd.Color1A>>2]=e.color1[3];const i=e.color2;return this.f32[t+n.MaterialCmd.Color2R>>2]=i?i[0]:0,this.f32[t+n.MaterialCmd.Color2G>>2]=i?i[1]:0,this.f32[t+n.MaterialCmd.Color2B>>2]=i?i[2]:0,this.f32[t+n.MaterialCmd.Color2A>>2]=i?i[3]:0,this.f32[t+n.MaterialCmd.FactorBase>>2]=(o=e.factorBase)!=null?o:1,this.f32[t+n.MaterialCmd.FactorInMin>>2]=(a=e.factorInMin)!=null?a:0,this.f32[t+n.MaterialCmd.FactorOutMin>>2]=(l=e.factorOutMin)!=null?l:0,this.f32[t+n.MaterialCmd.FactorInMax>>2]=(c=e.factorInMax)!=null?c:1,this.f32[t+n.MaterialCmd.FactorOutMax>>2]=(d=e.factorOutMax)!=null?d:1,this.commitMaterial(n.MaterialCmd._ColorSize)}writePolygonTextureMaterial(e){const t=this.beginMaterial(n.MaterialKind.PolygonTexture,n.MaterialPolygonTexture._Size,0);return t<0?-1:(this.f32[t+n.MaterialCmd.Color1R>>2]=e.color1[0],this.f32[t+n.MaterialCmd.Color1G>>2]=e.color1[1],this.f32[t+n.MaterialCmd.Color1B>>2]=e.color1[2],this.f32[t+n.MaterialCmd.Color1A>>2]=e.color1[3],this.u32[t+n.MaterialPolygonTexture.TextureId>>2]=e.textureId,this.f32[t+n.MaterialPolygonTexture.SpriteX1>>2]=e.spriteCoords[0],this.f32[t+n.MaterialPolygonTexture.SpriteY1>>2]=e.spriteCoords[1],this.f32[t+n.MaterialPolygonTexture.SpriteX2>>2]=e.spriteCoords[2],this.f32[t+n.MaterialPolygonTexture.SpriteY2>>2]=e.spriteCoords[3],this.f32[t+n.MaterialPolygonTexture.Opacity>>2]=e.opacity,this.commitMaterial(n.MaterialPolygonTexture._Size))}writeDrawPolygonTextured(e){var i;const t=this.beginCommand(n.CommandType.DrawPolygonTextured,n.CommandDrawPolygonTextured._Size,e);return t<0?!1:(this.u32[t+n.CommandDrawPolygonTextured.VertexOffset>>2]=e.vertexOffset,this.u32[t+n.CommandDrawPolygonTextured.VertexCount>>2]=e.vertexCount,this.f32[t+n.CommandDrawPolygonTextured.TexOffsetX>>2]=e.texParams[0],this.f32[t+n.CommandDrawPolygonTextured.TexOffsetY>>2]=e.texParams[1],this.f32[t+n.CommandDrawPolygonTextured.TexMulX>>2]=e.texParams[2],this.f32[t+n.CommandDrawPolygonTextured.TexMulY>>2]=e.texParams[3],this.f32[t+n.CommandDrawPolygonTextured.FloorElevation>>2]=(i=e.floorElevation)!=null?i:0,this.commitCommand(n.CommandDrawPolygonTextured._Size),!0)}writeDrawPolygon(e){var i;const t=this.beginCommand(n.CommandType.DrawPolygon,n.CommandDrawPolygon._Size,e);return t<0?!1:(this.u32[t+n.CommandDrawPolygon.VertexOffset>>2]=e.vertexOffset,this.u32[t+n.CommandDrawPolygon.VertexCount>>2]=e.vertexCount,this.f32[t+n.CommandDrawPolygon.FloorElevation>>2]=(i=e.floorElevation)!=null?i:0,this.commitCommand(n.CommandDrawPolygon._Size),!0)}writeDrawLine(e){var i;const t=this.beginCommand(n.CommandType.DrawLine,n.CommandDrawLine._Size,e);return t<0?!1:(this.u32[t+n.CommandDrawLine.VertexOffset>>2]=e.vertexOffset,this.u32[t+n.CommandDrawLine.VertexCount>>2]=e.vertexCount,this.f32[t+n.CommandDrawLine.Width>>2]=e.width,this.f32[t+n.CommandDrawLine.TileToPixelRatio>>2]=e.tileToPixelRatio,this.f32[t+n.CommandDrawLine.Shift>>2]=e.shift,this.u32[t+n.CommandDrawLine.Geometry>>2]=e.geometry,this.u32[t+n.CommandDrawLine.AbsZ>>2]=e.absZ?1:0,this.f32[t+n.CommandDrawLine.EcefScale>>2]=e.ecefScale,this.f32[t+n.CommandDrawLine.FloorElevation>>2]=(i=e.floorElevation)!=null?i:0,this.commitCommand(n.CommandDrawLine._Size),!0)}writeDrawLineParameterized(e){var i;const t=this.beginCommand(n.CommandType.DrawLineParameterized,n.CommandDrawLineParameterized._Size,e);return t<0?!1:(this.u32[t+n.CommandDrawLineParameterized.VertexOffset>>2]=e.vertexOffset,this.u32[t+n.CommandDrawLineParameterized.VertexCount>>2]=e.vertexCount,this.f32[t+n.CommandDrawLineParameterized.Width>>2]=e.width,this.f32[t+n.CommandDrawLineParameterized.LengthScale>>2]=e.lengthScale,this.f32[t+n.CommandDrawLineParameterized.CircleFactor>>2]=e.circleFactor,this.f32[t+n.CommandDrawLineParameterized.TileToPixelRatio>>2]=e.tileToPixelRatio,this.u32[t+n.CommandDrawLineParameterized.Geometry>>2]=e.geometry,this.f32[t+n.CommandDrawLineParameterized.EcefScale>>2]=e.ecefScale,this.f32[t+n.CommandDrawLineParameterized.FloorElevation>>2]=(i=e.floorElevation)!=null?i:0,this.commitCommand(n.CommandDrawLineParameterized._Size),!0)}writeDrawLineSprite(e){const t=this.beginCommand(n.CommandType.DrawLineSprite,n.CommandDrawLineSprite._Size,e);return t<0?!1:(this.u32[t+n.CommandDrawLineSprite.VertexOffset>>2]=e.vertexOffset,this.u32[t+n.CommandDrawLineSprite.VertexCount>>2]=e.vertexCount,this.f32[t+n.CommandDrawLineSprite.Opacity>>2]=e.opacity,this.f32[t+n.CommandDrawLineSprite.SizeFactor>>2]=e.sizeFactor,this.f32[t+n.CommandDrawLineSprite.CalcScale>>2]=e.calcScale,this.f32[t+n.CommandDrawLineSprite.ScaleRatio>>2]=e.scaleRatio,this.f32[t+n.CommandDrawLineSprite.BorderWidthOffset>>2]=e.borderWidthOffset,this.u32[t+n.CommandDrawLineSprite.Geometry>>2]=e.geometry,this.f32[t+n.CommandDrawLineSprite.VertexShift>>2]=e.vertexShift,this.f32[t+n.CommandDrawLineSprite.EndPosition>>2]=e.endPosition,this.f32[t+n.CommandDrawLineSprite.TipAmplitude>>2]=e.tipAmplitude,this.commitCommand(n.CommandDrawLineSprite._Size),!0)}writeDrawPointSprite(e){const t=this.beginCommand(n.CommandType.DrawPointSprite,n.CommandDrawPointSprite._Size,e);return t<0?!1:(this.u32[t+n.CommandDrawPointSprite.VertexOffset>>2]=e.vertexOffset,this.u32[t+n.CommandDrawPointSprite.VertexCount>>2]=e.vertexCount,this.f32[t+n.CommandDrawPointSprite.OpacityVisible>>2]=e.opacityVisible,this.f32[t+n.CommandDrawPointSprite.OpacityHidden>>2]=e.opacityHidden,this.f32[t+n.CommandDrawPointSprite.RotationCos>>2]=e.rotationCos,this.f32[t+n.CommandDrawPointSprite.RotationSin>>2]=e.rotationSin,this.f32[t+n.CommandDrawPointSprite.HeightFactor>>2]=e.heightFactor,this.f32[t+n.CommandDrawPointSprite.FloorElevation>>2]=e.floorElevation,this.f32[t+n.CommandDrawPointSprite.StyleScale>>2]=e.styleScale,this.f32[t+n.CommandDrawPointSprite.Dpi>>2]=e.dpi,this.f32[t+n.CommandDrawPointSprite.RoundingFactor>>2]=e.roundingFactor,this.u32[t+n.CommandDrawPointSprite.Flags>>2]=(e.skipHeightFactor?n.PointSpriteFlags.SkipHeightFactor:0)|(e.surfaceUseAbsZ?n.PointSpriteFlags.SurfaceUseAbsZ:0)|(e.labelTest?n.PointSpriteFlags.LabelTest:0),this.f32[t+n.CommandDrawPointSprite.SurfaceRelZNorm>>2]=e.surfaceRelZNorm,this.f32[t+n.CommandDrawPointSprite.SurfaceAbsZ>>2]=e.surfaceAbsZ,this.f32[t+n.CommandDrawPointSprite.IdentifyOpacity>>2]=e.identifyOpacity,this.f32[t+n.CommandDrawPointSprite.HalfPointSizeX>>2]=e.halfPointSizeX,this.f32[t+n.CommandDrawPointSprite.HalfPointSizeY>>2]=e.halfPointSizeY,this.commitCommand(n.CommandDrawPointSprite._Size),!0)}writePointSpriteMaterial(e){const t=this.beginMaterial(n.MaterialKind.PointSprite,n.MaterialPointSprite._Size,0);return t<0?-1:(this.u32[t+n.MaterialPointSprite.TextureId>>2]=e.textureId,this.commitMaterial(n.MaterialPointSprite._Size))}writeDrawLabelPoint(e){const t=this.beginCommand(n.CommandType.DrawLabelPoint,n.CommandDrawLabelPoint._Size,e);return t<0?!1:(this.u32[t+n.CommandDrawLabelPoint.VertexOffset>>2]=e.vertexOffset,this.u32[t+n.CommandDrawLabelPoint.VertexCount>>2]=e.vertexCount,this.f32[t+n.CommandDrawLabelPoint.Opacity>>2]=e.opacity,this.f32[t+n.CommandDrawLabelPoint.Scale>>2]=e.scale,this.f32[t+n.CommandDrawLabelPoint.OffsetX>>2]=e.offsetX,this.f32[t+n.CommandDrawLabelPoint.OffsetY>>2]=e.offsetY,this.f32[t+n.CommandDrawLabelPoint.Gamma>>2]=e.gamma,this.f32[t+n.CommandDrawLabelPoint.HaloBuffer>>2]=e.haloBuffer,this.f32[t+n.CommandDrawLabelPoint.FillBuffer>>2]=e.fillBuffer,this.f32[t+n.CommandDrawLabelPoint.HeightFactor>>2]=e.heightFactor,this.f32[t+n.CommandDrawLabelPoint.FloorElevation>>2]=e.floorElevation,this.u32[t+n.CommandDrawLabelPoint.Flags>>2]=(e.skipHeightFactor?n.LabelPointFlags.SkipHeightFactor:0)|(e.surfaceUseAbsZ?n.LabelPointFlags.SurfaceUseAbsZ:0)|(e.hasHalo?n.LabelPointFlags.HasHalo:0)|(e.labelIndexIcon?n.LabelPointFlags.LabelIndexIcon:0),this.f32[t+n.CommandDrawLabelPoint.SurfaceRelZNorm>>2]=e.surfaceRelZNorm,this.f32[t+n.CommandDrawLabelPoint.SurfaceAbsZ>>2]=e.surfaceAbsZ,this.f32.set(e.haloColor,t+n.CommandDrawLabelPoint.HaloColorR>>2),this.f32.set(e.fillColor,t+n.CommandDrawLabelPoint.FillColorR>>2),this.f32.set(e.haloHiddenColor,t+n.CommandDrawLabelPoint.HaloHiddenColorR>>2),this.f32.set(e.fillHiddenColor,t+n.CommandDrawLabelPoint.FillHiddenColorR>>2),this.f32[t+n.CommandDrawLabelPoint.HalfPointSizeX>>2]=e.halfPointSizeX,this.f32[t+n.CommandDrawLabelPoint.HalfPointSizeY>>2]=e.halfPointSizeY,this.commitCommand(n.CommandDrawLabelPoint._Size),!0)}writeDrawPointAnchor(e){const t=this.beginCommand(n.CommandType.DrawPointAnchor,n.CommandDrawPointAnchor._Size,e);return t<0?!1:(this.u32[t+n.CommandDrawPointAnchor.VertexOffset>>2]=e.vertexOffset,this.u32[t+n.CommandDrawPointAnchor.VertexCount>>2]=e.vertexCount,this.f32[t+n.CommandDrawPointAnchor.OffsetX>>2]=e.offsetX,this.f32[t+n.CommandDrawPointAnchor.OffsetY>>2]=e.offsetY,this.f32[t+n.CommandDrawPointAnchor.FloorElevation>>2]=e.floorElevation,this.u32[t+n.CommandDrawPointAnchor.Flags>>2]=e.surfaceUseAbsZ?n.PointSpriteFlags.SurfaceUseAbsZ:0,this.f32[t+n.CommandDrawPointAnchor.SurfaceRelZNorm>>2]=e.surfaceRelZNorm,this.f32[t+n.CommandDrawPointAnchor.SurfaceAbsZ>>2]=e.surfaceAbsZ,this.commitCommand(n.CommandDrawPointAnchor._Size),!0)}writeDrawMetricPoint(e){const t=this.beginCommand(n.CommandType.DrawMetricPoint,n.CommandDrawMetricPoint._Size,e);return t<0?!1:(this.u32[t+n.CommandDrawMetricPoint.VertexOffset>>2]=e.vertexOffset,this.u32[t+n.CommandDrawMetricPoint.VertexCount>>2]=e.vertexCount,this.f32[t+n.CommandDrawMetricPoint.FloorElevation>>2]=e.floorElevation,this.f32.set(e.color,t+n.CommandDrawMetricPoint.ColorR>>2),this.f32.set(e.spriteCoords,t+n.CommandDrawMetricPoint.Sprite0X>>2),this.commitCommand(n.CommandDrawMetricPoint._Size),!0)}writeDrawCircleMarker(e){const t=this.beginCommand(n.CommandType.DrawCircleMarker,n.CommandDrawCircleMarker._Size,e);return t<0?!1:(this.u32[t+n.CommandDrawCircleMarker.VertexOffset>>2]=e.vertexOffset,this.u32[t+n.CommandDrawCircleMarker.VertexCount>>2]=e.vertexCount,this.f32.set(e.color,t+n.CommandDrawCircleMarker.ColorR>>2),this.f32[t+n.CommandDrawCircleMarker.Width>>2]=e.width,this.commitCommand(n.CommandDrawCircleMarker._Size),!0)}setLabelingDepthTestDisabled(e){const t=this.u32[n.FrameHeader.Flags>>2];this.u32[n.FrameHeader.Flags>>2]=e?t|n.FrameFlags.LabelingDepthTestDisabled:t&~n.FrameFlags.LabelingDepthTestDisabled}writeDrawLabelLine(e){const t=this.beginCommand(n.CommandType.DrawLabelLine,n.CommandDrawLabelLine._Size,e);return t<0?!1:(this.u32[t+n.CommandDrawLabelLine.VertexOffset>>2]=e.vertexOffset,this.u32[t+n.CommandDrawLabelLine.VertexCount>>2]=e.vertexCount,this.f32[t+n.CommandDrawLabelLine.Opacity>>2]=e.opacity,this.f32[t+n.CommandDrawLabelLine.Scale>>2]=e.scale,this.f32[t+n.CommandDrawLabelLine.Gamma>>2]=e.gamma,this.f32[t+n.CommandDrawLabelLine.HaloBuffer>>2]=e.haloBuffer,this.f32[t+n.CommandDrawLabelLine.FillBuffer>>2]=e.fillBuffer,this.f32[t+n.CommandDrawLabelLine.TileToPixelRatio>>2]=e.tileToPixelRatio,this.f32[t+n.CommandDrawLabelLine.StyleZoom>>2]=e.styleZoom,this.u32[t+n.CommandDrawLabelLine.Flags>>2]=e.hasHalo?n.LabelPointFlags.HasHalo:0,this.f32.set(e.haloColor,t+n.CommandDrawLabelLine.HaloColorR>>2),this.f32.set(e.fillColor,t+n.CommandDrawLabelLine.FillColorR>>2),this.commitCommand(n.CommandDrawLabelLine._Size),!0)}writeLabelPointMaterial(e){const t=this.beginMaterial(n.MaterialKind.LabelPoint,n.MaterialLabelPoint._Size,0);return t<0?-1:(this.u32[t+n.MaterialLabelPoint.TextureId>>2]=e.textureId,this.commitMaterial(n.MaterialLabelPoint._Size))}writeLineOneWayMaterial(e){const t=this.beginMaterial(n.MaterialKind.LineOneWay,n.MaterialLineOneWay._Size,0);return t<0?-1:(this.f32.set(e.color,t+n.MaterialLineOneWay.ColorR>>2),this.f32[t+n.MaterialLineOneWay.Width>>2]=e.width,this.f32[t+n.MaterialLineOneWay.Length>>2]=e.length,this.f32[t+n.MaterialLineOneWay.TipWidth>>2]=e.tipWidth,this.f32[t+n.MaterialLineOneWay.TipHeight>>2]=e.tipHeight,this.commitMaterial(n.MaterialLineOneWay._Size))}writeLineArrowMaterial(e){const t=this.beginMaterial(n.MaterialKind.LineArrow,n.MaterialLineArrow._Size,0);return t<0?-1:(this.f32.set(e.color,t+n.MaterialLineArrow.ColorR>>2),this.f32.set(e.borderColor,t+n.MaterialLineArrow.BorderColorR>>2),this.f32[t+n.MaterialLineArrow.LineWidth>>2]=e.lineWidth,this.f32[t+n.MaterialLineArrow.StrokeWidth>>2]=e.strokeWidth,this.f32[t+n.MaterialLineArrow.TipWidth>>2]=e.tipWidth,this.f32[t+n.MaterialLineArrow.TipHeight>>2]=e.tipHeight,this.f32[t+n.MaterialLineArrow.RoundingRadius>>2]=e.roundingRadius,this.commitMaterial(n.MaterialLineArrow._Size))}writeLineStripeMaterial(e){const t=this.beginMaterial(n.MaterialKind.LineStripe,n.MaterialLineStripe._Size,e.gapTurnsOnly?n.MaterialFlags.LineGapTurnsOnly:0);return t<0?-1:(this.f32.set(e.dashColor,t+n.MaterialLineStripe.DashColorR>>2),this.f32.set(e.spaceColor,t+n.MaterialLineStripe.SpaceColorR>>2),this.f32.set(e.borderColor,t+n.MaterialLineStripe.BorderColorR>>2),this.f32[t+n.MaterialLineStripe.DashLength>>2]=e.dashLength,this.f32[t+n.MaterialLineStripe.SpaceLength>>2]=e.spaceLength,this.commitMaterial(n.MaterialLineStripe._Size))}writeLinePatternMaterial(e){const t=this.beginMaterial(n.MaterialKind.LinePattern,n.MaterialLinePattern._Size,0);return t<0?-1:(this.f32.set(e.color,t+n.MaterialLinePattern.ColorR>>2),this.u32[t+n.MaterialLinePattern.PatternType>>2]=e.patternType,this.f32.set(e.patternParams,t+n.MaterialLinePattern.ParamX>>2),this.commitMaterial(n.MaterialLinePattern._Size))}writeDrawDemElevation(e){return this.writeDemMeshCommand(n.CommandType.DrawDemElevation,e)}writeDrawDemTerrain(e){return this.writeDemMeshCommand(n.CommandType.DrawDemTerrain,e)}writeDrawMapMesh(e){const t=this.beginCommand(n.CommandType.DrawMapMesh,n.CommandDrawMapMesh._Size,e);return t<0?!1:(this.u32[t+n.CommandDrawMapMesh.VertexOffset>>2]=e.vertexOffset,this.u32[t+n.CommandDrawMapMesh.VertexCount>>2]=e.vertexCount,this.f32[t+n.CommandDrawMapMesh.HeightFactor>>2]=e.heightFactor,this.u32[t+n.CommandDrawMapMesh.Tier>>2]=e.tier,this.u32[t+n.CommandDrawMapMesh.Flags>>2]=e.absZ?n.MapMeshFlags.AbsZ:0,this.commitCommand(n.CommandDrawMapMesh._Size),!0)}writeDrawMesh(e){const t=this.beginCommand(n.CommandType.DrawMesh,n.CommandDrawMesh._Size,e);return t<0?!1:(this.u32[t+n.CommandDrawMesh.VertexOffset>>2]=e.vertexOffset,this.u32[t+n.CommandDrawMesh.VertexCount>>2]=e.vertexCount,this.f32[t+n.CommandDrawMesh.HeightFactor>>2]=e.heightFactor,this.f32[t+n.CommandDrawMesh.FloorElevation>>2]=e.floorElevation,this.u32[t+n.CommandDrawMesh.Mode>>2]=e.mode,this.u32[t+n.CommandDrawMesh.Flags>>2]=(e.absZ?n.MeshFlags.AbsZ:0)|(e.labeling?n.MeshFlags.Labeling:0),this.commitCommand(n.CommandDrawMesh._Size),!0)}writeDrawPolygon3d(e){var i,r;const t=this.beginCommand(n.CommandType.DrawPolygon3d,n.CommandDrawPolygon3d._Size,e);return t<0?!1:(this.u32[t+n.CommandDrawPolygon3d.VertexOffset>>2]=e.vertexOffset,this.u32[t+n.CommandDrawPolygon3d.VertexCount>>2]=e.vertexCount,this.f32[t+n.CommandDrawPolygon3d.HeightFactor>>2]=e.heightFactor,this.f32[t+n.CommandDrawPolygon3d.FloorElevation>>2]=e.floorElevation,this.u32[t+n.CommandDrawPolygon3d.IsHole>>2]=e.isHole,this.u32[t+n.CommandDrawPolygon3d.IsVertexColor>>2]=e.isVertexColor,this.f32[t+n.CommandDrawPolygon3d.NearCameraFade>>2]=e.nearCameraFade,this.u32[t+n.CommandDrawPolygon3d.RunSeq>>2]=e.runSeq,this.f32[t+n.CommandDrawPolygon3d.FloorStackOffset>>2]=(i=e.floorStackOffset)!=null?i:0,this.f32[t+n.CommandDrawPolygon3d.FloorStackTotal>>2]=(r=e.floorStackTotal)!=null?r:1,this.commitCommand(n.CommandDrawPolygon3d._Size),!0)}writeDrawGltfModel(e){var r,o,a,l,c,d,u,h,_,f,m,v,g,p;const t=this.beginCommand(n.CommandType.DrawGltfModel,n.CommandDrawGltfModel._Size,e);if(t<0)return!1;this.u32[t+n.CommandDrawGltfModel.IndexBuffer>>2]=e.indexBuffer,this.u32[t+n.CommandDrawGltfModel.IndexCount>>2]=e.indexCount,this.u32[t+n.CommandDrawGltfModel.InstanceBuffer>>2]=e.instanceBuffer,this.u32[t+n.CommandDrawGltfModel.InstanceOffset>>2]=e.instanceOffset,this.u32[t+n.CommandDrawGltfModel.InstanceCount>>2]=e.instanceCount,this.u32[t+n.CommandDrawGltfModel.Flags>>2]=(e.indexU32?n.GltfModelFlags.IndexU32:0)|(e.useAbsZ?n.GltfModelFlags.UseAbsZ:0)|(e.extToRelief?n.GltfModelFlags.ExtToRelief:0)|(e.collapseHeight?n.GltfModelFlags.CollapseHeight:0)|(e.reliefFoundation?n.GltfModelFlags.ReliefFoundation:0)|(e.surfaceUseAbsZ?n.GltfModelFlags.SurfaceUseAbsZ:0),this.f32[t+n.CommandDrawGltfModel.NearCameraFade>>2]=e.nearCameraFade,Un(this.f32,t+n.CommandDrawGltfModel.LightDirX>>2,e.lightDir,e.lightUse?1:0),Un(this.f32,t+n.CommandDrawGltfModel.LightColorR>>2,e.lightColor,(r=e.lightColor[3])!=null?r:0),Un(this.f32,t+n.CommandDrawGltfModel.LightAmbientR>>2,e.lightAmbient,(o=e.lightAmbient[3])!=null?o:0),this.u32[t+n.CommandDrawGltfModel.DemPos>>2]=e.demPos;const i=t+n.CommandDrawGltfModel.AnchorX>>2;return this.f32[i]=(a=e.demAnchor[0])!=null?a:0,this.f32[i+1]=(l=e.demAnchor[1])!=null?l:0,this.f32[i+2]=(c=e.demAnchor[2])!=null?c:0,this.f32[i+3]=(d=e.demAxisStart[0])!=null?d:0,this.f32[i+4]=(u=e.demAxisStart[1])!=null?u:0,this.f32[i+5]=(h=e.demAxisStart[2])!=null?h:0,this.f32[i+6]=(_=e.demAxisEnd[0])!=null?_:0,this.f32[i+7]=(f=e.demAxisEnd[1])!=null?f:0,this.f32[i+8]=(m=e.demAxisEnd[2])!=null?m:0,this.f32[t+n.CommandDrawGltfModel.SurfaceRelZ>>2]=e.surfaceRelZ,this.f32[t+n.CommandDrawGltfModel.SurfaceAbsZ>>2]=e.surfaceAbsZ,this.f32[t+n.CommandDrawGltfModel.ScaleX>>2]=(v=e.scaleFactor[0])!=null?v:1,this.f32[t+n.CommandDrawGltfModel.ScaleY>>2]=(g=e.scaleFactor[1])!=null?g:1,this.f32[t+n.CommandDrawGltfModel.ScaleZ>>2]=(p=e.scaleFactor[2])!=null?p:1,this.commitCommand(n.CommandDrawGltfModel._Size),!0}writeGltfMaterial(e){const t=this.beginMaterial(n.MaterialKind.GltfModel,n.MaterialGltf._Size,0);return t<0?-1:(this.f32[t+n.MaterialGltf.ColorR>>2]=e.color[0],this.f32[t+n.MaterialGltf.ColorG>>2]=e.color[1],this.f32[t+n.MaterialGltf.ColorB>>2]=e.color[2],this.f32[t+n.MaterialGltf.ColorA>>2]=e.color[3],this.u32[t+n.MaterialGltf.ColorTextureId>>2]=e.colorTextureId,this.u32[t+n.MaterialGltf.AoTextureId>>2]=e.aoTextureId,this.u32[t+n.MaterialGltf.PbrTextureId>>2]=e.pbrTextureId,this.f32[t+n.MaterialGltf.Metallic>>2]=e.metallic,this.f32[t+n.MaterialGltf.Roughness>>2]=e.roughness,this.u32[t+n.MaterialGltf.LightingModel>>2]=e.lightingModel,this.commitMaterial(n.MaterialGltf._Size))}writeDrawPolygon3dTexture(e){const t=this.beginCommand(n.CommandType.DrawPolygon3dTexture,n.CommandDrawPolygon3dTexture._Size,e);return t<0?!1:(this.u32[t+n.CommandDrawPolygon3dTexture.VertexOffset>>2]=e.vertexOffset,this.u32[t+n.CommandDrawPolygon3dTexture.VertexCount>>2]=e.vertexCount,this.f32[t+n.CommandDrawPolygon3dTexture.HeightFactor>>2]=e.heightFactor,this.f32[t+n.CommandDrawPolygon3dTexture.FloorElevation>>2]=e.floorElevation,this.f32[t+n.CommandDrawPolygon3dTexture.NearCameraFade>>2]=e.nearCameraFade,this.commitCommand(n.CommandDrawPolygon3dTexture._Size),!0)}writeWallTextureMaterial(e){const t=this.beginMaterial(n.MaterialKind.WallTexture,n.MaterialWallTexture._Size,0);return t<0?-1:(this.u32[t+n.MaterialWallTexture.TextureId>>2]=e.textureId,this.f32[t+n.MaterialWallTexture.WallPadL>>2]=e.wallPadding[0],this.f32[t+n.MaterialWallTexture.WallPadT>>2]=e.wallPadding[1],this.f32[t+n.MaterialWallTexture.WallPadR>>2]=e.wallPadding[2],this.f32[t+n.MaterialWallTexture.WallPadB>>2]=e.wallPadding[3],this.f32[t+n.MaterialWallTexture.TexPadL>>2]=e.texturePadding[0],this.f32[t+n.MaterialWallTexture.TexPadT>>2]=e.texturePadding[1],this.f32[t+n.MaterialWallTexture.TexPadR>>2]=e.texturePadding[2],this.f32[t+n.MaterialWallTexture.TexPadB>>2]=e.texturePadding[3],this.f32[t+n.MaterialWallTexture.PartCountX>>2]=e.partCount[0],this.f32[t+n.MaterialWallTexture.PartCountY>>2]=e.partCount[1],this.f32[t+n.MaterialWallTexture.MaxIntervalX>>2]=e.maxInterval[0],this.f32[t+n.MaterialWallTexture.MaxIntervalY>>2]=e.maxInterval[1],this.f32[t+n.MaterialWallTexture.SliceSizeX>>2]=e.sliceSize[0],this.f32[t+n.MaterialWallTexture.SliceSizeY>>2]=e.sliceSize[1],this.i32[t+n.MaterialWallTexture.LayoutModeH>>2]=e.layoutMode[0],this.i32[t+n.MaterialWallTexture.LayoutModeV>>2]=e.layoutMode[1],this.commitMaterial(n.MaterialWallTexture._Size))}writeLightBlock(e,t){const i=this.f32;Un(i,e,t.dir1Direction,t.useLight?1:0),i.set(t.dir1Color,e+4),Un(i,e+8,t.dir2Direction,0),i.set(t.dir2Color,e+12),i.set(t.ambientColor,e+16)}writeDemMeshCommand(e,t){const i=this.beginCommand(e,n.CommandDrawDemMesh._Size,t);return i<0?!1:(this.u32[i+n.CommandDrawDemMesh.VertexOffset>>2]=t.vertexOffset,this.u32[i+n.CommandDrawDemMesh.VertexCount>>2]=t.vertexCount,this.commitCommand(n.CommandDrawDemMesh._Size),!0)}beginCommand(e,t,i){var o;if(this.writeOffset+t>this._buffer.byteLength)return-1;this.u32[n.FrameHeader.CommandCount>>2]===0&&(this.u32[n.FrameHeader.CommandOffset>>2]=this.writeOffset);const r=this.writeOffset;return this.u32[r+n.CommandCommon.Type>>2]=e,this.u32[r+n.CommandCommon.MaterialId>>2]=(o=i.materialId)!=null?o:0,this.u32[r+n.CommandCommon.VertexBuffer>>2]=i.vertexBuffer,this.i32[r+n.CommandCommon.SourceId>>2]=i.sourceId,n.writeTileCoord(this.i32,r+n.CommandCommon.TileX>>2,i.tileX),n.writeTileCoord(this.i32,r+n.CommandCommon.TileY>>2,i.tileY),n.writeTileCoord(this.i32,r+n.CommandCommon.TileZ>>2,i.tileZ),this.u32[r+n.CommandCommon.Flags>>2]=(i.hasEcef?n.CommandFlags.HasEcef:0)|(i.castShadows?n.CommandFlags.CastShadows:0)|(i.receiveShadows?n.CommandFlags.ReceiveShadows:0)|(i.castOnly?n.CommandFlags.CastOnly:0)|(i.identifyOnly?n.CommandFlags.IdentifyOnly:0)|(i.useLight?n.CommandFlags.UseLight:0)|(i.depthTest?n.CommandFlags.DepthTest:0)|(i.depthGreater?n.CommandFlags.DepthGreater:0)|(i.tier!==void 0?i.tier+n.COMMAND_TIER_BIAS<<n.COMMAND_TIER_SHIFT:0),r}commitCommand(e){this.writeOffset+=e,this.u32[n.FrameHeader.CommandCount>>2]++}beginMaterial(e,t,i){if(this.writeOffset+t>this._buffer.byteLength)return-1;const r=this.u32[n.FrameHeader.MaterialCount>>2];r===0&&(this.u32[n.FrameHeader.MaterialOffset>>2]=this.writeOffset);const o=this.writeOffset;return this.u32[o+n.MaterialCmd.Id>>2]=r,this.u32[o+n.MaterialCmd.Kind>>2]=e,this.u32[o+n.MaterialCmd.ByteSize>>2]=t,this.u32[o+n.MaterialCmd.Flags>>2]=i,o}commitMaterial(e){const t=this.u32[n.FrameHeader.MaterialCount>>2];return this.writeOffset+=e,this.u32[n.FrameHeader.MaterialCount>>2]=t+1,t}}const xT=2;class bT{constructor(e){this.modules=e,this.idByImage=new Map,this.readyByImage=new Map,this.failedAttempts=new Map}getReadyTexture(e,t){const i=this.readyByImage.get(e);if(i)return i;if(this.idByImage.has(e))return;const r=n.uniqId();this.idByImage.set(e,r),this.load(e,r,t)}destroy(){var t;const e=Array.from(this.idByImage.values());e.length>0&&((t=this.modules.sunda.ledger)==null||t.deleteTextures(e)),this.idByImage.clear(),this.readyByImage.clear(),this.failedAttempts.clear()}load(e,t,i){return q(this,null,function*(){var r,o,a;try{const l=(r=i.icons[e])==null?void 0:r.url;if(!l)return;const c=n.getUrlForIconMapIcon(l,i,""),u=yield(yield fetch(c,{mode:"cors"})).blob(),h=yield createImageBitmap(u),{width:_,height:f}=h,m=mu(h,_,f);if(h.close(),!m)return;(o=this.modules.sunda.ledger)==null||o.uploadTexture(t,m,_,f),this.readyByImage.set(e,{id:t,width:_,height:f})}catch(l){console.warn(`[sunda] wall texture load failed: ${e}`,l);const c=((a=this.failedAttempts.get(e))!=null?a:0)+1;this.failedAttempts.set(e,c),c<=xT&&this.idByImage.delete(e)}})}}function ah(s){return s===n.DYNAMIC_STYLE_ID?1:-s}function lh(s,e){const{modules:t,state:i}=s,r=t.styleManager.getStyle(e.attributes.styleId),o=r==null?void 0:r.layersById[e.attributes.layerId],a=o&&mr(o,t,i);return a?{use:a.lightingMode!==n.ReservedLightingMode.none,shadow:a.lightConfig.shadowLightIndex!==-1}:{use:!1,shadow:!1}}function we(s,e,t,i,r,o){var l,c;const a=lh(s,t);return{vertexBuffer:r,vertexOffset:t.start,vertexCount:t.count,sourceId:(l=e.sourceId)!=null?l:-1,tileX:e.coords[0],tileY:e.coords[1],tileZ:e.coords[2],originOrder:ah(t.attributes.styleId),renderIndex:i.renderIndex,zoomLevel:t.tile.zoomLevel,groupIndex:(c=i.groupIndex)!=null?c:0,subRenderIndex:t.layerSettings.subRenderIndex||0,sequence:o,castShadows:i.castShadows!==!1&&a.shadow,receiveShadows:i.receiveShadows!==!1&&a.shadow,useLight:a.use}}function ch(s,e){var c,d,u,h,_,f,m,v,g,p;const t=s.originOrder-e.originOrder;if(t!==0)return t;const i=s.renderIndex-e.renderIndex;if(i!==0)return i;if(s.orderBy||e.orderBy){const x=Math.max((d=(c=s.orderBy)==null?void 0:c.length)!=null?d:0,(h=(u=e.orderBy)==null?void 0:u.length)!=null?h:0);for(let S=0;S<x;S++){const b=((f=(_=s.orderBy)==null?void 0:_[S])!=null?f:0)-((v=(m=e.orderBy)==null?void 0:m[S])!=null?v:0);if(b!==0)return b}}const r=s.groupIndex-e.groupIndex;if(r!==0)return r;const o=s.subRenderIndex-e.subRenderIndex;if(o!==0)return o;const a=((g=s.selected)!=null?g:0)-((p=e.selected)!=null?p:0);if(a!==0)return a;const l=s.zoomLevel-e.zoomLevel;return l!==0?l:s.sequence-e.sequence}function $e(s){return s.attributes}const ST=n.tileHeight/n.uint16ToTileCoords,yT=65535*32,ja=.75,TT=0,ET=1;function dh(){return typeof window!="undefined"?window.devicePixelRatio:1}function CT(s,e){return s.styleZoom<nh||s.pitch===rh&&!e.floorManager.hasActiveFloorOrMetro()&&s.styleState.immersiveRoadsOn!==!0||s.disableHidingPois}function IT(s){const e=(n.POINT_CENTER_SIZE-.5)/2,{size:t}=s;return[e/t[0],e/t[1]]}function an(s,e){return Mi(s,e)/ST}function Mi(s,e){const t=$e(e);return t.floorId?t.isFloorStack?s.floorManager.getFloorStackObjectElevation(t.floorId):s.floorManager.getFloorObjectElevation(t.floorId):0}function ms(s,e){var t,i;return e>=((t=s.minzoom)!=null?t:-1/0)&&e<((i=s.maxzoom)!=null?i:1/0)}function vs(s,e,t){var i;return!!e&&!s.floorManager.isVisibleFloorObject(e,String((i=t.style)==null?void 0:i.floorCulling))}function Qe(s,e){return n.makeBinderContext(s.styleZoom,s.pitch,s.styleState,e.attributes.tileData,!1,e.tile.dynamicObject)}function Xa(s){var r;const e=s.tile.dynamicObject,t=typeof(e==null?void 0:e.getResolvedHeight)=="function"?e.getResolvedHeight():void 0,i=t==null?void 0:t.relativeZ;return{hasSurface:i!==void 0,surfaceUseAbsZ:(t==null?void 0:t.absoluteZ)!==void 0,surfaceRelZNorm:i!==void 0?i/yT:0,surfaceAbsZ:(r=t==null?void 0:t.absoluteZ)!=null?r:0}}function uh(s,e,t,i){const r=s*e;return{scale:r,gamma:n.fonts.gamma/r,haloBuffer:i?(6-t/s)/8:ja}}function PT(s,e){return e===0?{fontSize:s.iconTextFontSize,color:s.iconTextColor,haloWidth:s.iconTextHaloWidth,haloColor:s.iconTextHaloColor}:e===2?{fontSize:s.textFontSize2,color:s.textColor2,haloWidth:s.textHaloWidth2,haloColor:s.textHaloColor2}:{fontSize:s.textFontSize,color:s.textColor,haloWidth:s.textHaloWidth,haloColor:s.textHaloColor}}function AT(s,e,t,i,r,o){var p,x,S,b,T,y,E;const{modules:a,state:l}=s;if(!ms(i,l.styleZoom))return null;const c=$e(t);if(vs(a,c.floorId,i))return null;const d=Bi(l,(p=c.animDirection)!=null?p:n.LabelingAnimation.none);if(d===0)return null;const u=a.assetManager.getSundaAtlasTextureId((x=c.atlasIndex)!=null?x:0);if(u===void 0)return null;const h=Qe(l,t);if(((S=i.style)==null?void 0:S.iconWidth)===void 0||n.resolveNumber(i.style.iconWidth,h,0)<=0)return null;const _=((b=i.style)==null?void 0:b.iconOpacity)!==void 0?n.resolveNumber(i.style.iconOpacity,h,1):1;h.isBehind=!0;const f=l.styleState.graphicsPreset==="light"?1:((T=i.style)==null?void 0:T.iconOpacity)!==void 0?n.resolveNumber(i.style.iconOpacity,h,1):1;h.isBehind=!1;const m=((y=i.style)==null?void 0:y.iconRotation)!==void 0?n.resolveNumber(i.style.iconRotation,h,0):0,v=Xa(t),g=l.globeMode?!0:((E=i.style)==null?void 0:E.elevation)!==void 0&&!!n.resolveNumber(i.style.elevation,h,0);return I({type:"pointSprite",materialKey:`pointSprite-${u}`,pointSpriteMaterial:{textureId:u},pointSprite:{opacityVisible:d*_,opacityHidden:d*f,rotationCos:Math.cos(m),rotationSin:Math.sin(m),heightFactor:a.buildingHeightAnimator.getDefaultBuildingHeight(),skipHeightFactor:g||v.hasSurface,floorElevation:an(a,t),styleScale:n.zoomToScale(l.styleZoom),dpi:n.zptPerInch*s.dpr,roundingFactor:l.stillness,surfaceUseAbsZ:v.surfaceUseAbsZ,surfaceRelZNorm:v.surfaceRelZNorm,surfaceAbsZ:v.surfaceAbsZ,labelTest:!!c.labelTest,identifyOpacity:l.iconIdentifyOpacity,halfPointSizeX:s.halfPointSize[0],halfPointSizeY:s.halfPointSize[1],hasEcef:wi(l,e,a.map.getFeatureFlag("globeOff"))}},we(s,e,t,i,r,o))}function LT(s,e,t,i,r,o){var b,T,y,E;const{modules:a,state:l}=s;if(!ms(i,l.styleZoom))return null;const c=$e(t),d=Bi(l,(b=c.animDirection)!=null?b:n.LabelingAnimation.none);if(d===0)return null;const u=a.assetManager.getSundaFontTextureId((T=c.fontName)!=null?T:"",(y=c.range)!=null?y:0);if(u===void 0)return null;const h=(E=i.style)!=null?E:{};if(h.textFontSize===void 0||h.textColor===void 0)return null;const _=Qe(l,t),f=n.resolveNumber(h.textFontSize,_,0)/n.fonts.baseSize;if(f<=0)return null;const m=h.textHaloWidth!==void 0?n.resolveNumber(h.textHaloWidth,_,0):0,v=m>0&&h.textHaloColor!==void 0,g=uh(f,s.dpr,m,v),p=n.getColorForShaders(n.resolveColor(h.textColor,_)),x=v?n.getColorForShaders(n.resolveColor(h.textHaloColor,_)):[0,0,0,0],S=n.uint16ToTileCoords/(n.tileSizeZpt*Re(2,l.zoom-t.tile.zoomLevel)*s.dpr);return V(I({type:"labelLine",materialKey:`labelPoint-${u}`,labelPointMaterial:{textureId:u},labelLine:{opacity:d,scale:g.scale,gamma:g.gamma,haloBuffer:g.haloBuffer,fillBuffer:ja,tileToPixelRatio:S,styleZoom:l.styleZoom,hasHalo:v,haloColor:x,fillColor:p}},we(s,e,t,i,r,o)),{subRenderIndex:TT})}function RT(s,e,t,i,r,o){var F,L,D,B,Q,Z,$,J,ge;const{modules:a,state:l}=s;if(!ms(i,l.styleZoom))return null;const c=$e(t);if(vs(a,c.floorId,i))return null;const d=Bi(l,(F=c.animDirection)!=null?F:n.LabelingAnimation.none);if(d===0)return null;const u=a.assetManager.getSundaFontTextureId((L=c.fontName)!=null?L:"",(D=c.range)!=null?D:0);if(u===void 0)return null;const h=Qe(l,t),_=(B=i.style)!=null?B:{},f=(Q=c.labelIndex)!=null?Q:1,m=PT(_,f),v=(Z=m.fontSize)!=null?Z:_.textFontSize;if(v===void 0||m.color===void 0)return null;const g=n.resolveNumber(v,h,0)/n.fonts.baseSize;if(g<=0)return null;const p=m.haloWidth!==void 0?n.resolveNumber(m.haloWidth,h,0):0,x=p>0&&m.haloColor!==void 0,S=uh(g,s.dpr,p,x),b=n.getColorForShaders(n.resolveColor(m.color,h)),T=x?n.getColorForShaders(n.resolveColor(m.haloColor,h)):[0,0,0,0];h.isBehind=!0;const y=n.getColorForShaders(n.resolveColor(m.color,h)),E=x?n.getColorForShaders(n.resolveColor(m.haloColor,h)):[0,0,0,0];h.isBehind=!1;const P=Xa(t),A=l.globeMode?!0:(($=i.style)==null?void 0:$.elevation)!==void 0&&!!n.resolveNumber(i.style.elevation,h,0);return V(I({type:"labelPoint",materialKey:`labelPoint-${u}`,labelPointMaterial:{textureId:u},labelPoint:{opacity:d,heightFactor:a.buildingHeightAnimator.getDefaultBuildingHeight(),skipHeightFactor:A||P.hasSurface,floorElevation:an(a,t),surfaceUseAbsZ:P.surfaceUseAbsZ,surfaceRelZNorm:P.surfaceRelZNorm,surfaceAbsZ:P.surfaceAbsZ,scale:S.scale,offsetX:((J=c.offsetX)!=null?J:0)*s.dpr,offsetY:((ge=c.offsetY)!=null?ge:0)*s.dpr,gamma:S.gamma,haloBuffer:S.haloBuffer,fillBuffer:ja,hasHalo:x,haloColor:T,fillColor:b,haloHiddenColor:E,fillHiddenColor:y,labelIndexIcon:f===0,halfPointSizeX:s.halfPointSize[0],halfPointSizeY:s.halfPointSize[1],hasEcef:wi(l,e,a.map.getFeatureFlag("globeOff"))}},we(s,e,t,i,r,o)),{subRenderIndex:ET})}function FT(s,e,t,i,r,o){var u,h;const{modules:a,state:l}=s;if(s.labelingDepthTestDisabled||!ms(i,l.styleZoom))return null;const c=$e(t);if(vs(a,c.floorId,i))return null;const d=Xa(t);return I({type:"pointAnchor",materialKey:"",pointAnchor:{offsetX:((u=c.offsetX)!=null?u:0)*s.dpr,offsetY:((h=c.offsetY)!=null?h:0)*s.dpr,floorElevation:an(a,t),surfaceUseAbsZ:d.surfaceUseAbsZ,surfaceRelZNorm:d.surfaceRelZNorm,surfaceAbsZ:d.surfaceAbsZ,hasEcef:wi(l,e,a.map.getFeatureFlag("globeOff"))}},we(s,e,t,i,r,o))}function DT(s,e,t,i,r,o){var S,b;const{modules:a,state:l}=s,c=(S=i.style)!=null?S:{};if(c.iconImage===void 0||c.color===void 0)return null;const d=$e(t);if(vs(a,d.floorId,i))return null;const u=Qe(l,t),h=n.resolveString(c.iconImage,u),_=a.styleManager.getStyle(t.attributes.styleId),f=(b=_==null?void 0:_.rasterSets.byKey[n.getStaticTextureRasterSetKey(h)])==null?void 0:b.rasters;if(!f)return null;const m=c.width!==void 0?n.resolveNumber(c.width,u,0):0,v=c.height!==void 0?n.resolveNumber(c.height,u,0):0,g=n.selectMetricPointRaster(f,m,v,s.dpr);if(!g)return null;const p=a.assetManager.getSundaAtlasTextureId(g.raster.atlasIndex);if(p===void 0)return null;const x=n.getColorForShaders(n.resolveColor(c.color,u));return x[3]<=0?null:I({type:"metricPoint",materialKey:`pointSprite-${p}`,pointSpriteMaterial:{textureId:p},metricPoint:{color:x,spriteCoords:g.spriteCoords,floorElevation:an(a,t)}},we(s,e,t,i,r,o))}function zT(s,e,t,i,r,o){var g;const{state:a}=s,l=(g=i.style)!=null?g:{},c=Qe(a,t),d=l.width!==void 0?n.resolveNumber(l.width,c,0):0,u=l.strokeWidth!==void 0?n.resolveNumber(l.strokeWidth,c,0):0,h=l.strokeWidth2!==void 0?n.resolveNumber(l.strokeWidth2,c,0):0;if(t.layerSettings.identify){const p=d+u*2+h*2;return p<=0?null:I({type:"circleMarker",materialKey:"",circleMarker:{color:[0,0,0,0],width:p*s.dpr}},we(s,e,t,i,r,o))}const _=t.layerSettings.subRenderIndex||0;let f,m;if(_===2){if(d===0)return null;f=d,m=l.color}else if(_===1){if(u===0)return null;f=d+u*2,m=l.strokeColor}else{if(h===0)return null;f=d+u*2+h*2,m=l.strokeColor2}if(m===void 0)return null;const v=n.getColorForShaders(n.resolveColor(m,c));return v[3]<=0?null:I({type:"circleMarker",materialKey:"",circleMarker:{color:v,width:f*s.dpr}},we(s,e,t,i,r,o))}const $a=new Float64Array([0,0,0]),BT=new Float64Array([0,1,0]);function gs(s,e){return{useLight:s,dir1Direction:e.dir1Direction,dir1Color:e.dir1ColorIntensity,dir2Direction:e.dir2Direction,dir2Color:e.dir2ColorIntensity,ambientColor:e.ambientColorIntensity}}function hh(){return gs(!1,n.DEFAULT_LIGHTING_MODES[n.ReservedLightingMode.none])}class OT{constructor(e,t){this.modules=e,this.state=t,this.sundaMapMeshVp=new Float64Array(16),this.sundaCenterVec4=new Float64Array(4),this.sundaVpAtCenter=new Float64Array(4),this.sundaStarsProj=new Float64Array(16),this.sundaStarsMatrix=new Float64Array(16),this.sundaStarsCamDir=new Float64Array(3),this.sundaHaloStops=new Float64Array(4),this.sundaHaloViewport=new Float64Array(4)}writeGlobeState(e){const t=this.modules.camera,i=!!this.state.globeMode,r=this.state.center,o=n.Mercator.toGeo(r),a=[n.degToRad(o[0]),Math.log(Math.tan(Math.PI/4+n.degToRad(o[1])/2))];this.sundaCenterVec4[0]=r[0],this.sundaCenterVec4[1]=r[1],this.sundaCenterVec4[2]=0,this.sundaCenterVec4[3]=1,n.transformMat4(this.sundaVpAtCenter,this.sundaCenterVec4,this.modules.camera.viewProjectionMatrix);const l=n.ECEF_EARTH_RADIUS*n.MAP_POINTS_IN_METER,c=(n.zoomToHeight(this.state.zoom,this.state.size)+l)/l,d=n.degToRad(o[0]),u=n.degToRad(o[1]),h=Math.cos(u),_=[Math.sin(d)*h*c,Math.sin(u)*c,Math.cos(d)*h*c];e.setGlobeState({ecefViewProjection:t.ecefMvpMatrix,crossfade:i?t.globeRatio:0,globeMode:i,cameraMercator:a,vpAtCenter:this.sundaVpAtCenter,cameraEcef:_})}writeStarsState(e){if(!this.state.globeMode)return;const t=this.modules.styleManager.getStyle(this.state.handyStyleId),i=t==null?void 0:t.environment;let r=1;if(i){const h=n.makeBinderContext(this.state.styleZoom,this.state.pitch,this.state.styleState,[]);r=n.resolveNumber(i.style.starsIntensity,h,1)}if(r<=0)return;const o=this.state.size,a=Math.max(o[0],o[1]),l=o[0]/a,c=o[1]/a;n.ortho(this.sundaStarsProj,-l/2,l/2,-c/2,c/2,.001,1);const d=n.Mercator.toGeo(this.state.center),u=n.set(this.sundaStarsCamDir,0,0,1);n.rotateX(u,u,$a,n.degToRad(d[1])),n.rotateY(u,u,$a,n.degToRad(d[0])),n.lookAt(this.sundaStarsMatrix,$a,u,BT),n.multiply(this.sundaStarsMatrix,this.sundaStarsProj,this.sundaStarsMatrix),e.setStarsState({starsMatrix:this.sundaStarsMatrix,intensity:r})}writeGlobeHaloState(e){if(!this.state.globeMode)return;const t=this.modules.styleManager.getStyle(this.state.handyStyleId),i=t==null?void 0:t.environment;if(!i)return;const r=n.makeBinderContext(this.state.styleZoom,this.state.pitch,this.state.styleState,[]),o=n.getColorForShaders(n.resolveColor(i.style.fogColor,r)),a=dh(),l=this.modules.camera.ecef.pixelRadius*a,c=this.state.size,d=c[0]*a,u=c[1]*a,{left:h,right:_,top:f,bottom:m}=this.state.padding;this.sundaHaloViewport[0]=d,this.sundaHaloViewport[1]=u,this.sundaHaloViewport[2]=(h-_)*a/2,this.sundaHaloViewport[3]=(m-f)*a/2;const v=this.modules.environmentManager.globHaloStops;for(let g=0;g<4;g++)this.sundaHaloStops[g]=(l+v[g]*a)/u;e.setGlobeHaloState({haloColor:o,radiusStops:this.sundaHaloStops,viewport:this.sundaHaloViewport,expFactor:this.modules.environmentManager.globeHaloExpFactor,backgroundColor:n.getColorForShaders(n.resolveColor(t.background.color,r))})}writeFogState(e){if(this.state.globeMode||!this.modules.environmentManager.isFogEnabled())return;let t=[1,1,1,1],i=[1,1,1,1];const r=this.modules.styleManager.getStyle(this.state.handyStyleId);if(r){const c=n.makeBinderContext(this.state.styleZoom,this.state.pitch,this.state.styleState,[]);t=n.getColorForShaders(n.resolveColor(r.environment.style.skyColor,c)),i=n.getColorForShaders(n.resolveColor(r.environment.style.fogColor,c))}const o=!this.state.demMode||!this.state.elevation||Number.isNaN(this.state.elevation)?0:this.state.elevation*n.MAP_POINTS_IN_METER,a=Math.min(1+Math.max(o/n.zoomToHeight(this.state.zoom,this.state.size),0),$l),l=this.modules.environmentManager;e.setFogState({fogColor:i,skyColor:t,limits:l.fogLimits,horizonBlend:l.fogHorizonBlend,horizonLevel:l.fogHorizonLevel,horizonPad:this.state.cameraConfig.fogHorizonPadFactor*a,fogDistance:this.modules.camera.fogDistance})}writeSkyState(e){this.state.globeMode||!this.modules.environmentManager.isSkyEnabled()||e.setSkyState({viewTransposed:this.modules.camera.viewMatrixTranspose,projInverted:this.modules.camera.projectionMatrixInverse})}writeShadowState(e){const t=this.modules.shadowManager;t.shadowLightIndex<0||e.setShadowState({shadowViewProjection:t.shadowMatrix,clipToShadow:t.clipToShadowMatrix,mapParams:t.shadowMapParams,bias:t.bias,orthoAnisotropy:t.orthoAnisotropy,shadowLightIndex:t.shadowLightIndex})}writeDemState(e){var o,a;const t=this.modules.styleManager.getStyle(this.state.handyStyleId);let i=0;if(t!=null&&t.dem){const l=n.makeBinderContext(this.state.styleZoom,this.state.pitch,this.state.styleState,[]);i=n.clamp(n.resolveNumber(t.dem.style.shadingIntensity,l),0,1)}e.setDemState({demMode:this.state.demMode,demTextureSize:this.modules.demManager.getDemTextureSizePx(),demScale:this.state.elevationScale,centerElevation:(o=this.state.elevation)!=null?o:0,minElevation:(a=this.modules.demManager.getMinElevation())!=null?a:0,shadingIntensity:i,backgroundColor:n.getColorForShaders(this.modules.styleManager.getClearColor()),demTextureMatrix:this.modules.demManager.demTextureMatrix});const r=this.state.demMode?this.modules.demManager.getFlatMapTextures():[];e.setFlatLevels(r),e.setIdentifyFlatLevelMask(r.reduce((l,c,d)=>c.detailLevel===0?l|1<<d:l,0))}writeMapMeshState(e){const t=1-Math.cos(this.state.pitch);n.fromTranslationScale(this.sundaMapMeshVp,[0,t/fs,0],[1/Va,1/fs,1]),n.multiply(this.sundaMapMeshVp,this.sundaMapMeshVp,this.modules.camera.viewProjectionMatrix),e.setMapMeshState({vpMatrix:this.sundaMapMeshVp,scaleX:Va,scaleY:fs,texShift:t})}writeLightState(e){var o;const t=this.modules.styleManager.getStyle(this.state.handyStyleId);let i=n.ReservedLightingMode.none,r=n.DEFAULT_LIGHTING_MODES[n.ReservedLightingMode.none];t!=null&&t.light.lightingModesResolved&&(i=t.light.defaultLightMode,r=(o=t.light.lightingModesResolved[i])!=null?o:r),e.setLightState(gs(i!==n.ReservedLightingMode.none,r))}writeDemLightState(e){var r;const t=this.modules.styleManager.getStyle(this.state.handyStyleId),i=(r=t==null?void 0:t.light.lightingModesResolved)==null?void 0:r[n.DEM_LIGHTING_MODE];i?e.setDemLightState(gs(!0,i)):e.setDemLightState(hh())}writeDemDraws(e,t){for(const i of t)if(!this.writeDemMeshDraws(i,i.demChildren,r=>e.writeDrawDemElevation(r))||!this.writeDemMeshDraws(i,i.children,r=>e.writeDrawDemTerrain(V(I({},r),{castShadows:!0}))))return}writeDemMeshDraws(e,t,i){var r;for(const o of t){if(o.symbol!=="dem"||o.sink!=="mesh2")continue;const a=e.getSundaVertexBufferId(o.id);if(a===void 0)continue;if(!i({vertexBuffer:a,vertexOffset:o.start,vertexCount:o.count,sourceId:(r=e.sourceId)!=null?r:-1,tileX:e.coords[0],tileY:e.coords[1],tileZ:e.coords[2]}))return!1}return!0}}const qa=[0,0,0];function wT(s,e,t){const i=s.styleManager.getStyle(t.attributes.styleId),r=i==null?void 0:i.layersById[t.attributes.layerId],o=r&&mr(r,s,e);return o!=null&&o.lightConfig?gs(o.lightingMode!==n.ReservedLightingMode.none,o.lightConfig):null}class NT{constructor(e,t){this.modules=e,this.state=t,this.lightByLayer=new Map,this.scaleByLayer=new Map,this.fadeByLayer=new Map}reset(){this.lightByLayer.clear(),this.scaleByLayer.clear(),this.fadeByLayer.clear()}resolveLight(e){var r;const t=e.attributes.layerId;let i=this.lightByLayer.get(t);return i||(i=(r=wT(this.modules,this.state,e))!=null?r:hh(),this.lightByLayer.set(t,i)),i}resolveScaleFactor(e){const t=e.attributes.layerId;let i=this.scaleByLayer.get(t);if(!i){i=[1,1,1];const r=this.modules.styleManager.getStyle(e.attributes.styleId),o=r==null?void 0:r.layersById[t];(o==null?void 0:o.type)==="gltfModel"&&n.isInterpolateExpression(o.style.scale)&&n.getTriple(n.resolveExpression(o.style.scale,n.makeBinderContext(this.state.styleZoom,this.state.pitch,this.state.styleState,[],!1)),i),this.scaleByLayer.set(t,i)}return i}resolveNearCameraFade(e){const t=e.attributes.layerId,i=this.fadeByLayer.get(t);if(i!==void 0)return i;const r=this.modules.styleManager.getStyle(e.attributes.styleId),o=r==null?void 0:r.layersById[t],a=(o==null?void 0:o.type)==="gltfModel"&&o.style.nearCameraFade!==void 0?n.resolveNumber(o.style.nearCameraFade,n.makeBinderContext(this.state.styleZoom,this.state.pitch,this.state.styleState,[],!1),0):0;return this.fadeByLayer.set(t,a),a}}function _h(s,e,t,i){var h,_;const r=t.sundaGltf,o=t.sundaInstance;if(!r||!o||!r.indexCount||!t.instanceCount)return null;const a=s.modules.styleManager.getStyle(t.attributes.styleId),l=a==null?void 0:a.layersById[t.attributes.layerId];if(!l)return null;const c=lh(s,t),d=!!t.layerSettings.shadow,u=d&&l.castShadows!==!1&&c.shadow;return d&&!u?null:{type:"gltf",materialKey:"",gltfSceneObject:t,gltf:r,gltfInstance:o,vertexBuffer:r.vertexBufferId,vertexOffset:0,vertexCount:0,sourceId:(h=e.sourceId)!=null?h:-1,tileX:e.coords[0],tileY:e.coords[1],tileZ:e.coords[2],originOrder:ah(t.attributes.styleId),renderIndex:l.renderIndex,zoomLevel:t.tile.zoomLevel,groupIndex:(_=l.groupIndex)!=null?_:0,subRenderIndex:t.layerSettings.subRenderIndex||0,sequence:i,castShadows:u,castOnly:d,receiveShadows:!d&&l.receiveShadows!==!1&&c.shadow,useLight:c.use,floorElevation:Mi(s.modules,t)}}function kT(s,e){var i,r,o;const t=new Map;for(const a of e)for(const l of a.children){const c=l.sundaGltf;if(l.symbol!=="gltfModel"||l.sink!=="instances"||!c||t.has(c.vertexBufferId))continue;const d=s.writeGltfMaterial({color:c.color,colorTextureId:(i=c.colorTextureId)!=null?i:0,aoTextureId:(r=c.aoTextureId)!=null?r:0,pbrTextureId:(o=c.pbrTextureId)!=null?o:0,metallic:c.metallic,roughness:c.roughness,lightingModel:c.lightingModel});if(d<0)return t;t.set(c.vertexBufferId,d)}return t}function UT(s,e,t,i,r,o){var g,p,x,S,b,T;const a=i.gltfSceneObject,l=i.gltf,c=i.gltfInstance,d=r.get(l.vertexBufferId);if(d===void 0)return null;const u=$e(a);let h=l.demPosition,_=(g=l.demAnchorBaked)!=null?g:qa;u.polygonDemAnchor&&u.hasFoundation&&(h=4,_=[(u.polygonDemAnchor[0]+n.tileCoordOffset)/n.maxUint16Value,(u.polygonDemAnchor[1]+n.tileCoordOffset)/n.maxUint16Value,0]);const f=a.renderingProperties,m=(f==null?void 0:f.gltfHasExplicitZ)===!1?!1:!!u.absZ,v=t.resolveLight(a);return s.writeDrawGltfModel({materialId:d,lightUse:v.useLight,lightDir:v.dir1Direction,lightColor:v.dir1Color,lightAmbient:v.ambientColor,demPos:h,demAnchor:_,demAxisStart:(p=l.demAxisBakedStart)!=null?p:qa,demAxisEnd:(x=l.demAxisBakedEnd)!=null?x:qa,useAbsZ:m,extToRelief:!!u.extToReliefNeeded,collapseHeight:!!u.collapseHeightNeeded,reliefFoundation:e.styleState.terrainEnabled===!0&&!!u.isFoundation,surfaceUseAbsZ:(f==null?void 0:f.surfaceAbsoluteZ)!==void 0,surfaceRelZ:((S=f==null?void 0:f.surfaceRelativeZ)!=null?S:0)+i.floorElevation,surfaceAbsZ:(b=f==null?void 0:f.surfaceAbsoluteZ)!=null?b:0,scaleFactor:t.resolveScaleFactor(a),vertexBuffer:l.vertexBufferId,indexBuffer:l.indexBufferId,indexCount:l.indexCount,indexU32:l.indexU32,instanceBuffer:c.bufferId,instanceOffset:c.offset,instanceCount:(T=a.instanceCount)!=null?T:0,nearCameraFade:t.resolveNearCameraFade(a),castShadows:i.castShadows,castOnly:i.castOnly,identifyOnly:o,receiveShadows:i.receiveShadows,useLight:i.useLight,sourceId:i.sourceId,tileX:i.tileX,tileY:i.tileY,tileZ:i.tileZ})}const fh=.01,MT=-1e-5,HT={oneWayLine:s=>s.stateBinder===Tn,arrow:s=>s.stateBinder===qe,pointSprite:s=>s.stateBinder===fi,labelPoint:s=>s.stateBinder===fi&&s.uniformSet==="fontFill",labelLine:s=>s.stateBinder===Tn&&s.uniformSet==="fontFill"&&!s.isOverlappedObject,circleMarker:s=>s.stateBinder===qe,extrusion:s=>s.stateBinder===So,extrusionTexture:s=>s.stateBinder===wc,lineExtrusion:s=>s.stateBinder===Pc,meshFill:s=>s.stateBinder===xo,meshInverse:s=>s.stateBinder===Sr};function GT(s){var i,r;const e=(r=(i=n.SUNDA_SINK_KINDS[s.symbol])==null?void 0:i[s.sink])!=null?r:null;if(e===null)return null;if(s.layerSettings.identify)return e;const t=HT[e];return t===void 0||t(s.layerSettings)?e:null}const VT=new Set(["polygon","line","dashedLine","patternedLine","oneWayLine","arrow","metricPoint"]);function Mn(s,e,t,i){const r=t.gpuState;if((r==null?void 0:r.depthTest)!==void 0){const o=r.depthTest&&r.depthFunc===n.DEPTH_FUNC.GREATER;return{depthTest:r.depthTest&&!o,depthGreater:o}}return{depthTest:i&&!!s.styleState._activeFloorIsMetro&&!!e.attributes.floorId,depthGreater:!1}}function mh(s,e){var i;const t=s.buildingHeightAnimator.getBuildingHeight((i=e.minzoom)!=null?i:0);return fh+(1-fh)*t}function vh(s,e,t){const i=$e(t);return i.floorId||i.isHole?1:mh(s,e)}function Ya(s,e,t){const i=$e(t);return i.floorId&&i.isFloorStack?s.floorManager.getFloorStackObjectHeight(i.floorId):i.isHole?1:mh(s,e)}function At(s,e,t,i){var c,d;const r=s.modules.styleManager.getStyle(e.attributes.styleId);let o;const a=t.groupId!==void 0?r==null?void 0:r.groupsById[t.groupId]:void 0;(c=a==null?void 0:a.orderBy)!=null&&c.length&&(o=a.orderBy.map(u=>n.resolveNumber(u,i,0)));const l=t.selectedIdx!==void 0?Number((d=e.attributes.tileData[t.selectedIdx])!=null?d:0):0;return{orderBy:o,selected:l}}function Hn(s,e,t,i){return wi(s,e,i)&&(t===n.LineGeometry.Solid12||t===n.LineGeometry.Solid16||t===n.LineGeometry.Shifted20||t===n.LineGeometry.Dashed28)?Zu(e):0}function ps(s,e){if(!e||e.factor<=0)return s;const t=s.value,i=e.color,r=e.factor;return{type:"color",value:[t[0]+(i[0]-t[0])*r,t[1]+(i[1]-t[1])*r,t[2]+(i[2]-t[2])*r,t[3]+(i[3]-t[3])*r]}}function gh(s){switch(s){case"repeat-with-stretch":return 1;case"stripe-top":return 2;case"repeat-with-max-interval":return 3;default:return 1}}function Lt(s,e,t){var r,o,a,l;if(!e.style||e.style.visibility==="hidden")return null;const i=xh(e,t);switch(s.symbol){case"polygon":return s.sink==="stroke"?e.style.strokeColor===void 0?null:Si(et(e.style.strokeColor,t,i),n.MaterialKind.LineColor):e.style.color===void 0?null:Si(et(e.style.color,t,i),n.MaterialKind.PolygonColorFill);case"line":case"shiftedLine":return e.style.color===void 0?null:s.sink==="patterned"||s.sink==="patterned3d"?WT(e,t):Si(et(e.style.color,t,i),n.MaterialKind.LineColor);case"dashedLine":{if(e.style.color===void 0)return null;const c=Rt(et(e.style.color,t)),d=e.style.gapColor!==void 0?Rt(et(e.style.gapColor,t)):[0,0,0,0],u=t.styleZoom,h=Re(2,n.getFractionalPart(u));t.styleZoom=Math.floor(u);const _=e.style.dashLength!==void 0?n.resolveNumber(e.style.dashLength,t,0)*h:0,f=e.style.gapLength!==void 0?n.resolveNumber(e.style.gapLength,t,0)*h:0;t.styleZoom=u;const m=!!e.style.gapTurnsOnly,v={dashColor:c,spaceColor:d,borderColor:[0,0,0,0],dashLength:_,spaceLength:f,gapTurnsOnly:m};return{key:[n.MaterialKind.LineStripe,...c,...d,_,f,m?1:0].join("|"),params:{kind:n.MaterialKind.LineStripe,color1:c},stripe:v}}case"oneWayLine":{const c=e.style;if(c.color===void 0||c.lineWidth===void 0||c.lineLength===void 0)return null;const d=Rt(et(c.color,t)),u={color:d,width:n.resolveNumber(c.lineWidth,t,0),length:n.resolveNumber(c.lineLength,t,0),tipWidth:n.resolveNumber((r=c.tipWidth)!=null?r:0,t,0),tipHeight:n.resolveNumber((o=c.tipHeight)!=null?o:0,t,0)};return u.width<=0||u.tipWidth<=0||d[3]===0?null:{key:[n.MaterialKind.LineOneWay,...d,u.width,u.length,u.tipWidth,u.tipHeight].join("|"),params:{kind:n.MaterialKind.LineOneWay,color1:d},oneWay:u}}case"arrow":{const c=e.style;if(c.color===void 0||c.lineWidth===void 0)return null;const d=Rt(et(c.color,t)),u=c.strokeColor!==void 0?Rt(et(c.strokeColor,t)):[0,0,0,0],h={color:d,borderColor:u,lineWidth:n.resolveNumber(c.lineWidth,t,0),strokeWidth:c.strokeWidth!==void 0?n.resolveNumber(c.strokeWidth,t,0):0,tipWidth:n.resolveNumber((a=c.tipWidth)!=null?a:0,t,0),tipHeight:n.resolveNumber((l=c.tipHeight)!=null?l:0,t,0),roundingRadius:c.roundingRadius!==void 0?n.resolveNumber(c.roundingRadius,t,0):0};return h.lineWidth<=0||h.tipWidth<=0||d[3]===0?null:{key:[n.MaterialKind.LineArrow,...d,...u,h.lineWidth,h.strokeWidth,h.tipWidth,h.tipHeight,h.roundingRadius].join("|"),params:{kind:n.MaterialKind.LineArrow,color1:d},arrow:h}}case"mapMesh":{if(e.style.color===void 0)return null;const c=et(e.style.color,t).value,d=[c[0]/255,c[1]/255,c[2]/255,c[3]/255];return{key:[n.MaterialKind.MapMeshSurface,...d].join("|"),params:{kind:n.MaterialKind.MapMeshSurface,color1:d}}}case"mesh":{if(s.sink==="fill")return ZT(s,e,t);if(s.sink!=="stroke")return null;const c=s.attributes.side,d=c===n.MeshFillSide.top?e.style.strokeColor:c===n.MeshFillSide.side?e.style.sideColor:c===n.MeshFillSide.bottom?e.style.bottomColor:void 0;return d===void 0?null:Si(et(d,t,i),n.MaterialKind.LineColor)}case"lineExtrusion":case"polygonExtrusion":{if(s.sink==="topStroke")return e.style.strokeColor===void 0?null:Si(et(e.style.strokeColor,t,i),n.MaterialKind.LineColor);if(s.sink==="sideStroke"){if(e.style.sideStrokeColor===void 0)return null;const d=n.resolveGradient(e.style.sideStrokeColor,t),u=d?ps(d.values[0],i):et(e.style.sideStrokeColor,t,i);return Si(u,n.MaterialKind.LineColor)}if(s.sink!=="topFill"&&e.style.sideColor!==void 0){const d=n.resolveGradient(e.style.sideColor,t);if(d&&d.values.length>=2&&d.steps.length>=2){const u=Rt(ps(d.values[0],i)),h=Rt(ps(d.values[1],i)),_=d.steps[0],f=d.steps[1];return{key:[n.MaterialKind.PolygonExtrusionGradient,...u,...h,_,f].join("|"),params:{kind:n.MaterialKind.PolygonExtrusionGradient,color1:u,color2:h,factorInMin:_,factorInMax:f}}}}const c=s.sink==="topFill"?e.style.topColor:e.style.sideColor;return c===void 0?null:Si(et(c,t,i),n.MaterialKind.PolygonExtrusionFill)}default:return null}}function ZT(s,e,t){var l;const i=e.style,r=s.attributes.side,o=r===n.MeshFillSide.top?(l=i.topColor)!=null?l:i.color:r===n.MeshFillSide.side?i.sideColor:r===n.MeshFillSide.bottom?i.bottomColor:void 0;if(o===void 0)return null;const a=n.resolveGradient(o,t);if(a&&a.values.length>=2&&a.steps.length>=2){const c=Rt(a.values[0]),d=Rt(a.values[1]),u=a.steps[0],h=a.steps[1];return{key:[n.MaterialKind.PolygonExtrusionGradient,...c,...d,u,h].join("|"),params:{kind:n.MaterialKind.PolygonExtrusionGradient,color1:c,color2:d,factorInMin:u,factorInMax:h}}}return Si(et(o,t),n.MaterialKind.PolygonExtrusionFill)}function WT(s,e){const t=s.style;if(t.color===void 0||t.width===void 0||t.pattern===void 0)return null;const i=n.resolveNumber(t.width,e,0);if(i===0)return null;const r=n.resolveExpression(t.pattern,e);if(!r||r[0]===n.LinePatternType.None)return null;const o=[0,0,0,0];switch(r[0]){case n.LinePatternType.Chess:{o[0]=r[1],o[1]=.5,o[2]=.25,o[3]=-.25;break}case n.LinePatternType.DoubleDash:{const c=r[1];o[0]=c,o[1]=r[2]/i,o[2]=.5*r[3]/c,o[3]=.5*r[4]/c,o[2]>=.5-Number.EPSILON&&(o[2]=.6),o[3]>=.5-Number.EPSILON&&(o[3]=.6);break}case n.LinePatternType.Stripe:{const c=r[1]+r[2];o[0]=c,o[1]=.55,o[2]=.5*r[1]/c,o[3]=.5*r[1]/c,o[2]>=.5-Number.EPSILON&&(o[2]=.6),o[3]>=.5-Number.EPSILON&&(o[3]=.6);break}case n.LinePatternType.Circle:{const c=r[1]+r[2];o[0]=c,o[1]=.5*r[1]/c;break}case n.LinePatternType.Triangles:{const c=r[1]+r[2];o[0]=c,o[1]=r[1]/c,o[2]=String(r[3])==="right"?-1:1;break}case n.LinePatternType.Chevron:{const c=r[1]+r[2];o[0]=c,o[1]=r[1]/c,o[2]=r[3]/c,o[3]=r[4]/i;break}}const a=Rt(et(t.color,e)),l={color:a,patternType:r[0],patternParams:o};return{key:[n.MaterialKind.LinePattern,...a,r[0],...o].join("|"),params:{kind:n.MaterialKind.LinePattern,color1:a},pattern:l}}function ph(s,e,t){var o,a;const i=s.sink==="topFill"?(o=e.style)==null?void 0:o.topColor:(a=e.style)==null?void 0:a.sideColor;if(i===void 0)return!1;const r=n.resolveColor(i,t,!0);return r.type==="color"&&!!r.isVertexColor}function et(s,e,t){const i=n.resolveColor(s,e,!0),r=i.type==="mix-color"?i.color1:i;return ps(r,t)}function jT(s){return typeof s=="object"&&s!==null&&s.type==="color-effect-options"}function xh(s,e){var r;const t=(r=s.style)==null?void 0:r.colorEffect;if(t===void 0)return null;const i=n.resolveExpression(t,e);return jT(i)?{color:i.effect.color.value,factor:n.clamp(i.effect.factor,0,1)}:null}function XT(s,e,t,i,r){var E;const o=s.style;if(!o||o.textureImage===void 0||o.color===void 0)return null;const a=t==null?void 0:t.rasterSets;if(!a)return null;const l=n.resolveString(o.textureImage,e),c=(E=a.byKey[n.getStaticTextureRasterSetKey(l)])==null?void 0:E.rasters;if(!c)return null;const d=o.lengthUnits===n.LengthUnits.Meters;if(o.textureSize===void 0)return null;const u=n.resolveExpression(o.textureSize,e);let[h,_]=Array.isArray(u)?u:[u,u];if(!(h>0)||!(_>0))return null;const f=h,m=_;d&&(h=h*n.getPixelsPerMeter(h,h),_=_*n.getPixelsPerMeter(_,_));const v=n.selectRaster(c,h*r,!0);if(v===void 0)return null;const g=c[v],p=i.getSundaAtlasTextureId(g.atlasIndex);if(p===void 0)return null;const x=xh(s,e),S=Rt(et(o.color,e,x)),b=o.textureOpacity!==void 0?n.resolveNumber(o.textureOpacity,e,1):1,T=[(g.x+.5)/n.atlasSize[0],(g.y+g.h-1)/n.atlasSize[1],(g.x+g.w-1)/n.atlasSize[0],(g.y+.5)/n.atlasSize[1]],y={color1:S,textureId:p,spriteCoords:T,opacity:b};return{candidate:{key:[n.MaterialKind.PolygonTexture,...S,p,...T,b].join("|"),params:{kind:n.MaterialKind.PolygonTexture,color1:S},polygonTexture:y},tileInfo:{rasterW:g.w,rasterH:g.h,useMeters:d,sizeW:f,sizeH:m}}}function $T(s,e,t,i,r){if(r.useMeters){const a=n.Mercator.toGeo(n.tileCoordsToMapPoint(s)),l=n.Mercator.scaleFactor(a[1]),c=n.tileZoomToSize(e)/n.MAP_POINTS_IN_METER/l,d=c/r.sizeW,u=c/r.sizeH,h=Math.trunc(n.atlasSize[0]/d),_=Math.trunc(n.atlasSize[1]/u);return[s[0]*n.atlasSize[0]%h/h,s[1]*n.atlasSize[1]%_/_,n.atlasSize[0]/h,n.atlasSize[1]/_]}const o=n.tileSizeZpt*Re(2,Math.round(t)-e)*i;return[s[0]*o%r.rasterW/r.rasterW,s[1]*o%r.rasterH/r.rasterH,o/r.rasterW,o/r.rasterH]}function Si(s,e){const t=Rt(s);return{key:[e,...t].join("|"),params:{kind:e,color1:t}}}function Rt(s){return n.getColorForShaders(s)}const qT=(s,e,t,i,r,o)=>{var m;const{modules:a,state:l,dpr:c}=s,d=Qe(l,t);if(t.sink==="stroke"){const v=Lt(t,i,d);if(!v||((m=i.style)==null?void 0:m.strokeWidth)===void 0)return null;const g=n.resolveNumber(i.style.strokeWidth,d,0);return g<=0?null:I(I(I({type:"line",materialKey:v.key,materialParams:v.params,lineGeometry:n.LineGeometry.Solid12,lineWidth:g*c,lineTileToPixelRatio:0,lineShift:0,lineAbsZ:!1,lineEcefScale:Hn(l,e,n.LineGeometry.Solid12,s.modules.map.getFeatureFlag("globeOff")),floorElevation:Mi(a,t)},Mn(l,t,i,!0)),we(s,e,t,i,r,o)),At(s,t,i,d))}let u=Lt(t,i,d),h;const _=a.styleManager.getStyle(t.attributes.styleId),f=XT(i,d,_,a.assetManager,c);return f&&(u=f.candidate,h=t.layerSettings.identify?void 0:$T(t.tile.coords,t.tile.zoomLevel,l.zoom,c,f.tileInfo)),u?I(I(I({type:"polygon",materialKey:u.key,materialParams:u.params,polygonTextureMaterial:u.polygonTexture,texParams:h,hasEcef:wi(l,e,a.map.getFeatureFlag("globeOff")),floorElevation:Mi(a,t)},Mn(l,t,i,!0)),we(s,e,t,i,r,o)),At(s,t,i,d)):null},YT=(s,e,t,i,r,o)=>{var g;const{modules:a,state:l,dpr:c}=s,d=Qe(l,t),u=Lt(t,i,d);if(!u)return null;const h=t.symbol==="shiftedLine"?n.LineGeometry.Shifted20:t.sink==="solid3d"?n.LineGeometry.Solid3d20:n.LineGeometry.Solid16,_=t.sink==="solid3d"&&!!$e(t).absZ;if(((g=i.style)==null?void 0:g.width)===void 0)return null;const f=n.resolveNumber(i.style.width,d,0);if(f<=0)return null;const m=n.uint16ToTileCoords/(n.tileSizeZpt*Re(2,l.zoom-t.tile.zoomLevel)*c),v=t.symbol==="shiftedLine"&&i.style.shift!==void 0?n.resolveNumber(i.style.shift,d,0)*c:0;return I(I(I({type:"line",materialKey:u.key,materialParams:u.params,lineGeometry:h,lineWidth:f*c,lineTileToPixelRatio:m,lineShift:v,lineAbsZ:_,lineEcefScale:Hn(l,e,h,s.modules.map.getFeatureFlag("globeOff")),floorElevation:h===n.LineGeometry.Solid16?Mi(a,t):0},Mn(l,t,i,h===n.LineGeometry.Solid16)),we(s,e,t,i,r,o)),At(s,t,i,d))},QT=(s,e,t,i,r,o)=>{var p;const{state:a,dpr:l}=s,c=Qe(a,t),d=Lt(t,i,c);if(!(d!=null&&d.pattern))return null;const u=t.sink==="patterned3d"?n.LineGeometry.Patterned3d20:n.LineGeometry.Patterned16;if(((p=i.style)==null?void 0:p.width)===void 0)return null;const h=n.resolveNumber(i.style.width,c,0);if(h<=0)return null;const _=n.uint16ToTileCoords/(n.tileSizeZpt*Re(2,a.zoom-t.tile.zoomLevel)*l),f=i.style.lengthUnits===n.LengthUnits.Meters,m=n.tilePointScaleFactor(n.createTileInfo(t.tile.coords),[n.maxTilePoint/2,n.maxTilePoint/2]),v=f?a.styleZoom:Math.floor(a.styleZoom),g=n.tileSizeZpt*Re(2,v-t.tile.zoomLevel)*l/(n.uint16ToTileCoords*m);return I(I(I({type:"lineParameterized",materialKey:d.key,patternMaterial:d.pattern,lineGeometry:u,lineWidth:h*l,stripeLengthScale:g,stripeCircleFactor:1,lineTileToPixelRatio:_,lineEcefScale:Hn(a,e,u,s.modules.map.getFeatureFlag("globeOff")),floorElevation:0},Mn(a,t,i,!1)),we(s,e,t,i,r,o)),At(s,t,i,c))},JT=(s,e,t,i,r,o)=>{var x;const{modules:a,state:l,dpr:c}=s,d=Qe(l,t),u=Lt(t,i,d);if(!(u!=null&&u.stripe))return null;const h=t.sink==="stroke3d"?n.LineGeometry.Dashed3d32:n.LineGeometry.Dashed28;if(((x=i.style)==null?void 0:x.width)===void 0)return null;const _=n.resolveNumber(i.style.width,d,0);if(_<=0)return null;const f=t.tile.size,m=n.zoomToScale(l.zoom),v=Math.min(m,n.z0Scale),g=n.zptToSceneDistance(_,f)/2*n.uint16ToTileCoords,p=n.zptToSceneDistance(n.uint16ToTileCoords/c,f)/2;return I(I(I({type:"lineParameterized",materialKey:u.key,stripeMaterial:u.stripe,lineGeometry:h,lineWidth:Math.max(0,v*g-m*p),stripeLengthScale:v*n.zptToSceneDistance(1,f),stripeCircleFactor:1e8/v,lineTileToPixelRatio:0,lineEcefScale:Hn(l,e,h,s.modules.map.getFeatureFlag("globeOff")),floorElevation:h===n.LineGeometry.Dashed28?Mi(a,t):0},Mn(l,t,i,h===n.LineGeometry.Dashed28)),we(s,e,t,i,r,o)),At(s,t,i,d))};function bh(s,e){const t=n.zoomToScale(s.state.zoom),i=Math.min(t,n.z0Scale);return{spriteCalcScale:i,spriteScaleRatio:t/i,spriteBorderWidthOffset:1/s.dpr,spriteSizeFactor:n.zptToSceneDistance(n.uint16ToTileCoords,e.tile.size)/2}}const KT=(s,e,t,i,r,o)=>{var u;const{state:a}=s,l=Qe(a,t),c=Lt(t,i,l);if(!(c!=null&&c.oneWay))return null;const d=Bi(a,(u=$e(t).animDirection)!=null?u:n.LabelingAnimation.none);return d===0?null:I(I(V(I({type:"lineSprite",materialKey:c.key,oneWayMaterial:c.oneWay,lineGeometry:n.LineGeometry.OneWay12,spriteOpacity:d},bh(s,t)),{spriteVertexShift:0,spriteEndPosition:1,spriteTipAmplitude:0}),we(s,e,t,i,r,o)),At(s,t,i,l))},e2=(s,e,t,i,r,o)=>{var v,g,p;const{state:a}=s,l=Qe(a,t),c=Lt(t,i,l);if(!(c!=null&&c.arrow))return null;const d=!!$e(t).isLongArrow,u=t.tile.dynamicObject;let h=0,_=1;u&&(d?_=(v=u.growPosition)!=null?v:1:h=(g=u.bouncePosition)!=null?g:0);const f=(p=i.style)==null?void 0:p.animation;let m=0;return f&&(f.type==="appearance"||f.type==="repeat")&&f.tipMovementAmplitude!==void 0&&(m=n.resolveNumber(f.tipMovementAmplitude,l,0)),I(I(V(I({type:"lineSprite",materialKey:c.key,arrowMaterial:c.arrow,lineGeometry:n.LineGeometry.Arrow36,spriteOpacity:1},bh(s,t)),{spriteVertexShift:h,spriteEndPosition:_,spriteTipAmplitude:n.zptToSceneDistance(m,t.tile.size)}),we(s,e,t,i,r,o)),At(s,t,i,l))},t2=(s,e,t,i,r,o)=>{var u;const{state:a}=s,l=Qe(a,t),c=Lt(t,i,l);if(!c)return null;const d=$e(t);return I(I({type:"mapMesh",materialKey:c.key,materialParams:c.params,mapMeshTier:(u=d.meshTier)!=null?u:0,mapMeshAbsZ:!!d.absZ},we(s,e,t,i,r,o)),At(s,t,i,l))};function Qa(s){return(e,t,i,r,o,a)=>{if(i.layerSettings.identify)return null;const{modules:l,state:c}=e,d=Qe(c,i),u=$e(i);let h="",_;if(s===n.MeshMode.Fill){const m=Lt(i,r,d);if(!m)return null;h=m.key,_=m.params}const f=s===n.MeshMode.DepthOnly&&u.floorId?l.floorManager.getFloorObjectElevation(u.floorId)-(c.zoom>=17?1:3):0;return I(I({type:"mesh",meshMode:s,materialKey:h,materialParams:_,heightFactor:vh(l,r,i),floorElevation:f,absZ:s!==n.MeshMode.DepthOnly&&!!u.absZ,labeling:s===n.MeshMode.Fill||s===n.MeshMode.DepthOnly&&(!!u.floorId||!!u.isHole)},we(e,t,i,r,o,a)),At(e,i,r,d))}}const i2=(s,e,t,i,r,o)=>{var _,f,m;const{modules:a,state:l}=s,c=Qe(l,t),d=Lt(t,i,c);if(!d)return null;const u=$e(t),h=u.isFloorStack&&u.floorId?a.floorManager.getFloorsStackObjectOffsets(u.floorId):null;return I(I({type:"polygon3d",materialKey:d.key,materialParams:d.params,isHole:!!u.isHole,heightFactor:Ya(a,i,t),floorElevation:an(a,t),floorStackOffset:(_=h==null?void 0:h.current)!=null?_:0,floorStackTotal:(f=h==null?void 0:h.total)!=null?f:1,isVertexColor:ph(t,i,c),nearCameraFade:((m=i.style)==null?void 0:m.nearCameraFade)!==void 0?n.resolveNumber(i.style.nearCameraFade,c,0):0},we(s,e,t,i,r,o)),At(s,t,i,c))},n2=(s,e,t,i,r,o)=>{var d,u;const{state:a}=s,l=Qe(a,t),c=Lt(t,i,l);return c?I(I({type:"polygon3d",materialKey:c.key,materialParams:c.params,isHole:!1,heightFactor:((d=i.style)==null?void 0:d.height)!==void 0?n.mapHeightToTileHeight(n.resolveNumber(i.style.height,l,0)):0,floorElevation:0,floorStackOffset:0,floorStackTotal:1,isVertexColor:ph(t,i,l),nearCameraFade:((u=i.style)==null?void 0:u.nearCameraFade)!==void 0?n.resolveNumber(i.style.nearCameraFade,l,0):0},we(s,e,t,i,r,o)),At(s,t,i,l)):null},r2=(s,e,t,i,r,o)=>{var g,p;const{modules:a,state:l,dpr:c}=s,d=Qe(l,t),u=Lt(t,i,d);if(!u)return null;const h=t.sink==="sideStroke"?n.LineGeometry.SideStroke24:n.LineGeometry.TopStroke20;let _;if(t.sink==="sideStroke")_=0;else{if(((g=i.style)==null?void 0:g.strokeWidth)===void 0)return null;const x=n.resolveNumber(i.style.strokeWidth,d,0);if(x<=0)return null;_=x*c}let f=0,m=0,v=!1;return t.symbol==="lineExtrusion"?f=((p=i.style)==null?void 0:p.height)!==void 0?n.mapHeightToTileHeight(n.resolveNumber(i.style.height,d,0)):0:t.symbol==="polygonExtrusion"?(f=Ya(a,i,t),t.sink==="topStroke"&&(m=MT)):(v=!!$e(t).absZ,f=vh(a,i,t)),I(I({type:"line",materialKey:u.key,materialParams:u.params,lineGeometry:h,lineWidth:_,lineTileToPixelRatio:m,lineShift:f,lineAbsZ:v,lineEcefScale:Hn(l,e,h,s.modules.map.getFeatureFlag("globeOff")),floorElevation:t.symbol==="polygonExtrusion"?Mi(a,t):0},we(s,e,t,i,r,o)),At(s,t,i,d))},s2=(s,e,t,i,r,o)=>{var p,x,S,b;const{modules:a,state:l}=s,c=(p=$e(t).textureIndex)!=null?p:0,d=(S=(x=i.style)==null?void 0:x.sideTextures)==null?void 0:S[c];if(!d)return null;const u=a.styleManager.getStyle(t.attributes.styleId);if(!u)return null;const h=s.wallTextureLoader.getReadyTexture(d.image,u);if(!h)return null;const _=n.MAP_POINTS_IN_METER*n.tilePointScaleFactor(n.createTileInfo(e.coords),[0,0]),f=d.wallPadding,m=d.texturePadding,v={wallPadding:[f[3]*_,f[0]*_,f[1]*_,f[2]*_],texturePadding:[m[3]/h.width,m[0]/h.height,m[1]/h.width,m[2]/h.height],partCount:[d.horizontal.slicesCount,d.vertical.slicesCount],maxInterval:[d.horizontal.maxInterval*_,d.vertical.maxInterval*_],sliceSize:[d.sliceSize[0]*_,d.sliceSize[1]*_],layoutMode:[gh(d.horizontal.mode),gh(d.vertical.mode)]},g=((b=i.style)==null?void 0:b.nearCameraFade)!==void 0?n.resolveNumber(i.style.nearCameraFade,Qe(l,t),0):0;return I({type:"polygon3dTexture",textureId:h.id,textureLayout:v,heightFactor:Ya(a,i,t),floorElevation:an(a,t),nearCameraFade:g,materialKey:`wallTex-${h.id}-${e.coords[1]}-${e.coords[2]}`},we(s,e,t,i,r,o))},o2={polygon:qT,line:YT,dashedLine:JT,patternedLine:QT,oneWayLine:KT,arrow:e2,pointSprite:AT,pointAnchor:FT,labelPoint:RT,labelLine:LT,metricPoint:DT,circleMarker:zT,mapMesh:t2,meshFill:Qa(n.MeshMode.Fill),meshInverse:Qa(n.MeshMode.DepthOnly),meshDepthClear:Qa(n.MeshMode.DepthClear),extrusion:i2,extrusionTexture:s2,lineExtrusion:n2,wallStroke:r2};function a2(s,e,t,i,r,o){const a=s.modules.styleManager.getStyle(i.attributes.styleId),l=a==null?void 0:a.layersById[i.attributes.layerId];return!l||l.drawToTarget?null:o2[e](s,t,i,l,r,o)}function Sh(s){throw new Error(`unknown sunda draw type: ${s.type}`)}class l2{constructor(e,t){this.modules=e,this.state=t,this.lastTruncatedDraws=0,this.frame=new pT(n.DEFAULT_FRAME_SIZE),this.frameState=new OT(e,t),this.gltfCache=new NT(e,t),this.wallTextureLoader=new bT(e)}destroy(){this.wallTextureLoader.destroy()}submit(e){const t=this.frame;t.clear(),t.setViewProjectionMatrix(this.modules.camera.viewProjectionMatrix),t.setCameraPosition(this.modules.camera.position);let i=0,r=0;if(this.state.loopWorld&&this.state.visibleMapReplicas.length>0){const m=this.state.visibleMapReplicas;i=m[0],r=m[m.length-1]}t.setReplicaRange(i,r);const o=CT(this.state,this.modules);t.setLabelingDepthTestDisabled(o);const a=this.modules.sunda.identifyRequest;a&&t.setIdentifyRequest(a.id,a.width,a.height),this.frameState.writeGlobeState(t),this.frameState.writeStarsState(t),this.frameState.writeGlobeHaloState(t),this.frameState.writeDemState(t),this.frameState.writeMapMeshState(t),this.frameState.writeLightState(t),this.frameState.writeFogState(t),this.frameState.writeSkyState(t),this.frameState.writeShadowState(t),this.state.demMode&&this.frameState.writeDemLightState(t);const{draws:l,identifyDraws:c}=this.collectPendingDraws(e,o,a!==void 0);l.sort(ch),c.sort(ch);const d=new Map,u=this.writeDrawMaterials(t,l,d),h=kT(t,e),_=!u||!this.writeDrawMaterials(t,c,d);this.gltfCache.reset();let f=this.writeDraws(t,l,d,h,!1);return this.state.demMode&&this.frameState.writeDemDraws(t,e),f+=this.writeDraws(t,c,d,h,!0),this.lastTruncatedDraws=f,_&&console.warn("[render] frame is full, material instances were truncated"),f>0&&console.warn(`[render] frame is full, ${f} draws were truncated`),this.modules.sunda.submit(t),this.modules.sunda.identifyRequest!==void 0}writeDrawMaterials(e,t,i){for(const r of t){if(!r.materialKey||i.has(r.materialKey))continue;const o=this.writeSundaDrawMaterial(e,r);if(o!==null){if(o<0)return!1;i.set(r.materialKey,o)}}return!0}writeDraws(e,t,i,r,o){let a=0,l=0,c=null;for(let d=0;d<t.length;d++){const u=t[d],h=u.materialKey?i.get(u.materialKey):0;if(h===void 0){a++;continue}if(u.type==="gltf"){const m=UT(e,this.state,this.gltfCache,u,r,o);if(m===null){a++;continue}if(!m){a+=t.length-d;break}continue}if(u.type==="polygon3dTexture"){if(!e.writeDrawPolygon3dTexture({materialId:h,vertexBuffer:u.vertexBuffer,vertexOffset:u.vertexOffset,vertexCount:u.vertexCount,sourceId:u.sourceId,tileX:u.tileX,tileY:u.tileY,tileZ:u.tileZ,heightFactor:u.heightFactor,floorElevation:u.floorElevation,nearCameraFade:u.nearCameraFade})){a+=t.length-d;break}continue}const _={materialId:h,vertexBuffer:u.vertexBuffer,vertexOffset:u.vertexOffset,vertexCount:u.vertexCount,sourceId:u.sourceId,tileX:u.tileX,tileY:u.tileY,tileZ:u.tileZ,tier:u.tierContent,castShadows:u.castShadows,receiveShadows:u.receiveShadows,useLight:u.useLight,depthTest:u.depthTest,depthGreater:u.depthGreater,identifyOnly:o};let f;switch(u.type){case"line":f=e.writeDrawLine(V(I({},_),{width:u.lineWidth,tileToPixelRatio:u.lineTileToPixelRatio,shift:u.lineShift,absZ:u.lineAbsZ,ecefScale:u.lineEcefScale,floorElevation:u.floorElevation,geometry:u.lineGeometry}));break;case"lineParameterized":f=e.writeDrawLineParameterized(V(I({},_),{width:u.lineWidth,lengthScale:u.stripeLengthScale,circleFactor:u.stripeCircleFactor,tileToPixelRatio:u.lineTileToPixelRatio,ecefScale:u.lineEcefScale,floorElevation:u.floorElevation,geometry:u.lineGeometry}));break;case"lineSprite":f=e.writeDrawLineSprite(V(I({},_),{opacity:u.spriteOpacity,sizeFactor:u.spriteSizeFactor,calcScale:u.spriteCalcScale,scaleRatio:u.spriteScaleRatio,borderWidthOffset:u.spriteBorderWidthOffset,geometry:u.lineGeometry,vertexShift:u.spriteVertexShift,endPosition:u.spriteEndPosition,tipAmplitude:u.spriteTipAmplitude}));break;case"pointSprite":f=e.writeDrawPointSprite(I(I({},_),u.pointSprite));break;case"pointAnchor":f=e.writeDrawPointAnchor(I(I({},_),u.pointAnchor));break;case"labelPoint":f=e.writeDrawLabelPoint(I(I({},_),u.labelPoint));break;case"labelLine":f=e.writeDrawLabelLine(I(I({},_),u.labelLine));break;case"metricPoint":f=e.writeDrawMetricPoint(I(I({},_),u.metricPoint));break;case"circleMarker":f=e.writeDrawCircleMarker(I(I({},_),u.circleMarker));break;case"mapMesh":f=e.writeDrawMapMesh(V(I({},_),{heightFactor:1,tier:u.mapMeshTier,absZ:u.mapMeshAbsZ}));break;case"mesh":f=e.writeDrawMesh(V(I({},_),{mode:u.meshMode,heightFactor:u.heightFactor,floorElevation:u.floorElevation,absZ:u.absZ,labeling:u.labeling}));break;case"polygon3d":{const m=`${u.renderIndex}:${u.groupIndex}:${u.subRenderIndex}`;m!==c&&(c=m,l++),f=e.writeDrawPolygon3d(V(I({},_),{heightFactor:u.heightFactor,floorElevation:u.floorElevation,floorStackOffset:u.floorStackOffset,floorStackTotal:u.floorStackTotal,isHole:u.isHole?1:0,isVertexColor:u.isVertexColor?1:0,nearCameraFade:u.nearCameraFade,runSeq:l}));break}case"polygon":f=u.texParams?e.writeDrawPolygonTextured(V(I({},_),{hasEcef:u.hasEcef,texParams:u.texParams,floorElevation:u.floorElevation})):e.writeDrawPolygon(V(I({},_),{hasEcef:u.hasEcef,floorElevation:u.floorElevation}));break;default:f=Sh(u)}if(!f){a+=t.length-d;break}}return a}collectPendingDraws(e,t,i){const r=[],o=[],a={modules:this.modules,state:this.state,halfPointSize:IT(this.state),labelingDepthTestDisabled:t,dpr:dh(),wallTextureLoader:this.wallTextureLoader},l=this.modules.identifier.getIdScope(n.DEFAULT_ID_SCOPE).getHidden(n.HideLevel.PolygonExtrusion).size>0;for(const c of e){for(const d of c.shadowChildren)if(d.symbol==="gltfModel"&&d.sink==="instances"&&Yo(d,this.modules,this.state)){const u=_h(a,c,d,r.length);u&&r.push(u)}this.collectSceneObjects(a,c,c.children,l,r),i&&this.collectSceneObjects(a,c,c.identifyChildren,l,o)}return{draws:r,identifyDraws:o}}collectSceneObjects(e,t,i,r,o){var a;for(const l of i){if(!Yo(l,this.modules,this.state))continue;if(l.symbol==="gltfModel"&&l.sink==="instances"){const g=_h(e,t,l,o.length);g&&o.push(g);continue}const c=t.getSundaVertexBufferId(l.id);if(c===void 0)continue;const d=GT(l);if(!d)continue;const u=this.state.immersiveLevel.tiers&&(a=$e(l).tiers)!=null?a:null,h=!!u&&!u.some(g=>!g),_=!!u&&VT.has(d);if(h&&!_)continue;const f=a2(e,d,t,l,c,o.length);if(!f)continue;const m=g=>{if(h||o.push(g),_)for(const p of u)p&&o.push(V(I({},g),{tierContent:p,sequence:o.length}))},v=this.getSundaVisibleSpans(l,r);if(v.length===1&&v[0].count===f.vertexCount)m(f);else for(const g of v)m(V(I({},f),{vertexOffset:g.offset,vertexCount:g.count}))}}writeSundaDrawMaterial(e,t){switch(t.type){case"polygon3dTexture":return e.writeWallTextureMaterial(I({textureId:t.textureId},t.textureLayout));case"polygon":return t.polygonTextureMaterial?e.writePolygonTextureMaterial(t.polygonTextureMaterial):e.writeMaterial(t.materialParams);case"lineParameterized":return t.stripeMaterial?e.writeLineStripeMaterial(t.stripeMaterial):t.patternMaterial?e.writeLinePatternMaterial(t.patternMaterial):null;case"lineSprite":return t.oneWayMaterial?e.writeLineOneWayMaterial(t.oneWayMaterial):t.arrowMaterial?e.writeLineArrowMaterial(t.arrowMaterial):null;case"pointSprite":case"metricPoint":return e.writePointSpriteMaterial(t.pointSpriteMaterial);case"labelPoint":case"labelLine":return e.writeLabelPointMaterial(t.labelPointMaterial);case"line":case"mapMesh":case"polygon3d":return e.writeMaterial(t.materialParams);case"mesh":return t.materialParams?e.writeMaterial(t.materialParams):null;case"pointAnchor":case"circleMarker":case"gltf":return null;default:return Sh(t)}}getSundaVisibleSpans(e,t){var u;const i=e.start,r=e.count,o=[{offset:i,count:r}];if(!t)return o;const a=(u=e.vao.getBuffer("a_float_visibility"))==null?void 0:u.getData(),l=i+r;if(!(a instanceof Uint8Array)||a.length<l)return o;const c=[];let d=-1;for(let h=i;h<l;h++){const _=a[h]!==0;_&&d<0?d=h:!_&&d>=0&&(c.push({offset:d,count:h-d}),d=-1)}return d>=0&&c.push({offset:d,count:l-d}),c}}function c2(){const s=globalThis.scheduler;return s!=null&&s.yield?s.yield():xs()}function xs(){return typeof MessageChannel!="undefined"?new Promise(s=>{const e=new MessageChannel;e.port1.onmessage=()=>{e.port1.close(),e.port2.close(),s()},e.port2.postMessage(null)}):new Promise(s=>setTimeout(s,0))}function Ja(s){if(s!=null&&s.aborted){const e=new Error("Style preparation aborted");throw e.name="AbortError",e}}function d2(i,r){return q(this,arguments,function*(s,e,t={}){var _,f,m,v,g,p;Ja(t.signal);const o=(_=t.budgetMs)!=null?_:4,a=(f=t.maxStepsPerSlice)!=null?f:32;if(!Number.isFinite(o)||o<=0)throw new Error("Invalid style preparation time budget");if(!Number.isSafeInteger(a)||a<=0)throw new Error("Invalid style preparation slice size");let l=performance.now();const c=(m=t.allocation)!=null?m:n.reserveHandyStyleIds(n.countHandyStyleIds(s)),d=n.makeHandyStyleSteps(s,e,c),u=(v=t.yieldTask)!=null?v:c2;let h=0;for(;;){Ja(t.signal);const x=d.next();if(x.done)return(g=t.onSlice)==null||g.call(t,{duration:performance.now()-l,steps:h}),Ja(t.signal),x.value;h+=1,(h>=a||performance.now()-l>=o)&&((p=t.onSlice)==null||p.call(t,{duration:performance.now()-l,steps:h}),yield u(),l=performance.now(),h=0)}})}const bs="Style preprocessing:";function u2(s){const e=new Map,t=i=>{i==null||i.forEach(r=>{const o={layers:i,layer:r};e.set(r.id,o),r.type==="group"&&t(r.layers)})};return t(s.layers),e}function h2(s){return s.type==="slot"?{type:"group",id:s.id,layers:[]}:s}function _2(s,e){var o,a,l,c;s.layers=((o=s.layers)!=null?o:[]).map(h2);const t=new Set;performance.now(),e!=null&&e.parentStyleId&&console.warn(`${bs} Parent style with id=${s.parentStyleId} have parent with id=${e.parentStyleId}. Recursive inheritance is not supported.`);const i=e!=null?e:s;if(i.layers=(a=i.layers)!=null?a:[],e){const d=u2(i),u=(l=s.layersInserts)!=null?l:[];u.length&&u.forEach(({layer:_,beforeId:f})=>{var m;if(f){const v=d.get(f);if(v){const{layers:g,layer:p}=v,x=g.findIndex(S=>p===S);g.splice(x,0,_),_.type!=="custom"&&_.type!=="group"&&t.add(_)}else console.warn(`${bs} Child style tries to insert layer with beforeId=${f}. There is no layer with such id in the parent style. Layer insertion ignored.`)}else(m=i.layers)==null||m.push(_)});const h=Object.keys((c=s.layersPatches)!=null?c:{}).reduce((_,f)=>(d.has(f)||_.push(f),_),[]);h.length&&console.warn(`${bs} Child style tries to patch layers with ids which do not exist in parent style: ${h.join("; ")}`)}const r=(d,u,h,_,f)=>{var m;if(u)for(let v=0;v<u.length;v++){const g=u[v];if(g.type==="custom")continue;let p=(m=h==null?void 0:h.layersPatches)==null?void 0:m[g.id];p&&(p==null?void 0:p.type)!==g.type&&(console.warn(`${bs} Layer patch ignored due type mismatch. Target layer with id=${g.id} has type=${g.type}, but the patch has type=${p.type}.`),p=void 0),n.removeUndefined(g),p&&n.removeUndefined(p),g.type!=="slot"&&(g.type==="group"?(r(d,g.layers,h,g,p),u[v]=I(I({},g),p),delete u[v].commonDefaults,delete u[v].layerTypeDefaults):u[v]=f2(d,g,_,f,g.type===(p==null?void 0:p.type)?p:void 0))}};return r(t,i.layers,e?s:void 0),e&&(["background","models","icons","labelingGroups","light","graphicsPresets","terrain","environment"].forEach(d=>{(i[d]&&Object.values(i[d]).length||s[d]&&Object.values(s[d]).length)&&(i[d]=I(I({},i[d]),s[d]))}),i.name=s.name),["models","icons"].forEach(d=>{i[d]&&Object.keys(i[d]).forEach(u=>{i[d][u]===null&&delete i[d][u]})}),i}function f2(s,e,t,i,r){var l,c,d,u,h,_,f,m;const o=I({},t==null?void 0:t.commonDefaults),a=I({},i==null?void 0:i.commonDefaults);switch(e.type){case"heatmap":case"overpass":case"tunnel":{delete o.interactive,delete a.interactive,delete o.ignoreTier,delete a.ignoreTier;break}case"embankment":case"polygon3d":case"buildingModel":case"model":case"lineExtrusion":case"polygonExtrusion":case"point":{delete o.ignoreTier,delete a.ignoreTier;break}case"arrow":case"dashedLine":case"labelLine":case"line":case"metricPoint":case"oneWayLine":case"polygon":case"raster":case"shiftedLine":break;default:n.assertUnreachable(e)}return V(I(I(I(I(I(I(I({},o),(l=t==null?void 0:t.layerTypeDefaults)==null?void 0:l[e.type]),e),a),(c=i==null?void 0:i.layerTypeDefaults)==null?void 0:c[e.type]),s.has(e)?e:void 0),r),{style:I(I(I(I(I(I(I({},(d=t==null?void 0:t.commonDefaults)==null?void 0:d.style),(h=(u=t==null?void 0:t.layerTypeDefaults)==null?void 0:u[e.type])==null?void 0:h.style),e.style),(_=i==null?void 0:i.commonDefaults)==null?void 0:_.style),(m=(f=i==null?void 0:i.layerTypeDefaults)==null?void 0:f[e.type])==null?void 0:m.style),s.has(e)?e.style:void 0),r==null?void 0:r.style)})}function m2(s,e,t){return q(this,null,function*(){const i=new URL(n.template(s,{id:e}));i.searchParams.append("key",t);const r=yield fetch(i.toString());if(r.status===404){console.warn(`No access to style with id «${e}».`);return}if(!r.ok)return;const o=yield r.json();if(o&&o.result)return{loadedId:e,style:o.result}})}function v2(s,e,t){return q(this,null,function*(){let i;try{const r=n.applyDefaults(t||{},{rootUrl:n.styles.url,stylePath:n.styles.path,iconsPath:n.icons.defaultUrl,fontsPath:n.fonts.defaultUrl,modelsPath:n.defaultModelsPath}),o=yield m2(n.getStyleUrl(r),s,e);if(!o)throw new Error;i=o.style}catch(r){throw new Error("FETCH_PARENT_STYLE_ERROR")}return i})}function g2(s,e,t){return q(this,null,function*(){let i;return s.parentStyleId&&(i=yield v2(s.parentStyleId,e,t)),_2(s,i)})}function p2(s,e,t){return q(this,null,function*(){n.checkStyleAbort(t);let i=s.style;if(s.kind!=="object"){const a=yield fetch(s.url,{signal:t});if(!a.ok)throw new Error(`Style request failed: ${a.status}`);const l=yield a.json();i=s.kind==="id"?l==null?void 0:l.result:l}if(!i)throw new Error("Can't set empty style");n.checkStyleAbort(t);const r=performance.now(),o=yield g2(i,s.tileKey,s.options);return n.measureStyle(e,"preprocess.elapsed",performance.now()-r),n.checkStyleAbort(t),o})}class x2{constructor(e,t){this.parser=e,this.labeling=t,this.measurements={},this.controllers=new Map,this.destroyed=!1}prepare(e,t,i,r){return q(this,null,function*(){if(n.checkStyleAbort(r),this.destroyed)throw new Error("Style preparation destroyed");this.measurements={};const o=this.measurements,a=new AbortController,l=()=>a.abort();r.addEventListener("abort",l,{once:!0}),this.controllers.set(i,a);try{const c=yield p2(e,o,a.signal),d=n.reserveHandyStyleIds(n.countHandyStyleIds(c)),u=this.getPorts(),h=[];yield xs();for(const[m,v]of u.entries()){n.checkStyleAbort(a.signal);const g=v.request("prepare-raw",{raw:c,id:t,request:i,allocation:d,options:e.options},p=>n.measureStyle(o,`send.raw.${m?"labeling":"parser"}`,p));g.catch(()=>{}),h.push(g),yield xs()}const _=yield d2(c,t,{signal:a.signal,allocation:d,budgetMs:4,maxStepsPerSlice:Number.MAX_SAFE_INTEGER,yieldTask:xs,onSlice:({duration:m})=>n.measureStyle(o,"build.slice",m)});n.applyStyleOptions(_,e.options);const f=yield Promise.all(h);return n.checkStyleAbort(a.signal),f.forEach((m,v)=>{for(const g in m)o[`${v?"labeling":"parser"}.${g}`]=m[g]}),_}catch(c){throw this.abort(i),c}finally{r.removeEventListener("abort",l),this.controllers.delete(i)}})}commit(e,t){return q(this,null,function*(){n.checkStyleAbort(t),yield Promise.all(this.getPorts().map(i=>i.request("commit",{request:e}))),n.checkStyleAbort(t)})}release(e){var t;(t=this.ports)==null||t.forEach(i=>{i.request("release",{request:e}).catch(()=>{})})}abort(e){var t,i;(t=this.controllers.get(e))==null||t.abort(),(i=this.ports)==null||i.forEach(r=>{r.request("abort",{request:e}).catch(()=>{})})}destroy(){var e;this.destroyed=!0,this.controllers.forEach((t,i)=>this.abort(i)),(e=this.ports)==null||e.forEach(t=>t.close())}getPorts(){if(this.destroyed)throw new Error("Style preparation destroyed");return this.ports||(this.ports=[this.parser,this.labeling].map(e=>{const t=new MessageChannel,i=new n.StylePort(t.port1,r=>{throw new Error(`Unknown main style method: ${r}`)});return e.postMessage({msg:{stylePreparationPort:!0,port:t.port2}},[t.port2]),i})),this.ports}}let Gn="./worker.js";function b2(s){Gn=s}function S2(){return Gn}function y2(s,e){return{setMetatile:s.get(n.ThreadName.Parser,"setMetatile"),getMemoryFootprint:s.get(n.ThreadName.Parser,"getMemoryFootprint"),prepareAtlas:s.get(n.ThreadName.Parser,"prepareAtlas"),packRasters:s.get(n.ThreadName.Parser,"packRasters"),fetchTrafficTile:s.get(n.ThreadName.Parser,"fetchTrafficTile"),deleteTrafficTile:s.get(n.ThreadName.Parser,"deleteTrafficTile"),abortTrafficTileRequest:s.get(n.ThreadName.Parser,"abortTrafficTileRequest"),generateTrafficTile:s.get(n.ThreadName.Parser,"generateTrafficTile"),generatePersonalPoi:s.get(n.ThreadName.Parser,"generatePersonalPoi"),syncStyle:s.get(n.ThreadName.Parser,"syncStyle"),setForceInteractivity:s.get(n.ThreadName.Parser,"setForceInteractivity"),GeoJsonSource:e.set("GeoJsonSource",n.GeoJsonSourceWorker,void 0,["fetchTiles"]).get(n.ThreadName.Parser),ZenithSource:e.set("ZenithWorker",n.ZenithWorker,void 0,["fetchTiles"]).get(n.ThreadName.Parser),MeshElevationSource:e.set("MeshElevationWorker",n.MeshElevationWorker,void 0,["fetchTiles"]).get(n.ThreadName.Parser)}}function T2(s){return{setCommercialPoiRandomSeed:s.get(n.ThreadName.Labeling,"setComPoiRandomSeed"),getMemoryFootprint:s.get(n.ThreadName.Labeling,"getMemoryFootprint"),appendFont:s.get(n.ThreadName.Labeling,"appendFont"),markFontAsLoaded:s.get(n.ThreadName.Labeling,"markFontAsLoaded"),addNewRasterSets:s.get(n.ThreadName.Labeling,"addNewRasterSets"),updatePackingInfo:s.get(n.ThreadName.Labeling,"updatePackingInfo"),syncStyle:s.get(n.ThreadName.Labeling,"syncStyle"),loadRtlPlugin:s.get(n.ThreadName.Labeling,"loadRtlPlugin"),markRtlPluginLoaded:s.get(n.ThreadName.Labeling,"markRtlPluginLoaded")}}function E2(s){return{ModelsSource:s.set("ModelsWorker",n.ModelsWorker).get(n.ThreadName.Models)}}class C2{constructor(){this.connector=new n.MainConnector,this.fnRegistry=new n.FnRegistry(this.connector),this.classRegistry=new n.ClassRegistry(this.fnRegistry),this.parserWorker=new Worker(Gn),this.labelingWorker=new Worker(Gn),this.modelsWorker=new Worker(Gn),this.stylePreparation=new x2(this.parserWorker,this.labelingWorker),this.parserWorker.postMessage({msg:{youare:"parser"}}),this.labelingWorker.postMessage({msg:{youare:"labeling"}}),this.connector.addWorker(n.ThreadName.Parser,this.parserWorker),this.connector.addWorker(n.ThreadName.Labeling,this.labelingWorker),this.modelsWorker.postMessage({msg:{youare:"models"}}),this.connector.addWorker(n.ThreadName.Models,this.modelsWorker),this.parser=y2(this.fnRegistry,this.classRegistry),this.labeling=T2(this.fnRegistry),this.models=E2(this.classRegistry)}syncStyle(e){this.parser.syncStyle(e),this.labeling.syncStyle(e)}setForceInteractivity(e){this.parser.setForceInteractivity(e)}destroy(){this.stylePreparation.destroy(),this.parserWorker.terminate(),this.labelingWorker.terminate(),this.modelsWorker.terminate()}}const I2=30,Ka=16;class P2{constructor(e){this.seq=0,this.lastPreparedFrameId=0,this.pending=[],this.buffers=new Map,this.textures=new Map,this.lastRefFrame=new Map,this.residencyQueue=new Set,this.vramUsedBytes=0,this.skippedUploadWarnings=0,this.lastMissingCount=0,this.lastPressure=!1,this.refBuffers=new Set,this.refTextures=new Set,this.config=n.defaultSundaRenderConfig(),e&&(this.writer=new n.RingWriter(e))}get stats(){let e=0;for(const t of this.pending)(t.type===n.RingRecordType.UploadBuffer||t.type===n.RingRecordType.UploadTexture||t.type===n.RingRecordType.PatchBuffer||t.type===n.RingRecordType.PatchTexture)&&(e+=t.data.byteLength);return{vramBytes:this.vramUsedBytes,missingCount:this.lastMissingCount,pressure:this.lastPressure,pendingBytes:e}}rebind(e){this.writer=new n.RingWriter(e),this.replay(),this.flush()}uploadBuffer(e,t,i,r,o){if(t.byteLength===0){this.deleteTileBuffers([e]);return}const a=this.buffers.get(e);if(a!=null&&a.resident){const l={size:t.byteLength,tileKey:r,data:new Uint8Array(t),isIndex:i,stride:o!=null?o:0,resident:!0};this.buffers.set(e,l),this.vramUsedBytes=Math.max(0,this.vramUsedBytes-a.size+l.size),this.lastRefFrame.set(e,this.lastPreparedFrameId),this.pushBufferUpload(e,l),this.flush();return}this.buffers.set(e,{size:t.byteLength,tileKey:r,data:new Uint8Array(t),isIndex:i,stride:o!=null?o:0,resident:!1}),this.residencyQueue.add(e)}uploadTexture(e,t,i,r){if(i<=0||r<=0||t.byteLength<i*r*4)return;const o=this.textures.get(e);if(o!=null&&o.resident){const a={size:t.byteLength,data:new Uint8Array(t),width:i,height:r,resident:!0};this.textures.set(e,a),this.pushTextureUpload(e,a),this.flush();return}this.textures.set(e,{size:t.byteLength,data:new Uint8Array(t),width:i,height:r,resident:!1}),this.residencyQueue.add(e)}patchTexture(e,t,i,r,o,a){const l=this.textures.get(e);if(!l||o<=0||a<=0||t.byteLength<o*a*4||i<0||r<0||i+o>l.width||r+a>l.height)return;const c=new Uint8Array(t),d=l.width*4,u=o*4;for(let _=0;_<a;_++)l.data.set(c.subarray(_*u,(_+1)*u),(r+_)*d+i*4);if(!l.resident)return;const h=Math.floor((n.MAX_RECORD_SIZE-n.RingPatchTexture.Data-Ka)/u);if(h<1){console.error(`[render][ledger] texture patch row too wide for ring: id=${e}`);return}for(let _=0;_<a;_+=h){const f=Math.min(h,a-_);this.pending.push({type:n.RingRecordType.PatchTexture,seq:this.nextSeq(),id:e,data:c.slice(_*u,(_+f)*u),x:i,y:r+_,w:o,h:f})}this.flush()}deleteTileBuffers(e){this.removeDeclarations(e,this.buffers,n.RingRecordType.DeleteBuffers,!0)}deleteTextures(e){this.removeDeclarations(e,this.textures,n.RingRecordType.DeleteTextures,!1)}setConfig(e){const t=I(I({},this.config),e),i=this.config;Object.keys(t).every(o=>t[o]===i[o])||(this.config=t,this.pending.push({type:n.RingRecordType.SetConfig,seq:this.nextSeq(),config:t}),this.flush())}prepareFrame(e,t){var l,c;this.lastPreparedFrameId=t;const i=this.refBuffers,r=this.refTextures;i.clear(),r.clear(),e.collectResourceRefs(i,r);for(const d of i){const u=this.buffers.get(d);u&&(this.lastRefFrame.set(d,t),u.resident||this.residencyQueue.add(d))}for(const d of r){const u=this.textures.get(d);u&&(this.lastRefFrame.set(d,t),u.resident||this.residencyQueue.add(d))}const o=[];for(const d of this.residencyQueue){const u=this.buffers.get(d);if(u){if(!this.tryPlaceBuffer(d,u,t,i,o))continue;this.residencyQueue.delete(d);continue}const h=this.textures.get(d);if(h){h.resident=!0,this.pushTextureUpload(d,h),this.residencyQueue.delete(d);continue}this.residencyQueue.delete(d)}e.setRequiredSeq(this.seq),o.length>0&&this.pending.push({type:n.RingRecordType.DeleteBuffers,seq:this.nextSeq(),ids:o,fence:t});let a=0;for(const d of i)(l=this.buffers.get(d))!=null&&l.resident||a++;for(const d of r)(c=this.textures.get(d))!=null&&c.resident||a++;this.lastMissingCount=a,this.lastPressure=a>0,this.flush()}onDeviceLost(){this.replay(),this.flush()}destroy(){this.flushTimer!==void 0&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.pending.length=0,this.buffers.clear(),this.textures.clear(),this.lastRefFrame.clear(),this.residencyQueue.clear(),this.vramUsedBytes=0}flush(){if(this.writer){for(;this.pending.length>0;){const e=this.pending[0];if(!this.writeRecord(e))break;this.pending.shift()}this.pending.length>0&&this.flushTimer===void 0&&(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flush()},8))}}removeDeclarations(e,t,i,r){const o=[];for(const a of e){const l=t.get(a);l&&(l.resident&&(o.push(a),r&&(this.vramUsedBytes=Math.max(0,this.vramUsedBytes-l.size))),t.delete(a),this.lastRefFrame.delete(a),this.residencyQueue.delete(a))}o.length!==0&&(this.pending.push({type:i,seq:this.nextSeq(),ids:o,fence:this.lastPreparedFrameId}),this.flush())}tryPlaceBuffer(e,t,i,r,o){const a=this.config.vramBudgetBytes;if(t.size>a)return!1;for(;this.vramUsedBytes+t.size>a;){const l=this.pickEvictionVictim(i,r);if(l===void 0)return this.skippedUploadWarnings<5&&(this.skippedUploadWarnings++,console.warn(`[render][ledger] buffer upload refused by budget: tile=${t.tileKey}, size=${t.size}, used=${this.vramUsedBytes}`)),!1;const c=this.buffers.get(l);c.resident=!1,this.vramUsedBytes=Math.max(0,this.vramUsedBytes-c.size),o.push(l)}return t.resident=!0,this.vramUsedBytes+=t.size,this.lastRefFrame.set(e,i),this.pushBufferUpload(e,t),!0}pickEvictionVictim(e,t){var o;let i,r=Number.POSITIVE_INFINITY;for(const[a,l]of this.buffers){if(!l.resident||t.has(a))continue;const c=(o=this.lastRefFrame.get(a))!=null?o:0;e-c<I2||c<r&&(r=c,i=a)}return i}pushBufferUpload(e,t){if(n.RingUploadBuffer.Data+t.data.byteLength<=n.MAX_RECORD_SIZE){this.pending.push({type:n.RingRecordType.UploadBuffer,seq:this.nextSeq(),id:e,data:t.data,isIndex:t.isIndex,stride:t.stride});return}const i=n.MAX_RECORD_SIZE-n.RingPatchBuffer.Data-Ka&-4;this.pending.push({type:n.RingRecordType.CreateBuffer,seq:this.nextSeq(),id:e,isIndex:t.isIndex,stride:t.stride,byteLength:t.data.byteLength});for(let r=0;r<t.data.byteLength;r+=i)this.pending.push({type:n.RingRecordType.PatchBuffer,seq:this.nextSeq(),id:e,data:t.data.subarray(r,Math.min(r+i,t.data.byteLength)),byteOffset:r})}pushTextureUpload(e,t){if(n.RingUploadTexture.Data+t.data.byteLength<=n.MAX_RECORD_SIZE){this.pending.push({type:n.RingRecordType.UploadTexture,seq:this.nextSeq(),id:e,data:t.data,width:t.width,height:t.height});return}const i=t.width*4,r=Math.floor((n.MAX_RECORD_SIZE-n.RingPatchTexture.Data-Ka)/i);if(r<1){console.error(`[render][ledger] texture row too wide for ring: id=${e}`);return}this.pending.push({type:n.RingRecordType.CreateTexture,seq:this.nextSeq(),id:e,width:t.width,height:t.height});for(let o=0;o<t.height;o+=r){const a=Math.min(r,t.height-o);this.pending.push({type:n.RingRecordType.PatchTexture,seq:this.nextSeq(),id:e,data:t.data.subarray(o*i,(o+a)*i),x:0,y:o,w:t.width,h:a})}}nextSeq(){return this.seq=this.seq+1>>>0,this.seq===0&&(this.seq=1),this.seq}replay(){this.pending.length=0,this.pending.push({type:n.RingRecordType.ClearAll,seq:this.nextSeq()}),this.pending.push({type:n.RingRecordType.SetConfig,seq:this.nextSeq(),config:this.config});for(const[e,t]of this.buffers)t.resident&&this.pushBufferUpload(e,t);for(const[e,t]of this.textures)t.resident&&this.pushTextureUpload(e,t)}writeRecord(e){const t=this.writer;if(!t)return!1;switch(e.type){case n.RingRecordType.UploadBuffer:return t.tryWriteUploadBuffer(e.seq,e.id,e.data,e.isIndex,e.stride);case n.RingRecordType.UploadTexture:return t.tryWriteUploadTexture(e.seq,e.id,e.data,e.width,e.height);case n.RingRecordType.CreateTexture:return t.tryWriteCreateTexture(e.seq,e.id,e.width,e.height);case n.RingRecordType.PatchTexture:return t.tryWritePatchTexture(e.seq,e.id,e.data,e.x,e.y,e.w,e.h);case n.RingRecordType.CreateBuffer:return t.tryWriteCreateBuffer(e.seq,e.id,e.isIndex,e.stride,e.byteLength);case n.RingRecordType.PatchBuffer:return t.tryWritePatchBuffer(e.seq,e.id,e.data,e.byteOffset);case n.RingRecordType.DeleteBuffers:case n.RingRecordType.DeleteTextures:return t.tryWriteDeleteIds(e.type,e.seq,e.ids,e.fence);case n.RingRecordType.SetConfig:return t.tryWriteSetConfig(e.seq,e.config);case n.RingRecordType.ClearAll:return t.tryWriteClearAll(e.seq)}}}const A2=3e3;function yh(s=!1){const e=typeof window!="undefined",t=typeof SharedArrayBuffer!="undefined",i=e&&window.crossOriginIsolated===!0,r=typeof OffscreenCanvas!="undefined",o=typeof HTMLCanvasElement!="undefined",a=o&&"transferControlToOffscreen"in HTMLCanvasElement.prototype;return s&&(console.log("[render][check] hasWindow:",e),console.log("[render][check] hasSharedArrayBuffer:",t),console.log("[render][check] isCrossOriginIsolated:",i),console.log("[render][check] hasOffscreenCanvas:",r),console.log("[render][check] hasHTMLCanvasElement:",o),console.log("[render][check] hasTransferControlToOffscreen:",a)),e&&t&&i&&r&&o&&a}function L2(){const s=document.createElement("canvas");return s.style.position="absolute",s.style.top="0",s.style.left="0",s.style.width="100%",s.style.height="100%",s.style.pointerEvents="none",s}class R2{constructor(e,t){this.frameId=0,this.revealPercent=100,this.identifyRequestSeq=0,this.frameWriteSlot=1;const i=e.sunda;i&&(this.modules=t,this._ledger=new P2,this._ledger.setConfig({waitForResources:!!i.waitForResources,showTileBounds:!!e.showDefaultTileBounds}),this.attach(!i.forceMainThread&&yh()))}get ledger(){return this._ledger}get identifyRequest(){return this.pendingIdentify}requestIdentify(e,t){var r;if(this.settleIdentify(void 0),!this.runner||(r=this._ledger)!=null&&r.stats.pressure)return Promise.resolve(void 0);this.identifyRequestSeq=this.identifyRequestSeq+1>>>0||1;const i=this.identifyRequestSeq;return new Promise(o=>{this.pendingIdentify={id:i,width:e,height:t,resolve:o,timer:setTimeout(()=>{var a;((a=this.pendingIdentify)==null?void 0:a.id)===i&&(console.warn("[render] sunda identify timed out"),this.settleIdentify(void 0))},A2)}})}setRenderMode(e){this._ledger&&(this.detach(),this.attach(e==="worker"&&yh()))}submit(e){var a;if(!this.transportBuffer||!this.transportI32||!this.transportU32)return;this.frameId=this.frameId+1>>>0,this.frameId===0&&(this.frameId=1),(a=this._ledger)==null||a.prepareFrame(e,this.frameId);const t=n.TransportHeader._Size+this.frameWriteSlot*n.DEFAULT_FRAME_SIZE,i=e.bytesUsed,r=new Uint8Array(this.transportBuffer,t,i),o=new Uint8Array(e.buffer,0,i);r.set(o),this.transportU32[t+n.FrameHeader.FrameId>>2]=this.frameId,this.frameWriteSlot=n.mailboxSwap(this.transportI32,n.TransportHeader.FrameMailbox,this.frameWriteSlot)}setConfig(e){var t;(t=this._ledger)==null||t.setConfig(e)}setRevealPercent(e){this.revealPercent=Math.max(0,Math.min(100,e)),this.applyRevealClip()}resize(e,t,i,r){var o;this.renderCanvas&&(this.renderCanvas.style.width=e+"px",this.renderCanvas.style.height=t+"px"),(o=this.runner)==null||o.then(a=>a.resize(e,t,i,r)).catch(()=>{})}destroy(){var e;(e=this._ledger)==null||e.destroy(),this._ledger=void 0,this.detach(),this.modules=void 0}attach(e){var o;const t=this.modules;if(!t||!this._ledger)return;console.log(`[render] mode: ${e?"worker thread":"main thread"}`),this.transportBuffer=e?new SharedArrayBuffer(n.TRANSPORT_SIZE):new ArrayBuffer(n.TRANSPORT_SIZE),this.transportI32=new Int32Array(this.transportBuffer),this.transportU32=new Uint32Array(this.transportBuffer),n.initTransportHeader(this.transportU32),this.frameWriteSlot=1,this._ledger.rebind(this.transportBuffer);const i=L2();this.renderCanvas=i,(o=t.layout.canvas.parentElement)==null||o.appendChild(i),this.applyRevealClip();let r;if(e){this.worker=new Worker(S2(),{name:"render"});const a=i.transferControlToOffscreen();r=n.wrap(this.worker)(n.RenderBackendType.WebGPU,n.transfer(a,[a]),this.transportBuffer,n.proxy(l=>this.onRunnerEvent(l)))}else r=n.createRenderRunner(n.RenderBackendType.WebGPU,i,this.transportBuffer,a=>this.onRunnerEvent(a));this.runner=r,r.then(a=>(t.map.invalidateSize(),a.start())).catch(a=>{this.runner===r&&(this.runner=void 0),this.onRunnerEvent({type:"error",message:`runner start failed: ${String(a)}`})})}applyRevealClip(){this.renderCanvas&&(this.renderCanvas.style.clipPath=`inset(0 ${100-this.revealPercent}% 0 0)`)}onRunnerEvent(e){var t,i;switch(e.type){case"deviceLost":console.warn(`[render] webgpu device recovered (generation ${e.generation}), replaying resources`),(t=this._ledger)==null||t.onDeviceLost();break;case"recoveryFailed":console.error("[render] webgpu device recovery failed, sunda rendering is dead");break;case"error":console.error(`[render][runner] ${e.message}`);break;case"identify":if(((i=this.pendingIdentify)==null?void 0:i.id)===e.requestId){const{width:r,height:o,pixels:a}=e;this.settleIdentify({width:r,height:o,pixels:a})}break}}settleIdentify(e){const t=this.pendingIdentify;t&&(this.pendingIdentify=void 0,clearTimeout(t.timer),t.resolve(e))}detach(){var i;this.settleIdentify(void 0);const e=this.worker;this.worker=void 0;const t=this.runner;this.runner=void 0,t==null||t.then(r=>r.destroy()).catch(()=>{}).then(()=>e==null?void 0:e.terminate()),(i=this.renderCanvas)==null||i.remove(),this.renderCanvas=void 0,this.transportBuffer=void 0,this.transportI32=void 0,this.transportU32=void 0}}class F2{constructor(e,t){this.state=e,this.modules=t,this.revealPercent=100,e.sunda&&this.enable(e.sunda)}get enabled(){return this.renderer!==void 0}get ledger(){var e;return(e=this.renderer)==null?void 0:e.ledger}get identifyRequest(){var e;return(e=this.renderer)==null?void 0:e.identifyRequest}enable(e){this.renderer||(this.state.sunda=e,this.renderer=new R2(this.state,this.modules),this.renderer.setRevealPercent(this.revealPercent),this.frameBuilder=new l2(this.modules,this.state),this.modules.assetManager.remirrorSundaAtlases())}disable(){if(this.renderer){this.destroyRuntime(),this.state.sunda=void 0;for(const e of this.modules.tileManager.getTileObjects())e.clearSundaRegistrations();this.modules.assetManager.clearSundaRegistrations()}}submit(e){var t;(t=this.renderer)==null||t.submit(e)}setConfig(e){var t;(t=this.renderer)==null||t.setConfig(e)}requestIdentify(e,t){return this.renderer?(this.state.needRerender=!0,this.renderer.requestIdentify(e,t)):Promise.resolve(void 0)}setRenderMode(e){var t;(t=this.renderer)==null||t.setRenderMode(e)}setRevealPercent(e){var t;this.revealPercent=Math.max(0,Math.min(100,e)),(t=this.renderer)==null||t.setRevealPercent(this.revealPercent)}resize(e,t,i,r){var o;(o=this.renderer)==null||o.resize(e,t,i,r)}destroy(){this.destroyRuntime()}destroyRuntime(){var e,t;(e=this.frameBuilder)==null||e.destroy(),this.frameBuilder=void 0,(t=this.renderer)==null||t.destroy(),this.renderer=void 0}}function D2(s,e){return(s[e+3]<<24|s[e+2]<<16|s[e+1]<<8|s[e])>>>0}class z2{constructor(e,t){this.idScopes={},this.pixelPackBuffer=null,this.pixelPackBufferSize=0,this.isIdle=()=>this.searchQueue.size===0&&!this.needsUpdate&&!this.cacheBusy,this.state=e,this.modules=t,this.identifyData=[],this.needsUpdate=!1,this.forceUpdate=!1,this.searchQueue=new Map,this.lastUpdateTime=NaN,this.cacheBusy=!1,this.stateDiffer=new n.Differ([{path:"center",type:"vec2"},{path:"zoom",type:"number"},{path:"size",type:"vec2"},{path:"rotation",type:"number"},{path:"pitch",type:"number"},{path:"padding",type:"padding"},{path:"demMode",type:"boolean"}])}queryFillCache(){this.needsUpdate=!0}getMemoryFootprint(){var t,i;const e={colorBuffer:(i=(t=this.scene)==null?void 0:t.pixels.byteLength)!=null?i:0};return{js:V(I({},e),{"--sum":n.getTotalMemory(e)})}}resetCache(){this.scene=void 0,this.queryFillCache()}search(e,t,i=!1){return this.scene===void 0&&i&&(this.needsUpdate=!0),this.forceUpdate=i,new Promise(r=>{this.searchQueue.set(e,{point:t,resolve:r})})}searchSync(e){return this.searchHigherPriority(e)}update(){if(this.cacheBusy)return;this.stateDiffer.check(this.state)&&(this.resetCache(),this.searchQueue.size>0&&this.searchQueue.clear());const e=this.modules.labeler.isIdle()&&!this.modules.buildingHeightAnimator.isAnimating()&&this.modules.assetManager.isIdle(),t=Number.isNaN(this.lastUpdateTime)?!0:Date.now()-this.lastUpdateTime>=n.identify.cacheRefreshTime;this.needsUpdate&&(this.forceUpdate||e&&t)&&this.fillCache(),this.scene!==void 0&&this.searchQueue.size>0&&(this.searchQueue.forEach(i=>{i.resolve(this.searchHigherPriority(i.point))}),this.searchQueue.clear())}getIdScope(e){return this.idScopes[e]||(this.idScopes[e]=new n.IdScope(this)),this.idScopes[e]}readIdentifyPixels(e=!1){return q(this,null,function*(){const t=this.modules.renderer.getRenderingContext(),i=this.modules.renderer.identifyBuffer,r=i.options.size,o=r[0],a=r[1];if(e||t instanceof WebGLRenderingContext||this.state.forceSyncIdentify){const l=new Uint8Array(o*a*4);return i.bind(t),t.readPixels(0,0,r[0],r[1],t.RGBA,t.UNSIGNED_BYTE,l),i.unbind(t),l}else return this._pendingReadIdentifyPixelsPromise?this._pendingReadIdentifyPixelsPromise:(this._pendingReadIdentifyPixelsPromise=new Promise((l,c)=>{q(this,null,function*(){const d=new Uint8Array(o*a*4);i.bind(t);const u=o*a*4;!this.pixelPackBuffer||this.pixelPackBufferSize!==u?(this.pixelPackBuffer&&t.deleteBuffer(this.pixelPackBuffer),this.pixelPackBuffer=t.createBuffer(),this.pixelPackBufferSize=u,t.bindBuffer(t.PIXEL_PACK_BUFFER,this.pixelPackBuffer),t.bufferData(t.PIXEL_PACK_BUFFER,u,t.STREAM_READ)):t.bindBuffer(t.PIXEL_PACK_BUFFER,this.pixelPackBuffer),t.readPixels(0,0,o,a,t.RGBA,t.UNSIGNED_BYTE,0);const h=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);if(t.flush(),!h){i.unbind(t),c("Failed to create sync object"),this._pendingReadIdentifyPixelsPromise=void 0;return}yield this.clientWaitAsync(t,h,0,10),t.deleteSync(h),t.bindBuffer(t.PIXEL_PACK_BUFFER,this.pixelPackBuffer),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,d),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),i.unbind(t),l(d),this._pendingReadIdentifyPixelsPromise=void 0})}),this._pendingReadIdentifyPixelsPromise)})}destroy(){const e=this.modules.renderer.getRenderingContext();this.pixelPackBuffer&&e instanceof WebGL2RenderingContext&&(e.deleteBuffer(this.pixelPackBuffer),this.pixelPackBuffer=null)}captureLegacyAndSundaScenes(){return q(this,null,function*(){if(!this.cacheBusy){this.cacheBusy=!0;try{const e=yield this.captureLegacyScene(),t=e&&(yield this.captureSundaScene());return!e||!t?void 0:(this.collectIdentifyData(),{legacy:e,sunda:t})}finally{this.cacheBusy=!1}}})}indexToIdentifierResponse(e){var t,i,r;for(let o=0;o<this.identifyData.length;o++){const a=this.identifyData[o],{dynamicObjectId:l,ids:c,metatileHash:d,sourceId:u,tileKey:h}=a,{startIndex:_,endIndex:f,idBuffer:m,floorIdBuffer:v,phaseBuffer:g,sublayerBuffer:p,styleIdBuffer:x,layerIdBuffer:S,instanceIdBuffer:b,objectClassBuffer:T,centerBuffer:y,strings:E}=c;if(e<_||e>f)continue;const P=e-_,A=m[P],F=new Uint32Array(p)[P],L=new Uint8Array(b)[P],D=new Uint32Array(T)[P];let B,Q="";const Z=v[P],$=this.modules.assetManager.getMetatile(d);if($){(t=$.reverseDictionaries.db_sublayer)!=null&&t[F]&&(B=$.reverseDictionaries.db_sublayer[F]);const Ie=E[e];Ie!==void 0?Q=Ie.objectClass:Q=(r=(i=$==null?void 0:$.reverseDictionaries.db_object_class)==null?void 0:i[D])!=null?r:""}const J=new Uint16Array(x)[P],ge=new Uint32Array(S)[P],Ce=this.modules.styleManager.getStyleLayer(J,ge);if(!Ce||Ce.type==="custom")return;const tt=new Int32Array(y,P*Int32Array.BYTES_PER_ELEMENT*2,2);return{id:A,styleId:J,layerId:ge,floorId:Z,phase:new Float32Array(g)[P],dynamicObjectId:l,sourceId:u,tileKey:h,sublayer:B,symbol:Ce.type,instanceId:L,objectClass:Q,center:tt[0]!==n.INVALID_IDENTIFY_CENTER_COORD||tt[1]!==n.INVALID_IDENTIFY_CENTER_COORD?[tt[0],tt[1]]:void 0}}}clientWaitAsync(e,t,i,r){return new Promise((o,a)=>{function l(){const c=e.clientWaitSync(t,i,0);if(c===e.WAIT_FAILED){a();return}if(c===e.TIMEOUT_EXPIRED){setTimeout(l,r);return}o()}l()})}searchHigherPriority(e){const{viewport:t}=this.state,i=n.fromValues$1(e[0]-t.left,e[1]-t.top),r=this.state.identifyPickDistance*window.devicePixelRatio;let o=1/0,a,l=!1;const c=n.create$6();for(c[0]=i[0]-r;c[0]<i[0]+r;c[0]++)for(c[1]=i[1]-r;c[1]<i[1]+r;c[1]++){const d=this.searchPointInCache(c);if(!d)continue;const u=d.dynamicObjectId!==void 0;if(u&&(d.phase=this.modules.dynamicStyle.getRenderIndexById(d.layerId)),l&&!u)continue;const h=n.distance(i,c);(!a||!l&&u||d.phase>a.phase||d.phase===a.phase&&h<o)&&(a=d,o=h,u&&(l=!0))}return a}searchPointInCache(e){const t=this.scene;if(t===void 0)return;const i=n.identify.pixelDensity*window.devicePixelRatio,r=this.state.size;if(e[0]<0||e[0]>r[0]-1||e[1]<0||e[1]>r[1]-1)return;const o=Math.floor(e[0]*i),a=t.height-1-Math.floor(e[1]*i);return this.indexToIdentifierResponse(D2(t.pixels,(a*t.width+o)*4))}fillCache(){return q(this,null,function*(){var e;if(!this.cacheBusy)try{this.cacheBusy=!0;const t=!Number.isNaN(this.state.handyStyleId),i=(e=yield this.captureSundaScene())!=null?e:yield this.captureLegacyScene();if(!i)return;this.scene=i,this.lastUpdateTime=Date.now();const r=this.state.metrics;r.interactive===void 0&&t&&(r.interactive=performance.now()-r.start),this.collectIdentifyData(),this.needsUpdate=!1,this.forceUpdate=!1}catch(t){this.needsUpdate=!1,this.forceUpdate=!1,console.warn(`Cannot fill cache: ${t}`)}finally{this.cacheBusy=!1}})}collectIdentifyData(){this.identifyData=this.modules.tileManager.getDisplayedIdentifyData(),this.modules.modelLayer.getDisplayedIdentifyData().forEach(t=>this.identifyData.push(t));const e=this.modules.personalPoiManager.getIdentifyDataChunk();e!==void 0&&this.identifyData.push(e),this.modules.layers.getDynamicObjectLayers().forEach(t=>{t.getIdentifyData().forEach(i=>this.identifyData.push(i))})}captureLegacyScene(){return q(this,null,function*(){if(!this.modules.renderer.renderIdentify(this.modules.tileManager.getTileObjects()))return;const e=yield this.readIdentifyPixels(),[t,i]=this.modules.renderer.identifyBuffer.options.size;return{width:t,height:i,pixels:e}})}captureSundaScene(){const[e,t]=this.modules.renderer.identifyBuffer.options.size;return this.modules.sunda.requestIdentify(e,t)}}function B2(s,e,t){var o;if(s.id===void 0)throw new Error("The layer id must be set.");if(e.layerIdToInnerId[s.id])throw new Error(`The layer with id «${s.id}» already exists in the map style.`);let i=-1;if(t){const a=Object.values(e.groupsById).find(l=>l&&l.id===t);if(a)i=e.layers.findIndex(l=>l.groupId===a.innerId);else{i=e.layers.findIndex(c=>c.id===t);const l=(o=e.layers[i])==null?void 0:o.groupId;if(l!==void 0&&s.type==="group")throw new Error(`Group layer with id «${s.id}» can't be added before layer with id «${t}» in group with innerId «${l}». Layer groups doesn't support nesting.`)}}else i=e.layers.length;if(i===-1)throw new Error(`The layer with beforeId «${t}» doesn't exist in the map style.`);let r=[];if(s.type!=="group"){r=[s];const a=i!==e.layers.length?e.layers[i]:void 0;if(a&&a.groupId!==void 0){const l=e.groupsById[a.groupId];if(!l){n.log(`Для слоя с id «${a.id}» находящегося в группе с groupId «${a.groupId}» отсутствует группа id в стиле c id «${e.id}»`);return}const c=l.layers.findIndex(d=>d.id===a.id);if(c===-1){n.log(`Слой с id «${a.id}» и groupId «${a.groupId}» отсутствует группе в стиле c id «${e.id}»`);return}s.groupId=l.innerId,l.layers.splice(c,0,s),l.layers.forEach((d,u)=>d.groupIndex=u)}}else e.groupsById[s.innerId]=s,e.layerIdToInnerId[s.id]=s.innerId,r=s.layers;e.revision++,e.layers.splice(i,0,...r),r.forEach(a=>{if(e.layersById[a.innerId]=a,e.layerIdToInnerId[a.id]=a.innerId,a.type==="point"||a.type==="polygon"||a.type==="metricPoint"||a.type==="embankment"||a.type==="polygon3d"){const l=Math.max(0,...Object.keys(e.rasterSets.byIndex).map(u=>Number(u))),c=new n.HandyIndexer(l+1);n.makeHandyRasterSets(a,c,e.icons).forEach(u=>{e.rasterSets.byKey[u.key]||(e.rasterSets.byIndex[u.index]=u,e.rasterSets.byKey[u.key]=u)})}}),Th(e)}function O2(s,e,t){const i=e.layerIdToInnerId[s];if(i===void 0)return;e.revision++;let r=[];const o=e.groupsById[i];if(o){if(r=o.layers,delete e.groupsById[i],delete e.layerIdToInnerId[o.id],r.length===0)return}else{const l=e.layersById[i];if(!l){n.log(`Слой с id «${s}» есть в списке идентификаторов слоев стиля, но при этом отсутствует в стиле c id «${e.id}»`);return}if(l.groupId!==void 0&&l.groupIndex!==void 0){const c=e.groupsById[l.groupId];c&&(c.layers.splice(l.groupIndex,1),c.layers.forEach((d,u)=>d.groupIndex=u))}r=[l]}const a=e.layers.findIndex(l=>l.id===r[0].id);a!==-1&&(r.forEach(l=>{const{styleManager:c,map:{state:d}}=t,u=c.getRemoveLayerHook(l.innerId);u&&(u(d),c.clearRemoveLayerHook(l.innerId)),delete e.layersById[l.innerId],delete e.layerIdToInnerId[l.id]}),e.layers.splice(a,r.length),Th(e))}function Th(s){const e=new n.HandyIndexer;let t;for(const i of s.layers)i.groupId!==void 0&&t&&i.groupId===t.groupId?i.renderIndex=t.renderIndex:i.renderIndex=e.getIndex(),t=i;for(const i in s.groupsById){const r=s.groupsById[i];r&&r.layers[0]&&(r.renderIndex=r.layers[0].renderIndex)}}function w2(s,e,t){const{map:{state:i},collector:r,imageManager:o,renderer:a,tileManager:l}=t;let c;try{c=N2(i,s,256)}catch(x){console.error(x);return}const d=o.addPreparedTexture(c),{downscale:u}=s.style,{size:h}=i,_=new Pe({size:[Math.ceil(h[0]*window.devicePixelRatio/u),Math.ceil(h[1]*window.devicePixelRatio/u)],magFilter:C.LinearFilter,minFilter:C.LinearFilter,wrapS:C.ClampToEdgeWrapping,wrapT:C.ClampToEdgeWrapping}),f=_.getTexture();if(!f){console.error("Can't init HeatMap Layer. Missing FrameBuffer texture");return}const m=o.addPreparedTexture(f),v=a.addFramebuffer({renderTarget:_,clearColor:[0,0,0,0],onResize:()=>{_.setSize([Math.ceil(i.size[0]*window.devicePixelRatio/u),Math.ceil(i.size[1]*window.devicePixelRatio/u)]),a.bindRenderTarget(_),a.bindRenderTarget(null);const x=_.getTexture();x&&o.updatePreparedTexture(m,x)}});n.generateSafely({collector:r,generator:n.HeatmapGenerator.generateTexture,args:[e,s,m,d]});const g=r.getAccumulatedData(),p=new n.TileObject("dynamicObject",g.data,t,i);return l.addObject(p),r.reset(),s.framebufferId={framebuffer:v},x=>{l.removeObject(p),p.clean(x),o.deleteTexture(m),o.deleteTexture(d),a.removeFramebuffer(v)}}function N2(s,e,t){const i=n.makeBinderContext(s.styleZoom,s.pitch,s.styleState,[]),r=e.style.color,o=[];if(!k2(r.argument))throw new Error(`Heatmap color must be interpolate expression with 'heatmap-density' argument in layer ${e.id}`);const a=t-1;for(let l=0;l<t;l++){const c=l/a,d=n.sampleColor(r,c,i);o.push(...d.value)}return new C(new Uint8Array(o),{size:[t,1]})}function k2(s){return typeof s=="object"&&s.type==="heatmap-density"}const Eh=1,Ch={type:"color",value:[0,0,0,0]};class U2{constructor(e){this.modules=e,this.customLayers=new Map,this.maxCountStyleLayers=1e4,this.styleIndex=Eh,this.handyStylesMap=new Map,this.installedStyleIds=[],this.waitingStyleRequests=new Map,this.onRemoveLayerHooks=new Map}getNextStyleId(){return this.styleIndex}installPreparedStyle(e,t){if(e.id!==this.styleIndex)throw new Error("Obsolete prepared style ID");this.beginStyle(t),this.registerStyle(e),e.layers.forEach(i=>this.initHandyLayer(e.id,i)),this.retainStyle(e.id)}hasLayer(e){const t=this.getStyle(this.modules.map.state.handyStyleId);return(t==null?void 0:t.layerIdToInnerId[e])!==void 0}addLayer(e,t){const i=this.getStyle(this.modules.map.state.handyStyleId);if(!i){console.error('Cannot add layer before map style was completely set. Please use "styleload" event.');return}const r=n.makeHandyGroupOrLayer(e,i.globals);r&&(B2(r,i,t),this.setMaxLayersCount(i.layers.length),e.type==="custom"&&r.type==="custom"?this.initCustomLayer(i.id,r,e.render,e.onRemove,e.onAdd):this.initHandyLayer(i.id,r),this.modules.workers.syncStyle(i))}setTerrainStyle(e){const t=this.getStyle(this.modules.map.state.handyStyleId);if(!t)return;const i=t.dem.style.contours,r=n.makeHandyDemLayer(e,t.globals);i!==void 0&&r.style.contours===void 0&&(r.style.contours=i),t.dem=r,this.modules.demManager.onTerrainStyleChange(),this.modules.renderer.addRerenderEvent()}addIcon(e,t){const i=this.getStyle(this.modules.map.state.handyStyleId);if(!i)return console.error('Cannot add icons before map style was completely set. Please use "styleload" event.'),!1;const r=i.layers.filter(d=>(d.type==="point"||d.type==="metricPoint")&&d.style.iconImage!==void 0&&n.expressionValues(d.style.iconImage).some(u=>u===e)),o=i.layers.filter(d=>(d.type==="polygon"||d.type==="embankment"||d.type==="polygon3d")&&!!d.style.textureImage&&n.expressionValues(d.style.textureImage).some(u=>u===e));if(!!i.icons[e])return console.error(`The icon with the name ${e} already exists.`),!1;const l=Math.max(0,...Object.keys(i.rasterSets.byIndex).map(d=>Number(d))),c=new n.HandyIndexer(l+1);return i.icons[e]=t,[...r,...o].forEach(d=>{n.getLayerImageProps(d).forEach(({imageType:u,anchor:h})=>{const _=n.makeHandyRasterSet(e,u,c,h,i.icons);i.rasterSets.byIndex[_.index]=_,i.rasterSets.byKey[_.key]=_})}),i.revision++,this.modules.workers.syncStyle(i),!0}removeIcon(e){const t=this.getStyle(this.modules.map.state.handyStyleId);if(!t)return console.error('Cannot remove icons before map style was completely set. Please use "styleload" event.'),!1;delete t.icons[e];let i=!1;return t.layers.filter(r=>r.type==="point"&&!!r.style.iconImage||r.type==="polygon"&&!!r.style.textureImage||r.type==="metricPoint"&&!!r.style.iconImage||r.type==="embankment"&&!!r.style.textureImage||r.type==="polygon3d"&&!!r.style.textureImage).forEach(r=>{n.getLayerImageProps(r).forEach(({image:o,imageType:a,anchor:l})=>{n.expressionValues(o).forEach(c=>{if(c===e){const d=a==="icon"?n.getStaticIconRasterSetKey(c,l[0],l[1]):n.getStaticTextureRasterSetKey(c),u=t.rasterSets.byKey[d];u&&(this.modules.assetManager.removeRasterSet(u,t.id),i=!0)}})})}),i?(t.revision++,this.modules.workers.syncStyle(t),!0):!1}addModel(e,t){const i=this.getStyle(this.modules.map.state.handyStyleId);return i?i.modelIndex[e]!==void 0?(console.error(`The model with the name ${e} already exists.`),!1):(i.models.push(t),i.modelIndex[e]=i.models.length-1,i.revision++,this.modules.workers.syncStyle(i),!0):(console.error('Cannot add models before map style was completely set. Please use "styleload" event.'),!1)}removeLayer(e){const t=this.getStyle(this.modules.map.state.handyStyleId);if(!t){console.error('Cannot remove layer before map style was completely set. Please use "styleload" event.');return}O2(e,t,this.modules),this.modules.workers.syncStyle(t)}showLayers(e){const t=this.getStyle(this.modules.map.state.handyStyleId);if(!t){console.error('Cannot hide layer or group before map style was completely set. Please use "styleload" event.');return}this.setLayerVisibility("visible",e,t)}hideLayers(e){const t=this.getStyle(this.modules.map.state.handyStyleId);if(!t){console.error('Cannot hide layer or group before map style was completely set. Please use "styleload" event.');return}this.setLayerVisibility("hidden",e,t)}setDynamicStyle(e){this.handyStylesMap.set(n.DYNAMIC_STYLE_ID,e),this.modules.workers.syncStyle(e)}getStyle(e){return this.handyStylesMap.get(e)}getStyleLayer(e,t){var i;return(i=this.handyStylesMap.get(e))==null?void 0:i.layersById[t]}getStyleRevision(e){var t;return((t=this.getStyle(e))==null?void 0:t.revision)||0}setFramebufferId(e,t,i){var o;const r=(o=this.handyStylesMap.get(e))==null?void 0:o.layersById[t];r&&(r.framebufferId=i)}getFramebufferId(e,t){var r;const i=(r=this.handyStylesMap.get(e))==null?void 0:r.layersById[t];return i!=null&&i.drawToTarget?{ids:void 0,defaultId:this.modules.renderer.getDrawTargetFramebufferId(i.drawToTarget),isDrawTarget:!0}:{ids:i==null?void 0:i.framebufferId,defaultId:void 0,isDrawTarget:!1}}waitForStyle(e){const t=this.handyStylesMap.get(e);if(t)return Promise.resolve(t);const i=this.waitingStyleRequests.get(e);if(i)return i.promise;const r={resolve:void 0,promise:void 0};return r.promise=new Promise(o=>{r.resolve=o}),this.waitingStyleRequests.set(e,r),r.promise}addRemoveLayerHook(e,t){this.onRemoveLayerHooks.set(e,t)}getRemoveLayerHook(e){return this.onRemoveLayerHooks.get(e)}clearRemoveLayerHook(e){this.onRemoveLayerHooks.delete(e)}callCustomLayerRender(e){const t=this.customLayers.get(e);t&&t.renderFunction(this.modules.renderer.getRenderingContext())}getCustomSceneObjects(){const e=[];return this.customLayers.forEach(t=>e.push(t.sceneObject)),e}getMaxLayersCount(){return this.maxCountStyleLayers}getStyleLayerForObject(e){const t=this.getStyle(e.attributes.styleId);return t?t.layersById[e.attributes.layerId]:null}getFeatureFlag(e,t){const i=this.getStyle(this.modules.map.state.handyStyleId);return i?i.graphicsPresets[t][e]===!0:!1}getClearColor(){const{map:e}=this.modules,{state:t}=e,i=this.handyStylesMap.get(t==null?void 0:t.handyStyleId);if(!i)return t.defaultBackgroundColor;const r=n.makeBinderContext(t.styleZoom,t.pitch,t.styleState,[]),o=n.resolveColor(i.environment.style.skyColor,r),a=t.globeMode?t.globeRatioTarget:0;return n.lerp$3(Ch.value,i.background.color.value,o.value,a),Ch}update(){const e=this.getStyle(this.modules.map.state.handyStyleId);e&&(e.light.lightingModesResolved=n.resolveLightingModes(e.light.lightingModes,n.makeBinderContext(this.modules.map.state.styleZoom,this.modules.map.state.pitch,this.modules.map.state.styleState,[],!1)))}hasCustomLayers(){return this.customLayers.size>0}beginStyle(e){const t=this.styleIndex++,{state:i}=this.modules.map;if(!Number.isNaN(i.handyStyleId)){const r=this.getStyle(i.handyStyleId);r&&(r.layers.forEach(o=>{const a=this.onRemoveLayerHooks.get(o.innerId);if(a&&(a(i),e&&!e()))throw new Error("Map destroyed during style commit")}),this.onRemoveLayerHooks.clear())}return t}retainStyle(e){if(this.installedStyleIds.push(e),this.installedStyleIds.length>n.UNUSED_STYLE_ID_SHIFT){const t=this.installedStyleIds.shift();this.modules.assetManager.releaseStyleSvgRasters(t),this.handyStylesMap.delete(t)}}registerStyle(e){this.handyStylesMap.set(e.id,e),this.setMaxLayersCount(e.layers.length);const t=this.waitingStyleRequests.get(e.id);t&&t.resolve(e)}setLayerVisibility(e,t,i){const{id:r,type:o}=t;if(r&&i.layersById){const a=i.layerIdToInnerId[r];if(a){const l=i.layersById[a];if(l)l.style&&(l.style.visibility=e);else{const c=i.groupsById[a];c==null||c.layers.forEach(d=>{d&&d.style&&(d.style.visibility=e)})}}}o&&i.layers.forEach(a=>{a.type===o&&(a.style.visibility=e)})}initHandyLayer(e,t){let i;switch(t.type){case"group":t.layers.forEach(r=>this.initHandyLayer(e,r));return;case"heatmap":i=w2(t,e,this.modules);break;case"polygonExtrusion":i=this.initPolygonExtrusionLayer(e,t);break}i&&this.modules.styleManager.addRemoveLayerHook(t.innerId,i)}setMaxLayersCount(e){this.maxCountStyleLayers<e&&(this.maxCountStyleLayers=e)}initCustomLayer(e,t,i,r,o){const a={sceneObject:{type:n.SceneObjectType.Custom,attributes:{styleId:e,layerId:t.innerId,tileData:[]},tile:{zoomLevel:0},layerSettings:{},canRender:!0},layer:t,renderFunction:i};o==null||o(),this.customLayers.set(t.innerId,a),this.modules.styleManager.addRemoveLayerHook(t.innerId,()=>{r==null||r(),this.customLayers.delete(t.innerId)})}initPolygonExtrusionLayer(e,t){const i=this.getStyle(e);if(!i)return;let r=!1;return t.style.sideTextures.forEach((o,a)=>{var u;const l=(u=i==null?void 0:i.icons[o.image])==null?void 0:u.url;if(!l){console.warn(`Texture source for polygonExtrusionSideTexture ${o.image} not found inside style.`);return}const c=n.getUrlForIconMapIcon(l,i,"");this.modules.imageManager.loadTexture(c,{skipAtlasSizeChecking:!0,generateMipmaps:this.modules.renderer.isWebgl2Context(),minFilter:this.modules.renderer.isWebgl2Context()?C.LinearMipMapLinearFilter:C.LinearFilter,imagePadding:0,premultiplyAlpha:!0}).then(h=>{h!==void 0&&!r&&(t.sideTextureIndices[a]=h)})}),()=>{r=!0}}}class ni{constructor(){this.events={}}on(e,t){let i=this.events[e];return i||(i=this.events[e]=[]),i.push(t),this}once(e,t){const i=r=>{this.off(e,i),t.call(this,r)};return this.on(e,i),this}off(e,t){const i=this.events[e];if(!i)return this;const r=i.indexOf(t);return r!==-1&&i.splice(r,1),this}emit(e,t){const i=this.events[e];if(!i)return this;const r=i.slice();for(let o=0;o<r.length;o++)r[o].call(this,t);return this}}const Ss="gltfModels";let Ih=class{constructor(e,t){var i,r;this.modules=t,this.type="default",this.id=n.sourceUuid(),this.state=e,this.options={tileServer:e.tileServer,tileSet:e.tileSet,tileProtocol:e.tileProtocol,tileKey:e.tileKey,subdomains:e.subdomains,appId:e.appId,defaultLang:e.tileServerDefaultLang,sessionId:(i=e.tileSessionId)!=null?i:e.sessionId,isDefaultSource:!0,modelsPath:e.defaultSourceModelsRootUrl,sharedModelsPath:e.sharedModelsPath,promoteId:"id",idScope:n.DEFAULT_ID_SCOPE,identifyAsDefaultSource:!0},this.modelsAppearStrategy=(r=e.defaultSourceModelsAppearStrategy)!=null?r:n.DEFAULT_MODELS_APPEAR_STRATEGY,this.zenithSource=new n.ZenithSourceCore(this.id,this.modules,this.options),this.universeTileLayer=new n.TileLayer(0,n.tiles.maxUniverseZoom,0,n.tiles.maxUniverseZoom,this.modules,e,this.zenithSource,{requestOddTiles:e.mobileSdkMode,useExtendedTilesBounds:!0}),this.universeTileLayer.getLabelingData=()=>{const o=n.TileLayer.prototype.getLabelingData.call(this.universeTileLayer);return this.regionalTileLayer.isBlank()||(o.labelsKeys=[]),o},this.modules.tileManager.addTileLayer(this.universeTileLayer),this.regionalTileLayer=new n.TileLayer(n.tiles.maxUniverseZoom+1,n.tiles.maxRegionalZoom,n.tiles.maxUniverseZoom+1,n.tiles.maxDetailLevel,this.modules,e,this.zenithSource,{requestOddTiles:e.mobileSdkMode}),this.modules.tileManager.addTileLayer(this.regionalTileLayer),this.commercialPoiSource=new n.GeoJsonSourceCore(this.id,this.modules,{url:n.bindUrl("commercialPoi",{host:e.tileServer,tileSet:e.commercialTileSet,protocol:e.tileProtocol,lang:e.lang}),flipY:!0,identifyAsDefaultSource:!0,promoteId:"db_id"},this.state),this.commercialPoiTileLayer=new n.TileLayer(n.commercialPoi.minZoom,n.commercialPoi.maxZoom,n.commercialPoi.minZoom,n.GEOJSON_DEFAULT_MAX_DETAIL_LEVEL,this.modules,e,this.commercialPoiSource,{viewportPadding:n.MODELS_TILES_VIEWPORT_PADDING}),this.modules.tileManager.addTileLayer(this.commercialPoiTileLayer),this.createModelsSource(),this.modules.sourceStorage.addSource(this)}destroyModelsSource(){this.modelsSource&&(this.modelsSource=null,this.modelsTileLayer&&this.modules.tileManager.removeTileLayer(this.modelsTileLayer))}createModelsSource(){var e;this.modelsSource||(this.modelsSource=new n.GeoJsonSourceCore(this.id,this.modules,{minZoom:n.models.minZoom,maxZoom:n.models.maxZoom,url:n.bindUrl({url:this.state.modelsTilesUrl},{host:this.state.tileServer,tileSet:this.state.modelsTileSet,protocol:this.state.tileProtocol,lang:this.state.lang}),ignoreMissingTiles:!0,identifyAsDefaultSource:!0,promoteId:"building_id",modelsPath:(e=this.state.defaultSourceModelsRootUrl)!=null?e:n.bindUrl("gltfModel",{host:this.state.tileServer,tileSet:this.state.tileSet,protocol:this.state.tileProtocol,lang:this.state.lang}),flipY:!0,attributes:{sourceName:Ss}},this.state),this.modelsTileLayer=new n.TileLayer(n.models.minZoom,n.models.maxZoom,n.models.minZoom,n.tiles.maxDetailLevel,this.modules,this.state,this.modelsSource,{viewportPadding:n.MODELS_TILES_VIEWPORT_PADDING}),this.modules.tileManager.addTileLayer(this.modelsTileLayer))}getMemoryFootprint(){const e=I({regionalTileLayer:this.regionalTileLayer.memSizeJs(),universeTileLayer:this.universeTileLayer.memSizeJs(),modelsTileLayer:this.modelsTileLayer?this.modelsTileLayer.memSizeJs():{}},this.commercialPoiTileLayer&&{commercialPoiTileLayer:this.commercialPoiTileLayer.memSizeJs()}),t=I({regionalTileLayer:this.regionalTileLayer.memSizeGpu(),universeTileLayer:this.universeTileLayer.memSizeGpu(),modelsTileLayer:this.modelsTileLayer?this.modelsTileLayer.memSizeGpu():{}},this.commercialPoiTileLayer&&{commercialPoiTileLayer:this.commercialPoiTileLayer.memSizeGpu()});return{js:V(I({},e),{"--sum":n.getTotalMemory(e)}),gpu:V(I({},t),{"--sum":n.getTotalMemory(t)})}}destroy(){var e,t;this.modules.tileManager.removeTileLayer(this.universeTileLayer),this.universeTileLayer.destroy(),this.modules.tileManager.removeTileLayer(this.regionalTileLayer),this.regionalTileLayer.destroy(),this.zenithSource.destroy(),this.commercialPoiTileLayer&&(this.modules.tileManager.removeTileLayer(this.commercialPoiTileLayer),this.commercialPoiTileLayer.destroy()),(e=this.commercialPoiSource)==null||e.destroy(),this.modelsTileLayer&&(this.modules.tileManager.removeTileLayer(this.modelsTileLayer),this.modelsTileLayer.destroy()),(t=this.modelsSource)==null||t.destroy(),this.modules.sourceStorage.removeSource(this.id)}setAttributes(e){var t,i,r;this.zenithSource.setAttributes(I(I({},e),n.zenithSourceAttrs)),this.universeTileLayer.redraw(),this.regionalTileLayer.redraw(),(t=this.commercialPoiSource)==null||t.setAttributes(e),(i=this.commercialPoiTileLayer)==null||i.redraw(),(r=this.modelsSource)==null||r.setAttributes(V(I({},e),{sourceName:Ss})),this.modelsTileLayer&&this.modelsTileLayer.redraw()}getAttributes(){return this.zenithSource.getAttributes()}getId(){return this.id}getZoomDirection(){return this.regionalTileLayer.getZoomDirection()}setHoverId(e){this.regionalTileLayer.setHoverId(e)}setDisabledRegionsId(e){this.regionalTileLayer.disabledRegions=e,this.universeTileLayer.disabledRegions=e}resetHoverId(){this.regionalTileLayer.resetHoverId()}setFeatureStateMap(e){var t,i;this.zenithSource.setFeatureStateMap(e),(t=this.modelsSource)==null||t.setFeatureStateMap(e),this.universeTileLayer.onFeatureStateMapChange(),this.regionalTileLayer.onFeatureStateMapChange(),(i=this.modelsTileLayer)==null||i.onFeatureStateMapChange(),this.modules.modelLayer.onFeatureStateMapChange()}generateHoverTile(e,t,i,r,o,a,l,c){return this.zenithSource.generateTile(e,t,i,r,o,a,l,c)}generateModel(e){return this.zenithSource.generateModel(e)}isIdentifiedAsDefault(){return!0}setDataType(e){this.options.dt!==e&&(!this.options.dt||!e||!n.equalArrays(this.options.dt,e))&&(this.options.dt=e,this.regionalTileLayer.redraw())}getDataType(){return this.options.dt}setDataFilter(e){var t;this.zenithSource.setDataFilter(e),(t=this.modelsSource)==null||t.setDataFilter(e)}hasLayer(e){return this.modelsTileLayer===e||this.regionalTileLayer===e||this.universeTileLayer===e||this.commercialPoiTileLayer===e}};const M2=64;class H2 extends ni{constructor(e,t){super(),this.tieredModelKeys=new Set,this.sundaAtlases=new Map,this.sundaFontTextureIds=new n.TwoKeyMap,this.loadFont=(o,a)=>{let l=this.requestFontRanges.get(o,a);return l||(l=this.createLoadFontRequest(o,a),this.requestFontRanges.set(o,a,l)),l},this.invalidateUsedGltfModels=n.throttle(()=>{var c;const o=new Set;if(this.modules.renderer.isDestroyed)return;const a=this.modules.tileManager.getTileObjects();for(const d of a)for(const u of d.children){if(!Ba(u))continue;const{styleId:h,layerId:_,modelIndices:f,sourceId:m,sourceName:v}=u.attributes,g=this.modules.styleManager.getStyleLayer(h,_);if(!g||g.type!=="gltfModel")continue;const p=this.modules.modelsScene.getCurrentLayerModelId(u.attributes,u.tile);f.forEach(x=>{const S=this.getModel(x,h);if(S){o.add(S);return}if(p===x){const b=this.dataModelIdToUrl[x];if(b){const T=m===this.modules.defaultSource.getId()&&v===Ss;this.loadModel(b,x,h,!1,g,T)}else this.loadModelByIndex(x,h,g)}})}const l=this.modules.tileManager.getCachedMods();for(const d of l)(c=d.objects)==null||c.forEach(u=>{for(const h of u.children){if(!Ba(h))continue;const{styleId:_,layerId:f,modelIndices:m}=h.attributes,v=this.modules.styleManager.getStyleLayer(_,f);if(!v||v.type!=="gltfModel")return;m.forEach(g=>{const p=this.getModel(g,h.attributes.styleId);p&&o.add(p)})}});for(const d in this.models){const u=this.models[d];!u.preserve&&!o.has(u)&&u.status===gt.Loaded&&u.usedEmptyScene!==!0?this.removeModel(d):u.usedEmptyScene=!1}},n.workerResetInterval),this.state=e,this.modules=t,this.modelsWorker=new this.modules.workers.models.ModelsSource,this.requestedMetatiles=new Set,this.metatiles={},this.loadedRasters={},this.failedRasters={},this.requestedRasters={},this.svgRasterSetStates={},this.disableIconCache=e.disableIconCache,this.textures=[],this.fontGlyphs={},this.fontTextures=new n.TwoKeyMap,this.requestFontRanges=new n.TwoKeyMap,this.pendingFontRanges=0,this.loadedFontRanges=0,this.models={},this.dataModelIdToUrl={},this.visibleBuildingIds=new Set,this.metatileLoader=(o,a,l)=>{const c=n.hashToString(a);fetch(o).then(d=>{if(!d.ok)throw new Error(`Failed to load metatile "${c}"`);return d.json()}).then(d=>this.setMetatile(a,l,d)).catch(d=>console.error(d))};const i=(o,a)=>{const l=this.modules.styleManager.getStyle(o);if(!l){console.error(`Not found style ${o} in AssetManager#addNewRasterSets`);return}const{rasterSets:c}=l;a.forEach(d=>{c.byIndex[d.index]=d,c.byKey[d.key]=d})},{fnRegistry:r}=this.modules.workers;r.set("addNewRasterSets",i),r.set("loadFont",this.loadFont),this.setPreparedMetatile(-1,n.fixedMetatile),this.setPreparedMetatile(n.geoJsonMetatileHash,n.createGeoJsonMetatile(Array.from(this.state.modelShowHideEventsSublayers)))}getMemoryFootprint(){const e={textures:this.textures.map(n.textureSizeJs),fontTextures:this.fontTextures.reduce((i,r)=>(i.push(n.textureSizeJs(r)),i),[]),fontGlyphs:Object.values(this.fontGlyphs).reduce((i,r)=>Object.values(r).reduce((o,a)=>{var l,c;return o.push({bitmap:(c=(l=a.bitmap)==null?void 0:l.byteLength)!=null?c:0}),o},i),[]),models:Object.values(this.models).map(n.modelSizeJs).filter(i=>i.buffers.length>0||i.textures.length>0),sundaAtlases:Array.from(this.sundaAtlases.values()).map(i=>({canvas:i.canvas.width*i.canvas.height*4}))},t={textures:this.textures.map(n.textureSizeGpu),fontTextures:this.fontTextures.reduce((i,r)=>(i.push(n.textureSizeGpu(r)),i),[]),models:Object.values(this.models).map(n.modelSizeGpu).filter(i=>i.buffers.length>0||i.textures.length>0)};return{js:V(I({},e),{"--sum":n.getTotalMemory(e)}),gpu:V(I({},t),{"--sum":n.getTotalMemory(t)})}}fillDataModelUrlMap(e){for(const t in e)this.dataModelIdToUrl[e[t]]=t}getDataModelUrlById(e){return this.dataModelIdToUrl[e]}loadMetatile(e,t,i){this.requestedMetatiles.has(t)||(this.requestedMetatiles.add(t),this.metatileLoader(e,t,i))}setMetatile(e,t,i){n.renameZenithEnumerationValues(i),i.tileProps=i.tileProps.map(n.zenithToJakartaPropKey);const r=n.prepareMetatile(i);this.setPreparedMetatile(e,r),this.projectMetatileMetadata===void 0&&(this.projectMetatileMetadata={regionId:t,metatileHash:e})}setPreparedMetatile(e,t){this.metatiles[e]=t,this.modules.workers.parser.setMetatile(e,t)}prepareRasters(e,t,i){var c,d,u,h,_,f,m;const r=this.modules.styleManager.getStyle(e);if(!r){console.error(`Not found style ${e} in AssetManager#prepareRasters`);return}const{rasterSets:o}=r,a=7,l=t.length/a;for(let v=0;v<l;v++){const g=t[v*a],p=t[v*a+1],x=t[v*a+6],S=t[v*a+2],b=t[v*a+3],T=t[v*a+4],y=t[v*a+5],E=o.byIndex[g];if(E===void 0){console.error(`Not found raster set with index ${g}`);continue}const P=E.rasters[p];if(P!==void 0&&(P.x!==S||P.y!==b||P.atlasIndex!==x)){const L=g<<16|p;(c=this.loadedRasters[e])==null||c.delete(L),(d=this.failedRasters[e])==null||d.delete(L),(u=this.requestedRasters[e])==null||u.delete(L),(_=(h=this.svgRasterSetStates[e])==null?void 0:h[g])==null||_.uploadedRasterIndices.delete(p)}if(E.isSvg){const L={rasterIndex:p,rasterSetIndex:g,x:S,y:b,w:T,h:y,anchorX:E.anchorX,anchorY:E.anchorY,atlasIndex:x,isPacked:!0};E.rasters[p]=L;const D=(f=this.svgRasterSetStates[r.id])==null?void 0:f[g];D&&this.prepareSvgRaster(r,D,p).catch(B=>this.logSvgError(D,B))}else{const L=(m=E.rasters[p])!=null?m:{rasterIndex:p,rasterSetIndex:g,x:S,y:b,w:T,h:y,anchorX:0,anchorY:0,atlasIndex:x,isPacked:!0};E.rasters[p]=L,L.x=S,L.y=b,L.w=T,L.h=y,L.atlasIndex=x,L.isPacked=!0}this.textures[x]===void 0&&(this.textures[x]=new C(void 0,{size:n.atlasSize,flipY:!1,premultiplyAlpha:!Nf,magFilter:C.LinearFilter,minFilter:C.LinearFilter}),this.modules.renderer.prepareTexture(this.textures[x]));const A=this.textures[x],F=i&&i[v];if(F!==void 0){A.subImage(F,S,b),this.mirrorSundaAtlas(x,F,S,b,T,y),this.modules.renderer.addRerenderEvent();continue}}this.modules.workers.labeling.updatePackingInfo(e,t)}loadRasters(e){const i=e.length/3;for(let r=0;r<i;r++){const o=e[r*3],a=e[r*3+1],l=e[r*3+2],c=a<<16|l,d=this.modules.styleManager.getStyle(o);if(!d){console.error(`Not found style ${o} in AssetManager#loadRasters`);continue}if(this.loadedRasters[o]||(this.loadedRasters[o]=new Set,this.failedRasters[o]=new Set,this.requestedRasters[o]=new Set),this.requestedRasters[o].has(c))continue;const{rasterSets:u}=d,h=u.byIndex[a];if(h===void 0){console.error(`Not found raster set with index ${a}`);continue}const _=h.rasters[l];if(_===void 0){console.error(`Not found raster ${l} in raster set ${h.key}`);continue}if(_.isPacked===!1){console.error(`Try to load not packed raster ${h.key}`);continue}this.requestedRasters[o].add(c),h.isSvg?this.loadSvg(c,d,a):this.loadPng(c,d,a,l)}}removeRasterSet(e,t){const{key:i,index:r}=e;this.removeSvgRasterSetState(t,r),this.removeRasterSetLoadingState(e,t),e.rasters.length=0;const o=this.modules.styleManager.getStyle(t);o&&(delete o.rasterSets.byIndex[r],delete o.rasterSets.byKey[i])}releaseStyleSvgRasters(e){const t=this.svgRasterSetStates[e];t&&(delete this.svgRasterSetStates[e],Object.values(t).forEach(i=>{this.removeRasterSetLoadingState(i.rasterSet,e),this.disposeSvgRasterSetState(i)}))}getMetatile(e){return this.metatiles[e]}getProjectMetadata(){return this.projectMetatileMetadata}getFontGlyphs(e){return this.fontGlyphs[e]||{}}getFontTexture(e,t){return this.fontTextures.get(e,t)}isIdle(){let e=0,t=0;for(const i in this.requestedRasters)e+=this.requestedRasters[i].size,t+=this.loadedRasters[i].size+this.failedRasters[i].size;return e===t&&this.pendingFontRanges===this.loadedFontRanges&&this.allModelsLoaded()}dangerouslySetMetatiles(e){this.metatiles=e}dangerouslySetRasters(e,t){this.loadedRasters=e,this.failedRasters=t}loadModelByIndex(e,t,i){const r=this.getModelUniqueKey(e,t);if(this.models[r]!==void 0)return;const o=this.modules.styleManager.getStyle(t);if(o===void 0){n.logGltfError({layer:"prepare",message:"Style not found. Can't determine url"});return}const a=o.models[e];if(a===void 0){n.logGltfError({layer:"prepare",message:`Model with index "${e}" is missing in the style.`});return}const l=n.getModelUrl(a.url,o);this.fetchModel(l,e,r,!1,i,!1)}loadModel(e,t,i,r,o,a,l){const c=this.getModelUniqueKey(t,i);if(this.models[c]!==void 0){l==null||l();return}this.fetchModel(e,t,c,r,o,a,l)}getModel(e,t){return this.models[this.getModelUniqueKey(e,t)]}allModelsLoaded(){for(const e in this.models)if(this.models[e].status===gt.Pending)return!1;return!0}isModelLoaded(e,t){const i=this.models[this.getModelUniqueKey(e,t)];return i&&i.status===gt.Loaded}clearSundaRegistrations(){for(const e in this.models)for(const t of this.models[e].scenes)for(const i of t.objects)i.sundaGltf=void 0;this.sundaAtlases.clear(),this.sundaFontTextureIds=new n.TwoKeyMap}remirrorSundaAtlases(){if(this.state.sunda)for(const e in this.loadedRasters){const t=this.modules.styleManager.getStyle(Number(e));if(t)for(const i of this.loadedRasters[e]){const r=i>>16,o=i&65535,a=t.rasterSets.byIndex[r];a&&(a.isSvg?this.loadSvg(i,t,r):this.loadPng(i,t,r,o))}}}getSundaFontTextureId(e,t){const i=this.modules.sunda.ledger;if(!i||!this.state.sunda)return;const r=this.fontTextures.has(e,t)?e:n.DEFAULT_FONT;let o=this.sundaFontTextureIds.get(r,t);if(o===void 0){const a=this.fontTextures.get(r,t),l=a==null?void 0:a.getSource(),c=a==null?void 0:a.options.size;if(!(l instanceof Uint8Array)||!c)return;const d=new Uint8Array(l.length*4);for(let u=0;u<l.length;u++)d[u*4+3]=l[u];o=n.uniqId(),i.uploadTexture(o,d.buffer,c[0],c[1]),this.sundaFontTextureIds.set(r,t,o)}return o}getSundaAtlasTextureId(e){const t=this.modules.sunda.ledger;if(!t||!this.state.sunda)return;const i=this.sundaAtlases.get(e);if(i){if(i.dirtyRects===null||i.textureId===void 0){const{width:r,height:o}=i.canvas,a=i.ctx.getImageData(0,0,r,o),l=i.textureId,c=n.uniqId();t.uploadTexture(c,a.data.buffer,r,o),l!==void 0&&t.deleteTextures([l]),i.textureId=c,i.dirtyRects=[]}else if(i.dirtyRects.length>0){for(const r of i.dirtyRects){const o=i.ctx.getImageData(r.x,r.y,r.w,r.h);t.patchTexture(i.textureId,o.data.buffer,r.x,r.y,r.w,r.h)}i.dirtyRects.length=0}return i.textureId}}removeModel(e){var o,a;const t=this.models[e];if(!t)return;const i=new Set,r=new Set;for(const l of t.scenes)l.objects.forEach(c=>{c.elementsBuffer&&c.elementsBuffer.remove();const d=c.sundaGltf;if(d){i.add(d.vertexBufferId),i.add(d.indexBufferId);for(const u of[d.colorTextureId,d.aoTextureId,d.pbrTextureId])u!==void 0&&r.add(u)}}),l.objects.splice(0,l.objects.length);this.modules.map.state.sunda&&(i.size>0&&((o=this.modules.sunda.ledger)==null||o.deleteTileBuffers([...i])),r.size>0&&((a=this.modules.sunda.ledger)==null||a.deleteTextures([...r]))),t.scenes.splice(0,t.scenes.length),t.buffers.forEach(l=>{l instanceof n.Buffer&&l.remove()}),t.buffers=[],t.textures.forEach(l=>l.remove()),t.textures=[],delete this.models[e],this.tieredModelKeys.delete(e)}getTieredModelKeys(){return this.tieredModelKeys}getModelUniqueKey(e,t){return e>=0?`${t},${e}`:String(e)}mirrorSundaAtlas(e,t,i,r,o,a){if(!this.state.sunda)return;let l=this.sundaAtlases.get(e);if(!l){const c=document.createElement("canvas");c.width=n.atlasSize[0],c.height=n.atlasSize[1];const d=c.getContext("2d");if(!d)return;l={canvas:c,ctx:d,dirtyRects:null,textureId:void 0},this.sundaAtlases.set(e,l)}l.ctx.clearRect(i,r,o,a),l.ctx.drawImage(t,i,r,o,a),l.dirtyRects&&(l.dirtyRects.push({x:i,y:r,w:o,h:a}),l.dirtyRects.length>M2&&(l.dirtyRects=null))}fetchModel(e,t,i,r,o,a,l){const{renderer:c}=this.modules,d=this.models[i]=w0(r);this.modelsWorker.loadModel(e,this.state.dracoDecoderUrl).then(u=>{if(u.type==="ok"){if(d.status=gt.Loaded,!u.result)return;k0(d,c,u.result,t,o,a,this.modules),d.isTiered&&this.tieredModelKeys.add(i),this.emit("modelloaded",t),this.modules.renderer.addRerenderEvent(),l==null||l()}else n.logGltfError(u),d.status=gt.Failed})}createLoadFontRequest(e,t){return q(this,null,function*(){this.pendingFontRanges+=1;const i=Number.isNaN(this.state.handyStyleId)?Eh:this.state.handyStyleId;try{const r=yield this.modules.styleManager.waitForStyle(i),o=yield fetch(n.getFontUrl(e,t,r)).then(l=>{if(!l.ok)throw new Error;return l}).catch(()=>{throw new Error(`Could not load font ${e} for range ${t}`)}).then(l=>l.arrayBuffer()),a=n.processFont(o);return this.prepareFontAtlas(e,t,a),this.modules.workers.labeling.appendFont(e,n.getGlyphMetrics(a.glyphData)),this.loadedFontRanges+=1,this.modules.workers.labeling.markFontAsLoaded(e,t)}catch(r){return this.loadedFontRanges+=1,e!==n.DEFAULT_FONT?this.loadFont(n.DEFAULT_FONT,t):(console.error(r),this.modules.workers.labeling.markFontAsLoaded(e,t))}})}prepareFontAtlas(e,t,i){const{bitmap:r,width:o,height:a,glyphData:l}=i;this.fontGlyphs[e]||(this.fontGlyphs[e]={});for(const d in l)this.fontGlyphs[e][d]=l[d];const c=new C(new Uint8Array(r),{size:[o,a],magFilter:C.LinearFilter,minFilter:C.LinearFilter,format:C.AlphaFormat,premultiplyAlpha:!1,flipY:!1});this.fontTextures.set(e,t,c),this.state.needLabeling=!0}loadPng(e,t,i,r){return q(this,null,function*(){const o=t.rasterSets.byIndex[i],a=o.rasters[r];let l="";if(o.type===n.RasterSetType.Unique){const c=o.id;o.url?l=n.getSizeDependentImageUrl(o.url,a.w,a.h):l=n.getUrl("dynamicPoi",{host:this.state.tileServer,tileSet:this.state.tileSet,protocol:this.state.tileProtocol,subdomain:n.getSubdomainFromString(this.state.subdomains,c),id:c,width:a.w.toString(),height:a.h.toString(),regionId:String(o.regionId)})}else if(o.type===n.RasterSetType.Static){const c=t.icons[o.name];if(!c){console.error(`There is no appropriate icon config in the style for raster set: "${o.name}"`),this.failedRasters[t.id].add(e);return}l=n.getUrlForIconMapIcon(c.url,t,n.getSubdomainFromString(this.state.subdomains,o.name))}this.modules.workers.parser.prepareAtlas(l).then(c=>q(this,null,function*(){const d=this.textures[a.atlasIndex];if(c){if(c.isBitmap){if((c.data[0].width!==a.w||c.data[0].height!==a.h)&&o.type===n.RasterSetType.Static){if(a.w<=0||a.h<=0)return;const u=document.createElement("canvas");u.width=a.w,u.height=a.h,u.getContext("2d").drawImage(c.data[0],0,0,u.width,u.height),d.subImage(u,a.x,a.y),this.mirrorSundaAtlas(a.atlasIndex,u,a.x,a.y,a.w,a.h)}else d.subImage(c.data[0],a.x,a.y),this.mirrorSundaAtlas(a.atlasIndex,c.data[0],a.x,a.y,c.data[0].width,c.data[0].height);this.modules.renderer.addRerenderEvent()}else es(c.data[0]).then(u=>{d.subImage(u,a.x,a.y),this.mirrorSundaAtlas(a.atlasIndex,u,a.x,a.y,u.width,u.height),this.modules.renderer.addRerenderEvent()});this.loadedRasters[t.id].add(e),o.isReady=!0}else this.failedRasters[t.id].add(e)}))})}loadSvg(e,t,i){return q(this,null,function*(){const r=t.rasterSets.byIndex[i];this.svgRasterSetStates[t.id]||(this.svgRasterSetStates[t.id]={});let o=this.svgRasterSetStates[t.id][i];if(o&&o.rasterSet!==r&&(this.removeSvgRasterSetState(t.id,i),o=void 0),!o){if(!t.iconBaseUrl){console.error(`Attempt to load svg without existing style for raster set: "${r.name}"`),this.failedRasters[t.id].add(e);return}const a=t.icons[r.name];if(!a){console.error(`There is no appropriate icon config in the style for raster set: "${r.name}"`),this.failedRasters[t.id].add(e);return}const l=n.getUrlForIconMapIcon(a.url,t,n.getSubdomainFromString(this.state.subdomains,r.name)),c=fetch(l,{cache:this.disableIconCache?"no-cache":"default"}).then(d=>{if(!d.ok)throw new Error("Not 2xx response");return d.text()});o={rasterSet:r,fetchPromise:c,rasterPromises:new Map,uploadedRasterIndices:new Set,errorLogged:!1},this.svgRasterSetStates[t.id][i]=o}try{yield Promise.all(r.rasters.map(a=>this.prepareSvgRaster(t,o,a.rasterIndex))),this.isSvgRasterSetStateCurrent(t,o)&&(this.loadedRasters[t.id].add(e),r.isReady=!0)}catch(a){this.logSvgError(o,a),this.isSvgRasterSetStateCurrent(t,o)&&this.failedRasters[t.id].add(e)}})}prepareSvgRaster(e,t,i){if(t.uploadedRasterIndices.has(i))return Promise.resolve();const r=t.rasterPromises.get(i);if(r)return r;const o=this.uploadSvgRaster(e,t,i);return t.rasterPromises.set(i,o),o.then(()=>this.finishSvgRasterPreparing(t,i,o),()=>this.finishSvgRasterPreparing(t,i,o)),o}uploadSvgRaster(e,t,i){return q(this,null,function*(){const r=yield this.getSvgImage(t);if(!this.isSvgRasterSetStateCurrent(e,t))return;const o=t.rasterSet.rasters[i];if(o){if(o.w>0&&o.h>0){const a=this.textures[o.atlasIndex];r.width=o.w,r.height=o.h,a.subImage(r,o.x,o.y),this.mirrorSundaAtlas(o.atlasIndex,r,o.x,o.y,o.w,o.h),this.modules.renderer.addRerenderEvent()}t.uploadedRasterIndices.add(i)}})}getSvgImage(e){return e.imagePromise||(e.imagePromise=e.fetchPromise.then(t=>{const{url:i,revokeURL:r}=d0(t);return c0(i).then(o=>(r==null||r(),o),o=>{throw r==null||r(),o})})),e.imagePromise}finishSvgRasterPreparing(e,t,i){e.rasterPromises.get(t)===i&&e.rasterPromises.delete(t)}removeSvgRasterSetState(e,t){var r;const i=(r=this.svgRasterSetStates[e])==null?void 0:r[t];i&&(delete this.svgRasterSetStates[e][t],this.disposeSvgRasterSetState(i))}disposeSvgRasterSetState(e){var t;(t=e.imagePromise)==null||t.then(i=>i.remove(),()=>{})}removeRasterSetLoadingState(e,t){e.rasters.forEach(({rasterSetIndex:i,rasterIndex:r})=>{var a,l,c;const o=i<<16|r;(a=this.loadedRasters[t])==null||a.delete(o),(l=this.failedRasters[t])==null||l.delete(o),(c=this.requestedRasters[t])==null||c.delete(o)})}isSvgRasterSetStateCurrent(e,t){var r;const i=t.rasterSet.index;return((r=this.svgRasterSetStates[e.id])==null?void 0:r[i])===t&&e.rasterSets.byIndex[i]===t.rasterSet}logSvgError(e,t){e.errorLogged||(e.errorLogged=!0,console.error(`Can't load an SVG for the "${e.rasterSet.name}" raster set. Error: `,t))}}class G2{constructor(e,t,i,r,o,a,l,c){this.modules=e,this.mapState=t,this.cache=i,this.maxStyleZoom=-1/0,this.minStyleZoom=1/0,this.ready=!1,this.useful=!1,this.status="initial",this.model=r,this.key=o,this.selectedIds=a,this.styleId=l,this.styleRevision=c,this.modelRevision=r.revision,this.objects=[]}update(){switch(this.status){case"initial":{this.useful&&(this.loadModel(),this.status="generating");break}case"generating":{if(this.useful&&this.processResponse&&this.model.texturesLoaded){const{objects:{data:e}}=this.processResponse;this.objects=Z2(e,this.modules),this.updateMinAndMaxStyleZoom(this.objects),this.status="generated",this.ready=!0,this.cache.add(this.key,this)}break}}}getIdentifyIds(){var e;return(e=this.processResponse)==null?void 0:e.objects.identifyIds}remove(){this.status==="generated"&&this.cache.remove(this.key),this.status="initial",this.objects.length&&(this.objects.forEach(e=>e.clean(this.mapState)),this.objects=[]),this.ready=!1}canBeRemoved(){return this.status==="initial"}loadModel(){const{model:{regionId:e,metatileHash:t,id:i,sourceModel:{fileName:r,matrix:o,offset:a}}}=this,c={url:n.getUrl("model",{host:this.mapState.tileServer,tileSet:this.mapState.tileSet,protocol:this.mapState.tileProtocol,subdomain:n.getSubdomainFromString(this.mapState.subdomains,r),regionId:e.toString(),name:r}),id:i,regionId:e,metatileHash:t,selected:this.selectedIds.some(d=>d===i),pixelRatio:window.devicePixelRatio,styleState:this.mapState.styleState,styleId:this.mapState.handyStyleId,offset:a,matrix:o};this.modules.defaultSource.generateModel(c).then(d=>{this.model.prepareTextures(d.textures),this.processResponse=d})}updateMinAndMaxStyleZoom(e){this.minStyleZoom=Math.min(...e.map(t=>Math.min(...t.children.map(i=>{var o;const r=this.modules.styleManager.getStyleLayer(i.attributes.styleId,i.attributes.layerId);return(r==null?void 0:r.type)==="dem"?1/0:(o=r==null?void 0:r.minzoom)!=null?o:-1/0})))),this.maxStyleZoom=Math.max(...e.map(t=>Math.max(...t.children.map(i=>{var o;const r=this.modules.styleManager.getStyleLayer(i.attributes.styleId,i.attributes.layerId);return(r==null?void 0:r.type)==="dem"?-1/0:(o=r==null?void 0:r.maxzoom)!=null?o:1/0}))))}}function V2(s,e,t,i,r){const o=e.join("|");return`model=${s}_sId=${t}_sRev=${i}_mRev=${r}_sel=${o}`}function Z2(s,e){var o,a,l;const t=new Ah(s,e),i=[],r=Ph((l=(a=(o=t.children[0])!=null?o:t.identifyChildren[0])!=null?a:t.depthTestChildren[0])!=null?l:t.shadowChildren[0]);return r&&["children","identifyChildren","depthTestChildren","shadowChildren"].forEach(c=>{var h;const d=(h=t.modelMatrices.get(0))!=null?h:n.create$2();n.copy(d,r),t.modelMatrices.set(0,d);let u=t[c].length;for(;u--;){const _=t[c][u],f=Ph(_);if(!f||n.exactEquals(d,f))continue;let m=i.find(v=>{const g=v.modelMatrices.get(0);return g?n.exactEquals(g,f):!1});m||(m=new Ah([],e),m.modelMatrices.set(0,n.copy(n.create$2(),f)),i.push(m)),m[c].push(_),_.tile=m,t[c].splice(u,1)}}),[t,...i]}function Ph(s){if(s&&"matrix"in s.attributes)return s.attributes.matrix}class Ah extends n.TileObjectBase{constructor(e,t){super("model");const{identifier:i}=t;n.spreadTileObjects(t,e,this,i.getIdScope(n.DEFAULT_ID_SCOPE)),this.size=n.tileZoomToSize(this.coords[2]),this.zoomLevel=this.coords[2],this.detailLevel=this.coords[3]}setTileCoords(e,t){}syncReplicas(e){}}class W2{constructor(e,t,i,r,o,a){var l;this.modules=e,this.mapState=t,this.cache=i,this.regionId=r,this.metatileHash=o,this.sourceModel=a,this.revision=0,this.texturesLoaded=!1,this.textures=[],this.readiness=0,this.id=a.id,this.attributes=(l=a.attributes)!=null?l:{},this.readinessTickerName=`model-readiness-${this.id}`,this.ids=e.identifier.getIdScope(n.DEFAULT_ID_SCOPE)}update(){var e,t;(e=this.currentMod)!=null&&e.useful&&this.currentMod.update(),(t=this.newMod)!=null&&t.useful&&this.newMod.update(),n.update(this.readinessTickerName,{step:(i,r)=>this.readiness=r},this.mapState)}isAnimating(){return n.exist(this.readinessTickerName,this.mapState)}commitMod(){this.newMod&&this.newMod.ready&&(this.currentMod=this.newMod,this.newMod=void 0)}setUsefulMod(){const e=this.mapState.handyStyleId,t=this.modules.styleManager.getStyleRevision(e),i=this.ids.getSelected().filter(r=>r===this.id);if(!this.currentMod&&!this.newMod){this.createNewMod(i,e,t,this.revision);return}if(this.currentMod&&n.deepEqual(this.currentMod.selectedIds,i)&&this.currentMod.styleId===e&&this.currentMod.styleRevision===t&&this.currentMod.modelRevision===this.revision){this.currentMod.useful=!0,this.newMod=void 0;return}if(this.newMod){n.deepEqual(this.newMod.selectedIds,i)&&this.newMod.styleId===e&&this.newMod.styleRevision===t&&this.newMod.modelRevision===this.revision?this.newMod.useful=!0:this.createNewMod(i,e,t,this.revision);return}this.createNewMod(i,e,t,this.revision)}getUsefulMod(){if(this.currentMod&&this.currentMod.useful)return this.currentMod;if(this.newMod&&this.newMod.useful)return this.newMod}getCurrentMod(){return this.currentMod}setAllModsNeedless(){this.currentMod&&(this.currentMod.useful=!1),this.newMod&&(this.newMod.useful=!1)}getOpacity(e){return this.readiness*this.modules.buildingHeightAnimator.getBuildingHeight(e)}getTexture(e){return this.textures[e]}prepareTextures(e){this.texturesLoaded||(e.isBitmap?(this.textures=e.data.map(t=>new C(t,{flipY:!1})),this.texturesLoaded=!0,this.startReadinessTicker()):Promise.all(e.data.map(t=>es(t))).then(t=>{this.textures=t.map(i=>new C(i,{flipY:!1})),this.texturesLoaded=!0,this.startReadinessTicker()}))}clean(){this.canBeCleaned()&&(this.texturesLoaded&&(this.textures.forEach(e=>e.remove()),this.textures=[],this.texturesLoaded=!1),this.stopReadinessTicker())}canBeCleaned(){return(!this.currentMod||this.currentMod.canBeRemoved())&&(!this.newMod||this.newMod.canBeRemoved())}createNewMod(e,t,i,r){const o=V2(this.id,e,t,i,r),a=this.cache.get(o);a?(this.newMod=a,this.newMod.useful=!0):this.newMod=new G2(this.modules,this.mapState,this.cache,this,o,e,t,i)}startReadinessTicker(){this.readiness=0,n.start(this.readinessTickerName,{easing:n.buildingAnimation.easing},this.mapState,0,1,n.buildingAnimation.duration,1)}stopReadinessTicker(){this.readiness=0,n.stop(this.readinessTickerName,this.mapState)}}class j2{constructor(e,t){this.mapState=e,this.modules=t,this.buildingsHeight=new Map,this.models=new Map,this.displayedMods=new Map,this.viewportModels=[],this.requestedModelsInfo=new Set,this.loadedModelsInfo=new Set,this.isStyleUpdateInProgress=!1,this.hiddenBuildingIds=new Set,this.cache=new n.LRU(n.modelCacheSize,(i,r)=>r.remove()),this.ids=t.identifier.getIdScope(n.DEFAULT_ID_SCOPE)}onFeatureStateMapChange(){this.models.forEach(e=>{e.revision++})}update(){this.findViewportModels(),this.mapState.styleZoom>n.loadModelsInfoStyleZoom&&this.modules.tileManager.getViewportTiles().forEach(e=>{e.type==="zenith"&&e.serverMetadata&&e.serverMetadata.forEach(t=>{const i=this.modules.sourceStorage.getSourceById(e.sourceId);if(i!==void 0&&"getUrl"in i){const r=i.getUrl("modelInfo",{regionId:t.regionId.toString()});this.loadModelsInfo(r,t.regionId,t.metatileHash)}else{const r=n.getUrl("modelInfo",{host:this.mapState.tileServer,tileSet:this.mapState.tileSet,protocol:this.mapState.tileProtocol,subdomain:this.mapState.subdomains[0],regionId:t.regionId.toString()});this.loadModelsInfo(r,t.regionId,t.metatileHash)}})}),this.models.forEach(e=>e.setAllModsNeedless()),this.viewportModels.forEach(e=>e.setUsefulMod()),this.models.forEach(e=>e.update()),this.isStyleUpdateInProgress||this.models.forEach(e=>e.commitMod()),this.updateScene(),this.cleanUnnessasaryModels(),this.updateObjectsVisibility()}activateStyleUpdating(){this.isStyleUpdateInProgress=!0}finishStyleUpdating(){this.isStyleUpdateInProgress=!1}redraw(){this.cache.reset(),this.cleanUnnessasaryModels()}isModelsInfoLoaded(e){return this.loadedModelsInfo.has(e)}getTexture(e,t){var i;return(i=this.models.get(e))==null?void 0:i.getTexture(t)}getDisplayedIdentifyData(){const e=[];return this.viewportModels.forEach(t=>{const i=t.getUsefulMod();if(!i)return;const r=i.getIdentifyIds();r&&e.push({metatileHash:t.metatileHash,ids:r})}),e}getOpacity(e,t){var i;return((i=this.models.get(e))==null?void 0:i.getOpacity(t))||0}hasModel(e){return this.models.has(e)}setBuildingHeight(e,t){this.buildingsHeight.set(e,t)}getBuildingHeight(e){return this.buildingsHeight.get(e)||0}isHidden(e){return this.ids.isHidden(e)}getVisibleModelData(e){const t=this.models.get(e);if(!t)return;const i=t.getCurrentMod();if(!i||!i.ready)return;const r=Math.max(t.sourceModel.minZoom,i.minStyleZoom),o=Math.min(t.sourceModel.maxZoom,i.maxStyleZoom),{styleZoom:a}=this.mapState;if(!(a<r||a>=o))return{minStyleZoom:r,maxStyleZoom:o,opacity:this.getOpacity(e,r)}}isIdle(){return this.viewportModelsReady()&&!this.viewportModels.some(e=>e.isAnimating())}viewportModelsReady(){return this.viewportModels.every(e=>{const t=e.getUsefulMod();return t&&t.ready})}setHiddenBuildingIds(e){e.forEach(t=>{this.hiddenBuildingIds.add(t)})}unsetHiddenBuildingIds(e){e.forEach(t=>{this.hiddenBuildingIds.delete(t)})}findViewportModels(){const{styleZoom:e}=this.mapState;this.viewportModels=[],this.models.forEach(t=>{const{bound:i,minZoom:r,maxZoom:o}=t.sourceModel;if(e<r||e>=o)return;const a=this.mapState.styleState._activeFloorIds,l=t.attributes.db_hidden_by_plan_id;if(l&&a.includes(l)||this.modules.floorManager.hasDisplayedFloorBuilding([t.id])||!!!this.modules.assetManager.getMetatile(t.metatileHash)||this.hiddenBuildingIds.has(t.id))return;n.tetragonIntersectsBounds(this.mapState.tilesBounds,i)&&this.viewportModels.push(t)})}updateScene(){let e=!1;const t=new Map;this.viewportModels.forEach(i=>{const r=i.getCurrentMod();r&&r.ready&&t.set(r.key,r)}),this.displayedMods.forEach((i,r)=>{t.has(r)||(i.objects.length&&i.objects.forEach(o=>this.modules.tileManager.removeObject(o)),e=!0)}),t.forEach((i,r)=>{this.displayedMods.has(r)||(i.objects.length&&i.objects.forEach(o=>this.modules.tileManager.addObject(o)),e=!0),this.cache.get(r)}),e&&(this.displayedMods=t,this.modules.renderer.addRerenderEvent(),this.modules.identifier.resetCache())}cleanUnnessasaryModels(){const e=new Set(this.cache.getData().map(t=>t.model));this.models.forEach(t=>{e.has(t)||t.clean()})}loadModelsInfo(e,t,i){this.requestedModelsInfo.has(t)||(this.requestedModelsInfo.add(t),fetch(e).then(r=>{if(!r.ok)throw new Error(`Failed to load models info for region ${t}`);return r.json()}).then(r=>{r.forEach(o=>{if(!o.fileName){console.error(`ZBM source "fileName" is empty. Failed to load model by url: ${e}`);return}const a=new W2(this.modules,this.mapState,this.cache,t,i,o);this.models.set(a.id,a)}),this.loadedModelsInfo.add(t)}).catch(r=>{this.loadedModelsInfo.add(t),console.error(r)}))}updateObjectsVisibility(){const e=this.ids;this.models.forEach(t=>{var o;const i=((o=this.getVisibleModelData(t.id))==null?void 0:o.opacity)||0,r=e.isHidden(t.id,n.HideLevel.PolygonExtrusion);i>=.5&&!r?e.hide([t.id],n.HideLevel.PolygonExtrusion):i<.5&&r&&e.show([t.id])})}}class X2{constructor(e){this.modules=e,this.isIdle=()=>!this.isGenerating,this.modCache=new Map,this.isGenerating=!1,this.currentPois=[],this.currentIdSet=new Set,this.currentTrafficState=!1,this.currentSelectedIds=[],this.currentModKey=Lh(this.currentTrafficState,this.currentSelectedIds),this.ids=e.identifier.getIdScope(n.DEFAULT_ID_SCOPE)}setPersonalPoi(e){this.currentPois=e;const t=new Set;for(const i of e)t.add(i.id);this.currentIdSet=t,this.modCache.clear(),this.displayedModKey=void 0}redraw(){this.modCache.clear(),this.displayedModKey=void 0}getIdentifyDataChunk(){return this.identifyDataChunk}update(){if(this.regionMetadata===void 0&&(this.regionMetadata=this.modules.assetManager.getProjectMetadata()),this.regionMetadata===void 0)return;this.updateModKey();const e=this.currentModKey,t=this.modCache.get(e);t===void 0&&!this.isGenerating&&this.generate(e,this.currentPois,this.regionMetadata),t!==void 0&&e!==this.displayedModKey&&this.show(e,t,this.regionMetadata)}generate(e,t,i){const{regionId:r,metatileHash:o}=i,a=this.modules.map.state;this.isGenerating=!0,this.modules.workers.parser.generatePersonalPoi(t,r,o,window.devicePixelRatio,this.ids.getSelected(),a.handyStyleId,a.styleState,this.modules.defaultSource.getId()).then(l=>{if(l===void 0){this.isGenerating=!1;return}const{collectorOutput:c,styleId:d}=l,{packedRasters:u,rastersToLoad:h}=c;u!==void 0&&this.modules.assetManager.prepareRasters(d,u),this.modules.assetManager.loadRasters(h),this.modCache.set(e,l),this.isGenerating=!1})}show(e,t,i){const{metatileHash:r}=i,{collectorOutput:{labels:o,identifyIds:a},styleId:l}=t;this.modules.labeler.removeLabels("ppoi"),o.length&&this.modules.labeler.addLabels("ppoi",n.LabelSource.PersonalPoi,[{metatileHash:r,labels:o,styleId:l}]),this.identifyDataChunk={metatileHash:r,ids:a},this.modules.identifier.resetCache(),this.displayedModKey=e}updateModKey(){const e=this.ids.getSelected().filter(i=>this.currentIdSet.has(i)),t=this.modules.trafficTileLayer.isEnabled();(!n.deepEqual(this.currentSelectedIds,e)||this.currentTrafficState!==t)&&(this.currentTrafficState=t,this.currentSelectedIds=e,this.currentModKey=Lh(t,e))}}function Lh(s,e){return`ppoi_${s}_${e.join("|")}`}let el=(ji=class extends n.Evented{constructor(e,t){super(),this.fogFactorBreakpoint=.4,this.demElevation=0,this.demTilesRevision=NaN,this.hasExplicitZ=!1,this.destroyed=!1,this.throttledResolveTierData=n.throttle(()=>{if(this.destroyed)return;this.resolveTierData()&&this.modules.renderer.addRerenderEvent()},yo),this.options=n.applyDefaults(t,ji.options),this.uniqId=String(n.uniqId()),this.labelKey=`html-${this.uniqId}`,this.modules=e.modules,this.mapState=e.state,this.hasExplicitZ=this.options.coordinates.length===3;const i=n.Mercator.fromGeo(this.options.coordinates);this.position={userValue:i,normalizedValue:n.normalizeMapPoint(i)},this.tierHeightResolver=new Tr(this.modules,this.mapState,()=>this.position.normalizedValue,()=>this.options.tier,()=>this.hasExplicitZ),this.screenPoint=[0,0],this.html=Q2(this.options),this.isHidden=!0,this.targetOpacity=0,this.modules.layers.addLayer(this),this.modules.scheduler.register(this,wt.Update),this.rounder=J2(!this.options.disableRounding);let{offset:r}=this.options;const{labeling:o}=this.options;o.type!=="none"&&(o.offset!==void 0&&(r=o.offset),this.modules.labeler.addLabelBox(this.labelKey,{id:this.uniqId,width:o.width,height:o.height,position:this.position.normalizedValue,offset:r,labelingGroup:this.getLabelingGroup(),parentPoiId:o.type==="pinnedToPoi"?o.poiId:void 0}))}get entityId(){return this}destroy(){this.destroyed=!0,this.removeHtml(),this.modules.labeler.removeLabels(this.labelKey),this.modules.layers.removeLayer(this),this.modules.scheduler.markDestroyed(this)}update(){this.refreshTierData();const e=this.checkZoom(),t=this.checkFog(),i=!this.isInvolvedInLabeling()||this.modules.labeler.isLabelBoxSurvived(this.uniqId);e&&t&&i?this.show():this.hide(),this.updatePosition()}setZIndex(e){this.options.zIndex=e,this.html.style.zIndex=String(e)}setContent(e){this.options.html=e,this.html.innerHTML="";const t=document.createElement("div");typeof e=="string"?t.innerHTML=e:t.append(e),this.html.append(t)}setLabelingSize(e,t){this.options.labeling.type!=="none"&&(this.options.labeling.width=e,this.options.labeling.height=t,this.updateLabelBox())}setPosition(e){this.hasExplicitZ=e.length===3,this.tierHeightResolver.reset(!0);const t=n.Mercator.fromGeo(e);this.position={userValue:t,normalizedValue:n.normalizeMapPoint(t)},this.mapState.demMode&&this.updateDemElevation(),this.updateLabelBox()}setOffset(e){this.options.offset=[e[0],e[1]],this.updateLabelBox()}setMinZoom(e){this.options.minZoom=e}setMaxZoom(e){this.options.maxZoom=e}getZIndex(){return this.options.zIndex}getOffset(){return this.options.offset}getPosition(){return n.Mercator.toGeo(this.position.userValue)}getHtmlElement(){return this.html.firstChild}dangerouslyGetRootElement(){return this.html}isShown(){return!this.isHidden}show(){if(this.isHidden&&(this.isHidden=!1,this.appendHtml(),this.emit("shown",{id:this.uniqId.toString(),point:[this.screenPoint[0],this.screenPoint[1]],object:this}),this.options.animate)){if(this.showAnimationTimer)return;this.hideAnimationTimer&&(clearTimeout(this.hideAnimationTimer),this.hideAnimationTimer=void 0),this.targetOpacity!==1&&(this.showAnimationTimer=window.setTimeout(()=>{this.setHtmlOpacity(1),this.showAnimationTimer=void 0},0))}}hide(){if(!this.isHidden)if(this.isHidden=!0,this.options.animate){if(this.hideAnimationTimer)return;this.showAnimationTimer&&(clearTimeout(this.showAnimationTimer),this.showAnimationTimer=void 0),this.setHtmlOpacity(0),this.hideAnimationTimer=window.setTimeout(()=>{this.removeHtml(),this.hideAnimationTimer=void 0},this.options.duration)}else this.removeHtml()}setHtmlOpacity(e){this.html.style.opacity=String(e),this.targetOpacity=e}removeHtml(){this.html.remove(),this.screenPoint=[0,0]}appendHtml(){this.getMarkerContainer().appendChild(this.html)}getMarkerContainer(){return this.options.preventMapInteractions?this.modules.layout.htmlContainerOutMap:this.modules.layout.htmlContainerInMap}updateDemElevation(){var e;this.demElevation=(e=this.modules.demManager.getElevation(this.position.normalizedValue))!=null?e:0,this.demTilesRevision=this.modules.demManager.getTilesRevision()}nearCenterScreenPosition(){var f,m;const e=this.modules.demManager,t=this.mapState;let i=0,r=0;const o=this.tierHeightResolver.getResolvedHeight();if(o.relativeZ!==void 0){const v=(t.demMode&&(f=t.elevation)!=null?f:0)*n.MAP_POINTS_IN_METER,g=o.absoluteZ;i=o.relativeZ+(g===void 0?0:(g-v)*t.elevationScale)}else if(t.demMode){const v=e.getTilesRevision();this.demTilesRevision!==v&&this.updateDemElevation(),i=(this.demElevation-(t.demMode&&(m=t.elevation)!=null?m:0))*t.elevationScale*n.MAP_POINTS_IN_METER}this.options.floorId&&(r=this.modules.floorManager.getFloorObjectElevation(this.options.floorId,!0));const{normalizedValue:a}=this.position,l=a[2]+i+r,c=this.modules.camera,d=this.mapState.center[0],u=Math.round((d-a[0])/n.worldSize);let h,_=1/0;for(let v=-1;v<=1;v++){const g=a[0]+n.worldSize*(u+v);yi[0]=g,yi[1]=a[1],yi[2]=l,Ti[0]=NaN,Ti[1]=NaN;const p=Fh(c,this.mapState,yi,!0);if(Number.isNaN(p[0]))continue;const x=Math.abs(g-d);x<_&&(_=x,h=[p[0],p[1]])}return h!==void 0?h:ye(this.mapState)?(yi[0]=a[0]+u*n.worldSize,yi[1]=a[1],yi[2]=l,Fh(c,this.mapState,yi,!1)):Ti}updatePosition(){const e=this.nearCenterScreenPosition(),t=e===void 0||e.length===0||Number.isNaN(e[0]),i=ye(this.mapState)&&this.modules.camera.globeRatio>1-tl&&!this.modules.camera.ecef.canSee(this.getPosition());this.html.hidden=t||i,!t&&(this.rounder(e,e[0]+this.options.offset[0],e[1]+this.options.offset[1],this.mapState.stillness),n.equals$1(this.screenPoint,e)||(this.html.style.transform=`translate3d(${e[0]}px, ${e[1]}px, 0px)`,this.screenPoint=e))}updateLabelBox(){if(this.options.labeling.type==="none")return;const{labeling:{width:e,height:t},offset:i}=this.options;this.modules.labeler.removeLabels(this.labelKey),this.modules.labeler.addLabelBox(this.labelKey,{id:this.uniqId,width:e,height:t,position:this.position.normalizedValue,offset:i,labelingGroup:this.getLabelingGroup(),parentPoiId:this.options.labeling.type==="pinnedToPoi"?this.options.labeling.poiId:void 0})}getLabelingGroup(){return this.isInvolvedInLabeling()?"markerText":"htmlLabel"}checkZoom(){const{zoom:e}=this.mapState,{minZoom:t,maxZoom:i}=this.options;return e>=t&&e<i}checkFog(){if(!this.modules.environmentManager.isFogEnabled()||this.mapState.globeMode)return!0;const{fogLimits:e}=this.modules.environmentManager,{fogDistance:t,position:i}=this.modules.camera,r=q2(this.position.normalizedValue[0]-i[0])/t,o=(this.position.normalizedValue[1]-i[1])/t,a=Math.sqrt(Re(r,2)+Re(o,2)),l=e[1]-e[0];return n.clamp((a-e[0])/l,0,1)<this.fogFactorBreakpoint}isInvolvedInLabeling(){return this.options.labeling.type==="full"||this.options.labeling.type==="pinnedToPoi"}refreshTierData(){if(!this.tierHeightResolver.shouldUseTierHeight()){this.tierHeightResolver.reset()&&this.modules.renderer.addRerenderEvent();return}this.tierHeightResolver.needsResolve()&&this.throttledResolveTierData()}resolveTierData(){return this.tierHeightResolver.resolve()}},ji.options={coordinates:[0,0],html:"",offset:[0,0],animate:!0,duration:500,labeling:{type:"none"},interactive:!0,preventMapInteractions:!1,zIndex:0,minZoom:-1/0,maxZoom:1/0,disableRounding:!1,floorId:"",tier:0},ji);const tl=.01,Rh=1.4844222,Vn=Math.PI*2,ln=n.create$3(),Hi=n.create$3(),Gi=n.create$3(),Zn=[0,0,0],cn=[0,0,0],yi=[0,0,0],Ti=[NaN,NaN];function Fh(s,e,t,i){var l;if(!ye(e))return s.flat.project(t,i,Ti);if(n.Mercator.toGeo(t,Zn),n.Ecef.fromGeo(Zn,cn),s.globeRatio>1-tl)return s.ecef.project(cn,i,Ti);const r=(l=t[2])!=null?l:0;if(Y2(cn,r,s,e,ln),s.globeRatio<tl)return il(ln,e,i,Ti);const o=1+r/n.worldSize;Hi[0]=cn[0]*o,Hi[1]=cn[1]*o,Hi[2]=cn[2]*o,Hi[3]=1,n.transformMat4(Hi,Hi,s.ecefMvpMatrix),n.lerp$3(ln,ln,Hi,s.globeRatio);const a=il(ln,e,i,Ti);return i&&Number.isNaN(a[0])?il(ln,e,!1,Ti):a}function $2(s){return((s+Math.PI)%Vn+Vn)%Vn-Math.PI}function q2(s){return s-Math.round(s/n.worldSize)*n.worldSize}function Y2(s,e,t,i,r){const o=Math.hypot(s[0],s[1],s[2])||1,a=Math.atan2(s[0]/o,s[2]/o),l=n.clamp(Math.asin(n.clamp(s[1]/o,-1,1)),-Rh,Rh),c=Math.log(Math.tan(Math.PI/4+l/2));n.Mercator.toGeo(i.center,Zn);const d=n.degToRad(Zn[0]),u=n.degToRad(Zn[1]),h=Math.log(Math.tan(Math.PI/4+u/2));r[0]=$2(a-d)/Vn*n.worldSize,r[1]=(c-h)/Vn*n.worldSize,r[2]=e,r[3]=0,n.transformMat4(r,r,t.viewProjectionMatrix),Gi[0]=i.center[0],Gi[1]=i.center[1],Gi[2]=0,Gi[3]=1,n.transformMat4(Gi,Gi,t.viewProjectionMatrix),n.add$2(r,r,Gi)}function il(s,e,t,i){const[r,o,a,l]=s,c=l*2;if(t&&(a>c||a<-c||r>c||r<-c||o>c||o<-c))return i[0]=NaN,i[1]=NaN,i;const d=e.size[0]/2,u=e.size[1]/2;return i[0]=d+e.viewport.left+r*d/l,i[1]=u+e.viewport.top-o*u/l,i}function Q2(s){const e=document.createElement("div");e.style.position="absolute",e.style.top="0",e.style.left="0",e.style.zIndex=String(s.zIndex),s.interactive||(e.style.pointerEvents="none"),s.animate&&(e.style.opacity="0",e.style.transition=`opacity ${s.duration}ms`,e.style.willChange="opacity");const t=document.createElement("div");return typeof s.html=="string"?t.innerHTML=s.html:t.append(s.html),e.append(t),e}function J2(s){return s?K2:e1}const K2=(s,e,t,i)=>{const r=Math.round(e),o=Math.round(t),a=r-e,l=o-t;s[0]=e+i*a,s[1]=t+i*l},e1=(s,e,t)=>{s[0]=e,s[1]=t},t1="#0085a0",i1="#ffffff",n1=4,r1=1,s1=2,o1=1.5,a1=2.8,Dh=6,l1=!0,c1=17.1,nl=n.entranceAnimation.iterationCount,rl=n.create$1();class sl extends ht{constructor(e,t){var v,g,p,x,S,b,T,y,E,P,A,F,L;super(e,{interactive:(v=t.interactive)!=null?v:!1}),this.options=t,this.vectors=this.options.coordinates.map(D=>D.map(B=>n.Mercator.fromGeo(B))),this.bouncePosition=0,this.growPosition=1;const{tileManager:i,dynamicStyle:r,collector:o,layers:a}=this.modules,l=(g=this.options.animate)!=null?g:l1;let c;if(l&&!this.mapState.disableLayerAnimation){const D=(p=this.options.iterationCount)!=null?p:nl;D>1?c={type:"repeat",tipMovementAmplitude:this.options.tipMovementAmplitude||Dh,iterationCount:D}:D===1&&(c={type:"appearance",tipMovementAmplitude:this.options.tipMovementAmplitude||Dh})}const d=n.makeHandyStyleLayer({type:"arrow",id:`dynamic-entrance-${this.uniqId}`,interactive:this.interactive,minzoom:(x=this.options.minZoom)!=null?x:c1,maxzoom:this.options.maxZoom,style:{color:(S=this.options.color)!=null?S:t1,strokeColor:(b=this.options.borderColor)!=null?b:i1,lineWidth:(T=this.options.width)!=null?T:n1,strokeWidth:(y=this.options.borderWidth)!=null?y:r1,tipWidth:(E=this.options.wingWidthMultiplier)!=null?E:o1,tipHeight:(P=this.options.tipHeightMultiplier)!=null?P:a1,roundingRadius:(A=this.options.roundingRadius)!=null?A:s1,animation:c}},r.getStyle().globals);if(!d)return;r.addLayer(d,this.options.zIndex),this.layerId=d.innerId;const u=this.getTileInfo(),h=[],_=n.makeGeneratorContext(this.mapState.styleState,n.emptySourceAttrs,n.fixedTileProps,h,n.emptyFeatureAttrs,!0,this.interactive?"0":"");n.runPrecomputes(d,_);for(let D=0;D<this.vectors.length;D++){const B=this.vectors[D],Q=this.getVertices(B,u);_.id=String(D),n.generateSafely({collector:o,generator:n.ArrowGenerator.generate,args:[r.getStyle().id,d,_,Q]})}const f=o.getAccumulatedData(),m=new n.TileObject("dynamicObject",f.data,this.modules,this.mapState,u.coords,this);this.tileObjects.push(m),i.addObject(m),this.interactive&&this.identifyIds.push(f.identifyIds),l&&!this.mapState.disableLayerAnimation?(this.bounceTickerId=`entrance-bounce-${this.uniqId}`,this.growTickerId=`entrance-grow-${this.uniqId}`,this.bounceTickerUpdate=n.update.bind(null,this.bounceTickerId,{step:(D,B)=>this.bouncePosition=B,complete:()=>{this.bounceTickerUpdate=void 0}},this.mapState),this.growTickerUpdate=n.update.bind(null,this.growTickerId,{step:(D,B)=>this.growPosition=B,complete:()=>{this.growTickerUpdate=void 0}},this.mapState),n.start(this.bounceTickerId,{easing:n.entranceAnimation.bounceType},this.mapState,-1,0,n.entranceAnimation.bounceTime,(F=this.options.iterationCount)!=null?F:nl,{layerId:this.layerId,styleId:r.getStyle().id}),n.start(this.growTickerId,{easing:n.entranceAnimation.growType},this.mapState,0,1,n.entranceAnimation.growTime,(L=this.options.iterationCount)!=null?L:nl,{layerId:this.layerId,styleId:r.getStyle().id})):(this.bouncePosition=0,this.growPosition=1),a.addLayer(this),o.reset(),this.modules.renderer.addRerenderEvent(),this.interactive&&this.modules.identifier.resetCache()}update(){super.update(),this.stopTickersOnGlobalAnimationDisabling(),this.bounceTickerUpdate&&this.bounceTickerUpdate(),this.growTickerUpdate&&this.growTickerUpdate()}isOutOfMainReplica(){return!1}entranceAnimationInProgress(){return this.bounceTickerUpdate!==void 0||this.growTickerUpdate!==void 0}remove(){this.destroy()}destroy(){this.bounceTickerUpdate=void 0,this.growTickerUpdate=void 0,this.bounceTickerId&&n.stop(this.bounceTickerId,this.mapState),this.growTickerId&&n.stop(this.growTickerId,this.mapState),this.interactive&&this.modules.identifier.resetCache(),this.layerId!==void 0&&this.modules.dynamicStyle.removeLayer(this.layerId),super.destroy()}getTileInfo(){const e=n.create();for(let t=0;t<this.vectors.length;t++){const i=this.vectors[t];for(let r=0;r<i.length;r++)n.expandByPoint(e,i[r])}return n.createTileInfo(n.getBoundsTileCoords(e))}getVertices(e,t){const i=[],r=[];for(let o=0;o<e.length;o++)n.mapPointToTilePoint(rl,e[o],t),i[o]=rl[0],r[o]=rl[1];return{x:i,y:r}}stopTickersOnGlobalAnimationDisabling(){this.mapState.disableLayerAnimation&&(this.bounceTickerId&&(this.bounceTickerUpdate=void 0,n.stop(this.bounceTickerId,this.mapState)),this.growTickerId&&(this.growTickerUpdate=void 0,n.stop(this.growTickerId,this.mapState)))}}class d1{constructor(e){this.layers=[],this.renderer=e.renderer}addLayer(e){this.layers.push(e),this.renderer.addRerenderEvent()}removeLayer(e){const t=this.layers.indexOf(e);t!==-1&&(this.layers.splice(t,1),this.renderer.addRerenderEvent())}getLayers(){return this.layers}getDynamicObjectLayers(){return this.layers.filter(e=>e instanceof ht)}getHtmlMarkers(){return this.layers.filter(e=>e instanceof el)}entranceAnimationFinished(){return this.layers.every(e=>e instanceof sl?!e.entranceAnimationInProgress():!0)}}const zh=()=>"",u1=[.5,.5];class h1{constructor(e){this.loadingCounter=0,this.isIdle=()=>this.loadingCounter===0,this.modules=e,this.cache={}}getRasterSet(e,t,i,r){return q(this,null,function*(){const o=this.getKey(e,i,r),a=this.getFromCache(o,t);if(a)return a;const l=yield this.loadIcon(e,t,i,r);return l&&this.storeInCache(l,o,t),l})}clear(){this.cache={}}decreaseLoadingCounter(){this.loadingCounter=Math.max(this.loadingCounter-1,0)}loadIcon(e,t,i,r){return q(this,null,function*(){const{dynamicStyle:o,workers:a,assetManager:l}=this.modules;let c=e;this.loadingCounter++,t&&(c=yield this.loadImageForTransformer(e).then(u=>t(u)).catch(()=>e));const d=yield this.loadImage(c);return d?Promise.resolve().then(()=>{i=i!==void 0?i:[d.width,d.height];const u=r!==void 0?[r[0]/i[0],r[1]/i[1]]:u1,h=[i[0]*window.devicePixelRatio,i[1]*window.devicePixelRatio],_=n.createLoadedRasterSet([{w:h[0],h:h[1],x:0,y:0,atlasIndex:0,isPacked:!1,anchorX:u[0],anchorY:u[1]}]);o.appendRasterSet(_),a.labeling.addNewRasterSets(o.getStyle().id,[_]);const f=new Uint16Array(3);return f[0]=h[0],f[1]=h[1],f[2]=_.index,a.parser.packRasters(f).then(m=>({packedRasters:m.packedRasters,rasterSet:_,scaledSize:h}))}).then(u=>{const{packedRasters:h,rasterSet:_,scaledSize:f}=u;return h!==void 0&&l.prepareRasters(o.getStyle().id,h,[fu(d,f)]),this.decreaseLoadingCounter(),_}):(this.decreaseLoadingCounter(),Promise.resolve(void 0))})}getFromCache(e,t){const i=this.cache[e];if(i)return i.get(t||zh)}storeInCache(e,t,i){this.cache[t]||(this.cache[t]=new Map),this.cache[t].set(i||zh,e)}getKey(e,t,i){const r=t!==void 0?`${t[0]},${t[1]}`:"",o=i!==void 0?`${i[0]},${i[1]}`:"";return`${e}_${r}_${o}`}loadImage(e){return new Promise(t=>{const i=new Image;i.crossOrigin="Anonymous",i.src=e,i.onload=()=>t(i),i.onerror=()=>t(void 0)})}loadImageForTransformer(e){return e.indexOf(".svg")===-1?new Promise(t=>{const i=new Image;i.crossOrigin="Anonymous",i.src=e,i.onload=()=>{t({type:"raster",source:i})},i.onerror=()=>{t({type:"unknown"})}}):new Promise(t=>{const i=new XMLHttpRequest;i.open("GET",e,!0),i.onload=function(){if(i.status!==200||i.response.byteLength===0){t({type:"unknown"});return}t({type:"vector",source:i.response})},i.onerror=function(){t({type:"unknown"})},i.send()})}}const Bh={trafficOn:!1,parkingOn:!1,navigatorOn:!1,immersiveRoadsOn:!1,floorStackOn:!1,terrainEnabled:!1,lang:n.defaultLang,graphicsPreset:cr()?"light":"immersive",_activeFloorIds:[],_activeFloorBuildingIds:[],_activeFloorIsMetro:!1,_floorHeight:n.DEFAULT_FLOORS_FLOOR_HEIGHT,_activeFloorsLevel:0,_backgroundFloorIds:[],_customUserTimeOffset:0};let ys=!1;function _1(){return I({},Bh)}function Ts(s,e){return s=I({},s),(e==null?void 0:e.immersiveRoadsOff)===!0?(ys=!0,s.immersiveRoadsOn=!1):ys&&(s.immersiveRoadsOn=ys,ys=!1),s.graphicsPreset&&s.graphicsPreset!=="light"&&cr()&&(console.warn(`"${String(s.graphicsPreset)}" graphicsPreset is not supported in deprecated system. Using "light" instead.`),s.graphicsPreset="light"),I(I({},Bh),s)}function Oh(s,e,t){const i=V(I(I({},s),e),{_activeFloorIds:s._activeFloorIds,_activeFloorBuildingIds:s._activeFloorBuildingIds,_activeFloorIsMetro:s._activeFloorIsMetro,_floorHeight:s._floorHeight,_backgroundFloorIds:s._backgroundFloorIds,_activeFloorsLevel:s._activeFloorsLevel});return Ts(i,t)}function wh(s,e=[],t=[],i=!1,r=[],o=0){return V(I({},s),{_activeFloorIds:e,_activeFloorBuildingIds:t,_activeFloorIsMetro:i,_floorHeight:i?n.DEFAULT_FLOORS_METRO_FLOOR_HEIGHT:n.DEFAULT_FLOORS_FLOOR_HEIGHT,_backgroundFloorIds:r,_activeFloorsLevel:o})}function f1(s,e=n.floors.commFloorsDefaultFloorLevel){const t=s.filter(c=>c.has_apartments).map(c=>c.level);if(t.length===0)return 0;const i=Math.min(...t),r=Math.max(...t),o=n.clamp(e,i,r),a=s.findIndex(c=>c.level===o);if(a!==-1)return a;let l=-1;for(let c=s.length-1;c>=0;c--)if(s[c].has_apartments&&s[c].level===r){l=c;break}return l}const Es=["default","metro"],ol="floorStackTicker",m1=500,Cs={MAX_DISTANCE_METERS:500,VERY_CLOSE_DISTANCE_METERS:500,DISTANCE_WEIGHT_MULTIPLIER:3,VERY_CLOSE_BONUS:1.5};class v1{constructor(e,t){this.state=e,this.modules=t,this.repository={descriptors:{default:new Map,metro:new Map},requestedFloors:new Set,failedRequestedFloors:new Set,floorIdsToObjectIds:new Map},this.stateDiffer=new n.Differ([{path:"center",type:"vec2"},{path:"zoom",type:"number"},{path:"size",type:"vec2"},{path:"rotation",type:"number"},{path:"pitch",type:"number"},{path:"padding",type:"padding"},{path:"demMode",type:"boolean"}]),this.stack={readiness:0,offsets:new Map,maxOffset:1},this.viewport={index:{metro:n.rbush(),default:n.rbush()},metro:{in:null,current:null,out:null},default:{in:null,current:null,out:null},area:{metro:new Map,default:new Map}},this.displayedComplex=null,this.needUpdate=!1,this.allowedFloors=new Set,this.hiddenObjectIds=new Set,this.pendingUpdateCall=!1,this.ids={default:t.identifier.getIdScope(n.DEFAULT_ID_SCOPE),floor:t.identifier.getIdScope(n.FLOOR_ID_SCOPE)},this.uiPoiSource=t.uiPoiSource;const i=n.throttle(this._update.bind(this),60);this.prevStyleState=this.state.styleState,this.update=()=>{this.updateReadiness();const r=this.needUpdate||this.stateDiffer.check(this.state);r&&(this.pendingUpdateCall=!0,i()),(r||this.prevStyleState!==this.state.styleState)&&(this.updateStyleState(),this.prevStyleState=this.state.styleState),r&&this.updateHiddenIds()}}get visibleComplexIsMetro(){var e;return((e=this.displayedComplex)==null?void 0:e.mode)==="metro"}get isStackEnabled(){return!this.state.demMode&&(this.state.styleState.floorStackOn&&this.floorHeight>0||this.state.styleState._activeFloorIsMetro)}get maxFloorOffset(){var t;const e=(t=this.state.styleState._floorHeight)!=null?t:0;return Math.floor(n.floors.maxStackHeight/e)}get floorHeight(){var i;const e=(i=this.state.styleState._floorHeight)!=null?i:0,t=n.Mercator.toGeo(this.state.center);return n.geoToMapDistance(t,e)}get isMetroEnabled(){return this.state.allowMetro&&this.state.styleZoom>=n.floors.displayStyleZoom.metro}get isDefaultEnabled(){return this.state.styleZoom>=n.floors.displayStyleZoom.default}get isUiPoiEnabled(){return this.state.floorsEnabled&&this.state.styleZoom>=n.floors.displayStyleZoom.uiPoi}get isEnabled(){return this.state.floorsEnabled&&(this.isDefaultEnabled||this.isMetroEnabled)}get shouldIgnoreFloorState(){return!!this.state.resetFloorModeOnActivation}get hiddenBuildingIds(){if(!this.displayedComplex||this.displayedComplex.mode==="building"||this.activeFloorIdx===void 0)return[];const e=this.displayedComplex.floors[this.activeFloorIdx];if(!e)return[];const t=[];if(e.id&&t.push(this.displayedComplex.id),!e.linked_floors_ids)return t;const i=this.repository.descriptors.default.has(this.displayedComplex.id)?"default":"metro";return this.displayedComplex.buildings.filter(r=>{const o=this.repository.descriptors[i].get(r);return e.linked_floors_ids.some(a=>o==null?void 0:o.floorIds.includes(a))}).forEach(r=>t.push(r)),t}hasActiveFloorOrMetro(){var e,t;return((e=this.displayedComplex)==null?void 0:e.mode)==="metro"||((t=this.displayedComplex)==null?void 0:t.mode)==="floor"&&this.isStackEnabled}getActiveFloorHiddenIds(){const e=this.ids.default.getRelatedChildrenIds(this.hiddenObjectIds);return Array.from(this.hiddenObjectIds).concat(e)}prepareFloors(e,t,i,r){r==="zenith"&&i.forEach((o,a)=>{let l=this.repository.floorIdsToObjectIds.get(a);l===void 0&&(l=new Set,this.repository.floorIdsToObjectIds.set(a,l));for(const c of o)l.add(c);this.loadFloor(a,e,t)})}changeFloorNumber(e,t){var l,c;let i="building";const r=this.viewport.default.current,o=this.viewport.metro.current;let a=r||o;if(typeof t=="number"&&(i="floor"),typeof t=="number"&&o&&o.buildings.includes(e)&&(a=o,i="metro"),t==="metro"&&o&&(o.id===e||o.buildings.includes(e)||(r==null?void 0:r.id)===e||r!=null&&r.buildings.includes(e))&&(a=o,e=a.id,i="metro",t=0),a&&(a.id===e||a.buildings.includes(e))){if(this.needUpdate=!0,i==="metro"&&typeof t=="number"){if(!o||t<0||t>=o.floors.length)return;a.mode="metro",r&&r.mode==="floor"&&(r.mode="metro",this.modules.map.emit("floorcomplexhide",{id:r.id})),this.displayedComplex!==a&&this.modules.map.emit("floorcomplexshow",{id:a.id,mode:"metro",currentFloor:t,floorNames:a.floors.map(d=>d.name),firmsToFloorIndexMap:a.firmsToFloorIndexMap,linkedComplexesFirmsToFloorIndexMap:this.getLinkedComplexesFirmsToFloorIndexMap(a)}),this.displayedComplex=a,this.setFloorIdx(t),a.selectedFloorIdx=t,this.updateStackState(),this.modules.map.emit("floorcomplexlevelchange",{id:e,floorIndex:t,floorName:a.floors[t].name,floorMode:"metro"})}else if(i==="building"){o&&(o.mode="floor"),a.mode="building";const d=(l=this.displayedComplex)==null?void 0:l.id;this.displayedComplex=null,d&&this.modules.map.emit("floorcomplexhide",{id:d})}else if(i==="floor"&&typeof t=="number"){if(t<0||t>=a.floors.length)return;this.setFloorIdx(t),a.selectedFloorIdx=t,o&&o.mode==="metro"&&(o.mode="floor",this.modules.map.emit("floorcomplexhide",{id:o.id})),this.displayedComplex!==a&&!((c=this.displayedComplex)!=null&&c.buildings.includes(a.id))&&this.modules.map.emit("floorcomplexshow",{id:a.id,mode:"floor",currentFloor:t,floorNames:a.floors.map(({name:d})=>d),firmsToFloorIndexMap:a.firmsToFloorIndexMap,linkedComplexesFirmsToFloorIndexMap:this.getLinkedComplexesFirmsToFloorIndexMap(a)}),this.displayedComplex=a,this.updateStackState(),a.mode="floor",this.modules.map.emit("floorcomplexlevelchange",{id:e,floorIndex:t,floorName:a.floors[t].name,floorMode:"floor"})}}}hasDisplayedFloorBuilding(e){if(!this.displayedComplex||this.displayedComplex.mode==="building")return!1;for(const t of this.hiddenBuildingIds){const i=this.repository.floorIdsToObjectIds.get(t);if(i&&(Array.isArray(e)&&e.some(r=>i.has(r))||typeof e=="string"&&i.has(e)))return!0}return!1}floorsReady(){return!this.pendingUpdateCall&&Array.from(this.repository.requestedFloors).every(e=>this.repository.failedRequestedFloors.has(e)||this.repository.descriptors.default.has(e)||this.repository.descriptors.metro.has(e))}setAllowedFloorIds(e){this.allowedFloors=new Set(e!=null?e:[]),this.needUpdate=!0}isApartmentFloor(e){var t;return!e||!this.displayedComplex?!1:((t=this.findFloorByFloorId(e))==null?void 0:t.has_apartments)===!0}isVisibleFloorObject(e,t){return this.displayedComplex?this.state.styleState._activeFloorIds.includes(e)||t==="all-floors"&&this.state.styleState._backgroundFloorIds.includes(e):!1}isVisibleFloorStackObject(e){if(!this.isStackEnabled||!this.displayedComplex||this.activeFloorIdx===void 0)return!1;let t=!1;for(const o of this.hiddenBuildingIds){if(t)break;const a=this.repository.descriptors.default.get(o);t=!!(a!=null&&a.floors.some(l=>l.id===e))}if(!t)return!1;const i=this.activeFloorIdx-this.displayedComplex.defaultFloor,r=this.stack.offsets.get(e);return r<this.maxFloorOffset&&i>0&&r>=0&&r<i}getFloorObjectElevation(e,t){var a;if(!this.isStackEnabled||!this.stack.offsets.has(e))return 0;let i=this.stack.offsets.get(e);if(((a=this.displayedComplex)==null?void 0:a.mode)==="metro"){if(i+=this.getFloorsStackShift(),i===0)return 0}else if(i<=0)return 0;if(this.isOffsetAboveStackLimit(i))return this.floorHeight*this.maxFloorOffset;const r=this.floorHeight*i;return t?r:n.lerp$2((i-1)/i,1,this.stack.readiness)*r}getFloorStackObjectElevation(e){return this.stack.offsets.has(e)?this.stack.offsets.get(e)*this.floorHeight:0}getFloorsStackObjectOffsets(e){return this.stack.offsets.has(e)?{current:this.stack.offsets.get(e),total:this.stack.maxOffset}:{current:0,total:1}}getFloorsStackShift(){var r,o,a;if(this.displayedComplex&&this.activeFloorIdx!==void 0&&((r=this.displayedComplex.floors[this.activeFloorIdx])==null?void 0:r.level)>0)return 0;const e=this.stack.offsets.size,t=1+(Array.isArray(this.state.styleState._backgroundFloorIds)?this.state.styleState._backgroundFloorIds.length:0),i=(a=(o=this.displayedComplex)==null?void 0:o.floors.filter(l=>l.level>0).length)!=null?a:0;return e-t-i}getPlanLevels(){return this.isStackEnabled?Object.fromEntries(Array.from(this.stack.offsets,([e,t])=>[e,this.getCappedFloorOffset(t)])):{}}getFloorStackObjectHeight(e){if(!this.isStackEnabled)return 1;const t=this.findFloorByFloorId(e);return(t?this.displayedComplex.floors.indexOf(t):-1)<this.activeFloorIdx-1?1:this.stack.readiness}findFloorByFloorId(e){var t;return(t=this.displayedComplex)==null?void 0:t.floors.find(({id:i,linked_floors_ids:r})=>i===e||(r==null?void 0:r.includes(e)))}getCappedFloorOffset(e){return this.isOffsetAboveStackLimit(e)?this.maxFloorOffset:e}isOffsetAboveStackLimit(e){var t;return this.isStackEnabled&&((t=this.displayedComplex)==null?void 0:t.mode)!=="metro"?e>this.maxFloorOffset:!1}_update(){this.pendingUpdateCall=!1;const e=this.displayedComplex;this.updateViewport();const t=!!(this.viewport.default.out&&this.viewport.default.in&&this.viewport.default.in.buildings.includes(this.viewport.default.out.id));this.viewport.default.out?t||this.modules.map.emit("floorcomplexout",{id:this.viewport.default.out.id}):this.viewport.metro.out&&this.modules.map.emit("floorcomplexout",{id:this.viewport.metro.out.id}),this.displayedComplex&&(!t&&this.viewport.default.out&&(this.displayedComplex===this.viewport.default.out||this.displayedComplex.buildings.includes(this.viewport.default.out.id))&&this.displayedComplex.mode==="floor"?(this.modules.map.emit("floorcomplexhide",{id:this.displayedComplex.id}),this.displayedComplex=null):this.displayedComplex===this.viewport.metro.out&&this.displayedComplex.mode==="metro"&&(this.modules.map.emit("floorcomplexhide",{id:this.displayedComplex.id}),this.displayedComplex=null));let i=null;const r=this.viewport.default.in||this.viewport.default.current,o=this.viewport.metro.in||this.viewport.metro.current,a=!t&&this.viewport.default.in||this.viewport.metro.in||!t&&this.viewport.default.out&&this.viewport.metro.current||this.viewport.metro.out&&!this.viewport.default.out&&r;if(r){const l=this.shouldIgnoreFloorState?"building":r.mode;i={id:r.id,mode:l==="floor"?"floor":"building",hasFloorsWithApartments:r.floors.some(c=>c.has_apartments),currentFloor:r.selectedFloorIdx,floorNames:r.floors.map(c=>c.name),firmsToFloorIndexMap:r.firmsToFloorIndexMap,linkedComplexesFirmsToFloorIndexMap:this.getLinkedComplexesFirmsToFloorIndexMap(r)},this.viewport.metro.current&&((this.shouldIgnoreFloorState?"building":this.viewport.metro.current.mode)==="metro"&&(i.mode="metro"),i.metro={id:this.viewport.metro.current.id,floorNames:this.viewport.metro.current.floors.map(d=>d.name),currentFloor:this.viewport.metro.current.selectedFloorIdx,firmsToFloorIndexMap:this.viewport.metro.current.firmsToFloorIndexMap,linkedComplexesFirmsToFloorIndexMap:this.getLinkedComplexesFirmsToFloorIndexMap(this.viewport.metro.current)})}o&&(i?(i.metro={id:o.id,floorNames:o.floors.map(c=>c.name),currentFloor:o.selectedFloorIdx,firmsToFloorIndexMap:o.firmsToFloorIndexMap,linkedComplexesFirmsToFloorIndexMap:this.getLinkedComplexesFirmsToFloorIndexMap(o)},o.mode==="metro"&&(i.mode="metro",i.currentFloor=o.selectedFloorIdx)):i={id:o.id,mode:"building",currentFloor:o.selectedFloorIdx,floorNames:[],firmsToFloorIndexMap:{},linkedComplexesFirmsToFloorIndexMap:{},metro:{id:o.id,floorNames:o.floors.map(c=>c.name),currentFloor:o.selectedFloorIdx,firmsToFloorIndexMap:o.firmsToFloorIndexMap,linkedComplexesFirmsToFloorIndexMap:this.getLinkedComplexesFirmsToFloorIndexMap(o)}},(this.shouldIgnoreFloorState?"building":o.mode)==="metro"&&(i.mode="metro")),i&&a&&this.modules.map.emit("floorcomplexin",i),this.displayFloorComplex(),this.needUpdate=!1,this.displayedComplex!==e&&(this.needUpdate=!0)}loadFloor(e,t,i){if(this.repository.requestedFloors.has(e))return;const r=n.getUrl("floorMeta",{protocol:this.state.tileProtocol,tileSet:this.state.tileSet,host:this.state.tileServer,subdomain:this.state.subdomains[0],regionId:t.toString(10),floorComplexId:e});this.repository.requestedFloors.add(e),fetch(r).then(o=>{if(o.ok===!1)throw new Error(o.statusText);return o.json()}).then(o=>(o.apartment_floors&&o.apartment_floors.length&&(o.floors=o.apartment_floors),o)).then(o=>{var _;let a=o.default_floor_idx,l="default";"is_metro"in o&&o.is_metro&&(a=o.default_metro_floor_idx,l="metro");const c=o.floors.reduce((f,m,v)=>(m.id&&(f[m.id]=v),f),{}),d=o.floors.some(f=>!!f.has_apartments),u=l==="default"&&d?f1(o.floors):a,h={id:e,regionId:t,metatileHash:i,center:o.center,bound:o.bound,defaultFloor:a,selectedFloorIdx:u,mode:d?"building":"floor",floors:o.floors,floorIds:o.floors.map(f=>f.id).filter(Boolean),buildings:o.linked_buildings_ids?o.linked_buildings_ids.concat(e):[e],firmsToFloorIndexMap:Object.entries((_=o.firm_id_to_floor_id)!=null?_:{}).reduce((f,[m,v])=>(f[m]=c[v],f),{})};o.original_centroid_x!==void 0&&o.original_centroid_y!==void 0&&(h.originalCenter=[o.original_centroid_x,o.original_centroid_y]),this.repository.descriptors[l].set(e,h),this.viewport.index[l].insert({complex:h,minX:h.bound.min[0],minY:h.bound.min[1],maxX:h.bound.max[0],maxY:h.bound.max[1]}),this.needUpdate=!0}).catch(()=>{this.repository.failedRequestedFloors.add(e)})}updateStackState(){if(this.stack.offsets.clear(),!this.displayedComplex)return;let e=1;this.displayedComplex.floors.forEach((t,i)=>{var o;const r=this.displayedComplex.mode==="metro"?t.level:i-this.displayedComplex.defaultFloor;t.id&&this.stack.offsets.set(t.id,r),r>e&&(e=r),(o=t.linked_floors_ids)==null||o.forEach(a=>{this.stack.offsets.set(a,r)})}),this.stack.maxOffset=e}getLinkedComplexesFirmsToFloorIndexMap(e){const t=this.repository.descriptors.default.has(e.id)?"default":"metro",i={};return e.buildings.forEach(r=>{r!==e.id&&this.repository.descriptors[t].has(r)&&(i[r]=this.repository.descriptors[t].get(r).firmsToFloorIndexMap)}),i}updateStyleState(){var d,u;const{styleState:e}=this.state;if(!this.displayedComplex){(Array.isArray(e._activeFloorIds)&&e._activeFloorIds.length>0||Array.isArray(e._activeFloorBuildingIds)&&e._activeFloorBuildingIds.length>0)&&(this.state.styleState=wh(e,[],[],!1,[],0));return}const t=new Set,i=new Set,r=new Set(this.state.styleState._activeFloorIds),o=new Set(this.state.styleState._activeFloorBuildingIds),a=e._activeFloorIsMetro===!0,l=this.displayedComplex;if(!l||this.activeFloorIdx===void 0||l.mode==="building")return;const c=l.floors[this.activeFloorIdx];if(c&&(c.id&&t.add(c.id),(d=c.linked_floors_ids)==null||d.forEach(h=>{t.add(h)}),this.hiddenBuildingIds.forEach(h=>i.add(h)),Nh(r,t)||Nh(o,i)||a!==(this.displayedComplex.mode==="metro"))){let h=new Set;if(this.displayedComplex.mode==="metro"&&this.displayedComplex.floors.length>1){const f=(u=this.displayedComplex.floors.find(m=>m.id===c.id))==null?void 0:u.level;f!==void 0&&(h=new Set(this.displayedComplex.floors.filter(m=>m.id!==void 0&&m.level<f).map(m=>m.id)))}const _=c.level;this.state.styleState=wh(e,Array.from(t),Array.from(i),this.displayedComplex.mode==="metro",Array.from(h),_)}}updateHiddenIds(){if(!this.displayedComplex){this.markHiddenObjectsForUpdate();return}const e=new Set;this.hiddenBuildingIds.forEach(t=>{const i=this.repository.floorIdsToObjectIds.get(t);i&&i.forEach(r=>e.add(r))}),this.markHiddenObjectsForUpdate(e)}markHiddenObjectsForUpdate(e){if(e){const t=this.ids.default.getHidden(n.HideLevel.PolygonExtrusion),i=n.subtract(e,t),r=n.subtract(this.hiddenObjectIds,e);this.ids.default.hide(Array.from(i),n.HideLevel.PolygonExtrusion);const o=this.ids.floor.getHidden(),a=n.intersection$1(i,o);this.ids.default.hide(Array.from(a),n.HideLevel.All),this.ids.default.show(Array.from(r)),this.hiddenObjectIds=new Set(e)}else this.ids.default.show(Array.from(this.hiddenObjectIds)),this.hiddenObjectIds.clear()}updateReadiness(){n.update(ol,{step:(e,t)=>this.stack.readiness=t},this.state)}setFloorIdx(e){var t;this.prevActiveFloorIdx=this.activeFloorIdx,this.activeFloorIdx=e,!Number.isNaN(e)&&this.isStackEnabled&&((t=this.displayedComplex)==null?void 0:t.mode)!=="metro"&&this.prevActiveFloorIdx!==void 0&&this.activeFloorIdx>this.prevActiveFloorIdx?(this.stack.readiness=0,n.start(ol,{easing:"easeOutQuint"},this.state,0,1,m1,1)):(this.stack.readiness=1,n.stop(ol,this.state))}updateViewport(){if(this.isUiPoiEnabled||Es.forEach(v=>{this.viewport.area[v].forEach((g,p)=>{this.viewport.area[v].delete(p),g.some(x=>this.viewport.area[v].has(x))||this.uiPoiSource.remove(g)})}),!this.isEnabled){this.viewport.default={in:null,current:null,out:this.viewport.default.current},this.viewport.metro={in:null,current:null,out:this.viewport.metro.current};return}const e={default:null,metro:null},t={default:new Map,metro:new Map},{center:i,zoom:r,rotation:o,size:a,viewport:l,padding:c,cameraConfig:d,globeMode:u}=this.state,h=new n.Camera({center:i,zoom:r,rotation:o,size:[Math.floor(a[0]*(1-n.floors.viewportPadding)),Math.floor(a[1]*(1-n.floors.viewportPadding))],styleState:{},pitch:0,viewport:l,padding:c,cameraConfig:d,globeMode:u}),_=h.getViewportVertices().map(v=>[v[0],v[1]]),f=p1(_),m=[[0,0],[0,0],[0,0],[0,0]];Es.forEach(v=>{if(v==="default"&&!this.isDefaultEnabled&&!this.isUiPoiEnabled||v==="metro"&&!this.isMetroEnabled)return;const g=this.viewport.index[v].search(f);let p,x;for(const S of g){if(this.allowedFloors.size>0&&!this.allowedFloors.has(S.complex.id)||!this.state.metro3dVisible&&v==="metro"&&S.complex.floors.length>1||(t[v].set(S.complex.id,S.complex.buildings),v==="default"&&!this.isDefaultEnabled))continue;const b=S.complex.bound;if(x1(h.position,b)){if(p){const E=kh(b);E<p.complexArea&&(p.complex=S.complex,p.complexArea=E)}else p={complex:S.complex,complexArea:kh(b)};continue}m[0][0]=b.min[0],m[0][1]=b.min[1],m[1][0]=b.max[0],m[1][1]=b.min[1],m[2][0]=b.max[0],m[2][1]=b.max[1],m[3][0]=b.min[0],m[3][1]=b.max[1];const T=b1(m,_);if(T.length<3)continue;const y=y1({complex:S.complex,cameraPosition:h.position,intersectionPolygon:T});x?x.score<y&&(x.complex=S.complex,x.score=y):x={complex:S.complex,score:y}}p?e[v]=p.complex:x&&(e[v]=x.complex)}),Es.forEach(v=>{const g=this.viewport[v].current,p=e[v];this.shouldIgnoreFloorState&&p&&p!==g&&(!this.displayedComplex||!this.displayedComplex.buildings.includes(p.id))&&(p.mode="building"),this.viewport[v].out=g!==p?g:null,this.viewport[v].in=p!==g?p:null,this.viewport[v].current=p}),Es.forEach(v=>{if(v==="metro")return;const g=this.viewport.area[v],p=t[v],x=this.viewport.index[v].all();p.forEach((S,b)=>{var T,y;if(!g.has(b)){const E=(T=x.find(P=>P.complex.id===b))==null?void 0:T.complex;if(E===void 0)return;if(!S.some(P=>g.has(P))){const P=x.filter(({complex:A})=>E.buildings.includes(A.id)).map(({complex:A})=>A);if(P.some(A=>A.floors.some(F=>!!F.has_apartments))){const A=g1(P),F=n.Mercator.toGeo((y=A.originalCenter)!=null?y:A.center);this.uiPoiSource.add({id:A.id,label:`Смотреть
3D-планировки`,sublayer:"MapGL_UI_POI_Show_Comm_Floors",coordinates:F,onClick:()=>{const{pitch:L,styleZoom:D,animation:B}=n.floors.commFloorsFly;this.modules.map.setCenter(F,B),this.modules.map.setPitch(L,B),this.modules.map.setStyleZoom(D,B),this.modules.map.changeFloorNumber(A.id,A.selectedFloorIdx),this.modules.map.once("moveend",()=>{this.modules.map.changeFloorNumber(A.id,A.selectedFloorIdx),this.modules.map.once("floorcomplexin",Q=>{S.includes(Q.id)&&this.modules.map.changeFloorNumber(Q.id,A.selectedFloorIdx)})}),this.modules.map.emit("showcommfloorsclick",{buildingIds:S,targetBuildingId:A.id})}})}}g.set(b,S)}}),g.forEach((S,b)=>{p.has(b)||(g.delete(b),S.some(T=>g.has(T))||this.uiPoiSource.remove(S))})})}displayFloorComplex(){var i;const e=this.viewport.default.current,t=this.viewport.metro.current;if(t&&t.mode==="metro"){if(t===this.displayedComplex)return;this.displayedComplex=t,this.updateStackState(),this.setFloorIdx(t.selectedFloorIdx),this.modules.map.emit("floorcomplexshow",{id:t.id,mode:"metro",currentFloor:t.selectedFloorIdx,floorNames:t.floors.map(r=>r.name),firmsToFloorIndexMap:t.firmsToFloorIndexMap,linkedComplexesFirmsToFloorIndexMap:this.getLinkedComplexesFirmsToFloorIndexMap(t)}),this.updateStyleState()}else if(e&&e.mode==="floor"){if(e===this.displayedComplex||(i=this.displayedComplex)!=null&&i.buildings.includes(e.id))return;this.displayedComplex=e,this.updateStackState(),this.setFloorIdx(this.displayedComplex.selectedFloorIdx),this.modules.map.emit("floorcomplexshow",{id:e.id,mode:"floor",currentFloor:e.selectedFloorIdx,floorNames:e.floors.map(r=>r.name),firmsToFloorIndexMap:e.firmsToFloorIndexMap,linkedComplexesFirmsToFloorIndexMap:this.getLinkedComplexesFirmsToFloorIndexMap(e)}),this.updateStyleState()}}}function g1(s){var d,u,h,_;if(s.length===1)return s[0];let e=1/0,t=1/0,i=-1/0,r=-1/0;for(const f of s)f.bound.min[0]<e&&(e=f.bound.min[0]),f.bound.min[1]<t&&(t=f.bound.min[1]),f.bound.max[0]>i&&(i=f.bound.max[0]),f.bound.max[1]>r&&(r=f.bound.max[1]);const o=(e+i)/2,a=(t+r)/2;let l=s[0],c=1/0;for(const f of s){const m=((u=(d=f.originalCenter)==null?void 0:d[0])!=null?u:f.center[0])-o,v=((_=(h=f.originalCenter)==null?void 0:h[1])!=null?_:f.center[1])-a,g=m*m+v*v;g<c&&(c=g,l=f)}return l}function Nh(s,e){if(s.size!==e.size)return!0;for(const t of s)if(!e.has(t))return!0;return!1}function p1(s){let e=s[0][0],t=s[0][1],i=e,r=t;for(let o=1;o<s.length;o++){const[a,l]=s[o];a<e?e=a:a>i&&(i=a),l<t?t=l:l>r&&(r=l)}return{minX:e,minY:t,maxX:i,maxY:r}}function x1(s,e){return s[0]>=e.min[0]&&s[0]<=e.max[0]&&s[1]>=e.min[1]&&s[1]<=e.max[1]}function kh(s){return(s.max[0]-s.min[0])*(s.max[1]-s.min[1])}function b1(s,e){let t=s;for(let o=0;o<e.length;o++){const a=e[o],l=e[(o+1)%e.length],c=t;t=[];for(let d=0;d<c.length;d++){const u=c[d],h=c[(d+1)%c.length];i(h,a,l)?(i(u,a,l)||t.push(r(u,h,a,l)),t.push(h)):i(u,a,l)&&t.push(r(u,h,a,l))}}return t;function i(o,a,l){return(l[0]-a[0])*(o[1]-a[1])>(l[1]-a[1])*(o[0]-a[0])}function r(o,a,l,c){const d=a[1]-o[1],u=o[0]-a[0],h=d*o[0]+u*o[1],_=c[1]-l[1],f=l[0]-c[0],m=_*l[0]+f*l[1],v=d*f-_*u;return v===0?a:[(f*h-u*m)/v,(d*m-_*h)/v]}}function S1(s){let e=0;for(let t=0,i=s.length-1;t<s.length;i=t++)e+=(s[i][0]+s[t][0])*(s[i][1]-s[t][1]);return Math.abs(e/2)}function y1(s){const e=Math.sqrt(Re(s.complex.center[0]-s.cameraPosition[0],2)+Re(s.complex.center[1]-s.cameraPosition[1],2)),t=e/(Cs.MAX_DISTANCE_METERS*n.MAP_POINTS_IN_METER),i=Math.max(0,1-t),r=e<Cs.VERY_CLOSE_DISTANCE_METERS*n.MAP_POINTS_IN_METER?Cs.VERY_CLOSE_BONUS:1;return S1(s.intersectionPolygon)*r*(1+i*Cs.DISTANCE_WEIGHT_MULTIPLIER)}class T1{constructor(e,t){this.state=e,this.modules=t,this.tileLayers=[],this.objects=[],this.viewportDiffer=new n.Differ([{path:"center",type:"vec3"},{path:"zoom",type:"number"},{path:"size",type:"vec2"},{path:"rotation",type:"number"},{path:"pitch",type:"number"},{path:"padding",type:"padding"},{path:"demMode",type:"boolean"},{path:"globeMode",type:"boolean"},{path:"elevation",type:"number"},{path:"minElevation",type:"number"},{path:"handyStyleId",type:"string"}]),this.metroDiffer=new n.Differ([{path:"visibleComplexIsMetro",type:"boolean"}])}getMemoryFootprint(e=()=>!0){const t={tileLayers:this.tileLayers.filter(e).map(r=>({[r.getSourceType()]:r.memSizeJs()})),objects:this.objects.filter(r=>r.purpose==="dynamicObject").map(r=>({[r.purpose]:n.tileObjectStatsJS(r)}))},i={tileLayers:this.tileLayers.filter(e).map(r=>({[r.getSourceType()]:r.memSizeGpu()})),objects:this.objects.filter(r=>r.purpose==="dynamicObject").map(r=>({[r.purpose]:n.tileObjectStatsGpu(r)}))};return{js:V(I({},t),{"--sum":n.getTotalMemory(t)}),gpu:V(I({},i),{"--sum":n.getTotalMemory(i)})}}addTileLayer(e){this.tileLayers.indexOf(e)===-1&&(this.tileLayers.push(e),e.redraw(),this.modules.identifier.resetCache(),this.state.needLabeling=!0,this.modules.renderer.addRerenderEvent())}removeTileLayer(e){n.excludeItemFromArray(this.tileLayers,e)&&(e.resetHoverId(),this.modules.identifier.resetCache(),this.state.needLabeling=!0,this.modules.renderer.addRerenderEvent())}redraw(){this.modules.labeler.clearPreviousLabels();for(const e of this.tileLayers)e.resetHoverId(),e.redraw();this.modules.renderer.addRerenderEvent()}activateStyleUpdating(){this.tileLayers.forEach(e=>e.activateStyleUpdating())}finishStyleUpdating(){this.tileLayers.forEach(e=>e.finishStyleUpdating())}getViewportTiles(){const e=[];for(const t of this.tileLayers)e.push(...t.getViewportTiles());return e}viewportTilesReady(){return this.tileLayers.every(e=>e.viewportTilesReady())}displayedTilesAnimationFinished(){return this.tileLayers.every(e=>e.displayedTilesAnimationFinished())}getDisplayedIdentifyData(){const e=[];for(const t of this.tileLayers)e.push(...t.getDisplayedIdentifyData());return e}getLabelingData(){return this.tileLayers.map(e=>e.getLabelingData())}isIdle(){return this.viewportTilesReady()&&this.displayedTilesAnimationFinished()}update(){const e=this.state;this.viewportDiffer.check(e)?(this.tileLayers.forEach(t=>t.updateViewport()),this.modules.map.emit("viewportchange")):this.metroDiffer.check(this.modules.floorManager)&&this.modules.floorManager.visibleComplexIsMetro&&this.tileLayers.forEach(t=>t.updateViewport());for(const t of this.tileLayers)t.update();if(this.updateTickers(),e.collectStats){this.state.stats.tileCount=0,this.state.stats.viewportTileCount=0,this.state.stats.displayedTileCount=0;for(const t of this.tileLayers)this.state.stats.tileCount+=t.getTileCount(),this.state.stats.viewportTileCount+=t.getViewportTileCount(),this.state.stats.displayedTileCount+=t.getDisplayedTileCount();this.state.stats.dynamicTileCount=this.objects.filter(t=>t.purpose==="dynamicObject"||t.purpose==="floor").length}}getTileObjects(){return this.objects}addObject(e,t){if(this.objects.indexOf(e)===-1){if(this.objects.push(e),t)return;this.modules.renderer.addRerenderEvent()}}removeObject(e,t){if(n.excludeItemFromArray(this.objects,e)){if(t)return;this.modules.renderer.addRerenderEvent()}}getCachedMods(){const e=[];for(const t of this.tileLayers){const i=t.gridState.tileModsCache.getData();for(const r of i)e.push(r)}return e}destroy(){for(const e of this.tileLayers)e.destroy();this.objects.forEach(e=>e.clean(this.state))}updateTickers(){this.objects.forEach(e=>e.updateTicker(this.state))}}const E1=(s,e,t,i,r)=>{n.start("labelingOpacity",{easing:e},s,t,i,r,1)},C1=n.update.bind(null,"labelingOpacity",{step:(s,e)=>s.labelingOpacity=e});function I1(s){return s?Object.keys(s).map(Number).sort((e,t)=>e-t):[]}function P1(s,e){const{config:t,ascSortedZoomNumbers:i}=e;if(i.length===0)return{city:n.labeling.commercialMargins.city};if(s<i[0])return{city:t[i[0]]};if(s>=i[i.length-1])return{city:t[i[i.length-1]]};for(let r=1;r<i.length;r++)if(s<i[r])return{city:t[i[r-1]]};return{city:n.labeling.commercialMargins.city}}const A1=s=>({appendLabels:s.get(n.ThreadName.Labeling,"appendLabels"),appendLabelBox:s.get(n.ThreadName.Labeling,"appendLabelBox"),removeLabels:s.get(n.ThreadName.Labeling,"removeLabels"),processLabels:s.get(n.ThreadName.Labeling,"processLabels"),setLayoutCacheMode:s.get(n.ThreadName.Labeling,"setLayoutCacheMode"),clearPreviousLabels:s.get(n.ThreadName.Labeling,"clearPreviousLabels")}),L1=1e3;class R1{constructor(e,t){this.state=e,this.modules=t,this.collectStats=!1,this.stats=[],this.labelTileRevision=0,this.viewportDiffer=new n.Differ([{path:"center",type:"vec2"},{path:"zoom",type:"number"},{path:"size",type:"vec2"},{path:"rotation",type:"number"},{path:"pitch",type:"number"},{path:"padding",type:"padding"},{path:"demMode",type:"boolean"},{path:"globeMode",type:"boolean"}]),this.useThrottleUpdate=!0,this.isLabelingInProgress=!1,this.skipHysteresisInNextLabeling=!1,this.alwaysActiveLabelKeys=[],this.survivedLabelBoxes=new Set,this.prevSurvivedCommPoiIds=new Set,this.demKeys={},this.labelTiles=[],this.guidelineTextures=new Map,this.worker=A1(this.modules.workers.fnRegistry),this.setLabelingInterval(n.labeling.interval)}disableThrottleUpdateOnce(){this.useThrottleUpdate=!1}update(){C1(this.state),this.state.needReplicasUpdate&&this.labelTiles.forEach(e=>{e.needSync=!0}),(this.viewportDiffer.check(this.state)||this.state.needLabeling)&&!this.isLabelingInProgress&&(this.state.needLabeling=!1,this.isLabelingInProgress=!0,this.useThrottleUpdate?this.throttledUpdateLabeling():(this.useThrottleUpdate=!0,this.generateLabelingTile()))}isIdle(){return this.state.tickers.labelingOpacity===void 0&&!this.isLabelingInProgress&&!this.state.needLabeling}setLabelingInterval(e){this.throttledUpdateLabeling=n.throttle(()=>{this.generateLabelingTile()},e)}addGuidelineTexture(e,t){const i=t.reduce((u,h)=>Math.max(u,h.length/4),0),r=t.length,o=i*r*4;if(i>n.MAX_GUIDELINE_TEXTURE_SIZE||r>n.MAX_GUIDELINE_TEXTURE_SIZE||!o)return;const a=`${e}_${i}_${r}`,l=this.guidelineTextures.get(a);if(l)return l.needed=!0,a;const c=new Float32Array(o);for(let u=0;u<r;u++){const h=t[u],_=u*i*4;c.set(h,_)}const d=new C(c,{size:[i,r],magFilter:C.NearestFilter,minFilter:C.NearestFilter,wrapS:C.ClampToEdgeWrapping,wrapT:C.ClampToEdgeWrapping,type:C.Float,format:C.RgbaFormat,generateMipmaps:!1,flipY:!1,premultiplyAlpha:!1});return this.guidelineTextures.set(a,{texture:d,needed:!0}),a}getGuidelineTexture(e){const t=this.guidelineTextures.get(e);if(!(!t||!t.needed))return t.texture}addLabels(e,t,i){this.enrichWithElevation(i,e),this.enrichTieredLabelsWithMeshHeights(i),this.worker.appendLabels(e,t,i,this.state.styleState,this.state.styleZoom,this.state.pitch),this.alwaysActiveLabelKeys.push(e),this.state.needLabeling=!0}addTileLabels(e,t,i){this.enrichWithElevation(i,e),this.enrichTieredLabelsWithMeshHeights(i),this.worker.appendLabels(e,t,i,this.state.styleState,this.state.styleZoom,this.state.pitch),this.state.needLabeling=!0}addLabelBox(e,t){this.worker.appendLabelBox(e,t),this.state.needLabeling=!0}removeLabels(e){this.worker.removeLabels(e);const t=this.alwaysActiveLabelKeys.indexOf(e);t!==-1&&this.alwaysActiveLabelKeys.splice(t,1),this.state.needLabeling=!0}isLabelBoxSurvived(e){return this.survivedLabelBoxes.has(e)}setLayoutCacheMode(e){this.worker.setLayoutCacheMode(e)}clearPreviousLabels(){this.worker.clearPreviousLabels()}resetHysteresis(){this.skipHysteresisInNextLabeling=!0,this.state.needLabeling=!0}getLabelingRevision(){return this.labelTileRevision}getMemoryFootprint(){const e={labelTiles:this.labelTiles.map(t=>({[t.purpose]:n.tileObjectStatsGpu(t)}))};return{gpu:V(I({},e),{"--sum":n.getTotalMemory(e)})}}generateLabelingTile(){const e=n.getBoundsTileCoords(n.tetragonBounds(this.state.tilesBounds),n.labeling.tileMultiplier);let t=[{coords:e,center:this.state.center,tilesBounds:this.state.tilesBounds}];if(!this.state.globeMode)if(e[2]<0)t=[{coords:[0,0,0,0],center:[0,0,0],tilesBounds:[[-n.HALF_WORLD_SIZE,-n.HALF_WORLD_SIZE,0],[n.HALF_WORLD_SIZE,-n.HALF_WORLD_SIZE,0],[n.HALF_WORLD_SIZE,n.HALF_WORLD_SIZE,0],[-n.HALF_WORLD_SIZE,n.HALF_WORLD_SIZE,0]]}];else{const l=n.getTileBounds(e),c=Re(2,e[2]),d=l.min[0]<-n.HALF_WORLD_SIZE,u=l.max[0]>n.HALF_WORLD_SIZE;if(d||u){const h=[...e];h[0]+=d?c:-c;const _=[...this.state.center];_[0]+=d?n.worldSize:-n.worldSize;const{min:f,max:m}=n.getTileBounds(h);t.push({coords:h,center:_,tilesBounds:[[f[0],f[1],0],[m[0],f[1],0],[m[0],m[1],0],[f[0],m[1],0]]})}}const i=this.modules.tileManager.getLabelingData(),r=t.map(({coords:l,center:c,tilesBounds:d})=>({center:c,elevation:this.state.demMode?this.state.elevation:void 0,zoom:this.state.zoom,styleZoom:this.state.styleZoom,rotation:this.state.rotation,size:this.state.size,pitch:this.state.pitch,viewport:this.state.viewport,padding:this.state.padding,globeMode:this.state.globeMode,styleState:this.state.styleState,buildingHeight:this.modules.buildingHeightAnimator.getDefaultBuildingHeight(),tilesBounds:d,debugLabels:this.modules.labelsDebug.isEnabled(),disableSurvivedPoiPrevalence:this.state.disableSurvivedPoiPrevalence,tileInfo:n.createTileInfo(l),cameraConfig:this.state.cameraConfig,tiersOn:this.state.immersiveLevel.tiers,demMode:this.state.demMode})),o=P1(this.state.styleZoom,this.state.cityCommPoiLabeling),a=performance.now();this.worker.processLabels(i,this.alwaysActiveLabelKeys,r,window.devicePixelRatio,this.modules.floorManager.getActiveFloorHiddenIds(),I(I({},n.labeling.commercialMargins),o),this.skipHysteresisInNextLabeling,this.modules.floorManager.getPlanLevels(),this.collectStats).then(({results:l,startAt:c,endAt:d})=>{const u=performance.now();this.survivedLabelBoxes.clear(),this.labelTiles.forEach(p=>{this.modules.tileManager.removeObject(p),p.clean(this.state)}),this.labelTiles.length=0,this.invalidateGuidelineTextures();const h=[];l.forEach((p,x)=>{p.survivedLabelBoxIds.forEach(P=>this.survivedLabelBoxes.add(P)),h.push(...p.survivedCommPois),this.modules.assetManager.loadRasters(p.collectorOutput.rastersToLoad);const S=r[x];if(S===void 0)return;const{globeMode:b,styleState:T,tileInfo:y}=S,E=new n.TileObject("labeling",p.collectorOutput.data,this.modules,this.state,y.coords,void 0,void 0);E.ecefDataState=n.ecefDataStateFromBool(n.isLabelingEcef(b,T,y)),this.labelTiles.push(E),this.modules.tileManager.addObject(E)}),this.processSurvivedCommPoiIds(h),this.labelTileRevision++,this.removeNeedlessGuidelineTextures();const _=this.state.metrics;_.firstlabeling===void 0&&l.some(({collectorOutput:p})=>p.data.length>0)&&(_.firstlabeling=performance.now()-_.start);const{animationTime:f,animationType:m,interval:v}=n.labeling;E1(this.state,m,0,1,Math.min(f,v)),this.modules.renderer.addRerenderEvent(),this.modules.identifier.queryFillCache(),l[0].labels&&e[2]>=0&&this.modules.labelsDebug.drawLabels(l[0].labels),this.isLabelingInProgress=!1;const g=l[0].stats;g!==void 0&&(this.stats.length===L1&&this.stats.shift(),this.stats.push(V(I({},g),{roundtripMs:u-a,toWorkerMs:c-performance.timeOrigin-a,workerMs:d-c,fromWorkerMs:performance.timeOrigin+u-d,mainMs:performance.now()-u,states:l.length})))}),this.skipHysteresisInNextLabeling=!1}processSurvivedCommPoiIds(e){if(e.length===0){this.prevSurvivedCommPoiIds.clear();return}const t=e.filter(i=>!this.prevSurvivedCommPoiIds.has(i.id));t.length!==0&&this.modules.map.emit("commpoishow",{commPois:t}),this.prevSurvivedCommPoiIds=new Set(e.map(i=>i.id))}enrichWithElevation(e,t){const{demManager:i,map:r}=this.modules;if(r.state.demMode){const o=this.demKeys[t],a=i.getLabelsDemKey(e);if(a===void 0||a===o)return;i.enrichWithElevation(e),this.demKeys[t]=a}}enrichTieredLabelsWithMeshHeights(e){const t=this.state.styleState.terrainEnabled===!0,i=this.state.styleState.immersiveRoadsOn===!0;if(!t&&!i)return;const r=[0,0,0],o=[0,0,0];e.forEach(({labels:a})=>{a.forEach(l=>{var f,m;if(l.type!==n.PreLabelType.Line&&l.type!==n.PreLabelType.OneWayLine||!l.screenSpace)return;let c=(m=(f=l.tiers)==null?void 0:f[0])!=null?m:0;if(!c&&!t&&i)return;c!==0&&t&&!i&&(c=0);const d=n.createTileInfo(l.tileCoords),{vertices:u}=l,h=[],_=[];for(let v=0;v<u[0].length;v++){o[0]=u[0][v],o[1]=u[1][v],n.tilePointToMapPoint(r,o,d);const g=this.modules.elevationIndex.getElevationAtTier(r,c,{tryToGetAbsZFirst:!0});if(g){const{relativeZ:p,absoluteZ:x}=g;h.push(p*n.MAP_POINTS_IN_METER),x!==void 0&&_.push(x*n.MAP_POINTS_IN_METER)}}h.length===u[0].length&&(u[2]=new Int32Array(h)),_.length===u[0].length&&(u[3]=new Int32Array(_))})})}invalidateGuidelineTextures(){this.guidelineTextures.forEach(e=>{e.needed=!1})}removeNeedlessGuidelineTextures(){Array.from(this.guidelineTextures).filter(([e,t])=>!t.needed).forEach(([e,t])=>{t.texture.remove(),this.guidelineTextures.delete(e)})}}class dn{constructor(e,t,i){this.type=e,this.handler=i,this.mouseDownPoint=t,this.handler.mapState.userHasInteracted=!0,this.handler.modules.map.emit("interactionstart",{target:"pitch/rotation"})}processAction(e){switch(e.type){case"mousemove":return this.processMouseMoveAction(e);case"mouseup":return this.processMouseUpAction(e);case"keyup":return this.processKeyUpAction(e);default:return this}}processMouseMoveAction(e){const t=ze(this.handler.container,e.clientX,e.clientY);return new Uh(this.type,this.mouseDownPoint,t,this.handler)}processMouseUpAction(e){switch(this.type){case"keyPrimary":if(e.button===0&&(e.ctrlKey||e.metaKey))return this.returnToInitialState();break;case"secondary":if(e.button===2){const t=ze(this.handler.container,e.clientX,e.clientY);return this.handler.modules.identifier.search("contextmenu",t,!0).then(i=>{Nt("contextmenu",i,e,t,this.handler.modules)}),this.returnToInitialState()}break;case"auxiliary":if(e.button===1)return this.returnToInitialState();break}return this}processKeyUpAction(e){return this.type==="keyPrimary"&&(e.key==="Control"||e.key==="Meta")?(this.handler.modules.map.emit("interactionend",{target:"pitch/rotation"}),new Is(this.mouseDownPoint,this.handler)):this}returnToInitialState(){return this.handler.mapState.userHasInteracted=!0,this.handler.modules.map.emit("interactionend",{target:"pitch/rotation"}),new pt(this.handler)}}class Uh{constructor(e,t,i,r){this.type=e,this.mouseDownPoint=t,this.mouseMovePoint=i,this.handler=r,this.handler.mapState.userHasInteracted=!0,(!this.handler.mapState.disablePitchByUserInteraction||!this.handler.mapState.disableRotationByUserInteraction)&&this.handler.container.classList.add("mapgl-rotating"),this.update(this.handler.mapState)}processAction(e){switch(e.type){case"mousemove":return this.processMouseMoveAction(e);case"mouseleave":return this.returnToInitialState();case"mouseup":return this.processMouseUpAction(e);case"keyup":return this.processKeyUpAction(e);default:return this}}update(e){this.mouseDownPoint[0]===0&&this.mouseDownPoint[1]===0&&(this.mouseDownPoint=this.mouseMovePoint);const t=n.normalizeMousePosition(e.size,this.mouseDownPoint),i=n.normalizeMousePosition(e.size,this.mouseMovePoint),r=(t[0]-i[0])*n.zoom.mouseRotateDelta,o=(i[1]-t[1])*n.zoom.mousePitchDelta;Jt(e),e.disableRotationByUserInteraction||Xi(e,e.rotation+r,{animate:!1}),e.disablePitchByUserInteraction||gn(e,n.clamp(e.pitch+o,e.minPitch,e.maxPitch),{animate:!1}),this.mouseDownPoint=this.mouseMovePoint,this.handler.modules.renderer.addRerenderEvent()}processMouseMoveAction(e){return this.mouseMovePoint=ze(this.handler.container,e.clientX,e.clientY),this.handler.mapState.userHasInteracted=!0,this.update(this.handler.mapState),this}processMouseUpAction(e){switch(this.type){case"keyPrimary":if(e.button===0&&(e.ctrlKey||e.metaKey))return this.returnToInitialState();break;case"secondary":if(e.button===2)return this.returnToInitialState();break;case"auxiliary":if(e.button===1)return this.returnToInitialState();break}return this}processKeyUpAction(e){return this.type==="keyPrimary"&&(e.key==="Control"||e.key==="Meta")?(this.handler.container.classList.remove("mapgl-rotating"),this.handler.modules.map.emit("interactionend",{target:"pitch/rotation"}),new Is(this.mouseMovePoint,this.handler)):this}returnToInitialState(){return this.handler.mapState.userHasInteracted=!0,this.handler.container.classList.remove("mapgl-rotating"),this.handler.modules.map.emit("interactionend",{target:"pitch/rotation"}),new pt(this.handler)}}class Is{constructor(e,t){this.handler=t,this.toInitialOnMouseUp=!1,this.mouseDownPoint=e,this.dragStartPoint=e,this.isTimerStarted=this.handler.dblClickTimer!==void 0,this.handler.mapState.userHasInteracted=!0,this.handler.modules.map.emit("interactionstart",{target:"center"}),this.isTimerStarted&&(window.clearTimeout(this.handler.dblClickTimer),this.handler.dblClickTimer=void 0)}processAction(e){switch(e.type){case"mousedown":return this.toInitialOnMouseUp=!0,this;case"mouseup":return this.processMouseUpAction(e);case"mousemove":return this.processMouseMoveAction(e);case"click":return this.processMouseClickAction(e);case"keydown":return this.processKeyDownAction(e);default:return this}}processMouseUpAction(e){return e.button===0&&(this.toInitialOnMouseUp||!this.handler.modules.layout.isActionWithCanvas(e))?(this.handler.mapState.userHasInteracted=!0,this.handler.modules.map.emit("interactionend",{target:"center"}),new pt(this.handler)):this}processMouseMoveAction(e){const t=ze(this.handler.container,e.clientX,e.clientY);return this.handler.mapState.disableDragging?(this.mouseDownPoint=t,this.dragStartPoint=t,this.toInitialOnMouseUp=!0,this):n.distance(this.mouseDownPoint,t)<n.events.dragThreshold?(this.dragStartPoint=t,this):new Mh(t,this.dragStartPoint,this.handler)}processMouseClickAction(e){if(!this.handler.modules.layout.isActionWithCanvas(e))return this;if(this.isTimerStarted){if(this.handler.mapState.zoom<this.handler.mapState.maxZoom){const t=this.handler.mapState,i=Math.min(t.zoom+1,t.maxZoom),r=ze(this.handler.container,e.clientX,e.clientY);Jt(t),Qt(t,i,{duration:n.zoom.animDuration,zoomPoint:t.keepCenterWhileUserZoomRotate?void 0:r}),this.handler.modules.renderer.addRerenderEvent()}}else{const t=ze(this.handler.container,e.clientX,e.clientY);this.handler.modules.identifier.search("mouseClick",t,!0).then(i=>{this.handler.dblClickTimer||(this.handler.dblClickTimer=window.setTimeout(()=>{Nt("click",i,e,t,this.handler.modules),this.handler.dblClickTimer=void 0},n.events.doubleClickTime))})}return this.handler.mapState.userHasInteracted=!0,this.handler.modules.map.emit("interactionend",{target:"center"}),new pt(this.handler)}processKeyDownAction(e){return e.key==="Control"||e.key==="Meta"?(this.handler.modules.map.emit("interactionend",{target:"center"}),new dn("keyPrimary",this.mouseDownPoint,this.handler)):this}}class Mh{constructor(e,t,i){this.mouseMovePoint=e,this.dragStartPoint=t,this.handler=i,this.handler.container.classList.add("mapgl-dragging"),this.handler.mapState.userHasInteracted=!0,this.update(this.handler.mapState)}processAction(e){switch(e.type){case"mousemove":return this.processMouseMoveAction(e);case"mouseup":return this.processMouseUpAction(e);case"keydown":return this.processKeyDownAction(e);default:return this}}update(e){const t=this.handler.modules.camera,i=t.flat.unproject(this.dragStartPoint),r=t.flat.unproject(this.mouseMovePoint);if(e.globeMode){const a=n.adjustGlobeDragSpeed(t.globeRatio,n.Mercator.toGeo(e.center));n.scale(i,i,a),n.scale(r,r,a)}const o=n.clone$1(e.center);n.add$1(o,o,i),n.sub$1(o,o,r),Jt(e),hi(e,o,{animate:!1}),this.dragStartPoint=this.mouseMovePoint,this.handler.modules.renderer.addRerenderEvent()}processMouseMoveAction(e){return this.mouseMovePoint=ze(this.handler.container,e.clientX,e.clientY),this.handler.mapState.userHasInteracted=!0,this.update(this.handler.mapState),this}processMouseUpAction(e){return e.button===0?this.returnToInitialState():this}processKeyDownAction(e){return e.key==="Control"||e.key==="Meta"?(this.handler.container.classList.remove("mapgl-dragging"),this.handler.modules.map.emit("interactionend",{target:"center"}),new dn("keyPrimary",this.mouseMovePoint,this.handler)):this}returnToInitialState(){return this.handler.container.classList.remove("mapgl-dragging"),this.handler.modules.map.emit("interactionend",{target:"center"}),this.handler.mapState.userHasInteracted=!0,new pt(this.handler)}}function Ps(s,e){if(!e.modules.layout.isActionWithCanvas(s))return;const t=F1(s,e.container);if(!t)return;const i=e.modules.identifier.searchSync(t);Nt("touchmove",i,s,t,e.modules)}function F1(s,e){var i;const t=(i=s.changedTouches[0])!=null?i:s.touches[0];if(t)return ze(e,t.clientX,t.clientY)}class Hh{constructor(e,t,i){this.handler=i,this.touchStartPoints=t,this.touchMovePoints=e,this.handler.mapState.userHasInteracted=!0,this.handler.mapState.disablePitchByUserInteraction||this.handler.container.classList.add("mapgl-rotating"),this.update(this.handler.mapState)}processAction(e){switch(e.type){case"touchstart":return this.processTouchStartAction(e);case"touchmove":return this.processTouchMoveAction(e);case"touchend":return this.processTouchEndAction(e);default:return this}}processTouchStartAction(e){return this.handler.container.classList.remove("mapgl-rotating"),this.handler.modules.map.emit("interactionend",{target:"pitch/zoom/rotation"}),new un(e,this.handler,!1)}processTouchMoveAction(e){return e.preventDefault(),this.touchMovePoints=Bt(e.touches,this.handler.container),Ps(e,this.handler),this.handler.mapState.userHasInteracted=!0,this.update(this.handler.mapState),this}processTouchEndAction(e){return this.handler.container.classList.remove("mapgl-rotating"),this.handler.modules.map.emit("interactionend",{target:"pitch/zoom/rotation"}),e.touches.length===0?(this.handler.mapState.userHasInteracted=!0,new pt(this.handler)):new un(e,this.handler,!1)}}class As extends Hh{constructor(e,t,i){super(e,t,i),this.startPxAngle=0,this.rotationDetected=!1,t.length>1&&(this.startPxAngle=n.calcAngle(t[0],t[1]))}update(e){if(this.touchStartPoints.length<2||this.touchMovePoints.length<2)return;const t=n.calcMidpoint(this.touchMovePoints[0],this.touchMovePoints[1]),i=n.dist(this.touchMovePoints[0],this.touchMovePoints[1]),r=n.dist(this.touchStartPoints[0],this.touchStartPoints[1]),o=i/r,a=e.zoom+Math.log(o)/Math.log(2)*n.zoom.mobilePinchDelta;let l=0,c=0;if(!this.rotationDetected){const h=n.calcAngle(this.touchMovePoints[0],this.touchMovePoints[1]);c=Math.abs(this.startPxAngle-h),c>Math.PI&&(c=2*Math.PI-c),c>=this.handler.mapState.touchRotationThreshold&&(this.rotationDetected=!0)}if(this.rotationDetected){const h=this.handler.modules.camera.flat.unproject(this.touchStartPoints[0]),_=this.handler.modules.camera.flat.unproject(this.touchStartPoints[1]),f=this.handler.modules.camera.flat.unproject(this.touchMovePoints[0]),m=this.handler.modules.camera.flat.unproject(this.touchMovePoints[1]);if(h&&_&&f&&m){const v=n.calcAngle(h,_),g=n.calcAngle(f,m);l=v-g}}const d=e.rotation+l,u=e.center;e.keepCenterWhileUserZoomRotate||n.add$1(u,e.center,n.getCenterCorrection(e,t,{zoom:a,rotation:d})),Jt(e),hi(e,u,{animate:!1}),Qt(e,a,{animate:!1}),this.handler.mapState.disableRotationByUserInteraction||Xi(e,d,{animate:!1}),this.touchStartPoints=this.touchMovePoints,this.handler.modules.renderer.addRerenderEvent()}}class Gh extends Hh{constructor(e,t,i){super(e,t,i)}update(e){const t=this.touchStartPoints.map(l=>n.normalizeMousePosition(e.size,l)),i=this.touchMovePoints.map(l=>n.normalizeMousePosition(e.size,l)),r=n.calcMidpoint(t[0],t[1]),a=(n.calcMidpoint(i[0],i[1])[1]-r[1])*n.zoom.mousePitchDelta;Jt(e),gn(e,n.clamp(e.pitch+a,e.minPitch,e.maxPitch),{animate:!1}),this.touchStartPoints=this.touchMovePoints,this.handler.modules.renderer.addRerenderEvent()}}class un{constructor(e,t,i){this.handler=t,this.needClickOnTouchEnd=i,this.toZoomRotate=!1,this.touchStartPoints=Bt(e.touches,this.handler.container),this.handler.mapState.userHasInteracted=!0,this.isTimerStarted=this.handler.dblClickTimer!==void 0,Ot(e)?this.startedInteractionTarget="pitch/zoom/rotation":this.isTimerStarted?(this.startedInteractionTarget="zoom/rotation",window.clearTimeout(this.handler.dblClickTimer),this.handler.dblClickTimer=void 0):this.startedInteractionTarget="center",this.handler.modules.map.emit("interactionstart",{target:this.startedInteractionTarget})}processAction(e){switch(e.type){case"touchstart":return this.processTouchStartAction(e);case"touchmove":return this.processTouchMoveAction(e);case"touchend":return this.processTouchEndAction(e);default:return this}}getStartedInteractionTarget(){return this.startedInteractionTarget}processTouchStartAction(e){return e.preventDefault(),this.touchStartPoints.length===1&&(this.needClickOnTouchEnd=!1,this.handler.modules.map.emit("interactionend",{target:"center"}),this.startedInteractionTarget="pitch/zoom/rotation",this.handler.modules.map.emit("interactionstart",{target:this.startedInteractionTarget}),this.handler.mapState.userHasInteracted=!0),this.touchStartPoints=Bt(e.touches,this.handler.container),this}processTouchMoveAction(e){e.preventDefault();const t=Bt(e.touches,this.handler.container);if(Ps(e,this.handler),!Ot(e))return n.distance(this.touchStartPoints[0],t[0])<n.events.dragThreshold?(this.touchStartPoints=t,this):this.isTimerStarted?new Vh(t[0],this.touchStartPoints[0],this.handler):this.handler.mapState.disableDragging?(this.touchStartPoints=t,this.needClickOnTouchEnd=!1,this):new al(t[0],this.touchStartPoints[0],this.handler);if(this.touchStartPoints.length<2)return this.processTouchStartAction(e);const i=n.create$6(),r=n.create$6();n.sub(i,t[0],this.touchStartPoints[0]),n.sub(r,t[1],this.touchStartPoints[1]);const o=n.dot$1(i,r);if(o>0){if(this.handler.mapState.enableTwoFingerDragging&&this.touchStartPoints.length===2)return n.distance(this.touchStartPoints[0],t[0])<n.events.dragThreshold?(this.touchStartPoints=t,this):new al(t[0],this.touchStartPoints[0],this.handler);const l=n.distance(this.touchStartPoints[0],t[0]),c=n.distance(this.touchStartPoints[1],t[1]);return l<n.events.pitchThreshold||c<n.events.pitchThreshold?(this.touchStartPoints=t,this):this.handler.mapState.disablePitchByUserInteraction?this:new Gh(t,this.touchStartPoints,this.handler)}return o<0?new As(t,this.touchStartPoints,this.handler):n.isNullVector(i)||n.isNullVector(r)?this.pitchWaitingTimer?this:this.toZoomRotate?(this.toZoomRotate=!1,new As(t,this.touchStartPoints,this.handler)):(this.pitchWaitingTimer=window.setTimeout(()=>{this.toZoomRotate=!0,this.pitchWaitingTimer=void 0},n.events.pitchWaitingTime),this):new As(t,this.touchStartPoints,this.handler)}processTouchEndAction(e){return e.cancelable&&e.preventDefault(),e.touches.length===0?e.changedTouches.length===1&&this.needClickOnTouchEnd?this.processTouchClickAction(this.touchStartPoints[0],e):(this.handler.mapState.userHasInteracted=!0,this.handler.modules.map.emit("interactionend",{target:e.changedTouches.length>1?"pitch/zoom/rotation":"center"}),new pt(this.handler)):(Ot(e)||(this.handler.modules.map.emit("interactionend",{target:"pitch/zoom/rotation"}),this.startedInteractionTarget="center",this.handler.modules.map.emit("interactionstart",{target:this.startedInteractionTarget}),this.handler.mapState.userHasInteracted=!0),this.touchStartPoints=Bt(e.touches,this.handler.container),this)}processTouchClickAction(e,t){if(this.isTimerStarted){if(this.handler.mapState.zoom<this.handler.mapState.maxZoom){const i=this.handler.mapState,r=Math.min(i.zoom+1,i.maxZoom),o=i.keepCenterWhileUserZoomRotate?void 0:e;Jt(i),Qt(i,r,{duration:n.zoom.animDuration,zoomPoint:o}),this.handler.modules.renderer.addRerenderEvent()}}else if(this.handler.modules.layout.isActionWithCanvas(t))this.handler.modules.identifier.search("mouseClick",e,!0).then(i=>{this.handler.dblClickTimer||(this.handler.dblClickTimer=window.setTimeout(()=>{Nt("click",i,t,e,this.handler.modules),this.handler.dblClickTimer=void 0},n.events.doubleClickTime))});else{const i=t.changedTouches[0];t.target&&i&&t.target.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,clientX:i.clientX,clientY:i.clientY}))}return this.handler.mapState.userHasInteracted=!0,this.handler.modules.map.emit("interactionend",{target:"center"}),new pt(this.handler)}}class al{constructor(e,t,i){this.handler=i,this.touchMovePoint=e,this.touchStartPoint=t,this.handler.mapState.userHasInteracted=!0,this.handler.container.classList.add("mapgl-dragging"),this.update(this.handler.mapState)}processAction(e){switch(e.type){case"touchstart":return this.processTouchStartAction(e);case"touchmove":return this.processTouchMoveAction(e);case"touchend":return this.processTouchEndAction();default:return this}}update(e){const t=this.handler.modules.camera,i=t.flat.unproject(this.touchStartPoint),r=t.flat.unproject(this.touchMovePoint);if(e.globeMode){const a=n.adjustGlobeDragSpeed(t.globeRatio,n.Mercator.toGeo(e.center));n.scale(i,i,a),n.scale(r,r,a)}const o=n.clone$1(e.center);n.add$1(o,o,i),n.sub$1(o,o,r),Jt(e),hi(e,o,{animate:!1}),this.touchStartPoint=this.touchMovePoint,this.handler.modules.renderer.addRerenderEvent()}processTouchStartAction(e){return this.handler.container.classList.remove("mapgl-dragging"),this.handler.modules.map.emit("interactionend",{target:"center"}),new un(e,this.handler,!1)}processTouchMoveAction(e){e.preventDefault();const t=Bt(e.touches,this.handler.container);return this.touchMovePoint=t[0],Ps(e,this.handler),this.handler.mapState.userHasInteracted=!0,this.update(this.handler.mapState),this}processTouchEndAction(){return this.handler.container.classList.remove("mapgl-dragging"),this.handler.modules.map.emit("interactionend",{target:"center"}),this.handler.mapState.userHasInteracted=!0,new pt(this.handler)}}class Vh{constructor(e,t,i){this.handler=i,this.mapHeight=i.mapState.size[1],this.startZoom=i.mapState.zoom,this.touchMovePointY=e[1],this.touchStartPoint=t,this.handler.mapState.userHasInteracted=!0,this.update(this.handler.mapState)}processAction(e){switch(e.type){case"touchstart":return this.processTouchStartAction(e);case"touchmove":return this.processTouchMoveAction(e);case"touchend":return this.processTouchEndAction();default:return this}}update(e){const t=this.touchMovePointY-this.touchStartPoint[1];if(t===0)return;const i=t/this.mapHeight,r=n.clamp(this.startZoom+i*n.zoom.mobileTapDelta,e.minZoom,e.maxZoom),o=e.center;e.keepCenterWhileUserZoomRotate||n.add$1(o,e.center,n.getCenterCorrection(e,this.touchStartPoint,{zoom:r})),Jt(e),hi(e,o,{animate:!1}),Qt(e,r,{animate:!1}),this.handler.modules.renderer.addRerenderEvent()}processTouchStartAction(e){return this.handler.modules.map.emit("interactionend",{target:"zoom/rotation"}),new un(e,this.handler,!1)}processTouchMoveAction(e){e.preventDefault();const t=Bt(e.touches,this.handler.container);return this.touchMovePointY=t[0][1],Ps(e,this.handler),this.handler.mapState.userHasInteracted=!0,this.update(this.handler.mapState),this}processTouchEndAction(){return this.handler.modules.map.emit("interactionend",{target:"zoom/rotation"}),this.handler.mapState.userHasInteracted=!0,new pt(this.handler)}}class pt{constructor(e){this.handler=e}processAction(e){switch(e.type){case"mousedown":return this.processMouseDownAction(e);case"touchstart":return this.processTouchStartAction(e);default:return this}}processMouseDownAction(e){const t=ze(this.handler.container,e.clientX,e.clientY);switch(e.button){case 0:if(e.ctrlKey||e.metaKey)return new dn("keyPrimary",t,this.handler);if(this.handler.modules.layout.isActionWithCanvas(e)){const i=this.handler.modules.identifier.searchSync(t);Nt("mousedown",i,e,t,this.handler.modules)}return new Is(t,this.handler);case 1:return new dn("auxiliary",t,this.handler);case 2:return new dn("secondary",t,this.handler);default:return this}}processTouchStartAction(e){if(e.preventDefault(),!e.touches)return this;if(this.handler.modules.layout.isActionWithCanvas(e)){const t=ze(this.handler.container,e.changedTouches[0].clientX,e.changedTouches[0].clientY),i=this.handler.modules.identifier.searchSync(t);Nt("touchstart",i,e,t,this.handler.modules)}return new un(e,this.handler,e.touches.length===1)}}class Ls{processAction(){return this}}class D1{constructor(e,t){this.preventDefault=i=>{i.preventDefault()},this.onMouseMove=i=>{this.dblClickTimer&&(this.dblClickTimer=void 0),this.switchState(i)},this.onTouchStart=i=>{this.modules.layout.isActionWithMap(i)&&this.switchState(i)},this.switchState=i=>{this.state;const r=this.state.processAction(i);this.state instanceof Ls||(this.state=r)},this.state=new pt(this),this.mapState=e,this.modules=t,this.container=t.layout.mapContainer,document.addEventListener("mouseup",this.switchState),document.addEventListener("keydown",this.switchState),document.addEventListener("keyup",this.switchState),document.addEventListener("mouseleave",this.switchState),document.addEventListener("mousemove",this.onMouseMove),this.container.addEventListener("click",this.switchState),this.container.addEventListener("mousedown",this.switchState),this.container.addEventListener("mouseout",this.switchState),document.addEventListener("touchstart",this.onTouchStart),document.addEventListener("touchend",this.switchState),document.addEventListener("touchmove",this.switchState),this.container.addEventListener("dragstart",this.preventDefault),this.container.addEventListener("drag",this.preventDefault),this.container.addEventListener("dragend",this.preventDefault),this.container.addEventListener("contextmenu",this.preventDefault),this.container.addEventListener("touchmove",this.preventDefault)}destroy(){document.removeEventListener("mouseup",this.switchState),document.removeEventListener("keydown",this.switchState),document.removeEventListener("keyup",this.switchState),document.removeEventListener("mouseleave",this.switchState),document.removeEventListener("mousemove",this.onMouseMove),this.container.removeEventListener("click",this.switchState),this.container.removeEventListener("mousedown",this.switchState),this.container.removeEventListener("mouseout",this.switchState),document.removeEventListener("touchstart",this.onTouchStart),document.removeEventListener("touchend",this.switchState),document.removeEventListener("touchmove",this.switchState),this.container.removeEventListener("dragstart",this.preventDefault),this.container.removeEventListener("drag",this.preventDefault),this.container.removeEventListener("dragend",this.preventDefault),this.container.removeEventListener("contextmenu",this.preventDefault),this.container.removeEventListener("touchmove",this.preventDefault)}block(){if(this.state instanceof Ls)return;const{map:e}=this.modules;switch(this.container.classList.remove("mapgl-dragging"),this.container.classList.remove("mapgl-rotating"),this.state.constructor){case Is:case Mh:case al:e.emit("interactionend",{target:"center"});break;case dn:case Uh:e.emit("interactionend",{target:"pitch/rotation"});break;case Vh:e.emit("interactionend",{target:"zoom/rotation"});break;case As:case Gh:e.emit("interactionend",{target:"pitch/zoom/rotation"});break;case un:{const t=this.state.getStartedInteractionTarget();e.emit("interactionend",{target:t});break}}this.state=new Ls}unblock(){this.state instanceof pt||this.state instanceof Ls&&(this.state=new pt(this))}}const z1=new Set([n.UNIVERSE_REGION_ID]);class ll extends Error{constructor(e,t){super(e),this.name="TrafficFetchMetaError",this.noRetry=t}}class B1{constructor(e,t){this.mapState=e,this.modules=t,this.fetchMetaRetryAttempt=null,this.justEnabled=this.mapState.trafficOn,this.isMetaLoading=!1,this.lastUpdateTime=-1/0,this.regionIds=new Set,this.id=n.uniqId();const i=t.identifier.getIdScope(n.DEFAULT_ID_SCOPE);this.gridState=n.createGridState("traffic",0,this.id,e.trafficMinZoom,e.trafficMaxZoom,e.trafficMinZoom,e.trafficMaxDetailLevel,t,e,i),this.viewportDiffer=new n.Differ([{path:"center",type:"vec2"},{path:"zoom",type:"number"},{path:"size",type:"vec2"},{path:"rotation",type:"number"},{path:"pitch",type:"number"},{path:"demMode",type:"boolean"}])}show(){this.mapState.trafficOn||(this.mapState.trafficOn=!0,this.justEnabled=!0,this.modules.map.patchStyleState({trafficOn:!0}),this.modules.map.emit("trafficshow"))}hide(){this.mapState.trafficOn&&(n.resetGridState(this.gridState),this.mapState.trafficOn=!1,this.justEnabled=!1,this.modules.map.patchStyleState({trafficOn:!1}),this.modules.map.emit("traffichide"))}isEnabled(){return this.mapState.trafficOn}destroy(){n.resetGridState(this.gridState)}redraw(){this.mapState.trafficOn&&(n.resetGridState(this.gridState),n.viewportChangeAction(this.gridState,this.mapState,this.modules))}activateStyleUpdating(){this.mapState.trafficOn&&n.startStyleUpdatingAction(this.modules,this.gridState,this.mapState.handyStyleId,this.modules.styleManager.getStyleRevision(this.mapState.handyStyleId),this.modules.map.core.getIsFirstStyleUpdate())}finishStyleUpdating(){this.mapState.trafficOn&&n.finishStyleUpdatingAction(this.gridState)}update(){if(!this.mapState.trafficOn)return;let e=!1;if(n.equalSets(this.regionIds,this.mapState.shownRegionIds)||(this.regionIds=new Set(this.mapState.shownRegionIds),e=!0),Date.now()-this.lastUpdateTime>n.traffic.updateInterval&&(e=!0,this.fetchMetaRetryAttempt=null),this.fetchMetaRetryAttempt!==null&&this.fetchMetaRetryAttempt<n.traffic.fetchMetaRetryDelays.length&&Date.now()-this.lastUpdateTime>n.traffic.fetchMetaRetryDelays[this.fetchMetaRetryAttempt]&&(this.fetchMetaRetryAttempt++,e=!0),e&&this.fetchMeta(),this.timestamp===void 0)return;(this.viewportDiffer.check(this.mapState)||this.justEnabled)&&(this.justEnabled=!1,n.viewportChangeAction(this.gridState,this.mapState,this.modules),this.modules.renderer.addRerenderEvent());const t=I({},this.gridState.displayedMods);n.newFrameAction(this.gridState,this.mapState,this.modules),this.fetch(n.getTilesToFetch(this.gridState),this.timestamp),this.abortFetch(n.getTilesToAbortFetch(this.gridState)),this.generate(n.getTilesToGenerate(this.gridState)),this.clearTiles(n.getTilesToRemove(this.gridState)),n.updateScene(this.modules,this.mapState,this.gridState,t)}viewportTilesReady(){return n.viewportTilesReady(this.gridState.tiles,this.gridState.viewportTiles)}getMemoryFootprint(){const e=this.gridState,t={gridState:{displayedMods:Object.keys(e.displayedMods).map(r=>n.modStatsJs(e.displayedMods[r])),tileModsCache:e.tileModsCache.keys().filter(r=>!e.displayedMods[r]).map(r=>n.modStatsJs(e.tileModsCache.get(r)))}},i={gridState:{displayedMods:Object.keys(e.displayedMods).map(r=>n.modStatsGpu(e.displayedMods[r])),tileModsCache:e.tileModsCache.keys().filter(r=>!e.displayedMods[r]).map(r=>n.modStatsGpu(e.tileModsCache.get(r)))}};return{js:V(I({},t),{"--sum":n.getTotalMemory(t)}),gpu:V(I({},t),{"--sum":n.getTotalMemory(i)})}}fetch(e,t){e.sort((i,r)=>n.compare(this.mapState.center,i,r)).forEach(i=>O1(i,this.modules,this.mapState,this.regionIds,t))}abortFetch(e){e.forEach(t=>{this.modules.workers.parser.abortTrafficTileRequest(t.key)})}generate(e){e.sort((t,i)=>n.compare(this.mapState.center,t,i)).forEach(t=>{const i=n.getTileModToGenerate(t);i&&this.modules.workers.parser.generateTrafficTile({styleId:this.mapState.handyStyleId,coords:t.coords,pixelRatio:window.devicePixelRatio,styleState:this.mapState.styleState,sourceId:this.modules.defaultSource.getId()}).then(r=>{if(!r){n.logEmptyTileGenerationResponse("traffic");return}Array.isArray(r.results)&&n.addGeneratedDataToTileMod(i,r.results)})})}clearTiles(e){for(const t of e)this.modules.workers.parser.deleteTrafficTile(t.key),delete this.gridState.tiles[t.key]}fetchMeta(){if(this.isMetaLoading||!this.regionIds.size)return;if(n.equalSets(this.regionIds,z1)){console.warn("Traffic metadata request skip: only Universe"),this.lastUpdateTime=Date.now();return}this.isMetaLoading=!0;const e=this.mapState,t=n.template(n.traffic.timestampUrl,{host:e.trafficServer,protocol:e.trafficProtocol||e.tileProtocol,regions:Array.from(this.regionIds).join(",")});fetch(t).then(i=>{if(i.ok)return i.json();throw new ll(`Request traffic timestamp error with status ${i.status}`,!1)}).then(i=>{var o,a;if(!i.length||((o=i[0])==null?void 0:o.time)===void 0||((a=i[0])==null?void 0:a.score)===void 0)throw new ll(`Bad traffic timestamp and score response ${i.toString()}`,!0);let r=0;i.forEach(l=>r+=l.score),r=Math.round(r/i.length),this.modules.map.emit("trafficscore",{score:r}),this.timestamp=i[0].time,this.isMetaLoading=!1,this.lastUpdateTime=Date.now(),this.fetchMetaRetryAttempt=null,this.redraw()}).catch(i=>{var r;!(i instanceof ll)||!i.noRetry?this.fetchMetaRetryAttempt=(r=this.fetchMetaRetryAttempt)!=null?r:0:this.fetchMetaRetryAttempt=null,this.lastUpdateTime=Date.now(),this.isMetaLoading=!1,console.error(i)})}}function O1(s,e,t,i,r){i.size&&e.workers.parser.fetchTrafficTile({coords:s.coords,tileServer:t.trafficServer,tileProtocol:t.trafficProtocol||t.tileProtocol,regionIds:Array.from(i),timestamp:r}).then(()=>{s.status===n.TileStatus.Loading&&(s.serverMetadata=[{regionId:0,metatileHash:-2}])})}class w1{constructor(e){this.externalContainer=e,this.rootContainer=document.createElement("div"),this.rootContainer.style.position="relative",this.rootContainer.style.height="100%",this.rootContainer.style.width="100%",this.rootContainer.style.overflow="hidden",this.externalContainer.appendChild(this.rootContainer),this.mapContainer=document.createElement("div"),this.mapContainer.style.position="relative",this.mapContainer.style.height="100%",this.mapContainer.style.width="100%",this.mapContainer.style.touchAction="none",this.mapContainer.style.webkitUserSelect="none",this.mapContainer.style.userSelect="none",this.rootContainer.appendChild(this.mapContainer),this.canvas=document.createElement("canvas"),this.canvas.style.display="block",this.mapContainer.appendChild(this.canvas),this.htmlContainerInMap=document.createElement("div"),this.htmlContainerInMap.style.position="absolute",this.htmlContainerInMap.style.left="0",this.htmlContainerInMap.style.top="0",this.htmlContainerInMap.style.width="100%",this.htmlContainerInMap.style.height="0",this.htmlContainerInMap.style.webkitUserSelect="auto",this.htmlContainerInMap.style.userSelect="auto",this.mapContainer.appendChild(this.htmlContainerInMap),this.htmlContainerOutMap=document.createElement("div"),this.htmlContainerOutMap.style.position="absolute",this.htmlContainerOutMap.style.left="0",this.htmlContainerOutMap.style.top="0",this.htmlContainerOutMap.style.width="100%",this.htmlContainerOutMap.style.height="0",this.mapContainer.after(this.htmlContainerOutMap)}setCanvasSize(e,t){const i=window.devicePixelRatio;return this.canvas.width=e*i,this.canvas.height=t*i,this.canvas.style.width=e+"px",this.canvas.style.height=t+"px",this}destroy(){for(;this.externalContainer.lastChild;)this.externalContainer.removeChild(this.externalContainer.lastChild)}isActionWithCanvas(e){return e.target===this.canvas}isActionWithMap(e){return e instanceof MouseEvent||e instanceof KeyboardEvent?this.isTargetInMap(e.target):Array.from(e.touches).map(i=>i.target).some(i=>this.isTargetInMap(i))}isTargetInMap(e){return!e||!(e instanceof Node)?!1:this.mapContainer.contains(e)}}class N1{constructor(e){this.loadingCounter=0,this.isIdle=()=>this.loadingCounter===0,this.modules=e,this.textureKeys=[],this.texturesMap=new Map}addTexture(e,t){return q(this,null,function*(){this.loadingCounter++;const i=yield es(e);return this.storeTexture(i,t)})}addPreparedTexture(e){const t=`prepared-${n.uniqId()}`;return this.textureKeys.push(t),this.texturesMap.set(t,e),this.textureKeys.length-1}updatePreparedTexture(e,t){this.deleteTexture(e),this.texturesMap.set(this.textureKeys[e],t)}loadTexture(e,t){return q(this,null,function*(){this.loadingCounter++;const i=yield this.loadImage(e);if(!i){this.decreaseLoadingCounter();return}return this.storeTexture(i,t)})}getTexture(e){return this.texturesMap.get(this.textureKeys[e])}destroy(){this.textureKeys=[],this.texturesMap.clear()}deleteTexture(e){var i;const t=this.textureKeys[e];return(i=this.texturesMap.get(t))==null||i.remove(),this.texturesMap.delete(t)}getMemoryFootprint(){const e={texturesMap:Array.from(this.texturesMap.values()).map(n.textureSizeJs)},t={texturesMap:Array.from(this.texturesMap.values()).map(n.textureSizeGpu)};return{js:V(I({},e),{"--sum":n.getTotalMemory(e)}),gpu:V(I({},t),{"--sum":n.getTotalMemory(t)})}}decreaseLoadingCounter(){this.loadingCounter=Math.max(this.loadingCounter-1,0)}storeTexture(e,t){var f,m,v,g,p,x,S;const i=t==null?void 0:t.size,r=(f=t==null?void 0:t.pixelRatio)!=null?f:window.devicePixelRatio,o=(m=t==null?void 0:t.imagePadding)!=null?m:1;this.decreaseLoadingCounter();const a=e.getAttribute("src")||e.currentSrc,l=k1(a,i),c=this.textureKeys.indexOf(l);if(c>-1&&this.texturesMap.has(l))return c;const d=(i?[i[0],i[1]]:[e.width,e.height]).map(b=>b*r),u=fu(e,d);e.remove();const h=d.map(b=>b+2*o);if(!(t!=null&&t.skipAtlasSizeChecking)&&(h[0]>n.atlasSize[0]||h[1]>n.atlasSize[1]))throw new Error(`Image texture dimensions ${h} are larger than the maximum possible ${n.atlasSize}`);const _=new C(void 0,{size:h,flipY:(v=t==null?void 0:t.flipY)!=null?v:!1,generateMipmaps:t==null?void 0:t.generateMipmaps,magFilter:C.LinearFilter,minFilter:(g=t==null?void 0:t.minFilter)!=null?g:C.LinearFilter,wrapS:(p=t==null?void 0:t.wrapS)!=null?p:C.defaultOptions.wrapS,wrapT:(x=t==null?void 0:t.wrapT)!=null?x:C.defaultOptions.wrapT,premultiplyAlpha:(S=t==null?void 0:t.premultiplyAlpha)!=null?S:C.defaultOptions.premultiplyAlpha});return this.modules.renderer.prepareTexture(_),_.subImage(u,o,o),u.remove(),this.texturesMap.set(l,_),this.textureKeys.push(l),this.modules.renderer.addRerenderEvent(),this.textureKeys.length-1}loadImage(e){return q(this,null,function*(){return new Promise(t=>{const i=new Image;i.crossOrigin="Anonymous",i.src=e,i.onload=()=>t(i),i.onerror=()=>t(void 0)})})}}function k1(s,e){const t=e!==void 0?`_${e[0]},${e[1]}`:"";return`${s}${t}`}const Zh=!0,Wh=!1,jh=!1,Xh=[0];class U1{constructor(e){this.isLoading=!1,this.attempts=0,this.getKeyInfo=()=>q(this,null,function*(){return yield this.request}),this.isIdle=()=>!this.isLoading;const{tileKey:t,keyUrl:i}=e;if(t===n.tiles.tileKey||!n.keyServerPath)this.request=Promise.resolve({showCommPoi:!1,urbi:!1,hideCopyright:!0});else{const r=n.getUrlFromTemplate(i,{keyID:t});this.isLoading=!0;const o=()=>q(this,null,function*(){return Xh.length>=this.attempts?(this.attempts&&(yield new Promise(a=>{this.lastTimeout=window.setTimeout(a,Xh[this.attempts]*1e3)}),this.clearLastTimeout()),this.attempts++,fetch(r).then(a=>a.ok?a.json():o(),o)):(console.error("Could not load tile key info. A style layers with commercial POI will be added to applied styles."),Promise.resolve(void 0))});this.request=o().then(a=>{if(this.isLoading=!1,!a||!a.result||a.meta.code!==200)return{showCommPoi:Zh,hideCopyright:jh,urbi:Wh,error:!0};const{showCommPoi:l,hideCopyright:c,urbi:d}=a.result.service.properties.public;return{showCommPoi:n.isNullish(l)?Zh:!!l,hideCopyright:n.isNullish(c)?jh:!!c,urbi:n.isNullish(d)?Wh:!!d}})}}destroy(){this.clearLastTimeout()}clearLastTimeout(){this.lastTimeout!==void 0&&(clearTimeout(this.lastTimeout),this.lastTimeout=void 0)}}class M1{constructor(){this.sources=[],this.viewportSources=[]}addSource(e){this.sources.push(e),e.type==="geojson"&&e.subtype==="viewport-internal"&&e instanceof n.GeoJsonViewportSource&&this.viewportSources.push(e)}removeSource(e){this.sources=this.sources.filter(t=>t.getId()!==e),this.viewportSources=this.viewportSources.filter(t=>t.getId()!==e)}getSourceById(e){return this.sources.find(t=>t.getId()===e)}update(){this.viewportSources.forEach(e=>e.update())}}const $h={dem:0,mapMesh:1,gltf:2};class H1{constructor(e){this.isDemMode=e,this.tree=n.rbush(n.DEM_TREE_SIZE),this.tiles=new Map,this.surfaceTreesByTier=new Map,this.surfaceEntries=new Map,this.surfaceEntryKeysByOwnerKey=new Map,this.surfaceRevisionsByTier=new Map,this.gltfTierSurfaces=new Map,this.gltfTierKeysByLinkId=new Map,this.revision=0,this.demRevision=0}register(e){const t=cl(e.sourceId,e.key),i=this.tiles.get(t);i&&(this.tree.remove(i,(r,o)=>qh(o,t)),this.unregisterSurfaceEntriesByOwnerKey(t)),this.tiles.set(t,e),this.tree.insert(e),this.registerTileSurfaceEntries(e,t),((i==null?void 0:i.kind)==="dem"||e.kind==="dem")&&this.demRevision++,this.revision++}unregister(e,t){const i=cl(e,t),r=this.tiles.get(i);r&&(this.tree.remove(r,(o,a)=>qh(a,i)),this.tiles.delete(i),this.unregisterSurfaceEntriesByOwnerKey(i),r.kind==="dem"&&this.demRevision++,this.revision++)}registerGltfTierSurface(e){if(e.triangles.length===0)return;this.unregisterGltfTierSurface(e.key),this.gltfTierSurfaces.set(e.key,e);const t=this.createGltfSurfaceEntry(e);t&&this.registerSurfaceEntry(e.key,t);const i=this.gltfTierKeysByLinkId.get(e.linkId);i?i.push(e.key):this.gltfTierKeysByLinkId.set(e.linkId,[e.key]),this.revision++}unregisterGltfTierSurface(e){const t=this.gltfTierSurfaces.get(e);if(!t)return;this.unregisterSurfaceEntriesByOwnerKey(t.key),this.gltfTierSurfaces.delete(e);const i=this.gltfTierKeysByLinkId.get(t.linkId);if(i){const r=i.filter(o=>o!==e);r.length?this.gltfTierKeysByLinkId.set(t.linkId,r):this.gltfTierKeysByLinkId.delete(t.linkId)}this.revision++}unregisterGltfTierSurfacesByLinkId(e){const t=this.gltfTierKeysByLinkId.get(e);if(t)for(const i of t.slice())this.unregisterGltfTierSurface(i)}isGltfTierSurfacesByLinkIdRegistered(e){const t=this.gltfTierKeysByLinkId.get(e);return t!==void 0&&t.length>0}clear(){const e=Array.from(this.tiles.values()).some(t=>t.kind==="dem");this.tree.clear(),this.tiles.clear();for(const t of this.surfaceTreesByTier.keys())this.bumpSurfaceRevision(t);this.surfaceTreesByTier.clear(),this.surfaceEntries.clear(),this.surfaceEntryKeysByOwnerKey.clear(),this.gltfTierSurfaces.clear(),this.gltfTierKeysByLinkId.clear(),this.minElevation=void 0,e&&this.demRevision++,this.revision++}getTiles(e){const t=Array.from(this.tiles.values());return e===void 0?t:t.filter(i=>i.kind===e)}getTilesAtPoint(e){const t=n.normalizeMapPoint(e);return this.tree.search({minX:t[0],minY:t[1],maxX:t[0],maxY:t[1]})}getElevation(e){var t;return(t=this.querySurfaceAtTier(e,0,{includeAbsoluteZ:!0,includeSurfaceTangents:!1}))==null?void 0:t.absoluteZ}getElevationAtTier(e,t,i){var a,l;const r=(a=i==null?void 0:i.includeAbsoluteZ)!=null?a:!0,o=(l=i==null?void 0:i.includeSurfaceTangents)!=null?l:!1;return t===0&&!r&&!o?{relativeZ:0}:this.querySurfaceAtTier(e,t,{includeAbsoluteZ:r,includeSurfaceTangents:o,cache:i==null?void 0:i.cache,tryToGetAbsZFirst:i==null?void 0:i.tryToGetAbsZFirst})}getElevationTile(e,t){return this.pickTile(e,t)}getMinElevation(){return this.minElevation}updateMinElevation(e){const t=this.tree.search({minX:e.min[0],minY:e.min[1],maxX:e.max[0],maxY:e.max[1]});this.minElevation=t.reduce((i,r)=>r.kind!=="dem"||r.minZ===void 0?i:i===void 0?r.minZ:Math.min(i,r.minZ),void 0)}getRevision(){return this.revision}getSurfaceRevision(e){var t;return(t=this.surfaceRevisionsByTier.get(e))!=null?t:0}getDemRevision(){return this.demRevision}pickTile(e,t){return this.getTilesAtPoint(e).reduce((r,o)=>t!==void 0&&o.kind!==t?r:!r||r.cellSize!==void 0&&o.cellSize!==void 0&&o.cellSize<r.cellSize?o:r,void 0)}registerTileSurfaceEntries(e,t){if(e.tree){if(e.kind==="dem"){this.registerSurfaceEntry(t,this.createDemSurfaceEntry(e,t));return}e.surfaceTier!==void 0&&this.registerSurfaceEntry(t,this.createMapMeshSurfaceEntry(e,t,e.surfaceTier))}}createDemSurfaceEntry(e,t){return{key:`${t}:surface:dem`,ownerKey:t,tier:0,sourceKind:"dem",cellSize:e.cellSize,minX:e.minX,minY:e.minY,maxX:e.maxX,maxY:e.maxY,query:(i,r)=>{if(!r.includeAbsoluteZ&&!r.includeSurfaceTangents)return{relativeZ:0};const o=n.getElevationSampleFromTile(e,i,{tileCoords:e.tileCoords,vertexStride:e.vertexStride,heightOffset:e.heightOffset,bucketSink:e.bucketSink,includeSurfaceTangents:r.includeSurfaceTangents});if(!o)return;const a={relativeZ:0};return r.includeAbsoluteZ&&(a.absoluteZ=o.elevation),o.surfaceTangents&&(a.surfaceTangents=o.surfaceTangents),a}}}createMapMeshSurfaceEntry(e,t,i){return{key:`${t}:surface:${i}`,ownerKey:t,tier:i,sourceKind:"mapMesh",minX:e.minX,minY:e.minY,maxX:e.maxX,maxY:e.maxY,query:(r,o)=>{var c;const a=n.getElevationFromTileSplit(e,r,{tileCoords:e.tileCoords,vertexStride:e.vertexStride,heightOffset:e.heightOffset,bucketSink:e.bucketSink,getDemElevation:d=>this.getMapMeshDemElevation(d),mapMeshBaseZ:((c=this.isDemMode)==null?void 0:c.call(this))===!1?0:void 0,includeAbsoluteZ:o.includeAbsoluteZ,includeSurfaceTangents:o.includeSurfaceTangents,triangleCache:o.cache,tryToGetAbsZFirst:o.tryToGetAbsZFirst});if(!a)return;const l={relativeZ:a.relativeZ/n.MAP_POINTS_IN_METER};return a.absoluteZ!==void 0&&(l.absoluteZ=a.absoluteZ/n.MAP_POINTS_IN_METER),a.surfaceTangents&&(l.surfaceTangents=a.surfaceTangents),l}}}getMapMeshDemElevation(e){return this.getElevation(e)}createGltfSurfaceEntry(e){if(e.triangles.length===0)return;const t=n.rbush(n.DEM_TREE_SIZE).load(e.triangles),i=e.triangles.reduce((r,o)=>({minX:Math.min(r.minX,o.minX),minY:Math.min(r.minY,o.minY),maxX:Math.max(r.maxX,o.maxX),maxY:Math.max(r.maxY,o.maxY)}),{minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0});return V(I({key:`${e.key}:surface:gltf`,ownerKey:e.key,tier:e.tier,sourceKind:"gltf"},i),{query:(r,o)=>this.queryGltfSurface(e,t,r,o)})}queryGltfSurface(e,t,i,r){var d;const o=n.normalizeMapPoint(i),a=u=>{var f;const h=E0(e,u,o,m=>this.getElevation(m),{includeAbsoluteZ:r.includeAbsoluteZ,includeSurfaceTangents:r.includeSurfaceTangents,baseZ:((f=this.isDemMode)==null?void 0:f.call(this))===!1?0:void 0});if(!h)return;const _={relativeZ:h.relativeZ/n.MAP_POINTS_IN_METER};return h.absoluteZ!==void 0&&(_.absoluteZ=h.absoluteZ/n.MAP_POINTS_IN_METER),h.surfaceTangents&&(_.surfaceTangents=h.surfaceTangents),_},l=(d=r.cache)==null?void 0:d.triangle;if((l==null?void 0:l.key)===e.key){const u=a(l);if(u)return u;r.cache.triangle=void 0}const c=t.search({minX:o[0],minY:o[1],maxX:o[0],maxY:o[1]});for(const u of c){const h=a(u);if(h)return r.cache&&(r.cache.triangle=u),h}}querySurfaceAtTier(e,t,i){const r=this.getSurfaceRevision(t),o=i.includeAbsoluteZ||i.includeSurfaceTangents?this.getDemRevision():-1,a=V(I({},i),{surfaceRevision:r,demRevision:o}),l=i.cache;if((l==null?void 0:l.tier)===t&&l.surfaceKey!==void 0&&l.surfaceRevision===r&&l.demRevision===o){const h=this.surfaceEntries.get(l.surfaceKey);if((h==null?void 0:h.tier)===t){const _=h.query(e,a);if(_)return _;l.triangle=void 0}}const c=this.surfaceTreesByTier.get(t);if(!c){l&&this.clearSurfaceQueryCache(l);return}const d=n.normalizeMapPoint(e),u=c.search({minX:d[0],minY:d[1],maxX:d[0],maxY:d[1]});u.length>1&&u.sort(G1);for(const h of u){l&&l.surfaceKey!==h.key&&(l.triangle=void 0);const _=h.query(e,a);if(_)return l&&(l.tier=t,l.surfaceKey=h.key,l.surfaceRevision=r,l.demRevision=o),_}l&&this.clearSurfaceQueryCache(l)}registerSurfaceEntry(e,t){var o;const i=this.surfaceEntries.get(t.key);i&&((o=this.surfaceTreesByTier.get(i.tier))==null||o.remove(i,(a,l)=>a.key===l.key)),this.surfaceEntries.set(t.key,t),this.getSurfaceTree(t.tier).insert(t),this.bumpSurfaceRevision(t.tier);const r=this.surfaceEntryKeysByOwnerKey.get(e);r?r.includes(t.key)||r.push(t.key):this.surfaceEntryKeysByOwnerKey.set(e,[t.key])}unregisterSurfaceEntriesByOwnerKey(e){const t=this.surfaceEntryKeysByOwnerKey.get(e);t&&(t.forEach(i=>{var o;const r=this.surfaceEntries.get(i);r&&((o=this.surfaceTreesByTier.get(r.tier))==null||o.remove(r,(a,l)=>a.key===l.key),this.surfaceEntries.delete(i),this.bumpSurfaceRevision(r.tier))}),this.surfaceEntryKeysByOwnerKey.delete(e))}getSurfaceTree(e){let t=this.surfaceTreesByTier.get(e);return t||(t=n.rbush(n.DEM_TREE_SIZE),this.surfaceTreesByTier.set(e,t)),t}clearSurfaceQueryCache(e){e.tier=void 0,e.surfaceKey=void 0,e.surfaceRevision=void 0,e.demRevision=void 0,e.triangle=void 0}bumpSurfaceRevision(e){this.surfaceRevisionsByTier.set(e,this.getSurfaceRevision(e)+1)}}function G1(s,e){const t=$h[s.sourceKind]-$h[e.sourceKind];return t!==0?t:s.cellSize!==void 0&&e.cellSize!==void 0?s.cellSize-e.cellSize:0}function cl(s,e){return`${s}:${e}`}function qh(s,e){return cl(s.sourceId,s.key)===e}const V1={dead:!0,alive:!0,unused:!0,commercialDead:!1,commercialAlive:!1};class Z1{constructor(e,t){this.mapState=e,this.modules=t,this.options={},this.viewportDiffer=new n.Differ([{path:"center",type:"vec2"},{path:"zoom",type:"number"},{path:"size",type:"vec2"},{path:"rotation",type:"number"},{path:"pitch",type:"number"},{path:"padding",type:"padding"},{path:"demMode",type:"boolean"}]),this.sizeDiffer=new n.Differ([{path:"size",type:"vec2"}])}update(){this.isEnabled()&&(this.sizeDiffer.check(this.mapState)&&this.updateSize(),this.viewportDiffer.check(this.mapState)&&this.clear())}isEnabled(){return!!this.canvas}show(e=V1){this.options=e,Object.values(e).every(i=>i===!1)?this.hide():(this.createCanvas(),this.mapState.needLabeling=!0)}hide(){this.canvas&&(this.modules.layout.mapContainer.removeChild(this.canvas),this.ctx=void 0,this.canvas=void 0)}drawLabels(e){if(!this.canvas||!this.ctx)return;const t=this.ctx,i=this.options,r={[n.BBoxType.Dead]:"#ff0000",[n.BBoxType.Alive]:"#30763c",[n.BBoxType.Unused]:"#aaa",[n.BBoxType.CommercialAlive]:"#3a9f22",[n.BBoxType.CommercialDead]:"#ff0000"},o=new Int32Array(e),a={[n.BBoxType.Dead]:[],[n.BBoxType.Alive]:[],[n.BBoxType.Unused]:[],[n.BBoxType.CommercialAlive]:[],[n.BBoxType.CommercialDead]:[]};for(let d=0;d<o.length;d+=5){const u=o[d+4];a[u].push({x:o[d],y:o[d+1],width:o[d+2],height:o[d+3]})}this.clear();const l=window.devicePixelRatio,c=d=>{t.strokeStyle=r[d],a[d].forEach(u=>t.strokeRect(u.x*l+.5,u.y*l+.5,u.width*l,u.height*l))};t.setLineDash([]),i.unused&&c(n.BBoxType.Unused),i.dead&&c(n.BBoxType.Dead),i.alive&&c(n.BBoxType.Alive),t.setLineDash([6]),i.commercialDead&&c(n.BBoxType.CommercialDead),i.commercialAlive&&c(n.BBoxType.CommercialAlive)}clear(){if(this.canvas&&this.ctx){const{clientWidth:e,clientHeight:t}=this.canvas;this.ctx.clearRect(0,0,e*window.devicePixelRatio,t*window.devicePixelRatio)}}createCanvas(){this.canvas||(this.canvas=document.createElement("canvas"),this.canvas.style.position="absolute",this.canvas.style.left="0",this.canvas.style.top="0",this.canvas.style.pointerEvents="none",this.modules.layout.mapContainer.appendChild(this.canvas),this.ctx=this.canvas.getContext("2d")||void 0,this.updateSize())}updateSize(){if(!this.canvas)return;const{clientWidth:e,clientHeight:t}=this.modules.layout.rootContainer;this.canvas.width=e*window.devicePixelRatio,this.canvas.height=t*window.devicePixelRatio,this.canvas.style.width=e+"px",this.canvas.style.height=t+"px"}}const W1=n.create$1();class j1{constructor(e){this.globHaloStops=[-2.5,0,1.5,13],this.globeHaloExpFactor=-1,this.fogLimits=new Float32Array([3.7,4.5]),this.fogHorizonBlend=.12,this.fogHorizonLevel=-.07,this.squaredDistMaxFog=0,this.lastStyleId=NaN,this.starsCount=2e4,this.starsGenerationCtx={randomSeed:12345},this.starsUpdateNeeded=!0,this.modules=e;const t=this.modules.renderer.getShaderProgram("sky"),i=this.modules.renderer.createBuffer(new Float32Array([-1,-1,1,-1,1,1,-1,1]));this.vao=ov(i,t)}update(){this.updateFog();const e=this.modules.map.state;isNaN(e.handyStyleId)||this.lastStyleId!==e.handyStyleId&&(this.updateSky(),this.updateStars(),this.lastStyleId=e.handyStyleId)}setParameters(e){const t=this.modules.map.state;e.min!==void 0&&(this.fogLimits[0]=e.min),e.max!==void 0&&(this.fogLimits[1]=e.max),e.horizonBlend!==void 0&&(this.fogHorizonBlend=e.horizonBlend),e.horizonLevel!==void 0&&(this.fogHorizonLevel=e.horizonLevel);const i=this.modules.styleManager.getStyleLayer(t.handyStyleId,n.ENVIRONMENT_STYLE_LAYER_ID);if(!i)return;const r={layer:{},usage:n.DataKeyUsage.Uniform,globals:{},precomputes:[]};e.fogColor!==void 0&&(i.style.fogColor=n.isArrayOfNumbers(e.fogColor)?n.toStyleColor(e.fogColor):n.makeEnvironmentColor(e.fogColor,r)),e.skyColor!==void 0&&(i.style.skyColor=n.isArrayOfNumbers(e.skyColor)?n.toStyleColor(e.skyColor):n.makeEnvironmentColor(e.skyColor,r)),this.modules.renderer.addRerenderEvent()}renderSky(){if(!this.isSkyEnabled())return;this.modules.renderer.applyGpuState(qe);const e=this.modules.renderer.getShaderProgram("sky");this.modules.renderer.enableShaderProgram(e),this.modules.renderer.isUboSupported()||(Ql(e,this.modules.map.state,this.modules),W(e,this.modules.map.state,this.modules),X(e,this.modules.map.state,this.modules)),this.modules.renderer.bindVao(this.vao),this.modules.renderer.drawTrianglesFan(0,4)}renderStars(){if(!this.starsVao)return;this.modules.renderer.applyGpuState(qe);const e=this.modules.renderer.getShaderProgram("stars");this.modules.renderer.enableShaderProgram(e),this.modules.renderer.isUboSupported()||Jl(e,this.modules.map.state,this.modules),this.modules.renderer.bindVao(this.starsVao),this.modules.renderer.drawPoints(0,this.starsCount)}renderGlobeHaloBackground(){this.modules.renderer.applyGpuState(qe);const e=this.modules.renderer.getShaderProgram("globeHaloBackground");this.modules.renderer.enableShaderProgram(e),this.modules.renderer.isUboSupported()||lo(e,this.modules.map.state,this.modules),this.modules.renderer.bindVao(this.vao),this.modules.renderer.drawTrianglesFan(0,4)}renderGlobeHalo(){this.modules.renderer.applyGpuState(mv);const e=this.modules.renderer.getShaderProgram("globeHalo");this.modules.renderer.enableShaderProgram(e),this.modules.renderer.isUboSupported()||lo(e,this.modules.map.state,this.modules),this.modules.renderer.bindVao(this.vao),this.modules.renderer.drawTrianglesFan(0,4)}isFogEnabled(){var a,l;if(this.modules.map.getFeatureFlag("fogOff")||!((a=this.envStyleLayer)!=null&&a.style.fogColor))return!1;const{styleZoom:e,styleState:t,pitch:i}=this.modules.map.state,r=n.makeBinderContext(e,i,t,[]),o=n.resolveColor((l=this.envStyleLayer)==null?void 0:l.style.fogColor,r);return o&&o.value[3]!==0}isSkyEnabled(){var a,l;if(this.modules.map.getFeatureFlag("skyOff")||!((a=this.envStyleLayer)!=null&&a.style.skyColor))return!1;const{styleZoom:e,styleState:t,pitch:i}=this.modules.map.state,r=n.makeBinderContext(e,i,t,[]),o=n.resolveColor((l=this.envStyleLayer)==null?void 0:l.style.skyColor,r);return o&&o.value[3]!==0}isPointInFog(e){const t=this.modules.camera;return n.sqrDist$1(e,t.position)>this.squaredDistMaxFog}isAABBInFog(e){if(!this.modules.environmentManager.isFogEnabled())return!1;const t=this.modules.camera,i=n.projectToXyRect(t.position,e.min,e.max,W1);return this.isPointInFog(i)}updateSky(){const e=this.modules.styleManager.getStyleLayer(this.modules.map.state.handyStyleId,n.ENVIRONMENT_STYLE_LAYER_ID);this.envStyleLayer=e}updateStars(){if(!this.starsUpdateNeeded)return;this.starsUpdateNeeded=!1;const e=n.generatePointsOnSphere(this.starsGenerationCtx,this.starsCount),t=4,i=new Float32Array(t*e.length);for(let a=0;a<e.length;++a){const l=e[a],c=n.getRandomValue(this.starsGenerationCtx,0,1);i[t*a]=l[0],i[t*a+1]=l[1],i[t*a+2]=l[2],i[t*a+3]=c}const r=this.modules.renderer.createBuffer(i),o=this.modules.renderer.getShaderProgram("stars");this.starsVao=av(r,o)}updateFog(){const e=this.modules.camera;this.squaredDistMaxFog=Re(e.fogDistance*this.fogLimits[1],2)}}class X1{constructor(e,t){this.mapState=e,this.mapModules=t,this.state={}}add(e,t=0,i=1,r=n.buildingAnimation.easing,o=n.buildingAnimation.duration){this.state[e]||(this.state[e]={tickerConfig:{start:t,end:i,duration:o,easing:r},tickerKey:"",readiness:t===i?1:0,ended:!1})}has(e){return!!this.state[e]}remove(e){this.state[e]&&delete this.state[e];const t=this.buildTickerKey(e);n.exist(t,this.mapState)&&n.stop(t,this.mapState)}getReadiness(e){var t;return(t=this.state[e])==null?void 0:t.readiness}isAnimating(e){if(!e){for(const t in this.state)if(n.get(this.state[t].tickerKey,this.mapState)!==void 0)return!0;return!1}return this.state[e]?n.get(this.state[e].tickerKey,this.mapState)!==void 0:!1}update(){const e=[];for(const t in this.state){const i=this.state[t];if(this.mapModules.tileManager.viewportTilesReady()){const{start:r,end:o,duration:a,easing:l}=i.tickerConfig;if(i.tickerKey)n.update(i.tickerKey,{step:(c,d)=>{i.readiness=d}},this.mapState);else{const c=this.buildTickerKey(t);i.tickerKey=c,n.start(c,{easing:l},this.mapState,r,o,a,1)}i.readiness===1&&!i.ended&&(i.ended=!0,e.push(t))}}return e}buildTickerKey(e){return`gltf-${e}`}}const Rs=.5,$1=4e3,Yh="-1";class q1{constructor(){this.preservedKeys=new Set,this.shownBuildings=new Map,this.shownAnchors=new Map,this.holdStartTime=new Map}onModelShown(e,t,i){if(i<=Rs)return;const r=Fs(t);r&&this.shownBuildings.set(r,{key:e,readiness:i}),t.anchor&&this.shownAnchors.set(e,{x:t.anchor[0],y:t.anchor[1],readiness:i,minzoom:t.layer.minzoom,maxzoom:t.layer.maxzoom})}resetShownMemory(){this.shownBuildings.clear(),this.shownAnchors.clear()}preserveReadiness(e){this.preservedKeys.add(e)}dropPreserved(e){this.preservedKeys.delete(e)}shouldSuppressGrowAnimation(e,t){if(this.preservedKeys.delete(e))return!0;const i=Fs(t);return Q1(i,e,this.shownBuildings.get(i))?!0:this.isShownByAnchor(e,t)}shouldHold(e,t,i,r,o,a){var d;const l=Fs(t);if(!l)return!1;for(const[u,h]of i)if(u!==e&&!(Fs(h)!==l&&!Y1(t.anchor,h.anchor))&&!(o<h.layer.minzoom||o>=h.layer.maxzoom)&&((d=r(u))!=null?d:0)>=Rs)return!1;const c=this.holdStartTime.get(e);return c===void 0?(this.holdStartTime.set(e,a),!0):a-c<=$1}isHolding(e){return this.holdStartTime.has(e)}stopHold(e){this.holdStartTime.delete(e)}onTileGone(e){e.forEach(t=>{this.preservedKeys.delete(t),this.holdStartTime.delete(t),this.shownAnchors.delete(t)}),this.shownBuildings.forEach((t,i)=>{e.has(t.key)&&this.shownBuildings.delete(i)})}clear(){this.preservedKeys.clear(),this.shownBuildings.clear(),this.shownAnchors.clear(),this.holdStartTime.clear()}isShownByAnchor(e,t){const i=t.anchor;if(!i)return!1;for(const[r,o]of this.shownAnchors)if(!(r===e||o.minzoom===t.layer.minzoom&&o.maxzoom===t.layer.maxzoom||o.readiness<=Rs)&&o.x===i[0]&&o.y===i[1])return!0;return!1}}function Fs(s){const{buildingId:e}=s;return e&&e!==Yh?e:""}function Y1(s,e){return!s||!e?!1:s[0]===e[0]&&s[1]===e[1]}function Q1(s,e,t){return!!s&&s!==Yh&&t!==void 0&&t.key!==e&&t.readiness>Rs}const J1=!0,dl="#ffffffff",K1=0,eE=0,tE=1,ul=15,iE=n.tileZoomToSize(ul)/n.MAP_POINTS_IN_METER,Ds=n.maxTilePoint/2,nE=["coordinates","rotation","scale","offset"];let hl=class Al extends ht{constructor(e,t){var y,E,P,A,F,L,D,B,Q,Z;super(e,{interactive:(y=t.interactive)!=null?y:!1}),this.map=e,this.hasExplicitZ=!1,this.needRerender=()=>this.isVisible()&&n.isTileVisible(n.mapPointTo32ZoomTileCoords(this.position.normalizedValue),this.mapState.tilesBounds,this.modules,n.MODELS_TILES_VIEWPORT_PADDING),this.hovered=!1,this.selected=!1,this.status=t.hideOnInit?"hidden":"visible",this.interactiveOcclusion=(E=t.interactiveOcclusion)!=null?E:J1,this.disableAnimation=t.disableAnimation,this.linkedIds=t.linkedIds,this.planId=t.planId,this.tickerNames=new Map,this.generatedAsEcef=ye(this.mapState),this.tier=(P=t.tier)!=null?P:0,this.hasExplicitZ=t.coordinates.length===3;const i=n.Mercator.fromGeo(t.coordinates);this.position={userValue:i,normalizedValue:n.normalizeMapPoint(i)},this.tierHeightResolver=new Tr(this.modules,this.mapState,()=>this.position.normalizedValue,()=>this.tier,()=>this.hasExplicitZ,{alwaysRequireAbsoluteZ:!0,trackPositionChanges:!0});const{dynamicStyle:r,collector:o,tileManager:a,layers:l,assetManager:c}=this.modules,{ignoreGlobalLighting:d,colorTextureUvIndex:u,nearCameraFade:h,showRatio:_,playAnimation:f}=t,m=e_((A=t.rotation)!=null?A:K1),v=(F=t.scale)!=null?F:tE,g=t_((L=t.offset)!=null?L:eE,t.coordinates[1]);if(this.appliedTransformations={scale:v,rotation:m,offset:g},this.layer=n.makeHandyStyleLayer({type:"model",id:`dynamic-gltf-model-${this.uniqId}`,style:{modelSrc:["get","model_src"],rotation:Array.isArray(m)?["literal",m]:m,scale:Array.isArray(v)?["literal",v]:v,offset:Array.isArray(g)?["literal",g]:g,linkedIds:["get","linkedIds"],ignoreGlobalLighting:d,colorTextureUvIndex:u,nearCameraFade:h,showRatio:_,playAnimation:f,color:["match",["object-attr","hovered"],[!0],((D=t.hover)==null?void 0:D.color)||dl,["match",["object-attr","selected"],[!0],((B=t.select)==null?void 0:B.color)||dl,t.color||dl]]},minzoom:t.minZoom,maxzoom:t.maxZoom,interactive:this.interactive,interactiveOcclusion:this.interactiveOcclusion},r.getStyle().globals),!this.layer)return;(Q=t.hover)!=null&&Q.color&&(this.on("mouseover",this.switchToHoveredColor),this.on("mouseout",this.switchToNormalColor)),r.addLayer(this.layer,t.zIndex);const p=n.getTileCoordsByCenterAndZoom(this.position.normalizedValue,ul),x=n.optionsToTileAttrs({model_src:t.modelSrc,linkedIds:t.linkedIds,db_plan_id:t.planId}),S=n.makeGeneratorContext(this.mapState.styleState,n.emptySourceAttrs,n.fixedTileProps,x,n.emptyFeatureAttrs,!0,t.interactive?"0":"");n.runPrecomputes(this.layer,S),n.generateSafely({collector:o,generator:n.GltfModelGenerator.generateInstances,args:[r.getStyle(),this.layer,S,{x:[Ds],y:[Ds],z:[(Z=this.position.userValue[2])!=null?Z:0]},n.createTileInfo(p),NaN]});const b=o.getAccumulatedData(),T=new n.TileObject("dynamicObject",b.data,this.modules,this.mapState,p,this);T.ecefDataState=n.ecefDataStateFromBool(ye(this.mapState)),this.tierHeightResolver.reset(),this.tierHeightResolver.resolve(),c.fillDataModelUrlMap(b.dataModelsUrls),this.modelId=b.dataModelsUrls[t.modelSrc],this.modelId!==void 0&&(c.loadModel(t.modelSrc,this.modelId,n.DYNAMIC_STYLE_ID,!0,this.layer,!1,()=>{this.status==="visible"&&(a.addObject(T),this.modules.renderer.addRerenderEvent(),this.linkedIds&&this.map.hideBuildingsById(this.linkedIds),this.updateIdentifier()),setTimeout(()=>this.emit("modelloaded"),0)}),this.tileObjects.push(T),t.interactive&&this.identifyIds.push(b.identifyIds),l.addLayer(this),o.reset(),this.status==="visible"&&this.hideLinkedObjects())}update(){super.update();const e=ye(this.mapState);if(e!==this.generatedAsEcef&&(this.applyTransformations(),this.generatedAsEcef=e),this.refreshTierData(),(this.generatedAsEcef||!this.visibleOnGlobe)&&this.updateGlobeVisibility(n.Mercator.toGeo(this.position.userValue)),!this.tickerNames.size)return;const t=[],i={};this.tickerNames.forEach((r,o)=>{n.update(r,{step:(a,l)=>{i[o]=l},complete:()=>{t.push(o)}},this.mapState)}),(i.coordinates!==void 0||i.rotation!==void 0||i.scale!==void 0||i.offset!==void 0)&&this.applyTransformations(i.coordinates,i.rotation,i.scale,i.offset),t.forEach(r=>{this.tickerNames.delete(r)}),this.interactive&&this.needRerender()&&this.modules.identifier.queryFillCache()}setState({hovered:e,selected:t}){e!==void 0&&e!==this.hovered&&(this.hovered=e,this.modules.renderer.addRerenderEvent()),t!==void 0&&t!==this.selected&&(this.selected=t,this.modules.renderer.addRerenderEvent())}isAnimationDisabled(){return this.disableAnimation}getLinkedIds(){return this.linkedIds}isVisible(){return this.status==="visible"}hide(){this.status==="visible"&&(this.status="hidden",this.tileObjects.forEach(e=>{this.modules.tileManager.removeObject(e)}),this.showHiddenBuildings(),this.showLinkedObjects(),this.mapState.shouldIsIdleWaitForUpdates=!0,this.modules.renderer.addRerenderEvent(),this.updateIdentifier())}isOutOfMainReplica(){return!1}show(){this.status==="hidden"&&(this.status="visible",this.tileObjects.forEach(e=>{this.modules.tileManager.addObject(e)}),this.linkedIds&&this.map.hideBuildingsById(this.linkedIds),this.hideLinkedObjects(),this.mapState.shouldIsIdleWaitForUpdates=!0,this.modules.renderer.addRerenderEvent(),this.updateIdentifier())}destroy(e){this.status!=="destroyed"&&(this.stopTransformation(),this.status="destroyed",this.modelId!==void 0&&!this.modules.layers.getDynamicObjectLayers().filter(i=>i instanceof Al&&i!==this).some(i=>i.modelId===this.modelId)&&!e&&this.modules.assetManager.removeModel(String(this.modelId)),this.updateIdentifier(),this.layer&&this.modules.dynamicStyle.removeLayer(this.layer.innerId),this.showHiddenBuildings(),this.off("mouseover",this.switchToHoveredColor),this.off("mouseout",this.switchToNormalColor),this.showLinkedObjects(),super.destroy())}transform(e){var r,o;if(this.status==="destroyed"||!this.layer)return;this.stopTransformation();const t={};e.forEach(a=>{const l=sE(a);if(!l)return;const{duration:c=0,easing:d="linear"}=a;t[l]={value:a[l],duration:c,easing:d}});const i={};for(const a in t){if(!rE(a)||t[a]===void 0)continue;let l;if(a==="coordinates"){const h=t[a].value;this.hasExplicitZ=h.length===3,this.tierHeightResolver.reset(!0),l=n.Mercator.fromGeo(h)}else a==="offset"?l=t_(t[a].value,(o=(r=t.coordinates)==null?void 0:r.value[1])!=null?o:n.Mercator.toGeo(this.position.userValue)[1]):l=t[a].value;if(!t[a].duration){i[a]=l;continue}const c=`dynamicGltfModel-${a}-${this.uniqId}`;let d,u;if(a==="coordinates")d=this.position.userValue,u=l;else{const h=[0,0,0];n.getTriple(this.appliedTransformations[a],h),d=h;const _=[0,0,0];n.getTriple(l,_),u=_}n.start(c,{easing:t[a].easing,renderAfterUpdate:this.needRerender},this.mapState,d,u,t[a].duration,1,{layerId:this.layer.innerId,styleId:n.DYNAMIC_STYLE_ID}),this.tickerNames.set(a,c)}(i.coordinates!==void 0||i.rotation!==void 0||i.scale!==void 0||i.offset!==void 0)&&(this.applyTransformations(i.coordinates,i.rotation,i.scale,i.offset),this.modules.renderer.addRerenderEvent(),this.updateIdentifier())}stopTransformation(){this.tickerNames.forEach(e=>{n.stop(e,this.mapState)}),this.tickerNames.clear()}getCoordinates(){return n.Mercator.toGeo(this.position.userValue)}getScale(){const e=[0,0,0];return n.getTriple(this.appliedTransformations.scale,e),e}getRotation(){const e=[0,0,0];return n.getTriple(this.appliedTransformations.rotation,e),e}getOffset(){const e=[0,0,0];return n.getTriple(this.appliedTransformations.offset,e),e}getWorldTransform(){return{position:this.position.userValue,rotation:this.getRotation()}}getTier(){return this.tier}setTier(e){this.tier!==e&&(this.tier=e,this.tierHeightResolver.reset(),this.refreshTierData(),this.modules.renderer.addRerenderEvent())}getResolvedHeight(){const e=this.tierHeightResolver.getResolvedHeight();return V(I({},e),{hasExplicitZ:this.hasExplicitZ})}refreshTierData(){if(!this.tierHeightResolver.shouldUseTierHeight()){this.tierHeightResolver.reset()&&this.modules.renderer.addRerenderEvent();return}this.tierHeightResolver.needsResolve()&&this.tierHeightResolver.resolve()&&this.modules.renderer.addRerenderEvent()}applyTransformations(e,t,i,r){var c;const o=this.tileObjects[0];if(!o)return;const a=o.buffers[0];if(!a)return;if(e&&(this.position={userValue:e,normalizedValue:n.normalizeMapPoint(e)},o.setTileCoords(n.getTileCoordsByCenterAndZoom(this.position.normalizedValue,ul),this.mapState)),t!==void 0||i!==void 0){const d=e_(t!=null?t:this.appliedTransformations.rotation),u=i!=null?i:this.appliedTransformations.scale;this.appliedTransformations.rotation=d,this.appliedTransformations.scale=u}if(r!==void 0){const d=r!=null?r:this.appliedTransformations.offset;this.appliedTransformations.offset=d}n.getTriple(this.appliedTransformations.offset,Kh),n.getTriple(this.appliedTransformations.scale,Qh),n.getTriple(this.appliedTransformations.rotation,Jh);const l=ye(this.mapState);n.GltfModelGenerator.patchBuffer(a,0,n.createTileInfo(o.coords),[Ds,Ds,(c=this.position.userValue[2])!=null?c:0],Kh,Qh,Jh,l),o.ecefDataState=n.ecefDataStateFromBool(l)}switchToHoveredColor(){this.hovered=!0,this.modules.renderer.addRerenderEvent()}switchToNormalColor(){this.hovered=!1,this.modules.renderer.addRerenderEvent()}updateIdentifier(){this.interactive&&this.modules.identifier.resetCache()}showLinkedObjects(){const e=this.planId?n.FLOOR_ID_SCOPE:n.DYNAMIC_MODEL_ID_SCOPE;this.linkedIds&&this.modules.identifier.getIdScope(e).show(this.linkedIds)}hideLinkedObjects(){const e=this.planId?n.FLOOR_ID_SCOPE:n.DYNAMIC_MODEL_ID_SCOPE;this.linkedIds&&this.modules.identifier.getIdScope(e).hide(this.linkedIds)}showHiddenBuildings(){if(!this.linkedIds)return;const e=this.modules.layers.getDynamicObjectLayers().filter(t=>t instanceof Al&&t!==this&&t.isVisible());this.linkedIds.forEach(t=>{e.every(r=>{var o;return!((o=r.getLinkedIds())!=null&&o.includes(t))})&&this.map.showHiddenBuildingsById([t])})}};const Qh=[0,0,0],Jh=[0,0,0],Kh=[0,0,0];function e_(s){return Array.isArray(s)?s.map(e=>e%360):s%360}function t_(s,e){const t=iE/n.Mercator.scaleFactor(e),i=["x","y"].filter((r,o)=>{const a=Array.isArray(s)?s[o]:s;return a<-t||a>t});return i.length&&console.warn(`
            The offset is too big along ${i.map(r=>`${r}-axis`).join(" and ")} at the current latitude.
            Please, use more accurate coordinates to place the model.
        `),Array.isArray(s)?[s[0]%t,s[1]%t,s[2]]:[s%t,s%t,s]}function rE(s){return nE.includes(s)}function sE(s){if("coordinates"in s)return"coordinates";if("rotation"in s)return"rotation";if("scale"in s)return"scale";if("offset"in s)return"offset"}const oE=[0,0,0],aE=[0,0,0],lE=[0,0,0],cE="modelshow",dE="modelhide",zs=0,i_=.1;class uE{constructor(e,t){this.sceneObjects=new Map,this.handoffTracker=new q1,this.sceneObjectsVisibilityMap=new Map,this.viewportDiffer=new n.Differ([{path:"center",type:"vec3"},{path:"zoom",type:"number"},{path:"size",type:"vec2"},{path:"rotation",type:"number"},{path:"pitch",type:"number"},{path:"padding",type:"padding"},{path:"demMode",type:"boolean"},{path:"elevation",type:"number"},{path:"minElevation",type:"number"}]),this.mapState=e,this.mapModules=t,this.modelsAnimator=new X1(e,t),this.modelInfo={},this.buildingIds=new Set,this.objectIdToLayerModelKey={},this.linkedIdToObjectId={},this.layerModelKeyBySourceTile=new Map,this.sceneObjectIdsByModelKeys=new Map,this.disabled=!1}addLayerModelToSourceTileMap(e,t){const i=e,r=_l(t.attributes.styleId,t.attributes.sourceId,t.tile.coords),o=this.layerModelKeyBySourceTile.get(r);o?o.add(i):this.layerModelKeyBySourceTile.set(r,new Set([i]))}clearSourceTileMapByTiles(e,t){t.map(i=>_l(this.mapState.handyStyleId,e,i.coords)).forEach(i=>this.deleteSourceTileKey(i))}clearSourceTileMapBySource(e){Array.from(this.layerModelKeyBySourceTile).map(i=>i[0]).filter(i=>i.split("_")[1]===String(e)).forEach(i=>this.deleteSourceTileKey(i))}getCurrentLayerModelId(e,t){var r;const i=Bs(e);return(r=this.modelInfo[i])==null?void 0:r.modelIds[t.id]}getModelOpacity(e){var i;if(e===void 0)return zs;const t=Bs(e.attributes);return t&&(i=this.modelsAnimator.getReadiness(t))!=null?i:zs}getModelHeightFactor(e){var i;if(!e)return 1;const t=Bs(e.attributes);return(i=this.modelsAnimator.getReadiness(t))!=null?i:1}isAnimating(e){if(!e)return this.modelsAnimator.isAnimating();const t=this.linkedIdToLayerModelKey(e);return t?this.modelsAnimator.isAnimating(t):!1}objectIdToKey(e){return this.objectIdToLayerModelKey[e]}update(){this.syncStateWithSceneObjects(),this.syncModelKeysWithSceneObjectIds(),this.modelsAnimator.update().length&&this.addNewSceneObjectsToVisibilityMap(),this.viewportDiffer.check(this.mapState)&&this.checkSceneObjectsVisibilityMap(),this.updateObjectsVisibility(),this.refreshShownBuildings()}addSceneObject(e){const t=Bs(e.attributes);let i=this.modelInfo[t];i?this.objectIdToLayerModelKey[e.id]||this.indexateObject(t,e,i):i=this.addLayerModel(e,t),i&&(i.modelIds[e.tile.id]=e.renderingProperties.modelId,this.sceneObjects.set(e.id,V(I({},e),{key:t})),this.addLayerModelToSourceTileMap(t,e))}removeSceneObject(e){this.removeSceneObjectState(e)}allObjectsHaveCurrentModelId(e,t,i){var a;const r=_l(i,e,t),o=this.layerModelKeyBySourceTile.get(r);if(!o)return!0;for(const l of o){const c=(a=this.modelInfo[l])==null?void 0:a.modelIds;if(!c)return!1;for(const d in c)if(c[d]===void 0)return!1}return!0}finishStyleUpdating(){Array.from(this.layerModelKeyBySourceTile).map(t=>t[0]).filter(t=>t.split("_")[0]!==String(this.mapState.handyStyleId)).forEach(t=>this.layerModelKeyBySourceTile.delete(t)),this.handoffTracker.clear()}updateModelId(e,t,i,r,o){var E,P,A,F;const{assetManager:a,sourceStorage:l,styleManager:c,camera:d,defaultSource:u}=this.mapModules,h=this.mapState;e.modelId=void 0;const{styleId:_,layerId:f,sourceId:m,sourceName:v,modelIndices:g,modelStepValues:p,modelStepSource:x}=t;if(!g.length)return;let S;switch(x){case n.ModelStepSource.None:S=0;break;case n.ModelStepSource.Zoom:S=n_(p,h.styleZoom);break;case n.ModelStepSource.Distance:S=hE(r,i,d.position,p,o);break;default:return}if(S===-1)return;const b=g[S];if(b===void 0)return;const T=a.getModel(b,_);if(T)switch(T.status){case gt.Loaded:e.modelId=b;const L=(P=(E=T.scenes.find((D,B)=>typeof t.scene=="number"&&!Number.isNaN(t.scene)&&B===t.scene||typeof t.scene=="string"&&D.name===t.scene))!=null?E:T.scenes.find((D,B)=>B===T.defaultScene))!=null?P:T.scenes.find((D,B)=>B===0);e.sceneId=L==null?void 0:L.id,T.usedEmptyScene=((F=(A=T.scenes.find(D=>D.id===e.sceneId))==null?void 0:A.objects.length)!=null?F:0)===0;return;case gt.Failed:e.modelId=NaN;return}else{const L=c.getStyleLayer(_,f),D=a.getDataModelUrlById(b);if(L&&!this.disabled){if(D===void 0)a.loadModelByIndex(b,_,L);else if(D.length){const B=m===u.getId()&&v===Ss;a.loadModel(D,b,_,!1,L,B)}}}if(g.length===1)return;const y=l.getSourceById(m);y&&(x===n.ModelStepSource.Zoom?e.modelId=this.getModelIdByZoom(y,t,r,S):x===n.ModelStepSource.Distance&&(e.modelId=this.getModelIdByDistance(t,r)))}getTieredModelsKey(e){const t=new Set;if(this.mapModules.assetManager.getTieredModelKeys().forEach(r=>{var a;const o=this.sceneObjectIdsByModelKeys.get(r);if(o)for(const l of o){const c=this.sceneObjects.get(l);if(!c||!c.bboxWorld)continue;const d=(a=c.meta)==null?void 0:a.linkId;if(!(d===void 0||!this.mapModules.elevationIndex.isGltfTierSurfacesByLinkIdRegistered(d))&&n.intersects(e,c.bboxWorld)){t.add(r);return}}}),t.size!==0)return Array.from(t).sort().join("|")}getModelIdByDistance(e,t){return this.getCurrentModelId(e,t)}getModelIdByZoom(e,t,i,r){const{styleId:o,modelIndices:a}=t,l=e.getZoomDirection();if(l===n.ZoomDirection.Stationary)return this.getCurrentModelId(t,i);const c=a.slice(0,r).reverse(),d=a.slice(r+1),u=l===n.ZoomDirection.ZoomingIn?c.concat(d):d.concat(c);for(let h=0;h<u.length;h++){const _=this.mapModules.assetManager.getModel(u[h],o);if(_&&_.status===gt.Loaded)return u[h];if((_==null?void 0:_.status)===gt.Failed)return NaN}}getCurrentModelId(e,t){const i=this.getCurrentLayerModelId(e,t);if(!i)return;const r=this.mapModules.assetManager.getModel(i,e.styleId);if(r&&r.status===gt.Loaded)return i;if((r==null?void 0:r.status)===gt.Failed)return NaN}removeSceneObjectState(e){var r,o,a;const t=this.sceneObjects.get(e),i=(r=t==null?void 0:t.meta)==null?void 0:r.linkId;typeof i=="number"&&this.mapModules.elevationIndex.unregisterGltfTierSurfacesByLinkId(i),(a=(o=t==null?void 0:t.meta)==null?void 0:o.linkedIds)==null||a.forEach(l=>{this.linkedIdToObjectId[l]===e&&delete this.linkedIdToObjectId[l]}),this.sceneObjects.delete(e),delete this.objectIdToLayerModelKey[e]}syncStateWithSceneObjects(){if(this.disabled=this.mapModules.map.getFeatureFlag("modelsOff"),this.disabled){this.destroy();return}const e=new Set,t=new Set,i=Array.from(this.sceneObjects.values());for(let l=0;l<i.length;l++)this.processSceneObject(i[l],e,t);t.forEach(l=>this.removeSceneObjectState(l));const r=this.mapState.styleZoom,o=this.mapModules.tileManager.viewportTilesReady(),a=new Set;for(const l of this.mapModules.tileManager.getTileObjects())a.add(l.id);for(const l of Object.keys(this.modelInfo)){const c=this.modelInfo[l];if(r<c.layer.minzoom||r>=c.layer.maxzoom){if(e.has(l)&&this.hasDisplayedOwner(c,a)&&this.handoffTracker.shouldHold(l,c,Object.entries(this.modelInfo),u=>this.modelsAnimator.getReadiness(u),r,this.mapState.time)){this.setHoldVisible(c,!0);continue}this.handoffTracker.dropPreserved(l),this.removeLayerModel(l,c)}else e.has(l)?this.handoffTracker.isHolding(l)&&(this.setHoldVisible(c,!1),this.handoffTracker.stopHold(l)):(o||c.linkedIds.length>0)&&this.removeLayerModel(l,c,!0)}}syncModelKeysWithSceneObjectIds(){this.sceneObjectIdsByModelKeys.clear(),this.sceneObjects.forEach(e=>{var o;const{modelId:t}=e.renderingProperties;if(t===void 0)return;const i=this.mapModules.assetManager.getModelUniqueKey(t,e.attributes.styleId),r=(o=this.sceneObjectIdsByModelKeys.get(i))!=null?o:new Set;r.add(e.id),this.sceneObjectIdsByModelKeys.set(i,r)})}processSceneObject(e,t,i){if(e.tile.destroyed){i.add(e.id);return}const r=e.key,o=this.modelInfo[r],a=this.mapState.disableModelsGrowthAnimation||e.tile.dynamicObject instanceof hl&&e.tile.dynamicObject.isAnimationDisabled();o&&!this.modelsAnimator.has(r)&&(this.mapModules.defaultSource.createModelsSource(),this.startAnimation(r,o,a)),o?this.objectIdToLayerModelKey[e.id]||this.indexateObject(r,e,o):this.addLayerModel(e,r,!0),t.add(r)}addLayerModel(e,t,i=!1){var a,l,c;const r=this.mapModules.styleManager.getStyleLayer(e.attributes.styleId,e.attributes.layerId);if(!r)return;if(i){const d=this.mapState.styleZoom;if(d<r.minzoom||d>=r.maxzoom)return}const o={layer:r,ids:e.tile.ids,linkedIds:[],ownerIds:new Set,modelIds:{},buildingId:((a=e.meta)==null?void 0:a.buildingId)||"",anchor:(l=e.meta)==null?void 0:l.anchor};return(c=e.meta)!=null&&c.planId&&(o.planId=e.meta.planId),this.indexateObject(t,e,o),this.modelInfo[t]=o,o}startAnimation(e,t,i){var a;if(this.handoffTracker.shouldSuppressGrowAnimation(e,t)||i){this.modelsAnimator.add(e,1,1);return}const r=(a=t.layer.minzoom)!=null?a:NaN;t.linkedIds.length>0&&this.mapModules.buildingHeightAnimator.getBuildingHeight(r)>.5?this.modelsAnimator.add(e,.5,1):this.modelsAnimator.add(e)}maybeEmitModelEvent(e,t,i){const r=!t.onKeyRemove&&!!i&&n.tetragonIntersectsBounds(i,{min:e.mapPoint,max:e.mapPoint}),o=e.visible;r!==o&&(e.visible=r,this.emitEvent(r&&!o?cE:dE,e))}addNewSceneObjectsToVisibilityMap(){var i,r,o,a;const e=this.mapModules.camera.getViewportVertices(i_),t=Array.from(this.sceneObjects.values());for(let l=0;l<t.length;l++){const c=t[l];if((i=c.attributes)!=null&&i.emitShowHideEvents&&((r=c.meta)!=null&&r.buildingId)&&c.attributes.lngLat){const d=c.key,u={visible:!1,mapPoint:n.Mercator.fromGeo(c.attributes.lngLat),buildingId:((o=c.meta)==null?void 0:o.buildingId)||"",sublayer:((a=c.meta)==null?void 0:a.sublayer)||"",key:d};let h=this.sceneObjectsVisibilityMap.get(d);h||(h=new Map,this.sceneObjectsVisibilityMap.set(d,h)),h.get(c.meta.buildingId)||(h.set(c.meta.buildingId,u),this.maybeEmitModelEvent(u,{onKeyShow:!0},e))}}}checkSceneObjectsVisibilityMap(){const e=this.mapModules.camera.getViewportVertices(i_);this.sceneObjectsVisibilityMap.forEach(t=>t.forEach(i=>this.maybeEmitModelEvent(i,{},e)))}indexateObject(e,t,i){var o,a,l,c,d;this.objectIdToLayerModelKey[t.id]=e,i.ownerIds.add(t.id),i.buildingId=((o=t.meta)==null?void 0:o.buildingId)||"",i.anchor=(l=(a=t.meta)==null?void 0:a.anchor)!=null?l:i.anchor,i.buildingId&&this.buildingIds.add(i.buildingId);const r=(d=(c=t.meta)==null?void 0:c.linkedIds)!=null?d:[];if(i.linkedIds.push(...r),t.tile.purpose!=="c3d")for(const u of r)this.linkedIdToObjectId[u]=t.id}refreshShownBuildings(){var e;if(this.mapState.styleZoom<n.loadModelsInfoStyleZoom){this.handoffTracker.resetShownMemory();return}for(const t in this.modelInfo){const i=this.modelInfo[t],r=(e=this.modelsAnimator.getReadiness(t))!=null?e:0;this.handoffTracker.onModelShown(t,i,r)}}hasDisplayedOwner(e,t){for(const i of e.ownerIds){const r=this.sceneObjects.get(i);if(r&&t.has(r.tile.id))return!0}return!1}setHoldVisible(e,t){for(const i of e.ownerIds){const r=this.sceneObjects.get(i);r&&(r.renderingProperties.holdVisible=t)}}deleteSourceTileKey(e){const t=this.layerModelKeyBySourceTile.get(e);t&&this.handoffTracker.onTileGone(t),this.layerModelKeyBySourceTile.delete(e)}removeLayerModel(e,t,i=!1){var o;if(this.handoffTracker.stopHold(e),this.setHoldVisible(t,!1),i){const a=this.modelsAnimator.getReadiness(e);a!==void 0&&a>0&&this.handoffTracker.preserveReadiness(e)}(o=t.ids)==null||o.show(t.linkedIds);for(const a of t.ownerIds)delete this.objectIdToLayerModelKey[a];t.buildingId&&this.buildingIds.delete(t.buildingId),this.modelsAnimator.remove(e);const r=this.sceneObjectsVisibilityMap.get(e);r&&(r.forEach(a=>this.maybeEmitModelEvent(a,{onKeyRemove:!0})),this.sceneObjectsVisibilityMap.delete(e)),delete this.modelInfo[e]}linkedIdToLayerModelKey(e){const t=this.linkedIdToObjectId[e];if(!t)return null;const i=this.objectIdToLayerModelKey[t];return i||null}emitEvent(e,t){const{buildingId:i,sublayer:r}=t;if(!r){console.warn(`No sublayer for model ${t.key}`);return}if(!i){console.warn(`No buildingId for model ${t.key}`);return}const o=n.isCommercialModel(r);this.mapModules.map.emit(e,{sublayer:r,id:i,isCommercial:o})}updateObjectsVisibility(){var i;const e=this.mapModules.identifier.getIdScope(n.DYNAMIC_MODEL_ID_SCOPE),t=this.mapModules.identifier.getIdScope(n.DEFAULT_ID_SCOPE);e.getHidden().forEach(r=>{t.hide([r],n.HideLevel.All)});for(const r in this.modelInfo){const o=this.modelInfo[r],a=o.ids;if(!a)continue;const l=(i=this.modelsAnimator.getReadiness(r))!=null?i:zs;for(const c of o.linkedIds){if(a.isHidden(c))continue;const d=o.planId!==void 0?n.HideLevel.FloorPolygons:n.HideLevel.PolygonExtrusion,u=a.isHidden(c,d);l>.5&&!u?a.hide([c],d):l<.5&&u&&a.show([c])}}}destroy(){this.mapModules.defaultSource.destroyModelsSource();for(const e in this.modelInfo){const t=this.modelInfo[e];this.removeLayerModel(e,t)}Array.from(this.sceneObjects.keys()).forEach(e=>this.removeSceneObjectState(e)),this.sceneObjects.clear(),this.handoffTracker.clear()}}function Bs(s){const{layerId:e,modelIndices:t}=s;return`${e}_${t.join(",")}`}function _l(s,e,t){return`${s}_${e}_${JSON.stringify(t)}`}function hE(s,e,t,i,r){const o=s.modelMatrices.get(0);if(!o)return-1;let a=e.min,l=e.max;r||(a=n.transformMat4$1(aE,a,o),l=n.transformMat4$1(lE,l,o));const c=n.projectToXyRect(t,a,l,oE),d=n.Mercator.toGeo(c),u=n.Mercator.scaleFactor(d[1]),h=n.dist$1(t,c)/n.MAP_POINTS_IN_METER/u;return n_(i,h)}function n_(s,e){let t=0;for(;t<s.length&&!(e<s[t]);)t++;return t-1}const _E=n.bezier(.42,0,1,1),fE=(s,e,t,i)=>e+t*_E(s/i),mE=n.bezier(0,0,.58,1),vE=(s,e,t,i)=>e+t*mE(s/i),gE=n.bezier(.42,0,.58,1),pE=(s,e,t,i)=>e+t*gE(s/i);function r_(s){switch(s[0]){case"cubic-bezier":{const e=n.bezier(s[1],s[2],s[3],s[4]);return(t,i,r,o)=>i+r*e(t/o)}case"exponential":{const e=s[1];return(t,i,r,o)=>{const a=i,l=i+r,c=t/o,u=(Re(e,c)-1)/(Re(e,1)-1);return(1-u)*a+u*l}}case"ease":return n.ease;case"ease-in":return fE;case"ease-out":return vE;case"ease-in-out":return pE;case"linear":return n.linear;default:return n.assertUnreachable(s,!0),console.warn("Invalid texture animation easing:",s),console.warn('Fallback to "linear".'),n.linear}}class xE{constructor(e,t){this.rerenderEvents=[],this.prevObjects=new Map,this.currentObjects=new Map,this.doubleSampledTextureAnimationStateMap=new Map,this.mapState=e,this.modules=t}frameEnd(){this.rerenderEvents.forEach(e=>this.modules.renderer.addRerenderEvent(e)),this.clearUnusedAnimationState(),this.doubleSampledTextureAnimationStateCleanup()}frameStart(){this.rerenderEvents=[]}clearAllTickers(){for(const e of this.currentObjects.keys())n.stop(e,this.mapState);this.clearUnusedAnimationState(),this.prevObjects=new Map,this.currentObjects=new Map}update(){const e=Date.now()+ +(this.mapState.styleState._customUserTimeOffset||0);[...this.prevObjects.values()].some(i=>i.timeToUpdate&&i.timeToUpdate<e)&&this.refresh()}animateGltfObject(e,t,i){const{localMatrix:r,animationStack:o,transformStack:a,textureTransformMatrix:l}=e.renderingProperties;if(t.style.playAnimation===void 0||!(o!=null&&o.length)||!r||!o||!a||!l)return;const c=this.updateAnimationKeyframes(e,t);pu(l,o,i.buffers,c),xu(r,o,a,i.buffers,c)}animateGltfVat(e,t){const{renderingProperties:i}=e,{useVat:r,vatFrameCount:o,vatDuration:a,vatAnimationIndex:l,vatAnimationName:c}=i;if(!r||!o||a===void 0)return;if(this.mapState.disableLayerAnimation||t.style.playAnimation===void 0){i.vatFrame=0;return}const d=this.resolveGltfAnimationOptions(t,e);if(!this.isVatAnimationSelected(d,l,c)){i.vatFrame=0;return}const u=this.applyAnimationState(t,e,"_vat",d);u.tickerByStep=!1;const h=u.animationStateID,_=u.animationDuration||a;if(!n.get(h,this.mapState)){if(u.repeatCount===0){i.vatFrame=0;return}if(u.currentCount<=0){i.vatFrame=o-1;return}this.startGltfAnimationTicker(u,h,o,_)}let m=!1;this.updateGltfAnimationTicker(u,h,(v,g)=>{i.vatFrame=g?o-1:Math.floor(v*o)%o,g||this.rerender(e,t,u)},()=>{m||(m=!0,u.currentCount>0&&u.currentCount--)}),m&&u.currentCount>0&&(n.stop(h,this.mapState),this.rerender(e,t,u))}animatePolygonNormalMapTexture(e,t){var L;if(!t.style.normalMapTextureAnimation)return[!1,[0,0,0,0]];let i=1;const r=t.innerId,o=e.attributes.styleId,a=`${o}_${r}`,l=Date.now(),[[c,d],[u,h],[_,f],m,v,g,p,x]=this.resolveDoubleSampledTextureAnimationOptions(t),S=[_,f,0,0];if(this.mapState.disableLayerAnimation)return[!1,S];const b=(L=this.doubleSampledTextureAnimationStateMap.get(a))!=null?L:{lastKnownOffsets:S,animationStage:0,previousTimestamp:l},{lastKnownOffsets:T,previousTimestamp:y,animationStage:E}=b;let P=E;const A=(l-y)/1e3;switch(E){case 0:{let D=!1;const B=n.makeBinderContext(this.mapState.styleZoom,this.mapState.pitch,this.mapState.styleState,[]),Q=n.resolveString(t.style.normalMapTextureImage,B),Z=this.modules.styleManager.getStyle(o);if(Z){const $=Z.rasterSets.byKey[n.getStaticTextureRasterSetKey(Q)];$&&$.isReady&&(D=!0)}D&&(v?(n.start(`${a}_animationSpeedUp`,{easing:r_(g),forceFinalValue:!0,renderAfterUpdate:!1},this.mapState,0,1,v,1),P=1):(m!==1/0&&n.start(`${a}_animationFullSpeed`,{forceFinalValue:!0,renderAfterUpdate:!1},this.mapState,1,1,m,1),P=2));break}case 1:{n.update(`${a}_animationSpeedUp`,{keepFinished:!0,step:(D,B,Q,Z)=>{Z?(i=1,n.stop(`${a}_animationSpeedUp`,this.mapState),m!==1/0&&n.start(`${a}_animationFullSpeed`,{forceFinalValue:!0,renderAfterUpdate:!1},this.mapState,1,1,m,1),P=2):i=B}},this.mapState);break}case 2:{m===1/0||n.update(`${a}_animationFullSpeed`,{keepFinished:!0,step:(D,B,Q,Z)=>{Z&&(n.stop(`${a}_animationFullSpeed`,this.mapState),p?(n.start(`${a}_animationSlowDown`,{easing:r_(x),forceFinalValue:!0,renderAfterUpdate:!1},this.mapState,1,0,p,1),P=3):P=4)}},this.mapState);break}case 3:{n.update(`${a}_animationSlowDown`,{keepFinished:!0,step:(D,B,Q,Z)=>{Z?(i=0,n.stop(`${a}_animationSlowDown`,this.mapState),P=4):i=B}},this.mapState);break}case 4:{i=0;break}}const F=[T[0]+c*i*A,T[1]+d*i*A,T[2]+u*i*A,T[3]+h*i*A].map(D=>D%1);return this.doubleSampledTextureAnimationStateMap.set(`${o}_${r}`,{animationStage:P,lastKnownOffsets:F,previousTimestamp:l,updatedOnThisFrame:!0,styleId:o,layerId:r}),P!==4&&this.rerenderEvents.push({type:"layerAnimationTicker",layerId:r,styleId:o,underCache:!0}),[!0,F]}startGltfAnimationTicker(e,t,i,r){const o=e.startOffset||0;let a=e.startOffset?i/(i*r/o):0,l=r*(1e3/e.playSpeed)-o*(1e3/e.playSpeed);e.elapsedTime&&(a=1-e.elapsedTime,l=r*(1e3/e.playSpeed)*e.elapsedTime),n.start(t,{easing:"linear",forceFinalValue:!0,renderAfterUpdate:!1},this.mapState,a,1,e.playSpeed===0?1/0:l,1)}updateGltfAnimationTicker(e,t,i,r){n.update(t,{keepFinished:!0,step:(o,a,l,c)=>{i(a,c)},complete:()=>{r()}},this.mapState),this.currentObjects.set(t,e)}doubleSampledTextureAnimationStateCleanup(){for(const[e,t]of this.doubleSampledTextureAnimationStateMap)if(t.updatedOnThisFrame)t.updatedOnThisFrame=!1,this.doubleSampledTextureAnimationStateMap.set(e,t);else{if(this.modules.renderCacheManager.isLayerInCache(t.styleId,t.layerId))return;this.doubleSampledTextureAnimationStateMap.delete(e),n.stop(`${e}_animationSpeedUp`,this.mapState),n.stop(`${e}_animationFullSpeed`,this.mapState),n.stop(`${e}_animationSlowDown`,this.mapState)}}resolveDoubleSampledTextureAnimationOptions(e){var v,g,p,x,S,b,T,y,E,P,A;const t=n.makeBinderContext(this.mapState.styleZoom,this.mapState.pitch,this.mapState.styleState,[]),i=n.resolveTextureAnimationExpression(e.style.normalMapTextureAnimation,t),r=(v=i[1])!=null?v:0,o=(g=i[2])!=null?g:0,a=(p=i[3])!=null?p:0,l=(x=i[4])!=null?x:0,c=(S=i[5])!=null?S:0,d=(b=i[6])!=null?b:0,u=(T=i[7])!=null?T:1/0,h=(y=i[8])!=null?y:0,_=(E=i[9])!=null?E:["linear"],f=(P=i[10])!=null?P:0,m=(A=i[11])!=null?A:["linear"];return[[r,o],[a,l],[c,d],u,h,_,f,m]}clearUnusedAnimationState(){for(const e of this.prevObjects.keys())if(!this.currentObjects.has(e)){const t=this.prevObjects.get(e);t&&this.modules.renderCacheManager.isLayerInCache(t.styleId,t.layerId)?this.currentObjects.set(e,t):n.stop(e,this.mapState)}this.prevObjects=new Map(this.currentObjects),this.currentObjects=new Map}refresh(){this.modules.renderer.addRerenderEvent()}isVatAnimationSelected(e,t,i){const r=e[0];return typeof r=="number"?t!==void 0&&r===t:typeof r=="string"?i!==void 0&&r===i:Array.isArray(r)?t!==void 0&&r.includes(t)||i!==void 0&&r.includes(i):!1}updateAnimationKeyframes(e,t){if(e.layerSettings.depthTest||e.layerSettings.shadow||this.mapState.disableLayerAnimation)return;const{animationStack:i}=e.renderingProperties;if(!i)return;const r=new Map,o=this.applyAnimationState(t,e),a=o.animationStateID;let l=!1;for(const c of i)if(this.isNeedAnimation(c,o)){if(!n.get(a,this.mapState)&&o.currentCount>0){const d=o.animationDuration||(c.max?c.max[0]:0);this.startGltfAnimationTicker(o,a,c.frameCount,d)}this.updateGltfAnimationTicker(o,a,(d,u)=>{const h=(c.frameCount-1)*d;r.set(c.actionId,h),u||this.rerender(e,t,o)},()=>{l||(l=!0,o.currentCount>0&&o.currentCount--)})}return l&&o.currentCount>0&&(n.stop(a,this.mapState),this.rerender(e,t,o)),r}initObjectAnimationState(e,t,i,r=""){var v,g,p;const o=typeof i[0]=="object"&&!Array.isArray(i[0])&&i[0].type==="schedule-detailed-result"?i[0].value:i[0],a=typeof i[0]=="object"&&!Array.isArray(i[0])&&i[0].type==="schedule-detailed-result"?i[0].currentStepElapsed/1e3:void 0,l=(v=i[2])!=null?v:1/0,c=l,d=(g=i[1])!=null?g:1,u=i[4]||void 0,h=i[3]||a||void 0,_=typeof o=="number"?o:void 0,f=typeof o=="string"?o:void 0,m=typeof o=="object"&&Array.isArray(o)?o:void 0;return{repeatCount:l,playSpeed:d,animationIndex:_,animationName:f,currentCount:c,animations:m,animationDuration:u,startOffset:h,tickerByStep:!!(h&&u),animationStateID:`${((p=i[5])==null?void 0:p.toString())||t.attributesHash}${r}`,timeToUpdate:i[6],layerId:e.innerId,styleId:t.attributes.styleId}}resolveGltfAnimationOptions(e,t){if(e.type!=="gltfModel"||e.style.playAnimation===void 0)return{type:"animation-options"};const i=n.makeBinderContext(this.mapState.styleZoom,this.mapState.pitch,this.mapState.styleState,t.attributes.tileData);let r;i.callBackFn=a=>{r=a};const o=n.resolveAnimationExpression(e.style.playAnimation,i);return o[6]===void 0&&r&&(o[6]=r),o}isNeedAnimation(e,t){return t.animationIndex!==void 0&&e.animationIndex===t.animationIndex||t.animationName!==void 0&&e.animationName===t.animationName||t.animations!==void 0&&t.animations.includes(e.animationIndex)||t.animations!==void 0&&t.animations.includes(e.animationName)}applyAnimationState(e,t,i="",r=this.resolveGltfAnimationOptions(e,t)){const o=this.initObjectAnimationState(e,t,r,i),a=this.prevObjects.get(o.animationStateID);return a&&(a&&((a==null?void 0:a.animationIndex)!==o.animationIndex||(a==null?void 0:a.animationName)!==o.animationName)?(n.update(o.animationStateID,{keepFinished:!0,step:(l,c)=>{a.elapsedTime?(a.elapsedTime>0||a.elapsedTime<1)&&(o.elapsedTime=a.elapsedTime):(a.elapsedTime=c,o.elapsedTime=c)}},this.mapState),n.stop(o.animationStateID,this.mapState)):o.repeatCount===a.repeatCount&&(o.currentCount=a.currentCount)),o}rerender(e,t,i){i.repeatCount!==0&&i.playSpeed!==0&&!i.tickerByStep&&(this.rerenderEvents.push({type:"layerAnimationTicker",layerId:t.innerId,styleId:e.attributes.styleId}),this.modules.identifier.queryFillCache())}}const Ft=.1,bE={id:"simple-mesh",type:"simpleMesh",innerId:n.SIMPLE_MESH_STYLE_LAYER_ID,filter:!1,minzoom:0,maxzoom:20,precomputes:[],renderIndex:0,style:{}},fl={polygonsQty:1e4,drawCallsQty:150,iterations:7},s_=[18,25],SE=1e3,Wn="__MAPGL_BENCH_TIME",yE=5,_n=class _n{constructor(e,t){this.state=e,this.modules=t,this.buffer=null,this.sceneObjects=[],this.timeout=1/0,this.scale=n.fromValues(1,1,1),this.startTs=0,this.de=ei(this.state,this.modules),this.framebufferId=this.createFramebuffer(),this.modules.dynamicStyle.addLayer(bE)}static mockResult(e){_n.mocked=e}run(){return q(this,arguments,function*(e=fl.polygonsQty,t=fl.drawCallsQty,i=fl.iterations,r=SE){if(_n.mocked)return _n.mocked;const o=this.getCachedResult();if(o)return o;this.timeout=r,this.startTs=performance.now();try{return yield this._run(e,t,t*i,i)}catch(a){return{status:"error"}}})}getScale(){return this.scale}destroy(){this.modules.renderer.removeFramebuffer(this.framebufferId),this.buffer=null,this.sceneObjects=[],this.modules.dynamicStyle.removeLayer(n.SIMPLE_MESH_STYLE_LAYER_ID)}getCachedResult(){try{const e="v1.81.0",t=localStorage.getItem(Wn);if(t){const i=t.split(":"),r=i[0];if(e===r){const o=i.slice(1).join(":").split(",").map(a=>parseFloat(a)).filter(a=>!Number.isNaN(a));if(o.length>=yE){const a=o.reduce((c,d)=>c+d,0)/o.length;return{status:"cached",tier:this.selectTier(a)}}}}}catch(e){}return null}selectTier(e){const t=s_.findIndex(i=>e<=i);return t>-1?s_.length-t:0}saveResult(e){try{const t="v1.81.0",i=localStorage.getItem(Wn);if(i){const r=i.split(":"),o=r[0];if(t!==o)localStorage.setItem(Wn,`${t}:${e.toPrecision(4)}`);else{const a=r.slice(1).join(":").split(",").map(l=>parseFloat(l)).filter(l=>!Number.isNaN(l));a.push(e),localStorage.setItem(Wn,`${t}:${a.map(l=>l.toPrecision(4)).join(",")}`)}}else localStorage.setItem(Wn,`${t}:${e.toPrecision(4)}`)}catch(t){}}_run(e,t,i,r){return q(this,null,function*(){const o=this.modules.renderer.getFramebuffer(this.framebufferId);if(!o)throw new Error("Failed to create framebuffer for benchmark.");this.modules.renderer.bindRenderTarget(o.renderTarget),this.modules.renderer.setViewport(0,0,this.modules.renderer.getViewportSize()[0],this.modules.renderer.getViewportSize()[1]);const a=this.prepareData(e,i),l=yield this.measureRendering(r,t);if(this.modules.renderer.bindRenderTarget(null),l.length<3)return{status:"timeout"};const c=this.processResults(l),d=Math.min(c.mean,c.median);this.saveResult(d);const u=this.selectTier(d);return{status:l.length<r?"part-done":"done",tier:u,measurements:c,preparation:a}})}prepareData(e,t){const i=performance.now();this.buffer=this.generateSphere(e);const r=performance.now(),o=performance.now();this.sceneObjects=this.createSceneObjects(t);const a=performance.now();return{generationTime:r-i,objectsTime:a-o}}measureRendering(e,t){return q(this,null,function*(){return new Promise(i=>{const r=[];let o=0,a=0;const l=()=>{const c=performance.now();if(c-this.startTs>this.timeout){i(r);return}this.modules.renderer.clear(!0),this.scale[0]+=.5-Math.random(),jo(this.state,this.modules,this.sceneObjects.slice(a,a+t),this.de),this.modules.renderer.waitForGpuCommandsToFinish(),r.push(performance.now()-c),o++,a+=t,o<e?Promise.resolve().then(l):i(r)};setTimeout(()=>{l()},0)})})}processResults(e){const t=e.slice();t.sort((r,o)=>r-o);const i=t.slice(0,t.length-.2*t.length);return{median:i[Math.floor(i.length/2)],mean:i.reduce((r,o)=>r+o,0)/i.length,min:i[0],max:i[i.length-1]}}generateSphere(e){const t=Math.floor(Math.sqrt(e/2)),i=t*2,l=t*i*2*3*3,c=new Float32Array(l);let d=0;const u=Math.PI/t,h=2*Math.PI/i,_=new Float32Array(3),f=new Float32Array(3),m=new Float32Array(3),v=new Float32Array(3);for(let g=0;g<t;g++){const p=g*u,x=(g+1)*u,S=Math.sin(p),b=Math.cos(p),T=Math.sin(x),y=Math.cos(x);for(let E=0;E<i;E++){const P=E*h,A=(E+1)*h,F=Math.sin(P),L=Math.cos(P),D=Math.sin(A),B=Math.cos(A);_[0]=Ft*S*L,_[1]=Ft*b,_[2]=Ft*S*F,f[0]=Ft*S*B,f[1]=Ft*b,f[2]=Ft*S*D,m[0]=Ft*T*L,m[1]=Ft*y,m[2]=Ft*T*F,v[0]=Ft*T*B,v[1]=Ft*y,v[2]=Ft*T*D,c.set(_,d),c.set(m,d+3),c.set(f,d+6),c.set(m,d+9),c.set(v,d+12),c.set(f,d+15),d+=18}}return c.buffer}createFramebuffer(){const e=new Pe({size:this.modules.renderer.getViewportSize(),magFilter:C.NearestFilter,minFilter:C.NearestFilter,wrapS:C.ClampToEdgeWrapping,wrapT:C.ClampToEdgeWrapping,type:C.Float,flipY:!0});return this.modules.renderer.addFramebuffer({clearColor:[0,0,0,0],renderTarget:e,onResize:()=>{}})}createSceneObjects(e){const t={programName:"simpleMesh",vaoCreator:Sc,stateBinder:()=>Cc,programBinder:kp,tileBinder:()=>!0,objectBinder:dx,needsVisibilityBuffer:!1},i=[],r=Sc(this.modules.renderer.createBuffer(this.buffer),this.modules.renderer.getShaderProgram("simpleMesh")),o=new n.TileObject("zenith",[],this.modules,this.state),a={layerId:n.SIMPLE_MESH_STYLE_LAYER_ID,styleId:n.DYNAMIC_STYLE_ID,tileData:[]};for(let l=0;l<e;l++){const d=(l/20&1)===0?1-(1+l%10)/10:(1+l%10)/10,u=n.fromValues(-1+l%20/10,1-Math.floor(l/20)*2/(e/20),0);i.push({id:n.uniqId(),type:n.SceneObjectType.Tile,start:0,count:this.buffer.byteLength/12,attributesHash:`benchmark-${l}`,vao:r,drawMode:n.GL_TRIANGLES,tile:o,symbol:"simpleMesh",sink:"fill",layerSettings:t,canRender:!0,attributes:a,meta:{scale:d,transform:u},renderingProperties:{}})}return i}};_n.mocked=null;let Os=_n;class TE extends n.Evented{constructor(e,t){super(),this.startRenderTime=0,this.catchNextUpdate=!1,this.collecting=!1,this.fpsStats=ws(),this.badFpsStats=ws(),this.caveatFpsStats=ws(),this.checkBadFrameCount=0,this.countToCheck=75,this.slowFrameTime=1e3/n.performanceCheck.fpsCaveat,this.badFrameRatioToCheck=.25,this.mapState=e,this.mapModules=t,this.originalMapState={center:this.mapState.center.slice(),zoom:this.mapState.zoom,rotation:this.mapState.rotation,pitch:this.mapState.pitch}}startCollecting(){this.collecting=!0,this.catchNextUpdate=!1}update(){if(!this.collecting||document.hidden){this.catchNextUpdate=!1;return}const{needRerender:e,rerenderEvents:t}=this.mapState,i=performance.now(),r=i-this.startRenderTime;if(this.catchNextUpdate){if(r>0){const o=1e3/r;ml(this.fpsStats,o),ml(this.caveatFpsStats,o),r>=this.slowFrameTime&&ml(this.badFpsStats,o),o<n.performanceCheck.fpsCaveat&&this.checkBadFrameCount++}this.catchNextUpdate=!1}(e||t.length>0)&&(this.startRenderTime=i,this.catchNextUpdate=!0),this.caveatFpsStats.count>this.countToCheck&&this.check()}getFpsStats(){const e=n.equalArrays(this.originalMapState.center,this.mapState.center)&&this.originalMapState.pitch===this.mapState.pitch&&this.originalMapState.rotation===this.mapState.rotation&&this.originalMapState.zoom===this.mapState.zoom;return{all:vl(this.fpsStats),bad:vl(this.badFpsStats),isStatic:e}}hasFpsStats(){return this.fpsStats.count>0}getMemoryStats(){return q(this,null,function*(){const e=yield this.getJsMemoryStats(),t=yield this.getGpuMemoryStats();return{cpu:e,gpu:t}})}check(){const e=vl(this.caveatFpsStats).avg;this.emit("fps",e),this.checkBadFrameCount/this.caveatFpsStats.count>=this.badFrameRatioToCheck&&(this.mapState.performanceCaveatEmitted=!0,this.emit("performancecaveat")),this.caveatFpsStats=ws(),this.checkBadFrameCount=0,this.countToCheck=Math.min(1e3,this.countToCheck*2)}getJsMemoryStats(){return q(this,null,function*(){const e=yield n.getRawMemoryStats(this.mapModules);return Object.values(e).filter(r=>!!r.js).map(r=>r.js).reduce((r,o)=>r+o["--sum"],0)})}getGpuMemoryStats(){return q(this,null,function*(){const e=yield n.getRawMemoryStats(this.mapModules);return Object.values(e).filter(r=>!!r.gpu).map(r=>r.gpu).reduce((r,o)=>r+o["--sum"],0)})}}function ws(){return{min:1/0,max:0,sum:0,count:0}}function ml(s,e){s.min=Math.min(s.min,e),s.max=Math.max(s.max,e),s.sum+=e,s.count++}function vl(s){return s.count===0?{min:0,max:0,avg:0,count:0}:{min:s.min,max:s.max,avg:s.sum/s.count,count:s.count}}const Ns={Point:0,Start:1,End:2},ks="fps",o_="frame",a_="skipped",l_=5e5,EE=.15;class CE{constructor(e=[]){this.startTime=performance.now(),this.activeScenarios=new Set,this.entries=[],this.overflowed=!1,this.captureMode="timeline",this.aggregateStarts=new Map,this.aggregates=new Map,this.lastStartIndex=new Map;for(const t of e)this.activeScenarios.add(t)}startScenarios(e){for(const t of e)this.activeScenarios.add(t)}stopScenarios(e){for(const t of e)this.activeScenarios.delete(t)}isScenarioActive(e){return this.activeScenarios.has(e)}setCaptureMode(e){this.captureMode=e}getCaptureMode(){return this.captureMode}logTime(e,t){this.activeScenarios.has(e)&&this.shouldCaptureTimeline()&&this.push(e,t,Ns.Point)}logStartTime(e,t){var l,c;if(!this.activeScenarios.has(e))return;const i=performance.now()-this.startTime,r=`${e}/${t}`;if(this.shouldCaptureSummary()){const d=(l=this.aggregateStarts.get(r))!=null?l:[];d.push(i),this.aggregateStarts.set(r,d)}if(!this.shouldCaptureTimeline())return;const o=this.entries,a=o.length;if(a>0){const d=o[a-1];if(d[3]===Ns.End&&d[0]===e&&d[1]===t&&i-d[2]<=EE){o.length=a-1;const u=this.lastStartIndex.get(r);if(u!==void 0){const h=o[u];h[4]=((c=h[4])!=null?c:1)+1}return}}this.push(e,t,Ns.Start,i),this.lastStartIndex.set(r,this.entries.length-1)}logEndTime(e,t){if(!this.activeScenarios.has(e))return;const i=performance.now()-this.startTime;this.shouldCaptureSummary()&&this.recordAggregate(e,t,i),this.shouldCaptureTimeline()&&this.push(e,t,Ns.End,i)}getLogTimes(){return this.entries}getLogTimeAggregates(){return Array.from(this.aggregates.values(),e=>I({},e))}clearLogTimes(){this.entries.length=0,this.overflowed=!1,this.lastStartIndex.clear(),this.aggregateStarts.clear(),this.aggregates.clear()}getStartTime(){return this.startTime}destroy(){this.activeScenarios.clear(),this.entries.length=0,this.overflowed=!1,this.lastStartIndex.clear(),this.aggregateStarts.clear(),this.aggregates.clear()}push(e,t,i,r){if(this.entries.length>=l_){this.overflowed||(this.overflowed=!0,console.warn(`[Profiler] entries buffer reached ${l_}, further samples dropped. Call clearLogTimes() to reset.`));return}this.entries.push([e,t,r!=null?r:performance.now()-this.startTime,i])}shouldCaptureTimeline(){return this.captureMode==="timeline"}shouldCaptureSummary(){return this.captureMode==="summary"}recordAggregate(e,t,i){var c,d;const r=`${e}/${t}`,o=(c=this.aggregateStarts.get(r))==null?void 0:c.pop();if(o===void 0)return;const a=i-o,l=(d=this.aggregates.get(r))!=null?d:{scenario:e,name:t,totalMs:0,count:0,maxMs:0};l.totalMs+=a,l.count++,l.maxMs=Math.max(l.maxMs,a),this.aggregates.set(r,l)}}class IE{constructor(e){this.modules=e,this.points=new Map}add(e){const t=Array.isArray(e)?e:[e];let i=!1;for(const r of t)this.points.set(r.id,r),i=!0;i&&this.sync()}remove(e){const t=Array.isArray(e)?e:[e];let i=!1;for(const r of t)this.points.delete(r)&&(i=!0);i&&this.sync()}has(e){return this.points.has(e)}clear(){this.points.size!==0&&(this.points.clear(),this.sync())}handleClick(e){const t=this.points.get(e);return t?(t.onClick(),!0):!1}destroy(){var e;(e=this.source)==null||e.destroy()}getSourceId(){return this.source?this.source.getId():null}ensureSource(){return this.source||(this.source=new n.GeoJsonSource(this.modules.map,{data:{type:"FeatureCollection",features:[]},attributes:{type:"mapgl_ui_poi"},promoteId:"mapgl_ui_poi_id"},this)),this.source}sync(){const e=[];this.points.forEach(i=>{e.push({type:"Feature",id:i.id,geometry:{type:"Point",coordinates:i.coordinates},properties:{mapgl_ui_poi_id:i.id,mapgl_ui_poi_sublayer:i.sublayer,mapgl_ui_poi_label:i.label}})});const t={type:"FeatureCollection",features:e};this.ensureSource().setData(t)}}const Us=3,Ms=3,Hs=4,Gs=4;class PE{constructor(e){this.maxParticles=e,this.data={positions:new Float32Array(e*Us),velocities:new Float32Array(e*Ms),params:new Float32Array(e*Hs),colors:new Float32Array(e*Gs),masses:new Float32Array(e),initialSizes:new Float32Array(e),angularVelocities:new Float32Array(e),frames:new Float32Array(e),aliveCount:0}}get capacity(){return this.maxParticles}get aliveCount(){return this.data.aliveCount}spawn(e,t,i,r,o,a,l,c,d,u,h,_,f,m){if(this.data.aliveCount>=this.maxParticles)return-1;const v=this.data.aliveCount,g=v*Us,p=v*Ms,x=v*Hs,S=v*Gs;return this.data.positions[g]=e,this.data.positions[g+1]=t,this.data.positions[g+2]=i,this.data.velocities[p]=r,this.data.velocities[p+1]=o,this.data.velocities[p+2]=a,this.data.params[x]=l,this.data.params[x+1]=0,this.data.params[x+2]=0,this.data.params[x+3]=u,this.data.colors[S]=h,this.data.colors[S+1]=_,this.data.colors[S+2]=f,this.data.colors[S+3]=m,this.data.masses[v]=c,this.data.initialSizes[v]=l,this.data.angularVelocities[v]=d,this.data.frames[v]=0,this.data.aliveCount++,v}kill(e){const t=this.data.aliveCount-1;e<t&&this.swap(t,e),this.data.aliveCount--}reset(){this.data.aliveCount=0}swap(e,t){const i=e*Us,r=t*Us;this.data.positions[r]=this.data.positions[i],this.data.positions[r+1]=this.data.positions[i+1],this.data.positions[r+2]=this.data.positions[i+2];const o=e*Ms,a=t*Ms;this.data.velocities[a]=this.data.velocities[o],this.data.velocities[a+1]=this.data.velocities[o+1],this.data.velocities[a+2]=this.data.velocities[o+2];const l=e*Hs,c=t*Hs;this.data.params[c]=this.data.params[l],this.data.params[c+1]=this.data.params[l+1],this.data.params[c+2]=this.data.params[l+2],this.data.params[c+3]=this.data.params[l+3];const d=e*Gs,u=t*Gs;this.data.colors[u]=this.data.colors[d],this.data.colors[u+1]=this.data.colors[d+1],this.data.colors[u+2]=this.data.colors[d+2],this.data.colors[u+3]=this.data.colors[d+3],this.data.masses[t]=this.data.masses[e],this.data.initialSizes[t]=this.data.initialSizes[e],this.data.angularVelocities[t]=this.data.angularVelocities[e],this.data.frames[t]=this.data.frames[e]}}function AE(s,e){const{positions:t,velocities:i,params:r,angularVelocities:o}=s.data;let a=0;for(;a<s.data.aliveCount;){const l=a*4,c=r[l+2]+e;if(c>=r[l+3]){s.kill(a);continue}r[l+2]=c;const d=a*3;t[d]+=i[d]*e,t[d+1]+=i[d+1]*e,t[d+2]+=i[d+2]*e,r[l+1]+=o[a]*e,a++}}class c_{emit(e,t){const i=e*3;t[i]=0,t[i+1]=0,t[i+2]=0}}class LE{constructor(e){this.radius=1,this.radialVelocity=!1,this.speedMin=0,this.speedMax=0,e!==void 0&&(this.radius=e)}emit(e,t,i){const r=e*3,o=Math.random()*2*Math.PI,a=Math.acos(2*Math.random()-1),l=this.radius*Math.cbrt(Math.random()),c=Math.sin(a),d=c*Math.cos(o),u=c*Math.sin(o),h=Math.cos(a);if(t[r]=d*l,t[r+1]=u*l,t[r+2]=h*l,this.radialVelocity){const _=this.speedMin+Math.random()*(this.speedMax-this.speedMin),f=e*3;i[f]=d*_,i[f+1]=u*_,i[f+2]=h*_}}}class RE{constructor(e,t,i){this.sizeX=10,this.sizeY=10,this.sizeZ=10,e!==void 0&&(this.sizeX=e),t!==void 0&&(this.sizeY=t),i!==void 0&&(this.sizeZ=i)}emit(e,t){const i=e*3;t[i]=(Math.random()-.5)*this.sizeX,t[i+1]=(Math.random()-.5)*this.sizeY,t[i+2]=(Math.random()-.5)*this.sizeZ}}class FE{constructor(e){this.radius=1,e!==void 0&&(this.radius=e)}emit(e,t){const i=e*3,r=Math.random()*2*Math.PI,o=this.radius*Math.sqrt(Math.random());t[i]=o*Math.cos(r),t[i+1]=o*Math.sin(r),t[i+2]=0}}class DE{constructor(e){this.angle=.3,this.speedMin=3,this.speedMax=6,(e==null?void 0:e.angle)!==void 0&&(this.angle=e.angle),(e==null?void 0:e.speedMin)!==void 0&&(this.speedMin=e.speedMin),(e==null?void 0:e.speedMax)!==void 0&&(this.speedMax=e.speedMax)}emit(e,t,i){const r=e*3;t[r]=0,t[r+1]=0,t[r+2]=0;const o=Math.cos(this.angle),a=o+(1-o)*Math.random(),l=Math.sqrt(1-a*a),c=Math.random()*2*Math.PI,d=this.speedMin+Math.random()*(this.speedMax-this.speedMin),u=e*3;i[u]=l*Math.cos(c)*d,i[u+1]=l*Math.sin(c)*d,i[u+2]=a*d}}class zE{constructor(e,t){this.emitterPosition=[0,0,0],this.emitter=new c_,this.affectors=[],this.renderFar=500,this.emitterVelocity=[0,0,0],this.parent=null,this.offset=[0,0,0],this.referencePosition=[0,0,0],this.spawnAccumulator=0,this.active=!0,this.prevReferencePosition=[0,0,0],this.referenceInitialized=!1,this.prevEmitterPosition=[0,0,0],this.emitterPositionInitialized=!1,this.options=e,this.pool=new PE(e.maxParticles),this.renderState=t,this.totalFrames=e.texture?e.texture.cols*e.texture.rows:0,e.parent&&(this.parent=e.parent),e.offset&&(this.offset=e.offset),this.affectorCtx={pool:this.pool.data,dt:0}}get aliveCount(){return this.pool.aliveCount}get poolData(){return this.pool}get mode(){return this.options.mode}get spawnConfig(){return this.options.spawn}get velocityInheritance(){var e;return(e=this.options.velocityInheritance)!=null?e:0}set velocityInheritance(e){this.options.velocityInheritance=e}update(e,t){if(this.active){if(this.options.mode!=="camera"&&this.parent&&this.resolveParent(),this.options.mode==="camera"&&t?(this.referencePosition[0]=t[0],this.referencePosition[1]=t[1],this.referencePosition[2]=t[2]):(this.referencePosition[0]=this.emitterPosition[0],this.referencePosition[1]=this.emitterPosition[1],this.referencePosition[2]=this.emitterPosition[2]),this.referenceInitialized){const i=this.referencePosition[0]-this.prevReferencePosition[0],r=this.referencePosition[1]-this.prevReferencePosition[1],o=this.referencePosition[2]-this.prevReferencePosition[2];(i!==0||r!==0||o!==0)&&this.shiftPositions(-i,-r,-o)}this.prevReferencePosition[0]=this.referencePosition[0],this.prevReferencePosition[1]=this.referencePosition[1],this.prevReferencePosition[2]=this.referencePosition[2],this.referenceInitialized=!0,this.emitterPositionInitialized&&e>0&&(this.emitterVelocity[0]=(this.emitterPosition[0]-this.prevEmitterPosition[0])/e,this.emitterVelocity[1]=(this.emitterPosition[1]-this.prevEmitterPosition[1])/e,this.emitterVelocity[2]=(this.emitterPosition[2]-this.prevEmitterPosition[2])/e),this.prevEmitterPosition[0]=this.emitterPosition[0],this.prevEmitterPosition[1]=this.emitterPosition[1],this.prevEmitterPosition[2]=this.emitterPosition[2],this.emitterPositionInitialized=!0,this.spawn(e),this.affectorCtx.pool=this.pool.data,this.affectorCtx.dt=e;for(let i=0;i<this.affectors.length;i++){const r=this.affectors[i];r.enabled&&r.apply(this.affectorCtx)}AE(this.pool,e)}}start(){this.active=!0}stop(){this.active=!1}setEmitterGeoPosition(e){var i;const t=n.Mercator.fromGeo(e);this.emitterPosition[0]=t[0],this.emitterPosition[1]=t[1],this.emitterPosition[2]=(i=t[2])!=null?i:0}setParent(e,t){this.parent=e,t&&(this.offset=t)}reset(){this.pool.reset(),this.spawnAccumulator=0}destroy(){this.active=!1,this.pool.reset()}setRate(e){this.options.rate=e}setSoftness(e){this.renderState.setSoftness(e)}setTexture(e){this.renderState.setTexture(e),this.totalFrames=e?e.cols*e.rows:0}spawn(e){var o;this.spawnAccumulator+=this.options.rate*e;const t=Math.floor(this.spawnAccumulator);this.spawnAccumulator-=t;const{spawn:i}=this.options,r=i.spread*(Math.PI/180);for(let a=0;a<t;a++){const l=jn(i.mass[0],i.mass[1]),c=jn(i.size[0],i.size[1]),d=jn(i.lifetime[0],i.lifetime[1]),u=i.rotation?jn(i.rotation[0],i.rotation[1]):0,h=this.pool.spawn(0,0,0,0,0,0,c,l,u,d,i.color[0],i.color[1],i.color[2],i.color[3]);if(h===-1)break;this.totalFrames>0&&(this.pool.data.frames[h]=Math.floor(Math.random()*this.totalFrames)),this.emitter.emit(h,this.pool.data.positions,this.pool.data.velocities);const _=h*3,f=this.pool.data.velocities[_],m=this.pool.data.velocities[_+1],v=this.pool.data.velocities[_+2];if(f===0&&m===0&&v===0){const p=BE(i.direction,r),x=jn(i.speed[0],i.speed[1]);this.pool.data.velocities[_]=p[0]*x,this.pool.data.velocities[_+1]=p[1]*x,this.pool.data.velocities[_+2]=p[2]*x}const g=(o=this.options.velocityInheritance)!=null?o:0;g>0&&(this.pool.data.velocities[_]+=this.emitterVelocity[0]*g,this.pool.data.velocities[_+1]+=this.emitterVelocity[1]*g,this.pool.data.velocities[_+2]+=this.emitterVelocity[2]*g)}}shiftPositions(e,t,i){const{positions:r}=this.pool.data;for(let o=0;o<this.pool.aliveCount;o++){const a=o*3;r[a]+=e,r[a+1]+=t,r[a+2]+=i}}resolveParent(){var u;const e=this.parent;if(!e)return;const t=e.getWorldTransform(),i=t.position,r=t.rotation[2]*Math.PI/180,o=this.offset[0]*n.MAP_POINTS_IN_METER,a=this.offset[1]*n.MAP_POINTS_IN_METER,l=this.offset[2]*n.MAP_POINTS_IN_METER,c=Math.cos(r),d=Math.sin(r);this.emitterPosition[0]=i[0]+o*c-a*d,this.emitterPosition[1]=i[1]+o*d+a*c,this.emitterPosition[2]=((u=i[2])!=null?u:0)+l}}function jn(s,e){return s+Math.random()*(e-s)}function BE(s,e){if(e<=0)return[s[0],s[1],s[2]];const t=Math.cos(e),i=t+(1-t)*Math.random(),r=Math.sqrt(1-i*i),o=Math.random()*2*Math.PI,a=r*Math.cos(o),l=r*Math.sin(o),c=i,[d,u,h]=s;let _,f,m;Math.abs(d)<.9?(_=1,f=0,m=0):(_=0,f=1,m=0);let v=u*m-h*f,g=h*_-d*m,p=d*f-u*_;const x=Math.sqrt(v*v+g*g+p*p);v/=x,g/=x,p/=x;const S=g*h-p*u,b=p*d-v*h,T=v*u-g*d;return[v*a+S*l+d*c,g*a+b*l+u*c,p*a+T*l+h*c]}class OE{constructor(e,t,i,r,o=0,a,l){this.program=null,this.quadBuffer=null,this.positionBuffer=null,this.velocityBuffer=null,this.paramsBuffer=null,this.colorBuffer=null,this.frameBuffer=null,this.vao=null,this.initialized=!1,this.viewportArr=new Float32Array(2),this.atlasGridArr=new Float32Array(2),this.textureEntry=null,this.localMvpBuffer=new Float32Array(16),this.renderer=e,this.gl=t,this.renderMode=i,this.maxParticles=r,this.softness=o,this.textureCache=l,a&&(this.atlasGridArr[0]=a.cols,this.atlasGridArr[1]=a.rows,this.textureEntry=this.acquireTexture(a.src,l))}render(e,t,i,r,o){this.initialized||this.init();const a=e.aliveCount;if(a===0)return;const{positions:l,velocities:c,params:d,colors:u,frames:h}=e.data;this.positionBuffer.subData(0,l.subarray(0,a*3)),this.velocityBuffer&&this.velocityBuffer.subData(0,c.subarray(0,a*3)),this.paramsBuffer.subData(0,d.subarray(0,a*4)),this.colorBuffer.subData(0,u.subarray(0,a*4)),this.frameBuffer.subData(0,h.subarray(0,a));const _=i[0],f=i[1],m=i[2];for(let p=0;p<12;p++)this.localMvpBuffer[p]=t[p];this.localMvpBuffer[12]=t[0]*_+t[4]*f+t[8]*m+t[12],this.localMvpBuffer[13]=t[1]*_+t[5]*f+t[9]*m+t[13],this.localMvpBuffer[14]=t[2]*_+t[6]*f+t[10]*m+t[14],this.localMvpBuffer[15]=t[3]*_+t[7]*f+t[11]*m+t[15],this.program.enable(),this.viewportArr[0]=r,this.viewportArr[1]=o;const v=this.textureEntry,g=v&&v.ready&&v.texture?1:0;g>0&&this.renderer.enableTexture(v.texture,0),this.program.bind({u_mvp:this.localMvpBuffer,u_viewport:this.viewportArr,u_useTexture:g,u_texture:0,u_softness:this.softness,u_atlasGrid:this.atlasGridArr}),this.renderer.bindVao(this.vao),this.renderer.drawInstancedArrays(this.gl.TRIANGLES,0,6,a)}setSoftness(e){this.softness=e}setTexture(e){this.textureEntry&&(this.textureEntry.refCount--,this.textureEntry=null),e?(this.atlasGridArr[0]=e.cols,this.atlasGridArr[1]=e.rows,this.textureEntry=this.acquireTexture(e.src,this.textureCache)):(this.atlasGridArr[0]=0,this.atlasGridArr[1]=0)}destroy(){var e,t,i,r,o,a;(e=this.quadBuffer)==null||e.remove(),(t=this.positionBuffer)==null||t.remove(),(i=this.velocityBuffer)==null||i.remove(),(r=this.paramsBuffer)==null||r.remove(),(o=this.colorBuffer)==null||o.remove(),(a=this.frameBuffer)==null||a.remove(),this.textureEntry&&(this.textureEntry.refCount--,this.textureEntry=null),this.program=null,this.vao=null,this.initialized=!1}init(){if(this.initialized)return;const e=this.gl,t=this.renderMode==="stretch"?"particleStretch":"particleBillboard";this.program=this.renderer.getShaderProgram(t);const i=new Float32Array([-1,-1,1,-1,1,1,-1,-1,1,1,-1,1]);this.quadBuffer=new n.Buffer(e,i,{itemSize:2,dataType:n.Buffer.Float,instanceDivisor:0,drawType:n.Buffer.StaticDraw});const r=this.maxParticles;this.positionBuffer=new n.Buffer(e,new Float32Array(r*3),{itemSize:3,dataType:n.Buffer.Float,instanceDivisor:1,drawType:n.Buffer.DynamicDraw}),this.positionBuffer.purpose="instanced",this.paramsBuffer=new n.Buffer(e,new Float32Array(r*4),{itemSize:4,dataType:n.Buffer.Float,instanceDivisor:1,drawType:n.Buffer.DynamicDraw}),this.paramsBuffer.purpose="instanced",this.colorBuffer=new n.Buffer(e,new Float32Array(r*4),{itemSize:4,dataType:n.Buffer.Float,instanceDivisor:1,drawType:n.Buffer.DynamicDraw}),this.colorBuffer.purpose="instanced",this.renderMode==="stretch"&&(this.velocityBuffer=new n.Buffer(e,new Float32Array(r*3),{itemSize:3,dataType:n.Buffer.Float,instanceDivisor:1,drawType:n.Buffer.DynamicDraw}),this.velocityBuffer.purpose="instanced"),this.frameBuffer=new n.Buffer(e,new Float32Array(r),{itemSize:1,dataType:n.Buffer.Float,instanceDivisor:1,drawType:n.Buffer.DynamicDraw}),this.frameBuffer.purpose="instanced";const o={a_quadVertex:this.quadBuffer,a_position:this.positionBuffer,a_frame:this.frameBuffer,a_params:this.paramsBuffer,a_color:this.colorBuffer};this.velocityBuffer&&(o.a_velocity=this.velocityBuffer),this.vao=new M(this.program,o),this.initialized=!0}acquireTexture(e,t){if(t){const o=t.get(e);if(o)return o.refCount++,o}const i={texture:null,ready:!1,refCount:1};t&&t.set(e,i);const r=new Image;return r.crossOrigin="anonymous",r.onload=()=>{const o=new C(r,{generateMipmaps:!1,premultiplyAlpha:!0,flipY:!1,magFilter:C.LinearFilter,minFilter:C.LinearFilter});this.renderer.prepareTexture(o),i.texture=o,i.ready=!0},r.src=e,i}}class wE{constructor(e){this.enabled=!0,this.gravity=-9.81,e!==void 0&&(this.gravity=e)}apply(e){const{velocities:t,aliveCount:i}=e.pool,r=this.gravity*e.dt;for(let o=0;o<i;o++)t[o*3+2]+=r}}function gl(s,e){const t=s.keys;if(t.length===0)return 0;if(t.length===1||e<=t[0].t)return t[0].value;const i=t[t.length-1];if(e>=i.t)return i.value;for(let r=0;r<t.length-1;r++){const o=t[r],a=t[r+1];if(e>=o.t&&e<a.t){if(s.interpolation==="step")return o.value;const l=a.t-o.t,c=l===0?0:(e-o.t)/l;return o.value+(a.value-o.value)*c}}return i.value}class d_{constructor(e){this.enabled=!0,this.buoyancy=9.81,this.curve=null,typeof e=="number"?this.buoyancy=e:e&&(this.curve=e)}apply(e){const{velocities:t,params:i,aliveCount:r}=e.pool,o=e.dt;if(this.curve){for(let l=0;l<r;l++){const c=i[l*4+2]/i[l*4+3];t[l*3+2]+=gl(this.curve,c)*o}return}const a=this.buoyancy*o;for(let l=0;l<r;l++)t[l*3+2]+=a}}class NE{constructor(e){this.enabled=!0,this.velocity=[0,0,0],this.strength=[30,30,1],e!=null&&e.velocity&&(this.velocity=e.velocity),e!=null&&e.strength&&(this.strength=e.strength)}apply(e){const{velocities:t,masses:i,aliveCount:r}=e.pool,o=e.dt,a=this.strength[0],l=this.strength[1],c=this.strength[2],d=this.velocity[0],u=this.velocity[1],h=this.velocity[2];for(let _=0;_<r;_++){const f=_*3,m=i[_],v=Math.min(1,a*o/m),g=Math.min(1,l*o/m),p=Math.min(1,c*o/m);t[f]+=(d-t[f])*v,t[f+1]+=(u-t[f+1])*g,t[f+2]+=(h-t[f+2])*p}}}class kE{constructor(e){this.enabled=!0,this.coefficient=1,(e==null?void 0:e.coefficient)!==void 0?this.coefficient=e.coefficient:(e==null?void 0:e.airDensity)!==void 0&&(e==null?void 0:e.dragCoefficient)!==void 0&&(this.coefficient=e.airDensity*e.dragCoefficient)}apply(e){const{velocities:t,masses:i,aliveCount:r}=e.pool,o=e.dt,a=this.coefficient;for(let l=0;l<r;l++){const c=l*3,d=t[c],u=t[c+1],h=t[c+2];if(d*d+u*u+h*h<1e-4)continue;const f=i[l],m=Math.max(0,1-a*o/f);t[c]*=m,t[c+1]*=m,t[c+2]*=m}}}class UE{constructor(e){this.enabled=!0,this.strength=5,this.frequency=.1,this.timeSpeed=.5,this.time=0,(e==null?void 0:e.strength)!==void 0&&(this.strength=e.strength),(e==null?void 0:e.frequency)!==void 0&&(this.frequency=e.frequency),(e==null?void 0:e.timeSpeed)!==void 0&&(this.timeSpeed=e.timeSpeed)}apply(e){const{positions:t,velocities:i,masses:r,aliveCount:o}=e.pool,a=e.dt;this.time+=a*this.timeSpeed;const l=this.frequency,c=this.strength*a,d=this.time;for(let u=0;u<o;u++){const h=u*3,_=u*3,f=r[u],m=t[h]*l,v=t[h+1]*l,g=t[h+2]*l,p=ME(m,v,g,d),x=HE(m,v,g,d),S=GE(m,v,g,d),b=c/f;i[_]+=p*b,i[_+1]+=x*b,i[_+2]+=S*b}}}function ME(s,e,t,i){return Math.sin(e*1.618+i*.7)*Math.cos(t*2.236+i*.3)+Math.sin(t*.927+s*1.414+i)*.5}function HE(s,e,t,i){return Math.sin(t*1.732+i*.9)*Math.cos(s*1.414+i*.5)+Math.cos(s*2.618+e*.866+i*1.1)*.5}function GE(s,e,t,i){return Math.cos(s*2.236+i*.6)*Math.sin(e*1.414+i*.8)+Math.sin(e*1.732+t*.618+i*.4)*.5}class VE{constructor(e){this.enabled=!0,this.omega=2,this.attraction=.9,this.tightness=4,this.curve=null,(e==null?void 0:e.omega)!==void 0&&(this.omega=e.omega),(e==null?void 0:e.attraction)!==void 0&&(this.attraction=e.attraction),(e==null?void 0:e.tightness)!==void 0&&(this.tightness=e.tightness),(e==null?void 0:e.curve)!==void 0&&(this.curve=e.curve)}apply(e){var f;const{positions:t,velocities:i,params:r,aliveCount:o}=e.pool,a=e.dt,l=(f=this.curve)==null?void 0:f.keys,c=!!(l!=null&&l.length),d=this.omega,u=this.attraction,h=Math.min(1,a*this.tightness);if(!c){for(let m=0;m<o;m++){const v=m*3,g=t[v],p=t[v+1],x=Math.sqrt(g*g+p*p);if(x<1e-6)continue;const S=1/x,b=(g*i[v+1]-p*i[v])*S,T=(g*i[v]+p*i[v+1])*S,y=d*x,E=b+(y-b)*h,P=T+(0-T)*h*u;i[v]=-E*p*S+P*g*S,i[v+1]=E*g*S+P*p*S}return}const _=this.tightness;for(let m=0;m<o;m++){const v=m*3,g=r[m*4+2]/r[m*4+3],p=gl(this.curve,g),x=Math.min(1,a*(_*p)),S=t[v],b=t[v+1],T=Math.sqrt(S*S+b*b);if(T<1e-6)continue;const y=1/T,E=(S*i[v+1]-b*i[v])*y,P=(S*i[v]+b*i[v+1])*y,A=d*p*T,F=E+(A-E)*x,L=P+(0-P)*x*u;i[v]=-F*b*y+L*S*y,i[v+1]=F*S*y+L*b*y}}}class ZE{constructor(e){this.enabled=!0,this.curve={keys:[{t:0,value:1},{t:1,value:1}]},e&&(this.curve=e)}apply(e){const{params:t,initialSizes:i,aliveCount:r}=e.pool,o=this.curve.keys;if(o.length===2){const a=o[0],l=o[1],c=a.value,d=l.value;for(let u=0;u<r;u++){const h=u*4,_=t[h+2]/t[h+3],f=c+(d-c)*_;t[h]=i[u]*f}return}for(let a=0;a<r;a++){const l=a*4,c=t[l+2]/t[l+3];t[l]=i[a]*gl(this.curve,c)}}}class WE{constructor(e){this.enabled=!0,this.curve={keys:[{t:0,color:[1,1,1,1]}]},e&&(this.curve=e)}apply(e){const{params:t,colors:i,aliveCount:r}=e.pool,o=this.curve.keys;if(o.length===2){const a=o[0],l=o[1],c=a.color[0],d=a.color[1],u=a.color[2],h=a.color[3],_=l.color[0],f=l.color[1],m=l.color[2],v=l.color[3];for(let g=0;g<r;g++){const p=g*4,x=t[p+2]/t[p+3];i[p]=c+(_-c)*x,i[p+1]=d+(f-d)*x,i[p+2]=u+(m-u)*x,i[p+3]=h+(v-h)*x}return}for(let a=0;a<r;a++){const l=a*4,c=t[l+2]/t[l+3];let d=0,u=0,h=0,_=0;if(o.length===1){const f=o[0].color;d=f[0],u=f[1],h=f[2],_=f[3]}else if(c<=o[0].t){const f=o[0].color;d=f[0],u=f[1],h=f[2],_=f[3]}else{const f=o[o.length-1];if(c>=f.t)d=f.color[0],u=f.color[1],h=f.color[2],_=f.color[3];else{let m=!1;for(let v=0;v<o.length-1;v++){const g=o[v],p=o[v+1];if(c>=g.t&&c<p.t){if(this.curve.interpolation==="step")d=g.color[0],u=g.color[1],h=g.color[2],_=g.color[3];else{const x=p.t-g.t,S=x===0?0:(c-g.t)/x;d=g.color[0]+(p.color[0]-g.color[0])*S,u=g.color[1]+(p.color[1]-g.color[1])*S,h=g.color[2]+(p.color[2]-g.color[2])*S,_=g.color[3]+(p.color[3]-g.color[3])*S}m=!0;break}}m||(d=f.color[0],u=f.color[1],h=f.color[2],_=f.color[3])}}i[l]=d,i[l+1]=u,i[l+2]=h,i[l+3]=_}}}class jE{constructor(e,t){this.enabled=!0,this.center=[0,0,0],this.volumeSize=[100,100,100],e&&(this.volumeSize=e),t&&(this.center=t)}apply(e){const{positions:t,aliveCount:i}=e.pool,r=this.volumeSize[0]/2,o=this.volumeSize[1]/2,a=this.volumeSize[2]/2,l=this.center[0],c=this.center[1],d=this.center[2];for(let u=0;u<i;u++){const h=u*3,_=t[h]-l;_>r?t[h]-=this.volumeSize[0]:_<-r&&(t[h]+=this.volumeSize[0]);const f=t[h+1]-c;f>o?t[h+1]-=this.volumeSize[1]:f<-o&&(t[h+1]+=this.volumeSize[1]);const m=t[h+2]-d;m>a?t[h+2]-=this.volumeSize[2]:m<-a&&(t[h+2]+=this.volumeSize[2])}}}const pl=.5,XE=1.5;class $E{constructor(e,t){this.systems=[],this.renderStates=new Map,this.lastTime=0,this.cameraMvpBuffer=new Float64Array(16),this.cameraOrigin=[0,0,0],this.textureCache=new Map,this.state=e,this.modules=t}add(e){var c,d;const t=this.modules.renderer,i=t.getRenderingContext(),r=e.mode==="camera"?1:n.MAP_POINTS_IN_METER,o=V(I({},e),{emitter:e.emitter,spawn:V(I({},e.spawn),{speed:[e.spawn.speed[0]*r,e.spawn.speed[1]*r],size:[e.spawn.size[0]*r,e.spawn.size[1]*r]})}),a=new OE(t,i,e.renderMode,e.maxParticles,(c=e.softness)!=null?c:0,e.texture,this.textureCache),l=new zE(o,a);if(this.renderStates.set(l,a),l.emitter=this.createEmitter(e.emitter,r),e.emitter.position){const u=n.Mercator.fromGeo(e.emitter.position);l.emitterPosition=[u[0],u[1],(d=u[2])!=null?d:0]}return e.affectors&&(l.affectors=this.createAffectors(e.affectors,r)),e.mode==="camera"&&(l.renderFar=this.computeCameraFar(e)),this.systems.push(l),l}remove(e){const t=this.systems.indexOf(e);if(t!==-1){this.systems.splice(t,1);const i=this.renderStates.get(e);i&&(i.destroy(),this.renderStates.delete(e)),e.destroy(),this.purgeTextureCache()}}update(){if(this.systems.length===0)return;const e=performance.now(),t=this.lastTime===0?.016:Math.min((e-this.lastTime)/1e3,.1);this.lastTime=e;const i=this.modules.camera,r=i.position[0],o=i.position[1],a=i.position[2];for(const l of this.systems)if(l.mode==="camera"){const c=n.MAP_POINTS_IN_METER;l.update(t,[r/c,o/c,a/c])}else l.update(t,[r,o,a]);this.hasAlive()&&this.state.rerenderEvents.push({type:"coreAnimationTicker"})}render(){if(this.systems.length===0||!this.hasAlive())return;const e=this.modules.camera,[t,i]=this.modules.renderer.getViewportSize();for(const r of this.systems){const o=this.renderStates.get(r);o&&(r.mode==="camera"?(this.modules.renderer.applyGpuState(qe),this.buildCameraModeVP(e.viewMatrix,t,i,r.renderFar),o.render(r.poolData,this.cameraMvpBuffer,this.cameraOrigin,t,i)):(this.modules.renderer.applyGpuState(Ri),o.render(r.poolData,e.viewProjectionMatrix,r.referencePosition,t,i)))}}destroy(){for(const e of this.systems){const t=this.renderStates.get(e);t&&t.destroy(),e.destroy()}this.systems=[],this.renderStates.clear(),this.purgeTextureCache()}purgeTextureCache(){for(const[e,t]of this.textureCache)t.refCount<=0&&(t.texture&&t.texture.remove(),this.textureCache.delete(e))}hasAlive(){for(const e of this.systems)if(e.aliveCount>0)return!0;return!1}buildCameraModeVP(e,t,i,r){const o=t/i,a=this.state.cameraConfig.fov,l=1/Math.tan(a/2),c=1/(pl-r),d=l/o,u=l,h=(r+pl)*c,_=2*r*pl*c,f=e,m=this.cameraMvpBuffer;m[0]=d*f[0],m[1]=u*f[1],m[2]=h*f[2],m[3]=-f[2],m[4]=d*f[4],m[5]=u*f[5],m[6]=h*f[6],m[7]=-f[6],m[8]=d*f[8],m[9]=u*f[9],m[10]=h*f[10],m[11]=-f[10],m[12]=0,m[13]=0,m[14]=_,m[15]=0}computeCameraFar(e){var l,c,d,u,h;let t=0,i=0,r=0;const o=(l=e.affectors)==null?void 0:l.find(_=>_.type==="wrapVolume");o&&o.type==="wrapVolume"?(t=o.volumeSize[0],i=o.volumeSize[1],r=o.volumeSize[2]):e.emitter.shape==="box"?(t=(c=e.emitter.size[0])!=null?c:10,i=(d=e.emitter.size[1])!=null?d:10,r=(u=e.emitter.size[2])!=null?u:10):(e.emitter.shape==="sphere"||e.emitter.shape==="circle")&&(t=i=r=((h=e.emitter.size[0])!=null?h:1)*2);const a=Math.sqrt(Re(t/2,2)+Re(i/2,2)+Re(r/2,2));return Math.max(a*XE,100)}createEmitter(e,t){var i,r,o,a,l,c,d,u;switch(e.shape){case"sphere":return new LE(((i=e.size[0])!=null?i:1)*t);case"box":return new RE(((r=e.size[0])!=null?r:10)*t,((o=e.size[1])!=null?o:10)*t,((a=e.size[2])!=null?a:10)*t);case"circle":return new FE(((l=e.size[0])!=null?l:1)*t);case"cone":return new DE({angle:(c=e.size[0])!=null?c:.3,speedMin:((d=e.size[1])!=null?d:3)*t,speedMax:((u=e.size[2])!=null?u:6)*t});default:return new c_}}createAffectors(e,t){const i=[];for(const r of e)switch(r.type){case"gravity":i.push(new wE(r.value*t));break;case"buoyancy":"curve"in r?i.push(new d_({interpolation:r.curve.interpolation,keys:r.curve.keys.map(o=>({t:o.t,value:o.value*t}))})):i.push(new d_(r.value*t));break;case"wind":i.push(new NE({velocity:[r.velocity[0]*t,r.velocity[1]*t,r.velocity[2]*t],strength:r.strength}));break;case"drag":i.push(new kE({coefficient:r.coefficient}));break;case"turbulence":i.push(new UE({strength:r.strength!==void 0?r.strength*t:void 0,frequency:r.frequency,timeSpeed:r.timeSpeed}));break;case"swirl":i.push(new VE({omega:r.omega,attraction:r.attraction,curve:r.curve}));break;case"scale":i.push(new ZE(r.curve));break;case"color":i.push(new WE(r.curve));break;case"wrapVolume":i.push(new jE([r.volumeSize[0]*t,r.volumeSize[1]*t,r.volumeSize[2]*t]));break}return i}}class qE{constructor(e,t,i){this.benchmark=null,this.profiler=new CE,this.map=i,this.camera=new n.Camera(e),this.layout=new w1(t),this.collector=new n.Collector("main"),this.workers=new C2,this.identifier=new z2(e,this),this.styleManager=new U2(this),this.assetManager=new H2(e,this),this.imageManager=new N1(this),this.uiPoiSource=new IE(this),this.floorManager=new v1(e,this),this.personalPoiManager=new X2(this),this.buildingHeightAnimator=new Wf(e,this),this.modelsScene=new uE(e,this),this.renderer=new kn(e,this),this.sunda=new F2(e,this),this.layers=new d1(this),this.sourceStorage=new M1,this.tileManager=new T1(e,this),this.modelLayer=new j2(e,this),this.dynamicStyle=new n.DynamicStyle,this.imageCache=new h1(this),this.labeler=new R1(e,this),this.trafficTileLayer=new B1(e,this),this.handler=new D1(e,this),this.mouseMoveHandler=new Gf(this),this.tileKeyInfo=new U1(e),this.elevationIndex=new H1(()=>e.demMode),this.demManager=new Kg(this),this.environmentManager=new j1(this),this.defaultSource=new Ih(e,this),this.labelsDebug=new Z1(e,this),this.postEffectsManager=new Bp(e,this),this.renderCacheManager=new gT(e,this),this.animationManager=new xE(e,this),this.shadowManager=new Rp(e,this),this.particleManager=new $E(e,this),this.instanceLinker=new J0(this),this.performanceChecker=new TE(e,this),e.graphicsPresetMode==="auto"&&(this.benchmark=new Os(e,this)),this.scheduler=new cf}destroy(){this.profiler.destroy(),this.demManager.disable(),this.imageManager.destroy(),this.trafficTileLayer.destroy(),this.tileManager.destroy(),this.workers.destroy(),this.identifier.destroy(),this.renderer.destroy(),this.sunda.destroy(),this.handler.destroy(),this.mouseMoveHandler.destroy(),this.labelsDebug.hide(),this.renderCacheManager.destroy(),this.particleManager.destroy(),this.tileKeyInfo.destroy(),this.scheduler.destroy(),this.layout.destroy()}}class YE{constructor(){this.lastDpr=window.devicePixelRatio}update(e,t){const i=window.devicePixelRatio;i!==this.lastDpr?(this.lastDpr=i,e.dpiChanged=!0,t.map.invalidateSize(),t.imageCache.clear()):e.dpiChanged=!1}}class QE{constructor(){this.metricsTimeout=n.metricsTimeout}update(e,t){if(e.metricsSent||e.graphicsPresetMode==="auto"&&!e.metrics.graphicsPreset)return;const i=e.metrics,r=performance.now()-i.start>this.metricsTimeout;(i.interactive!==void 0&&i.init!==void 0&&i.firstlabeling!==void 0&&i.ready!==void 0&&i.firstcontent!==void 0&&i.firstdraw!==void 0&&t.performanceChecker.hasFpsStats()||r)&&(i.fail=r,t.map.emit("metrics",i),e.metricsSent=!0)}}class JE{update(e,t){const i=t.demManager.getReliefTileType()==="vector"&&e.styleZoom<ld;e.demMode=this.checkDemEnabled(e,t)&&e.elevationScale>0&&!i}checkDemEnabled(e,t){return e.styleState.terrainEnabled===!0&&!e.globeMode&&!t.map.getFeatureFlag("reliefOff")?t.demManager.isEnabled()||t.demManager.enable():t.demManager.isEnabled()&&t.demManager.disable(),t.demManager.isEnabled()}}const u_=s=>{const{renderer:e,postEffectsManager:t,styleManager:i}=s,r=i.getClearColor();r!==void 0&&(e.setClearColor(r),t.setClearColor(r))};class KE{constructor(){this.prevGlobeMode=!1}update(e,t){this.updateGlobeMode(e,t),e.globeMode!==this.prevGlobeMode&&(this.prevGlobeMode=e.globeMode,t.map.emit(e.globeMode?"globeshow":"globehide"))}updateGlobeMode(e,t){const{handyStyleId:i,zoom:r}=e;if(!t.styleManager.getStyleLayer(i,n.ENVIRONMENT_STYLE_LAYER_ID)){const l=e.globeMode;e.globeMode=!1,e.globeRatioTarget=0,l&&!e.loopWorld&&!e.styleState.globeEnabled&&n.clampPoint(e.center,e.maxBounds,e.center);return}const{globeMaxZoom:a}=n.globeConfig;e.globeMode=!!e.styleState.globeEnabled&&r<a&&!t.map.getFeatureFlag("globeOff"),e.globeMode?e.globeRatioTarget=n.clamp(a-r,0,1):e.globeRatioTarget=0,e.globeRatioTarget>0&&u_(t),e.styleState.globeEnabled&&n.worldWrapX(e.center)}}class eC{constructor(){this.lastResizeTime=0}update(e,t){if(!e.enableTrackResize)return;const i=performance.now();if(i-this.lastResizeTime>=e.autoResizeInterval){const r=t.layout.canvas,{clientWidth:o,clientHeight:a}=t.layout.rootContainer,l=window.devicePixelRatio;(r.width!==Math.floor(o*l)||r.height!==Math.floor(a*l))&&(this.lastResizeTime=i,t.map.invalidateSize())}}}class tC{update(e,t){if(e.elevationScale=t.demManager.getVerticalScale(),!t.demManager.isEnabled()){e.elevation!==void 0&&(t.renderer.addRerenderEvent(),e.elevation=void 0);return}const i=t.demManager.getElevation(e.center);if(i!==void 0)if(e.elevation===void 0||e.skipElevationAnimation)e.elevation=i;else{const o=jg*(i-e.elevation);Math.abs(o)<Xg?e.elevation=i:e.elevation+=o;const a=t.demManager.getElevation(t.camera.position);if(a!==void 0){const l=e.elevationScale,c=a*l,d=t.camera.position[2]/n.MAP_POINTS_IN_METER,u=Math.min(30,d*.2),h=e.elevation*l+d-u;c>h&&(e.elevation+=(c-h)/l)}}const r=t.demManager.getMinElevation();r!==void 0&&(e.minElevation=r)}}const Ei=[0,0,0];class iC{constructor(){this.replicasDiffer=new n.Differ([{path:"visibleMapReplicas",type:"replicas"}])}update(e,t){const{size:i,zoom:r}=e,[o,a,l,c]=t.camera.getViewportVertices(),d=n.getLineConstants(o,a),u=n.pointToLineSignedDistance(t.camera.position,d),h=u<0,_=e.cameraConfig;let f=t.environmentManager.fogLimits[1]*t.camera.fogDistance;if(h&&(f+=u),t.demManager.isEnabled()&&e.elevation!==void 0&&!Number.isNaN(e.elevation)){const p=t.camera.position[2],x=e.minElevation!==void 0&&!Number.isNaN(e.minElevation)?e.minElevation:e.elevation,S=Math.max(e.elevation-x,0)*n.MAP_POINTS_IN_METER,b=Math.min(S/p+1,2),T=(b-1)*Math.max(1-e.pitch/e.maxPitch,.1)+1;n.lerp(o,t.camera.position,o,T),n.lerp(a,t.camera.position,a,T),n.lerp(c,t.camera.position,c,b),n.lerp(l,t.camera.position,l,b)}let m=n.pointToLineDistance(l,d);if(m>f){const p=f/m;n.lerp(l,a,l,p),n.lerp(c,o,c,p),m=f}n.copy$1(e.extendedTilesBounds[0],o),n.copy$1(e.extendedTilesBounds[1],a),n.copy$1(e.extendedTilesBounds[2],l),n.copy$1(e.extendedTilesBounds[3],c);const v=Math.min(_.minTrapezeHeight,f),g=Math.max(n.pixelToMapDistance(i[1],r)*_.viewportLimitRatio,v);if(m>g){const p=g/m;n.lerp(l,a,l,p),n.lerp(c,o,c,p),m=g}if(t.floorManager.visibleComplexIsMetro){const p=n.Mercator.toGeo(e.center),x=n.Mercator.scaleFactor(p[1]),S=n.MAX_UNDERGROUND_DEPTH*n.MAP_POINTS_IN_METER*x,b=t.camera.position,T=(b[2]+S)/b[2];n.subtract$1(Ei,l,b),n.scaleAndAdd(l,b,Ei,T),n.subtract$1(Ei,c,b),n.scaleAndAdd(c,b,Ei,T),n.subtract$1(Ei,a,b),n.scaleAndAdd(a,b,Ei,T),n.subtract$1(Ei,o,b),n.scaleAndAdd(o,b,Ei,T)}if((t.demManager.isEnabled()||t.floorManager.visibleComplexIsMetro)&&h){const p=(m+Math.abs(u))/m;n.lerp(o,c,o,p),n.lerp(a,l,a,p)}n.copy$1(e.tilesBounds[0],o),n.copy$1(e.tilesBounds[1],a),n.copy$1(e.tilesBounds[2],l),n.copy$1(e.tilesBounds[3],c),e.visibleMapReplicas=e.loopWorld||e.styleState.globeEnabled?n.getVisibleMapReplicas(e.tilesBounds,e.globeMode):[0],this.replicasDiffer.check(e)&&(e.needReplicasUpdate=!0)}}class nC{update(e){const t=!!e.styleState.immersiveRoadsOn;e.immersiveLevel.tiers=t&&e.styleZoom>=n.DEFAULT_MIN_TIERS_STYLE_ZOOM}}class rC{update(e,t){e.styleUpdateInProgress&&t.tileManager.viewportTilesReady()&&t.trafficTileLayer.viewportTilesReady()&&t.modelLayer.viewportModelsReady()&&(t.tileManager.finishStyleUpdating(),t.trafficTileLayer.finishStyleUpdating(),t.modelLayer.finishStyleUpdating(),t.modelsScene.finishStyleUpdating(),t.personalPoiManager.redraw(),u_(t),e.styleUpdateInProgress=!1,e.isFirstStyleUpdate=!1,t.renderer.addRerenderEvent(),e.needLabeling=!0)}}class sC{constructor(e){this.submitSundaFrame=e}update(e,t){var i,r;if(e.willRender=n.render.alwaysRerender||t.renderer.isNeedRerender(),e.willRender){const o=t.tileManager.getTileObjects(),a=(r=(i=this.submitSundaFrame)==null?void 0:i.call(this,o))!=null?r:!1;t.renderer.prerenderUpdate(),e.metrics.firstdraw===void 0&&(e.metrics.firstdraw=performance.now()-e.metrics.start),o.forEach(l=>{l.needSync&&l.syncReplicas(e)}),t.renderCacheManager.frameStart(),t.animationManager.frameStart(),t.renderer.renderElevation(o),t.shadowManager.drawShadowMap(o),t.renderer.renderLabelingTexture(o),t.renderer.renderSpriteLabelingTexture(o),t.renderer.renderTileObjects(o),t.particleManager.render(),t.shadowManager.drawDebugFbIfNeeded(),e.needRerender=a,e.rerenderEvents=new Array,t.animationManager.frameEnd(),t.renderCacheManager.frameEnd()}}}class oC{constructor(){this.differ=new n.Differ([{path:"graphicsPreset",type:"string"}])}update(e,t){if(!t.styleManager.getStyle(t.map.state.handyStyleId))return;const i=e.styleState.graphicsPreset,r=e.graphicsPresetSelection,o=this.differ.check(e.styleState),l=(r==null?void 0:r.name)===i?r.source:void 0;(e.metrics.graphicsPreset!==i||e.metrics.graphicsPresetSource!==l)&&(e.metrics.graphicsPreset=e.styleState.graphicsPreset,l?e.metrics.graphicsPresetSource=l:delete e.metrics.graphicsPresetSource,e.metricsSent=!1),o&&e.graphicsPresetMode&&t.map.emit("graphicspresetchange")}}class aC{constructor(){this.differ=new n.Differ([{path:"center",type:"vec2"},{path:"zoom",type:"number"},{path:"rotation",type:"number"},{path:"pitch",type:"number"}]),this.debouncedSet=n.debounce(e=>{n.start("stillness",{},e,e.stillness,1,400,1)},100,!1),this.stillnessTickerUpdate=n.update.bind(null,"stillness",{step:(e,t)=>{e.stillness=t}})}update(e){this.differ.check(e)&&(e.stillness=0,n.stop("stillness",e),this.debouncedSet(e)),this.stillnessTickerUpdate(e)}}function lC(s){const{modules:e,handlerSteps:t,state:i}=s,r=new YE,o=new aC,a=new QE,l=new JE,c=new KE,d=new eC,u=new tC,h=new iC,_=new nC,f=new rC,m=new sC(s.submitSundaFrame),v=new oC;return{[wt.Init]:[{name:"profiler.logFrameStart",updater:{update:()=>e.profiler.logStartTime(ks,o_)}},{name:"immersiveLevel",updater:_},{name:"dpiHandler",updater:r},{name:"framestart",updater:{update:()=>{e.map.emit("framestart"),e.renderer.resetStateAfterExternalRender(),i.time=Date.now()}}},{name:"metricsHandler",updater:a},{name:"autoResize",updater:d}],[wt.Input]:[{name:"mouseMoveHandler",updater:e.mouseMoveHandler},...t.map((g,p)=>({name:`handler:${p}`,updater:g})),{name:"zoomTransform",criticality:ut.Critical,updater:Lf},{name:"centerTransform",criticality:ut.Critical,updater:Tf},{name:"rotationTransform",criticality:ut.Critical,updater:Cf},{name:"pitchTransform",criticality:ut.Critical,updater:Pf},{name:"stillnessUpdater",updater:o},{name:"inertiaTransform",updater:Sf},{name:"viewportTransform",updater:_f},{name:"paddingTransform",updater:pf}],[wt.MapState]:[{name:"globeMode",updater:c},{name:"demMode",updater:l},{name:"camera.update",criticality:ut.Critical,updater:e.camera},{name:"updateElevation",criticality:ut.Critical,updater:u},{name:"updateTilesBounds",criticality:ut.Critical,updater:h}],[wt.Update]:[{name:"demManager",criticality:ut.Critical,updater:e.demManager},{name:"environmentManager",updater:e.environmentManager},{name:"labelsDebug",updater:e.labelsDebug},{name:"trafficTileLayer",updater:e.trafficTileLayer},{name:"tileManager",criticality:ut.Critical,updater:e.tileManager},{name:"instanceLinker",updater:e.instanceLinker},{name:"sourceStorage",updater:e.sourceStorage},{name:"floorManager",updater:e.floorManager},{name:"modelLayer",updater:e.modelLayer},{name:"personalPoiManager",updater:e.personalPoiManager},{name:"dynamicStyle",updater:e.dynamicStyle},{name:"styleManager",criticality:ut.Critical,updater:e.styleManager},{name:"buildingHeightAnimator",updater:e.buildingHeightAnimator},{name:"modelsScene",updater:e.modelsScene},{name:"shadowManager",updater:e.shadowManager},{name:"animationManager",updater:e.animationManager},{name:"particleManager",updater:e.particleManager},{name:"map.emit.update",updater:{update:()=>e.map.emit("update")}}],[wt.PreDraw]:[{name:"labeler",updater:e.labeler},{name:"performanceChecker",updater:e.performanceChecker},{name:"identifier",updater:e.identifier},{name:"postEffectsManager",updater:e.postEffectsManager},{name:"loopWorldWrap",updater:{update:(g,p)=>{g.loopWorld&&!p.renderer.isNeedRerender()&&n.worldWrapX(g.center)}}},{name:"resetStats",updater:{update:g=>{g.collectStats&&(g.stats.drawCount=0,g.stats.vertexCount=0,g.stats.triangleCount=0,g.stats.drawCountBySymbol={})}}}],[wt.Draw]:[{name:"draw",criticality:ut.Critical,updater:m}],[wt.Cleanup]:[{name:"collectStats",updater:{update:(g,p)=>{g.willRender&&g.collectStats&&(p.map.emit("stats",g.stats),(!g.metricsSent||g.metrics.graphicsPreset!==g.styleState.graphicsPreset)&&(g.metrics.vertexCount=g.stats.vertexCount,g.metrics.triangleCount=g.stats.triangleCount,g.metrics.drawCount=g.stats.drawCount))}}},{name:"finishStyleUpdatingCheck",updater:f},{name:"map.update",updater:e.map},{name:"assetManager",updater:{update:()=>e.assetManager.invalidateUsedGltfModels()}},{name:"resetFlags",updater:{update:g=>{g.needReplicasUpdate=!1,g.shouldIsReadyWaitForUpdates=!1,g.shouldIsIdleWaitForUpdates=!1}}},{name:"frameend",updater:{update:()=>e.map.emit("frameend")}},{name:"graphicsPresetCheck",updater:v},{name:"profiler.logEnd",updater:{update:(g,p)=>{g.willRender||(p.profiler.logStartTime(ks,a_),p.profiler.logEndTime(ks,a_)),p.profiler.logEndTime(ks,o_)}}}]}}const hn=["light","normal","immersive"];function Xn(s){return hn.some(e=>e===s)}function h_(s,e,t,i){return i&&e!==t?"deprecatedSystem":s}const cC=["immersiveRoadsOff","reliefOff","shadowsOff","fogOff","skyOff","modelsOff","globeOff","transparentBuildingsOff","AALinesOff"],dC=.3,__=10;function uC(s,e){if(s===!1&&e)switch(e){case"taa":return Et.TAA;case"fxaa":return Et.FXAA;case"msaa":return Et.MSAA;case"smaa":return Et.SMAA;default:return}}function hC(s,e,t){var l;if(s.graphicsPreset==="auto")return null;const i=s.graphicsPreset,r=(l=s.styleState)==null?void 0:l.graphicsPreset,o=i||(Xn(r)?r:hn[2]),a=i||Xn(r)?"hostOption":"default";return{name:e,source:h_(a,o,e,t)}}const fn=class fn{constructor(e,t={},i){var _,f,m,v,g,p,x,S,b,T,y,E,P,A,F,L,D,B,Q;this.benchmarkResult=null,this.requestedFrame=requestAnimationFrame(()=>{}),this.fatalFrameCount=0,this.renderLoop=()=>{if(!this.modules.renderer.isDestroyed){try{this.modules.scheduler.runFrame(),this.fatalFrameCount=0}catch(Z){if(this.fatalFrameCount++,console.error(`[renderLoop] uncaught exception (frame ${this.fatalFrameCount}/${__})`,Z),this.fatalFrameCount>=__)return}this.requestedFrame=requestAnimationFrame(this.renderLoop)}};const r=I(I({},fn.options),t),o=I(I({},fn.options.padding),r.padding),a=I(I({},fn.options.viewport),r.viewport),l=r.maxBounds?n.fromGeo(r.maxBounds):r.loopWorld?n.worldLoopBounds:n.worldBounds,c=n.Mercator.fromGeo(r.center);n.worldWrapX(c),n.clampPoint(c,l,c);const d=r.graphicsPreset&&r.graphicsPreset!=="auto"?V(I({},r.styleState),{graphicsPreset:r.graphicsPreset,lang:r.lang}):V(I({},r.styleState),{lang:r.lang}),u=this.state={time:Date.now(),center:c,zoom:r.styleZoom!==void 0?n.getZoomFromStyleZoom(r.styleZoom,c):r.zoom,rotation:n.degToRad(r.rotation),pitch:n.degToRad(r.pitch),styleZoom:r.styleZoom!==void 0?r.styleZoom:n.getStyleZoom(r.zoom,c),zoomTypePreserving:r.styleZoom!==void 0?"styleZoom":"zoom",minZoom:r.minZoom,maxZoom:r.maxZoom,maxBounds:l,loopWorld:(_=r.loopWorld)!=null?_:!1,touchRotationThreshold:n.degToRad(r.touchRotationThreshold),minPitch:n.degToRad(r.minPitch),maxPitch:n.degToRad(r.maxPitch),lowZoomMaxPitch:r.lowZoomMaxPitch?n.degToRad(r.lowZoomMaxPitch):null,size:[Math.max(1,e.clientWidth-a.left-a.right),Math.max(1,e.clientHeight-a.top-a.bottom)],tickers:{},stillness:1,needRerender:!0,willRender:!1,needLabeling:!1,needReplicasUpdate:!1,userHasInteracted:!1,dpiChanged:!1,viewport:a,padding:o,labelingOpacity:0,tileServer:r.tileServer,styleServer:r.styleServer||n.styles.url,fontUrl:r.fontUrl||n.fonts.defaultUrl,modelUrl:r.modelUrl||n.defaultModelsPath,iconUrl:r.iconUrl||n.icons.defaultUrl,keyUrl:r.keyUrl||n.keyServerPath,tileSet:r.tileSet,tileProtocol:r.tileProtocol,commercialTileSet:r.commercialTileSet,modelsTileSet:(f=r.modelsTileSet)!=null?f:n.models.tileSet,modelsTilesUrl:(m=r.modelsTilesUrl)!=null?m:n.urls.models,defaultSourceModelsRootUrl:r.defaultSourceModelsRootUrl,defaultSourceModelsAppearStrategy:r.defaultSourceModelsAppearStrategy,sharedModelsPath:r.sharedModelsPath,subdomains:r.subdomains.split(""),floorsEnabled:r.floorsEnabled,collectStats:r.collectStats,stats:{tileCount:0,dynamicTileCount:0,viewportTileCount:0,displayedTileCount:0,drawCount:0,vertexCount:0,triangleCount:0,drawCountBySymbol:{},foundVisibleTilesCount:0},trafficOn:!!r.trafficOn,trafficServer:r.trafficServer,trafficProtocol:r.trafficProtocol,identifyPickDistance:n.identify.pickDistance,lang:r.lang,tileServerDefaultLang:r.tileServerDefaultLang,tileKey:r.key,appId:r.appId,disableHoverStyles:r.disableHoverStyles,keepCenterWhileUserZoomRotate:!!r.keepCenterWhileUserZoomRotate,disableRotationByUserInteraction:!!r.disableRotationByUserInteraction,disablePitchByUserInteraction:!!r.disablePitchByUserInteraction,disableDragging:!!r.disableDragging,enableTwoFingerDragging:!!r.enableTwoFingerDragging,performanceCaveatEmitted:!1,sessionId:r.sessionId,tileSessionId:r.tileSessionId,shownRegionIds:new Set,preserveDrawingBuffer:!!r.preserveDrawingBuffer,defaultBackgroundColor:n.handyColor(r.defaultBackgroundColor),handyStyleId:NaN,styleId:"",styleState:Ts(d),disableIconCache:r.disableIconCache,disableRenderingCache:r.disableRenderingCache,rtlPlugin:{scenario:(v=r.useRtlTextPlugin)!=null?v:"depends-on-language",loadFailed:!1,url:(g=r.rtlPluginUrl)!=null?g:n.rtlPluginUrl,hash:(p=r.rtlPluginHash)!=null?p:n.rtlPluginHash},mobileSdkMode:r.mobileSdkMode,dracoDecoderUrl:(x=r==null?void 0:r.dracoDecoderUrl)!=null?x:n.dracoDecoderUrl,demMode:!1,globeMode:!1,globeRatioTarget:0,visibleMapReplicas:[0],tilesBounds:[[0,0],[0,0],[0,0],[0,0]],extendedTilesBounds:[[0,0],[0,0],[0,0],[0,0]],elevation:void 0,elevationScale:0,minElevation:void 0,skipElevationAnimation:r.skipElevationAnimation,metrics:{start:performance.now(),fail:!1,vertexCount:0,triangleCount:0,drawCount:0},metricsSent:!1,graphicsPresetSelection:null,styleUpdateInProgress:!1,isFirstStyleUpdate:!0,shouldIsReadyWaitForUpdates:!1,shouldIsIdleWaitForUpdates:!1,commercialPoiRandomSeed:r.commercialPoiRandomSeed,disableSurvivedPoiPrevalence:!!r.disableSurvivedPoiPrevalence,webglVersion:r.webglVersion,sunda:r.sunda,enableTrackResize:!!r.enableTrackResize,autoResizeInterval:n.render.autoResizeInterval,showDefaultTileBounds:!!r.showDefaultTileBounds,immersiveLevel:{tiers:!1},pitchHightLimitation:r.pitchHightLimitation===void 0?n.degToRad(90):n.degToRad(r.pitchHightLimitation),isLabelingDepthTestDisabled:!1,iconIdentifyOpacity:(S=r.iconIdentifyOpacity)!=null?S:dC,disableHidingPois:(b=r.disableHidingPois)!=null?b:!1,resetFloorModeOnActivation:(T=r.resetFloorModeOnActivation)!=null?T:!1,aaMode:uC(r.disableAntiAliasing,r.antiAliasingMode),rerenderEvents:new Array,cameraConfig:Object.assign({},n.defaultCameraConfig),cityCommPoiLabeling:{config:r.cityCommPoiLabelingConfig,ascSortedZoomNumbers:I1(r.cityCommPoiLabelingConfig)},trafficMinZoom:(y=r.trafficMinZoom)!=null?y:n.traffic.minZoom,trafficMaxZoom:(E=r.trafficMaxZoom)!=null?E:n.traffic.maxZoom,trafficMaxDetailLevel:(P=r.trafficMaxDetailLevel)!=null?P:n.traffic.maxDetailLevel,bssHostAppParams:r.bssHostAppParams,disableStyleFallback:!!r.disableStyleFallback,hiddenImmersiveRoutesEnabled:dm(),modelShowHideEventsSublayers:new Set((A=r.modelShowHideEventsSublayers)!=null?A:[]),graphicsPresetMode:r.graphicsPreset,shouldEmitGraphicsPresetChangeEvent:!1,isDeprecatedSystem:cr(),isFloatTextureSupported:!1,isVertexTextureFetchSupported:!1,disableModelsGrowthAnimation:(F=r.disableModelsGrowthAnimation)!=null?F:!1,disableLayerAnimation:(L=r.disableLayerAnimation)!=null?L:!1,allowMetro:(D=r.allowMetro)!=null?D:!1,metro3dVisible:(B=r.metro3dVisible)!=null?B:!1,forceSyncIdentify:(Q=r.forceSyncIdentify)!=null?Q:!1,forceInteractivity:!1};u.graphicsPresetSelection=hC(t,u.styleState.graphicsPreset,u.isDeprecatedSystem),u.graphicsPresetSelection&&(u.metrics.graphicsPreset=u.graphicsPresetSelection.name,u.metrics.graphicsPresetSource=u.graphicsPresetSelection.source),r.cameraConfig&&Object.assign(u.cameraConfig,r.cameraConfig),this.modules=new qE(u,e,i),u.isFloatTextureSupported=Yf(this.modules.renderer.getRenderingContext()),u.isVertexTextureFetchSupported=Qf(this.modules.renderer.getRenderingContext()),typeof u.commercialPoiRandomSeed=="number"&&this.modules.workers.labeling.setCommercialPoiRandomSeed(u.commercialPoiRandomSeed),this.modules.styleManager.setDynamicStyle(this.modules.dynamicStyle.getStyle()),this.handlers=[new Uf(u,this.modules.layout.mapContainer),new Mf(this.modules)],r.disableZoomOnScroll||this.handlers.push(new kf(u,this.modules.layout.mapContainer)),Of&&or&&this.handlers.push(new Hf(u,e,i)),lf(lC({modules:this.modules,state:this.state,handlerSteps:this.handlers,submitSundaFrame:Z=>{var $,J;return(J=($=this.modules.sunda.frameBuilder)==null?void 0:$.submit(Z))!=null?J:!1}}),this.state,this.modules),(r.graphicsPreset==="auto"?this.measurePerformance():Promise.resolve()).finally(()=>{this.requestedFrame=requestAnimationFrame(this.renderLoop)})}destroy(){cancelAnimationFrame(this.requestedFrame),this.modules.destroy(),this.handlers.forEach(e=>e.destroy())}isIdle(){return!this.modules.renderer.isNeedRerender()&&!this.modules.renderer.hasPendingShaderPrograms()&&!this.state.shouldIsIdleWaitForUpdates&&this.modules.tileManager.isIdle()&&this.modules.assetManager.isIdle()&&this.modules.trafficTileLayer.viewportTilesReady()&&this.modules.layers.entranceAnimationFinished()&&this.modules.modelLayer.isIdle()&&!this.modules.buildingHeightAnimator.isAnimating()&&!this.modules.modelsScene.isAnimating()&&this.modules.labeler.isIdle()&&this.modules.identifier.isIdle()&&this.modules.demManager.isIdle()}isReady(){return this.isIdle()&&this.modules.floorManager.floorsReady()&&this.modules.identifier.isIdle()&&this.modules.imageManager.isIdle()&&this.modules.imageCache.isIdle()&&this.modules.personalPoiManager.isIdle()&&this.modules.tileKeyInfo.isIdle()&&this.modules.postEffectsManager.isReady()&&!this.state.shouldIsReadyWaitForUpdates}isReadyForMetrics(){return!this.modules.renderer.isNeedRerender(!0)&&!this.modules.renderer.hasPendingShaderPrograms()&&!this.state.shouldIsIdleWaitForUpdates&&this.modules.tileManager.isIdle()&&this.modules.assetManager.isIdle()&&this.modules.trafficTileLayer.viewportTilesReady()&&this.modules.modelLayer.isIdle()&&!this.modules.buildingHeightAnimator.isAnimating()&&!this.modules.modelsScene.isAnimating()&&this.modules.labeler.isIdle()&&this.modules.floorManager.floorsReady()&&this.modules.identifier.isIdle()&&this.modules.imageManager.isIdle()&&this.modules.imageCache.isIdle()&&this.modules.personalPoiManager.isIdle()&&this.modules.tileKeyInfo.isIdle()&&this.modules.postEffectsManager.isReady(!0)&&!this.state.shouldIsReadyWaitForUpdates}hasActiveLayerAnimation(){return this.state.rerenderEvents.some(e=>e.type==="layerAnimationTicker")||!this.modules.layers.entranceAnimationFinished()}redrawMap(){this.modules.tileManager.redraw(),this.modules.trafficTileLayer.redraw(),this.modules.modelLayer.redraw(),this.modules.personalPoiManager.redraw()}activateStyleUpdating(){this.modules.tileManager.activateStyleUpdating(),this.modules.modelLayer.activateStyleUpdating(),this.modules.trafficTileLayer.activateStyleUpdating(),this.state.styleUpdateInProgress=!0}getIsFirstStyleUpdate(){return this.state.isFirstStyleUpdate}measurePerformance(){return q(this,null,function*(){performance.now();const e=yield this.modules.benchmark.run();this.benchmarkResult=e,this.modules.benchmark.destroy(),this.modules.benchmark=null;let t=hn[0],i="benchmarkFallback";switch(e.status){case"error":case"timeout":break;case"part-done":case"done":{t=hn[e.tier],i="benchmark",this.state.metrics.benchRenderTime=Math.round(e.measurements.mean),this.state.metrics.benchGenTime=Math.round(e.preparation.generationTime);break}case"cached":{t=hn[e.tier],i="benchmarkCache";break}}this.modules.map.patchStyleState({graphicsPreset:t},{source:i,recordUnchanged:!0}),this.state.graphicsPresetSelection&&(this.state.metrics.graphicsPreset=this.state.graphicsPresetSelection.name,this.state.metrics.graphicsPresetSource=this.state.graphicsPresetSelection.source)})}};fn.options={center:[0,0],zoom:0,minZoom:n.MAP_DEFAULTS.minZoom,maxZoom:n.MAP_DEFAULTS.maxZoom,rotation:0,touchRotationThreshold:10,pitch:0,minPitch:0,maxPitch:45,lowZoomMaxPitch:45,viewport:{top:0,right:0,bottom:0,left:0},padding:{top:0,right:0,bottom:0,left:0},tileServer:n.tiles.server,tileSet:n.tiles.tileSet,tileProtocol:n.tiles.protocol,commercialTileSet:n.commercialPoi.tileSet,key:n.tiles.tileKey,subdomains:n.tiles.subdomains,floorsEnabled:n.floors.enabled,trafficProtocol:n.traffic.protocol,trafficServer:n.traffic.host,collectStats:!1,style:"",styleState:_1(),styleOptions:{rootUrl:"",iconsPath:"",fontsPath:"",stylePath:"",modelsPath:""},lang:n.defaultLang,appId:n.tiles.appId,disableHoverStyles:!1,disableZoomOnScroll:!1,disableDragging:!1,enableTwoFingerDragging:!1,disableRotationByUserInteraction:!1,disablePitchByUserInteraction:!1,defaultBackgroundColor:"#f6f2de",disableIconCache:!1,disableRenderingCache:!1,mobileSdkMode:!1,skipElevationAnimation:!1,enableTrackResize:!1,showDefaultTileBounds:!1,immersiveOn:!1,pitchHightLimitation:90,trafficOn:!1,trafficMinZoom:n.traffic.minZoom,trafficMaxZoom:n.traffic.maxZoom,trafficMaxDetailLevel:n.traffic.maxDetailLevel,disableStyleFallback:!1,modelShowHideEventsSublayers:[],styleServer:"",fontUrl:"",modelUrl:"",iconUrl:"",keyUrl:"",disableLayerAnimation:!1,sharedModelsPath:""};let xl=fn;const _C="https://mapgl.2gis.com/api/js",Vs={minZoom:2,maxZoom:20},fC="tile{subdomain}-sdk.maps.2gis.com",f_="https://tile{subdomain}-sdk.maps.2gis.com/api/v3/ald",mC="https://s1.bss.2gis.com/bss/3",vC="https://disk.2gis.com/shared-models/",bl=()=>{let s="",e;for(let t=0;t<32;t++)e=Math.random()*16|0,t>4&&t<21&&!(t%4)&&(s+="-"),s+=(t===12?4:t===16?e&3|8:e).toString(16);return s},gC=2;function pC(s){const e=[gC,s instanceof WebGLRenderingContext?1:2,s.getParameter(s.ALIASED_LINE_WIDTH_RANGE),s.getParameter(s.ALIASED_POINT_SIZE_RANGE),s.getParameter(s.COMPRESSED_TEXTURE_FORMATS),s.getParameter(s.MAX_COMBINED_TEXTURE_IMAGE_UNITS),s.getParameter(s.MAX_CUBE_MAP_TEXTURE_SIZE),s.getParameter(s.MAX_FRAGMENT_UNIFORM_VECTORS),s.getParameter(s.MAX_RENDERBUFFER_SIZE),s.getParameter(s.MAX_TEXTURE_IMAGE_UNITS),s.getParameter(s.MAX_TEXTURE_SIZE),s.getParameter(s.MAX_VARYING_VECTORS),s.getParameter(s.MAX_VERTEX_ATTRIBS),s.getParameter(s.MAX_VERTEX_TEXTURE_IMAGE_UNITS),s.getParameter(s.MAX_VERTEX_UNIFORM_VECTORS),s.getParameter(s.MAX_VIEWPORT_DIMS),s.getParameter(s.PACK_ALIGNMENT),s.getParameter(s.SUBPIXEL_BITS),s.getParameter(s.UNPACK_ALIGNMENT),s.getParameter(s.VIEWPORT),s.getParameter(s.SHADING_LANGUAGE_VERSION),s.getParameter(s.VENDOR),s.getParameter(s.RENDERER)];s instanceof WebGLRenderingContext?e.push(...new Array(28).fill(-1)):e.push(s.getParameter(s.MAX_3D_TEXTURE_SIZE),s.getParameter(s.MAX_ARRAY_TEXTURE_LAYERS),s.getParameter(s.MAX_CLIENT_WAIT_TIMEOUT_WEBGL),s.getParameter(s.MAX_COLOR_ATTACHMENTS),s.getParameter(s.MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS),s.getParameter(s.MAX_COMBINED_UNIFORM_BLOCKS),s.getParameter(s.MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS),s.getParameter(s.MAX_DRAW_BUFFERS),s.getParameter(s.MAX_ELEMENT_INDEX),s.getParameter(s.MAX_ELEMENTS_INDICES),s.getParameter(s.MAX_ELEMENTS_VERTICES),s.getParameter(s.MAX_FRAGMENT_INPUT_COMPONENTS),s.getParameter(s.MAX_FRAGMENT_UNIFORM_BLOCKS),s.getParameter(s.MAX_FRAGMENT_UNIFORM_COMPONENTS),s.getParameter(s.MAX_PROGRAM_TEXEL_OFFSET),s.getParameter(s.MAX_SAMPLES),s.getParameter(s.MAX_SERVER_WAIT_TIMEOUT),s.getParameter(s.MAX_TEXTURE_LOD_BIAS),s.getParameter(s.MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS),s.getParameter(s.MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS),s.getParameter(s.MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS),s.getParameter(s.MAX_UNIFORM_BLOCK_SIZE),s.getParameter(s.MAX_UNIFORM_BUFFER_BINDINGS),s.getParameter(s.MAX_VARYING_COMPONENTS),s.getParameter(s.MAX_VERTEX_OUTPUT_COMPONENTS),s.getParameter(s.MAX_VERTEX_UNIFORM_BLOCKS),s.getParameter(s.MAX_VERTEX_UNIFORM_COMPONENTS),s.getParameter(s.MIN_PROGRAM_TEXEL_OFFSET));const t=s.getExtension("WEBGL_debug_renderer_info");t?e.push(s.getParameter(t.UNMASKED_VENDOR_WEBGL),s.getParameter(t.UNMASKED_RENDERER_WEBGL)):e.push("Unsupported","Unsupported");const i=s.getShaderPrecisionFormat(s.FRAGMENT_SHADER,s.LOW_FLOAT),r=s.getShaderPrecisionFormat(s.FRAGMENT_SHADER,s.MEDIUM_FLOAT),o=s.getShaderPrecisionFormat(s.FRAGMENT_SHADER,s.HIGH_FLOAT);return o&&r&&i?(e.push(`[${i.rangeMin},${i.rangeMax}](${i.precision})`),e.push(`[${r.rangeMin},${r.rangeMax}](${r.precision})`),e.push(`[${o.rangeMin},${o.rangeMax}](${o.precision})`)):e.push(new Array(3).fill("Unsupported")),e.push(window.devicePixelRatio),e}function xC(s){const e={};for(const[t,i]of Object.entries(s)){if(n.isTypedArray(i)){e[t]=Array.from(i);continue}e[t]=i}return e}function bC(s){var o,a;const e={1:["stateSetVersion","webGlVersion","ALIASED_LINE_WIDTH_RANGE","ALIASED_POINT_SIZE_RANGE","COMPRESSED_TEXTURE_FORMATS","MAX_COMBINED_TEXTURE_IMAGE_UNITS","MAX_CUBE_MAP_TEXTURE_SIZE","MAX_FRAGMENT_UNIFORM_VECTORS","MAX_RENDERBUFFER_SIZE","MAX_TEXTURE_IMAGE_UNITS","MAX_TEXTURE_SIZE","MAX_VARYING_VECTORS","MAX_VERTEX_ATTRIBS","MAX_VERTEX_TEXTURE_IMAGE_UNITS","MAX_VERTEX_UNIFORM_VECTORS","MAX_VIEWPORT_DIMS","PACK_ALIGNMENT","SUBPIXEL_BITS","UNPACK_ALIGNMENT","VIEWPORT","SHADING_LANGUAGE_VERSION","VENDOR","RENDERER","MAX_3D_TEXTURE_SIZE","MAX_ARRAY_TEXTURE_LAYERS","MAX_CLIENT_WAIT_TIMEOUT_WEBGL","MAX_COLOR_ATTACHMENTS","MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS","MAX_COMBINED_UNIFORM_BLOCKS","MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS","MAX_DRAW_BUFFERS","MAX_ELEMENT_INDEX","MAX_ELEMENTS_INDICES","MAX_ELEMENTS_VERTICES","MAX_FRAGMENT_INPUT_COMPONENTS","MAX_FRAGMENT_UNIFORM_BLOCKS","MAX_FRAGMENT_UNIFORM_COMPONENTS","MAX_PROGRAM_TEXEL_OFFSET","MAX_SAMPLES","MAX_SERVER_WAIT_TIMEOUT","MAX_TEXTURE_LOD_BIAS","MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS","MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS","MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS","MAX_UNIFORM_BLOCK_SIZE","MAX_UNIFORM_BUFFER_BINDINGS","MAX_VARYING_COMPONENTS","MAX_VERTEX_OUTPUT_COMPONENTS","MAX_VERTEX_UNIFORM_BLOCKS","MAX_VERTEX_UNIFORM_COMPONENTS","MIN_PROGRAM_TEXEL_OFFSET"]};e[2]=[...e[1],"UNMASKED_VENDOR_WEBGL","UNMASKED_RENDERER_WEBGL","precisionLow","precisionMedium","precisionHigh","devicePixelRatio"];const t=s[0],i=(o=e[t])!=null?o:{},r={};for(let l=0;l<s.length;l++)r[(a=i[l])!=null?a:l]=s[l];return r}const SC=/(android|bb\d+|meego).+mobile|armv7l|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|redmi|series[46]0|samsungbrowser.*mobile|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i,yC=/CrOS/,TC=/android|ipad|playbook|silk/i,EC=()=>{const s=typeof navigator!="undefined"?navigator.userAgent:"";if(!s)return!1;const e=SC.test(s)&&!yC.test(s),t=TC.test(s),i=navigator.maxTouchPoints>1&&s.includes("Macintosh")&&s.includes("Safari");return e||t||i},Zs=5e3,CC=64,IC=16;class PC{constructor(e,t){var i;this.queue=[],this.commPoiMsgOrderNumber=0,this.utcOffset=LC(),this.unsentMessages=[],this.isMetricsFailed=!1,this.webglStatsValues=[],this.onCommPoiShowEvent=({commPois:r})=>{const o=Date.now(),{tileKey:a,sessionId:l}=this.map.state;for(const c of r){const d=AC(c,o,this.commPoiMsgOrderNumber++,a,this.utcOffset,l);d&&this.queue.push(d)}this.timer||(this.timer=window.setTimeout(this.sendMessages,Zs))},this.onContextLostEvent=()=>q(this,null,function*(){const r=Date.now(),o={cpu:0,gpu:0},{graphicsPreset:a,graphicsPresetSource:l}=this.map.state.metrics,d=I({start:0,fail:!0,contextLost:!0},a!==void 0&&l?{graphicsPreset:a,graphicsPresetSource:l}:{}),u=yield this.createMetricMessage(r,d,o);this.queue.push(u),this.timer||(this.timer=window.setTimeout(this.sendMessages,Zs))}),this.onMetricsEvent=r=>q(this,null,function*(){this.isMetricsFailed&&(r.fail=!0);const o=I({},r),a=Date.now(),l=yield this.getMetricsMessage(o,a);this.queue.push(l),this.timer||(this.timer=window.setTimeout(this.sendMessages,Zs))}),this.onSendFail=r=>{this.unsentMessages.push(...r),this.timer||(this.timer=window.setTimeout(this.sendMessages,Zs))},this.sendMessages=()=>{this.timer=void 0;const r=[...this.unsentMessages,...this.queue];this.queue=[],this.unsentMessages=[],r.length&&fetch(this.bssUrl,{method:"POST",body:JSON.stringify(r),headers:{"Content-Type":"application/json"}}).then(o=>{o.ok||this.onSendFail(r)},()=>this.onSendFail(r))},this.markMetricsAsFailed=()=>{this.isMetricsFailed=!0},this.map=e,this.bssUrl=(i=t.bssUrl)!=null?i:mC,this.webglStatsValues=pC(this.map.getWebGLContext()),t.disableBssStatisticsForCommPoi||e.on("commpoishow",this.onCommPoiShowEvent),e.on("metrics",this.onMetricsEvent),this.map.on("error",r=>{r.type==="webglcontextlost"&&this.onContextLostEvent()}),window.addEventListener("blur",this.markMetricsAsFailed,{once:!0}),window.addEventListener("focus",this.markMetricsAsFailed,{once:!0}),document.addEventListener("visibilitychange",this.markMetricsAsFailed,{once:!0}),(!document.hasFocus()||document.hidden)&&this.markMetricsAsFailed()}destroy(){clearTimeout(this.timer),this.queue=[],this.timer=void 0,this.map.off("commpoishow",this.onCommPoiShowEvent),window.removeEventListener("blur",this.markMetricsAsFailed),window.removeEventListener("focus",this.markMetricsAsFailed),document.removeEventListener("visibilitychange",this.markMetricsAsFailed)}getCommonStats(){return q(this,null,function*(){const e=bC(this.webglStatsValues),t=xC(e),i=this.map.performanceChecker.getFpsStats(),r=Array.from(this.map.state.center),o=this.map.state.zoom,a=this.map.state.rotation,l=this.map.state.pitch,c=this.map.state.demMode,d=yield um();return{webglStats:t,fps:i,center:r,zoom:o,rotation:a,pitch:l,reliefEnabled:c,webGpuSupported:d}})}createMetricMessage(e,t,i){return q(this,null,function*(){const r=yield this.getCommonStats(),o=V(I(I({},t),r),{memory:i});return"graphicsPresetSource"in o&&!o.graphicsPresetSource&&delete o.graphicsPresetSource,{type:411,eventType:"mapglCounter",eventId:bl(),timestamp:e,payload:{mapGlMapMetrics:o,mapGlHostAppParams:RC(this.map.state.bssHostAppParams)},common:{formatVersion:3,appVersion:n.limitString(Pl,CC),product:44,deviceType:EC()?"mobile":"desktop",key:this.map.state.tileKey,styleId:this.map.state.styleId}}})}getMetricsMessage(e,t){return q(this,null,function*(){const i=yield this.map.performanceChecker.getMemoryStats(),r=yield this.createMetricMessage(t,e,i);return r.payload.mapGlMapMetrics.fail&&!r.payload.mapGlMapMetrics.fps.isStatic&&e.firstcontent!==void 0&&(r.payload.mapGlMapMetrics.fail=!1),r})}}function AC(s,e,t,i,r,o){const a={adsHighlight:!0,entity:{id:s.id,type:"branch"}};s.adsPriority!==void 0&&(a.adsPriority=s.adsPriority);const l={type:302,eventType:"view",eventId:bl(),eventOrdinal:t,uiElement:{name:"POI",ownerName:"map"},timestamp:e,utcOffset:r,payload:{POI:a},common:{formatVersion:3,appVersion:n.limitString(Pl,IC),product:44,apikey:i}};return o&&(l.common.sessionId=o),!i||i===n.DEFAULT_EMPTY_KEY?null:l}function LC(){const e=new Date().getTimezoneOffset(),t=e>0?"-":"+",i=`${Math.floor(Math.abs(e)/60)}`,r=`${Math.abs(e)%60}`;return t+(i.length>1?i:"0"+i)+":"+(r.length>1?r:"0"+r)}function RC(s){if(s){const e=I({},s);return"userId"in e&&typeof e.userId!="string"&&delete e.userId,"sessionId"in e&&typeof e.sessionId!="string"&&delete e.sessionId,"product"in e&&typeof e.product!="number"&&delete e.product,e}return s}const m_=s=>typeof s=="number"&&!isNaN(s)&&s!==Number.NEGATIVE_INFINITY&&s!==Number.POSITIVE_INFINITY;function FC(s){return Array.isArray(s)&&m_(s[0])&&m_(s[1])}var Sl=(s=>(s[s.IgnoreCall=0]="IgnoreCall",s[s.UseDefault=1]="UseDefault",s))(Sl||{});const DC={0:"Method call will be ignored.",1:"Method call will use default value."};class zC{constructor(e){this.options=e}isValidGeoPoint(e,t){return this.processValidationResult(e,FC(e),"Invalid GeoPoint",t)}processValidationResult(e,t,i,r){return!t&&this.options.reportToConsole&&console.warn(`${i}: ${JSON.stringify(e)}
${DC[r]}`),t}}const v_=new zC({reportToConsole:!0}),g_=["zoom","rotation","pitch","center"],BC=150,OC=["static","immersive_roads"];class yl extends n.Evented{constructor(e,t){var o;super(),this.styleRequestGeneration=0,this.destroyed=!1;const i=this.core=new xl(e,t,this);this.state=i.state,this.modules=i.modules,this.performanceChecker=i.modules.performanceChecker,this.values={isMoveChanging:!1,isIdle:!1},g_.forEach(a=>{this.cloneFromStateToValues(a,`${a}1`),this.cloneFromStateToValues(a,`${a}2`),this.cloneFromStateToValues(a,`${a}End1`),this.cloneFromStateToValues(a,`${a}End2`),this.values[`${a}EndTime`]=0,this.values[`is${a}Changing`]=!1}),this.cloneFromStateToValues("size","size"),this.performanceChecker.on("performancecaveat",()=>{this.emit("performancecaveat")});const r=a=>{if(a instanceof Error)throw a};this.setStyle((o=t==null?void 0:t.style)!=null?o:n.DEFAULT_MAPGL_STYLE,t==null?void 0:t.styleOptions).catch(r),this.setLang(this.state.lang),t&&!t.disableBssStatistics&&(this._bssDispatcher=new PC(this,{disableBssStatisticsForCommPoi:!!t.disableBssStatisticsForCommPoi,bssUrl:t.bssUrl})),this.state.metrics.init=performance.now()-this.state.metrics.start,this.updateDataToggle()}setCenter(e,t){if(!v_.isValidGeoPoint(e,Sl.IgnoreCall))return this;this.state.userHasInteracted=!1;let i=n.Mercator.fromGeo(e);return!this.state.loopWorld&&!this.state.styleState.globeEnabled&&(i=n.normalizeMapPoint(i)),hi(this.state,i,t),this}setZoom(e,t){return n.isBetween(e,Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER)?(this.state.zoomTypePreserving="zoom",this.state.userHasInteracted=!1,Qt(this.state,e,t),this.state.shouldIsReadyWaitForUpdates=!0,this):this}setStyleZoom(e,t){if(!n.isBetween(e,Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER))return this;const i=n.getZoomFromStyleZoom(e,this.state.center);return this.state.zoomTypePreserving="styleZoom",this.state.userHasInteracted=!1,Qt(this.state,i,t),this}setMinZoom(e,t){return this.state.minZoom=e,this.setZoom(this.state.zoom,t),this}setMaxZoom(e,t){return this.state.maxZoom=e,this.setZoom(this.state.zoom,t),this}setRotation(e,t){return n.isBetween(e,Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER)?(this.state.userHasInteracted=!1,Xi(this.state,n.degToRad(e),t),this):this}setPitch(e,t){return n.isBetween(e,Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER)?(this.state.userHasInteracted=!1,gn(this.state,n.degToRad(e),t),this):this}setAnimationTerrain(e){this.modules.demManager.setAnimationTerrain(e)}getAnimationTerrainStatus(){return this.modules.demManager.getAnimationTerrainStatus()}setMinPitch(e,t){return this.state.minPitch=n.degToRad(e),this.setPitch(n.radToDeg(this.state.pitch),t),this}setMaxPitch(e,t){return this.state.maxPitch=n.degToRad(e),this.setPitch(n.radToDeg(this.state.pitch),t),this}setLowZoomMaxPitch(e,t){return this.state.lowZoomMaxPitch=n.degToRad(e),this.setPitch(n.radToDeg(this.state.pitch),t),this}setViewport(e,t){return this.state.userHasInteracted=!1,Bl(this.state,this.modules.layout.rootContainer,this.modules.renderer,e,t),this}setMaxBounds(e){return this.state.maxBounds=n.fromGeo(e),this}setPadding(e,t){var r,o,a,l;const i={top:(r=e.top)!=null?r:0,left:(o=e.left)!=null?o:0,right:(a=e.right)!=null?a:0,bottom:(l=e.bottom)!=null?l:0};return this.state.userHasInteracted=!1,wl(this.state,this.modules.renderer,i,t),this}setTime(e){this.patchStyleState({_customUserTimeOffset:e?e-this.state.time:0}),this.modules.animationManager.clearAllTickers(),this.modules.renderer.addRerenderEvent()}getTime(e){return e?this.state.time-new Date().getTimezoneOffset()*6e4+ +(this.state.styleState._customUserTimeOffset||0):this.state.time+ +(this.state.styleState._customUserTimeOffset||0)}getPadding(){return this.state.padding}getCenter(){const e=n.normalizeMapPoint(this.state.center);return n.Mercator.toGeo(e).slice(0,2)}getZoom(){return this.state.zoom}getStyleZoom(){return this.state.styleZoom}getMinZoom(){return this.state.minZoom}getMaxZoom(){return this.state.maxZoom}getRotation(){return n.radToDeg(this.state.rotation)}getPitch(){return n.radToDeg(this.state.pitch)}getViewport(){return this.state.viewport}getSize(){return[this.state.size[0],this.state.size[1]]}getBounds(e){let t=this.modules.camera;if(e!=null&&e.skipPadding)t=new n.Camera(V(I({},this.state),{padding:{left:0,right:0,top:0,bottom:0}}));else if(e!=null&&e.sizeExtension){const r=e.sizeExtension,[o,a]=this.state.size,l=[o+r,a+r];t=new n.Camera(V(I({},this.state),{size:l}))}t.update();const i=n.tetragonBounds(t.getViewportVertices());return{southWest:n.Mercator.toGeo(i.min),northEast:n.Mercator.toGeo(i.max)}}getDefaultSource(){return this.modules.defaultSource}hideBuildingsById(e,t=n.DEFAULT_ID_SCOPE){if(!e.length)return;const{identifier:i}=this.modules;i.getIdScope(t).hide(e),this.modules.renderer.addRerenderEvent({type:"triggerRerender"})}showHiddenBuildingsById(e,t=n.DEFAULT_ID_SCOPE){if(!e.length)return;const{identifier:i}=this.modules;i.getIdScope(t).show(e),this.modules.renderer.addRerenderEvent({type:"triggerRerender"})}getWebGLContext(){return this.modules.renderer.getRenderingContext()}getCanvas(){return this.modules.layout.canvas}showTraffic(){this.modules.trafficTileLayer.show()}hideTraffic(){this.modules.trafficTileLayer.hide()}isTrafficOn(){return this.modules.trafficTileLayer.isEnabled()}setPersonalPoi(e){this.modules.personalPoiManager.setPersonalPoi(e)}setSelectedIds(e=[],t=n.DEFAULT_ID_SCOPE){const{identifier:i}=this.modules,r=i.getIdScope(t);return r==null||r.select(e),this.modules.identifier.queryFillCache(),this}project(e){return this.modules.camera.project(e)}unproject(e){return this.modules.camera.unproject(e)}getCameraProjectionMatrix(){return this.modules.camera.projectionMatrix}getCameraViewMatrix(){return this.modules.camera.viewMatrix}getCameraViewProjectionMatrix(){return this.modules.camera.viewProjectionMatrix}invalidateSize(){this.state.userHasInteracted=!1;const e=window.devicePixelRatio,{viewport:t}=this.state,{clientWidth:i,clientHeight:r}=this.modules.layout.rootContainer;return this.state.size=[Math.max(1,i-t.left-t.right),Math.max(1,r-t.top-t.bottom)],this.modules.renderer.setPixelRatio(e),this.modules.renderer.setSize(i,r),this.modules.renderer.addRerenderEvent(),this.modules.sunda.resize(i,r,e,t),this}destroy(){var e,t;this.destroyed=!0,this.styleRequestGeneration++,(e=this.stylePreparationController)==null||e.abort(),this.core.destroy(),(t=this._bssDispatcher)==null||t.destroy()}refresh(){return this.modules.renderer.addRerenderEvent(),this.state.needLabeling=!0,this.modules.identifier.resetCache(),this}changeFloorNumber(e,t){return this.modules.floorManager.changeFloorNumber(e,t),this.state.shouldIsReadyWaitForUpdates=!0,this}hasLayer(e){return this.modules.styleManager.hasLayer(e)}addLayer(e,t){return e.type==="custom"&&(this.state.aaMode=void 0),this.modules.styleManager.addLayer(e,t),this.core.activateStyleUpdating(),this}removeLayer(e){return this.modules.styleManager.removeLayer(e),this.core.activateStyleUpdating(),this}hideLayers(e){const{id:t,type:i}=e,r=o=>(this.modules.styleManager.hideLayers(o),this.modules.renderer.addRerenderEvent(),this);if(n.isStyleLayerType(i)&&n.isStyleLayerHidable(i)){const o=n.convertStyleLayerTypeToHandy(i);if(o)return r({type:o})}else if(t)return r({id:t});return console.warn(`[#hideLayers] The layer with type "${i}" can't be hidden.`),this}showLayers(e){const{id:t,type:i}=e,r=o=>(this.modules.styleManager.showLayers(o),this.modules.renderer.addRerenderEvent(),this);if(n.isStyleLayerType(i)&&n.isStyleLayerHidable(i)){const o=n.convertStyleLayerTypeToHandy(i);if(o)return r({type:o})}else if(t)return r({id:t});return console.warn(`[#showLayers] The layer with type "${i}" can't be shown.`),this}setStyle(e,t){return q(this,null,function*(){var l;const i=++this.styleRequestGeneration;(l=this.stylePreparationController)==null||l.abort();let r,o=!1,a=!1;try{return o=typeof e=="string"&&n.isStyleId(e)&&!this.core.state.disableStyleFallback&&Number.isNaN(this.state.handyStyleId)&&e!==n.DEFAULT_MAPGL_STYLE,r=yield this.setPreparedStyle(e,t,i),i!==this.styleRequestGeneration||this.destroyed?Promise.reject("Cancel setting obsolete style"):(a=!0,this.performanceChecker.startCollecting(),this.emit("styleload",{style:r}),r)}catch(c){if(i!==this.styleRequestGeneration||this.destroyed)return Promise.reject("Cancel setting obsolete style");if(a)throw c;if(c instanceof Error&&this.emit("error",{type:"styleloaderror",style:e}),o&&!this.currentPendingStyle)return this.setStyle(n.DEFAULT_MAPGL_STYLE);throw c}})}addIcon(e,t){return e?(this.modules.styleManager.addIcon(e,t)&&this.core.activateStyleUpdating(),this):(console.error("The icon name is empty."),this)}removeIcon(e){return e?(this.modules.styleManager.removeIcon(e)&&this.core.activateStyleUpdating(),this):this}addModel(e,t){return e?(this.modules.styleManager.addModel(e,t)&&this.core.activateStyleUpdating(),this):(console.error("The model name is empty."),this)}waitForGpuToFinishDrawing(){return this.modules.identifier.readIdentifyPixels(!0),this}setLang(e){const t=n.isRtlPluginRequired(this.state.rtlPlugin.scenario,e);this.state.rtlPlugin.loadFailed&&t||(this.state.lang=e,this.state.styleState.lang=e,this.state.rtlPlugin.loadFailed||n.setupMapboxRtlAdapterIfNeeded(this.state.rtlPlugin,this.modules,e).catch(i=>{throw this.state.rtlPlugin.loadFailed=!0,this.setLang(n.defaultLang),i}),this.modules.tileManager.redraw())}showLabelsDebug(e){this.modules.labelsDebug.show(e)}hideLabelsDebug(){this.modules.labelsDebug.hide()}getContainer(){return this.modules.layout.mapContainer}getIconUrl(e){var r;const t=this.modules.styleManager.getStyle(this.state.handyStyleId);if(!t)return;const i=(r=t.icons[e])==null?void 0:r.url;if(i)return n.getUrlForIconMapIcon(i,t,n.getSubdomainFromString(this.modules.map.state.subdomains,i))}getExternalContainer(){return this.modules.layout.externalContainer}fitBounds({northEast:e,southWest:t},i){const r=I({top:0,left:0,right:0,bottom:0},i!=null&&i.padding?i.padding:{}),o=this.getViewport(),a=this.getPadding(),l=i!=null&&i.skipMapPadding?r:ff(a,r),c=this.getSize(),d=i!=null&&i.considerRotation?this.getRotation():0;if(c[0]-l.left-l.right<=0||c[1]-l.top-l.bottom<=0)return console.warn("Map cannot fit within canvas with the given bounds and padding."),this;i!=null&&i.considerRotation||Xi(this.state,d,{animate:!1});const u=Jn([[t[0],e[1]],e,[e[0],t[1]],t],d,[c[0]-l.left-l.right,c[1]-l.top-l.bottom]);if(!u)return console.warn("Map cannot fit within canvas with the given bounds and padding."),this;const h=[(c[0]-l.left-l.right)/2+l.left+o.left,(c[1]-l.top-l.bottom)/2+l.top+o.top];let _;(i==null?void 0:i.maxZoom)!==void 0?_=Math.min(u.zoom,i==null?void 0:i.maxZoom):_=u.zoom,_=n.clamp(_,this.state.minZoom,this.state.maxZoom);const m=new n.Camera({zoom:_,rotation:this.state.rotation,size:this.state.size,padding:this.state.padding,viewport:this.state.viewport,pitch:0,center:u.center,cameraConfig:this.state.cameraConfig,globeMode:this.state.globeMode,styleState:this.state.styleState}).flat.unproject(h),v=[0,0];n.sub(v,u.center,m);const g=[0,0,0];n.add(g,u.center,v);const p=i!=null&&i.animation?i.animation:{};p.easing||(p.easing="easeOutCubic");const x=I({},p);return hi(this.state,g,p),Qt(this.state,_,x),gn(this.state,0,p),this}update(){const e=this.state,{time:t,userHasInteracted:i}=e,r=this.values,o={};g_.forEach(c=>{let d=e[c];c==="zoom"&&e.zoomTypePreserving==="styleZoom"&&(d=e.styleZoom),o[`${c}start`]=!r[`is${c}Changing`]&&!this.areEqual(d,r[`${c}1`])&&this.areEqual(r[`${c}1`],r[`${c}2`]),o[`${c}start`]&&(r[`is${c}Changing`]=!0),r[`is${c}Changing`]&&(o[c]=!this.areEqual(d,r[`${c}1`]),t-r[`${c}EndTime`]>BC&&(o[`${c}end`]=this.areEqual(d,r[`${c}End1`])&&!this.areEqual(r[`${c}End1`],r[`${c}End2`]),o[`${c}end`]&&(r[`is${c}Changing`]=!1),this.copyFromValuesToValues(`${c}End2`,`${c}End1`),this.copyFromStateToValues(d,`${c}End1`),r[`${c}EndTime`]=t)),this.copyFromValuesToValues(`${c}2`,`${c}1`),this.copyFromStateToValues(d,`${c}1`)}),o.resize=!this.areEqual(e.size,r.size),this.copyFromStateToValues(e.size,"size"),o.movestart=(o.zoomstart||o.rotationstart||o.centerstart||o.pitchstart)&&!r.isMoveChanging,o.movestart&&(r.isMoveChanging=!0),o.move=r.iszoomChanging||r.isrotationChanging||r.iscenterChanging||r.ispitchChanging,o.moveend=(o.zoomend||o.rotationend||o.centerend||o.pitchend)&&!o.move,o.moveend&&(r.isMoveChanging=!1);const a=r.isIdle,l=r.isReady;r.isIdle=this.isIdle(),r.isReady=this.isReady(),o.idle=!a&&r.isIdle,o.ready=!l&&r.isReady,e.metrics.ready===void 0&&this.isReadyForMetrics()&&(e.metrics.ready=performance.now()-e.metrics.start);for(const c in o){const d=c;o[d]&&this.emit(d,{isUser:i})}}isIdle(){return!this.values.isMoveChanging&&!this.currentPendingStyle&&this.core.isIdle()}isReady(){return!this.values.isMoveChanging&&!this.currentPendingStyle&&this.core.isReady()}isReadyForMetrics(){return!this.values.isMoveChanging&&!this.currentPendingStyle&&this.core.isReadyForMetrics()}setAutoHoverMode(e){this.modules.defaultSource.resetHoverId(),this.state.disableHoverStyles=!e}setForceInteractivity(e){this.state.forceInteractivity=e,this.modules.workers.setForceInteractivity(e),this.modules.tileManager.redraw()}setStyleState(e,t={source:"hostRuntime"}){const i=this.state.styleState.graphicsPreset,r=Xn(e.graphicsPreset)?e.graphicsPreset:hn[2],{_customUserTimeOffset:o}=this.state.styleState,a=()=>{this.state.styleState._customUserTimeOffset=o};if(this.state.graphicsPresetMode){const l=this.state.isDeprecatedSystem?"light":e.graphicsPreset;this.state.styleState=Ts(e,this.getGraphicsPresetFeatures(l))}else this.state.styleState=Ts(e);this.updateGraphicsPresetSelection(i,r,t),a(),this.updateDataToggle(),this.modules.renderer.addRerenderEvent()}getStyleState(){return I({},this.state.styleState)}patchStyleState(e,t={source:"hostRuntime"}){const i=this.state.styleState.graphicsPreset,r=e.graphicsPreset;if(this.state.graphicsPresetMode){const o=this.state.isDeprecatedSystem?"light":e.graphicsPreset;this.state.styleState=Oh(this.state.styleState,e,this.getGraphicsPresetFeatures(o))}else this.state.styleState=Oh(this.state.styleState,e);r!==void 0&&this.updateGraphicsPresetSelection(i,r,t),this.updateDataToggle(),this.modules.renderer.addRerenderEvent()}setOption(e,t){if(Ll.indexOf(e)===-1){console.error(`Can't change the "${e}" option.`);return}switch(e){case"loopWorld":{if(this.state.loopWorld===t)return;const i=t?n.worldLoopBounds:n.worldBounds,r=this.state.maxBounds;(n.exactEquals$1(r.min,n.worldLoopBounds.min)&&n.exactEquals$1(r.max,n.worldLoopBounds.max)||n.exactEquals$1(r.min,n.worldBounds.min)&&n.exactEquals$1(r.max,n.worldBounds.max))&&(this.state.maxBounds=i),this.modules.renderer.addRerenderEvent();break}case"disableHidingPois":{if(this.state.disableHidingPois===t)return;this.modules.renderer.addRerenderEvent();break}}this.state[e]=t}getOption(e){if(Ll.indexOf(e)===-1){console.error(`Can't get the value of the "${e}" option.`);return}return this.state[e]}getGroundPoint(e){return this.modules.demManager.getGroundPoint(e)}getElevationAtTier(e,t,i){if(t!==0&&!this.state.immersiveLevel.tiers)return;const r=this.modules.elevationIndex.getElevationAtTier(n.Mercator.fromGeo(e),t,i);if(!r)return;const o=n.Mercator.scaleFactor(e[1]),a={relativeZ:r.relativeZ/o};return r.absoluteZ!==void 0&&(a.absoluteZ=r.absoluteZ/o),r.surfaceTangents&&(a.surfaceTangents=r.surfaceTangents),a}getElevationRevision(){return this.modules.elevationIndex.getRevision()}setAllowedFloorIds(e){this.modules.floorManager.setAllowedFloorIds(e)}getMapRenderStat(){var f,m,v;this.modules.renderer.addRerenderEvent();const{drawCount:e,vertexCount:t,triangleCount:i}=this.state.stats,o=598044/(this.state.size[0]*this.state.size[1]/window.devicePixelRatio),a=[{level:0,draws:[0,500],vertcles:[0,1e6],triangles:[0,333e3]},{level:1,draws:[501,1e3],vertcles:[1000001,2e6],triangles:[3330001,666e3]},{level:2,draws:[1001,1500],vertcles:[2000001,3e6],triangles:[666001,999e3]},{level:3,draws:[1501,2500],vertcles:[3000001,6e6],triangles:[999001,2e6]},{level:4,draws:[2501,3500],vertcles:[6000001,12e6],triangles:[2000001,4e6]},{level:5,draws:[3501,1/0],vertcles:[12000001,1/0],triangles:[4000001,1/0]}],l=e*o,c=t*o,d=i*o,u=((f=a.find(g=>g.draws[0]<=l&&g.draws[1]>=l))==null?void 0:f.level)||0,h=((m=a.find(g=>g.vertcles[0]<=c&&g.vertcles[1]>=c))==null?void 0:m.level)||0,_=((v=a.find(g=>g.triangles[0]<=d&&g.triangles[1]>=d))==null?void 0:v.level)||0;return{drawCount:e,vertexCount:t,drawsLevel:u,vertexLevel:h,triangleCount:i,triangleLevel:_,level:Math.ceil((u+h)/2)}}getDataToggle(){return this.modules.defaultSource.getDataType()}setLightingStyle(e){const t=this.modules.styleManager.getStyle(this.state.handyStyleId);t&&(t.light=n.makeHandyLightStyle(e,t.dem,t.globals),t.light.lightingModesResolved={},this.state.needRerender=!0)}getFeatureFlag(e,t){return!this.modules||(t=t!=null?t:this.core.state.styleState.graphicsPreset,!t)?!1:this.modules.styleManager.getFeatureFlag(e,t)}getCurrentGraphicsPreset(){if(!this.state.graphicsPresetMode)throw new Error("You can get current graphics preset only when graphicsPresetMode is set.");return{name:this.state.styleState.graphicsPreset,preset:this.getGraphicsPresetFeatures()}}getGraphicsPresetFeatures(e){return cC.reduce((t,i)=>(t[i]=this.getFeatureFlag(i,e),t),{})}updateGraphicsPresetSelection(e,t,i){const r=this.state.styleState.graphicsPreset;if(!(!i.recordUnchanged&&e===r)){if(!Xn(t)||!Xn(r)){this.state.graphicsPresetSelection=null;return}this.state.graphicsPresetSelection={name:r,source:h_(i.source,t,r,this.state.isDeprecatedSystem)}}}setPreparedStyle(e,t,i){return q(this,null,function*(){if(this.destroyed)throw new Error("Map destroyed");const r=new AbortController;this.stylePreparationController=r,this.currentPendingStyle=typeof e=="string"?e:`__prepared_${i}`;const o=this.modules.workers.stylePreparation;r.signal.addEventListener("abort",()=>o.abort(i),{once:!0});try{let a;if(typeof e=="string"&&n.isStyleId(e)){const u=n.applyDefaults(t||{},{rootUrl:this.state.styleServer,stylePath:n.styles.path,iconsPath:this.state.iconUrl,fontsPath:this.state.fontUrl,modelsPath:this.state.modelUrl}),h=new URL(n.template(n.getStyleUrl(u),{id:e}));h.searchParams.append("key",this.state.tileKey),a={kind:"id",url:h.toString(),options:u,tileKey:this.state.tileKey}}else if(typeof e=="string"){const u=n.applyDefaults(t||{},{rootUrl:e,stylePath:"style.json",iconsPath:"",fontsPath:"",modelsPath:""});a={kind:"url",url:n.getStyleUrl(u),options:u,tileKey:this.state.tileKey}}else{const u=n.applyDefaults(t||{},{rootUrl:`${window.location.protocol}//${window.location.host}`,stylePath:"",iconsPath:"",fontsPath:"",modelsPath:""});a={kind:"object",style:e?JSON.parse(JSON.stringify(e)):void 0,options:u,tileKey:this.state.tileKey}}const l=this.modules.styleManager.getNextStyleId(),c=yield o.prepare(a,l,i,r.signal);if(yield o.commit(i,r.signal),i!==this.styleRequestGeneration||this.destroyed)throw new Error("Obsolete style");this.stylePreparationController=void 0;const d=performance.now();return this.modules.styleManager.installPreparedStyle(c,()=>!this.destroyed),this.state.handyStyleId=c.id,this.state.styleId=typeof e=="string"?e:`__prepared_${i}`,this.patchStyleState({}),this.core.activateStyleUpdating(),n.measureStyle(o.measurements,"commit",performance.now()-d),o.release(i),e}catch(a){if(o.abort(i),r.signal.aborted||i!==this.styleRequestGeneration||this.destroyed)return Promise.reject("Cancel preparing obsolete style");throw a}finally{i===this.styleRequestGeneration&&(this.currentPendingStyle=void 0,this.stylePreparationController=void 0)}})}copyFromStateToValues(e,t){$n(e)?n.copy$3(this.values[t],e):this.values[t]=e}cloneFromStateToValues(e,t){const i=this.state[e];$n(i)?this.values[t]=n.clone(i):this.values[t]=i}copyFromValuesToValues(e,t){const i=this.values[t];$n(i)?n.copy$3(this.values[e],i):this.values[e]=i}areEqual(e,t){return $n(e)&&$n(t)?n.exactEquals$1(e,t):e===t}updateDataToggle(){this.modules.defaultSource.setDataType(this.state.styleState.immersiveRoadsOn?OC:void 0)}}function $n(s){return s.length!==void 0}const p_={extraReplicas:[NaN,NaN],tile:[0,0,0,0],mapPoint:[0,0],geoPoint:[0,0]};class x_ extends ht{constructor(e,t,i){super(e,t),this.length=1,this.isGeometryOutOfMainReplica=!1,this.wasGlobeLineHidden=!1,this.tileCache={parts:void 0,zoom:NaN,length:NaN,points:void 0,objectsByPart:new Map,generatedPartsRef:void 0,globeEnabled:void 0},this.removed=!1,this.baseOptions=t,this.dynamicStyleId=this.modules.dynamicStyle.getStyle().id,this.geoPoints=t.coordinates.filter((r,o,a)=>o===0||!n.exactEquals$2(a[o],a[o-1])),this.points=this.geoPoints.map(r=>n.Mercator.fromGeo(r)),this.isGeometryOutOfMainReplica=this.points.some(r=>r[0]>n.HALF_WORLD_SIZE||r[0]<-n.HALF_WORLD_SIZE),this.distances=[],this.initDistances(),this.stateDiffer=new n.Differ([{path:"center",type:"vec2"},{path:"zoom",type:"number"},{path:"size",type:"vec2"},{path:"rotation",type:"number"},{path:"pitch",type:"number"},{path:"padding",type:"padding"},{path:"demMode",type:"boolean"}]),this.debouncedGenerate=n.debounce(()=>{this.generate()},200),this.tileAttrs=n.optionsToTileAttrs(V(I({beginningIsCut:0,endingIsCut:0},i),{db_tiers:t.tiers}))}get tileProps(){return n.fixedMetatile.tileProps}get globeEnabled(){return!!this.mapState.styleState.globeEnabled&&!this.modules.map.getFeatureFlag("globeOff")}update(){if(!this.removed){if(super.update(),this.mapState.globeMode&&!this.hasVisibleTileParts()){this.wasGlobeLineHidden||(this.cleanTileObjects(!1),this.wasGlobeLineHidden=!0);return}this.wasGlobeLineHidden||this.tileCache.globeEnabled!==this.globeEnabled?(this.wasGlobeLineHidden=!1,this.stateDiffer.check(this.mapState),this.generate()):this.stateDiffer.check(this.mapState)&&this.debouncedGenerate(),this.animationTickerName&&this.updateShowTicker(this.animationTickerName)}}isOutOfMainReplica(){return this.isGeometryOutOfMainReplica}remove(){this.removed||(this.removed=!0,this.animationTickerName&&(n.stop(this.animationTickerName,this.mapState),this.animationTickerName=void 0),this.interactive&&this.modules.identifier.resetCache(),this.destroyCachedObjects(new Set(this.tileObjects)),this.removeStyleLayers(),super.destroy())}initDistances(){let e=0;this.distances.push(e);for(let t=1;t<this.geoPoints.length;t++)e+=n.geoPointsDistance(this.geoPoints[t-1],this.geoPoints[t]),this.distances.push(e)}initShowAnimation(e,t){const i=this.baseOptions;i.showAnimation&&i.showAnimation.animate!==!1&&this.points.length>1&&(this.distances.length||this.initDistances(),this.animationTickerName=`${e}-${this.uniqId}`,t&&this.startShowTicker(this.animationTickerName,t))}startShowTicker(e,t){var c,d,u;const o=this.baseOptions,a=((c=o.showAnimation)==null?void 0:c.easing)!==void 0?o.showAnimation.easing:"linear",l=((d=o.showAnimation)==null?void 0:d.duration)!==void 0?o.showAnimation.duration:250;n.start(e,{easing:a,animationGroup:(u=o.showAnimation)==null?void 0:u.animationGroup},this.mapState,0,1,l,1,{layerId:t,styleId:this.dynamicStyleId}),this.length=0}updateShowTicker(e){const t=this.baseOptions;n.update(e,{step:(i,r)=>{var a,l,c,d;const o=n.affineStep(((l=(a=t.showAnimation)==null?void 0:a.durationRange)==null?void 0:l.start)||0,((d=(c=t.showAnimation)==null?void 0:c.durationRange)==null?void 0:d.end)||1,r);o!==this.length&&(this.length=o,this.generate())}},this.mapState)}splitIntoTileParts(e){const t=Math.min(Math.floor(this.modules.map.getZoom()),e),i=this.tileCache;if(i.parts!==void 0&&i.zoom===t&&i.length===this.length&&i.points===this.points)return i.parts;const r=n.tileZoomToSize(t),o=n.splitPolylineByLength(this.points,this.distances,this.length),a=n.splitPolylineByMaxSize(o,r),l=n.create$1(),c=n.create(),d=[];for(const u of a){n.reset(c);for(let v=0;v<u.length;v++)n.expandByPoint(c,u[v]);n.center(l,c);const h=n.getTileCoordsByCenterAndZoom(l,t),_=n.createTileInfo(h),f=[],m=[];for(let v=0;v<u.length;v++)n.mapPointToTilePoint(l,u[v],_),f[v]=l[0],m[v]=l[1];d.push({vertices:{x:f,y:m},tileInfo:_,mapPoints:u})}return this.tileCache.parts=d,this.tileCache.zoom=t,this.tileCache.length=this.length,this.tileCache.points=this.points,d}cleanTileObjects(e){const{tileManager:t}=this.modules;this.tileObjects.forEach(i=>{i.clean(this.mapState),t.removeObject(i,e)}),this.tileObjects=[],this.destroyCachedObjects()}tryVisibilityOnlyUpdate(e,t){if(this.tileCache.globeEnabled!==this.globeEnabled||e!==this.tileCache.generatedPartsRef||this.tileCache.objectsByPart.size===0)return!1;const{tileManager:i}=this.modules;for(const r of this.tileObjects)i.removeObject(r,t);this.tileObjects=[],this.identifyIds=[];for(let r=0;r<e.length;r++){const{tileInfo:o}=e[r];if(this.isTileReplicaVisible(o.coords)){const a=this.tileCache.objectsByPart.get(r);if(!a){for(const l of this.tileObjects)i.removeObject(l,t);return this.tileObjects=[],this.identifyIds=[],!1}i.addObject(a.tileObject,t),this.tileObjects.push(a.tileObject),this.interactive&&a.identifyIds&&this.identifyIds.push(a.identifyIds)}}return this.interactive&&this.modules.identifier.resetCache(),t||this.modules.renderer.addRerenderEvent(),!0}makeCtx(e){const t=n.makeGeneratorContext(this.mapState.styleState,n.emptySourceAttrs,n.fixedTileProps,this.tileAttrs,n.emptyFeatureAttrs,!0,this.interactive?"0":"",e);return t.globeOff=this.modules.map.getFeatureFlag("globeOff"),t}collectTileObject(e,t,i){const{collector:r,tileManager:o}=this.modules,a=r.getAccumulatedData(),l=new n.TileObject("dynamicObject",a.data,this.modules,this.mapState,e.coords,this);o.addObject(l,t),this.tileObjects.push(l),i!==void 0&&this.tileCache.objectsByPart.set(i,{tileObject:l,identifyIds:this.interactive?a.identifyIds:void 0}),this.interactive&&this.identifyIds.push(a.identifyIds)}saveTilePartsCache(e){this.tileCache.generatedPartsRef=e}finishGeneration(e){this.interactive&&this.modules.identifier.resetCache(),this.modules.collector.reset(),e||this.modules.renderer.addRerenderEvent()}prepareGeneration(e){if(this.points.length<2||this.removed)return;const t=!!this.animationTickerName,i=this.splitIntoTileParts(e);if(this.mapState.globeMode&&!this.hasVisibleTileParts()){this.cleanTileObjects(t);return}if(!this.tryVisibilityOnlyUpdate(i,t))return this.cleanTileObjects(t),this.tileCache.globeEnabled=this.globeEnabled,{tileParts:i,skipRerender:t}}isTileReplicaVisible(e){const t=Math.pow(2,e[2]),i=this.mapState.visibleMapReplicas,r=this.isOutOfMainReplica(),{extraReplicas:o,tile:a,mapPoint:l,geoPoint:c}=p_;o[0]=r?i[0]-1:NaN,o[1]=r?i[i.length-1]+1:NaN,a[1]=e[1],a[2]=e[2],a[3]=e[3];const d=n.tileZoomToSize(e[2]),u=d/2,h=e[1]*d-n.HALF_WORLD_SIZE;for(let _=-1;_<=i.length;_++){const f=_===-1?o[0]:_===i.length?o[1]:i[_];if(!Number.isNaN(f)){if(a[0]=e[0]+f*t,this.mapState.globeMode){if(l[0]=a[0]*d-n.HALF_WORLD_SIZE+u,l[1]=h+u,n.Mercator.toGeo(l,c),this.modules.camera.ecef.canSee(c)&&n.isTileOnSphereInViewport(this.mapState,this.modules.camera,a))return!0}else if(n.isTileVisible(a,this.mapState.tilesBounds,this.modules))return!0}}return!1}hasVisibleTileParts(){const e=this.tileCache.parts;if(e===void 0||e.length===0)return!0;const t=this.modules.camera.ecef,{geoPoint:i}=p_;for(const r of e){const o=r.mapPoints;if(n.Mercator.toGeo(o[0],i),t.canSee(i)||(n.Mercator.toGeo(o[o.length-1],i),t.canSee(i)))return!0}return!1}destroyCachedObjects(e){for(const t of this.tileCache.objectsByPart.values())e!=null&&e.has(t.tileObject)||t.tileObject.destroyed||t.tileObject.clean(this.mapState);this.tileCache.objectsByPart.clear(),this.tileCache.generatedPartsRef=void 0}}const b_=0,wC=-1,NC=-2,S_=3,kC=0,UC=0,MC="#3388ff",HC="#00000000",GC="#00000000";let y_=class extends x_{constructor(e,t){var a,l,c,d,u,h,_,f,m,v,g,p,x;super(e,t,{}),this.options=t;const{dynamicStyle:i,layers:r}=this.modules;if(this.options.width!==0){this.rawStyleLayer={type:"line",id:`dynamic-polyline-${this.uniqId}`,minzoom:this.options.minZoom,maxzoom:this.options.maxZoom,style:{color:(a=this.options.color)!=null?a:MC,width:(l=this.options.width)!=null?l:S_},gpuState:this.options.renderingMode!=="3d"?this.options.gpuState:{depthTest:!0}};const S=n.makeHandyStyleLayer(this.rawStyleLayer,i.getStyle().globals);if(S&&(this.styleLayerId=S.innerId,i.addLayer(S,(c=this.options.zIndex)!=null?c:b_)),this.options.renderingMode==="3d"&&this.options.hiddenPartColor){this.rawHiddenStyleLayer={type:"line",id:`dynamic-polyline-hidden-${this.uniqId}`,minzoom:this.options.minZoom,maxzoom:this.options.maxZoom,style:{color:this.options.hiddenPartColor,width:(d=this.options.width)!=null?d:S_},gpuState:{depthTest:!0,depthMask:!1,cullFace:!1,depthFunc:n.DEPTH_FUNC.GREATER}};const b=n.makeHandyStyleLayer(this.rawHiddenStyleLayer,i.getStyle().globals);b&&(this.styleHiddenLayerId=b.innerId,i.addLayer(b,(u=this.options.zIndex)!=null?u:b_))}}if(this.options.width2){this.rawStyleLayer2={type:"line",id:`dynamic-polyline2-${this.uniqId}`,minzoom:this.options.minZoom,maxzoom:this.options.maxZoom,style:{color:(h=this.options.color2)!=null?h:HC,width:(_=this.options.width2)!=null?_:kC},gpuState:this.options.renderingMode!=="3d"?this.options.gpuState:{depthTest:!0}};const S=n.makeHandyStyleLayer(this.rawStyleLayer2,i.getStyle().globals);S&&(this.styleLayer2Id=S.innerId,i.addLayer(S,(f=this.options.zIndex2)!=null?f:wC))}if(this.options.width3){this.rawStyleLayer3={type:"line",id:`dynamic-polyline3-${this.uniqId}`,minzoom:this.options.minZoom,maxzoom:this.options.maxZoom,style:{color:(m=this.options.color3)!=null?m:GC,width:(v=this.options.width3)!=null?v:UC},gpuState:this.options.renderingMode!=="3d"?this.options.gpuState:{depthTest:!0}};const S=n.makeHandyStyleLayer(this.rawStyleLayer3,i.getStyle().globals);S&&(this.styleLayer3Id=S.innerId,i.addLayer(S,(g=this.options.zIndex3)!=null?g:NC))}if(this.styleLayerId===void 0&&this.styleLayer2Id===void 0&&this.styleLayer3Id===void 0)return;const o=(x=(p=this.styleLayer3Id)!=null?p:this.styleLayer2Id)!=null?x:this.styleLayerId;this.initShowAnimation("polyline",o),r.addLayer(this),this.generate()}snapPoint(e){function t([h,_],f=0){return[f+(h+n.HALF_WORLD_SIZE)/n.worldSize,(_+n.HALF_WORLD_SIZE)/n.worldSize]}function i([h,_]){return[h*n.worldSize-n.HALF_WORLD_SIZE,_*n.worldSize-n.HALF_WORLD_SIZE]}const r=this.mapState.visibleMapReplicas,o=this.points.map(h=>t(h));let a=1/0,l=o[0],c=0;for(const h of r){const _=t(this.modules.camera.flat.unproject(e),h);for(let f=0;f<o.length-1;f++){const m=o[f],v=o[f+1],g=n.getClosestPointOnLineSegment(_,m,v),p=g[0]-_[0],x=g[1]-_[1],S=p*p+x*x;S<a&&(a=S,l=i(g),c=f)}}const d=n.Mercator.toGeo(l),u=this.distances[c]+n.geoPointsDistance(d,this.geoPoints[c]);return{point:d,distance:u}}setStyle(e){this.setSubLayerStyle(this.styleLayerId,this.rawStyleLayer,e.color),this.setSubLayerStyle(this.styleLayer2Id,this.rawStyleLayer2,e.color2),this.setSubLayerStyle(this.styleLayer3Id,this.rawStyleLayer3,e.color3),this.setSubLayerStyle(this.styleHiddenLayerId,this.rawHiddenStyleLayer,e.hiddenPartColor)}removeStyleLayers(){this.styleLayerId!==void 0&&this.modules.dynamicStyle.removeLayer(this.styleLayerId),this.styleHiddenLayerId!==void 0&&this.modules.dynamicStyle.removeLayer(this.styleHiddenLayerId),this.styleLayer2Id!==void 0&&this.modules.dynamicStyle.removeLayer(this.styleLayer2Id),this.styleLayer3Id!==void 0&&this.modules.dynamicStyle.removeLayer(this.styleLayer3Id)}generate(){const e=this.prepareGeneration(15);if(!e)return;const{tileParts:t,skipRerender:i}=e,{dynamicStyle:r,collector:o}=this.modules,{tileProps:a}=this;for(let l=0;l<t.length;l++){const{vertices:c,tileInfo:d}=t[l];if(!this.isTileReplicaVisible(d.coords))continue;if(this.options.displayTileBounds){const f=r.getStyle().layers.find(g=>g.id==="debug-tile-bounds");n.generateTileBounds(o,f,this.mapState.styleState);const m=o.getAccumulatedData(),v=new n.TileObject("dynamicObject",m.data,this.modules,this.mapState,d.coords);this.tileObjects.push(v),this.modules.tileManager.addObject(v,i)}this.tileAttrs[a.beginningIsCut]=0,this.tileAttrs[a.endingIsCut]=0,l!==0&&(this.tileAttrs[a.beginningIsCut]=1),l+1!==t.length&&(this.tileAttrs[a.endingIsCut]=1);const u=this.makeCtx(d),h=_=>{if(_===void 0)return;const f=r.getStyle().layersById[_];n.isLineStyleLayer(f)&&(n.runPrecomputes(f,u),n.generateSafely({collector:o,generator:n.LineGenerator.generate,args:[r.getStyle().id,f,u,d,c]}))};h(this.styleLayerId),h(this.styleHiddenLayerId),h(this.styleLayer2Id),h(this.styleLayer3Id),this.collectTileObject(d,i,l)}this.saveTilePartsCache(t),this.finishGeneration(i)}setSubLayerStyle(e,t,i){if(e!==void 0&&i&&t&&i!==t.style.color){const{dynamicStyle:r}=this.modules;t.style.color=i;const o=n.makeHandyStyleLayer(t,this.modules.dynamicStyle.getStyle().globals);o&&(r.updateLayerStyle(e,o),this.modules.renderer.addRerenderEvent())}}};const VC=0,ZC=-1,T_=8,E_=12,WC="#2480ff",jC="#ffffff",C_=6,I_=20,XC="#ffffff00";class P_ extends x_{constructor(e,t){var r,o,a,l,c,d,u,h,_,f,m;super(e,t,{previousPointX:0,previousPointY:0,nextPointX:0,nextPointY:0,componentDistanceStart:0,objectLength:0}),this.options=t;const{layers:i}=this.modules;i.addLayer(this),this.dashLayerRaw={type:"dashedLine",id:`dynamic-dashed-polyline-dash-${this.uniqId}`,minzoom:this.options.minZoom,maxzoom:this.options.maxZoom,style:{color:this.options.dashColor||WC,dashLength:(r=this.options.dashLength)!=null?r:C_,gapColor:this.options.gapColor||XC,gapLength:(o=this.options.gapLength)!=null?o:I_,width:(a=this.options.width)!=null?a:T_},gpuState:this.options.renderingMode!=="3d"?this.options.gpuState:{depthTest:!0}},this.baseLayerRaw={type:"line",id:`dynamic-dashed-polyline-base-${this.uniqId}`,minzoom:this.options.minZoom,maxzoom:this.options.maxZoom,style:{color:this.options.dash2Color||jC,width:(c=(l=this.options)==null?void 0:l.width2)!=null?c:E_},gpuState:this.options.renderingMode!=="3d"?this.options.gpuState:{depthTest:!0}},this.dashLayer=n.makeHandyStyleLayer(this.dashLayerRaw,this.modules.dynamicStyle.getStyle().globals),this.baseLayer=n.makeHandyStyleLayer(this.baseLayerRaw,this.modules.dynamicStyle.getStyle().globals),t.renderingMode==="3d"&&t.hiddenPartDashColor&&(this.hiddenDashLayerRaw={type:"dashedLine",id:`dynamic-hidden-dashed-polyline-dash-${this.uniqId}`,minzoom:this.options.minZoom,maxzoom:this.options.maxZoom,style:{color:t.hiddenPartDashColor,dashLength:(d=this.options.dashLength)!=null?d:C_,gapColor:this.options.hiddenPartGapColor,gapLength:(u=this.options.gapLength)!=null?u:I_,width:(h=this.options.width)!=null?h:T_},gpuState:{depthTest:!0,depthMask:!1,cullFace:!1,depthFunc:n.DEPTH_FUNC.GREATER}},this.hiddenDashLayer=n.makeHandyStyleLayer(this.hiddenDashLayerRaw,this.modules.dynamicStyle.getStyle().globals),this.options.hiddenPartDash2Color&&(this.hiddenBaseLayerRaw={type:"line",id:`dynamic-hidden-dashed-polyline-base-${this.uniqId}`,minzoom:this.options.minZoom,maxzoom:this.options.maxZoom,style:{color:this.options.hiddenPartDash2Color,width:(f=(_=this.options)==null?void 0:_.width2)!=null?f:E_},gpuState:{depthTest:!0,depthMask:!1,cullFace:!1,depthFunc:n.DEPTH_FUNC.GREATER}},this.hiddenBaseLayer=n.makeHandyStyleLayer(this.hiddenBaseLayerRaw,this.modules.dynamicStyle.getStyle().globals))),this.initShowAnimation("dashedLine",(m=this.baseLayer)==null?void 0:m.innerId),this.generate()}setStyle(e){const{dashColor:t,dash2Color:i,gapColor:r,hiddenPartDashColor:o,hiddenPartGapColor:a,hiddenPartDash2Color:l}=e,{dynamicStyle:c}=this.modules;if(this.dashLayer){t!==void 0&&(this.dashLayerRaw.style.color=t),r!==void 0&&(this.dashLayerRaw.style.gapColor=r);const d=n.makeHandyStyleLayer(this.dashLayerRaw,c.getStyle().globals);d&&c.updateLayerStyle(this.dashLayer.innerId,d)}if(this.baseLayer){i!==void 0&&(this.baseLayerRaw.style.color=i);const d=n.makeHandyStyleLayer(this.baseLayerRaw,c.getStyle().globals);d&&c.updateLayerStyle(this.baseLayer.innerId,d)}if(this.hiddenDashLayer&&this.hiddenDashLayerRaw){o!==void 0&&(this.hiddenDashLayerRaw.style.color=o),r!==void 0&&(this.hiddenDashLayerRaw.style.gapColor=a);const d=n.makeHandyStyleLayer(this.hiddenDashLayerRaw,c.getStyle().globals);d&&c.updateLayerStyle(this.hiddenDashLayer.innerId,d)}if(this.hiddenBaseLayer&&this.hiddenBaseLayerRaw){l!==void 0&&(this.hiddenBaseLayerRaw.style.color=l);const d=n.makeHandyStyleLayer(this.hiddenBaseLayerRaw,c.getStyle().globals);d&&c.updateLayerStyle(this.hiddenBaseLayer.innerId,d)}this.modules.renderer.addRerenderEvent()}removeStyleLayers(){this.baseLayer&&this.modules.dynamicStyle.removeLayer(this.baseLayer.innerId),this.dashLayer&&this.modules.dynamicStyle.removeLayer(this.dashLayer.innerId),this.hiddenBaseLayer&&this.modules.dynamicStyle.removeLayer(this.hiddenBaseLayer.innerId),this.hiddenDashLayer&&this.modules.dynamicStyle.removeLayer(this.hiddenDashLayer.innerId)}generate(){const e=this.prepareGeneration(12);if(!e)return;const{tileParts:t,skipRerender:i}=e,{dynamicStyle:r}=this.modules,{tileProps:o}=this;let a=0;const l=[],c=n.create$1();for(const{vertices:h}of t){let _=0;const{x:f,y:m}=h;for(let v=1;v<f.length;v++){const g=f[v]-f[v-1],p=m[v]-m[v-1];_+=Math.sqrt(g*g+p*p)}l.push(_),a+=_}let d=0;const u=this.makeCtx();t.forEach((h,_)=>{const{tileInfo:f,vertices:m}=h,v=l[_];if(this.tileAttrs[o.beginningIsCut]=0,this.tileAttrs[o.endingIsCut]=0,this.tileAttrs[o.previousPointX]=0,this.tileAttrs[o.previousPointY]=0,this.tileAttrs[o.nextPointX]=0,this.tileAttrs[o.nextPointY]=0,this.tileAttrs[o.componentDistanceStart]=d,d+=v,this.tileAttrs[o.objectLength]=a,_!==0){const x=t[_-1].mapPoints,S=x[x.length-2];n.mapPointToTilePoint(c,S,f),this.tileAttrs[o.beginningIsCut]=1,this.tileAttrs[o.previousPointX]=c[0],this.tileAttrs[o.previousPointY]=c[1]}if(_!==t.length-1){const S=t[_+1].mapPoints[1];n.mapPointToTilePoint(c,S,f),this.tileAttrs[o.endingIsCut]=1,this.tileAttrs[o.nextPointX]=c[0],this.tileAttrs[o.nextPointY]=c[1]}if(!this.isTileReplicaVisible(f.coords))return;u.tileInfo=f;const g=x=>{var b;if(x===void 0)return;const S=(b=this.options.zIndex)!=null?b:VC;r.addLayer(x,S),n.runPrecomputes(x,u),n.generateSafely({collector:this.modules.collector,generator:n.DashedLineGenerator.generate,args:[this.dynamicStyleId,x,u,m]})},p=x=>{var b;if(x===void 0)return;const S=(b=this.options.zIndex2)!=null?b:ZC;r.addLayer(x,S),n.runPrecomputes(x,u),n.generateSafely({collector:this.modules.collector,generator:n.LineGenerator.generate,args:[this.dynamicStyleId,x,u,f,m]})};g(this.dashLayer),p(this.baseLayer),g(this.hiddenDashLayer),p(this.hiddenBaseLayer),this.collectTileObject(f,i,_)}),this.saveTilePartsCache(t),this.finishGeneration(i)}}const $C="#3388ff33",qC="#3388ff",YC=3;let A_=class extends ht{constructor(e,t){if(super(e,t),this.isGeometryOutOfMainReplica=!1,this.options=t,!this.verifyCoordinates()){console.warn(`Invalid coordinates for Polygon dynamic object with id ${this.uniqId} and options:`,t,"Polygon will not be created.");return}const i=this.options.coordinates.map(g=>{const p=g.map(x=>n.Mercator.fromGeo(x));if(p.length>1){const x=p[0],S=p[p.length-1];(x[0]!==S[0]||x[1]!==S[1])&&p.push(x)}return p});let r=[];const o=[],{dynamicStyle:a,layers:l}=this.modules;i.forEach(g=>{r.length&&o.push(r.length),r=r.concat(g)}),this.isGeometryOutOfMainReplica=r.some(g=>g[0]>n.HALF_WORLD_SIZE||g[0]<-n.HALF_WORLD_SIZE);const c=n.makeHandyStyleLayer({type:"polygon",id:`dynamic-polygon-${this.uniqId}`,minzoom:this.options.minZoom,maxzoom:this.options.maxZoom,style:{color:this.options.color||$C}},a.getStyle().globals);if(!c)return;a.addLayer(c,this.options.zIndex),this.fillLayerId=c.innerId;const d=n.optionsToTileAttrs({beginningIsCut:0,endingIsCut:0,db_tiers:t.tiers});let u;if(this.options.strokeWidth!==0){const g=n.makeHandyStyleLayer({type:"line",id:`dynamic-polygon-stroke-${this.uniqId}`,minzoom:this.options.minZoom,maxzoom:this.options.maxZoom,style:{color:this.options.strokeColor||qC,width:this.options.strokeWidth||YC}},a.getStyle().globals);g&&(u=g,a.addLayer(u,this.options.zIndex),this.borderLayerId=u.innerId)}const h=n.create();for(let g=0;g<r.length;g++)n.expandByPoint(h,r[g]);const _=n.getBoundsTileCoords(h),f=n.createTileInfo(_),m=[];for(let g=0;g<r.length;g++)m.push(r[g][0]),m.push(r[g][1]);const v=n.earcut(m,o);this.generationState={polygonLayer:c,borderLayer:u,rings:i,points:r,tileAttrs:d,tileInfo:f,trianglesIndexes:v,asEcef:ye(this.mapState)},this.generate(),l.addLayer(this)}update(){if(super.update(),this.generationState===void 0)return;const e=ye(this.mapState);e!==this.generationState.asEcef&&(this.regenerate(),this.generationState.asEcef=e),this.updateGlobeVisibility(this.options.coordinates[0][0])}isOutOfMainReplica(){return this.isGeometryOutOfMainReplica}remove(){this.interactive&&this.modules.identifier.resetCache(),this.fillLayerId&&this.modules.dynamicStyle.removeLayer(this.fillLayerId),this.borderLayerId&&this.modules.dynamicStyle.removeLayer(this.borderLayerId),super.destroy()}generate(){if(this.generationState===void 0)return;const{polygonLayer:e,borderLayer:t,rings:i,points:r,trianglesIndexes:o,tileAttrs:a,tileInfo:l}=this.generationState;if(r.length===0)return;const{dynamicStyle:c,collector:d,tileManager:u,identifier:h}=this.modules,_=ye(this.mapState),f=n.ecefDataStateFromBool(_),m=n.makeGeneratorContext(this.mapState.styleState,n.emptySourceAttrs,n.fixedTileProps,a,n.emptyFeatureAttrs,!0,this.interactive?"0":"",_?l:void 0,f);n.runPrecomputes(e,m);const v=n.create$1(),g=[],p=[],x=[];for(let T=0;T<o.length;T+=3){for(let y=0;y<3;y++)n.mapPointToTilePoint(v,r[o[T+y]],l),g[y]=v[0],p[y]=v[1],x[y]=0;n.generateSafely({collector:d,generator:n.PolygonGenerator.generate,args:[c.getStyle().id,e,m,{x:g,y:p,cut:x},n.pixelRatioToDpi(window.devicePixelRatio),l,c.getStyle().rasterSets]})}t&&(n.runPrecomputes(t,m),i.forEach(T=>{const y=[],E=[];T.forEach((P,A)=>{n.mapPointToTilePoint(v,P,l),y[A]=v[0],E[A]=v[1]}),n.generateSafely({collector:d,generator:n.LineGenerator.generate,args:[c.getStyle().id,t,m,l,{x:y,y:E}]})}));const S=d.getAccumulatedData(),b=new n.TileObject("dynamicObject",S.data,this.modules,this.mapState,l.coords,this);b.ecefDataState=f,this.visibleOnGlobe&&u.addObject(b),this.tileObjects.push(b),this.interactive&&this.identifyIds.push(S.identifyIds),d.reset(),this.modules.renderer.addRerenderEvent(),this.interactive&&h.resetCache()}regenerate(){const{tileManager:e}=this.modules;for(const t of this.tileObjects)t.clean(this.mapState),e.removeObject(t);this.tileObjects=[],this.identifyIds=[],this.generate()}verifyCoordinates(){var t;const e=(t=this.options)==null?void 0:t.coordinates;return Array.isArray(e)&&Array.isArray(e[0])&&e[0].length>0}};const QC="#3388ff33",JC="#3388ff",KC=1,eI=150;let L_=class extends ht{constructor(e,t){var g,p,x,S;if(super(e,t),this.isGeometryOutOfMainReplica=!1,this.options=t,t.segments&&t.segments<=0)return;const{dynamicStyle:i,layers:r}=this.modules,o=tI(n.Mercator.fromGeo(this.options.coordinates),n.geoToMapDistance(this.options.coordinates,this.options.radius),(g=this.options.segments)!=null?g:eI);this.isGeometryOutOfMainReplica=o.some(b=>b[0]>n.HALF_WORLD_SIZE||b[0]<-n.HALF_WORLD_SIZE);const a=n.makeHandyStyleLayer({type:"polygon",id:`dynamic-circle-${this.uniqId}`,minzoom:this.options.minZoom,maxzoom:this.options.maxZoom,style:{color:(p=this.options.color)!=null?p:QC,strokeWidth:(x=this.options.borderWidth)!=null?x:KC,strokeColor:(S=this.options.borderColor)!=null?S:JC}},i.getStyle().globals);if(!a)return;i.addLayer(a,this.options.zIndex),this.layerId=a.innerId;const l=n.optionsToTileAttrs({db_tiers:this.options.tiers}),c=n.create();for(let b=0;b<o.length;b++)n.expandByPoint(c,o[b]);const d=n.getBoundsTileCoords(c),u=n.createTileInfo(d),h=[],_=[],f=[],m=n.create$1(),v=this.options.borderWidth!==0?1:0;for(let b=0;b<o.length;b++)n.mapPointToTilePoint(m,o[b],u),h[b]=m[0],_[b]=m[1],f[b]=v;this.generationState={circleLayer:a,asEcef:ye(this.mapState),tileAttrs:l,tileInfo:u,tilePoints:{x:h,y:_,cut:f}},this.generate(),r.addLayer(this)}update(){if(super.update(),this.generationState===void 0)return;const e=ye(this.mapState);e!==this.generationState.asEcef&&(this.regenerate(),this.generationState.asEcef=e),this.updateGlobeVisibility(this.options.coordinates)}remove(){this.interactive&&this.modules.identifier.resetCache(),this.layerId&&this.modules.dynamicStyle.removeLayer(this.layerId),super.destroy()}isOutOfMainReplica(){return this.isGeometryOutOfMainReplica}generate(){if(this.generationState===void 0)return;const{circleLayer:e,tileAttrs:t,tileInfo:i,tilePoints:r}=this.generationState,{dynamicStyle:o,collector:a,tileManager:l,identifier:c}=this.modules,d=ye(this.mapState),u=n.ecefDataStateFromBool(d),h=n.makeGeneratorContext(this.mapState.styleState,n.emptySourceAttrs,n.fixedTileProps,t,n.emptyFeatureAttrs,!0,this.interactive?"0":"",d?i:void 0,u);n.runPrecomputes(e,h),n.generateSafely({collector:a,generator:n.PolygonGenerator.generate,args:[o.getStyle().id,e,h,r,n.pixelRatioToDpi(window.devicePixelRatio),i]});const _=a.getAccumulatedData(),f=new n.TileObject("dynamicObject",_.data,this.modules,this.mapState,i.coords,this);f.ecefDataState=u,l.addObject(f),this.tileObjects.push(f),this.interactive&&this.identifyIds.push(_.identifyIds),a.reset(),this.modules.renderer.addRerenderEvent(),this.interactive&&c.resetCache()}regenerate(){const{tileManager:e}=this.modules;for(const t of this.tileObjects)t.clean(this.mapState),e.removeObject(t);this.tileObjects=[],this.identifyIds=[],this.generate()}};function tI(s,e,t){const i=[];if(t>0){i.push(n.fromValues(s[0]+e,s[1],s[2]));const r=Math.PI/Math.ceil(t/2);for(let o=r;o<Math.PI;o+=r){const a=e*Math.cos(o),l=e*Math.sin(o);i.push(n.fromValues(s[0]+a,s[1]+l,s[2]),n.fromValues(s[0]+a,s[1]-l,s[2]))}i.push(n.fromValues(s[0]-e,s[1],s[2]))}return i}function Tl(s,e,t,i,r,o){if(r-i<=t)return;const a=i+r>>1;R_(s,e,a,i,r,o%2),Tl(s,e,t,i,a-1,o+1),Tl(s,e,t,a+1,r,o+1)}function R_(s,e,t,i,r,o){for(;r>i;){if(r-i>600){const d=r-i+1,u=t-i+1,h=Math.log(d),_=.5*Math.exp(2*h/3),f=.5*Math.sqrt(h*_*(d-_)/d)*(u-d/2<0?-1:1),m=Math.max(i,Math.floor(t-u*_/d+f)),v=Math.min(r,Math.floor(t+(d-u)*_/d+f));R_(s,e,t,m,v,o)}const a=e[2*t+o];let l=i,c=r;for(qn(s,e,i,t),e[2*r+o]>a&&qn(s,e,i,r);l<c;){for(qn(s,e,l,c),l++,c--;e[2*l+o]<a;)l++;for(;e[2*c+o]>a;)c--}e[2*i+o]===a?qn(s,e,i,c):(c++,qn(s,e,c,r)),c<=t&&(i=c+1),t<=c&&(r=c-1)}}function qn(s,e,t,i){El(s,t,i),El(e,2*t,2*i),El(e,2*t+1,2*i+1)}function El(s,e,t){const i=s[e];s[e]=s[t],s[t]=i}function iI(s,e,t,i,r,o,a){const l=[0,s.length-1,0],c=[];let d,u;for(;l.length;){const h=l.pop(),_=l.pop(),f=l.pop();if(_-f<=a){for(let g=f;g<=_;g++)d=e[2*g],u=e[2*g+1],d>=t&&d<=r&&u>=i&&u<=o&&c.push(s[g]);continue}const m=Math.floor((f+_)/2);d=e[2*m],u=e[2*m+1],d>=t&&d<=r&&u>=i&&u<=o&&c.push(s[m]);const v=(h+1)%2;(h===0?t<=d:i<=u)&&(l.push(f),l.push(m-1),l.push(v)),(h===0?r>=d:o>=u)&&(l.push(m+1),l.push(_),l.push(v))}return c}function nI(s,e,t,i,r,o){const a=[0,s.length-1,0],l=[],c=r*r;for(;a.length;){const d=a.pop(),u=a.pop(),h=a.pop();if(u-h<=o){for(let g=h;g<=u;g++)F_(e[2*g],e[2*g+1],t,i)<=c&&l.push(s[g]);continue}const _=Math.floor((h+u)/2),f=e[2*_],m=e[2*_+1];F_(f,m,t,i)<=c&&l.push(s[_]);const v=(d+1)%2;(d===0?t-r<=f:i-r<=m)&&(a.push(h),a.push(_-1),a.push(v)),(d===0?t+r>=f:i+r>=m)&&(a.push(_+1),a.push(u),a.push(v))}return l}function F_(s,e,t,i){const r=s-t,o=e-i;return r*r+o*o}const rI=s=>s[0],sI=s=>s[1];class oI{constructor(e,t=rI,i=sI,r=64,o=Float64Array){this.nodeSize=r,this.points=e;const a=e.length<65536?Uint16Array:Uint32Array,l=this.ids=new a(e.length),c=this.coords=new o(e.length*2);for(let d=0;d<e.length;d++)l[d]=d,c[2*d]=t(e[d]),c[2*d+1]=i(e[d]);Tl(l,c,r,0,l.length-1,0)}range(e,t,i,r){return iI(this.ids,this.coords,e,t,i,r,this.nodeSize)}within(e,t,i){return nI(this.ids,this.coords,e,t,i,this.nodeSize)}}function aI(s,e,t){const i=[],r=[],o=[],a=n.create$1();return e.forEach(({mapCoords:l,weight:c})=>{lI(a,l,t);const d=a[0],u=a[1];for(let h=0;h<6;h++)i.push(d,u),o.push(c);r.push(-1,-1,1,-1,-1,1,-1,1,1,-1,1,1)}),{vertices:s.createBuffer(new Uint16Array(i),{itemSize:2,dataType:n.Buffer.UnsignedShort,stride:0,offset:0,normalized:!0}),widens:s.createBuffer(new Int8Array(r),{itemSize:2,dataType:n.Buffer.Byte,stride:0,offset:0,normalized:!1}),weights:s.createBuffer(new Float32Array(o),{itemSize:1,dataType:n.Buffer.Float,stride:0,offset:0,normalized:!1})}}function lI(s,e,t){s[0]=(e[0]-t.offset[0])*n.maxUint16Value/t.size,s[1]=(e[1]-t.offset[1])*n.maxUint16Value/t.size}function cI(s,e){const t=dI(s),i=uI(t,e);return new C(new Uint8Array(i),{size:[e,1]})}function dI(s){const e=new Error("The palette is not valid. The heatmap won't be rendered."),t=Object.getOwnPropertyNames(s);if(t.length===0)throw e;const i=t.map(l=>Number(l));if(i.some(l=>Number.isNaN(l)||l<0||l>1))throw e;const r={};i.forEach(l=>{if(typeof s[l]!="string")throw e;r[l]=n.handyColor(s[l])});const o=Math.min(...i),a=Math.max(...i);return o>0&&(r[0]=r[o]),a<1&&(r[1]=r[a]),r}function uI(s,e){const t=Object.keys(s).map(a=>Number(a)).sort((a,l)=>a-l);let i=0;const r=[],o=e-1;for(let a=0;a<e;a++){const l=a/o;l>t[i+1]&&i++;const c=t[i],d=t[i+1],u=d-c,_=(l-c)/u;for(let f=0;f<4;f++)r[a*4+f]=n.getIntermediateValue(s[c].value[f],s[d].value[f],_)}return r.map(a=>Math.round(a))}function hI(s,e){return s.every((t,i)=>t===e[i])}const _I=256,fI=.5,mI=3,vI=10,gI=1,pI=1,xI={0:"rgba(89, 0, 89, 0)",.25:"rgba(0, 0, 89, 0.78)",.5:"rgba(0, 198, 68, 1)",.7:"rgba(198, 186, 0, 1)",.8:"rgba(249, 152, 0, 1)",1:"rgba(200, 0, 0, 1)"};class bI extends ht{constructor(e,t={}){super(e,{interactive:!1}),this.offscreenTextureIndex=-1,this.fillBuffers=m=>{if(!this.tree)return;const v=n.tetragonBounds(this.mapState.tilesBounds),g=n.getBoundsTileCoords(v);if(this.tileCoords&&hI(g,this.tileCoords))return;this.resetBuffers(),this.tileCoords=g;const p=n.tileZoomToSize(g[2]),x=n.tileCoordsToMapPoint(g);n.fromTranslationScale(this.matrix,x,n.fromValues(p,p,n.tileHeight));const S=this.tree.range(x[0],x[1],x[0]+p,x[1]+p).map(T=>this.points[T]),b=n.createTileInfo(g);this.buffers=aI(this.modules.renderer,S,b),this.vertexCount=S.length*6,this.vao=new M(m,{a_vec2_position:this.buffers.vertices,a_vec2_widen:this.buffers.widens,a_float_weight:this.buffers.weights})},this.resizeFrameBuffer=()=>{this.frameBuffer.setSize([Math.ceil(this.mapState.size[0]*window.devicePixelRatio/this.downscale),Math.ceil(this.mapState.size[1]*window.devicePixelRatio/this.downscale)]),this.modules.renderer.bindRenderTarget(this.frameBuffer),this.modules.renderer.bindRenderTarget(null);const m=this.frameBuffer.getTexture();m?this.modules.imageManager.updatePreparedTexture(this.offscreenTextureIndex,m):n.log("Can't update a non-prepared texture"),this.heatmapNeedRerender=!0,this.modules.renderer.addRerenderEvent()};const{downscale:i,palette:r,points:o,minZoom:a,maxZoom:l,zIndex:c,pointRadius:d,intensity:u,opacity:h}=t;this.rampTextureIndex=this.modules.imageManager.addPreparedTexture(cI(r!=null?r:xI,_I)),this.downscale=i!=null?i:pI,this.frameBuffer=new Pe({size:[Math.ceil(this.mapState.size[0]*window.devicePixelRatio/this.downscale),Math.ceil(this.mapState.size[1]*window.devicePixelRatio/this.downscale)],magFilter:C.LinearFilter,minFilter:C.LinearFilter,wrapS:C.ClampToEdgeWrapping,wrapT:C.ClampToEdgeWrapping});const _=this.frameBuffer.getTexture();_?this.offscreenTextureIndex=this.modules.imageManager.addPreparedTexture(_):n.log("Can't add a non-prepared texture."),this.points=[],this.vertexCount=0,this.isDestroyed=!1,this.heatmapNeedRerender=!1,this.matrix=n.create$2(),this.mvpMatrix=n.create$2(),this.viewDiffer=new n.Differ([{path:"center",type:"vec2"},{path:"zoom",type:"number"},{path:"rotation",type:"number"},{path:"pitch",type:"number"},{path:"padding",type:"padding"}]),this.sizeDiffer=new n.Differ([{path:"size",type:"vec2"}]),this.throttledFillBuffer=n.throttle(this.fillBuffers,50);const f=n.makeHandyStyleLayer({type:"heatmap",id:`dynamic-heatmap-${this.uniqId}`,minzoom:a,maxzoom:l,style:{opacity:h!=null?h:fI,intensity:u!=null?u:mI,radius:d!=null?d:vI}},this.modules.dynamicStyle.getStyle().globals);if(!f)throw new Error("There is no correct style layer for heatmap");this.layer=f,this.modules.dynamicStyle.addLayer(f,c),o&&this.setPoints(o)}isOutOfMainReplica(){return!1}setPoints(e){if(!this.isDestroyed){if(this.points=e.map(({coordinates:t,weight:i})=>({mapCoords:n.Mercator.fromGeo(t),weight:i!=null?i:gI})),this.tree=new oI(this.points,t=>t.mapCoords[0],t=>t.mapCoords[1]),this.tileCoords=void 0,!this.tileObjects.length){const{layers:t,collector:i,dynamicStyle:r,tileManager:o}=this.modules;n.generateSafely({collector:i,generator:n.HeatmapGenerator.generateTexture,args:[r.getStyle().id,this.layer,this.offscreenTextureIndex,this.rampTextureIndex]});const a=i.getAccumulatedData(),l=new n.TileObject("dynamicObject",a.data,this.modules,this.mapState);o.addObject(l),this.tileObjects.push(l),t.addLayer(this),i.reset()}this.modules.renderer.addRerenderEvent(),this.heatmapNeedRerender=!0}}update(){super.update();const e=this.modules.renderer.getShaderProgram("heatmap",this.modules.renderer.commonShaderDefines);if(this.sizeDiffer.check(this.mapState)&&this.resizeFrameBuffer(),!this.heatmapNeedRerender&&!this.viewDiffer.check(this.mapState)&&!this.modules.renderer.isNeedRerender()||!this.tree)return;const{zoom:t,styleZoom:i,styleState:r,pitch:o}=this.mapState;if(this.modules.renderer.resetStateAfterExternalRender(),this.throttledFillBuffer(e),!this.vao||!this.buffers||!this.tree||!this.tileCoords)return;const a=n.makeBinderContext(i,o,r,[]),l=n.resolveNumber(this.layer.style.radius,a),c=n.resolveNumber(this.layer.style.intensity,a),d=n.tileSizeZpt*Math.pow(2,t-this.tileCoords[2])*window.devicePixelRatio;this.modules.renderer.enableShaderProgram(e),this.modules.renderer.isUboSupported()||Kl(e,this.mapState,this.modules),this.modules.renderer.bindShaderProgram(e,{u_mat4_mvp:n.mul$1(this.mvpMatrix,this.modules.camera.viewProjectionMatrix,this.matrix),u_mat4_model:this.matrix,u_float_radius:l*window.devicePixelRatio,u_float_intensity:c,u_float_tile_to_pixel_ratio:1/d}),this.modules.renderer.bindVao(this.vao),this.modules.renderer.setViewport(0,0,Math.ceil(this.mapState.size[0]*window.devicePixelRatio/this.downscale),Math.ceil(this.mapState.size[1]*window.devicePixelRatio/this.downscale)),this.modules.renderer.bindRenderTarget(this.frameBuffer),this.modules.renderer.clearWithColor([0,0,0,0],!1),this.modules.renderer.applyGpuState(zc),this.modules.renderer.drawTriangles(0,this.vertexCount),this.modules.renderer.bindRenderTarget(null),this.heatmapNeedRerender=!1}destroy(){if(this.isDestroyed)return;super.destroy(),this.points=[],this.tree=void 0,this.isDestroyed=!0,this.resetBuffers(),this.layer&&this.modules.dynamicStyle.removeLayer(this.layer.innerId),this.frameBuffer.remove();const{imageManager:e}=this.modules;e.deleteTexture(this.offscreenTextureIndex),e.deleteTexture(this.rampTextureIndex)}resetBuffers(){this.buffers&&(Object.values(this.buffers).forEach(e=>e.remove()),this.buffers=void 0),this.vao&&(this.vao.remove(),this.vao=void 0)}}const SI=18,yI=[.5,.5],TI=[0,18],EI=0,CI=0;let D_=class extends Fl{constructor(e,t){super(e,t,t.draggable),this.generatedAsEcef=!1,this.generatedWithTierHeight=!1,this.hasExplicitZ=!1,this.throttledResolveTierData=n.throttle(()=>{if(this.status==="destroyed")return;this.resolveTierData()&&this.modules.renderer.addRerenderEvent()},yo),this.map=e,this.options=t;const{coordinates:i,size:r,zIndex:o,minZoom:a,maxZoom:l,hoverIcon:c,hoverSize:d,hoverAnchor:u,label:h,rotation:_,opacity:f,hoverOpacity:m}=t;this.status="normal",this.hasExplicitZ=i.length===3;const v=n.Mercator.fromGeo(i);this.position={userValue:v,normalizedValue:n.normalizeMapPoint(v)},this.tierHeightResolver=new Tr(this.modules,this.mapState,()=>this.position.normalizedValue,()=>{var x;return(x=this.options.tier)!=null?x:0},()=>this.hasExplicitZ),this.rotation=n.degToRad(_!=null?_:CI),this.zIndex=o!==void 0?o:EI,this.minZoom=a!=null?a:-1/0,this.maxZoom=l!=null?l:1/0;const g=t.icon!==void 0?t.icon:n.defaultMarkerIcon,p=t.icon!==void 0?t.anchor:n.defaultMarkerAnchor;this.on("mouseover",this.switchToHoveredStyle),this.on("mouseout",this.switchToNormalStyle),this.modules.layers.addLayer(this),this.setIconInternal({icon:g,anchor:p,size:r,opacity:f}).then(()=>{c!==void 0&&this.setHoverIconInternal({icon:c,anchor:u,size:d,opacity:m})}),this.setLabel(h)}destroy(){var e;this.status!=="destroyed"&&(this.status="destroyed",(e=this.label)==null||e.remove(),this.interactive&&this.modules.identifier.resetCache(),this.off("mouseover",this.switchToHoveredStyle),this.off("mouseout",this.switchToNormalStyle),super.destroy())}update(){super.update();const e=ye(this.mapState),t=this.tierHeightResolver.shouldUseTierHeight();(this.mapState.dpiChanged||e!==this.generatedAsEcef||t!==this.generatedWithTierHeight)&&(this.generatedWithTierHeight=t,this.regenerate(),this.generatedAsEcef=e),this.refreshTierData(),this.updateGlobeVisibility(this.options.coordinates)}isOutOfMainReplica(){return!1}setRotation(e){if(this.status==="destroyed")return;const t=n.degToRad(e);t!==this.rotation&&(this.rotation=t,this.normalStateData&&(this.normalStateData.styleLayer.style.iconRotation=this.rotation,this.modules.renderer.addRerenderEvent()),this.hoverStateData&&(this.hoverStateData.styleLayer.style.iconRotation=this.rotation,this.modules.renderer.addRerenderEvent()))}getRotation(){return n.radToDeg(this.rotation)}setIcon(e){this.status!=="destroyed"&&(z_({icon:this.options.icon,anchor:this.options.anchor,size:this.options.size,opacity:this.options.opacity},e)||(this.options.icon=e.icon,this.options.anchor=e.anchor,this.options.size=e.size,this.options.opacity=e.opacity,this.setIconInternal(e)))}setHoverIcon(e){if(this.status!=="destroyed"){if(!e){this.status==="hover"&&this.switchToNormalStyle(),this.hoverStateData&&(n.excludeItemFromArray(this.tileObjects,this.hoverStateData.tileObject),n.excludeItemFromArray(this.identifyIds,this.hoverStateData.identifyIds),this.hoverStateData.tileObject.clean(this.mapState),this.hoverStateData=void 0);return}z_({icon:this.options.hoverIcon,anchor:this.options.hoverAnchor,size:this.options.hoverSize,opacity:this.options.hoverOpacity},e)||(this.options.hoverIcon=e.icon,this.options.hoverAnchor=e.anchor,this.options.hoverSize=e.size,this.options.hoverOpacity=e.opacity,this.setHoverIconInternal(e))}}setLabel(e){var t,i,r,o,a,l;this.status!=="destroyed"&&((t=this.label)==null||t.remove(),e&&(this.label=new Cr(this.map,V(I({coordinates:this.getCoordinates()},e),{tier:(i=e.tier)!=null?i:this.options.tier,minZoom:Math.max((r=e.minZoom)!=null?r:this.minZoom,this.minZoom),maxZoom:Math.min((o=e.maxZoom)!=null?o:this.maxZoom,this.maxZoom),fontSize:(a=e.fontSize)!=null?a:SI,anchor:e.anchor||yI,offset:e.offset||TI,zIndex:(l=e.zIndex)!=null?l:this.zIndex+1e-5,interactive:this.interactive}),this)))}setCoordinates(e){var t;this.hasExplicitZ=e.length===3,this.tierHeightResolver.reset(!0),this.setPosition(n.Mercator.fromGeo(e)),(t=this.label)==null||t.setCoordinates(e)}getCoordinates(){return n.Mercator.toGeo(this.getPosition())}show(){var e;this.status==="hidden"&&((e=this.label)==null||e.show(),this.normalStateData&&(this.modules.tileManager.addObject(this.normalStateData.tileObject),this.modules.renderer.addRerenderEvent(),this.interactive&&this.modules.identifier.resetCache()),this.status="normal")}hide(){var t,i,r;if(this.status==="destroyed"||this.status==="hidden")return;(t=this.label)==null||t.hide();const e=this.status==="normal"?(i=this.normalStateData)==null?void 0:i.tileObject:(r=this.hoverStateData)==null?void 0:r.tileObject;e&&(this.modules.tileManager.removeObject(e),this.modules.renderer.addRerenderEvent(),this.interactive&&this.modules.identifier.resetCache()),this.status="hidden"}getResolvedHeight(){return this.tierHeightResolver.getResolvedHeight()}setPosition(e){if(this.position={userValue:e,normalizedValue:n.normalizeMapPoint(e)},!!this.tileObjects.length){if(ye(this.mapState)){this.regenerate();return}this.tileObjects.forEach(t=>{t.setTileCoords(n.mapPointTo32ZoomTileCoords(this.position.normalizedValue),this.mapState)}),this.status!=="hidden"&&(this.modules.renderer.addRerenderEvent(),this.interactive&&this.modules.identifier.resetCache())}}getPosition(){return this.position.userValue}contains(e){if(!this.normalStateData)return!1;const{hoverStateData:t,normalStateData:i}=this,r=t!==void 0?t.size:i.size,o=t!==void 0?t.anchor:i.anchor,a=this.modules.camera.flat.project(this.position.normalizedValue),l=a[0]-r[0]*o[0],c=a[0]+r[0]*(1-o[0]),d=a[1]-r[1]*o[1],u=a[1]+r[1]*(1-o[1]);return e[0]>l&&e[0]<c&&e[1]>d&&e[1]<u}switchToHoveredStyle(){if(this.status==="normal"&&this.hoverStateData&&this.normalStateData){const{tileManager:e}=this.modules;e.removeObject(this.normalStateData.tileObject),e.addObject(this.hoverStateData.tileObject),this.status="hover",this.modules.renderer.addRerenderEvent()}this.label&&(this.label.hovered=!0,this.modules.renderer.addRerenderEvent())}switchToNormalStyle(){if(this.status==="hover"&&this.normalStateData&&this.hoverStateData){const{tileManager:e}=this.modules;e.removeObject(this.hoverStateData.tileObject),e.addObject(this.normalStateData.tileObject),this.status="normal",this.modules.renderer.addRerenderEvent()}this.label&&(this.label.hovered=!1,this.modules.renderer.addRerenderEvent())}getMarkerStateData(e,{icon:t,anchor:i,size:r,opacity:o}){const{zIndex:a,position:l}=this,{collector:c,dynamicStyle:d,styleManager:u,defaultSource:h}=this.modules,_=n.optionsToTileAttrs({dpi:window.devicePixelRatio*96}),f=n.mapPointTo32ZoomTileCoords(l.normalizedValue),m=typeof this.position.userValue[2]=="number"?this.position.userValue[2]:0,v=this.tierHeightResolver.shouldUseTierHeight(),g=m!==0||v;this.generatedWithTierHeight=v;const p=n.makeHandyStyleLayer({type:"point",id:`dynamic-marker-${this.uniqId}`,minzoom:this.minZoom,maxzoom:this.maxZoom,style:{iconImage:t,iconAnchor:i,iconRotation:this.rotation,iconOpacity:o,elevation:m,allowElevation:g}},d.getStyle().globals);if(!p)throw new Error(`Marker with icon ${t} was created with null style layer`);const x=n.resolveSimpleLiteralExpression(p.style.iconAnchor);d.addLayer(p,a),d.appendRasterSet(e,n.getStaticIconRasterSetKey(t,x[0],x[1]));const S=n.makeGeneratorContext(this.mapState.styleState,n.emptySourceAttrs,n.fixedMetatile.tileProps,_,n.emptyFeatureAttrs,!0,this.interactive?"0":"");n.runPrecomputes(p,S),n.generateSafely({collector:c,generator:n.preLabelingPoint,args:[d.getStyle(),p,S,n.fixedMetatile,n.LATEST_TILE_VERSION,f,h.getId(),{x:[0],y:[0]},n.pixelRatioToDpi(window.devicePixelRatio)]});const{identifyIds:b,labels:T}=c.getAccumulatedData();if(!T.length)throw new Error(`Marker with icon ${t} was created with empty labels`);const y=[{metatileHash:-1,labels:T,styleId:d.getStyle().id}],E=n.unpackPreLabelingResult(y,n.LabelSource.DynamicObject,u,this.mapState.styleState,this.mapState.styleZoom,this.mapState.pitch);if(E.length!==1)throw new Error(`Marker with icon ${t} has empty unpacked labels`);const P=E[0],A=n.createTileInfo(f),F=ye(this.mapState)?(B,Q)=>n.encodeTilePointToEcefU16(A,B,Q):void 0;n.generateNotStretchableIconElement(c,P,"",[0,0,m],0,e.rasters[0],window.devicePixelRatio,F);const{data:L}=c.getAccumulatedData();c.reset();const D=new n.TileObject("dynamicObject",L,this.modules,this.mapState,f,this);return D.ecefDataState=n.ecefDataStateFromBool(ye(this.mapState)),this.tierHeightResolver.shouldUseTierHeight()&&this.resolveTierData(),{styleLayer:p,tileObject:D,identifyIds:b,icon:t,anchor:[e.rasters[0].anchorX,e.rasters[0].anchorY],size:r||[e.rasters[0].w/window.devicePixelRatio,e.rasters[0].h/window.devicePixelRatio]}}refreshTierData(){if(!this.tierHeightResolver.shouldUseTierHeight()){this.tierHeightResolver.reset()&&this.modules.renderer.addRerenderEvent();return}this.tierHeightResolver.needsResolve()&&this.throttledResolveTierData()}resolveTierData(){return this.tierHeightResolver.resolve()}setIconInternal(e){return q(this,null,function*(){return this.modules.imageCache.getRasterSet(e.icon,void 0,e.size,e.anchor).then(t=>{if(this.status==="destroyed"||!t)return;const i=this.normalStateData,r=this.getMarkerStateData(t,e);this.status==="normal"&&this.visibleOnGlobe&&(i&&this.modules.tileManager.removeObject(i.tileObject),this.modules.tileManager.addObject(r.tileObject),this.modules.renderer.addRerenderEvent(),this.interactive&&this.modules.identifier.resetCache()),i&&(n.excludeItemFromArray(this.tileObjects,i.tileObject),n.excludeItemFromArray(this.identifyIds,i.identifyIds),i.tileObject.clean(this.mapState)),this.tileObjects.push(r.tileObject),this.interactive&&this.identifyIds.push(r.identifyIds),this.normalStateData=r})})}setHoverIconInternal(e){return q(this,null,function*(){return this.modules.imageCache.getRasterSet(e.icon,void 0,e.size,e.anchor).then(t=>{if(this.status==="destroyed"||!t)return;const i=this.hoverStateData,r=this.getMarkerStateData(t,e);this.status==="hover"&&this.visibleOnGlobe&&(i&&this.modules.tileManager.removeObject(i.tileObject),this.modules.tileManager.addObject(r.tileObject),this.modules.renderer.addRerenderEvent(),this.interactive&&this.modules.identifier.resetCache()),i&&(n.excludeItemFromArray(this.tileObjects,i.tileObject),n.excludeItemFromArray(this.identifyIds,i.identifyIds),i.tileObject.clean(this.mapState)),this.tileObjects.push(r.tileObject),this.interactive&&this.identifyIds.push(r.identifyIds),this.hoverStateData=r})})}regenerate(){const{icon:e,hoverIcon:t}=this.options;e&&this.setIconInternal(I({icon:e},this.options)),e&&t&&this.setHoverIconInternal(I({icon:e,hoverIcon:t},this.options)),ye(this.mapState)!==this.generatedAsEcef&&this.setLabel(this.options.label)}};function z_(s,e){var t,i,r,o,a,l,c,d,u,h;return!(s.icon!==e.icon||((t=s.anchor)==null?void 0:t[0])!==((i=e.anchor)==null?void 0:i[0])||((r=s.anchor)==null?void 0:r[1])!==((o=e.anchor)==null?void 0:o[1])||((a=s.size)==null?void 0:a[0])!==((l=e.size)==null?void 0:l[0])||((c=s.size)==null?void 0:c[1])!==((d=e.size)==null?void 0:d[1])||((u=s.opacity)==null?void 0:u.toString())!==((h=e.opacity)==null?void 0:h.toString()))}const II=n.inferGeneratorType({symbol:"polygon",sinks:{fill:{stride:8,binder:(s,e)=>{s.views.position=new Uint16Array(e),s.views.localID=new Uint32Array(e,4)},packObjectAttributes(s,e,t){return n.createObjectAttributesArray([s,e.innerId],e,t)},unpackObjectAttributes(s){return{styleId:s[0],layerId:s[1],tileData:s.slice(2)}}}},generate(s,e,t,i,r){const o=r.x,a=r.y,l=s.idIndexer.getIndex(i,e,t),c=n.resolveExpression(t.ignoreTier,i)?null:i.tileAttrs[i.tileProps.db_tiers],d=s.getBucket(t.type,"fill",n.PolygonGenerator.sinks.fill.packObjectAttributes(e,t,c,"","",i),n.PolygonGenerator.sinks.fill.binder);let u=d.elements.offset;PI(d.indices,u,0,1,2,2,1,3),Ws(d,u++,o[0],a[0],l),Ws(d,u++,o[1],a[1],l),Ws(d,u++,o[2],a[2],l),Ws(d,u++,o[3],a[3],l),d.elements.offset=u}});function Ws(s,e,t,i,r){const o=e*4;s.views.position[o]=n.tileCoordOffset+t,s.views.position[o+1]=n.tileCoordOffset+i;const a=e*2;s.views.localID[a]=r}function PI(s,e,t,i,r,o,a,l){const c=s.buffer,d=s.offset;c[d]=e+t,c[d+1]=e+i,c[d+2]=e+r,c[d+3]=e+o,c[d+4]=e+a,c[d+5]=e+l,s.offset=d+6}const AI="#0085a0";class LI extends ht{constructor(e,t){super(e,t),this.isGeometryOutOfMainReplica=!1;const{dynamicStyle:i,collector:r,tileManager:o,identifier:a,layers:l}=this.modules;this.options=t,this.points=[];const c=n.makeHandyStyleLayer({type:"polygon",id:`dynamic-polygon-${this.uniqId}`,minzoom:this.options.minZoom,maxzoom:this.options.maxZoom,style:{color:this.options.color||AI}},i.getStyle().globals);if(!c)return;i.addLayer(c,this.options.zIndex),this.layerId=c.innerId;const d=n.optionsToTileAttrs({db_tiers:t.tiers});this.points=RI(n.Mercator.fromGeo(this.options.center),n.geoToMapDistance(this.options.center,this.options.width),n.geoToMapDistance(this.options.center,this.options.height)),this.isGeometryOutOfMainReplica=this.points.some(S=>S[0]>n.HALF_WORLD_SIZE||S[0]<-n.HALF_WORLD_SIZE);const u=n.create();for(let S=0;S<this.points.length;S++)n.expandByPoint(u,this.points[S]);const h=n.getBoundsTileCoords(u),_=n.createTileInfo(h),f=[],m=[],v=n.create$1();for(let S=0;S<this.points.length;S++)n.mapPointToTilePoint(v,this.points[S],_),f[S]=v[0],m[S]=v[1];const g=n.makeGeneratorContext(this.mapState.styleState,n.emptySourceAttrs,n.fixedTileProps,d,n.emptyFeatureAttrs,!0,this.options.interactive?"0":"");n.generateSafely({collector:r,generator:II.generate,args:[i.getStyle().id,c,g,{x:f,y:m}]});const p=r.getAccumulatedData(),x=new n.TileObject("dynamicObject",p.data,this.modules,this.mapState,h,this);o.addObject(x),this.tileObjects.push(x),this.options.interactive&&this.identifyIds.push(p.identifyIds),l.addLayer(this),r.reset(),this.modules.renderer.addRerenderEvent(),this.options.interactive&&a.resetCache()}destroy(){this.layerId!==void 0&&this.modules.dynamicStyle.removeLayer(this.layerId),this.options.interactive&&this.modules&&this.modules.identifier.resetCache(),super.destroy()}isOutOfMainReplica(){return this.isGeometryOutOfMainReplica}}function RI(s,e,t){const i=e/2,r=t/2,o=s[0],a=s[1],l=s[2];return[[o-i,a-r,l],[o+i,a-r,l],[o-i,a+r,l],[o+i,a+r,l]]}let B_=class extends ht{constructor(e,t){super(e,{interactive:!1}),this.isGeometryOutOfMainReplica=!1;const{dynamicStyle:i}=this.modules;this.options=V(I({},t),{image:{url:t.image.url}}),this.points=[],this.styleLayer=n.makeHandyStyleLayer({type:"raster",id:`dynamic-raster-${this.uniqId}`,minzoom:this.options.minZoom,maxzoom:this.options.maxZoom,style:{opacity:this.options.opacity}},i.getStyle().globals),this.styleLayer&&(i.addLayer(this.styleLayer,this.options.zIndex),this.layerId=this.styleLayer.innerId,this.modules.imageManager.loadTexture(this.options.image.url,{skipAtlasSizeChecking:!0}).then(r=>{this.textureIndex=r,this.generate()}))}destroy(){this.layerId!==void 0&&this.modules.dynamicStyle.removeLayer(this.layerId),super.destroy()}updateImage(e){const{url:t,bounds:i}=e;return!t&&!i?Promise.resolve():(t&&(this.options.image.url=t),i&&(this.options.bounds=i),(t?this.modules.imageManager.loadTexture(t,{skipAtlasSizeChecking:!0}):Promise.resolve(this.textureIndex)).then(o=>{this.textureIndex=o,this.clean(),this.generate()}))}isOutOfMainReplica(){return this.isGeometryOutOfMainReplica}generate(){var m;if(!this.styleLayer||this.textureIndex===void 0)return;const{collector:e,dynamicStyle:t,tileManager:i,layers:r}=this.modules;this.points=FI(this.options.bounds),this.isGeometryOutOfMainReplica=this.points.some(v=>v[0]>n.HALF_WORLD_SIZE||v[0]<-n.HALF_WORLD_SIZE);const o=n.create();for(let v=0;v<this.points.length;v++)n.expandByPoint(o,this.points[v]);const a=n.getBoundsTileCoords(o),l=n.createTileInfo(a),c=[],d=[],u=n.create$1();for(let v=0;v<this.points.length;v++)n.mapPointToTilePoint(u,this.points[v],l),c[v]=u[0],d[v]=u[1];const h=n.makeGeneratorContext(this.mapState.styleState,{},n.fixedTileProps,[],n.emptyFeatureAttrs,!0);n.generateSafely({collector:e,generator:n.RasterGenerator.generate,args:[{x:c,y:d},t.getStyle().id,h,this.styleLayer,this.textureIndex,(m=this.options.tiers)!=null?m:null]});const _=e.getAccumulatedData(),f=new n.TileObject("dynamicObject",_.data,this.modules,this.mapState,a,this);i.addObject(f),this.tileObjects.push(f),r.addLayer(this),e.reset(),this.modules.renderer.addRerenderEvent()}clean(){const e=this.tileObjects[0];e&&(e.clean(this.mapState),this.modules.tileManager.removeObject(e),this.modules.layers.removeLayer(this),this.tileObjects=[])}};function FI(s){const{min:e,max:t}=n.fromGeo(s);return[e,[t[0],e[1]],[e[0],t[1]],t]}class DI{constructor(e,t,i){this.id=e,this.modules=t,this.options=i,this.type="raster",this.textureIndices={},this.tileLoader=new n.BaseTileLoader("arrayBuffer"),this.attributes={},this.tiles=new Map,this.sourceAttrs=i.attributes||{},this.url=r=>{const[o,a,l]=n.tileCoordsToOSM(r),{min:c,max:d}=n.getTileBounds(r),u={southWest:[c[0],c[1]].map(f=>f/n.WEB_MERCATOR_TO_WORLD_SIZE_MULTIPLIER),northEast:[d[0],d[1]].map(f=>f/n.WEB_MERCATOR_TO_WORLD_SIZE_MULTIPLIER)};let h=this.options.url(o,a,l,u);const _=this.modules.map.state.tileKey;return _&&(h=h.replace("{key}",_)),h}}deleteTextures(){for(const e in this.textureIndices)this.modules.imageManager.deleteTexture(this.textureIndices[e]);this.textureIndices={}}abortTileFetches(e){this.tileLoader.abortRequests(e.map(n.coordsToKey))}deleteTiles(e){for(const t of e){const i=n.coordsToKey(t),r=this.textureIndices[i];isNaN(r)||this.modules.imageManager.deleteTexture(r),this.tiles.delete(i)}}fetchTiles(e){return e.map(t=>this.fetchTile(t))}fetchTile(e){const t=n.coordsToKey(e),i=this.url(e);return this.tileLoader.fetch(e,()=>i).then(r=>{if(r.error){const a=this.modules.sourceStorage.getSourceById(this.id);(a==null?void 0:a.type)==="raster"&&this.modules.map.emit("error",{type:"rasterTileLoadError",tileCoords:n.tileCoordsToOSM(e),tileUrl:i,source:a,responseMessage:r.error.message,responseStatus:r.error.status})}return r.rejected||this.tiles.set(t,r.data),[{regionId:0,metatileHash:-1}]})}generateTile(e,t){return q(this,null,function*(){const i=[],r=[],o=this.modules.styleManager.getStyle(e.handyStyleId),a=n.coordsToKey(t),l=this.tiles.get(a);if(!l||!o)return Promise.resolve({results:i,transferable:r});const c=yield this.modules.imageManager.addTexture(l,{imagePadding:0,size:[n.tileSizeZpt,n.tileSizeZpt]});if(c===void 0)return Promise.resolve({results:i,transferable:r});this.textureIndices[a]=c;const d=[],u=[],h=n.create$1(),_=zI(n.tileCoordsToMapPoint(t),n.tileZoomToSize(t[2])),f=n.createTileInfo(t);for(let g=0;g<_.length;g++)n.mapPointToTilePoint(h,_[g],f),d[g]=h[0],u[g]=h[1];const m=n.makeGeneratorContext(e.styleState,this.sourceAttrs,n.fixedTileProps,[],n.emptyFeatureAttrs,!0);o.layers.filter(g=>g.type==="raster"&&n.resolveExpression(g.filter,m)).forEach(g=>{n.runPrecomputes(g,m),n.generateSafely({collector:this.modules.collector,generator:n.RasterGenerator.generate,args:[{x:d,y:u},o.id,m,g,c,null]})});const v=this.modules.collector.getAccumulatedData();return i.push({regionId:0,metatileHash:0,styleId:o.id,collectorOutput:v}),r.push(...v.transferable),this.modules.collector.reset(),Promise.resolve({results:i,transferable:r})})}getAttributes(){return this.attributes}setAttributes(e){this.attributes=e}destroy(){this.tileLoader.destroy()}}function zI(s,e){const t=s[0],i=s[1],r=s[2];return[[t,i,r],[t+e,i,r],[t,i+e,r],[t+e,i+e,r]]}let O_=class{constructor(e,t,i){var a,l;this.type="raster",this.id=n.sourceUuid(),this.modules=e.modules,this.source=new DI(this.id,this.modules,t);const r=(a=t.minZoom)!=null?a:n.MAP_DEFAULTS.minZoom,o=(l=t.maxZoom)!=null?l:n.MAP_DEFAULTS.maxZoom;this.layer=new n.TileLayer(r,o,r,o,this.modules,e.state,this.source),this.modules.tileManager.addTileLayer(this.layer),this.modules.sourceStorage.addSource(this),this.mapglApiSource=i}destroy(){this.source.deleteTextures(),this.modules.tileManager.removeTileLayer(this.layer),this.modules.sourceStorage.removeSource(this.getId()),this.layer.destroy()}getAttributes(){return this.source.getAttributes()}getZoomDirection(){return this.layer.getZoomDirection()}getId(){return this.source.id}setAttributes(e){this.source.setAttributes(e),this.layer.redraw()}isIdentifiedAsDefault(){return!1}};const BI=0;class OI extends ht{constructor(e,t){var a;super(e,t),this.options=t,this.generatedAsEcef=!1;const i=n.Mercator.fromGeo(t.coordinates);this.position={userValue:i,normalizedValue:n.normalizeMapPoint(i)},this.zIndex=(a=t.zIndex)!=null?a:BI,this.isDestroyed=!1,this.labelKey=`onlineMarker-${this.uniqId}`;const r=this.options.floorId?e.modules.floorManager.getFloorObjectElevation(this.options.floorId,!0):0,o=t.elevation?t.elevation*n.Mercator.scaleFactor(t.coordinates[1])*n.MAP_POINTS_IN_METER:0;this.elevation=o+r,this.actualIcon=t.icon,this.setIcon(t.icon)}destroy(){this.isDestroyed=!0,this.modules.identifier.resetCache(),this.modules.labeler.removeLabels(this.labelKey),super.destroy()}isOutOfMainReplica(){return!1}setIcon(e){this.actualIcon=e;const{url:t,transformer:i,size:r,anchor:o}=e;this.modules.imageCache.getRasterSet(t,i,r,o).then(a=>{if(this.isDestroyed||!a||this.actualIcon!==e)return;this.removeIcon();const l=n.makeHandyStyleLayer({type:"point",id:`dynamic-onlineMarker-${this.uniqId}`,minzoom:-1/0,maxzoom:1/0,style:{iconImage:t,iconAnchor:o}},this.modules.dynamicStyle.getStyle().globals),c=n.optionsToTileAttrs({}),{collector:d,dynamicStyle:u,styleManager:h,defaultSource:_}=this.modules,f=this.zIndex;if(!l)return;const m=n.resolveFirstAnchorExpression(l.style.iconAnchor);u.addLayer(l,f),u.appendRasterSet(a,n.getStaticIconRasterSetKey(t,m[0],m[1]));const v=n.mapPointTo32ZoomTileCoords(this.position.normalizedValue),g={x:[0],y:[0]},p=n.makeGeneratorContext(this.mapState.styleState,n.emptySourceAttrs,n.fixedMetatile.tileProps,c,n.emptyFeatureAttrs,!0,this.interactive?"0":"");n.runPrecomputes(l,p),n.generateSafely({collector:d,generator:n.preLabelingPoint,args:[u.getStyle(),l,p,n.fixedMetatile,n.LATEST_TILE_VERSION,v,_.getId(),g,n.pixelRatioToDpi(window.devicePixelRatio)]});const x=d.getAccumulatedData(),{identifyIds:S,labels:b}=x;if(!b.length)return;const T=[{metatileHash:-1,labels:b,styleId:u.getStyle().id}],y=n.unpackPreLabelingResult(T,n.LabelSource.DynamicObject,h,this.mapState.styleState,this.mapState.styleZoom,this.mapState.pitch);if(y.length!==1)return;const E=y[0],P=n.createTileInfo(v),A=ye(this.mapState)?(D,B)=>n.encodeTilePointToEcefU16(P,D,B):void 0;n.generateNotStretchableIconElement(d,E,"",[0,0,this.elevation],0,a.rasters[0],window.devicePixelRatio,A);const F=d.getAccumulatedData();d.reset();const L=new n.TileObject("dynamicObject",F.data,this.modules,this.mapState,n.mapPointTo32ZoomTileCoords(this.position.normalizedValue),this);L.ecefDataState=n.ecefDataStateFromBool(ye(this.mapState)),this.tileObjects.push(L),this.identifyIds=[S],this.modules.tileManager.addObject(L),this.modules.layers.addLayer(this),this.modules.identifier.queryFillCache(),this.modules.labeler.removeLabels(this.labelKey),this.modules.labeler.addLabelBox(this.labelKey,{id:this.uniqId,width:r[0],height:r[1],position:this.position.normalizedValue,offset:[-o[0],-o[1]],labelingGroup:"marker"}),this.modules.renderer.addRerenderEvent()})}update(){super.update();const e=ye(this.mapState);e!==this.generatedAsEcef&&(this.setIcon(this.actualIcon),this.generatedAsEcef=e),this.updateGlobeVisibility(this.options.coordinates)}removeIcon(){const e=this.tileObjects[0];e&&(e.clean(this.mapState),this.modules.tileManager.removeObject(e),this.tileObjects=[])}}function wI(s,e,t,i,r,o){return{type:s,maxDetailLevel:o,minDetailLevel:r,maxZoomLevel:i,minZoomLevel:t,zoomLevel:Math.floor(e),tiles:{},viewportTiles:[],useExtendedTilesBounds:!1}}function NI(s){s.tiles={},s.viewportTiles=[]}function kI(s){return{type:"data",key:n.coordsToKey(s),coords:s,zoomLevel:s[2],detailLevel:s[3],needFetch:!1,needAbortFetch:!1,status:n.TileStatus.Initial}}function UI(s,e,t,i,r){return wI("data",s,e,t,i,r)}function MI(s,e,t,i){if(s.zoomLevel<s.minZoomLevel){s.viewportTiles=[];return}const r=n.clamp(s.zoomLevel,s.minZoomLevel,s.maxZoomLevel),o=n.clamp(s.zoomLevel,s.minDetailLevel,s.maxDetailLevel);s.viewportTiles=n.findVisibleTiles(e,t,r,s.minZoomLevel,o,void 0,void 0,void 0,s.useExtendedTilesBounds).map(n.coordsToKey);for(let a=0;a<s.viewportTiles.length;a++){const l=s.viewportTiles[a];let c=s.tiles[l];c||(c=s.tiles[l]=i(n.keyToCoords(l)))}}function HI(s){const e=[];for(const t in s.tiles){const i=s.tiles[t];i.needFetch&&(i.needFetch=!1,e.push(i))}return e}function GI(s){const e=[];for(const t in s.tiles){const i=s.tiles[t];i.needAbortFetch&&(i.needAbortFetch=!1,e.push(i))}return e}function VI(s,e){const t=new Set(s.viewportTiles),i=[];for(const r in s.tiles){const o=s.tiles[r];!t.has(r)&&i.push(o)}return i}class ZI extends n.Evented{constructor(e,t,i){super(),this.prevZoomLevel=0,this.mapState=e,this.modules=t,this.config=i,this.gridState=UI(e.styleZoom,i.minZoom,i.maxZoom,i.minZoom,i.maxZoom),this.viewportDiffer=new n.Differ([{path:"center",type:"vec2"},{path:"zoom",type:"number"},{path:"size",type:"vec2"},{path:"rotation",type:"number"},{path:"pitch",type:"number"},{path:"demMode",type:"boolean"}]),this.dataTileLoader=new n.BaseTileLoader("json"),this.modules.layers.addLayer(this),this.modules.scheduler.register(this,wt.Update)}get entityId(){return this}destroy(){NI(this.gridState),this.modules.layers.removeLayer(this),this.modules.scheduler.markDestroyed(this)}update(){let e=!0;if(this.viewportDiffer.check(this.mapState)){const t=Math.floor(this.mapState.styleZoom);t!==this.prevZoomLevel&&(e=!1),this.prevZoomLevel=t,this.gridState.zoomLevel=t,MI(this.gridState,this.mapState,this.modules,kI),this.emit("tilesSetChanged",{tileIds:this.gridState.viewportTiles})}for(const t in this.gridState.tiles){if(!this.gridState.viewportTiles.includes(t)){this.gridState.tiles[t].status===n.TileStatus.Loading&&(this.gridState.tiles[t].needAbortFetch=!0);continue}this.gridState.tiles[t].status===n.TileStatus.Initial&&(this.gridState.tiles[t].needFetch=!0,this.gridState.tiles[t].status=n.TileStatus.Loading)}e&&(this.fetch(HI(this.gridState)),this.abortFetch(GI(this.gridState)),this.clearTiles(VI(this.gridState)))}fetch(e){e.sort((t,i)=>n.compare(this.mapState.center,t,i)).forEach(t=>this.fetchTile(t))}abortFetch(e){const t=e.map(i=>i.key);this.dataTileLoader.abortRequests(t)}clearTiles(e){for(const t of e)delete this.gridState.tiles[t.key],this.emit("dataTileCleared",{tileId:t.key})}fetchTile(e){const{tsURLTemplate:t}=this.config;this.dataTileLoader.fetch(e.coords,t).then(i=>{i.rejected||this.emit("dataTileLoaded",{tileId:e.key,data:i.data})})}}const WI=Object.freeze(Object.defineProperty({__proto__:null,Benchmark:Os,Circle:L_,CircleMarker:Dl,DashedPolyline:P_,DataTileLayer:ZI,DefaultSource:Ih,DynamicObject:ht,Entrance:sl,GeoJsonSource:n.GeoJsonSource,GeoJsonTileSource:n.GeoJsonTileSource,GeoJsonViewportSource:n.GeoJsonViewportSource,GltfModel:hl,Heatmap:bI,HtmlMarker:el,LinePatternType:n.LinePatternType,Map:yl,MapClass:yl,Marker:D_,OnlineMarker:OI,PointLabel:Cr,Polygon:A_,Polyline:y_,Raster:B_,RasterTileSource:O_,Rect:LI,ZenithSource:eo,config:n.index,linePatternFromString:n.linePatternFromString,mapglUtils:af,setFixedElapsedTime:n.setFixedElapsedTime,utils:of},Symbol.toStringTag,{value:"Module"})),jI="topRight";class Vi{constructor(e,t,i){var r;this._wrap=document.createElement("div"),this._wrap.style.userSelect="none",typeof t=="string"?this._wrap.innerHTML=t:this._wrap.appendChild(t),this._position=(r=i==null?void 0:i.position)!=null?r:jI,this._controlPane=e._controlPane,this._container=this._controlPane.getContainerByPosition(this._position),this._container.append(this._wrap)}destroy(){this._wrap.remove()}getPosition(){return this._position}setPosition(e){this._container.removeChild(this._wrap),this._container=this._controlPane.getContainerByPosition(e),this._container.append(this._wrap),this._position=e}getContainer(){return this._wrap}}const Zi={root:"mapgl_QEdaFvncPWE-",button:"mapgl_mjx-K8iaDdc-",zoomIn:"mapgl_zKZCVsRur9c-",zoomOut:"mapgl_3t-wJELDATg-"},XI=`
    <div class="${Zi.root}">
        <button type="button" class="${Zi.button} ${Zi.zoomIn}">
            <svg
                xmlns="http://www.w3.org/2000/svg"
                viewBox="0 0 32 32"
                width="32"
                height="32"
                fill="currentColor"
            >
                <path d="M24 15h-7V8h-2v7H8v2h7v7h2v-7h7v-2z"></path>
            </svg>
        </button>
        <button type="button" class="${Zi.button} ${Zi.zoomOut}">
            <svg
                xmlns="http://www.w3.org/2000/svg"
                viewBox="0 0 32 32"
                fill="currentColor"
                width="32"
                height="32"
            >
                <path d="M8 15h16v2H8z"></path>
            </svg>
        </button>
    </div>
`;class w_ extends Vi{constructor(e,t){super(e,XI,t),this._zoomIn=i=>{i.preventDefault(),this._map.setZoom(this._map.getZoom()+1,{duration:400})},this._zoomOut=i=>{i.preventDefault(),this._map.setZoom(this._map.getZoom()-1,{duration:400})},this._checkZoom=()=>{const i=this._map.getZoom();i<=this._map.getMinZoom()?this._zoomOutButton.disabled=!0:this._zoomOutButton.disabled=!1,i>=this._map.getMaxZoom()?this._zoomInButton.disabled=!0:this._zoomInButton.disabled=!1},this._map=e,this._zoomInButton=this._wrap.querySelector(`.${Zi.zoomIn}`),this._zoomOutButton=this._wrap.querySelector(`.${Zi.zoomOut}`),this._zoomInButton.addEventListener("click",this._zoomIn),this._zoomOutButton.addEventListener("click",this._zoomOut),this._map.on("zoom",this._checkZoom)}destroy(){this._map.off("zoom",this._checkZoom),this._zoomInButton.removeEventListener("click",this._zoomIn),this._zoomOutButton.removeEventListener("click",this._zoomOut),super.destroy()}}const Wi={root:"mapgl_ON-gf73kIU0-",button:"mapgl_mWyZxMObEi8-",none:"mapgl_FwnEmRmDBLg-",easy:"mapgl_uSuUHuf71nM-",medium:"mapgl_LdqAv9Ly624-",hard:"mapgl_udRZCM1quWE-"},$I=`<svg xmlns="http://www.w3.org/2000/svg" width="20" height="14" viewBox="0 0 20 14" style="margin-top: 4px">
    <path d="M 18,5 C 18,4 17,1 15,1 H 12 10 C 8,1 7,4 7,5 H 5 v 2 h 1 v 4 c 0,0.6 0,1 1,1 v 2 h 2 v -2 h 7 v 2 h 2 v -2 c 1,0 1,-0.4 1,-1 V 7 h 1 V 5 H 18 z M 10,3 h 2 3 c 2,0 2,1 2,3 H 8 C 8,4 8,3 10,3 z M 9,10 H 8 C 7.4,10 7,9.6 7,9 7,8.4 7.4,8 8,8 h 1 c 0.6,0 1,0.4 1,1 0,0.6 -0.4,1 -1,1 z m 8,0 H 16 C 15.4,10 15,9.6 15,9 15,8.4 15.4,8 16,8 h 1 c 0.6,0 1,0.4 1,1 0,0.6 -0.4,1 -1,1 z M 4,4 H 6 V 3 H 4 C 1,3 1,6 1,7 H 0 v 1 h 1 v 4 H 3 V 11 H 5 V 7 H 2 C 2,6 2,4 4,4 z M 3,9 4,10 H 2 V 9 h 1 z" fill="#616161" fill-rule="evenodd"/>
    <g fill="#fff">
        <path d="m 16,8 h 1 c 0.4,0 0.7,0.2 0.8,0.5 C 17.9,8.4 18,8.2 18,8 18,7.4 17.6,7 17,7 h -1 c -0.6,0 -1,0.4 -1,1 0,0.2 0.1,0.4 0.2,0.5 C 15.3,8.2 15.6,8 16,8 z"/>
        <path d="M 8,8 H 9 C 9.4,8 9.7,8.2 9.8,8.5 9.9,8.4 10,8.2 10,8 10,7.4 9.6,7 9,7 H 8 C 7.4,7 7,7.4 7,8 7,8.2 7.1,8.4 7.2,8.5 7.3,8.2 7.6,8 8,8 z"/>
        <path d="M 6,3 H 4 C 4,3 4,3 4,3 2,3 2,5 2,6 H 2 C 2.1,5 2.5,4 4,4 H 5 6 V 3 z"/>
        <path d="M0 7H1V8H0z"/>
        <path d="M 15,2 H 12 10 C 8,2 8,3 8,5 H 8 C 8,3.7 8.3,3 10,3 h 2 3 c 1.7,0 1.9,0.7 2,2 h 0 C 17,3 17,2 15,2 z"/>
        <path d="M3 9L4 9 3 8 2 8 2 9 2 9 2 9 3 9z"/>
        <path d="M 7,11 C 6,11 6,10.6 6,10 v 1 c 0,0.6 0,1 1,1 v -1 z"/>
        <path d="m 18,11 v 1 c 1,0 1,-0.4 1,-1 v -1 c 0,0.6 0,1 -1,1 z"/>
        <path d="M19 6H20V7H19z"/>
        <path d="M3 11L1 11 1 12 3 12 3 11 5 11 5 7 5 7 5 10 3 10z"/>
        <path d="M16 13H18V14H16z"/>
        <path d="M5 6H6V7H5z"/>
        <path d="M9 13L7 13 7 14 9 14 9 12 16 12 16 11 9 11z"/>
    </g>
    <g fill="#444">
        <path d="M 2,6 C 2,6.4 2,6.7 2,7 H 5 V 6 H 2 z"/>
        <path d="M2 9L2 10 4 10 3 9z"/>
        <path d="M 4,3 H 6 V 2 H 4 C 1,2 1,5 1,6 H 0 V 7 H 1 C 1,6 1,3 4,3 z"/>
        <path d="M 18,4 C 18,3 17,0 15,0 H 12 10 C 8,0 7,3 7,4 H 6 5 V 5 H 7 C 7,4 8,1 10,1 h 2 3 c 2,0 3,3 3,4 h 2 V 4 h -2 z"/>
        <path d="M 8,10 H 9 C 9.6,10 10,9.6 10,9 10,8.8 9.9,8.6 9.8,8.5 9.7,8.8 9.4,9 9,9 H 8 C 7.6,9 7.3,8.8 7.2,8.5 7.1,8.6 7,8.8 7,9 c 0,0.6 0.4,1 1,1 z"/>
        <path d="M 17,6 C 17,5.6 17,5.3 17,5 H 8 c 0,0.3 0,0.6 0,1 h 9 z"/>
        <path d="M 17.8,8.5 C 17.7,8.8 17.4,9 17,9 H 16 C 15.6,9 15.3,8.8 15.2,8.5 15.1,8.6 15,8.8 15,9 c 0,0.6 0.4,1 1,1 h 1 c 0.6,0 1,-0.4 1,-1 0,-0.2 -0.1,-0.4 -0.2,-0.5 z"/>
    </g>
</svg>
`;class N_ extends Vi{constructor(e,t){super(e,"",t),this._onClick=i=>{i.preventDefault(),this._map.isTrafficOn()?this._map.hideTraffic():this._map.showTraffic()},this._map=e,this._render(),e.on("trafficscore",({score:i})=>{this._score=i,this._render()}),e.on("trafficshow",()=>{this._render()}),e.on("traffichide",()=>{this._render()})}_render(){const e=this._map.isTrafficOn()?qI(this._score):Wi.none,t=`
            <div class="${Wi.root}">
                <button type="button" class="${Wi.button} ${e}">
                    ${this._map.isTrafficOn()&&this._score!==void 0?this._score:$I}
                </button>
            </div>
        `;this._wrap.innerHTML=t,this._wrap.querySelector(`.${Wi.button}`).addEventListener("click",this._onClick)}}function qI(s){return s===void 0?"":s>6?Wi.hard:s>3?Wi.medium:Wi.easy}const js={container:"mapgl_K-1Yb8HCVpQ-",logos:"mapgl_CLps5xx6CNs-"};var k_=(s=>(s.osm="osm",s.api="api",s.license="license",s))(k_||{});const YI=`<a href="https://dev.2gis.ru/link_api_map" target="_blank" style="height: 20px;">
    <svg width="40" height="20" viewBox="0 0 40 20" fill="none" xmlns="http://www.w3.org/2000/svg">
        <path d="M2.00011 8.72731C1.98229 5.72738 4.05025 4 6.80779 4C9.47674 4 11.2797 5.58179 11.2797 8.05437C11.2797 10.1091 10.0602 11.2546 7.99196 12.2727C7.21431 12.6547 6.34807 13.1818 5.46454 13.4544H11.3681V16H2.00011V12.66C3.85604 12.0235 4.88111 11.3271 6.59576 10.4728C7.90363 9.81815 8.71666 9.23633 8.71666 8.1819C8.71666 7.16358 7.97439 6.36366 6.80779 6.36366C5.27006 6.36366 4.52753 7.52729 4.56292 8.72731H2.00011Z" fill="#6E7173"/>
        <path d="M23.6348 9.63643V10.5453C23.6348 13.5455 21.6552 16 18.067 16C14.6202 16 12.2518 13.4727 12.2518 9.99986C12.2518 6.52731 14.5497 4 18.1554 4C21.2487 4 23.1751 5.8363 23.6348 7.99991H21.0717C20.6301 6.96353 19.534 6.36366 18.2261 6.36366C15.9813 6.36366 14.7263 8.14523 14.7263 9.99986C14.7263 11.8545 15.9991 13.6363 18.2086 13.6363C19.5872 13.6363 20.736 12.9456 21.0896 11.8181H17.7313V9.63643H23.6348Z" fill="#6E7173"/>
        <path d="M27.4528 16H24.9783V4H27.4528V16Z" fill="#6E7173"/>
        <path d="M38.4292 7.63648H35.8662C35.6185 6.85461 34.947 6.18167 33.4446 6.18167C32.1543 6.18167 31.5004 6.69096 31.5004 7.41809C31.5004 8.30915 32.7375 8.56366 34.293 8.83623L34.361 8.84818C36.4076 9.20779 38.5 9.57545 38.5 12.2727C38.5 14.8 36.4672 16 33.7274 16C31.1998 16 28.9373 14.4727 28.6899 12.1818H31.2527C31.5712 13.1273 32.5079 13.8181 33.8512 13.8181C35.1415 13.8181 35.8662 13.3818 35.8662 12.5455C35.8662 11.514 34.3606 11.2653 32.8555 11.0167C32.8221 11.0112 32.7887 11.0056 32.7553 11.0001C31.1468 10.7273 28.8844 9.9818 28.8844 7.54535C28.8844 5.34534 30.7581 4 33.5332 4C36.2727 4 38.164 5.41814 38.4292 7.63648Z" fill="#6E7173"/>
    </svg>
</a>`,QI=`<a href="https://dev.urbi.ae" target="_blank" style="height: 20px; line-height: 20px;">
    <svg style="width: auto; height: 16px;" width="29" height="12" viewBox="0 0 29 12" fill="none" xmlns="http://www.w3.org/2000/svg">
        <path fill-rule="evenodd" clip-rule="evenodd" d="M5 4V8.0625C5 9.13823 4.64701 9.5 3.75 9.5C3.00479 9.5 2.5 9.15185 2.5 8.0625V4H0V8.5C0 10.6515 1.45917 12 3.75 12C6.19263 12 7.5 10.6515 7.5 8.5V4H5ZM18.5 9.5V2H16V11.9993L20.5 12C23.013 12.0276 24.5 10.4576 24.5 8C24.5 5.4872 23.2711 4 20.5 4H19.5V6.5H20.5C21.6954 6.5 22 6.9645 22 8C22 9.06311 21.3422 9.51381 20.5 9.5H18.5ZM13 4C12.1529 4 11.7541 4.19542 11.5 5L11 4H9.01412V12H11.5V7.75C11.5 6.87606 12.1106 6.5 13 6.5H15V4H13ZM28.25 12V4H25.75V12H28.25ZM27 3C27.9508 3 28.75 2.32569 28.75 1.5C28.75 0.674312 27.9508 0 27 0C26.0492 0 25.25 0.674312 25.25 1.5C25.25 2.32569 26.0492 3 27 3Z" fill="#6E7173"/>
    </svg>
</a>`,U_=s=>`
    <div class=${js.container}>
        <div class=${js.logos}>
            ${s==="2gis"?YI:QI}
        </div>
    </div>
`,JI=200,Ci=.4,KI=6.9,eP={features:[{type:"Feature",properties:{},geometry:{coordinates:[[[31.287134399571926,46.13828663057069],[32.75238568004798,45.79865765372267],[33.58288063506086,46.01903186613521],[33.61486347995313,46.2235364272577],[33.78934942202696,46.198543888421256],[35.00827602994491,45.75534495217423],[35.2288647404554,45.79620376974098],[35.17718890419883,45.90635851081622],[35.435536217844785,46.10280090340363],[35.79210757517962,46.37361688082296],[36.11428232078944,46.29643073207143],[36.55169983042855,46.510726153023995],[36.8324385653631,46.4588228565425],[37.14524285843429,46.69589191473136],[37.39260951621397,46.689280151379506],[37.627431059848774,46.82264082535376],[38.1229012131082,46.84212508154449],[38.33448922300602,46.97422615512966],[38.224662200013626,47.230888527366346],[38.32912700579817,47.25438400708447],[38.34419757143178,47.312784332059664],[38.21546574161874,47.30909993831261],[38.254518753011865,47.36826000208279],[38.31067651491526,47.38482171052604],[38.321606223663025,47.571364572295465],[38.3617938178036,47.57882910808604],[38.36170197978049,47.618956233608515],[38.45674637734251,47.62208601169297],[38.46107375227305,47.64691148544472],[38.63803321177437,47.647842642655746],[38.672098728783254,47.68762314810277],[38.775725461608346,47.68709376851825],[38.8049944923477,47.813690288503295],[38.834920351813224,47.8196727375917],[38.84241614380997,47.85748354545768],[39.07247756595089,47.86497172354581],[39.10052537670751,47.840884138531834],[39.38214421832214,47.86795888702861],[39.40746330974267,47.8256169720315],[39.482844878880115,47.85023053453213],[39.53382832770623,47.81883936134608],[39.73848854131376,47.82763637975813],[39.79371699101341,47.869042802541685],[39.83078252402845,47.99974474342423],[39.77863815152742,48.03277123184873],[39.88321233741743,48.03971572761765],[39.870917803736376,48.113006872810985],[39.93505319594328,48.18105768715421],[39.94606694701065,48.22361687262517],[40.01236868994266,48.22433847068592],[40.03218509167988,48.26056076274611],[39.984065212024376,48.320002192647365],[39.922439044370975,48.29188408842856],[39.851945001258656,48.331239182362935],[39.94636538164761,48.35223341528243],[39.941853222859265,48.388067879458134],[39.899783141900656,48.45166958120498],[39.85004077188802,48.47107700658495],[39.85404334598155,48.49815859245703],[39.871488094298144,48.507759719913],[39.83989084312387,48.58511601134842],[39.690955803936305,48.59154349398949],[39.668972082370914,48.61595180677952],[39.71340429381095,48.65723964838148],[39.72739208280473,48.68576344104625],[39.720852030234056,48.70453377084817],[39.71060957078353,48.71895533887451],[39.72773821117514,48.727349762777976],[39.742522688889096,48.74565876284592],[39.73675984758131,48.75923566351821],[39.75294236354742,48.76535707528038],[39.77230712573868,48.765131537231696],[39.78708527484656,48.792695126714506],[39.79951920927968,48.83846452038483],[39.97324551864918,48.788853683331496],[40.0854569051011,48.87270686936236],[40.054991236497585,48.91511705296017],[40.01572101314082,48.91564488817568],[39.985747700540486,48.87433169550951],[39.92581794882187,48.895346707874324],[39.85691072202724,48.89266055501065],[39.84380033698696,48.90643237682923],[39.77980530005851,48.92505561008153],[39.76769275004051,48.96624269122293],[39.75249250304927,48.988397421631134],[39.72953342924575,48.98364479695306],[39.6963475099607,49.006204908207565],[39.67412801512273,48.99350840477692],[39.688776866237845,49.04629763624743],[39.77599141224027,49.03984390969006],[39.80998946255809,49.05657174933967],[39.94020528746006,49.054672146531885],[39.94517686594733,49.08306814321608],[40.03354656530658,49.17940433543734],[40.08179564952226,49.187957220033326],[40.127812302222935,49.23339833688371],[40.21735722846822,49.24434936924021],[40.23083631365782,49.264375707391025],[40.184193609561845,49.28357807698788],[40.20554425700146,49.348627711592286],[40.0352506597566,49.460305560239135],[40.042265513048875,49.52110947883719],[40.17301947712943,49.570462036839785],[40.135367644468886,49.619991840168154],[39.930446598607006,49.58753811881613],[39.89326483911972,49.561338740411344],[39.80152397436578,49.5648154530997],[39.747824755329106,49.601752391386356],[39.65652368638126,49.620013992728445],[39.59591913143757,49.727977277611615],[39.43167355486196,49.76704897880802],[39.38482981859343,49.7428519723461],[39.28679269123114,49.7589376228415],[39.23167115889703,49.80067773683314],[39.23126430925569,49.83799228995301],[39.184177982005934,49.89212328019818],[38.939466721594385,49.8129411626972],[38.67999394500015,49.99954348208959],[38.498971405582154,49.969630683120045],[38.36122588838947,50.008962505581735],[38.33064743770436,50.10587365547255],[38.179344250662524,50.08108187117696],[38.17324129258458,49.96421343242167],[38.0243275352658,49.9126740335152],[38.00390141376576,49.80621204332192],[37.9339784494789,49.72626072303203],[37.997665462537555,49.705679809807805],[37.98195913415958,49.63338227733652],[37.87841001479606,49.55639540561637],[37.8726905583969,49.314558240834856],[37.83487442598039,49.211403426079585],[37.568531160033984,49.23978324969454],[37.49068171343487,49.18083483226363],[37.467253126665184,49.08118016596504],[37.29258016280227,48.98322524059054],[37.27222555931064,48.936467375391885],[36.983084082742096,48.80186787172613],[36.72382254183347,48.816637155788754],[36.863697512625095,48.16812695432242],[36.85276964213293,48.06101666035238],[36.63699950073965,48.1120861847823],[36.55643334225425,48.079707051057994],[36.5326892781749,47.85663993329777],[36.15757828505022,47.87029971236788],[36.007257866960344,48.150801757163464],[35.84084530869785,48.072372143164614],[35.69001200739808,48.14916424481041],[34.84251652180234,48.13828093857032],[34.93636037372508,47.54124693653375],[34.561002995692604,47.57138977148597],[33.975870854429644,47.468842659893966],[33.94579238047862,47.53020932511487],[33.65802349898351,47.49630012349715],[33.57945696368617,47.61817363276853],[33.07047295330287,47.579949515419315],[33.106438567586736,47.23712252316682],[32.87965855893614,47.10939623564883],[32.94045936300873,47.00638816222238],[32.531962255274834,46.887846448242044],[32.23541823078415,46.84566846340053],[31.99589893588245,46.69298741295057],[31.792169481175108,46.355938076969124],[31.231245271853055,46.42046225841926],[31.287134399571926,46.13828663057069]]],type:"Polygon"}}]};class tP extends Vi{constructor(e,t){super(e,U_(t.copyrightType),t),this._copyrightType="2gis",this._isHidden=!1,this._onViewportchange=()=>{this._throttledVisibleCopyright()},this._onClick=r=>{if(r.target&&nP(r.target)){const o=r.target.dataset.type;iP(o)&&this._map.emit("copyrightclick",{type:o,href:r.target.href,originalEvent:r})}},this._copyrightType=t.copyrightType,this._map=e,this._map._impl.on("viewportchange",this._onViewportchange),this._map._impl.on("idle",this._onViewportchange),t.interactive===!1&&(this._wrap.style.pointerEvents="none"),this._wrap.querySelector(`.${js.container}`).addEventListener("click",this._onClick),this._throttledVisibleCopyright=n.throttle(()=>{this.update()},JI)}destroy(){this._map._impl.off("viewportchange",this._onViewportchange),this._map._impl.off("idle",this._onViewportchange),this._wrap.querySelector(`.${js.container}`).removeEventListener("click",this._onClick),super.destroy()}update(){let e=!1;if(this._map.getZoom()>KI){const t=this._map.getSize(),i=this._map._impl.unproject([t[0]*Ci,t[1]*Ci]),r=this._map._impl.unproject([t[0]*(1-Ci),t[1]*Ci]),o=this._map._impl.unproject([t[0]*Ci,t[1]*(1-Ci)]),a=this._map._impl.unproject([t[0]*(1-Ci),t[1]*(1-Ci)]);e=rP([i,r,a,o,i],eP.features[0].geometry.coordinates[0])}e&&!this._isHidden&&(this._isHidden=!0,super.getContainer().innerHTML=""),!e&&this._isHidden&&(this._isHidden=!1,super.getContainer().innerHTML=U_(this._copyrightType))}}function iP(s){return s!==void 0&&s in k_}function nP(s){return s&&"href"in s&&"dataset"in s}function rP(s,e){for(let t=0;t<s.length-1;t++){const i=s[t],r=s[t+1];for(let o=0;o<e.length-1;o++){const a=e[o],l=e[o+1];if(sP(i,r,a,l))return!0}}return!!(M_(s[0],e)||M_(e[0],s))}function sP(s,e,t,i){const r=Xs(t,i,s),o=Xs(t,i,e),a=Xs(s,e,t),l=Xs(s,e,i);return!!((r>0&&o<0||r<0&&o>0)&&(a>0&&l<0||a<0&&l>0)||r===0&&$s(t,i,s)||o===0&&$s(t,i,e)||a===0&&$s(s,e,t)||l===0&&$s(s,e,i))}function Xs(s,e,t){return(e[0]-s[0])*(t[1]-s[1])-(e[1]-s[1])*(t[0]-s[0])}function $s(s,e,t){return Math.min(s[0],e[0])<=t[0]&&t[0]<=Math.max(s[0],e[0])&&Math.min(s[1],e[1])<=t[1]&&t[1]<=Math.max(s[1],e[1])}function M_(s,e){const[t,i]=s;let r=!1;for(let o=0,a=e.length-1;o<e.length;a=o++){const[l,c]=e[o],[d,u]=e[a];c>i!=u>i&&t<(d-l)*(i-c)/(u-c)+l&&(r=!r)}return r}const H_={wrap:"mapgl_r8Wn2E5pGh0-",container:"mapgl_ir0vRf5QXrk-"};class oP{constructor(e,t){this.rootContainer=e._impl.modules.layout.rootContainer,this.content=t,this.isShown=!1}display(){this.isShown||(this.wrap||(this.wrap=this.initWrap()),this.rootContainer.appendChild(this.wrap),this.isShown=!0)}hide(){this.isShown&&(this.wrap&&this.rootContainer.removeChild(this.wrap),this.isShown=!1)}isDisplayed(){return this.isShown}}const aP=` <div class=${H_.container}>Your MapGL key is invalid. Please contact api@2gis.com to get MapGL key.</div> `;class lP extends oP{constructor(e){super(e,aP),e._impl.on("error",t=>{t.type==="invalidtilekey"&&(this.isDisplayed()||this.display())})}initWrap(){const e=document.createElement("div");return e.classList.add(`${H_.wrap}`),e.innerHTML=this.content,e}}class G_{constructor(e){this.northEast=e.northEast,this.southWest=e.southWest}extend(e){return this.southWest=[Math.min(this.southWest[0],e[0]),Math.min(this.southWest[1],e[1])],this.northEast=[Math.max(this.northEast[0],e[0]),Math.max(this.northEast[1],e[1])],this}getCenter(){return[(this.southWest[0]+this.northEast[0])/2,(this.southWest[1]+this.northEast[1])/2]}containsPoint(e){const[t,i]=e,r=t>=this.southWest[0]&&t<=this.northEast[0],o=i>=this.southWest[1]&&i<=this.northEast[1];return r&&o}containsBounds(e){const{southWest:t,northEast:i}=e,r=this.containsPoint(t),o=this.containsPoint(i);return r&&o}intersects(e){const{southWest:t,northEast:i}=e,r=this.getPointRelatedLocation(t),o=this.getPointRelatedLocation(i),a=+r.N+ +o.N,l=+r.S+ +o.S,c=+r.W+ +o.W,d=+r.E+ +o.E;return!(a===2||l===2||c===2||d===2)}getPointRelatedLocation(e){return{S:e[1]<this.southWest[1],N:e[1]>this.northEast[1],W:e[0]<this.southWest[0],E:e[0]>this.northEast[0]}}}const Ve={root:"mapgl_h2pl79nAYpk-",container:"mapgl_64D1bmNQN3Q-",scroller:"mapgl_jdJbkjpLO7k-",content:"mapgl_54Rmy50n6Fw-",control:"mapgl_3i1QoGerxio-",label:"mapgl_wGplqJ4hHPc-",mm:"mapgl_GbM3JIwbvBI-",icon:"mapgl_MX6K1s-5thI-",floorLevelName:"mapgl_aMwUNIDCavU-"},cP=`
    <div class="${Ve.root}">
        <div class="${Ve.container}">
            <div class="${Ve.scroller}">
                <div class="${Ve.content}" />
            </div>
        </div>
    </div>
`,dP=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M12.1142 14.1859L23.2303 9.29482L18.0571 1.2998L5.55708 5.01563L5.56217 5.04408L0.599976 10.0063L1.95007 11.3564L5.59996 7.70647L6.39699 6.90943L7.09339 7.79575L12.1142 14.1859ZM21.8071 12.1061L15.1198 15.0485L12.8071 16.1326V22.6321L21.8071 18.4131V12.1061ZM6.21714 9.91771L3.21617 12.9187V18.8564L5.50707 19.9405V14.9136L8.00707 15.9136V21.1236L10.8071 22.4487V15.7594L6.21714 9.91771Z" fill="#0059D6"/>
</svg>`,V_=`<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="20px" height="20px" viewBox="337.5 232.3 125 85.9" xml:space="preserve">
<polygon fill="#FF0013" points="453.9,306.2 424.7,232.3 400,275.5 375.4,232.3 346.1,306.2 337.5,306.2 337.5,317.4 381.7,317.4 381.7,306.2 375.1,306.2 381.5,287.8 400,318.2 418.5,287.8 424.9,306.2 418.3,306.2 418.3,317.4 462.5,317.4 462.5,306.2 "/>
</svg>`;class Z_ extends Vi{constructor(e,t){super(e,cP,t),this._removeButtonsEventListeners=()=>{this._content&&this._content.childNodes.forEach(i=>{if(this._handlers.has(i)){const r=this._handlers.get(i);r!==void 0&&i.removeEventListener("click",r)}})},this._showControl=i=>{var d;const{currentFloor:r,id:o,floorNames:a,metro:l,mode:c}=i;this._floor={mode:c,currentFloorLevelIndexByMode:V(I({},(d=this._floor)==null?void 0:d.currentFloorLevelIndexByMode),{[c]:r}),floorPlanId:o,floorNames:a,metro:l},this._root.style.display="block",this._renderControl()},this._hideControl=()=>{this._map._impl.state.floorsEnabled&&(this._removeButtonsEventListeners(),this._floor=void 0,this._root.style.display="none")},this._onLevelChange=i=>{this._switchCurrentFloorLevel({floorMode:i.floorMode,floorIndex:i.floorLevelIndex})},this._controlHandler=(i,r)=>o=>{var a,l;o.preventDefault(),this._switchCurrentFloorLevel({floorMode:i,floorIndex:r}),this._floor&&this._map._impl.changeFloorNumber(i==="metro"&&((a=this._floor.metro)!=null&&a.id)?(l=this._floor.metro)==null?void 0:l.id:this._floor.floorPlanId,i==="building"?"building":r)},this._map=e,this._root=this._wrap.querySelector(`.${Ve.root}`),this._content=this._wrap.querySelector(`.${Ve.content}`),this._handlers=new WeakMap,this._root.style.display="none",this._map._impl.on("floorcomplexin",this._showControl),this._map._impl.on("floorcomplexout",this._hideControl),this._map.on("floorlevelchange",this._onLevelChange)}destroy(){this._map._impl.off("floorcomplexin",this._showControl),this._map._impl.off("floorcomplexout",this._hideControl),this._map.off("floorlevelchange",this._onLevelChange),this._removeButtonsEventListeners(),super.destroy()}_renderControl(){var o,a,l;if(!this._floor)return;this._content.innerHTML="";let e;const t=this._floor.metro&&((o=this._floor.metro)==null?void 0:o.floorNames.length)>1;(a=this._floor.metro)==null||a.floorNames.forEach((c,d)=>{const u=document.createElement("button");if(u.name=`metro-${d.toLocaleString()}`,u.type="button",u.className=Ve.control,!t)u.innerHTML=V_;else{const _=document.createElement("div");_.className=`${Ve.label} ${Ve.mm}`;const f=document.createElement("div");f.className=Ve.icon,f.innerHTML=V_;const m=document.createElement("div");m.className=Ve.floorLevelName,m.textContent=c,_.append(f,m),u.append(_)}this._floor&&this._floor.mode==="metro"&&this._floor.currentFloorLevelIndexByMode.metro===d&&(u.disabled=!0,e=u);const h=this._controlHandler("metro",d);u.addEventListener("click",h),this._handlers.set(u,h),this._content.append(u)}),this._floor.floorNames.forEach((c,d)=>{const u=document.createElement("button");u.className=Ve.control;const h=document.createElement("div");h.className=Ve.label,h.textContent=c,u.append(h),u.name=`floor-${d.toLocaleString()}`,u.type="button",this._floor&&this._floor.mode==="floor"&&this._floor.currentFloorLevelIndexByMode.floor===d&&(u.disabled=!0,e=u);const _=this._controlHandler("floor",d);u.addEventListener("click",_),this._handlers.set(u,_),this._content.append(u)});const i=document.createElement("button");i.className=`${Ve.control}`,i.innerHTML=`<div class="${Ve.label}">${dP}</div>`,i.name="building",i.type="button",this._floor&&this._floor.mode==="building"&&(i.disabled=!0,e=i);const r=this._controlHandler("building",NaN);if(i.addEventListener("click",r),this._handlers.set(i,r),this._content.append(i),e&&e.offsetTop){const c=(l=e.parentElement)==null?void 0:l.parentElement;c&&(c.scrollTop=e.offsetTop)}}_switchCurrentFloorLevel(e){if(!this._floor)return;const t=this._floor.mode==="building"?"building":this._floor.mode==="metro"?`metro-${this._floor.currentFloorLevelIndexByMode.metro}`:`floor-${this._floor.currentFloorLevelIndexByMode.floor}`,i=this._wrap.querySelector(`.${Ve.control}[name="${t}"]`);i&&(i.disabled=!1);const r=this._wrap.querySelector(e.floorMode==="building"?`.${Ve.control}[name="building"]`:e.floorMode==="metro"?`.${Ve.control}[name="metro-${e.floorIndex}"]`:`.${Ve.control}[name="floor-${e.floorIndex}"]`);r&&(r.disabled=!0),e.floorMode!=="building"?(this._floor.mode=e.floorMode,this._floor.currentFloorLevelIndexByMode[e.floorMode]=e.floorIndex):this._floor.mode="building"}}const Cl={controlPane:"mapgl_z0m6n5pr5no-",container:"mapgl_ITPUswrhaGk-",topLeft:"mapgl_Px-KwzXdVa0-",topCenter:"mapgl_SCX3EYsS-Cw-",topRight:"mapgl_i42TyWqpCPk-",centerLeft:"mapgl_-zKby6nN-nU-",centerRight:"mapgl_SlQM4-ZNKF0-",bottomLeft:"mapgl_lNg3h7Hg-Mo-",bottomCenter:"mapgl_grOepPBwilk-",bottomRight:"mapgl_CiHYefDPhI0-"},Yn=10;class uP{constructor(e,t){this.wrap=document.createElement("div"),this.wrap.className=Cl.controlPane,this.containers={};const{rootContainer:i}=e._impl.modules.layout;i.appendChild(this.wrap),this.padding={top:Yn,right:Yn,bottom:Yn,left:Yn},this.setPadding(t.padding||{})}setPadding(e){Object.keys(this.padding).forEach(t=>{var r;const i=t;this.padding[i]=(r=e[i])!=null?r:Yn,this.wrap.style[`margin${i.replace(/^\w/,o=>o.toUpperCase())}`]=`${this.padding[i]}px`})}getPadding(){return I({},this.padding)}destroy(){this.wrap.remove()}getContainerByPosition(e){let t=this.containers[e];return t||(t=this.containers[e]=this._initControlContainer(e)),t}_initControlContainer(e){const t=document.createElement("div");return t.classList.add(Cl.container,Cl[e]),this.wrap.appendChild(t),t}}const W_={root:"mapgl_9m2ynAxdBT0-",label:"mapgl_sR4nXEQ3L2M-"},qs={meter:{en:"m",ru:"м"},kilometer:{en:"km",ru:"км"}},hP=66;class j_ extends Vi{constructor(e,t){super(e,"",t),this._render=()=>{const{state:i}=this._map._impl,r=!!i.styleState.globeEnabled&&i.zoom<n.globeConfig.globeMaxZoom;if(this._wrap.hidden!==r&&(this._wrap.hidden=r),r)return;const o=this._wrap.getBoundingClientRect(),a=this._calcSize([o.x,o.y],o.width||hP,0),l=_P(a,this._map.getLanguage());(!this._root||!this._label||this._root.parentNode!==this._wrap||this._label.parentNode!==this._root)&&(this._root=document.createElement("div"),this._root.className=W_.root,this._label=document.createElement("div"),this._label.className=W_.label,this._root.appendChild(this._label),this._wrap.textContent="",this._wrap.appendChild(this._root)),this._label.textContent!==l&&(this._label.textContent=l)},this._map=e,this._render(),e.on("zoom",this._render),e.on("pitch",this._render),e.on("changeLanguage",this._render),e.on("move",this._render),e.on("resize",this._render)}destroy(){this._map.off("zoom",this._render),this._map.off("pitch",this._render),this._map.off("changeLanguage",this._render),this._map.off("move",this._render),this._map.off("resize",this._render),super.destroy()}_calcSize(e,t,i){return n.getMetersFromPixelsXY(this._map.getCenter(),this._map.getZoom(),this._map.getRotation(),this._map.getSize(),this._map.getPitch(),e,void 0,this._map.getPadding(),t,i)}}function _P(s,e){return s<1e3?`${s} ${qs.meter[e]||qs.meter.en}`:`${(s/1e3).toFixed(1)} ${qs.kilometer[e]||qs.kilometer.en}`}class X_{constructor(e){this._impl=e._impl.getDefaultSource()}setFeatureStateMap(e){this._impl.setFeatureStateMap(e)}}function st(s,e){const t=I({},s);for(const i in e){const r=i;t[r]===void 0&&(t[r]=e[r])}return t}const fP={center:[0,0],zoom:0,minZoom:Vs.minZoom,maxZoom:Vs.maxZoom,rotation:0,touchRotationThreshold:10,pitch:0,minPitch:0,maxPitch:45,lowZoomMaxPitch:45,viewport:{top:0,right:0,bottom:0,left:0},padding:{top:0,right:0,bottom:0,left:0},style:"",lang:"en",iconIdentifyOpacity:.3,disableHidingPois:!1,disableHoverStyles:!1,disableZoomOnScroll:!1,disableDragging:!1,enableTwoFingerDragging:!1,disableRotationByUserInteraction:!1,disablePitchByUserInteraction:!1,defaultBackgroundColor:"#f6f2de",disableIconCache:!1,mobileSdkMode:!1,skipElevationAnimation:!1,enableTrackResize:!1,showDefaultTileBounds:!1,immersiveOn:!1,pitchHightLimitation:90,loopWorld:!1,cityCommPoiLabelingConfig:n.cityCommPoiLabelingConfig,disableRenderingCache:!1,disableStyleFallback:!1,fontUrl:"",modelUrl:"",iconUrl:"",keyUrl:"",disableModelsGrowthAnimation:!1,disableLayerAnimation:!1,trafficOn:!1,allowMetro:!1,metro3dVisible:!1,resetFloorModeOnActivation:!1,forceSyncIdentify:!1,sharedModelsPath:vC,antiAliasingMode:"taa"};let mP=class extends ni{constructor(e,t){var l;super();let i;if(typeof e=="string"){const c=document.getElementById(e);if(c)i=c;else throw new Error(`Could not found html element with id: ${e}`)}else i=e;const r=I({},t.styleOptions),o=st(this._validateOptions(t),fP),a=V(I({},o),{disableHoverStyles:(l=t.disableHoverStyles)!=null?l:!0,tileServer:t.tileServer||fC,style:t.style||n.DEFAULT_MAPGL_STYLE,styleOptions:r,styleState:t.styleState,sessionId:bl(),tileSessionId:t.tileSessionId});this._impl=new yl(i,a),this._impl.on("idle",c=>this._emitMapEvent("idle",c)).on("ready",c=>this._emitMapEvent("ready",c)).on("resize",c=>this._emitMapEvent("resize",c)).on("move",c=>this._emitMapEvent("move",c)).on("movestart",c=>this._emitMapEvent("movestart",c)).on("moveend",c=>this._emitMapEvent("moveend",c)).on("center",c=>this._emitMapEvent("center",c)).on("centerstart",c=>this._emitMapEvent("centerstart",c)).on("centerend",c=>this._emitMapEvent("centerend",c)).on("zoom",c=>this._emitMapEvent("zoom",c)).on("zoomstart",c=>this._emitMapEvent("zoomstart",c)).on("zoomend",c=>this._emitMapEvent("zoomend",c)).on("rotation",c=>this._emitMapEvent("rotation",c)).on("rotationstart",c=>this._emitMapEvent("rotationstart",c)).on("rotationend",c=>this._emitMapEvent("rotationend",c)).on("pitch",c=>this._emitMapEvent("pitch",c)).on("pitchstart",c=>this._emitMapEvent("pitchstart",c)).on("pitchend",c=>this._emitMapEvent("pitchend",c)).on("trafficshow",()=>this.emit("trafficshow")).on("traffichide",()=>this.emit("traffichide")).on("floorcomplexshow",({id:c,currentFloor:d,floorNames:u,mode:h})=>this.emit("floorplanshow",{floorPlanId:c,currentFloorLevelIndex:d,floorLevels:u.map((_,f)=>({floorLevelIndex:f,floorLevelName:_})),floorMode:h==="metro"?"metro":"floor"})).on("floorcomplexhide",c=>this.emit("floorplanhide",{floorPlanId:c.id})).on("floorcomplexlevelchange",c=>this.emit("floorlevelchange",{floorLevelName:c.floorName,floorLevelIndex:c.floorIndex,floorPlanId:c.id,floorMode:c.floorMode})).on("floorsactivegroupchange",c=>this.emit("floorsactivegroupchange",c)).on("modelshow",c=>this.emit("modelshow",c)).on("modelhide",c=>this.emit("modelhide",c)),this._impl.on("click",c=>this._emitMapPointerEvent("click",c)).on("dblclick",c=>this._emitMapPointerEvent("dblclick",c)).on("contextmenu",c=>this._emitMapPointerEvent("contextmenu",c)).on("mousemove",c=>this._emitMapPointerEvent("mousemove",c)).on("mouseover",c=>this._emitMapPointerEvent("mouseover",c)).on("mouseout",c=>this._emitMapPointerEvent("mouseout",c)).on("mousedown",c=>this._emitMapPointerEvent("mousedown",c)).on("mouseup",c=>this._emitMapPointerEvent("mouseup",c)).on("touchstart",c=>this._emitMapPointerEvent("touchstart",c)).on("touchend",c=>this._emitMapPointerEvent("touchend",c)).on("touchmove",c=>this._emitMapPointerEvent("touchmove",c)),this._impl.on("error",c=>this._emitMapErrorEvent("error",c)),this._impl.on("trafficscore",({score:c})=>this.emit("trafficscore",{score:c})),this._impl.on("styleload",({style:c})=>this.emit("styleload",{style:c})),this._impl.on("globeshow",()=>this.emit("globeshow")),this._impl.on("globehide",()=>this.emit("globehide")),this._impl.on("graphicspresetchange",()=>this.emit("graphicspresetchange",this._impl.getCurrentGraphicsPreset())),this._controlPane=new uP(this,{padding:t.controlsLayoutPadding}),this._initControls(t),new lP(this),this._defaultSource=new X_(this)}setCenter(e,t){return this._impl.setCenter(e,t),this}getCenter(){return this._impl.getCenter()}setZoom(e,t){return this._impl.setZoom(e,t),this}getZoom(){return this._impl.getZoom()}getStyleZoom(){return this._impl.getStyleZoom()}setStyleZoom(e,t){return this._impl.setStyleZoom(e,t),this}setRotation(e,t){return this._impl.setRotation(e,t),this}getRotation(){return this._impl.getRotation()}setPitch(e,t){return this._impl.setPitch(e,t),this}getPitch(){return this._impl.getPitch()}setMinZoom(e,t){return this._impl.setMinZoom(e,t),this}getMinZoom(){return this._impl.getMinZoom()}getMaxZoom(){return this._impl.getMaxZoom()}setMaxZoom(e,t){return this._impl.setMaxZoom(e,t),this}setMinPitch(e,t){return this._impl.setMinPitch(e,t),this}setMaxPitch(e,t){return this._impl.setMaxPitch(e,t),this}setLowZoomMaxPitch(e,t){return this._impl.setLowZoomMaxPitch(e,t),this}getSize(){return this._impl.getSize()}isIdle(){return this._impl.isIdle()}getBounds(e){return new G_(this._impl.getBounds(e))}project(e){return this._impl.project(e)}unproject(e){return this._impl.unproject(e)}getProjectionMatrix(){return this._impl.getCameraViewProjectionMatrix().slice()}getProjectionMatrixForGltfPlugin(){return this._impl.getCameraProjectionMatrix().slice()}getWebGLContext(){return this._impl.getWebGLContext()}getCanvas(){return this._impl.getCanvas()}getContainer(){return this._impl.getExternalContainer()}invalidateSize(){return this._impl.invalidateSize(),this}showTraffic(){return this._impl.showTraffic(),this}hideTraffic(){return this._impl.hideTraffic(),this}isTrafficOn(){return this._impl.isTrafficOn()}setSelectedObjects(e=[],t){return this._impl.setSelectedIds(e,t),this}setStyleById(e){return q(this,null,function*(){return this._impl.setStyle(e)})}setStyleFromUrl(e,t){return q(this,null,function*(){return this._impl.setStyle(e,t)})}setLanguage(e){return this._impl.setLang(e),this.emit("changeLanguage",{lang:e}),this}getLanguage(){return this._impl.state.lang}setFloorPlanLevel(e,t){this._impl.changeFloorNumber(e,t)}setMaxBounds(e){return this._impl.setMaxBounds(e),this}getPadding(){return this._impl.getPadding()}getDefaultSource(){return this._defaultSource}setPadding(e,t){return this._impl.setPadding(e,t),this}setStyle(e,t){return this._impl.setStyle(e,t)}hasLayer(e){return this._impl.hasLayer(e)}addLayer(e,t){return this.addDraftLayer(e,t),this}addDraftLayer(e,t){return this._impl.addLayer(e,t),this}addIcon(e,t){return this._impl.addIcon(e,t),this}removeIcon(e){return this._impl.removeIcon(e),this}getMapRenderStat(){return this._impl.getMapRenderStat()}addModel(e,t){return this._impl.addModel(e,t),this}removeLayer(e){return this._impl.removeLayer(e),this}setAutoHoverMode(e){return this._impl.setAutoHoverMode(e),this}forceInteractivity(e){return this._impl.setForceInteractivity(e),this}fitBounds(e,t){return this._impl.fitBounds(e,t),this}setStyleState(e){return this._impl.setStyleState(e),this}setTime(e){this._impl.setTime(e)}getTime(e){return this._impl.getTime(e)}getStyleState(){return this._impl.getStyleState()}getIconUrl(e){return this._impl.getIconUrl(e)}setStyleOptions(e){return this._impl.patchStyleState({trafficOn:e.traffic}),this}setOption(e,t){return this._impl.setOption(e,t),this}getOption(e){return this._impl.getOption(e)}patchStyleState(e){return this._impl.patchStyleState(e),this}destroy(){this._controlPane.destroy(),this._impl.destroy(),this.emit("destroy")}triggerRerender(){this._impl.modules.renderer.addRerenderEvent({type:"triggerRerender"})}setControlsLayoutPadding(e){this._controlPane.setPadding(e)}getControlsLayoutPadding(){return this._controlPane.getPadding()}setHiddenObjects(e){this._impl.hideBuildingsById(e)}setEnvironmentParams(e){this._impl.modules.environmentManager.setParameters(e)}unsetHiddenObjects(e){this._impl.showHiddenBuildingsById(e)}showLabelsDebug(e){this._impl.showLabelsDebug(e)}hideLabelsDebug(){this._impl.hideLabelsDebug()}getGroundPoint(e){return this._impl.getGroundPoint(e)}getElevationAtTier(e,t,i){return this._impl.getElevationAtTier(e,t,i)}setAllowedFloorIds(e){this._impl.setAllowedFloorIds(e)}setLightingStyle(e){this._impl.setLightingStyle(e)}hideLayers(e){return this._impl.hideLayers(e),this}showLayers(e){return this._impl.showLayers(e),this}getGraphicsPreset(){return this._impl.getCurrentGraphicsPreset().preset}blockInteraction(){this._impl.modules.handler.block(),this._impl.core.handlers.forEach(e=>{e.block()}),this._impl.modules.mouseMoveHandler.block()}unblockInteraction(){this._impl.modules.handler.unblock(),this._impl.core.handlers.forEach(e=>{e.unblock()}),this._impl.modules.mouseMoveHandler.unblock()}_emitMapEvent(e,t){this.emit(e,{isUser:t.isUser})}_emitMapErrorEvent(e,t){switch(t.type){case"rasterTileLoadError":{const{tileCoords:i,tileUrl:r,source:o,responseMessage:a,responseStatus:l}=t;if((o==null?void 0:o.type)==="raster"){const c=o.mapglApiSource;this.emit(e,{type:t.type,responseMessage:a,responseStatus:l,tileUrl:r,tileCoords:[i[0],i[1],i[2]],source:c})}break}case"webglcontextlost":{this.emit(e,{type:t.type});break}case"styleloaderror":{this.emit("styleloaderror",{style:t.style}),this.emit(e,{type:t.type,style:t.style});break}case"invalidtilekey":{this.emit(e,{type:t.type});break}default:n.assertUnreachable(t)}}_emitMapPointerEvent(e,t){const{originalEvent:i,lngLat:r,point:o,target:a,targetData:l}=t;let c;if(l!==void 0)switch(l.type){case"geojson":{c={type:l.type,source:l.source.mapglApiSource,feature:l.feature,id:l.id,layerId:l.layerId};break}case"zenith":{c={type:l.type,id:l.id,source:l.source.mapglApiSource,attributes:l.attributes,layerId:l.layerId};break}case"default":{c={type:l.type,id:l.id,layerId:l.layerId};const{poiIcon:u}=l;u&&(c.poiIcon=u);const{floorId:h,isApartmentFloor:_}=l;h&&(c.floorId=h),_&&(c.isApartmentFloor=_);break}}let d;a!==void 0&&(d={id:a.id},a.center&&(d.center=a.center)),this.emit(e,{originalEvent:i,lngLat:r,point:o,target:d,targetData:c})}_initControls(e){if(e.copyright!==!1&&this._impl.modules.tileKeyInfo.getKeyInfo().then(t=>{!t.error&&!t.hideCopyright&&new tP(this,{position:typeof e.copyright=="string"?e.copyright:"bottomRight",interactive:e.interactiveCopyright,copyrightType:t.urbi?"Urbi":"2gis"})}),e.zoomControl!==!1){const t=typeof e.zoomControl=="string"?e.zoomControl:"topRight";new w_(this,{position:t})}if(e.trafficControl){const t=typeof e.trafficControl=="string"?e.trafficControl:"topRight";new N_(this,{position:t})}if(e.scaleControl){const t=typeof e.scaleControl=="string"?e.scaleControl:"bottomLeft";new j_(this,{position:t})}if(e.floorControl){const t=typeof e.floorControl=="string"?e.floorControl:"topRight";new Z_(this,{position:t})}}_validateOptions(e){return e=I({},e),typeof e=="object"&&"center"in e&&(v_.isValidGeoPoint(e.center,Sl.UseDefault)||(e.center=void 0)),e}};const vP={minZoom:-1/0,maxZoom:1/0,anchor:[.5,.5],offset:[0,18],relativeAnchor:[.5,.5],zIndex:0,lineHeight:1.2,letterSpacing:0,haloRadius:0,fontSize:18,color:"#000000",haloColor:"#ffffff",font:"Noto_Sans"},gP={minZoom:-1/0,maxZoom:1/0,zIndex:0,icon:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzBweCIgaGVpZ2h0PSI0OHB4IiB2aWV3Qm94PSIwIDAgMzAgNDgiIHZlcnNpb249IjEuMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayI+PCEtLSBHZW5lcmF0b3I6IFNrZXRjaCA1MS4yICg1NzUxOSkgLSBodHRwOi8vd3d3LmJvaGVtaWFuY29kaW5nLmNvbS9za2V0Y2ggLS0+PHRpdGxlPlBhZ2UgMSBDb3B5PC90aXRsZT48ZGVzYz5DcmVhdGVkIHdpdGggU2tldGNoLjwvZGVzYz48ZGVmcz48bGluZWFyR3JhZGllbnQgeDE9IjUwJSIgeTE9IjUwJSIgeDI9IjUwJSIgeTI9IjAlIiBpZD0ibGluZWFyR3JhZGllbnQtMSI+PHN0b3Agc3RvcC1jb2xvcj0iIzFCODlFRSIgb2Zmc2V0PSIwJSI+PC9zdG9wPjxzdG9wIHN0b3AtY29sb3I9IiMzMTk4RUMiIG9mZnNldD0iMTAwJSI+PC9zdG9wPjwvbGluZWFyR3JhZGllbnQ+PC9kZWZzPjxnIGlkPSJQYWdlLTEiIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGlkPSJSZWNvdmVyeS0wMSIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoLTgzOS4wMDAwMDAsIC00MjUuMDAwMDAwKSI+PGcgaWQ9IlBhZ2UtMS1Db3B5IiB0cmFuc2Zvcm09InRyYW5zbGF0ZSg4MzkuMDAwMDAwLCA0MjUuMDAwMDAwKSI+PGVsbGlwc2UgaWQ9Ik92YWwtMyIgZmlsbD0iIzAwMDAwMCIgb3BhY2l0eT0iMC4wMzYzODA1OTciIGN4PSIxNSIgY3k9IjQ1LjUiIHJ4PSIzIiByeT0iMS41Ij48L2VsbGlwc2U+PGVsbGlwc2UgaWQ9Ik92YWwtMy1Db3B5IiBmaWxsPSIjMDAwMDAwIiBvcGFjaXR5PSIwLjAzNjM4MDU5NyIgY3g9IjE1IiBjeT0iNDUuNSIgcng9IjQuNSIgcnk9IjIuNSI+PC9lbGxpcHNlPjxwYXRoIGQ9Ik0xNSw0NS44ODM2MzUzIEwxNS44ODIzNTI5LDQ1Ljg4MzYzNTMgQzE1Ljg4MjM1MjksMjkuMjE3NzUyOSAyMC43NzY3NjQ3LDIzLjc5NzQ1ODggMjcuOTg3MzUyOSwyMy43OTc0NTg4IEwyOC4zMjk3MDU5LDIzLjc5NzQ1ODggQzI5LjA3Nzk0MTIsMjEuNTkwNjk0MSAzMCwxNy45OTE1NzY1IDMwLDE1LjAwMDQgQzMwLDcuMTQzOTI5NDEgMjMuNzY3OTQxMiwwLjAwMDQgMTUsMC4wMDA0IEM2LjIzMjA1ODgyLDAuMDAwNCAwLDcuMTQzOTI5NDEgMCwxNS4wMDA0IEMwLDE3Ljk5MTU3NjUgMC45MjIwNTg4MjQsMjEuNTkwNjk0MSAxLjY3MDI5NDEyLDIzLjc5NzQ1ODggTDIuMDEyNjQ3MDYsMjMuNzk3NDU4OCBDOS4yMjQxMTc2NSwyMy43OTc0NTg4IDE0LjExNzY0NzEsMjkuMjE3NzUyOSAxNC4xMTc2NDcxLDQ1Ljg4MzYzNTMgTDE1LDQ1Ljg4MzYzNTMgWiIgaWQ9IkZpbGwtMSIgZmlsbD0idXJsKCNsaW5lYXJHcmFkaWVudC0xKSI+PC9wYXRoPjwvZz48L2c+PC9nPjwvc3ZnPg==",interactive:!0,hoverSize:[15,43],rotation:0,userData:void 0,opacity:1,hoverOpacity:1,tier:0};class pP extends ni{constructor(e,t){super(),t.icon||(t.anchor=[15,46]);const i=st(t,gP);this.userData=i.userData,this.rootOptions={zIndex:i.zIndex,minZoom:i.minZoom,maxZoom:i.maxZoom},this._impl=new D_(e._impl,{coordinates:i.coordinates,icon:i.icon,zIndex:i.zIndex,minZoom:i.minZoom,maxZoom:i.maxZoom,interactive:i.interactive,opacity:i.opacity,hoverOpacity:i.hoverOpacity,tier:i.tier,label:$_(this.rootOptions,t.label),anchor:t.anchor,size:t.size,rotation:t.rotation,hoverIcon:t.hoverIcon,hoverSize:t.hoverSize,hoverAnchor:t.hoverAnchor}),this._impl.on("click",r=>this._emitPointerEvent("click",r)).on("dblclick",r=>this._emitPointerEvent("dblclick",r)).on("mousemove",r=>this._emitPointerEvent("mousemove",r)).on("mouseover",r=>this._emitPointerEvent("mouseover",r)).on("mouseout",r=>this._emitPointerEvent("mouseout",r)).on("mousedown",r=>this._emitPointerEvent("mousedown",r)).on("mouseup",r=>this._emitPointerEvent("mouseup",r)).on("touchstart",r=>this._emitPointerEvent("touchstart",r)).on("touchend",r=>this._emitPointerEvent("touchend",r)).on("touchmove",r=>this._emitPointerEvent("touchmove",r))}setIcon({icon:e,anchor:t,size:i,opacity:r}){return this._impl.setIcon({icon:e,anchor:t,size:i,opacity:r}),this}setHoverIcon(e){const t=e?{icon:e.icon,anchor:e.anchor,size:e.size,opacity:e.opacity}:void 0;return this._impl.setHoverIcon(t),this}setRotation(e){return this._impl.setRotation(e),this}getRotation(){return this._impl.getRotation()}setLabel(e){return this._impl.setLabel($_(this.rootOptions,e)),this}setCoordinates(e){return this._impl.setCoordinates(e),this}getCoordinates(){return this._impl.getCoordinates()}show(){return this._impl.show(),this}hide(){return this._impl.hide(),this}destroy(){this._impl.destroy()}_emitPointerEvent(e,t){const{originalEvent:i,lngLat:r,point:o}=t;this.emit(e,{originalEvent:i,lngLat:r,point:o,targetData:this})}}function $_(s,e){var i,r,o;if(!e)return;e.minZoom=Math.max((i=e.minZoom)!=null?i:s.minZoom,s.minZoom),e.maxZoom=Math.min((r=e.maxZoom)!=null?r:s.maxZoom,s.maxZoom),e.zIndex=(o=e.zIndex)!=null?o:s.zIndex+1e-5;const t=st(e,vP);return e.offset===void 0&&e.anchor!==void 0&&(t.offset=e.anchor.map(a=>-a)),V(I({text:t.text,image:e.image,minZoom:t.minZoom,maxZoom:t.maxZoom,color:t.color,fontSize:t.fontSize,haloRadius:t.haloRadius,haloColor:t.haloColor,letterSpacing:t.letterSpacing,lineHeight:t.lineHeight,zIndex:t.zIndex,offset:t.offset,anchor:t.relativeAnchor},e.tier!==void 0?{tier:e.tier}:{}),{font:t.font})}const xP="Noto_Sans",bP={anchor:[0,0],offset:[0,0],fontSize:24,color:"#000000",haloColor:"#ffffff",haloRadius:0,minZoom:-1/0,maxZoom:1/0,zIndex:0,letterSpacing:0,lineHeight:1.2,relativeAnchor:[.5,.5],userData:void 0,interactive:!1};class SP extends ni{constructor(e,t){super(),this.userData=t.userData;const i=st(t,bP);t.offset===void 0&&t.anchor!==void 0&&(i.offset=t.anchor.map(r=>-r)),this._impl=new Cr(e._impl,I({coordinates:i.coordinates,text:i.text,minZoom:i.minZoom,maxZoom:i.maxZoom,color:i.color,fontSize:i.fontSize,haloRadius:i.haloRadius,haloColor:i.haloColor,letterSpacing:i.letterSpacing,lineHeight:i.lineHeight,zIndex:i.zIndex,offset:i.offset,anchor:i.relativeAnchor,labeling:t.labeling,image:t.image,font:xP,interactive:i.interactive},t.tier!==void 0?{tier:t.tier}:{})),this._impl.on("click",r=>this._emitPointerEvent("click",r)).on("dblclick",r=>this._emitPointerEvent("dblclick",r)).on("mousemove",r=>this._emitPointerEvent("mousemove",r)).on("mouseover",r=>this._emitPointerEvent("mouseover",r)).on("mouseout",r=>this._emitPointerEvent("mouseout",r)).on("mousedown",r=>this._emitPointerEvent("mousedown",r)).on("mouseup",r=>this._emitPointerEvent("mouseup",r)).on("touchstart",r=>this._emitPointerEvent("touchstart",r)).on("touchend",r=>this._emitPointerEvent("touchend",r))}destroy(){this._impl.remove()}show(){return this._impl.show(),this}hide(){return this._impl.hide(),this}setCoordinates(e){return this._impl.setCoordinates(e),this}getCoordinates(){return this._impl.getCoordinates()}_emitPointerEvent(e,t){const{originalEvent:i,lngLat:r,point:o}=t;this.emit(e,{originalEvent:i,lngLat:r,point:o,targetData:this})}}const yP={minZoom:-1/0,maxZoom:1/0,zIndex:0,anchor:[-0,-0],preventMapInteractions:!0,userData:void 0,interactive:!0,disableRounding:!1,labeling:{type:"none"},floorId:""},TP=!1;class EP{constructor(e,t){this.userData=t.userData;const i=st(t,yP);this._impl=new el(e._impl,I({coordinates:i.coordinates,html:i.html,offset:[-i.anchor[0],-i.anchor[1]],minZoom:i.minZoom,maxZoom:i.maxZoom,zIndex:i.zIndex,preventMapInteractions:i.preventMapInteractions,interactive:i.interactive,animate:TP,disableRounding:i.disableRounding,labeling:i.labeling,floorId:i.floorId},t.tier!==void 0?{tier:t.tier}:{}))}destroy(){this._impl.destroy()}setCoordinates(e){return this._impl.setPosition(e),this}setAnchor(e){return this._impl.setOffset([-e[0],-e[1]]),this}setContent(e){return this._impl.setContent(e),this}setZIndex(e){return this._impl.setZIndex(e),this}getCoordinates(){return this._impl.getPosition()}getAnchor(){const e=this._impl.getOffset();return[-e[0],-e[1]]}getContent(){return this._impl.getHtmlElement()}getZIndex(){return this._impl.getZIndex()}}const CP={zIndex:0,minZoom:-1/0,maxZoom:1/0,color:"#3388ff33",strokeColor:"#3388ff",strokeWidth:1,interactive:!0,userData:void 0};class IP extends ni{constructor(e,t){super(),this.userData=t.userData;const i=st(t,CP),r={coordinates:i.coordinates,radius:i.radius,minZoom:i.minZoom,maxZoom:i.maxZoom,interactive:i.interactive,color:i.color,zIndex:i.zIndex,borderWidth:i.strokeWidth,borderColor:i.strokeColor,segments:150,tiers:t.tiers};this._impl=new L_(e._impl,r),this._impl.on("click",o=>this._emitPointerEvent("click",o)).on("dblclick",o=>this._emitPointerEvent("dblclick",o)).on("mousemove",o=>this._emitPointerEvent("mousemove",o)).on("mouseover",o=>this._emitPointerEvent("mouseover",o)).on("mouseout",o=>this._emitPointerEvent("mouseout",o)).on("mousedown",o=>this._emitPointerEvent("mousedown",o)).on("mouseup",o=>this._emitPointerEvent("mouseup",o)).on("touchstart",o=>this._emitPointerEvent("touchstart",o)).on("touchend",o=>this._emitPointerEvent("touchend",o)).on("touchmove",o=>this._emitPointerEvent("touchmove",o))}destroy(){this._impl.remove()}_emitPointerEvent(e,t){const{originalEvent:i,lngLat:r,point:o}=t;this.emit(e,{originalEvent:i,lngLat:r,point:o,targetData:this})}}const PP={interactive:!0,maxZoom:1/0,minZoom:-1/0,color:"#ffffff",radius:20,diameter:NaN,zIndex:0,strokeWidth:3,stroke2Width:0,strokeColor:"#3388ff",stroke2Color:"#00000000",userData:void 0};class AP extends ni{constructor(e,t){super(),this.userData=t.userData,this.options=st(t,PP);const i={coordinates:this.options.coordinates,interactive:this.options.interactive,maxZoom:this.options.maxZoom,minZoom:this.options.minZoom,color:this.options.color,width:Number.isNaN(this.options.diameter)?this.options.radius:this.options.diameter,zIndex:this.options.zIndex,borderWidth:this.options.strokeWidth,borderColor:this.options.strokeColor,border2Width:this.options.stroke2Width,border2Color:this.options.stroke2Color,draggable:!1};this._impl=new Dl(e._impl,i),this._impl.on("click",r=>this._emitPointerEvent("click",r)).on("dblclick",r=>this._emitPointerEvent("dblclick",r)).on("mousemove",r=>this._emitPointerEvent("mousemove",r)).on("mouseover",r=>this._emitPointerEvent("mouseover",r)).on("mouseout",r=>this._emitPointerEvent("mouseout",r)).on("mousedown",r=>this._emitPointerEvent("mousedown",r)).on("mouseup",r=>this._emitPointerEvent("mouseup",r)).on("touchstart",r=>this._emitPointerEvent("touchstart",r)).on("touchend",r=>this._emitPointerEvent("touchend",r)).on("touchmove",r=>this._emitPointerEvent("touchmove",r))}destroy(){this._impl.remove()}_emitPointerEvent(e,t){const{originalEvent:i,lngLat:r,point:o}=t;this.emit(e,{originalEvent:i,lngLat:r,point:o,targetData:this})}}const LP={interactive:!0,maxZoom:1/0,minZoom:-1/0,width:3,width2:0,width3:0,color:"#3388ff",color2:"#00000000",color3:"#00000000",zIndex:0,zIndex2:-1,zIndex3:-2,dashLength:0,gapLength:0,gapColor:"#ffffff00",userData:void 0,renderingMode:"2d"};class RP extends ni{constructor(e,t){super(),this.userData=t.userData;const i=st(t,LP);if(t.dashLength){const r={coordinates:i.coordinates,interactive:i.interactive,maxZoom:i.maxZoom,minZoom:i.minZoom,width:i.width,width2:i.width2,dashColor:i.color,dash2Color:i.color,gapColor:i.gapColor,dashLength:i.dashLength,dash2Length:0,zIndex:i.zIndex,zIndex2:i.zIndex2,gapLength:i.gapLength===0?i.dashLength:i.gapLength,displayTileBounds:!1,showAnimation:{animate:!1},renderingMode:i.renderingMode,hiddenPartDashColor:t.hiddenPartColor,hiddenPartDash2Color:t.hiddenPartColor,hiddenPartGapColor:t.hiddenPartGapColor,gpuState:t.gpuState,tiers:t.tiers};this._impl=new P_(e._impl,r),this._impl.on("click",o=>this._emitPointerEvent("click",o)).on("dblclick",o=>this._emitPointerEvent("dblclick",o)).on("mousemove",o=>this._emitPointerEvent("mousemove",o)).on("mouseover",o=>this._emitPointerEvent("mouseover",o)).on("mouseout",o=>this._emitPointerEvent("mouseout",o)).on("mousedown",o=>this._emitPointerEvent("mousedown",o)).on("mouseup",o=>this._emitPointerEvent("mouseup",o)).on("touchstart",o=>this._emitPointerEvent("touchstart",o)).on("touchend",o=>this._emitPointerEvent("touchend",o)).on("touchmove",o=>this._emitPointerEvent("touchmove",o))}else{const r={coordinates:i.coordinates,interactive:i.interactive,maxZoom:i.maxZoom,minZoom:i.minZoom,width:i.width,width2:i.width2,width3:i.width3,color:i.color,color2:i.color2,color3:i.color3,zIndex:i.zIndex,zIndex2:i.zIndex2,zIndex3:i.zIndex3,displayTileBounds:!1,showAnimation:{animate:!1},gpuState:t.gpuState,renderingMode:i.renderingMode,hiddenPartColor:t.hiddenPartColor,tiers:t.tiers};this._impl=new y_(e._impl,r),this._impl.on("click",o=>this._emitPointerEvent("click",o)).on("dblclick",o=>this._emitPointerEvent("dblclick",o)).on("mousemove",o=>this._emitPointerEvent("mousemove",o)).on("mouseover",o=>this._emitPointerEvent("mouseover",o)).on("mouseout",o=>this._emitPointerEvent("mouseout",o)).on("mousedown",o=>this._emitPointerEvent("mousedown",o)).on("mouseup",o=>this._emitPointerEvent("mouseup",o)).on("touchstart",o=>this._emitPointerEvent("touchstart",o)).on("touchend",o=>this._emitPointerEvent("touchend",o)).on("touchmove",o=>this._emitPointerEvent("touchmove",o))}}destroy(){this._impl.remove()}_emitPointerEvent(e,t){const{originalEvent:i,lngLat:r,point:o}=t;this.emit(e,{originalEvent:i,lngLat:r,point:o,targetData:this})}}const FP={interactive:!0,maxZoom:1/0,minZoom:-1/0,color:"#3388ff33",zIndex:0,strokeWidth:3,strokeColor:"#3388ff",userData:void 0};class DP extends ni{constructor(e,t){super(),this.userData=t.userData;const i=st(t,FP),r={coordinates:i.coordinates,interactive:i.interactive,maxZoom:i.maxZoom,minZoom:i.minZoom,color:i.color,zIndex:i.zIndex,strokeWidth:i.strokeWidth,strokeColor:i.strokeColor,tiers:t.tiers};this._impl=new A_(e._impl,r),this._impl.on("click",o=>this._emitPointerEvent("click",o)).on("dblclick",o=>this._emitPointerEvent("dblclick",o)).on("mousemove",o=>this._emitPointerEvent("mousemove",o)).on("mouseover",o=>this._emitPointerEvent("mouseover",o)).on("mouseout",o=>this._emitPointerEvent("mouseout",o)).on("mousedown",o=>this._emitPointerEvent("mousedown",o)).on("mouseup",o=>this._emitPointerEvent("mouseup",o)).on("touchstart",o=>this._emitPointerEvent("touchstart",o)).on("touchend",o=>this._emitPointerEvent("touchend",o)).on("touchmove",o=>this._emitPointerEvent("touchmove",o))}destroy(){this._impl.remove()}_emitPointerEvent(e,t){const{originalEvent:i,lngLat:r,point:o}=t;this.emit(e,{originalEvent:i,lngLat:r,point:o,targetData:this})}}const zP={minZoom:-1/0,maxZoom:1/0,zIndex:0,opacity:1};class BP{constructor(e,t){const i=st(t,zP),r={bounds:i.bounds,image:{url:i.image.url},minZoom:i.minZoom,maxZoom:i.maxZoom,zIndex:i.zIndex,opacity:i.opacity,tiers:t.tiers};this._impl=new B_(e._impl,r)}updateImage(e){return q(this,null,function*(){yield this._impl.updateImage(e)})}destroy(){this._impl.destroy()}}const OP={zIndex:0,minZoom:-1/0,maxZoom:1/0,color:"#0085a0",strokeColor:"#ffffff",width:4,strokeWidth:1,roundingRadius:2,tipWidthMultiplier:1.5,tipHeightMultiplier:2.8,tipMovementAmplitude:6,animate:!1,iterationCount:1/0,interactive:!1,userData:void 0};class wP extends ni{constructor(e,t){super(),this.userData=t.userData;const i=st(t,OP),a={coordinates:(l=>typeof l[0][0]=="number")(i.coordinates)?[i.coordinates]:i.coordinates,interactive:i.interactive,minZoom:i.minZoom,maxZoom:i.maxZoom,zIndex:i.zIndex,color:i.color,borderColor:i.strokeColor,width:i.width,borderWidth:i.strokeWidth,roundingRadius:i.roundingRadius,wingWidthMultiplier:i.tipWidthMultiplier,tipHeightMultiplier:i.tipHeightMultiplier,tipMovementAmplitude:i.tipMovementAmplitude,animate:i.animate,iterationCount:i.iterationCount};this._impl=new sl(e._impl,a),this._impl.on("click",l=>this._emitPointerEvent("click",l)).on("dblclick",l=>this._emitPointerEvent("dblclick",l)).on("mousemove",l=>this._emitPointerEvent("mousemove",l)).on("mouseover",l=>this._emitPointerEvent("mouseover",l)).on("mouseout",l=>this._emitPointerEvent("mouseout",l)).on("mousedown",l=>this._emitPointerEvent("mousedown",l)).on("mouseup",l=>this._emitPointerEvent("mouseup",l)).on("touchstart",l=>this._emitPointerEvent("touchstart",l)).on("touchend",l=>this._emitPointerEvent("touchend",l)).on("touchmove",l=>this._emitPointerEvent("touchmove",l))}destroy(){this._impl.remove()}_emitPointerEvent(e,t){const{originalEvent:i,lngLat:r,point:o}=t;this.emit(e,{originalEvent:i,lngLat:r,point:o,targetData:this})}}const NP={scale:1,rotation:0,offset:0,linkedIds:[],interactive:!1,interactiveOcclusion:!0,minZoom:-1/0,maxZoom:1/0,zIndex:0,hideOnInit:!1,ignoreGlobalLighting:!1,colorTextureUvIndex:0,nearCameraFade:2500,showRatio:1,userData:void 0,planId:"",disableAnimation:!1,hover:{},select:{},color:"#ffffffff",playAnimation:-1,tier:0};class kP extends ni{constructor(e,t){super(),this.userData=t.userData;const i=st(t,NP),r={coordinates:i.coordinates,modelSrc:i.modelSrc,scale:i.scale,rotation:i.rotation,offset:i.offset,linkedIds:i.linkedIds,planId:i.planId,interactive:i.interactive,interactiveOcclusion:i.interactiveOcclusion,minZoom:i.minZoom,maxZoom:i.maxZoom,zIndex:i.zIndex,hideOnInit:i.hideOnInit,ignoreGlobalLighting:i.ignoreGlobalLighting,colorTextureUvIndex:i.colorTextureUvIndex,nearCameraFade:i.nearCameraFade,showRatio:i.showRatio,disableAnimation:i.disableAnimation,hover:i.hover,select:i.select,color:i.color,playAnimation:i.playAnimation,tier:i.tier};this._impl=new hl(e._impl,r),this._impl.on("click",o=>this._emitPointerEvent("click",o)).on("dblclick",o=>this._emitPointerEvent("dblclick",o)).on("mousemove",o=>this._emitPointerEvent("mousemove",o)).on("mouseover",o=>this._emitPointerEvent("mouseover",o)).on("mouseout",o=>this._emitPointerEvent("mouseout",o)).on("mousedown",o=>this._emitPointerEvent("mousedown",o)).on("mouseup",o=>this._emitPointerEvent("mouseup",o)).on("touchstart",o=>this._emitPointerEvent("touchstart",o)).on("touchend",o=>this._emitPointerEvent("touchend",o)).on("touchmove",o=>this._emitPointerEvent("touchmove",o)).on("modelloaded",()=>this._emitPointerEvent("modelloaded"))}destroy(e){this._impl.destroy(e)}hide(){this._impl.hide()}show(){this._impl.show()}transform(e){this._impl.transform(e)}stopTransformation(){this._impl.stopTransformation()}getCoordinates(){return this._impl.getCoordinates()}getScale(){return this._impl.getScale()}getRotation(){return this._impl.getRotation()}getOffset(){return this._impl.getOffset()}getWorldTransform(){var i;const e=this._impl.getWorldTransform(),t=e.position;return{position:[t[0],t[1],(i=t[2])!=null?i:0],rotation:e.rotation}}getTier(){return this._impl.getTier()}setTier(e){this._impl.setTier(e)}setState(e){this._impl.setState(e)}_emitPointerEvent(e,t){this.emit(e,t?{originalEvent:t.originalEvent,lngLat:t.lngLat,point:t.point,targetData:this}:void 0)}}const q_={attributes:{},maxZoom:17,dimensions:2,modelsPath:"",modelsAppearStrategy:"byModel",promoteId:"",idScope:"default",tolerance:3};class UP{constructor(e,t){this.options=st(t,q_),this._impl=new n.GeoJsonSource(e._impl,this.options,this),this._isDestroyed=!1}destroy(){this._isDestroyed=!0,this._impl.destroy()}setAttributes(e){return this._isDestroyed||this._impl.setAttributes(e),this}getAttributes(){return this._isDestroyed?{}:this._impl.getAttributes()}setData(e){return q(this,null,function*(){this._isDestroyed||(yield this._impl.setData(e))})}}const MP=V(I({},q_),{viewportPadding:0});class HP{constructor(e,t){this.options=st(t,MP);const i=V(I({},this.options),{data:n.EMPTY_FEATURE_COLLECTION});this._impl=new n.GeoJsonViewportSource(e._impl,i,this),this._impl.setDataFn(t.data),this._impl.setViewportPadding(this.options.viewportPadding)}destroy(){this._impl.destroy()}setAttributes(e){return this._impl.setAttributes(e),this}getAttributes(){return this._impl.getAttributes()}setData(e){return q(this,null,function*(){return this._impl.setDataFn(e)})}setViewportPadding(e){return this._impl.setViewportPadding(e),this}}const Y_={container:"mapgl_54Xq9OUdARA-",text:"mapgl_qYE18V9u8c0-"},GP=s=>`
    <div class=${Y_.container}>
        <div class=${Y_.text}>${s}</div>
    </div>
`;class VP extends Vi{constructor(e,t){super(e,GP(t),{position:"bottomLeft"})}}const ZP={attributes:{},attribution:"",minZoom:Vs.minZoom,maxZoom:Vs.maxZoom};class WP{constructor(e,t){this.options=st(t,ZP),this._impl=new O_(e._impl,this.options,this),this._attribution=new VP(e,this.options.attribution)}destroy(){this._impl.destroy(),this._attribution.destroy()}setAttributes(e){return this._impl.setAttributes(e),this}getAttributes(){return this._impl.getAttributes()}}const Qs=class Qs{constructor(e,t){this.options=t;const i=this.prepareOptions(this.options,e);this._impl=new eo(e._impl,i,this)}destroy(){this._impl.destroy()}setAttributes(e){return this._impl.setAttributes(e),this}getAttributes(){return this._impl.getAttributes()}setFeatureStateMap(e){this._impl.setFeatureStateMap(e)}prepareOptions(e,t){var r,o,a,l,c,d,u,h,_,f;const i={tileServer:(r=e.tileServer)!=null?r:"",tileSet:(o=e.tileSet)!=null?o:"",tileProtocol:(a=e.tileProtocol)!=null?a:"",tileKey:(l=e.tileKey)!=null?l:"",subdomains:(c=e.subdomains)!=null?c:e.layerId?["0,1,2,3"]:[""],appId:(d=e.appId)!=null?d:t._impl.state.appId,tileTemplateUrl:e.tileTemplateUrl,metatileTemplateUrl:e.metatileTemplateUrl,defaultLang:e.defaultLang,sessionId:e.sessionId,sourceAttributes:e.sourceAttributes,modelsPath:e.modelsPath,disableTilesAnimation:e.disableTilesAnimation,promoteAttributes:e.promoteAttributes,promoteId:e.promoteId,idScope:e.idScope,modelsAppearStrategy:e.modelsAppearStrategy,minZoom:(u=e.minZoom)!=null?u:9,maxZoom:(h=e.maxZoom)!=null?h:15,maxDetailLevel:(_=e.maxGenerateZoom)!=null?_:17,strokeMinZoom:(f=e.strokeMinZoom)!=null?f:8};return e.layerId&&(i.tileTemplateUrl||(i.tileTemplateUrl=`${f_}?ts=userdata&x={x}&y={y}&z={z}&layer=${e.layerId}`),i.metatileTemplateUrl||(i.metatileTemplateUrl=`${f_}/file/{hash}?ts=userdata&layer=${e.layerId}`)),i}};Qs.tileTemplateUrl="{protocol}://{host}/v2/ald?ts={tileSet}&x={x}&y={y}&z={z}&lang={lang}",Qs.metatileTemplateUrl="{protocol}://{host}/v2/ald/file/{hash}.json?ts={tileSet}";let Il=Qs;function jP(s){const e=s.split("?")[1];if(!e)return;const i=e.split("&").map(r=>r.split("=")).find(r=>r[0]==="callback");if(i)return i[1]}setTimeout(()=>{const s=Array.from(document.querySelectorAll("script")).find(t=>t.src.match(_C));if(!s)return;const e=jP(s.src);if(e)if(typeof window[e]=="function")window[e]();else throw new Error(`Not found callback function with name "${e}"`)},0),setTimeout(()=>{if("__mapglPlugins"in window)for(const s in window.__mapglPlugins)window.mapgl[s]=window.__mapglPlugins[s]},0);function XP(s){b2(s)}const Pl="v1.81.0";ie.applyDefaultGraphicsPresets=n.applyDefaultGraphicsPresets,ie.API_VERSION=Pl,ie.Arrow=wP,ie.Circle=IP,ie.CircleMarker=AP,ie.Control=Vi,ie.DefaultSource=X_,ie.FloorControl=Z_,ie.GeoJsonSource=UP,ie.GeoJsonViewportSource=HP,ie.GltfModel=kP,ie.HtmlMarker=EP,ie.Label=SP,ie.LngLatBoundsClass=G_,ie.Map=mP,ie.Marker=pP,ie.Polygon=DP,ie.Polyline=RP,ie.Raster=BP,ie.RasterTileSource=WP,ie.ScaleControl=j_,ie.TrafficControl=N_,ie.ZenithSource=Il,ie.ZoomControl=w_,ie._J=WI,ie.isSupported=Jf,ie.isTerrainSupported=Vl,ie.notSupportedReason=Wl,ie.setWorkerUrl=XP,ie.terrainNotSupportedReason=cm,Object.defineProperty(ie,Symbol.toStringTag,{value:"Module"})}));
