open-plant 1.4.13 → 1.4.15

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 $i=Object.defineProperty;var Ki=(t,e,n)=>e in t?$i(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var S=(t,e,n)=>Ki(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 Gn(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=Gn(t,t.VERTEX_SHADER,e),i=Gn(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 on(t){return t*Math.PI/180}class Jr{constructor(){S(this,"viewportWidth",1);S(this,"viewportHeight",1);S(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=on(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=on(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=on(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 Ji=`#version 300 es
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 Ge=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 Le(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,w=-1-this.viewState.offsetX*y,A=1-this.viewState.offsetY*b;return new Float32Array([y,0,0,0,b,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 eo=`#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
- `,Qi=`#version 300 es
21
+ `,to=`#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 Qr{constructor(e){S(this,"canvas");S(this,"gl");S(this,"camera",new Jr);S(this,"imageWidth");S(this,"imageHeight");S(this,"clearColor");S(this,"program");S(this,"vao");S(this,"quadBuffer");S(this,"uCameraLocation");S(this,"uBoundsLocation");S(this,"uTextureLocation");S(this,"resizeObserver");S(this,"tiles",[]);S(this,"frameId",null);S(this,"loadVersion",0);S(this,"destroyed",!1);S(this,"fitted",!1);S(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,Ji,Qi);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 eo(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 sn(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 qn(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 to(t,e,n){return e===null?t:(t===null||(e=tt(t.key,e,n),e.left=t),e)}function mn(t,e,n,r,i){if(t){r(`${e}${n?"└── ":"├── "}${i(t)}
33
- `);const o=e+(n?" ":"│ ");t.left&&mn(t.left,o,!1,r,i),t.right&&mn(t.right,o,!0,r,i)}}class In{constructor(e=eo){this._root=null,this._size=0,this._comparator=e}insert(e,n){return this._size++,this._root=sn(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 ro(this._root)}load(e,n=[],r=!1){let i=e.length;const o=this._comparator;if(r&&yn(e,n,0,i-1,o),this._root===null)this._root=gn(e,n,0,i),this._size=i;else{const s=io(this.toList(),no(e,n),o);i=this._size+i,this._root=pn({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 mn(this._root,"",!0,r=>n.push(r),e),n.join("")}update(e,n,r){const i=this._comparator;let{left:o,right:s}=qn(e,this._root,i);i(e,n)<0?s=sn(n,r,s,i):o=sn(n,r,o,i),this._root=to(o,s,i)}split(e){return qn(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 gn(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=gn(t,e,n,o),l.right=gn(t,e,o+1,r),l}return null}function no(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 ro(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 pn(t,e,n){const r=n-e;if(r>0){const i=e+Math.floor(r/2),o=pn(t,e,i),s=t.head;return s.left=o,t.head=t.head.next,s.right=pn(t,i+1,n),s}return null}function io(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 yn(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}yn(t,e,n,a,i),yn(t,e,a+1,r,i)}const Je=11102230246251565e-32,De=134217729,oo=(3+8*Je)*Je;function an(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 so(t,e){let n=e[0];for(let r=1;r<t;r++)n+=e[r];return n}function Mt(t){return new Float64Array(t)}const ao=(3+16*Je)*Je,lo=(2+12*Je)*Je,co=(9+64*Je)*Je*Je,lt=Mt(4),Hn=Mt(8),Zn=Mt(12),$n=Mt(16),ke=Mt(4);function uo(t,e,n,r,i,o,s){let a,l,u,f,c,h,d,m,g,y,b,x,A,E,M,C,T,k;const X=t-i,N=n-i,P=e-o,z=r-o;E=X*z,h=De*X,d=h-(h-X),m=X-d,h=De*z,g=h-(h-z),y=z-g,M=m*y-(E-d*g-m*g-d*y),C=P*N,h=De*P,d=h-(h-P),m=P-d,h=De*N,g=h-(h-N),y=N-g,T=m*y-(C-d*g-m*g-d*y),b=M-T,c=M-b,lt[0]=M-(b+c)+(c-T),x=E+b,c=x-E,A=E-(x-c)+(b-c),b=A-C,c=A-b,lt[1]=A-(b+c)+(c-C),k=x+b,c=k-x,lt[2]=x-(k-c)+(b-c),lt[3]=k;let F=so(4,lt),O=lo*s;if(F>=O||-F>=O||(c=t-X,a=t-(X+c)+(c-i),c=n-N,u=n-(N+c)+(c-i),c=e-P,l=e-(P+c)+(c-o),c=r-z,f=r-(z+c)+(c-o),a===0&&l===0&&u===0&&f===0)||(O=co*s+oo*Math.abs(F),F+=X*f+z*a-(P*u+N*l),F>=O||-F>=O))return F;E=a*z,h=De*a,d=h-(h-a),m=a-d,h=De*z,g=h-(h-z),y=z-g,M=m*y-(E-d*g-m*g-d*y),C=l*N,h=De*l,d=h-(h-l),m=l-d,h=De*N,g=h-(h-N),y=N-g,T=m*y-(C-d*g-m*g-d*y),b=M-T,c=M-b,ke[0]=M-(b+c)+(c-T),x=E+b,c=x-E,A=E-(x-c)+(b-c),b=A-C,c=A-b,ke[1]=A-(b+c)+(c-C),k=x+b,c=k-x,ke[2]=x-(k-c)+(b-c),ke[3]=k;const $=an(4,lt,4,ke,Hn);E=X*f,h=De*X,d=h-(h-X),m=X-d,h=De*f,g=h-(h-f),y=f-g,M=m*y-(E-d*g-m*g-d*y),C=P*u,h=De*P,d=h-(h-P),m=P-d,h=De*u,g=h-(h-u),y=u-g,T=m*y-(C-d*g-m*g-d*y),b=M-T,c=M-b,ke[0]=M-(b+c)+(c-T),x=E+b,c=x-E,A=E-(x-c)+(b-c),b=A-C,c=A-b,ke[1]=A-(b+c)+(c-C),k=x+b,c=k-x,ke[2]=x-(k-c)+(b-c),ke[3]=k;const W=an($,Hn,4,ke,Zn);E=a*f,h=De*a,d=h-(h-a),m=a-d,h=De*f,g=h-(h-f),y=f-g,M=m*y-(E-d*g-m*g-d*y),C=l*u,h=De*l,d=h-(h-l),m=l-d,h=De*u,g=h-(h-u),y=u-g,T=m*y-(C-d*g-m*g-d*y),b=M-T,c=M-b,ke[0]=M-(b+c)+(c-T),x=E+b,c=x-E,A=E-(x-c)+(b-c),b=A-C,c=A-b,ke[1]=A-(b+c)+(c-C),k=x+b,c=k-x,ke[2]=x-(k-c)+(b-c),ke[3]=k;const J=an(W,Zn,4,ke,$n);return $n[J-1]}function fo(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)>=ao*u?l:-uo(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,bn=(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 ho=nt*nt,Kn=(t,e)=>{if(-nt<t&&t<nt&&-nt<e&&e<nt)return 0;const n=t-e;return n*n<ho*t*e?0:t<e?-1:1};class mo{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 In,this.round(0)}round(e){const n=this.tree.add(e),r=this.tree.prev(n);if(r!==null&&Kn(n.key,r.key)===0)return this.tree.remove(e),r.key;const i=this.tree.next(n);return i!==null&&Kn(n.key,i.key)===0?(this.tree.remove(e),i.key):e}}const xt=new mo,Ot=(t,e)=>t.x*e.y-t.y*e.x,ei=(t,e)=>t.x*e.x+t.y*e.y,Jn=(t,e,n)=>{const r=fo(t.x,t.y,e.x,e.y,n.x,n.y);return r>0?-1:r<0?1:0},Gt=t=>Math.sqrt(ei(t,t)),go=(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)},po=(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 ei(i,r)/Gt(i)/Gt(r)},Qn=(t,e,n)=>e.y===0?null:{x:t.x+e.x/e.y*(n-t.y),y:n},er=(t,e,n)=>e.x===0?null:{x:n,y:t.y+e.y/e.x*(n-t.x)},yo=(t,e,n,r)=>{if(e.x===0)return er(n,r,t.x);if(r.x===0)return er(t,e,n.x);if(e.y===0)return Qn(n,r,t.y);if(r.y===0)return Qn(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:go(this.point,e.point,o.point),cosine:po(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 bo=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=++bo,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=bn(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=yo(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 tr{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 xo{constructor(e,n){if(!Array.isArray(e))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");this.exteriorRing=new tr(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 tr(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 nr{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 xo(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 rr{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 wo{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 rr(o));else{const s=o.enclosingRing();s.poly||n.push(new rr(s)),s.poly.addInterior(o)}}return n}}class So{constructor(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:rt.compare;this.queue=e,this.tree=new In(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 ir=typeof process<"u"&&process.env.POLYGON_CLIPPING_MAX_QUEUE_SIZE||1e6,Eo=typeof process<"u"&&process.env.POLYGON_CLIPPING_MAX_SWEEPLINE_SEGMENTS||1e6;class Ro{run(e,n,r){Ze.type=e,xt.reset();const i=[new nr(n,!0)];for(let c=0,h=r.length;c<h;c++)i.push(new nr(r[c],!1));if(Ze.numMultiPolys=i.length,Ze.type==="difference"){const c=i[0];let h=1;for(;h<i.length;)bn(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(bn(d.bbox,i[m].bbox)===null)return[]}const o=new In(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>ir)throw new Error("Infinite loop when putting segment endpoints in a priority queue (queue size too big).")}const s=new So(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>ir)throw new Error("Infinite loop when passing sweep line over endpoints (queue size too big).");if(s.segments.length>Eo)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 wo(u).getGeom()}}const Ze=new Ro,Ao=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)},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("intersection",t,n)},Co=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)},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("difference",t,n)};var To={union:Ao,intersection:Mo,xor:Co,difference:Po};function ht(t){return t==null?null:ti(t)||ni(t)||vo(t)?t:null}function or(t){return typeof t=="number"&&Number.isFinite(t)}function Yt(t){return Array.isArray(t)&&t.length>=2&&or(t[0])&&or(t[1])}function ti(t){return Array.isArray(t)&&t.length>0&&t.every(e=>Yt(e))}function ni(t){return Array.isArray(t)&&t.length>0&&t.every(e=>ti(e))}function vo(t){return Array.isArray(t)&&t.length>0&&t.every(e=>ni(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 ln(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 ri(t){if(!Array.isArray(t)||t.length===0)return[];const e=t[0];if(Yt(e)){const i=ln([t]);return i.length>0?[i]:[]}if(!Array.isArray(e)||e.length===0)return[];const n=e[0];if(Yt(n)){const i=ln(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=ln(i);o.length>0&&r.push(o)}return r}function sr(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=ri(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 ii(t,e,n){if(t<n.minX||t>n.maxX||e<n.minY||e>n.maxY||!sr(t,e,n.outer))return!1;for(const r of n.holes)if(sr(t,e,r))return!1;return!0}function St(t,e,n){for(const r of n)if(ii(t,e,r))return!0;return!1}const _n=[160,160,160,255];function _(t,e,n){return Math.max(e,Math.min(n,t))}function Ln(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 Io(t,e,n){let i=100*Ln(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 ye(){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 xn(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 _o(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 oi(t){const n=String(t??"").trim().match(/^#?([0-9a-fA-F]{6})$/);if(!n)return[..._n];const r=Number.parseInt(n[1],16);return[r>>16&255,r>>8&255,r&255,255]}function Lo(t){const e=String(t?.classId??"").trim();return e||String(t?.className??"").trim()}function Fo(t){const e=[[..._n]],n=new Map;for(const i of t??[]){const o=Lo(i);!o||n.has(o)||(n.set(o,e.length),e.push(oi(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 Do=[6,4,2],No=64,Bo=.04,ko=1,Uo=4,Ht=1e-6,zo=.1;function Oo(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 ar(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 Yo(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 lr(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 vt(t,e){return Ye(e?t.map(([n,r])=>[_(n,e[0],e[2]),_(r,e[1],e[3])]):t)}function cr(t,e){return Number.isFinite(t)?Number(t.toFixed(e)):t}function Wo(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=cr(Number(r[0]),e),o=cr(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 Xo(t,e){if(!Array.isArray(t)||t.length===0)return[];const n=t.map(r=>Wo(r,e)).filter(r=>r.length>=4);return n.length>0?n:[]}function Vo(t,e){const n=t.map(i=>Xo(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=To.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 Go(t){if(t.length===0)return null;for(const e of Do){const n=Vo(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 Ho(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 Zo(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 $o(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=_(((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 Ko(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=$o(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=Ko(r,e);return i.length<3?n:Ye(i)}function Jo(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 Qo(t,e){const n=Oo(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||No));if(n.length===1)return vt(ar(n[0],r,i),e.clipBounds);const o=[],s=Math.max(Ht,r*zo);for(let h=0;h<n.length;h+=1){const d=n[h],m=ar(d,r,i);if(m.length>=4&&o.push([m]),h===0)continue;const g=Yo(n[h-1],d,r,s);g.length>=4&&o.push([g])}const a=Go(o),l=a?Ho(a):[];if(!l.length)return vt(lr(n,r),e.clipBounds);const u=typeof e.simplifyTolerance=="number"&&Number.isFinite(e.simplifyTolerance)?Math.max(0,e.simplifyTolerance):Math.max(.25,r*Bo),f=typeof e.smoothingPasses=="number"&&Number.isFinite(e.smoothingPasses)?Math.round(_(e.smoothingPasses,0,Uo)):ko,c=jo(Jo(Zo(l,1e-9),f),u);return c.length<4?vt(lr(n,r),e.clipBounds):vt(c,e.clipBounds)}const ot=[],ur=[],Ke={color:"#ff4d4f",width:2,lineDash:ot,lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},si={color:"#4cc9f0",width:2,lineDash:[10,8],lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},ai="rgba(23, 23, 25, 0.1)",li=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},fr={x:16,y:-24},es=20,hr=1e-6,dr="transparent",ts=3,ns=2,ci=96,rs=1,mr=1e3,ui=2,fi=2,is=4096,os=.2,ss=1.12,as=.89,ls=32,cs="#000000",us=.1,fs="#FFCF00",hs="#FF0000",ds=1.5,gr=[2,2],ms=1,gs=.25,ps=4,ys=1,bs=0,xs=4,ws=1.5;function Zt(t,e,n){return[_(t[0],0,e),_(t[1],0,n)]}function Fn(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=Fn;function Ue(t){return Ye(t)}function Wt(t){return Math.abs(wt(Ue(t)))}function pr(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 Ne(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 Dn(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?Dn({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 yr(t){return typeof t=="number"&&Number.isFinite(t)}function Ss(t){return Array.isArray(t)&&t.length>=2&&yr(t[0])&&yr(t[1])}function Es(t){return Array.isArray(t)&&t.length>=2&&t.every(e=>Ss(e))}function hi(t,e){if(!(!Array.isArray(t)||t.length===0)){if(Es(t)){e.push(t.map(([n,r])=>[n,r]));return}for(const n of t)hi(n,e)}}function br(t,e){const n=[];hi(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 Rs(t,e){return typeof t!="number"||!Number.isFinite(t)?e:_(t,0,1)}function di(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 As(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 wn(t,e,n=ci){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=ri(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 Ms(t){if(!Array.isArray(t))return gr;const e=t.filter(n=>Number.isFinite(n)&&n>=0);return e.length>0?e:gr}function Cs(t){return typeof t!="number"||!Number.isFinite(t)?ms:_(t,gs,ps)}function Ps(t){return typeof t!="number"||!Number.isFinite(t)?ys:Math.round(_(t,bs,xs))}function Ts(t){const e=yt(t?.radius,ls),n=yt(t?.cursorLineWidth,ds),r=Cs(t?.edgeDetail),i=Ps(t?.edgeSmoothing);return{radius:e,edgeDetail:r,edgeSmoothing:i,clickSelectRoi:t?.clickSelectRoi===!0,fillColor:t?.fillColor||cs,fillOpacity:Rs(t?.fillOpacity,us),cursorColor:t?.cursorColor||fs,cursorActiveColor:t?.cursorActiveColor||hs,cursorLineWidth:n,cursorLineDash:Ms(t?.cursorLineDash)}}function vs(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 Is(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 _s=.58,Ls=4096,Fs=.5;let It=null;const _t=new Map;function Ds(){if(It)return It;if(typeof document>"u")return null;const e=document.createElement("canvas").getContext("2d");return e?(It=e,It):null}function Nn(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*_s,o=Ds();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>Ls&&_t.clear(),_t.set(n,s),s}function Ns(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)>Fs||(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 Bn(t,e="top-center"){let n=null;for(const r of t){const i=Ns(r.outer,e);i&&(!n||i[1]<n[1]||i[1]===n[1]&&i[0]<n[0])&&(n=i)}return n}function kn(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 Un(t,e){return e?kn({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 zn(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<=hr||!Number.isFinite(e))return 0;let s=o;r!=null&&Number.isFinite(r)&&(s=_(r,i,o));const a=Math.max(hr,Math.abs(s)*1e-9);return e>=s-a?es:0}function Bs(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 ks(t){const e=typeof t?.x=="number"&&Number.isFinite(t.x)?t.x:fr.x,n=typeof t?.y=="number"&&Number.isFinite(t.y)?t.y:fr.y;return{x:e,y:n}}function Us(t){return Number.isFinite(t)?`${Math.max(0,t).toFixed(3)} mm²`:"0.000 mm²"}function zs(t){const e=typeof t?.format=="function"?t.format:Us,n=ks(t?.cursorOffset);return{enabled:t?.enabled===!0,format:e,style:Bs(t?.style),cursorOffsetX:n.x,cursorOffsetY:n.y}}function mi(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=Nn(a,o)+o.paddingX*2,f=o.fontSize+o.paddingY*2,c=n[0],h=n[1]-o.offsetY,d=s?_(c,u*.5+1,r-u*.5-1):c,m=s?_(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,di(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 Os(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=Nn(l,o)+o.paddingX*2,c=o.fontSize+o.paddingY*2,h=_(n[0]+s,f*.5+1,r-f*.5-1),d=_(n[1]+a,c*.5+1,i-c*.5-1),m=h-f*.5,g=d-c*.5;t.fillStyle=o.backgroundColor,di(t,m,g,f,c,o.borderRadius),t.fill(),t.fillStyle=o.textColor,t.fillText(l,h,d+.5),t.restore()}function Ys(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 gi(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??As(u.coordinates),c=br(u.coordinates,f);if(u.invertedFill?.fillColor){const d=[],m=br(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}),Ys(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||Ne(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 Ws(t){return{rectangleAreaMm2:yt(t?.rectangleAreaMm2,ui),circleAreaMm2:yt(t?.circleAreaMm2,fi),rectanglePixelSize:yt(t?.rectanglePixelSize,is)}}const xr=1e3;function Xs(t){return t*xr*xr}function wr(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 Vs(t,e,n=ci){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 Gs(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 wr(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"?ui:r.rectangleAreaMm2:(e==="stamp-circle"||e==="stamp-circle-2mm2"||e==="stamp-circle-hpf-0.2mm2")&&(l=e==="stamp-circle-hpf-0.2mm2"?os:e==="stamp-circle-2mm2"?fi:r.circleAreaMm2),!Number.isFinite(l)||l<=0)return[];const u=Xs(l);let f=[];if(e==="stamp-rectangle"||e==="stamp-rectangle-2mm2"){const c=s(Math.sqrt(u)*.5);f=wr(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=Vs(n,c)}return f.length?f.map(c=>Zt(c,i,o)):[]}function qs(t){return{color:ai,width:li,lineDash:ot,lineJoin:t.lineJoin,lineCap:t.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function Hs(t){if(typeof t!="string")return dr;const e=t.trim();return e.length>0?e:dr}function Sr(t){return Array.isArray(t)&&t.length>=4&&Wt(t)>rs}function pi({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:E,resolveRegionStrokeStyle:M,resolveRegionLabelStyle:C,overlayShapes:T,hoveredRegionId:k=null,activeRegionId:X=null,regionLabelStyle:N,drawAreaTooltip:P,autoLiftRegionLabelAtMaxZoom:z=!1,regionLabelAnchor:F="top-center",clampRegionLabelToViewport:O=!0,regionLabelAutoLiftOffsetPx:$,invalidateRef:W,className:J,style:he}){const K=p.useRef(null),Pe=p.useRef(!1),Ae=p.useRef(new Map),we=p.useRef(t),v=p.useRef({isDrawing:!1,pointerId:null,start:null,current:null,cursor:null,cursorScreen:null,points:[],screenPoints:[],stampCenter:null}),I=c??t!=="cursor",U=p.useMemo(()=>d&&d.length>0?d:!g||g.length===0?ur:g.map((w,R)=>({id:R,coordinates:w})),[d,g]),oe=p.useMemo(()=>m??ur,[m]),j=p.useMemo(()=>{const w=[];for(let R=0;R<U.length;R+=1){const D=U[R],B=jt(D.coordinates);B.length!==0&&w.push({region:D,regionIndex:R,regionKey:D.id??R,polygons:B})}return w},[U]),ue=p.useMemo(()=>{const w=[];for(let R=0;R<oe.length;R+=1){const D=oe[R],B=jt(D.coordinates);B.length!==0&&w.push({region:D,regionIndex:R,regionKey:D.id??R,polygons:B})}return w},[oe]),ee=p.useMemo(()=>Dn(b),[b]),de=p.useMemo(()=>je(ee,x),[ee,x]),se=p.useMemo(()=>je(ee,A),[ee,A]),pe=p.useMemo(()=>je(si,E),[E]),Q=p.useMemo(()=>Hs(y),[y]),ae=p.useMemo(()=>kn(N),[N]),fe=p.useMemo(()=>zs(P),[P]),Ee=p.useMemo(()=>Ws(o),[o]),te=p.useMemo(()=>Ts(s),[s]),ve=p.useMemo(()=>({position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",touchAction:"none",pointerEvents:I?"auto":"none",cursor:I?t==="brush"?"none":"crosshair":"default",...he}),[I,t,he]),be=p.useCallback(()=>{const w=K.current;if(!w)return;const R=w.getBoundingClientRect(),D=Math.max(1,window.devicePixelRatio||1),B=Math.max(1,Math.round(R.width*D)),H=Math.max(1,Math.round(R.height*D));(w.width!==B||w.height!==H)&&(w.width=B,w.height=H)},[]),me=p.useCallback(w=>{const R=a.current;if(!R||w.length===0)return[];const D=new Array(w.length);for(let B=0;B<w.length;B+=1){const H=qe(R.worldToScreen(w[B][0],w[B][1]));if(!H)return[];D[B]=H}return D},[a]),V=p.useCallback(w=>{const R=a.current,D=K.current;if(!R||!D)return null;const B=D.getBoundingClientRect(),H=qe(R.screenToWorld(B.left+w[0],B.top+w[1]));return H?Zt(H,e,n):null},[a,e,n]),Z=p.useCallback(()=>{const w=a.current,R=w?.getViewState?.().rotationDeg??0;if(!(Math.abs(R%360)<.01||!w))return{worldToScreen:(D,B)=>qe(w.worldToScreen(D,B)),screenToWorld:V}},[a,V]),re=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,B=a.current?.getViewState?.().zoom,H=typeof B=="number"&&Number.isFinite(B)&&B>0?B:1,xe=D+Math.log2(H),le=Math.max(1e-9,Ln(R,D,xe));return w/le/H},[r,i,a]),ie=p.useCallback((w,R)=>Gs({stampTool:w,center:R,resolvedStampOptions:Ee,imageWidth:e,imageHeight:n,micronsToWorldPixels:re,getRectangleProjection:Z}),[re,e,n,Ee,Z]),Se=p.useCallback(()=>{const w=v.current;return Lt(t)?ie(t,w.stampCenter):t==="brush"?[]:w.isDrawing?t==="freehand"?w.points:t==="rectangle"?Kt(w.start,w.current,Z()):t==="circular"?wn(w.start,w.current):[]:[]},[t,ie,Z]),Y=p.useCallback(()=>{be();const w=K.current;if(!w)return;const R=w.getContext("2d");if(!R)return;const D=Math.max(1,window.devicePixelRatio||1),B=w.width/D,H=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),j.length>0)for(const le of j){const{region:ge,polygons:Re,regionIndex:Te,regionKey:ze}=le,Ve=$t(X,ze)?"active":$t(k,ze)?"hover":"default";let Qe=Ve==="active"?se:Ve==="hover"?de:ee;if(M){const Tt=M({region:ge,regionId:ze,regionIndex:Te,state:Ve});Qe=je(Qe,Tt||void 0)}const Pt=Ve==="default"?null:qs(Qe);for(const Tt of Re){const nn=me(Tt.outer);nn.length>=4&&(Pt&&Ne(R,nn,Pt,!0,!1),Ne(R,nn,Qe,!0,!1));for(const Zi of Tt.holes){const rn=me(Zi);rn.length>=4&&(Pt&&Ne(R,rn,Pt,!0,!1),Ne(R,rn,Qe,!0,!1))}}}if(ue.length>0)for(const le of ue)for(const ge of le.polygons){const Re=me(ge.outer);Re.length>=4&&Ne(R,Re,pe,!0,!1);for(const Te of ge.holes){const ze=me(Te);ze.length>=4&&Ne(R,ze,pe,!0,!1)}}if(Array.isArray(T)&&T.length>0){const le=me(Ue([[0,0],[e,0],[e,n],[0,n]]));gi({ctx:R,overlayShapes:T,imageOuterRing:le,worldToScreenPoints:me,baseStrokeStyle:ee,onInvertedFillDebug:globalThis.__OPEN_PLANT_DEBUG_OVERLAY__?ge=>{const Re=String(ge.id),Te=`${ge.outerRingPoints}|${ge.sourceRingCount}|${ge.holeRingCount}|${ge.fillColor}`;Ae.current.get(Re)!==Te&&(Ae.current.set(Re,Te),console.debug("[open-plant] invertedFill",ge))}:void 0})}const xe=Se();if(I){if(t==="brush")vs(R,v.current,te),Is(R,v.current,a.current,te);else if(xe.length>0)if(t==="freehand"){const le=me(xe);le.length>=2&&Ne(R,le,ee,!1,!1),le.length>=3&&Ne(R,me(Ue(xe)),ee,!0,!0,Q)}else{const le=me(xe);le.length>=4&&Ne(R,le,ee,!0,!0,Q)}}if(j.length>0){const le=Math.max(1e-6,a.current?.getViewState?.().zoom??1),ge=typeof $=="number"&&Number.isFinite($)?Math.max(0,$):zn(z,le,a.current?.getZoomRange?.(),a.current?.getRegionLabelAutoLiftCapZoom?.());for(const Re of j){if(!Re.region.label)continue;const Te=Bn(Re.polygons,F);if(!Te)continue;const ze=qe(a.current?.worldToScreen(Te[0],Te[1])??[]);if(!ze)continue;let Ve=Un(ae,C?.({region:Re.region,regionId:Re.regionKey,regionIndex:Re.regionIndex,zoom:le}));ge>0&&(Ve={...Ve,offsetY:Ve.offsetY+ge}),mi(R,Re.region.label,ze,B,H,Ve,O)}}if(fe.enabled&&I&&(t==="freehand"||t==="rectangle"||t==="circular")){const le=v.current;if(le.isDrawing){const ge=t==="freehand"?Ue(xe):xe;if(ge.length>=4){const Re=Wt(ge),Te=typeof r=="number"&&Number.isFinite(r)&&r>0?r:0,ze=Te>0?Re*Te*Te/(mr*mr):0,Ve=fe.format(ze),Qe=le.cursorScreen??(le.current?qe(a.current?.worldToScreen(le.current[0],le.current[1])??[]):null);Qe&&Os(R,Ve,Qe,B,H,fe.style,fe.cursorOffsetX,fe.cursorOffsetY)}}}},[I,t,Se,be,me,e,n,a,j,T,k,X,ee,de,se,Q,ue,pe,M,C,ae,fe,z,F,O,$,r,te]),L=p.useCallback(()=>{Pe.current||(Pe.current=!0,requestAnimationFrame(()=>{Pe.current=!1,Y()}))},[Y]),G=p.useCallback((w=!1)=>{const R=v.current,D=K.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)},[]),q=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]),ne=p.useCallback(w=>{const R=K.current;if(!R)return null;const D=R.getBoundingClientRect(),B=_(w.clientX-D.left,0,D.width),H=_(w.clientY-D.top,0,D.height);return!Number.isFinite(B)||!Number.isFinite(H)?null:[B,H]},[]),ce=p.useCallback(()=>{const w=v.current;if(!w.isDrawing){G(!0),L();return}let R=[];if(t==="freehand")w.points.length>=ts&&(R=Ue(w.points));else if(t==="rectangle")R=Kt(w.start,w.current,Z());else if(t==="circular")R=wn(w.start,w.current);else if(t==="brush"){const D=w.points[w.points.length-1]??w.current??w.start;if(te.clickSelectRoi&&D&&w.points.length<=1&&l?.(D)){G(!0),L();return}const B=Math.max(.25,te.edgeDetail),H=w.screenPoints.length>0?w.screenPoints:me(w.points),xe=Math.max(.5,te.radius*.04/B),le=Qo(H,{radius:te.radius,circleSides:Math.max(16,Math.round(32*B)),simplifyTolerance:xe,smoothingPasses:te.edgeSmoothing}),ge=[];for(const Re of le){const Te=V(Re);Te&&ge.push(Te)}R=Ue(ge)}(t==="freehand"||t==="rectangle"||t==="circular"||t==="brush")&&Sr(R)&&u&&u({tool:t,intent:t==="brush"?"brush":"roi",coordinates:R,bbox:pr(R),areaPx:Wt(R)}),G(!0),L()},[t,u,G,L,me,V,Z,te.radius,te.edgeDetail,te.edgeSmoothing,te.clickSelectRoi,l]),Be=p.useCallback((w,R)=>{const D=ie(w,R);if(!Sr(D))return;const B=w==="stamp-rectangle-4096px"?"patch":"roi",H={tool:w,intent:B,coordinates:D,bbox:pr(D),areaPx:Wt(D)};u?.(H),B==="patch"&&f&&f(H)},[ie,u,f]),Me=p.useCallback((w,R,D)=>{const B=Math.max(ws,te.radius*.1),H=B*B,xe=w.screenPoints[w.screenPoints.length-1];if(!xe){w.points.push(R),w.screenPoints.push(D),w.current=R;return}const le=D[0]-xe[0],ge=D[1]-xe[1];le*le+ge*ge>=H?(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},[te.radius]),Ce=p.useCallback(w=>{if(!I||t==="cursor"||w.button!==0)return;const R=q(w);if(!R)return;const D=ne(w);if(!D)return;if(w.preventDefault(),w.stopPropagation(),Lt(t)){const xe=v.current;xe.stampCenter=R,Be(t,R),L();return}const B=K.current;B&&B.setPointerCapture(w.pointerId);const H=v.current;H.isDrawing=!0,H.pointerId=w.pointerId,H.start=R,H.current=R,H.cursor=R,H.cursorScreen=D,H.points=t==="freehand"||t==="brush"?[R]:[],H.screenPoints=t==="brush"?[D]:[],L()},[I,t,q,ne,Be,L]),_e=p.useCallback(w=>{if(!I||t==="cursor")return;const R=q(w);if(!R)return;const D=ne(w);if(!D)return;const B=v.current;if(B.cursor=R,B.cursorScreen=D,Lt(t)){B.stampCenter=R,w.preventDefault(),w.stopPropagation(),L();return}if(t==="brush"){if(!B.isDrawing||B.pointerId!==w.pointerId){L();return}w.preventDefault(),w.stopPropagation(),Me(B,R,D),L();return}if(!(!B.isDrawing||B.pointerId!==w.pointerId)){if(w.preventDefault(),w.stopPropagation(),t==="freehand"){const H=a.current,xe=Math.max(1e-6,H?.getViewState?.().zoom??1),le=ns/xe,ge=le*le,Re=B.points[B.points.length-1];if(!Re)B.points.push(R);else{const Te=R[0]-Re[0],ze=R[1]-Re[1];Te*Te+ze*ze>=ge&&B.points.push(R)}}else B.current=R;L()}},[I,t,q,ne,L,a,Me]),Le=p.useCallback(w=>{const R=v.current;if(!R.isDrawing||R.pointerId!==w.pointerId)return;w.preventDefault(),w.stopPropagation();const D=q(w),B=ne(w);D&&(R.cursor=D,B&&(R.cursorScreen=B),t==="brush"?B&&Me(R,D,B):R.current=D);const H=K.current;H&&H.hasPointerCapture(w.pointerId)&&H.releasePointerCapture(w.pointerId),ce()},[ce,q,ne,t,Me]),Ie=p.useCallback(()=>{const w=v.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&&L()},[t,L]);return p.useEffect(()=>{be(),L();const w=K.current;if(!w)return;const R=new ResizeObserver(()=>{be(),L()});return R.observe(w),()=>{R.disconnect()}},[be,L]),p.useEffect(()=>{I||G(),L()},[I,L,G]),p.useEffect(()=>{we.current!==t&&(we.current=t,G(),L())},[t,G,L]),p.useEffect(()=>{L()},[h,U,T,L]),p.useEffect(()=>{if(W)return W.current=L,()=>{W.current===L&&(W.current=null)}},[W,L]),p.useEffect(()=>{if(!I)return;const w=R=>{R.key==="Escape"&&(G(),L())};return window.addEventListener("keydown",w),()=>{window.removeEventListener("keydown",w)}},[I,G,L]),He.jsx("canvas",{ref:K,className:J,style:ve,onPointerDown:Ce,onPointerMove:_e,onPointerUp:Le,onPointerCancel:Le,onPointerLeave:Ie,onContextMenu:w=>{I&&w.preventDefault()},onWheel:w=>{if(!I)return;const R=K.current,D=a.current;if(!R||typeof D?.zoomBy!="function")return;w.preventDefault(),w.stopPropagation();const B=R.getBoundingClientRect(),H=w.clientX-B.left,xe=w.clientY-B.top;D.zoomBy(w.deltaY<0?ss:as,H,xe),L()}})}const yi=p.createContext(null),Zs=yi.Provider;function at(){const t=p.useContext(yi);if(!t)throw new Error("useViewerContext must be used within a <WsiViewer>");return t}function $s({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(pi,{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 Er(t,e,n,r){return[Math.min(t,n),Math.min(e,r),Math.max(t,n),Math.max(e,r)]}function Rr(t,e){return!(t[2]<e[0]||t[0]>e[2]||t[3]<e[1]||t[1]>e[3])}class Ks{constructor(e=16){S(this,"targetNodeSize");S(this,"items",[]);S(this,"globalBounds",[0,0,0,0]);S(this,"gridSize",1);S(this,"cellWidth",1);S(this,"cellHeight",1);S(this,"buckets",[]);S(this,"visited",new Uint32Array(0));S(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=Er(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=Er(e[0],e[1],e[2],e[3]);if(!Rr(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];Rr(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 bi(t){return new Ks(t)}const js=`#version 300 es
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=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 no(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 Hn(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 ro(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 _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 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 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 rt(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 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 oo(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 so(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,ao=(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 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*je)*je,uo=(2+12*je)*je,fo=(9+64*je)*je*je,lt=Ct(4),Zn=Ct(8),$n=Ct(12),Kn=Ct(16),Ue=Ct(4);function ho(t,e,n,r,i,o,s){let a,l,u,f,c,h,d,m,g,y,b,w,A,S,C,M,P,U;const Y=t-i,N=n-i,v=e-o,B=r-o;S=Y*B,h=Be*Y,d=h-(h-Y),m=Y-d,h=Be*B,g=h-(h-B),y=B-g,C=m*y-(S-d*g-m*g-d*y),M=v*N,h=Be*v,d=h-(h-v),m=v-d,h=Be*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),w=S+b,c=w-S,A=S-(w-c)+(b-c),b=A-M,c=A-b,lt[1]=A-(b+c)+(c-M),U=w+b,c=U-w,lt[2]=w-(U-c)+(b-c),lt[3]=U;let F=lo(4,lt),z=uo*s;if(F>=z||-F>=z||(c=t-Y,a=t-(Y+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+=Y*f+B*a-(v*u+N*l),F>=z||-F>=z))return F;S=a*B,h=Be*a,d=h-(h-a),m=a-d,h=Be*B,g=h-(h-B),y=B-g,C=m*y-(S-d*g-m*g-d*y),M=l*N,h=Be*l,d=h-(h-l),m=l-d,h=Be*N,g=h-(h-N),y=N-g,P=m*y-(M-d*g-m*g-d*y),b=C-P,c=C-b,Ue[0]=C-(b+c)+(c-P),w=S+b,c=w-S,A=S-(w-c)+(b-c),b=A-M,c=A-b,Ue[1]=A-(b+c)+(c-M),U=w+b,c=U-w,Ue[2]=w-(U-c)+(b-c),Ue[3]=U;const K=ln(4,lt,4,Ue,Zn);S=Y*f,h=Be*Y,d=h-(h-Y),m=Y-d,h=Be*f,g=h-(h-f),y=f-g,C=m*y-(S-d*g-m*g-d*y),M=v*u,h=Be*v,d=h-(h-v),m=v-d,h=Be*u,g=h-(h-u),y=u-g,P=m*y-(M-d*g-m*g-d*y),b=C-P,c=C-b,Ue[0]=C-(b+c)+(c-P),w=S+b,c=w-S,A=S-(w-c)+(b-c),b=A-M,c=A-b,Ue[1]=A-(b+c)+(c-M),U=w+b,c=U-w,Ue[2]=w-(U-c)+(b-c),Ue[3]=U;const W=ln(K,Zn,4,Ue,$n);S=a*f,h=Be*a,d=h-(h-a),m=a-d,h=Be*f,g=h-(h-f),y=f-g,C=m*y-(S-d*g-m*g-d*y),M=l*u,h=Be*l,d=h-(h-l),m=l-d,h=Be*u,g=h-(h-u),y=u-g,P=m*y-(M-d*g-m*g-d*y),b=C-P,c=C-b,Ue[0]=C-(b+c)+(c-P),w=S+b,c=w-S,A=S-(w-c)+(b-c),b=A-M,c=A-b,Ue[1]=A-(b+c)+(c-M),U=w+b,c=U-w,Ue[2]=w-(U-c)+(b-c),Ue[3]=U;const j=ln(W,$n,4,Ue,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 tt=Number.EPSILON;tt===void 0&&(tt=Math.pow(2,-52));const go=tt*tt,jn=(t,e)=>{if(-tt<t&&t<tt&&-tt<e&&e<tt)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: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: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 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=++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 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=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 nt(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=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 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(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 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]:nt.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){qe.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(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 _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 qe=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 qe.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 qe.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 qe.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 qe.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 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 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 it=[],hr=[],$e={color:"#ff4d4f",width:2,lineDash:it,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,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},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 He=Dn;function ze(t){return Ye(t)}function Wt(t){return Math.abs(wt(ze(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 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 Nn(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?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?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 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 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=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 ze(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??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 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,n="top-center"){let r=null;for(const i of t){const o=e(i.outer);if(o.length===0)continue;const s=ks(o,n);s&&(!r||s[1]<r[1]||s[1]===r[1]&&s[0]<r[0])&&(r=s)}return r}function Un(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 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):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 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=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 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 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 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 ze(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:it,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:w,regionStrokeActiveStyle:A,patchStrokeStyle:S,resolveRegionStrokeStyle:C,resolveRegionLabelStyle:M,overlayShapes:P,hoveredRegionId:U=null,activeRegionId:Y=null,regionLabelStyle:N,drawAreaTooltip:v,autoLiftRegionLabelAtMaxZoom:B=!1,regionLabelAnchor:F="top-center",clampRegionLabelToViewport:z=!0,regionLabelAutoLiftOffsetPx:K,invalidateRef:W,className:j,style:ce}){const Q=p.useRef(null),Te=p.useRef(!1),ve=p.useRef(new Map),Ae=p.useRef(t),I=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((x,R)=>({id:R,coordinates:x})),[d,g]),q=p.useMemo(()=>m??hr,[m]),ee=p.useMemo(()=>{const x=[];for(let R=0;R<X.length;R+=1){const D=X[R],k=jt(D.coordinates);k.length!==0&&x.push({region:D,regionIndex:R,regionKey:D.id??R,polygons:k})}return x},[X]),le=p.useMemo(()=>{const x=[];for(let R=0;R<q.length;R+=1){const D=q[R],k=jt(D.coordinates);k.length!==0&&x.push({region:D,regionIndex:R,regionKey:D.id??R,polygons:k})}return x},[q]),re=p.useMemo(()=>Nn(b),[b]),pe=p.useMemo(()=>Ke(re,w),[re,w]),te=p.useMemo(()=>Ke(re,A),[re,A]),ye=p.useMemo(()=>Ke(li,S),[S]),fe=p.useMemo(()=>$s(y),[y]),se=p.useMemo(()=>Un(N),[N]),ue=p.useMemo(()=>Ys(v),[v]),Me=p.useMemo(()=>Vs(o),[o]),H=p.useMemo(()=>Is(s),[s]),Ie=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]),Se=p.useCallback(()=>{const x=Q.current;if(!x)return;const R=x.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));(x.width!==k||x.height!==Z)&&(x.width=k,x.height=Z)},[T,t]),he=p.useCallback(x=>{const R=a.current;if(!R||x.length===0)return[];const D=new Array(x.length);for(let k=0;k<x.length;k+=1){const Z=He(R.worldToScreen(x[k][0],x[k][1]));if(!Z)return[];D[k]=Z}return D},[a]),V=p.useCallback(x=>{const R=a.current,D=Q.current;if(!R||!D)return null;const k=D.getBoundingClientRect(),Z=He(R.screenToWorld(k.left+x[0],k.top+x[1]));return Z?Zt(Z,e,n):null},[a,e,n]),$=p.useCallback(()=>{const x=a.current,R=x?.getViewState?.().rotationDeg??0;if(!(Math.abs(R%360)<.01||!x))return{worldToScreen:(D,k)=>He(x.worldToScreen(D,k)),screenToWorld:V}},[a,V]),ie=p.useCallback(x=>{if(!Number.isFinite(x)||x<=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,de=D+Math.log2(Z),ae=Math.max(1e-9,Fn(R,D,de));return x/ae/Z},[r,i,a]),oe=p.useCallback((x,R)=>Hs({stampTool:x,center:R,resolvedStampOptions:Me,imageWidth:e,imageHeight:n,micronsToWorldPixels:ie,getRectangleProjection:$}),[ie,e,n,Me,$]),Ee=p.useCallback(()=>{const x=I.current;return Lt(t)?oe(t,x.stampCenter):t==="brush"?[]:x.isDrawing?t==="freehand"?x.points:t==="rectangle"?Kt(x.start,x.current,$()):t==="circular"?Sn(x.start,x.current):[]:[]},[t,oe,$]),Fe=p.useCallback(()=>{Se();const x=Q.current;if(!x)return;const R=x.getContext("2d");if(!R)return;const D=Math.max(1,window.devicePixelRatio||1),k=x.width/D,Z=x.height/D;if(R.setTransform(1,0,0,1,0,0),R.clearRect(0,0,x.width,x.height),R.setTransform(D,0,0,D,0,0),ee.length>0)for(const ae of ee){const{region:ge,polygons:Pe,regionIndex:_e,regionKey:Ne}=ae,at=$t(Y,Ne)?"active":$t(U,Ne)?"hover":"default";let Qe=at==="active"?te:at==="hover"?pe:re;if(C){const vt=C({region:ge,regionId:Ne,regionIndex:_e,state:at});Qe=Ke(Qe,vt||void 0)}const Pt=at==="default"?null:Zs(Qe);for(const vt of Pe){const rn=he(vt.outer);rn.length>=4&&(Pt&&ke(R,rn,Pt,!0,!1),ke(R,rn,Qe,!0,!1));for(const Ki of vt.holes){const on=he(Ki);on.length>=4&&(Pt&&ke(R,on,Pt,!0,!1),ke(R,on,Qe,!0,!1))}}}if(le.length>0)for(const ae of le)for(const ge of ae.polygons){const Pe=he(ge.outer);Pe.length>=4&&ke(R,Pe,ye,!0,!1);for(const _e of ge.holes){const Ne=he(_e);Ne.length>=4&&ke(R,Ne,ye,!0,!1)}}if(Array.isArray(P)&&P.length>0){const ae=he(ze([[0,0],[e,0],[e,n],[0,n]]));yi({ctx:R,overlayShapes:P,imageOuterRing:ae,worldToScreenPoints:he,baseStrokeStyle:re,onInvertedFillDebug:globalThis.__OPEN_PLANT_DEBUG_OVERLAY__?ge=>{const Pe=String(ge.id),_e=`${ge.outerRingPoints}|${ge.sourceRingCount}|${ge.holeRingCount}|${ge.fillColor}`;ve.current.get(Pe)!==_e&&(ve.current.set(Pe,_e),console.debug("[open-plant] invertedFill",ge))}:void 0})}const de=Ee();if(T){if(t==="brush")_s(R,I.current,H),Ls(R,I.current,a.current,H);else if(de.length>0)if(t==="freehand"){const ae=he(de);ae.length>=2&&ke(R,ae,re,!1,!1),ae.length>=3&&ke(R,he(ze(de)),re,!0,!0,fe)}else{const ae=he(de);ae.length>=4&&ke(R,ae,re,!0,!0,fe)}}if(ee.length>0){const ae=Math.max(1e-6,a.current?.getViewState?.().zoom??1),ge=typeof K=="number"&&Number.isFinite(K)?Math.max(0,K):On(B,ae,a.current?.getZoomRange?.(),a.current?.getRegionLabelAutoLiftCapZoom?.());for(const Pe of ee){if(!Pe.region.label)continue;const _e=kn(Pe.polygons,he,F);if(!_e)continue;let Ne=zn(se,M?.({region:Pe.region,regionId:Pe.regionKey,regionIndex:Pe.regionIndex,zoom:ae}));ge>0&&(Ne={...Ne,offsetY:Ne.offsetY+ge}),pi(R,Pe.region.label,_e,k,Z,Ne,z)}}if(ue.enabled&&T&&(t==="freehand"||t==="rectangle"||t==="circular")){const ae=I.current;if(ae.isDrawing){const ge=t==="freehand"?ze(de):de;if(ge.length>=4){const Pe=Wt(ge),_e=typeof r=="number"&&Number.isFinite(r)&&r>0?r:0,Ne=_e>0?Pe*_e*_e/(pr*pr):0,at=ue.format(Ne),Qe=ae.cursorScreen??(ae.current?He(a.current?.worldToScreen(ae.current[0],ae.current[1])??[]):null);Qe&&Ws(R,at,Qe,k,Z,ue.style,ue.cursorOffsetX,ue.cursorOffsetY)}}}},[T,t,Ee,Se,he,e,n,a,ee,P,U,Y,re,pe,te,fe,le,ye,C,M,se,ue,B,F,z,K,r,H]),G=p.useCallback(()=>{Te.current||(Te.current=!0,requestAnimationFrame(()=>{Te.current=!1,Fe()}))},[Fe]),be=p.useCallback((x=!1)=>{const R=I.current,D=Q.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,x||(R.cursor=null,R.cursorScreen=null)},[]),xe=p.useCallback(x=>{const R=a.current;if(!R||e<=0||n<=0)return null;const D=He(R.screenToWorld(x.clientX,x.clientY));return D?Zt(D,e,n):null},[a,e,n]),_=p.useCallback(x=>{const R=Q.current;if(!R)return null;const D=R.getBoundingClientRect(),k=L(x.clientX-D.left,0,D.width),Z=L(x.clientY-D.top,0,D.height);return!Number.isFinite(k)||!Number.isFinite(Z)?null:[k,Z]},[]),O=p.useCallback(()=>{const x=I.current;if(!x.isDrawing){be(!0),G();return}let R=[];if(t==="freehand")x.points.length>=rs&&(R=ze(x.points));else if(t==="rectangle")R=Kt(x.start,x.current,$());else if(t==="circular")R=Sn(x.start,x.current);else if(t==="brush"){const D=x.points[x.points.length-1]??x.current??x.start;if(H.clickSelectRoi&&D&&x.points.length<=1&&l?.(D)){be(!0),G();return}const k=Math.max(.25,H.edgeDetail),Z=x.screenPoints.length>0?x.screenPoints:he(x.points),de=Math.max(.5,H.radius*.04/k),ae=ts(Z,{radius:H.radius,circleSides:Math.max(16,Math.round(32*k)),simplifyTolerance:de,smoothingPasses:H.edgeSmoothing}),ge=[];for(const Pe of ae){const _e=V(Pe);_e&&ge.push(_e)}R=ze(ge)}(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)}),be(!0),G()},[t,u,be,G,he,V,$,H.radius,H.edgeDetail,H.edgeSmoothing,H.clickSelectRoi,l]),J=p.useCallback((x,R)=>{const D=oe(x,R);if(!Rr(D))return;const k=x==="stamp-rectangle-4096px"?"patch":"roi",Z={tool:x,intent:k,coordinates:D,bbox:br(D),areaPx:Wt(D)};u?.(Z),k==="patch"&&f&&f(Z)},[oe,u,f]),ne=p.useCallback((x,R,D)=>{const k=Math.max(Es,H.radius*.1),Z=k*k,de=x.screenPoints[x.screenPoints.length-1];if(!de){x.points.push(R),x.screenPoints.push(D),x.current=R;return}const ae=D[0]-de[0],ge=D[1]-de[1];ae*ae+ge*ge>=Z?(x.points.push(R),x.screenPoints.push(D)):(x.points[x.points.length-1]=R,x.screenPoints[x.screenPoints.length-1]=D),x.current=R},[H.radius]),Re=p.useCallback(x=>{if(!T||t==="cursor"||x.button!==0)return;const R=xe(x);if(!R)return;const D=_(x);if(!D)return;if(x.preventDefault(),x.stopPropagation(),Lt(t)){const de=I.current;de.stampCenter=R,J(t,R),G();return}const k=Q.current;k&&k.setPointerCapture(x.pointerId);const Z=I.current;Z.isDrawing=!0,Z.pointerId=x.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,xe,_,J,G]),me=p.useCallback(x=>{if(!T||t==="cursor")return;const R=xe(x);if(!R)return;const D=_(x);if(!D)return;const k=I.current;if(k.cursor=R,k.cursorScreen=D,Lt(t)){k.stampCenter=R,x.preventDefault(),x.stopPropagation(),G();return}if(t==="brush"){if(!k.isDrawing||k.pointerId!==x.pointerId){G();return}x.preventDefault(),x.stopPropagation(),ne(k,R,D),G();return}if(!(!k.isDrawing||k.pointerId!==x.pointerId)){if(x.preventDefault(),x.stopPropagation(),t==="freehand"){const Z=a.current,de=Math.max(1e-6,Z?.getViewState?.().zoom??1),ae=is/de,ge=ae*ae,Pe=k.points[k.points.length-1];if(!Pe)k.points.push(R);else{const _e=R[0]-Pe[0],Ne=R[1]-Pe[1];_e*_e+Ne*Ne>=ge&&k.points.push(R)}}else k.current=R;G()}},[T,t,xe,_,G,a,ne]),Ce=p.useCallback(x=>{const R=I.current;if(!R.isDrawing||R.pointerId!==x.pointerId)return;x.preventDefault(),x.stopPropagation();const D=xe(x),k=_(x);D&&(R.cursor=D,k&&(R.cursorScreen=k),t==="brush"?k&&ne(R,D,k):R.current=D);const Z=Q.current;Z&&Z.hasPointerCapture(x.pointerId)&&Z.releasePointerCapture(x.pointerId),O()},[O,xe,_,t,ne]),De=p.useCallback(()=>{const x=I.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&&G()},[t,G]);return p.useEffect(()=>{Se(),G();const x=Q.current;if(!x)return;const R=new ResizeObserver(()=>{Se(),G()});return R.observe(x),()=>{R.disconnect()}},[Se,G]),p.useEffect(()=>tn(()=>{Se(),G()}),[Se,G]),p.useEffect(()=>{T||be(),G()},[T,G,be]),p.useEffect(()=>{Ae.current!==t&&(Ae.current=t,be(),G())},[t,be,G]),p.useEffect(()=>{G()},[h,X,P,G]),p.useEffect(()=>{if(W)return W.current=G,()=>{W.current===G&&(W.current=null)}},[W,G]),p.useEffect(()=>{if(!T)return;const x=R=>{R.key==="Escape"&&(be(),G())};return window.addEventListener("keydown",x),()=>{window.removeEventListener("keydown",x)}},[T,be,G]),Ge.jsx("canvas",{ref:Q,className:j,style:Ie,onPointerDown:Re,onPointerMove:me,onPointerUp:Ce,onPointerCancel:Ce,onPointerLeave:De,onContextMenu:x=>{T&&x.preventDefault()},onWheel:x=>{if(!T)return;const R=Q.current,D=a.current;if(!R||typeof D?.zoomBy!="function")return;x.preventDefault(),x.stopPropagation();const k=R.getBoundingClientRect(),Z=x.clientX-k.left,de=x.clientY-k.top;D.zoomBy(x.deltaY<0?ls:cs,Z,de),G()}})}const xi=p.createContext(null),Ks=xi.Provider;function st(){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}=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(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
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
- }`,Js=`#version 300 es
46
+ }`,ea=`#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
- }`,Qs=`#version 300 es
62
+ }`,ta=`#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
- }`,ea=`#version 300 es
67
+ }`,na=`#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 ta{constructor(){S(this,"canvas");S(this,"gl");S(this,"accumProgram");S(this,"colorProgram");S(this,"accumVao");S(this,"colorVao");S(this,"pointBuffer");S(this,"quadBuffer");S(this,"accumTexture");S(this,"gradientTexture");S(this,"framebuffer");S(this,"accumInternalFormat");S(this,"accumTextureFormat");S(this,"accumTextureType");S(this,"uAccumResolution");S(this,"uAccumPointSize");S(this,"uAccumCoreRatio");S(this,"uAccumPointAlpha");S(this,"uColorAccumTexture");S(this,"uColorGradientTexture");S(this,"uColorOpacity");S(this,"uColorCutoff");S(this,"uColorGain");S(this,"uColorResolution");S(this,"uColorGamma");S(this,"uColorBias");S(this,"uColorStretch");S(this,"pointCapacity",0);S(this,"interleavedCapacity",0);S(this,"interleavedBuffer",null);S(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,Js),this.colorProgram=bt(e,Qs,ea);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"),E=e.getUniformLocation(this.colorProgram,"uGamma"),M=e.getUniformLocation(this.colorProgram,"uBias"),C=e.getUniformLocation(this.colorProgram,"uStretch"),T=e.getUniformLocation(this.colorProgram,"uResolution");if(!c||!h||!d||!m||!g||!y||!b||!x||!A||!E||!M||!C||!T)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=E,this.uColorBias=M,this.uColorStretch=C,this.uColorResolution=T,e.bindVertexArray(this.accumVao),e.bindBuffer(e.ARRAY_BUFFER,this.pointBuffer),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const k=e.getAttribLocation(this.accumProgram,"aCenter"),X=e.getAttribLocation(this.accumProgram,"aWeight");if(k<0||X<0)throw new Error("Failed to resolve heatmap WebGL attributes.");e.enableVertexAttribArray(k),e.vertexAttribPointer(k,2,e.FLOAT,!1,12,0),e.enableVertexAttribArray(X),e.vertexAttribPointer(X,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 Ar="__open_plant_heatmap_layer__",na=["#00000000","#3876FF","#4CDDDD","#FFE75C","#FF8434","#FF3434"],ra=3,ia=2,oa=.9,sa=52e3,aa="screen",la=2.2,Sn=128,Jt=1600,ca=1.9,ua=4.2,En=3e3,xi=Math.SQRT2,fa=2048,ha=.9,$e=16;function Ct(t,e){return e.maxTierZoom+Math.log2(Math.max(1e-6,t))}function On(t,e){return Math.max(1e-6,2**(t-e.maxTierZoom))}function da(t,e,n){if(!Number.isFinite(n)||Math.abs(n)<1e-6)return Math.max(1e-6,t);const r=Ct(t,e)-n;return On(r,e)}function ma(t){return!Number.isFinite(t)||Math.abs(t)<1e-6?0:Math.round(t*1.5/Math.max(1e-6,Math.log2(xi)))}function wi(t){const e=_(t,0,$e);return _(.55+Math.sqrt(Math.max(0,e))*.48,.55,6)}function ga(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 Si(t){return .022-_(t,0,$e)/$e*.015}function Ei(t){const e=_(t,0,$e);return .18+Math.pow(Math.max(0,e),.72)*.42+Math.log2(e+1)*.24}function Ri(t){return wi(t)}function Ai(t){const n=_(t,0,$e)/$e;return _(.46-n*.34,.12,.46)}function Mi(t,e,n){const i=_(t,0,$e)/$e,o=Ct(e,n),s=n.maxTierZoom-3.2,a=n.maxTierZoom-1.15,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 pa(t,e,n){const r=Math.max(0,t),i=Math.max(1e-6,e),o=Math.log1p(r)/Math.log1p(i);return _(o,0,1)}function ya(t){return ha}function ba(t,e){if(t.length===0)return 1;const n=Math.min(t.length,fa),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=ya(),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 Ci(t,e,n){const r=Ct(t,e),i=e.maxTierZoom-2.45,o=e.maxTierZoom-1.2,s=r<=i?1:r>=o?0:(()=>{const a=_((r-i)/Math.max(1e-6,o-i),0,1);return 1-a*a*(3-2*a)})();return _(s,0,1)}function xa(t){if(t>=1)return 1;const e=1/Math.max(t,1e-6);return 1+Math.log2(e)*.28}function wa(t,e,n,r){const i=Math.max(1,t,e),o=typeof window>"u"?1:_(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:Jt,l=Sn/i,u=Jt/i;return _(a*o*s/i,l,u)}function Rn(t){const e=t.heatmapScale??wa(t.logicalWidth,t.logicalHeight,t.totalPointCount,t.rawZoom),n=Math.max(Sn,Math.min(Jt,Math.round(t.logicalWidth*e))),r=Math.max(Sn,Math.min(Jt,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*ca*s),u=Math.max(.6,t.blur*ua*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 Yn(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 Sa(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 Ea(t){return(t>>>0)/4294967295}function Pi(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 Wn(t,e,n){return t.dataRef===e&&t.clipKey===n?!0:e?t.clipKey===n&&t.inputCount===Yn(e)&&t.positionsRef===e.positions&&t.weightsRef===e.weights:!1}function Ra(t,e,n,r){const i=Yn(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 E=t.positions[A*2],M=t.positions[A*2+1];if(!Number.isFinite(E)||!Number.isFinite(M)||e.length>0&&!St(E,M,e))continue;const C=t.weights?.[A],T=typeof C=="number"&&Number.isFinite(C)?Math.max(0,C):1;T<=0||(o[l]=E,s[l]=M,a[l]=T,l+=1,E<u&&(u=E),E>c&&(c=E),M<f&&(f=M),M>h&&(h=M))}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 E=o[A],M=s[A];d.push({minX:E,minY:M,maxX:E,maxY:M,value:A})}const m=bi(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*=xi,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 An(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 Ti(t,e){const n=Math.max(En,e);return t<=n?1:_(n/Math.max(1,t),1/65536,1)}function vi(t){return t>=1?1:Math.max(1,Math.round(1/Math.max(1e-6,t)))}function Aa(t,e){if(e>=1)return!0;const n=Sa(t,1374496523,1757159915);return Ea(n)<=_(e,0,1)}function Ii(t,e,n,r){const i=Math.max(1,n*r),o=Math.PI*e*e,s=Math.max(1,t)*o/i;return _(.085/Math.sqrt(Math.max(1,s)),.012,.075)}function Mr(t,e,n,r){if(!Number.isFinite(t)||t<=0)return e;const i=e>=t?n:r;return t+(e-t)*_(i,0,1)}function Ma(t){if(t.webgl!==void 0)return t.webgl;if(typeof document>"u")return t.webgl=null,null;try{t.webgl=new ta}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 Cr(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 Ca(t,e,n){if(n.length!==0){t.beginPath();for(let r=0;r<n.length;r+=1){const i=n[r],o=Cr(e,i.outer);o.length>=3&&Et(t,o,!0);for(let s=0;s<i.holes.length;s+=1){const a=Cr(e,i.holes[s]);a.length>=3&&Et(t,a,!0)}}t.clip("evenodd")}}function _i(t,e,n,r,i){const o=t.sourceData;return o&&o.sourceRef===i&&Wn(o,e,r)?o:(t.sourceData=Ra(e,n,r,i),t.fixedState=null,t.screenLevelIndex=-1,t.sourceData)}function Pa(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??Ct(f,r),h=On(c,r),d=Rn({logicalWidth:i,logicalHeight:o,totalPointCount:e.pointCount,rawZoom:h,radius:s,blur:a}),m=n.getViewBounds(),g=An(e,m,d.outerWorldRadius),y=Ti(g.length,u),b=vi(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:Ii(g.length,d.kernelRadiusPx+d.blurRadiusPx,d.rasterWidth,d.rasterHeight)}}function Pr(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=Ma(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 E=n.webglPositions,M=n.webglWeights;if(!E||!M)return 0;const C=a.kernelRadiusPx+a.blurRadiusPx,T=xa(f);let k=0;for(let N=0;N<u.length;N+=1){const P=u[N];if(!Aa(P,f))continue;const z=l.xs[P],F=l.ys[P];if(!Number.isFinite(z)||!Number.isFinite(F))continue;const O=r.worldToScreen(z,F);if(!Array.isArray(O)||O.length<2)continue;const $=Number(O[0]),W=Number(O[1]);if(!Number.isFinite($)||!Number.isFinite(W))continue;const J=$*a.rasterScaleX,he=W*a.rasterScaleY;if(J<-C||he<-C||J>a.rasterWidth+C||he>a.rasterHeight+C)continue;const K=k*2;E[K]=J,E[K+1]=he,M[k]=Math.max(0,(l.ws[P]??0)*T),k+=1}return k<=0||!x.render({width:a.rasterWidth,height:a.rasterHeight,positions:E,weights:M,count:k,kernelRadiusPx:a.kernelRadiusPx,blurRadiusPx:a.blurRadiusPx,pointAlpha:h,gradient:d,opacity:m,cutoff:Si(g),gain:Ei(g),gamma:Ri(g),bias:Ai(g),stretch:Mi(g,a.rawZoom,i)})?0:(e.save(),b.length>0&&Ca(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(),k)}function Ta(t){const{ctx:e,runtime:n,renderer:r,source:i,logicalWidth:o,logicalHeight:s,state:a}=t,l=_i(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=Ci(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=Rn({logicalWidth:o,logicalHeight:s,totalPointCount:l.pointCount,rawZoom:u,radius:a.radius,blur:a.blur}),x=An(l,c,b.outerWorldRadius);if(x.length===0)return{pointCount:l.pointCount,renderTimeMs:0,visiblePointCount:0,renderedBinCount:0,sampleStride:1,maxDensity:0};const A=Ti(x.length,a.maxRenderedPoints),E=vi(A),M=Ii(x.length,b.kernelRadiusPx+b.blurRadiusPx,b.rasterWidth,b.rasterHeight);n.screenLevelIndex=-1,n.screenSecondaryLevelIndex=-1,n.screenSecondaryLevelWeight=0,n.screenNormalizationMaxWeight=1,n.screenPointAlpha=Mr(n.screenPointAlpha,M,.12,.08),n.screenVisibilityStrength=r.isViewAnimating()?Mr(n.screenVisibilityStrength,f,.16,.12):f;const C=Pr({ctx:e,runtime:n,renderer:r,source:i,logicalWidth:o,logicalHeight:s,frame:b,sourceData:l,visiblePointIndices:x,sampleProbability:A,sampleStride:E,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:C,sampleStride:E,maxDensity:Math.round(n.screenPointAlpha*255)}}const h=n.fixedState;if(!h)return null;const d=Rn({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=An(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=Pr({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 va({data:t,visible:e=!0,opacity:n=oa,radius:r=ra,blur:i=ia,gradient:o=na,backgroundColor:s=null,scaleMode:a=aa,fixedZoom:l,zoomThreshold:u=0,densityContrast:f=la,clipToRegions:c,zIndex:h=5,maxRenderedPoints:d=sa,onStats:m}){const{rendererRef:g,source:y,registerDrawCallback:b,unregisterDrawCallback:x,requestOverlayRedraw:A}=at(),E=p.useMemo(()=>{const k=(c??[]).map(X=>ht(X?.coordinates)).filter(X=>X!=null);return dt(k)},[c]),M=p.useMemo(()=>Pi(E),[E]),C=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}),T=p.useRef({data:t,visible:e,opacity:n,radius:_(r,.05,128),blur:_(i,.05,128),gradient:o,backgroundColor:s,scaleMode:a,fixedZoom:l,zoomThreshold:u,densityContrast:_(f,0,$e),clipPolygons:E,clipKey:M,maxRenderedPoints:Math.max(En,Math.floor(d)),onStats:m});return T.current={data:t,visible:e,opacity:n,radius:_(r,.05,128),blur:_(i,.05,128),gradient:o,backgroundColor:s,scaleMode:a,fixedZoom:l,zoomThreshold:u,densityContrast:_(f,0,$e),clipPolygons:E,clipKey:M,maxRenderedPoints:Math.max(En,Math.floor(d)),onStats:m},p.useEffect(()=>(b(Ar,h,(X,N,P)=>{const z=T.current,F=C.current,O=g.current;if(!z.visible||!z.data||!O||!y)return;const $=_i(F,z.data,z.clipPolygons,z.clipKey,y);if(!$)return;z.scaleMode==="fixed-zoom"&&(!F.fixedState||!Wn(F.fixedState,z.data,z.clipKey)||z.fixedZoom!==void 0&&Math.abs(F.fixedState.referenceZoom-z.fixedZoom)>1e-6)?F.fixedState=Pa({sourceData:$,renderer:O,source:y,logicalWidth:N,logicalHeight:P,radius:z.radius,blur:z.blur,fixedZoom:z.fixedZoom,zoomThreshold:z.zoomThreshold,densityContrast:z.densityContrast,maxRenderedPoints:z.maxRenderedPoints}):z.scaleMode!=="fixed-zoom"&&(F.fixedState=null);const J=performance.now(),he=Ta({ctx:X,runtime:F,renderer:O,source:y,logicalWidth:N,logicalHeight:P,state:z});!he||!z.onStats||z.onStats({...he,renderTimeMs:performance.now()-J})}),()=>{x(Ar),C.current.sourceData=null,C.current.fixedState=null,C.current.screenLevelIndex=-1,C.current.screenSecondaryLevelIndex=-1,C.current.screenSecondaryLevelWeight=0,C.current.screenPointAlpha=0,C.current.screenNormalizationMaxWeight=1,C.current.screenVisibilityStrength=1,C.current.webgl?.destroy(),C.current.webgl=void 0,C.current.webglPositions=null,C.current.webglWeights=null,C.current.webglCapacity=0}),[b,x,g,y,h]),p.useEffect(()=>{C.current.sourceData=null,C.current.fixedState=null,C.current.screenLevelIndex=-1,C.current.screenSecondaryLevelIndex=-1,C.current.screenSecondaryLevelWeight=0,C.current.screenPointAlpha=0,C.current.screenNormalizationMaxWeight=1,C.current.screenVisibilityStrength=1,A()},[t?.positions,t?.weights,t?.count,M,A]),p.useEffect(()=>{C.current.fixedState=null,C.current.screenSecondaryLevelIndex=-1,C.current.screenSecondaryLevelWeight=0,C.current.screenPointAlpha=0,C.current.screenNormalizationMaxWeight=1,C.current.screenVisibilityStrength=1,A()},[r,i,a,l,u,f,d,A]),p.useEffect(()=>{A()},[e,n,o,s,A]),null}const Ia={applyZoomThreshold:da,buildClipKey:Pi,resolveCellSupportFactor:ga,resolveContinuousZoom:Ct,resolveDensityCutoff:Si,resolveDensityBias:Ai,resolveDensityGain:Ei,resolveDensityGamma:Ri,resolveDensityStretch:Mi,resolveNormalizedDensityWeight:pa,resolveNormalizationUpperWeight:ba,resolveDensityWeightExponent:wi,resolveRawZoomFromContinuousZoom:On,resolvePointCount:Yn,resolveThresholdLevelBias:ma,resolveZoomVisibilityStrength:Ci,isSameHeatmapInput:Wn},Tr="__overlay_layer__";function _a({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(Tr,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]]));gi({ctx:u,overlayShapes:f,imageOuterRing:d,worldToScreenPoints:c,baseStrokeStyle:Ke})}),()=>i(Tr)),[r,i]),p.useEffect(()=>{o()},[t,o]),null}function La(t){return Array.isArray(t?.classes)?t.classes.map(e=>({classId:String(e?.classId??""),className:String(e?.className??""),classColor:String(e?.classColor??"")})):[]}function vr(t){return String(t??"").replace(/\/+$/,"")}function Li(t){const e=String(t??"");return e.startsWith("/")?e:`/${e}`}function Fa(t){const e=vr(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=vr(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 Da(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=Li(l),c=Fa(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 Xn(t,e,n,r){if(t.tileUrlBuilder)return t.tileUrlBuilder(e,n,r,t.tilePath,t.tileBaseUrl);const i=Li(t.tilePath);return`${t.tileBaseUrl}${i}/${e}/${r}_${n}.webp`}function Na(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 Ir(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 _r(t,e,n=1e-4){return Math.abs(t[0]-e[0])<=n&&Math.abs(t[1]-e[1])<=n}function Lr(t){const e=[];for(const n of t){const r=e[e.length-1];(!r||!_r(r,n))&&e.push(n)}return e.length>1&&_r(e[0],e[e.length-1])&&e.pop(),e}function Fr(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 Dr(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 Ba(t,e,n,r,i){let o=Lr(t);if(o.length<3)return[];const s=[{inside:a=>a[0]>=e,intersect:(a,l)=>Fr(a,l,e)},{inside:a=>a[0]<=r,intersect:(a,l)=>Fr(a,l,r)},{inside:a=>a[1]>=n,intersect:(a,l)=>Dr(a,l,n)},{inside:a=>a[1]<=i,intersect:(a,l)=>Dr(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=Lr(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 ka={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 Ua({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 v=Math.max(1,t.width),I=Math.max(1,t.height),U=v/I,oe=d/m;let j,ue;return U>oe?(j=d,ue=d/U):(ue=m,j=m*U),{x:(d-j)/2,y:(m-ue)/2,w:j,h:ue}},[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))),E=r?.backgroundColor||Oe.backgroundColor,M=r?.borderColor||Oe.borderColor,C=r?.viewportBorderColor||Oe.viewportBorderColor,T=r?.viewportBorderStyle==="stroke"||r?.viewportBorderStyle==="dash"?r.viewportBorderStyle:Oe.viewportBorderStyle,k=r?.viewportFillColor??Oe.viewportFillColor,X=r?.interactive??Oe.interactive,N=r?.showThumbnail??Oe.showThumbnail,P=r?.position||Oe.position,z=r?.onClose,F=r?.closeIcon,O=r?.closeButtonStyle,$=p.useMemo(()=>{const v={};return P==="top-left"||P==="bottom-left"?v.left=y:v.right=y,P==="top-left"||P==="top-right"?v.top=y:v.bottom=y,{position:"absolute",...v,width:d,height:m,borderRadius:b,overflow:"hidden",zIndex:4,pointerEvents:X?"auto":"none",touchAction:"none",boxShadow:"0 10px 22px rgba(0, 0, 0, 0.3)",...s}},[y,P,d,m,b,X,s]),W=p.useCallback(()=>{const v=a.current;if(!v)return;const I=v.getContext("2d");if(!I)return;const U=d,oe=m,j=Math.max(1,window.devicePixelRatio||1),ue=Math.max(1,Math.round(U*j)),ee=Math.max(1,Math.round(oe*j));(v.width!==ue||v.height!==ee)&&(v.width=ue,v.height=ee),I.setTransform(1,0,0,1,0,0),I.clearRect(0,0,v.width,v.height),I.setTransform(j,0,0,j,0,0),I.fillStyle=E,I.fillRect(0,0,U,oe);const{x:de,y:se,w:pe,h:Q}=g,ae=l.current;ae&&I.drawImage(ae,de,se,pe,Q),I.strokeStyle=M,I.lineWidth=x,I.strokeRect(x*.5,x*.5,U-x,oe-x);const fe=e.current,Ee=fe?.getViewBounds?.(),te=fe?.getViewCorners?.(),ve=Array.isArray(te)&&te.length>=4&&te.every(q=>Array.isArray(q)&&q.length>=2&&Number.isFinite(q[0])&&Number.isFinite(q[1]))?te:null,be=gt(Ee)?Ee:gt(u.current)?u.current:null;gt(Ee)&&(u.current=Ee);const me=pe/Math.max(1,t.width),V=Q/Math.max(1,t.height),Z=T==="dash";if(ve){const q=ve.map(ce=>[de+ce[0]*me,se+ce[1]*V]),ne=Ba(q,de,se,de+pe,se+Q);if(ne.length>=3){I.beginPath();for(let ce=0;ce<ne.length;ce+=1)ce===0?I.moveTo(ne[ce][0],ne[ce][1]):I.lineTo(ne[ce][0],ne[ce][1]);I.closePath(),I.fillStyle=k,I.fill(),I.strokeStyle=C,I.lineWidth=2.25,Z?Ir(I,ne,4,3):I.stroke();return}}if(!be)return;const re=_(de+be[0]*me,de,de+pe),ie=_(se+be[1]*V,se,se+Q),Se=_(de+be[2]*me,de,de+pe),Y=_(se+be[3]*V,se,se+Q),L=Math.max(1,Se-re),G=Math.max(1,Y-ie);if(I.fillStyle=k,I.fillRect(re,ie,L,G),I.strokeStyle=C,I.lineWidth=2.25,Z){const q=[[re+.5,ie+.5],[re+.5+Math.max(1,L-1),ie+.5],[re+.5+Math.max(1,L-1),ie+.5+Math.max(1,G-1)],[re+.5,ie+.5+Math.max(1,G-1)]];Ir(I,q,4,3)}else I.strokeRect(re+.5,ie+.5,Math.max(1,L-1),Math.max(1,G-1))},[d,m,g,E,M,x,e,t.width,t.height,k,C,T]),J=p.useCallback(()=>{h.current||(h.current=!0,c.current=requestAnimationFrame(()=>{h.current=!1,c.current=null,W()}))},[W]),he=p.useCallback((v,I)=>{const U=a.current;if(!U)return null;const oe=U.getBoundingClientRect();if(!oe.width||!oe.height)return null;const j=oe.width/d,ue=oe.height/m,ee=g.x*j,de=g.y*ue,se=g.w*j,pe=g.h*ue,Q=_((v-oe.left-ee)/se,0,1),ae=_((I-oe.top-de)/pe,0,1);return[Q*t.width,ae*t.height]},[t.width,t.height,d,m,g]),K=p.useCallback((v,I)=>{const U=e.current;if(!U)return;if(U.setViewCenter){U.setViewCenter(v,I),J();return}const oe=U.getViewBounds?.(),j=gt(oe)?oe:gt(u.current)?u.current:null;if(!j)return;const ue=Math.max(1e-6,j[2]-j[0]),ee=Math.max(1e-6,j[3]-j[1]);U.setViewState({offsetX:v-ue*.5,offsetY:I-ee*.5}),J()},[e,J]),Pe=p.useCallback(v=>{if(!X||v.button!==0)return;const I=a.current;if(!I)return;const U=he(v.clientX,v.clientY);U&&(v.preventDefault(),v.stopPropagation(),I.setPointerCapture(v.pointerId),f.current={active:!0,pointerId:v.pointerId},K(U[0],U[1]))},[X,he,K]),Ae=p.useCallback(v=>{const I=f.current;if(!I.active||I.pointerId!==v.pointerId)return;const U=he(v.clientX,v.clientY);U&&(v.preventDefault(),v.stopPropagation(),K(U[0],U[1]))},[he,K]),we=p.useCallback(v=>{const I=f.current;if(!I.active||I.pointerId!==v.pointerId)return;const U=a.current;if(U&&U.hasPointerCapture(v.pointerId))try{U.releasePointerCapture(v.pointerId)}catch{}f.current={active:!1,pointerId:null},J()},[J]);return p.useEffect(()=>{let v=!1;l.current=null,J();const I=0,U=2**(t.maxTierZoom-I),oe=Math.ceil(t.width/U),j=Math.ceil(t.height/U),ue=Math.max(1,Math.ceil(oe/t.tileSize)),ee=Math.max(1,Math.ceil(j/t.tileSize)),de=ue*ee;if(!N||de>A)return;const se=document.createElement("canvas");se.width=Math.max(1,Math.round(g.w)),se.height=Math.max(1,Math.round(g.h));const pe=se.getContext("2d");if(!pe)return;pe.fillStyle=E,pe.fillRect(0,0,se.width,se.height);const Q=[];for(let ae=0;ae<ee;ae+=1)for(let fe=0;fe<ue;fe+=1){const Ee=fe*t.tileSize*U,te=ae*t.tileSize*U,ve=Math.min((fe+1)*t.tileSize,oe)*U,be=Math.min((ae+1)*t.tileSize,j)*U;Q.push({url:Xn(t,I,fe,ae),bounds:[Ee,te,ve,be]})}return Promise.allSettled(Q.map(async ae=>{const fe=Na(ae.url,n),Ee=await fetch(ae.url,{headers:fe?{Authorization:n}:void 0});if(!Ee.ok)throw new Error(`HTTP ${Ee.status}`);const te=await createImageBitmap(await Ee.blob());return{tile:ae,bitmap:te}})).then(ae=>{if(v){for(const te of ae)te.status==="fulfilled"&&te.value.bitmap.close();return}const fe=se.width/Math.max(1,t.width),Ee=se.height/Math.max(1,t.height);for(const te of ae){if(te.status!=="fulfilled")continue;const{tile:{bounds:ve},bitmap:be}=te.value,me=ve[0]*fe,V=ve[1]*Ee,Z=Math.max(1,(ve[2]-ve[0])*fe),re=Math.max(1,(ve[3]-ve[1])*Ee);pe.drawImage(be,me,V,Z,re),be.close()}l.current=se,J()}),()=>{v=!0}},[t,n,g,E,N,A,J]),p.useEffect(()=>{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:$,children:[He.jsx("canvas",{ref:a,style:{width:"100%",height:"100%",display:"block",borderRadius:"inherit"},onPointerDown:Pe,onPointerMove:Ae,onPointerUp:we,onPointerCancel:we,onContextMenu:v=>{v.preventDefault()},onWheel:v=>{v.preventDefault(),v.stopPropagation()}}),z&&He.jsx("button",{type:"button","aria-label":"Hide overview map",onClick:v=>{v.stopPropagation(),z()},style:O?{...O}:{...ka},children:F??"×"})]})}const Nr="__patch_layer__",za=[];function Oa({regions:t,strokeStyle:e}){const{rendererRef:n,registerDrawCallback:r,unregisterDrawCallback:i,requestOverlayRedraw:o}=at(),s=t??za,a=p.useMemo(()=>je(si,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(Nr,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&&Ne(h,x,m,!0,!1);for(const A of b.holes){const E=g(A);E.length>=4&&Ne(h,E,m,!0,!1)}}}),()=>i(Nr)),[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 Fi(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 Ya=`
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"),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||!y||!b||!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=y,this.uColorOpacity=b,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 U=e.getAttribLocation(this.accumProgram,"aCenter"),Y=e.getAttribLocation(this.accumProgram,"aWeight");if(U<0||Y<0)throw new Error("Failed to resolve heatmap WebGL attributes.");e.enableVertexAttribArray(U),e.vertexAttribPointer(U,2,e.FLOAT,!1,12,0),e.enableVertexAttribArray(Y),e.vertexAttribPointer(Y,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,Ze=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,Ze);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,Ze)/Ze*.015}function Ai(t){const e=L(t,0,Ze);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,Ze)/Ze;return L(.46-n*.34,.12,.46)}function Pi(t,e,n){const i=L(t,0,Ze)/Ze,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,w=0;for(;b<=g&&w<32;)y.push(b),b*=Si,w+=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),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: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,w=Pa(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=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]),W=Number(z[1]);if(!Number.isFinite(K)||!Number.isFinite(W))continue;const j=K*a.rasterScaleX,ce=W*a.rasterScaleY;if(j<-M||ce<-M||j>a.rasterWidth+M||ce>a.rasterHeight+M)continue;const Q=U*2;S[Q]=j,S[Q+1]=ce,C[U]=Math.max(0,(l.ws[v]??0)*P),U+=1}return U<=0||!w.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(w.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}),w=Cn(l,c,b.outerWorldRadius);if(w.length===0)return{pointCount:l.pointCount,renderTimeMs:0,visiblePointCount:0,renderedBinCount:0,sampleStride:1,maxDensity:0};const A=Ii(w.length,a.maxRenderedPoints),S=_i(A),C=Li(w.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: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 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:w,requestOverlayRedraw:A}=st(),S=p.useMemo(()=>{const U=(c??[]).map(Y=>ht(Y?.coordinates)).filter(Y=>Y!=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,Ze),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,Ze),clipPolygons:S,clipKey:C,maxRenderedPoints:Math.max(Rn,Math.floor(d)),onStats:m},p.useEffect(()=>(b(Mr,h,(Y,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:Y,runtime:F,renderer:z,source:y,logicalWidth:N,logicalHeight:v,state:B});!ce||!B.onStats||B.onStats({...ce,renderTimeMs:performance.now()-j})}),()=>{w(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,w,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}=st(),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=He(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(ze([[0,0],[h.width,0],[h.width,h.height],[0,h.height]]));yi({ctx:u,overlayShapes:f,imageOuterRing:d,worldToScreenPoints:c,baseStrokeStyle:$e})}),()=>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 I=Math.max(1,t.width),T=Math.max(1,t.height),X=I/T,q=d/m;let ee,le;return X>q?(ee=d,le=d/X):(le=m,ee=m*X),{x:(d-ee)/2,y:(m-le)/2,w:ee,h:le}},[t.width,t.height,d,m]),y=ct(r?.margin,Oe.margin,0),b=ct(r?.borderRadius,Oe.borderRadius,0),w=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,Y=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 I={};return v==="top-left"||v==="bottom-left"?I.left=y:I.right=y,v==="top-left"||v==="top-right"?I.top=y:I.bottom=y,{position:"absolute",...I,width:d,height:m,borderRadius:b,overflow:"hidden",zIndex:4,pointerEvents:Y?"auto":"none",touchAction:"none",boxShadow:"0 10px 22px rgba(0, 0, 0, 0.3)",...s}},[y,v,d,m,b,Y,s]),W=p.useCallback(()=>{const I=a.current;if(!I)return;const T=I.getContext("2d");if(!T)return;const X=d,q=m,ee=Math.max(1,window.devicePixelRatio||1),le=Math.max(1,Math.round(X*ee)),re=Math.max(1,Math.round(q*ee));(I.width!==le||I.height!==re)&&(I.width=le,I.height=re),T.setTransform(1,0,0,1,0,0),T.clearRect(0,0,I.width,I.height),T.setTransform(ee,0,0,ee,0,0),T.fillStyle=S,T.fillRect(0,0,X,q);const{x:pe,y:te,w:ye,h:fe}=g,se=l.current;se&&T.drawImage(se,pe,te,ye,fe),T.strokeStyle=C,T.lineWidth=w,T.strokeRect(w*.5,w*.5,X-w,q-w);const ue=e.current,Me=ue?.getViewBounds?.(),H=ue?.getViewCorners?.(),Ie=Array.isArray(H)&&H.length>=4&&H.every(xe=>Array.isArray(xe)&&xe.length>=2&&Number.isFinite(xe[0])&&Number.isFinite(xe[1]))?H:null,Se=gt(Me)?Me:gt(u.current)?u.current:null;gt(Me)&&(u.current=Me);const he=ye/Math.max(1,t.width),V=fe/Math.max(1,t.height),$=P==="dash";if(Ie){const xe=Ie.map(O=>[pe+O[0]*he,te+O[1]*V]),_=Ua(xe,pe,te,pe+ye,te+fe);if(_.length>=3){T.beginPath();for(let O=0;O<_.length;O+=1)O===0?T.moveTo(_[O][0],_[O][1]):T.lineTo(_[O][0],_[O][1]);T.closePath(),T.fillStyle=U,T.fill(),T.strokeStyle=M,T.lineWidth=2.25,$?Lr(T,_,4,3):T.stroke();return}}if(!Se)return;const ie=L(pe+Se[0]*he,pe,pe+ye),oe=L(te+Se[1]*V,te,te+fe),Ee=L(pe+Se[2]*he,pe,pe+ye),Fe=L(te+Se[3]*V,te,te+fe),G=Math.max(1,Ee-ie),be=Math.max(1,Fe-oe);if(T.fillStyle=U,T.fillRect(ie,oe,G,be),T.strokeStyle=M,T.lineWidth=2.25,$){const xe=[[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,be-1)],[ie+.5,oe+.5+Math.max(1,be-1)]];Lr(T,xe,4,3)}else T.strokeRect(ie+.5,oe+.5,Math.max(1,G-1),Math.max(1,be-1))},[d,m,g,S,C,w,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,W()}))},[W]),ce=p.useCallback((I,T)=>{const X=a.current;if(!X)return null;const q=X.getBoundingClientRect();if(!q.width||!q.height)return null;const ee=q.width/d,le=q.height/m,re=g.x*ee,pe=g.y*le,te=g.w*ee,ye=g.h*le,fe=L((I-q.left-re)/te,0,1),se=L((T-q.top-pe)/ye,0,1);return[fe*t.width,se*t.height]},[t.width,t.height,d,m,g]),Q=p.useCallback((I,T)=>{const X=e.current;if(!X)return;if(X.setViewCenter){X.setViewCenter(I,T),j();return}const q=X.getViewBounds?.(),ee=gt(q)?q:gt(u.current)?u.current:null;if(!ee)return;const le=Math.max(1e-6,ee[2]-ee[0]),re=Math.max(1e-6,ee[3]-ee[1]);X.setViewState({offsetX:I-le*.5,offsetY:T-re*.5}),j()},[e,j]),Te=p.useCallback(I=>{if(!Y||I.button!==0)return;const T=a.current;if(!T)return;const X=ce(I.clientX,I.clientY);X&&(I.preventDefault(),I.stopPropagation(),T.setPointerCapture(I.pointerId),f.current={active:!0,pointerId:I.pointerId},Q(X[0],X[1]))},[Y,ce,Q]),ve=p.useCallback(I=>{const T=f.current;if(!T.active||T.pointerId!==I.pointerId)return;const X=ce(I.clientX,I.clientY);X&&(I.preventDefault(),I.stopPropagation(),Q(X[0],X[1]))},[ce,Q]),Ae=p.useCallback(I=>{const T=f.current;if(!T.active||T.pointerId!==I.pointerId)return;const X=a.current;if(X&&X.hasPointerCapture(I.pointerId))try{X.releasePointerCapture(I.pointerId)}catch{}f.current={active:!1,pointerId:null},j()},[j]);return p.useEffect(()=>{let I=!1;l.current=null,j();const T=0,X=2**(t.maxTierZoom-T),q=Math.ceil(t.width/X),ee=Math.ceil(t.height/X),le=Math.max(1,Math.ceil(q/t.tileSize)),re=Math.max(1,Math.ceil(ee/t.tileSize)),pe=le*re;if(!N||pe>A)return;const te=document.createElement("canvas");te.width=Math.max(1,Math.round(g.w)),te.height=Math.max(1,Math.round(g.h));const ye=te.getContext("2d");if(!ye)return;ye.fillStyle=S,ye.fillRect(0,0,te.width,te.height);const fe=[];for(let se=0;se<re;se+=1)for(let ue=0;ue<le;ue+=1){const Me=ue*t.tileSize*X,H=se*t.tileSize*X,Ie=Math.min((ue+1)*t.tileSize,q)*X,Se=Math.min((se+1)*t.tileSize,ee)*X;fe.push({url:Vn(t,T,ue,se),bounds:[Me,H,Ie,Se]})}return Promise.allSettled(fe.map(async se=>{const ue=ka(se.url,n),Me=await fetch(se.url,{headers:ue?{Authorization:n}:void 0});if(!Me.ok)throw new Error(`HTTP ${Me.status}`);const H=await createImageBitmap(await Me.blob());return{tile:se,bitmap:H}})).then(se=>{if(I){for(const H of se)H.status==="fulfilled"&&H.value.bitmap.close();return}const ue=te.width/Math.max(1,t.width),Me=te.height/Math.max(1,t.height);for(const H of se){if(H.status!=="fulfilled")continue;const{tile:{bounds:Ie},bitmap:Se}=H.value,he=Ie[0]*ue,V=Ie[1]*Me,$=Math.max(1,(Ie[2]-Ie[0])*ue),ie=Math.max(1,(Ie[3]-Ie[1])*Me);ye.drawImage(Se,he,V,$,ie),Se.close()}l.current=te,j()}),()=>{I=!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},[]),Ge.jsxs("div",{className:o,style:K,children:[Ge.jsx("canvas",{ref:a,style:{width:"100%",height:"100%",display:"block",borderRadius:"inherit"},onPointerDown:Te,onPointerMove:ve,onPointerUp:Ae,onPointerCancel:Ae,onContextMenu:I=>{I.preventDefault()},onWheel:I=>{I.preventDefault(),I.stopPropagation()}}),B&&Ge.jsx("button",{type:"button","aria-label":"Hide overview map",onClick:I=>{I.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}=st(),s=t??Ya,a=p.useMemo(()=>Ke(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=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(kr,20,h=>{const{prepared:d,resolvedStrokeStyle:m,worldToScreenPoints:g}=f.current;for(const y of d)for(const b of y.polygons){const w=g(b.outer);w.length>=4&&ke(h,w,m,!0,!1);for(const A of b.holes){const S=g(A);S.length>=4&&ke(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=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],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=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 Xa=`
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 Wa(){if(typeof navigator>"u")return!1;const t=navigator;return typeof t.gpu=="object"&&t.gpu!==null}function Di(){if(!Wa())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,cn=globalThis.GPUBufferUsage?.STORAGE??128,Bt=globalThis.GPUBufferUsage?.COPY_DST??8,Xa=globalThis.GPUBufferUsage?.COPY_SRC??4,Va=globalThis.GPUBufferUsage?.UNIFORM??64,Ga=globalThis.GPUBufferUsage?.MAP_READ??1,qa=globalThis.GPUMapMode?.READ??1;async function Ha(){const t=Di();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 Za(){return Dt||(Dt=(async()=>{const t=Di();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:Ya}),entryPoint:"main"}});return{device:n,pipeline:i,bindGroupLayout:r}})(),Dt)}function kt(t,e){return Math.ceil(t/e)*e}async function Ni(t,e,n){const r=await Za();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:cn|Bt}),h=r.device.createBuffer({size:kt(l,4),usage:cn|Bt}),d=r.device.createBuffer({size:kt(u,4),usage:cn|Xa}),m=r.device.createBuffer({size:16,usage:Va|Bt}),g=r.device.createBuffer({size:kt(u,4),usage:Bt|Ga});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(qa),y=!0;const E=g.getMappedRange();return new Uint32Array(E.slice(0))}finally{if(y)try{g.unmap()}catch{}c.destroy(),h.destroy(),d.destroy(),m.destroy(),g.destroy()}}async function Bi(t,e,n={}){const r=ye(),i=n.bridgeToDraw===!0;if(!t||!t.count||!t.positions||!t.paletteIndices)return{data:null,meta:{mode:"hybrid-webgpu",durationMs:ye()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}};const o=dt(e??[]);if(o.length===0){const E={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return t.fillModes instanceof Uint8Array&&(E.fillModes=new Uint8Array(0)),t.ids instanceof Uint32Array&&(E.ids=new Uint32Array(0)),{data:E,meta:{mode:"hybrid-webgpu",durationMs:ye()-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 E={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(E.fillModes=new Uint8Array(0)),l&&(E.ids=new Uint32Array(0)),{data:E,meta:{mode:"hybrid-webgpu",durationMs:ye()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const u=new Float32Array(o.length*4);for(let E=0;E<o.length;E+=1){const M=E*4,C=o[E];u[M]=C.minX,u[M+1]=C.minY,u[M+2]=C.maxX,u[M+3]=C.maxY}let f=null,c=!1;try{f=await Ni(t.positions,s,u),c=!!f}catch{f=null,c=!1}if(!f)return{data:Rt(t,e),meta:{mode:"hybrid-webgpu",durationMs:ye()-r,usedWebGpu:!1,candidateCount:s,bridgedToDraw:!1}};let h=0;for(let E=0;E<s;E+=1)f[E]===1&&(h+=1);const d=new Uint32Array(h);if(h>0){let E=0;for(let M=0;M<s;M+=1)f[M]===1&&(d[E]=M,E+=1)}if(h===0){if(i){const M={count:s,positions:t.positions.subarray(0,s*2),paletteIndices:t.paletteIndices.subarray(0,s),drawIndices:new Uint32Array(0)};return a&&(M.fillModes=a.subarray(0,s)),l&&(M.ids=l.subarray(0,s)),{data:M,meta:{mode:"hybrid-webgpu",durationMs:ye()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!0}}}const E={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(E.fillModes=new Uint8Array(0)),l&&(E.ids=new Uint32Array(0)),{data:E,meta:{mode:"hybrid-webgpu",durationMs:ye()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!1}}}if(i){const E=new Uint32Array(h);let M=0;for(let T=0;T<h;T+=1){const k=d[T]??0,X=t.positions[k*2],N=t.positions[k*2+1];St(X,N,o)&&(E[M]=k,M+=1)}const C={count:s,positions:t.positions.subarray(0,s*2),paletteIndices:t.paletteIndices.subarray(0,s),drawIndices:E.subarray(0,M)};return a&&(C.fillModes=a.subarray(0,s)),l&&(C.ids=l.subarray(0,s)),{data:C,meta:{mode:"hybrid-webgpu",durationMs:ye()-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 E=0;E<h;E+=1){const M=d[E]??0,C=t.positions[M*2],T=t.positions[M*2+1];St(C,T,o)&&(m[x*2]=C,m[x*2+1]=T,g[x]=t.paletteIndices[M],y&&(y[x]=a[M]),b&&(b[x]=l[M]),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:ye()-r,usedWebGpu:!0,candidateCount:h,bridgedToDraw:!1}}}class ki{constructor(e,n){S(this,"worker",null);S(this,"supported",!0);S(this,"requestId",1);S(this,"pendingById",new Map);S(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))});S(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 ki(()=>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:ye()-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:ye()-e.startMs}})},rejectPending:(t,e)=>{t.reject(e)}});function $a(){At.terminate("worker terminated")}async function Ui(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=ye(),f=At.beginRequest({kind:"data",resolve:a,reject:l,startMs:u});if(!f){a({data:Rt(t,e),meta:{mode:"sync",durationMs:ye()-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 Ka(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=ye(),a=At.beginRequest({kind:"index",resolve:i,reject:o,startMs:s});if(!a){i({indices:Fi(t,e),meta:{mode:"sync",durationMs:ye()-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 Ja(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 Bi(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 Ui(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 Qa=24,el=1024,tl=4,Xt=-1;function pt(t,e,n){return(t*73856093^e*19349663)>>>0&n}function nl(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))*tl;return Math.max(Qa,Math.min(el,o))}function rl(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 il(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=rl(t.drawIndices??null,r),o=i?i.length:r;if(o===0)return null;const s=nl(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 O=i[F],$=t.positions[O*2],W=t.positions[O*2+1];!Number.isFinite($)||!Number.isFinite(W)||(l[f]=Math.floor($*a),u[f]=Math.floor(W*a),f+=1)}else for(let F=0;F<r;F+=1){const O=t.positions[F*2],$=t.positions[F*2+1];!Number.isFinite(O)||!Number.isFinite($)||(l[f]=Math.floor(O*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 y=0;const b=new Int32Array(f);for(let F=0;F<f;F+=1){const O=l[F],$=u[F];let W=pt(O,$,d);for(;;){const J=m[W*2];if(J===2147483647){if(m[W*2]=O,m[W*2+1]=$,g[W]=1,b[F]=W,y+=1,y*4>h*3){const he=h;h<<=1,d=h-1;const K=new Int32Array(h*2),Pe=new Int32Array(h);K.fill(2147483647);for(let Ae=0;Ae<he;Ae+=1){if(m[Ae*2]===2147483647)continue;const we=m[Ae*2],v=m[Ae*2+1];let I=pt(we,v,d);for(;K[I*2]!==2147483647;)I=I+1&d;K[I*2]=we,K[I*2+1]=v,Pe[I]=g[Ae]}for(m=K,g=Pe,W=pt(O,$,d);m[W*2]!==O||m[W*2+1]!==$;)W=W+1&d;b[F]=W}break}if(J===O&&m[W*2+1]===$){g[W]+=1,b[F]=W;break}W=W+1&d}}const x=new Int32Array(y*2),A=new Uint32Array(y),E=new Uint32Array(y),M=new Int32Array(h);M.fill(Xt);let C=0,T=0;for(let F=0;F<h;F+=1)m[F*2]!==2147483647&&(x[C*2]=m[F*2],x[C*2+1]=m[F*2+1],A[C]=T,E[C]=g[F],M[F]=C,T+=g[F],C+=1);const k=new Uint32Array(f),X=new Uint32Array(y);if(X.set(A),i)for(let F=0;F<f;F+=1){const O=M[b[F]];k[X[O]]=i[F],X[O]+=1}else{let F=0;for(let O=0;O<r;O+=1){const $=t.positions[O*2],W=t.positions[O*2+1];if(!Number.isFinite($)||!Number.isFinite(W))continue;const J=M[b[F]];k[X[J]]=O,X[J]+=1,F+=1}}let N=1;for(;N<y*2;)N<<=1;const P=N-1,z=new Int32Array(N);z.fill(Xt);for(let F=0;F<y;F+=1){const O=x[F*2],$=x[F*2+1];let W=pt(O,$,P);for(;z[W]!==Xt;)W=W+1&P;z[W]=F}return{cellSize:s,safeCount:r,cellCount:y,hashCapacity:N,hashTable:z,cellKeys:x,cellOffsets:A,cellLengths:E,pointIndices:k}}function zi(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 ol(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 ki(()=>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(ol(t,e.pointData))},rejectPending:(t,e)=>{t.reject(e)}});function sl(){Mn.terminate("worker terminated")}function al(t,e){const n=st(t);if(n<=0)return null;const r=t.positions.subarray(0,n*2),i=il({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 Oi(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(al(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 ll=.65,cl=4;function ul(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 Oi(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 E=Math.max(1e-6,b.getViewState().zoom),M=b.getPointSizeByZoom(a),T=Math.max(cl,M*ll)/E;if(!Number.isFinite(T)||T<=0)return null;const{cellSize:k,cellOffsets:X,cellLengths:N,pointIndices:P,positions:z,safeCount:F}=u,O=Math.floor(x/k),$=Math.floor(A/k),W=Math.max(1,Math.ceil(T/k)),J=T*T;let he=-1,K=J,Pe=0,Ae=0;for(let v=O-W;v<=O+W;v+=1)for(let I=$-W;I<=$+W;I+=1){const U=zi(u,v,I);if(U<0)continue;const oe=X[U],j=oe+N[U];for(let ue=oe;ue<j;ue+=1){const ee=P[ue];if(ee>=F)continue;const de=z[ee*2],se=z[ee*2+1],pe=de-x,Q=se-A,ae=pe*pe+Q*Q;ae>K||(K=ae,he=ee,Pe=de,Ae=se)}}if(he<0)return null;const we=u.ids?Number(u.ids[he]):null;return{index:he,id:we,coordinate:[x,A],pointCoordinate:[Pe,Ae]}},[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 fl=0;const hl=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__${fl++}`),M=Ja(a,u,e,l??dl,f),{getCellByCoordinates:C}=ul(M,b,c,h,x,"cursor",g,A.current);return p.useImperativeHandle(m,()=>({queryAt:C}),[C]),p.useEffect(()=>{const T=g.current;if(!T)return;const k=A.current;return T.registerPointLayer(k),()=>{T.unregisterPointLayer(k)}},[g,y]),p.useEffect(()=>{const T=g.current;T&&T.setPointPalette(n,A.current)},[y,n,g]),p.useEffect(()=>{const T=g.current;T&&T.setPointLineDash(d,A.current)},[y,d,g]),p.useEffect(()=>{const T=g.current;!T||r===void 0||T.setPointSizeByZoom(r,A.current)},[y,r,g]),p.useEffect(()=>{const T=g.current;!T||i===void 0||T.setPointOpacity(i,A.current)},[y,i,g]),p.useEffect(()=>{const T=g.current;!T||o===void 0||T.setPointStrokeScale(o,A.current)},[y,o,g]),p.useEffect(()=>{const T=g.current;!T||s===void 0||T.setPointInnerFillOpacity(s,A.current)},[y,s,g]),p.useEffect(()=>{const T=g.current;T&&T.setPointData(M,A.current)},[y,M,g]),null}),dl=[],ml=180,Br=20;function gl(t){const e=_(t,0,1);return e*e*(3-2*e)}function pl(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=_(c,0,Br);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=_(c,0,Br),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=_(x/ml,0,1),E=gl(A),M=b.from+(b.to-b.from)*E;if(a(M),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=zn(t,c,h.getZoomRange(),h.getRegionLabelAutoLiftCapZoom());u(d)},[t,u]);return p.useEffect(()=>()=>{l()},[l]),{regionLabelAutoLiftOffsetPx:r,syncRegionLabelAutoLiftTarget:f,cancelRegionLabelAutoLiftAnimation:l,applyRegionLabelAutoLiftOffset:a}}const yl=6;function Cn(t,e){return t.id??e}function bl(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=_(((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 kr(t,e,n,r){for(let i=1;i<n.length;i+=1){const o=n[i-1],s=n[i];if(bl(t,e,o[0],o[1],s[0],s[1])<=r)return!0}return!1}function xl(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(kr(t,e,n.outer,i))return!0;for(const o of n.holes)if(kr(t,e,o,i))return!0;return!1}function wl(t,e,n,r,i,o,s){if(!t.label||!t.labelAnchor)return!1;const a=Fn(n.worldToScreen(t.labelAnchor[0],t.labelAnchor[1]));if(!a)return!1;const u=Nn(t.label,r)+r.paddingX*2,f=r.fontSize+r.paddingY*2,c=a[0],h=a[1]-r.offsetY,d=s?_(c,u*.5+1,i-u*.5-1):c,m=s?_(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 Sl(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:Cn(i,r),polygons:o,label:s,labelAnchor:s?Bn(o,e):null})}return n}function Ur(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=yl/h;for(let g=n.length-1;g>=0;g-=1){const y=n[g];for(const x of y.polygons)if(xl(f,c,x,m))return{region:y.region,regionIndex:y.regionIndex,regionId:y.regionId};let b=Un(i,o?.({region:y.region,regionId:y.regionId,regionIndex:y.regionIndex,zoom:h}));if(d>0&&(b={...b,offsetY:b.offsetY+d}),!!wl(y,e,r,b,a,l,u))return{region:y.region,regionIndex:y.regionIndex,regionId:y.regionId}}return null}const zr=[],El=[];let Rl=0;function Al(t){return{color:ai,width:li,lineDash:ot,lineJoin:t.lineJoin,lineCap:t.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function Ml({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:E,unregisterDrawCallback:M,requestOverlayRedraw:C,drawInvalidateRef:T,registerViewStateListener:k,screenToWorld:X,worldToScreen:N,isInteractionLocked:P}=at(),z=t??zr,F=e??El,O=p.useMemo(()=>z.length>0?z:F.length===0?zr:F.map((V,Z)=>({id:Z,coordinates:V})),[z,F]),[$,W]=p.useState(()=>f??null),[J,he]=p.useState(()=>c??null),K=f!==void 0,Pe=c!==void 0,Ae=K?f??null:$,we=Pe?c??null:J,v=p.useRef(f??null),I=p.useRef(null),U=p.useRef(null);if(I.current===null||U.current===null){const V=Rl++;I.current=`__region_layer__${V}`,U.current=`__region_label__${V}`}p.useEffect(()=>{Pe&&he(c??null)},[Pe,c]),p.useEffect(()=>{if(!K)return;const V=f??null;v.current=V,W(V)},[K,f]);const oe=p.useCallback(V=>{String(we)!==String(V)&&(Pe||he(V),d?.(V))},[we,Pe,d]),{regionLabelAutoLiftOffsetPx:j,syncRegionLabelAutoLiftTarget:ue}=pl(l,y,T),ee=p.useMemo(()=>Dn(n),[n]),de=p.useMemo(()=>je(ee,r),[ee,r]),se=p.useMemo(()=>je(ee,i),[ee,i]),{staticLabelStyle:pe,labelStyleResolver:Q}=p.useMemo(()=>typeof s=="function"?{staticLabelStyle:void 0,labelStyleResolver:s}:{staticLabelStyle:s,labelStyleResolver:void 0},[s]),ae=p.useMemo(()=>kn(pe),[pe]),fe=p.useMemo(()=>{const V=[];for(let Z=0;Z<O.length;Z+=1){const re=O[Z],ie=jt(re.coordinates);ie.length!==0&&V.push({region:re,regionIndex:Z,regionKey:re.id??Z,polygons:ie})}return V},[O]),Ee=p.useMemo(()=>Sl(O,a),[O,a]);p.useEffect(()=>{const V=y.current;if(V)return ue(V.getViewState().zoom),k(Z=>{ue(Z.zoom)})},[b,k,ue]),p.useEffect(()=>{!(we===null?!0:O.some((ie,Se)=>String(Cn(ie,Se))===String(we)))&&we!==null&&oe(null);const Z=v.current;!(Z===null?!0:O.some((ie,Se)=>String(Cn(ie,Se))===String(Z)))&&Z!==null&&(v.current=null,K||W(null),m?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[O,we,K,m,oe]);const te=p.useCallback(V=>{const Z=y.current;if(!Z||V.length===0)return[];const re=new Array(V.length);for(let ie=0;ie<V.length;ie+=1){const Se=qe(Z.worldToScreen(V[ie][0],V[ie][1]));if(!Se)return[];re[ie]=Se}return re},[]),ve=p.useRef({preparedRegions:fe,hoveredRegionId:Ae,activeRegionId:we,resolvedStrokeStyle:ee,resolvedHoverStrokeStyle:de,resolvedActiveStrokeStyle:se,resolveStrokeStyleProp:o,worldToScreenPoints:te});ve.current={preparedRegions:fe,hoveredRegionId:Ae,activeRegionId:we,resolvedStrokeStyle:ee,resolvedHoverStrokeStyle:de,resolvedActiveStrokeStyle:se,resolveStrokeStyleProp:o,worldToScreenPoints:te},p.useEffect(()=>{const V=re=>{const{preparedRegions:ie,hoveredRegionId:Se,activeRegionId:Y,resolvedStrokeStyle:L,resolvedHoverStrokeStyle:G,resolvedActiveStrokeStyle:q,resolveStrokeStyleProp:ne,worldToScreenPoints:ce}=ve.current;for(const Be of ie){const{region:Me,polygons:Ce,regionIndex:_e,regionKey:Le}=Be,Ie=$t(Y,Le)?"active":$t(Se,Le)?"hover":"default";let w=Ie==="active"?q:Ie==="hover"?G:L;if(ne){const D=ne({region:Me,regionId:Le,regionIndex:_e,state:Ie});w=je(w,D||void 0)}const R=Ie==="default"?null:Al(w);for(const D of Ce){const B=ce(D.outer);B.length>=4&&(R&&Ne(re,B,R,!0,!1),Ne(re,B,w,!0,!1));for(const H of D.holes){const xe=ce(H);xe.length>=4&&(R&&Ne(re,xe,R,!0,!1),Ne(re,xe,w,!0,!1))}}}},Z=I.current;if(Z)return E(Z,10,V),()=>M(Z)},[E,M]);const be=p.useRef({preparedRegions:fe,resolvedLabelStyle:ae,labelStyleResolver:Q,labelAnchor:a,autoLiftLabelAtMaxZoom:l,clampLabelToViewport:u,regionLabelAutoLiftOffsetPx:j,rendererRef:y});be.current={preparedRegions:fe,resolvedLabelStyle:ae,labelStyleResolver:Q,labelAnchor:a,autoLiftLabelAtMaxZoom:l,clampLabelToViewport:u,regionLabelAutoLiftOffsetPx:j,rendererRef:y},p.useEffect(()=>{const V=(re,ie,Se)=>{const{preparedRegions:Y,resolvedLabelStyle:L,labelStyleResolver:G,labelAnchor:q,autoLiftLabelAtMaxZoom:ne,clampLabelToViewport:ce,regionLabelAutoLiftOffsetPx:Be,rendererRef:Me}=be.current;if(Y.length===0)return;const Ce=Math.max(1e-6,Me.current?.getViewState?.().zoom??1),_e=typeof Be=="number"&&Number.isFinite(Be)?Math.max(0,Be):zn(ne,Ce,Me.current?.getZoomRange?.(),Me.current?.getRegionLabelAutoLiftCapZoom?.());for(const Le of Y){if(!Le.region.label)continue;const Ie=Bn(Le.polygons,q);if(!Ie)continue;const w=qe(Me.current?.worldToScreen(Ie[0],Ie[1])??[]);if(!w)continue;let R=Un(L,G?.({region:Le.region,regionId:Le.regionKey,regionIndex:Le.regionIndex,zoom:Ce}));_e>0&&(R={...R,offsetY:R.offsetY+_e}),mi(re,Le.region.label,w,ie,Se,R,ce)}},Z=U.current;if(Z)return E(Z,50,V),()=>M(Z)},[E,M]),p.useEffect(()=>{C()},[fe,Ae,we,ee,ae,j,C]);const me=p.useRef({preparedRegionHits:Ee,resolvedLabelStyle:ae,labelStyleResolver:Q,regionLabelAutoLiftOffsetPx:j,clampLabelToViewport:u,onHover:m,onClick:g,commitActive:oe});return me.current={preparedRegionHits:Ee,resolvedLabelStyle:ae,labelStyleResolver:Q,regionLabelAutoLiftOffsetPx:j,clampLabelToViewport:u,onHover:m,onClick:g,commitActive:oe},p.useEffect(()=>{if(!h)return;const V=A.current;if(!V)return;const Z=Se=>{if(P())return;const Y=y.current;if(!Y)return;const{preparedRegionHits:L,resolvedLabelStyle:G,labelStyleResolver:q,regionLabelAutoLiftOffsetPx:ne,clampLabelToViewport:ce,onHover:Be}=me.current,Me=X(Se.clientX,Se.clientY);if(!Me)return;let Ce=null,_e=null;if(L.length>0){const Ie=N(Me[0],Me[1]);if(Ie){const w=x.current?.getBoundingClientRect();_e=Ur(Me,Ie,L,Y,G,q,typeof ne=="number"?ne:0,w?.width??0,w?.height??0,ce),Ce=_e?.regionId??null}}const Le=v.current;String(Le)!==String(Ce)&&(v.current=Ce,K||W(Ce),Be?.({region:_e?.region??null,regionId:Ce,regionIndex:_e?.regionIndex??-1,coordinate:Me}),C())},re=Se=>{if(P())return;const Y=y.current;if(!Y)return;const{preparedRegionHits:L,resolvedLabelStyle:G,labelStyleResolver:q,regionLabelAutoLiftOffsetPx:ne,clampLabelToViewport:ce,onClick:Be,commitActive:Me}=me.current;if(L.length===0)return;const Ce=X(Se.clientX,Se.clientY);if(!Ce)return;const _e=N(Ce[0],Ce[1]);if(!_e)return;const Le=x.current?.getBoundingClientRect(),Ie=Ur(Ce,_e,L,Y,G,q,typeof ne=="number"?ne:0,Le?.width??0,Le?.height??0,ce),w=Ie?.regionId??null;Me(w),Ie&&Be&&Be({region:Ie.region,regionId:Ie.regionId,regionIndex:Ie.regionIndex,coordinate:Ce})},ie=()=>{v.current!==null&&(v.current=null,K||W(null),me.current.onHover?.({region:null,regionId:null,regionIndex:-1,coordinate:null}),C())};return V.addEventListener("pointermove",Z),V.addEventListener("click",re),V.addEventListener("pointerleave",ie),()=>{V.removeEventListener("pointermove",Z),V.removeEventListener("click",re),V.removeEventListener("pointerleave",ie)}},[A,y,x,h,K,X,N,P,C]),null}function Cl({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 Qr({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 Pl(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 Yi{constructor(e){S(this,"maxConcurrency");S(this,"maxRetries");S(this,"retryBaseDelayMs");S(this,"retryMaxDelayMs");S(this,"onTileLoad");S(this,"onTileError");S(this,"onStateChange");S(this,"authToken");S(this,"destroyed",!1);S(this,"queue",[]);S(this,"queuedByKey",new Map);S(this,"inflight",new Map);S(this,"visibleKeys",new Set);S(this,"timerId",null);S(this,"abortedCount",0);S(this,"retryCount",0);S(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:ye()};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-ye());this.timerId=globalThis.setTimeout(()=>{this.timerId=null,this.pump()},n)}takeNextReadyQueueItem(){if(this.queue.length===0)return null;const e=ye(),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=Pl(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:ye()+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 Tl(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 vl(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 Il(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 Pn=.35,Tn=.5,_l=256,vn=[{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}],Ll=.1,Fl=5,Dl=0,Nl=1,Bl=0,kl=1,Ul=-100,zl=100,Ol=2e3;function tn(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 Qt(t){return t.map(e=>({zoom:e.zoom,size:e.size}))}function Or(t){if(!t)return Qt(vn);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?Qt(vn):Array.from(e.entries()).sort((n,r)=>n[0]-r[0]).map(([n,r])=>({zoom:n,size:r}))}function Yl(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 Wl(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=_((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 Yr(t){return typeof t!="number"||!Number.isFinite(t)?1:_(t,Ll,Fl)}function Wr(t){return typeof t!="number"||!Number.isFinite(t)?1:_(t,Dl,Nl)}function Xl(t){return t?[_(t[0],0,100),_(t[1],0,100)]:[1,0]}function Xr(t){return typeof t!="number"||!Number.isFinite(t)?0:_(t,Bl,kl)}function un(t){return typeof t!="number"||!Number.isFinite(t)?0:_(t,Ul,zl)}function Vr(t){const e=un(t?.brightness),n=un(t?.contrast),r=un(t?.saturation);return{brightness:e/200,contrast:n/100,saturation:r/100}}function Vn(t){return t}function fn(t){return typeof t!="number"||!Number.isFinite(t)?0:_(t,0,Ol)}function zt(t){return typeof t!="number"||!Number.isFinite(t)||t<=0?null:Math.max(1e-6,t)}function hn(t){return typeof t=="function"?t:Vn}function Wi(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 Xi(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 Vl(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"?Wi(n,e.clientX,e.clientY):null,n.classList.add("dragging"),n.setPointerCapture(e.pointerId))}function Gl(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=Wi(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/Pn,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=tn(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 ql(t,e,n){t.pointerId===n.pointerId&&Xi(e,n)}function Hl(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 Zl=4;function $l(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)<Zl)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 Kl(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?_(u,d,m):e.width*.5,x=g<=y?_(f,g,y):e.height*.5;t.setCenter(b,x)}function Jl(t,e){const n=Math.max(1e-6,t.getViewState().zoom),r=e.maxTierZoom+Math.log2(n);return _(Math.floor(r),0,e.maxTierZoom)}function Ql(t,e){return!(t[2]<=e[0]||t[0]>=e[2]||t[3]<=e[1]||t[1]>=e[3])}function Vi(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=_(Math.floor(u/i/e.tileSize),0,a-1),m=_(Math.floor((c-1)/i/e.tileSize),0,a-1),g=_(Math.floor(f/i/e.tileSize),0,l-1),y=_(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 E=g;E<=y;E+=1)for(let M=d;M<=m;M+=1){const C=M*e.tileSize*i,T=E*e.tileSize*i,k=Math.min((M+1)*e.tileSize,o)*i,X=Math.min((E+1)*e.tileSize,s)*i,N=M-b,P=E-x;A.push({key:`${n}/${M}/${E}`,tier:n,x:M,y:E,bounds:[C,T,k,X],distance2:N*N+P*P,url:Xn(e,n,M,E)})}return A.sort((E,M)=>E.distance2-M.distance2),A}function ec(t,e){const n=Jl(t,e);return{tier:n,visible:Vi(t,e,n)}}function tc(t){t.interactionLocked||Vl({event:t.event,canvas:t.canvas,state:t.state,config:{ctrlDragRotate:t.ctrlDragRotate,rotationDragSensitivityDegPerPixel:t.rotationDragSensitivityDegPerPixel},cancelViewAnimation:t.cancelViewAnimation})}function nc(t){t.interactionLocked||Gl({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 rc(t){t.interactionLocked||ql(t.event,t.canvas,t.state)}function ic(t){t.interactionLocked||Kl({event:t.event,canvas:t.canvas,onZoomBy:t.onZoomBy})}function oc(t){jl(t.event,t.state.dragging)}function sc(t,e){Xi(t,e)}function ac(t){return{pointerDown:e=>tc({event:e,interactionLocked:t.getInteractionLocked(),canvas:t.canvas,state:t.state,ctrlDragRotate:t.getCtrlDragRotate(),rotationDragSensitivityDegPerPixel:t.getRotationDragSensitivityDegPerPixel(),cancelViewAnimation:t.cancelViewAnimation}),pointerMove:e=>nc({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=>rc({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){$l({event:e,canvas:t.canvas,snapState:t.zoomSnapState,onSnapZoom:t.onSnapZoom});return}Hl({event:e,canvas:t.canvas,onZoomBy:t.zoomBy})},doubleClick:e=>ic({event:e,interactionLocked:t.getInteractionLocked(),canvas:t.canvas,onZoomBy:t.zoomBy}),contextMenu:e=>oc({event:e,canvas:t.canvas,state:t.state})}}function lc(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 cc(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 uc(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=cc(e,i);i.close(),f&&(n.set(r.key,{key:r.key,texture:f,bounds:r.bounds,tier:r.tier,lastUsed:o}),lc({gl:e,cache:n,maxCacheTiles:s}),u())}function fc(t,e){for(const[,n]of e)t.deleteTexture(n.texture)}function hc(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 dc(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.removeCanvasEventListeners(),t.cancelDrag(),t.tileScheduler.destroy(),!t.contextLost&&!t.gl.isContextLost()){fc(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 mc(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 gc(t,e){return e<=0?new Uint8Array(0):t.length<e?new Uint8Array(e):t.subarray(0,e)}function Gr(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?mc(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=gc(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 pc(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,P)=>N.tier-P.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 E=[];for(const N of g){const P=i.get(N.key);if(!P){E.push(N);continue}P.lastUsed=o,e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,P.texture),e.uniform4f(s.uBounds,P.bounds[0],P.bounds[1],P.bounds[2],P.bounds[3]),e.drawArrays(e.TRIANGLE_STRIP,0,4),A+=1}const M=E.slice(),C=1e6,T=[];m>0&&T.push(m-1),m<r.maxTierZoom&&T.push(m+1);for(const N of T){const P=c(N);for(const z of P)i.has(z.key)||(z.distance2+=C,M.push(z))}u.schedule(M),e.bindTexture(e.TEXTURE_2D,null),e.bindVertexArray(null);let k=0,X=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 P=l[N];P.pointCount<=0||(e.useProgram(P.pointProgram.program),e.bindVertexArray(P.pointProgram.vao),e.uniformMatrix3fv(P.pointProgram.uCamera,!1,n.getMatrix()),e.uniform1f(P.pointProgram.uPointSize,P.pointSizePx),e.uniform2f(P.pointProgram.uPointLineDash,P.pointLineDash[0],P.pointLineDash[1]),e.uniform1f(P.pointProgram.uPointOpacity,P.pointOpacity),e.uniform1f(P.pointProgram.uPointStrokeScale,P.pointStrokeScale),e.uniform1f(P.pointProgram.uPointInnerFillAlpha,P.pointInnerFillOpacity),e.uniform1f(P.pointProgram.uPaletteSize,P.pointPaletteSize),e.uniform1i(P.pointProgram.uPalette,1),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,P.pointProgram.paletteTexture),P.usePointIndices?e.drawElements(e.POINTS,P.pointCount,e.UNSIGNED_INT,0):e.drawArrays(e.POINTS,0,P.pointCount),k+=P.pointCount,X+=1)}e.bindTexture(e.TEXTURE_2D,null),e.bindVertexArray(null)}return{tier:m,visible:g.length,rendered:A,points:k,fallback:x.length,cacheHits:A,cacheMisses:E.length,drawCalls:x.length+A+X}}function Hr(t){const r=bt(t,`#version 300 es
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}}]}),w=r.device.createCommandEncoder(),A=w.beginComputePass();A.setPipeline(r.pipeline),A.setBindGroup(0,b),A.dispatchWorkgroups(Math.ceil(s/256)),A.end(),w.copyBufferToBuffer(d,0,g,0,u),r.device.queue.submit([w.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=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 ki(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 U=d[P]??0,Y=t.positions[U*2],N=t.positions[U*2+1];St(Y,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:we()-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 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],y&&(y[w]=a[C]),b&&(b[w]=l[C]),w+=1)}const A={count:w,positions:m.subarray(0,w*2),paletteIndices:g.subarray(0,w)};return y&&(A.fillModes=y.subarray(0,w)),b&&(A.ids=b.subarray(0,w)),{data:A,meta:{mode:"hybrid-webgpu",durationMs:we()-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: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 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=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 Qa(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:Ni(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 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],W=t.positions[z*2+1];!Number.isFinite(K)||!Number.isFinite(W)||(l[f]=Math.floor(K*a),u[f]=Math.floor(W*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 W=pt(z,K,d);for(;;){const j=m[W*2];if(j===2147483647){if(m[W*2]=z,m[W*2+1]=K,g[W]=1,b[F]=W,y+=1,y*4>h*3){const ce=h;h<<=1,d=h-1;const Q=new Int32Array(h*2),Te=new Int32Array(h);Q.fill(2147483647);for(let ve=0;ve<ce;ve+=1){if(m[ve*2]===2147483647)continue;const Ae=m[ve*2],I=m[ve*2+1];let T=pt(Ae,I,d);for(;Q[T*2]!==2147483647;)T=T+1&d;Q[T*2]=Ae,Q[T*2+1]=I,Te[T]=g[ve]}for(m=Q,g=Te,W=pt(z,K,d);m[W*2]!==z||m[W*2+1]!==K;)W=W+1&d;b[F]=W}break}if(j===z&&m[W*2+1]===K){g[W]+=1,b[F]=W;break}W=W+1&d}}const w=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&&(w[M*2]=m[F*2],w[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),Y=new Uint32Array(y);if(Y.set(A),i)for(let F=0;F<f;F+=1){const z=C[b[F]];U[Y[z]]=i[F],Y[z]+=1}else{let F=0;for(let z=0;z<r;z+=1){const K=t.positions[z*2],W=t.positions[z*2+1];if(!Number.isFinite(K)||!Number.isFinite(W))continue;const j=C[b[F]];U[Y[j]]=z,Y[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=w[F*2],K=w[F*2+1];let W=pt(z,K,v);for(;B[W]!==Xt;)W=W+1&v;B[W]=F}return{cellSize:s,safeCount:r,cellCount:y,hashCapacity:N,hashTable:B,cellKeys:w,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=ot(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=ot(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 w=Number(y[0]),A=Number(y[1]);if(!Number.isFinite(w)||!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:Y,cellLengths:N,pointIndices:v,positions:B,safeCount:F}=u,z=Math.floor(w/U),K=Math.floor(A/U),W=Math.max(1,Math.ceil(P/U)),j=P*P;let ce=-1,Q=j,Te=0,ve=0;for(let I=z-W;I<=z+W;I+=1)for(let T=K-W;T<=K+W;T+=1){const X=Yi(u,I,T);if(X<0)continue;const q=Y[X],ee=q+N[X];for(let le=q;le<ee;le+=1){const re=v[le];if(re>=F)continue;const pe=B[re*2],te=B[re*2+1],ye=pe-w,fe=te-A,se=ye*ye+fe*fe;se>Q||(Q=se,ce=re,Te=pe,ve=te)}}if(ce<0)return null;const Ae=u.ids?Number(u.ids[ce]):null;return{index:ce,id:Ae,coordinate:[w,A],pointCoordinate:[Te,ve]}},[a,u]),m=p.useCallback((y,b)=>{if(!n)return;const w=y?.index??null,A=y?.id??null;c.current===w&&h.current===A||(c.current=w,h.current=A,n({index:w,id:A,coordinate:b,pointCoordinate:y?.pointCoordinate??null}))},[n]),g=p.useCallback((y,b)=>{if(!r)return;const w=d(y);w&&r({...w,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}=st(),w=p.useRef(null),A=p.useRef(`__point_layer__${dl++}`),C=el(a,u,e,l??gl,f),{getCellByCoordinates:M}=hl(C,b,c,h,w,"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,w=Math.max(0,y-b.startMs),A=L(w/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,a){if(!t.label)return!1;const l=kn(t.polygons,S=>{const C=[];for(let M=0;M<S.length;M+=1){const P=Dn(n.worldToScreen(S[M][0],S[M][1]));if(!P)return[];C.push(P)}return C},r);if(!l)return!1;const f=Bn(t.label,i)+i.paddingX*2,c=i.fontSize+i.paddingY*2,h=l[0],d=l[1]-i.offsetY,m=a?L(h,f*.5+1,o-f*.5-1):h,g=a?L(d,c*.5+1,s-c*.5-1):d,y=m-f*.5,b=m+f*.5,w=g-c*.5,A=g+c*.5;return e[0]>=y&&e[0]<=b&&e[1]>=w&&e[1]<=A}function Rl(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:Pn(r,n),polygons:i,label:o})}return e}function Or(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=xl/d;for(let y=n.length-1;y>=0;y-=1){const b=n[y];for(const A of b.polygons)if(Sl(c,h,A,g))return{region:b.region,regionIndex:b.regionIndex,regionId:b.regionId};let w=zn(o,s?.({region:b.region,regionId:b.regionId,regionIndex:b.regionIndex,zoom:d}));if(m>0&&(w={...w,offsetY:w.offsetY+m}),!!El(b,e,r,i,w,l,u,f))return{region:b.region,regionIndex:b.regionIndex,regionId:b.regionId}}return null}const Yr=[],Al=[];let Cl=0;function Ml(t){return{color:ci,width:ui,lineDash:it,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:w,containerRef:A,registerDrawCallback:S,unregisterDrawCallback:C,requestOverlayRedraw:M,drawInvalidateRef:P,registerViewStateListener:U,screenToWorld:Y,worldToScreen:N,isInteractionLocked:v}=st(),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,W]=p.useState(()=>f??null),[j,ce]=p.useState(()=>c??null),Q=f!==void 0,Te=c!==void 0,ve=Q?f??null:K,Ae=Te?c??null:j,I=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(!Q)return;const V=f??null;I.current=V,W(V)},[Q,f]);const q=p.useCallback(V=>{String(Ae)!==String(V)&&(Te||ce(V),d?.(V))},[Ae,Te,d]),{regionLabelAutoLiftOffsetPx:ee,syncRegionLabelAutoLiftTarget:le}=bl(l,y,P),re=p.useMemo(()=>Nn(n),[n]),pe=p.useMemo(()=>Ke(re,r),[re,r]),te=p.useMemo(()=>Ke(re,i),[re,i]),{staticLabelStyle:ye,labelStyleResolver:fe}=p.useMemo(()=>typeof s=="function"?{staticLabelStyle:void 0,labelStyleResolver:s}:{staticLabelStyle:s,labelStyleResolver:void 0},[s]),se=p.useMemo(()=>Un(ye),[ye]),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]),Me=p.useMemo(()=>Rl(z),[z]);p.useEffect(()=>{const V=y.current;if(V)return le(V.getViewState().zoom),U($=>{le($.zoom)})},[b,U,le]),p.useEffect(()=>{!(Ae===null?!0:z.some((oe,Ee)=>String(Pn(oe,Ee))===String(Ae)))&&Ae!==null&&q(null);const $=I.current;!($===null?!0:z.some((oe,Ee)=>String(Pn(oe,Ee))===String($)))&&$!==null&&(I.current=null,Q||W(null),m?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[z,Ae,Q,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 Ee=He($.worldToScreen(V[oe][0],V[oe][1]));if(!Ee)return[];ie[oe]=Ee}return ie},[]),Ie=p.useRef({preparedRegions:ue,hoveredRegionId:ve,activeRegionId:Ae,resolvedStrokeStyle:re,resolvedHoverStrokeStyle:pe,resolvedActiveStrokeStyle:te,resolveStrokeStyleProp:o,worldToScreenPoints:H});Ie.current={preparedRegions:ue,hoveredRegionId:ve,activeRegionId:Ae,resolvedStrokeStyle:re,resolvedHoverStrokeStyle:pe,resolvedActiveStrokeStyle:te,resolveStrokeStyleProp:o,worldToScreenPoints:H},p.useEffect(()=>{const V=ie=>{const{preparedRegions:oe,hoveredRegionId:Ee,activeRegionId:Fe,resolvedStrokeStyle:G,resolvedHoverStrokeStyle:be,resolvedActiveStrokeStyle:xe,resolveStrokeStyleProp:_,worldToScreenPoints:O}=Ie.current;for(const J of oe){const{region:ne,polygons:Re,regionIndex:me,regionKey:Ce}=J,De=$t(Fe,Ce)?"active":$t(Ee,Ce)?"hover":"default";let x=De==="active"?xe:De==="hover"?be:G;if(_){const D=_({region:ne,regionId:Ce,regionIndex:me,state:De});x=Ke(x,D||void 0)}const R=De==="default"?null:Ml(x);for(const D of Re){const k=O(D.outer);k.length>=4&&(R&&ke(ie,k,R,!0,!1),ke(ie,k,x,!0,!1));for(const Z of D.holes){const de=O(Z);de.length>=4&&(R&&ke(ie,de,R,!0,!1),ke(ie,de,x,!0,!1))}}}},$=T.current;if($)return S($,10,V),()=>C($)},[S,C]);const Se=p.useRef({preparedRegions:ue,resolvedLabelStyle:se,labelStyleResolver:fe,labelAnchor:a,autoLiftLabelAtMaxZoom:l,clampLabelToViewport:u,regionLabelAutoLiftOffsetPx:ee,rendererRef:y});Se.current={preparedRegions:ue,resolvedLabelStyle:se,labelStyleResolver:fe,labelAnchor:a,autoLiftLabelAtMaxZoom:l,clampLabelToViewport:u,regionLabelAutoLiftOffsetPx:ee,rendererRef:y},p.useEffect(()=>{const V=(ie,oe,Ee)=>{const{preparedRegions:Fe,resolvedLabelStyle:G,labelStyleResolver:be,labelAnchor:xe,autoLiftLabelAtMaxZoom:_,clampLabelToViewport:O,regionLabelAutoLiftOffsetPx:J,rendererRef:ne}=Se.current;if(Fe.length===0)return;const Re=Math.max(1e-6,ne.current?.getViewState?.().zoom??1),me=typeof J=="number"&&Number.isFinite(J)?Math.max(0,J):On(_,Re,ne.current?.getZoomRange?.(),ne.current?.getRegionLabelAutoLiftCapZoom?.());for(const Ce of Fe){if(!Ce.region.label)continue;const De=kn(Ce.polygons,R=>{const D=ne.current;if(!D)return[];const k=[];for(let Z=0;Z<R.length;Z+=1){const de=He(D.worldToScreen(R[Z][0],R[Z][1]));if(!de)return[];k.push(de)}return k},xe);if(!De)continue;let x=zn(G,be?.({region:Ce.region,regionId:Ce.regionKey,regionIndex:Ce.regionIndex,zoom:Re}));me>0&&(x={...x,offsetY:x.offsetY+me}),pi(ie,Ce.region.label,De,oe,Ee,x,O)}},$=X.current;if($)return S($,50,V),()=>C($)},[S,C]),p.useEffect(()=>{M()},[ue,ve,Ae,re,se,ee,M]);const he=p.useRef({preparedRegionHits:Me,labelAnchor:a,resolvedLabelStyle:se,labelStyleResolver:fe,regionLabelAutoLiftOffsetPx:ee,clampLabelToViewport:u,onHover:m,onClick:g,commitActive:q});return he.current={preparedRegionHits:Me,labelAnchor:a,resolvedLabelStyle:se,labelStyleResolver:fe,regionLabelAutoLiftOffsetPx:ee,clampLabelToViewport:u,onHover:m,onClick:g,commitActive:q},p.useEffect(()=>{if(!h)return;const V=A.current;if(!V)return;const $=Ee=>{if(v())return;const Fe=y.current;if(!Fe)return;const{preparedRegionHits:G,labelAnchor:be,resolvedLabelStyle:xe,labelStyleResolver:_,regionLabelAutoLiftOffsetPx:O,clampLabelToViewport:J,onHover:ne}=he.current,Re=Y(Ee.clientX,Ee.clientY);if(!Re)return;let me=null,Ce=null;if(G.length>0){const x=N(Re[0],Re[1]);if(x){const R=w.current?.getBoundingClientRect();Ce=Or(Re,x,G,Fe,be,xe,_,typeof O=="number"?O:0,R?.width??0,R?.height??0,J),me=Ce?.regionId??null}}const De=I.current;String(De)!==String(me)&&(I.current=me,Q||W(me),ne?.({region:Ce?.region??null,regionId:me,regionIndex:Ce?.regionIndex??-1,coordinate:Re}),M())},ie=Ee=>{if(v())return;const Fe=y.current;if(!Fe)return;const{preparedRegionHits:G,labelAnchor:be,resolvedLabelStyle:xe,labelStyleResolver:_,regionLabelAutoLiftOffsetPx:O,clampLabelToViewport:J,onClick:ne,commitActive:Re}=he.current;if(G.length===0)return;const me=Y(Ee.clientX,Ee.clientY);if(!me)return;const Ce=N(me[0],me[1]);if(!Ce)return;const De=w.current?.getBoundingClientRect(),x=Or(me,Ce,G,Fe,be,xe,_,typeof O=="number"?O:0,De?.width??0,De?.height??0,J),R=x?.regionId??null;Re(R),x&&ne&&ne({region:x.region,regionId:x.regionId,regionIndex:x.regionIndex,coordinate:me})},oe=()=>{I.current!==null&&(I.current=null,Q||W(null),he.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,w,h,Q,Y,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]),Ge.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: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=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: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 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,w=g<=y?L(f,g,y):e.height*.5;t.setCenter(b,w)}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,w=(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,Y=Math.min((S+1)*e.tileSize,s)*i,N=C-b,v=S-w;A.push({key:`${n}/${C}/${S}`,tier:n,x:C,y:S,bounds:[M,P,U,Y],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 w=b.lastPointData;if(!w)return b;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=yc(b.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),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:w.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 w=[];for(const[,N]of i)b.has(N.key)||d(N.bounds,y)&&w.push(N);w.sort((N,v)=>N.tier-v.tier);for(const N of w)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,Y=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,Y+=1)}e.bindTexture(e.TEXTURE_2D,null),e.bindVertexArray(null)}return{tier:m,visible:g.length,rendered:A,points:U,fallback:w.length,cacheHits:A,cacheMisses:S.length,drawCalls:w.length+A+Y}}function $r(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 Zr(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 Kr(t){const r=bt(t,`#version 300 es
180
180
  precision highp float;
181
181
  in vec2 aPosition;
182
182
  in uint aClass;
@@ -199,6 +199,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
199
199
  uniform sampler2D uPalette;
200
200
  uniform float uPaletteSize;
201
201
  uniform float uPointSize;
202
+ uniform float uPointCssSize;
202
203
  uniform float uPointOpacity;
203
204
  uniform float uPointStrokeScale;
204
205
  uniform float uPointInnerFillAlpha;
@@ -223,13 +224,13 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
223
224
  outColor = vec4(color.rgb * alpha, alpha);
224
225
  } else {
225
226
  float s = uPointStrokeScale;
226
- float ringWidth = s * mix(0.18, 0.35, smoothstep(3.0, 16.0, uPointSize));
227
+ float ringWidth = s * mix(0.18, 0.35, smoothstep(3.0, 16.0, uPointCssSize));
227
228
  float innerRadius = 1.0 - ringWidth;
228
229
  float innerMask = smoothstep(innerRadius - aa, innerRadius + aa, r);
229
230
  float dashMask = 1.0;
230
231
  if (uPointLineDash.x > 0.0 && uPointLineDash.y > 0.0) {
231
232
  float angle01 = (atan(pc.y, pc.x) + PI) / (2.0 * PI);
232
- float circumferencePx = max(1.0, 2.0 * PI * max(0.5, uPointSize * 0.5));
233
+ float circumferencePx = max(1.0, 2.0 * PI * max(0.5, uPointCssSize * 0.5));
233
234
  float dashCycle = uPointLineDash.x + uPointLineDash.y;
234
235
  float dashOffset = mod(angle01 * circumferencePx, dashCycle);
235
236
  dashMask = dashOffset <= uPointLineDash.x ? 1.0 : 0.0;
@@ -241,6 +242,6 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
241
242
  // Premultiplied alpha output: inner fill is black, so it only contributes alpha.
242
243
  outColor = vec4(color.rgb * ringAlpha * pointOpacity, alpha);
243
244
  }
244
- }`),i=Fe(t,r,"uCamera"),o=Fe(t,r,"uPointSize"),s=Fe(t,r,"uPointOpacity"),a=Fe(t,r,"uPointStrokeScale"),l=Fe(t,r,"uPointInnerFillAlpha"),u=Fe(t,r,"uPalette"),f=Fe(t,r,"uPaletteSize"),c=Fe(t,r,"uPointLineDash"),h=t.createVertexArray(),d=t.createBuffer(),m=t.createBuffer(),g=t.createBuffer(),y=t.createBuffer(),b=t.createTexture();if(!h||!d||!m||!g||!y||!b)throw new Error("point buffer allocation failed");t.bindVertexArray(h),t.bindBuffer(t.ARRAY_BUFFER,d),t.bufferData(t.ARRAY_BUFFER,0,t.DYNAMIC_DRAW);const x=t.getAttribLocation(r,"aPosition");if(x<0)throw new Error("point position attribute not found");t.enableVertexAttribArray(x),t.vertexAttribPointer(x,2,t.FLOAT,!1,0,0),t.bindBuffer(t.ARRAY_BUFFER,m),t.bufferData(t.ARRAY_BUFFER,0,t.DYNAMIC_DRAW);const A=t.getAttribLocation(r,"aClass");if(A<0)throw new Error("point class attribute not found");t.enableVertexAttribArray(A),t.vertexAttribIPointer(A,1,t.UNSIGNED_SHORT,0,0),t.bindBuffer(t.ARRAY_BUFFER,g),t.bufferData(t.ARRAY_BUFFER,0,t.DYNAMIC_DRAW);const E=t.getAttribLocation(r,"aFillMode");if(E<0)throw new Error("point fill mode attribute not found");return t.enableVertexAttribArray(E),t.vertexAttribIPointer(E,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,b),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:h,posBuffer:d,classBuffer:m,fillModeBuffer:g,indexBuffer:y,paletteTexture:b,uCamera:i,uPointSize:o,uPointOpacity:s,uPointLineDash:c,uPointStrokeScale:a,uPointInnerFillAlpha:l,uPalette:u,uPaletteSize:f}}function Gi(t){t.animation=null,t.frame!==null&&(cancelAnimationFrame(t.frame),t.frame=null)}function yc(t){const{state:e,camera:n,target:r,durationMs:i,easing:o,onUpdate:s}=t,a=n.getViewState();Gi(e),e.animation={startMs:ye(),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,ye()-u.startMs),c=u.durationMs<=0?1:_(f/u.durationMs,0,1);let h=c;try{h=u.easing(c)}catch{h=c}if(Number.isFinite(h)||(h=c),h=_(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 bc(t){const e=Math.max(t*.5,1e-6),n=Math.max(1,t*8);return{minZoom:e,maxZoom:Math.max(e,n)}}function xc(t,e,n){const r=bc(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 wc(t,e,n,r,i){const o=t.getViewState(),s={zoom:typeof r.zoom=="number"&&Number.isFinite(r.zoom)?_(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 $r(t,e,n,r,i){const o=Math.min(e/t.width,n/t.height),s=Number.isFinite(o)&&o>0?o:1,a=_(s,r,i),l=e/a,u=n/a;return{fitZoom:s,target:{zoom:a,offsetX:(t.width-l)*.5,offsetY:(t.height-u)*.5,rotationDeg:0}}}function Sc(t,e,n,r,i,o){const s=t.getViewState(),a=_(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=tn(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 Ec(t,e,n,r,i,o){const s=t.getViewState(),a=_(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=tn(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 Rc=250;function Kr(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 Ac(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 Mc(t,e,n,r,i){const o=t.camera.getViewState(),[s,a]=t.camera.screenToWorld(n,r),l=t.camera.getViewportSize(),u=_(e,t.minZoom,t.maxZoom);if(u===o.zoom)return;const f=tn(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,E=d/x*h+m/x*c;return{offsetX:s-A-l.width/(2*x),offsetY:a-E-l.height/(2*x)}},y=g(u);t.viewAnimationState.animation={startMs:ye(),durationMs:Math.max(0,i),from:o,to:{zoom:u,offsetX:y.offsetX,offsetY:y.offsetY,rotationDeg:o.rotationDeg},easing:Vn};const b=()=>{const x=t.viewAnimationState.animation;if(!x)return;const A=Math.max(0,ye()-x.startMs),E=_(A/i,0,1),M=_(E*E*(3-2*E),0,1),C=o.zoom+(u-o.zoom)*M,{offsetX:T,offsetY:k}=g(C);t.camera.setViewState({zoom:C,offsetX:T,offsetY:k,rotationDeg:o.rotationDeg});const X=E>=1;X&&(t.clampViewState(),t.viewAnimationState.animation=null,t.viewAnimationState.frame=null),t.onViewStateChange(t.camera.getViewState()),t.requestRender(),X||(t.viewAnimationState.frame=requestAnimationFrame(b))};t.viewAnimationState.frame=requestAnimationFrame(b)}const We="__default_point_layer__";class qi{constructor(e,n,r={}){S(this,"canvas");S(this,"source");S(this,"gl");S(this,"camera",new Jr);S(this,"onViewStateChange");S(this,"onStats");S(this,"onTileError");S(this,"onContextLost");S(this,"onContextRestored");S(this,"resizeObserver");S(this,"tileProgram");S(this,"tileScheduler");S(this,"authToken");S(this,"destroyed",!1);S(this,"contextLost",!1);S(this,"frame",null);S(this,"frameSerial",0);S(this,"interactionState",{dragging:!1,mode:"none",rotateLastAngleRad:null,pointerId:null,lastPointerX:0,lastPointerY:0});S(this,"interactionLocked",!1);S(this,"ctrlDragRotate",!0);S(this,"rotationDragSensitivityDegPerPixel",Pn);S(this,"maxCacheTiles");S(this,"fitZoom",1);S(this,"minZoom",1e-6);S(this,"maxZoom",1);S(this,"minZoomOverride",null);S(this,"maxZoomOverride",null);S(this,"viewTransitionDurationMs",0);S(this,"viewTransitionEasing",Vn);S(this,"viewAnimationState",{animation:null,frame:null});S(this,"pointLayers",new Map);S(this,"defaultPointSizeStops",Qt(vn));S(this,"defaultPointOpacity",1);S(this,"defaultPointLineDash",[1,0]);S(this,"defaultPointStrokeScale",1);S(this,"defaultPointInnerFillOpacity",0);S(this,"imageColorSettings",{brightness:0,contrast:0,saturation:0});S(this,"cache",new Map);S(this,"zoomSnaps",[]);S(this,"zoomSnapFitAsMin",!1);S(this,"zoomSnapState",{accumulatedDelta:0,lastSnapTimeMs:0,blockedDirection:null});S(this,"panExtentX",.2);S(this,"panExtentY",.2);S(this,"boundPointerDown");S(this,"boundPointerMove");S(this,"boundPointerUp");S(this,"boundWheel");S(this,"boundDoubleClick");S(this,"boundContextMenu");S(this,"boundContextLost");S(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.ctrlDragRotate=r.ctrlDragRotate??!0,this.rotationDragSensitivityDegPerPixel=typeof r.rotationDragSensitivityDegPerPixel=="number"&&Number.isFinite(r.rotationDragSensitivityDegPerPixel)?Math.max(0,r.rotationDragSensitivityDegPerPixel):Pn,this.defaultPointSizeStops=Or(r.pointSizeByZoom),this.defaultPointOpacity=Wr(r.pointOpacity),this.defaultPointStrokeScale=Yr(r.pointStrokeScale),this.defaultPointInnerFillOpacity=Xr(r.pointInnerFillOpacity),this.imageColorSettings=Vr(r.imageColorSettings),this.minZoomOverride=zt(r.minZoom),this.maxZoomOverride=zt(r.maxZoom),this.viewTransitionDurationMs=fn(r.viewTransition?.duration),this.viewTransitionEasing=hn(r.viewTransition?.easing),this.zoomSnaps=Kr(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=Hr(this.gl),this.tileScheduler=new Yi({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)=>uc({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);const o=ac({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),Tl(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=xc(this.fitZoom,this.minZoomOverride,this.maxZoomOverride);this.minZoom=e.minZoom,this.maxZoom=e.maxZoom}resolveTargetViewState(e){return wc(this.camera,this.minZoom,this.maxZoom,e,()=>Vt(this.camera,this.source,this.panExtentX,this.panExtentY))}cancelViewAnimation(){Gi(this.viewAnimationState)}startViewAnimation(e,n,r){yc({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:Zr(this.gl),runtime:this.createPointBufferRuntime(),pointSizeStops:Qt(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())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,pointSizePx:this.getPointSizeByZoom(r.id)*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();xn(s,o)||this.applyViewStateAndRender(o)}setViewTransition(e){this.viewTransitionDurationMs=fn(e?.duration),this.viewTransitionEasing=hn(e?.easing)}setViewState(e,n){const r=this.resolveTargetViewState(e),i=this.camera.getViewState();if(xn(i,r))return;const o=fn(n?.duration??this.viewTransitionDurationMs),s=hn(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=Gr(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=Xl(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=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=We){const r=this.ensurePointLayer(n),i=Or(e);Yl(r.pointSizeStops,i)||(r.pointSizeStops=i,this.requestRender())}setPointOpacity(e,n=We){const r=this.ensurePointLayer(n),i=Wr(e);r.pointOpacity!==i&&(r.pointOpacity=i,this.requestRender())}setPointStrokeScale(e,n=We){const r=this.ensurePointLayer(n),i=Yr(e);r.pointStrokeScale!==i&&(r.pointStrokeScale=i,this.requestRender())}setPointInnerFillOpacity(e,n=We){const r=this.ensurePointLayer(n),i=Xr(e);r.pointInnerFillOpacity!==i&&(r.pointInnerFillOpacity=i,this.requestRender())}setImageColorSettings(e){const n=Vr(e),r=this.imageColorSettings;r.brightness===n.brightness&&r.contrast===n.contrast&&r.saturation===n.saturation||(this.imageColorSettings=n,this.requestRender())}cancelDrag(){sc(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)<1e-6||this.setViewState({rotationDeg:0},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=Wl(r,o);return _(s,Tn,_l)}fitToImage(e){const n=this.canvas.getBoundingClientRect(),r=Math.max(1,n.width||1),i=Math.max(1,n.height||1),o=$r(this.source,r,i,this.minZoom,this.maxZoom);this.fitZoom=o.fitZoom,this.applyZoomBounds(),this.setViewState(o.target,e)}zoomBy(e,n,r,i){const o=Sc(this.camera,this.minZoom,this.maxZoom,e,n,r);o&&this.setViewState(o,i)}zoomTo(e,n,r,i){const o=Ec(this.camera,this.minZoom,this.maxZoom,e,n,r);o&&this.setViewState(o,i)}setZoomSnaps(e,n){this.zoomSnaps=Kr(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=Ac(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=$r(this.source,c,h,this.minZoom,this.maxZoom);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 Mc(this.getZoomPivotAnimationContext(),l,n,r,Rc),!0}render(){if(this.destroyed||this.contextLost||this.gl.isContextLost())return;const e=this.onStats?ye():0;this.frameSerial+=1;const n=pc({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:()=>ec(this.camera,this.source),getVisibleTilesForTier:r=>Vi(this.camera,this.source,r),getViewBounds:()=>en(this.camera),intersectsBounds:Ql});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:ye()-e})}}requestRender(){this.frame!==null||this.destroyed||this.contextLost||this.gl.isContextLost()||(this.frame=requestAnimationFrame(()=>{this.frame=null,this.render()}))}resize(){Il(this.canvas,this.gl,this.camera),this.requestRender()}onWebGlContextLost(e){const n=hc({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=Hr(this.gl);for(const n of this.pointLayers.values())n.program=Zr(this.gl),n.runtime={...n.runtime,pointBuffersDirty:!0},n.runtime.lastPointPalette&&n.runtime.lastPointPalette.length>0&&(n.runtime=Gr(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=dc({destroyed:this.destroyed,frame:this.frame,cancelViewAnimation:()=>this.cancelViewAnimation(),resizeObserver:this.resizeObserver,removeCanvasEventListeners:()=>vl(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 Cc=[];function Pc({source:t,viewState:e,onViewStateChange:n,onStats:r,onTileError:i,onContextLost:o,onContextRestored:s,imageColorSettings:a=null,fitNonce:l=0,rotationResetNonce:u=0,authToken:f="",ctrlDragRotate:c=!0,minZoom:h,maxZoom:d,viewTransition:m,zoomSnaps:g,zoomSnapFitAsMin:y,panExtent:b,onPointerWorldMove:x,debugOverlay:A=!1,debugOverlayStyle:E,className:M,style:C,children:T}){const k=p.useRef(null),X=p.useRef(null),N=p.useRef(null),P=p.useRef(null),z=p.useRef(null),F=p.useRef(null),O=p.useRef(Cc),$=p.useRef(!1),W=p.useRef(new Set),J=p.useRef(new Set),he=p.useRef(n),K=p.useRef(r),Pe=p.useRef(i),Ae=p.useRef(o),we=p.useRef(s),[v,I]=p.useState(0),[U,oe]=p.useState(null),j=p.useRef(A);p.useEffect(()=>{he.current=n},[n]),p.useEffect(()=>{K.current=r},[r]),p.useEffect(()=>{Pe.current=i},[i]),p.useEffect(()=>{Ae.current=o},[o]),p.useEffect(()=>{we.current=s},[s]),p.useEffect(()=>{j.current=A,A||oe(null)},[A]);const ue=p.useMemo(()=>({position:"relative",width:"100%",height:"100%",...C}),[C]),ee=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)",...E}),[E]),de=p.useCallback(Y=>{K.current?.(Y),j.current&&oe(Y)},[]),se=p.useMemo(()=>U?[`tier ${U.tier} | frame ${U.frameMs?.toFixed(2)??"-"} ms | drawCalls ${U.drawCalls??"-"}`,`tiles visible ${U.visible} | rendered ${U.rendered} | fallback ${U.fallback}`,`cache size ${U.cache} | hit ${U.cacheHits??"-"} | miss ${U.cacheMisses??"-"}`,`queue inflight ${U.inflight} | queued ${U.queued??"-"} | retries ${U.retries??"-"} | failed ${U.failed??"-"} | aborted ${U.aborted??"-"}`,`points ${U.points}`].join(`
245
- `):"stats: waiting for first frame...",[U]),pe=p.useCallback(()=>{const Y=N.current;if(!Y)return;const L=Y.getContext("2d");if(!L)return;const G=Math.max(1,window.devicePixelRatio||1),q=Y.getBoundingClientRect(),ne=Math.max(1,Math.round(q.width*G)),ce=Math.max(1,Math.round(q.height*G));(Y.width!==ne||Y.height!==ce)&&(Y.width=ne,Y.height=ce);const Be=q.width,Me=q.height;L.setTransform(1,0,0,1,0,0),L.clearRect(0,0,Y.width,Y.height),L.setTransform(G,0,0,G,0,0);const Ce=O.current;for(let _e=0;_e<Ce.length;_e+=1)L.save(),Ce[_e].draw(L,Be,Me),L.restore()},[]),Q=p.useCallback(()=>{$.current||($.current=!0,requestAnimationFrame(()=>{$.current=!1,pe()}))},[pe]),ae=p.useCallback((Y,L,G)=>{const q=O.current.filter(ne=>ne.id!==Y);q.push({id:Y,priority:L,draw:G}),q.sort((ne,ce)=>ne.priority-ce.priority),O.current=q,Q()},[Q]),fe=p.useCallback(Y=>{O.current=O.current.filter(L=>L.id!==Y),Q()},[Q]),Ee=p.useCallback((Y,L)=>{L?W.current.add(Y):W.current.delete(Y),P.current?.setInteractionLock(W.current.size>0)},[]),te=p.useCallback(()=>W.current.size>0,[]),ve=p.useCallback((Y,L)=>{const G=P.current;return G?Fn(G.worldToScreen(Y,L)):null},[]),be=p.useCallback((Y,L)=>{const G=P.current;if(!G)return null;const q=G.screenToWorld(Y,L);if(!Array.isArray(q)||q.length<2)return null;const ne=Number(q[0]),ce=Number(q[1]);return!Number.isFinite(ne)||!Number.isFinite(ce)?null:[ne,ce]},[]),me=p.useCallback(Y=>(J.current.add(Y),()=>{J.current.delete(Y)}),[]),V=p.useCallback(Y=>{he.current?.(Y);const L=J.current;if(L.size>0){const G=Array.from(L);for(let q=0;q<G.length;q+=1)G[q](Y)}z.current?.(),F.current?.(),Q()},[Q]);p.useEffect(()=>{const Y=X.current;if(!Y||!t)return;const L=new qi(Y,t,{onViewStateChange:V,onStats:de,onTileError:G=>{Pe.current?.(G)},onContextLost:()=>{Ae.current?.()},onContextRestored:()=>{we.current?.()},authToken:f,imageColorSettings:a,ctrlDragRotate:c,minZoom:h,maxZoom:d,viewTransition:m,zoomSnaps:g,zoomSnapFitAsMin:y,panExtent:b});return P.current=L,I(G=>G+1),e&&L.setViewState(e),L.setInteractionLock(W.current.size>0),()=>{L.destroy(),P.current=null}},[t,de,c,V]),p.useEffect(()=>{P.current?.setAuthToken(f)},[f]),p.useEffect(()=>{const Y=P.current;!Y||!e||Y.isViewAnimating()||Y.setViewState(e)},[e]),p.useEffect(()=>{P.current?.fitToImage()},[l]),p.useEffect(()=>{P.current?.resetRotation()},[u]),p.useEffect(()=>{P.current?.setZoomRange(h,d)},[h,d]),p.useEffect(()=>{P.current?.setViewTransition(m)},[m]),p.useEffect(()=>{P.current?.setZoomSnaps(g,y)},[g,y]),p.useEffect(()=>{P.current?.setPanExtent(b)},[b]),p.useEffect(()=>{P.current?.setImageColorSettings(a)},[a]),p.useEffect(()=>{const Y=N.current;if(!Y)return;z.current=Q,Q();const L=new ResizeObserver(()=>Q());return L.observe(Y),()=>{L.disconnect(),z.current===Q&&(z.current=null)}},[Q]);const Z=p.useMemo(()=>({source:t,rendererRef:P,rendererSerial:v,canvasRef:X,containerRef:k,drawInvalidateRef:z,overviewInvalidateRef:F,worldToScreen:ve,screenToWorld:be,registerDrawCallback:ae,unregisterDrawCallback:fe,requestOverlayRedraw:Q,registerViewStateListener:me,setInteractionLock:Ee,isInteractionLocked:te}),[t,v,ve,be,ae,fe,Q,me,Ee,te]),re=p.useRef(x);p.useEffect(()=>{re.current=x},[x]);const ie=p.useCallback(Y=>{const L=re.current;if(!L)return;const G=be(Y.clientX,Y.clientY),q=!!G&&G[0]>=0&&G[1]>=0&&!!t&&G[0]<=t.width&&G[1]<=t.height;L({coordinate:G,clientX:Y.clientX,clientY:Y.clientY,insideImage:q})},[be,t]),Se=p.useCallback(()=>{re.current?.({coordinate:null,clientX:-1,clientY:-1,insideImage:!1})},[]);return He.jsx(Zs,{value:Z,children:He.jsxs("div",{ref:k,className:M,style:ue,onPointerMove:x?ie:void 0,onPointerLeave:x?Se:void 0,children:[He.jsx("canvas",{ref:X,className:"wsi-render-canvas",style:{position:"absolute",inset:0,zIndex:1,width:"100%",height:"100%",display:"block",touchAction:"none"}}),He.jsx("canvas",{ref:N,className:"wsi-overlay-canvas",style:{position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",pointerEvents:"none",touchAction:"none"}}),T,A&&He.jsx("pre",{"data-open-plant-debug-overlay":!0,style:ee,children:se})]})})}function Tc(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 vc=128,dn=[];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 Ic(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(vc,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 _c(t,e,n){if(!t||e<t.minX||e>t.maxX||n<t.minY||n>t.maxY)return dn;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]??dn}function Lc(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 Fc(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=Tc(e??[]);if(!t||o===0||s.length===0)return{groups:[],inputPointCount:o,pointsInsideAnyRegion:0,unmatchedPointCount:o};const a=new Map,l=new Map,u=Ic(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=_c(u,g,y);if(x.length===0)continue;for(const M of x){const C=s[M];let T=!1;for(const k of C.polygons)if(ii(g,y,k)){T=!0;break}T&&(!b||C.area<b.area)&&(b=C)}if(!b)continue;f+=1;const A=t.paletteIndices[m]??0,E=a.get(b.regionIndex)??new Map;E.set(A,(E.get(A)??0)+1),a.set(b.regionIndex,E),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:Lc(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 Dc(t){return t.replace(/^\s*SRID\s*=\s*\d+\s*;\s*/i,"")}function Nc(t){return t>="A"&&t<="Z"||t>="a"&&t<="z"}function Bc(t){return t>="0"&&t<="9"}function jr(t){return t==="+"||t==="-"||t==="."||Bc(t)}class kc{constructor(e){S(this,"text");S(this,"index",0);this.text=Dc(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=Hi(i);return s?{type:"Polygon",coordinates:s}:null}const o=zc(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()&&Nc(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 Uc(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 Hi(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(!Uc(i))return null;r.push([i[0],i[1]])}e.push(r)}return e}function zc(t){if(!Array.isArray(t))return null;const e=[];for(const n of t){const r=Hi(n);if(!r)return null;e.push(r)}return e}function Oc(t){return typeof t!="string"?null:new kc(t).parse()}exports.DEFAULT_POINT_COLOR=_n;exports.DrawLayer=pi;exports.DrawingLayer=$s;exports.HeatmapLayer=va;exports.M1TileRenderer=Qr;exports.OverlayLayer=_a;exports.OverviewMap=Ua;exports.PatchLayer=Oa;exports.PointLayer=hl;exports.RegionLayer=Ml;exports.TileScheduler=Yi;exports.TileViewerCanvas=Cl;exports.WsiTileRenderer=qi;exports.WsiViewer=Pc;exports.__heatmapLayerInternals=Ia;exports.buildClassPalette=Fo;exports.buildPointSpatialIndexAsync=Oi;exports.calcScaleLength=Io;exports.calcScaleResolution=Ln;exports.clamp=_;exports.closeRing=Ue;exports.computeRoiPointGroups=Fc;exports.createCircle=wn;exports.createRectangle=Kt;exports.createSpatialIndex=bi;exports.filterPointDataByPolygons=Rt;exports.filterPointDataByPolygonsHybrid=Bi;exports.filterPointDataByPolygonsInWorker=Ui;exports.filterPointIndicesByPolygons=Fi;exports.filterPointIndicesByPolygonsInWorker=Ka;exports.getWebGpuCapabilities=Ha;exports.hexToRgba=oi;exports.isSameViewState=xn;exports.lookupCellIndex=zi;exports.normalizeImageClasses=La;exports.normalizeImageInfo=Da;exports.parseWkt=Oc;exports.prefilterPointsByBoundsWebGpu=Ni;exports.terminatePointHitIndexWorker=sl;exports.terminateRoiClipWorker=$a;exports.toBearerToken=_o;exports.toRoiGeometry=ht;exports.toTileUrl=Xn;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(),y=t.createBuffer(),b=t.createBuffer(),w=t.createTexture();if(!d||!m||!g||!y||!b||!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,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,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:y,indexBuffer:b,paletteTexture:w,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: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: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,w=l-y,A=u-b;return{zoom:a,offsetX:w-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,w=l-y,A=u-b;return{zoom:a,offsetX:w-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=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)}},y=g(u);t.viewAnimationState.animation={startMs:we(),durationMs:Math.max(0,i),from:o,to:{zoom:u,offsetX:y.offsetX,offsetY:y.offsetY,rotationDeg:o.rotationDeg},easing:Gn};const b=()=>{const w=t.viewAnimationState.animation;if(!w)return;const A=Math.max(0,we()-w.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 Y=S>=1;Y&&(t.clampViewState(),t.viewAnimationState.animation=null,t.viewAnimationState.frame=null),t.onViewStateChange(t.camera.getViewState()),t.requestRender(),Y||(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?we():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:we()-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:w,onPointerWorldMove:A,debugOverlay:S=!1,debugOverlayStyle:C,className:M,style:P,children:U}){const Y=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),W=p.useRef(!1),j=p.useRef(new Set),ce=p.useRef(new Set),Q=p.useRef(n),Te=p.useRef(r),ve=p.useRef(i),Ae=p.useRef(o),I=p.useRef(s),[T,X]=p.useState(0),[q,ee]=p.useState(null),le=p.useRef(S);p.useEffect(()=>{Q.current=n},[n]),p.useEffect(()=>{Te.current=r},[r]),p.useEffect(()=>{ve.current=i},[i]),p.useEffect(()=>{Ae.current=o},[o]),p.useEffect(()=>{I.current=s},[s]),p.useEffect(()=>{le.current=S,S||ee(null)},[S]);const re=p.useMemo(()=>({position:"relative",width:"100%",height:"100%",...P}),[P]),pe=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]),te=Tc(l),ye=p.useCallback(_=>({..._,rotationDeg:_.rotationDeg-te}),[te]),fe=p.useCallback(_=>typeof _.rotationDeg!="number"||!Number.isFinite(_.rotationDeg)?_:{..._,rotationDeg:_.rotationDeg+te},[te]),se=p.useCallback(_=>{Te.current?.(_),le.current&&ee(_)},[]),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]),Me=p.useCallback(()=>{const _=v.current;if(!_)return;const O=_.getContext("2d");if(!O)return;const J=Math.max(1,window.devicePixelRatio||1),ne=_.getBoundingClientRect(),Re=Math.max(1,Math.round(ne.width*J)),me=Math.max(1,Math.round(ne.height*J));(_.width!==Re||_.height!==me)&&(_.width=Re,_.height=me);const Ce=ne.width,De=ne.height;O.setTransform(1,0,0,1,0,0),O.clearRect(0,0,_.width,_.height),O.setTransform(J,0,0,J,0,0);const x=K.current;for(let R=0;R<x.length;R+=1)O.save(),x[R].draw(O,Ce,De),O.restore()},[]),H=p.useCallback(()=>{W.current||(W.current=!0,requestAnimationFrame(()=>{W.current=!1,Me()}))},[Me]),Ie=p.useCallback((_,O,J)=>{const ne=K.current.filter(Re=>Re.id!==_);ne.push({id:_,priority:O,draw:J}),ne.sort((Re,me)=>Re.priority-me.priority),K.current=ne,H()},[H]),Se=p.useCallback(_=>{K.current=K.current.filter(O=>O.id!==_),H()},[H]),he=p.useCallback((_,O)=>{O?j.current.add(_):j.current.delete(_),B.current?.setInteractionLock(j.current.size>0)},[]),V=p.useCallback(()=>j.current.size>0,[]),$=p.useCallback((_,O)=>{const J=B.current;return J?Dn(J.worldToScreen(_,O)):null},[]),ie=p.useCallback((_,O)=>{const J=B.current;if(!J)return null;const ne=J.screenToWorld(_,O);if(!Array.isArray(ne)||ne.length<2)return null;const Re=Number(ne[0]),me=Number(ne[1]);return!Number.isFinite(Re)||!Number.isFinite(me)?null:[Re,me]},[]),oe=p.useCallback(_=>(ce.current.add(_),()=>{ce.current.delete(_)}),[]),Ee=p.useCallback(_=>{Q.current?.(ye(_));const O=ce.current;if(O.size>0){const J=Array.from(O);for(let ne=0;ne<J.length;ne+=1)J[ne](_)}F.current?.(),z.current?.(),H()},[H,ye]);p.useEffect(()=>{const _=N.current;if(!_||!t)return;const O=new Zi(_,t,{onViewStateChange:Ee,onStats:se,onTileError:J=>{ve.current?.(J)},onContextLost:()=>{Ae.current?.()},onContextRestored:()=>{I.current?.()},authToken:c,imageColorSettings:a,initialRotationDeg:l,ctrlDragRotate:h,minZoom:d,maxZoom:m,viewTransition:g,zoomSnaps:y,zoomSnapFitAsMin:b,panExtent:w});return B.current=O,X(J=>J+1),e&&O.setViewState(fe(e)),O.setInteractionLock(j.current.size>0),()=>{O.destroy(),B.current=null}},[t,se,h,Ee,te,fe]),p.useEffect(()=>{B.current?.setAuthToken(c)},[c]),p.useEffect(()=>{const _=B.current;!_||!e||_.isViewAnimating()||_.setViewState(fe(e))},[e,fe]),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(w)},[w]),p.useEffect(()=>{B.current?.setImageColorSettings(a)},[a]),p.useEffect(()=>{const _=v.current;if(!_)return;F.current=H,H();const O=new ResizeObserver(()=>H());return O.observe(_),()=>{O.disconnect(),F.current===H&&(F.current=null)}},[H]),p.useEffect(()=>tn(()=>H()),[H]);const Fe=p.useMemo(()=>({source:t,rendererRef:B,rendererSerial:T,canvasRef:N,containerRef:Y,drawInvalidateRef:F,overviewInvalidateRef:z,worldToScreen:$,screenToWorld:ie,registerDrawCallback:Ie,unregisterDrawCallback:Se,requestOverlayRedraw:H,registerViewStateListener:oe,setInteractionLock:he,isInteractionLocked:V}),[t,T,$,ie,Ie,Se,H,oe,he,V]),G=p.useRef(A);p.useEffect(()=>{G.current=A},[A]);const be=p.useCallback(_=>{const O=G.current;if(!O)return;const J=ie(_.clientX,_.clientY),ne=!!J&&J[0]>=0&&J[1]>=0&&!!t&&J[0]<=t.width&&J[1]<=t.height;O({coordinate:J,clientX:_.clientX,clientY:_.clientY,insideImage:ne})},[ie,t]),xe=p.useCallback(()=>{G.current?.({coordinate:null,clientX:-1,clientY:-1,insideImage:!1})},[]);return Ge.jsx(Ks,{value:Fe,children:Ge.jsxs("div",{ref:Y,className:M,style:re,onPointerMove:A?be:void 0,onPointerLeave:A?xe:void 0,children:[Ge.jsx("canvas",{ref:N,className:"wsi-render-canvas",style:{position:"absolute",inset:0,zIndex:1,width:"100%",height:"100%",display:"block",touchAction:"none"}}),Ge.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&&Ge.jsx("pre",{"data-open-plant-debug-overlay":!0,style:pe,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 w=d[b];w>=r||(g[y]=w,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 w=Dc(u,g,y);if(w.length===0)continue;for(const C of w){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,w])=>({classId:Nc(b,n.paletteIndexToClassId),paletteIndex:b,count:w})).sort((b,w)=>w.count-b.count||b.paletteIndex-w.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=ze;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=st;
246
247
  //# sourceMappingURL=index.cjs.map