open-plant 1.4.14 → 1.4.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var ji=Object.defineProperty;var Qi=(t,e,n)=>e in t?ji(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var E=(t,e,n)=>Qi(t,typeof e!="symbol"?e+"":e,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const He=require("react/jsx-runtime"),p=require("react");var ft=typeof document<"u"?document.currentScript:null;function qn(t,e,n){const r=t.createShader(e);if(!r)throw new Error("Failed to create shader.");if(t.shaderSource(r,n),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS)){const o=t.getShaderInfoLog(r)??"unknown shader error";throw t.deleteShader(r),new Error(o)}return r}function bt(t,e,n){const r=qn(t,t.VERTEX_SHADER,e),i=qn(t,t.FRAGMENT_SHADER,n),o=t.createProgram();if(!o)throw t.deleteShader(r),t.deleteShader(i),new Error("Failed to create program.");if(t.attachShader(o,r),t.attachShader(o,i),t.linkProgram(o),t.deleteShader(r),t.deleteShader(i),!t.getProgramParameter(o,t.LINK_STATUS)){const a=t.getProgramInfoLog(o)??"unknown link error";throw t.deleteProgram(o),new Error(a)}return o}function Fe(t,e,n){const r=t.getUniformLocation(e,n);if(!r)throw new Error(`Failed to get uniform location: ${n}`);return r}function Ji(t){const e=t.getContext("webgl2",{alpha:!1,antialias:!1,depth:!1,stencil:!1,preserveDrawingBuffer:!1,powerPreference:"high-performance"});if(!e)throw new Error("WebGL2 is not available.");return e}function sn(t){return t*Math.PI/180}class ei{constructor(){E(this,"viewportWidth",1);E(this,"viewportHeight",1);E(this,"viewState",{offsetX:0,offsetY:0,zoom:1,rotationDeg:0})}setViewport(e,n){this.viewportWidth=Math.max(1,e),this.viewportHeight=Math.max(1,n)}getViewportSize(){return{width:this.viewportWidth,height:this.viewportHeight}}setViewState(e){e.offsetX!==void 0&&(this.viewState.offsetX=e.offsetX),e.offsetY!==void 0&&(this.viewState.offsetY=e.offsetY),e.zoom!==void 0&&(this.viewState.zoom=Math.max(1e-4,e.zoom)),typeof e.rotationDeg=="number"&&Number.isFinite(e.rotationDeg)&&(this.viewState.rotationDeg=e.rotationDeg)}getViewState(){return{...this.viewState}}getCenter(){const e=Math.max(1e-6,this.viewState.zoom);return[this.viewState.offsetX+this.viewportWidth/(2*e),this.viewState.offsetY+this.viewportHeight/(2*e)]}setCenter(e,n){const r=Math.max(1e-6,this.viewState.zoom);this.viewState.offsetX=e-this.viewportWidth/(2*r),this.viewState.offsetY=n-this.viewportHeight/(2*r)}screenToWorld(e,n){const r=Math.max(1e-6,this.viewState.zoom),[i,o]=this.getCenter(),s=this.viewState.rotationDeg??0,a=(e-this.viewportWidth*.5)/r,l=(n-this.viewportHeight*.5)/r,u=sn(s),f=Math.cos(u),c=Math.sin(u);return[i+a*f-l*c,o+a*c+l*f]}worldToScreen(e,n){const r=Math.max(1e-6,this.viewState.zoom),[i,o]=this.getCenter(),s=this.viewState.rotationDeg??0,a=e-i,l=n-o,u=sn(s),f=Math.cos(u),c=Math.sin(u),h=a*f+l*c,d=-a*c+l*f;return[this.viewportWidth*.5+h*r,this.viewportHeight*.5+d*r]}getViewCorners(){const e=this.viewportWidth,n=this.viewportHeight;return[this.screenToWorld(0,0),this.screenToWorld(e,0),this.screenToWorld(e,n),this.screenToWorld(0,n)]}getMatrix(){const e=Math.max(1e-6,this.viewState.zoom),n=this.viewState.rotationDeg??0;if(n===0){const m=this.viewportWidth/e,g=this.viewportHeight/e,y=2/m,b=-2/g,x=-1-this.viewState.offsetX*y,A=1-this.viewState.offsetY*b;return new Float32Array([y,0,0,0,b,0,x,A,1])}const[r,i]=this.getCenter(),o=sn(n),s=Math.cos(o),a=Math.sin(o),l=2*e*s/this.viewportWidth,u=2*e*a/this.viewportWidth,f=2*e*a/this.viewportHeight,c=-2*e*s/this.viewportHeight,h=-(l*r+u*i),d=-(f*r+c*i);return new Float32Array([l,f,0,u,c,0,h,d,1])}}const eo=`#version 300 es
1
+ "use strict";var to=Object.defineProperty;var no=(t,e,n)=>e in t?to(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var E=(t,e,n)=>no(t,typeof e!="symbol"?e+"":e,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ge=require("react/jsx-runtime"),p=require("react");var ft=typeof document<"u"?document.currentScript:null;function Hn(t,e,n){const r=t.createShader(e);if(!r)throw new Error("Failed to create shader.");if(t.shaderSource(r,n),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS)){const o=t.getShaderInfoLog(r)??"unknown shader error";throw t.deleteShader(r),new Error(o)}return r}function bt(t,e,n){const r=Hn(t,t.VERTEX_SHADER,e),i=Hn(t,t.FRAGMENT_SHADER,n),o=t.createProgram();if(!o)throw t.deleteShader(r),t.deleteShader(i),new Error("Failed to create program.");if(t.attachShader(o,r),t.attachShader(o,i),t.linkProgram(o),t.deleteShader(r),t.deleteShader(i),!t.getProgramParameter(o,t.LINK_STATUS)){const a=t.getProgramInfoLog(o)??"unknown link error";throw t.deleteProgram(o),new Error(a)}return o}function Le(t,e,n){const r=t.getUniformLocation(e,n);if(!r)throw new Error(`Failed to get uniform location: ${n}`);return r}function ro(t){const e=t.getContext("webgl2",{alpha:!1,antialias:!1,depth:!1,stencil:!1,preserveDrawingBuffer:!1,powerPreference:"high-performance"});if(!e)throw new Error("WebGL2 is not available.");return e}function sn(t){return t*Math.PI/180}class ii{constructor(){E(this,"viewportWidth",1);E(this,"viewportHeight",1);E(this,"viewState",{offsetX:0,offsetY:0,zoom:1,rotationDeg:0})}setViewport(e,n){this.viewportWidth=Math.max(1,e),this.viewportHeight=Math.max(1,n)}getViewportSize(){return{width:this.viewportWidth,height:this.viewportHeight}}setViewState(e){e.offsetX!==void 0&&(this.viewState.offsetX=e.offsetX),e.offsetY!==void 0&&(this.viewState.offsetY=e.offsetY),e.zoom!==void 0&&(this.viewState.zoom=Math.max(1e-4,e.zoom)),typeof e.rotationDeg=="number"&&Number.isFinite(e.rotationDeg)&&(this.viewState.rotationDeg=e.rotationDeg)}getViewState(){return{...this.viewState}}getCenter(){const e=Math.max(1e-6,this.viewState.zoom);return[this.viewState.offsetX+this.viewportWidth/(2*e),this.viewState.offsetY+this.viewportHeight/(2*e)]}setCenter(e,n){const r=Math.max(1e-6,this.viewState.zoom);this.viewState.offsetX=e-this.viewportWidth/(2*r),this.viewState.offsetY=n-this.viewportHeight/(2*r)}screenToWorld(e,n){const r=Math.max(1e-6,this.viewState.zoom),[i,o]=this.getCenter(),s=this.viewState.rotationDeg??0,a=(e-this.viewportWidth*.5)/r,l=(n-this.viewportHeight*.5)/r,u=sn(s),f=Math.cos(u),c=Math.sin(u);return[i+a*f-l*c,o+a*c+l*f]}worldToScreen(e,n){const r=Math.max(1e-6,this.viewState.zoom),[i,o]=this.getCenter(),s=this.viewState.rotationDeg??0,a=e-i,l=n-o,u=sn(s),f=Math.cos(u),c=Math.sin(u),h=a*f+l*c,d=-a*c+l*f;return[this.viewportWidth*.5+h*r,this.viewportHeight*.5+d*r]}getViewCorners(){const e=this.viewportWidth,n=this.viewportHeight;return[this.screenToWorld(0,0),this.screenToWorld(e,0),this.screenToWorld(e,n),this.screenToWorld(0,n)]}getMatrix(){const e=Math.max(1e-6,this.viewState.zoom),n=this.viewState.rotationDeg??0;if(n===0){const m=this.viewportWidth/e,g=this.viewportHeight/e,b=2/m,y=-2/g,w=-1-this.viewState.offsetX*b,A=1-this.viewState.offsetY*y;return new Float32Array([b,0,0,0,y,0,w,A,1])}const[r,i]=this.getCenter(),o=sn(n),s=Math.cos(o),a=Math.sin(o),l=2*e*s/this.viewportWidth,u=2*e*a/this.viewportWidth,f=2*e*a/this.viewportHeight,c=-2*e*s/this.viewportHeight,h=-(l*r+u*i),d=-(f*r+c*i);return new Float32Array([l,f,0,u,c,0,h,d,1])}}const io=`#version 300 es
2
2
  precision highp float;
3
3
 
4
4
  in vec2 aUnit;
@@ -18,7 +18,7 @@ void main() {
18
18
  gl_Position = vec4(clip.xy, 0.0, 1.0);
19
19
  vUv = aUv;
20
20
  }
21
- `,to=`#version 300 es
21
+ `,oo=`#version 300 es
22
22
  precision highp float;
23
23
 
24
24
  in vec2 vUv;
@@ -29,8 +29,8 @@ out vec4 outColor;
29
29
  void main() {
30
30
  outColor = texture(uTexture, vUv);
31
31
  }
32
- `;class ti{constructor(e){E(this,"canvas");E(this,"gl");E(this,"camera",new ei);E(this,"imageWidth");E(this,"imageHeight");E(this,"clearColor");E(this,"program");E(this,"vao");E(this,"quadBuffer");E(this,"uCameraLocation");E(this,"uBoundsLocation");E(this,"uTextureLocation");E(this,"resizeObserver");E(this,"tiles",[]);E(this,"frameId",null);E(this,"loadVersion",0);E(this,"destroyed",!1);E(this,"fitted",!1);E(this,"controlledViewState",!1);this.canvas=e.canvas,this.imageWidth=Math.max(1,e.imageWidth),this.imageHeight=Math.max(1,e.imageHeight),this.clearColor=e.clearColor??[.03,.05,.08,1],this.gl=Ji(this.canvas),this.program=bt(this.gl,eo,to);const n=this.gl.createVertexArray(),r=this.gl.createBuffer();if(!n||!r)throw new Error("Failed to create WebGL buffers.");this.vao=n,this.quadBuffer=r,this.gl.bindVertexArray(this.vao),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.quadBuffer);const i=new Float32Array([0,0,0,0,1,0,1,0,0,1,0,1,1,1,1,1]);this.gl.bufferData(this.gl.ARRAY_BUFFER,i,this.gl.STATIC_DRAW);const o=this.gl.getAttribLocation(this.program,"aUnit"),s=this.gl.getAttribLocation(this.program,"aUv");if(o<0||s<0)throw new Error("Failed to get attribute locations.");const a=4*Float32Array.BYTES_PER_ELEMENT;this.gl.enableVertexAttribArray(o),this.gl.vertexAttribPointer(o,2,this.gl.FLOAT,!1,a,0),this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,a,2*Float32Array.BYTES_PER_ELEMENT),this.gl.bindVertexArray(null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.uCameraLocation=Fe(this.gl,this.program,"uCamera"),this.uBoundsLocation=Fe(this.gl,this.program,"uBounds"),this.uTextureLocation=Fe(this.gl,this.program,"uTexture"),e.initialViewState&&(this.controlledViewState=!0,this.camera.setViewState(e.initialViewState)),this.resizeObserver=new ResizeObserver(()=>{this.resize()}),this.resizeObserver.observe(this.canvas),this.resize()}async setTiles(e){if(this.destroyed)return;const n=++this.loadVersion,r=await Promise.all(e.map(async i=>await this.loadTile(i,n)));if(this.destroyed||n!==this.loadVersion){for(const i of r)i&&this.gl.deleteTexture(i.texture);return}this.disposeTiles(this.tiles),this.tiles=r.filter(i=>i!==null),this.requestRender()}setViewState(e){this.controlledViewState=!0,this.camera.setViewState(e),this.requestRender()}getViewState(){return this.camera.getViewState()}destroy(){this.destroyed||(this.destroyed=!0,this.loadVersion+=1,this.frameId!==null&&(cancelAnimationFrame(this.frameId),this.frameId=null),this.resizeObserver.disconnect(),this.disposeTiles(this.tiles),this.tiles=[],this.gl.deleteBuffer(this.quadBuffer),this.gl.deleteVertexArray(this.vao),this.gl.deleteProgram(this.program))}async loadTile(e,n){try{const r=await fetch(e.url);if(!r.ok)throw new Error(`Tile fetch failed: ${r.status} ${r.statusText}`);const i=await r.blob(),o=await createImageBitmap(i);if(this.destroyed||n!==this.loadVersion)return o.close(),null;const s=this.gl.createTexture();if(!s)throw o.close(),new Error("Failed to create tile texture.");return this.gl.bindTexture(this.gl.TEXTURE_2D,s),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,1),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,o),this.gl.bindTexture(this.gl.TEXTURE_2D,null),o.close(),{id:e.id,bounds:e.bounds,texture:s}}catch(r){return console.error(`[M1TileRenderer] tile load failed: ${e.id}`,r),null}}resize(){if(this.destroyed)return;const e=this.canvas.getBoundingClientRect(),n=Math.max(1,e.width||this.canvas.clientWidth||1),r=Math.max(1,e.height||this.canvas.clientHeight||1),i=Math.max(1,window.devicePixelRatio||1),o=Math.max(1,Math.round(n*i)),s=Math.max(1,Math.round(r*i));(this.canvas.width!==o||this.canvas.height!==s)&&(this.canvas.width=o,this.canvas.height=s),this.camera.setViewport(n,r),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),!this.fitted&&!this.controlledViewState&&(this.fitToImage(),this.fitted=!0),this.requestRender()}fitToImage(){const e=this.camera.getViewportSize(),n=Math.min(e.width/this.imageWidth,e.height/this.imageHeight),r=Number.isFinite(n)&&n>0?n:1,i=e.width/r,o=e.height/r,s=(this.imageWidth-i)*.5,a=(this.imageHeight-o)*.5;this.camera.setViewState({zoom:r,offsetX:s,offsetY:a})}requestRender(){this.frameId!==null||this.destroyed||(this.frameId=requestAnimationFrame(()=>{this.frameId=null,this.render()}))}render(){if(!this.destroyed){this.gl.clearColor(this.clearColor[0],this.clearColor[1],this.clearColor[2],this.clearColor[3]),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.useProgram(this.program),this.gl.bindVertexArray(this.vao),this.gl.uniformMatrix3fv(this.uCameraLocation,!1,this.camera.getMatrix()),this.gl.uniform1i(this.uTextureLocation,0);for(const e of this.tiles)this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,e.texture),this.gl.uniform4f(this.uBoundsLocation,e.bounds[0],e.bounds[1],e.bounds[2],e.bounds[3]),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindVertexArray(null)}}disposeTiles(e){for(const n of e)this.gl.deleteTexture(n.texture)}}class it{constructor(e,n){this.next=null,this.key=e,this.data=n,this.left=null,this.right=null}}function no(t,e){return t>e?1:t<e?-1:0}function tt(t,e,n){const r=new it(null,null);let i=r,o=r;for(;;){const s=n(t,e.key);if(s<0){if(e.left===null)break;if(n(t,e.left.key)<0){const a=e.left;if(e.left=a.right,a.right=e,e=a,e.left===null)break}o.left=e,o=e,e=e.left}else if(s>0){if(e.right===null)break;if(n(t,e.right.key)>0){const a=e.right;if(e.right=a.left,a.left=e,e=a,e.right===null)break}i.right=e,i=e,e=e.right}else break}return i.right=e.left,o.left=e.right,e.left=r.right,e.right=r.left,e}function an(t,e,n,r){const i=new it(t,e);if(n===null)return i.left=i.right=null,i;n=tt(t,n,r);const o=r(t,n.key);return o<0?(i.left=n.left,i.right=n,n.left=null):o>=0&&(i.right=n.right,i.left=n,n.right=null),i}function Hn(t,e,n){let r=null,i=null;if(e){e=tt(t,e,n);const o=n(e.key,t);o===0?(r=e.left,i=e.right):o<0?(i=e.right,e.right=null,r=e):(r=e.left,e.left=null,i=e)}return{left:r,right:i}}function ro(t,e,n){return e===null?t:(t===null||(e=tt(t.key,e,n),e.left=t),e)}function gn(t,e,n,r,i){if(t){r(`${e}${n?"└── ":"├── "}${i(t)}
33
- `);const o=e+(n?" ":"│ ");t.left&&gn(t.left,o,!1,r,i),t.right&&gn(t.right,o,!0,r,i)}}class _n{constructor(e=no){this._root=null,this._size=0,this._comparator=e}insert(e,n){return this._size++,this._root=an(e,n,this._root,this._comparator)}add(e,n){const r=new it(e,n);this._root===null&&(r.left=r.right=null,this._size++,this._root=r);const i=this._comparator,o=tt(e,this._root,i),s=i(e,o.key);return s===0?this._root=o:(s<0?(r.left=o.left,r.right=o,o.left=null):s>0&&(r.right=o.right,r.left=o,o.right=null),this._size++,this._root=r),this._root}remove(e){this._root=this._remove(e,this._root,this._comparator)}_remove(e,n,r){let i;return n===null?null:(n=tt(e,n,r),r(e,n.key)===0?(n.left===null?i=n.right:(i=tt(e,n.left,r),i.right=n.right),this._size--,i):n)}pop(){let e=this._root;if(e){for(;e.left;)e=e.left;return this._root=tt(e.key,this._root,this._comparator),this._root=this._remove(e.key,this._root,this._comparator),{key:e.key,data:e.data}}return null}findStatic(e){let n=this._root;const r=this._comparator;for(;n;){const i=r(e,n.key);if(i===0)return n;i<0?n=n.left:n=n.right}return null}find(e){return this._root&&(this._root=tt(e,this._root,this._comparator),this._comparator(e,this._root.key)!==0)?null:this._root}contains(e){let n=this._root;const r=this._comparator;for(;n;){const i=r(e,n.key);if(i===0)return!0;i<0?n=n.left:n=n.right}return!1}forEach(e,n){let r=this._root;const i=[];let o=!1;for(;!o;)r!==null?(i.push(r),r=r.left):i.length!==0?(r=i.pop(),e.call(n,r),r=r.right):o=!0;return this}range(e,n,r,i){const o=[],s=this._comparator;let a=this._root,l;for(;o.length!==0||a;)if(a)o.push(a),a=a.left;else{if(a=o.pop(),l=s(a.key,n),l>0)break;if(s(a.key,e)>=0&&r.call(i,a))return this;a=a.right}return this}keys(){const e=[];return this.forEach(({key:n})=>{e.push(n)}),e}values(){const e=[];return this.forEach(({data:n})=>{e.push(n)}),e}min(){return this._root?this.minNode(this._root).key:null}max(){return this._root?this.maxNode(this._root).key:null}minNode(e=this._root){if(e)for(;e.left;)e=e.left;return e}maxNode(e=this._root){if(e)for(;e.right;)e=e.right;return e}at(e){let n=this._root,r=!1,i=0;const o=[];for(;!r;)if(n)o.push(n),n=n.left;else if(o.length>0){if(n=o.pop(),i===e)return n;i++,n=n.right}else r=!0;return null}next(e){let n=this._root,r=null;if(e.right){for(r=e.right;r.left;)r=r.left;return r}const i=this._comparator;for(;n;){const o=i(e.key,n.key);if(o===0)break;o<0?(r=n,n=n.left):n=n.right}return r}prev(e){let n=this._root,r=null;if(e.left!==null){for(r=e.left;r.right;)r=r.right;return r}const i=this._comparator;for(;n;){const o=i(e.key,n.key);if(o===0)break;o<0?n=n.left:(r=n,n=n.right)}return r}clear(){return this._root=null,this._size=0,this}toList(){return oo(this._root)}load(e,n=[],r=!1){let i=e.length;const o=this._comparator;if(r&&bn(e,n,0,i-1,o),this._root===null)this._root=pn(e,n,0,i),this._size=i;else{const s=so(this.toList(),io(e,n),o);i=this._size+i,this._root=yn({head:s},0,i)}return this}isEmpty(){return this._root===null}get size(){return this._size}get root(){return this._root}toString(e=n=>String(n.key)){const n=[];return gn(this._root,"",!0,r=>n.push(r),e),n.join("")}update(e,n,r){const i=this._comparator;let{left:o,right:s}=Hn(e,this._root,i);i(e,n)<0?s=an(n,r,s,i):o=an(n,r,o,i),this._root=ro(o,s,i)}split(e){return Hn(e,this._root,this._comparator)}*[Symbol.iterator](){let e=this._root;const n=[];let r=!1;for(;!r;)e!==null?(n.push(e),e=e.left):n.length!==0?(e=n.pop(),yield e,e=e.right):r=!0}}function pn(t,e,n,r){const i=r-n;if(i>0){const o=n+Math.floor(i/2),s=t[o],a=e[o],l=new it(s,a);return l.left=pn(t,e,n,o),l.right=pn(t,e,o+1,r),l}return null}function io(t,e){const n=new it(null,null);let r=n;for(let i=0;i<t.length;i++)r=r.next=new it(t[i],e[i]);return r.next=null,n.next}function oo(t){let e=t;const n=[];let r=!1;const i=new it(null,null);let o=i;for(;!r;)e?(n.push(e),e=e.left):n.length>0?(e=o=o.next=n.pop(),e=e.right):r=!0;return o.next=null,i.next}function yn(t,e,n){const r=n-e;if(r>0){const i=e+Math.floor(r/2),o=yn(t,e,i),s=t.head;return s.left=o,t.head=t.head.next,s.right=yn(t,i+1,n),s}return null}function so(t,e,n){const r=new it(null,null);let i=r,o=t,s=e;for(;o!==null&&s!==null;)n(o.key,s.key)<0?(i.next=o,o=o.next):(i.next=s,s=s.next),i=i.next;return o!==null?i.next=o:s!==null&&(i.next=s),r.next}function bn(t,e,n,r,i){if(n>=r)return;const o=t[n+r>>1];let s=n-1,a=r+1;for(;;){do s++;while(i(t[s],o)<0);do a--;while(i(t[a],o)>0);if(s>=a)break;let l=t[s];t[s]=t[a],t[a]=l,l=e[s],e[s]=e[a],e[a]=l}bn(t,e,n,a,i),bn(t,e,a+1,r,i)}const Qe=11102230246251565e-32,Ne=134217729,ao=(3+8*Qe)*Qe;function ln(t,e,n,r,i){let o,s,a,l,u=e[0],f=r[0],c=0,h=0;f>u==f>-u?(o=u,u=e[++c]):(o=f,f=r[++h]);let d=0;if(c<t&&h<n)for(f>u==f>-u?(s=u+o,a=o-(s-u),u=e[++c]):(s=f+o,a=o-(s-f),f=r[++h]),o=s,a!==0&&(i[d++]=a);c<t&&h<n;)f>u==f>-u?(s=o+u,l=s-o,a=o-(s-l)+(u-l),u=e[++c]):(s=o+f,l=s-o,a=o-(s-l)+(f-l),f=r[++h]),o=s,a!==0&&(i[d++]=a);for(;c<t;)s=o+u,l=s-o,a=o-(s-l)+(u-l),u=e[++c],o=s,a!==0&&(i[d++]=a);for(;h<n;)s=o+f,l=s-o,a=o-(s-l)+(f-l),f=r[++h],o=s,a!==0&&(i[d++]=a);return(o!==0||d===0)&&(i[d++]=o),d}function lo(t,e){let n=e[0];for(let r=1;r<t;r++)n+=e[r];return n}function Ct(t){return new Float64Array(t)}const co=(3+16*Qe)*Qe,uo=(2+12*Qe)*Qe,fo=(9+64*Qe)*Qe*Qe,lt=Ct(4),Zn=Ct(8),$n=Ct(12),Kn=Ct(16),ke=Ct(4);function ho(t,e,n,r,i,o,s){let a,l,u,f,c,h,d,m,g,y,b,x,A,S,C,M,P,U;const O=t-i,N=n-i,v=e-o,B=r-o;S=O*B,h=Ne*O,d=h-(h-O),m=O-d,h=Ne*B,g=h-(h-B),y=B-g,C=m*y-(S-d*g-m*g-d*y),M=v*N,h=Ne*v,d=h-(h-v),m=v-d,h=Ne*N,g=h-(h-N),y=N-g,P=m*y-(M-d*g-m*g-d*y),b=C-P,c=C-b,lt[0]=C-(b+c)+(c-P),x=S+b,c=x-S,A=S-(x-c)+(b-c),b=A-M,c=A-b,lt[1]=A-(b+c)+(c-M),U=x+b,c=U-x,lt[2]=x-(U-c)+(b-c),lt[3]=U;let F=lo(4,lt),z=uo*s;if(F>=z||-F>=z||(c=t-O,a=t-(O+c)+(c-i),c=n-N,u=n-(N+c)+(c-i),c=e-v,l=e-(v+c)+(c-o),c=r-B,f=r-(B+c)+(c-o),a===0&&l===0&&u===0&&f===0)||(z=fo*s+ao*Math.abs(F),F+=O*f+B*a-(v*u+N*l),F>=z||-F>=z))return F;S=a*B,h=Ne*a,d=h-(h-a),m=a-d,h=Ne*B,g=h-(h-B),y=B-g,C=m*y-(S-d*g-m*g-d*y),M=l*N,h=Ne*l,d=h-(h-l),m=l-d,h=Ne*N,g=h-(h-N),y=N-g,P=m*y-(M-d*g-m*g-d*y),b=C-P,c=C-b,ke[0]=C-(b+c)+(c-P),x=S+b,c=x-S,A=S-(x-c)+(b-c),b=A-M,c=A-b,ke[1]=A-(b+c)+(c-M),U=x+b,c=U-x,ke[2]=x-(U-c)+(b-c),ke[3]=U;const K=ln(4,lt,4,ke,Zn);S=O*f,h=Ne*O,d=h-(h-O),m=O-d,h=Ne*f,g=h-(h-f),y=f-g,C=m*y-(S-d*g-m*g-d*y),M=v*u,h=Ne*v,d=h-(h-v),m=v-d,h=Ne*u,g=h-(h-u),y=u-g,P=m*y-(M-d*g-m*g-d*y),b=C-P,c=C-b,ke[0]=C-(b+c)+(c-P),x=S+b,c=x-S,A=S-(x-c)+(b-c),b=A-M,c=A-b,ke[1]=A-(b+c)+(c-M),U=x+b,c=U-x,ke[2]=x-(U-c)+(b-c),ke[3]=U;const Y=ln(K,Zn,4,ke,$n);S=a*f,h=Ne*a,d=h-(h-a),m=a-d,h=Ne*f,g=h-(h-f),y=f-g,C=m*y-(S-d*g-m*g-d*y),M=l*u,h=Ne*l,d=h-(h-l),m=l-d,h=Ne*u,g=h-(h-u),y=u-g,P=m*y-(M-d*g-m*g-d*y),b=C-P,c=C-b,ke[0]=C-(b+c)+(c-P),x=S+b,c=x-S,A=S-(x-c)+(b-c),b=A-M,c=A-b,ke[1]=A-(b+c)+(c-M),U=x+b,c=U-x,ke[2]=x-(U-c)+(b-c),ke[3]=U;const j=ln(Y,$n,4,ke,Kn);return Kn[j-1]}function mo(t,e,n,r,i,o){const s=(e-o)*(n-i),a=(t-i)*(r-o),l=s-a,u=Math.abs(s+a);return Math.abs(l)>=co*u?l:-ho(t,e,n,r,i,o,u)}const mt=(t,e)=>t.ll.x<=e.x&&e.x<=t.ur.x&&t.ll.y<=e.y&&e.y<=t.ur.y,xn=(t,e)=>{if(e.ur.x<t.ll.x||t.ur.x<e.ll.x||e.ur.y<t.ll.y||t.ur.y<e.ll.y)return null;const n=t.ll.x<e.ll.x?e.ll.x:t.ll.x,r=t.ur.x<e.ur.x?t.ur.x:e.ur.x,i=t.ll.y<e.ll.y?e.ll.y:t.ll.y,o=t.ur.y<e.ur.y?t.ur.y:e.ur.y;return{ll:{x:n,y:i},ur:{x:r,y:o}}};let nt=Number.EPSILON;nt===void 0&&(nt=Math.pow(2,-52));const go=nt*nt,jn=(t,e)=>{if(-nt<t&&t<nt&&-nt<e&&e<nt)return 0;const n=t-e;return n*n<go*t*e?0:t<e?-1:1};class po{constructor(){this.reset()}reset(){this.xRounder=new Qn,this.yRounder=new Qn}round(e,n){return{x:this.xRounder.round(e),y:this.yRounder.round(n)}}}class Qn{constructor(){this.tree=new _n,this.round(0)}round(e){const n=this.tree.add(e),r=this.tree.prev(n);if(r!==null&&jn(n.key,r.key)===0)return this.tree.remove(e),r.key;const i=this.tree.next(n);return i!==null&&jn(n.key,i.key)===0?(this.tree.remove(e),i.key):e}}const xt=new po,Ot=(t,e)=>t.x*e.y-t.y*e.x,ni=(t,e)=>t.x*e.x+t.y*e.y,Jn=(t,e,n)=>{const r=mo(t.x,t.y,e.x,e.y,n.x,n.y);return r>0?-1:r<0?1:0},Gt=t=>Math.sqrt(ni(t,t)),yo=(t,e,n)=>{const r={x:e.x-t.x,y:e.y-t.y},i={x:n.x-t.x,y:n.y-t.y};return Ot(i,r)/Gt(i)/Gt(r)},bo=(t,e,n)=>{const r={x:e.x-t.x,y:e.y-t.y},i={x:n.x-t.x,y:n.y-t.y};return ni(i,r)/Gt(i)/Gt(r)},er=(t,e,n)=>e.y===0?null:{x:t.x+e.x/e.y*(n-t.y),y:n},tr=(t,e,n)=>e.x===0?null:{x:n,y:t.y+e.y/e.x*(n-t.x)},xo=(t,e,n,r)=>{if(e.x===0)return tr(n,r,t.x);if(r.x===0)return tr(t,e,n.x);if(e.y===0)return er(n,r,t.y);if(r.y===0)return er(t,e,n.y);const i=Ot(e,r);if(i==0)return null;const o={x:n.x-t.x,y:n.y-t.y},s=Ot(o,e)/i,a=Ot(o,r)/i,l=t.x+a*e.x,u=n.x+s*r.x,f=t.y+a*e.y,c=n.y+s*r.y,h=(l+u)/2,d=(f+c)/2;return{x:h,y:d}};class Xe{static compare(e,n){const r=Xe.comparePoints(e.point,n.point);return r!==0?r:(e.point!==n.point&&e.link(n),e.isLeft!==n.isLeft?e.isLeft?1:-1:rt.compare(e.segment,n.segment))}static comparePoints(e,n){return e.x<n.x?-1:e.x>n.x?1:e.y<n.y?-1:e.y>n.y?1:0}constructor(e,n){e.events===void 0?e.events=[this]:e.events.push(this),this.point=e,this.isLeft=n}link(e){if(e.point===this.point)throw new Error("Tried to link already linked events");const n=e.point.events;for(let r=0,i=n.length;r<i;r++){const o=n[r];this.point.events.push(o),o.point=this.point}this.checkForConsuming()}checkForConsuming(){const e=this.point.events.length;for(let n=0;n<e;n++){const r=this.point.events[n];if(r.segment.consumedBy===void 0)for(let i=n+1;i<e;i++){const o=this.point.events[i];o.consumedBy===void 0&&r.otherSE.point.events===o.otherSE.point.events&&r.segment.consume(o.segment)}}}getAvailableLinkedEvents(){const e=[];for(let n=0,r=this.point.events.length;n<r;n++){const i=this.point.events[n];i!==this&&!i.segment.ringOut&&i.segment.isInResult()&&e.push(i)}return e}getLeftmostComparator(e){const n=new Map,r=i=>{const o=i.otherSE;n.set(i,{sine:yo(this.point,e.point,o.point),cosine:bo(this.point,e.point,o.point)})};return(i,o)=>{n.has(i)||r(i),n.has(o)||r(o);const{sine:s,cosine:a}=n.get(i),{sine:l,cosine:u}=n.get(o);return s>=0&&l>=0?a<u?1:a>u?-1:0:s<0&&l<0?a<u?-1:a>u?1:0:l<s?-1:l>s?1:0}}}let wo=0;class rt{static compare(e,n){const r=e.leftSE.point.x,i=n.leftSE.point.x,o=e.rightSE.point.x,s=n.rightSE.point.x;if(s<r)return 1;if(o<i)return-1;const a=e.leftSE.point.y,l=n.leftSE.point.y,u=e.rightSE.point.y,f=n.rightSE.point.y;if(r<i){if(l<a&&l<u)return 1;if(l>a&&l>u)return-1;const c=e.comparePoint(n.leftSE.point);if(c<0)return 1;if(c>0)return-1;const h=n.comparePoint(e.rightSE.point);return h!==0?h:-1}if(r>i){if(a<l&&a<f)return-1;if(a>l&&a>f)return 1;const c=n.comparePoint(e.leftSE.point);if(c!==0)return c;const h=e.comparePoint(n.rightSE.point);return h<0?1:h>0?-1:1}if(a<l)return-1;if(a>l)return 1;if(o<s){const c=n.comparePoint(e.rightSE.point);if(c!==0)return c}if(o>s){const c=e.comparePoint(n.rightSE.point);if(c<0)return 1;if(c>0)return-1}if(o!==s){const c=u-a,h=o-r,d=f-l,m=s-i;if(c>h&&d<m)return 1;if(c<h&&d>m)return-1}return o>s?1:o<s||u<f?-1:u>f?1:e.id<n.id?-1:e.id>n.id?1:0}constructor(e,n,r,i){this.id=++wo,this.leftSE=e,e.segment=this,e.otherSE=n,this.rightSE=n,n.segment=this,n.otherSE=e,this.rings=r,this.windings=i}static fromRing(e,n,r){let i,o,s;const a=Xe.comparePoints(e,n);if(a<0)i=e,o=n,s=1;else if(a>0)i=n,o=e,s=-1;else throw new Error(`Tried to create degenerate segment at [${e.x}, ${e.y}]`);const l=new Xe(i,!0),u=new Xe(o,!1);return new rt(l,u,[r],[s])}replaceRightSE(e){this.rightSE=e,this.rightSE.segment=this,this.rightSE.otherSE=this.leftSE,this.leftSE.otherSE=this.rightSE}bbox(){const e=this.leftSE.point.y,n=this.rightSE.point.y;return{ll:{x:this.leftSE.point.x,y:e<n?e:n},ur:{x:this.rightSE.point.x,y:e>n?e:n}}}vector(){return{x:this.rightSE.point.x-this.leftSE.point.x,y:this.rightSE.point.y-this.leftSE.point.y}}isAnEndpoint(e){return e.x===this.leftSE.point.x&&e.y===this.leftSE.point.y||e.x===this.rightSE.point.x&&e.y===this.rightSE.point.y}comparePoint(e){if(this.isAnEndpoint(e))return 0;const n=this.leftSE.point,r=this.rightSE.point,i=this.vector();if(n.x===r.x)return e.x===n.x?0:e.x<n.x?1:-1;const o=(e.y-n.y)/i.y,s=n.x+o*i.x;if(e.x===s)return 0;const a=(e.x-n.x)/i.x,l=n.y+a*i.y;return e.y===l?0:e.y<l?-1:1}getIntersection(e){const n=this.bbox(),r=e.bbox(),i=xn(n,r);if(i===null)return null;const o=this.leftSE.point,s=this.rightSE.point,a=e.leftSE.point,l=e.rightSE.point,u=mt(n,a)&&this.comparePoint(a)===0,f=mt(r,o)&&e.comparePoint(o)===0,c=mt(n,l)&&this.comparePoint(l)===0,h=mt(r,s)&&e.comparePoint(s)===0;if(f&&u)return h&&!c?s:!h&&c?l:null;if(f)return c&&o.x===l.x&&o.y===l.y?null:o;if(u)return h&&s.x===a.x&&s.y===a.y?null:a;if(h&&c)return null;if(h)return s;if(c)return l;const d=xo(o,this.vector(),a,e.vector());return d===null||!mt(i,d)?null:xt.round(d.x,d.y)}split(e){const n=[],r=e.events!==void 0,i=new Xe(e,!0),o=new Xe(e,!1),s=this.rightSE;this.replaceRightSE(o),n.push(o),n.push(i);const a=new rt(i,s,this.rings.slice(),this.windings.slice());return Xe.comparePoints(a.leftSE.point,a.rightSE.point)>0&&a.swapEvents(),Xe.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),r&&(i.checkForConsuming(),o.checkForConsuming()),n}swapEvents(){const e=this.rightSE;this.rightSE=this.leftSE,this.leftSE=e,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(let n=0,r=this.windings.length;n<r;n++)this.windings[n]*=-1}consume(e){let n=this,r=e;for(;n.consumedBy;)n=n.consumedBy;for(;r.consumedBy;)r=r.consumedBy;const i=rt.compare(n,r);if(i!==0){if(i>0){const o=n;n=r,r=o}if(n.prev===r){const o=n;n=r,r=o}for(let o=0,s=r.rings.length;o<s;o++){const a=r.rings[o],l=r.windings[o],u=n.rings.indexOf(a);u===-1?(n.rings.push(a),n.windings.push(l)):n.windings[u]+=l}r.rings=null,r.windings=null,r.consumedBy=n,r.leftSE.consumedBy=n.leftSE,r.rightSE.consumedBy=n.rightSE}}prevInResult(){return this._prevInResult!==void 0?this._prevInResult:(this.prev?this.prev.isInResult()?this._prevInResult=this.prev:this._prevInResult=this.prev.prevInResult():this._prevInResult=null,this._prevInResult)}beforeState(){if(this._beforeState!==void 0)return this._beforeState;if(!this.prev)this._beforeState={rings:[],windings:[],multiPolys:[]};else{const e=this.prev.consumedBy||this.prev;this._beforeState=e.afterState()}return this._beforeState}afterState(){if(this._afterState!==void 0)return this._afterState;const e=this.beforeState();this._afterState={rings:e.rings.slice(0),windings:e.windings.slice(0),multiPolys:[]};const n=this._afterState.rings,r=this._afterState.windings,i=this._afterState.multiPolys;for(let a=0,l=this.rings.length;a<l;a++){const u=this.rings[a],f=this.windings[a],c=n.indexOf(u);c===-1?(n.push(u),r.push(f)):r[c]+=f}const o=[],s=[];for(let a=0,l=n.length;a<l;a++){if(r[a]===0)continue;const u=n[a],f=u.poly;if(s.indexOf(f)===-1)if(u.isExterior)o.push(f);else{s.indexOf(f)===-1&&s.push(f);const c=o.indexOf(u.poly);c!==-1&&o.splice(c,1)}}for(let a=0,l=o.length;a<l;a++){const u=o[a].multiPoly;i.indexOf(u)===-1&&i.push(u)}return this._afterState}isInResult(){if(this.consumedBy)return!1;if(this._isInResult!==void 0)return this._isInResult;const e=this.beforeState().multiPolys,n=this.afterState().multiPolys;switch(Ze.type){case"union":{const r=e.length===0,i=n.length===0;this._isInResult=r!==i;break}case"intersection":{let r,i;e.length<n.length?(r=e.length,i=n.length):(r=n.length,i=e.length),this._isInResult=i===Ze.numMultiPolys&&r<i;break}case"xor":{const r=Math.abs(e.length-n.length);this._isInResult=r%2===1;break}case"difference":{const r=i=>i.length===1&&i[0].isSubject;this._isInResult=r(e)!==r(n);break}default:throw new Error(`Unrecognized operation type found ${Ze.type}`)}return this._isInResult}}class nr{constructor(e,n,r){if(!Array.isArray(e)||e.length===0)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=n,this.isExterior=r,this.segments=[],typeof e[0][0]!="number"||typeof e[0][1]!="number")throw new Error("Input geometry is not a valid Polygon or MultiPolygon");const i=xt.round(e[0][0],e[0][1]);this.bbox={ll:{x:i.x,y:i.y},ur:{x:i.x,y:i.y}};let o=i;for(let s=1,a=e.length;s<a;s++){if(typeof e[s][0]!="number"||typeof e[s][1]!="number")throw new Error("Input geometry is not a valid Polygon or MultiPolygon");let l=xt.round(e[s][0],e[s][1]);l.x===o.x&&l.y===o.y||(this.segments.push(rt.fromRing(o,l,this)),l.x<this.bbox.ll.x&&(this.bbox.ll.x=l.x),l.y<this.bbox.ll.y&&(this.bbox.ll.y=l.y),l.x>this.bbox.ur.x&&(this.bbox.ur.x=l.x),l.y>this.bbox.ur.y&&(this.bbox.ur.y=l.y),o=l)}(i.x!==o.x||i.y!==o.y)&&this.segments.push(rt.fromRing(o,i,this))}getSweepEvents(){const e=[];for(let n=0,r=this.segments.length;n<r;n++){const i=this.segments[n];e.push(i.leftSE),e.push(i.rightSE)}return e}}class So{constructor(e,n){if(!Array.isArray(e))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");this.exteriorRing=new nr(e[0],this,!0),this.bbox={ll:{x:this.exteriorRing.bbox.ll.x,y:this.exteriorRing.bbox.ll.y},ur:{x:this.exteriorRing.bbox.ur.x,y:this.exteriorRing.bbox.ur.y}},this.interiorRings=[];for(let r=1,i=e.length;r<i;r++){const o=new nr(e[r],this,!1);o.bbox.ll.x<this.bbox.ll.x&&(this.bbox.ll.x=o.bbox.ll.x),o.bbox.ll.y<this.bbox.ll.y&&(this.bbox.ll.y=o.bbox.ll.y),o.bbox.ur.x>this.bbox.ur.x&&(this.bbox.ur.x=o.bbox.ur.x),o.bbox.ur.y>this.bbox.ur.y&&(this.bbox.ur.y=o.bbox.ur.y),this.interiorRings.push(o)}this.multiPoly=n}getSweepEvents(){const e=this.exteriorRing.getSweepEvents();for(let n=0,r=this.interiorRings.length;n<r;n++){const i=this.interiorRings[n].getSweepEvents();for(let o=0,s=i.length;o<s;o++)e.push(i[o])}return e}}class rr{constructor(e,n){if(!Array.isArray(e))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");try{typeof e[0][0][0]=="number"&&(e=[e])}catch{}this.polys=[],this.bbox={ll:{x:Number.POSITIVE_INFINITY,y:Number.POSITIVE_INFINITY},ur:{x:Number.NEGATIVE_INFINITY,y:Number.NEGATIVE_INFINITY}};for(let r=0,i=e.length;r<i;r++){const o=new So(e[r],this);o.bbox.ll.x<this.bbox.ll.x&&(this.bbox.ll.x=o.bbox.ll.x),o.bbox.ll.y<this.bbox.ll.y&&(this.bbox.ll.y=o.bbox.ll.y),o.bbox.ur.x>this.bbox.ur.x&&(this.bbox.ur.x=o.bbox.ur.x),o.bbox.ur.y>this.bbox.ur.y&&(this.bbox.ur.y=o.bbox.ur.y),this.polys.push(o)}this.isSubject=n}getSweepEvents(){const e=[];for(let n=0,r=this.polys.length;n<r;n++){const i=this.polys[n].getSweepEvents();for(let o=0,s=i.length;o<s;o++)e.push(i[o])}return e}}class qt{static factory(e){const n=[];for(let r=0,i=e.length;r<i;r++){const o=e[r];if(!o.isInResult()||o.ringOut)continue;let s=null,a=o.leftSE,l=o.rightSE;const u=[a],f=a.point,c=[];for(;s=a,a=l,u.push(a),a.point!==f;)for(;;){const h=a.getAvailableLinkedEvents();if(h.length===0){const g=u[0].point,y=u[u.length-1].point;throw new Error(`Unable to complete output ring starting at [${g.x}, ${g.y}]. Last matching segment found ends at [${y.x}, ${y.y}].`)}if(h.length===1){l=h[0].otherSE;break}let d=null;for(let g=0,y=c.length;g<y;g++)if(c[g].point===a.point){d=g;break}if(d!==null){const g=c.splice(d)[0],y=u.splice(g.index);y.unshift(y[0].otherSE),n.push(new qt(y.reverse()));continue}c.push({index:u.length,point:a.point});const m=a.getLeftmostComparator(s);l=h.sort(m)[0].otherSE;break}n.push(new qt(u))}return n}constructor(e){this.events=e;for(let n=0,r=e.length;n<r;n++)e[n].segment.ringOut=this;this.poly=null}getGeom(){let e=this.events[0].point;const n=[e];for(let u=1,f=this.events.length-1;u<f;u++){const c=this.events[u].point,h=this.events[u+1].point;Jn(c,e,h)!==0&&(n.push(c),e=c)}if(n.length===1)return null;const r=n[0],i=n[1];Jn(r,e,i)===0&&n.shift(),n.push(n[0]);const o=this.isExteriorRing()?1:-1,s=this.isExteriorRing()?0:n.length-1,a=this.isExteriorRing()?n.length:-1,l=[];for(let u=s;u!=a;u+=o)l.push([n[u].x,n[u].y]);return l}isExteriorRing(){if(this._isExteriorRing===void 0){const e=this.enclosingRing();this._isExteriorRing=e?!e.isExteriorRing():!0}return this._isExteriorRing}enclosingRing(){return this._enclosingRing===void 0&&(this._enclosingRing=this._calcEnclosingRing()),this._enclosingRing}_calcEnclosingRing(){let e=this.events[0];for(let i=1,o=this.events.length;i<o;i++){const s=this.events[i];Xe.compare(e,s)>0&&(e=s)}let n=e.segment.prevInResult(),r=n?n.prevInResult():null;for(;;){if(!n)return null;if(!r)return n.ringOut;if(r.ringOut!==n.ringOut)return r.ringOut.enclosingRing()!==n.ringOut?n.ringOut:n.ringOut.enclosingRing();n=r.prevInResult(),r=n?n.prevInResult():null}}}class ir{constructor(e){this.exteriorRing=e,e.poly=this,this.interiorRings=[]}addInterior(e){this.interiorRings.push(e),e.poly=this}getGeom(){const e=[this.exteriorRing.getGeom()];if(e[0]===null)return null;for(let n=0,r=this.interiorRings.length;n<r;n++){const i=this.interiorRings[n].getGeom();i!==null&&e.push(i)}return e}}class Eo{constructor(e){this.rings=e,this.polys=this._composePolys(e)}getGeom(){const e=[];for(let n=0,r=this.polys.length;n<r;n++){const i=this.polys[n].getGeom();i!==null&&e.push(i)}return e}_composePolys(e){const n=[];for(let r=0,i=e.length;r<i;r++){const o=e[r];if(!o.poly)if(o.isExteriorRing())n.push(new ir(o));else{const s=o.enclosingRing();s.poly||n.push(new ir(s)),s.poly.addInterior(o)}}return n}}class Ro{constructor(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:rt.compare;this.queue=e,this.tree=new _n(n),this.segments=[]}process(e){const n=e.segment,r=[];if(e.consumedBy)return e.isLeft?this.queue.remove(e.otherSE):this.tree.remove(n),r;const i=e.isLeft?this.tree.add(n):this.tree.find(n);if(!i)throw new Error(`Unable to find segment #${n.id} [${n.leftSE.point.x}, ${n.leftSE.point.y}] -> [${n.rightSE.point.x}, ${n.rightSE.point.y}] in SweepLine tree.`);let o=i,s=i,a,l;for(;a===void 0;)o=this.tree.prev(o),o===null?a=null:o.key.consumedBy===void 0&&(a=o.key);for(;l===void 0;)s=this.tree.next(s),s===null?l=null:s.key.consumedBy===void 0&&(l=s.key);if(e.isLeft){let u=null;if(a){const c=a.getIntersection(n);if(c!==null&&(n.isAnEndpoint(c)||(u=c),!a.isAnEndpoint(c))){const h=this._splitSafely(a,c);for(let d=0,m=h.length;d<m;d++)r.push(h[d])}}let f=null;if(l){const c=l.getIntersection(n);if(c!==null&&(n.isAnEndpoint(c)||(f=c),!l.isAnEndpoint(c))){const h=this._splitSafely(l,c);for(let d=0,m=h.length;d<m;d++)r.push(h[d])}}if(u!==null||f!==null){let c=null;u===null?c=f:f===null?c=u:c=Xe.comparePoints(u,f)<=0?u:f,this.queue.remove(n.rightSE),r.push(n.rightSE);const h=n.split(c);for(let d=0,m=h.length;d<m;d++)r.push(h[d])}r.length>0?(this.tree.remove(n),r.push(e)):(this.segments.push(n),n.prev=a)}else{if(a&&l){const u=a.getIntersection(l);if(u!==null){if(!a.isAnEndpoint(u)){const f=this._splitSafely(a,u);for(let c=0,h=f.length;c<h;c++)r.push(f[c])}if(!l.isAnEndpoint(u)){const f=this._splitSafely(l,u);for(let c=0,h=f.length;c<h;c++)r.push(f[c])}}}this.tree.remove(n)}return r}_splitSafely(e,n){this.tree.remove(e);const r=e.rightSE;this.queue.remove(r);const i=e.split(n);return i.push(r),e.consumedBy===void 0&&this.tree.add(e),i}}const or=typeof process<"u"&&process.env.POLYGON_CLIPPING_MAX_QUEUE_SIZE||1e6,Ao=typeof process<"u"&&process.env.POLYGON_CLIPPING_MAX_SWEEPLINE_SEGMENTS||1e6;class Co{run(e,n,r){Ze.type=e,xt.reset();const i=[new rr(n,!0)];for(let c=0,h=r.length;c<h;c++)i.push(new rr(r[c],!1));if(Ze.numMultiPolys=i.length,Ze.type==="difference"){const c=i[0];let h=1;for(;h<i.length;)xn(i[h].bbox,c.bbox)!==null?h++:i.splice(h,1)}if(Ze.type==="intersection")for(let c=0,h=i.length;c<h;c++){const d=i[c];for(let m=c+1,g=i.length;m<g;m++)if(xn(d.bbox,i[m].bbox)===null)return[]}const o=new _n(Xe.compare);for(let c=0,h=i.length;c<h;c++){const d=i[c].getSweepEvents();for(let m=0,g=d.length;m<g;m++)if(o.insert(d[m]),o.size>or)throw new Error("Infinite loop when putting segment endpoints in a priority queue (queue size too big).")}const s=new Ro(o);let a=o.size,l=o.pop();for(;l;){const c=l.key;if(o.size===a){const d=c.segment;throw new Error(`Unable to pop() ${c.isLeft?"left":"right"} SweepEvent [${c.point.x}, ${c.point.y}] from segment #${d.id} [${d.leftSE.point.x}, ${d.leftSE.point.y}] -> [${d.rightSE.point.x}, ${d.rightSE.point.y}] from queue.`)}if(o.size>or)throw new Error("Infinite loop when passing sweep line over endpoints (queue size too big).");if(s.segments.length>Ao)throw new Error("Infinite loop when passing sweep line over endpoints (too many sweep line segments).");const h=s.process(c);for(let d=0,m=h.length;d<m;d++){const g=h[d];g.consumedBy===void 0&&o.insert(g)}a=o.size,l=o.pop()}xt.reset();const u=qt.factory(s.segments);return new Eo(u).getGeom()}}const Ze=new Co,Mo=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return Ze.run("union",t,n)},Po=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return Ze.run("intersection",t,n)},vo=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return Ze.run("xor",t,n)},To=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return Ze.run("difference",t,n)};var Io={union:Mo,intersection:Po,xor:vo,difference:To};function ht(t){return t==null?null:ri(t)||ii(t)||_o(t)?t:null}function sr(t){return typeof t=="number"&&Number.isFinite(t)}function Yt(t){return Array.isArray(t)&&t.length>=2&&sr(t[0])&&sr(t[1])}function ri(t){return Array.isArray(t)&&t.length>0&&t.every(e=>Yt(e))}function ii(t){return Array.isArray(t)&&t.length>0&&t.every(e=>ri(e))}function _o(t){return Array.isArray(t)&&t.length>0&&t.every(e=>ii(e))}function Ye(t){if(!Array.isArray(t)||t.length<3)return[];const e=[];for(const i of t){if(!Array.isArray(i)||i.length<2)continue;const o=Number(i[0]),s=Number(i[1]);if(!Number.isFinite(o)||!Number.isFinite(s))continue;const a=e[e.length-1];a&&a[0]===o&&a[1]===s||e.push([o,s])}if(e.length<3)return[];const n=e[0],r=e[e.length-1];return(n[0]!==r[0]||n[1]!==r[1])&&e.push([n[0],n[1]]),e.length>=4?e:[]}function wt(t){if(!Array.isArray(t)||t.length<4)return 0;let e=0;for(let n=0;n<t.length-1;n+=1){const r=t[n],i=t[n+1];e+=r[0]*i[1]-i[0]*r[1]}return e*.5}function cn(t){if(!Array.isArray(t)||t.length===0)return[];const e=[];for(const o of t){const s=Ye(o);s.length>=4&&e.push(s)}if(e.length===0)return[];if(e.length===1)return[e[0]];let n=0,r=0;for(let o=0;o<e.length;o+=1){const s=Math.abs(wt(e[o]));s<=r||(r=s,n=o)}const i=[e[n]];for(let o=0;o<e.length;o+=1)o!==n&&i.push(e[o]);return i}function oi(t){if(!Array.isArray(t)||t.length===0)return[];const e=t[0];if(Yt(e)){const i=cn([t]);return i.length>0?[i]:[]}if(!Array.isArray(e)||e.length===0)return[];const n=e[0];if(Yt(n)){const i=cn(t);return i.length>0?[i]:[]}if(!Array.isArray(n)||n.length===0||!Yt(n[0]))return[];const r=[];for(const i of t){const o=cn(i);o.length>0&&r.push(o)}return r}function ar(t,e,n){let r=!1;for(let i=0,o=n.length-1;i<n.length;o=i,i+=1){const s=n[i][0],a=n[i][1],l=n[o][0],u=n[o][1];if(a===u||a>e==u>e)continue;t<(l-s)*(e-a)/(u-a)+s&&(r=!r)}return r}function dt(t){const e=[];for(const n of t??[]){const r=oi(n);for(const i of r){const o=i[0];if(!o||o.length<4)continue;let s=1/0,a=1/0,l=-1/0,u=-1/0;for(const[c,h]of o)c<s&&(s=c),c>l&&(l=c),h<a&&(a=h),h>u&&(u=h);if(!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(l)||!Number.isFinite(u))continue;let f=Math.abs(wt(o));for(let c=1;c<i.length;c+=1)f-=Math.abs(wt(i[c]));e.push({outer:o,holes:i.slice(1),minX:s,minY:a,maxX:l,maxY:u,area:Math.max(1e-6,f)})}}return e}function si(t,e,n){if(t<n.minX||t>n.maxX||e<n.minY||e>n.maxY||!ar(t,e,n.outer))return!1;for(const r of n.holes)if(ar(t,e,r))return!1;return!0}function St(t,e,n){for(const r of n)if(si(t,e,r))return!0;return!1}const Ln=[160,160,160,255];function L(t,e,n){return Math.max(e,Math.min(n,t))}function Fn(t,e,n){const r=Number(t),i=Number(e),o=Number(n);return!Number.isFinite(r)||r<=0?1:!Number.isFinite(i)||!Number.isFinite(o)?r:Math.pow(2,i-o)*r}function Lo(t,e,n){let i=100*Fn(t,e,n);if(Number(t)){let o="μm";return i>1e3&&(i/=1e3,o="mm"),`${i.toPrecision(3)} ${o}`}return`${Math.round(i*1e3)/1e3} pixels`}function xe(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function st(t){const e=t.fillModes instanceof Uint8Array?t.fillModes.length:Number.MAX_SAFE_INTEGER;return Math.max(0,Math.min(Math.floor(t.count??0),Math.floor((t.positions?.length??0)/2),t.paletteIndices?.length??0,e))}function wn(t,e){return!t&&!e?!0:!t||!e?!1:Math.abs((t.zoom??0)-(e.zoom??0))<1e-6&&Math.abs((t.offsetX??0)-(e.offsetX??0))<1e-6&&Math.abs((t.offsetY??0)-(e.offsetY??0))<1e-6&&Math.abs((t.rotationDeg??0)-(e.rotationDeg??0))<1e-6}function Fo(t){const e=String(t??"").trim();if(!e)return"";if(/^bearer\s+/i.test(e)){const n=e.replace(/^bearer\s+/i,"").trim();return n?`Bearer ${n}`:""}return`Bearer ${e}`}function ai(t){const n=String(t??"").trim().match(/^#?([0-9a-fA-F]{6})$/);if(!n)return[...Ln];const r=Number.parseInt(n[1],16);return[r>>16&255,r>>8&255,r&255,255]}function Do(t){const e=String(t?.classId??"").trim();return e||String(t?.className??"").trim()}function No(t){const e=[[...Ln]],n=new Map;for(const i of t??[]){const o=Do(i);!o||n.has(o)||(n.set(o,e.length),e.push(ai(i?.classColor)))}const r=new Uint8Array(e.length*4);for(let i=0;i<e.length;i+=1)r[i*4]=e[i][0],r[i*4+1]=e[i][1],r[i*4+2]=e[i][2],r[i*4+3]=e[i][3];return{colors:r,classToPaletteIndex:n}}const Bo=[6,4,2],ko=64,Uo=.04,zo=1,Oo=4,Ht=1e-6,Yo=.1;function Wo(t){if(!Array.isArray(t)||t.length===0)return[];const e=[];for(const n of t){if(!Array.isArray(n)||n.length<2)continue;const r=Number(n[0]),i=Number(n[1]);if(!Number.isFinite(r)||!Number.isFinite(i))continue;const o=e[e.length-1];o&&Math.abs(o[0]-r)<1e-9&&Math.abs(o[1]-i)<1e-9||e.push([r,i])}return e}function lr(t,e,n){if(e<=Ht||n<8)return[];const r=[];for(let i=0;i<=n;i+=1){const o=i/n*Math.PI*2;r.push([t[0]+Math.cos(o)*e,t[1]+Math.sin(o)*e])}return Ye(r)}function Xo(t,e,n,r){const i=e[0]-t[0],o=e[1]-t[1],s=Math.sqrt(i*i+o*o);if(!Number.isFinite(s)||s<=r)return[];const a=i/s,u=-(o/s),f=a,c=Math.max(Ht,n);return Ye([[t[0]+u*c,t[1]+f*c],[e[0]+u*c,e[1]+f*c],[e[0]-u*c,e[1]-f*c],[t[0]-u*c,t[1]-f*c]])}function cr(t,e){if(!t.length)return[];let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[a,l]of t)a<n&&(n=a),a>i&&(i=a),l<r&&(r=l),l>o&&(o=l);if(!Number.isFinite(n)||!Number.isFinite(r))return[];const s=Math.max(e,1);return Ye([[n-s,r-s],[i+s,r-s],[i+s,o+s],[n-s,o+s]])}function Tt(t,e){return Ye(e?t.map(([n,r])=>[L(n,e[0],e[2]),L(r,e[1],e[3])]):t)}function ur(t,e){return Number.isFinite(t)?Number(t.toFixed(e)):t}function Vo(t,e){if(!Array.isArray(t)||t.length===0)return[];const n=[];for(const r of t){if(!Array.isArray(r)||r.length<2)continue;const i=ur(Number(r[0]),e),o=ur(Number(r[1]),e);if(!Number.isFinite(i)||!Number.isFinite(o))continue;const s=n[n.length-1];(!s||s[0]!==i||s[1]!==o)&&n.push([i,o])}if(n.length>=2){const r=n[0],i=n[n.length-1];if(!r||!i)return[];(r[0]!==i[0]||r[1]!==i[1])&&n.push([r[0],r[1]])}return n.length>=4?n:[]}function Go(t,e){if(!Array.isArray(t)||t.length===0)return[];const n=t.map(r=>Vo(r,e)).filter(r=>r.length>=4);return n.length>0?n:[]}function qo(t,e){const n=t.map(i=>Go(i,e)).filter(i=>i.length>0);if(n.length===0)return null;let r=[n[0]];try{for(let i=1;i<n.length;i+=1)if(r=Io.union(r,[n[i]]),!Array.isArray(r)||r.length===0)return null}catch(i){return console.error("buildBrushStrokePolygon union failed",e,i),null}return r.length>0?r:null}function Ho(t){if(t.length===0)return null;for(const e of Bo){const n=qo(t,e);if(n)return n}return null}function Zo(t){if(!Array.isArray(t)||t.length===0)return[];const e=[];for(const n of t){if(!Array.isArray(n)||n.length<2)continue;const r=Number(n[0]),i=Number(n[1]);!Number.isFinite(r)||!Number.isFinite(i)||e.push([r,i])}return Ye(e)}function $o(t){let e=[],n=0;for(const r of t){if(!Array.isArray(r)||r.length===0)continue;const i=Zo(r[0]??[]);if(i.length<4)continue;const o=Math.abs(wt(i));o<=n||(n=o,e=i)}return e}function Ko(t,e=1e-9){const n=Ye(t);if(n.length<5)return n;const r=[n[0]];for(let i=1;i<n.length-1;i+=1){const o=r[r.length-1],s=n[i],a=n[i+1],l=(s[0]-o[0])*(a[1]-s[1])-(s[1]-o[1])*(a[0]-s[0]);Math.abs(l)<=e||r.push(s)}return r.push(r[0]),Ye(r)}function jo(t,e,n){const r=n[0]-e[0],i=n[1]-e[1],o=r*r+i*i;if(o<=1e-12){const c=t[0]-e[0],h=t[1]-e[1];return c*c+h*h}const s=L(((t[0]-e[0])*r+(t[1]-e[1])*i)/o,0,1),a=e[0]+r*s,l=e[1]+i*s,u=t[0]-a,f=t[1]-l;return u*u+f*f}function Qo(t,e){if(t.length<=2||e<=0)return t.slice();const n=new Uint8Array(t.length);n[0]=1,n[t.length-1]=1;const r=e*e,i=[[0,t.length-1]];for(;i.length>0;){const s=i.pop();if(!s)break;const[a,l]=s;if(l-a<=1)continue;let u=0,f=-1;for(let c=a+1;c<l;c+=1){const h=jo(t[c],t[a],t[l]);h>u&&(u=h,f=c)}f>=0&&u>r&&(n[f]=1,i.push([a,f],[f,l]))}const o=[];for(let s=0;s<t.length;s+=1)n[s]&&o.push(t[s]);return o}function Jo(t,e){const n=Ye(t);if(n.length<5||e<=0)return n;const r=n.slice(0,-1),i=Qo(r,e);return i.length<3?n:Ye(i)}function es(t,e){let n=Ye(t);if(e<=0||n.length<5)return n;for(let r=0;r<e;r+=1){const i=n.slice(0,-1);if(i.length<3)break;const o=[];for(let s=0;s<i.length;s+=1){const a=i[s],l=i[(s+1)%i.length];o.push([a[0]*.75+l[0]*.25,a[1]*.75+l[1]*.25],[a[0]*.25+l[0]*.75,a[1]*.25+l[1]*.75])}n=Ye(o)}return n}function ts(t,e){const n=Wo(t),r=Math.max(Ht,Number(e.radius)||0);if(n.length===0||!Number.isFinite(r))return[];const i=Math.max(12,Math.floor(e.circleSides||ko));if(n.length===1)return Tt(lr(n[0],r,i),e.clipBounds);const o=[],s=Math.max(Ht,r*Yo);for(let h=0;h<n.length;h+=1){const d=n[h],m=lr(d,r,i);if(m.length>=4&&o.push([m]),h===0)continue;const g=Xo(n[h-1],d,r,s);g.length>=4&&o.push([g])}const a=Ho(o),l=a?$o(a):[];if(!l.length)return Tt(cr(n,r),e.clipBounds);const u=typeof e.simplifyTolerance=="number"&&Number.isFinite(e.simplifyTolerance)?Math.max(0,e.simplifyTolerance):Math.max(.25,r*Uo),f=typeof e.smoothingPasses=="number"&&Number.isFinite(e.smoothingPasses)?Math.round(L(e.smoothingPasses,0,Oo)):zo,c=Jo(es(Ko(l,1e-9),f),u);return c.length<4?Tt(cr(n,r),e.clipBounds):Tt(c,e.clipBounds)}function fr(){if(typeof window>"u")return 1;const t=window.devicePixelRatio||1;return Number.isFinite(t)&&t>0?t:1}function tn(t){if(typeof window>"u")return()=>{};let e=!0,n=fr(),r=null,i=null;const o=()=>{i?.(),i=null,r=null},s=()=>{o(),r=window.matchMedia(`(resolution: ${n}dppx)`);const f=()=>{a("match-media")};if(typeof r.addEventListener=="function"){r.addEventListener("change",f),i=()=>r?.removeEventListener("change",f);return}r.addListener(f),i=()=>r?.removeListener(f)},a=f=>{if(!e)return;const c=fr();if(Math.abs(c-n)<=1e-4)return;const h=n;n=c,s(),t({previousDpr:h,nextDpr:c,trigger:f})},l=()=>a("window-resize"),u=()=>a("visual-viewport-resize");return s(),window.addEventListener("resize",l),window.visualViewport?.addEventListener("resize",u),()=>{e=!1,o(),window.removeEventListener("resize",l),window.visualViewport?.removeEventListener("resize",u)}}const ot=[],hr=[],Ke={color:"#ff4d4f",width:2,lineDash:ot,lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},li={color:"#4cc9f0",width:2,lineDash:[10,8],lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},ci="rgba(23, 23, 25, 0.1)",ui=6,Ge={fontFamily:"Pretendard, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:11,fontWeight:600,textColor:"#171719",backgroundColor:"#FFCC00",borderColor:"rgba(0, 0, 0, 0)",borderWidth:0,paddingX:8,paddingY:4,offsetY:10,borderRadius:4},et={fontFamily:"Pretendard, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:13,fontWeight:500,textColor:"#FFFFFF",backgroundColor:"rgba(23, 23, 25, 0.5)",borderRadius:4,paddingX:6,paddingY:3},dr={x:16,y:-24},ns=20,mr=1e-6,gr="transparent",rs=3,is=2,fi=96,os=1,pr=1e3,hi=2,di=2,ss=4096,as=.2,ls=1.12,cs=.89,us=32,fs="#000000",hs=.1,ds="#FFCF00",ms="#FF0000",gs=1.5,yr=[2,2],ps=1,ys=.25,bs=4,xs=1,ws=0,Ss=4,Es=1.5;function Zt(t,e,n){return[L(t[0],0,e),L(t[1],0,n)]}function Dn(t){if(!Array.isArray(t)||t.length<2)return null;const e=Number(t[0]),n=Number(t[1]);return!Number.isFinite(e)||!Number.isFinite(n)?null:[e,n]}const qe=Dn;function Ue(t){return Ye(t)}function Wt(t){return Math.abs(wt(Ue(t)))}function br(t){if(!Array.isArray(t)||t.length===0)return[0,0,0,0];let e=1/0,n=1/0,r=-1/0,i=-1/0;for(const[o,s]of t)o<e&&(e=o),o>r&&(r=o),s<n&&(n=s),s>i&&(i=s);return[e,n,r,i]}function Et(t,e,n=!1){if(e.length!==0){t.moveTo(e[0][0],e[0][1]);for(let r=1;r<e.length;r+=1)t.lineTo(e[r][0],e[r][1]);n&&t.closePath()}}function Be(t,e,n,r=!1,i=!1,o="rgba(255, 77, 79, 0.16)"){e.length!==0&&(t.beginPath(),Et(t,e,r),i&&r&&(t.fillStyle=o,t.fill()),t.strokeStyle=n.color,t.lineWidth=n.width,t.lineJoin=n.lineJoin,t.lineCap=n.lineCap,t.shadowColor=n.shadowColor,t.shadowBlur=n.shadowBlur,t.shadowOffsetX=n.shadowOffsetX,t.shadowOffsetY=n.shadowOffsetY,t.setLineDash(n.lineDash),t.stroke(),t.setLineDash(ot),t.shadowColor="rgba(0, 0, 0, 0)",t.shadowBlur=0,t.shadowOffsetX=0,t.shadowOffsetY=0)}function Nn(t){const e=Array.isArray(t?.lineDash)?t.lineDash.filter(s=>Number.isFinite(s)&&s>=0):ot,n=typeof t?.width=="number"&&Number.isFinite(t.width)?Math.max(0,t.width):Ke.width,r=typeof t?.shadowBlur=="number"&&Number.isFinite(t.shadowBlur)?Math.max(0,t.shadowBlur):Ke.shadowBlur,i=typeof t?.shadowOffsetX=="number"&&Number.isFinite(t.shadowOffsetX)?t.shadowOffsetX:Ke.shadowOffsetX,o=typeof t?.shadowOffsetY=="number"&&Number.isFinite(t.shadowOffsetY)?t.shadowOffsetY:Ke.shadowOffsetY;return{color:t?.color||Ke.color,width:n,lineDash:e.length?e:ot,lineJoin:t?.lineJoin||Ke.lineJoin,lineCap:t?.lineCap||Ke.lineCap,shadowColor:t?.shadowColor||Ke.shadowColor,shadowBlur:r,shadowOffsetX:i,shadowOffsetY:o}}function je(t,e){return e?Nn({color:e.color??t.color,width:e.width??t.width,lineDash:e.lineDash??t.lineDash,lineJoin:e.lineJoin??t.lineJoin,lineCap:e.lineCap??t.lineCap,shadowColor:e.shadowColor??t.shadowColor,shadowBlur:e.shadowBlur??t.shadowBlur,shadowOffsetX:e.shadowOffsetX??t.shadowOffsetX,shadowOffsetY:e.shadowOffsetY??t.shadowOffsetY}):t}function $t(t,e){return t==null||e===null||e===void 0?!1:String(t)===String(e)}function xr(t){return typeof t=="number"&&Number.isFinite(t)}function Rs(t){return Array.isArray(t)&&t.length>=2&&xr(t[0])&&xr(t[1])}function As(t){return Array.isArray(t)&&t.length>=2&&t.every(e=>Rs(e))}function mi(t,e){if(!(!Array.isArray(t)||t.length===0)){if(As(t)){e.push(t.map(([n,r])=>[n,r]));return}for(const n of t)mi(n,e)}}function wr(t,e){const n=[];mi(t,n);const r=[];for(const i of n){if(i.length<2)continue;const o=e?Ue(i):i;o.length>=(e?4:2)&&r.push(o)}return r}function yt(t,e){return typeof t!="number"||!Number.isFinite(t)||t<=0?e:t}function Cs(t,e){return typeof t!="number"||!Number.isFinite(t)?e:L(t,0,1)}function gi(t,e,n,r,i,o){const s=Math.max(0,Math.min(o,r*.5,i*.5));t.beginPath(),t.moveTo(e+s,n),t.lineTo(e+r-s,n),t.quadraticCurveTo(e+r,n,e+r,n+s),t.lineTo(e+r,n+i-s),t.quadraticCurveTo(e+r,n+i,e+r-s,n+i),t.lineTo(e+s,n+i),t.quadraticCurveTo(e,n+i,e,n+i-s),t.lineTo(e,n+s),t.quadraticCurveTo(e,n,e+s,n),t.closePath()}function Ms(t){const e=t[0];return Array.isArray(e)&&Array.isArray(e[0])}function Kt(t,e,n){if(!t||!e)return[];if(n){const r=n.worldToScreen(t[0],t[1]),i=n.worldToScreen(e[0],e[1]);if(r&&i){const o=[[r[0],r[1]],[i[0],r[1]],[i[0],i[1]],[r[0],i[1]]],s=[];for(const a of o){const l=n.screenToWorld(a);if(!l)return Kt(t,e);s.push(l)}return Ue(s)}}return Ue([[t[0],t[1]],[e[0],t[1]],[e[0],e[1]],[t[0],e[1]]])}function Sn(t,e,n=fi){if(!t||!e)return[];const r=(t[0]+e[0])*.5,i=(t[1]+e[1])*.5,o=Math.hypot(e[0]-t[0],e[1]-t[1])*.5;if(o<1)return[];const s=[];for(let a=0;a<=n;a+=1){const l=a/n*Math.PI*2;s.push([r+Math.cos(l)*o,i+Math.sin(l)*o])}return Ue(s)}function jt(t){const e=oi(ht(t));if(e.length===0)return[];const n=[];for(const r of e){const i=r[0];if(!i||i.length<4)continue;const o=i.map(([a,l])=>[a,l]),s=[];for(let a=1;a<r.length;a+=1){const l=r[a];!l||l.length<4||s.push(l.map(([u,f])=>[u,f]))}n.push({outer:o,holes:s})}return n}function Ps(t){if(!Array.isArray(t))return yr;const e=t.filter(n=>Number.isFinite(n)&&n>=0);return e.length>0?e:yr}function vs(t){return typeof t!="number"||!Number.isFinite(t)?ps:L(t,ys,bs)}function Ts(t){return typeof t!="number"||!Number.isFinite(t)?xs:Math.round(L(t,ws,Ss))}function Is(t){const e=yt(t?.radius,us),n=yt(t?.cursorLineWidth,gs),r=vs(t?.edgeDetail),i=Ts(t?.edgeSmoothing);return{radius:e,edgeDetail:r,edgeSmoothing:i,clickSelectRoi:t?.clickSelectRoi===!0,fillColor:t?.fillColor||fs,fillOpacity:Cs(t?.fillOpacity,hs),cursorColor:t?.cursorColor||ds,cursorActiveColor:t?.cursorActiveColor||ms,cursorLineWidth:n,cursorLineDash:Ps(t?.cursorLineDash)}}function _s(t,e,n){if(!e.isDrawing||e.screenPoints.length===0)return;const r=e.screenPoints;if(r.length===0)return;const i=n.radius;if(!(!Number.isFinite(i)||i<=0)){if(t.save(),t.globalAlpha=n.fillOpacity,t.fillStyle=n.fillColor,t.strokeStyle=n.fillColor,t.lineCap="round",t.lineJoin="round",t.lineWidth=i*2,r.length===1)t.beginPath(),t.arc(r[0][0],r[0][1],i,0,Math.PI*2),t.fill();else{t.beginPath(),t.moveTo(r[0][0],r[0][1]);for(let o=1;o<r.length;o+=1)t.lineTo(r[o][0],r[o][1]);t.stroke()}t.restore()}}function Ls(t,e,n,r){const i=e.cursor;if(!i)return;const o=e.cursorScreen??qe(n?.worldToScreen(i[0],i[1])??[]);if(!o)return;const s=r.radius;!Number.isFinite(s)||s<=0||(t.save(),t.beginPath(),t.arc(o[0],o[1],s,0,Math.PI*2),t.strokeStyle=e.isDrawing?r.cursorActiveColor:r.cursorColor,t.lineWidth=r.cursorLineWidth,t.setLineDash(r.cursorLineDash),t.stroke(),t.setLineDash(ot),t.restore())}const Fs=.58,Ds=4096,Ns=.5;let It=null;const _t=new Map;function Bs(){if(It)return It;if(typeof document>"u")return null;const e=document.createElement("canvas").getContext("2d");return e?(It=e,It):null}function Bn(t,e){const n=`${e.fontWeight}|${e.fontSize}|${e.fontFamily}|${t}`,r=_t.get(n);if(r!==void 0)return r;const i=t.length*e.fontSize*Fs,o=Bs();let s=i;if(o){o.font=`${e.fontWeight} ${e.fontSize}px ${e.fontFamily}`;const a=o.measureText(t).width;Number.isFinite(a)&&a>=0&&(s=a)}return _t.size>Ds&&_t.clear(),_t.set(n,s),s}function ks(t,e="top-center"){if(!t.length)return null;let n=1/0;for(const o of t)o[1]<n&&(n=o[1]);if(!Number.isFinite(n))return null;let r=1/0,i=-1/0;for(const o of t)Math.abs(o[1]-n)>Ns||(o[0]<r&&(r=o[0]),o[0]>i&&(i=o[0]));return!Number.isFinite(r)||!Number.isFinite(i)?null:e==="top-center"?[(r+i)*.5,n]:[r,n]}function kn(t,e="top-center"){let n=null;for(const r of t){const i=ks(r.outer,e);i&&(!n||i[1]<n[1]||i[1]===n[1]&&i[0]<n[0])&&(n=i)}return n}function Un(t){const e=typeof t?.paddingX=="number"&&Number.isFinite(t.paddingX)?Math.max(0,t.paddingX):Ge.paddingX,n=typeof t?.paddingY=="number"&&Number.isFinite(t.paddingY)?Math.max(0,t.paddingY):Ge.paddingY,r=typeof t?.fontSize=="number"&&Number.isFinite(t.fontSize)?Math.max(8,t.fontSize):Ge.fontSize,i=typeof t?.borderWidth=="number"&&Number.isFinite(t.borderWidth)?Math.max(0,t.borderWidth):Ge.borderWidth,o=typeof t?.offsetY=="number"&&Number.isFinite(t.offsetY)?t.offsetY:Ge.offsetY,s=typeof t?.borderRadius=="number"&&Number.isFinite(t.borderRadius)?Math.max(0,t.borderRadius):Ge.borderRadius;return{fontFamily:t?.fontFamily||Ge.fontFamily,fontSize:r,fontWeight:t?.fontWeight||Ge.fontWeight,textColor:t?.textColor||Ge.textColor,backgroundColor:t?.backgroundColor||Ge.backgroundColor,borderColor:t?.borderColor||Ge.borderColor,borderWidth:i,paddingX:e,paddingY:n,offsetY:o,borderRadius:s}}function zn(t,e){return e?Un({fontFamily:e.fontFamily??t.fontFamily,fontSize:e.fontSize??t.fontSize,fontWeight:e.fontWeight??t.fontWeight,textColor:e.textColor??t.textColor,backgroundColor:e.backgroundColor??t.backgroundColor,borderColor:e.borderColor??t.borderColor,borderWidth:e.borderWidth??t.borderWidth,paddingX:e.paddingX??t.paddingX,paddingY:e.paddingY??t.paddingY,offsetY:e.offsetY??t.offsetY,borderRadius:e.borderRadius??t.borderRadius}):t}function On(t,e,n,r){if(!t||!n)return 0;const i=Number(n.minZoom),o=Number(n.maxZoom);if(!Number.isFinite(i)||!Number.isFinite(o)||o-i<=mr||!Number.isFinite(e))return 0;let s=o;r!=null&&Number.isFinite(r)&&(s=L(r,i,o));const a=Math.max(mr,Math.abs(s)*1e-9);return e>=s-a?ns:0}function Us(t){const e=typeof t?.fontSize=="number"&&Number.isFinite(t.fontSize)?Math.max(8,t.fontSize):et.fontSize,n=typeof t?.borderRadius=="number"&&Number.isFinite(t.borderRadius)?Math.max(0,t.borderRadius):et.borderRadius,r=typeof t?.paddingX=="number"&&Number.isFinite(t.paddingX)?Math.max(0,t.paddingX):et.paddingX,i=typeof t?.paddingY=="number"&&Number.isFinite(t.paddingY)?Math.max(0,t.paddingY):et.paddingY;return{fontFamily:t?.fontFamily||et.fontFamily,fontSize:e,fontWeight:t?.fontWeight||et.fontWeight,textColor:t?.textColor||et.textColor,backgroundColor:t?.backgroundColor||et.backgroundColor,borderRadius:n,paddingX:r,paddingY:i}}function zs(t){const e=typeof t?.x=="number"&&Number.isFinite(t.x)?t.x:dr.x,n=typeof t?.y=="number"&&Number.isFinite(t.y)?t.y:dr.y;return{x:e,y:n}}function Os(t){return Number.isFinite(t)?`${Math.max(0,t).toFixed(3)} mm²`:"0.000 mm²"}function Ys(t){const e=typeof t?.format=="function"?t.format:Os,n=zs(t?.cursorOffset);return{enabled:t?.enabled===!0,format:e,style:Us(t?.style),cursorOffsetX:n.x,cursorOffsetY:n.y}}function pi(t,e,n,r,i,o,s=!0){const a=e.trim();if(!a)return;t.save(),t.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,t.textAlign="center",t.textBaseline="middle";const u=Bn(a,o)+o.paddingX*2,f=o.fontSize+o.paddingY*2,c=n[0],h=n[1]-o.offsetY,d=s?L(c,u*.5+1,r-u*.5-1):c,m=s?L(h,f*.5+1,i-f*.5-1):h,g=d-u*.5,y=m-f*.5;t.fillStyle=o.backgroundColor,t.strokeStyle=o.borderColor,t.lineWidth=o.borderWidth,gi(t,g,y,u,f,o.borderRadius),t.fill(),o.borderWidth>0&&t.stroke(),t.fillStyle=o.textColor,t.fillText(a,d,m+.5),t.restore()}function Ws(t,e,n,r,i,o,s,a){const l=e.trim();if(!l)return;t.save(),t.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,t.textAlign="center",t.textBaseline="middle";const f=Bn(l,o)+o.paddingX*2,c=o.fontSize+o.paddingY*2,h=L(n[0]+s,f*.5+1,r-f*.5-1),d=L(n[1]+a,c*.5+1,i-c*.5-1),m=h-f*.5,g=d-c*.5;t.fillStyle=o.backgroundColor,gi(t,m,g,f,c,o.borderRadius),t.fill(),t.fillStyle=o.textColor,t.fillText(l,h,d+.5),t.restore()}function Xs(t,e,n,r){if(!(e.length<4||n.length===0)){t.save(),t.beginPath(),Et(t,e,!0);for(const i of n)i.length<4||Et(t,i,!0);t.fillStyle=r,t.fill("evenodd"),t.restore()}}function yi(t){const{ctx:e,overlayShapes:n,imageOuterRing:r,worldToScreenPoints:i,baseStrokeStyle:o,onInvertedFillDebug:s}=t,a=!!globalThis.__OPEN_PLANT_DEBUG_OVERLAY__;for(let l=0;l<n.length;l+=1){const u=n[l];if(!u?.coordinates?.length||u.visible===!1)continue;const f=u.closed??Ms(u.coordinates),c=wr(u.coordinates,f);if(u.invertedFill?.fillColor){const d=[],m=wr(u.coordinates,!0);for(const g of m){const y=i(g);y.length>=4&&d.push(y)}a&&s&&s({id:u.id??l,outerRingPoints:r.length,sourceRingCount:m.length,holeRingCount:d.length,fillColor:u.invertedFill.fillColor}),Xs(e,r,d,u.invertedFill.fillColor)}if(c.length===0)continue;const h=je(o,u.stroke??u.strokeStyle);for(const d of c){const m=i(d);m.length<2||Be(e,m,h,f,u.fill??!1)}}}function Lt(t){return typeof t=="string"&&(t==="stamp-rectangle"||t==="stamp-circle"||t==="stamp-rectangle-4096px"||t==="stamp-rectangle-2mm2"||t==="stamp-circle-2mm2"||t==="stamp-circle-hpf-0.2mm2")}function Vs(t){return{rectangleAreaMm2:yt(t?.rectangleAreaMm2,hi),circleAreaMm2:yt(t?.circleAreaMm2,di),rectanglePixelSize:yt(t?.rectanglePixelSize,ss)}}const Sr=1e3;function Gs(t){return t*Sr*Sr}function Er(t,e,n){if(!t||!Number.isFinite(e)||e<=0)return[];if(n){const r=n.worldToScreen(t[0],t[1]),i=n.worldToScreen(t[0]+e,t[1]);if(r&&i){const o=Math.hypot(i[0]-r[0],i[1]-r[1]),s=[[r[0]-o,r[1]-o],[r[0]+o,r[1]-o],[r[0]+o,r[1]+o],[r[0]-o,r[1]+o]],a=[];for(const l of s){const u=n.screenToWorld(l);if(!u)throw new Error("Failed to create rectangle");a.push(u)}return Ue(a)}}return Ue([[t[0]-e,t[1]-e],[t[0]+e,t[1]-e],[t[0]+e,t[1]+e],[t[0]-e,t[1]+e]])}function qs(t,e,n=fi){if(!t||!Number.isFinite(e)||e<=0)return[];const r=[];for(let i=0;i<=n;i+=1){const o=i/n*Math.PI*2;r.push([t[0]+Math.cos(o)*e,t[1]+Math.sin(o)*e])}return Ue(r)}function Hs(t){const{stampTool:e,center:n,resolvedStampOptions:r,imageWidth:i,imageHeight:o,micronsToWorldPixels:s,getRectangleProjection:a}=t;if(!n)return[];if(e==="stamp-rectangle-4096px"){const c=r.rectanglePixelSize*.5;return Er(n,c,a()).map(h=>Zt(h,i,o))}let l=0;if(e==="stamp-rectangle"||e==="stamp-rectangle-2mm2"?l=e==="stamp-rectangle-2mm2"?hi:r.rectangleAreaMm2:(e==="stamp-circle"||e==="stamp-circle-2mm2"||e==="stamp-circle-hpf-0.2mm2")&&(l=e==="stamp-circle-hpf-0.2mm2"?as:e==="stamp-circle-2mm2"?di:r.circleAreaMm2),!Number.isFinite(l)||l<=0)return[];const u=Gs(l);let f=[];if(e==="stamp-rectangle"||e==="stamp-rectangle-2mm2"){const c=s(Math.sqrt(u)*.5);f=Er(n,c,a())}else if(e==="stamp-circle"||e==="stamp-circle-2mm2"||e==="stamp-circle-hpf-0.2mm2"){const c=s(Math.sqrt(u/Math.PI));f=qs(n,c)}return f.length?f.map(c=>Zt(c,i,o)):[]}function Zs(t){return{color:ci,width:ui,lineDash:ot,lineJoin:t.lineJoin,lineCap:t.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function $s(t){if(typeof t!="string")return gr;const e=t.trim();return e.length>0?e:gr}function Rr(t){return Array.isArray(t)&&t.length>=4&&Wt(t)>os}function bi({tool:t,imageWidth:e,imageHeight:n,imageMpp:r,imageZoom:i,stampOptions:o,brushOptions:s,projectorRef:a,onBrushTap:l,onDrawComplete:u,onPatchComplete:f,enabled:c,viewStateSignal:h,persistedRegions:d,patchRegions:m,persistedPolygons:g,drawFillColor:y,regionStrokeStyle:b,regionStrokeHoverStyle:x,regionStrokeActiveStyle:A,patchStrokeStyle:S,resolveRegionStrokeStyle:C,resolveRegionLabelStyle:M,overlayShapes:P,hoveredRegionId:U=null,activeRegionId:O=null,regionLabelStyle:N,drawAreaTooltip:v,autoLiftRegionLabelAtMaxZoom:B=!1,regionLabelAnchor:F="top-center",clampRegionLabelToViewport:z=!0,regionLabelAutoLiftOffsetPx:K,invalidateRef:Y,className:j,style:ce}){const J=p.useRef(null),Te=p.useRef(!1),Pe=p.useRef(new Map),Re=p.useRef(t),_=p.useRef({isDrawing:!1,pointerId:null,start:null,current:null,cursor:null,cursorScreen:null,points:[],screenPoints:[],stampCenter:null}),T=c??t!=="cursor",X=p.useMemo(()=>d&&d.length>0?d:!g||g.length===0?hr:g.map((w,R)=>({id:R,coordinates:w})),[d,g]),q=p.useMemo(()=>m??hr,[m]),te=p.useMemo(()=>{const w=[];for(let R=0;R<X.length;R+=1){const D=X[R],k=jt(D.coordinates);k.length!==0&&w.push({region:D,regionIndex:R,regionKey:D.id??R,polygons:k})}return w},[X]),le=p.useMemo(()=>{const w=[];for(let R=0;R<q.length;R+=1){const D=q[R],k=jt(D.coordinates);k.length!==0&&w.push({region:D,regionIndex:R,regionKey:D.id??R,polygons:k})}return w},[q]),re=p.useMemo(()=>Nn(b),[b]),ge=p.useMemo(()=>je(re,x),[re,x]),ne=p.useMemo(()=>je(re,A),[re,A]),pe=p.useMemo(()=>je(li,S),[S]),he=p.useMemo(()=>$s(y),[y]),se=p.useMemo(()=>Un(N),[N]),ue=p.useMemo(()=>Ys(v),[v]),Ae=p.useMemo(()=>Vs(o),[o]),H=p.useMemo(()=>Is(s),[s]),Le=p.useMemo(()=>({position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",touchAction:"none",pointerEvents:T?"auto":"none",cursor:T?t==="brush"?"none":"crosshair":"default",...ce}),[T,t,ce]),we=p.useCallback(()=>{const w=J.current;if(!w)return;const R=w.getBoundingClientRect(),D=Math.max(1,window.devicePixelRatio||1),k=Math.max(1,Math.round(R.width*D)),Z=Math.max(1,Math.round(R.height*D));(w.width!==k||w.height!==Z)&&(w.width=k,w.height=Z)},[T,t]),de=p.useCallback(w=>{const R=a.current;if(!R||w.length===0)return[];const D=new Array(w.length);for(let k=0;k<w.length;k+=1){const Z=qe(R.worldToScreen(w[k][0],w[k][1]));if(!Z)return[];D[k]=Z}return D},[a]),V=p.useCallback(w=>{const R=a.current,D=J.current;if(!R||!D)return null;const k=D.getBoundingClientRect(),Z=qe(R.screenToWorld(k.left+w[0],k.top+w[1]));return Z?Zt(Z,e,n):null},[a,e,n]),$=p.useCallback(()=>{const w=a.current,R=w?.getViewState?.().rotationDeg??0;if(!(Math.abs(R%360)<.01||!w))return{worldToScreen:(D,k)=>qe(w.worldToScreen(D,k)),screenToWorld:V}},[a,V]),ie=p.useCallback(w=>{if(!Number.isFinite(w)||w<=0)return 0;const R=typeof r=="number"&&Number.isFinite(r)&&r>0?r:1,D=typeof i=="number"&&Number.isFinite(i)?i:0,k=a.current?.getViewState?.().zoom,Z=typeof k=="number"&&Number.isFinite(k)&&k>0?k:1,Ee=D+Math.log2(Z),ae=Math.max(1e-9,Fn(R,D,Ee));return w/ae/Z},[r,i,a]),oe=p.useCallback((w,R)=>Hs({stampTool:w,center:R,resolvedStampOptions:Ae,imageWidth:e,imageHeight:n,micronsToWorldPixels:ie,getRectangleProjection:$}),[ie,e,n,Ae,$]),Se=p.useCallback(()=>{const w=_.current;return Lt(t)?oe(t,w.stampCenter):t==="brush"?[]:w.isDrawing?t==="freehand"?w.points:t==="rectangle"?Kt(w.start,w.current,$()):t==="circular"?Sn(w.start,w.current):[]:[]},[t,oe,$]),De=p.useCallback(()=>{we();const w=J.current;if(!w)return;const R=w.getContext("2d");if(!R)return;const D=Math.max(1,window.devicePixelRatio||1),k=w.width/D,Z=w.height/D;if(R.setTransform(1,0,0,1,0,0),R.clearRect(0,0,w.width,w.height),R.setTransform(D,0,0,D,0,0),te.length>0)for(const ae of te){const{region:me,polygons:Me,regionIndex:_e,regionKey:ze}=ae,Ve=$t(O,ze)?"active":$t(U,ze)?"hover":"default";let Je=Ve==="active"?ne:Ve==="hover"?ge:re;if(C){const vt=C({region:me,regionId:ze,regionIndex:_e,state:Ve});Je=je(Je,vt||void 0)}const Pt=Ve==="default"?null:Zs(Je);for(const vt of Me){const rn=de(vt.outer);rn.length>=4&&(Pt&&Be(R,rn,Pt,!0,!1),Be(R,rn,Je,!0,!1));for(const Ki of vt.holes){const on=de(Ki);on.length>=4&&(Pt&&Be(R,on,Pt,!0,!1),Be(R,on,Je,!0,!1))}}}if(le.length>0)for(const ae of le)for(const me of ae.polygons){const Me=de(me.outer);Me.length>=4&&Be(R,Me,pe,!0,!1);for(const _e of me.holes){const ze=de(_e);ze.length>=4&&Be(R,ze,pe,!0,!1)}}if(Array.isArray(P)&&P.length>0){const ae=de(Ue([[0,0],[e,0],[e,n],[0,n]]));yi({ctx:R,overlayShapes:P,imageOuterRing:ae,worldToScreenPoints:de,baseStrokeStyle:re,onInvertedFillDebug:globalThis.__OPEN_PLANT_DEBUG_OVERLAY__?me=>{const Me=String(me.id),_e=`${me.outerRingPoints}|${me.sourceRingCount}|${me.holeRingCount}|${me.fillColor}`;Pe.current.get(Me)!==_e&&(Pe.current.set(Me,_e),console.debug("[open-plant] invertedFill",me))}:void 0})}const Ee=Se();if(T){if(t==="brush")_s(R,_.current,H),Ls(R,_.current,a.current,H);else if(Ee.length>0)if(t==="freehand"){const ae=de(Ee);ae.length>=2&&Be(R,ae,re,!1,!1),ae.length>=3&&Be(R,de(Ue(Ee)),re,!0,!0,he)}else{const ae=de(Ee);ae.length>=4&&Be(R,ae,re,!0,!0,he)}}if(te.length>0){const ae=Math.max(1e-6,a.current?.getViewState?.().zoom??1),me=typeof K=="number"&&Number.isFinite(K)?Math.max(0,K):On(B,ae,a.current?.getZoomRange?.(),a.current?.getRegionLabelAutoLiftCapZoom?.());for(const Me of te){if(!Me.region.label)continue;const _e=kn(Me.polygons,F);if(!_e)continue;const ze=qe(a.current?.worldToScreen(_e[0],_e[1])??[]);if(!ze)continue;let Ve=zn(se,M?.({region:Me.region,regionId:Me.regionKey,regionIndex:Me.regionIndex,zoom:ae}));me>0&&(Ve={...Ve,offsetY:Ve.offsetY+me}),pi(R,Me.region.label,ze,k,Z,Ve,z)}}if(ue.enabled&&T&&(t==="freehand"||t==="rectangle"||t==="circular")){const ae=_.current;if(ae.isDrawing){const me=t==="freehand"?Ue(Ee):Ee;if(me.length>=4){const Me=Wt(me),_e=typeof r=="number"&&Number.isFinite(r)&&r>0?r:0,ze=_e>0?Me*_e*_e/(pr*pr):0,Ve=ue.format(ze),Je=ae.cursorScreen??(ae.current?qe(a.current?.worldToScreen(ae.current[0],ae.current[1])??[]):null);Je&&Ws(R,Ve,Je,k,Z,ue.style,ue.cursorOffsetX,ue.cursorOffsetY)}}}},[T,t,Se,we,de,e,n,a,te,P,U,O,re,ge,ne,he,le,pe,C,M,se,ue,B,F,z,K,r,H]),G=p.useCallback(()=>{Te.current||(Te.current=!0,requestAnimationFrame(()=>{Te.current=!1,De()}))},[De]),ye=p.useCallback((w=!1)=>{const R=_.current,D=J.current;D&&R.pointerId!==null&&D.hasPointerCapture(R.pointerId)&&D.releasePointerCapture(R.pointerId),R.isDrawing=!1,R.pointerId=null,R.start=null,R.current=null,R.points=[],R.screenPoints=[],R.stampCenter=null,w||(R.cursor=null,R.cursorScreen=null)},[]),be=p.useCallback(w=>{const R=a.current;if(!R||e<=0||n<=0)return null;const D=qe(R.screenToWorld(w.clientX,w.clientY));return D?Zt(D,e,n):null},[a,e,n]),I=p.useCallback(w=>{const R=J.current;if(!R)return null;const D=R.getBoundingClientRect(),k=L(w.clientX-D.left,0,D.width),Z=L(w.clientY-D.top,0,D.height);return!Number.isFinite(k)||!Number.isFinite(Z)?null:[k,Z]},[]),W=p.useCallback(()=>{const w=_.current;if(!w.isDrawing){ye(!0),G();return}let R=[];if(t==="freehand")w.points.length>=rs&&(R=Ue(w.points));else if(t==="rectangle")R=Kt(w.start,w.current,$());else if(t==="circular")R=Sn(w.start,w.current);else if(t==="brush"){const D=w.points[w.points.length-1]??w.current??w.start;if(H.clickSelectRoi&&D&&w.points.length<=1&&l?.(D)){ye(!0),G();return}const k=Math.max(.25,H.edgeDetail),Z=w.screenPoints.length>0?w.screenPoints:de(w.points),Ee=Math.max(.5,H.radius*.04/k),ae=ts(Z,{radius:H.radius,circleSides:Math.max(16,Math.round(32*k)),simplifyTolerance:Ee,smoothingPasses:H.edgeSmoothing}),me=[];for(const Me of ae){const _e=V(Me);_e&&me.push(_e)}R=Ue(me)}(t==="freehand"||t==="rectangle"||t==="circular"||t==="brush")&&Rr(R)&&u&&u({tool:t,intent:t==="brush"?"brush":"roi",coordinates:R,bbox:br(R),areaPx:Wt(R)}),ye(!0),G()},[t,u,ye,G,de,V,$,H.radius,H.edgeDetail,H.edgeSmoothing,H.clickSelectRoi,l]),Q=p.useCallback((w,R)=>{const D=oe(w,R);if(!Rr(D))return;const k=w==="stamp-rectangle-4096px"?"patch":"roi",Z={tool:w,intent:k,coordinates:D,bbox:br(D),areaPx:Wt(D)};u?.(Z),k==="patch"&&f&&f(Z)},[oe,u,f]),ee=p.useCallback((w,R,D)=>{const k=Math.max(Es,H.radius*.1),Z=k*k,Ee=w.screenPoints[w.screenPoints.length-1];if(!Ee){w.points.push(R),w.screenPoints.push(D),w.current=R;return}const ae=D[0]-Ee[0],me=D[1]-Ee[1];ae*ae+me*me>=Z?(w.points.push(R),w.screenPoints.push(D)):(w.points[w.points.length-1]=R,w.screenPoints[w.screenPoints.length-1]=D),w.current=R},[H.radius]),fe=p.useCallback(w=>{if(!T||t==="cursor"||w.button!==0)return;const R=be(w);if(!R)return;const D=I(w);if(!D)return;if(w.preventDefault(),w.stopPropagation(),Lt(t)){const Ee=_.current;Ee.stampCenter=R,Q(t,R),G();return}const k=J.current;k&&k.setPointerCapture(w.pointerId);const Z=_.current;Z.isDrawing=!0,Z.pointerId=w.pointerId,Z.start=R,Z.current=R,Z.cursor=R,Z.cursorScreen=D,Z.points=t==="freehand"||t==="brush"?[R]:[],Z.screenPoints=t==="brush"?[D]:[],G()},[T,t,be,I,Q,G]),Ce=p.useCallback(w=>{if(!T||t==="cursor")return;const R=be(w);if(!R)return;const D=I(w);if(!D)return;const k=_.current;if(k.cursor=R,k.cursorScreen=D,Lt(t)){k.stampCenter=R,w.preventDefault(),w.stopPropagation(),G();return}if(t==="brush"){if(!k.isDrawing||k.pointerId!==w.pointerId){G();return}w.preventDefault(),w.stopPropagation(),ee(k,R,D),G();return}if(!(!k.isDrawing||k.pointerId!==w.pointerId)){if(w.preventDefault(),w.stopPropagation(),t==="freehand"){const Z=a.current,Ee=Math.max(1e-6,Z?.getViewState?.().zoom??1),ae=is/Ee,me=ae*ae,Me=k.points[k.points.length-1];if(!Me)k.points.push(R);else{const _e=R[0]-Me[0],ze=R[1]-Me[1];_e*_e+ze*ze>=me&&k.points.push(R)}}else k.current=R;G()}},[T,t,be,I,G,a,ee]),Ie=p.useCallback(w=>{const R=_.current;if(!R.isDrawing||R.pointerId!==w.pointerId)return;w.preventDefault(),w.stopPropagation();const D=be(w),k=I(w);D&&(R.cursor=D,k&&(R.cursorScreen=k),t==="brush"?k&&ee(R,D,k):R.current=D);const Z=J.current;Z&&Z.hasPointerCapture(w.pointerId)&&Z.releasePointerCapture(w.pointerId),W()},[W,be,I,t,ee]),ve=p.useCallback(()=>{const w=_.current;let R=!1;t==="brush"&&!w.isDrawing&&w.cursor&&(w.cursor=null,w.cursorScreen=null,R=!0),Lt(t)&&w.stampCenter&&(w.stampCenter=null,R=!0),R&&G()},[t,G]);return p.useEffect(()=>{we(),G();const w=J.current;if(!w)return;const R=new ResizeObserver(()=>{we(),G()});return R.observe(w),()=>{R.disconnect()}},[we,G]),p.useEffect(()=>tn(()=>{we(),G()}),[we,G]),p.useEffect(()=>{T||ye(),G()},[T,G,ye]),p.useEffect(()=>{Re.current!==t&&(Re.current=t,ye(),G())},[t,ye,G]),p.useEffect(()=>{G()},[h,X,P,G]),p.useEffect(()=>{if(Y)return Y.current=G,()=>{Y.current===G&&(Y.current=null)}},[Y,G]),p.useEffect(()=>{if(!T)return;const w=R=>{R.key==="Escape"&&(ye(),G())};return window.addEventListener("keydown",w),()=>{window.removeEventListener("keydown",w)}},[T,ye,G]),He.jsx("canvas",{ref:J,className:j,style:Le,onPointerDown:fe,onPointerMove:Ce,onPointerUp:Ie,onPointerCancel:Ie,onPointerLeave:ve,onContextMenu:w=>{T&&w.preventDefault()},onWheel:w=>{if(!T)return;const R=J.current,D=a.current;if(!R||typeof D?.zoomBy!="function")return;w.preventDefault(),w.stopPropagation();const k=R.getBoundingClientRect(),Z=w.clientX-k.left,Ee=w.clientY-k.top;D.zoomBy(w.deltaY<0?ls:cs,Z,Ee),G()}})}const xi=p.createContext(null),Ks=xi.Provider;function at(){const t=p.useContext(xi);if(!t)throw new Error("useViewerContext must be used within a <WsiViewer>");return t}function js({tool:t="cursor",stampOptions:e,brushOptions:n,fillColor:r,areaTooltip:i,onComplete:o,onPatchComplete:s,onBrushTap:a}){const{source:l,rendererRef:u,rendererSerial:f,setInteractionLock:c}=at(),h=t!=="cursor";p.useEffect(()=>(c("drawing-layer",h),()=>c("drawing-layer",!1)),[h,c]);const d=p.useMemo(()=>u.current?.getViewState(),[f]);return l?He.jsx(bi,{tool:t,enabled:h,imageWidth:l.width,imageHeight:l.height,imageMpp:l.mpp,imageZoom:l.maxTierZoom,stampOptions:e,brushOptions:n,drawFillColor:r,projectorRef:u,onBrushTap:a,viewStateSignal:d,drawAreaTooltip:i,onDrawComplete:o,onPatchComplete:s}):null}function Ar(t,e,n,r){return[Math.min(t,n),Math.min(e,r),Math.max(t,n),Math.max(e,r)]}function Cr(t,e){return!(t[2]<e[0]||t[0]>e[2]||t[3]<e[1]||t[1]>e[3])}class Qs{constructor(e=16){E(this,"targetNodeSize");E(this,"items",[]);E(this,"globalBounds",[0,0,0,0]);E(this,"gridSize",1);E(this,"cellWidth",1);E(this,"cellHeight",1);E(this,"buckets",[]);E(this,"visited",new Uint32Array(0));E(this,"querySerial",1);const n=Number.isFinite(e)?Math.floor(e):16;this.targetNodeSize=Math.max(1,n)}load(e){if(!Array.isArray(e)||e.length===0){this.items=[],this.globalBounds=[0,0,0,0],this.gridSize=1,this.cellWidth=1,this.cellHeight=1,this.buckets=[],this.visited=new Uint32Array(0),this.querySerial=1;return}const n=[];let r=1/0,i=1/0,o=-1/0,s=-1/0;for(const f of e){if(!f||!Number.isFinite(f.minX)||!Number.isFinite(f.minY)||!Number.isFinite(f.maxX)||!Number.isFinite(f.maxY))continue;const c=Ar(f.minX,f.minY,f.maxX,f.maxY);r=Math.min(r,c[0]),i=Math.min(i,c[1]),o=Math.max(o,c[2]),s=Math.max(s,c[3]),n.push({minX:c[0],minY:c[1],maxX:c[2],maxY:c[3],value:f.value})}if(this.items=n,this.visited=new Uint32Array(n.length),this.querySerial=1,n.length===0||!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(o)||!Number.isFinite(s)){this.globalBounds=[0,0,0,0],this.gridSize=1,this.cellWidth=1,this.cellHeight=1,this.buckets=[];return}this.globalBounds=[r,i,o,s],this.gridSize=Math.max(1,Math.ceil(Math.sqrt(n.length/this.targetNodeSize)));const a=Math.max(0,o-r),l=Math.max(0,s-i);this.cellWidth=a>0?a/this.gridSize:1,this.cellHeight=l>0?l/this.gridSize:1;const u=this.gridSize*this.gridSize;this.buckets=Array.from({length:u},()=>[]);for(let f=0;f<n.length;f+=1){const c=n[f],h=this.toCellX(c.minX),d=this.toCellX(c.maxX),m=this.toCellY(c.minY),g=this.toCellY(c.maxY);for(let y=m;y<=g;y+=1)for(let b=h;b<=d;b+=1)this.buckets[y*this.gridSize+b].push(f)}}search(e){if(this.items.length===0)return[];if(!Array.isArray(e)||e.length<4)return[];const n=Ar(e[0],e[1],e[2],e[3]);if(!Cr(n,this.globalBounds))return[];const r=this.toCellX(n[0]),i=this.toCellX(n[2]),o=this.toCellY(n[1]),s=this.toCellY(n[3]),a=this.nextSerial(),l=[];for(let u=o;u<=s;u+=1)for(let f=r;f<=i;f+=1){const c=this.buckets[u*this.gridSize+f];if(!(!c||c.length===0))for(const h of c){if(this.visited[h]===a)continue;this.visited[h]=a;const d=this.items[h];Cr(n,[d.minX,d.minY,d.maxX,d.maxY])&&l.push(d)}}return l}nextSerial(){return this.querySerial+=1,this.querySerial===4294967295&&(this.visited.fill(0),this.querySerial=1),this.querySerial}toCellX(e){const n=this.globalBounds[0],r=this.globalBounds[2];if(this.gridSize<=1||r<=n)return 0;const i=(e-n)/this.cellWidth;return!Number.isFinite(i)||i<=0?0:i>=this.gridSize-1?this.gridSize-1:Math.max(0,Math.min(this.gridSize-1,Math.floor(i)))}toCellY(e){const n=this.globalBounds[1],r=this.globalBounds[3];if(this.gridSize<=1||r<=n)return 0;const i=(e-n)/this.cellHeight;return!Number.isFinite(i)||i<=0?0:i>=this.gridSize-1?this.gridSize-1:Math.max(0,Math.min(this.gridSize-1,Math.floor(i)))}}function wi(t){return new Qs(t)}const Js=`#version 300 es
32
+ `;class oi{constructor(e){E(this,"canvas");E(this,"gl");E(this,"camera",new ii);E(this,"imageWidth");E(this,"imageHeight");E(this,"clearColor");E(this,"program");E(this,"vao");E(this,"quadBuffer");E(this,"uCameraLocation");E(this,"uBoundsLocation");E(this,"uTextureLocation");E(this,"resizeObserver");E(this,"tiles",[]);E(this,"frameId",null);E(this,"loadVersion",0);E(this,"destroyed",!1);E(this,"fitted",!1);E(this,"controlledViewState",!1);this.canvas=e.canvas,this.imageWidth=Math.max(1,e.imageWidth),this.imageHeight=Math.max(1,e.imageHeight),this.clearColor=e.clearColor??[.03,.05,.08,1],this.gl=ro(this.canvas),this.program=bt(this.gl,io,oo);const n=this.gl.createVertexArray(),r=this.gl.createBuffer();if(!n||!r)throw new Error("Failed to create WebGL buffers.");this.vao=n,this.quadBuffer=r,this.gl.bindVertexArray(this.vao),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.quadBuffer);const i=new Float32Array([0,0,0,0,1,0,1,0,0,1,0,1,1,1,1,1]);this.gl.bufferData(this.gl.ARRAY_BUFFER,i,this.gl.STATIC_DRAW);const o=this.gl.getAttribLocation(this.program,"aUnit"),s=this.gl.getAttribLocation(this.program,"aUv");if(o<0||s<0)throw new Error("Failed to get attribute locations.");const a=4*Float32Array.BYTES_PER_ELEMENT;this.gl.enableVertexAttribArray(o),this.gl.vertexAttribPointer(o,2,this.gl.FLOAT,!1,a,0),this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,a,2*Float32Array.BYTES_PER_ELEMENT),this.gl.bindVertexArray(null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.uCameraLocation=Le(this.gl,this.program,"uCamera"),this.uBoundsLocation=Le(this.gl,this.program,"uBounds"),this.uTextureLocation=Le(this.gl,this.program,"uTexture"),e.initialViewState&&(this.controlledViewState=!0,this.camera.setViewState(e.initialViewState)),this.resizeObserver=new ResizeObserver(()=>{this.resize()}),this.resizeObserver.observe(this.canvas),this.resize()}async setTiles(e){if(this.destroyed)return;const n=++this.loadVersion,r=await Promise.all(e.map(async i=>await this.loadTile(i,n)));if(this.destroyed||n!==this.loadVersion){for(const i of r)i&&this.gl.deleteTexture(i.texture);return}this.disposeTiles(this.tiles),this.tiles=r.filter(i=>i!==null),this.requestRender()}setViewState(e){this.controlledViewState=!0,this.camera.setViewState(e),this.requestRender()}getViewState(){return this.camera.getViewState()}destroy(){this.destroyed||(this.destroyed=!0,this.loadVersion+=1,this.frameId!==null&&(cancelAnimationFrame(this.frameId),this.frameId=null),this.resizeObserver.disconnect(),this.disposeTiles(this.tiles),this.tiles=[],this.gl.deleteBuffer(this.quadBuffer),this.gl.deleteVertexArray(this.vao),this.gl.deleteProgram(this.program))}async loadTile(e,n){try{const r=await fetch(e.url);if(!r.ok)throw new Error(`Tile fetch failed: ${r.status} ${r.statusText}`);const i=await r.blob(),o=await createImageBitmap(i);if(this.destroyed||n!==this.loadVersion)return o.close(),null;const s=this.gl.createTexture();if(!s)throw o.close(),new Error("Failed to create tile texture.");return this.gl.bindTexture(this.gl.TEXTURE_2D,s),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,1),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,o),this.gl.bindTexture(this.gl.TEXTURE_2D,null),o.close(),{id:e.id,bounds:e.bounds,texture:s}}catch(r){return console.error(`[M1TileRenderer] tile load failed: ${e.id}`,r),null}}resize(){if(this.destroyed)return;const e=this.canvas.getBoundingClientRect(),n=Math.max(1,e.width||this.canvas.clientWidth||1),r=Math.max(1,e.height||this.canvas.clientHeight||1),i=Math.max(1,window.devicePixelRatio||1),o=Math.max(1,Math.round(n*i)),s=Math.max(1,Math.round(r*i));(this.canvas.width!==o||this.canvas.height!==s)&&(this.canvas.width=o,this.canvas.height=s),this.camera.setViewport(n,r),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),!this.fitted&&!this.controlledViewState&&(this.fitToImage(),this.fitted=!0),this.requestRender()}fitToImage(){const e=this.camera.getViewportSize(),n=Math.min(e.width/this.imageWidth,e.height/this.imageHeight),r=Number.isFinite(n)&&n>0?n:1,i=e.width/r,o=e.height/r,s=(this.imageWidth-i)*.5,a=(this.imageHeight-o)*.5;this.camera.setViewState({zoom:r,offsetX:s,offsetY:a})}requestRender(){this.frameId!==null||this.destroyed||(this.frameId=requestAnimationFrame(()=>{this.frameId=null,this.render()}))}render(){if(!this.destroyed){this.gl.clearColor(this.clearColor[0],this.clearColor[1],this.clearColor[2],this.clearColor[3]),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.useProgram(this.program),this.gl.bindVertexArray(this.vao),this.gl.uniformMatrix3fv(this.uCameraLocation,!1,this.camera.getMatrix()),this.gl.uniform1i(this.uTextureLocation,0);for(const e of this.tiles)this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,e.texture),this.gl.uniform4f(this.uBoundsLocation,e.bounds[0],e.bounds[1],e.bounds[2],e.bounds[3]),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindVertexArray(null)}}disposeTiles(e){for(const n of e)this.gl.deleteTexture(n.texture)}}class rt{constructor(e,n){this.next=null,this.key=e,this.data=n,this.left=null,this.right=null}}function so(t,e){return t>e?1:t<e?-1:0}function et(t,e,n){const r=new rt(null,null);let i=r,o=r;for(;;){const s=n(t,e.key);if(s<0){if(e.left===null)break;if(n(t,e.left.key)<0){const a=e.left;if(e.left=a.right,a.right=e,e=a,e.left===null)break}o.left=e,o=e,e=e.left}else if(s>0){if(e.right===null)break;if(n(t,e.right.key)>0){const a=e.right;if(e.right=a.left,a.left=e,e=a,e.right===null)break}i.right=e,i=e,e=e.right}else break}return i.right=e.left,o.left=e.right,e.left=r.right,e.right=r.left,e}function an(t,e,n,r){const i=new rt(t,e);if(n===null)return i.left=i.right=null,i;n=et(t,n,r);const o=r(t,n.key);return o<0?(i.left=n.left,i.right=n,n.left=null):o>=0&&(i.right=n.right,i.left=n,n.right=null),i}function Zn(t,e,n){let r=null,i=null;if(e){e=et(t,e,n);const o=n(e.key,t);o===0?(r=e.left,i=e.right):o<0?(i=e.right,e.right=null,r=e):(r=e.left,e.left=null,i=e)}return{left:r,right:i}}function ao(t,e,n){return e===null?t:(t===null||(e=et(t.key,e,n),e.left=t),e)}function gn(t,e,n,r,i){if(t){r(`${e}${n?"└── ":"├── "}${i(t)}
33
+ `);const o=e+(n?" ":"│ ");t.left&&gn(t.left,o,!1,r,i),t.right&&gn(t.right,o,!0,r,i)}}class Ln{constructor(e=so){this._root=null,this._size=0,this._comparator=e}insert(e,n){return this._size++,this._root=an(e,n,this._root,this._comparator)}add(e,n){const r=new rt(e,n);this._root===null&&(r.left=r.right=null,this._size++,this._root=r);const i=this._comparator,o=et(e,this._root,i),s=i(e,o.key);return s===0?this._root=o:(s<0?(r.left=o.left,r.right=o,o.left=null):s>0&&(r.right=o.right,r.left=o,o.right=null),this._size++,this._root=r),this._root}remove(e){this._root=this._remove(e,this._root,this._comparator)}_remove(e,n,r){let i;return n===null?null:(n=et(e,n,r),r(e,n.key)===0?(n.left===null?i=n.right:(i=et(e,n.left,r),i.right=n.right),this._size--,i):n)}pop(){let e=this._root;if(e){for(;e.left;)e=e.left;return this._root=et(e.key,this._root,this._comparator),this._root=this._remove(e.key,this._root,this._comparator),{key:e.key,data:e.data}}return null}findStatic(e){let n=this._root;const r=this._comparator;for(;n;){const i=r(e,n.key);if(i===0)return n;i<0?n=n.left:n=n.right}return null}find(e){return this._root&&(this._root=et(e,this._root,this._comparator),this._comparator(e,this._root.key)!==0)?null:this._root}contains(e){let n=this._root;const r=this._comparator;for(;n;){const i=r(e,n.key);if(i===0)return!0;i<0?n=n.left:n=n.right}return!1}forEach(e,n){let r=this._root;const i=[];let o=!1;for(;!o;)r!==null?(i.push(r),r=r.left):i.length!==0?(r=i.pop(),e.call(n,r),r=r.right):o=!0;return this}range(e,n,r,i){const o=[],s=this._comparator;let a=this._root,l;for(;o.length!==0||a;)if(a)o.push(a),a=a.left;else{if(a=o.pop(),l=s(a.key,n),l>0)break;if(s(a.key,e)>=0&&r.call(i,a))return this;a=a.right}return this}keys(){const e=[];return this.forEach(({key:n})=>{e.push(n)}),e}values(){const e=[];return this.forEach(({data:n})=>{e.push(n)}),e}min(){return this._root?this.minNode(this._root).key:null}max(){return this._root?this.maxNode(this._root).key:null}minNode(e=this._root){if(e)for(;e.left;)e=e.left;return e}maxNode(e=this._root){if(e)for(;e.right;)e=e.right;return e}at(e){let n=this._root,r=!1,i=0;const o=[];for(;!r;)if(n)o.push(n),n=n.left;else if(o.length>0){if(n=o.pop(),i===e)return n;i++,n=n.right}else r=!0;return null}next(e){let n=this._root,r=null;if(e.right){for(r=e.right;r.left;)r=r.left;return r}const i=this._comparator;for(;n;){const o=i(e.key,n.key);if(o===0)break;o<0?(r=n,n=n.left):n=n.right}return r}prev(e){let n=this._root,r=null;if(e.left!==null){for(r=e.left;r.right;)r=r.right;return r}const i=this._comparator;for(;n;){const o=i(e.key,n.key);if(o===0)break;o<0?n=n.left:(r=n,n=n.right)}return r}clear(){return this._root=null,this._size=0,this}toList(){return co(this._root)}load(e,n=[],r=!1){let i=e.length;const o=this._comparator;if(r&&bn(e,n,0,i-1,o),this._root===null)this._root=pn(e,n,0,i),this._size=i;else{const s=uo(this.toList(),lo(e,n),o);i=this._size+i,this._root=yn({head:s},0,i)}return this}isEmpty(){return this._root===null}get size(){return this._size}get root(){return this._root}toString(e=n=>String(n.key)){const n=[];return gn(this._root,"",!0,r=>n.push(r),e),n.join("")}update(e,n,r){const i=this._comparator;let{left:o,right:s}=Zn(e,this._root,i);i(e,n)<0?s=an(n,r,s,i):o=an(n,r,o,i),this._root=ao(o,s,i)}split(e){return Zn(e,this._root,this._comparator)}*[Symbol.iterator](){let e=this._root;const n=[];let r=!1;for(;!r;)e!==null?(n.push(e),e=e.left):n.length!==0?(e=n.pop(),yield e,e=e.right):r=!0}}function pn(t,e,n,r){const i=r-n;if(i>0){const o=n+Math.floor(i/2),s=t[o],a=e[o],l=new rt(s,a);return l.left=pn(t,e,n,o),l.right=pn(t,e,o+1,r),l}return null}function lo(t,e){const n=new rt(null,null);let r=n;for(let i=0;i<t.length;i++)r=r.next=new rt(t[i],e[i]);return r.next=null,n.next}function co(t){let e=t;const n=[];let r=!1;const i=new rt(null,null);let o=i;for(;!r;)e?(n.push(e),e=e.left):n.length>0?(e=o=o.next=n.pop(),e=e.right):r=!0;return o.next=null,i.next}function yn(t,e,n){const r=n-e;if(r>0){const i=e+Math.floor(r/2),o=yn(t,e,i),s=t.head;return s.left=o,t.head=t.head.next,s.right=yn(t,i+1,n),s}return null}function uo(t,e,n){const r=new rt(null,null);let i=r,o=t,s=e;for(;o!==null&&s!==null;)n(o.key,s.key)<0?(i.next=o,o=o.next):(i.next=s,s=s.next),i=i.next;return o!==null?i.next=o:s!==null&&(i.next=s),r.next}function bn(t,e,n,r,i){if(n>=r)return;const o=t[n+r>>1];let s=n-1,a=r+1;for(;;){do s++;while(i(t[s],o)<0);do a--;while(i(t[a],o)>0);if(s>=a)break;let l=t[s];t[s]=t[a],t[a]=l,l=e[s],e[s]=e[a],e[a]=l}bn(t,e,n,a,i),bn(t,e,a+1,r,i)}const je=11102230246251565e-32,Be=134217729,fo=(3+8*je)*je;function ln(t,e,n,r,i){let o,s,a,l,u=e[0],f=r[0],c=0,h=0;f>u==f>-u?(o=u,u=e[++c]):(o=f,f=r[++h]);let d=0;if(c<t&&h<n)for(f>u==f>-u?(s=u+o,a=o-(s-u),u=e[++c]):(s=f+o,a=o-(s-f),f=r[++h]),o=s,a!==0&&(i[d++]=a);c<t&&h<n;)f>u==f>-u?(s=o+u,l=s-o,a=o-(s-l)+(u-l),u=e[++c]):(s=o+f,l=s-o,a=o-(s-l)+(f-l),f=r[++h]),o=s,a!==0&&(i[d++]=a);for(;c<t;)s=o+u,l=s-o,a=o-(s-l)+(u-l),u=e[++c],o=s,a!==0&&(i[d++]=a);for(;h<n;)s=o+f,l=s-o,a=o-(s-l)+(f-l),f=r[++h],o=s,a!==0&&(i[d++]=a);return(o!==0||d===0)&&(i[d++]=o),d}function ho(t,e){let n=e[0];for(let r=1;r<t;r++)n+=e[r];return n}function Ct(t){return new Float64Array(t)}const mo=(3+16*je)*je,go=(2+12*je)*je,po=(9+64*je)*je*je,lt=Ct(4),$n=Ct(8),Kn=Ct(12),jn=Ct(16),Ue=Ct(4);function yo(t,e,n,r,i,o,s){let a,l,u,f,c,h,d,m,g,b,y,w,A,S,C,M,P,O;const W=t-i,L=n-i,T=e-o,D=r-o;S=W*D,h=Be*W,d=h-(h-W),m=W-d,h=Be*D,g=h-(h-D),b=D-g,C=m*b-(S-d*g-m*g-d*b),M=T*L,h=Be*T,d=h-(h-T),m=T-d,h=Be*L,g=h-(h-L),b=L-g,P=m*b-(M-d*g-m*g-d*b),y=C-P,c=C-y,lt[0]=C-(y+c)+(c-P),w=S+y,c=w-S,A=S-(w-c)+(y-c),y=A-M,c=A-y,lt[1]=A-(y+c)+(c-M),O=w+y,c=O-w,lt[2]=w-(O-c)+(y-c),lt[3]=O;let I=ho(4,lt),Y=go*s;if(I>=Y||-I>=Y||(c=t-W,a=t-(W+c)+(c-i),c=n-L,u=n-(L+c)+(c-i),c=e-T,l=e-(T+c)+(c-o),c=r-D,f=r-(D+c)+(c-o),a===0&&l===0&&u===0&&f===0)||(Y=po*s+fo*Math.abs(I),I+=W*f+D*a-(T*u+L*l),I>=Y||-I>=Y))return I;S=a*D,h=Be*a,d=h-(h-a),m=a-d,h=Be*D,g=h-(h-D),b=D-g,C=m*b-(S-d*g-m*g-d*b),M=l*L,h=Be*l,d=h-(h-l),m=l-d,h=Be*L,g=h-(h-L),b=L-g,P=m*b-(M-d*g-m*g-d*b),y=C-P,c=C-y,Ue[0]=C-(y+c)+(c-P),w=S+y,c=w-S,A=S-(w-c)+(y-c),y=A-M,c=A-y,Ue[1]=A-(y+c)+(c-M),O=w+y,c=O-w,Ue[2]=w-(O-c)+(y-c),Ue[3]=O;const $=ln(4,lt,4,Ue,$n);S=W*f,h=Be*W,d=h-(h-W),m=W-d,h=Be*f,g=h-(h-f),b=f-g,C=m*b-(S-d*g-m*g-d*b),M=T*u,h=Be*T,d=h-(h-T),m=T-d,h=Be*u,g=h-(h-u),b=u-g,P=m*b-(M-d*g-m*g-d*b),y=C-P,c=C-y,Ue[0]=C-(y+c)+(c-P),w=S+y,c=w-S,A=S-(w-c)+(y-c),y=A-M,c=A-y,Ue[1]=A-(y+c)+(c-M),O=w+y,c=O-w,Ue[2]=w-(O-c)+(y-c),Ue[3]=O;const k=ln($,$n,4,Ue,Kn);S=a*f,h=Be*a,d=h-(h-a),m=a-d,h=Be*f,g=h-(h-f),b=f-g,C=m*b-(S-d*g-m*g-d*b),M=l*u,h=Be*l,d=h-(h-l),m=l-d,h=Be*u,g=h-(h-u),b=u-g,P=m*b-(M-d*g-m*g-d*b),y=C-P,c=C-y,Ue[0]=C-(y+c)+(c-P),w=S+y,c=w-S,A=S-(w-c)+(y-c),y=A-M,c=A-y,Ue[1]=A-(y+c)+(c-M),O=w+y,c=O-w,Ue[2]=w-(O-c)+(y-c),Ue[3]=O;const ae=ln(k,Kn,4,Ue,jn);return jn[ae-1]}function bo(t,e,n,r,i,o){const s=(e-o)*(n-i),a=(t-i)*(r-o),l=s-a,u=Math.abs(s+a);return Math.abs(l)>=mo*u?l:-yo(t,e,n,r,i,o,u)}const mt=(t,e)=>t.ll.x<=e.x&&e.x<=t.ur.x&&t.ll.y<=e.y&&e.y<=t.ur.y,xn=(t,e)=>{if(e.ur.x<t.ll.x||t.ur.x<e.ll.x||e.ur.y<t.ll.y||t.ur.y<e.ll.y)return null;const n=t.ll.x<e.ll.x?e.ll.x:t.ll.x,r=t.ur.x<e.ur.x?t.ur.x:e.ur.x,i=t.ll.y<e.ll.y?e.ll.y:t.ll.y,o=t.ur.y<e.ur.y?t.ur.y:e.ur.y;return{ll:{x:n,y:i},ur:{x:r,y:o}}};let tt=Number.EPSILON;tt===void 0&&(tt=Math.pow(2,-52));const xo=tt*tt,Qn=(t,e)=>{if(-tt<t&&t<tt&&-tt<e&&e<tt)return 0;const n=t-e;return n*n<xo*t*e?0:t<e?-1:1};class wo{constructor(){this.reset()}reset(){this.xRounder=new Jn,this.yRounder=new Jn}round(e,n){return{x:this.xRounder.round(e),y:this.yRounder.round(n)}}}class Jn{constructor(){this.tree=new Ln,this.round(0)}round(e){const n=this.tree.add(e),r=this.tree.prev(n);if(r!==null&&Qn(n.key,r.key)===0)return this.tree.remove(e),r.key;const i=this.tree.next(n);return i!==null&&Qn(n.key,i.key)===0?(this.tree.remove(e),i.key):e}}const xt=new wo,Ot=(t,e)=>t.x*e.y-t.y*e.x,si=(t,e)=>t.x*e.x+t.y*e.y,er=(t,e,n)=>{const r=bo(t.x,t.y,e.x,e.y,n.x,n.y);return r>0?-1:r<0?1:0},Gt=t=>Math.sqrt(si(t,t)),So=(t,e,n)=>{const r={x:e.x-t.x,y:e.y-t.y},i={x:n.x-t.x,y:n.y-t.y};return Ot(i,r)/Gt(i)/Gt(r)},Eo=(t,e,n)=>{const r={x:e.x-t.x,y:e.y-t.y},i={x:n.x-t.x,y:n.y-t.y};return si(i,r)/Gt(i)/Gt(r)},tr=(t,e,n)=>e.y===0?null:{x:t.x+e.x/e.y*(n-t.y),y:n},nr=(t,e,n)=>e.x===0?null:{x:n,y:t.y+e.y/e.x*(n-t.x)},Ro=(t,e,n,r)=>{if(e.x===0)return nr(n,r,t.x);if(r.x===0)return nr(t,e,n.x);if(e.y===0)return tr(n,r,t.y);if(r.y===0)return tr(t,e,n.y);const i=Ot(e,r);if(i==0)return null;const o={x:n.x-t.x,y:n.y-t.y},s=Ot(o,e)/i,a=Ot(o,r)/i,l=t.x+a*e.x,u=n.x+s*r.x,f=t.y+a*e.y,c=n.y+s*r.y,h=(l+u)/2,d=(f+c)/2;return{x:h,y:d}};class We{static compare(e,n){const r=We.comparePoints(e.point,n.point);return r!==0?r:(e.point!==n.point&&e.link(n),e.isLeft!==n.isLeft?e.isLeft?1:-1:nt.compare(e.segment,n.segment))}static comparePoints(e,n){return e.x<n.x?-1:e.x>n.x?1:e.y<n.y?-1:e.y>n.y?1:0}constructor(e,n){e.events===void 0?e.events=[this]:e.events.push(this),this.point=e,this.isLeft=n}link(e){if(e.point===this.point)throw new Error("Tried to link already linked events");const n=e.point.events;for(let r=0,i=n.length;r<i;r++){const o=n[r];this.point.events.push(o),o.point=this.point}this.checkForConsuming()}checkForConsuming(){const e=this.point.events.length;for(let n=0;n<e;n++){const r=this.point.events[n];if(r.segment.consumedBy===void 0)for(let i=n+1;i<e;i++){const o=this.point.events[i];o.consumedBy===void 0&&r.otherSE.point.events===o.otherSE.point.events&&r.segment.consume(o.segment)}}}getAvailableLinkedEvents(){const e=[];for(let n=0,r=this.point.events.length;n<r;n++){const i=this.point.events[n];i!==this&&!i.segment.ringOut&&i.segment.isInResult()&&e.push(i)}return e}getLeftmostComparator(e){const n=new Map,r=i=>{const o=i.otherSE;n.set(i,{sine:So(this.point,e.point,o.point),cosine:Eo(this.point,e.point,o.point)})};return(i,o)=>{n.has(i)||r(i),n.has(o)||r(o);const{sine:s,cosine:a}=n.get(i),{sine:l,cosine:u}=n.get(o);return s>=0&&l>=0?a<u?1:a>u?-1:0:s<0&&l<0?a<u?-1:a>u?1:0:l<s?-1:l>s?1:0}}}let Ao=0;class nt{static compare(e,n){const r=e.leftSE.point.x,i=n.leftSE.point.x,o=e.rightSE.point.x,s=n.rightSE.point.x;if(s<r)return 1;if(o<i)return-1;const a=e.leftSE.point.y,l=n.leftSE.point.y,u=e.rightSE.point.y,f=n.rightSE.point.y;if(r<i){if(l<a&&l<u)return 1;if(l>a&&l>u)return-1;const c=e.comparePoint(n.leftSE.point);if(c<0)return 1;if(c>0)return-1;const h=n.comparePoint(e.rightSE.point);return h!==0?h:-1}if(r>i){if(a<l&&a<f)return-1;if(a>l&&a>f)return 1;const c=n.comparePoint(e.leftSE.point);if(c!==0)return c;const h=e.comparePoint(n.rightSE.point);return h<0?1:h>0?-1:1}if(a<l)return-1;if(a>l)return 1;if(o<s){const c=n.comparePoint(e.rightSE.point);if(c!==0)return c}if(o>s){const c=e.comparePoint(n.rightSE.point);if(c<0)return 1;if(c>0)return-1}if(o!==s){const c=u-a,h=o-r,d=f-l,m=s-i;if(c>h&&d<m)return 1;if(c<h&&d>m)return-1}return o>s?1:o<s||u<f?-1:u>f?1:e.id<n.id?-1:e.id>n.id?1:0}constructor(e,n,r,i){this.id=++Ao,this.leftSE=e,e.segment=this,e.otherSE=n,this.rightSE=n,n.segment=this,n.otherSE=e,this.rings=r,this.windings=i}static fromRing(e,n,r){let i,o,s;const a=We.comparePoints(e,n);if(a<0)i=e,o=n,s=1;else if(a>0)i=n,o=e,s=-1;else throw new Error(`Tried to create degenerate segment at [${e.x}, ${e.y}]`);const l=new We(i,!0),u=new We(o,!1);return new nt(l,u,[r],[s])}replaceRightSE(e){this.rightSE=e,this.rightSE.segment=this,this.rightSE.otherSE=this.leftSE,this.leftSE.otherSE=this.rightSE}bbox(){const e=this.leftSE.point.y,n=this.rightSE.point.y;return{ll:{x:this.leftSE.point.x,y:e<n?e:n},ur:{x:this.rightSE.point.x,y:e>n?e:n}}}vector(){return{x:this.rightSE.point.x-this.leftSE.point.x,y:this.rightSE.point.y-this.leftSE.point.y}}isAnEndpoint(e){return e.x===this.leftSE.point.x&&e.y===this.leftSE.point.y||e.x===this.rightSE.point.x&&e.y===this.rightSE.point.y}comparePoint(e){if(this.isAnEndpoint(e))return 0;const n=this.leftSE.point,r=this.rightSE.point,i=this.vector();if(n.x===r.x)return e.x===n.x?0:e.x<n.x?1:-1;const o=(e.y-n.y)/i.y,s=n.x+o*i.x;if(e.x===s)return 0;const a=(e.x-n.x)/i.x,l=n.y+a*i.y;return e.y===l?0:e.y<l?-1:1}getIntersection(e){const n=this.bbox(),r=e.bbox(),i=xn(n,r);if(i===null)return null;const o=this.leftSE.point,s=this.rightSE.point,a=e.leftSE.point,l=e.rightSE.point,u=mt(n,a)&&this.comparePoint(a)===0,f=mt(r,o)&&e.comparePoint(o)===0,c=mt(n,l)&&this.comparePoint(l)===0,h=mt(r,s)&&e.comparePoint(s)===0;if(f&&u)return h&&!c?s:!h&&c?l:null;if(f)return c&&o.x===l.x&&o.y===l.y?null:o;if(u)return h&&s.x===a.x&&s.y===a.y?null:a;if(h&&c)return null;if(h)return s;if(c)return l;const d=Ro(o,this.vector(),a,e.vector());return d===null||!mt(i,d)?null:xt.round(d.x,d.y)}split(e){const n=[],r=e.events!==void 0,i=new We(e,!0),o=new We(e,!1),s=this.rightSE;this.replaceRightSE(o),n.push(o),n.push(i);const a=new nt(i,s,this.rings.slice(),this.windings.slice());return We.comparePoints(a.leftSE.point,a.rightSE.point)>0&&a.swapEvents(),We.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),r&&(i.checkForConsuming(),o.checkForConsuming()),n}swapEvents(){const e=this.rightSE;this.rightSE=this.leftSE,this.leftSE=e,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(let n=0,r=this.windings.length;n<r;n++)this.windings[n]*=-1}consume(e){let n=this,r=e;for(;n.consumedBy;)n=n.consumedBy;for(;r.consumedBy;)r=r.consumedBy;const i=nt.compare(n,r);if(i!==0){if(i>0){const o=n;n=r,r=o}if(n.prev===r){const o=n;n=r,r=o}for(let o=0,s=r.rings.length;o<s;o++){const a=r.rings[o],l=r.windings[o],u=n.rings.indexOf(a);u===-1?(n.rings.push(a),n.windings.push(l)):n.windings[u]+=l}r.rings=null,r.windings=null,r.consumedBy=n,r.leftSE.consumedBy=n.leftSE,r.rightSE.consumedBy=n.rightSE}}prevInResult(){return this._prevInResult!==void 0?this._prevInResult:(this.prev?this.prev.isInResult()?this._prevInResult=this.prev:this._prevInResult=this.prev.prevInResult():this._prevInResult=null,this._prevInResult)}beforeState(){if(this._beforeState!==void 0)return this._beforeState;if(!this.prev)this._beforeState={rings:[],windings:[],multiPolys:[]};else{const e=this.prev.consumedBy||this.prev;this._beforeState=e.afterState()}return this._beforeState}afterState(){if(this._afterState!==void 0)return this._afterState;const e=this.beforeState();this._afterState={rings:e.rings.slice(0),windings:e.windings.slice(0),multiPolys:[]};const n=this._afterState.rings,r=this._afterState.windings,i=this._afterState.multiPolys;for(let a=0,l=this.rings.length;a<l;a++){const u=this.rings[a],f=this.windings[a],c=n.indexOf(u);c===-1?(n.push(u),r.push(f)):r[c]+=f}const o=[],s=[];for(let a=0,l=n.length;a<l;a++){if(r[a]===0)continue;const u=n[a],f=u.poly;if(s.indexOf(f)===-1)if(u.isExterior)o.push(f);else{s.indexOf(f)===-1&&s.push(f);const c=o.indexOf(u.poly);c!==-1&&o.splice(c,1)}}for(let a=0,l=o.length;a<l;a++){const u=o[a].multiPoly;i.indexOf(u)===-1&&i.push(u)}return this._afterState}isInResult(){if(this.consumedBy)return!1;if(this._isInResult!==void 0)return this._isInResult;const e=this.beforeState().multiPolys,n=this.afterState().multiPolys;switch(qe.type){case"union":{const r=e.length===0,i=n.length===0;this._isInResult=r!==i;break}case"intersection":{let r,i;e.length<n.length?(r=e.length,i=n.length):(r=n.length,i=e.length),this._isInResult=i===qe.numMultiPolys&&r<i;break}case"xor":{const r=Math.abs(e.length-n.length);this._isInResult=r%2===1;break}case"difference":{const r=i=>i.length===1&&i[0].isSubject;this._isInResult=r(e)!==r(n);break}default:throw new Error(`Unrecognized operation type found ${qe.type}`)}return this._isInResult}}class rr{constructor(e,n,r){if(!Array.isArray(e)||e.length===0)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=n,this.isExterior=r,this.segments=[],typeof e[0][0]!="number"||typeof e[0][1]!="number")throw new Error("Input geometry is not a valid Polygon or MultiPolygon");const i=xt.round(e[0][0],e[0][1]);this.bbox={ll:{x:i.x,y:i.y},ur:{x:i.x,y:i.y}};let o=i;for(let s=1,a=e.length;s<a;s++){if(typeof e[s][0]!="number"||typeof e[s][1]!="number")throw new Error("Input geometry is not a valid Polygon or MultiPolygon");let l=xt.round(e[s][0],e[s][1]);l.x===o.x&&l.y===o.y||(this.segments.push(nt.fromRing(o,l,this)),l.x<this.bbox.ll.x&&(this.bbox.ll.x=l.x),l.y<this.bbox.ll.y&&(this.bbox.ll.y=l.y),l.x>this.bbox.ur.x&&(this.bbox.ur.x=l.x),l.y>this.bbox.ur.y&&(this.bbox.ur.y=l.y),o=l)}(i.x!==o.x||i.y!==o.y)&&this.segments.push(nt.fromRing(o,i,this))}getSweepEvents(){const e=[];for(let n=0,r=this.segments.length;n<r;n++){const i=this.segments[n];e.push(i.leftSE),e.push(i.rightSE)}return e}}class Co{constructor(e,n){if(!Array.isArray(e))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");this.exteriorRing=new rr(e[0],this,!0),this.bbox={ll:{x:this.exteriorRing.bbox.ll.x,y:this.exteriorRing.bbox.ll.y},ur:{x:this.exteriorRing.bbox.ur.x,y:this.exteriorRing.bbox.ur.y}},this.interiorRings=[];for(let r=1,i=e.length;r<i;r++){const o=new rr(e[r],this,!1);o.bbox.ll.x<this.bbox.ll.x&&(this.bbox.ll.x=o.bbox.ll.x),o.bbox.ll.y<this.bbox.ll.y&&(this.bbox.ll.y=o.bbox.ll.y),o.bbox.ur.x>this.bbox.ur.x&&(this.bbox.ur.x=o.bbox.ur.x),o.bbox.ur.y>this.bbox.ur.y&&(this.bbox.ur.y=o.bbox.ur.y),this.interiorRings.push(o)}this.multiPoly=n}getSweepEvents(){const e=this.exteriorRing.getSweepEvents();for(let n=0,r=this.interiorRings.length;n<r;n++){const i=this.interiorRings[n].getSweepEvents();for(let o=0,s=i.length;o<s;o++)e.push(i[o])}return e}}class ir{constructor(e,n){if(!Array.isArray(e))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");try{typeof e[0][0][0]=="number"&&(e=[e])}catch{}this.polys=[],this.bbox={ll:{x:Number.POSITIVE_INFINITY,y:Number.POSITIVE_INFINITY},ur:{x:Number.NEGATIVE_INFINITY,y:Number.NEGATIVE_INFINITY}};for(let r=0,i=e.length;r<i;r++){const o=new Co(e[r],this);o.bbox.ll.x<this.bbox.ll.x&&(this.bbox.ll.x=o.bbox.ll.x),o.bbox.ll.y<this.bbox.ll.y&&(this.bbox.ll.y=o.bbox.ll.y),o.bbox.ur.x>this.bbox.ur.x&&(this.bbox.ur.x=o.bbox.ur.x),o.bbox.ur.y>this.bbox.ur.y&&(this.bbox.ur.y=o.bbox.ur.y),this.polys.push(o)}this.isSubject=n}getSweepEvents(){const e=[];for(let n=0,r=this.polys.length;n<r;n++){const i=this.polys[n].getSweepEvents();for(let o=0,s=i.length;o<s;o++)e.push(i[o])}return e}}class qt{static factory(e){const n=[];for(let r=0,i=e.length;r<i;r++){const o=e[r];if(!o.isInResult()||o.ringOut)continue;let s=null,a=o.leftSE,l=o.rightSE;const u=[a],f=a.point,c=[];for(;s=a,a=l,u.push(a),a.point!==f;)for(;;){const h=a.getAvailableLinkedEvents();if(h.length===0){const g=u[0].point,b=u[u.length-1].point;throw new Error(`Unable to complete output ring starting at [${g.x}, ${g.y}]. Last matching segment found ends at [${b.x}, ${b.y}].`)}if(h.length===1){l=h[0].otherSE;break}let d=null;for(let g=0,b=c.length;g<b;g++)if(c[g].point===a.point){d=g;break}if(d!==null){const g=c.splice(d)[0],b=u.splice(g.index);b.unshift(b[0].otherSE),n.push(new qt(b.reverse()));continue}c.push({index:u.length,point:a.point});const m=a.getLeftmostComparator(s);l=h.sort(m)[0].otherSE;break}n.push(new qt(u))}return n}constructor(e){this.events=e;for(let n=0,r=e.length;n<r;n++)e[n].segment.ringOut=this;this.poly=null}getGeom(){let e=this.events[0].point;const n=[e];for(let u=1,f=this.events.length-1;u<f;u++){const c=this.events[u].point,h=this.events[u+1].point;er(c,e,h)!==0&&(n.push(c),e=c)}if(n.length===1)return null;const r=n[0],i=n[1];er(r,e,i)===0&&n.shift(),n.push(n[0]);const o=this.isExteriorRing()?1:-1,s=this.isExteriorRing()?0:n.length-1,a=this.isExteriorRing()?n.length:-1,l=[];for(let u=s;u!=a;u+=o)l.push([n[u].x,n[u].y]);return l}isExteriorRing(){if(this._isExteriorRing===void 0){const e=this.enclosingRing();this._isExteriorRing=e?!e.isExteriorRing():!0}return this._isExteriorRing}enclosingRing(){return this._enclosingRing===void 0&&(this._enclosingRing=this._calcEnclosingRing()),this._enclosingRing}_calcEnclosingRing(){let e=this.events[0];for(let i=1,o=this.events.length;i<o;i++){const s=this.events[i];We.compare(e,s)>0&&(e=s)}let n=e.segment.prevInResult(),r=n?n.prevInResult():null;for(;;){if(!n)return null;if(!r)return n.ringOut;if(r.ringOut!==n.ringOut)return r.ringOut.enclosingRing()!==n.ringOut?n.ringOut:n.ringOut.enclosingRing();n=r.prevInResult(),r=n?n.prevInResult():null}}}class or{constructor(e){this.exteriorRing=e,e.poly=this,this.interiorRings=[]}addInterior(e){this.interiorRings.push(e),e.poly=this}getGeom(){const e=[this.exteriorRing.getGeom()];if(e[0]===null)return null;for(let n=0,r=this.interiorRings.length;n<r;n++){const i=this.interiorRings[n].getGeom();i!==null&&e.push(i)}return e}}class Mo{constructor(e){this.rings=e,this.polys=this._composePolys(e)}getGeom(){const e=[];for(let n=0,r=this.polys.length;n<r;n++){const i=this.polys[n].getGeom();i!==null&&e.push(i)}return e}_composePolys(e){const n=[];for(let r=0,i=e.length;r<i;r++){const o=e[r];if(!o.poly)if(o.isExteriorRing())n.push(new or(o));else{const s=o.enclosingRing();s.poly||n.push(new or(s)),s.poly.addInterior(o)}}return n}}class Po{constructor(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:nt.compare;this.queue=e,this.tree=new Ln(n),this.segments=[]}process(e){const n=e.segment,r=[];if(e.consumedBy)return e.isLeft?this.queue.remove(e.otherSE):this.tree.remove(n),r;const i=e.isLeft?this.tree.add(n):this.tree.find(n);if(!i)throw new Error(`Unable to find segment #${n.id} [${n.leftSE.point.x}, ${n.leftSE.point.y}] -> [${n.rightSE.point.x}, ${n.rightSE.point.y}] in SweepLine tree.`);let o=i,s=i,a,l;for(;a===void 0;)o=this.tree.prev(o),o===null?a=null:o.key.consumedBy===void 0&&(a=o.key);for(;l===void 0;)s=this.tree.next(s),s===null?l=null:s.key.consumedBy===void 0&&(l=s.key);if(e.isLeft){let u=null;if(a){const c=a.getIntersection(n);if(c!==null&&(n.isAnEndpoint(c)||(u=c),!a.isAnEndpoint(c))){const h=this._splitSafely(a,c);for(let d=0,m=h.length;d<m;d++)r.push(h[d])}}let f=null;if(l){const c=l.getIntersection(n);if(c!==null&&(n.isAnEndpoint(c)||(f=c),!l.isAnEndpoint(c))){const h=this._splitSafely(l,c);for(let d=0,m=h.length;d<m;d++)r.push(h[d])}}if(u!==null||f!==null){let c=null;u===null?c=f:f===null?c=u:c=We.comparePoints(u,f)<=0?u:f,this.queue.remove(n.rightSE),r.push(n.rightSE);const h=n.split(c);for(let d=0,m=h.length;d<m;d++)r.push(h[d])}r.length>0?(this.tree.remove(n),r.push(e)):(this.segments.push(n),n.prev=a)}else{if(a&&l){const u=a.getIntersection(l);if(u!==null){if(!a.isAnEndpoint(u)){const f=this._splitSafely(a,u);for(let c=0,h=f.length;c<h;c++)r.push(f[c])}if(!l.isAnEndpoint(u)){const f=this._splitSafely(l,u);for(let c=0,h=f.length;c<h;c++)r.push(f[c])}}}this.tree.remove(n)}return r}_splitSafely(e,n){this.tree.remove(e);const r=e.rightSE;this.queue.remove(r);const i=e.split(n);return i.push(r),e.consumedBy===void 0&&this.tree.add(e),i}}const sr=typeof process<"u"&&process.env.POLYGON_CLIPPING_MAX_QUEUE_SIZE||1e6,vo=typeof process<"u"&&process.env.POLYGON_CLIPPING_MAX_SWEEPLINE_SEGMENTS||1e6;class To{run(e,n,r){qe.type=e,xt.reset();const i=[new ir(n,!0)];for(let c=0,h=r.length;c<h;c++)i.push(new ir(r[c],!1));if(qe.numMultiPolys=i.length,qe.type==="difference"){const c=i[0];let h=1;for(;h<i.length;)xn(i[h].bbox,c.bbox)!==null?h++:i.splice(h,1)}if(qe.type==="intersection")for(let c=0,h=i.length;c<h;c++){const d=i[c];for(let m=c+1,g=i.length;m<g;m++)if(xn(d.bbox,i[m].bbox)===null)return[]}const o=new Ln(We.compare);for(let c=0,h=i.length;c<h;c++){const d=i[c].getSweepEvents();for(let m=0,g=d.length;m<g;m++)if(o.insert(d[m]),o.size>sr)throw new Error("Infinite loop when putting segment endpoints in a priority queue (queue size too big).")}const s=new Po(o);let a=o.size,l=o.pop();for(;l;){const c=l.key;if(o.size===a){const d=c.segment;throw new Error(`Unable to pop() ${c.isLeft?"left":"right"} SweepEvent [${c.point.x}, ${c.point.y}] from segment #${d.id} [${d.leftSE.point.x}, ${d.leftSE.point.y}] -> [${d.rightSE.point.x}, ${d.rightSE.point.y}] from queue.`)}if(o.size>sr)throw new Error("Infinite loop when passing sweep line over endpoints (queue size too big).");if(s.segments.length>vo)throw new Error("Infinite loop when passing sweep line over endpoints (too many sweep line segments).");const h=s.process(c);for(let d=0,m=h.length;d<m;d++){const g=h[d];g.consumedBy===void 0&&o.insert(g)}a=o.size,l=o.pop()}xt.reset();const u=qt.factory(s.segments);return new Mo(u).getGeom()}}const qe=new To,Io=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return qe.run("union",t,n)},_o=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return qe.run("intersection",t,n)},Lo=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return qe.run("xor",t,n)},Fo=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return qe.run("difference",t,n)};var Do={union:Io,intersection:_o,xor:Lo,difference:Fo};function ht(t){return t==null?null:ai(t)||li(t)||No(t)?t:null}function ar(t){return typeof t=="number"&&Number.isFinite(t)}function Yt(t){return Array.isArray(t)&&t.length>=2&&ar(t[0])&&ar(t[1])}function ai(t){return Array.isArray(t)&&t.length>0&&t.every(e=>Yt(e))}function li(t){return Array.isArray(t)&&t.length>0&&t.every(e=>ai(e))}function No(t){return Array.isArray(t)&&t.length>0&&t.every(e=>li(e))}function Ye(t){if(!Array.isArray(t)||t.length<3)return[];const e=[];for(const i of t){if(!Array.isArray(i)||i.length<2)continue;const o=Number(i[0]),s=Number(i[1]);if(!Number.isFinite(o)||!Number.isFinite(s))continue;const a=e[e.length-1];a&&a[0]===o&&a[1]===s||e.push([o,s])}if(e.length<3)return[];const n=e[0],r=e[e.length-1];return(n[0]!==r[0]||n[1]!==r[1])&&e.push([n[0],n[1]]),e.length>=4?e:[]}function wt(t){if(!Array.isArray(t)||t.length<4)return 0;let e=0;for(let n=0;n<t.length-1;n+=1){const r=t[n],i=t[n+1];e+=r[0]*i[1]-i[0]*r[1]}return e*.5}function cn(t){if(!Array.isArray(t)||t.length===0)return[];const e=[];for(const o of t){const s=Ye(o);s.length>=4&&e.push(s)}if(e.length===0)return[];if(e.length===1)return[e[0]];let n=0,r=0;for(let o=0;o<e.length;o+=1){const s=Math.abs(wt(e[o]));s<=r||(r=s,n=o)}const i=[e[n]];for(let o=0;o<e.length;o+=1)o!==n&&i.push(e[o]);return i}function ci(t){if(!Array.isArray(t)||t.length===0)return[];const e=t[0];if(Yt(e)){const i=cn([t]);return i.length>0?[i]:[]}if(!Array.isArray(e)||e.length===0)return[];const n=e[0];if(Yt(n)){const i=cn(t);return i.length>0?[i]:[]}if(!Array.isArray(n)||n.length===0||!Yt(n[0]))return[];const r=[];for(const i of t){const o=cn(i);o.length>0&&r.push(o)}return r}function lr(t,e,n){let r=!1;for(let i=0,o=n.length-1;i<n.length;o=i,i+=1){const s=n[i][0],a=n[i][1],l=n[o][0],u=n[o][1];if(a===u||a>e==u>e)continue;t<(l-s)*(e-a)/(u-a)+s&&(r=!r)}return r}function dt(t){const e=[];for(const n of t??[]){const r=ci(n);for(const i of r){const o=i[0];if(!o||o.length<4)continue;let s=1/0,a=1/0,l=-1/0,u=-1/0;for(const[c,h]of o)c<s&&(s=c),c>l&&(l=c),h<a&&(a=h),h>u&&(u=h);if(!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(l)||!Number.isFinite(u))continue;let f=Math.abs(wt(o));for(let c=1;c<i.length;c+=1)f-=Math.abs(wt(i[c]));e.push({outer:o,holes:i.slice(1),minX:s,minY:a,maxX:l,maxY:u,area:Math.max(1e-6,f)})}}return e}function ui(t,e,n){if(t<n.minX||t>n.maxX||e<n.minY||e>n.maxY||!lr(t,e,n.outer))return!1;for(const r of n.holes)if(lr(t,e,r))return!1;return!0}function St(t,e,n){for(const r of n)if(ui(t,e,r))return!0;return!1}const Fn=[160,160,160,255];function F(t,e,n){return Math.max(e,Math.min(n,t))}function Dn(t,e,n){const r=Number(t),i=Number(e),o=Number(n);return!Number.isFinite(r)||r<=0?1:!Number.isFinite(i)||!Number.isFinite(o)?r:Math.pow(2,i-o)*r}function Bo(t,e,n){let i=100*Dn(t,e,n);if(Number(t)){let o="μm";return i>1e3&&(i/=1e3,o="mm"),`${i.toPrecision(3)} ${o}`}return`${Math.round(i*1e3)/1e3} pixels`}function we(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function ot(t){const e=t.fillModes instanceof Uint8Array?t.fillModes.length:Number.MAX_SAFE_INTEGER;return Math.max(0,Math.min(Math.floor(t.count??0),Math.floor((t.positions?.length??0)/2),t.paletteIndices?.length??0,e))}function wn(t,e){return!t&&!e?!0:!t||!e?!1:Math.abs((t.zoom??0)-(e.zoom??0))<1e-6&&Math.abs((t.offsetX??0)-(e.offsetX??0))<1e-6&&Math.abs((t.offsetY??0)-(e.offsetY??0))<1e-6&&Math.abs((t.rotationDeg??0)-(e.rotationDeg??0))<1e-6}function ko(t){const e=String(t??"").trim();if(!e)return"";if(/^bearer\s+/i.test(e)){const n=e.replace(/^bearer\s+/i,"").trim();return n?`Bearer ${n}`:""}return`Bearer ${e}`}function fi(t){const n=String(t??"").trim().match(/^#?([0-9a-fA-F]{6})$/);if(!n)return[...Fn];const r=Number.parseInt(n[1],16);return[r>>16&255,r>>8&255,r&255,255]}function Uo(t){const e=String(t?.classId??"").trim();return e||String(t?.className??"").trim()}function zo(t){const e=[[...Fn]],n=new Map;for(const i of t??[]){const o=Uo(i);!o||n.has(o)||(n.set(o,e.length),e.push(fi(i?.classColor)))}const r=new Uint8Array(e.length*4);for(let i=0;i<e.length;i+=1)r[i*4]=e[i][0],r[i*4+1]=e[i][1],r[i*4+2]=e[i][2],r[i*4+3]=e[i][3];return{colors:r,classToPaletteIndex:n}}const Oo=[6,4,2],Yo=64,Xo=.04,Wo=1,Vo=4,Ht=1e-6,Go=.1;function qo(t){if(!Array.isArray(t)||t.length===0)return[];const e=[];for(const n of t){if(!Array.isArray(n)||n.length<2)continue;const r=Number(n[0]),i=Number(n[1]);if(!Number.isFinite(r)||!Number.isFinite(i))continue;const o=e[e.length-1];o&&Math.abs(o[0]-r)<1e-9&&Math.abs(o[1]-i)<1e-9||e.push([r,i])}return e}function cr(t,e,n){if(e<=Ht||n<8)return[];const r=[];for(let i=0;i<=n;i+=1){const o=i/n*Math.PI*2;r.push([t[0]+Math.cos(o)*e,t[1]+Math.sin(o)*e])}return Ye(r)}function Ho(t,e,n,r){const i=e[0]-t[0],o=e[1]-t[1],s=Math.sqrt(i*i+o*o);if(!Number.isFinite(s)||s<=r)return[];const a=i/s,u=-(o/s),f=a,c=Math.max(Ht,n);return Ye([[t[0]+u*c,t[1]+f*c],[e[0]+u*c,e[1]+f*c],[e[0]-u*c,e[1]-f*c],[t[0]-u*c,t[1]-f*c]])}function ur(t,e){if(!t.length)return[];let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[a,l]of t)a<n&&(n=a),a>i&&(i=a),l<r&&(r=l),l>o&&(o=l);if(!Number.isFinite(n)||!Number.isFinite(r))return[];const s=Math.max(e,1);return Ye([[n-s,r-s],[i+s,r-s],[i+s,o+s],[n-s,o+s]])}function Tt(t,e){return Ye(e?t.map(([n,r])=>[F(n,e[0],e[2]),F(r,e[1],e[3])]):t)}function fr(t,e){return Number.isFinite(t)?Number(t.toFixed(e)):t}function Zo(t,e){if(!Array.isArray(t)||t.length===0)return[];const n=[];for(const r of t){if(!Array.isArray(r)||r.length<2)continue;const i=fr(Number(r[0]),e),o=fr(Number(r[1]),e);if(!Number.isFinite(i)||!Number.isFinite(o))continue;const s=n[n.length-1];(!s||s[0]!==i||s[1]!==o)&&n.push([i,o])}if(n.length>=2){const r=n[0],i=n[n.length-1];if(!r||!i)return[];(r[0]!==i[0]||r[1]!==i[1])&&n.push([r[0],r[1]])}return n.length>=4?n:[]}function $o(t,e){if(!Array.isArray(t)||t.length===0)return[];const n=t.map(r=>Zo(r,e)).filter(r=>r.length>=4);return n.length>0?n:[]}function Ko(t,e){const n=t.map(i=>$o(i,e)).filter(i=>i.length>0);if(n.length===0)return null;let r=[n[0]];try{for(let i=1;i<n.length;i+=1)if(r=Do.union(r,[n[i]]),!Array.isArray(r)||r.length===0)return null}catch(i){return console.error("buildBrushStrokePolygon union failed",e,i),null}return r.length>0?r:null}function jo(t){if(t.length===0)return null;for(const e of Oo){const n=Ko(t,e);if(n)return n}return null}function Qo(t){if(!Array.isArray(t)||t.length===0)return[];const e=[];for(const n of t){if(!Array.isArray(n)||n.length<2)continue;const r=Number(n[0]),i=Number(n[1]);!Number.isFinite(r)||!Number.isFinite(i)||e.push([r,i])}return Ye(e)}function Jo(t){let e=[],n=0;for(const r of t){if(!Array.isArray(r)||r.length===0)continue;const i=Qo(r[0]??[]);if(i.length<4)continue;const o=Math.abs(wt(i));o<=n||(n=o,e=i)}return e}function es(t,e=1e-9){const n=Ye(t);if(n.length<5)return n;const r=[n[0]];for(let i=1;i<n.length-1;i+=1){const o=r[r.length-1],s=n[i],a=n[i+1],l=(s[0]-o[0])*(a[1]-s[1])-(s[1]-o[1])*(a[0]-s[0]);Math.abs(l)<=e||r.push(s)}return r.push(r[0]),Ye(r)}function ts(t,e,n){const r=n[0]-e[0],i=n[1]-e[1],o=r*r+i*i;if(o<=1e-12){const c=t[0]-e[0],h=t[1]-e[1];return c*c+h*h}const s=F(((t[0]-e[0])*r+(t[1]-e[1])*i)/o,0,1),a=e[0]+r*s,l=e[1]+i*s,u=t[0]-a,f=t[1]-l;return u*u+f*f}function ns(t,e){if(t.length<=2||e<=0)return t.slice();const n=new Uint8Array(t.length);n[0]=1,n[t.length-1]=1;const r=e*e,i=[[0,t.length-1]];for(;i.length>0;){const s=i.pop();if(!s)break;const[a,l]=s;if(l-a<=1)continue;let u=0,f=-1;for(let c=a+1;c<l;c+=1){const h=ts(t[c],t[a],t[l]);h>u&&(u=h,f=c)}f>=0&&u>r&&(n[f]=1,i.push([a,f],[f,l]))}const o=[];for(let s=0;s<t.length;s+=1)n[s]&&o.push(t[s]);return o}function rs(t,e){const n=Ye(t);if(n.length<5||e<=0)return n;const r=n.slice(0,-1),i=ns(r,e);return i.length<3?n:Ye(i)}function is(t,e){let n=Ye(t);if(e<=0||n.length<5)return n;for(let r=0;r<e;r+=1){const i=n.slice(0,-1);if(i.length<3)break;const o=[];for(let s=0;s<i.length;s+=1){const a=i[s],l=i[(s+1)%i.length];o.push([a[0]*.75+l[0]*.25,a[1]*.75+l[1]*.25],[a[0]*.25+l[0]*.75,a[1]*.25+l[1]*.75])}n=Ye(o)}return n}function os(t,e){const n=qo(t),r=Math.max(Ht,Number(e.radius)||0);if(n.length===0||!Number.isFinite(r))return[];const i=Math.max(12,Math.floor(e.circleSides||Yo));if(n.length===1)return Tt(cr(n[0],r,i),e.clipBounds);const o=[],s=Math.max(Ht,r*Go);for(let h=0;h<n.length;h+=1){const d=n[h],m=cr(d,r,i);if(m.length>=4&&o.push([m]),h===0)continue;const g=Ho(n[h-1],d,r,s);g.length>=4&&o.push([g])}const a=jo(o),l=a?Jo(a):[];if(!l.length)return Tt(ur(n,r),e.clipBounds);const u=typeof e.simplifyTolerance=="number"&&Number.isFinite(e.simplifyTolerance)?Math.max(0,e.simplifyTolerance):Math.max(.25,r*Xo),f=typeof e.smoothingPasses=="number"&&Number.isFinite(e.smoothingPasses)?Math.round(F(e.smoothingPasses,0,Vo)):Wo,c=rs(is(es(l,1e-9),f),u);return c.length<4?Tt(ur(n,r),e.clipBounds):Tt(c,e.clipBounds)}function hr(){if(typeof window>"u")return 1;const t=window.devicePixelRatio||1;return Number.isFinite(t)&&t>0?t:1}function tn(t){if(typeof window>"u")return()=>{};let e=!0,n=hr(),r=null,i=null;const o=()=>{i?.(),i=null,r=null},s=()=>{o(),r=window.matchMedia(`(resolution: ${n}dppx)`);const f=()=>{a("match-media")};if(typeof r.addEventListener=="function"){r.addEventListener("change",f),i=()=>r?.removeEventListener("change",f);return}r.addListener(f),i=()=>r?.removeListener(f)},a=f=>{if(!e)return;const c=hr();if(Math.abs(c-n)<=1e-4)return;const h=n;n=c,s(),t({previousDpr:h,nextDpr:c,trigger:f})},l=()=>a("window-resize"),u=()=>a("visual-viewport-resize");return s(),window.addEventListener("resize",l),window.visualViewport?.addEventListener("resize",u),()=>{e=!1,o(),window.removeEventListener("resize",l),window.visualViewport?.removeEventListener("resize",u)}}const it=[],dr=[],$e={color:"#ff4d4f",width:2,lineDash:it,lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},hi={color:"#4cc9f0",width:2,lineDash:[10,8],lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},di="rgba(23, 23, 25, 0.1)",mi=6,Ve={fontFamily:"Pretendard, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:11,fontWeight:600,textColor:"#171719",backgroundColor:"#FFCC00",borderColor:"rgba(0, 0, 0, 0)",borderWidth:0,paddingX:8,paddingY:4,offsetY:10,borderRadius:4},Je={fontFamily:"Pretendard, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:13,fontWeight:500,textColor:"#FFFFFF",backgroundColor:"rgba(23, 23, 25, 0.5)",borderRadius:4,paddingX:6,paddingY:3},mr={x:16,y:-24},ss=20,gr=1e-6,pr="transparent",as=3,ls=2,gi=96,cs=1,yr=1e3,pi=2,yi=2,us=4096,fs=.2,hs=1.12,ds=.89,ms=32,gs="#000000",ps=.1,ys="#FFCF00",bs="#FF0000",xs=1.5,br=[2,2],ws=1,Ss=.25,Es=4,Rs=1,As=0,Cs=4,Ms=1.5;function Zt(t,e,n){return[F(t[0],0,e),F(t[1],0,n)]}function Nn(t){if(!Array.isArray(t)||t.length<2)return null;const e=Number(t[0]),n=Number(t[1]);return!Number.isFinite(e)||!Number.isFinite(n)?null:[e,n]}const He=Nn;function ze(t){return Ye(t)}function Xt(t){return Math.abs(wt(ze(t)))}function xr(t){if(!Array.isArray(t)||t.length===0)return[0,0,0,0];let e=1/0,n=1/0,r=-1/0,i=-1/0;for(const[o,s]of t)o<e&&(e=o),o>r&&(r=o),s<n&&(n=s),s>i&&(i=s);return[e,n,r,i]}function Et(t,e,n=!1){if(e.length!==0){t.moveTo(e[0][0],e[0][1]);for(let r=1;r<e.length;r+=1)t.lineTo(e[r][0],e[r][1]);n&&t.closePath()}}function ke(t,e,n,r=!1,i=!1,o="rgba(255, 77, 79, 0.16)"){e.length!==0&&(t.beginPath(),Et(t,e,r),i&&r&&(t.fillStyle=o,t.fill()),t.strokeStyle=n.color,t.lineWidth=n.width,t.lineJoin=n.lineJoin,t.lineCap=n.lineCap,t.shadowColor=n.shadowColor,t.shadowBlur=n.shadowBlur,t.shadowOffsetX=n.shadowOffsetX,t.shadowOffsetY=n.shadowOffsetY,t.setLineDash(n.lineDash),t.stroke(),t.setLineDash(it),t.shadowColor="rgba(0, 0, 0, 0)",t.shadowBlur=0,t.shadowOffsetX=0,t.shadowOffsetY=0)}function Bn(t){const e=Array.isArray(t?.lineDash)?t.lineDash.filter(s=>Number.isFinite(s)&&s>=0):it,n=typeof t?.width=="number"&&Number.isFinite(t.width)?Math.max(0,t.width):$e.width,r=typeof t?.shadowBlur=="number"&&Number.isFinite(t.shadowBlur)?Math.max(0,t.shadowBlur):$e.shadowBlur,i=typeof t?.shadowOffsetX=="number"&&Number.isFinite(t.shadowOffsetX)?t.shadowOffsetX:$e.shadowOffsetX,o=typeof t?.shadowOffsetY=="number"&&Number.isFinite(t.shadowOffsetY)?t.shadowOffsetY:$e.shadowOffsetY;return{color:t?.color||$e.color,width:n,lineDash:e.length?e:it,lineJoin:t?.lineJoin||$e.lineJoin,lineCap:t?.lineCap||$e.lineCap,shadowColor:t?.shadowColor||$e.shadowColor,shadowBlur:r,shadowOffsetX:i,shadowOffsetY:o}}function Ke(t,e){return e?Bn({color:e.color??t.color,width:e.width??t.width,lineDash:e.lineDash??t.lineDash,lineJoin:e.lineJoin??t.lineJoin,lineCap:e.lineCap??t.lineCap,shadowColor:e.shadowColor??t.shadowColor,shadowBlur:e.shadowBlur??t.shadowBlur,shadowOffsetX:e.shadowOffsetX??t.shadowOffsetX,shadowOffsetY:e.shadowOffsetY??t.shadowOffsetY}):t}function $t(t,e){return t==null||e===null||e===void 0?!1:String(t)===String(e)}function wr(t){return typeof t=="number"&&Number.isFinite(t)}function Ps(t){return Array.isArray(t)&&t.length>=2&&wr(t[0])&&wr(t[1])}function vs(t){return Array.isArray(t)&&t.length>=2&&t.every(e=>Ps(e))}function bi(t,e){if(!(!Array.isArray(t)||t.length===0)){if(vs(t)){e.push(t.map(([n,r])=>[n,r]));return}for(const n of t)bi(n,e)}}function Sr(t,e){const n=[];bi(t,n);const r=[];for(const i of n){if(i.length<2)continue;const o=e?ze(i):i;o.length>=(e?4:2)&&r.push(o)}return r}function yt(t,e){return typeof t!="number"||!Number.isFinite(t)||t<=0?e:t}function Ts(t,e){return typeof t!="number"||!Number.isFinite(t)?e:F(t,0,1)}function xi(t,e,n,r,i,o){const s=Math.max(0,Math.min(o,r*.5,i*.5));t.beginPath(),t.moveTo(e+s,n),t.lineTo(e+r-s,n),t.quadraticCurveTo(e+r,n,e+r,n+s),t.lineTo(e+r,n+i-s),t.quadraticCurveTo(e+r,n+i,e+r-s,n+i),t.lineTo(e+s,n+i),t.quadraticCurveTo(e,n+i,e,n+i-s),t.lineTo(e,n+s),t.quadraticCurveTo(e,n,e+s,n),t.closePath()}function Is(t){const e=t[0];return Array.isArray(e)&&Array.isArray(e[0])}function Kt(t,e,n){if(!t||!e)return[];if(n){const r=n.worldToScreen(t[0],t[1]),i=n.worldToScreen(e[0],e[1]);if(r&&i){const o=[[r[0],r[1]],[i[0],r[1]],[i[0],i[1]],[r[0],i[1]]],s=[];for(const a of o){const l=n.screenToWorld(a);if(!l)return Kt(t,e);s.push(l)}return ze(s)}}return ze([[t[0],t[1]],[e[0],t[1]],[e[0],e[1]],[t[0],e[1]]])}function Sn(t,e,n=gi){if(!t||!e)return[];const r=(t[0]+e[0])*.5,i=(t[1]+e[1])*.5,o=Math.hypot(e[0]-t[0],e[1]-t[1])*.5;if(o<1)return[];const s=[];for(let a=0;a<=n;a+=1){const l=a/n*Math.PI*2;s.push([r+Math.cos(l)*o,i+Math.sin(l)*o])}return ze(s)}function jt(t){const e=ci(ht(t));if(e.length===0)return[];const n=[];for(const r of e){const i=r[0];if(!i||i.length<4)continue;const o=i.map(([a,l])=>[a,l]),s=[];for(let a=1;a<r.length;a+=1){const l=r[a];!l||l.length<4||s.push(l.map(([u,f])=>[u,f]))}n.push({outer:o,holes:s})}return n}function _s(t){if(!Array.isArray(t))return br;const e=t.filter(n=>Number.isFinite(n)&&n>=0);return e.length>0?e:br}function Ls(t){return typeof t!="number"||!Number.isFinite(t)?ws:F(t,Ss,Es)}function Fs(t){return typeof t!="number"||!Number.isFinite(t)?Rs:Math.round(F(t,As,Cs))}function Ds(t){const e=yt(t?.radius,ms),n=yt(t?.cursorLineWidth,xs),r=Ls(t?.edgeDetail),i=Fs(t?.edgeSmoothing);return{radius:e,edgeDetail:r,edgeSmoothing:i,clickSelectRoi:t?.clickSelectRoi===!0,fillColor:t?.fillColor||gs,fillOpacity:Ts(t?.fillOpacity,ps),cursorColor:t?.cursorColor||ys,cursorActiveColor:t?.cursorActiveColor||bs,cursorLineWidth:n,cursorLineDash:_s(t?.cursorLineDash)}}function Ns(t,e,n){if(!e.isDrawing||e.screenPoints.length===0)return;const r=e.screenPoints;if(r.length===0)return;const i=n.radius;if(!(!Number.isFinite(i)||i<=0)){if(t.save(),t.globalAlpha=n.fillOpacity,t.fillStyle=n.fillColor,t.strokeStyle=n.fillColor,t.lineCap="round",t.lineJoin="round",t.lineWidth=i*2,r.length===1)t.beginPath(),t.arc(r[0][0],r[0][1],i,0,Math.PI*2),t.fill();else{t.beginPath(),t.moveTo(r[0][0],r[0][1]);for(let o=1;o<r.length;o+=1)t.lineTo(r[o][0],r[o][1]);t.stroke()}t.restore()}}function Bs(t,e,n,r){const i=e.cursor;if(!i)return;const o=e.cursorScreen??He(n?.worldToScreen(i[0],i[1])??[]);if(!o)return;const s=r.radius;!Number.isFinite(s)||s<=0||(t.save(),t.beginPath(),t.arc(o[0],o[1],s,0,Math.PI*2),t.strokeStyle=e.isDrawing?r.cursorActiveColor:r.cursorColor,t.lineWidth=r.cursorLineWidth,t.setLineDash(r.cursorLineDash),t.stroke(),t.setLineDash(it),t.restore())}const ks=.58,Us=4096,zs=.5;let It=null;const _t=new Map;function Os(){if(It)return It;if(typeof document>"u")return null;const e=document.createElement("canvas").getContext("2d");return e?(It=e,It):null}function kn(t,e){const n=`${e.fontWeight}|${e.fontSize}|${e.fontFamily}|${t}`,r=_t.get(n);if(r!==void 0)return r;const i=t.length*e.fontSize*ks,o=Os();let s=i;if(o){o.font=`${e.fontWeight} ${e.fontSize}px ${e.fontFamily}`;const a=o.measureText(t).width;Number.isFinite(a)&&a>=0&&(s=a)}return _t.size>Us&&_t.clear(),_t.set(n,s),s}function Ys(t,e="top-center"){if(!t.length)return null;let n=1/0;for(const o of t)o[1]<n&&(n=o[1]);if(!Number.isFinite(n))return null;let r=1/0,i=-1/0;for(const o of t)Math.abs(o[1]-n)>zs||(o[0]<r&&(r=o[0]),o[0]>i&&(i=o[0]));return!Number.isFinite(r)||!Number.isFinite(i)?null:e==="top-center"?[(r+i)*.5,n]:[r,n]}function Un(t,e,n="top-center"){let r=null;for(const i of t){const o=e(i.outer);if(o.length===0)continue;const s=Ys(o,n);s&&(!r||s[1]<r[1]||s[1]===r[1]&&s[0]<r[0])&&(r=s)}return r}function zn(t){const e=typeof t?.paddingX=="number"&&Number.isFinite(t.paddingX)?Math.max(0,t.paddingX):Ve.paddingX,n=typeof t?.paddingY=="number"&&Number.isFinite(t.paddingY)?Math.max(0,t.paddingY):Ve.paddingY,r=typeof t?.fontSize=="number"&&Number.isFinite(t.fontSize)?Math.max(8,t.fontSize):Ve.fontSize,i=typeof t?.borderWidth=="number"&&Number.isFinite(t.borderWidth)?Math.max(0,t.borderWidth):Ve.borderWidth,o=typeof t?.offsetY=="number"&&Number.isFinite(t.offsetY)?t.offsetY:Ve.offsetY,s=typeof t?.borderRadius=="number"&&Number.isFinite(t.borderRadius)?Math.max(0,t.borderRadius):Ve.borderRadius;return{fontFamily:t?.fontFamily||Ve.fontFamily,fontSize:r,fontWeight:t?.fontWeight||Ve.fontWeight,textColor:t?.textColor||Ve.textColor,backgroundColor:t?.backgroundColor||Ve.backgroundColor,borderColor:t?.borderColor||Ve.borderColor,borderWidth:i,paddingX:e,paddingY:n,offsetY:o,borderRadius:s}}function On(t,e){return e?zn({fontFamily:e.fontFamily??t.fontFamily,fontSize:e.fontSize??t.fontSize,fontWeight:e.fontWeight??t.fontWeight,textColor:e.textColor??t.textColor,backgroundColor:e.backgroundColor??t.backgroundColor,borderColor:e.borderColor??t.borderColor,borderWidth:e.borderWidth??t.borderWidth,paddingX:e.paddingX??t.paddingX,paddingY:e.paddingY??t.paddingY,offsetY:e.offsetY??t.offsetY,borderRadius:e.borderRadius??t.borderRadius}):t}function Yn(t,e,n,r){if(!t||!n)return 0;const i=Number(n.minZoom),o=Number(n.maxZoom);if(!Number.isFinite(i)||!Number.isFinite(o)||o-i<=gr||!Number.isFinite(e))return 0;let s=o;r!=null&&Number.isFinite(r)&&(s=F(r,i,o));const a=Math.max(gr,Math.abs(s)*1e-9);return e>=s-a?ss:0}function Xs(t){const e=typeof t?.fontSize=="number"&&Number.isFinite(t.fontSize)?Math.max(8,t.fontSize):Je.fontSize,n=typeof t?.borderRadius=="number"&&Number.isFinite(t.borderRadius)?Math.max(0,t.borderRadius):Je.borderRadius,r=typeof t?.paddingX=="number"&&Number.isFinite(t.paddingX)?Math.max(0,t.paddingX):Je.paddingX,i=typeof t?.paddingY=="number"&&Number.isFinite(t.paddingY)?Math.max(0,t.paddingY):Je.paddingY;return{fontFamily:t?.fontFamily||Je.fontFamily,fontSize:e,fontWeight:t?.fontWeight||Je.fontWeight,textColor:t?.textColor||Je.textColor,backgroundColor:t?.backgroundColor||Je.backgroundColor,borderRadius:n,paddingX:r,paddingY:i}}function Ws(t){const e=typeof t?.x=="number"&&Number.isFinite(t.x)?t.x:mr.x,n=typeof t?.y=="number"&&Number.isFinite(t.y)?t.y:mr.y;return{x:e,y:n}}function Vs(t){return Number.isFinite(t)?`${Math.max(0,t).toFixed(3)} mm²`:"0.000 mm²"}function Gs(t){const e=typeof t?.format=="function"?t.format:Vs,n=Ws(t?.cursorOffset);return{enabled:t?.enabled===!0,format:e,style:Xs(t?.style),cursorOffsetX:n.x,cursorOffsetY:n.y}}function wi(t,e,n,r,i,o,s=!0){const a=e.trim();if(!a)return;t.save(),t.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,t.textAlign="center",t.textBaseline="middle";const u=kn(a,o)+o.paddingX*2,f=o.fontSize+o.paddingY*2,c=n[0],h=n[1]-o.offsetY,d=s?F(c,u*.5+1,r-u*.5-1):c,m=s?F(h,f*.5+1,i-f*.5-1):h,g=d-u*.5,b=m-f*.5;t.fillStyle=o.backgroundColor,t.strokeStyle=o.borderColor,t.lineWidth=o.borderWidth,xi(t,g,b,u,f,o.borderRadius),t.fill(),o.borderWidth>0&&t.stroke(),t.fillStyle=o.textColor,t.fillText(a,d,m+.5),t.restore()}function qs(t,e,n,r,i,o,s,a){const l=e.trim();if(!l)return;t.save(),t.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,t.textAlign="center",t.textBaseline="middle";const f=kn(l,o)+o.paddingX*2,c=o.fontSize+o.paddingY*2,h=F(n[0]+s,f*.5+1,r-f*.5-1),d=F(n[1]+a,c*.5+1,i-c*.5-1),m=h-f*.5,g=d-c*.5;t.fillStyle=o.backgroundColor,xi(t,m,g,f,c,o.borderRadius),t.fill(),t.fillStyle=o.textColor,t.fillText(l,h,d+.5),t.restore()}function Hs(t,e,n,r){if(!(e.length<4||n.length===0)){t.save(),t.beginPath(),Et(t,e,!0);for(const i of n)i.length<4||Et(t,i,!0);t.fillStyle=r,t.fill("evenodd"),t.restore()}}function Si(t){const{ctx:e,overlayShapes:n,imageOuterRing:r,worldToScreenPoints:i,baseStrokeStyle:o,onInvertedFillDebug:s}=t,a=!!globalThis.__OPEN_PLANT_DEBUG_OVERLAY__;for(let l=0;l<n.length;l+=1){const u=n[l];if(!u?.coordinates?.length||u.visible===!1)continue;const f=u.closed??Is(u.coordinates),c=Sr(u.coordinates,f);if(u.invertedFill?.fillColor){const d=[],m=Sr(u.coordinates,!0);for(const g of m){const b=i(g);b.length>=4&&d.push(b)}a&&s&&s({id:u.id??l,outerRingPoints:r.length,sourceRingCount:m.length,holeRingCount:d.length,fillColor:u.invertedFill.fillColor}),Hs(e,r,d,u.invertedFill.fillColor)}if(c.length===0)continue;const h=Ke(o,u.stroke??u.strokeStyle);for(const d of c){const m=i(d);m.length<2||ke(e,m,h,f,u.fill??!1)}}}function Lt(t){return typeof t=="string"&&(t==="stamp-rectangle"||t==="stamp-circle"||t==="stamp-rectangle-4096px"||t==="stamp-rectangle-2mm2"||t==="stamp-circle-2mm2"||t==="stamp-circle-hpf-0.2mm2")}function Zs(t){return{rectangleAreaMm2:yt(t?.rectangleAreaMm2,pi),circleAreaMm2:yt(t?.circleAreaMm2,yi),rectanglePixelSize:yt(t?.rectanglePixelSize,us)}}const Er=1e3;function $s(t){return t*Er*Er}function Rr(t,e,n){if(!t||!Number.isFinite(e)||e<=0)return[];if(n){const r=n.worldToScreen(t[0],t[1]),i=n.worldToScreen(t[0]+e,t[1]);if(r&&i){const o=Math.hypot(i[0]-r[0],i[1]-r[1]),s=[[r[0]-o,r[1]-o],[r[0]+o,r[1]-o],[r[0]+o,r[1]+o],[r[0]-o,r[1]+o]],a=[];for(const l of s){const u=n.screenToWorld(l);if(!u)throw new Error("Failed to create rectangle");a.push(u)}return ze(a)}}return ze([[t[0]-e,t[1]-e],[t[0]+e,t[1]-e],[t[0]+e,t[1]+e],[t[0]-e,t[1]+e]])}function Ks(t,e,n=gi){if(!t||!Number.isFinite(e)||e<=0)return[];const r=[];for(let i=0;i<=n;i+=1){const o=i/n*Math.PI*2;r.push([t[0]+Math.cos(o)*e,t[1]+Math.sin(o)*e])}return ze(r)}function js(t){const{stampTool:e,center:n,resolvedStampOptions:r,imageWidth:i,imageHeight:o,micronsToWorldPixels:s,getRectangleProjection:a}=t;if(!n)return[];if(e==="stamp-rectangle-4096px"){const c=r.rectanglePixelSize*.5;return Rr(n,c,a()).map(h=>Zt(h,i,o))}let l=0;if(e==="stamp-rectangle"||e==="stamp-rectangle-2mm2"?l=e==="stamp-rectangle-2mm2"?pi:r.rectangleAreaMm2:(e==="stamp-circle"||e==="stamp-circle-2mm2"||e==="stamp-circle-hpf-0.2mm2")&&(l=e==="stamp-circle-hpf-0.2mm2"?fs:e==="stamp-circle-2mm2"?yi:r.circleAreaMm2),!Number.isFinite(l)||l<=0)return[];const u=$s(l);let f=[];if(e==="stamp-rectangle"||e==="stamp-rectangle-2mm2"){const c=s(Math.sqrt(u)*.5);f=Rr(n,c,a())}else if(e==="stamp-circle"||e==="stamp-circle-2mm2"||e==="stamp-circle-hpf-0.2mm2"){const c=s(Math.sqrt(u/Math.PI));f=Ks(n,c)}return f.length?f.map(c=>Zt(c,i,o)):[]}function Qs(t){return{color:di,width:mi,lineDash:it,lineJoin:t.lineJoin,lineCap:t.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function Js(t){if(typeof t!="string")return pr;const e=t.trim();return e.length>0?e:pr}function Ar(t){return Array.isArray(t)&&t.length>=4&&Xt(t)>cs}function Ei({tool:t,imageWidth:e,imageHeight:n,imageMpp:r,imageZoom:i,stampOptions:o,brushOptions:s,projectorRef:a,onBrushTap:l,onDrawComplete:u,onPatchComplete:f,enabled:c,viewStateSignal:h,persistedRegions:d,patchRegions:m,persistedPolygons:g,drawFillColor:b,regionStrokeStyle:y,regionStrokeHoverStyle:w,regionStrokeActiveStyle:A,patchStrokeStyle:S,resolveRegionStrokeStyle:C,resolveRegionLabelStyle:M,overlayShapes:P,hoveredRegionId:O=null,activeRegionId:W=null,regionLabelStyle:L,drawAreaTooltip:T,autoLiftRegionLabelAtMaxZoom:D=!1,regionLabelAnchor:I="top-center",clampRegionLabelToViewport:Y=!0,regionLabelAutoLiftOffsetPx:$,invalidateRef:k,className:ae,style:he}){const J=p.useRef(null),ve=p.useRef(!1),Ce=p.useRef(new Map),N=p.useRef(t),v=p.useRef({isDrawing:!1,pointerId:null,start:null,current:null,cursor:null,cursorScreen:null,points:[],screenPoints:[],stampCenter:null}),z=c??t!=="cursor",ie=p.useMemo(()=>d&&d.length>0?d:!g||g.length===0?dr:g.map((x,R)=>({id:R,coordinates:x})),[d,g]),H=p.useMemo(()=>m??dr,[m]),ge=p.useMemo(()=>{const x=[];for(let R=0;R<ie.length;R+=1){const _=ie[R],B=jt(_.coordinates);B.length!==0&&x.push({region:_,regionIndex:R,regionKey:_.id??R,polygons:B})}return x},[ie]),le=p.useMemo(()=>{const x=[];for(let R=0;R<H.length;R+=1){const _=H[R],B=jt(_.coordinates);B.length!==0&&x.push({region:_,regionIndex:R,regionKey:_.id??R,polygons:B})}return x},[H]),ne=p.useMemo(()=>Bn(y),[y]),_e=p.useMemo(()=>Ke(ne,w),[ne,w]),ue=p.useMemo(()=>Ke(ne,A),[ne,A]),pe=p.useMemo(()=>Ke(hi,S),[S]),de=p.useMemo(()=>Js(b),[b]),re=p.useMemo(()=>zn(L),[L]),oe=p.useMemo(()=>Gs(T),[T]),ce=p.useMemo(()=>Zs(o),[o]),q=p.useMemo(()=>Ds(s),[s]),Pe=p.useMemo(()=>({position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",touchAction:"none",pointerEvents:z?"auto":"none",cursor:z?t==="brush"?"none":"crosshair":"default",...he}),[z,t,he]),Ee=p.useCallback(()=>{const x=J.current;if(!x)return;const R=x.getBoundingClientRect(),_=Math.max(1,window.devicePixelRatio||1),B=Math.max(1,Math.round(R.width*_)),G=Math.max(1,Math.round(R.height*_));(x.width!==B||x.height!==G)&&(x.width=B,x.height=G)},[z,t]),ye=p.useCallback(x=>{const R=a.current;if(!R||x.length===0)return[];const _=new Array(x.length);for(let B=0;B<x.length;B+=1){const G=He(R.worldToScreen(x[B][0],x[B][1]));if(!G)return[];_[B]=G}return _},[a]),V=p.useCallback(x=>{const R=a.current,_=J.current;if(!R||!_)return null;const B=_.getBoundingClientRect(),G=He(R.screenToWorld(B.left+x[0],B.top+x[1]));return G?Zt(G,e,n):null},[a,e,n]),K=p.useCallback(()=>{const x=a.current,R=x?.getViewState?.().rotationDeg??0;if(!(Math.abs(R%360)<.01||!x))return{worldToScreen:(_,B)=>He(x.worldToScreen(_,B)),screenToWorld:V}},[a,V]),fe=p.useCallback(x=>{if(!Number.isFinite(x)||x<=0)return 0;const R=typeof r=="number"&&Number.isFinite(r)&&r>0?r:1,_=typeof i=="number"&&Number.isFinite(i)?i:0,B=a.current?.getViewState?.().zoom,G=typeof B=="number"&&Number.isFinite(B)&&B>0?B:1,me=_+Math.log2(G),se=Math.max(1e-9,Dn(R,_,me));return x/se/G},[r,i,a]),te=p.useCallback((x,R)=>js({stampTool:x,center:R,resolvedStampOptions:ce,imageWidth:e,imageHeight:n,micronsToWorldPixels:fe,getRectangleProjection:K}),[fe,e,n,ce,K]),j=p.useCallback(()=>{const x=v.current;return Lt(t)?te(t,x.stampCenter):t==="brush"?[]:x.isDrawing?t==="freehand"?x.points:t==="rectangle"?Kt(x.start,x.current,K()):t==="circular"?Sn(x.start,x.current):[]:[]},[t,te,K]),Re=p.useCallback(()=>{Ee();const x=J.current;if(!x)return;const R=x.getContext("2d");if(!R)return;const _=Math.max(1,window.devicePixelRatio||1),B=x.width/_,G=x.height/_;if(R.setTransform(1,0,0,1,0,0),R.clearRect(0,0,x.width,x.height),R.setTransform(_,0,0,_,0,0),ge.length>0)for(const se of ge){const{region:xe,polygons:Me,regionIndex:Ie,regionKey:Ne}=se,at=$t(W,Ne)?"active":$t(O,Ne)?"hover":"default";let Qe=at==="active"?ue:at==="hover"?_e:ne;if(C){const vt=C({region:xe,regionId:Ne,regionIndex:Ie,state:at});Qe=Ke(Qe,vt||void 0)}const Pt=at==="default"?null:Qs(Qe);for(const vt of Me){const rn=ye(vt.outer);rn.length>=4&&(Pt&&ke(R,rn,Pt,!0,!1),ke(R,rn,Qe,!0,!1));for(const eo of vt.holes){const on=ye(eo);on.length>=4&&(Pt&&ke(R,on,Pt,!0,!1),ke(R,on,Qe,!0,!1))}}}if(le.length>0)for(const se of le)for(const xe of se.polygons){const Me=ye(xe.outer);Me.length>=4&&ke(R,Me,pe,!0,!1);for(const Ie of xe.holes){const Ne=ye(Ie);Ne.length>=4&&ke(R,Ne,pe,!0,!1)}}if(Array.isArray(P)&&P.length>0){const se=ye(ze([[0,0],[e,0],[e,n],[0,n]]));Si({ctx:R,overlayShapes:P,imageOuterRing:se,worldToScreenPoints:ye,baseStrokeStyle:ne,onInvertedFillDebug:globalThis.__OPEN_PLANT_DEBUG_OVERLAY__?xe=>{const Me=String(xe.id),Ie=`${xe.outerRingPoints}|${xe.sourceRingCount}|${xe.holeRingCount}|${xe.fillColor}`;Ce.current.get(Me)!==Ie&&(Ce.current.set(Me,Ie),console.debug("[open-plant] invertedFill",xe))}:void 0})}const me=j();if(z){if(t==="brush")Ns(R,v.current,q),Bs(R,v.current,a.current,q);else if(me.length>0)if(t==="freehand"){const se=ye(me);se.length>=2&&ke(R,se,ne,!1,!1),se.length>=3&&ke(R,ye(ze(me)),ne,!0,!0,de)}else{const se=ye(me);se.length>=4&&ke(R,se,ne,!0,!0,de)}}if(ge.length>0){const se=Math.max(1e-6,a.current?.getViewState?.().zoom??1),xe=typeof $=="number"&&Number.isFinite($)?Math.max(0,$):Yn(D,se,a.current?.getZoomRange?.(),a.current?.getRegionLabelAutoLiftCapZoom?.());for(const Me of ge){if(!Me.region.label)continue;const Ie=Un(Me.polygons,ye,I);if(!Ie)continue;let Ne=On(re,M?.({region:Me.region,regionId:Me.regionKey,regionIndex:Me.regionIndex,zoom:se}));xe>0&&(Ne={...Ne,offsetY:Ne.offsetY+xe}),wi(R,Me.region.label,Ie,B,G,Ne,Y)}}if(oe.enabled&&z&&(t==="freehand"||t==="rectangle"||t==="circular")){const se=v.current;if(se.isDrawing){const xe=t==="freehand"?ze(me):me;if(xe.length>=4){const Me=Xt(xe),Ie=typeof r=="number"&&Number.isFinite(r)&&r>0?r:0,Ne=Ie>0?Me*Ie*Ie/(yr*yr):0,at=oe.format(Ne),Qe=se.cursorScreen??(se.current?He(a.current?.worldToScreen(se.current[0],se.current[1])??[]):null);Qe&&qs(R,at,Qe,B,G,oe.style,oe.cursorOffsetX,oe.cursorOffsetY)}}}},[z,t,j,Ee,ye,e,n,a,ge,P,O,W,ne,_e,ue,de,le,pe,C,M,re,oe,D,I,Y,$,r,q]),X=p.useCallback(()=>{ve.current||(ve.current=!0,requestAnimationFrame(()=>{ve.current=!1,Re()}))},[Re]),Te=p.useCallback((x=!1)=>{const R=v.current,_=J.current;_&&R.pointerId!==null&&_.hasPointerCapture(R.pointerId)&&_.releasePointerCapture(R.pointerId),R.isDrawing=!1,R.pointerId=null,R.start=null,R.current=null,R.points=[],R.screenPoints=[],R.stampCenter=null,x||(R.cursor=null,R.cursorScreen=null)},[]),Fe=p.useCallback(x=>{const R=a.current;if(!R||e<=0||n<=0)return null;const _=He(R.screenToWorld(x.clientX,x.clientY));return _?Zt(_,e,n):null},[a,e,n]),U=p.useCallback(x=>{const R=J.current;if(!R)return null;const _=R.getBoundingClientRect(),B=F(x.clientX-_.left,0,_.width),G=F(x.clientY-_.top,0,_.height);return!Number.isFinite(B)||!Number.isFinite(G)?null:[B,G]},[]),Z=p.useCallback(()=>{const x=v.current;if(!x.isDrawing){Te(!0),X();return}let R=[];if(t==="freehand")x.points.length>=as&&(R=ze(x.points));else if(t==="rectangle")R=Kt(x.start,x.current,K());else if(t==="circular")R=Sn(x.start,x.current);else if(t==="brush"){const _=x.points[x.points.length-1]??x.current??x.start;if(q.clickSelectRoi&&_&&x.points.length<=1&&l?.(_)){Te(!0),X();return}const B=Math.max(.25,q.edgeDetail),G=x.screenPoints.length>0?x.screenPoints:ye(x.points),me=Math.max(.5,q.radius*.04/B),se=os(G,{radius:q.radius,circleSides:Math.max(16,Math.round(32*B)),simplifyTolerance:me,smoothingPasses:q.edgeSmoothing}),xe=[];for(const Me of se){const Ie=V(Me);Ie&&xe.push(Ie)}R=ze(xe)}(t==="freehand"||t==="rectangle"||t==="circular"||t==="brush")&&Ar(R)&&u&&u({tool:t,intent:t==="brush"?"brush":"roi",coordinates:R,bbox:xr(R),areaPx:Xt(R)}),Te(!0),X()},[t,u,Te,X,ye,V,K,q.radius,q.edgeDetail,q.edgeSmoothing,q.clickSelectRoi,l]),Q=p.useCallback((x,R)=>{const _=te(x,R);if(!Ar(_))return;const B=x==="stamp-rectangle-4096px"?"patch":"roi",G={tool:x,intent:B,coordinates:_,bbox:xr(_),areaPx:Xt(_)};u?.(G),B==="patch"&&f&&f(G)},[te,u,f]),ee=p.useCallback((x,R,_)=>{const B=Math.max(Ms,q.radius*.1),G=B*B,me=x.screenPoints[x.screenPoints.length-1];if(!me){x.points.push(R),x.screenPoints.push(_),x.current=R;return}const se=_[0]-me[0],xe=_[1]-me[1];se*se+xe*xe>=G?(x.points.push(R),x.screenPoints.push(_)):(x.points[x.points.length-1]=R,x.screenPoints[x.screenPoints.length-1]=_),x.current=R},[q.radius]),Se=p.useCallback(x=>{if(!z||t==="cursor"||x.button!==0)return;const R=Fe(x);if(!R)return;const _=U(x);if(!_)return;if(x.preventDefault(),x.stopPropagation(),Lt(t)){const me=v.current;me.stampCenter=R,Q(t,R),X();return}const B=J.current;B&&B.setPointerCapture(x.pointerId);const G=v.current;G.isDrawing=!0,G.pointerId=x.pointerId,G.start=R,G.current=R,G.cursor=R,G.cursorScreen=_,G.points=t==="freehand"||t==="brush"?[R]:[],G.screenPoints=t==="brush"?[_]:[],X()},[z,t,Fe,U,Q,X]),be=p.useCallback(x=>{if(!z||t==="cursor")return;const R=Fe(x);if(!R)return;const _=U(x);if(!_)return;const B=v.current;if(B.cursor=R,B.cursorScreen=_,Lt(t)){B.stampCenter=R,x.preventDefault(),x.stopPropagation(),X();return}if(t==="brush"){if(!B.isDrawing||B.pointerId!==x.pointerId){X();return}x.preventDefault(),x.stopPropagation(),ee(B,R,_),X();return}if(!(!B.isDrawing||B.pointerId!==x.pointerId)){if(x.preventDefault(),x.stopPropagation(),t==="freehand"){const G=a.current,me=Math.max(1e-6,G?.getViewState?.().zoom??1),se=ls/me,xe=se*se,Me=B.points[B.points.length-1];if(!Me)B.points.push(R);else{const Ie=R[0]-Me[0],Ne=R[1]-Me[1];Ie*Ie+Ne*Ne>=xe&&B.points.push(R)}}else B.current=R;X()}},[z,t,Fe,U,X,a,ee]),Ae=p.useCallback(x=>{const R=v.current;if(!R.isDrawing||R.pointerId!==x.pointerId)return;x.preventDefault(),x.stopPropagation();const _=Fe(x),B=U(x);_&&(R.cursor=_,B&&(R.cursorScreen=B),t==="brush"?B&&ee(R,_,B):R.current=_);const G=J.current;G&&G.hasPointerCapture(x.pointerId)&&G.releasePointerCapture(x.pointerId),Z()},[Z,Fe,U,t,ee]),De=p.useCallback(()=>{const x=v.current;let R=!1;t==="brush"&&!x.isDrawing&&x.cursor&&(x.cursor=null,x.cursorScreen=null,R=!0),Lt(t)&&x.stampCenter&&(x.stampCenter=null,R=!0),R&&X()},[t,X]);return p.useEffect(()=>{Ee(),X();const x=J.current;if(!x)return;const R=new ResizeObserver(()=>{Ee(),X()});return R.observe(x),()=>{R.disconnect()}},[Ee,X]),p.useEffect(()=>tn(()=>{Ee(),X()}),[Ee,X]),p.useEffect(()=>{z||Te(),X()},[z,X,Te]),p.useEffect(()=>{N.current!==t&&(N.current=t,Te(),X())},[t,Te,X]),p.useEffect(()=>{X()},[h,ie,P,X]),p.useEffect(()=>{if(k)return k.current=X,()=>{k.current===X&&(k.current=null)}},[k,X]),p.useEffect(()=>{if(!z)return;const x=R=>{R.key==="Escape"&&(Te(),X())};return window.addEventListener("keydown",x),()=>{window.removeEventListener("keydown",x)}},[z,Te,X]),Ge.jsx("canvas",{ref:J,className:ae,style:Pe,onPointerDown:Se,onPointerMove:be,onPointerUp:Ae,onPointerCancel:Ae,onPointerLeave:De,onContextMenu:x=>{z&&x.preventDefault()},onWheel:x=>{if(!z)return;const R=J.current,_=a.current;if(!R||typeof _?.zoomBy!="function")return;x.preventDefault(),x.stopPropagation();const B=R.getBoundingClientRect(),G=x.clientX-B.left,me=x.clientY-B.top;_.zoomBy(x.deltaY<0?hs:ds,G,me),X()}})}const Ri=p.createContext(null),ea=Ri.Provider;function st(){const t=p.useContext(Ri);if(!t)throw new Error("useViewerContext must be used within a <WsiViewer>");return t}function ta({tool:t="cursor",stampOptions:e,brushOptions:n,fillColor:r,areaTooltip:i,onComplete:o,onPatchComplete:s,onBrushTap:a}){const{source:l,rendererRef:u,rendererSerial:f,setInteractionLock:c}=st(),h=t!=="cursor";p.useEffect(()=>(c("drawing-layer",h),()=>c("drawing-layer",!1)),[h,c]);const d=p.useMemo(()=>u.current?.getViewState(),[f]);return l?Ge.jsx(Ei,{tool:t,enabled:h,imageWidth:l.width,imageHeight:l.height,imageMpp:l.mpp,imageZoom:l.maxTierZoom,stampOptions:e,brushOptions:n,drawFillColor:r,projectorRef:u,onBrushTap:a,viewStateSignal:d,drawAreaTooltip:i,onDrawComplete:o,onPatchComplete:s}):null}function Cr(t,e,n,r){return[Math.min(t,n),Math.min(e,r),Math.max(t,n),Math.max(e,r)]}function Mr(t,e){return!(t[2]<e[0]||t[0]>e[2]||t[3]<e[1]||t[1]>e[3])}class na{constructor(e=16){E(this,"targetNodeSize");E(this,"items",[]);E(this,"globalBounds",[0,0,0,0]);E(this,"gridSize",1);E(this,"cellWidth",1);E(this,"cellHeight",1);E(this,"buckets",[]);E(this,"visited",new Uint32Array(0));E(this,"querySerial",1);const n=Number.isFinite(e)?Math.floor(e):16;this.targetNodeSize=Math.max(1,n)}load(e){if(!Array.isArray(e)||e.length===0){this.items=[],this.globalBounds=[0,0,0,0],this.gridSize=1,this.cellWidth=1,this.cellHeight=1,this.buckets=[],this.visited=new Uint32Array(0),this.querySerial=1;return}const n=[];let r=1/0,i=1/0,o=-1/0,s=-1/0;for(const f of e){if(!f||!Number.isFinite(f.minX)||!Number.isFinite(f.minY)||!Number.isFinite(f.maxX)||!Number.isFinite(f.maxY))continue;const c=Cr(f.minX,f.minY,f.maxX,f.maxY);r=Math.min(r,c[0]),i=Math.min(i,c[1]),o=Math.max(o,c[2]),s=Math.max(s,c[3]),n.push({minX:c[0],minY:c[1],maxX:c[2],maxY:c[3],value:f.value})}if(this.items=n,this.visited=new Uint32Array(n.length),this.querySerial=1,n.length===0||!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(o)||!Number.isFinite(s)){this.globalBounds=[0,0,0,0],this.gridSize=1,this.cellWidth=1,this.cellHeight=1,this.buckets=[];return}this.globalBounds=[r,i,o,s],this.gridSize=Math.max(1,Math.ceil(Math.sqrt(n.length/this.targetNodeSize)));const a=Math.max(0,o-r),l=Math.max(0,s-i);this.cellWidth=a>0?a/this.gridSize:1,this.cellHeight=l>0?l/this.gridSize:1;const u=this.gridSize*this.gridSize;this.buckets=Array.from({length:u},()=>[]);for(let f=0;f<n.length;f+=1){const c=n[f],h=this.toCellX(c.minX),d=this.toCellX(c.maxX),m=this.toCellY(c.minY),g=this.toCellY(c.maxY);for(let b=m;b<=g;b+=1)for(let y=h;y<=d;y+=1)this.buckets[b*this.gridSize+y].push(f)}}search(e){if(this.items.length===0)return[];if(!Array.isArray(e)||e.length<4)return[];const n=Cr(e[0],e[1],e[2],e[3]);if(!Mr(n,this.globalBounds))return[];const r=this.toCellX(n[0]),i=this.toCellX(n[2]),o=this.toCellY(n[1]),s=this.toCellY(n[3]),a=this.nextSerial(),l=[];for(let u=o;u<=s;u+=1)for(let f=r;f<=i;f+=1){const c=this.buckets[u*this.gridSize+f];if(!(!c||c.length===0))for(const h of c){if(this.visited[h]===a)continue;this.visited[h]=a;const d=this.items[h];Mr(n,[d.minX,d.minY,d.maxX,d.maxY])&&l.push(d)}}return l}nextSerial(){return this.querySerial+=1,this.querySerial===4294967295&&(this.visited.fill(0),this.querySerial=1),this.querySerial}toCellX(e){const n=this.globalBounds[0],r=this.globalBounds[2];if(this.gridSize<=1||r<=n)return 0;const i=(e-n)/this.cellWidth;return!Number.isFinite(i)||i<=0?0:i>=this.gridSize-1?this.gridSize-1:Math.max(0,Math.min(this.gridSize-1,Math.floor(i)))}toCellY(e){const n=this.globalBounds[1],r=this.globalBounds[3];if(this.gridSize<=1||r<=n)return 0;const i=(e-n)/this.cellHeight;return!Number.isFinite(i)||i<=0?0:i>=this.gridSize-1?this.gridSize-1:Math.max(0,Math.min(this.gridSize-1,Math.floor(i)))}}function Ai(t){return new na(t)}const ra=`#version 300 es
34
34
  precision highp float;
35
35
  in vec2 aCenter;
36
36
  in float aWeight;
@@ -43,7 +43,7 @@ void main() {
43
43
  gl_Position = vec4(clip, 0.0, 1.0);
44
44
  gl_PointSize = uPointSize;
45
45
  vWeight = aWeight;
46
- }`,ea=`#version 300 es
46
+ }`,ia=`#version 300 es
47
47
  precision highp float;
48
48
  in float vWeight;
49
49
  uniform float uCoreRatio;
@@ -59,12 +59,12 @@ void main() {
59
59
  float alpha = intensity * max(0.0, vWeight) * max(0.0, uPointAlpha);
60
60
  if (alpha <= 0.0001) discard;
61
61
  outColor = vec4(0.0, 0.0, 0.0, alpha);
62
- }`,ta=`#version 300 es
62
+ }`,oa=`#version 300 es
63
63
  precision highp float;
64
64
  in vec2 aPosition;
65
65
  void main() {
66
66
  gl_Position = vec4(aPosition, 0.0, 1.0);
67
- }`,na=`#version 300 es
67
+ }`,sa=`#version 300 es
68
68
  precision highp float;
69
69
  uniform sampler2D uAccumTexture;
70
70
  uniform sampler2D uGradientTexture;
@@ -100,7 +100,7 @@ void main() {
100
100
  float alpha = gradientColor.a * clamp(uOpacity, 0.0, 1.0);
101
101
  if (alpha <= 0.0001) discard;
102
102
  outColor = vec4(gradientColor.rgb * alpha, alpha);
103
- }`;class ra{constructor(){E(this,"canvas");E(this,"gl");E(this,"accumProgram");E(this,"colorProgram");E(this,"accumVao");E(this,"colorVao");E(this,"pointBuffer");E(this,"quadBuffer");E(this,"accumTexture");E(this,"gradientTexture");E(this,"framebuffer");E(this,"accumInternalFormat");E(this,"accumTextureFormat");E(this,"accumTextureType");E(this,"uAccumResolution");E(this,"uAccumPointSize");E(this,"uAccumCoreRatio");E(this,"uAccumPointAlpha");E(this,"uColorAccumTexture");E(this,"uColorGradientTexture");E(this,"uColorOpacity");E(this,"uColorCutoff");E(this,"uColorGain");E(this,"uColorResolution");E(this,"uColorGamma");E(this,"uColorBias");E(this,"uColorStretch");E(this,"pointCapacity",0);E(this,"interleavedCapacity",0);E(this,"interleavedBuffer",null);E(this,"gradientKey","");this.canvas=document.createElement("canvas");const e=this.canvas.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,preserveDrawingBuffer:!0,premultipliedAlpha:!0,powerPreference:"high-performance"});if(!e)throw new Error("WebGL2 is not available for heatmap rendering.");this.gl=e;const r=!!e.getExtension("EXT_color_buffer_float");this.accumInternalFormat=r?e.RGBA16F:e.RGBA8,this.accumTextureFormat=e.RGBA,this.accumTextureType=r?e.HALF_FLOAT:e.UNSIGNED_BYTE,this.accumProgram=bt(e,Js,ea),this.colorProgram=bt(e,ta,na);const i=e.createVertexArray(),o=e.createVertexArray(),s=e.createBuffer(),a=e.createBuffer(),l=e.createTexture(),u=e.createTexture(),f=e.createFramebuffer();if(!i||!o||!s||!a||!l||!u||!f)throw new Error("Failed to allocate heatmap WebGL resources.");this.accumVao=i,this.colorVao=o,this.pointBuffer=s,this.quadBuffer=a,this.accumTexture=l,this.gradientTexture=u,this.framebuffer=f;const c=e.getUniformLocation(this.accumProgram,"uResolution"),h=e.getUniformLocation(this.accumProgram,"uPointSize"),d=e.getUniformLocation(this.accumProgram,"uCoreRatio"),m=e.getUniformLocation(this.accumProgram,"uPointAlpha"),g=e.getUniformLocation(this.colorProgram,"uAccumTexture"),y=e.getUniformLocation(this.colorProgram,"uGradientTexture"),b=e.getUniformLocation(this.colorProgram,"uOpacity"),x=e.getUniformLocation(this.colorProgram,"uCutoff"),A=e.getUniformLocation(this.colorProgram,"uGain"),S=e.getUniformLocation(this.colorProgram,"uGamma"),C=e.getUniformLocation(this.colorProgram,"uBias"),M=e.getUniformLocation(this.colorProgram,"uStretch"),P=e.getUniformLocation(this.colorProgram,"uResolution");if(!c||!h||!d||!m||!g||!y||!b||!x||!A||!S||!C||!M||!P)throw new Error("Failed to resolve heatmap WebGL uniforms.");this.uAccumResolution=c,this.uAccumPointSize=h,this.uAccumCoreRatio=d,this.uAccumPointAlpha=m,this.uColorAccumTexture=g,this.uColorGradientTexture=y,this.uColorOpacity=b,this.uColorCutoff=x,this.uColorGain=A,this.uColorGamma=S,this.uColorBias=C,this.uColorStretch=M,this.uColorResolution=P,e.bindVertexArray(this.accumVao),e.bindBuffer(e.ARRAY_BUFFER,this.pointBuffer),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const U=e.getAttribLocation(this.accumProgram,"aCenter"),O=e.getAttribLocation(this.accumProgram,"aWeight");if(U<0||O<0)throw new Error("Failed to resolve heatmap WebGL attributes.");e.enableVertexAttribArray(U),e.vertexAttribPointer(U,2,e.FLOAT,!1,12,0),e.enableVertexAttribArray(O),e.vertexAttribPointer(O,1,e.FLOAT,!1,12,8),e.bindVertexArray(null),e.bindVertexArray(this.colorVao),e.bindBuffer(e.ARRAY_BUFFER,this.quadBuffer),e.bufferData(e.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,1,1]),e.STATIC_DRAW);const N=e.getAttribLocation(this.colorProgram,"aPosition");if(N<0)throw new Error("Failed to resolve heatmap color position attribute.");e.enableVertexAttribArray(N),e.vertexAttribPointer(N,2,e.FLOAT,!1,8,0),e.bindVertexArray(null),e.bindBuffer(e.ARRAY_BUFFER,null),e.bindTexture(e.TEXTURE_2D,this.accumTexture),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.bindTexture(e.TEXTURE_2D,null),e.bindTexture(e.TEXTURE_2D,this.gradientTexture),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.bindTexture(e.TEXTURE_2D,null),this.ensureCanvasSize(1,1)}render(e){if(e.count<=0||e.width<=0||e.height<=0)return!1;this.ensureCanvasSize(e.width,e.height),this.ensureGradientTexture(e.gradient),this.uploadPointData(e.positions,e.weights,e.count);const n=this.gl;return n.disable(n.SCISSOR_TEST),n.disable(n.DEPTH_TEST),n.disable(n.CULL_FACE),n.bindFramebuffer(n.FRAMEBUFFER,this.framebuffer),n.viewport(0,0,e.width,e.height),n.clearColor(0,0,0,0),n.clear(n.COLOR_BUFFER_BIT),n.useProgram(this.accumProgram),n.bindVertexArray(this.accumVao),n.uniform2f(this.uAccumResolution,e.width,e.height),n.uniform1f(this.uAccumPointSize,Math.max(1,(e.kernelRadiusPx+e.blurRadiusPx)*2)),n.uniform1f(this.uAccumCoreRatio,e.kernelRadiusPx/Math.max(1e-6,e.kernelRadiusPx+e.blurRadiusPx)),n.uniform1f(this.uAccumPointAlpha,Math.max(0,e.pointAlpha)),n.enable(n.BLEND),n.blendEquation(n.FUNC_ADD),n.blendFuncSeparate(n.ONE,n.ONE,n.ONE,n.ONE),n.drawArrays(n.POINTS,0,e.count),n.disable(n.BLEND),n.bindVertexArray(null),n.bindFramebuffer(n.FRAMEBUFFER,null),n.viewport(0,0,e.width,e.height),n.clearColor(0,0,0,0),n.clear(n.COLOR_BUFFER_BIT),n.useProgram(this.colorProgram),n.bindVertexArray(this.colorVao),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,this.accumTexture),n.uniform1i(this.uColorAccumTexture,0),n.activeTexture(n.TEXTURE1),n.bindTexture(n.TEXTURE_2D,this.gradientTexture),n.uniform1i(this.uColorGradientTexture,1),n.uniform1f(this.uColorOpacity,e.opacity),n.uniform1f(this.uColorCutoff,e.cutoff??.008),n.uniform1f(this.uColorGain,e.gain??2.6),n.uniform1f(this.uColorGamma,e.gamma??1),n.uniform1f(this.uColorBias,e.bias??0),n.uniform1f(this.uColorStretch,e.stretch??1),n.uniform2f(this.uColorResolution,e.width,e.height),n.drawArrays(n.TRIANGLE_STRIP,0,4),n.bindVertexArray(null),n.bindTexture(n.TEXTURE_2D,null),n.flush(),!0}destroy(){const e=this.gl;e.deleteTexture(this.accumTexture),e.deleteTexture(this.gradientTexture),e.deleteFramebuffer(this.framebuffer),e.deleteBuffer(this.pointBuffer),e.deleteBuffer(this.quadBuffer),e.deleteVertexArray(this.accumVao),e.deleteVertexArray(this.colorVao),e.deleteProgram(this.accumProgram),e.deleteProgram(this.colorProgram),this.canvas.width=0,this.canvas.height=0}ensureCanvasSize(e,n){const r=Math.max(1,Math.round(e)),i=Math.max(1,Math.round(n));this.canvas.width!==r&&(this.canvas.width=r),this.canvas.height!==i&&(this.canvas.height=i);const o=this.gl;o.bindTexture(o.TEXTURE_2D,this.accumTexture),o.texImage2D(o.TEXTURE_2D,0,this.accumInternalFormat,r,i,0,this.accumTextureFormat,this.accumTextureType,null),o.bindFramebuffer(o.FRAMEBUFFER,this.framebuffer),o.framebufferTexture2D(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,this.accumTexture,0);const s=o.checkFramebufferStatus(o.FRAMEBUFFER);if(o.bindFramebuffer(o.FRAMEBUFFER,null),s!==o.FRAMEBUFFER_COMPLETE)throw new Error(`Heatmap framebuffer incomplete: ${s}`)}ensureGradientTexture(e){const n=e.join("|");if(this.gradientKey===n)return;const r=document.createElement("canvas");r.width=256,r.height=1;const i=r.getContext("2d");if(!i)throw new Error("Failed to create heatmap gradient canvas.");const o=i.createLinearGradient(0,0,256,0),s=e.length>1?e:["#00000000","#3876FF","#4CDDDD","#FFE75C","#FF8434","#FF3434"],a=1/Math.max(1,s.length-1);for(let f=0;f<s.length;f+=1)o.addColorStop(f*a,s[f]);i.clearRect(0,0,256,1),i.fillStyle=o,i.fillRect(0,0,256,1);const l=i.getImageData(0,0,256,1).data,u=this.gl;u.bindTexture(u.TEXTURE_2D,this.gradientTexture),u.texImage2D(u.TEXTURE_2D,0,u.RGBA,256,1,0,u.RGBA,u.UNSIGNED_BYTE,l),u.bindTexture(u.TEXTURE_2D,null),this.gradientKey=n}uploadPointData(e,n,r){const i=this.gl,o=r*3,s=o*4;i.bindBuffer(i.ARRAY_BUFFER,this.pointBuffer),r>this.pointCapacity&&(i.bufferData(i.ARRAY_BUFFER,s,i.DYNAMIC_DRAW),this.pointCapacity=r),o>this.interleavedCapacity&&(this.interleavedCapacity=o,this.interleavedBuffer=new Float32Array(o));const a=this.interleavedBuffer;if(!a)throw new Error("Failed to allocate heatmap upload buffer.");for(let l=0;l<r;l+=1){const u=l*2,f=l*3;a[f]=e[u]??0,a[f+1]=e[u+1]??0,a[f+2]=n[l]??0}i.bufferSubData(i.ARRAY_BUFFER,0,a.subarray(0,o)),i.bindBuffer(i.ARRAY_BUFFER,null)}}const Mr="__open_plant_heatmap_layer__",ia=["#00000000","#3876FF","#4CDDDD","#FFE75C","#FF8434","#FF3434"],oa=3,sa=2,aa=.9,la=52e3,ca="screen",ua=2.2,En=128,Qt=1600,fa=1.9,ha=4.2,Rn=3e3,Si=Math.SQRT2,da=2048,ma=.9,$e=16;function Mt(t,e){return e.maxTierZoom+Math.log2(Math.max(1e-6,t))}function Yn(t,e){return Math.max(1e-6,2**(t-e.maxTierZoom))}function ga(t,e,n){if(!Number.isFinite(n)||Math.abs(n)<1e-6)return Math.max(1e-6,t);const r=Mt(t,e)-n;return Yn(r,e)}function pa(t){return!Number.isFinite(t)||Math.abs(t)<1e-6?0:Math.round(t*1.5/Math.max(1e-6,Math.log2(Si)))}function Ei(t){const e=L(t,0,$e);return L(.55+Math.sqrt(Math.max(0,e))*.48,.55,6)}function ya(t){const e=Math.max(0,t);return e<=1?.18:e<=2?.3:e<=4?.48:e<=8?.7:e<=16?.86:1}function Ri(t){return .022-L(t,0,$e)/$e*.015}function Ai(t){const e=L(t,0,$e);return .18+Math.pow(Math.max(0,e),.72)*.42+Math.log2(e+1)*.24}function Ci(t){return Ei(t)}function Mi(t){const n=L(t,0,$e)/$e;return L(.46-n*.34,.12,.46)}function Pi(t,e,n){const i=L(t,0,$e)/$e,o=Mt(e,n),s=n.maxTierZoom-3.2,a=n.maxTierZoom-1.15,l=L((o-s)/Math.max(1e-6,a-s),0,1),u=1.12+Math.pow(i,.82)*1.18,f=1+l*(.48+i*.92);return u*f}function ba(t,e,n){const r=Math.max(0,t),i=Math.max(1e-6,e),o=Math.log1p(r)/Math.log1p(i);return L(o,0,1)}function xa(t){return ma}function wa(t,e){if(t.length===0)return 1;const n=Math.min(t.length,da),r=new Array(n);let i=1;for(let f=0;f<n;f+=1){const c=Math.min(t.length-1,Math.floor((f+.5)*t.length/n)),h=Math.max(0,t[c]?.weight??0);r[f]=h,h>i&&(i=h)}for(let f=0;f<t.length;f+=1){const c=Math.max(0,t[f]?.weight??0);c>i&&(i=c)}r.sort((f,c)=>f-c);const o=xa(),s=Math.max(0,Math.min(r.length-1,Math.floor((r.length-1)*o))),a=r[s]??i;return Math.max(1,Math.min(i,Math.max(a*1.08,i*.14)))}function vi(t,e,n){const r=Mt(t,e),i=e.maxTierZoom-2.45,o=e.maxTierZoom-1.2,s=r<=i?1:r>=o?0:(()=>{const a=L((r-i)/Math.max(1e-6,o-i),0,1);return 1-a*a*(3-2*a)})();return L(s,0,1)}function Sa(t){if(t>=1)return 1;const e=1/Math.max(t,1e-6);return 1+Math.log2(e)*.28}function Ea(t,e,n,r){const i=Math.max(1,t,e),o=typeof window>"u"?1:L(window.devicePixelRatio||1,1,2.4),s=r<=.35?1.42:r<=.55?1.26:r<=.8?1.14:1,a=n>16e4?896:n>8e4?1152:n>3e4?1408:Qt,l=En/i,u=Qt/i;return L(a*o*s/i,l,u)}function An(t){const e=t.heatmapScale??Ea(t.logicalWidth,t.logicalHeight,t.totalPointCount,t.rawZoom),n=Math.max(En,Math.min(Qt,Math.round(t.logicalWidth*e))),r=Math.max(En,Math.min(Qt,Math.round(t.logicalHeight*e))),i=n/Math.max(1,t.logicalWidth),o=r/Math.max(1,t.logicalHeight),s=Math.min(i,o),a=Math.max(1e-6,t.rawZoom),l=Math.max(.75,t.radius*fa*s),u=Math.max(.6,t.blur*ha*s),f=(l+u)/Math.max(1e-6,a*s),c=Math.max(f*.4,.62/Math.max(1e-6,a*s));return{heatmapScale:e,rasterWidth:n,rasterHeight:r,rasterScaleX:i,rasterScaleY:o,rawZoom:a,kernelRadiusPx:l,blurRadiusPx:u,outerWorldRadius:f,desiredCellWorldSize:c}}function Wn(t){if(!t)return 0;const e=Math.floor(t.positions.length/2),n=t.weights?t.weights.length:Number.MAX_SAFE_INTEGER;return Math.max(0,Math.min(Math.floor(t.count),e,n))}function Ft(t,e){const n=Number.isFinite(t)?Math.round(t*1024):0;return Math.imul(e^n,73244475)>>>0}function Ra(t,e,n=2654435769){let r=Math.imul(n^(t|0),2246822507)>>>0;return r=Math.imul(r^(e|0),3266489909)>>>0,r^=r>>>16,r>>>0}function Aa(t){return(t>>>0)/4294967295}function Ti(t){let e=2166136261;for(let n=0;n<t.length;n+=1){const r=t[n];e=Math.imul(e^r.outer.length,16777619)>>>0;for(let i=0;i<r.outer.length;i+=1){const o=r.outer[i];e=Ft(o[0],e),e=Ft(o[1],e)}e=Math.imul(e^r.holes.length,16777619)>>>0;for(let i=0;i<r.holes.length;i+=1){const o=r.holes[i];e=Math.imul(e^o.length,16777619)>>>0;for(let s=0;s<o.length;s+=1){const a=o[s];e=Ft(a[0],e),e=Ft(a[1],e)}}}return`${t.length}:${e>>>0}`}function Xn(t,e,n){return t.dataRef===e&&t.clipKey===n?!0:e?t.clipKey===n&&t.inputCount===Wn(e)&&t.positionsRef===e.positions&&t.weightsRef===e.weights:!1}function Ca(t,e,n,r){const i=Wn(t);if(!t||i<=0)return null;let o=new Float32Array(i),s=new Float32Array(i),a=new Float32Array(i),l=0,u=1/0,f=1/0,c=-1/0,h=-1/0;for(let A=0;A<i;A+=1){const S=t.positions[A*2],C=t.positions[A*2+1];if(!Number.isFinite(S)||!Number.isFinite(C)||e.length>0&&!St(S,C,e))continue;const M=t.weights?.[A],P=typeof M=="number"&&Number.isFinite(M)?Math.max(0,M):1;P<=0||(o[l]=S,s[l]=C,a[l]=P,l+=1,S<u&&(u=S),S>c&&(c=S),C<f&&(f=C),C>h&&(h=C))}if(l===0||!Number.isFinite(u)||!Number.isFinite(f)||!Number.isFinite(c)||!Number.isFinite(h))return null;l<i&&(o=o.slice(0,l),s=s.slice(0,l),a=a.slice(0,l));const d=[];for(let A=0;A<l;A+=1){const S=o[A],C=s[A];d.push({minX:S,minY:C,maxX:S,maxY:C,value:A})}const m=wi(64);m.load(d);const g=Math.max(r?.width??0,r?.height??0,c-u,h-f,1),y=[];let b=.5,x=0;for(;b<=g&&x<32;)y.push(b),b*=Si,x+=1;return y.length===0&&y.push(1),{dataRef:t,sourceRef:r,positionsRef:t.positions,weightsRef:t.weights,inputCount:i,clipRef:e,clipKey:n,pointCount:l,xs:o,ys:s,ws:a,pointIndex:m,cellSizes:y,levels:Array.from({length:y.length},()=>null)}}function Cn(t,e,n){const r=t.pointIndex.search([e[0]-n,e[1]-n,e[2]+n,e[3]+n]),i=new Array(r.length);let o=0;for(let s=0;s<r.length;s+=1){const a=r[s];a&&(i[o]=a.value,o+=1)}return i.length=o,i}function Ii(t,e){const n=Math.max(Rn,e);return t<=n?1:L(n/Math.max(1,t),1/65536,1)}function _i(t){return t>=1?1:Math.max(1,Math.round(1/Math.max(1e-6,t)))}function Ma(t,e){if(e>=1)return!0;const n=Ra(t,1374496523,1757159915);return Aa(n)<=L(e,0,1)}function Li(t,e,n,r){const i=Math.max(1,n*r),o=Math.PI*e*e,s=Math.max(1,t)*o/i;return L(.085/Math.sqrt(Math.max(1,s)),.012,.075)}function Pr(t,e,n,r){if(!Number.isFinite(t)||t<=0)return e;const i=e>=t?n:r;return t+(e-t)*L(i,0,1)}function Pa(t){if(t.webgl!==void 0)return t.webgl;if(typeof document>"u")return t.webgl=null,null;try{t.webgl=new ra}catch(e){if(!t.webglWarningIssued&&typeof console<"u"&&typeof console.warn=="function"){const n=e instanceof Error?e.message:String(e);console.warn(`[open-plant] HeatmapLayer disabled because WebGL2 heatmap initialization failed: ${n}`),t.webglWarningIssued=!0}t.webgl=null}return t.webgl}function vr(t,e){const n=[];for(let r=0;r<e.length;r+=1){const i=e[r];if(!i)continue;const o=t.worldToScreen(i[0],i[1]);if(!Array.isArray(o)||o.length<2)continue;const s=Number(o[0]),a=Number(o[1]);!Number.isFinite(s)||!Number.isFinite(a)||n.push([s,a])}return n}function va(t,e,n){if(n.length!==0){t.beginPath();for(let r=0;r<n.length;r+=1){const i=n[r],o=vr(e,i.outer);o.length>=3&&Et(t,o,!0);for(let s=0;s<i.holes.length;s+=1){const a=vr(e,i.holes[s]);a.length>=3&&Et(t,a,!0)}}t.clip("evenodd")}}function Fi(t,e,n,r,i){const o=t.sourceData;return o&&o.sourceRef===i&&Xn(o,e,r)?o:(t.sourceData=Ca(e,n,r,i),t.fixedState=null,t.screenLevelIndex=-1,t.sourceData)}function Ta(t){const{sourceData:e,renderer:n,source:r,logicalWidth:i,logicalHeight:o,radius:s,blur:a,fixedZoom:l,maxRenderedPoints:u}=t,f=Math.max(1e-6,n.getViewState().zoom),c=l??Mt(f,r),h=Yn(c,r),d=An({logicalWidth:i,logicalHeight:o,totalPointCount:e.pointCount,rawZoom:h,radius:s,blur:a}),m=n.getViewBounds(),g=Cn(e,m,d.outerWorldRadius),y=Ii(g.length,u),b=_i(y),x=Math.min(d.rasterScaleX,d.rasterScaleY);return{dataRef:e.dataRef,positionsRef:e.positionsRef,weightsRef:e.weightsRef,inputCount:e.inputCount,clipRef:e.clipRef,clipKey:e.clipKey,referenceZoom:c,referenceRawZoom:h,heatmapScale:d.heatmapScale,kernelWorldRadius:d.kernelRadiusPx/Math.max(1e-6,h*x),blurWorldRadius:d.blurRadiusPx/Math.max(1e-6,h*x),sampleProbability:y,sampleStride:b,pointAlpha:Li(g.length,d.kernelRadiusPx+d.blurRadiusPx,d.rasterWidth,d.rasterHeight)}}function Tr(t){const{ctx:e,runtime:n,renderer:r,source:i,logicalWidth:o,logicalHeight:s,frame:a,sourceData:l,visiblePointIndices:u,sampleProbability:f,sampleStride:c,pointAlpha:h,gradient:d,opacity:m,densityContrast:g,backgroundColor:y,clipPolygons:b}=t,x=Pa(n);if(!x||u.length===0)return 0;const A=Math.min(u.length,Math.max(64,Math.ceil(u.length*Math.min(1,f*1.15))));A>n.webglCapacity&&(n.webglCapacity=A,n.webglPositions=new Float32Array(A*2),n.webglWeights=new Float32Array(A));const S=n.webglPositions,C=n.webglWeights;if(!S||!C)return 0;const M=a.kernelRadiusPx+a.blurRadiusPx,P=Sa(f);let U=0;for(let N=0;N<u.length;N+=1){const v=u[N];if(!Ma(v,f))continue;const B=l.xs[v],F=l.ys[v];if(!Number.isFinite(B)||!Number.isFinite(F))continue;const z=r.worldToScreen(B,F);if(!Array.isArray(z)||z.length<2)continue;const K=Number(z[0]),Y=Number(z[1]);if(!Number.isFinite(K)||!Number.isFinite(Y))continue;const j=K*a.rasterScaleX,ce=Y*a.rasterScaleY;if(j<-M||ce<-M||j>a.rasterWidth+M||ce>a.rasterHeight+M)continue;const J=U*2;S[J]=j,S[J+1]=ce,C[U]=Math.max(0,(l.ws[v]??0)*P),U+=1}return U<=0||!x.render({width:a.rasterWidth,height:a.rasterHeight,positions:S,weights:C,count:U,kernelRadiusPx:a.kernelRadiusPx,blurRadiusPx:a.blurRadiusPx,pointAlpha:h,gradient:d,opacity:m,cutoff:Ri(g),gain:Ai(g),gamma:Ci(g),bias:Mi(g),stretch:Pi(g,a.rawZoom,i)})?0:(e.save(),b.length>0&&va(e,r,b),y&&(e.fillStyle=y,e.fillRect(0,0,o,s)),e.globalAlpha=1,e.imageSmoothingEnabled=!0,e.drawImage(x.canvas,0,0,a.rasterWidth,a.rasterHeight,0,0,o,s),e.restore(),U)}function Ia(t){const{ctx:e,runtime:n,renderer:r,source:i,logicalWidth:o,logicalHeight:s,state:a}=t,l=Fi(n,a.data,a.clipPolygons,a.clipKey,i);if(!l||l.cellSizes.length===0||l.pointCount<=0)return null;const u=Math.max(1e-6,r.getViewState().zoom),f=vi(u,i,a.zoomThreshold),c=r.getViewBounds();if(f<=.001)return{pointCount:l.pointCount,renderTimeMs:0,visiblePointCount:0,renderedBinCount:0,sampleStride:1,maxDensity:0};if(a.scaleMode!=="fixed-zoom"){const b=An({logicalWidth:o,logicalHeight:s,totalPointCount:l.pointCount,rawZoom:u,radius:a.radius,blur:a.blur}),x=Cn(l,c,b.outerWorldRadius);if(x.length===0)return{pointCount:l.pointCount,renderTimeMs:0,visiblePointCount:0,renderedBinCount:0,sampleStride:1,maxDensity:0};const A=Ii(x.length,a.maxRenderedPoints),S=_i(A),C=Li(x.length,b.kernelRadiusPx+b.blurRadiusPx,b.rasterWidth,b.rasterHeight);n.screenLevelIndex=-1,n.screenSecondaryLevelIndex=-1,n.screenSecondaryLevelWeight=0,n.screenNormalizationMaxWeight=1,n.screenPointAlpha=Pr(n.screenPointAlpha,C,.12,.08),n.screenVisibilityStrength=r.isViewAnimating()?Pr(n.screenVisibilityStrength,f,.16,.12):f;const M=Tr({ctx:e,runtime:n,renderer:r,source:i,logicalWidth:o,logicalHeight:s,frame:b,sourceData:l,visiblePointIndices:x,sampleProbability:A,sampleStride:S,pointAlpha:n.screenPointAlpha*Math.max(.08,n.screenVisibilityStrength),gradient:a.gradient,opacity:a.opacity*n.screenVisibilityStrength,densityContrast:a.densityContrast,backgroundColor:a.backgroundColor,clipPolygons:a.clipPolygons});return{pointCount:l.pointCount,renderTimeMs:0,visiblePointCount:x.length,renderedBinCount:M,sampleStride:S,maxDensity:Math.round(n.screenPointAlpha*255)}}const h=n.fixedState;if(!h)return null;const d=An({logicalWidth:o,logicalHeight:s,totalPointCount:l.pointCount,rawZoom:u,radius:a.radius,blur:a.blur,heatmapScale:h.heatmapScale}),m=Math.min(d.rasterScaleX,d.rasterScaleY);d.kernelRadiusPx=Math.max(.75,h.kernelWorldRadius*u*m),d.blurRadiusPx=Math.max(.6,h.blurWorldRadius*u*m),d.outerWorldRadius=h.kernelWorldRadius+h.blurWorldRadius;const g=Cn(l,c,d.outerWorldRadius);if(g.length===0)return{pointCount:l.pointCount,renderTimeMs:0,visiblePointCount:0,renderedBinCount:0,sampleStride:1,maxDensity:0};n.screenPointAlpha=h.pointAlpha,n.screenVisibilityStrength=f;const y=Tr({ctx:e,runtime:n,renderer:r,source:i,logicalWidth:o,logicalHeight:s,frame:d,sourceData:l,visiblePointIndices:g,sampleProbability:h.sampleProbability,sampleStride:h.sampleStride,pointAlpha:h.pointAlpha*Math.max(.08,f),gradient:a.gradient,opacity:a.opacity*f,densityContrast:a.densityContrast,backgroundColor:a.backgroundColor,clipPolygons:a.clipPolygons});return{pointCount:l.pointCount,renderTimeMs:0,visiblePointCount:g.length,renderedBinCount:y,sampleStride:h.sampleStride,maxDensity:Math.round(h.pointAlpha*255)}}function _a({data:t,visible:e=!0,opacity:n=aa,radius:r=oa,blur:i=sa,gradient:o=ia,backgroundColor:s=null,scaleMode:a=ca,fixedZoom:l,zoomThreshold:u=0,densityContrast:f=ua,clipToRegions:c,zIndex:h=5,maxRenderedPoints:d=la,onStats:m}){const{rendererRef:g,source:y,registerDrawCallback:b,unregisterDrawCallback:x,requestOverlayRedraw:A}=at(),S=p.useMemo(()=>{const U=(c??[]).map(O=>ht(O?.coordinates)).filter(O=>O!=null);return dt(U)},[c]),C=p.useMemo(()=>Ti(S),[S]),M=p.useRef({sourceData:null,fixedState:null,screenLevelIndex:-1,screenSecondaryLevelIndex:-1,screenSecondaryLevelWeight:0,screenPointAlpha:0,screenNormalizationMaxWeight:1,screenVisibilityStrength:1,webgl:void 0,webglWarningIssued:!1,webglPositions:null,webglWeights:null,webglCapacity:0}),P=p.useRef({data:t,visible:e,opacity:n,radius:L(r,.05,128),blur:L(i,.05,128),gradient:o,backgroundColor:s,scaleMode:a,fixedZoom:l,zoomThreshold:u,densityContrast:L(f,0,$e),clipPolygons:S,clipKey:C,maxRenderedPoints:Math.max(Rn,Math.floor(d)),onStats:m});return P.current={data:t,visible:e,opacity:n,radius:L(r,.05,128),blur:L(i,.05,128),gradient:o,backgroundColor:s,scaleMode:a,fixedZoom:l,zoomThreshold:u,densityContrast:L(f,0,$e),clipPolygons:S,clipKey:C,maxRenderedPoints:Math.max(Rn,Math.floor(d)),onStats:m},p.useEffect(()=>(b(Mr,h,(O,N,v)=>{const B=P.current,F=M.current,z=g.current;if(!B.visible||!B.data||!z||!y)return;const K=Fi(F,B.data,B.clipPolygons,B.clipKey,y);if(!K)return;B.scaleMode==="fixed-zoom"&&(!F.fixedState||!Xn(F.fixedState,B.data,B.clipKey)||B.fixedZoom!==void 0&&Math.abs(F.fixedState.referenceZoom-B.fixedZoom)>1e-6)?F.fixedState=Ta({sourceData:K,renderer:z,source:y,logicalWidth:N,logicalHeight:v,radius:B.radius,blur:B.blur,fixedZoom:B.fixedZoom,zoomThreshold:B.zoomThreshold,densityContrast:B.densityContrast,maxRenderedPoints:B.maxRenderedPoints}):B.scaleMode!=="fixed-zoom"&&(F.fixedState=null);const j=performance.now(),ce=Ia({ctx:O,runtime:F,renderer:z,source:y,logicalWidth:N,logicalHeight:v,state:B});!ce||!B.onStats||B.onStats({...ce,renderTimeMs:performance.now()-j})}),()=>{x(Mr),M.current.sourceData=null,M.current.fixedState=null,M.current.screenLevelIndex=-1,M.current.screenSecondaryLevelIndex=-1,M.current.screenSecondaryLevelWeight=0,M.current.screenPointAlpha=0,M.current.screenNormalizationMaxWeight=1,M.current.screenVisibilityStrength=1,M.current.webgl?.destroy(),M.current.webgl=void 0,M.current.webglPositions=null,M.current.webglWeights=null,M.current.webglCapacity=0}),[b,x,g,y,h]),p.useEffect(()=>{M.current.sourceData=null,M.current.fixedState=null,M.current.screenLevelIndex=-1,M.current.screenSecondaryLevelIndex=-1,M.current.screenSecondaryLevelWeight=0,M.current.screenPointAlpha=0,M.current.screenNormalizationMaxWeight=1,M.current.screenVisibilityStrength=1,A()},[t?.positions,t?.weights,t?.count,C,A]),p.useEffect(()=>{M.current.fixedState=null,M.current.screenSecondaryLevelIndex=-1,M.current.screenSecondaryLevelWeight=0,M.current.screenPointAlpha=0,M.current.screenNormalizationMaxWeight=1,M.current.screenVisibilityStrength=1,A()},[r,i,a,l,u,f,d,A]),p.useEffect(()=>{A()},[e,n,o,s,A]),null}const La={applyZoomThreshold:ga,buildClipKey:Ti,resolveCellSupportFactor:ya,resolveContinuousZoom:Mt,resolveDensityCutoff:Ri,resolveDensityBias:Mi,resolveDensityGain:Ai,resolveDensityGamma:Ci,resolveDensityStretch:Pi,resolveNormalizedDensityWeight:ba,resolveNormalizationUpperWeight:wa,resolveDensityWeightExponent:Ei,resolveRawZoomFromContinuousZoom:Yn,resolvePointCount:Wn,resolveThresholdLevelBias:pa,resolveZoomVisibilityStrength:vi,isSameHeatmapInput:Xn},Ir="__overlay_layer__";function Fa({shapes:t}){const{rendererRef:e,source:n,registerDrawCallback:r,unregisterDrawCallback:i,requestOverlayRedraw:o}=at(),s=p.useCallback(l=>{const u=e.current;if(!u||l.length===0)return[];const f=new Array(l.length);for(let c=0;c<l.length;c+=1){const h=qe(u.worldToScreen(l[c][0],l[c][1]));if(!h)return[];f[c]=h}return f},[]),a=p.useRef({shapes:t,worldToScreenPoints:s,source:n});return a.current={shapes:t,worldToScreenPoints:s,source:n},p.useEffect(()=>(r(Ir,30,u=>{const{shapes:f,worldToScreenPoints:c,source:h}=a.current;if(!Array.isArray(f)||f.length===0||!h)return;const d=c(Ue([[0,0],[h.width,0],[h.width,h.height],[0,h.height]]));yi({ctx:u,overlayShapes:f,imageOuterRing:d,worldToScreenPoints:c,baseStrokeStyle:Ke})}),()=>i(Ir)),[r,i]),p.useEffect(()=>{o()},[t,o]),null}function Da(t){return Array.isArray(t?.classes)?t.classes.map(e=>({classId:String(e?.classId??""),className:String(e?.className??""),classColor:String(e?.classColor??"")})):[]}function _r(t){return String(t??"").replace(/\/+$/,"")}function Di(t){const e=String(t??"");return e.startsWith("/")?e:`/${e}`}function Na(t){const e=_r(t);if(!e)return"";if(/\/TileGroup\d+$/i.test(e))return e;let n=null;try{n=new URL(e)}catch{n=null}if(n){const r=`${n.protocol}//${n.host}`,i=_r(n.pathname||"");return/\/ims$/i.test(i)?`${r}${i}`:/\/tiles$/i.test(i)?`${r}${i}`:`${r}${i}/tiles`}return/\/ims$/i.test(e)?"/ims":/\/tiles$/i.test(e)?`${e}`:`${e}/tiles`}function Ba(t,e){const n=t?.imsInfo??{},r=!!t?.imsInfo,i=Number(n.width??t?.width??0),o=Number(n.height??t?.height??0),s=Number(n.tileSize??t?.tileSize??0),a=Number(n.zoom??t?.zoom??0),l=String(n.path??t?.path??""),u=Number(n.mpp??t?.mpp??0);if(!i||!o||!s||!l)throw new Error("Incomplete image metadata: width/height/tileSize/path required");const f=Di(l),c=Na(e),h=t?.tileUrlBuilder??(r?(d,m,g)=>`${c}${f}/${d}/${g}_${m}.webp`:void 0);return{id:t?._id||t?.id||"unknown",name:t?.name||"unknown",width:i,height:o,mpp:Number.isFinite(u)&&u>0?u:void 0,tileSize:s,maxTierZoom:Number.isFinite(a)?Math.max(0,Math.floor(a)):0,tilePath:l,tileBaseUrl:e,tileUrlBuilder:h}}function Vn(t,e,n,r){if(t.tileUrlBuilder)return t.tileUrlBuilder(e,n,r,t.tilePath,t.tileBaseUrl);const i=Di(t.tilePath);return`${t.tileBaseUrl}${i}/${e}/${r}_${n}.webp`}function ka(t,e){if(!e)return!1;const n=new URL(t,typeof window<"u"?window.location.href:void 0).hostname.toLowerCase();return!(n.includes("amazonaws.com")||n.startsWith("s3.")||n.includes(".s3."))}const Oe={width:200,height:125,margin:16,position:"bottom-right",borderRadius:6,borderWidth:0,backgroundColor:"rgba(4, 10, 18, 0.88)",borderColor:"rgba(230, 244, 255, 0.35)",viewportBorderColor:"rgba(255, 106, 61, 0.95)",viewportBorderStyle:"dash",viewportFillColor:"transparent",interactive:!0,showThumbnail:!0,maxThumbnailTiles:16};function Lr(t,e,n,r){const i=e.length;if(!(i<3)){for(let o=0;o<i;o+=1){const s=e[o],a=e[(o+1)%i],l=Math.hypot(a[0]-s[0],a[1]-s[1]);if(l<1e-6)continue;const u=Math.max(1,Math.round((l+r)/(n+r))),f=u*n+(u-1)*r,c=l/Math.max(1e-6,f),h=n*c,d=r*c;t.beginPath(),t.moveTo(s[0],s[1]),t.lineTo(a[0],a[1]),t.setLineDash([h,d]),t.lineDashOffset=0,t.stroke()}t.setLineDash([]),t.lineDashOffset=0}}function Fr(t,e,n=1e-4){return Math.abs(t[0]-e[0])<=n&&Math.abs(t[1]-e[1])<=n}function Dr(t){const e=[];for(const n of t){const r=e[e.length-1];(!r||!Fr(r,n))&&e.push(n)}return e.length>1&&Fr(e[0],e[e.length-1])&&e.pop(),e}function Nr(t,e,n){const r=e[0]-t[0];if(Math.abs(r)<1e-6)return[n,t[1]];const i=(n-t[0])/r;return[n,t[1]+(e[1]-t[1])*i]}function Br(t,e,n){const r=e[1]-t[1];if(Math.abs(r)<1e-6)return[t[0],n];const i=(n-t[1])/r;return[t[0]+(e[0]-t[0])*i,n]}function Ua(t,e,n,r,i){let o=Dr(t);if(o.length<3)return[];const s=[{inside:a=>a[0]>=e,intersect:(a,l)=>Nr(a,l,e)},{inside:a=>a[0]<=r,intersect:(a,l)=>Nr(a,l,r)},{inside:a=>a[1]>=n,intersect:(a,l)=>Br(a,l,n)},{inside:a=>a[1]<=i,intersect:(a,l)=>Br(a,l,i)}];for(const a of s){if(o.length===0)return[];const l=o;o=[];let u=l[l.length-1],f=a.inside(u);for(const c of l){const h=a.inside(c);h?(f||o.push(a.intersect(u,c)),o.push(c)):f&&o.push(a.intersect(u,c)),u=c,f=h}o=Dr(o)}return o.length>=3?o:[]}function ct(t,e,n=1){return typeof t!="number"||!Number.isFinite(t)?e:Math.max(n,t)}function gt(t){return Array.isArray(t)&&t.length===4&&Number.isFinite(t[0])&&Number.isFinite(t[1])&&Number.isFinite(t[2])&&Number.isFinite(t[3])}const za={position:"absolute",top:4,right:4,zIndex:1,width:18,height:18,borderRadius:999,border:"1px solid rgba(255,255,255,0.4)",background:"rgba(16, 17, 19, 0.85)",color:"#fff",fontSize:12,lineHeight:1,cursor:"pointer",padding:0,display:"flex",alignItems:"center",justifyContent:"center"};function Oa({source:t,projectorRef:e,authToken:n="",options:r,invalidateRef:i,className:o,style:s}){const a=p.useRef(null),l=p.useRef(null),u=p.useRef(null),f=p.useRef({active:!1,pointerId:null}),c=p.useRef(null),h=p.useRef(!1),d=ct(r?.width,Oe.width,64),m=ct(r?.height,Oe.height,48),g=p.useMemo(()=>{const _=Math.max(1,t.width),T=Math.max(1,t.height),X=_/T,q=d/m;let te,le;return X>q?(te=d,le=d/X):(le=m,te=m*X),{x:(d-te)/2,y:(m-le)/2,w:te,h:le}},[t.width,t.height,d,m]),y=ct(r?.margin,Oe.margin,0),b=ct(r?.borderRadius,Oe.borderRadius,0),x=ct(r?.borderWidth,Oe.borderWidth,0),A=Math.max(1,Math.round(ct(r?.maxThumbnailTiles,Oe.maxThumbnailTiles,1))),S=r?.backgroundColor||Oe.backgroundColor,C=r?.borderColor||Oe.borderColor,M=r?.viewportBorderColor||Oe.viewportBorderColor,P=r?.viewportBorderStyle==="stroke"||r?.viewportBorderStyle==="dash"?r.viewportBorderStyle:Oe.viewportBorderStyle,U=r?.viewportFillColor??Oe.viewportFillColor,O=r?.interactive??Oe.interactive,N=r?.showThumbnail??Oe.showThumbnail,v=r?.position||Oe.position,B=r?.onClose,F=r?.closeIcon,z=r?.closeButtonStyle,K=p.useMemo(()=>{const _={};return v==="top-left"||v==="bottom-left"?_.left=y:_.right=y,v==="top-left"||v==="top-right"?_.top=y:_.bottom=y,{position:"absolute",..._,width:d,height:m,borderRadius:b,overflow:"hidden",zIndex:4,pointerEvents:O?"auto":"none",touchAction:"none",boxShadow:"0 10px 22px rgba(0, 0, 0, 0.3)",...s}},[y,v,d,m,b,O,s]),Y=p.useCallback(()=>{const _=a.current;if(!_)return;const T=_.getContext("2d");if(!T)return;const X=d,q=m,te=Math.max(1,window.devicePixelRatio||1),le=Math.max(1,Math.round(X*te)),re=Math.max(1,Math.round(q*te));(_.width!==le||_.height!==re)&&(_.width=le,_.height=re),T.setTransform(1,0,0,1,0,0),T.clearRect(0,0,_.width,_.height),T.setTransform(te,0,0,te,0,0),T.fillStyle=S,T.fillRect(0,0,X,q);const{x:ge,y:ne,w:pe,h:he}=g,se=l.current;se&&T.drawImage(se,ge,ne,pe,he),T.strokeStyle=C,T.lineWidth=x,T.strokeRect(x*.5,x*.5,X-x,q-x);const ue=e.current,Ae=ue?.getViewBounds?.(),H=ue?.getViewCorners?.(),Le=Array.isArray(H)&&H.length>=4&&H.every(be=>Array.isArray(be)&&be.length>=2&&Number.isFinite(be[0])&&Number.isFinite(be[1]))?H:null,we=gt(Ae)?Ae:gt(u.current)?u.current:null;gt(Ae)&&(u.current=Ae);const de=pe/Math.max(1,t.width),V=he/Math.max(1,t.height),$=P==="dash";if(Le){const be=Le.map(W=>[ge+W[0]*de,ne+W[1]*V]),I=Ua(be,ge,ne,ge+pe,ne+he);if(I.length>=3){T.beginPath();for(let W=0;W<I.length;W+=1)W===0?T.moveTo(I[W][0],I[W][1]):T.lineTo(I[W][0],I[W][1]);T.closePath(),T.fillStyle=U,T.fill(),T.strokeStyle=M,T.lineWidth=2.25,$?Lr(T,I,4,3):T.stroke();return}}if(!we)return;const ie=L(ge+we[0]*de,ge,ge+pe),oe=L(ne+we[1]*V,ne,ne+he),Se=L(ge+we[2]*de,ge,ge+pe),De=L(ne+we[3]*V,ne,ne+he),G=Math.max(1,Se-ie),ye=Math.max(1,De-oe);if(T.fillStyle=U,T.fillRect(ie,oe,G,ye),T.strokeStyle=M,T.lineWidth=2.25,$){const be=[[ie+.5,oe+.5],[ie+.5+Math.max(1,G-1),oe+.5],[ie+.5+Math.max(1,G-1),oe+.5+Math.max(1,ye-1)],[ie+.5,oe+.5+Math.max(1,ye-1)]];Lr(T,be,4,3)}else T.strokeRect(ie+.5,oe+.5,Math.max(1,G-1),Math.max(1,ye-1))},[d,m,g,S,C,x,e,t.width,t.height,U,M,P]),j=p.useCallback(()=>{h.current||(h.current=!0,c.current=requestAnimationFrame(()=>{h.current=!1,c.current=null,Y()}))},[Y]),ce=p.useCallback((_,T)=>{const X=a.current;if(!X)return null;const q=X.getBoundingClientRect();if(!q.width||!q.height)return null;const te=q.width/d,le=q.height/m,re=g.x*te,ge=g.y*le,ne=g.w*te,pe=g.h*le,he=L((_-q.left-re)/ne,0,1),se=L((T-q.top-ge)/pe,0,1);return[he*t.width,se*t.height]},[t.width,t.height,d,m,g]),J=p.useCallback((_,T)=>{const X=e.current;if(!X)return;if(X.setViewCenter){X.setViewCenter(_,T),j();return}const q=X.getViewBounds?.(),te=gt(q)?q:gt(u.current)?u.current:null;if(!te)return;const le=Math.max(1e-6,te[2]-te[0]),re=Math.max(1e-6,te[3]-te[1]);X.setViewState({offsetX:_-le*.5,offsetY:T-re*.5}),j()},[e,j]),Te=p.useCallback(_=>{if(!O||_.button!==0)return;const T=a.current;if(!T)return;const X=ce(_.clientX,_.clientY);X&&(_.preventDefault(),_.stopPropagation(),T.setPointerCapture(_.pointerId),f.current={active:!0,pointerId:_.pointerId},J(X[0],X[1]))},[O,ce,J]),Pe=p.useCallback(_=>{const T=f.current;if(!T.active||T.pointerId!==_.pointerId)return;const X=ce(_.clientX,_.clientY);X&&(_.preventDefault(),_.stopPropagation(),J(X[0],X[1]))},[ce,J]),Re=p.useCallback(_=>{const T=f.current;if(!T.active||T.pointerId!==_.pointerId)return;const X=a.current;if(X&&X.hasPointerCapture(_.pointerId))try{X.releasePointerCapture(_.pointerId)}catch{}f.current={active:!1,pointerId:null},j()},[j]);return p.useEffect(()=>{let _=!1;l.current=null,j();const T=0,X=2**(t.maxTierZoom-T),q=Math.ceil(t.width/X),te=Math.ceil(t.height/X),le=Math.max(1,Math.ceil(q/t.tileSize)),re=Math.max(1,Math.ceil(te/t.tileSize)),ge=le*re;if(!N||ge>A)return;const ne=document.createElement("canvas");ne.width=Math.max(1,Math.round(g.w)),ne.height=Math.max(1,Math.round(g.h));const pe=ne.getContext("2d");if(!pe)return;pe.fillStyle=S,pe.fillRect(0,0,ne.width,ne.height);const he=[];for(let se=0;se<re;se+=1)for(let ue=0;ue<le;ue+=1){const Ae=ue*t.tileSize*X,H=se*t.tileSize*X,Le=Math.min((ue+1)*t.tileSize,q)*X,we=Math.min((se+1)*t.tileSize,te)*X;he.push({url:Vn(t,T,ue,se),bounds:[Ae,H,Le,we]})}return Promise.allSettled(he.map(async se=>{const ue=ka(se.url,n),Ae=await fetch(se.url,{headers:ue?{Authorization:n}:void 0});if(!Ae.ok)throw new Error(`HTTP ${Ae.status}`);const H=await createImageBitmap(await Ae.blob());return{tile:se,bitmap:H}})).then(se=>{if(_){for(const H of se)H.status==="fulfilled"&&H.value.bitmap.close();return}const ue=ne.width/Math.max(1,t.width),Ae=ne.height/Math.max(1,t.height);for(const H of se){if(H.status!=="fulfilled")continue;const{tile:{bounds:Le},bitmap:we}=H.value,de=Le[0]*ue,V=Le[1]*Ae,$=Math.max(1,(Le[2]-Le[0])*ue),ie=Math.max(1,(Le[3]-Le[1])*Ae);pe.drawImage(we,de,V,$,ie),we.close()}l.current=ne,j()}),()=>{_=!0}},[t,n,g,S,N,A,j]),p.useEffect(()=>{j()},[j]),p.useEffect(()=>tn(()=>j()),[j]),p.useEffect(()=>{if(i)return i.current=j,()=>{i.current===j&&(i.current=null)}},[i,j]),p.useEffect(()=>()=>{f.current={active:!1,pointerId:null},c.current!==null&&(cancelAnimationFrame(c.current),c.current=null),h.current=!1},[]),He.jsxs("div",{className:o,style:K,children:[He.jsx("canvas",{ref:a,style:{width:"100%",height:"100%",display:"block",borderRadius:"inherit"},onPointerDown:Te,onPointerMove:Pe,onPointerUp:Re,onPointerCancel:Re,onContextMenu:_=>{_.preventDefault()},onWheel:_=>{_.preventDefault(),_.stopPropagation()}}),B&&He.jsx("button",{type:"button","aria-label":"Hide overview map",onClick:_=>{_.stopPropagation(),B()},style:z?{...z}:{...za},children:F??"×"})]})}const kr="__patch_layer__",Ya=[];function Wa({regions:t,strokeStyle:e}){const{rendererRef:n,registerDrawCallback:r,unregisterDrawCallback:i,requestOverlayRedraw:o}=at(),s=t??Ya,a=p.useMemo(()=>je(li,e),[e]),l=p.useMemo(()=>{const c=[];for(let h=0;h<s.length;h+=1){const d=s[h],m=jt(d.coordinates);m.length!==0&&c.push({region:d,regionIndex:h,regionKey:d.id??h,polygons:m})}return c},[s]),u=p.useCallback(c=>{const h=n.current;if(!h||c.length===0)return[];const d=new Array(c.length);for(let m=0;m<c.length;m+=1){const g=qe(h.worldToScreen(c[m][0],c[m][1]));if(!g)return[];d[m]=g}return d},[]),f=p.useRef({prepared:l,resolvedStrokeStyle:a,worldToScreenPoints:u});return f.current={prepared:l,resolvedStrokeStyle:a,worldToScreenPoints:u},p.useEffect(()=>(r(kr,20,h=>{const{prepared:d,resolvedStrokeStyle:m,worldToScreenPoints:g}=f.current;for(const y of d)for(const b of y.polygons){const x=g(b.outer);x.length>=4&&Be(h,x,m,!0,!1);for(const A of b.holes){const S=g(A);S.length>=4&&Be(h,S,m,!0,!1)}}}),()=>i(kr)),[r,i]),p.useEffect(()=>{o()},[l,a,o]),null}function Rt(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return null;const n=dt(e??[]);if(n.length===0){const m={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return t.fillModes instanceof Uint8Array&&(m.fillModes=new Uint8Array(0)),t.ids instanceof Uint32Array&&(m.ids=new Uint32Array(0)),m}const r=st(t),i=t.positions,o=t.paletteIndices,s=t.fillModes instanceof Uint8Array&&t.fillModes.length>=r?t.fillModes:null,a=t.ids instanceof Uint32Array&&t.ids.length>=r?t.ids:null,l=new Float32Array(r*2),u=new Uint16Array(r),f=s?new Uint8Array(r):null,c=a?new Uint32Array(r):null;let h=0;for(let m=0;m<r;m+=1){const g=i[m*2],y=i[m*2+1];St(g,y,n)&&(l[h*2]=g,l[h*2+1]=y,u[h]=o[m],f&&(f[h]=s[m]),c&&(c[h]=a[m]),h+=1)}const d={count:h,positions:l.subarray(0,h*2),paletteIndices:u.subarray(0,h)};return f&&(d.fillModes=f.subarray(0,h)),c&&(d.ids=c.subarray(0,h)),d}function Ni(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return new Uint32Array(0);const n=dt(e??[]);if(n.length===0)return new Uint32Array(0);const r=st(t);if(r===0)return new Uint32Array(0);const i=t.positions,o=new Uint32Array(r);let s=0;for(let a=0;a<r;a+=1){const l=i[a*2],u=i[a*2+1];St(l,u,n)&&(o[s]=a,s+=1)}return o.subarray(0,s)}let Dt=null;const Xa=`
103
+ }`;class aa{constructor(){E(this,"canvas");E(this,"gl");E(this,"accumProgram");E(this,"colorProgram");E(this,"accumVao");E(this,"colorVao");E(this,"pointBuffer");E(this,"quadBuffer");E(this,"accumTexture");E(this,"gradientTexture");E(this,"framebuffer");E(this,"accumInternalFormat");E(this,"accumTextureFormat");E(this,"accumTextureType");E(this,"uAccumResolution");E(this,"uAccumPointSize");E(this,"uAccumCoreRatio");E(this,"uAccumPointAlpha");E(this,"uColorAccumTexture");E(this,"uColorGradientTexture");E(this,"uColorOpacity");E(this,"uColorCutoff");E(this,"uColorGain");E(this,"uColorResolution");E(this,"uColorGamma");E(this,"uColorBias");E(this,"uColorStretch");E(this,"pointCapacity",0);E(this,"interleavedCapacity",0);E(this,"interleavedBuffer",null);E(this,"gradientKey","");this.canvas=document.createElement("canvas");const e=this.canvas.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,preserveDrawingBuffer:!0,premultipliedAlpha:!0,powerPreference:"high-performance"});if(!e)throw new Error("WebGL2 is not available for heatmap rendering.");this.gl=e;const r=!!e.getExtension("EXT_color_buffer_float");this.accumInternalFormat=r?e.RGBA16F:e.RGBA8,this.accumTextureFormat=e.RGBA,this.accumTextureType=r?e.HALF_FLOAT:e.UNSIGNED_BYTE,this.accumProgram=bt(e,ra,ia),this.colorProgram=bt(e,oa,sa);const i=e.createVertexArray(),o=e.createVertexArray(),s=e.createBuffer(),a=e.createBuffer(),l=e.createTexture(),u=e.createTexture(),f=e.createFramebuffer();if(!i||!o||!s||!a||!l||!u||!f)throw new Error("Failed to allocate heatmap WebGL resources.");this.accumVao=i,this.colorVao=o,this.pointBuffer=s,this.quadBuffer=a,this.accumTexture=l,this.gradientTexture=u,this.framebuffer=f;const c=e.getUniformLocation(this.accumProgram,"uResolution"),h=e.getUniformLocation(this.accumProgram,"uPointSize"),d=e.getUniformLocation(this.accumProgram,"uCoreRatio"),m=e.getUniformLocation(this.accumProgram,"uPointAlpha"),g=e.getUniformLocation(this.colorProgram,"uAccumTexture"),b=e.getUniformLocation(this.colorProgram,"uGradientTexture"),y=e.getUniformLocation(this.colorProgram,"uOpacity"),w=e.getUniformLocation(this.colorProgram,"uCutoff"),A=e.getUniformLocation(this.colorProgram,"uGain"),S=e.getUniformLocation(this.colorProgram,"uGamma"),C=e.getUniformLocation(this.colorProgram,"uBias"),M=e.getUniformLocation(this.colorProgram,"uStretch"),P=e.getUniformLocation(this.colorProgram,"uResolution");if(!c||!h||!d||!m||!g||!b||!y||!w||!A||!S||!C||!M||!P)throw new Error("Failed to resolve heatmap WebGL uniforms.");this.uAccumResolution=c,this.uAccumPointSize=h,this.uAccumCoreRatio=d,this.uAccumPointAlpha=m,this.uColorAccumTexture=g,this.uColorGradientTexture=b,this.uColorOpacity=y,this.uColorCutoff=w,this.uColorGain=A,this.uColorGamma=S,this.uColorBias=C,this.uColorStretch=M,this.uColorResolution=P,e.bindVertexArray(this.accumVao),e.bindBuffer(e.ARRAY_BUFFER,this.pointBuffer),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const O=e.getAttribLocation(this.accumProgram,"aCenter"),W=e.getAttribLocation(this.accumProgram,"aWeight");if(O<0||W<0)throw new Error("Failed to resolve heatmap WebGL attributes.");e.enableVertexAttribArray(O),e.vertexAttribPointer(O,2,e.FLOAT,!1,12,0),e.enableVertexAttribArray(W),e.vertexAttribPointer(W,1,e.FLOAT,!1,12,8),e.bindVertexArray(null),e.bindVertexArray(this.colorVao),e.bindBuffer(e.ARRAY_BUFFER,this.quadBuffer),e.bufferData(e.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,1,1]),e.STATIC_DRAW);const L=e.getAttribLocation(this.colorProgram,"aPosition");if(L<0)throw new Error("Failed to resolve heatmap color position attribute.");e.enableVertexAttribArray(L),e.vertexAttribPointer(L,2,e.FLOAT,!1,8,0),e.bindVertexArray(null),e.bindBuffer(e.ARRAY_BUFFER,null),e.bindTexture(e.TEXTURE_2D,this.accumTexture),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.bindTexture(e.TEXTURE_2D,null),e.bindTexture(e.TEXTURE_2D,this.gradientTexture),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.bindTexture(e.TEXTURE_2D,null),this.ensureCanvasSize(1,1)}render(e){if(e.count<=0||e.width<=0||e.height<=0)return!1;this.ensureCanvasSize(e.width,e.height),this.ensureGradientTexture(e.gradient),this.uploadPointData(e.positions,e.weights,e.count);const n=this.gl;return n.disable(n.SCISSOR_TEST),n.disable(n.DEPTH_TEST),n.disable(n.CULL_FACE),n.bindFramebuffer(n.FRAMEBUFFER,this.framebuffer),n.viewport(0,0,e.width,e.height),n.clearColor(0,0,0,0),n.clear(n.COLOR_BUFFER_BIT),n.useProgram(this.accumProgram),n.bindVertexArray(this.accumVao),n.uniform2f(this.uAccumResolution,e.width,e.height),n.uniform1f(this.uAccumPointSize,Math.max(1,(e.kernelRadiusPx+e.blurRadiusPx)*2)),n.uniform1f(this.uAccumCoreRatio,e.kernelRadiusPx/Math.max(1e-6,e.kernelRadiusPx+e.blurRadiusPx)),n.uniform1f(this.uAccumPointAlpha,Math.max(0,e.pointAlpha)),n.enable(n.BLEND),n.blendEquation(n.FUNC_ADD),n.blendFuncSeparate(n.ONE,n.ONE,n.ONE,n.ONE),n.drawArrays(n.POINTS,0,e.count),n.disable(n.BLEND),n.bindVertexArray(null),n.bindFramebuffer(n.FRAMEBUFFER,null),n.viewport(0,0,e.width,e.height),n.clearColor(0,0,0,0),n.clear(n.COLOR_BUFFER_BIT),n.useProgram(this.colorProgram),n.bindVertexArray(this.colorVao),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,this.accumTexture),n.uniform1i(this.uColorAccumTexture,0),n.activeTexture(n.TEXTURE1),n.bindTexture(n.TEXTURE_2D,this.gradientTexture),n.uniform1i(this.uColorGradientTexture,1),n.uniform1f(this.uColorOpacity,e.opacity),n.uniform1f(this.uColorCutoff,e.cutoff??.008),n.uniform1f(this.uColorGain,e.gain??2.6),n.uniform1f(this.uColorGamma,e.gamma??1),n.uniform1f(this.uColorBias,e.bias??0),n.uniform1f(this.uColorStretch,e.stretch??1),n.uniform2f(this.uColorResolution,e.width,e.height),n.drawArrays(n.TRIANGLE_STRIP,0,4),n.bindVertexArray(null),n.bindTexture(n.TEXTURE_2D,null),n.flush(),!0}destroy(){const e=this.gl;e.deleteTexture(this.accumTexture),e.deleteTexture(this.gradientTexture),e.deleteFramebuffer(this.framebuffer),e.deleteBuffer(this.pointBuffer),e.deleteBuffer(this.quadBuffer),e.deleteVertexArray(this.accumVao),e.deleteVertexArray(this.colorVao),e.deleteProgram(this.accumProgram),e.deleteProgram(this.colorProgram),this.canvas.width=0,this.canvas.height=0}ensureCanvasSize(e,n){const r=Math.max(1,Math.round(e)),i=Math.max(1,Math.round(n));this.canvas.width!==r&&(this.canvas.width=r),this.canvas.height!==i&&(this.canvas.height=i);const o=this.gl;o.bindTexture(o.TEXTURE_2D,this.accumTexture),o.texImage2D(o.TEXTURE_2D,0,this.accumInternalFormat,r,i,0,this.accumTextureFormat,this.accumTextureType,null),o.bindFramebuffer(o.FRAMEBUFFER,this.framebuffer),o.framebufferTexture2D(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,this.accumTexture,0);const s=o.checkFramebufferStatus(o.FRAMEBUFFER);if(o.bindFramebuffer(o.FRAMEBUFFER,null),s!==o.FRAMEBUFFER_COMPLETE)throw new Error(`Heatmap framebuffer incomplete: ${s}`)}ensureGradientTexture(e){const n=e.join("|");if(this.gradientKey===n)return;const r=document.createElement("canvas");r.width=256,r.height=1;const i=r.getContext("2d");if(!i)throw new Error("Failed to create heatmap gradient canvas.");const o=i.createLinearGradient(0,0,256,0),s=e.length>1?e:["#00000000","#3876FF","#4CDDDD","#FFE75C","#FF8434","#FF3434"],a=1/Math.max(1,s.length-1);for(let f=0;f<s.length;f+=1)o.addColorStop(f*a,s[f]);i.clearRect(0,0,256,1),i.fillStyle=o,i.fillRect(0,0,256,1);const l=i.getImageData(0,0,256,1).data,u=this.gl;u.bindTexture(u.TEXTURE_2D,this.gradientTexture),u.texImage2D(u.TEXTURE_2D,0,u.RGBA,256,1,0,u.RGBA,u.UNSIGNED_BYTE,l),u.bindTexture(u.TEXTURE_2D,null),this.gradientKey=n}uploadPointData(e,n,r){const i=this.gl,o=r*3,s=o*4;i.bindBuffer(i.ARRAY_BUFFER,this.pointBuffer),r>this.pointCapacity&&(i.bufferData(i.ARRAY_BUFFER,s,i.DYNAMIC_DRAW),this.pointCapacity=r),o>this.interleavedCapacity&&(this.interleavedCapacity=o,this.interleavedBuffer=new Float32Array(o));const a=this.interleavedBuffer;if(!a)throw new Error("Failed to allocate heatmap upload buffer.");for(let l=0;l<r;l+=1){const u=l*2,f=l*3;a[f]=e[u]??0,a[f+1]=e[u+1]??0,a[f+2]=n[l]??0}i.bufferSubData(i.ARRAY_BUFFER,0,a.subarray(0,o)),i.bindBuffer(i.ARRAY_BUFFER,null)}}const Pr="__open_plant_heatmap_layer__",la=["#00000000","#3876FF","#4CDDDD","#FFE75C","#FF8434","#FF3434"],ca=3,ua=2,fa=.9,ha=52e3,da="screen",ma=2.2,En=128,Qt=1600,ga=1.9,pa=4.2,Rn=3e3,Ci=Math.SQRT2,ya=2048,ba=.9,Ze=16;function Mt(t,e){return e.maxTierZoom+Math.log2(Math.max(1e-6,t))}function Xn(t,e){return Math.max(1e-6,2**(t-e.maxTierZoom))}function xa(t,e,n){if(!Number.isFinite(n)||Math.abs(n)<1e-6)return Math.max(1e-6,t);const r=Mt(t,e)-n;return Xn(r,e)}function wa(t){return!Number.isFinite(t)||Math.abs(t)<1e-6?0:Math.round(t*1.5/Math.max(1e-6,Math.log2(Ci)))}function Mi(t){const e=F(t,0,Ze);return F(.55+Math.sqrt(Math.max(0,e))*.48,.55,6)}function Sa(t){const e=Math.max(0,t);return e<=1?.18:e<=2?.3:e<=4?.48:e<=8?.7:e<=16?.86:1}function Pi(t){return .022-F(t,0,Ze)/Ze*.015}function vi(t){const e=F(t,0,Ze);return .18+Math.pow(Math.max(0,e),.72)*.42+Math.log2(e+1)*.24}function Ti(t){return Mi(t)}function Ii(t){const n=F(t,0,Ze)/Ze;return F(.46-n*.34,.12,.46)}function _i(t,e,n){const i=F(t,0,Ze)/Ze,o=Mt(e,n),s=n.maxTierZoom-3.2,a=n.maxTierZoom-1.15,l=F((o-s)/Math.max(1e-6,a-s),0,1),u=1.12+Math.pow(i,.82)*1.18,f=1+l*(.48+i*.92);return u*f}function Ea(t,e,n){const r=Math.max(0,t),i=Math.max(1e-6,e),o=Math.log1p(r)/Math.log1p(i);return F(o,0,1)}function Ra(t){return ba}function Aa(t,e){if(t.length===0)return 1;const n=Math.min(t.length,ya),r=new Array(n);let i=1;for(let f=0;f<n;f+=1){const c=Math.min(t.length-1,Math.floor((f+.5)*t.length/n)),h=Math.max(0,t[c]?.weight??0);r[f]=h,h>i&&(i=h)}for(let f=0;f<t.length;f+=1){const c=Math.max(0,t[f]?.weight??0);c>i&&(i=c)}r.sort((f,c)=>f-c);const o=Ra(),s=Math.max(0,Math.min(r.length-1,Math.floor((r.length-1)*o))),a=r[s]??i;return Math.max(1,Math.min(i,Math.max(a*1.08,i*.14)))}function Li(t,e,n){const r=Mt(t,e),i=e.maxTierZoom-2.45,o=e.maxTierZoom-1.2,s=r<=i?1:r>=o?0:(()=>{const a=F((r-i)/Math.max(1e-6,o-i),0,1);return 1-a*a*(3-2*a)})();return F(s,0,1)}function Ca(t){if(t>=1)return 1;const e=1/Math.max(t,1e-6);return 1+Math.log2(e)*.28}function Ma(t,e,n,r){const i=Math.max(1,t,e),o=typeof window>"u"?1:F(window.devicePixelRatio||1,1,2.4),s=r<=.35?1.42:r<=.55?1.26:r<=.8?1.14:1,a=n>16e4?896:n>8e4?1152:n>3e4?1408:Qt,l=En/i,u=Qt/i;return F(a*o*s/i,l,u)}function An(t){const e=t.heatmapScale??Ma(t.logicalWidth,t.logicalHeight,t.totalPointCount,t.rawZoom),n=Math.max(En,Math.min(Qt,Math.round(t.logicalWidth*e))),r=Math.max(En,Math.min(Qt,Math.round(t.logicalHeight*e))),i=n/Math.max(1,t.logicalWidth),o=r/Math.max(1,t.logicalHeight),s=Math.min(i,o),a=Math.max(1e-6,t.rawZoom),l=Math.max(.75,t.radius*ga*s),u=Math.max(.6,t.blur*pa*s),f=(l+u)/Math.max(1e-6,a*s),c=Math.max(f*.4,.62/Math.max(1e-6,a*s));return{heatmapScale:e,rasterWidth:n,rasterHeight:r,rasterScaleX:i,rasterScaleY:o,rawZoom:a,kernelRadiusPx:l,blurRadiusPx:u,outerWorldRadius:f,desiredCellWorldSize:c}}function Wn(t){if(!t)return 0;const e=Math.floor(t.positions.length/2),n=t.weights?t.weights.length:Number.MAX_SAFE_INTEGER;return Math.max(0,Math.min(Math.floor(t.count),e,n))}function Ft(t,e){const n=Number.isFinite(t)?Math.round(t*1024):0;return Math.imul(e^n,73244475)>>>0}function Pa(t,e,n=2654435769){let r=Math.imul(n^(t|0),2246822507)>>>0;return r=Math.imul(r^(e|0),3266489909)>>>0,r^=r>>>16,r>>>0}function va(t){return(t>>>0)/4294967295}function Fi(t){let e=2166136261;for(let n=0;n<t.length;n+=1){const r=t[n];e=Math.imul(e^r.outer.length,16777619)>>>0;for(let i=0;i<r.outer.length;i+=1){const o=r.outer[i];e=Ft(o[0],e),e=Ft(o[1],e)}e=Math.imul(e^r.holes.length,16777619)>>>0;for(let i=0;i<r.holes.length;i+=1){const o=r.holes[i];e=Math.imul(e^o.length,16777619)>>>0;for(let s=0;s<o.length;s+=1){const a=o[s];e=Ft(a[0],e),e=Ft(a[1],e)}}}return`${t.length}:${e>>>0}`}function Vn(t,e,n){return t.dataRef===e&&t.clipKey===n?!0:e?t.clipKey===n&&t.inputCount===Wn(e)&&t.positionsRef===e.positions&&t.weightsRef===e.weights:!1}function Ta(t,e,n,r){const i=Wn(t);if(!t||i<=0)return null;let o=new Float32Array(i),s=new Float32Array(i),a=new Float32Array(i),l=0,u=1/0,f=1/0,c=-1/0,h=-1/0;for(let A=0;A<i;A+=1){const S=t.positions[A*2],C=t.positions[A*2+1];if(!Number.isFinite(S)||!Number.isFinite(C)||e.length>0&&!St(S,C,e))continue;const M=t.weights?.[A],P=typeof M=="number"&&Number.isFinite(M)?Math.max(0,M):1;P<=0||(o[l]=S,s[l]=C,a[l]=P,l+=1,S<u&&(u=S),S>c&&(c=S),C<f&&(f=C),C>h&&(h=C))}if(l===0||!Number.isFinite(u)||!Number.isFinite(f)||!Number.isFinite(c)||!Number.isFinite(h))return null;l<i&&(o=o.slice(0,l),s=s.slice(0,l),a=a.slice(0,l));const d=[];for(let A=0;A<l;A+=1){const S=o[A],C=s[A];d.push({minX:S,minY:C,maxX:S,maxY:C,value:A})}const m=Ai(64);m.load(d);const g=Math.max(r?.width??0,r?.height??0,c-u,h-f,1),b=[];let y=.5,w=0;for(;y<=g&&w<32;)b.push(y),y*=Ci,w+=1;return b.length===0&&b.push(1),{dataRef:t,sourceRef:r,positionsRef:t.positions,weightsRef:t.weights,inputCount:i,clipRef:e,clipKey:n,pointCount:l,xs:o,ys:s,ws:a,pointIndex:m,cellSizes:b,levels:Array.from({length:b.length},()=>null)}}function Cn(t,e,n){const r=t.pointIndex.search([e[0]-n,e[1]-n,e[2]+n,e[3]+n]),i=new Array(r.length);let o=0;for(let s=0;s<r.length;s+=1){const a=r[s];a&&(i[o]=a.value,o+=1)}return i.length=o,i}function Di(t,e){const n=Math.max(Rn,e);return t<=n?1:F(n/Math.max(1,t),1/65536,1)}function Ni(t){return t>=1?1:Math.max(1,Math.round(1/Math.max(1e-6,t)))}function Ia(t,e){if(e>=1)return!0;const n=Pa(t,1374496523,1757159915);return va(n)<=F(e,0,1)}function Bi(t,e,n,r){const i=Math.max(1,n*r),o=Math.PI*e*e,s=Math.max(1,t)*o/i;return F(.085/Math.sqrt(Math.max(1,s)),.012,.075)}function vr(t,e,n,r){if(!Number.isFinite(t)||t<=0)return e;const i=e>=t?n:r;return t+(e-t)*F(i,0,1)}function _a(t){if(t.webgl!==void 0)return t.webgl;if(typeof document>"u")return t.webgl=null,null;try{t.webgl=new aa}catch(e){if(!t.webglWarningIssued&&typeof console<"u"&&typeof console.warn=="function"){const n=e instanceof Error?e.message:String(e);console.warn(`[open-plant] HeatmapLayer disabled because WebGL2 heatmap initialization failed: ${n}`),t.webglWarningIssued=!0}t.webgl=null}return t.webgl}function Tr(t,e){const n=[];for(let r=0;r<e.length;r+=1){const i=e[r];if(!i)continue;const o=t.worldToScreen(i[0],i[1]);if(!Array.isArray(o)||o.length<2)continue;const s=Number(o[0]),a=Number(o[1]);!Number.isFinite(s)||!Number.isFinite(a)||n.push([s,a])}return n}function La(t,e,n){if(n.length!==0){t.beginPath();for(let r=0;r<n.length;r+=1){const i=n[r],o=Tr(e,i.outer);o.length>=3&&Et(t,o,!0);for(let s=0;s<i.holes.length;s+=1){const a=Tr(e,i.holes[s]);a.length>=3&&Et(t,a,!0)}}t.clip("evenodd")}}function ki(t,e,n,r,i){const o=t.sourceData;return o&&o.sourceRef===i&&Vn(o,e,r)?o:(t.sourceData=Ta(e,n,r,i),t.fixedState=null,t.screenLevelIndex=-1,t.sourceData)}function Fa(t){const{sourceData:e,renderer:n,source:r,logicalWidth:i,logicalHeight:o,radius:s,blur:a,fixedZoom:l,maxRenderedPoints:u}=t,f=Math.max(1e-6,n.getViewState().zoom),c=l??Mt(f,r),h=Xn(c,r),d=An({logicalWidth:i,logicalHeight:o,totalPointCount:e.pointCount,rawZoom:h,radius:s,blur:a}),m=n.getViewBounds(),g=Cn(e,m,d.outerWorldRadius),b=Di(g.length,u),y=Ni(b),w=Math.min(d.rasterScaleX,d.rasterScaleY);return{dataRef:e.dataRef,positionsRef:e.positionsRef,weightsRef:e.weightsRef,inputCount:e.inputCount,clipRef:e.clipRef,clipKey:e.clipKey,referenceZoom:c,referenceRawZoom:h,heatmapScale:d.heatmapScale,kernelWorldRadius:d.kernelRadiusPx/Math.max(1e-6,h*w),blurWorldRadius:d.blurRadiusPx/Math.max(1e-6,h*w),sampleProbability:b,sampleStride:y,pointAlpha:Bi(g.length,d.kernelRadiusPx+d.blurRadiusPx,d.rasterWidth,d.rasterHeight)}}function Ir(t){const{ctx:e,runtime:n,renderer:r,source:i,logicalWidth:o,logicalHeight:s,frame:a,sourceData:l,visiblePointIndices:u,sampleProbability:f,sampleStride:c,pointAlpha:h,gradient:d,opacity:m,densityContrast:g,backgroundColor:b,clipPolygons:y}=t,w=_a(n);if(!w||u.length===0)return 0;const A=Math.min(u.length,Math.max(64,Math.ceil(u.length*Math.min(1,f*1.15))));A>n.webglCapacity&&(n.webglCapacity=A,n.webglPositions=new Float32Array(A*2),n.webglWeights=new Float32Array(A));const S=n.webglPositions,C=n.webglWeights;if(!S||!C)return 0;const M=a.kernelRadiusPx+a.blurRadiusPx,P=Ca(f);let O=0;for(let L=0;L<u.length;L+=1){const T=u[L];if(!Ia(T,f))continue;const D=l.xs[T],I=l.ys[T];if(!Number.isFinite(D)||!Number.isFinite(I))continue;const Y=r.worldToScreen(D,I);if(!Array.isArray(Y)||Y.length<2)continue;const $=Number(Y[0]),k=Number(Y[1]);if(!Number.isFinite($)||!Number.isFinite(k))continue;const ae=$*a.rasterScaleX,he=k*a.rasterScaleY;if(ae<-M||he<-M||ae>a.rasterWidth+M||he>a.rasterHeight+M)continue;const J=O*2;S[J]=ae,S[J+1]=he,C[O]=Math.max(0,(l.ws[T]??0)*P),O+=1}return O<=0||!w.render({width:a.rasterWidth,height:a.rasterHeight,positions:S,weights:C,count:O,kernelRadiusPx:a.kernelRadiusPx,blurRadiusPx:a.blurRadiusPx,pointAlpha:h,gradient:d,opacity:m,cutoff:Pi(g),gain:vi(g),gamma:Ti(g),bias:Ii(g),stretch:_i(g,a.rawZoom,i)})?0:(e.save(),y.length>0&&La(e,r,y),b&&(e.fillStyle=b,e.fillRect(0,0,o,s)),e.globalAlpha=1,e.imageSmoothingEnabled=!0,e.drawImage(w.canvas,0,0,a.rasterWidth,a.rasterHeight,0,0,o,s),e.restore(),O)}function Da(t){const{ctx:e,runtime:n,renderer:r,source:i,logicalWidth:o,logicalHeight:s,state:a}=t,l=ki(n,a.data,a.clipPolygons,a.clipKey,i);if(!l||l.cellSizes.length===0||l.pointCount<=0)return null;const u=Math.max(1e-6,r.getViewState().zoom),f=Li(u,i,a.zoomThreshold),c=r.getViewBounds();if(f<=.001)return{pointCount:l.pointCount,renderTimeMs:0,visiblePointCount:0,renderedBinCount:0,sampleStride:1,maxDensity:0};if(a.scaleMode!=="fixed-zoom"){const y=An({logicalWidth:o,logicalHeight:s,totalPointCount:l.pointCount,rawZoom:u,radius:a.radius,blur:a.blur}),w=Cn(l,c,y.outerWorldRadius);if(w.length===0)return{pointCount:l.pointCount,renderTimeMs:0,visiblePointCount:0,renderedBinCount:0,sampleStride:1,maxDensity:0};const A=Di(w.length,a.maxRenderedPoints),S=Ni(A),C=Bi(w.length,y.kernelRadiusPx+y.blurRadiusPx,y.rasterWidth,y.rasterHeight);n.screenLevelIndex=-1,n.screenSecondaryLevelIndex=-1,n.screenSecondaryLevelWeight=0,n.screenNormalizationMaxWeight=1,n.screenPointAlpha=vr(n.screenPointAlpha,C,.12,.08),n.screenVisibilityStrength=r.isViewAnimating()?vr(n.screenVisibilityStrength,f,.16,.12):f;const M=Ir({ctx:e,runtime:n,renderer:r,source:i,logicalWidth:o,logicalHeight:s,frame:y,sourceData:l,visiblePointIndices:w,sampleProbability:A,sampleStride:S,pointAlpha:n.screenPointAlpha*Math.max(.08,n.screenVisibilityStrength),gradient:a.gradient,opacity:a.opacity*n.screenVisibilityStrength,densityContrast:a.densityContrast,backgroundColor:a.backgroundColor,clipPolygons:a.clipPolygons});return{pointCount:l.pointCount,renderTimeMs:0,visiblePointCount:w.length,renderedBinCount:M,sampleStride:S,maxDensity:Math.round(n.screenPointAlpha*255)}}const h=n.fixedState;if(!h)return null;const d=An({logicalWidth:o,logicalHeight:s,totalPointCount:l.pointCount,rawZoom:u,radius:a.radius,blur:a.blur,heatmapScale:h.heatmapScale}),m=Math.min(d.rasterScaleX,d.rasterScaleY);d.kernelRadiusPx=Math.max(.75,h.kernelWorldRadius*u*m),d.blurRadiusPx=Math.max(.6,h.blurWorldRadius*u*m),d.outerWorldRadius=h.kernelWorldRadius+h.blurWorldRadius;const g=Cn(l,c,d.outerWorldRadius);if(g.length===0)return{pointCount:l.pointCount,renderTimeMs:0,visiblePointCount:0,renderedBinCount:0,sampleStride:1,maxDensity:0};n.screenPointAlpha=h.pointAlpha,n.screenVisibilityStrength=f;const b=Ir({ctx:e,runtime:n,renderer:r,source:i,logicalWidth:o,logicalHeight:s,frame:d,sourceData:l,visiblePointIndices:g,sampleProbability:h.sampleProbability,sampleStride:h.sampleStride,pointAlpha:h.pointAlpha*Math.max(.08,f),gradient:a.gradient,opacity:a.opacity*f,densityContrast:a.densityContrast,backgroundColor:a.backgroundColor,clipPolygons:a.clipPolygons});return{pointCount:l.pointCount,renderTimeMs:0,visiblePointCount:g.length,renderedBinCount:b,sampleStride:h.sampleStride,maxDensity:Math.round(h.pointAlpha*255)}}function Na({data:t,visible:e=!0,opacity:n=fa,radius:r=ca,blur:i=ua,gradient:o=la,backgroundColor:s=null,scaleMode:a=da,fixedZoom:l,zoomThreshold:u=0,densityContrast:f=ma,clipToRegions:c,zIndex:h=5,maxRenderedPoints:d=ha,onStats:m}){const{rendererRef:g,source:b,registerDrawCallback:y,unregisterDrawCallback:w,requestOverlayRedraw:A}=st(),S=p.useMemo(()=>{const O=(c??[]).map(W=>ht(W?.coordinates)).filter(W=>W!=null);return dt(O)},[c]),C=p.useMemo(()=>Fi(S),[S]),M=p.useRef({sourceData:null,fixedState:null,screenLevelIndex:-1,screenSecondaryLevelIndex:-1,screenSecondaryLevelWeight:0,screenPointAlpha:0,screenNormalizationMaxWeight:1,screenVisibilityStrength:1,webgl:void 0,webglWarningIssued:!1,webglPositions:null,webglWeights:null,webglCapacity:0}),P=p.useRef({data:t,visible:e,opacity:n,radius:F(r,.05,128),blur:F(i,.05,128),gradient:o,backgroundColor:s,scaleMode:a,fixedZoom:l,zoomThreshold:u,densityContrast:F(f,0,Ze),clipPolygons:S,clipKey:C,maxRenderedPoints:Math.max(Rn,Math.floor(d)),onStats:m});return P.current={data:t,visible:e,opacity:n,radius:F(r,.05,128),blur:F(i,.05,128),gradient:o,backgroundColor:s,scaleMode:a,fixedZoom:l,zoomThreshold:u,densityContrast:F(f,0,Ze),clipPolygons:S,clipKey:C,maxRenderedPoints:Math.max(Rn,Math.floor(d)),onStats:m},p.useEffect(()=>(y(Pr,h,(W,L,T)=>{const D=P.current,I=M.current,Y=g.current;if(!D.visible||!D.data||!Y||!b)return;const $=ki(I,D.data,D.clipPolygons,D.clipKey,b);if(!$)return;D.scaleMode==="fixed-zoom"&&(!I.fixedState||!Vn(I.fixedState,D.data,D.clipKey)||D.fixedZoom!==void 0&&Math.abs(I.fixedState.referenceZoom-D.fixedZoom)>1e-6)?I.fixedState=Fa({sourceData:$,renderer:Y,source:b,logicalWidth:L,logicalHeight:T,radius:D.radius,blur:D.blur,fixedZoom:D.fixedZoom,zoomThreshold:D.zoomThreshold,densityContrast:D.densityContrast,maxRenderedPoints:D.maxRenderedPoints}):D.scaleMode!=="fixed-zoom"&&(I.fixedState=null);const ae=performance.now(),he=Da({ctx:W,runtime:I,renderer:Y,source:b,logicalWidth:L,logicalHeight:T,state:D});!he||!D.onStats||D.onStats({...he,renderTimeMs:performance.now()-ae})}),()=>{w(Pr),M.current.sourceData=null,M.current.fixedState=null,M.current.screenLevelIndex=-1,M.current.screenSecondaryLevelIndex=-1,M.current.screenSecondaryLevelWeight=0,M.current.screenPointAlpha=0,M.current.screenNormalizationMaxWeight=1,M.current.screenVisibilityStrength=1,M.current.webgl?.destroy(),M.current.webgl=void 0,M.current.webglPositions=null,M.current.webglWeights=null,M.current.webglCapacity=0}),[y,w,g,b,h]),p.useEffect(()=>{M.current.sourceData=null,M.current.fixedState=null,M.current.screenLevelIndex=-1,M.current.screenSecondaryLevelIndex=-1,M.current.screenSecondaryLevelWeight=0,M.current.screenPointAlpha=0,M.current.screenNormalizationMaxWeight=1,M.current.screenVisibilityStrength=1,A()},[t?.positions,t?.weights,t?.count,C,A]),p.useEffect(()=>{M.current.fixedState=null,M.current.screenSecondaryLevelIndex=-1,M.current.screenSecondaryLevelWeight=0,M.current.screenPointAlpha=0,M.current.screenNormalizationMaxWeight=1,M.current.screenVisibilityStrength=1,A()},[r,i,a,l,u,f,d,A]),p.useEffect(()=>{A()},[e,n,o,s,A]),null}const Ba={applyZoomThreshold:xa,buildClipKey:Fi,resolveCellSupportFactor:Sa,resolveContinuousZoom:Mt,resolveDensityCutoff:Pi,resolveDensityBias:Ii,resolveDensityGain:vi,resolveDensityGamma:Ti,resolveDensityStretch:_i,resolveNormalizedDensityWeight:Ea,resolveNormalizationUpperWeight:Aa,resolveDensityWeightExponent:Mi,resolveRawZoomFromContinuousZoom:Xn,resolvePointCount:Wn,resolveThresholdLevelBias:wa,resolveZoomVisibilityStrength:Li,isSameHeatmapInput:Vn},_r="__overlay_layer__";function ka({shapes:t}){const{rendererRef:e,rendererSerial:n,source:r,registerDrawCallback:i,unregisterDrawCallback:o,requestOverlayRedraw:s}=st(),a=p.useCallback(u=>{const f=e.current;if(!f||u.length===0)return[];const c=new Array(u.length);for(let h=0;h<u.length;h+=1){const d=He(f.worldToScreen(u[h][0],u[h][1]));if(!d)return[];c[h]=d}return c},[]),l=p.useRef({shapes:t,worldToScreenPoints:a,source:r});return l.current={shapes:t,worldToScreenPoints:a,source:r},p.useEffect(()=>(i(_r,30,f=>{const{shapes:c,worldToScreenPoints:h,source:d}=l.current;if(!Array.isArray(c)||c.length===0||!d)return;const m=h(ze([[0,0],[d.width,0],[d.width,d.height],[0,d.height]]));Si({ctx:f,overlayShapes:c,imageOuterRing:m,worldToScreenPoints:h,baseStrokeStyle:$e})}),()=>o(_r)),[i,o]),p.useEffect(()=>{s()},[n,t,r,s]),null}function Ua(t){return Array.isArray(t?.classes)?t.classes.map(e=>({classId:String(e?.classId??""),className:String(e?.className??""),classColor:String(e?.classColor??"")})):[]}function Lr(t){return String(t??"").replace(/\/+$/,"")}function Ui(t){const e=String(t??"");return e.startsWith("/")?e:`/${e}`}function za(t){const e=Lr(t);if(!e)return"";if(/\/TileGroup\d+$/i.test(e))return e;let n=null;try{n=new URL(e)}catch{n=null}if(n){const r=`${n.protocol}//${n.host}`,i=Lr(n.pathname||"");return/\/ims$/i.test(i)?`${r}${i}`:/\/tiles$/i.test(i)?`${r}${i}`:`${r}${i}/tiles`}return/\/ims$/i.test(e)?"/ims":/\/tiles$/i.test(e)?`${e}`:`${e}/tiles`}function Oa(t,e){const n=t?.imsInfo??{},r=!!t?.imsInfo,i=Number(n.width??t?.width??0),o=Number(n.height??t?.height??0),s=Number(n.tileSize??t?.tileSize??0),a=Number(n.zoom??t?.zoom??0),l=String(n.path??t?.path??""),u=Number(n.mpp??t?.mpp??0);if(!i||!o||!s||!l)throw new Error("Incomplete image metadata: width/height/tileSize/path required");const f=Ui(l),c=za(e),h=t?.tileUrlBuilder??(r?(d,m,g)=>`${c}${f}/${d}/${g}_${m}.webp`:void 0);return{id:t?._id||t?.id||"unknown",name:t?.name||"unknown",width:i,height:o,mpp:Number.isFinite(u)&&u>0?u:void 0,tileSize:s,maxTierZoom:Number.isFinite(a)?Math.max(0,Math.floor(a)):0,tilePath:l,tileBaseUrl:e,tileUrlBuilder:h}}function Gn(t,e,n,r){if(t.tileUrlBuilder)return t.tileUrlBuilder(e,n,r,t.tilePath,t.tileBaseUrl);const i=Ui(t.tilePath);return`${t.tileBaseUrl}${i}/${e}/${r}_${n}.webp`}function Ya(t,e){if(!e)return!1;const n=new URL(t,typeof window<"u"?window.location.href:void 0).hostname.toLowerCase();return!(n.includes("amazonaws.com")||n.startsWith("s3.")||n.includes(".s3."))}const Oe={width:200,height:125,margin:16,position:"bottom-right",borderRadius:6,borderWidth:0,backgroundColor:"rgba(4, 10, 18, 0.88)",borderColor:"rgba(230, 244, 255, 0.35)",viewportBorderColor:"rgba(255, 106, 61, 0.95)",viewportBorderStyle:"dash",viewportFillColor:"transparent",interactive:!0,showThumbnail:!0,maxThumbnailTiles:16};function Fr(t,e,n,r){const i=e.length;if(!(i<3)){for(let o=0;o<i;o+=1){const s=e[o],a=e[(o+1)%i],l=Math.hypot(a[0]-s[0],a[1]-s[1]);if(l<1e-6)continue;const u=Math.max(1,Math.round((l+r)/(n+r))),f=u*n+(u-1)*r,c=l/Math.max(1e-6,f),h=n*c,d=r*c;t.beginPath(),t.moveTo(s[0],s[1]),t.lineTo(a[0],a[1]),t.setLineDash([h,d]),t.lineDashOffset=0,t.stroke()}t.setLineDash([]),t.lineDashOffset=0}}function Dr(t,e,n=1e-4){return Math.abs(t[0]-e[0])<=n&&Math.abs(t[1]-e[1])<=n}function Nr(t){const e=[];for(const n of t){const r=e[e.length-1];(!r||!Dr(r,n))&&e.push(n)}return e.length>1&&Dr(e[0],e[e.length-1])&&e.pop(),e}function Br(t,e,n){const r=e[0]-t[0];if(Math.abs(r)<1e-6)return[n,t[1]];const i=(n-t[0])/r;return[n,t[1]+(e[1]-t[1])*i]}function kr(t,e,n){const r=e[1]-t[1];if(Math.abs(r)<1e-6)return[t[0],n];const i=(n-t[1])/r;return[t[0]+(e[0]-t[0])*i,n]}function Ur(t,e,n,r,i){let o=Nr(t);if(o.length<3)return[];const s=[{inside:a=>a[0]>=e,intersect:(a,l)=>Br(a,l,e)},{inside:a=>a[0]<=r,intersect:(a,l)=>Br(a,l,r)},{inside:a=>a[1]>=n,intersect:(a,l)=>kr(a,l,n)},{inside:a=>a[1]<=i,intersect:(a,l)=>kr(a,l,i)}];for(const a of s){if(o.length===0)return[];const l=o;o=[];let u=l[l.length-1],f=a.inside(u);for(const c of l){const h=a.inside(c);h?(f||o.push(a.intersect(u,c)),o.push(c)):f&&o.push(a.intersect(u,c)),u=c,f=h}o=Nr(o)}return o.length>=3?o:[]}function ct(t,e,n=1){return typeof t!="number"||!Number.isFinite(t)?e:Math.max(n,t)}function Mn(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Xa(t){return t*Math.PI/180}function Wa(t,e,n){const r=Mn(n),i=Xa(r),o=Math.cos(i),s=Math.sin(i),a=t*.5,l=e*.5,u=-o*a-s*l,f=s*a-o*l,c=[[0,0],[t,0],[t,e],[0,e]].map(([b,y])=>[o*b+s*y+u,-s*b+o*y+f]);let h=1/0,d=1/0,m=-1/0,g=-1/0;for(const[b,y]of c)b<h&&(h=b),b>m&&(m=b),y<d&&(d=y),y>g&&(g=y);return{cos:o,sin:s,minX:h,minY:d,width:Math.max(1e-6,m-h),height:Math.max(1e-6,g-d),translateX:u,translateY:f}}function zr(t,e,n,r,i){const o=Wa(t,e,i),s=o.width/o.height,a=n/r;let l,u;return s>a?(l=n,u=n/s):(u=r,l=r*s),{contentX:(n-l)/2,contentY:(r-u)/2,contentWidth:l,contentHeight:u,metrics:o}}function Or(t,e,n){const{contentX:r,contentY:i,contentWidth:o,contentHeight:s,metrics:a}=n,l=a.cos*t+a.sin*e+a.translateX-a.minX,u=-a.sin*t+a.cos*e+a.translateY-a.minY;return[r+l/a.width*o,i+u/a.height*s]}function Va(t,e,n,r,i){const{metrics:o}=n,s=t+o.minX-o.translateX,a=e+o.minY-o.translateY,l=s*o.cos-a*o.sin,u=s*o.sin+a*o.cos;return[F(l,0,r),F(u,0,i)]}function Ga(t){return[[t[0],t[1]],[t[2],t[1]],[t[2],t[3]],[t[0],t[3]]]}function gt(t){return Array.isArray(t)&&t.length===4&&Number.isFinite(t[0])&&Number.isFinite(t[1])&&Number.isFinite(t[2])&&Number.isFinite(t[3])}const qa={position:"absolute",top:4,right:4,zIndex:1,width:18,height:18,borderRadius:999,border:"1px solid rgba(255,255,255,0.4)",background:"rgba(16, 17, 19, 0.85)",color:"#fff",fontSize:12,lineHeight:1,cursor:"pointer",padding:0,display:"flex",alignItems:"center",justifyContent:"center"};function Ha({source:t,projectorRef:e,authToken:n="",options:r,invalidateRef:i,className:o,style:s}){const a=p.useRef(null),l=p.useRef(null),u=p.useRef(null),f=p.useRef({active:!1,pointerId:null}),c=p.useRef(null),h=p.useRef(!1),d=ct(r?.width,Oe.width,64),m=ct(r?.height,Oe.height,48),g=ct(r?.margin,Oe.margin,0),b=ct(r?.borderRadius,Oe.borderRadius,0),y=ct(r?.borderWidth,Oe.borderWidth,0),w=Math.max(1,Math.round(ct(r?.maxThumbnailTiles,Oe.maxThumbnailTiles,1))),A=r?.backgroundColor||Oe.backgroundColor,S=r?.borderColor||Oe.borderColor,C=r?.viewportBorderColor||Oe.viewportBorderColor,M=r?.viewportBorderStyle==="stroke"||r?.viewportBorderStyle==="dash"?r.viewportBorderStyle:Oe.viewportBorderStyle,P=r?.viewportFillColor??Oe.viewportFillColor,O=r?.interactive??Oe.interactive,W=r?.showThumbnail??Oe.showThumbnail,L=r?.position||Oe.position,T=r?.onClose,D=r?.closeIcon,I=r?.closeButtonStyle,Y=p.useMemo(()=>{const N={};return L==="top-left"||L==="bottom-left"?N.left=g:N.right=g,L==="top-left"||L==="top-right"?N.top=g:N.bottom=g,{position:"absolute",...N,width:d,height:m,borderRadius:b,overflow:"hidden",zIndex:4,pointerEvents:O?"auto":"none",touchAction:"none",boxShadow:"0 10px 22px rgba(0, 0, 0, 0.3)",...s}},[g,L,d,m,b,O,s]),$=p.useCallback(()=>{const N=a.current;if(!N)return;const v=N.getContext("2d");if(!v)return;const z=d,ie=m,H=Math.max(1,window.devicePixelRatio||1),ge=Math.max(1,Math.round(z*H)),le=Math.max(1,Math.round(ie*H));(N.width!==ge||N.height!==le)&&(N.width=ge,N.height=le),v.setTransform(1,0,0,1,0,0),v.clearRect(0,0,N.width,N.height),v.setTransform(H,0,0,H,0,0),v.fillStyle=A,v.fillRect(0,0,z,ie);const ne=e.current,_e=Mn(ne?.getInitialRotationDeg?.()),ue=zr(t.width,t.height,z,ie,_e),{contentX:pe,contentY:de,contentWidth:re,contentHeight:oe,metrics:ce}=ue,q=l.current;q&&(v.save(),v.beginPath(),v.rect(pe,de,re,oe),v.clip(),v.translate(pe,de),v.scale(re/ce.width,oe/ce.height),v.transform(ce.cos,-ce.sin,ce.sin,ce.cos,ce.translateX-ce.minX,ce.translateY-ce.minY),v.drawImage(q,0,0,t.width,t.height),v.restore()),v.strokeStyle=S,v.lineWidth=y,v.strokeRect(y*.5,y*.5,z-y,ie-y);const Pe=ne?.getViewBounds?.(),Ee=ne?.getViewCorners?.(),ye=Array.isArray(Ee)&&Ee.length>=4&&Ee.every(j=>Array.isArray(j)&&j.length>=2&&Number.isFinite(j[0])&&Number.isFinite(j[1]))?Ee:null,V=gt(Pe)?Pe:gt(u.current)?u.current:null;gt(Pe)&&(u.current=Pe);const K=M==="dash";if(ye){const j=ye.map(X=>Or(X[0],X[1],ue)),Re=Ur(j,pe,de,pe+re,de+oe);if(Re.length>=3){v.beginPath();for(let X=0;X<Re.length;X+=1)X===0?v.moveTo(Re[X][0],Re[X][1]):v.lineTo(Re[X][0],Re[X][1]);v.closePath(),v.fillStyle=P,v.fill(),v.strokeStyle=C,v.lineWidth=2.25,K?Fr(v,Re,4,3):v.stroke();return}}if(!V)return;const fe=Ga(V).map(j=>Or(j[0],j[1],ue)),te=Ur(fe,pe,de,pe+re,de+oe);if(!(te.length<3)){v.beginPath();for(let j=0;j<te.length;j+=1)j===0?v.moveTo(te[j][0],te[j][1]):v.lineTo(te[j][0],te[j][1]);v.closePath(),v.fillStyle=P,v.fill(),v.strokeStyle=C,v.lineWidth=2.25,K?Fr(v,te,4,3):v.stroke()}},[d,m,A,S,y,e,t.width,t.height,P,C,M]),k=p.useCallback(()=>{h.current||(h.current=!0,c.current=requestAnimationFrame(()=>{h.current=!1,c.current=null,$()}))},[$]),ae=p.useCallback((N,v)=>{const z=a.current;if(!z)return null;const ie=z.getBoundingClientRect();if(!ie.width||!ie.height)return null;const H=e.current,ge=Mn(H?.getInitialRotationDeg?.()),le=zr(t.width,t.height,d,m,ge),ne=ie.width/d,_e=ie.height/m,ue=le.contentX*ne,pe=le.contentY*_e,de=le.contentWidth*ne,re=le.contentHeight*_e,oe=F((N-ie.left-ue)/de,0,1),ce=F((v-ie.top-pe)/re,0,1);return Va(oe*le.metrics.width,ce*le.metrics.height,le,t.width,t.height)},[e,t.width,t.height,d,m]),he=p.useCallback((N,v)=>{const z=e.current;if(!z)return;if(z.setViewCenter){z.setViewCenter(N,v),k();return}const ie=z.getViewBounds?.(),H=gt(ie)?ie:gt(u.current)?u.current:null;if(!H)return;const ge=Math.max(1e-6,H[2]-H[0]),le=Math.max(1e-6,H[3]-H[1]);z.setViewState({offsetX:N-ge*.5,offsetY:v-le*.5}),k()},[e,k]),J=p.useCallback(N=>{if(!O||N.button!==0)return;const v=a.current;if(!v)return;const z=ae(N.clientX,N.clientY);z&&(N.preventDefault(),N.stopPropagation(),v.setPointerCapture(N.pointerId),f.current={active:!0,pointerId:N.pointerId},he(z[0],z[1]))},[O,ae,he]),ve=p.useCallback(N=>{const v=f.current;if(!v.active||v.pointerId!==N.pointerId)return;const z=ae(N.clientX,N.clientY);z&&(N.preventDefault(),N.stopPropagation(),he(z[0],z[1]))},[ae,he]),Ce=p.useCallback(N=>{const v=f.current;if(!v.active||v.pointerId!==N.pointerId)return;const z=a.current;if(z&&z.hasPointerCapture(N.pointerId))try{z.releasePointerCapture(N.pointerId)}catch{}f.current={active:!1,pointerId:null},k()},[k]);return p.useEffect(()=>{let N=!1;l.current=null,k();const v=0,z=2**(t.maxTierZoom-v),ie=Math.ceil(t.width/z),H=Math.ceil(t.height/z),ge=Math.max(1,Math.ceil(ie/t.tileSize)),le=Math.max(1,Math.ceil(H/t.tileSize)),ne=ge*le;if(!W||ne>w)return;const _e=Math.min(d/Math.max(1,t.width),m/Math.max(1,t.height)),ue=document.createElement("canvas");ue.width=Math.max(1,Math.round(t.width*_e)),ue.height=Math.max(1,Math.round(t.height*_e));const pe=ue.getContext("2d");if(!pe)return;pe.fillStyle=A,pe.fillRect(0,0,ue.width,ue.height);const de=[];for(let re=0;re<le;re+=1)for(let oe=0;oe<ge;oe+=1){const ce=oe*t.tileSize*z,q=re*t.tileSize*z,Pe=Math.min((oe+1)*t.tileSize,ie)*z,Ee=Math.min((re+1)*t.tileSize,H)*z;de.push({url:Gn(t,v,oe,re),bounds:[ce,q,Pe,Ee]})}return Promise.allSettled(de.map(async re=>{const oe=Ya(re.url,n),ce=await fetch(re.url,{headers:oe?{Authorization:n}:void 0});if(!ce.ok)throw new Error(`HTTP ${ce.status}`);const q=await createImageBitmap(await ce.blob());return{tile:re,bitmap:q}})).then(re=>{if(N){for(const q of re)q.status==="fulfilled"&&q.value.bitmap.close();return}const oe=ue.width/Math.max(1,t.width),ce=ue.height/Math.max(1,t.height);for(const q of re){if(q.status!=="fulfilled")continue;const{tile:{bounds:Pe},bitmap:Ee}=q.value,ye=Pe[0]*oe,V=Pe[1]*ce,K=Math.max(1,(Pe[2]-Pe[0])*oe),fe=Math.max(1,(Pe[3]-Pe[1])*ce);pe.drawImage(Ee,ye,V,K,fe),Ee.close()}l.current=ue,k()}),()=>{N=!0}},[t,n,A,d,m,W,w,k]),p.useEffect(()=>{k()},[k]),p.useEffect(()=>{if(e.current)return;let N=0;const v=()=>{if(e.current){k();return}N=requestAnimationFrame(v)};return N=requestAnimationFrame(v),()=>cancelAnimationFrame(N)},[e,k]),p.useEffect(()=>tn(()=>k()),[k]),p.useEffect(()=>{if(i)return i.current=k,()=>{i.current===k&&(i.current=null)}},[i,k]),p.useEffect(()=>()=>{f.current={active:!1,pointerId:null},c.current!==null&&(cancelAnimationFrame(c.current),c.current=null),h.current=!1},[]),Ge.jsxs("div",{className:o,style:Y,children:[Ge.jsx("canvas",{ref:a,style:{width:"100%",height:"100%",display:"block",borderRadius:"inherit"},onPointerDown:J,onPointerMove:ve,onPointerUp:Ce,onPointerCancel:Ce,onContextMenu:N=>{N.preventDefault()},onWheel:N=>{N.preventDefault(),N.stopPropagation()}}),T&&Ge.jsx("button",{type:"button","aria-label":"Hide overview map",onClick:N=>{N.stopPropagation(),T()},style:I?{...I}:{...qa},children:D??"×"})]})}const Yr="__patch_layer__",Za=[];function $a({regions:t,strokeStyle:e}){const{rendererRef:n,registerDrawCallback:r,unregisterDrawCallback:i,requestOverlayRedraw:o}=st(),s=t??Za,a=p.useMemo(()=>Ke(hi,e),[e]),l=p.useMemo(()=>{const c=[];for(let h=0;h<s.length;h+=1){const d=s[h],m=jt(d.coordinates);m.length!==0&&c.push({region:d,regionIndex:h,regionKey:d.id??h,polygons:m})}return c},[s]),u=p.useCallback(c=>{const h=n.current;if(!h||c.length===0)return[];const d=new Array(c.length);for(let m=0;m<c.length;m+=1){const g=He(h.worldToScreen(c[m][0],c[m][1]));if(!g)return[];d[m]=g}return d},[]),f=p.useRef({prepared:l,resolvedStrokeStyle:a,worldToScreenPoints:u});return f.current={prepared:l,resolvedStrokeStyle:a,worldToScreenPoints:u},p.useEffect(()=>(r(Yr,20,h=>{const{prepared:d,resolvedStrokeStyle:m,worldToScreenPoints:g}=f.current;for(const b of d)for(const y of b.polygons){const w=g(y.outer);w.length>=4&&ke(h,w,m,!0,!1);for(const A of y.holes){const S=g(A);S.length>=4&&ke(h,S,m,!0,!1)}}}),()=>i(Yr)),[r,i]),p.useEffect(()=>{o()},[l,a,o]),null}function Rt(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return null;const n=dt(e??[]);if(n.length===0){const m={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return t.fillModes instanceof Uint8Array&&(m.fillModes=new Uint8Array(0)),t.ids instanceof Uint32Array&&(m.ids=new Uint32Array(0)),m}const r=ot(t),i=t.positions,o=t.paletteIndices,s=t.fillModes instanceof Uint8Array&&t.fillModes.length>=r?t.fillModes:null,a=t.ids instanceof Uint32Array&&t.ids.length>=r?t.ids:null,l=new Float32Array(r*2),u=new Uint16Array(r),f=s?new Uint8Array(r):null,c=a?new Uint32Array(r):null;let h=0;for(let m=0;m<r;m+=1){const g=i[m*2],b=i[m*2+1];St(g,b,n)&&(l[h*2]=g,l[h*2+1]=b,u[h]=o[m],f&&(f[h]=s[m]),c&&(c[h]=a[m]),h+=1)}const d={count:h,positions:l.subarray(0,h*2),paletteIndices:u.subarray(0,h)};return f&&(d.fillModes=f.subarray(0,h)),c&&(d.ids=c.subarray(0,h)),d}function zi(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return new Uint32Array(0);const n=dt(e??[]);if(n.length===0)return new Uint32Array(0);const r=ot(t);if(r===0)return new Uint32Array(0);const i=t.positions,o=new Uint32Array(r);let s=0;for(let a=0;a<r;a+=1){const l=i[a*2],u=i[a*2+1];St(l,u,n)&&(o[s]=a,s+=1)}return o.subarray(0,s)}let Dt=null;const Ka=`
104
104
  struct Params {
105
105
  pointCount: u32,
106
106
  boundsCount: u32,
@@ -131,7 +131,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
131
131
  }
132
132
  outputMask[i] = inside;
133
133
  }
134
- `;function Va(){if(typeof navigator>"u")return!1;const t=navigator;return typeof t.gpu=="object"&&t.gpu!==null}function Bi(){if(!Va())return null;const e=navigator.gpu;if(!e||typeof e!="object")return null;const n=e;return typeof n.requestAdapter!="function"?null:n}const Nt=globalThis.GPUShaderStage?.COMPUTE??4,un=globalThis.GPUBufferUsage?.STORAGE??128,Bt=globalThis.GPUBufferUsage?.COPY_DST??8,Ga=globalThis.GPUBufferUsage?.COPY_SRC??4,qa=globalThis.GPUBufferUsage?.UNIFORM??64,Ha=globalThis.GPUBufferUsage?.MAP_READ??1,Za=globalThis.GPUMapMode?.READ??1;async function $a(){const t=Bi();if(!t)return{supported:!1,features:[]};const e=await t.requestAdapter();return e?{supported:!0,adapterName:e.info?.description??e.info?.vendor??"unknown",features:Array.from(e.features),limits:{maxStorageBufferBindingSize:Number(e.limits.maxStorageBufferBindingSize),maxComputeInvocationsPerWorkgroup:Number(e.limits.maxComputeInvocationsPerWorkgroup),maxComputeWorkgroupSizeX:Number(e.limits.maxComputeWorkgroupSizeX)}}:{supported:!1,features:[]}}async function Ka(){return Dt||(Dt=(async()=>{const t=Bi();if(!t)return null;const e=await t.requestAdapter();if(!e)return null;const n=await e.requestDevice(),r=n.createBindGroupLayout({entries:[{binding:0,visibility:Nt,buffer:{type:"read-only-storage"}},{binding:1,visibility:Nt,buffer:{type:"read-only-storage"}},{binding:2,visibility:Nt,buffer:{type:"storage"}},{binding:3,visibility:Nt,buffer:{type:"uniform"}}]}),i=n.createComputePipeline({layout:n.createPipelineLayout({bindGroupLayouts:[r]}),compute:{module:n.createShaderModule({code:Xa}),entryPoint:"main"}});return{device:n,pipeline:i,bindGroupLayout:r}})(),Dt)}function kt(t,e){return Math.ceil(t/e)*e}async function ki(t,e,n){const r=await Ka();if(!r)return null;const i=Math.max(0,Math.floor(e)),o=Math.max(0,Math.floor(n.length/4));if(i===0||o===0)return new Uint32Array(0);const s=Math.min(i,Math.floor(t.length/2));if(s===0)return new Uint32Array(0);const a=s*2*Float32Array.BYTES_PER_ELEMENT,l=o*4*Float32Array.BYTES_PER_ELEMENT,u=s*Uint32Array.BYTES_PER_ELEMENT,f=Number(r.device.limits.maxStorageBufferBindingSize);if(a>f||l>f||u>f)return null;const c=r.device.createBuffer({size:kt(a,4),usage:un|Bt}),h=r.device.createBuffer({size:kt(l,4),usage:un|Bt}),d=r.device.createBuffer({size:kt(u,4),usage:un|Ga}),m=r.device.createBuffer({size:16,usage:qa|Bt}),g=r.device.createBuffer({size:kt(u,4),usage:Bt|Ha});let y=!1;try{r.device.queue.writeBuffer(c,0,t.buffer,t.byteOffset,a),r.device.queue.writeBuffer(h,0,n.buffer,n.byteOffset,l),r.device.queue.writeBuffer(m,0,new Uint32Array([s,o,0,0]));const b=r.device.createBindGroup({layout:r.bindGroupLayout,entries:[{binding:0,resource:{buffer:c}},{binding:1,resource:{buffer:h}},{binding:2,resource:{buffer:d}},{binding:3,resource:{buffer:m}}]}),x=r.device.createCommandEncoder(),A=x.beginComputePass();A.setPipeline(r.pipeline),A.setBindGroup(0,b),A.dispatchWorkgroups(Math.ceil(s/256)),A.end(),x.copyBufferToBuffer(d,0,g,0,u),r.device.queue.submit([x.finish()]),await g.mapAsync(Za),y=!0;const S=g.getMappedRange();return new Uint32Array(S.slice(0))}finally{if(y)try{g.unmap()}catch{}c.destroy(),h.destroy(),d.destroy(),m.destroy(),g.destroy()}}async function Ui(t,e,n={}){const r=xe(),i=n.bridgeToDraw===!0;if(!t||!t.count||!t.positions||!t.paletteIndices)return{data:null,meta:{mode:"hybrid-webgpu",durationMs:xe()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}};const o=dt(e??[]);if(o.length===0){const S={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return t.fillModes instanceof Uint8Array&&(S.fillModes=new Uint8Array(0)),t.ids instanceof Uint32Array&&(S.ids=new Uint32Array(0)),{data:S,meta:{mode:"hybrid-webgpu",durationMs:xe()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const s=st(t),a=t.fillModes instanceof Uint8Array&&t.fillModes.length>=s?t.fillModes:null,l=t.ids instanceof Uint32Array&&t.ids.length>=s?t.ids:null;if(s===0){const S={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(S.fillModes=new Uint8Array(0)),l&&(S.ids=new Uint32Array(0)),{data:S,meta:{mode:"hybrid-webgpu",durationMs:xe()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const u=new Float32Array(o.length*4);for(let S=0;S<o.length;S+=1){const C=S*4,M=o[S];u[C]=M.minX,u[C+1]=M.minY,u[C+2]=M.maxX,u[C+3]=M.maxY}let f=null,c=!1;try{f=await ki(t.positions,s,u),c=!!f}catch{f=null,c=!1}if(!f)return{data:Rt(t,e),meta:{mode:"hybrid-webgpu",durationMs:xe()-r,usedWebGpu:!1,candidateCount:s,bridgedToDraw:!1}};let h=0;for(let S=0;S<s;S+=1)f[S]===1&&(h+=1);const d=new Uint32Array(h);if(h>0){let S=0;for(let C=0;C<s;C+=1)f[C]===1&&(d[S]=C,S+=1)}if(h===0){if(i){const C={count:s,positions:t.positions.subarray(0,s*2),paletteIndices:t.paletteIndices.subarray(0,s),drawIndices:new Uint32Array(0)};return a&&(C.fillModes=a.subarray(0,s)),l&&(C.ids=l.subarray(0,s)),{data:C,meta:{mode:"hybrid-webgpu",durationMs:xe()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!0}}}const S={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(S.fillModes=new Uint8Array(0)),l&&(S.ids=new Uint32Array(0)),{data:S,meta:{mode:"hybrid-webgpu",durationMs:xe()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!1}}}if(i){const S=new Uint32Array(h);let C=0;for(let P=0;P<h;P+=1){const U=d[P]??0,O=t.positions[U*2],N=t.positions[U*2+1];St(O,N,o)&&(S[C]=U,C+=1)}const M={count:s,positions:t.positions.subarray(0,s*2),paletteIndices:t.paletteIndices.subarray(0,s),drawIndices:S.subarray(0,C)};return a&&(M.fillModes=a.subarray(0,s)),l&&(M.ids=l.subarray(0,s)),{data:M,meta:{mode:"hybrid-webgpu",durationMs:xe()-r,usedWebGpu:!0,candidateCount:h,bridgedToDraw:!0}}}const m=new Float32Array(h*2),g=new Uint16Array(h),y=a?new Uint8Array(h):null,b=l?new Uint32Array(h):null;let x=0;for(let S=0;S<h;S+=1){const C=d[S]??0,M=t.positions[C*2],P=t.positions[C*2+1];St(M,P,o)&&(m[x*2]=M,m[x*2+1]=P,g[x]=t.paletteIndices[C],y&&(y[x]=a[C]),b&&(b[x]=l[C]),x+=1)}const A={count:x,positions:m.subarray(0,x*2),paletteIndices:g.subarray(0,x)};return y&&(A.fillModes=y.subarray(0,x)),b&&(A.ids=b.subarray(0,x)),{data:A,meta:{mode:"hybrid-webgpu",durationMs:xe()-r,usedWebGpu:!0,candidateCount:h,bridgedToDraw:!1}}}class zi{constructor(e,n){E(this,"worker",null);E(this,"supported",!0);E(this,"requestId",1);E(this,"pendingById",new Map);E(this,"handleMessage",e=>{const n=e.data;if(!n)return;const r=this.pendingById.get(n.id);r&&(this.pendingById.delete(n.id),this.handlers.onResponse(n,r))});E(this,"handleError",()=>{this.supported=!1,this.teardownWorker("worker crashed")});this.createWorker=e,this.handlers=n}beginRequest(e){const n=this.getOrCreateWorker();if(!n)return null;const r=this.requestId++;return this.pendingById.set(r,e),{id:r,worker:n}}cancelRequest(e){const n=this.pendingById.get(e);if(n)return this.pendingById.delete(e),n}terminate(e="worker terminated"){this.teardownWorker(e)}getOrCreateWorker(){if(!this.supported)return null;if(this.worker)return this.worker;try{const e=this.createWorker();return e.addEventListener("message",this.handleMessage),e.addEventListener("error",this.handleError),this.worker=e,e}catch{return this.supported=!1,null}}teardownWorker(e){this.worker&&(this.worker.removeEventListener("message",this.handleMessage),this.worker.removeEventListener("error",this.handleError),this.worker.terminate(),this.worker=null);const n=new Error(e);for(const[,r]of this.pendingById)this.handlers.rejectPending(r,n);this.pendingById.clear()}}const At=new zi(()=>new Worker(new URL(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/roi-clip-worker-CHxxL_lK.js").href:new URL("assets/roi-clip-worker-CHxxL_lK.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),typeof document>"u"?require("url").pathToFileURL(__filename).href:ft&&ft.tagName.toUpperCase()==="SCRIPT"&&ft.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),{onResponse:(t,e)=>{if(t.type==="roi-clip-failure"){e.reject(new Error(t.error||"worker clip failed"));return}if(t.type==="roi-clip-index-success"){if(e.kind!=="index"){e.reject(new Error("worker response mismatch: expected point data result"));return}const l=Math.max(0,Math.floor(t.count)),u=new Uint32Array(t.indices).subarray(0,l);e.resolve({indices:u,meta:{mode:"worker",durationMs:Number.isFinite(t.durationMs)?t.durationMs:xe()-e.startMs}});return}if(e.kind!=="data"){e.reject(new Error("worker response mismatch: expected index result"));return}const n=Math.max(0,Math.floor(t.count)),r=new Float32Array(t.positions),i=new Uint16Array(t.paletteIndices),o=t.fillModes?new Uint8Array(t.fillModes):null,s=t.ids?new Uint32Array(t.ids):null,a={count:n,positions:r.subarray(0,n*2),paletteIndices:i.subarray(0,n)};o&&(a.fillModes=o.subarray(0,n)),s&&(a.ids=s.subarray(0,n)),e.resolve({data:a,meta:{mode:"worker",durationMs:Number.isFinite(t.durationMs)?t.durationMs:xe()-e.startMs}})},rejectPending:(t,e)=>{t.reject(e)}});function ja(){At.terminate("worker terminated")}async function Oi(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return{data:null,meta:{mode:"worker",durationMs:0}};const n=st(t),r=t.positions.slice(0,n*2),i=t.paletteIndices.slice(0,n),o=t.fillModes instanceof Uint8Array&&t.fillModes.length>=n?t.fillModes.slice(0,n):null,s=t.ids instanceof Uint32Array&&t.ids.length>=n?t.ids.slice(0,n):null;return new Promise((a,l)=>{const u=xe(),f=At.beginRequest({kind:"data",resolve:a,reject:l,startMs:u});if(!f){a({data:Rt(t,e),meta:{mode:"sync",durationMs:xe()-u}});return}const c={type:"roi-clip-request",id:f.id,count:n,positions:r.buffer,paletteIndices:i.buffer,fillModes:o?.buffer,ids:s?.buffer,polygons:e??[]},h=[r.buffer,i.buffer];o&&h.push(o.buffer),s&&h.push(s.buffer);try{f.worker.postMessage(c,h)}catch(d){const m=At.cancelRequest(f.id);m?m.reject(d):l(d)}})}async function Qa(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return{indices:new Uint32Array(0),meta:{mode:"worker",durationMs:0}};const n=st(t),r=t.positions.slice(0,n*2);return new Promise((i,o)=>{const s=xe(),a=At.beginRequest({kind:"index",resolve:i,reject:o,startMs:s});if(!a){i({indices:Ni(t,e),meta:{mode:"sync",durationMs:xe()-s}});return}const l={type:"roi-clip-index-request",id:a.id,count:n,positions:r.buffer,polygons:e??[]};try{a.worker.postMessage(l,[r.buffer])}catch(u){const f=At.cancelRequest(a.id);f?f.reject(u):o(u)}})}const Ja={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};function el(t,e,n,r,i){const o=p.useRef(0),[s,a]=p.useState(n),l=p.useMemo(()=>r.map(u=>ht(u.coordinates)).filter(u=>u!=null),[r]);return p.useEffect(()=>{const u=++o.current;let f=!1;if(!t)return a(n),()=>{f=!0};if(!n||!n.count||!n.positions||!n.paletteIndices)return a(null),()=>{f=!0};if(l.length===0)return a(Ja),i?.({mode:e,durationMs:0,inputCount:n.count,outputCount:0,polygonCount:0}),()=>{f=!0};const c=(d,m)=>{if(f||u!==o.current)return;const g=n.count,y=d?.drawIndices?d.drawIndices.length:d?.count??0;a(d),i?.({mode:m.mode,durationMs:m.durationMs,inputCount:g,outputCount:y,polygonCount:l.length,usedWebGpu:m.usedWebGpu,candidateCount:m.candidateCount,bridgedToDraw:m.bridgedToDraw})};return(async()=>{if(e==="sync"){const d=performance.now(),m=Rt(n,l);c(m,{mode:"sync",durationMs:performance.now()-d});return}if(e==="hybrid-webgpu"){const d=await Ui(n,l,{bridgeToDraw:!0});c(d.data,{mode:d.meta.mode,durationMs:d.meta.durationMs,usedWebGpu:d.meta.usedWebGpu,candidateCount:d.meta.candidateCount,bridgedToDraw:d.meta.bridgedToDraw});return}try{const d=await Oi(n,l);c(d.data,{mode:d.meta.mode,durationMs:d.meta.durationMs})}catch{const d=performance.now(),m=Rt(n,l);c(m,{mode:"sync",durationMs:performance.now()-d})}})(),()=>{f=!0}},[t,e,n,l,i]),s}const tl=24,nl=1024,rl=4,Xt=-1;function pt(t,e,n){return(t*73856093^e*19349663)>>>0&n}function il(t,e,n){if(t<=0||e<=0||n<=0)return 256;const r=Math.max(1,t*e),o=Math.sqrt(r/Math.max(1,n))*rl;return Math.max(tl,Math.min(nl,o))}function ol(t,e){if(!(t instanceof Uint32Array)||t.length===0)return null;let n=!0;for(let o=0;o<t.length;o+=1)if(!(t[o]<e)){n=!1;break}if(n)return t;const r=new Uint32Array(t.length);let i=0;for(let o=0;o<t.length;o+=1)t[o]>=e||(r[i]=t[o],i+=1);return i>0?r.subarray(0,i):null}function sl(t){const e=Math.max(0,Math.floor(t.count)),n=Math.floor(t.positions.length/2),r=Math.max(0,Math.min(e,n));if(r<=0)return null;const i=ol(t.drawIndices??null,r),o=i?i.length:r;if(o===0)return null;const s=il(t.sourceWidth,t.sourceHeight,o),a=1/s,l=new Int32Array(o),u=new Int32Array(o);let f=0;if(i)for(let F=0;F<o;F+=1){const z=i[F],K=t.positions[z*2],Y=t.positions[z*2+1];!Number.isFinite(K)||!Number.isFinite(Y)||(l[f]=Math.floor(K*a),u[f]=Math.floor(Y*a),f+=1)}else for(let F=0;F<r;F+=1){const z=t.positions[F*2],K=t.positions[F*2+1];!Number.isFinite(z)||!Number.isFinite(K)||(l[f]=Math.floor(z*a),u[f]=Math.floor(K*a),f+=1)}if(f===0)return null;let c=Math.min(f,Math.max(64,f>>>3));(!Number.isFinite(c)||c<=0)&&(c=f);let h=1;for(;h<c*2;)h<<=1;let d=h-1,m=new Int32Array(h*2),g=new Int32Array(h);m.fill(2147483647);let y=0;const b=new Int32Array(f);for(let F=0;F<f;F+=1){const z=l[F],K=u[F];let Y=pt(z,K,d);for(;;){const j=m[Y*2];if(j===2147483647){if(m[Y*2]=z,m[Y*2+1]=K,g[Y]=1,b[F]=Y,y+=1,y*4>h*3){const ce=h;h<<=1,d=h-1;const J=new Int32Array(h*2),Te=new Int32Array(h);J.fill(2147483647);for(let Pe=0;Pe<ce;Pe+=1){if(m[Pe*2]===2147483647)continue;const Re=m[Pe*2],_=m[Pe*2+1];let T=pt(Re,_,d);for(;J[T*2]!==2147483647;)T=T+1&d;J[T*2]=Re,J[T*2+1]=_,Te[T]=g[Pe]}for(m=J,g=Te,Y=pt(z,K,d);m[Y*2]!==z||m[Y*2+1]!==K;)Y=Y+1&d;b[F]=Y}break}if(j===z&&m[Y*2+1]===K){g[Y]+=1,b[F]=Y;break}Y=Y+1&d}}const x=new Int32Array(y*2),A=new Uint32Array(y),S=new Uint32Array(y),C=new Int32Array(h);C.fill(Xt);let M=0,P=0;for(let F=0;F<h;F+=1)m[F*2]!==2147483647&&(x[M*2]=m[F*2],x[M*2+1]=m[F*2+1],A[M]=P,S[M]=g[F],C[F]=M,P+=g[F],M+=1);const U=new Uint32Array(f),O=new Uint32Array(y);if(O.set(A),i)for(let F=0;F<f;F+=1){const z=C[b[F]];U[O[z]]=i[F],O[z]+=1}else{let F=0;for(let z=0;z<r;z+=1){const K=t.positions[z*2],Y=t.positions[z*2+1];if(!Number.isFinite(K)||!Number.isFinite(Y))continue;const j=C[b[F]];U[O[j]]=z,O[j]+=1,F+=1}}let N=1;for(;N<y*2;)N<<=1;const v=N-1,B=new Int32Array(N);B.fill(Xt);for(let F=0;F<y;F+=1){const z=x[F*2],K=x[F*2+1];let Y=pt(z,K,v);for(;B[Y]!==Xt;)Y=Y+1&v;B[Y]=F}return{cellSize:s,safeCount:r,cellCount:y,hashCapacity:N,hashTable:B,cellKeys:x,cellOffsets:A,cellLengths:S,pointIndices:U}}function Yi(t,e,n){const{hashTable:r,cellKeys:i,hashMask:o}=t;let s=pt(e,n,o);for(;;){const a=r[s];if(a===Xt)return-1;if(i[a*2]===e&&i[a*2+1]===n)return a;s=s+1&o}}function al(t,e){if(t.safeCount<=0||t.cellCount<=0)return null;const n=t.safeCount;return{cellSize:t.cellSize,safeCount:n,positions:e.positions.subarray(0,n*2),ids:e.ids instanceof Uint32Array&&e.ids.length>=n?e.ids.subarray(0,n):null,hashCapacity:t.hashCapacity,hashMask:t.hashCapacity-1,hashTable:new Int32Array(t.hashTable),cellKeys:new Int32Array(t.cellKeys),cellOffsets:new Uint32Array(t.cellOffsets),cellLengths:new Uint32Array(t.cellLengths),pointIndices:new Uint32Array(t.pointIndices)}}const Mn=new zi(()=>new Worker(new URL(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/point-hit-index-worker-CNFA6pZm.js").href:new URL("assets/point-hit-index-worker-CNFA6pZm.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),typeof document>"u"?require("url").pathToFileURL(__filename).href:ft&&ft.tagName.toUpperCase()==="SCRIPT"&&ft.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),{onResponse:(t,e)=>{if(t.type==="point-hit-index-failure"){e.reject(new Error(t.error||"worker index build failed"));return}e.resolve(al(t,e.pointData))},rejectPending:(t,e)=>{t.reject(e)}});function ll(){Mn.terminate("worker terminated")}function cl(t,e){const n=st(t);if(n<=0)return null;const r=t.positions.subarray(0,n*2),i=sl({count:n,positions:r,drawIndices:t.drawIndices instanceof Uint32Array?t.drawIndices:null,sourceWidth:e?.width??0,sourceHeight:e?.height??0});return i?{cellSize:i.cellSize,safeCount:n,positions:r,ids:t.ids instanceof Uint32Array&&t.ids.length>=n?t.ids.subarray(0,n):null,hashCapacity:i.hashCapacity,hashMask:i.hashCapacity-1,hashTable:i.hashTable,cellKeys:i.cellKeys,cellOffsets:i.cellOffsets,cellLengths:i.cellLengths,pointIndices:i.pointIndices}:null}async function Wi(t,e){if(!t||!t.positions||!t.paletteIndices)return null;const n=st(t);return n<=0?null:new Promise((r,i)=>{const o={resolve:r,reject:i,pointData:t},s=Mn.beginRequest(o);if(!s||!s.worker){r(cl(t,e));return}const a=t.positions.slice(0,n*2),l=t.drawIndices instanceof Uint32Array&&t.drawIndices.length>0?t.drawIndices.slice():void 0,u={type:"point-hit-index-request",id:s.id,count:n,positions:a.buffer,drawIndices:l?.buffer,sourceWidth:e?.width??0,sourceHeight:e?.height??0},f=[a.buffer];l&&f.push(l.buffer);try{s.worker.postMessage(u,f)}catch(c){const h=Mn.cancelRequest(s.id);h?h.reject(c):i(c)}})}const ul=.65,fl=4;function hl(t,e,n,r,i,o,s,a){const l=!!(n||r||i),[u,f]=p.useState(null),c=p.useRef(null),h=p.useRef(null);p.useEffect(()=>{if(!l||!t){f(null);return}let y=!1;return Wi(t,e).then(b=>{y||f(b)}),()=>{y=!0}},[l,t,e]);const d=p.useCallback(y=>{const b=s.current;if(!b||!u)return null;const x=Number(y[0]),A=Number(y[1]);if(!Number.isFinite(x)||!Number.isFinite(A))return null;const S=Math.max(1e-6,b.getViewState().zoom),C=b.getPointSizeByZoom(a),P=Math.max(fl,C*ul)/S;if(!Number.isFinite(P)||P<=0)return null;const{cellSize:U,cellOffsets:O,cellLengths:N,pointIndices:v,positions:B,safeCount:F}=u,z=Math.floor(x/U),K=Math.floor(A/U),Y=Math.max(1,Math.ceil(P/U)),j=P*P;let ce=-1,J=j,Te=0,Pe=0;for(let _=z-Y;_<=z+Y;_+=1)for(let T=K-Y;T<=K+Y;T+=1){const X=Yi(u,_,T);if(X<0)continue;const q=O[X],te=q+N[X];for(let le=q;le<te;le+=1){const re=v[le];if(re>=F)continue;const ge=B[re*2],ne=B[re*2+1],pe=ge-x,he=ne-A,se=pe*pe+he*he;se>J||(J=se,ce=re,Te=ge,Pe=ne)}}if(ce<0)return null;const Re=u.ids?Number(u.ids[ce]):null;return{index:ce,id:Re,coordinate:[x,A],pointCoordinate:[Te,Pe]}},[a,u]),m=p.useCallback((y,b)=>{if(!n)return;const x=y?.index??null,A=y?.id??null;c.current===x&&h.current===A||(c.current=x,h.current=A,n({index:x,id:A,coordinate:b,pointCoordinate:y?.pointCoordinate??null}))},[n]),g=p.useCallback((y,b)=>{if(!r)return;const x=d(y);x&&r({...x,button:b})},[r,d]);return p.useEffect(()=>{if(i)return i.current=d,()=>{i.current===d&&(i.current=null)}},[i,d]),p.useEffect(()=>{const y=c.current;y!==null&&(u&&y<u.safeCount||(c.current=null,h.current=null,n?.({index:null,id:null,coordinate:null,pointCoordinate:null})))},[u,n]),p.useEffect(()=>{},[o,n]),{getCellByCoordinates:d,emitPointHover:m,emitPointClick:g}}let dl=0;const ml=p.forwardRef(function({data:e=null,palette:n=null,sizeByZoom:r,opacity:i,strokeScale:o,innerFillOpacity:s,clipEnabled:a=!1,clipToRegions:l,clipMode:u="worker",onClipStats:f,onHover:c,onClick:h,dashed:d},m){const{rendererRef:g,rendererSerial:y,source:b}=at(),x=p.useRef(null),A=p.useRef(`__point_layer__${dl++}`),C=el(a,u,e,l??gl,f),{getCellByCoordinates:M}=hl(C,b,c,h,x,"cursor",g,A.current);return p.useImperativeHandle(m,()=>({queryAt:M}),[M]),p.useEffect(()=>{const P=g.current;if(!P)return;const U=A.current;return P.registerPointLayer(U),()=>{P.unregisterPointLayer(U)}},[g,y]),p.useEffect(()=>{const P=g.current;P&&P.setPointPalette(n,A.current)},[y,n,g]),p.useEffect(()=>{const P=g.current;P&&P.setPointLineDash(d,A.current)},[y,d,g]),p.useEffect(()=>{const P=g.current;!P||r===void 0||P.setPointSizeByZoom(r,A.current)},[y,r,g]),p.useEffect(()=>{const P=g.current;!P||i===void 0||P.setPointOpacity(i,A.current)},[y,i,g]),p.useEffect(()=>{const P=g.current;!P||o===void 0||P.setPointStrokeScale(o,A.current)},[y,o,g]),p.useEffect(()=>{const P=g.current;!P||s===void 0||P.setPointInnerFillOpacity(s,A.current)},[y,s,g]),p.useEffect(()=>{const P=g.current;P&&P.setPointData(C,A.current)},[y,C,g]),null}),gl=[],pl=180,Ur=20;function yl(t){const e=L(t,0,1);return e*e*(3-2*e)}function bl(t,e,n){const[r,i]=p.useState(0),o=p.useRef(0),s=p.useRef({rafId:null,startMs:0,from:0,to:0}),a=p.useCallback(c=>{const h=L(c,0,Ur);Math.abs(o.current-h)<1e-4||(o.current=h,i(h))},[]),l=p.useCallback(()=>{const c=s.current;c.rafId!==null&&(cancelAnimationFrame(c.rafId),c.rafId=null)},[]),u=p.useCallback(c=>{const h=L(c,0,Ur),d=s.current,m=o.current;if(Math.abs(m-h)<1e-4){l(),d.to=h,a(h);return}l(),d.startMs=performance.now(),d.from=m,d.to=h;const g=y=>{const b=s.current,x=Math.max(0,y-b.startMs),A=L(x/pl,0,1),S=yl(A),C=b.from+(b.to-b.from)*S;if(a(C),n.current?.(),A>=1){b.rafId=null,a(b.to);return}b.rafId=requestAnimationFrame(g)};d.rafId=requestAnimationFrame(g)},[a,l]),f=p.useCallback(c=>{const h=e.current;if(!h||typeof c!="number"||!Number.isFinite(c)){u(0);return}const d=On(t,c,h.getZoomRange(),h.getRegionLabelAutoLiftCapZoom());u(d)},[t,u]);return p.useEffect(()=>()=>{l()},[l]),{regionLabelAutoLiftOffsetPx:r,syncRegionLabelAutoLiftTarget:f,cancelRegionLabelAutoLiftAnimation:l,applyRegionLabelAutoLiftOffset:a}}const xl=6;function Pn(t,e){return t.id??e}function wl(t,e,n,r,i,o){const s=i-n,a=o-r,l=s*s+a*a;if(l<=1e-12){const m=t-n,g=e-r;return m*m+g*g}const u=L(((t-n)*s+(e-r)*a)/l,0,1),f=n+s*u,c=r+a*u,h=t-f,d=e-c;return h*h+d*d}function zr(t,e,n,r){for(let i=1;i<n.length;i+=1){const o=n[i-1],s=n[i];if(wl(t,e,o[0],o[1],s[0],s[1])<=r)return!0}return!1}function Sl(t,e,n,r){if(t<n.minX-r||t>n.maxX+r||e<n.minY-r||e>n.maxY+r)return!1;const i=r*r;if(zr(t,e,n.outer,i))return!0;for(const o of n.holes)if(zr(t,e,o,i))return!0;return!1}function El(t,e,n,r,i,o,s){if(!t.label||!t.labelAnchor)return!1;const a=Dn(n.worldToScreen(t.labelAnchor[0],t.labelAnchor[1]));if(!a)return!1;const u=Bn(t.label,r)+r.paddingX*2,f=r.fontSize+r.paddingY*2,c=a[0],h=a[1]-r.offsetY,d=s?L(c,u*.5+1,i-u*.5-1):c,m=s?L(h,f*.5+1,o-f*.5-1):h,g=d-u*.5,y=d+u*.5,b=m-f*.5,x=m+f*.5;return e[0]>=g&&e[0]<=y&&e[1]>=b&&e[1]<=x}function Rl(t,e="top-center"){const n=[];for(let r=0;r<t.length;r+=1){const i=t[r],o=dt([ht(i?.coordinates)]);if(o.length===0)continue;const s=typeof i?.label=="string"?i.label.trim():"";n.push({region:i,regionIndex:r,regionId:Pn(i,r),polygons:o,label:s,labelAnchor:s?kn(o,e):null})}return n}function Or(t,e,n,r,i,o,s,a,l,u=!0){const f=t[0],c=t[1],h=Math.max(1e-6,r.getViewState().zoom),d=Math.max(0,s),m=xl/h;for(let g=n.length-1;g>=0;g-=1){const y=n[g];for(const x of y.polygons)if(Sl(f,c,x,m))return{region:y.region,regionIndex:y.regionIndex,regionId:y.regionId};let b=zn(i,o?.({region:y.region,regionId:y.regionId,regionIndex:y.regionIndex,zoom:h}));if(d>0&&(b={...b,offsetY:b.offsetY+d}),!!El(y,e,r,b,a,l,u))return{region:y.region,regionIndex:y.regionIndex,regionId:y.regionId}}return null}const Yr=[],Al=[];let Cl=0;function Ml(t){return{color:ci,width:ui,lineDash:ot,lineJoin:t.lineJoin,lineCap:t.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function Pl({regions:t,polygons:e,strokeStyle:n,hoverStrokeStyle:r,activeStrokeStyle:i,resolveStrokeStyle:o,labelStyle:s,labelAnchor:a="top-center",autoLiftLabelAtMaxZoom:l=!1,clampLabelToViewport:u=!0,hoveredRegionId:f,activeRegionId:c,interactive:h=!0,onActiveChange:d,onHover:m,onClick:g}){const{rendererRef:y,rendererSerial:b,canvasRef:x,containerRef:A,registerDrawCallback:S,unregisterDrawCallback:C,requestOverlayRedraw:M,drawInvalidateRef:P,registerViewStateListener:U,screenToWorld:O,worldToScreen:N,isInteractionLocked:v}=at(),B=t??Yr,F=e??Al,z=p.useMemo(()=>B.length>0?B:F.length===0?Yr:F.map((V,$)=>({id:$,coordinates:V})),[B,F]),[K,Y]=p.useState(()=>f??null),[j,ce]=p.useState(()=>c??null),J=f!==void 0,Te=c!==void 0,Pe=J?f??null:K,Re=Te?c??null:j,_=p.useRef(f??null),T=p.useRef(null),X=p.useRef(null);if(T.current===null||X.current===null){const V=Cl++;T.current=`__region_layer__${V}`,X.current=`__region_label__${V}`}p.useEffect(()=>{Te&&ce(c??null)},[Te,c]),p.useEffect(()=>{if(!J)return;const V=f??null;_.current=V,Y(V)},[J,f]);const q=p.useCallback(V=>{String(Re)!==String(V)&&(Te||ce(V),d?.(V))},[Re,Te,d]),{regionLabelAutoLiftOffsetPx:te,syncRegionLabelAutoLiftTarget:le}=bl(l,y,P),re=p.useMemo(()=>Nn(n),[n]),ge=p.useMemo(()=>je(re,r),[re,r]),ne=p.useMemo(()=>je(re,i),[re,i]),{staticLabelStyle:pe,labelStyleResolver:he}=p.useMemo(()=>typeof s=="function"?{staticLabelStyle:void 0,labelStyleResolver:s}:{staticLabelStyle:s,labelStyleResolver:void 0},[s]),se=p.useMemo(()=>Un(pe),[pe]),ue=p.useMemo(()=>{const V=[];for(let $=0;$<z.length;$+=1){const ie=z[$],oe=jt(ie.coordinates);oe.length!==0&&V.push({region:ie,regionIndex:$,regionKey:ie.id??$,polygons:oe})}return V},[z]),Ae=p.useMemo(()=>Rl(z,a),[z,a]);p.useEffect(()=>{const V=y.current;if(V)return le(V.getViewState().zoom),U($=>{le($.zoom)})},[b,U,le]),p.useEffect(()=>{!(Re===null?!0:z.some((oe,Se)=>String(Pn(oe,Se))===String(Re)))&&Re!==null&&q(null);const $=_.current;!($===null?!0:z.some((oe,Se)=>String(Pn(oe,Se))===String($)))&&$!==null&&(_.current=null,J||Y(null),m?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[z,Re,J,m,q]);const H=p.useCallback(V=>{const $=y.current;if(!$||V.length===0)return[];const ie=new Array(V.length);for(let oe=0;oe<V.length;oe+=1){const Se=qe($.worldToScreen(V[oe][0],V[oe][1]));if(!Se)return[];ie[oe]=Se}return ie},[]),Le=p.useRef({preparedRegions:ue,hoveredRegionId:Pe,activeRegionId:Re,resolvedStrokeStyle:re,resolvedHoverStrokeStyle:ge,resolvedActiveStrokeStyle:ne,resolveStrokeStyleProp:o,worldToScreenPoints:H});Le.current={preparedRegions:ue,hoveredRegionId:Pe,activeRegionId:Re,resolvedStrokeStyle:re,resolvedHoverStrokeStyle:ge,resolvedActiveStrokeStyle:ne,resolveStrokeStyleProp:o,worldToScreenPoints:H},p.useEffect(()=>{const V=ie=>{const{preparedRegions:oe,hoveredRegionId:Se,activeRegionId:De,resolvedStrokeStyle:G,resolvedHoverStrokeStyle:ye,resolvedActiveStrokeStyle:be,resolveStrokeStyleProp:I,worldToScreenPoints:W}=Le.current;for(const Q of oe){const{region:ee,polygons:fe,regionIndex:Ce,regionKey:Ie}=Q,ve=$t(De,Ie)?"active":$t(Se,Ie)?"hover":"default";let w=ve==="active"?be:ve==="hover"?ye:G;if(I){const D=I({region:ee,regionId:Ie,regionIndex:Ce,state:ve});w=je(w,D||void 0)}const R=ve==="default"?null:Ml(w);for(const D of fe){const k=W(D.outer);k.length>=4&&(R&&Be(ie,k,R,!0,!1),Be(ie,k,w,!0,!1));for(const Z of D.holes){const Ee=W(Z);Ee.length>=4&&(R&&Be(ie,Ee,R,!0,!1),Be(ie,Ee,w,!0,!1))}}}},$=T.current;if($)return S($,10,V),()=>C($)},[S,C]);const we=p.useRef({preparedRegions:ue,resolvedLabelStyle:se,labelStyleResolver:he,labelAnchor:a,autoLiftLabelAtMaxZoom:l,clampLabelToViewport:u,regionLabelAutoLiftOffsetPx:te,rendererRef:y});we.current={preparedRegions:ue,resolvedLabelStyle:se,labelStyleResolver:he,labelAnchor:a,autoLiftLabelAtMaxZoom:l,clampLabelToViewport:u,regionLabelAutoLiftOffsetPx:te,rendererRef:y},p.useEffect(()=>{const V=(ie,oe,Se)=>{const{preparedRegions:De,resolvedLabelStyle:G,labelStyleResolver:ye,labelAnchor:be,autoLiftLabelAtMaxZoom:I,clampLabelToViewport:W,regionLabelAutoLiftOffsetPx:Q,rendererRef:ee}=we.current;if(De.length===0)return;const fe=Math.max(1e-6,ee.current?.getViewState?.().zoom??1),Ce=typeof Q=="number"&&Number.isFinite(Q)?Math.max(0,Q):On(I,fe,ee.current?.getZoomRange?.(),ee.current?.getRegionLabelAutoLiftCapZoom?.());for(const Ie of De){if(!Ie.region.label)continue;const ve=kn(Ie.polygons,be);if(!ve)continue;const w=qe(ee.current?.worldToScreen(ve[0],ve[1])??[]);if(!w)continue;let R=zn(G,ye?.({region:Ie.region,regionId:Ie.regionKey,regionIndex:Ie.regionIndex,zoom:fe}));Ce>0&&(R={...R,offsetY:R.offsetY+Ce}),pi(ie,Ie.region.label,w,oe,Se,R,W)}},$=X.current;if($)return S($,50,V),()=>C($)},[S,C]),p.useEffect(()=>{M()},[ue,Pe,Re,re,se,te,M]);const de=p.useRef({preparedRegionHits:Ae,resolvedLabelStyle:se,labelStyleResolver:he,regionLabelAutoLiftOffsetPx:te,clampLabelToViewport:u,onHover:m,onClick:g,commitActive:q});return de.current={preparedRegionHits:Ae,resolvedLabelStyle:se,labelStyleResolver:he,regionLabelAutoLiftOffsetPx:te,clampLabelToViewport:u,onHover:m,onClick:g,commitActive:q},p.useEffect(()=>{if(!h)return;const V=A.current;if(!V)return;const $=Se=>{if(v())return;const De=y.current;if(!De)return;const{preparedRegionHits:G,resolvedLabelStyle:ye,labelStyleResolver:be,regionLabelAutoLiftOffsetPx:I,clampLabelToViewport:W,onHover:Q}=de.current,ee=O(Se.clientX,Se.clientY);if(!ee)return;let fe=null,Ce=null;if(G.length>0){const ve=N(ee[0],ee[1]);if(ve){const w=x.current?.getBoundingClientRect();Ce=Or(ee,ve,G,De,ye,be,typeof I=="number"?I:0,w?.width??0,w?.height??0,W),fe=Ce?.regionId??null}}const Ie=_.current;String(Ie)!==String(fe)&&(_.current=fe,J||Y(fe),Q?.({region:Ce?.region??null,regionId:fe,regionIndex:Ce?.regionIndex??-1,coordinate:ee}),M())},ie=Se=>{if(v())return;const De=y.current;if(!De)return;const{preparedRegionHits:G,resolvedLabelStyle:ye,labelStyleResolver:be,regionLabelAutoLiftOffsetPx:I,clampLabelToViewport:W,onClick:Q,commitActive:ee}=de.current;if(G.length===0)return;const fe=O(Se.clientX,Se.clientY);if(!fe)return;const Ce=N(fe[0],fe[1]);if(!Ce)return;const Ie=x.current?.getBoundingClientRect(),ve=Or(fe,Ce,G,De,ye,be,typeof I=="number"?I:0,Ie?.width??0,Ie?.height??0,W),w=ve?.regionId??null;ee(w),ve&&Q&&Q({region:ve.region,regionId:ve.regionId,regionIndex:ve.regionIndex,coordinate:fe})},oe=()=>{_.current!==null&&(_.current=null,J||Y(null),de.current.onHover?.({region:null,regionId:null,regionIndex:-1,coordinate:null}),M())};return V.addEventListener("pointermove",$),V.addEventListener("click",ie),V.addEventListener("pointerleave",oe),()=>{V.removeEventListener("pointermove",$),V.removeEventListener("click",ie),V.removeEventListener("pointerleave",oe)}},[A,y,x,h,J,O,N,v,M]),null}function vl({imageWidth:t,imageHeight:e,tiles:n,viewState:r,className:i,style:o}){const s=p.useRef(null),a=p.useRef(null),l=p.useMemo(()=>({width:"100%",height:"100%",display:"block",...o}),[o]);return p.useEffect(()=>{const u=s.current;if(!u)return;const f=new ti({canvas:u,imageWidth:t,imageHeight:e,initialViewState:r});return a.current=f,f.setTiles(n),()=>{f.destroy(),a.current=null}},[t,e]),p.useEffect(()=>{const u=a.current;u&&u.setTiles(n)},[n]),p.useEffect(()=>{const u=a.current;!u||!r||u.setViewState(r)},[r]),He.jsx("canvas",{ref:s,className:i,style:l})}function Tl(t,e){if(!e)return!1;try{const r=new URL(t,typeof window<"u"?window.location.href:void 0).hostname.toLowerCase();if(r.includes("amazonaws.com")||r.startsWith("s3.")||r.includes(".s3."))return!1}catch{}return!0}class Xi{constructor(e){E(this,"maxConcurrency");E(this,"maxRetries");E(this,"retryBaseDelayMs");E(this,"retryMaxDelayMs");E(this,"onTileLoad");E(this,"onTileError");E(this,"onStateChange");E(this,"authToken");E(this,"destroyed",!1);E(this,"queue",[]);E(this,"queuedByKey",new Map);E(this,"inflight",new Map);E(this,"visibleKeys",new Set);E(this,"timerId",null);E(this,"abortedCount",0);E(this,"retryCount",0);E(this,"failedCount",0);this.maxConcurrency=Math.max(1,Math.floor(e.maxConcurrency??12)),this.maxRetries=Math.max(0,Math.floor(e.maxRetries??2)),this.retryBaseDelayMs=Math.max(10,Math.floor(e.retryBaseDelayMs??120)),this.retryMaxDelayMs=Math.max(this.retryBaseDelayMs,Math.floor(e.retryMaxDelayMs??1200)),this.authToken=e.authToken??"",this.onTileLoad=e.onTileLoad,this.onTileError=e.onTileError,this.onStateChange=e.onStateChange}setAuthToken(e){this.authToken=String(e??"")}schedule(e){if(this.destroyed)return;const n=new Set;for(const r of e)n.add(r.key);this.visibleKeys=n,this.dropInvisibleQueued(n),this.abortInvisibleInflight(n);for(const r of e){if(this.inflight.has(r.key)){const s=this.inflight.get(r.key);s&&(s.tile=r);continue}const i=this.queuedByKey.get(r.key);if(i){i.tile=r;continue}const o={tile:r,attempt:0,readyAt:xe()};this.queue.push(o),this.queuedByKey.set(r.key,o)}this.sortQueue(),this.pump(),this.emitStateChange()}clear(){this.clearPumpTimer(),this.visibleKeys.clear(),this.queue=[],this.queuedByKey.clear();for(const[,e]of this.inflight)e.controller.abort();this.inflight.clear(),this.emitStateChange()}destroy(){this.destroyed||(this.destroyed=!0,this.clear())}getInflightCount(){return this.inflight.size}getSnapshot(){return{inflight:this.inflight.size,queued:this.queue.length,aborted:this.abortedCount,retries:this.retryCount,failed:this.failedCount}}dropInvisibleQueued(e){if(this.queue.length===0)return;const n=[];for(const r of this.queue){if(!e.has(r.tile.key)){this.queuedByKey.delete(r.tile.key);continue}n.push(r)}this.queue=n}abortInvisibleInflight(e){for(const[n,r]of this.inflight)e.has(n)||(this.inflight.delete(n),this.abortedCount+=1,r.controller.abort())}sortQueue(){this.queue.sort((e,n)=>e.readyAt!==n.readyAt?e.readyAt-n.readyAt:e.tile.distance2!==n.tile.distance2?e.tile.distance2-n.tile.distance2:e.tile.tier!==n.tile.tier?n.tile.tier-e.tile.tier:e.tile.key.localeCompare(n.tile.key))}pump(){if(this.destroyed)return;for(this.clearPumpTimer();this.inflight.size<this.maxConcurrency;){const r=this.takeNextReadyQueueItem();if(!r)break;this.startFetch(r)}if(this.inflight.size>=this.maxConcurrency||this.queue.length===0)return;const e=this.queue[0]?.readyAt;if(typeof e!="number")return;const n=Math.max(0,e-xe());this.timerId=globalThis.setTimeout(()=>{this.timerId=null,this.pump()},n)}takeNextReadyQueueItem(){if(this.queue.length===0)return null;const e=xe(),n=this.queue[0];return!n||n.readyAt>e?null:(this.queue.shift(),this.queuedByKey.delete(n.tile.key),n)}startFetch(e){const n=new AbortController,r={tile:e.tile,attempt:e.attempt,controller:n};this.inflight.set(e.tile.key,r),this.emitStateChange();const i=Tl(e.tile.url,this.authToken);fetch(e.tile.url,{signal:n.signal,headers:i?{Authorization:this.authToken}:void 0}).then(o=>{if(!o.ok)throw new Error(`HTTP ${o.status}`);return o.blob()}).then(o=>createImageBitmap(o)).then(o=>{if(this.destroyed||n.signal.aborted){o.close();return}if(!this.visibleKeys.has(e.tile.key)){o.close();return}this.onTileLoad(e.tile,o)}).catch(o=>{if(n.signal.aborted||this.destroyed)return;if(e.attempt<this.maxRetries&&this.visibleKeys.has(e.tile.key)){this.retryCount+=1;const a=e.attempt+1,l=this.getRetryDelay(a),u={tile:e.tile,attempt:a,readyAt:xe()+l},f=this.queuedByKey.get(e.tile.key);f?(f.tile=u.tile,f.readyAt=Math.min(f.readyAt,u.readyAt),f.attempt=Math.max(f.attempt,u.attempt)):(this.queue.push(u),this.queuedByKey.set(u.tile.key,u)),this.sortQueue();return}this.failedCount+=1,this.onTileError?.(e.tile,o,e.attempt+1)}).finally(()=>{this.inflight.delete(e.tile.key),this.pump(),this.emitStateChange()})}getRetryDelay(e){const n=Math.max(0,e-1),r=Math.min(this.retryMaxDelayMs,this.retryBaseDelayMs*2**n),i=.85+Math.random()*.3;return Math.round(r*i)}clearPumpTimer(){this.timerId!==null&&(globalThis.clearTimeout(this.timerId),this.timerId=null)}emitStateChange(){this.onStateChange?.(this.getSnapshot())}}function Il(t,e){t.addEventListener("pointerdown",e.pointerDown),t.addEventListener("pointermove",e.pointerMove),t.addEventListener("pointerup",e.pointerUp),t.addEventListener("pointercancel",e.pointerUp),t.addEventListener("wheel",e.wheel,{passive:!1}),t.addEventListener("dblclick",e.doubleClick),t.addEventListener("contextmenu",e.contextMenu),t.addEventListener("webglcontextlost",e.contextLost),t.addEventListener("webglcontextrestored",e.contextRestored)}function _l(t,e){t.removeEventListener("pointerdown",e.pointerDown),t.removeEventListener("pointermove",e.pointerMove),t.removeEventListener("pointerup",e.pointerUp),t.removeEventListener("pointercancel",e.pointerUp),t.removeEventListener("wheel",e.wheel),t.removeEventListener("dblclick",e.doubleClick),t.removeEventListener("contextmenu",e.contextMenu),t.removeEventListener("webglcontextlost",e.contextLost),t.removeEventListener("webglcontextrestored",e.contextRestored)}function Ll(t,e,n){const r=t.getBoundingClientRect(),i=Math.max(1,r.width||t.clientWidth||1),o=Math.max(1,r.height||t.clientHeight||1),s=Math.max(1,window.devicePixelRatio||1),a=Math.max(1,Math.round(i*s)),l=Math.max(1,Math.round(o*s));(t.width!==a||t.height!==l)&&(t.width=a,t.height=l),n.setViewport(i,o),e.viewport(0,0,a,l)}const vn=.35,Tn=.5,Fl=256,In=[{zoom:1,size:2.8},{zoom:2,size:3.4},{zoom:3,size:4.2},{zoom:4,size:5.3},{zoom:5,size:6.8},{zoom:6,size:8.4},{zoom:7,size:9.8},{zoom:8,size:11.2},{zoom:9,size:14},{zoom:10,size:17.5},{zoom:11,size:22},{zoom:12,size:28}],Dl=.1,Nl=5,Bl=0,kl=1,Ul=0,zl=1,Ol=-100,Yl=100,Wl=2e3;function nn(t){return t*Math.PI/180}function Ut(t,e){return!t||!e?t===e:t.buffer===e.buffer&&t.byteOffset===e.byteOffset&&t.byteLength===e.byteLength}function Jt(t){return t.map(e=>({zoom:e.zoom,size:e.size}))}function Wr(t){if(!t)return Jt(In);const e=new Map;for(const[n,r]of Object.entries(t)){const i=Number(n),o=Number(r);!Number.isFinite(i)||!Number.isFinite(o)||o<=0||e.set(i,o)}return e.size===0?Jt(In):Array.from(e.entries()).sort((n,r)=>n[0]-r[0]).map(([n,r])=>({zoom:n,size:r}))}function Xl(t,e){if(t===e)return!0;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1)if(t[n].zoom!==e[n].zoom||t[n].size!==e[n].size)return!1;return!0}function Vl(t,e){if(!Number.isFinite(t))return e[0]?.size??Tn;if(e.length===0)return Tn;if(e.length===1||t<=e[0].zoom)return e[0].size;for(let s=1;s<e.length;s+=1){const a=e[s-1],l=e[s];if(t>l.zoom)continue;const u=Math.max(1e-6,l.zoom-a.zoom),f=L((t-a.zoom)/u,0,1);return a.size+(l.size-a.size)*f}const n=e[e.length-1],r=e[e.length-2],i=Math.max(1e-6,n.zoom-r.zoom),o=(n.size-r.size)/i;return n.size+(t-n.zoom)*o}function Xr(t){return typeof t!="number"||!Number.isFinite(t)?1:L(t,Dl,Nl)}function Vr(t){return typeof t!="number"||!Number.isFinite(t)?1:L(t,Bl,kl)}function Gl(t){return t?[L(t[0],0,100),L(t[1],0,100)]:[1,0]}function Gr(t){return typeof t!="number"||!Number.isFinite(t)?0:L(t,Ul,zl)}function fn(t){return typeof t!="number"||!Number.isFinite(t)?0:L(t,Ol,Yl)}function qr(t){const e=fn(t?.brightness),n=fn(t?.contrast),r=fn(t?.saturation);return{brightness:e/200,contrast:n/100,saturation:r/100}}function Gn(t){return t}function hn(t){return typeof t!="number"||!Number.isFinite(t)?0:L(t,0,Wl)}function zt(t){return typeof t!="number"||!Number.isFinite(t)||t<=0?null:Math.max(1e-6,t)}function dn(t){return typeof t=="function"?t:Gn}function Vi(t,e,n){const r=t.getBoundingClientRect(),i=e-r.left-r.width*.5,o=n-r.top-r.height*.5;return Math.atan2(o,i)}function Gi(t,e){if(e.pointerId!==null&&t.hasPointerCapture(e.pointerId))try{t.releasePointerCapture(e.pointerId)}catch{}e.dragging=!1,e.mode="none",e.rotateLastAngleRad=null,e.pointerId=null,t.classList.remove("dragging")}function ql(t){const{event:e,canvas:n,state:r,config:i,cancelViewAnimation:o}=t,s=i.ctrlDragRotate&&(e.ctrlKey||e.metaKey);(e.button===0||s&&e.button===2)&&(o(),s&&e.preventDefault(),r.dragging=!0,r.mode=s?"rotate":"pan",r.pointerId=e.pointerId,r.lastPointerX=e.clientX,r.lastPointerY=e.clientY,r.rotateLastAngleRad=r.mode==="rotate"?Vi(n,e.clientX,e.clientY):null,n.classList.add("dragging"),n.setPointerCapture(e.pointerId))}function Hl(t){const{event:e,canvas:n,state:r,config:i,camera:o,clampViewState:s,emitViewState:a,requestRender:l}=t;if(!r.dragging||e.pointerId!==r.pointerId)return;const u=e.clientX-r.lastPointerX,f=e.clientY-r.lastPointerY;if(r.lastPointerX=e.clientX,r.lastPointerY=e.clientY,r.mode==="rotate"){const c=Vi(n,e.clientX,e.clientY),h=r.rotateLastAngleRad;if(r.rotateLastAngleRad=c,h!==null){const d=c-h,m=Math.atan2(Math.sin(d),Math.cos(d)),g=i.rotationDragSensitivityDegPerPixel/vn,y=o.getViewState();o.setViewState({rotationDeg:y.rotationDeg-m*180/Math.PI*g})}}else{const c=o.getViewState(),h=Math.max(1e-6,c.zoom),d=nn(c.rotationDeg),m=Math.cos(d),g=Math.sin(d),y=(u*m-f*g)/h,b=(u*g+f*m)/h;o.setViewState({offsetX:c.offsetX-y,offsetY:c.offsetY-b})}s(),a(),l()}function Zl(t,e,n){t.pointerId===n.pointerId&&Gi(e,n)}function $l(t){const{event:e,canvas:n,onZoomBy:r}=t;e.preventDefault();const i=n.getBoundingClientRect(),o=e.clientX-i.left,s=e.clientY-i.top,a=e.deltaY<0?1.12:.89;r(a,o,s)}const Kl=4;function jl(t){const{event:e,canvas:n,snapState:r,onSnapZoom:i}=t;e.preventDefault();const o=e.deltaY<0?"in":e.deltaY>0?"out":null;if(o&&r.blockedDirection)if(o!==r.blockedDirection)r.blockedDirection=null,r.accumulatedDelta=0;else return;if(r.accumulatedDelta!==0&&e.deltaY!==0&&Math.sign(r.accumulatedDelta)!==Math.sign(e.deltaY)&&(r.accumulatedDelta=0),r.accumulatedDelta+=e.deltaY,Math.abs(r.accumulatedDelta)<Kl)return;const s=n.getBoundingClientRect(),a=e.clientX-s.left,l=e.clientY-s.top,u=r.accumulatedDelta>0?"out":"in";if(r.accumulatedDelta=0,!i(u,a,l)){r.blockedDirection=u;return}r.blockedDirection=null}function Ql(t){const{event:e,canvas:n,onZoomBy:r}=t,i=n.getBoundingClientRect(),o=e.clientX-i.left,s=e.clientY-i.top;r(e.shiftKey?.8:1.25,o,s)}function Jl(t,e){(e||t.ctrlKey||t.metaKey)&&t.preventDefault()}function en(t){const e=t.getViewCorners();let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[s,a]of e)s<n&&(n=s),s>i&&(i=s),a<r&&(r=a),a>o&&(o=a);return[n,r,i,o]}function Vt(t,e,n=.2,r=.2){const i=en(t),o=Math.max(1e-6,i[2]-i[0]),s=Math.max(1e-6,i[3]-i[1]),a=o*n,l=s*r,[u,f]=t.getCenter(),c=o*.5,h=s*.5,d=c-a,m=e.width-c+a,g=h-l,y=e.height-h+l,b=d<=m?L(u,d,m):e.width*.5,x=g<=y?L(f,g,y):e.height*.5;t.setCenter(b,x)}function ec(t,e){const n=Math.max(1e-6,t.getViewState().zoom),r=e.maxTierZoom+Math.log2(n);return L(Math.floor(r),0,e.maxTierZoom)}function tc(t,e){return!(t[2]<=e[0]||t[0]>=e[2]||t[3]<=e[1]||t[1]>=e[3])}function qi(t,e,n){const r=en(t),i=Math.pow(2,e.maxTierZoom-n),o=Math.ceil(e.width/i),s=Math.ceil(e.height/i),a=Math.max(1,Math.ceil(o/e.tileSize)),l=Math.max(1,Math.ceil(s/e.tileSize)),u=r[0],f=r[1],c=r[2],h=r[3],d=L(Math.floor(u/i/e.tileSize),0,a-1),m=L(Math.floor((c-1)/i/e.tileSize),0,a-1),g=L(Math.floor(f/i/e.tileSize),0,l-1),y=L(Math.floor((h-1)/i/e.tileSize),0,l-1);if(d>m||g>y)return[];const b=(u+c)*.5/i/e.tileSize,x=(f+h)*.5/i/e.tileSize,A=[];for(let S=g;S<=y;S+=1)for(let C=d;C<=m;C+=1){const M=C*e.tileSize*i,P=S*e.tileSize*i,U=Math.min((C+1)*e.tileSize,o)*i,O=Math.min((S+1)*e.tileSize,s)*i,N=C-b,v=S-x;A.push({key:`${n}/${C}/${S}`,tier:n,x:C,y:S,bounds:[M,P,U,O],distance2:N*N+v*v,url:Vn(e,n,C,S)})}return A.sort((S,C)=>S.distance2-C.distance2),A}function nc(t,e){const n=ec(t,e);return{tier:n,visible:qi(t,e,n)}}function rc(t){t.interactionLocked||ql({event:t.event,canvas:t.canvas,state:t.state,config:{ctrlDragRotate:t.ctrlDragRotate,rotationDragSensitivityDegPerPixel:t.rotationDragSensitivityDegPerPixel},cancelViewAnimation:t.cancelViewAnimation})}function ic(t){t.interactionLocked||Hl({event:t.event,canvas:t.canvas,state:t.state,config:{ctrlDragRotate:t.ctrlDragRotate,rotationDragSensitivityDegPerPixel:t.rotationDragSensitivityDegPerPixel},camera:t.camera,clampViewState:()=>Vt(t.camera,t.source,t.panExtentX,t.panExtentY),emitViewState:t.emitViewState,requestRender:t.requestRender})}function oc(t){t.interactionLocked||Zl(t.event,t.canvas,t.state)}function sc(t){t.interactionLocked||Ql({event:t.event,canvas:t.canvas,onZoomBy:t.onZoomBy})}function ac(t){Jl(t.event,t.state.dragging)}function lc(t,e){Gi(t,e)}function cc(t){return{pointerDown:e=>rc({event:e,interactionLocked:t.getInteractionLocked(),canvas:t.canvas,state:t.state,ctrlDragRotate:t.getCtrlDragRotate(),rotationDragSensitivityDegPerPixel:t.getRotationDragSensitivityDegPerPixel(),cancelViewAnimation:t.cancelViewAnimation}),pointerMove:e=>ic({event:e,interactionLocked:t.getInteractionLocked(),canvas:t.canvas,state:t.state,ctrlDragRotate:t.getCtrlDragRotate(),rotationDragSensitivityDegPerPixel:t.getRotationDragSensitivityDegPerPixel(),camera:t.camera,source:t.source,panExtentX:t.getPanExtentX(),panExtentY:t.getPanExtentY(),emitViewState:t.emitViewState,requestRender:t.requestRender}),pointerUp:e=>oc({event:e,interactionLocked:t.getInteractionLocked(),canvas:t.canvas,state:t.state}),wheel:e=>{if(t.getInteractionLocked()){e.preventDefault();return}if(t.getUseZoomSnaps?.()&&t.onSnapZoom&&t.zoomSnapState){jl({event:e,canvas:t.canvas,snapState:t.zoomSnapState,onSnapZoom:t.onSnapZoom});return}$l({event:e,canvas:t.canvas,onZoomBy:t.zoomBy})},doubleClick:e=>sc({event:e,interactionLocked:t.getInteractionLocked(),canvas:t.canvas,onZoomBy:t.zoomBy}),contextMenu:e=>ac({event:e,canvas:t.canvas,state:t.state})}}function uc(t){const{gl:e,cache:n,maxCacheTiles:r}=t;if(n.size<=r)return;const i=Math.max(0,Math.floor(r));for(;n.size>i;){let o=null,s=null;for(const[a,l]of n)(!s||l.lastUsed<s.lastUsed)&&(o=a,s=l);if(!o||!s)break;e.deleteTexture(s.texture),n.delete(o)}}function fc(t,e){if(t.isContextLost())return null;const n=t.createTexture();return n?(t.bindTexture(t.TEXTURE_2D,n),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,1),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),t.bindTexture(t.TEXTURE_2D,null),n):null}function hc(t){const{gl:e,cache:n,tile:r,bitmap:i,frameSerial:o,maxCacheTiles:s,destroyed:a,contextLost:l,requestRender:u}=t;if(a||l||e.isContextLost()){i.close();return}if(n.has(r.key)){i.close();return}const f=fc(e,i);i.close(),f&&(n.set(r.key,{key:r.key,texture:f,bounds:r.bounds,tier:r.tier,lastUsed:o}),uc({gl:e,cache:n,maxCacheTiles:s}),u())}function dc(t,e){for(const[,n]of e)t.deleteTexture(n.texture)}function mc(t){const{event:e,destroyed:n,contextLost:r,cancelViewAnimation:i,cancelDrag:o,tileScheduler:s,cache:a,onContextLost:l}=t;if(e.preventDefault(),n||r)return{handled:!1,frame:t.frame};let u=t.frame;return u!==null&&(cancelAnimationFrame(u),u=null),i(),o(),s.clear(),a.clear(),l?.(),{handled:!0,frame:u}}function gc(t){if(t.destroyed)return{didDestroy:!1,frame:t.frame};let e=t.frame;if(e!==null&&(cancelAnimationFrame(e),e=null),t.cancelViewAnimation(),t.resizeObserver.disconnect(),t.removeDprListener(),t.removeCanvasEventListeners(),t.cancelDrag(),t.tileScheduler.destroy(),!t.contextLost&&!t.gl.isContextLost()){dc(t.gl,t.cache),t.gl.deleteBuffer(t.tileProgram.vbo),t.gl.deleteVertexArray(t.tileProgram.vao),t.gl.deleteProgram(t.tileProgram.program);for(let n=0;n<t.pointPrograms.length;n+=1){const r=t.pointPrograms[n];t.gl.deleteBuffer(r.posBuffer),t.gl.deleteBuffer(r.classBuffer),t.gl.deleteBuffer(r.fillModeBuffer),t.gl.deleteBuffer(r.indexBuffer),t.gl.deleteTexture(r.paletteTexture),t.gl.deleteVertexArray(r.vao),t.gl.deleteProgram(r.program)}}return t.cache.clear(),{didDestroy:!0,frame:e}}function pc(t,e){if(e<=0||t.length===0)return new Uint32Array(0);let n=t.length;for(let o=0;o<t.length;o+=1)t[o]<e||(n-=1);if(n===t.length)return t;if(n<=0)return new Uint32Array(0);const r=new Uint32Array(n);let i=0;for(let o=0;o<t.length;o+=1){const s=t[o];s>=e||(r[i]=s,i+=1)}return r}function yc(t,e){return e<=0?new Uint8Array(0):t.length<e?new Uint8Array(e):t.subarray(0,e)}function Hr(t,e,n,r,i){if(!i||i.length===0)return{...t,lastPointPalette:null};const o=new Uint8Array(i);if(r||e.isContextLost())return{...t,lastPointPalette:o};const s=Math.max(1,Math.floor(o.length/4));return e.bindTexture(e.TEXTURE_2D,n.paletteTexture),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,s,1,0,e.RGBA,e.UNSIGNED_BYTE,o),e.bindTexture(e.TEXTURE_2D,null),{...t,lastPointPalette:o,pointPaletteSize:s}}function Zr(t,e,n,r,i){if(!i||!i.count||!i.positions||!i.paletteIndices)return{...t,lastPointData:null,pointCount:0,usePointIndices:!1};const o=i.fillModes instanceof Uint8Array?i.fillModes:null,s=o!==null,a=Math.max(0,Math.min(i.count,Math.floor(i.positions.length/2),i.paletteIndices.length,s?o.length:Number.MAX_SAFE_INTEGER)),l=i.positions.subarray(0,a*2),u=i.paletteIndices.subarray(0,a),f=s?o.subarray(0,a):void 0,c=i.drawIndices instanceof Uint32Array,h=c?pc(i.drawIndices,a):null,d=t.lastPointData,m=d?.fillModes instanceof Uint8Array,g=t.pointBuffersDirty||!d||d.count!==a||!Ut(d.positions,l)||!Ut(d.paletteIndices,u)||m!==s||s&&(!d?.fillModes||!Ut(d.fillModes,f)),y=t.pointBuffersDirty||c&&(!d?.drawIndices||!Ut(d.drawIndices,h))||!c&&!!d?.drawIndices,b={...t,lastPointData:{count:a,positions:l,paletteIndices:u,fillModes:f,drawIndices:c?h??void 0:void 0}};if(r||e.isContextLost())return b;const x=b.lastPointData;if(!x)return b;if(g){e.bindBuffer(e.ARRAY_BUFFER,n.posBuffer),e.bufferData(e.ARRAY_BUFFER,x.positions,e.STATIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,n.classBuffer),e.bufferData(e.ARRAY_BUFFER,x.paletteIndices,e.STATIC_DRAW);const A=yc(b.zeroFillModes,a);e.bindBuffer(e.ARRAY_BUFFER,n.fillModeBuffer),e.bufferData(e.ARRAY_BUFFER,x.fillModes??A,e.STATIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,null),b.zeroFillModes=A}return c&&y&&(e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n.indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,h??new Uint32Array(0),e.DYNAMIC_DRAW),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),b.usePointIndices=c,b.pointCount=c?h?.length??0:x.count,(g||y)&&(b.pointBuffersDirty=!1),b}function bc(t){const{gl:e,camera:n,source:r,cache:i,frameSerial:o,tileProgram:s,imageColorSettings:a,pointLayers:l,tileScheduler:u,getVisibleTiles:f,getVisibleTilesForTier:c,getViewBounds:h,intersectsBounds:d}=t;e.clearColor(.03,.06,.1,1),e.clear(e.COLOR_BUFFER_BIT);const{tier:m,visible:g}=f(),y=h(),b=new Set(g.map(N=>N.key));e.useProgram(s.program),e.bindVertexArray(s.vao),e.uniformMatrix3fv(s.uCamera,!1,n.getMatrix()),e.uniform1i(s.uTexture,0),e.uniform1f(s.uBrightness,a.brightness),e.uniform1f(s.uContrast,a.contrast),e.uniform1f(s.uSaturation,a.saturation);const x=[];for(const[,N]of i)b.has(N.key)||d(N.bounds,y)&&x.push(N);x.sort((N,v)=>N.tier-v.tier);for(const N of x)N.lastUsed=o,e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,N.texture),e.uniform4f(s.uBounds,N.bounds[0],N.bounds[1],N.bounds[2],N.bounds[3]),e.drawArrays(e.TRIANGLE_STRIP,0,4);let A=0;const S=[];for(const N of g){const v=i.get(N.key);if(!v){S.push(N);continue}v.lastUsed=o,e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,v.texture),e.uniform4f(s.uBounds,v.bounds[0],v.bounds[1],v.bounds[2],v.bounds[3]),e.drawArrays(e.TRIANGLE_STRIP,0,4),A+=1}const C=S.slice(),M=1e6,P=[];m>0&&P.push(m-1),m<r.maxTierZoom&&P.push(m+1);for(const N of P){const v=c(N);for(const B of v)i.has(B.key)||(B.distance2+=M,C.push(B))}u.schedule(C),e.bindTexture(e.TEXTURE_2D,null),e.bindVertexArray(null);let U=0,O=0;if(l.length>0){e.enable(e.BLEND),e.blendFunc(e.ONE,e.ONE_MINUS_SRC_ALPHA);for(let N=0;N<l.length;N+=1){const v=l[N];v.pointCount<=0||(e.useProgram(v.pointProgram.program),e.bindVertexArray(v.pointProgram.vao),e.uniformMatrix3fv(v.pointProgram.uCamera,!1,n.getMatrix()),e.uniform1f(v.pointProgram.uPointSize,v.pointSizePx),e.uniform1f(v.pointProgram.uPointCssSize,v.pointCssSizePx),e.uniform2f(v.pointProgram.uPointLineDash,v.pointLineDash[0],v.pointLineDash[1]),e.uniform1f(v.pointProgram.uPointOpacity,v.pointOpacity),e.uniform1f(v.pointProgram.uPointStrokeScale,v.pointStrokeScale),e.uniform1f(v.pointProgram.uPointInnerFillAlpha,v.pointInnerFillOpacity),e.uniform1f(v.pointProgram.uPaletteSize,v.pointPaletteSize),e.uniform1i(v.pointProgram.uPalette,1),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,v.pointProgram.paletteTexture),v.usePointIndices?e.drawElements(e.POINTS,v.pointCount,e.UNSIGNED_INT,0):e.drawArrays(e.POINTS,0,v.pointCount),U+=v.pointCount,O+=1)}e.bindTexture(e.TEXTURE_2D,null),e.bindVertexArray(null)}return{tier:m,visible:g.length,rendered:A,points:U,fallback:x.length,cacheHits:A,cacheMisses:S.length,drawCalls:x.length+A+O}}function $r(t){const r=bt(t,`#version 300 es
134
+ `;function ja(){if(typeof navigator>"u")return!1;const t=navigator;return typeof t.gpu=="object"&&t.gpu!==null}function Oi(){if(!ja())return null;const e=navigator.gpu;if(!e||typeof e!="object")return null;const n=e;return typeof n.requestAdapter!="function"?null:n}const Nt=globalThis.GPUShaderStage?.COMPUTE??4,un=globalThis.GPUBufferUsage?.STORAGE??128,Bt=globalThis.GPUBufferUsage?.COPY_DST??8,Qa=globalThis.GPUBufferUsage?.COPY_SRC??4,Ja=globalThis.GPUBufferUsage?.UNIFORM??64,el=globalThis.GPUBufferUsage?.MAP_READ??1,tl=globalThis.GPUMapMode?.READ??1;async function nl(){const t=Oi();if(!t)return{supported:!1,features:[]};const e=await t.requestAdapter();return e?{supported:!0,adapterName:e.info?.description??e.info?.vendor??"unknown",features:Array.from(e.features),limits:{maxStorageBufferBindingSize:Number(e.limits.maxStorageBufferBindingSize),maxComputeInvocationsPerWorkgroup:Number(e.limits.maxComputeInvocationsPerWorkgroup),maxComputeWorkgroupSizeX:Number(e.limits.maxComputeWorkgroupSizeX)}}:{supported:!1,features:[]}}async function rl(){return Dt||(Dt=(async()=>{const t=Oi();if(!t)return null;const e=await t.requestAdapter();if(!e)return null;const n=await e.requestDevice(),r=n.createBindGroupLayout({entries:[{binding:0,visibility:Nt,buffer:{type:"read-only-storage"}},{binding:1,visibility:Nt,buffer:{type:"read-only-storage"}},{binding:2,visibility:Nt,buffer:{type:"storage"}},{binding:3,visibility:Nt,buffer:{type:"uniform"}}]}),i=n.createComputePipeline({layout:n.createPipelineLayout({bindGroupLayouts:[r]}),compute:{module:n.createShaderModule({code:Ka}),entryPoint:"main"}});return{device:n,pipeline:i,bindGroupLayout:r}})(),Dt)}function kt(t,e){return Math.ceil(t/e)*e}async function Yi(t,e,n){const r=await rl();if(!r)return null;const i=Math.max(0,Math.floor(e)),o=Math.max(0,Math.floor(n.length/4));if(i===0||o===0)return new Uint32Array(0);const s=Math.min(i,Math.floor(t.length/2));if(s===0)return new Uint32Array(0);const a=s*2*Float32Array.BYTES_PER_ELEMENT,l=o*4*Float32Array.BYTES_PER_ELEMENT,u=s*Uint32Array.BYTES_PER_ELEMENT,f=Number(r.device.limits.maxStorageBufferBindingSize);if(a>f||l>f||u>f)return null;const c=r.device.createBuffer({size:kt(a,4),usage:un|Bt}),h=r.device.createBuffer({size:kt(l,4),usage:un|Bt}),d=r.device.createBuffer({size:kt(u,4),usage:un|Qa}),m=r.device.createBuffer({size:16,usage:Ja|Bt}),g=r.device.createBuffer({size:kt(u,4),usage:Bt|el});let b=!1;try{r.device.queue.writeBuffer(c,0,t.buffer,t.byteOffset,a),r.device.queue.writeBuffer(h,0,n.buffer,n.byteOffset,l),r.device.queue.writeBuffer(m,0,new Uint32Array([s,o,0,0]));const y=r.device.createBindGroup({layout:r.bindGroupLayout,entries:[{binding:0,resource:{buffer:c}},{binding:1,resource:{buffer:h}},{binding:2,resource:{buffer:d}},{binding:3,resource:{buffer:m}}]}),w=r.device.createCommandEncoder(),A=w.beginComputePass();A.setPipeline(r.pipeline),A.setBindGroup(0,y),A.dispatchWorkgroups(Math.ceil(s/256)),A.end(),w.copyBufferToBuffer(d,0,g,0,u),r.device.queue.submit([w.finish()]),await g.mapAsync(tl),b=!0;const S=g.getMappedRange();return new Uint32Array(S.slice(0))}finally{if(b)try{g.unmap()}catch{}c.destroy(),h.destroy(),d.destroy(),m.destroy(),g.destroy()}}async function Xi(t,e,n={}){const r=we(),i=n.bridgeToDraw===!0;if(!t||!t.count||!t.positions||!t.paletteIndices)return{data:null,meta:{mode:"hybrid-webgpu",durationMs:we()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}};const o=dt(e??[]);if(o.length===0){const S={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return t.fillModes instanceof Uint8Array&&(S.fillModes=new Uint8Array(0)),t.ids instanceof Uint32Array&&(S.ids=new Uint32Array(0)),{data:S,meta:{mode:"hybrid-webgpu",durationMs:we()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const s=ot(t),a=t.fillModes instanceof Uint8Array&&t.fillModes.length>=s?t.fillModes:null,l=t.ids instanceof Uint32Array&&t.ids.length>=s?t.ids:null;if(s===0){const S={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(S.fillModes=new Uint8Array(0)),l&&(S.ids=new Uint32Array(0)),{data:S,meta:{mode:"hybrid-webgpu",durationMs:we()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const u=new Float32Array(o.length*4);for(let S=0;S<o.length;S+=1){const C=S*4,M=o[S];u[C]=M.minX,u[C+1]=M.minY,u[C+2]=M.maxX,u[C+3]=M.maxY}let f=null,c=!1;try{f=await Yi(t.positions,s,u),c=!!f}catch{f=null,c=!1}if(!f)return{data:Rt(t,e),meta:{mode:"hybrid-webgpu",durationMs:we()-r,usedWebGpu:!1,candidateCount:s,bridgedToDraw:!1}};let h=0;for(let S=0;S<s;S+=1)f[S]===1&&(h+=1);const d=new Uint32Array(h);if(h>0){let S=0;for(let C=0;C<s;C+=1)f[C]===1&&(d[S]=C,S+=1)}if(h===0){if(i){const C={count:s,positions:t.positions.subarray(0,s*2),paletteIndices:t.paletteIndices.subarray(0,s),drawIndices:new Uint32Array(0)};return a&&(C.fillModes=a.subarray(0,s)),l&&(C.ids=l.subarray(0,s)),{data:C,meta:{mode:"hybrid-webgpu",durationMs:we()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!0}}}const S={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(S.fillModes=new Uint8Array(0)),l&&(S.ids=new Uint32Array(0)),{data:S,meta:{mode:"hybrid-webgpu",durationMs:we()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!1}}}if(i){const S=new Uint32Array(h);let C=0;for(let P=0;P<h;P+=1){const O=d[P]??0,W=t.positions[O*2],L=t.positions[O*2+1];St(W,L,o)&&(S[C]=O,C+=1)}const M={count:s,positions:t.positions.subarray(0,s*2),paletteIndices:t.paletteIndices.subarray(0,s),drawIndices:S.subarray(0,C)};return a&&(M.fillModes=a.subarray(0,s)),l&&(M.ids=l.subarray(0,s)),{data:M,meta:{mode:"hybrid-webgpu",durationMs:we()-r,usedWebGpu:!0,candidateCount:h,bridgedToDraw:!0}}}const m=new Float32Array(h*2),g=new Uint16Array(h),b=a?new Uint8Array(h):null,y=l?new Uint32Array(h):null;let w=0;for(let S=0;S<h;S+=1){const C=d[S]??0,M=t.positions[C*2],P=t.positions[C*2+1];St(M,P,o)&&(m[w*2]=M,m[w*2+1]=P,g[w]=t.paletteIndices[C],b&&(b[w]=a[C]),y&&(y[w]=l[C]),w+=1)}const A={count:w,positions:m.subarray(0,w*2),paletteIndices:g.subarray(0,w)};return b&&(A.fillModes=b.subarray(0,w)),y&&(A.ids=y.subarray(0,w)),{data:A,meta:{mode:"hybrid-webgpu",durationMs:we()-r,usedWebGpu:!0,candidateCount:h,bridgedToDraw:!1}}}class Wi{constructor(e,n){E(this,"worker",null);E(this,"supported",!0);E(this,"requestId",1);E(this,"pendingById",new Map);E(this,"handleMessage",e=>{const n=e.data;if(!n)return;const r=this.pendingById.get(n.id);r&&(this.pendingById.delete(n.id),this.handlers.onResponse(n,r))});E(this,"handleError",()=>{this.supported=!1,this.teardownWorker("worker crashed")});this.createWorker=e,this.handlers=n}beginRequest(e){const n=this.getOrCreateWorker();if(!n)return null;const r=this.requestId++;return this.pendingById.set(r,e),{id:r,worker:n}}cancelRequest(e){const n=this.pendingById.get(e);if(n)return this.pendingById.delete(e),n}terminate(e="worker terminated"){this.teardownWorker(e)}getOrCreateWorker(){if(!this.supported)return null;if(this.worker)return this.worker;try{const e=this.createWorker();return e.addEventListener("message",this.handleMessage),e.addEventListener("error",this.handleError),this.worker=e,e}catch{return this.supported=!1,null}}teardownWorker(e){this.worker&&(this.worker.removeEventListener("message",this.handleMessage),this.worker.removeEventListener("error",this.handleError),this.worker.terminate(),this.worker=null);const n=new Error(e);for(const[,r]of this.pendingById)this.handlers.rejectPending(r,n);this.pendingById.clear()}}const At=new Wi(()=>new Worker(new URL(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/roi-clip-worker-CHxxL_lK.js").href:new URL("assets/roi-clip-worker-CHxxL_lK.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),typeof document>"u"?require("url").pathToFileURL(__filename).href:ft&&ft.tagName.toUpperCase()==="SCRIPT"&&ft.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),{onResponse:(t,e)=>{if(t.type==="roi-clip-failure"){e.reject(new Error(t.error||"worker clip failed"));return}if(t.type==="roi-clip-index-success"){if(e.kind!=="index"){e.reject(new Error("worker response mismatch: expected point data result"));return}const l=Math.max(0,Math.floor(t.count)),u=new Uint32Array(t.indices).subarray(0,l);e.resolve({indices:u,meta:{mode:"worker",durationMs:Number.isFinite(t.durationMs)?t.durationMs:we()-e.startMs}});return}if(e.kind!=="data"){e.reject(new Error("worker response mismatch: expected index result"));return}const n=Math.max(0,Math.floor(t.count)),r=new Float32Array(t.positions),i=new Uint16Array(t.paletteIndices),o=t.fillModes?new Uint8Array(t.fillModes):null,s=t.ids?new Uint32Array(t.ids):null,a={count:n,positions:r.subarray(0,n*2),paletteIndices:i.subarray(0,n)};o&&(a.fillModes=o.subarray(0,n)),s&&(a.ids=s.subarray(0,n)),e.resolve({data:a,meta:{mode:"worker",durationMs:Number.isFinite(t.durationMs)?t.durationMs:we()-e.startMs}})},rejectPending:(t,e)=>{t.reject(e)}});function il(){At.terminate("worker terminated")}async function Vi(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return{data:null,meta:{mode:"worker",durationMs:0}};const n=ot(t),r=t.positions.slice(0,n*2),i=t.paletteIndices.slice(0,n),o=t.fillModes instanceof Uint8Array&&t.fillModes.length>=n?t.fillModes.slice(0,n):null,s=t.ids instanceof Uint32Array&&t.ids.length>=n?t.ids.slice(0,n):null;return new Promise((a,l)=>{const u=we(),f=At.beginRequest({kind:"data",resolve:a,reject:l,startMs:u});if(!f){a({data:Rt(t,e),meta:{mode:"sync",durationMs:we()-u}});return}const c={type:"roi-clip-request",id:f.id,count:n,positions:r.buffer,paletteIndices:i.buffer,fillModes:o?.buffer,ids:s?.buffer,polygons:e??[]},h=[r.buffer,i.buffer];o&&h.push(o.buffer),s&&h.push(s.buffer);try{f.worker.postMessage(c,h)}catch(d){const m=At.cancelRequest(f.id);m?m.reject(d):l(d)}})}async function ol(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return{indices:new Uint32Array(0),meta:{mode:"worker",durationMs:0}};const n=ot(t),r=t.positions.slice(0,n*2);return new Promise((i,o)=>{const s=we(),a=At.beginRequest({kind:"index",resolve:i,reject:o,startMs:s});if(!a){i({indices:zi(t,e),meta:{mode:"sync",durationMs:we()-s}});return}const l={type:"roi-clip-index-request",id:a.id,count:n,positions:r.buffer,polygons:e??[]};try{a.worker.postMessage(l,[r.buffer])}catch(u){const f=At.cancelRequest(a.id);f?f.reject(u):o(u)}})}const sl={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};function al(t,e,n,r,i){const o=p.useRef(0),[s,a]=p.useState(n),l=p.useMemo(()=>r.map(u=>ht(u.coordinates)).filter(u=>u!=null),[r]);return p.useEffect(()=>{const u=++o.current;let f=!1;if(!t)return a(n),()=>{f=!0};if(!n||!n.count||!n.positions||!n.paletteIndices)return a(null),()=>{f=!0};if(l.length===0)return a(sl),i?.({mode:e,durationMs:0,inputCount:n.count,outputCount:0,polygonCount:0}),()=>{f=!0};const c=(d,m)=>{if(f||u!==o.current)return;const g=n.count,b=d?.drawIndices?d.drawIndices.length:d?.count??0;a(d),i?.({mode:m.mode,durationMs:m.durationMs,inputCount:g,outputCount:b,polygonCount:l.length,usedWebGpu:m.usedWebGpu,candidateCount:m.candidateCount,bridgedToDraw:m.bridgedToDraw})};return(async()=>{if(e==="sync"){const d=performance.now(),m=Rt(n,l);c(m,{mode:"sync",durationMs:performance.now()-d});return}if(e==="hybrid-webgpu"){const d=await Xi(n,l,{bridgeToDraw:!0});c(d.data,{mode:d.meta.mode,durationMs:d.meta.durationMs,usedWebGpu:d.meta.usedWebGpu,candidateCount:d.meta.candidateCount,bridgedToDraw:d.meta.bridgedToDraw});return}try{const d=await Vi(n,l);c(d.data,{mode:d.meta.mode,durationMs:d.meta.durationMs})}catch{const d=performance.now(),m=Rt(n,l);c(m,{mode:"sync",durationMs:performance.now()-d})}})(),()=>{f=!0}},[t,e,n,l,i]),s}const ll=24,cl=1024,ul=4,Wt=-1;function pt(t,e,n){return(t*73856093^e*19349663)>>>0&n}function fl(t,e,n){if(t<=0||e<=0||n<=0)return 256;const r=Math.max(1,t*e),o=Math.sqrt(r/Math.max(1,n))*ul;return Math.max(ll,Math.min(cl,o))}function hl(t,e){if(!(t instanceof Uint32Array)||t.length===0)return null;let n=!0;for(let o=0;o<t.length;o+=1)if(!(t[o]<e)){n=!1;break}if(n)return t;const r=new Uint32Array(t.length);let i=0;for(let o=0;o<t.length;o+=1)t[o]>=e||(r[i]=t[o],i+=1);return i>0?r.subarray(0,i):null}function dl(t){const e=Math.max(0,Math.floor(t.count)),n=Math.floor(t.positions.length/2),r=Math.max(0,Math.min(e,n));if(r<=0)return null;const i=hl(t.drawIndices??null,r),o=i?i.length:r;if(o===0)return null;const s=fl(t.sourceWidth,t.sourceHeight,o),a=1/s,l=new Int32Array(o),u=new Int32Array(o);let f=0;if(i)for(let I=0;I<o;I+=1){const Y=i[I],$=t.positions[Y*2],k=t.positions[Y*2+1];!Number.isFinite($)||!Number.isFinite(k)||(l[f]=Math.floor($*a),u[f]=Math.floor(k*a),f+=1)}else for(let I=0;I<r;I+=1){const Y=t.positions[I*2],$=t.positions[I*2+1];!Number.isFinite(Y)||!Number.isFinite($)||(l[f]=Math.floor(Y*a),u[f]=Math.floor($*a),f+=1)}if(f===0)return null;let c=Math.min(f,Math.max(64,f>>>3));(!Number.isFinite(c)||c<=0)&&(c=f);let h=1;for(;h<c*2;)h<<=1;let d=h-1,m=new Int32Array(h*2),g=new Int32Array(h);m.fill(2147483647);let b=0;const y=new Int32Array(f);for(let I=0;I<f;I+=1){const Y=l[I],$=u[I];let k=pt(Y,$,d);for(;;){const ae=m[k*2];if(ae===2147483647){if(m[k*2]=Y,m[k*2+1]=$,g[k]=1,y[I]=k,b+=1,b*4>h*3){const he=h;h<<=1,d=h-1;const J=new Int32Array(h*2),ve=new Int32Array(h);J.fill(2147483647);for(let Ce=0;Ce<he;Ce+=1){if(m[Ce*2]===2147483647)continue;const N=m[Ce*2],v=m[Ce*2+1];let z=pt(N,v,d);for(;J[z*2]!==2147483647;)z=z+1&d;J[z*2]=N,J[z*2+1]=v,ve[z]=g[Ce]}for(m=J,g=ve,k=pt(Y,$,d);m[k*2]!==Y||m[k*2+1]!==$;)k=k+1&d;y[I]=k}break}if(ae===Y&&m[k*2+1]===$){g[k]+=1,y[I]=k;break}k=k+1&d}}const w=new Int32Array(b*2),A=new Uint32Array(b),S=new Uint32Array(b),C=new Int32Array(h);C.fill(Wt);let M=0,P=0;for(let I=0;I<h;I+=1)m[I*2]!==2147483647&&(w[M*2]=m[I*2],w[M*2+1]=m[I*2+1],A[M]=P,S[M]=g[I],C[I]=M,P+=g[I],M+=1);const O=new Uint32Array(f),W=new Uint32Array(b);if(W.set(A),i)for(let I=0;I<f;I+=1){const Y=C[y[I]];O[W[Y]]=i[I],W[Y]+=1}else{let I=0;for(let Y=0;Y<r;Y+=1){const $=t.positions[Y*2],k=t.positions[Y*2+1];if(!Number.isFinite($)||!Number.isFinite(k))continue;const ae=C[y[I]];O[W[ae]]=Y,W[ae]+=1,I+=1}}let L=1;for(;L<b*2;)L<<=1;const T=L-1,D=new Int32Array(L);D.fill(Wt);for(let I=0;I<b;I+=1){const Y=w[I*2],$=w[I*2+1];let k=pt(Y,$,T);for(;D[k]!==Wt;)k=k+1&T;D[k]=I}return{cellSize:s,safeCount:r,cellCount:b,hashCapacity:L,hashTable:D,cellKeys:w,cellOffsets:A,cellLengths:S,pointIndices:O}}function Gi(t,e,n){const{hashTable:r,cellKeys:i,hashMask:o}=t;let s=pt(e,n,o);for(;;){const a=r[s];if(a===Wt)return-1;if(i[a*2]===e&&i[a*2+1]===n)return a;s=s+1&o}}function ml(t,e){if(t.safeCount<=0||t.cellCount<=0)return null;const n=t.safeCount;return{cellSize:t.cellSize,safeCount:n,positions:e.positions.subarray(0,n*2),ids:e.ids instanceof Uint32Array&&e.ids.length>=n?e.ids.subarray(0,n):null,hashCapacity:t.hashCapacity,hashMask:t.hashCapacity-1,hashTable:new Int32Array(t.hashTable),cellKeys:new Int32Array(t.cellKeys),cellOffsets:new Uint32Array(t.cellOffsets),cellLengths:new Uint32Array(t.cellLengths),pointIndices:new Uint32Array(t.pointIndices)}}const Pn=new Wi(()=>new Worker(new URL(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/point-hit-index-worker-CNFA6pZm.js").href:new URL("assets/point-hit-index-worker-CNFA6pZm.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),typeof document>"u"?require("url").pathToFileURL(__filename).href:ft&&ft.tagName.toUpperCase()==="SCRIPT"&&ft.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),{onResponse:(t,e)=>{if(t.type==="point-hit-index-failure"){e.reject(new Error(t.error||"worker index build failed"));return}e.resolve(ml(t,e.pointData))},rejectPending:(t,e)=>{t.reject(e)}});function gl(){Pn.terminate("worker terminated")}function pl(t,e){const n=ot(t);if(n<=0)return null;const r=t.positions.subarray(0,n*2),i=dl({count:n,positions:r,drawIndices:t.drawIndices instanceof Uint32Array?t.drawIndices:null,sourceWidth:e?.width??0,sourceHeight:e?.height??0});return i?{cellSize:i.cellSize,safeCount:n,positions:r,ids:t.ids instanceof Uint32Array&&t.ids.length>=n?t.ids.subarray(0,n):null,hashCapacity:i.hashCapacity,hashMask:i.hashCapacity-1,hashTable:i.hashTable,cellKeys:i.cellKeys,cellOffsets:i.cellOffsets,cellLengths:i.cellLengths,pointIndices:i.pointIndices}:null}async function qi(t,e){if(!t||!t.positions||!t.paletteIndices)return null;const n=ot(t);return n<=0?null:new Promise((r,i)=>{const o={resolve:r,reject:i,pointData:t},s=Pn.beginRequest(o);if(!s||!s.worker){r(pl(t,e));return}const a=t.positions.slice(0,n*2),l=t.drawIndices instanceof Uint32Array&&t.drawIndices.length>0?t.drawIndices.slice():void 0,u={type:"point-hit-index-request",id:s.id,count:n,positions:a.buffer,drawIndices:l?.buffer,sourceWidth:e?.width??0,sourceHeight:e?.height??0},f=[a.buffer];l&&f.push(l.buffer);try{s.worker.postMessage(u,f)}catch(c){const h=Pn.cancelRequest(s.id);h?h.reject(c):i(c)}})}const yl=.65,bl=4;function xl(t,e,n,r,i,o,s,a){const l=!!(n||r||i),[u,f]=p.useState(null),c=p.useRef(null),h=p.useRef(null);p.useEffect(()=>{if(!l||!t){f(null);return}let b=!1;return qi(t,e).then(y=>{b||f(y)}),()=>{b=!0}},[l,t,e]);const d=p.useCallback(b=>{const y=s.current;if(!y||!u)return null;const w=Number(b[0]),A=Number(b[1]);if(!Number.isFinite(w)||!Number.isFinite(A))return null;const S=Math.max(1e-6,y.getViewState().zoom),C=y.getPointSizeByZoom(a),P=Math.max(bl,C*yl)/S;if(!Number.isFinite(P)||P<=0)return null;const{cellSize:O,cellOffsets:W,cellLengths:L,pointIndices:T,positions:D,safeCount:I}=u,Y=Math.floor(w/O),$=Math.floor(A/O),k=Math.max(1,Math.ceil(P/O)),ae=P*P;let he=-1,J=ae,ve=0,Ce=0;for(let v=Y-k;v<=Y+k;v+=1)for(let z=$-k;z<=$+k;z+=1){const ie=Gi(u,v,z);if(ie<0)continue;const H=W[ie],ge=H+L[ie];for(let le=H;le<ge;le+=1){const ne=T[le];if(ne>=I)continue;const _e=D[ne*2],ue=D[ne*2+1],pe=_e-w,de=ue-A,re=pe*pe+de*de;re>J||(J=re,he=ne,ve=_e,Ce=ue)}}if(he<0)return null;const N=u.ids?Number(u.ids[he]):null;return{index:he,id:N,coordinate:[w,A],pointCoordinate:[ve,Ce]}},[a,u]),m=p.useCallback((b,y)=>{if(!n)return;const w=b?.index??null,A=b?.id??null;c.current===w&&h.current===A||(c.current=w,h.current=A,n({index:w,id:A,coordinate:y,pointCoordinate:b?.pointCoordinate??null}))},[n]),g=p.useCallback((b,y)=>{if(!r)return;const w=d(b);w&&r({...w,button:y})},[r,d]);return p.useEffect(()=>{if(i)return i.current=d,()=>{i.current===d&&(i.current=null)}},[i,d]),p.useEffect(()=>{const b=c.current;b!==null&&(u&&b<u.safeCount||(c.current=null,h.current=null,n?.({index:null,id:null,coordinate:null,pointCoordinate:null})))},[u,n]),p.useEffect(()=>{},[o,n]),{getCellByCoordinates:d,emitPointHover:m,emitPointClick:g}}let wl=0;const Sl=p.forwardRef(function({data:e=null,palette:n=null,sizeByZoom:r,opacity:i,strokeScale:o,innerFillOpacity:s,clipEnabled:a=!1,clipToRegions:l,clipMode:u="worker",onClipStats:f,onHover:c,onClick:h,dashed:d},m){const{rendererRef:g,rendererSerial:b,source:y}=st(),w=p.useRef(null),A=p.useRef(`__point_layer__${wl++}`),C=al(a,u,e,l??El,f),{getCellByCoordinates:M}=xl(C,y,c,h,w,"cursor",g,A.current);return p.useImperativeHandle(m,()=>({queryAt:M}),[M]),p.useEffect(()=>{const P=g.current;if(!P)return;const O=A.current;return P.registerPointLayer(O),()=>{P.unregisterPointLayer(O)}},[g,b]),p.useEffect(()=>{const P=g.current;P&&P.setPointPalette(n,A.current)},[b,n,g]),p.useEffect(()=>{const P=g.current;P&&P.setPointLineDash(d,A.current)},[b,d,g]),p.useEffect(()=>{const P=g.current;!P||r===void 0||P.setPointSizeByZoom(r,A.current)},[b,r,g]),p.useEffect(()=>{const P=g.current;!P||i===void 0||P.setPointOpacity(i,A.current)},[b,i,g]),p.useEffect(()=>{const P=g.current;!P||o===void 0||P.setPointStrokeScale(o,A.current)},[b,o,g]),p.useEffect(()=>{const P=g.current;!P||s===void 0||P.setPointInnerFillOpacity(s,A.current)},[b,s,g]),p.useEffect(()=>{const P=g.current;P&&P.setPointData(C,A.current)},[b,C,g]),null}),El=[],Rl=180,Xr=20;function Al(t){const e=F(t,0,1);return e*e*(3-2*e)}function Cl(t,e,n){const[r,i]=p.useState(0),o=p.useRef(0),s=p.useRef({rafId:null,startMs:0,from:0,to:0}),a=p.useCallback(c=>{const h=F(c,0,Xr);Math.abs(o.current-h)<1e-4||(o.current=h,i(h))},[]),l=p.useCallback(()=>{const c=s.current;c.rafId!==null&&(cancelAnimationFrame(c.rafId),c.rafId=null)},[]),u=p.useCallback(c=>{const h=F(c,0,Xr),d=s.current,m=o.current;if(Math.abs(m-h)<1e-4){l(),d.to=h,a(h);return}l(),d.startMs=performance.now(),d.from=m,d.to=h;const g=b=>{const y=s.current,w=Math.max(0,b-y.startMs),A=F(w/Rl,0,1),S=Al(A),C=y.from+(y.to-y.from)*S;if(a(C),n.current?.(),A>=1){y.rafId=null,a(y.to);return}y.rafId=requestAnimationFrame(g)};d.rafId=requestAnimationFrame(g)},[a,l]),f=p.useCallback(c=>{const h=e.current;if(!h||typeof c!="number"||!Number.isFinite(c)){u(0);return}const d=Yn(t,c,h.getZoomRange(),h.getRegionLabelAutoLiftCapZoom());u(d)},[t,u]);return p.useEffect(()=>()=>{l()},[l]),{regionLabelAutoLiftOffsetPx:r,syncRegionLabelAutoLiftTarget:f,cancelRegionLabelAutoLiftAnimation:l,applyRegionLabelAutoLiftOffset:a}}const Ml=6;function vn(t,e){return t.id??e}function Pl(t,e,n,r,i,o){const s=i-n,a=o-r,l=s*s+a*a;if(l<=1e-12){const m=t-n,g=e-r;return m*m+g*g}const u=F(((t-n)*s+(e-r)*a)/l,0,1),f=n+s*u,c=r+a*u,h=t-f,d=e-c;return h*h+d*d}function Wr(t,e,n,r){for(let i=1;i<n.length;i+=1){const o=n[i-1],s=n[i];if(Pl(t,e,o[0],o[1],s[0],s[1])<=r)return!0}return!1}function vl(t,e,n,r){if(t<n.minX-r||t>n.maxX+r||e<n.minY-r||e>n.maxY+r)return!1;const i=r*r;if(Wr(t,e,n.outer,i))return!0;for(const o of n.holes)if(Wr(t,e,o,i))return!0;return!1}function Tl(t,e,n,r,i,o,s,a){if(!t.label)return!1;const l=Un(t.polygons,S=>{const C=[];for(let M=0;M<S.length;M+=1){const P=Nn(n.worldToScreen(S[M][0],S[M][1]));if(!P)return[];C.push(P)}return C},r);if(!l)return!1;const f=kn(t.label,i)+i.paddingX*2,c=i.fontSize+i.paddingY*2,h=l[0],d=l[1]-i.offsetY,m=a?F(h,f*.5+1,o-f*.5-1):h,g=a?F(d,c*.5+1,s-c*.5-1):d,b=m-f*.5,y=m+f*.5,w=g-c*.5,A=g+c*.5;return e[0]>=b&&e[0]<=y&&e[1]>=w&&e[1]<=A}function Il(t){const e=[];for(let n=0;n<t.length;n+=1){const r=t[n],i=dt([ht(r?.coordinates)]);if(i.length===0)continue;const o=typeof r?.label=="string"?r.label.trim():"";e.push({region:r,regionIndex:n,regionId:vn(r,n),polygons:i,label:o})}return e}function Vr(t,e,n,r,i,o,s,a,l,u,f=!0){const c=t[0],h=t[1],d=Math.max(1e-6,r.getViewState().zoom),m=Math.max(0,a),g=Ml/d;for(let b=n.length-1;b>=0;b-=1){const y=n[b];for(const A of y.polygons)if(vl(c,h,A,g))return{region:y.region,regionIndex:y.regionIndex,regionId:y.regionId};let w=On(o,s?.({region:y.region,regionId:y.regionId,regionIndex:y.regionIndex,zoom:d}));if(m>0&&(w={...w,offsetY:w.offsetY+m}),!!Tl(y,e,r,i,w,l,u,f))return{region:y.region,regionIndex:y.regionIndex,regionId:y.regionId}}return null}const Gr=[],_l=[];let Ll=0;function Fl(t){return{color:di,width:mi,lineDash:it,lineJoin:t.lineJoin,lineCap:t.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function Dl({regions:t,polygons:e,strokeStyle:n,hoverStrokeStyle:r,activeStrokeStyle:i,resolveStrokeStyle:o,labelStyle:s,labelAnchor:a="top-center",autoLiftLabelAtMaxZoom:l=!1,clampLabelToViewport:u=!0,hoveredRegionId:f,activeRegionId:c,interactive:h=!0,onActiveChange:d,onHover:m,onClick:g}){const{rendererRef:b,rendererSerial:y,canvasRef:w,containerRef:A,registerDrawCallback:S,unregisterDrawCallback:C,requestOverlayRedraw:M,drawInvalidateRef:P,registerViewStateListener:O,screenToWorld:W,worldToScreen:L,isInteractionLocked:T}=st(),D=t??Gr,I=e??_l,Y=p.useMemo(()=>D.length>0?D:I.length===0?Gr:I.map((V,K)=>({id:K,coordinates:V})),[D,I]),[$,k]=p.useState(()=>f??null),[ae,he]=p.useState(()=>c??null),J=f!==void 0,ve=c!==void 0,Ce=J?f??null:$,N=ve?c??null:ae,v=p.useRef(f??null),z=p.useRef(null),ie=p.useRef(null);if(z.current===null||ie.current===null){const V=Ll++;z.current=`__region_layer__${V}`,ie.current=`__region_label__${V}`}p.useEffect(()=>{ve&&he(c??null)},[ve,c]),p.useEffect(()=>{if(!J)return;const V=f??null;v.current=V,k(V)},[J,f]);const H=p.useCallback(V=>{String(N)!==String(V)&&(ve||he(V),d?.(V))},[N,ve,d]),{regionLabelAutoLiftOffsetPx:ge,syncRegionLabelAutoLiftTarget:le}=Cl(l,b,P),ne=p.useMemo(()=>Bn(n),[n]),_e=p.useMemo(()=>Ke(ne,r),[ne,r]),ue=p.useMemo(()=>Ke(ne,i),[ne,i]),{staticLabelStyle:pe,labelStyleResolver:de}=p.useMemo(()=>typeof s=="function"?{staticLabelStyle:void 0,labelStyleResolver:s}:{staticLabelStyle:s,labelStyleResolver:void 0},[s]),re=p.useMemo(()=>zn(pe),[pe]),oe=p.useMemo(()=>{const V=[];for(let K=0;K<Y.length;K+=1){const fe=Y[K],te=jt(fe.coordinates);te.length!==0&&V.push({region:fe,regionIndex:K,regionKey:fe.id??K,polygons:te})}return V},[Y]),ce=p.useMemo(()=>Il(Y),[Y]);p.useEffect(()=>{const V=b.current;if(V)return le(V.getViewState().zoom),O(K=>{le(K.zoom)})},[y,O,le]),p.useEffect(()=>{!(N===null?!0:Y.some((te,j)=>String(vn(te,j))===String(N)))&&N!==null&&H(null);const K=v.current;!(K===null?!0:Y.some((te,j)=>String(vn(te,j))===String(K)))&&K!==null&&(v.current=null,J||k(null),m?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[Y,N,J,m,H]);const q=p.useCallback(V=>{const K=b.current;if(!K||V.length===0)return[];const fe=new Array(V.length);for(let te=0;te<V.length;te+=1){const j=He(K.worldToScreen(V[te][0],V[te][1]));if(!j)return[];fe[te]=j}return fe},[]),Pe=p.useRef({preparedRegions:oe,hoveredRegionId:Ce,activeRegionId:N,resolvedStrokeStyle:ne,resolvedHoverStrokeStyle:_e,resolvedActiveStrokeStyle:ue,resolveStrokeStyleProp:o,worldToScreenPoints:q});Pe.current={preparedRegions:oe,hoveredRegionId:Ce,activeRegionId:N,resolvedStrokeStyle:ne,resolvedHoverStrokeStyle:_e,resolvedActiveStrokeStyle:ue,resolveStrokeStyleProp:o,worldToScreenPoints:q},p.useEffect(()=>{const V=fe=>{const{preparedRegions:te,hoveredRegionId:j,activeRegionId:Re,resolvedStrokeStyle:X,resolvedHoverStrokeStyle:Te,resolvedActiveStrokeStyle:Fe,resolveStrokeStyleProp:U,worldToScreenPoints:Z}=Pe.current;for(const Q of te){const{region:ee,polygons:Se,regionIndex:be,regionKey:Ae}=Q,De=$t(Re,Ae)?"active":$t(j,Ae)?"hover":"default";let x=De==="active"?Fe:De==="hover"?Te:X;if(U){const _=U({region:ee,regionId:Ae,regionIndex:be,state:De});x=Ke(x,_||void 0)}const R=De==="default"?null:Fl(x);for(const _ of Se){const B=Z(_.outer);B.length>=4&&(R&&ke(fe,B,R,!0,!1),ke(fe,B,x,!0,!1));for(const G of _.holes){const me=Z(G);me.length>=4&&(R&&ke(fe,me,R,!0,!1),ke(fe,me,x,!0,!1))}}}},K=z.current;if(K)return S(K,10,V),()=>C(K)},[S,C]);const Ee=p.useRef({preparedRegions:oe,resolvedLabelStyle:re,labelStyleResolver:de,labelAnchor:a,autoLiftLabelAtMaxZoom:l,clampLabelToViewport:u,regionLabelAutoLiftOffsetPx:ge,rendererRef:b});Ee.current={preparedRegions:oe,resolvedLabelStyle:re,labelStyleResolver:de,labelAnchor:a,autoLiftLabelAtMaxZoom:l,clampLabelToViewport:u,regionLabelAutoLiftOffsetPx:ge,rendererRef:b},p.useEffect(()=>{const V=(fe,te,j)=>{const{preparedRegions:Re,resolvedLabelStyle:X,labelStyleResolver:Te,labelAnchor:Fe,autoLiftLabelAtMaxZoom:U,clampLabelToViewport:Z,regionLabelAutoLiftOffsetPx:Q,rendererRef:ee}=Ee.current;if(Re.length===0)return;const Se=Math.max(1e-6,ee.current?.getViewState?.().zoom??1),be=typeof Q=="number"&&Number.isFinite(Q)?Math.max(0,Q):Yn(U,Se,ee.current?.getZoomRange?.(),ee.current?.getRegionLabelAutoLiftCapZoom?.());for(const Ae of Re){if(!Ae.region.label)continue;const De=Un(Ae.polygons,R=>{const _=ee.current;if(!_)return[];const B=[];for(let G=0;G<R.length;G+=1){const me=He(_.worldToScreen(R[G][0],R[G][1]));if(!me)return[];B.push(me)}return B},Fe);if(!De)continue;let x=On(X,Te?.({region:Ae.region,regionId:Ae.regionKey,regionIndex:Ae.regionIndex,zoom:Se}));be>0&&(x={...x,offsetY:x.offsetY+be}),wi(fe,Ae.region.label,De,te,j,x,Z)}},K=ie.current;if(K)return S(K,50,V),()=>C(K)},[S,C]),p.useEffect(()=>{M()},[oe,Ce,N,ne,re,ge,M]);const ye=p.useRef({preparedRegionHits:ce,labelAnchor:a,resolvedLabelStyle:re,labelStyleResolver:de,regionLabelAutoLiftOffsetPx:ge,clampLabelToViewport:u,onHover:m,onClick:g,commitActive:H});return ye.current={preparedRegionHits:ce,labelAnchor:a,resolvedLabelStyle:re,labelStyleResolver:de,regionLabelAutoLiftOffsetPx:ge,clampLabelToViewport:u,onHover:m,onClick:g,commitActive:H},p.useEffect(()=>{if(!h)return;const V=A.current;if(!V)return;const K=j=>{if(T())return;const Re=b.current;if(!Re)return;const{preparedRegionHits:X,labelAnchor:Te,resolvedLabelStyle:Fe,labelStyleResolver:U,regionLabelAutoLiftOffsetPx:Z,clampLabelToViewport:Q,onHover:ee}=ye.current,Se=W(j.clientX,j.clientY);if(!Se)return;let be=null,Ae=null;if(X.length>0){const x=L(Se[0],Se[1]);if(x){const R=w.current?.getBoundingClientRect();Ae=Vr(Se,x,X,Re,Te,Fe,U,typeof Z=="number"?Z:0,R?.width??0,R?.height??0,Q),be=Ae?.regionId??null}}const De=v.current;String(De)!==String(be)&&(v.current=be,J||k(be),ee?.({region:Ae?.region??null,regionId:be,regionIndex:Ae?.regionIndex??-1,coordinate:Se}),M())},fe=j=>{if(T())return;const Re=b.current;if(!Re)return;const{preparedRegionHits:X,labelAnchor:Te,resolvedLabelStyle:Fe,labelStyleResolver:U,regionLabelAutoLiftOffsetPx:Z,clampLabelToViewport:Q,onClick:ee,commitActive:Se}=ye.current;if(X.length===0)return;const be=W(j.clientX,j.clientY);if(!be)return;const Ae=L(be[0],be[1]);if(!Ae)return;const De=w.current?.getBoundingClientRect(),x=Vr(be,Ae,X,Re,Te,Fe,U,typeof Z=="number"?Z:0,De?.width??0,De?.height??0,Q),R=x?.regionId??null;Se(R),x&&ee&&ee({region:x.region,regionId:x.regionId,regionIndex:x.regionIndex,coordinate:be})},te=()=>{v.current!==null&&(v.current=null,J||k(null),ye.current.onHover?.({region:null,regionId:null,regionIndex:-1,coordinate:null}),M())};return V.addEventListener("pointermove",K),V.addEventListener("click",fe),V.addEventListener("pointerleave",te),()=>{V.removeEventListener("pointermove",K),V.removeEventListener("click",fe),V.removeEventListener("pointerleave",te)}},[A,b,w,h,J,W,L,T,M]),null}function Nl({imageWidth:t,imageHeight:e,tiles:n,viewState:r,className:i,style:o}){const s=p.useRef(null),a=p.useRef(null),l=p.useMemo(()=>({width:"100%",height:"100%",display:"block",...o}),[o]);return p.useEffect(()=>{const u=s.current;if(!u)return;const f=new oi({canvas:u,imageWidth:t,imageHeight:e,initialViewState:r});return a.current=f,f.setTiles(n),()=>{f.destroy(),a.current=null}},[t,e]),p.useEffect(()=>{const u=a.current;u&&u.setTiles(n)},[n]),p.useEffect(()=>{const u=a.current;!u||!r||u.setViewState(r)},[r]),Ge.jsx("canvas",{ref:s,className:i,style:l})}function Bl(t,e){if(!e)return!1;try{const r=new URL(t,typeof window<"u"?window.location.href:void 0).hostname.toLowerCase();if(r.includes("amazonaws.com")||r.startsWith("s3.")||r.includes(".s3."))return!1}catch{}return!0}class Hi{constructor(e){E(this,"maxConcurrency");E(this,"maxRetries");E(this,"retryBaseDelayMs");E(this,"retryMaxDelayMs");E(this,"onTileLoad");E(this,"onTileError");E(this,"onStateChange");E(this,"authToken");E(this,"destroyed",!1);E(this,"queue",[]);E(this,"queuedByKey",new Map);E(this,"inflight",new Map);E(this,"visibleKeys",new Set);E(this,"timerId",null);E(this,"abortedCount",0);E(this,"retryCount",0);E(this,"failedCount",0);this.maxConcurrency=Math.max(1,Math.floor(e.maxConcurrency??12)),this.maxRetries=Math.max(0,Math.floor(e.maxRetries??2)),this.retryBaseDelayMs=Math.max(10,Math.floor(e.retryBaseDelayMs??120)),this.retryMaxDelayMs=Math.max(this.retryBaseDelayMs,Math.floor(e.retryMaxDelayMs??1200)),this.authToken=e.authToken??"",this.onTileLoad=e.onTileLoad,this.onTileError=e.onTileError,this.onStateChange=e.onStateChange}setAuthToken(e){this.authToken=String(e??"")}schedule(e){if(this.destroyed)return;const n=new Set;for(const r of e)n.add(r.key);this.visibleKeys=n,this.dropInvisibleQueued(n),this.abortInvisibleInflight(n);for(const r of e){if(this.inflight.has(r.key)){const s=this.inflight.get(r.key);s&&(s.tile=r);continue}const i=this.queuedByKey.get(r.key);if(i){i.tile=r;continue}const o={tile:r,attempt:0,readyAt:we()};this.queue.push(o),this.queuedByKey.set(r.key,o)}this.sortQueue(),this.pump(),this.emitStateChange()}clear(){this.clearPumpTimer(),this.visibleKeys.clear(),this.queue=[],this.queuedByKey.clear();for(const[,e]of this.inflight)e.controller.abort();this.inflight.clear(),this.emitStateChange()}destroy(){this.destroyed||(this.destroyed=!0,this.clear())}getInflightCount(){return this.inflight.size}getSnapshot(){return{inflight:this.inflight.size,queued:this.queue.length,aborted:this.abortedCount,retries:this.retryCount,failed:this.failedCount}}dropInvisibleQueued(e){if(this.queue.length===0)return;const n=[];for(const r of this.queue){if(!e.has(r.tile.key)){this.queuedByKey.delete(r.tile.key);continue}n.push(r)}this.queue=n}abortInvisibleInflight(e){for(const[n,r]of this.inflight)e.has(n)||(this.inflight.delete(n),this.abortedCount+=1,r.controller.abort())}sortQueue(){this.queue.sort((e,n)=>e.readyAt!==n.readyAt?e.readyAt-n.readyAt:e.tile.distance2!==n.tile.distance2?e.tile.distance2-n.tile.distance2:e.tile.tier!==n.tile.tier?n.tile.tier-e.tile.tier:e.tile.key.localeCompare(n.tile.key))}pump(){if(this.destroyed)return;for(this.clearPumpTimer();this.inflight.size<this.maxConcurrency;){const r=this.takeNextReadyQueueItem();if(!r)break;this.startFetch(r)}if(this.inflight.size>=this.maxConcurrency||this.queue.length===0)return;const e=this.queue[0]?.readyAt;if(typeof e!="number")return;const n=Math.max(0,e-we());this.timerId=globalThis.setTimeout(()=>{this.timerId=null,this.pump()},n)}takeNextReadyQueueItem(){if(this.queue.length===0)return null;const e=we(),n=this.queue[0];return!n||n.readyAt>e?null:(this.queue.shift(),this.queuedByKey.delete(n.tile.key),n)}startFetch(e){const n=new AbortController,r={tile:e.tile,attempt:e.attempt,controller:n};this.inflight.set(e.tile.key,r),this.emitStateChange();const i=Bl(e.tile.url,this.authToken);fetch(e.tile.url,{signal:n.signal,headers:i?{Authorization:this.authToken}:void 0}).then(o=>{if(!o.ok)throw new Error(`HTTP ${o.status}`);return o.blob()}).then(o=>createImageBitmap(o)).then(o=>{if(this.destroyed||n.signal.aborted){o.close();return}if(!this.visibleKeys.has(e.tile.key)){o.close();return}this.onTileLoad(e.tile,o)}).catch(o=>{if(n.signal.aborted||this.destroyed)return;if(e.attempt<this.maxRetries&&this.visibleKeys.has(e.tile.key)){this.retryCount+=1;const a=e.attempt+1,l=this.getRetryDelay(a),u={tile:e.tile,attempt:a,readyAt:we()+l},f=this.queuedByKey.get(e.tile.key);f?(f.tile=u.tile,f.readyAt=Math.min(f.readyAt,u.readyAt),f.attempt=Math.max(f.attempt,u.attempt)):(this.queue.push(u),this.queuedByKey.set(u.tile.key,u)),this.sortQueue();return}this.failedCount+=1,this.onTileError?.(e.tile,o,e.attempt+1)}).finally(()=>{this.inflight.delete(e.tile.key),this.pump(),this.emitStateChange()})}getRetryDelay(e){const n=Math.max(0,e-1),r=Math.min(this.retryMaxDelayMs,this.retryBaseDelayMs*2**n),i=.85+Math.random()*.3;return Math.round(r*i)}clearPumpTimer(){this.timerId!==null&&(globalThis.clearTimeout(this.timerId),this.timerId=null)}emitStateChange(){this.onStateChange?.(this.getSnapshot())}}function kl(t,e){t.addEventListener("pointerdown",e.pointerDown),t.addEventListener("pointermove",e.pointerMove),t.addEventListener("pointerup",e.pointerUp),t.addEventListener("pointercancel",e.pointerUp),t.addEventListener("wheel",e.wheel,{passive:!1}),t.addEventListener("dblclick",e.doubleClick),t.addEventListener("contextmenu",e.contextMenu),t.addEventListener("webglcontextlost",e.contextLost),t.addEventListener("webglcontextrestored",e.contextRestored)}function Ul(t,e){t.removeEventListener("pointerdown",e.pointerDown),t.removeEventListener("pointermove",e.pointerMove),t.removeEventListener("pointerup",e.pointerUp),t.removeEventListener("pointercancel",e.pointerUp),t.removeEventListener("wheel",e.wheel),t.removeEventListener("dblclick",e.doubleClick),t.removeEventListener("contextmenu",e.contextMenu),t.removeEventListener("webglcontextlost",e.contextLost),t.removeEventListener("webglcontextrestored",e.contextRestored)}function zl(t,e,n){const r=t.getBoundingClientRect(),i=Math.max(1,r.width||t.clientWidth||1),o=Math.max(1,r.height||t.clientHeight||1),s=Math.max(1,window.devicePixelRatio||1),a=Math.max(1,Math.round(i*s)),l=Math.max(1,Math.round(o*s));(t.width!==a||t.height!==l)&&(t.width=a,t.height=l),n.setViewport(i,o),e.viewport(0,0,a,l)}const Tn=.35,In=.5,Ol=256,_n=[{zoom:1,size:2.8},{zoom:2,size:3.4},{zoom:3,size:4.2},{zoom:4,size:5.3},{zoom:5,size:6.8},{zoom:6,size:8.4},{zoom:7,size:9.8},{zoom:8,size:11.2},{zoom:9,size:14},{zoom:10,size:17.5},{zoom:11,size:22},{zoom:12,size:28}],Yl=.1,Xl=5,Wl=0,Vl=1,Gl=0,ql=1,Hl=-100,Zl=100,$l=2e3;function nn(t){return t*Math.PI/180}function Ut(t,e){return!t||!e?t===e:t.buffer===e.buffer&&t.byteOffset===e.byteOffset&&t.byteLength===e.byteLength}function Jt(t){return t.map(e=>({zoom:e.zoom,size:e.size}))}function qr(t){if(!t)return Jt(_n);const e=new Map;for(const[n,r]of Object.entries(t)){const i=Number(n),o=Number(r);!Number.isFinite(i)||!Number.isFinite(o)||o<=0||e.set(i,o)}return e.size===0?Jt(_n):Array.from(e.entries()).sort((n,r)=>n[0]-r[0]).map(([n,r])=>({zoom:n,size:r}))}function Kl(t,e){if(t===e)return!0;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1)if(t[n].zoom!==e[n].zoom||t[n].size!==e[n].size)return!1;return!0}function jl(t,e){if(!Number.isFinite(t))return e[0]?.size??In;if(e.length===0)return In;if(e.length===1||t<=e[0].zoom)return e[0].size;for(let s=1;s<e.length;s+=1){const a=e[s-1],l=e[s];if(t>l.zoom)continue;const u=Math.max(1e-6,l.zoom-a.zoom),f=F((t-a.zoom)/u,0,1);return a.size+(l.size-a.size)*f}const n=e[e.length-1],r=e[e.length-2],i=Math.max(1e-6,n.zoom-r.zoom),o=(n.size-r.size)/i;return n.size+(t-n.zoom)*o}function Hr(t){return typeof t!="number"||!Number.isFinite(t)?1:F(t,Yl,Xl)}function Zr(t){return typeof t!="number"||!Number.isFinite(t)?1:F(t,Wl,Vl)}function Ql(t){return t?[F(t[0],0,100),F(t[1],0,100)]:[1,0]}function $r(t){return typeof t!="number"||!Number.isFinite(t)?0:F(t,Gl,ql)}function fn(t){return typeof t!="number"||!Number.isFinite(t)?0:F(t,Hl,Zl)}function Kr(t){const e=fn(t?.brightness),n=fn(t?.contrast),r=fn(t?.saturation);return{brightness:e/200,contrast:n/100,saturation:r/100}}function qn(t){return t}function hn(t){return typeof t!="number"||!Number.isFinite(t)?0:F(t,0,$l)}function zt(t){return typeof t!="number"||!Number.isFinite(t)||t<=0?null:Math.max(1e-6,t)}function dn(t){return typeof t=="function"?t:qn}function Zi(t,e,n){const r=t.getBoundingClientRect(),i=e-r.left-r.width*.5,o=n-r.top-r.height*.5;return Math.atan2(o,i)}function $i(t,e){if(e.pointerId!==null&&t.hasPointerCapture(e.pointerId))try{t.releasePointerCapture(e.pointerId)}catch{}e.dragging=!1,e.mode="none",e.rotateLastAngleRad=null,e.pointerId=null,t.classList.remove("dragging")}function Jl(t){const{event:e,canvas:n,state:r,config:i,cancelViewAnimation:o}=t,s=i.ctrlDragRotate&&(e.ctrlKey||e.metaKey);(e.button===0||s&&e.button===2)&&(o(),s&&e.preventDefault(),r.dragging=!0,r.mode=s?"rotate":"pan",r.pointerId=e.pointerId,r.lastPointerX=e.clientX,r.lastPointerY=e.clientY,r.rotateLastAngleRad=r.mode==="rotate"?Zi(n,e.clientX,e.clientY):null,n.classList.add("dragging"),n.setPointerCapture(e.pointerId))}function ec(t){const{event:e,canvas:n,state:r,config:i,camera:o,clampViewState:s,emitViewState:a,requestRender:l}=t;if(!r.dragging||e.pointerId!==r.pointerId)return;const u=e.clientX-r.lastPointerX,f=e.clientY-r.lastPointerY;if(r.lastPointerX=e.clientX,r.lastPointerY=e.clientY,r.mode==="rotate"){const c=Zi(n,e.clientX,e.clientY),h=r.rotateLastAngleRad;if(r.rotateLastAngleRad=c,h!==null){const d=c-h,m=Math.atan2(Math.sin(d),Math.cos(d)),g=i.rotationDragSensitivityDegPerPixel/Tn,b=o.getViewState();o.setViewState({rotationDeg:b.rotationDeg-m*180/Math.PI*g})}}else{const c=o.getViewState(),h=Math.max(1e-6,c.zoom),d=nn(c.rotationDeg),m=Math.cos(d),g=Math.sin(d),b=(u*m-f*g)/h,y=(u*g+f*m)/h;o.setViewState({offsetX:c.offsetX-b,offsetY:c.offsetY-y})}s(),a(),l()}function tc(t,e,n){t.pointerId===n.pointerId&&$i(e,n)}function nc(t){const{event:e,canvas:n,onZoomBy:r}=t;e.preventDefault();const i=n.getBoundingClientRect(),o=e.clientX-i.left,s=e.clientY-i.top,a=e.deltaY<0?1.12:.89;r(a,o,s)}const rc=4;function ic(t){const{event:e,canvas:n,snapState:r,onSnapZoom:i}=t;e.preventDefault();const o=e.deltaY<0?"in":e.deltaY>0?"out":null;if(o&&r.blockedDirection)if(o!==r.blockedDirection)r.blockedDirection=null,r.accumulatedDelta=0;else return;if(r.accumulatedDelta!==0&&e.deltaY!==0&&Math.sign(r.accumulatedDelta)!==Math.sign(e.deltaY)&&(r.accumulatedDelta=0),r.accumulatedDelta+=e.deltaY,Math.abs(r.accumulatedDelta)<rc)return;const s=n.getBoundingClientRect(),a=e.clientX-s.left,l=e.clientY-s.top,u=r.accumulatedDelta>0?"out":"in";if(r.accumulatedDelta=0,!i(u,a,l)){r.blockedDirection=u;return}r.blockedDirection=null}function oc(t){const{event:e,canvas:n,onZoomBy:r}=t,i=n.getBoundingClientRect(),o=e.clientX-i.left,s=e.clientY-i.top;r(e.shiftKey?.8:1.25,o,s)}function sc(t,e){(e||t.ctrlKey||t.metaKey)&&t.preventDefault()}function en(t){const e=t.getViewCorners();let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[s,a]of e)s<n&&(n=s),s>i&&(i=s),a<r&&(r=a),a>o&&(o=a);return[n,r,i,o]}function Vt(t,e,n=.2,r=.2){const i=en(t),o=Math.max(1e-6,i[2]-i[0]),s=Math.max(1e-6,i[3]-i[1]),a=o*n,l=s*r,[u,f]=t.getCenter(),c=o*.5,h=s*.5,d=c-a,m=e.width-c+a,g=h-l,b=e.height-h+l,y=d<=m?F(u,d,m):e.width*.5,w=g<=b?F(f,g,b):e.height*.5;t.setCenter(y,w)}function ac(t,e){const n=Math.max(1e-6,t.getViewState().zoom),r=e.maxTierZoom+Math.log2(n);return F(Math.floor(r),0,e.maxTierZoom)}function lc(t,e){return!(t[2]<=e[0]||t[0]>=e[2]||t[3]<=e[1]||t[1]>=e[3])}function Ki(t,e,n){const r=en(t),i=Math.pow(2,e.maxTierZoom-n),o=Math.ceil(e.width/i),s=Math.ceil(e.height/i),a=Math.max(1,Math.ceil(o/e.tileSize)),l=Math.max(1,Math.ceil(s/e.tileSize)),u=r[0],f=r[1],c=r[2],h=r[3],d=F(Math.floor(u/i/e.tileSize),0,a-1),m=F(Math.floor((c-1)/i/e.tileSize),0,a-1),g=F(Math.floor(f/i/e.tileSize),0,l-1),b=F(Math.floor((h-1)/i/e.tileSize),0,l-1);if(d>m||g>b)return[];const y=(u+c)*.5/i/e.tileSize,w=(f+h)*.5/i/e.tileSize,A=[];for(let S=g;S<=b;S+=1)for(let C=d;C<=m;C+=1){const M=C*e.tileSize*i,P=S*e.tileSize*i,O=Math.min((C+1)*e.tileSize,o)*i,W=Math.min((S+1)*e.tileSize,s)*i,L=C-y,T=S-w;A.push({key:`${n}/${C}/${S}`,tier:n,x:C,y:S,bounds:[M,P,O,W],distance2:L*L+T*T,url:Gn(e,n,C,S)})}return A.sort((S,C)=>S.distance2-C.distance2),A}function cc(t,e){const n=ac(t,e);return{tier:n,visible:Ki(t,e,n)}}function uc(t){t.interactionLocked||Jl({event:t.event,canvas:t.canvas,state:t.state,config:{ctrlDragRotate:t.ctrlDragRotate,rotationDragSensitivityDegPerPixel:t.rotationDragSensitivityDegPerPixel},cancelViewAnimation:t.cancelViewAnimation})}function fc(t){t.interactionLocked||ec({event:t.event,canvas:t.canvas,state:t.state,config:{ctrlDragRotate:t.ctrlDragRotate,rotationDragSensitivityDegPerPixel:t.rotationDragSensitivityDegPerPixel},camera:t.camera,clampViewState:()=>Vt(t.camera,t.source,t.panExtentX,t.panExtentY),emitViewState:t.emitViewState,requestRender:t.requestRender})}function hc(t){t.interactionLocked||tc(t.event,t.canvas,t.state)}function dc(t){t.interactionLocked||oc({event:t.event,canvas:t.canvas,onZoomBy:t.onZoomBy})}function mc(t){sc(t.event,t.state.dragging)}function gc(t,e){$i(t,e)}function pc(t){return{pointerDown:e=>uc({event:e,interactionLocked:t.getInteractionLocked(),canvas:t.canvas,state:t.state,ctrlDragRotate:t.getCtrlDragRotate(),rotationDragSensitivityDegPerPixel:t.getRotationDragSensitivityDegPerPixel(),cancelViewAnimation:t.cancelViewAnimation}),pointerMove:e=>fc({event:e,interactionLocked:t.getInteractionLocked(),canvas:t.canvas,state:t.state,ctrlDragRotate:t.getCtrlDragRotate(),rotationDragSensitivityDegPerPixel:t.getRotationDragSensitivityDegPerPixel(),camera:t.camera,source:t.source,panExtentX:t.getPanExtentX(),panExtentY:t.getPanExtentY(),emitViewState:t.emitViewState,requestRender:t.requestRender}),pointerUp:e=>hc({event:e,interactionLocked:t.getInteractionLocked(),canvas:t.canvas,state:t.state}),wheel:e=>{if(t.getInteractionLocked()){e.preventDefault();return}if(t.getUseZoomSnaps?.()&&t.onSnapZoom&&t.zoomSnapState){ic({event:e,canvas:t.canvas,snapState:t.zoomSnapState,onSnapZoom:t.onSnapZoom});return}nc({event:e,canvas:t.canvas,onZoomBy:t.zoomBy})},doubleClick:e=>dc({event:e,interactionLocked:t.getInteractionLocked(),canvas:t.canvas,onZoomBy:t.zoomBy}),contextMenu:e=>mc({event:e,canvas:t.canvas,state:t.state})}}function yc(t){const{gl:e,cache:n,maxCacheTiles:r}=t;if(n.size<=r)return;const i=Math.max(0,Math.floor(r));for(;n.size>i;){let o=null,s=null;for(const[a,l]of n)(!s||l.lastUsed<s.lastUsed)&&(o=a,s=l);if(!o||!s)break;e.deleteTexture(s.texture),n.delete(o)}}function bc(t,e){if(t.isContextLost())return null;const n=t.createTexture();return n?(t.bindTexture(t.TEXTURE_2D,n),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,1),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),t.bindTexture(t.TEXTURE_2D,null),n):null}function xc(t){const{gl:e,cache:n,tile:r,bitmap:i,frameSerial:o,maxCacheTiles:s,destroyed:a,contextLost:l,requestRender:u}=t;if(a||l||e.isContextLost()){i.close();return}if(n.has(r.key)){i.close();return}const f=bc(e,i);i.close(),f&&(n.set(r.key,{key:r.key,texture:f,bounds:r.bounds,tier:r.tier,lastUsed:o}),yc({gl:e,cache:n,maxCacheTiles:s}),u())}function wc(t,e){for(const[,n]of e)t.deleteTexture(n.texture)}function Sc(t){const{event:e,destroyed:n,contextLost:r,cancelViewAnimation:i,cancelDrag:o,tileScheduler:s,cache:a,onContextLost:l}=t;if(e.preventDefault(),n||r)return{handled:!1,frame:t.frame};let u=t.frame;return u!==null&&(cancelAnimationFrame(u),u=null),i(),o(),s.clear(),a.clear(),l?.(),{handled:!0,frame:u}}function Ec(t){if(t.destroyed)return{didDestroy:!1,frame:t.frame};let e=t.frame;if(e!==null&&(cancelAnimationFrame(e),e=null),t.cancelViewAnimation(),t.resizeObserver.disconnect(),t.removeDprListener(),t.removeCanvasEventListeners(),t.cancelDrag(),t.tileScheduler.destroy(),!t.contextLost&&!t.gl.isContextLost()){wc(t.gl,t.cache),t.gl.deleteBuffer(t.tileProgram.vbo),t.gl.deleteVertexArray(t.tileProgram.vao),t.gl.deleteProgram(t.tileProgram.program);for(let n=0;n<t.pointPrograms.length;n+=1){const r=t.pointPrograms[n];t.gl.deleteBuffer(r.posBuffer),t.gl.deleteBuffer(r.classBuffer),t.gl.deleteBuffer(r.fillModeBuffer),t.gl.deleteBuffer(r.indexBuffer),t.gl.deleteTexture(r.paletteTexture),t.gl.deleteVertexArray(r.vao),t.gl.deleteProgram(r.program)}}return t.cache.clear(),{didDestroy:!0,frame:e}}function Rc(t,e){if(e<=0||t.length===0)return new Uint32Array(0);let n=t.length;for(let o=0;o<t.length;o+=1)t[o]<e||(n-=1);if(n===t.length)return t;if(n<=0)return new Uint32Array(0);const r=new Uint32Array(n);let i=0;for(let o=0;o<t.length;o+=1){const s=t[o];s>=e||(r[i]=s,i+=1)}return r}function Ac(t,e){return e<=0?new Uint8Array(0):t.length<e?new Uint8Array(e):t.subarray(0,e)}function jr(t,e,n,r,i){if(!i||i.length===0)return{...t,lastPointPalette:null};const o=new Uint8Array(i);if(r||e.isContextLost())return{...t,lastPointPalette:o};const s=Math.max(1,Math.floor(o.length/4));return e.bindTexture(e.TEXTURE_2D,n.paletteTexture),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,s,1,0,e.RGBA,e.UNSIGNED_BYTE,o),e.bindTexture(e.TEXTURE_2D,null),{...t,lastPointPalette:o,pointPaletteSize:s}}function Qr(t,e,n,r,i){if(!i||!i.count||!i.positions||!i.paletteIndices)return{...t,lastPointData:null,pointCount:0,usePointIndices:!1};const o=i.fillModes instanceof Uint8Array?i.fillModes:null,s=o!==null,a=Math.max(0,Math.min(i.count,Math.floor(i.positions.length/2),i.paletteIndices.length,s?o.length:Number.MAX_SAFE_INTEGER)),l=i.positions.subarray(0,a*2),u=i.paletteIndices.subarray(0,a),f=s?o.subarray(0,a):void 0,c=i.drawIndices instanceof Uint32Array,h=c?Rc(i.drawIndices,a):null,d=t.lastPointData,m=d?.fillModes instanceof Uint8Array,g=t.pointBuffersDirty||!d||d.count!==a||!Ut(d.positions,l)||!Ut(d.paletteIndices,u)||m!==s||s&&(!d?.fillModes||!Ut(d.fillModes,f)),b=t.pointBuffersDirty||c&&(!d?.drawIndices||!Ut(d.drawIndices,h))||!c&&!!d?.drawIndices,y={...t,lastPointData:{count:a,positions:l,paletteIndices:u,fillModes:f,drawIndices:c?h??void 0:void 0}};if(r||e.isContextLost())return y;const w=y.lastPointData;if(!w)return y;if(g){e.bindBuffer(e.ARRAY_BUFFER,n.posBuffer),e.bufferData(e.ARRAY_BUFFER,w.positions,e.STATIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,n.classBuffer),e.bufferData(e.ARRAY_BUFFER,w.paletteIndices,e.STATIC_DRAW);const A=Ac(y.zeroFillModes,a);e.bindBuffer(e.ARRAY_BUFFER,n.fillModeBuffer),e.bufferData(e.ARRAY_BUFFER,w.fillModes??A,e.STATIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,null),y.zeroFillModes=A}return c&&b&&(e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n.indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,h??new Uint32Array(0),e.DYNAMIC_DRAW),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),y.usePointIndices=c,y.pointCount=c?h?.length??0:w.count,(g||b)&&(y.pointBuffersDirty=!1),y}function Cc(t){const{gl:e,camera:n,source:r,cache:i,frameSerial:o,tileProgram:s,imageColorSettings:a,pointLayers:l,tileScheduler:u,getVisibleTiles:f,getVisibleTilesForTier:c,getViewBounds:h,intersectsBounds:d}=t;e.clearColor(.03,.06,.1,1),e.clear(e.COLOR_BUFFER_BIT);const{tier:m,visible:g}=f(),b=h(),y=new Set(g.map(L=>L.key));e.useProgram(s.program),e.bindVertexArray(s.vao),e.uniformMatrix3fv(s.uCamera,!1,n.getMatrix()),e.uniform1i(s.uTexture,0),e.uniform1f(s.uBrightness,a.brightness),e.uniform1f(s.uContrast,a.contrast),e.uniform1f(s.uSaturation,a.saturation);const w=[];for(const[,L]of i)y.has(L.key)||d(L.bounds,b)&&w.push(L);w.sort((L,T)=>L.tier-T.tier);for(const L of w)L.lastUsed=o,e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,L.texture),e.uniform4f(s.uBounds,L.bounds[0],L.bounds[1],L.bounds[2],L.bounds[3]),e.drawArrays(e.TRIANGLE_STRIP,0,4);let A=0;const S=[];for(const L of g){const T=i.get(L.key);if(!T){S.push(L);continue}T.lastUsed=o,e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,T.texture),e.uniform4f(s.uBounds,T.bounds[0],T.bounds[1],T.bounds[2],T.bounds[3]),e.drawArrays(e.TRIANGLE_STRIP,0,4),A+=1}const C=S.slice(),M=1e6,P=[];m>0&&P.push(m-1),m<r.maxTierZoom&&P.push(m+1);for(const L of P){const T=c(L);for(const D of T)i.has(D.key)||(D.distance2+=M,C.push(D))}u.schedule(C),e.bindTexture(e.TEXTURE_2D,null),e.bindVertexArray(null);let O=0,W=0;if(l.length>0){e.enable(e.BLEND),e.blendFunc(e.ONE,e.ONE_MINUS_SRC_ALPHA);for(let L=0;L<l.length;L+=1){const T=l[L];T.pointCount<=0||(e.useProgram(T.pointProgram.program),e.bindVertexArray(T.pointProgram.vao),e.uniformMatrix3fv(T.pointProgram.uCamera,!1,n.getMatrix()),e.uniform1f(T.pointProgram.uPointSize,T.pointSizePx),e.uniform1f(T.pointProgram.uPointCssSize,T.pointCssSizePx),e.uniform2f(T.pointProgram.uPointLineDash,T.pointLineDash[0],T.pointLineDash[1]),e.uniform1f(T.pointProgram.uPointOpacity,T.pointOpacity),e.uniform1f(T.pointProgram.uPointStrokeScale,T.pointStrokeScale),e.uniform1f(T.pointProgram.uPointInnerFillAlpha,T.pointInnerFillOpacity),e.uniform1f(T.pointProgram.uPaletteSize,T.pointPaletteSize),e.uniform1i(T.pointProgram.uPalette,1),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,T.pointProgram.paletteTexture),T.usePointIndices?e.drawElements(e.POINTS,T.pointCount,e.UNSIGNED_INT,0):e.drawArrays(e.POINTS,0,T.pointCount),O+=T.pointCount,W+=1)}e.bindTexture(e.TEXTURE_2D,null),e.bindVertexArray(null)}return{tier:m,visible:g.length,rendered:A,points:O,fallback:w.length,cacheHits:A,cacheMisses:S.length,drawCalls:w.length+A+W}}function Jr(t){const r=bt(t,`#version 300 es
135
135
  precision highp float;
136
136
  in vec2 aUnit;
137
137
  in vec2 aUv;
@@ -176,7 +176,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
176
176
 
177
177
  color.rgb = clamp(color.rgb + uBrightness, vec3(0.0), vec3(1.0));
178
178
  outColor = color;
179
- }`),i=Fe(t,r,"uCamera"),o=Fe(t,r,"uBounds"),s=Fe(t,r,"uTexture"),a=Fe(t,r,"uBrightness"),l=Fe(t,r,"uContrast"),u=Fe(t,r,"uSaturation"),f=t.createVertexArray(),c=t.createBuffer();if(!f||!c)throw new Error("buffer allocation failed");t.bindVertexArray(f),t.bindBuffer(t.ARRAY_BUFFER,c),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,0,1,0,1,0,0,1,0,1,1,1,1,1]),t.STATIC_DRAW);const h=t.getAttribLocation(r,"aUnit"),d=t.getAttribLocation(r,"aUv");if(h<0||d<0)throw new Error("tile attribute lookup failed");return t.enableVertexAttribArray(h),t.enableVertexAttribArray(d),t.vertexAttribPointer(h,2,t.FLOAT,!1,16,0),t.vertexAttribPointer(d,2,t.FLOAT,!1,16,8),t.bindVertexArray(null),t.bindBuffer(t.ARRAY_BUFFER,null),{program:r,vao:f,vbo:c,uCamera:i,uBounds:o,uTexture:s,uBrightness:a,uContrast:l,uSaturation:u}}function Kr(t){const r=bt(t,`#version 300 es
179
+ }`),i=Le(t,r,"uCamera"),o=Le(t,r,"uBounds"),s=Le(t,r,"uTexture"),a=Le(t,r,"uBrightness"),l=Le(t,r,"uContrast"),u=Le(t,r,"uSaturation"),f=t.createVertexArray(),c=t.createBuffer();if(!f||!c)throw new Error("buffer allocation failed");t.bindVertexArray(f),t.bindBuffer(t.ARRAY_BUFFER,c),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,0,1,0,1,0,0,1,0,1,1,1,1,1]),t.STATIC_DRAW);const h=t.getAttribLocation(r,"aUnit"),d=t.getAttribLocation(r,"aUv");if(h<0||d<0)throw new Error("tile attribute lookup failed");return t.enableVertexAttribArray(h),t.enableVertexAttribArray(d),t.vertexAttribPointer(h,2,t.FLOAT,!1,16,0),t.vertexAttribPointer(d,2,t.FLOAT,!1,16,8),t.bindVertexArray(null),t.bindBuffer(t.ARRAY_BUFFER,null),{program:r,vao:f,vbo:c,uCamera:i,uBounds:o,uTexture:s,uBrightness:a,uContrast:l,uSaturation:u}}function ei(t){const r=bt(t,`#version 300 es
180
180
  precision highp float;
181
181
  in vec2 aPosition;
182
182
  in uint aClass;
@@ -242,6 +242,6 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
242
242
  // Premultiplied alpha output: inner fill is black, so it only contributes alpha.
243
243
  outColor = vec4(color.rgb * ringAlpha * pointOpacity, alpha);
244
244
  }
245
- }`),i=Fe(t,r,"uCamera"),o=Fe(t,r,"uPointSize"),s=Fe(t,r,"uPointCssSize"),a=Fe(t,r,"uPointOpacity"),l=Fe(t,r,"uPointStrokeScale"),u=Fe(t,r,"uPointInnerFillAlpha"),f=Fe(t,r,"uPalette"),c=Fe(t,r,"uPaletteSize"),h=Fe(t,r,"uPointLineDash"),d=t.createVertexArray(),m=t.createBuffer(),g=t.createBuffer(),y=t.createBuffer(),b=t.createBuffer(),x=t.createTexture();if(!d||!m||!g||!y||!b||!x)throw new Error("point buffer allocation failed");t.bindVertexArray(d),t.bindBuffer(t.ARRAY_BUFFER,m),t.bufferData(t.ARRAY_BUFFER,0,t.DYNAMIC_DRAW);const A=t.getAttribLocation(r,"aPosition");if(A<0)throw new Error("point position attribute not found");t.enableVertexAttribArray(A),t.vertexAttribPointer(A,2,t.FLOAT,!1,0,0),t.bindBuffer(t.ARRAY_BUFFER,g),t.bufferData(t.ARRAY_BUFFER,0,t.DYNAMIC_DRAW);const S=t.getAttribLocation(r,"aClass");if(S<0)throw new Error("point class attribute not found");t.enableVertexAttribArray(S),t.vertexAttribIPointer(S,1,t.UNSIGNED_SHORT,0,0),t.bindBuffer(t.ARRAY_BUFFER,y),t.bufferData(t.ARRAY_BUFFER,0,t.DYNAMIC_DRAW);const C=t.getAttribLocation(r,"aFillMode");if(C<0)throw new Error("point fill mode attribute not found");return t.enableVertexAttribArray(C),t.vertexAttribIPointer(C,1,t.UNSIGNED_BYTE,0,0),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,b),t.bufferData(t.ELEMENT_ARRAY_BUFFER,0,t.DYNAMIC_DRAW),t.bindVertexArray(null),t.bindBuffer(t.ARRAY_BUFFER,null),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null),t.bindTexture(t.TEXTURE_2D,x),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,new Uint8Array([160,160,160,255])),t.bindTexture(t.TEXTURE_2D,null),{program:r,vao:d,posBuffer:m,classBuffer:g,fillModeBuffer:y,indexBuffer:b,paletteTexture:x,uCamera:i,uPointSize:o,uPointCssSize:s,uPointOpacity:a,uPointLineDash:h,uPointStrokeScale:l,uPointInnerFillAlpha:u,uPalette:f,uPaletteSize:c}}function Hi(t){t.animation=null,t.frame!==null&&(cancelAnimationFrame(t.frame),t.frame=null)}function xc(t){const{state:e,camera:n,target:r,durationMs:i,easing:o,onUpdate:s}=t,a=n.getViewState();Hi(e),e.animation={startMs:xe(),durationMs:Math.max(0,i),from:a,to:r,easing:o};const l=()=>{const u=e.animation;if(!u)return;const f=Math.max(0,xe()-u.startMs),c=u.durationMs<=0?1:L(f/u.durationMs,0,1);let h=c;try{h=u.easing(c)}catch{h=c}if(Number.isFinite(h)||(h=c),h=L(h,0,1),n.setViewState({zoom:u.from.zoom+(u.to.zoom-u.from.zoom)*h,offsetX:u.from.offsetX+(u.to.offsetX-u.from.offsetX)*h,offsetY:u.from.offsetY+(u.to.offsetY-u.from.offsetY)*h,rotationDeg:u.from.rotationDeg+(u.to.rotationDeg-u.from.rotationDeg)*h}),s(),c>=1){e.animation=null,e.frame=null;return}e.frame=requestAnimationFrame(l)};e.frame=requestAnimationFrame(l)}function wc(t){const e=Math.max(t*.5,1e-6),n=Math.max(1,t*8);return{minZoom:e,maxZoom:Math.max(e,n)}}function Sc(t,e,n){const r=wc(t);let i=e??r.minZoom,o=n??r.maxZoom;return i=Math.max(1e-6,i),o=Math.max(1e-6,o),i>o&&(i=o),{minZoom:i,maxZoom:o}}function Ec(t,e,n,r,i){const o=t.getViewState(),s={zoom:typeof r.zoom=="number"&&Number.isFinite(r.zoom)?L(r.zoom,e,n):o.zoom,offsetX:typeof r.offsetX=="number"&&Number.isFinite(r.offsetX)?r.offsetX:o.offsetX,offsetY:typeof r.offsetY=="number"&&Number.isFinite(r.offsetY)?r.offsetY:o.offsetY,rotationDeg:typeof r.rotationDeg=="number"&&Number.isFinite(r.rotationDeg)?r.rotationDeg:o.rotationDeg};t.setViewState(s),i();const a=t.getViewState();return t.setViewState(o),a}function jr(t,e,n,r,i,o=0){const s=Math.min(e/t.width,n/t.height),a=Number.isFinite(s)&&s>0?s:1,l=L(a,r,i),u=e/l,f=n/l;return{fitZoom:a,target:{zoom:l,offsetX:(t.width-u)*.5,offsetY:(t.height-f)*.5,rotationDeg:o}}}function Rc(t,e,n,r,i,o){const s=t.getViewState(),a=L(s.zoom*r,e,n);if(a===s.zoom)return null;const[l,u]=t.screenToWorld(i,o),f=t.getViewportSize(),c=i-f.width*.5,h=o-f.height*.5,d=nn(s.rotationDeg),m=Math.cos(d),g=Math.sin(d),y=c/a*m-h/a*g,b=c/a*g+h/a*m,x=l-y,A=u-b;return{zoom:a,offsetX:x-f.width/(2*a),offsetY:A-f.height/(2*a)}}function Ac(t,e,n,r,i,o){const s=t.getViewState(),a=L(r,e,n);if(a===s.zoom)return null;const[l,u]=t.screenToWorld(i,o),f=t.getViewportSize(),c=i-f.width*.5,h=o-f.height*.5,d=nn(s.rotationDeg),m=Math.cos(d),g=Math.sin(d),y=c/a*m-h/a*g,b=c/a*g+h/a*m,x=l-y,A=u-b;return{zoom:a,offsetX:x-f.width/(2*a),offsetY:A-f.height/(2*a)}}const Cc=250;function Qr(t,e){if(!t||t.length===0)return[];if(!e||e<=0)return[];const n=10/e;return t.map(r=>r/n).filter(r=>Number.isFinite(r)&&r>0).sort((r,i)=>r-i)}function Mc(t,e,n,r){if(t.length===0)return null;const i=Math.max(e*.005,1e-8);if(n==="in"){for(const o of t)if(o>e+i)return{type:"snap",zoom:o};return null}for(let o=t.length-1;o>=0;o--)if(t[o]<e-i)return{type:"snap",zoom:t[o]};return r&&e<=t[0]+i?{type:"fit"}:null}function Pc(t,e,n,r,i){const o=t.camera.getViewState(),[s,a]=t.camera.screenToWorld(n,r),l=t.camera.getViewportSize(),u=L(e,t.minZoom,t.maxZoom);if(u===o.zoom)return;const f=nn(o.rotationDeg),c=Math.cos(f),h=Math.sin(f),d=n-l.width*.5,m=r-l.height*.5;t.cancelViewAnimation();const g=x=>{const A=d/x*c-m/x*h,S=d/x*h+m/x*c;return{offsetX:s-A-l.width/(2*x),offsetY:a-S-l.height/(2*x)}},y=g(u);t.viewAnimationState.animation={startMs:xe(),durationMs:Math.max(0,i),from:o,to:{zoom:u,offsetX:y.offsetX,offsetY:y.offsetY,rotationDeg:o.rotationDeg},easing:Gn};const b=()=>{const x=t.viewAnimationState.animation;if(!x)return;const A=Math.max(0,xe()-x.startMs),S=L(A/i,0,1),C=L(S*S*(3-2*S),0,1),M=o.zoom+(u-o.zoom)*C,{offsetX:P,offsetY:U}=g(M);t.camera.setViewState({zoom:M,offsetX:P,offsetY:U,rotationDeg:o.rotationDeg});const O=S>=1;O&&(t.clampViewState(),t.viewAnimationState.animation=null,t.viewAnimationState.frame=null),t.onViewStateChange(t.camera.getViewState()),t.requestRender(),O||(t.viewAnimationState.frame=requestAnimationFrame(b))};t.viewAnimationState.frame=requestAnimationFrame(b)}const We="__default_point_layer__";class Zi{constructor(e,n,r={}){E(this,"canvas");E(this,"source");E(this,"gl");E(this,"camera",new ei);E(this,"onViewStateChange");E(this,"onStats");E(this,"onTileError");E(this,"onContextLost");E(this,"onContextRestored");E(this,"resizeObserver");E(this,"removeDprListener");E(this,"tileProgram");E(this,"tileScheduler");E(this,"authToken");E(this,"destroyed",!1);E(this,"contextLost",!1);E(this,"frame",null);E(this,"frameSerial",0);E(this,"interactionState",{dragging:!1,mode:"none",rotateLastAngleRad:null,pointerId:null,lastPointerX:0,lastPointerY:0});E(this,"interactionLocked",!1);E(this,"ctrlDragRotate",!0);E(this,"rotationDragSensitivityDegPerPixel",vn);E(this,"maxCacheTiles");E(this,"fitZoom",1);E(this,"initialRotationDeg",0);E(this,"minZoom",1e-6);E(this,"maxZoom",1);E(this,"minZoomOverride",null);E(this,"maxZoomOverride",null);E(this,"viewTransitionDurationMs",0);E(this,"viewTransitionEasing",Gn);E(this,"viewAnimationState",{animation:null,frame:null});E(this,"pointLayers",new Map);E(this,"defaultPointSizeStops",Jt(In));E(this,"defaultPointOpacity",1);E(this,"defaultPointLineDash",[1,0]);E(this,"defaultPointStrokeScale",1);E(this,"defaultPointInnerFillOpacity",0);E(this,"imageColorSettings",{brightness:0,contrast:0,saturation:0});E(this,"cache",new Map);E(this,"zoomSnaps",[]);E(this,"zoomSnapFitAsMin",!1);E(this,"zoomSnapState",{accumulatedDelta:0,lastSnapTimeMs:0,blockedDirection:null});E(this,"panExtentX",.2);E(this,"panExtentY",.2);E(this,"boundPointerDown");E(this,"boundPointerMove");E(this,"boundPointerUp");E(this,"boundWheel");E(this,"boundDoubleClick");E(this,"boundContextMenu");E(this,"boundContextLost");E(this,"boundContextRestored");this.canvas=e,this.source=n,this.onViewStateChange=r.onViewStateChange,this.onStats=r.onStats,this.onTileError=r.onTileError,this.onContextLost=r.onContextLost,this.onContextRestored=r.onContextRestored,this.authToken=r.authToken??"",this.maxCacheTiles=Math.max(32,Math.floor(r.maxCacheTiles??320)),this.initialRotationDeg=typeof r.initialRotationDeg=="number"&&Number.isFinite(r.initialRotationDeg)?r.initialRotationDeg:0,this.ctrlDragRotate=r.ctrlDragRotate??!0,this.rotationDragSensitivityDegPerPixel=typeof r.rotationDragSensitivityDegPerPixel=="number"&&Number.isFinite(r.rotationDragSensitivityDegPerPixel)?Math.max(0,r.rotationDragSensitivityDegPerPixel):vn,this.defaultPointSizeStops=Wr(r.pointSizeByZoom),this.defaultPointOpacity=Vr(r.pointOpacity),this.defaultPointStrokeScale=Xr(r.pointStrokeScale),this.defaultPointInnerFillOpacity=Gr(r.pointInnerFillOpacity),this.imageColorSettings=qr(r.imageColorSettings),this.minZoomOverride=zt(r.minZoom),this.maxZoomOverride=zt(r.maxZoom),this.viewTransitionDurationMs=hn(r.viewTransition?.duration),this.viewTransitionEasing=dn(r.viewTransition?.easing),this.zoomSnaps=Qr(r.zoomSnaps,this.source.mpp),this.zoomSnapFitAsMin=!!r.zoomSnapFitAsMin,this.applyPanExtent(r.panExtent);const i=e.getContext("webgl2",{alpha:!1,antialias:!1,depth:!1,stencil:!1,powerPreference:"high-performance"});if(!i)throw new Error("WebGL2 not supported");this.gl=i,this.tileProgram=$r(this.gl),this.tileScheduler=new Xi({authToken:this.authToken,maxConcurrency:r.tileScheduler?.maxConcurrency??12,maxRetries:r.tileScheduler?.maxRetries??2,retryBaseDelayMs:r.tileScheduler?.retryBaseDelayMs??120,retryMaxDelayMs:r.tileScheduler?.retryMaxDelayMs??1200,onTileLoad:(s,a)=>hc({gl:this.gl,cache:this.cache,tile:s,bitmap:a,frameSerial:this.frameSerial,maxCacheTiles:this.maxCacheTiles,destroyed:this.destroyed,contextLost:this.contextLost,requestRender:()=>this.requestRender()}),onTileError:(s,a,l)=>{this.onTileError?.({tile:s,error:a,attemptCount:l}),console.warn("tile load failed",s.url,a)}}),this.resizeObserver=new ResizeObserver(()=>this.resize()),this.resizeObserver.observe(e),this.removeDprListener=tn(()=>this.resize());const o=cc({canvas:this.canvas,state:this.interactionState,getInteractionLocked:()=>this.interactionLocked,getCtrlDragRotate:()=>this.ctrlDragRotate,getRotationDragSensitivityDegPerPixel:()=>this.rotationDragSensitivityDegPerPixel,cancelViewAnimation:()=>this.cancelViewAnimation(),camera:this.camera,source:this.source,emitViewState:()=>this.onViewStateChange?.(this.camera.getViewState()),requestRender:()=>this.requestRender(),getPanExtentX:()=>this.panExtentX,getPanExtentY:()=>this.panExtentY,zoomBy:(s,a,l)=>this.zoomBy(s,a,l),getUseZoomSnaps:()=>this.zoomSnaps.length>0,onSnapZoom:(s,a,l)=>this.handleSnapZoom(s,a,l),zoomSnapState:this.zoomSnapState});this.boundPointerDown=o.pointerDown,this.boundPointerMove=o.pointerMove,this.boundPointerUp=o.pointerUp,this.boundWheel=o.wheel,this.boundDoubleClick=o.doubleClick,this.boundContextMenu=o.contextMenu,this.boundContextLost=s=>this.onWebGlContextLost(s),this.boundContextRestored=s=>this.onWebGlContextRestored(s),Il(e,this.getCanvasHandlers()),this.fitToImage({duration:0}),this.resize()}getCanvasHandlers(){return{pointerDown:this.boundPointerDown,pointerMove:this.boundPointerMove,pointerUp:this.boundPointerUp,wheel:this.boundWheel,doubleClick:this.boundDoubleClick,contextMenu:this.boundContextMenu,contextLost:this.boundContextLost,contextRestored:this.boundContextRestored}}applyZoomBounds(){const e=Sc(this.fitZoom,this.minZoomOverride,this.maxZoomOverride);this.minZoom=e.minZoom,this.maxZoom=e.maxZoom}resolveTargetViewState(e){return Ec(this.camera,this.minZoom,this.maxZoom,e,()=>Vt(this.camera,this.source,this.panExtentX,this.panExtentY))}cancelViewAnimation(){Hi(this.viewAnimationState)}startViewAnimation(e,n,r){xc({state:this.viewAnimationState,camera:this.camera,target:e,durationMs:n,easing:r,onUpdate:()=>{Vt(this.camera,this.source,this.panExtentX,this.panExtentY),this.onViewStateChange?.(this.camera.getViewState()),this.requestRender()}})}createPointBufferRuntime(){return{pointCount:0,usePointIndices:!1,pointBuffersDirty:!0,lastPointData:null,zeroFillModes:new Uint8Array(0),lastPointPalette:null,pointPaletteSize:1}}createPointLayerState(e){return{id:e,program:Kr(this.gl),runtime:this.createPointBufferRuntime(),pointSizeStops:Jt(this.defaultPointSizeStops),pointOpacity:this.defaultPointOpacity,pointLineDash:[...this.defaultPointLineDash],pointStrokeScale:this.defaultPointStrokeScale,pointInnerFillOpacity:this.defaultPointInnerFillOpacity}}ensurePointLayer(e=We){const n=String(e||We),r=this.pointLayers.get(n);if(r)return r;const i=this.createPointLayerState(n);return this.pointLayers.set(n,i),i}deletePointProgram(e){this.contextLost||this.gl.isContextLost()||(this.gl.deleteBuffer(e.posBuffer),this.gl.deleteBuffer(e.classBuffer),this.gl.deleteBuffer(e.fillModeBuffer),this.gl.deleteBuffer(e.indexBuffer),this.gl.deleteTexture(e.paletteTexture),this.gl.deleteVertexArray(e.vao),this.gl.deleteProgram(e.program))}getPointRenderLayers(){const e=Math.max(1,window.devicePixelRatio||1),n=[];for(const r of this.pointLayers.values()){const i=this.getPointSizeByZoom(r.id);n.push({pointProgram:r.program,pointCount:r.runtime.pointCount,usePointIndices:r.runtime.usePointIndices,pointPaletteSize:r.runtime.pointPaletteSize,pointLineDash:r.pointLineDash,pointOpacity:r.pointOpacity,pointStrokeScale:r.pointStrokeScale,pointInnerFillOpacity:r.pointInnerFillOpacity,pointCssSizePx:i,pointSizePx:i*e})}return n}applyViewStateAndRender(e,n=!0){n&&this.cancelViewAnimation(),this.camera.setViewState(e),this.onViewStateChange?.(this.camera.getViewState()),this.requestRender()}setAuthToken(e){this.authToken=String(e??""),this.tileScheduler.setAuthToken(this.authToken)}setZoomRange(e,n){const r=zt(e),i=zt(n);if(this.minZoomOverride===r&&this.maxZoomOverride===i)return;this.minZoomOverride=r,this.maxZoomOverride=i,this.applyZoomBounds();const o=this.resolveTargetViewState({}),s=this.camera.getViewState();wn(s,o)||this.applyViewStateAndRender(o)}setViewTransition(e){this.viewTransitionDurationMs=hn(e?.duration),this.viewTransitionEasing=dn(e?.easing)}setViewState(e,n){const r=this.resolveTargetViewState(e),i=this.camera.getViewState();if(wn(i,r))return;const o=hn(n?.duration??this.viewTransitionDurationMs),s=dn(n?.easing??this.viewTransitionEasing);if(o<=0){this.applyViewStateAndRender(r);return}this.startViewAnimation(r,o,s)}getViewState(){return this.camera.getViewState()}getZoomRange(){return{minZoom:this.minZoom,maxZoom:this.maxZoom}}getRegionLabelAutoLiftCapZoom(){const e=this.zoomSnaps.filter(n=>n>=this.minZoom&&n<=this.maxZoom);return e.length>0?e[e.length-1]:this.maxZoom}isViewAnimating(){return this.viewAnimationState.animation!==null}registerPointLayer(e){this.ensurePointLayer(e)}unregisterPointLayer(e){const n=String(e||We),r=this.pointLayers.get(n);r&&(this.pointLayers.delete(n),this.deletePointProgram(r.program),this.requestRender())}setPointPalette(e,n=We){const r=this.ensurePointLayer(n);r.runtime=Hr(r.runtime,this.gl,r.program,this.contextLost,e),!(!e||e.length===0)&&this.requestRender()}setPointLineDash(e,n=We){const r=this.ensurePointLayer(n),i=Gl(e);r.pointLineDash[0]===i[0]&&r.pointLineDash[1]===i[1]||(r.pointLineDash=i,this.requestRender())}setPointData(e,n=We){const r=this.ensurePointLayer(n);r.runtime=Zr(r.runtime,this.gl,r.program,this.contextLost,e),this.requestRender()}setInteractionLock(e){const n=!!e;this.interactionLocked!==n&&(this.interactionLocked=n,n&&this.cancelDrag())}setPointSizeByZoom(e,n=We){const r=this.ensurePointLayer(n),i=Wr(e);Xl(r.pointSizeStops,i)||(r.pointSizeStops=i,this.requestRender())}setPointOpacity(e,n=We){const r=this.ensurePointLayer(n),i=Vr(e);r.pointOpacity!==i&&(r.pointOpacity=i,this.requestRender())}setPointStrokeScale(e,n=We){const r=this.ensurePointLayer(n),i=Xr(e);r.pointStrokeScale!==i&&(r.pointStrokeScale=i,this.requestRender())}setPointInnerFillOpacity(e,n=We){const r=this.ensurePointLayer(n),i=Gr(e);r.pointInnerFillOpacity!==i&&(r.pointInnerFillOpacity=i,this.requestRender())}setImageColorSettings(e){const n=qr(e),r=this.imageColorSettings;r.brightness===n.brightness&&r.contrast===n.contrast&&r.saturation===n.saturation||(this.imageColorSettings=n,this.requestRender())}cancelDrag(){lc(this.canvas,this.interactionState)}screenToWorld(e,n){const r=this.canvas.getBoundingClientRect(),i=e-r.left,o=n-r.top;return this.camera.screenToWorld(i,o)}worldToScreen(e,n){return this.camera.worldToScreen(e,n)}setViewCenter(e,n,r){if(!Number.isFinite(e)||!Number.isFinite(n))return;const i=this.camera.getViewState(),o=Math.max(1e-6,i.zoom),s=this.camera.getViewportSize();this.setViewState({offsetX:e-s.width/(2*o),offsetY:n-s.height/(2*o)},r)}getViewCorners(){return this.camera.getViewCorners()}getViewBounds(){return en(this.camera)}resetRotation(e){const n=this.camera.getViewState();Math.abs(n.rotationDeg-this.initialRotationDeg)<1e-6||this.setViewState({rotationDeg:this.initialRotationDeg},e)}getPointSizeByZoom(e=We){const n=Math.max(1e-6,this.camera.getViewState().zoom),r=this.source.maxTierZoom+Math.log2(n),o=this.pointLayers.get(String(e||We))?.pointSizeStops??this.defaultPointSizeStops,s=Vl(r,o);return L(s,Tn,Fl)}fitToImage(e){const n=this.canvas.getBoundingClientRect(),r=Math.max(1,n.width||1),i=Math.max(1,n.height||1),o=jr(this.source,r,i,this.minZoom,this.maxZoom,this.initialRotationDeg);this.fitZoom=o.fitZoom,this.applyZoomBounds(),this.setViewState(o.target,e)}zoomBy(e,n,r,i){const o=Rc(this.camera,this.minZoom,this.maxZoom,e,n,r);o&&this.setViewState(o,i)}zoomTo(e,n,r,i){const o=Ac(this.camera,this.minZoom,this.maxZoom,e,n,r);o&&this.setViewState(o,i)}setZoomSnaps(e,n){this.zoomSnaps=Qr(e,this.source.mpp),this.zoomSnapFitAsMin=!!n}setPanExtent(e){this.applyPanExtent(e)}applyPanExtent(e){typeof e=="number"&&Number.isFinite(e)?(this.panExtentX=Math.max(0,e),this.panExtentY=Math.max(0,e)):e!=null&&typeof e=="object"?(this.panExtentX=typeof e.x=="number"&&Number.isFinite(e.x)?Math.max(0,e.x):.2,this.panExtentY=typeof e.y=="number"&&Number.isFinite(e.y)?Math.max(0,e.y):.2):(this.panExtentX=.2,this.panExtentY=.2)}getZoomPivotAnimationContext(){return{camera:this.camera,viewAnimationState:this.viewAnimationState,minZoom:this.minZoom,maxZoom:this.maxZoom,cancelViewAnimation:()=>this.cancelViewAnimation(),clampViewState:()=>Vt(this.camera,this.source,this.panExtentX,this.panExtentY),onViewStateChange:e=>this.onViewStateChange?.(e),requestRender:()=>this.requestRender()}}handleSnapZoom(e,n,r){const i=this.viewAnimationState.animation,o=i?i.to.zoom:this.camera.getViewState().zoom,s=this.zoomSnaps.filter(f=>f>=this.minZoom&&f<=this.maxZoom),a=Mc(s,o,e,this.zoomSnapFitAsMin);if(!a)return!1;let l;if(a.type==="fit"){const f=this.canvas.getBoundingClientRect(),c=Math.max(1,f.width||1),h=Math.max(1,f.height||1),d=jr(this.source,c,h,this.minZoom,this.maxZoom,this.initialRotationDeg);this.fitZoom=d.fitZoom,this.applyZoomBounds(),l=d.target.zoom}else l=a.zoom;const u=Math.max(Math.abs(l)*.005,1e-8);if(i){if((i.to.zoom>i.from.zoom+u?"in":i.to.zoom<i.from.zoom-u?"out":null)===e&&Math.abs(i.to.zoom-l)<=u)return!1}else if(Math.abs(o-l)<=u)return!1;return Pc(this.getZoomPivotAnimationContext(),l,n,r,Cc),!0}render(){if(this.destroyed||this.contextLost||this.gl.isContextLost())return;const e=this.onStats?xe():0;this.frameSerial+=1;const n=bc({gl:this.gl,camera:this.camera,source:this.source,cache:this.cache,frameSerial:this.frameSerial,tileProgram:this.tileProgram,imageColorSettings:this.imageColorSettings,pointLayers:this.getPointRenderLayers(),tileScheduler:this.tileScheduler,getVisibleTiles:()=>nc(this.camera,this.source),getVisibleTilesForTier:r=>qi(this.camera,this.source,r),getViewBounds:()=>en(this.camera),intersectsBounds:tc});if(this.onStats){const r=this.tileScheduler.getSnapshot();this.onStats({tier:n.tier,visible:n.visible,rendered:n.rendered,points:n.points,fallback:n.fallback,cache:this.cache.size,inflight:r.inflight,queued:r.queued,retries:r.retries,failed:r.failed,aborted:r.aborted,cacheHits:n.cacheHits,cacheMisses:n.cacheMisses,drawCalls:n.drawCalls,frameMs:xe()-e})}}requestRender(){this.frame!==null||this.destroyed||this.contextLost||this.gl.isContextLost()||(this.frame=requestAnimationFrame(()=>{this.frame=null,this.render()}))}resize(){Ll(this.canvas,this.gl,this.camera),this.requestRender()}onWebGlContextLost(e){const n=mc({event:e,destroyed:this.destroyed,contextLost:this.contextLost,frame:this.frame,cancelViewAnimation:()=>this.cancelViewAnimation(),cancelDrag:()=>this.cancelDrag(),tileScheduler:this.tileScheduler,cache:this.cache,onContextLost:this.onContextLost});if(n.handled){this.frame=n.frame,this.contextLost=!0;for(const r of this.pointLayers.values())r.runtime={...r.runtime,pointBuffersDirty:!0}}}onWebGlContextRestored(e){if(!this.destroyed){this.contextLost=!1,this.cache.clear(),this.tileProgram=$r(this.gl);for(const n of this.pointLayers.values())n.program=Kr(this.gl),n.runtime={...n.runtime,pointBuffersDirty:!0},n.runtime.lastPointPalette&&n.runtime.lastPointPalette.length>0&&(n.runtime=Hr(n.runtime,this.gl,n.program,this.contextLost,n.runtime.lastPointPalette)),n.runtime.lastPointData&&(n.runtime=Zr(n.runtime,this.gl,n.program,this.contextLost,n.runtime.lastPointData));this.resize(),this.onContextRestored?.()}}destroy(){const e=gc({destroyed:this.destroyed,frame:this.frame,cancelViewAnimation:()=>this.cancelViewAnimation(),resizeObserver:this.resizeObserver,removeDprListener:this.removeDprListener,removeCanvasEventListeners:()=>_l(this.canvas,this.getCanvasHandlers()),cancelDrag:()=>this.cancelDrag(),tileScheduler:this.tileScheduler,contextLost:this.contextLost,gl:this.gl,cache:this.cache,tileProgram:this.tileProgram,pointPrograms:Array.from(this.pointLayers.values(),n=>n.program)});e.didDestroy&&(this.destroyed=!0,this.frame=e.frame)}}const vc=[];function Tc(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Ic({source:t,viewState:e,onViewStateChange:n,onStats:r,onTileError:i,onContextLost:o,onContextRestored:s,imageColorSettings:a=null,initialRotate:l=0,fitNonce:u=0,rotationResetNonce:f=0,authToken:c="",ctrlDragRotate:h=!0,minZoom:d,maxZoom:m,viewTransition:g,zoomSnaps:y,zoomSnapFitAsMin:b,panExtent:x,onPointerWorldMove:A,debugOverlay:S=!1,debugOverlayStyle:C,className:M,style:P,children:U}){const O=p.useRef(null),N=p.useRef(null),v=p.useRef(null),B=p.useRef(null),F=p.useRef(null),z=p.useRef(null),K=p.useRef(vc),Y=p.useRef(!1),j=p.useRef(new Set),ce=p.useRef(new Set),J=p.useRef(n),Te=p.useRef(r),Pe=p.useRef(i),Re=p.useRef(o),_=p.useRef(s),[T,X]=p.useState(0),[q,te]=p.useState(null),le=p.useRef(S);p.useEffect(()=>{J.current=n},[n]),p.useEffect(()=>{Te.current=r},[r]),p.useEffect(()=>{Pe.current=i},[i]),p.useEffect(()=>{Re.current=o},[o]),p.useEffect(()=>{_.current=s},[s]),p.useEffect(()=>{le.current=S,S||te(null)},[S]);const re=p.useMemo(()=>({position:"relative",width:"100%",height:"100%",...P}),[P]),ge=p.useMemo(()=>({position:"absolute",top:8,left:8,zIndex:7,margin:0,padding:"8px 10px",maxWidth:"min(420px, 80%)",pointerEvents:"none",whiteSpace:"pre-wrap",lineHeight:1.35,fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:11,color:"#cde6ff",background:"rgba(6, 12, 20, 0.82)",border:"1px solid rgba(173, 216, 255, 0.28)",borderRadius:8,boxShadow:"0 8px 22px rgba(0,0,0,0.35)",...C}),[C]),ne=Tc(l),pe=p.useCallback(I=>({...I,rotationDeg:I.rotationDeg-ne}),[ne]),he=p.useCallback(I=>typeof I.rotationDeg!="number"||!Number.isFinite(I.rotationDeg)?I:{...I,rotationDeg:I.rotationDeg+ne},[ne]),se=p.useCallback(I=>{Te.current?.(I),le.current&&te(I)},[]),ue=p.useMemo(()=>q?[`tier ${q.tier} | frame ${q.frameMs?.toFixed(2)??"-"} ms | drawCalls ${q.drawCalls??"-"}`,`tiles visible ${q.visible} | rendered ${q.rendered} | fallback ${q.fallback}`,`cache size ${q.cache} | hit ${q.cacheHits??"-"} | miss ${q.cacheMisses??"-"}`,`queue inflight ${q.inflight} | queued ${q.queued??"-"} | retries ${q.retries??"-"} | failed ${q.failed??"-"} | aborted ${q.aborted??"-"}`,`points ${q.points}`].join(`
246
- `):"stats: waiting for first frame...",[q]),Ae=p.useCallback(()=>{const I=v.current;if(!I)return;const W=I.getContext("2d");if(!W)return;const Q=Math.max(1,window.devicePixelRatio||1),ee=I.getBoundingClientRect(),fe=Math.max(1,Math.round(ee.width*Q)),Ce=Math.max(1,Math.round(ee.height*Q));(I.width!==fe||I.height!==Ce)&&(I.width=fe,I.height=Ce);const Ie=ee.width,ve=ee.height;W.setTransform(1,0,0,1,0,0),W.clearRect(0,0,I.width,I.height),W.setTransform(Q,0,0,Q,0,0);const w=K.current;for(let R=0;R<w.length;R+=1)W.save(),w[R].draw(W,Ie,ve),W.restore()},[]),H=p.useCallback(()=>{Y.current||(Y.current=!0,requestAnimationFrame(()=>{Y.current=!1,Ae()}))},[Ae]),Le=p.useCallback((I,W,Q)=>{const ee=K.current.filter(fe=>fe.id!==I);ee.push({id:I,priority:W,draw:Q}),ee.sort((fe,Ce)=>fe.priority-Ce.priority),K.current=ee,H()},[H]),we=p.useCallback(I=>{K.current=K.current.filter(W=>W.id!==I),H()},[H]),de=p.useCallback((I,W)=>{W?j.current.add(I):j.current.delete(I),B.current?.setInteractionLock(j.current.size>0)},[]),V=p.useCallback(()=>j.current.size>0,[]),$=p.useCallback((I,W)=>{const Q=B.current;return Q?Dn(Q.worldToScreen(I,W)):null},[]),ie=p.useCallback((I,W)=>{const Q=B.current;if(!Q)return null;const ee=Q.screenToWorld(I,W);if(!Array.isArray(ee)||ee.length<2)return null;const fe=Number(ee[0]),Ce=Number(ee[1]);return!Number.isFinite(fe)||!Number.isFinite(Ce)?null:[fe,Ce]},[]),oe=p.useCallback(I=>(ce.current.add(I),()=>{ce.current.delete(I)}),[]),Se=p.useCallback(I=>{J.current?.(pe(I));const W=ce.current;if(W.size>0){const Q=Array.from(W);for(let ee=0;ee<Q.length;ee+=1)Q[ee](I)}F.current?.(),z.current?.(),H()},[H,pe]);p.useEffect(()=>{const I=N.current;if(!I||!t)return;const W=new Zi(I,t,{onViewStateChange:Se,onStats:se,onTileError:Q=>{Pe.current?.(Q)},onContextLost:()=>{Re.current?.()},onContextRestored:()=>{_.current?.()},authToken:c,imageColorSettings:a,initialRotationDeg:l,ctrlDragRotate:h,minZoom:d,maxZoom:m,viewTransition:g,zoomSnaps:y,zoomSnapFitAsMin:b,panExtent:x});return B.current=W,X(Q=>Q+1),e&&W.setViewState(he(e)),W.setInteractionLock(j.current.size>0),()=>{W.destroy(),B.current=null}},[t,se,h,Se,ne,he]),p.useEffect(()=>{B.current?.setAuthToken(c)},[c]),p.useEffect(()=>{const I=B.current;!I||!e||I.isViewAnimating()||I.setViewState(he(e))},[e,he]),p.useEffect(()=>{B.current?.fitToImage()},[u]),p.useEffect(()=>{B.current?.resetRotation()},[f]),p.useEffect(()=>{B.current?.setZoomRange(d,m)},[d,m]),p.useEffect(()=>{B.current?.setViewTransition(g)},[g]),p.useEffect(()=>{B.current?.setZoomSnaps(y,b)},[y,b]),p.useEffect(()=>{B.current?.setPanExtent(x)},[x]),p.useEffect(()=>{B.current?.setImageColorSettings(a)},[a]),p.useEffect(()=>{const I=v.current;if(!I)return;F.current=H,H();const W=new ResizeObserver(()=>H());return W.observe(I),()=>{W.disconnect(),F.current===H&&(F.current=null)}},[H]),p.useEffect(()=>tn(()=>H()),[H]);const De=p.useMemo(()=>({source:t,rendererRef:B,rendererSerial:T,canvasRef:N,containerRef:O,drawInvalidateRef:F,overviewInvalidateRef:z,worldToScreen:$,screenToWorld:ie,registerDrawCallback:Le,unregisterDrawCallback:we,requestOverlayRedraw:H,registerViewStateListener:oe,setInteractionLock:de,isInteractionLocked:V}),[t,T,$,ie,Le,we,H,oe,de,V]),G=p.useRef(A);p.useEffect(()=>{G.current=A},[A]);const ye=p.useCallback(I=>{const W=G.current;if(!W)return;const Q=ie(I.clientX,I.clientY),ee=!!Q&&Q[0]>=0&&Q[1]>=0&&!!t&&Q[0]<=t.width&&Q[1]<=t.height;W({coordinate:Q,clientX:I.clientX,clientY:I.clientY,insideImage:ee})},[ie,t]),be=p.useCallback(()=>{G.current?.({coordinate:null,clientX:-1,clientY:-1,insideImage:!1})},[]);return He.jsx(Ks,{value:De,children:He.jsxs("div",{ref:O,className:M,style:re,onPointerMove:A?ye:void 0,onPointerLeave:A?be:void 0,children:[He.jsx("canvas",{ref:N,className:"wsi-render-canvas",style:{position:"absolute",inset:0,zIndex:1,width:"100%",height:"100%",display:"block",touchAction:"none"}}),He.jsx("canvas",{ref:v,className:"wsi-overlay-canvas",style:{position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",pointerEvents:"none",touchAction:"none"}}),U,S&&He.jsx("pre",{"data-open-plant-debug-overlay":!0,style:ge,children:ue})]})})}function _c(t){const e=[];for(let n=0;n<t.length;n+=1){const r=t[n],i=dt([ht(r?.coordinates)]);if(i.length===0)continue;let o=0,s=1/0,a=1/0,l=-1/0,u=-1/0;for(const f of i)o+=f.area,f.minX<s&&(s=f.minX),f.minY<a&&(a=f.minY),f.maxX>l&&(l=f.maxX),f.maxY>u&&(u=f.maxY);!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(l)||!Number.isFinite(u)||e.push({regionId:r.id??n,regionIndex:n,polygons:i,area:Math.max(1e-6,o),minX:s,minY:a,maxX:l,maxY:u})}return e}const Lc=128,mn=[];function ut(t,e,n,r,i){if(i<=1||n<=e)return 0;const o=(t-e)/r;return!Number.isFinite(o)||o<=0?0:o>=i-1?i-1:Math.floor(o)}function Fc(t){if(t.length===0)return null;let e=1/0,n=1/0,r=-1/0,i=-1/0;for(const f of t)f.minX<e&&(e=f.minX),f.minY<n&&(n=f.minY),f.maxX>r&&(r=f.maxX),f.maxY>i&&(i=f.maxY);if(!Number.isFinite(e)||!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(i))return null;const o=Math.ceil(Math.sqrt(t.length*2)),s=Math.max(1,Math.min(Lc,o)),a=r>e?(r-e)/s:1,l=i>n?(i-n)/s:1,u=Array.from({length:s*s},()=>[]);for(let f=0;f<t.length;f+=1){const c=t[f],h=ut(c.minX,e,r,a,s),d=ut(c.maxX,e,r,a,s),m=ut(c.minY,n,i,l,s),g=ut(c.maxY,n,i,l,s);for(let y=m;y<=g;y+=1)for(let b=h;b<=d;b+=1)u[y*s+b].push(f)}return{minX:e,minY:n,maxX:r,maxY:i,gridSize:s,cellWidth:a,cellHeight:l,buckets:u}}function Dc(t,e,n){if(!t||e<t.minX||e>t.maxX||n<t.minY||n>t.maxY)return mn;const r=ut(e,t.minX,t.maxX,t.cellWidth,t.gridSize),i=ut(n,t.minY,t.maxY,t.cellHeight,t.gridSize);return t.buckets[i*t.gridSize+r]??mn}function Nc(t,e){if(Array.isArray(e)){const n=e[t];if(typeof n=="string"&&n.length>0)return n}if(e instanceof Map){const n=e.get(t);if(typeof n=="string"&&n.length>0)return n}return String(t)}function Bc(t,e,n={}){const r=Math.max(0,Math.min(Math.floor(t?.count??0),Math.floor((t?.positions?.length??0)/2),t?.paletteIndices?.length??0,t?.fillModes instanceof Uint8Array?t.fillModes.length:Number.MAX_SAFE_INTEGER));let i=null;if(t?.drawIndices instanceof Uint32Array){const d=t.drawIndices;let m=d.length;for(let g=0;g<d.length;g+=1)d[g]<r||(m-=1);if(m===d.length)i=d;else if(m>0){const g=new Uint32Array(m);let y=0;for(let b=0;b<d.length;b+=1){const x=d[b];x>=r||(g[y]=x,y+=1)}i=g}else i=new Uint32Array(0)}const o=i?i.length:r,s=_c(e??[]);if(!t||o===0||s.length===0)return{groups:[],inputPointCount:o,pointsInsideAnyRegion:0,unmatchedPointCount:o};const a=new Map,l=new Map,u=Fc(s);let f=0;for(let d=0;d<o;d+=1){const m=i?i[d]:d,g=t.positions[m*2],y=t.positions[m*2+1];if(!Number.isFinite(g)||!Number.isFinite(y))continue;let b=null;const x=Dc(u,g,y);if(x.length===0)continue;for(const C of x){const M=s[C];let P=!1;for(const U of M.polygons)if(si(g,y,U)){P=!0;break}P&&(!b||M.area<b.area)&&(b=M)}if(!b)continue;f+=1;const A=t.paletteIndices[m]??0,S=a.get(b.regionIndex)??new Map;S.set(A,(S.get(A)??0)+1),a.set(b.regionIndex,S),l.set(b.regionIndex,(l.get(b.regionIndex)??0)+1)}const c=n.includeEmptyRegions??!1,h=[];for(const d of s){const m=l.get(d.regionIndex)??0;if(!c&&m<=0)continue;const g=a.get(d.regionIndex)??new Map,y=Array.from(g.entries()).map(([b,x])=>({classId:Nc(b,n.paletteIndexToClassId),paletteIndex:b,count:x})).sort((b,x)=>x.count-b.count||b.paletteIndex-x.paletteIndex);h.push({regionId:d.regionId,regionIndex:d.regionIndex,totalCount:m,classCounts:y})}return{groups:h,inputPointCount:o,pointsInsideAnyRegion:f,unmatchedPointCount:Math.max(0,o-f)}}function kc(t){return t.replace(/^\s*SRID\s*=\s*\d+\s*;\s*/i,"")}function Uc(t){return t>="A"&&t<="Z"||t>="a"&&t<="z"}function zc(t){return t>="0"&&t<="9"}function Jr(t){return t==="+"||t==="-"||t==="."||zc(t)}class Oc{constructor(e){E(this,"text");E(this,"index",0);this.text=kc(e.trim())}parse(){if(!this.text)return null;const e=this.readWord();if(!e)return null;const n=e.toUpperCase();if(n!=="POLYGON"&&n!=="MULTIPOLYGON")return null;this.skipWhitespace();const r=this.peekWord();if(r){const s=r.toUpperCase();(s==="Z"||s==="M"||s==="ZM")&&(this.readWord(),this.skipWhitespace())}if(this.consumeWordIf("EMPTY"))return this.skipWhitespace(),this.isEof()?n==="POLYGON"?{type:"Polygon",coordinates:[]}:{type:"MultiPolygon",coordinates:[]}:null;let i;try{i=this.parseNestedList()}catch{return null}if(this.skipWhitespace(),!this.isEof())return null;if(n==="POLYGON"){const s=$i(i);return s?{type:"Polygon",coordinates:s}:null}const o=Wc(i);return o?{type:"MultiPolygon",coordinates:o}:null}isEof(){return this.index>=this.text.length}currentChar(){return this.text[this.index]??""}skipWhitespace(){for(;!this.isEof()&&/\s/.test(this.currentChar());)this.index+=1}readWord(){if(this.skipWhitespace(),this.isEof())return null;const e=this.index;for(;!this.isEof()&&Uc(this.currentChar());)this.index+=1;return this.index===e?null:this.text.slice(e,this.index)}peekWord(){const e=this.index,n=this.readWord();return this.index=e,n}consumeWordIf(e){const n=this.index,r=this.readWord();return!r||r.toUpperCase()!==e.toUpperCase()?(this.index=n,!1):!0}parseNestedList(){if(this.skipWhitespace(),this.currentChar()!=="(")throw new Error("Expected '('");this.index+=1;const e=[];for(;;){this.skipWhitespace(),this.currentChar()==="("?e.push(this.parseNestedList()):e.push(this.parseCoordinateTuple()),this.skipWhitespace();const n=this.currentChar();if(n===","){this.index+=1;continue}if(n===")"){this.index+=1;break}throw new Error("Expected ',' or ')'")}return e}parseCoordinateTuple(){this.skipWhitespace();const e=[];for(;;){this.skipWhitespace();const n=this.currentChar();if(!n||!Jr(n))break;const r=this.readNumber();if(r===null)break;e.push(r),this.skipWhitespace();const i=this.currentChar();if(!i||i===","||i===")")break;if(!Jr(i))throw new Error("Invalid coordinate")}if(e.length<2)throw new Error("Coordinate requires at least x y");return[e[0],e[1]]}readNumber(){if(this.skipWhitespace(),this.isEof())return null;const n=this.text.slice(this.index).match(/^[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?/);if(!n)return null;const r=Number(n[0]);return Number.isFinite(r)?(this.index+=n[0].length,r):null}}function Yc(t){return Array.isArray(t)&&t.length>=2&&typeof t[0]=="number"&&Number.isFinite(t[0])&&typeof t[1]=="number"&&Number.isFinite(t[1])}function $i(t){if(!Array.isArray(t))return null;const e=[];for(const n of t){if(!Array.isArray(n))return null;const r=[];for(const i of n){if(!Yc(i))return null;r.push([i[0],i[1]])}e.push(r)}return e}function Wc(t){if(!Array.isArray(t))return null;const e=[];for(const n of t){const r=$i(n);if(!r)return null;e.push(r)}return e}function Xc(t){return typeof t!="string"?null:new Oc(t).parse()}exports.DEFAULT_POINT_COLOR=Ln;exports.DrawLayer=bi;exports.DrawingLayer=js;exports.HeatmapLayer=_a;exports.M1TileRenderer=ti;exports.OverlayLayer=Fa;exports.OverviewMap=Oa;exports.PatchLayer=Wa;exports.PointLayer=ml;exports.RegionLayer=Pl;exports.TileScheduler=Xi;exports.TileViewerCanvas=vl;exports.WsiTileRenderer=Zi;exports.WsiViewer=Ic;exports.__heatmapLayerInternals=La;exports.buildClassPalette=No;exports.buildPointSpatialIndexAsync=Wi;exports.calcScaleLength=Lo;exports.calcScaleResolution=Fn;exports.clamp=L;exports.closeRing=Ue;exports.computeRoiPointGroups=Bc;exports.createCircle=Sn;exports.createRectangle=Kt;exports.createSpatialIndex=wi;exports.filterPointDataByPolygons=Rt;exports.filterPointDataByPolygonsHybrid=Ui;exports.filterPointDataByPolygonsInWorker=Oi;exports.filterPointIndicesByPolygons=Ni;exports.filterPointIndicesByPolygonsInWorker=Qa;exports.getWebGpuCapabilities=$a;exports.hexToRgba=ai;exports.isSameViewState=wn;exports.lookupCellIndex=Yi;exports.normalizeImageClasses=Da;exports.normalizeImageInfo=Ba;exports.parseWkt=Xc;exports.prefilterPointsByBoundsWebGpu=ki;exports.terminatePointHitIndexWorker=ll;exports.terminateRoiClipWorker=ja;exports.toBearerToken=Fo;exports.toRoiGeometry=ht;exports.toTileUrl=Vn;exports.useViewerContext=at;
245
+ }`),i=Le(t,r,"uCamera"),o=Le(t,r,"uPointSize"),s=Le(t,r,"uPointCssSize"),a=Le(t,r,"uPointOpacity"),l=Le(t,r,"uPointStrokeScale"),u=Le(t,r,"uPointInnerFillAlpha"),f=Le(t,r,"uPalette"),c=Le(t,r,"uPaletteSize"),h=Le(t,r,"uPointLineDash"),d=t.createVertexArray(),m=t.createBuffer(),g=t.createBuffer(),b=t.createBuffer(),y=t.createBuffer(),w=t.createTexture();if(!d||!m||!g||!b||!y||!w)throw new Error("point buffer allocation failed");t.bindVertexArray(d),t.bindBuffer(t.ARRAY_BUFFER,m),t.bufferData(t.ARRAY_BUFFER,0,t.DYNAMIC_DRAW);const A=t.getAttribLocation(r,"aPosition");if(A<0)throw new Error("point position attribute not found");t.enableVertexAttribArray(A),t.vertexAttribPointer(A,2,t.FLOAT,!1,0,0),t.bindBuffer(t.ARRAY_BUFFER,g),t.bufferData(t.ARRAY_BUFFER,0,t.DYNAMIC_DRAW);const S=t.getAttribLocation(r,"aClass");if(S<0)throw new Error("point class attribute not found");t.enableVertexAttribArray(S),t.vertexAttribIPointer(S,1,t.UNSIGNED_SHORT,0,0),t.bindBuffer(t.ARRAY_BUFFER,b),t.bufferData(t.ARRAY_BUFFER,0,t.DYNAMIC_DRAW);const C=t.getAttribLocation(r,"aFillMode");if(C<0)throw new Error("point fill mode attribute not found");return t.enableVertexAttribArray(C),t.vertexAttribIPointer(C,1,t.UNSIGNED_BYTE,0,0),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,y),t.bufferData(t.ELEMENT_ARRAY_BUFFER,0,t.DYNAMIC_DRAW),t.bindVertexArray(null),t.bindBuffer(t.ARRAY_BUFFER,null),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null),t.bindTexture(t.TEXTURE_2D,w),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,new Uint8Array([160,160,160,255])),t.bindTexture(t.TEXTURE_2D,null),{program:r,vao:d,posBuffer:m,classBuffer:g,fillModeBuffer:b,indexBuffer:y,paletteTexture:w,uCamera:i,uPointSize:o,uPointCssSize:s,uPointOpacity:a,uPointLineDash:h,uPointStrokeScale:l,uPointInnerFillAlpha:u,uPalette:f,uPaletteSize:c}}function ji(t){t.animation=null,t.frame!==null&&(cancelAnimationFrame(t.frame),t.frame=null)}function Mc(t){const{state:e,camera:n,target:r,durationMs:i,easing:o,onUpdate:s}=t,a=n.getViewState();ji(e),e.animation={startMs:we(),durationMs:Math.max(0,i),from:a,to:r,easing:o};const l=()=>{const u=e.animation;if(!u)return;const f=Math.max(0,we()-u.startMs),c=u.durationMs<=0?1:F(f/u.durationMs,0,1);let h=c;try{h=u.easing(c)}catch{h=c}if(Number.isFinite(h)||(h=c),h=F(h,0,1),n.setViewState({zoom:u.from.zoom+(u.to.zoom-u.from.zoom)*h,offsetX:u.from.offsetX+(u.to.offsetX-u.from.offsetX)*h,offsetY:u.from.offsetY+(u.to.offsetY-u.from.offsetY)*h,rotationDeg:u.from.rotationDeg+(u.to.rotationDeg-u.from.rotationDeg)*h}),s(),c>=1){e.animation=null,e.frame=null;return}e.frame=requestAnimationFrame(l)};e.frame=requestAnimationFrame(l)}function Pc(t){const e=Math.max(t*.5,1e-6),n=Math.max(1,t*8);return{minZoom:e,maxZoom:Math.max(e,n)}}function vc(t,e,n){const r=Pc(t);let i=e??r.minZoom,o=n??r.maxZoom;return i=Math.max(1e-6,i),o=Math.max(1e-6,o),i>o&&(i=o),{minZoom:i,maxZoom:o}}function Tc(t,e,n,r,i){const o=t.getViewState(),s={zoom:typeof r.zoom=="number"&&Number.isFinite(r.zoom)?F(r.zoom,e,n):o.zoom,offsetX:typeof r.offsetX=="number"&&Number.isFinite(r.offsetX)?r.offsetX:o.offsetX,offsetY:typeof r.offsetY=="number"&&Number.isFinite(r.offsetY)?r.offsetY:o.offsetY,rotationDeg:typeof r.rotationDeg=="number"&&Number.isFinite(r.rotationDeg)?r.rotationDeg:o.rotationDeg};t.setViewState(s),i();const a=t.getViewState();return t.setViewState(o),a}function ti(t,e,n,r,i,o=0){const s=Math.min(e/t.width,n/t.height),a=Number.isFinite(s)&&s>0?s:1,l=F(a,r,i),u=e/l,f=n/l;return{fitZoom:a,target:{zoom:l,offsetX:(t.width-u)*.5,offsetY:(t.height-f)*.5,rotationDeg:o}}}function Ic(t,e,n,r,i,o){const s=t.getViewState(),a=F(s.zoom*r,e,n);if(a===s.zoom)return null;const[l,u]=t.screenToWorld(i,o),f=t.getViewportSize(),c=i-f.width*.5,h=o-f.height*.5,d=nn(s.rotationDeg),m=Math.cos(d),g=Math.sin(d),b=c/a*m-h/a*g,y=c/a*g+h/a*m,w=l-b,A=u-y;return{zoom:a,offsetX:w-f.width/(2*a),offsetY:A-f.height/(2*a)}}function _c(t,e,n,r,i,o){const s=t.getViewState(),a=F(r,e,n);if(a===s.zoom)return null;const[l,u]=t.screenToWorld(i,o),f=t.getViewportSize(),c=i-f.width*.5,h=o-f.height*.5,d=nn(s.rotationDeg),m=Math.cos(d),g=Math.sin(d),b=c/a*m-h/a*g,y=c/a*g+h/a*m,w=l-b,A=u-y;return{zoom:a,offsetX:w-f.width/(2*a),offsetY:A-f.height/(2*a)}}const Lc=250;function ni(t,e){if(!t||t.length===0)return[];if(!e||e<=0)return[];const n=10/e;return t.map(r=>r/n).filter(r=>Number.isFinite(r)&&r>0).sort((r,i)=>r-i)}function Fc(t,e,n,r){if(t.length===0)return null;const i=Math.max(e*.005,1e-8);if(n==="in"){for(const o of t)if(o>e+i)return{type:"snap",zoom:o};return null}for(let o=t.length-1;o>=0;o--)if(t[o]<e-i)return{type:"snap",zoom:t[o]};return r&&e<=t[0]+i?{type:"fit"}:null}function Dc(t,e,n,r,i){const o=t.camera.getViewState(),[s,a]=t.camera.screenToWorld(n,r),l=t.camera.getViewportSize(),u=F(e,t.minZoom,t.maxZoom);if(u===o.zoom)return;const f=nn(o.rotationDeg),c=Math.cos(f),h=Math.sin(f),d=n-l.width*.5,m=r-l.height*.5;t.cancelViewAnimation();const g=w=>{const A=d/w*c-m/w*h,S=d/w*h+m/w*c;return{offsetX:s-A-l.width/(2*w),offsetY:a-S-l.height/(2*w)}},b=g(u);t.viewAnimationState.animation={startMs:we(),durationMs:Math.max(0,i),from:o,to:{zoom:u,offsetX:b.offsetX,offsetY:b.offsetY,rotationDeg:o.rotationDeg},easing:qn};const y=()=>{const w=t.viewAnimationState.animation;if(!w)return;const A=Math.max(0,we()-w.startMs),S=F(A/i,0,1),C=F(S*S*(3-2*S),0,1),M=o.zoom+(u-o.zoom)*C,{offsetX:P,offsetY:O}=g(M);t.camera.setViewState({zoom:M,offsetX:P,offsetY:O,rotationDeg:o.rotationDeg});const W=S>=1;W&&(t.clampViewState(),t.viewAnimationState.animation=null,t.viewAnimationState.frame=null),t.onViewStateChange(t.camera.getViewState()),t.requestRender(),W||(t.viewAnimationState.frame=requestAnimationFrame(y))};t.viewAnimationState.frame=requestAnimationFrame(y)}const Xe="__default_point_layer__";class Qi{constructor(e,n,r={}){E(this,"canvas");E(this,"source");E(this,"gl");E(this,"camera",new ii);E(this,"onViewStateChange");E(this,"onStats");E(this,"onTileError");E(this,"onContextLost");E(this,"onContextRestored");E(this,"resizeObserver");E(this,"removeDprListener");E(this,"tileProgram");E(this,"tileScheduler");E(this,"authToken");E(this,"destroyed",!1);E(this,"contextLost",!1);E(this,"frame",null);E(this,"frameSerial",0);E(this,"interactionState",{dragging:!1,mode:"none",rotateLastAngleRad:null,pointerId:null,lastPointerX:0,lastPointerY:0});E(this,"interactionLocked",!1);E(this,"ctrlDragRotate",!0);E(this,"rotationDragSensitivityDegPerPixel",Tn);E(this,"maxCacheTiles");E(this,"fitZoom",1);E(this,"initialRotationDeg",0);E(this,"minZoom",1e-6);E(this,"maxZoom",1);E(this,"minZoomOverride",null);E(this,"maxZoomOverride",null);E(this,"viewTransitionDurationMs",0);E(this,"viewTransitionEasing",qn);E(this,"viewAnimationState",{animation:null,frame:null});E(this,"pointLayers",new Map);E(this,"defaultPointSizeStops",Jt(_n));E(this,"defaultPointOpacity",1);E(this,"defaultPointLineDash",[1,0]);E(this,"defaultPointStrokeScale",1);E(this,"defaultPointInnerFillOpacity",0);E(this,"imageColorSettings",{brightness:0,contrast:0,saturation:0});E(this,"cache",new Map);E(this,"zoomSnaps",[]);E(this,"zoomSnapFitAsMin",!1);E(this,"zoomSnapState",{accumulatedDelta:0,lastSnapTimeMs:0,blockedDirection:null});E(this,"panExtentX",.2);E(this,"panExtentY",.2);E(this,"boundPointerDown");E(this,"boundPointerMove");E(this,"boundPointerUp");E(this,"boundWheel");E(this,"boundDoubleClick");E(this,"boundContextMenu");E(this,"boundContextLost");E(this,"boundContextRestored");this.canvas=e,this.source=n,this.onViewStateChange=r.onViewStateChange,this.onStats=r.onStats,this.onTileError=r.onTileError,this.onContextLost=r.onContextLost,this.onContextRestored=r.onContextRestored,this.authToken=r.authToken??"",this.maxCacheTiles=Math.max(32,Math.floor(r.maxCacheTiles??320)),this.initialRotationDeg=typeof r.initialRotationDeg=="number"&&Number.isFinite(r.initialRotationDeg)?r.initialRotationDeg:0,this.ctrlDragRotate=r.ctrlDragRotate??!0,this.rotationDragSensitivityDegPerPixel=typeof r.rotationDragSensitivityDegPerPixel=="number"&&Number.isFinite(r.rotationDragSensitivityDegPerPixel)?Math.max(0,r.rotationDragSensitivityDegPerPixel):Tn,this.defaultPointSizeStops=qr(r.pointSizeByZoom),this.defaultPointOpacity=Zr(r.pointOpacity),this.defaultPointStrokeScale=Hr(r.pointStrokeScale),this.defaultPointInnerFillOpacity=$r(r.pointInnerFillOpacity),this.imageColorSettings=Kr(r.imageColorSettings),this.minZoomOverride=zt(r.minZoom),this.maxZoomOverride=zt(r.maxZoom),this.viewTransitionDurationMs=hn(r.viewTransition?.duration),this.viewTransitionEasing=dn(r.viewTransition?.easing),this.zoomSnaps=ni(r.zoomSnaps,this.source.mpp),this.zoomSnapFitAsMin=!!r.zoomSnapFitAsMin,this.applyPanExtent(r.panExtent);const i=e.getContext("webgl2",{alpha:!1,antialias:!1,depth:!1,stencil:!1,powerPreference:"high-performance"});if(!i)throw new Error("WebGL2 not supported");this.gl=i,this.tileProgram=Jr(this.gl),this.tileScheduler=new Hi({authToken:this.authToken,maxConcurrency:r.tileScheduler?.maxConcurrency??12,maxRetries:r.tileScheduler?.maxRetries??2,retryBaseDelayMs:r.tileScheduler?.retryBaseDelayMs??120,retryMaxDelayMs:r.tileScheduler?.retryMaxDelayMs??1200,onTileLoad:(s,a)=>xc({gl:this.gl,cache:this.cache,tile:s,bitmap:a,frameSerial:this.frameSerial,maxCacheTiles:this.maxCacheTiles,destroyed:this.destroyed,contextLost:this.contextLost,requestRender:()=>this.requestRender()}),onTileError:(s,a,l)=>{this.onTileError?.({tile:s,error:a,attemptCount:l}),console.warn("tile load failed",s.url,a)}}),this.resizeObserver=new ResizeObserver(()=>this.resize()),this.resizeObserver.observe(e),this.removeDprListener=tn(()=>this.resize());const o=pc({canvas:this.canvas,state:this.interactionState,getInteractionLocked:()=>this.interactionLocked,getCtrlDragRotate:()=>this.ctrlDragRotate,getRotationDragSensitivityDegPerPixel:()=>this.rotationDragSensitivityDegPerPixel,cancelViewAnimation:()=>this.cancelViewAnimation(),camera:this.camera,source:this.source,emitViewState:()=>this.onViewStateChange?.(this.camera.getViewState()),requestRender:()=>this.requestRender(),getPanExtentX:()=>this.panExtentX,getPanExtentY:()=>this.panExtentY,zoomBy:(s,a,l)=>this.zoomBy(s,a,l),getUseZoomSnaps:()=>this.zoomSnaps.length>0,onSnapZoom:(s,a,l)=>this.handleSnapZoom(s,a,l),zoomSnapState:this.zoomSnapState});this.boundPointerDown=o.pointerDown,this.boundPointerMove=o.pointerMove,this.boundPointerUp=o.pointerUp,this.boundWheel=o.wheel,this.boundDoubleClick=o.doubleClick,this.boundContextMenu=o.contextMenu,this.boundContextLost=s=>this.onWebGlContextLost(s),this.boundContextRestored=s=>this.onWebGlContextRestored(s),kl(e,this.getCanvasHandlers()),this.fitToImage({duration:0}),this.resize()}getCanvasHandlers(){return{pointerDown:this.boundPointerDown,pointerMove:this.boundPointerMove,pointerUp:this.boundPointerUp,wheel:this.boundWheel,doubleClick:this.boundDoubleClick,contextMenu:this.boundContextMenu,contextLost:this.boundContextLost,contextRestored:this.boundContextRestored}}applyZoomBounds(){const e=vc(this.fitZoom,this.minZoomOverride,this.maxZoomOverride);this.minZoom=e.minZoom,this.maxZoom=e.maxZoom}resolveTargetViewState(e){return Tc(this.camera,this.minZoom,this.maxZoom,e,()=>Vt(this.camera,this.source,this.panExtentX,this.panExtentY))}cancelViewAnimation(){ji(this.viewAnimationState)}startViewAnimation(e,n,r){Mc({state:this.viewAnimationState,camera:this.camera,target:e,durationMs:n,easing:r,onUpdate:()=>{Vt(this.camera,this.source,this.panExtentX,this.panExtentY),this.onViewStateChange?.(this.camera.getViewState()),this.requestRender()}})}createPointBufferRuntime(){return{pointCount:0,usePointIndices:!1,pointBuffersDirty:!0,lastPointData:null,zeroFillModes:new Uint8Array(0),lastPointPalette:null,pointPaletteSize:1}}createPointLayerState(e){return{id:e,program:ei(this.gl),runtime:this.createPointBufferRuntime(),pointSizeStops:Jt(this.defaultPointSizeStops),pointOpacity:this.defaultPointOpacity,pointLineDash:[...this.defaultPointLineDash],pointStrokeScale:this.defaultPointStrokeScale,pointInnerFillOpacity:this.defaultPointInnerFillOpacity}}ensurePointLayer(e=Xe){const n=String(e||Xe),r=this.pointLayers.get(n);if(r)return r;const i=this.createPointLayerState(n);return this.pointLayers.set(n,i),i}deletePointProgram(e){this.contextLost||this.gl.isContextLost()||(this.gl.deleteBuffer(e.posBuffer),this.gl.deleteBuffer(e.classBuffer),this.gl.deleteBuffer(e.fillModeBuffer),this.gl.deleteBuffer(e.indexBuffer),this.gl.deleteTexture(e.paletteTexture),this.gl.deleteVertexArray(e.vao),this.gl.deleteProgram(e.program))}getPointRenderLayers(){const e=Math.max(1,window.devicePixelRatio||1),n=[];for(const r of this.pointLayers.values()){const i=this.getPointSizeByZoom(r.id);n.push({pointProgram:r.program,pointCount:r.runtime.pointCount,usePointIndices:r.runtime.usePointIndices,pointPaletteSize:r.runtime.pointPaletteSize,pointLineDash:r.pointLineDash,pointOpacity:r.pointOpacity,pointStrokeScale:r.pointStrokeScale,pointInnerFillOpacity:r.pointInnerFillOpacity,pointCssSizePx:i,pointSizePx:i*e})}return n}applyViewStateAndRender(e,n=!0){n&&this.cancelViewAnimation(),this.camera.setViewState(e),this.onViewStateChange?.(this.camera.getViewState()),this.requestRender()}setAuthToken(e){this.authToken=String(e??""),this.tileScheduler.setAuthToken(this.authToken)}setZoomRange(e,n){const r=zt(e),i=zt(n);if(this.minZoomOverride===r&&this.maxZoomOverride===i)return;this.minZoomOverride=r,this.maxZoomOverride=i,this.applyZoomBounds();const o=this.resolveTargetViewState({}),s=this.camera.getViewState();wn(s,o)||this.applyViewStateAndRender(o)}setViewTransition(e){this.viewTransitionDurationMs=hn(e?.duration),this.viewTransitionEasing=dn(e?.easing)}setViewState(e,n){const r=this.resolveTargetViewState(e),i=this.camera.getViewState();if(wn(i,r))return;const o=hn(n?.duration??this.viewTransitionDurationMs),s=dn(n?.easing??this.viewTransitionEasing);if(o<=0){this.applyViewStateAndRender(r);return}this.startViewAnimation(r,o,s)}getViewState(){return this.camera.getViewState()}getZoomRange(){return{minZoom:this.minZoom,maxZoom:this.maxZoom}}getRegionLabelAutoLiftCapZoom(){const e=this.zoomSnaps.filter(n=>n>=this.minZoom&&n<=this.maxZoom);return e.length>0?e[e.length-1]:this.maxZoom}isViewAnimating(){return this.viewAnimationState.animation!==null}registerPointLayer(e){this.ensurePointLayer(e)}unregisterPointLayer(e){const n=String(e||Xe),r=this.pointLayers.get(n);r&&(this.pointLayers.delete(n),this.deletePointProgram(r.program),this.requestRender())}setPointPalette(e,n=Xe){const r=this.ensurePointLayer(n);r.runtime=jr(r.runtime,this.gl,r.program,this.contextLost,e),!(!e||e.length===0)&&this.requestRender()}setPointLineDash(e,n=Xe){const r=this.ensurePointLayer(n),i=Ql(e);r.pointLineDash[0]===i[0]&&r.pointLineDash[1]===i[1]||(r.pointLineDash=i,this.requestRender())}setPointData(e,n=Xe){const r=this.ensurePointLayer(n);r.runtime=Qr(r.runtime,this.gl,r.program,this.contextLost,e),this.requestRender()}setInteractionLock(e){const n=!!e;this.interactionLocked!==n&&(this.interactionLocked=n,n&&this.cancelDrag())}setPointSizeByZoom(e,n=Xe){const r=this.ensurePointLayer(n),i=qr(e);Kl(r.pointSizeStops,i)||(r.pointSizeStops=i,this.requestRender())}setPointOpacity(e,n=Xe){const r=this.ensurePointLayer(n),i=Zr(e);r.pointOpacity!==i&&(r.pointOpacity=i,this.requestRender())}setPointStrokeScale(e,n=Xe){const r=this.ensurePointLayer(n),i=Hr(e);r.pointStrokeScale!==i&&(r.pointStrokeScale=i,this.requestRender())}setPointInnerFillOpacity(e,n=Xe){const r=this.ensurePointLayer(n),i=$r(e);r.pointInnerFillOpacity!==i&&(r.pointInnerFillOpacity=i,this.requestRender())}setImageColorSettings(e){const n=Kr(e),r=this.imageColorSettings;r.brightness===n.brightness&&r.contrast===n.contrast&&r.saturation===n.saturation||(this.imageColorSettings=n,this.requestRender())}cancelDrag(){gc(this.canvas,this.interactionState)}screenToWorld(e,n){const r=this.canvas.getBoundingClientRect(),i=e-r.left,o=n-r.top;return this.camera.screenToWorld(i,o)}worldToScreen(e,n){return this.camera.worldToScreen(e,n)}setViewCenter(e,n,r){if(!Number.isFinite(e)||!Number.isFinite(n))return;const i=this.camera.getViewState(),o=Math.max(1e-6,i.zoom),s=this.camera.getViewportSize();this.setViewState({offsetX:e-s.width/(2*o),offsetY:n-s.height/(2*o)},r)}getViewCorners(){return this.camera.getViewCorners()}getInitialRotationDeg(){return this.initialRotationDeg}getViewBounds(){return en(this.camera)}resetRotation(e){const n=this.camera.getViewState();Math.abs(n.rotationDeg-this.initialRotationDeg)<1e-6||this.setViewState({rotationDeg:this.initialRotationDeg},e)}getPointSizeByZoom(e=Xe){const n=Math.max(1e-6,this.camera.getViewState().zoom),r=this.source.maxTierZoom+Math.log2(n),o=this.pointLayers.get(String(e||Xe))?.pointSizeStops??this.defaultPointSizeStops,s=jl(r,o);return F(s,In,Ol)}fitToImage(e){const n=this.canvas.getBoundingClientRect(),r=Math.max(1,n.width||1),i=Math.max(1,n.height||1),o=ti(this.source,r,i,this.minZoom,this.maxZoom,this.initialRotationDeg);this.fitZoom=o.fitZoom,this.applyZoomBounds(),this.setViewState(o.target,e)}zoomBy(e,n,r,i){const o=Ic(this.camera,this.minZoom,this.maxZoom,e,n,r);o&&this.setViewState(o,i)}zoomTo(e,n,r,i){const o=_c(this.camera,this.minZoom,this.maxZoom,e,n,r);o&&this.setViewState(o,i)}setZoomSnaps(e,n){this.zoomSnaps=ni(e,this.source.mpp),this.zoomSnapFitAsMin=!!n}setPanExtent(e){this.applyPanExtent(e)}applyPanExtent(e){typeof e=="number"&&Number.isFinite(e)?(this.panExtentX=Math.max(0,e),this.panExtentY=Math.max(0,e)):e!=null&&typeof e=="object"?(this.panExtentX=typeof e.x=="number"&&Number.isFinite(e.x)?Math.max(0,e.x):.2,this.panExtentY=typeof e.y=="number"&&Number.isFinite(e.y)?Math.max(0,e.y):.2):(this.panExtentX=.2,this.panExtentY=.2)}getZoomPivotAnimationContext(){return{camera:this.camera,viewAnimationState:this.viewAnimationState,minZoom:this.minZoom,maxZoom:this.maxZoom,cancelViewAnimation:()=>this.cancelViewAnimation(),clampViewState:()=>Vt(this.camera,this.source,this.panExtentX,this.panExtentY),onViewStateChange:e=>this.onViewStateChange?.(e),requestRender:()=>this.requestRender()}}handleSnapZoom(e,n,r){const i=this.viewAnimationState.animation,o=i?i.to.zoom:this.camera.getViewState().zoom,s=this.zoomSnaps.filter(f=>f>=this.minZoom&&f<=this.maxZoom),a=Fc(s,o,e,this.zoomSnapFitAsMin);if(!a)return!1;let l;if(a.type==="fit"){const f=this.canvas.getBoundingClientRect(),c=Math.max(1,f.width||1),h=Math.max(1,f.height||1),d=ti(this.source,c,h,this.minZoom,this.maxZoom,this.initialRotationDeg);this.fitZoom=d.fitZoom,this.applyZoomBounds(),l=d.target.zoom}else l=a.zoom;const u=Math.max(Math.abs(l)*.005,1e-8);if(i){if((i.to.zoom>i.from.zoom+u?"in":i.to.zoom<i.from.zoom-u?"out":null)===e&&Math.abs(i.to.zoom-l)<=u)return!1}else if(Math.abs(o-l)<=u)return!1;return Dc(this.getZoomPivotAnimationContext(),l,n,r,Lc),!0}render(){if(this.destroyed||this.contextLost||this.gl.isContextLost())return;const e=this.onStats?we():0;this.frameSerial+=1;const n=Cc({gl:this.gl,camera:this.camera,source:this.source,cache:this.cache,frameSerial:this.frameSerial,tileProgram:this.tileProgram,imageColorSettings:this.imageColorSettings,pointLayers:this.getPointRenderLayers(),tileScheduler:this.tileScheduler,getVisibleTiles:()=>cc(this.camera,this.source),getVisibleTilesForTier:r=>Ki(this.camera,this.source,r),getViewBounds:()=>en(this.camera),intersectsBounds:lc});if(this.onStats){const r=this.tileScheduler.getSnapshot();this.onStats({tier:n.tier,visible:n.visible,rendered:n.rendered,points:n.points,fallback:n.fallback,cache:this.cache.size,inflight:r.inflight,queued:r.queued,retries:r.retries,failed:r.failed,aborted:r.aborted,cacheHits:n.cacheHits,cacheMisses:n.cacheMisses,drawCalls:n.drawCalls,frameMs:we()-e})}}requestRender(){this.frame!==null||this.destroyed||this.contextLost||this.gl.isContextLost()||(this.frame=requestAnimationFrame(()=>{this.frame=null,this.render()}))}resize(){zl(this.canvas,this.gl,this.camera),this.requestRender()}onWebGlContextLost(e){const n=Sc({event:e,destroyed:this.destroyed,contextLost:this.contextLost,frame:this.frame,cancelViewAnimation:()=>this.cancelViewAnimation(),cancelDrag:()=>this.cancelDrag(),tileScheduler:this.tileScheduler,cache:this.cache,onContextLost:this.onContextLost});if(n.handled){this.frame=n.frame,this.contextLost=!0;for(const r of this.pointLayers.values())r.runtime={...r.runtime,pointBuffersDirty:!0}}}onWebGlContextRestored(e){if(!this.destroyed){this.contextLost=!1,this.cache.clear(),this.tileProgram=Jr(this.gl);for(const n of this.pointLayers.values())n.program=ei(this.gl),n.runtime={...n.runtime,pointBuffersDirty:!0},n.runtime.lastPointPalette&&n.runtime.lastPointPalette.length>0&&(n.runtime=jr(n.runtime,this.gl,n.program,this.contextLost,n.runtime.lastPointPalette)),n.runtime.lastPointData&&(n.runtime=Qr(n.runtime,this.gl,n.program,this.contextLost,n.runtime.lastPointData));this.resize(),this.onContextRestored?.()}}destroy(){const e=Ec({destroyed:this.destroyed,frame:this.frame,cancelViewAnimation:()=>this.cancelViewAnimation(),resizeObserver:this.resizeObserver,removeDprListener:this.removeDprListener,removeCanvasEventListeners:()=>Ul(this.canvas,this.getCanvasHandlers()),cancelDrag:()=>this.cancelDrag(),tileScheduler:this.tileScheduler,contextLost:this.contextLost,gl:this.gl,cache:this.cache,tileProgram:this.tileProgram,pointPrograms:Array.from(this.pointLayers.values(),n=>n.program)});e.didDestroy&&(this.destroyed=!0,this.frame=e.frame)}}const Nc=[];function Bc(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function kc({source:t,viewState:e,onViewStateChange:n,onStats:r,onTileError:i,onContextLost:o,onContextRestored:s,imageColorSettings:a=null,initialRotate:l=0,fitNonce:u=0,rotationResetNonce:f=0,authToken:c="",ctrlDragRotate:h=!0,minZoom:d,maxZoom:m,viewTransition:g,zoomSnaps:b,zoomSnapFitAsMin:y,panExtent:w,onPointerWorldMove:A,debugOverlay:S=!1,debugOverlayStyle:C,className:M,style:P,children:O}){const W=p.useRef(null),L=p.useRef(null),T=p.useRef(null),D=p.useRef(null),I=p.useRef(null),Y=p.useRef(null),$=p.useRef(Nc),k=p.useRef(!1),ae=p.useRef(new Set),he=p.useRef(new Set),J=p.useRef(n),ve=p.useRef(r),Ce=p.useRef(i),N=p.useRef(o),v=p.useRef(s),[z,ie]=p.useState(0),[H,ge]=p.useState(null),le=p.useRef(S);p.useEffect(()=>{J.current=n},[n]),p.useEffect(()=>{ve.current=r},[r]),p.useEffect(()=>{Ce.current=i},[i]),p.useEffect(()=>{N.current=o},[o]),p.useEffect(()=>{v.current=s},[s]),p.useEffect(()=>{le.current=S,S||ge(null)},[S]);const ne=p.useMemo(()=>({position:"relative",width:"100%",height:"100%",...P}),[P]),_e=p.useMemo(()=>({position:"absolute",top:8,left:8,zIndex:7,margin:0,padding:"8px 10px",maxWidth:"min(420px, 80%)",pointerEvents:"none",whiteSpace:"pre-wrap",lineHeight:1.35,fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:11,color:"#cde6ff",background:"rgba(6, 12, 20, 0.82)",border:"1px solid rgba(173, 216, 255, 0.28)",borderRadius:8,boxShadow:"0 8px 22px rgba(0,0,0,0.35)",...C}),[C]),ue=Bc(l),pe=p.useCallback(U=>({...U,rotationDeg:U.rotationDeg-ue}),[ue]),de=p.useCallback(U=>typeof U.rotationDeg!="number"||!Number.isFinite(U.rotationDeg)?U:{...U,rotationDeg:U.rotationDeg+ue},[ue]),re=p.useCallback(U=>{ve.current?.(U),le.current&&ge(U)},[]),oe=p.useMemo(()=>H?[`tier ${H.tier} | frame ${H.frameMs?.toFixed(2)??"-"} ms | drawCalls ${H.drawCalls??"-"}`,`tiles visible ${H.visible} | rendered ${H.rendered} | fallback ${H.fallback}`,`cache size ${H.cache} | hit ${H.cacheHits??"-"} | miss ${H.cacheMisses??"-"}`,`queue inflight ${H.inflight} | queued ${H.queued??"-"} | retries ${H.retries??"-"} | failed ${H.failed??"-"} | aborted ${H.aborted??"-"}`,`points ${H.points}`].join(`
246
+ `):"stats: waiting for first frame...",[H]),ce=p.useCallback(()=>{const U=T.current;if(!U)return;const Z=U.getContext("2d");if(!Z)return;const Q=Math.max(1,window.devicePixelRatio||1),ee=U.getBoundingClientRect(),Se=Math.max(1,Math.round(ee.width*Q)),be=Math.max(1,Math.round(ee.height*Q));(U.width!==Se||U.height!==be)&&(U.width=Se,U.height=be);const Ae=ee.width,De=ee.height;Z.setTransform(1,0,0,1,0,0),Z.clearRect(0,0,U.width,U.height),Z.setTransform(Q,0,0,Q,0,0);const x=$.current;for(let R=0;R<x.length;R+=1)Z.save(),x[R].draw(Z,Ae,De),Z.restore()},[]),q=p.useCallback(()=>{k.current||(k.current=!0,requestAnimationFrame(()=>{k.current=!1,ce()}))},[ce]),Pe=p.useCallback((U,Z,Q)=>{const ee=$.current.filter(Se=>Se.id!==U);ee.push({id:U,priority:Z,draw:Q}),ee.sort((Se,be)=>Se.priority-be.priority),$.current=ee,q()},[q]),Ee=p.useCallback(U=>{$.current=$.current.filter(Z=>Z.id!==U),q()},[q]),ye=p.useCallback((U,Z)=>{Z?ae.current.add(U):ae.current.delete(U),D.current?.setInteractionLock(ae.current.size>0)},[]),V=p.useCallback(()=>ae.current.size>0,[]),K=p.useCallback((U,Z)=>{const Q=D.current;return Q?Nn(Q.worldToScreen(U,Z)):null},[]),fe=p.useCallback((U,Z)=>{const Q=D.current;if(!Q)return null;const ee=Q.screenToWorld(U,Z);if(!Array.isArray(ee)||ee.length<2)return null;const Se=Number(ee[0]),be=Number(ee[1]);return!Number.isFinite(Se)||!Number.isFinite(be)?null:[Se,be]},[]),te=p.useCallback(U=>(he.current.add(U),()=>{he.current.delete(U)}),[]),j=p.useCallback(U=>{J.current?.(pe(U));const Z=he.current;if(Z.size>0){const Q=Array.from(Z);for(let ee=0;ee<Q.length;ee+=1)Q[ee](U)}I.current?.(),Y.current?.(),q()},[q,pe]);p.useEffect(()=>{const U=L.current;if(!U||!t)return;const Z=new Qi(U,t,{onViewStateChange:j,onStats:re,onTileError:Q=>{Ce.current?.(Q)},onContextLost:()=>{N.current?.()},onContextRestored:()=>{v.current?.()},authToken:c,imageColorSettings:a,initialRotationDeg:l,ctrlDragRotate:h,minZoom:d,maxZoom:m,viewTransition:g,zoomSnaps:b,zoomSnapFitAsMin:y,panExtent:w});return D.current=Z,ie(Q=>Q+1),e&&Z.setViewState(de(e)),Z.setInteractionLock(ae.current.size>0),()=>{Z.destroy(),D.current=null}},[t,re,h,j,ue,de]),p.useEffect(()=>{D.current?.setAuthToken(c)},[c]),p.useEffect(()=>{const U=D.current;!U||!e||U.isViewAnimating()||U.setViewState(de(e))},[e,de]),p.useEffect(()=>{D.current?.fitToImage()},[u]),p.useEffect(()=>{D.current?.resetRotation()},[f]),p.useEffect(()=>{D.current?.setZoomRange(d,m)},[d,m]),p.useEffect(()=>{D.current?.setViewTransition(g)},[g]),p.useEffect(()=>{D.current?.setZoomSnaps(b,y)},[b,y]),p.useEffect(()=>{D.current?.setPanExtent(w)},[w]),p.useEffect(()=>{D.current?.setImageColorSettings(a)},[a]),p.useEffect(()=>{const U=T.current;if(!U)return;I.current=q,q();const Z=new ResizeObserver(()=>q());return Z.observe(U),()=>{Z.disconnect(),I.current===q&&(I.current=null)}},[q]),p.useEffect(()=>tn(()=>q()),[q]);const Re=p.useMemo(()=>({source:t,rendererRef:D,rendererSerial:z,canvasRef:L,containerRef:W,drawInvalidateRef:I,overviewInvalidateRef:Y,worldToScreen:K,screenToWorld:fe,registerDrawCallback:Pe,unregisterDrawCallback:Ee,requestOverlayRedraw:q,registerViewStateListener:te,setInteractionLock:ye,isInteractionLocked:V}),[t,z,K,fe,Pe,Ee,q,te,ye,V]),X=p.useRef(A);p.useEffect(()=>{X.current=A},[A]);const Te=p.useCallback(U=>{const Z=X.current;if(!Z)return;const Q=fe(U.clientX,U.clientY),ee=!!Q&&Q[0]>=0&&Q[1]>=0&&!!t&&Q[0]<=t.width&&Q[1]<=t.height;Z({coordinate:Q,clientX:U.clientX,clientY:U.clientY,insideImage:ee})},[fe,t]),Fe=p.useCallback(()=>{X.current?.({coordinate:null,clientX:-1,clientY:-1,insideImage:!1})},[]);return Ge.jsx(ea,{value:Re,children:Ge.jsxs("div",{ref:W,className:M,style:ne,onPointerMove:A?Te:void 0,onPointerLeave:A?Fe:void 0,children:[Ge.jsx("canvas",{ref:L,className:"wsi-render-canvas",style:{position:"absolute",inset:0,zIndex:1,width:"100%",height:"100%",display:"block",touchAction:"none"}}),Ge.jsx("canvas",{ref:T,className:"wsi-overlay-canvas",style:{position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",pointerEvents:"none",touchAction:"none"}}),O,S&&Ge.jsx("pre",{"data-open-plant-debug-overlay":!0,style:_e,children:oe})]})})}function Uc(t){const e=[];for(let n=0;n<t.length;n+=1){const r=t[n],i=dt([ht(r?.coordinates)]);if(i.length===0)continue;let o=0,s=1/0,a=1/0,l=-1/0,u=-1/0;for(const f of i)o+=f.area,f.minX<s&&(s=f.minX),f.minY<a&&(a=f.minY),f.maxX>l&&(l=f.maxX),f.maxY>u&&(u=f.maxY);!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(l)||!Number.isFinite(u)||e.push({regionId:r.id??n,regionIndex:n,polygons:i,area:Math.max(1e-6,o),minX:s,minY:a,maxX:l,maxY:u})}return e}const zc=128,mn=[];function ut(t,e,n,r,i){if(i<=1||n<=e)return 0;const o=(t-e)/r;return!Number.isFinite(o)||o<=0?0:o>=i-1?i-1:Math.floor(o)}function Oc(t){if(t.length===0)return null;let e=1/0,n=1/0,r=-1/0,i=-1/0;for(const f of t)f.minX<e&&(e=f.minX),f.minY<n&&(n=f.minY),f.maxX>r&&(r=f.maxX),f.maxY>i&&(i=f.maxY);if(!Number.isFinite(e)||!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(i))return null;const o=Math.ceil(Math.sqrt(t.length*2)),s=Math.max(1,Math.min(zc,o)),a=r>e?(r-e)/s:1,l=i>n?(i-n)/s:1,u=Array.from({length:s*s},()=>[]);for(let f=0;f<t.length;f+=1){const c=t[f],h=ut(c.minX,e,r,a,s),d=ut(c.maxX,e,r,a,s),m=ut(c.minY,n,i,l,s),g=ut(c.maxY,n,i,l,s);for(let b=m;b<=g;b+=1)for(let y=h;y<=d;y+=1)u[b*s+y].push(f)}return{minX:e,minY:n,maxX:r,maxY:i,gridSize:s,cellWidth:a,cellHeight:l,buckets:u}}function Yc(t,e,n){if(!t||e<t.minX||e>t.maxX||n<t.minY||n>t.maxY)return mn;const r=ut(e,t.minX,t.maxX,t.cellWidth,t.gridSize),i=ut(n,t.minY,t.maxY,t.cellHeight,t.gridSize);return t.buckets[i*t.gridSize+r]??mn}function Xc(t,e){if(Array.isArray(e)){const n=e[t];if(typeof n=="string"&&n.length>0)return n}if(e instanceof Map){const n=e.get(t);if(typeof n=="string"&&n.length>0)return n}return String(t)}function Wc(t,e,n={}){const r=Math.max(0,Math.min(Math.floor(t?.count??0),Math.floor((t?.positions?.length??0)/2),t?.paletteIndices?.length??0,t?.fillModes instanceof Uint8Array?t.fillModes.length:Number.MAX_SAFE_INTEGER));let i=null;if(t?.drawIndices instanceof Uint32Array){const d=t.drawIndices;let m=d.length;for(let g=0;g<d.length;g+=1)d[g]<r||(m-=1);if(m===d.length)i=d;else if(m>0){const g=new Uint32Array(m);let b=0;for(let y=0;y<d.length;y+=1){const w=d[y];w>=r||(g[b]=w,b+=1)}i=g}else i=new Uint32Array(0)}const o=i?i.length:r,s=Uc(e??[]);if(!t||o===0||s.length===0)return{groups:[],inputPointCount:o,pointsInsideAnyRegion:0,unmatchedPointCount:o};const a=new Map,l=new Map,u=Oc(s);let f=0;for(let d=0;d<o;d+=1){const m=i?i[d]:d,g=t.positions[m*2],b=t.positions[m*2+1];if(!Number.isFinite(g)||!Number.isFinite(b))continue;let y=null;const w=Yc(u,g,b);if(w.length===0)continue;for(const C of w){const M=s[C];let P=!1;for(const O of M.polygons)if(ui(g,b,O)){P=!0;break}P&&(!y||M.area<y.area)&&(y=M)}if(!y)continue;f+=1;const A=t.paletteIndices[m]??0,S=a.get(y.regionIndex)??new Map;S.set(A,(S.get(A)??0)+1),a.set(y.regionIndex,S),l.set(y.regionIndex,(l.get(y.regionIndex)??0)+1)}const c=n.includeEmptyRegions??!1,h=[];for(const d of s){const m=l.get(d.regionIndex)??0;if(!c&&m<=0)continue;const g=a.get(d.regionIndex)??new Map,b=Array.from(g.entries()).map(([y,w])=>({classId:Xc(y,n.paletteIndexToClassId),paletteIndex:y,count:w})).sort((y,w)=>w.count-y.count||y.paletteIndex-w.paletteIndex);h.push({regionId:d.regionId,regionIndex:d.regionIndex,totalCount:m,classCounts:b})}return{groups:h,inputPointCount:o,pointsInsideAnyRegion:f,unmatchedPointCount:Math.max(0,o-f)}}function Vc(t){return t.replace(/^\s*SRID\s*=\s*\d+\s*;\s*/i,"")}function Gc(t){return t>="A"&&t<="Z"||t>="a"&&t<="z"}function qc(t){return t>="0"&&t<="9"}function ri(t){return t==="+"||t==="-"||t==="."||qc(t)}class Hc{constructor(e){E(this,"text");E(this,"index",0);this.text=Vc(e.trim())}parse(){if(!this.text)return null;const e=this.readWord();if(!e)return null;const n=e.toUpperCase();if(n!=="POLYGON"&&n!=="MULTIPOLYGON")return null;this.skipWhitespace();const r=this.peekWord();if(r){const s=r.toUpperCase();(s==="Z"||s==="M"||s==="ZM")&&(this.readWord(),this.skipWhitespace())}if(this.consumeWordIf("EMPTY"))return this.skipWhitespace(),this.isEof()?n==="POLYGON"?{type:"Polygon",coordinates:[]}:{type:"MultiPolygon",coordinates:[]}:null;let i;try{i=this.parseNestedList()}catch{return null}if(this.skipWhitespace(),!this.isEof())return null;if(n==="POLYGON"){const s=Ji(i);return s?{type:"Polygon",coordinates:s}:null}const o=$c(i);return o?{type:"MultiPolygon",coordinates:o}:null}isEof(){return this.index>=this.text.length}currentChar(){return this.text[this.index]??""}skipWhitespace(){for(;!this.isEof()&&/\s/.test(this.currentChar());)this.index+=1}readWord(){if(this.skipWhitespace(),this.isEof())return null;const e=this.index;for(;!this.isEof()&&Gc(this.currentChar());)this.index+=1;return this.index===e?null:this.text.slice(e,this.index)}peekWord(){const e=this.index,n=this.readWord();return this.index=e,n}consumeWordIf(e){const n=this.index,r=this.readWord();return!r||r.toUpperCase()!==e.toUpperCase()?(this.index=n,!1):!0}parseNestedList(){if(this.skipWhitespace(),this.currentChar()!=="(")throw new Error("Expected '('");this.index+=1;const e=[];for(;;){this.skipWhitespace(),this.currentChar()==="("?e.push(this.parseNestedList()):e.push(this.parseCoordinateTuple()),this.skipWhitespace();const n=this.currentChar();if(n===","){this.index+=1;continue}if(n===")"){this.index+=1;break}throw new Error("Expected ',' or ')'")}return e}parseCoordinateTuple(){this.skipWhitespace();const e=[];for(;;){this.skipWhitespace();const n=this.currentChar();if(!n||!ri(n))break;const r=this.readNumber();if(r===null)break;e.push(r),this.skipWhitespace();const i=this.currentChar();if(!i||i===","||i===")")break;if(!ri(i))throw new Error("Invalid coordinate")}if(e.length<2)throw new Error("Coordinate requires at least x y");return[e[0],e[1]]}readNumber(){if(this.skipWhitespace(),this.isEof())return null;const n=this.text.slice(this.index).match(/^[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?/);if(!n)return null;const r=Number(n[0]);return Number.isFinite(r)?(this.index+=n[0].length,r):null}}function Zc(t){return Array.isArray(t)&&t.length>=2&&typeof t[0]=="number"&&Number.isFinite(t[0])&&typeof t[1]=="number"&&Number.isFinite(t[1])}function Ji(t){if(!Array.isArray(t))return null;const e=[];for(const n of t){if(!Array.isArray(n))return null;const r=[];for(const i of n){if(!Zc(i))return null;r.push([i[0],i[1]])}e.push(r)}return e}function $c(t){if(!Array.isArray(t))return null;const e=[];for(const n of t){const r=Ji(n);if(!r)return null;e.push(r)}return e}function Kc(t){return typeof t!="string"?null:new Hc(t).parse()}exports.DEFAULT_POINT_COLOR=Fn;exports.DrawLayer=Ei;exports.DrawingLayer=ta;exports.HeatmapLayer=Na;exports.M1TileRenderer=oi;exports.OverlayLayer=ka;exports.OverviewMap=Ha;exports.PatchLayer=$a;exports.PointLayer=Sl;exports.RegionLayer=Dl;exports.TileScheduler=Hi;exports.TileViewerCanvas=Nl;exports.WsiTileRenderer=Qi;exports.WsiViewer=kc;exports.__heatmapLayerInternals=Ba;exports.buildClassPalette=zo;exports.buildPointSpatialIndexAsync=qi;exports.calcScaleLength=Bo;exports.calcScaleResolution=Dn;exports.clamp=F;exports.closeRing=ze;exports.computeRoiPointGroups=Wc;exports.createCircle=Sn;exports.createRectangle=Kt;exports.createSpatialIndex=Ai;exports.filterPointDataByPolygons=Rt;exports.filterPointDataByPolygonsHybrid=Xi;exports.filterPointDataByPolygonsInWorker=Vi;exports.filterPointIndicesByPolygons=zi;exports.filterPointIndicesByPolygonsInWorker=ol;exports.getWebGpuCapabilities=nl;exports.hexToRgba=fi;exports.isSameViewState=wn;exports.lookupCellIndex=Gi;exports.normalizeImageClasses=Ua;exports.normalizeImageInfo=Oa;exports.parseWkt=Kc;exports.prefilterPointsByBoundsWebGpu=Yi;exports.terminatePointHitIndexWorker=gl;exports.terminateRoiClipWorker=il;exports.toBearerToken=ko;exports.toRoiGeometry=ht;exports.toTileUrl=Gn;exports.useViewerContext=st;
247
247
  //# sourceMappingURL=index.cjs.map