open-plant 1.3.2 → 1.3.4

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 Ai=Object.defineProperty;var Ti=(e,t,n)=>t in e?Ai(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var S=(e,t,n)=>Ti(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const We=require("react/jsx-runtime"),h=require("react");var gt=typeof document<"u"?document.currentScript:null;function Qn(e,t,n){const r=e.createShader(t);if(!r)throw new Error("Failed to create shader.");if(e.shaderSource(r,n),e.compileShader(r),!e.getShaderParameter(r,e.COMPILE_STATUS)){const o=e.getShaderInfoLog(r)??"unknown shader error";throw e.deleteShader(r),new Error(o)}return r}function Rn(e,t,n){const r=Qn(e,e.VERTEX_SHADER,t),i=Qn(e,e.FRAGMENT_SHADER,n),o=e.createProgram();if(!o)throw e.deleteShader(r),e.deleteShader(i),new Error("Failed to create program.");if(e.attachShader(o,r),e.attachShader(o,i),e.linkProgram(o),e.deleteShader(r),e.deleteShader(i),!e.getProgramParameter(o,e.LINK_STATUS)){const a=e.getProgramInfoLog(o)??"unknown link error";throw e.deleteProgram(o),new Error(a)}return o}function Ee(e,t,n){const r=e.getUniformLocation(t,n);if(!r)throw new Error(`Failed to get uniform location: ${n}`);return r}function Ri(e){const t=e.getContext("webgl2",{alpha:!1,antialias:!1,depth:!1,stencil:!1,preserveDrawingBuffer:!1,powerPreference:"high-performance"});if(!t)throw new Error("WebGL2 is not available.");return t}function an(e){return e*Math.PI/180}class Pr{constructor(){S(this,"viewportWidth",1);S(this,"viewportHeight",1);S(this,"viewState",{offsetX:0,offsetY:0,zoom:1,rotationDeg:0})}setViewport(t,n){this.viewportWidth=Math.max(1,t),this.viewportHeight=Math.max(1,n)}getViewportSize(){return{width:this.viewportWidth,height:this.viewportHeight}}setViewState(t){t.offsetX!==void 0&&(this.viewState.offsetX=t.offsetX),t.offsetY!==void 0&&(this.viewState.offsetY=t.offsetY),t.zoom!==void 0&&(this.viewState.zoom=Math.max(1e-4,t.zoom)),typeof t.rotationDeg=="number"&&Number.isFinite(t.rotationDeg)&&(this.viewState.rotationDeg=t.rotationDeg)}getViewState(){return{...this.viewState}}getCenter(){const t=Math.max(1e-6,this.viewState.zoom);return[this.viewState.offsetX+this.viewportWidth/(2*t),this.viewState.offsetY+this.viewportHeight/(2*t)]}setCenter(t,n){const r=Math.max(1e-6,this.viewState.zoom);this.viewState.offsetX=t-this.viewportWidth/(2*r),this.viewState.offsetY=n-this.viewportHeight/(2*r)}screenToWorld(t,n){const r=Math.max(1e-6,this.viewState.zoom),[i,o]=this.getCenter(),s=this.viewState.rotationDeg??0,a=(t-this.viewportWidth*.5)/r,c=(n-this.viewportHeight*.5)/r,u=an(s),l=Math.cos(u),d=Math.sin(u);return[i+a*l-c*d,o+a*d+c*l]}worldToScreen(t,n){const r=Math.max(1e-6,this.viewState.zoom),[i,o]=this.getCenter(),s=this.viewState.rotationDeg??0,a=t-i,c=n-o,u=an(s),l=Math.cos(u),d=Math.sin(u),f=a*l+c*d,y=-a*d+c*l;return[this.viewportWidth*.5+f*r,this.viewportHeight*.5+y*r]}getViewCorners(){const t=this.viewportWidth,n=this.viewportHeight;return[this.screenToWorld(0,0),this.screenToWorld(t,0),this.screenToWorld(t,n),this.screenToWorld(0,n)]}getMatrix(){const t=Math.max(1e-6,this.viewState.zoom),n=this.viewState.rotationDeg??0;if(n===0){const b=this.viewportWidth/t,w=this.viewportHeight/t,x=2/b,R=-2/w,E=-1-this.viewState.offsetX*x,X=1-this.viewState.offsetY*R;return new Float32Array([x,0,0,0,R,0,E,X,1])}const[r,i]=this.getCenter(),o=an(n),s=Math.cos(o),a=Math.sin(o),c=2*t*s/this.viewportWidth,u=2*t*a/this.viewportWidth,l=2*t*a/this.viewportHeight,d=-2*t*s/this.viewportHeight,f=-(c*r+u*i),y=-(l*r+d*i);return new Float32Array([c,l,0,u,d,0,f,y,1])}}const Ci=`#version 300 es
1
+ "use strict";var Ri=Object.defineProperty;var Ci=(e,t,n)=>t in e?Ri(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var S=(e,t,n)=>Ci(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ze=require("react/jsx-runtime"),d=require("react");var gt=typeof document<"u"?document.currentScript:null;function tr(e,t,n){const r=e.createShader(t);if(!r)throw new Error("Failed to create shader.");if(e.shaderSource(r,n),e.compileShader(r),!e.getShaderParameter(r,e.COMPILE_STATUS)){const o=e.getShaderInfoLog(r)??"unknown shader error";throw e.deleteShader(r),new Error(o)}return r}function Pn(e,t,n){const r=tr(e,e.VERTEX_SHADER,t),i=tr(e,e.FRAGMENT_SHADER,n),o=e.createProgram();if(!o)throw e.deleteShader(r),e.deleteShader(i),new Error("Failed to create program.");if(e.attachShader(o,r),e.attachShader(o,i),e.linkProgram(o),e.deleteShader(r),e.deleteShader(i),!e.getProgramParameter(o,e.LINK_STATUS)){const a=e.getProgramInfoLog(o)??"unknown link error";throw e.deleteProgram(o),new Error(a)}return o}function Pe(e,t,n){const r=e.getUniformLocation(t,n);if(!r)throw new Error(`Failed to get uniform location: ${n}`);return r}function Pi(e){const t=e.getContext("webgl2",{alpha:!1,antialias:!1,depth:!1,stencil:!1,preserveDrawingBuffer:!1,powerPreference:"high-performance"});if(!t)throw new Error("WebGL2 is not available.");return t}function un(e){return e*Math.PI/180}class Er{constructor(){S(this,"viewportWidth",1);S(this,"viewportHeight",1);S(this,"viewState",{offsetX:0,offsetY:0,zoom:1,rotationDeg:0})}setViewport(t,n){this.viewportWidth=Math.max(1,t),this.viewportHeight=Math.max(1,n)}getViewportSize(){return{width:this.viewportWidth,height:this.viewportHeight}}setViewState(t){t.offsetX!==void 0&&(this.viewState.offsetX=t.offsetX),t.offsetY!==void 0&&(this.viewState.offsetY=t.offsetY),t.zoom!==void 0&&(this.viewState.zoom=Math.max(1e-4,t.zoom)),typeof t.rotationDeg=="number"&&Number.isFinite(t.rotationDeg)&&(this.viewState.rotationDeg=t.rotationDeg)}getViewState(){return{...this.viewState}}getCenter(){const t=Math.max(1e-6,this.viewState.zoom);return[this.viewState.offsetX+this.viewportWidth/(2*t),this.viewState.offsetY+this.viewportHeight/(2*t)]}setCenter(t,n){const r=Math.max(1e-6,this.viewState.zoom);this.viewState.offsetX=t-this.viewportWidth/(2*r),this.viewState.offsetY=n-this.viewportHeight/(2*r)}screenToWorld(t,n){const r=Math.max(1e-6,this.viewState.zoom),[i,o]=this.getCenter(),s=this.viewState.rotationDeg??0,a=(t-this.viewportWidth*.5)/r,c=(n-this.viewportHeight*.5)/r,u=un(s),l=Math.cos(u),h=Math.sin(u);return[i+a*l-c*h,o+a*h+c*l]}worldToScreen(t,n){const r=Math.max(1e-6,this.viewState.zoom),[i,o]=this.getCenter(),s=this.viewState.rotationDeg??0,a=t-i,c=n-o,u=un(s),l=Math.cos(u),h=Math.sin(u),f=a*l+c*h,y=-a*h+c*l;return[this.viewportWidth*.5+f*r,this.viewportHeight*.5+y*r]}getViewCorners(){const t=this.viewportWidth,n=this.viewportHeight;return[this.screenToWorld(0,0),this.screenToWorld(t,0),this.screenToWorld(t,n),this.screenToWorld(0,n)]}getMatrix(){const t=Math.max(1e-6,this.viewState.zoom),n=this.viewState.rotationDeg??0;if(n===0){const b=this.viewportWidth/t,x=this.viewportHeight/t,w=2/b,A=-2/x,E=-1-this.viewState.offsetX*w,X=1-this.viewState.offsetY*A;return new Float32Array([w,0,0,0,A,0,E,X,1])}const[r,i]=this.getCenter(),o=un(n),s=Math.cos(o),a=Math.sin(o),c=2*t*s/this.viewportWidth,u=2*t*a/this.viewportWidth,l=2*t*a/this.viewportHeight,h=-2*t*s/this.viewportHeight,f=-(c*r+u*i),y=-(l*r+h*i);return new Float32Array([c,l,0,u,h,0,f,y,1])}}const Ii=`#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
- `,Pi=`#version 300 es
21
+ `,Ei=`#version 300 es
22
22
  precision highp float;
23
23
 
24
24
  in vec2 vUv;
@@ -29,7 +29,7 @@ out vec4 outColor;
29
29
  void main() {
30
30
  outColor = texture(uTexture, vUv);
31
31
  }
32
- `;class Ir{constructor(t){S(this,"canvas");S(this,"gl");S(this,"camera",new Pr);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=t.canvas,this.imageWidth=Math.max(1,t.imageWidth),this.imageHeight=Math.max(1,t.imageHeight),this.clearColor=t.clearColor??[.03,.05,.08,1],this.gl=Ri(this.canvas),this.program=Rn(this.gl,Ci,Pi);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=Ee(this.gl,this.program,"uCamera"),this.uBoundsLocation=Ee(this.gl,this.program,"uBounds"),this.uTextureLocation=Ee(this.gl,this.program,"uTexture"),t.initialViewState&&(this.controlledViewState=!0,this.camera.setViewState(t.initialViewState)),this.resizeObserver=new ResizeObserver(()=>{this.resize()}),this.resizeObserver.observe(this.canvas),this.resize()}async setTiles(t){if(this.destroyed)return;const n=++this.loadVersion,r=await Promise.all(t.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(t){this.controlledViewState=!0,this.camera.setViewState(t),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(t,n){try{const r=await fetch(t.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:t.id,bounds:t.bounds,texture:s}}catch(r){return console.error(`[M1TileRenderer] tile load failed: ${t.id}`,r),null}}resize(){if(this.destroyed)return;const t=this.canvas.getBoundingClientRect(),n=Math.max(1,t.width||this.canvas.clientWidth||1),r=Math.max(1,t.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 t=this.camera.getViewportSize(),n=Math.min(t.width/this.imageWidth,t.height/this.imageHeight),r=Number.isFinite(n)&&n>0?n:1,i=t.width/r,o=t.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 t of this.tiles)this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,t.texture),this.gl.uniform4f(this.uBoundsLocation,t.bounds[0],t.bounds[1],t.bounds[2],t.bounds[3]),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindVertexArray(null)}}disposeTiles(t){for(const n of t)this.gl.deleteTexture(n.texture)}}function Ct(e){return e??null}function er(e){return typeof e=="number"&&Number.isFinite(e)}function Ii(e){return Array.isArray(e)&&e.length>=2&&er(e[0])&&er(e[1])}function Er(e){return Array.isArray(e)&&e.length>0&&e.every(t=>Ii(t))}function vr(e){return Array.isArray(e)&&e.length>0&&e.every(t=>Er(t))}function Ei(e){return Array.isArray(e)&&e.length>0&&e.every(t=>vr(t))}function Ne(e){if(!Array.isArray(e)||e.length<3)return[];const t=[];for(const i of e){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=t[t.length-1];a&&a[0]===o&&a[1]===s||t.push([o,s])}if(t.length<3)return[];const n=t[0],r=t[t.length-1];return(n[0]!==r[0]||n[1]!==r[1])&&t.push([n[0],n[1]]),t.length>=4?t:[]}function Mt(e){if(!Array.isArray(e)||e.length<4)return 0;let t=0;for(let n=0;n<e.length-1;n+=1){const r=e[n],i=e[n+1];t+=r[0]*i[1]-i[0]*r[1]}return t*.5}function cn(e){if(!Array.isArray(e)||e.length===0)return[];const t=[];for(const o of e){const s=Ne(o);s.length>=4&&t.push(s)}if(t.length===0)return[];if(t.length===1)return[t[0]];let n=0,r=0;for(let o=0;o<t.length;o+=1){const s=Math.abs(Mt(t[o]));s<=r||(r=s,n=o)}const i=[t[n]];for(let o=0;o<t.length;o+=1)o!==n&&i.push(t[o]);return i}function _r(e){if(!e)return[];if(Er(e)){const t=cn([e]);return t.length>0?[t]:[]}if(vr(e)){const t=cn(e);return t.length>0?[t]:[]}if(Ei(e)){const t=[];for(const n of e){const r=cn(n);r.length>0&&t.push(r)}return t}return[]}function tr(e,t,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],c=n[o][0],u=n[o][1];a>t!=u>t&&e<(c-s)*(t-a)/(u-a||Number.EPSILON)+s&&(r=!r)}return r}function Pt(e){const t=[];for(const n of e??[]){const r=_r(n);for(const i of r){const o=i[0];if(!o||o.length<4)continue;let s=1/0,a=1/0,c=-1/0,u=-1/0;for(const[d,f]of o)d<s&&(s=d),d>c&&(c=d),f<a&&(a=f),f>u&&(u=f);if(!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(c)||!Number.isFinite(u))continue;let l=Math.abs(Mt(o));for(let d=1;d<i.length;d+=1)l-=Math.abs(Mt(i[d]));t.push({outer:o,holes:i.slice(1),minX:s,minY:a,maxX:c,maxY:u,area:Math.max(1e-6,l)})}}return t}function Fr(e,t,n){if(e<n.minX||e>n.maxX||t<n.minY||t>n.maxY||!tr(e,t,n.outer))return!1;for(const r of n.holes)if(tr(e,t,r))return!1;return!0}function Zt(e,t,n){for(const r of n)if(Fr(e,t,r))return!0;return!1}const Cn=[160,160,160,255];function k(e,t,n){return Math.max(t,Math.min(n,e))}function Pn(e,t,n){const r=Number(e),i=Number(t),o=Number(n);return!Number.isFinite(r)||r<=0?1:!Number.isFinite(i)||!Number.isFinite(o)?r:Math.pow(2,i-o)*r}function vi(e,t,n){let i=100*Pn(e,t,n);if(Number(e)){let o="μm";return i>1e3&&(i/=1e3,o="mm"),`${i.toPrecision(3)} ${o}`}return`${Math.round(i*1e3)/1e3} pixels`}function fe(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function ut(e){const t=e.fillModes instanceof Uint8Array?e.fillModes.length:Number.MAX_SAFE_INTEGER;return Math.max(0,Math.min(Math.floor(e.count??0),Math.floor((e.positions?.length??0)/2),e.paletteIndices?.length??0,t))}function gn(e,t){return!e&&!t?!0:!e||!t?!1:Math.abs((e.zoom??0)-(t.zoom??0))<1e-6&&Math.abs((e.offsetX??0)-(t.offsetX??0))<1e-6&&Math.abs((e.offsetY??0)-(t.offsetY??0))<1e-6&&Math.abs((e.rotationDeg??0)-(t.rotationDeg??0))<1e-6}function _i(e){const t=String(e??"").trim();if(!t)return"";if(/^bearer\s+/i.test(t)){const n=t.replace(/^bearer\s+/i,"").trim();return n?`Bearer ${n}`:""}return`Bearer ${t}`}function Br(e){const n=String(e??"").trim().match(/^#?([0-9a-fA-F]{6})$/);if(!n)return[...Cn];const r=Number.parseInt(n[1],16);return[r>>16&255,r>>8&255,r&255,255]}function Fi(e){const t=[[...Cn]],n=new Map;for(const i of e??[]){const o=String(i?.termId??"");!o||n.has(o)||(n.set(o,t.length),t.push(Br(i?.termColor)))}const r=new Uint8Array(t.length*4);for(let i=0;i<t.length;i+=1)r[i*4]=t[i][0],r[i*4+1]=t[i][1],r[i*4+2]=t[i][2],r[i*4+3]=t[i][3];return{colors:r,termToPaletteIndex:n}}const Bi=.1,Li=4e6,Ui=4096,Di=64,ki=1,Ni=4,Lr=1e-6,zi=24;function Oi(e){if(!Array.isArray(e)||e.length===0)return[];const t=[];for(const n of e){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=t[t.length-1];o&&Math.abs(o[0]-r)<1e-9&&Math.abs(o[1]-i)<1e-9||t.push([r,i])}return t}function Wi(e,t,n){if(t<=Lr||n<8)return[];const r=[];for(let i=0;i<=n;i+=1){const o=i/n*Math.PI*2;r.push([e[0]+Math.cos(o)*t,e[1]+Math.sin(o)*t])}return Ne(r)}function un(e,t){if(!e.length)return[];let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[a,c]of e)a<n&&(n=a),a>i&&(i=a),c<r&&(r=c),c>o&&(o=c);if(!Number.isFinite(n)||!Number.isFinite(r))return[];const s=Math.max(t,1);return Ne([[n-s,r-s],[i+s,r-s],[i+s,o+s],[n-s,o+s]])}function Yi(e,t){let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[a,c]of e)a<n&&(n=a),a>i&&(i=a),c<r&&(r=c),c>o&&(o=c);const s=Math.max(t,1);return[n-s,r-s,i+s,o+s]}function Xi(e,t,n){const r=Math.max(Bi,Number(n.minRasterStep)||0),i=Math.max(32768,Math.floor(n.maxRasterPixels||Li)),o=Math.max(256,Math.floor(n.maxRasterSize||Ui)),s=Math.max(.001,e[2]-e[0]),a=Math.max(.001,e[3]-e[1]);let c=Math.max(r,Number.EPSILON),u=3,l=Math.ceil(s/c)+u*2+1,d=Math.ceil(a/c)+u*2+1;for(;(l>o||d>o||l*d>i)&&(c*=1.15,l=Math.ceil(s/c)+u*2+1,d=Math.ceil(a/c)+u*2+1,!(c>Math.max(s,a))););return l=Math.max(8,l),d=Math.max(8,d),{minX:e[0],minY:e[1],step:c,padding:u,width:l,height:d}}function Vi(e,t){if(typeof OffscreenCanvas<"u"){const r=new OffscreenCanvas(e,t).getContext("2d",{willReadFrequently:!0});if(r)return r}if(typeof document<"u"){const n=document.createElement("canvas");return n.width=e,n.height=t,n.getContext("2d",{willReadFrequently:!0})}return null}function Gi(e,t){return[(e[0]-t.minX)/t.step+t.padding,(e[1]-t.minY)/t.step+t.padding]}function qi(e,t,n){const r=Vi(n.width,n.height);if(!r)return new Uint8Array(0);r.clearRect(0,0,n.width,n.height),r.fillStyle="#ffffff",r.strokeStyle="#ffffff",r.lineCap="round",r.lineJoin="round",r.lineWidth=t*2/n.step;const i=e.map(a=>Gi(a,n));if(i.length<=1){const a=i[0];if(!a)return new Uint8Array(0);r.beginPath(),r.arc(a[0],a[1],t/n.step,0,Math.PI*2),r.fill()}else{r.beginPath(),r.moveTo(i[0][0],i[0][1]);for(let a=1;a<i.length;a+=1)r.lineTo(i[a][0],i[a][1]);r.stroke()}const o=r.getImageData(0,0,n.width,n.height),s=new Uint8Array(n.width*n.height);for(let a=0;a<s.length;a+=1)s[a]=o.data[a*4+3]>=zi?1:0;return s}function Hi(e,t,n){const r=[],i=t+1,o=(a,c)=>c*i+a,s=(a,c)=>a>=0&&c>=0&&a<t&&c<n&&e[c*t+a]>0;for(let a=0;a<n;a+=1)for(let c=0;c<t;c+=1)s(c,a)&&(s(c,a-1)||r.push({start:o(c,a),end:o(c+1,a),dir:0}),s(c+1,a)||r.push({start:o(c+1,a),end:o(c+1,a+1),dir:1}),s(c,a+1)||r.push({start:o(c+1,a+1),end:o(c,a+1),dir:2}),s(c-1,a)||r.push({start:o(c,a+1),end:o(c,a),dir:3}));return r}function $i(e,t){const n=(t-e+4)%4;return n===1?0:n===0?1:n===3?2:3}function Zi(e){if(!e.length)return[];const t=new Map;for(let i=0;i<e.length;i+=1){const o=t.get(e[i].start);o?o.push(i):t.set(e[i].start,[i])}const n=new Uint8Array(e.length),r=[];for(let i=0;i<e.length;i+=1){if(n[i])continue;const o=e[i],s=o.start;let a=o.end,c=o.dir;const u=[o.start,o.end];n[i]=1;let l=0;const d=e.length*3;for(;a!==s&&l<d;){const f=t.get(a);if(!f||f.length===0)break;let y=-1,b=1/0;for(const x of f){if(n[x])continue;const R=e[x],E=$i(c,R.dir);E<b&&(b=E,y=x)}if(y<0)break;n[y]=1;const w=e[y];a=w.end,c=w.dir,u.push(a),l+=1}u.length>=4&&u[0]===u[u.length-1]&&r.push(u)}return r}function Ki(e,t,n){const r=t+1,i=[];for(const o of e){const s=o%r,a=Math.floor(o/r);i.push([n.minX+(s-n.padding)*n.step,n.minY+(a-n.padding)*n.step])}return Ne(i)}function ji(e,t=1e-9){const n=Ne(e);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],c=(s[0]-o[0])*(a[1]-s[1])-(s[1]-o[1])*(a[0]-s[0]);Math.abs(c)<=t||r.push(s)}return r.push(r[0]),Ne(r)}function Ji(e,t,n){const r=n[0]-t[0],i=n[1]-t[1],o=r*r+i*i;if(o<=1e-12){const d=e[0]-t[0],f=e[1]-t[1];return d*d+f*f}const s=k(((e[0]-t[0])*r+(e[1]-t[1])*i)/o,0,1),a=t[0]+r*s,c=t[1]+i*s,u=e[0]-a,l=e[1]-c;return u*u+l*l}function Qi(e,t){if(e.length<=2||t<=0)return e.slice();const n=new Uint8Array(e.length);n[0]=1,n[e.length-1]=1;const r=t*t,i=[[0,e.length-1]];for(;i.length>0;){const s=i.pop();if(!s)break;const[a,c]=s;if(c-a<=1)continue;let u=0,l=-1;for(let d=a+1;d<c;d+=1){const f=Ji(e[d],e[a],e[c]);f>u&&(u=f,l=d)}l>=0&&u>r&&(n[l]=1,i.push([a,l],[l,c]))}const o=[];for(let s=0;s<e.length;s+=1)n[s]&&o.push(e[s]);return o}function eo(e,t){const n=Ne(e);if(n.length<5||t<=0)return n;const r=n.slice(0,-1),i=Qi(r,t);return i.length<3?n:Ne(i)}function to(e,t){let n=Ne(e);if(t<=0||n.length<5)return n;for(let r=0;r<t;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],c=i[(s+1)%i.length];o.push([a[0]*.75+c[0]*.25,a[1]*.75+c[1]*.25],[a[0]*.25+c[0]*.75,a[1]*.25+c[1]*.75])}n=Ne(o)}return n}function yt(e,t){return t?Ne(e.map(([n,r])=>[k(n,t[0],t[2]),k(r,t[1],t[3])])):e}function no(e,t){const n=Oi(e),r=Math.max(Lr,Number(t.radius)||0);if(n.length===0||!Number.isFinite(r))return[];const i=Math.max(12,Math.floor(t.circleSides||Di));if(n.length===1)return yt(Wi(n[0],r,i),t.clipBounds);const o=Yi(n,r),s=Xi(o,r,t),a=qi(n,r,s);if(!a.length)return yt(un(n,r),t.clipBounds);const c=Hi(a,s.width,s.height),u=Zi(c);if(!u.length)return yt(un(n,r),t.clipBounds);let l=[],d=0;for(const w of u){const x=Ki(w,s.width,s),R=Math.abs(Mt(x));R<=d||(d=R,l=x)}if(!l.length)return yt(un(n,r),t.clipBounds);const f=typeof t.simplifyTolerance=="number"&&Number.isFinite(t.simplifyTolerance)?Math.max(0,t.simplifyTolerance):s.step*.2,y=typeof t.smoothingPasses=="number"&&Number.isFinite(t.smoothingPasses)?Math.round(k(t.smoothingPasses,0,Ni)):ki,b=eo(to(ji(l,s.step*.001),y),f);return yt(b,t.clipBounds)}const At=[],nr=[],Qe={color:"#ff4d4f",width:2,lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},ro={color:"#4cc9f0",width:2,lineDash:[10,8],lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},io="rgba(23, 23, 25, 0.1)",oo=6,Oe={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},rr={x:16,y:-24},so=20,ir=1e-6,or="transparent",ao=3,co=2,Ur=96,uo=1,sr=1e3,Dr=2,kr=2,lo=4096,fo=.2,ho=1.12,mo=.89,go=32,po="#000000",bo=.1,yo="#FFCF00",wo="#FF0000",So=1.5,ar=[2,2],xo=1,Mo=.25,Ao=4,To=1,Ro=0,Co=4,Po=.05,Io=256,cr=1.5;function Kt(e,t,n){return[k(e[0],0,t),k(e[1],0,n)]}function jt(e){if(!Array.isArray(e)||e.length<2)return null;const t=Number(e[0]),n=Number(e[1]);return!Number.isFinite(t)||!Number.isFinite(n)?null:[t,n]}const ct=jt;function Be(e){return Ne(e)}function Ht(e){return Math.abs(Mt(Be(e)))}function ur(e){if(!Array.isArray(e)||e.length===0)return[0,0,0,0];let t=1/0,n=1/0,r=-1/0,i=-1/0;for(const[o,s]of e)o<t&&(t=o),o>r&&(r=o),s<n&&(n=s),s>i&&(i=s);return[t,n,r,i]}function pn(e,t,n=!1){if(t.length!==0){e.moveTo(t[0][0],t[0][1]);for(let r=1;r<t.length;r+=1)e.lineTo(t[r][0],t[r][1]);n&&e.closePath()}}function Xe(e,t,n,r=!1,i=!1,o="rgba(255, 77, 79, 0.16)"){t.length!==0&&(e.beginPath(),pn(e,t,r),i&&r&&(e.fillStyle=o,e.fill()),e.strokeStyle=n.color,e.lineWidth=n.width,e.lineJoin=n.lineJoin,e.lineCap=n.lineCap,e.shadowColor=n.shadowColor,e.shadowBlur=n.shadowBlur,e.shadowOffsetX=n.shadowOffsetX,e.shadowOffsetY=n.shadowOffsetY,e.setLineDash(n.lineDash),e.stroke(),e.setLineDash(At),e.shadowColor="rgba(0, 0, 0, 0)",e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0)}function Nr(e){const t=Array.isArray(e?.lineDash)?e.lineDash.filter(s=>Number.isFinite(s)&&s>=0):At,n=typeof e?.width=="number"&&Number.isFinite(e.width)?Math.max(0,e.width):Qe.width,r=typeof e?.shadowBlur=="number"&&Number.isFinite(e.shadowBlur)?Math.max(0,e.shadowBlur):Qe.shadowBlur,i=typeof e?.shadowOffsetX=="number"&&Number.isFinite(e.shadowOffsetX)?e.shadowOffsetX:Qe.shadowOffsetX,o=typeof e?.shadowOffsetY=="number"&&Number.isFinite(e.shadowOffsetY)?e.shadowOffsetY:Qe.shadowOffsetY;return{color:e?.color||Qe.color,width:n,lineDash:t.length?t:At,lineJoin:e?.lineJoin||Qe.lineJoin,lineCap:e?.lineCap||Qe.lineCap,shadowColor:e?.shadowColor||Qe.shadowColor,shadowBlur:r,shadowOffsetX:i,shadowOffsetY:o}}function wt(e,t){return t?Nr({color:t.color??e.color,width:t.width??e.width,lineDash:t.lineDash??e.lineDash,lineJoin:t.lineJoin??e.lineJoin,lineCap:t.lineCap??e.lineCap,shadowColor:t.shadowColor??e.shadowColor,shadowBlur:t.shadowBlur??e.shadowBlur,shadowOffsetX:t.shadowOffsetX??e.shadowOffsetX,shadowOffsetY:t.shadowOffsetY??e.shadowOffsetY}):e}function lr(e,t){return e==null||t===null||t===void 0?!1:String(e)===String(t)}function fr(e){return typeof e=="number"&&Number.isFinite(e)}function Eo(e){return Array.isArray(e)&&e.length>=2&&fr(e[0])&&fr(e[1])}function vo(e){return Array.isArray(e)&&e.length>=2&&e.every(t=>Eo(t))}function zr(e,t){if(!(!Array.isArray(e)||e.length===0)){if(vo(e)){t.push(e.map(([n,r])=>[n,r]));return}for(const n of e)zr(n,t)}}function dr(e,t){const n=[];zr(e,n);const r=[];for(const i of n){if(i.length<2)continue;const o=t?Be(i):i;o.length>=(t?4:2)&&r.push(o)}return r}function xt(e,t){return typeof e!="number"||!Number.isFinite(e)||e<=0?t:e}function _o(e,t){return typeof e!="number"||!Number.isFinite(e)?t:k(e,0,1)}function Or(e,t,n,r,i,o){const s=Math.max(0,Math.min(o,r*.5,i*.5));e.beginPath(),e.moveTo(t+s,n),e.lineTo(t+r-s,n),e.quadraticCurveTo(t+r,n,t+r,n+s),e.lineTo(t+r,n+i-s),e.quadraticCurveTo(t+r,n+i,t+r-s,n+i),e.lineTo(t+s,n+i),e.quadraticCurveTo(t,n+i,t,n+i-s),e.lineTo(t,n+s),e.quadraticCurveTo(t,n,t+s,n),e.closePath()}function Fo(e){const t=e[0];return Array.isArray(t)&&Array.isArray(t[0])}function Jt(e,t,n){if(!e||!t)return[];if(n){const r=n.worldToScreen(e[0],e[1]),i=n.worldToScreen(t[0],t[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 c=n.screenToWorld(a);if(!c)return Jt(e,t);s.push(c)}return Be(s)}}return Be([[e[0],e[1]],[t[0],e[1]],[t[0],t[1]],[e[0],t[1]]])}function bn(e,t,n=Ur){if(!e||!t)return[];const r=(e[0]+t[0])*.5,i=(e[1]+t[1])*.5,o=Math.hypot(t[0]-e[0],t[1]-e[1])*.5;if(o<1)return[];const s=[];for(let a=0;a<=n;a+=1){const c=a/n*Math.PI*2;s.push([r+Math.cos(c)*o,i+Math.sin(c)*o])}return Be(s)}function hr(e){const t=_r(Ct(e));if(t.length===0)return[];const n=[];for(const r of t){const i=r[0];if(!i||i.length<4)continue;const o=i.map(([a,c])=>[a,c]),s=[];for(let a=1;a<r.length;a+=1){const c=r[a];!c||c.length<4||s.push(c.map(([u,l])=>[u,l]))}n.push({outer:o,holes:s})}return n}function Bo(e){if(!Array.isArray(e))return ar;const t=e.filter(n=>Number.isFinite(n)&&n>=0);return t.length>0?t:ar}function Lo(e){return typeof e!="number"||!Number.isFinite(e)?xo:k(e,Mo,Ao)}function Uo(e){return typeof e!="number"||!Number.isFinite(e)?To:Math.round(k(e,Ro,Co))}function Do(e){const t=xt(e?.radius,go),n=xt(e?.cursorLineWidth,So),r=Lo(e?.edgeDetail),i=Uo(e?.edgeSmoothing);return{radius:t,edgeDetail:r,edgeSmoothing:i,clickSelectRoi:e?.clickSelectRoi===!0,fillColor:e?.fillColor||po,fillOpacity:_o(e?.fillOpacity,bo),cursorColor:e?.cursorColor||yo,cursorActiveColor:e?.cursorActiveColor||wo,cursorLineWidth:n,cursorLineDash:Bo(e?.cursorLineDash)}}function ko(e,t,n){if(!t.isDrawing||t.screenPoints.length===0)return;const r=t.screenPoints;if(r.length===0)return;const i=n.radius;if(!(!Number.isFinite(i)||i<=0)){if(e.save(),e.globalAlpha=n.fillOpacity,e.fillStyle=n.fillColor,e.strokeStyle=n.fillColor,e.lineCap="round",e.lineJoin="round",e.lineWidth=i*2,r.length===1)e.beginPath(),e.arc(r[0][0],r[0][1],i,0,Math.PI*2),e.fill();else{e.beginPath(),e.moveTo(r[0][0],r[0][1]);for(let o=1;o<r.length;o+=1)e.lineTo(r[o][0],r[o][1]);e.stroke()}e.restore()}}function No(e,t,n,r){const i=t.cursor;if(!i)return;const o=t.cursorScreen??ct(n?.worldToScreen(i[0],i[1])??[]);if(!o)return;const s=r.radius;!Number.isFinite(s)||s<=0||(e.save(),e.beginPath(),e.arc(o[0],o[1],s,0,Math.PI*2),e.strokeStyle=t.isDrawing?r.cursorActiveColor:r.cursorColor,e.lineWidth=r.cursorLineWidth,e.setLineDash(r.cursorLineDash),e.stroke(),e.setLineDash(At),e.restore())}const zo=.58,Oo=4096,Wo=.5;let kt=null;const Nt=new Map;function Yo(){if(kt)return kt;if(typeof document>"u")return null;const t=document.createElement("canvas").getContext("2d");return t?(kt=t,kt):null}function In(e,t){const n=`${t.fontWeight}|${t.fontSize}|${t.fontFamily}|${e}`,r=Nt.get(n);if(r!==void 0)return r;const i=e.length*t.fontSize*zo,o=Yo();let s=i;if(o){o.font=`${t.fontWeight} ${t.fontSize}px ${t.fontFamily}`;const a=o.measureText(e).width;Number.isFinite(a)&&a>=0&&(s=a)}return Nt.size>Oo&&Nt.clear(),Nt.set(n,s),s}function Xo(e){if(!e.length)return null;let t=1/0;for(const i of e)i[1]<t&&(t=i[1]);if(!Number.isFinite(t))return null;let n=1/0,r=-1/0;for(const i of e)Math.abs(i[1]-t)>Wo||(i[0]<n&&(n=i[0]),i[0]>r&&(r=i[0]));return!Number.isFinite(n)||!Number.isFinite(r)?null:[(n+r)*.5,t]}function Wr(e){let t=null;for(const n of e){const r=Xo(n.outer);r&&(!t||r[1]<t[1]||r[1]===t[1]&&r[0]<t[0])&&(t=r)}return t}function En(e){const t=typeof e?.paddingX=="number"&&Number.isFinite(e.paddingX)?Math.max(0,e.paddingX):Oe.paddingX,n=typeof e?.paddingY=="number"&&Number.isFinite(e.paddingY)?Math.max(0,e.paddingY):Oe.paddingY,r=typeof e?.fontSize=="number"&&Number.isFinite(e.fontSize)?Math.max(8,e.fontSize):Oe.fontSize,i=typeof e?.borderWidth=="number"&&Number.isFinite(e.borderWidth)?Math.max(0,e.borderWidth):Oe.borderWidth,o=typeof e?.offsetY=="number"&&Number.isFinite(e.offsetY)?e.offsetY:Oe.offsetY,s=typeof e?.borderRadius=="number"&&Number.isFinite(e.borderRadius)?Math.max(0,e.borderRadius):Oe.borderRadius;return{fontFamily:e?.fontFamily||Oe.fontFamily,fontSize:r,fontWeight:e?.fontWeight||Oe.fontWeight,textColor:e?.textColor||Oe.textColor,backgroundColor:e?.backgroundColor||Oe.backgroundColor,borderColor:e?.borderColor||Oe.borderColor,borderWidth:i,paddingX:t,paddingY:n,offsetY:o,borderRadius:s}}function Yr(e,t){return t?En({fontFamily:t.fontFamily??e.fontFamily,fontSize:t.fontSize??e.fontSize,fontWeight:t.fontWeight??e.fontWeight,textColor:t.textColor??e.textColor,backgroundColor:t.backgroundColor??e.backgroundColor,borderColor:t.borderColor??e.borderColor,borderWidth:t.borderWidth??e.borderWidth,paddingX:t.paddingX??e.paddingX,paddingY:t.paddingY??e.paddingY,offsetY:t.offsetY??e.offsetY,borderRadius:t.borderRadius??e.borderRadius}):e}function Xr(e,t,n){if(!e||!n)return 0;const r=Number(n.minZoom),i=Number(n.maxZoom);return!Number.isFinite(r)||!Number.isFinite(i)||i-r<=ir||!Number.isFinite(t)?0:t>=i-ir?so:0}function Vo(e){const t=typeof e?.fontSize=="number"&&Number.isFinite(e.fontSize)?Math.max(8,e.fontSize):et.fontSize,n=typeof e?.borderRadius=="number"&&Number.isFinite(e.borderRadius)?Math.max(0,e.borderRadius):et.borderRadius,r=typeof e?.paddingX=="number"&&Number.isFinite(e.paddingX)?Math.max(0,e.paddingX):et.paddingX,i=typeof e?.paddingY=="number"&&Number.isFinite(e.paddingY)?Math.max(0,e.paddingY):et.paddingY;return{fontFamily:e?.fontFamily||et.fontFamily,fontSize:t,fontWeight:e?.fontWeight||et.fontWeight,textColor:e?.textColor||et.textColor,backgroundColor:e?.backgroundColor||et.backgroundColor,borderRadius:n,paddingX:r,paddingY:i}}function Go(e){const t=typeof e?.x=="number"&&Number.isFinite(e.x)?e.x:rr.x,n=typeof e?.y=="number"&&Number.isFinite(e.y)?e.y:rr.y;return{x:t,y:n}}function qo(e){return Number.isFinite(e)?`${Math.max(0,e).toFixed(3)} mm²`:"0.000 mm²"}function Ho(e){const t=typeof e?.format=="function"?e.format:qo,n=Go(e?.cursorOffset);return{enabled:e?.enabled===!0,format:t,style:Vo(e?.style),cursorOffsetX:n.x,cursorOffsetY:n.y}}function $o(e,t,n,r,i,o){const s=t.trim();if(!s)return;e.save(),e.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,e.textAlign="center",e.textBaseline="middle";const c=In(s,o)+o.paddingX*2,u=o.fontSize+o.paddingY*2,l=k(n[0],c*.5+1,r-c*.5-1),d=k(n[1]-o.offsetY,u*.5+1,i-u*.5-1),f=l-c*.5,y=d-u*.5;e.fillStyle=o.backgroundColor,e.strokeStyle=o.borderColor,e.lineWidth=o.borderWidth,Or(e,f,y,c,u,o.borderRadius),e.fill(),o.borderWidth>0&&e.stroke(),e.fillStyle=o.textColor,e.fillText(s,l,d+.5),e.restore()}function Zo(e,t,n,r,i,o,s,a){const c=t.trim();if(!c)return;e.save(),e.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,e.textAlign="center",e.textBaseline="middle";const l=In(c,o)+o.paddingX*2,d=o.fontSize+o.paddingY*2,f=k(n[0]+s,l*.5+1,r-l*.5-1),y=k(n[1]+a,d*.5+1,i-d*.5-1),b=f-l*.5,w=y-d*.5;e.fillStyle=o.backgroundColor,Or(e,b,w,l,d,o.borderRadius),e.fill(),e.fillStyle=o.textColor,e.fillText(c,f,y+.5),e.restore()}function Ko(e,t,n,r){if(!(t.length<4||n.length===0)){e.save(),e.beginPath(),pn(e,t,!0);for(const i of n)i.length<4||pn(e,i,!0);e.fillStyle=r,e.fill("evenodd"),e.restore()}}function jo(e){const{ctx:t,overlayShapes:n,imageOuterRing:r,worldToScreenPoints:i,baseStrokeStyle:o,onInvertedFillDebug:s}=e,a=!!globalThis.__OPEN_PLANT_DEBUG_OVERLAY__;for(let c=0;c<n.length;c+=1){const u=n[c];if(!u?.coordinates?.length||u.visible===!1)continue;const l=u.closed??Fo(u.coordinates),d=dr(u.coordinates,l);if(u.invertedFill?.fillColor){const y=[],b=dr(u.coordinates,!0);for(const w of b){const x=i(w);x.length>=4&&y.push(x)}a&&s&&s({id:u.id??c,outerRingPoints:r.length,sourceRingCount:b.length,holeRingCount:y.length,fillColor:u.invertedFill.fillColor}),Ko(t,r,y,u.invertedFill.fillColor)}if(d.length===0)continue;const f=wt(o,u.stroke??u.strokeStyle);for(const y of d){const b=i(y);b.length<2||Xe(t,b,f,l,u.fill??!1)}}}function zt(e){return e==="stamp-rectangle"||e==="stamp-circle"||e==="stamp-rectangle-4096px"||e==="stamp-rectangle-2mm2"||e==="stamp-circle-2mm2"||e==="stamp-circle-hpf-0.2mm2"}function Jo(e){return{rectangleAreaMm2:xt(e?.rectangleAreaMm2,Dr),circleAreaMm2:xt(e?.circleAreaMm2,kr),rectanglePixelSize:xt(e?.rectanglePixelSize,lo)}}const mr=1e3;function Qo(e){return e*mr*mr}function gr(e,t,n){if(!e||!Number.isFinite(t)||t<=0)return[];if(n){const r=n.worldToScreen(e[0],e[1]),i=n.worldToScreen(e[0]+t,e[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 c of s){const u=n.screenToWorld(c);if(!u)throw new Error("Failed to create rectangle");a.push(u)}return Be(a)}}return Be([[e[0]-t,e[1]-t],[e[0]+t,e[1]-t],[e[0]+t,e[1]+t],[e[0]-t,e[1]+t]])}function es(e,t,n=Ur){if(!e||!Number.isFinite(t)||t<=0)return[];const r=[];for(let i=0;i<=n;i+=1){const o=i/n*Math.PI*2;r.push([e[0]+Math.cos(o)*t,e[1]+Math.sin(o)*t])}return Be(r)}function ts(e){const{stampTool:t,center:n,resolvedStampOptions:r,imageWidth:i,imageHeight:o,micronsToWorldPixels:s,getRectangleProjection:a}=e;if(!n)return[];if(t==="stamp-rectangle-4096px"){const d=r.rectanglePixelSize*.5;return gr(n,d,a()).map(f=>Kt(f,i,o))}let c=0;if(t==="stamp-rectangle"||t==="stamp-rectangle-2mm2"?c=t==="stamp-rectangle-2mm2"?Dr:r.rectangleAreaMm2:(t==="stamp-circle"||t==="stamp-circle-2mm2"||t==="stamp-circle-hpf-0.2mm2")&&(c=t==="stamp-circle-hpf-0.2mm2"?fo:t==="stamp-circle-2mm2"?kr:r.circleAreaMm2),!Number.isFinite(c)||c<=0)return[];const u=Qo(c);let l=[];if(t==="stamp-rectangle"||t==="stamp-rectangle-2mm2"){const d=s(Math.sqrt(u)*.5);l=gr(n,d,a())}else if(t==="stamp-circle"||t==="stamp-circle-2mm2"||t==="stamp-circle-hpf-0.2mm2"){const d=s(Math.sqrt(u/Math.PI));l=es(n,d)}return l.length?l.map(d=>Kt(d,i,o)):[]}function ns(e){return{color:io,width:oo,lineDash:At,lineJoin:e.lineJoin,lineCap:e.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function rs(e){if(typeof e!="string")return or;const t=e.trim();return t.length>0?t:or}function pr(e){return Array.isArray(e)&&e.length>=4&&Ht(e)>uo}function Vr({tool:e,imageWidth:t,imageHeight:n,imageMpp:r,imageZoom:i,stampOptions:o,brushOptions:s,projectorRef:a,onBrushTap:c,onDrawComplete:u,onPatchComplete:l,enabled:d,viewStateSignal:f,persistedRegions:y,patchRegions:b,persistedPolygons:w,drawFillColor:x,regionStrokeStyle:R,regionStrokeHoverStyle:E,regionStrokeActiveStyle:X,patchStrokeStyle:A,resolveRegionStrokeStyle:F,resolveRegionLabelStyle:K,overlayShapes:oe,hoveredRegionId:Q=null,activeRegionId:ee=null,regionLabelStyle:se,drawAreaTooltip:ge,autoLiftRegionLabelAtMaxZoom:Te=!1,regionLabelAutoLiftOffsetPx:_,invalidateRef:L,className:O,style:D}){const V=h.useRef(null),Le=h.useRef(!1),Re=h.useRef(new Map),Ve=h.useRef(e),de=h.useRef({isDrawing:!1,pointerId:null,start:null,current:null,cursor:null,cursorScreen:null,points:[],screenPoints:[],stampCenter:null}),ae=d??e!=="cursor",v=h.useMemo(()=>y&&y.length>0?y:!w||w.length===0?nr:w.map((m,g)=>({id:g,coordinates:m})),[y,w]),P=h.useMemo(()=>b??nr,[b]),N=h.useMemo(()=>{const m=[];for(let g=0;g<v.length;g+=1){const M=v[g],C=hr(M.coordinates);C.length!==0&&m.push({region:M,regionIndex:g,regionKey:M.id??g,polygons:C})}return m},[v]),ce=h.useMemo(()=>{const m=[];for(let g=0;g<P.length;g+=1){const M=P[g],C=hr(M.coordinates);C.length!==0&&m.push({region:M,regionIndex:g,regionKey:M.id??g,polygons:C})}return m},[P]),G=h.useMemo(()=>Nr(R),[R]),pe=h.useMemo(()=>wt(G,E),[G,E]),Se=h.useMemo(()=>wt(G,X),[G,X]),le=h.useMemo(()=>wt(ro,A),[A]),q=h.useMemo(()=>rs(x),[x]),he=h.useMemo(()=>En(se),[se]),te=h.useMemo(()=>Ho(ge),[ge]),ue=h.useMemo(()=>Jo(o),[o]),Z=h.useMemo(()=>Do(s),[s]),xe=h.useMemo(()=>({position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",touchAction:"none",pointerEvents:ae?"auto":"none",cursor:ae?e==="brush"?"none":"crosshair":"default",...D}),[ae,e,D]),ne=h.useCallback(()=>{const m=V.current;if(!m)return;const g=m.getBoundingClientRect(),M=Math.max(1,window.devicePixelRatio||1),C=Math.max(1,Math.round(g.width*M)),I=Math.max(1,Math.round(g.height*M));(m.width!==C||m.height!==I)&&(m.width=C,m.height=I)},[]),J=h.useCallback(m=>{const g=a.current;if(!g||m.length===0)return[];const M=new Array(m.length);for(let C=0;C<m.length;C+=1){const I=ct(g.worldToScreen(m[C][0],m[C][1]));if(!I)return[];M[C]=I}return M},[a]),Ce=h.useCallback(m=>{const g=a.current,M=V.current;if(!g||!M)return null;const C=M.getBoundingClientRect(),I=ct(g.screenToWorld(C.left+m[0],C.top+m[1]));return I?Kt(I,t,n):null},[a,t,n]),we=h.useCallback(()=>{const m=a.current,g=m?.getViewState?.().rotationDeg??0;if(!(Math.abs(g%360)<.01||!m))return{worldToScreen:(M,C)=>ct(m.worldToScreen(M,C)),screenToWorld:Ce}},[a,Ce]),Ge=h.useCallback(m=>{if(!Number.isFinite(m)||m<=0)return 0;const g=typeof r=="number"&&Number.isFinite(r)&&r>0?r:1,M=typeof i=="number"&&Number.isFinite(i)?i:0,C=a.current?.getViewState?.().zoom,I=typeof C=="number"&&Number.isFinite(C)&&C>0?C:1,me=M+Math.log2(I),H=Math.max(1e-9,Pn(g,M,me));return m/H/I},[r,i,a]),Ue=h.useCallback((m,g)=>ts({stampTool:m,center:g,resolvedStampOptions:ue,imageWidth:t,imageHeight:n,micronsToWorldPixels:Ge,getRectangleProjection:we}),[Ge,t,n,ue,we]),ve=h.useCallback(()=>{const m=de.current;return zt(e)?Ue(e,m.stampCenter):e==="brush"?[]:m.isDrawing?e==="freehand"?m.points:e==="rectangle"?Jt(m.start,m.current,we()):e==="circular"?bn(m.start,m.current):[]:[]},[e,Ue,we]),De=h.useCallback(()=>{ne();const m=V.current;if(!m)return;const g=m.getContext("2d");if(!g)return;const M=Math.max(1,window.devicePixelRatio||1),C=m.width/M,I=m.height/M;if(g.setTransform(1,0,0,1,0,0),g.clearRect(0,0,m.width,m.height),g.setTransform(M,0,0,M,0,0),N.length>0)for(const H of N){const{region:ie,polygons:$,regionIndex:re,regionKey:ye}=H,Ie=lr(ee,ye)?"active":lr(Q,ye)?"hover":"default";let ke=Ie==="active"?Se:Ie==="hover"?pe:G;if(F){const He=F({region:ie,regionId:ye,regionIndex:re,state:Ie});ke=wt(ke,He||void 0)}const rt=Ie==="default"?null:ns(ke);for(const He of $){const pt=J(He.outer);pt.length>=4&&(rt&&Xe(g,pt,rt,!0,!1),Xe(g,pt,ke,!0,!1));for(const bt of He.holes){const $e=J(bt);$e.length>=4&&(rt&&Xe(g,$e,rt,!0,!1),Xe(g,$e,ke,!0,!1))}}}if(ce.length>0)for(const H of ce)for(const ie of H.polygons){const $=J(ie.outer);$.length>=4&&Xe(g,$,le,!0,!1);for(const re of ie.holes){const ye=J(re);ye.length>=4&&Xe(g,ye,le,!0,!1)}}if(Array.isArray(oe)&&oe.length>0){const H=J(Be([[0,0],[t,0],[t,n],[0,n]]));jo({ctx:g,overlayShapes:oe,imageOuterRing:H,worldToScreenPoints:J,baseStrokeStyle:G,onInvertedFillDebug:globalThis.__OPEN_PLANT_DEBUG_OVERLAY__?ie=>{const $=String(ie.id),re=`${ie.outerRingPoints}|${ie.sourceRingCount}|${ie.holeRingCount}|${ie.fillColor}`;Re.current.get($)!==re&&(Re.current.set($,re),console.debug("[open-plant] invertedFill",ie))}:void 0})}const me=ve();if(ae){if(e==="brush")ko(g,de.current,Z),No(g,de.current,a.current,Z);else if(me.length>0)if(e==="freehand"){const H=J(me);H.length>=2&&Xe(g,H,G,!1,!1),H.length>=3&&Xe(g,J(Be(me)),G,!0,!0,q)}else{const H=J(me);H.length>=4&&Xe(g,H,G,!0,!0,q)}}if(N.length>0){const H=Math.max(1e-6,a.current?.getViewState?.().zoom??1),ie=typeof _=="number"&&Number.isFinite(_)?Math.max(0,_):Xr(Te,H,a.current?.getZoomRange?.());for(const $ of N){if(!$.region.label)continue;const re=Wr($.polygons);if(!re)continue;const ye=ct(a.current?.worldToScreen(re[0],re[1])??[]);if(!ye)continue;let Ie=Yr(he,K?.({region:$.region,regionId:$.regionKey,regionIndex:$.regionIndex,zoom:H}));ie>0&&(Ie={...Ie,offsetY:Ie.offsetY+ie}),$o(g,$.region.label,ye,C,I,Ie)}}if(te.enabled&&ae&&(e==="freehand"||e==="rectangle"||e==="circular")){const H=de.current;if(H.isDrawing){const ie=e==="freehand"?Be(me):me;if(ie.length>=4){const $=Ht(ie),re=typeof r=="number"&&Number.isFinite(r)&&r>0?r:0,ye=re>0?$*re*re/(sr*sr):0,Ie=te.format(ye),ke=H.cursorScreen??(H.current?ct(a.current?.worldToScreen(H.current[0],H.current[1])??[]):null);ke&&Zo(g,Ie,ke,C,I,te.style,te.cursorOffsetX,te.cursorOffsetY)}}}},[ae,e,ve,ne,J,t,n,a,N,oe,Q,ee,G,pe,Se,q,ce,le,F,K,he,te,Te,_,r,Z]),W=h.useCallback(()=>{Le.current||(Le.current=!0,requestAnimationFrame(()=>{Le.current=!1,De()}))},[De]),Y=h.useCallback((m=!1)=>{const g=de.current,M=V.current;M&&g.pointerId!==null&&M.hasPointerCapture(g.pointerId)&&M.releasePointerCapture(g.pointerId),g.isDrawing=!1,g.pointerId=null,g.start=null,g.current=null,g.points=[],g.screenPoints=[],g.stampCenter=null,m||(g.cursor=null,g.cursorScreen=null)},[]),Me=h.useCallback(m=>{const g=a.current;if(!g||t<=0||n<=0)return null;const M=ct(g.screenToWorld(m.clientX,m.clientY));return M?Kt(M,t,n):null},[a,t,n]),Pe=h.useCallback(m=>{const g=V.current;if(!g)return null;const M=g.getBoundingClientRect(),C=k(m.clientX-M.left,0,M.width),I=k(m.clientY-M.top,0,M.height);return!Number.isFinite(C)||!Number.isFinite(I)?null:[C,I]},[]),be=h.useCallback(()=>{const m=de.current;if(!m.isDrawing){Y(!0),W();return}let g=[];if(e==="freehand")m.points.length>=ao&&(g=Be(m.points));else if(e==="rectangle")g=Jt(m.start,m.current,we());else if(e==="circular")g=bn(m.start,m.current);else if(e==="brush"){const M=m.points[m.points.length-1]??m.current??m.start;if(Z.clickSelectRoi&&M&&m.points.length<=1&&c?.(M)){Y(!0),W();return}const C=Z.edgeDetail,I=Math.max(Po,Z.radius*2/(Io*C)),me=m.screenPoints.length>0?m.screenPoints:J(m.points),H=no(me,{radius:Z.radius,minRasterStep:I,circleSides:Math.max(24,Math.round(64*C)),simplifyTolerance:I*.25,smoothingPasses:Z.edgeSmoothing}),ie=[];for(const $ of H){const re=Ce($);re&&ie.push(re)}g=Be(ie)}(e==="freehand"||e==="rectangle"||e==="circular"||e==="brush")&&pr(g)&&u&&u({tool:e,intent:e==="brush"?"brush":"roi",coordinates:g,bbox:ur(g),areaPx:Ht(g)}),Y(!0),W()},[e,u,Y,W,J,Ce,we,Z.radius,Z.edgeDetail,Z.edgeSmoothing,Z.clickSelectRoi,c]),Ae=h.useCallback((m,g)=>{const M=Ue(m,g);if(!pr(M))return;const C=m==="stamp-rectangle-4096px"?"patch":"roi",I={tool:m,intent:C,coordinates:M,bbox:ur(M),areaPx:Ht(M)};u?.(I),C==="patch"&&l&&l(I)},[Ue,u,l]),tt=h.useCallback((m,g,M)=>{const C=cr*cr,I=m.screenPoints[m.screenPoints.length-1];if(!I){m.points.push(g),m.screenPoints.push(M),m.current=g;return}const me=M[0]-I[0],H=M[1]-I[1];me*me+H*H>=C?(m.points.push(g),m.screenPoints.push(M)):(m.points[m.points.length-1]=g,m.screenPoints[m.screenPoints.length-1]=M),m.current=g},[]),It=h.useCallback(m=>{if(!ae||e==="cursor"||m.button!==0)return;const g=Me(m);if(!g)return;const M=Pe(m);if(!M)return;if(m.preventDefault(),m.stopPropagation(),zt(e)){const me=de.current;me.stampCenter=g,Ae(e,g),W();return}const C=V.current;C&&C.setPointerCapture(m.pointerId);const I=de.current;I.isDrawing=!0,I.pointerId=m.pointerId,I.start=g,I.current=g,I.cursor=g,I.cursorScreen=M,I.points=e==="freehand"||e==="brush"?[g]:[],I.screenPoints=e==="brush"?[M]:[],W()},[ae,e,Me,Pe,Ae,W]),nt=h.useCallback(m=>{if(!ae||e==="cursor")return;const g=Me(m);if(!g)return;const M=Pe(m);if(!M)return;const C=de.current;if(C.cursor=g,C.cursorScreen=M,zt(e)){C.stampCenter=g,m.preventDefault(),m.stopPropagation(),W();return}if(e==="brush"){if(!C.isDrawing||C.pointerId!==m.pointerId){W();return}m.preventDefault(),m.stopPropagation(),tt(C,g,M),W();return}if(!(!C.isDrawing||C.pointerId!==m.pointerId)){if(m.preventDefault(),m.stopPropagation(),e==="freehand"){const I=a.current,me=Math.max(1e-6,I?.getViewState?.().zoom??1),H=co/me,ie=H*H,$=C.points[C.points.length-1];if(!$)C.points.push(g);else{const re=g[0]-$[0],ye=g[1]-$[1];re*re+ye*ye>=ie&&C.points.push(g)}}else C.current=g;W()}},[ae,e,Me,Pe,W,a,tt]),Et=h.useCallback(m=>{const g=de.current;if(!g.isDrawing||g.pointerId!==m.pointerId)return;m.preventDefault(),m.stopPropagation();const M=Me(m),C=Pe(m);M&&(g.cursor=M,C&&(g.cursorScreen=C),e==="brush"?C&&tt(g,M,C):g.current=M);const I=V.current;I&&I.hasPointerCapture(m.pointerId)&&I.releasePointerCapture(m.pointerId),be()},[be,Me,Pe,e,tt]),vt=h.useCallback(()=>{const m=de.current;let g=!1;e==="brush"&&!m.isDrawing&&m.cursor&&(m.cursor=null,m.cursorScreen=null,g=!0),zt(e)&&m.stampCenter&&(m.stampCenter=null,g=!0),g&&W()},[e,W]);return h.useEffect(()=>{ne(),W();const m=V.current;if(!m)return;const g=new ResizeObserver(()=>{ne(),W()});return g.observe(m),()=>{g.disconnect()}},[ne,W]),h.useEffect(()=>{ae||Y(),W()},[ae,W,Y]),h.useEffect(()=>{Ve.current!==e&&(Ve.current=e,Y(),W())},[e,Y,W]),h.useEffect(()=>{W()},[f,v,oe,W]),h.useEffect(()=>{if(L)return L.current=W,()=>{L.current===W&&(L.current=null)}},[L,W]),h.useEffect(()=>{if(!ae)return;const m=g=>{g.key==="Escape"&&(Y(),W())};return window.addEventListener("keydown",m),()=>{window.removeEventListener("keydown",m)}},[ae,Y,W]),We.jsx("canvas",{ref:V,className:O,style:xe,onPointerDown:It,onPointerMove:nt,onPointerUp:Et,onPointerCancel:Et,onPointerLeave:vt,onContextMenu:m=>{ae&&m.preventDefault()},onWheel:m=>{if(!ae)return;const g=V.current,M=a.current;if(!g||typeof M?.zoomBy!="function")return;m.preventDefault(),m.stopPropagation();const C=g.getBoundingClientRect(),I=m.clientX-C.left,me=m.clientY-C.top;M.zoomBy(m.deltaY<0?ho:mo,I,me),W()}})}function br(e){return String(e??"").replace(/\/+$/,"")}function Gr(e){const t=String(e??"");return t.startsWith("/")?t:`/${t}`}function is(e){const t=br(e);if(!t)return"";if(/\/TileGroup\d+$/i.test(t))return t;let n=null;try{n=new URL(t)}catch{n=null}if(n){const r=`${n.protocol}//${n.host}`,i=br(n.pathname||"");return/\/ims$/i.test(i)?`${r}${i}`:/\/tiles$/i.test(i)?`${r}${i}`:`${r}${i}/tiles`}return/\/ims$/i.test(t)?"/ims":/\/tiles$/i.test(t)?`${t}`:`${t}/tiles`}function os(e,t){const n=e?.imsInfo??{},r=!!e?.imsInfo,i=Number(n.width??e?.width??0),o=Number(n.height??e?.height??0),s=Number(n.tileSize??e?.tileSize??0),a=Number(n.zoom??e?.zoom??0),c=String(n.path??e?.path??""),u=Number(n.mpp??e?.mpp??0);if(!i||!o||!s||!c)throw new Error("Incomplete image metadata: width/height/tileSize/path required");const l=Array.isArray(e?.terms)?e.terms.map(b=>({termId:String(b?.termId??""),termName:String(b?.termName??""),termColor:String(b?.termColor??"")})):[],d=Gr(c),f=is(t),y=r?(b,w,x)=>`${f}${d}/${b}/${x}_${w}.webp`:void 0;return{id:e?._id||"unknown",name:e?.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:c,tileBaseUrl:t,terms:l,tileUrlBuilder:y}}function vn(e,t,n,r){if(e.tileUrlBuilder)return e.tileUrlBuilder(t,n,r);const i=Gr(e.tilePath);return`${e.tileBaseUrl}${i}/${t}/${r}_${n}.webp`}const Fe={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:"#171719",viewportBorderStyle:"dash",viewportFillColor:"transparent",interactive:!0,showThumbnail:!0,maxThumbnailTiles:16};function yr(e,t,n,r){const i=t.length;if(i===4){for(let o=0;o<i;o+=1){const s=t[o],a=t[(o+1)%i],c=Math.hypot(a[0]-s[0],a[1]-s[1]);if(c<1e-6)continue;const u=Math.max(1,Math.round((c+r)/(n+r))),l=u*n+(u-1)*r,d=c/Math.max(1e-6,l),f=n*d,y=r*d;e.beginPath(),e.moveTo(s[0],s[1]),e.lineTo(a[0],a[1]),e.setLineDash([f,y]),e.lineDashOffset=0,e.stroke()}e.setLineDash([]),e.lineDashOffset=0}}function mt(e,t,n=1){return typeof e!="number"||!Number.isFinite(e)?t:Math.max(n,e)}function Ot(e){return Array.isArray(e)&&e.length===4&&Number.isFinite(e[0])&&Number.isFinite(e[1])&&Number.isFinite(e[2])&&Number.isFinite(e[3])}const ss={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 qr({source:e,projectorRef:t,authToken:n="",options:r,invalidateRef:i,className:o,style:s}){const a=h.useRef(null),c=h.useRef(null),u=h.useRef(null),l=h.useRef({active:!1,pointerId:null}),d=h.useRef(null),f=h.useRef(!1),y=mt(r?.width,Fe.width,64),b=mt(r?.height,Fe.height,48),w=h.useMemo(()=>{const v=Math.max(1,e.width),P=Math.max(1,e.height),N=v/P,ce=y/b;let G,pe;return N>ce?(G=y,pe=y/N):(pe=b,G=b*N),{x:(y-G)/2,y:(b-pe)/2,w:G,h:pe}},[e.width,e.height,y,b]),x=mt(r?.margin,Fe.margin,0),R=mt(r?.borderRadius,Fe.borderRadius,0),E=mt(r?.borderWidth,Fe.borderWidth,0),X=Math.max(1,Math.round(mt(r?.maxThumbnailTiles,Fe.maxThumbnailTiles,1))),A=r?.backgroundColor||Fe.backgroundColor,F=r?.borderColor||Fe.borderColor,K=r?.viewportBorderColor||Fe.viewportBorderColor,oe=r?.viewportBorderStyle==="stroke"||r?.viewportBorderStyle==="dash"?r.viewportBorderStyle:Fe.viewportBorderStyle,Q=r?.viewportFillColor??Fe.viewportFillColor,ee=r?.interactive??Fe.interactive,se=r?.showThumbnail??Fe.showThumbnail,ge=r?.position||Fe.position,Te=r?.onClose,_=r?.closeIcon,L=r?.closeButtonStyle,O=h.useMemo(()=>{const v={};return ge==="top-left"||ge==="bottom-left"?v.left=x:v.right=x,ge==="top-left"||ge==="top-right"?v.top=x:v.bottom=x,{position:"absolute",...v,width:y,height:b,borderRadius:R,overflow:"hidden",zIndex:4,pointerEvents:ee?"auto":"none",touchAction:"none",boxShadow:"0 10px 22px rgba(0, 0, 0, 0.3)",...s}},[x,ge,y,b,R,ee,s]),D=h.useCallback(()=>{const v=a.current;if(!v)return;const P=v.getContext("2d");if(!P)return;const N=y,ce=b,G=Math.max(1,window.devicePixelRatio||1),pe=Math.max(1,Math.round(N*G)),Se=Math.max(1,Math.round(ce*G));(v.width!==pe||v.height!==Se)&&(v.width=pe,v.height=Se),P.setTransform(1,0,0,1,0,0),P.clearRect(0,0,v.width,v.height),P.setTransform(G,0,0,G,0,0),P.fillStyle=A,P.fillRect(0,0,N,ce);const{x:le,y:q,w:he,h:te}=w,ue=c.current;ue&&P.drawImage(ue,le,q,he,te),P.strokeStyle=F,P.lineWidth=E,P.strokeRect(E*.5,E*.5,N-E,ce-E);const Z=t.current,xe=Z?.getViewBounds?.(),ne=Z?.getViewCorners?.(),J=Ot(xe)?xe:Ot(u.current)?u.current:null;if(!J)return;u.current=J;const Ce=he/Math.max(1,e.width),we=te/Math.max(1,e.height),Ge=Array.isArray(ne)&&ne.length>=4&&ne.every(be=>Array.isArray(be)&&be.length>=2&&Number.isFinite(be[0])&&Number.isFinite(be[1]))?ne:null,Ue=oe==="dash";if(Ge){const be=Ge.map(Ae=>[le+Ae[0]*Ce,q+Ae[1]*we]);P.save(),P.beginPath(),P.rect(le,q,he,te),P.clip(),P.beginPath();for(let Ae=0;Ae<be.length;Ae+=1)Ae===0?P.moveTo(be[Ae][0],be[Ae][1]):P.lineTo(be[Ae][0],be[Ae][1]);P.closePath(),P.fillStyle=Q,P.fill(),P.strokeStyle=K,P.lineWidth=2.25,Ue?yr(P,be,4,3):P.stroke(),P.restore();return}const ve=k(le+J[0]*Ce,le,le+he),De=k(q+J[1]*we,q,q+te),W=k(le+J[2]*Ce,le,le+he),Y=k(q+J[3]*we,q,q+te),Me=Math.max(1,W-ve),Pe=Math.max(1,Y-De);if(P.fillStyle=Q,P.fillRect(ve,De,Me,Pe),P.strokeStyle=K,P.lineWidth=2.25,Ue){const be=[[ve+.5,De+.5],[ve+.5+Math.max(1,Me-1),De+.5],[ve+.5+Math.max(1,Me-1),De+.5+Math.max(1,Pe-1)],[ve+.5,De+.5+Math.max(1,Pe-1)]];yr(P,be,4,3)}else P.strokeRect(ve+.5,De+.5,Math.max(1,Me-1),Math.max(1,Pe-1))},[y,b,w,A,F,E,t,e.width,e.height,Q,K,oe]),V=h.useCallback(()=>{f.current||(f.current=!0,d.current=requestAnimationFrame(()=>{f.current=!1,d.current=null,D()}))},[D]),Le=h.useCallback((v,P)=>{const N=a.current;if(!N)return null;const ce=N.getBoundingClientRect();if(!ce.width||!ce.height)return null;const G=ce.width/y,pe=ce.height/b,Se=w.x*G,le=w.y*pe,q=w.w*G,he=w.h*pe,te=k((v-ce.left-Se)/q,0,1),ue=k((P-ce.top-le)/he,0,1);return[te*e.width,ue*e.height]},[e.width,e.height,y,b,w]),Re=h.useCallback((v,P)=>{const N=t.current;if(!N)return;if(N.setViewCenter){N.setViewCenter(v,P),V();return}const ce=N.getViewBounds?.(),G=Ot(ce)?ce:Ot(u.current)?u.current:null;if(!G)return;const pe=Math.max(1e-6,G[2]-G[0]),Se=Math.max(1e-6,G[3]-G[1]);N.setViewState({offsetX:v-pe*.5,offsetY:P-Se*.5}),V()},[t,V]),Ve=h.useCallback(v=>{if(!ee||v.button!==0)return;const P=a.current;if(!P)return;const N=Le(v.clientX,v.clientY);N&&(v.preventDefault(),v.stopPropagation(),P.setPointerCapture(v.pointerId),l.current={active:!0,pointerId:v.pointerId},Re(N[0],N[1]))},[ee,Le,Re]),de=h.useCallback(v=>{const P=l.current;if(!P.active||P.pointerId!==v.pointerId)return;const N=Le(v.clientX,v.clientY);N&&(v.preventDefault(),v.stopPropagation(),Re(N[0],N[1]))},[Le,Re]),ae=h.useCallback(v=>{const P=l.current;if(!P.active||P.pointerId!==v.pointerId)return;const N=a.current;if(N&&N.hasPointerCapture(v.pointerId))try{N.releasePointerCapture(v.pointerId)}catch{}l.current={active:!1,pointerId:null},V()},[V]);return h.useEffect(()=>{let v=!1;c.current=null,V();const P=0,N=2**(e.maxTierZoom-P),ce=Math.ceil(e.width/N),G=Math.ceil(e.height/N),pe=Math.max(1,Math.ceil(ce/e.tileSize)),Se=Math.max(1,Math.ceil(G/e.tileSize)),le=pe*Se;if(!se||le>X)return;const q=document.createElement("canvas");q.width=Math.max(1,Math.round(w.w)),q.height=Math.max(1,Math.round(w.h));const he=q.getContext("2d");if(!he)return;he.fillStyle=A,he.fillRect(0,0,q.width,q.height);const te=[];for(let ue=0;ue<Se;ue+=1)for(let Z=0;Z<pe;Z+=1){const xe=Z*e.tileSize*N,ne=ue*e.tileSize*N,J=Math.min((Z+1)*e.tileSize,ce)*N,Ce=Math.min((ue+1)*e.tileSize,G)*N;te.push({url:vn(e,P,Z,ue),bounds:[xe,ne,J,Ce]})}return Promise.allSettled(te.map(async ue=>{const Z=!!n,xe=await fetch(ue.url,{headers:Z?{Authorization:n}:void 0});if(!xe.ok)throw new Error(`HTTP ${xe.status}`);const ne=await createImageBitmap(await xe.blob());return{tile:ue,bitmap:ne}})).then(ue=>{if(v){for(const ne of ue)ne.status==="fulfilled"&&ne.value.bitmap.close();return}const Z=q.width/Math.max(1,e.width),xe=q.height/Math.max(1,e.height);for(const ne of ue){if(ne.status!=="fulfilled")continue;const{tile:{bounds:J},bitmap:Ce}=ne.value,we=J[0]*Z,Ge=J[1]*xe,Ue=Math.max(1,(J[2]-J[0])*Z),ve=Math.max(1,(J[3]-J[1])*xe);he.drawImage(Ce,we,Ge,Ue,ve),Ce.close()}c.current=q,V()}),()=>{v=!0}},[e,n,w,A,se,X,V]),h.useEffect(()=>{V()},[V]),h.useEffect(()=>{if(i)return i.current=V,()=>{i.current===V&&(i.current=null)}},[i,V]),h.useEffect(()=>()=>{l.current={active:!1,pointerId:null},d.current!==null&&(cancelAnimationFrame(d.current),d.current=null),f.current=!1},[]),We.jsxs("div",{className:o,style:O,children:[We.jsx("canvas",{ref:a,style:{width:"100%",height:"100%",display:"block",borderRadius:"inherit"},onPointerDown:Ve,onPointerMove:de,onPointerUp:ae,onPointerCancel:ae,onContextMenu:v=>{v.preventDefault()},onWheel:v=>{v.preventDefault(),v.stopPropagation()}}),Te&&We.jsx("button",{type:"button","aria-label":"Hide overview map",onClick:v=>{v.stopPropagation(),Te()},style:L?{...L}:{...ss},children:_??"×"})]})}function as({imageWidth:e,imageHeight:t,tiles:n,viewState:r,className:i,style:o}){const s=h.useRef(null),a=h.useRef(null),c=h.useMemo(()=>({width:"100%",height:"100%",display:"block",...o}),[o]);return h.useEffect(()=>{const u=s.current;if(!u)return;const l=new Ir({canvas:u,imageWidth:e,imageHeight:t,initialViewState:r});return a.current=l,l.setTiles(n),()=>{l.destroy(),a.current=null}},[e,t]),h.useEffect(()=>{const u=a.current;u&&u.setTiles(n)},[n]),h.useEffect(()=>{const u=a.current;!u||!r||u.setViewState(r)},[r]),We.jsx("canvas",{ref:s,className:i,style:c})}function Tt(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return null;const n=Pt(t??[]);if(n.length===0){const b={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return e.fillModes instanceof Uint8Array&&(b.fillModes=new Uint8Array(0)),e.ids instanceof Uint32Array&&(b.ids=new Uint32Array(0)),b}const r=ut(e),i=e.positions,o=e.paletteIndices,s=e.fillModes instanceof Uint8Array&&e.fillModes.length>=r?e.fillModes:null,a=e.ids instanceof Uint32Array&&e.ids.length>=r?e.ids:null,c=new Float32Array(r*2),u=new Uint16Array(r),l=s?new Uint8Array(r):null,d=a?new Uint32Array(r):null;let f=0;for(let b=0;b<r;b+=1){const w=i[b*2],x=i[b*2+1];Zt(w,x,n)&&(c[f*2]=w,c[f*2+1]=x,u[f]=o[b],l&&(l[f]=s[b]),d&&(d[f]=a[b]),f+=1)}const y={count:f,positions:c.subarray(0,f*2),paletteIndices:u.subarray(0,f)};return l&&(y.fillModes=l.subarray(0,f)),d&&(y.ids=d.subarray(0,f)),y}function Hr(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return new Uint32Array(0);const n=Pt(t??[]);if(n.length===0)return new Uint32Array(0);const r=ut(e);if(r===0)return new Uint32Array(0);const i=e.positions,o=new Uint32Array(r);let s=0;for(let a=0;a<r;a+=1){const c=i[a*2],u=i[a*2+1];Zt(c,u,n)&&(o[s]=a,s+=1)}return o.subarray(0,s)}let Wt=null;const cs=`
32
+ `;class vr{constructor(t){S(this,"canvas");S(this,"gl");S(this,"camera",new Er);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=t.canvas,this.imageWidth=Math.max(1,t.imageWidth),this.imageHeight=Math.max(1,t.imageHeight),this.clearColor=t.clearColor??[.03,.05,.08,1],this.gl=Pi(this.canvas),this.program=Pn(this.gl,Ii,Ei);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=Pe(this.gl,this.program,"uCamera"),this.uBoundsLocation=Pe(this.gl,this.program,"uBounds"),this.uTextureLocation=Pe(this.gl,this.program,"uTexture"),t.initialViewState&&(this.controlledViewState=!0,this.camera.setViewState(t.initialViewState)),this.resizeObserver=new ResizeObserver(()=>{this.resize()}),this.resizeObserver.observe(this.canvas),this.resize()}async setTiles(t){if(this.destroyed)return;const n=++this.loadVersion,r=await Promise.all(t.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(t){this.controlledViewState=!0,this.camera.setViewState(t),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(t,n){try{const r=await fetch(t.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:t.id,bounds:t.bounds,texture:s}}catch(r){return console.error(`[M1TileRenderer] tile load failed: ${t.id}`,r),null}}resize(){if(this.destroyed)return;const t=this.canvas.getBoundingClientRect(),n=Math.max(1,t.width||this.canvas.clientWidth||1),r=Math.max(1,t.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 t=this.camera.getViewportSize(),n=Math.min(t.width/this.imageWidth,t.height/this.imageHeight),r=Number.isFinite(n)&&n>0?n:1,i=t.width/r,o=t.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 t of this.tiles)this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,t.texture),this.gl.uniform4f(this.uBoundsLocation,t.bounds[0],t.bounds[1],t.bounds[2],t.bounds[3]),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindVertexArray(null)}}disposeTiles(t){for(const n of t)this.gl.deleteTexture(n.texture)}}function It(e){return e??null}function nr(e){return typeof e=="number"&&Number.isFinite(e)}function vi(e){return Array.isArray(e)&&e.length>=2&&nr(e[0])&&nr(e[1])}function _r(e){return Array.isArray(e)&&e.length>0&&e.every(t=>vi(t))}function Fr(e){return Array.isArray(e)&&e.length>0&&e.every(t=>_r(t))}function _i(e){return Array.isArray(e)&&e.length>0&&e.every(t=>Fr(t))}function Ue(e){if(!Array.isArray(e)||e.length<3)return[];const t=[];for(const i of e){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=t[t.length-1];a&&a[0]===o&&a[1]===s||t.push([o,s])}if(t.length<3)return[];const n=t[0],r=t[t.length-1];return(n[0]!==r[0]||n[1]!==r[1])&&t.push([n[0],n[1]]),t.length>=4?t:[]}function Tt(e){if(!Array.isArray(e)||e.length<4)return 0;let t=0;for(let n=0;n<e.length-1;n+=1){const r=e[n],i=e[n+1];t+=r[0]*i[1]-i[0]*r[1]}return t*.5}function ln(e){if(!Array.isArray(e)||e.length===0)return[];const t=[];for(const o of e){const s=Ue(o);s.length>=4&&t.push(s)}if(t.length===0)return[];if(t.length===1)return[t[0]];let n=0,r=0;for(let o=0;o<t.length;o+=1){const s=Math.abs(Tt(t[o]));s<=r||(r=s,n=o)}const i=[t[n]];for(let o=0;o<t.length;o+=1)o!==n&&i.push(t[o]);return i}function Br(e){if(!e)return[];if(_r(e)){const t=ln([e]);return t.length>0?[t]:[]}if(Fr(e)){const t=ln(e);return t.length>0?[t]:[]}if(_i(e)){const t=[];for(const n of e){const r=ln(n);r.length>0&&t.push(r)}return t}return[]}function rr(e,t,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],c=n[o][0],u=n[o][1];a>t!=u>t&&e<(c-s)*(t-a)/(u-a||Number.EPSILON)+s&&(r=!r)}return r}function Et(e){const t=[];for(const n of e??[]){const r=Br(n);for(const i of r){const o=i[0];if(!o||o.length<4)continue;let s=1/0,a=1/0,c=-1/0,u=-1/0;for(const[h,f]of o)h<s&&(s=h),h>c&&(c=h),f<a&&(a=f),f>u&&(u=f);if(!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(c)||!Number.isFinite(u))continue;let l=Math.abs(Tt(o));for(let h=1;h<i.length;h+=1)l-=Math.abs(Tt(i[h]));t.push({outer:o,holes:i.slice(1),minX:s,minY:a,maxX:c,maxY:u,area:Math.max(1e-6,l)})}}return t}function Ur(e,t,n){if(e<n.minX||e>n.maxX||t<n.minY||t>n.maxY||!rr(e,t,n.outer))return!1;for(const r of n.holes)if(rr(e,t,r))return!1;return!0}function jt(e,t,n){for(const r of n)if(Ur(e,t,r))return!0;return!1}const In=[160,160,160,255];function k(e,t,n){return Math.max(t,Math.min(n,e))}function En(e,t,n){const r=Number(e),i=Number(t),o=Number(n);return!Number.isFinite(r)||r<=0?1:!Number.isFinite(i)||!Number.isFinite(o)?r:Math.pow(2,i-o)*r}function Fi(e,t,n){let i=100*En(e,t,n);if(Number(e)){let o="μm";return i>1e3&&(i/=1e3,o="mm"),`${i.toPrecision(3)} ${o}`}return`${Math.round(i*1e3)/1e3} pixels`}function fe(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function at(e){const t=e.fillModes instanceof Uint8Array?e.fillModes.length:Number.MAX_SAFE_INTEGER;return Math.max(0,Math.min(Math.floor(e.count??0),Math.floor((e.positions?.length??0)/2),e.paletteIndices?.length??0,t))}function bn(e,t){return!e&&!t?!0:!e||!t?!1:Math.abs((e.zoom??0)-(t.zoom??0))<1e-6&&Math.abs((e.offsetX??0)-(t.offsetX??0))<1e-6&&Math.abs((e.offsetY??0)-(t.offsetY??0))<1e-6&&Math.abs((e.rotationDeg??0)-(t.rotationDeg??0))<1e-6}function Bi(e){const t=String(e??"").trim();if(!t)return"";if(/^bearer\s+/i.test(t)){const n=t.replace(/^bearer\s+/i,"").trim();return n?`Bearer ${n}`:""}return`Bearer ${t}`}function Lr(e){const n=String(e??"").trim().match(/^#?([0-9a-fA-F]{6})$/);if(!n)return[...In];const r=Number.parseInt(n[1],16);return[r>>16&255,r>>8&255,r&255,255]}function Ui(e){const t=[[...In]],n=new Map;for(const i of e??[]){const o=String(i?.termId??"");!o||n.has(o)||(n.set(o,t.length),t.push(Lr(i?.termColor)))}const r=new Uint8Array(t.length*4);for(let i=0;i<t.length;i+=1)r[i*4]=t[i][0],r[i*4+1]=t[i][1],r[i*4+2]=t[i][2],r[i*4+3]=t[i][3];return{colors:r,termToPaletteIndex:n}}const Li=.1,Di=4e6,ki=4096,Ni=64,zi=1,Oi=4,Dr=1e-6,Wi=24;function Yi(e){if(!Array.isArray(e)||e.length===0)return[];const t=[];for(const n of e){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=t[t.length-1];o&&Math.abs(o[0]-r)<1e-9&&Math.abs(o[1]-i)<1e-9||t.push([r,i])}return t}function Xi(e,t,n){if(t<=Dr||n<8)return[];const r=[];for(let i=0;i<=n;i+=1){const o=i/n*Math.PI*2;r.push([e[0]+Math.cos(o)*t,e[1]+Math.sin(o)*t])}return Ue(r)}function fn(e,t){if(!e.length)return[];let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[a,c]of e)a<n&&(n=a),a>i&&(i=a),c<r&&(r=c),c>o&&(o=c);if(!Number.isFinite(n)||!Number.isFinite(r))return[];const s=Math.max(t,1);return Ue([[n-s,r-s],[i+s,r-s],[i+s,o+s],[n-s,o+s]])}function Vi(e,t){let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[a,c]of e)a<n&&(n=a),a>i&&(i=a),c<r&&(r=c),c>o&&(o=c);const s=Math.max(t,1);return[n-s,r-s,i+s,o+s]}function Gi(e,t,n){const r=Math.max(Li,Number(n.minRasterStep)||0),i=Math.max(32768,Math.floor(n.maxRasterPixels||Di)),o=Math.max(256,Math.floor(n.maxRasterSize||ki)),s=Math.max(.001,e[2]-e[0]),a=Math.max(.001,e[3]-e[1]);let c=Math.max(r,Number.EPSILON),u=3,l=Math.ceil(s/c)+u*2+1,h=Math.ceil(a/c)+u*2+1;for(;(l>o||h>o||l*h>i)&&(c*=1.15,l=Math.ceil(s/c)+u*2+1,h=Math.ceil(a/c)+u*2+1,!(c>Math.max(s,a))););return l=Math.max(8,l),h=Math.max(8,h),{minX:e[0],minY:e[1],step:c,padding:u,width:l,height:h}}function qi(e,t){if(typeof OffscreenCanvas<"u"){const r=new OffscreenCanvas(e,t).getContext("2d",{willReadFrequently:!0});if(r)return r}if(typeof document<"u"){const n=document.createElement("canvas");return n.width=e,n.height=t,n.getContext("2d",{willReadFrequently:!0})}return null}function Hi(e,t){return[(e[0]-t.minX)/t.step+t.padding,(e[1]-t.minY)/t.step+t.padding]}function $i(e,t,n){const r=qi(n.width,n.height);if(!r)return new Uint8Array(0);r.clearRect(0,0,n.width,n.height),r.fillStyle="#ffffff",r.strokeStyle="#ffffff",r.lineCap="round",r.lineJoin="round",r.lineWidth=t*2/n.step;const i=e.map(a=>Hi(a,n));if(i.length<=1){const a=i[0];if(!a)return new Uint8Array(0);r.beginPath(),r.arc(a[0],a[1],t/n.step,0,Math.PI*2),r.fill()}else{r.beginPath(),r.moveTo(i[0][0],i[0][1]);for(let a=1;a<i.length;a+=1)r.lineTo(i[a][0],i[a][1]);r.stroke()}const o=r.getImageData(0,0,n.width,n.height),s=new Uint8Array(n.width*n.height);for(let a=0;a<s.length;a+=1)s[a]=o.data[a*4+3]>=Wi?1:0;return s}function Zi(e,t,n){const r=[],i=t+1,o=(a,c)=>c*i+a,s=(a,c)=>a>=0&&c>=0&&a<t&&c<n&&e[c*t+a]>0;for(let a=0;a<n;a+=1)for(let c=0;c<t;c+=1)s(c,a)&&(s(c,a-1)||r.push({start:o(c,a),end:o(c+1,a),dir:0}),s(c+1,a)||r.push({start:o(c+1,a),end:o(c+1,a+1),dir:1}),s(c,a+1)||r.push({start:o(c+1,a+1),end:o(c,a+1),dir:2}),s(c-1,a)||r.push({start:o(c,a+1),end:o(c,a),dir:3}));return r}function Ki(e,t){const n=(t-e+4)%4;return n===1?0:n===0?1:n===3?2:3}function ji(e){if(!e.length)return[];const t=new Map;for(let i=0;i<e.length;i+=1){const o=t.get(e[i].start);o?o.push(i):t.set(e[i].start,[i])}const n=new Uint8Array(e.length),r=[];for(let i=0;i<e.length;i+=1){if(n[i])continue;const o=e[i],s=o.start;let a=o.end,c=o.dir;const u=[o.start,o.end];n[i]=1;let l=0;const h=e.length*3;for(;a!==s&&l<h;){const f=t.get(a);if(!f||f.length===0)break;let y=-1,b=1/0;for(const w of f){if(n[w])continue;const A=e[w],E=Ki(c,A.dir);E<b&&(b=E,y=w)}if(y<0)break;n[y]=1;const x=e[y];a=x.end,c=x.dir,u.push(a),l+=1}u.length>=4&&u[0]===u[u.length-1]&&r.push(u)}return r}function Ji(e,t,n){const r=t+1,i=[];for(const o of e){const s=o%r,a=Math.floor(o/r);i.push([n.minX+(s-n.padding)*n.step,n.minY+(a-n.padding)*n.step])}return Ue(i)}function Qi(e,t=1e-9){const n=Ue(e);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],c=(s[0]-o[0])*(a[1]-s[1])-(s[1]-o[1])*(a[0]-s[0]);Math.abs(c)<=t||r.push(s)}return r.push(r[0]),Ue(r)}function eo(e,t,n){const r=n[0]-t[0],i=n[1]-t[1],o=r*r+i*i;if(o<=1e-12){const h=e[0]-t[0],f=e[1]-t[1];return h*h+f*f}const s=k(((e[0]-t[0])*r+(e[1]-t[1])*i)/o,0,1),a=t[0]+r*s,c=t[1]+i*s,u=e[0]-a,l=e[1]-c;return u*u+l*l}function to(e,t){if(e.length<=2||t<=0)return e.slice();const n=new Uint8Array(e.length);n[0]=1,n[e.length-1]=1;const r=t*t,i=[[0,e.length-1]];for(;i.length>0;){const s=i.pop();if(!s)break;const[a,c]=s;if(c-a<=1)continue;let u=0,l=-1;for(let h=a+1;h<c;h+=1){const f=eo(e[h],e[a],e[c]);f>u&&(u=f,l=h)}l>=0&&u>r&&(n[l]=1,i.push([a,l],[l,c]))}const o=[];for(let s=0;s<e.length;s+=1)n[s]&&o.push(e[s]);return o}function no(e,t){const n=Ue(e);if(n.length<5||t<=0)return n;const r=n.slice(0,-1),i=to(r,t);return i.length<3?n:Ue(i)}function ro(e,t){let n=Ue(e);if(t<=0||n.length<5)return n;for(let r=0;r<t;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],c=i[(s+1)%i.length];o.push([a[0]*.75+c[0]*.25,a[1]*.75+c[1]*.25],[a[0]*.25+c[0]*.75,a[1]*.25+c[1]*.75])}n=Ue(o)}return n}function St(e,t){return t?Ue(e.map(([n,r])=>[k(n,t[0],t[2]),k(r,t[1],t[3])])):e}function io(e,t){const n=Yi(e),r=Math.max(Dr,Number(t.radius)||0);if(n.length===0||!Number.isFinite(r))return[];const i=Math.max(12,Math.floor(t.circleSides||Ni));if(n.length===1)return St(Xi(n[0],r,i),t.clipBounds);const o=Vi(n,r),s=Gi(o,r,t),a=$i(n,r,s);if(!a.length)return St(fn(n,r),t.clipBounds);const c=Zi(a,s.width,s.height),u=ji(c);if(!u.length)return St(fn(n,r),t.clipBounds);let l=[],h=0;for(const x of u){const w=Ji(x,s.width,s),A=Math.abs(Tt(w));A<=h||(h=A,l=w)}if(!l.length)return St(fn(n,r),t.clipBounds);const f=typeof t.simplifyTolerance=="number"&&Number.isFinite(t.simplifyTolerance)?Math.max(0,t.simplifyTolerance):s.step*.2,y=typeof t.smoothingPasses=="number"&&Number.isFinite(t.smoothingPasses)?Math.round(k(t.smoothingPasses,0,Oi)):zi,b=no(ro(Qi(l,s.step*.001),y),f);return St(b,t.clipBounds)}const Rt=[],ir=[],je={color:"#ff4d4f",width:2,lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},oo={color:"#4cc9f0",width:2,lineDash:[10,8],lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},so="rgba(23, 23, 25, 0.1)",ao=6,Ne={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},or={x:16,y:-24},co=20,sr=1e-6,ar="transparent",uo=3,lo=2,kr=96,fo=1,cr=1e3,Nr=2,zr=2,ho=4096,mo=.2,go=1.12,po=.89,bo=32,yo="#000000",wo=.1,So="#FFCF00",xo="#FF0000",Mo=1.5,ur=[2,2],Ao=1,To=.25,Ro=4,Co=1,Po=0,Io=4,Eo=.05,vo=256,lr=1.5;function Jt(e,t,n){return[k(e[0],0,t),k(e[1],0,n)]}function Qt(e){if(!Array.isArray(e)||e.length<2)return null;const t=Number(e[0]),n=Number(e[1]);return!Number.isFinite(t)||!Number.isFinite(n)?null:[t,n]}const st=Qt;function _e(e){return Ue(e)}function Zt(e){return Math.abs(Tt(_e(e)))}function fr(e){if(!Array.isArray(e)||e.length===0)return[0,0,0,0];let t=1/0,n=1/0,r=-1/0,i=-1/0;for(const[o,s]of e)o<t&&(t=o),o>r&&(r=o),s<n&&(n=s),s>i&&(i=s);return[t,n,r,i]}function yn(e,t,n=!1){if(t.length!==0){e.moveTo(t[0][0],t[0][1]);for(let r=1;r<t.length;r+=1)e.lineTo(t[r][0],t[r][1]);n&&e.closePath()}}function Xe(e,t,n,r=!1,i=!1,o="rgba(255, 77, 79, 0.16)"){t.length!==0&&(e.beginPath(),yn(e,t,r),i&&r&&(e.fillStyle=o,e.fill()),e.strokeStyle=n.color,e.lineWidth=n.width,e.lineJoin=n.lineJoin,e.lineCap=n.lineCap,e.shadowColor=n.shadowColor,e.shadowBlur=n.shadowBlur,e.shadowOffsetX=n.shadowOffsetX,e.shadowOffsetY=n.shadowOffsetY,e.setLineDash(n.lineDash),e.stroke(),e.setLineDash(Rt),e.shadowColor="rgba(0, 0, 0, 0)",e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0)}function Or(e){const t=Array.isArray(e?.lineDash)?e.lineDash.filter(s=>Number.isFinite(s)&&s>=0):Rt,n=typeof e?.width=="number"&&Number.isFinite(e.width)?Math.max(0,e.width):je.width,r=typeof e?.shadowBlur=="number"&&Number.isFinite(e.shadowBlur)?Math.max(0,e.shadowBlur):je.shadowBlur,i=typeof e?.shadowOffsetX=="number"&&Number.isFinite(e.shadowOffsetX)?e.shadowOffsetX:je.shadowOffsetX,o=typeof e?.shadowOffsetY=="number"&&Number.isFinite(e.shadowOffsetY)?e.shadowOffsetY:je.shadowOffsetY;return{color:e?.color||je.color,width:n,lineDash:t.length?t:Rt,lineJoin:e?.lineJoin||je.lineJoin,lineCap:e?.lineCap||je.lineCap,shadowColor:e?.shadowColor||je.shadowColor,shadowBlur:r,shadowOffsetX:i,shadowOffsetY:o}}function xt(e,t){return t?Or({color:t.color??e.color,width:t.width??e.width,lineDash:t.lineDash??e.lineDash,lineJoin:t.lineJoin??e.lineJoin,lineCap:t.lineCap??e.lineCap,shadowColor:t.shadowColor??e.shadowColor,shadowBlur:t.shadowBlur??e.shadowBlur,shadowOffsetX:t.shadowOffsetX??e.shadowOffsetX,shadowOffsetY:t.shadowOffsetY??e.shadowOffsetY}):e}function dr(e,t){return e==null||t===null||t===void 0?!1:String(e)===String(t)}function hr(e){return typeof e=="number"&&Number.isFinite(e)}function _o(e){return Array.isArray(e)&&e.length>=2&&hr(e[0])&&hr(e[1])}function Fo(e){return Array.isArray(e)&&e.length>=2&&e.every(t=>_o(t))}function Wr(e,t){if(!(!Array.isArray(e)||e.length===0)){if(Fo(e)){t.push(e.map(([n,r])=>[n,r]));return}for(const n of e)Wr(n,t)}}function mr(e,t){const n=[];Wr(e,n);const r=[];for(const i of n){if(i.length<2)continue;const o=t?_e(i):i;o.length>=(t?4:2)&&r.push(o)}return r}function At(e,t){return typeof e!="number"||!Number.isFinite(e)||e<=0?t:e}function Bo(e,t){return typeof e!="number"||!Number.isFinite(e)?t:k(e,0,1)}function Yr(e,t,n,r,i,o){const s=Math.max(0,Math.min(o,r*.5,i*.5));e.beginPath(),e.moveTo(t+s,n),e.lineTo(t+r-s,n),e.quadraticCurveTo(t+r,n,t+r,n+s),e.lineTo(t+r,n+i-s),e.quadraticCurveTo(t+r,n+i,t+r-s,n+i),e.lineTo(t+s,n+i),e.quadraticCurveTo(t,n+i,t,n+i-s),e.lineTo(t,n+s),e.quadraticCurveTo(t,n,t+s,n),e.closePath()}function Uo(e){const t=e[0];return Array.isArray(t)&&Array.isArray(t[0])}function en(e,t,n){if(!e||!t)return[];if(n){const r=n.worldToScreen(e[0],e[1]),i=n.worldToScreen(t[0],t[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 c=n.screenToWorld(a);if(!c)return en(e,t);s.push(c)}return _e(s)}}return _e([[e[0],e[1]],[t[0],e[1]],[t[0],t[1]],[e[0],t[1]]])}function wn(e,t,n=kr){if(!e||!t)return[];const r=(e[0]+t[0])*.5,i=(e[1]+t[1])*.5,o=Math.hypot(t[0]-e[0],t[1]-e[1])*.5;if(o<1)return[];const s=[];for(let a=0;a<=n;a+=1){const c=a/n*Math.PI*2;s.push([r+Math.cos(c)*o,i+Math.sin(c)*o])}return _e(s)}function gr(e){const t=Br(It(e));if(t.length===0)return[];const n=[];for(const r of t){const i=r[0];if(!i||i.length<4)continue;const o=i.map(([a,c])=>[a,c]),s=[];for(let a=1;a<r.length;a+=1){const c=r[a];!c||c.length<4||s.push(c.map(([u,l])=>[u,l]))}n.push({outer:o,holes:s})}return n}function Lo(e){if(!Array.isArray(e))return ur;const t=e.filter(n=>Number.isFinite(n)&&n>=0);return t.length>0?t:ur}function Do(e){return typeof e!="number"||!Number.isFinite(e)?Ao:k(e,To,Ro)}function ko(e){return typeof e!="number"||!Number.isFinite(e)?Co:Math.round(k(e,Po,Io))}function No(e){const t=At(e?.radius,bo),n=At(e?.cursorLineWidth,Mo),r=Do(e?.edgeDetail),i=ko(e?.edgeSmoothing);return{radius:t,edgeDetail:r,edgeSmoothing:i,clickSelectRoi:e?.clickSelectRoi===!0,fillColor:e?.fillColor||yo,fillOpacity:Bo(e?.fillOpacity,wo),cursorColor:e?.cursorColor||So,cursorActiveColor:e?.cursorActiveColor||xo,cursorLineWidth:n,cursorLineDash:Lo(e?.cursorLineDash)}}function zo(e,t,n){if(!t.isDrawing||t.screenPoints.length===0)return;const r=t.screenPoints;if(r.length===0)return;const i=n.radius;if(!(!Number.isFinite(i)||i<=0)){if(e.save(),e.globalAlpha=n.fillOpacity,e.fillStyle=n.fillColor,e.strokeStyle=n.fillColor,e.lineCap="round",e.lineJoin="round",e.lineWidth=i*2,r.length===1)e.beginPath(),e.arc(r[0][0],r[0][1],i,0,Math.PI*2),e.fill();else{e.beginPath(),e.moveTo(r[0][0],r[0][1]);for(let o=1;o<r.length;o+=1)e.lineTo(r[o][0],r[o][1]);e.stroke()}e.restore()}}function Oo(e,t,n,r){const i=t.cursor;if(!i)return;const o=t.cursorScreen??st(n?.worldToScreen(i[0],i[1])??[]);if(!o)return;const s=r.radius;!Number.isFinite(s)||s<=0||(e.save(),e.beginPath(),e.arc(o[0],o[1],s,0,Math.PI*2),e.strokeStyle=t.isDrawing?r.cursorActiveColor:r.cursorColor,e.lineWidth=r.cursorLineWidth,e.setLineDash(r.cursorLineDash),e.stroke(),e.setLineDash(Rt),e.restore())}const Wo=.58,Yo=4096,Xo=.5;let zt=null;const Ot=new Map;function Vo(){if(zt)return zt;if(typeof document>"u")return null;const t=document.createElement("canvas").getContext("2d");return t?(zt=t,zt):null}function vn(e,t){const n=`${t.fontWeight}|${t.fontSize}|${t.fontFamily}|${e}`,r=Ot.get(n);if(r!==void 0)return r;const i=e.length*t.fontSize*Wo,o=Vo();let s=i;if(o){o.font=`${t.fontWeight} ${t.fontSize}px ${t.fontFamily}`;const a=o.measureText(e).width;Number.isFinite(a)&&a>=0&&(s=a)}return Ot.size>Yo&&Ot.clear(),Ot.set(n,s),s}function Go(e,t="top-center"){if(!e.length)return null;let n=1/0;for(const o of e)o[1]<n&&(n=o[1]);if(!Number.isFinite(n))return null;let r=1/0,i=-1/0;for(const o of e)Math.abs(o[1]-n)>Xo||(o[0]<r&&(r=o[0]),o[0]>i&&(i=o[0]));return!Number.isFinite(r)||!Number.isFinite(i)?null:t==="top-center"?[(r+i)*.5,n]:[r,n]}function Xr(e,t="top-center"){let n=null;for(const r of e){const i=Go(r.outer,t);i&&(!n||i[1]<n[1]||i[1]===n[1]&&i[0]<n[0])&&(n=i)}return n}function _n(e){const t=typeof e?.paddingX=="number"&&Number.isFinite(e.paddingX)?Math.max(0,e.paddingX):Ne.paddingX,n=typeof e?.paddingY=="number"&&Number.isFinite(e.paddingY)?Math.max(0,e.paddingY):Ne.paddingY,r=typeof e?.fontSize=="number"&&Number.isFinite(e.fontSize)?Math.max(8,e.fontSize):Ne.fontSize,i=typeof e?.borderWidth=="number"&&Number.isFinite(e.borderWidth)?Math.max(0,e.borderWidth):Ne.borderWidth,o=typeof e?.offsetY=="number"&&Number.isFinite(e.offsetY)?e.offsetY:Ne.offsetY,s=typeof e?.borderRadius=="number"&&Number.isFinite(e.borderRadius)?Math.max(0,e.borderRadius):Ne.borderRadius;return{fontFamily:e?.fontFamily||Ne.fontFamily,fontSize:r,fontWeight:e?.fontWeight||Ne.fontWeight,textColor:e?.textColor||Ne.textColor,backgroundColor:e?.backgroundColor||Ne.backgroundColor,borderColor:e?.borderColor||Ne.borderColor,borderWidth:i,paddingX:t,paddingY:n,offsetY:o,borderRadius:s}}function Vr(e,t){return t?_n({fontFamily:t.fontFamily??e.fontFamily,fontSize:t.fontSize??e.fontSize,fontWeight:t.fontWeight??e.fontWeight,textColor:t.textColor??e.textColor,backgroundColor:t.backgroundColor??e.backgroundColor,borderColor:t.borderColor??e.borderColor,borderWidth:t.borderWidth??e.borderWidth,paddingX:t.paddingX??e.paddingX,paddingY:t.paddingY??e.paddingY,offsetY:t.offsetY??e.offsetY,borderRadius:t.borderRadius??e.borderRadius}):e}function Gr(e,t,n){if(!e||!n)return 0;const r=Number(n.minZoom),i=Number(n.maxZoom);return!Number.isFinite(r)||!Number.isFinite(i)||i-r<=sr||!Number.isFinite(t)?0:t>=i-sr?co:0}function qo(e){const t=typeof e?.fontSize=="number"&&Number.isFinite(e.fontSize)?Math.max(8,e.fontSize):Je.fontSize,n=typeof e?.borderRadius=="number"&&Number.isFinite(e.borderRadius)?Math.max(0,e.borderRadius):Je.borderRadius,r=typeof e?.paddingX=="number"&&Number.isFinite(e.paddingX)?Math.max(0,e.paddingX):Je.paddingX,i=typeof e?.paddingY=="number"&&Number.isFinite(e.paddingY)?Math.max(0,e.paddingY):Je.paddingY;return{fontFamily:e?.fontFamily||Je.fontFamily,fontSize:t,fontWeight:e?.fontWeight||Je.fontWeight,textColor:e?.textColor||Je.textColor,backgroundColor:e?.backgroundColor||Je.backgroundColor,borderRadius:n,paddingX:r,paddingY:i}}function Ho(e){const t=typeof e?.x=="number"&&Number.isFinite(e.x)?e.x:or.x,n=typeof e?.y=="number"&&Number.isFinite(e.y)?e.y:or.y;return{x:t,y:n}}function $o(e){return Number.isFinite(e)?`${Math.max(0,e).toFixed(3)} mm²`:"0.000 mm²"}function Zo(e){const t=typeof e?.format=="function"?e.format:$o,n=Ho(e?.cursorOffset);return{enabled:e?.enabled===!0,format:t,style:qo(e?.style),cursorOffsetX:n.x,cursorOffsetY:n.y}}function Ko(e,t,n,r,i,o,s=!0){const a=t.trim();if(!a)return;e.save(),e.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,e.textAlign="center",e.textBaseline="middle";const u=vn(a,o)+o.paddingX*2,l=o.fontSize+o.paddingY*2,h=n[0],f=n[1]-o.offsetY,y=s?k(h,u*.5+1,r-u*.5-1):h,b=s?k(f,l*.5+1,i-l*.5-1):f,x=y-u*.5,w=b-l*.5;e.fillStyle=o.backgroundColor,e.strokeStyle=o.borderColor,e.lineWidth=o.borderWidth,Yr(e,x,w,u,l,o.borderRadius),e.fill(),o.borderWidth>0&&e.stroke(),e.fillStyle=o.textColor,e.fillText(a,y,b+.5),e.restore()}function jo(e,t,n,r,i,o,s,a){const c=t.trim();if(!c)return;e.save(),e.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,e.textAlign="center",e.textBaseline="middle";const l=vn(c,o)+o.paddingX*2,h=o.fontSize+o.paddingY*2,f=k(n[0]+s,l*.5+1,r-l*.5-1),y=k(n[1]+a,h*.5+1,i-h*.5-1),b=f-l*.5,x=y-h*.5;e.fillStyle=o.backgroundColor,Yr(e,b,x,l,h,o.borderRadius),e.fill(),e.fillStyle=o.textColor,e.fillText(c,f,y+.5),e.restore()}function Jo(e,t,n,r){if(!(t.length<4||n.length===0)){e.save(),e.beginPath(),yn(e,t,!0);for(const i of n)i.length<4||yn(e,i,!0);e.fillStyle=r,e.fill("evenodd"),e.restore()}}function Qo(e){const{ctx:t,overlayShapes:n,imageOuterRing:r,worldToScreenPoints:i,baseStrokeStyle:o,onInvertedFillDebug:s}=e,a=!!globalThis.__OPEN_PLANT_DEBUG_OVERLAY__;for(let c=0;c<n.length;c+=1){const u=n[c];if(!u?.coordinates?.length||u.visible===!1)continue;const l=u.closed??Uo(u.coordinates),h=mr(u.coordinates,l);if(u.invertedFill?.fillColor){const y=[],b=mr(u.coordinates,!0);for(const x of b){const w=i(x);w.length>=4&&y.push(w)}a&&s&&s({id:u.id??c,outerRingPoints:r.length,sourceRingCount:b.length,holeRingCount:y.length,fillColor:u.invertedFill.fillColor}),Jo(t,r,y,u.invertedFill.fillColor)}if(h.length===0)continue;const f=xt(o,u.stroke??u.strokeStyle);for(const y of h){const b=i(y);b.length<2||Xe(t,b,f,l,u.fill??!1)}}}function Wt(e){return e==="stamp-rectangle"||e==="stamp-circle"||e==="stamp-rectangle-4096px"||e==="stamp-rectangle-2mm2"||e==="stamp-circle-2mm2"||e==="stamp-circle-hpf-0.2mm2"}function es(e){return{rectangleAreaMm2:At(e?.rectangleAreaMm2,Nr),circleAreaMm2:At(e?.circleAreaMm2,zr),rectanglePixelSize:At(e?.rectanglePixelSize,ho)}}const pr=1e3;function ts(e){return e*pr*pr}function br(e,t,n){if(!e||!Number.isFinite(t)||t<=0)return[];if(n){const r=n.worldToScreen(e[0],e[1]),i=n.worldToScreen(e[0]+t,e[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 c of s){const u=n.screenToWorld(c);if(!u)throw new Error("Failed to create rectangle");a.push(u)}return _e(a)}}return _e([[e[0]-t,e[1]-t],[e[0]+t,e[1]-t],[e[0]+t,e[1]+t],[e[0]-t,e[1]+t]])}function ns(e,t,n=kr){if(!e||!Number.isFinite(t)||t<=0)return[];const r=[];for(let i=0;i<=n;i+=1){const o=i/n*Math.PI*2;r.push([e[0]+Math.cos(o)*t,e[1]+Math.sin(o)*t])}return _e(r)}function rs(e){const{stampTool:t,center:n,resolvedStampOptions:r,imageWidth:i,imageHeight:o,micronsToWorldPixels:s,getRectangleProjection:a}=e;if(!n)return[];if(t==="stamp-rectangle-4096px"){const h=r.rectanglePixelSize*.5;return br(n,h,a()).map(f=>Jt(f,i,o))}let c=0;if(t==="stamp-rectangle"||t==="stamp-rectangle-2mm2"?c=t==="stamp-rectangle-2mm2"?Nr:r.rectangleAreaMm2:(t==="stamp-circle"||t==="stamp-circle-2mm2"||t==="stamp-circle-hpf-0.2mm2")&&(c=t==="stamp-circle-hpf-0.2mm2"?mo:t==="stamp-circle-2mm2"?zr:r.circleAreaMm2),!Number.isFinite(c)||c<=0)return[];const u=ts(c);let l=[];if(t==="stamp-rectangle"||t==="stamp-rectangle-2mm2"){const h=s(Math.sqrt(u)*.5);l=br(n,h,a())}else if(t==="stamp-circle"||t==="stamp-circle-2mm2"||t==="stamp-circle-hpf-0.2mm2"){const h=s(Math.sqrt(u/Math.PI));l=ns(n,h)}return l.length?l.map(h=>Jt(h,i,o)):[]}function is(e){return{color:so,width:ao,lineDash:Rt,lineJoin:e.lineJoin,lineCap:e.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function os(e){if(typeof e!="string")return ar;const t=e.trim();return t.length>0?t:ar}function yr(e){return Array.isArray(e)&&e.length>=4&&Zt(e)>fo}function qr({tool:e,imageWidth:t,imageHeight:n,imageMpp:r,imageZoom:i,stampOptions:o,brushOptions:s,projectorRef:a,onBrushTap:c,onDrawComplete:u,onPatchComplete:l,enabled:h,viewStateSignal:f,persistedRegions:y,patchRegions:b,persistedPolygons:x,drawFillColor:w,regionStrokeStyle:A,regionStrokeHoverStyle:E,regionStrokeActiveStyle:X,patchStrokeStyle:R,resolveRegionStrokeStyle:_,resolveRegionLabelStyle:H,overlayShapes:se,hoveredRegionId:j=null,activeRegionId:J=null,regionLabelStyle:ae,drawAreaTooltip:ge,autoLiftRegionLabelAtMaxZoom:Te=!1,regionLabelAnchor:B="top-center",clampRegionLabelToViewport:D=!0,regionLabelAutoLiftOffsetPx:O,invalidateRef:U,className:Q,style:Le}){const ue=d.useRef(null),Oe=d.useRef(!1),Fe=d.useRef(new Map),We=d.useRef(e),C=d.useRef({isDrawing:!1,pointerId:null,start:null,current:null,cursor:null,cursorScreen:null,points:[],screenPoints:[],stampCenter:null}),M=h??e!=="cursor",z=d.useMemo(()=>y&&y.length>0?y:!x||x.length===0?ir:x.map((m,g)=>({id:g,coordinates:m})),[y,x]),ce=d.useMemo(()=>b??ir,[b]),$=d.useMemo(()=>{const m=[];for(let g=0;g<z.length;g+=1){const T=z[g],I=gr(T.coordinates);I.length!==0&&m.push({region:T,regionIndex:g,regionKey:T.id??g,polygons:I})}return m},[z]),le=d.useMemo(()=>{const m=[];for(let g=0;g<ce.length;g+=1){const T=ce[g],I=gr(T.coordinates);I.length!==0&&m.push({region:T,regionIndex:g,regionKey:T.id??g,polygons:I})}return m},[ce]),de=d.useMemo(()=>Or(A),[A]),ye=d.useMemo(()=>xt(de,E),[de,E]),ee=d.useMemo(()=>xt(de,X),[de,X]),he=d.useMemo(()=>xt(oo,R),[R]),re=d.useMemo(()=>os(w),[w]),ne=d.useMemo(()=>_n(ae),[ae]),K=d.useMemo(()=>Zo(ge),[ge]),xe=d.useMemo(()=>es(o),[o]),G=d.useMemo(()=>No(s),[s]),we=d.useMemo(()=>({position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",touchAction:"none",pointerEvents:M?"auto":"none",cursor:M?e==="brush"?"none":"crosshair":"default",...Le}),[M,e,Le]),pe=d.useCallback(()=>{const m=ue.current;if(!m)return;const g=m.getBoundingClientRect(),T=Math.max(1,window.devicePixelRatio||1),I=Math.max(1,Math.round(g.width*T)),v=Math.max(1,Math.round(g.height*T));(m.width!==I||m.height!==v)&&(m.width=I,m.height=v)},[]),Se=d.useCallback(m=>{const g=a.current;if(!g||m.length===0)return[];const T=new Array(m.length);for(let I=0;I<m.length;I+=1){const v=st(g.worldToScreen(m[I][0],m[I][1]));if(!v)return[];T[I]=v}return T},[a]),De=d.useCallback(m=>{const g=a.current,T=ue.current;if(!g||!T)return null;const I=T.getBoundingClientRect(),v=st(g.screenToWorld(I.left+m[0],I.top+m[1]));return v?Jt(v,t,n):null},[a,t,n]),Ae=d.useCallback(()=>{const m=a.current,g=m?.getViewState?.().rotationDeg??0;if(!(Math.abs(g%360)<.01||!m))return{worldToScreen:(T,I)=>st(m.worldToScreen(T,I)),screenToWorld:De}},[a,De]),Ie=d.useCallback(m=>{if(!Number.isFinite(m)||m<=0)return 0;const g=typeof r=="number"&&Number.isFinite(r)&&r>0?r:1,T=typeof i=="number"&&Number.isFinite(i)?i:0,I=a.current?.getViewState?.().zoom,v=typeof I=="number"&&Number.isFinite(I)&&I>0?I:1,me=T+Math.log2(v),V=Math.max(1e-9,En(g,T,me));return m/V/v},[r,i,a]),Re=d.useCallback((m,g)=>rs({stampTool:m,center:g,resolvedStampOptions:xe,imageWidth:t,imageHeight:n,micronsToWorldPixels:Ie,getRectangleProjection:Ae}),[Ie,t,n,xe,Ae]),ct=d.useCallback(()=>{const m=C.current;return Wt(e)?Re(e,m.stampCenter):e==="brush"?[]:m.isDrawing?e==="freehand"?m.points:e==="rectangle"?en(m.start,m.current,Ae()):e==="circular"?wn(m.start,m.current):[]:[]},[e,Re,Ae]),ut=d.useCallback(()=>{pe();const m=ue.current;if(!m)return;const g=m.getContext("2d");if(!g)return;const T=Math.max(1,window.devicePixelRatio||1),I=m.width/T,v=m.height/T;if(g.setTransform(1,0,0,1,0,0),g.clearRect(0,0,m.width,m.height),g.setTransform(T,0,0,T,0,0),$.length>0)for(const V of $){const{region:oe,polygons:q,regionIndex:te,regionKey:Me}=V,Ce=dr(J,Me)?"active":dr(j,Me)?"hover":"default";let Be=Ce==="active"?ee:Ce==="hover"?ye:de;if(_){const Ge=_({region:oe,regionId:Me,regionIndex:te,state:Ce});Be=xt(Be,Ge||void 0)}const tt=Ce==="default"?null:is(Be);for(const Ge of q){const yt=Se(Ge.outer);yt.length>=4&&(tt&&Xe(g,yt,tt,!0,!1),Xe(g,yt,Be,!0,!1));for(const wt of Ge.holes){const qe=Se(wt);qe.length>=4&&(tt&&Xe(g,qe,tt,!0,!1),Xe(g,qe,Be,!0,!1))}}}if(le.length>0)for(const V of le)for(const oe of V.polygons){const q=Se(oe.outer);q.length>=4&&Xe(g,q,he,!0,!1);for(const te of oe.holes){const Me=Se(te);Me.length>=4&&Xe(g,Me,he,!0,!1)}}if(Array.isArray(se)&&se.length>0){const V=Se(_e([[0,0],[t,0],[t,n],[0,n]]));Qo({ctx:g,overlayShapes:se,imageOuterRing:V,worldToScreenPoints:Se,baseStrokeStyle:de,onInvertedFillDebug:globalThis.__OPEN_PLANT_DEBUG_OVERLAY__?oe=>{const q=String(oe.id),te=`${oe.outerRingPoints}|${oe.sourceRingCount}|${oe.holeRingCount}|${oe.fillColor}`;Fe.current.get(q)!==te&&(Fe.current.set(q,te),console.debug("[open-plant] invertedFill",oe))}:void 0})}const me=ct();if(M){if(e==="brush")zo(g,C.current,G),Oo(g,C.current,a.current,G);else if(me.length>0)if(e==="freehand"){const V=Se(me);V.length>=2&&Xe(g,V,de,!1,!1),V.length>=3&&Xe(g,Se(_e(me)),de,!0,!0,re)}else{const V=Se(me);V.length>=4&&Xe(g,V,de,!0,!0,re)}}if($.length>0){const V=Math.max(1e-6,a.current?.getViewState?.().zoom??1),oe=typeof O=="number"&&Number.isFinite(O)?Math.max(0,O):Gr(Te,V,a.current?.getZoomRange?.());for(const q of $){if(!q.region.label)continue;const te=Xr(q.polygons,B);if(!te)continue;const Me=st(a.current?.worldToScreen(te[0],te[1])??[]);if(!Me)continue;let Ce=Vr(ne,H?.({region:q.region,regionId:q.regionKey,regionIndex:q.regionIndex,zoom:V}));oe>0&&(Ce={...Ce,offsetY:Ce.offsetY+oe}),Ko(g,q.region.label,Me,I,v,Ce,D)}}if(K.enabled&&M&&(e==="freehand"||e==="rectangle"||e==="circular")){const V=C.current;if(V.isDrawing){const oe=e==="freehand"?_e(me):me;if(oe.length>=4){const q=Zt(oe),te=typeof r=="number"&&Number.isFinite(r)&&r>0?r:0,Me=te>0?q*te*te/(cr*cr):0,Ce=K.format(Me),Be=V.cursorScreen??(V.current?st(a.current?.worldToScreen(V.current[0],V.current[1])??[]):null);Be&&jo(g,Ce,Be,I,v,K.style,K.cursorOffsetX,K.cursorOffsetY)}}}},[M,e,ct,pe,Se,t,n,a,$,se,j,J,de,ye,ee,re,le,he,_,H,ne,K,Te,B,D,O,r,G]),W=d.useCallback(()=>{Oe.current||(Oe.current=!0,requestAnimationFrame(()=>{Oe.current=!1,ut()}))},[ut]),Y=d.useCallback((m=!1)=>{const g=C.current,T=ue.current;T&&g.pointerId!==null&&T.hasPointerCapture(g.pointerId)&&T.releasePointerCapture(g.pointerId),g.isDrawing=!1,g.pointerId=null,g.start=null,g.current=null,g.points=[],g.screenPoints=[],g.stampCenter=null,m||(g.cursor=null,g.cursorScreen=null)},[]),ie=d.useCallback(m=>{const g=a.current;if(!g||t<=0||n<=0)return null;const T=st(g.screenToWorld(m.clientX,m.clientY));return T?Jt(T,t,n):null},[a,t,n]),be=d.useCallback(m=>{const g=ue.current;if(!g)return null;const T=g.getBoundingClientRect(),I=k(m.clientX-T.left,0,T.width),v=k(m.clientY-T.top,0,T.height);return!Number.isFinite(I)||!Number.isFinite(v)?null:[I,v]},[]),pt=d.useCallback(()=>{const m=C.current;if(!m.isDrawing){Y(!0),W();return}let g=[];if(e==="freehand")m.points.length>=uo&&(g=_e(m.points));else if(e==="rectangle")g=en(m.start,m.current,Ae());else if(e==="circular")g=wn(m.start,m.current);else if(e==="brush"){const T=m.points[m.points.length-1]??m.current??m.start;if(G.clickSelectRoi&&T&&m.points.length<=1&&c?.(T)){Y(!0),W();return}const I=G.edgeDetail,v=Math.max(Eo,G.radius*2/(vo*I)),me=m.screenPoints.length>0?m.screenPoints:Se(m.points),V=io(me,{radius:G.radius,minRasterStep:v,circleSides:Math.max(24,Math.round(64*I)),simplifyTolerance:v*.25,smoothingPasses:G.edgeSmoothing}),oe=[];for(const q of V){const te=De(q);te&&oe.push(te)}g=_e(oe)}(e==="freehand"||e==="rectangle"||e==="circular"||e==="brush")&&yr(g)&&u&&u({tool:e,intent:e==="brush"?"brush":"roi",coordinates:g,bbox:fr(g),areaPx:Zt(g)}),Y(!0),W()},[e,u,Y,W,Se,De,Ae,G.radius,G.edgeDetail,G.edgeSmoothing,G.clickSelectRoi,c]),bt=d.useCallback((m,g)=>{const T=Re(m,g);if(!yr(T))return;const I=m==="stamp-rectangle-4096px"?"patch":"roi",v={tool:m,intent:I,coordinates:T,bbox:fr(T),areaPx:Zt(T)};u?.(v),I==="patch"&&l&&l(v)},[Re,u,l]),Qe=d.useCallback((m,g,T)=>{const I=lr*lr,v=m.screenPoints[m.screenPoints.length-1];if(!v){m.points.push(g),m.screenPoints.push(T),m.current=g;return}const me=T[0]-v[0],V=T[1]-v[1];me*me+V*V>=I?(m.points.push(g),m.screenPoints.push(T)):(m.points[m.points.length-1]=g,m.screenPoints[m.screenPoints.length-1]=T),m.current=g},[]),vt=d.useCallback(m=>{if(!M||e==="cursor"||m.button!==0)return;const g=ie(m);if(!g)return;const T=be(m);if(!T)return;if(m.preventDefault(),m.stopPropagation(),Wt(e)){const me=C.current;me.stampCenter=g,bt(e,g),W();return}const I=ue.current;I&&I.setPointerCapture(m.pointerId);const v=C.current;v.isDrawing=!0,v.pointerId=m.pointerId,v.start=g,v.current=g,v.cursor=g,v.cursorScreen=T,v.points=e==="freehand"||e==="brush"?[g]:[],v.screenPoints=e==="brush"?[T]:[],W()},[M,e,ie,be,bt,W]),et=d.useCallback(m=>{if(!M||e==="cursor")return;const g=ie(m);if(!g)return;const T=be(m);if(!T)return;const I=C.current;if(I.cursor=g,I.cursorScreen=T,Wt(e)){I.stampCenter=g,m.preventDefault(),m.stopPropagation(),W();return}if(e==="brush"){if(!I.isDrawing||I.pointerId!==m.pointerId){W();return}m.preventDefault(),m.stopPropagation(),Qe(I,g,T),W();return}if(!(!I.isDrawing||I.pointerId!==m.pointerId)){if(m.preventDefault(),m.stopPropagation(),e==="freehand"){const v=a.current,me=Math.max(1e-6,v?.getViewState?.().zoom??1),V=lo/me,oe=V*V,q=I.points[I.points.length-1];if(!q)I.points.push(g);else{const te=g[0]-q[0],Me=g[1]-q[1];te*te+Me*Me>=oe&&I.points.push(g)}}else I.current=g;W()}},[M,e,ie,be,W,a,Qe]),_t=d.useCallback(m=>{const g=C.current;if(!g.isDrawing||g.pointerId!==m.pointerId)return;m.preventDefault(),m.stopPropagation();const T=ie(m),I=be(m);T&&(g.cursor=T,I&&(g.cursorScreen=I),e==="brush"?I&&Qe(g,T,I):g.current=T);const v=ue.current;v&&v.hasPointerCapture(m.pointerId)&&v.releasePointerCapture(m.pointerId),pt()},[pt,ie,be,e,Qe]),Ft=d.useCallback(()=>{const m=C.current;let g=!1;e==="brush"&&!m.isDrawing&&m.cursor&&(m.cursor=null,m.cursorScreen=null,g=!0),Wt(e)&&m.stampCenter&&(m.stampCenter=null,g=!0),g&&W()},[e,W]);return d.useEffect(()=>{pe(),W();const m=ue.current;if(!m)return;const g=new ResizeObserver(()=>{pe(),W()});return g.observe(m),()=>{g.disconnect()}},[pe,W]),d.useEffect(()=>{M||Y(),W()},[M,W,Y]),d.useEffect(()=>{We.current!==e&&(We.current=e,Y(),W())},[e,Y,W]),d.useEffect(()=>{W()},[f,z,se,W]),d.useEffect(()=>{if(U)return U.current=W,()=>{U.current===W&&(U.current=null)}},[U,W]),d.useEffect(()=>{if(!M)return;const m=g=>{g.key==="Escape"&&(Y(),W())};return window.addEventListener("keydown",m),()=>{window.removeEventListener("keydown",m)}},[M,Y,W]),ze.jsx("canvas",{ref:ue,className:Q,style:we,onPointerDown:vt,onPointerMove:et,onPointerUp:_t,onPointerCancel:_t,onPointerLeave:Ft,onContextMenu:m=>{M&&m.preventDefault()},onWheel:m=>{if(!M)return;const g=ue.current,T=a.current;if(!g||typeof T?.zoomBy!="function")return;m.preventDefault(),m.stopPropagation();const I=g.getBoundingClientRect(),v=m.clientX-I.left,me=m.clientY-I.top;T.zoomBy(m.deltaY<0?go:po,v,me),W()}})}function wr(e){return String(e??"").replace(/\/+$/,"")}function Hr(e){const t=String(e??"");return t.startsWith("/")?t:`/${t}`}function ss(e){const t=wr(e);if(!t)return"";if(/\/TileGroup\d+$/i.test(t))return t;let n=null;try{n=new URL(t)}catch{n=null}if(n){const r=`${n.protocol}//${n.host}`,i=wr(n.pathname||"");return/\/ims$/i.test(i)?`${r}${i}`:/\/tiles$/i.test(i)?`${r}${i}`:`${r}${i}/tiles`}return/\/ims$/i.test(t)?"/ims":/\/tiles$/i.test(t)?`${t}`:`${t}/tiles`}function as(e,t){const n=e?.imsInfo??{},r=!!e?.imsInfo,i=Number(n.width??e?.width??0),o=Number(n.height??e?.height??0),s=Number(n.tileSize??e?.tileSize??0),a=Number(n.zoom??e?.zoom??0),c=String(n.path??e?.path??""),u=Number(n.mpp??e?.mpp??0);if(!i||!o||!s||!c)throw new Error("Incomplete image metadata: width/height/tileSize/path required");const l=Array.isArray(e?.terms)?e.terms.map(b=>({termId:String(b?.termId??""),termName:String(b?.termName??""),termColor:String(b?.termColor??"")})):[],h=Hr(c),f=ss(t),y=r?(b,x,w)=>`${f}${h}/${b}/${w}_${x}.webp`:void 0;return{id:e?._id||"unknown",name:e?.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:c,tileBaseUrl:t,terms:l,tileUrlBuilder:y}}function Fn(e,t,n,r){if(e.tileUrlBuilder)return e.tileUrlBuilder(t,n,r);const i=Hr(e.tilePath);return`${e.tileBaseUrl}${i}/${t}/${r}_${n}.webp`}const ve={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:"#171719",viewportBorderStyle:"dash",viewportFillColor:"transparent",interactive:!0,showThumbnail:!0,maxThumbnailTiles:16};function Sr(e,t,n,r){const i=t.length;if(i===4){for(let o=0;o<i;o+=1){const s=t[o],a=t[(o+1)%i],c=Math.hypot(a[0]-s[0],a[1]-s[1]);if(c<1e-6)continue;const u=Math.max(1,Math.round((c+r)/(n+r))),l=u*n+(u-1)*r,h=c/Math.max(1e-6,l),f=n*h,y=r*h;e.beginPath(),e.moveTo(s[0],s[1]),e.lineTo(a[0],a[1]),e.setLineDash([f,y]),e.lineDashOffset=0,e.stroke()}e.setLineDash([]),e.lineDashOffset=0}}function mt(e,t,n=1){return typeof e!="number"||!Number.isFinite(e)?t:Math.max(n,e)}function Yt(e){return Array.isArray(e)&&e.length===4&&Number.isFinite(e[0])&&Number.isFinite(e[1])&&Number.isFinite(e[2])&&Number.isFinite(e[3])}const cs={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 $r({source:e,projectorRef:t,authToken:n="",options:r,invalidateRef:i,className:o,style:s}){const a=d.useRef(null),c=d.useRef(null),u=d.useRef(null),l=d.useRef({active:!1,pointerId:null}),h=d.useRef(null),f=d.useRef(!1),y=mt(r?.width,ve.width,64),b=mt(r?.height,ve.height,48),x=d.useMemo(()=>{const C=Math.max(1,e.width),M=Math.max(1,e.height),z=C/M,ce=y/b;let $,le;return z>ce?($=y,le=y/z):(le=b,$=b*z),{x:(y-$)/2,y:(b-le)/2,w:$,h:le}},[e.width,e.height,y,b]),w=mt(r?.margin,ve.margin,0),A=mt(r?.borderRadius,ve.borderRadius,0),E=mt(r?.borderWidth,ve.borderWidth,0),X=Math.max(1,Math.round(mt(r?.maxThumbnailTiles,ve.maxThumbnailTiles,1))),R=r?.backgroundColor||ve.backgroundColor,_=r?.borderColor||ve.borderColor,H=r?.viewportBorderColor||ve.viewportBorderColor,se=r?.viewportBorderStyle==="stroke"||r?.viewportBorderStyle==="dash"?r.viewportBorderStyle:ve.viewportBorderStyle,j=r?.viewportFillColor??ve.viewportFillColor,J=r?.interactive??ve.interactive,ae=r?.showThumbnail??ve.showThumbnail,ge=r?.position||ve.position,Te=r?.onClose,B=r?.closeIcon,D=r?.closeButtonStyle,O=d.useMemo(()=>{const C={};return ge==="top-left"||ge==="bottom-left"?C.left=w:C.right=w,ge==="top-left"||ge==="top-right"?C.top=w:C.bottom=w,{position:"absolute",...C,width:y,height:b,borderRadius:A,overflow:"hidden",zIndex:4,pointerEvents:J?"auto":"none",touchAction:"none",boxShadow:"0 10px 22px rgba(0, 0, 0, 0.3)",...s}},[w,ge,y,b,A,J,s]),U=d.useCallback(()=>{const C=a.current;if(!C)return;const M=C.getContext("2d");if(!M)return;const z=y,ce=b,$=Math.max(1,window.devicePixelRatio||1),le=Math.max(1,Math.round(z*$)),de=Math.max(1,Math.round(ce*$));(C.width!==le||C.height!==de)&&(C.width=le,C.height=de),M.setTransform(1,0,0,1,0,0),M.clearRect(0,0,C.width,C.height),M.setTransform($,0,0,$,0,0),M.fillStyle=R,M.fillRect(0,0,z,ce);const{x:ye,y:ee,w:he,h:re}=x,ne=c.current;ne&&M.drawImage(ne,ye,ee,he,re),M.strokeStyle=_,M.lineWidth=E,M.strokeRect(E*.5,E*.5,z-E,ce-E);const K=t.current,xe=K?.getViewBounds?.(),G=K?.getViewCorners?.(),we=Yt(xe)?xe:Yt(u.current)?u.current:null;if(!we)return;u.current=we;const pe=he/Math.max(1,e.width),Se=re/Math.max(1,e.height),De=Array.isArray(G)&&G.length>=4&&G.every(ie=>Array.isArray(ie)&&ie.length>=2&&Number.isFinite(ie[0])&&Number.isFinite(ie[1]))?G:null,Ae=se==="dash";if(De){const ie=De.map(be=>[ye+be[0]*pe,ee+be[1]*Se]);M.save(),M.beginPath(),M.rect(ye,ee,he,re),M.clip(),M.beginPath();for(let be=0;be<ie.length;be+=1)be===0?M.moveTo(ie[be][0],ie[be][1]):M.lineTo(ie[be][0],ie[be][1]);M.closePath(),M.fillStyle=j,M.fill(),M.strokeStyle=H,M.lineWidth=2.25,Ae?Sr(M,ie,4,3):M.stroke(),M.restore();return}const Ie=k(ye+we[0]*pe,ye,ye+he),Re=k(ee+we[1]*Se,ee,ee+re),ct=k(ye+we[2]*pe,ye,ye+he),ut=k(ee+we[3]*Se,ee,ee+re),W=Math.max(1,ct-Ie),Y=Math.max(1,ut-Re);if(M.fillStyle=j,M.fillRect(Ie,Re,W,Y),M.strokeStyle=H,M.lineWidth=2.25,Ae){const ie=[[Ie+.5,Re+.5],[Ie+.5+Math.max(1,W-1),Re+.5],[Ie+.5+Math.max(1,W-1),Re+.5+Math.max(1,Y-1)],[Ie+.5,Re+.5+Math.max(1,Y-1)]];Sr(M,ie,4,3)}else M.strokeRect(Ie+.5,Re+.5,Math.max(1,W-1),Math.max(1,Y-1))},[y,b,x,R,_,E,t,e.width,e.height,j,H,se]),Q=d.useCallback(()=>{f.current||(f.current=!0,h.current=requestAnimationFrame(()=>{f.current=!1,h.current=null,U()}))},[U]),Le=d.useCallback((C,M)=>{const z=a.current;if(!z)return null;const ce=z.getBoundingClientRect();if(!ce.width||!ce.height)return null;const $=ce.width/y,le=ce.height/b,de=x.x*$,ye=x.y*le,ee=x.w*$,he=x.h*le,re=k((C-ce.left-de)/ee,0,1),ne=k((M-ce.top-ye)/he,0,1);return[re*e.width,ne*e.height]},[e.width,e.height,y,b,x]),ue=d.useCallback((C,M)=>{const z=t.current;if(!z)return;if(z.setViewCenter){z.setViewCenter(C,M),Q();return}const ce=z.getViewBounds?.(),$=Yt(ce)?ce:Yt(u.current)?u.current:null;if(!$)return;const le=Math.max(1e-6,$[2]-$[0]),de=Math.max(1e-6,$[3]-$[1]);z.setViewState({offsetX:C-le*.5,offsetY:M-de*.5}),Q()},[t,Q]),Oe=d.useCallback(C=>{if(!J||C.button!==0)return;const M=a.current;if(!M)return;const z=Le(C.clientX,C.clientY);z&&(C.preventDefault(),C.stopPropagation(),M.setPointerCapture(C.pointerId),l.current={active:!0,pointerId:C.pointerId},ue(z[0],z[1]))},[J,Le,ue]),Fe=d.useCallback(C=>{const M=l.current;if(!M.active||M.pointerId!==C.pointerId)return;const z=Le(C.clientX,C.clientY);z&&(C.preventDefault(),C.stopPropagation(),ue(z[0],z[1]))},[Le,ue]),We=d.useCallback(C=>{const M=l.current;if(!M.active||M.pointerId!==C.pointerId)return;const z=a.current;if(z&&z.hasPointerCapture(C.pointerId))try{z.releasePointerCapture(C.pointerId)}catch{}l.current={active:!1,pointerId:null},Q()},[Q]);return d.useEffect(()=>{let C=!1;c.current=null,Q();const M=0,z=2**(e.maxTierZoom-M),ce=Math.ceil(e.width/z),$=Math.ceil(e.height/z),le=Math.max(1,Math.ceil(ce/e.tileSize)),de=Math.max(1,Math.ceil($/e.tileSize)),ye=le*de;if(!ae||ye>X)return;const ee=document.createElement("canvas");ee.width=Math.max(1,Math.round(x.w)),ee.height=Math.max(1,Math.round(x.h));const he=ee.getContext("2d");if(!he)return;he.fillStyle=R,he.fillRect(0,0,ee.width,ee.height);const re=[];for(let ne=0;ne<de;ne+=1)for(let K=0;K<le;K+=1){const xe=K*e.tileSize*z,G=ne*e.tileSize*z,we=Math.min((K+1)*e.tileSize,ce)*z,pe=Math.min((ne+1)*e.tileSize,$)*z;re.push({url:Fn(e,M,K,ne),bounds:[xe,G,we,pe]})}return Promise.allSettled(re.map(async ne=>{const K=!!n,xe=await fetch(ne.url,{headers:K?{Authorization:n}:void 0});if(!xe.ok)throw new Error(`HTTP ${xe.status}`);const G=await createImageBitmap(await xe.blob());return{tile:ne,bitmap:G}})).then(ne=>{if(C){for(const G of ne)G.status==="fulfilled"&&G.value.bitmap.close();return}const K=ee.width/Math.max(1,e.width),xe=ee.height/Math.max(1,e.height);for(const G of ne){if(G.status!=="fulfilled")continue;const{tile:{bounds:we},bitmap:pe}=G.value,Se=we[0]*K,De=we[1]*xe,Ae=Math.max(1,(we[2]-we[0])*K),Ie=Math.max(1,(we[3]-we[1])*xe);he.drawImage(pe,Se,De,Ae,Ie),pe.close()}c.current=ee,Q()}),()=>{C=!0}},[e,n,x,R,ae,X,Q]),d.useEffect(()=>{Q()},[Q]),d.useEffect(()=>{if(i)return i.current=Q,()=>{i.current===Q&&(i.current=null)}},[i,Q]),d.useEffect(()=>()=>{l.current={active:!1,pointerId:null},h.current!==null&&(cancelAnimationFrame(h.current),h.current=null),f.current=!1},[]),ze.jsxs("div",{className:o,style:O,children:[ze.jsx("canvas",{ref:a,style:{width:"100%",height:"100%",display:"block",borderRadius:"inherit"},onPointerDown:Oe,onPointerMove:Fe,onPointerUp:We,onPointerCancel:We,onContextMenu:C=>{C.preventDefault()},onWheel:C=>{C.preventDefault(),C.stopPropagation()}}),Te&&ze.jsx("button",{type:"button","aria-label":"Hide overview map",onClick:C=>{C.stopPropagation(),Te()},style:D?{...D}:{...cs},children:B??"×"})]})}function us({imageWidth:e,imageHeight:t,tiles:n,viewState:r,className:i,style:o}){const s=d.useRef(null),a=d.useRef(null),c=d.useMemo(()=>({width:"100%",height:"100%",display:"block",...o}),[o]);return d.useEffect(()=>{const u=s.current;if(!u)return;const l=new vr({canvas:u,imageWidth:e,imageHeight:t,initialViewState:r});return a.current=l,l.setTiles(n),()=>{l.destroy(),a.current=null}},[e,t]),d.useEffect(()=>{const u=a.current;u&&u.setTiles(n)},[n]),d.useEffect(()=>{const u=a.current;!u||!r||u.setViewState(r)},[r]),ze.jsx("canvas",{ref:s,className:i,style:c})}function Ct(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return null;const n=Et(t??[]);if(n.length===0){const b={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return e.fillModes instanceof Uint8Array&&(b.fillModes=new Uint8Array(0)),e.ids instanceof Uint32Array&&(b.ids=new Uint32Array(0)),b}const r=at(e),i=e.positions,o=e.paletteIndices,s=e.fillModes instanceof Uint8Array&&e.fillModes.length>=r?e.fillModes:null,a=e.ids instanceof Uint32Array&&e.ids.length>=r?e.ids:null,c=new Float32Array(r*2),u=new Uint16Array(r),l=s?new Uint8Array(r):null,h=a?new Uint32Array(r):null;let f=0;for(let b=0;b<r;b+=1){const x=i[b*2],w=i[b*2+1];jt(x,w,n)&&(c[f*2]=x,c[f*2+1]=w,u[f]=o[b],l&&(l[f]=s[b]),h&&(h[f]=a[b]),f+=1)}const y={count:f,positions:c.subarray(0,f*2),paletteIndices:u.subarray(0,f)};return l&&(y.fillModes=l.subarray(0,f)),h&&(y.ids=h.subarray(0,f)),y}function Zr(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return new Uint32Array(0);const n=Et(t??[]);if(n.length===0)return new Uint32Array(0);const r=at(e);if(r===0)return new Uint32Array(0);const i=e.positions,o=new Uint32Array(r);let s=0;for(let a=0;a<r;a+=1){const c=i[a*2],u=i[a*2+1];jt(c,u,n)&&(o[s]=a,s+=1)}return o.subarray(0,s)}let Xt=null;const ls=`
33
33
  struct Params {
34
34
  pointCount: u32,
35
35
  boundsCount: u32,
@@ -60,7 +60,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
60
60
  }
61
61
  outputMask[i] = inside;
62
62
  }
63
- `;function us(){if(typeof navigator>"u")return!1;const e=navigator;return typeof e.gpu=="object"&&e.gpu!==null}function $r(){if(!us())return null;const t=navigator.gpu;if(!t||typeof t!="object")return null;const n=t;return typeof n.requestAdapter!="function"?null:n}const Yt=globalThis.GPUShaderStage?.COMPUTE??4,ln=globalThis.GPUBufferUsage?.STORAGE??128,Xt=globalThis.GPUBufferUsage?.COPY_DST??8,ls=globalThis.GPUBufferUsage?.COPY_SRC??4,fs=globalThis.GPUBufferUsage?.UNIFORM??64,ds=globalThis.GPUBufferUsage?.MAP_READ??1,hs=globalThis.GPUMapMode?.READ??1;async function ms(){const e=$r();if(!e)return{supported:!1,features:[]};const t=await e.requestAdapter();return t?{supported:!0,adapterName:t.info?.description??t.info?.vendor??"unknown",features:Array.from(t.features),limits:{maxStorageBufferBindingSize:Number(t.limits.maxStorageBufferBindingSize),maxComputeInvocationsPerWorkgroup:Number(t.limits.maxComputeInvocationsPerWorkgroup),maxComputeWorkgroupSizeX:Number(t.limits.maxComputeWorkgroupSizeX)}}:{supported:!1,features:[]}}async function gs(){return Wt||(Wt=(async()=>{const e=$r();if(!e)return null;const t=await e.requestAdapter();if(!t)return null;const n=await t.requestDevice(),r=n.createBindGroupLayout({entries:[{binding:0,visibility:Yt,buffer:{type:"read-only-storage"}},{binding:1,visibility:Yt,buffer:{type:"read-only-storage"}},{binding:2,visibility:Yt,buffer:{type:"storage"}},{binding:3,visibility:Yt,buffer:{type:"uniform"}}]}),i=n.createComputePipeline({layout:n.createPipelineLayout({bindGroupLayouts:[r]}),compute:{module:n.createShaderModule({code:cs}),entryPoint:"main"}});return{device:n,pipeline:i,bindGroupLayout:r}})(),Wt)}function Vt(e,t){return Math.ceil(e/t)*t}async function Zr(e,t,n){const r=await gs();if(!r)return null;const i=Math.max(0,Math.floor(t)),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(e.length/2));if(s===0)return new Uint32Array(0);const a=s*2*Float32Array.BYTES_PER_ELEMENT,c=o*4*Float32Array.BYTES_PER_ELEMENT,u=s*Uint32Array.BYTES_PER_ELEMENT,l=Number(r.device.limits.maxStorageBufferBindingSize);if(a>l||c>l||u>l)return null;const d=r.device.createBuffer({size:Vt(a,4),usage:ln|Xt}),f=r.device.createBuffer({size:Vt(c,4),usage:ln|Xt}),y=r.device.createBuffer({size:Vt(u,4),usage:ln|ls}),b=r.device.createBuffer({size:16,usage:fs|Xt}),w=r.device.createBuffer({size:Vt(u,4),usage:Xt|ds});r.device.queue.writeBuffer(d,0,e.buffer,e.byteOffset,a),r.device.queue.writeBuffer(f,0,n.buffer,n.byteOffset,c),r.device.queue.writeBuffer(b,0,new Uint32Array([s,o,0,0]));const x=r.device.createBindGroup({layout:r.bindGroupLayout,entries:[{binding:0,resource:{buffer:d}},{binding:1,resource:{buffer:f}},{binding:2,resource:{buffer:y}},{binding:3,resource:{buffer:b}}]}),R=r.device.createCommandEncoder(),E=R.beginComputePass();E.setPipeline(r.pipeline),E.setBindGroup(0,x),E.dispatchWorkgroups(Math.ceil(s/256)),E.end(),R.copyBufferToBuffer(y,0,w,0,u),r.device.queue.submit([R.finish()]),await w.mapAsync(hs);const X=w.getMappedRange(),A=new Uint32Array(X.slice(0));return w.unmap(),d.destroy(),f.destroy(),y.destroy(),b.destroy(),w.destroy(),A}async function Kr(e,t,n={}){const r=fe(),i=n.bridgeToDraw===!0;if(!e||!e.count||!e.positions||!e.paletteIndices)return{data:null,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}};const o=Pt(t??[]);if(o.length===0){const A={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return e.fillModes instanceof Uint8Array&&(A.fillModes=new Uint8Array(0)),e.ids instanceof Uint32Array&&(A.ids=new Uint32Array(0)),{data:A,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const s=ut(e),a=e.fillModes instanceof Uint8Array&&e.fillModes.length>=s?e.fillModes:null,c=e.ids instanceof Uint32Array&&e.ids.length>=s?e.ids:null;if(s===0){const A={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(A.fillModes=new Uint8Array(0)),c&&(A.ids=new Uint32Array(0)),{data:A,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const u=new Float32Array(o.length*4);for(let A=0;A<o.length;A+=1){const F=A*4,K=o[A];u[F]=K.minX,u[F+1]=K.minY,u[F+2]=K.maxX,u[F+3]=K.maxY}let l=null,d=!1;try{l=await Zr(e.positions,s,u),d=!!l}catch{l=null,d=!1}if(!l)return{data:Tt(e,t),meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!1,candidateCount:s,bridgedToDraw:!1}};let f=0;for(let A=0;A<s;A+=1)l[A]===1&&(f+=1);const y=new Uint32Array(f);if(f>0){let A=0;for(let F=0;F<s;F+=1)l[F]===1&&(y[A]=F,A+=1)}if(f===0){if(i){const F={count:s,positions:e.positions.subarray(0,s*2),paletteIndices:e.paletteIndices.subarray(0,s),drawIndices:new Uint32Array(0)};return a&&(F.fillModes=a.subarray(0,s)),c&&(F.ids=c.subarray(0,s)),{data:F,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!0}}}const A={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(A.fillModes=new Uint8Array(0)),c&&(A.ids=new Uint32Array(0)),{data:A,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!1}}}if(i){const A=new Uint32Array(f);let F=0;for(let oe=0;oe<f;oe+=1){const Q=y[oe]??0,ee=e.positions[Q*2],se=e.positions[Q*2+1];Zt(ee,se,o)&&(A[F]=Q,F+=1)}const K={count:s,positions:e.positions.subarray(0,s*2),paletteIndices:e.paletteIndices.subarray(0,s),drawIndices:A.subarray(0,F)};return a&&(K.fillModes=a.subarray(0,s)),c&&(K.ids=c.subarray(0,s)),{data:K,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!0,candidateCount:f,bridgedToDraw:!0}}}const b=new Float32Array(f*2),w=new Uint16Array(f),x=a?new Uint8Array(f):null,R=c?new Uint32Array(f):null;let E=0;for(let A=0;A<f;A+=1){const F=y[A]??0,K=e.positions[F*2],oe=e.positions[F*2+1];Zt(K,oe,o)&&(b[E*2]=K,b[E*2+1]=oe,w[E]=e.paletteIndices[F],x&&(x[E]=a[F]),R&&(R[E]=c[F]),E+=1)}const X={count:E,positions:b.subarray(0,E*2),paletteIndices:w.subarray(0,E)};return x&&(X.fillModes=x.subarray(0,E)),R&&(X.ids=R.subarray(0,E)),{data:X,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!0,candidateCount:f,bridgedToDraw:!1}}}class jr{constructor(t,n){S(this,"worker",null);S(this,"supported",!0);S(this,"requestId",1);S(this,"pendingById",new Map);S(this,"handleMessage",t=>{const n=t.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=t,this.handlers=n}beginRequest(t){const n=this.getOrCreateWorker();if(!n)return null;const r=this.requestId++;return this.pendingById.set(r,t),{id:r,worker:n}}cancelRequest(t){const n=this.pendingById.get(t);if(n)return this.pendingById.delete(t),n}terminate(t="worker terminated"){this.teardownWorker(t)}getOrCreateWorker(){if(!this.supported)return null;if(this.worker)return this.worker;try{const t=this.createWorker();return t.addEventListener("message",this.handleMessage),t.addEventListener("error",this.handleError),this.worker=t,t}catch{return this.supported=!1,null}}teardownWorker(t){this.worker&&(this.worker.removeEventListener("message",this.handleMessage),this.worker.removeEventListener("error",this.handleError),this.worker.terminate(),this.worker=null);const n=new Error(t);for(const[,r]of this.pendingById)this.handlers.rejectPending(r,n);this.pendingById.clear()}}const Rt=new jr(()=>new Worker(new URL(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/roi-clip-worker-BDVQwN2T.js").href:new URL("assets/roi-clip-worker-BDVQwN2T.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),typeof document>"u"?require("url").pathToFileURL(__filename).href:gt&&gt.tagName.toUpperCase()==="SCRIPT"&&gt.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),{onResponse:(e,t)=>{if(e.type==="roi-clip-failure"){t.reject(new Error(e.error||"worker clip failed"));return}if(e.type==="roi-clip-index-success"){if(t.kind!=="index"){t.reject(new Error("worker response mismatch: expected point data result"));return}const c=Math.max(0,Math.floor(e.count)),u=new Uint32Array(e.indices).subarray(0,c);t.resolve({indices:u,meta:{mode:"worker",durationMs:Number.isFinite(e.durationMs)?e.durationMs:fe()-t.startMs}});return}if(t.kind!=="data"){t.reject(new Error("worker response mismatch: expected index result"));return}const n=Math.max(0,Math.floor(e.count)),r=new Float32Array(e.positions),i=new Uint16Array(e.paletteIndices),o=e.fillModes?new Uint8Array(e.fillModes):null,s=e.ids?new Uint32Array(e.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)),t.resolve({data:a,meta:{mode:"worker",durationMs:Number.isFinite(e.durationMs)?e.durationMs:fe()-t.startMs}})},rejectPending:(e,t)=>{e.reject(t)}});function ps(){Rt.terminate("worker terminated")}async function Jr(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return{data:null,meta:{mode:"worker",durationMs:0}};const n=ut(e),r=e.positions.slice(0,n*2),i=e.paletteIndices.slice(0,n),o=e.fillModes instanceof Uint8Array&&e.fillModes.length>=n?e.fillModes.slice(0,n):null,s=e.ids instanceof Uint32Array&&e.ids.length>=n?e.ids.slice(0,n):null;return new Promise((a,c)=>{const u=fe(),l=Rt.beginRequest({kind:"data",resolve:a,reject:c,startMs:u});if(!l){a({data:Tt(e,t),meta:{mode:"sync",durationMs:fe()-u}});return}const d={type:"roi-clip-request",id:l.id,count:n,positions:r.buffer,paletteIndices:i.buffer,fillModes:o?.buffer,ids:s?.buffer,polygons:t??[]},f=[r.buffer,i.buffer];o&&f.push(o.buffer),s&&f.push(s.buffer);try{l.worker.postMessage(d,f)}catch(y){const b=Rt.cancelRequest(l.id);b?b.reject(y):c(y)}})}async function bs(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return{indices:new Uint32Array(0),meta:{mode:"worker",durationMs:0}};const n=ut(e),r=e.positions.slice(0,n*2);return new Promise((i,o)=>{const s=fe(),a=Rt.beginRequest({kind:"index",resolve:i,reject:o,startMs:s});if(!a){i({indices:Hr(e,t),meta:{mode:"sync",durationMs:fe()-s}});return}const c={type:"roi-clip-index-request",id:a.id,count:n,positions:r.buffer,polygons:t??[]};try{a.worker.postMessage(c,[r.buffer])}catch(u){const l=Rt.cancelRequest(a.id);l?l.reject(u):o(u)}})}const ys=24,ws=1024,Ss=4,$t=-1;function St(e,t,n){return(e*73856093^t*19349663)>>>0&n}function xs(e,t,n){if(e<=0||t<=0||n<=0)return 256;const r=Math.max(1,e*t),o=Math.sqrt(r/Math.max(1,n))*Ss;return Math.max(ys,Math.min(ws,o))}function Ms(e,t){if(!(e instanceof Uint32Array)||e.length===0)return null;let n=!0;for(let o=0;o<e.length;o+=1)if(!(e[o]<t)){n=!1;break}if(n)return e;const r=new Uint32Array(e.length);let i=0;for(let o=0;o<e.length;o+=1)e[o]>=t||(r[i]=e[o],i+=1);return i>0?r.subarray(0,i):null}function As(e){const t=Math.max(0,Math.floor(e.count)),n=Math.floor(e.positions.length/2),r=Math.max(0,Math.min(t,n));if(r<=0)return null;const i=Ms(e.drawIndices??null,r),o=i?i.length:r;if(o===0)return null;const s=xs(e.sourceWidth,e.sourceHeight,o),a=1/s,c=new Int32Array(o),u=new Int32Array(o);let l=0;if(i)for(let _=0;_<o;_+=1){const L=i[_],O=e.positions[L*2],D=e.positions[L*2+1];!Number.isFinite(O)||!Number.isFinite(D)||(c[l]=Math.floor(O*a),u[l]=Math.floor(D*a),l+=1)}else for(let _=0;_<r;_+=1){const L=e.positions[_*2],O=e.positions[_*2+1];!Number.isFinite(L)||!Number.isFinite(O)||(c[l]=Math.floor(L*a),u[l]=Math.floor(O*a),l+=1)}if(l===0)return null;let d=Math.min(l,Math.max(64,l>>>3));(!Number.isFinite(d)||d<=0)&&(d=l);let f=1;for(;f<d*2;)f<<=1;let y=f-1,b=new Int32Array(f*2),w=new Int32Array(f);b.fill(2147483647);let x=0;const R=new Int32Array(l);for(let _=0;_<l;_+=1){const L=c[_],O=u[_];let D=St(L,O,y);for(;;){const V=b[D*2];if(V===2147483647){if(b[D*2]=L,b[D*2+1]=O,w[D]=1,R[_]=D,x+=1,x*4>f*3){const Le=f;f<<=1,y=f-1;const Re=new Int32Array(f*2),Ve=new Int32Array(f);Re.fill(2147483647);for(let de=0;de<Le;de+=1){if(b[de*2]===2147483647)continue;const ae=b[de*2],v=b[de*2+1];let P=St(ae,v,y);for(;Re[P*2]!==2147483647;)P=P+1&y;Re[P*2]=ae,Re[P*2+1]=v,Ve[P]=w[de]}for(b=Re,w=Ve,D=St(L,O,y);b[D*2]!==L||b[D*2+1]!==O;)D=D+1&y;R[_]=D}break}if(V===L&&b[D*2+1]===O){w[D]+=1,R[_]=D;break}D=D+1&y}}const E=new Int32Array(x*2),X=new Uint32Array(x),A=new Uint32Array(x),F=new Int32Array(f);F.fill($t);let K=0,oe=0;for(let _=0;_<f;_+=1)b[_*2]!==2147483647&&(E[K*2]=b[_*2],E[K*2+1]=b[_*2+1],X[K]=oe,A[K]=w[_],F[_]=K,oe+=w[_],K+=1);const Q=new Uint32Array(l),ee=new Uint32Array(x);if(ee.set(X),i)for(let _=0;_<l;_+=1){const L=F[R[_]];Q[ee[L]]=i[_],ee[L]+=1}else{let _=0;for(let L=0;L<r;L+=1){const O=e.positions[L*2],D=e.positions[L*2+1];if(!Number.isFinite(O)||!Number.isFinite(D))continue;const V=F[R[_]];Q[ee[V]]=L,ee[V]+=1,_+=1}}let se=1;for(;se<x*2;)se<<=1;const ge=se-1,Te=new Int32Array(se);Te.fill($t);for(let _=0;_<x;_+=1){const L=E[_*2],O=E[_*2+1];let D=St(L,O,ge);for(;Te[D]!==$t;)D=D+1&ge;Te[D]=_}return{cellSize:s,safeCount:r,cellCount:x,hashCapacity:se,hashTable:Te,cellKeys:E,cellOffsets:X,cellLengths:A,pointIndices:Q}}function Qr(e,t,n){const{hashTable:r,cellKeys:i,hashMask:o}=e;let s=St(t,n,o);for(;;){const a=r[s];if(a===$t)return-1;if(i[a*2]===t&&i[a*2+1]===n)return a;s=s+1&o}}function Ts(e,t){if(e.safeCount<=0||e.cellCount<=0)return null;const n=e.safeCount;return{cellSize:e.cellSize,safeCount:n,positions:t.positions.subarray(0,n*2),ids:t.ids instanceof Uint32Array&&t.ids.length>=n?t.ids.subarray(0,n):null,hashCapacity:e.hashCapacity,hashMask:e.hashCapacity-1,hashTable:new Int32Array(e.hashTable),cellKeys:new Int32Array(e.cellKeys),cellOffsets:new Uint32Array(e.cellOffsets),cellLengths:new Uint32Array(e.cellLengths),pointIndices:new Uint32Array(e.pointIndices)}}const yn=new jr(()=>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:gt&&gt.tagName.toUpperCase()==="SCRIPT"&&gt.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),{onResponse:(e,t)=>{if(e.type==="point-hit-index-failure"){t.reject(new Error(e.error||"worker index build failed"));return}t.resolve(Ts(e,t.pointData))},rejectPending:(e,t)=>{e.reject(t)}});function Rs(){yn.terminate("worker terminated")}function Cs(e,t){const n=ut(e);if(n<=0)return null;const r=e.positions.subarray(0,n*2),i=As({count:n,positions:r,drawIndices:e.drawIndices instanceof Uint32Array?e.drawIndices:null,sourceWidth:t?.width??0,sourceHeight:t?.height??0});return i?{cellSize:i.cellSize,safeCount:n,positions:r,ids:e.ids instanceof Uint32Array&&e.ids.length>=n?e.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 ei(e,t){if(!e||!e.positions||!e.paletteIndices)return null;const n=ut(e);return n<=0?null:new Promise((r,i)=>{const o={resolve:r,reject:i,pointData:e},s=yn.beginRequest(o);if(!s||!s.worker){r(Cs(e,t));return}const a=e.positions.slice(0,n*2),c=e.drawIndices instanceof Uint32Array&&e.drawIndices.length>0?e.drawIndices.slice():void 0,u={type:"point-hit-index-request",id:s.id,count:n,positions:a.buffer,drawIndices:c?.buffer,sourceWidth:t?.width??0,sourceHeight:t?.height??0},l=[a.buffer];c&&l.push(c.buffer);try{s.worker.postMessage(u,l)}catch(d){const f=yn.cancelRequest(s.id);f?f.reject(d):i(d)}})}function Ps(e){const t=[];for(let n=0;n<e.length;n+=1){const r=e[n],i=Pt([Ct(r?.coordinates)]);if(i.length===0)continue;let o=0;for(const s of i)o+=s.area;t.push({regionId:r.id??n,regionIndex:n,polygons:i,area:Math.max(1e-6,o)})}return t}function Is(e,t){if(Array.isArray(t)){const n=t[e];if(typeof n=="string"&&n.length>0)return n}if(t instanceof Map){const n=t.get(e);if(typeof n=="string"&&n.length>0)return n}return String(e)}function ti(e,t,n={}){const r=Math.max(0,Math.min(Math.floor(e?.count??0),Math.floor((e?.positions?.length??0)/2),e?.paletteIndices?.length??0,e?.fillModes instanceof Uint8Array?e.fillModes.length:Number.MAX_SAFE_INTEGER));let i=null;if(e?.drawIndices instanceof Uint32Array){const f=e.drawIndices;let y=f.length;for(let b=0;b<f.length;b+=1)f[b]<r||(y-=1);if(y===f.length)i=f;else if(y>0){const b=new Uint32Array(y);let w=0;for(let x=0;x<f.length;x+=1){const R=f[x];R>=r||(b[w]=R,w+=1)}i=b}else i=new Uint32Array(0)}const o=i?i.length:r,s=Ps(t??[]);if(!e||o===0||s.length===0)return{groups:[],inputPointCount:o,pointsInsideAnyRegion:0,unmatchedPointCount:o};const a=new Map,c=new Map;let u=0;for(let f=0;f<o;f+=1){const y=i?i[f]:f,b=e.positions[y*2],w=e.positions[y*2+1];let x=null;for(const X of s){let A=!1;for(const F of X.polygons)if(Fr(b,w,F)){A=!0;break}A&&(!x||X.area<x.area)&&(x=X)}if(!x)continue;u+=1;const R=e.paletteIndices[y]??0,E=a.get(x.regionIndex)??new Map;E.set(R,(E.get(R)??0)+1),a.set(x.regionIndex,E),c.set(x.regionIndex,(c.get(x.regionIndex)??0)+1)}const l=n.includeEmptyRegions??!1,d=[];for(const f of s){const y=c.get(f.regionIndex)??0;if(!l&&y<=0)continue;const b=a.get(f.regionIndex)??new Map,w=Array.from(b.entries()).map(([x,R])=>({termId:Is(x,n.paletteIndexToTermId),paletteIndex:x,count:R})).sort((x,R)=>R.count-x.count||x.paletteIndex-R.paletteIndex);d.push({regionId:f.regionId,regionIndex:f.regionIndex,totalCount:y,termCounts:w})}return{groups:d,inputPointCount:o,pointsInsideAnyRegion:u,unmatchedPointCount:Math.max(0,o-u)}}function Es(e,t){if(!t)return!1;try{const r=new URL(e,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 ni{constructor(t){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(t.maxConcurrency??12)),this.maxRetries=Math.max(0,Math.floor(t.maxRetries??2)),this.retryBaseDelayMs=Math.max(10,Math.floor(t.retryBaseDelayMs??120)),this.retryMaxDelayMs=Math.max(this.retryBaseDelayMs,Math.floor(t.retryMaxDelayMs??1200)),this.authToken=t.authToken??"",this.onTileLoad=t.onTileLoad,this.onTileError=t.onTileError,this.onStateChange=t.onStateChange}setAuthToken(t){this.authToken=String(t??"")}schedule(t){if(this.destroyed)return;const n=new Set;for(const r of t)n.add(r.key);this.visibleKeys=n,this.dropInvisibleQueued(n),this.abortInvisibleInflight(n);for(const r of t){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:fe()};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[,t]of this.inflight)t.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(t){if(this.queue.length===0)return;const n=[];for(const r of this.queue){if(!t.has(r.tile.key)){this.queuedByKey.delete(r.tile.key);continue}n.push(r)}this.queue=n}abortInvisibleInflight(t){for(const[n,r]of this.inflight)t.has(n)||(this.inflight.delete(n),this.abortedCount+=1,r.controller.abort())}sortQueue(){this.queue.sort((t,n)=>t.readyAt!==n.readyAt?t.readyAt-n.readyAt:t.tile.distance2!==n.tile.distance2?t.tile.distance2-n.tile.distance2:t.tile.tier!==n.tile.tier?n.tile.tier-t.tile.tier:t.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 t=this.queue[0]?.readyAt;if(typeof t!="number")return;const n=Math.max(0,t-fe());this.timerId=window.setTimeout(()=>{this.timerId=null,this.pump()},n)}takeNextReadyQueueItem(){if(this.queue.length===0)return null;const t=fe(),n=this.queue[0];return!n||n.readyAt>t?null:(this.queue.shift(),this.queuedByKey.delete(n.tile.key),n)}startFetch(t){const n=new AbortController,r={tile:t.tile,attempt:t.attempt,controller:n};this.inflight.set(t.tile.key,r),this.emitStateChange();const i=Es(t.tile.url,this.authToken);fetch(t.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(t.tile.key)){o.close();return}this.onTileLoad(t.tile,o)}).catch(o=>{if(n.signal.aborted||this.destroyed)return;if(t.attempt<this.maxRetries&&this.visibleKeys.has(t.tile.key)){this.retryCount+=1;const a=t.attempt+1,c=this.getRetryDelay(a),u={tile:t.tile,attempt:a,readyAt:fe()+c},l=this.queuedByKey.get(t.tile.key);l?(l.tile=u.tile,l.readyAt=Math.min(l.readyAt,u.readyAt),l.attempt=Math.max(l.attempt,u.attempt)):(this.queue.push(u),this.queuedByKey.set(u.tile.key,u)),this.sortQueue();return}this.failedCount+=1,this.onTileError?.(t.tile,o,t.attempt+1)}).finally(()=>{this.inflight.delete(t.tile.key),this.pump(),this.emitStateChange()})}getRetryDelay(t){const n=Math.max(0,t-1),r=Math.min(this.retryMaxDelayMs,this.retryBaseDelayMs*2**n),i=.85+Math.random()*.3;return Math.round(r*i)}clearPumpTimer(){this.timerId!==null&&(window.clearTimeout(this.timerId),this.timerId=null)}emitStateChange(){this.onStateChange?.(this.getSnapshot())}}function vs(e,t){e.addEventListener("pointerdown",t.pointerDown),e.addEventListener("pointermove",t.pointerMove),e.addEventListener("pointerup",t.pointerUp),e.addEventListener("pointercancel",t.pointerUp),e.addEventListener("wheel",t.wheel,{passive:!1}),e.addEventListener("dblclick",t.doubleClick),e.addEventListener("contextmenu",t.contextMenu),e.addEventListener("webglcontextlost",t.contextLost),e.addEventListener("webglcontextrestored",t.contextRestored)}function _s(e,t){e.removeEventListener("pointerdown",t.pointerDown),e.removeEventListener("pointermove",t.pointerMove),e.removeEventListener("pointerup",t.pointerUp),e.removeEventListener("pointercancel",t.pointerUp),e.removeEventListener("wheel",t.wheel),e.removeEventListener("dblclick",t.doubleClick),e.removeEventListener("contextmenu",t.contextMenu),e.removeEventListener("webglcontextlost",t.contextLost),e.removeEventListener("webglcontextrestored",t.contextRestored)}function Fs(e,t,n){const r=e.getBoundingClientRect(),i=Math.max(1,r.width||e.clientWidth||1),o=Math.max(1,r.height||e.clientHeight||1),s=Math.max(1,window.devicePixelRatio||1),a=Math.max(1,Math.round(i*s)),c=Math.max(1,Math.round(o*s));(e.width!==a||e.height!==c)&&(e.width=a,e.height=c),n.setViewport(i,o),t.viewport(0,0,a,c)}const wn=.35,Sn=.5,Bs=256,xn=[{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}],Ls=.1,Us=5,Ds=0,ks=1,Ns=-100,zs=100,Os=2e3;function ri(e){return e*Math.PI/180}function Gt(e,t){return!e||!t?e===t:e.buffer===t.buffer&&e.byteOffset===t.byteOffset&&e.byteLength===t.byteLength}function Mn(e){return e.map(t=>({zoom:t.zoom,size:t.size}))}function wr(e){if(!e)return Mn(xn);const t=new Map;for(const[n,r]of Object.entries(e)){const i=Number(n),o=Number(r);!Number.isFinite(i)||!Number.isFinite(o)||o<=0||t.set(i,o)}return t.size===0?Mn(xn):Array.from(t.entries()).sort((n,r)=>n[0]-r[0]).map(([n,r])=>({zoom:n,size:r}))}function Ws(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n].zoom!==t[n].zoom||e[n].size!==t[n].size)return!1;return!0}function Ys(e,t){if(!Number.isFinite(e))return t[0]?.size??Sn;if(t.length===0)return Sn;if(t.length===1||e<=t[0].zoom)return t[0].size;for(let s=1;s<t.length;s+=1){const a=t[s-1],c=t[s];if(e>c.zoom)continue;const u=Math.max(1e-6,c.zoom-a.zoom),l=k((e-a.zoom)/u,0,1);return a.size+(c.size-a.size)*l}const n=t[t.length-1],r=t[t.length-2],i=Math.max(1e-6,n.zoom-r.zoom),o=(n.size-r.size)/i;return n.size+(e-n.zoom)*o}function Sr(e){return typeof e!="number"||!Number.isFinite(e)?1:k(e,Ls,Us)}function xr(e){return typeof e!="number"||!Number.isFinite(e)?0:k(e,Ds,ks)}function fn(e){return typeof e!="number"||!Number.isFinite(e)?0:k(e,Ns,zs)}function Mr(e){const t=fn(e?.brightness),n=fn(e?.contrast),r=fn(e?.saturation);return{brightness:t/200,contrast:n/100,saturation:r/100}}function ii(e){return e}function dn(e){return typeof e!="number"||!Number.isFinite(e)?0:k(e,0,Os)}function qt(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?null:Math.max(1e-6,e)}function hn(e){return typeof e=="function"?e:ii}function oi(e,t,n){const r=e.getBoundingClientRect(),i=t-r.left-r.width*.5,o=n-r.top-r.height*.5;return Math.atan2(o,i)}function si(e,t){if(t.pointerId!==null&&e.hasPointerCapture(t.pointerId))try{e.releasePointerCapture(t.pointerId)}catch{}t.dragging=!1,t.mode="none",t.rotateLastAngleRad=null,t.pointerId=null,e.classList.remove("dragging")}function Xs(e){const{event:t,canvas:n,state:r,config:i,cancelViewAnimation:o}=e,s=i.ctrlDragRotate&&(t.ctrlKey||t.metaKey);(t.button===0||s&&t.button===2)&&(o(),s&&t.preventDefault(),r.dragging=!0,r.mode=s?"rotate":"pan",r.pointerId=t.pointerId,r.lastPointerX=t.clientX,r.lastPointerY=t.clientY,r.rotateLastAngleRad=r.mode==="rotate"?oi(n,t.clientX,t.clientY):null,n.classList.add("dragging"),n.setPointerCapture(t.pointerId))}function Vs(e){const{event:t,canvas:n,state:r,config:i,camera:o,clampViewState:s,emitViewState:a,requestRender:c}=e;if(!r.dragging||t.pointerId!==r.pointerId)return;const u=t.clientX-r.lastPointerX,l=t.clientY-r.lastPointerY;if(r.lastPointerX=t.clientX,r.lastPointerY=t.clientY,r.mode==="rotate"){const d=oi(n,t.clientX,t.clientY),f=r.rotateLastAngleRad;if(r.rotateLastAngleRad=d,f!==null){const y=d-f,b=Math.atan2(Math.sin(y),Math.cos(y)),w=i.rotationDragSensitivityDegPerPixel/wn,x=o.getViewState();o.setViewState({rotationDeg:x.rotationDeg-b*180/Math.PI*w})}}else{const d=o.getViewState(),f=Math.max(1e-6,d.zoom),y=ri(d.rotationDeg),b=Math.cos(y),w=Math.sin(y),x=(u*b-l*w)/f,R=(u*w+l*b)/f;o.setViewState({offsetX:d.offsetX-x,offsetY:d.offsetY-R})}s(),a(),c()}function Gs(e,t,n){e.pointerId===n.pointerId&&si(t,n)}function qs(e){const{event:t,canvas:n,onZoomBy:r}=e;t.preventDefault();const i=n.getBoundingClientRect(),o=t.clientX-i.left,s=t.clientY-i.top,a=t.deltaY<0?1.12:.89;r(a,o,s)}function Hs(e){const{event:t,canvas:n,onZoomBy:r}=e,i=n.getBoundingClientRect(),o=t.clientX-i.left,s=t.clientY-i.top;r(t.shiftKey?.8:1.25,o,s)}function $s(e,t){(t||e.ctrlKey||e.metaKey)&&e.preventDefault()}function _n(e){const t=e.getViewCorners();let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[s,a]of t)s<n&&(n=s),s>i&&(i=s),a<r&&(r=a),a>o&&(o=a);return[n,r,i,o]}function An(e,t){const n=_n(e),r=Math.max(1e-6,n[2]-n[0]),i=Math.max(1e-6,n[3]-n[1]),o=r*.2,s=i*.2,[a,c]=e.getCenter(),u=r*.5,l=i*.5,d=u-o,f=t.width-u+o,y=l-s,b=t.height-l+s,w=d<=f?k(a,d,f):t.width*.5,x=y<=b?k(c,y,b):t.height*.5;e.setCenter(w,x)}function Zs(e,t){const n=Math.max(1e-6,e.getViewState().zoom),r=t.maxTierZoom+Math.log2(n);return k(Math.floor(r),0,t.maxTierZoom)}function Ks(e,t){return!(e[2]<=t[0]||e[0]>=t[2]||e[3]<=t[1]||e[1]>=t[3])}function ai(e,t,n){const r=_n(e),i=Math.pow(2,t.maxTierZoom-n),o=Math.ceil(t.width/i),s=Math.ceil(t.height/i),a=Math.max(1,Math.ceil(o/t.tileSize)),c=Math.max(1,Math.ceil(s/t.tileSize)),u=r[0],l=r[1],d=r[2],f=r[3],y=k(Math.floor(u/i/t.tileSize),0,a-1),b=k(Math.floor((d-1)/i/t.tileSize),0,a-1),w=k(Math.floor(l/i/t.tileSize),0,c-1),x=k(Math.floor((f-1)/i/t.tileSize),0,c-1);if(y>b||w>x)return[];const R=(u+d)*.5/i/t.tileSize,E=(l+f)*.5/i/t.tileSize,X=[];for(let A=w;A<=x;A+=1)for(let F=y;F<=b;F+=1){const K=F*t.tileSize*i,oe=A*t.tileSize*i,Q=Math.min((F+1)*t.tileSize,o)*i,ee=Math.min((A+1)*t.tileSize,s)*i,se=F-R,ge=A-E;X.push({key:`${n}/${F}/${A}`,tier:n,x:F,y:A,bounds:[K,oe,Q,ee],distance2:se*se+ge*ge,url:vn(t,n,F,A)})}return X.sort((A,F)=>A.distance2-F.distance2),X}function js(e,t){const n=Zs(e,t);return{tier:n,visible:ai(e,t,n)}}function Js(e){e.interactionLocked||Xs({event:e.event,canvas:e.canvas,state:e.state,config:{ctrlDragRotate:e.ctrlDragRotate,rotationDragSensitivityDegPerPixel:e.rotationDragSensitivityDegPerPixel},cancelViewAnimation:e.cancelViewAnimation})}function Qs(e){e.interactionLocked||Vs({event:e.event,canvas:e.canvas,state:e.state,config:{ctrlDragRotate:e.ctrlDragRotate,rotationDragSensitivityDegPerPixel:e.rotationDragSensitivityDegPerPixel},camera:e.camera,clampViewState:()=>An(e.camera,e.source),emitViewState:e.emitViewState,requestRender:e.requestRender})}function ea(e){e.interactionLocked||Gs(e.event,e.canvas,e.state)}function ta(e){if(e.interactionLocked){e.event.preventDefault();return}qs({event:e.event,canvas:e.canvas,onZoomBy:e.onZoomBy})}function na(e){e.interactionLocked||Hs({event:e.event,canvas:e.canvas,onZoomBy:e.onZoomBy})}function ra(e){$s(e.event,e.state.dragging)}function ia(e,t){si(e,t)}function oa(e){return{pointerDown:t=>Js({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,state:e.state,ctrlDragRotate:e.getCtrlDragRotate(),rotationDragSensitivityDegPerPixel:e.getRotationDragSensitivityDegPerPixel(),cancelViewAnimation:e.cancelViewAnimation}),pointerMove:t=>Qs({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,state:e.state,ctrlDragRotate:e.getCtrlDragRotate(),rotationDragSensitivityDegPerPixel:e.getRotationDragSensitivityDegPerPixel(),camera:e.camera,source:e.source,emitViewState:e.emitViewState,requestRender:e.requestRender}),pointerUp:t=>ea({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,state:e.state}),wheel:t=>ta({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,onZoomBy:e.zoomBy}),doubleClick:t=>na({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,onZoomBy:e.zoomBy}),contextMenu:t=>ra({event:t,canvas:e.canvas,state:e.state})}}function sa(e){const{gl:t,cache:n,maxCacheTiles:r}=e;if(n.size<=r)return;const i=Array.from(n.entries());i.sort((s,a)=>s[1].lastUsed-a[1].lastUsed);const o=n.size-r;for(let s=0;s<o;s+=1){const[a,c]=i[s];t.deleteTexture(c.texture),n.delete(a)}}function aa(e,t){if(e.isContextLost())return null;const n=e.createTexture();return n?(e.bindTexture(e.TEXTURE_2D,n),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,1),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.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.bindTexture(e.TEXTURE_2D,null),n):null}function ca(e){const{gl:t,cache:n,tile:r,bitmap:i,frameSerial:o,maxCacheTiles:s,destroyed:a,contextLost:c,requestRender:u}=e;if(a||c||t.isContextLost()){i.close();return}if(n.has(r.key)){i.close();return}const l=aa(t,i);i.close(),l&&(n.set(r.key,{key:r.key,texture:l,bounds:r.bounds,tier:r.tier,lastUsed:o}),sa({gl:t,cache:n,maxCacheTiles:s}),u())}function ua(e,t){for(const[,n]of t)e.deleteTexture(n.texture)}function la(e){const{event:t,destroyed:n,contextLost:r,cancelViewAnimation:i,cancelDrag:o,tileScheduler:s,cache:a,onContextLost:c}=e;if(t.preventDefault(),n||r)return{handled:!1,frame:e.frame};let u=e.frame;return u!==null&&(cancelAnimationFrame(u),u=null),i(),o(),s.clear(),a.clear(),c?.(),{handled:!0,frame:u}}function fa(e){if(e.destroyed)return{didDestroy:!1,frame:e.frame};let t=e.frame;return t!==null&&(cancelAnimationFrame(t),t=null),e.cancelViewAnimation(),e.resizeObserver.disconnect(),e.removeCanvasEventListeners(),e.cancelDrag(),e.tileScheduler.destroy(),!e.contextLost&&!e.gl.isContextLost()&&(ua(e.gl,e.cache),e.gl.deleteBuffer(e.tileProgram.vbo),e.gl.deleteVertexArray(e.tileProgram.vao),e.gl.deleteProgram(e.tileProgram.program),e.gl.deleteBuffer(e.pointProgram.posBuffer),e.gl.deleteBuffer(e.pointProgram.termBuffer),e.gl.deleteBuffer(e.pointProgram.fillModeBuffer),e.gl.deleteBuffer(e.pointProgram.indexBuffer),e.gl.deleteTexture(e.pointProgram.paletteTexture),e.gl.deleteVertexArray(e.pointProgram.vao),e.gl.deleteProgram(e.pointProgram.program)),e.cache.clear(),{didDestroy:!0,frame:t}}function da(e,t){if(t<=0||e.length===0)return new Uint32Array(0);let n=e.length;for(let o=0;o<e.length;o+=1)e[o]<t||(n-=1);if(n===e.length)return e;if(n<=0)return new Uint32Array(0);const r=new Uint32Array(n);let i=0;for(let o=0;o<e.length;o+=1){const s=e[o];s>=t||(r[i]=s,i+=1)}return r}function ha(e,t){return t<=0?new Uint8Array(0):e.length<t?new Uint8Array(t):e.subarray(0,t)}function ma(e,t,n,r,i){if(!i||i.length===0)return{...e,lastPointPalette:null};const o=new Uint8Array(i);if(r||t.isContextLost())return{...e,lastPointPalette:o};const s=Math.max(1,Math.floor(o.length/4));return t.bindTexture(t.TEXTURE_2D,n.paletteTexture),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,s,1,0,t.RGBA,t.UNSIGNED_BYTE,o),t.bindTexture(t.TEXTURE_2D,null),{...e,lastPointPalette:o,pointPaletteSize:s}}function ga(e,t,n,r,i){if(!i||!i.count||!i.positions||!i.paletteIndices)return{...e,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)),c=i.positions.subarray(0,a*2),u=i.paletteIndices.subarray(0,a),l=s?o.subarray(0,a):void 0,d=i.drawIndices instanceof Uint32Array,f=d?da(i.drawIndices,a):null,y=e.lastPointData,b=y?.fillModes instanceof Uint8Array,w=e.pointBuffersDirty||!y||y.count!==a||!Gt(y.positions,c)||!Gt(y.paletteIndices,u)||b!==s||s&&(!y?.fillModes||!Gt(y.fillModes,l)),x=e.pointBuffersDirty||d&&(!y?.drawIndices||!Gt(y.drawIndices,f))||!d&&!!y?.drawIndices,R={...e,lastPointData:{count:a,positions:c,paletteIndices:u,fillModes:l,drawIndices:d?f??void 0:void 0}};if(r||t.isContextLost())return R;const E=R.lastPointData;if(!E)return R;if(w){t.bindBuffer(t.ARRAY_BUFFER,n.posBuffer),t.bufferData(t.ARRAY_BUFFER,E.positions,t.STATIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,n.termBuffer),t.bufferData(t.ARRAY_BUFFER,E.paletteIndices,t.STATIC_DRAW);const X=ha(R.zeroFillModes,a);t.bindBuffer(t.ARRAY_BUFFER,n.fillModeBuffer),t.bufferData(t.ARRAY_BUFFER,E.fillModes??X,t.STATIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,null),R.zeroFillModes=X}return d&&x&&(t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,n.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,f??new Uint32Array(0),t.DYNAMIC_DRAW),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null)),R.usePointIndices=d,R.pointCount=d?f?.length??0:E.count,(w||x)&&(R.pointBuffersDirty=!1),R}function pa(e){const{gl:t,camera:n,source:r,cache:i,frameSerial:o,tileProgram:s,pointProgram:a,imageColorSettings:c,pointCount:u,usePointIndices:l,pointPaletteSize:d,pointStrokeScale:f,pointInnerFillOpacity:y,pointSizePx:b,tileScheduler:w,getVisibleTiles:x,getVisibleTilesForTier:R,getViewBounds:E,intersectsBounds:X}=e;t.clearColor(.03,.06,.1,1),t.clear(t.COLOR_BUFFER_BIT);const{tier:A,visible:F}=x(),K=E(),oe=new Set(F.map(O=>O.key));t.useProgram(s.program),t.bindVertexArray(s.vao),t.uniformMatrix3fv(s.uCamera,!1,n.getMatrix()),t.uniform1i(s.uTexture,0),t.uniform1f(s.uBrightness,c.brightness),t.uniform1f(s.uContrast,c.contrast),t.uniform1f(s.uSaturation,c.saturation);const Q=[];for(const[,O]of i)oe.has(O.key)||X(O.bounds,K)&&Q.push(O);Q.sort((O,D)=>O.tier-D.tier);for(const O of Q)O.lastUsed=o,t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,O.texture),t.uniform4f(s.uBounds,O.bounds[0],O.bounds[1],O.bounds[2],O.bounds[3]),t.drawArrays(t.TRIANGLE_STRIP,0,4);let ee=0;const se=[];for(const O of F){const D=i.get(O.key);if(!D){se.push(O);continue}D.lastUsed=o,t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,D.texture),t.uniform4f(s.uBounds,D.bounds[0],D.bounds[1],D.bounds[2],D.bounds[3]),t.drawArrays(t.TRIANGLE_STRIP,0,4),ee+=1}const ge=se.slice(),Te=1e6,_=[];A>0&&_.push(A-1),A<r.maxTierZoom&&_.push(A+1);for(const O of _){const D=R(O);for(const V of D)i.has(V.key)||(V.distance2+=Te,ge.push(V))}w.schedule(ge),t.bindTexture(t.TEXTURE_2D,null),t.bindVertexArray(null);let L=0;return u>0&&(t.enable(t.BLEND),t.blendFunc(t.ONE,t.ONE_MINUS_SRC_ALPHA),t.useProgram(a.program),t.bindVertexArray(a.vao),t.uniformMatrix3fv(a.uCamera,!1,n.getMatrix()),t.uniform1f(a.uPointSize,b),t.uniform1f(a.uPointStrokeScale,f),t.uniform1f(a.uPointInnerFillAlpha,y),t.uniform1f(a.uPaletteSize,d),t.uniform1i(a.uPalette,1),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,a.paletteTexture),l?t.drawElements(t.POINTS,u,t.UNSIGNED_INT,0):t.drawArrays(t.POINTS,0,u),t.bindTexture(t.TEXTURE_2D,null),t.bindVertexArray(null),L=u),{tier:A,visible:F.length,rendered:ee,points:L,fallback:Q.length,cacheHits:ee,cacheMisses:se.length,drawCalls:Q.length+ee+(L>0?1:0)}}function Ar(e){const r=Rn(e,`#version 300 es
63
+ `;function fs(){if(typeof navigator>"u")return!1;const e=navigator;return typeof e.gpu=="object"&&e.gpu!==null}function Kr(){if(!fs())return null;const t=navigator.gpu;if(!t||typeof t!="object")return null;const n=t;return typeof n.requestAdapter!="function"?null:n}const Vt=globalThis.GPUShaderStage?.COMPUTE??4,dn=globalThis.GPUBufferUsage?.STORAGE??128,Gt=globalThis.GPUBufferUsage?.COPY_DST??8,ds=globalThis.GPUBufferUsage?.COPY_SRC??4,hs=globalThis.GPUBufferUsage?.UNIFORM??64,ms=globalThis.GPUBufferUsage?.MAP_READ??1,gs=globalThis.GPUMapMode?.READ??1;async function ps(){const e=Kr();if(!e)return{supported:!1,features:[]};const t=await e.requestAdapter();return t?{supported:!0,adapterName:t.info?.description??t.info?.vendor??"unknown",features:Array.from(t.features),limits:{maxStorageBufferBindingSize:Number(t.limits.maxStorageBufferBindingSize),maxComputeInvocationsPerWorkgroup:Number(t.limits.maxComputeInvocationsPerWorkgroup),maxComputeWorkgroupSizeX:Number(t.limits.maxComputeWorkgroupSizeX)}}:{supported:!1,features:[]}}async function bs(){return Xt||(Xt=(async()=>{const e=Kr();if(!e)return null;const t=await e.requestAdapter();if(!t)return null;const n=await t.requestDevice(),r=n.createBindGroupLayout({entries:[{binding:0,visibility:Vt,buffer:{type:"read-only-storage"}},{binding:1,visibility:Vt,buffer:{type:"read-only-storage"}},{binding:2,visibility:Vt,buffer:{type:"storage"}},{binding:3,visibility:Vt,buffer:{type:"uniform"}}]}),i=n.createComputePipeline({layout:n.createPipelineLayout({bindGroupLayouts:[r]}),compute:{module:n.createShaderModule({code:ls}),entryPoint:"main"}});return{device:n,pipeline:i,bindGroupLayout:r}})(),Xt)}function qt(e,t){return Math.ceil(e/t)*t}async function jr(e,t,n){const r=await bs();if(!r)return null;const i=Math.max(0,Math.floor(t)),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(e.length/2));if(s===0)return new Uint32Array(0);const a=s*2*Float32Array.BYTES_PER_ELEMENT,c=o*4*Float32Array.BYTES_PER_ELEMENT,u=s*Uint32Array.BYTES_PER_ELEMENT,l=Number(r.device.limits.maxStorageBufferBindingSize);if(a>l||c>l||u>l)return null;const h=r.device.createBuffer({size:qt(a,4),usage:dn|Gt}),f=r.device.createBuffer({size:qt(c,4),usage:dn|Gt}),y=r.device.createBuffer({size:qt(u,4),usage:dn|ds}),b=r.device.createBuffer({size:16,usage:hs|Gt}),x=r.device.createBuffer({size:qt(u,4),usage:Gt|ms});r.device.queue.writeBuffer(h,0,e.buffer,e.byteOffset,a),r.device.queue.writeBuffer(f,0,n.buffer,n.byteOffset,c),r.device.queue.writeBuffer(b,0,new Uint32Array([s,o,0,0]));const w=r.device.createBindGroup({layout:r.bindGroupLayout,entries:[{binding:0,resource:{buffer:h}},{binding:1,resource:{buffer:f}},{binding:2,resource:{buffer:y}},{binding:3,resource:{buffer:b}}]}),A=r.device.createCommandEncoder(),E=A.beginComputePass();E.setPipeline(r.pipeline),E.setBindGroup(0,w),E.dispatchWorkgroups(Math.ceil(s/256)),E.end(),A.copyBufferToBuffer(y,0,x,0,u),r.device.queue.submit([A.finish()]),await x.mapAsync(gs);const X=x.getMappedRange(),R=new Uint32Array(X.slice(0));return x.unmap(),h.destroy(),f.destroy(),y.destroy(),b.destroy(),x.destroy(),R}async function Jr(e,t,n={}){const r=fe(),i=n.bridgeToDraw===!0;if(!e||!e.count||!e.positions||!e.paletteIndices)return{data:null,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}};const o=Et(t??[]);if(o.length===0){const R={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return e.fillModes instanceof Uint8Array&&(R.fillModes=new Uint8Array(0)),e.ids instanceof Uint32Array&&(R.ids=new Uint32Array(0)),{data:R,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const s=at(e),a=e.fillModes instanceof Uint8Array&&e.fillModes.length>=s?e.fillModes:null,c=e.ids instanceof Uint32Array&&e.ids.length>=s?e.ids:null;if(s===0){const R={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(R.fillModes=new Uint8Array(0)),c&&(R.ids=new Uint32Array(0)),{data:R,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const u=new Float32Array(o.length*4);for(let R=0;R<o.length;R+=1){const _=R*4,H=o[R];u[_]=H.minX,u[_+1]=H.minY,u[_+2]=H.maxX,u[_+3]=H.maxY}let l=null,h=!1;try{l=await jr(e.positions,s,u),h=!!l}catch{l=null,h=!1}if(!l)return{data:Ct(e,t),meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!1,candidateCount:s,bridgedToDraw:!1}};let f=0;for(let R=0;R<s;R+=1)l[R]===1&&(f+=1);const y=new Uint32Array(f);if(f>0){let R=0;for(let _=0;_<s;_+=1)l[_]===1&&(y[R]=_,R+=1)}if(f===0){if(i){const _={count:s,positions:e.positions.subarray(0,s*2),paletteIndices:e.paletteIndices.subarray(0,s),drawIndices:new Uint32Array(0)};return a&&(_.fillModes=a.subarray(0,s)),c&&(_.ids=c.subarray(0,s)),{data:_,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!0}}}const R={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(R.fillModes=new Uint8Array(0)),c&&(R.ids=new Uint32Array(0)),{data:R,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!1}}}if(i){const R=new Uint32Array(f);let _=0;for(let se=0;se<f;se+=1){const j=y[se]??0,J=e.positions[j*2],ae=e.positions[j*2+1];jt(J,ae,o)&&(R[_]=j,_+=1)}const H={count:s,positions:e.positions.subarray(0,s*2),paletteIndices:e.paletteIndices.subarray(0,s),drawIndices:R.subarray(0,_)};return a&&(H.fillModes=a.subarray(0,s)),c&&(H.ids=c.subarray(0,s)),{data:H,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!0,candidateCount:f,bridgedToDraw:!0}}}const b=new Float32Array(f*2),x=new Uint16Array(f),w=a?new Uint8Array(f):null,A=c?new Uint32Array(f):null;let E=0;for(let R=0;R<f;R+=1){const _=y[R]??0,H=e.positions[_*2],se=e.positions[_*2+1];jt(H,se,o)&&(b[E*2]=H,b[E*2+1]=se,x[E]=e.paletteIndices[_],w&&(w[E]=a[_]),A&&(A[E]=c[_]),E+=1)}const X={count:E,positions:b.subarray(0,E*2),paletteIndices:x.subarray(0,E)};return w&&(X.fillModes=w.subarray(0,E)),A&&(X.ids=A.subarray(0,E)),{data:X,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!0,candidateCount:f,bridgedToDraw:!1}}}class Qr{constructor(t,n){S(this,"worker",null);S(this,"supported",!0);S(this,"requestId",1);S(this,"pendingById",new Map);S(this,"handleMessage",t=>{const n=t.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=t,this.handlers=n}beginRequest(t){const n=this.getOrCreateWorker();if(!n)return null;const r=this.requestId++;return this.pendingById.set(r,t),{id:r,worker:n}}cancelRequest(t){const n=this.pendingById.get(t);if(n)return this.pendingById.delete(t),n}terminate(t="worker terminated"){this.teardownWorker(t)}getOrCreateWorker(){if(!this.supported)return null;if(this.worker)return this.worker;try{const t=this.createWorker();return t.addEventListener("message",this.handleMessage),t.addEventListener("error",this.handleError),this.worker=t,t}catch{return this.supported=!1,null}}teardownWorker(t){this.worker&&(this.worker.removeEventListener("message",this.handleMessage),this.worker.removeEventListener("error",this.handleError),this.worker.terminate(),this.worker=null);const n=new Error(t);for(const[,r]of this.pendingById)this.handlers.rejectPending(r,n);this.pendingById.clear()}}const Pt=new Qr(()=>new Worker(new URL(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/roi-clip-worker-BDVQwN2T.js").href:new URL("assets/roi-clip-worker-BDVQwN2T.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),typeof document>"u"?require("url").pathToFileURL(__filename).href:gt&&gt.tagName.toUpperCase()==="SCRIPT"&&gt.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),{onResponse:(e,t)=>{if(e.type==="roi-clip-failure"){t.reject(new Error(e.error||"worker clip failed"));return}if(e.type==="roi-clip-index-success"){if(t.kind!=="index"){t.reject(new Error("worker response mismatch: expected point data result"));return}const c=Math.max(0,Math.floor(e.count)),u=new Uint32Array(e.indices).subarray(0,c);t.resolve({indices:u,meta:{mode:"worker",durationMs:Number.isFinite(e.durationMs)?e.durationMs:fe()-t.startMs}});return}if(t.kind!=="data"){t.reject(new Error("worker response mismatch: expected index result"));return}const n=Math.max(0,Math.floor(e.count)),r=new Float32Array(e.positions),i=new Uint16Array(e.paletteIndices),o=e.fillModes?new Uint8Array(e.fillModes):null,s=e.ids?new Uint32Array(e.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)),t.resolve({data:a,meta:{mode:"worker",durationMs:Number.isFinite(e.durationMs)?e.durationMs:fe()-t.startMs}})},rejectPending:(e,t)=>{e.reject(t)}});function ys(){Pt.terminate("worker terminated")}async function ei(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return{data:null,meta:{mode:"worker",durationMs:0}};const n=at(e),r=e.positions.slice(0,n*2),i=e.paletteIndices.slice(0,n),o=e.fillModes instanceof Uint8Array&&e.fillModes.length>=n?e.fillModes.slice(0,n):null,s=e.ids instanceof Uint32Array&&e.ids.length>=n?e.ids.slice(0,n):null;return new Promise((a,c)=>{const u=fe(),l=Pt.beginRequest({kind:"data",resolve:a,reject:c,startMs:u});if(!l){a({data:Ct(e,t),meta:{mode:"sync",durationMs:fe()-u}});return}const h={type:"roi-clip-request",id:l.id,count:n,positions:r.buffer,paletteIndices:i.buffer,fillModes:o?.buffer,ids:s?.buffer,polygons:t??[]},f=[r.buffer,i.buffer];o&&f.push(o.buffer),s&&f.push(s.buffer);try{l.worker.postMessage(h,f)}catch(y){const b=Pt.cancelRequest(l.id);b?b.reject(y):c(y)}})}async function ws(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return{indices:new Uint32Array(0),meta:{mode:"worker",durationMs:0}};const n=at(e),r=e.positions.slice(0,n*2);return new Promise((i,o)=>{const s=fe(),a=Pt.beginRequest({kind:"index",resolve:i,reject:o,startMs:s});if(!a){i({indices:Zr(e,t),meta:{mode:"sync",durationMs:fe()-s}});return}const c={type:"roi-clip-index-request",id:a.id,count:n,positions:r.buffer,polygons:t??[]};try{a.worker.postMessage(c,[r.buffer])}catch(u){const l=Pt.cancelRequest(a.id);l?l.reject(u):o(u)}})}const Ss=24,xs=1024,Ms=4,Kt=-1;function Mt(e,t,n){return(e*73856093^t*19349663)>>>0&n}function As(e,t,n){if(e<=0||t<=0||n<=0)return 256;const r=Math.max(1,e*t),o=Math.sqrt(r/Math.max(1,n))*Ms;return Math.max(Ss,Math.min(xs,o))}function Ts(e,t){if(!(e instanceof Uint32Array)||e.length===0)return null;let n=!0;for(let o=0;o<e.length;o+=1)if(!(e[o]<t)){n=!1;break}if(n)return e;const r=new Uint32Array(e.length);let i=0;for(let o=0;o<e.length;o+=1)e[o]>=t||(r[i]=e[o],i+=1);return i>0?r.subarray(0,i):null}function Rs(e){const t=Math.max(0,Math.floor(e.count)),n=Math.floor(e.positions.length/2),r=Math.max(0,Math.min(t,n));if(r<=0)return null;const i=Ts(e.drawIndices??null,r),o=i?i.length:r;if(o===0)return null;const s=As(e.sourceWidth,e.sourceHeight,o),a=1/s,c=new Int32Array(o),u=new Int32Array(o);let l=0;if(i)for(let B=0;B<o;B+=1){const D=i[B],O=e.positions[D*2],U=e.positions[D*2+1];!Number.isFinite(O)||!Number.isFinite(U)||(c[l]=Math.floor(O*a),u[l]=Math.floor(U*a),l+=1)}else for(let B=0;B<r;B+=1){const D=e.positions[B*2],O=e.positions[B*2+1];!Number.isFinite(D)||!Number.isFinite(O)||(c[l]=Math.floor(D*a),u[l]=Math.floor(O*a),l+=1)}if(l===0)return null;let h=Math.min(l,Math.max(64,l>>>3));(!Number.isFinite(h)||h<=0)&&(h=l);let f=1;for(;f<h*2;)f<<=1;let y=f-1,b=new Int32Array(f*2),x=new Int32Array(f);b.fill(2147483647);let w=0;const A=new Int32Array(l);for(let B=0;B<l;B+=1){const D=c[B],O=u[B];let U=Mt(D,O,y);for(;;){const Q=b[U*2];if(Q===2147483647){if(b[U*2]=D,b[U*2+1]=O,x[U]=1,A[B]=U,w+=1,w*4>f*3){const Le=f;f<<=1,y=f-1;const ue=new Int32Array(f*2),Oe=new Int32Array(f);ue.fill(2147483647);for(let Fe=0;Fe<Le;Fe+=1){if(b[Fe*2]===2147483647)continue;const We=b[Fe*2],C=b[Fe*2+1];let M=Mt(We,C,y);for(;ue[M*2]!==2147483647;)M=M+1&y;ue[M*2]=We,ue[M*2+1]=C,Oe[M]=x[Fe]}for(b=ue,x=Oe,U=Mt(D,O,y);b[U*2]!==D||b[U*2+1]!==O;)U=U+1&y;A[B]=U}break}if(Q===D&&b[U*2+1]===O){x[U]+=1,A[B]=U;break}U=U+1&y}}const E=new Int32Array(w*2),X=new Uint32Array(w),R=new Uint32Array(w),_=new Int32Array(f);_.fill(Kt);let H=0,se=0;for(let B=0;B<f;B+=1)b[B*2]!==2147483647&&(E[H*2]=b[B*2],E[H*2+1]=b[B*2+1],X[H]=se,R[H]=x[B],_[B]=H,se+=x[B],H+=1);const j=new Uint32Array(l),J=new Uint32Array(w);if(J.set(X),i)for(let B=0;B<l;B+=1){const D=_[A[B]];j[J[D]]=i[B],J[D]+=1}else{let B=0;for(let D=0;D<r;D+=1){const O=e.positions[D*2],U=e.positions[D*2+1];if(!Number.isFinite(O)||!Number.isFinite(U))continue;const Q=_[A[B]];j[J[Q]]=D,J[Q]+=1,B+=1}}let ae=1;for(;ae<w*2;)ae<<=1;const ge=ae-1,Te=new Int32Array(ae);Te.fill(Kt);for(let B=0;B<w;B+=1){const D=E[B*2],O=E[B*2+1];let U=Mt(D,O,ge);for(;Te[U]!==Kt;)U=U+1&ge;Te[U]=B}return{cellSize:s,safeCount:r,cellCount:w,hashCapacity:ae,hashTable:Te,cellKeys:E,cellOffsets:X,cellLengths:R,pointIndices:j}}function ti(e,t,n){const{hashTable:r,cellKeys:i,hashMask:o}=e;let s=Mt(t,n,o);for(;;){const a=r[s];if(a===Kt)return-1;if(i[a*2]===t&&i[a*2+1]===n)return a;s=s+1&o}}function Cs(e,t){if(e.safeCount<=0||e.cellCount<=0)return null;const n=e.safeCount;return{cellSize:e.cellSize,safeCount:n,positions:t.positions.subarray(0,n*2),ids:t.ids instanceof Uint32Array&&t.ids.length>=n?t.ids.subarray(0,n):null,hashCapacity:e.hashCapacity,hashMask:e.hashCapacity-1,hashTable:new Int32Array(e.hashTable),cellKeys:new Int32Array(e.cellKeys),cellOffsets:new Uint32Array(e.cellOffsets),cellLengths:new Uint32Array(e.cellLengths),pointIndices:new Uint32Array(e.pointIndices)}}const Sn=new Qr(()=>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:gt&&gt.tagName.toUpperCase()==="SCRIPT"&&gt.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),{onResponse:(e,t)=>{if(e.type==="point-hit-index-failure"){t.reject(new Error(e.error||"worker index build failed"));return}t.resolve(Cs(e,t.pointData))},rejectPending:(e,t)=>{e.reject(t)}});function Ps(){Sn.terminate("worker terminated")}function Is(e,t){const n=at(e);if(n<=0)return null;const r=e.positions.subarray(0,n*2),i=Rs({count:n,positions:r,drawIndices:e.drawIndices instanceof Uint32Array?e.drawIndices:null,sourceWidth:t?.width??0,sourceHeight:t?.height??0});return i?{cellSize:i.cellSize,safeCount:n,positions:r,ids:e.ids instanceof Uint32Array&&e.ids.length>=n?e.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 ni(e,t){if(!e||!e.positions||!e.paletteIndices)return null;const n=at(e);return n<=0?null:new Promise((r,i)=>{const o={resolve:r,reject:i,pointData:e},s=Sn.beginRequest(o);if(!s||!s.worker){r(Is(e,t));return}const a=e.positions.slice(0,n*2),c=e.drawIndices instanceof Uint32Array&&e.drawIndices.length>0?e.drawIndices.slice():void 0,u={type:"point-hit-index-request",id:s.id,count:n,positions:a.buffer,drawIndices:c?.buffer,sourceWidth:t?.width??0,sourceHeight:t?.height??0},l=[a.buffer];c&&l.push(c.buffer);try{s.worker.postMessage(u,l)}catch(h){const f=Sn.cancelRequest(s.id);f?f.reject(h):i(h)}})}function Es(e){const t=[];for(let n=0;n<e.length;n+=1){const r=e[n],i=Et([It(r?.coordinates)]);if(i.length===0)continue;let o=0;for(const s of i)o+=s.area;t.push({regionId:r.id??n,regionIndex:n,polygons:i,area:Math.max(1e-6,o)})}return t}function vs(e,t){if(Array.isArray(t)){const n=t[e];if(typeof n=="string"&&n.length>0)return n}if(t instanceof Map){const n=t.get(e);if(typeof n=="string"&&n.length>0)return n}return String(e)}function ri(e,t,n={}){const r=Math.max(0,Math.min(Math.floor(e?.count??0),Math.floor((e?.positions?.length??0)/2),e?.paletteIndices?.length??0,e?.fillModes instanceof Uint8Array?e.fillModes.length:Number.MAX_SAFE_INTEGER));let i=null;if(e?.drawIndices instanceof Uint32Array){const f=e.drawIndices;let y=f.length;for(let b=0;b<f.length;b+=1)f[b]<r||(y-=1);if(y===f.length)i=f;else if(y>0){const b=new Uint32Array(y);let x=0;for(let w=0;w<f.length;w+=1){const A=f[w];A>=r||(b[x]=A,x+=1)}i=b}else i=new Uint32Array(0)}const o=i?i.length:r,s=Es(t??[]);if(!e||o===0||s.length===0)return{groups:[],inputPointCount:o,pointsInsideAnyRegion:0,unmatchedPointCount:o};const a=new Map,c=new Map;let u=0;for(let f=0;f<o;f+=1){const y=i?i[f]:f,b=e.positions[y*2],x=e.positions[y*2+1];let w=null;for(const X of s){let R=!1;for(const _ of X.polygons)if(Ur(b,x,_)){R=!0;break}R&&(!w||X.area<w.area)&&(w=X)}if(!w)continue;u+=1;const A=e.paletteIndices[y]??0,E=a.get(w.regionIndex)??new Map;E.set(A,(E.get(A)??0)+1),a.set(w.regionIndex,E),c.set(w.regionIndex,(c.get(w.regionIndex)??0)+1)}const l=n.includeEmptyRegions??!1,h=[];for(const f of s){const y=c.get(f.regionIndex)??0;if(!l&&y<=0)continue;const b=a.get(f.regionIndex)??new Map,x=Array.from(b.entries()).map(([w,A])=>({termId:vs(w,n.paletteIndexToTermId),paletteIndex:w,count:A})).sort((w,A)=>A.count-w.count||w.paletteIndex-A.paletteIndex);h.push({regionId:f.regionId,regionIndex:f.regionIndex,totalCount:y,termCounts:x})}return{groups:h,inputPointCount:o,pointsInsideAnyRegion:u,unmatchedPointCount:Math.max(0,o-u)}}function _s(e,t){if(!t)return!1;try{const r=new URL(e,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 ii{constructor(t){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(t.maxConcurrency??12)),this.maxRetries=Math.max(0,Math.floor(t.maxRetries??2)),this.retryBaseDelayMs=Math.max(10,Math.floor(t.retryBaseDelayMs??120)),this.retryMaxDelayMs=Math.max(this.retryBaseDelayMs,Math.floor(t.retryMaxDelayMs??1200)),this.authToken=t.authToken??"",this.onTileLoad=t.onTileLoad,this.onTileError=t.onTileError,this.onStateChange=t.onStateChange}setAuthToken(t){this.authToken=String(t??"")}schedule(t){if(this.destroyed)return;const n=new Set;for(const r of t)n.add(r.key);this.visibleKeys=n,this.dropInvisibleQueued(n),this.abortInvisibleInflight(n);for(const r of t){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:fe()};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[,t]of this.inflight)t.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(t){if(this.queue.length===0)return;const n=[];for(const r of this.queue){if(!t.has(r.tile.key)){this.queuedByKey.delete(r.tile.key);continue}n.push(r)}this.queue=n}abortInvisibleInflight(t){for(const[n,r]of this.inflight)t.has(n)||(this.inflight.delete(n),this.abortedCount+=1,r.controller.abort())}sortQueue(){this.queue.sort((t,n)=>t.readyAt!==n.readyAt?t.readyAt-n.readyAt:t.tile.distance2!==n.tile.distance2?t.tile.distance2-n.tile.distance2:t.tile.tier!==n.tile.tier?n.tile.tier-t.tile.tier:t.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 t=this.queue[0]?.readyAt;if(typeof t!="number")return;const n=Math.max(0,t-fe());this.timerId=window.setTimeout(()=>{this.timerId=null,this.pump()},n)}takeNextReadyQueueItem(){if(this.queue.length===0)return null;const t=fe(),n=this.queue[0];return!n||n.readyAt>t?null:(this.queue.shift(),this.queuedByKey.delete(n.tile.key),n)}startFetch(t){const n=new AbortController,r={tile:t.tile,attempt:t.attempt,controller:n};this.inflight.set(t.tile.key,r),this.emitStateChange();const i=_s(t.tile.url,this.authToken);fetch(t.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(t.tile.key)){o.close();return}this.onTileLoad(t.tile,o)}).catch(o=>{if(n.signal.aborted||this.destroyed)return;if(t.attempt<this.maxRetries&&this.visibleKeys.has(t.tile.key)){this.retryCount+=1;const a=t.attempt+1,c=this.getRetryDelay(a),u={tile:t.tile,attempt:a,readyAt:fe()+c},l=this.queuedByKey.get(t.tile.key);l?(l.tile=u.tile,l.readyAt=Math.min(l.readyAt,u.readyAt),l.attempt=Math.max(l.attempt,u.attempt)):(this.queue.push(u),this.queuedByKey.set(u.tile.key,u)),this.sortQueue();return}this.failedCount+=1,this.onTileError?.(t.tile,o,t.attempt+1)}).finally(()=>{this.inflight.delete(t.tile.key),this.pump(),this.emitStateChange()})}getRetryDelay(t){const n=Math.max(0,t-1),r=Math.min(this.retryMaxDelayMs,this.retryBaseDelayMs*2**n),i=.85+Math.random()*.3;return Math.round(r*i)}clearPumpTimer(){this.timerId!==null&&(window.clearTimeout(this.timerId),this.timerId=null)}emitStateChange(){this.onStateChange?.(this.getSnapshot())}}function Fs(e,t){e.addEventListener("pointerdown",t.pointerDown),e.addEventListener("pointermove",t.pointerMove),e.addEventListener("pointerup",t.pointerUp),e.addEventListener("pointercancel",t.pointerUp),e.addEventListener("wheel",t.wheel,{passive:!1}),e.addEventListener("dblclick",t.doubleClick),e.addEventListener("contextmenu",t.contextMenu),e.addEventListener("webglcontextlost",t.contextLost),e.addEventListener("webglcontextrestored",t.contextRestored)}function Bs(e,t){e.removeEventListener("pointerdown",t.pointerDown),e.removeEventListener("pointermove",t.pointerMove),e.removeEventListener("pointerup",t.pointerUp),e.removeEventListener("pointercancel",t.pointerUp),e.removeEventListener("wheel",t.wheel),e.removeEventListener("dblclick",t.doubleClick),e.removeEventListener("contextmenu",t.contextMenu),e.removeEventListener("webglcontextlost",t.contextLost),e.removeEventListener("webglcontextrestored",t.contextRestored)}function Us(e,t,n){const r=e.getBoundingClientRect(),i=Math.max(1,r.width||e.clientWidth||1),o=Math.max(1,r.height||e.clientHeight||1),s=Math.max(1,window.devicePixelRatio||1),a=Math.max(1,Math.round(i*s)),c=Math.max(1,Math.round(o*s));(e.width!==a||e.height!==c)&&(e.width=a,e.height=c),n.setViewport(i,o),t.viewport(0,0,a,c)}const xn=.35,Mn=.5,Ls=256,An=[{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}],Ds=.1,ks=5,Ns=0,zs=1,Os=-100,Ws=100,Ys=2e3;function oi(e){return e*Math.PI/180}function Ht(e,t){return!e||!t?e===t:e.buffer===t.buffer&&e.byteOffset===t.byteOffset&&e.byteLength===t.byteLength}function Tn(e){return e.map(t=>({zoom:t.zoom,size:t.size}))}function xr(e){if(!e)return Tn(An);const t=new Map;for(const[n,r]of Object.entries(e)){const i=Number(n),o=Number(r);!Number.isFinite(i)||!Number.isFinite(o)||o<=0||t.set(i,o)}return t.size===0?Tn(An):Array.from(t.entries()).sort((n,r)=>n[0]-r[0]).map(([n,r])=>({zoom:n,size:r}))}function Xs(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n].zoom!==t[n].zoom||e[n].size!==t[n].size)return!1;return!0}function Vs(e,t){if(!Number.isFinite(e))return t[0]?.size??Mn;if(t.length===0)return Mn;if(t.length===1||e<=t[0].zoom)return t[0].size;for(let s=1;s<t.length;s+=1){const a=t[s-1],c=t[s];if(e>c.zoom)continue;const u=Math.max(1e-6,c.zoom-a.zoom),l=k((e-a.zoom)/u,0,1);return a.size+(c.size-a.size)*l}const n=t[t.length-1],r=t[t.length-2],i=Math.max(1e-6,n.zoom-r.zoom),o=(n.size-r.size)/i;return n.size+(e-n.zoom)*o}function Mr(e){return typeof e!="number"||!Number.isFinite(e)?1:k(e,Ds,ks)}function Ar(e){return typeof e!="number"||!Number.isFinite(e)?0:k(e,Ns,zs)}function hn(e){return typeof e!="number"||!Number.isFinite(e)?0:k(e,Os,Ws)}function Tr(e){const t=hn(e?.brightness),n=hn(e?.contrast),r=hn(e?.saturation);return{brightness:t/200,contrast:n/100,saturation:r/100}}function si(e){return e}function mn(e){return typeof e!="number"||!Number.isFinite(e)?0:k(e,0,Ys)}function $t(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?null:Math.max(1e-6,e)}function gn(e){return typeof e=="function"?e:si}function ai(e,t,n){const r=e.getBoundingClientRect(),i=t-r.left-r.width*.5,o=n-r.top-r.height*.5;return Math.atan2(o,i)}function ci(e,t){if(t.pointerId!==null&&e.hasPointerCapture(t.pointerId))try{e.releasePointerCapture(t.pointerId)}catch{}t.dragging=!1,t.mode="none",t.rotateLastAngleRad=null,t.pointerId=null,e.classList.remove("dragging")}function Gs(e){const{event:t,canvas:n,state:r,config:i,cancelViewAnimation:o}=e,s=i.ctrlDragRotate&&(t.ctrlKey||t.metaKey);(t.button===0||s&&t.button===2)&&(o(),s&&t.preventDefault(),r.dragging=!0,r.mode=s?"rotate":"pan",r.pointerId=t.pointerId,r.lastPointerX=t.clientX,r.lastPointerY=t.clientY,r.rotateLastAngleRad=r.mode==="rotate"?ai(n,t.clientX,t.clientY):null,n.classList.add("dragging"),n.setPointerCapture(t.pointerId))}function qs(e){const{event:t,canvas:n,state:r,config:i,camera:o,clampViewState:s,emitViewState:a,requestRender:c}=e;if(!r.dragging||t.pointerId!==r.pointerId)return;const u=t.clientX-r.lastPointerX,l=t.clientY-r.lastPointerY;if(r.lastPointerX=t.clientX,r.lastPointerY=t.clientY,r.mode==="rotate"){const h=ai(n,t.clientX,t.clientY),f=r.rotateLastAngleRad;if(r.rotateLastAngleRad=h,f!==null){const y=h-f,b=Math.atan2(Math.sin(y),Math.cos(y)),x=i.rotationDragSensitivityDegPerPixel/xn,w=o.getViewState();o.setViewState({rotationDeg:w.rotationDeg-b*180/Math.PI*x})}}else{const h=o.getViewState(),f=Math.max(1e-6,h.zoom),y=oi(h.rotationDeg),b=Math.cos(y),x=Math.sin(y),w=(u*b-l*x)/f,A=(u*x+l*b)/f;o.setViewState({offsetX:h.offsetX-w,offsetY:h.offsetY-A})}s(),a(),c()}function Hs(e,t,n){e.pointerId===n.pointerId&&ci(t,n)}function $s(e){const{event:t,canvas:n,onZoomBy:r}=e;t.preventDefault();const i=n.getBoundingClientRect(),o=t.clientX-i.left,s=t.clientY-i.top,a=t.deltaY<0?1.12:.89;r(a,o,s)}function Zs(e){const{event:t,canvas:n,onZoomBy:r}=e,i=n.getBoundingClientRect(),o=t.clientX-i.left,s=t.clientY-i.top;r(t.shiftKey?.8:1.25,o,s)}function Ks(e,t){(t||e.ctrlKey||e.metaKey)&&e.preventDefault()}function Bn(e){const t=e.getViewCorners();let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[s,a]of t)s<n&&(n=s),s>i&&(i=s),a<r&&(r=a),a>o&&(o=a);return[n,r,i,o]}function Rn(e,t){const n=Bn(e),r=Math.max(1e-6,n[2]-n[0]),i=Math.max(1e-6,n[3]-n[1]),o=r*.2,s=i*.2,[a,c]=e.getCenter(),u=r*.5,l=i*.5,h=u-o,f=t.width-u+o,y=l-s,b=t.height-l+s,x=h<=f?k(a,h,f):t.width*.5,w=y<=b?k(c,y,b):t.height*.5;e.setCenter(x,w)}function js(e,t){const n=Math.max(1e-6,e.getViewState().zoom),r=t.maxTierZoom+Math.log2(n);return k(Math.floor(r),0,t.maxTierZoom)}function Js(e,t){return!(e[2]<=t[0]||e[0]>=t[2]||e[3]<=t[1]||e[1]>=t[3])}function ui(e,t,n){const r=Bn(e),i=Math.pow(2,t.maxTierZoom-n),o=Math.ceil(t.width/i),s=Math.ceil(t.height/i),a=Math.max(1,Math.ceil(o/t.tileSize)),c=Math.max(1,Math.ceil(s/t.tileSize)),u=r[0],l=r[1],h=r[2],f=r[3],y=k(Math.floor(u/i/t.tileSize),0,a-1),b=k(Math.floor((h-1)/i/t.tileSize),0,a-1),x=k(Math.floor(l/i/t.tileSize),0,c-1),w=k(Math.floor((f-1)/i/t.tileSize),0,c-1);if(y>b||x>w)return[];const A=(u+h)*.5/i/t.tileSize,E=(l+f)*.5/i/t.tileSize,X=[];for(let R=x;R<=w;R+=1)for(let _=y;_<=b;_+=1){const H=_*t.tileSize*i,se=R*t.tileSize*i,j=Math.min((_+1)*t.tileSize,o)*i,J=Math.min((R+1)*t.tileSize,s)*i,ae=_-A,ge=R-E;X.push({key:`${n}/${_}/${R}`,tier:n,x:_,y:R,bounds:[H,se,j,J],distance2:ae*ae+ge*ge,url:Fn(t,n,_,R)})}return X.sort((R,_)=>R.distance2-_.distance2),X}function Qs(e,t){const n=js(e,t);return{tier:n,visible:ui(e,t,n)}}function ea(e){e.interactionLocked||Gs({event:e.event,canvas:e.canvas,state:e.state,config:{ctrlDragRotate:e.ctrlDragRotate,rotationDragSensitivityDegPerPixel:e.rotationDragSensitivityDegPerPixel},cancelViewAnimation:e.cancelViewAnimation})}function ta(e){e.interactionLocked||qs({event:e.event,canvas:e.canvas,state:e.state,config:{ctrlDragRotate:e.ctrlDragRotate,rotationDragSensitivityDegPerPixel:e.rotationDragSensitivityDegPerPixel},camera:e.camera,clampViewState:()=>Rn(e.camera,e.source),emitViewState:e.emitViewState,requestRender:e.requestRender})}function na(e){e.interactionLocked||Hs(e.event,e.canvas,e.state)}function ra(e){if(e.interactionLocked){e.event.preventDefault();return}$s({event:e.event,canvas:e.canvas,onZoomBy:e.onZoomBy})}function ia(e){e.interactionLocked||Zs({event:e.event,canvas:e.canvas,onZoomBy:e.onZoomBy})}function oa(e){Ks(e.event,e.state.dragging)}function sa(e,t){ci(e,t)}function aa(e){return{pointerDown:t=>ea({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,state:e.state,ctrlDragRotate:e.getCtrlDragRotate(),rotationDragSensitivityDegPerPixel:e.getRotationDragSensitivityDegPerPixel(),cancelViewAnimation:e.cancelViewAnimation}),pointerMove:t=>ta({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,state:e.state,ctrlDragRotate:e.getCtrlDragRotate(),rotationDragSensitivityDegPerPixel:e.getRotationDragSensitivityDegPerPixel(),camera:e.camera,source:e.source,emitViewState:e.emitViewState,requestRender:e.requestRender}),pointerUp:t=>na({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,state:e.state}),wheel:t=>ra({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,onZoomBy:e.zoomBy}),doubleClick:t=>ia({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,onZoomBy:e.zoomBy}),contextMenu:t=>oa({event:t,canvas:e.canvas,state:e.state})}}function ca(e){const{gl:t,cache:n,maxCacheTiles:r}=e;if(n.size<=r)return;const i=Array.from(n.entries());i.sort((s,a)=>s[1].lastUsed-a[1].lastUsed);const o=n.size-r;for(let s=0;s<o;s+=1){const[a,c]=i[s];t.deleteTexture(c.texture),n.delete(a)}}function ua(e,t){if(e.isContextLost())return null;const n=e.createTexture();return n?(e.bindTexture(e.TEXTURE_2D,n),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,1),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.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.bindTexture(e.TEXTURE_2D,null),n):null}function la(e){const{gl:t,cache:n,tile:r,bitmap:i,frameSerial:o,maxCacheTiles:s,destroyed:a,contextLost:c,requestRender:u}=e;if(a||c||t.isContextLost()){i.close();return}if(n.has(r.key)){i.close();return}const l=ua(t,i);i.close(),l&&(n.set(r.key,{key:r.key,texture:l,bounds:r.bounds,tier:r.tier,lastUsed:o}),ca({gl:t,cache:n,maxCacheTiles:s}),u())}function fa(e,t){for(const[,n]of t)e.deleteTexture(n.texture)}function da(e){const{event:t,destroyed:n,contextLost:r,cancelViewAnimation:i,cancelDrag:o,tileScheduler:s,cache:a,onContextLost:c}=e;if(t.preventDefault(),n||r)return{handled:!1,frame:e.frame};let u=e.frame;return u!==null&&(cancelAnimationFrame(u),u=null),i(),o(),s.clear(),a.clear(),c?.(),{handled:!0,frame:u}}function ha(e){if(e.destroyed)return{didDestroy:!1,frame:e.frame};let t=e.frame;return t!==null&&(cancelAnimationFrame(t),t=null),e.cancelViewAnimation(),e.resizeObserver.disconnect(),e.removeCanvasEventListeners(),e.cancelDrag(),e.tileScheduler.destroy(),!e.contextLost&&!e.gl.isContextLost()&&(fa(e.gl,e.cache),e.gl.deleteBuffer(e.tileProgram.vbo),e.gl.deleteVertexArray(e.tileProgram.vao),e.gl.deleteProgram(e.tileProgram.program),e.gl.deleteBuffer(e.pointProgram.posBuffer),e.gl.deleteBuffer(e.pointProgram.termBuffer),e.gl.deleteBuffer(e.pointProgram.fillModeBuffer),e.gl.deleteBuffer(e.pointProgram.indexBuffer),e.gl.deleteTexture(e.pointProgram.paletteTexture),e.gl.deleteVertexArray(e.pointProgram.vao),e.gl.deleteProgram(e.pointProgram.program)),e.cache.clear(),{didDestroy:!0,frame:t}}function ma(e,t){if(t<=0||e.length===0)return new Uint32Array(0);let n=e.length;for(let o=0;o<e.length;o+=1)e[o]<t||(n-=1);if(n===e.length)return e;if(n<=0)return new Uint32Array(0);const r=new Uint32Array(n);let i=0;for(let o=0;o<e.length;o+=1){const s=e[o];s>=t||(r[i]=s,i+=1)}return r}function ga(e,t){return t<=0?new Uint8Array(0):e.length<t?new Uint8Array(t):e.subarray(0,t)}function pa(e,t,n,r,i){if(!i||i.length===0)return{...e,lastPointPalette:null};const o=new Uint8Array(i);if(r||t.isContextLost())return{...e,lastPointPalette:o};const s=Math.max(1,Math.floor(o.length/4));return t.bindTexture(t.TEXTURE_2D,n.paletteTexture),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,s,1,0,t.RGBA,t.UNSIGNED_BYTE,o),t.bindTexture(t.TEXTURE_2D,null),{...e,lastPointPalette:o,pointPaletteSize:s}}function ba(e,t,n,r,i){if(!i||!i.count||!i.positions||!i.paletteIndices)return{...e,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)),c=i.positions.subarray(0,a*2),u=i.paletteIndices.subarray(0,a),l=s?o.subarray(0,a):void 0,h=i.drawIndices instanceof Uint32Array,f=h?ma(i.drawIndices,a):null,y=e.lastPointData,b=y?.fillModes instanceof Uint8Array,x=e.pointBuffersDirty||!y||y.count!==a||!Ht(y.positions,c)||!Ht(y.paletteIndices,u)||b!==s||s&&(!y?.fillModes||!Ht(y.fillModes,l)),w=e.pointBuffersDirty||h&&(!y?.drawIndices||!Ht(y.drawIndices,f))||!h&&!!y?.drawIndices,A={...e,lastPointData:{count:a,positions:c,paletteIndices:u,fillModes:l,drawIndices:h?f??void 0:void 0}};if(r||t.isContextLost())return A;const E=A.lastPointData;if(!E)return A;if(x){t.bindBuffer(t.ARRAY_BUFFER,n.posBuffer),t.bufferData(t.ARRAY_BUFFER,E.positions,t.STATIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,n.termBuffer),t.bufferData(t.ARRAY_BUFFER,E.paletteIndices,t.STATIC_DRAW);const X=ga(A.zeroFillModes,a);t.bindBuffer(t.ARRAY_BUFFER,n.fillModeBuffer),t.bufferData(t.ARRAY_BUFFER,E.fillModes??X,t.STATIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,null),A.zeroFillModes=X}return h&&w&&(t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,n.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,f??new Uint32Array(0),t.DYNAMIC_DRAW),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null)),A.usePointIndices=h,A.pointCount=h?f?.length??0:E.count,(x||w)&&(A.pointBuffersDirty=!1),A}function ya(e){const{gl:t,camera:n,source:r,cache:i,frameSerial:o,tileProgram:s,pointProgram:a,imageColorSettings:c,pointCount:u,usePointIndices:l,pointPaletteSize:h,pointStrokeScale:f,pointInnerFillOpacity:y,pointSizePx:b,tileScheduler:x,getVisibleTiles:w,getVisibleTilesForTier:A,getViewBounds:E,intersectsBounds:X}=e;t.clearColor(.03,.06,.1,1),t.clear(t.COLOR_BUFFER_BIT);const{tier:R,visible:_}=w(),H=E(),se=new Set(_.map(O=>O.key));t.useProgram(s.program),t.bindVertexArray(s.vao),t.uniformMatrix3fv(s.uCamera,!1,n.getMatrix()),t.uniform1i(s.uTexture,0),t.uniform1f(s.uBrightness,c.brightness),t.uniform1f(s.uContrast,c.contrast),t.uniform1f(s.uSaturation,c.saturation);const j=[];for(const[,O]of i)se.has(O.key)||X(O.bounds,H)&&j.push(O);j.sort((O,U)=>O.tier-U.tier);for(const O of j)O.lastUsed=o,t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,O.texture),t.uniform4f(s.uBounds,O.bounds[0],O.bounds[1],O.bounds[2],O.bounds[3]),t.drawArrays(t.TRIANGLE_STRIP,0,4);let J=0;const ae=[];for(const O of _){const U=i.get(O.key);if(!U){ae.push(O);continue}U.lastUsed=o,t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,U.texture),t.uniform4f(s.uBounds,U.bounds[0],U.bounds[1],U.bounds[2],U.bounds[3]),t.drawArrays(t.TRIANGLE_STRIP,0,4),J+=1}const ge=ae.slice(),Te=1e6,B=[];R>0&&B.push(R-1),R<r.maxTierZoom&&B.push(R+1);for(const O of B){const U=A(O);for(const Q of U)i.has(Q.key)||(Q.distance2+=Te,ge.push(Q))}x.schedule(ge),t.bindTexture(t.TEXTURE_2D,null),t.bindVertexArray(null);let D=0;return u>0&&(t.enable(t.BLEND),t.blendFunc(t.ONE,t.ONE_MINUS_SRC_ALPHA),t.useProgram(a.program),t.bindVertexArray(a.vao),t.uniformMatrix3fv(a.uCamera,!1,n.getMatrix()),t.uniform1f(a.uPointSize,b),t.uniform1f(a.uPointStrokeScale,f),t.uniform1f(a.uPointInnerFillAlpha,y),t.uniform1f(a.uPaletteSize,h),t.uniform1i(a.uPalette,1),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,a.paletteTexture),l?t.drawElements(t.POINTS,u,t.UNSIGNED_INT,0):t.drawArrays(t.POINTS,0,u),t.bindTexture(t.TEXTURE_2D,null),t.bindVertexArray(null),D=u),{tier:R,visible:_.length,rendered:J,points:D,fallback:j.length,cacheHits:J,cacheMisses:ae.length,drawCalls:j.length+J+(D>0?1:0)}}function Rr(e){const r=Pn(e,`#version 300 es
64
64
  precision highp float;
65
65
  in vec2 aUnit;
66
66
  in vec2 aUv;
@@ -105,7 +105,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
105
105
 
106
106
  color.rgb = clamp(color.rgb + uBrightness, vec3(0.0), vec3(1.0));
107
107
  outColor = color;
108
- }`),i=Ee(e,r,"uCamera"),o=Ee(e,r,"uBounds"),s=Ee(e,r,"uTexture"),a=Ee(e,r,"uBrightness"),c=Ee(e,r,"uContrast"),u=Ee(e,r,"uSaturation"),l=e.createVertexArray(),d=e.createBuffer();if(!l||!d)throw new Error("buffer allocation failed");e.bindVertexArray(l),e.bindBuffer(e.ARRAY_BUFFER,d),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,0,0,0,1,0,1,0,0,1,0,1,1,1,1,1]),e.STATIC_DRAW);const f=e.getAttribLocation(r,"aUnit"),y=e.getAttribLocation(r,"aUv");if(f<0||y<0)throw new Error("tile attribute lookup failed");return e.enableVertexAttribArray(f),e.enableVertexAttribArray(y),e.vertexAttribPointer(f,2,e.FLOAT,!1,16,0),e.vertexAttribPointer(y,2,e.FLOAT,!1,16,8),e.bindVertexArray(null),e.bindBuffer(e.ARRAY_BUFFER,null),{program:r,vao:l,vbo:d,uCamera:i,uBounds:o,uTexture:s,uBrightness:a,uContrast:c,uSaturation:u}}function Tr(e){const r=Rn(e,`#version 300 es
108
+ }`),i=Pe(e,r,"uCamera"),o=Pe(e,r,"uBounds"),s=Pe(e,r,"uTexture"),a=Pe(e,r,"uBrightness"),c=Pe(e,r,"uContrast"),u=Pe(e,r,"uSaturation"),l=e.createVertexArray(),h=e.createBuffer();if(!l||!h)throw new Error("buffer allocation failed");e.bindVertexArray(l),e.bindBuffer(e.ARRAY_BUFFER,h),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,0,0,0,1,0,1,0,0,1,0,1,1,1,1,1]),e.STATIC_DRAW);const f=e.getAttribLocation(r,"aUnit"),y=e.getAttribLocation(r,"aUv");if(f<0||y<0)throw new Error("tile attribute lookup failed");return e.enableVertexAttribArray(f),e.enableVertexAttribArray(y),e.vertexAttribPointer(f,2,e.FLOAT,!1,16,0),e.vertexAttribPointer(y,2,e.FLOAT,!1,16,8),e.bindVertexArray(null),e.bindBuffer(e.ARRAY_BUFFER,null),{program:r,vao:l,vbo:h,uCamera:i,uBounds:o,uTexture:s,uBrightness:a,uContrast:c,uSaturation:u}}function Cr(e){const r=Pn(e,`#version 300 es
109
109
  precision highp float;
110
110
  in vec2 aPosition;
111
111
  in uint aTerm;
@@ -158,6 +158,6 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
158
158
  // Premultiplied alpha output: inner fill is black, so it only contributes alpha.
159
159
  outColor = vec4(color.rgb * ringAlpha, alpha);
160
160
  }
161
- }`),i=Ee(e,r,"uCamera"),o=Ee(e,r,"uPointSize"),s=Ee(e,r,"uPointStrokeScale"),a=Ee(e,r,"uPointInnerFillAlpha"),c=Ee(e,r,"uPalette"),u=Ee(e,r,"uPaletteSize"),l=e.createVertexArray(),d=e.createBuffer(),f=e.createBuffer(),y=e.createBuffer(),b=e.createBuffer(),w=e.createTexture();if(!l||!d||!f||!y||!b||!w)throw new Error("point buffer allocation failed");e.bindVertexArray(l),e.bindBuffer(e.ARRAY_BUFFER,d),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const x=e.getAttribLocation(r,"aPosition");if(x<0)throw new Error("point position attribute not found");e.enableVertexAttribArray(x),e.vertexAttribPointer(x,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,f),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const R=e.getAttribLocation(r,"aTerm");if(R<0)throw new Error("point term attribute not found");e.enableVertexAttribArray(R),e.vertexAttribIPointer(R,1,e.UNSIGNED_SHORT,0,0),e.bindBuffer(e.ARRAY_BUFFER,y),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const E=e.getAttribLocation(r,"aFillMode");if(E<0)throw new Error("point fill mode attribute not found");return e.enableVertexAttribArray(E),e.vertexAttribIPointer(E,1,e.UNSIGNED_BYTE,0,0),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,b),e.bufferData(e.ELEMENT_ARRAY_BUFFER,0,e.DYNAMIC_DRAW),e.bindVertexArray(null),e.bindBuffer(e.ARRAY_BUFFER,null),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null),e.bindTexture(e.TEXTURE_2D,w),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.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,new Uint8Array([160,160,160,255])),e.bindTexture(e.TEXTURE_2D,null),{program:r,vao:l,posBuffer:d,termBuffer:f,fillModeBuffer:y,indexBuffer:b,paletteTexture:w,uCamera:i,uPointSize:o,uPointStrokeScale:s,uPointInnerFillAlpha:a,uPalette:c,uPaletteSize:u}}function ci(e){e.animation=null,e.frame!==null&&(cancelAnimationFrame(e.frame),e.frame=null)}function ba(e){const{state:t,camera:n,target:r,durationMs:i,easing:o,onUpdate:s}=e,a=n.getViewState();ci(t),t.animation={startMs:fe(),durationMs:Math.max(0,i),from:a,to:r,easing:o};const c=()=>{const u=t.animation;if(!u)return;const l=Math.max(0,fe()-u.startMs),d=u.durationMs<=0?1:k(l/u.durationMs,0,1);let f=d;try{f=u.easing(d)}catch{f=d}if(Number.isFinite(f)||(f=d),f=k(f,0,1),n.setViewState({zoom:u.from.zoom+(u.to.zoom-u.from.zoom)*f,offsetX:u.from.offsetX+(u.to.offsetX-u.from.offsetX)*f,offsetY:u.from.offsetY+(u.to.offsetY-u.from.offsetY)*f,rotationDeg:u.from.rotationDeg+(u.to.rotationDeg-u.from.rotationDeg)*f}),s(),d>=1){t.animation=null,t.frame=null;return}t.frame=requestAnimationFrame(c)};t.frame=requestAnimationFrame(c)}function ya(e){const t=Math.max(e*.5,1e-6),n=Math.max(1,e*8);return{minZoom:t,maxZoom:Math.max(t,n)}}function wa(e,t,n){const r=ya(e);let i=t??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 Sa(e,t,n,r,i){const o=e.getViewState(),s={zoom:typeof r.zoom=="number"&&Number.isFinite(r.zoom)?k(r.zoom,t,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};e.setViewState(s),i();const a=e.getViewState();return e.setViewState(o),a}function xa(e,t,n,r,i){const o=Math.min(t/e.width,n/e.height),s=Number.isFinite(o)&&o>0?o:1,a=k(s,r,i),c=t/a,u=n/a;return{fitZoom:s,target:{zoom:a,offsetX:(e.width-c)*.5,offsetY:(e.height-u)*.5,rotationDeg:0}}}function Ma(e,t,n,r,i,o){const s=e.getViewState(),a=k(s.zoom*r,t,n);if(a===s.zoom)return null;const[c,u]=e.screenToWorld(i,o),l=e.getViewportSize(),d=i-l.width*.5,f=o-l.height*.5,y=ri(s.rotationDeg),b=Math.cos(y),w=Math.sin(y),x=d/a*b-f/a*w,R=d/a*w+f/a*b,E=c-x,X=u-R;return{zoom:a,offsetX:E-l.width/(2*a),offsetY:X-l.height/(2*a)}}class ui{constructor(t,n,r={}){S(this,"canvas");S(this,"source");S(this,"gl");S(this,"camera",new Pr);S(this,"onViewStateChange");S(this,"onStats");S(this,"onTileError");S(this,"onContextLost");S(this,"onContextRestored");S(this,"resizeObserver");S(this,"tileProgram");S(this,"pointProgram");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",wn);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",ii);S(this,"viewAnimationState",{animation:null,frame:null});S(this,"pointCount",0);S(this,"usePointIndices",!1);S(this,"pointBuffersDirty",!0);S(this,"pointPaletteSize",1);S(this,"pointSizeStops",Mn(xn));S(this,"pointStrokeScale",1);S(this,"pointInnerFillOpacity",0);S(this,"imageColorSettings",{brightness:0,contrast:0,saturation:0});S(this,"lastPointData",null);S(this,"lastPointPalette",null);S(this,"zeroFillModes",new Uint8Array(0));S(this,"cache",new Map);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=t,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):wn,this.pointSizeStops=wr(r.pointSizeByZoom),this.pointStrokeScale=Sr(r.pointStrokeScale),this.pointInnerFillOpacity=xr(r.pointInnerFillOpacity),this.imageColorSettings=Mr(r.imageColorSettings),this.minZoomOverride=qt(r.minZoom),this.maxZoomOverride=qt(r.maxZoom),this.viewTransitionDurationMs=dn(r.viewTransition?.duration),this.viewTransitionEasing=hn(r.viewTransition?.easing);const i=t.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=Ar(this.gl),this.pointProgram=Tr(this.gl),this.tileScheduler=new ni({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)=>ca({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,c)=>{this.onTileError?.({tile:s,error:a,attemptCount:c}),console.warn("tile load failed",s.url,a)}}),this.resizeObserver=new ResizeObserver(()=>this.resize()),this.resizeObserver.observe(t);const o=oa({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(),zoomBy:(s,a,c)=>this.zoomBy(s,a,c)});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),vs(t,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 t=wa(this.fitZoom,this.minZoomOverride,this.maxZoomOverride);this.minZoom=t.minZoom,this.maxZoom=t.maxZoom}resolveTargetViewState(t){return Sa(this.camera,this.minZoom,this.maxZoom,t,()=>An(this.camera,this.source))}cancelViewAnimation(){ci(this.viewAnimationState)}startViewAnimation(t,n,r){ba({state:this.viewAnimationState,camera:this.camera,target:t,durationMs:n,easing:r,onUpdate:()=>{An(this.camera,this.source),this.onViewStateChange?.(this.camera.getViewState()),this.requestRender()}})}getPointBufferRuntime(){return{pointCount:this.pointCount,usePointIndices:this.usePointIndices,pointBuffersDirty:this.pointBuffersDirty,lastPointData:this.lastPointData,zeroFillModes:this.zeroFillModes,lastPointPalette:this.lastPointPalette,pointPaletteSize:this.pointPaletteSize}}applyPointBufferRuntime(t){this.pointCount=t.pointCount,this.usePointIndices=t.usePointIndices,this.pointBuffersDirty=t.pointBuffersDirty,this.lastPointData=t.lastPointData,this.zeroFillModes=t.zeroFillModes,this.lastPointPalette=t.lastPointPalette,this.pointPaletteSize=t.pointPaletteSize}applyViewStateAndRender(t,n=!0){n&&this.cancelViewAnimation(),this.camera.setViewState(t),this.onViewStateChange?.(this.camera.getViewState()),this.requestRender()}setAuthToken(t){this.authToken=String(t??""),this.tileScheduler.setAuthToken(this.authToken)}setZoomRange(t,n){const r=qt(t),i=qt(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();gn(s,o)||this.applyViewStateAndRender(o)}setViewTransition(t){this.viewTransitionDurationMs=dn(t?.duration),this.viewTransitionEasing=hn(t?.easing)}setViewState(t,n){const r=this.resolveTargetViewState(t),i=this.camera.getViewState();if(gn(i,r))return;const o=dn(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}}setPointPalette(t){const n=ma(this.getPointBufferRuntime(),this.gl,this.pointProgram,this.contextLost,t);this.applyPointBufferRuntime(n),!(!t||t.length===0)&&this.requestRender()}setPointData(t){const n=ga(this.getPointBufferRuntime(),this.gl,this.pointProgram,this.contextLost,t);this.applyPointBufferRuntime(n),this.requestRender()}setInteractionLock(t){const n=!!t;this.interactionLocked!==n&&(this.interactionLocked=n,n&&this.cancelDrag())}setPointSizeByZoom(t){const n=wr(t);Ws(this.pointSizeStops,n)||(this.pointSizeStops=n,this.requestRender())}setPointStrokeScale(t){const n=Sr(t);this.pointStrokeScale!==n&&(this.pointStrokeScale=n,this.requestRender())}setPointInnerFillOpacity(t){const n=xr(t);this.pointInnerFillOpacity!==n&&(this.pointInnerFillOpacity=n,this.requestRender())}setImageColorSettings(t){const n=Mr(t),r=this.imageColorSettings;r.brightness===n.brightness&&r.contrast===n.contrast&&r.saturation===n.saturation||(this.imageColorSettings=n,this.requestRender())}cancelDrag(){ia(this.canvas,this.interactionState)}screenToWorld(t,n){const r=this.canvas.getBoundingClientRect(),i=t-r.left,o=n-r.top;return this.camera.screenToWorld(i,o)}worldToScreen(t,n){return this.camera.worldToScreen(t,n)}setViewCenter(t,n,r){if(!Number.isFinite(t)||!Number.isFinite(n))return;const i=this.camera.getViewState(),o=Math.max(1e-6,i.zoom),s=this.camera.getViewportSize();this.setViewState({offsetX:t-s.width/(2*o),offsetY:n-s.height/(2*o)},r)}getViewCorners(){return this.camera.getViewCorners()}resetRotation(t){const n=this.camera.getViewState();Math.abs(n.rotationDeg)<1e-6||this.setViewState({rotationDeg:0},t)}getPointSizeByZoom(){const t=Math.max(1e-6,this.camera.getViewState().zoom),n=this.source.maxTierZoom+Math.log2(t),r=Ys(n,this.pointSizeStops);return k(r,Sn,Bs)}fitToImage(t){const n=this.canvas.getBoundingClientRect(),r=Math.max(1,n.width||1),i=Math.max(1,n.height||1),o=xa(this.source,r,i,this.minZoom,this.maxZoom);this.fitZoom=o.fitZoom,this.applyZoomBounds(),this.setViewState(o.target,t)}zoomBy(t,n,r,i){const o=Ma(this.camera,this.minZoom,this.maxZoom,t,n,r);o&&this.setViewState(o,i)}render(){if(this.destroyed||this.contextLost||this.gl.isContextLost())return;const t=this.onStats?fe():0;this.frameSerial+=1;const n=pa({gl:this.gl,camera:this.camera,source:this.source,cache:this.cache,frameSerial:this.frameSerial,tileProgram:this.tileProgram,pointProgram:this.pointProgram,imageColorSettings:this.imageColorSettings,pointCount:this.pointCount,usePointIndices:this.usePointIndices,pointPaletteSize:this.pointPaletteSize,pointStrokeScale:this.pointStrokeScale,pointInnerFillOpacity:this.pointInnerFillOpacity,pointSizePx:this.getPointSizeByZoom(),tileScheduler:this.tileScheduler,getVisibleTiles:()=>js(this.camera,this.source),getVisibleTilesForTier:r=>ai(this.camera,this.source,r),getViewBounds:()=>_n(this.camera),intersectsBounds:Ks});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:fe()-t})}}requestRender(){this.frame!==null||this.destroyed||this.contextLost||this.gl.isContextLost()||(this.frame=requestAnimationFrame(()=>{this.frame=null,this.render()}))}resize(){Fs(this.canvas,this.gl,this.camera),this.requestRender()}onWebGlContextLost(t){const n=la({event:t,destroyed:this.destroyed,contextLost:this.contextLost,frame:this.frame,cancelViewAnimation:()=>this.cancelViewAnimation(),cancelDrag:()=>this.cancelDrag(),tileScheduler:this.tileScheduler,cache:this.cache,onContextLost:this.onContextLost});n.handled&&(this.frame=n.frame,this.contextLost=!0,this.pointBuffersDirty=!0)}onWebGlContextRestored(t){this.destroyed||(this.contextLost=!1,this.cache.clear(),this.tileProgram=Ar(this.gl),this.pointProgram=Tr(this.gl),this.pointBuffersDirty=!0,this.lastPointPalette&&this.lastPointPalette.length>0&&this.setPointPalette(this.lastPointPalette),this.lastPointData?this.setPointData(this.lastPointData):this.pointCount=0,this.resize(),this.requestRender(),this.onContextRestored?.())}destroy(){const t=fa({destroyed:this.destroyed,frame:this.frame,cancelViewAnimation:()=>this.cancelViewAnimation(),resizeObserver:this.resizeObserver,removeCanvasEventListeners:()=>_s(this.canvas,this.getCanvasHandlers()),cancelDrag:()=>this.cancelDrag(),tileScheduler:this.tileScheduler,contextLost:this.contextLost,gl:this.gl,cache:this.cache,tileProgram:this.tileProgram,pointProgram:this.pointProgram});t.didDestroy&&(this.destroyed=!0,this.frame=t.frame)}}const Aa=6;function Tn(e,t){return e.id??t}function Ta(e,t,n,r,i,o){const s=i-n,a=o-r,c=s*s+a*a;if(c<=1e-12){const b=e-n,w=t-r;return b*b+w*w}const u=k(((e-n)*s+(t-r)*a)/c,0,1),l=n+s*u,d=r+a*u,f=e-l,y=t-d;return f*f+y*y}function Rr(e,t,n,r){for(let i=1;i<n.length;i+=1){const o=n[i-1],s=n[i];if(Ta(e,t,o[0],o[1],s[0],s[1])<=r)return!0}return!1}function Ra(e,t,n,r){if(e<n.minX-r||e>n.maxX+r||t<n.minY-r||t>n.maxY+r)return!1;const i=r*r;if(Rr(e,t,n.outer,i))return!0;for(const o of n.holes)if(Rr(e,t,o,i))return!0;return!1}function Ca(e,t,n,r,i,o){if(!e.label||!e.labelAnchor)return!1;const s=jt(n.worldToScreen(e.labelAnchor[0],e.labelAnchor[1]));if(!s)return!1;const c=In(e.label,r)+r.paddingX*2,u=r.fontSize+r.paddingY*2,l=k(s[0],c*.5+1,i-c*.5-1),d=k(s[1]-r.offsetY,u*.5+1,o-u*.5-1),f=l-c*.5,y=l+c*.5,b=d-u*.5,w=d+u*.5;return t[0]>=f&&t[0]<=y&&t[1]>=b&&t[1]<=w}function Pa(e){const t=[];for(let n=0;n<e.length;n+=1){const r=e[n],i=Pt([Ct(r?.coordinates)]);if(i.length===0)continue;const o=typeof r?.label=="string"?r.label.trim():"";t.push({region:r,regionIndex:n,regionId:Tn(r,n),polygons:i,label:o,labelAnchor:o?Wr(i):null})}return t}function Ia(e,t,n,r,i,o,s,a,c){const u=e[0],l=e[1],d=Math.max(1e-6,r.getViewState().zoom),f=Math.max(0,s),y=Aa/d;for(let b=n.length-1;b>=0;b-=1){const w=n[b];for(const R of w.polygons)if(Ra(u,l,R,y))return{region:w.region,regionIndex:w.regionIndex,regionId:w.regionId};let x=Yr(i,o?.({region:w.region,regionId:w.regionId,regionIndex:w.regionIndex,zoom:d}));if(f>0&&(x={...x,offsetY:x.offsetY+f}),!!Ca(w,t,r,x,a,c))return{region:w.region,regionIndex:w.regionIndex,regionId:w.regionId}}return null}const mn=[],Ea=[],va={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)},_a=.65,Fa=4,Ba=180,Cr=20;function La(e){const t=k(e,0,1);return t*t*(3-2*t)}function Ua({source:e,viewState:t,imageColorSettings:n=null,onViewStateChange:r,onStats:i,onTileError:o,onContextLost:s,onContextRestored:a,debugOverlay:c=!1,debugOverlayStyle:u,fitNonce:l=0,rotationResetNonce:d=0,authToken:f="",ctrlDragRotate:y=!0,pointData:b=null,pointPalette:w=null,pointSizeByZoom:x,pointStrokeScale:R,pointInnerFillOpacity:E,minZoom:X,maxZoom:A,viewTransition:F,roiRegions:K,roiPolygons:oe,clipPointsToRois:Q=!1,clipMode:ee="worker",onClipStats:se,onRoiPointGroups:ge,roiPaletteIndexToTermId:Te,interactionLock:_=!1,drawTool:L="cursor",stampOptions:O,brushOptions:D,drawFillColor:V,regionStrokeStyle:Le,regionStrokeHoverStyle:Re,regionStrokeActiveStyle:Ve,patchStrokeStyle:de,resolveRegionStrokeStyle:ae,resolveRegionLabelStyle:v,overlayShapes:P,customLayers:N,patchRegions:ce,regionLabelStyle:G,drawAreaTooltip:pe,autoLiftRegionLabelAtMaxZoom:Se=!1,onPointerWorldMove:le,onPointHover:q,onPointClick:he,onRegionHover:te,onRegionClick:ue,activeRegionId:Z,onActiveRegionChange:xe,getCellByCoordinatesRef:ne,onDrawComplete:J,onPatchComplete:Ce,overviewMapConfig:we,className:Ge,style:Ue}){const ve=we?.show??!1,De=we?.options,W=h.useRef(null),Y=h.useRef(null),Me=h.useRef(null),Pe=h.useRef(null),be=h.useRef(r),Ae=h.useRef(i),tt=h.useRef(c),[It,nt]=h.useState(null),[Et,vt]=h.useState(()=>Z??null),m=Z!==void 0,g=m?Z??null:Et,[M,C]=h.useState(null),[I,me]=h.useState(null),[H,ie]=h.useState(0),$=h.useRef(null),re=h.useRef(null),ye=h.useRef(null),Ie=h.useRef(0),ke=h.useRef({rafId:null,startMs:0,from:0,to:0}),rt=h.useRef(0),He=K??mn,pt=ce??mn,bt=oe??Ea,$e=(N?.length??0)>0,li=h.useMemo(()=>({position:"relative",width:"100%",height:"100%",...Ue}),[Ue]),fi=h.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)",...u}),[u]),Ye=h.useMemo(()=>He.length>0?He:bt.length===0?mn:bt.map((p,T)=>({id:T,coordinates:p})),[He,bt]),Ze=h.useMemo(()=>Pa(Ye),[Ye]),Fn=h.useMemo(()=>En(G),[G]),lt=h.useCallback(p=>{const T=k(p,0,Cr);Math.abs(Ie.current-T)<1e-4||(Ie.current=T,ie(T))},[]),it=h.useCallback(()=>{const p=ke.current;p.rafId!==null&&(cancelAnimationFrame(p.rafId),p.rafId=null)},[]),Qt=h.useCallback(p=>{const T=k(p,0,Cr),B=ke.current,U=Ie.current;if(Math.abs(U-T)<1e-4){it(),B.to=T,lt(T);return}it(),B.startMs=performance.now(),B.from=U,B.to=T;const z=j=>{const _e=ke.current,ze=Math.max(0,j-_e.startMs),ht=k(ze/Ba,0,1),en=La(ht),tn=_e.from+(_e.to-_e.from)*en;if(lt(tn),Me.current?.(),ht>=1){_e.rafId=null,lt(_e.to);return}_e.rafId=requestAnimationFrame(z)};B.rafId=requestAnimationFrame(z)},[lt,it]),Ke=h.useCallback(p=>{const T=Y.current;if(!T||typeof p!="number"||!Number.isFinite(p)){Qt(0);return}const B=Xr(Se,p,T.getZoomRange());Qt(B)},[Se,Qt]),ot=h.useMemo(()=>Ye.map(p=>Ct(p.coordinates)).filter(p=>p!=null),[Ye]),[st,_t]=h.useState(b);h.useEffect(()=>{const p=++rt.current;let T=!1;if(!Q)return _t(b),()=>{T=!0};if(!b||!b.count||!b.positions||!b.paletteIndices)return _t(null),()=>{T=!0};if(ot.length===0)return _t(va),se?.({mode:ee,durationMs:0,inputCount:b.count,outputCount:0,polygonCount:0}),()=>{T=!0};const B=(z,j)=>{if(T||p!==rt.current)return;const _e=b.count,ze=z?.drawIndices?z.drawIndices.length:z?.count??0;_t(z),se?.({mode:j.mode,durationMs:j.durationMs,inputCount:_e,outputCount:ze,polygonCount:ot.length,usedWebGpu:j.usedWebGpu,candidateCount:j.candidateCount,bridgedToDraw:j.bridgedToDraw})};return(async()=>{if(ee==="sync"){const z=performance.now(),j=Tt(b,ot);B(j,{mode:"sync",durationMs:performance.now()-z});return}if(ee==="hybrid-webgpu"){const z=await Kr(b,ot,{bridgeToDraw:!0});B(z.data,{mode:z.meta.mode,durationMs:z.meta.durationMs,usedWebGpu:z.meta.usedWebGpu,candidateCount:z.meta.candidateCount,bridgedToDraw:z.meta.bridgedToDraw});return}try{const z=await Jr(b,ot);B(z.data,{mode:z.meta.mode,durationMs:z.meta.durationMs})}catch{const z=performance.now(),j=Tt(b,ot);B(j,{mode:"sync",durationMs:performance.now()-z})}})(),()=>{T=!0}},[Q,ee,b,ot,se]);const Bn=!!(q||he||ne),[qe,Ln]=h.useState(null);h.useEffect(()=>{if(!Bn||!st){Ln(null);return}let p=!1;return ei(st,e).then(T=>{p||Ln(T)}),()=>{p=!0}},[Bn,st,e]);const at=h.useCallback(p=>{const T=Y.current;if(!T||!qe)return null;const B=Number(p[0]),U=Number(p[1]);if(!Number.isFinite(B)||!Number.isFinite(U))return null;const z=Math.max(1e-6,T.getViewState().zoom),j=T.getPointSizeByZoom(),ze=Math.max(Fa,j*_a)/z;if(!Number.isFinite(ze)||ze<=0)return null;const{cellSize:ht,cellOffsets:en,cellLengths:tn,pointIndices:yi,positions:Wn,safeCount:wi}=qe,Yn=Math.floor(B/ht),Xn=Math.floor(U/ht),Lt=Math.max(1,Math.ceil(ze/ht)),Si=ze*ze;let Ut=-1,Vn=Si,Gn=0,qn=0;for(let nn=Yn-Lt;nn<=Yn+Lt;nn+=1)for(let rn=Xn-Lt;rn<=Xn+Lt;rn+=1){const on=Qr(qe,nn,rn);if(on<0)continue;const Hn=en[on],Mi=Hn+tn[on];for(let sn=Hn;sn<Mi;sn+=1){const Dt=yi[sn];if(Dt>=wi)continue;const $n=Wn[Dt*2],Zn=Wn[Dt*2+1],Kn=$n-B,jn=Zn-U,Jn=Kn*Kn+jn*jn;Jn>Vn||(Vn=Jn,Ut=Dt,Gn=$n,qn=Zn)}}if(Ut<0)return null;const xi=qe.ids?Number(qe.ids[Ut]):null;return{index:Ut,id:xi,coordinate:[B,U],pointCoordinate:[Gn,qn]}},[qe]),ft=h.useCallback((p,T)=>{if(!q)return;const B=p?.index??null,U=p?.id??null;re.current===B&&ye.current===U||(re.current=B,ye.current=U,q({index:B,id:U,coordinate:T,pointCoordinate:p?.pointCoordinate??null}))},[q]),Ft=h.useCallback((p,T)=>{if(!he)return;const B=at(p);B&&he({...B,button:T})},[he,at]);h.useEffect(()=>{if(ne)return ne.current=at,()=>{ne.current===at&&(ne.current=null)}},[ne,at]),h.useEffect(()=>{m&&vt(Z??null)},[m,Z]);const je=h.useCallback(p=>{String(g)!==String(p)&&(m||vt(p),xe?.(p))},[g,m,xe]);h.useEffect(()=>{be.current=r},[r]),h.useEffect(()=>{Ae.current=i},[i]),h.useEffect(()=>{tt.current=c,c||me(null)},[c]),h.useEffect(()=>()=>{it()},[it]);const Un=h.useCallback(p=>{Ae.current?.(p),tt.current&&me(p)},[]),di=h.useMemo(()=>I?[`tier ${I.tier} | frame ${I.frameMs?.toFixed(2)??"-"} ms | drawCalls ${I.drawCalls??"-"}`,`tiles visible ${I.visible} | rendered ${I.rendered} | fallback ${I.fallback}`,`cache size ${I.cache} | hit ${I.cacheHits??"-"} | miss ${I.cacheMisses??"-"}`,`queue inflight ${I.inflight} | queued ${I.queued??"-"} | retries ${I.retries??"-"} | failed ${I.failed??"-"} | aborted ${I.aborted??"-"}`,`points ${I.points}`].join(`
162
- `):"stats: waiting for first frame...",[I]);h.useEffect(()=>{!(g===null?!0:Ye.some((U,z)=>String(Tn(U,z))===String(g)))&&g!==null&&je(null);const T=$.current;!(T===null?!0:Ye.some((U,z)=>String(Tn(U,z))===String(T)))&&T!==null&&($.current=null,nt(null),te?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[Ye,g,te,je]),h.useEffect(()=>{const p=re.current;p!==null&&(qe&&p<qe.safeCount||(re.current=null,ye.current=null,q?.({index:null,id:null,coordinate:null,pointCoordinate:null})))},[qe,q]);const Dn=h.useCallback(p=>{Ke(p.zoom),$e&&C(p);const T=be.current;T&&T(p),Me.current?.(),Pe.current?.()},[$e,Ke]);h.useEffect(()=>{const p=Y.current;p&&Ke(p.getViewState().zoom)},[Ke,X,A]),h.useEffect(()=>{L!=="cursor"&&$.current!==null&&($.current=null,nt(null),te?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[L,te]),h.useEffect(()=>{L!=="cursor"&&re.current!==null&&(re.current=null,ye.current=null,q?.({index:null,id:null,coordinate:null,pointCoordinate:null}))},[L,q]);const Je=h.useCallback((p,T)=>{const B=Y.current;if(!B)return null;const U=B.screenToWorld(p,T);if(!Array.isArray(U)||U.length<2)return null;const z=Number(U[0]),j=Number(U[1]);return!Number.isFinite(z)||!Number.isFinite(j)?null:[z,j]},[]),kn=h.useCallback((p,T)=>{const B=Y.current;if(!B)return null;const U=B.worldToScreen(p,T);return jt(U)},[]),Bt=h.useCallback((p,T)=>{const B=W.current;if(!B)return null;const U=B.getBoundingClientRect();if(!Number.isFinite(U.width)||!Number.isFinite(U.height)||U.width<=0||U.height<=0)return null;const z=p-U.left,j=T-U.top;return!Number.isFinite(z)||!Number.isFinite(j)?null:{screenCoord:[z,j],canvasWidth:Math.max(1,U.width),canvasHeight:Math.max(1,U.height)}},[]),dt=h.useCallback((p,T,B,U)=>{const z=Y.current;return z?Ia(p,T,Ze,z,Fn,v,H,B,U):null},[Ze,Fn,v,H]),Nn=h.useCallback(()=>{Y.current?.requestRender(),Me.current?.(),Pe.current?.()},[]),zn=h.useMemo(()=>M??Y.current?.getViewState()??null,[M]),On=h.useMemo(()=>{if(!e)return null;const p=zn;return p?{source:e,viewState:p,drawTool:L,interactionLock:_,worldToScreen:kn,screenToWorld:Je,requestRedraw:Nn}:null},[e,zn,L,_,kn,Je,Nn]),hi=h.useCallback(p=>{const T=p.target===W.current,B=Je(p.clientX,p.clientY);if(le){const ze=!!B&&B[0]>=0&&B[1]>=0&&!!e&&B[0]<=e.width&&B[1]<=e.height;le({coordinate:B,clientX:p.clientX,clientY:p.clientY,insideImage:ze})}if(L!=="cursor")return;if(!T){ft(null,null),$.current!==null&&($.current=null,nt(null),te?.({region:null,regionId:null,regionIndex:-1,coordinate:null}));return}if(!B){ft(null,null);return}if(q&&ft(at(B),B),!Ze.length)return;const U=Bt(p.clientX,p.clientY);if(!U)return;const z=dt(B,U.screenCoord,U.canvasWidth,U.canvasHeight),j=z?.regionId??null,_e=$.current;String(_e)!==String(j)&&($.current=j,nt(j),te?.({region:z?.region??null,regionId:j,regionIndex:z?.regionIndex??-1,coordinate:B}))},[L,Ze,Je,te,le,e,ft,at,q,Bt,dt]),mi=h.useCallback(()=>{le?.({coordinate:null,clientX:-1,clientY:-1,insideImage:!1}),ft(null,null),$.current!==null&&($.current=null,nt(null),te?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[te,le,ft]),gi=h.useCallback(p=>{if(L!=="cursor"||p.target!==W.current)return;const T=Je(p.clientX,p.clientY);if(!T)return;if(Ft(T,p.button),!Ze.length){je(null);return}const B=Bt(p.clientX,p.clientY);if(!B)return;const U=dt(T,B.screenCoord,B.canvasWidth,B.canvasHeight);if(!U){je(null);return}const z=g!==null&&String(g)===String(U.regionId)?null:U.regionId;je(z),ue?.({region:U.region,regionId:U.regionId,regionIndex:U.regionIndex,coordinate:T})},[L,Ze,Je,ue,g,je,Ft,Bt,dt]),pi=h.useCallback(p=>{if(L!=="brush"||D?.clickSelectRoi!==!0||!Ze.length)return!1;const T=Y.current,B=W.current;if(!T||!B)return!1;const U=B.getBoundingClientRect();if(U.width<=0||U.height<=0)return!1;const z=jt(T.worldToScreen(p[0],p[1]));if(!z)return!1;const j=dt(p,z,U.width,U.height);if(!j)return!1;const _e=g!==null&&String(g)===String(j.regionId)?null:j.regionId;return je(_e),ue?.({region:j.region,regionId:j.regionId,regionIndex:j.regionIndex,coordinate:p}),!0},[L,D?.clickSelectRoi,Ze,g,je,ue,dt]),bi=h.useCallback(p=>{if(!he||L!=="cursor"||p.target!==W.current)return;p.preventDefault();const T=Je(p.clientX,p.clientY);T&&Ft(T,p.button)},[L,Je,Ft,he]);return h.useEffect(()=>{const p=W.current;if(!p||!e)return;const T=new ui(p,e,{onViewStateChange:Dn,onStats:Un,onTileError:o,onContextLost:s,onContextRestored:a,authToken:f,imageColorSettings:n,ctrlDragRotate:y,pointSizeByZoom:x,pointStrokeScale:R,pointInnerFillOpacity:E,minZoom:X,maxZoom:A,viewTransition:F});return Y.current=T,t&&T.setViewState(t),Ke(T.getViewState().zoom),T.setInteractionLock(_),$e&&C(T.getViewState()),()=>{it(),lt(0),T.destroy(),Y.current=null}},[e,Un,o,s,a,f,y,Dn,$e,Ke,it,lt]),h.useEffect(()=>{const p=Y.current;!p||!t||p.setViewState(t)},[t]),h.useEffect(()=>{const p=Y.current;p&&p.fitToImage()},[l]),h.useEffect(()=>{const p=Y.current;p&&p.resetRotation()},[d]),h.useEffect(()=>{const p=Y.current;!p||!w||p.setPointPalette(w)},[w]),h.useEffect(()=>{const p=Y.current;p&&p.setPointSizeByZoom(x)},[x]),h.useEffect(()=>{const p=Y.current;p&&p.setPointStrokeScale(R)},[R]),h.useEffect(()=>{const p=Y.current;p&&p.setPointInnerFillOpacity(E)},[E]),h.useEffect(()=>{const p=Y.current;p&&(p.setZoomRange(X,A),Ke(p.getViewState().zoom))},[X,A,Ke]),h.useEffect(()=>{const p=Y.current;p&&p.setViewTransition(F)},[F]),h.useEffect(()=>{const p=Y.current;p&&p.setImageColorSettings(n)},[n]),h.useEffect(()=>{const p=Y.current;p&&p.setPointData(st)},[st]),h.useEffect(()=>{if(!ge)return;const T=ti(Q?st:b,Ye,{paletteIndexToTermId:Te,includeEmptyRegions:!0});ge(T)},[ge,Q,b,st,Ye,Te]),h.useEffect(()=>{const p=Y.current;p&&p.setInteractionLock(_)},[_]),We.jsxs("div",{className:Ge,style:li,onPointerMove:hi,onPointerLeave:mi,onClick:gi,onContextMenu:bi,children:[We.jsx("canvas",{ref:W,className:"wsi-render-canvas",style:{position:"absolute",inset:0,zIndex:1,width:"100%",height:"100%",display:"block",touchAction:"none",cursor:L==="cursor"&&It!==null?"pointer":_?"crosshair":"grab"}}),e&&On&&Array.isArray(N)&&N.length>0?N.map((p,T)=>We.jsx("div",{className:p.className,style:{position:"absolute",inset:0,zIndex:p.zIndex??3,pointerEvents:p.pointerEvents??"none",...p.style},children:p.render(On)},p.id??T)):null,e?We.jsx(Vr,{tool:L,enabled:L!=="cursor",imageWidth:e.width,imageHeight:e.height,imageMpp:e.mpp,imageZoom:e.maxTierZoom,stampOptions:O,brushOptions:D,drawFillColor:V,projectorRef:Y,onBrushTap:pi,viewStateSignal:t,persistedRegions:Ye,patchRegions:pt,regionStrokeStyle:Le,regionStrokeHoverStyle:Re,regionStrokeActiveStyle:Ve,patchStrokeStyle:de,resolveRegionStrokeStyle:ae,resolveRegionLabelStyle:v,overlayShapes:P,hoveredRegionId:It,activeRegionId:g,regionLabelStyle:G,drawAreaTooltip:pe,autoLiftRegionLabelAtMaxZoom:Se,regionLabelAutoLiftOffsetPx:H,invalidateRef:Me,onDrawComplete:J,onPatchComplete:Ce}):null,c?We.jsx("pre",{"data-open-plant-debug-overlay":!0,style:fi,children:di}):null,e&&ve&&We.jsx(qr,{source:e,projectorRef:Y,authToken:f,options:De,invalidateRef:Pe,className:we?.className,style:we?.style})]})}exports.DEFAULT_POINT_COLOR=Cn;exports.DrawLayer=Vr;exports.M1TileRenderer=Ir;exports.OverviewMap=qr;exports.TileScheduler=ni;exports.TileViewerCanvas=as;exports.WsiTileRenderer=ui;exports.WsiViewerCanvas=Ua;exports.buildPointSpatialIndexAsync=ei;exports.buildTermPalette=Fi;exports.calcScaleLength=vi;exports.calcScaleResolution=Pn;exports.clamp=k;exports.closeRing=Be;exports.computeRoiPointGroups=ti;exports.createCircle=bn;exports.createRectangle=Jt;exports.filterPointDataByPolygons=Tt;exports.filterPointDataByPolygonsHybrid=Kr;exports.filterPointDataByPolygonsInWorker=Jr;exports.filterPointIndicesByPolygons=Hr;exports.filterPointIndicesByPolygonsInWorker=bs;exports.getWebGpuCapabilities=ms;exports.hexToRgba=Br;exports.isSameViewState=gn;exports.lookupCellIndex=Qr;exports.normalizeImageInfo=os;exports.prefilterPointsByBoundsWebGpu=Zr;exports.terminatePointHitIndexWorker=Rs;exports.terminateRoiClipWorker=ps;exports.toBearerToken=_i;exports.toRoiGeometry=Ct;exports.toTileUrl=vn;
161
+ }`),i=Pe(e,r,"uCamera"),o=Pe(e,r,"uPointSize"),s=Pe(e,r,"uPointStrokeScale"),a=Pe(e,r,"uPointInnerFillAlpha"),c=Pe(e,r,"uPalette"),u=Pe(e,r,"uPaletteSize"),l=e.createVertexArray(),h=e.createBuffer(),f=e.createBuffer(),y=e.createBuffer(),b=e.createBuffer(),x=e.createTexture();if(!l||!h||!f||!y||!b||!x)throw new Error("point buffer allocation failed");e.bindVertexArray(l),e.bindBuffer(e.ARRAY_BUFFER,h),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const w=e.getAttribLocation(r,"aPosition");if(w<0)throw new Error("point position attribute not found");e.enableVertexAttribArray(w),e.vertexAttribPointer(w,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,f),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const A=e.getAttribLocation(r,"aTerm");if(A<0)throw new Error("point term attribute not found");e.enableVertexAttribArray(A),e.vertexAttribIPointer(A,1,e.UNSIGNED_SHORT,0,0),e.bindBuffer(e.ARRAY_BUFFER,y),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const E=e.getAttribLocation(r,"aFillMode");if(E<0)throw new Error("point fill mode attribute not found");return e.enableVertexAttribArray(E),e.vertexAttribIPointer(E,1,e.UNSIGNED_BYTE,0,0),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,b),e.bufferData(e.ELEMENT_ARRAY_BUFFER,0,e.DYNAMIC_DRAW),e.bindVertexArray(null),e.bindBuffer(e.ARRAY_BUFFER,null),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null),e.bindTexture(e.TEXTURE_2D,x),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.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,new Uint8Array([160,160,160,255])),e.bindTexture(e.TEXTURE_2D,null),{program:r,vao:l,posBuffer:h,termBuffer:f,fillModeBuffer:y,indexBuffer:b,paletteTexture:x,uCamera:i,uPointSize:o,uPointStrokeScale:s,uPointInnerFillAlpha:a,uPalette:c,uPaletteSize:u}}function li(e){e.animation=null,e.frame!==null&&(cancelAnimationFrame(e.frame),e.frame=null)}function wa(e){const{state:t,camera:n,target:r,durationMs:i,easing:o,onUpdate:s}=e,a=n.getViewState();li(t),t.animation={startMs:fe(),durationMs:Math.max(0,i),from:a,to:r,easing:o};const c=()=>{const u=t.animation;if(!u)return;const l=Math.max(0,fe()-u.startMs),h=u.durationMs<=0?1:k(l/u.durationMs,0,1);let f=h;try{f=u.easing(h)}catch{f=h}if(Number.isFinite(f)||(f=h),f=k(f,0,1),n.setViewState({zoom:u.from.zoom+(u.to.zoom-u.from.zoom)*f,offsetX:u.from.offsetX+(u.to.offsetX-u.from.offsetX)*f,offsetY:u.from.offsetY+(u.to.offsetY-u.from.offsetY)*f,rotationDeg:u.from.rotationDeg+(u.to.rotationDeg-u.from.rotationDeg)*f}),s(),h>=1){t.animation=null,t.frame=null;return}t.frame=requestAnimationFrame(c)};t.frame=requestAnimationFrame(c)}function Sa(e){const t=Math.max(e*.5,1e-6),n=Math.max(1,e*8);return{minZoom:t,maxZoom:Math.max(t,n)}}function xa(e,t,n){const r=Sa(e);let i=t??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 Ma(e,t,n,r,i){const o=e.getViewState(),s={zoom:typeof r.zoom=="number"&&Number.isFinite(r.zoom)?k(r.zoom,t,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};e.setViewState(s),i();const a=e.getViewState();return e.setViewState(o),a}function Aa(e,t,n,r,i){const o=Math.min(t/e.width,n/e.height),s=Number.isFinite(o)&&o>0?o:1,a=k(s,r,i),c=t/a,u=n/a;return{fitZoom:s,target:{zoom:a,offsetX:(e.width-c)*.5,offsetY:(e.height-u)*.5,rotationDeg:0}}}function Ta(e,t,n,r,i,o){const s=e.getViewState(),a=k(s.zoom*r,t,n);if(a===s.zoom)return null;const[c,u]=e.screenToWorld(i,o),l=e.getViewportSize(),h=i-l.width*.5,f=o-l.height*.5,y=oi(s.rotationDeg),b=Math.cos(y),x=Math.sin(y),w=h/a*b-f/a*x,A=h/a*x+f/a*b,E=c-w,X=u-A;return{zoom:a,offsetX:E-l.width/(2*a),offsetY:X-l.height/(2*a)}}class fi{constructor(t,n,r={}){S(this,"canvas");S(this,"source");S(this,"gl");S(this,"camera",new Er);S(this,"onViewStateChange");S(this,"onStats");S(this,"onTileError");S(this,"onContextLost");S(this,"onContextRestored");S(this,"resizeObserver");S(this,"tileProgram");S(this,"pointProgram");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",xn);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",si);S(this,"viewAnimationState",{animation:null,frame:null});S(this,"pointCount",0);S(this,"usePointIndices",!1);S(this,"pointBuffersDirty",!0);S(this,"pointPaletteSize",1);S(this,"pointSizeStops",Tn(An));S(this,"pointStrokeScale",1);S(this,"pointInnerFillOpacity",0);S(this,"imageColorSettings",{brightness:0,contrast:0,saturation:0});S(this,"lastPointData",null);S(this,"lastPointPalette",null);S(this,"zeroFillModes",new Uint8Array(0));S(this,"cache",new Map);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=t,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):xn,this.pointSizeStops=xr(r.pointSizeByZoom),this.pointStrokeScale=Mr(r.pointStrokeScale),this.pointInnerFillOpacity=Ar(r.pointInnerFillOpacity),this.imageColorSettings=Tr(r.imageColorSettings),this.minZoomOverride=$t(r.minZoom),this.maxZoomOverride=$t(r.maxZoom),this.viewTransitionDurationMs=mn(r.viewTransition?.duration),this.viewTransitionEasing=gn(r.viewTransition?.easing);const i=t.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=Rr(this.gl),this.pointProgram=Cr(this.gl),this.tileScheduler=new ii({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)=>la({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,c)=>{this.onTileError?.({tile:s,error:a,attemptCount:c}),console.warn("tile load failed",s.url,a)}}),this.resizeObserver=new ResizeObserver(()=>this.resize()),this.resizeObserver.observe(t);const o=aa({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(),zoomBy:(s,a,c)=>this.zoomBy(s,a,c)});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),Fs(t,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 t=xa(this.fitZoom,this.minZoomOverride,this.maxZoomOverride);this.minZoom=t.minZoom,this.maxZoom=t.maxZoom}resolveTargetViewState(t){return Ma(this.camera,this.minZoom,this.maxZoom,t,()=>Rn(this.camera,this.source))}cancelViewAnimation(){li(this.viewAnimationState)}startViewAnimation(t,n,r){wa({state:this.viewAnimationState,camera:this.camera,target:t,durationMs:n,easing:r,onUpdate:()=>{Rn(this.camera,this.source),this.onViewStateChange?.(this.camera.getViewState()),this.requestRender()}})}getPointBufferRuntime(){return{pointCount:this.pointCount,usePointIndices:this.usePointIndices,pointBuffersDirty:this.pointBuffersDirty,lastPointData:this.lastPointData,zeroFillModes:this.zeroFillModes,lastPointPalette:this.lastPointPalette,pointPaletteSize:this.pointPaletteSize}}applyPointBufferRuntime(t){this.pointCount=t.pointCount,this.usePointIndices=t.usePointIndices,this.pointBuffersDirty=t.pointBuffersDirty,this.lastPointData=t.lastPointData,this.zeroFillModes=t.zeroFillModes,this.lastPointPalette=t.lastPointPalette,this.pointPaletteSize=t.pointPaletteSize}applyViewStateAndRender(t,n=!0){n&&this.cancelViewAnimation(),this.camera.setViewState(t),this.onViewStateChange?.(this.camera.getViewState()),this.requestRender()}setAuthToken(t){this.authToken=String(t??""),this.tileScheduler.setAuthToken(this.authToken)}setZoomRange(t,n){const r=$t(t),i=$t(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();bn(s,o)||this.applyViewStateAndRender(o)}setViewTransition(t){this.viewTransitionDurationMs=mn(t?.duration),this.viewTransitionEasing=gn(t?.easing)}setViewState(t,n){const r=this.resolveTargetViewState(t),i=this.camera.getViewState();if(bn(i,r))return;const o=mn(n?.duration??this.viewTransitionDurationMs),s=gn(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}}setPointPalette(t){const n=pa(this.getPointBufferRuntime(),this.gl,this.pointProgram,this.contextLost,t);this.applyPointBufferRuntime(n),!(!t||t.length===0)&&this.requestRender()}setPointData(t){const n=ba(this.getPointBufferRuntime(),this.gl,this.pointProgram,this.contextLost,t);this.applyPointBufferRuntime(n),this.requestRender()}setInteractionLock(t){const n=!!t;this.interactionLocked!==n&&(this.interactionLocked=n,n&&this.cancelDrag())}setPointSizeByZoom(t){const n=xr(t);Xs(this.pointSizeStops,n)||(this.pointSizeStops=n,this.requestRender())}setPointStrokeScale(t){const n=Mr(t);this.pointStrokeScale!==n&&(this.pointStrokeScale=n,this.requestRender())}setPointInnerFillOpacity(t){const n=Ar(t);this.pointInnerFillOpacity!==n&&(this.pointInnerFillOpacity=n,this.requestRender())}setImageColorSettings(t){const n=Tr(t),r=this.imageColorSettings;r.brightness===n.brightness&&r.contrast===n.contrast&&r.saturation===n.saturation||(this.imageColorSettings=n,this.requestRender())}cancelDrag(){sa(this.canvas,this.interactionState)}screenToWorld(t,n){const r=this.canvas.getBoundingClientRect(),i=t-r.left,o=n-r.top;return this.camera.screenToWorld(i,o)}worldToScreen(t,n){return this.camera.worldToScreen(t,n)}setViewCenter(t,n,r){if(!Number.isFinite(t)||!Number.isFinite(n))return;const i=this.camera.getViewState(),o=Math.max(1e-6,i.zoom),s=this.camera.getViewportSize();this.setViewState({offsetX:t-s.width/(2*o),offsetY:n-s.height/(2*o)},r)}getViewCorners(){return this.camera.getViewCorners()}resetRotation(t){const n=this.camera.getViewState();Math.abs(n.rotationDeg)<1e-6||this.setViewState({rotationDeg:0},t)}getPointSizeByZoom(){const t=Math.max(1e-6,this.camera.getViewState().zoom),n=this.source.maxTierZoom+Math.log2(t),r=Vs(n,this.pointSizeStops);return k(r,Mn,Ls)}fitToImage(t){const n=this.canvas.getBoundingClientRect(),r=Math.max(1,n.width||1),i=Math.max(1,n.height||1),o=Aa(this.source,r,i,this.minZoom,this.maxZoom);this.fitZoom=o.fitZoom,this.applyZoomBounds(),this.setViewState(o.target,t)}zoomBy(t,n,r,i){const o=Ta(this.camera,this.minZoom,this.maxZoom,t,n,r);o&&this.setViewState(o,i)}render(){if(this.destroyed||this.contextLost||this.gl.isContextLost())return;const t=this.onStats?fe():0;this.frameSerial+=1;const n=ya({gl:this.gl,camera:this.camera,source:this.source,cache:this.cache,frameSerial:this.frameSerial,tileProgram:this.tileProgram,pointProgram:this.pointProgram,imageColorSettings:this.imageColorSettings,pointCount:this.pointCount,usePointIndices:this.usePointIndices,pointPaletteSize:this.pointPaletteSize,pointStrokeScale:this.pointStrokeScale,pointInnerFillOpacity:this.pointInnerFillOpacity,pointSizePx:this.getPointSizeByZoom(),tileScheduler:this.tileScheduler,getVisibleTiles:()=>Qs(this.camera,this.source),getVisibleTilesForTier:r=>ui(this.camera,this.source,r),getViewBounds:()=>Bn(this.camera),intersectsBounds:Js});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:fe()-t})}}requestRender(){this.frame!==null||this.destroyed||this.contextLost||this.gl.isContextLost()||(this.frame=requestAnimationFrame(()=>{this.frame=null,this.render()}))}resize(){Us(this.canvas,this.gl,this.camera),this.requestRender()}onWebGlContextLost(t){const n=da({event:t,destroyed:this.destroyed,contextLost:this.contextLost,frame:this.frame,cancelViewAnimation:()=>this.cancelViewAnimation(),cancelDrag:()=>this.cancelDrag(),tileScheduler:this.tileScheduler,cache:this.cache,onContextLost:this.onContextLost});n.handled&&(this.frame=n.frame,this.contextLost=!0,this.pointBuffersDirty=!0)}onWebGlContextRestored(t){this.destroyed||(this.contextLost=!1,this.cache.clear(),this.tileProgram=Rr(this.gl),this.pointProgram=Cr(this.gl),this.pointBuffersDirty=!0,this.lastPointPalette&&this.lastPointPalette.length>0&&this.setPointPalette(this.lastPointPalette),this.lastPointData?this.setPointData(this.lastPointData):this.pointCount=0,this.resize(),this.requestRender(),this.onContextRestored?.())}destroy(){const t=ha({destroyed:this.destroyed,frame:this.frame,cancelViewAnimation:()=>this.cancelViewAnimation(),resizeObserver:this.resizeObserver,removeCanvasEventListeners:()=>Bs(this.canvas,this.getCanvasHandlers()),cancelDrag:()=>this.cancelDrag(),tileScheduler:this.tileScheduler,contextLost:this.contextLost,gl:this.gl,cache:this.cache,tileProgram:this.tileProgram,pointProgram:this.pointProgram});t.didDestroy&&(this.destroyed=!0,this.frame=t.frame)}}const Ra=6;function Cn(e,t){return e.id??t}function Ca(e,t,n,r,i,o){const s=i-n,a=o-r,c=s*s+a*a;if(c<=1e-12){const b=e-n,x=t-r;return b*b+x*x}const u=k(((e-n)*s+(t-r)*a)/c,0,1),l=n+s*u,h=r+a*u,f=e-l,y=t-h;return f*f+y*y}function Pr(e,t,n,r){for(let i=1;i<n.length;i+=1){const o=n[i-1],s=n[i];if(Ca(e,t,o[0],o[1],s[0],s[1])<=r)return!0}return!1}function Pa(e,t,n,r){if(e<n.minX-r||e>n.maxX+r||t<n.minY-r||t>n.maxY+r)return!1;const i=r*r;if(Pr(e,t,n.outer,i))return!0;for(const o of n.holes)if(Pr(e,t,o,i))return!0;return!1}function Ia(e,t,n,r,i,o,s){if(!e.label||!e.labelAnchor)return!1;const a=Qt(n.worldToScreen(e.labelAnchor[0],e.labelAnchor[1]));if(!a)return!1;const u=vn(e.label,r)+r.paddingX*2,l=r.fontSize+r.paddingY*2,h=a[0],f=a[1]-r.offsetY,y=s?k(h,u*.5+1,i-u*.5-1):h,b=s?k(f,l*.5+1,o-l*.5-1):f,x=y-u*.5,w=y+u*.5,A=b-l*.5,E=b+l*.5;return t[0]>=x&&t[0]<=w&&t[1]>=A&&t[1]<=E}function Ea(e,t="top-center"){const n=[];for(let r=0;r<e.length;r+=1){const i=e[r],o=Et([It(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?Xr(o,t):null})}return n}function va(e,t,n,r,i,o,s,a,c,u=!0){const l=e[0],h=e[1],f=Math.max(1e-6,r.getViewState().zoom),y=Math.max(0,s),b=Ra/f;for(let x=n.length-1;x>=0;x-=1){const w=n[x];for(const E of w.polygons)if(Pa(l,h,E,b))return{region:w.region,regionIndex:w.regionIndex,regionId:w.regionId};let A=Vr(i,o?.({region:w.region,regionId:w.regionId,regionIndex:w.regionIndex,zoom:f}));if(y>0&&(A={...A,offsetY:A.offsetY+y}),!!Ia(w,t,r,A,a,c,u))return{region:w.region,regionIndex:w.regionIndex,regionId:w.regionId}}return null}const pn=[],_a=[],Fa={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)},Ba=.65,Ua=4,La=180,Ir=20;function Da(e){const t=k(e,0,1);return t*t*(3-2*t)}function ka({source:e,viewState:t,imageColorSettings:n=null,onViewStateChange:r,onStats:i,onTileError:o,onContextLost:s,onContextRestored:a,debugOverlay:c=!1,debugOverlayStyle:u,fitNonce:l=0,rotationResetNonce:h=0,authToken:f="",ctrlDragRotate:y=!0,pointData:b=null,pointPalette:x=null,pointSizeByZoom:w,pointStrokeScale:A,pointInnerFillOpacity:E,minZoom:X,maxZoom:R,viewTransition:_,roiRegions:H,roiPolygons:se,clipPointsToRois:j=!1,clipMode:J="worker",onClipStats:ae,onRoiPointGroups:ge,roiPaletteIndexToTermId:Te,interactionLock:B=!1,drawTool:D="cursor",stampOptions:O,brushOptions:U,drawFillColor:Q,regionStrokeStyle:Le,regionStrokeHoverStyle:ue,regionStrokeActiveStyle:Oe,patchStrokeStyle:Fe,resolveRegionStrokeStyle:We,resolveRegionLabelStyle:C,overlayShapes:M,customLayers:z,patchRegions:ce,regionLabelStyle:$,regionLabelAnchor:le="top-center",drawAreaTooltip:de,autoLiftRegionLabelAtMaxZoom:ye=!1,clampRegionLabelToViewport:ee=!0,onPointerWorldMove:he,onPointHover:re,onPointClick:ne,onRegionHover:K,onRegionClick:xe,activeRegionId:G,onActiveRegionChange:we,getCellByCoordinatesRef:pe,onDrawComplete:Se,onPatchComplete:De,overviewMapConfig:Ae,className:Ie,style:Re}){const ct=Ae?.show??!1,ut=Ae?.options,W=d.useRef(null),Y=d.useRef(null),ie=d.useRef(null),be=d.useRef(null),pt=d.useRef(r),bt=d.useRef(i),Qe=d.useRef(c),[vt,et]=d.useState(null),[_t,Ft]=d.useState(()=>G??null),m=G!==void 0,g=m?G??null:_t,[T,I]=d.useState(null),[v,me]=d.useState(null),[V,oe]=d.useState(0),q=d.useRef(null),te=d.useRef(null),Me=d.useRef(null),Ce=d.useRef(0),Be=d.useRef({rafId:null,startMs:0,from:0,to:0}),tt=d.useRef(0),Ge=H??pn,yt=ce??pn,wt=se??_a,qe=(z?.length??0)>0,di=d.useMemo(()=>({position:"relative",width:"100%",height:"100%",...Re}),[Re]),hi=d.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)",...u}),[u]),Ye=d.useMemo(()=>Ge.length>0?Ge:wt.length===0?pn:wt.map((p,P)=>({id:P,coordinates:p})),[Ge,wt]),He=d.useMemo(()=>Ea(Ye,le),[Ye,le]),Un=d.useMemo(()=>_n($),[$]),lt=d.useCallback(p=>{const P=k(p,0,Ir);Math.abs(Ce.current-P)<1e-4||(Ce.current=P,oe(P))},[]),nt=d.useCallback(()=>{const p=Be.current;p.rafId!==null&&(cancelAnimationFrame(p.rafId),p.rafId=null)},[]),tn=d.useCallback(p=>{const P=k(p,0,Ir),F=Be.current,L=Ce.current;if(Math.abs(L-P)<1e-4){nt(),F.to=P,lt(P);return}nt(),F.startMs=performance.now(),F.from=L,F.to=P;const N=Z=>{const Ee=Be.current,ke=Math.max(0,Z-Ee.startMs),ht=k(ke/La,0,1),nn=Da(ht),rn=Ee.from+(Ee.to-Ee.from)*nn;if(lt(rn),ie.current?.(),ht>=1){Ee.rafId=null,lt(Ee.to);return}Ee.rafId=requestAnimationFrame(N)};F.rafId=requestAnimationFrame(N)},[lt,nt]),$e=d.useCallback(p=>{const P=Y.current;if(!P||typeof p!="number"||!Number.isFinite(p)){tn(0);return}const F=Gr(ye,p,P.getZoomRange());tn(F)},[ye,tn]),rt=d.useMemo(()=>Ye.map(p=>It(p.coordinates)).filter(p=>p!=null),[Ye]),[it,Bt]=d.useState(b);d.useEffect(()=>{const p=++tt.current;let P=!1;if(!j)return Bt(b),()=>{P=!0};if(!b||!b.count||!b.positions||!b.paletteIndices)return Bt(null),()=>{P=!0};if(rt.length===0)return Bt(Fa),ae?.({mode:J,durationMs:0,inputCount:b.count,outputCount:0,polygonCount:0}),()=>{P=!0};const F=(N,Z)=>{if(P||p!==tt.current)return;const Ee=b.count,ke=N?.drawIndices?N.drawIndices.length:N?.count??0;Bt(N),ae?.({mode:Z.mode,durationMs:Z.durationMs,inputCount:Ee,outputCount:ke,polygonCount:rt.length,usedWebGpu:Z.usedWebGpu,candidateCount:Z.candidateCount,bridgedToDraw:Z.bridgedToDraw})};return(async()=>{if(J==="sync"){const N=performance.now(),Z=Ct(b,rt);F(Z,{mode:"sync",durationMs:performance.now()-N});return}if(J==="hybrid-webgpu"){const N=await Jr(b,rt,{bridgeToDraw:!0});F(N.data,{mode:N.meta.mode,durationMs:N.meta.durationMs,usedWebGpu:N.meta.usedWebGpu,candidateCount:N.meta.candidateCount,bridgedToDraw:N.meta.bridgedToDraw});return}try{const N=await ei(b,rt);F(N.data,{mode:N.meta.mode,durationMs:N.meta.durationMs})}catch{const N=performance.now(),Z=Ct(b,rt);F(Z,{mode:"sync",durationMs:performance.now()-N})}})(),()=>{P=!0}},[j,J,b,rt,ae]);const Ln=!!(re||ne||pe),[Ve,Dn]=d.useState(null);d.useEffect(()=>{if(!Ln||!it){Dn(null);return}let p=!1;return ni(it,e).then(P=>{p||Dn(P)}),()=>{p=!0}},[Ln,it,e]);const ot=d.useCallback(p=>{const P=Y.current;if(!P||!Ve)return null;const F=Number(p[0]),L=Number(p[1]);if(!Number.isFinite(F)||!Number.isFinite(L))return null;const N=Math.max(1e-6,P.getViewState().zoom),Z=P.getPointSizeByZoom(),ke=Math.max(Ua,Z*Ba)/N;if(!Number.isFinite(ke)||ke<=0)return null;const{cellSize:ht,cellOffsets:nn,cellLengths:rn,pointIndices:Si,positions:Xn,safeCount:xi}=Ve,Vn=Math.floor(F/ht),Gn=Math.floor(L/ht),Dt=Math.max(1,Math.ceil(ke/ht)),Mi=ke*ke;let kt=-1,qn=Mi,Hn=0,$n=0;for(let on=Vn-Dt;on<=Vn+Dt;on+=1)for(let sn=Gn-Dt;sn<=Gn+Dt;sn+=1){const an=ti(Ve,on,sn);if(an<0)continue;const Zn=nn[an],Ti=Zn+rn[an];for(let cn=Zn;cn<Ti;cn+=1){const Nt=Si[cn];if(Nt>=xi)continue;const Kn=Xn[Nt*2],jn=Xn[Nt*2+1],Jn=Kn-F,Qn=jn-L,er=Jn*Jn+Qn*Qn;er>qn||(qn=er,kt=Nt,Hn=Kn,$n=jn)}}if(kt<0)return null;const Ai=Ve.ids?Number(Ve.ids[kt]):null;return{index:kt,id:Ai,coordinate:[F,L],pointCoordinate:[Hn,$n]}},[Ve]),ft=d.useCallback((p,P)=>{if(!re)return;const F=p?.index??null,L=p?.id??null;te.current===F&&Me.current===L||(te.current=F,Me.current=L,re({index:F,id:L,coordinate:P,pointCoordinate:p?.pointCoordinate??null}))},[re]),Ut=d.useCallback((p,P)=>{if(!ne)return;const F=ot(p);F&&ne({...F,button:P})},[ne,ot]);d.useEffect(()=>{if(pe)return pe.current=ot,()=>{pe.current===ot&&(pe.current=null)}},[pe,ot]),d.useEffect(()=>{m&&Ft(G??null)},[m,G]);const Ze=d.useCallback(p=>{String(g)!==String(p)&&(m||Ft(p),we?.(p))},[g,m,we]);d.useEffect(()=>{pt.current=r},[r]),d.useEffect(()=>{bt.current=i},[i]),d.useEffect(()=>{Qe.current=c,c||me(null)},[c]),d.useEffect(()=>()=>{nt()},[nt]);const kn=d.useCallback(p=>{bt.current?.(p),Qe.current&&me(p)},[]),mi=d.useMemo(()=>v?[`tier ${v.tier} | frame ${v.frameMs?.toFixed(2)??"-"} ms | drawCalls ${v.drawCalls??"-"}`,`tiles visible ${v.visible} | rendered ${v.rendered} | fallback ${v.fallback}`,`cache size ${v.cache} | hit ${v.cacheHits??"-"} | miss ${v.cacheMisses??"-"}`,`queue inflight ${v.inflight} | queued ${v.queued??"-"} | retries ${v.retries??"-"} | failed ${v.failed??"-"} | aborted ${v.aborted??"-"}`,`points ${v.points}`].join(`
162
+ `):"stats: waiting for first frame...",[v]);d.useEffect(()=>{!(g===null?!0:Ye.some((L,N)=>String(Cn(L,N))===String(g)))&&g!==null&&Ze(null);const P=q.current;!(P===null?!0:Ye.some((L,N)=>String(Cn(L,N))===String(P)))&&P!==null&&(q.current=null,et(null),K?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[Ye,g,K,Ze]),d.useEffect(()=>{const p=te.current;p!==null&&(Ve&&p<Ve.safeCount||(te.current=null,Me.current=null,re?.({index:null,id:null,coordinate:null,pointCoordinate:null})))},[Ve,re]);const Nn=d.useCallback(p=>{$e(p.zoom),qe&&I(p);const P=pt.current;P&&P(p),ie.current?.(),be.current?.()},[qe,$e]);d.useEffect(()=>{const p=Y.current;p&&$e(p.getViewState().zoom)},[$e,X,R]),d.useEffect(()=>{D!=="cursor"&&q.current!==null&&(q.current=null,et(null),K?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[D,K]),d.useEffect(()=>{D!=="cursor"&&te.current!==null&&(te.current=null,Me.current=null,re?.({index:null,id:null,coordinate:null,pointCoordinate:null}))},[D,re]);const Ke=d.useCallback((p,P)=>{const F=Y.current;if(!F)return null;const L=F.screenToWorld(p,P);if(!Array.isArray(L)||L.length<2)return null;const N=Number(L[0]),Z=Number(L[1]);return!Number.isFinite(N)||!Number.isFinite(Z)?null:[N,Z]},[]),zn=d.useCallback((p,P)=>{const F=Y.current;if(!F)return null;const L=F.worldToScreen(p,P);return Qt(L)},[]),Lt=d.useCallback((p,P)=>{const F=W.current;if(!F)return null;const L=F.getBoundingClientRect();if(!Number.isFinite(L.width)||!Number.isFinite(L.height)||L.width<=0||L.height<=0)return null;const N=p-L.left,Z=P-L.top;return!Number.isFinite(N)||!Number.isFinite(Z)?null:{screenCoord:[N,Z],canvasWidth:Math.max(1,L.width),canvasHeight:Math.max(1,L.height)}},[]),dt=d.useCallback((p,P,F,L)=>{const N=Y.current;return N?va(p,P,He,N,Un,C,V,F,L,ee):null},[He,Un,C,V,ee]),On=d.useCallback(()=>{Y.current?.requestRender(),ie.current?.(),be.current?.()},[]),Wn=d.useMemo(()=>T??Y.current?.getViewState()??null,[T]),Yn=d.useMemo(()=>{if(!e)return null;const p=Wn;return p?{source:e,viewState:p,drawTool:D,interactionLock:B,worldToScreen:zn,screenToWorld:Ke,requestRedraw:On}:null},[e,Wn,D,B,zn,Ke,On]),gi=d.useCallback(p=>{const P=p.target===W.current,F=Ke(p.clientX,p.clientY);if(he){const ke=!!F&&F[0]>=0&&F[1]>=0&&!!e&&F[0]<=e.width&&F[1]<=e.height;he({coordinate:F,clientX:p.clientX,clientY:p.clientY,insideImage:ke})}if(D!=="cursor")return;if(!P){ft(null,null),q.current!==null&&(q.current=null,et(null),K?.({region:null,regionId:null,regionIndex:-1,coordinate:null}));return}if(!F){ft(null,null);return}if(re&&ft(ot(F),F),!He.length)return;const L=Lt(p.clientX,p.clientY);if(!L)return;const N=dt(F,L.screenCoord,L.canvasWidth,L.canvasHeight),Z=N?.regionId??null,Ee=q.current;String(Ee)!==String(Z)&&(q.current=Z,et(Z),K?.({region:N?.region??null,regionId:Z,regionIndex:N?.regionIndex??-1,coordinate:F}))},[D,He,Ke,K,he,e,ft,ot,re,Lt,dt]),pi=d.useCallback(()=>{he?.({coordinate:null,clientX:-1,clientY:-1,insideImage:!1}),ft(null,null),q.current!==null&&(q.current=null,et(null),K?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[K,he,ft]),bi=d.useCallback(p=>{if(D!=="cursor"||p.target!==W.current)return;const P=Ke(p.clientX,p.clientY);if(!P)return;if(Ut(P,p.button),!He.length){Ze(null);return}const F=Lt(p.clientX,p.clientY);if(!F)return;const L=dt(P,F.screenCoord,F.canvasWidth,F.canvasHeight);if(!L){Ze(null);return}const N=g!==null&&String(g)===String(L.regionId)?null:L.regionId;Ze(N),xe?.({region:L.region,regionId:L.regionId,regionIndex:L.regionIndex,coordinate:P})},[D,He,Ke,xe,g,Ze,Ut,Lt,dt]),yi=d.useCallback(p=>{if(D!=="brush"||U?.clickSelectRoi!==!0||!He.length)return!1;const P=Y.current,F=W.current;if(!P||!F)return!1;const L=F.getBoundingClientRect();if(L.width<=0||L.height<=0)return!1;const N=Qt(P.worldToScreen(p[0],p[1]));if(!N)return!1;const Z=dt(p,N,L.width,L.height);if(!Z)return!1;const Ee=g!==null&&String(g)===String(Z.regionId)?null:Z.regionId;return Ze(Ee),xe?.({region:Z.region,regionId:Z.regionId,regionIndex:Z.regionIndex,coordinate:p}),!0},[D,U?.clickSelectRoi,He,g,Ze,xe,dt]),wi=d.useCallback(p=>{if(!ne||D!=="cursor"||p.target!==W.current)return;p.preventDefault();const P=Ke(p.clientX,p.clientY);P&&Ut(P,p.button)},[D,Ke,Ut,ne]);return d.useEffect(()=>{const p=W.current;if(!p||!e)return;const P=new fi(p,e,{onViewStateChange:Nn,onStats:kn,onTileError:o,onContextLost:s,onContextRestored:a,authToken:f,imageColorSettings:n,ctrlDragRotate:y,pointSizeByZoom:w,pointStrokeScale:A,pointInnerFillOpacity:E,minZoom:X,maxZoom:R,viewTransition:_});return Y.current=P,t&&P.setViewState(t),$e(P.getViewState().zoom),P.setInteractionLock(B),qe&&I(P.getViewState()),()=>{nt(),lt(0),P.destroy(),Y.current=null}},[e,kn,o,s,a,f,y,Nn,qe,$e,nt,lt]),d.useEffect(()=>{const p=Y.current;!p||!t||p.setViewState(t)},[t]),d.useEffect(()=>{const p=Y.current;p&&p.fitToImage()},[l]),d.useEffect(()=>{const p=Y.current;p&&p.resetRotation()},[h]),d.useEffect(()=>{const p=Y.current;!p||!x||p.setPointPalette(x)},[x]),d.useEffect(()=>{const p=Y.current;p&&p.setPointSizeByZoom(w)},[w]),d.useEffect(()=>{const p=Y.current;p&&p.setPointStrokeScale(A)},[A]),d.useEffect(()=>{const p=Y.current;p&&p.setPointInnerFillOpacity(E)},[E]),d.useEffect(()=>{const p=Y.current;p&&(p.setZoomRange(X,R),$e(p.getViewState().zoom))},[X,R,$e]),d.useEffect(()=>{const p=Y.current;p&&p.setViewTransition(_)},[_]),d.useEffect(()=>{const p=Y.current;p&&p.setImageColorSettings(n)},[n]),d.useEffect(()=>{const p=Y.current;p&&p.setPointData(it)},[it]),d.useEffect(()=>{if(!ge)return;const P=ri(j?it:b,Ye,{paletteIndexToTermId:Te,includeEmptyRegions:!0});ge(P)},[ge,j,b,it,Ye,Te]),d.useEffect(()=>{const p=Y.current;p&&p.setInteractionLock(B)},[B]),ze.jsxs("div",{className:Ie,style:di,onPointerMove:gi,onPointerLeave:pi,onClick:bi,onContextMenu:wi,children:[ze.jsx("canvas",{ref:W,className:"wsi-render-canvas",style:{position:"absolute",inset:0,zIndex:1,width:"100%",height:"100%",display:"block",touchAction:"none",cursor:D==="cursor"&&vt!==null?"pointer":B?"crosshair":"grab"}}),e&&Yn&&Array.isArray(z)&&z.length>0?z.map((p,P)=>ze.jsx("div",{className:p.className,style:{position:"absolute",inset:0,zIndex:p.zIndex??3,pointerEvents:p.pointerEvents??"none",...p.style},children:p.render(Yn)},p.id??P)):null,e?ze.jsx(qr,{tool:D,enabled:D!=="cursor",imageWidth:e.width,imageHeight:e.height,imageMpp:e.mpp,imageZoom:e.maxTierZoom,stampOptions:O,brushOptions:U,drawFillColor:Q,projectorRef:Y,onBrushTap:yi,viewStateSignal:t,persistedRegions:Ye,patchRegions:yt,regionStrokeStyle:Le,regionStrokeHoverStyle:ue,regionStrokeActiveStyle:Oe,patchStrokeStyle:Fe,resolveRegionStrokeStyle:We,resolveRegionLabelStyle:C,overlayShapes:M,hoveredRegionId:vt,activeRegionId:g,regionLabelStyle:$,regionLabelAnchor:le,drawAreaTooltip:de,autoLiftRegionLabelAtMaxZoom:ye,clampRegionLabelToViewport:ee,regionLabelAutoLiftOffsetPx:V,invalidateRef:ie,onDrawComplete:Se,onPatchComplete:De}):null,c?ze.jsx("pre",{"data-open-plant-debug-overlay":!0,style:hi,children:mi}):null,e&&ct&&ze.jsx($r,{source:e,projectorRef:Y,authToken:f,options:ut,invalidateRef:be,className:Ae?.className,style:Ae?.style})]})}exports.DEFAULT_POINT_COLOR=In;exports.DrawLayer=qr;exports.M1TileRenderer=vr;exports.OverviewMap=$r;exports.TileScheduler=ii;exports.TileViewerCanvas=us;exports.WsiTileRenderer=fi;exports.WsiViewerCanvas=ka;exports.buildPointSpatialIndexAsync=ni;exports.buildTermPalette=Ui;exports.calcScaleLength=Fi;exports.calcScaleResolution=En;exports.clamp=k;exports.closeRing=_e;exports.computeRoiPointGroups=ri;exports.createCircle=wn;exports.createRectangle=en;exports.filterPointDataByPolygons=Ct;exports.filterPointDataByPolygonsHybrid=Jr;exports.filterPointDataByPolygonsInWorker=ei;exports.filterPointIndicesByPolygons=Zr;exports.filterPointIndicesByPolygonsInWorker=ws;exports.getWebGpuCapabilities=ps;exports.hexToRgba=Lr;exports.isSameViewState=bn;exports.lookupCellIndex=ti;exports.normalizeImageInfo=as;exports.prefilterPointsByBoundsWebGpu=jr;exports.terminatePointHitIndexWorker=Ps;exports.terminateRoiClipWorker=ys;exports.toBearerToken=Bi;exports.toRoiGeometry=It;exports.toTileUrl=Fn;
163
163
  //# sourceMappingURL=index.cjs.map