open-plant 1.4.21 → 1.4.22
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/README.md +3 -3
- package/dist/index.cjs +8 -8
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +2712 -2749
- package/dist/index.js.map +1 -1
- package/dist/types/index.d.ts +1 -1
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/react/heatmap-layer.d.ts +41 -49
- package/dist/types/react/heatmap-layer.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
|
|
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 S=(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 ht=typeof document<"u"?document.currentScript:null;function Jn(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 St(t,e,n){const r=Jn(t,t.VERTEX_SHADER,e),i=Jn(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 un(t){return t*Math.PI/180}class di{constructor(){S(this,"viewportWidth",1);S(this,"viewportHeight",1);S(this,"viewState",{offsetX:0,offsetY:0,zoom:1,rotationDeg:0})}setViewport(e,n){this.viewportWidth=Math.max(1,e),this.viewportHeight=Math.max(1,n)}getViewportSize(){return{width:this.viewportWidth,height:this.viewportHeight}}setViewState(e){e.offsetX!==void 0&&(this.viewState.offsetX=e.offsetX),e.offsetY!==void 0&&(this.viewState.offsetY=e.offsetY),e.zoom!==void 0&&(this.viewState.zoom=Math.max(1e-4,e.zoom)),typeof e.rotationDeg=="number"&&Number.isFinite(e.rotationDeg)&&(this.viewState.rotationDeg=e.rotationDeg)}getViewState(){return{...this.viewState}}getCenter(){const e=Math.max(1e-6,this.viewState.zoom);return[this.viewState.offsetX+this.viewportWidth/(2*e),this.viewState.offsetY+this.viewportHeight/(2*e)]}setCenter(e,n){const r=Math.max(1e-6,this.viewState.zoom);this.viewState.offsetX=e-this.viewportWidth/(2*r),this.viewState.offsetY=n-this.viewportHeight/(2*r)}screenToWorld(e,n){const r=Math.max(1e-6,this.viewState.zoom),[i,o]=this.getCenter(),s=this.viewState.rotationDeg??0,a=(e-this.viewportWidth*.5)/r,l=(n-this.viewportHeight*.5)/r,u=un(s),f=Math.cos(u),c=Math.sin(u);return[i+a*f-l*c,o+a*c+l*f]}worldToScreen(e,n){const r=Math.max(1e-6,this.viewState.zoom),[i,o]=this.getCenter(),s=this.viewState.rotationDeg??0,a=e-i,l=n-o,u=un(s),f=Math.cos(u),c=Math.sin(u),h=a*f+l*c,d=-a*c+l*f;return[this.viewportWidth*.5+h*r,this.viewportHeight*.5+d*r]}getViewCorners(){const e=this.viewportWidth,n=this.viewportHeight;return[this.screenToWorld(0,0),this.screenToWorld(e,0),this.screenToWorld(e,n),this.screenToWorld(0,n)]}getMatrix(){const e=Math.max(1e-6,this.viewState.zoom),n=this.viewState.rotationDeg??0;if(n===0){const m=this.viewportWidth/e,p=this.viewportHeight/e,x=2/m,y=-2/p,b=-1-this.viewState.offsetX*x,M=1-this.viewState.offsetY*y;return new Float32Array([x,0,0,0,y,0,b,M,1])}const[r,i]=this.getCenter(),o=un(n),s=Math.cos(o),a=Math.sin(o),l=2*e*s/this.viewportWidth,u=2*e*a/this.viewportWidth,f=2*e*a/this.viewportHeight,c=-2*e*s/this.viewportHeight,h=-(l*r+u*i),d=-(f*r+c*i);return new Float32Array([l,f,0,u,c,0,h,d,1])}}const 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
|
|
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
|
|
32
|
+
`;class mi{constructor(e){S(this,"canvas");S(this,"gl");S(this,"camera",new di);S(this,"imageWidth");S(this,"imageHeight");S(this,"clearColor");S(this,"program");S(this,"vao");S(this,"quadBuffer");S(this,"uCameraLocation");S(this,"uBoundsLocation");S(this,"uTextureLocation");S(this,"resizeObserver");S(this,"tiles",[]);S(this,"frameId",null);S(this,"loadVersion",0);S(this,"destroyed",!1);S(this,"fitted",!1);S(this,"controlledViewState",!1);this.canvas=e.canvas,this.imageWidth=Math.max(1,e.imageWidth),this.imageHeight=Math.max(1,e.imageHeight),this.clearColor=e.clearColor??[.03,.05,.08,1],this.gl=fo(this.canvas,{preserveDrawingBuffer:e.preserveDrawingBuffer}),this.program=St(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 nt{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 Je(t,e,n){const r=new nt(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 fn(t,e,n,r){const i=new nt(t,e);if(n===null)return i.left=i.right=null,i;n=Je(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 er(t,e,n){let r=null,i=null;if(e){e=Je(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=Je(t.key,e,n),e.left=t),e)}function xn(t,e,n,r,i){if(t){r(`${e}${n?"└── ":"├── "}${i(t)}
|
|
33
|
+
`);const o=e+(n?" ":"│ ");t.left&&xn(t.left,o,!1,r,i),t.right&&xn(t.right,o,!0,r,i)}}class kn{constructor(e=go){this._root=null,this._size=0,this._comparator=e}insert(e,n){return this._size++,this._root=fn(e,n,this._root,this._comparator)}add(e,n){const r=new nt(e,n);this._root===null&&(r.left=r.right=null,this._size++,this._root=r);const i=this._comparator,o=Je(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=Je(e,n,r),r(e,n.key)===0?(n.left===null?i=n.right:(i=Je(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=Je(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=Je(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&&Rn(e,n,0,i-1,o),this._root===null)this._root=wn(e,n,0,i),this._size=i;else{const s=xo(this.toList(),yo(e,n),o);i=this._size+i,this._root=Sn({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 xn(this._root,"",!0,r=>n.push(r),e),n.join("")}update(e,n,r){const i=this._comparator;let{left:o,right:s}=er(e,this._root,i);i(e,n)<0?s=fn(n,r,s,i):o=fn(n,r,o,i),this._root=po(o,s,i)}split(e){return er(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 wn(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 nt(s,a);return l.left=wn(t,e,n,o),l.right=wn(t,e,o+1,r),l}return null}function yo(t,e){const n=new nt(null,null);let r=n;for(let i=0;i<t.length;i++)r=r.next=new nt(t[i],e[i]);return r.next=null,n.next}function bo(t){let e=t;const n=[];let r=!1;const i=new nt(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 Sn(t,e,n){const r=n-e;if(r>0){const i=e+Math.floor(r/2),o=Sn(t,e,i),s=t.head;return s.left=o,t.head=t.head.next,s.right=Sn(t,i+1,n),s}return null}function xo(t,e,n){const r=new nt(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 Rn(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}Rn(t,e,n,a,i),Rn(t,e,a+1,r,i)}const Ke=11102230246251565e-32,ze=134217729,wo=(3+8*Ke)*Ke;function hn(t,e,n,r,i){let o,s,a,l,u=e[0],f=r[0],c=0,h=0;f>u==f>-u?(o=u,u=e[++c]):(o=f,f=r[++h]);let d=0;if(c<t&&h<n)for(f>u==f>-u?(s=u+o,a=o-(s-u),u=e[++c]):(s=f+o,a=o-(s-f),f=r[++h]),o=s,a!==0&&(i[d++]=a);c<t&&h<n;)f>u==f>-u?(s=o+u,l=s-o,a=o-(s-l)+(u-l),u=e[++c]):(s=o+f,l=s-o,a=o-(s-l)+(f-l),f=r[++h]),o=s,a!==0&&(i[d++]=a);for(;c<t;)s=o+u,l=s-o,a=o-(s-l)+(u-l),u=e[++c],o=s,a!==0&&(i[d++]=a);for(;h<n;)s=o+f,l=s-o,a=o-(s-l)+(f-l),f=r[++h],o=s,a!==0&&(i[d++]=a);return(o!==0||d===0)&&(i[d++]=o),d}function So(t,e){let n=e[0];for(let r=1;r<t;r++)n+=e[r];return n}function vt(t){return new Float64Array(t)}const Ro=(3+16*Ke)*Ke,Eo=(2+12*Ke)*Ke,Mo=(9+64*Ke)*Ke*Ke,at=vt(4),tr=vt(8),nr=vt(12),rr=vt(16),Ue=vt(4);function Ao(t,e,n,r,i,o,s){let a,l,u,f,c,h,d,m,p,x,y,b,M,R,A,C,N,k;const O=t-i,P=n-i,T=e-o,W=r-o;R=O*W,h=ze*O,d=h-(h-O),m=O-d,h=ze*W,p=h-(h-W),x=W-p,A=m*x-(R-d*p-m*p-d*x),C=T*P,h=ze*T,d=h-(h-T),m=T-d,h=ze*P,p=h-(h-P),x=P-p,N=m*x-(C-d*p-m*p-d*x),y=A-N,c=A-y,at[0]=A-(y+c)+(c-N),b=R+y,c=b-R,M=R-(b-c)+(y-c),y=M-C,c=M-y,at[1]=M-(y+c)+(c-C),k=b+y,c=k-b,at[2]=b-(k-c)+(y-c),at[3]=k;let I=So(4,at),Y=Eo*s;if(I>=Y||-I>=Y||(c=t-O,a=t-(O+c)+(c-i),c=n-P,u=n-(P+c)+(c-i),c=e-T,l=e-(T+c)+(c-o),c=r-W,f=r-(W+c)+(c-o),a===0&&l===0&&u===0&&f===0)||(Y=Mo*s+wo*Math.abs(I),I+=O*f+W*a-(T*u+P*l),I>=Y||-I>=Y))return I;R=a*W,h=ze*a,d=h-(h-a),m=a-d,h=ze*W,p=h-(h-W),x=W-p,A=m*x-(R-d*p-m*p-d*x),C=l*P,h=ze*l,d=h-(h-l),m=l-d,h=ze*P,p=h-(h-P),x=P-p,N=m*x-(C-d*p-m*p-d*x),y=A-N,c=A-y,Ue[0]=A-(y+c)+(c-N),b=R+y,c=b-R,M=R-(b-c)+(y-c),y=M-C,c=M-y,Ue[1]=M-(y+c)+(c-C),k=b+y,c=k-b,Ue[2]=b-(k-c)+(y-c),Ue[3]=k;const $=hn(4,at,4,Ue,tr);R=O*f,h=ze*O,d=h-(h-O),m=O-d,h=ze*f,p=h-(h-f),x=f-p,A=m*x-(R-d*p-m*p-d*x),C=T*u,h=ze*T,d=h-(h-T),m=T-d,h=ze*u,p=h-(h-u),x=u-p,N=m*x-(C-d*p-m*p-d*x),y=A-N,c=A-y,Ue[0]=A-(y+c)+(c-N),b=R+y,c=b-R,M=R-(b-c)+(y-c),y=M-C,c=M-y,Ue[1]=M-(y+c)+(c-C),k=b+y,c=k-b,Ue[2]=b-(k-c)+(y-c),Ue[3]=k;const F=hn($,tr,4,Ue,nr);R=a*f,h=ze*a,d=h-(h-a),m=a-d,h=ze*f,p=h-(h-f),x=f-p,A=m*x-(R-d*p-m*p-d*x),C=l*u,h=ze*l,d=h-(h-l),m=l-d,h=ze*u,p=h-(h-u),x=u-p,N=m*x-(C-d*p-m*p-d*x),y=A-N,c=A-y,Ue[0]=A-(y+c)+(c-N),b=R+y,c=b-R,M=R-(b-c)+(y-c),y=M-C,c=M-y,Ue[1]=M-(y+c)+(c-C),k=b+y,c=k-b,Ue[2]=b-(k-c)+(y-c),Ue[3]=k;const ge=hn(F,nr,4,Ue,rr);return rr[ge-1]}function Po(t,e,n,r,i,o){const s=(e-o)*(n-i),a=(t-i)*(r-o),l=s-a,u=Math.abs(s+a);return Math.abs(l)>=Ro*u?l:-Ao(t,e,n,r,i,o,u)}const pt=(t,e)=>t.ll.x<=e.x&&e.x<=t.ur.x&&t.ll.y<=e.y&&e.y<=t.ur.y,En=(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 et=Number.EPSILON;et===void 0&&(et=Math.pow(2,-52));const Co=et*et,ir=(t,e)=>{if(-et<t&&t<et&&-et<e&&e<et)return 0;const n=t-e;return n*n<Co*t*e?0:t<e?-1:1};class vo{constructor(){this.reset()}reset(){this.xRounder=new or,this.yRounder=new or}round(e,n){return{x:this.xRounder.round(e),y:this.yRounder.round(n)}}}class or{constructor(){this.tree=new kn,this.round(0)}round(e){const n=this.tree.add(e),r=this.tree.prev(n);if(r!==null&&ir(n.key,r.key)===0)return this.tree.remove(e),r.key;const i=this.tree.next(n);return i!==null&&ir(n.key,i.key)===0?(this.tree.remove(e),i.key):e}}const Rt=new vo,Xt=(t,e)=>t.x*e.y-t.y*e.x,gi=(t,e)=>t.x*e.x+t.y*e.y,sr=(t,e,n)=>{const r=Po(t.x,t.y,e.x,e.y,n.x,n.y);return r>0?-1:r<0?1:0},qt=t=>Math.sqrt(gi(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 Xt(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 gi(i,r)/qt(i)/qt(r)},ar=(t,e,n)=>e.y===0?null:{x:t.x+e.x/e.y*(n-t.y),y:n},lr=(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 lr(n,r,t.x);if(r.x===0)return lr(t,e,n.x);if(e.y===0)return ar(n,r,t.y);if(r.y===0)return ar(t,e,n.y);const i=Xt(e,r);if(i==0)return null;const o={x:n.x-t.x,y:n.y-t.y},s=Xt(o,e)/i,a=Xt(o,r)/i,l=t.x+a*e.x,u=n.x+s*r.x,f=t.y+a*e.y,c=n.y+s*r.y,h=(l+u)/2,d=(f+c)/2;return{x:h,y:d}};class We{static compare(e,n){const r=We.comparePoints(e.point,n.point);return r!==0?r:(e.point!==n.point&&e.link(n),e.isLeft!==n.isLeft?e.isLeft?1:-1:tt.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:u}=n.get(o);return s>=0&&l>=0?a<u?1:a>u?-1:0:s<0&&l<0?a<u?-1:a>u?1:0:l<s?-1:l>s?1:0}}}let Fo=0;class tt{static compare(e,n){const r=e.leftSE.point.x,i=n.leftSE.point.x,o=e.rightSE.point.x,s=n.rightSE.point.x;if(s<r)return 1;if(o<i)return-1;const a=e.leftSE.point.y,l=n.leftSE.point.y,u=e.rightSE.point.y,f=n.rightSE.point.y;if(r<i){if(l<a&&l<u)return 1;if(l>a&&l>u)return-1;const c=e.comparePoint(n.leftSE.point);if(c<0)return 1;if(c>0)return-1;const h=n.comparePoint(e.rightSE.point);return h!==0?h:-1}if(r>i){if(a<l&&a<f)return-1;if(a>l&&a>f)return 1;const c=n.comparePoint(e.leftSE.point);if(c!==0)return c;const h=e.comparePoint(n.rightSE.point);return h<0?1:h>0?-1:1}if(a<l)return-1;if(a>l)return 1;if(o<s){const c=n.comparePoint(e.rightSE.point);if(c!==0)return c}if(o>s){const c=e.comparePoint(n.rightSE.point);if(c<0)return 1;if(c>0)return-1}if(o!==s){const c=u-a,h=o-r,d=f-l,m=s-i;if(c>h&&d<m)return 1;if(c<h&&d>m)return-1}return o>s?1:o<s||u<f?-1:u>f?1:e.id<n.id?-1:e.id>n.id?1:0}constructor(e,n,r,i){this.id=++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=We.comparePoints(e,n);if(a<0)i=e,o=n,s=1;else if(a>0)i=n,o=e,s=-1;else throw new Error(`Tried to create degenerate segment at [${e.x}, ${e.y}]`);const l=new We(i,!0),u=new We(o,!1);return new tt(l,u,[r],[s])}replaceRightSE(e){this.rightSE=e,this.rightSE.segment=this,this.rightSE.otherSE=this.leftSE,this.leftSE.otherSE=this.rightSE}bbox(){const e=this.leftSE.point.y,n=this.rightSE.point.y;return{ll:{x:this.leftSE.point.x,y:e<n?e:n},ur:{x:this.rightSE.point.x,y:e>n?e:n}}}vector(){return{x:this.rightSE.point.x-this.leftSE.point.x,y:this.rightSE.point.y-this.leftSE.point.y}}isAnEndpoint(e){return e.x===this.leftSE.point.x&&e.y===this.leftSE.point.y||e.x===this.rightSE.point.x&&e.y===this.rightSE.point.y}comparePoint(e){if(this.isAnEndpoint(e))return 0;const n=this.leftSE.point,r=this.rightSE.point,i=this.vector();if(n.x===r.x)return e.x===n.x?0:e.x<n.x?1:-1;const o=(e.y-n.y)/i.y,s=n.x+o*i.x;if(e.x===s)return 0;const a=(e.x-n.x)/i.x,l=n.y+a*i.y;return e.y===l?0:e.y<l?-1:1}getIntersection(e){const n=this.bbox(),r=e.bbox(),i=En(n,r);if(i===null)return null;const o=this.leftSE.point,s=this.rightSE.point,a=e.leftSE.point,l=e.rightSE.point,u=pt(n,a)&&this.comparePoint(a)===0,f=pt(r,o)&&e.comparePoint(o)===0,c=pt(n,l)&&this.comparePoint(l)===0,h=pt(r,s)&&e.comparePoint(s)===0;if(f&&u)return h&&!c?s:!h&&c?l:null;if(f)return c&&o.x===l.x&&o.y===l.y?null:o;if(u)return h&&s.x===a.x&&s.y===a.y?null:a;if(h&&c)return null;if(h)return s;if(c)return l;const d=_o(o,this.vector(),a,e.vector());return d===null||!pt(i,d)?null:Rt.round(d.x,d.y)}split(e){const n=[],r=e.events!==void 0,i=new We(e,!0),o=new We(e,!1),s=this.rightSE;this.replaceRightSE(o),n.push(o),n.push(i);const a=new tt(i,s,this.rings.slice(),this.windings.slice());return We.comparePoints(a.leftSE.point,a.rightSE.point)>0&&a.swapEvents(),We.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),r&&(i.checkForConsuming(),o.checkForConsuming()),n}swapEvents(){const e=this.rightSE;this.rightSE=this.leftSE,this.leftSE=e,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(let n=0,r=this.windings.length;n<r;n++)this.windings[n]*=-1}consume(e){let n=this,r=e;for(;n.consumedBy;)n=n.consumedBy;for(;r.consumedBy;)r=r.consumedBy;const i=tt.compare(n,r);if(i!==0){if(i>0){const o=n;n=r,r=o}if(n.prev===r){const o=n;n=r,r=o}for(let o=0,s=r.rings.length;o<s;o++){const a=r.rings[o],l=r.windings[o],u=n.rings.indexOf(a);u===-1?(n.rings.push(a),n.windings.push(l)):n.windings[u]+=l}r.rings=null,r.windings=null,r.consumedBy=n,r.leftSE.consumedBy=n.leftSE,r.rightSE.consumedBy=n.rightSE}}prevInResult(){return this._prevInResult!==void 0?this._prevInResult:(this.prev?this.prev.isInResult()?this._prevInResult=this.prev:this._prevInResult=this.prev.prevInResult():this._prevInResult=null,this._prevInResult)}beforeState(){if(this._beforeState!==void 0)return this._beforeState;if(!this.prev)this._beforeState={rings:[],windings:[],multiPolys:[]};else{const e=this.prev.consumedBy||this.prev;this._beforeState=e.afterState()}return this._beforeState}afterState(){if(this._afterState!==void 0)return this._afterState;const e=this.beforeState();this._afterState={rings:e.rings.slice(0),windings:e.windings.slice(0),multiPolys:[]};const n=this._afterState.rings,r=this._afterState.windings,i=this._afterState.multiPolys;for(let a=0,l=this.rings.length;a<l;a++){const u=this.rings[a],f=this.windings[a],c=n.indexOf(u);c===-1?(n.push(u),r.push(f)):r[c]+=f}const o=[],s=[];for(let a=0,l=n.length;a<l;a++){if(r[a]===0)continue;const u=n[a],f=u.poly;if(s.indexOf(f)===-1)if(u.isExterior)o.push(f);else{s.indexOf(f)===-1&&s.push(f);const c=o.indexOf(u.poly);c!==-1&&o.splice(c,1)}}for(let a=0,l=o.length;a<l;a++){const u=o[a].multiPoly;i.indexOf(u)===-1&&i.push(u)}return this._afterState}isInResult(){if(this.consumedBy)return!1;if(this._isInResult!==void 0)return this._isInResult;const e=this.beforeState().multiPolys,n=this.afterState().multiPolys;switch(Ze.type){case"union":{const r=e.length===0,i=n.length===0;this._isInResult=r!==i;break}case"intersection":{let r,i;e.length<n.length?(r=e.length,i=n.length):(r=n.length,i=e.length),this._isInResult=i===Ze.numMultiPolys&&r<i;break}case"xor":{const r=Math.abs(e.length-n.length);this._isInResult=r%2===1;break}case"difference":{const r=i=>i.length===1&&i[0].isSubject;this._isInResult=r(e)!==r(n);break}default:throw new Error(`Unrecognized operation type found ${Ze.type}`)}return this._isInResult}}class cr{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=Rt.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=Rt.round(e[s][0],e[s][1]);l.x===o.x&&l.y===o.y||(this.segments.push(tt.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(tt.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 cr(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 cr(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 ur{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 $t{static factory(e){const n=[];for(let r=0,i=e.length;r<i;r++){const o=e[r];if(!o.isInResult()||o.ringOut)continue;let s=null,a=o.leftSE,l=o.rightSE;const u=[a],f=a.point,c=[];for(;s=a,a=l,u.push(a),a.point!==f;)for(;;){const h=a.getAvailableLinkedEvents();if(h.length===0){const p=u[0].point,x=u[u.length-1].point;throw new Error(`Unable to complete output ring starting at [${p.x}, ${p.y}]. Last matching segment found ends at [${x.x}, ${x.y}].`)}if(h.length===1){l=h[0].otherSE;break}let d=null;for(let p=0,x=c.length;p<x;p++)if(c[p].point===a.point){d=p;break}if(d!==null){const p=c.splice(d)[0],x=u.splice(p.index);x.unshift(x[0].otherSE),n.push(new $t(x.reverse()));continue}c.push({index:u.length,point:a.point});const m=a.getLeftmostComparator(s);l=h.sort(m)[0].otherSE;break}n.push(new $t(u))}return n}constructor(e){this.events=e;for(let n=0,r=e.length;n<r;n++)e[n].segment.ringOut=this;this.poly=null}getGeom(){let e=this.events[0].point;const n=[e];for(let u=1,f=this.events.length-1;u<f;u++){const c=this.events[u].point,h=this.events[u+1].point;sr(c,e,h)!==0&&(n.push(c),e=c)}if(n.length===1)return null;const r=n[0],i=n[1];sr(r,e,i)===0&&n.shift(),n.push(n[0]);const o=this.isExteriorRing()?1:-1,s=this.isExteriorRing()?0:n.length-1,a=this.isExteriorRing()?n.length:-1,l=[];for(let u=s;u!=a;u+=o)l.push([n[u].x,n[u].y]);return l}isExteriorRing(){if(this._isExteriorRing===void 0){const e=this.enclosingRing();this._isExteriorRing=e?!e.isExteriorRing():!0}return this._isExteriorRing}enclosingRing(){return this._enclosingRing===void 0&&(this._enclosingRing=this._calcEnclosingRing()),this._enclosingRing}_calcEnclosingRing(){let e=this.events[0];for(let i=1,o=this.events.length;i<o;i++){const s=this.events[i];We.compare(e,s)>0&&(e=s)}let n=e.segment.prevInResult(),r=n?n.prevInResult():null;for(;;){if(!n)return null;if(!r)return n.ringOut;if(r.ringOut!==n.ringOut)return r.ringOut.enclosingRing()!==n.ringOut?n.ringOut:n.ringOut.enclosingRing();n=r.prevInResult(),r=n?n.prevInResult():null}}}class fr{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 fr(o));else{const s=o.enclosingRing();s.poly||n.push(new fr(s)),s.poly.addInterior(o)}}return n}}class No{constructor(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:tt.compare;this.queue=e,this.tree=new kn(n),this.segments=[]}process(e){const n=e.segment,r=[];if(e.consumedBy)return e.isLeft?this.queue.remove(e.otherSE):this.tree.remove(n),r;const i=e.isLeft?this.tree.add(n):this.tree.find(n);if(!i)throw new Error(`Unable to find segment #${n.id} [${n.leftSE.point.x}, ${n.leftSE.point.y}] -> [${n.rightSE.point.x}, ${n.rightSE.point.y}] in SweepLine tree.`);let o=i,s=i,a,l;for(;a===void 0;)o=this.tree.prev(o),o===null?a=null:o.key.consumedBy===void 0&&(a=o.key);for(;l===void 0;)s=this.tree.next(s),s===null?l=null:s.key.consumedBy===void 0&&(l=s.key);if(e.isLeft){let u=null;if(a){const c=a.getIntersection(n);if(c!==null&&(n.isAnEndpoint(c)||(u=c),!a.isAnEndpoint(c))){const h=this._splitSafely(a,c);for(let d=0,m=h.length;d<m;d++)r.push(h[d])}}let f=null;if(l){const c=l.getIntersection(n);if(c!==null&&(n.isAnEndpoint(c)||(f=c),!l.isAnEndpoint(c))){const h=this._splitSafely(l,c);for(let d=0,m=h.length;d<m;d++)r.push(h[d])}}if(u!==null||f!==null){let c=null;u===null?c=f:f===null?c=u:c=We.comparePoints(u,f)<=0?u:f,this.queue.remove(n.rightSE),r.push(n.rightSE);const h=n.split(c);for(let d=0,m=h.length;d<m;d++)r.push(h[d])}r.length>0?(this.tree.remove(n),r.push(e)):(this.segments.push(n),n.prev=a)}else{if(a&&l){const u=a.getIntersection(l);if(u!==null){if(!a.isAnEndpoint(u)){const f=this._splitSafely(a,u);for(let c=0,h=f.length;c<h;c++)r.push(f[c])}if(!l.isAnEndpoint(u)){const f=this._splitSafely(l,u);for(let c=0,h=f.length;c<h;c++)r.push(f[c])}}}this.tree.remove(n)}return r}_splitSafely(e,n){this.tree.remove(e);const r=e.rightSE;this.queue.remove(r);const i=e.split(n);return i.push(r),e.consumedBy===void 0&&this.tree.add(e),i}}const hr=typeof process<"u"&&process.env.POLYGON_CLIPPING_MAX_QUEUE_SIZE||1e6,Bo=typeof process<"u"&&process.env.POLYGON_CLIPPING_MAX_SWEEPLINE_SEGMENTS||1e6;class zo{run(e,n,r){Ze.type=e,Rt.reset();const i=[new ur(n,!0)];for(let c=0,h=r.length;c<h;c++)i.push(new ur(r[c],!1));if(Ze.numMultiPolys=i.length,Ze.type==="difference"){const c=i[0];let h=1;for(;h<i.length;)En(i[h].bbox,c.bbox)!==null?h++:i.splice(h,1)}if(Ze.type==="intersection")for(let c=0,h=i.length;c<h;c++){const d=i[c];for(let m=c+1,p=i.length;m<p;m++)if(En(d.bbox,i[m].bbox)===null)return[]}const o=new kn(We.compare);for(let c=0,h=i.length;c<h;c++){const d=i[c].getSweepEvents();for(let m=0,p=d.length;m<p;m++)if(o.insert(d[m]),o.size>hr)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 c=l.key;if(o.size===a){const d=c.segment;throw new Error(`Unable to pop() ${c.isLeft?"left":"right"} SweepEvent [${c.point.x}, ${c.point.y}] from segment #${d.id} [${d.leftSE.point.x}, ${d.leftSE.point.y}] -> [${d.rightSE.point.x}, ${d.rightSE.point.y}] from queue.`)}if(o.size>hr)throw new Error("Infinite loop when passing sweep line over endpoints (queue size too big).");if(s.segments.length>Bo)throw new Error("Infinite loop when passing sweep line over endpoints (too many sweep line segments).");const h=s.process(c);for(let d=0,m=h.length;d<m;d++){const p=h[d];p.consumedBy===void 0&&o.insert(p)}a=o.size,l=o.pop()}Rt.reset();const u=$t.factory(s.segments);return new Do(u).getGeom()}}const Ze=new zo,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)},Yo=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 Xo={union:ko,intersection:Uo,xor:Oo,difference:Yo};function mt(t){return t==null?null:pi(t)||yi(t)||Wo(t)?t:null}function dr(t){return typeof t=="number"&&Number.isFinite(t)}function Wt(t){return Array.isArray(t)&&t.length>=2&&dr(t[0])&&dr(t[1])}function pi(t){return Array.isArray(t)&&t.length>0&&t.every(e=>Wt(e))}function yi(t){return Array.isArray(t)&&t.length>0&&t.every(e=>pi(e))}function Wo(t){return Array.isArray(t)&&t.length>0&&t.every(e=>yi(e))}function Xe(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 Et(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 dn(t){if(!Array.isArray(t)||t.length===0)return[];const e=[];for(const o of t){const s=Xe(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(Et(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 bi(t){if(!Array.isArray(t)||t.length===0)return[];const e=t[0];if(Wt(e)){const i=dn([t]);return i.length>0?[i]:[]}if(!Array.isArray(e)||e.length===0)return[];const n=e[0];if(Wt(n)){const i=dn(t);return i.length>0?[i]:[]}if(!Array.isArray(n)||n.length===0||!Wt(n[0]))return[];const r=[];for(const i of t){const o=dn(i);o.length>0&&r.push(o)}return r}function mr(t,e,n){let r=!1;for(let i=0,o=n.length-1;i<n.length;o=i,i+=1){const s=n[i][0],a=n[i][1],l=n[o][0],u=n[o][1];if(a===u||a>e==u>e)continue;t<(l-s)*(e-a)/(u-a)+s&&(r=!r)}return r}function gt(t){const e=[];for(const n of t??[]){const r=bi(n);for(const i of r){const o=i[0];if(!o||o.length<4)continue;let s=1/0,a=1/0,l=-1/0,u=-1/0;for(const[c,h]of o)c<s&&(s=c),c>l&&(l=c),h<a&&(a=h),h>u&&(u=h);if(!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(l)||!Number.isFinite(u))continue;let f=Math.abs(Et(o));for(let c=1;c<i.length;c+=1)f-=Math.abs(Et(i[c]));e.push({outer:o,holes:i.slice(1),minX:s,minY:a,maxX:l,maxY:u,area:Math.max(1e-6,f)})}}return e}function xi(t,e,n){if(t<n.minX||t>n.maxX||e<n.minY||e>n.maxY||!mr(t,e,n.outer))return!1;for(const r of n.holes)if(mr(t,e,r))return!1;return!0}function Mt(t,e,n){for(const r of n)if(xi(t,e,r))return!0;return!1}const Un=[160,160,160,255];function L(t,e,n){return Math.max(e,Math.min(n,t))}function On(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 Kt(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*On(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 it(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 Mn(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 wi(t){const n=String(t??"").trim().match(/^#?([0-9a-fA-F]{6})$/);if(!n)return[...Un];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 Ho(t){const e=String(t?.classId??"").trim();return e||String(t?.className??"").trim()}function qo(t){const e=[[...Un]],n=new Map;for(const i of t??[]){const o=Ho(i);!o||n.has(o)||(n.set(o,e.length),e.push(wi(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,jt=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 gr(t,e,n){if(e<=jt||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 Xe(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,u=-(o/s),f=a,c=Math.max(jt,n);return Xe([[t[0]+u*c,t[1]+f*c],[e[0]+u*c,e[1]+f*c],[e[0]-u*c,e[1]-f*c],[t[0]-u*c,t[1]-f*c]])}function pr(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 Xe([[n-s,r-s],[i+s,r-s],[i+s,o+s],[n-s,o+s]])}function _t(t,e){return Xe(e?t.map(([n,r])=>[L(n,e[0],e[2]),L(r,e[1],e[3])]):t)}function yr(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=yr(Number(r[0]),e),o=yr(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=Xo.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 Xe(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(Et(i));o<=n||(n=o,e=i)}return e}function cs(t,e=1e-9){const n=Xe(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]),Xe(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 c=t[0]-e[0],h=t[1]-e[1];return c*c+h*h}const s=L(((t[0]-e[0])*r+(t[1]-e[1])*i)/o,0,1),a=e[0]+r*s,l=e[1]+i*s,u=t[0]-a,f=t[1]-l;return u*u+f*f}function 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 u=0,f=-1;for(let c=a+1;c<l;c+=1){const h=us(t[c],t[a],t[l]);h>u&&(u=h,f=c)}f>=0&&u>r&&(n[f]=1,i.push([a,f],[f,l]))}const o=[];for(let s=0;s<t.length;s+=1)n[s]&&o.push(t[s]);return o}function hs(t,e){const n=Xe(t);if(n.length<5||e<=0)return n;const r=n.slice(0,-1),i=fs(r,e);return i.length<3?n:Xe(i)}function ds(t,e){let n=Xe(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=Xe(o)}return n}function ms(t,e){const n=ts(t),r=Math.max(jt,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 _t(gr(n[0],r,i),e.clipBounds);const o=[],s=Math.max(jt,r*es);for(let h=0;h<n.length;h+=1){const d=n[h],m=gr(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 _t(pr(n,r),e.clipBounds);const u=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(L(e.smoothingPasses,0,Jo)):Qo,c=hs(ds(cs(l,1e-9),f),u);return c.length<4?_t(pr(n,r),e.clipBounds):_t(c,e.clipBounds)}function br(){if(typeof window>"u")return 1;const t=window.devicePixelRatio||1;return Number.isFinite(t)&&t>0?t:1}function sn(t){if(typeof window>"u")return()=>{};let e=!0,n=br(),r=null,i=null;const o=()=>{i?.(),i=null,r=null},s=()=>{o(),r=window.matchMedia(`(resolution: ${n}dppx)`);const f=()=>{a("match-media")};if(typeof r.addEventListener=="function"){r.addEventListener("change",f),i=()=>r?.removeEventListener("change",f);return}r.addListener(f),i=()=>r?.removeListener(f)},a=f=>{if(!e)return;const c=br();if(Math.abs(c-n)<=1e-4)return;const h=n;n=c,s(),t({previousDpr:h,nextDpr:c,trigger:f})},l=()=>a("window-resize"),u=()=>a("visual-viewport-resize");return s(),window.addEventListener("resize",l),window.visualViewport?.addEventListener("resize",u),()=>{e=!1,o(),window.removeEventListener("resize",l),window.visualViewport?.removeEventListener("resize",u)}}const rt=[],xr=[],qe={color:"#ff4d4f",width:2,lineDash:rt,lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},Si={color:"#4cc9f0",width:2,lineDash:[10,8],lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},Ri="rgba(23, 23, 25, 0.1)",Ei=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},Qe={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},wr={x:16,y:-24},gs=20,Sr=1e-6,Rr="transparent",ps=3,ys=2,Mi=96,bs=1,Er=1e3,Ai=2,Pi=2,xs=4096,ws=.2,Ss=1.12,Rs=.89,Es=32,Ms="#000000",As=.1,Ps="#FFCF00",Cs="#FF0000",vs=1.5,Mr=[2,2],Ts=1,Is=.25,_s=4,Fs=1,Ls=0,Ds=4,Ns=1.5;function Qt(t,e,n){return[L(t[0],0,e),L(t[1],0,n)]}function Yn(t){if(!Array.isArray(t)||t.length<2)return null;const e=Number(t[0]),n=Number(t[1]);return!Number.isFinite(e)||!Number.isFinite(n)?null:[e,n]}const He=Yn;function Oe(t){return Xe(t)}function Vt(t){return Math.abs(Et(Oe(t)))}function Ar(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 At(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(),At(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(rt),t.shadowColor="rgba(0, 0, 0, 0)",t.shadowBlur=0,t.shadowOffsetX=0,t.shadowOffsetY=0)}function Xn(t){const e=Array.isArray(t?.lineDash)?t.lineDash.filter(s=>Number.isFinite(s)&&s>=0):rt,n=typeof t?.width=="number"&&Number.isFinite(t.width)?Math.max(0,t.width):qe.width,r=typeof t?.shadowBlur=="number"&&Number.isFinite(t.shadowBlur)?Math.max(0,t.shadowBlur):qe.shadowBlur,i=typeof t?.shadowOffsetX=="number"&&Number.isFinite(t.shadowOffsetX)?t.shadowOffsetX:qe.shadowOffsetX,o=typeof t?.shadowOffsetY=="number"&&Number.isFinite(t.shadowOffsetY)?t.shadowOffsetY:qe.shadowOffsetY;return{color:t?.color||qe.color,width:n,lineDash:e.length?e:rt,lineJoin:t?.lineJoin||qe.lineJoin,lineCap:t?.lineCap||qe.lineCap,shadowColor:t?.shadowColor||qe.shadowColor,shadowBlur:r,shadowOffsetX:i,shadowOffsetY:o}}function $e(t,e){return e?Xn({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 Pr(t){return typeof t=="number"&&Number.isFinite(t)}function Bs(t){return Array.isArray(t)&&t.length>=2&&Pr(t[0])&&Pr(t[1])}function zs(t){return Array.isArray(t)&&t.length>=2&&t.every(e=>Bs(e))}function Ci(t,e){if(!(!Array.isArray(t)||t.length===0)){if(zs(t)){e.push(t.map(([n,r])=>[n,r]));return}for(const n of t)Ci(n,e)}}function Cr(t,e){const n=[];Ci(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 wt(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:L(t,0,1)}function vi(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 en(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 en(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 An(t,e,n=Mi){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 tn(t){const e=bi(mt(t));if(e.length===0)return[];const n=[];for(const r of e){const i=r[0];if(!i||i.length<4)continue;const o=i.map(([a,l])=>[a,l]),s=[];for(let a=1;a<r.length;a+=1){const l=r[a];!l||l.length<4||s.push(l.map(([u,f])=>[u,f]))}n.push({outer:o,holes:s})}return n}function Os(t){if(!Array.isArray(t))return Mr;const e=t.filter(n=>Number.isFinite(n)&&n>=0);return e.length>0?e:Mr}function Ys(t){return typeof t!="number"||!Number.isFinite(t)?Ts:L(t,Is,_s)}function Xs(t){return typeof t!="number"||!Number.isFinite(t)?Fs:Math.round(L(t,Ls,Ds))}function Ws(t){const e=wt(t?.radius,Es),n=wt(t?.cursorLineWidth,vs),r=Ys(t?.edgeDetail),i=Xs(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||Ps,cursorActiveColor:t?.cursorActiveColor||Cs,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??He(n?.worldToScreen(i[0],i[1])??[]);if(!o)return;const s=r.radius;!Number.isFinite(s)||s<=0||(t.save(),t.beginPath(),t.arc(o[0],o[1],s,0,Math.PI*2),t.strokeStyle=e.isDrawing?r.cursorActiveColor:r.cursorColor,t.lineWidth=r.cursorLineWidth,t.setLineDash(r.cursorLineDash),t.stroke(),t.setLineDash(rt),t.restore())}const Zs=.58,Hs=4096,qs=.5;let Ft=null;const Lt=new Map;function $s(){if(Ft)return Ft;if(typeof document>"u")return null;const e=document.createElement("canvas").getContext("2d");return e?(Ft=e,Ft):null}function Wn(t,e){const n=`${e.fontWeight}|${e.fontSize}|${e.fontFamily}|${t}`,r=Lt.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 Lt.size>Hs&&Lt.clear(),Lt.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)>qs||(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 Vn(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 Gn(t){const e=typeof t?.paddingX=="number"&&Number.isFinite(t.paddingX)?Math.max(0,t.paddingX):Ve.paddingX,n=typeof t?.paddingY=="number"&&Number.isFinite(t.paddingY)?Math.max(0,t.paddingY):Ve.paddingY,r=typeof t?.fontSize=="number"&&Number.isFinite(t.fontSize)?Math.max(8,t.fontSize):Ve.fontSize,i=typeof t?.borderWidth=="number"&&Number.isFinite(t.borderWidth)?Math.max(0,t.borderWidth):Ve.borderWidth,o=typeof t?.offsetY=="number"&&Number.isFinite(t.offsetY)?t.offsetY:Ve.offsetY,s=typeof t?.borderRadius=="number"&&Number.isFinite(t.borderRadius)?Math.max(0,t.borderRadius):Ve.borderRadius;return{fontFamily:t?.fontFamily||Ve.fontFamily,fontSize:r,fontWeight:t?.fontWeight||Ve.fontWeight,textColor:t?.textColor||Ve.textColor,backgroundColor:t?.backgroundColor||Ve.backgroundColor,borderColor:t?.borderColor||Ve.borderColor,borderWidth:i,paddingX:e,paddingY:n,offsetY:o,borderRadius:s}}function Zn(t,e){return e?Gn({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 Hn(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<=Sr||!Number.isFinite(e))return 0;let s=o;r!=null&&Number.isFinite(r)&&(s=L(r,i,o));const a=Math.max(Sr,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):Qe.fontSize,n=typeof t?.borderRadius=="number"&&Number.isFinite(t.borderRadius)?Math.max(0,t.borderRadius):Qe.borderRadius,r=typeof t?.paddingX=="number"&&Number.isFinite(t.paddingX)?Math.max(0,t.paddingX):Qe.paddingX,i=typeof t?.paddingY=="number"&&Number.isFinite(t.paddingY)?Math.max(0,t.paddingY):Qe.paddingY;return{fontFamily:t?.fontFamily||Qe.fontFamily,fontSize:e,fontWeight:t?.fontWeight||Qe.fontWeight,textColor:t?.textColor||Qe.textColor,backgroundColor:t?.backgroundColor||Qe.backgroundColor,borderRadius:n,paddingX:r,paddingY:i}}function Qs(t){const e=typeof t?.x=="number"&&Number.isFinite(t.x)?t.x:wr.x,n=typeof t?.y=="number"&&Number.isFinite(t.y)?t.y:wr.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 Ti(t,e,n,r,i,o,s=!0){const a=e.trim();if(!a)return;t.save(),t.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,t.textAlign="center",t.textBaseline="middle";const u=Wn(a,o)+o.paddingX*2,f=o.fontSize+o.paddingY*2,c=n[0],h=n[1]-o.offsetY,d=s?L(c,u*.5+1,r-u*.5-1):c,m=s?L(h,f*.5+1,i-f*.5-1):h,p=d-u*.5,x=m-f*.5;t.fillStyle=o.backgroundColor,t.strokeStyle=o.borderColor,t.lineWidth=o.borderWidth,vi(t,p,x,u,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=Wn(l,o)+o.paddingX*2,c=o.fontSize+o.paddingY*2,h=L(n[0]+s,f*.5+1,r-f*.5-1),d=L(n[1]+a,c*.5+1,i-c*.5-1),m=h-f*.5,p=d-c*.5;t.fillStyle=o.backgroundColor,vi(t,m,p,f,c,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(),At(t,e,!0);for(const i of n)i.length<4||At(t,i,!0);t.fillStyle=r,t.fill("evenodd"),t.restore()}}function Ii(t){const{ctx:e,overlayShapes:n,imageOuterRing:r,worldToScreenPoints:i,baseStrokeStyle:o,onInvertedFillDebug:s}=t,a=!!globalThis.__OPEN_PLANT_DEBUG_OVERLAY__;for(let l=0;l<n.length;l+=1){const u=n[l];if(!u?.coordinates?.length||u.visible===!1)continue;const f=u.closed??Us(u.coordinates),c=Cr(u.coordinates,f);if(u.invertedFill?.fillColor){const d=[],m=Cr(u.coordinates,!0);for(const p of m){const x=i(p);x.length>=4&&d.push(x)}a&&s&&s({id:u.id??l,outerRingPoints:r.length,sourceRingCount:m.length,holeRingCount:d.length,fillColor:u.invertedFill.fillColor}),na(e,r,d,u.invertedFill.fillColor)}if(c.length===0)continue;const h=$e(o,u.stroke??u.strokeStyle);for(const d of c){const m=i(d);m.length<2||ke(e,m,h,f,u.fill??!1)}}}function Dt(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:wt(t?.rectangleAreaMm2,Ai),circleAreaMm2:wt(t?.circleAreaMm2,Pi),rectanglePixelSize:wt(t?.rectanglePixelSize,xs)}}const vr=1e3;function ia(t){return t*vr*vr}function Tr(t,e,n){if(!t||!Number.isFinite(e)||e<=0)return[];if(n){const r=n.worldToScreen(t[0],t[1]),i=n.worldToScreen(t[0]+e,t[1]);if(r&&i){const o=Math.hypot(i[0]-r[0],i[1]-r[1]),s=[[r[0]-o,r[1]-o],[r[0]+o,r[1]-o],[r[0]+o,r[1]+o],[r[0]-o,r[1]+o]],a=[];for(const l of s){const u=n.screenToWorld(l);if(!u)throw new Error("Failed to create rectangle");a.push(u)}return 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=Mi){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 c=r.rectanglePixelSize*.5;return Tr(n,c,a()).map(h=>Qt(h,i,o))}let l=0;if(e==="stamp-rectangle"||e==="stamp-rectangle-2mm2"?l=e==="stamp-rectangle-2mm2"?Ai: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"?Pi:r.circleAreaMm2),!Number.isFinite(l)||l<=0)return[];const u=ia(l);let f=[];if(e==="stamp-rectangle"||e==="stamp-rectangle-2mm2"){const c=s(Math.sqrt(u)*.5);f=Tr(n,c,a())}else if(e==="stamp-circle"||e==="stamp-circle-2mm2"||e==="stamp-circle-hpf-0.2mm2"){const c=s(Math.sqrt(u/Math.PI));f=oa(n,c)}return f.length?f.map(c=>Qt(c,i,o)):[]}function aa(t){return{color:Ri,width:Ei,lineDash:rt,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 Rr;const e=t.trim();return e.length>0?e:Rr}function Ir(t){return Array.isArray(t)&&t.length>=4&&Vt(t)>bs}function _i({tool:t,imageWidth:e,imageHeight:n,imageMpp:r,imageZoom:i,stampOptions:o,brushOptions:s,projectorRef:a,onBrushTap:l,onDrawComplete:u,onPatchComplete:f,enabled:c,viewStateSignal:h,persistedRegions:d,patchRegions:m,persistedPolygons:p,drawFillColor:x,regionStrokeStyle:y,regionStrokeHoverStyle:b,regionStrokeActiveStyle:M,patchStrokeStyle:R,resolveRegionStrokeStyle:A,resolveRegionLabelStyle:C,overlayShapes:N,hoveredRegionId:k=null,activeRegionId:O=null,regionLabelStyle:P,drawAreaTooltip:T,autoLiftRegionLabelAtMaxZoom:W=!1,regionLabelAnchor:I="top-center",clampRegionLabelToViewport:Y=!0,regionLabelAutoLiftOffsetPx:$,invalidateRef:F,className:ge,style:V}){const H=g.useRef(null),Me=g.useRef(!1),Se=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}),B=c??t!=="cursor",se=g.useMemo(()=>d&&d.length>0?d:!p||p.length===0?xr:p.map((w,E)=>({id:E,coordinates:w})),[d,p]),ue=g.useMemo(()=>m??xr,[m]),Q=g.useMemo(()=>{const w=[];for(let E=0;E<se.length;E+=1){const _=se[E],z=tn(_.coordinates);z.length!==0&&w.push({region:_,regionIndex:E,regionKey:_.id??E,polygons:z})}return w},[se]),ce=g.useMemo(()=>{const w=[];for(let E=0;E<ue.length;E+=1){const _=ue[E],z=tn(_.coordinates);z.length!==0&&w.push({region:_,regionIndex:E,regionKey:_.id??E,polygons:z})}return w},[ue]),ne=g.useMemo(()=>Xn(y),[y]),_e=g.useMemo(()=>$e(ne,b),[ne,b]),Re=g.useMemo(()=>$e(ne,M),[ne,M]),fe=g.useMemo(()=>$e(Si,R),[R]),xe=g.useMemo(()=>la(x),[x]),te=g.useMemo(()=>Gn(P),[P]),ae=g.useMemo(()=>ea(T),[T]),he=g.useMemo(()=>ra(o),[o]),le=g.useMemo(()=>Ws(s),[s]),re=g.useMemo(()=>({position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",touchAction:"none",pointerEvents:B?"auto":"none",cursor:B?t==="brush"?"none":"crosshair":"default",...V}),[B,t,V]),Pe=g.useCallback(()=>{const w=H.current;if(!w)return;const E=w.getBoundingClientRect(),_=Math.max(1,window.devicePixelRatio||1),z=Math.max(1,Math.round(E.width*_)),Z=Math.max(1,Math.round(E.height*_));(w.width!==z||w.height!==Z)&&(w.width=z,w.height=Z)},[B,t]),we=g.useCallback(w=>{const E=a.current;if(!E||w.length===0)return[];const _=new Array(w.length);for(let z=0;z<w.length;z+=1){const Z=He(E.worldToScreen(w[z][0],w[z][1]));if(!Z)return[];_[z]=Z}return _},[a]),G=g.useCallback(w=>{const E=a.current,_=H.current;if(!E||!_)return null;const z=_.getBoundingClientRect(),Z=He(E.screenToWorld(z.left+w[0],z.top+w[1]));return Z?Qt(Z,e,n):null},[a,e,n]),j=g.useCallback(()=>{const w=a.current,E=w?.getViewState?.().rotationDeg??0;if(!(Math.abs(E%360)<.01||!w))return{worldToScreen:(_,z)=>He(w.worldToScreen(_,z)),screenToWorld:G}},[a,G]),be=g.useCallback(w=>{if(!Number.isFinite(w)||w<=0)return 0;const E=typeof r=="number"&&Number.isFinite(r)&&r>0?r:1,_=typeof i=="number"&&Number.isFinite(i)?i:0,z=a.current?.getViewState?.().zoom,Z=typeof z=="number"&&Number.isFinite(z)&&z>0?z:1,ye=_+Math.log2(Z),oe=Math.max(1e-9,On(E,_,ye));return w/oe/Z},[r,i,a]),ee=g.useCallback((w,E)=>sa({stampTool:w,center:E,resolvedStampOptions:he,imageWidth:e,imageHeight:n,micronsToWorldPixels:be,getRectangleProjection:j}),[be,e,n,he,j]),J=g.useCallback(()=>{const w=v.current;return Dt(t)?ee(t,w.stampCenter):t==="brush"?[]:w.isDrawing?t==="freehand"?w.points:t==="rectangle"?en(w.start,w.current,j()):t==="circular"?An(w.start,w.current):[]:[]},[t,ee,j]),Ae=g.useCallback(()=>{Pe();const w=H.current;if(!w)return;const E=w.getContext("2d");if(!E)return;const _=Math.max(1,window.devicePixelRatio||1),z=w.width/_,Z=w.height/_;if(E.setTransform(1,0,0,1,0,0),E.clearRect(0,0,w.width,w.height),E.setTransform(_,0,0,_,0,0),Q.length>0)for(const oe of Q){const{region:me,polygons:ve,regionIndex:Te,regionKey:Be}=oe,st=Jt(O,Be)?"active":Jt(k,Be)?"hover":"default";let je=st==="active"?Re:st==="hover"?_e:ne;if(A){const It=A({region:me,regionId:Be,regionIndex:Te,state:st});je=$e(je,It||void 0)}const Tt=st==="default"?null:aa(je);for(const It of ve){const ln=we(It.outer);ln.length>=4&&(Tt&&ke(E,ln,Tt,!0,!1),ke(E,ln,je,!0,!1));for(const lo of It.holes){const cn=we(lo);cn.length>=4&&(Tt&&ke(E,cn,Tt,!0,!1),ke(E,cn,je,!0,!1))}}}if(ce.length>0)for(const oe of ce)for(const me of oe.polygons){const ve=we(me.outer);ve.length>=4&&ke(E,ve,fe,!0,!1);for(const Te of me.holes){const Be=we(Te);Be.length>=4&&ke(E,Be,fe,!0,!1)}}if(Array.isArray(N)&&N.length>0){const oe=we(Oe([[0,0],[e,0],[e,n],[0,n]]));Ii({ctx:E,overlayShapes:N,imageOuterRing:oe,worldToScreenPoints:we,baseStrokeStyle:ne,onInvertedFillDebug:globalThis.__OPEN_PLANT_DEBUG_OVERLAY__?me=>{const ve=String(me.id),Te=`${me.outerRingPoints}|${me.sourceRingCount}|${me.holeRingCount}|${me.fillColor}`;Se.current.get(ve)!==Te&&(Se.current.set(ve,Te),console.debug("[open-plant] invertedFill",me))}:void 0})}const ye=J();if(B){if(t==="brush")Vs(E,v.current,le),Gs(E,v.current,a.current,le);else if(ye.length>0)if(t==="freehand"){const oe=we(ye);oe.length>=2&&ke(E,oe,ne,!1,!1),oe.length>=3&&ke(E,we(Oe(ye)),ne,!0,!0,xe)}else{const oe=we(ye);oe.length>=4&&ke(E,oe,ne,!0,!0,xe)}}if(Q.length>0){const oe=Math.max(1e-6,a.current?.getViewState?.().zoom??1),me=typeof $=="number"&&Number.isFinite($)?Math.max(0,$):Hn(W,oe,a.current?.getZoomRange?.(),a.current?.getRegionLabelAutoLiftCapZoom?.());for(const ve of Q){if(!ve.region.label)continue;const Te=Vn(ve.polygons,we,I);if(!Te)continue;let Be=Zn(te,C?.({region:ve.region,regionId:ve.regionKey,regionIndex:ve.regionIndex,zoom:oe}));me>0&&(Be={...Be,offsetY:Be.offsetY+me}),Ti(E,ve.region.label,Te,z,Z,Be,Y)}}if(ae.enabled&&B&&(t==="freehand"||t==="rectangle"||t==="circular")){const oe=v.current;if(oe.isDrawing){const me=t==="freehand"?Oe(ye):ye;if(me.length>=4){const ve=Vt(me),Te=typeof r=="number"&&Number.isFinite(r)&&r>0?r:0,Be=Te>0?ve*Te*Te/(Er*Er):0,st=ae.format(Be),je=oe.cursorScreen??(oe.current?He(a.current?.worldToScreen(oe.current[0],oe.current[1])??[]):null);je&&ta(E,st,je,z,Z,ae.style,ae.cursorOffsetX,ae.cursorOffsetY)}}}},[B,t,J,Pe,we,e,n,a,Q,N,k,O,ne,_e,Re,xe,ce,fe,A,C,te,ae,W,I,Y,$,r,le]),X=g.useCallback(()=>{Me.current||(Me.current=!0,requestAnimationFrame(()=>{Me.current=!1,Ae()}))},[Ae]),Ce=g.useCallback((w=!1)=>{const E=v.current,_=H.current;_&&E.pointerId!==null&&_.hasPointerCapture(E.pointerId)&&_.releasePointerCapture(E.pointerId),E.isDrawing=!1,E.pointerId=null,E.start=null,E.current=null,E.points=[],E.screenPoints=[],E.stampCenter=null,w||(E.cursor=null,E.cursorScreen=null)},[]),De=g.useCallback(w=>{const E=a.current;if(!E||e<=0||n<=0)return null;const _=He(E.screenToWorld(w.clientX,w.clientY));return _?Qt(_,e,n):null},[a,e,n]),Le=g.useCallback(w=>{const E=H.current;if(!E)return null;const _=E.getBoundingClientRect(),z=L(w.clientX-_.left,0,_.width),Z=L(w.clientY-_.top,0,_.height);return!Number.isFinite(z)||!Number.isFinite(Z)?null:[z,Z]},[]),U=g.useCallback(()=>{const w=v.current;if(!w.isDrawing){Ce(!0),X();return}let E=[];if(t==="freehand")w.points.length>=ps&&(E=Oe(w.points));else if(t==="rectangle")E=en(w.start,w.current,j());else if(t==="circular")E=An(w.start,w.current);else if(t==="brush"){const _=w.points[w.points.length-1]??w.current??w.start;if(le.clickSelectRoi&&_&&w.points.length<=1&&l?.(_)){Ce(!0),X();return}const z=Math.max(.25,le.edgeDetail),Z=w.screenPoints.length>0?w.screenPoints:we(w.points),ye=Math.max(.5,le.radius*.04/z),oe=ms(Z,{radius:le.radius,circleSides:Math.max(16,Math.round(32*z)),simplifyTolerance:ye,smoothingPasses:le.edgeSmoothing}),me=[];for(const ve of oe){const Te=G(ve);Te&&me.push(Te)}E=Oe(me)}(t==="freehand"||t==="rectangle"||t==="circular"||t==="brush")&&Ir(E)&&u&&u({tool:t,intent:t==="brush"?"brush":"roi",coordinates:E,bbox:Ar(E),areaPx:Vt(E)}),Ce(!0),X()},[t,u,Ce,X,we,G,j,le.radius,le.edgeDetail,le.edgeSmoothing,le.clickSelectRoi,l]),q=g.useCallback((w,E)=>{const _=ee(w,E);if(!Ir(_))return;const z=w==="stamp-rectangle-4096px"?"patch":"roi",Z={tool:w,intent:z,coordinates:_,bbox:Ar(_),areaPx:Vt(_)};u?.(Z),z==="patch"&&f&&f(Z)},[ee,u,f]),K=g.useCallback((w,E,_)=>{const z=Math.max(Ns,le.radius*.1),Z=z*z,ye=w.screenPoints[w.screenPoints.length-1];if(!ye){w.points.push(E),w.screenPoints.push(_),w.current=E;return}const oe=_[0]-ye[0],me=_[1]-ye[1];oe*oe+me*me>=Z?(w.points.push(E),w.screenPoints.push(_)):(w.points[w.points.length-1]=E,w.screenPoints[w.screenPoints.length-1]=_),w.current=E},[le.radius]),ie=g.useCallback(w=>{if(!B||t==="cursor"||w.button!==0)return;const E=De(w);if(!E)return;const _=Le(w);if(!_)return;if(w.preventDefault(),w.stopPropagation(),Dt(t)){const ye=v.current;ye.stampCenter=E,q(t,E),X();return}const z=H.current;z&&z.setPointerCapture(w.pointerId);const Z=v.current;Z.isDrawing=!0,Z.pointerId=w.pointerId,Z.start=E,Z.current=E,Z.cursor=E,Z.cursorScreen=_,Z.points=t==="freehand"||t==="brush"?[E]:[],Z.screenPoints=t==="brush"?[_]:[],X()},[B,t,De,Le,q,X]),pe=g.useCallback(w=>{if(!B||t==="cursor")return;const E=De(w);if(!E)return;const _=Le(w);if(!_)return;const z=v.current;if(z.cursor=E,z.cursorScreen=_,Dt(t)){z.stampCenter=E,w.preventDefault(),w.stopPropagation(),X();return}if(t==="brush"){if(!z.isDrawing||z.pointerId!==w.pointerId){X();return}w.preventDefault(),w.stopPropagation(),K(z,E,_),X();return}if(!(!z.isDrawing||z.pointerId!==w.pointerId)){if(w.preventDefault(),w.stopPropagation(),t==="freehand"){const Z=a.current,ye=Math.max(1e-6,Z?.getViewState?.().zoom??1),oe=ys/ye,me=oe*oe,ve=z.points[z.points.length-1];if(!ve)z.points.push(E);else{const Te=E[0]-ve[0],Be=E[1]-ve[1];Te*Te+Be*Be>=me&&z.points.push(E)}}else z.current=E;X()}},[B,t,De,Le,X,a,K]),de=g.useCallback(w=>{const E=v.current;if(!E.isDrawing||E.pointerId!==w.pointerId)return;w.preventDefault(),w.stopPropagation();const _=De(w),z=Le(w);_&&(E.cursor=_,z&&(E.cursorScreen=z),t==="brush"?z&&K(E,_,z):E.current=_);const Z=H.current;Z&&Z.hasPointerCapture(w.pointerId)&&Z.releasePointerCapture(w.pointerId),U()},[U,De,Le,t,K]),Ne=g.useCallback(()=>{const w=v.current;let E=!1;t==="brush"&&!w.isDrawing&&w.cursor&&(w.cursor=null,w.cursorScreen=null,E=!0),Dt(t)&&w.stampCenter&&(w.stampCenter=null,E=!0),E&&X()},[t,X]);return g.useEffect(()=>{Pe(),X();const w=H.current;if(!w)return;const E=new ResizeObserver(()=>{Pe(),X()});return E.observe(w),()=>{E.disconnect()}},[Pe,X]),g.useEffect(()=>sn(()=>{Pe(),X()}),[Pe,X]),g.useEffect(()=>{B||Ce(),X()},[B,X,Ce]),g.useEffect(()=>{D.current!==t&&(D.current=t,Ce(),X())},[t,Ce,X]),g.useEffect(()=>{X()},[h,se,N,X]),g.useEffect(()=>{if(F)return F.current=X,()=>{F.current===X&&(F.current=null)}},[F,X]),g.useEffect(()=>{if(!B)return;const w=E=>{E.key==="Escape"&&(Ce(),X())};return window.addEventListener("keydown",w),()=>{window.removeEventListener("keydown",w)}},[B,Ce,X]),Ge.jsx("canvas",{ref:H,className:ge,style:re,onPointerDown:ie,onPointerMove:pe,onPointerUp:de,onPointerCancel:de,onPointerLeave:Ne,onContextMenu:w=>{B&&w.preventDefault()},onWheel:w=>{if(!B)return;const E=H.current,_=a.current,z=typeof _?.handleWheelZoom=="function",Z=typeof _?.zoomBy=="function";if(!E||!z&&!Z)return;w.preventDefault(),w.stopPropagation();const ye=E.getBoundingClientRect(),oe=w.clientX-ye.left,me=w.clientY-ye.top;z?_.handleWheelZoom?.(w.deltaY,oe,me):_.zoomBy?.(w.deltaY<0?Ss:Rs,oe,me),X()}})}const Fi=g.createContext(null),ca=Fi.Provider;function ot(){const t=g.useContext(Fi);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:u,rendererSerial:f,setInteractionLock:c}=ot(),h=t!=="cursor";g.useEffect(()=>(c("drawing-layer",h),()=>c("drawing-layer",!1)),[h,c]);const d=g.useMemo(()=>u.current?.getViewState(),[f]);return l?Ge.jsx(_i,{tool:t,enabled:h,imageWidth:l.width,imageHeight:l.height,imageMpp:l.mpp,imageZoom:l.maxTierZoom,stampOptions:e,brushOptions:n,drawFillColor:r,projectorRef:u,onBrushTap:a,viewStateSignal:d,drawAreaTooltip:i,onDrawComplete:o,onPatchComplete:s}):null}function _r(t,e,n,r){return[Math.min(t,n),Math.min(e,r),Math.max(t,n),Math.max(e,r)]}function Fr(t,e){return!(t[2]<e[0]||t[0]>e[2]||t[3]<e[1]||t[1]>e[3])}class fa{constructor(e=16){S(this,"targetNodeSize");S(this,"items",[]);S(this,"globalBounds",[0,0,0,0]);S(this,"gridSize",1);S(this,"cellWidth",1);S(this,"cellHeight",1);S(this,"buckets",[]);S(this,"visited",new Uint32Array(0));S(this,"querySerial",1);const n=Number.isFinite(e)?Math.floor(e):16;this.targetNodeSize=Math.max(1,n)}load(e){if(!Array.isArray(e)||e.length===0){this.items=[],this.globalBounds=[0,0,0,0],this.gridSize=1,this.cellWidth=1,this.cellHeight=1,this.buckets=[],this.visited=new Uint32Array(0),this.querySerial=1;return}const n=[];let r=1/0,i=1/0,o=-1/0,s=-1/0;for(const f of e){if(!f||!Number.isFinite(f.minX)||!Number.isFinite(f.minY)||!Number.isFinite(f.maxX)||!Number.isFinite(f.maxY))continue;const c=_r(f.minX,f.minY,f.maxX,f.maxY);r=Math.min(r,c[0]),i=Math.min(i,c[1]),o=Math.max(o,c[2]),s=Math.max(s,c[3]),n.push({minX:c[0],minY:c[1],maxX:c[2],maxY:c[3],value:f.value})}if(this.items=n,this.visited=new Uint32Array(n.length),this.querySerial=1,n.length===0||!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(o)||!Number.isFinite(s)){this.globalBounds=[0,0,0,0],this.gridSize=1,this.cellWidth=1,this.cellHeight=1,this.buckets=[];return}this.globalBounds=[r,i,o,s],this.gridSize=Math.max(1,Math.ceil(Math.sqrt(n.length/this.targetNodeSize)));const a=Math.max(0,o-r),l=Math.max(0,s-i);this.cellWidth=a>0?a/this.gridSize:1,this.cellHeight=l>0?l/this.gridSize:1;const u=this.gridSize*this.gridSize;this.buckets=Array.from({length:u},()=>[]);for(let f=0;f<n.length;f+=1){const c=n[f],h=this.toCellX(c.minX),d=this.toCellX(c.maxX),m=this.toCellY(c.minY),p=this.toCellY(c.maxY);for(let x=m;x<=p;x+=1)for(let y=h;y<=d;y+=1)this.buckets[x*this.gridSize+y].push(f)}}search(e){if(this.items.length===0)return[];if(!Array.isArray(e)||e.length<4)return[];const n=_r(e[0],e[1],e[2],e[3]);if(!Fr(n,this.globalBounds))return[];const r=this.toCellX(n[0]),i=this.toCellX(n[2]),o=this.toCellY(n[1]),s=this.toCellY(n[3]),a=this.nextSerial(),l=[];for(let u=o;u<=s;u+=1)for(let f=r;f<=i;f+=1){const c=this.buckets[u*this.gridSize+f];if(!(!c||c.length===0))for(const h of c){if(this.visited[h]===a)continue;this.visited[h]=a;const d=this.items[h];Fr(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 Li(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"),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=`
|
|
103
|
+
}`;class pa{constructor(){S(this,"canvas");S(this,"gl");S(this,"accumProgram");S(this,"colorProgram");S(this,"accumVao");S(this,"colorVao");S(this,"pointBuffer");S(this,"quadBuffer");S(this,"accumTexture");S(this,"gradientTexture");S(this,"framebuffer");S(this,"accumInternalFormat");S(this,"accumTextureFormat");S(this,"accumTextureType");S(this,"uAccumResolution");S(this,"uAccumPointSize");S(this,"uAccumCoreRatio");S(this,"uAccumPointAlpha");S(this,"uColorAccumTexture");S(this,"uColorGradientTexture");S(this,"uColorOpacity");S(this,"uColorCutoff");S(this,"uColorGain");S(this,"uColorResolution");S(this,"uColorGamma");S(this,"uColorBias");S(this,"uColorStretch");S(this,"pointCapacity",0);S(this,"interleavedCapacity",0);S(this,"interleavedBuffer",null);S(this,"gradientKey","");this.canvas=document.createElement("canvas");const e=this.canvas.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,preserveDrawingBuffer:!0,premultipliedAlpha:!0,powerPreference:"high-performance"});if(!e)throw new Error("WebGL2 is not available for heatmap rendering.");this.gl=e;const r=!!e.getExtension("EXT_color_buffer_float");this.accumInternalFormat=r?e.RGBA16F:e.RGBA8,this.accumTextureFormat=e.RGBA,this.accumTextureType=r?e.HALF_FLOAT:e.UNSIGNED_BYTE,this.accumProgram=St(e,ha,da),this.colorProgram=St(e,ma,ga);const i=e.createVertexArray(),o=e.createVertexArray(),s=e.createBuffer(),a=e.createBuffer(),l=e.createTexture(),u=e.createTexture(),f=e.createFramebuffer();if(!i||!o||!s||!a||!l||!u||!f)throw new Error("Failed to allocate heatmap WebGL resources.");this.accumVao=i,this.colorVao=o,this.pointBuffer=s,this.quadBuffer=a,this.accumTexture=l,this.gradientTexture=u,this.framebuffer=f;const c=e.getUniformLocation(this.accumProgram,"uResolution"),h=e.getUniformLocation(this.accumProgram,"uPointSize"),d=e.getUniformLocation(this.accumProgram,"uCoreRatio"),m=e.getUniformLocation(this.accumProgram,"uPointAlpha"),p=e.getUniformLocation(this.colorProgram,"uAccumTexture"),x=e.getUniformLocation(this.colorProgram,"uGradientTexture"),y=e.getUniformLocation(this.colorProgram,"uOpacity"),b=e.getUniformLocation(this.colorProgram,"uCutoff"),M=e.getUniformLocation(this.colorProgram,"uGain"),R=e.getUniformLocation(this.colorProgram,"uGamma"),A=e.getUniformLocation(this.colorProgram,"uBias"),C=e.getUniformLocation(this.colorProgram,"uStretch"),N=e.getUniformLocation(this.colorProgram,"uResolution");if(!c||!h||!d||!m||!p||!x||!y||!b||!M||!R||!A||!C||!N)throw new Error("Failed to resolve heatmap WebGL uniforms.");this.uAccumResolution=c,this.uAccumPointSize=h,this.uAccumCoreRatio=d,this.uAccumPointAlpha=m,this.uColorAccumTexture=p,this.uColorGradientTexture=x,this.uColorOpacity=y,this.uColorCutoff=b,this.uColorGain=M,this.uColorGamma=R,this.uColorBias=A,this.uColorStretch=C,this.uColorResolution=N,e.bindVertexArray(this.accumVao),e.bindBuffer(e.ARRAY_BUFFER,this.pointBuffer),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const k=e.getAttribLocation(this.accumProgram,"aCenter"),O=e.getAttribLocation(this.accumProgram,"aWeight");if(k<0||O<0)throw new Error("Failed to resolve heatmap WebGL attributes.");e.enableVertexAttribArray(k),e.vertexAttribPointer(k,2,e.FLOAT,!1,12,0),e.enableVertexAttribArray(O),e.vertexAttribPointer(O,1,e.FLOAT,!1,12,8),e.bindVertexArray(null),e.bindVertexArray(this.colorVao),e.bindBuffer(e.ARRAY_BUFFER,this.quadBuffer),e.bufferData(e.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,1,1]),e.STATIC_DRAW);const 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,u=this.gl;u.bindTexture(u.TEXTURE_2D,this.gradientTexture),u.texImage2D(u.TEXTURE_2D,0,u.RGBA,256,1,0,u.RGBA,u.UNSIGNED_BYTE,l),u.bindTexture(u.TEXTURE_2D,null),this.gradientKey=n}uploadPointData(e,n,r){const i=this.gl,o=r*3,s=o*4;i.bindBuffer(i.ARRAY_BUFFER,this.pointBuffer),r>this.pointCapacity&&(i.bufferData(i.ARRAY_BUFFER,s,i.DYNAMIC_DRAW),this.pointCapacity=r),o>this.interleavedCapacity&&(this.interleavedCapacity=o,this.interleavedBuffer=new Float32Array(o));const a=this.interleavedBuffer;if(!a)throw new Error("Failed to allocate heatmap upload buffer.");for(let l=0;l<r;l+=1){const u=l*2,f=l*3;a[f]=e[u]??0,a[f+1]=e[u+1]??0,a[f+2]=n[l]??0}i.bufferSubData(i.ARRAY_BUFFER,0,a.subarray(0,o)),i.bindBuffer(i.ARRAY_BUFFER,null)}}const Lr="__open_plant_heatmap_layer__",ya=["#00000000","#3876FF","#4CDDDD","#FFE75C","#FF8434","#FF3434"],ba=3,xa=2,wa=.9,Sa=52e3,Ra="screen",Pn=128,nn=1600,ct=.01,ut=128,Cn=3e3,yt={cutoff:.06,gain:1.45,gamma:1.2,bias:.14,stretch:1};function Di(t){return{cutoff:L(t?.cutoff??yt.cutoff,0,1),gain:L(t?.gain??yt.gain,0,16),gamma:L(t?.gamma??yt.gamma,.35,6),bias:L(t?.bias??yt.bias,0,.92),stretch:L(t?.stretch??yt.stretch,1,4)}}function Ni(t,e){return e.maxTierZoom+Math.log2(Math.max(1e-6,t))}function Bi(t,e){return Math.max(1e-6,2**(t-e.maxTierZoom))}function vn(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,value:r}))}function Tn(t){return!t||t.length===0?"":t.map(e=>`${e.magnification}:${e.value}`).join("|")}function In(t,e,n){if(!e||e.length===0||!Number.isFinite(t)||t<=0)return n;if(e.length===1||t<=e[0].magnification)return e[0].value;for(let a=1;a<e.length;a+=1){const l=e[a-1],u=e[a];if(t>u.magnification)continue;const f=Math.max(1e-6,u.magnification-l.magnification),c=L((t-l.magnification)/f,0,1);return l.value+(u.value-l.value)*c}const r=e[e.length-1],i=e[e.length-2],o=Math.max(1e-6,r.magnification-i.magnification),s=(r.value-i.value)/o;return r.value+(t-r.magnification)*s}function qn(t){const{rawZoom:e,source:n,radius:r,blur:i,radiusMagnificationStops:o,blurMagnificationStops:s}=t,a=Kt(n.mpp??0,e),l=In(a,o,r);let u=i;return s&&s.length>0?u=In(a,s,i):o&&o.length>0&&r>1e-6&&(u=l*(i/Math.max(1e-6,r))),{radius:L(l,ct,ut),blur:L(u,ct,ut)}}function Ea(t){if(t>=1)return 1;const e=1/Math.max(t,1e-6);return 1+Math.log2(e)*.28}function Ma(t,e,n,r){const i=Math.max(1,t,e),o=typeof window>"u"?1:L(window.devicePixelRatio||1,1,2.4),s=r<=.35?1.42:r<=.55?1.26:r<=.8?1.14:1,a=n>16e4?896:n>8e4?1152:n>3e4?1408:nn,l=Pn/i,u=nn/i;return L(a*o*s/i,l,u)}function _n(t){const e=t.heatmapScale??Ma(t.logicalWidth,t.logicalHeight,t.totalPointCount,t.rawZoom),n=Math.max(Pn,Math.min(nn,Math.round(t.logicalWidth*e))),r=Math.max(Pn,Math.min(nn,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=t.radius*s,u=t.blur*s,f=(l+u)/Math.max(1e-6,a*s);return{heatmapScale:e,rasterWidth:n,rasterHeight:r,rasterScaleX:i,rasterScaleY:o,rawZoom:a,kernelRadiusPx:l,blurRadiusPx:u,outerWorldRadius:f}}function $n(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 Nt(t,e){const n=Number.isFinite(t)?Math.round(t*1024):0;return Math.imul(e^n,73244475)>>>0}function Aa(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 Pa(t){return(t>>>0)/4294967295}function zi(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=Nt(o[0],e),e=Nt(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=Nt(a[0],e),e=Nt(a[1],e)}}}return`${t.length}:${e>>>0}`}function Kn(t,e,n){return t.dataRef===e&&t.clipKey===n?!0:e?t.clipKey===n&&t.inputCount===$n(e)&&t.positionsRef===e.positions&&t.weightsRef===e.weights:!1}function Ca(t,e,n,r){const i=$n(t);if(!t||i<=0)return null;let o=new Float32Array(i),s=new Float32Array(i),a=new Float32Array(i),l=0;for(let c=0;c<i;c+=1){const h=t.positions[c*2],d=t.positions[c*2+1];if(!Number.isFinite(h)||!Number.isFinite(d)||e.length>0&&!Mt(h,d,e))continue;const m=t.weights?.[c],p=typeof m=="number"&&Number.isFinite(m)?Math.max(0,m):1;p<=0||(o[l]=h,s[l]=d,a[l]=p,l+=1)}if(l===0)return null;l<i&&(o=o.slice(0,l),s=s.slice(0,l),a=a.slice(0,l));const u=[];for(let c=0;c<l;c+=1){const h=o[c],d=s[c];u.push({minX:h,minY:d,maxX:h,maxY:d,value:c})}const f=Li(64);return f.load(u),{dataRef:t,sourceRef:r,positionsRef:t.positions,weightsRef:t.weights,inputCount:i,clipKey:n,pointCount:l,xs:o,ys:s,ws:a,pointIndex:f}}function Fn(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 ki(t,e){const n=Math.max(Cn,e);return t<=n?1:L(n/Math.max(1,t),1/65536,1)}function Ui(t){return t>=1?1:Math.max(1,Math.round(1/Math.max(1e-6,t)))}function va(t,e){if(e>=1)return!0;const n=Aa(t,1374496523,1757159915);return Pa(n)<=L(e,0,1)}function Oi(t,e,n,r){const i=Math.max(1,n*r),o=Math.PI*e*e,s=Math.max(1,t)*o/i;return L(.085/Math.sqrt(Math.max(1,s)),.012,.075)}function Ta(t,e,n,r){if(!Number.isFinite(t)||t<=0)return e;const i=e>=t?n:r;return t+(e-t)*L(i,0,1)}function Ia(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 Dr(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 _a(t,e,n){if(n.length!==0){t.beginPath();for(let r=0;r<n.length;r+=1){const i=n[r],o=Dr(e,i.outer);o.length>=3&&At(t,o,!0);for(let s=0;s<i.holes.length;s+=1){const a=Dr(e,i.holes[s]);a.length>=3&&At(t,a,!0)}}t.clip("evenodd")}}function Yi(t,e,n,r,i){const o=t.sourceData;return o&&o.sourceRef===i&&Kn(o,e,r)?o:(t.sourceData=Ca(e,n,r,i),t.fixedState=null,t.sourceData)}function Fa(t){const{sourceData:e,renderer:n,source:r,logicalWidth:i,logicalHeight:o,radius:s,blur:a,radiusMagnificationStops:l,blurMagnificationStops:u,radiusMagnificationKey:f,blurMagnificationKey:c,fixedZoom:h,maxRenderedPoints:d}=t,m=Math.max(1e-6,n.getViewState().zoom),p=h??Ni(m,r),x=Bi(p,r),y=qn({rawZoom:x,source:r,radius:s,blur:a,radiusMagnificationStops:l,blurMagnificationStops:u}),b=_n({logicalWidth:i,logicalHeight:o,totalPointCount:e.pointCount,rawZoom:x,radius:y.radius,blur:y.blur}),M=n.getViewBounds(),R=Fn(e,M,b.outerWorldRadius),A=ki(R.length,d),C=Ui(A),N=Math.min(b.rasterScaleX,b.rasterScaleY);return{dataRef:e.dataRef,positionsRef:e.positionsRef,weightsRef:e.weightsRef,inputCount:e.inputCount,clipKey:e.clipKey,baseRadius:s,baseBlur:a,radiusMagnificationKey:f,blurMagnificationKey:c,referenceZoom:p,heatmapScale:b.heatmapScale,kernelWorldRadius:b.kernelRadiusPx/Math.max(1e-6,x*N),blurWorldRadius:b.blurRadiusPx/Math.max(1e-6,x*N),sampleProbability:A,sampleStride:C,pointAlpha:Oi(R.length,b.kernelRadiusPx+b.blurRadiusPx,b.rasterWidth,b.rasterHeight)}}function Nr(t){const{ctx:e,runtime:n,renderer:r,logicalWidth:i,logicalHeight:o,frame:s,sourceData:a,visiblePointIndices:l,sampleProbability:u,pointAlpha:f,gradient:c,opacity:h,density:d,backgroundColor:m,clipPolygons:p}=t,x=Ia(n);if(!x||l.length===0)return 0;const y=Math.min(l.length,Math.max(64,Math.ceil(l.length*Math.min(1,u*1.15))));y>n.webglCapacity&&(n.webglCapacity=y,n.webglPositions=new Float32Array(y*2),n.webglWeights=new Float32Array(y));const b=n.webglPositions,M=n.webglWeights;if(!b||!M)return 0;const R=s.kernelRadiusPx+s.blurRadiusPx,A=Ea(u);let C=0;for(let k=0;k<l.length;k+=1){const O=l[k];if(!va(O,u))continue;const P=a.xs[O],T=a.ys[O];if(!Number.isFinite(P)||!Number.isFinite(T))continue;const W=r.worldToScreen(P,T);if(!Array.isArray(W)||W.length<2)continue;const I=Number(W[0]),Y=Number(W[1]);if(!Number.isFinite(I)||!Number.isFinite(Y))continue;const $=I*s.rasterScaleX,F=Y*s.rasterScaleY;if($<-R||F<-R||$>s.rasterWidth+R||F>s.rasterHeight+R)continue;const ge=C*2;b[ge]=$,b[ge+1]=F,M[C]=Math.max(0,(a.ws[O]??0)*A),C+=1}return C<=0||!x.render({width:s.rasterWidth,height:s.rasterHeight,positions:b,weights:M,count:C,kernelRadiusPx:s.kernelRadiusPx,blurRadiusPx:s.blurRadiusPx,pointAlpha:f,gradient:c,opacity:h,cutoff:d.cutoff,gain:d.gain,gamma:d.gamma,bias:d.bias,stretch:d.stretch})?0:(e.save(),p.length>0&&_a(e,r,p),m&&(e.fillStyle=m,e.fillRect(0,0,i,o)),e.globalAlpha=1,e.imageSmoothingEnabled=!0,e.drawImage(x.canvas,0,0,s.rasterWidth,s.rasterHeight,0,0,i,o),e.restore(),C)}function La(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.pointCount<=0)return null;const u=Math.max(1e-6,r.getViewState().zoom),f=a.densityParams,c=r.getViewBounds();if(a.scaleMode!=="fixed-zoom"){const y=qn({rawZoom:u,source:i,radius:a.radius,blur:a.blur,radiusMagnificationStops:a.radiusMagnificationStops,blurMagnificationStops:a.blurMagnificationStops}),b=_n({logicalWidth:o,logicalHeight:s,totalPointCount:l.pointCount,rawZoom:u,radius:y.radius,blur:y.blur}),M=Fn(l,c,b.outerWorldRadius);if(M.length===0)return{pointCount:l.pointCount,renderTimeMs:0,visiblePointCount:0,renderedBinCount:0,sampleStride:1,maxDensity:0};const R=ki(M.length,a.maxRenderedPoints),A=Ui(R),C=Oi(M.length,b.kernelRadiusPx+b.blurRadiusPx,b.rasterWidth,b.rasterHeight);n.screenPointAlpha=Ta(n.screenPointAlpha,C,.12,.08);const N=Nr({ctx:e,runtime:n,renderer:r,logicalWidth:o,logicalHeight:s,frame:b,sourceData:l,visiblePointIndices:M,sampleProbability:R,pointAlpha:n.screenPointAlpha,gradient:a.gradient,opacity:a.opacity,density:f,backgroundColor:a.backgroundColor,clipPolygons:a.clipPolygons});return{pointCount:l.pointCount,renderTimeMs:0,visiblePointCount:M.length,renderedBinCount:N,sampleStride:A,maxDensity:Math.round(n.screenPointAlpha*255)}}const h=n.fixedState;if(!h)return null;const d=_n({logicalWidth:o,logicalHeight:s,totalPointCount:l.pointCount,rawZoom:u,radius:a.radius,blur:a.blur,heatmapScale:h.heatmapScale}),m=Math.min(d.rasterScaleX,d.rasterScaleY);d.kernelRadiusPx=h.kernelWorldRadius*u*m,d.blurRadiusPx=h.blurWorldRadius*u*m,d.outerWorldRadius=h.kernelWorldRadius+h.blurWorldRadius;const p=Fn(l,c,d.outerWorldRadius);if(p.length===0)return{pointCount:l.pointCount,renderTimeMs:0,visiblePointCount:0,renderedBinCount:0,sampleStride:1,maxDensity:0};const x=Nr({ctx:e,runtime:n,renderer:r,logicalWidth:o,logicalHeight:s,frame:d,sourceData:l,visiblePointIndices:p,sampleProbability:h.sampleProbability,pointAlpha:h.pointAlpha,gradient:a.gradient,opacity:a.opacity,density:f,backgroundColor:a.backgroundColor,clipPolygons:a.clipPolygons});return{pointCount:l.pointCount,renderTimeMs:0,visiblePointCount:p.length,renderedBinCount:x,sampleStride:h.sampleStride,maxDensity:Math.round(h.pointAlpha*255)}}function Xi(t){t.fixedState=null,t.screenPointAlpha=0}function Br(t){t.sourceData=null,Xi(t)}function Da({data:t,visible:e=!0,opacity:n=wa,radius:r=ba,blur:i=xa,radiusByMagnification:o,blurByMagnification:s,gradient:a=ya,backgroundColor:l=null,scaleMode:u=Ra,fixedZoom:f,densityParams:c,clipToRegions:h,zIndex:d=5,maxRenderedPoints:m=Sa,onStats:p}){const{rendererRef:x,source:y,registerDrawCallback:b,unregisterDrawCallback:M,requestOverlayRedraw:R}=ot(),A=g.useMemo(()=>{const Y=(h??[]).map($=>mt($?.coordinates)).filter($=>$!=null);return gt(Y)},[h]),C=g.useMemo(()=>zi(A),[A]),N=g.useMemo(()=>vn(o),[o]),k=g.useMemo(()=>vn(s),[s]),O=g.useMemo(()=>Tn(N),[N]),P=g.useMemo(()=>Tn(k),[k]),T=g.useMemo(()=>Di(c),[c?.cutoff,c?.gain,c?.gamma,c?.bias,c?.stretch]),W=g.useRef({sourceData:null,fixedState:null,screenPointAlpha:0,webgl:void 0,webglWarningIssued:!1,webglPositions:null,webglWeights:null,webglCapacity:0}),I=g.useRef({data:t,visible:e,opacity:n,radius:L(r,ct,ut),blur:L(i,ct,ut),radiusMagnificationStops:N,blurMagnificationStops:k,radiusMagnificationKey:O,blurMagnificationKey:P,gradient:a,backgroundColor:l,scaleMode:u,fixedZoom:f,densityParams:T,clipPolygons:A,clipKey:C,maxRenderedPoints:Math.max(Cn,Math.floor(m)),onStats:p});return I.current={data:t,visible:e,opacity:n,radius:L(r,ct,ut),blur:L(i,ct,ut),radiusMagnificationStops:N,blurMagnificationStops:k,radiusMagnificationKey:O,blurMagnificationKey:P,gradient:a,backgroundColor:l,scaleMode:u,fixedZoom:f,densityParams:T,clipPolygons:A,clipKey:C,maxRenderedPoints:Math.max(Cn,Math.floor(m)),onStats:p},g.useEffect(()=>(b(Lr,d,($,F,ge)=>{const V=I.current,H=W.current,Me=x.current;if(!V.visible||!V.data||!Me||!y)return;const Se=Yi(H,V.data,V.clipPolygons,V.clipKey,y);if(!Se)return;V.scaleMode==="fixed-zoom"&&(!H.fixedState||!Kn(H.fixedState,V.data,V.clipKey)||Math.abs(H.fixedState.baseRadius-V.radius)>1e-6||Math.abs(H.fixedState.baseBlur-V.blur)>1e-6||H.fixedState.radiusMagnificationKey!==V.radiusMagnificationKey||H.fixedState.blurMagnificationKey!==V.blurMagnificationKey||V.fixedZoom!==void 0&&Math.abs(H.fixedState.referenceZoom-V.fixedZoom)>1e-6)?H.fixedState=Fa({sourceData:Se,renderer:Me,source:y,logicalWidth:F,logicalHeight:ge,radius:V.radius,blur:V.blur,radiusMagnificationStops:V.radiusMagnificationStops,blurMagnificationStops:V.blurMagnificationStops,radiusMagnificationKey:V.radiusMagnificationKey,blurMagnificationKey:V.blurMagnificationKey,fixedZoom:V.fixedZoom,maxRenderedPoints:V.maxRenderedPoints}):V.scaleMode!=="fixed-zoom"&&(H.fixedState=null);const v=performance.now(),B=La({ctx:$,runtime:H,renderer:Me,source:y,logicalWidth:F,logicalHeight:ge,state:V});!B||!V.onStats||V.onStats({...B,renderTimeMs:performance.now()-v})}),()=>{M(Lr),Br(W.current),W.current.webgl?.destroy(),W.current.webgl=void 0,W.current.webglPositions=null,W.current.webglWeights=null,W.current.webglCapacity=0}),[b,M,x,y,d]),g.useEffect(()=>{Br(W.current),R()},[t?.positions,t?.weights,t?.count,C,R]),g.useEffect(()=>{Xi(W.current),R()},[r,i,O,P,u,f,T.cutoff,T.gain,T.gamma,T.bias,T.stretch,m,R]),g.useEffect(()=>{R()},[e,n,a,l,R]),null}const Na={buildClipKey:zi,buildHeatmapMagnificationStopsKey:Tn,resolveContinuousZoom:Ni,resolveHeatmapDensityParams:Di,resolveHeatmapKernelParams:qn,resolveHeatmapValueByMagnificationStops:In,normalizeHeatmapMagnificationStops:vn,resolveRawZoomFromContinuousZoom:Bi,resolvePointCount:$n,isSameHeatmapInput:Kn},zr="__overlay_layer__";function Ba({shapes:t}){const{rendererRef:e,rendererSerial:n,source:r,registerDrawCallback:i,unregisterDrawCallback:o,requestOverlayRedraw:s}=ot(),a=g.useCallback(u=>{const f=e.current;if(!f||u.length===0)return[];const c=new Array(u.length);for(let h=0;h<u.length;h+=1){const d=He(f.worldToScreen(u[h][0],u[h][1]));if(!d)return[];c[h]=d}return c},[]),l=g.useRef({shapes:t,worldToScreenPoints:a,source:r});return l.current={shapes:t,worldToScreenPoints:a,source:r},g.useEffect(()=>(i(zr,30,f=>{const{shapes:c,worldToScreenPoints:h,source:d}=l.current;if(!Array.isArray(c)||c.length===0||!d)return;const m=h(Oe([[0,0],[d.width,0],[d.width,d.height],[0,d.height]]));Ii({ctx:f,overlayShapes:c,imageOuterRing:m,worldToScreenPoints:h,baseStrokeStyle:qe})}),()=>o(zr)),[i,o]),g.useEffect(()=>{s()},[n,t,r,s]),null}function za(t){return Array.isArray(t?.classes)?t.classes.map(e=>({classId:String(e?.classId??""),className:String(e?.className??""),classColor:String(e?.classColor??"")})):[]}function kr(t){return String(t??"").replace(/\/+$/,"")}function Wi(t){const e=String(t??"");return e.startsWith("/")?e:`/${e}`}function ka(t){const e=kr(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=kr(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 Ua(t,e){const n=t?.imsInfo??{},r=!!t?.imsInfo,i=Number(n.width??t?.width??0),o=Number(n.height??t?.height??0),s=Number(n.tileSize??t?.tileSize??0),a=Number(n.zoom??t?.zoom??0),l=String(n.path??t?.path??""),u=Number(n.mpp??t?.mpp??0);if(!i||!o||!s||!l)throw new Error("Incomplete image metadata: width/height/tileSize/path required");const f=Wi(l),c=ka(e),h=t?.tileUrlBuilder??(r?(d,m,p)=>`${c}${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(u)&&u>0?u:void 0,tileSize:s,maxTierZoom:Number.isFinite(a)?Math.max(0,Math.floor(a)):0,tilePath:l,tileBaseUrl:e,tileUrlBuilder:h}}function jn(t,e,n,r){if(t.tileUrlBuilder)return t.tileUrlBuilder(e,n,r,t.tilePath,t.tileBaseUrl);const i=Wi(t.tilePath);return`${t.tileBaseUrl}${i}/${e}/${r}_${n}.webp`}function Oa(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 Ye={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 Ur(t,e,n,r){const i=e.length;if(!(i<3)){for(let o=0;o<i;o+=1){const s=e[o],a=e[(o+1)%i],l=Math.hypot(a[0]-s[0],a[1]-s[1]);if(l<1e-6)continue;const u=Math.max(1,Math.round((l+r)/(n+r))),f=u*n+(u-1)*r,c=l/Math.max(1e-6,f),h=n*c,d=r*c;t.beginPath(),t.moveTo(s[0],s[1]),t.lineTo(a[0],a[1]),t.setLineDash([h,d]),t.lineDashOffset=0,t.stroke()}t.setLineDash([]),t.lineDashOffset=0}}function Or(t,e,n=1e-4){return Math.abs(t[0]-e[0])<=n&&Math.abs(t[1]-e[1])<=n}function Yr(t){const e=[];for(const n of t){const r=e[e.length-1];(!r||!Or(r,n))&&e.push(n)}return e.length>1&&Or(e[0],e[e.length-1])&&e.pop(),e}function Xr(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 Wr(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 Vr(t,e,n,r,i){let o=Yr(t);if(o.length<3)return[];const s=[{inside:a=>a[0]>=e,intersect:(a,l)=>Xr(a,l,e)},{inside:a=>a[0]<=r,intersect:(a,l)=>Xr(a,l,r)},{inside:a=>a[1]>=n,intersect:(a,l)=>Wr(a,l,n)},{inside:a=>a[1]<=i,intersect:(a,l)=>Wr(a,l,i)}];for(const a of s){if(o.length===0)return[];const l=o;o=[];let u=l[l.length-1],f=a.inside(u);for(const c of l){const h=a.inside(c);h?(f||o.push(a.intersect(u,c)),o.push(c)):f&&o.push(a.intersect(u,c)),u=c,f=h}o=Yr(o)}return o.length>=3?o:[]}function lt(t,e,n=1){return typeof t!="number"||!Number.isFinite(t)?e:Math.max(n,t)}function Ln(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Ya(t){return t*Math.PI/180}function Xa(t,e,n){const r=Ln(n),i=Ya(r),o=Math.cos(i),s=Math.sin(i),a=t*.5,l=e*.5,u=-o*a-s*l,f=s*a-o*l,c=[[0,0],[t,0],[t,e],[0,e]].map(([x,y])=>[o*x+s*y+u,-s*x+o*y+f]);let h=1/0,d=1/0,m=-1/0,p=-1/0;for(const[x,y]of c)x<h&&(h=x),x>m&&(m=x),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:u,translateY:f}}function Gr(t,e,n,r,i){const o=Xa(t,e,i),s=o.width/o.height,a=n/r;let l,u;return s>a?(l=n,u=n/s):(u=r,l=r*s),{contentX:(n-l)/2,contentY:(r-u)/2,contentWidth:l,contentHeight:u,metrics:o}}function Zr(t,e,n){const{contentX:r,contentY:i,contentWidth:o,contentHeight:s,metrics:a}=n,l=a.cos*t+a.sin*e+a.translateX-a.minX,u=-a.sin*t+a.cos*e+a.translateY-a.minY;return[r+l/a.width*o,i+u/a.height*s]}function Wa(t,e,n,r,i){const{metrics:o}=n,s=t+o.minX-o.translateX,a=e+o.minY-o.translateY,l=s*o.cos-a*o.sin,u=s*o.sin+a*o.cos;return[L(l,0,r),L(u,0,i)]}function Va(t){return[[t[0],t[1]],[t[2],t[1]],[t[2],t[3]],[t[0],t[3]]]}function bt(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 Ga={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 Za({source:t,projectorRef:e,authToken:n="",options:r,invalidateRef:i,className:o,style:s}){const a=g.useRef(null),l=g.useRef(null),u=g.useRef(null),f=g.useRef({active:!1,pointerId:null}),c=g.useRef(null),h=g.useRef(!1),d=lt(r?.width,Ye.width,64),m=lt(r?.height,Ye.height,48),p=lt(r?.margin,Ye.margin,0),x=lt(r?.borderRadius,Ye.borderRadius,0),y=lt(r?.borderWidth,Ye.borderWidth,0),b=Math.max(1,Math.round(lt(r?.maxThumbnailTiles,Ye.maxThumbnailTiles,1))),M=r?.backgroundColor||Ye.backgroundColor,R=r?.borderColor||Ye.borderColor,A=r?.viewportBorderColor||Ye.viewportBorderColor,C=r?.viewportBorderStyle==="stroke"||r?.viewportBorderStyle==="dash"?r.viewportBorderStyle:Ye.viewportBorderStyle,N=r?.viewportFillColor??Ye.viewportFillColor,k=r?.interactive??Ye.interactive,O=r?.showThumbnail??Ye.showThumbnail,P=r?.position||Ye.position,T=r?.onClose,W=r?.closeIcon,I=r?.closeButtonStyle,Y=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:x,overflow:"hidden",zIndex:4,pointerEvents:k?"auto":"none",touchAction:"none",boxShadow:"0 10px 22px rgba(0, 0, 0, 0.3)",...s}},[p,P,d,m,x,k,s]),$=g.useCallback(()=>{const D=a.current;if(!D)return;const v=D.getContext("2d");if(!v)return;const B=d,se=m,ue=Math.max(1,window.devicePixelRatio||1),Q=Math.max(1,Math.round(B*ue)),ce=Math.max(1,Math.round(se*ue));(D.width!==Q||D.height!==ce)&&(D.width=Q,D.height=ce),v.setTransform(1,0,0,1,0,0),v.clearRect(0,0,D.width,D.height),v.setTransform(ue,0,0,ue,0,0),v.fillStyle=M,v.fillRect(0,0,B,se);const ne=e.current,_e=Ln(ne?.getInitialRotationDeg?.()),Re=Gr(t.width,t.height,B,se,_e),{contentX:fe,contentY:xe,contentWidth:te,contentHeight:ae,metrics:he}=Re,le=l.current;le&&(v.save(),v.beginPath(),v.rect(fe,xe,te,ae),v.clip(),v.translate(fe,xe),v.scale(te/he.width,ae/he.height),v.transform(he.cos,-he.sin,he.sin,he.cos,he.translateX-he.minX,he.translateY-he.minY),v.drawImage(le,0,0,t.width,t.height),v.restore()),v.strokeStyle=R,v.lineWidth=y,v.strokeRect(y*.5,y*.5,B-y,se-y);const re=ne?.getViewBounds?.(),Pe=ne?.getViewCorners?.(),we=Array.isArray(Pe)&&Pe.length>=4&&Pe.every(J=>Array.isArray(J)&&J.length>=2&&Number.isFinite(J[0])&&Number.isFinite(J[1]))?Pe:null,G=bt(re)?re:bt(u.current)?u.current:null;bt(re)&&(u.current=re);const j=C==="dash";if(we){const J=we.map(X=>Zr(X[0],X[1],Re)),Ae=Vr(J,fe,xe,fe+te,xe+ae);if(Ae.length>=3){v.beginPath();for(let X=0;X<Ae.length;X+=1)X===0?v.moveTo(Ae[X][0],Ae[X][1]):v.lineTo(Ae[X][0],Ae[X][1]);v.closePath(),v.fillStyle=N,v.fill(),v.strokeStyle=A,v.lineWidth=2.25,j?Ur(v,Ae,4,3):v.stroke();return}}if(!G)return;const be=Va(G).map(J=>Zr(J[0],J[1],Re)),ee=Vr(be,fe,xe,fe+te,xe+ae);if(!(ee.length<3)){v.beginPath();for(let J=0;J<ee.length;J+=1)J===0?v.moveTo(ee[J][0],ee[J][1]):v.lineTo(ee[J][0],ee[J][1]);v.closePath(),v.fillStyle=N,v.fill(),v.strokeStyle=A,v.lineWidth=2.25,j?Ur(v,ee,4,3):v.stroke()}},[d,m,M,R,y,e,t.width,t.height,N,A,C]),F=g.useCallback(()=>{h.current||(h.current=!0,c.current=requestAnimationFrame(()=>{h.current=!1,c.current=null,$()}))},[$]),ge=g.useCallback((D,v)=>{const B=a.current;if(!B)return null;const se=B.getBoundingClientRect();if(!se.width||!se.height)return null;const ue=e.current,Q=Ln(ue?.getInitialRotationDeg?.()),ce=Gr(t.width,t.height,d,m,Q),ne=se.width/d,_e=se.height/m,Re=ce.contentX*ne,fe=ce.contentY*_e,xe=ce.contentWidth*ne,te=ce.contentHeight*_e,ae=L((D-se.left-Re)/xe,0,1),he=L((v-se.top-fe)/te,0,1);return Wa(ae*ce.metrics.width,he*ce.metrics.height,ce,t.width,t.height)},[e,t.width,t.height,d,m]),V=g.useCallback((D,v)=>{const B=e.current;if(!B)return;if(B.setViewCenter){B.setViewCenter(D,v),F();return}const se=B.getViewBounds?.(),ue=bt(se)?se:bt(u.current)?u.current:null;if(!ue)return;const Q=Math.max(1e-6,ue[2]-ue[0]),ce=Math.max(1e-6,ue[3]-ue[1]);B.setViewState({offsetX:D-Q*.5,offsetY:v-ce*.5}),F()},[e,F]),H=g.useCallback(D=>{if(!k||D.button!==0)return;const v=a.current;if(!v)return;const B=ge(D.clientX,D.clientY);B&&(D.preventDefault(),D.stopPropagation(),v.setPointerCapture(D.pointerId),f.current={active:!0,pointerId:D.pointerId},V(B[0],B[1]))},[k,ge,V]),Me=g.useCallback(D=>{const v=f.current;if(!v.active||v.pointerId!==D.pointerId)return;const B=ge(D.clientX,D.clientY);B&&(D.preventDefault(),D.stopPropagation(),V(B[0],B[1]))},[ge,V]),Se=g.useCallback(D=>{const v=f.current;if(!v.active||v.pointerId!==D.pointerId)return;const B=a.current;if(B&&B.hasPointerCapture(D.pointerId))try{B.releasePointerCapture(D.pointerId)}catch{}f.current={active:!1,pointerId:null},F()},[F]);return g.useEffect(()=>{let D=!1;l.current=null,F();const v=0,B=2**(t.maxTierZoom-v),se=Math.ceil(t.width/B),ue=Math.ceil(t.height/B),Q=Math.max(1,Math.ceil(se/t.tileSize)),ce=Math.max(1,Math.ceil(ue/t.tileSize)),ne=Q*ce;if(!O||ne>b)return;const _e=Math.min(d/Math.max(1,t.width),m/Math.max(1,t.height)),Re=document.createElement("canvas");Re.width=Math.max(1,Math.round(t.width*_e)),Re.height=Math.max(1,Math.round(t.height*_e));const fe=Re.getContext("2d");if(!fe)return;fe.fillStyle=M,fe.fillRect(0,0,Re.width,Re.height);const xe=[];for(let te=0;te<ce;te+=1)for(let ae=0;ae<Q;ae+=1){const he=ae*t.tileSize*B,le=te*t.tileSize*B,re=Math.min((ae+1)*t.tileSize,se)*B,Pe=Math.min((te+1)*t.tileSize,ue)*B;xe.push({url:jn(t,v,ae,te),bounds:[he,le,re,Pe]})}return Promise.allSettled(xe.map(async te=>{const ae=Oa(te.url,n),he=await fetch(te.url,{headers:ae?{Authorization:n}:void 0});if(!he.ok)throw new Error(`HTTP ${he.status}`);const le=await createImageBitmap(await he.blob());return{tile:te,bitmap:le}})).then(te=>{if(D){for(const le of te)le.status==="fulfilled"&&le.value.bitmap.close();return}const ae=Re.width/Math.max(1,t.width),he=Re.height/Math.max(1,t.height);for(const le of te){if(le.status!=="fulfilled")continue;const{tile:{bounds:re},bitmap:Pe}=le.value,we=re[0]*ae,G=re[1]*he,j=Math.max(1,(re[2]-re[0])*ae),be=Math.max(1,(re[3]-re[1])*he);fe.drawImage(Pe,we,G,j,be),Pe.close()}l.current=Re,F()}),()=>{D=!0}},[t,n,M,d,m,O,b,F]),g.useEffect(()=>{F()},[F]),g.useEffect(()=>{if(e.current)return;let D=0;const v=()=>{if(e.current){F();return}D=requestAnimationFrame(v)};return D=requestAnimationFrame(v),()=>cancelAnimationFrame(D)},[e,F]),g.useEffect(()=>sn(()=>F()),[F]),g.useEffect(()=>{if(i)return i.current=F,()=>{i.current===F&&(i.current=null)}},[i,F]),g.useEffect(()=>()=>{f.current={active:!1,pointerId:null},c.current!==null&&(cancelAnimationFrame(c.current),c.current=null),h.current=!1},[]),Ge.jsxs("div",{className:o,style:Y,children:[Ge.jsx("canvas",{ref:a,style:{width:"100%",height:"100%",display:"block",borderRadius:"inherit"},onPointerDown:H,onPointerMove:Me,onPointerUp:Se,onPointerCancel:Se,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:I?{...I}:{...Ga},children:W??"×"})]})}const Hr="__patch_layer__",Ha=[];function qa({regions:t,strokeStyle:e}){const{rendererRef:n,registerDrawCallback:r,unregisterDrawCallback:i,requestOverlayRedraw:o}=ot(),s=t??Ha,a=g.useMemo(()=>$e(Si,e),[e]),l=g.useMemo(()=>{const c=[];for(let h=0;h<s.length;h+=1){const d=s[h],m=tn(d.coordinates);m.length!==0&&c.push({region:d,regionIndex:h,regionKey:d.id??h,polygons:m})}return c},[s]),u=g.useCallback(c=>{const h=n.current;if(!h||c.length===0)return[];const d=new Array(c.length);for(let m=0;m<c.length;m+=1){const p=He(h.worldToScreen(c[m][0],c[m][1]));if(!p)return[];d[m]=p}return d},[]),f=g.useRef({prepared:l,resolvedStrokeStyle:a,worldToScreenPoints:u});return f.current={prepared:l,resolvedStrokeStyle:a,worldToScreenPoints:u},g.useEffect(()=>(r(Hr,20,h=>{const{prepared:d,resolvedStrokeStyle:m,worldToScreenPoints:p}=f.current;for(const x of d)for(const y of x.polygons){const b=p(y.outer);b.length>=4&&ke(h,b,m,!0,!1);for(const M of y.holes){const R=p(M);R.length>=4&&ke(h,R,m,!0,!1)}}}),()=>i(Hr)),[r,i]),g.useEffect(()=>{o()},[l,a,o]),null}function Pt(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return null;const n=gt(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=it(t),i=t.positions,o=t.paletteIndices,s=t.fillModes instanceof Uint8Array&&t.fillModes.length>=r?t.fillModes:null,a=t.ids instanceof Uint32Array&&t.ids.length>=r?t.ids:null,l=new Float32Array(r*2),u=new Uint16Array(r),f=s?new Uint8Array(r):null,c=a?new Uint32Array(r):null;let h=0;for(let m=0;m<r;m+=1){const p=i[m*2],x=i[m*2+1];Mt(p,x,n)&&(l[h*2]=p,l[h*2+1]=x,u[h]=o[m],f&&(f[h]=s[m]),c&&(c[h]=a[m]),h+=1)}const d={count:h,positions:l.subarray(0,h*2),paletteIndices:u.subarray(0,h)};return f&&(d.fillModes=f.subarray(0,h)),c&&(d.ids=c.subarray(0,h)),d}function Vi(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return new Uint32Array(0);const n=gt(e??[]);if(n.length===0)return new Uint32Array(0);const r=it(t);if(r===0)return new Uint32Array(0);const i=t.positions,o=new Uint32Array(r);let s=0;for(let a=0;a<r;a+=1){const l=i[a*2],u=i[a*2+1];Mt(l,u,n)&&(o[s]=a,s+=1)}return o.subarray(0,s)}let Bt=null;const $a=`
|
|
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=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
|
|
134
|
+
`;function Ka(){if(typeof navigator>"u")return!1;const t=navigator;return typeof t.gpu=="object"&&t.gpu!==null}function Gi(){if(!Ka())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,mn=globalThis.GPUBufferUsage?.STORAGE??128,kt=globalThis.GPUBufferUsage?.COPY_DST??8,ja=globalThis.GPUBufferUsage?.COPY_SRC??4,Qa=globalThis.GPUBufferUsage?.UNIFORM??64,Ja=globalThis.GPUBufferUsage?.MAP_READ??1,el=globalThis.GPUMapMode?.READ??1;async function tl(){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 nl(){return Bt||(Bt=(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:$a}),entryPoint:"main"}});return{device:n,pipeline:i,bindGroupLayout:r}})(),Bt)}function Ut(t,e){return Math.ceil(t/e)*e}async function Zi(t,e,n){const r=await nl();if(!r)return null;const i=Math.max(0,Math.floor(e)),o=Math.max(0,Math.floor(n.length/4));if(i===0||o===0)return new Uint32Array(0);const s=Math.min(i,Math.floor(t.length/2));if(s===0)return new Uint32Array(0);const a=s*2*Float32Array.BYTES_PER_ELEMENT,l=o*4*Float32Array.BYTES_PER_ELEMENT,u=s*Uint32Array.BYTES_PER_ELEMENT,f=Number(r.device.limits.maxStorageBufferBindingSize);if(a>f||l>f||u>f)return null;const c=r.device.createBuffer({size:Ut(a,4),usage:mn|kt}),h=r.device.createBuffer({size:Ut(l,4),usage:mn|kt}),d=r.device.createBuffer({size:Ut(u,4),usage:mn|ja}),m=r.device.createBuffer({size:16,usage:Qa|kt}),p=r.device.createBuffer({size:Ut(u,4),usage:kt|Ja});let x=!1;try{r.device.queue.writeBuffer(c,0,t.buffer,t.byteOffset,a),r.device.queue.writeBuffer(h,0,n.buffer,n.byteOffset,l),r.device.queue.writeBuffer(m,0,new Uint32Array([s,o,0,0]));const y=r.device.createBindGroup({layout:r.bindGroupLayout,entries:[{binding:0,resource:{buffer:c}},{binding:1,resource:{buffer:h}},{binding:2,resource:{buffer:d}},{binding:3,resource:{buffer:m}}]}),b=r.device.createCommandEncoder(),M=b.beginComputePass();M.setPipeline(r.pipeline),M.setBindGroup(0,y),M.dispatchWorkgroups(Math.ceil(s/256)),M.end(),b.copyBufferToBuffer(d,0,p,0,u),r.device.queue.submit([b.finish()]),await p.mapAsync(el),x=!0;const R=p.getMappedRange();return new Uint32Array(R.slice(0))}finally{if(x)try{p.unmap()}catch{}c.destroy(),h.destroy(),d.destroy(),m.destroy(),p.destroy()}}async function Hi(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=gt(e??[]);if(o.length===0){const R={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return t.fillModes instanceof Uint8Array&&(R.fillModes=new Uint8Array(0)),t.ids instanceof Uint32Array&&(R.ids=new Uint32Array(0)),{data:R,meta:{mode:"hybrid-webgpu",durationMs:Ee()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const s=it(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 R={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(R.fillModes=new Uint8Array(0)),l&&(R.ids=new Uint32Array(0)),{data:R,meta:{mode:"hybrid-webgpu",durationMs:Ee()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const u=new Float32Array(o.length*4);for(let R=0;R<o.length;R+=1){const A=R*4,C=o[R];u[A]=C.minX,u[A+1]=C.minY,u[A+2]=C.maxX,u[A+3]=C.maxY}let f=null,c=!1;try{f=await Zi(t.positions,s,u),c=!!f}catch{f=null,c=!1}if(!f)return{data:Pt(t,e),meta:{mode:"hybrid-webgpu",durationMs:Ee()-r,usedWebGpu:!1,candidateCount:s,bridgedToDraw:!1}};let h=0;for(let R=0;R<s;R+=1)f[R]===1&&(h+=1);const d=new Uint32Array(h);if(h>0){let R=0;for(let A=0;A<s;A+=1)f[A]===1&&(d[R]=A,R+=1)}if(h===0){if(i){const A={count:s,positions:t.positions.subarray(0,s*2),paletteIndices:t.paletteIndices.subarray(0,s),drawIndices:new Uint32Array(0)};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:0,bridgedToDraw:!0}}}const R={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(R.fillModes=new Uint8Array(0)),l&&(R.ids=new Uint32Array(0)),{data:R,meta:{mode:"hybrid-webgpu",durationMs:Ee()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!1}}}if(i){const R=new Uint32Array(h);let A=0;for(let N=0;N<h;N+=1){const k=d[N]??0,O=t.positions[k*2],P=t.positions[k*2+1];Mt(O,P,o)&&(R[A]=k,A+=1)}const C={count:s,positions:t.positions.subarray(0,s*2),paletteIndices:t.paletteIndices.subarray(0,s),drawIndices:R.subarray(0,A)};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:h,bridgedToDraw:!0}}}const m=new Float32Array(h*2),p=new Uint16Array(h),x=a?new Uint8Array(h):null,y=l?new Uint32Array(h):null;let b=0;for(let R=0;R<h;R+=1){const A=d[R]??0,C=t.positions[A*2],N=t.positions[A*2+1];Mt(C,N,o)&&(m[b*2]=C,m[b*2+1]=N,p[b]=t.paletteIndices[A],x&&(x[b]=a[A]),y&&(y[b]=l[A]),b+=1)}const M={count:b,positions:m.subarray(0,b*2),paletteIndices:p.subarray(0,b)};return x&&(M.fillModes=x.subarray(0,b)),y&&(M.ids=y.subarray(0,b)),{data:M,meta:{mode:"hybrid-webgpu",durationMs:Ee()-r,usedWebGpu:!0,candidateCount:h,bridgedToDraw:!1}}}class qi{constructor(e,n){S(this,"worker",null);S(this,"supported",!0);S(this,"requestId",1);S(this,"pendingById",new Map);S(this,"handleMessage",e=>{const n=e.data;if(!n)return;const r=this.pendingById.get(n.id);r&&(this.pendingById.delete(n.id),this.handlers.onResponse(n,r))});S(this,"handleError",()=>{this.supported=!1,this.teardownWorker("worker crashed")});this.createWorker=e,this.handlers=n}beginRequest(e){const n=this.getOrCreateWorker();if(!n)return null;const r=this.requestId++;return this.pendingById.set(r,e),{id:r,worker:n}}cancelRequest(e){const n=this.pendingById.get(e);if(n)return this.pendingById.delete(e),n}terminate(e="worker terminated"){this.teardownWorker(e)}getOrCreateWorker(){if(!this.supported)return null;if(this.worker)return this.worker;try{const e=this.createWorker();return e.addEventListener("message",this.handleMessage),e.addEventListener("error",this.handleError),this.worker=e,e}catch{return this.supported=!1,null}}teardownWorker(e){this.worker&&(this.worker.removeEventListener("message",this.handleMessage),this.worker.removeEventListener("error",this.handleError),this.worker.terminate(),this.worker=null);const n=new Error(e);for(const[,r]of this.pendingById)this.handlers.rejectPending(r,n);this.pendingById.clear()}}const Ct=new qi(()=>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:ht&&ht.tagName.toUpperCase()==="SCRIPT"&&ht.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),{onResponse:(t,e)=>{if(t.type==="roi-clip-failure"){e.reject(new Error(t.error||"worker clip failed"));return}if(t.type==="roi-clip-index-success"){if(e.kind!=="index"){e.reject(new Error("worker response mismatch: expected point data result"));return}const l=Math.max(0,Math.floor(t.count)),u=new Uint32Array(t.indices).subarray(0,l);e.resolve({indices:u,meta:{mode:"worker",durationMs:Number.isFinite(t.durationMs)?t.durationMs: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 rl(){Ct.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=it(t),r=t.positions.slice(0,n*2),i=t.paletteIndices.slice(0,n),o=t.fillModes instanceof Uint8Array&&t.fillModes.length>=n?t.fillModes.slice(0,n):null,s=t.ids instanceof Uint32Array&&t.ids.length>=n?t.ids.slice(0,n):null;return new Promise((a,l)=>{const u=Ee(),f=Ct.beginRequest({kind:"data",resolve:a,reject:l,startMs:u});if(!f){a({data:Pt(t,e),meta:{mode:"sync",durationMs:Ee()-u}});return}const c={type:"roi-clip-request",id:f.id,count:n,positions:r.buffer,paletteIndices:i.buffer,fillModes:o?.buffer,ids:s?.buffer,polygons:e??[]},h=[r.buffer,i.buffer];o&&h.push(o.buffer),s&&h.push(s.buffer);try{f.worker.postMessage(c,h)}catch(d){const m=Ct.cancelRequest(f.id);m?m.reject(d):l(d)}})}async function il(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return{indices:new Uint32Array(0),meta:{mode:"worker",durationMs:0}};const n=it(t),r=t.positions.slice(0,n*2);return new Promise((i,o)=>{const s=Ee(),a=Ct.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(u){const f=Ct.cancelRequest(a.id);f?f.reject(u):o(u)}})}const ol={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};function sl(t,e,n,r,i){const o=g.useRef(0),[s,a]=g.useState(n),l=g.useMemo(()=>r.map(u=>mt(u.coordinates)).filter(u=>u!=null),[r]);return g.useEffect(()=>{const u=++o.current;let f=!1;if(!t)return a(n),()=>{f=!0};if(!n||!n.count||!n.positions||!n.paletteIndices)return a(null),()=>{f=!0};if(l.length===0)return a(ol),i?.({mode:e,durationMs:0,inputCount:n.count,outputCount:0,polygonCount:0}),()=>{f=!0};const c=(d,m)=>{if(f||u!==o.current)return;const p=n.count,x=d?.drawIndices?d.drawIndices.length:d?.count??0;a(d),i?.({mode:m.mode,durationMs:m.durationMs,inputCount:p,outputCount:x,polygonCount:l.length,usedWebGpu:m.usedWebGpu,candidateCount:m.candidateCount,bridgedToDraw:m.bridgedToDraw})};return(async()=>{if(e==="sync"){const d=performance.now(),m=Pt(n,l);c(m,{mode:"sync",durationMs:performance.now()-d});return}if(e==="hybrid-webgpu"){const d=await Hi(n,l,{bridgeToDraw:!0});c(d.data,{mode:d.meta.mode,durationMs:d.meta.durationMs,usedWebGpu:d.meta.usedWebGpu,candidateCount:d.meta.candidateCount,bridgedToDraw:d.meta.bridgedToDraw});return}try{const d=await $i(n,l);c(d.data,{mode:d.meta.mode,durationMs:d.meta.durationMs})}catch{const d=performance.now(),m=Pt(n,l);c(m,{mode:"sync",durationMs:performance.now()-d})}})(),()=>{f=!0}},[t,e,n,l,i]),s}const al=24,ll=1024,cl=4,Gt=-1;function xt(t,e,n){return(t*73856093^e*19349663)>>>0&n}function ul(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))*cl;return Math.max(al,Math.min(ll,o))}function fl(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 hl(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=fl(t.drawIndices??null,r),o=i?i.length:r;if(o===0)return null;const s=ul(t.sourceWidth,t.sourceHeight,o),a=1/s,l=new Int32Array(o),u=new Int32Array(o);let f=0;if(i)for(let I=0;I<o;I+=1){const Y=i[I],$=t.positions[Y*2],F=t.positions[Y*2+1];!Number.isFinite($)||!Number.isFinite(F)||(l[f]=Math.floor($*a),u[f]=Math.floor(F*a),f+=1)}else for(let I=0;I<r;I+=1){const Y=t.positions[I*2],$=t.positions[I*2+1];!Number.isFinite(Y)||!Number.isFinite($)||(l[f]=Math.floor(Y*a),u[f]=Math.floor($*a),f+=1)}if(f===0)return null;let c=Math.min(f,Math.max(64,f>>>3));(!Number.isFinite(c)||c<=0)&&(c=f);let h=1;for(;h<c*2;)h<<=1;let d=h-1,m=new Int32Array(h*2),p=new Int32Array(h);m.fill(2147483647);let x=0;const y=new Int32Array(f);for(let I=0;I<f;I+=1){const Y=l[I],$=u[I];let F=xt(Y,$,d);for(;;){const ge=m[F*2];if(ge===2147483647){if(m[F*2]=Y,m[F*2+1]=$,p[F]=1,y[I]=F,x+=1,x*4>h*3){const V=h;h<<=1,d=h-1;const H=new Int32Array(h*2),Me=new Int32Array(h);H.fill(2147483647);for(let Se=0;Se<V;Se+=1){if(m[Se*2]===2147483647)continue;const D=m[Se*2],v=m[Se*2+1];let B=xt(D,v,d);for(;H[B*2]!==2147483647;)B=B+1&d;H[B*2]=D,H[B*2+1]=v,Me[B]=p[Se]}for(m=H,p=Me,F=xt(Y,$,d);m[F*2]!==Y||m[F*2+1]!==$;)F=F+1&d;y[I]=F}break}if(ge===Y&&m[F*2+1]===$){p[F]+=1,y[I]=F;break}F=F+1&d}}const b=new Int32Array(x*2),M=new Uint32Array(x),R=new Uint32Array(x),A=new Int32Array(h);A.fill(Gt);let C=0,N=0;for(let I=0;I<h;I+=1)m[I*2]!==2147483647&&(b[C*2]=m[I*2],b[C*2+1]=m[I*2+1],M[C]=N,R[C]=p[I],A[I]=C,N+=p[I],C+=1);const k=new Uint32Array(f),O=new Uint32Array(x);if(O.set(M),i)for(let I=0;I<f;I+=1){const Y=A[y[I]];k[O[Y]]=i[I],O[Y]+=1}else{let I=0;for(let Y=0;Y<r;Y+=1){const $=t.positions[Y*2],F=t.positions[Y*2+1];if(!Number.isFinite($)||!Number.isFinite(F))continue;const ge=A[y[I]];k[O[ge]]=Y,O[ge]+=1,I+=1}}let P=1;for(;P<x*2;)P<<=1;const T=P-1,W=new Int32Array(P);W.fill(Gt);for(let I=0;I<x;I+=1){const Y=b[I*2],$=b[I*2+1];let F=xt(Y,$,T);for(;W[F]!==Gt;)F=F+1&T;W[F]=I}return{cellSize:s,safeCount:r,cellCount:x,hashCapacity:P,hashTable:W,cellKeys:b,cellOffsets:M,cellLengths:R,pointIndices:k}}function Ki(t,e,n){const{hashTable:r,cellKeys:i,hashMask:o}=t;let s=xt(e,n,o);for(;;){const a=r[s];if(a===Gt)return-1;if(i[a*2]===e&&i[a*2+1]===n)return a;s=s+1&o}}function dl(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 Dn=new qi(()=>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:ht&&ht.tagName.toUpperCase()==="SCRIPT"&&ht.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(dl(t,e.pointData))},rejectPending:(t,e)=>{t.reject(e)}});function ml(){Dn.terminate("worker terminated")}function gl(t,e){const n=it(t);if(n<=0)return null;const r=t.positions.subarray(0,n*2),i=hl({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=it(t);return n<=0?null:new Promise((r,i)=>{const o={resolve:r,reject:i,pointData:t},s=Dn.beginRequest(o);if(!s||!s.worker){r(gl(t,e));return}const a=t.positions.slice(0,n*2),l=t.drawIndices instanceof Uint32Array&&t.drawIndices.length>0?t.drawIndices.slice():void 0,u={type:"point-hit-index-request",id:s.id,count:n,positions:a.buffer,drawIndices:l?.buffer,sourceWidth:e?.width??0,sourceHeight:e?.height??0},f=[a.buffer];l&&f.push(l.buffer);try{s.worker.postMessage(u,f)}catch(c){const h=Dn.cancelRequest(s.id);h?h.reject(c):i(c)}})}const pl=.65,yl=4;function bl(t,e,n,r,i,o,s,a){const l=!!(n||r||i),[u,f]=g.useState(null),c=g.useRef(null),h=g.useRef(null);g.useEffect(()=>{if(!l||!t){f(null);return}let x=!1;return ji(t,e).then(y=>{x||f(y)}),()=>{x=!0}},[l,t,e]);const d=g.useCallback(x=>{const y=s.current;if(!y||!u)return null;const b=Number(x[0]),M=Number(x[1]);if(!Number.isFinite(b)||!Number.isFinite(M))return null;const R=Math.max(1e-6,y.getViewState().zoom),A=y.getPointSize(a),N=Math.max(yl,A*pl)/R;if(!Number.isFinite(N)||N<=0)return null;const{cellSize:k,cellOffsets:O,cellLengths:P,pointIndices:T,positions:W,safeCount:I}=u,Y=Math.floor(b/k),$=Math.floor(M/k),F=Math.max(1,Math.ceil(N/k)),ge=N*N;let V=-1,H=ge,Me=0,Se=0;for(let v=Y-F;v<=Y+F;v+=1)for(let B=$-F;B<=$+F;B+=1){const se=Ki(u,v,B);if(se<0)continue;const ue=O[se],Q=ue+P[se];for(let ce=ue;ce<Q;ce+=1){const ne=T[ce];if(ne>=I)continue;const _e=W[ne*2],Re=W[ne*2+1],fe=_e-b,xe=Re-M,te=fe*fe+xe*xe;te>H||(H=te,V=ne,Me=_e,Se=Re)}}if(V<0)return null;const D=u.ids?Number(u.ids[V]):null;return{index:V,id:D,coordinate:[b,M],pointCoordinate:[Me,Se]}},[a,u]),m=g.useCallback((x,y)=>{if(!n)return;const b=x?.index??null,M=x?.id??null;c.current===b&&h.current===M||(c.current=b,h.current=M,n({index:b,id:M,coordinate:y,pointCoordinate:x?.pointCoordinate??null}))},[n]),p=g.useCallback((x,y)=>{if(!r)return;const b=d(x);b&&r({...b,button:y})},[r,d]);return g.useEffect(()=>{if(i)return i.current=d,()=>{i.current===d&&(i.current=null)}},[i,d]),g.useEffect(()=>{const x=c.current;x!==null&&(u&&x<u.safeCount||(c.current=null,h.current=null,n?.({index:null,id:null,coordinate:null,pointCoordinate:null})))},[u,n]),g.useEffect(()=>{},[o,n]),{getCellByCoordinates:d,emitPointHover:m,emitPointClick:p}}let xl=0;const wl=g.forwardRef(function({data:e=null,palette:n=null,sizeByZoom:r,sizeByMagnification:i,weightByMagnification:o,opacity:s,strokeScale:a,innerFillOpacity:l,innerFillColor:u,clipEnabled:f=!1,clipToRegions:c,clipMode:h="worker",onClipStats:d,onHover:m,onClick:p,dashed:x},y){const{rendererRef:b,rendererSerial:M,source:R}=ot(),A=g.useRef(null),C=g.useRef(`__point_layer__${xl++}`),k=sl(f,h,e,c??Sl,d),{getCellByCoordinates:O}=bl(k,R,m,p,A,"cursor",b,C.current);return g.useImperativeHandle(y,()=>({queryAt:O}),[O]),g.useEffect(()=>{const P=b.current;if(!P)return;const T=C.current;return P.registerPointLayer(T),()=>{P.unregisterPointLayer(T)}},[b,M]),g.useEffect(()=>{const P=b.current;P&&P.setPointPalette(n,C.current)},[M,n,b]),g.useEffect(()=>{const P=b.current;P&&P.setPointLineDash(x,C.current)},[M,x,b]),g.useEffect(()=>{const P=b.current;P&&P.setPointSizeByZoom(r,C.current)},[M,r,b]),g.useEffect(()=>{const P=b.current;P&&P.setPointSizeByMagnification(i,C.current)},[M,i,b]),g.useEffect(()=>{const P=b.current;P&&P.setPointWeightByMagnification(o,C.current)},[M,o,b]),g.useEffect(()=>{const P=b.current;!P||s===void 0||P.setPointOpacity(s,C.current)},[M,s,b]),g.useEffect(()=>{const P=b.current;!P||a===void 0||P.setPointStrokeScale(a,C.current)},[M,a,b]),g.useEffect(()=>{const P=b.current;!P||l===void 0||P.setPointInnerFillOpacity(l,C.current)},[M,l,b]),g.useEffect(()=>{const P=b.current;P&&P.setPointInnerFillColor(u,C.current)},[M,u,b]),g.useEffect(()=>{const P=b.current;P&&P.setPointData(k,C.current)},[M,k,b]),null}),Sl=[],Rl=180,qr=20;function El(t){const e=L(t,0,1);return e*e*(3-2*e)}function Ml(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(c=>{const h=L(c,0,qr);Math.abs(o.current-h)<1e-4||(o.current=h,i(h))},[]),l=g.useCallback(()=>{const c=s.current;c.rafId!==null&&(cancelAnimationFrame(c.rafId),c.rafId=null)},[]),u=g.useCallback(c=>{const h=L(c,0,qr),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=x=>{const y=s.current,b=Math.max(0,x-y.startMs),M=L(b/Rl,0,1),R=El(M),A=y.from+(y.to-y.from)*R;if(a(A),n.current?.(),M>=1){y.rafId=null,a(y.to);return}y.rafId=requestAnimationFrame(p)};d.rafId=requestAnimationFrame(p)},[a,l]),f=g.useCallback(c=>{const h=e.current;if(!h||typeof c!="number"||!Number.isFinite(c)){u(0);return}const d=Hn(t,c,h.getZoomRange(),h.getRegionLabelAutoLiftCapZoom());u(d)},[t,u]);return g.useEffect(()=>()=>{l()},[l]),{regionLabelAutoLiftOffsetPx:r,syncRegionLabelAutoLiftTarget:f,cancelRegionLabelAutoLiftAnimation:l,applyRegionLabelAutoLiftOffset:a}}const Al=6;function Nn(t,e){return t.id??e}function Pl(t,e,n,r,i,o){const s=i-n,a=o-r,l=s*s+a*a;if(l<=1e-12){const m=t-n,p=e-r;return m*m+p*p}const u=L(((t-n)*s+(e-r)*a)/l,0,1),f=n+s*u,c=r+a*u,h=t-f,d=e-c;return h*h+d*d}function $r(t,e,n,r){for(let i=1;i<n.length;i+=1){const o=n[i-1],s=n[i];if(Pl(t,e,o[0],o[1],s[0],s[1])<=r)return!0}return!1}function Cl(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($r(t,e,n.outer,i))return!0;for(const o of n.holes)if($r(t,e,o,i))return!0;return!1}function vl(t,e,n,r,i,o,s,a){if(!t.label)return!1;const l=Vn(t.polygons,R=>{const A=[];for(let C=0;C<R.length;C+=1){const N=Yn(n.worldToScreen(R[C][0],R[C][1]));if(!N)return[];A.push(N)}return A},r);if(!l)return!1;const f=Wn(t.label,i)+i.paddingX*2,c=i.fontSize+i.paddingY*2,h=l[0],d=l[1]-i.offsetY,m=a?L(h,f*.5+1,o-f*.5-1):h,p=a?L(d,c*.5+1,s-c*.5-1):d,x=m-f*.5,y=m+f*.5,b=p-c*.5,M=p+c*.5;return e[0]>=x&&e[0]<=y&&e[1]>=b&&e[1]<=M}function Tl(t){const e=[];for(let n=0;n<t.length;n+=1){const r=t[n],i=gt([mt(r?.coordinates)]);if(i.length===0)continue;const o=typeof r?.label=="string"?r.label.trim():"";e.push({region:r,regionIndex:n,regionId:Nn(r,n),polygons:i,label:o})}return e}function Kr(t,e,n,r,i,o,s,a,l,u,f=!0){const c=t[0],h=t[1],d=Math.max(1e-6,r.getViewState().zoom),m=Math.max(0,a),p=Al/d;for(let x=n.length-1;x>=0;x-=1){const y=n[x];for(const M of y.polygons)if(Cl(c,h,M,p))return{region:y.region,regionIndex:y.regionIndex,regionId:y.regionId};let b=Zn(o,s?.({region:y.region,regionId:y.regionId,regionIndex:y.regionIndex,zoom:d}));if(m>0&&(b={...b,offsetY:b.offsetY+m}),!!vl(y,e,r,i,b,l,u,f))return{region:y.region,regionIndex:y.regionIndex,regionId:y.regionId}}return null}const jr=[],Il=[];let _l=0;function Fl(t){return{color:Ri,width:Ei,lineDash:rt,lineJoin:t.lineJoin,lineCap:t.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function Ll({regions:t,polygons:e,strokeStyle:n,hoverStrokeStyle:r,activeStrokeStyle:i,resolveStrokeStyle:o,labelStyle:s,labelAnchor:a="top-center",autoLiftLabelAtMaxZoom:l=!1,clampLabelToViewport:u=!0,hoveredRegionId:f,activeRegionId:c,interactive:h=!0,onActiveChange:d,onHover:m,onClick:p}){const{rendererRef:x,rendererSerial:y,canvasRef:b,containerRef:M,registerDrawCallback:R,unregisterDrawCallback:A,requestOverlayRedraw:C,drawInvalidateRef:N,registerViewStateListener:k,screenToWorld:O,worldToScreen:P,isInteractionLocked:T}=ot(),W=t??jr,I=e??Il,Y=g.useMemo(()=>W.length>0?W:I.length===0?jr:I.map((G,j)=>({id:j,coordinates:G})),[W,I]),[$,F]=g.useState(()=>f??null),[ge,V]=g.useState(()=>c??null),H=f!==void 0,Me=c!==void 0,Se=H?f??null:$,D=Me?c??null:ge,v=g.useRef(f??null),B=g.useRef(null),se=g.useRef(null);if(B.current===null||se.current===null){const G=_l++;B.current=`__region_layer__${G}`,se.current=`__region_label__${G}`}g.useEffect(()=>{Me&&V(c??null)},[Me,c]),g.useEffect(()=>{if(!H)return;const G=f??null;v.current=G,F(G)},[H,f]);const ue=g.useCallback(G=>{String(D)!==String(G)&&(Me||V(G),d?.(G))},[D,Me,d]),{regionLabelAutoLiftOffsetPx:Q,syncRegionLabelAutoLiftTarget:ce}=Ml(l,x,N),ne=g.useMemo(()=>Xn(n),[n]),_e=g.useMemo(()=>$e(ne,r),[ne,r]),Re=g.useMemo(()=>$e(ne,i),[ne,i]),{staticLabelStyle:fe,labelStyleResolver:xe}=g.useMemo(()=>typeof s=="function"?{staticLabelStyle:void 0,labelStyleResolver:s}:{staticLabelStyle:s,labelStyleResolver:void 0},[s]),te=g.useMemo(()=>Gn(fe),[fe]),ae=g.useMemo(()=>{const G=[];for(let j=0;j<Y.length;j+=1){const be=Y[j],ee=tn(be.coordinates);ee.length!==0&&G.push({region:be,regionIndex:j,regionKey:be.id??j,polygons:ee})}return G},[Y]),he=g.useMemo(()=>Tl(Y),[Y]);g.useEffect(()=>{const G=x.current;if(G)return ce(G.getViewState().zoom),k(j=>{ce(j.zoom)})},[y,k,ce]),g.useEffect(()=>{!(D===null?!0:Y.some((ee,J)=>String(Nn(ee,J))===String(D)))&&D!==null&&ue(null);const j=v.current;!(j===null?!0:Y.some((ee,J)=>String(Nn(ee,J))===String(j)))&&j!==null&&(v.current=null,H||F(null),m?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[Y,D,H,m,ue]);const le=g.useCallback(G=>{const j=x.current;if(!j||G.length===0)return[];const be=new Array(G.length);for(let ee=0;ee<G.length;ee+=1){const J=He(j.worldToScreen(G[ee][0],G[ee][1]));if(!J)return[];be[ee]=J}return be},[]),re=g.useRef({preparedRegions:ae,hoveredRegionId:Se,activeRegionId:D,resolvedStrokeStyle:ne,resolvedHoverStrokeStyle:_e,resolvedActiveStrokeStyle:Re,resolveStrokeStyleProp:o,worldToScreenPoints:le});re.current={preparedRegions:ae,hoveredRegionId:Se,activeRegionId:D,resolvedStrokeStyle:ne,resolvedHoverStrokeStyle:_e,resolvedActiveStrokeStyle:Re,resolveStrokeStyleProp:o,worldToScreenPoints:le},g.useEffect(()=>{const G=be=>{const{preparedRegions:ee,hoveredRegionId:J,activeRegionId:Ae,resolvedStrokeStyle:X,resolvedHoverStrokeStyle:Ce,resolvedActiveStrokeStyle:De,resolveStrokeStyleProp:Le,worldToScreenPoints:U}=re.current;for(const q of ee){const{region:K,polygons:ie,regionIndex:pe,regionKey:de}=q,Ne=Jt(Ae,de)?"active":Jt(J,de)?"hover":"default";let w=Ne==="active"?De:Ne==="hover"?Ce:X;if(Le){const _=Le({region:K,regionId:de,regionIndex:pe,state:Ne});w=$e(w,_||void 0)}const E=Ne==="default"?null:Fl(w);for(const _ of ie){const z=U(_.outer);z.length>=4&&(E&&ke(be,z,E,!0,!1),ke(be,z,w,!0,!1));for(const Z of _.holes){const ye=U(Z);ye.length>=4&&(E&&ke(be,ye,E,!0,!1),ke(be,ye,w,!0,!1))}}}},j=B.current;if(j)return R(j,10,G),()=>A(j)},[R,A]);const Pe=g.useRef({preparedRegions:ae,resolvedLabelStyle:te,labelStyleResolver:xe,labelAnchor:a,autoLiftLabelAtMaxZoom:l,clampLabelToViewport:u,regionLabelAutoLiftOffsetPx:Q,rendererRef:x});Pe.current={preparedRegions:ae,resolvedLabelStyle:te,labelStyleResolver:xe,labelAnchor:a,autoLiftLabelAtMaxZoom:l,clampLabelToViewport:u,regionLabelAutoLiftOffsetPx:Q,rendererRef:x},g.useEffect(()=>{const G=(be,ee,J)=>{const{preparedRegions:Ae,resolvedLabelStyle:X,labelStyleResolver:Ce,labelAnchor:De,autoLiftLabelAtMaxZoom:Le,clampLabelToViewport:U,regionLabelAutoLiftOffsetPx:q,rendererRef:K}=Pe.current;if(Ae.length===0)return;const ie=Math.max(1e-6,K.current?.getViewState?.().zoom??1),pe=typeof q=="number"&&Number.isFinite(q)?Math.max(0,q):Hn(Le,ie,K.current?.getZoomRange?.(),K.current?.getRegionLabelAutoLiftCapZoom?.());for(const de of Ae){if(!de.region.label)continue;const Ne=Vn(de.polygons,E=>{const _=K.current;if(!_)return[];const z=[];for(let Z=0;Z<E.length;Z+=1){const ye=He(_.worldToScreen(E[Z][0],E[Z][1]));if(!ye)return[];z.push(ye)}return z},De);if(!Ne)continue;let w=Zn(X,Ce?.({region:de.region,regionId:de.regionKey,regionIndex:de.regionIndex,zoom:ie}));pe>0&&(w={...w,offsetY:w.offsetY+pe}),Ti(be,de.region.label,Ne,ee,J,w,U)}},j=se.current;if(j)return R(j,50,G),()=>A(j)},[R,A]),g.useEffect(()=>{C()},[ae,Se,D,ne,te,Q,C]);const we=g.useRef({preparedRegionHits:he,labelAnchor:a,resolvedLabelStyle:te,labelStyleResolver:xe,regionLabelAutoLiftOffsetPx:Q,clampLabelToViewport:u,onHover:m,onClick:p,commitActive:ue});return we.current={preparedRegionHits:he,labelAnchor:a,resolvedLabelStyle:te,labelStyleResolver:xe,regionLabelAutoLiftOffsetPx:Q,clampLabelToViewport:u,onHover:m,onClick:p,commitActive:ue},g.useEffect(()=>{if(!h)return;const G=M.current;if(!G)return;const j=J=>{if(T())return;const Ae=x.current;if(!Ae)return;const{preparedRegionHits:X,labelAnchor:Ce,resolvedLabelStyle:De,labelStyleResolver:Le,regionLabelAutoLiftOffsetPx:U,clampLabelToViewport:q,onHover:K}=we.current,ie=O(J.clientX,J.clientY);if(!ie)return;let pe=null,de=null;if(X.length>0){const w=P(ie[0],ie[1]);if(w){const E=b.current?.getBoundingClientRect();de=Kr(ie,w,X,Ae,Ce,De,Le,typeof U=="number"?U:0,E?.width??0,E?.height??0,q),pe=de?.regionId??null}}const Ne=v.current;String(Ne)!==String(pe)&&(v.current=pe,H||F(pe),K?.({region:de?.region??null,regionId:pe,regionIndex:de?.regionIndex??-1,coordinate:ie}),C())},be=J=>{if(T())return;const Ae=x.current;if(!Ae)return;const{preparedRegionHits:X,labelAnchor:Ce,resolvedLabelStyle:De,labelStyleResolver:Le,regionLabelAutoLiftOffsetPx:U,clampLabelToViewport:q,onClick:K,commitActive:ie}=we.current;if(X.length===0)return;const pe=O(J.clientX,J.clientY);if(!pe)return;const de=P(pe[0],pe[1]);if(!de)return;const Ne=b.current?.getBoundingClientRect(),w=Kr(pe,de,X,Ae,Ce,De,Le,typeof U=="number"?U:0,Ne?.width??0,Ne?.height??0,q),E=w?.regionId??null;ie(E),w&&K&&K({region:w.region,regionId:w.regionId,regionIndex:w.regionIndex,coordinate:pe})},ee=()=>{v.current!==null&&(v.current=null,H||F(null),we.current.onHover?.({region:null,regionId:null,regionIndex:-1,coordinate:null}),C())};return G.addEventListener("pointermove",j),G.addEventListener("click",be),G.addEventListener("pointerleave",ee),()=>{G.removeEventListener("pointermove",j),G.removeEventListener("click",be),G.removeEventListener("pointerleave",ee)}},[M,x,b,h,H,O,P,T,C]),null}function Dl({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 u=s.current;if(!u)return;const f=new mi({canvas:u,imageWidth:t,imageHeight:e,initialViewState:r});return a.current=f,f.setTiles(n),()=>{f.destroy(),a.current=null}},[t,e]),g.useEffect(()=>{const u=a.current;u&&u.setTiles(n)},[n]),g.useEffect(()=>{const u=a.current;!u||!r||u.setViewState(r)},[r]),Ge.jsx("canvas",{ref:s,className:i,style:l})}function Nl(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){S(this,"maxConcurrency");S(this,"maxRetries");S(this,"retryBaseDelayMs");S(this,"retryMaxDelayMs");S(this,"onTileLoad");S(this,"onTileError");S(this,"onStateChange");S(this,"authToken");S(this,"destroyed",!1);S(this,"queue",[]);S(this,"queuedByKey",new Map);S(this,"inflight",new Map);S(this,"visibleKeys",new Set);S(this,"timerId",null);S(this,"abortedCount",0);S(this,"retryCount",0);S(this,"failedCount",0);this.maxConcurrency=Math.max(1,Math.floor(e.maxConcurrency??12)),this.maxRetries=Math.max(0,Math.floor(e.maxRetries??2)),this.retryBaseDelayMs=Math.max(10,Math.floor(e.retryBaseDelayMs??120)),this.retryMaxDelayMs=Math.max(this.retryBaseDelayMs,Math.floor(e.retryMaxDelayMs??1200)),this.authToken=e.authToken??"",this.onTileLoad=e.onTileLoad,this.onTileError=e.onTileError,this.onStateChange=e.onStateChange}setAuthToken(e){this.authToken=String(e??"")}schedule(e){if(this.destroyed)return;const n=new Set;for(const r of e)n.add(r.key);this.visibleKeys=n,this.dropInvisibleQueued(n),this.abortInvisibleInflight(n);for(const r of e){if(this.inflight.has(r.key)){const s=this.inflight.get(r.key);s&&(s.tile=r);continue}const i=this.queuedByKey.get(r.key);if(i){i.tile=r;continue}const o={tile:r,attempt:0,readyAt: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=Nl(e.tile.url,this.authToken);fetch(e.tile.url,{signal:n.signal,headers:i?{Authorization:this.authToken}:void 0}).then(o=>{if(!o.ok)throw new Error(`HTTP ${o.status}`);return o.blob()}).then(o=>createImageBitmap(o)).then(o=>{if(this.destroyed||n.signal.aborted){o.close();return}if(!this.visibleKeys.has(e.tile.key)){o.close();return}this.onTileLoad(e.tile,o)}).catch(o=>{if(n.signal.aborted||this.destroyed)return;if(e.attempt<this.maxRetries&&this.visibleKeys.has(e.tile.key)){this.retryCount+=1;const a=e.attempt+1,l=this.getRetryDelay(a),u={tile:e.tile,attempt:a,readyAt:Ee()+l},f=this.queuedByKey.get(e.tile.key);f?(f.tile=u.tile,f.readyAt=Math.min(f.readyAt,u.readyAt),f.attempt=Math.max(f.attempt,u.attempt)):(this.queue.push(u),this.queuedByKey.set(u.tile.key,u)),this.sortQueue();return}this.failedCount+=1,this.onTileError?.(e.tile,o,e.attempt+1)}).finally(()=>{this.inflight.delete(e.tile.key),this.pump(),this.emitStateChange()})}getRetryDelay(e){const n=Math.max(0,e-1),r=Math.min(this.retryMaxDelayMs,this.retryBaseDelayMs*2**n),i=.85+Math.random()*.3;return Math.round(r*i)}clearPumpTimer(){this.timerId!==null&&(globalThis.clearTimeout(this.timerId),this.timerId=null)}emitStateChange(){this.onStateChange?.(this.getSnapshot())}}function Bl(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 zl(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 kl(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 Bn=.35,dt=.5,Qr=256,zn=[{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}],Ul=.1,Ol=5,Yl=0,Xl=1,Wl=0,Vl=1,Gl=-100,Zl=100,Hl=2e3,Ji=[255,255,255];function an(t){return t*Math.PI/180}function Ot(t,e){return!t||!e?t===e:t.buffer===e.buffer&&t.byteOffset===e.byteOffset&&t.byteLength===e.byteLength}function rn(t){return t.map(e=>({zoom:e.zoom,size:e.size}))}function ql(t){return!t||t.length===0?null:t.map(e=>({magnification:e.magnification,size:e.size}))}function $l(t){return!t||t.length===0?null:t.map(e=>({magnification:e.magnification,weight:e.weight}))}function Jr(t){if(!t)return rn(zn);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?rn(zn):Array.from(e.entries()).sort((n,r)=>n[0]-r[0]).map(([n,r])=>({zoom:n,size:r}))}function ei(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 ti(t){if(!t)return null;const e=new Map;for(const[n,r]of Object.entries(t)){const i=Number(n),o=Zt(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 Kl(t,e){if(t===e)return!0;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1)if(t[n].zoom!==e[n].zoom||t[n].size!==e[n].size)return!1;return!0}function jl(t,e){if(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 Ql(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 Jl(t,e){if(!Number.isFinite(t))return e[0]?.size??dt;if(e.length===0)return dt;if(e.length===1||t<=e[0].zoom)return e[0].size;for(let s=1;s<e.length;s+=1){const a=e[s-1],l=e[s];if(t>l.zoom)continue;const u=Math.max(1e-6,l.zoom-a.zoom),f=L((t-a.zoom)/u,0,1);return a.size+(l.size-a.size)*f}const n=e[e.length-1],r=e[e.length-2],i=Math.max(1e-6,n.zoom-r.zoom),o=(n.size-r.size)/i;return n.size+(t-n.zoom)*o}function ec(t,e){if(!Number.isFinite(t))return e[0]?.size??dt;if(e.length===0)return dt;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 u=Math.max(1e-6,l.magnification-a.magnification),f=L((t-a.magnification)/u,0,1);return a.size+(l.size-a.size)*f}const n=e[e.length-1],r=e[e.length-2],i=Math.max(1e-6,n.magnification-r.magnification),o=(n.size-r.size)/i;return n.size+(t-n.magnification)*o}function tc(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 u=Math.max(1e-6,l.magnification-a.magnification),f=L((t-a.magnification)/u,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 Zt(t){return typeof t!="number"||!Number.isFinite(t)?1:L(t,Ul,Ol)}function ni(t){return typeof t!="number"||!Number.isFinite(t)?1:L(t,Yl,Xl)}function nc(t){return t?[L(t[0],0,100),L(t[1],0,100)]:[1,0]}function ri(t){return typeof t!="number"||!Number.isFinite(t)?0:L(t,Wl,Vl)}function ii(t){const e=Zo(t,[...Ji,255]);return[e[0],e[1],e[2]]}function gn(t){return typeof t!="number"||!Number.isFinite(t)?0:L(t,Gl,Zl)}function oi(t){const e=gn(t?.brightness),n=gn(t?.contrast),r=gn(t?.saturation);return{brightness:e/200,contrast:n/100,saturation:r/100}}function Qn(t){return t}function pn(t){return typeof t!="number"||!Number.isFinite(t)?0:L(t,0,Hl)}function Yt(t){return typeof t!="number"||!Number.isFinite(t)||t<=0?null:Math.max(1e-6,t)}function yn(t){return typeof t=="function"?t:Qn}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 rc(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 ic(t){const{event:e,canvas:n,state:r,config:i,camera:o,clampViewState:s,emitViewState:a,requestRender:l}=t;if(!r.dragging||e.pointerId!==r.pointerId)return;const u=e.clientX-r.lastPointerX,f=e.clientY-r.lastPointerY;if(r.lastPointerX=e.clientX,r.lastPointerY=e.clientY,r.mode==="rotate"){const c=eo(n,e.clientX,e.clientY),h=r.rotateLastAngleRad;if(r.rotateLastAngleRad=c,h!==null){const d=c-h,m=Math.atan2(Math.sin(d),Math.cos(d)),p=i.rotationDragSensitivityDegPerPixel/Bn,x=o.getViewState();o.setViewState({rotationDeg:x.rotationDeg-m*180/Math.PI*p})}}else{const c=o.getViewState(),h=Math.max(1e-6,c.zoom),d=an(c.rotationDeg),m=Math.cos(d),p=Math.sin(d),x=(u*m-f*p)/h,y=(u*p+f*m)/h;o.setViewState({offsetX:c.offsetX-x,offsetY:c.offsetY-y})}s(),a(),l()}function oc(t,e,n){t.pointerId===n.pointerId&&to(e,n)}function sc(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 ac=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)<ac)return;const s=r.accumulatedDelta>0?"out":"in";if(r.accumulatedDelta=0,!i(s,e,n)){r.blockedDirection=s;return}r.blockedDirection=null}function lc(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 cc(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 uc(t,e){(e||t.ctrlKey||t.metaKey)&&t.preventDefault()}function on(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 Ht(t,e,n=.2,r=.2){const i=on(t),o=Math.max(1e-6,i[2]-i[0]),s=Math.max(1e-6,i[3]-i[1]),a=o*n,l=s*r,[u,f]=t.getCenter(),c=o*.5,h=s*.5,d=c-a,m=e.width-c+a,p=h-l,x=e.height-h+l,y=d<=m?L(u,d,m):e.width*.5,b=p<=x?L(f,p,x):e.height*.5;t.setCenter(y,b)}function fc(t,e){const n=Math.max(1e-6,t.getViewState().zoom),r=e.maxTierZoom+Math.log2(n);return L(Math.floor(r),0,e.maxTierZoom)}function hc(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=on(t),i=Math.pow(2,e.maxTierZoom-n),o=Math.ceil(e.width/i),s=Math.ceil(e.height/i),a=Math.max(1,Math.ceil(o/e.tileSize)),l=Math.max(1,Math.ceil(s/e.tileSize)),u=r[0],f=r[1],c=r[2],h=r[3],d=L(Math.floor(u/i/e.tileSize),0,a-1),m=L(Math.floor((c-1)/i/e.tileSize),0,a-1),p=L(Math.floor(f/i/e.tileSize),0,l-1),x=L(Math.floor((h-1)/i/e.tileSize),0,l-1);if(d>m||p>x)return[];const y=(u+c)*.5/i/e.tileSize,b=(f+h)*.5/i/e.tileSize,M=[];for(let R=p;R<=x;R+=1)for(let A=d;A<=m;A+=1){const C=A*e.tileSize*i,N=R*e.tileSize*i,k=Math.min((A+1)*e.tileSize,o)*i,O=Math.min((R+1)*e.tileSize,s)*i,P=A-y,T=R-b;M.push({key:`${n}/${A}/${R}`,tier:n,x:A,y:R,bounds:[C,N,k,O],distance2:P*P+T*T,url:jn(e,n,A,R)})}return M.sort((R,A)=>R.distance2-A.distance2),M}function dc(t,e){const n=fc(t,e);return{tier:n,visible:io(t,e,n)}}function mc(t){t.interactionLocked||rc({event:t.event,canvas:t.canvas,state:t.state,config:{ctrlDragRotate:t.ctrlDragRotate,rotationDragSensitivityDegPerPixel:t.rotationDragSensitivityDegPerPixel},cancelViewAnimation:t.cancelViewAnimation})}function gc(t){t.interactionLocked||ic({event:t.event,canvas:t.canvas,state:t.state,config:{ctrlDragRotate:t.ctrlDragRotate,rotationDragSensitivityDegPerPixel:t.rotationDragSensitivityDegPerPixel},camera:t.camera,clampViewState:()=>Ht(t.camera,t.source,t.panExtentX,t.panExtentY),emitViewState:t.emitViewState,requestRender:t.requestRender})}function pc(t){t.interactionLocked||oc(t.event,t.canvas,t.state)}function yc(t){t.interactionLocked||cc({event:t.event,canvas:t.canvas,onZoomBy:t.onZoomBy})}function bc(t){uc(t.event,t.state.dragging)}function xc(t,e){to(t,e)}function wc(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=>gc({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=>pc({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){lc({event:e,canvas:t.canvas,snapState:t.zoomSnapState,onSnapZoom:t.onSnapZoom});return}sc({event:e,canvas:t.canvas,onZoomBy:t.zoomBy})},doubleClick:e=>yc({event:e,interactionLocked:t.getInteractionLocked(),canvas:t.canvas,onZoomBy:t.zoomBy}),contextMenu:e=>bc({event:e,canvas:t.canvas,state:t.state})}}function Sc(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 Rc(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 Ec(t){const{gl:e,cache:n,tile:r,bitmap:i,frameSerial:o,maxCacheTiles:s,destroyed:a,contextLost:l,requestRender:u}=t;if(a||l||e.isContextLost()){i.close();return}if(n.has(r.key)){i.close();return}const f=Rc(e,i);i.close(),f&&(n.set(r.key,{key:r.key,texture:f,bounds:r.bounds,tier:r.tier,lastUsed:o}),Sc({gl:e,cache:n,maxCacheTiles:s}),u())}function Mc(t,e){for(const[,n]of e)t.deleteTexture(n.texture)}function Ac(t){const{event:e,destroyed:n,contextLost:r,cancelViewAnimation:i,cancelDrag:o,tileScheduler:s,cache:a,onContextLost:l}=t;if(e.preventDefault(),n||r)return{handled:!1,frame:t.frame};let u=t.frame;return u!==null&&(cancelAnimationFrame(u),u=null),i(),o(),s.clear(),a.clear(),l?.(),{handled:!0,frame:u}}function Pc(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()){Mc(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 Cc(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 vc(t,e){return e<=0?new Uint8Array(0):t.length<e?new Uint8Array(e):t.subarray(0,e)}function si(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 ai(t,e,n,r,i){if(!i||!i.count||!i.positions||!i.paletteIndices)return{...t,lastPointData:null,pointCount:0,usePointIndices:!1};const o=i.fillModes instanceof Uint8Array?i.fillModes:null,s=o!==null,a=Math.max(0,Math.min(i.count,Math.floor(i.positions.length/2),i.paletteIndices.length,s?o.length:Number.MAX_SAFE_INTEGER)),l=i.positions.subarray(0,a*2),u=i.paletteIndices.subarray(0,a),f=s?o.subarray(0,a):void 0,c=i.drawIndices instanceof Uint32Array,h=c?Cc(i.drawIndices,a):null,d=t.lastPointData,m=d?.fillModes instanceof Uint8Array,p=t.pointBuffersDirty||!d||d.count!==a||!Ot(d.positions,l)||!Ot(d.paletteIndices,u)||m!==s||s&&(!d?.fillModes||!Ot(d.fillModes,f)),x=t.pointBuffersDirty||c&&(!d?.drawIndices||!Ot(d.drawIndices,h))||!c&&!!d?.drawIndices,y={...t,lastPointData:{count:a,positions:l,paletteIndices:u,fillModes:f,drawIndices:c?h??void 0:void 0}};if(r||e.isContextLost())return y;const b=y.lastPointData;if(!b)return y;if(p){e.bindBuffer(e.ARRAY_BUFFER,n.posBuffer),e.bufferData(e.ARRAY_BUFFER,b.positions,e.STATIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,n.classBuffer),e.bufferData(e.ARRAY_BUFFER,b.paletteIndices,e.STATIC_DRAW);const M=vc(y.zeroFillModes,a);e.bindBuffer(e.ARRAY_BUFFER,n.fillModeBuffer),e.bufferData(e.ARRAY_BUFFER,b.fillModes??M,e.STATIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,null),y.zeroFillModes=M}return c&&x&&(e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n.indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,h??new Uint32Array(0),e.DYNAMIC_DRAW),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),y.usePointIndices=c,y.pointCount=c?h?.length??0:b.count,(p||x)&&(y.pointBuffersDirty=!1),y}function Tc(t){const{gl:e,camera:n,source:r,cache:i,frameSerial:o,tileProgram:s,imageColorSettings:a,pointLayers:l,tileScheduler:u,getVisibleTiles:f,getVisibleTilesForTier:c,getViewBounds:h,intersectsBounds:d}=t;e.clearColor(.03,.06,.1,1),e.clear(e.COLOR_BUFFER_BIT);const{tier:m,visible:p}=f(),x=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 b=[];for(const[,P]of i)y.has(P.key)||d(P.bounds,x)&&b.push(P);b.sort((P,T)=>P.tier-T.tier);for(const P of b)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 R=[];for(const P of p){const T=i.get(P.key);if(!T){R.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 A=R.slice(),C=1e6,N=[];m>0&&N.push(m-1),m<r.maxTierZoom&&N.push(m+1);for(const P of N){const T=c(P);for(const W of T)i.has(W.key)||(W.distance2+=C,A.push(W))}u.schedule(A),e.bindTexture(e.TEXTURE_2D,null),e.bindVertexArray(null);let k=0,O=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),k+=T.pointCount,O+=1)}e.bindTexture(e.TEXTURE_2D,null),e.bindVertexArray(null)}return{tier:m,visible:p.length,rendered:M,points:k,fallback:b.length,cacheHits:M,cacheMisses:R.length,drawCalls:b.length+M+O}}function li(t){const r=St(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=Ie(t,r,"uCamera"),o=Ie(t,r,"uBounds"),s=Ie(t,r,"uTexture"),a=Ie(t,r,"uBrightness"),l=Ie(t,r,"uContrast"),
|
|
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"),u=Ie(t,r,"uSaturation"),f=t.createVertexArray(),c=t.createBuffer();if(!f||!c)throw new Error("buffer allocation failed");t.bindVertexArray(f),t.bindBuffer(t.ARRAY_BUFFER,c),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,0,1,0,1,0,0,1,0,1,1,1,1,1]),t.STATIC_DRAW);const h=t.getAttribLocation(r,"aUnit"),d=t.getAttribLocation(r,"aUv");if(h<0||d<0)throw new Error("tile attribute lookup failed");return t.enableVertexAttribArray(h),t.enableVertexAttribArray(d),t.vertexAttribPointer(h,2,t.FLOAT,!1,16,0),t.vertexAttribPointer(d,2,t.FLOAT,!1,16,8),t.bindVertexArray(null),t.bindBuffer(t.ARRAY_BUFFER,null),{program:r,vao:f,vbo:c,uCamera:i,uBounds:o,uTexture:s,uBrightness:a,uContrast:l,uSaturation:u}}function ci(t){const r=St(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=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;
|
|
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"),u=Ie(t,r,"uPointInnerFillAlpha"),f=Ie(t,r,"uPointInnerFillColor"),c=Ie(t,r,"uPalette"),h=Ie(t,r,"uPaletteSize"),d=Ie(t,r,"uPointLineDash"),m=t.createVertexArray(),p=t.createBuffer(),x=t.createBuffer(),y=t.createBuffer(),b=t.createBuffer(),M=t.createTexture();if(!m||!p||!x||!y||!b||!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 R=t.getAttribLocation(r,"aPosition");if(R<0)throw new Error("point position attribute not found");t.enableVertexAttribArray(R),t.vertexAttribPointer(R,2,t.FLOAT,!1,0,0),t.bindBuffer(t.ARRAY_BUFFER,x),t.bufferData(t.ARRAY_BUFFER,0,t.DYNAMIC_DRAW);const A=t.getAttribLocation(r,"aClass");if(A<0)throw new Error("point class attribute not found");t.enableVertexAttribArray(A),t.vertexAttribIPointer(A,1,t.UNSIGNED_SHORT,0,0),t.bindBuffer(t.ARRAY_BUFFER,y),t.bufferData(t.ARRAY_BUFFER,0,t.DYNAMIC_DRAW);const C=t.getAttribLocation(r,"aFillMode");if(C<0)throw new Error("point fill mode attribute not found");return t.enableVertexAttribArray(C),t.vertexAttribIPointer(C,1,t.UNSIGNED_BYTE,0,0),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,b),t.bufferData(t.ELEMENT_ARRAY_BUFFER,0,t.DYNAMIC_DRAW),t.bindVertexArray(null),t.bindBuffer(t.ARRAY_BUFFER,null),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null),t.bindTexture(t.TEXTURE_2D,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:x,fillModeBuffer:y,indexBuffer:b,paletteTexture:M,uCamera:i,uPointSize:o,uPointCssSize:s,uPointOpacity:a,uPointLineDash:d,uPointStrokeScale:l,uPointInnerFillAlpha:u,uPointInnerFillColor:f,uPalette:c,uPaletteSize:h}}function oo(t){t.animation=null,t.frame!==null&&(cancelAnimationFrame(t.frame),t.frame=null)}function Ic(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 u=e.animation;if(!u)return;const f=Math.max(0,Ee()-u.startMs),c=u.durationMs<=0?1:L(f/u.durationMs,0,1);let h=c;try{h=u.easing(c)}catch{h=c}if(Number.isFinite(h)||(h=c),h=L(h,0,1),n.setViewState({zoom:u.from.zoom+(u.to.zoom-u.from.zoom)*h,offsetX:u.from.offsetX+(u.to.offsetX-u.from.offsetX)*h,offsetY:u.from.offsetY+(u.to.offsetY-u.from.offsetY)*h,rotationDeg:u.from.rotationDeg+(u.to.rotationDeg-u.from.rotationDeg)*h}),s(),c>=1){e.animation=null,e.frame=null;return}e.frame=requestAnimationFrame(l)};e.frame=requestAnimationFrame(l)}function _c(t){const e=Math.max(t*.5,1e-6),n=Math.max(1,t*8);return{minZoom:e,maxZoom:Math.max(e,n)}}function Fc(t,e,n){const r=_c(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 Lc(t,e,n,r,i){const o=t.getViewState(),s={zoom:typeof r.zoom=="number"&&Number.isFinite(r.zoom)?L(r.zoom,e,n):o.zoom,offsetX:typeof r.offsetX=="number"&&Number.isFinite(r.offsetX)?r.offsetX:o.offsetX,offsetY:typeof r.offsetY=="number"&&Number.isFinite(r.offsetY)?r.offsetY:o.offsetY,rotationDeg:typeof r.rotationDeg=="number"&&Number.isFinite(r.rotationDeg)?r.rotationDeg:o.rotationDeg};t.setViewState(s),i();const a=t.getViewState();return t.setViewState(o),a}function ui(t,e,n,r,i,o=0){const s=Math.min(e/t.width,n/t.height),a=Number.isFinite(s)&&s>0?s:1,l=L(a,r,i),u=e/l,f=n/l;return{fitZoom:a,target:{zoom:l,offsetX:(t.width-u)*.5,offsetY:(t.height-f)*.5,rotationDeg:o}}}function Dc(t,e,n,r,i,o){const s=t.getViewState(),a=L(s.zoom*r,e,n);if(a===s.zoom)return null;const[l,u]=t.screenToWorld(i,o),f=t.getViewportSize(),c=i-f.width*.5,h=o-f.height*.5,d=an(s.rotationDeg),m=Math.cos(d),p=Math.sin(d),x=c/a*m-h/a*p,y=c/a*p+h/a*m,b=l-x,M=u-y;return{zoom:a,offsetX:b-f.width/(2*a),offsetY:M-f.height/(2*a)}}function Nc(t,e,n,r,i,o){const s=t.getViewState(),a=L(r,e,n);if(a===s.zoom)return null;const[l,u]=t.screenToWorld(i,o),f=t.getViewportSize(),c=i-f.width*.5,h=o-f.height*.5,d=an(s.rotationDeg),m=Math.cos(d),p=Math.sin(d),x=c/a*m-h/a*p,y=c/a*p+h/a*m,b=l-x,M=u-y;return{zoom:a,offsetX:b-f.width/(2*a),offsetY:M-f.height/(2*a)}}const Bc=250;function fi(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 zc(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 kc(t,e,n,r,i){const o=t.camera.getViewState(),[s,a]=t.camera.screenToWorld(n,r),l=t.camera.getViewportSize(),u=L(e,t.minZoom,t.maxZoom);if(u===o.zoom)return;const f=an(o.rotationDeg),c=Math.cos(f),h=Math.sin(f),d=n-l.width*.5,m=r-l.height*.5;t.cancelViewAnimation();const p=b=>{const M=d/b*c-m/b*h,R=d/b*h+m/b*c;return{offsetX:s-M-l.width/(2*b),offsetY:a-R-l.height/(2*b)}},x=p(u);t.viewAnimationState.animation={startMs:Ee(),durationMs:Math.max(0,i),from:o,to:{zoom:u,offsetX:x.offsetX,offsetY:x.offsetY,rotationDeg:o.rotationDeg},easing:Qn};const y=()=>{const b=t.viewAnimationState.animation;if(!b)return;const M=Math.max(0,Ee()-b.startMs),R=L(M/i,0,1),A=L(R*R*(3-2*R),0,1),C=o.zoom+(u-o.zoom)*A,{offsetX:N,offsetY:k}=p(C);t.camera.setViewState({zoom:C,offsetX:N,offsetY:k,rotationDeg:o.rotationDeg});const O=R>=1;O&&(t.clampViewState(),t.viewAnimationState.animation=null,t.viewAnimationState.frame=null),t.onViewStateChange(t.camera.getViewState()),t.requestRender(),O||(t.viewAnimationState.frame=requestAnimationFrame(y))};t.viewAnimationState.frame=requestAnimationFrame(y)}const Fe="__default_point_layer__";class so{constructor(e,n,r={}){S(this,"canvas");S(this,"source");S(this,"gl");S(this,"camera",new di);S(this,"onViewStateChange");S(this,"onStats");S(this,"onTileError");S(this,"onContextLost");S(this,"onContextRestored");S(this,"resizeObserver");S(this,"removeDprListener");S(this,"tileProgram");S(this,"tileScheduler");S(this,"authToken");S(this,"destroyed",!1);S(this,"contextLost",!1);S(this,"frame",null);S(this,"frameSerial",0);S(this,"interactionState",{dragging:!1,mode:"none",rotateLastAngleRad:null,pointerId:null,lastPointerX:0,lastPointerY:0});S(this,"interactionLocked",!1);S(this,"ctrlDragRotate",!0);S(this,"rotationDragSensitivityDegPerPixel",Bn);S(this,"maxCacheTiles");S(this,"fitZoom",1);S(this,"initialRotationDeg",0);S(this,"minZoom",1e-6);S(this,"maxZoom",1);S(this,"minZoomOverride",null);S(this,"maxZoomOverride",null);S(this,"viewTransitionDurationMs",0);S(this,"viewTransitionEasing",Qn);S(this,"viewAnimationState",{animation:null,frame:null});S(this,"pointLayers",new Map);S(this,"defaultPointSizeZoomStops",rn(zn));S(this,"defaultPointSizeMagnificationStops",null);S(this,"defaultPointWeightMagnificationStops",null);S(this,"defaultPointOpacity",1);S(this,"defaultPointLineDash",[1,0]);S(this,"defaultPointStrokeScale",1);S(this,"defaultPointInnerFillOpacity",0);S(this,"defaultPointInnerFillColor",[...Ji]);S(this,"imageColorSettings",{brightness:0,contrast:0,saturation:0});S(this,"cache",new Map);S(this,"zoomSnaps",[]);S(this,"zoomSnapFitAsMin",!1);S(this,"zoomSnapState",{accumulatedDelta:0,lastSnapTimeMs:0,blockedDirection:null});S(this,"panExtentX",.2);S(this,"panExtentY",.2);S(this,"boundPointerDown");S(this,"boundPointerMove");S(this,"boundPointerUp");S(this,"boundWheel");S(this,"boundDoubleClick");S(this,"boundContextMenu");S(this,"boundContextLost");S(this,"boundContextRestored");this.canvas=e,this.source=n,this.onViewStateChange=r.onViewStateChange,this.onStats=r.onStats,this.onTileError=r.onTileError,this.onContextLost=r.onContextLost,this.onContextRestored=r.onContextRestored,this.authToken=r.authToken??"",this.maxCacheTiles=Math.max(32,Math.floor(r.maxCacheTiles??320)),this.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):Bn,this.defaultPointSizeZoomStops=Jr(r.pointSizeByZoom),this.defaultPointSizeMagnificationStops=ei(r.pointSizeByMagnification),this.defaultPointWeightMagnificationStops=ti(r.pointWeightByMagnification),this.defaultPointOpacity=ni(r.pointOpacity),this.defaultPointStrokeScale=Zt(r.pointStrokeScale),this.defaultPointInnerFillOpacity=ri(r.pointInnerFillOpacity),this.defaultPointInnerFillColor=ii(r.pointInnerFillColor),this.imageColorSettings=oi(r.imageColorSettings),this.minZoomOverride=Yt(r.minZoom),this.maxZoomOverride=Yt(r.maxZoom),this.viewTransitionDurationMs=pn(r.viewTransition?.duration),this.viewTransitionEasing=yn(r.viewTransition?.easing),this.zoomSnaps=fi(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=li(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)=>Ec({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=sn(()=>this.resize());const o=wc({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),Bl(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=Fc(this.fitZoom,this.minZoomOverride,this.maxZoomOverride);this.minZoom=e.minZoom,this.maxZoom=e.maxZoom}resolveTargetViewState(e){return Lc(this.camera,this.minZoom,this.maxZoom,e,()=>Ht(this.camera,this.source,this.panExtentX,this.panExtentY))}cancelViewAnimation(){oo(this.viewAnimationState)}startViewAnimation(e,n,r){this.resetZoomSnapStateForZoomChange(this.camera.getViewState().zoom,e.zoom),Ic({state:this.viewAnimationState,camera:this.camera,target:e,durationMs:n,easing:r,onUpdate:()=>{Ht(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:ci(this.gl),runtime:this.createPointBufferRuntime(),pointSizeZoomStops:rn(this.defaultPointSizeZoomStops),pointSizeMagnificationStops:ql(this.defaultPointSizeMagnificationStops),pointWeightMagnificationStops:$l(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=Yt(e),i=Yt(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();Mn(s,o)||this.applyViewStateAndRender(o)}setViewTransition(e){this.viewTransitionDurationMs=pn(e?.duration),this.viewTransitionEasing=yn(e?.easing)}setViewState(e,n){const r=this.resolveTargetViewState(e),i=this.camera.getViewState();if(Mn(i,r))return;const o=pn(n?.duration??this.viewTransitionDurationMs),s=yn(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=si(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=nc(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=ai(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=Jr(e);Kl(r.pointSizeZoomStops,i)||(r.pointSizeZoomStops=i,this.requestRender())}setPointSizeByMagnification(e,n=Fe){const r=this.ensurePointLayer(n),i=ei(e);jl(r.pointSizeMagnificationStops,i)||(r.pointSizeMagnificationStops=i,this.requestRender())}setPointWeightByMagnification(e,n=Fe){const r=this.ensurePointLayer(n),i=ti(e);Ql(r.pointWeightMagnificationStops,i)||(r.pointWeightMagnificationStops=i,this.requestRender())}setPointOpacity(e,n=Fe){const r=this.ensurePointLayer(n),i=ni(e);r.pointOpacity!==i&&(r.pointOpacity=i,this.requestRender())}setPointStrokeScale(e,n=Fe){const r=this.ensurePointLayer(n),i=Zt(e);r.pointStrokeScale!==i&&(r.pointStrokeScale=i,this.requestRender())}setPointInnerFillOpacity(e,n=Fe){const r=this.ensurePointLayer(n),i=ri(e);r.pointInnerFillOpacity!==i&&(r.pointInnerFillOpacity=i,this.requestRender())}setPointInnerFillColor(e,n=Fe){const r=this.ensurePointLayer(n),i=ii(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=oi(e),r=this.imageColorSettings;r.brightness===n.brightness&&r.contrast===n.contrast&&r.saturation===n.saturation||(this.imageColorSettings=n,this.requestRender())}cancelDrag(){xc(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 on(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),u=Kt(this.source.mpp??0,l);if(u>0){const f=ec(u,r);return L(f,dt,Qr)}}const i=Math.max(1e-6,this.camera.getViewState().zoom),o=this.source.maxTierZoom+Math.log2(i),s=n?.pointSizeZoomStops??this.defaultPointSizeZoomStops,a=Jl(o,s);return L(a,dt,Qr)}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=Kt(this.source.mpp??0,i);if(o>0)return Zt(tc(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=ui(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=Dc(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=Nc(this.camera,this.minZoom,this.maxZoom,e,n,r);o&&this.setViewState(o,i)}setZoomSnaps(e,n){this.zoomSnaps=fi(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:()=>Ht(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=zc(s,o,e,this.zoomSnapFitAsMin);if(!a)return!1;let l;if(a.type==="fit"){const f=this.canvas.getBoundingClientRect(),c=Math.max(1,f.width||1),h=Math.max(1,f.height||1),d=ui(this.source,c,h,this.minZoom,this.maxZoom,this.initialRotationDeg);this.fitZoom=d.fitZoom,this.applyZoomBounds(),l=d.target.zoom}else l=a.zoom;const u=Math.max(Math.abs(l)*.005,1e-8);if(i){if((i.to.zoom>i.from.zoom+u?"in":i.to.zoom<i.from.zoom-u?"out":null)===e&&Math.abs(i.to.zoom-l)<=u)return!1}else if(Math.abs(o-l)<=u)return!1;return kc(this.getZoomPivotAnimationContext(),l,n,r,Bc),!0}render(){if(this.destroyed||this.contextLost||this.gl.isContextLost())return;const e=this.onStats?Ee():0;this.frameSerial+=1;const n=Tc({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:()=>dc(this.camera,this.source),getVisibleTilesForTier:r=>io(this.camera,this.source,r),getViewBounds:()=>on(this.camera),intersectsBounds:hc});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(){kl(this.canvas,this.gl,this.camera),this.requestRender()}onWebGlContextLost(e){const n=Ac({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=li(this.gl);for(const n of this.pointLayers.values())n.program=ci(this.gl),n.runtime={...n.runtime,pointBuffersDirty:!0},n.runtime.lastPointPalette&&n.runtime.lastPointPalette.length>0&&(n.runtime=si(n.runtime,this.gl,n.program,this.contextLost,n.runtime.lastPointPalette)),n.runtime.lastPointData&&(n.runtime=ai(n.runtime,this.gl,n.program,this.contextLost,n.runtime.lastPointData));this.resize(),this.onContextRestored?.()}}destroy(){const e=Pc({destroyed:this.destroyed,frame:this.frame,cancelViewAnimation:()=>this.cancelViewAnimation(),resizeObserver:this.resizeObserver,removeDprListener:this.removeDprListener,removeCanvasEventListeners:()=>zl(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 Uc=[];function Oc(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Yc({source:t,viewState:e,onViewStateChange:n,onStats:r,onTileError:i,onContextLost:o,onContextRestored:s,imageColorSettings:a=null,initialRotate:l=0,fitNonce:u=0,rotationResetNonce:f=0,authToken:c="",ctrlDragRotate:h=!0,minZoom:d,maxZoom:m,viewTransition:p,zoomSnaps:x,zoomSnapFitAsMin:y,panExtent:b,preserveDrawingBuffer:M,onPointerWorldMove:R,debugOverlay:A=!1,debugOverlayStyle:C,className:N,style:k,children:O}){const P=g.useRef(null),T=g.useRef(null),W=g.useRef(null),I=g.useRef(null),Y=g.useRef(null),$=g.useRef(null),F=g.useRef(Uc),ge=g.useRef(!1),V=g.useRef(new Set),H=g.useRef(new Set),Me=g.useRef(n),Se=g.useRef(r),D=g.useRef(i),v=g.useRef(o),B=g.useRef(s),[se,ue]=g.useState(0),[Q,ce]=g.useState(null),ne=g.useRef(A);g.useEffect(()=>{Me.current=n},[n]),g.useEffect(()=>{Se.current=r},[r]),g.useEffect(()=>{D.current=i},[i]),g.useEffect(()=>{v.current=o},[o]),g.useEffect(()=>{B.current=s},[s]),g.useEffect(()=>{ne.current=A,A||ce(null)},[A]);const _e=g.useMemo(()=>({position:"relative",width:"100%",height:"100%",...k}),[k]),Re=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]),fe=Oc(l),xe=g.useCallback(U=>({...U,rotationDeg:U.rotationDeg-fe}),[fe]),te=g.useCallback(U=>typeof U.rotationDeg!="number"||!Number.isFinite(U.rotationDeg)?U:{...U,rotationDeg:U.rotationDeg+fe},[fe]),ae=g.useCallback(U=>{Se.current?.(U),ne.current&&ce(U)},[]),he=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]),le=g.useCallback(()=>{const U=W.current;if(!U)return;const q=U.getContext("2d");if(!q)return;const K=Math.max(1,window.devicePixelRatio||1),ie=U.getBoundingClientRect(),pe=Math.max(1,Math.round(ie.width*K)),de=Math.max(1,Math.round(ie.height*K));(U.width!==pe||U.height!==de)&&(U.width=pe,U.height=de);const Ne=ie.width,w=ie.height;q.setTransform(1,0,0,1,0,0),q.clearRect(0,0,U.width,U.height),q.setTransform(K,0,0,K,0,0);const E=F.current;for(let _=0;_<E.length;_+=1)q.save(),E[_].draw(q,Ne,w),q.restore()},[]),re=g.useCallback(()=>{ge.current||(ge.current=!0,requestAnimationFrame(()=>{ge.current=!1,le()}))},[le]),Pe=g.useCallback((U,q,K)=>{const ie=F.current.filter(pe=>pe.id!==U);ie.push({id:U,priority:q,draw:K}),ie.sort((pe,de)=>pe.priority-de.priority),F.current=ie,re()},[re]),we=g.useCallback(U=>{F.current=F.current.filter(q=>q.id!==U),re()},[re]),G=g.useCallback((U,q)=>{q?V.current.add(U):V.current.delete(U),I.current?.setInteractionLock(V.current.size>0)},[]),j=g.useCallback(()=>V.current.size>0,[]),be=g.useCallback((U,q)=>{const K=I.current;return K?Yn(K.worldToScreen(U,q)):null},[]),ee=g.useCallback((U,q)=>{const K=I.current;if(!K)return null;const ie=K.screenToWorld(U,q);if(!Array.isArray(ie)||ie.length<2)return null;const pe=Number(ie[0]),de=Number(ie[1]);return!Number.isFinite(pe)||!Number.isFinite(de)?null:[pe,de]},[]),J=g.useCallback(U=>(H.current.add(U),()=>{H.current.delete(U)}),[]),Ae=g.useCallback(U=>{Me.current?.(xe(U));const q=H.current;if(q.size>0){const K=Array.from(q);for(let ie=0;ie<K.length;ie+=1)K[ie](U)}Y.current?.(),$.current?.(),re()},[re,xe]);g.useEffect(()=>{const U=T.current;if(!U||!t)return;const q=new so(U,t,{onViewStateChange:Ae,onStats:ae,onTileError:K=>{D.current?.(K)},onContextLost:()=>{v.current?.()},onContextRestored:()=>{B.current?.()},authToken:c,imageColorSettings:a,initialRotationDeg:l,ctrlDragRotate:h,minZoom:d,maxZoom:m,viewTransition:p,zoomSnaps:x,zoomSnapFitAsMin:y,panExtent:b,preserveDrawingBuffer:M});return I.current=q,ue(K=>K+1),e&&q.setViewState(te(e)),q.setInteractionLock(V.current.size>0),()=>{q.destroy(),I.current=null}},[t,ae,h,Ae,fe,te]),g.useEffect(()=>{I.current?.setAuthToken(c)},[c]),g.useEffect(()=>{const U=I.current;!U||!e||U.isViewAnimating()||U.setViewState(te(e))},[e,te]),g.useEffect(()=>{I.current?.fitToImage()},[u]),g.useEffect(()=>{I.current?.resetRotation()},[f]),g.useEffect(()=>{I.current?.setZoomRange(d,m)},[d,m]),g.useEffect(()=>{I.current?.setViewTransition(p)},[p]),g.useEffect(()=>{I.current?.setZoomSnaps(x,y)},[x,y]),g.useEffect(()=>{I.current?.setPanExtent(b)},[b]),g.useEffect(()=>{I.current?.setImageColorSettings(a)},[a]),g.useEffect(()=>{const U=W.current;if(!U)return;Y.current=re,re();const q=new ResizeObserver(()=>re());return q.observe(U),()=>{q.disconnect(),Y.current===re&&(Y.current=null)}},[re]),g.useEffect(()=>sn(()=>re()),[re]);const X=g.useMemo(()=>({source:t,rendererRef:I,rendererSerial:se,canvasRef:T,containerRef:P,drawInvalidateRef:Y,overviewInvalidateRef:$,worldToScreen:be,screenToWorld:ee,registerDrawCallback:Pe,unregisterDrawCallback:we,requestOverlayRedraw:re,registerViewStateListener:J,setInteractionLock:G,isInteractionLocked:j}),[t,se,be,ee,Pe,we,re,J,G,j]),Ce=g.useRef(R);g.useEffect(()=>{Ce.current=R},[R]);const De=g.useCallback(U=>{const q=Ce.current;if(!q)return;const K=ee(U.clientX,U.clientY),ie=!!K&&K[0]>=0&&K[1]>=0&&!!t&&K[0]<=t.width&&K[1]<=t.height;q({coordinate:K,clientX:U.clientX,clientY:U.clientY,insideImage:ie})},[ee,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:N,style:_e,onPointerMove:R?De:void 0,onPointerLeave:R?Le:void 0,children:[Ge.jsx("canvas",{ref:T,className:"wsi-render-canvas",style:{position:"absolute",inset:0,zIndex:1,width:"100%",height:"100%",display:"block",touchAction:"none"}}),Ge.jsx("canvas",{ref:W,className:"wsi-overlay-canvas",style:{position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",pointerEvents:"none",touchAction:"none"}}),O,A&&Ge.jsx("pre",{"data-open-plant-debug-overlay":!0,style:Re,children:he})]})})}function Xc(t){const e=[];for(let n=0;n<t.length;n+=1){const r=t[n],i=gt([mt(r?.coordinates)]);if(i.length===0)continue;let o=0,s=1/0,a=1/0,l=-1/0,u=-1/0;for(const f of i)o+=f.area,f.minX<s&&(s=f.minX),f.minY<a&&(a=f.minY),f.maxX>l&&(l=f.maxX),f.maxY>u&&(u=f.maxY);!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(l)||!Number.isFinite(u)||e.push({regionId:r.id??n,regionIndex:n,polygons:i,area:Math.max(1e-6,o),minX:s,minY:a,maxX:l,maxY:u})}return e}const Wc=128,bn=[];function ft(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 Vc(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(Wc,o)),a=r>e?(r-e)/s:1,l=i>n?(i-n)/s:1,u=Array.from({length:s*s},()=>[]);for(let f=0;f<t.length;f+=1){const c=t[f],h=ft(c.minX,e,r,a,s),d=ft(c.maxX,e,r,a,s),m=ft(c.minY,n,i,l,s),p=ft(c.maxY,n,i,l,s);for(let x=m;x<=p;x+=1)for(let y=h;y<=d;y+=1)u[x*s+y].push(f)}return{minX:e,minY:n,maxX:r,maxY:i,gridSize:s,cellWidth:a,cellHeight:l,buckets:u}}function Gc(t,e,n){if(!t||e<t.minX||e>t.maxX||n<t.minY||n>t.maxY)return bn;const r=ft(e,t.minX,t.maxX,t.cellWidth,t.gridSize),i=ft(n,t.minY,t.maxY,t.cellHeight,t.gridSize);return t.buckets[i*t.gridSize+r]??bn}function Zc(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 Hc(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 x=0;for(let y=0;y<d.length;y+=1){const b=d[y];b>=r||(p[x]=b,x+=1)}i=p}else i=new Uint32Array(0)}const o=i?i.length:r,s=Xc(e??[]);if(!t||o===0||s.length===0)return{groups:[],inputPointCount:o,pointsInsideAnyRegion:0,unmatchedPointCount:o};const a=new Map,l=new Map,u=Vc(s);let f=0;for(let d=0;d<o;d+=1){const m=i?i[d]:d,p=t.positions[m*2],x=t.positions[m*2+1];if(!Number.isFinite(p)||!Number.isFinite(x))continue;let y=null;const b=Gc(u,p,x);if(b.length===0)continue;for(const A of b){const C=s[A];let N=!1;for(const k of C.polygons)if(xi(p,x,k)){N=!0;break}N&&(!y||C.area<y.area)&&(y=C)}if(!y)continue;f+=1;const M=t.paletteIndices[m]??0,R=a.get(y.regionIndex)??new Map;R.set(M,(R.get(M)??0)+1),a.set(y.regionIndex,R),l.set(y.regionIndex,(l.get(y.regionIndex)??0)+1)}const c=n.includeEmptyRegions??!1,h=[];for(const d of s){const m=l.get(d.regionIndex)??0;if(!c&&m<=0)continue;const p=a.get(d.regionIndex)??new Map,x=Array.from(p.entries()).map(([y,b])=>({classId:Zc(y,n.paletteIndexToClassId),paletteIndex:y,count:b})).sort((y,b)=>b.count-y.count||y.paletteIndex-b.paletteIndex);h.push({regionId:d.regionId,regionIndex:d.regionIndex,totalCount:m,classCounts:x})}return{groups:h,inputPointCount:o,pointsInsideAnyRegion:f,unmatchedPointCount:Math.max(0,o-f)}}function qc(t){return t.replace(/^\s*SRID\s*=\s*\d+\s*;\s*/i,"")}function $c(t){return t>="A"&&t<="Z"||t>="a"&&t<="z"}function Kc(t){return t>="0"&&t<="9"}function hi(t){return t==="+"||t==="-"||t==="."||Kc(t)}class jc{constructor(e){S(this,"text");S(this,"index",0);this.text=qc(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=Jc(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()&&$c(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||!hi(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(!hi(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 Qc(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(!Qc(i))return null;r.push([i[0],i[1]])}e.push(r)}return e}function Jc(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 eu(t){return typeof t!="string"?null:new jc(t).parse()}exports.DEFAULT_POINT_COLOR=Un;exports.DrawLayer=_i;exports.DrawingLayer=ua;exports.HeatmapLayer=Da;exports.M1TileRenderer=mi;exports.OverlayLayer=Ba;exports.OverviewMap=Za;exports.PatchLayer=qa;exports.PointLayer=wl;exports.RegionLayer=Ll;exports.TileScheduler=Qi;exports.TileViewerCanvas=Dl;exports.WsiTileRenderer=so;exports.WsiViewer=Yc;exports.__heatmapLayerInternals=Na;exports.buildClassPalette=qo;exports.buildPointSpatialIndexAsync=ji;exports.calcScaleLength=Vo;exports.calcScaleResolution=On;exports.calcViewingMagnification=Kt;exports.clamp=L;exports.closeRing=Oe;exports.computeRoiPointGroups=Hc;exports.createCircle=An;exports.createRectangle=en;exports.createSpatialIndex=Li;exports.filterPointDataByPolygons=Pt;exports.filterPointDataByPolygonsHybrid=Hi;exports.filterPointDataByPolygonsInWorker=$i;exports.filterPointIndicesByPolygons=Vi;exports.filterPointIndicesByPolygonsInWorker=il;exports.getWebGpuCapabilities=tl;exports.hexToRgba=wi;exports.isSameViewState=Mn;exports.lookupCellIndex=Ki;exports.normalizeImageClasses=za;exports.normalizeImageInfo=Ua;exports.parseWkt=eu;exports.prefilterPointsByBoundsWebGpu=Zi;exports.terminatePointHitIndexWorker=ml;exports.terminateRoiClipWorker=rl;exports.toBearerToken=Go;exports.toRoiGeometry=mt;exports.toTileUrl=jn;exports.useViewerContext=ot;
|
|
248
248
|
//# sourceMappingURL=index.cjs.map
|