open-plant 1.4.19 → 1.4.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +8 -8
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +913 -989
- package/dist/index.js.map +1 -1
- package/dist/types/core/gl-utils.d.ts +3 -1
- package/dist/types/core/gl-utils.d.ts.map +1 -1
- package/dist/types/core/m1-tile-renderer.d.ts +1 -0
- package/dist/types/core/m1-tile-renderer.d.ts.map +1 -1
- package/dist/types/react/wsi-viewer.d.ts +2 -1
- package/dist/types/react/wsi-viewer.d.ts.map +1 -1
- package/dist/types/wsi/wsi-renderer-types.d.ts +1 -0
- package/dist/types/wsi/wsi-renderer-types.d.ts.map +1 -1
- package/dist/types/wsi/wsi-tile-renderer.d.ts +2 -0
- package/dist/types/wsi/wsi-tile-renderer.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var co=Object.defineProperty;var uo=(t,e,n)=>e in t?co(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var E=(t,e,n)=>uo(t,typeof e!="symbol"?e+"":e,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ge=require("react/jsx-runtime"),g=require("react");var ft=typeof document<"u"?document.currentScript:null;function $n(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 xt(t,e,n){const r=$n(t,t.VERTEX_SHADER,e),i=$n(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
|
|
1
|
+
"use strict";var co=Object.defineProperty;var uo=(t,e,n)=>e in t?co(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var E=(t,e,n)=>uo(t,typeof e!="symbol"?e+"":e,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ge=require("react/jsx-runtime"),g=require("react");var ft=typeof document<"u"?document.currentScript:null;function $n(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 xt(t,e,n){const r=$n(t,t.VERTEX_SHADER,e),i=$n(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 Ie(t,e,n){const r=t.getUniformLocation(e,n);if(!r)throw new Error(`Failed to get uniform location: ${n}`);return r}function fo(t,e){const n=t.getContext("webgl2",{alpha:!1,antialias:!1,depth:!1,stencil:!1,preserveDrawingBuffer:e?.preserveDrawingBuffer??!1,powerPreference:"high-performance"});if(!n)throw new Error("WebGL2 is not available.");return n}function ln(t){return t*Math.PI/180}class ci{constructor(){E(this,"viewportWidth",1);E(this,"viewportHeight",1);E(this,"viewState",{offsetX:0,offsetY:0,zoom:1,rotationDeg:0})}setViewport(e,n){this.viewportWidth=Math.max(1,e),this.viewportHeight=Math.max(1,n)}getViewportSize(){return{width:this.viewportWidth,height:this.viewportHeight}}setViewState(e){e.offsetX!==void 0&&(this.viewState.offsetX=e.offsetX),e.offsetY!==void 0&&(this.viewState.offsetY=e.offsetY),e.zoom!==void 0&&(this.viewState.zoom=Math.max(1e-4,e.zoom)),typeof e.rotationDeg=="number"&&Number.isFinite(e.rotationDeg)&&(this.viewState.rotationDeg=e.rotationDeg)}getViewState(){return{...this.viewState}}getCenter(){const e=Math.max(1e-6,this.viewState.zoom);return[this.viewState.offsetX+this.viewportWidth/(2*e),this.viewState.offsetY+this.viewportHeight/(2*e)]}setCenter(e,n){const r=Math.max(1e-6,this.viewState.zoom);this.viewState.offsetX=e-this.viewportWidth/(2*r),this.viewState.offsetY=n-this.viewportHeight/(2*r)}screenToWorld(e,n){const r=Math.max(1e-6,this.viewState.zoom),[i,o]=this.getCenter(),s=this.viewState.rotationDeg??0,a=(e-this.viewportWidth*.5)/r,l=(n-this.viewportHeight*.5)/r,c=ln(s),f=Math.cos(c),u=Math.sin(c);return[i+a*f-l*u,o+a*u+l*f]}worldToScreen(e,n){const r=Math.max(1e-6,this.viewState.zoom),[i,o]=this.getCenter(),s=this.viewState.rotationDeg??0,a=e-i,l=n-o,c=ln(s),f=Math.cos(c),u=Math.sin(c),h=a*f+l*u,d=-a*u+l*f;return[this.viewportWidth*.5+h*r,this.viewportHeight*.5+d*r]}getViewCorners(){const e=this.viewportWidth,n=this.viewportHeight;return[this.screenToWorld(0,0),this.screenToWorld(e,0),this.screenToWorld(e,n),this.screenToWorld(0,n)]}getMatrix(){const e=Math.max(1e-6,this.viewState.zoom),n=this.viewState.rotationDeg??0;if(n===0){const m=this.viewportWidth/e,p=this.viewportHeight/e,b=2/m,y=-2/p,x=-1-this.viewState.offsetX*b,M=1-this.viewState.offsetY*y;return new Float32Array([b,0,0,0,y,0,x,M,1])}const[r,i]=this.getCenter(),o=ln(n),s=Math.cos(o),a=Math.sin(o),l=2*e*s/this.viewportWidth,c=2*e*a/this.viewportWidth,f=2*e*a/this.viewportHeight,u=-2*e*s/this.viewportHeight,h=-(l*r+c*i),d=-(f*r+u*i);return new Float32Array([l,f,0,c,u,0,h,d,1])}}const ho=`#version 300 es
|
|
2
2
|
precision highp float;
|
|
3
3
|
|
|
4
4
|
in vec2 aUnit;
|
|
@@ -29,8 +29,8 @@ out vec4 outColor;
|
|
|
29
29
|
void main() {
|
|
30
30
|
outColor = texture(uTexture, vUv);
|
|
31
31
|
}
|
|
32
|
-
`;class ui{constructor(e){E(this,"canvas");E(this,"gl");E(this,"camera",new ci);E(this,"imageWidth");E(this,"imageHeight");E(this,"clearColor");E(this,"program");E(this,"vao");E(this,"quadBuffer");E(this,"uCameraLocation");E(this,"uBoundsLocation");E(this,"uTextureLocation");E(this,"resizeObserver");E(this,"tiles",[]);E(this,"frameId",null);E(this,"loadVersion",0);E(this,"destroyed",!1);E(this,"fitted",!1);E(this,"controlledViewState",!1);this.canvas=e.canvas,this.imageWidth=Math.max(1,e.imageWidth),this.imageHeight=Math.max(1,e.imageHeight),this.clearColor=e.clearColor??[.03,.05,.08,1],this.gl=fo(this.canvas),this.program=xt(this.gl,ho,mo);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=
|
|
33
|
-
`);const o=e+(n?" ":"│ ");t.left&&yn(t.left,o,!1,r,i),t.right&&yn(t.right,o,!0,r,i)}}class Dn{constructor(e=go){this._root=null,this._size=0,this._comparator=e}insert(e,n){return this._size++,this._root=cn(e,n,this._root,this._comparator)}add(e,n){const r=new rt(e,n);this._root===null&&(r.left=r.right=null,this._size++,this._root=r);const i=this._comparator,o=et(e,this._root,i),s=i(e,o.key);return s===0?this._root=o:(s<0?(r.left=o.left,r.right=o,o.left=null):s>0&&(r.right=o.right,r.left=o,o.right=null),this._size++,this._root=r),this._root}remove(e){this._root=this._remove(e,this._root,this._comparator)}_remove(e,n,r){let i;return n===null?null:(n=et(e,n,r),r(e,n.key)===0?(n.left===null?i=n.right:(i=et(e,n.left,r),i.right=n.right),this._size--,i):n)}pop(){let e=this._root;if(e){for(;e.left;)e=e.left;return this._root=et(e.key,this._root,this._comparator),this._root=this._remove(e.key,this._root,this._comparator),{key:e.key,data:e.data}}return null}findStatic(e){let n=this._root;const r=this._comparator;for(;n;){const i=r(e,n.key);if(i===0)return n;i<0?n=n.left:n=n.right}return null}find(e){return this._root&&(this._root=et(e,this._root,this._comparator),this._comparator(e,this._root.key)!==0)?null:this._root}contains(e){let n=this._root;const r=this._comparator;for(;n;){const i=r(e,n.key);if(i===0)return!0;i<0?n=n.left:n=n.right}return!1}forEach(e,n){let r=this._root;const i=[];let o=!1;for(;!o;)r!==null?(i.push(r),r=r.left):i.length!==0?(r=i.pop(),e.call(n,r),r=r.right):o=!0;return this}range(e,n,r,i){const o=[],s=this._comparator;let a=this._root,l;for(;o.length!==0||a;)if(a)o.push(a),a=a.left;else{if(a=o.pop(),l=s(a.key,n),l>0)break;if(s(a.key,e)>=0&&r.call(i,a))return this;a=a.right}return this}keys(){const e=[];return this.forEach(({key:n})=>{e.push(n)}),e}values(){const e=[];return this.forEach(({data:n})=>{e.push(n)}),e}min(){return this._root?this.minNode(this._root).key:null}max(){return this._root?this.maxNode(this._root).key:null}minNode(e=this._root){if(e)for(;e.left;)e=e.left;return e}maxNode(e=this._root){if(e)for(;e.right;)e=e.right;return e}at(e){let n=this._root,r=!1,i=0;const o=[];for(;!r;)if(n)o.push(n),n=n.left;else if(o.length>0){if(n=o.pop(),i===e)return n;i++,n=n.right}else r=!0;return null}next(e){let n=this._root,r=null;if(e.right){for(r=e.right;r.left;)r=r.left;return r}const i=this._comparator;for(;n;){const o=i(e.key,n.key);if(o===0)break;o<0?(r=n,n=n.left):n=n.right}return r}prev(e){let n=this._root,r=null;if(e.left!==null){for(r=e.left;r.right;)r=r.right;return r}const i=this._comparator;for(;n;){const o=i(e.key,n.key);if(o===0)break;o<0?n=n.left:(r=n,n=n.right)}return r}clear(){return this._root=null,this._size=0,this}toList(){return bo(this._root)}load(e,n=[],r=!1){let i=e.length;const o=this._comparator;if(r&&wn(e,n,0,i-1,o),this._root===null)this._root=bn(e,n,0,i),this._size=i;else{const s=xo(this.toList(),yo(e,n),o);i=this._size+i,this._root=xn({head:s},0,i)}return this}isEmpty(){return this._root===null}get size(){return this._size}get root(){return this._root}toString(e=n=>String(n.key)){const n=[];return yn(this._root,"",!0,r=>n.push(r),e),n.join("")}update(e,n,r){const i=this._comparator;let{left:o,right:s}=Kn(e,this._root,i);i(e,n)<0?s=cn(n,r,s,i):o=cn(n,r,o,i),this._root=po(o,s,i)}split(e){return Kn(e,this._root,this._comparator)}*[Symbol.iterator](){let e=this._root;const n=[];let r=!1;for(;!r;)e!==null?(n.push(e),e=e.left):n.length!==0?(e=n.pop(),yield e,e=e.right):r=!0}}function bn(t,e,n,r){const i=r-n;if(i>0){const o=n+Math.floor(i/2),s=t[o],a=e[o],l=new rt(s,a);return l.left=bn(t,e,n,o),l.right=bn(t,e,o+1,r),l}return null}function yo(t,e){const n=new rt(null,null);let r=n;for(let i=0;i<t.length;i++)r=r.next=new rt(t[i],e[i]);return r.next=null,n.next}function bo(t){let e=t;const n=[];let r=!1;const i=new rt(null,null);let o=i;for(;!r;)e?(n.push(e),e=e.left):n.length>0?(e=o=o.next=n.pop(),e=e.right):r=!0;return o.next=null,i.next}function xn(t,e,n){const r=n-e;if(r>0){const i=e+Math.floor(r/2),o=xn(t,e,i),s=t.head;return s.left=o,t.head=t.head.next,s.right=xn(t,i+1,n),s}return null}function xo(t,e,n){const r=new rt(null,null);let i=r,o=t,s=e;for(;o!==null&&s!==null;)n(o.key,s.key)<0?(i.next=o,o=o.next):(i.next=s,s=s.next),i=i.next;return o!==null?i.next=o:s!==null&&(i.next=s),r.next}function wn(t,e,n,r,i){if(n>=r)return;const o=t[n+r>>1];let s=n-1,a=r+1;for(;;){do s++;while(i(t[s],o)<0);do a--;while(i(t[a],o)>0);if(s>=a)break;let l=t[s];t[s]=t[a],t[a]=l,l=e[s],e[s]=e[a],e[a]=l}wn(t,e,n,a,i),wn(t,e,a+1,r,i)}const je=11102230246251565e-32,Be=134217729,wo=(3+8*je)*je;function un(t,e,n,r,i){let o,s,a,l,c=e[0],f=r[0],u=0,h=0;f>c==f>-c?(o=c,c=e[++u]):(o=f,f=r[++h]);let d=0;if(u<t&&h<n)for(f>c==f>-c?(s=c+o,a=o-(s-c),c=e[++u]):(s=f+o,a=o-(s-f),f=r[++h]),o=s,a!==0&&(i[d++]=a);u<t&&h<n;)f>c==f>-c?(s=o+c,l=s-o,a=o-(s-l)+(c-l),c=e[++u]):(s=o+f,l=s-o,a=o-(s-l)+(f-l),f=r[++h]),o=s,a!==0&&(i[d++]=a);for(;u<t;)s=o+c,l=s-o,a=o-(s-l)+(c-l),c=e[++u],o=s,a!==0&&(i[d++]=a);for(;h<n;)s=o+f,l=s-o,a=o-(s-l)+(f-l),f=r[++h],o=s,a!==0&&(i[d++]=a);return(o!==0||d===0)&&(i[d++]=o),d}function So(t,e){let n=e[0];for(let r=1;r<t;r++)n+=e[r];return n}function Ct(t){return new Float64Array(t)}const Eo=(3+16*je)*je,Ro=(2+12*je)*je,Mo=(9+64*je)*je*je,lt=Ct(4),jn=Ct(8),Qn=Ct(12),Jn=Ct(16),Ue=Ct(4);function Ao(t,e,n,r,i,o,s){let a,l,c,f,u,h,d,m,p,b,y,x,M,S,C,A,k,U;const Y=t-i,P=n-i,T=e-o,L=r-o;S=Y*L,h=Be*Y,d=h-(h-Y),m=Y-d,h=Be*L,p=h-(h-L),b=L-p,C=m*b-(S-d*p-m*p-d*b),A=T*P,h=Be*T,d=h-(h-T),m=T-d,h=Be*P,p=h-(h-P),b=P-p,k=m*b-(A-d*p-m*p-d*b),y=C-k,u=C-y,lt[0]=C-(y+u)+(u-k),x=S+y,u=x-S,M=S-(x-u)+(y-u),y=M-A,u=M-y,lt[1]=M-(y+u)+(u-A),U=x+y,u=U-x,lt[2]=x-(U-u)+(y-u),lt[3]=U;let F=So(4,lt),W=Ro*s;if(F>=W||-F>=W||(u=t-Y,a=t-(Y+u)+(u-i),u=n-P,c=n-(P+u)+(u-i),u=e-T,l=e-(T+u)+(u-o),u=r-L,f=r-(L+u)+(u-o),a===0&&l===0&&c===0&&f===0)||(W=Mo*s+wo*Math.abs(F),F+=Y*f+L*a-(T*c+P*l),F>=W||-F>=W))return F;S=a*L,h=Be*a,d=h-(h-a),m=a-d,h=Be*L,p=h-(h-L),b=L-p,C=m*b-(S-d*p-m*p-d*b),A=l*P,h=Be*l,d=h-(h-l),m=l-d,h=Be*P,p=h-(h-P),b=P-p,k=m*b-(A-d*p-m*p-d*b),y=C-k,u=C-y,Ue[0]=C-(y+u)+(u-k),x=S+y,u=x-S,M=S-(x-u)+(y-u),y=M-A,u=M-y,Ue[1]=M-(y+u)+(u-A),U=x+y,u=U-x,Ue[2]=x-(U-u)+(y-u),Ue[3]=U;const $=un(4,lt,4,Ue,jn);S=Y*f,h=Be*Y,d=h-(h-Y),m=Y-d,h=Be*f,p=h-(h-f),b=f-p,C=m*b-(S-d*p-m*p-d*b),A=T*c,h=Be*T,d=h-(h-T),m=T-d,h=Be*c,p=h-(h-c),b=c-p,k=m*b-(A-d*p-m*p-d*b),y=C-k,u=C-y,Ue[0]=C-(y+u)+(u-k),x=S+y,u=x-S,M=S-(x-u)+(y-u),y=M-A,u=M-y,Ue[1]=M-(y+u)+(u-A),U=x+y,u=U-x,Ue[2]=x-(U-u)+(y-u),Ue[3]=U;const z=un($,jn,4,Ue,Qn);S=a*f,h=Be*a,d=h-(h-a),m=a-d,h=Be*f,p=h-(h-f),b=f-p,C=m*b-(S-d*p-m*p-d*b),A=l*c,h=Be*l,d=h-(h-l),m=l-d,h=Be*c,p=h-(h-c),b=c-p,k=m*b-(A-d*p-m*p-d*b),y=C-k,u=C-y,Ue[0]=C-(y+u)+(u-k),x=S+y,u=x-S,M=S-(x-u)+(y-u),y=M-A,u=M-y,Ue[1]=M-(y+u)+(u-A),U=x+y,u=U-x,Ue[2]=x-(U-u)+(y-u),Ue[3]=U;const ae=un(z,Qn,4,Ue,Jn);return Jn[ae-1]}function Co(t,e,n,r,i,o){const s=(e-o)*(n-i),a=(t-i)*(r-o),l=s-a,c=Math.abs(s+a);return Math.abs(l)>=Eo*c?l:-Ao(t,e,n,r,i,o,c)}const gt=(t,e)=>t.ll.x<=e.x&&e.x<=t.ur.x&&t.ll.y<=e.y&&e.y<=t.ur.y,Sn=(t,e)=>{if(e.ur.x<t.ll.x||t.ur.x<e.ll.x||e.ur.y<t.ll.y||t.ur.y<e.ll.y)return null;const n=t.ll.x<e.ll.x?e.ll.x:t.ll.x,r=t.ur.x<e.ur.x?t.ur.x:e.ur.x,i=t.ll.y<e.ll.y?e.ll.y:t.ll.y,o=t.ur.y<e.ur.y?t.ur.y:e.ur.y;return{ll:{x:n,y:i},ur:{x:r,y:o}}};let tt=Number.EPSILON;tt===void 0&&(tt=Math.pow(2,-52));const Po=tt*tt,er=(t,e)=>{if(-tt<t&&t<tt&&-tt<e&&e<tt)return 0;const n=t-e;return n*n<Po*t*e?0:t<e?-1:1};class vo{constructor(){this.reset()}reset(){this.xRounder=new tr,this.yRounder=new tr}round(e,n){return{x:this.xRounder.round(e),y:this.yRounder.round(n)}}}class tr{constructor(){this.tree=new Dn,this.round(0)}round(e){const n=this.tree.add(e),r=this.tree.prev(n);if(r!==null&&er(n.key,r.key)===0)return this.tree.remove(e),r.key;const i=this.tree.next(n);return i!==null&&er(n.key,i.key)===0?(this.tree.remove(e),i.key):e}}const wt=new vo,Wt=(t,e)=>t.x*e.y-t.y*e.x,fi=(t,e)=>t.x*e.x+t.y*e.y,nr=(t,e,n)=>{const r=Co(t.x,t.y,e.x,e.y,n.x,n.y);return r>0?-1:r<0?1:0},qt=t=>Math.sqrt(fi(t,t)),To=(t,e,n)=>{const r={x:e.x-t.x,y:e.y-t.y},i={x:n.x-t.x,y:n.y-t.y};return Wt(i,r)/qt(i)/qt(r)},Io=(t,e,n)=>{const r={x:e.x-t.x,y:e.y-t.y},i={x:n.x-t.x,y:n.y-t.y};return fi(i,r)/qt(i)/qt(r)},rr=(t,e,n)=>e.y===0?null:{x:t.x+e.x/e.y*(n-t.y),y:n},ir=(t,e,n)=>e.x===0?null:{x:n,y:t.y+e.y/e.x*(n-t.x)},_o=(t,e,n,r)=>{if(e.x===0)return ir(n,r,t.x);if(r.x===0)return ir(t,e,n.x);if(e.y===0)return rr(n,r,t.y);if(r.y===0)return rr(t,e,n.y);const i=Wt(e,r);if(i==0)return null;const o={x:n.x-t.x,y:n.y-t.y},s=Wt(o,e)/i,a=Wt(o,r)/i,l=t.x+a*e.x,c=n.x+s*r.x,f=t.y+a*e.y,u=n.y+s*r.y,h=(l+c)/2,d=(f+u)/2;return{x:h,y:d}};class Xe{static compare(e,n){const r=Xe.comparePoints(e.point,n.point);return r!==0?r:(e.point!==n.point&&e.link(n),e.isLeft!==n.isLeft?e.isLeft?1:-1:nt.compare(e.segment,n.segment))}static comparePoints(e,n){return e.x<n.x?-1:e.x>n.x?1:e.y<n.y?-1:e.y>n.y?1:0}constructor(e,n){e.events===void 0?e.events=[this]:e.events.push(this),this.point=e,this.isLeft=n}link(e){if(e.point===this.point)throw new Error("Tried to link already linked events");const n=e.point.events;for(let r=0,i=n.length;r<i;r++){const o=n[r];this.point.events.push(o),o.point=this.point}this.checkForConsuming()}checkForConsuming(){const e=this.point.events.length;for(let n=0;n<e;n++){const r=this.point.events[n];if(r.segment.consumedBy===void 0)for(let i=n+1;i<e;i++){const o=this.point.events[i];o.consumedBy===void 0&&r.otherSE.point.events===o.otherSE.point.events&&r.segment.consume(o.segment)}}}getAvailableLinkedEvents(){const e=[];for(let n=0,r=this.point.events.length;n<r;n++){const i=this.point.events[n];i!==this&&!i.segment.ringOut&&i.segment.isInResult()&&e.push(i)}return e}getLeftmostComparator(e){const n=new Map,r=i=>{const o=i.otherSE;n.set(i,{sine:To(this.point,e.point,o.point),cosine:Io(this.point,e.point,o.point)})};return(i,o)=>{n.has(i)||r(i),n.has(o)||r(o);const{sine:s,cosine:a}=n.get(i),{sine:l,cosine:c}=n.get(o);return s>=0&&l>=0?a<c?1:a>c?-1:0:s<0&&l<0?a<c?-1:a>c?1:0:l<s?-1:l>s?1:0}}}let Fo=0;class nt{static compare(e,n){const r=e.leftSE.point.x,i=n.leftSE.point.x,o=e.rightSE.point.x,s=n.rightSE.point.x;if(s<r)return 1;if(o<i)return-1;const a=e.leftSE.point.y,l=n.leftSE.point.y,c=e.rightSE.point.y,f=n.rightSE.point.y;if(r<i){if(l<a&&l<c)return 1;if(l>a&&l>c)return-1;const u=e.comparePoint(n.leftSE.point);if(u<0)return 1;if(u>0)return-1;const h=n.comparePoint(e.rightSE.point);return h!==0?h:-1}if(r>i){if(a<l&&a<f)return-1;if(a>l&&a>f)return 1;const u=n.comparePoint(e.leftSE.point);if(u!==0)return u;const h=e.comparePoint(n.rightSE.point);return h<0?1:h>0?-1:1}if(a<l)return-1;if(a>l)return 1;if(o<s){const u=n.comparePoint(e.rightSE.point);if(u!==0)return u}if(o>s){const u=e.comparePoint(n.rightSE.point);if(u<0)return 1;if(u>0)return-1}if(o!==s){const u=c-a,h=o-r,d=f-l,m=s-i;if(u>h&&d<m)return 1;if(u<h&&d>m)return-1}return o>s?1:o<s||c<f?-1:c>f?1:e.id<n.id?-1:e.id>n.id?1:0}constructor(e,n,r,i){this.id=++Fo,this.leftSE=e,e.segment=this,e.otherSE=n,this.rightSE=n,n.segment=this,n.otherSE=e,this.rings=r,this.windings=i}static fromRing(e,n,r){let i,o,s;const a=Xe.comparePoints(e,n);if(a<0)i=e,o=n,s=1;else if(a>0)i=n,o=e,s=-1;else throw new Error(`Tried to create degenerate segment at [${e.x}, ${e.y}]`);const l=new Xe(i,!0),c=new Xe(o,!1);return new nt(l,c,[r],[s])}replaceRightSE(e){this.rightSE=e,this.rightSE.segment=this,this.rightSE.otherSE=this.leftSE,this.leftSE.otherSE=this.rightSE}bbox(){const e=this.leftSE.point.y,n=this.rightSE.point.y;return{ll:{x:this.leftSE.point.x,y:e<n?e:n},ur:{x:this.rightSE.point.x,y:e>n?e:n}}}vector(){return{x:this.rightSE.point.x-this.leftSE.point.x,y:this.rightSE.point.y-this.leftSE.point.y}}isAnEndpoint(e){return e.x===this.leftSE.point.x&&e.y===this.leftSE.point.y||e.x===this.rightSE.point.x&&e.y===this.rightSE.point.y}comparePoint(e){if(this.isAnEndpoint(e))return 0;const n=this.leftSE.point,r=this.rightSE.point,i=this.vector();if(n.x===r.x)return e.x===n.x?0:e.x<n.x?1:-1;const o=(e.y-n.y)/i.y,s=n.x+o*i.x;if(e.x===s)return 0;const a=(e.x-n.x)/i.x,l=n.y+a*i.y;return e.y===l?0:e.y<l?-1:1}getIntersection(e){const n=this.bbox(),r=e.bbox(),i=Sn(n,r);if(i===null)return null;const o=this.leftSE.point,s=this.rightSE.point,a=e.leftSE.point,l=e.rightSE.point,c=gt(n,a)&&this.comparePoint(a)===0,f=gt(r,o)&&e.comparePoint(o)===0,u=gt(n,l)&&this.comparePoint(l)===0,h=gt(r,s)&&e.comparePoint(s)===0;if(f&&c)return h&&!u?s:!h&&u?l:null;if(f)return u&&o.x===l.x&&o.y===l.y?null:o;if(c)return h&&s.x===a.x&&s.y===a.y?null:a;if(h&&u)return null;if(h)return s;if(u)return l;const d=_o(o,this.vector(),a,e.vector());return d===null||!gt(i,d)?null:wt.round(d.x,d.y)}split(e){const n=[],r=e.events!==void 0,i=new Xe(e,!0),o=new Xe(e,!1),s=this.rightSE;this.replaceRightSE(o),n.push(o),n.push(i);const a=new nt(i,s,this.rings.slice(),this.windings.slice());return Xe.comparePoints(a.leftSE.point,a.rightSE.point)>0&&a.swapEvents(),Xe.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),r&&(i.checkForConsuming(),o.checkForConsuming()),n}swapEvents(){const e=this.rightSE;this.rightSE=this.leftSE,this.leftSE=e,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(let n=0,r=this.windings.length;n<r;n++)this.windings[n]*=-1}consume(e){let n=this,r=e;for(;n.consumedBy;)n=n.consumedBy;for(;r.consumedBy;)r=r.consumedBy;const i=nt.compare(n,r);if(i!==0){if(i>0){const o=n;n=r,r=o}if(n.prev===r){const o=n;n=r,r=o}for(let o=0,s=r.rings.length;o<s;o++){const a=r.rings[o],l=r.windings[o],c=n.rings.indexOf(a);c===-1?(n.rings.push(a),n.windings.push(l)):n.windings[c]+=l}r.rings=null,r.windings=null,r.consumedBy=n,r.leftSE.consumedBy=n.leftSE,r.rightSE.consumedBy=n.rightSE}}prevInResult(){return this._prevInResult!==void 0?this._prevInResult:(this.prev?this.prev.isInResult()?this._prevInResult=this.prev:this._prevInResult=this.prev.prevInResult():this._prevInResult=null,this._prevInResult)}beforeState(){if(this._beforeState!==void 0)return this._beforeState;if(!this.prev)this._beforeState={rings:[],windings:[],multiPolys:[]};else{const e=this.prev.consumedBy||this.prev;this._beforeState=e.afterState()}return this._beforeState}afterState(){if(this._afterState!==void 0)return this._afterState;const e=this.beforeState();this._afterState={rings:e.rings.slice(0),windings:e.windings.slice(0),multiPolys:[]};const n=this._afterState.rings,r=this._afterState.windings,i=this._afterState.multiPolys;for(let a=0,l=this.rings.length;a<l;a++){const c=this.rings[a],f=this.windings[a],u=n.indexOf(c);u===-1?(n.push(c),r.push(f)):r[u]+=f}const o=[],s=[];for(let a=0,l=n.length;a<l;a++){if(r[a]===0)continue;const c=n[a],f=c.poly;if(s.indexOf(f)===-1)if(c.isExterior)o.push(f);else{s.indexOf(f)===-1&&s.push(f);const u=o.indexOf(c.poly);u!==-1&&o.splice(u,1)}}for(let a=0,l=o.length;a<l;a++){const c=o[a].multiPoly;i.indexOf(c)===-1&&i.push(c)}return this._afterState}isInResult(){if(this.consumedBy)return!1;if(this._isInResult!==void 0)return this._isInResult;const e=this.beforeState().multiPolys,n=this.afterState().multiPolys;switch(Ze.type){case"union":{const r=e.length===0,i=n.length===0;this._isInResult=r!==i;break}case"intersection":{let r,i;e.length<n.length?(r=e.length,i=n.length):(r=n.length,i=e.length),this._isInResult=i===Ze.numMultiPolys&&r<i;break}case"xor":{const r=Math.abs(e.length-n.length);this._isInResult=r%2===1;break}case"difference":{const r=i=>i.length===1&&i[0].isSubject;this._isInResult=r(e)!==r(n);break}default:throw new Error(`Unrecognized operation type found ${Ze.type}`)}return this._isInResult}}class or{constructor(e,n,r){if(!Array.isArray(e)||e.length===0)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=n,this.isExterior=r,this.segments=[],typeof e[0][0]!="number"||typeof e[0][1]!="number")throw new Error("Input geometry is not a valid Polygon or MultiPolygon");const i=wt.round(e[0][0],e[0][1]);this.bbox={ll:{x:i.x,y:i.y},ur:{x:i.x,y:i.y}};let o=i;for(let s=1,a=e.length;s<a;s++){if(typeof e[s][0]!="number"||typeof e[s][1]!="number")throw new Error("Input geometry is not a valid Polygon or MultiPolygon");let l=wt.round(e[s][0],e[s][1]);l.x===o.x&&l.y===o.y||(this.segments.push(nt.fromRing(o,l,this)),l.x<this.bbox.ll.x&&(this.bbox.ll.x=l.x),l.y<this.bbox.ll.y&&(this.bbox.ll.y=l.y),l.x>this.bbox.ur.x&&(this.bbox.ur.x=l.x),l.y>this.bbox.ur.y&&(this.bbox.ur.y=l.y),o=l)}(i.x!==o.x||i.y!==o.y)&&this.segments.push(nt.fromRing(o,i,this))}getSweepEvents(){const e=[];for(let n=0,r=this.segments.length;n<r;n++){const i=this.segments[n];e.push(i.leftSE),e.push(i.rightSE)}return e}}class Lo{constructor(e,n){if(!Array.isArray(e))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");this.exteriorRing=new or(e[0],this,!0),this.bbox={ll:{x:this.exteriorRing.bbox.ll.x,y:this.exteriorRing.bbox.ll.y},ur:{x:this.exteriorRing.bbox.ur.x,y:this.exteriorRing.bbox.ur.y}},this.interiorRings=[];for(let r=1,i=e.length;r<i;r++){const o=new or(e[r],this,!1);o.bbox.ll.x<this.bbox.ll.x&&(this.bbox.ll.x=o.bbox.ll.x),o.bbox.ll.y<this.bbox.ll.y&&(this.bbox.ll.y=o.bbox.ll.y),o.bbox.ur.x>this.bbox.ur.x&&(this.bbox.ur.x=o.bbox.ur.x),o.bbox.ur.y>this.bbox.ur.y&&(this.bbox.ur.y=o.bbox.ur.y),this.interiorRings.push(o)}this.multiPoly=n}getSweepEvents(){const e=this.exteriorRing.getSweepEvents();for(let n=0,r=this.interiorRings.length;n<r;n++){const i=this.interiorRings[n].getSweepEvents();for(let o=0,s=i.length;o<s;o++)e.push(i[o])}return e}}class sr{constructor(e,n){if(!Array.isArray(e))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");try{typeof e[0][0][0]=="number"&&(e=[e])}catch{}this.polys=[],this.bbox={ll:{x:Number.POSITIVE_INFINITY,y:Number.POSITIVE_INFINITY},ur:{x:Number.NEGATIVE_INFINITY,y:Number.NEGATIVE_INFINITY}};for(let r=0,i=e.length;r<i;r++){const o=new Lo(e[r],this);o.bbox.ll.x<this.bbox.ll.x&&(this.bbox.ll.x=o.bbox.ll.x),o.bbox.ll.y<this.bbox.ll.y&&(this.bbox.ll.y=o.bbox.ll.y),o.bbox.ur.x>this.bbox.ur.x&&(this.bbox.ur.x=o.bbox.ur.x),o.bbox.ur.y>this.bbox.ur.y&&(this.bbox.ur.y=o.bbox.ur.y),this.polys.push(o)}this.isSubject=n}getSweepEvents(){const e=[];for(let n=0,r=this.polys.length;n<r;n++){const i=this.polys[n].getSweepEvents();for(let o=0,s=i.length;o<s;o++)e.push(i[o])}return e}}class Ht{static factory(e){const n=[];for(let r=0,i=e.length;r<i;r++){const o=e[r];if(!o.isInResult()||o.ringOut)continue;let s=null,a=o.leftSE,l=o.rightSE;const c=[a],f=a.point,u=[];for(;s=a,a=l,c.push(a),a.point!==f;)for(;;){const h=a.getAvailableLinkedEvents();if(h.length===0){const p=c[0].point,b=c[c.length-1].point;throw new Error(`Unable to complete output ring starting at [${p.x}, ${p.y}]. Last matching segment found ends at [${b.x}, ${b.y}].`)}if(h.length===1){l=h[0].otherSE;break}let d=null;for(let p=0,b=u.length;p<b;p++)if(u[p].point===a.point){d=p;break}if(d!==null){const p=u.splice(d)[0],b=c.splice(p.index);b.unshift(b[0].otherSE),n.push(new Ht(b.reverse()));continue}u.push({index:c.length,point:a.point});const m=a.getLeftmostComparator(s);l=h.sort(m)[0].otherSE;break}n.push(new Ht(c))}return n}constructor(e){this.events=e;for(let n=0,r=e.length;n<r;n++)e[n].segment.ringOut=this;this.poly=null}getGeom(){let e=this.events[0].point;const n=[e];for(let c=1,f=this.events.length-1;c<f;c++){const u=this.events[c].point,h=this.events[c+1].point;nr(u,e,h)!==0&&(n.push(u),e=u)}if(n.length===1)return null;const r=n[0],i=n[1];nr(r,e,i)===0&&n.shift(),n.push(n[0]);const o=this.isExteriorRing()?1:-1,s=this.isExteriorRing()?0:n.length-1,a=this.isExteriorRing()?n.length:-1,l=[];for(let c=s;c!=a;c+=o)l.push([n[c].x,n[c].y]);return l}isExteriorRing(){if(this._isExteriorRing===void 0){const e=this.enclosingRing();this._isExteriorRing=e?!e.isExteriorRing():!0}return this._isExteriorRing}enclosingRing(){return this._enclosingRing===void 0&&(this._enclosingRing=this._calcEnclosingRing()),this._enclosingRing}_calcEnclosingRing(){let e=this.events[0];for(let i=1,o=this.events.length;i<o;i++){const s=this.events[i];Xe.compare(e,s)>0&&(e=s)}let n=e.segment.prevInResult(),r=n?n.prevInResult():null;for(;;){if(!n)return null;if(!r)return n.ringOut;if(r.ringOut!==n.ringOut)return r.ringOut.enclosingRing()!==n.ringOut?n.ringOut:n.ringOut.enclosingRing();n=r.prevInResult(),r=n?n.prevInResult():null}}}class ar{constructor(e){this.exteriorRing=e,e.poly=this,this.interiorRings=[]}addInterior(e){this.interiorRings.push(e),e.poly=this}getGeom(){const e=[this.exteriorRing.getGeom()];if(e[0]===null)return null;for(let n=0,r=this.interiorRings.length;n<r;n++){const i=this.interiorRings[n].getGeom();i!==null&&e.push(i)}return e}}class Do{constructor(e){this.rings=e,this.polys=this._composePolys(e)}getGeom(){const e=[];for(let n=0,r=this.polys.length;n<r;n++){const i=this.polys[n].getGeom();i!==null&&e.push(i)}return e}_composePolys(e){const n=[];for(let r=0,i=e.length;r<i;r++){const o=e[r];if(!o.poly)if(o.isExteriorRing())n.push(new ar(o));else{const s=o.enclosingRing();s.poly||n.push(new ar(s)),s.poly.addInterior(o)}}return n}}class No{constructor(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:nt.compare;this.queue=e,this.tree=new Dn(n),this.segments=[]}process(e){const n=e.segment,r=[];if(e.consumedBy)return e.isLeft?this.queue.remove(e.otherSE):this.tree.remove(n),r;const i=e.isLeft?this.tree.add(n):this.tree.find(n);if(!i)throw new Error(`Unable to find segment #${n.id} [${n.leftSE.point.x}, ${n.leftSE.point.y}] -> [${n.rightSE.point.x}, ${n.rightSE.point.y}] in SweepLine tree.`);let o=i,s=i,a,l;for(;a===void 0;)o=this.tree.prev(o),o===null?a=null:o.key.consumedBy===void 0&&(a=o.key);for(;l===void 0;)s=this.tree.next(s),s===null?l=null:s.key.consumedBy===void 0&&(l=s.key);if(e.isLeft){let c=null;if(a){const u=a.getIntersection(n);if(u!==null&&(n.isAnEndpoint(u)||(c=u),!a.isAnEndpoint(u))){const h=this._splitSafely(a,u);for(let d=0,m=h.length;d<m;d++)r.push(h[d])}}let f=null;if(l){const u=l.getIntersection(n);if(u!==null&&(n.isAnEndpoint(u)||(f=u),!l.isAnEndpoint(u))){const h=this._splitSafely(l,u);for(let d=0,m=h.length;d<m;d++)r.push(h[d])}}if(c!==null||f!==null){let u=null;c===null?u=f:f===null?u=c:u=Xe.comparePoints(c,f)<=0?c:f,this.queue.remove(n.rightSE),r.push(n.rightSE);const h=n.split(u);for(let d=0,m=h.length;d<m;d++)r.push(h[d])}r.length>0?(this.tree.remove(n),r.push(e)):(this.segments.push(n),n.prev=a)}else{if(a&&l){const c=a.getIntersection(l);if(c!==null){if(!a.isAnEndpoint(c)){const f=this._splitSafely(a,c);for(let u=0,h=f.length;u<h;u++)r.push(f[u])}if(!l.isAnEndpoint(c)){const f=this._splitSafely(l,c);for(let u=0,h=f.length;u<h;u++)r.push(f[u])}}}this.tree.remove(n)}return r}_splitSafely(e,n){this.tree.remove(e);const r=e.rightSE;this.queue.remove(r);const i=e.split(n);return i.push(r),e.consumedBy===void 0&&this.tree.add(e),i}}const lr=typeof process<"u"&&process.env.POLYGON_CLIPPING_MAX_QUEUE_SIZE||1e6,zo=typeof process<"u"&&process.env.POLYGON_CLIPPING_MAX_SWEEPLINE_SEGMENTS||1e6;class Bo{run(e,n,r){Ze.type=e,wt.reset();const i=[new sr(n,!0)];for(let u=0,h=r.length;u<h;u++)i.push(new sr(r[u],!1));if(Ze.numMultiPolys=i.length,Ze.type==="difference"){const u=i[0];let h=1;for(;h<i.length;)Sn(i[h].bbox,u.bbox)!==null?h++:i.splice(h,1)}if(Ze.type==="intersection")for(let u=0,h=i.length;u<h;u++){const d=i[u];for(let m=u+1,p=i.length;m<p;m++)if(Sn(d.bbox,i[m].bbox)===null)return[]}const o=new Dn(Xe.compare);for(let u=0,h=i.length;u<h;u++){const d=i[u].getSweepEvents();for(let m=0,p=d.length;m<p;m++)if(o.insert(d[m]),o.size>lr)throw new Error("Infinite loop when putting segment endpoints in a priority queue (queue size too big).")}const s=new No(o);let a=o.size,l=o.pop();for(;l;){const u=l.key;if(o.size===a){const d=u.segment;throw new Error(`Unable to pop() ${u.isLeft?"left":"right"} SweepEvent [${u.point.x}, ${u.point.y}] from segment #${d.id} [${d.leftSE.point.x}, ${d.leftSE.point.y}] -> [${d.rightSE.point.x}, ${d.rightSE.point.y}] from queue.`)}if(o.size>lr)throw new Error("Infinite loop when passing sweep line over endpoints (queue size too big).");if(s.segments.length>zo)throw new Error("Infinite loop when passing sweep line over endpoints (too many sweep line segments).");const h=s.process(u);for(let d=0,m=h.length;d<m;d++){const p=h[d];p.consumedBy===void 0&&o.insert(p)}a=o.size,l=o.pop()}wt.reset();const c=Ht.factory(s.segments);return new Do(c).getGeom()}}const Ze=new Bo,ko=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return Ze.run("union",t,n)},Uo=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return Ze.run("intersection",t,n)},Oo=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return Ze.run("xor",t,n)},Wo=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return Ze.run("difference",t,n)};var Yo={union:ko,intersection:Uo,xor:Oo,difference:Wo};function dt(t){return t==null?null:hi(t)||di(t)||Xo(t)?t:null}function cr(t){return typeof t=="number"&&Number.isFinite(t)}function Yt(t){return Array.isArray(t)&&t.length>=2&&cr(t[0])&&cr(t[1])}function hi(t){return Array.isArray(t)&&t.length>0&&t.every(e=>Yt(e))}function di(t){return Array.isArray(t)&&t.length>0&&t.every(e=>hi(e))}function Xo(t){return Array.isArray(t)&&t.length>0&&t.every(e=>di(e))}function Ye(t){if(!Array.isArray(t)||t.length<3)return[];const e=[];for(const i of t){if(!Array.isArray(i)||i.length<2)continue;const o=Number(i[0]),s=Number(i[1]);if(!Number.isFinite(o)||!Number.isFinite(s))continue;const a=e[e.length-1];a&&a[0]===o&&a[1]===s||e.push([o,s])}if(e.length<3)return[];const n=e[0],r=e[e.length-1];return(n[0]!==r[0]||n[1]!==r[1])&&e.push([n[0],n[1]]),e.length>=4?e:[]}function St(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 fn(t){if(!Array.isArray(t)||t.length===0)return[];const e=[];for(const o of t){const s=Ye(o);s.length>=4&&e.push(s)}if(e.length===0)return[];if(e.length===1)return[e[0]];let n=0,r=0;for(let o=0;o<e.length;o+=1){const s=Math.abs(St(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 mi(t){if(!Array.isArray(t)||t.length===0)return[];const e=t[0];if(Yt(e)){const i=fn([t]);return i.length>0?[i]:[]}if(!Array.isArray(e)||e.length===0)return[];const n=e[0];if(Yt(n)){const i=fn(t);return i.length>0?[i]:[]}if(!Array.isArray(n)||n.length===0||!Yt(n[0]))return[];const r=[];for(const i of t){const o=fn(i);o.length>0&&r.push(o)}return r}function ur(t,e,n){let r=!1;for(let i=0,o=n.length-1;i<n.length;o=i,i+=1){const s=n[i][0],a=n[i][1],l=n[o][0],c=n[o][1];if(a===c||a>e==c>e)continue;t<(l-s)*(e-a)/(c-a)+s&&(r=!r)}return r}function mt(t){const e=[];for(const n of t??[]){const r=mi(n);for(const i of r){const o=i[0];if(!o||o.length<4)continue;let s=1/0,a=1/0,l=-1/0,c=-1/0;for(const[u,h]of o)u<s&&(s=u),u>l&&(l=u),h<a&&(a=h),h>c&&(c=h);if(!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(l)||!Number.isFinite(c))continue;let f=Math.abs(St(o));for(let u=1;u<i.length;u+=1)f-=Math.abs(St(i[u]));e.push({outer:o,holes:i.slice(1),minX:s,minY:a,maxX:l,maxY:c,area:Math.max(1e-6,f)})}}return e}function gi(t,e,n){if(t<n.minX||t>n.maxX||e<n.minY||e>n.maxY||!ur(t,e,n.outer))return!1;for(const r of n.holes)if(ur(t,e,r))return!1;return!0}function Et(t,e,n){for(const r of n)if(gi(t,e,r))return!0;return!1}const Nn=[160,160,160,255];function _(t,e,n){return Math.max(e,Math.min(n,t))}function zn(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 En(t,e){const n=Number(t),r=Number(e);return!Number.isFinite(n)||n<=0||!Number.isFinite(r)||r<=0?0:r*(10/n)}function Vo(t,e,n){let i=100*zn(t,e,n);if(Number(t)){let o="μm";return i>1e3&&(i/=1e3,o="mm"),`${i.toPrecision(3)} ${o}`}return`${Math.round(i*1e3)/1e3} pixels`}function we(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function ot(t){const e=t.fillModes instanceof Uint8Array?t.fillModes.length:Number.MAX_SAFE_INTEGER;return Math.max(0,Math.min(Math.floor(t.count??0),Math.floor((t.positions?.length??0)/2),t.paletteIndices?.length??0,e))}function Rn(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 Go(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 pi(t){const n=String(t??"").trim().match(/^#?([0-9a-fA-F]{6})$/);if(!n)return[...Nn];const r=Number.parseInt(n[1],16);return[r>>16&255,r>>8&255,r&255,255]}function Zo(t,e){const n=String(t??"").trim();if(!n)return[...e];const r=n.match(/^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/);if(r){const i=r[1].length===3?r[1].split("").map(s=>s+s).join(""):r[1],o=Number.parseInt(i,16);return[o>>16&255,o>>8&255,o&255,255]}return[...e]}function qo(t){const e=String(t?.classId??"").trim();return e||String(t?.className??"").trim()}function Ho(t){const e=[[...Nn]],n=new Map;for(const i of t??[]){const o=qo(i);!o||n.has(o)||(n.set(o,e.length),e.push(pi(i?.classColor)))}const r=new Uint8Array(e.length*4);for(let i=0;i<e.length;i+=1)r[i*4]=e[i][0],r[i*4+1]=e[i][1],r[i*4+2]=e[i][2],r[i*4+3]=e[i][3];return{colors:r,classToPaletteIndex:n}}const $o=[6,4,2],Ko=64,jo=.04,Qo=1,Jo=4,$t=1e-6,es=.1;function ts(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 fr(t,e,n){if(e<=$t||n<8)return[];const r=[];for(let i=0;i<=n;i+=1){const o=i/n*Math.PI*2;r.push([t[0]+Math.cos(o)*e,t[1]+Math.sin(o)*e])}return Ye(r)}function ns(t,e,n,r){const i=e[0]-t[0],o=e[1]-t[1],s=Math.sqrt(i*i+o*o);if(!Number.isFinite(s)||s<=r)return[];const a=i/s,c=-(o/s),f=a,u=Math.max($t,n);return Ye([[t[0]+c*u,t[1]+f*u],[e[0]+c*u,e[1]+f*u],[e[0]-c*u,e[1]-f*u],[t[0]-c*u,t[1]-f*u]])}function hr(t,e){if(!t.length)return[];let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[a,l]of t)a<n&&(n=a),a>i&&(i=a),l<r&&(r=l),l>o&&(o=l);if(!Number.isFinite(n)||!Number.isFinite(r))return[];const s=Math.max(e,1);return Ye([[n-s,r-s],[i+s,r-s],[i+s,o+s],[n-s,o+s]])}function It(t,e){return Ye(e?t.map(([n,r])=>[_(n,e[0],e[2]),_(r,e[1],e[3])]):t)}function dr(t,e){return Number.isFinite(t)?Number(t.toFixed(e)):t}function rs(t,e){if(!Array.isArray(t)||t.length===0)return[];const n=[];for(const r of t){if(!Array.isArray(r)||r.length<2)continue;const i=dr(Number(r[0]),e),o=dr(Number(r[1]),e);if(!Number.isFinite(i)||!Number.isFinite(o))continue;const s=n[n.length-1];(!s||s[0]!==i||s[1]!==o)&&n.push([i,o])}if(n.length>=2){const r=n[0],i=n[n.length-1];if(!r||!i)return[];(r[0]!==i[0]||r[1]!==i[1])&&n.push([r[0],r[1]])}return n.length>=4?n:[]}function is(t,e){if(!Array.isArray(t)||t.length===0)return[];const n=t.map(r=>rs(r,e)).filter(r=>r.length>=4);return n.length>0?n:[]}function os(t,e){const n=t.map(i=>is(i,e)).filter(i=>i.length>0);if(n.length===0)return null;let r=[n[0]];try{for(let i=1;i<n.length;i+=1)if(r=Yo.union(r,[n[i]]),!Array.isArray(r)||r.length===0)return null}catch(i){return console.error("buildBrushStrokePolygon union failed",e,i),null}return r.length>0?r:null}function ss(t){if(t.length===0)return null;for(const e of $o){const n=os(t,e);if(n)return n}return null}function as(t){if(!Array.isArray(t)||t.length===0)return[];const e=[];for(const n of t){if(!Array.isArray(n)||n.length<2)continue;const r=Number(n[0]),i=Number(n[1]);!Number.isFinite(r)||!Number.isFinite(i)||e.push([r,i])}return Ye(e)}function ls(t){let e=[],n=0;for(const r of t){if(!Array.isArray(r)||r.length===0)continue;const i=as(r[0]??[]);if(i.length<4)continue;const o=Math.abs(St(i));o<=n||(n=o,e=i)}return e}function cs(t,e=1e-9){const n=Ye(t);if(n.length<5)return n;const r=[n[0]];for(let i=1;i<n.length-1;i+=1){const o=r[r.length-1],s=n[i],a=n[i+1],l=(s[0]-o[0])*(a[1]-s[1])-(s[1]-o[1])*(a[0]-s[0]);Math.abs(l)<=e||r.push(s)}return r.push(r[0]),Ye(r)}function us(t,e,n){const r=n[0]-e[0],i=n[1]-e[1],o=r*r+i*i;if(o<=1e-12){const u=t[0]-e[0],h=t[1]-e[1];return u*u+h*h}const s=_(((t[0]-e[0])*r+(t[1]-e[1])*i)/o,0,1),a=e[0]+r*s,l=e[1]+i*s,c=t[0]-a,f=t[1]-l;return c*c+f*f}function fs(t,e){if(t.length<=2||e<=0)return t.slice();const n=new Uint8Array(t.length);n[0]=1,n[t.length-1]=1;const r=e*e,i=[[0,t.length-1]];for(;i.length>0;){const s=i.pop();if(!s)break;const[a,l]=s;if(l-a<=1)continue;let c=0,f=-1;for(let u=a+1;u<l;u+=1){const h=us(t[u],t[a],t[l]);h>c&&(c=h,f=u)}f>=0&&c>r&&(n[f]=1,i.push([a,f],[f,l]))}const o=[];for(let s=0;s<t.length;s+=1)n[s]&&o.push(t[s]);return o}function hs(t,e){const n=Ye(t);if(n.length<5||e<=0)return n;const r=n.slice(0,-1),i=fs(r,e);return i.length<3?n:Ye(i)}function ds(t,e){let n=Ye(t);if(e<=0||n.length<5)return n;for(let r=0;r<e;r+=1){const i=n.slice(0,-1);if(i.length<3)break;const o=[];for(let s=0;s<i.length;s+=1){const a=i[s],l=i[(s+1)%i.length];o.push([a[0]*.75+l[0]*.25,a[1]*.75+l[1]*.25],[a[0]*.25+l[0]*.75,a[1]*.25+l[1]*.75])}n=Ye(o)}return n}function ms(t,e){const n=ts(t),r=Math.max($t,Number(e.radius)||0);if(n.length===0||!Number.isFinite(r))return[];const i=Math.max(12,Math.floor(e.circleSides||Ko));if(n.length===1)return It(fr(n[0],r,i),e.clipBounds);const o=[],s=Math.max($t,r*es);for(let h=0;h<n.length;h+=1){const d=n[h],m=fr(d,r,i);if(m.length>=4&&o.push([m]),h===0)continue;const p=ns(n[h-1],d,r,s);p.length>=4&&o.push([p])}const a=ss(o),l=a?ls(a):[];if(!l.length)return It(hr(n,r),e.clipBounds);const c=typeof e.simplifyTolerance=="number"&&Number.isFinite(e.simplifyTolerance)?Math.max(0,e.simplifyTolerance):Math.max(.25,r*jo),f=typeof e.smoothingPasses=="number"&&Number.isFinite(e.smoothingPasses)?Math.round(_(e.smoothingPasses,0,Jo)):Qo,u=hs(ds(cs(l,1e-9),f),c);return u.length<4?It(hr(n,r),e.clipBounds):It(u,e.clipBounds)}function mr(){if(typeof window>"u")return 1;const t=window.devicePixelRatio||1;return Number.isFinite(t)&&t>0?t:1}function rn(t){if(typeof window>"u")return()=>{};let e=!0,n=mr(),r=null,i=null;const o=()=>{i?.(),i=null,r=null},s=()=>{o(),r=window.matchMedia(`(resolution: ${n}dppx)`);const f=()=>{a("match-media")};if(typeof r.addEventListener=="function"){r.addEventListener("change",f),i=()=>r?.removeEventListener("change",f);return}r.addListener(f),i=()=>r?.removeListener(f)},a=f=>{if(!e)return;const u=mr();if(Math.abs(u-n)<=1e-4)return;const h=n;n=u,s(),t({previousDpr:h,nextDpr:u,trigger:f})},l=()=>a("window-resize"),c=()=>a("visual-viewport-resize");return s(),window.addEventListener("resize",l),window.visualViewport?.addEventListener("resize",c),()=>{e=!1,o(),window.removeEventListener("resize",l),window.visualViewport?.removeEventListener("resize",c)}}const it=[],gr=[],$e={color:"#ff4d4f",width:2,lineDash:it,lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},yi={color:"#4cc9f0",width:2,lineDash:[10,8],lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},bi="rgba(23, 23, 25, 0.1)",xi=6,Ve={fontFamily:"Pretendard, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:11,fontWeight:600,textColor:"#171719",backgroundColor:"#FFCC00",borderColor:"rgba(0, 0, 0, 0)",borderWidth:0,paddingX:8,paddingY:4,offsetY:10,borderRadius:4},Je={fontFamily:"Pretendard, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:13,fontWeight:500,textColor:"#FFFFFF",backgroundColor:"rgba(23, 23, 25, 0.5)",borderRadius:4,paddingX:6,paddingY:3},pr={x:16,y:-24},gs=20,yr=1e-6,br="transparent",ps=3,ys=2,wi=96,bs=1,xr=1e3,Si=2,Ei=2,xs=4096,ws=.2,Ss=1.12,Es=.89,Rs=32,Ms="#000000",As=.1,Cs="#FFCF00",Ps="#FF0000",vs=1.5,wr=[2,2],Ts=1,Is=.25,_s=4,Fs=1,Ls=0,Ds=4,Ns=1.5;function Kt(t,e,n){return[_(t[0],0,e),_(t[1],0,n)]}function Bn(t){if(!Array.isArray(t)||t.length<2)return null;const e=Number(t[0]),n=Number(t[1]);return!Number.isFinite(e)||!Number.isFinite(n)?null:[e,n]}const qe=Bn;function Oe(t){return Ye(t)}function Xt(t){return Math.abs(St(Oe(t)))}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 Rt(t,e,n=!1){if(e.length!==0){t.moveTo(e[0][0],e[0][1]);for(let r=1;r<e.length;r+=1)t.lineTo(e[r][0],e[r][1]);n&&t.closePath()}}function ke(t,e,n,r=!1,i=!1,o="rgba(255, 77, 79, 0.16)"){e.length!==0&&(t.beginPath(),Rt(t,e,r),i&&r&&(t.fillStyle=o,t.fill()),t.strokeStyle=n.color,t.lineWidth=n.width,t.lineJoin=n.lineJoin,t.lineCap=n.lineCap,t.shadowColor=n.shadowColor,t.shadowBlur=n.shadowBlur,t.shadowOffsetX=n.shadowOffsetX,t.shadowOffsetY=n.shadowOffsetY,t.setLineDash(n.lineDash),t.stroke(),t.setLineDash(it),t.shadowColor="rgba(0, 0, 0, 0)",t.shadowBlur=0,t.shadowOffsetX=0,t.shadowOffsetY=0)}function kn(t){const e=Array.isArray(t?.lineDash)?t.lineDash.filter(s=>Number.isFinite(s)&&s>=0):it,n=typeof t?.width=="number"&&Number.isFinite(t.width)?Math.max(0,t.width):$e.width,r=typeof t?.shadowBlur=="number"&&Number.isFinite(t.shadowBlur)?Math.max(0,t.shadowBlur):$e.shadowBlur,i=typeof t?.shadowOffsetX=="number"&&Number.isFinite(t.shadowOffsetX)?t.shadowOffsetX:$e.shadowOffsetX,o=typeof t?.shadowOffsetY=="number"&&Number.isFinite(t.shadowOffsetY)?t.shadowOffsetY:$e.shadowOffsetY;return{color:t?.color||$e.color,width:n,lineDash:e.length?e:it,lineJoin:t?.lineJoin||$e.lineJoin,lineCap:t?.lineCap||$e.lineCap,shadowColor:t?.shadowColor||$e.shadowColor,shadowBlur:r,shadowOffsetX:i,shadowOffsetY:o}}function Ke(t,e){return e?kn({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 jt(t,e){return t==null||e===null||e===void 0?!1:String(t)===String(e)}function Er(t){return typeof t=="number"&&Number.isFinite(t)}function zs(t){return Array.isArray(t)&&t.length>=2&&Er(t[0])&&Er(t[1])}function Bs(t){return Array.isArray(t)&&t.length>=2&&t.every(e=>zs(e))}function Ri(t,e){if(!(!Array.isArray(t)||t.length===0)){if(Bs(t)){e.push(t.map(([n,r])=>[n,r]));return}for(const n of t)Ri(n,e)}}function Rr(t,e){const n=[];Ri(t,n);const r=[];for(const i of n){if(i.length<2)continue;const o=e?Oe(i):i;o.length>=(e?4:2)&&r.push(o)}return r}function bt(t,e){return typeof t!="number"||!Number.isFinite(t)||t<=0?e:t}function ks(t,e){return typeof t!="number"||!Number.isFinite(t)?e:_(t,0,1)}function Mi(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 Us(t){const e=t[0];return Array.isArray(e)&&Array.isArray(e[0])}function Qt(t,e,n){if(!t||!e)return[];if(n){const r=n.worldToScreen(t[0],t[1]),i=n.worldToScreen(e[0],e[1]);if(r&&i){const o=[[r[0],r[1]],[i[0],r[1]],[i[0],i[1]],[r[0],i[1]]],s=[];for(const a of o){const l=n.screenToWorld(a);if(!l)return Qt(t,e);s.push(l)}return Oe(s)}}return Oe([[t[0],t[1]],[e[0],t[1]],[e[0],e[1]],[t[0],e[1]]])}function Mn(t,e,n=wi){if(!t||!e)return[];const r=(t[0]+e[0])*.5,i=(t[1]+e[1])*.5,o=Math.hypot(e[0]-t[0],e[1]-t[1])*.5;if(o<1)return[];const s=[];for(let a=0;a<=n;a+=1){const l=a/n*Math.PI*2;s.push([r+Math.cos(l)*o,i+Math.sin(l)*o])}return Oe(s)}function Jt(t){const e=mi(dt(t));if(e.length===0)return[];const n=[];for(const r of e){const i=r[0];if(!i||i.length<4)continue;const o=i.map(([a,l])=>[a,l]),s=[];for(let a=1;a<r.length;a+=1){const l=r[a];!l||l.length<4||s.push(l.map(([c,f])=>[c,f]))}n.push({outer:o,holes:s})}return n}function Os(t){if(!Array.isArray(t))return wr;const e=t.filter(n=>Number.isFinite(n)&&n>=0);return e.length>0?e:wr}function Ws(t){return typeof t!="number"||!Number.isFinite(t)?Ts:_(t,Is,_s)}function Ys(t){return typeof t!="number"||!Number.isFinite(t)?Fs:Math.round(_(t,Ls,Ds))}function Xs(t){const e=bt(t?.radius,Rs),n=bt(t?.cursorLineWidth,vs),r=Ws(t?.edgeDetail),i=Ys(t?.edgeSmoothing);return{radius:e,edgeDetail:r,edgeSmoothing:i,clickSelectRoi:t?.clickSelectRoi===!0,fillColor:t?.fillColor||Ms,fillOpacity:ks(t?.fillOpacity,As),cursorColor:t?.cursorColor||Cs,cursorActiveColor:t?.cursorActiveColor||Ps,cursorLineWidth:n,cursorLineDash:Os(t?.cursorLineDash)}}function Vs(t,e,n){if(!e.isDrawing||e.screenPoints.length===0)return;const r=e.screenPoints;if(r.length===0)return;const i=n.radius;if(!(!Number.isFinite(i)||i<=0)){if(t.save(),t.globalAlpha=n.fillOpacity,t.fillStyle=n.fillColor,t.strokeStyle=n.fillColor,t.lineCap="round",t.lineJoin="round",t.lineWidth=i*2,r.length===1)t.beginPath(),t.arc(r[0][0],r[0][1],i,0,Math.PI*2),t.fill();else{t.beginPath(),t.moveTo(r[0][0],r[0][1]);for(let o=1;o<r.length;o+=1)t.lineTo(r[o][0],r[o][1]);t.stroke()}t.restore()}}function Gs(t,e,n,r){const i=e.cursor;if(!i)return;const o=e.cursorScreen??qe(n?.worldToScreen(i[0],i[1])??[]);if(!o)return;const s=r.radius;!Number.isFinite(s)||s<=0||(t.save(),t.beginPath(),t.arc(o[0],o[1],s,0,Math.PI*2),t.strokeStyle=e.isDrawing?r.cursorActiveColor:r.cursorColor,t.lineWidth=r.cursorLineWidth,t.setLineDash(r.cursorLineDash),t.stroke(),t.setLineDash(it),t.restore())}const Zs=.58,qs=4096,Hs=.5;let _t=null;const Ft=new Map;function $s(){if(_t)return _t;if(typeof document>"u")return null;const e=document.createElement("canvas").getContext("2d");return e?(_t=e,_t):null}function Un(t,e){const n=`${e.fontWeight}|${e.fontSize}|${e.fontFamily}|${t}`,r=Ft.get(n);if(r!==void 0)return r;const i=t.length*e.fontSize*Zs,o=$s();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 Ft.size>qs&&Ft.clear(),Ft.set(n,s),s}function Ks(t,e="top-center"){if(!t.length)return null;let n=1/0;for(const o of t)o[1]<n&&(n=o[1]);if(!Number.isFinite(n))return null;let r=1/0,i=-1/0;for(const o of t)Math.abs(o[1]-n)>Hs||(o[0]<r&&(r=o[0]),o[0]>i&&(i=o[0]));return!Number.isFinite(r)||!Number.isFinite(i)?null:e==="top-center"?[(r+i)*.5,n]:[r,n]}function On(t,e,n="top-center"){let r=null;for(const i of t){const o=e(i.outer);if(o.length===0)continue;const s=Ks(o,n);s&&(!r||s[1]<r[1]||s[1]===r[1]&&s[0]<r[0])&&(r=s)}return r}function Wn(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 Yn(t,e){return e?Wn({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 Xn(t,e,n,r){if(!t||!n)return 0;const i=Number(n.minZoom),o=Number(n.maxZoom);if(!Number.isFinite(i)||!Number.isFinite(o)||o-i<=yr||!Number.isFinite(e))return 0;let s=o;r!=null&&Number.isFinite(r)&&(s=_(r,i,o));const a=Math.max(yr,Math.abs(s)*1e-9);return e>=s-a?gs:0}function js(t){const e=typeof t?.fontSize=="number"&&Number.isFinite(t.fontSize)?Math.max(8,t.fontSize):Je.fontSize,n=typeof t?.borderRadius=="number"&&Number.isFinite(t.borderRadius)?Math.max(0,t.borderRadius):Je.borderRadius,r=typeof t?.paddingX=="number"&&Number.isFinite(t.paddingX)?Math.max(0,t.paddingX):Je.paddingX,i=typeof t?.paddingY=="number"&&Number.isFinite(t.paddingY)?Math.max(0,t.paddingY):Je.paddingY;return{fontFamily:t?.fontFamily||Je.fontFamily,fontSize:e,fontWeight:t?.fontWeight||Je.fontWeight,textColor:t?.textColor||Je.textColor,backgroundColor:t?.backgroundColor||Je.backgroundColor,borderRadius:n,paddingX:r,paddingY:i}}function Qs(t){const e=typeof t?.x=="number"&&Number.isFinite(t.x)?t.x:pr.x,n=typeof t?.y=="number"&&Number.isFinite(t.y)?t.y:pr.y;return{x:e,y:n}}function Js(t){return Number.isFinite(t)?`${Math.max(0,t).toFixed(3)} mm²`:"0.000 mm²"}function ea(t){const e=typeof t?.format=="function"?t.format:Js,n=Qs(t?.cursorOffset);return{enabled:t?.enabled===!0,format:e,style:js(t?.style),cursorOffsetX:n.x,cursorOffsetY:n.y}}function Ai(t,e,n,r,i,o,s=!0){const a=e.trim();if(!a)return;t.save(),t.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,t.textAlign="center",t.textBaseline="middle";const c=Un(a,o)+o.paddingX*2,f=o.fontSize+o.paddingY*2,u=n[0],h=n[1]-o.offsetY,d=s?_(u,c*.5+1,r-c*.5-1):u,m=s?_(h,f*.5+1,i-f*.5-1):h,p=d-c*.5,b=m-f*.5;t.fillStyle=o.backgroundColor,t.strokeStyle=o.borderColor,t.lineWidth=o.borderWidth,Mi(t,p,b,c,f,o.borderRadius),t.fill(),o.borderWidth>0&&t.stroke(),t.fillStyle=o.textColor,t.fillText(a,d,m+.5),t.restore()}function ta(t,e,n,r,i,o,s,a){const l=e.trim();if(!l)return;t.save(),t.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,t.textAlign="center",t.textBaseline="middle";const f=Un(l,o)+o.paddingX*2,u=o.fontSize+o.paddingY*2,h=_(n[0]+s,f*.5+1,r-f*.5-1),d=_(n[1]+a,u*.5+1,i-u*.5-1),m=h-f*.5,p=d-u*.5;t.fillStyle=o.backgroundColor,Mi(t,m,p,f,u,o.borderRadius),t.fill(),t.fillStyle=o.textColor,t.fillText(l,h,d+.5),t.restore()}function na(t,e,n,r){if(!(e.length<4||n.length===0)){t.save(),t.beginPath(),Rt(t,e,!0);for(const i of n)i.length<4||Rt(t,i,!0);t.fillStyle=r,t.fill("evenodd"),t.restore()}}function Ci(t){const{ctx:e,overlayShapes:n,imageOuterRing:r,worldToScreenPoints:i,baseStrokeStyle:o,onInvertedFillDebug:s}=t,a=!!globalThis.__OPEN_PLANT_DEBUG_OVERLAY__;for(let l=0;l<n.length;l+=1){const c=n[l];if(!c?.coordinates?.length||c.visible===!1)continue;const f=c.closed??Us(c.coordinates),u=Rr(c.coordinates,f);if(c.invertedFill?.fillColor){const d=[],m=Rr(c.coordinates,!0);for(const p of m){const b=i(p);b.length>=4&&d.push(b)}a&&s&&s({id:c.id??l,outerRingPoints:r.length,sourceRingCount:m.length,holeRingCount:d.length,fillColor:c.invertedFill.fillColor}),na(e,r,d,c.invertedFill.fillColor)}if(u.length===0)continue;const h=Ke(o,c.stroke??c.strokeStyle);for(const d of u){const m=i(d);m.length<2||ke(e,m,h,f,c.fill??!1)}}}function Lt(t){return typeof t=="string"&&(t==="stamp-rectangle"||t==="stamp-circle"||t==="stamp-rectangle-4096px"||t==="stamp-rectangle-2mm2"||t==="stamp-circle-2mm2"||t==="stamp-circle-hpf-0.2mm2")}function ra(t){return{rectangleAreaMm2:bt(t?.rectangleAreaMm2,Si),circleAreaMm2:bt(t?.circleAreaMm2,Ei),rectanglePixelSize:bt(t?.rectanglePixelSize,xs)}}const Mr=1e3;function ia(t){return t*Mr*Mr}function Ar(t,e,n){if(!t||!Number.isFinite(e)||e<=0)return[];if(n){const r=n.worldToScreen(t[0],t[1]),i=n.worldToScreen(t[0]+e,t[1]);if(r&&i){const o=Math.hypot(i[0]-r[0],i[1]-r[1]),s=[[r[0]-o,r[1]-o],[r[0]+o,r[1]-o],[r[0]+o,r[1]+o],[r[0]-o,r[1]+o]],a=[];for(const l of s){const c=n.screenToWorld(l);if(!c)throw new Error("Failed to create rectangle");a.push(c)}return Oe(a)}}return Oe([[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 oa(t,e,n=wi){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 Oe(r)}function sa(t){const{stampTool:e,center:n,resolvedStampOptions:r,imageWidth:i,imageHeight:o,micronsToWorldPixels:s,getRectangleProjection:a}=t;if(!n)return[];if(e==="stamp-rectangle-4096px"){const u=r.rectanglePixelSize*.5;return Ar(n,u,a()).map(h=>Kt(h,i,o))}let l=0;if(e==="stamp-rectangle"||e==="stamp-rectangle-2mm2"?l=e==="stamp-rectangle-2mm2"?Si:r.rectangleAreaMm2:(e==="stamp-circle"||e==="stamp-circle-2mm2"||e==="stamp-circle-hpf-0.2mm2")&&(l=e==="stamp-circle-hpf-0.2mm2"?ws:e==="stamp-circle-2mm2"?Ei:r.circleAreaMm2),!Number.isFinite(l)||l<=0)return[];const c=ia(l);let f=[];if(e==="stamp-rectangle"||e==="stamp-rectangle-2mm2"){const u=s(Math.sqrt(c)*.5);f=Ar(n,u,a())}else if(e==="stamp-circle"||e==="stamp-circle-2mm2"||e==="stamp-circle-hpf-0.2mm2"){const u=s(Math.sqrt(c/Math.PI));f=oa(n,u)}return f.length?f.map(u=>Kt(u,i,o)):[]}function aa(t){return{color:bi,width:xi,lineDash:it,lineJoin:t.lineJoin,lineCap:t.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function la(t){if(typeof t!="string")return br;const e=t.trim();return e.length>0?e:br}function Cr(t){return Array.isArray(t)&&t.length>=4&&Xt(t)>bs}function Pi({tool:t,imageWidth:e,imageHeight:n,imageMpp:r,imageZoom:i,stampOptions:o,brushOptions:s,projectorRef:a,onBrushTap:l,onDrawComplete:c,onPatchComplete:f,enabled:u,viewStateSignal:h,persistedRegions:d,patchRegions:m,persistedPolygons:p,drawFillColor:b,regionStrokeStyle:y,regionStrokeHoverStyle:x,regionStrokeActiveStyle:M,patchStrokeStyle:S,resolveRegionStrokeStyle:C,resolveRegionLabelStyle:A,overlayShapes:k,hoveredRegionId:U=null,activeRegionId:Y=null,regionLabelStyle:P,drawAreaTooltip:T,autoLiftRegionLabelAtMaxZoom:L=!1,regionLabelAnchor:F="top-center",clampRegionLabelToViewport:W=!0,regionLabelAutoLiftOffsetPx:$,invalidateRef:z,className:ae,style:de}){const J=g.useRef(null),ve=g.useRef(!1),Ae=g.useRef(new Map),D=g.useRef(t),v=g.useRef({isDrawing:!1,pointerId:null,start:null,current:null,cursor:null,cursorScreen:null,points:[],screenPoints:[],stampCenter:null}),O=u??t!=="cursor",oe=g.useMemo(()=>d&&d.length>0?d:!p||p.length===0?gr:p.map((w,R)=>({id:R,coordinates:w})),[d,p]),q=g.useMemo(()=>m??gr,[m]),pe=g.useMemo(()=>{const w=[];for(let R=0;R<oe.length;R+=1){const I=oe[R],N=Jt(I.coordinates);N.length!==0&&w.push({region:I,regionIndex:R,regionKey:I.id??R,polygons:N})}return w},[oe]),le=g.useMemo(()=>{const w=[];for(let R=0;R<q.length;R+=1){const I=q[R],N=Jt(I.coordinates);N.length!==0&&w.push({region:I,regionIndex:R,regionKey:I.id??R,polygons:N})}return w},[q]),ne=g.useMemo(()=>kn(y),[y]),Fe=g.useMemo(()=>Ke(ne,x),[ne,x]),ue=g.useMemo(()=>Ke(ne,M),[ne,M]),ye=g.useMemo(()=>Ke(yi,S),[S]),me=g.useMemo(()=>la(b),[b]),re=g.useMemo(()=>Wn(P),[P]),se=g.useMemo(()=>ea(T),[T]),ce=g.useMemo(()=>ra(o),[o]),Z=g.useMemo(()=>Xs(s),[s]),Pe=g.useMemo(()=>({position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",touchAction:"none",pointerEvents:O?"auto":"none",cursor:O?t==="brush"?"none":"crosshair":"default",...de}),[O,t,de]),Ee=g.useCallback(()=>{const w=J.current;if(!w)return;const R=w.getBoundingClientRect(),I=Math.max(1,window.devicePixelRatio||1),N=Math.max(1,Math.round(R.width*I)),G=Math.max(1,Math.round(R.height*I));(w.width!==N||w.height!==G)&&(w.width=N,w.height=G)},[O,t]),be=g.useCallback(w=>{const R=a.current;if(!R||w.length===0)return[];const I=new Array(w.length);for(let N=0;N<w.length;N+=1){const G=qe(R.worldToScreen(w[N][0],w[N][1]));if(!G)return[];I[N]=G}return I},[a]),V=g.useCallback(w=>{const R=a.current,I=J.current;if(!R||!I)return null;const N=I.getBoundingClientRect(),G=qe(R.screenToWorld(N.left+w[0],N.top+w[1]));return G?Kt(G,e,n):null},[a,e,n]),K=g.useCallback(()=>{const w=a.current,R=w?.getViewState?.().rotationDeg??0;if(!(Math.abs(R%360)<.01||!w))return{worldToScreen:(I,N)=>qe(w.worldToScreen(I,N)),screenToWorld:V}},[a,V]),fe=g.useCallback(w=>{if(!Number.isFinite(w)||w<=0)return 0;const R=typeof r=="number"&&Number.isFinite(r)&&r>0?r:1,I=typeof i=="number"&&Number.isFinite(i)?i:0,N=a.current?.getViewState?.().zoom,G=typeof N=="number"&&Number.isFinite(N)&&N>0?N:1,ge=I+Math.log2(G),ie=Math.max(1e-9,zn(R,I,ge));return w/ie/G},[r,i,a]),te=g.useCallback((w,R)=>sa({stampTool:w,center:R,resolvedStampOptions:ce,imageWidth:e,imageHeight:n,micronsToWorldPixels:fe,getRectangleProjection:K}),[fe,e,n,ce,K]),j=g.useCallback(()=>{const w=v.current;return Lt(t)?te(t,w.stampCenter):t==="brush"?[]:w.isDrawing?t==="freehand"?w.points:t==="rectangle"?Qt(w.start,w.current,K()):t==="circular"?Mn(w.start,w.current):[]:[]},[t,te,K]),Re=g.useCallback(()=>{Ee();const w=J.current;if(!w)return;const R=w.getContext("2d");if(!R)return;const I=Math.max(1,window.devicePixelRatio||1),N=w.width/I,G=w.height/I;if(R.setTransform(1,0,0,1,0,0),R.clearRect(0,0,w.width,w.height),R.setTransform(I,0,0,I,0,0),pe.length>0)for(const ie of pe){const{region:he,polygons:Ce,regionIndex:Ie,regionKey:ze}=ie,at=jt(Y,ze)?"active":jt(U,ze)?"hover":"default";let Qe=at==="active"?ue:at==="hover"?Fe:ne;if(C){const Tt=C({region:he,regionId:ze,regionIndex:Ie,state:at});Qe=Ke(Qe,Tt||void 0)}const vt=at==="default"?null:aa(Qe);for(const Tt of Ce){const sn=be(Tt.outer);sn.length>=4&&(vt&&ke(R,sn,vt,!0,!1),ke(R,sn,Qe,!0,!1));for(const lo of Tt.holes){const an=be(lo);an.length>=4&&(vt&&ke(R,an,vt,!0,!1),ke(R,an,Qe,!0,!1))}}}if(le.length>0)for(const ie of le)for(const he of ie.polygons){const Ce=be(he.outer);Ce.length>=4&&ke(R,Ce,ye,!0,!1);for(const Ie of he.holes){const ze=be(Ie);ze.length>=4&&ke(R,ze,ye,!0,!1)}}if(Array.isArray(k)&&k.length>0){const ie=be(Oe([[0,0],[e,0],[e,n],[0,n]]));Ci({ctx:R,overlayShapes:k,imageOuterRing:ie,worldToScreenPoints:be,baseStrokeStyle:ne,onInvertedFillDebug:globalThis.__OPEN_PLANT_DEBUG_OVERLAY__?he=>{const Ce=String(he.id),Ie=`${he.outerRingPoints}|${he.sourceRingCount}|${he.holeRingCount}|${he.fillColor}`;Ae.current.get(Ce)!==Ie&&(Ae.current.set(Ce,Ie),console.debug("[open-plant] invertedFill",he))}:void 0})}const ge=j();if(O){if(t==="brush")Vs(R,v.current,Z),Gs(R,v.current,a.current,Z);else if(ge.length>0)if(t==="freehand"){const ie=be(ge);ie.length>=2&&ke(R,ie,ne,!1,!1),ie.length>=3&&ke(R,be(Oe(ge)),ne,!0,!0,me)}else{const ie=be(ge);ie.length>=4&&ke(R,ie,ne,!0,!0,me)}}if(pe.length>0){const ie=Math.max(1e-6,a.current?.getViewState?.().zoom??1),he=typeof $=="number"&&Number.isFinite($)?Math.max(0,$):Xn(L,ie,a.current?.getZoomRange?.(),a.current?.getRegionLabelAutoLiftCapZoom?.());for(const Ce of pe){if(!Ce.region.label)continue;const Ie=On(Ce.polygons,be,F);if(!Ie)continue;let ze=Yn(re,A?.({region:Ce.region,regionId:Ce.regionKey,regionIndex:Ce.regionIndex,zoom:ie}));he>0&&(ze={...ze,offsetY:ze.offsetY+he}),Ai(R,Ce.region.label,Ie,N,G,ze,W)}}if(se.enabled&&O&&(t==="freehand"||t==="rectangle"||t==="circular")){const ie=v.current;if(ie.isDrawing){const he=t==="freehand"?Oe(ge):ge;if(he.length>=4){const Ce=Xt(he),Ie=typeof r=="number"&&Number.isFinite(r)&&r>0?r:0,ze=Ie>0?Ce*Ie*Ie/(xr*xr):0,at=se.format(ze),Qe=ie.cursorScreen??(ie.current?qe(a.current?.worldToScreen(ie.current[0],ie.current[1])??[]):null);Qe&&ta(R,at,Qe,N,G,se.style,se.cursorOffsetX,se.cursorOffsetY)}}}},[O,t,j,Ee,be,e,n,a,pe,k,U,Y,ne,Fe,ue,me,le,ye,C,A,re,se,L,F,W,$,r,Z]),X=g.useCallback(()=>{ve.current||(ve.current=!0,requestAnimationFrame(()=>{ve.current=!1,Re()}))},[Re]),Te=g.useCallback((w=!1)=>{const R=v.current,I=J.current;I&&R.pointerId!==null&&I.hasPointerCapture(R.pointerId)&&I.releasePointerCapture(R.pointerId),R.isDrawing=!1,R.pointerId=null,R.start=null,R.current=null,R.points=[],R.screenPoints=[],R.stampCenter=null,w||(R.cursor=null,R.cursorScreen=null)},[]),De=g.useCallback(w=>{const R=a.current;if(!R||e<=0||n<=0)return null;const I=qe(R.screenToWorld(w.clientX,w.clientY));return I?Kt(I,e,n):null},[a,e,n]),B=g.useCallback(w=>{const R=J.current;if(!R)return null;const I=R.getBoundingClientRect(),N=_(w.clientX-I.left,0,I.width),G=_(w.clientY-I.top,0,I.height);return!Number.isFinite(N)||!Number.isFinite(G)?null:[N,G]},[]),H=g.useCallback(()=>{const w=v.current;if(!w.isDrawing){Te(!0),X();return}let R=[];if(t==="freehand")w.points.length>=ps&&(R=Oe(w.points));else if(t==="rectangle")R=Qt(w.start,w.current,K());else if(t==="circular")R=Mn(w.start,w.current);else if(t==="brush"){const I=w.points[w.points.length-1]??w.current??w.start;if(Z.clickSelectRoi&&I&&w.points.length<=1&&l?.(I)){Te(!0),X();return}const N=Math.max(.25,Z.edgeDetail),G=w.screenPoints.length>0?w.screenPoints:be(w.points),ge=Math.max(.5,Z.radius*.04/N),ie=ms(G,{radius:Z.radius,circleSides:Math.max(16,Math.round(32*N)),simplifyTolerance:ge,smoothingPasses:Z.edgeSmoothing}),he=[];for(const Ce of ie){const Ie=V(Ce);Ie&&he.push(Ie)}R=Oe(he)}(t==="freehand"||t==="rectangle"||t==="circular"||t==="brush")&&Cr(R)&&c&&c({tool:t,intent:t==="brush"?"brush":"roi",coordinates:R,bbox:Sr(R),areaPx:Xt(R)}),Te(!0),X()},[t,c,Te,X,be,V,K,Z.radius,Z.edgeDetail,Z.edgeSmoothing,Z.clickSelectRoi,l]),Q=g.useCallback((w,R)=>{const I=te(w,R);if(!Cr(I))return;const N=w==="stamp-rectangle-4096px"?"patch":"roi",G={tool:w,intent:N,coordinates:I,bbox:Sr(I),areaPx:Xt(I)};c?.(G),N==="patch"&&f&&f(G)},[te,c,f]),ee=g.useCallback((w,R,I)=>{const N=Math.max(Ns,Z.radius*.1),G=N*N,ge=w.screenPoints[w.screenPoints.length-1];if(!ge){w.points.push(R),w.screenPoints.push(I),w.current=R;return}const ie=I[0]-ge[0],he=I[1]-ge[1];ie*ie+he*he>=G?(w.points.push(R),w.screenPoints.push(I)):(w.points[w.points.length-1]=R,w.screenPoints[w.screenPoints.length-1]=I),w.current=R},[Z.radius]),Se=g.useCallback(w=>{if(!O||t==="cursor"||w.button!==0)return;const R=De(w);if(!R)return;const I=B(w);if(!I)return;if(w.preventDefault(),w.stopPropagation(),Lt(t)){const ge=v.current;ge.stampCenter=R,Q(t,R),X();return}const N=J.current;N&&N.setPointerCapture(w.pointerId);const G=v.current;G.isDrawing=!0,G.pointerId=w.pointerId,G.start=R,G.current=R,G.cursor=R,G.cursorScreen=I,G.points=t==="freehand"||t==="brush"?[R]:[],G.screenPoints=t==="brush"?[I]:[],X()},[O,t,De,B,Q,X]),xe=g.useCallback(w=>{if(!O||t==="cursor")return;const R=De(w);if(!R)return;const I=B(w);if(!I)return;const N=v.current;if(N.cursor=R,N.cursorScreen=I,Lt(t)){N.stampCenter=R,w.preventDefault(),w.stopPropagation(),X();return}if(t==="brush"){if(!N.isDrawing||N.pointerId!==w.pointerId){X();return}w.preventDefault(),w.stopPropagation(),ee(N,R,I),X();return}if(!(!N.isDrawing||N.pointerId!==w.pointerId)){if(w.preventDefault(),w.stopPropagation(),t==="freehand"){const G=a.current,ge=Math.max(1e-6,G?.getViewState?.().zoom??1),ie=ys/ge,he=ie*ie,Ce=N.points[N.points.length-1];if(!Ce)N.points.push(R);else{const Ie=R[0]-Ce[0],ze=R[1]-Ce[1];Ie*Ie+ze*ze>=he&&N.points.push(R)}}else N.current=R;X()}},[O,t,De,B,X,a,ee]),Me=g.useCallback(w=>{const R=v.current;if(!R.isDrawing||R.pointerId!==w.pointerId)return;w.preventDefault(),w.stopPropagation();const I=De(w),N=B(w);I&&(R.cursor=I,N&&(R.cursorScreen=N),t==="brush"?N&&ee(R,I,N):R.current=I);const G=J.current;G&&G.hasPointerCapture(w.pointerId)&&G.releasePointerCapture(w.pointerId),H()},[H,De,B,t,ee]),Ne=g.useCallback(()=>{const w=v.current;let R=!1;t==="brush"&&!w.isDrawing&&w.cursor&&(w.cursor=null,w.cursorScreen=null,R=!0),Lt(t)&&w.stampCenter&&(w.stampCenter=null,R=!0),R&&X()},[t,X]);return g.useEffect(()=>{Ee(),X();const w=J.current;if(!w)return;const R=new ResizeObserver(()=>{Ee(),X()});return R.observe(w),()=>{R.disconnect()}},[Ee,X]),g.useEffect(()=>rn(()=>{Ee(),X()}),[Ee,X]),g.useEffect(()=>{O||Te(),X()},[O,X,Te]),g.useEffect(()=>{D.current!==t&&(D.current=t,Te(),X())},[t,Te,X]),g.useEffect(()=>{X()},[h,oe,k,X]),g.useEffect(()=>{if(z)return z.current=X,()=>{z.current===X&&(z.current=null)}},[z,X]),g.useEffect(()=>{if(!O)return;const w=R=>{R.key==="Escape"&&(Te(),X())};return window.addEventListener("keydown",w),()=>{window.removeEventListener("keydown",w)}},[O,Te,X]),Ge.jsx("canvas",{ref:J,className:ae,style:Pe,onPointerDown:Se,onPointerMove:xe,onPointerUp:Me,onPointerCancel:Me,onPointerLeave:Ne,onContextMenu:w=>{O&&w.preventDefault()},onWheel:w=>{if(!O)return;const R=J.current,I=a.current,N=typeof I?.handleWheelZoom=="function",G=typeof I?.zoomBy=="function";if(!R||!N&&!G)return;w.preventDefault(),w.stopPropagation();const ge=R.getBoundingClientRect(),ie=w.clientX-ge.left,he=w.clientY-ge.top;N?I.handleWheelZoom?.(w.deltaY,ie,he):I.zoomBy?.(w.deltaY<0?Ss:Es,ie,he),X()}})}const vi=g.createContext(null),ca=vi.Provider;function st(){const t=g.useContext(vi);if(!t)throw new Error("useViewerContext must be used within a <WsiViewer>");return t}function ua({tool:t="cursor",stampOptions:e,brushOptions:n,fillColor:r,areaTooltip:i,onComplete:o,onPatchComplete:s,onBrushTap:a}){const{source:l,rendererRef:c,rendererSerial:f,setInteractionLock:u}=st(),h=t!=="cursor";g.useEffect(()=>(u("drawing-layer",h),()=>u("drawing-layer",!1)),[h,u]);const d=g.useMemo(()=>c.current?.getViewState(),[f]);return l?Ge.jsx(Pi,{tool:t,enabled:h,imageWidth:l.width,imageHeight:l.height,imageMpp:l.mpp,imageZoom:l.maxTierZoom,stampOptions:e,brushOptions:n,drawFillColor:r,projectorRef:c,onBrushTap:a,viewStateSignal:d,drawAreaTooltip:i,onDrawComplete:o,onPatchComplete:s}):null}function Pr(t,e,n,r){return[Math.min(t,n),Math.min(e,r),Math.max(t,n),Math.max(e,r)]}function vr(t,e){return!(t[2]<e[0]||t[0]>e[2]||t[3]<e[1]||t[1]>e[3])}class fa{constructor(e=16){E(this,"targetNodeSize");E(this,"items",[]);E(this,"globalBounds",[0,0,0,0]);E(this,"gridSize",1);E(this,"cellWidth",1);E(this,"cellHeight",1);E(this,"buckets",[]);E(this,"visited",new Uint32Array(0));E(this,"querySerial",1);const n=Number.isFinite(e)?Math.floor(e):16;this.targetNodeSize=Math.max(1,n)}load(e){if(!Array.isArray(e)||e.length===0){this.items=[],this.globalBounds=[0,0,0,0],this.gridSize=1,this.cellWidth=1,this.cellHeight=1,this.buckets=[],this.visited=new Uint32Array(0),this.querySerial=1;return}const n=[];let r=1/0,i=1/0,o=-1/0,s=-1/0;for(const f of e){if(!f||!Number.isFinite(f.minX)||!Number.isFinite(f.minY)||!Number.isFinite(f.maxX)||!Number.isFinite(f.maxY))continue;const u=Pr(f.minX,f.minY,f.maxX,f.maxY);r=Math.min(r,u[0]),i=Math.min(i,u[1]),o=Math.max(o,u[2]),s=Math.max(s,u[3]),n.push({minX:u[0],minY:u[1],maxX:u[2],maxY:u[3],value:f.value})}if(this.items=n,this.visited=new Uint32Array(n.length),this.querySerial=1,n.length===0||!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(o)||!Number.isFinite(s)){this.globalBounds=[0,0,0,0],this.gridSize=1,this.cellWidth=1,this.cellHeight=1,this.buckets=[];return}this.globalBounds=[r,i,o,s],this.gridSize=Math.max(1,Math.ceil(Math.sqrt(n.length/this.targetNodeSize)));const a=Math.max(0,o-r),l=Math.max(0,s-i);this.cellWidth=a>0?a/this.gridSize:1,this.cellHeight=l>0?l/this.gridSize:1;const c=this.gridSize*this.gridSize;this.buckets=Array.from({length:c},()=>[]);for(let f=0;f<n.length;f+=1){const u=n[f],h=this.toCellX(u.minX),d=this.toCellX(u.maxX),m=this.toCellY(u.minY),p=this.toCellY(u.maxY);for(let b=m;b<=p;b+=1)for(let y=h;y<=d;y+=1)this.buckets[b*this.gridSize+y].push(f)}}search(e){if(this.items.length===0)return[];if(!Array.isArray(e)||e.length<4)return[];const n=Pr(e[0],e[1],e[2],e[3]);if(!vr(n,this.globalBounds))return[];const r=this.toCellX(n[0]),i=this.toCellX(n[2]),o=this.toCellY(n[1]),s=this.toCellY(n[3]),a=this.nextSerial(),l=[];for(let c=o;c<=s;c+=1)for(let f=r;f<=i;f+=1){const u=this.buckets[c*this.gridSize+f];if(!(!u||u.length===0))for(const h of u){if(this.visited[h]===a)continue;this.visited[h]=a;const d=this.items[h];vr(n,[d.minX,d.minY,d.maxX,d.maxY])&&l.push(d)}}return l}nextSerial(){return this.querySerial+=1,this.querySerial===4294967295&&(this.visited.fill(0),this.querySerial=1),this.querySerial}toCellX(e){const n=this.globalBounds[0],r=this.globalBounds[2];if(this.gridSize<=1||r<=n)return 0;const i=(e-n)/this.cellWidth;return!Number.isFinite(i)||i<=0?0:i>=this.gridSize-1?this.gridSize-1:Math.max(0,Math.min(this.gridSize-1,Math.floor(i)))}toCellY(e){const n=this.globalBounds[1],r=this.globalBounds[3];if(this.gridSize<=1||r<=n)return 0;const i=(e-n)/this.cellHeight;return!Number.isFinite(i)||i<=0?0:i>=this.gridSize-1?this.gridSize-1:Math.max(0,Math.min(this.gridSize-1,Math.floor(i)))}}function Ti(t){return new fa(t)}const ha=`#version 300 es
|
|
32
|
+
`;class ui{constructor(e){E(this,"canvas");E(this,"gl");E(this,"camera",new ci);E(this,"imageWidth");E(this,"imageHeight");E(this,"clearColor");E(this,"program");E(this,"vao");E(this,"quadBuffer");E(this,"uCameraLocation");E(this,"uBoundsLocation");E(this,"uTextureLocation");E(this,"resizeObserver");E(this,"tiles",[]);E(this,"frameId",null);E(this,"loadVersion",0);E(this,"destroyed",!1);E(this,"fitted",!1);E(this,"controlledViewState",!1);this.canvas=e.canvas,this.imageWidth=Math.max(1,e.imageWidth),this.imageHeight=Math.max(1,e.imageHeight),this.clearColor=e.clearColor??[.03,.05,.08,1],this.gl=fo(this.canvas,{preserveDrawingBuffer:e.preserveDrawingBuffer}),this.program=xt(this.gl,ho,mo);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=Ie(this.gl,this.program,"uCamera"),this.uBoundsLocation=Ie(this.gl,this.program,"uBounds"),this.uTextureLocation=Ie(this.gl,this.program,"uTexture"),e.initialViewState&&(this.controlledViewState=!0,this.camera.setViewState(e.initialViewState)),this.resizeObserver=new ResizeObserver(()=>{this.resize()}),this.resizeObserver.observe(this.canvas),this.resize()}async setTiles(e){if(this.destroyed)return;const n=++this.loadVersion,r=await Promise.all(e.map(async i=>await this.loadTile(i,n)));if(this.destroyed||n!==this.loadVersion){for(const i of r)i&&this.gl.deleteTexture(i.texture);return}this.disposeTiles(this.tiles),this.tiles=r.filter(i=>i!==null),this.requestRender()}setViewState(e){this.controlledViewState=!0,this.camera.setViewState(e),this.requestRender()}getViewState(){return this.camera.getViewState()}destroy(){this.destroyed||(this.destroyed=!0,this.loadVersion+=1,this.frameId!==null&&(cancelAnimationFrame(this.frameId),this.frameId=null),this.resizeObserver.disconnect(),this.disposeTiles(this.tiles),this.tiles=[],this.gl.deleteBuffer(this.quadBuffer),this.gl.deleteVertexArray(this.vao),this.gl.deleteProgram(this.program))}async loadTile(e,n){try{const r=await fetch(e.url);if(!r.ok)throw new Error(`Tile fetch failed: ${r.status} ${r.statusText}`);const i=await r.blob(),o=await createImageBitmap(i);if(this.destroyed||n!==this.loadVersion)return o.close(),null;const s=this.gl.createTexture();if(!s)throw o.close(),new Error("Failed to create tile texture.");return this.gl.bindTexture(this.gl.TEXTURE_2D,s),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,1),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,o),this.gl.bindTexture(this.gl.TEXTURE_2D,null),o.close(),{id:e.id,bounds:e.bounds,texture:s}}catch(r){return console.error(`[M1TileRenderer] tile load failed: ${e.id}`,r),null}}resize(){if(this.destroyed)return;const e=this.canvas.getBoundingClientRect(),n=Math.max(1,e.width||this.canvas.clientWidth||1),r=Math.max(1,e.height||this.canvas.clientHeight||1),i=Math.max(1,window.devicePixelRatio||1),o=Math.max(1,Math.round(n*i)),s=Math.max(1,Math.round(r*i));(this.canvas.width!==o||this.canvas.height!==s)&&(this.canvas.width=o,this.canvas.height=s),this.camera.setViewport(n,r),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),!this.fitted&&!this.controlledViewState&&(this.fitToImage(),this.fitted=!0),this.requestRender()}fitToImage(){const e=this.camera.getViewportSize(),n=Math.min(e.width/this.imageWidth,e.height/this.imageHeight),r=Number.isFinite(n)&&n>0?n:1,i=e.width/r,o=e.height/r,s=(this.imageWidth-i)*.5,a=(this.imageHeight-o)*.5;this.camera.setViewState({zoom:r,offsetX:s,offsetY:a})}requestRender(){this.frameId!==null||this.destroyed||(this.frameId=requestAnimationFrame(()=>{this.frameId=null,this.render()}))}render(){if(!this.destroyed){this.gl.clearColor(this.clearColor[0],this.clearColor[1],this.clearColor[2],this.clearColor[3]),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.useProgram(this.program),this.gl.bindVertexArray(this.vao),this.gl.uniformMatrix3fv(this.uCameraLocation,!1,this.camera.getMatrix()),this.gl.uniform1i(this.uTextureLocation,0);for(const e of this.tiles)this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,e.texture),this.gl.uniform4f(this.uBoundsLocation,e.bounds[0],e.bounds[1],e.bounds[2],e.bounds[3]),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindVertexArray(null)}}disposeTiles(e){for(const n of e)this.gl.deleteTexture(n.texture)}}class rt{constructor(e,n){this.next=null,this.key=e,this.data=n,this.left=null,this.right=null}}function go(t,e){return t>e?1:t<e?-1:0}function et(t,e,n){const r=new rt(null,null);let i=r,o=r;for(;;){const s=n(t,e.key);if(s<0){if(e.left===null)break;if(n(t,e.left.key)<0){const a=e.left;if(e.left=a.right,a.right=e,e=a,e.left===null)break}o.left=e,o=e,e=e.left}else if(s>0){if(e.right===null)break;if(n(t,e.right.key)>0){const a=e.right;if(e.right=a.left,a.left=e,e=a,e.right===null)break}i.right=e,i=e,e=e.right}else break}return i.right=e.left,o.left=e.right,e.left=r.right,e.right=r.left,e}function cn(t,e,n,r){const i=new rt(t,e);if(n===null)return i.left=i.right=null,i;n=et(t,n,r);const o=r(t,n.key);return o<0?(i.left=n.left,i.right=n,n.left=null):o>=0&&(i.right=n.right,i.left=n,n.right=null),i}function Kn(t,e,n){let r=null,i=null;if(e){e=et(t,e,n);const o=n(e.key,t);o===0?(r=e.left,i=e.right):o<0?(i=e.right,e.right=null,r=e):(r=e.left,e.left=null,i=e)}return{left:r,right:i}}function po(t,e,n){return e===null?t:(t===null||(e=et(t.key,e,n),e.left=t),e)}function yn(t,e,n,r,i){if(t){r(`${e}${n?"└── ":"├── "}${i(t)}
|
|
33
|
+
`);const o=e+(n?" ":"│ ");t.left&&yn(t.left,o,!1,r,i),t.right&&yn(t.right,o,!0,r,i)}}class Dn{constructor(e=go){this._root=null,this._size=0,this._comparator=e}insert(e,n){return this._size++,this._root=cn(e,n,this._root,this._comparator)}add(e,n){const r=new rt(e,n);this._root===null&&(r.left=r.right=null,this._size++,this._root=r);const i=this._comparator,o=et(e,this._root,i),s=i(e,o.key);return s===0?this._root=o:(s<0?(r.left=o.left,r.right=o,o.left=null):s>0&&(r.right=o.right,r.left=o,o.right=null),this._size++,this._root=r),this._root}remove(e){this._root=this._remove(e,this._root,this._comparator)}_remove(e,n,r){let i;return n===null?null:(n=et(e,n,r),r(e,n.key)===0?(n.left===null?i=n.right:(i=et(e,n.left,r),i.right=n.right),this._size--,i):n)}pop(){let e=this._root;if(e){for(;e.left;)e=e.left;return this._root=et(e.key,this._root,this._comparator),this._root=this._remove(e.key,this._root,this._comparator),{key:e.key,data:e.data}}return null}findStatic(e){let n=this._root;const r=this._comparator;for(;n;){const i=r(e,n.key);if(i===0)return n;i<0?n=n.left:n=n.right}return null}find(e){return this._root&&(this._root=et(e,this._root,this._comparator),this._comparator(e,this._root.key)!==0)?null:this._root}contains(e){let n=this._root;const r=this._comparator;for(;n;){const i=r(e,n.key);if(i===0)return!0;i<0?n=n.left:n=n.right}return!1}forEach(e,n){let r=this._root;const i=[];let o=!1;for(;!o;)r!==null?(i.push(r),r=r.left):i.length!==0?(r=i.pop(),e.call(n,r),r=r.right):o=!0;return this}range(e,n,r,i){const o=[],s=this._comparator;let a=this._root,l;for(;o.length!==0||a;)if(a)o.push(a),a=a.left;else{if(a=o.pop(),l=s(a.key,n),l>0)break;if(s(a.key,e)>=0&&r.call(i,a))return this;a=a.right}return this}keys(){const e=[];return this.forEach(({key:n})=>{e.push(n)}),e}values(){const e=[];return this.forEach(({data:n})=>{e.push(n)}),e}min(){return this._root?this.minNode(this._root).key:null}max(){return this._root?this.maxNode(this._root).key:null}minNode(e=this._root){if(e)for(;e.left;)e=e.left;return e}maxNode(e=this._root){if(e)for(;e.right;)e=e.right;return e}at(e){let n=this._root,r=!1,i=0;const o=[];for(;!r;)if(n)o.push(n),n=n.left;else if(o.length>0){if(n=o.pop(),i===e)return n;i++,n=n.right}else r=!0;return null}next(e){let n=this._root,r=null;if(e.right){for(r=e.right;r.left;)r=r.left;return r}const i=this._comparator;for(;n;){const o=i(e.key,n.key);if(o===0)break;o<0?(r=n,n=n.left):n=n.right}return r}prev(e){let n=this._root,r=null;if(e.left!==null){for(r=e.left;r.right;)r=r.right;return r}const i=this._comparator;for(;n;){const o=i(e.key,n.key);if(o===0)break;o<0?n=n.left:(r=n,n=n.right)}return r}clear(){return this._root=null,this._size=0,this}toList(){return bo(this._root)}load(e,n=[],r=!1){let i=e.length;const o=this._comparator;if(r&&wn(e,n,0,i-1,o),this._root===null)this._root=bn(e,n,0,i),this._size=i;else{const s=xo(this.toList(),yo(e,n),o);i=this._size+i,this._root=xn({head:s},0,i)}return this}isEmpty(){return this._root===null}get size(){return this._size}get root(){return this._root}toString(e=n=>String(n.key)){const n=[];return yn(this._root,"",!0,r=>n.push(r),e),n.join("")}update(e,n,r){const i=this._comparator;let{left:o,right:s}=Kn(e,this._root,i);i(e,n)<0?s=cn(n,r,s,i):o=cn(n,r,o,i),this._root=po(o,s,i)}split(e){return Kn(e,this._root,this._comparator)}*[Symbol.iterator](){let e=this._root;const n=[];let r=!1;for(;!r;)e!==null?(n.push(e),e=e.left):n.length!==0?(e=n.pop(),yield e,e=e.right):r=!0}}function bn(t,e,n,r){const i=r-n;if(i>0){const o=n+Math.floor(i/2),s=t[o],a=e[o],l=new rt(s,a);return l.left=bn(t,e,n,o),l.right=bn(t,e,o+1,r),l}return null}function yo(t,e){const n=new rt(null,null);let r=n;for(let i=0;i<t.length;i++)r=r.next=new rt(t[i],e[i]);return r.next=null,n.next}function bo(t){let e=t;const n=[];let r=!1;const i=new rt(null,null);let o=i;for(;!r;)e?(n.push(e),e=e.left):n.length>0?(e=o=o.next=n.pop(),e=e.right):r=!0;return o.next=null,i.next}function xn(t,e,n){const r=n-e;if(r>0){const i=e+Math.floor(r/2),o=xn(t,e,i),s=t.head;return s.left=o,t.head=t.head.next,s.right=xn(t,i+1,n),s}return null}function xo(t,e,n){const r=new rt(null,null);let i=r,o=t,s=e;for(;o!==null&&s!==null;)n(o.key,s.key)<0?(i.next=o,o=o.next):(i.next=s,s=s.next),i=i.next;return o!==null?i.next=o:s!==null&&(i.next=s),r.next}function wn(t,e,n,r,i){if(n>=r)return;const o=t[n+r>>1];let s=n-1,a=r+1;for(;;){do s++;while(i(t[s],o)<0);do a--;while(i(t[a],o)>0);if(s>=a)break;let l=t[s];t[s]=t[a],t[a]=l,l=e[s],e[s]=e[a],e[a]=l}wn(t,e,n,a,i),wn(t,e,a+1,r,i)}const je=11102230246251565e-32,Be=134217729,wo=(3+8*je)*je;function un(t,e,n,r,i){let o,s,a,l,c=e[0],f=r[0],u=0,h=0;f>c==f>-c?(o=c,c=e[++u]):(o=f,f=r[++h]);let d=0;if(u<t&&h<n)for(f>c==f>-c?(s=c+o,a=o-(s-c),c=e[++u]):(s=f+o,a=o-(s-f),f=r[++h]),o=s,a!==0&&(i[d++]=a);u<t&&h<n;)f>c==f>-c?(s=o+c,l=s-o,a=o-(s-l)+(c-l),c=e[++u]):(s=o+f,l=s-o,a=o-(s-l)+(f-l),f=r[++h]),o=s,a!==0&&(i[d++]=a);for(;u<t;)s=o+c,l=s-o,a=o-(s-l)+(c-l),c=e[++u],o=s,a!==0&&(i[d++]=a);for(;h<n;)s=o+f,l=s-o,a=o-(s-l)+(f-l),f=r[++h],o=s,a!==0&&(i[d++]=a);return(o!==0||d===0)&&(i[d++]=o),d}function So(t,e){let n=e[0];for(let r=1;r<t;r++)n+=e[r];return n}function Ct(t){return new Float64Array(t)}const Eo=(3+16*je)*je,Ro=(2+12*je)*je,Mo=(9+64*je)*je*je,lt=Ct(4),jn=Ct(8),Qn=Ct(12),Jn=Ct(16),Ue=Ct(4);function Ao(t,e,n,r,i,o,s){let a,l,c,f,u,h,d,m,p,b,y,x,M,S,C,A,B,z;const Y=t-i,P=n-i,I=e-o,O=r-o;S=Y*O,h=Be*Y,d=h-(h-Y),m=Y-d,h=Be*O,p=h-(h-O),b=O-p,C=m*b-(S-d*p-m*p-d*b),A=I*P,h=Be*I,d=h-(h-I),m=I-d,h=Be*P,p=h-(h-P),b=P-p,B=m*b-(A-d*p-m*p-d*b),y=C-B,u=C-y,lt[0]=C-(y+u)+(u-B),x=S+y,u=x-S,M=S-(x-u)+(y-u),y=M-A,u=M-y,lt[1]=M-(y+u)+(u-A),z=x+y,u=z-x,lt[2]=x-(z-u)+(y-u),lt[3]=z;let v=So(4,lt),W=Ro*s;if(v>=W||-v>=W||(u=t-Y,a=t-(Y+u)+(u-i),u=n-P,c=n-(P+u)+(u-i),u=e-I,l=e-(I+u)+(u-o),u=r-O,f=r-(O+u)+(u-o),a===0&&l===0&&c===0&&f===0)||(W=Mo*s+wo*Math.abs(v),v+=Y*f+O*a-(I*c+P*l),v>=W||-v>=W))return v;S=a*O,h=Be*a,d=h-(h-a),m=a-d,h=Be*O,p=h-(h-O),b=O-p,C=m*b-(S-d*p-m*p-d*b),A=l*P,h=Be*l,d=h-(h-l),m=l-d,h=Be*P,p=h-(h-P),b=P-p,B=m*b-(A-d*p-m*p-d*b),y=C-B,u=C-y,Ue[0]=C-(y+u)+(u-B),x=S+y,u=x-S,M=S-(x-u)+(y-u),y=M-A,u=M-y,Ue[1]=M-(y+u)+(u-A),z=x+y,u=z-x,Ue[2]=x-(z-u)+(y-u),Ue[3]=z;const j=un(4,lt,4,Ue,jn);S=Y*f,h=Be*Y,d=h-(h-Y),m=Y-d,h=Be*f,p=h-(h-f),b=f-p,C=m*b-(S-d*p-m*p-d*b),A=I*c,h=Be*I,d=h-(h-I),m=I-d,h=Be*c,p=h-(h-c),b=c-p,B=m*b-(A-d*p-m*p-d*b),y=C-B,u=C-y,Ue[0]=C-(y+u)+(u-B),x=S+y,u=x-S,M=S-(x-u)+(y-u),y=M-A,u=M-y,Ue[1]=M-(y+u)+(u-A),z=x+y,u=z-x,Ue[2]=x-(z-u)+(y-u),Ue[3]=z;const L=un(j,jn,4,Ue,Qn);S=a*f,h=Be*a,d=h-(h-a),m=a-d,h=Be*f,p=h-(h-f),b=f-p,C=m*b-(S-d*p-m*p-d*b),A=l*c,h=Be*l,d=h-(h-l),m=l-d,h=Be*c,p=h-(h-c),b=c-p,B=m*b-(A-d*p-m*p-d*b),y=C-B,u=C-y,Ue[0]=C-(y+u)+(u-B),x=S+y,u=x-S,M=S-(x-u)+(y-u),y=M-A,u=M-y,Ue[1]=M-(y+u)+(u-A),z=x+y,u=z-x,Ue[2]=x-(z-u)+(y-u),Ue[3]=z;const ge=un(L,Qn,4,Ue,Jn);return Jn[ge-1]}function Co(t,e,n,r,i,o){const s=(e-o)*(n-i),a=(t-i)*(r-o),l=s-a,c=Math.abs(s+a);return Math.abs(l)>=Eo*c?l:-Ao(t,e,n,r,i,o,c)}const gt=(t,e)=>t.ll.x<=e.x&&e.x<=t.ur.x&&t.ll.y<=e.y&&e.y<=t.ur.y,Sn=(t,e)=>{if(e.ur.x<t.ll.x||t.ur.x<e.ll.x||e.ur.y<t.ll.y||t.ur.y<e.ll.y)return null;const n=t.ll.x<e.ll.x?e.ll.x:t.ll.x,r=t.ur.x<e.ur.x?t.ur.x:e.ur.x,i=t.ll.y<e.ll.y?e.ll.y:t.ll.y,o=t.ur.y<e.ur.y?t.ur.y:e.ur.y;return{ll:{x:n,y:i},ur:{x:r,y:o}}};let tt=Number.EPSILON;tt===void 0&&(tt=Math.pow(2,-52));const Po=tt*tt,er=(t,e)=>{if(-tt<t&&t<tt&&-tt<e&&e<tt)return 0;const n=t-e;return n*n<Po*t*e?0:t<e?-1:1};class vo{constructor(){this.reset()}reset(){this.xRounder=new tr,this.yRounder=new tr}round(e,n){return{x:this.xRounder.round(e),y:this.yRounder.round(n)}}}class tr{constructor(){this.tree=new Dn,this.round(0)}round(e){const n=this.tree.add(e),r=this.tree.prev(n);if(r!==null&&er(n.key,r.key)===0)return this.tree.remove(e),r.key;const i=this.tree.next(n);return i!==null&&er(n.key,i.key)===0?(this.tree.remove(e),i.key):e}}const wt=new vo,Wt=(t,e)=>t.x*e.y-t.y*e.x,fi=(t,e)=>t.x*e.x+t.y*e.y,nr=(t,e,n)=>{const r=Co(t.x,t.y,e.x,e.y,n.x,n.y);return r>0?-1:r<0?1:0},qt=t=>Math.sqrt(fi(t,t)),To=(t,e,n)=>{const r={x:e.x-t.x,y:e.y-t.y},i={x:n.x-t.x,y:n.y-t.y};return Wt(i,r)/qt(i)/qt(r)},Io=(t,e,n)=>{const r={x:e.x-t.x,y:e.y-t.y},i={x:n.x-t.x,y:n.y-t.y};return fi(i,r)/qt(i)/qt(r)},rr=(t,e,n)=>e.y===0?null:{x:t.x+e.x/e.y*(n-t.y),y:n},ir=(t,e,n)=>e.x===0?null:{x:n,y:t.y+e.y/e.x*(n-t.x)},_o=(t,e,n,r)=>{if(e.x===0)return ir(n,r,t.x);if(r.x===0)return ir(t,e,n.x);if(e.y===0)return rr(n,r,t.y);if(r.y===0)return rr(t,e,n.y);const i=Wt(e,r);if(i==0)return null;const o={x:n.x-t.x,y:n.y-t.y},s=Wt(o,e)/i,a=Wt(o,r)/i,l=t.x+a*e.x,c=n.x+s*r.x,f=t.y+a*e.y,u=n.y+s*r.y,h=(l+c)/2,d=(f+u)/2;return{x:h,y:d}};class Xe{static compare(e,n){const r=Xe.comparePoints(e.point,n.point);return r!==0?r:(e.point!==n.point&&e.link(n),e.isLeft!==n.isLeft?e.isLeft?1:-1:nt.compare(e.segment,n.segment))}static comparePoints(e,n){return e.x<n.x?-1:e.x>n.x?1:e.y<n.y?-1:e.y>n.y?1:0}constructor(e,n){e.events===void 0?e.events=[this]:e.events.push(this),this.point=e,this.isLeft=n}link(e){if(e.point===this.point)throw new Error("Tried to link already linked events");const n=e.point.events;for(let r=0,i=n.length;r<i;r++){const o=n[r];this.point.events.push(o),o.point=this.point}this.checkForConsuming()}checkForConsuming(){const e=this.point.events.length;for(let n=0;n<e;n++){const r=this.point.events[n];if(r.segment.consumedBy===void 0)for(let i=n+1;i<e;i++){const o=this.point.events[i];o.consumedBy===void 0&&r.otherSE.point.events===o.otherSE.point.events&&r.segment.consume(o.segment)}}}getAvailableLinkedEvents(){const e=[];for(let n=0,r=this.point.events.length;n<r;n++){const i=this.point.events[n];i!==this&&!i.segment.ringOut&&i.segment.isInResult()&&e.push(i)}return e}getLeftmostComparator(e){const n=new Map,r=i=>{const o=i.otherSE;n.set(i,{sine:To(this.point,e.point,o.point),cosine:Io(this.point,e.point,o.point)})};return(i,o)=>{n.has(i)||r(i),n.has(o)||r(o);const{sine:s,cosine:a}=n.get(i),{sine:l,cosine:c}=n.get(o);return s>=0&&l>=0?a<c?1:a>c?-1:0:s<0&&l<0?a<c?-1:a>c?1:0:l<s?-1:l>s?1:0}}}let Fo=0;class nt{static compare(e,n){const r=e.leftSE.point.x,i=n.leftSE.point.x,o=e.rightSE.point.x,s=n.rightSE.point.x;if(s<r)return 1;if(o<i)return-1;const a=e.leftSE.point.y,l=n.leftSE.point.y,c=e.rightSE.point.y,f=n.rightSE.point.y;if(r<i){if(l<a&&l<c)return 1;if(l>a&&l>c)return-1;const u=e.comparePoint(n.leftSE.point);if(u<0)return 1;if(u>0)return-1;const h=n.comparePoint(e.rightSE.point);return h!==0?h:-1}if(r>i){if(a<l&&a<f)return-1;if(a>l&&a>f)return 1;const u=n.comparePoint(e.leftSE.point);if(u!==0)return u;const h=e.comparePoint(n.rightSE.point);return h<0?1:h>0?-1:1}if(a<l)return-1;if(a>l)return 1;if(o<s){const u=n.comparePoint(e.rightSE.point);if(u!==0)return u}if(o>s){const u=e.comparePoint(n.rightSE.point);if(u<0)return 1;if(u>0)return-1}if(o!==s){const u=c-a,h=o-r,d=f-l,m=s-i;if(u>h&&d<m)return 1;if(u<h&&d>m)return-1}return o>s?1:o<s||c<f?-1:c>f?1:e.id<n.id?-1:e.id>n.id?1:0}constructor(e,n,r,i){this.id=++Fo,this.leftSE=e,e.segment=this,e.otherSE=n,this.rightSE=n,n.segment=this,n.otherSE=e,this.rings=r,this.windings=i}static fromRing(e,n,r){let i,o,s;const a=Xe.comparePoints(e,n);if(a<0)i=e,o=n,s=1;else if(a>0)i=n,o=e,s=-1;else throw new Error(`Tried to create degenerate segment at [${e.x}, ${e.y}]`);const l=new Xe(i,!0),c=new Xe(o,!1);return new nt(l,c,[r],[s])}replaceRightSE(e){this.rightSE=e,this.rightSE.segment=this,this.rightSE.otherSE=this.leftSE,this.leftSE.otherSE=this.rightSE}bbox(){const e=this.leftSE.point.y,n=this.rightSE.point.y;return{ll:{x:this.leftSE.point.x,y:e<n?e:n},ur:{x:this.rightSE.point.x,y:e>n?e:n}}}vector(){return{x:this.rightSE.point.x-this.leftSE.point.x,y:this.rightSE.point.y-this.leftSE.point.y}}isAnEndpoint(e){return e.x===this.leftSE.point.x&&e.y===this.leftSE.point.y||e.x===this.rightSE.point.x&&e.y===this.rightSE.point.y}comparePoint(e){if(this.isAnEndpoint(e))return 0;const n=this.leftSE.point,r=this.rightSE.point,i=this.vector();if(n.x===r.x)return e.x===n.x?0:e.x<n.x?1:-1;const o=(e.y-n.y)/i.y,s=n.x+o*i.x;if(e.x===s)return 0;const a=(e.x-n.x)/i.x,l=n.y+a*i.y;return e.y===l?0:e.y<l?-1:1}getIntersection(e){const n=this.bbox(),r=e.bbox(),i=Sn(n,r);if(i===null)return null;const o=this.leftSE.point,s=this.rightSE.point,a=e.leftSE.point,l=e.rightSE.point,c=gt(n,a)&&this.comparePoint(a)===0,f=gt(r,o)&&e.comparePoint(o)===0,u=gt(n,l)&&this.comparePoint(l)===0,h=gt(r,s)&&e.comparePoint(s)===0;if(f&&c)return h&&!u?s:!h&&u?l:null;if(f)return u&&o.x===l.x&&o.y===l.y?null:o;if(c)return h&&s.x===a.x&&s.y===a.y?null:a;if(h&&u)return null;if(h)return s;if(u)return l;const d=_o(o,this.vector(),a,e.vector());return d===null||!gt(i,d)?null:wt.round(d.x,d.y)}split(e){const n=[],r=e.events!==void 0,i=new Xe(e,!0),o=new Xe(e,!1),s=this.rightSE;this.replaceRightSE(o),n.push(o),n.push(i);const a=new nt(i,s,this.rings.slice(),this.windings.slice());return Xe.comparePoints(a.leftSE.point,a.rightSE.point)>0&&a.swapEvents(),Xe.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),r&&(i.checkForConsuming(),o.checkForConsuming()),n}swapEvents(){const e=this.rightSE;this.rightSE=this.leftSE,this.leftSE=e,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(let n=0,r=this.windings.length;n<r;n++)this.windings[n]*=-1}consume(e){let n=this,r=e;for(;n.consumedBy;)n=n.consumedBy;for(;r.consumedBy;)r=r.consumedBy;const i=nt.compare(n,r);if(i!==0){if(i>0){const o=n;n=r,r=o}if(n.prev===r){const o=n;n=r,r=o}for(let o=0,s=r.rings.length;o<s;o++){const a=r.rings[o],l=r.windings[o],c=n.rings.indexOf(a);c===-1?(n.rings.push(a),n.windings.push(l)):n.windings[c]+=l}r.rings=null,r.windings=null,r.consumedBy=n,r.leftSE.consumedBy=n.leftSE,r.rightSE.consumedBy=n.rightSE}}prevInResult(){return this._prevInResult!==void 0?this._prevInResult:(this.prev?this.prev.isInResult()?this._prevInResult=this.prev:this._prevInResult=this.prev.prevInResult():this._prevInResult=null,this._prevInResult)}beforeState(){if(this._beforeState!==void 0)return this._beforeState;if(!this.prev)this._beforeState={rings:[],windings:[],multiPolys:[]};else{const e=this.prev.consumedBy||this.prev;this._beforeState=e.afterState()}return this._beforeState}afterState(){if(this._afterState!==void 0)return this._afterState;const e=this.beforeState();this._afterState={rings:e.rings.slice(0),windings:e.windings.slice(0),multiPolys:[]};const n=this._afterState.rings,r=this._afterState.windings,i=this._afterState.multiPolys;for(let a=0,l=this.rings.length;a<l;a++){const c=this.rings[a],f=this.windings[a],u=n.indexOf(c);u===-1?(n.push(c),r.push(f)):r[u]+=f}const o=[],s=[];for(let a=0,l=n.length;a<l;a++){if(r[a]===0)continue;const c=n[a],f=c.poly;if(s.indexOf(f)===-1)if(c.isExterior)o.push(f);else{s.indexOf(f)===-1&&s.push(f);const u=o.indexOf(c.poly);u!==-1&&o.splice(u,1)}}for(let a=0,l=o.length;a<l;a++){const c=o[a].multiPoly;i.indexOf(c)===-1&&i.push(c)}return this._afterState}isInResult(){if(this.consumedBy)return!1;if(this._isInResult!==void 0)return this._isInResult;const e=this.beforeState().multiPolys,n=this.afterState().multiPolys;switch(Ze.type){case"union":{const r=e.length===0,i=n.length===0;this._isInResult=r!==i;break}case"intersection":{let r,i;e.length<n.length?(r=e.length,i=n.length):(r=n.length,i=e.length),this._isInResult=i===Ze.numMultiPolys&&r<i;break}case"xor":{const r=Math.abs(e.length-n.length);this._isInResult=r%2===1;break}case"difference":{const r=i=>i.length===1&&i[0].isSubject;this._isInResult=r(e)!==r(n);break}default:throw new Error(`Unrecognized operation type found ${Ze.type}`)}return this._isInResult}}class or{constructor(e,n,r){if(!Array.isArray(e)||e.length===0)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=n,this.isExterior=r,this.segments=[],typeof e[0][0]!="number"||typeof e[0][1]!="number")throw new Error("Input geometry is not a valid Polygon or MultiPolygon");const i=wt.round(e[0][0],e[0][1]);this.bbox={ll:{x:i.x,y:i.y},ur:{x:i.x,y:i.y}};let o=i;for(let s=1,a=e.length;s<a;s++){if(typeof e[s][0]!="number"||typeof e[s][1]!="number")throw new Error("Input geometry is not a valid Polygon or MultiPolygon");let l=wt.round(e[s][0],e[s][1]);l.x===o.x&&l.y===o.y||(this.segments.push(nt.fromRing(o,l,this)),l.x<this.bbox.ll.x&&(this.bbox.ll.x=l.x),l.y<this.bbox.ll.y&&(this.bbox.ll.y=l.y),l.x>this.bbox.ur.x&&(this.bbox.ur.x=l.x),l.y>this.bbox.ur.y&&(this.bbox.ur.y=l.y),o=l)}(i.x!==o.x||i.y!==o.y)&&this.segments.push(nt.fromRing(o,i,this))}getSweepEvents(){const e=[];for(let n=0,r=this.segments.length;n<r;n++){const i=this.segments[n];e.push(i.leftSE),e.push(i.rightSE)}return e}}class Lo{constructor(e,n){if(!Array.isArray(e))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");this.exteriorRing=new or(e[0],this,!0),this.bbox={ll:{x:this.exteriorRing.bbox.ll.x,y:this.exteriorRing.bbox.ll.y},ur:{x:this.exteriorRing.bbox.ur.x,y:this.exteriorRing.bbox.ur.y}},this.interiorRings=[];for(let r=1,i=e.length;r<i;r++){const o=new or(e[r],this,!1);o.bbox.ll.x<this.bbox.ll.x&&(this.bbox.ll.x=o.bbox.ll.x),o.bbox.ll.y<this.bbox.ll.y&&(this.bbox.ll.y=o.bbox.ll.y),o.bbox.ur.x>this.bbox.ur.x&&(this.bbox.ur.x=o.bbox.ur.x),o.bbox.ur.y>this.bbox.ur.y&&(this.bbox.ur.y=o.bbox.ur.y),this.interiorRings.push(o)}this.multiPoly=n}getSweepEvents(){const e=this.exteriorRing.getSweepEvents();for(let n=0,r=this.interiorRings.length;n<r;n++){const i=this.interiorRings[n].getSweepEvents();for(let o=0,s=i.length;o<s;o++)e.push(i[o])}return e}}class sr{constructor(e,n){if(!Array.isArray(e))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");try{typeof e[0][0][0]=="number"&&(e=[e])}catch{}this.polys=[],this.bbox={ll:{x:Number.POSITIVE_INFINITY,y:Number.POSITIVE_INFINITY},ur:{x:Number.NEGATIVE_INFINITY,y:Number.NEGATIVE_INFINITY}};for(let r=0,i=e.length;r<i;r++){const o=new Lo(e[r],this);o.bbox.ll.x<this.bbox.ll.x&&(this.bbox.ll.x=o.bbox.ll.x),o.bbox.ll.y<this.bbox.ll.y&&(this.bbox.ll.y=o.bbox.ll.y),o.bbox.ur.x>this.bbox.ur.x&&(this.bbox.ur.x=o.bbox.ur.x),o.bbox.ur.y>this.bbox.ur.y&&(this.bbox.ur.y=o.bbox.ur.y),this.polys.push(o)}this.isSubject=n}getSweepEvents(){const e=[];for(let n=0,r=this.polys.length;n<r;n++){const i=this.polys[n].getSweepEvents();for(let o=0,s=i.length;o<s;o++)e.push(i[o])}return e}}class Ht{static factory(e){const n=[];for(let r=0,i=e.length;r<i;r++){const o=e[r];if(!o.isInResult()||o.ringOut)continue;let s=null,a=o.leftSE,l=o.rightSE;const c=[a],f=a.point,u=[];for(;s=a,a=l,c.push(a),a.point!==f;)for(;;){const h=a.getAvailableLinkedEvents();if(h.length===0){const p=c[0].point,b=c[c.length-1].point;throw new Error(`Unable to complete output ring starting at [${p.x}, ${p.y}]. Last matching segment found ends at [${b.x}, ${b.y}].`)}if(h.length===1){l=h[0].otherSE;break}let d=null;for(let p=0,b=u.length;p<b;p++)if(u[p].point===a.point){d=p;break}if(d!==null){const p=u.splice(d)[0],b=c.splice(p.index);b.unshift(b[0].otherSE),n.push(new Ht(b.reverse()));continue}u.push({index:c.length,point:a.point});const m=a.getLeftmostComparator(s);l=h.sort(m)[0].otherSE;break}n.push(new Ht(c))}return n}constructor(e){this.events=e;for(let n=0,r=e.length;n<r;n++)e[n].segment.ringOut=this;this.poly=null}getGeom(){let e=this.events[0].point;const n=[e];for(let c=1,f=this.events.length-1;c<f;c++){const u=this.events[c].point,h=this.events[c+1].point;nr(u,e,h)!==0&&(n.push(u),e=u)}if(n.length===1)return null;const r=n[0],i=n[1];nr(r,e,i)===0&&n.shift(),n.push(n[0]);const o=this.isExteriorRing()?1:-1,s=this.isExteriorRing()?0:n.length-1,a=this.isExteriorRing()?n.length:-1,l=[];for(let c=s;c!=a;c+=o)l.push([n[c].x,n[c].y]);return l}isExteriorRing(){if(this._isExteriorRing===void 0){const e=this.enclosingRing();this._isExteriorRing=e?!e.isExteriorRing():!0}return this._isExteriorRing}enclosingRing(){return this._enclosingRing===void 0&&(this._enclosingRing=this._calcEnclosingRing()),this._enclosingRing}_calcEnclosingRing(){let e=this.events[0];for(let i=1,o=this.events.length;i<o;i++){const s=this.events[i];Xe.compare(e,s)>0&&(e=s)}let n=e.segment.prevInResult(),r=n?n.prevInResult():null;for(;;){if(!n)return null;if(!r)return n.ringOut;if(r.ringOut!==n.ringOut)return r.ringOut.enclosingRing()!==n.ringOut?n.ringOut:n.ringOut.enclosingRing();n=r.prevInResult(),r=n?n.prevInResult():null}}}class ar{constructor(e){this.exteriorRing=e,e.poly=this,this.interiorRings=[]}addInterior(e){this.interiorRings.push(e),e.poly=this}getGeom(){const e=[this.exteriorRing.getGeom()];if(e[0]===null)return null;for(let n=0,r=this.interiorRings.length;n<r;n++){const i=this.interiorRings[n].getGeom();i!==null&&e.push(i)}return e}}class Do{constructor(e){this.rings=e,this.polys=this._composePolys(e)}getGeom(){const e=[];for(let n=0,r=this.polys.length;n<r;n++){const i=this.polys[n].getGeom();i!==null&&e.push(i)}return e}_composePolys(e){const n=[];for(let r=0,i=e.length;r<i;r++){const o=e[r];if(!o.poly)if(o.isExteriorRing())n.push(new ar(o));else{const s=o.enclosingRing();s.poly||n.push(new ar(s)),s.poly.addInterior(o)}}return n}}class No{constructor(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:nt.compare;this.queue=e,this.tree=new Dn(n),this.segments=[]}process(e){const n=e.segment,r=[];if(e.consumedBy)return e.isLeft?this.queue.remove(e.otherSE):this.tree.remove(n),r;const i=e.isLeft?this.tree.add(n):this.tree.find(n);if(!i)throw new Error(`Unable to find segment #${n.id} [${n.leftSE.point.x}, ${n.leftSE.point.y}] -> [${n.rightSE.point.x}, ${n.rightSE.point.y}] in SweepLine tree.`);let o=i,s=i,a,l;for(;a===void 0;)o=this.tree.prev(o),o===null?a=null:o.key.consumedBy===void 0&&(a=o.key);for(;l===void 0;)s=this.tree.next(s),s===null?l=null:s.key.consumedBy===void 0&&(l=s.key);if(e.isLeft){let c=null;if(a){const u=a.getIntersection(n);if(u!==null&&(n.isAnEndpoint(u)||(c=u),!a.isAnEndpoint(u))){const h=this._splitSafely(a,u);for(let d=0,m=h.length;d<m;d++)r.push(h[d])}}let f=null;if(l){const u=l.getIntersection(n);if(u!==null&&(n.isAnEndpoint(u)||(f=u),!l.isAnEndpoint(u))){const h=this._splitSafely(l,u);for(let d=0,m=h.length;d<m;d++)r.push(h[d])}}if(c!==null||f!==null){let u=null;c===null?u=f:f===null?u=c:u=Xe.comparePoints(c,f)<=0?c:f,this.queue.remove(n.rightSE),r.push(n.rightSE);const h=n.split(u);for(let d=0,m=h.length;d<m;d++)r.push(h[d])}r.length>0?(this.tree.remove(n),r.push(e)):(this.segments.push(n),n.prev=a)}else{if(a&&l){const c=a.getIntersection(l);if(c!==null){if(!a.isAnEndpoint(c)){const f=this._splitSafely(a,c);for(let u=0,h=f.length;u<h;u++)r.push(f[u])}if(!l.isAnEndpoint(c)){const f=this._splitSafely(l,c);for(let u=0,h=f.length;u<h;u++)r.push(f[u])}}}this.tree.remove(n)}return r}_splitSafely(e,n){this.tree.remove(e);const r=e.rightSE;this.queue.remove(r);const i=e.split(n);return i.push(r),e.consumedBy===void 0&&this.tree.add(e),i}}const lr=typeof process<"u"&&process.env.POLYGON_CLIPPING_MAX_QUEUE_SIZE||1e6,zo=typeof process<"u"&&process.env.POLYGON_CLIPPING_MAX_SWEEPLINE_SEGMENTS||1e6;class Bo{run(e,n,r){Ze.type=e,wt.reset();const i=[new sr(n,!0)];for(let u=0,h=r.length;u<h;u++)i.push(new sr(r[u],!1));if(Ze.numMultiPolys=i.length,Ze.type==="difference"){const u=i[0];let h=1;for(;h<i.length;)Sn(i[h].bbox,u.bbox)!==null?h++:i.splice(h,1)}if(Ze.type==="intersection")for(let u=0,h=i.length;u<h;u++){const d=i[u];for(let m=u+1,p=i.length;m<p;m++)if(Sn(d.bbox,i[m].bbox)===null)return[]}const o=new Dn(Xe.compare);for(let u=0,h=i.length;u<h;u++){const d=i[u].getSweepEvents();for(let m=0,p=d.length;m<p;m++)if(o.insert(d[m]),o.size>lr)throw new Error("Infinite loop when putting segment endpoints in a priority queue (queue size too big).")}const s=new No(o);let a=o.size,l=o.pop();for(;l;){const u=l.key;if(o.size===a){const d=u.segment;throw new Error(`Unable to pop() ${u.isLeft?"left":"right"} SweepEvent [${u.point.x}, ${u.point.y}] from segment #${d.id} [${d.leftSE.point.x}, ${d.leftSE.point.y}] -> [${d.rightSE.point.x}, ${d.rightSE.point.y}] from queue.`)}if(o.size>lr)throw new Error("Infinite loop when passing sweep line over endpoints (queue size too big).");if(s.segments.length>zo)throw new Error("Infinite loop when passing sweep line over endpoints (too many sweep line segments).");const h=s.process(u);for(let d=0,m=h.length;d<m;d++){const p=h[d];p.consumedBy===void 0&&o.insert(p)}a=o.size,l=o.pop()}wt.reset();const c=Ht.factory(s.segments);return new Do(c).getGeom()}}const Ze=new Bo,ko=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return Ze.run("union",t,n)},Uo=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return Ze.run("intersection",t,n)},Oo=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return Ze.run("xor",t,n)},Wo=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return Ze.run("difference",t,n)};var Yo={union:ko,intersection:Uo,xor:Oo,difference:Wo};function dt(t){return t==null?null:hi(t)||di(t)||Xo(t)?t:null}function cr(t){return typeof t=="number"&&Number.isFinite(t)}function Yt(t){return Array.isArray(t)&&t.length>=2&&cr(t[0])&&cr(t[1])}function hi(t){return Array.isArray(t)&&t.length>0&&t.every(e=>Yt(e))}function di(t){return Array.isArray(t)&&t.length>0&&t.every(e=>hi(e))}function Xo(t){return Array.isArray(t)&&t.length>0&&t.every(e=>di(e))}function Ye(t){if(!Array.isArray(t)||t.length<3)return[];const e=[];for(const i of t){if(!Array.isArray(i)||i.length<2)continue;const o=Number(i[0]),s=Number(i[1]);if(!Number.isFinite(o)||!Number.isFinite(s))continue;const a=e[e.length-1];a&&a[0]===o&&a[1]===s||e.push([o,s])}if(e.length<3)return[];const n=e[0],r=e[e.length-1];return(n[0]!==r[0]||n[1]!==r[1])&&e.push([n[0],n[1]]),e.length>=4?e:[]}function St(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 fn(t){if(!Array.isArray(t)||t.length===0)return[];const e=[];for(const o of t){const s=Ye(o);s.length>=4&&e.push(s)}if(e.length===0)return[];if(e.length===1)return[e[0]];let n=0,r=0;for(let o=0;o<e.length;o+=1){const s=Math.abs(St(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 mi(t){if(!Array.isArray(t)||t.length===0)return[];const e=t[0];if(Yt(e)){const i=fn([t]);return i.length>0?[i]:[]}if(!Array.isArray(e)||e.length===0)return[];const n=e[0];if(Yt(n)){const i=fn(t);return i.length>0?[i]:[]}if(!Array.isArray(n)||n.length===0||!Yt(n[0]))return[];const r=[];for(const i of t){const o=fn(i);o.length>0&&r.push(o)}return r}function ur(t,e,n){let r=!1;for(let i=0,o=n.length-1;i<n.length;o=i,i+=1){const s=n[i][0],a=n[i][1],l=n[o][0],c=n[o][1];if(a===c||a>e==c>e)continue;t<(l-s)*(e-a)/(c-a)+s&&(r=!r)}return r}function mt(t){const e=[];for(const n of t??[]){const r=mi(n);for(const i of r){const o=i[0];if(!o||o.length<4)continue;let s=1/0,a=1/0,l=-1/0,c=-1/0;for(const[u,h]of o)u<s&&(s=u),u>l&&(l=u),h<a&&(a=h),h>c&&(c=h);if(!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(l)||!Number.isFinite(c))continue;let f=Math.abs(St(o));for(let u=1;u<i.length;u+=1)f-=Math.abs(St(i[u]));e.push({outer:o,holes:i.slice(1),minX:s,minY:a,maxX:l,maxY:c,area:Math.max(1e-6,f)})}}return e}function gi(t,e,n){if(t<n.minX||t>n.maxX||e<n.minY||e>n.maxY||!ur(t,e,n.outer))return!1;for(const r of n.holes)if(ur(t,e,r))return!1;return!0}function Et(t,e,n){for(const r of n)if(gi(t,e,r))return!0;return!1}const Nn=[160,160,160,255];function F(t,e,n){return Math.max(e,Math.min(n,t))}function zn(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 En(t,e){const n=Number(t),r=Number(e);return!Number.isFinite(n)||n<=0||!Number.isFinite(r)||r<=0?0:r*(10/n)}function Vo(t,e,n){let i=100*zn(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 Ee(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function ot(t){const e=t.fillModes instanceof Uint8Array?t.fillModes.length:Number.MAX_SAFE_INTEGER;return Math.max(0,Math.min(Math.floor(t.count??0),Math.floor((t.positions?.length??0)/2),t.paletteIndices?.length??0,e))}function Rn(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 Go(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 pi(t){const n=String(t??"").trim().match(/^#?([0-9a-fA-F]{6})$/);if(!n)return[...Nn];const r=Number.parseInt(n[1],16);return[r>>16&255,r>>8&255,r&255,255]}function Zo(t,e){const n=String(t??"").trim();if(!n)return[...e];const r=n.match(/^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/);if(r){const i=r[1].length===3?r[1].split("").map(s=>s+s).join(""):r[1],o=Number.parseInt(i,16);return[o>>16&255,o>>8&255,o&255,255]}return[...e]}function qo(t){const e=String(t?.classId??"").trim();return e||String(t?.className??"").trim()}function Ho(t){const e=[[...Nn]],n=new Map;for(const i of t??[]){const o=qo(i);!o||n.has(o)||(n.set(o,e.length),e.push(pi(i?.classColor)))}const r=new Uint8Array(e.length*4);for(let i=0;i<e.length;i+=1)r[i*4]=e[i][0],r[i*4+1]=e[i][1],r[i*4+2]=e[i][2],r[i*4+3]=e[i][3];return{colors:r,classToPaletteIndex:n}}const $o=[6,4,2],Ko=64,jo=.04,Qo=1,Jo=4,$t=1e-6,es=.1;function ts(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 fr(t,e,n){if(e<=$t||n<8)return[];const r=[];for(let i=0;i<=n;i+=1){const o=i/n*Math.PI*2;r.push([t[0]+Math.cos(o)*e,t[1]+Math.sin(o)*e])}return Ye(r)}function ns(t,e,n,r){const i=e[0]-t[0],o=e[1]-t[1],s=Math.sqrt(i*i+o*o);if(!Number.isFinite(s)||s<=r)return[];const a=i/s,c=-(o/s),f=a,u=Math.max($t,n);return Ye([[t[0]+c*u,t[1]+f*u],[e[0]+c*u,e[1]+f*u],[e[0]-c*u,e[1]-f*u],[t[0]-c*u,t[1]-f*u]])}function hr(t,e){if(!t.length)return[];let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[a,l]of t)a<n&&(n=a),a>i&&(i=a),l<r&&(r=l),l>o&&(o=l);if(!Number.isFinite(n)||!Number.isFinite(r))return[];const s=Math.max(e,1);return Ye([[n-s,r-s],[i+s,r-s],[i+s,o+s],[n-s,o+s]])}function It(t,e){return Ye(e?t.map(([n,r])=>[F(n,e[0],e[2]),F(r,e[1],e[3])]):t)}function dr(t,e){return Number.isFinite(t)?Number(t.toFixed(e)):t}function rs(t,e){if(!Array.isArray(t)||t.length===0)return[];const n=[];for(const r of t){if(!Array.isArray(r)||r.length<2)continue;const i=dr(Number(r[0]),e),o=dr(Number(r[1]),e);if(!Number.isFinite(i)||!Number.isFinite(o))continue;const s=n[n.length-1];(!s||s[0]!==i||s[1]!==o)&&n.push([i,o])}if(n.length>=2){const r=n[0],i=n[n.length-1];if(!r||!i)return[];(r[0]!==i[0]||r[1]!==i[1])&&n.push([r[0],r[1]])}return n.length>=4?n:[]}function is(t,e){if(!Array.isArray(t)||t.length===0)return[];const n=t.map(r=>rs(r,e)).filter(r=>r.length>=4);return n.length>0?n:[]}function os(t,e){const n=t.map(i=>is(i,e)).filter(i=>i.length>0);if(n.length===0)return null;let r=[n[0]];try{for(let i=1;i<n.length;i+=1)if(r=Yo.union(r,[n[i]]),!Array.isArray(r)||r.length===0)return null}catch(i){return console.error("buildBrushStrokePolygon union failed",e,i),null}return r.length>0?r:null}function ss(t){if(t.length===0)return null;for(const e of $o){const n=os(t,e);if(n)return n}return null}function as(t){if(!Array.isArray(t)||t.length===0)return[];const e=[];for(const n of t){if(!Array.isArray(n)||n.length<2)continue;const r=Number(n[0]),i=Number(n[1]);!Number.isFinite(r)||!Number.isFinite(i)||e.push([r,i])}return Ye(e)}function ls(t){let e=[],n=0;for(const r of t){if(!Array.isArray(r)||r.length===0)continue;const i=as(r[0]??[]);if(i.length<4)continue;const o=Math.abs(St(i));o<=n||(n=o,e=i)}return e}function cs(t,e=1e-9){const n=Ye(t);if(n.length<5)return n;const r=[n[0]];for(let i=1;i<n.length-1;i+=1){const o=r[r.length-1],s=n[i],a=n[i+1],l=(s[0]-o[0])*(a[1]-s[1])-(s[1]-o[1])*(a[0]-s[0]);Math.abs(l)<=e||r.push(s)}return r.push(r[0]),Ye(r)}function us(t,e,n){const r=n[0]-e[0],i=n[1]-e[1],o=r*r+i*i;if(o<=1e-12){const u=t[0]-e[0],h=t[1]-e[1];return u*u+h*h}const s=F(((t[0]-e[0])*r+(t[1]-e[1])*i)/o,0,1),a=e[0]+r*s,l=e[1]+i*s,c=t[0]-a,f=t[1]-l;return c*c+f*f}function fs(t,e){if(t.length<=2||e<=0)return t.slice();const n=new Uint8Array(t.length);n[0]=1,n[t.length-1]=1;const r=e*e,i=[[0,t.length-1]];for(;i.length>0;){const s=i.pop();if(!s)break;const[a,l]=s;if(l-a<=1)continue;let c=0,f=-1;for(let u=a+1;u<l;u+=1){const h=us(t[u],t[a],t[l]);h>c&&(c=h,f=u)}f>=0&&c>r&&(n[f]=1,i.push([a,f],[f,l]))}const o=[];for(let s=0;s<t.length;s+=1)n[s]&&o.push(t[s]);return o}function hs(t,e){const n=Ye(t);if(n.length<5||e<=0)return n;const r=n.slice(0,-1),i=fs(r,e);return i.length<3?n:Ye(i)}function ds(t,e){let n=Ye(t);if(e<=0||n.length<5)return n;for(let r=0;r<e;r+=1){const i=n.slice(0,-1);if(i.length<3)break;const o=[];for(let s=0;s<i.length;s+=1){const a=i[s],l=i[(s+1)%i.length];o.push([a[0]*.75+l[0]*.25,a[1]*.75+l[1]*.25],[a[0]*.25+l[0]*.75,a[1]*.25+l[1]*.75])}n=Ye(o)}return n}function ms(t,e){const n=ts(t),r=Math.max($t,Number(e.radius)||0);if(n.length===0||!Number.isFinite(r))return[];const i=Math.max(12,Math.floor(e.circleSides||Ko));if(n.length===1)return It(fr(n[0],r,i),e.clipBounds);const o=[],s=Math.max($t,r*es);for(let h=0;h<n.length;h+=1){const d=n[h],m=fr(d,r,i);if(m.length>=4&&o.push([m]),h===0)continue;const p=ns(n[h-1],d,r,s);p.length>=4&&o.push([p])}const a=ss(o),l=a?ls(a):[];if(!l.length)return It(hr(n,r),e.clipBounds);const c=typeof e.simplifyTolerance=="number"&&Number.isFinite(e.simplifyTolerance)?Math.max(0,e.simplifyTolerance):Math.max(.25,r*jo),f=typeof e.smoothingPasses=="number"&&Number.isFinite(e.smoothingPasses)?Math.round(F(e.smoothingPasses,0,Jo)):Qo,u=hs(ds(cs(l,1e-9),f),c);return u.length<4?It(hr(n,r),e.clipBounds):It(u,e.clipBounds)}function mr(){if(typeof window>"u")return 1;const t=window.devicePixelRatio||1;return Number.isFinite(t)&&t>0?t:1}function rn(t){if(typeof window>"u")return()=>{};let e=!0,n=mr(),r=null,i=null;const o=()=>{i?.(),i=null,r=null},s=()=>{o(),r=window.matchMedia(`(resolution: ${n}dppx)`);const f=()=>{a("match-media")};if(typeof r.addEventListener=="function"){r.addEventListener("change",f),i=()=>r?.removeEventListener("change",f);return}r.addListener(f),i=()=>r?.removeListener(f)},a=f=>{if(!e)return;const u=mr();if(Math.abs(u-n)<=1e-4)return;const h=n;n=u,s(),t({previousDpr:h,nextDpr:u,trigger:f})},l=()=>a("window-resize"),c=()=>a("visual-viewport-resize");return s(),window.addEventListener("resize",l),window.visualViewport?.addEventListener("resize",c),()=>{e=!1,o(),window.removeEventListener("resize",l),window.visualViewport?.removeEventListener("resize",c)}}const it=[],gr=[],$e={color:"#ff4d4f",width:2,lineDash:it,lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},yi={color:"#4cc9f0",width:2,lineDash:[10,8],lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},bi="rgba(23, 23, 25, 0.1)",xi=6,Ve={fontFamily:"Pretendard, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:11,fontWeight:600,textColor:"#171719",backgroundColor:"#FFCC00",borderColor:"rgba(0, 0, 0, 0)",borderWidth:0,paddingX:8,paddingY:4,offsetY:10,borderRadius:4},Je={fontFamily:"Pretendard, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:13,fontWeight:500,textColor:"#FFFFFF",backgroundColor:"rgba(23, 23, 25, 0.5)",borderRadius:4,paddingX:6,paddingY:3},pr={x:16,y:-24},gs=20,yr=1e-6,br="transparent",ps=3,ys=2,wi=96,bs=1,xr=1e3,Si=2,Ei=2,xs=4096,ws=.2,Ss=1.12,Es=.89,Rs=32,Ms="#000000",As=.1,Cs="#FFCF00",Ps="#FF0000",vs=1.5,wr=[2,2],Ts=1,Is=.25,_s=4,Fs=1,Ls=0,Ds=4,Ns=1.5;function Kt(t,e,n){return[F(t[0],0,e),F(t[1],0,n)]}function Bn(t){if(!Array.isArray(t)||t.length<2)return null;const e=Number(t[0]),n=Number(t[1]);return!Number.isFinite(e)||!Number.isFinite(n)?null:[e,n]}const qe=Bn;function Oe(t){return Ye(t)}function Xt(t){return Math.abs(St(Oe(t)))}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 Rt(t,e,n=!1){if(e.length!==0){t.moveTo(e[0][0],e[0][1]);for(let r=1;r<e.length;r+=1)t.lineTo(e[r][0],e[r][1]);n&&t.closePath()}}function ke(t,e,n,r=!1,i=!1,o="rgba(255, 77, 79, 0.16)"){e.length!==0&&(t.beginPath(),Rt(t,e,r),i&&r&&(t.fillStyle=o,t.fill()),t.strokeStyle=n.color,t.lineWidth=n.width,t.lineJoin=n.lineJoin,t.lineCap=n.lineCap,t.shadowColor=n.shadowColor,t.shadowBlur=n.shadowBlur,t.shadowOffsetX=n.shadowOffsetX,t.shadowOffsetY=n.shadowOffsetY,t.setLineDash(n.lineDash),t.stroke(),t.setLineDash(it),t.shadowColor="rgba(0, 0, 0, 0)",t.shadowBlur=0,t.shadowOffsetX=0,t.shadowOffsetY=0)}function kn(t){const e=Array.isArray(t?.lineDash)?t.lineDash.filter(s=>Number.isFinite(s)&&s>=0):it,n=typeof t?.width=="number"&&Number.isFinite(t.width)?Math.max(0,t.width):$e.width,r=typeof t?.shadowBlur=="number"&&Number.isFinite(t.shadowBlur)?Math.max(0,t.shadowBlur):$e.shadowBlur,i=typeof t?.shadowOffsetX=="number"&&Number.isFinite(t.shadowOffsetX)?t.shadowOffsetX:$e.shadowOffsetX,o=typeof t?.shadowOffsetY=="number"&&Number.isFinite(t.shadowOffsetY)?t.shadowOffsetY:$e.shadowOffsetY;return{color:t?.color||$e.color,width:n,lineDash:e.length?e:it,lineJoin:t?.lineJoin||$e.lineJoin,lineCap:t?.lineCap||$e.lineCap,shadowColor:t?.shadowColor||$e.shadowColor,shadowBlur:r,shadowOffsetX:i,shadowOffsetY:o}}function Ke(t,e){return e?kn({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 jt(t,e){return t==null||e===null||e===void 0?!1:String(t)===String(e)}function Er(t){return typeof t=="number"&&Number.isFinite(t)}function zs(t){return Array.isArray(t)&&t.length>=2&&Er(t[0])&&Er(t[1])}function Bs(t){return Array.isArray(t)&&t.length>=2&&t.every(e=>zs(e))}function Ri(t,e){if(!(!Array.isArray(t)||t.length===0)){if(Bs(t)){e.push(t.map(([n,r])=>[n,r]));return}for(const n of t)Ri(n,e)}}function Rr(t,e){const n=[];Ri(t,n);const r=[];for(const i of n){if(i.length<2)continue;const o=e?Oe(i):i;o.length>=(e?4:2)&&r.push(o)}return r}function bt(t,e){return typeof t!="number"||!Number.isFinite(t)||t<=0?e:t}function ks(t,e){return typeof t!="number"||!Number.isFinite(t)?e:F(t,0,1)}function Mi(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 Us(t){const e=t[0];return Array.isArray(e)&&Array.isArray(e[0])}function Qt(t,e,n){if(!t||!e)return[];if(n){const r=n.worldToScreen(t[0],t[1]),i=n.worldToScreen(e[0],e[1]);if(r&&i){const o=[[r[0],r[1]],[i[0],r[1]],[i[0],i[1]],[r[0],i[1]]],s=[];for(const a of o){const l=n.screenToWorld(a);if(!l)return Qt(t,e);s.push(l)}return Oe(s)}}return Oe([[t[0],t[1]],[e[0],t[1]],[e[0],e[1]],[t[0],e[1]]])}function Mn(t,e,n=wi){if(!t||!e)return[];const r=(t[0]+e[0])*.5,i=(t[1]+e[1])*.5,o=Math.hypot(e[0]-t[0],e[1]-t[1])*.5;if(o<1)return[];const s=[];for(let a=0;a<=n;a+=1){const l=a/n*Math.PI*2;s.push([r+Math.cos(l)*o,i+Math.sin(l)*o])}return Oe(s)}function Jt(t){const e=mi(dt(t));if(e.length===0)return[];const n=[];for(const r of e){const i=r[0];if(!i||i.length<4)continue;const o=i.map(([a,l])=>[a,l]),s=[];for(let a=1;a<r.length;a+=1){const l=r[a];!l||l.length<4||s.push(l.map(([c,f])=>[c,f]))}n.push({outer:o,holes:s})}return n}function Os(t){if(!Array.isArray(t))return wr;const e=t.filter(n=>Number.isFinite(n)&&n>=0);return e.length>0?e:wr}function Ws(t){return typeof t!="number"||!Number.isFinite(t)?Ts:F(t,Is,_s)}function Ys(t){return typeof t!="number"||!Number.isFinite(t)?Fs:Math.round(F(t,Ls,Ds))}function Xs(t){const e=bt(t?.radius,Rs),n=bt(t?.cursorLineWidth,vs),r=Ws(t?.edgeDetail),i=Ys(t?.edgeSmoothing);return{radius:e,edgeDetail:r,edgeSmoothing:i,clickSelectRoi:t?.clickSelectRoi===!0,fillColor:t?.fillColor||Ms,fillOpacity:ks(t?.fillOpacity,As),cursorColor:t?.cursorColor||Cs,cursorActiveColor:t?.cursorActiveColor||Ps,cursorLineWidth:n,cursorLineDash:Os(t?.cursorLineDash)}}function Vs(t,e,n){if(!e.isDrawing||e.screenPoints.length===0)return;const r=e.screenPoints;if(r.length===0)return;const i=n.radius;if(!(!Number.isFinite(i)||i<=0)){if(t.save(),t.globalAlpha=n.fillOpacity,t.fillStyle=n.fillColor,t.strokeStyle=n.fillColor,t.lineCap="round",t.lineJoin="round",t.lineWidth=i*2,r.length===1)t.beginPath(),t.arc(r[0][0],r[0][1],i,0,Math.PI*2),t.fill();else{t.beginPath(),t.moveTo(r[0][0],r[0][1]);for(let o=1;o<r.length;o+=1)t.lineTo(r[o][0],r[o][1]);t.stroke()}t.restore()}}function Gs(t,e,n,r){const i=e.cursor;if(!i)return;const o=e.cursorScreen??qe(n?.worldToScreen(i[0],i[1])??[]);if(!o)return;const s=r.radius;!Number.isFinite(s)||s<=0||(t.save(),t.beginPath(),t.arc(o[0],o[1],s,0,Math.PI*2),t.strokeStyle=e.isDrawing?r.cursorActiveColor:r.cursorColor,t.lineWidth=r.cursorLineWidth,t.setLineDash(r.cursorLineDash),t.stroke(),t.setLineDash(it),t.restore())}const Zs=.58,qs=4096,Hs=.5;let _t=null;const Ft=new Map;function $s(){if(_t)return _t;if(typeof document>"u")return null;const e=document.createElement("canvas").getContext("2d");return e?(_t=e,_t):null}function Un(t,e){const n=`${e.fontWeight}|${e.fontSize}|${e.fontFamily}|${t}`,r=Ft.get(n);if(r!==void 0)return r;const i=t.length*e.fontSize*Zs,o=$s();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 Ft.size>qs&&Ft.clear(),Ft.set(n,s),s}function Ks(t,e="top-center"){if(!t.length)return null;let n=1/0;for(const o of t)o[1]<n&&(n=o[1]);if(!Number.isFinite(n))return null;let r=1/0,i=-1/0;for(const o of t)Math.abs(o[1]-n)>Hs||(o[0]<r&&(r=o[0]),o[0]>i&&(i=o[0]));return!Number.isFinite(r)||!Number.isFinite(i)?null:e==="top-center"?[(r+i)*.5,n]:[r,n]}function On(t,e,n="top-center"){let r=null;for(const i of t){const o=e(i.outer);if(o.length===0)continue;const s=Ks(o,n);s&&(!r||s[1]<r[1]||s[1]===r[1]&&s[0]<r[0])&&(r=s)}return r}function Wn(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 Yn(t,e){return e?Wn({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 Xn(t,e,n,r){if(!t||!n)return 0;const i=Number(n.minZoom),o=Number(n.maxZoom);if(!Number.isFinite(i)||!Number.isFinite(o)||o-i<=yr||!Number.isFinite(e))return 0;let s=o;r!=null&&Number.isFinite(r)&&(s=F(r,i,o));const a=Math.max(yr,Math.abs(s)*1e-9);return e>=s-a?gs:0}function js(t){const e=typeof t?.fontSize=="number"&&Number.isFinite(t.fontSize)?Math.max(8,t.fontSize):Je.fontSize,n=typeof t?.borderRadius=="number"&&Number.isFinite(t.borderRadius)?Math.max(0,t.borderRadius):Je.borderRadius,r=typeof t?.paddingX=="number"&&Number.isFinite(t.paddingX)?Math.max(0,t.paddingX):Je.paddingX,i=typeof t?.paddingY=="number"&&Number.isFinite(t.paddingY)?Math.max(0,t.paddingY):Je.paddingY;return{fontFamily:t?.fontFamily||Je.fontFamily,fontSize:e,fontWeight:t?.fontWeight||Je.fontWeight,textColor:t?.textColor||Je.textColor,backgroundColor:t?.backgroundColor||Je.backgroundColor,borderRadius:n,paddingX:r,paddingY:i}}function Qs(t){const e=typeof t?.x=="number"&&Number.isFinite(t.x)?t.x:pr.x,n=typeof t?.y=="number"&&Number.isFinite(t.y)?t.y:pr.y;return{x:e,y:n}}function Js(t){return Number.isFinite(t)?`${Math.max(0,t).toFixed(3)} mm²`:"0.000 mm²"}function ea(t){const e=typeof t?.format=="function"?t.format:Js,n=Qs(t?.cursorOffset);return{enabled:t?.enabled===!0,format:e,style:js(t?.style),cursorOffsetX:n.x,cursorOffsetY:n.y}}function Ai(t,e,n,r,i,o,s=!0){const a=e.trim();if(!a)return;t.save(),t.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,t.textAlign="center",t.textBaseline="middle";const c=Un(a,o)+o.paddingX*2,f=o.fontSize+o.paddingY*2,u=n[0],h=n[1]-o.offsetY,d=s?F(u,c*.5+1,r-c*.5-1):u,m=s?F(h,f*.5+1,i-f*.5-1):h,p=d-c*.5,b=m-f*.5;t.fillStyle=o.backgroundColor,t.strokeStyle=o.borderColor,t.lineWidth=o.borderWidth,Mi(t,p,b,c,f,o.borderRadius),t.fill(),o.borderWidth>0&&t.stroke(),t.fillStyle=o.textColor,t.fillText(a,d,m+.5),t.restore()}function ta(t,e,n,r,i,o,s,a){const l=e.trim();if(!l)return;t.save(),t.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,t.textAlign="center",t.textBaseline="middle";const f=Un(l,o)+o.paddingX*2,u=o.fontSize+o.paddingY*2,h=F(n[0]+s,f*.5+1,r-f*.5-1),d=F(n[1]+a,u*.5+1,i-u*.5-1),m=h-f*.5,p=d-u*.5;t.fillStyle=o.backgroundColor,Mi(t,m,p,f,u,o.borderRadius),t.fill(),t.fillStyle=o.textColor,t.fillText(l,h,d+.5),t.restore()}function na(t,e,n,r){if(!(e.length<4||n.length===0)){t.save(),t.beginPath(),Rt(t,e,!0);for(const i of n)i.length<4||Rt(t,i,!0);t.fillStyle=r,t.fill("evenodd"),t.restore()}}function Ci(t){const{ctx:e,overlayShapes:n,imageOuterRing:r,worldToScreenPoints:i,baseStrokeStyle:o,onInvertedFillDebug:s}=t,a=!!globalThis.__OPEN_PLANT_DEBUG_OVERLAY__;for(let l=0;l<n.length;l+=1){const c=n[l];if(!c?.coordinates?.length||c.visible===!1)continue;const f=c.closed??Us(c.coordinates),u=Rr(c.coordinates,f);if(c.invertedFill?.fillColor){const d=[],m=Rr(c.coordinates,!0);for(const p of m){const b=i(p);b.length>=4&&d.push(b)}a&&s&&s({id:c.id??l,outerRingPoints:r.length,sourceRingCount:m.length,holeRingCount:d.length,fillColor:c.invertedFill.fillColor}),na(e,r,d,c.invertedFill.fillColor)}if(u.length===0)continue;const h=Ke(o,c.stroke??c.strokeStyle);for(const d of u){const m=i(d);m.length<2||ke(e,m,h,f,c.fill??!1)}}}function Lt(t){return typeof t=="string"&&(t==="stamp-rectangle"||t==="stamp-circle"||t==="stamp-rectangle-4096px"||t==="stamp-rectangle-2mm2"||t==="stamp-circle-2mm2"||t==="stamp-circle-hpf-0.2mm2")}function ra(t){return{rectangleAreaMm2:bt(t?.rectangleAreaMm2,Si),circleAreaMm2:bt(t?.circleAreaMm2,Ei),rectanglePixelSize:bt(t?.rectanglePixelSize,xs)}}const Mr=1e3;function ia(t){return t*Mr*Mr}function Ar(t,e,n){if(!t||!Number.isFinite(e)||e<=0)return[];if(n){const r=n.worldToScreen(t[0],t[1]),i=n.worldToScreen(t[0]+e,t[1]);if(r&&i){const o=Math.hypot(i[0]-r[0],i[1]-r[1]),s=[[r[0]-o,r[1]-o],[r[0]+o,r[1]-o],[r[0]+o,r[1]+o],[r[0]-o,r[1]+o]],a=[];for(const l of s){const c=n.screenToWorld(l);if(!c)throw new Error("Failed to create rectangle");a.push(c)}return Oe(a)}}return Oe([[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 oa(t,e,n=wi){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 Oe(r)}function sa(t){const{stampTool:e,center:n,resolvedStampOptions:r,imageWidth:i,imageHeight:o,micronsToWorldPixels:s,getRectangleProjection:a}=t;if(!n)return[];if(e==="stamp-rectangle-4096px"){const u=r.rectanglePixelSize*.5;return Ar(n,u,a()).map(h=>Kt(h,i,o))}let l=0;if(e==="stamp-rectangle"||e==="stamp-rectangle-2mm2"?l=e==="stamp-rectangle-2mm2"?Si:r.rectangleAreaMm2:(e==="stamp-circle"||e==="stamp-circle-2mm2"||e==="stamp-circle-hpf-0.2mm2")&&(l=e==="stamp-circle-hpf-0.2mm2"?ws:e==="stamp-circle-2mm2"?Ei:r.circleAreaMm2),!Number.isFinite(l)||l<=0)return[];const c=ia(l);let f=[];if(e==="stamp-rectangle"||e==="stamp-rectangle-2mm2"){const u=s(Math.sqrt(c)*.5);f=Ar(n,u,a())}else if(e==="stamp-circle"||e==="stamp-circle-2mm2"||e==="stamp-circle-hpf-0.2mm2"){const u=s(Math.sqrt(c/Math.PI));f=oa(n,u)}return f.length?f.map(u=>Kt(u,i,o)):[]}function aa(t){return{color:bi,width:xi,lineDash:it,lineJoin:t.lineJoin,lineCap:t.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function la(t){if(typeof t!="string")return br;const e=t.trim();return e.length>0?e:br}function Cr(t){return Array.isArray(t)&&t.length>=4&&Xt(t)>bs}function Pi({tool:t,imageWidth:e,imageHeight:n,imageMpp:r,imageZoom:i,stampOptions:o,brushOptions:s,projectorRef:a,onBrushTap:l,onDrawComplete:c,onPatchComplete:f,enabled:u,viewStateSignal:h,persistedRegions:d,patchRegions:m,persistedPolygons:p,drawFillColor:b,regionStrokeStyle:y,regionStrokeHoverStyle:x,regionStrokeActiveStyle:M,patchStrokeStyle:S,resolveRegionStrokeStyle:C,resolveRegionLabelStyle:A,overlayShapes:B,hoveredRegionId:z=null,activeRegionId:Y=null,regionLabelStyle:P,drawAreaTooltip:I,autoLiftRegionLabelAtMaxZoom:O=!1,regionLabelAnchor:v="top-center",clampRegionLabelToViewport:W=!0,regionLabelAutoLiftOffsetPx:j,invalidateRef:L,className:ge,style:le}){const Q=g.useRef(null),ve=g.useRef(!1),Ae=g.useRef(new Map),D=g.useRef(t),T=g.useRef({isDrawing:!1,pointerId:null,start:null,current:null,cursor:null,cursorScreen:null,points:[],screenPoints:[],stampCenter:null}),k=u??t!=="cursor",oe=g.useMemo(()=>d&&d.length>0?d:!p||p.length===0?gr:p.map((w,R)=>({id:R,coordinates:w})),[d,p]),ue=g.useMemo(()=>m??gr,[m]),$=g.useMemo(()=>{const w=[];for(let R=0;R<oe.length;R+=1){const _=oe[R],N=Jt(_.coordinates);N.length!==0&&w.push({region:_,regionIndex:R,regionKey:_.id??R,polygons:N})}return w},[oe]),ce=g.useMemo(()=>{const w=[];for(let R=0;R<ue.length;R+=1){const _=ue[R],N=Jt(_.coordinates);N.length!==0&&w.push({region:_,regionIndex:R,regionKey:_.id??R,polygons:N})}return w},[ue]),te=g.useMemo(()=>kn(y),[y]),_e=g.useMemo(()=>Ke(te,x),[te,x]),Se=g.useMemo(()=>Ke(te,M),[te,M]),fe=g.useMemo(()=>Ke(yi,S),[S]),xe=g.useMemo(()=>la(b),[b]),ee=g.useMemo(()=>Wn(P),[P]),se=g.useMemo(()=>ea(I),[I]),he=g.useMemo(()=>ra(o),[o]),ae=g.useMemo(()=>Xs(s),[s]),ne=g.useMemo(()=>({position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",touchAction:"none",pointerEvents:k?"auto":"none",cursor:k?t==="brush"?"none":"crosshair":"default",...le}),[k,t,le]),Me=g.useCallback(()=>{const w=Q.current;if(!w)return;const R=w.getBoundingClientRect(),_=Math.max(1,window.devicePixelRatio||1),N=Math.max(1,Math.round(R.width*_)),G=Math.max(1,Math.round(R.height*_));(w.width!==N||w.height!==G)&&(w.width=N,w.height=G)},[k,t]),we=g.useCallback(w=>{const R=a.current;if(!R||w.length===0)return[];const _=new Array(w.length);for(let N=0;N<w.length;N+=1){const G=qe(R.worldToScreen(w[N][0],w[N][1]));if(!G)return[];_[N]=G}return _},[a]),V=g.useCallback(w=>{const R=a.current,_=Q.current;if(!R||!_)return null;const N=_.getBoundingClientRect(),G=qe(R.screenToWorld(N.left+w[0],N.top+w[1]));return G?Kt(G,e,n):null},[a,e,n]),H=g.useCallback(()=>{const w=a.current,R=w?.getViewState?.().rotationDeg??0;if(!(Math.abs(R%360)<.01||!w))return{worldToScreen:(_,N)=>qe(w.worldToScreen(_,N)),screenToWorld:V}},[a,V]),be=g.useCallback(w=>{if(!Number.isFinite(w)||w<=0)return 0;const R=typeof r=="number"&&Number.isFinite(r)&&r>0?r:1,_=typeof i=="number"&&Number.isFinite(i)?i:0,N=a.current?.getViewState?.().zoom,G=typeof N=="number"&&Number.isFinite(N)&&N>0?N:1,ye=_+Math.log2(G),ie=Math.max(1e-9,zn(R,_,ye));return w/ie/G},[r,i,a]),J=g.useCallback((w,R)=>sa({stampTool:w,center:R,resolvedStampOptions:he,imageWidth:e,imageHeight:n,micronsToWorldPixels:be,getRectangleProjection:H}),[be,e,n,he,H]),K=g.useCallback(()=>{const w=T.current;return Lt(t)?J(t,w.stampCenter):t==="brush"?[]:w.isDrawing?t==="freehand"?w.points:t==="rectangle"?Qt(w.start,w.current,H()):t==="circular"?Mn(w.start,w.current):[]:[]},[t,J,H]),Re=g.useCallback(()=>{Me();const w=Q.current;if(!w)return;const R=w.getContext("2d");if(!R)return;const _=Math.max(1,window.devicePixelRatio||1),N=w.width/_,G=w.height/_;if(R.setTransform(1,0,0,1,0,0),R.clearRect(0,0,w.width,w.height),R.setTransform(_,0,0,_,0,0),$.length>0)for(const ie of $){const{region:me,polygons:Pe,regionIndex:Te,regionKey:ze}=ie,at=jt(Y,ze)?"active":jt(z,ze)?"hover":"default";let Qe=at==="active"?Se:at==="hover"?_e:te;if(C){const Tt=C({region:me,regionId:ze,regionIndex:Te,state:at});Qe=Ke(Qe,Tt||void 0)}const vt=at==="default"?null:aa(Qe);for(const Tt of Pe){const sn=we(Tt.outer);sn.length>=4&&(vt&&ke(R,sn,vt,!0,!1),ke(R,sn,Qe,!0,!1));for(const lo of Tt.holes){const an=we(lo);an.length>=4&&(vt&&ke(R,an,vt,!0,!1),ke(R,an,Qe,!0,!1))}}}if(ce.length>0)for(const ie of ce)for(const me of ie.polygons){const Pe=we(me.outer);Pe.length>=4&&ke(R,Pe,fe,!0,!1);for(const Te of me.holes){const ze=we(Te);ze.length>=4&&ke(R,ze,fe,!0,!1)}}if(Array.isArray(B)&&B.length>0){const ie=we(Oe([[0,0],[e,0],[e,n],[0,n]]));Ci({ctx:R,overlayShapes:B,imageOuterRing:ie,worldToScreenPoints:we,baseStrokeStyle:te,onInvertedFillDebug:globalThis.__OPEN_PLANT_DEBUG_OVERLAY__?me=>{const Pe=String(me.id),Te=`${me.outerRingPoints}|${me.sourceRingCount}|${me.holeRingCount}|${me.fillColor}`;Ae.current.get(Pe)!==Te&&(Ae.current.set(Pe,Te),console.debug("[open-plant] invertedFill",me))}:void 0})}const ye=K();if(k){if(t==="brush")Vs(R,T.current,ae),Gs(R,T.current,a.current,ae);else if(ye.length>0)if(t==="freehand"){const ie=we(ye);ie.length>=2&&ke(R,ie,te,!1,!1),ie.length>=3&&ke(R,we(Oe(ye)),te,!0,!0,xe)}else{const ie=we(ye);ie.length>=4&&ke(R,ie,te,!0,!0,xe)}}if($.length>0){const ie=Math.max(1e-6,a.current?.getViewState?.().zoom??1),me=typeof j=="number"&&Number.isFinite(j)?Math.max(0,j):Xn(O,ie,a.current?.getZoomRange?.(),a.current?.getRegionLabelAutoLiftCapZoom?.());for(const Pe of $){if(!Pe.region.label)continue;const Te=On(Pe.polygons,we,v);if(!Te)continue;let ze=Yn(ee,A?.({region:Pe.region,regionId:Pe.regionKey,regionIndex:Pe.regionIndex,zoom:ie}));me>0&&(ze={...ze,offsetY:ze.offsetY+me}),Ai(R,Pe.region.label,Te,N,G,ze,W)}}if(se.enabled&&k&&(t==="freehand"||t==="rectangle"||t==="circular")){const ie=T.current;if(ie.isDrawing){const me=t==="freehand"?Oe(ye):ye;if(me.length>=4){const Pe=Xt(me),Te=typeof r=="number"&&Number.isFinite(r)&&r>0?r:0,ze=Te>0?Pe*Te*Te/(xr*xr):0,at=se.format(ze),Qe=ie.cursorScreen??(ie.current?qe(a.current?.worldToScreen(ie.current[0],ie.current[1])??[]):null);Qe&&ta(R,at,Qe,N,G,se.style,se.cursorOffsetX,se.cursorOffsetY)}}}},[k,t,K,Me,we,e,n,a,$,B,z,Y,te,_e,Se,xe,ce,fe,C,A,ee,se,O,v,W,j,r,ae]),X=g.useCallback(()=>{ve.current||(ve.current=!0,requestAnimationFrame(()=>{ve.current=!1,Re()}))},[Re]),Ce=g.useCallback((w=!1)=>{const R=T.current,_=Q.current;_&&R.pointerId!==null&&_.hasPointerCapture(R.pointerId)&&_.releasePointerCapture(R.pointerId),R.isDrawing=!1,R.pointerId=null,R.start=null,R.current=null,R.points=[],R.screenPoints=[],R.stampCenter=null,w||(R.cursor=null,R.cursorScreen=null)},[]),De=g.useCallback(w=>{const R=a.current;if(!R||e<=0||n<=0)return null;const _=qe(R.screenToWorld(w.clientX,w.clientY));return _?Kt(_,e,n):null},[a,e,n]),Le=g.useCallback(w=>{const R=Q.current;if(!R)return null;const _=R.getBoundingClientRect(),N=F(w.clientX-_.left,0,_.width),G=F(w.clientY-_.top,0,_.height);return!Number.isFinite(N)||!Number.isFinite(G)?null:[N,G]},[]),U=g.useCallback(()=>{const w=T.current;if(!w.isDrawing){Ce(!0),X();return}let R=[];if(t==="freehand")w.points.length>=ps&&(R=Oe(w.points));else if(t==="rectangle")R=Qt(w.start,w.current,H());else if(t==="circular")R=Mn(w.start,w.current);else if(t==="brush"){const _=w.points[w.points.length-1]??w.current??w.start;if(ae.clickSelectRoi&&_&&w.points.length<=1&&l?.(_)){Ce(!0),X();return}const N=Math.max(.25,ae.edgeDetail),G=w.screenPoints.length>0?w.screenPoints:we(w.points),ye=Math.max(.5,ae.radius*.04/N),ie=ms(G,{radius:ae.radius,circleSides:Math.max(16,Math.round(32*N)),simplifyTolerance:ye,smoothingPasses:ae.edgeSmoothing}),me=[];for(const Pe of ie){const Te=V(Pe);Te&&me.push(Te)}R=Oe(me)}(t==="freehand"||t==="rectangle"||t==="circular"||t==="brush")&&Cr(R)&&c&&c({tool:t,intent:t==="brush"?"brush":"roi",coordinates:R,bbox:Sr(R),areaPx:Xt(R)}),Ce(!0),X()},[t,c,Ce,X,we,V,H,ae.radius,ae.edgeDetail,ae.edgeSmoothing,ae.clickSelectRoi,l]),Z=g.useCallback((w,R)=>{const _=J(w,R);if(!Cr(_))return;const N=w==="stamp-rectangle-4096px"?"patch":"roi",G={tool:w,intent:N,coordinates:_,bbox:Sr(_),areaPx:Xt(_)};c?.(G),N==="patch"&&f&&f(G)},[J,c,f]),q=g.useCallback((w,R,_)=>{const N=Math.max(Ns,ae.radius*.1),G=N*N,ye=w.screenPoints[w.screenPoints.length-1];if(!ye){w.points.push(R),w.screenPoints.push(_),w.current=R;return}const ie=_[0]-ye[0],me=_[1]-ye[1];ie*ie+me*me>=G?(w.points.push(R),w.screenPoints.push(_)):(w.points[w.points.length-1]=R,w.screenPoints[w.screenPoints.length-1]=_),w.current=R},[ae.radius]),re=g.useCallback(w=>{if(!k||t==="cursor"||w.button!==0)return;const R=De(w);if(!R)return;const _=Le(w);if(!_)return;if(w.preventDefault(),w.stopPropagation(),Lt(t)){const ye=T.current;ye.stampCenter=R,Z(t,R),X();return}const N=Q.current;N&&N.setPointerCapture(w.pointerId);const G=T.current;G.isDrawing=!0,G.pointerId=w.pointerId,G.start=R,G.current=R,G.cursor=R,G.cursorScreen=_,G.points=t==="freehand"||t==="brush"?[R]:[],G.screenPoints=t==="brush"?[_]:[],X()},[k,t,De,Le,Z,X]),pe=g.useCallback(w=>{if(!k||t==="cursor")return;const R=De(w);if(!R)return;const _=Le(w);if(!_)return;const N=T.current;if(N.cursor=R,N.cursorScreen=_,Lt(t)){N.stampCenter=R,w.preventDefault(),w.stopPropagation(),X();return}if(t==="brush"){if(!N.isDrawing||N.pointerId!==w.pointerId){X();return}w.preventDefault(),w.stopPropagation(),q(N,R,_),X();return}if(!(!N.isDrawing||N.pointerId!==w.pointerId)){if(w.preventDefault(),w.stopPropagation(),t==="freehand"){const G=a.current,ye=Math.max(1e-6,G?.getViewState?.().zoom??1),ie=ys/ye,me=ie*ie,Pe=N.points[N.points.length-1];if(!Pe)N.points.push(R);else{const Te=R[0]-Pe[0],ze=R[1]-Pe[1];Te*Te+ze*ze>=me&&N.points.push(R)}}else N.current=R;X()}},[k,t,De,Le,X,a,q]),de=g.useCallback(w=>{const R=T.current;if(!R.isDrawing||R.pointerId!==w.pointerId)return;w.preventDefault(),w.stopPropagation();const _=De(w),N=Le(w);_&&(R.cursor=_,N&&(R.cursorScreen=N),t==="brush"?N&&q(R,_,N):R.current=_);const G=Q.current;G&&G.hasPointerCapture(w.pointerId)&&G.releasePointerCapture(w.pointerId),U()},[U,De,Le,t,q]),Ne=g.useCallback(()=>{const w=T.current;let R=!1;t==="brush"&&!w.isDrawing&&w.cursor&&(w.cursor=null,w.cursorScreen=null,R=!0),Lt(t)&&w.stampCenter&&(w.stampCenter=null,R=!0),R&&X()},[t,X]);return g.useEffect(()=>{Me(),X();const w=Q.current;if(!w)return;const R=new ResizeObserver(()=>{Me(),X()});return R.observe(w),()=>{R.disconnect()}},[Me,X]),g.useEffect(()=>rn(()=>{Me(),X()}),[Me,X]),g.useEffect(()=>{k||Ce(),X()},[k,X,Ce]),g.useEffect(()=>{D.current!==t&&(D.current=t,Ce(),X())},[t,Ce,X]),g.useEffect(()=>{X()},[h,oe,B,X]),g.useEffect(()=>{if(L)return L.current=X,()=>{L.current===X&&(L.current=null)}},[L,X]),g.useEffect(()=>{if(!k)return;const w=R=>{R.key==="Escape"&&(Ce(),X())};return window.addEventListener("keydown",w),()=>{window.removeEventListener("keydown",w)}},[k,Ce,X]),Ge.jsx("canvas",{ref:Q,className:ge,style:ne,onPointerDown:re,onPointerMove:pe,onPointerUp:de,onPointerCancel:de,onPointerLeave:Ne,onContextMenu:w=>{k&&w.preventDefault()},onWheel:w=>{if(!k)return;const R=Q.current,_=a.current,N=typeof _?.handleWheelZoom=="function",G=typeof _?.zoomBy=="function";if(!R||!N&&!G)return;w.preventDefault(),w.stopPropagation();const ye=R.getBoundingClientRect(),ie=w.clientX-ye.left,me=w.clientY-ye.top;N?_.handleWheelZoom?.(w.deltaY,ie,me):_.zoomBy?.(w.deltaY<0?Ss:Es,ie,me),X()}})}const vi=g.createContext(null),ca=vi.Provider;function st(){const t=g.useContext(vi);if(!t)throw new Error("useViewerContext must be used within a <WsiViewer>");return t}function ua({tool:t="cursor",stampOptions:e,brushOptions:n,fillColor:r,areaTooltip:i,onComplete:o,onPatchComplete:s,onBrushTap:a}){const{source:l,rendererRef:c,rendererSerial:f,setInteractionLock:u}=st(),h=t!=="cursor";g.useEffect(()=>(u("drawing-layer",h),()=>u("drawing-layer",!1)),[h,u]);const d=g.useMemo(()=>c.current?.getViewState(),[f]);return l?Ge.jsx(Pi,{tool:t,enabled:h,imageWidth:l.width,imageHeight:l.height,imageMpp:l.mpp,imageZoom:l.maxTierZoom,stampOptions:e,brushOptions:n,drawFillColor:r,projectorRef:c,onBrushTap:a,viewStateSignal:d,drawAreaTooltip:i,onDrawComplete:o,onPatchComplete:s}):null}function Pr(t,e,n,r){return[Math.min(t,n),Math.min(e,r),Math.max(t,n),Math.max(e,r)]}function vr(t,e){return!(t[2]<e[0]||t[0]>e[2]||t[3]<e[1]||t[1]>e[3])}class fa{constructor(e=16){E(this,"targetNodeSize");E(this,"items",[]);E(this,"globalBounds",[0,0,0,0]);E(this,"gridSize",1);E(this,"cellWidth",1);E(this,"cellHeight",1);E(this,"buckets",[]);E(this,"visited",new Uint32Array(0));E(this,"querySerial",1);const n=Number.isFinite(e)?Math.floor(e):16;this.targetNodeSize=Math.max(1,n)}load(e){if(!Array.isArray(e)||e.length===0){this.items=[],this.globalBounds=[0,0,0,0],this.gridSize=1,this.cellWidth=1,this.cellHeight=1,this.buckets=[],this.visited=new Uint32Array(0),this.querySerial=1;return}const n=[];let r=1/0,i=1/0,o=-1/0,s=-1/0;for(const f of e){if(!f||!Number.isFinite(f.minX)||!Number.isFinite(f.minY)||!Number.isFinite(f.maxX)||!Number.isFinite(f.maxY))continue;const u=Pr(f.minX,f.minY,f.maxX,f.maxY);r=Math.min(r,u[0]),i=Math.min(i,u[1]),o=Math.max(o,u[2]),s=Math.max(s,u[3]),n.push({minX:u[0],minY:u[1],maxX:u[2],maxY:u[3],value:f.value})}if(this.items=n,this.visited=new Uint32Array(n.length),this.querySerial=1,n.length===0||!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(o)||!Number.isFinite(s)){this.globalBounds=[0,0,0,0],this.gridSize=1,this.cellWidth=1,this.cellHeight=1,this.buckets=[];return}this.globalBounds=[r,i,o,s],this.gridSize=Math.max(1,Math.ceil(Math.sqrt(n.length/this.targetNodeSize)));const a=Math.max(0,o-r),l=Math.max(0,s-i);this.cellWidth=a>0?a/this.gridSize:1,this.cellHeight=l>0?l/this.gridSize:1;const c=this.gridSize*this.gridSize;this.buckets=Array.from({length:c},()=>[]);for(let f=0;f<n.length;f+=1){const u=n[f],h=this.toCellX(u.minX),d=this.toCellX(u.maxX),m=this.toCellY(u.minY),p=this.toCellY(u.maxY);for(let b=m;b<=p;b+=1)for(let y=h;y<=d;y+=1)this.buckets[b*this.gridSize+y].push(f)}}search(e){if(this.items.length===0)return[];if(!Array.isArray(e)||e.length<4)return[];const n=Pr(e[0],e[1],e[2],e[3]);if(!vr(n,this.globalBounds))return[];const r=this.toCellX(n[0]),i=this.toCellX(n[2]),o=this.toCellY(n[1]),s=this.toCellY(n[3]),a=this.nextSerial(),l=[];for(let c=o;c<=s;c+=1)for(let f=r;f<=i;f+=1){const u=this.buckets[c*this.gridSize+f];if(!(!u||u.length===0))for(const h of u){if(this.visited[h]===a)continue;this.visited[h]=a;const d=this.items[h];vr(n,[d.minX,d.minY,d.maxX,d.maxY])&&l.push(d)}}return l}nextSerial(){return this.querySerial+=1,this.querySerial===4294967295&&(this.visited.fill(0),this.querySerial=1),this.querySerial}toCellX(e){const n=this.globalBounds[0],r=this.globalBounds[2];if(this.gridSize<=1||r<=n)return 0;const i=(e-n)/this.cellWidth;return!Number.isFinite(i)||i<=0?0:i>=this.gridSize-1?this.gridSize-1:Math.max(0,Math.min(this.gridSize-1,Math.floor(i)))}toCellY(e){const n=this.globalBounds[1],r=this.globalBounds[3];if(this.gridSize<=1||r<=n)return 0;const i=(e-n)/this.cellHeight;return!Number.isFinite(i)||i<=0?0:i>=this.gridSize-1?this.gridSize-1:Math.max(0,Math.min(this.gridSize-1,Math.floor(i)))}}function Ti(t){return new fa(t)}const ha=`#version 300 es
|
|
34
34
|
precision highp float;
|
|
35
35
|
in vec2 aCenter;
|
|
36
36
|
in float aWeight;
|
|
@@ -100,7 +100,7 @@ void main() {
|
|
|
100
100
|
float alpha = gradientColor.a * clamp(uOpacity, 0.0, 1.0);
|
|
101
101
|
if (alpha <= 0.0001) discard;
|
|
102
102
|
outColor = vec4(gradientColor.rgb * alpha, alpha);
|
|
103
|
-
}`;class pa{constructor(){E(this,"canvas");E(this,"gl");E(this,"accumProgram");E(this,"colorProgram");E(this,"accumVao");E(this,"colorVao");E(this,"pointBuffer");E(this,"quadBuffer");E(this,"accumTexture");E(this,"gradientTexture");E(this,"framebuffer");E(this,"accumInternalFormat");E(this,"accumTextureFormat");E(this,"accumTextureType");E(this,"uAccumResolution");E(this,"uAccumPointSize");E(this,"uAccumCoreRatio");E(this,"uAccumPointAlpha");E(this,"uColorAccumTexture");E(this,"uColorGradientTexture");E(this,"uColorOpacity");E(this,"uColorCutoff");E(this,"uColorGain");E(this,"uColorResolution");E(this,"uColorGamma");E(this,"uColorBias");E(this,"uColorStretch");E(this,"pointCapacity",0);E(this,"interleavedCapacity",0);E(this,"interleavedBuffer",null);E(this,"gradientKey","");this.canvas=document.createElement("canvas");const e=this.canvas.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,preserveDrawingBuffer:!0,premultipliedAlpha:!0,powerPreference:"high-performance"});if(!e)throw new Error("WebGL2 is not available for heatmap rendering.");this.gl=e;const r=!!e.getExtension("EXT_color_buffer_float");this.accumInternalFormat=r?e.RGBA16F:e.RGBA8,this.accumTextureFormat=e.RGBA,this.accumTextureType=r?e.HALF_FLOAT:e.UNSIGNED_BYTE,this.accumProgram=xt(e,ha,da),this.colorProgram=xt(e,ma,ga);const i=e.createVertexArray(),o=e.createVertexArray(),s=e.createBuffer(),a=e.createBuffer(),l=e.createTexture(),c=e.createTexture(),f=e.createFramebuffer();if(!i||!o||!s||!a||!l||!c||!f)throw new Error("Failed to allocate heatmap WebGL resources.");this.accumVao=i,this.colorVao=o,this.pointBuffer=s,this.quadBuffer=a,this.accumTexture=l,this.gradientTexture=c,this.framebuffer=f;const u=e.getUniformLocation(this.accumProgram,"uResolution"),h=e.getUniformLocation(this.accumProgram,"uPointSize"),d=e.getUniformLocation(this.accumProgram,"uCoreRatio"),m=e.getUniformLocation(this.accumProgram,"uPointAlpha"),p=e.getUniformLocation(this.colorProgram,"uAccumTexture"),b=e.getUniformLocation(this.colorProgram,"uGradientTexture"),y=e.getUniformLocation(this.colorProgram,"uOpacity"),x=e.getUniformLocation(this.colorProgram,"uCutoff"),M=e.getUniformLocation(this.colorProgram,"uGain"),S=e.getUniformLocation(this.colorProgram,"uGamma"),C=e.getUniformLocation(this.colorProgram,"uBias"),A=e.getUniformLocation(this.colorProgram,"uStretch"),k=e.getUniformLocation(this.colorProgram,"uResolution");if(!u||!h||!d||!m||!p||!b||!y||!x||!M||!S||!C||!A||!k)throw new Error("Failed to resolve heatmap WebGL uniforms.");this.uAccumResolution=u,this.uAccumPointSize=h,this.uAccumCoreRatio=d,this.uAccumPointAlpha=m,this.uColorAccumTexture=p,this.uColorGradientTexture=b,this.uColorOpacity=y,this.uColorCutoff=x,this.uColorGain=M,this.uColorGamma=S,this.uColorBias=C,this.uColorStretch=A,this.uColorResolution=k,e.bindVertexArray(this.accumVao),e.bindBuffer(e.ARRAY_BUFFER,this.pointBuffer),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const U=e.getAttribLocation(this.accumProgram,"aCenter"),Y=e.getAttribLocation(this.accumProgram,"aWeight");if(U<0||Y<0)throw new Error("Failed to resolve heatmap WebGL attributes.");e.enableVertexAttribArray(U),e.vertexAttribPointer(U,2,e.FLOAT,!1,12,0),e.enableVertexAttribArray(Y),e.vertexAttribPointer(Y,1,e.FLOAT,!1,12,8),e.bindVertexArray(null),e.bindVertexArray(this.colorVao),e.bindBuffer(e.ARRAY_BUFFER,this.quadBuffer),e.bufferData(e.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,1,1]),e.STATIC_DRAW);const P=e.getAttribLocation(this.colorProgram,"aPosition");if(P<0)throw new Error("Failed to resolve heatmap color position attribute.");e.enableVertexAttribArray(P),e.vertexAttribPointer(P,2,e.FLOAT,!1,8,0),e.bindVertexArray(null),e.bindBuffer(e.ARRAY_BUFFER,null),e.bindTexture(e.TEXTURE_2D,this.accumTexture),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.bindTexture(e.TEXTURE_2D,null),e.bindTexture(e.TEXTURE_2D,this.gradientTexture),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.bindTexture(e.TEXTURE_2D,null),this.ensureCanvasSize(1,1)}render(e){if(e.count<=0||e.width<=0||e.height<=0)return!1;this.ensureCanvasSize(e.width,e.height),this.ensureGradientTexture(e.gradient),this.uploadPointData(e.positions,e.weights,e.count);const n=this.gl;return n.disable(n.SCISSOR_TEST),n.disable(n.DEPTH_TEST),n.disable(n.CULL_FACE),n.bindFramebuffer(n.FRAMEBUFFER,this.framebuffer),n.viewport(0,0,e.width,e.height),n.clearColor(0,0,0,0),n.clear(n.COLOR_BUFFER_BIT),n.useProgram(this.accumProgram),n.bindVertexArray(this.accumVao),n.uniform2f(this.uAccumResolution,e.width,e.height),n.uniform1f(this.uAccumPointSize,Math.max(1,(e.kernelRadiusPx+e.blurRadiusPx)*2)),n.uniform1f(this.uAccumCoreRatio,e.kernelRadiusPx/Math.max(1e-6,e.kernelRadiusPx+e.blurRadiusPx)),n.uniform1f(this.uAccumPointAlpha,Math.max(0,e.pointAlpha)),n.enable(n.BLEND),n.blendEquation(n.FUNC_ADD),n.blendFuncSeparate(n.ONE,n.ONE,n.ONE,n.ONE),n.drawArrays(n.POINTS,0,e.count),n.disable(n.BLEND),n.bindVertexArray(null),n.bindFramebuffer(n.FRAMEBUFFER,null),n.viewport(0,0,e.width,e.height),n.clearColor(0,0,0,0),n.clear(n.COLOR_BUFFER_BIT),n.useProgram(this.colorProgram),n.bindVertexArray(this.colorVao),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,this.accumTexture),n.uniform1i(this.uColorAccumTexture,0),n.activeTexture(n.TEXTURE1),n.bindTexture(n.TEXTURE_2D,this.gradientTexture),n.uniform1i(this.uColorGradientTexture,1),n.uniform1f(this.uColorOpacity,e.opacity),n.uniform1f(this.uColorCutoff,e.cutoff??.008),n.uniform1f(this.uColorGain,e.gain??2.6),n.uniform1f(this.uColorGamma,e.gamma??1),n.uniform1f(this.uColorBias,e.bias??0),n.uniform1f(this.uColorStretch,e.stretch??1),n.uniform2f(this.uColorResolution,e.width,e.height),n.drawArrays(n.TRIANGLE_STRIP,0,4),n.bindVertexArray(null),n.bindTexture(n.TEXTURE_2D,null),n.flush(),!0}destroy(){const e=this.gl;e.deleteTexture(this.accumTexture),e.deleteTexture(this.gradientTexture),e.deleteFramebuffer(this.framebuffer),e.deleteBuffer(this.pointBuffer),e.deleteBuffer(this.quadBuffer),e.deleteVertexArray(this.accumVao),e.deleteVertexArray(this.colorVao),e.deleteProgram(this.accumProgram),e.deleteProgram(this.colorProgram),this.canvas.width=0,this.canvas.height=0}ensureCanvasSize(e,n){const r=Math.max(1,Math.round(e)),i=Math.max(1,Math.round(n));this.canvas.width!==r&&(this.canvas.width=r),this.canvas.height!==i&&(this.canvas.height=i);const o=this.gl;o.bindTexture(o.TEXTURE_2D,this.accumTexture),o.texImage2D(o.TEXTURE_2D,0,this.accumInternalFormat,r,i,0,this.accumTextureFormat,this.accumTextureType,null),o.bindFramebuffer(o.FRAMEBUFFER,this.framebuffer),o.framebufferTexture2D(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,this.accumTexture,0);const s=o.checkFramebufferStatus(o.FRAMEBUFFER);if(o.bindFramebuffer(o.FRAMEBUFFER,null),s!==o.FRAMEBUFFER_COMPLETE)throw new Error(`Heatmap framebuffer incomplete: ${s}`)}ensureGradientTexture(e){const n=e.join("|");if(this.gradientKey===n)return;const r=document.createElement("canvas");r.width=256,r.height=1;const i=r.getContext("2d");if(!i)throw new Error("Failed to create heatmap gradient canvas.");const o=i.createLinearGradient(0,0,256,0),s=e.length>1?e:["#00000000","#3876FF","#4CDDDD","#FFE75C","#FF8434","#FF3434"],a=1/Math.max(1,s.length-1);for(let f=0;f<s.length;f+=1)o.addColorStop(f*a,s[f]);i.clearRect(0,0,256,1),i.fillStyle=o,i.fillRect(0,0,256,1);const l=i.getImageData(0,0,256,1).data,c=this.gl;c.bindTexture(c.TEXTURE_2D,this.gradientTexture),c.texImage2D(c.TEXTURE_2D,0,c.RGBA,256,1,0,c.RGBA,c.UNSIGNED_BYTE,l),c.bindTexture(c.TEXTURE_2D,null),this.gradientKey=n}uploadPointData(e,n,r){const i=this.gl,o=r*3,s=o*4;i.bindBuffer(i.ARRAY_BUFFER,this.pointBuffer),r>this.pointCapacity&&(i.bufferData(i.ARRAY_BUFFER,s,i.DYNAMIC_DRAW),this.pointCapacity=r),o>this.interleavedCapacity&&(this.interleavedCapacity=o,this.interleavedBuffer=new Float32Array(o));const a=this.interleavedBuffer;if(!a)throw new Error("Failed to allocate heatmap upload buffer.");for(let l=0;l<r;l+=1){const c=l*2,f=l*3;a[f]=e[c]??0,a[f+1]=e[c+1]??0,a[f+2]=n[l]??0}i.bufferSubData(i.ARRAY_BUFFER,0,a.subarray(0,o)),i.bindBuffer(i.ARRAY_BUFFER,null)}}const Tr="__open_plant_heatmap_layer__",ya=["#00000000","#3876FF","#4CDDDD","#FFE75C","#FF8434","#FF3434"],ba=3,xa=2,wa=.9,Sa=52e3,Ea="screen",Ra=2.2,An=128,en=1600,Ma=1.9,Aa=4.2,Cn=3e3,Ii=Math.SQRT2,Ca=2048,Pa=.9,He=16;function Pt(t,e){return e.maxTierZoom+Math.log2(Math.max(1e-6,t))}function Vn(t,e){return Math.max(1e-6,2**(t-e.maxTierZoom))}function va(t,e,n){if(!Number.isFinite(n)||Math.abs(n)<1e-6)return Math.max(1e-6,t);const r=Pt(t,e)-n;return Vn(r,e)}function Ta(t){return!Number.isFinite(t)||Math.abs(t)<1e-6?0:Math.round(t*1.5/Math.max(1e-6,Math.log2(Ii)))}function _i(t){const e=_(t,0,He);return _(.55+Math.sqrt(Math.max(0,e))*.48,.55,6)}function Ia(t){const e=Math.max(0,t);return e<=1?.18:e<=2?.3:e<=4?.48:e<=8?.7:e<=16?.86:1}function Fi(t){return .022-_(t,0,He)/He*.015}function Li(t){const e=_(t,0,He);return .18+Math.pow(Math.max(0,e),.72)*.42+Math.log2(e+1)*.24}function Di(t){return _i(t)}function Ni(t){const n=_(t,0,He)/He;return _(.46-n*.34,.12,.46)}function zi(t,e,n){const i=_(t,0,He)/He,o=Pt(e,n),s=n.maxTierZoom-3.2,a=n.maxTierZoom-1.15,l=_((o-s)/Math.max(1e-6,a-s),0,1),c=1.12+Math.pow(i,.82)*1.18,f=1+l*(.48+i*.92);return c*f}function _a(t,e,n){const r=Math.max(0,t),i=Math.max(1e-6,e),o=Math.log1p(r)/Math.log1p(i);return _(o,0,1)}function Fa(t){return Pa}function La(t,e){if(t.length===0)return 1;const n=Math.min(t.length,Ca),r=new Array(n);let i=1;for(let f=0;f<n;f+=1){const u=Math.min(t.length-1,Math.floor((f+.5)*t.length/n)),h=Math.max(0,t[u]?.weight??0);r[f]=h,h>i&&(i=h)}for(let f=0;f<t.length;f+=1){const u=Math.max(0,t[f]?.weight??0);u>i&&(i=u)}r.sort((f,u)=>f-u);const o=Fa(),s=Math.max(0,Math.min(r.length-1,Math.floor((r.length-1)*o))),a=r[s]??i;return Math.max(1,Math.min(i,Math.max(a*1.08,i*.14)))}function Bi(t,e,n){const r=Pt(t,e),i=e.maxTierZoom-2.45,o=e.maxTierZoom-1.2,s=r<=i?1:r>=o?0:(()=>{const a=_((r-i)/Math.max(1e-6,o-i),0,1);return 1-a*a*(3-2*a)})();return _(s,0,1)}function Da(t){if(t>=1)return 1;const e=1/Math.max(t,1e-6);return 1+Math.log2(e)*.28}function Na(t,e,n,r){const i=Math.max(1,t,e),o=typeof window>"u"?1:_(window.devicePixelRatio||1,1,2.4),s=r<=.35?1.42:r<=.55?1.26:r<=.8?1.14:1,a=n>16e4?896:n>8e4?1152:n>3e4?1408:en,l=An/i,c=en/i;return _(a*o*s/i,l,c)}function Pn(t){const e=t.heatmapScale??Na(t.logicalWidth,t.logicalHeight,t.totalPointCount,t.rawZoom),n=Math.max(An,Math.min(en,Math.round(t.logicalWidth*e))),r=Math.max(An,Math.min(en,Math.round(t.logicalHeight*e))),i=n/Math.max(1,t.logicalWidth),o=r/Math.max(1,t.logicalHeight),s=Math.min(i,o),a=Math.max(1e-6,t.rawZoom),l=Math.max(.75,t.radius*Ma*s),c=Math.max(.6,t.blur*Aa*s),f=(l+c)/Math.max(1e-6,a*s),u=Math.max(f*.4,.62/Math.max(1e-6,a*s));return{heatmapScale:e,rasterWidth:n,rasterHeight:r,rasterScaleX:i,rasterScaleY:o,rawZoom:a,kernelRadiusPx:l,blurRadiusPx:c,outerWorldRadius:f,desiredCellWorldSize:u}}function Gn(t){if(!t)return 0;const e=Math.floor(t.positions.length/2),n=t.weights?t.weights.length:Number.MAX_SAFE_INTEGER;return Math.max(0,Math.min(Math.floor(t.count),e,n))}function Dt(t,e){const n=Number.isFinite(t)?Math.round(t*1024):0;return Math.imul(e^n,73244475)>>>0}function za(t,e,n=2654435769){let r=Math.imul(n^(t|0),2246822507)>>>0;return r=Math.imul(r^(e|0),3266489909)>>>0,r^=r>>>16,r>>>0}function Ba(t){return(t>>>0)/4294967295}function ki(t){let e=2166136261;for(let n=0;n<t.length;n+=1){const r=t[n];e=Math.imul(e^r.outer.length,16777619)>>>0;for(let i=0;i<r.outer.length;i+=1){const o=r.outer[i];e=Dt(o[0],e),e=Dt(o[1],e)}e=Math.imul(e^r.holes.length,16777619)>>>0;for(let i=0;i<r.holes.length;i+=1){const o=r.holes[i];e=Math.imul(e^o.length,16777619)>>>0;for(let s=0;s<o.length;s+=1){const a=o[s];e=Dt(a[0],e),e=Dt(a[1],e)}}}return`${t.length}:${e>>>0}`}function Zn(t,e,n){return t.dataRef===e&&t.clipKey===n?!0:e?t.clipKey===n&&t.inputCount===Gn(e)&&t.positionsRef===e.positions&&t.weightsRef===e.weights:!1}function ka(t,e,n,r){const i=Gn(t);if(!t||i<=0)return null;let o=new Float32Array(i),s=new Float32Array(i),a=new Float32Array(i),l=0,c=1/0,f=1/0,u=-1/0,h=-1/0;for(let M=0;M<i;M+=1){const S=t.positions[M*2],C=t.positions[M*2+1];if(!Number.isFinite(S)||!Number.isFinite(C)||e.length>0&&!Et(S,C,e))continue;const A=t.weights?.[M],k=typeof A=="number"&&Number.isFinite(A)?Math.max(0,A):1;k<=0||(o[l]=S,s[l]=C,a[l]=k,l+=1,S<c&&(c=S),S>u&&(u=S),C<f&&(f=C),C>h&&(h=C))}if(l===0||!Number.isFinite(c)||!Number.isFinite(f)||!Number.isFinite(u)||!Number.isFinite(h))return null;l<i&&(o=o.slice(0,l),s=s.slice(0,l),a=a.slice(0,l));const d=[];for(let M=0;M<l;M+=1){const S=o[M],C=s[M];d.push({minX:S,minY:C,maxX:S,maxY:C,value:M})}const m=Ti(64);m.load(d);const p=Math.max(r?.width??0,r?.height??0,u-c,h-f,1),b=[];let y=.5,x=0;for(;y<=p&&x<32;)b.push(y),y*=Ii,x+=1;return b.length===0&&b.push(1),{dataRef:t,sourceRef:r,positionsRef:t.positions,weightsRef:t.weights,inputCount:i,clipRef:e,clipKey:n,pointCount:l,xs:o,ys:s,ws:a,pointIndex:m,cellSizes:b,levels:Array.from({length:b.length},()=>null)}}function vn(t,e,n){const r=t.pointIndex.search([e[0]-n,e[1]-n,e[2]+n,e[3]+n]),i=new Array(r.length);let o=0;for(let s=0;s<r.length;s+=1){const a=r[s];a&&(i[o]=a.value,o+=1)}return i.length=o,i}function Ui(t,e){const n=Math.max(Cn,e);return t<=n?1:_(n/Math.max(1,t),1/65536,1)}function Oi(t){return t>=1?1:Math.max(1,Math.round(1/Math.max(1e-6,t)))}function Ua(t,e){if(e>=1)return!0;const n=za(t,1374496523,1757159915);return Ba(n)<=_(e,0,1)}function Wi(t,e,n,r){const i=Math.max(1,n*r),o=Math.PI*e*e,s=Math.max(1,t)*o/i;return _(.085/Math.sqrt(Math.max(1,s)),.012,.075)}function Ir(t,e,n,r){if(!Number.isFinite(t)||t<=0)return e;const i=e>=t?n:r;return t+(e-t)*_(i,0,1)}function Oa(t){if(t.webgl!==void 0)return t.webgl;if(typeof document>"u")return t.webgl=null,null;try{t.webgl=new pa}catch(e){if(!t.webglWarningIssued&&typeof console<"u"&&typeof console.warn=="function"){const n=e instanceof Error?e.message:String(e);console.warn(`[open-plant] HeatmapLayer disabled because WebGL2 heatmap initialization failed: ${n}`),t.webglWarningIssued=!0}t.webgl=null}return t.webgl}function _r(t,e){const n=[];for(let r=0;r<e.length;r+=1){const i=e[r];if(!i)continue;const o=t.worldToScreen(i[0],i[1]);if(!Array.isArray(o)||o.length<2)continue;const s=Number(o[0]),a=Number(o[1]);!Number.isFinite(s)||!Number.isFinite(a)||n.push([s,a])}return n}function Wa(t,e,n){if(n.length!==0){t.beginPath();for(let r=0;r<n.length;r+=1){const i=n[r],o=_r(e,i.outer);o.length>=3&&Rt(t,o,!0);for(let s=0;s<i.holes.length;s+=1){const a=_r(e,i.holes[s]);a.length>=3&&Rt(t,a,!0)}}t.clip("evenodd")}}function Yi(t,e,n,r,i){const o=t.sourceData;return o&&o.sourceRef===i&&Zn(o,e,r)?o:(t.sourceData=ka(e,n,r,i),t.fixedState=null,t.screenLevelIndex=-1,t.sourceData)}function Ya(t){const{sourceData:e,renderer:n,source:r,logicalWidth:i,logicalHeight:o,radius:s,blur:a,fixedZoom:l,maxRenderedPoints:c}=t,f=Math.max(1e-6,n.getViewState().zoom),u=l??Pt(f,r),h=Vn(u,r),d=Pn({logicalWidth:i,logicalHeight:o,totalPointCount:e.pointCount,rawZoom:h,radius:s,blur:a}),m=n.getViewBounds(),p=vn(e,m,d.outerWorldRadius),b=Ui(p.length,c),y=Oi(b),x=Math.min(d.rasterScaleX,d.rasterScaleY);return{dataRef:e.dataRef,positionsRef:e.positionsRef,weightsRef:e.weightsRef,inputCount:e.inputCount,clipRef:e.clipRef,clipKey:e.clipKey,referenceZoom:u,referenceRawZoom:h,heatmapScale:d.heatmapScale,kernelWorldRadius:d.kernelRadiusPx/Math.max(1e-6,h*x),blurWorldRadius:d.blurRadiusPx/Math.max(1e-6,h*x),sampleProbability:b,sampleStride:y,pointAlpha:Wi(p.length,d.kernelRadiusPx+d.blurRadiusPx,d.rasterWidth,d.rasterHeight)}}function Fr(t){const{ctx:e,runtime:n,renderer:r,source:i,logicalWidth:o,logicalHeight:s,frame:a,sourceData:l,visiblePointIndices:c,sampleProbability:f,sampleStride:u,pointAlpha:h,gradient:d,opacity:m,densityContrast:p,backgroundColor:b,clipPolygons:y}=t,x=Oa(n);if(!x||c.length===0)return 0;const M=Math.min(c.length,Math.max(64,Math.ceil(c.length*Math.min(1,f*1.15))));M>n.webglCapacity&&(n.webglCapacity=M,n.webglPositions=new Float32Array(M*2),n.webglWeights=new Float32Array(M));const S=n.webglPositions,C=n.webglWeights;if(!S||!C)return 0;const A=a.kernelRadiusPx+a.blurRadiusPx,k=Da(f);let U=0;for(let P=0;P<c.length;P+=1){const T=c[P];if(!Ua(T,f))continue;const L=l.xs[T],F=l.ys[T];if(!Number.isFinite(L)||!Number.isFinite(F))continue;const W=r.worldToScreen(L,F);if(!Array.isArray(W)||W.length<2)continue;const $=Number(W[0]),z=Number(W[1]);if(!Number.isFinite($)||!Number.isFinite(z))continue;const ae=$*a.rasterScaleX,de=z*a.rasterScaleY;if(ae<-A||de<-A||ae>a.rasterWidth+A||de>a.rasterHeight+A)continue;const J=U*2;S[J]=ae,S[J+1]=de,C[U]=Math.max(0,(l.ws[T]??0)*k),U+=1}return U<=0||!x.render({width:a.rasterWidth,height:a.rasterHeight,positions:S,weights:C,count:U,kernelRadiusPx:a.kernelRadiusPx,blurRadiusPx:a.blurRadiusPx,pointAlpha:h,gradient:d,opacity:m,cutoff:Fi(p),gain:Li(p),gamma:Di(p),bias:Ni(p),stretch:zi(p,a.rawZoom,i)})?0:(e.save(),y.length>0&&Wa(e,r,y),b&&(e.fillStyle=b,e.fillRect(0,0,o,s)),e.globalAlpha=1,e.imageSmoothingEnabled=!0,e.drawImage(x.canvas,0,0,a.rasterWidth,a.rasterHeight,0,0,o,s),e.restore(),U)}function Xa(t){const{ctx:e,runtime:n,renderer:r,source:i,logicalWidth:o,logicalHeight:s,state:a}=t,l=Yi(n,a.data,a.clipPolygons,a.clipKey,i);if(!l||l.cellSizes.length===0||l.pointCount<=0)return null;const c=Math.max(1e-6,r.getViewState().zoom),f=Bi(c,i,a.zoomThreshold),u=r.getViewBounds();if(f<=.001)return{pointCount:l.pointCount,renderTimeMs:0,visiblePointCount:0,renderedBinCount:0,sampleStride:1,maxDensity:0};if(a.scaleMode!=="fixed-zoom"){const y=Pn({logicalWidth:o,logicalHeight:s,totalPointCount:l.pointCount,rawZoom:c,radius:a.radius,blur:a.blur}),x=vn(l,u,y.outerWorldRadius);if(x.length===0)return{pointCount:l.pointCount,renderTimeMs:0,visiblePointCount:0,renderedBinCount:0,sampleStride:1,maxDensity:0};const M=Ui(x.length,a.maxRenderedPoints),S=Oi(M),C=Wi(x.length,y.kernelRadiusPx+y.blurRadiusPx,y.rasterWidth,y.rasterHeight);n.screenLevelIndex=-1,n.screenSecondaryLevelIndex=-1,n.screenSecondaryLevelWeight=0,n.screenNormalizationMaxWeight=1,n.screenPointAlpha=Ir(n.screenPointAlpha,C,.12,.08),n.screenVisibilityStrength=r.isViewAnimating()?Ir(n.screenVisibilityStrength,f,.16,.12):f;const A=Fr({ctx:e,runtime:n,renderer:r,source:i,logicalWidth:o,logicalHeight:s,frame:y,sourceData:l,visiblePointIndices:x,sampleProbability:M,sampleStride:S,pointAlpha:n.screenPointAlpha*Math.max(.08,n.screenVisibilityStrength),gradient:a.gradient,opacity:a.opacity*n.screenVisibilityStrength,densityContrast:a.densityContrast,backgroundColor:a.backgroundColor,clipPolygons:a.clipPolygons});return{pointCount:l.pointCount,renderTimeMs:0,visiblePointCount:x.length,renderedBinCount:A,sampleStride:S,maxDensity:Math.round(n.screenPointAlpha*255)}}const h=n.fixedState;if(!h)return null;const d=Pn({logicalWidth:o,logicalHeight:s,totalPointCount:l.pointCount,rawZoom:c,radius:a.radius,blur:a.blur,heatmapScale:h.heatmapScale}),m=Math.min(d.rasterScaleX,d.rasterScaleY);d.kernelRadiusPx=Math.max(.75,h.kernelWorldRadius*c*m),d.blurRadiusPx=Math.max(.6,h.blurWorldRadius*c*m),d.outerWorldRadius=h.kernelWorldRadius+h.blurWorldRadius;const p=vn(l,u,d.outerWorldRadius);if(p.length===0)return{pointCount:l.pointCount,renderTimeMs:0,visiblePointCount:0,renderedBinCount:0,sampleStride:1,maxDensity:0};n.screenPointAlpha=h.pointAlpha,n.screenVisibilityStrength=f;const b=Fr({ctx:e,runtime:n,renderer:r,source:i,logicalWidth:o,logicalHeight:s,frame:d,sourceData:l,visiblePointIndices:p,sampleProbability:h.sampleProbability,sampleStride:h.sampleStride,pointAlpha:h.pointAlpha*Math.max(.08,f),gradient:a.gradient,opacity:a.opacity*f,densityContrast:a.densityContrast,backgroundColor:a.backgroundColor,clipPolygons:a.clipPolygons});return{pointCount:l.pointCount,renderTimeMs:0,visiblePointCount:p.length,renderedBinCount:b,sampleStride:h.sampleStride,maxDensity:Math.round(h.pointAlpha*255)}}function Va({data:t,visible:e=!0,opacity:n=wa,radius:r=ba,blur:i=xa,gradient:o=ya,backgroundColor:s=null,scaleMode:a=Ea,fixedZoom:l,zoomThreshold:c=0,densityContrast:f=Ra,clipToRegions:u,zIndex:h=5,maxRenderedPoints:d=Sa,onStats:m}){const{rendererRef:p,source:b,registerDrawCallback:y,unregisterDrawCallback:x,requestOverlayRedraw:M}=st(),S=g.useMemo(()=>{const U=(u??[]).map(Y=>dt(Y?.coordinates)).filter(Y=>Y!=null);return mt(U)},[u]),C=g.useMemo(()=>ki(S),[S]),A=g.useRef({sourceData:null,fixedState:null,screenLevelIndex:-1,screenSecondaryLevelIndex:-1,screenSecondaryLevelWeight:0,screenPointAlpha:0,screenNormalizationMaxWeight:1,screenVisibilityStrength:1,webgl:void 0,webglWarningIssued:!1,webglPositions:null,webglWeights:null,webglCapacity:0}),k=g.useRef({data:t,visible:e,opacity:n,radius:_(r,.05,128),blur:_(i,.05,128),gradient:o,backgroundColor:s,scaleMode:a,fixedZoom:l,zoomThreshold:c,densityContrast:_(f,0,He),clipPolygons:S,clipKey:C,maxRenderedPoints:Math.max(Cn,Math.floor(d)),onStats:m});return k.current={data:t,visible:e,opacity:n,radius:_(r,.05,128),blur:_(i,.05,128),gradient:o,backgroundColor:s,scaleMode:a,fixedZoom:l,zoomThreshold:c,densityContrast:_(f,0,He),clipPolygons:S,clipKey:C,maxRenderedPoints:Math.max(Cn,Math.floor(d)),onStats:m},g.useEffect(()=>(y(Tr,h,(Y,P,T)=>{const L=k.current,F=A.current,W=p.current;if(!L.visible||!L.data||!W||!b)return;const $=Yi(F,L.data,L.clipPolygons,L.clipKey,b);if(!$)return;L.scaleMode==="fixed-zoom"&&(!F.fixedState||!Zn(F.fixedState,L.data,L.clipKey)||L.fixedZoom!==void 0&&Math.abs(F.fixedState.referenceZoom-L.fixedZoom)>1e-6)?F.fixedState=Ya({sourceData:$,renderer:W,source:b,logicalWidth:P,logicalHeight:T,radius:L.radius,blur:L.blur,fixedZoom:L.fixedZoom,zoomThreshold:L.zoomThreshold,densityContrast:L.densityContrast,maxRenderedPoints:L.maxRenderedPoints}):L.scaleMode!=="fixed-zoom"&&(F.fixedState=null);const ae=performance.now(),de=Xa({ctx:Y,runtime:F,renderer:W,source:b,logicalWidth:P,logicalHeight:T,state:L});!de||!L.onStats||L.onStats({...de,renderTimeMs:performance.now()-ae})}),()=>{x(Tr),A.current.sourceData=null,A.current.fixedState=null,A.current.screenLevelIndex=-1,A.current.screenSecondaryLevelIndex=-1,A.current.screenSecondaryLevelWeight=0,A.current.screenPointAlpha=0,A.current.screenNormalizationMaxWeight=1,A.current.screenVisibilityStrength=1,A.current.webgl?.destroy(),A.current.webgl=void 0,A.current.webglPositions=null,A.current.webglWeights=null,A.current.webglCapacity=0}),[y,x,p,b,h]),g.useEffect(()=>{A.current.sourceData=null,A.current.fixedState=null,A.current.screenLevelIndex=-1,A.current.screenSecondaryLevelIndex=-1,A.current.screenSecondaryLevelWeight=0,A.current.screenPointAlpha=0,A.current.screenNormalizationMaxWeight=1,A.current.screenVisibilityStrength=1,M()},[t?.positions,t?.weights,t?.count,C,M]),g.useEffect(()=>{A.current.fixedState=null,A.current.screenSecondaryLevelIndex=-1,A.current.screenSecondaryLevelWeight=0,A.current.screenPointAlpha=0,A.current.screenNormalizationMaxWeight=1,A.current.screenVisibilityStrength=1,M()},[r,i,a,l,c,f,d,M]),g.useEffect(()=>{M()},[e,n,o,s,M]),null}const Ga={applyZoomThreshold:va,buildClipKey:ki,resolveCellSupportFactor:Ia,resolveContinuousZoom:Pt,resolveDensityCutoff:Fi,resolveDensityBias:Ni,resolveDensityGain:Li,resolveDensityGamma:Di,resolveDensityStretch:zi,resolveNormalizedDensityWeight:_a,resolveNormalizationUpperWeight:La,resolveDensityWeightExponent:_i,resolveRawZoomFromContinuousZoom:Vn,resolvePointCount:Gn,resolveThresholdLevelBias:Ta,resolveZoomVisibilityStrength:Bi,isSameHeatmapInput:Zn},Lr="__overlay_layer__";function Za({shapes:t}){const{rendererRef:e,rendererSerial:n,source:r,registerDrawCallback:i,unregisterDrawCallback:o,requestOverlayRedraw:s}=st(),a=g.useCallback(c=>{const f=e.current;if(!f||c.length===0)return[];const u=new Array(c.length);for(let h=0;h<c.length;h+=1){const d=qe(f.worldToScreen(c[h][0],c[h][1]));if(!d)return[];u[h]=d}return u},[]),l=g.useRef({shapes:t,worldToScreenPoints:a,source:r});return l.current={shapes:t,worldToScreenPoints:a,source:r},g.useEffect(()=>(i(Lr,30,f=>{const{shapes:u,worldToScreenPoints:h,source:d}=l.current;if(!Array.isArray(u)||u.length===0||!d)return;const m=h(Oe([[0,0],[d.width,0],[d.width,d.height],[0,d.height]]));Ci({ctx:f,overlayShapes:u,imageOuterRing:m,worldToScreenPoints:h,baseStrokeStyle:$e})}),()=>o(Lr)),[i,o]),g.useEffect(()=>{s()},[n,t,r,s]),null}function qa(t){return Array.isArray(t?.classes)?t.classes.map(e=>({classId:String(e?.classId??""),className:String(e?.className??""),classColor:String(e?.classColor??"")})):[]}function Dr(t){return String(t??"").replace(/\/+$/,"")}function Xi(t){const e=String(t??"");return e.startsWith("/")?e:`/${e}`}function Ha(t){const e=Dr(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=Dr(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 $a(t,e){const n=t?.imsInfo??{},r=!!t?.imsInfo,i=Number(n.width??t?.width??0),o=Number(n.height??t?.height??0),s=Number(n.tileSize??t?.tileSize??0),a=Number(n.zoom??t?.zoom??0),l=String(n.path??t?.path??""),c=Number(n.mpp??t?.mpp??0);if(!i||!o||!s||!l)throw new Error("Incomplete image metadata: width/height/tileSize/path required");const f=Xi(l),u=Ha(e),h=t?.tileUrlBuilder??(r?(d,m,p)=>`${u}${f}/${d}/${p}_${m}.webp`:void 0);return{id:t?._id||t?.id||"unknown",name:t?.name||"unknown",width:i,height:o,mpp:Number.isFinite(c)&&c>0?c:void 0,tileSize:s,maxTierZoom:Number.isFinite(a)?Math.max(0,Math.floor(a)):0,tilePath:l,tileBaseUrl:e,tileUrlBuilder:h}}function qn(t,e,n,r){if(t.tileUrlBuilder)return t.tileUrlBuilder(e,n,r,t.tilePath,t.tileBaseUrl);const i=Xi(t.tilePath);return`${t.tileBaseUrl}${i}/${e}/${r}_${n}.webp`}function Ka(t,e){if(!e)return!1;const n=new URL(t,typeof window<"u"?window.location.href:void 0).hostname.toLowerCase();return!(n.includes("amazonaws.com")||n.startsWith("s3.")||n.includes(".s3."))}const We={width:200,height:125,margin:16,position:"bottom-right",borderRadius:6,borderWidth:0,backgroundColor:"rgba(4, 10, 18, 0.88)",borderColor:"rgba(230, 244, 255, 0.35)",viewportBorderColor:"rgba(255, 106, 61, 0.95)",viewportBorderStyle:"dash",viewportFillColor:"transparent",interactive:!0,showThumbnail:!0,maxThumbnailTiles:16};function Nr(t,e,n,r){const i=e.length;if(!(i<3)){for(let o=0;o<i;o+=1){const s=e[o],a=e[(o+1)%i],l=Math.hypot(a[0]-s[0],a[1]-s[1]);if(l<1e-6)continue;const c=Math.max(1,Math.round((l+r)/(n+r))),f=c*n+(c-1)*r,u=l/Math.max(1e-6,f),h=n*u,d=r*u;t.beginPath(),t.moveTo(s[0],s[1]),t.lineTo(a[0],a[1]),t.setLineDash([h,d]),t.lineDashOffset=0,t.stroke()}t.setLineDash([]),t.lineDashOffset=0}}function zr(t,e,n=1e-4){return Math.abs(t[0]-e[0])<=n&&Math.abs(t[1]-e[1])<=n}function Br(t){const e=[];for(const n of t){const r=e[e.length-1];(!r||!zr(r,n))&&e.push(n)}return e.length>1&&zr(e[0],e[e.length-1])&&e.pop(),e}function kr(t,e,n){const r=e[0]-t[0];if(Math.abs(r)<1e-6)return[n,t[1]];const i=(n-t[0])/r;return[n,t[1]+(e[1]-t[1])*i]}function Ur(t,e,n){const r=e[1]-t[1];if(Math.abs(r)<1e-6)return[t[0],n];const i=(n-t[1])/r;return[t[0]+(e[0]-t[0])*i,n]}function Or(t,e,n,r,i){let o=Br(t);if(o.length<3)return[];const s=[{inside:a=>a[0]>=e,intersect:(a,l)=>kr(a,l,e)},{inside:a=>a[0]<=r,intersect:(a,l)=>kr(a,l,r)},{inside:a=>a[1]>=n,intersect:(a,l)=>Ur(a,l,n)},{inside:a=>a[1]<=i,intersect:(a,l)=>Ur(a,l,i)}];for(const a of s){if(o.length===0)return[];const l=o;o=[];let c=l[l.length-1],f=a.inside(c);for(const u of l){const h=a.inside(u);h?(f||o.push(a.intersect(c,u)),o.push(u)):f&&o.push(a.intersect(c,u)),c=u,f=h}o=Br(o)}return o.length>=3?o:[]}function ct(t,e,n=1){return typeof t!="number"||!Number.isFinite(t)?e:Math.max(n,t)}function Tn(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function ja(t){return t*Math.PI/180}function Qa(t,e,n){const r=Tn(n),i=ja(r),o=Math.cos(i),s=Math.sin(i),a=t*.5,l=e*.5,c=-o*a-s*l,f=s*a-o*l,u=[[0,0],[t,0],[t,e],[0,e]].map(([b,y])=>[o*b+s*y+c,-s*b+o*y+f]);let h=1/0,d=1/0,m=-1/0,p=-1/0;for(const[b,y]of u)b<h&&(h=b),b>m&&(m=b),y<d&&(d=y),y>p&&(p=y);return{cos:o,sin:s,minX:h,minY:d,width:Math.max(1e-6,m-h),height:Math.max(1e-6,p-d),translateX:c,translateY:f}}function Wr(t,e,n,r,i){const o=Qa(t,e,i),s=o.width/o.height,a=n/r;let l,c;return s>a?(l=n,c=n/s):(c=r,l=r*s),{contentX:(n-l)/2,contentY:(r-c)/2,contentWidth:l,contentHeight:c,metrics:o}}function Yr(t,e,n){const{contentX:r,contentY:i,contentWidth:o,contentHeight:s,metrics:a}=n,l=a.cos*t+a.sin*e+a.translateX-a.minX,c=-a.sin*t+a.cos*e+a.translateY-a.minY;return[r+l/a.width*o,i+c/a.height*s]}function Ja(t,e,n,r,i){const{metrics:o}=n,s=t+o.minX-o.translateX,a=e+o.minY-o.translateY,l=s*o.cos-a*o.sin,c=s*o.sin+a*o.cos;return[_(l,0,r),_(c,0,i)]}function el(t){return[[t[0],t[1]],[t[2],t[1]],[t[2],t[3]],[t[0],t[3]]]}function pt(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 tl={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 nl({source:t,projectorRef:e,authToken:n="",options:r,invalidateRef:i,className:o,style:s}){const a=g.useRef(null),l=g.useRef(null),c=g.useRef(null),f=g.useRef({active:!1,pointerId:null}),u=g.useRef(null),h=g.useRef(!1),d=ct(r?.width,We.width,64),m=ct(r?.height,We.height,48),p=ct(r?.margin,We.margin,0),b=ct(r?.borderRadius,We.borderRadius,0),y=ct(r?.borderWidth,We.borderWidth,0),x=Math.max(1,Math.round(ct(r?.maxThumbnailTiles,We.maxThumbnailTiles,1))),M=r?.backgroundColor||We.backgroundColor,S=r?.borderColor||We.borderColor,C=r?.viewportBorderColor||We.viewportBorderColor,A=r?.viewportBorderStyle==="stroke"||r?.viewportBorderStyle==="dash"?r.viewportBorderStyle:We.viewportBorderStyle,k=r?.viewportFillColor??We.viewportFillColor,U=r?.interactive??We.interactive,Y=r?.showThumbnail??We.showThumbnail,P=r?.position||We.position,T=r?.onClose,L=r?.closeIcon,F=r?.closeButtonStyle,W=g.useMemo(()=>{const D={};return P==="top-left"||P==="bottom-left"?D.left=p:D.right=p,P==="top-left"||P==="top-right"?D.top=p:D.bottom=p,{position:"absolute",...D,width:d,height:m,borderRadius:b,overflow:"hidden",zIndex:4,pointerEvents:U?"auto":"none",touchAction:"none",boxShadow:"0 10px 22px rgba(0, 0, 0, 0.3)",...s}},[p,P,d,m,b,U,s]),$=g.useCallback(()=>{const D=a.current;if(!D)return;const v=D.getContext("2d");if(!v)return;const O=d,oe=m,q=Math.max(1,window.devicePixelRatio||1),pe=Math.max(1,Math.round(O*q)),le=Math.max(1,Math.round(oe*q));(D.width!==pe||D.height!==le)&&(D.width=pe,D.height=le),v.setTransform(1,0,0,1,0,0),v.clearRect(0,0,D.width,D.height),v.setTransform(q,0,0,q,0,0),v.fillStyle=M,v.fillRect(0,0,O,oe);const ne=e.current,Fe=Tn(ne?.getInitialRotationDeg?.()),ue=Wr(t.width,t.height,O,oe,Fe),{contentX:ye,contentY:me,contentWidth:re,contentHeight:se,metrics:ce}=ue,Z=l.current;Z&&(v.save(),v.beginPath(),v.rect(ye,me,re,se),v.clip(),v.translate(ye,me),v.scale(re/ce.width,se/ce.height),v.transform(ce.cos,-ce.sin,ce.sin,ce.cos,ce.translateX-ce.minX,ce.translateY-ce.minY),v.drawImage(Z,0,0,t.width,t.height),v.restore()),v.strokeStyle=S,v.lineWidth=y,v.strokeRect(y*.5,y*.5,O-y,oe-y);const Pe=ne?.getViewBounds?.(),Ee=ne?.getViewCorners?.(),be=Array.isArray(Ee)&&Ee.length>=4&&Ee.every(j=>Array.isArray(j)&&j.length>=2&&Number.isFinite(j[0])&&Number.isFinite(j[1]))?Ee:null,V=pt(Pe)?Pe:pt(c.current)?c.current:null;pt(Pe)&&(c.current=Pe);const K=A==="dash";if(be){const j=be.map(X=>Yr(X[0],X[1],ue)),Re=Or(j,ye,me,ye+re,me+se);if(Re.length>=3){v.beginPath();for(let X=0;X<Re.length;X+=1)X===0?v.moveTo(Re[X][0],Re[X][1]):v.lineTo(Re[X][0],Re[X][1]);v.closePath(),v.fillStyle=k,v.fill(),v.strokeStyle=C,v.lineWidth=2.25,K?Nr(v,Re,4,3):v.stroke();return}}if(!V)return;const fe=el(V).map(j=>Yr(j[0],j[1],ue)),te=Or(fe,ye,me,ye+re,me+se);if(!(te.length<3)){v.beginPath();for(let j=0;j<te.length;j+=1)j===0?v.moveTo(te[j][0],te[j][1]):v.lineTo(te[j][0],te[j][1]);v.closePath(),v.fillStyle=k,v.fill(),v.strokeStyle=C,v.lineWidth=2.25,K?Nr(v,te,4,3):v.stroke()}},[d,m,M,S,y,e,t.width,t.height,k,C,A]),z=g.useCallback(()=>{h.current||(h.current=!0,u.current=requestAnimationFrame(()=>{h.current=!1,u.current=null,$()}))},[$]),ae=g.useCallback((D,v)=>{const O=a.current;if(!O)return null;const oe=O.getBoundingClientRect();if(!oe.width||!oe.height)return null;const q=e.current,pe=Tn(q?.getInitialRotationDeg?.()),le=Wr(t.width,t.height,d,m,pe),ne=oe.width/d,Fe=oe.height/m,ue=le.contentX*ne,ye=le.contentY*Fe,me=le.contentWidth*ne,re=le.contentHeight*Fe,se=_((D-oe.left-ue)/me,0,1),ce=_((v-oe.top-ye)/re,0,1);return Ja(se*le.metrics.width,ce*le.metrics.height,le,t.width,t.height)},[e,t.width,t.height,d,m]),de=g.useCallback((D,v)=>{const O=e.current;if(!O)return;if(O.setViewCenter){O.setViewCenter(D,v),z();return}const oe=O.getViewBounds?.(),q=pt(oe)?oe:pt(c.current)?c.current:null;if(!q)return;const pe=Math.max(1e-6,q[2]-q[0]),le=Math.max(1e-6,q[3]-q[1]);O.setViewState({offsetX:D-pe*.5,offsetY:v-le*.5}),z()},[e,z]),J=g.useCallback(D=>{if(!U||D.button!==0)return;const v=a.current;if(!v)return;const O=ae(D.clientX,D.clientY);O&&(D.preventDefault(),D.stopPropagation(),v.setPointerCapture(D.pointerId),f.current={active:!0,pointerId:D.pointerId},de(O[0],O[1]))},[U,ae,de]),ve=g.useCallback(D=>{const v=f.current;if(!v.active||v.pointerId!==D.pointerId)return;const O=ae(D.clientX,D.clientY);O&&(D.preventDefault(),D.stopPropagation(),de(O[0],O[1]))},[ae,de]),Ae=g.useCallback(D=>{const v=f.current;if(!v.active||v.pointerId!==D.pointerId)return;const O=a.current;if(O&&O.hasPointerCapture(D.pointerId))try{O.releasePointerCapture(D.pointerId)}catch{}f.current={active:!1,pointerId:null},z()},[z]);return g.useEffect(()=>{let D=!1;l.current=null,z();const v=0,O=2**(t.maxTierZoom-v),oe=Math.ceil(t.width/O),q=Math.ceil(t.height/O),pe=Math.max(1,Math.ceil(oe/t.tileSize)),le=Math.max(1,Math.ceil(q/t.tileSize)),ne=pe*le;if(!Y||ne>x)return;const Fe=Math.min(d/Math.max(1,t.width),m/Math.max(1,t.height)),ue=document.createElement("canvas");ue.width=Math.max(1,Math.round(t.width*Fe)),ue.height=Math.max(1,Math.round(t.height*Fe));const ye=ue.getContext("2d");if(!ye)return;ye.fillStyle=M,ye.fillRect(0,0,ue.width,ue.height);const me=[];for(let re=0;re<le;re+=1)for(let se=0;se<pe;se+=1){const ce=se*t.tileSize*O,Z=re*t.tileSize*O,Pe=Math.min((se+1)*t.tileSize,oe)*O,Ee=Math.min((re+1)*t.tileSize,q)*O;me.push({url:qn(t,v,se,re),bounds:[ce,Z,Pe,Ee]})}return Promise.allSettled(me.map(async re=>{const se=Ka(re.url,n),ce=await fetch(re.url,{headers:se?{Authorization:n}:void 0});if(!ce.ok)throw new Error(`HTTP ${ce.status}`);const Z=await createImageBitmap(await ce.blob());return{tile:re,bitmap:Z}})).then(re=>{if(D){for(const Z of re)Z.status==="fulfilled"&&Z.value.bitmap.close();return}const se=ue.width/Math.max(1,t.width),ce=ue.height/Math.max(1,t.height);for(const Z of re){if(Z.status!=="fulfilled")continue;const{tile:{bounds:Pe},bitmap:Ee}=Z.value,be=Pe[0]*se,V=Pe[1]*ce,K=Math.max(1,(Pe[2]-Pe[0])*se),fe=Math.max(1,(Pe[3]-Pe[1])*ce);ye.drawImage(Ee,be,V,K,fe),Ee.close()}l.current=ue,z()}),()=>{D=!0}},[t,n,M,d,m,Y,x,z]),g.useEffect(()=>{z()},[z]),g.useEffect(()=>{if(e.current)return;let D=0;const v=()=>{if(e.current){z();return}D=requestAnimationFrame(v)};return D=requestAnimationFrame(v),()=>cancelAnimationFrame(D)},[e,z]),g.useEffect(()=>rn(()=>z()),[z]),g.useEffect(()=>{if(i)return i.current=z,()=>{i.current===z&&(i.current=null)}},[i,z]),g.useEffect(()=>()=>{f.current={active:!1,pointerId:null},u.current!==null&&(cancelAnimationFrame(u.current),u.current=null),h.current=!1},[]),Ge.jsxs("div",{className:o,style:W,children:[Ge.jsx("canvas",{ref:a,style:{width:"100%",height:"100%",display:"block",borderRadius:"inherit"},onPointerDown:J,onPointerMove:ve,onPointerUp:Ae,onPointerCancel:Ae,onContextMenu:D=>{D.preventDefault()},onWheel:D=>{D.preventDefault(),D.stopPropagation()}}),T&&Ge.jsx("button",{type:"button","aria-label":"Hide overview map",onClick:D=>{D.stopPropagation(),T()},style:F?{...F}:{...tl},children:L??"×"})]})}const Xr="__patch_layer__",rl=[];function il({regions:t,strokeStyle:e}){const{rendererRef:n,registerDrawCallback:r,unregisterDrawCallback:i,requestOverlayRedraw:o}=st(),s=t??rl,a=g.useMemo(()=>Ke(yi,e),[e]),l=g.useMemo(()=>{const u=[];for(let h=0;h<s.length;h+=1){const d=s[h],m=Jt(d.coordinates);m.length!==0&&u.push({region:d,regionIndex:h,regionKey:d.id??h,polygons:m})}return u},[s]),c=g.useCallback(u=>{const h=n.current;if(!h||u.length===0)return[];const d=new Array(u.length);for(let m=0;m<u.length;m+=1){const p=qe(h.worldToScreen(u[m][0],u[m][1]));if(!p)return[];d[m]=p}return d},[]),f=g.useRef({prepared:l,resolvedStrokeStyle:a,worldToScreenPoints:c});return f.current={prepared:l,resolvedStrokeStyle:a,worldToScreenPoints:c},g.useEffect(()=>(r(Xr,20,h=>{const{prepared:d,resolvedStrokeStyle:m,worldToScreenPoints:p}=f.current;for(const b of d)for(const y of b.polygons){const x=p(y.outer);x.length>=4&&ke(h,x,m,!0,!1);for(const M of y.holes){const S=p(M);S.length>=4&&ke(h,S,m,!0,!1)}}}),()=>i(Xr)),[r,i]),g.useEffect(()=>{o()},[l,a,o]),null}function Mt(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return null;const n=mt(e??[]);if(n.length===0){const m={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return t.fillModes instanceof Uint8Array&&(m.fillModes=new Uint8Array(0)),t.ids instanceof Uint32Array&&(m.ids=new Uint32Array(0)),m}const r=ot(t),i=t.positions,o=t.paletteIndices,s=t.fillModes instanceof Uint8Array&&t.fillModes.length>=r?t.fillModes:null,a=t.ids instanceof Uint32Array&&t.ids.length>=r?t.ids:null,l=new Float32Array(r*2),c=new Uint16Array(r),f=s?new Uint8Array(r):null,u=a?new Uint32Array(r):null;let h=0;for(let m=0;m<r;m+=1){const p=i[m*2],b=i[m*2+1];Et(p,b,n)&&(l[h*2]=p,l[h*2+1]=b,c[h]=o[m],f&&(f[h]=s[m]),u&&(u[h]=a[m]),h+=1)}const d={count:h,positions:l.subarray(0,h*2),paletteIndices:c.subarray(0,h)};return f&&(d.fillModes=f.subarray(0,h)),u&&(d.ids=u.subarray(0,h)),d}function Vi(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return new Uint32Array(0);const n=mt(e??[]);if(n.length===0)return new Uint32Array(0);const r=ot(t);if(r===0)return new Uint32Array(0);const i=t.positions,o=new Uint32Array(r);let s=0;for(let a=0;a<r;a+=1){const l=i[a*2],c=i[a*2+1];Et(l,c,n)&&(o[s]=a,s+=1)}return o.subarray(0,s)}let Nt=null;const ol=`
|
|
103
|
+
}`;class pa{constructor(){E(this,"canvas");E(this,"gl");E(this,"accumProgram");E(this,"colorProgram");E(this,"accumVao");E(this,"colorVao");E(this,"pointBuffer");E(this,"quadBuffer");E(this,"accumTexture");E(this,"gradientTexture");E(this,"framebuffer");E(this,"accumInternalFormat");E(this,"accumTextureFormat");E(this,"accumTextureType");E(this,"uAccumResolution");E(this,"uAccumPointSize");E(this,"uAccumCoreRatio");E(this,"uAccumPointAlpha");E(this,"uColorAccumTexture");E(this,"uColorGradientTexture");E(this,"uColorOpacity");E(this,"uColorCutoff");E(this,"uColorGain");E(this,"uColorResolution");E(this,"uColorGamma");E(this,"uColorBias");E(this,"uColorStretch");E(this,"pointCapacity",0);E(this,"interleavedCapacity",0);E(this,"interleavedBuffer",null);E(this,"gradientKey","");this.canvas=document.createElement("canvas");const e=this.canvas.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,preserveDrawingBuffer:!0,premultipliedAlpha:!0,powerPreference:"high-performance"});if(!e)throw new Error("WebGL2 is not available for heatmap rendering.");this.gl=e;const r=!!e.getExtension("EXT_color_buffer_float");this.accumInternalFormat=r?e.RGBA16F:e.RGBA8,this.accumTextureFormat=e.RGBA,this.accumTextureType=r?e.HALF_FLOAT:e.UNSIGNED_BYTE,this.accumProgram=xt(e,ha,da),this.colorProgram=xt(e,ma,ga);const i=e.createVertexArray(),o=e.createVertexArray(),s=e.createBuffer(),a=e.createBuffer(),l=e.createTexture(),c=e.createTexture(),f=e.createFramebuffer();if(!i||!o||!s||!a||!l||!c||!f)throw new Error("Failed to allocate heatmap WebGL resources.");this.accumVao=i,this.colorVao=o,this.pointBuffer=s,this.quadBuffer=a,this.accumTexture=l,this.gradientTexture=c,this.framebuffer=f;const u=e.getUniformLocation(this.accumProgram,"uResolution"),h=e.getUniformLocation(this.accumProgram,"uPointSize"),d=e.getUniformLocation(this.accumProgram,"uCoreRatio"),m=e.getUniformLocation(this.accumProgram,"uPointAlpha"),p=e.getUniformLocation(this.colorProgram,"uAccumTexture"),b=e.getUniformLocation(this.colorProgram,"uGradientTexture"),y=e.getUniformLocation(this.colorProgram,"uOpacity"),x=e.getUniformLocation(this.colorProgram,"uCutoff"),M=e.getUniformLocation(this.colorProgram,"uGain"),S=e.getUniformLocation(this.colorProgram,"uGamma"),C=e.getUniformLocation(this.colorProgram,"uBias"),A=e.getUniformLocation(this.colorProgram,"uStretch"),B=e.getUniformLocation(this.colorProgram,"uResolution");if(!u||!h||!d||!m||!p||!b||!y||!x||!M||!S||!C||!A||!B)throw new Error("Failed to resolve heatmap WebGL uniforms.");this.uAccumResolution=u,this.uAccumPointSize=h,this.uAccumCoreRatio=d,this.uAccumPointAlpha=m,this.uColorAccumTexture=p,this.uColorGradientTexture=b,this.uColorOpacity=y,this.uColorCutoff=x,this.uColorGain=M,this.uColorGamma=S,this.uColorBias=C,this.uColorStretch=A,this.uColorResolution=B,e.bindVertexArray(this.accumVao),e.bindBuffer(e.ARRAY_BUFFER,this.pointBuffer),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const z=e.getAttribLocation(this.accumProgram,"aCenter"),Y=e.getAttribLocation(this.accumProgram,"aWeight");if(z<0||Y<0)throw new Error("Failed to resolve heatmap WebGL attributes.");e.enableVertexAttribArray(z),e.vertexAttribPointer(z,2,e.FLOAT,!1,12,0),e.enableVertexAttribArray(Y),e.vertexAttribPointer(Y,1,e.FLOAT,!1,12,8),e.bindVertexArray(null),e.bindVertexArray(this.colorVao),e.bindBuffer(e.ARRAY_BUFFER,this.quadBuffer),e.bufferData(e.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,1,1]),e.STATIC_DRAW);const P=e.getAttribLocation(this.colorProgram,"aPosition");if(P<0)throw new Error("Failed to resolve heatmap color position attribute.");e.enableVertexAttribArray(P),e.vertexAttribPointer(P,2,e.FLOAT,!1,8,0),e.bindVertexArray(null),e.bindBuffer(e.ARRAY_BUFFER,null),e.bindTexture(e.TEXTURE_2D,this.accumTexture),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.bindTexture(e.TEXTURE_2D,null),e.bindTexture(e.TEXTURE_2D,this.gradientTexture),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.bindTexture(e.TEXTURE_2D,null),this.ensureCanvasSize(1,1)}render(e){if(e.count<=0||e.width<=0||e.height<=0)return!1;this.ensureCanvasSize(e.width,e.height),this.ensureGradientTexture(e.gradient),this.uploadPointData(e.positions,e.weights,e.count);const n=this.gl;return n.disable(n.SCISSOR_TEST),n.disable(n.DEPTH_TEST),n.disable(n.CULL_FACE),n.bindFramebuffer(n.FRAMEBUFFER,this.framebuffer),n.viewport(0,0,e.width,e.height),n.clearColor(0,0,0,0),n.clear(n.COLOR_BUFFER_BIT),n.useProgram(this.accumProgram),n.bindVertexArray(this.accumVao),n.uniform2f(this.uAccumResolution,e.width,e.height),n.uniform1f(this.uAccumPointSize,Math.max(1,(e.kernelRadiusPx+e.blurRadiusPx)*2)),n.uniform1f(this.uAccumCoreRatio,e.kernelRadiusPx/Math.max(1e-6,e.kernelRadiusPx+e.blurRadiusPx)),n.uniform1f(this.uAccumPointAlpha,Math.max(0,e.pointAlpha)),n.enable(n.BLEND),n.blendEquation(n.FUNC_ADD),n.blendFuncSeparate(n.ONE,n.ONE,n.ONE,n.ONE),n.drawArrays(n.POINTS,0,e.count),n.disable(n.BLEND),n.bindVertexArray(null),n.bindFramebuffer(n.FRAMEBUFFER,null),n.viewport(0,0,e.width,e.height),n.clearColor(0,0,0,0),n.clear(n.COLOR_BUFFER_BIT),n.useProgram(this.colorProgram),n.bindVertexArray(this.colorVao),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,this.accumTexture),n.uniform1i(this.uColorAccumTexture,0),n.activeTexture(n.TEXTURE1),n.bindTexture(n.TEXTURE_2D,this.gradientTexture),n.uniform1i(this.uColorGradientTexture,1),n.uniform1f(this.uColorOpacity,e.opacity),n.uniform1f(this.uColorCutoff,e.cutoff??.008),n.uniform1f(this.uColorGain,e.gain??2.6),n.uniform1f(this.uColorGamma,e.gamma??1),n.uniform1f(this.uColorBias,e.bias??0),n.uniform1f(this.uColorStretch,e.stretch??1),n.uniform2f(this.uColorResolution,e.width,e.height),n.drawArrays(n.TRIANGLE_STRIP,0,4),n.bindVertexArray(null),n.bindTexture(n.TEXTURE_2D,null),n.flush(),!0}destroy(){const e=this.gl;e.deleteTexture(this.accumTexture),e.deleteTexture(this.gradientTexture),e.deleteFramebuffer(this.framebuffer),e.deleteBuffer(this.pointBuffer),e.deleteBuffer(this.quadBuffer),e.deleteVertexArray(this.accumVao),e.deleteVertexArray(this.colorVao),e.deleteProgram(this.accumProgram),e.deleteProgram(this.colorProgram),this.canvas.width=0,this.canvas.height=0}ensureCanvasSize(e,n){const r=Math.max(1,Math.round(e)),i=Math.max(1,Math.round(n));this.canvas.width!==r&&(this.canvas.width=r),this.canvas.height!==i&&(this.canvas.height=i);const o=this.gl;o.bindTexture(o.TEXTURE_2D,this.accumTexture),o.texImage2D(o.TEXTURE_2D,0,this.accumInternalFormat,r,i,0,this.accumTextureFormat,this.accumTextureType,null),o.bindFramebuffer(o.FRAMEBUFFER,this.framebuffer),o.framebufferTexture2D(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,this.accumTexture,0);const s=o.checkFramebufferStatus(o.FRAMEBUFFER);if(o.bindFramebuffer(o.FRAMEBUFFER,null),s!==o.FRAMEBUFFER_COMPLETE)throw new Error(`Heatmap framebuffer incomplete: ${s}`)}ensureGradientTexture(e){const n=e.join("|");if(this.gradientKey===n)return;const r=document.createElement("canvas");r.width=256,r.height=1;const i=r.getContext("2d");if(!i)throw new Error("Failed to create heatmap gradient canvas.");const o=i.createLinearGradient(0,0,256,0),s=e.length>1?e:["#00000000","#3876FF","#4CDDDD","#FFE75C","#FF8434","#FF3434"],a=1/Math.max(1,s.length-1);for(let f=0;f<s.length;f+=1)o.addColorStop(f*a,s[f]);i.clearRect(0,0,256,1),i.fillStyle=o,i.fillRect(0,0,256,1);const l=i.getImageData(0,0,256,1).data,c=this.gl;c.bindTexture(c.TEXTURE_2D,this.gradientTexture),c.texImage2D(c.TEXTURE_2D,0,c.RGBA,256,1,0,c.RGBA,c.UNSIGNED_BYTE,l),c.bindTexture(c.TEXTURE_2D,null),this.gradientKey=n}uploadPointData(e,n,r){const i=this.gl,o=r*3,s=o*4;i.bindBuffer(i.ARRAY_BUFFER,this.pointBuffer),r>this.pointCapacity&&(i.bufferData(i.ARRAY_BUFFER,s,i.DYNAMIC_DRAW),this.pointCapacity=r),o>this.interleavedCapacity&&(this.interleavedCapacity=o,this.interleavedBuffer=new Float32Array(o));const a=this.interleavedBuffer;if(!a)throw new Error("Failed to allocate heatmap upload buffer.");for(let l=0;l<r;l+=1){const c=l*2,f=l*3;a[f]=e[c]??0,a[f+1]=e[c+1]??0,a[f+2]=n[l]??0}i.bufferSubData(i.ARRAY_BUFFER,0,a.subarray(0,o)),i.bindBuffer(i.ARRAY_BUFFER,null)}}const Tr="__open_plant_heatmap_layer__",ya=["#00000000","#3876FF","#4CDDDD","#FFE75C","#FF8434","#FF3434"],ba=3,xa=2,wa=.9,Sa=52e3,Ea="screen",Ra=2.2,An=128,en=1600,Ma=1.9,Aa=4.2,Cn=3e3,Ii=Math.SQRT2,Ca=2048,Pa=.9,He=16;function Pt(t,e){return e.maxTierZoom+Math.log2(Math.max(1e-6,t))}function Vn(t,e){return Math.max(1e-6,2**(t-e.maxTierZoom))}function va(t,e,n){if(!Number.isFinite(n)||Math.abs(n)<1e-6)return Math.max(1e-6,t);const r=Pt(t,e)-n;return Vn(r,e)}function Ta(t){return!Number.isFinite(t)||Math.abs(t)<1e-6?0:Math.round(t*1.5/Math.max(1e-6,Math.log2(Ii)))}function _i(t){const e=F(t,0,He);return F(.55+Math.sqrt(Math.max(0,e))*.48,.55,6)}function Ia(t){const e=Math.max(0,t);return e<=1?.18:e<=2?.3:e<=4?.48:e<=8?.7:e<=16?.86:1}function Fi(t){return .022-F(t,0,He)/He*.015}function Li(t){const e=F(t,0,He);return .18+Math.pow(Math.max(0,e),.72)*.42+Math.log2(e+1)*.24}function Di(t){return _i(t)}function Ni(t){const n=F(t,0,He)/He;return F(.46-n*.34,.12,.46)}function zi(t,e,n){const i=F(t,0,He)/He,o=Pt(e,n),s=n.maxTierZoom-3.2,a=n.maxTierZoom-1.15,l=F((o-s)/Math.max(1e-6,a-s),0,1),c=1.12+Math.pow(i,.82)*1.18,f=1+l*(.48+i*.92);return c*f}function _a(t,e,n){const r=Math.max(0,t),i=Math.max(1e-6,e),o=Math.log1p(r)/Math.log1p(i);return F(o,0,1)}function Fa(t){return Pa}function La(t,e){if(t.length===0)return 1;const n=Math.min(t.length,Ca),r=new Array(n);let i=1;for(let f=0;f<n;f+=1){const u=Math.min(t.length-1,Math.floor((f+.5)*t.length/n)),h=Math.max(0,t[u]?.weight??0);r[f]=h,h>i&&(i=h)}for(let f=0;f<t.length;f+=1){const u=Math.max(0,t[f]?.weight??0);u>i&&(i=u)}r.sort((f,u)=>f-u);const o=Fa(),s=Math.max(0,Math.min(r.length-1,Math.floor((r.length-1)*o))),a=r[s]??i;return Math.max(1,Math.min(i,Math.max(a*1.08,i*.14)))}function Bi(t,e,n){const r=Pt(t,e),i=e.maxTierZoom-2.45,o=e.maxTierZoom-1.2,s=r<=i?1:r>=o?0:(()=>{const a=F((r-i)/Math.max(1e-6,o-i),0,1);return 1-a*a*(3-2*a)})();return F(s,0,1)}function Da(t){if(t>=1)return 1;const e=1/Math.max(t,1e-6);return 1+Math.log2(e)*.28}function Na(t,e,n,r){const i=Math.max(1,t,e),o=typeof window>"u"?1:F(window.devicePixelRatio||1,1,2.4),s=r<=.35?1.42:r<=.55?1.26:r<=.8?1.14:1,a=n>16e4?896:n>8e4?1152:n>3e4?1408:en,l=An/i,c=en/i;return F(a*o*s/i,l,c)}function Pn(t){const e=t.heatmapScale??Na(t.logicalWidth,t.logicalHeight,t.totalPointCount,t.rawZoom),n=Math.max(An,Math.min(en,Math.round(t.logicalWidth*e))),r=Math.max(An,Math.min(en,Math.round(t.logicalHeight*e))),i=n/Math.max(1,t.logicalWidth),o=r/Math.max(1,t.logicalHeight),s=Math.min(i,o),a=Math.max(1e-6,t.rawZoom),l=Math.max(.75,t.radius*Ma*s),c=Math.max(.6,t.blur*Aa*s),f=(l+c)/Math.max(1e-6,a*s),u=Math.max(f*.4,.62/Math.max(1e-6,a*s));return{heatmapScale:e,rasterWidth:n,rasterHeight:r,rasterScaleX:i,rasterScaleY:o,rawZoom:a,kernelRadiusPx:l,blurRadiusPx:c,outerWorldRadius:f,desiredCellWorldSize:u}}function Gn(t){if(!t)return 0;const e=Math.floor(t.positions.length/2),n=t.weights?t.weights.length:Number.MAX_SAFE_INTEGER;return Math.max(0,Math.min(Math.floor(t.count),e,n))}function Dt(t,e){const n=Number.isFinite(t)?Math.round(t*1024):0;return Math.imul(e^n,73244475)>>>0}function za(t,e,n=2654435769){let r=Math.imul(n^(t|0),2246822507)>>>0;return r=Math.imul(r^(e|0),3266489909)>>>0,r^=r>>>16,r>>>0}function Ba(t){return(t>>>0)/4294967295}function ki(t){let e=2166136261;for(let n=0;n<t.length;n+=1){const r=t[n];e=Math.imul(e^r.outer.length,16777619)>>>0;for(let i=0;i<r.outer.length;i+=1){const o=r.outer[i];e=Dt(o[0],e),e=Dt(o[1],e)}e=Math.imul(e^r.holes.length,16777619)>>>0;for(let i=0;i<r.holes.length;i+=1){const o=r.holes[i];e=Math.imul(e^o.length,16777619)>>>0;for(let s=0;s<o.length;s+=1){const a=o[s];e=Dt(a[0],e),e=Dt(a[1],e)}}}return`${t.length}:${e>>>0}`}function Zn(t,e,n){return t.dataRef===e&&t.clipKey===n?!0:e?t.clipKey===n&&t.inputCount===Gn(e)&&t.positionsRef===e.positions&&t.weightsRef===e.weights:!1}function ka(t,e,n,r){const i=Gn(t);if(!t||i<=0)return null;let o=new Float32Array(i),s=new Float32Array(i),a=new Float32Array(i),l=0,c=1/0,f=1/0,u=-1/0,h=-1/0;for(let M=0;M<i;M+=1){const S=t.positions[M*2],C=t.positions[M*2+1];if(!Number.isFinite(S)||!Number.isFinite(C)||e.length>0&&!Et(S,C,e))continue;const A=t.weights?.[M],B=typeof A=="number"&&Number.isFinite(A)?Math.max(0,A):1;B<=0||(o[l]=S,s[l]=C,a[l]=B,l+=1,S<c&&(c=S),S>u&&(u=S),C<f&&(f=C),C>h&&(h=C))}if(l===0||!Number.isFinite(c)||!Number.isFinite(f)||!Number.isFinite(u)||!Number.isFinite(h))return null;l<i&&(o=o.slice(0,l),s=s.slice(0,l),a=a.slice(0,l));const d=[];for(let M=0;M<l;M+=1){const S=o[M],C=s[M];d.push({minX:S,minY:C,maxX:S,maxY:C,value:M})}const m=Ti(64);m.load(d);const p=Math.max(r?.width??0,r?.height??0,u-c,h-f,1),b=[];let y=.5,x=0;for(;y<=p&&x<32;)b.push(y),y*=Ii,x+=1;return b.length===0&&b.push(1),{dataRef:t,sourceRef:r,positionsRef:t.positions,weightsRef:t.weights,inputCount:i,clipRef:e,clipKey:n,pointCount:l,xs:o,ys:s,ws:a,pointIndex:m,cellSizes:b,levels:Array.from({length:b.length},()=>null)}}function vn(t,e,n){const r=t.pointIndex.search([e[0]-n,e[1]-n,e[2]+n,e[3]+n]),i=new Array(r.length);let o=0;for(let s=0;s<r.length;s+=1){const a=r[s];a&&(i[o]=a.value,o+=1)}return i.length=o,i}function Ui(t,e){const n=Math.max(Cn,e);return t<=n?1:F(n/Math.max(1,t),1/65536,1)}function Oi(t){return t>=1?1:Math.max(1,Math.round(1/Math.max(1e-6,t)))}function Ua(t,e){if(e>=1)return!0;const n=za(t,1374496523,1757159915);return Ba(n)<=F(e,0,1)}function Wi(t,e,n,r){const i=Math.max(1,n*r),o=Math.PI*e*e,s=Math.max(1,t)*o/i;return F(.085/Math.sqrt(Math.max(1,s)),.012,.075)}function Ir(t,e,n,r){if(!Number.isFinite(t)||t<=0)return e;const i=e>=t?n:r;return t+(e-t)*F(i,0,1)}function Oa(t){if(t.webgl!==void 0)return t.webgl;if(typeof document>"u")return t.webgl=null,null;try{t.webgl=new pa}catch(e){if(!t.webglWarningIssued&&typeof console<"u"&&typeof console.warn=="function"){const n=e instanceof Error?e.message:String(e);console.warn(`[open-plant] HeatmapLayer disabled because WebGL2 heatmap initialization failed: ${n}`),t.webglWarningIssued=!0}t.webgl=null}return t.webgl}function _r(t,e){const n=[];for(let r=0;r<e.length;r+=1){const i=e[r];if(!i)continue;const o=t.worldToScreen(i[0],i[1]);if(!Array.isArray(o)||o.length<2)continue;const s=Number(o[0]),a=Number(o[1]);!Number.isFinite(s)||!Number.isFinite(a)||n.push([s,a])}return n}function Wa(t,e,n){if(n.length!==0){t.beginPath();for(let r=0;r<n.length;r+=1){const i=n[r],o=_r(e,i.outer);o.length>=3&&Rt(t,o,!0);for(let s=0;s<i.holes.length;s+=1){const a=_r(e,i.holes[s]);a.length>=3&&Rt(t,a,!0)}}t.clip("evenodd")}}function Yi(t,e,n,r,i){const o=t.sourceData;return o&&o.sourceRef===i&&Zn(o,e,r)?o:(t.sourceData=ka(e,n,r,i),t.fixedState=null,t.screenLevelIndex=-1,t.sourceData)}function Ya(t){const{sourceData:e,renderer:n,source:r,logicalWidth:i,logicalHeight:o,radius:s,blur:a,fixedZoom:l,maxRenderedPoints:c}=t,f=Math.max(1e-6,n.getViewState().zoom),u=l??Pt(f,r),h=Vn(u,r),d=Pn({logicalWidth:i,logicalHeight:o,totalPointCount:e.pointCount,rawZoom:h,radius:s,blur:a}),m=n.getViewBounds(),p=vn(e,m,d.outerWorldRadius),b=Ui(p.length,c),y=Oi(b),x=Math.min(d.rasterScaleX,d.rasterScaleY);return{dataRef:e.dataRef,positionsRef:e.positionsRef,weightsRef:e.weightsRef,inputCount:e.inputCount,clipRef:e.clipRef,clipKey:e.clipKey,referenceZoom:u,referenceRawZoom:h,heatmapScale:d.heatmapScale,kernelWorldRadius:d.kernelRadiusPx/Math.max(1e-6,h*x),blurWorldRadius:d.blurRadiusPx/Math.max(1e-6,h*x),sampleProbability:b,sampleStride:y,pointAlpha:Wi(p.length,d.kernelRadiusPx+d.blurRadiusPx,d.rasterWidth,d.rasterHeight)}}function Fr(t){const{ctx:e,runtime:n,renderer:r,source:i,logicalWidth:o,logicalHeight:s,frame:a,sourceData:l,visiblePointIndices:c,sampleProbability:f,sampleStride:u,pointAlpha:h,gradient:d,opacity:m,densityContrast:p,backgroundColor:b,clipPolygons:y}=t,x=Oa(n);if(!x||c.length===0)return 0;const M=Math.min(c.length,Math.max(64,Math.ceil(c.length*Math.min(1,f*1.15))));M>n.webglCapacity&&(n.webglCapacity=M,n.webglPositions=new Float32Array(M*2),n.webglWeights=new Float32Array(M));const S=n.webglPositions,C=n.webglWeights;if(!S||!C)return 0;const A=a.kernelRadiusPx+a.blurRadiusPx,B=Da(f);let z=0;for(let P=0;P<c.length;P+=1){const I=c[P];if(!Ua(I,f))continue;const O=l.xs[I],v=l.ys[I];if(!Number.isFinite(O)||!Number.isFinite(v))continue;const W=r.worldToScreen(O,v);if(!Array.isArray(W)||W.length<2)continue;const j=Number(W[0]),L=Number(W[1]);if(!Number.isFinite(j)||!Number.isFinite(L))continue;const ge=j*a.rasterScaleX,le=L*a.rasterScaleY;if(ge<-A||le<-A||ge>a.rasterWidth+A||le>a.rasterHeight+A)continue;const Q=z*2;S[Q]=ge,S[Q+1]=le,C[z]=Math.max(0,(l.ws[I]??0)*B),z+=1}return z<=0||!x.render({width:a.rasterWidth,height:a.rasterHeight,positions:S,weights:C,count:z,kernelRadiusPx:a.kernelRadiusPx,blurRadiusPx:a.blurRadiusPx,pointAlpha:h,gradient:d,opacity:m,cutoff:Fi(p),gain:Li(p),gamma:Di(p),bias:Ni(p),stretch:zi(p,a.rawZoom,i)})?0:(e.save(),y.length>0&&Wa(e,r,y),b&&(e.fillStyle=b,e.fillRect(0,0,o,s)),e.globalAlpha=1,e.imageSmoothingEnabled=!0,e.drawImage(x.canvas,0,0,a.rasterWidth,a.rasterHeight,0,0,o,s),e.restore(),z)}function Xa(t){const{ctx:e,runtime:n,renderer:r,source:i,logicalWidth:o,logicalHeight:s,state:a}=t,l=Yi(n,a.data,a.clipPolygons,a.clipKey,i);if(!l||l.cellSizes.length===0||l.pointCount<=0)return null;const c=Math.max(1e-6,r.getViewState().zoom),f=Bi(c,i,a.zoomThreshold),u=r.getViewBounds();if(f<=.001)return{pointCount:l.pointCount,renderTimeMs:0,visiblePointCount:0,renderedBinCount:0,sampleStride:1,maxDensity:0};if(a.scaleMode!=="fixed-zoom"){const y=Pn({logicalWidth:o,logicalHeight:s,totalPointCount:l.pointCount,rawZoom:c,radius:a.radius,blur:a.blur}),x=vn(l,u,y.outerWorldRadius);if(x.length===0)return{pointCount:l.pointCount,renderTimeMs:0,visiblePointCount:0,renderedBinCount:0,sampleStride:1,maxDensity:0};const M=Ui(x.length,a.maxRenderedPoints),S=Oi(M),C=Wi(x.length,y.kernelRadiusPx+y.blurRadiusPx,y.rasterWidth,y.rasterHeight);n.screenLevelIndex=-1,n.screenSecondaryLevelIndex=-1,n.screenSecondaryLevelWeight=0,n.screenNormalizationMaxWeight=1,n.screenPointAlpha=Ir(n.screenPointAlpha,C,.12,.08),n.screenVisibilityStrength=r.isViewAnimating()?Ir(n.screenVisibilityStrength,f,.16,.12):f;const A=Fr({ctx:e,runtime:n,renderer:r,source:i,logicalWidth:o,logicalHeight:s,frame:y,sourceData:l,visiblePointIndices:x,sampleProbability:M,sampleStride:S,pointAlpha:n.screenPointAlpha*Math.max(.08,n.screenVisibilityStrength),gradient:a.gradient,opacity:a.opacity*n.screenVisibilityStrength,densityContrast:a.densityContrast,backgroundColor:a.backgroundColor,clipPolygons:a.clipPolygons});return{pointCount:l.pointCount,renderTimeMs:0,visiblePointCount:x.length,renderedBinCount:A,sampleStride:S,maxDensity:Math.round(n.screenPointAlpha*255)}}const h=n.fixedState;if(!h)return null;const d=Pn({logicalWidth:o,logicalHeight:s,totalPointCount:l.pointCount,rawZoom:c,radius:a.radius,blur:a.blur,heatmapScale:h.heatmapScale}),m=Math.min(d.rasterScaleX,d.rasterScaleY);d.kernelRadiusPx=Math.max(.75,h.kernelWorldRadius*c*m),d.blurRadiusPx=Math.max(.6,h.blurWorldRadius*c*m),d.outerWorldRadius=h.kernelWorldRadius+h.blurWorldRadius;const p=vn(l,u,d.outerWorldRadius);if(p.length===0)return{pointCount:l.pointCount,renderTimeMs:0,visiblePointCount:0,renderedBinCount:0,sampleStride:1,maxDensity:0};n.screenPointAlpha=h.pointAlpha,n.screenVisibilityStrength=f;const b=Fr({ctx:e,runtime:n,renderer:r,source:i,logicalWidth:o,logicalHeight:s,frame:d,sourceData:l,visiblePointIndices:p,sampleProbability:h.sampleProbability,sampleStride:h.sampleStride,pointAlpha:h.pointAlpha*Math.max(.08,f),gradient:a.gradient,opacity:a.opacity*f,densityContrast:a.densityContrast,backgroundColor:a.backgroundColor,clipPolygons:a.clipPolygons});return{pointCount:l.pointCount,renderTimeMs:0,visiblePointCount:p.length,renderedBinCount:b,sampleStride:h.sampleStride,maxDensity:Math.round(h.pointAlpha*255)}}function Va({data:t,visible:e=!0,opacity:n=wa,radius:r=ba,blur:i=xa,gradient:o=ya,backgroundColor:s=null,scaleMode:a=Ea,fixedZoom:l,zoomThreshold:c=0,densityContrast:f=Ra,clipToRegions:u,zIndex:h=5,maxRenderedPoints:d=Sa,onStats:m}){const{rendererRef:p,source:b,registerDrawCallback:y,unregisterDrawCallback:x,requestOverlayRedraw:M}=st(),S=g.useMemo(()=>{const z=(u??[]).map(Y=>dt(Y?.coordinates)).filter(Y=>Y!=null);return mt(z)},[u]),C=g.useMemo(()=>ki(S),[S]),A=g.useRef({sourceData:null,fixedState:null,screenLevelIndex:-1,screenSecondaryLevelIndex:-1,screenSecondaryLevelWeight:0,screenPointAlpha:0,screenNormalizationMaxWeight:1,screenVisibilityStrength:1,webgl:void 0,webglWarningIssued:!1,webglPositions:null,webglWeights:null,webglCapacity:0}),B=g.useRef({data:t,visible:e,opacity:n,radius:F(r,.05,128),blur:F(i,.05,128),gradient:o,backgroundColor:s,scaleMode:a,fixedZoom:l,zoomThreshold:c,densityContrast:F(f,0,He),clipPolygons:S,clipKey:C,maxRenderedPoints:Math.max(Cn,Math.floor(d)),onStats:m});return B.current={data:t,visible:e,opacity:n,radius:F(r,.05,128),blur:F(i,.05,128),gradient:o,backgroundColor:s,scaleMode:a,fixedZoom:l,zoomThreshold:c,densityContrast:F(f,0,He),clipPolygons:S,clipKey:C,maxRenderedPoints:Math.max(Cn,Math.floor(d)),onStats:m},g.useEffect(()=>(y(Tr,h,(Y,P,I)=>{const O=B.current,v=A.current,W=p.current;if(!O.visible||!O.data||!W||!b)return;const j=Yi(v,O.data,O.clipPolygons,O.clipKey,b);if(!j)return;O.scaleMode==="fixed-zoom"&&(!v.fixedState||!Zn(v.fixedState,O.data,O.clipKey)||O.fixedZoom!==void 0&&Math.abs(v.fixedState.referenceZoom-O.fixedZoom)>1e-6)?v.fixedState=Ya({sourceData:j,renderer:W,source:b,logicalWidth:P,logicalHeight:I,radius:O.radius,blur:O.blur,fixedZoom:O.fixedZoom,zoomThreshold:O.zoomThreshold,densityContrast:O.densityContrast,maxRenderedPoints:O.maxRenderedPoints}):O.scaleMode!=="fixed-zoom"&&(v.fixedState=null);const ge=performance.now(),le=Xa({ctx:Y,runtime:v,renderer:W,source:b,logicalWidth:P,logicalHeight:I,state:O});!le||!O.onStats||O.onStats({...le,renderTimeMs:performance.now()-ge})}),()=>{x(Tr),A.current.sourceData=null,A.current.fixedState=null,A.current.screenLevelIndex=-1,A.current.screenSecondaryLevelIndex=-1,A.current.screenSecondaryLevelWeight=0,A.current.screenPointAlpha=0,A.current.screenNormalizationMaxWeight=1,A.current.screenVisibilityStrength=1,A.current.webgl?.destroy(),A.current.webgl=void 0,A.current.webglPositions=null,A.current.webglWeights=null,A.current.webglCapacity=0}),[y,x,p,b,h]),g.useEffect(()=>{A.current.sourceData=null,A.current.fixedState=null,A.current.screenLevelIndex=-1,A.current.screenSecondaryLevelIndex=-1,A.current.screenSecondaryLevelWeight=0,A.current.screenPointAlpha=0,A.current.screenNormalizationMaxWeight=1,A.current.screenVisibilityStrength=1,M()},[t?.positions,t?.weights,t?.count,C,M]),g.useEffect(()=>{A.current.fixedState=null,A.current.screenSecondaryLevelIndex=-1,A.current.screenSecondaryLevelWeight=0,A.current.screenPointAlpha=0,A.current.screenNormalizationMaxWeight=1,A.current.screenVisibilityStrength=1,M()},[r,i,a,l,c,f,d,M]),g.useEffect(()=>{M()},[e,n,o,s,M]),null}const Ga={applyZoomThreshold:va,buildClipKey:ki,resolveCellSupportFactor:Ia,resolveContinuousZoom:Pt,resolveDensityCutoff:Fi,resolveDensityBias:Ni,resolveDensityGain:Li,resolveDensityGamma:Di,resolveDensityStretch:zi,resolveNormalizedDensityWeight:_a,resolveNormalizationUpperWeight:La,resolveDensityWeightExponent:_i,resolveRawZoomFromContinuousZoom:Vn,resolvePointCount:Gn,resolveThresholdLevelBias:Ta,resolveZoomVisibilityStrength:Bi,isSameHeatmapInput:Zn},Lr="__overlay_layer__";function Za({shapes:t}){const{rendererRef:e,rendererSerial:n,source:r,registerDrawCallback:i,unregisterDrawCallback:o,requestOverlayRedraw:s}=st(),a=g.useCallback(c=>{const f=e.current;if(!f||c.length===0)return[];const u=new Array(c.length);for(let h=0;h<c.length;h+=1){const d=qe(f.worldToScreen(c[h][0],c[h][1]));if(!d)return[];u[h]=d}return u},[]),l=g.useRef({shapes:t,worldToScreenPoints:a,source:r});return l.current={shapes:t,worldToScreenPoints:a,source:r},g.useEffect(()=>(i(Lr,30,f=>{const{shapes:u,worldToScreenPoints:h,source:d}=l.current;if(!Array.isArray(u)||u.length===0||!d)return;const m=h(Oe([[0,0],[d.width,0],[d.width,d.height],[0,d.height]]));Ci({ctx:f,overlayShapes:u,imageOuterRing:m,worldToScreenPoints:h,baseStrokeStyle:$e})}),()=>o(Lr)),[i,o]),g.useEffect(()=>{s()},[n,t,r,s]),null}function qa(t){return Array.isArray(t?.classes)?t.classes.map(e=>({classId:String(e?.classId??""),className:String(e?.className??""),classColor:String(e?.classColor??"")})):[]}function Dr(t){return String(t??"").replace(/\/+$/,"")}function Xi(t){const e=String(t??"");return e.startsWith("/")?e:`/${e}`}function Ha(t){const e=Dr(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=Dr(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 $a(t,e){const n=t?.imsInfo??{},r=!!t?.imsInfo,i=Number(n.width??t?.width??0),o=Number(n.height??t?.height??0),s=Number(n.tileSize??t?.tileSize??0),a=Number(n.zoom??t?.zoom??0),l=String(n.path??t?.path??""),c=Number(n.mpp??t?.mpp??0);if(!i||!o||!s||!l)throw new Error("Incomplete image metadata: width/height/tileSize/path required");const f=Xi(l),u=Ha(e),h=t?.tileUrlBuilder??(r?(d,m,p)=>`${u}${f}/${d}/${p}_${m}.webp`:void 0);return{id:t?._id||t?.id||"unknown",name:t?.name||"unknown",width:i,height:o,mpp:Number.isFinite(c)&&c>0?c:void 0,tileSize:s,maxTierZoom:Number.isFinite(a)?Math.max(0,Math.floor(a)):0,tilePath:l,tileBaseUrl:e,tileUrlBuilder:h}}function qn(t,e,n,r){if(t.tileUrlBuilder)return t.tileUrlBuilder(e,n,r,t.tilePath,t.tileBaseUrl);const i=Xi(t.tilePath);return`${t.tileBaseUrl}${i}/${e}/${r}_${n}.webp`}function Ka(t,e){if(!e)return!1;const n=new URL(t,typeof window<"u"?window.location.href:void 0).hostname.toLowerCase();return!(n.includes("amazonaws.com")||n.startsWith("s3.")||n.includes(".s3."))}const We={width:200,height:125,margin:16,position:"bottom-right",borderRadius:6,borderWidth:0,backgroundColor:"rgba(4, 10, 18, 0.88)",borderColor:"rgba(230, 244, 255, 0.35)",viewportBorderColor:"rgba(255, 106, 61, 0.95)",viewportBorderStyle:"dash",viewportFillColor:"transparent",interactive:!0,showThumbnail:!0,maxThumbnailTiles:16};function Nr(t,e,n,r){const i=e.length;if(!(i<3)){for(let o=0;o<i;o+=1){const s=e[o],a=e[(o+1)%i],l=Math.hypot(a[0]-s[0],a[1]-s[1]);if(l<1e-6)continue;const c=Math.max(1,Math.round((l+r)/(n+r))),f=c*n+(c-1)*r,u=l/Math.max(1e-6,f),h=n*u,d=r*u;t.beginPath(),t.moveTo(s[0],s[1]),t.lineTo(a[0],a[1]),t.setLineDash([h,d]),t.lineDashOffset=0,t.stroke()}t.setLineDash([]),t.lineDashOffset=0}}function zr(t,e,n=1e-4){return Math.abs(t[0]-e[0])<=n&&Math.abs(t[1]-e[1])<=n}function Br(t){const e=[];for(const n of t){const r=e[e.length-1];(!r||!zr(r,n))&&e.push(n)}return e.length>1&&zr(e[0],e[e.length-1])&&e.pop(),e}function kr(t,e,n){const r=e[0]-t[0];if(Math.abs(r)<1e-6)return[n,t[1]];const i=(n-t[0])/r;return[n,t[1]+(e[1]-t[1])*i]}function Ur(t,e,n){const r=e[1]-t[1];if(Math.abs(r)<1e-6)return[t[0],n];const i=(n-t[1])/r;return[t[0]+(e[0]-t[0])*i,n]}function Or(t,e,n,r,i){let o=Br(t);if(o.length<3)return[];const s=[{inside:a=>a[0]>=e,intersect:(a,l)=>kr(a,l,e)},{inside:a=>a[0]<=r,intersect:(a,l)=>kr(a,l,r)},{inside:a=>a[1]>=n,intersect:(a,l)=>Ur(a,l,n)},{inside:a=>a[1]<=i,intersect:(a,l)=>Ur(a,l,i)}];for(const a of s){if(o.length===0)return[];const l=o;o=[];let c=l[l.length-1],f=a.inside(c);for(const u of l){const h=a.inside(u);h?(f||o.push(a.intersect(c,u)),o.push(u)):f&&o.push(a.intersect(c,u)),c=u,f=h}o=Br(o)}return o.length>=3?o:[]}function ct(t,e,n=1){return typeof t!="number"||!Number.isFinite(t)?e:Math.max(n,t)}function Tn(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function ja(t){return t*Math.PI/180}function Qa(t,e,n){const r=Tn(n),i=ja(r),o=Math.cos(i),s=Math.sin(i),a=t*.5,l=e*.5,c=-o*a-s*l,f=s*a-o*l,u=[[0,0],[t,0],[t,e],[0,e]].map(([b,y])=>[o*b+s*y+c,-s*b+o*y+f]);let h=1/0,d=1/0,m=-1/0,p=-1/0;for(const[b,y]of u)b<h&&(h=b),b>m&&(m=b),y<d&&(d=y),y>p&&(p=y);return{cos:o,sin:s,minX:h,minY:d,width:Math.max(1e-6,m-h),height:Math.max(1e-6,p-d),translateX:c,translateY:f}}function Wr(t,e,n,r,i){const o=Qa(t,e,i),s=o.width/o.height,a=n/r;let l,c;return s>a?(l=n,c=n/s):(c=r,l=r*s),{contentX:(n-l)/2,contentY:(r-c)/2,contentWidth:l,contentHeight:c,metrics:o}}function Yr(t,e,n){const{contentX:r,contentY:i,contentWidth:o,contentHeight:s,metrics:a}=n,l=a.cos*t+a.sin*e+a.translateX-a.minX,c=-a.sin*t+a.cos*e+a.translateY-a.minY;return[r+l/a.width*o,i+c/a.height*s]}function Ja(t,e,n,r,i){const{metrics:o}=n,s=t+o.minX-o.translateX,a=e+o.minY-o.translateY,l=s*o.cos-a*o.sin,c=s*o.sin+a*o.cos;return[F(l,0,r),F(c,0,i)]}function el(t){return[[t[0],t[1]],[t[2],t[1]],[t[2],t[3]],[t[0],t[3]]]}function pt(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 tl={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 nl({source:t,projectorRef:e,authToken:n="",options:r,invalidateRef:i,className:o,style:s}){const a=g.useRef(null),l=g.useRef(null),c=g.useRef(null),f=g.useRef({active:!1,pointerId:null}),u=g.useRef(null),h=g.useRef(!1),d=ct(r?.width,We.width,64),m=ct(r?.height,We.height,48),p=ct(r?.margin,We.margin,0),b=ct(r?.borderRadius,We.borderRadius,0),y=ct(r?.borderWidth,We.borderWidth,0),x=Math.max(1,Math.round(ct(r?.maxThumbnailTiles,We.maxThumbnailTiles,1))),M=r?.backgroundColor||We.backgroundColor,S=r?.borderColor||We.borderColor,C=r?.viewportBorderColor||We.viewportBorderColor,A=r?.viewportBorderStyle==="stroke"||r?.viewportBorderStyle==="dash"?r.viewportBorderStyle:We.viewportBorderStyle,B=r?.viewportFillColor??We.viewportFillColor,z=r?.interactive??We.interactive,Y=r?.showThumbnail??We.showThumbnail,P=r?.position||We.position,I=r?.onClose,O=r?.closeIcon,v=r?.closeButtonStyle,W=g.useMemo(()=>{const D={};return P==="top-left"||P==="bottom-left"?D.left=p:D.right=p,P==="top-left"||P==="top-right"?D.top=p:D.bottom=p,{position:"absolute",...D,width:d,height:m,borderRadius:b,overflow:"hidden",zIndex:4,pointerEvents:z?"auto":"none",touchAction:"none",boxShadow:"0 10px 22px rgba(0, 0, 0, 0.3)",...s}},[p,P,d,m,b,z,s]),j=g.useCallback(()=>{const D=a.current;if(!D)return;const T=D.getContext("2d");if(!T)return;const k=d,oe=m,ue=Math.max(1,window.devicePixelRatio||1),$=Math.max(1,Math.round(k*ue)),ce=Math.max(1,Math.round(oe*ue));(D.width!==$||D.height!==ce)&&(D.width=$,D.height=ce),T.setTransform(1,0,0,1,0,0),T.clearRect(0,0,D.width,D.height),T.setTransform(ue,0,0,ue,0,0),T.fillStyle=M,T.fillRect(0,0,k,oe);const te=e.current,_e=Tn(te?.getInitialRotationDeg?.()),Se=Wr(t.width,t.height,k,oe,_e),{contentX:fe,contentY:xe,contentWidth:ee,contentHeight:se,metrics:he}=Se,ae=l.current;ae&&(T.save(),T.beginPath(),T.rect(fe,xe,ee,se),T.clip(),T.translate(fe,xe),T.scale(ee/he.width,se/he.height),T.transform(he.cos,-he.sin,he.sin,he.cos,he.translateX-he.minX,he.translateY-he.minY),T.drawImage(ae,0,0,t.width,t.height),T.restore()),T.strokeStyle=S,T.lineWidth=y,T.strokeRect(y*.5,y*.5,k-y,oe-y);const ne=te?.getViewBounds?.(),Me=te?.getViewCorners?.(),we=Array.isArray(Me)&&Me.length>=4&&Me.every(K=>Array.isArray(K)&&K.length>=2&&Number.isFinite(K[0])&&Number.isFinite(K[1]))?Me:null,V=pt(ne)?ne:pt(c.current)?c.current:null;pt(ne)&&(c.current=ne);const H=A==="dash";if(we){const K=we.map(X=>Yr(X[0],X[1],Se)),Re=Or(K,fe,xe,fe+ee,xe+se);if(Re.length>=3){T.beginPath();for(let X=0;X<Re.length;X+=1)X===0?T.moveTo(Re[X][0],Re[X][1]):T.lineTo(Re[X][0],Re[X][1]);T.closePath(),T.fillStyle=B,T.fill(),T.strokeStyle=C,T.lineWidth=2.25,H?Nr(T,Re,4,3):T.stroke();return}}if(!V)return;const be=el(V).map(K=>Yr(K[0],K[1],Se)),J=Or(be,fe,xe,fe+ee,xe+se);if(!(J.length<3)){T.beginPath();for(let K=0;K<J.length;K+=1)K===0?T.moveTo(J[K][0],J[K][1]):T.lineTo(J[K][0],J[K][1]);T.closePath(),T.fillStyle=B,T.fill(),T.strokeStyle=C,T.lineWidth=2.25,H?Nr(T,J,4,3):T.stroke()}},[d,m,M,S,y,e,t.width,t.height,B,C,A]),L=g.useCallback(()=>{h.current||(h.current=!0,u.current=requestAnimationFrame(()=>{h.current=!1,u.current=null,j()}))},[j]),ge=g.useCallback((D,T)=>{const k=a.current;if(!k)return null;const oe=k.getBoundingClientRect();if(!oe.width||!oe.height)return null;const ue=e.current,$=Tn(ue?.getInitialRotationDeg?.()),ce=Wr(t.width,t.height,d,m,$),te=oe.width/d,_e=oe.height/m,Se=ce.contentX*te,fe=ce.contentY*_e,xe=ce.contentWidth*te,ee=ce.contentHeight*_e,se=F((D-oe.left-Se)/xe,0,1),he=F((T-oe.top-fe)/ee,0,1);return Ja(se*ce.metrics.width,he*ce.metrics.height,ce,t.width,t.height)},[e,t.width,t.height,d,m]),le=g.useCallback((D,T)=>{const k=e.current;if(!k)return;if(k.setViewCenter){k.setViewCenter(D,T),L();return}const oe=k.getViewBounds?.(),ue=pt(oe)?oe:pt(c.current)?c.current:null;if(!ue)return;const $=Math.max(1e-6,ue[2]-ue[0]),ce=Math.max(1e-6,ue[3]-ue[1]);k.setViewState({offsetX:D-$*.5,offsetY:T-ce*.5}),L()},[e,L]),Q=g.useCallback(D=>{if(!z||D.button!==0)return;const T=a.current;if(!T)return;const k=ge(D.clientX,D.clientY);k&&(D.preventDefault(),D.stopPropagation(),T.setPointerCapture(D.pointerId),f.current={active:!0,pointerId:D.pointerId},le(k[0],k[1]))},[z,ge,le]),ve=g.useCallback(D=>{const T=f.current;if(!T.active||T.pointerId!==D.pointerId)return;const k=ge(D.clientX,D.clientY);k&&(D.preventDefault(),D.stopPropagation(),le(k[0],k[1]))},[ge,le]),Ae=g.useCallback(D=>{const T=f.current;if(!T.active||T.pointerId!==D.pointerId)return;const k=a.current;if(k&&k.hasPointerCapture(D.pointerId))try{k.releasePointerCapture(D.pointerId)}catch{}f.current={active:!1,pointerId:null},L()},[L]);return g.useEffect(()=>{let D=!1;l.current=null,L();const T=0,k=2**(t.maxTierZoom-T),oe=Math.ceil(t.width/k),ue=Math.ceil(t.height/k),$=Math.max(1,Math.ceil(oe/t.tileSize)),ce=Math.max(1,Math.ceil(ue/t.tileSize)),te=$*ce;if(!Y||te>x)return;const _e=Math.min(d/Math.max(1,t.width),m/Math.max(1,t.height)),Se=document.createElement("canvas");Se.width=Math.max(1,Math.round(t.width*_e)),Se.height=Math.max(1,Math.round(t.height*_e));const fe=Se.getContext("2d");if(!fe)return;fe.fillStyle=M,fe.fillRect(0,0,Se.width,Se.height);const xe=[];for(let ee=0;ee<ce;ee+=1)for(let se=0;se<$;se+=1){const he=se*t.tileSize*k,ae=ee*t.tileSize*k,ne=Math.min((se+1)*t.tileSize,oe)*k,Me=Math.min((ee+1)*t.tileSize,ue)*k;xe.push({url:qn(t,T,se,ee),bounds:[he,ae,ne,Me]})}return Promise.allSettled(xe.map(async ee=>{const se=Ka(ee.url,n),he=await fetch(ee.url,{headers:se?{Authorization:n}:void 0});if(!he.ok)throw new Error(`HTTP ${he.status}`);const ae=await createImageBitmap(await he.blob());return{tile:ee,bitmap:ae}})).then(ee=>{if(D){for(const ae of ee)ae.status==="fulfilled"&&ae.value.bitmap.close();return}const se=Se.width/Math.max(1,t.width),he=Se.height/Math.max(1,t.height);for(const ae of ee){if(ae.status!=="fulfilled")continue;const{tile:{bounds:ne},bitmap:Me}=ae.value,we=ne[0]*se,V=ne[1]*he,H=Math.max(1,(ne[2]-ne[0])*se),be=Math.max(1,(ne[3]-ne[1])*he);fe.drawImage(Me,we,V,H,be),Me.close()}l.current=Se,L()}),()=>{D=!0}},[t,n,M,d,m,Y,x,L]),g.useEffect(()=>{L()},[L]),g.useEffect(()=>{if(e.current)return;let D=0;const T=()=>{if(e.current){L();return}D=requestAnimationFrame(T)};return D=requestAnimationFrame(T),()=>cancelAnimationFrame(D)},[e,L]),g.useEffect(()=>rn(()=>L()),[L]),g.useEffect(()=>{if(i)return i.current=L,()=>{i.current===L&&(i.current=null)}},[i,L]),g.useEffect(()=>()=>{f.current={active:!1,pointerId:null},u.current!==null&&(cancelAnimationFrame(u.current),u.current=null),h.current=!1},[]),Ge.jsxs("div",{className:o,style:W,children:[Ge.jsx("canvas",{ref:a,style:{width:"100%",height:"100%",display:"block",borderRadius:"inherit"},onPointerDown:Q,onPointerMove:ve,onPointerUp:Ae,onPointerCancel:Ae,onContextMenu:D=>{D.preventDefault()},onWheel:D=>{D.preventDefault(),D.stopPropagation()}}),I&&Ge.jsx("button",{type:"button","aria-label":"Hide overview map",onClick:D=>{D.stopPropagation(),I()},style:v?{...v}:{...tl},children:O??"×"})]})}const Xr="__patch_layer__",rl=[];function il({regions:t,strokeStyle:e}){const{rendererRef:n,registerDrawCallback:r,unregisterDrawCallback:i,requestOverlayRedraw:o}=st(),s=t??rl,a=g.useMemo(()=>Ke(yi,e),[e]),l=g.useMemo(()=>{const u=[];for(let h=0;h<s.length;h+=1){const d=s[h],m=Jt(d.coordinates);m.length!==0&&u.push({region:d,regionIndex:h,regionKey:d.id??h,polygons:m})}return u},[s]),c=g.useCallback(u=>{const h=n.current;if(!h||u.length===0)return[];const d=new Array(u.length);for(let m=0;m<u.length;m+=1){const p=qe(h.worldToScreen(u[m][0],u[m][1]));if(!p)return[];d[m]=p}return d},[]),f=g.useRef({prepared:l,resolvedStrokeStyle:a,worldToScreenPoints:c});return f.current={prepared:l,resolvedStrokeStyle:a,worldToScreenPoints:c},g.useEffect(()=>(r(Xr,20,h=>{const{prepared:d,resolvedStrokeStyle:m,worldToScreenPoints:p}=f.current;for(const b of d)for(const y of b.polygons){const x=p(y.outer);x.length>=4&&ke(h,x,m,!0,!1);for(const M of y.holes){const S=p(M);S.length>=4&&ke(h,S,m,!0,!1)}}}),()=>i(Xr)),[r,i]),g.useEffect(()=>{o()},[l,a,o]),null}function Mt(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return null;const n=mt(e??[]);if(n.length===0){const m={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return t.fillModes instanceof Uint8Array&&(m.fillModes=new Uint8Array(0)),t.ids instanceof Uint32Array&&(m.ids=new Uint32Array(0)),m}const r=ot(t),i=t.positions,o=t.paletteIndices,s=t.fillModes instanceof Uint8Array&&t.fillModes.length>=r?t.fillModes:null,a=t.ids instanceof Uint32Array&&t.ids.length>=r?t.ids:null,l=new Float32Array(r*2),c=new Uint16Array(r),f=s?new Uint8Array(r):null,u=a?new Uint32Array(r):null;let h=0;for(let m=0;m<r;m+=1){const p=i[m*2],b=i[m*2+1];Et(p,b,n)&&(l[h*2]=p,l[h*2+1]=b,c[h]=o[m],f&&(f[h]=s[m]),u&&(u[h]=a[m]),h+=1)}const d={count:h,positions:l.subarray(0,h*2),paletteIndices:c.subarray(0,h)};return f&&(d.fillModes=f.subarray(0,h)),u&&(d.ids=u.subarray(0,h)),d}function Vi(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return new Uint32Array(0);const n=mt(e??[]);if(n.length===0)return new Uint32Array(0);const r=ot(t);if(r===0)return new Uint32Array(0);const i=t.positions,o=new Uint32Array(r);let s=0;for(let a=0;a<r;a+=1){const l=i[a*2],c=i[a*2+1];Et(l,c,n)&&(o[s]=a,s+=1)}return o.subarray(0,s)}let Nt=null;const ol=`
|
|
104
104
|
struct Params {
|
|
105
105
|
pointCount: u32,
|
|
106
106
|
boundsCount: u32,
|
|
@@ -131,7 +131,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
131
131
|
}
|
|
132
132
|
outputMask[i] = inside;
|
|
133
133
|
}
|
|
134
|
-
`;function sl(){if(typeof navigator>"u")return!1;const t=navigator;return typeof t.gpu=="object"&&t.gpu!==null}function Gi(){if(!sl())return null;const e=navigator.gpu;if(!e||typeof e!="object")return null;const n=e;return typeof n.requestAdapter!="function"?null:n}const zt=globalThis.GPUShaderStage?.COMPUTE??4,hn=globalThis.GPUBufferUsage?.STORAGE??128,Bt=globalThis.GPUBufferUsage?.COPY_DST??8,al=globalThis.GPUBufferUsage?.COPY_SRC??4,ll=globalThis.GPUBufferUsage?.UNIFORM??64,cl=globalThis.GPUBufferUsage?.MAP_READ??1,ul=globalThis.GPUMapMode?.READ??1;async function fl(){const t=Gi();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 hl(){return Nt||(Nt=(async()=>{const t=Gi();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:zt,buffer:{type:"read-only-storage"}},{binding:1,visibility:zt,buffer:{type:"read-only-storage"}},{binding:2,visibility:zt,buffer:{type:"storage"}},{binding:3,visibility:zt,buffer:{type:"uniform"}}]}),i=n.createComputePipeline({layout:n.createPipelineLayout({bindGroupLayouts:[r]}),compute:{module:n.createShaderModule({code:ol}),entryPoint:"main"}});return{device:n,pipeline:i,bindGroupLayout:r}})(),Nt)}function kt(t,e){return Math.ceil(t/e)*e}async function Zi(t,e,n){const r=await hl();if(!r)return null;const i=Math.max(0,Math.floor(e)),o=Math.max(0,Math.floor(n.length/4));if(i===0||o===0)return new Uint32Array(0);const s=Math.min(i,Math.floor(t.length/2));if(s===0)return new Uint32Array(0);const a=s*2*Float32Array.BYTES_PER_ELEMENT,l=o*4*Float32Array.BYTES_PER_ELEMENT,c=s*Uint32Array.BYTES_PER_ELEMENT,f=Number(r.device.limits.maxStorageBufferBindingSize);if(a>f||l>f||c>f)return null;const u=r.device.createBuffer({size:kt(a,4),usage:hn|Bt}),h=r.device.createBuffer({size:kt(l,4),usage:hn|Bt}),d=r.device.createBuffer({size:kt(c,4),usage:hn|al}),m=r.device.createBuffer({size:16,usage:ll|Bt}),p=r.device.createBuffer({size:kt(c,4),usage:Bt|cl});let b=!1;try{r.device.queue.writeBuffer(u,0,t.buffer,t.byteOffset,a),r.device.queue.writeBuffer(h,0,n.buffer,n.byteOffset,l),r.device.queue.writeBuffer(m,0,new Uint32Array([s,o,0,0]));const y=r.device.createBindGroup({layout:r.bindGroupLayout,entries:[{binding:0,resource:{buffer:u}},{binding:1,resource:{buffer:h}},{binding:2,resource:{buffer:d}},{binding:3,resource:{buffer:m}}]}),x=r.device.createCommandEncoder(),M=x.beginComputePass();M.setPipeline(r.pipeline),M.setBindGroup(0,y),M.dispatchWorkgroups(Math.ceil(s/256)),M.end(),x.copyBufferToBuffer(d,0,p,0,c),r.device.queue.submit([x.finish()]),await p.mapAsync(ul),b=!0;const S=p.getMappedRange();return new Uint32Array(S.slice(0))}finally{if(b)try{p.unmap()}catch{}u.destroy(),h.destroy(),d.destroy(),m.destroy(),p.destroy()}}async function qi(t,e,n={}){const r=we(),i=n.bridgeToDraw===!0;if(!t||!t.count||!t.positions||!t.paletteIndices)return{data:null,meta:{mode:"hybrid-webgpu",durationMs:we()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}};const o=mt(e??[]);if(o.length===0){const S={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return t.fillModes instanceof Uint8Array&&(S.fillModes=new Uint8Array(0)),t.ids instanceof Uint32Array&&(S.ids=new Uint32Array(0)),{data:S,meta:{mode:"hybrid-webgpu",durationMs:we()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const s=ot(t),a=t.fillModes instanceof Uint8Array&&t.fillModes.length>=s?t.fillModes:null,l=t.ids instanceof Uint32Array&&t.ids.length>=s?t.ids:null;if(s===0){const S={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(S.fillModes=new Uint8Array(0)),l&&(S.ids=new Uint32Array(0)),{data:S,meta:{mode:"hybrid-webgpu",durationMs:we()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const c=new Float32Array(o.length*4);for(let S=0;S<o.length;S+=1){const C=S*4,A=o[S];c[C]=A.minX,c[C+1]=A.minY,c[C+2]=A.maxX,c[C+3]=A.maxY}let f=null,u=!1;try{f=await Zi(t.positions,s,c),u=!!f}catch{f=null,u=!1}if(!f)return{data:Mt(t,e),meta:{mode:"hybrid-webgpu",durationMs:we()-r,usedWebGpu:!1,candidateCount:s,bridgedToDraw:!1}};let h=0;for(let S=0;S<s;S+=1)f[S]===1&&(h+=1);const d=new Uint32Array(h);if(h>0){let S=0;for(let C=0;C<s;C+=1)f[C]===1&&(d[S]=C,S+=1)}if(h===0){if(i){const C={count:s,positions:t.positions.subarray(0,s*2),paletteIndices:t.paletteIndices.subarray(0,s),drawIndices:new Uint32Array(0)};return a&&(C.fillModes=a.subarray(0,s)),l&&(C.ids=l.subarray(0,s)),{data:C,meta:{mode:"hybrid-webgpu",durationMs:we()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!0}}}const S={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(S.fillModes=new Uint8Array(0)),l&&(S.ids=new Uint32Array(0)),{data:S,meta:{mode:"hybrid-webgpu",durationMs:we()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!1}}}if(i){const S=new Uint32Array(h);let C=0;for(let k=0;k<h;k+=1){const U=d[k]??0,Y=t.positions[U*2],P=t.positions[U*2+1];Et(Y,P,o)&&(S[C]=U,C+=1)}const A={count:s,positions:t.positions.subarray(0,s*2),paletteIndices:t.paletteIndices.subarray(0,s),drawIndices:S.subarray(0,C)};return a&&(A.fillModes=a.subarray(0,s)),l&&(A.ids=l.subarray(0,s)),{data:A,meta:{mode:"hybrid-webgpu",durationMs:we()-r,usedWebGpu:!0,candidateCount:h,bridgedToDraw:!0}}}const m=new Float32Array(h*2),p=new Uint16Array(h),b=a?new Uint8Array(h):null,y=l?new Uint32Array(h):null;let x=0;for(let S=0;S<h;S+=1){const C=d[S]??0,A=t.positions[C*2],k=t.positions[C*2+1];Et(A,k,o)&&(m[x*2]=A,m[x*2+1]=k,p[x]=t.paletteIndices[C],b&&(b[x]=a[C]),y&&(y[x]=l[C]),x+=1)}const M={count:x,positions:m.subarray(0,x*2),paletteIndices:p.subarray(0,x)};return b&&(M.fillModes=b.subarray(0,x)),y&&(M.ids=y.subarray(0,x)),{data:M,meta:{mode:"hybrid-webgpu",durationMs:we()-r,usedWebGpu:!0,candidateCount:h,bridgedToDraw:!1}}}class Hi{constructor(e,n){E(this,"worker",null);E(this,"supported",!0);E(this,"requestId",1);E(this,"pendingById",new Map);E(this,"handleMessage",e=>{const n=e.data;if(!n)return;const r=this.pendingById.get(n.id);r&&(this.pendingById.delete(n.id),this.handlers.onResponse(n,r))});E(this,"handleError",()=>{this.supported=!1,this.teardownWorker("worker crashed")});this.createWorker=e,this.handlers=n}beginRequest(e){const n=this.getOrCreateWorker();if(!n)return null;const r=this.requestId++;return this.pendingById.set(r,e),{id:r,worker:n}}cancelRequest(e){const n=this.pendingById.get(e);if(n)return this.pendingById.delete(e),n}terminate(e="worker terminated"){this.teardownWorker(e)}getOrCreateWorker(){if(!this.supported)return null;if(this.worker)return this.worker;try{const e=this.createWorker();return e.addEventListener("message",this.handleMessage),e.addEventListener("error",this.handleError),this.worker=e,e}catch{return this.supported=!1,null}}teardownWorker(e){this.worker&&(this.worker.removeEventListener("message",this.handleMessage),this.worker.removeEventListener("error",this.handleError),this.worker.terminate(),this.worker=null);const n=new Error(e);for(const[,r]of this.pendingById)this.handlers.rejectPending(r,n);this.pendingById.clear()}}const At=new Hi(()=>new Worker(new URL(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/roi-clip-worker-CHxxL_lK.js").href:new URL("assets/roi-clip-worker-CHxxL_lK.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),typeof document>"u"?require("url").pathToFileURL(__filename).href:ft&&ft.tagName.toUpperCase()==="SCRIPT"&&ft.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),{onResponse:(t,e)=>{if(t.type==="roi-clip-failure"){e.reject(new Error(t.error||"worker clip failed"));return}if(t.type==="roi-clip-index-success"){if(e.kind!=="index"){e.reject(new Error("worker response mismatch: expected point data result"));return}const l=Math.max(0,Math.floor(t.count)),c=new Uint32Array(t.indices).subarray(0,l);e.resolve({indices:c,meta:{mode:"worker",durationMs:Number.isFinite(t.durationMs)?t.durationMs:we()-e.startMs}});return}if(e.kind!=="data"){e.reject(new Error("worker response mismatch: expected index result"));return}const n=Math.max(0,Math.floor(t.count)),r=new Float32Array(t.positions),i=new Uint16Array(t.paletteIndices),o=t.fillModes?new Uint8Array(t.fillModes):null,s=t.ids?new Uint32Array(t.ids):null,a={count:n,positions:r.subarray(0,n*2),paletteIndices:i.subarray(0,n)};o&&(a.fillModes=o.subarray(0,n)),s&&(a.ids=s.subarray(0,n)),e.resolve({data:a,meta:{mode:"worker",durationMs:Number.isFinite(t.durationMs)?t.durationMs:we()-e.startMs}})},rejectPending:(t,e)=>{t.reject(e)}});function dl(){At.terminate("worker terminated")}async function $i(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return{data:null,meta:{mode:"worker",durationMs:0}};const n=ot(t),r=t.positions.slice(0,n*2),i=t.paletteIndices.slice(0,n),o=t.fillModes instanceof Uint8Array&&t.fillModes.length>=n?t.fillModes.slice(0,n):null,s=t.ids instanceof Uint32Array&&t.ids.length>=n?t.ids.slice(0,n):null;return new Promise((a,l)=>{const c=we(),f=At.beginRequest({kind:"data",resolve:a,reject:l,startMs:c});if(!f){a({data:Mt(t,e),meta:{mode:"sync",durationMs:we()-c}});return}const u={type:"roi-clip-request",id:f.id,count:n,positions:r.buffer,paletteIndices:i.buffer,fillModes:o?.buffer,ids:s?.buffer,polygons:e??[]},h=[r.buffer,i.buffer];o&&h.push(o.buffer),s&&h.push(s.buffer);try{f.worker.postMessage(u,h)}catch(d){const m=At.cancelRequest(f.id);m?m.reject(d):l(d)}})}async function ml(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return{indices:new Uint32Array(0),meta:{mode:"worker",durationMs:0}};const n=ot(t),r=t.positions.slice(0,n*2);return new Promise((i,o)=>{const s=we(),a=At.beginRequest({kind:"index",resolve:i,reject:o,startMs:s});if(!a){i({indices:Vi(t,e),meta:{mode:"sync",durationMs:we()-s}});return}const l={type:"roi-clip-index-request",id:a.id,count:n,positions:r.buffer,polygons:e??[]};try{a.worker.postMessage(l,[r.buffer])}catch(c){const f=At.cancelRequest(a.id);f?f.reject(c):o(c)}})}const gl={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};function pl(t,e,n,r,i){const o=g.useRef(0),[s,a]=g.useState(n),l=g.useMemo(()=>r.map(c=>dt(c.coordinates)).filter(c=>c!=null),[r]);return g.useEffect(()=>{const c=++o.current;let f=!1;if(!t)return a(n),()=>{f=!0};if(!n||!n.count||!n.positions||!n.paletteIndices)return a(null),()=>{f=!0};if(l.length===0)return a(gl),i?.({mode:e,durationMs:0,inputCount:n.count,outputCount:0,polygonCount:0}),()=>{f=!0};const u=(d,m)=>{if(f||c!==o.current)return;const p=n.count,b=d?.drawIndices?d.drawIndices.length:d?.count??0;a(d),i?.({mode:m.mode,durationMs:m.durationMs,inputCount:p,outputCount:b,polygonCount:l.length,usedWebGpu:m.usedWebGpu,candidateCount:m.candidateCount,bridgedToDraw:m.bridgedToDraw})};return(async()=>{if(e==="sync"){const d=performance.now(),m=Mt(n,l);u(m,{mode:"sync",durationMs:performance.now()-d});return}if(e==="hybrid-webgpu"){const d=await qi(n,l,{bridgeToDraw:!0});u(d.data,{mode:d.meta.mode,durationMs:d.meta.durationMs,usedWebGpu:d.meta.usedWebGpu,candidateCount:d.meta.candidateCount,bridgedToDraw:d.meta.bridgedToDraw});return}try{const d=await $i(n,l);u(d.data,{mode:d.meta.mode,durationMs:d.meta.durationMs})}catch{const d=performance.now(),m=Mt(n,l);u(m,{mode:"sync",durationMs:performance.now()-d})}})(),()=>{f=!0}},[t,e,n,l,i]),s}const yl=24,bl=1024,xl=4,Vt=-1;function yt(t,e,n){return(t*73856093^e*19349663)>>>0&n}function wl(t,e,n){if(t<=0||e<=0||n<=0)return 256;const r=Math.max(1,t*e),o=Math.sqrt(r/Math.max(1,n))*xl;return Math.max(yl,Math.min(bl,o))}function Sl(t,e){if(!(t instanceof Uint32Array)||t.length===0)return null;let n=!0;for(let o=0;o<t.length;o+=1)if(!(t[o]<e)){n=!1;break}if(n)return t;const r=new Uint32Array(t.length);let i=0;for(let o=0;o<t.length;o+=1)t[o]>=e||(r[i]=t[o],i+=1);return i>0?r.subarray(0,i):null}function El(t){const e=Math.max(0,Math.floor(t.count)),n=Math.floor(t.positions.length/2),r=Math.max(0,Math.min(e,n));if(r<=0)return null;const i=Sl(t.drawIndices??null,r),o=i?i.length:r;if(o===0)return null;const s=wl(t.sourceWidth,t.sourceHeight,o),a=1/s,l=new Int32Array(o),c=new Int32Array(o);let f=0;if(i)for(let F=0;F<o;F+=1){const W=i[F],$=t.positions[W*2],z=t.positions[W*2+1];!Number.isFinite($)||!Number.isFinite(z)||(l[f]=Math.floor($*a),c[f]=Math.floor(z*a),f+=1)}else for(let F=0;F<r;F+=1){const W=t.positions[F*2],$=t.positions[F*2+1];!Number.isFinite(W)||!Number.isFinite($)||(l[f]=Math.floor(W*a),c[f]=Math.floor($*a),f+=1)}if(f===0)return null;let u=Math.min(f,Math.max(64,f>>>3));(!Number.isFinite(u)||u<=0)&&(u=f);let h=1;for(;h<u*2;)h<<=1;let d=h-1,m=new Int32Array(h*2),p=new Int32Array(h);m.fill(2147483647);let b=0;const y=new Int32Array(f);for(let F=0;F<f;F+=1){const W=l[F],$=c[F];let z=yt(W,$,d);for(;;){const ae=m[z*2];if(ae===2147483647){if(m[z*2]=W,m[z*2+1]=$,p[z]=1,y[F]=z,b+=1,b*4>h*3){const de=h;h<<=1,d=h-1;const J=new Int32Array(h*2),ve=new Int32Array(h);J.fill(2147483647);for(let Ae=0;Ae<de;Ae+=1){if(m[Ae*2]===2147483647)continue;const D=m[Ae*2],v=m[Ae*2+1];let O=yt(D,v,d);for(;J[O*2]!==2147483647;)O=O+1&d;J[O*2]=D,J[O*2+1]=v,ve[O]=p[Ae]}for(m=J,p=ve,z=yt(W,$,d);m[z*2]!==W||m[z*2+1]!==$;)z=z+1&d;y[F]=z}break}if(ae===W&&m[z*2+1]===$){p[z]+=1,y[F]=z;break}z=z+1&d}}const x=new Int32Array(b*2),M=new Uint32Array(b),S=new Uint32Array(b),C=new Int32Array(h);C.fill(Vt);let A=0,k=0;for(let F=0;F<h;F+=1)m[F*2]!==2147483647&&(x[A*2]=m[F*2],x[A*2+1]=m[F*2+1],M[A]=k,S[A]=p[F],C[F]=A,k+=p[F],A+=1);const U=new Uint32Array(f),Y=new Uint32Array(b);if(Y.set(M),i)for(let F=0;F<f;F+=1){const W=C[y[F]];U[Y[W]]=i[F],Y[W]+=1}else{let F=0;for(let W=0;W<r;W+=1){const $=t.positions[W*2],z=t.positions[W*2+1];if(!Number.isFinite($)||!Number.isFinite(z))continue;const ae=C[y[F]];U[Y[ae]]=W,Y[ae]+=1,F+=1}}let P=1;for(;P<b*2;)P<<=1;const T=P-1,L=new Int32Array(P);L.fill(Vt);for(let F=0;F<b;F+=1){const W=x[F*2],$=x[F*2+1];let z=yt(W,$,T);for(;L[z]!==Vt;)z=z+1&T;L[z]=F}return{cellSize:s,safeCount:r,cellCount:b,hashCapacity:P,hashTable:L,cellKeys:x,cellOffsets:M,cellLengths:S,pointIndices:U}}function Ki(t,e,n){const{hashTable:r,cellKeys:i,hashMask:o}=t;let s=yt(e,n,o);for(;;){const a=r[s];if(a===Vt)return-1;if(i[a*2]===e&&i[a*2+1]===n)return a;s=s+1&o}}function Rl(t,e){if(t.safeCount<=0||t.cellCount<=0)return null;const n=t.safeCount;return{cellSize:t.cellSize,safeCount:n,positions:e.positions.subarray(0,n*2),ids:e.ids instanceof Uint32Array&&e.ids.length>=n?e.ids.subarray(0,n):null,hashCapacity:t.hashCapacity,hashMask:t.hashCapacity-1,hashTable:new Int32Array(t.hashTable),cellKeys:new Int32Array(t.cellKeys),cellOffsets:new Uint32Array(t.cellOffsets),cellLengths:new Uint32Array(t.cellLengths),pointIndices:new Uint32Array(t.pointIndices)}}const In=new Hi(()=>new Worker(new URL(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/point-hit-index-worker-CNFA6pZm.js").href:new URL("assets/point-hit-index-worker-CNFA6pZm.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),typeof document>"u"?require("url").pathToFileURL(__filename).href:ft&&ft.tagName.toUpperCase()==="SCRIPT"&&ft.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),{onResponse:(t,e)=>{if(t.type==="point-hit-index-failure"){e.reject(new Error(t.error||"worker index build failed"));return}e.resolve(Rl(t,e.pointData))},rejectPending:(t,e)=>{t.reject(e)}});function Ml(){In.terminate("worker terminated")}function Al(t,e){const n=ot(t);if(n<=0)return null;const r=t.positions.subarray(0,n*2),i=El({count:n,positions:r,drawIndices:t.drawIndices instanceof Uint32Array?t.drawIndices:null,sourceWidth:e?.width??0,sourceHeight:e?.height??0});return i?{cellSize:i.cellSize,safeCount:n,positions:r,ids:t.ids instanceof Uint32Array&&t.ids.length>=n?t.ids.subarray(0,n):null,hashCapacity:i.hashCapacity,hashMask:i.hashCapacity-1,hashTable:i.hashTable,cellKeys:i.cellKeys,cellOffsets:i.cellOffsets,cellLengths:i.cellLengths,pointIndices:i.pointIndices}:null}async function ji(t,e){if(!t||!t.positions||!t.paletteIndices)return null;const n=ot(t);return n<=0?null:new Promise((r,i)=>{const o={resolve:r,reject:i,pointData:t},s=In.beginRequest(o);if(!s||!s.worker){r(Al(t,e));return}const a=t.positions.slice(0,n*2),l=t.drawIndices instanceof Uint32Array&&t.drawIndices.length>0?t.drawIndices.slice():void 0,c={type:"point-hit-index-request",id:s.id,count:n,positions:a.buffer,drawIndices:l?.buffer,sourceWidth:e?.width??0,sourceHeight:e?.height??0},f=[a.buffer];l&&f.push(l.buffer);try{s.worker.postMessage(c,f)}catch(u){const h=In.cancelRequest(s.id);h?h.reject(u):i(u)}})}const Cl=.65,Pl=4;function vl(t,e,n,r,i,o,s,a){const l=!!(n||r||i),[c,f]=g.useState(null),u=g.useRef(null),h=g.useRef(null);g.useEffect(()=>{if(!l||!t){f(null);return}let b=!1;return ji(t,e).then(y=>{b||f(y)}),()=>{b=!0}},[l,t,e]);const d=g.useCallback(b=>{const y=s.current;if(!y||!c)return null;const x=Number(b[0]),M=Number(b[1]);if(!Number.isFinite(x)||!Number.isFinite(M))return null;const S=Math.max(1e-6,y.getViewState().zoom),C=y.getPointSize(a),k=Math.max(Pl,C*Cl)/S;if(!Number.isFinite(k)||k<=0)return null;const{cellSize:U,cellOffsets:Y,cellLengths:P,pointIndices:T,positions:L,safeCount:F}=c,W=Math.floor(x/U),$=Math.floor(M/U),z=Math.max(1,Math.ceil(k/U)),ae=k*k;let de=-1,J=ae,ve=0,Ae=0;for(let v=W-z;v<=W+z;v+=1)for(let O=$-z;O<=$+z;O+=1){const oe=Ki(c,v,O);if(oe<0)continue;const q=Y[oe],pe=q+P[oe];for(let le=q;le<pe;le+=1){const ne=T[le];if(ne>=F)continue;const Fe=L[ne*2],ue=L[ne*2+1],ye=Fe-x,me=ue-M,re=ye*ye+me*me;re>J||(J=re,de=ne,ve=Fe,Ae=ue)}}if(de<0)return null;const D=c.ids?Number(c.ids[de]):null;return{index:de,id:D,coordinate:[x,M],pointCoordinate:[ve,Ae]}},[a,c]),m=g.useCallback((b,y)=>{if(!n)return;const x=b?.index??null,M=b?.id??null;u.current===x&&h.current===M||(u.current=x,h.current=M,n({index:x,id:M,coordinate:y,pointCoordinate:b?.pointCoordinate??null}))},[n]),p=g.useCallback((b,y)=>{if(!r)return;const x=d(b);x&&r({...x,button:y})},[r,d]);return g.useEffect(()=>{if(i)return i.current=d,()=>{i.current===d&&(i.current=null)}},[i,d]),g.useEffect(()=>{const b=u.current;b!==null&&(c&&b<c.safeCount||(u.current=null,h.current=null,n?.({index:null,id:null,coordinate:null,pointCoordinate:null})))},[c,n]),g.useEffect(()=>{},[o,n]),{getCellByCoordinates:d,emitPointHover:m,emitPointClick:p}}let Tl=0;const Il=g.forwardRef(function({data:e=null,palette:n=null,sizeByZoom:r,sizeByMagnification:i,weightByMagnification:o,opacity:s,strokeScale:a,innerFillOpacity:l,innerFillColor:c,clipEnabled:f=!1,clipToRegions:u,clipMode:h="worker",onClipStats:d,onHover:m,onClick:p,dashed:b},y){const{rendererRef:x,rendererSerial:M,source:S}=st(),C=g.useRef(null),A=g.useRef(`__point_layer__${Tl++}`),U=pl(f,h,e,u??_l,d),{getCellByCoordinates:Y}=vl(U,S,m,p,C,"cursor",x,A.current);return g.useImperativeHandle(y,()=>({queryAt:Y}),[Y]),g.useEffect(()=>{const P=x.current;if(!P)return;const T=A.current;return P.registerPointLayer(T),()=>{P.unregisterPointLayer(T)}},[x,M]),g.useEffect(()=>{const P=x.current;P&&P.setPointPalette(n,A.current)},[M,n,x]),g.useEffect(()=>{const P=x.current;P&&P.setPointLineDash(b,A.current)},[M,b,x]),g.useEffect(()=>{const P=x.current;P&&P.setPointSizeByZoom(r,A.current)},[M,r,x]),g.useEffect(()=>{const P=x.current;P&&P.setPointSizeByMagnification(i,A.current)},[M,i,x]),g.useEffect(()=>{const P=x.current;P&&P.setPointWeightByMagnification(o,A.current)},[M,o,x]),g.useEffect(()=>{const P=x.current;!P||s===void 0||P.setPointOpacity(s,A.current)},[M,s,x]),g.useEffect(()=>{const P=x.current;!P||a===void 0||P.setPointStrokeScale(a,A.current)},[M,a,x]),g.useEffect(()=>{const P=x.current;!P||l===void 0||P.setPointInnerFillOpacity(l,A.current)},[M,l,x]),g.useEffect(()=>{const P=x.current;P&&P.setPointInnerFillColor(c,A.current)},[M,c,x]),g.useEffect(()=>{const P=x.current;P&&P.setPointData(U,A.current)},[M,U,x]),null}),_l=[],Fl=180,Vr=20;function Ll(t){const e=_(t,0,1);return e*e*(3-2*e)}function Dl(t,e,n){const[r,i]=g.useState(0),o=g.useRef(0),s=g.useRef({rafId:null,startMs:0,from:0,to:0}),a=g.useCallback(u=>{const h=_(u,0,Vr);Math.abs(o.current-h)<1e-4||(o.current=h,i(h))},[]),l=g.useCallback(()=>{const u=s.current;u.rafId!==null&&(cancelAnimationFrame(u.rafId),u.rafId=null)},[]),c=g.useCallback(u=>{const h=_(u,0,Vr),d=s.current,m=o.current;if(Math.abs(m-h)<1e-4){l(),d.to=h,a(h);return}l(),d.startMs=performance.now(),d.from=m,d.to=h;const p=b=>{const y=s.current,x=Math.max(0,b-y.startMs),M=_(x/Fl,0,1),S=Ll(M),C=y.from+(y.to-y.from)*S;if(a(C),n.current?.(),M>=1){y.rafId=null,a(y.to);return}y.rafId=requestAnimationFrame(p)};d.rafId=requestAnimationFrame(p)},[a,l]),f=g.useCallback(u=>{const h=e.current;if(!h||typeof u!="number"||!Number.isFinite(u)){c(0);return}const d=Xn(t,u,h.getZoomRange(),h.getRegionLabelAutoLiftCapZoom());c(d)},[t,c]);return g.useEffect(()=>()=>{l()},[l]),{regionLabelAutoLiftOffsetPx:r,syncRegionLabelAutoLiftTarget:f,cancelRegionLabelAutoLiftAnimation:l,applyRegionLabelAutoLiftOffset:a}}const Nl=6;function _n(t,e){return t.id??e}function zl(t,e,n,r,i,o){const s=i-n,a=o-r,l=s*s+a*a;if(l<=1e-12){const m=t-n,p=e-r;return m*m+p*p}const c=_(((t-n)*s+(e-r)*a)/l,0,1),f=n+s*c,u=r+a*c,h=t-f,d=e-u;return h*h+d*d}function Gr(t,e,n,r){for(let i=1;i<n.length;i+=1){const o=n[i-1],s=n[i];if(zl(t,e,o[0],o[1],s[0],s[1])<=r)return!0}return!1}function Bl(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(Gr(t,e,n.outer,i))return!0;for(const o of n.holes)if(Gr(t,e,o,i))return!0;return!1}function kl(t,e,n,r,i,o,s,a){if(!t.label)return!1;const l=On(t.polygons,S=>{const C=[];for(let A=0;A<S.length;A+=1){const k=Bn(n.worldToScreen(S[A][0],S[A][1]));if(!k)return[];C.push(k)}return C},r);if(!l)return!1;const f=Un(t.label,i)+i.paddingX*2,u=i.fontSize+i.paddingY*2,h=l[0],d=l[1]-i.offsetY,m=a?_(h,f*.5+1,o-f*.5-1):h,p=a?_(d,u*.5+1,s-u*.5-1):d,b=m-f*.5,y=m+f*.5,x=p-u*.5,M=p+u*.5;return e[0]>=b&&e[0]<=y&&e[1]>=x&&e[1]<=M}function Ul(t){const e=[];for(let n=0;n<t.length;n+=1){const r=t[n],i=mt([dt(r?.coordinates)]);if(i.length===0)continue;const o=typeof r?.label=="string"?r.label.trim():"";e.push({region:r,regionIndex:n,regionId:_n(r,n),polygons:i,label:o})}return e}function Zr(t,e,n,r,i,o,s,a,l,c,f=!0){const u=t[0],h=t[1],d=Math.max(1e-6,r.getViewState().zoom),m=Math.max(0,a),p=Nl/d;for(let b=n.length-1;b>=0;b-=1){const y=n[b];for(const M of y.polygons)if(Bl(u,h,M,p))return{region:y.region,regionIndex:y.regionIndex,regionId:y.regionId};let x=Yn(o,s?.({region:y.region,regionId:y.regionId,regionIndex:y.regionIndex,zoom:d}));if(m>0&&(x={...x,offsetY:x.offsetY+m}),!!kl(y,e,r,i,x,l,c,f))return{region:y.region,regionIndex:y.regionIndex,regionId:y.regionId}}return null}const qr=[],Ol=[];let Wl=0;function Yl(t){return{color:bi,width:xi,lineDash:it,lineJoin:t.lineJoin,lineCap:t.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function Xl({regions:t,polygons:e,strokeStyle:n,hoverStrokeStyle:r,activeStrokeStyle:i,resolveStrokeStyle:o,labelStyle:s,labelAnchor:a="top-center",autoLiftLabelAtMaxZoom:l=!1,clampLabelToViewport:c=!0,hoveredRegionId:f,activeRegionId:u,interactive:h=!0,onActiveChange:d,onHover:m,onClick:p}){const{rendererRef:b,rendererSerial:y,canvasRef:x,containerRef:M,registerDrawCallback:S,unregisterDrawCallback:C,requestOverlayRedraw:A,drawInvalidateRef:k,registerViewStateListener:U,screenToWorld:Y,worldToScreen:P,isInteractionLocked:T}=st(),L=t??qr,F=e??Ol,W=g.useMemo(()=>L.length>0?L:F.length===0?qr:F.map((V,K)=>({id:K,coordinates:V})),[L,F]),[$,z]=g.useState(()=>f??null),[ae,de]=g.useState(()=>u??null),J=f!==void 0,ve=u!==void 0,Ae=J?f??null:$,D=ve?u??null:ae,v=g.useRef(f??null),O=g.useRef(null),oe=g.useRef(null);if(O.current===null||oe.current===null){const V=Wl++;O.current=`__region_layer__${V}`,oe.current=`__region_label__${V}`}g.useEffect(()=>{ve&&de(u??null)},[ve,u]),g.useEffect(()=>{if(!J)return;const V=f??null;v.current=V,z(V)},[J,f]);const q=g.useCallback(V=>{String(D)!==String(V)&&(ve||de(V),d?.(V))},[D,ve,d]),{regionLabelAutoLiftOffsetPx:pe,syncRegionLabelAutoLiftTarget:le}=Dl(l,b,k),ne=g.useMemo(()=>kn(n),[n]),Fe=g.useMemo(()=>Ke(ne,r),[ne,r]),ue=g.useMemo(()=>Ke(ne,i),[ne,i]),{staticLabelStyle:ye,labelStyleResolver:me}=g.useMemo(()=>typeof s=="function"?{staticLabelStyle:void 0,labelStyleResolver:s}:{staticLabelStyle:s,labelStyleResolver:void 0},[s]),re=g.useMemo(()=>Wn(ye),[ye]),se=g.useMemo(()=>{const V=[];for(let K=0;K<W.length;K+=1){const fe=W[K],te=Jt(fe.coordinates);te.length!==0&&V.push({region:fe,regionIndex:K,regionKey:fe.id??K,polygons:te})}return V},[W]),ce=g.useMemo(()=>Ul(W),[W]);g.useEffect(()=>{const V=b.current;if(V)return le(V.getViewState().zoom),U(K=>{le(K.zoom)})},[y,U,le]),g.useEffect(()=>{!(D===null?!0:W.some((te,j)=>String(_n(te,j))===String(D)))&&D!==null&&q(null);const K=v.current;!(K===null?!0:W.some((te,j)=>String(_n(te,j))===String(K)))&&K!==null&&(v.current=null,J||z(null),m?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[W,D,J,m,q]);const Z=g.useCallback(V=>{const K=b.current;if(!K||V.length===0)return[];const fe=new Array(V.length);for(let te=0;te<V.length;te+=1){const j=qe(K.worldToScreen(V[te][0],V[te][1]));if(!j)return[];fe[te]=j}return fe},[]),Pe=g.useRef({preparedRegions:se,hoveredRegionId:Ae,activeRegionId:D,resolvedStrokeStyle:ne,resolvedHoverStrokeStyle:Fe,resolvedActiveStrokeStyle:ue,resolveStrokeStyleProp:o,worldToScreenPoints:Z});Pe.current={preparedRegions:se,hoveredRegionId:Ae,activeRegionId:D,resolvedStrokeStyle:ne,resolvedHoverStrokeStyle:Fe,resolvedActiveStrokeStyle:ue,resolveStrokeStyleProp:o,worldToScreenPoints:Z},g.useEffect(()=>{const V=fe=>{const{preparedRegions:te,hoveredRegionId:j,activeRegionId:Re,resolvedStrokeStyle:X,resolvedHoverStrokeStyle:Te,resolvedActiveStrokeStyle:De,resolveStrokeStyleProp:B,worldToScreenPoints:H}=Pe.current;for(const Q of te){const{region:ee,polygons:Se,regionIndex:xe,regionKey:Me}=Q,Ne=jt(Re,Me)?"active":jt(j,Me)?"hover":"default";let w=Ne==="active"?De:Ne==="hover"?Te:X;if(B){const I=B({region:ee,regionId:Me,regionIndex:xe,state:Ne});w=Ke(w,I||void 0)}const R=Ne==="default"?null:Yl(w);for(const I of Se){const N=H(I.outer);N.length>=4&&(R&&ke(fe,N,R,!0,!1),ke(fe,N,w,!0,!1));for(const G of I.holes){const ge=H(G);ge.length>=4&&(R&&ke(fe,ge,R,!0,!1),ke(fe,ge,w,!0,!1))}}}},K=O.current;if(K)return S(K,10,V),()=>C(K)},[S,C]);const Ee=g.useRef({preparedRegions:se,resolvedLabelStyle:re,labelStyleResolver:me,labelAnchor:a,autoLiftLabelAtMaxZoom:l,clampLabelToViewport:c,regionLabelAutoLiftOffsetPx:pe,rendererRef:b});Ee.current={preparedRegions:se,resolvedLabelStyle:re,labelStyleResolver:me,labelAnchor:a,autoLiftLabelAtMaxZoom:l,clampLabelToViewport:c,regionLabelAutoLiftOffsetPx:pe,rendererRef:b},g.useEffect(()=>{const V=(fe,te,j)=>{const{preparedRegions:Re,resolvedLabelStyle:X,labelStyleResolver:Te,labelAnchor:De,autoLiftLabelAtMaxZoom:B,clampLabelToViewport:H,regionLabelAutoLiftOffsetPx:Q,rendererRef:ee}=Ee.current;if(Re.length===0)return;const Se=Math.max(1e-6,ee.current?.getViewState?.().zoom??1),xe=typeof Q=="number"&&Number.isFinite(Q)?Math.max(0,Q):Xn(B,Se,ee.current?.getZoomRange?.(),ee.current?.getRegionLabelAutoLiftCapZoom?.());for(const Me of Re){if(!Me.region.label)continue;const Ne=On(Me.polygons,R=>{const I=ee.current;if(!I)return[];const N=[];for(let G=0;G<R.length;G+=1){const ge=qe(I.worldToScreen(R[G][0],R[G][1]));if(!ge)return[];N.push(ge)}return N},De);if(!Ne)continue;let w=Yn(X,Te?.({region:Me.region,regionId:Me.regionKey,regionIndex:Me.regionIndex,zoom:Se}));xe>0&&(w={...w,offsetY:w.offsetY+xe}),Ai(fe,Me.region.label,Ne,te,j,w,H)}},K=oe.current;if(K)return S(K,50,V),()=>C(K)},[S,C]),g.useEffect(()=>{A()},[se,Ae,D,ne,re,pe,A]);const be=g.useRef({preparedRegionHits:ce,labelAnchor:a,resolvedLabelStyle:re,labelStyleResolver:me,regionLabelAutoLiftOffsetPx:pe,clampLabelToViewport:c,onHover:m,onClick:p,commitActive:q});return be.current={preparedRegionHits:ce,labelAnchor:a,resolvedLabelStyle:re,labelStyleResolver:me,regionLabelAutoLiftOffsetPx:pe,clampLabelToViewport:c,onHover:m,onClick:p,commitActive:q},g.useEffect(()=>{if(!h)return;const V=M.current;if(!V)return;const K=j=>{if(T())return;const Re=b.current;if(!Re)return;const{preparedRegionHits:X,labelAnchor:Te,resolvedLabelStyle:De,labelStyleResolver:B,regionLabelAutoLiftOffsetPx:H,clampLabelToViewport:Q,onHover:ee}=be.current,Se=Y(j.clientX,j.clientY);if(!Se)return;let xe=null,Me=null;if(X.length>0){const w=P(Se[0],Se[1]);if(w){const R=x.current?.getBoundingClientRect();Me=Zr(Se,w,X,Re,Te,De,B,typeof H=="number"?H:0,R?.width??0,R?.height??0,Q),xe=Me?.regionId??null}}const Ne=v.current;String(Ne)!==String(xe)&&(v.current=xe,J||z(xe),ee?.({region:Me?.region??null,regionId:xe,regionIndex:Me?.regionIndex??-1,coordinate:Se}),A())},fe=j=>{if(T())return;const Re=b.current;if(!Re)return;const{preparedRegionHits:X,labelAnchor:Te,resolvedLabelStyle:De,labelStyleResolver:B,regionLabelAutoLiftOffsetPx:H,clampLabelToViewport:Q,onClick:ee,commitActive:Se}=be.current;if(X.length===0)return;const xe=Y(j.clientX,j.clientY);if(!xe)return;const Me=P(xe[0],xe[1]);if(!Me)return;const Ne=x.current?.getBoundingClientRect(),w=Zr(xe,Me,X,Re,Te,De,B,typeof H=="number"?H:0,Ne?.width??0,Ne?.height??0,Q),R=w?.regionId??null;Se(R),w&&ee&&ee({region:w.region,regionId:w.regionId,regionIndex:w.regionIndex,coordinate:xe})},te=()=>{v.current!==null&&(v.current=null,J||z(null),be.current.onHover?.({region:null,regionId:null,regionIndex:-1,coordinate:null}),A())};return V.addEventListener("pointermove",K),V.addEventListener("click",fe),V.addEventListener("pointerleave",te),()=>{V.removeEventListener("pointermove",K),V.removeEventListener("click",fe),V.removeEventListener("pointerleave",te)}},[M,b,x,h,J,Y,P,T,A]),null}function Vl({imageWidth:t,imageHeight:e,tiles:n,viewState:r,className:i,style:o}){const s=g.useRef(null),a=g.useRef(null),l=g.useMemo(()=>({width:"100%",height:"100%",display:"block",...o}),[o]);return g.useEffect(()=>{const c=s.current;if(!c)return;const f=new ui({canvas:c,imageWidth:t,imageHeight:e,initialViewState:r});return a.current=f,f.setTiles(n),()=>{f.destroy(),a.current=null}},[t,e]),g.useEffect(()=>{const c=a.current;c&&c.setTiles(n)},[n]),g.useEffect(()=>{const c=a.current;!c||!r||c.setViewState(r)},[r]),Ge.jsx("canvas",{ref:s,className:i,style:l})}function Gl(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 Qi{constructor(e){E(this,"maxConcurrency");E(this,"maxRetries");E(this,"retryBaseDelayMs");E(this,"retryMaxDelayMs");E(this,"onTileLoad");E(this,"onTileError");E(this,"onStateChange");E(this,"authToken");E(this,"destroyed",!1);E(this,"queue",[]);E(this,"queuedByKey",new Map);E(this,"inflight",new Map);E(this,"visibleKeys",new Set);E(this,"timerId",null);E(this,"abortedCount",0);E(this,"retryCount",0);E(this,"failedCount",0);this.maxConcurrency=Math.max(1,Math.floor(e.maxConcurrency??12)),this.maxRetries=Math.max(0,Math.floor(e.maxRetries??2)),this.retryBaseDelayMs=Math.max(10,Math.floor(e.retryBaseDelayMs??120)),this.retryMaxDelayMs=Math.max(this.retryBaseDelayMs,Math.floor(e.retryMaxDelayMs??1200)),this.authToken=e.authToken??"",this.onTileLoad=e.onTileLoad,this.onTileError=e.onTileError,this.onStateChange=e.onStateChange}setAuthToken(e){this.authToken=String(e??"")}schedule(e){if(this.destroyed)return;const n=new Set;for(const r of e)n.add(r.key);this.visibleKeys=n,this.dropInvisibleQueued(n),this.abortInvisibleInflight(n);for(const r of e){if(this.inflight.has(r.key)){const s=this.inflight.get(r.key);s&&(s.tile=r);continue}const i=this.queuedByKey.get(r.key);if(i){i.tile=r;continue}const o={tile:r,attempt:0,readyAt:we()};this.queue.push(o),this.queuedByKey.set(r.key,o)}this.sortQueue(),this.pump(),this.emitStateChange()}clear(){this.clearPumpTimer(),this.visibleKeys.clear(),this.queue=[],this.queuedByKey.clear();for(const[,e]of this.inflight)e.controller.abort();this.inflight.clear(),this.emitStateChange()}destroy(){this.destroyed||(this.destroyed=!0,this.clear())}getInflightCount(){return this.inflight.size}getSnapshot(){return{inflight:this.inflight.size,queued:this.queue.length,aborted:this.abortedCount,retries:this.retryCount,failed:this.failedCount}}dropInvisibleQueued(e){if(this.queue.length===0)return;const n=[];for(const r of this.queue){if(!e.has(r.tile.key)){this.queuedByKey.delete(r.tile.key);continue}n.push(r)}this.queue=n}abortInvisibleInflight(e){for(const[n,r]of this.inflight)e.has(n)||(this.inflight.delete(n),this.abortedCount+=1,r.controller.abort())}sortQueue(){this.queue.sort((e,n)=>e.readyAt!==n.readyAt?e.readyAt-n.readyAt:e.tile.distance2!==n.tile.distance2?e.tile.distance2-n.tile.distance2:e.tile.tier!==n.tile.tier?n.tile.tier-e.tile.tier:e.tile.key.localeCompare(n.tile.key))}pump(){if(this.destroyed)return;for(this.clearPumpTimer();this.inflight.size<this.maxConcurrency;){const r=this.takeNextReadyQueueItem();if(!r)break;this.startFetch(r)}if(this.inflight.size>=this.maxConcurrency||this.queue.length===0)return;const e=this.queue[0]?.readyAt;if(typeof e!="number")return;const n=Math.max(0,e-we());this.timerId=globalThis.setTimeout(()=>{this.timerId=null,this.pump()},n)}takeNextReadyQueueItem(){if(this.queue.length===0)return null;const e=we(),n=this.queue[0];return!n||n.readyAt>e?null:(this.queue.shift(),this.queuedByKey.delete(n.tile.key),n)}startFetch(e){const n=new AbortController,r={tile:e.tile,attempt:e.attempt,controller:n};this.inflight.set(e.tile.key,r),this.emitStateChange();const i=Gl(e.tile.url,this.authToken);fetch(e.tile.url,{signal:n.signal,headers:i?{Authorization:this.authToken}:void 0}).then(o=>{if(!o.ok)throw new Error(`HTTP ${o.status}`);return o.blob()}).then(o=>createImageBitmap(o)).then(o=>{if(this.destroyed||n.signal.aborted){o.close();return}if(!this.visibleKeys.has(e.tile.key)){o.close();return}this.onTileLoad(e.tile,o)}).catch(o=>{if(n.signal.aborted||this.destroyed)return;if(e.attempt<this.maxRetries&&this.visibleKeys.has(e.tile.key)){this.retryCount+=1;const a=e.attempt+1,l=this.getRetryDelay(a),c={tile:e.tile,attempt:a,readyAt:we()+l},f=this.queuedByKey.get(e.tile.key);f?(f.tile=c.tile,f.readyAt=Math.min(f.readyAt,c.readyAt),f.attempt=Math.max(f.attempt,c.attempt)):(this.queue.push(c),this.queuedByKey.set(c.tile.key,c)),this.sortQueue();return}this.failedCount+=1,this.onTileError?.(e.tile,o,e.attempt+1)}).finally(()=>{this.inflight.delete(e.tile.key),this.pump(),this.emitStateChange()})}getRetryDelay(e){const n=Math.max(0,e-1),r=Math.min(this.retryMaxDelayMs,this.retryBaseDelayMs*2**n),i=.85+Math.random()*.3;return Math.round(r*i)}clearPumpTimer(){this.timerId!==null&&(globalThis.clearTimeout(this.timerId),this.timerId=null)}emitStateChange(){this.onStateChange?.(this.getSnapshot())}}function Zl(t,e){t.addEventListener("pointerdown",e.pointerDown),t.addEventListener("pointermove",e.pointerMove),t.addEventListener("pointerup",e.pointerUp),t.addEventListener("pointercancel",e.pointerUp),t.addEventListener("wheel",e.wheel,{passive:!1}),t.addEventListener("dblclick",e.doubleClick),t.addEventListener("contextmenu",e.contextMenu),t.addEventListener("webglcontextlost",e.contextLost),t.addEventListener("webglcontextrestored",e.contextRestored)}function ql(t,e){t.removeEventListener("pointerdown",e.pointerDown),t.removeEventListener("pointermove",e.pointerMove),t.removeEventListener("pointerup",e.pointerUp),t.removeEventListener("pointercancel",e.pointerUp),t.removeEventListener("wheel",e.wheel),t.removeEventListener("dblclick",e.doubleClick),t.removeEventListener("contextmenu",e.contextMenu),t.removeEventListener("webglcontextlost",e.contextLost),t.removeEventListener("webglcontextrestored",e.contextRestored)}function Hl(t,e,n){const r=t.getBoundingClientRect(),i=Math.max(1,r.width||t.clientWidth||1),o=Math.max(1,r.height||t.clientHeight||1),s=Math.max(1,window.devicePixelRatio||1),a=Math.max(1,Math.round(i*s)),l=Math.max(1,Math.round(o*s));(t.width!==a||t.height!==l)&&(t.width=a,t.height=l),n.setViewport(i,o),e.viewport(0,0,a,l)}const Fn=.35,ht=.5,Hr=256,Ln=[{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}],$l=.1,Kl=5,jl=0,Ql=1,Jl=0,ec=1,tc=-100,nc=100,rc=2e3,Ji=[255,255,255];function on(t){return t*Math.PI/180}function Ut(t,e){return!t||!e?t===e:t.buffer===e.buffer&&t.byteOffset===e.byteOffset&&t.byteLength===e.byteLength}function tn(t){return t.map(e=>({zoom:e.zoom,size:e.size}))}function ic(t){return!t||t.length===0?null:t.map(e=>({magnification:e.magnification,size:e.size}))}function oc(t){return!t||t.length===0?null:t.map(e=>({magnification:e.magnification,weight:e.weight}))}function $r(t){if(!t)return tn(Ln);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?tn(Ln):Array.from(e.entries()).sort((n,r)=>n[0]-r[0]).map(([n,r])=>({zoom:n,size:r}))}function Kr(t){if(!t)return null;const e=new Map;for(const[n,r]of Object.entries(t)){const i=Number(n),o=Number(r);!Number.isFinite(i)||i<=0||!Number.isFinite(o)||o<=0||e.set(i,o)}return e.size===0?null:Array.from(e.entries()).sort((n,r)=>n[0]-r[0]).map(([n,r])=>({magnification:n,size:r}))}function jr(t){if(!t)return null;const e=new Map;for(const[n,r]of Object.entries(t)){const i=Number(n),o=Gt(r);!Number.isFinite(i)||i<=0||e.set(i,o)}return e.size===0?null:Array.from(e.entries()).sort((n,r)=>n[0]-r[0]).map(([n,r])=>({magnification:n,weight:r}))}function sc(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 ac(t,e){if(t===e)return!0;if(!t||!e)return t===e;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1)if(t[n].magnification!==e[n].magnification||t[n].size!==e[n].size)return!1;return!0}function lc(t,e){if(t===e)return!0;if(!t||!e)return t===e;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1)if(t[n].magnification!==e[n].magnification||t[n].weight!==e[n].weight)return!1;return!0}function cc(t,e){if(!Number.isFinite(t))return e[0]?.size??ht;if(e.length===0)return ht;if(e.length===1||t<=e[0].zoom)return e[0].size;for(let s=1;s<e.length;s+=1){const a=e[s-1],l=e[s];if(t>l.zoom)continue;const c=Math.max(1e-6,l.zoom-a.zoom),f=_((t-a.zoom)/c,0,1);return a.size+(l.size-a.size)*f}const n=e[e.length-1],r=e[e.length-2],i=Math.max(1e-6,n.zoom-r.zoom),o=(n.size-r.size)/i;return n.size+(t-n.zoom)*o}function uc(t,e){if(!Number.isFinite(t))return e[0]?.size??ht;if(e.length===0)return ht;if(e.length===1||t<=e[0].magnification)return e[0].size;for(let s=1;s<e.length;s+=1){const a=e[s-1],l=e[s];if(t>l.magnification)continue;const c=Math.max(1e-6,l.magnification-a.magnification),f=_((t-a.magnification)/c,0,1);return a.size+(l.size-a.size)*f}const n=e[e.length-1],r=e[e.length-2],i=Math.max(1e-6,n.magnification-r.magnification),o=(n.size-r.size)/i;return n.size+(t-n.magnification)*o}function fc(t,e){if(!Number.isFinite(t))return e[0]?.weight??1;if(e.length===0)return 1;if(e.length===1||t<=e[0].magnification)return e[0].weight;for(let s=1;s<e.length;s+=1){const a=e[s-1],l=e[s];if(t>l.magnification)continue;const c=Math.max(1e-6,l.magnification-a.magnification),f=_((t-a.magnification)/c,0,1);return a.weight+(l.weight-a.weight)*f}const n=e[e.length-1],r=e[e.length-2],i=Math.max(1e-6,n.magnification-r.magnification),o=(n.weight-r.weight)/i;return n.weight+(t-n.magnification)*o}function Gt(t){return typeof t!="number"||!Number.isFinite(t)?1:_(t,$l,Kl)}function Qr(t){return typeof t!="number"||!Number.isFinite(t)?1:_(t,jl,Ql)}function hc(t){return t?[_(t[0],0,100),_(t[1],0,100)]:[1,0]}function Jr(t){return typeof t!="number"||!Number.isFinite(t)?0:_(t,Jl,ec)}function ei(t){const e=Zo(t,[...Ji,255]);return[e[0],e[1],e[2]]}function dn(t){return typeof t!="number"||!Number.isFinite(t)?0:_(t,tc,nc)}function ti(t){const e=dn(t?.brightness),n=dn(t?.contrast),r=dn(t?.saturation);return{brightness:e/200,contrast:n/100,saturation:r/100}}function Hn(t){return t}function mn(t){return typeof t!="number"||!Number.isFinite(t)?0:_(t,0,rc)}function Ot(t){return typeof t!="number"||!Number.isFinite(t)||t<=0?null:Math.max(1e-6,t)}function gn(t){return typeof t=="function"?t:Hn}function eo(t,e,n){const r=t.getBoundingClientRect(),i=e-r.left-r.width*.5,o=n-r.top-r.height*.5;return Math.atan2(o,i)}function to(t,e){if(e.pointerId!==null&&t.hasPointerCapture(e.pointerId))try{t.releasePointerCapture(e.pointerId)}catch{}e.dragging=!1,e.mode="none",e.rotateLastAngleRad=null,e.pointerId=null,t.classList.remove("dragging")}function dc(t){const{event:e,canvas:n,state:r,config:i,cancelViewAnimation:o}=t,s=i.ctrlDragRotate&&(e.ctrlKey||e.metaKey);(e.button===0||s&&e.button===2)&&(o(),s&&e.preventDefault(),r.dragging=!0,r.mode=s?"rotate":"pan",r.pointerId=e.pointerId,r.lastPointerX=e.clientX,r.lastPointerY=e.clientY,r.rotateLastAngleRad=r.mode==="rotate"?eo(n,e.clientX,e.clientY):null,n.classList.add("dragging"),n.setPointerCapture(e.pointerId))}function mc(t){const{event:e,canvas:n,state:r,config:i,camera:o,clampViewState:s,emitViewState:a,requestRender:l}=t;if(!r.dragging||e.pointerId!==r.pointerId)return;const c=e.clientX-r.lastPointerX,f=e.clientY-r.lastPointerY;if(r.lastPointerX=e.clientX,r.lastPointerY=e.clientY,r.mode==="rotate"){const u=eo(n,e.clientX,e.clientY),h=r.rotateLastAngleRad;if(r.rotateLastAngleRad=u,h!==null){const d=u-h,m=Math.atan2(Math.sin(d),Math.cos(d)),p=i.rotationDragSensitivityDegPerPixel/Fn,b=o.getViewState();o.setViewState({rotationDeg:b.rotationDeg-m*180/Math.PI*p})}}else{const u=o.getViewState(),h=Math.max(1e-6,u.zoom),d=on(u.rotationDeg),m=Math.cos(d),p=Math.sin(d),b=(c*m-f*p)/h,y=(c*p+f*m)/h;o.setViewState({offsetX:u.offsetX-b,offsetY:u.offsetY-y})}s(),a(),l()}function gc(t,e,n){t.pointerId===n.pointerId&&to(e,n)}function pc(t){const{event:e,canvas:n,onZoomBy:r}=t;e.preventDefault();const i=n.getBoundingClientRect(),o=e.clientX-i.left,s=e.clientY-i.top;no(e.deltaY,o,s,r)}const yc=4;function no(t,e,n,r){const i=t<0?1.12:.89;r(i,e,n)}function ro(t,e,n,r,i){const o=t<0?"in":t>0?"out":null;if(o&&r.blockedDirection)if(o!==r.blockedDirection)r.blockedDirection=null,r.accumulatedDelta=0;else return;if(r.accumulatedDelta!==0&&t!==0&&Math.sign(r.accumulatedDelta)!==Math.sign(t)&&(r.accumulatedDelta=0),r.accumulatedDelta+=t,Math.abs(r.accumulatedDelta)<yc)return;const s=r.accumulatedDelta>0?"out":"in";if(r.accumulatedDelta=0,!i(s,e,n)){r.blockedDirection=s;return}r.blockedDirection=null}function bc(t){const{event:e,canvas:n,snapState:r,onSnapZoom:i}=t;e.preventDefault();const o=n.getBoundingClientRect(),s=e.clientX-o.left,a=e.clientY-o.top;ro(e.deltaY,s,a,r,i)}function xc(t){const{event:e,canvas:n,onZoomBy:r}=t,i=n.getBoundingClientRect(),o=e.clientX-i.left,s=e.clientY-i.top;r(e.shiftKey?.8:1.25,o,s)}function wc(t,e){(e||t.ctrlKey||t.metaKey)&&t.preventDefault()}function nn(t){const e=t.getViewCorners();let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[s,a]of e)s<n&&(n=s),s>i&&(i=s),a<r&&(r=a),a>o&&(o=a);return[n,r,i,o]}function Zt(t,e,n=.2,r=.2){const i=nn(t),o=Math.max(1e-6,i[2]-i[0]),s=Math.max(1e-6,i[3]-i[1]),a=o*n,l=s*r,[c,f]=t.getCenter(),u=o*.5,h=s*.5,d=u-a,m=e.width-u+a,p=h-l,b=e.height-h+l,y=d<=m?_(c,d,m):e.width*.5,x=p<=b?_(f,p,b):e.height*.5;t.setCenter(y,x)}function Sc(t,e){const n=Math.max(1e-6,t.getViewState().zoom),r=e.maxTierZoom+Math.log2(n);return _(Math.floor(r),0,e.maxTierZoom)}function Ec(t,e){return!(t[2]<=e[0]||t[0]>=e[2]||t[3]<=e[1]||t[1]>=e[3])}function io(t,e,n){const r=nn(t),i=Math.pow(2,e.maxTierZoom-n),o=Math.ceil(e.width/i),s=Math.ceil(e.height/i),a=Math.max(1,Math.ceil(o/e.tileSize)),l=Math.max(1,Math.ceil(s/e.tileSize)),c=r[0],f=r[1],u=r[2],h=r[3],d=_(Math.floor(c/i/e.tileSize),0,a-1),m=_(Math.floor((u-1)/i/e.tileSize),0,a-1),p=_(Math.floor(f/i/e.tileSize),0,l-1),b=_(Math.floor((h-1)/i/e.tileSize),0,l-1);if(d>m||p>b)return[];const y=(c+u)*.5/i/e.tileSize,x=(f+h)*.5/i/e.tileSize,M=[];for(let S=p;S<=b;S+=1)for(let C=d;C<=m;C+=1){const A=C*e.tileSize*i,k=S*e.tileSize*i,U=Math.min((C+1)*e.tileSize,o)*i,Y=Math.min((S+1)*e.tileSize,s)*i,P=C-y,T=S-x;M.push({key:`${n}/${C}/${S}`,tier:n,x:C,y:S,bounds:[A,k,U,Y],distance2:P*P+T*T,url:qn(e,n,C,S)})}return M.sort((S,C)=>S.distance2-C.distance2),M}function Rc(t,e){const n=Sc(t,e);return{tier:n,visible:io(t,e,n)}}function Mc(t){t.interactionLocked||dc({event:t.event,canvas:t.canvas,state:t.state,config:{ctrlDragRotate:t.ctrlDragRotate,rotationDragSensitivityDegPerPixel:t.rotationDragSensitivityDegPerPixel},cancelViewAnimation:t.cancelViewAnimation})}function Ac(t){t.interactionLocked||mc({event:t.event,canvas:t.canvas,state:t.state,config:{ctrlDragRotate:t.ctrlDragRotate,rotationDragSensitivityDegPerPixel:t.rotationDragSensitivityDegPerPixel},camera:t.camera,clampViewState:()=>Zt(t.camera,t.source,t.panExtentX,t.panExtentY),emitViewState:t.emitViewState,requestRender:t.requestRender})}function Cc(t){t.interactionLocked||gc(t.event,t.canvas,t.state)}function Pc(t){t.interactionLocked||xc({event:t.event,canvas:t.canvas,onZoomBy:t.onZoomBy})}function vc(t){wc(t.event,t.state.dragging)}function Tc(t,e){to(t,e)}function Ic(t){return{pointerDown:e=>Mc({event:e,interactionLocked:t.getInteractionLocked(),canvas:t.canvas,state:t.state,ctrlDragRotate:t.getCtrlDragRotate(),rotationDragSensitivityDegPerPixel:t.getRotationDragSensitivityDegPerPixel(),cancelViewAnimation:t.cancelViewAnimation}),pointerMove:e=>Ac({event:e,interactionLocked:t.getInteractionLocked(),canvas:t.canvas,state:t.state,ctrlDragRotate:t.getCtrlDragRotate(),rotationDragSensitivityDegPerPixel:t.getRotationDragSensitivityDegPerPixel(),camera:t.camera,source:t.source,panExtentX:t.getPanExtentX(),panExtentY:t.getPanExtentY(),emitViewState:t.emitViewState,requestRender:t.requestRender}),pointerUp:e=>Cc({event:e,interactionLocked:t.getInteractionLocked(),canvas:t.canvas,state:t.state}),wheel:e=>{if(t.getInteractionLocked()){e.preventDefault();return}if(t.getUseZoomSnaps?.()&&t.onSnapZoom&&t.zoomSnapState){bc({event:e,canvas:t.canvas,snapState:t.zoomSnapState,onSnapZoom:t.onSnapZoom});return}pc({event:e,canvas:t.canvas,onZoomBy:t.zoomBy})},doubleClick:e=>Pc({event:e,interactionLocked:t.getInteractionLocked(),canvas:t.canvas,onZoomBy:t.zoomBy}),contextMenu:e=>vc({event:e,canvas:t.canvas,state:t.state})}}function _c(t){const{gl:e,cache:n,maxCacheTiles:r}=t;if(n.size<=r)return;const i=Math.max(0,Math.floor(r));for(;n.size>i;){let o=null,s=null;for(const[a,l]of n)(!s||l.lastUsed<s.lastUsed)&&(o=a,s=l);if(!o||!s)break;e.deleteTexture(s.texture),n.delete(o)}}function Fc(t,e){if(t.isContextLost())return null;const n=t.createTexture();return n?(t.bindTexture(t.TEXTURE_2D,n),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,1),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),t.bindTexture(t.TEXTURE_2D,null),n):null}function Lc(t){const{gl:e,cache:n,tile:r,bitmap:i,frameSerial:o,maxCacheTiles:s,destroyed:a,contextLost:l,requestRender:c}=t;if(a||l||e.isContextLost()){i.close();return}if(n.has(r.key)){i.close();return}const f=Fc(e,i);i.close(),f&&(n.set(r.key,{key:r.key,texture:f,bounds:r.bounds,tier:r.tier,lastUsed:o}),_c({gl:e,cache:n,maxCacheTiles:s}),c())}function Dc(t,e){for(const[,n]of e)t.deleteTexture(n.texture)}function Nc(t){const{event:e,destroyed:n,contextLost:r,cancelViewAnimation:i,cancelDrag:o,tileScheduler:s,cache:a,onContextLost:l}=t;if(e.preventDefault(),n||r)return{handled:!1,frame:t.frame};let c=t.frame;return c!==null&&(cancelAnimationFrame(c),c=null),i(),o(),s.clear(),a.clear(),l?.(),{handled:!0,frame:c}}function zc(t){if(t.destroyed)return{didDestroy:!1,frame:t.frame};let e=t.frame;if(e!==null&&(cancelAnimationFrame(e),e=null),t.cancelViewAnimation(),t.resizeObserver.disconnect(),t.removeDprListener(),t.removeCanvasEventListeners(),t.cancelDrag(),t.tileScheduler.destroy(),!t.contextLost&&!t.gl.isContextLost()){Dc(t.gl,t.cache),t.gl.deleteBuffer(t.tileProgram.vbo),t.gl.deleteVertexArray(t.tileProgram.vao),t.gl.deleteProgram(t.tileProgram.program);for(let n=0;n<t.pointPrograms.length;n+=1){const r=t.pointPrograms[n];t.gl.deleteBuffer(r.posBuffer),t.gl.deleteBuffer(r.classBuffer),t.gl.deleteBuffer(r.fillModeBuffer),t.gl.deleteBuffer(r.indexBuffer),t.gl.deleteTexture(r.paletteTexture),t.gl.deleteVertexArray(r.vao),t.gl.deleteProgram(r.program)}}return t.cache.clear(),{didDestroy:!0,frame:e}}function Bc(t,e){if(e<=0||t.length===0)return new Uint32Array(0);let n=t.length;for(let o=0;o<t.length;o+=1)t[o]<e||(n-=1);if(n===t.length)return t;if(n<=0)return new Uint32Array(0);const r=new Uint32Array(n);let i=0;for(let o=0;o<t.length;o+=1){const s=t[o];s>=e||(r[i]=s,i+=1)}return r}function kc(t,e){return e<=0?new Uint8Array(0):t.length<e?new Uint8Array(e):t.subarray(0,e)}function ni(t,e,n,r,i){if(!i||i.length===0)return{...t,lastPointPalette:null};const o=new Uint8Array(i);if(r||e.isContextLost())return{...t,lastPointPalette:o};const s=Math.max(1,Math.floor(o.length/4));return e.bindTexture(e.TEXTURE_2D,n.paletteTexture),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,s,1,0,e.RGBA,e.UNSIGNED_BYTE,o),e.bindTexture(e.TEXTURE_2D,null),{...t,lastPointPalette:o,pointPaletteSize:s}}function ri(t,e,n,r,i){if(!i||!i.count||!i.positions||!i.paletteIndices)return{...t,lastPointData:null,pointCount:0,usePointIndices:!1};const o=i.fillModes instanceof Uint8Array?i.fillModes:null,s=o!==null,a=Math.max(0,Math.min(i.count,Math.floor(i.positions.length/2),i.paletteIndices.length,s?o.length:Number.MAX_SAFE_INTEGER)),l=i.positions.subarray(0,a*2),c=i.paletteIndices.subarray(0,a),f=s?o.subarray(0,a):void 0,u=i.drawIndices instanceof Uint32Array,h=u?Bc(i.drawIndices,a):null,d=t.lastPointData,m=d?.fillModes instanceof Uint8Array,p=t.pointBuffersDirty||!d||d.count!==a||!Ut(d.positions,l)||!Ut(d.paletteIndices,c)||m!==s||s&&(!d?.fillModes||!Ut(d.fillModes,f)),b=t.pointBuffersDirty||u&&(!d?.drawIndices||!Ut(d.drawIndices,h))||!u&&!!d?.drawIndices,y={...t,lastPointData:{count:a,positions:l,paletteIndices:c,fillModes:f,drawIndices:u?h??void 0:void 0}};if(r||e.isContextLost())return y;const x=y.lastPointData;if(!x)return y;if(p){e.bindBuffer(e.ARRAY_BUFFER,n.posBuffer),e.bufferData(e.ARRAY_BUFFER,x.positions,e.STATIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,n.classBuffer),e.bufferData(e.ARRAY_BUFFER,x.paletteIndices,e.STATIC_DRAW);const M=kc(y.zeroFillModes,a);e.bindBuffer(e.ARRAY_BUFFER,n.fillModeBuffer),e.bufferData(e.ARRAY_BUFFER,x.fillModes??M,e.STATIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,null),y.zeroFillModes=M}return u&&b&&(e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n.indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,h??new Uint32Array(0),e.DYNAMIC_DRAW),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),y.usePointIndices=u,y.pointCount=u?h?.length??0:x.count,(p||b)&&(y.pointBuffersDirty=!1),y}function Uc(t){const{gl:e,camera:n,source:r,cache:i,frameSerial:o,tileProgram:s,imageColorSettings:a,pointLayers:l,tileScheduler:c,getVisibleTiles:f,getVisibleTilesForTier:u,getViewBounds:h,intersectsBounds:d}=t;e.clearColor(.03,.06,.1,1),e.clear(e.COLOR_BUFFER_BIT);const{tier:m,visible:p}=f(),b=h(),y=new Set(p.map(P=>P.key));e.useProgram(s.program),e.bindVertexArray(s.vao),e.uniformMatrix3fv(s.uCamera,!1,n.getMatrix()),e.uniform1i(s.uTexture,0),e.uniform1f(s.uBrightness,a.brightness),e.uniform1f(s.uContrast,a.contrast),e.uniform1f(s.uSaturation,a.saturation);const x=[];for(const[,P]of i)y.has(P.key)||d(P.bounds,b)&&x.push(P);x.sort((P,T)=>P.tier-T.tier);for(const P of x)P.lastUsed=o,e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,P.texture),e.uniform4f(s.uBounds,P.bounds[0],P.bounds[1],P.bounds[2],P.bounds[3]),e.drawArrays(e.TRIANGLE_STRIP,0,4);let M=0;const S=[];for(const P of p){const T=i.get(P.key);if(!T){S.push(P);continue}T.lastUsed=o,e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,T.texture),e.uniform4f(s.uBounds,T.bounds[0],T.bounds[1],T.bounds[2],T.bounds[3]),e.drawArrays(e.TRIANGLE_STRIP,0,4),M+=1}const C=S.slice(),A=1e6,k=[];m>0&&k.push(m-1),m<r.maxTierZoom&&k.push(m+1);for(const P of k){const T=u(P);for(const L of T)i.has(L.key)||(L.distance2+=A,C.push(L))}c.schedule(C),e.bindTexture(e.TEXTURE_2D,null),e.bindVertexArray(null);let U=0,Y=0;if(l.length>0){e.enable(e.BLEND),e.blendFunc(e.ONE,e.ONE_MINUS_SRC_ALPHA);for(let P=0;P<l.length;P+=1){const T=l[P];T.pointCount<=0||(e.useProgram(T.pointProgram.program),e.bindVertexArray(T.pointProgram.vao),e.uniformMatrix3fv(T.pointProgram.uCamera,!1,n.getMatrix()),e.uniform1f(T.pointProgram.uPointSize,T.pointSizePx),e.uniform1f(T.pointProgram.uPointCssSize,T.pointCssSizePx),e.uniform2f(T.pointProgram.uPointLineDash,T.pointLineDash[0],T.pointLineDash[1]),e.uniform1f(T.pointProgram.uPointOpacity,T.pointOpacity),e.uniform1f(T.pointProgram.uPointStrokeScale,T.pointStrokeScale),e.uniform1f(T.pointProgram.uPointInnerFillAlpha,T.pointInnerFillOpacity),e.uniform3f(T.pointProgram.uPointInnerFillColor,T.pointInnerFillColor[0],T.pointInnerFillColor[1],T.pointInnerFillColor[2]),e.uniform1f(T.pointProgram.uPaletteSize,T.pointPaletteSize),e.uniform1i(T.pointProgram.uPalette,1),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,T.pointProgram.paletteTexture),T.usePointIndices?e.drawElements(e.POINTS,T.pointCount,e.UNSIGNED_INT,0):e.drawArrays(e.POINTS,0,T.pointCount),U+=T.pointCount,Y+=1)}e.bindTexture(e.TEXTURE_2D,null),e.bindVertexArray(null)}return{tier:m,visible:p.length,rendered:M,points:U,fallback:x.length,cacheHits:M,cacheMisses:S.length,drawCalls:x.length+M+Y}}function ii(t){const r=xt(t,`#version 300 es
|
|
134
|
+
`;function sl(){if(typeof navigator>"u")return!1;const t=navigator;return typeof t.gpu=="object"&&t.gpu!==null}function Gi(){if(!sl())return null;const e=navigator.gpu;if(!e||typeof e!="object")return null;const n=e;return typeof n.requestAdapter!="function"?null:n}const zt=globalThis.GPUShaderStage?.COMPUTE??4,hn=globalThis.GPUBufferUsage?.STORAGE??128,Bt=globalThis.GPUBufferUsage?.COPY_DST??8,al=globalThis.GPUBufferUsage?.COPY_SRC??4,ll=globalThis.GPUBufferUsage?.UNIFORM??64,cl=globalThis.GPUBufferUsage?.MAP_READ??1,ul=globalThis.GPUMapMode?.READ??1;async function fl(){const t=Gi();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 hl(){return Nt||(Nt=(async()=>{const t=Gi();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:zt,buffer:{type:"read-only-storage"}},{binding:1,visibility:zt,buffer:{type:"read-only-storage"}},{binding:2,visibility:zt,buffer:{type:"storage"}},{binding:3,visibility:zt,buffer:{type:"uniform"}}]}),i=n.createComputePipeline({layout:n.createPipelineLayout({bindGroupLayouts:[r]}),compute:{module:n.createShaderModule({code:ol}),entryPoint:"main"}});return{device:n,pipeline:i,bindGroupLayout:r}})(),Nt)}function kt(t,e){return Math.ceil(t/e)*e}async function Zi(t,e,n){const r=await hl();if(!r)return null;const i=Math.max(0,Math.floor(e)),o=Math.max(0,Math.floor(n.length/4));if(i===0||o===0)return new Uint32Array(0);const s=Math.min(i,Math.floor(t.length/2));if(s===0)return new Uint32Array(0);const a=s*2*Float32Array.BYTES_PER_ELEMENT,l=o*4*Float32Array.BYTES_PER_ELEMENT,c=s*Uint32Array.BYTES_PER_ELEMENT,f=Number(r.device.limits.maxStorageBufferBindingSize);if(a>f||l>f||c>f)return null;const u=r.device.createBuffer({size:kt(a,4),usage:hn|Bt}),h=r.device.createBuffer({size:kt(l,4),usage:hn|Bt}),d=r.device.createBuffer({size:kt(c,4),usage:hn|al}),m=r.device.createBuffer({size:16,usage:ll|Bt}),p=r.device.createBuffer({size:kt(c,4),usage:Bt|cl});let b=!1;try{r.device.queue.writeBuffer(u,0,t.buffer,t.byteOffset,a),r.device.queue.writeBuffer(h,0,n.buffer,n.byteOffset,l),r.device.queue.writeBuffer(m,0,new Uint32Array([s,o,0,0]));const y=r.device.createBindGroup({layout:r.bindGroupLayout,entries:[{binding:0,resource:{buffer:u}},{binding:1,resource:{buffer:h}},{binding:2,resource:{buffer:d}},{binding:3,resource:{buffer:m}}]}),x=r.device.createCommandEncoder(),M=x.beginComputePass();M.setPipeline(r.pipeline),M.setBindGroup(0,y),M.dispatchWorkgroups(Math.ceil(s/256)),M.end(),x.copyBufferToBuffer(d,0,p,0,c),r.device.queue.submit([x.finish()]),await p.mapAsync(ul),b=!0;const S=p.getMappedRange();return new Uint32Array(S.slice(0))}finally{if(b)try{p.unmap()}catch{}u.destroy(),h.destroy(),d.destroy(),m.destroy(),p.destroy()}}async function qi(t,e,n={}){const r=Ee(),i=n.bridgeToDraw===!0;if(!t||!t.count||!t.positions||!t.paletteIndices)return{data:null,meta:{mode:"hybrid-webgpu",durationMs:Ee()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}};const o=mt(e??[]);if(o.length===0){const S={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return t.fillModes instanceof Uint8Array&&(S.fillModes=new Uint8Array(0)),t.ids instanceof Uint32Array&&(S.ids=new Uint32Array(0)),{data:S,meta:{mode:"hybrid-webgpu",durationMs:Ee()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const s=ot(t),a=t.fillModes instanceof Uint8Array&&t.fillModes.length>=s?t.fillModes:null,l=t.ids instanceof Uint32Array&&t.ids.length>=s?t.ids:null;if(s===0){const S={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(S.fillModes=new Uint8Array(0)),l&&(S.ids=new Uint32Array(0)),{data:S,meta:{mode:"hybrid-webgpu",durationMs:Ee()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const c=new Float32Array(o.length*4);for(let S=0;S<o.length;S+=1){const C=S*4,A=o[S];c[C]=A.minX,c[C+1]=A.minY,c[C+2]=A.maxX,c[C+3]=A.maxY}let f=null,u=!1;try{f=await Zi(t.positions,s,c),u=!!f}catch{f=null,u=!1}if(!f)return{data:Mt(t,e),meta:{mode:"hybrid-webgpu",durationMs:Ee()-r,usedWebGpu:!1,candidateCount:s,bridgedToDraw:!1}};let h=0;for(let S=0;S<s;S+=1)f[S]===1&&(h+=1);const d=new Uint32Array(h);if(h>0){let S=0;for(let C=0;C<s;C+=1)f[C]===1&&(d[S]=C,S+=1)}if(h===0){if(i){const C={count:s,positions:t.positions.subarray(0,s*2),paletteIndices:t.paletteIndices.subarray(0,s),drawIndices:new Uint32Array(0)};return a&&(C.fillModes=a.subarray(0,s)),l&&(C.ids=l.subarray(0,s)),{data:C,meta:{mode:"hybrid-webgpu",durationMs:Ee()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!0}}}const S={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(S.fillModes=new Uint8Array(0)),l&&(S.ids=new Uint32Array(0)),{data:S,meta:{mode:"hybrid-webgpu",durationMs:Ee()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!1}}}if(i){const S=new Uint32Array(h);let C=0;for(let B=0;B<h;B+=1){const z=d[B]??0,Y=t.positions[z*2],P=t.positions[z*2+1];Et(Y,P,o)&&(S[C]=z,C+=1)}const A={count:s,positions:t.positions.subarray(0,s*2),paletteIndices:t.paletteIndices.subarray(0,s),drawIndices:S.subarray(0,C)};return a&&(A.fillModes=a.subarray(0,s)),l&&(A.ids=l.subarray(0,s)),{data:A,meta:{mode:"hybrid-webgpu",durationMs:Ee()-r,usedWebGpu:!0,candidateCount:h,bridgedToDraw:!0}}}const m=new Float32Array(h*2),p=new Uint16Array(h),b=a?new Uint8Array(h):null,y=l?new Uint32Array(h):null;let x=0;for(let S=0;S<h;S+=1){const C=d[S]??0,A=t.positions[C*2],B=t.positions[C*2+1];Et(A,B,o)&&(m[x*2]=A,m[x*2+1]=B,p[x]=t.paletteIndices[C],b&&(b[x]=a[C]),y&&(y[x]=l[C]),x+=1)}const M={count:x,positions:m.subarray(0,x*2),paletteIndices:p.subarray(0,x)};return b&&(M.fillModes=b.subarray(0,x)),y&&(M.ids=y.subarray(0,x)),{data:M,meta:{mode:"hybrid-webgpu",durationMs:Ee()-r,usedWebGpu:!0,candidateCount:h,bridgedToDraw:!1}}}class Hi{constructor(e,n){E(this,"worker",null);E(this,"supported",!0);E(this,"requestId",1);E(this,"pendingById",new Map);E(this,"handleMessage",e=>{const n=e.data;if(!n)return;const r=this.pendingById.get(n.id);r&&(this.pendingById.delete(n.id),this.handlers.onResponse(n,r))});E(this,"handleError",()=>{this.supported=!1,this.teardownWorker("worker crashed")});this.createWorker=e,this.handlers=n}beginRequest(e){const n=this.getOrCreateWorker();if(!n)return null;const r=this.requestId++;return this.pendingById.set(r,e),{id:r,worker:n}}cancelRequest(e){const n=this.pendingById.get(e);if(n)return this.pendingById.delete(e),n}terminate(e="worker terminated"){this.teardownWorker(e)}getOrCreateWorker(){if(!this.supported)return null;if(this.worker)return this.worker;try{const e=this.createWorker();return e.addEventListener("message",this.handleMessage),e.addEventListener("error",this.handleError),this.worker=e,e}catch{return this.supported=!1,null}}teardownWorker(e){this.worker&&(this.worker.removeEventListener("message",this.handleMessage),this.worker.removeEventListener("error",this.handleError),this.worker.terminate(),this.worker=null);const n=new Error(e);for(const[,r]of this.pendingById)this.handlers.rejectPending(r,n);this.pendingById.clear()}}const At=new Hi(()=>new Worker(new URL(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/roi-clip-worker-CHxxL_lK.js").href:new URL("assets/roi-clip-worker-CHxxL_lK.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),typeof document>"u"?require("url").pathToFileURL(__filename).href:ft&&ft.tagName.toUpperCase()==="SCRIPT"&&ft.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),{onResponse:(t,e)=>{if(t.type==="roi-clip-failure"){e.reject(new Error(t.error||"worker clip failed"));return}if(t.type==="roi-clip-index-success"){if(e.kind!=="index"){e.reject(new Error("worker response mismatch: expected point data result"));return}const l=Math.max(0,Math.floor(t.count)),c=new Uint32Array(t.indices).subarray(0,l);e.resolve({indices:c,meta:{mode:"worker",durationMs:Number.isFinite(t.durationMs)?t.durationMs:Ee()-e.startMs}});return}if(e.kind!=="data"){e.reject(new Error("worker response mismatch: expected index result"));return}const n=Math.max(0,Math.floor(t.count)),r=new Float32Array(t.positions),i=new Uint16Array(t.paletteIndices),o=t.fillModes?new Uint8Array(t.fillModes):null,s=t.ids?new Uint32Array(t.ids):null,a={count:n,positions:r.subarray(0,n*2),paletteIndices:i.subarray(0,n)};o&&(a.fillModes=o.subarray(0,n)),s&&(a.ids=s.subarray(0,n)),e.resolve({data:a,meta:{mode:"worker",durationMs:Number.isFinite(t.durationMs)?t.durationMs:Ee()-e.startMs}})},rejectPending:(t,e)=>{t.reject(e)}});function dl(){At.terminate("worker terminated")}async function $i(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return{data:null,meta:{mode:"worker",durationMs:0}};const n=ot(t),r=t.positions.slice(0,n*2),i=t.paletteIndices.slice(0,n),o=t.fillModes instanceof Uint8Array&&t.fillModes.length>=n?t.fillModes.slice(0,n):null,s=t.ids instanceof Uint32Array&&t.ids.length>=n?t.ids.slice(0,n):null;return new Promise((a,l)=>{const c=Ee(),f=At.beginRequest({kind:"data",resolve:a,reject:l,startMs:c});if(!f){a({data:Mt(t,e),meta:{mode:"sync",durationMs:Ee()-c}});return}const u={type:"roi-clip-request",id:f.id,count:n,positions:r.buffer,paletteIndices:i.buffer,fillModes:o?.buffer,ids:s?.buffer,polygons:e??[]},h=[r.buffer,i.buffer];o&&h.push(o.buffer),s&&h.push(s.buffer);try{f.worker.postMessage(u,h)}catch(d){const m=At.cancelRequest(f.id);m?m.reject(d):l(d)}})}async function ml(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return{indices:new Uint32Array(0),meta:{mode:"worker",durationMs:0}};const n=ot(t),r=t.positions.slice(0,n*2);return new Promise((i,o)=>{const s=Ee(),a=At.beginRequest({kind:"index",resolve:i,reject:o,startMs:s});if(!a){i({indices:Vi(t,e),meta:{mode:"sync",durationMs:Ee()-s}});return}const l={type:"roi-clip-index-request",id:a.id,count:n,positions:r.buffer,polygons:e??[]};try{a.worker.postMessage(l,[r.buffer])}catch(c){const f=At.cancelRequest(a.id);f?f.reject(c):o(c)}})}const gl={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};function pl(t,e,n,r,i){const o=g.useRef(0),[s,a]=g.useState(n),l=g.useMemo(()=>r.map(c=>dt(c.coordinates)).filter(c=>c!=null),[r]);return g.useEffect(()=>{const c=++o.current;let f=!1;if(!t)return a(n),()=>{f=!0};if(!n||!n.count||!n.positions||!n.paletteIndices)return a(null),()=>{f=!0};if(l.length===0)return a(gl),i?.({mode:e,durationMs:0,inputCount:n.count,outputCount:0,polygonCount:0}),()=>{f=!0};const u=(d,m)=>{if(f||c!==o.current)return;const p=n.count,b=d?.drawIndices?d.drawIndices.length:d?.count??0;a(d),i?.({mode:m.mode,durationMs:m.durationMs,inputCount:p,outputCount:b,polygonCount:l.length,usedWebGpu:m.usedWebGpu,candidateCount:m.candidateCount,bridgedToDraw:m.bridgedToDraw})};return(async()=>{if(e==="sync"){const d=performance.now(),m=Mt(n,l);u(m,{mode:"sync",durationMs:performance.now()-d});return}if(e==="hybrid-webgpu"){const d=await qi(n,l,{bridgeToDraw:!0});u(d.data,{mode:d.meta.mode,durationMs:d.meta.durationMs,usedWebGpu:d.meta.usedWebGpu,candidateCount:d.meta.candidateCount,bridgedToDraw:d.meta.bridgedToDraw});return}try{const d=await $i(n,l);u(d.data,{mode:d.meta.mode,durationMs:d.meta.durationMs})}catch{const d=performance.now(),m=Mt(n,l);u(m,{mode:"sync",durationMs:performance.now()-d})}})(),()=>{f=!0}},[t,e,n,l,i]),s}const yl=24,bl=1024,xl=4,Vt=-1;function yt(t,e,n){return(t*73856093^e*19349663)>>>0&n}function wl(t,e,n){if(t<=0||e<=0||n<=0)return 256;const r=Math.max(1,t*e),o=Math.sqrt(r/Math.max(1,n))*xl;return Math.max(yl,Math.min(bl,o))}function Sl(t,e){if(!(t instanceof Uint32Array)||t.length===0)return null;let n=!0;for(let o=0;o<t.length;o+=1)if(!(t[o]<e)){n=!1;break}if(n)return t;const r=new Uint32Array(t.length);let i=0;for(let o=0;o<t.length;o+=1)t[o]>=e||(r[i]=t[o],i+=1);return i>0?r.subarray(0,i):null}function El(t){const e=Math.max(0,Math.floor(t.count)),n=Math.floor(t.positions.length/2),r=Math.max(0,Math.min(e,n));if(r<=0)return null;const i=Sl(t.drawIndices??null,r),o=i?i.length:r;if(o===0)return null;const s=wl(t.sourceWidth,t.sourceHeight,o),a=1/s,l=new Int32Array(o),c=new Int32Array(o);let f=0;if(i)for(let v=0;v<o;v+=1){const W=i[v],j=t.positions[W*2],L=t.positions[W*2+1];!Number.isFinite(j)||!Number.isFinite(L)||(l[f]=Math.floor(j*a),c[f]=Math.floor(L*a),f+=1)}else for(let v=0;v<r;v+=1){const W=t.positions[v*2],j=t.positions[v*2+1];!Number.isFinite(W)||!Number.isFinite(j)||(l[f]=Math.floor(W*a),c[f]=Math.floor(j*a),f+=1)}if(f===0)return null;let u=Math.min(f,Math.max(64,f>>>3));(!Number.isFinite(u)||u<=0)&&(u=f);let h=1;for(;h<u*2;)h<<=1;let d=h-1,m=new Int32Array(h*2),p=new Int32Array(h);m.fill(2147483647);let b=0;const y=new Int32Array(f);for(let v=0;v<f;v+=1){const W=l[v],j=c[v];let L=yt(W,j,d);for(;;){const ge=m[L*2];if(ge===2147483647){if(m[L*2]=W,m[L*2+1]=j,p[L]=1,y[v]=L,b+=1,b*4>h*3){const le=h;h<<=1,d=h-1;const Q=new Int32Array(h*2),ve=new Int32Array(h);Q.fill(2147483647);for(let Ae=0;Ae<le;Ae+=1){if(m[Ae*2]===2147483647)continue;const D=m[Ae*2],T=m[Ae*2+1];let k=yt(D,T,d);for(;Q[k*2]!==2147483647;)k=k+1&d;Q[k*2]=D,Q[k*2+1]=T,ve[k]=p[Ae]}for(m=Q,p=ve,L=yt(W,j,d);m[L*2]!==W||m[L*2+1]!==j;)L=L+1&d;y[v]=L}break}if(ge===W&&m[L*2+1]===j){p[L]+=1,y[v]=L;break}L=L+1&d}}const x=new Int32Array(b*2),M=new Uint32Array(b),S=new Uint32Array(b),C=new Int32Array(h);C.fill(Vt);let A=0,B=0;for(let v=0;v<h;v+=1)m[v*2]!==2147483647&&(x[A*2]=m[v*2],x[A*2+1]=m[v*2+1],M[A]=B,S[A]=p[v],C[v]=A,B+=p[v],A+=1);const z=new Uint32Array(f),Y=new Uint32Array(b);if(Y.set(M),i)for(let v=0;v<f;v+=1){const W=C[y[v]];z[Y[W]]=i[v],Y[W]+=1}else{let v=0;for(let W=0;W<r;W+=1){const j=t.positions[W*2],L=t.positions[W*2+1];if(!Number.isFinite(j)||!Number.isFinite(L))continue;const ge=C[y[v]];z[Y[ge]]=W,Y[ge]+=1,v+=1}}let P=1;for(;P<b*2;)P<<=1;const I=P-1,O=new Int32Array(P);O.fill(Vt);for(let v=0;v<b;v+=1){const W=x[v*2],j=x[v*2+1];let L=yt(W,j,I);for(;O[L]!==Vt;)L=L+1&I;O[L]=v}return{cellSize:s,safeCount:r,cellCount:b,hashCapacity:P,hashTable:O,cellKeys:x,cellOffsets:M,cellLengths:S,pointIndices:z}}function Ki(t,e,n){const{hashTable:r,cellKeys:i,hashMask:o}=t;let s=yt(e,n,o);for(;;){const a=r[s];if(a===Vt)return-1;if(i[a*2]===e&&i[a*2+1]===n)return a;s=s+1&o}}function Rl(t,e){if(t.safeCount<=0||t.cellCount<=0)return null;const n=t.safeCount;return{cellSize:t.cellSize,safeCount:n,positions:e.positions.subarray(0,n*2),ids:e.ids instanceof Uint32Array&&e.ids.length>=n?e.ids.subarray(0,n):null,hashCapacity:t.hashCapacity,hashMask:t.hashCapacity-1,hashTable:new Int32Array(t.hashTable),cellKeys:new Int32Array(t.cellKeys),cellOffsets:new Uint32Array(t.cellOffsets),cellLengths:new Uint32Array(t.cellLengths),pointIndices:new Uint32Array(t.pointIndices)}}const In=new Hi(()=>new Worker(new URL(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/point-hit-index-worker-CNFA6pZm.js").href:new URL("assets/point-hit-index-worker-CNFA6pZm.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),typeof document>"u"?require("url").pathToFileURL(__filename).href:ft&&ft.tagName.toUpperCase()==="SCRIPT"&&ft.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),{onResponse:(t,e)=>{if(t.type==="point-hit-index-failure"){e.reject(new Error(t.error||"worker index build failed"));return}e.resolve(Rl(t,e.pointData))},rejectPending:(t,e)=>{t.reject(e)}});function Ml(){In.terminate("worker terminated")}function Al(t,e){const n=ot(t);if(n<=0)return null;const r=t.positions.subarray(0,n*2),i=El({count:n,positions:r,drawIndices:t.drawIndices instanceof Uint32Array?t.drawIndices:null,sourceWidth:e?.width??0,sourceHeight:e?.height??0});return i?{cellSize:i.cellSize,safeCount:n,positions:r,ids:t.ids instanceof Uint32Array&&t.ids.length>=n?t.ids.subarray(0,n):null,hashCapacity:i.hashCapacity,hashMask:i.hashCapacity-1,hashTable:i.hashTable,cellKeys:i.cellKeys,cellOffsets:i.cellOffsets,cellLengths:i.cellLengths,pointIndices:i.pointIndices}:null}async function ji(t,e){if(!t||!t.positions||!t.paletteIndices)return null;const n=ot(t);return n<=0?null:new Promise((r,i)=>{const o={resolve:r,reject:i,pointData:t},s=In.beginRequest(o);if(!s||!s.worker){r(Al(t,e));return}const a=t.positions.slice(0,n*2),l=t.drawIndices instanceof Uint32Array&&t.drawIndices.length>0?t.drawIndices.slice():void 0,c={type:"point-hit-index-request",id:s.id,count:n,positions:a.buffer,drawIndices:l?.buffer,sourceWidth:e?.width??0,sourceHeight:e?.height??0},f=[a.buffer];l&&f.push(l.buffer);try{s.worker.postMessage(c,f)}catch(u){const h=In.cancelRequest(s.id);h?h.reject(u):i(u)}})}const Cl=.65,Pl=4;function vl(t,e,n,r,i,o,s,a){const l=!!(n||r||i),[c,f]=g.useState(null),u=g.useRef(null),h=g.useRef(null);g.useEffect(()=>{if(!l||!t){f(null);return}let b=!1;return ji(t,e).then(y=>{b||f(y)}),()=>{b=!0}},[l,t,e]);const d=g.useCallback(b=>{const y=s.current;if(!y||!c)return null;const x=Number(b[0]),M=Number(b[1]);if(!Number.isFinite(x)||!Number.isFinite(M))return null;const S=Math.max(1e-6,y.getViewState().zoom),C=y.getPointSize(a),B=Math.max(Pl,C*Cl)/S;if(!Number.isFinite(B)||B<=0)return null;const{cellSize:z,cellOffsets:Y,cellLengths:P,pointIndices:I,positions:O,safeCount:v}=c,W=Math.floor(x/z),j=Math.floor(M/z),L=Math.max(1,Math.ceil(B/z)),ge=B*B;let le=-1,Q=ge,ve=0,Ae=0;for(let T=W-L;T<=W+L;T+=1)for(let k=j-L;k<=j+L;k+=1){const oe=Ki(c,T,k);if(oe<0)continue;const ue=Y[oe],$=ue+P[oe];for(let ce=ue;ce<$;ce+=1){const te=I[ce];if(te>=v)continue;const _e=O[te*2],Se=O[te*2+1],fe=_e-x,xe=Se-M,ee=fe*fe+xe*xe;ee>Q||(Q=ee,le=te,ve=_e,Ae=Se)}}if(le<0)return null;const D=c.ids?Number(c.ids[le]):null;return{index:le,id:D,coordinate:[x,M],pointCoordinate:[ve,Ae]}},[a,c]),m=g.useCallback((b,y)=>{if(!n)return;const x=b?.index??null,M=b?.id??null;u.current===x&&h.current===M||(u.current=x,h.current=M,n({index:x,id:M,coordinate:y,pointCoordinate:b?.pointCoordinate??null}))},[n]),p=g.useCallback((b,y)=>{if(!r)return;const x=d(b);x&&r({...x,button:y})},[r,d]);return g.useEffect(()=>{if(i)return i.current=d,()=>{i.current===d&&(i.current=null)}},[i,d]),g.useEffect(()=>{const b=u.current;b!==null&&(c&&b<c.safeCount||(u.current=null,h.current=null,n?.({index:null,id:null,coordinate:null,pointCoordinate:null})))},[c,n]),g.useEffect(()=>{},[o,n]),{getCellByCoordinates:d,emitPointHover:m,emitPointClick:p}}let Tl=0;const Il=g.forwardRef(function({data:e=null,palette:n=null,sizeByZoom:r,sizeByMagnification:i,weightByMagnification:o,opacity:s,strokeScale:a,innerFillOpacity:l,innerFillColor:c,clipEnabled:f=!1,clipToRegions:u,clipMode:h="worker",onClipStats:d,onHover:m,onClick:p,dashed:b},y){const{rendererRef:x,rendererSerial:M,source:S}=st(),C=g.useRef(null),A=g.useRef(`__point_layer__${Tl++}`),z=pl(f,h,e,u??_l,d),{getCellByCoordinates:Y}=vl(z,S,m,p,C,"cursor",x,A.current);return g.useImperativeHandle(y,()=>({queryAt:Y}),[Y]),g.useEffect(()=>{const P=x.current;if(!P)return;const I=A.current;return P.registerPointLayer(I),()=>{P.unregisterPointLayer(I)}},[x,M]),g.useEffect(()=>{const P=x.current;P&&P.setPointPalette(n,A.current)},[M,n,x]),g.useEffect(()=>{const P=x.current;P&&P.setPointLineDash(b,A.current)},[M,b,x]),g.useEffect(()=>{const P=x.current;P&&P.setPointSizeByZoom(r,A.current)},[M,r,x]),g.useEffect(()=>{const P=x.current;P&&P.setPointSizeByMagnification(i,A.current)},[M,i,x]),g.useEffect(()=>{const P=x.current;P&&P.setPointWeightByMagnification(o,A.current)},[M,o,x]),g.useEffect(()=>{const P=x.current;!P||s===void 0||P.setPointOpacity(s,A.current)},[M,s,x]),g.useEffect(()=>{const P=x.current;!P||a===void 0||P.setPointStrokeScale(a,A.current)},[M,a,x]),g.useEffect(()=>{const P=x.current;!P||l===void 0||P.setPointInnerFillOpacity(l,A.current)},[M,l,x]),g.useEffect(()=>{const P=x.current;P&&P.setPointInnerFillColor(c,A.current)},[M,c,x]),g.useEffect(()=>{const P=x.current;P&&P.setPointData(z,A.current)},[M,z,x]),null}),_l=[],Fl=180,Vr=20;function Ll(t){const e=F(t,0,1);return e*e*(3-2*e)}function Dl(t,e,n){const[r,i]=g.useState(0),o=g.useRef(0),s=g.useRef({rafId:null,startMs:0,from:0,to:0}),a=g.useCallback(u=>{const h=F(u,0,Vr);Math.abs(o.current-h)<1e-4||(o.current=h,i(h))},[]),l=g.useCallback(()=>{const u=s.current;u.rafId!==null&&(cancelAnimationFrame(u.rafId),u.rafId=null)},[]),c=g.useCallback(u=>{const h=F(u,0,Vr),d=s.current,m=o.current;if(Math.abs(m-h)<1e-4){l(),d.to=h,a(h);return}l(),d.startMs=performance.now(),d.from=m,d.to=h;const p=b=>{const y=s.current,x=Math.max(0,b-y.startMs),M=F(x/Fl,0,1),S=Ll(M),C=y.from+(y.to-y.from)*S;if(a(C),n.current?.(),M>=1){y.rafId=null,a(y.to);return}y.rafId=requestAnimationFrame(p)};d.rafId=requestAnimationFrame(p)},[a,l]),f=g.useCallback(u=>{const h=e.current;if(!h||typeof u!="number"||!Number.isFinite(u)){c(0);return}const d=Xn(t,u,h.getZoomRange(),h.getRegionLabelAutoLiftCapZoom());c(d)},[t,c]);return g.useEffect(()=>()=>{l()},[l]),{regionLabelAutoLiftOffsetPx:r,syncRegionLabelAutoLiftTarget:f,cancelRegionLabelAutoLiftAnimation:l,applyRegionLabelAutoLiftOffset:a}}const Nl=6;function _n(t,e){return t.id??e}function zl(t,e,n,r,i,o){const s=i-n,a=o-r,l=s*s+a*a;if(l<=1e-12){const m=t-n,p=e-r;return m*m+p*p}const c=F(((t-n)*s+(e-r)*a)/l,0,1),f=n+s*c,u=r+a*c,h=t-f,d=e-u;return h*h+d*d}function Gr(t,e,n,r){for(let i=1;i<n.length;i+=1){const o=n[i-1],s=n[i];if(zl(t,e,o[0],o[1],s[0],s[1])<=r)return!0}return!1}function Bl(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(Gr(t,e,n.outer,i))return!0;for(const o of n.holes)if(Gr(t,e,o,i))return!0;return!1}function kl(t,e,n,r,i,o,s,a){if(!t.label)return!1;const l=On(t.polygons,S=>{const C=[];for(let A=0;A<S.length;A+=1){const B=Bn(n.worldToScreen(S[A][0],S[A][1]));if(!B)return[];C.push(B)}return C},r);if(!l)return!1;const f=Un(t.label,i)+i.paddingX*2,u=i.fontSize+i.paddingY*2,h=l[0],d=l[1]-i.offsetY,m=a?F(h,f*.5+1,o-f*.5-1):h,p=a?F(d,u*.5+1,s-u*.5-1):d,b=m-f*.5,y=m+f*.5,x=p-u*.5,M=p+u*.5;return e[0]>=b&&e[0]<=y&&e[1]>=x&&e[1]<=M}function Ul(t){const e=[];for(let n=0;n<t.length;n+=1){const r=t[n],i=mt([dt(r?.coordinates)]);if(i.length===0)continue;const o=typeof r?.label=="string"?r.label.trim():"";e.push({region:r,regionIndex:n,regionId:_n(r,n),polygons:i,label:o})}return e}function Zr(t,e,n,r,i,o,s,a,l,c,f=!0){const u=t[0],h=t[1],d=Math.max(1e-6,r.getViewState().zoom),m=Math.max(0,a),p=Nl/d;for(let b=n.length-1;b>=0;b-=1){const y=n[b];for(const M of y.polygons)if(Bl(u,h,M,p))return{region:y.region,regionIndex:y.regionIndex,regionId:y.regionId};let x=Yn(o,s?.({region:y.region,regionId:y.regionId,regionIndex:y.regionIndex,zoom:d}));if(m>0&&(x={...x,offsetY:x.offsetY+m}),!!kl(y,e,r,i,x,l,c,f))return{region:y.region,regionIndex:y.regionIndex,regionId:y.regionId}}return null}const qr=[],Ol=[];let Wl=0;function Yl(t){return{color:bi,width:xi,lineDash:it,lineJoin:t.lineJoin,lineCap:t.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function Xl({regions:t,polygons:e,strokeStyle:n,hoverStrokeStyle:r,activeStrokeStyle:i,resolveStrokeStyle:o,labelStyle:s,labelAnchor:a="top-center",autoLiftLabelAtMaxZoom:l=!1,clampLabelToViewport:c=!0,hoveredRegionId:f,activeRegionId:u,interactive:h=!0,onActiveChange:d,onHover:m,onClick:p}){const{rendererRef:b,rendererSerial:y,canvasRef:x,containerRef:M,registerDrawCallback:S,unregisterDrawCallback:C,requestOverlayRedraw:A,drawInvalidateRef:B,registerViewStateListener:z,screenToWorld:Y,worldToScreen:P,isInteractionLocked:I}=st(),O=t??qr,v=e??Ol,W=g.useMemo(()=>O.length>0?O:v.length===0?qr:v.map((V,H)=>({id:H,coordinates:V})),[O,v]),[j,L]=g.useState(()=>f??null),[ge,le]=g.useState(()=>u??null),Q=f!==void 0,ve=u!==void 0,Ae=Q?f??null:j,D=ve?u??null:ge,T=g.useRef(f??null),k=g.useRef(null),oe=g.useRef(null);if(k.current===null||oe.current===null){const V=Wl++;k.current=`__region_layer__${V}`,oe.current=`__region_label__${V}`}g.useEffect(()=>{ve&&le(u??null)},[ve,u]),g.useEffect(()=>{if(!Q)return;const V=f??null;T.current=V,L(V)},[Q,f]);const ue=g.useCallback(V=>{String(D)!==String(V)&&(ve||le(V),d?.(V))},[D,ve,d]),{regionLabelAutoLiftOffsetPx:$,syncRegionLabelAutoLiftTarget:ce}=Dl(l,b,B),te=g.useMemo(()=>kn(n),[n]),_e=g.useMemo(()=>Ke(te,r),[te,r]),Se=g.useMemo(()=>Ke(te,i),[te,i]),{staticLabelStyle:fe,labelStyleResolver:xe}=g.useMemo(()=>typeof s=="function"?{staticLabelStyle:void 0,labelStyleResolver:s}:{staticLabelStyle:s,labelStyleResolver:void 0},[s]),ee=g.useMemo(()=>Wn(fe),[fe]),se=g.useMemo(()=>{const V=[];for(let H=0;H<W.length;H+=1){const be=W[H],J=Jt(be.coordinates);J.length!==0&&V.push({region:be,regionIndex:H,regionKey:be.id??H,polygons:J})}return V},[W]),he=g.useMemo(()=>Ul(W),[W]);g.useEffect(()=>{const V=b.current;if(V)return ce(V.getViewState().zoom),z(H=>{ce(H.zoom)})},[y,z,ce]),g.useEffect(()=>{!(D===null?!0:W.some((J,K)=>String(_n(J,K))===String(D)))&&D!==null&&ue(null);const H=T.current;!(H===null?!0:W.some((J,K)=>String(_n(J,K))===String(H)))&&H!==null&&(T.current=null,Q||L(null),m?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[W,D,Q,m,ue]);const ae=g.useCallback(V=>{const H=b.current;if(!H||V.length===0)return[];const be=new Array(V.length);for(let J=0;J<V.length;J+=1){const K=qe(H.worldToScreen(V[J][0],V[J][1]));if(!K)return[];be[J]=K}return be},[]),ne=g.useRef({preparedRegions:se,hoveredRegionId:Ae,activeRegionId:D,resolvedStrokeStyle:te,resolvedHoverStrokeStyle:_e,resolvedActiveStrokeStyle:Se,resolveStrokeStyleProp:o,worldToScreenPoints:ae});ne.current={preparedRegions:se,hoveredRegionId:Ae,activeRegionId:D,resolvedStrokeStyle:te,resolvedHoverStrokeStyle:_e,resolvedActiveStrokeStyle:Se,resolveStrokeStyleProp:o,worldToScreenPoints:ae},g.useEffect(()=>{const V=be=>{const{preparedRegions:J,hoveredRegionId:K,activeRegionId:Re,resolvedStrokeStyle:X,resolvedHoverStrokeStyle:Ce,resolvedActiveStrokeStyle:De,resolveStrokeStyleProp:Le,worldToScreenPoints:U}=ne.current;for(const Z of J){const{region:q,polygons:re,regionIndex:pe,regionKey:de}=Z,Ne=jt(Re,de)?"active":jt(K,de)?"hover":"default";let w=Ne==="active"?De:Ne==="hover"?Ce:X;if(Le){const _=Le({region:q,regionId:de,regionIndex:pe,state:Ne});w=Ke(w,_||void 0)}const R=Ne==="default"?null:Yl(w);for(const _ of re){const N=U(_.outer);N.length>=4&&(R&&ke(be,N,R,!0,!1),ke(be,N,w,!0,!1));for(const G of _.holes){const ye=U(G);ye.length>=4&&(R&&ke(be,ye,R,!0,!1),ke(be,ye,w,!0,!1))}}}},H=k.current;if(H)return S(H,10,V),()=>C(H)},[S,C]);const Me=g.useRef({preparedRegions:se,resolvedLabelStyle:ee,labelStyleResolver:xe,labelAnchor:a,autoLiftLabelAtMaxZoom:l,clampLabelToViewport:c,regionLabelAutoLiftOffsetPx:$,rendererRef:b});Me.current={preparedRegions:se,resolvedLabelStyle:ee,labelStyleResolver:xe,labelAnchor:a,autoLiftLabelAtMaxZoom:l,clampLabelToViewport:c,regionLabelAutoLiftOffsetPx:$,rendererRef:b},g.useEffect(()=>{const V=(be,J,K)=>{const{preparedRegions:Re,resolvedLabelStyle:X,labelStyleResolver:Ce,labelAnchor:De,autoLiftLabelAtMaxZoom:Le,clampLabelToViewport:U,regionLabelAutoLiftOffsetPx:Z,rendererRef:q}=Me.current;if(Re.length===0)return;const re=Math.max(1e-6,q.current?.getViewState?.().zoom??1),pe=typeof Z=="number"&&Number.isFinite(Z)?Math.max(0,Z):Xn(Le,re,q.current?.getZoomRange?.(),q.current?.getRegionLabelAutoLiftCapZoom?.());for(const de of Re){if(!de.region.label)continue;const Ne=On(de.polygons,R=>{const _=q.current;if(!_)return[];const N=[];for(let G=0;G<R.length;G+=1){const ye=qe(_.worldToScreen(R[G][0],R[G][1]));if(!ye)return[];N.push(ye)}return N},De);if(!Ne)continue;let w=Yn(X,Ce?.({region:de.region,regionId:de.regionKey,regionIndex:de.regionIndex,zoom:re}));pe>0&&(w={...w,offsetY:w.offsetY+pe}),Ai(be,de.region.label,Ne,J,K,w,U)}},H=oe.current;if(H)return S(H,50,V),()=>C(H)},[S,C]),g.useEffect(()=>{A()},[se,Ae,D,te,ee,$,A]);const we=g.useRef({preparedRegionHits:he,labelAnchor:a,resolvedLabelStyle:ee,labelStyleResolver:xe,regionLabelAutoLiftOffsetPx:$,clampLabelToViewport:c,onHover:m,onClick:p,commitActive:ue});return we.current={preparedRegionHits:he,labelAnchor:a,resolvedLabelStyle:ee,labelStyleResolver:xe,regionLabelAutoLiftOffsetPx:$,clampLabelToViewport:c,onHover:m,onClick:p,commitActive:ue},g.useEffect(()=>{if(!h)return;const V=M.current;if(!V)return;const H=K=>{if(I())return;const Re=b.current;if(!Re)return;const{preparedRegionHits:X,labelAnchor:Ce,resolvedLabelStyle:De,labelStyleResolver:Le,regionLabelAutoLiftOffsetPx:U,clampLabelToViewport:Z,onHover:q}=we.current,re=Y(K.clientX,K.clientY);if(!re)return;let pe=null,de=null;if(X.length>0){const w=P(re[0],re[1]);if(w){const R=x.current?.getBoundingClientRect();de=Zr(re,w,X,Re,Ce,De,Le,typeof U=="number"?U:0,R?.width??0,R?.height??0,Z),pe=de?.regionId??null}}const Ne=T.current;String(Ne)!==String(pe)&&(T.current=pe,Q||L(pe),q?.({region:de?.region??null,regionId:pe,regionIndex:de?.regionIndex??-1,coordinate:re}),A())},be=K=>{if(I())return;const Re=b.current;if(!Re)return;const{preparedRegionHits:X,labelAnchor:Ce,resolvedLabelStyle:De,labelStyleResolver:Le,regionLabelAutoLiftOffsetPx:U,clampLabelToViewport:Z,onClick:q,commitActive:re}=we.current;if(X.length===0)return;const pe=Y(K.clientX,K.clientY);if(!pe)return;const de=P(pe[0],pe[1]);if(!de)return;const Ne=x.current?.getBoundingClientRect(),w=Zr(pe,de,X,Re,Ce,De,Le,typeof U=="number"?U:0,Ne?.width??0,Ne?.height??0,Z),R=w?.regionId??null;re(R),w&&q&&q({region:w.region,regionId:w.regionId,regionIndex:w.regionIndex,coordinate:pe})},J=()=>{T.current!==null&&(T.current=null,Q||L(null),we.current.onHover?.({region:null,regionId:null,regionIndex:-1,coordinate:null}),A())};return V.addEventListener("pointermove",H),V.addEventListener("click",be),V.addEventListener("pointerleave",J),()=>{V.removeEventListener("pointermove",H),V.removeEventListener("click",be),V.removeEventListener("pointerleave",J)}},[M,b,x,h,Q,Y,P,I,A]),null}function Vl({imageWidth:t,imageHeight:e,tiles:n,viewState:r,className:i,style:o}){const s=g.useRef(null),a=g.useRef(null),l=g.useMemo(()=>({width:"100%",height:"100%",display:"block",...o}),[o]);return g.useEffect(()=>{const c=s.current;if(!c)return;const f=new ui({canvas:c,imageWidth:t,imageHeight:e,initialViewState:r});return a.current=f,f.setTiles(n),()=>{f.destroy(),a.current=null}},[t,e]),g.useEffect(()=>{const c=a.current;c&&c.setTiles(n)},[n]),g.useEffect(()=>{const c=a.current;!c||!r||c.setViewState(r)},[r]),Ge.jsx("canvas",{ref:s,className:i,style:l})}function Gl(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 Qi{constructor(e){E(this,"maxConcurrency");E(this,"maxRetries");E(this,"retryBaseDelayMs");E(this,"retryMaxDelayMs");E(this,"onTileLoad");E(this,"onTileError");E(this,"onStateChange");E(this,"authToken");E(this,"destroyed",!1);E(this,"queue",[]);E(this,"queuedByKey",new Map);E(this,"inflight",new Map);E(this,"visibleKeys",new Set);E(this,"timerId",null);E(this,"abortedCount",0);E(this,"retryCount",0);E(this,"failedCount",0);this.maxConcurrency=Math.max(1,Math.floor(e.maxConcurrency??12)),this.maxRetries=Math.max(0,Math.floor(e.maxRetries??2)),this.retryBaseDelayMs=Math.max(10,Math.floor(e.retryBaseDelayMs??120)),this.retryMaxDelayMs=Math.max(this.retryBaseDelayMs,Math.floor(e.retryMaxDelayMs??1200)),this.authToken=e.authToken??"",this.onTileLoad=e.onTileLoad,this.onTileError=e.onTileError,this.onStateChange=e.onStateChange}setAuthToken(e){this.authToken=String(e??"")}schedule(e){if(this.destroyed)return;const n=new Set;for(const r of e)n.add(r.key);this.visibleKeys=n,this.dropInvisibleQueued(n),this.abortInvisibleInflight(n);for(const r of e){if(this.inflight.has(r.key)){const s=this.inflight.get(r.key);s&&(s.tile=r);continue}const i=this.queuedByKey.get(r.key);if(i){i.tile=r;continue}const o={tile:r,attempt:0,readyAt:Ee()};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-Ee());this.timerId=globalThis.setTimeout(()=>{this.timerId=null,this.pump()},n)}takeNextReadyQueueItem(){if(this.queue.length===0)return null;const e=Ee(),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=Gl(e.tile.url,this.authToken);fetch(e.tile.url,{signal:n.signal,headers:i?{Authorization:this.authToken}:void 0}).then(o=>{if(!o.ok)throw new Error(`HTTP ${o.status}`);return o.blob()}).then(o=>createImageBitmap(o)).then(o=>{if(this.destroyed||n.signal.aborted){o.close();return}if(!this.visibleKeys.has(e.tile.key)){o.close();return}this.onTileLoad(e.tile,o)}).catch(o=>{if(n.signal.aborted||this.destroyed)return;if(e.attempt<this.maxRetries&&this.visibleKeys.has(e.tile.key)){this.retryCount+=1;const a=e.attempt+1,l=this.getRetryDelay(a),c={tile:e.tile,attempt:a,readyAt:Ee()+l},f=this.queuedByKey.get(e.tile.key);f?(f.tile=c.tile,f.readyAt=Math.min(f.readyAt,c.readyAt),f.attempt=Math.max(f.attempt,c.attempt)):(this.queue.push(c),this.queuedByKey.set(c.tile.key,c)),this.sortQueue();return}this.failedCount+=1,this.onTileError?.(e.tile,o,e.attempt+1)}).finally(()=>{this.inflight.delete(e.tile.key),this.pump(),this.emitStateChange()})}getRetryDelay(e){const n=Math.max(0,e-1),r=Math.min(this.retryMaxDelayMs,this.retryBaseDelayMs*2**n),i=.85+Math.random()*.3;return Math.round(r*i)}clearPumpTimer(){this.timerId!==null&&(globalThis.clearTimeout(this.timerId),this.timerId=null)}emitStateChange(){this.onStateChange?.(this.getSnapshot())}}function Zl(t,e){t.addEventListener("pointerdown",e.pointerDown),t.addEventListener("pointermove",e.pointerMove),t.addEventListener("pointerup",e.pointerUp),t.addEventListener("pointercancel",e.pointerUp),t.addEventListener("wheel",e.wheel,{passive:!1}),t.addEventListener("dblclick",e.doubleClick),t.addEventListener("contextmenu",e.contextMenu),t.addEventListener("webglcontextlost",e.contextLost),t.addEventListener("webglcontextrestored",e.contextRestored)}function ql(t,e){t.removeEventListener("pointerdown",e.pointerDown),t.removeEventListener("pointermove",e.pointerMove),t.removeEventListener("pointerup",e.pointerUp),t.removeEventListener("pointercancel",e.pointerUp),t.removeEventListener("wheel",e.wheel),t.removeEventListener("dblclick",e.doubleClick),t.removeEventListener("contextmenu",e.contextMenu),t.removeEventListener("webglcontextlost",e.contextLost),t.removeEventListener("webglcontextrestored",e.contextRestored)}function Hl(t,e,n){const r=t.getBoundingClientRect(),i=Math.max(1,r.width||t.clientWidth||1),o=Math.max(1,r.height||t.clientHeight||1),s=Math.max(1,window.devicePixelRatio||1),a=Math.max(1,Math.round(i*s)),l=Math.max(1,Math.round(o*s));(t.width!==a||t.height!==l)&&(t.width=a,t.height=l),n.setViewport(i,o),e.viewport(0,0,a,l)}const Fn=.35,ht=.5,Hr=256,Ln=[{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}],$l=.1,Kl=5,jl=0,Ql=1,Jl=0,ec=1,tc=-100,nc=100,rc=2e3,Ji=[255,255,255];function on(t){return t*Math.PI/180}function Ut(t,e){return!t||!e?t===e:t.buffer===e.buffer&&t.byteOffset===e.byteOffset&&t.byteLength===e.byteLength}function tn(t){return t.map(e=>({zoom:e.zoom,size:e.size}))}function ic(t){return!t||t.length===0?null:t.map(e=>({magnification:e.magnification,size:e.size}))}function oc(t){return!t||t.length===0?null:t.map(e=>({magnification:e.magnification,weight:e.weight}))}function $r(t){if(!t)return tn(Ln);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?tn(Ln):Array.from(e.entries()).sort((n,r)=>n[0]-r[0]).map(([n,r])=>({zoom:n,size:r}))}function Kr(t){if(!t)return null;const e=new Map;for(const[n,r]of Object.entries(t)){const i=Number(n),o=Number(r);!Number.isFinite(i)||i<=0||!Number.isFinite(o)||o<=0||e.set(i,o)}return e.size===0?null:Array.from(e.entries()).sort((n,r)=>n[0]-r[0]).map(([n,r])=>({magnification:n,size:r}))}function jr(t){if(!t)return null;const e=new Map;for(const[n,r]of Object.entries(t)){const i=Number(n),o=Gt(r);!Number.isFinite(i)||i<=0||e.set(i,o)}return e.size===0?null:Array.from(e.entries()).sort((n,r)=>n[0]-r[0]).map(([n,r])=>({magnification:n,weight:r}))}function sc(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 ac(t,e){if(t===e)return!0;if(!t||!e)return t===e;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1)if(t[n].magnification!==e[n].magnification||t[n].size!==e[n].size)return!1;return!0}function lc(t,e){if(t===e)return!0;if(!t||!e)return t===e;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1)if(t[n].magnification!==e[n].magnification||t[n].weight!==e[n].weight)return!1;return!0}function cc(t,e){if(!Number.isFinite(t))return e[0]?.size??ht;if(e.length===0)return ht;if(e.length===1||t<=e[0].zoom)return e[0].size;for(let s=1;s<e.length;s+=1){const a=e[s-1],l=e[s];if(t>l.zoom)continue;const c=Math.max(1e-6,l.zoom-a.zoom),f=F((t-a.zoom)/c,0,1);return a.size+(l.size-a.size)*f}const n=e[e.length-1],r=e[e.length-2],i=Math.max(1e-6,n.zoom-r.zoom),o=(n.size-r.size)/i;return n.size+(t-n.zoom)*o}function uc(t,e){if(!Number.isFinite(t))return e[0]?.size??ht;if(e.length===0)return ht;if(e.length===1||t<=e[0].magnification)return e[0].size;for(let s=1;s<e.length;s+=1){const a=e[s-1],l=e[s];if(t>l.magnification)continue;const c=Math.max(1e-6,l.magnification-a.magnification),f=F((t-a.magnification)/c,0,1);return a.size+(l.size-a.size)*f}const n=e[e.length-1],r=e[e.length-2],i=Math.max(1e-6,n.magnification-r.magnification),o=(n.size-r.size)/i;return n.size+(t-n.magnification)*o}function fc(t,e){if(!Number.isFinite(t))return e[0]?.weight??1;if(e.length===0)return 1;if(e.length===1||t<=e[0].magnification)return e[0].weight;for(let s=1;s<e.length;s+=1){const a=e[s-1],l=e[s];if(t>l.magnification)continue;const c=Math.max(1e-6,l.magnification-a.magnification),f=F((t-a.magnification)/c,0,1);return a.weight+(l.weight-a.weight)*f}const n=e[e.length-1],r=e[e.length-2],i=Math.max(1e-6,n.magnification-r.magnification),o=(n.weight-r.weight)/i;return n.weight+(t-n.magnification)*o}function Gt(t){return typeof t!="number"||!Number.isFinite(t)?1:F(t,$l,Kl)}function Qr(t){return typeof t!="number"||!Number.isFinite(t)?1:F(t,jl,Ql)}function hc(t){return t?[F(t[0],0,100),F(t[1],0,100)]:[1,0]}function Jr(t){return typeof t!="number"||!Number.isFinite(t)?0:F(t,Jl,ec)}function ei(t){const e=Zo(t,[...Ji,255]);return[e[0],e[1],e[2]]}function dn(t){return typeof t!="number"||!Number.isFinite(t)?0:F(t,tc,nc)}function ti(t){const e=dn(t?.brightness),n=dn(t?.contrast),r=dn(t?.saturation);return{brightness:e/200,contrast:n/100,saturation:r/100}}function Hn(t){return t}function mn(t){return typeof t!="number"||!Number.isFinite(t)?0:F(t,0,rc)}function Ot(t){return typeof t!="number"||!Number.isFinite(t)||t<=0?null:Math.max(1e-6,t)}function gn(t){return typeof t=="function"?t:Hn}function eo(t,e,n){const r=t.getBoundingClientRect(),i=e-r.left-r.width*.5,o=n-r.top-r.height*.5;return Math.atan2(o,i)}function to(t,e){if(e.pointerId!==null&&t.hasPointerCapture(e.pointerId))try{t.releasePointerCapture(e.pointerId)}catch{}e.dragging=!1,e.mode="none",e.rotateLastAngleRad=null,e.pointerId=null,t.classList.remove("dragging")}function dc(t){const{event:e,canvas:n,state:r,config:i,cancelViewAnimation:o}=t,s=i.ctrlDragRotate&&(e.ctrlKey||e.metaKey);(e.button===0||s&&e.button===2)&&(o(),s&&e.preventDefault(),r.dragging=!0,r.mode=s?"rotate":"pan",r.pointerId=e.pointerId,r.lastPointerX=e.clientX,r.lastPointerY=e.clientY,r.rotateLastAngleRad=r.mode==="rotate"?eo(n,e.clientX,e.clientY):null,n.classList.add("dragging"),n.setPointerCapture(e.pointerId))}function mc(t){const{event:e,canvas:n,state:r,config:i,camera:o,clampViewState:s,emitViewState:a,requestRender:l}=t;if(!r.dragging||e.pointerId!==r.pointerId)return;const c=e.clientX-r.lastPointerX,f=e.clientY-r.lastPointerY;if(r.lastPointerX=e.clientX,r.lastPointerY=e.clientY,r.mode==="rotate"){const u=eo(n,e.clientX,e.clientY),h=r.rotateLastAngleRad;if(r.rotateLastAngleRad=u,h!==null){const d=u-h,m=Math.atan2(Math.sin(d),Math.cos(d)),p=i.rotationDragSensitivityDegPerPixel/Fn,b=o.getViewState();o.setViewState({rotationDeg:b.rotationDeg-m*180/Math.PI*p})}}else{const u=o.getViewState(),h=Math.max(1e-6,u.zoom),d=on(u.rotationDeg),m=Math.cos(d),p=Math.sin(d),b=(c*m-f*p)/h,y=(c*p+f*m)/h;o.setViewState({offsetX:u.offsetX-b,offsetY:u.offsetY-y})}s(),a(),l()}function gc(t,e,n){t.pointerId===n.pointerId&&to(e,n)}function pc(t){const{event:e,canvas:n,onZoomBy:r}=t;e.preventDefault();const i=n.getBoundingClientRect(),o=e.clientX-i.left,s=e.clientY-i.top;no(e.deltaY,o,s,r)}const yc=4;function no(t,e,n,r){const i=t<0?1.12:.89;r(i,e,n)}function ro(t,e,n,r,i){const o=t<0?"in":t>0?"out":null;if(o&&r.blockedDirection)if(o!==r.blockedDirection)r.blockedDirection=null,r.accumulatedDelta=0;else return;if(r.accumulatedDelta!==0&&t!==0&&Math.sign(r.accumulatedDelta)!==Math.sign(t)&&(r.accumulatedDelta=0),r.accumulatedDelta+=t,Math.abs(r.accumulatedDelta)<yc)return;const s=r.accumulatedDelta>0?"out":"in";if(r.accumulatedDelta=0,!i(s,e,n)){r.blockedDirection=s;return}r.blockedDirection=null}function bc(t){const{event:e,canvas:n,snapState:r,onSnapZoom:i}=t;e.preventDefault();const o=n.getBoundingClientRect(),s=e.clientX-o.left,a=e.clientY-o.top;ro(e.deltaY,s,a,r,i)}function xc(t){const{event:e,canvas:n,onZoomBy:r}=t,i=n.getBoundingClientRect(),o=e.clientX-i.left,s=e.clientY-i.top;r(e.shiftKey?.8:1.25,o,s)}function wc(t,e){(e||t.ctrlKey||t.metaKey)&&t.preventDefault()}function nn(t){const e=t.getViewCorners();let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[s,a]of e)s<n&&(n=s),s>i&&(i=s),a<r&&(r=a),a>o&&(o=a);return[n,r,i,o]}function Zt(t,e,n=.2,r=.2){const i=nn(t),o=Math.max(1e-6,i[2]-i[0]),s=Math.max(1e-6,i[3]-i[1]),a=o*n,l=s*r,[c,f]=t.getCenter(),u=o*.5,h=s*.5,d=u-a,m=e.width-u+a,p=h-l,b=e.height-h+l,y=d<=m?F(c,d,m):e.width*.5,x=p<=b?F(f,p,b):e.height*.5;t.setCenter(y,x)}function Sc(t,e){const n=Math.max(1e-6,t.getViewState().zoom),r=e.maxTierZoom+Math.log2(n);return F(Math.floor(r),0,e.maxTierZoom)}function Ec(t,e){return!(t[2]<=e[0]||t[0]>=e[2]||t[3]<=e[1]||t[1]>=e[3])}function io(t,e,n){const r=nn(t),i=Math.pow(2,e.maxTierZoom-n),o=Math.ceil(e.width/i),s=Math.ceil(e.height/i),a=Math.max(1,Math.ceil(o/e.tileSize)),l=Math.max(1,Math.ceil(s/e.tileSize)),c=r[0],f=r[1],u=r[2],h=r[3],d=F(Math.floor(c/i/e.tileSize),0,a-1),m=F(Math.floor((u-1)/i/e.tileSize),0,a-1),p=F(Math.floor(f/i/e.tileSize),0,l-1),b=F(Math.floor((h-1)/i/e.tileSize),0,l-1);if(d>m||p>b)return[];const y=(c+u)*.5/i/e.tileSize,x=(f+h)*.5/i/e.tileSize,M=[];for(let S=p;S<=b;S+=1)for(let C=d;C<=m;C+=1){const A=C*e.tileSize*i,B=S*e.tileSize*i,z=Math.min((C+1)*e.tileSize,o)*i,Y=Math.min((S+1)*e.tileSize,s)*i,P=C-y,I=S-x;M.push({key:`${n}/${C}/${S}`,tier:n,x:C,y:S,bounds:[A,B,z,Y],distance2:P*P+I*I,url:qn(e,n,C,S)})}return M.sort((S,C)=>S.distance2-C.distance2),M}function Rc(t,e){const n=Sc(t,e);return{tier:n,visible:io(t,e,n)}}function Mc(t){t.interactionLocked||dc({event:t.event,canvas:t.canvas,state:t.state,config:{ctrlDragRotate:t.ctrlDragRotate,rotationDragSensitivityDegPerPixel:t.rotationDragSensitivityDegPerPixel},cancelViewAnimation:t.cancelViewAnimation})}function Ac(t){t.interactionLocked||mc({event:t.event,canvas:t.canvas,state:t.state,config:{ctrlDragRotate:t.ctrlDragRotate,rotationDragSensitivityDegPerPixel:t.rotationDragSensitivityDegPerPixel},camera:t.camera,clampViewState:()=>Zt(t.camera,t.source,t.panExtentX,t.panExtentY),emitViewState:t.emitViewState,requestRender:t.requestRender})}function Cc(t){t.interactionLocked||gc(t.event,t.canvas,t.state)}function Pc(t){t.interactionLocked||xc({event:t.event,canvas:t.canvas,onZoomBy:t.onZoomBy})}function vc(t){wc(t.event,t.state.dragging)}function Tc(t,e){to(t,e)}function Ic(t){return{pointerDown:e=>Mc({event:e,interactionLocked:t.getInteractionLocked(),canvas:t.canvas,state:t.state,ctrlDragRotate:t.getCtrlDragRotate(),rotationDragSensitivityDegPerPixel:t.getRotationDragSensitivityDegPerPixel(),cancelViewAnimation:t.cancelViewAnimation}),pointerMove:e=>Ac({event:e,interactionLocked:t.getInteractionLocked(),canvas:t.canvas,state:t.state,ctrlDragRotate:t.getCtrlDragRotate(),rotationDragSensitivityDegPerPixel:t.getRotationDragSensitivityDegPerPixel(),camera:t.camera,source:t.source,panExtentX:t.getPanExtentX(),panExtentY:t.getPanExtentY(),emitViewState:t.emitViewState,requestRender:t.requestRender}),pointerUp:e=>Cc({event:e,interactionLocked:t.getInteractionLocked(),canvas:t.canvas,state:t.state}),wheel:e=>{if(t.getInteractionLocked()){e.preventDefault();return}if(t.getUseZoomSnaps?.()&&t.onSnapZoom&&t.zoomSnapState){bc({event:e,canvas:t.canvas,snapState:t.zoomSnapState,onSnapZoom:t.onSnapZoom});return}pc({event:e,canvas:t.canvas,onZoomBy:t.zoomBy})},doubleClick:e=>Pc({event:e,interactionLocked:t.getInteractionLocked(),canvas:t.canvas,onZoomBy:t.zoomBy}),contextMenu:e=>vc({event:e,canvas:t.canvas,state:t.state})}}function _c(t){const{gl:e,cache:n,maxCacheTiles:r}=t;if(n.size<=r)return;const i=Math.max(0,Math.floor(r));for(;n.size>i;){let o=null,s=null;for(const[a,l]of n)(!s||l.lastUsed<s.lastUsed)&&(o=a,s=l);if(!o||!s)break;e.deleteTexture(s.texture),n.delete(o)}}function Fc(t,e){if(t.isContextLost())return null;const n=t.createTexture();return n?(t.bindTexture(t.TEXTURE_2D,n),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,1),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),t.bindTexture(t.TEXTURE_2D,null),n):null}function Lc(t){const{gl:e,cache:n,tile:r,bitmap:i,frameSerial:o,maxCacheTiles:s,destroyed:a,contextLost:l,requestRender:c}=t;if(a||l||e.isContextLost()){i.close();return}if(n.has(r.key)){i.close();return}const f=Fc(e,i);i.close(),f&&(n.set(r.key,{key:r.key,texture:f,bounds:r.bounds,tier:r.tier,lastUsed:o}),_c({gl:e,cache:n,maxCacheTiles:s}),c())}function Dc(t,e){for(const[,n]of e)t.deleteTexture(n.texture)}function Nc(t){const{event:e,destroyed:n,contextLost:r,cancelViewAnimation:i,cancelDrag:o,tileScheduler:s,cache:a,onContextLost:l}=t;if(e.preventDefault(),n||r)return{handled:!1,frame:t.frame};let c=t.frame;return c!==null&&(cancelAnimationFrame(c),c=null),i(),o(),s.clear(),a.clear(),l?.(),{handled:!0,frame:c}}function zc(t){if(t.destroyed)return{didDestroy:!1,frame:t.frame};let e=t.frame;if(e!==null&&(cancelAnimationFrame(e),e=null),t.cancelViewAnimation(),t.resizeObserver.disconnect(),t.removeDprListener(),t.removeCanvasEventListeners(),t.cancelDrag(),t.tileScheduler.destroy(),!t.contextLost&&!t.gl.isContextLost()){Dc(t.gl,t.cache),t.gl.deleteBuffer(t.tileProgram.vbo),t.gl.deleteVertexArray(t.tileProgram.vao),t.gl.deleteProgram(t.tileProgram.program);for(let n=0;n<t.pointPrograms.length;n+=1){const r=t.pointPrograms[n];t.gl.deleteBuffer(r.posBuffer),t.gl.deleteBuffer(r.classBuffer),t.gl.deleteBuffer(r.fillModeBuffer),t.gl.deleteBuffer(r.indexBuffer),t.gl.deleteTexture(r.paletteTexture),t.gl.deleteVertexArray(r.vao),t.gl.deleteProgram(r.program)}}return t.cache.clear(),{didDestroy:!0,frame:e}}function Bc(t,e){if(e<=0||t.length===0)return new Uint32Array(0);let n=t.length;for(let o=0;o<t.length;o+=1)t[o]<e||(n-=1);if(n===t.length)return t;if(n<=0)return new Uint32Array(0);const r=new Uint32Array(n);let i=0;for(let o=0;o<t.length;o+=1){const s=t[o];s>=e||(r[i]=s,i+=1)}return r}function kc(t,e){return e<=0?new Uint8Array(0):t.length<e?new Uint8Array(e):t.subarray(0,e)}function ni(t,e,n,r,i){if(!i||i.length===0)return{...t,lastPointPalette:null};const o=new Uint8Array(i);if(r||e.isContextLost())return{...t,lastPointPalette:o};const s=Math.max(1,Math.floor(o.length/4));return e.bindTexture(e.TEXTURE_2D,n.paletteTexture),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,s,1,0,e.RGBA,e.UNSIGNED_BYTE,o),e.bindTexture(e.TEXTURE_2D,null),{...t,lastPointPalette:o,pointPaletteSize:s}}function ri(t,e,n,r,i){if(!i||!i.count||!i.positions||!i.paletteIndices)return{...t,lastPointData:null,pointCount:0,usePointIndices:!1};const o=i.fillModes instanceof Uint8Array?i.fillModes:null,s=o!==null,a=Math.max(0,Math.min(i.count,Math.floor(i.positions.length/2),i.paletteIndices.length,s?o.length:Number.MAX_SAFE_INTEGER)),l=i.positions.subarray(0,a*2),c=i.paletteIndices.subarray(0,a),f=s?o.subarray(0,a):void 0,u=i.drawIndices instanceof Uint32Array,h=u?Bc(i.drawIndices,a):null,d=t.lastPointData,m=d?.fillModes instanceof Uint8Array,p=t.pointBuffersDirty||!d||d.count!==a||!Ut(d.positions,l)||!Ut(d.paletteIndices,c)||m!==s||s&&(!d?.fillModes||!Ut(d.fillModes,f)),b=t.pointBuffersDirty||u&&(!d?.drawIndices||!Ut(d.drawIndices,h))||!u&&!!d?.drawIndices,y={...t,lastPointData:{count:a,positions:l,paletteIndices:c,fillModes:f,drawIndices:u?h??void 0:void 0}};if(r||e.isContextLost())return y;const x=y.lastPointData;if(!x)return y;if(p){e.bindBuffer(e.ARRAY_BUFFER,n.posBuffer),e.bufferData(e.ARRAY_BUFFER,x.positions,e.STATIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,n.classBuffer),e.bufferData(e.ARRAY_BUFFER,x.paletteIndices,e.STATIC_DRAW);const M=kc(y.zeroFillModes,a);e.bindBuffer(e.ARRAY_BUFFER,n.fillModeBuffer),e.bufferData(e.ARRAY_BUFFER,x.fillModes??M,e.STATIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,null),y.zeroFillModes=M}return u&&b&&(e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n.indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,h??new Uint32Array(0),e.DYNAMIC_DRAW),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),y.usePointIndices=u,y.pointCount=u?h?.length??0:x.count,(p||b)&&(y.pointBuffersDirty=!1),y}function Uc(t){const{gl:e,camera:n,source:r,cache:i,frameSerial:o,tileProgram:s,imageColorSettings:a,pointLayers:l,tileScheduler:c,getVisibleTiles:f,getVisibleTilesForTier:u,getViewBounds:h,intersectsBounds:d}=t;e.clearColor(.03,.06,.1,1),e.clear(e.COLOR_BUFFER_BIT);const{tier:m,visible:p}=f(),b=h(),y=new Set(p.map(P=>P.key));e.useProgram(s.program),e.bindVertexArray(s.vao),e.uniformMatrix3fv(s.uCamera,!1,n.getMatrix()),e.uniform1i(s.uTexture,0),e.uniform1f(s.uBrightness,a.brightness),e.uniform1f(s.uContrast,a.contrast),e.uniform1f(s.uSaturation,a.saturation);const x=[];for(const[,P]of i)y.has(P.key)||d(P.bounds,b)&&x.push(P);x.sort((P,I)=>P.tier-I.tier);for(const P of x)P.lastUsed=o,e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,P.texture),e.uniform4f(s.uBounds,P.bounds[0],P.bounds[1],P.bounds[2],P.bounds[3]),e.drawArrays(e.TRIANGLE_STRIP,0,4);let M=0;const S=[];for(const P of p){const I=i.get(P.key);if(!I){S.push(P);continue}I.lastUsed=o,e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,I.texture),e.uniform4f(s.uBounds,I.bounds[0],I.bounds[1],I.bounds[2],I.bounds[3]),e.drawArrays(e.TRIANGLE_STRIP,0,4),M+=1}const C=S.slice(),A=1e6,B=[];m>0&&B.push(m-1),m<r.maxTierZoom&&B.push(m+1);for(const P of B){const I=u(P);for(const O of I)i.has(O.key)||(O.distance2+=A,C.push(O))}c.schedule(C),e.bindTexture(e.TEXTURE_2D,null),e.bindVertexArray(null);let z=0,Y=0;if(l.length>0){e.enable(e.BLEND),e.blendFunc(e.ONE,e.ONE_MINUS_SRC_ALPHA);for(let P=0;P<l.length;P+=1){const I=l[P];I.pointCount<=0||(e.useProgram(I.pointProgram.program),e.bindVertexArray(I.pointProgram.vao),e.uniformMatrix3fv(I.pointProgram.uCamera,!1,n.getMatrix()),e.uniform1f(I.pointProgram.uPointSize,I.pointSizePx),e.uniform1f(I.pointProgram.uPointCssSize,I.pointCssSizePx),e.uniform2f(I.pointProgram.uPointLineDash,I.pointLineDash[0],I.pointLineDash[1]),e.uniform1f(I.pointProgram.uPointOpacity,I.pointOpacity),e.uniform1f(I.pointProgram.uPointStrokeScale,I.pointStrokeScale),e.uniform1f(I.pointProgram.uPointInnerFillAlpha,I.pointInnerFillOpacity),e.uniform3f(I.pointProgram.uPointInnerFillColor,I.pointInnerFillColor[0],I.pointInnerFillColor[1],I.pointInnerFillColor[2]),e.uniform1f(I.pointProgram.uPaletteSize,I.pointPaletteSize),e.uniform1i(I.pointProgram.uPalette,1),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,I.pointProgram.paletteTexture),I.usePointIndices?e.drawElements(e.POINTS,I.pointCount,e.UNSIGNED_INT,0):e.drawArrays(e.POINTS,0,I.pointCount),z+=I.pointCount,Y+=1)}e.bindTexture(e.TEXTURE_2D,null),e.bindVertexArray(null)}return{tier:m,visible:p.length,rendered:M,points:z,fallback:x.length,cacheHits:M,cacheMisses:S.length,drawCalls:x.length+M+Y}}function ii(t){const r=xt(t,`#version 300 es
|
|
135
135
|
precision highp float;
|
|
136
136
|
in vec2 aUnit;
|
|
137
137
|
in vec2 aUv;
|
|
@@ -176,7 +176,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
176
176
|
|
|
177
177
|
color.rgb = clamp(color.rgb + uBrightness, vec3(0.0), vec3(1.0));
|
|
178
178
|
outColor = color;
|
|
179
|
-
}`),i=
|
|
179
|
+
}`),i=Ie(t,r,"uCamera"),o=Ie(t,r,"uBounds"),s=Ie(t,r,"uTexture"),a=Ie(t,r,"uBrightness"),l=Ie(t,r,"uContrast"),c=Ie(t,r,"uSaturation"),f=t.createVertexArray(),u=t.createBuffer();if(!f||!u)throw new Error("buffer allocation failed");t.bindVertexArray(f),t.bindBuffer(t.ARRAY_BUFFER,u),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,0,1,0,1,0,0,1,0,1,1,1,1,1]),t.STATIC_DRAW);const h=t.getAttribLocation(r,"aUnit"),d=t.getAttribLocation(r,"aUv");if(h<0||d<0)throw new Error("tile attribute lookup failed");return t.enableVertexAttribArray(h),t.enableVertexAttribArray(d),t.vertexAttribPointer(h,2,t.FLOAT,!1,16,0),t.vertexAttribPointer(d,2,t.FLOAT,!1,16,8),t.bindVertexArray(null),t.bindBuffer(t.ARRAY_BUFFER,null),{program:r,vao:f,vbo:u,uCamera:i,uBounds:o,uTexture:s,uBrightness:a,uContrast:l,uSaturation:c}}function oi(t){const r=xt(t,`#version 300 es
|
|
180
180
|
precision highp float;
|
|
181
181
|
in vec2 aPosition;
|
|
182
182
|
in uint aClass;
|
|
@@ -243,6 +243,6 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
243
243
|
vec3 fillRgb = (uPointInnerFillColor / 255.0) * fillAlpha * pointOpacity;
|
|
244
244
|
outColor = vec4(color.rgb * ringAlpha * pointOpacity + fillRgb, alpha);
|
|
245
245
|
}
|
|
246
|
-
}`),i=_e(t,r,"uCamera"),o=_e(t,r,"uPointSize"),s=_e(t,r,"uPointCssSize"),a=_e(t,r,"uPointOpacity"),l=_e(t,r,"uPointStrokeScale"),c=_e(t,r,"uPointInnerFillAlpha"),f=_e(t,r,"uPointInnerFillColor"),u=_e(t,r,"uPalette"),h=_e(t,r,"uPaletteSize"),d=_e(t,r,"uPointLineDash"),m=t.createVertexArray(),p=t.createBuffer(),b=t.createBuffer(),y=t.createBuffer(),x=t.createBuffer(),M=t.createTexture();if(!m||!p||!b||!y||!x||!M)throw new Error("point buffer allocation failed");t.bindVertexArray(m),t.bindBuffer(t.ARRAY_BUFFER,p),t.bufferData(t.ARRAY_BUFFER,0,t.DYNAMIC_DRAW);const S=t.getAttribLocation(r,"aPosition");if(S<0)throw new Error("point position attribute not found");t.enableVertexAttribArray(S),t.vertexAttribPointer(S,2,t.FLOAT,!1,0,0),t.bindBuffer(t.ARRAY_BUFFER,b),t.bufferData(t.ARRAY_BUFFER,0,t.DYNAMIC_DRAW);const C=t.getAttribLocation(r,"aClass");if(C<0)throw new Error("point class attribute not found");t.enableVertexAttribArray(C),t.vertexAttribIPointer(C,1,t.UNSIGNED_SHORT,0,0),t.bindBuffer(t.ARRAY_BUFFER,y),t.bufferData(t.ARRAY_BUFFER,0,t.DYNAMIC_DRAW);const A=t.getAttribLocation(r,"aFillMode");if(A<0)throw new Error("point fill mode attribute not found");return t.enableVertexAttribArray(A),t.vertexAttribIPointer(A,1,t.UNSIGNED_BYTE,0,0),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,x),t.bufferData(t.ELEMENT_ARRAY_BUFFER,0,t.DYNAMIC_DRAW),t.bindVertexArray(null),t.bindBuffer(t.ARRAY_BUFFER,null),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null),t.bindTexture(t.TEXTURE_2D,M),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,new Uint8Array([160,160,160,255])),t.bindTexture(t.TEXTURE_2D,null),{program:r,vao:m,posBuffer:p,classBuffer:b,fillModeBuffer:y,indexBuffer:x,paletteTexture:M,uCamera:i,uPointSize:o,uPointCssSize:s,uPointOpacity:a,uPointLineDash:d,uPointStrokeScale:l,uPointInnerFillAlpha:c,uPointInnerFillColor:f,uPalette:u,uPaletteSize:h}}function oo(t){t.animation=null,t.frame!==null&&(cancelAnimationFrame(t.frame),t.frame=null)}function Oc(t){const{state:e,camera:n,target:r,durationMs:i,easing:o,onUpdate:s}=t,a=n.getViewState();oo(e),e.animation={startMs:we(),durationMs:Math.max(0,i),from:a,to:r,easing:o};const l=()=>{const c=e.animation;if(!c)return;const f=Math.max(0,we()-c.startMs),u=c.durationMs<=0?1:_(f/c.durationMs,0,1);let h=u;try{h=c.easing(u)}catch{h=u}if(Number.isFinite(h)||(h=u),h=_(h,0,1),n.setViewState({zoom:c.from.zoom+(c.to.zoom-c.from.zoom)*h,offsetX:c.from.offsetX+(c.to.offsetX-c.from.offsetX)*h,offsetY:c.from.offsetY+(c.to.offsetY-c.from.offsetY)*h,rotationDeg:c.from.rotationDeg+(c.to.rotationDeg-c.from.rotationDeg)*h}),s(),u>=1){e.animation=null,e.frame=null;return}e.frame=requestAnimationFrame(l)};e.frame=requestAnimationFrame(l)}function Wc(t){const e=Math.max(t*.5,1e-6),n=Math.max(1,t*8);return{minZoom:e,maxZoom:Math.max(e,n)}}function Yc(t,e,n){const r=Wc(t);let i=e??r.minZoom,o=n??r.maxZoom;return i=Math.max(1e-6,i),o=Math.max(1e-6,o),i>o&&(i=o),{minZoom:i,maxZoom:o}}function Xc(t,e,n,r,i){const o=t.getViewState(),s={zoom:typeof r.zoom=="number"&&Number.isFinite(r.zoom)?_(r.zoom,e,n):o.zoom,offsetX:typeof r.offsetX=="number"&&Number.isFinite(r.offsetX)?r.offsetX:o.offsetX,offsetY:typeof r.offsetY=="number"&&Number.isFinite(r.offsetY)?r.offsetY:o.offsetY,rotationDeg:typeof r.rotationDeg=="number"&&Number.isFinite(r.rotationDeg)?r.rotationDeg:o.rotationDeg};t.setViewState(s),i();const a=t.getViewState();return t.setViewState(o),a}function si(t,e,n,r,i,o=0){const s=Math.min(e/t.width,n/t.height),a=Number.isFinite(s)&&s>0?s:1,l=_(a,r,i),c=e/l,f=n/l;return{fitZoom:a,target:{zoom:l,offsetX:(t.width-c)*.5,offsetY:(t.height-f)*.5,rotationDeg:o}}}function Vc(t,e,n,r,i,o){const s=t.getViewState(),a=_(s.zoom*r,e,n);if(a===s.zoom)return null;const[l,c]=t.screenToWorld(i,o),f=t.getViewportSize(),u=i-f.width*.5,h=o-f.height*.5,d=on(s.rotationDeg),m=Math.cos(d),p=Math.sin(d),b=u/a*m-h/a*p,y=u/a*p+h/a*m,x=l-b,M=c-y;return{zoom:a,offsetX:x-f.width/(2*a),offsetY:M-f.height/(2*a)}}function Gc(t,e,n,r,i,o){const s=t.getViewState(),a=_(r,e,n);if(a===s.zoom)return null;const[l,c]=t.screenToWorld(i,o),f=t.getViewportSize(),u=i-f.width*.5,h=o-f.height*.5,d=on(s.rotationDeg),m=Math.cos(d),p=Math.sin(d),b=u/a*m-h/a*p,y=u/a*p+h/a*m,x=l-b,M=c-y;return{zoom:a,offsetX:x-f.width/(2*a),offsetY:M-f.height/(2*a)}}const Zc=250;function ai(t,e){if(!t||t.length===0)return[];if(!e||e<=0)return[];const n=10/e;return t.map(r=>r/n).filter(r=>Number.isFinite(r)&&r>0).sort((r,i)=>r-i)}function qc(t,e,n,r){if(t.length===0)return null;const i=Math.max(e*.005,1e-8);if(n==="in"){for(const o of t)if(o>e+i)return{type:"snap",zoom:o};return null}for(let o=t.length-1;o>=0;o--)if(t[o]<e-i)return{type:"snap",zoom:t[o]};return r&&e<=t[0]+i?{type:"fit"}:null}function Hc(t,e,n,r,i){const o=t.camera.getViewState(),[s,a]=t.camera.screenToWorld(n,r),l=t.camera.getViewportSize(),c=_(e,t.minZoom,t.maxZoom);if(c===o.zoom)return;const f=on(o.rotationDeg),u=Math.cos(f),h=Math.sin(f),d=n-l.width*.5,m=r-l.height*.5;t.cancelViewAnimation();const p=x=>{const M=d/x*u-m/x*h,S=d/x*h+m/x*u;return{offsetX:s-M-l.width/(2*x),offsetY:a-S-l.height/(2*x)}},b=p(c);t.viewAnimationState.animation={startMs:we(),durationMs:Math.max(0,i),from:o,to:{zoom:c,offsetX:b.offsetX,offsetY:b.offsetY,rotationDeg:o.rotationDeg},easing:Hn};const y=()=>{const x=t.viewAnimationState.animation;if(!x)return;const M=Math.max(0,we()-x.startMs),S=_(M/i,0,1),C=_(S*S*(3-2*S),0,1),A=o.zoom+(c-o.zoom)*C,{offsetX:k,offsetY:U}=p(A);t.camera.setViewState({zoom:A,offsetX:k,offsetY:U,rotationDeg:o.rotationDeg});const Y=S>=1;Y&&(t.clampViewState(),t.viewAnimationState.animation=null,t.viewAnimationState.frame=null),t.onViewStateChange(t.camera.getViewState()),t.requestRender(),Y||(t.viewAnimationState.frame=requestAnimationFrame(y))};t.viewAnimationState.frame=requestAnimationFrame(y)}const Le="__default_point_layer__";class so{constructor(e,n,r={}){E(this,"canvas");E(this,"source");E(this,"gl");E(this,"camera",new ci);E(this,"onViewStateChange");E(this,"onStats");E(this,"onTileError");E(this,"onContextLost");E(this,"onContextRestored");E(this,"resizeObserver");E(this,"removeDprListener");E(this,"tileProgram");E(this,"tileScheduler");E(this,"authToken");E(this,"destroyed",!1);E(this,"contextLost",!1);E(this,"frame",null);E(this,"frameSerial",0);E(this,"interactionState",{dragging:!1,mode:"none",rotateLastAngleRad:null,pointerId:null,lastPointerX:0,lastPointerY:0});E(this,"interactionLocked",!1);E(this,"ctrlDragRotate",!0);E(this,"rotationDragSensitivityDegPerPixel",Fn);E(this,"maxCacheTiles");E(this,"fitZoom",1);E(this,"initialRotationDeg",0);E(this,"minZoom",1e-6);E(this,"maxZoom",1);E(this,"minZoomOverride",null);E(this,"maxZoomOverride",null);E(this,"viewTransitionDurationMs",0);E(this,"viewTransitionEasing",Hn);E(this,"viewAnimationState",{animation:null,frame:null});E(this,"pointLayers",new Map);E(this,"defaultPointSizeZoomStops",tn(Ln));E(this,"defaultPointSizeMagnificationStops",null);E(this,"defaultPointWeightMagnificationStops",null);E(this,"defaultPointOpacity",1);E(this,"defaultPointLineDash",[1,0]);E(this,"defaultPointStrokeScale",1);E(this,"defaultPointInnerFillOpacity",0);E(this,"defaultPointInnerFillColor",[...Ji]);E(this,"imageColorSettings",{brightness:0,contrast:0,saturation:0});E(this,"cache",new Map);E(this,"zoomSnaps",[]);E(this,"zoomSnapFitAsMin",!1);E(this,"zoomSnapState",{accumulatedDelta:0,lastSnapTimeMs:0,blockedDirection:null});E(this,"panExtentX",.2);E(this,"panExtentY",.2);E(this,"boundPointerDown");E(this,"boundPointerMove");E(this,"boundPointerUp");E(this,"boundWheel");E(this,"boundDoubleClick");E(this,"boundContextMenu");E(this,"boundContextLost");E(this,"boundContextRestored");this.canvas=e,this.source=n,this.onViewStateChange=r.onViewStateChange,this.onStats=r.onStats,this.onTileError=r.onTileError,this.onContextLost=r.onContextLost,this.onContextRestored=r.onContextRestored,this.authToken=r.authToken??"",this.maxCacheTiles=Math.max(32,Math.floor(r.maxCacheTiles??320)),this.initialRotationDeg=typeof r.initialRotationDeg=="number"&&Number.isFinite(r.initialRotationDeg)?r.initialRotationDeg:0,this.ctrlDragRotate=r.ctrlDragRotate??!0,this.rotationDragSensitivityDegPerPixel=typeof r.rotationDragSensitivityDegPerPixel=="number"&&Number.isFinite(r.rotationDragSensitivityDegPerPixel)?Math.max(0,r.rotationDragSensitivityDegPerPixel):Fn,this.defaultPointSizeZoomStops=$r(r.pointSizeByZoom),this.defaultPointSizeMagnificationStops=Kr(r.pointSizeByMagnification),this.defaultPointWeightMagnificationStops=jr(r.pointWeightByMagnification),this.defaultPointOpacity=Qr(r.pointOpacity),this.defaultPointStrokeScale=Gt(r.pointStrokeScale),this.defaultPointInnerFillOpacity=Jr(r.pointInnerFillOpacity),this.defaultPointInnerFillColor=ei(r.pointInnerFillColor),this.imageColorSettings=ti(r.imageColorSettings),this.minZoomOverride=Ot(r.minZoom),this.maxZoomOverride=Ot(r.maxZoom),this.viewTransitionDurationMs=mn(r.viewTransition?.duration),this.viewTransitionEasing=gn(r.viewTransition?.easing),this.zoomSnaps=ai(r.zoomSnaps,this.source.mpp),this.zoomSnapFitAsMin=!!r.zoomSnapFitAsMin,this.applyPanExtent(r.panExtent);const i=e.getContext("webgl2",{alpha:!1,antialias:!1,depth:!1,stencil:!1,powerPreference:"high-performance"});if(!i)throw new Error("WebGL2 not supported");this.gl=i,this.tileProgram=ii(this.gl),this.tileScheduler=new Qi({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)=>Lc({gl:this.gl,cache:this.cache,tile:s,bitmap:a,frameSerial:this.frameSerial,maxCacheTiles:this.maxCacheTiles,destroyed:this.destroyed,contextLost:this.contextLost,requestRender:()=>this.requestRender()}),onTileError:(s,a,l)=>{this.onTileError?.({tile:s,error:a,attemptCount:l}),console.warn("tile load failed",s.url,a)}}),this.resizeObserver=new ResizeObserver(()=>this.resize()),this.resizeObserver.observe(e),this.removeDprListener=rn(()=>this.resize());const o=Ic({canvas:this.canvas,state:this.interactionState,getInteractionLocked:()=>this.interactionLocked,getCtrlDragRotate:()=>this.ctrlDragRotate,getRotationDragSensitivityDegPerPixel:()=>this.rotationDragSensitivityDegPerPixel,cancelViewAnimation:()=>this.cancelViewAnimation(),camera:this.camera,source:this.source,emitViewState:()=>this.onViewStateChange?.(this.camera.getViewState()),requestRender:()=>this.requestRender(),getPanExtentX:()=>this.panExtentX,getPanExtentY:()=>this.panExtentY,zoomBy:(s,a,l)=>this.zoomBy(s,a,l),getUseZoomSnaps:()=>this.zoomSnaps.length>0,onSnapZoom:(s,a,l)=>this.handleSnapZoom(s,a,l),zoomSnapState:this.zoomSnapState});this.boundPointerDown=o.pointerDown,this.boundPointerMove=o.pointerMove,this.boundPointerUp=o.pointerUp,this.boundWheel=o.wheel,this.boundDoubleClick=o.doubleClick,this.boundContextMenu=o.contextMenu,this.boundContextLost=s=>this.onWebGlContextLost(s),this.boundContextRestored=s=>this.onWebGlContextRestored(s),Zl(e,this.getCanvasHandlers()),this.fitToImage({duration:0}),this.resize()}getCanvasHandlers(){return{pointerDown:this.boundPointerDown,pointerMove:this.boundPointerMove,pointerUp:this.boundPointerUp,wheel:this.boundWheel,doubleClick:this.boundDoubleClick,contextMenu:this.boundContextMenu,contextLost:this.boundContextLost,contextRestored:this.boundContextRestored}}applyZoomBounds(){const e=Yc(this.fitZoom,this.minZoomOverride,this.maxZoomOverride);this.minZoom=e.minZoom,this.maxZoom=e.maxZoom}resolveTargetViewState(e){return Xc(this.camera,this.minZoom,this.maxZoom,e,()=>Zt(this.camera,this.source,this.panExtentX,this.panExtentY))}cancelViewAnimation(){oo(this.viewAnimationState)}startViewAnimation(e,n,r){Oc({state:this.viewAnimationState,camera:this.camera,target:e,durationMs:n,easing:r,onUpdate:()=>{Zt(this.camera,this.source,this.panExtentX,this.panExtentY),this.onViewStateChange?.(this.camera.getViewState()),this.requestRender()}})}createPointBufferRuntime(){return{pointCount:0,usePointIndices:!1,pointBuffersDirty:!0,lastPointData:null,zeroFillModes:new Uint8Array(0),lastPointPalette:null,pointPaletteSize:1}}createPointLayerState(e){return{id:e,program:oi(this.gl),runtime:this.createPointBufferRuntime(),pointSizeZoomStops:tn(this.defaultPointSizeZoomStops),pointSizeMagnificationStops:ic(this.defaultPointSizeMagnificationStops),pointWeightMagnificationStops:oc(this.defaultPointWeightMagnificationStops),pointOpacity:this.defaultPointOpacity,pointLineDash:[...this.defaultPointLineDash],pointStrokeScale:this.defaultPointStrokeScale,pointInnerFillOpacity:this.defaultPointInnerFillOpacity,pointInnerFillColor:[...this.defaultPointInnerFillColor]}}ensurePointLayer(e=Le){const n=String(e||Le),r=this.pointLayers.get(n);if(r)return r;const i=this.createPointLayerState(n);return this.pointLayers.set(n,i),i}deletePointProgram(e){this.contextLost||this.gl.isContextLost()||(this.gl.deleteBuffer(e.posBuffer),this.gl.deleteBuffer(e.classBuffer),this.gl.deleteBuffer(e.fillModeBuffer),this.gl.deleteBuffer(e.indexBuffer),this.gl.deleteTexture(e.paletteTexture),this.gl.deleteVertexArray(e.vao),this.gl.deleteProgram(e.program))}getPointRenderLayers(){const e=Math.max(1,window.devicePixelRatio||1),n=[];for(const r of this.pointLayers.values()){const i=this.getPointSize(r.id);n.push({pointProgram:r.program,pointCount:r.runtime.pointCount,usePointIndices:r.runtime.usePointIndices,pointPaletteSize:r.runtime.pointPaletteSize,pointLineDash:r.pointLineDash,pointOpacity:r.pointOpacity,pointStrokeScale:this.getPointStrokeScale(r.id),pointInnerFillOpacity:r.pointInnerFillOpacity,pointInnerFillColor:r.pointInnerFillColor,pointCssSizePx:i,pointSizePx:i*e})}return n}applyViewStateAndRender(e,n=!0){n&&this.cancelViewAnimation(),this.camera.setViewState(e),this.onViewStateChange?.(this.camera.getViewState()),this.requestRender()}setAuthToken(e){this.authToken=String(e??""),this.tileScheduler.setAuthToken(this.authToken)}setZoomRange(e,n){const r=Ot(e),i=Ot(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();Rn(s,o)||this.applyViewStateAndRender(o)}setViewTransition(e){this.viewTransitionDurationMs=mn(e?.duration),this.viewTransitionEasing=gn(e?.easing)}setViewState(e,n){const r=this.resolveTargetViewState(e),i=this.camera.getViewState();if(Rn(i,r))return;const o=mn(n?.duration??this.viewTransitionDurationMs),s=gn(n?.easing??this.viewTransitionEasing);if(o<=0){this.applyViewStateAndRender(r);return}this.startViewAnimation(r,o,s)}getViewState(){return this.camera.getViewState()}getZoomRange(){return{minZoom:this.minZoom,maxZoom:this.maxZoom}}getRegionLabelAutoLiftCapZoom(){const e=this.zoomSnaps.filter(n=>n>=this.minZoom&&n<=this.maxZoom);return e.length>0?e[e.length-1]:this.maxZoom}isViewAnimating(){return this.viewAnimationState.animation!==null}registerPointLayer(e){this.ensurePointLayer(e)}unregisterPointLayer(e){const n=String(e||Le),r=this.pointLayers.get(n);r&&(this.pointLayers.delete(n),this.deletePointProgram(r.program),this.requestRender())}setPointPalette(e,n=Le){const r=this.ensurePointLayer(n);r.runtime=ni(r.runtime,this.gl,r.program,this.contextLost,e),!(!e||e.length===0)&&this.requestRender()}setPointLineDash(e,n=Le){const r=this.ensurePointLayer(n),i=hc(e);r.pointLineDash[0]===i[0]&&r.pointLineDash[1]===i[1]||(r.pointLineDash=i,this.requestRender())}setPointData(e,n=Le){const r=this.ensurePointLayer(n);r.runtime=ri(r.runtime,this.gl,r.program,this.contextLost,e),this.requestRender()}setInteractionLock(e){const n=!!e;this.interactionLocked!==n&&(this.interactionLocked=n,n&&this.cancelDrag())}setPointSizeByZoom(e,n=Le){const r=this.ensurePointLayer(n),i=$r(e);sc(r.pointSizeZoomStops,i)||(r.pointSizeZoomStops=i,this.requestRender())}setPointSizeByMagnification(e,n=Le){const r=this.ensurePointLayer(n),i=Kr(e);ac(r.pointSizeMagnificationStops,i)||(r.pointSizeMagnificationStops=i,this.requestRender())}setPointWeightByMagnification(e,n=Le){const r=this.ensurePointLayer(n),i=jr(e);lc(r.pointWeightMagnificationStops,i)||(r.pointWeightMagnificationStops=i,this.requestRender())}setPointOpacity(e,n=Le){const r=this.ensurePointLayer(n),i=Qr(e);r.pointOpacity!==i&&(r.pointOpacity=i,this.requestRender())}setPointStrokeScale(e,n=Le){const r=this.ensurePointLayer(n),i=Gt(e);r.pointStrokeScale!==i&&(r.pointStrokeScale=i,this.requestRender())}setPointInnerFillOpacity(e,n=Le){const r=this.ensurePointLayer(n),i=Jr(e);r.pointInnerFillOpacity!==i&&(r.pointInnerFillOpacity=i,this.requestRender())}setPointInnerFillColor(e,n=Le){const r=this.ensurePointLayer(n),i=ei(e);r.pointInnerFillColor[0]===i[0]&&r.pointInnerFillColor[1]===i[1]&&r.pointInnerFillColor[2]===i[2]||(r.pointInnerFillColor=i,this.requestRender())}setImageColorSettings(e){const n=ti(e),r=this.imageColorSettings;r.brightness===n.brightness&&r.contrast===n.contrast&&r.saturation===n.saturation||(this.imageColorSettings=n,this.requestRender())}cancelDrag(){Tc(this.canvas,this.interactionState)}screenToWorld(e,n){const r=this.canvas.getBoundingClientRect(),i=e-r.left,o=n-r.top;return this.camera.screenToWorld(i,o)}worldToScreen(e,n){return this.camera.worldToScreen(e,n)}setViewCenter(e,n,r){if(!Number.isFinite(e)||!Number.isFinite(n))return;const i=this.camera.getViewState(),o=Math.max(1e-6,i.zoom),s=this.camera.getViewportSize();this.setViewState({offsetX:e-s.width/(2*o),offsetY:n-s.height/(2*o)},r)}getViewCorners(){return this.camera.getViewCorners()}getInitialRotationDeg(){return this.initialRotationDeg}getViewBounds(){return nn(this.camera)}resetRotation(e){const n=this.camera.getViewState();Math.abs(n.rotationDeg-this.initialRotationDeg)<1e-6||this.setViewState({rotationDeg:this.initialRotationDeg},e)}getPointSize(e=Le){const n=this.pointLayers.get(String(e||Le)),r=n?.pointSizeMagnificationStops??this.defaultPointSizeMagnificationStops;if(r&&r.length>0){const l=Math.max(1e-6,this.camera.getViewState().zoom),c=En(this.source.mpp??0,l);if(c>0){const f=uc(c,r);return _(f,ht,Hr)}}const i=Math.max(1e-6,this.camera.getViewState().zoom),o=this.source.maxTierZoom+Math.log2(i),s=n?.pointSizeZoomStops??this.defaultPointSizeZoomStops,a=cc(o,s);return _(a,ht,Hr)}getPointSizeByZoom(e=Le){return this.getPointSize(e)}getPointStrokeScale(e=Le){const n=this.pointLayers.get(String(e||Le)),r=n?.pointWeightMagnificationStops??this.defaultPointWeightMagnificationStops;if(r&&r.length>0){const i=Math.max(1e-6,this.camera.getViewState().zoom),o=En(this.source.mpp??0,i);if(o>0)return Gt(fc(o,r))}return n?.pointStrokeScale??this.defaultPointStrokeScale}fitToImage(e){const n=this.canvas.getBoundingClientRect(),r=Math.max(1,n.width||1),i=Math.max(1,n.height||1),o=si(this.source,r,i,this.minZoom,this.maxZoom,this.initialRotationDeg);this.fitZoom=o.fitZoom,this.applyZoomBounds(),this.setViewState(o.target,e)}zoomBy(e,n,r,i){const o=Vc(this.camera,this.minZoom,this.maxZoom,e,n,r);o&&this.setViewState(o,i)}handleWheelZoom(e,n,r){if(this.zoomSnaps.length>0){ro(e,n,r,this.zoomSnapState,(i,o,s)=>this.handleSnapZoom(i,o,s));return}no(e,n,r,(i,o,s)=>this.zoomBy(i,o,s))}zoomTo(e,n,r,i){const o=Gc(this.camera,this.minZoom,this.maxZoom,e,n,r);o&&this.setViewState(o,i)}setZoomSnaps(e,n){this.zoomSnaps=ai(e,this.source.mpp),this.zoomSnapFitAsMin=!!n}setPanExtent(e){this.applyPanExtent(e)}applyPanExtent(e){typeof e=="number"&&Number.isFinite(e)?(this.panExtentX=Math.max(0,e),this.panExtentY=Math.max(0,e)):e!=null&&typeof e=="object"?(this.panExtentX=typeof e.x=="number"&&Number.isFinite(e.x)?Math.max(0,e.x):.2,this.panExtentY=typeof e.y=="number"&&Number.isFinite(e.y)?Math.max(0,e.y):.2):(this.panExtentX=.2,this.panExtentY=.2)}getZoomPivotAnimationContext(){return{camera:this.camera,viewAnimationState:this.viewAnimationState,minZoom:this.minZoom,maxZoom:this.maxZoom,cancelViewAnimation:()=>this.cancelViewAnimation(),clampViewState:()=>Zt(this.camera,this.source,this.panExtentX,this.panExtentY),onViewStateChange:e=>this.onViewStateChange?.(e),requestRender:()=>this.requestRender()}}handleSnapZoom(e,n,r){const i=this.viewAnimationState.animation,o=i?i.to.zoom:this.camera.getViewState().zoom,s=this.zoomSnaps.filter(f=>f>=this.minZoom&&f<=this.maxZoom),a=qc(s,o,e,this.zoomSnapFitAsMin);if(!a)return!1;let l;if(a.type==="fit"){const f=this.canvas.getBoundingClientRect(),u=Math.max(1,f.width||1),h=Math.max(1,f.height||1),d=si(this.source,u,h,this.minZoom,this.maxZoom,this.initialRotationDeg);this.fitZoom=d.fitZoom,this.applyZoomBounds(),l=d.target.zoom}else l=a.zoom;const c=Math.max(Math.abs(l)*.005,1e-8);if(i){if((i.to.zoom>i.from.zoom+c?"in":i.to.zoom<i.from.zoom-c?"out":null)===e&&Math.abs(i.to.zoom-l)<=c)return!1}else if(Math.abs(o-l)<=c)return!1;return Hc(this.getZoomPivotAnimationContext(),l,n,r,Zc),!0}render(){if(this.destroyed||this.contextLost||this.gl.isContextLost())return;const e=this.onStats?we():0;this.frameSerial+=1;const n=Uc({gl:this.gl,camera:this.camera,source:this.source,cache:this.cache,frameSerial:this.frameSerial,tileProgram:this.tileProgram,imageColorSettings:this.imageColorSettings,pointLayers:this.getPointRenderLayers(),tileScheduler:this.tileScheduler,getVisibleTiles:()=>Rc(this.camera,this.source),getVisibleTilesForTier:r=>io(this.camera,this.source,r),getViewBounds:()=>nn(this.camera),intersectsBounds:Ec});if(this.onStats){const r=this.tileScheduler.getSnapshot();this.onStats({tier:n.tier,visible:n.visible,rendered:n.rendered,points:n.points,fallback:n.fallback,cache:this.cache.size,inflight:r.inflight,queued:r.queued,retries:r.retries,failed:r.failed,aborted:r.aborted,cacheHits:n.cacheHits,cacheMisses:n.cacheMisses,drawCalls:n.drawCalls,frameMs:we()-e})}}requestRender(){this.frame!==null||this.destroyed||this.contextLost||this.gl.isContextLost()||(this.frame=requestAnimationFrame(()=>{this.frame=null,this.render()}))}resize(){Hl(this.canvas,this.gl,this.camera),this.requestRender()}onWebGlContextLost(e){const n=Nc({event:e,destroyed:this.destroyed,contextLost:this.contextLost,frame:this.frame,cancelViewAnimation:()=>this.cancelViewAnimation(),cancelDrag:()=>this.cancelDrag(),tileScheduler:this.tileScheduler,cache:this.cache,onContextLost:this.onContextLost});if(n.handled){this.frame=n.frame,this.contextLost=!0;for(const r of this.pointLayers.values())r.runtime={...r.runtime,pointBuffersDirty:!0}}}onWebGlContextRestored(e){if(!this.destroyed){this.contextLost=!1,this.cache.clear(),this.tileProgram=ii(this.gl);for(const n of this.pointLayers.values())n.program=oi(this.gl),n.runtime={...n.runtime,pointBuffersDirty:!0},n.runtime.lastPointPalette&&n.runtime.lastPointPalette.length>0&&(n.runtime=ni(n.runtime,this.gl,n.program,this.contextLost,n.runtime.lastPointPalette)),n.runtime.lastPointData&&(n.runtime=ri(n.runtime,this.gl,n.program,this.contextLost,n.runtime.lastPointData));this.resize(),this.onContextRestored?.()}}destroy(){const e=zc({destroyed:this.destroyed,frame:this.frame,cancelViewAnimation:()=>this.cancelViewAnimation(),resizeObserver:this.resizeObserver,removeDprListener:this.removeDprListener,removeCanvasEventListeners:()=>ql(this.canvas,this.getCanvasHandlers()),cancelDrag:()=>this.cancelDrag(),tileScheduler:this.tileScheduler,contextLost:this.contextLost,gl:this.gl,cache:this.cache,tileProgram:this.tileProgram,pointPrograms:Array.from(this.pointLayers.values(),n=>n.program)});e.didDestroy&&(this.destroyed=!0,this.frame=e.frame)}}const $c=[];function Kc(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function jc({source:t,viewState:e,onViewStateChange:n,onStats:r,onTileError:i,onContextLost:o,onContextRestored:s,imageColorSettings:a=null,initialRotate:l=0,fitNonce:c=0,rotationResetNonce:f=0,authToken:u="",ctrlDragRotate:h=!0,minZoom:d,maxZoom:m,viewTransition:p,zoomSnaps:b,zoomSnapFitAsMin:y,panExtent:x,onPointerWorldMove:M,debugOverlay:S=!1,debugOverlayStyle:C,className:A,style:k,children:U}){const Y=g.useRef(null),P=g.useRef(null),T=g.useRef(null),L=g.useRef(null),F=g.useRef(null),W=g.useRef(null),$=g.useRef($c),z=g.useRef(!1),ae=g.useRef(new Set),de=g.useRef(new Set),J=g.useRef(n),ve=g.useRef(r),Ae=g.useRef(i),D=g.useRef(o),v=g.useRef(s),[O,oe]=g.useState(0),[q,pe]=g.useState(null),le=g.useRef(S);g.useEffect(()=>{J.current=n},[n]),g.useEffect(()=>{ve.current=r},[r]),g.useEffect(()=>{Ae.current=i},[i]),g.useEffect(()=>{D.current=o},[o]),g.useEffect(()=>{v.current=s},[s]),g.useEffect(()=>{le.current=S,S||pe(null)},[S]);const ne=g.useMemo(()=>({position:"relative",width:"100%",height:"100%",...k}),[k]),Fe=g.useMemo(()=>({position:"absolute",top:8,left:8,zIndex:7,margin:0,padding:"8px 10px",maxWidth:"min(420px, 80%)",pointerEvents:"none",whiteSpace:"pre-wrap",lineHeight:1.35,fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:11,color:"#cde6ff",background:"rgba(6, 12, 20, 0.82)",border:"1px solid rgba(173, 216, 255, 0.28)",borderRadius:8,boxShadow:"0 8px 22px rgba(0,0,0,0.35)",...C}),[C]),ue=Kc(l),ye=g.useCallback(B=>({...B,rotationDeg:B.rotationDeg-ue}),[ue]),me=g.useCallback(B=>typeof B.rotationDeg!="number"||!Number.isFinite(B.rotationDeg)?B:{...B,rotationDeg:B.rotationDeg+ue},[ue]),re=g.useCallback(B=>{ve.current?.(B),le.current&&pe(B)},[]),se=g.useMemo(()=>q?[`tier ${q.tier} | frame ${q.frameMs?.toFixed(2)??"-"} ms | drawCalls ${q.drawCalls??"-"}`,`tiles visible ${q.visible} | rendered ${q.rendered} | fallback ${q.fallback}`,`cache size ${q.cache} | hit ${q.cacheHits??"-"} | miss ${q.cacheMisses??"-"}`,`queue inflight ${q.inflight} | queued ${q.queued??"-"} | retries ${q.retries??"-"} | failed ${q.failed??"-"} | aborted ${q.aborted??"-"}`,`points ${q.points}`].join(`
|
|
247
|
-
`):"stats: waiting for first frame...",[q]),ce=g.useCallback(()=>{const B=T.current;if(!B)return;const H=B.getContext("2d");if(!H)return;const Q=Math.max(1,window.devicePixelRatio||1),ee=B.getBoundingClientRect(),Se=Math.max(1,Math.round(ee.width*Q)),xe=Math.max(1,Math.round(ee.height*Q));(B.width!==Se||B.height!==xe)&&(B.width=Se,B.height=xe);const Me=ee.width,Ne=ee.height;H.setTransform(1,0,0,1,0,0),H.clearRect(0,0,B.width,B.height),H.setTransform(Q,0,0,Q,0,0);const w=$.current;for(let R=0;R<w.length;R+=1)H.save(),w[R].draw(H,Me,Ne),H.restore()},[]),Z=g.useCallback(()=>{z.current||(z.current=!0,requestAnimationFrame(()=>{z.current=!1,ce()}))},[ce]),Pe=g.useCallback((B,H,Q)=>{const ee=$.current.filter(Se=>Se.id!==B);ee.push({id:B,priority:H,draw:Q}),ee.sort((Se,xe)=>Se.priority-xe.priority),$.current=ee,Z()},[Z]),Ee=g.useCallback(B=>{$.current=$.current.filter(H=>H.id!==B),Z()},[Z]),be=g.useCallback((B,H)=>{H?ae.current.add(B):ae.current.delete(B),L.current?.setInteractionLock(ae.current.size>0)},[]),V=g.useCallback(()=>ae.current.size>0,[]),K=g.useCallback((B,H)=>{const Q=L.current;return Q?Bn(Q.worldToScreen(B,H)):null},[]),fe=g.useCallback((B,H)=>{const Q=L.current;if(!Q)return null;const ee=Q.screenToWorld(B,H);if(!Array.isArray(ee)||ee.length<2)return null;const Se=Number(ee[0]),xe=Number(ee[1]);return!Number.isFinite(Se)||!Number.isFinite(xe)?null:[Se,xe]},[]),te=g.useCallback(B=>(de.current.add(B),()=>{de.current.delete(B)}),[]),j=g.useCallback(B=>{J.current?.(ye(B));const H=de.current;if(H.size>0){const Q=Array.from(H);for(let ee=0;ee<Q.length;ee+=1)Q[ee](B)}F.current?.(),W.current?.(),Z()},[Z,ye]);g.useEffect(()=>{const B=P.current;if(!B||!t)return;const H=new so(B,t,{onViewStateChange:j,onStats:re,onTileError:Q=>{Ae.current?.(Q)},onContextLost:()=>{D.current?.()},onContextRestored:()=>{v.current?.()},authToken:u,imageColorSettings:a,initialRotationDeg:l,ctrlDragRotate:h,minZoom:d,maxZoom:m,viewTransition:p,zoomSnaps:b,zoomSnapFitAsMin:y,panExtent:x});return L.current=H,oe(Q=>Q+1),e&&H.setViewState(me(e)),H.setInteractionLock(ae.current.size>0),()=>{H.destroy(),L.current=null}},[t,re,h,j,ue,me]),g.useEffect(()=>{L.current?.setAuthToken(u)},[u]),g.useEffect(()=>{const B=L.current;!B||!e||B.isViewAnimating()||B.setViewState(me(e))},[e,me]),g.useEffect(()=>{L.current?.fitToImage()},[c]),g.useEffect(()=>{L.current?.resetRotation()},[f]),g.useEffect(()=>{L.current?.setZoomRange(d,m)},[d,m]),g.useEffect(()=>{L.current?.setViewTransition(p)},[p]),g.useEffect(()=>{L.current?.setZoomSnaps(b,y)},[b,y]),g.useEffect(()=>{L.current?.setPanExtent(x)},[x]),g.useEffect(()=>{L.current?.setImageColorSettings(a)},[a]),g.useEffect(()=>{const B=T.current;if(!B)return;F.current=Z,Z();const H=new ResizeObserver(()=>Z());return H.observe(B),()=>{H.disconnect(),F.current===Z&&(F.current=null)}},[Z]),g.useEffect(()=>rn(()=>Z()),[Z]);const Re=g.useMemo(()=>({source:t,rendererRef:L,rendererSerial:O,canvasRef:P,containerRef:Y,drawInvalidateRef:F,overviewInvalidateRef:W,worldToScreen:K,screenToWorld:fe,registerDrawCallback:Pe,unregisterDrawCallback:Ee,requestOverlayRedraw:Z,registerViewStateListener:te,setInteractionLock:be,isInteractionLocked:V}),[t,O,K,fe,Pe,Ee,Z,te,be,V]),X=g.useRef(M);g.useEffect(()=>{X.current=M},[M]);const Te=g.useCallback(B=>{const H=X.current;if(!H)return;const Q=fe(B.clientX,B.clientY),ee=!!Q&&Q[0]>=0&&Q[1]>=0&&!!t&&Q[0]<=t.width&&Q[1]<=t.height;H({coordinate:Q,clientX:B.clientX,clientY:B.clientY,insideImage:ee})},[fe,t]),De=g.useCallback(()=>{X.current?.({coordinate:null,clientX:-1,clientY:-1,insideImage:!1})},[]);return Ge.jsx(ca,{value:Re,children:Ge.jsxs("div",{ref:Y,className:A,style:ne,onPointerMove:M?Te:void 0,onPointerLeave:M?De:void 0,children:[Ge.jsx("canvas",{ref:P,className:"wsi-render-canvas",style:{position:"absolute",inset:0,zIndex:1,width:"100%",height:"100%",display:"block",touchAction:"none"}}),Ge.jsx("canvas",{ref:T,className:"wsi-overlay-canvas",style:{position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",pointerEvents:"none",touchAction:"none"}}),U,S&&Ge.jsx("pre",{"data-open-plant-debug-overlay":!0,style:Fe,children:se})]})})}function Qc(t){const e=[];for(let n=0;n<t.length;n+=1){const r=t[n],i=mt([dt(r?.coordinates)]);if(i.length===0)continue;let o=0,s=1/0,a=1/0,l=-1/0,c=-1/0;for(const f of i)o+=f.area,f.minX<s&&(s=f.minX),f.minY<a&&(a=f.minY),f.maxX>l&&(l=f.maxX),f.maxY>c&&(c=f.maxY);!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(l)||!Number.isFinite(c)||e.push({regionId:r.id??n,regionIndex:n,polygons:i,area:Math.max(1e-6,o),minX:s,minY:a,maxX:l,maxY:c})}return e}const Jc=128,pn=[];function ut(t,e,n,r,i){if(i<=1||n<=e)return 0;const o=(t-e)/r;return!Number.isFinite(o)||o<=0?0:o>=i-1?i-1:Math.floor(o)}function eu(t){if(t.length===0)return null;let e=1/0,n=1/0,r=-1/0,i=-1/0;for(const f of t)f.minX<e&&(e=f.minX),f.minY<n&&(n=f.minY),f.maxX>r&&(r=f.maxX),f.maxY>i&&(i=f.maxY);if(!Number.isFinite(e)||!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(i))return null;const o=Math.ceil(Math.sqrt(t.length*2)),s=Math.max(1,Math.min(Jc,o)),a=r>e?(r-e)/s:1,l=i>n?(i-n)/s:1,c=Array.from({length:s*s},()=>[]);for(let f=0;f<t.length;f+=1){const u=t[f],h=ut(u.minX,e,r,a,s),d=ut(u.maxX,e,r,a,s),m=ut(u.minY,n,i,l,s),p=ut(u.maxY,n,i,l,s);for(let b=m;b<=p;b+=1)for(let y=h;y<=d;y+=1)c[b*s+y].push(f)}return{minX:e,minY:n,maxX:r,maxY:i,gridSize:s,cellWidth:a,cellHeight:l,buckets:c}}function tu(t,e,n){if(!t||e<t.minX||e>t.maxX||n<t.minY||n>t.maxY)return pn;const r=ut(e,t.minX,t.maxX,t.cellWidth,t.gridSize),i=ut(n,t.minY,t.maxY,t.cellHeight,t.gridSize);return t.buckets[i*t.gridSize+r]??pn}function nu(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 ru(t,e,n={}){const r=Math.max(0,Math.min(Math.floor(t?.count??0),Math.floor((t?.positions?.length??0)/2),t?.paletteIndices?.length??0,t?.fillModes instanceof Uint8Array?t.fillModes.length:Number.MAX_SAFE_INTEGER));let i=null;if(t?.drawIndices instanceof Uint32Array){const d=t.drawIndices;let m=d.length;for(let p=0;p<d.length;p+=1)d[p]<r||(m-=1);if(m===d.length)i=d;else if(m>0){const p=new Uint32Array(m);let b=0;for(let y=0;y<d.length;y+=1){const x=d[y];x>=r||(p[b]=x,b+=1)}i=p}else i=new Uint32Array(0)}const o=i?i.length:r,s=Qc(e??[]);if(!t||o===0||s.length===0)return{groups:[],inputPointCount:o,pointsInsideAnyRegion:0,unmatchedPointCount:o};const a=new Map,l=new Map,c=eu(s);let f=0;for(let d=0;d<o;d+=1){const m=i?i[d]:d,p=t.positions[m*2],b=t.positions[m*2+1];if(!Number.isFinite(p)||!Number.isFinite(b))continue;let y=null;const x=tu(c,p,b);if(x.length===0)continue;for(const C of x){const A=s[C];let k=!1;for(const U of A.polygons)if(gi(p,b,U)){k=!0;break}k&&(!y||A.area<y.area)&&(y=A)}if(!y)continue;f+=1;const M=t.paletteIndices[m]??0,S=a.get(y.regionIndex)??new Map;S.set(M,(S.get(M)??0)+1),a.set(y.regionIndex,S),l.set(y.regionIndex,(l.get(y.regionIndex)??0)+1)}const u=n.includeEmptyRegions??!1,h=[];for(const d of s){const m=l.get(d.regionIndex)??0;if(!u&&m<=0)continue;const p=a.get(d.regionIndex)??new Map,b=Array.from(p.entries()).map(([y,x])=>({classId:nu(y,n.paletteIndexToClassId),paletteIndex:y,count:x})).sort((y,x)=>x.count-y.count||y.paletteIndex-x.paletteIndex);h.push({regionId:d.regionId,regionIndex:d.regionIndex,totalCount:m,classCounts:b})}return{groups:h,inputPointCount:o,pointsInsideAnyRegion:f,unmatchedPointCount:Math.max(0,o-f)}}function iu(t){return t.replace(/^\s*SRID\s*=\s*\d+\s*;\s*/i,"")}function ou(t){return t>="A"&&t<="Z"||t>="a"&&t<="z"}function su(t){return t>="0"&&t<="9"}function li(t){return t==="+"||t==="-"||t==="."||su(t)}class au{constructor(e){E(this,"text");E(this,"index",0);this.text=iu(e.trim())}parse(){if(!this.text)return null;const e=this.readWord();if(!e)return null;const n=e.toUpperCase();if(n!=="POLYGON"&&n!=="MULTIPOLYGON")return null;this.skipWhitespace();const r=this.peekWord();if(r){const s=r.toUpperCase();(s==="Z"||s==="M"||s==="ZM")&&(this.readWord(),this.skipWhitespace())}if(this.consumeWordIf("EMPTY"))return this.skipWhitespace(),this.isEof()?n==="POLYGON"?{type:"Polygon",coordinates:[]}:{type:"MultiPolygon",coordinates:[]}:null;let i;try{i=this.parseNestedList()}catch{return null}if(this.skipWhitespace(),!this.isEof())return null;if(n==="POLYGON"){const s=ao(i);return s?{type:"Polygon",coordinates:s}:null}const o=cu(i);return o?{type:"MultiPolygon",coordinates:o}:null}isEof(){return this.index>=this.text.length}currentChar(){return this.text[this.index]??""}skipWhitespace(){for(;!this.isEof()&&/\s/.test(this.currentChar());)this.index+=1}readWord(){if(this.skipWhitespace(),this.isEof())return null;const e=this.index;for(;!this.isEof()&&ou(this.currentChar());)this.index+=1;return this.index===e?null:this.text.slice(e,this.index)}peekWord(){const e=this.index,n=this.readWord();return this.index=e,n}consumeWordIf(e){const n=this.index,r=this.readWord();return!r||r.toUpperCase()!==e.toUpperCase()?(this.index=n,!1):!0}parseNestedList(){if(this.skipWhitespace(),this.currentChar()!=="(")throw new Error("Expected '('");this.index+=1;const e=[];for(;;){this.skipWhitespace(),this.currentChar()==="("?e.push(this.parseNestedList()):e.push(this.parseCoordinateTuple()),this.skipWhitespace();const n=this.currentChar();if(n===","){this.index+=1;continue}if(n===")"){this.index+=1;break}throw new Error("Expected ',' or ')'")}return e}parseCoordinateTuple(){this.skipWhitespace();const e=[];for(;;){this.skipWhitespace();const n=this.currentChar();if(!n||!li(n))break;const r=this.readNumber();if(r===null)break;e.push(r),this.skipWhitespace();const i=this.currentChar();if(!i||i===","||i===")")break;if(!li(i))throw new Error("Invalid coordinate")}if(e.length<2)throw new Error("Coordinate requires at least x y");return[e[0],e[1]]}readNumber(){if(this.skipWhitespace(),this.isEof())return null;const n=this.text.slice(this.index).match(/^[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?/);if(!n)return null;const r=Number(n[0]);return Number.isFinite(r)?(this.index+=n[0].length,r):null}}function lu(t){return Array.isArray(t)&&t.length>=2&&typeof t[0]=="number"&&Number.isFinite(t[0])&&typeof t[1]=="number"&&Number.isFinite(t[1])}function ao(t){if(!Array.isArray(t))return null;const e=[];for(const n of t){if(!Array.isArray(n))return null;const r=[];for(const i of n){if(!lu(i))return null;r.push([i[0],i[1]])}e.push(r)}return e}function cu(t){if(!Array.isArray(t))return null;const e=[];for(const n of t){const r=ao(n);if(!r)return null;e.push(r)}return e}function uu(t){return typeof t!="string"?null:new au(t).parse()}exports.DEFAULT_POINT_COLOR=Nn;exports.DrawLayer=Pi;exports.DrawingLayer=ua;exports.HeatmapLayer=Va;exports.M1TileRenderer=ui;exports.OverlayLayer=Za;exports.OverviewMap=nl;exports.PatchLayer=il;exports.PointLayer=Il;exports.RegionLayer=Xl;exports.TileScheduler=Qi;exports.TileViewerCanvas=Vl;exports.WsiTileRenderer=so;exports.WsiViewer=jc;exports.__heatmapLayerInternals=Ga;exports.buildClassPalette=Ho;exports.buildPointSpatialIndexAsync=ji;exports.calcScaleLength=Vo;exports.calcScaleResolution=zn;exports.calcViewingMagnification=En;exports.clamp=_;exports.closeRing=Oe;exports.computeRoiPointGroups=ru;exports.createCircle=Mn;exports.createRectangle=Qt;exports.createSpatialIndex=Ti;exports.filterPointDataByPolygons=Mt;exports.filterPointDataByPolygonsHybrid=qi;exports.filterPointDataByPolygonsInWorker=$i;exports.filterPointIndicesByPolygons=Vi;exports.filterPointIndicesByPolygonsInWorker=ml;exports.getWebGpuCapabilities=fl;exports.hexToRgba=pi;exports.isSameViewState=Rn;exports.lookupCellIndex=Ki;exports.normalizeImageClasses=qa;exports.normalizeImageInfo=$a;exports.parseWkt=uu;exports.prefilterPointsByBoundsWebGpu=Zi;exports.terminatePointHitIndexWorker=Ml;exports.terminateRoiClipWorker=dl;exports.toBearerToken=Go;exports.toRoiGeometry=dt;exports.toTileUrl=qn;exports.useViewerContext=st;
|
|
246
|
+
}`),i=Ie(t,r,"uCamera"),o=Ie(t,r,"uPointSize"),s=Ie(t,r,"uPointCssSize"),a=Ie(t,r,"uPointOpacity"),l=Ie(t,r,"uPointStrokeScale"),c=Ie(t,r,"uPointInnerFillAlpha"),f=Ie(t,r,"uPointInnerFillColor"),u=Ie(t,r,"uPalette"),h=Ie(t,r,"uPaletteSize"),d=Ie(t,r,"uPointLineDash"),m=t.createVertexArray(),p=t.createBuffer(),b=t.createBuffer(),y=t.createBuffer(),x=t.createBuffer(),M=t.createTexture();if(!m||!p||!b||!y||!x||!M)throw new Error("point buffer allocation failed");t.bindVertexArray(m),t.bindBuffer(t.ARRAY_BUFFER,p),t.bufferData(t.ARRAY_BUFFER,0,t.DYNAMIC_DRAW);const S=t.getAttribLocation(r,"aPosition");if(S<0)throw new Error("point position attribute not found");t.enableVertexAttribArray(S),t.vertexAttribPointer(S,2,t.FLOAT,!1,0,0),t.bindBuffer(t.ARRAY_BUFFER,b),t.bufferData(t.ARRAY_BUFFER,0,t.DYNAMIC_DRAW);const C=t.getAttribLocation(r,"aClass");if(C<0)throw new Error("point class attribute not found");t.enableVertexAttribArray(C),t.vertexAttribIPointer(C,1,t.UNSIGNED_SHORT,0,0),t.bindBuffer(t.ARRAY_BUFFER,y),t.bufferData(t.ARRAY_BUFFER,0,t.DYNAMIC_DRAW);const A=t.getAttribLocation(r,"aFillMode");if(A<0)throw new Error("point fill mode attribute not found");return t.enableVertexAttribArray(A),t.vertexAttribIPointer(A,1,t.UNSIGNED_BYTE,0,0),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,x),t.bufferData(t.ELEMENT_ARRAY_BUFFER,0,t.DYNAMIC_DRAW),t.bindVertexArray(null),t.bindBuffer(t.ARRAY_BUFFER,null),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null),t.bindTexture(t.TEXTURE_2D,M),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,new Uint8Array([160,160,160,255])),t.bindTexture(t.TEXTURE_2D,null),{program:r,vao:m,posBuffer:p,classBuffer:b,fillModeBuffer:y,indexBuffer:x,paletteTexture:M,uCamera:i,uPointSize:o,uPointCssSize:s,uPointOpacity:a,uPointLineDash:d,uPointStrokeScale:l,uPointInnerFillAlpha:c,uPointInnerFillColor:f,uPalette:u,uPaletteSize:h}}function oo(t){t.animation=null,t.frame!==null&&(cancelAnimationFrame(t.frame),t.frame=null)}function Oc(t){const{state:e,camera:n,target:r,durationMs:i,easing:o,onUpdate:s}=t,a=n.getViewState();oo(e),e.animation={startMs:Ee(),durationMs:Math.max(0,i),from:a,to:r,easing:o};const l=()=>{const c=e.animation;if(!c)return;const f=Math.max(0,Ee()-c.startMs),u=c.durationMs<=0?1:F(f/c.durationMs,0,1);let h=u;try{h=c.easing(u)}catch{h=u}if(Number.isFinite(h)||(h=u),h=F(h,0,1),n.setViewState({zoom:c.from.zoom+(c.to.zoom-c.from.zoom)*h,offsetX:c.from.offsetX+(c.to.offsetX-c.from.offsetX)*h,offsetY:c.from.offsetY+(c.to.offsetY-c.from.offsetY)*h,rotationDeg:c.from.rotationDeg+(c.to.rotationDeg-c.from.rotationDeg)*h}),s(),u>=1){e.animation=null,e.frame=null;return}e.frame=requestAnimationFrame(l)};e.frame=requestAnimationFrame(l)}function Wc(t){const e=Math.max(t*.5,1e-6),n=Math.max(1,t*8);return{minZoom:e,maxZoom:Math.max(e,n)}}function Yc(t,e,n){const r=Wc(t);let i=e??r.minZoom,o=n??r.maxZoom;return i=Math.max(1e-6,i),o=Math.max(1e-6,o),i>o&&(i=o),{minZoom:i,maxZoom:o}}function Xc(t,e,n,r,i){const o=t.getViewState(),s={zoom:typeof r.zoom=="number"&&Number.isFinite(r.zoom)?F(r.zoom,e,n):o.zoom,offsetX:typeof r.offsetX=="number"&&Number.isFinite(r.offsetX)?r.offsetX:o.offsetX,offsetY:typeof r.offsetY=="number"&&Number.isFinite(r.offsetY)?r.offsetY:o.offsetY,rotationDeg:typeof r.rotationDeg=="number"&&Number.isFinite(r.rotationDeg)?r.rotationDeg:o.rotationDeg};t.setViewState(s),i();const a=t.getViewState();return t.setViewState(o),a}function si(t,e,n,r,i,o=0){const s=Math.min(e/t.width,n/t.height),a=Number.isFinite(s)&&s>0?s:1,l=F(a,r,i),c=e/l,f=n/l;return{fitZoom:a,target:{zoom:l,offsetX:(t.width-c)*.5,offsetY:(t.height-f)*.5,rotationDeg:o}}}function Vc(t,e,n,r,i,o){const s=t.getViewState(),a=F(s.zoom*r,e,n);if(a===s.zoom)return null;const[l,c]=t.screenToWorld(i,o),f=t.getViewportSize(),u=i-f.width*.5,h=o-f.height*.5,d=on(s.rotationDeg),m=Math.cos(d),p=Math.sin(d),b=u/a*m-h/a*p,y=u/a*p+h/a*m,x=l-b,M=c-y;return{zoom:a,offsetX:x-f.width/(2*a),offsetY:M-f.height/(2*a)}}function Gc(t,e,n,r,i,o){const s=t.getViewState(),a=F(r,e,n);if(a===s.zoom)return null;const[l,c]=t.screenToWorld(i,o),f=t.getViewportSize(),u=i-f.width*.5,h=o-f.height*.5,d=on(s.rotationDeg),m=Math.cos(d),p=Math.sin(d),b=u/a*m-h/a*p,y=u/a*p+h/a*m,x=l-b,M=c-y;return{zoom:a,offsetX:x-f.width/(2*a),offsetY:M-f.height/(2*a)}}const Zc=250;function ai(t,e){if(!t||t.length===0)return[];if(!e||e<=0)return[];const n=10/e;return t.map(r=>r/n).filter(r=>Number.isFinite(r)&&r>0).sort((r,i)=>r-i)}function qc(t,e,n,r){if(t.length===0)return null;const i=Math.max(e*.005,1e-8);if(n==="in"){for(const o of t)if(o>e+i)return{type:"snap",zoom:o};return null}for(let o=t.length-1;o>=0;o--)if(t[o]<e-i)return{type:"snap",zoom:t[o]};return r&&e<=t[0]+i?{type:"fit"}:null}function Hc(t,e,n,r,i){const o=t.camera.getViewState(),[s,a]=t.camera.screenToWorld(n,r),l=t.camera.getViewportSize(),c=F(e,t.minZoom,t.maxZoom);if(c===o.zoom)return;const f=on(o.rotationDeg),u=Math.cos(f),h=Math.sin(f),d=n-l.width*.5,m=r-l.height*.5;t.cancelViewAnimation();const p=x=>{const M=d/x*u-m/x*h,S=d/x*h+m/x*u;return{offsetX:s-M-l.width/(2*x),offsetY:a-S-l.height/(2*x)}},b=p(c);t.viewAnimationState.animation={startMs:Ee(),durationMs:Math.max(0,i),from:o,to:{zoom:c,offsetX:b.offsetX,offsetY:b.offsetY,rotationDeg:o.rotationDeg},easing:Hn};const y=()=>{const x=t.viewAnimationState.animation;if(!x)return;const M=Math.max(0,Ee()-x.startMs),S=F(M/i,0,1),C=F(S*S*(3-2*S),0,1),A=o.zoom+(c-o.zoom)*C,{offsetX:B,offsetY:z}=p(A);t.camera.setViewState({zoom:A,offsetX:B,offsetY:z,rotationDeg:o.rotationDeg});const Y=S>=1;Y&&(t.clampViewState(),t.viewAnimationState.animation=null,t.viewAnimationState.frame=null),t.onViewStateChange(t.camera.getViewState()),t.requestRender(),Y||(t.viewAnimationState.frame=requestAnimationFrame(y))};t.viewAnimationState.frame=requestAnimationFrame(y)}const Fe="__default_point_layer__";class so{constructor(e,n,r={}){E(this,"canvas");E(this,"source");E(this,"gl");E(this,"camera",new ci);E(this,"onViewStateChange");E(this,"onStats");E(this,"onTileError");E(this,"onContextLost");E(this,"onContextRestored");E(this,"resizeObserver");E(this,"removeDprListener");E(this,"tileProgram");E(this,"tileScheduler");E(this,"authToken");E(this,"destroyed",!1);E(this,"contextLost",!1);E(this,"frame",null);E(this,"frameSerial",0);E(this,"interactionState",{dragging:!1,mode:"none",rotateLastAngleRad:null,pointerId:null,lastPointerX:0,lastPointerY:0});E(this,"interactionLocked",!1);E(this,"ctrlDragRotate",!0);E(this,"rotationDragSensitivityDegPerPixel",Fn);E(this,"maxCacheTiles");E(this,"fitZoom",1);E(this,"initialRotationDeg",0);E(this,"minZoom",1e-6);E(this,"maxZoom",1);E(this,"minZoomOverride",null);E(this,"maxZoomOverride",null);E(this,"viewTransitionDurationMs",0);E(this,"viewTransitionEasing",Hn);E(this,"viewAnimationState",{animation:null,frame:null});E(this,"pointLayers",new Map);E(this,"defaultPointSizeZoomStops",tn(Ln));E(this,"defaultPointSizeMagnificationStops",null);E(this,"defaultPointWeightMagnificationStops",null);E(this,"defaultPointOpacity",1);E(this,"defaultPointLineDash",[1,0]);E(this,"defaultPointStrokeScale",1);E(this,"defaultPointInnerFillOpacity",0);E(this,"defaultPointInnerFillColor",[...Ji]);E(this,"imageColorSettings",{brightness:0,contrast:0,saturation:0});E(this,"cache",new Map);E(this,"zoomSnaps",[]);E(this,"zoomSnapFitAsMin",!1);E(this,"zoomSnapState",{accumulatedDelta:0,lastSnapTimeMs:0,blockedDirection:null});E(this,"panExtentX",.2);E(this,"panExtentY",.2);E(this,"boundPointerDown");E(this,"boundPointerMove");E(this,"boundPointerUp");E(this,"boundWheel");E(this,"boundDoubleClick");E(this,"boundContextMenu");E(this,"boundContextLost");E(this,"boundContextRestored");this.canvas=e,this.source=n,this.onViewStateChange=r.onViewStateChange,this.onStats=r.onStats,this.onTileError=r.onTileError,this.onContextLost=r.onContextLost,this.onContextRestored=r.onContextRestored,this.authToken=r.authToken??"",this.maxCacheTiles=Math.max(32,Math.floor(r.maxCacheTiles??320)),this.initialRotationDeg=typeof r.initialRotationDeg=="number"&&Number.isFinite(r.initialRotationDeg)?r.initialRotationDeg:0,this.ctrlDragRotate=r.ctrlDragRotate??!0,this.rotationDragSensitivityDegPerPixel=typeof r.rotationDragSensitivityDegPerPixel=="number"&&Number.isFinite(r.rotationDragSensitivityDegPerPixel)?Math.max(0,r.rotationDragSensitivityDegPerPixel):Fn,this.defaultPointSizeZoomStops=$r(r.pointSizeByZoom),this.defaultPointSizeMagnificationStops=Kr(r.pointSizeByMagnification),this.defaultPointWeightMagnificationStops=jr(r.pointWeightByMagnification),this.defaultPointOpacity=Qr(r.pointOpacity),this.defaultPointStrokeScale=Gt(r.pointStrokeScale),this.defaultPointInnerFillOpacity=Jr(r.pointInnerFillOpacity),this.defaultPointInnerFillColor=ei(r.pointInnerFillColor),this.imageColorSettings=ti(r.imageColorSettings),this.minZoomOverride=Ot(r.minZoom),this.maxZoomOverride=Ot(r.maxZoom),this.viewTransitionDurationMs=mn(r.viewTransition?.duration),this.viewTransitionEasing=gn(r.viewTransition?.easing),this.zoomSnaps=ai(r.zoomSnaps,this.source.mpp),this.zoomSnapFitAsMin=!!r.zoomSnapFitAsMin,this.applyPanExtent(r.panExtent);const i=e.getContext("webgl2",{alpha:!1,antialias:!1,depth:!1,stencil:!1,powerPreference:"high-performance",preserveDrawingBuffer:r.preserveDrawingBuffer??!1});if(!i)throw new Error("WebGL2 not supported");this.gl=i,this.tileProgram=ii(this.gl),this.tileScheduler=new Qi({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)=>Lc({gl:this.gl,cache:this.cache,tile:s,bitmap:a,frameSerial:this.frameSerial,maxCacheTiles:this.maxCacheTiles,destroyed:this.destroyed,contextLost:this.contextLost,requestRender:()=>this.requestRender()}),onTileError:(s,a,l)=>{this.onTileError?.({tile:s,error:a,attemptCount:l}),console.warn("tile load failed",s.url,a)}}),this.resizeObserver=new ResizeObserver(()=>this.resize()),this.resizeObserver.observe(e),this.removeDprListener=rn(()=>this.resize());const o=Ic({canvas:this.canvas,state:this.interactionState,getInteractionLocked:()=>this.interactionLocked,getCtrlDragRotate:()=>this.ctrlDragRotate,getRotationDragSensitivityDegPerPixel:()=>this.rotationDragSensitivityDegPerPixel,cancelViewAnimation:()=>this.cancelViewAnimation(),camera:this.camera,source:this.source,emitViewState:()=>this.onViewStateChange?.(this.camera.getViewState()),requestRender:()=>this.requestRender(),getPanExtentX:()=>this.panExtentX,getPanExtentY:()=>this.panExtentY,zoomBy:(s,a,l)=>this.zoomBy(s,a,l),getUseZoomSnaps:()=>this.zoomSnaps.length>0,onSnapZoom:(s,a,l)=>this.handleSnapZoom(s,a,l),zoomSnapState:this.zoomSnapState});this.boundPointerDown=o.pointerDown,this.boundPointerMove=o.pointerMove,this.boundPointerUp=o.pointerUp,this.boundWheel=o.wheel,this.boundDoubleClick=o.doubleClick,this.boundContextMenu=o.contextMenu,this.boundContextLost=s=>this.onWebGlContextLost(s),this.boundContextRestored=s=>this.onWebGlContextRestored(s),Zl(e,this.getCanvasHandlers()),this.fitToImage({duration:0}),this.resize()}getCanvasHandlers(){return{pointerDown:this.boundPointerDown,pointerMove:this.boundPointerMove,pointerUp:this.boundPointerUp,wheel:this.boundWheel,doubleClick:this.boundDoubleClick,contextMenu:this.boundContextMenu,contextLost:this.boundContextLost,contextRestored:this.boundContextRestored}}applyZoomBounds(){const e=Yc(this.fitZoom,this.minZoomOverride,this.maxZoomOverride);this.minZoom=e.minZoom,this.maxZoom=e.maxZoom}resolveTargetViewState(e){return Xc(this.camera,this.minZoom,this.maxZoom,e,()=>Zt(this.camera,this.source,this.panExtentX,this.panExtentY))}cancelViewAnimation(){oo(this.viewAnimationState)}startViewAnimation(e,n,r){this.resetZoomSnapStateForZoomChange(this.camera.getViewState().zoom,e.zoom),Oc({state:this.viewAnimationState,camera:this.camera,target:e,durationMs:n,easing:r,onUpdate:()=>{Zt(this.camera,this.source,this.panExtentX,this.panExtentY),this.onViewStateChange?.(this.camera.getViewState()),this.requestRender()}})}createPointBufferRuntime(){return{pointCount:0,usePointIndices:!1,pointBuffersDirty:!0,lastPointData:null,zeroFillModes:new Uint8Array(0),lastPointPalette:null,pointPaletteSize:1}}createPointLayerState(e){return{id:e,program:oi(this.gl),runtime:this.createPointBufferRuntime(),pointSizeZoomStops:tn(this.defaultPointSizeZoomStops),pointSizeMagnificationStops:ic(this.defaultPointSizeMagnificationStops),pointWeightMagnificationStops:oc(this.defaultPointWeightMagnificationStops),pointOpacity:this.defaultPointOpacity,pointLineDash:[...this.defaultPointLineDash],pointStrokeScale:this.defaultPointStrokeScale,pointInnerFillOpacity:this.defaultPointInnerFillOpacity,pointInnerFillColor:[...this.defaultPointInnerFillColor]}}ensurePointLayer(e=Fe){const n=String(e||Fe),r=this.pointLayers.get(n);if(r)return r;const i=this.createPointLayerState(n);return this.pointLayers.set(n,i),i}deletePointProgram(e){this.contextLost||this.gl.isContextLost()||(this.gl.deleteBuffer(e.posBuffer),this.gl.deleteBuffer(e.classBuffer),this.gl.deleteBuffer(e.fillModeBuffer),this.gl.deleteBuffer(e.indexBuffer),this.gl.deleteTexture(e.paletteTexture),this.gl.deleteVertexArray(e.vao),this.gl.deleteProgram(e.program))}getPointRenderLayers(){const e=Math.max(1,window.devicePixelRatio||1),n=[];for(const r of this.pointLayers.values()){const i=this.getPointSize(r.id);n.push({pointProgram:r.program,pointCount:r.runtime.pointCount,usePointIndices:r.runtime.usePointIndices,pointPaletteSize:r.runtime.pointPaletteSize,pointLineDash:r.pointLineDash,pointOpacity:r.pointOpacity,pointStrokeScale:this.getPointStrokeScale(r.id),pointInnerFillOpacity:r.pointInnerFillOpacity,pointInnerFillColor:r.pointInnerFillColor,pointCssSizePx:i,pointSizePx:i*e})}return n}resetZoomSnapState(){this.zoomSnapState.accumulatedDelta=0,this.zoomSnapState.lastSnapTimeMs=0,this.zoomSnapState.blockedDirection=null}resetZoomSnapStateForZoomChange(e,n){Math.abs(e-n)<1e-6||this.resetZoomSnapState()}applyViewStateAndRender(e,n=!0){const r=this.camera.getViewState();n&&this.cancelViewAnimation(),this.resetZoomSnapStateForZoomChange(r.zoom,e.zoom),this.camera.setViewState(e),this.onViewStateChange?.(this.camera.getViewState()),this.requestRender()}setAuthToken(e){this.authToken=String(e??""),this.tileScheduler.setAuthToken(this.authToken)}setZoomRange(e,n){const r=Ot(e),i=Ot(n);if(this.minZoomOverride===r&&this.maxZoomOverride===i)return;this.minZoomOverride=r,this.maxZoomOverride=i,this.applyZoomBounds(),this.resetZoomSnapState();const o=this.resolveTargetViewState({}),s=this.camera.getViewState();Rn(s,o)||this.applyViewStateAndRender(o)}setViewTransition(e){this.viewTransitionDurationMs=mn(e?.duration),this.viewTransitionEasing=gn(e?.easing)}setViewState(e,n){const r=this.resolveTargetViewState(e),i=this.camera.getViewState();if(Rn(i,r))return;const o=mn(n?.duration??this.viewTransitionDurationMs),s=gn(n?.easing??this.viewTransitionEasing);if(o<=0){this.applyViewStateAndRender(r);return}this.startViewAnimation(r,o,s)}getViewState(){return this.camera.getViewState()}getZoomRange(){return{minZoom:this.minZoom,maxZoom:this.maxZoom}}getRegionLabelAutoLiftCapZoom(){const e=this.zoomSnaps.filter(n=>n>=this.minZoom&&n<=this.maxZoom);return e.length>0?e[e.length-1]:this.maxZoom}isViewAnimating(){return this.viewAnimationState.animation!==null}registerPointLayer(e){this.ensurePointLayer(e)}unregisterPointLayer(e){const n=String(e||Fe),r=this.pointLayers.get(n);r&&(this.pointLayers.delete(n),this.deletePointProgram(r.program),this.requestRender())}setPointPalette(e,n=Fe){const r=this.ensurePointLayer(n);r.runtime=ni(r.runtime,this.gl,r.program,this.contextLost,e),!(!e||e.length===0)&&this.requestRender()}setPointLineDash(e,n=Fe){const r=this.ensurePointLayer(n),i=hc(e);r.pointLineDash[0]===i[0]&&r.pointLineDash[1]===i[1]||(r.pointLineDash=i,this.requestRender())}setPointData(e,n=Fe){const r=this.ensurePointLayer(n);r.runtime=ri(r.runtime,this.gl,r.program,this.contextLost,e),this.requestRender()}setInteractionLock(e){const n=!!e;this.interactionLocked!==n&&(this.interactionLocked=n,n&&this.cancelDrag())}setPointSizeByZoom(e,n=Fe){const r=this.ensurePointLayer(n),i=$r(e);sc(r.pointSizeZoomStops,i)||(r.pointSizeZoomStops=i,this.requestRender())}setPointSizeByMagnification(e,n=Fe){const r=this.ensurePointLayer(n),i=Kr(e);ac(r.pointSizeMagnificationStops,i)||(r.pointSizeMagnificationStops=i,this.requestRender())}setPointWeightByMagnification(e,n=Fe){const r=this.ensurePointLayer(n),i=jr(e);lc(r.pointWeightMagnificationStops,i)||(r.pointWeightMagnificationStops=i,this.requestRender())}setPointOpacity(e,n=Fe){const r=this.ensurePointLayer(n),i=Qr(e);r.pointOpacity!==i&&(r.pointOpacity=i,this.requestRender())}setPointStrokeScale(e,n=Fe){const r=this.ensurePointLayer(n),i=Gt(e);r.pointStrokeScale!==i&&(r.pointStrokeScale=i,this.requestRender())}setPointInnerFillOpacity(e,n=Fe){const r=this.ensurePointLayer(n),i=Jr(e);r.pointInnerFillOpacity!==i&&(r.pointInnerFillOpacity=i,this.requestRender())}setPointInnerFillColor(e,n=Fe){const r=this.ensurePointLayer(n),i=ei(e);r.pointInnerFillColor[0]===i[0]&&r.pointInnerFillColor[1]===i[1]&&r.pointInnerFillColor[2]===i[2]||(r.pointInnerFillColor=i,this.requestRender())}setImageColorSettings(e){const n=ti(e),r=this.imageColorSettings;r.brightness===n.brightness&&r.contrast===n.contrast&&r.saturation===n.saturation||(this.imageColorSettings=n,this.requestRender())}cancelDrag(){Tc(this.canvas,this.interactionState)}screenToWorld(e,n){const r=this.canvas.getBoundingClientRect(),i=e-r.left,o=n-r.top;return this.camera.screenToWorld(i,o)}worldToScreen(e,n){return this.camera.worldToScreen(e,n)}setViewCenter(e,n,r){if(!Number.isFinite(e)||!Number.isFinite(n))return;const i=this.camera.getViewState(),o=Math.max(1e-6,i.zoom),s=this.camera.getViewportSize();this.setViewState({offsetX:e-s.width/(2*o),offsetY:n-s.height/(2*o)},r)}getViewCorners(){return this.camera.getViewCorners()}getInitialRotationDeg(){return this.initialRotationDeg}getViewBounds(){return nn(this.camera)}resetRotation(e){const n=this.camera.getViewState();Math.abs(n.rotationDeg-this.initialRotationDeg)<1e-6||this.setViewState({rotationDeg:this.initialRotationDeg},e)}getPointSize(e=Fe){const n=this.pointLayers.get(String(e||Fe)),r=n?.pointSizeMagnificationStops??this.defaultPointSizeMagnificationStops;if(r&&r.length>0){const l=Math.max(1e-6,this.camera.getViewState().zoom),c=En(this.source.mpp??0,l);if(c>0){const f=uc(c,r);return F(f,ht,Hr)}}const i=Math.max(1e-6,this.camera.getViewState().zoom),o=this.source.maxTierZoom+Math.log2(i),s=n?.pointSizeZoomStops??this.defaultPointSizeZoomStops,a=cc(o,s);return F(a,ht,Hr)}getPointSizeByZoom(e=Fe){return this.getPointSize(e)}getPointStrokeScale(e=Fe){const n=this.pointLayers.get(String(e||Fe)),r=n?.pointWeightMagnificationStops??this.defaultPointWeightMagnificationStops;if(r&&r.length>0){const i=Math.max(1e-6,this.camera.getViewState().zoom),o=En(this.source.mpp??0,i);if(o>0)return Gt(fc(o,r))}return n?.pointStrokeScale??this.defaultPointStrokeScale}fitToImage(e){const n=this.canvas.getBoundingClientRect(),r=Math.max(1,n.width||1),i=Math.max(1,n.height||1),o=si(this.source,r,i,this.minZoom,this.maxZoom,this.initialRotationDeg);this.fitZoom=o.fitZoom,this.applyZoomBounds(),this.setViewState(o.target,e)}zoomBy(e,n,r,i){const o=Vc(this.camera,this.minZoom,this.maxZoom,e,n,r);o&&this.setViewState(o,i)}handleWheelZoom(e,n,r){if(this.zoomSnaps.length>0){ro(e,n,r,this.zoomSnapState,(i,o,s)=>this.handleSnapZoom(i,o,s));return}no(e,n,r,(i,o,s)=>this.zoomBy(i,o,s))}zoomTo(e,n,r,i){const o=Gc(this.camera,this.minZoom,this.maxZoom,e,n,r);o&&this.setViewState(o,i)}setZoomSnaps(e,n){this.zoomSnaps=ai(e,this.source.mpp),this.zoomSnapFitAsMin=!!n,this.resetZoomSnapState()}setPanExtent(e){this.applyPanExtent(e)}applyPanExtent(e){typeof e=="number"&&Number.isFinite(e)?(this.panExtentX=Math.max(0,e),this.panExtentY=Math.max(0,e)):e!=null&&typeof e=="object"?(this.panExtentX=typeof e.x=="number"&&Number.isFinite(e.x)?Math.max(0,e.x):.2,this.panExtentY=typeof e.y=="number"&&Number.isFinite(e.y)?Math.max(0,e.y):.2):(this.panExtentX=.2,this.panExtentY=.2)}getZoomPivotAnimationContext(){return{camera:this.camera,viewAnimationState:this.viewAnimationState,minZoom:this.minZoom,maxZoom:this.maxZoom,cancelViewAnimation:()=>this.cancelViewAnimation(),clampViewState:()=>Zt(this.camera,this.source,this.panExtentX,this.panExtentY),onViewStateChange:e=>this.onViewStateChange?.(e),requestRender:()=>this.requestRender()}}handleSnapZoom(e,n,r){const i=this.viewAnimationState.animation,o=i?i.to.zoom:this.camera.getViewState().zoom,s=this.zoomSnaps.filter(f=>f>=this.minZoom&&f<=this.maxZoom),a=qc(s,o,e,this.zoomSnapFitAsMin);if(!a)return!1;let l;if(a.type==="fit"){const f=this.canvas.getBoundingClientRect(),u=Math.max(1,f.width||1),h=Math.max(1,f.height||1),d=si(this.source,u,h,this.minZoom,this.maxZoom,this.initialRotationDeg);this.fitZoom=d.fitZoom,this.applyZoomBounds(),l=d.target.zoom}else l=a.zoom;const c=Math.max(Math.abs(l)*.005,1e-8);if(i){if((i.to.zoom>i.from.zoom+c?"in":i.to.zoom<i.from.zoom-c?"out":null)===e&&Math.abs(i.to.zoom-l)<=c)return!1}else if(Math.abs(o-l)<=c)return!1;return Hc(this.getZoomPivotAnimationContext(),l,n,r,Zc),!0}render(){if(this.destroyed||this.contextLost||this.gl.isContextLost())return;const e=this.onStats?Ee():0;this.frameSerial+=1;const n=Uc({gl:this.gl,camera:this.camera,source:this.source,cache:this.cache,frameSerial:this.frameSerial,tileProgram:this.tileProgram,imageColorSettings:this.imageColorSettings,pointLayers:this.getPointRenderLayers(),tileScheduler:this.tileScheduler,getVisibleTiles:()=>Rc(this.camera,this.source),getVisibleTilesForTier:r=>io(this.camera,this.source,r),getViewBounds:()=>nn(this.camera),intersectsBounds:Ec});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:Ee()-e})}}requestRender(){this.frame!==null||this.destroyed||this.contextLost||this.gl.isContextLost()||(this.frame=requestAnimationFrame(()=>{this.frame=null,this.render()}))}resize(){Hl(this.canvas,this.gl,this.camera),this.requestRender()}onWebGlContextLost(e){const n=Nc({event:e,destroyed:this.destroyed,contextLost:this.contextLost,frame:this.frame,cancelViewAnimation:()=>this.cancelViewAnimation(),cancelDrag:()=>this.cancelDrag(),tileScheduler:this.tileScheduler,cache:this.cache,onContextLost:this.onContextLost});if(n.handled){this.frame=n.frame,this.contextLost=!0;for(const r of this.pointLayers.values())r.runtime={...r.runtime,pointBuffersDirty:!0}}}onWebGlContextRestored(e){if(!this.destroyed){this.contextLost=!1,this.cache.clear(),this.tileProgram=ii(this.gl);for(const n of this.pointLayers.values())n.program=oi(this.gl),n.runtime={...n.runtime,pointBuffersDirty:!0},n.runtime.lastPointPalette&&n.runtime.lastPointPalette.length>0&&(n.runtime=ni(n.runtime,this.gl,n.program,this.contextLost,n.runtime.lastPointPalette)),n.runtime.lastPointData&&(n.runtime=ri(n.runtime,this.gl,n.program,this.contextLost,n.runtime.lastPointData));this.resize(),this.onContextRestored?.()}}destroy(){const e=zc({destroyed:this.destroyed,frame:this.frame,cancelViewAnimation:()=>this.cancelViewAnimation(),resizeObserver:this.resizeObserver,removeDprListener:this.removeDprListener,removeCanvasEventListeners:()=>ql(this.canvas,this.getCanvasHandlers()),cancelDrag:()=>this.cancelDrag(),tileScheduler:this.tileScheduler,contextLost:this.contextLost,gl:this.gl,cache:this.cache,tileProgram:this.tileProgram,pointPrograms:Array.from(this.pointLayers.values(),n=>n.program)});e.didDestroy&&(this.destroyed=!0,this.frame=e.frame)}}const $c=[];function Kc(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function jc({source:t,viewState:e,onViewStateChange:n,onStats:r,onTileError:i,onContextLost:o,onContextRestored:s,imageColorSettings:a=null,initialRotate:l=0,fitNonce:c=0,rotationResetNonce:f=0,authToken:u="",ctrlDragRotate:h=!0,minZoom:d,maxZoom:m,viewTransition:p,zoomSnaps:b,zoomSnapFitAsMin:y,panExtent:x,preserveDrawingBuffer:M,onPointerWorldMove:S,debugOverlay:C=!1,debugOverlayStyle:A,className:B,style:z,children:Y}){const P=g.useRef(null),I=g.useRef(null),O=g.useRef(null),v=g.useRef(null),W=g.useRef(null),j=g.useRef(null),L=g.useRef($c),ge=g.useRef(!1),le=g.useRef(new Set),Q=g.useRef(new Set),ve=g.useRef(n),Ae=g.useRef(r),D=g.useRef(i),T=g.useRef(o),k=g.useRef(s),[oe,ue]=g.useState(0),[$,ce]=g.useState(null),te=g.useRef(C);g.useEffect(()=>{ve.current=n},[n]),g.useEffect(()=>{Ae.current=r},[r]),g.useEffect(()=>{D.current=i},[i]),g.useEffect(()=>{T.current=o},[o]),g.useEffect(()=>{k.current=s},[s]),g.useEffect(()=>{te.current=C,C||ce(null)},[C]);const _e=g.useMemo(()=>({position:"relative",width:"100%",height:"100%",...z}),[z]),Se=g.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)",...A}),[A]),fe=Kc(l),xe=g.useCallback(U=>({...U,rotationDeg:U.rotationDeg-fe}),[fe]),ee=g.useCallback(U=>typeof U.rotationDeg!="number"||!Number.isFinite(U.rotationDeg)?U:{...U,rotationDeg:U.rotationDeg+fe},[fe]),se=g.useCallback(U=>{Ae.current?.(U),te.current&&ce(U)},[]),he=g.useMemo(()=>$?[`tier ${$.tier} | frame ${$.frameMs?.toFixed(2)??"-"} ms | drawCalls ${$.drawCalls??"-"}`,`tiles visible ${$.visible} | rendered ${$.rendered} | fallback ${$.fallback}`,`cache size ${$.cache} | hit ${$.cacheHits??"-"} | miss ${$.cacheMisses??"-"}`,`queue inflight ${$.inflight} | queued ${$.queued??"-"} | retries ${$.retries??"-"} | failed ${$.failed??"-"} | aborted ${$.aborted??"-"}`,`points ${$.points}`].join(`
|
|
247
|
+
`):"stats: waiting for first frame...",[$]),ae=g.useCallback(()=>{const U=O.current;if(!U)return;const Z=U.getContext("2d");if(!Z)return;const q=Math.max(1,window.devicePixelRatio||1),re=U.getBoundingClientRect(),pe=Math.max(1,Math.round(re.width*q)),de=Math.max(1,Math.round(re.height*q));(U.width!==pe||U.height!==de)&&(U.width=pe,U.height=de);const Ne=re.width,w=re.height;Z.setTransform(1,0,0,1,0,0),Z.clearRect(0,0,U.width,U.height),Z.setTransform(q,0,0,q,0,0);const R=L.current;for(let _=0;_<R.length;_+=1)Z.save(),R[_].draw(Z,Ne,w),Z.restore()},[]),ne=g.useCallback(()=>{ge.current||(ge.current=!0,requestAnimationFrame(()=>{ge.current=!1,ae()}))},[ae]),Me=g.useCallback((U,Z,q)=>{const re=L.current.filter(pe=>pe.id!==U);re.push({id:U,priority:Z,draw:q}),re.sort((pe,de)=>pe.priority-de.priority),L.current=re,ne()},[ne]),we=g.useCallback(U=>{L.current=L.current.filter(Z=>Z.id!==U),ne()},[ne]),V=g.useCallback((U,Z)=>{Z?le.current.add(U):le.current.delete(U),v.current?.setInteractionLock(le.current.size>0)},[]),H=g.useCallback(()=>le.current.size>0,[]),be=g.useCallback((U,Z)=>{const q=v.current;return q?Bn(q.worldToScreen(U,Z)):null},[]),J=g.useCallback((U,Z)=>{const q=v.current;if(!q)return null;const re=q.screenToWorld(U,Z);if(!Array.isArray(re)||re.length<2)return null;const pe=Number(re[0]),de=Number(re[1]);return!Number.isFinite(pe)||!Number.isFinite(de)?null:[pe,de]},[]),K=g.useCallback(U=>(Q.current.add(U),()=>{Q.current.delete(U)}),[]),Re=g.useCallback(U=>{ve.current?.(xe(U));const Z=Q.current;if(Z.size>0){const q=Array.from(Z);for(let re=0;re<q.length;re+=1)q[re](U)}W.current?.(),j.current?.(),ne()},[ne,xe]);g.useEffect(()=>{const U=I.current;if(!U||!t)return;const Z=new so(U,t,{onViewStateChange:Re,onStats:se,onTileError:q=>{D.current?.(q)},onContextLost:()=>{T.current?.()},onContextRestored:()=>{k.current?.()},authToken:u,imageColorSettings:a,initialRotationDeg:l,ctrlDragRotate:h,minZoom:d,maxZoom:m,viewTransition:p,zoomSnaps:b,zoomSnapFitAsMin:y,panExtent:x,preserveDrawingBuffer:M});return v.current=Z,ue(q=>q+1),e&&Z.setViewState(ee(e)),Z.setInteractionLock(le.current.size>0),()=>{Z.destroy(),v.current=null}},[t,se,h,Re,fe,ee]),g.useEffect(()=>{v.current?.setAuthToken(u)},[u]),g.useEffect(()=>{const U=v.current;!U||!e||U.isViewAnimating()||U.setViewState(ee(e))},[e,ee]),g.useEffect(()=>{v.current?.fitToImage()},[c]),g.useEffect(()=>{v.current?.resetRotation()},[f]),g.useEffect(()=>{v.current?.setZoomRange(d,m)},[d,m]),g.useEffect(()=>{v.current?.setViewTransition(p)},[p]),g.useEffect(()=>{v.current?.setZoomSnaps(b,y)},[b,y]),g.useEffect(()=>{v.current?.setPanExtent(x)},[x]),g.useEffect(()=>{v.current?.setImageColorSettings(a)},[a]),g.useEffect(()=>{const U=O.current;if(!U)return;W.current=ne,ne();const Z=new ResizeObserver(()=>ne());return Z.observe(U),()=>{Z.disconnect(),W.current===ne&&(W.current=null)}},[ne]),g.useEffect(()=>rn(()=>ne()),[ne]);const X=g.useMemo(()=>({source:t,rendererRef:v,rendererSerial:oe,canvasRef:I,containerRef:P,drawInvalidateRef:W,overviewInvalidateRef:j,worldToScreen:be,screenToWorld:J,registerDrawCallback:Me,unregisterDrawCallback:we,requestOverlayRedraw:ne,registerViewStateListener:K,setInteractionLock:V,isInteractionLocked:H}),[t,oe,be,J,Me,we,ne,K,V,H]),Ce=g.useRef(S);g.useEffect(()=>{Ce.current=S},[S]);const De=g.useCallback(U=>{const Z=Ce.current;if(!Z)return;const q=J(U.clientX,U.clientY),re=!!q&&q[0]>=0&&q[1]>=0&&!!t&&q[0]<=t.width&&q[1]<=t.height;Z({coordinate:q,clientX:U.clientX,clientY:U.clientY,insideImage:re})},[J,t]),Le=g.useCallback(()=>{Ce.current?.({coordinate:null,clientX:-1,clientY:-1,insideImage:!1})},[]);return Ge.jsx(ca,{value:X,children:Ge.jsxs("div",{ref:P,className:B,style:_e,onPointerMove:S?De:void 0,onPointerLeave:S?Le:void 0,children:[Ge.jsx("canvas",{ref:I,className:"wsi-render-canvas",style:{position:"absolute",inset:0,zIndex:1,width:"100%",height:"100%",display:"block",touchAction:"none"}}),Ge.jsx("canvas",{ref:O,className:"wsi-overlay-canvas",style:{position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",pointerEvents:"none",touchAction:"none"}}),Y,C&&Ge.jsx("pre",{"data-open-plant-debug-overlay":!0,style:Se,children:he})]})})}function Qc(t){const e=[];for(let n=0;n<t.length;n+=1){const r=t[n],i=mt([dt(r?.coordinates)]);if(i.length===0)continue;let o=0,s=1/0,a=1/0,l=-1/0,c=-1/0;for(const f of i)o+=f.area,f.minX<s&&(s=f.minX),f.minY<a&&(a=f.minY),f.maxX>l&&(l=f.maxX),f.maxY>c&&(c=f.maxY);!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(l)||!Number.isFinite(c)||e.push({regionId:r.id??n,regionIndex:n,polygons:i,area:Math.max(1e-6,o),minX:s,minY:a,maxX:l,maxY:c})}return e}const Jc=128,pn=[];function ut(t,e,n,r,i){if(i<=1||n<=e)return 0;const o=(t-e)/r;return!Number.isFinite(o)||o<=0?0:o>=i-1?i-1:Math.floor(o)}function eu(t){if(t.length===0)return null;let e=1/0,n=1/0,r=-1/0,i=-1/0;for(const f of t)f.minX<e&&(e=f.minX),f.minY<n&&(n=f.minY),f.maxX>r&&(r=f.maxX),f.maxY>i&&(i=f.maxY);if(!Number.isFinite(e)||!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(i))return null;const o=Math.ceil(Math.sqrt(t.length*2)),s=Math.max(1,Math.min(Jc,o)),a=r>e?(r-e)/s:1,l=i>n?(i-n)/s:1,c=Array.from({length:s*s},()=>[]);for(let f=0;f<t.length;f+=1){const u=t[f],h=ut(u.minX,e,r,a,s),d=ut(u.maxX,e,r,a,s),m=ut(u.minY,n,i,l,s),p=ut(u.maxY,n,i,l,s);for(let b=m;b<=p;b+=1)for(let y=h;y<=d;y+=1)c[b*s+y].push(f)}return{minX:e,minY:n,maxX:r,maxY:i,gridSize:s,cellWidth:a,cellHeight:l,buckets:c}}function tu(t,e,n){if(!t||e<t.minX||e>t.maxX||n<t.minY||n>t.maxY)return pn;const r=ut(e,t.minX,t.maxX,t.cellWidth,t.gridSize),i=ut(n,t.minY,t.maxY,t.cellHeight,t.gridSize);return t.buckets[i*t.gridSize+r]??pn}function nu(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 ru(t,e,n={}){const r=Math.max(0,Math.min(Math.floor(t?.count??0),Math.floor((t?.positions?.length??0)/2),t?.paletteIndices?.length??0,t?.fillModes instanceof Uint8Array?t.fillModes.length:Number.MAX_SAFE_INTEGER));let i=null;if(t?.drawIndices instanceof Uint32Array){const d=t.drawIndices;let m=d.length;for(let p=0;p<d.length;p+=1)d[p]<r||(m-=1);if(m===d.length)i=d;else if(m>0){const p=new Uint32Array(m);let b=0;for(let y=0;y<d.length;y+=1){const x=d[y];x>=r||(p[b]=x,b+=1)}i=p}else i=new Uint32Array(0)}const o=i?i.length:r,s=Qc(e??[]);if(!t||o===0||s.length===0)return{groups:[],inputPointCount:o,pointsInsideAnyRegion:0,unmatchedPointCount:o};const a=new Map,l=new Map,c=eu(s);let f=0;for(let d=0;d<o;d+=1){const m=i?i[d]:d,p=t.positions[m*2],b=t.positions[m*2+1];if(!Number.isFinite(p)||!Number.isFinite(b))continue;let y=null;const x=tu(c,p,b);if(x.length===0)continue;for(const C of x){const A=s[C];let B=!1;for(const z of A.polygons)if(gi(p,b,z)){B=!0;break}B&&(!y||A.area<y.area)&&(y=A)}if(!y)continue;f+=1;const M=t.paletteIndices[m]??0,S=a.get(y.regionIndex)??new Map;S.set(M,(S.get(M)??0)+1),a.set(y.regionIndex,S),l.set(y.regionIndex,(l.get(y.regionIndex)??0)+1)}const u=n.includeEmptyRegions??!1,h=[];for(const d of s){const m=l.get(d.regionIndex)??0;if(!u&&m<=0)continue;const p=a.get(d.regionIndex)??new Map,b=Array.from(p.entries()).map(([y,x])=>({classId:nu(y,n.paletteIndexToClassId),paletteIndex:y,count:x})).sort((y,x)=>x.count-y.count||y.paletteIndex-x.paletteIndex);h.push({regionId:d.regionId,regionIndex:d.regionIndex,totalCount:m,classCounts:b})}return{groups:h,inputPointCount:o,pointsInsideAnyRegion:f,unmatchedPointCount:Math.max(0,o-f)}}function iu(t){return t.replace(/^\s*SRID\s*=\s*\d+\s*;\s*/i,"")}function ou(t){return t>="A"&&t<="Z"||t>="a"&&t<="z"}function su(t){return t>="0"&&t<="9"}function li(t){return t==="+"||t==="-"||t==="."||su(t)}class au{constructor(e){E(this,"text");E(this,"index",0);this.text=iu(e.trim())}parse(){if(!this.text)return null;const e=this.readWord();if(!e)return null;const n=e.toUpperCase();if(n!=="POLYGON"&&n!=="MULTIPOLYGON")return null;this.skipWhitespace();const r=this.peekWord();if(r){const s=r.toUpperCase();(s==="Z"||s==="M"||s==="ZM")&&(this.readWord(),this.skipWhitespace())}if(this.consumeWordIf("EMPTY"))return this.skipWhitespace(),this.isEof()?n==="POLYGON"?{type:"Polygon",coordinates:[]}:{type:"MultiPolygon",coordinates:[]}:null;let i;try{i=this.parseNestedList()}catch{return null}if(this.skipWhitespace(),!this.isEof())return null;if(n==="POLYGON"){const s=ao(i);return s?{type:"Polygon",coordinates:s}:null}const o=cu(i);return o?{type:"MultiPolygon",coordinates:o}:null}isEof(){return this.index>=this.text.length}currentChar(){return this.text[this.index]??""}skipWhitespace(){for(;!this.isEof()&&/\s/.test(this.currentChar());)this.index+=1}readWord(){if(this.skipWhitespace(),this.isEof())return null;const e=this.index;for(;!this.isEof()&&ou(this.currentChar());)this.index+=1;return this.index===e?null:this.text.slice(e,this.index)}peekWord(){const e=this.index,n=this.readWord();return this.index=e,n}consumeWordIf(e){const n=this.index,r=this.readWord();return!r||r.toUpperCase()!==e.toUpperCase()?(this.index=n,!1):!0}parseNestedList(){if(this.skipWhitespace(),this.currentChar()!=="(")throw new Error("Expected '('");this.index+=1;const e=[];for(;;){this.skipWhitespace(),this.currentChar()==="("?e.push(this.parseNestedList()):e.push(this.parseCoordinateTuple()),this.skipWhitespace();const n=this.currentChar();if(n===","){this.index+=1;continue}if(n===")"){this.index+=1;break}throw new Error("Expected ',' or ')'")}return e}parseCoordinateTuple(){this.skipWhitespace();const e=[];for(;;){this.skipWhitespace();const n=this.currentChar();if(!n||!li(n))break;const r=this.readNumber();if(r===null)break;e.push(r),this.skipWhitespace();const i=this.currentChar();if(!i||i===","||i===")")break;if(!li(i))throw new Error("Invalid coordinate")}if(e.length<2)throw new Error("Coordinate requires at least x y");return[e[0],e[1]]}readNumber(){if(this.skipWhitespace(),this.isEof())return null;const n=this.text.slice(this.index).match(/^[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?/);if(!n)return null;const r=Number(n[0]);return Number.isFinite(r)?(this.index+=n[0].length,r):null}}function lu(t){return Array.isArray(t)&&t.length>=2&&typeof t[0]=="number"&&Number.isFinite(t[0])&&typeof t[1]=="number"&&Number.isFinite(t[1])}function ao(t){if(!Array.isArray(t))return null;const e=[];for(const n of t){if(!Array.isArray(n))return null;const r=[];for(const i of n){if(!lu(i))return null;r.push([i[0],i[1]])}e.push(r)}return e}function cu(t){if(!Array.isArray(t))return null;const e=[];for(const n of t){const r=ao(n);if(!r)return null;e.push(r)}return e}function uu(t){return typeof t!="string"?null:new au(t).parse()}exports.DEFAULT_POINT_COLOR=Nn;exports.DrawLayer=Pi;exports.DrawingLayer=ua;exports.HeatmapLayer=Va;exports.M1TileRenderer=ui;exports.OverlayLayer=Za;exports.OverviewMap=nl;exports.PatchLayer=il;exports.PointLayer=Il;exports.RegionLayer=Xl;exports.TileScheduler=Qi;exports.TileViewerCanvas=Vl;exports.WsiTileRenderer=so;exports.WsiViewer=jc;exports.__heatmapLayerInternals=Ga;exports.buildClassPalette=Ho;exports.buildPointSpatialIndexAsync=ji;exports.calcScaleLength=Vo;exports.calcScaleResolution=zn;exports.calcViewingMagnification=En;exports.clamp=F;exports.closeRing=Oe;exports.computeRoiPointGroups=ru;exports.createCircle=Mn;exports.createRectangle=Qt;exports.createSpatialIndex=Ti;exports.filterPointDataByPolygons=Mt;exports.filterPointDataByPolygonsHybrid=qi;exports.filterPointDataByPolygonsInWorker=$i;exports.filterPointIndicesByPolygons=Vi;exports.filterPointIndicesByPolygonsInWorker=ml;exports.getWebGpuCapabilities=fl;exports.hexToRgba=pi;exports.isSameViewState=Rn;exports.lookupCellIndex=Ki;exports.normalizeImageClasses=qa;exports.normalizeImageInfo=$a;exports.parseWkt=uu;exports.prefilterPointsByBoundsWebGpu=Zi;exports.terminatePointHitIndexWorker=Ml;exports.terminateRoiClipWorker=dl;exports.toBearerToken=Go;exports.toRoiGeometry=dt;exports.toTileUrl=qn;exports.useViewerContext=st;
|
|
248
248
|
//# sourceMappingURL=index.cjs.map
|