From 4617efa085ac5eb4b2df5e19b4cfcf4bcc835584 Mon Sep 17 00:00:00 2001
From: Claude Opus 5 c&&(h=c-n)}return(h!==void 0||_!==void 0)&&(n.center=Ta(i,new z(h??p,_??m)).wrap()),n},this.applyConstrain=(e,t)=>this._helper.applyConstrain(e,t),this._helper=new vs({calcMatrices:()=>this._calcMatrices(),defaultConstrain:(e,t)=>this.defaultConstrain(e,t)},e),this._coveringTilesDetailsProvider=new bs}clone(){let t=new e;return t.apply(this,!1),t}apply(e,t,n){this._helper.apply(e,t,n)}get cameraPosition(){return this._cameraPosition}get projectionMatrix(){return this._projectionMatrix}get modelViewProjectionMatrix(){return this._viewProjMatrix}get inverseProjectionMatrix(){return this._invProjMatrix}get mercatorMatrix(){return this._mercatorMatrix}getVisibleUnwrappedCoordinates(e){let t=[new Zn(0,e)];if(this._helper._renderWorldCopies){let n=this.screenPointToMercatorCoordinate(new z(0,0)),r=this.screenPointToMercatorCoordinate(new z(this._helper._width,0)),i=this.screenPointToMercatorCoordinate(new z(this._helper._width,this._helper._height)),a=this.screenPointToMercatorCoordinate(new z(0,this._helper._height)),o=Math.floor(Math.min(n.x,r.x,i.x,a.x)),s=Math.floor(Math.max(n.x,r.x,i.x,a.x));for(let n=o-1;n<=s+1;n++)n!==0&&t.push(new Zn(n,e))}return t}getCameraFrustum(){return xs.fromInvProjectionMatrix(this._invViewProjMatrix,this.worldSize)}getClippingPlane(){return null}getCoveringTilesDetailsProvider(){return this._coveringTilesDetailsProvider}recalculateZoomAndCenter(e){let t=this.screenPointToLocation(this.centerPoint,e),n=e?e.getElevationForLngLatZoom(t,this._helper._tileZoom):0;this._helper.recalculateZoomAndCenter(n)}setLocationAtPoint(e,t){let n=Oe(this.elevation,this.center.lat),r=this.screenPointToMercatorCoordinateAtZ(t,n),i=this.screenPointToMercatorCoordinateAtZ(this.centerPoint,n),a=N.fromLngLat(e),o=new N(a.x-(r.x-i.x),a.y-(r.y-i.y));this.setCenter(o?.toLngLat()),this._helper._renderWorldCopies&&this.setCenter(this.center.wrap())}locationToScreenPoint(e,t){return t?this.coordinatePoint(N.fromLngLat(e),t.getElevationForLngLat(e,this),this._pixelMatrix3D):this.coordinatePoint(N.fromLngLat(e))}screenPointToLocation(e,t){return this.screenPointToMercatorCoordinate(e,t)?.toLngLat()}screenPointToMercatorCoordinate(e,t){if(t){let n=t.pointCoordinate(e);if(n!=null)return n}return this.screenPointToMercatorCoordinateAtZ(e)}screenPointToMercatorCoordinateAtZ(e,t){let n=t||0,r=[e.x,e.y,0,1],i=[e.x,e.y,1,1];A(r,r,this._pixelMatrixInverse),A(i,i,this._pixelMatrixInverse);let a=r[3],o=i[3],s=r[0]/a,c=i[0]/o,l=r[1]/a,u=i[1]/o,d=r[2]/a,f=i[2]/o,p=d===f?0:(n-d)/(f-d);return new N(Yn.number(s,c,p)/this.worldSize,Yn.number(l,u,p)/this.worldSize,n)}coordinatePoint(e,t=0,n=this._pixelMatrix){let r=[e.x*this.worldSize,e.y*this.worldSize,t,1];return A(r,r,n),new z(r[0]/r[3],r[1]/r[3])}getBounds(){let e=Math.max(0,this._helper._height/2-Ea(this));return new Ri().extend(this.screenPointToLocation(new z(0,e))).extend(this.screenPointToLocation(new z(this._helper._width,e))).extend(this.screenPointToLocation(new z(this._helper._width,this._helper._height))).extend(this.screenPointToLocation(new z(0,this._helper._height)))}isPointOnMapSurface(e,t){return t?t.pointCoordinate(e)!=null:e.y>this.height/2-Ea(this)}calculatePosMatrix(e,t=!1,n=!1){let r=e.key??dr(e.wrap,e.canonical.z,e.canonical.z,e.canonical.x,e.canonical.y),i=t?this._alignedPosMatrixCache:this._posMatrixCache;if(i.has(r)){let e=i.get(r);return n?e.f32:e.f64}let a=Da(e,this.worldSize);Qn(a,t?this._alignedProjMatrix:this._viewProjMatrix,a);let o={f64:a,f32:new Float32Array(a)};return i.set(r,o),n?o.f32:o.f64}calculateFogMatrix(e){let t=e.key,n=this._fogMatrixCacheF32;if(n.has(t))return n.get(t);let r=Da(e,this.worldSize);return Qn(r,this._fogMatrix,r),n.set(t,new Float32Array(r)),n.get(t)}calculateCenterFromCameraLngLatAlt(e,t,n,r){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,n,r)}_calculateNearFarZIfNeeded(e,t,n){if(!this._helper.autoCalculateNearFarZ)return;let r=Math.min(this.elevation,this.minElevationForCurrentTile,this.getCameraAltitude()-100),i=e-r*this._helper._pixelPerMeter/Math.cos(t),a=r<0?i:e,o=Math.PI/2+this.pitchInRadians,s=k(this.fov)*(Math.abs(Math.cos(k(this.roll)))*this.height+Math.abs(Math.sin(k(this.roll)))*this.width)/this.height*(.5+n.y/this.height),c=Math.sin(s)*a/Math.sin(j(Math.PI-o-s,.01,Math.PI-.01)),l=Ea(this),u=Math.atan(l/this._helper.cameraToCenterDistance),d=k(90-Sa),f=u>d?2*u*(.5+n.y/(l*2)):d,p=Math.sin(f)*a/Math.sin(j(Math.PI-o-f,.01,Math.PI-.01)),m=Math.min(c,p);this._helper._farZ=(Math.cos(Math.PI/2-t)*m+a)*1.01,this._helper._nearZ=this._helper._height/50}_calcMatrices(){if(!this._helper._height)return;let e=this.centerOffset,t=wa(this.worldSize,this.center),n=t.x,r=t.y;this._helper._pixelPerMeter=Oe(1,this.center.lat)*this.worldSize;let i=k(Math.min(this.pitch,Sa)),a=Math.max(this._helper.cameraToCenterDistance/2,this._helper.cameraToCenterDistance+this._helper._elevation*this._helper._pixelPerMeter/Math.cos(i));this._calculateNearFarZIfNeeded(a,i,e);let o;o=new Float64Array(16),Et(o,this.fovInRadians,this._helper._width/this._helper._height,this._helper._nearZ,this._helper._farZ),this._invProjMatrix=new Float64Array(16),Qa(this._invProjMatrix,o),o[8]=-e.x*2/this._helper._width,o[9]=e.y*2/this._helper._height,this._projectionMatrix=Jn(o),rr(o,o,[1,-1,1]),F(o,o,[0,0,-this._helper.cameraToCenterDistance]),f(o,o,-this.rollInRadians),cr(o,o,this.pitchInRadians),f(o,o,-this.bearingInRadians),F(o,o,[-n,-r,0]),this._mercatorMatrix=rr([],o,[this.worldSize,this.worldSize,this.worldSize]),rr(o,o,[1,1,this._helper._pixelPerMeter]),this._pixelMatrix=Qn(new Float64Array(16),this.clipSpaceToPixelsMatrix,o),F(o,o,[0,0,-this.elevation]),this._viewProjMatrix=o,this._invViewProjMatrix=gt([],o);let s=[0,0,-1,1];A(s,s,this._invViewProjMatrix),this._cameraPosition=[s[0]/s[3],s[1]/s[3],s[2]/s[3]],this._fogMatrix=new Float64Array(16),Et(this._fogMatrix,this.fovInRadians,this.width/this.height,a,this._helper._farZ),this._fogMatrix[8]=-e.x*2/this.width,this._fogMatrix[9]=e.y*2/this.height,rr(this._fogMatrix,this._fogMatrix,[1,-1,1]),F(this._fogMatrix,this._fogMatrix,[0,0,-this.cameraToCenterDistance]),f(this._fogMatrix,this._fogMatrix,-this.rollInRadians),cr(this._fogMatrix,this._fogMatrix,this.pitchInRadians),f(this._fogMatrix,this._fogMatrix,-this.bearingInRadians),F(this._fogMatrix,this._fogMatrix,[-n,-r,0]),rr(this._fogMatrix,this._fogMatrix,[1,1,this._helper._pixelPerMeter]),F(this._fogMatrix,this._fogMatrix,[0,0,-this.elevation]),this._pixelMatrix3D=Qn(new Float64Array(16),this.clipSpaceToPixelsMatrix,o);let c=this._helper._width%2/2,l=this._helper._height%2/2,u=Math.cos(this.bearingInRadians),d=Math.sin(-this.bearingInRadians),p=n-Math.round(n)+u*c+d*l,m=r-Math.round(r)+u*l+d*c,h=new Float64Array(o);if(F(h,h,[p>.5?p-1:p,m>.5?m-1:m,0]),this._alignedProjMatrix=h,o=gt(new Float64Array(16),this._pixelMatrix),!o)throw Error(`failed to invert matrix`);this._pixelMatrixInverse=o,this._clearMatrixCaches()}_clearMatrixCaches(){this._posMatrixCache.clear(),this._alignedPosMatrixCache.clear(),this._fogMatrixCacheF32.clear()}maxPitchScaleFactor(){if(!this._pixelMatrixInverse)return 1;let e=this.screenPointToMercatorCoordinate(new z(0,0)),t=[e.x*this.worldSize,e.y*this.worldSize,0,1];return A(t,t,this._pixelMatrix)[3]/this._helper.cameraToCenterDistance}getCameraPoint(){return this._helper.getCameraPoint()}getCameraAltitude(){return this._helper.getCameraAltitude()}getCameraLngLat(){let e=Oe(1,this.center.lat)*this.worldSize,t=this._helper.cameraToCenterDistance/e;return Oa(this.center,this.elevation,this.pitch,this.bearing,t).toLngLat()}lngLatToCameraDepth(e,t){let n=N.fromLngLat(e),r=[n.x*this.worldSize,n.y*this.worldSize,t,1];return A(r,r,this._viewProjMatrix),r[2]/r[3]}getProjectionData(e){let{overscaledTileID:t,aligned:n,applyTerrainMatrix:r}=e,i=this._helper.getMercatorTileCoordinates(t),a=t?this.calculatePosMatrix(t,n,!0):null,o;return o=t?.terrainRttPosMatrix32f&&r?t.terrainRttPosMatrix32f:a||Be(),{mainMatrix:o,tileMercatorCoords:i,clippingPlane:[0,0,0,0],projectionTransition:0,fallbackMatrix:o}}isLocationOccluded(e){return!1}getPixelScale(){return 1}getCircleRadiusCorrection(){return 1}getPitchedTextCorrection(e,t,n){return 1}transformLightDirection(e){return Nn(e)}getRayDirectionFromPixel(e){throw Error(`Not implemented.`)}projectTileCoordinates(e,t,n,r){let i=this.calculatePosMatrix(n),a;r?(a=[e,t,r(e,t),1],A(a,a,i)):(a=[e,t,0,1],So(a,a,i));let o=a[3];return{point:new z(a[0]/o,a[1]/o),signedDistanceFromCamera:o,isOccluded:!1}}populateCache(e){for(let t of e)this.calculatePosMatrix(t)}getProjectionDataForCustomLayer(e=!0){let t=new ht(0,0,0,0,0),n=this.getProjectionData({overscaledTileID:t,applyGlobeMatrix:e}),r=Da(t,this.worldSize);Qn(r,this._viewProjMatrix,r);let i=[M,M,this.worldSize/this._helper.pixelsPerMeter],a=c();return rr(a,r,i),{...n,tileMercatorCoords:[0,0,1,1],fallbackMatrix:a,mainMatrix:a}}getFastPathSimpleProjectionMatrix(e){return this.calculatePosMatrix(e)}};function Ds(){a(`Map cannot fit within canvas with the given bounds, padding, and/or offset.`)}function Os(e){if(e.useSlerp)if(e.k<1){let t=m(e.startEulerAngles.roll,e.startEulerAngles.pitch,e.startEulerAngles.bearing),n=m(e.endEulerAngles.roll,e.endEulerAngles.pitch,e.endEulerAngles.bearing),r=new Float64Array(4);ie(r,t,n,e.k);let i=rn(r);e.tr.setRoll(i.roll),e.tr.setPitch(i.pitch),e.tr.setBearing(i.bearing)}else e.tr.setRoll(e.endEulerAngles.roll),e.tr.setPitch(e.endEulerAngles.pitch),e.tr.setBearing(e.endEulerAngles.bearing);else e.tr.setRoll(Yn.number(e.startEulerAngles.roll,e.endEulerAngles.roll,e.k)),e.tr.setPitch(Yn.number(e.startEulerAngles.pitch,e.endEulerAngles.pitch,e.k)),e.tr.setBearing(Yn.number(e.startEulerAngles.bearing,e.endEulerAngles.bearing,e.k))}function ks(e,t,n,r,i){let a=i.padding,o=wa(i.worldSize,n.getNorthWest()),s=wa(i.worldSize,n.getNorthEast()),c=wa(i.worldSize,n.getSouthEast()),l=wa(i.worldSize,n.getSouthWest()),u=k(-r),d=o.rotate(u),f=s.rotate(u),p=c.rotate(u),m=l.rotate(u),h=new z(Math.max(d.x,f.x,m.x,p.x),Math.max(d.y,f.y,m.y,p.y)),g=new z(Math.min(d.x,f.x,m.x,p.x),Math.min(d.y,f.y,m.y,p.y)),_=h.sub(g),v=i.width-(a.left+a.right+t.left+t.right),y=i.height-(a.top+a.bottom+t.top+t.bottom),b=v/_.x,x=y/_.y;if(x<0||b<0){Ds();return}let S=Math.min(ar(i.scale*Math.min(b,x)),e.maxZoom),C=z.convert(e.offset),w=new z((t.left-t.right)/2,(t.top-t.bottom)/2).rotate(k(r)),T=C.add(w).mult(i.scale/Se(S));return{center:Ta(i.worldSize,o.add(c).div(2).sub(T)),zoom:S,bearing:r}}var As=class{get useGlobeControls(){return!1}handlePanInertia(e,t){let n=e.mag(),r=Math.abs(Ea(t));return{easingOffset:e.mult(Math.min(r*.75/n,1)),easingCenter:t.center}}handleMapControlsRollPitchBearingZoom(e,t){e.bearingDelta&&t.setBearing(t.bearing+e.bearingDelta),e.pitchDelta&&t.setPitch(t.pitch+e.pitchDelta),e.rollDelta&&t.setRoll(t.roll+e.rollDelta),e.zoomDelta&&t.setZoom(t.zoom+e.zoomDelta)}handleMapControlsPan(e,t,n){e.around.distSqr(t.centerPoint)<.01||t.setLocationAtPoint(n,e.around)}cameraForBoxAndBearing(e,t,n,r,i){return ks(e,t,n,r,i)}handleJumpToCenterZoom(e,t){let n=t.zoom===void 0?e.zoom:+t.zoom;e.zoom!==n&&e.setZoom(+t.zoom),t.center!==void 0&&e.setCenter(B.convert(t.center))}handleEaseTo(e,t){let n=e.zoom,r=e.padding,i={roll:e.roll,pitch:e.pitch,bearing:e.bearing},a={roll:t.roll===void 0?e.roll:t.roll,pitch:t.pitch===void 0?e.pitch:t.pitch,bearing:t.bearing===void 0?e.bearing:t.bearing},o=t.zoom!==void 0,s=!e.isPaddingEqual(t.padding),c=!1,l=o?+t.zoom:e.zoom,u=e.centerPoint.add(t.offsetAsPoint),d=e.screenPointToLocation(u),{center:f,zoom:p}=e.applyConstrain(B.convert(t.center||d),l??n);gs(e,f);let m=wa(e.worldSize,d),h=wa(e.worldSize,f).sub(m),g=Se(p-n);return c=p!==n,{easeFunc:o=>{if(c&&e.setZoom(Yn.number(n,p,o)),Ge(i,a)||Os({startEulerAngles:i,endEulerAngles:a,tr:e,k:o,useSlerp:i.roll!=a.roll}),s&&(e.interpolatePadding(r,t.padding,o),u=e.centerPoint.add(t.offsetAsPoint)),t.around)e.setLocationAtPoint(t.around,t.aroundPoint);else{let t=Se(e.zoom-n),r=(p>n?Math.min(2,g):Math.max(.5,g))**(1-o),i=Ta(e.worldSize,m.add(h.mult(o*r)).mult(t));e.setLocationAtPoint(e.renderWorldCopies?i.wrap():i,u)}},isZooming:c,elevationCenter:f}}handleFlyTo(e,t){let n=t.zoom!==void 0,r=e.zoom,i=e.applyConstrain(B.convert(t.center||t.locationAtOffset),n?+t.zoom:r),a=i.center,o=i.zoom;gs(e,a);let s=e.worldSize,c=wa(s,t.locationAtOffset),l=wa(s,a).sub(c),u=l.mag(),d=Se(o-r),f=t.minZoom===void 0?e.minZoom:+t.minZoom,p=Math.max(f,e.minZoom),m=Math.min(p,r,o),h=e.applyConstrain(a,m).zoom;return{easeFunc:(t,n,i,u)=>{e.setZoom(t===1?o:r+ar(n));let d=t===1?a:Ta(s,c.add(l.mult(i)));e.setLocationAtPoint(e.renderWorldCopies?d.wrap():d,u)},scaleOfZoom:d,targetCenter:a,scaleOfMinZoom:Se(h-r),pixelPathLength:u}}};let js;const Ms=()=>js||=new ae({type:new nt(Ft.projection.type,`type`)});var Y=class{constructor(e,t,n){this.blendFunction=e,this.blendColor=t,this.mask=n}};Y.Replace=[1,0],Y.disabled=new Y(Y.Replace,V.transparent,[!1,!1,!1,!1]),Y.unblended=new Y(Y.Replace,V.transparent,[!0,!0,!0,!0]),Y.alphaBlended=new Y([1,771],V.transparent,[!0,!0,!0,!0]);const Ns=1029,Ps=2305;var X=class{constructor(e,t,n){this.enable=e,this.mode=t,this.frontFace=n}};X.disabled=new X(!1,Ns,Ps),X.backCCW=new X(!0,Ns,Ps),X.frontCCW=new X(!0,1028,Ps);var Z=class{constructor(e,t,n){this.func=e,this.mask=t,this.range=n}};Z.ReadOnly=!1,Z.ReadWrite=!0,Z.disabled=new Z(519,Z.ReadOnly,[0,1]);const Fs=7680;var Q=class{constructor(e,t,n,r,i,a){this.test=e,this.ref=t,this.mask=n,this.fail=r,this.depthFail=i,this.pass=a}};Q.disabled=new Q({func:519,mask:0},0,0,Fs,Fs,Fs);const Is=(e,t)=>({u_input:new H(e,t.u_input),u_output_expected:new H(e,t.u_output_expected)}),Ls=(e,t)=>({u_input:e,u_output_expected:t});var Rs=class e{get awaitingQuery(){return!!this._readbackQueue}constructor(e){this._readbackWaitFrames=4,this._measureWaitFrames=6,this._texWidth=1,this._texHeight=1,this._measuredError=0,this._updateCount=0,this._lastReadbackFrame=-1e3,this._readbackQueue=null,this._cachedRenderContext=e;let t=e.context,n=t.gl;this._texFormat=n.RGBA,this._texType=n.UNSIGNED_BYTE;let r=new O;r.emplaceBack(-1,-1),r.emplaceBack(2,-1),r.emplaceBack(-1,2);let i=new He;i.emplaceBack(0,1,2),this._fullscreenTriangle=new us(t.createVertexBuffer(r,ds.members),t.createIndexBuffer(i),o.simpleSegment(0,0,r.length,i.length)),this._resultBuffer=new Uint8Array(4),t.activeTexture.set(n.TEXTURE1);let a=n.createTexture();n.bindTexture(n.TEXTURE_2D,a),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.NEAREST),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.NEAREST),n.texStorage2D(n.TEXTURE_2D,1,n.RGBA8,this._texWidth,this._texHeight),this._fbo=t.createFramebuffer(this._texWidth,this._texHeight,!1,!1),this._fbo.colorAttachment.set(a),this._pbo=n.createBuffer(),n.bindBuffer(n.PIXEL_PACK_BUFFER,this._pbo),n.bufferData(n.PIXEL_PACK_BUFFER,4,n.STREAM_READ),n.bindBuffer(n.PIXEL_PACK_BUFFER,null)}destroy(){let e=this._cachedRenderContext.context.gl;this._fullscreenTriangle.destroy(),this._fbo.destroy(),e.deleteBuffer(this._pbo),this._fullscreenTriangle=null,this._fbo=null,this._pbo=null,this._resultBuffer=null}updateErrorLoop(e,t){let n=this._updateCount;return this._readbackQueue?n>=this._readbackQueue.frameNumberIssued+this._readbackWaitFrames&&this._tryReadback():n>=this._lastReadbackFrame+this._measureWaitFrames&&this._renderErrorTexture(e,t),this._updateCount++,this._measuredError}_bindFramebuffer(){let e=this._cachedRenderContext.context,t=e.gl;e.activeTexture.set(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this._fbo.colorAttachment.get()),e.bindFramebuffer.set(this._fbo.framebuffer)}_renderErrorTexture(e,t){let n=this._cachedRenderContext.context,r=n.gl;this._bindFramebuffer(),n.viewport.set([0,0,this._texWidth,this._texHeight]),n.clear({color:V.transparent}),this._cachedRenderContext.useProgram(`projectionErrorMeasurement`).draw(n,r.TRIANGLES,Z.disabled,Q.disabled,Y.unblended,X.disabled,Ls(e,t),null,null,`$clipping`,this._fullscreenTriangle.vertexBuffer,this._fullscreenTriangle.indexBuffer,this._fullscreenTriangle.segments),r.bindBuffer(r.PIXEL_PACK_BUFFER,this._pbo),r.readBuffer(r.COLOR_ATTACHMENT0),r.readPixels(0,0,this._texWidth,this._texHeight,this._texFormat,this._texType,0),r.bindBuffer(r.PIXEL_PACK_BUFFER,null);let i=r.fenceSync(r.SYNC_GPU_COMMANDS_COMPLETE,0);r.flush(),this._readbackQueue={frameNumberIssued:this._updateCount,sync:i}}_tryReadback(){let t=this._cachedRenderContext.context.gl;if(!this._readbackQueue)return;let n=t.clientWaitSync(this._readbackQueue.sync,0,0);if(n===t.WAIT_FAILED){a(`WebGL2 clientWaitSync failed.`),this._readbackQueue=null,this._lastReadbackFrame=this._updateCount;return}n!==t.TIMEOUT_EXPIRED&&(t.bindBuffer(t.PIXEL_PACK_BUFFER,this._pbo),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,this._resultBuffer,0,4),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),this._readbackQueue=null,this._measuredError=e._parseRGBA8float(this._resultBuffer),this._lastReadbackFrame=this._updateCount)}static _parseRGBA8float(e){let t=0;return t+=e[0]/256,t+=e[1]/65536,t+=e[2]/16777216,e[3]<127&&(t=-t),t/128}};const zs=M/128;function Bs(e,t){let n=Vs(t,`16bit`),r=O.deserialize({arrayBuffer:n.vertices,length:n.vertices.byteLength/2/2}),i=He.deserialize({arrayBuffer:n.indices,length:n.indices.byteLength/2/3});return new us(e.createVertexBuffer(r,ds.members),e.createIndexBuffer(i),o.simpleSegment(0,0,r.length,i.length))}function Vs(e,t){let n=e.granularity===void 0?1:Math.max(e.granularity,1),r=n+(e.generateBorders?2:0),i=n+(e.extendToNorthPole||e.generateBorders?1:0)+(e.extendToSouthPole||e.generateBorders?1:0),a=r+1,o=i+1,s=e.generateBorders?-1:0,c=e.generateBorders||e.extendToNorthPole?-1:0,l=n+ +!!e.generateBorders,u=n+(e.generateBorders||e.extendToSouthPole?1:0),d=a*o,f=r*i*6,p=a*o>65536;if(p&&t===`16bit`)throw Error(`Granularity is too large and meshes would not fit inside 16 bit vertex indices.`);let m=p||t===`32bit`,h=new Int16Array(d*2),g=0;for(let t=c;t<=u;t++)for(let r=s;r<=l;r++){let i=r/n*M;r===-1&&(i=-zs),r===n+1&&(i=M+zs);let a=t/n*M;t===-1&&(a=e.extendToNorthPole?wt:-zs),t===n+1&&(a=e.extendToSouthPole?En:M+zs),h[g++]=i,h[g++]=a}let _=m?new Uint32Array(f):new Uint16Array(f),v=0;for(let e=0;e0}get latitudeErrorCorrectionRadians(){return this._verticalPerspectiveProjection.latitudeErrorCorrectionRadians}get currentProjection(){return this.useGlobeRendering?this._verticalPerspectiveProjection:this._mercatorProjection}get name(){return`globe`}get useSubdivision(){return this.currentProjection.useSubdivision}get shaderVariantName(){return this.currentProjection.shaderVariantName}get shaderDefine(){return this.currentProjection.shaderDefine}get shaderPreludeCode(){return this.currentProjection.shaderPreludeCode}get vertexShaderPreludeCode(){return this.currentProjection.vertexShaderPreludeCode}get subdivisionGranularity(){return this.currentProjection.subdivisionGranularity}get useGlobeControls(){return this.transitionState>0}destroy(){this._mercatorProjection.destroy(),this._verticalPerspectiveProjection.destroy()}updateGPUdependent(e){this._mercatorProjection.updateGPUdependent(e),this._verticalPerspectiveProjection.updateGPUdependent(e)}getMeshFromTileID(e,t,n,r,i){return this.currentProjection.getMeshFromTileID(e,t,n,r,i)}setProjection(e){this._transitionable.setValue(`type`,e?.type||`mercator`)}updateTransitions(e){this._transitioning=this._transitionable.transitioned(e,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()||this.currentProjection.hasTransition()}recalculate(e){this.properties=this._transitioning.possiblyEvaluate(e)}setErrorQueryLatitudeDegrees(e){this._verticalPerspectiveProjection.setErrorQueryLatitudeDegrees(e),this._mercatorProjection.setErrorQueryLatitudeDegrees(e)}};function Ks(e){let t=Qs(e.worldSize,e.center.lat);return 2*Math.PI*t}function qs(e,t,n){let r=dt(Zs(t),Zs(n)),i=Math.acos(r),a=Ks(e);return i/(2*Math.PI)*a}function Js(e,t){return[kn(e*Math.PI*2+Math.PI,Math.PI*2),2*Math.atan(Math.exp(Math.PI-t*Math.PI*2))-Math.PI*.5]}function Ys(e,t){let n=Math.cos(t),r=new Float64Array(3);return r[0]=Math.sin(e)*n,r[1]=Math.sin(t),r[2]=Math.cos(e)*n,r}function Xs(e,t,n,r,i){let a=1/(1<1e-6){let r=e[0]/n,i=e[2]/n,a=Math.acos(i);return new B(sn((r>0?a:-a)/Math.PI*180,-180,180),t)}else return new B(0,t)}function ec(e){let t=I();return t[0]=e[0]*-e[3],t[1]=e[1]*-e[3],t[2]=e[2]*-e[3],{center:t,radius:Math.sqrt(1-e[3]*e[3])}}function tc(e,t,n){let r=I();xt(r,n,e);let i=I();return nn(i,e,r,t/ct(r)),i}function nc(e){return Math.cos(e*Math.PI/180)}function rc(e,t){let n=nc(e);return ar(nc(t)/n)}function ic(e,t){return 360/Ks({worldSize:e,center:{lat:t}})}function ac(e,t){let n=e.rotate(t.bearingInRadians),r=t.zoom+rc(t.center.lat,0),i=It(1/nc(t.center.lat),1/nc(Math.min(Math.abs(t.center.lat),60)),ur(r,7,3,0,1)),a=ic(t.worldSize,t.center.lat);return new B(t.center.lng-n.x*a*i,j(t.center.lat+n.y*a,-on,on))}function oc(e){let t=.5*e,n=Math.sin(t),r=Math.cos(t);return Math.log(n+r)-Math.log(r-n)}function sc(e,t,n,r){let i=e.lat+n*r;if(Math.abs(n)>1){let a=e.lat+n,o=(Math.sign(a)===Math.sign(e.lat)?Math.abs(e.lat):-Math.abs(e.lat))*Math.PI/180,s=Math.abs(e.lat+n)*Math.PI/180,c=oc(o+r*(s-o)),l=oc(o),u=oc(s),d=(c-l)/(u-l);return new B(e.lng+t*d,i)}else return new B(e.lng+t*r,i)}var cc=class{constructor(e){this._cachePrevious=new Map,this._cache=new Map,this._hadAnyChanges=!1,this._boundingVolumeFactory=e}swapBuffers(){if(!this._hadAnyChanges)return;let e=this._cachePrevious;this._cachePrevious=this._cache,this._cache=e,this._cache.clear(),this._hadAnyChanges=!1}getTileBoundingVolume(e,t,n,r){let i=`${e.z}_${e.x}_${e.y}_${r?.terrain?`t`:``}`,a=this._cache.get(i);if(a)return a;let o=this._cachePrevious.get(i);if(o)return this._cache.set(i,o),o;let s=this._boundingVolumeFactory(e,t,n,r);return this._cache.set(i,s),this._hadAnyChanges=!0,s}},lc=class e{constructor(e,t,n,r){this.min=n,this.max=r,this.points=e,this.planes=t}static fromAabb(t,n){let r=[];for(let e=0;e<8;e++)r.push([(e>>0&1)==1?n[0]:t[0],(e>>1&1)==1?n[1]:t[1],(e>>2&1)==1?n[2]:t[2]]);return new e(r,[[-1,0,0,n[0]],[1,0,0,-t[0]],[0,-1,0,n[1]],[0,1,0,-t[1]],[0,0,-1,n[2]],[0,0,1,-t[2]]],t,n)}static fromCenterSizeAngles(t,n,r){let i=tt([],r[0],r[1],r[2]),a=At([],[n[0],0,0],i),o=At([],[0,n[1],0],i),s=At([],[0,0,n[2]],i),c=[...t],l=[...t];for(let e=0;e<8;e++)for(let n=0;n<3;n++){let r=t[n]+a[n]*((e>>0&1)==1?1:-1)+o[n]*((e>>1&1)==1?1:-1)+s[n]*((e>>2&1)==1?1:-1);c[n]=Math.min(c[n],r),l[n]=Math.max(l[n],r)}let u=[];for(let e=0;e<8;e++){let n=[...t];he(n,n,In([],a,(e>>0&1)==1?1:-1)),he(n,n,In([],o,(e>>1&1)==1?1:-1)),he(n,n,In([],s,(e>>2&1)==1?1:-1)),u.push(n)}return new e(u,[[...a,-dt(a,u[0])],[...o,-dt(o,u[0])],[...s,-dt(s,u[0])],[-a[0],-a[1],-a[2],-dt(a,u[7])],[-o[0],-o[1],-o[2],-dt(o,u[7])],[-s[0],-s[1],-s[2],-dt(s,u[7])]],c,l)}intersectsFrustum(e){let t=!0,n=this.points.length,r=this.planes.length,i=e.planes.length,a=e.points.length;for(let r=0;r=0&&a++}if(a===0)return 0;ao&&(o=n)}let l=[c.lng+a,c.lat+s,c.lng+i,c.lat+o];return this.isSurfacePointOnScreen([0,1,0])&&(l[3]=90,l[0]=-180,l[2]=180),this.isSurfacePointOnScreen([0,-1,0])&&(l[1]=-90,l[0]=-180,l[2]=180),new Ri(l)}calculateCenterFromCameraLngLatAlt(e,t,n,r){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,n,r)}setLocationAtPoint(e,t){let n=Zs(this.unprojectScreenPoint(t)),r=Zs(e),i=I();pn(i);let a=I();Gn(a,n,i,-this.center.lng*Math.PI/180),Rt(a,a,i,this.center.lat*Math.PI/180);let o=r[0]*r[0]+r[2]*r[2],s=a[0]*a[0];if(o=-g&&p<=g,v=h>=-g&&h<=g,y,b;if(_&&v){let e=this.center.lng*Math.PI/180,t=this.center.lat*Math.PI/180,n=Mn(u,e),r=Mn(p,t),i=Mn(d,e),a=Mn(h,t);n+r=0}isSurfacePointOnScreen(e){if(!this.isSurfacePointVisible(e))return!1;let t=re();return A(t,[...e,1],this._globeViewProjMatrixNoCorrection),t[0]/=t[3],t[1]/=t[3],t[2]/=t[3],t[0]>-1&&t[0]<1&&t[1]>-1&&t[1]<1&&t[2]>-1&&t[2]<1}rayPlanetIntersection(e,t){let n=dt(e,t),r=I(),i=I();In(i,t,n),xt(r,e,i);let a=1-dt(r,r);if(a<0)return null;let o=dt(e,e)-1,s=-n+(n<0?1:-1)*Math.sqrt(a),c=o/s,l=s;return{tMin:Math.min(c,l),tMax:Math.max(c,l)}}unprojectScreenPoint(e){let n=this._cameraPosition,r=this.getRayDirectionFromPixel(e),i=this.rayPlanetIntersection(n,r);if(i){let e=I();he(e,n,[r[0]*i.tMin,r[1]*i.tMin,r[2]*i.tMin]);let a=I();return t(a,e),$s(a)}let a=this._cachedClippingPlane,o=a[0]*r[0]+a[1]*r[1]+a[2]*r[2],s=-vt(a,n)/o,c=I();if(s>0)he(c,n,[r[0]*s,r[1]*s,r[2]*s]);else{let e=I();he(e,n,[r[0]*2,r[1]*2,r[2]*2]);let t=vt(this._cachedClippingPlane,e);xt(c,e,[this._cachedClippingPlane[0]*t,this._cachedClippingPlane[1]*t,this._cachedClippingPlane[2]*t])}let l=ec(a);return $s(tc(l.center,l.radius,c))}getProjectionDataForCustomLayer(e=!0){let t=this.getProjectionData({overscaledTileID:new ht(0,0,0,0,0),applyGlobeMatrix:e});return t.tileMercatorCoords=[0,0,1,1],t}getFastPathSimpleProjectionMatrix(e){}},hc=class e{get pixelsToClipSpaceMatrix(){return this._helper.pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._helper.clipSpaceToPixelsMatrix}get pixelsToGLUnits(){return this._helper.pixelsToGLUnits}get centerOffset(){return this._helper.centerOffset}get size(){return this._helper.size}get rotationMatrix(){return this._helper.rotationMatrix}get centerPoint(){return this._helper.centerPoint}get pixelsPerMeter(){return this._helper.pixelsPerMeter}setMinZoom(e){this._helper.setMinZoom(e)}setMaxZoom(e){this._helper.setMaxZoom(e)}setMinPitch(e){this._helper.setMinPitch(e)}setMaxPitch(e){this._helper.setMaxPitch(e)}setRenderWorldCopies(e){this._helper.setRenderWorldCopies(e)}setBearing(e){this._helper.setBearing(e)}setPitch(e){this._helper.setPitch(e)}setRoll(e){this._helper.setRoll(e)}setFov(e){this._helper.setFov(e)}setZoom(e){this._helper.setZoom(e)}setCenter(e){this._helper.setCenter(e)}setElevation(e){this._helper.setElevation(e)}setMinElevationForCurrentTile(e){this._helper.setMinElevationForCurrentTile(e)}setPadding(e){this._helper.setPadding(e)}interpolatePadding(e,t,n){this._helper.interpolatePadding(e,t,n)}isPaddingEqual(e){return this._helper.isPaddingEqual(e)}resize(e,t,n=!0){this._helper.resize(e,t,n)}getMaxBounds(){return this._helper.getMaxBounds()}setMaxBounds(e){this._helper.setMaxBounds(e)}setConstrainOverride(e){this._helper.setConstrainOverride(e)}overrideNearFarZ(e,t){this._helper.overrideNearFarZ(e,t)}clearNearFarZOverride(){this._helper.clearNearFarZOverride()}getCameraQueryGeometry(e){return this._helper.getCameraQueryGeometry(this.getCameraPoint(),e)}get tileSize(){return this._helper.tileSize}get tileZoom(){return this._helper.tileZoom}get scale(){return this._helper.scale}get worldSize(){return this._helper.worldSize}get width(){return this._helper.width}get height(){return this._helper.height}get lngRange(){return this._helper.lngRange}get latRange(){return this._helper.latRange}get minZoom(){return this._helper.minZoom}get maxZoom(){return this._helper.maxZoom}get zoom(){return this._helper.zoom}get center(){return this._helper.center}get minPitch(){return this._helper.minPitch}get maxPitch(){return this._helper.maxPitch}get pitch(){return this._helper.pitch}get pitchInRadians(){return this._helper.pitchInRadians}get roll(){return this._helper.roll}get rollInRadians(){return this._helper.rollInRadians}get bearing(){return this._helper.bearing}get bearingInRadians(){return this._helper.bearingInRadians}get fov(){return this._helper.fov}get fovInRadians(){return this._helper.fovInRadians}get elevation(){return this._helper.elevation}get minElevationForCurrentTile(){return this._helper.minElevationForCurrentTile}get padding(){return this._helper.padding}get unmodified(){return this._helper.unmodified}get renderWorldCopies(){return this._helper.renderWorldCopies}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}get constrainOverride(){return this._helper.constrainOverride}get nearZ(){return this._helper.nearZ}get farZ(){return this._helper.farZ}get autoCalculateNearFarZ(){return this._helper.autoCalculateNearFarZ}get isGlobeRendering(){return this._globeness>0}setTransitionState(e,t){this._globeness=e,this._globeLatitudeErrorCorrectionRadians=t,this._calcMatrices(),this._verticalPerspectiveTransform.getCoveringTilesDetailsProvider().prepareNextFrame(),this._mercatorTransform.getCoveringTilesDetailsProvider().prepareNextFrame()}get currentTransform(){return this.isGlobeRendering?this._verticalPerspectiveTransform:this._mercatorTransform}constructor(e){this._globeLatitudeErrorCorrectionRadians=0,this._globeness=1,this.defaultConstrain=(e,t)=>this.currentTransform.defaultConstrain(e,t),this.applyConstrain=(e,t)=>this._helper.applyConstrain(e,t),this._helper=new vs({calcMatrices:()=>this._calcMatrices(),defaultConstrain:(e,t)=>this.defaultConstrain(e,t)},e),this._globeness=1,this._mercatorTransform=new Es,this._verticalPerspectiveTransform=new mc}clone(){let t=new e;return t._globeness=this._globeness,t._globeLatitudeErrorCorrectionRadians=this._globeLatitudeErrorCorrectionRadians,t.apply(this,!1),t}apply(e,t){this._helper.apply(e,t),this._mercatorTransform.apply(this,!1),this._verticalPerspectiveTransform.apply(this,!1,this._globeLatitudeErrorCorrectionRadians)}get projectionMatrix(){return this.currentTransform.projectionMatrix}get modelViewProjectionMatrix(){return this.currentTransform.modelViewProjectionMatrix}get inverseProjectionMatrix(){return this.currentTransform.inverseProjectionMatrix}get cameraPosition(){return this.currentTransform.cameraPosition}getProjectionData(e){let t=this._mercatorTransform.getProjectionData(e),n=this._verticalPerspectiveTransform.getProjectionData(e);return{mainMatrix:this.isGlobeRendering?n.mainMatrix:t.mainMatrix,clippingPlane:n.clippingPlane,tileMercatorCoords:n.tileMercatorCoords,projectionTransition:e.applyGlobeMatrix?this._globeness:0,fallbackMatrix:t.fallbackMatrix}}isLocationOccluded(e){return this.currentTransform.isLocationOccluded(e)}transformLightDirection(e){return this.currentTransform.transformLightDirection(e)}getPixelScale(){return It(this._mercatorTransform.getPixelScale(),this._verticalPerspectiveTransform.getPixelScale(),this._globeness)}getCircleRadiusCorrection(){return It(this._mercatorTransform.getCircleRadiusCorrection(),this._verticalPerspectiveTransform.getCircleRadiusCorrection(),this._globeness)}getPitchedTextCorrection(e,t,n){return It(this._mercatorTransform.getPitchedTextCorrection(e,t,n),this._verticalPerspectiveTransform.getPitchedTextCorrection(e,t,n),this._globeness)}projectTileCoordinates(e,t,n,r){return this.currentTransform.projectTileCoordinates(e,t,n,r)}_calcMatrices(){!this._helper._width||!this._helper._height||(this._verticalPerspectiveTransform.apply(this,!1,this._globeLatitudeErrorCorrectionRadians),this._helper._nearZ=this._verticalPerspectiveTransform.nearZ,this._helper._farZ=this._verticalPerspectiveTransform.farZ,this._mercatorTransform.apply(this,!0,this.isGlobeRendering),this._helper._nearZ=this._mercatorTransform.nearZ,this._helper._farZ=this._mercatorTransform.farZ)}calculateFogMatrix(e){return this.currentTransform.calculateFogMatrix(e)}getVisibleUnwrappedCoordinates(e){return this.currentTransform.getVisibleUnwrappedCoordinates(e)}getCameraFrustum(){return this.currentTransform.getCameraFrustum()}getClippingPlane(){return this.currentTransform.getClippingPlane()}getCoveringTilesDetailsProvider(){return this.currentTransform.getCoveringTilesDetailsProvider()}recalculateZoomAndCenter(e){this.currentTransform.recalculateZoomAndCenter(e)}maxPitchScaleFactor(){return this._mercatorTransform.maxPitchScaleFactor()}getCameraPoint(){return this._helper.getCameraPoint()}getCameraAltitude(){return this._helper.getCameraAltitude()}getCameraLngLat(){return this._helper.getCameraLngLat()}lngLatToCameraDepth(e,t){return this.currentTransform.lngLatToCameraDepth(e,t)}populateCache(e){this._mercatorTransform.populateCache(e),this._verticalPerspectiveTransform.populateCache(e)}getBounds(){return this.currentTransform.getBounds()}calculateCenterFromCameraLngLatAlt(e,t,n,r){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,n,r)}setLocationAtPoint(e,t){if(!this.isGlobeRendering){this._mercatorTransform.setLocationAtPoint(e,t),this.apply(this._mercatorTransform,!1);return}this._verticalPerspectiveTransform.setLocationAtPoint(e,t),this.apply(this._verticalPerspectiveTransform,!1)}locationToScreenPoint(e,t){return this.currentTransform.locationToScreenPoint(e,t)}screenPointToMercatorCoordinate(e,t){return this.currentTransform.screenPointToMercatorCoordinate(e,t)}screenPointToLocation(e,t){return this.currentTransform.screenPointToLocation(e,t)}isPointOnMapSurface(e,t){return this.currentTransform.isPointOnMapSurface(e,t)}getRayDirectionFromPixel(e){return this._verticalPerspectiveTransform.getRayDirectionFromPixel(e)}getProjectionDataForCustomLayer(e=!0){let t=this._mercatorTransform.getProjectionDataForCustomLayer(e);if(!this.isGlobeRendering)return t;let n=this._verticalPerspectiveTransform.getProjectionDataForCustomLayer(e);return n.fallbackMatrix=t.mainMatrix,n}getFastPathSimpleProjectionMatrix(e){return this.currentTransform.getFastPathSimpleProjectionMatrix(e)}},gc=class e{get useGlobeControls(){return!0}handlePanInertia(e,t){let n=ac(e,t);return Math.abs(n.lng-t.center.lng)>180&&(n.lng=t.center.lng+179.5*Math.sign(n.lng-t.center.lng)),{easingCenter:n,easingOffset:new z(0,0)}}handleMapControlsRollPitchBearingZoom(e,t){let n=e.around,r=t.screenPointToLocation(n);e.bearingDelta&&t.setBearing(t.bearing+e.bearingDelta),e.pitchDelta&&t.setPitch(t.pitch+e.pitchDelta),e.rollDelta&&t.setRoll(t.roll+e.rollDelta);let i=t.zoom;e.zoomDelta&&t.setZoom(t.zoom+e.zoomDelta);let a=t.zoom-i;if(a===0)return;let o=me(t.center.lng,r.lng),s=o/(Math.abs(o/180)+1),c=me(t.center.lat,r.lat),l=t.getRayDirectionFromPixel(n),u=t.cameraPosition,d=dt(u,l)*-1,f=I();he(f,u,[l[0]*d,l[1]*d,l[2]*d]);let p=pt(f)-1,m=Math.exp(-Math.max(p-.3,0)*.5),h=Qs(t.worldSize,t.center.lat)/Math.min(t.width,t.height),g=ur(h,.9,.5,1,.25),_=(1-Se(-a))*Math.min(m,g),v=t.center.lat,y=t.zoom,b=new B(t.center.lng+s*_,j(t.center.lat+c*_,-on,on));t.setLocationAtPoint(r,n);let x=t.center,S=ur(Math.abs(o),45,85,0,1),C=ur(h,.75,.35,0,1),w=Math.max(S,C)**.25,T=me(x.lng,b.lng),ee=me(x.lat,b.lat);t.setCenter(new B(x.lng+T*w,x.lat+ee*w).wrap()),t.setZoom(y+rc(v,t.center.lat))}handleMapControlsPan(e,t,n){if(!e.panDelta)return;let r=t.center.lat,i=t.zoom;t.setCenter(ac(e.panDelta,t).wrap()),t.setZoom(i+rc(r,t.center.lat))}cameraForBoxAndBearing(t,n,r,i,a){let o=ks(t,n,r,i,a),s=n.left/a.width*2-1,c=(a.width-n.right)/a.width*2-1,l=n.top/a.height*-2+1,u=(a.height-n.bottom)/a.height*-2+1,d=me(r.getWest(),r.getEast())<0,f=d?r.getEast():r.getWest(),p=d?r.getWest():r.getEast(),m=Math.max(r.getNorth(),r.getSouth()),h=Math.min(r.getNorth(),r.getSouth()),g=f+me(f,p)*.5,_=m+me(m,h)*.5,v=a.clone();v.setCenter(o.center),v.setBearing(o.bearing),v.setPitch(0),v.setRoll(0),v.setZoom(o.zoom);let y=v.modelViewProjectionMatrix,b=[Zs(r.getNorthWest()),Zs(r.getNorthEast()),Zs(r.getSouthWest()),Zs(r.getSouthEast()),Zs(new B(p,_)),Zs(new B(f,_)),Zs(new B(g,m)),Zs(new B(g,h))],x=Zs(o.center),S=1/0;for(let t of b)s<0&&(S=e.getLesserNonNegativeNonNull(S,e.solveVectorScale(t,x,y,`x`,s))),c>0&&(S=e.getLesserNonNegativeNonNull(S,e.solveVectorScale(t,x,y,`x`,c))),l>0&&(S=e.getLesserNonNegativeNonNull(S,e.solveVectorScale(t,x,y,`y`,l))),u<0&&(S=e.getLesserNonNegativeNonNull(S,e.solveVectorScale(t,x,y,`y`,u)));if(!Number.isFinite(S)||S===0){Ds();return}return o.zoom=Math.min(v.zoom+ar(S),t.maxZoom),o}handleJumpToCenterZoom(e,t){let n=e.center.lat,r=e.applyConstrain(t.center?B.convert(t.center):e.center,e.zoom).center;e.setCenter(r.wrap());let i=t.zoom===void 0?e.zoom+rc(n,r.lat):+t.zoom;e.zoom!==i&&e.setZoom(i)}handleEaseTo(e,t){let n=e.zoom,r=e.center,i=e.padding,o={roll:e.roll,pitch:e.pitch,bearing:e.bearing},s={roll:t.roll===void 0?e.roll:t.roll,pitch:t.pitch===void 0?e.pitch:t.pitch,bearing:t.bearing===void 0?e.bearing:t.bearing},c=t.zoom!==void 0,l=!e.isPaddingEqual(t.padding),u=!1,d=t.center?B.convert(t.center):r,f=e.applyConstrain(d,n).center;gs(e,f);let p=e.clone();p.setCenter(f),p.setZoom(c?+t.zoom:n+rc(r.lat,d.lat)),p.setBearing(t.bearing);let m=new z(j(e.centerPoint.x+t.offsetAsPoint.x,0,e.width),j(e.centerPoint.y+t.offsetAsPoint.y,0,e.height));p.setLocationAtPoint(f,m);let h=(t.offset&&t.offsetAsPoint.mag())>0?p.center:f,g=c?+t.zoom:n+rc(r.lat,h.lat),_=n+rc(r.lat,0),v=g+rc(h.lat,0),y=me(r.lng,h.lng),b=me(r.lat,h.lat),x=Se(v-_);return u=g!==n,{easeFunc:n=>{if(Ge(o,s)||Os({startEulerAngles:o,endEulerAngles:s,tr:e,k:n,useSlerp:o.roll!=s.roll}),l&&e.interpolatePadding(i,t.padding,n),t.around)a(`Easing around a point is not supported under globe projection.`),e.setLocationAtPoint(t.around,t.aroundPoint);else{let t=n*(v>_?Math.min(2,x):Math.max(.5,x))**(1-n),i=sc(r,y,b,t);e.setCenter(i.wrap())}if(u){let t=Yn.number(_,v,n)+rc(0,e.center.lat);e.setZoom(t)}},isZooming:u,elevationCenter:h}}handleFlyTo(e,t){let n=t.zoom!==void 0,r=e.center,i=e.zoom,a=e.padding,o=!e.isPaddingEqual(t.padding),s=e.applyConstrain(B.convert(t.center||t.locationAtOffset),i).center,c=n?+t.zoom:e.zoom+rc(e.center.lat,s.lat),l=e.clone();l.setCenter(s),l.setZoom(c),l.setBearing(t.bearing);let u=new z(j(e.centerPoint.x+t.offsetAsPoint.x,0,e.width),j(e.centerPoint.y+t.offsetAsPoint.y,0,e.height));l.setLocationAtPoint(s,u);let d=l.center;gs(e,d);let f=qs(e,r,d),p=i+rc(r.lat,0),m=c+rc(d.lat,0),h=Se(m-p),g=typeof t.minZoom==`number`?+t.minZoom:e.minZoom,_=Math.max(g,e.minZoom)+rc(d.lat,0),v=Math.min(_,p,m)+rc(0,d.lat),y=Se(e.applyConstrain(d,v).zoom+rc(d.lat,0)-p),b=me(r.lng,d.lng),x=me(r.lat,d.lat);return{easeFunc:(n,i,s,l)=>{let u=sc(r,b,x,s);o&&e.interpolatePadding(a,t.padding,n);let f=n===1?d:u;e.setCenter(f.wrap());let m=p+ar(i);e.setZoom(n===1?c:m+rc(0,f.lat))},scaleOfZoom:h,targetCenter:d,scaleOfMinZoom:y,pixelPathLength:f}}static solveVectorScale(e,t,n,r,i){let a=i,o=r===`x`?[n[0],n[4],n[8],n[12]]:[n[1],n[5],n[9],n[13]],s=[n[3],n[7],n[11],n[15]],c=e[0]*o[0]+e[1]*o[1]+e[2]*o[2],l=e[0]*s[0]+e[1]*s[1]+e[2]*s[2],u=t[0]*o[0]+t[1]*o[1]+t[2]*o[2],d=t[0]*s[0]+t[1]*s[1]+t[2]*s[2],f=(u+o[3]-a*d-a*s[3])/(u-c-a*d+a*l);return u+a*l===c+a*d||s[3]*(c-u)+o[3]*(d-l)+c*d===u*l?null:f}static getLesserNonNegativeNonNull(e,t){return t!==null&&t>=0&&ts;this._popup?.isOpen()&&d&&this._popup.remove(),this._element.style.opacity=d?this._opacityWhenCovered:this._opacity,this._element.classList.toggle(`maplibregl-marker-covered`,d)}getOffset(){return this._offset}setOffset(e){return this._offset=z.convert(e),this._update(),this}addClassName(e){this._element.classList.add(e)}removeClassName(e){this._element.classList.remove(e)}toggleClassName(e){return this._element.classList.toggle(e)}setDraggable(e){return this._draggable=!!e,this._map&&(e?(this._map.on(`mousedown`,this._addDragHandler),this._map.on(`touchstart`,this._addDragHandler)):(this._map.off(`mousedown`,this._addDragHandler),this._map.off(`touchstart`,this._addDragHandler))),this}isDraggable(){return this._draggable}setRotation(e){return this._rotation=e||0,this._update(),this}getRotation(){return this._rotation}setRotationAlignment(e){return this._rotationAlignment=e||`auto`,this._update(),this}getRotationAlignment(){return this._rotationAlignment}setPitchAlignment(e){return this._pitchAlignment=e&&e!==`auto`?e:this._rotationAlignment,this._update(),this}getPitchAlignment(){return this._pitchAlignment}setOpacity(e,t){return(this._opacity===void 0||e===void 0&&t===void 0)&&(this._opacity=`1`,this._opacityWhenCovered=`0.2`),e!==void 0&&(this._opacity=String(e)),t!==void 0&&(this._opacityWhenCovered=String(t)),this._map&&this._updateOpacity(!0),this}};const jp={positionOptions:{enableHighAccuracy:!1,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showAccuracyCircle:!0,showUserLocation:!0};let Mp=0,Np=!1;var Pp=class extends On{},Fp=class extends On{},Ip=class extends On{},Lp=class extends _n{constructor(e){super(),this._onSuccess=e=>{if(this._map){if(this._isOutOfMapMaxBounds(e)){this._setErrorState(),this.fire(new Fp(`outofmaxbounds`,e)),this._updateMarker(),this._finish();return}if(this.options.trackUserLocation)switch(this._lastKnownPosition=e,this._watchState){case`WAITING_ACTIVE`:case`ACTIVE_LOCK`:case`ACTIVE_ERROR`:this._watchState=`ACTIVE_LOCK`,this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-waiting`),this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-active-error`),this._geolocateButton.classList.add(`maplibregl-ctrl-geolocate-active`);break;case`BACKGROUND`:case`BACKGROUND_ERROR`:this._watchState=`BACKGROUND`,this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-waiting`),this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-background-error`),this._geolocateButton.classList.add(`maplibregl-ctrl-geolocate-background`);break;default:throw Error(`Unexpected watchState ${this._watchState}`)}this.options.showUserLocation&&this._watchState!==`OFF`&&this._updateMarker(e),(!this.options.trackUserLocation||this._watchState===`ACTIVE_LOCK`)&&this._updateCamera(e),this.options.showUserLocation&&this._dotElement.classList.remove(`maplibregl-user-location-dot-stale`),this.fire(new Fp(`geolocate`,e)),this._finish()}},this._updateCamera=e=>{let t=new B(e.coords.longitude,e.coords.latitude),n=e.coords.accuracy,r=L({bearing:this._map.getBearing()},this.options.fitBoundsOptions),i=Ri.fromLngLat(t,n);this._map.fitBounds(i,r,{geolocateSource:!0})},this._updateMarker=e=>{if(e){let t=new B(e.coords.longitude,e.coords.latitude);this._accuracyCircleMarker.setLngLat(t).addTo(this._map),this._userLocationDotMarker.setLngLat(t).addTo(this._map),this._accuracy=e.coords.accuracy,this._updateCircleRadiusIfNeeded()}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove()},this._onUpdate=()=>{this._updateCircleRadiusIfNeeded()},this._onError=e=>{if(this._map){if(e.code===1){this._watchState=`OFF`,this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-waiting`),this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-active`),this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-active-error`),this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-background`),this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-background-error`),this._geolocateButton.disabled=!0;let e=this._map._getUIString(`GeolocateControl.LocationNotAvailable`);this._geolocateButton.title=e,this._geolocateButton.setAttribute(`aria-label`,e),this._geolocationWatchID!==void 0&&this._clearWatch()}else if(e.code===3&&Np)return;else this._setErrorState();this._watchState!==`OFF`&&this.options.showUserLocation&&this._dotElement.classList.add(`maplibregl-user-location-dot-stale`),this.fire(new Ip(`error`,e)),this._finish()}},this._finish=()=>{this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0},this._onMoveStart=e=>{if(!this._map)return;let t=e?.[0]instanceof ResizeObserverEntry;!e.geolocateSource&&this._watchState===`ACTIVE_LOCK`&&!t&&!this._map.isZooming()&&(this._watchState=`BACKGROUND`,this._geolocateButton.classList.add(`maplibregl-ctrl-geolocate-background`),this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-active`),this.fire(new Pp(`trackuserlocationend`)),this.fire(new Pp(`userlocationlostfocus`)))},this._setupUI=()=>{this._map&&(this._container.addEventListener(`contextmenu`,e=>{e.preventDefault()}),this._geolocateButton=W.create(`button`,`maplibregl-ctrl-geolocate`,this._container),W.create(`span`,`maplibregl-ctrl-icon`,this._geolocateButton).setAttribute(`aria-hidden`,`true`),this._geolocateButton.type=`button`,this._geolocateButton.disabled=!0)},this._finishSetupUI=e=>{if(this._map){if(e===!1){a(`Geolocation support is not available so the GeolocateControl will be disabled.`);let e=this._map._getUIString(`GeolocateControl.LocationNotAvailable`);this._geolocateButton.disabled=!0,this._geolocateButton.title=e,this._geolocateButton.setAttribute(`aria-label`,e)}else{let e=this._map._getUIString(`GeolocateControl.FindMyLocation`);this._geolocateButton.disabled=!1,this._geolocateButton.title=e,this._geolocateButton.setAttribute(`aria-label`,e)}this.options.trackUserLocation&&(this._geolocateButton.setAttribute(`aria-pressed`,`false`),this._watchState=`OFF`),this.options.showUserLocation&&(this._dotElement=W.create(`div`,`maplibregl-user-location-dot`),this._userLocationDotMarker=new Ap({element:this._dotElement}),this._circleElement=W.create(`div`,`maplibregl-user-location-accuracy-circle`),this._accuracyCircleMarker=new Ap({element:this._circleElement,pitchAlignment:`map`}),this.options.trackUserLocation&&(this._watchState=`OFF`),this._map.on(`zoom`,this._onUpdate),this._map.on(`move`,this._onUpdate),this._map.on(`rotate`,this._onUpdate),this._map.on(`pitch`,this._onUpdate)),this._geolocateButton.addEventListener(`click`,()=>this.trigger()),this._setup=!0,this.options.trackUserLocation&&this._map.on(`movestart`,this._onMoveStart)}},this.options=L({},jp,e)}onAdd(e){return this._map=e,this._container=W.create(`div`,`maplibregl-ctrl maplibregl-ctrl-group`),this._setupUI(),wp().then(e=>this._finishSetupUI(e)),this._container}onRemove(){this._geolocationWatchID!==void 0&&(window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),this._container.remove(),this._map.off(`movestart`,this._onMoveStart),this._map.off(`zoom`,this._onUpdate),this._map.off(`move`,this._onUpdate),this._map.off(`rotate`,this._onUpdate),this._map.off(`pitch`,this._onUpdate),this._map=void 0,Mp=0,Np=!1}_isOutOfMapMaxBounds(e){let t=this._map.getMaxBounds(),n=e.coords;return t&&(n.longitudec&&(_=c-n)}if(_!==void 0||v!==void 0){let e=new l(_??h,v??g);n.center=Mn(i,e).wrap()}return n},this.applyConstrain=(e,t)=>this._helper.applyConstrain(e,t),this._helper=new rc({calcMatrices:()=>this._calcMatrices(),defaultConstrain:(e,t)=>this.defaultConstrain(e,t)},e),this._coveringTilesDetailsProvider=new ac}clone(){let e=new t;return e.apply(this,!1),e}apply(e,t,n){this._helper.apply(e,t,n)}get cameraPosition(){return this._cameraPosition}get projectionMatrix(){return this._projectionMatrix}get modelViewProjectionMatrix(){return this._viewProjMatrix}get inverseProjectionMatrix(){return this._invProjMatrix}get mercatorMatrix(){return this._mercatorMatrix}getVisibleUnwrappedCoordinates(e){let t=[new Tt(0,e)];if(this._helper._renderWorldCopies){let n=this.screenPointToMercatorCoordinate(new l(0,0)),r=this.screenPointToMercatorCoordinate(new l(this._helper._width,0)),i=this.screenPointToMercatorCoordinate(new l(this._helper._width,this._helper._height)),a=this.screenPointToMercatorCoordinate(new l(0,this._helper._height)),o=Math.floor(Math.min(n.x,r.x,i.x,a.x)),s=Math.floor(Math.max(n.x,r.x,i.x,a.x));for(let n=o-1;n<=s+1;n++)n!==0&&t.push(new Tt(n,e))}return t}getCameraFrustum(){return oc.fromInvProjectionMatrix(this._invViewProjMatrix,this.worldSize)}getClippingPlane(){return null}getCoveringTilesDetailsProvider(){return this._coveringTilesDetailsProvider}recalculateZoomAndCenter(e){let t=this.screenPointToLocation(this.centerPoint,e),n=e?e.getElevationForLngLat(t,this):0;this._helper.recalculateZoomAndCenter(n)}setLocationAtPoint(e,t,n=this.elevation){let r=n-this.elevation,i=this.screenPointToMercatorCoordinateAtZ(t,r),a=this.screenPointToMercatorCoordinateAtZ(this.centerPoint,0),o=B.fromLngLat(e),s=new B(o.x-(i.x-a.x),o.y-(i.y-a.y));this.setCenter(s?.toLngLat()),this._helper._renderWorldCopies&&this.setCenter(this.center.wrap())}locationToScreenPoint(e,t){return t?this.coordinatePoint(B.fromLngLat(e),t.getElevationForLngLat(e,this),this._pixelMatrix3D):this.coordinatePoint(B.fromLngLat(e))}screenPointToLocation(e,t){return this.screenPointToMercatorCoordinate(e,t)?.toLngLat()}screenPointToLocationAtElevation(e,t){return this.screenPointToMercatorCoordinateAtZ(e,t-this.elevation)?.toLngLat()}screenPointToMercatorCoordinate(e,t){if(t){let n=this.screenTerrainPointToMercatorCoordinate(e,t);if(n!=null)return n}return this.screenPointToMercatorCoordinateAtZ(e)}screenTerrainPointToMercatorCoordinate(e,t){let n=t.getCoverageIndex();if(!n)return null;let{near:r,far:i}=this.getRaySegmentFromPixel(e),a=this.worldSize,o=i[0]-r[0],s=i[1]-r[1],c=i[2]-r[2],l={index:n,exaggeration:t.exaggeration,near:r,dx:o,dy:s,dz:c,worldSize:a},u=0,d=1;if(c===0){if(r[2]>n.maxElevation||r[2]o&&(o=n)}let u=[c.lng+a,c.lat+s,c.lng+i,c.lat+o];return this.isSurfacePointOnScreen([0,1,0])&&(u[3]=90,u[0]=-180,u[2]=180),this.isSurfacePointOnScreen([0,-1,0])&&(u[1]=-90,u[0]=-180,u[2]=180),new _a(u)}calculateCenterFromCameraLngLatAlt(e,t,n,r){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,n,r)}setLocationAtPoint(e,t,n){let r=Ic(this.unprojectScreenPoint(t)),i=Ic(e),a=L();cr(a);let o=L();ir(o,r,a,-this.center.lng*Math.PI/180),Sn(o,o,a,this.center.lat*Math.PI/180);let s=i[0]*i[0]+i[2]*i[2],c=o[0]*o[0];if(ss;this._popup?.isOpen()&&f&&this._popup.remove(),this._element.style.opacity=f?this._opacityWhenCovered:this._opacity,this._element.classList.toggle(`maplibregl-marker-covered`,f)}getOffset(){return this._offset}setOffset(e){return this._offset=l.convert(e),this._update(),this}addClassName(e){this._element.classList.add(e)}removeClassName(e){this._element.classList.remove(e)}toggleClassName(e){return this._element.classList.toggle(e)}setDraggable(e){return this._draggable=!!e,this._element.classList.toggle(`maplibregl-marker-draggable`,this._draggable),this._map&&(e?(this._map.on(`mousedown`,this._addDragHandler),this._map.on(`touchstart`,this._addDragHandler)):(this._map.off(`mousedown`,this._addDragHandler),this._map.off(`touchstart`,this._addDragHandler))),this._defaultMarker&&(this._draggable?(this._element.addEventListener(`keydown`,this._onKeyDown),this._element.addEventListener(`keyup`,this._onKeyUp),this._element.addEventListener(`blur`,this._onBlur)):(this._element.removeEventListener(`keydown`,this._onKeyDown),this._element.removeEventListener(`keyup`,this._onKeyUp),this._element.removeEventListener(`blur`,this._onBlur),this._endKeyboardDrag())),this._updateTabIndex(),this._updateAccessibilityRole(),this}isDraggable(){return this._draggable}_updateTabIndex(){this._popup||this._defaultMarker&&this._draggable?this._element.hasAttribute(`tabindex`)||(this._element.setAttribute(`tabindex`,`0`),this._tabIndexManaged=!0):this._tabIndexManaged&&=(this._element.getAttribute(`tabindex`)===`0`&&this._element.removeAttribute(`tabindex`),!1)}_updateAccessibilityRole(){if(!this._defaultMarker||this._element.hasAttribute(`role`)&&!this._roleManaged)return;let e=this._draggable||this._popup?`button`:`img`;this._element.setAttribute(`role`,e),this._roleManaged=!0}setRotation(e){return this._rotation=e||0,this._update(),this}getRotation(){return this._rotation}setRotationAlignment(e){return this._rotationAlignment=e||`auto`,this._update(),this}getRotationAlignment(){return this._rotationAlignment}setPitchAlignment(e){return this._pitchAlignment=e&&e!==`auto`?e:this._rotationAlignment,this._update(),this}getPitchAlignment(){return this._pitchAlignment}setOpacity(e,t){return(this._opacity===void 0||e===void 0&&t===void 0)&&(this._opacity=`1`,this._opacityWhenCovered=`0.2`),e!==void 0&&(this._opacity=String(e)),t!==void 0&&(this._opacityWhenCovered=String(t)),this._map&&this._updateOpacity(!0),this}};const bm={positionOptions:{enableHighAccuracy:!1,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showAccuracyCircle:!0,showUserLocation:!0};let xm=0,Sm=!1;var Cm=class extends Xe{},wm=class extends Xe{},Tm=class extends Xe{},Em=class extends h{constructor(e){super(),this._onSuccess=e=>{if(this._map){if(this._isOutOfMapMaxBounds(e)){this._setErrorState(),this.fire(new wm(`outofmaxbounds`,e)),this._updateMarker(),this._finish();return}if(this.options.trackUserLocation)switch(this._lastKnownPosition=e,this._watchState){case`WAITING_ACTIVE`:case`ACTIVE_LOCK`:case`ACTIVE_ERROR`:this._watchState=`ACTIVE_LOCK`,this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-waiting`),this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-active-error`),this._geolocateButton.classList.add(`maplibregl-ctrl-geolocate-active`);break;case`BACKGROUND`:case`BACKGROUND_ERROR`:this._watchState=`BACKGROUND`,this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-waiting`),this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-background-error`),this._geolocateButton.classList.add(`maplibregl-ctrl-geolocate-background`);break;default:throw Error(`Unexpected watchState ${this._watchState}`)}this.options.showUserLocation&&this._watchState!==`OFF`&&this._updateMarker(e),(!this.options.trackUserLocation||this._watchState===`ACTIVE_LOCK`)&&this._updateCamera(e),this.options.showUserLocation&&this._dotElement.classList.remove(`maplibregl-user-location-dot-stale`),this.fire(new wm(`geolocate`,e)),this._finish()}},this._updateCamera=e=>{let t=new V(e.coords.longitude,e.coords.latitude),n=e.coords.accuracy,r=this._map.getBearing(),i=z({bearing:r},this.options.fitBoundsOptions),a=_a.fromLngLat(t,n);this._map.fitBounds(a,i,{geolocateSource:!0})},this._updateMarker=e=>{if(e){let t=new V(e.coords.longitude,e.coords.latitude);this._accuracyCircleMarker.setLngLat(t).addTo(this._map),this._userLocationDotMarker.setLngLat(t).addTo(this._map),this._accuracy=e.coords.accuracy,this._updateCircleRadiusIfNeeded()}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove()},this._onUpdate=()=>{this._updateCircleRadiusIfNeeded()},this._onError=e=>{if(this._map){if(e.code===1){this._watchState=`OFF`,this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-waiting`),this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-active`),this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-active-error`),this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-background`),this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-background-error`),this._geolocateButton.disabled=!0;let e=this._map._getUIString(`GeolocateControl.LocationNotAvailable`);this._geolocateButton.title=e,this._geolocateButton.setAttribute(`aria-label`,e),this._geolocationWatchID!==void 0&&this._clearWatch()}else if(e.code===3&&Sm)return;else this._setErrorState();this._watchState!==`OFF`&&this.options.showUserLocation&&this._dotElement.classList.add(`maplibregl-user-location-dot-stale`),this.fire(new Tm(`error`,e)),this._finish()}},this._finish=()=>{this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0},this._onMoveStart=e=>{if(!this._map)return;let t=e?.[0]instanceof ResizeObserverEntry;!e.geolocateSource&&this._watchState===`ACTIVE_LOCK`&&!t&&!this._map.isZooming()&&(this._watchState=`BACKGROUND`,this._geolocateButton.classList.add(`maplibregl-ctrl-geolocate-background`),this._geolocateButton.classList.remove(`maplibregl-ctrl-geolocate-active`),this.fire(new Cm(`trackuserlocationend`)),this.fire(new Cm(`userlocationlostfocus`)))},this._setupUI=()=>{this._map&&(this._container.addEventListener(`contextmenu`,e=>{e.preventDefault()}),this._geolocateButton=W.create(`button`,`maplibregl-ctrl-geolocate`,this._container),W.create(`span`,`maplibregl-ctrl-icon`,this._geolocateButton).setAttribute(`aria-hidden`,`true`),this._geolocateButton.type=`button`,this._geolocateButton.disabled=!0)},this._finishSetupUI=e=>{if(this._map){if(e===!1){I(`Geolocation support is not available so the GeolocateControl will be disabled.`);let e=this._map._getUIString(`GeolocateControl.LocationNotAvailable`);this._geolocateButton.disabled=!0,this._geolocateButton.title=e,this._geolocateButton.setAttribute(`aria-label`,e)}else{let e=this._map._getUIString(`GeolocateControl.FindMyLocation`);this._geolocateButton.disabled=!1,this._geolocateButton.title=e,this._geolocateButton.setAttribute(`aria-label`,e)}this.options.trackUserLocation&&(this._geolocateButton.setAttribute(`aria-pressed`,`false`),this._watchState=`OFF`),this.options.showUserLocation&&(this._dotElement=W.create(`div`,`maplibregl-user-location-dot`),this._userLocationDotMarker=new ym({element:this._dotElement}),this._circleElement=W.create(`div`,`maplibregl-user-location-accuracy-circle`),this._accuracyCircleMarker=new ym({element:this._circleElement,pitchAlignment:`map`}),this.options.trackUserLocation&&(this._watchState=`OFF`),this._map.on(`zoom`,this._onUpdate),this._map.on(`move`,this._onUpdate),this._map.on(`rotate`,this._onUpdate),this._map.on(`pitch`,this._onUpdate)),this._geolocateButton.addEventListener(`click`,()=>this.trigger()),this._setup=!0,this.options.trackUserLocation&&this._map.on(`movestart`,this._onMoveStart)}},this.options=z({},bm,e)}onAdd(e){return this._map=e,this._container=W.create(`div`,`maplibregl-ctrl maplibregl-ctrl-group`),this._setupUI(),fm().then(e=>this._finishSetupUI(e)),this._container}onRemove(){this._geolocationWatchID!==void 0&&(window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),this._container.remove(),this._map.off(`movestart`,this._onMoveStart),this._map.off(`zoom`,this._onUpdate),this._map.off(`move`,this._onUpdate),this._map.off(`rotate`,this._onUpdate),this._map.off(`pitch`,this._onUpdate),this._map=void 0,xm=0,Sm=!1}_isOutOfMapMaxBounds(e){let t=this._map.getMaxBounds(),n=e.coords;return t&&(n.longitudePrice bars (top of the chart)
-
+
diff --git a/web/settings/tabs/weather.js b/web/settings/tabs/weather.js
index 86cecf2d5..58484a7f7 100644
--- a/web/settings/tabs/weather.js
+++ b/web/settings/tabs/weather.js
@@ -285,6 +285,233 @@
el.textContent = arraysSummary(n);
}
+ // ---- Roof geometry from Lantmäteriet -------------------------------------
+ //
+ // Typing a tilt and an azimuth means measuring your own roof, and most people
+ // guess. Sweden publishes the two datasets needed to do it properly, so this
+ // picks your building off a map and reads the slants out of the LiDAR.
+ //
+ // Both datasets are free but sit behind a Geotorget account, so the operator
+ // brings their own credentials. Everything degrades to the numeric fields
+ // above when the module, the credentials or the coverage is missing.
+
+ var roofState = { features: [], selectedId: null };
+
+ function roofFieldset(ctx) {
+ var field = ctx.field, help = ctx.help, config = ctx.config;
+ if (!config.roofmodel) config.roofmodel = {};
+ var stored = config.roofmodel.has_geotorget_token;
+ return '';
+ }
+
+ function roofSay(html, tone) {
+ var el = document.getElementById("roof-status");
+ if (!el) return;
+ el.style.color = tone === "bad" ? "var(--warn, #f59e0b)" : "var(--text-dim)";
+ el.innerHTML = html;
+ }
+
+ function findBuildings(ctx) {
+ var w = (ctx.config && ctx.config.weather) || {};
+ var q = "";
+ if (w.latitude != null && w.longitude != null) {
+ q = "?lat=" + encodeURIComponent(w.latitude) + "&lon=" + encodeURIComponent(w.longitude);
+ }
+ roofSay("Searching Lantmäteriet for buildings…");
+ return fetch("/api/roofmodel/buildings" + q)
+ .then(function (r) { return r.json().then(function (d) { return { ok: r.ok, d: d }; }); })
+ .then(function (res) {
+ var d = res.d || {};
+ if (d.enabled === false) {
+ roofSay("Roof derivation is off. Tick Enable roof derivation, add your " +
+ "Geotorget credentials and save, then try again.", "bad");
+ return;
+ }
+ if (!res.ok || d.error) {
+ roofSay(ctx.escHtml(d.error || "the building search failed"), "bad");
+ return;
+ }
+ roofState.features = d.buildings || [];
+ roofState.selectedId = null;
+ if (!roofState.features.length) {
+ roofSay("No buildings found here. Move the marker onto your roof and try again.", "bad");
+ return;
+ }
+ roofSay("Found " + roofState.features.length +
+ " building(s). Pick yours on the map or in the list.");
+ drawBuildings();
+ renderBuildingList(ctx);
+ })
+ .catch(function (e) { roofSay(ctx.escHtml(String(e && e.message || e)), "bad"); });
+ }
+
+ function featureCollection() {
+ return {
+ type: "FeatureCollection",
+ features: roofState.features.map(function (f) {
+ var p = Object.assign({}, f.properties || {});
+ p.selected = (f.id || p.building_id) === roofState.selectedId;
+ return { type: "Feature", id: f.id, geometry: f.geometry, properties: p };
+ }),
+ };
+ }
+
+ // MapLibre paints with concrete colours and cannot read var(), the same
+ // problem the canvas charts have. Resolve the theme tokens through a hidden
+ // probe that inherits :root, exactly as app.js's cssColor does. Resolved once
+ // per layer creation, so a theme toggle mid-pick keeps the old hue until the
+ // tab is reopened — the footprints stay legible either way.
+ var _probe = null;
+ function themeColor(name, fallback) {
+ if (!_probe) {
+ _probe = document.createElement("span");
+ _probe.style.cssText = "position:absolute;visibility:hidden;pointer-events:none";
+ document.body.appendChild(_probe);
+ }
+ _probe.style.color = "var(" + name + ", " + fallback + ")";
+ return getComputedStyle(_probe).color || fallback;
+ }
+
+ function drawBuildings() {
+ var map = window._weatherMap;
+ if (!map || !map.isStyleLoaded || !map.isStyleLoaded()) return;
+ var data = featureCollection();
+ var src = map.getSource("roof-buildings");
+ if (src) { src.setData(data); return; }
+ var candidate = themeColor("--cyan", "#38bdf8");
+ var picked = themeColor("--accent-e", "#f5b942");
+ map.addSource("roof-buildings", { type: "geojson", data: data });
+ map.addLayer({
+ id: "roof-buildings-fill", type: "fill", source: "roof-buildings",
+ paint: {
+ "fill-color": ["case", ["get", "selected"], picked, candidate],
+ "fill-opacity": ["case", ["get", "selected"], 0.55, 0.25],
+ },
+ });
+ map.addLayer({
+ id: "roof-buildings-line", type: "line", source: "roof-buildings",
+ paint: {
+ "line-color": ["case", ["get", "selected"], picked, candidate],
+ "line-width": ["case", ["get", "selected"], 2.5, 1],
+ },
+ });
+ map.on("click", "roof-buildings-fill", function (e) {
+ if (!e.features || !e.features.length) return;
+ var p = e.features[0].properties || {};
+ selectBuilding(p.building_id || e.features[0].id);
+ });
+ map.on("mouseenter", "roof-buildings-fill", function () {
+ map.getCanvas().style.cursor = "pointer";
+ });
+ map.on("mouseleave", "roof-buildings-fill", function () {
+ map.getCanvas().style.cursor = "";
+ });
+ }
+
+ function selectBuilding(id) {
+ roofState.selectedId = id;
+ drawBuildings();
+ var list = document.getElementById("roof-buildings");
+ if (list) {
+ Array.prototype.forEach.call(list.querySelectorAll("[data-building]"), function (el) {
+ var on = el.getAttribute("data-building") === id;
+ el.style.borderColor = on ? "var(--accent-e)" : "var(--line)";
+ el.style.background = on ? "var(--ink-sunken)" : "transparent";
+ });
+ }
+ var derive = document.getElementById("roof-derive");
+ if (derive) derive.disabled = !id;
+ }
+
+ // Also rendered as a list, so the picker still works where the map does not
+ // (no WebGL, blocked CDN).
+ function renderBuildingList(ctx) {
+ var host = document.getElementById("roof-buildings");
+ if (!host) return;
+ var esc = ctx.escHtml;
+ host.innerHTML = roofState.features.slice(0, 12).map(function (f) {
+ var p = f.properties || {};
+ var id = f.id || p.building_id;
+ return '';
+ }).join("");
+ Array.prototype.forEach.call(host.querySelectorAll("[data-building]"), function (el) {
+ el.addEventListener("click", function () {
+ selectBuilding(el.getAttribute("data-building"));
+ });
+ });
+ }
+
+ function deriveRoof(ctx) {
+ if (!roofState.selectedId) return;
+ roofSay("Reading the laser scan and fitting roof planes… this can take a minute.");
+ fetch("/api/roofmodel/derive", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ building_id: roofState.selectedId }),
+ })
+ .then(function (r) { return r.json().then(function (d) { return { ok: r.ok, d: d }; }); })
+ .then(function (res) {
+ var d = res.d || {};
+ if (!res.ok || d.error || d.enabled === false) {
+ roofSay(ctx.escHtml(d.error || "the derive failed"), "bad");
+ return;
+ }
+ var arrays = d.proposed_arrays || [];
+ if (!arrays.length) {
+ roofSay("No roof faces worth mounting panels on were found on that building. " +
+ "North-facing and very small faces are dropped.", "bad");
+ return;
+ }
+ // Fill the form rather than saving: the operator sees the numbers and
+ // presses Save, so the panel config never changes behind their back.
+ ctx.config.weather.pv_arrays = arrays.map(function (a) {
+ return {
+ name: a.name || "", kwp: a.kwp,
+ tilt_deg: a.tilt_deg, azimuth_deg: a.azimuth_deg,
+ };
+ });
+ renderPVArrays(ctx);
+ var m = d.model || {};
+ var when = m.captured_at_ms
+ ? new Date(m.captured_at_ms).toISOString().slice(0, 10)
+ : "date unknown";
+ var shade = m.shading && m.shading.evaluated ? ", shading evaluated" : "";
+ roofSay("Filled in " + arrays.length + " array(s) from " + m.planes_found +
+ " roof plane(s). Laser data from " + ctx.escHtml(when) + shade +
+ ". Review them and press Save.");
+ })
+ .catch(function (e) { roofSay(ctx.escHtml(String(e && e.message || e)), "bad"); });
+ }
+
function initWeatherMap(ctx) {
var container = document.getElementById("weather-map");
if (!container) return;
@@ -327,7 +554,8 @@
'Tilt: 0° = flat roof, 35° = typical pitched roof, 90° = wall. Azimuth: 0 = N, 90 = E, 180 = S, 270 = W. ' +
'Rated (W) is watts, same unit as PV rated.' +
'