open-plant 1.3.0 → 1.3.2

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.
Files changed (78) hide show
  1. package/dist/assets/point-hit-index-worker-CNFA6pZm.js +2 -0
  2. package/dist/assets/point-hit-index-worker-CNFA6pZm.js.map +1 -0
  3. package/dist/assets/roi-clip-worker-BDVQwN2T.js.map +1 -1
  4. package/dist/index.cjs +17 -13
  5. package/dist/index.cjs.map +1 -1
  6. package/dist/index.js +3233 -3037
  7. package/dist/index.js.map +1 -1
  8. package/dist/types/core/ortho-camera.d.ts +7 -0
  9. package/dist/types/core/ortho-camera.d.ts.map +1 -1
  10. package/dist/types/index.d.ts +2 -0
  11. package/dist/types/index.d.ts.map +1 -1
  12. package/dist/types/react/draw-layer-brush.d.ts +9 -0
  13. package/dist/types/react/draw-layer-brush.d.ts.map +1 -0
  14. package/dist/types/react/draw-layer-label.d.ts +21 -0
  15. package/dist/types/react/draw-layer-label.d.ts.map +1 -0
  16. package/dist/types/react/draw-layer-overlay.d.ts +18 -0
  17. package/dist/types/react/draw-layer-overlay.d.ts.map +1 -0
  18. package/dist/types/react/draw-layer-stamp.d.ts +24 -0
  19. package/dist/types/react/draw-layer-stamp.d.ts.map +1 -0
  20. package/dist/types/react/draw-layer-types.d.ts +243 -0
  21. package/dist/types/react/draw-layer-types.d.ts.map +1 -0
  22. package/dist/types/react/draw-layer-utils.d.ts +30 -0
  23. package/dist/types/react/draw-layer-utils.d.ts.map +1 -0
  24. package/dist/types/react/draw-layer.d.ts +4 -187
  25. package/dist/types/react/draw-layer.d.ts.map +1 -1
  26. package/dist/types/react/wsi-region-hit-utils.d.ts +21 -0
  27. package/dist/types/react/wsi-region-hit-utils.d.ts.map +1 -0
  28. package/dist/types/react/wsi-viewer-canvas.d.ts +2 -1
  29. package/dist/types/react/wsi-viewer-canvas.d.ts.map +1 -1
  30. package/dist/types/wsi/brush-stroke.d.ts.map +1 -1
  31. package/dist/types/wsi/image-info.d.ts +26 -1
  32. package/dist/types/wsi/image-info.d.ts.map +1 -1
  33. package/dist/types/wsi/point-clip-hybrid.d.ts.map +1 -1
  34. package/dist/types/wsi/point-clip-worker-client.d.ts.map +1 -1
  35. package/dist/types/wsi/point-clip.d.ts +1 -1
  36. package/dist/types/wsi/point-clip.d.ts.map +1 -1
  37. package/dist/types/wsi/point-hit-index-shared.d.ts +25 -0
  38. package/dist/types/wsi/point-hit-index-shared.d.ts.map +1 -0
  39. package/dist/types/wsi/point-hit-index-worker-client.d.ts.map +1 -1
  40. package/dist/types/wsi/roi-geometry.d.ts +3 -0
  41. package/dist/types/wsi/roi-geometry.d.ts.map +1 -1
  42. package/dist/types/wsi/roi-term-stats.d.ts.map +1 -1
  43. package/dist/types/wsi/tile-scheduler.d.ts.map +1 -1
  44. package/dist/types/wsi/utils.d.ts +3 -2
  45. package/dist/types/wsi/utils.d.ts.map +1 -1
  46. package/dist/types/wsi/worker-client.d.ts +28 -0
  47. package/dist/types/wsi/worker-client.d.ts.map +1 -0
  48. package/dist/types/wsi/wsi-canvas-lifecycle.d.ts +15 -0
  49. package/dist/types/wsi/wsi-canvas-lifecycle.d.ts.map +1 -0
  50. package/dist/types/wsi/wsi-input-handlers.d.ts +67 -0
  51. package/dist/types/wsi/wsi-input-handlers.d.ts.map +1 -0
  52. package/dist/types/wsi/wsi-interaction.d.ts +50 -0
  53. package/dist/types/wsi/wsi-interaction.d.ts.map +1 -0
  54. package/dist/types/wsi/wsi-lifecycle-ops.d.ts +38 -0
  55. package/dist/types/wsi/wsi-lifecycle-ops.d.ts.map +1 -0
  56. package/dist/types/wsi/wsi-normalize.d.ts +20 -0
  57. package/dist/types/wsi/wsi-normalize.d.ts.map +1 -0
  58. package/dist/types/wsi/wsi-point-data.d.ts +14 -0
  59. package/dist/types/wsi/wsi-point-data.d.ts.map +1 -0
  60. package/dist/types/wsi/wsi-render-pass.d.ts +40 -0
  61. package/dist/types/wsi/wsi-render-pass.d.ts.map +1 -0
  62. package/dist/types/wsi/wsi-renderer-types.d.ts +132 -0
  63. package/dist/types/wsi/wsi-renderer-types.d.ts.map +1 -0
  64. package/dist/types/wsi/wsi-shaders.d.ts +4 -0
  65. package/dist/types/wsi/wsi-shaders.d.ts.map +1 -0
  66. package/dist/types/wsi/wsi-tile-cache.d.ts +8 -0
  67. package/dist/types/wsi/wsi-tile-cache.d.ts.map +1 -0
  68. package/dist/types/wsi/wsi-tile-renderer.d.ts +11 -70
  69. package/dist/types/wsi/wsi-tile-renderer.d.ts.map +1 -1
  70. package/dist/types/wsi/wsi-tile-visibility.d.ts +22 -0
  71. package/dist/types/wsi/wsi-tile-visibility.d.ts.map +1 -0
  72. package/dist/types/wsi/wsi-view-animation.d.ts +4 -0
  73. package/dist/types/wsi/wsi-view-animation.d.ts.map +1 -0
  74. package/dist/types/wsi/wsi-view-ops.d.ts +17 -0
  75. package/dist/types/wsi/wsi-view-ops.d.ts.map +1 -0
  76. package/package.json +1 -1
  77. package/dist/assets/point-hit-index-worker-Bp1uxxyQ.js +0 -2
  78. package/dist/assets/point-hit-index-worker-Bp1uxxyQ.js.map +0 -1
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Ei=Object.defineProperty;var Ci=(t,e,n)=>e in t?Ei(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var S=(t,e,n)=>Ci(t,typeof e!="symbol"?e+"":e,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const He=require("react/jsx-runtime"),d=require("react");var Tt=typeof document<"u"?document.currentScript:null;function ur(t,e,n){const r=t.createShader(e);if(!r)throw new Error("Failed to create shader.");if(t.shaderSource(r,n),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS)){const o=t.getShaderInfoLog(r)??"unknown shader error";throw t.deleteShader(r),new Error(o)}return r}function Ri(t,e,n){const r=ur(t,t.VERTEX_SHADER,e),i=ur(t,t.FRAGMENT_SHADER,n),o=t.createProgram();if(!o)throw t.deleteShader(r),t.deleteShader(i),new Error("Failed to create program.");if(t.attachShader(o,r),t.attachShader(o,i),t.linkProgram(o),t.deleteShader(r),t.deleteShader(i),!t.getProgramParameter(o,t.LINK_STATUS)){const a=t.getProgramInfoLog(o)??"unknown link error";throw t.deleteProgram(o),new Error(a)}return o}function gn(t,e,n){const r=t.getUniformLocation(e,n);if(!r)throw new Error(`Failed to get uniform location: ${n}`);return r}function Ii(t){const e=t.getContext("webgl2",{alpha:!1,antialias:!1,depth:!1,stencil:!1,preserveDrawingBuffer:!1,powerPreference:"high-performance"});if(!e)throw new Error("WebGL2 is not available.");return e}let Pi=class{constructor(){S(this,"viewportWidth",1);S(this,"viewportHeight",1);S(this,"viewState",{offsetX:0,offsetY:0,zoom:1})}setViewport(e,n){this.viewportWidth=Math.max(1,e),this.viewportHeight=Math.max(1,n)}getViewportSize(){return{width:this.viewportWidth,height:this.viewportHeight}}setViewState(e){e.offsetX!==void 0&&(this.viewState.offsetX=e.offsetX),e.offsetY!==void 0&&(this.viewState.offsetY=e.offsetY),e.zoom!==void 0&&(this.viewState.zoom=Math.max(1e-4,e.zoom))}getViewState(){return{...this.viewState}}getMatrix(){const e=this.viewportWidth/this.viewState.zoom,n=this.viewportHeight/this.viewState.zoom,r=2/e,i=-2/n,o=-1-this.viewState.offsetX*r,s=1-this.viewState.offsetY*i;return new Float32Array([r,0,0,0,i,0,o,s,1])}};const vi=`#version 300 es
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
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
- `,_i=`#version 300 es
21
+ `,Pi=`#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 Lr{constructor(e){S(this,"canvas");S(this,"gl");S(this,"camera",new Pi);S(this,"imageWidth");S(this,"imageHeight");S(this,"clearColor");S(this,"program");S(this,"vao");S(this,"quadBuffer");S(this,"uCameraLocation");S(this,"uBoundsLocation");S(this,"uTextureLocation");S(this,"resizeObserver");S(this,"tiles",[]);S(this,"frameId",null);S(this,"loadVersion",0);S(this,"destroyed",!1);S(this,"fitted",!1);S(this,"controlledViewState",!1);this.canvas=e.canvas,this.imageWidth=Math.max(1,e.imageWidth),this.imageHeight=Math.max(1,e.imageHeight),this.clearColor=e.clearColor??[.03,.05,.08,1],this.gl=Ii(this.canvas),this.program=Ri(this.gl,vi,_i);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=gn(this.gl,this.program,"uCamera"),this.uBoundsLocation=gn(this.gl,this.program,"uBounds"),this.uTextureLocation=gn(this.gl,this.program,"uTexture"),e.initialViewState&&(this.controlledViewState=!0,this.camera.setViewState(e.initialViewState)),this.resizeObserver=new ResizeObserver(()=>{this.resize()}),this.resizeObserver.observe(this.canvas),this.resize()}async setTiles(e){if(this.destroyed)return;const n=++this.loadVersion,r=await Promise.all(e.map(async i=>await this.loadTile(i,n)));if(this.destroyed||n!==this.loadVersion){for(const i of r)i&&this.gl.deleteTexture(i.texture);return}this.disposeTiles(this.tiles),this.tiles=r.filter(i=>i!==null),this.requestRender()}setViewState(e){this.controlledViewState=!0,this.camera.setViewState(e),this.requestRender()}getViewState(){return this.camera.getViewState()}destroy(){this.destroyed||(this.destroyed=!0,this.loadVersion+=1,this.frameId!==null&&(cancelAnimationFrame(this.frameId),this.frameId=null),this.resizeObserver.disconnect(),this.disposeTiles(this.tiles),this.tiles=[],this.gl.deleteBuffer(this.quadBuffer),this.gl.deleteVertexArray(this.vao),this.gl.deleteProgram(this.program))}async loadTile(e,n){try{const r=await fetch(e.url);if(!r.ok)throw new Error(`Tile fetch failed: ${r.status} ${r.statusText}`);const i=await r.blob(),o=await createImageBitmap(i);if(this.destroyed||n!==this.loadVersion)return o.close(),null;const s=this.gl.createTexture();if(!s)throw o.close(),new Error("Failed to create tile texture.");return this.gl.bindTexture(this.gl.TEXTURE_2D,s),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,1),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,o),this.gl.bindTexture(this.gl.TEXTURE_2D,null),o.close(),{id:e.id,bounds:e.bounds,texture:s}}catch(r){return console.error(`[M1TileRenderer] tile load failed: ${e.id}`,r),null}}resize(){if(this.destroyed)return;const e=this.canvas.getBoundingClientRect(),n=Math.max(1,e.width||this.canvas.clientWidth||1),r=Math.max(1,e.height||this.canvas.clientHeight||1),i=Math.max(1,window.devicePixelRatio||1),o=Math.max(1,Math.round(n*i)),s=Math.max(1,Math.round(r*i));(this.canvas.width!==o||this.canvas.height!==s)&&(this.canvas.width=o,this.canvas.height=s),this.camera.setViewport(n,r),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),!this.fitted&&!this.controlledViewState&&(this.fitToImage(),this.fitted=!0),this.requestRender()}fitToImage(){const e=this.camera.getViewportSize(),n=Math.min(e.width/this.imageWidth,e.height/this.imageHeight),r=Number.isFinite(n)&&n>0?n:1,i=e.width/r,o=e.height/r,s=(this.imageWidth-i)*.5,a=(this.imageHeight-o)*.5;this.camera.setViewState({zoom:r,offsetX:s,offsetY:a})}requestRender(){this.frameId!==null||this.destroyed||(this.frameId=requestAnimationFrame(()=>{this.frameId=null,this.render()}))}render(){if(!this.destroyed){this.gl.clearColor(this.clearColor[0],this.clearColor[1],this.clearColor[2],this.clearColor[3]),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.useProgram(this.program),this.gl.bindVertexArray(this.vao),this.gl.uniformMatrix3fv(this.uCameraLocation,!1,this.camera.getMatrix()),this.gl.uniform1i(this.uTextureLocation,0);for(const e of this.tiles)this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,e.texture),this.gl.uniform4f(this.uBoundsLocation,e.bounds[0],e.bounds[1],e.bounds[2],e.bounds[3]),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindVertexArray(null)}}disposeTiles(e){for(const n of e)this.gl.deleteTexture(n.texture)}}const Fi=.1,Ui=4e6,Bi=4096,Li=64,Ni=1,zi=4,Nr=1e-6,ki=24;function rn(t,e,n){return Math.max(e,Math.min(n,t))}function Ke(t){if(!Array.isArray(t)||t.length<3)return[];const e=t.map(([i,o])=>[i,o]),n=e[0],r=e[e.length-1];return!n||!r?[]:((n[0]!==r[0]||n[1]!==r[1])&&e.push([n[0],n[1]]),e)}function Di(t){if(!Array.isArray(t)||t.length===0)return[];const e=[];for(const n of t){if(!Array.isArray(n)||n.length<2)continue;const r=Number(n[0]),i=Number(n[1]);if(!Number.isFinite(r)||!Number.isFinite(i))continue;const o=e[e.length-1];o&&Math.abs(o[0]-r)<1e-9&&Math.abs(o[1]-i)<1e-9||e.push([r,i])}return e}function Oi(t,e,n){if(e<=Nr||n<8)return[];const r=[];for(let i=0;i<=n;i+=1){const o=i/n*Math.PI*2;r.push([t[0]+Math.cos(o)*e,t[1]+Math.sin(o)*e])}return Ke(r)}function pn(t,e){if(!t.length)return[];let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[a,c]of t)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(e,1);return Ke([[n-s,r-s],[i+s,r-s],[i+s,o+s],[n-s,o+s]])}function Xi(t,e){let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[a,c]of t)a<n&&(n=a),a>i&&(i=a),c<r&&(r=c),c>o&&(o=c);const s=Math.max(e,1);return[n-s,r-s,i+s,o+s]}function Yi(t,e,n){const r=Math.max(Fi,Number(n.minRasterStep)||0),i=Math.max(32768,Math.floor(n.maxRasterPixels||Ui)),o=Math.max(256,Math.floor(n.maxRasterSize||Bi)),s=Math.max(.001,t[2]-t[0]),a=Math.max(.001,t[3]-t[1]);let c=Math.max(r,Number.EPSILON),l=3,m=Math.ceil(s/c)+l*2+1,p=Math.ceil(a/c)+l*2+1;for(;(m>o||p>o||m*p>i)&&(c*=1.15,m=Math.ceil(s/c)+l*2+1,p=Math.ceil(a/c)+l*2+1,!(c>Math.max(s,a))););return m=Math.max(8,m),p=Math.max(8,p),{minX:t[0],minY:t[1],step:c,padding:l,width:m,height:p}}function Wi(t,e){if(typeof OffscreenCanvas<"u"){const r=new OffscreenCanvas(t,e).getContext("2d",{willReadFrequently:!0});if(r)return r}if(typeof document<"u"){const n=document.createElement("canvas");return n.width=t,n.height=e,n.getContext("2d",{willReadFrequently:!0})}return null}function Vi(t,e){return[(t[0]-e.minX)/e.step+e.padding,(t[1]-e.minY)/e.step+e.padding]}function Gi(t,e,n){const r=Wi(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=e*2/n.step;const i=t.map(a=>Vi(a,n));if(i.length<=1){const a=i[0];if(!a)return new Uint8Array(0);r.beginPath(),r.arc(a[0],a[1],e/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]>=ki?1:0;return s}function Hi(t,e,n){const r=[],i=e+1,o=(a,c)=>c*i+a,s=(a,c)=>a>=0&&c>=0&&a<e&&c<n&&t[c*e+a]>0;for(let a=0;a<n;a+=1)for(let c=0;c<e;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 qi(t,e){const n=(e-t+4)%4;return n===1?0:n===0?1:n===3?2:3}function $i(t){if(!t.length)return[];const e=new Map;for(let i=0;i<t.length;i+=1){const o=e.get(t[i].start);o?o.push(i):e.set(t[i].start,[i])}const n=new Uint8Array(t.length),r=[];for(let i=0;i<t.length;i+=1){if(n[i])continue;const o=t[i],s=o.start;let a=o.end,c=o.dir;const l=[o.start,o.end];n[i]=1;let m=0;const p=t.length*3;for(;a!==s&&m<p;){const b=e.get(a);if(!b||b.length===0)break;let w=-1,f=1/0;for(const A of b){if(n[A])continue;const v=t[A],U=qi(c,v.dir);U<f&&(f=U,w=A)}if(w<0)break;n[w]=1;const y=t[w];a=y.end,c=y.dir,l.push(a),m+=1}l.length>=4&&l[0]===l[l.length-1]&&r.push(l)}return r}function Zi(t,e,n){const r=e+1,i=[];for(const o of t){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 Ke(i)}function Ki(t){if(t.length<4)return 0;let e=0;for(let n=0;n<t.length-1;n+=1){const r=t[n],i=t[n+1];e+=r[0]*i[1]-i[0]*r[1]}return e*.5}function ji(t,e=1e-9){const n=Ke(t);if(n.length<5)return n;const r=[n[0]];for(let i=1;i<n.length-1;i+=1){const o=r[r.length-1],s=n[i],a=n[i+1],c=(s[0]-o[0])*(a[1]-s[1])-(s[1]-o[1])*(a[0]-s[0]);Math.abs(c)<=e||r.push(s)}return r.push(r[0]),Ke(r)}function Ji(t,e,n){const r=n[0]-e[0],i=n[1]-e[1],o=r*r+i*i;if(o<=1e-12){const p=t[0]-e[0],b=t[1]-e[1];return p*p+b*b}const s=rn(((t[0]-e[0])*r+(t[1]-e[1])*i)/o,0,1),a=e[0]+r*s,c=e[1]+i*s,l=t[0]-a,m=t[1]-c;return l*l+m*m}function Qi(t,e){if(t.length<=2||e<=0)return t.slice();const n=new Uint8Array(t.length);n[0]=1,n[t.length-1]=1;const r=e*e,i=[[0,t.length-1]];for(;i.length>0;){const s=i.pop();if(!s)break;const[a,c]=s;if(c-a<=1)continue;let l=0,m=-1;for(let p=a+1;p<c;p+=1){const b=Ji(t[p],t[a],t[c]);b>l&&(l=b,m=p)}m>=0&&l>r&&(n[m]=1,i.push([a,m],[m,c]))}const o=[];for(let s=0;s<t.length;s+=1)n[s]&&o.push(t[s]);return o}function eo(t,e){const n=Ke(t);if(n.length<5||e<=0)return n;const r=n.slice(0,-1),i=Qi(r,e);return i.length<3?n:Ke(i)}function to(t,e){let n=Ke(t);if(e<=0||n.length<5)return n;for(let r=0;r<e;r+=1){const i=n.slice(0,-1);if(i.length<3)break;const o=[];for(let s=0;s<i.length;s+=1){const a=i[s],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=Ke(o)}return n}function Ct(t,e){return e?Ke(t.map(([n,r])=>[rn(n,e[0],e[2]),rn(r,e[1],e[3])])):t}function no(t,e){const n=Di(t),r=Math.max(Nr,Number(e.radius)||0);if(n.length===0||!Number.isFinite(r))return[];const i=Math.max(12,Math.floor(e.circleSides||Li));if(n.length===1)return Ct(Oi(n[0],r,i),e.clipBounds);const o=Xi(n,r),s=Yi(o,r,e),a=Gi(n,r,s);if(!a.length)return Ct(pn(n,r),e.clipBounds);const c=Hi(a,s.width,s.height),l=$i(c);if(!l.length)return Ct(pn(n,r),e.clipBounds);let m=[],p=0;for(const y of l){const A=Zi(y,s.width,s),v=Math.abs(Ki(A));v<=p||(p=v,m=A)}if(!m.length)return Ct(pn(n,r),e.clipBounds);const b=typeof e.simplifyTolerance=="number"&&Number.isFinite(e.simplifyTolerance)?Math.max(0,e.simplifyTolerance):s.step*.2,w=typeof e.smoothingPasses=="number"&&Number.isFinite(e.smoothingPasses)?Math.round(rn(e.smoothingPasses,0,zi)):Ni,f=eo(to(ji(m,s.step*.001),w),b);return Ct(f,e.clipBounds)}function lr(t){return typeof t=="number"&&Number.isFinite(t)}function ro(t){return Array.isArray(t)&&t.length>=2&&lr(t[0])&&lr(t[1])}function zr(t){return Array.isArray(t)&&t.length>0&&t.every(e=>ro(e))}function kr(t){return Array.isArray(t)&&t.length>0&&t.every(e=>zr(e))}function io(t){return Array.isArray(t)&&t.length>0&&t.every(e=>kr(e))}function oo(t){if(!Array.isArray(t)||t.length<3)return[];const e=[];for(const i of t){if(!Array.isArray(i)||i.length<2)continue;const o=Number(i[0]),s=Number(i[1]);if(!Number.isFinite(o)||!Number.isFinite(s))continue;const a=e[e.length-1];a&&a[0]===o&&a[1]===s||e.push([o,s])}if(e.length<3)return[];const n=e[0],r=e[e.length-1];return(n[0]!==r[0]||n[1]!==r[1])&&e.push([n[0],n[1]]),e.length>=4?e:[]}function xn(t){if(!Array.isArray(t)||t.length<4)return 0;let e=0;for(let n=0;n<t.length-1;n+=1){const r=t[n],i=t[n+1];e+=r[0]*i[1]-i[0]*r[1]}return e*.5}function bn(t){if(!Array.isArray(t)||t.length===0)return[];const e=[];for(const o of t){const s=oo(o);s.length>=4&&e.push(s)}if(e.length===0)return[];if(e.length===1)return[e[0]];let n=0,r=0;for(let o=0;o<e.length;o+=1){const s=Math.abs(xn(e[o]));s<=r||(r=s,n=o)}const i=[e[n]];for(let o=0;o<e.length;o+=1)o!==n&&i.push(e[o]);return i}function Dr(t){if(!t)return[];if(zr(t)){const e=bn([t]);return e.length>0?[e]:[]}if(kr(t)){const e=bn(t);return e.length>0?[e]:[]}if(io(t)){const e=[];for(const n of t){const r=bn(n);r.length>0&&e.push(r)}return e}return[]}function fr(t,e,n){let r=!1;for(let i=0,o=n.length-1;i<n.length;o=i,i+=1){const s=n[i][0],a=n[i][1],c=n[o][0],l=n[o][1];a>e!=l>e&&t<(c-s)*(e-a)/(l-a||Number.EPSILON)+s&&(r=!r)}return r}function Ut(t){const e=[];for(const n of t??[]){const r=Dr(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,l=-1/0;for(const[p,b]of o)p<s&&(s=p),p>c&&(c=p),b<a&&(a=b),b>l&&(l=b);if(!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(c)||!Number.isFinite(l))continue;let m=Math.abs(xn(o));for(let p=1;p<i.length;p+=1)m-=Math.abs(xn(i[p]));e.push({outer:o,holes:i.slice(1),minX:s,minY:a,maxX:c,maxY:l,area:Math.max(1e-6,m)})}}return e}function Or(t,e,n){if(t<n.minX||t>n.maxX||e<n.minY||e>n.maxY||!fr(t,e,n.outer))return!1;for(const r of n.holes)if(fr(t,e,r))return!1;return!0}function on(t,e,n){for(const r of n)if(Or(t,e,r))return!0;return!1}const Bn=[160,160,160,255];function ae(t,e,n){return Math.max(e,Math.min(n,t))}function Ln(t,e,n){const r=Number(t),i=Number(e),o=Number(n);return!Number.isFinite(r)||r<=0?1:!Number.isFinite(i)||!Number.isFinite(o)?r:Math.pow(2,i-o)*r}function so(t,e,n){let i=100*Ln(t,e,n);if(Number(t)){let o="μm";return i>1e3&&(i/=1e3,o="mm"),`${i.toPrecision(3)} ${o}`}return`${Math.round(i*1e3)/1e3} pixels`}function ao(t,e){return!t&&!e?!0:!t||!e?!1:Math.abs((t.zoom??0)-(e.zoom??0))<1e-6&&Math.abs((t.offsetX??0)-(e.offsetX??0))<1e-6&&Math.abs((t.offsetY??0)-(e.offsetY??0))<1e-6&&Math.abs((t.rotationDeg??0)-(e.rotationDeg??0))<1e-6}function co(t){const e=String(t??"").trim();if(!e)return"";if(/^bearer\s+/i.test(e)){const n=e.replace(/^bearer\s+/i,"").trim();return n?`Bearer ${n}`:""}return`Bearer ${e}`}function Xr(t){const n=String(t??"").trim().match(/^#?([0-9a-fA-F]{6})$/);if(!n)return[...Bn];const r=Number.parseInt(n[1],16);return[r>>16&255,r>>8&255,r&255,255]}function uo(t){const e=[[...Bn]],n=new Map;for(const i of t??[]){const o=String(i?.termId??"");!o||n.has(o)||(n.set(o,e.length),e.push(Xr(i?.termColor)))}const r=new Uint8Array(e.length*4);for(let i=0;i<e.length;i+=1)r[i*4]=e[i][0],r[i*4+1]=e[i][1],r[i*4+2]=e[i][2],r[i*4+3]=e[i][3];return{colors:r,termToPaletteIndex:n}}function hr(t,e,n){const r=t.createShader(t.VERTEX_SHADER),i=t.createShader(t.FRAGMENT_SHADER);if(!r||!i)throw new Error("Shader allocation failed");if(t.shaderSource(r,e),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new Error(t.getShaderInfoLog(r)||"vertex compile failed");if(t.shaderSource(i,n),t.compileShader(i),!t.getShaderParameter(i,t.COMPILE_STATUS))throw new Error(t.getShaderInfoLog(i)||"fragment compile failed");const o=t.createProgram();if(!o)throw new Error("Program allocation failed");if(t.attachShader(o,r),t.attachShader(o,i),t.linkProgram(o),t.deleteShader(r),t.deleteShader(i),!t.getProgramParameter(o,t.LINK_STATUS))throw new Error(t.getProgramInfoLog(o)||"program link failed");return o}const lo="rgba(255, 77, 79, 0.16)",dr="transparent",fo=3,ho=2,Yr=96,mo=1,mr=[],_t=[],sn=1e3,Wr=2,Vr=2,go=4096,po=.2,bo=1.12,wo=.89,yo=32,So="#000000",Mo=.1,Ao="#FFCF00",xo="#FF0000",To=1.5,gr=[2,2],Eo=1,Co=.25,Ro=4,Io=1,Po=0,vo=4,_o=.05,Fo=256,pr=1.5,st={color:"#ff4d4f",width:2,lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},Uo={color:"#4cc9f0",width:2,lineDash:[10,8],lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},Bo="rgba(23, 23, 25, 0.1)",Lo=6,Ve={fontFamily:"Pretendard, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:11,fontWeight:600,textColor:"#171719",backgroundColor:"#FFCC00",borderColor:"rgba(0, 0, 0, 0)",borderWidth:0,paddingX:8,paddingY:4,offsetY:10,borderRadius:4},at={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},br={x:16,y:-24},No=20,wr=1e-6;function qe(t,e,n){return Math.max(e,Math.min(n,t))}function Gr(t,e,n){if(!t||!n)return 0;const r=Number(n.minZoom),i=Number(n.maxZoom);return!Number.isFinite(r)||!Number.isFinite(i)||i-r<=wr||!Number.isFinite(e)?0:e>=i-wr?No:0}function Yt(t){return t==="stamp-rectangle"||t==="stamp-circle"||t==="stamp-rectangle-4096px"||t==="stamp-rectangle-2mm2"||t==="stamp-circle-2mm2"||t==="stamp-circle-hpf-0.2mm2"}function Pt(t,e){return typeof t!="number"||!Number.isFinite(t)||t<=0?e:t}function zo(t){return{rectangleAreaMm2:Pt(t?.rectangleAreaMm2,Wr),circleAreaMm2:Pt(t?.circleAreaMm2,Vr),rectanglePixelSize:Pt(t?.rectanglePixelSize,go)}}function ko(t,e){return typeof t!="number"||!Number.isFinite(t)?e:qe(t,0,1)}function Do(t){if(!Array.isArray(t))return gr;const e=t.filter(n=>Number.isFinite(n)&&n>=0);return e.length>0?e:gr}function Oo(t){return typeof t!="number"||!Number.isFinite(t)?Eo:qe(t,Co,Ro)}function Xo(t){return typeof t!="number"||!Number.isFinite(t)?Io:Math.round(qe(t,Po,vo))}function Yo(t){const e=Pt(t?.radius,yo),n=Pt(t?.cursorLineWidth,To),r=Oo(t?.edgeDetail),i=Xo(t?.edgeSmoothing);return{radius:e,edgeDetail:r,edgeSmoothing:i,clickSelectRoi:t?.clickSelectRoi===!0,fillColor:t?.fillColor||So,fillOpacity:ko(t?.fillOpacity,Mo),cursorColor:t?.cursorColor||Ao,cursorActiveColor:t?.cursorActiveColor||xo,cursorLineWidth:n,cursorLineDash:Do(t?.cursorLineDash)}}function Wo(t){return t*sn*sn}function yr(t,e,n){if(!t||!Number.isFinite(e)||e<=0)return[];if(n){const r=n.worldToScreen(t[0],t[1]),i=n.worldToScreen(t[0]+e,t[1]);if(r&&i){const o=Math.hypot(i[0]-r[0],i[1]-r[1]),s=[[r[0]-o,r[1]-o],[r[0]+o,r[1]-o],[r[0]+o,r[1]+o],[r[0]-o,r[1]+o]],a=[];for(const c of s){const l=n.screenToWorld(c);if(!l)throw new Error("Failed to create rectangle");a.push(l)}return Ne(a)}}return Ne([[t[0]-e,t[1]-e],[t[0]+e,t[1]-e],[t[0]+e,t[1]+e],[t[0]-e,t[1]+e]])}function Vo(t,e,n=Yr){if(!t||!Number.isFinite(e)||e<=0)return[];const r=[];for(let i=0;i<=n;i+=1){const o=i/n*Math.PI*2;r.push([t[0]+Math.cos(o)*e,t[1]+Math.sin(o)*e])}return Ne(r)}function Ne(t){if(!Array.isArray(t)||t.length<3)return[];const e=t.map(([i,o])=>[i,o]),n=e[0],r=e[e.length-1];return!n||!r?[]:((n[0]!==r[0]||n[1]!==r[1])&&e.push([n[0],n[1]]),e)}function an(t,e,n){if(!t||!e)return[];if(n){const r=n.worldToScreen(t[0],t[1]),i=n.worldToScreen(e[0],e[1]);if(r&&i){const o=[[r[0],r[1]],[i[0],r[1]],[i[0],i[1]],[r[0],i[1]]],s=[];for(const a of o){const c=n.screenToWorld(a);if(!c)return an(t,e);s.push(c)}return Ne(s)}}return Ne([[t[0],t[1]],[e[0],t[1]],[e[0],e[1]],[t[0],e[1]]])}function Tn(t,e,n=Yr){if(!t||!e)return[];const r=(t[0]+e[0])*.5,i=(t[1]+e[1])*.5,o=Math.hypot(e[0]-t[0],e[1]-t[1])*.5;if(o<1)return[];const s=[];for(let a=0;a<=n;a+=1){const c=a/n*Math.PI*2;s.push([r+Math.cos(c)*o,i+Math.sin(c)*o])}return Ne(s)}function tn(t){if(!Array.isArray(t)||t.length<4)return 0;let e=0;for(let n=0;n<t.length-1;n+=1){const r=t[n],i=t[n+1];e+=r[0]*i[1]-i[0]*r[1]}return Math.abs(e*.5)}function Sr(t){if(!Array.isArray(t)||t.length===0)return[0,0,0,0];let e=1/0,n=1/0,r=-1/0,i=-1/0;for(const[o,s]of t)o<e&&(e=o),o>r&&(r=o),s<n&&(n=s),s>i&&(i=s);return[e,n,r,i]}function Mr(t){return Array.isArray(t)&&t.length>=4&&tn(t)>mo}function En(t,e,n=!1){if(e.length!==0){t.moveTo(e[0][0],e[0][1]);for(let r=1;r<e.length;r+=1)t.lineTo(e[r][0],e[r][1]);n&&t.closePath()}}function Ze(t,e,n,r=!1,i=!1,o=lo){e.length!==0&&(t.beginPath(),En(t,e,r),i&&r&&(t.fillStyle=o,t.fill()),t.strokeStyle=n.color,t.lineWidth=n.width,t.lineJoin=n.lineJoin,t.lineCap=n.lineCap,t.shadowColor=n.shadowColor,t.shadowBlur=n.shadowBlur,t.shadowOffsetX=n.shadowOffsetX,t.shadowOffsetY=n.shadowOffsetY,t.setLineDash(n.lineDash),t.stroke(),t.setLineDash(_t),t.shadowColor="rgba(0, 0, 0, 0)",t.shadowBlur=0,t.shadowOffsetX=0,t.shadowOffsetY=0)}function Go(t){if(typeof t!="string")return dr;const e=t.trim();return e.length>0?e:dr}function Hr(t){const e=Array.isArray(t?.lineDash)?t.lineDash.filter(s=>Number.isFinite(s)&&s>=0):_t,n=typeof t?.width=="number"&&Number.isFinite(t.width)?Math.max(0,t.width):st.width,r=typeof t?.shadowBlur=="number"&&Number.isFinite(t.shadowBlur)?Math.max(0,t.shadowBlur):st.shadowBlur,i=typeof t?.shadowOffsetX=="number"&&Number.isFinite(t.shadowOffsetX)?t.shadowOffsetX:st.shadowOffsetX,o=typeof t?.shadowOffsetY=="number"&&Number.isFinite(t.shadowOffsetY)?t.shadowOffsetY:st.shadowOffsetY;return{color:t?.color||st.color,width:n,lineDash:e.length?e:_t,lineJoin:t?.lineJoin||st.lineJoin,lineCap:t?.lineCap||st.lineCap,shadowColor:t?.shadowColor||st.shadowColor,shadowBlur:r,shadowOffsetX:i,shadowOffsetY:o}}function Rt(t,e){return e?Hr({color:e.color??t.color,width:e.width??t.width,lineDash:e.lineDash??t.lineDash,lineJoin:e.lineJoin??t.lineJoin,lineCap:e.lineCap??t.lineCap,shadowColor:e.shadowColor??t.shadowColor,shadowBlur:e.shadowBlur??t.shadowBlur,shadowOffsetX:e.shadowOffsetX??t.shadowOffsetX,shadowOffsetY:e.shadowOffsetY??t.shadowOffsetY}):t}function Ar(t,e){return t==null||e===null||e===void 0?!1:String(t)===String(e)}function Ho(t){const e=t[0];return Array.isArray(e)&&Array.isArray(e[0])}function xr(t){return typeof t=="number"&&Number.isFinite(t)}function qo(t){return Array.isArray(t)&&t.length>=2&&xr(t[0])&&xr(t[1])}function $o(t){return Array.isArray(t)&&t.length>=2&&t.every(e=>qo(e))}function qr(t,e){if(!(!Array.isArray(t)||t.length===0)){if($o(t)){e.push(t.map(([n,r])=>[n,r]));return}for(const n of t)qr(n,e)}}function Tr(t,e){const n=[];qr(t,n);const r=[];for(const i of n){if(i.length<2)continue;const o=e?Ne(i):i;o.length>=(e?4:2)&&r.push(o)}return r}function Zo(t,e,n,r){if(!(e.length<4||n.length===0)){t.save(),t.beginPath(),En(t,e,!0);for(const i of n)i.length<4||En(t,i,!0);t.fillStyle=r,t.fill("evenodd"),t.restore()}}function Nn(t){const e=typeof t?.paddingX=="number"&&Number.isFinite(t.paddingX)?Math.max(0,t.paddingX):Ve.paddingX,n=typeof t?.paddingY=="number"&&Number.isFinite(t.paddingY)?Math.max(0,t.paddingY):Ve.paddingY,r=typeof t?.fontSize=="number"&&Number.isFinite(t.fontSize)?Math.max(8,t.fontSize):Ve.fontSize,i=typeof t?.borderWidth=="number"&&Number.isFinite(t.borderWidth)?Math.max(0,t.borderWidth):Ve.borderWidth,o=typeof t?.offsetY=="number"&&Number.isFinite(t.offsetY)?t.offsetY:Ve.offsetY,s=typeof t?.borderRadius=="number"&&Number.isFinite(t.borderRadius)?Math.max(0,t.borderRadius):Ve.borderRadius;return{fontFamily:t?.fontFamily||Ve.fontFamily,fontSize:r,fontWeight:t?.fontWeight||Ve.fontWeight,textColor:t?.textColor||Ve.textColor,backgroundColor:t?.backgroundColor||Ve.backgroundColor,borderColor:t?.borderColor||Ve.borderColor,borderWidth:i,paddingX:e,paddingY:n,offsetY:o,borderRadius:s}}function $r(t,e){return e?Nn({fontFamily:e.fontFamily??t.fontFamily,fontSize:e.fontSize??t.fontSize,fontWeight:e.fontWeight??t.fontWeight,textColor:e.textColor??t.textColor,backgroundColor:e.backgroundColor??t.backgroundColor,borderColor:e.borderColor??t.borderColor,borderWidth:e.borderWidth??t.borderWidth,paddingX:e.paddingX??t.paddingX,paddingY:e.paddingY??t.paddingY,offsetY:e.offsetY??t.offsetY,borderRadius:e.borderRadius??t.borderRadius}):t}function Ko(t){const e=typeof t?.fontSize=="number"&&Number.isFinite(t.fontSize)?Math.max(8,t.fontSize):at.fontSize,n=typeof t?.borderRadius=="number"&&Number.isFinite(t.borderRadius)?Math.max(0,t.borderRadius):at.borderRadius,r=typeof t?.paddingX=="number"&&Number.isFinite(t.paddingX)?Math.max(0,t.paddingX):at.paddingX,i=typeof t?.paddingY=="number"&&Number.isFinite(t.paddingY)?Math.max(0,t.paddingY):at.paddingY;return{fontFamily:t?.fontFamily||at.fontFamily,fontSize:e,fontWeight:t?.fontWeight||at.fontWeight,textColor:t?.textColor||at.textColor,backgroundColor:t?.backgroundColor||at.backgroundColor,borderRadius:n,paddingX:r,paddingY:i}}function jo(t){const e=typeof t?.x=="number"&&Number.isFinite(t.x)?t.x:br.x,n=typeof t?.y=="number"&&Number.isFinite(t.y)?t.y:br.y;return{x:e,y:n}}function Cn(t){return Number.isFinite(t)?`${Math.max(0,t).toFixed(3)} mm²`:"0.000 mm²"}function Jo(t){const e=typeof t?.format=="function"?t.format:Cn,n=jo(t?.cursorOffset);return{enabled:t?.enabled===!0,format:e,style:Ko(t?.style),cursorOffsetX:n.x,cursorOffsetY:n.y}}function Qo(t){return{color:Bo,width:Lo,lineDash:_t,lineJoin:t.lineJoin,lineCap:t.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function Zr(t,e,n,r,i,o){const s=Math.max(0,Math.min(o,r*.5,i*.5));t.beginPath(),t.moveTo(e+s,n),t.lineTo(e+r-s,n),t.quadraticCurveTo(e+r,n,e+r,n+s),t.lineTo(e+r,n+i-s),t.quadraticCurveTo(e+r,n+i,e+r-s,n+i),t.lineTo(e+s,n+i),t.quadraticCurveTo(e,n+i,e,n+i-s),t.lineTo(e,n+s),t.quadraticCurveTo(e,n,e+s,n),t.closePath()}function es(t){if(!t.length)return null;let e=1/0;for(const i of t)i[1]<e&&(e=i[1]);if(!Number.isFinite(e))return null;let n=1/0,r=-1/0;for(const i of t)Math.abs(i[1]-e)>.5||(i[0]<n&&(n=i[0]),i[0]>r&&(r=i[0]));return!Number.isFinite(n)||!Number.isFinite(r)?null:[(n+r)*.5,e]}function ts(t){let e=null;for(const n of t){const r=es(n.outer);r&&(!e||r[1]<e[1]||r[1]===e[1]&&r[0]<e[0])&&(e=r)}return e}function Er(t){const e=Dr(t);if(e.length===0)return[];const n=[];for(const r of e){const i=r[0];if(!i||i.length<4)continue;const o=i.map(([a,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(([l,m])=>[l,m]))}n.push({outer:o,holes:s})}return n}function ns(t,e,n,r,i,o){const s=e.trim();if(!s)return;t.save(),t.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,t.textAlign="center",t.textBaseline="middle";const c=t.measureText(s).width+o.paddingX*2,l=o.fontSize+o.paddingY*2,m=qe(n[0],c*.5+1,r-c*.5-1),p=qe(n[1]-o.offsetY,l*.5+1,i-l*.5-1),b=m-c*.5,w=p-l*.5;t.fillStyle=o.backgroundColor,t.strokeStyle=o.borderColor,t.lineWidth=o.borderWidth,Zr(t,b,w,c,l,o.borderRadius),t.fill(),o.borderWidth>0&&t.stroke(),t.fillStyle=o.textColor,t.fillText(s,m,p+.5),t.restore()}function rs(t,e,n,r,i,o,s,a){const c=e.trim();if(!c)return;t.save(),t.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,t.textAlign="center",t.textBaseline="middle";const m=t.measureText(c).width+o.paddingX*2,p=o.fontSize+o.paddingY*2,b=qe(n[0]+s,m*.5+1,r-m*.5-1),w=qe(n[1]+a,p*.5+1,i-p*.5-1),f=b-m*.5,y=w-p*.5;t.fillStyle=o.backgroundColor,Zr(t,f,y,m,p,o.borderRadius),t.fill(),t.fillStyle=o.textColor,t.fillText(c,b,w+.5),t.restore()}function Wt(t,e,n){return[qe(t[0],0,e),qe(t[1],0,n)]}function gt(t){if(!Array.isArray(t)||t.length<2)return null;const e=Number(t[0]),n=Number(t[1]);return!Number.isFinite(e)||!Number.isFinite(n)?null:[e,n]}function Kr({tool:t,imageWidth:e,imageHeight:n,imageMpp:r,imageZoom:i,stampOptions:o,brushOptions:s,projectorRef:a,onBrushTap:c,onDrawComplete:l,onPatchComplete:m,enabled:p,viewStateSignal:b,persistedRegions:w,patchRegions:f,persistedPolygons:y,drawFillColor:A,regionStrokeStyle:v,regionStrokeHoverStyle:U,regionStrokeActiveStyle:L,patchStrokeStyle:G,resolveRegionStrokeStyle:F,resolveRegionLabelStyle:z,overlayShapes:$,hoveredRegionId:se=null,activeRegionId:le=null,regionLabelStyle:pe,drawAreaTooltip:Te,autoLiftRegionLabelAtMaxZoom:Ee=!1,regionLabelAutoLiftOffsetPx:T,invalidateRef:D,className:ee,style:H}){const V=d.useRef(null),Ce=d.useRef(!1),De=d.useRef(new Map),Pe=d.useRef(t),fe=d.useRef({isDrawing:!1,pointerId:null,start:null,current:null,cursor:null,cursorScreen:null,points:[],screenPoints:[],stampCenter:null}),ce=p??t!=="cursor",I=d.useMemo(()=>w&&w.length>0?w:!y||y.length===0?mr:y.map((u,h)=>({id:h,coordinates:u})),[w,y]),R=d.useMemo(()=>f??mr,[f]),N=d.useMemo(()=>{const u=[];for(let h=0;h<I.length;h+=1){const M=I[h],x=Er(M.coordinates);x.length!==0&&u.push({region:M,regionIndex:h,regionKey:M.id??h,polygons:x})}return u},[I]),re=d.useMemo(()=>{const u=[];for(let h=0;h<R.length;h+=1){const M=R[h],x=Er(M.coordinates);x.length!==0&&u.push({region:M,regionIndex:h,regionKey:M.id??h,polygons:x})}return u},[R]),q=d.useMemo(()=>Hr(v),[v]),he=d.useMemo(()=>Rt(q,U),[q,U]),Se=d.useMemo(()=>Rt(q,L),[q,L]),te=d.useMemo(()=>Rt(Uo,G),[G]),Z=d.useMemo(()=>Go(A),[A]),ie=d.useMemo(()=>Nn(pe),[pe]),de=d.useMemo(()=>Jo(Te),[Te]),ne=d.useMemo(()=>zo(o),[o]),Y=d.useMemo(()=>Yo(s),[s]),be=d.useMemo(()=>({position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",touchAction:"none",pointerEvents:ce?"auto":"none",cursor:ce?t==="brush"?"none":"crosshair":"default",...H}),[ce,t,H]),me=d.useCallback(()=>{const u=V.current;if(!u)return;const h=u.getBoundingClientRect(),M=Math.max(1,window.devicePixelRatio||1),x=Math.max(1,Math.round(h.width*M)),C=Math.max(1,Math.round(h.height*M));(u.width!==x||u.height!==C)&&(u.width=x,u.height=C)},[]),K=d.useCallback(u=>{const h=a.current;if(!h||u.length===0)return[];const M=new Array(u.length);for(let x=0;x<u.length;x+=1){const C=gt(h.worldToScreen(u[x][0],u[x][1]));if(!C)return[];M[x]=C}return M},[a]),Me=d.useCallback(u=>{const h=a.current,M=V.current;if(!h||!M)return null;const x=M.getBoundingClientRect(),C=gt(h.screenToWorld(x.left+u[0],x.top+u[1]));return C?Wt(C,e,n):null},[a,e,n]),ve=d.useCallback(()=>{const u=a.current,h=u?.getViewState?.().rotationDeg??0;if(!(Math.abs(h%360)<.01||!u))return{worldToScreen:(M,x)=>gt(u.worldToScreen(M,x)),screenToWorld:Me}},[a,Me]),Xe=d.useCallback(u=>{if(!Number.isFinite(u)||u<=0)return 0;const h=typeof r=="number"&&Number.isFinite(r)&&r>0?r:1,M=typeof i=="number"&&Number.isFinite(i)?i:0,x=a.current?.getViewState?.().zoom,C=typeof x=="number"&&Number.isFinite(x)&&x>0?x:1,X=M+Math.log2(C),k=Math.max(1e-9,Ln(h,M,X));return u/k/C},[r,i,a]),Ye=d.useCallback((u,h)=>{if(!h)return[];let M=0;if(u==="stamp-rectangle-4096px"){const X=ne.rectanglePixelSize*.5;return yr(h,X,ve()).map(k=>Wt(k,e,n))}if(u==="stamp-rectangle"||u==="stamp-rectangle-2mm2"?M=u==="stamp-rectangle-2mm2"?Wr:ne.rectangleAreaMm2:(u==="stamp-circle"||u==="stamp-circle-2mm2"||u==="stamp-circle-hpf-0.2mm2")&&(M=u==="stamp-circle-hpf-0.2mm2"?po:u==="stamp-circle-2mm2"?Vr:ne.circleAreaMm2),!Number.isFinite(M)||M<=0)return[];const x=Wo(M);let C=[];if(u==="stamp-rectangle"||u==="stamp-rectangle-2mm2"){const X=Xe(Math.sqrt(x)*.5);C=yr(h,X,ve())}else if(u==="stamp-circle"||u==="stamp-circle-2mm2"||u==="stamp-circle-hpf-0.2mm2"){const X=Xe(Math.sqrt(x/Math.PI));C=Vo(h,X)}return C.length?C.map(X=>Wt(X,e,n)):[]},[Xe,e,n,ne,ve]),Fe=d.useCallback(()=>{const u=fe.current;return Yt(t)?Ye(t,u.stampCenter):t==="brush"?[]:u.isDrawing?t==="freehand"?u.points:t==="rectangle"?an(u.start,u.current,ve()):t==="circular"?Tn(u.start,u.current):[]:[]},[t,Ye,ve]),Ae=d.useCallback(u=>{const h=fe.current;if(!h.isDrawing||h.screenPoints.length===0)return;const M=h.screenPoints;if(M.length===0)return;const x=Y.radius;if(!(!Number.isFinite(x)||x<=0)){if(u.save(),u.globalAlpha=Y.fillOpacity,u.fillStyle=Y.fillColor,u.strokeStyle=Y.fillColor,u.lineCap="round",u.lineJoin="round",u.lineWidth=x*2,M.length===1)u.beginPath(),u.arc(M[0][0],M[0][1],x,0,Math.PI*2),u.fill();else{u.beginPath(),u.moveTo(M[0][0],M[0][1]);for(let C=1;C<M.length;C+=1)u.lineTo(M[C][0],M[C][1]);u.stroke()}u.restore()}},[Y]),J=d.useCallback(u=>{const h=fe.current,M=h.cursor;if(!M)return;const x=h.cursorScreen??gt(a.current?.worldToScreen(M[0],M[1])??[]);if(!x)return;const C=Y.radius;!Number.isFinite(C)||C<=0||(u.save(),u.beginPath(),u.arc(x[0],x[1],C,0,Math.PI*2),u.strokeStyle=h.isDrawing?Y.cursorActiveColor:Y.cursorColor,u.lineWidth=Y.cursorLineWidth,u.setLineDash(Y.cursorLineDash),u.stroke(),u.setLineDash(_t),u.restore())},[a,Y]),je=d.useCallback(()=>{me();const u=V.current;if(!u)return;const h=u.getContext("2d");if(!h)return;const M=Math.max(1,window.devicePixelRatio||1),x=u.width/M,C=u.height/M;if(h.setTransform(1,0,0,1,0,0),h.clearRect(0,0,u.width,u.height),h.setTransform(M,0,0,M,0,0),N.length>0)for(const k of N){const{region:oe,polygons:Q,regionIndex:W,regionKey:ge}=k,ye=Ar(le,ge)?"active":Ar(se,ge)?"hover":"default";let Oe=ye==="active"?Se:ye==="hover"?he:q;if(F){const Ie=F({region:oe,regionId:ge,regionIndex:W,state:ye});Oe=Rt(Oe,Ie||void 0)}const _e=ye==="default"?null:Qo(Oe);for(const Ie of Q){const $e=K(Ie.outer);$e.length>=4&&(_e&&Ze(h,$e,_e,!0,!1),Ze(h,$e,Oe,!0,!1));for(const Je of Ie.holes){const Ue=K(Je);Ue.length>=4&&(_e&&Ze(h,Ue,_e,!0,!1),Ze(h,Ue,Oe,!0,!1))}}}if(re.length>0)for(const k of re)for(const oe of k.polygons){const Q=K(oe.outer);Q.length>=4&&Ze(h,Q,te,!0,!1);for(const W of oe.holes){const ge=K(W);ge.length>=4&&Ze(h,ge,te,!0,!1)}}if(Array.isArray($)&&$.length>0){const k=!!globalThis.__OPEN_PLANT_DEBUG_OVERLAY__,oe=K(Ne([[0,0],[e,0],[e,n],[0,n]]));for(let Q=0;Q<$.length;Q+=1){const W=$[Q];if(!W?.coordinates?.length||W.visible===!1)continue;const ge=W.closed??Ho(W.coordinates),ye=Tr(W.coordinates,ge);if(W.invertedFill?.fillColor){const _e=[],Ie=Tr(W.coordinates,!0);for(const $e of Ie){const Je=K($e);Je.length>=4&&_e.push(Je)}if(k){const $e=String(W.id??Q),Je=`${oe.length}|${Ie.length}|${_e.length}|${W.invertedFill.fillColor}`;De.current.get($e)!==Je&&(De.current.set($e,Je),console.debug("[open-plant] invertedFill",{id:W.id??Q,outerRingPoints:oe.length,sourceRingCount:Ie.length,holeRingCount:_e.length,fillColor:W.invertedFill.fillColor}))}Zo(h,oe,_e,W.invertedFill.fillColor)}if(ye.length===0)continue;const Oe=Rt(q,W.stroke??W.strokeStyle);for(const _e of ye){const Ie=K(_e);Ie.length<2||Ze(h,Ie,Oe,ge,W.fill??!1)}}}const X=Fe();if(ce){if(t==="brush")Ae(h),J(h);else if(X.length>0)if(t==="freehand"){const k=K(X);k.length>=2&&Ze(h,k,q,!1,!1),k.length>=3&&Ze(h,K(Ne(X)),q,!0,!0,Z)}else{const k=K(X);k.length>=4&&Ze(h,k,q,!0,!0,Z)}}if(N.length>0){const k=Math.max(1e-6,a.current?.getViewState?.().zoom??1),oe=typeof T=="number"&&Number.isFinite(T)?Math.max(0,T):Gr(Ee,k,a.current?.getZoomRange?.());for(const Q of N){if(!Q.region.label)continue;const W=ts(Q.polygons);if(!W)continue;const ge=gt(a.current?.worldToScreen(W[0],W[1])??[]);if(!ge)continue;let ye=$r(ie,z?.({region:Q.region,regionId:Q.regionKey,regionIndex:Q.regionIndex,zoom:k}));oe>0&&(ye={...ye,offsetY:ye.offsetY+oe}),ns(h,Q.region.label,ge,x,C,ye)}}if(de.enabled&&ce&&(t==="freehand"||t==="rectangle"||t==="circular")){const k=fe.current;if(k.isDrawing){const oe=t==="freehand"?Ne(X):X;if(oe.length>=4){const Q=tn(oe),W=typeof r=="number"&&Number.isFinite(r)&&r>0?r:0,ge=W>0?Q*W*W/(sn*sn):0;let ye=Cn(ge);try{ye=de.format(ge)}catch{ye=Cn(ge)}const Oe=k.cursorScreen??(k.current?gt(a.current?.worldToScreen(k.current[0],k.current[1])??[]):null);Oe&&rs(h,ye,Oe,x,C,de.style,de.cursorOffsetX,de.cursorOffsetY)}}}},[ce,t,Fe,Ae,J,me,K,e,n,a,N,$,se,le,q,he,Se,Z,re,te,F,z,ie,de,Ee,T,r]),O=d.useCallback(()=>{Ce.current||(Ce.current=!0,requestAnimationFrame(()=>{Ce.current=!1,je()}))},[je]),xe=d.useCallback((u=!1)=>{const h=fe.current,M=V.current;if(M&&h.pointerId!==null&&M.hasPointerCapture(h.pointerId))try{M.releasePointerCapture(h.pointerId)}catch{}h.isDrawing=!1,h.pointerId=null,h.start=null,h.current=null,h.points=[],h.screenPoints=[],h.stampCenter=null,u||(h.cursor=null,h.cursorScreen=null)},[]),ue=d.useCallback(u=>{const h=a.current;if(!h||e<=0||n<=0)return null;const M=gt(h.screenToWorld(u.clientX,u.clientY));return M?Wt(M,e,n):null},[a,e,n]),we=d.useCallback(u=>{const h=V.current;if(!h)return null;const M=h.getBoundingClientRect(),x=qe(u.clientX-M.left,0,M.width),C=qe(u.clientY-M.top,0,M.height);return!Number.isFinite(x)||!Number.isFinite(C)?null:[x,C]},[]),Et=d.useCallback(()=>{const u=fe.current;if(!u.isDrawing){xe(!0),O();return}let h=[];if(t==="freehand")u.points.length>=fo&&(h=Ne(u.points));else if(t==="rectangle")h=an(u.start,u.current,ve());else if(t==="circular")h=Tn(u.start,u.current);else if(t==="brush"){const M=u.points[u.points.length-1]??u.current??u.start;if(Y.clickSelectRoi&&M&&u.points.length<=1&&c?.(M)){xe(!0),O();return}const x=Y.edgeDetail,C=Math.max(_o,Y.radius*2/(Fo*x)),X=u.screenPoints.length>0?u.screenPoints:K(u.points),k=no(X,{radius:Y.radius,minRasterStep:C,circleSides:Math.max(24,Math.round(64*x)),simplifyTolerance:C*.25,smoothingPasses:Y.edgeSmoothing}),oe=[];for(const Q of k){const W=Me(Q);W&&oe.push(W)}h=Ne(oe)}(t==="freehand"||t==="rectangle"||t==="circular"||t==="brush")&&Mr(h)&&l&&l({tool:t,intent:t==="brush"?"brush":"roi",coordinates:h,bbox:Sr(h),areaPx:tn(h)}),xe(!0),O()},[t,l,xe,O,K,Me,ve,Y.radius,Y.edgeDetail,Y.edgeSmoothing,Y.clickSelectRoi,c]),tt=d.useCallback((u,h)=>{const M=Ye(u,h);if(!Mr(M))return;const x=u==="stamp-rectangle-4096px"?"patch":"roi",C={tool:u,intent:x,coordinates:M,bbox:Sr(M),areaPx:tn(M)};l?.(C),x==="patch"&&m&&m(C)},[Ye,l,m]),wt=d.useCallback((u,h,M)=>{const x=pr*pr,C=u.screenPoints[u.screenPoints.length-1];if(!C){u.points.push(h),u.screenPoints.push(M),u.current=h;return}const X=M[0]-C[0],k=M[1]-C[1];X*X+k*k>=x?(u.points.push(h),u.screenPoints.push(M)):(u.points[u.points.length-1]=h,u.screenPoints[u.screenPoints.length-1]=M),u.current=h},[]),Bt=d.useCallback(u=>{if(!ce||t==="cursor"||u.button!==0)return;const h=ue(u);if(!h)return;const M=we(u);if(!M)return;if(u.preventDefault(),u.stopPropagation(),Yt(t)){const X=fe.current;X.stampCenter=h,tt(t,h),O();return}const x=V.current;x&&x.setPointerCapture(u.pointerId);const C=fe.current;C.isDrawing=!0,C.pointerId=u.pointerId,C.start=h,C.current=h,C.cursor=h,C.cursorScreen=M,C.points=t==="freehand"||t==="brush"?[h]:[],C.screenPoints=t==="brush"?[M]:[],O()},[ce,t,ue,we,tt,O]),lt=d.useCallback(u=>{if(!ce||t==="cursor")return;const h=ue(u);if(!h)return;const M=we(u);if(!M)return;const x=fe.current;if(x.cursor=h,x.cursorScreen=M,Yt(t)){x.stampCenter=h,u.preventDefault(),u.stopPropagation(),O();return}if(t==="brush"){if(!x.isDrawing||x.pointerId!==u.pointerId){O();return}u.preventDefault(),u.stopPropagation(),wt(x,h,M),O();return}if(!(!x.isDrawing||x.pointerId!==u.pointerId)){if(u.preventDefault(),u.stopPropagation(),t==="freehand"){const C=a.current,X=Math.max(1e-6,C?.getViewState?.().zoom??1),k=ho/X,oe=k*k,Q=x.points[x.points.length-1];if(!Q)x.points.push(h);else{const W=h[0]-Q[0],ge=h[1]-Q[1];W*W+ge*ge>=oe&&x.points.push(h)}}else x.current=h;O()}},[ce,t,ue,we,O,a,wt]),Re=d.useCallback(u=>{const h=fe.current;if(!h.isDrawing||h.pointerId!==u.pointerId)return;u.preventDefault(),u.stopPropagation();const M=ue(u),x=we(u);M&&(h.cursor=M,x&&(h.cursorScreen=x),t==="brush"?x&&wt(h,M,x):h.current=M);const C=V.current;if(C&&C.hasPointerCapture(u.pointerId))try{C.releasePointerCapture(u.pointerId)}catch{}Et()},[Et,ue,we,t,wt]),Lt=d.useCallback(()=>{const u=fe.current;let h=!1;t==="brush"&&!u.isDrawing&&u.cursor&&(u.cursor=null,u.cursorScreen=null,h=!0),Yt(t)&&u.stampCenter&&(u.stampCenter=null,h=!0),h&&O()},[t,O]);return d.useEffect(()=>{me(),O();const u=V.current;if(!u)return;const h=new ResizeObserver(()=>{me(),O()});return h.observe(u),()=>{h.disconnect()}},[me,O]),d.useEffect(()=>{ce||xe(),O()},[ce,O,xe]),d.useEffect(()=>{Pe.current!==t&&(Pe.current=t,xe(),O())},[t,xe,O]),d.useEffect(()=>{O()},[b,I,$,O]),d.useEffect(()=>{if(D)return D.current=O,()=>{D.current===O&&(D.current=null)}},[D,O]),d.useEffect(()=>{if(!ce)return;const u=h=>{h.key==="Escape"&&(xe(),O())};return window.addEventListener("keydown",u),()=>{window.removeEventListener("keydown",u)}},[ce,xe,O]),He.jsx("canvas",{ref:V,className:ee,style:be,onPointerDown:Bt,onPointerMove:lt,onPointerUp:Re,onPointerCancel:Re,onPointerLeave:Lt,onContextMenu:u=>{ce&&u.preventDefault()},onWheel:u=>{if(!ce)return;const h=V.current,M=a.current;if(!h||typeof M?.zoomBy!="function")return;u.preventDefault(),u.stopPropagation();const x=h.getBoundingClientRect(),C=u.clientX-x.left,X=u.clientY-x.top;M.zoomBy(u.deltaY<0?bo:wo,C,X),O()}})}function Cr(t){return String(t??"").replace(/\/+$/,"")}function jr(t){const e=String(t??"");return e.startsWith("/")?e:`/${e}`}function is(t){const e=Cr(t);if(!e)return"";if(/\/TileGroup\d+$/i.test(e))return e;let n=null;try{n=new URL(e)}catch{n=null}if(n){const r=`${n.protocol}//${n.host}`,i=Cr(n.pathname||"");return/\/ims$/i.test(i)?`${r}${i}`:/\/tiles$/i.test(i)?`${r}${i}`:`${r}${i}/tiles`}return/\/ims$/i.test(e)?"/ims":/\/tiles$/i.test(e)?`${e}`:`${e}/tiles`}function os(t,e){const n=t?.imsInfo||{},r=!!t?.imsInfo,i=Number(n.width??t?.width??0),o=Number(n.height??t?.height??0),s=Number(n.tileSize??t?.tileSize??0),a=Number(n.zoom??t?.zoom??0),c=String(n.path??t?.path??""),l=Number(n.mpp??t?.mpp??0);if(!i||!o||!s||!c)throw new Error("이미지 메타데이터가 불완전합니다. width/height/tileSize/path 확인 필요");const m=Array.isArray(t?.terms)?t.terms.map(f=>({termId:String(f?.termId??""),termName:String(f?.termName??""),termColor:String(f?.termColor??"")})):[],p=jr(c),b=is(e),w=r?(f,y,A)=>`${b}${p}/${f}/${A}_${y}.webp`:void 0;return{id:t?._id||"unknown",name:t?.name||"unknown",width:i,height:o,mpp:Number.isFinite(l)&&l>0?l:void 0,tileSize:s,maxTierZoom:Number.isFinite(a)?Math.max(0,Math.floor(a)):0,tilePath:c,tileBaseUrl:e,terms:m,tileUrlBuilder:w}}function zn(t,e,n,r){if(t.tileUrlBuilder)return t.tileUrlBuilder(e,n,r);const i=jr(t.tilePath);return`${t.tileBaseUrl}${i}/${e}/${r}_${n}.webp`}const Le={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 Rr(t,e,n,r){const i=e.length;if(i===4){for(let o=0;o<i;o+=1){const s=e[o],a=e[(o+1)%i],c=Math.hypot(a[0]-s[0],a[1]-s[1]);if(c<1e-6)continue;const l=Math.max(1,Math.round((c+r)/(n+r))),m=l*n+(l-1)*r,p=c/Math.max(1e-6,m),b=n*p,w=r*p;t.beginPath(),t.moveTo(s[0],s[1]),t.lineTo(a[0],a[1]),t.setLineDash([b,w]),t.lineDashOffset=0,t.stroke()}t.setLineDash([]),t.lineDashOffset=0}}function xt(t,e,n=1){return typeof t!="number"||!Number.isFinite(t)?e:Math.max(n,t)}function Vt(t){return Array.isArray(t)&&t.length===4&&Number.isFinite(t[0])&&Number.isFinite(t[1])&&Number.isFinite(t[2])&&Number.isFinite(t[3])}const 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 Jr({source:t,projectorRef:e,authToken:n="",options:r,invalidateRef:i,className:o,style:s}){const a=d.useRef(null),c=d.useRef(null),l=d.useRef(null),m=d.useRef({active:!1,pointerId:null}),p=d.useRef(null),b=d.useRef(!1),w=xt(r?.width,Le.width,64),f=xt(r?.height,Le.height,48),y=d.useMemo(()=>{const I=Math.max(1,t.width),R=Math.max(1,t.height),N=I/R,re=w/f;let q,he;return N>re?(q=w,he=w/N):(he=f,q=f*N),{x:(w-q)/2,y:(f-he)/2,w:q,h:he}},[t.width,t.height,w,f]),A=xt(r?.margin,Le.margin,0),v=xt(r?.borderRadius,Le.borderRadius,0),U=xt(r?.borderWidth,Le.borderWidth,0),L=Math.max(1,Math.round(xt(r?.maxThumbnailTiles,Le.maxThumbnailTiles,1))),G=r?.backgroundColor||Le.backgroundColor,F=r?.borderColor||Le.borderColor,z=r?.viewportBorderColor||Le.viewportBorderColor,$=r?.viewportBorderStyle==="stroke"||r?.viewportBorderStyle==="dash"?r.viewportBorderStyle:Le.viewportBorderStyle,se=r?.viewportFillColor??Le.viewportFillColor,le=r?.interactive??Le.interactive,pe=r?.showThumbnail??Le.showThumbnail,Te=r?.position||Le.position,Ee=r?.onClose,T=r?.closeIcon,D=r?.closeButtonStyle,ee=d.useMemo(()=>{const I={};return Te==="top-left"||Te==="bottom-left"?I.left=A:I.right=A,Te==="top-left"||Te==="top-right"?I.top=A:I.bottom=A,{position:"absolute",...I,width:w,height:f,borderRadius:v,overflow:"hidden",zIndex:4,pointerEvents:le?"auto":"none",touchAction:"none",boxShadow:"0 10px 22px rgba(0, 0, 0, 0.3)",...s}},[A,Te,w,f,v,le,s]),H=d.useCallback(()=>{const I=a.current;if(!I)return;const R=I.getContext("2d");if(!R)return;const N=w,re=f,q=Math.max(1,window.devicePixelRatio||1),he=Math.max(1,Math.round(N*q)),Se=Math.max(1,Math.round(re*q));(I.width!==he||I.height!==Se)&&(I.width=he,I.height=Se),R.setTransform(1,0,0,1,0,0),R.clearRect(0,0,I.width,I.height),R.setTransform(q,0,0,q,0,0),R.fillStyle=G,R.fillRect(0,0,N,re);const{x:te,y:Z,w:ie,h:de}=y,ne=c.current;ne&&R.drawImage(ne,te,Z,ie,de),R.strokeStyle=F,R.lineWidth=U,R.strokeRect(U*.5,U*.5,N-U,re-U);const Y=e.current,be=Y?.getViewBounds?.(),me=Y?.getViewCorners?.(),K=Vt(be)?be:Vt(l.current)?l.current:null;if(!K)return;l.current=K;const Me=ie/Math.max(1,t.width),ve=de/Math.max(1,t.height),Xe=Array.isArray(me)&&me.length>=4&&me.every(ue=>Array.isArray(ue)&&ue.length>=2&&Number.isFinite(ue[0])&&Number.isFinite(ue[1]))?me:null,Ye=$==="dash";if(Xe){const ue=Xe.map(we=>[te+we[0]*Me,Z+we[1]*ve]);R.save(),R.beginPath(),R.rect(te,Z,ie,de),R.clip(),R.beginPath();for(let we=0;we<ue.length;we+=1)we===0?R.moveTo(ue[we][0],ue[we][1]):R.lineTo(ue[we][0],ue[we][1]);R.closePath(),R.fillStyle=se,R.fill(),R.strokeStyle=z,R.lineWidth=2.25,Ye?Rr(R,ue,4,3):R.stroke(),R.restore();return}const Fe=ae(te+K[0]*Me,te,te+ie),Ae=ae(Z+K[1]*ve,Z,Z+de),J=ae(te+K[2]*Me,te,te+ie),je=ae(Z+K[3]*ve,Z,Z+de),O=Math.max(1,J-Fe),xe=Math.max(1,je-Ae);if(R.fillStyle=se,R.fillRect(Fe,Ae,O,xe),R.strokeStyle=z,R.lineWidth=2.25,Ye){const ue=[[Fe+.5,Ae+.5],[Fe+.5+Math.max(1,O-1),Ae+.5],[Fe+.5+Math.max(1,O-1),Ae+.5+Math.max(1,xe-1)],[Fe+.5,Ae+.5+Math.max(1,xe-1)]];Rr(R,ue,4,3)}else R.strokeRect(Fe+.5,Ae+.5,Math.max(1,O-1),Math.max(1,xe-1))},[w,f,y,G,F,U,e,t.width,t.height,se,z,$]),V=d.useCallback(()=>{b.current||(b.current=!0,p.current=requestAnimationFrame(()=>{b.current=!1,p.current=null,H()}))},[H]),Ce=d.useCallback((I,R)=>{const N=a.current;if(!N)return null;const re=N.getBoundingClientRect();if(!re.width||!re.height)return null;const q=re.width/w,he=re.height/f,Se=y.x*q,te=y.y*he,Z=y.w*q,ie=y.h*he,de=ae((I-re.left-Se)/Z,0,1),ne=ae((R-re.top-te)/ie,0,1);return[de*t.width,ne*t.height]},[t.width,t.height,w,f,y]),De=d.useCallback((I,R)=>{const N=e.current;if(!N)return;if(N.setViewCenter){N.setViewCenter(I,R),V();return}const re=N.getViewBounds?.(),q=Vt(re)?re:Vt(l.current)?l.current:null;if(!q)return;const he=Math.max(1e-6,q[2]-q[0]),Se=Math.max(1e-6,q[3]-q[1]);N.setViewState({offsetX:I-he*.5,offsetY:R-Se*.5}),V()},[e,V]),Pe=d.useCallback(I=>{if(!le||I.button!==0)return;const R=a.current;if(!R)return;const N=Ce(I.clientX,I.clientY);N&&(I.preventDefault(),I.stopPropagation(),R.setPointerCapture(I.pointerId),m.current={active:!0,pointerId:I.pointerId},De(N[0],N[1]))},[le,Ce,De]),fe=d.useCallback(I=>{const R=m.current;if(!R.active||R.pointerId!==I.pointerId)return;const N=Ce(I.clientX,I.clientY);N&&(I.preventDefault(),I.stopPropagation(),De(N[0],N[1]))},[Ce,De]),ce=d.useCallback(I=>{const R=m.current;if(!R.active||R.pointerId!==I.pointerId)return;const N=a.current;if(N&&N.hasPointerCapture(I.pointerId))try{N.releasePointerCapture(I.pointerId)}catch{}m.current={active:!1,pointerId:null},V()},[V]);return d.useEffect(()=>{let I=!1;c.current=null,V();const R=0,N=2**(t.maxTierZoom-R),re=Math.ceil(t.width/N),q=Math.ceil(t.height/N),he=Math.max(1,Math.ceil(re/t.tileSize)),Se=Math.max(1,Math.ceil(q/t.tileSize)),te=he*Se;if(!pe||te>L)return;const Z=document.createElement("canvas");Z.width=Math.max(1,Math.round(y.w)),Z.height=Math.max(1,Math.round(y.h));const ie=Z.getContext("2d");if(!ie)return;ie.fillStyle=G,ie.fillRect(0,0,Z.width,Z.height);const de=[];for(let ne=0;ne<Se;ne+=1)for(let Y=0;Y<he;Y+=1){const be=Y*t.tileSize*N,me=ne*t.tileSize*N,K=Math.min((Y+1)*t.tileSize,re)*N,Me=Math.min((ne+1)*t.tileSize,q)*N;de.push({url:zn(t,R,Y,ne),bounds:[be,me,K,Me]})}return Promise.allSettled(de.map(async ne=>{const Y=!!n,be=await fetch(ne.url,{headers:Y?{Authorization:n}:void 0});if(!be.ok)throw new Error(`HTTP ${be.status}`);const me=await createImageBitmap(await be.blob());return{tile:ne,bitmap:me}})).then(ne=>{if(I){for(const me of ne)me.status==="fulfilled"&&me.value.bitmap.close();return}const Y=Z.width/Math.max(1,t.width),be=Z.height/Math.max(1,t.height);for(const me of ne){if(me.status!=="fulfilled")continue;const{tile:{bounds:K},bitmap:Me}=me.value,ve=K[0]*Y,Xe=K[1]*be,Ye=Math.max(1,(K[2]-K[0])*Y),Fe=Math.max(1,(K[3]-K[1])*be);ie.drawImage(Me,ve,Xe,Ye,Fe),Me.close()}c.current=Z,V()}),()=>{I=!0}},[t,n,y,G,pe,L,V]),d.useEffect(()=>{V()},[V]),d.useEffect(()=>{if(i)return i.current=V,()=>{i.current===V&&(i.current=null)}},[i,V]),d.useEffect(()=>()=>{m.current={active:!1,pointerId:null},p.current!==null&&(cancelAnimationFrame(p.current),p.current=null),b.current=!1},[]),He.jsxs("div",{className:o,style:ee,children:[He.jsx("canvas",{ref:a,style:{width:"100%",height:"100%",display:"block",borderRadius:"inherit"},onPointerDown:Pe,onPointerMove:fe,onPointerUp:ce,onPointerCancel:ce,onContextMenu:I=>{I.preventDefault()},onWheel:I=>{I.preventDefault(),I.stopPropagation()}}),Ee&&He.jsx("button",{type:"button","aria-label":"Hide overview map",onClick:I=>{I.stopPropagation(),Ee()},style:D?{...D}:{...ss},children:T??"×"})]})}function as({imageWidth:t,imageHeight:e,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 l=s.current;if(!l)return;const m=new Lr({canvas:l,imageWidth:t,imageHeight:e,initialViewState:r});return a.current=m,m.setTiles(n),()=>{m.destroy(),a.current=null}},[t,e]),d.useEffect(()=>{const l=a.current;l&&l.setTiles(n)},[n]),d.useEffect(()=>{const l=a.current;!l||!r||l.setViewState(r)},[r]),He.jsx("canvas",{ref:s,className:i,style:c})}function Qr(t){const e=t.fillModes instanceof Uint8Array?t.fillModes.length:Number.MAX_SAFE_INTEGER;return Math.max(0,Math.min(Math.floor(t.count??0),Math.floor((t.positions?.length??0)/2),t.paletteIndices?.length??0,e))}function Ft(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return null;const n=Ut(e??[]);if(n.length===0){const f={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return t.fillModes instanceof Uint8Array&&(f.fillModes=new Uint8Array(0)),t.ids instanceof Uint32Array&&(f.ids=new Uint32Array(0)),f}const r=Qr(t),i=t.positions,o=t.paletteIndices,s=t.fillModes instanceof Uint8Array&&t.fillModes.length>=r?t.fillModes:null,a=t.ids instanceof Uint32Array&&t.ids.length>=r?t.ids:null,c=new Float32Array(r*2),l=new Uint16Array(r),m=s?new Uint8Array(r):null,p=a?new Uint32Array(r):null;let b=0;for(let f=0;f<r;f+=1){const y=i[f*2],A=i[f*2+1];on(y,A,n)&&(c[b*2]=y,c[b*2+1]=A,l[b]=o[f],m&&(m[b]=s[f]),p&&(p[b]=a[f]),b+=1)}const w={count:b,positions:c.subarray(0,b*2),paletteIndices:l.subarray(0,b)};return m&&(w.fillModes=m.subarray(0,b)),p&&(w.ids=p.subarray(0,b)),w}function ei(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return new Uint32Array(0);const n=Ut(e??[]);if(n.length===0)return new Uint32Array(0);const r=Qr(t);if(r===0)return new Uint32Array(0);const i=t.positions,o=new Uint32Array(r);let s=0;for(let a=0;a<r;a+=1){const c=i[a*2],l=i[a*2+1];on(c,l,n)&&(o[s]=a,s+=1)}return o.subarray(0,s)}let Gt=null;const cs=`
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=`
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 t=navigator;return typeof t.gpu=="object"&&t.gpu!==null}function ti(){if(!us())return null;const e=navigator.gpu;if(!e||typeof e!="object")return null;const n=e;return typeof n.requestAdapter!="function"?null:n}const Ht=globalThis.GPUShaderStage?.COMPUTE??4,wn=globalThis.GPUBufferUsage?.STORAGE??128,qt=globalThis.GPUBufferUsage?.COPY_DST??8,ls=globalThis.GPUBufferUsage?.COPY_SRC??4,fs=globalThis.GPUBufferUsage?.UNIFORM??64,hs=globalThis.GPUBufferUsage?.MAP_READ??1,ds=globalThis.GPUMapMode?.READ??1;async function ms(){const t=ti();if(!t)return{supported:!1,features:[]};const e=await t.requestAdapter();return e?{supported:!0,adapterName:e.info?.description??e.info?.vendor??"unknown",features:Array.from(e.features),limits:{maxStorageBufferBindingSize:Number(e.limits.maxStorageBufferBindingSize),maxComputeInvocationsPerWorkgroup:Number(e.limits.maxComputeInvocationsPerWorkgroup),maxComputeWorkgroupSizeX:Number(e.limits.maxComputeWorkgroupSizeX)}}:{supported:!1,features:[]}}async function gs(){return Gt||(Gt=(async()=>{const t=ti();if(!t)return null;const e=await t.requestAdapter();if(!e)return null;const n=await e.requestDevice(),r=n.createBindGroupLayout({entries:[{binding:0,visibility:Ht,buffer:{type:"read-only-storage"}},{binding:1,visibility:Ht,buffer:{type:"read-only-storage"}},{binding:2,visibility:Ht,buffer:{type:"storage"}},{binding:3,visibility:Ht,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}})(),Gt)}function $t(t,e){return Math.ceil(t/e)*e}async function ni(t,e,n){const r=await gs();if(!r)return null;const i=Math.max(0,Math.floor(e)),o=Math.max(0,Math.floor(n.length/4));if(i===0||o===0)return new Uint32Array(0);const s=Math.min(i,Math.floor(t.length/2));if(s===0)return new Uint32Array(0);const a=s*2*Float32Array.BYTES_PER_ELEMENT,c=o*4*Float32Array.BYTES_PER_ELEMENT,l=s*Uint32Array.BYTES_PER_ELEMENT,m=Number(r.device.limits.maxStorageBufferBindingSize);if(a>m||c>m||l>m)return null;const p=r.device.createBuffer({size:$t(a,4),usage:wn|qt}),b=r.device.createBuffer({size:$t(c,4),usage:wn|qt}),w=r.device.createBuffer({size:$t(l,4),usage:wn|ls}),f=r.device.createBuffer({size:16,usage:fs|qt}),y=r.device.createBuffer({size:$t(l,4),usage:qt|hs});r.device.queue.writeBuffer(p,0,t.buffer,t.byteOffset,a),r.device.queue.writeBuffer(b,0,n.buffer,n.byteOffset,c),r.device.queue.writeBuffer(f,0,new Uint32Array([s,o,0,0]));const A=r.device.createBindGroup({layout:r.bindGroupLayout,entries:[{binding:0,resource:{buffer:p}},{binding:1,resource:{buffer:b}},{binding:2,resource:{buffer:w}},{binding:3,resource:{buffer:f}}]}),v=r.device.createCommandEncoder(),U=v.beginComputePass();U.setPipeline(r.pipeline),U.setBindGroup(0,A),U.dispatchWorkgroups(Math.ceil(s/256)),U.end(),v.copyBufferToBuffer(w,0,y,0,l),r.device.queue.submit([v.finish()]),await y.mapAsync(ds);const L=y.getMappedRange(),G=new Uint32Array(L.slice(0));return y.unmap(),p.destroy(),b.destroy(),w.destroy(),f.destroy(),y.destroy(),G}function et(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}async function ri(t,e,n={}){const r=et(),i=n.bridgeToDraw===!0;if(!t||!t.count||!t.positions||!t.paletteIndices)return{data:null,meta:{mode:"hybrid-webgpu",durationMs:et()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}};const o=Ut(e??[]);if(o.length===0){const F={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return t.fillModes instanceof Uint8Array&&(F.fillModes=new Uint8Array(0)),t.ids instanceof Uint32Array&&(F.ids=new Uint32Array(0)),{data:F,meta:{mode:"hybrid-webgpu",durationMs:et()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const s=t.fillModes instanceof Uint8Array?t.fillModes.length:Number.MAX_SAFE_INTEGER,a=Math.max(0,Math.min(t.count,Math.floor(t.positions.length/2),t.paletteIndices.length,s)),c=t.fillModes instanceof Uint8Array&&t.fillModes.length>=a?t.fillModes:null,l=t.ids instanceof Uint32Array&&t.ids.length>=a?t.ids:null;if(a===0){const F={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return c&&(F.fillModes=new Uint8Array(0)),l&&(F.ids=new Uint32Array(0)),{data:F,meta:{mode:"hybrid-webgpu",durationMs:et()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const m=new Float32Array(o.length*4);for(let F=0;F<o.length;F+=1){const z=F*4,$=o[F];m[z]=$.minX,m[z+1]=$.minY,m[z+2]=$.maxX,m[z+3]=$.maxY}let p=null,b=!1;try{p=await ni(t.positions,a,m),b=!!p}catch{p=null,b=!1}if(!p)return{data:Ft(t,e),meta:{mode:"hybrid-webgpu",durationMs:et()-r,usedWebGpu:!1,candidateCount:a,bridgedToDraw:!1}};let w=0;for(let F=0;F<a;F+=1)p[F]===1&&(w+=1);const f=new Uint32Array(w);if(w>0){let F=0;for(let z=0;z<a;z+=1)p[z]===1&&(f[F]=z,F+=1)}if(w===0){if(i){const z={count:a,positions:t.positions.subarray(0,a*2),paletteIndices:t.paletteIndices.subarray(0,a),drawIndices:new Uint32Array(0)};return c&&(z.fillModes=c.subarray(0,a)),l&&(z.ids=l.subarray(0,a)),{data:z,meta:{mode:"hybrid-webgpu",durationMs:et()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!0}}}const F={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return c&&(F.fillModes=new Uint8Array(0)),l&&(F.ids=new Uint32Array(0)),{data:F,meta:{mode:"hybrid-webgpu",durationMs:et()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!1}}}if(i){const F=new Uint32Array(w);let z=0;for(let se=0;se<w;se+=1){const le=f[se]??0,pe=t.positions[le*2],Te=t.positions[le*2+1];on(pe,Te,o)&&(F[z]=le,z+=1)}const $={count:a,positions:t.positions.subarray(0,a*2),paletteIndices:t.paletteIndices.subarray(0,a),drawIndices:F.subarray(0,z)};return c&&($.fillModes=c.subarray(0,a)),l&&($.ids=l.subarray(0,a)),{data:$,meta:{mode:"hybrid-webgpu",durationMs:et()-r,usedWebGpu:!0,candidateCount:w,bridgedToDraw:!0}}}const y=new Float32Array(w*2),A=new Uint16Array(w),v=c?new Uint8Array(w):null,U=l?new Uint32Array(w):null;let L=0;for(let F=0;F<w;F+=1){const z=f[F]??0,$=t.positions[z*2],se=t.positions[z*2+1];on($,se,o)&&(y[L*2]=$,y[L*2+1]=se,A[L]=t.paletteIndices[z],v&&(v[L]=c[z]),U&&(U[L]=l[z]),L+=1)}const G={count:L,positions:y.subarray(0,L*2),paletteIndices:A.subarray(0,L)};return v&&(G.fillModes=v.subarray(0,L)),U&&(G.ids=U.subarray(0,L)),{data:G,meta:{mode:"hybrid-webgpu",durationMs:et()-r,usedWebGpu:!0,candidateCount:w,bridgedToDraw:!1}}}let ze=null,Rn=!0,ii=1;const ut=new Map;function ct(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function oi(){if(!Rn)return null;if(ze)return ze;try{const t=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:Tt&&Tt.tagName.toUpperCase()==="SCRIPT"&&Tt.src||new URL("index.cjs",document.baseURI).href),{type:"module"});return t.addEventListener("message",kn),t.addEventListener("error",Dn),ze=t,t}catch{return Rn=!1,null}}function kn(t){const e=t.data;if(!e)return;const n=ut.get(e.id);if(!n)return;if(ut.delete(e.id),e.type==="roi-clip-failure"){n.reject(new Error(e.error||"worker clip failed"));return}if(e.type==="roi-clip-index-success"){if(n.kind!=="index"){n.reject(new Error("worker response mismatch: expected point data result"));return}const l=Math.max(0,Math.floor(e.count)),m=new Uint32Array(e.indices).subarray(0,l);n.resolve({indices:m,meta:{mode:"worker",durationMs:Number.isFinite(e.durationMs)?e.durationMs:ct()-n.startMs}});return}if(n.kind!=="data"){n.reject(new Error("worker response mismatch: expected index result"));return}const r=Math.max(0,Math.floor(e.count)),i=new Float32Array(e.positions),o=new Uint16Array(e.paletteIndices),s=e.fillModes?new Uint8Array(e.fillModes):null,a=e.ids?new Uint32Array(e.ids):null,c={count:r,positions:i.subarray(0,r*2),paletteIndices:o.subarray(0,r)};s&&(c.fillModes=s.subarray(0,r)),a&&(c.ids=a.subarray(0,r)),n.resolve({data:c,meta:{mode:"worker",durationMs:Number.isFinite(e.durationMs)?e.durationMs:ct()-n.startMs}})}function Dn(){Rn=!1,ze&&(ze.removeEventListener("message",kn),ze.removeEventListener("error",Dn),ze.terminate(),ze=null);for(const[,t]of ut)t.reject(new Error("worker crashed"));ut.clear()}function ps(){if(ze){ze.removeEventListener("message",kn),ze.removeEventListener("error",Dn),ze.terminate(),ze=null;for(const[,t]of ut)t.reject(new Error("worker terminated"));ut.clear()}}async function si(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return{data:null,meta:{mode:"worker",durationMs:0}};const n=oi();if(!n){const p=ct();return{data:Ft(t,e),meta:{mode:"sync",durationMs:ct()-p}}}const r=t.fillModes instanceof Uint8Array?t.fillModes.length:Number.MAX_SAFE_INTEGER,i=Math.max(0,Math.min(t.count,Math.floor(t.positions.length/2),t.paletteIndices.length,r)),o=t.positions.slice(0,i*2),s=t.paletteIndices.slice(0,i),a=t.fillModes instanceof Uint8Array&&t.fillModes.length>=i?t.fillModes.slice(0,i):null,c=t.ids instanceof Uint32Array&&t.ids.length>=i?t.ids.slice(0,i):null,l=ii++,m=ct();return new Promise((p,b)=>{ut.set(l,{kind:"data",resolve:p,reject:b,startMs:m});const w={type:"roi-clip-request",id:l,count:i,positions:o.buffer,paletteIndices:s.buffer,fillModes:a?.buffer,ids:c?.buffer,polygons:e??[]},f=[o.buffer,s.buffer];a&&f.push(a.buffer),c&&f.push(c.buffer),n.postMessage(w,f)})}async function bs(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return{indices:new Uint32Array(0),meta:{mode:"worker",durationMs:0}};const n=oi();if(!n){const c=ct();return{indices:ei(t,e),meta:{mode:"sync",durationMs:ct()-c}}}const r=t.fillModes instanceof Uint8Array?t.fillModes.length:Number.MAX_SAFE_INTEGER,i=Math.max(0,Math.min(t.count,Math.floor(t.positions.length/2),t.paletteIndices.length,r)),o=t.positions.slice(0,i*2),s=ii++,a=ct();return new Promise((c,l)=>{ut.set(s,{kind:"index",resolve:c,reject:l,startMs:a});const m={type:"roi-clip-index-request",id:s,count:i,positions:o.buffer,polygons:e??[]};n.postMessage(m,[o.buffer])})}const nn=-1;function It(t,e,n){return(t*73856093^e*19349663)>>>0&n}function ai(t,e,n){const{hashTable:r,cellKeys:i,hashMask:o}=t;let s=It(e,n,o);for(;;){const a=r[s];if(a===nn)return-1;if(i[a*2]===e&&i[a*2+1]===n)return a;s=s+1&o}}let ke=null,In=!0,ws=1;const bt=new Map;function ys(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function Ss(){if(!In)return null;if(ke)return ke;try{const t=new Worker(new URL(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/point-hit-index-worker-Bp1uxxyQ.js").href:new URL("assets/point-hit-index-worker-Bp1uxxyQ.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),typeof document>"u"?require("url").pathToFileURL(__filename).href:Tt&&Tt.tagName.toUpperCase()==="SCRIPT"&&Tt.src||new URL("index.cjs",document.baseURI).href),{type:"module"});return t.addEventListener("message",On),t.addEventListener("error",Xn),ke=t,t}catch{return In=!1,null}}function Ms(t,e){if(t.safeCount<=0||t.cellCount<=0)return null;const n=t.safeCount;return{cellSize:t.cellSize,safeCount:n,positions:e.positions.subarray(0,n*2),ids:e.ids instanceof Uint32Array&&e.ids.length>=n?e.ids.subarray(0,n):null,hashCapacity:t.hashCapacity,hashMask:t.hashCapacity-1,hashTable:new Int32Array(t.hashTable),cellKeys:new Int32Array(t.cellKeys),cellOffsets:new Uint32Array(t.cellOffsets),cellLengths:new Uint32Array(t.cellLengths),pointIndices:new Uint32Array(t.pointIndices)}}function On(t){const e=t.data;if(!e)return;const n=bt.get(e.id);if(n){if(bt.delete(e.id),e.type==="point-hit-index-failure"){n.reject(new Error(e.error||"worker index build failed"));return}n.resolve(Ms(e,n.pointData))}}function Xn(){In=!1,ke&&(ke.removeEventListener("message",On),ke.removeEventListener("error",Xn),ke.terminate(),ke=null);for(const[,t]of bt)t.reject(new Error("worker crashed"));bt.clear()}function As(){if(ke){ke.removeEventListener("message",On),ke.removeEventListener("error",Xn),ke.terminate(),ke=null;for(const[,t]of bt)t.reject(new Error("worker terminated"));bt.clear()}}const xs=24,Ts=1024,Es=4;function ci(t){const e=t.fillModes instanceof Uint8Array?t.fillModes.length:Number.MAX_SAFE_INTEGER;return Math.max(0,Math.min(Math.floor(t.count??0),Math.floor((t.positions?.length??0)/2),t.paletteIndices?.length??0,e))}function Cs(t,e){const n=ci(t);if(n<=0)return null;const r=t.positions.subarray(0,n*2),i=t.ids instanceof Uint32Array&&t.ids.length>=n?t.ids.subarray(0,n):null;let o=null;if(t.drawIndices instanceof Uint32Array&&t.drawIndices.length>0){const T=t.drawIndices;let D=!0;for(let ee=0;ee<T.length;ee+=1)if(T[ee]>=n){D=!1;break}if(D)o=T;else{const ee=new Uint32Array(T.length);let H=0;for(let V=0;V<T.length;V+=1)T[V]<n&&(ee[H++]=T[V]);o=H>0?ee.subarray(0,H):null}}const s=o?o.length:n;if(s===0)return null;const a=e&&e.width>0&&e.height>0?Math.max(xs,Math.min(Ts,Math.sqrt(Math.max(1,e.width*e.height)/Math.max(1,s))*Es)):256,c=1/a,l=new Int32Array(s),m=new Int32Array(s);let p=0;if(o)for(let T=0;T<s;T+=1){const D=o[T],ee=r[D*2],H=r[D*2+1];!Number.isFinite(ee)||!Number.isFinite(H)||(l[p]=Math.floor(ee*c),m[p]=Math.floor(H*c),p+=1)}else for(let T=0;T<n;T+=1){const D=r[T*2],ee=r[T*2+1];!Number.isFinite(D)||!Number.isFinite(ee)||(l[p]=Math.floor(D*c),m[p]=Math.floor(ee*c),p+=1)}if(p===0)return null;let b=1;for(;b<p;)b<<=1;let w=b-1,f=new Int32Array(b*2),y=new Int32Array(b);f.fill(2147483647);let A=0;const v=new Int32Array(p);for(let T=0;T<p;T+=1){const D=l[T],ee=m[T];let H=It(D,ee,w);for(;;){if(f[H*2]===2147483647){if(f[H*2]=D,f[H*2+1]=ee,y[H]=1,v[T]=H,A+=1,A*4>b*3){const V=b;b<<=1,w=b-1;const Ce=new Int32Array(b*2),De=new Int32Array(b);Ce.fill(2147483647);for(let Pe=0;Pe<V;Pe+=1){if(f[Pe*2]===2147483647)continue;let fe=It(f[Pe*2],f[Pe*2+1],w);for(;Ce[fe*2]!==2147483647;)fe=fe+1&w;Ce[fe*2]=f[Pe*2],Ce[fe*2+1]=f[Pe*2+1],De[fe]=y[Pe]}for(f=Ce,y=De,H=It(D,ee,w);f[H*2]!==D||f[H*2+1]!==ee;)H=H+1&w;v[T]=H}break}if(f[H*2]===D&&f[H*2+1]===ee){y[H]+=1,v[T]=H;break}H=H+1&w}}const U=new Int32Array(A*2),L=new Uint32Array(A),G=new Uint32Array(A),F=new Int32Array(b);F.fill(nn);let z=0,$=0;for(let T=0;T<b;T+=1)f[T*2]!==2147483647&&(U[z*2]=f[T*2],U[z*2+1]=f[T*2+1],L[z]=$,G[z]=y[T],F[T]=z,$+=y[T],z+=1);const se=new Uint32Array(p),le=new Uint32Array(A);if(le.set(L),o)for(let T=0;T<p;T+=1){const D=F[v[T]];se[le[D]++]=o[T]}else{let T=0;for(let D=0;D<n;D+=1){const ee=r[D*2],H=r[D*2+1];if(!Number.isFinite(ee)||!Number.isFinite(H))continue;const V=F[v[T]];se[le[V]++]=D,T+=1}}let pe=1;for(;pe<A*2;)pe<<=1;const Te=pe-1,Ee=new Int32Array(pe);Ee.fill(nn);for(let T=0;T<A;T+=1){let D=It(U[T*2],U[T*2+1],Te);for(;Ee[D]!==nn;)D=D+1&Te;Ee[D]=T}return{cellSize:a,safeCount:n,positions:r,ids:i,hashCapacity:pe,hashMask:Te,hashTable:Ee,cellKeys:U,cellOffsets:L,cellLengths:G,pointIndices:se}}async function ui(t,e){if(!t||!t.positions||!t.paletteIndices)return null;const n=ci(t);if(n<=0)return null;const r=Ss();if(!r)return Cs(t,e);const i=t.positions.slice(0,n*2),o=t.drawIndices instanceof Uint32Array&&t.drawIndices.length>0?t.drawIndices.slice():void 0,s=ws++,a=ys();return new Promise((c,l)=>{bt.set(s,{resolve:c,reject:l,startMs:a,pointData:t});const m={type:"point-hit-index-request",id:s,count:n,positions:i.buffer,drawIndices:o?.buffer,sourceWidth:e?.width??0,sourceHeight:e?.height??0},p=[i.buffer];o&&p.push(o.buffer),r.postMessage(m,p)})}function Rs(t){const e=[];for(let n=0;n<t.length;n+=1){const r=t[n],i=Ut([r?.coordinates]);if(i.length===0)continue;let o=0;for(const s of i)o+=s.area;e.push({regionId:r.id??n,regionIndex:n,polygons:i,area:Math.max(1e-6,o)})}return e}function Is(t,e){if(Array.isArray(e)){const n=e[t];if(typeof n=="string"&&n.length>0)return n}if(e instanceof Map){const n=e.get(t);if(typeof n=="string"&&n.length>0)return n}return String(t)}function li(t,e,n={}){const r=Math.max(0,Math.min(Math.floor(t?.count??0),Math.floor((t?.positions?.length??0)/2),t?.paletteIndices?.length??0,t?.fillModes instanceof Uint8Array?t.fillModes.length:Number.MAX_SAFE_INTEGER));let i=null;if(t?.drawIndices instanceof Uint32Array){const b=t.drawIndices;let w=b.length;for(let f=0;f<b.length;f+=1)b[f]<r||(w-=1);if(w===b.length)i=b;else if(w>0){const f=new Uint32Array(w);let y=0;for(let A=0;A<b.length;A+=1){const v=b[A];v>=r||(f[y]=v,y+=1)}i=f}else i=new Uint32Array(0)}const o=i?i.length:r,s=Rs(e??[]);if(!t||o===0||s.length===0)return{groups:[],inputPointCount:o,pointsInsideAnyRegion:0,unmatchedPointCount:o};const a=new Map,c=new Map;let l=0;for(let b=0;b<o;b+=1){const w=i?i[b]:b,f=t.positions[w*2],y=t.positions[w*2+1];let A=null;for(const L of s){let G=!1;for(const F of L.polygons)if(Or(f,y,F)){G=!0;break}G&&(!A||L.area<A.area)&&(A=L)}if(!A)continue;l+=1;const v=t.paletteIndices[w]??0,U=a.get(A.regionIndex)??new Map;U.set(v,(U.get(v)??0)+1),a.set(A.regionIndex,U),c.set(A.regionIndex,(c.get(A.regionIndex)??0)+1)}const m=n.includeEmptyRegions??!1,p=[];for(const b of s){const w=c.get(b.regionIndex)??0;if(!m&&w<=0)continue;const f=a.get(b.regionIndex)??new Map,y=Array.from(f.entries()).map(([A,v])=>({termId:Is(A,n.paletteIndexToTermId),paletteIndex:A,count:v})).sort((A,v)=>v.count-A.count||A.paletteIndex-v.paletteIndex);p.push({regionId:b.regionId,regionIndex:b.regionIndex,totalCount:w,termCounts:y})}return{groups:p,inputPointCount:o,pointsInsideAnyRegion:l,unmatchedPointCount:Math.max(0,o-l)}}function Zt(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function Ps(t,e){if(!e)return!1;try{const r=new URL(t,typeof window<"u"?window.location.href:void 0).hostname.toLowerCase();if(r.includes("amazonaws.com")||r.startsWith("s3.")||r.includes(".s3."))return!1}catch{}return!0}class fi{constructor(e){S(this,"maxConcurrency");S(this,"maxRetries");S(this,"retryBaseDelayMs");S(this,"retryMaxDelayMs");S(this,"onTileLoad");S(this,"onTileError");S(this,"onStateChange");S(this,"authToken");S(this,"destroyed",!1);S(this,"queue",[]);S(this,"queuedByKey",new Map);S(this,"inflight",new Map);S(this,"visibleKeys",new Set);S(this,"timerId",null);S(this,"abortedCount",0);S(this,"retryCount",0);S(this,"failedCount",0);this.maxConcurrency=Math.max(1,Math.floor(e.maxConcurrency??12)),this.maxRetries=Math.max(0,Math.floor(e.maxRetries??2)),this.retryBaseDelayMs=Math.max(10,Math.floor(e.retryBaseDelayMs??120)),this.retryMaxDelayMs=Math.max(this.retryBaseDelayMs,Math.floor(e.retryMaxDelayMs??1200)),this.authToken=e.authToken??"",this.onTileLoad=e.onTileLoad,this.onTileError=e.onTileError,this.onStateChange=e.onStateChange}setAuthToken(e){this.authToken=String(e??"")}schedule(e){if(this.destroyed)return;const n=new Set;for(const r of e)n.add(r.key);this.visibleKeys=n,this.dropInvisibleQueued(n),this.abortInvisibleInflight(n);for(const r of e){if(this.inflight.has(r.key)){const s=this.inflight.get(r.key);s&&(s.tile=r);continue}const i=this.queuedByKey.get(r.key);if(i){i.tile=r;continue}const o={tile:r,attempt:0,readyAt:Zt()};this.queue.push(o),this.queuedByKey.set(r.key,o)}this.sortQueue(),this.pump(),this.emitStateChange()}clear(){this.clearPumpTimer(),this.visibleKeys.clear(),this.queue=[],this.queuedByKey.clear();for(const[,e]of this.inflight)e.controller.abort();this.inflight.clear(),this.emitStateChange()}destroy(){this.destroyed||(this.destroyed=!0,this.clear())}getInflightCount(){return this.inflight.size}getSnapshot(){return{inflight:this.inflight.size,queued:this.queue.length,aborted:this.abortedCount,retries:this.retryCount,failed:this.failedCount}}dropInvisibleQueued(e){if(this.queue.length===0)return;const n=[];for(const r of this.queue){if(!e.has(r.tile.key)){this.queuedByKey.delete(r.tile.key);continue}n.push(r)}this.queue=n}abortInvisibleInflight(e){for(const[n,r]of this.inflight)e.has(n)||(this.inflight.delete(n),this.abortedCount+=1,r.controller.abort())}sortQueue(){this.queue.sort((e,n)=>e.readyAt!==n.readyAt?e.readyAt-n.readyAt:e.tile.distance2!==n.tile.distance2?e.tile.distance2-n.tile.distance2:e.tile.tier!==n.tile.tier?n.tile.tier-e.tile.tier:e.tile.key.localeCompare(n.tile.key))}pump(){if(this.destroyed)return;for(this.clearPumpTimer();this.inflight.size<this.maxConcurrency;){const r=this.takeNextReadyQueueItem();if(!r)break;this.startFetch(r)}if(this.inflight.size>=this.maxConcurrency||this.queue.length===0)return;const e=this.queue[0]?.readyAt;if(typeof e!="number")return;const n=Math.max(0,e-Zt());this.timerId=window.setTimeout(()=>{this.timerId=null,this.pump()},n)}takeNextReadyQueueItem(){if(this.queue.length===0)return null;const e=Zt(),n=this.queue[0];return!n||n.readyAt>e?null:(this.queue.shift(),this.queuedByKey.delete(n.tile.key),n)}startFetch(e){const n=new AbortController,r={tile:e.tile,attempt:e.attempt,controller:n};this.inflight.set(e.tile.key,r),this.emitStateChange();const i=Ps(e.tile.url,this.authToken);fetch(e.tile.url,{signal:n.signal,headers:i?{Authorization:this.authToken}:void 0}).then(o=>{if(!o.ok)throw new Error(`HTTP ${o.status}`);return o.blob()}).then(o=>createImageBitmap(o)).then(o=>{if(this.destroyed||n.signal.aborted){o.close();return}if(!this.visibleKeys.has(e.tile.key)){o.close();return}this.onTileLoad(e.tile,o)}).catch(o=>{if(n.signal.aborted||this.destroyed)return;if(e.attempt<this.maxRetries&&this.visibleKeys.has(e.tile.key)){this.retryCount+=1;const a=e.attempt+1,c=this.getRetryDelay(a),l={tile:e.tile,attempt:a,readyAt:Zt()+c},m=this.queuedByKey.get(e.tile.key);m?(m.tile=l.tile,m.readyAt=Math.min(m.readyAt,l.readyAt),m.attempt=Math.max(m.attempt,l.attempt)):(this.queue.push(l),this.queuedByKey.set(l.tile.key,l)),this.sortQueue();return}this.failedCount+=1,this.onTileError?.(e.tile,o,e.attempt+1)}).finally(()=>{this.inflight.delete(e.tile.key),this.pump(),this.emitStateChange()})}getRetryDelay(e){const n=Math.max(0,e-1),r=Math.min(this.retryMaxDelayMs,this.retryBaseDelayMs*2**n),i=.85+Math.random()*.3;return Math.round(r*i)}clearPumpTimer(){this.timerId!==null&&(window.clearTimeout(this.timerId),this.timerId=null)}emitStateChange(){this.onStateChange?.(this.getSnapshot())}}const Ir=.35,Pn=.5,vs=256,vn=[{zoom:1,size:2.8},{zoom:2,size:3.4},{zoom:3,size:4.2},{zoom:4,size:5.3},{zoom:5,size:6.8},{zoom:6,size:8.4},{zoom:7,size:9.8},{zoom:8,size:11.2},{zoom:9,size:14},{zoom:10,size:17.5},{zoom:11,size:22},{zoom:12,size:28}];class _s{constructor(){S(this,"viewportWidth",1);S(this,"viewportHeight",1);S(this,"viewState",{zoom:1,offsetX:0,offsetY:0,rotationDeg:0})}setViewport(e,n){this.viewportWidth=Math.max(1,e),this.viewportHeight=Math.max(1,n)}getViewport(){return{width:this.viewportWidth,height:this.viewportHeight}}setViewState(e){typeof e.zoom=="number"&&(this.viewState.zoom=Math.max(1e-4,e.zoom)),typeof e.offsetX=="number"&&(this.viewState.offsetX=e.offsetX),typeof e.offsetY=="number"&&(this.viewState.offsetY=e.offsetY),typeof e.rotationDeg=="number"&&Number.isFinite(e.rotationDeg)&&(this.viewState.rotationDeg=e.rotationDeg)}getViewState(){return{...this.viewState}}getCenter(){const e=Math.max(1e-6,this.viewState.zoom);return[this.viewState.offsetX+this.viewportWidth/(2*e),this.viewState.offsetY+this.viewportHeight/(2*e)]}setCenter(e,n){const r=Math.max(1e-6,this.viewState.zoom);this.viewState.offsetX=e-this.viewportWidth/(2*r),this.viewState.offsetY=n-this.viewportHeight/(2*r)}screenToWorld(e,n){const r=this.viewState,i=Math.max(1e-6,r.zoom),[o,s]=this.getCenter(),a=(e-this.viewportWidth*.5)/i,c=(n-this.viewportHeight*.5)/i,l=vt(r.rotationDeg),m=Math.cos(l),p=Math.sin(l);return[o+a*m-c*p,s+a*p+c*m]}worldToScreen(e,n){const r=this.viewState,i=Math.max(1e-6,r.zoom),[o,s]=this.getCenter(),a=e-o,c=n-s,l=vt(r.rotationDeg),m=Math.cos(l),p=Math.sin(l),b=a*m+c*p,w=-a*p+c*m;return[this.viewportWidth*.5+b*i,this.viewportHeight*.5+w*i]}getViewCorners(){const e=this.viewportWidth,n=this.viewportHeight;return[this.screenToWorld(0,0),this.screenToWorld(e,0),this.screenToWorld(e,n),this.screenToWorld(0,n)]}getMatrix(){const e=Math.max(1e-6,this.viewState.zoom),[n,r]=this.getCenter(),i=vt(this.viewState.rotationDeg),o=Math.cos(i),s=Math.sin(i),a=2*e*o/this.viewportWidth,c=2*e*s/this.viewportWidth,l=2*e*s/this.viewportHeight,m=-2*e*o/this.viewportHeight,p=-(a*n+c*r),b=-(l*n+m*r);return new Float32Array([a,l,0,c,m,0,p,b,1])}}function vt(t){return t*Math.PI/180}function Kt(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function Ge(t,e,n){const r=t.getUniformLocation(e,n);if(!r)throw new Error(`uniform location lookup failed: ${n}`);return r}function jt(t,e){return!t||!e?t===e:t.buffer===e.buffer&&t.byteOffset===e.byteOffset&&t.byteLength===e.byteLength}function _n(t){return t.map(e=>({zoom:e.zoom,size:e.size}))}function Pr(t){if(!t)return _n(vn);const e=new Map;for(const[n,r]of Object.entries(t)){const i=Number(n),o=Number(r);!Number.isFinite(i)||!Number.isFinite(o)||o<=0||e.set(i,o)}return e.size===0?_n(vn):Array.from(e.entries()).sort((n,r)=>n[0]-r[0]).map(([n,r])=>({zoom:n,size:r}))}function Fs(t,e){if(t===e)return!0;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1)if(t[n].zoom!==e[n].zoom||t[n].size!==e[n].size)return!1;return!0}function Us(t,e){if(!Number.isFinite(t))return e[0]?.size??Pn;if(e.length===0)return Pn;if(e.length===1||t<=e[0].zoom)return e[0].size;for(let s=1;s<e.length;s+=1){const a=e[s-1],c=e[s];if(t>c.zoom)continue;const l=Math.max(1e-6,c.zoom-a.zoom),m=ae((t-a.zoom)/l,0,1);return a.size+(c.size-a.size)*m}const n=e[e.length-1],r=e[e.length-2],i=Math.max(1e-6,n.zoom-r.zoom),o=(n.size-r.size)/i;return n.size+(t-n.zoom)*o}const Bs=.1,Ls=5;function vr(t){return typeof t!="number"||!Number.isFinite(t)?1:ae(t,Bs,Ls)}const Ns=-100,zs=100;function yn(t){return typeof t!="number"||!Number.isFinite(t)?0:ae(t,Ns,zs)}function _r(t){const e=yn(t?.brightness),n=yn(t?.contrast),r=yn(t?.saturation);return{brightness:e/200,contrast:n/100,saturation:r/100}}const ks=2e3;function hi(t){return t}function Sn(t){return typeof t!="number"||!Number.isFinite(t)?0:ae(t,0,ks)}function Jt(t){return typeof t!="number"||!Number.isFinite(t)||t<=0?null:Math.max(1e-6,t)}function Mn(t){return typeof t=="function"?t:hi}function Fr(t,e){return Math.abs(t.zoom-e.zoom)<=1e-6&&Math.abs(t.offsetX-e.offsetX)<=1e-6&&Math.abs(t.offsetY-e.offsetY)<=1e-6&&Math.abs(t.rotationDeg-e.rotationDeg)<=1e-6}class di{constructor(e,n,r={}){S(this,"canvas");S(this,"source");S(this,"gl");S(this,"camera",new _s);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,"dragging",!1);S(this,"interactionMode","none");S(this,"rotateLastAngleRad",null);S(this,"pointerId",null);S(this,"lastPointerX",0);S(this,"lastPointerY",0);S(this,"interactionLocked",!1);S(this,"ctrlDragRotate",!0);S(this,"rotationDragSensitivityDegPerPixel",.35);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",hi);S(this,"viewAnimation",null);S(this,"viewAnimationFrame",null);S(this,"currentTier",0);S(this,"pointCount",0);S(this,"usePointIndices",!1);S(this,"pointBuffersDirty",!0);S(this,"pointPaletteSize",1);S(this,"pointSizeStops",_n(vn));S(this,"pointStrokeScale",1);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=e,this.source=n,this.onViewStateChange=r.onViewStateChange,this.onStats=r.onStats,this.onTileError=r.onTileError,this.onContextLost=r.onContextLost,this.onContextRestored=r.onContextRestored,this.authToken=r.authToken??"",this.maxCacheTiles=Math.max(32,Math.floor(r.maxCacheTiles??320)),this.ctrlDragRotate=r.ctrlDragRotate??!0,this.rotationDragSensitivityDegPerPixel=typeof r.rotationDragSensitivityDegPerPixel=="number"&&Number.isFinite(r.rotationDragSensitivityDegPerPixel)?Math.max(0,r.rotationDragSensitivityDegPerPixel):Ir,this.pointSizeStops=Pr(r.pointSizeByZoom),this.pointStrokeScale=vr(r.pointStrokeScale),this.imageColorSettings=_r(r.imageColorSettings),this.minZoomOverride=Jt(r.minZoom),this.maxZoomOverride=Jt(r.maxZoom),this.viewTransitionDurationMs=Sn(r.viewTransition?.duration),this.viewTransitionEasing=Mn(r.viewTransition?.easing);const i=e.getContext("webgl2",{alpha:!1,antialias:!1,depth:!1,stencil:!1,powerPreference:"high-performance"});if(!i)throw new Error("WebGL2 not supported");this.gl=i,this.tileProgram=this.initTileProgram(),this.pointProgram=this.initPointProgram(),this.tileScheduler=new fi({authToken:this.authToken,maxConcurrency:r.tileScheduler?.maxConcurrency??12,maxRetries:r.tileScheduler?.maxRetries??2,retryBaseDelayMs:r.tileScheduler?.retryBaseDelayMs??120,retryMaxDelayMs:r.tileScheduler?.retryMaxDelayMs??1200,onTileLoad:(o,s)=>this.handleTileLoaded(o,s),onTileError:(o,s,a)=>{this.onTileError?.({tile:o,error:s,attemptCount:a}),console.warn("tile load failed",o.url,s)}}),this.resizeObserver=new ResizeObserver(()=>this.resize()),this.resizeObserver.observe(e),this.boundPointerDown=o=>this.onPointerDown(o),this.boundPointerMove=o=>this.onPointerMove(o),this.boundPointerUp=o=>this.onPointerUp(o),this.boundWheel=o=>this.onWheel(o),this.boundDoubleClick=o=>this.onDoubleClick(o),this.boundContextMenu=o=>this.onContextMenu(o),this.boundContextLost=o=>this.onWebGlContextLost(o),this.boundContextRestored=o=>this.onWebGlContextRestored(o),e.addEventListener("pointerdown",this.boundPointerDown),e.addEventListener("pointermove",this.boundPointerMove),e.addEventListener("pointerup",this.boundPointerUp),e.addEventListener("pointercancel",this.boundPointerUp),e.addEventListener("wheel",this.boundWheel,{passive:!1}),e.addEventListener("dblclick",this.boundDoubleClick),e.addEventListener("contextmenu",this.boundContextMenu),e.addEventListener("webglcontextlost",this.boundContextLost),e.addEventListener("webglcontextrestored",this.boundContextRestored),this.fitToImage({duration:0}),this.resize()}resolveDefaultZoomBounds(){const e=Math.max(this.fitZoom*.5,1e-6),n=Math.max(1,this.fitZoom*8);return{minZoom:e,maxZoom:Math.max(e,n)}}applyZoomBounds(){const e=this.resolveDefaultZoomBounds();let n=this.minZoomOverride??e.minZoom,r=this.maxZoomOverride??e.maxZoom;n=Math.max(1e-6,n),r=Math.max(1e-6,r),n>r&&(n=r),this.minZoom=n,this.maxZoom=r}resolveTargetViewState(e){const n=this.camera.getViewState(),r={zoom:typeof e.zoom=="number"&&Number.isFinite(e.zoom)?ae(e.zoom,this.minZoom,this.maxZoom):n.zoom,offsetX:typeof e.offsetX=="number"&&Number.isFinite(e.offsetX)?e.offsetX:n.offsetX,offsetY:typeof e.offsetY=="number"&&Number.isFinite(e.offsetY)?e.offsetY:n.offsetY,rotationDeg:typeof e.rotationDeg=="number"&&Number.isFinite(e.rotationDeg)?e.rotationDeg:n.rotationDeg};this.camera.setViewState(r),this.clampViewState();const i=this.camera.getViewState();return this.camera.setViewState(n),i}cancelViewAnimation(){this.viewAnimation=null,this.viewAnimationFrame!==null&&(cancelAnimationFrame(this.viewAnimationFrame),this.viewAnimationFrame=null)}startViewAnimation(e,n,r){const i=this.camera.getViewState();this.cancelViewAnimation(),this.viewAnimation={startMs:Kt(),durationMs:Math.max(0,n),from:i,to:e,easing:r};const o=()=>{const s=this.viewAnimation;if(!s)return;const a=Math.max(0,Kt()-s.startMs),c=s.durationMs<=0?1:ae(a/s.durationMs,0,1);let l=c;try{l=s.easing(c)}catch{l=c}Number.isFinite(l)||(l=c),l=ae(l,0,1);const m={zoom:s.from.zoom+(s.to.zoom-s.from.zoom)*l,offsetX:s.from.offsetX+(s.to.offsetX-s.from.offsetX)*l,offsetY:s.from.offsetY+(s.to.offsetY-s.from.offsetY)*l,rotationDeg:s.from.rotationDeg+(s.to.rotationDeg-s.from.rotationDeg)*l};if(this.camera.setViewState(m),this.clampViewState(),this.emitViewState(),this.requestRender(),c>=1){this.viewAnimation=null,this.viewAnimationFrame=null;return}this.viewAnimationFrame=requestAnimationFrame(o)};this.viewAnimationFrame=requestAnimationFrame(o)}setAuthToken(e){this.authToken=String(e??""),this.tileScheduler.setAuthToken(this.authToken)}setZoomRange(e,n){const r=Jt(e),i=Jt(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();Fr(s,o)||(this.cancelViewAnimation(),this.camera.setViewState(o),this.emitViewState(),this.requestRender())}setViewTransition(e){this.viewTransitionDurationMs=Sn(e?.duration),this.viewTransitionEasing=Mn(e?.easing)}setViewState(e,n){const r=this.resolveTargetViewState(e),i=this.camera.getViewState();if(Fr(i,r))return;const o=Sn(n?.duration??this.viewTransitionDurationMs),s=Mn(n?.easing??this.viewTransitionEasing);if(o<=0){this.cancelViewAnimation(),this.camera.setViewState(r),this.emitViewState(),this.requestRender();return}this.startViewAnimation(r,o,s)}getViewState(){return this.camera.getViewState()}getZoomRange(){return{minZoom:this.minZoom,maxZoom:this.maxZoom}}setPointPalette(e){if(!e||e.length===0){this.lastPointPalette=null;return}if(this.lastPointPalette=new Uint8Array(e),this.contextLost||this.gl.isContextLost())return;const n=this.gl,r=Math.max(1,Math.floor(this.lastPointPalette.length/4));this.pointPaletteSize=r,n.bindTexture(n.TEXTURE_2D,this.pointProgram.paletteTexture),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,r,1,0,n.RGBA,n.UNSIGNED_BYTE,this.lastPointPalette),n.bindTexture(n.TEXTURE_2D,null),this.requestRender()}setPointData(e){if(!e||!e.count||!e.positions||!e.paletteIndices){this.lastPointData=null,this.pointCount=0,this.usePointIndices=!1,this.requestRender();return}const n=e.fillModes instanceof Uint8Array?e.fillModes:null,r=n!==null,i=Math.max(0,Math.min(e.count,Math.floor(e.positions.length/2),e.paletteIndices.length,r?n.length:Number.MAX_SAFE_INTEGER)),o=e.positions.subarray(0,i*2),s=e.paletteIndices.subarray(0,i),a=r?n.subarray(0,i):void 0,c=e.drawIndices instanceof Uint32Array,l=c?this.sanitizeDrawIndices(e.drawIndices,i):null,m=this.lastPointData,p=m?.fillModes instanceof Uint8Array,b=this.pointBuffersDirty||!m||m.count!==i||!jt(m.positions,o)||!jt(m.paletteIndices,s)||p!==r||r&&(!m?.fillModes||!jt(m.fillModes,a)),w=this.pointBuffersDirty||c&&(!m?.drawIndices||!jt(m.drawIndices,l))||!c&&!!m?.drawIndices;if(this.lastPointData={count:i,positions:o,paletteIndices:s,fillModes:a,drawIndices:c?l??void 0:void 0},this.contextLost||this.gl.isContextLost())return;const f=this.gl;b&&(f.bindBuffer(f.ARRAY_BUFFER,this.pointProgram.posBuffer),f.bufferData(f.ARRAY_BUFFER,this.lastPointData.positions,f.STATIC_DRAW),f.bindBuffer(f.ARRAY_BUFFER,this.pointProgram.termBuffer),f.bufferData(f.ARRAY_BUFFER,this.lastPointData.paletteIndices,f.STATIC_DRAW),f.bindBuffer(f.ARRAY_BUFFER,this.pointProgram.fillModeBuffer),f.bufferData(f.ARRAY_BUFFER,this.lastPointData.fillModes??this.getZeroFillModes(i),f.STATIC_DRAW),f.bindBuffer(f.ARRAY_BUFFER,null)),c&&w&&(f.bindBuffer(f.ELEMENT_ARRAY_BUFFER,this.pointProgram.indexBuffer),f.bufferData(f.ELEMENT_ARRAY_BUFFER,l??new Uint32Array(0),f.DYNAMIC_DRAW),f.bindBuffer(f.ELEMENT_ARRAY_BUFFER,null)),this.usePointIndices=c;const y=c?l?.length??0:this.lastPointData.count;this.pointCount=y,(b||w)&&(this.pointBuffersDirty=!1),this.requestRender()}sanitizeDrawIndices(e,n){if(n<=0||e.length===0)return new Uint32Array(0);let r=e.length;for(let s=0;s<e.length;s+=1)e[s]<n||(r-=1);if(r===e.length)return e;if(r<=0)return new Uint32Array(0);const i=new Uint32Array(r);let o=0;for(let s=0;s<e.length;s+=1){const a=e[s];a>=n||(i[o]=a,o+=1)}return i}getZeroFillModes(e){return e<=0?new Uint8Array(0):(this.zeroFillModes.length<e&&(this.zeroFillModes=new Uint8Array(e)),this.zeroFillModes.subarray(0,e))}setInteractionLock(e){const n=!!e;this.interactionLocked!==n&&(this.interactionLocked=n,n&&this.cancelDrag())}setPointSizeByZoom(e){const n=Pr(e);Fs(this.pointSizeStops,n)||(this.pointSizeStops=n,this.requestRender())}setPointStrokeScale(e){const n=vr(e);this.pointStrokeScale!==n&&(this.pointStrokeScale=n,this.requestRender())}setImageColorSettings(e){const n=_r(e),r=this.imageColorSettings;r.brightness===n.brightness&&r.contrast===n.contrast&&r.saturation===n.saturation||(this.imageColorSettings=n,this.requestRender())}cancelDrag(){if(this.pointerId!==null&&this.canvas.hasPointerCapture(this.pointerId))try{this.canvas.releasePointerCapture(this.pointerId)}catch{}this.dragging=!1,this.interactionMode="none",this.rotateLastAngleRad=null,this.pointerId=null,this.canvas.classList.remove("dragging")}getPointerAngleRad(e,n){const r=this.canvas.getBoundingClientRect(),i=e-r.left-r.width*.5,o=n-r.top-r.height*.5;return Math.atan2(o,i)}screenToWorld(e,n){const r=this.canvas.getBoundingClientRect(),i=e-r.left,o=n-r.top;return this.camera.screenToWorld(i,o)}worldToScreen(e,n){return this.camera.worldToScreen(e,n)}setViewCenter(e,n,r){if(!Number.isFinite(e)||!Number.isFinite(n))return;const i=this.camera.getViewState(),o=Math.max(1e-6,i.zoom),s=this.camera.getViewport();this.setViewState({offsetX:e-s.width/(2*o),offsetY:n-s.height/(2*o)},r)}getViewCorners(){return this.camera.getViewCorners()}resetRotation(e){const n=this.camera.getViewState();Math.abs(n.rotationDeg)<1e-6||this.setViewState({rotationDeg:0},e)}getPointSizeByZoom(){const e=Math.max(1e-6,this.camera.getViewState().zoom),n=this.source.maxTierZoom+Math.log2(e),r=Us(n,this.pointSizeStops);return ae(r,Pn,vs)}fitToImage(e){const n=this.canvas.getBoundingClientRect(),r=Math.max(1,n.width||1),i=Math.max(1,n.height||1),o=Math.min(r/this.source.width,i/this.source.height),s=Number.isFinite(o)&&o>0?o:1;this.fitZoom=s,this.applyZoomBounds();const a=ae(s,this.minZoom,this.maxZoom),c=r/a,l=i/a;this.setViewState({zoom:a,offsetX:(this.source.width-c)*.5,offsetY:(this.source.height-l)*.5,rotationDeg:0},e)}zoomBy(e,n,r,i){const o=this.camera.getViewState(),s=ae(o.zoom*e,this.minZoom,this.maxZoom);if(s===o.zoom)return;const[a,c]=this.camera.screenToWorld(n,r),l=this.camera.getViewport(),m=n-l.width*.5,p=r-l.height*.5,b=vt(o.rotationDeg),w=Math.cos(b),f=Math.sin(b),y=m/s*w-p/s*f,A=m/s*f+p/s*w,v=a-y,U=c-A;this.setViewState({zoom:s,offsetX:v-l.width/(2*s),offsetY:U-l.height/(2*s)},i)}clampViewState(){const e=this.getViewBounds(),n=Math.max(1e-6,e[2]-e[0]),r=Math.max(1e-6,e[3]-e[1]),i=n*.2,o=r*.2,[s,a]=this.camera.getCenter(),c=n*.5,l=r*.5,m=c-i,p=this.source.width-c+i,b=l-o,w=this.source.height-l+o,f=m<=p?ae(s,m,p):this.source.width*.5,y=b<=w?ae(a,b,w):this.source.height*.5;this.camera.setCenter(f,y)}emitViewState(){this.onViewStateChange?.(this.camera.getViewState())}selectTier(){const e=Math.max(1e-6,this.camera.getViewState().zoom),n=this.source.maxTierZoom+Math.log2(e);return ae(Math.floor(n),0,this.source.maxTierZoom)}getViewBounds(){const e=this.camera.getViewCorners();let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[s,a]of e)s<n&&(n=s),s>i&&(i=s),a<r&&(r=a),a>o&&(o=a);return[n,r,i,o]}intersectsBounds(e,n){return!(e[2]<=n[0]||e[0]>=n[2]||e[3]<=n[1]||e[1]>=n[3])}getVisibleTiles(){const e=this.selectTier();return this.currentTier=e,this.getVisibleTilesForTier(e)}getVisibleTilesForTier(e){const n=this.getViewBounds(),r=Math.pow(2,this.source.maxTierZoom-e),i=Math.ceil(this.source.width/r),o=Math.ceil(this.source.height/r),s=Math.max(1,Math.ceil(i/this.source.tileSize)),a=Math.max(1,Math.ceil(o/this.source.tileSize)),c=n[0],l=n[1],m=n[2],p=n[3],b=ae(Math.floor(c/r/this.source.tileSize),0,s-1),w=ae(Math.floor((m-1)/r/this.source.tileSize),0,s-1),f=ae(Math.floor(l/r/this.source.tileSize),0,a-1),y=ae(Math.floor((p-1)/r/this.source.tileSize),0,a-1);if(b>w||f>y)return[];const A=(c+m)*.5/r/this.source.tileSize,v=(l+p)*.5/r/this.source.tileSize,U=[];for(let L=f;L<=y;L+=1)for(let G=b;G<=w;G+=1){const F=G*this.source.tileSize*r,z=L*this.source.tileSize*r,$=Math.min((G+1)*this.source.tileSize,i)*r,se=Math.min((L+1)*this.source.tileSize,o)*r,le=G-A,pe=L-v;U.push({key:`${e}/${G}/${L}`,tier:e,x:G,y:L,bounds:[F,z,$,se],distance2:le*le+pe*pe,url:zn(this.source,e,G,L)})}return U.sort((L,G)=>L.distance2-G.distance2),U}trimCache(){if(this.cache.size<=this.maxCacheTiles)return;const e=Array.from(this.cache.entries());e.sort((r,i)=>r[1].lastUsed-i[1].lastUsed);const n=this.cache.size-this.maxCacheTiles;for(let r=0;r<n;r+=1){const[i,o]=e[r];this.gl.deleteTexture(o.texture),this.cache.delete(i)}}render(){if(this.destroyed||this.contextLost||this.gl.isContextLost())return;const e=this.onStats?Kt():0;this.frameSerial+=1;const n=this.gl,r=this.tileProgram,i=this.pointProgram;n.clearColor(.03,.06,.1,1),n.clear(n.COLOR_BUFFER_BIT);const o=this.getVisibleTiles(),s=this.getViewBounds(),a=new Set(o.map(y=>y.key));n.useProgram(r.program),n.bindVertexArray(r.vao),n.uniformMatrix3fv(r.uCamera,!1,this.camera.getMatrix()),n.uniform1i(r.uTexture,0),n.uniform1f(r.uBrightness,this.imageColorSettings.brightness),n.uniform1f(r.uContrast,this.imageColorSettings.contrast),n.uniform1f(r.uSaturation,this.imageColorSettings.saturation);const c=[];for(const[,y]of this.cache)a.has(y.key)||this.intersectsBounds(y.bounds,s)&&c.push(y);c.sort((y,A)=>y.tier-A.tier);for(const y of c)y.lastUsed=this.frameSerial,n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,y.texture),n.uniform4f(r.uBounds,y.bounds[0],y.bounds[1],y.bounds[2],y.bounds[3]),n.drawArrays(n.TRIANGLE_STRIP,0,4);let l=0;const m=[];for(const y of o){const A=this.cache.get(y.key);if(!A){m.push(y);continue}A.lastUsed=this.frameSerial,n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,A.texture),n.uniform4f(r.uBounds,A.bounds[0],A.bounds[1],A.bounds[2],A.bounds[3]),n.drawArrays(n.TRIANGLE_STRIP,0,4),l+=1}const p=m.slice(),b=1e6,w=[];this.currentTier>0&&w.push(this.currentTier-1),this.currentTier<this.source.maxTierZoom&&w.push(this.currentTier+1);for(const y of w){const A=this.getVisibleTilesForTier(y);for(const v of A)this.cache.has(v.key)||(v.distance2+=b,p.push(v))}this.tileScheduler.schedule(p),n.bindTexture(n.TEXTURE_2D,null),n.bindVertexArray(null);let f=0;if(this.pointCount>0&&(n.enable(n.BLEND),n.blendFunc(n.ONE,n.ONE_MINUS_SRC_ALPHA),n.useProgram(i.program),n.bindVertexArray(i.vao),n.uniformMatrix3fv(i.uCamera,!1,this.camera.getMatrix()),n.uniform1f(i.uPointSize,this.getPointSizeByZoom()),n.uniform1f(i.uPointStrokeScale,this.pointStrokeScale),n.uniform1f(i.uPaletteSize,this.pointPaletteSize),n.uniform1i(i.uPalette,1),n.activeTexture(n.TEXTURE1),n.bindTexture(n.TEXTURE_2D,i.paletteTexture),this.usePointIndices?n.drawElements(n.POINTS,this.pointCount,n.UNSIGNED_INT,0):n.drawArrays(n.POINTS,0,this.pointCount),n.bindTexture(n.TEXTURE_2D,null),n.bindVertexArray(null),f=this.pointCount),this.onStats){const y=this.tileScheduler.getSnapshot();this.onStats({tier:this.currentTier,visible:o.length,rendered:l,points:f,fallback:c.length,cache:this.cache.size,inflight:y.inflight,queued:y.queued,retries:y.retries,failed:y.failed,aborted:y.aborted,cacheHits:l,cacheMisses:m.length,drawCalls:c.length+l+(f>0?1:0),frameMs:Kt()-e})}}requestRender(){this.frame!==null||this.destroyed||this.contextLost||this.gl.isContextLost()||(this.frame=requestAnimationFrame(()=>{this.frame=null,this.render()}))}resize(){const e=this.canvas.getBoundingClientRect(),n=Math.max(1,e.width||this.canvas.clientWidth||1),r=Math.max(1,e.height||this.canvas.clientHeight||1),i=Math.max(1,window.devicePixelRatio||1),o=Math.max(1,Math.round(n*i)),s=Math.max(1,Math.round(r*i));(this.canvas.width!==o||this.canvas.height!==s)&&(this.canvas.width=o,this.canvas.height=s),this.camera.setViewport(n,r),this.gl.viewport(0,0,o,s),this.requestRender()}onPointerDown(e){if(this.interactionLocked)return;const n=this.ctrlDragRotate&&(e.ctrlKey||e.metaKey);(e.button===0||n&&e.button===2)&&(this.cancelViewAnimation(),n&&e.preventDefault(),this.dragging=!0,this.interactionMode=n?"rotate":"pan",this.pointerId=e.pointerId,this.lastPointerX=e.clientX,this.lastPointerY=e.clientY,this.rotateLastAngleRad=this.interactionMode==="rotate"?this.getPointerAngleRad(e.clientX,e.clientY):null,this.canvas.classList.add("dragging"),this.canvas.setPointerCapture(e.pointerId))}onPointerMove(e){if(this.interactionLocked||!this.dragging||e.pointerId!==this.pointerId)return;const n=e.clientX-this.lastPointerX,r=e.clientY-this.lastPointerY;if(this.lastPointerX=e.clientX,this.lastPointerY=e.clientY,this.interactionMode==="rotate"){const i=this.getPointerAngleRad(e.clientX,e.clientY),o=this.rotateLastAngleRad;if(this.rotateLastAngleRad=i,o!==null){const s=i-o,a=Math.atan2(Math.sin(s),Math.cos(s)),c=this.rotationDragSensitivityDegPerPixel/Ir,l=this.camera.getViewState();this.camera.setViewState({rotationDeg:l.rotationDeg-a*180/Math.PI*c})}}else{const i=this.camera.getViewState(),o=Math.max(1e-6,i.zoom),s=vt(i.rotationDeg),a=Math.cos(s),c=Math.sin(s),l=(n*a-r*c)/o,m=(n*c+r*a)/o;this.camera.setViewState({offsetX:i.offsetX-l,offsetY:i.offsetY-m})}this.clampViewState(),this.emitViewState(),this.requestRender()}onPointerUp(e){this.interactionLocked||e.pointerId===this.pointerId&&this.cancelDrag()}onWheel(e){if(this.interactionLocked){e.preventDefault();return}e.preventDefault();const n=this.canvas.getBoundingClientRect(),r=e.clientX-n.left,i=e.clientY-n.top,o=e.deltaY<0?1.12:.89;this.zoomBy(o,r,i)}onDoubleClick(e){if(this.interactionLocked)return;const n=this.canvas.getBoundingClientRect(),r=e.clientX-n.left,i=e.clientY-n.top;this.zoomBy(e.shiftKey?.8:1.25,r,i)}onContextMenu(e){(this.dragging||e.ctrlKey||e.metaKey)&&e.preventDefault()}onWebGlContextLost(e){e.preventDefault(),!(this.destroyed||this.contextLost)&&(this.contextLost=!0,this.pointBuffersDirty=!0,this.frame!==null&&(cancelAnimationFrame(this.frame),this.frame=null),this.cancelViewAnimation(),this.cancelDrag(),this.tileScheduler.clear(),this.cache.clear(),this.onContextLost?.())}onWebGlContextRestored(e){this.destroyed||(this.contextLost=!1,this.cache.clear(),this.tileProgram=this.initTileProgram(),this.pointProgram=this.initPointProgram(),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(){if(!this.destroyed){if(this.destroyed=!0,this.frame!==null&&(cancelAnimationFrame(this.frame),this.frame=null),this.cancelViewAnimation(),this.resizeObserver.disconnect(),this.canvas.removeEventListener("pointerdown",this.boundPointerDown),this.canvas.removeEventListener("pointermove",this.boundPointerMove),this.canvas.removeEventListener("pointerup",this.boundPointerUp),this.canvas.removeEventListener("pointercancel",this.boundPointerUp),this.canvas.removeEventListener("wheel",this.boundWheel),this.canvas.removeEventListener("dblclick",this.boundDoubleClick),this.canvas.removeEventListener("contextmenu",this.boundContextMenu),this.canvas.removeEventListener("webglcontextlost",this.boundContextLost),this.canvas.removeEventListener("webglcontextrestored",this.boundContextRestored),this.cancelDrag(),this.tileScheduler.destroy(),!this.contextLost&&!this.gl.isContextLost()){for(const[,e]of this.cache)this.gl.deleteTexture(e.texture);this.gl.deleteBuffer(this.tileProgram.vbo),this.gl.deleteVertexArray(this.tileProgram.vao),this.gl.deleteProgram(this.tileProgram.program),this.gl.deleteBuffer(this.pointProgram.posBuffer),this.gl.deleteBuffer(this.pointProgram.termBuffer),this.gl.deleteBuffer(this.pointProgram.fillModeBuffer),this.gl.deleteBuffer(this.pointProgram.indexBuffer),this.gl.deleteTexture(this.pointProgram.paletteTexture),this.gl.deleteVertexArray(this.pointProgram.vao),this.gl.deleteProgram(this.pointProgram.program)}this.cache.clear()}}initTileProgram(){const e=this.gl,i=hr(e,`#version 300 es
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
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
- }`),o=Ge(e,i,"uCamera"),s=Ge(e,i,"uBounds"),a=Ge(e,i,"uTexture"),c=Ge(e,i,"uBrightness"),l=Ge(e,i,"uContrast"),m=Ge(e,i,"uSaturation"),p=e.createVertexArray(),b=e.createBuffer();if(!p||!b)throw new Error("buffer allocation failed");e.bindVertexArray(p),e.bindBuffer(e.ARRAY_BUFFER,b),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 w=e.getAttribLocation(i,"aUnit"),f=e.getAttribLocation(i,"aUv");if(w<0||f<0)throw new Error("tile attribute lookup failed");return e.enableVertexAttribArray(w),e.enableVertexAttribArray(f),e.vertexAttribPointer(w,2,e.FLOAT,!1,16,0),e.vertexAttribPointer(f,2,e.FLOAT,!1,16,8),e.bindVertexArray(null),e.bindBuffer(e.ARRAY_BUFFER,null),{program:i,vao:p,vbo:b,uCamera:o,uBounds:s,uTexture:a,uBrightness:c,uContrast:l,uSaturation:m}}initPointProgram(){const e=this.gl,i=hr(e,`#version 300 es
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
109
109
  precision highp float;
110
110
  in vec2 aPosition;
111
111
  in uint aTerm;
@@ -128,6 +128,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
128
128
  uniform float uPaletteSize;
129
129
  uniform float uPointSize;
130
130
  uniform float uPointStrokeScale;
131
+ uniform float uPointInnerFillAlpha;
131
132
  out vec4 outColor;
132
133
  void main() {
133
134
  vec2 pc = gl_PointCoord * 2.0 - 1.0;
@@ -141,19 +142,22 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
141
142
 
142
143
  float aa = 1.5 / max(1.0, uPointSize);
143
144
  float outerMask = 1.0 - smoothstep(1.0 - aa, 1.0 + aa, r);
144
- float alpha = 0.0;
145
145
  if (vFillMode != 0u) {
146
- alpha = outerMask * color.a;
146
+ float alpha = outerMask * color.a;
147
+ if (alpha <= 0.001) discard;
148
+ outColor = vec4(color.rgb * alpha, alpha);
147
149
  } else {
148
150
  float s = uPointStrokeScale;
149
151
  float ringWidth = clamp(3.0 * s / max(1.0, uPointSize), 0.12 * s, 0.62 * s);
150
152
  float innerRadius = 1.0 - ringWidth;
151
153
  float innerMask = smoothstep(innerRadius - aa, innerRadius + aa, r);
152
- alpha = outerMask * innerMask * color.a;
154
+ float ringAlpha = outerMask * innerMask * color.a;
155
+ float fillAlpha = outerMask * (1.0 - innerMask) * clamp(uPointInnerFillAlpha, 0.0, 1.0);
156
+ float alpha = ringAlpha + fillAlpha;
157
+ if (alpha <= 0.001) discard;
158
+ // Premultiplied alpha output: inner fill is black, so it only contributes alpha.
159
+ outColor = vec4(color.rgb * ringAlpha, alpha);
153
160
  }
154
- if (alpha <= 0.001) discard;
155
-
156
- outColor = vec4(color.rgb * alpha, alpha);
157
- }`),o=Ge(e,i,"uCamera"),s=Ge(e,i,"uPointSize"),a=Ge(e,i,"uPointStrokeScale"),c=Ge(e,i,"uPalette"),l=Ge(e,i,"uPaletteSize"),m=e.createVertexArray(),p=e.createBuffer(),b=e.createBuffer(),w=e.createBuffer(),f=e.createBuffer(),y=e.createTexture();if(!m||!p||!b||!w||!f||!y)throw new Error("point buffer allocation failed");e.bindVertexArray(m),e.bindBuffer(e.ARRAY_BUFFER,p),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const A=e.getAttribLocation(i,"aPosition");if(A<0)throw new Error("point position attribute not found");e.enableVertexAttribArray(A),e.vertexAttribPointer(A,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,b),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const v=e.getAttribLocation(i,"aTerm");if(v<0)throw new Error("point term attribute not found");e.enableVertexAttribArray(v),e.vertexAttribIPointer(v,1,e.UNSIGNED_SHORT,0,0),e.bindBuffer(e.ARRAY_BUFFER,w),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const U=e.getAttribLocation(i,"aFillMode");if(U<0)throw new Error("point fill mode attribute not found");return e.enableVertexAttribArray(U),e.vertexAttribIPointer(U,1,e.UNSIGNED_BYTE,0,0),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,f),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,y),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:i,vao:m,posBuffer:p,termBuffer:b,fillModeBuffer:w,indexBuffer:f,paletteTexture:y,uCamera:o,uPointSize:s,uPointStrokeScale:a,uPalette:c,uPaletteSize:l}}handleTileLoaded(e,n){if(this.destroyed||this.contextLost||this.gl.isContextLost()){n.close();return}if(this.cache.has(e.key)){n.close();return}const r=this.createTextureFromBitmap(n);n.close(),r&&(this.cache.set(e.key,{key:e.key,texture:r,bounds:e.bounds,tier:e.tier,lastUsed:this.frameSerial}),this.trimCache(),this.requestRender())}createTextureFromBitmap(e){if(this.contextLost||this.gl.isContextLost())return null;const n=this.gl,r=n.createTexture();return r?(n.bindTexture(n.TEXTURE_2D,r),n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,1),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.LINEAR),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,e),n.bindTexture(n.TEXTURE_2D,null),r):null}}const An=[],Ds=[],Os={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)},Xs=.65,Ys=4,Ws=6,Vs=.5,Gs=.58,Hs=4096,qs=180,Ur=20;let Qt=null;const en=new Map;function Fn(t,e){return t.id??e}function pt(t,e,n){return Math.max(e,Math.min(n,t))}function $s(t){const e=pt(t,0,1);return e*e*(3-2*e)}function Un(t){if(!Array.isArray(t)||t.length<2)return null;const e=Number(t[0]),n=Number(t[1]);return!Number.isFinite(e)||!Number.isFinite(n)?null:[e,n]}function Zs(t){if(t.length===0)return null;let e=1/0;for(const i of t)i[1]<e&&(e=i[1]);if(!Number.isFinite(e))return null;let n=1/0,r=-1/0;for(const i of t)Math.abs(i[1]-e)>Vs||(i[0]<n&&(n=i[0]),i[0]>r&&(r=i[0]));return!Number.isFinite(n)||!Number.isFinite(r)?null:[(n+r)*.5,e]}function Ks(t){let e=null;for(const n of t){const r=Zs(n.outer);r&&(!e||r[1]<e[1]||r[1]===e[1]&&r[0]<e[0])&&(e=r)}return e}function js(t,e,n,r,i,o){const s=i-n,a=o-r,c=s*s+a*a;if(c<=1e-12){const f=t-n,y=e-r;return f*f+y*y}const l=pt(((t-n)*s+(e-r)*a)/c,0,1),m=n+s*l,p=r+a*l,b=t-m,w=e-p;return b*b+w*w}function Br(t,e,n,r){for(let i=1;i<n.length;i+=1){const o=n[i-1],s=n[i];if(js(t,e,o[0],o[1],s[0],s[1])<=r)return!0}return!1}function Js(t,e,n,r){if(t<n.minX-r||t>n.maxX+r||e<n.minY-r||e>n.maxY+r)return!1;const i=r*r;if(Br(t,e,n.outer,i))return!0;for(const o of n.holes)if(Br(t,e,o,i))return!0;return!1}function Qs(){if(Qt)return Qt;if(typeof document>"u")return null;const e=document.createElement("canvas").getContext("2d");return e?(Qt=e,Qt):null}function ea(t,e){const n=`${e.fontWeight}|${e.fontSize}|${e.fontFamily}|${t}`,r=en.get(n);if(r!==void 0)return r;const i=t.length*e.fontSize*Gs,o=Qs();let s=i;if(o){o.font=`${e.fontWeight} ${e.fontSize}px ${e.fontFamily}`;const a=o.measureText(t).width;Number.isFinite(a)&&a>=0&&(s=a)}return en.size>Hs&&en.clear(),en.set(n,s),s}function ta(t,e,n,r,i,o){if(!t.label||!t.labelAnchor)return!1;const s=Un(n.worldToScreen(t.labelAnchor[0],t.labelAnchor[1]));if(!s)return!1;const c=ea(t.label,r)+r.paddingX*2,l=r.fontSize+r.paddingY*2,m=pt(s[0],c*.5+1,i-c*.5-1),p=pt(s[1]-r.offsetY,l*.5+1,o-l*.5-1),b=m-c*.5,w=m+c*.5,f=p-l*.5,y=p+l*.5;return e[0]>=b&&e[0]<=w&&e[1]>=f&&e[1]<=y}function na(t){const e=[];for(let n=0;n<t.length;n+=1){const r=t[n],i=Ut([r?.coordinates]);if(i.length===0)continue;const o=typeof r?.label=="string"?r.label.trim():"";e.push({region:r,regionIndex:n,regionId:Fn(r,n),polygons:i,label:o,labelAnchor:o?Ks(i):null})}return e}function ra(t,e,n,r,i,o,s,a,c){const l=t[0],m=t[1],p=Math.max(1e-6,r.getViewState().zoom),b=Math.max(0,s),w=Ws/p;for(let f=n.length-1;f>=0;f-=1){const y=n[f];for(const v of y.polygons)if(Js(l,m,v,w))return{region:y.region,regionIndex:y.regionIndex,regionId:y.regionId};let A=$r(i,o?.({region:y.region,regionId:y.regionId,regionIndex:y.regionIndex,zoom:p}));if(b>0&&(A={...A,offsetY:A.offsetY+b}),!!ta(y,e,r,A,a,c))return{region:y.region,regionIndex:y.regionIndex,regionId:y.regionId}}return null}function ia({source:t,viewState:e,imageColorSettings:n=null,onViewStateChange:r,onStats:i,onTileError:o,onContextLost:s,onContextRestored:a,debugOverlay:c=!1,debugOverlayStyle:l,fitNonce:m=0,rotationResetNonce:p=0,authToken:b="",ctrlDragRotate:w=!0,pointData:f=null,pointPalette:y=null,pointSizeByZoom:A,pointStrokeScale:v,minZoom:U,maxZoom:L,viewTransition:G,roiRegions:F,roiPolygons:z,clipPointsToRois:$=!1,clipMode:se="worker",onClipStats:le,onRoiPointGroups:pe,roiPaletteIndexToTermId:Te,interactionLock:Ee=!1,drawTool:T="cursor",stampOptions:D,brushOptions:ee,drawFillColor:H,regionStrokeStyle:V,regionStrokeHoverStyle:Ce,regionStrokeActiveStyle:De,patchStrokeStyle:Pe,resolveRegionStrokeStyle:fe,resolveRegionLabelStyle:ce,overlayShapes:I,customLayers:R,patchRegions:N,regionLabelStyle:re,drawAreaTooltip:q,autoLiftRegionLabelAtMaxZoom:he=!1,onPointerWorldMove:Se,onPointHover:te,onPointClick:Z,onRegionHover:ie,onRegionClick:de,activeRegionId:ne,onActiveRegionChange:Y,getCellByCoordinatesRef:be,onDrawComplete:me,onPatchComplete:K,overviewMapConfig:Me,className:ve,style:Xe}){const Ye=Me?.show??!1,Fe=Me?.options,Ae=d.useRef(null),J=d.useRef(null),je=d.useRef(null),O=d.useRef(null),xe=d.useRef(r),ue=d.useRef(i),we=d.useRef(c),[Et,tt]=d.useState(null),[wt,Bt]=d.useState(()=>ne??null),lt=ne!==void 0,Re=lt?ne??null:wt,[Lt,u]=d.useState(null),[h,M]=d.useState(null),[x,C]=d.useState(0),X=d.useRef(null),k=d.useRef(null),oe=d.useRef(null),Q=d.useRef(0),W=d.useRef({rafId:null,startMs:0,from:0,to:0}),ge=d.useRef(0),ye=F??An,Oe=N??An,_e=z??Ds,Ie=(R?.length??0)>0,$e=d.useMemo(()=>({position:"relative",width:"100%",height:"100%",...Xe}),[Xe]),Je=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)",...l}),[l]),Ue=d.useMemo(()=>ye.length>0?ye:_e.length===0?An:_e.map((g,E)=>({id:E,coordinates:g})),[ye,_e]),nt=d.useMemo(()=>na(Ue),[Ue]),Yn=d.useMemo(()=>Nn(re),[re]),yt=d.useCallback(g=>{const E=pt(g,0,Ur);Math.abs(Q.current-E)<1e-4||(Q.current=E,C(E))},[]),ft=d.useCallback(()=>{const g=W.current;g.rafId!==null&&(cancelAnimationFrame(g.rafId),g.rafId=null)},[]),cn=d.useCallback(g=>{const E=pt(g,0,Ur),P=W.current,_=Q.current;if(Math.abs(_-E)<1e-4){ft(),P.to=E,yt(E);return}ft(),P.startMs=performance.now(),P.from=_,P.to=E;const B=j=>{const Be=W.current,We=Math.max(0,j-Be.startMs),At=pt(We/qs,0,1),un=$s(At),ln=Be.from+(Be.to-Be.from)*un;if(yt(ln),je.current?.(),At>=1){Be.rafId=null,yt(Be.to);return}Be.rafId=requestAnimationFrame(B)};P.rafId=requestAnimationFrame(B)},[yt,ft]),rt=d.useCallback(g=>{const E=J.current;if(!E||typeof g!="number"||!Number.isFinite(g)){cn(0);return}const P=Gr(he,g,E.getZoomRange());cn(P)},[he,cn]),ht=d.useMemo(()=>Ue.map(g=>g.coordinates),[Ue]),[dt,Nt]=d.useState(f);d.useEffect(()=>{const g=++ge.current;let E=!1;if(!$)return Nt(f),()=>{E=!0};if(!f||!f.count||!f.positions||!f.paletteIndices)return Nt(null),()=>{E=!0};if(ht.length===0)return Nt(Os),le?.({mode:se,durationMs:0,inputCount:f.count,outputCount:0,polygonCount:0}),()=>{E=!0};const P=(B,j)=>{if(E||g!==ge.current)return;const Be=f.count,We=B?.drawIndices?B.drawIndices.length:B?.count??0;Nt(B),le?.({mode:j.mode,durationMs:j.durationMs,inputCount:Be,outputCount:We,polygonCount:ht.length,usedWebGpu:j.usedWebGpu,candidateCount:j.candidateCount,bridgedToDraw:j.bridgedToDraw})};return(async()=>{if(se==="sync"){const B=performance.now(),j=Ft(f,ht);P(j,{mode:"sync",durationMs:performance.now()-B});return}if(se==="hybrid-webgpu"){const B=await ri(f,ht,{bridgeToDraw:!0});P(B.data,{mode:B.meta.mode,durationMs:B.meta.durationMs,usedWebGpu:B.meta.usedWebGpu,candidateCount:B.meta.candidateCount,bridgedToDraw:B.meta.bridgedToDraw});return}try{const B=await si(f,ht);P(B.data,{mode:B.meta.mode,durationMs:B.meta.durationMs})}catch{const B=performance.now(),j=Ft(f,ht);P(j,{mode:"sync",durationMs:performance.now()-B})}})(),()=>{E=!0}},[$,se,f,ht,le]);const Wn=!!(te||Z||be),[Qe,Vn]=d.useState(null);d.useEffect(()=>{if(!Wn||!dt){Vn(null);return}let g=!1;return ui(dt,t).then(E=>{g||Vn(E)}),()=>{g=!0}},[Wn,dt,t]);const mt=d.useCallback(g=>{const E=J.current;if(!E||!Qe)return null;const P=Number(g[0]),_=Number(g[1]);if(!Number.isFinite(P)||!Number.isFinite(_))return null;const B=Math.max(1e-6,E.getViewState().zoom),j=E.getPointSizeByZoom(),We=Math.max(Ys,j*Xs)/B;if(!Number.isFinite(We)||We<=0)return null;const{cellSize:At,cellOffsets:un,cellLengths:ln,pointIndices:Si,positions:jn,safeCount:Mi}=Qe,Jn=Math.floor(P/At),Qn=Math.floor(_/At),Dt=Math.max(1,Math.ceil(We/At)),Ai=We*We;let Ot=-1,er=Ai,tr=0,nr=0;for(let fn=Jn-Dt;fn<=Jn+Dt;fn+=1)for(let hn=Qn-Dt;hn<=Qn+Dt;hn+=1){const dn=ai(Qe,fn,hn);if(dn<0)continue;const rr=un[dn],Ti=rr+ln[dn];for(let mn=rr;mn<Ti;mn+=1){const Xt=Si[mn];if(Xt>=Mi)continue;const ir=jn[Xt*2],or=jn[Xt*2+1],sr=ir-P,ar=or-_,cr=sr*sr+ar*ar;cr>er||(er=cr,Ot=Xt,tr=ir,nr=or)}}if(Ot<0)return null;const xi=Qe.ids?Number(Qe.ids[Ot]):null;return{index:Ot,id:xi,coordinate:[P,_],pointCoordinate:[tr,nr]}},[Qe]),St=d.useCallback((g,E)=>{if(!te)return;const P=g?.index??null,_=g?.id??null;k.current===P&&oe.current===_||(k.current=P,oe.current=_,te({index:P,id:_,coordinate:E,pointCoordinate:g?.pointCoordinate??null}))},[te]),zt=d.useCallback((g,E)=>{if(!Z)return;const P=mt(g);P&&Z({...P,button:E})},[Z,mt]);d.useEffect(()=>{if(be)return be.current=mt,()=>{be.current===mt&&(be.current=null)}},[be,mt]),d.useEffect(()=>{lt&&Bt(ne??null)},[lt,ne]);const it=d.useCallback(g=>{String(Re)!==String(g)&&(lt||Bt(g),Y?.(g))},[Re,lt,Y]);d.useEffect(()=>{xe.current=r},[r]),d.useEffect(()=>{ue.current=i},[i]),d.useEffect(()=>{we.current=c,c||M(null)},[c]),d.useEffect(()=>()=>{ft()},[ft]);const Gn=d.useCallback(g=>{ue.current?.(g),we.current&&M(g)},[]),mi=d.useMemo(()=>h?[`tier ${h.tier} | frame ${h.frameMs?.toFixed(2)??"-"} ms | drawCalls ${h.drawCalls??"-"}`,`tiles visible ${h.visible} | rendered ${h.rendered} | fallback ${h.fallback}`,`cache size ${h.cache} | hit ${h.cacheHits??"-"} | miss ${h.cacheMisses??"-"}`,`queue inflight ${h.inflight} | queued ${h.queued??"-"} | retries ${h.retries??"-"} | failed ${h.failed??"-"} | aborted ${h.aborted??"-"}`,`points ${h.points}`].join(`
158
- `):"stats: waiting for first frame...",[h]);d.useEffect(()=>{!(Re===null?!0:Ue.some((_,B)=>String(Fn(_,B))===String(Re)))&&Re!==null&&it(null);const E=X.current;!(E===null?!0:Ue.some((_,B)=>String(Fn(_,B))===String(E)))&&E!==null&&(X.current=null,tt(null),ie?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[Ue,Re,ie,it]),d.useEffect(()=>{const g=k.current;g!==null&&(Qe&&g<Qe.safeCount||(k.current=null,oe.current=null,te?.({index:null,id:null,coordinate:null,pointCoordinate:null})))},[Qe,te]);const Hn=d.useCallback(g=>{rt(g.zoom),Ie&&u(g);const E=xe.current;E&&E(g),je.current?.(),O.current?.()},[Ie,rt]);d.useEffect(()=>{const g=J.current;g&&rt(g.getViewState().zoom)},[rt,U,L]),d.useEffect(()=>{T!=="cursor"&&X.current!==null&&(X.current=null,tt(null),ie?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[T,ie]),d.useEffect(()=>{T!=="cursor"&&k.current!==null&&(k.current=null,oe.current=null,te?.({index:null,id:null,coordinate:null,pointCoordinate:null}))},[T,te]);const ot=d.useCallback((g,E)=>{const P=J.current;if(!P)return null;const _=P.screenToWorld(g,E);if(!Array.isArray(_)||_.length<2)return null;const B=Number(_[0]),j=Number(_[1]);return!Number.isFinite(B)||!Number.isFinite(j)?null:[B,j]},[]),qn=d.useCallback((g,E)=>{const P=J.current;if(!P)return null;const _=P.worldToScreen(g,E);return Un(_)},[]),kt=d.useCallback((g,E)=>{const P=Ae.current;if(!P)return null;const _=P.getBoundingClientRect();if(!Number.isFinite(_.width)||!Number.isFinite(_.height)||_.width<=0||_.height<=0)return null;const B=g-_.left,j=E-_.top;return!Number.isFinite(B)||!Number.isFinite(j)?null:{screenCoord:[B,j],canvasWidth:Math.max(1,_.width),canvasHeight:Math.max(1,_.height)}},[]),Mt=d.useCallback((g,E,P,_)=>{const B=J.current;return B?ra(g,E,nt,B,Yn,ce,x,P,_):null},[nt,Yn,ce,x]),$n=d.useCallback(()=>{J.current?.requestRender(),je.current?.(),O.current?.()},[]),Zn=d.useMemo(()=>Lt??J.current?.getViewState()??null,[Lt]),Kn=d.useMemo(()=>{if(!t)return null;const g=Zn;return g?{source:t,viewState:g,drawTool:T,interactionLock:Ee,worldToScreen:qn,screenToWorld:ot,requestRedraw:$n}:null},[t,Zn,T,Ee,qn,ot,$n]),gi=d.useCallback(g=>{const E=g.target===Ae.current,P=ot(g.clientX,g.clientY);if(Se){const We=!!P&&P[0]>=0&&P[1]>=0&&!!t&&P[0]<=t.width&&P[1]<=t.height;Se({coordinate:P,clientX:g.clientX,clientY:g.clientY,insideImage:We})}if(T!=="cursor")return;if(!E){St(null,null),X.current!==null&&(X.current=null,tt(null),ie?.({region:null,regionId:null,regionIndex:-1,coordinate:null}));return}if(!P){St(null,null);return}if(te&&St(mt(P),P),!nt.length)return;const _=kt(g.clientX,g.clientY);if(!_)return;const B=Mt(P,_.screenCoord,_.canvasWidth,_.canvasHeight),j=B?.regionId??null,Be=X.current;String(Be)!==String(j)&&(X.current=j,tt(j),ie?.({region:B?.region??null,regionId:j,regionIndex:B?.regionIndex??-1,coordinate:P}))},[T,nt,ot,ie,Se,t,St,mt,te,kt,Mt]),pi=d.useCallback(()=>{Se?.({coordinate:null,clientX:-1,clientY:-1,insideImage:!1}),St(null,null),X.current!==null&&(X.current=null,tt(null),ie?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[ie,Se,St]),bi=d.useCallback(g=>{if(T!=="cursor"||g.target!==Ae.current)return;const E=ot(g.clientX,g.clientY);if(!E)return;if(zt(E,g.button),!nt.length){it(null);return}const P=kt(g.clientX,g.clientY);if(!P)return;const _=Mt(E,P.screenCoord,P.canvasWidth,P.canvasHeight);if(!_){it(null);return}const B=Re!==null&&String(Re)===String(_.regionId)?null:_.regionId;it(B),de?.({region:_.region,regionId:_.regionId,regionIndex:_.regionIndex,coordinate:E})},[T,nt,ot,de,Re,it,zt,kt,Mt]),wi=d.useCallback(g=>{if(T!=="brush"||ee?.clickSelectRoi!==!0||!nt.length)return!1;const E=J.current,P=Ae.current;if(!E||!P)return!1;const _=P.getBoundingClientRect();if(_.width<=0||_.height<=0)return!1;const B=Un(E.worldToScreen(g[0],g[1]));if(!B)return!1;const j=Mt(g,B,_.width,_.height);if(!j)return!1;const Be=Re!==null&&String(Re)===String(j.regionId)?null:j.regionId;return it(Be),de?.({region:j.region,regionId:j.regionId,regionIndex:j.regionIndex,coordinate:g}),!0},[T,ee?.clickSelectRoi,nt,Re,it,de,Mt]),yi=d.useCallback(g=>{if(!Z||T!=="cursor"||g.target!==Ae.current)return;g.preventDefault();const E=ot(g.clientX,g.clientY);E&&zt(E,g.button)},[T,ot,zt,Z]);return d.useEffect(()=>{const g=Ae.current;if(!g||!t)return;const E=new di(g,t,{onViewStateChange:Hn,onStats:Gn,onTileError:o,onContextLost:s,onContextRestored:a,authToken:b,imageColorSettings:n,ctrlDragRotate:w,pointSizeByZoom:A,pointStrokeScale:v,minZoom:U,maxZoom:L,viewTransition:G});return J.current=E,e&&E.setViewState(e),rt(E.getViewState().zoom),E.setInteractionLock(Ee),Ie&&u(E.getViewState()),()=>{ft(),yt(0),E.destroy(),J.current=null}},[t,Gn,o,s,a,b,w,A,v,Hn,Ie,rt,ft,yt]),d.useEffect(()=>{const g=J.current;!g||!e||g.setViewState(e)},[e]),d.useEffect(()=>{const g=J.current;g&&g.fitToImage()},[m]),d.useEffect(()=>{const g=J.current;g&&g.resetRotation()},[p]),d.useEffect(()=>{const g=J.current;!g||!y||g.setPointPalette(y)},[y]),d.useEffect(()=>{const g=J.current;g&&g.setPointSizeByZoom(A)},[A]),d.useEffect(()=>{const g=J.current;g&&g.setPointStrokeScale(v)},[v]),d.useEffect(()=>{const g=J.current;g&&(g.setZoomRange(U,L),rt(g.getViewState().zoom))},[U,L,rt]),d.useEffect(()=>{const g=J.current;g&&g.setViewTransition(G)},[G]),d.useEffect(()=>{const g=J.current;g&&g.setImageColorSettings(n)},[n]),d.useEffect(()=>{const g=J.current;g&&g.setPointData(dt)},[dt]),d.useEffect(()=>{if(!pe)return;const E=li($?dt:f,Ue,{paletteIndexToTermId:Te,includeEmptyRegions:!0});pe(E)},[pe,$,f,dt,Ue,Te]),d.useEffect(()=>{const g=J.current;g&&g.setInteractionLock(Ee)},[Ee]),He.jsxs("div",{className:ve,style:$e,onPointerMove:gi,onPointerLeave:pi,onClick:bi,onContextMenu:yi,children:[He.jsx("canvas",{ref:Ae,className:"wsi-render-canvas",style:{position:"absolute",inset:0,zIndex:1,width:"100%",height:"100%",display:"block",touchAction:"none",cursor:T==="cursor"&&Et!==null?"pointer":Ee?"crosshair":"grab"}}),t&&Kn&&Array.isArray(R)&&R.length>0?R.map((g,E)=>He.jsx("div",{className:g.className,style:{position:"absolute",inset:0,zIndex:g.zIndex??3,pointerEvents:g.pointerEvents??"none",...g.style},children:g.render(Kn)},g.id??E)):null,t?He.jsx(Kr,{tool:T,enabled:T!=="cursor",imageWidth:t.width,imageHeight:t.height,imageMpp:t.mpp,imageZoom:t.maxTierZoom,stampOptions:D,brushOptions:ee,drawFillColor:H,projectorRef:J,onBrushTap:wi,viewStateSignal:e,persistedRegions:Ue,patchRegions:Oe,regionStrokeStyle:V,regionStrokeHoverStyle:Ce,regionStrokeActiveStyle:De,patchStrokeStyle:Pe,resolveRegionStrokeStyle:fe,resolveRegionLabelStyle:ce,overlayShapes:I,hoveredRegionId:Et,activeRegionId:Re,regionLabelStyle:re,drawAreaTooltip:q,autoLiftRegionLabelAtMaxZoom:he,regionLabelAutoLiftOffsetPx:x,invalidateRef:je,onDrawComplete:me,onPatchComplete:K}):null,c?He.jsx("pre",{"data-open-plant-debug-overlay":!0,style:Je,children:mi}):null,t&&Ye&&He.jsx(Jr,{source:t,projectorRef:J,authToken:b,options:Fe,invalidateRef:O,className:Me?.className,style:Me?.style})]})}exports.DEFAULT_POINT_COLOR=Bn;exports.DrawLayer=Kr;exports.M1TileRenderer=Lr;exports.OverviewMap=Jr;exports.TileScheduler=fi;exports.TileViewerCanvas=as;exports.WsiTileRenderer=di;exports.WsiViewerCanvas=ia;exports.buildPointSpatialIndexAsync=ui;exports.buildTermPalette=uo;exports.calcScaleLength=so;exports.calcScaleResolution=Ln;exports.clamp=ae;exports.closeRing=Ne;exports.computeRoiPointGroups=li;exports.createCircle=Tn;exports.createRectangle=an;exports.filterPointDataByPolygons=Ft;exports.filterPointDataByPolygonsHybrid=ri;exports.filterPointDataByPolygonsInWorker=si;exports.filterPointIndicesByPolygons=ei;exports.filterPointIndicesByPolygonsInWorker=bs;exports.getWebGpuCapabilities=ms;exports.hexToRgba=Xr;exports.isSameViewState=ao;exports.lookupCellIndex=ai;exports.normalizeImageInfo=os;exports.prefilterPointsByBoundsWebGpu=ni;exports.terminatePointHitIndexWorker=As;exports.terminateRoiClipWorker=ps;exports.toBearerToken=co;exports.toTileUrl=zn;
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;
159
163
  //# sourceMappingURL=index.cjs.map