@fnndsc/argus 0.7.1 → 0.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/ChRISlogo-color-t-i99soF.svg +164 -0
- package/dist/assets/MesloLGS-NF-Bold-DbxbaV6p.ttf +0 -0
- package/dist/assets/MesloLGS-NF-Regular-DAUcZJjt.ttf +0 -0
- package/dist/assets/Settings-B_WPNkCE.js +4407 -0
- package/dist/assets/_commonjsHelpers-CE1G-McA.js +1 -0
- package/dist/assets/addVolumesToViewports-kPbPUzG1.js +1 -0
- package/dist/assets/antonio-latin-400-normal-CZjzwNAN.woff2 +0 -0
- package/dist/assets/antonio-latin-700-normal-DSH-lEDG.woff2 +0 -0
- package/dist/assets/arrive-ClURnB_N.wav +0 -0
- package/dist/assets/blosc-CrUiACa7.js +17 -0
- package/dist/assets/chakra-petch-latin-400-normal-SafcrIr2.woff2 +0 -0
- package/dist/assets/chakra-petch-latin-500-normal-BR1ody1F.woff2 +0 -0
- package/dist/assets/chakra-petch-latin-600-normal-DVQm9bgb.woff2 +0 -0
- package/dist/assets/chakra-petch-latin-700-normal-CnDBPjkL.woff2 +0 -0
- package/dist/assets/charlswasm_decode-BrO4esUm.wasm +0 -0
- package/dist/assets/chunk-INHXZS53-D3tQiqtZ.js +1 -0
- package/dist/assets/computeWorker-D8XJyv-f.js +4095 -0
- package/dist/assets/cornerstoneEngine-COmMRWtq.js +2 -0
- package/dist/assets/dcmjs.es-DfWkgqfk.js +18 -0
- package/dist/assets/decodeImageFrameWorker-BtcTb_T6.js +5 -0
- package/dist/assets/index-B1IRr1ii.js +4145 -0
- package/dist/assets/index-BEqlmVJ8.js +2456 -0
- package/dist/assets/index-BbgujRGq.css +1 -0
- package/dist/assets/index-BivV2-EJ.js +9 -0
- package/dist/assets/index-CH659Lsh.js +1 -0
- package/dist/assets/index-DRvbvdZm.js +320 -0
- package/dist/assets/index-Ddoc1eo6.js +1 -0
- package/dist/assets/index-WxcTPiRU.js +2 -0
- package/dist/assets/index-oaz5IMVa.js +1 -0
- package/dist/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
- package/dist/assets/jetbrains-mono-latin-500-normal-BWZEU5yA.woff2 +0 -0
- package/dist/assets/jpeg-B-x1txLf.js +1 -0
- package/dist/assets/libjpegturbowasm_decode-7ZJ2wGuU.wasm +0 -0
- package/dist/assets/lossless-CyYqoyFe.js +1 -0
- package/dist/assets/lz4-B_Exjfmr.js +15 -0
- package/dist/assets/niivueEngine-B2PDgoH7.js +2 -0
- package/dist/assets/openjpegwasm_decode-B3gWTHpv.wasm +0 -0
- package/dist/assets/openjphjs-B5O5ikHp.wasm +0 -0
- package/dist/assets/press-Cr6-1MeH.wav +0 -0
- package/dist/assets/refuse-DQOeTs-N.wav +0 -0
- package/dist/assets/retreat-CxfXQVOC.wav +0 -0
- package/dist/assets/throttle-CjIII7Yf.js +1 -0
- package/dist/assets/zstd-u5eweWyS.js +15 -0
- package/dist/index.html +626 -0
- package/package.json +1 -1
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
import{b7 as Re,t as Rt,e as Z,al as mv,aJ as Ne,aK as Vi,b8 as Se,at as Q,b9 as jr,ba as pv,ac as We,V as so,ar as Xe,bb as Gn,ad as pn,am as Pn,ae as Qo,bc as wn,bd as Xr,be as vv,bf as bh,bg as Iv,ah as Ea,bh as ve,i as ie,bi as vc,bj as wv,bk as rn,bl as _h,bm as Hn,bn as eo,bo as Fi,bp as yh,bq as xh,br as Nl,bs as qr,E as yt,aN as Es,bt as Ss,bu as Ev,bv as $o,bw as IC,bx as Fn,by as _n,bz as Ph,bA as wC,bB as EC,bC as SC,bD as CC,bE as Yc,bF as bC,bG as _C,bH as yC,aw as xC,bI as Vo,bJ as la,bK as Oo,bL as vo,b5 as Kc,bM as PC,bN as Sv,bO as DC,bP as Dh,bQ as Cv,bR as TC,bS as MC,aL as Eg,K as kl,bT as Sa,ao as bv,bU as AC,bV as Ul,bW as LC,bX as OC,aO as fr,bY as _v,bZ as Ud,b_ as yv,b$ as Th,c0 as Mh,c1 as RC,c2 as Vt,c3 as Lt,c4 as NC,c5 as Di,av as kC,g as UC,c6 as po,c7 as VC,c8 as FC,c9 as Zc,ca as Sg,cb as GC,cc as Vd,ag as Ks,af as HC,cd as Cg,J as WC,ai as BC,ce as zC,cf as Ah,cg as xv,ch as Pv,ci as $C,cj as ku,ck as bg,cl as jC,cm as di,cn as XC,co as qC,cp as _g,cq as tr,cr as YC,cs as KC,ct as ZC,cu as Jc,cv as yg,cw as JC,cx as QC,cy as Bc,cz as tb,cA as er,cB as xg,cC as eb,cD as nb,cE as ob,cF as ib}from"./Settings-B_WPNkCE.js";import{i as sb,b as ae,g as N,j as ab,c as le,u as oe,k as Dv,l as Lh,m as Uu,f as gr,h as Zs,n as rb,d as cb,o as Oh,r as de,p as lb,q as Tv,t as gn,w as is,x as Rh,y as Mv,z as db,A as da,M as ub,B as Av,C as Pg,D as Fa,E as Vu,F as hb}from"./index-Ddoc1eo6.js";import{c as Ic,g as fb}from"./_commonjsHelpers-CE1G-McA.js";import{A as Kn,E as Js,c as B,f as Ot,d as xt,a as Me,l as mr,n as Wt,e as pr,s as bn,b as Oe,g as tn,h as mn,i as ee,j as Yr,k as gb,m as ke,t as Un,o as Ue,p as Lv,q as Fu,r as yn,u as Ov,v as ho,w as Rv,x as Nv,y as mb,z as pb,B as vb,C as Dg,D as Ib,F as wb,G as Eb}from"./throttle-CjIII7Yf.js";import{a as Sb}from"./addVolumesToViewports-kPbPUzG1.js";import"./dcmjs.es-DfWkgqfk.js";function Cb(i,t){let n;if(t===void 0)for(const e of i)e!=null&&(n>e||n===void 0&&e>=e)&&(n=e);else{let e=-1;for(let o of i)(o=t(o,++e,i))!=null&&(n>o||n===void 0&&o>=o)&&(n=o)}return n}function bb(i){if(!(s=i.length))return[];for(var t=-1,n=Cb(i,_b),e=new Array(n);++t<n;)for(var o=-1,s,a=e[t]=new Array(s);++o<s;)a[o]=i[o][t];return e}function _b(i){return i.length}function Tg(){return bb(arguments)}function yb(i,t,n,e,o){var s=i*i,a=s*i;return((1-3*i+3*s-a)*t+(4-6*s+3*a)*n+(1+3*i+3*s-3*a)*e+a*o)/6}function Fd(i){var t=i.length-1;return function(n){var e=n<=0?n=0:n>=1?(n=1,t-1):Math.floor(n*t),o=i[e],s=i[e+1],a=e>0?i[e-1]:2*o-s,r=e<t-1?i[e+2]:2*s-o;return yb((n-e/t)*t,a,o,s,r)}}function Ga(i,t){for(var n=new Array(t),e=0;e<t;++e)n[e]=i(e/(t-1));return n}var Fo;(function(i){i[i.Primary=1]="Primary",i[i.Secondary=2]="Secondary",i[i.Primary_And_Secondary=3]="Primary_And_Secondary",i[i.Auxiliary=4]="Auxiliary",i[i.Primary_And_Auxiliary=5]="Primary_And_Auxiliary",i[i.Secondary_And_Auxiliary=6]="Secondary_And_Auxiliary",i[i.Primary_And_Secondary_And_Auxiliary=7]="Primary_And_Secondary_And_Auxiliary",i[i.Fourth_Button=8]="Fourth_Button",i[i.Fifth_Button=16]="Fifth_Button",i[i.Wheel=524288]="Wheel",i[i.Wheel_Primary=524289]="Wheel_Primary"})(Fo||(Fo={}));var vn;(function(i){i[i.Shift=16]="Shift",i[i.Ctrl=17]="Ctrl",i[i.Alt=18]="Alt",i[i.Meta=91]="Meta",i[i.ShiftCtrl=1617]="ShiftCtrl",i[i.ShiftAlt=1618]="ShiftAlt",i[i.ShiftMeta=1691]="ShiftMeta",i[i.CtrlAlt=1718]="CtrlAlt",i[i.CtrlMeta=1791]="CtrlMeta",i[i.AltMeta=1891]="AltMeta"})(vn||(vn={}));var se;(function(i){i.Active="Active",i.Passive="Passive",i.Enabled="Enabled",i.Disabled="Disabled"})(se||(se={}));var To;(function(i){i.Default="",i.Highlighted="Highlighted",i.Selected="Selected",i.Locked="Locked",i.AutoGenerated="AutoGenerated"})(To||(To={}));var E;(function(i){i.TOOL_ACTIVATED="CORNERSTONE_TOOLS_TOOL_ACTIVATED",i.TOOLGROUP_VIEWPORT_ADDED="CORNERSTONE_TOOLS_TOOLGROUP_VIEWPORT_ADDED",i.TOOLGROUP_VIEWPORT_REMOVED="CORNERSTONE_TOOLS_TOOLGROUP_VIEWPORT_REMOVED",i.TOOL_MODE_CHANGED="CORNERSTONE_TOOLS_TOOL_MODE_CHANGED",i.CROSSHAIR_TOOL_CENTER_CHANGED="CORNERSTONE_TOOLS_CROSSHAIR_TOOL_CENTER_CHANGED",i.WORLD_CROSSHAIR_POINT_CHANGED="CORNERSTONE_TOOLS_WORLD_CROSSHAIR_POINT_CHANGED",i.WORLD_CROSSHAIR_POINT_CLEARED="CORNERSTONE_TOOLS_WORLD_CROSSHAIR_POINT_CLEARED",i.WORLD_CROSSHAIR_JUMPED_TO_POINT="CORNERSTONE_TOOLS_WORLD_CROSSHAIR_JUMPED_TO_POINT",i.SLICE_INTERSECTION_LINE_SELECTED="CORNERSTONE_TOOLS_SLICE_INTERSECTION_LINE_SELECTED",i.SLICE_INTERSECTION_MANIPULATION_STARTED="CORNERSTONE_TOOLS_SLICE_INTERSECTION_MANIPULATION_STARTED",i.SLICE_INTERSECTION_MANIPULATION_ENDED="CORNERSTONE_TOOLS_SLICE_INTERSECTION_MANIPULATION_ENDED",i.SLICE_INTERSECTION_SLAB_THICKNESS_CHANGED="CORNERSTONE_TOOLS_SLICE_INTERSECTION_SLAB_THICKNESS_CHANGED",i.VOLUMECROPPINGCONTROL_TOOL_CHANGED="CORNERSTONE_TOOLS_VOLUMECROPPINGCONTROL_TOOL_CHANGED",i.VOLUMECROPPING_TOOL_CHANGED="CORNERSTONE_TOOLS_VOLUMECROPPING_TOOL_CHANGED",i.STACK_PREFETCH_COMPLETE="CORNERSTONE_TOOLS_STACK_PREFETCH_COMPLETE",i.ANNOTATION_ADDED="CORNERSTONE_TOOLS_ANNOTATION_ADDED",i.ANNOTATION_COMPLETED="CORNERSTONE_TOOLS_ANNOTATION_COMPLETED",i.ANNOTATION_MODIFIED="CORNERSTONE_TOOLS_ANNOTATION_MODIFIED",i.ANNOTATION_REMOVED="CORNERSTONE_TOOLS_ANNOTATION_REMOVED",i.ANNOTATION_SELECTION_CHANGE="CORNERSTONE_TOOLS_ANNOTATION_SELECTION_CHANGE",i.ANNOTATION_LOCK_CHANGE="CORNERSTONE_TOOLS_ANNOTATION_LOCK_CHANGE",i.ANNOTATION_VISIBILITY_CHANGE="CORNERSTONE_TOOLS_ANNOTATION_VISIBILITY_CHANGE",i.ANNOTATION_RENDERED="CORNERSTONE_TOOLS_ANNOTATION_RENDERED",i.ANNOTATION_CUT_MERGE_PROCESS_COMPLETED="CORNERSTONE_TOOLS_ANNOTATION_CUT_MERGE_PROCESS_COMPLETED",i.ANNOTATION_INTERPOLATION_PROCESS_COMPLETED="CORNERSTONE_TOOLS_ANNOTATION_INTERPOLATION_PROCESS_COMPLETED",i.INTERPOLATED_ANNOTATIONS_REMOVED="CORNERSTONE_TOOLS_INTERPOLATED_ANNOTATIONS_REMOVED",i.SEGMENTATION_MODIFIED="CORNERSTONE_TOOLS_SEGMENTATION_MODIFIED",i.SEGMENTATION_RENDERED="CORNERSTONE_TOOLS_SEGMENTATION_RENDERED",i.SEGMENTATION_REPRESENTATION_ADDED="CORNERSTONE_TOOLS_SEGMENTATION_REPRESENTATION_ADDED",i.SEGMENTATION_ADDED="CORNERSTONE_TOOLS_SEGMENTATION_ADDED",i.SEGMENTATION_REPRESENTATION_MODIFIED="CORNERSTONE_TOOLS_SEGMENTATION_REPRESENTATION_MODIFIED",i.SEGMENTATION_REMOVED="CORNERSTONE_TOOLS_SEGMENTATION_REMOVED",i.SEGMENTATION_REPRESENTATION_REMOVED="CORNERSTONE_TOOLS_SEGMENTATION_REPRESENTATION_REMOVED",i.SEGMENTATION_DATA_MODIFIED="CORNERSTONE_TOOLS_SEGMENTATION_DATA_MODIFIED",i.HISTORY_UNDO="CORNERSTONE_TOOLS_HISTORY_UNDO",i.HISTORY_REDO="CORNERSTONE_TOOLS_HISTORY_REDO",i.KEY_DOWN="CORNERSTONE_TOOLS_KEY_DOWN",i.KEY_UP="CORNERSTONE_TOOLS_KEY_UP",i.MOUSE_DOWN="CORNERSTONE_TOOLS_MOUSE_DOWN",i.MOUSE_UP="CORNERSTONE_TOOLS_MOUSE_UP",i.MOUSE_DOWN_ACTIVATE="CORNERSTONE_TOOLS_MOUSE_DOWN_ACTIVATE",i.MOUSE_DRAG="CORNERSTONE_TOOLS_MOUSE_DRAG",i.MOUSE_MOVE="CORNERSTONE_TOOLS_MOUSE_MOVE",i.MOUSE_CLICK="CORNERSTONE_TOOLS_MOUSE_CLICK",i.MOUSE_DOUBLE_CLICK="CORNERSTONE_TOOLS_MOUSE_DOUBLE_CLICK",i.MOUSE_WHEEL="CORNERSTONE_TOOLS_MOUSE_WHEEL",i.TOUCH_START="CORNERSTONE_TOOLS_TOUCH_START",i.TOUCH_START_ACTIVATE="CORNERSTONE_TOOLS_TOUCH_START_ACTIVATE",i.TOUCH_PRESS="CORNERSTONE_TOOLS_TOUCH_PRESS",i.TOUCH_DRAG="CORNERSTONE_TOOLS_TOUCH_DRAG",i.TOUCH_END="CORNERSTONE_TOOLS_TOUCH_END",i.TOUCH_TAP="CORNERSTONE_TOOLS_TAP",i.TOUCH_SWIPE="CORNERSTONE_TOOLS_SWIPE"})(E||(E={}));var St;(function(i){i.Labelmap="Labelmap",i.Contour="Contour",i.Surface="Surface"})(St||(St={}));var ss;(function(i){i.UP="UP",i.DOWN="DOWN",i.LEFT="LEFT",i.RIGHT="RIGHT"})(ss||(ss={}));var dt;(function(i){i.CalculateCursorGeometry="calculateCursorGeometry",i.RenderCursor="renderCursor",i.OnInteractionStart="onInteractionStart",i.OnInteractionEnd="onInteractionEnd",i.Preview="preview",i.RejectPreview="rejectPreview",i.AcceptPreview="acceptPreview",i.Fill="fill",i.Interpolate="interpolate",i.StrategyFunction="strategyFunction",i.CreateIsInThreshold="createIsInThreshold",i.Initialize="initialize",i.INTERNAL_setValue="setValue",i.AddPreview="addPreview",i.ComputeInnerCircleRadius="computeInnerCircleRadius",i.GetStatistics="getStatistics",i.EnsureImageVolumeFor3DManipulation="ensureImageVolumeFor3DManipulation",i.EnsureSegmentationVolumeFor3DManipulation="ensureSegmentationVolumeFor3DManipulation"})(dt||(dt={}));var Bt;(function(i){i.Interaction="Interaction",i.HandlesUpdated="HandlesUpdated",i.StatsUpdated="StatsUpdated",i.InitialSetup="InitialSetup",i.Completed="Completed",i.InterpolationUpdated="InterpolationUpdated",i.History="History",i.MetadataReferenceModified="MetadataReferenceModified",i.LabelChange="LabelChange"})(Bt||(Bt={}));var no;(function(i){i.POLYSEG_CONTOUR_TO_LABELMAP="Converting Contour to Labelmap",i.POLYSEG_SURFACE_TO_LABELMAP="Converting Surfaces to Labelmap",i.POLYSEG_CONTOUR_TO_SURFACE="Converting Contour to Surface",i.POLYSEG_LABELMAP_TO_SURFACE="Converting Labelmap to Surface",i.SURFACE_CLIPPING="Clipping Surfaces",i.COMPUTE_STATISTICS="Computing Statistics",i.INTERPOLATE_LABELMAP="Interpolating Labelmap",i.COMPUTE_LARGEST_BIDIRECTIONAL="Computing Largest Bidirectional",i.GENERATE_CONTOUR_SETS="Generating Contour Sets"})(no||(no={}));var Io;(function(i){i.Linear="Linear",i.Area="Area",i.Volume="Volume",i.Pixel="Pixel"})(Io||(Io={}));const CG=Object.freeze(Object.defineProperty({__proto__:null,AnnotationStyleStates:To,ChangeTypes:Bt,Events:E,get KeyboardBindings(){return vn},get MeasurementType(){return Io},get MouseBindings(){return Fo},SegmentationRepresentations:St,StrategyCallbacks:dt,get Swipe(){return ss},ToolModes:se,WorkerTypes:no},Symbol.toStringTag,{value:"Module"}));let Vl={};function xb(){Vl={}}const Mg={isInteractingWithTool:!1,isMultiPartToolActive:!1,tools:{},toolGroups:[],synchronizers:[],svgNodeCache:Vl,enabledElements:[],handleRadius:6};let $={isInteractingWithTool:!1,isMultiPartToolActive:!1,tools:{},toolGroups:[],synchronizers:[],svgNodeCache:Vl,enabledElements:[],handleRadius:6};function Pb(){xb(),$={...Re({...Mg,svgNodeCache:{}}),svgNodeCache:{...Mg.svgNodeCache}}}var Gd,Ag;function Db(){if(Ag)return Gd;Ag=1;var i="Expected a function",t="__lodash_hash_undefined__",n="[object Function]",e="[object GeneratorFunction]",o="[object Symbol]",s=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,a=/^\w*$/,r=/^\./,c=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,l=/[\\^$.*+?()[\]{}|]/g,d=/\\(\\)?/g,u=/^\[object .+?Constructor\]$/,h=typeof Ic=="object"&&Ic&&Ic.Object===Object&&Ic,f=typeof self=="object"&&self&&self.Object===Object&&self,g=h||f||Function("return this")();function m(G,et){return G?.[et]}function p(G){var et=!1;if(G!=null&&typeof G.toString!="function")try{et=!!(G+"")}catch{}return et}var v=Array.prototype,I=Function.prototype,w=Object.prototype,C=g["__core-js_shared__"],S=(function(){var G=/[^.]+$/.exec(C&&C.keys&&C.keys.IE_PROTO||"");return G?"Symbol(src)_1."+G:""})(),b=I.toString,_=w.hasOwnProperty,y=w.toString,D=RegExp("^"+b.call(_).replace(l,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),T=g.Symbol,P=v.splice,x=Ht(g,"Map"),M=Ht(Object,"create"),L=T?T.prototype:void 0,R=L?L.toString:void 0;function U(G){var et=-1,at=G?G.length:0;for(this.clear();++et<at;){var jt=G[et];this.set(jt[0],jt[1])}}function W(){this.__data__=M?M(null):{}}function K(G){return this.has(G)&&delete this.__data__[G]}function j(G){var et=this.__data__;if(M){var at=et[G];return at===t?void 0:at}return _.call(et,G)?et[G]:void 0}function F(G){var et=this.__data__;return M?et[G]!==void 0:_.call(et,G)}function z(G,et){var at=this.__data__;return at[G]=M&&et===void 0?t:et,this}U.prototype.clear=W,U.prototype.delete=K,U.prototype.get=j,U.prototype.has=F,U.prototype.set=z;function q(G){var et=-1,at=G?G.length:0;for(this.clear();++et<at;){var jt=G[et];this.set(jt[0],jt[1])}}function J(){this.__data__=[]}function it(G){var et=this.__data__,at=te(et,G);if(at<0)return!1;var jt=et.length-1;return at==jt?et.pop():P.call(et,at,1),!0}function tt(G){var et=this.__data__,at=te(et,G);return at<0?void 0:et[at][1]}function ot(G){return te(this.__data__,G)>-1}function nt(G,et){var at=this.__data__,jt=te(at,G);return jt<0?at.push([G,et]):at[jt][1]=et,this}q.prototype.clear=J,q.prototype.delete=it,q.prototype.get=tt,q.prototype.has=ot,q.prototype.set=nt;function lt(G){var et=-1,at=G?G.length:0;for(this.clear();++et<at;){var jt=G[et];this.set(jt[0],jt[1])}}function rt(){this.__data__={hash:new U,map:new(x||q),string:new U}}function ut(G){return Ut(this,G).delete(G)}function Tt(G){return Ut(this,G).get(G)}function kt(G){return Ut(this,G).has(G)}function Pt(G,et){return Ut(this,G).set(G,et),this}lt.prototype.clear=rt,lt.prototype.delete=ut,lt.prototype.get=Tt,lt.prototype.has=kt,lt.prototype.set=Pt;function te(G,et){for(var at=G.length;at--;)if(Bo(G[at][0],et))return at;return-1}function Ie(G,et){et=Jt(et,G)?[et]:ce(et);for(var at=0,jt=et.length;G!=null&&at<jt;)G=G[Ve(et[at++])];return at&&at==jt?G:void 0}function re(G){if(!lo(G)||De(G))return!1;var et=yi(G)||p(G)?D:u;return et.test(Wo(G))}function Zt(G){if(typeof G=="string")return G;if(oi(G))return R?R.call(G):"";var et=G+"";return et=="0"&&1/G==-1/0?"-0":et}function ce(G){return co(G)?G:ln(G)}function Ut(G,et){var at=G.__data__;return Pe(et)?at[typeof et=="string"?"string":"hash"]:at.map}function Ht(G,et){var at=m(G,et);return re(at)?at:void 0}function Jt(G,et){if(co(G))return!1;var at=typeof G;return at=="number"||at=="symbol"||at=="boolean"||G==null||oi(G)?!0:a.test(G)||!s.test(G)||et!=null&&G in Object(et)}function Pe(G){var et=typeof G;return et=="string"||et=="number"||et=="symbol"||et=="boolean"?G!=="__proto__":G===null}function De(G){return!!S&&S in G}var ln=jn(function(G){G=st(G);var et=[];return r.test(G)&&et.push(""),G.replace(c,function(at,jt,je,dn){et.push(je?dn.replace(d,"$1"):jt||at)}),et});function Ve(G){if(typeof G=="string"||oi(G))return G;var et=G+"";return et=="0"&&1/G==-1/0?"-0":et}function Wo(G){if(G!=null){try{return b.call(G)}catch{}try{return G+""}catch{}}return""}function jn(G,et){if(typeof G!="function"||et&&typeof et!="function")throw new TypeError(i);var at=function(){var jt=arguments,je=et?et.apply(this,jt):jt[0],dn=at.cache;if(dn.has(je))return dn.get(je);var yo=G.apply(this,jt);return at.cache=dn.set(je,yo),yo};return at.cache=new(jn.Cache||lt),at}jn.Cache=lt;function Bo(G,et){return G===et||G!==G&&et!==et}var co=Array.isArray;function yi(G){var et=lo(G)?y.call(G):"";return et==n||et==e}function lo(G){var et=typeof G;return!!G&&(et=="object"||et=="function")}function xi(G){return!!G&&typeof G=="object"}function oi(G){return typeof G=="symbol"||xi(G)&&y.call(G)==o}function st(G){return G==null?"":Zt(G)}function Mt(G,et,at){var jt=G==null?void 0:Ie(G,et);return jt===void 0?at:jt}return Gd=Mt,Gd}var Tb=Db();const Mb=fb(Tb),Lg=Symbol("DefinedCursors"),kv=new Set(["alias","all-scroll","auto","cell","col-resize","context-menu","copy","crosshair","default","e-resize","ew-resize","grab","grabbing","help","move","ne-resize","nesw-resize","no-drop","none","not-allowed","n-resize","ns-resize","nw-resize","nwse-resize","pointer","progress","row-resize","se-resize","s-resize","sw-resize","text","vertical-text","wait","w-resize","zoom-in","zoom-out"]);class An{constructor(t,n){this.name=t+"",this.fallback=n}getName(){return this.name+""}addFallbackStyleProperty(t){const{fallback:n}=this;return n instanceof An?`${t}, ${n.getStyleProperty()}`:t+""}getStyleProperty(){return this.addFallbackStyleProperty(this.name)+""}static getDefinedCursor(t){const n=Og(An,Lg);let e=n.get(t);if(e instanceof An)return e;if(kv.has(t))return e=new An(t),n.set(t,e),e}static setDefinedCursor(t,n){return n instanceof An?(Og(An,Lg).set(t,n),!0):!1}}function Og(i,t){let n=i[t];return n instanceof Map||(n=new Map,Object.defineProperty(i,t,{value:n})),n}const Ab=kv.values(),Lb="image-cursor";class vr extends An{constructor(t,n,e,o,s){super(o||vr.getUniqueInstanceName(Lb),s),this.url=t,this.x=Number(n)||0,this.y=Number(e)||0}getStyleProperty(){const{url:t,x:n,y:e}=this;let o=`url('${t}')`;return n>=0&&e>=0&&(n>0||e>0)&&(o+=` ${n} ${e}`),this.addFallbackStyleProperty(o)}static getUniqueInstanceName(t){return`${t}-${sb(vr)}`}}const he={iconContent:"",iconSize:16,viewBox:{x:16,y:16},mousePoint:{x:8,y:8},mousePointerGroupString:`
|
|
2
|
+
<path stroke="{{color}}" d="M8 16L8 0"></path>
|
|
3
|
+
<path stroke="{{color}}" d="M16 8L0 8"></path>
|
|
4
|
+
`},Xn={x:127,y:60},As=`
|
|
5
|
+
<rect fill="{{color}}" x="80.19" y="25.03" width="47.14" height="15.85"/>
|
|
6
|
+
`,Ti=`
|
|
7
|
+
<rect fill="{{color}}" x="80.19" y="25.03" width="47.14" height="15.85"/>
|
|
8
|
+
<rect fill="{{color}}" x="95.84" y="9.38" width="15.85" height="47.14"/>
|
|
9
|
+
`,wc='<path fill="{{color}}" d="M82.89,10a12.09,12.09,0,0,0-16.8-2.5l-27.5,20.4-8.5-6.3a2.93,2.93,0,0,1-1.1-3,14.66,14.66,0,0,0,.1-6.6,14.08,14.08,0,1,0-6.5,15.2,2.87,2.87,0,0,1,3.2.2l8.2,6.1-8.2,6.1a2.87,2.87,0,0,1-3.2.2,14.16,14.16,0,1,0,6.7,14.4,14,14,0,0,0-.3-5.8,2.93,2.93,0,0,1,1.1-3l8.5-6.3,27.5,20.4A11.91,11.91,0,0,0,82.89,57l-31.7-23.5ZM15.29,21a5.9,5.9,0,1,1,5.9-5.9A5.91,5.91,0,0,1,15.29,21Zm0,36.8a5.9,5.9,0,1,1,5.9-5.9A5.91,5.91,0,0,1,15.29,57.77Zm28.3-21.5a2.8,2.8,0,1,1,2.8-2.8A2.8,2.8,0,0,1,43.59,36.27Z" transform="translate(-1.17 -0.96)"/>',Ls='<path fill="{{color}}" d="M8.86,2.25V66.08H72.69V2.25H8.86ZM65.28,58.67h-49v-49h49v49Z" transform="translate(-8.86 -2.25)"/>',Ec='<path fill="{{color}}" d="M40.77,2.25A31.92,31.92,0,1,0,72.69,34.16,31.92,31.92,0,0,0,40.77,2.25Zm0,57.63A25.71,25.71,0,1,1,66.48,34.16,25.71,25.71,0,0,1,40.77,59.87Z" transform="translate(-8.86 -2.25)"/>',Fl={Angle:fe(he,{name:"Angle",iconContent:`<path fill="{{color}}" d="M1203 544q0 13-10 23l-393 393 393 393q10 10 10 23t-10 23l-50
|
|
10
|
+
50q-10 10-23 10t-23-10l-466-466q-10-10-10-23t10-23l466-466q10-10 23-10t23
|
|
11
|
+
10l50 50q10 10 10 23z" />`,viewBox:{x:1792,y:1792}}),ArrowAnnotate:fe(he,{name:"ArrowAnnotate",iconContent:`<g id="arrowAnnotate-group" fill="none" stroke-width="1" stroke="{{color}}" stroke-linecap="round" stroke-linejoin="round">
|
|
12
|
+
<path id="arrowAnnotate-arrow" d="M23,7 l-15,15 M7,17 l0,6 6,0" stroke-width="2" />
|
|
13
|
+
</g>`,viewBox:{x:24,y:24}}),Bidirectional:fe(he,{name:"Bidirectional",iconContent:`<g fill="{{color}}" stroke-width="3" stroke="{{color}}">
|
|
14
|
+
<path d="M27.63 3.21L3.12 28.81"></path>
|
|
15
|
+
<path d="M27.63 15.75L15.27 4.43"></path>
|
|
16
|
+
<path d="M16.5 4.28C16.5 4.96 15.95 5.51 15.27 5.51C14.59 5.51 14.03 4.96 14.03 4.28C14.03 3.59 14.59 3.04 15.27 3.04C15.95 3.04 16.5 3.59 16.5 4.28Z" ></path>
|
|
17
|
+
<path d="M28.87 3.19C28.87 3.87 28.31 4.43 27.63 4.43C26.95 4.43 26.4 3.87 26.4 3.19C26.4 2.51 26.95 1.95 27.63 1.95C28.31 1.95 28.87 2.51 28.87 3.19Z"></path>
|
|
18
|
+
<path d="M28.87 15.75C28.87 16.43 28.31 16.99 27.63 16.99C26.95 16.99 26.4 16.43 26.4 15.75C26.4 15.07 26.95 14.51 27.63 14.51C28.31 14.51 28.87 15.07 28.87 15.75Z"></path>
|
|
19
|
+
<path d="M4.73 28.44C4.73 29.12 4.17 29.68 3.49 29.68C2.81 29.68 2.25 29.12 2.25 28.44C2.25 27.76 2.81 27.2 3.49 27.2C4.17 27.2 4.73 27.76 4.73 28.44Z"></path>
|
|
20
|
+
</g>`,viewBox:{x:48,y:48}}),CobbAngle:fe(he,{name:"CobbAngle",iconContent:`<g stroke="{{color}}" stroke-width="3">
|
|
21
|
+
<path d="M28.59 2.34L3.82 12.32"></path>
|
|
22
|
+
<path d="M28.59 29.66L3.82 19.68"></path>
|
|
23
|
+
<path stroke-dasharray="2" fill-opacity="0" d="M12.37
|
|
24
|
+
23.06C12.67 22.36 12.85 21.93 12.92 21.76C14.6 17.8 14.68 13.35 13.15
|
|
25
|
+
9.33C13.11 9.24 13.02 9 12.88 8.63">
|
|
26
|
+
</path>
|
|
27
|
+
</g>`,viewBox:{x:32,y:32}}),CircleROI:fe(he,{name:"CircleROI",iconContent:'<circle stroke="{{color}}" fill="none" stroke-width="3" cx="16" cy="16" r="14" />',viewBox:{x:32,y:32}}),EllipticalROI:fe(he,{name:"EllipticalROI",iconContent:`<path stroke="{{color}}" fill="none" stroke-width="3" d="M30.74 15.76C30.74 20.99 24.14 25.23 16
|
|
28
|
+
25.23C7.86 25.23 1.26 20.99 1.26 15.76C1.26 10.54 7.86 6.3 16 6.3C24.14
|
|
29
|
+
6.3 30.74 10.54 30.74 15.76Z" />`,viewBox:{x:32,y:32}}),FreehandROI:fe(he,{name:"FreehandROI",iconContent:`<g fill="{{color}}" stroke="{{color}}" stroke-width="2">
|
|
30
|
+
<ellipse ry="1" rx="1" id="svg_3" cy="4.240343" cx="14.306499"/>
|
|
31
|
+
<line id="svg_4" y2="3.58462" x2="12.242186" y1="3.997482" x1="13.432202"/>
|
|
32
|
+
<line id="svg_5" y2="3.268901" x2="10.857882" y1="3.608906" x1="12.387902"/>
|
|
33
|
+
<line id="svg_6" y2="3.147471" x2="9.740724" y1="3.293187" x1="10.955026"/>
|
|
34
|
+
<line id="svg_7" y2="3.147471" x2="8.089274" y1="3.196043" x1="9.983585"/>
|
|
35
|
+
<line id="svg_8" y2="3.268901" x2="6.874972" y1="3.123185" x1="8.307848"/>
|
|
36
|
+
<line id="svg_9" y2="3.657478" x2="5.587812" y1="3.220329" x1="7.020688"/>
|
|
37
|
+
<line id="svg_10" y2="4.046054" x2="4.737801" y1="3.560334" x1="5.854959"/>
|
|
38
|
+
<line id="svg_11" y2="4.337487" x2="4.300652" y1="3.997482" x1="4.834945"/>
|
|
39
|
+
<line id="svg_12" y2="4.726063" x2="3.88779" y1="4.191771" x1="4.470655"/>
|
|
40
|
+
<line id="svg_15" y2="5.3575" x2="3.377783" y1="4.604633" x1="3.960648"/>
|
|
41
|
+
<line id="svg_16" y2="6.183226" x2="2.916348" y1="5.138926" x1="3.547785"/>
|
|
42
|
+
<line id="svg_17" y2="6.960379" x2="2.770632" y1="5.867507" x1="3.037779"/>
|
|
43
|
+
<line id="svg_18" y2="7.713246" x2="2.673488" y1="6.741804" x1="2.819204"/>
|
|
44
|
+
<line id="svg_19" y2="8.684687" x2="2.697774" y1="7.616102" x1="2.673488"/>
|
|
45
|
+
<line id="svg_20" y2="9.753273" x2="2.892062" y1="8.611829" x1="2.697774"/>
|
|
46
|
+
<line id="svg_21" y2="10.724714" x2="3.134923" y1="9.534698" x1="2.84349"/>
|
|
47
|
+
<line id="svg_23" y2="11.647583" x2="3.596357" y1="10.578998" x1="3.086351"/>
|
|
48
|
+
<line id="svg_25" y2="12.521881" x2="4.276366" y1="11.501867" x1="3.499213"/>
|
|
49
|
+
<line id="svg_26" y2="13.930471" x2="5.830673" y1="12.376165" x1="4.13065"/>
|
|
50
|
+
<line id="svg_28" y2="14.707624" x2="7.263549" y1="13.881899" x1="5.733528"/>
|
|
51
|
+
<line id="svg_29" y2="15.339061" x2="8.963571" y1="14.61048" x1="7.06926"/>
|
|
52
|
+
<line id="svg_30" y2="15.581921" x2="10.882168" y1="15.314775" x1="8.817855"/>
|
|
53
|
+
<line id="svg_31" y2="15.460491" x2="12.023612" y1="15.581921" x1="10.785024"/>
|
|
54
|
+
<line id="svg_33" y2="15.120487" x2="13.092197" y1="15.484777" x1="11.877895"/>
|
|
55
|
+
<line id="svg_34" y2="14.586194" x2="13.86935" y1="15.217631" x1="12.897909"/>
|
|
56
|
+
<line id="svg_35" y2="13.833327" x2="14.597931" y1="14.756196" x1="13.699348"/>
|
|
57
|
+
<line id="svg_37" y2="12.716169" x2="15.180796" y1="13.881899" x1="14.549359"/>
|
|
58
|
+
<line id="svg_39" y2="11.429009" x2="15.520801" y1="12.813313" x1="15.15651"/>
|
|
59
|
+
<ellipse ry="1" rx="1" id="svg_40" cy="10.967574" cx="15.520801"/>
|
|
60
|
+
</g>`,viewBox:{x:18,y:18}}),FreehandROISculptor:fe(he,{name:"FreehandROISculptor",iconContent:`<g id="icon-freehand-sculpt" fill="none" stroke-width="1.5" stroke="{{color}}" stroke-linecap="round" stroke-linejoin="round">
|
|
61
|
+
<line id="svg_1" y2="2.559367" x2="10.184807" y1="4.467781" x1="8.81711"/>
|
|
62
|
+
<line id="svg_4" y2="1.493836" x2="11.727442" y1="2.766112" x1="10.089386"/>
|
|
63
|
+
<line id="svg_7" y2="1.080346" x2="13.047428" y1="1.748291" x1="11.345759"/>
|
|
64
|
+
<line id="svg_8" y2="1.000829" x2="14.351511" y1="1.112153" x1="12.77707"/>
|
|
65
|
+
<line id="svg_9" y2="1.350705" x2="15.242104" y1="0.905408" x1="13.969828"/>
|
|
66
|
+
<line id="svg_10" y2="2.098167" x2="15.862339" y1="1.14396" x1="14.955842"/>
|
|
67
|
+
<line id="svg_11" y2="3.195505" x2="16.41896" y1="1.939133" x1="15.766918"/>
|
|
68
|
+
<line id="svg_12" y2="4.292843" x2="16.530284" y1="2.925147" x1="16.387153"/>
|
|
69
|
+
<line id="svg_16" y2="5.644637" x2="16.196311" y1="3.831643" x1="16.593898"/>
|
|
70
|
+
<line id="svg_18" y2="7.266789" x2="15.623787" y1="5.19934" x1="16.275829"/>
|
|
71
|
+
<line id="svg_19" y2="10.813258" x2="14.526449" y1="6.726071" x1="15.766918"/>
|
|
72
|
+
<line id="svg_20" y2="5.056209" x2="8.085552" y1="4.181519" x1="8.976145"/>
|
|
73
|
+
<line id="svg_23" y2="5.326568" x2="7.481221" y1="4.78585" x1="8.403621"/>
|
|
74
|
+
<line id="svg_24" y2="5.565119" x2="6.749662" y1="5.294761" x1="7.624352"/>
|
|
75
|
+
<line id="svg_25" y2="5.994512" x2="5.429675" y1="5.533312" x1="6.956407"/>
|
|
76
|
+
<line id="svg_27" y2="6.551133" x2="4.284627" y1="5.962706" x1="5.572807"/>
|
|
77
|
+
<line id="svg_28" y2="7.584858" x2="3.044158" y1="6.392099" x1="4.427758"/>
|
|
78
|
+
<line id="svg_29" y2="8.84123" x2="2.185372" y1="7.489437" x1="3.219096"/>
|
|
79
|
+
<line id="svg_31" y2="10.606513" x2="1.644654" y1="8.602678" x1="2.280792"/>
|
|
80
|
+
<line id="svg_32" y2="13.214679" x2="1.48562" y1="10.352058" x1="1.724171"/>
|
|
81
|
+
<line id="svg_33" y2="14.375631" x2="1.676461" y1="12.992031" x1="1.453813"/>
|
|
82
|
+
<line id="svg_34" y2="15.298031" x2="2.264889" y1="14.152983" x1="1.517427"/>
|
|
83
|
+
<line id="svg_35" y2="16.172721" x2="3.521261" y1="14.948155" x1="1.915013"/>
|
|
84
|
+
<line id="svg_36" y2="16.824762" x2="5.207027" y1="15.997783" x1="3.28271"/>
|
|
85
|
+
<line id="svg_38" y2="17.063314" x2="7.035924" y1="16.745245" x1="4.968475"/>
|
|
86
|
+
<line id="svg_39" y2="16.888376" x2="9.278311" y1="17.047411" x1="6.733758"/>
|
|
87
|
+
<line id="svg_40" y2="16.284045" x2="10.661911" y1="16.983797" x1="8.992048"/>
|
|
88
|
+
<line id="svg_41" y2="15.313934" x2="11.647925" y1="16.395369" x1="10.455166"/>
|
|
89
|
+
<line id="svg_44" y2="13.898527" x2="12.82478" y1="15.425259" x1="11.504794"/>
|
|
90
|
+
<line id="svg_45" y2="12.037824" x2="14.144766" y1="14.312017" x1="12.522614"/>
|
|
91
|
+
<line id="svg_47" y2="10.59061" x2="14.605966" y1="12.228665" x1="13.953925"/>
|
|
92
|
+
<ellipse ry="1" rx="1" id="svg_48" cy="3.982726" cx="13.460918"/>
|
|
93
|
+
</g>`,viewBox:{x:18,y:18}}),Length:fe(he,{name:"Length",iconContent:`<g id="length-group" fill="none" stroke-width="1" stroke="{{color}}" stroke-linecap="round" stroke-linejoin="round">
|
|
94
|
+
<path id="length-dashes" d="m22.5,6 -16.5,16.5" stroke-width="3" stroke-dasharray="0.6666,5" />
|
|
95
|
+
</g>`,viewBox:{x:24,y:24}}),Height:fe(he,{name:"Height",iconContent:'<path d="m 6 22 l 8.5 0 v -16 h 8" stroke-width="3" fill="none" stroke="{{color}}" />',viewBox:{x:24,y:24}}),Probe:fe(he,{name:"Probe",iconContent:`<path fill="{{color}}" d="M1152 896q0 106-75 181t-181 75-181-75-75-181 75-181 181-75 181 75
|
|
96
|
+
75 181zm-256-544q-148 0-273 73t-198 198-73 273 73 273 198 198 273 73 273-73
|
|
97
|
+
198-198 73-273-73-273-198-198-273-73zm768 544q0 209-103 385.5t-279.5
|
|
98
|
+
279.5-385.5 103-385.5-103-279.5-279.5-103-385.5 103-385.5 279.5-279.5
|
|
99
|
+
385.5-103 385.5 103 279.5 279.5 103 385.5z" />`,viewBox:{x:1792,y:1792}}),RectangleROI:fe(he,{name:"RectangleROI",iconContent:`<path fill="{{color}}" d="M1312 256h-832q-66 0-113 47t-47 113v832q0 66 47
|
|
100
|
+
113t113 47h832q66 0 113-47t47-113v-832q0-66-47-113t-113-47zm288 160v832q0
|
|
101
|
+
119-84.5 203.5t-203.5 84.5h-832q-119 0-203.5-84.5t-84.5-203.5v-832q0-119
|
|
102
|
+
84.5-203.5t203.5-84.5h832q119 0 203.5 84.5t84.5 203.5z" />`,viewBox:{x:1792,y:1792}}),Label:fe(he,{name:"Label",iconContent:`<path fill="{{color}}" d="M789 559l-170 450q33 0 136.5 2t160.5 2q19 0
|
|
103
|
+
57-2-87-253-184-452zm-725 1105l2-79q23-7 56-12.5t57-10.5 49.5-14.5 44.5-29
|
|
104
|
+
31-50.5l237-616 280-724h128q8 14 11 21l205 480q33 78 106 257.5t114 274.5q15
|
|
105
|
+
34 58 144.5t72 168.5q20 45 35 57 19 15 88 29.5t84 20.5q6 38 6 57 0 5-.5
|
|
106
|
+
13.5t-.5 12.5q-63 0-190-8t-191-8q-76 0-215 7t-178 8q0-43 4-78l131-28q1 0
|
|
107
|
+
12.5-2.5t15.5-3.5 14.5-4.5 15-6.5 11-8 9-11
|
|
108
|
+
2.5-14q0-16-31-96.5t-72-177.5-42-100l-450-2q-26 58-76.5 195.5t-50.5 162.5q0
|
|
109
|
+
22 14 37.5t43.5 24.5 48.5 13.5 57 8.5 41 4q1 19 1 58 0 9-2 27-58
|
|
110
|
+
0-174.5-10t-174.5-10q-8 0-26.5 4t-21.5 4q-80 14-188 14z" />`,viewBox:{x:1792,y:1792}}),Crosshairs:fe(he,{name:"Crosshairs",iconContent:`<path fill="{{color}}" d="M1325 1024h-109q-26 0-45-19t-19-45v-128q0-26
|
|
111
|
+
19-45t45-19h109q-32-108-112.5-188.5t-188.5-112.5v109q0 26-19 45t-45
|
|
112
|
+
19h-128q-26 0-45-19t-19-45v-109q-108 32-188.5 112.5t-112.5 188.5h109q26
|
|
113
|
+
0 45 19t19 45v128q0 26-19 45t-45 19h-109q32 108 112.5 188.5t188.5
|
|
114
|
+
112.5v-109q0-26 19-45t45-19h128q26 0 45 19t19 45v109q108-32
|
|
115
|
+
188.5-112.5t112.5-188.5zm339-192v128q0 26-19 45t-45 19h-143q-37 161-154.5
|
|
116
|
+
278.5t-278.5 154.5v143q0 26-19 45t-45 19h-128q-26
|
|
117
|
+
0-45-19t-19-45v-143q-161-37-278.5-154.5t-154.5-278.5h-143q-26
|
|
118
|
+
0-45-19t-19-45v-128q0-26 19-45t45-19h143q37-161
|
|
119
|
+
154.5-278.5t278.5-154.5v-143q0-26 19-45t45-19h128q26 0 45 19t19 45v143q161
|
|
120
|
+
37 278.5 154.5t154.5 278.5h143q26 0 45 19t19 45z" />`,viewBox:{x:1792,y:1792}}),Eraser:fe(he,{name:"Eraser",iconContent:`<path transform="translate(0,1792) scale(1,-1)" fill="{{color}}" d="M960 1408l336-384h-768l-336 384h768zm1013-1077q15
|
|
121
|
+
34 9.5 71.5t-30.5 65.5l-896 1024q-38 44-96 44h-768q-38
|
|
122
|
+
0-69.5-20.5t-47.5-54.5q-15-34-9.5-71.5t30.5-65.5l896-1024q38-44 96-44h768q38
|
|
123
|
+
0 69.5 20.5t47.5 54.5z" />`,viewBox:{x:2048,y:1792}}),Magnify:fe(he,{name:"Magnify",iconContent:`<path fill="{{color}}" d="M508.5 481.6l-129-129c-2.3-2.3-5.3-3.5-8.5-3.5h-10.3C395
|
|
124
|
+
312 416 262.5 416 208 416 93.1 322.9 0 208 0S0 93.1 0 208s93.1 208 208 208c54.5
|
|
125
|
+
0 104-21 141.1-55.2V371c0 3.2 1.3 6.2 3.5 8.5l129 129c4.7 4.7 12.3 4.7 17
|
|
126
|
+
0l9.9-9.9c4.7-4.7 4.7-12.3 0-17zM208 384c-97.3 0-176-78.7-176-176S110.7 32 208
|
|
127
|
+
32s176 78.7 176 176-78.7 176-176 176z" />`,viewBox:{x:512,y:512}}),Pan:fe(he,{name:"Pan",iconContent:`<path fill="{{color}}" d="M1411 541l-355 355 355 355 144-144q29-31 70-14 39 17
|
|
128
|
+
39 59v448q0 26-19 45t-45 19h-448q-42 0-59-40-17-39 14-69l144-144-355-355-355
|
|
129
|
+
355 144 144q31 30 14 69-17 40-59 40h-448q-26 0-45-19t-19-45v-448q0-42 40-59
|
|
130
|
+
39-17 69 14l144 144 355-355-355-355-144 144q-19 19-45 19-12
|
|
131
|
+
0-24-5-40-17-40-59v-448q0-26 19-45t45-19h448q42 0 59 40 17 39-14 69l-144
|
|
132
|
+
144 355 355 355-355-144-144q-31-30-14-69 17-40 59-40h448q26 0 45 19t19
|
|
133
|
+
45v448q0 42-39 59-13 5-25 5-26 0-45-19z" />`,viewBox:{x:1792,y:1792}}),Rotate:fe(he,{name:"Rotate",iconContent:`<path fill="{{color}}" d="M1664 256v448q0 26-19 45t-45 19h-448q-42 0-59-40-17-39
|
|
134
|
+
14-69l138-138q-148-137-349-137-104 0-198.5 40.5t-163.5 109.5-109.5
|
|
135
|
+
163.5-40.5 198.5 40.5 198.5 109.5 163.5 163.5 109.5 198.5 40.5q119 0
|
|
136
|
+
225-52t179-147q7-10 23-12 15 0 25 9l137 138q9 8 9.5 20.5t-7.5 22.5q-109
|
|
137
|
+
132-264 204.5t-327 72.5q-156 0-298-61t-245-164-164-245-61-298 61-298
|
|
138
|
+
164-245 245-164 298-61q147 0 284.5 55.5t244.5 156.5l130-129q29-31 70-14
|
|
139
|
+
39 17 39 59z" />`,viewBox:{x:1792,y:1792}}),StackScroll:fe(he,{name:"StackScroll",iconContent:`<path fill="{{color}}" d="M24 21v2c0 0.547-0.453 1-1 1h-22c-0.547
|
|
140
|
+
0-1-0.453-1-1v-2c0-0.547 0.453-1 1-1h22c0.547 0 1 0.453 1 1zM24 13v2c0
|
|
141
|
+
0.547-0.453 1-1 1h-22c-0.547 0-1-0.453-1-1v-2c0-0.547 0.453-1 1-1h22c0.547
|
|
142
|
+
0 1 0.453 1 1zM24 5v2c0 0.547-0.453 1-1 1h-22c-0.547
|
|
143
|
+
0-1-0.453-1-1v-2c0-0.547 0.453-1 1-1h22c0.547 0 1 0.453 1 1z" />`,viewBox:{x:24,y:28}}),WindowLevelRegion:fe(he,{name:"WindowLevelRegion",iconContent:`<path fill="{{color}}" d="M1664 416v960q0 119-84.5 203.5t-203.5 84.5h-960q-119
|
|
144
|
+
0-203.5-84.5t-84.5-203.5v-960q0-119 84.5-203.5t203.5-84.5h960q119 0 203.5
|
|
145
|
+
84.5t84.5 203.5z" />`,viewBox:{x:1792,y:1792}}),WindowLevel:fe(he,{name:"WindowLevel",iconContent:`
|
|
146
|
+
<path fill="{{color}}" d="M14.5,3.5 a1 1 0 0 1 -11,11 Z" stroke="none" opacity="0.8" />
|
|
147
|
+
<circle cx="9" cy="9" r="8" fill="none" stroke-width="2" stroke="{{color}}" />`,viewBox:{x:18,y:18}}),Zoom:fe(he,{name:"Zoom",iconContent:`
|
|
148
|
+
<path fill="{{color}}" d="M508.5 481.6l-129-129c-2.3-2.3-5.3-3.5-8.5-3.5h-10.3C395
|
|
149
|
+
312 416 262.5 416 208 416 93.1 322.9 0 208 0S0 93.1 0 208s93.1 208 208 208c54.5
|
|
150
|
+
0 104-21 141.1-55.2V371c0 3.2 1.3 6.2 3.5 8.5l129 129c4.7 4.7 12.3 4.7 17
|
|
151
|
+
0l9.9-9.9c4.7-4.7 4.7-12.3 0-17zM208 384c-97.3 0-176-78.7-176-176S110.7 32 208
|
|
152
|
+
32s176 78.7 176 176-78.7 176-176 176z" />
|
|
153
|
+
<path fill="{{color}}" transform="scale(0.22,0.22) translate(1400,0)" d="M1216
|
|
154
|
+
320q0 26-19 45t-45 19h-128v1024h128q26 0 45 19t19 45-19 45l-256 256q-19
|
|
155
|
+
19-45 19t-45-19l-256-256q-19-19-19-45t19-45 45-19h128v-1024h-128q-26
|
|
156
|
+
0-45-19t-19-45 19-45l256-256q19-19 45-19t45 19l256 256q19 19 19 45z" />`,viewBox:{x:640,y:512}}),SegmentationFreeHandEraseInside:fe(he,{name:"SegmentationFreeHandEraseInside",iconContent:`${wc} ${As}`,viewBox:Xn}),SegmentationFreeHandFillInside:fe(he,{name:"SegmentationFreeHandFillInside",iconContent:`${wc} ${Ti}`,viewBox:Xn}),SegmentationFreeHandEraseOutside:fe(he,{name:"SegmentationFreeHandEraseOutside",iconContent:`${wc} ${As}`,viewBox:Xn}),SegmentationFreeHandFillOutside:fe(he,{name:"SegmentationFreeHandFillOutside",iconContent:`${wc} ${Ti}`,viewBox:Xn}),SegmentationRectangleEraseInside:fe(he,{name:"SegmentationRectangleEraseInside",iconContent:`${Ls} ${As}`,viewBox:Xn}),RectangleScissor:fe(he,{name:"RectangleScissor",iconContent:`${Ls} ${Ti}`,viewBox:Xn}),"RectangleScissor.FILL_INSIDE":fe(he,{name:"RectangleScissor.FILL_INSIDE",iconContent:`${Ls} ${Ti}`,viewBox:Xn}),"RectangleScissor.FILL_OUTSIDE":fe(he,{name:"RectangleScissor.FILL_OUTSIDE",iconContent:`${Ls} ${Ti}`,viewBox:Xn}),"RectangleScissor.ERASE_OUTSIDE":fe(he,{name:"RectangleScissor.ERASE_OUTSIDE",iconContent:`${Ls} ${As}`,viewBox:Xn}),"RectangleScissor.ERASE_INSIDE":fe(he,{name:"RectangleScissor.ERASE_INSIDE",iconContent:`${Ls} ${As}`,viewBox:Xn}),CircleScissor:fe(he,{name:"CircleScissor",iconContent:`${Ec} ${Ti}`,viewBox:Xn}),"CircleScissor.FILL_INSIDE":fe(he,{name:"CircleScissor.FILL_INSIDE",iconContent:`${Ec} ${Ti}`,viewBox:Xn}),"CircleScissor.ERASE_OUTSIDE":fe(he,{name:"CircleScissor.ERASE_OUTSIDE",iconContent:`${Ec} ${As}`,viewBox:Xn}),"CircleScissor.FILL_OUTSIDE":fe(he,{name:"CircleScissor.FILL_OUTSIDE",iconContent:`${Ec} ${Ti}`,viewBox:Xn})};function fe(i,t){return Object.assign(Object.create(i),{...t,name:t.name||i.name})}function Ob(i,t,n){Fl[i]=fe(he,{iconContent:t,viewBox:n})}function Rb(i){return Fl[i]}const Nb=Object.keys(Fl);class kb{constructor(){const t={color:"rgb(255, 255, 0)",colorHighlighted:"rgb(0, 255, 0)",colorSelected:"rgb(0, 220, 0)",colorLocked:"rgb(209, 193, 90)",lineWidth:"1",lineDash:"",shadow:!0,textBoxVisibility:!0,textBoxFontFamily:"Helvetica Neue, Helvetica, Arial, sans-serif",textBoxFontSize:"14px",textBoxColor:"rgb(255, 255, 0)",textBoxColorHighlighted:"rgb(0, 255, 0)",textBoxColorSelected:"rgb(0, 255, 0)",textBoxColorLocked:"rgb(209, 193, 90)",textBoxBackground:"",textBoxLinkLineWidth:"1",textBoxLinkLineDash:"2,3",textBoxShadow:!0,markerSize:"10",angleArcLineDash:""};this._initializeConfig(t)}getAnnotationToolStyles(t){return this.config.annotations&&this.config.annotations[t]}getViewportToolStyles(t){return this.config.viewports&&this.config.viewports[t]}getToolGroupToolStyles(t){return this.config.toolGroups&&this.config.toolGroups[t]}getDefaultToolStyles(){return this.config.default}setAnnotationStyles(t,n){let e=this.config.annotations;e||(this.config={...this.config,annotations:{}},e=this.config.annotations),e[t]=n}setViewportToolStyles(t,n){let e=this.config.viewports;e||(this.config={...this.config,viewports:{}},e=this.config.viewports),e[t]=n}setToolGroupToolStyles(t,n){let e=this.config.toolGroups;e||(this.config={...this.config,toolGroups:{}},e=this.config.toolGroups),e[t]=n}setDefaultToolStyles(t){this.config.default=t}getStyleProperty(t,n){const{annotationUID:e,viewportId:o,toolGroupId:s,toolName:a}=n;return this._getToolStyle(t,e,o,s,a)}_getToolStyle(t,n,e,o,s){if(n){const r=this.getAnnotationToolStyles(n);if(r&&r[t]!==void 0)return r[t]}if(e){const r=this.getViewportToolStyles(e);if(r){if(r[s]&&r[s][t]!==void 0)return r[s][t];if(r.global&&r.global[t]!==void 0)return r.global[t]}}if(o){const r=this.getToolGroupToolStyles(o);if(r){if(r[s]&&r[s][t]!==void 0)return r[s][t];if(r.global&&r.global[t]!==void 0)return r.global[t]}}const a=this.getDefaultToolStyles();if(a[s]&&a[s][t]!==void 0)return a[s][t];if(a.global&&a.global[t]!==void 0)return a.global[t]}_initializeConfig(t){const n={};for(const e in t)n[e]=t[e];this.config={default:{global:n}}}}const Nh=new kb;function Ub(i,t,n){const e=[`${i}`];return t&&e.push(`${e[0]}${t}`),n&&e.push(`${e[e.length-1]}${n}`),e}function Nn(i,t,n,e){const o=Ub(i,n,e);for(let s=o.length-1;s>=0;--s){const a=Nh.getStyleProperty(o[s],t);if(a!==void 0)return a}}const Vb="color",Fb=To.Highlighted,Gb=se.Active;class Qs extends vr{constructor(t,n,e,o,s){super(t,n,e,o,s)}static getDefinedCursor(t,n=!1,e){e||(e=Nn(Vb,{},Fb,Gb));const o=Hb(t,n,e);let s=super.getDefinedCursor(o);const a=Number(Nn("pointerStrokeWidth",{}));if(!s){const r=Rb(t);r&&(s=Wb(r,o,n,e,a,super.getDefinedCursor("default")),super.setDefinedCursor(o,s))}return s}}function Uv(i,t){const n=Object(t),e=Object.prototype.hasOwnProperty.bind(n);return(i+"").replace(/\{\{(\w+)\}\}/g,(o,s)=>e(s)?n[s]+"":"")}function Hb(i,t,n){return`${t?"pointer":"cursor"}:${i}/${n}`}function Wb(i,t,n,e,o,s){const{x:a,y:r}=i.mousePoint;return new Qs(Bb(i,n,{color:e,pointerStrokeWidth:o}),a,r,t,s)}function Bb(i,t,n){const e=zb(i,t,n);return`${URL.createObjectURL(e)}#${i.name||"unknown"}-${t?"pointer":"cursor"}`}function zb(i,t,n){const e=(t?jb:$b)(i,n);return new Blob([e],{type:"image/svg+xml"})}function $b(i,t){const{iconContent:n,iconSize:e,viewBox:o}=i,s=`
|
|
157
|
+
<svg data-icon="cursor" role="img" xmlns="http://www.w3.org/2000/svg"
|
|
158
|
+
width="${e}" height="${e}" viewBox="0 0
|
|
159
|
+
${o.x} ${o.y}">
|
|
160
|
+
${n}
|
|
161
|
+
</svg>`;return Uv(s,t)}function jb(i,t){const{iconContent:n,iconSize:e,viewBox:o,mousePointerGroupString:s}=i,a=e/Math.max(o.x,o.y,1),r=16+e,c=t.pointerStrokeWidth||1,l=`
|
|
162
|
+
<svg data-icon="cursor" role="img" xmlns="http://www.w3.org/2000/svg"
|
|
163
|
+
width="${r}" height="${r}" viewBox="0 0 ${r} ${r}">
|
|
164
|
+
<g stroke-width="${c}">${s}</g>
|
|
165
|
+
<g transform="translate(16, 16) scale(${a})">${n}</g>
|
|
166
|
+
</svg>`;return Uv(l,t)}const Rg=Symbol("ElementCursorsMap");function Vv(i,t){Ir(i)[0]=t,Kr(i,t)}function Kr(i,t){const n=Ir(i);n[1]=n[0],n[0]=t,i.style.cursor=(t instanceof An?t:An.getDefinedCursor("auto")).getStyleProperty()}function Ft(i){Kr(i,Ir(i)[1])}function wt(i){Kr(i,An.getDefinedCursor("none"))}function Ir(i){let t=Ir[Rg];t instanceof WeakMap||(t=new WeakMap,Object.defineProperty(Ir,Rg,{value:t}));let n=t.get(i);return n||(n=[null,null],t.set(i,n)),n}const Xb=Object.freeze(Object.defineProperty({__proto__:null,hideElementCursor:wt,initElementCursor:Vv,resetElementCursor:Ft,setElementCursor:Kr},Symbol.toStringTag,{value:"Module"}));function qb(i,t){let n=Qs.getDefinedCursor(t,!0);n||(n=An.getDefinedCursor(t)),n||(console.log(`Cursor ${t} is not defined either as SVG or as a standard cursor.`),n=An.getDefinedCursor(t)),Kr(i,n)}const Yb=[...Nb,...Ab],bG=Object.freeze(Object.defineProperty({__proto__:null,CursorNames:Yb,CursorSVG:Fl,ImageMouseCursor:vr,MouseCursor:An,SVGMouseCursor:Qs,elementCursor:Xb,registerCursor:Ob,setCursorForElement:qb},Symbol.toStringTag,{value:"Module"}));function Be(i){return $.toolGroups.find(t=>t.id===i)}const{Active:Ha,Passive:Hd,Enabled:Wd,Disabled:Bd}=se,Kb=[{mouseButton:Fo.Primary}];class kh{constructor(t){this.viewportsInfo=[],this.toolOptions={},this.currentActivePrimaryToolName=null,this.prevActivePrimaryToolName=null,this.restoreToolOptions={},this._toolInstances={},this.id=t}getViewportIds(){return this.viewportsInfo.map(({viewportId:t})=>t)}getViewportsInfo(){return this.viewportsInfo.slice()}getToolInstance(t){const n=this._toolInstances[t];if(!n){console.warn(`'${t}' is not registered with this toolGroup (${this.id}).`);return}return n}getToolInstances(){return this._toolInstances}hasTool(t){return!!this._toolInstances[t]}addTool(t,n={}){const e=$.tools[t],o=typeof t<"u"&&t!=="",s=this.toolOptions[t];if(!o){console.warn("Tool with configuration did not produce a toolName: ",n);return}if(!e){console.warn(`'${t}' is not registered with the library. You need to use cornerstoneTools.addTool to register it.`);return}if(s){console.warn(`'${t}' is already registered for ToolGroup ${this.id}.`);return}const{toolClass:a}=e,r={name:t,toolGroupId:this.id,configuration:n},c=new a(r);this._toolInstances[t]=c}addToolInstance(t,n,e={}){let o=$.tools[t]?.toolClass;if(!o){const s=$.tools[n].toolClass;class a extends s{}a.toolName=t,o=a,$.tools[t]={toolClass:a}}this.addTool(o.toolName,e)}addViewport(t,n){if(typeof t!="string")throw new Error("viewportId must be defined and be a string");const e=this._findRenderingEngine(t,n);this.viewportsInfo.some(({viewportId:a})=>a===t)||this.viewportsInfo.push({viewportId:t,renderingEngineId:e});const o=this.getActivePrimaryMouseButtonTool();this.setViewportsCursorByToolName(o);const s={toolGroupId:this.id,viewportId:t,renderingEngineId:e};Rt(Z,E.TOOLGROUP_VIEWPORT_ADDED,s)}removeViewports(t,n){const e=[];if(this.viewportsInfo.forEach((s,a)=>{let r=!1;s.renderingEngineId===t&&(r=!0,n&&s.viewportId!==n&&(r=!1)),r&&e.push(a)}),e.length)for(let s=e.length-1;s>=0;s--)this.viewportsInfo.splice(e[s],1);const o={toolGroupId:this.id,viewportId:n,renderingEngineId:t};Rt(Z,E.TOOLGROUP_VIEWPORT_REMOVED,o)}setActiveStrategy(t,n){const e=this._toolInstances[t];if(e===void 0){console.warn(`Tool ${t} not added to toolGroup, can't set tool configuration.`);return}e.setActiveStrategy(n)}setToolMode(t,n,e={}){if(!t){console.warn("setToolMode: toolName must be defined");return}if(n===se.Active){this.setToolActive(t,e||this.restoreToolOptions[t]);return}if(n===se.Passive){this.setToolPassive(t);return}if(n===se.Enabled){this.setToolEnabled(t);return}if(n===se.Disabled){this.setToolDisabled(t);return}console.warn("setToolMode: mode must be defined")}setToolActive(t,n={}){const e=this._toolInstances[t];if(e===void 0){console.warn(`Tool ${t} not added to toolGroup, can't set tool mode.`);return}if(!e){console.warn(`'${t}' instance ${e} is not registered with this toolGroup, can't set tool mode.`);return}const o=this.toolOptions[t]?this.toolOptions[t].bindings:[],s=n.bindings?n.bindings:[],r={bindings:[...o,...s].reduce((l,d)=>{const u=d.numTouchPoints!==void 0,h=d.mouseButton!==void 0;return!l.some(f=>zd(f,d))&&(u||h)&&l.push(d),l},[]),mode:Ha};if(this.toolOptions[t]=r,this._toolInstances[t].mode=Ha,this._hasMousePrimaryButtonBinding(n))this.setViewportsCursorByToolName(t),e.isPrimary=!0;else{if(!this.getActivePrimaryMouseButtonTool()){const d=An.getDefinedCursor("default");this._setCursorForViewports(d)}e.isPrimary=!1}this._hasMousePrimaryButtonBinding(n)&&(this.prevActivePrimaryToolName===null?this.prevActivePrimaryToolName=t:this.prevActivePrimaryToolName=this.currentActivePrimaryToolName,this.currentActivePrimaryToolName=t),typeof e.onSetToolActive=="function"&&e.onSetToolActive(),this._renderViewports();const c={toolGroupId:this.id,toolName:t,toolBindingsOptions:n};Rt(Z,E.TOOL_ACTIVATED,c),this._triggerToolModeChangedEvent(t,Ha,n)}setToolPassive(t,n){const e=this._toolInstances[t];if(e===void 0){console.warn(`Tool ${t} not added to toolGroup, can't set tool mode.`);return}const o=this.getToolOptions(t),s=Object.assign({bindings:o?o.bindings:[]},o,{mode:Hd}),a=Array.isArray(n?.removeAllBindings)?n.removeAllBindings:this.getDefaultPrimaryBindings();s.bindings=s.bindings.filter(c=>n?.removeAllBindings!==!0&&!a.some(l=>zd(c,l)));let r=Hd;s.bindings.length!==0&&(r=Ha,s.mode=r),this.toolOptions[t]=s,e.mode=r,e.isPrimary=!1,typeof e.onSetToolPassive=="function"&&e.onSetToolPassive(),this._renderViewports(),this._triggerToolModeChangedEvent(t,Hd)}setToolEnabled(t){const n=this._toolInstances[t];if(n===void 0){console.warn(`Tool ${t} not added to toolGroup, can't set tool mode.`);return}const e={bindings:[],mode:Wd};this.toolOptions[t]=e,n.mode=Wd,typeof n.onSetToolEnabled=="function"&&n.onSetToolEnabled(),this._renderViewports(),this._triggerToolModeChangedEvent(t,Wd)}setToolDisabled(t){const n=this._toolInstances[t];if(n===void 0){console.warn(`Tool ${t} not added to toolGroup, can't set tool mode.`);return}const e={bindings:[],mode:Bd};this.restoreToolOptions[t]=this.toolOptions[t],this.toolOptions[t]=e,n.mode=Bd,typeof n.onSetToolDisabled=="function"&&n.onSetToolDisabled(),this._renderViewports(),this._triggerToolModeChangedEvent(t,Bd)}getToolOptions(t){const n=this.toolOptions[t];if(n!==void 0)return n}getActivePrimaryMouseButtonTool(){return Object.keys(this.toolOptions).find(t=>{const n=this.toolOptions[t];return n.mode===Ha&&this._hasMousePrimaryButtonBinding(n)})}setViewportsCursorByToolName(t,n){const e=this._getCursor(t,n);this._setCursorForViewports(e)}_getCursor(t,n){let e,o;return n&&(e=`${t}.${n}`,o=Qs.getDefinedCursor(e,!0),o)||(e=`${t}`,o=Qs.getDefinedCursor(e,!0),o)||(e=t,o=Qs.getDefinedCursor(e,!0),o)?o:An.getDefinedCursor("default")}_setCursorForViewports(t){mv.getRuntimeSettings().get("useCursors")&&this.viewportsInfo.forEach(({renderingEngineId:e,viewportId:o})=>{const s=ae(o,e);if(!s)return;const{viewport:a}=s;Vv(a.element,t)})}setToolConfiguration(t,n,e){const o=this._toolInstances[t];if(o===void 0)return console.warn(`Tool ${t} not present, can't set tool configuration.`),!1;let s;return e?s=n:s=Object.assign(o.configuration,n),o.configuration=s,typeof o.onSetToolConfiguration=="function"&&o.onSetToolConfiguration(),this._renderViewports(),!0}getDefaultMousePrimary(){return Fo.Primary}getDefaultPrimaryBindings(){return Kb}getToolConfiguration(t,n){if(this._toolInstances[t]===void 0){console.warn(`Tool ${t} not present, can't set tool configuration.`);return}const e=Mb(this._toolInstances[t].configuration,n)||this._toolInstances[t].configuration;return Re(e)}getPrevActivePrimaryToolName(){return this.prevActivePrimaryToolName}setActivePrimaryTool(t){const n=this.getCurrentActivePrimaryToolName();this.setToolDisabled(n),this.setToolActive(t,{bindings:[{mouseButton:Fo.Primary}]})}getCurrentActivePrimaryToolName(){return this.currentActivePrimaryToolName}clone(t,n=null){let e=Be(t);return e?(console.debug(`ToolGroup ${t} already exists`),e):(e=new kh(t),$.toolGroups.push(e),n=n??(()=>!0),Object.keys(this._toolInstances).filter(n).forEach(o=>{const s=this._toolInstances[o],a=this.toolOptions[o],r=s.mode;e.addTool(o),e.setToolMode(o,r,{bindings:a?.bindings??[]})}),e)}_hasMousePrimaryButtonBinding(t){const n=this.getDefaultPrimaryBindings();return t?.bindings?.some(e=>n.some(o=>zd(e,o)))}_renderViewports(){this.viewportsInfo.forEach(({renderingEngineId:t,viewportId:n})=>{Ne(t).renderViewport(n)})}_triggerToolModeChangedEvent(t,n,e){const o={toolGroupId:this.id,toolName:t,mode:n,toolBindingsOptions:e};Rt(Z,E.TOOL_MODE_CHANGED,o)}_findRenderingEngine(t,n){const e=Vi();if(e?.length===0)throw new Error("No rendering engines found.");if(n)return n;const o=e.filter(s=>s.getViewport(t));if(o.length===0){if(e.length===1)return e[0].id;throw new Error("No rendering engines found that contain the viewport with the same viewportId, you must specify a renderingEngineId.")}if(o.length>1)throw new Error("Multiple rendering engines found that contain the viewport with the same viewportId, you must specify a renderingEngineId.");return o[0].id}}function zd(i,t){return i.mouseButton!==t.mouseButton||i.numTouchPoints!==t.numTouchPoints?!1:i.modifierKey===t.modifierKey}function Zb(i){if($.toolGroups.some(e=>e.id===i)){console.warn(`'${i}' already exists.`);return}const n=new kh(i);return $.toolGroups.push(n),n}function Fv(i){const t=$.toolGroups.findIndex(n=>n.id===i);t>-1&&$.toolGroups.splice(t,1)}function Gv(){const i=[...$.toolGroups];for(const t of i)Fv(t.id);$.toolGroups=[]}function Ae(i,t){t||(t=Vi().find(e=>e.getViewports().find(o=>o.id===i))?.id);const n=$.toolGroups.filter(e=>e.viewportsInfo.some(o=>o.renderingEngineId===t&&(!o.viewportId||o.viewportId===i)));if(n.length){if(n.length>1)throw new Error(`Multiple tool groups found for renderingEngineId: ${t} and viewportId: ${i}. You should only
|
|
167
|
+
have one tool group per viewport in a renderingEngine.`);return n[0]}}function Jb(){return $.toolGroups}const Qb=[se.Active,se.Passive,se.Enabled];function Hv(i){return $.toolGroups.filter(({toolOptions:t})=>{const n=Object.keys(t);for(let e=0;e<n.length;e++)if(i===n[e]&&t[i]&&Qb.includes(t[i].mode))return!0;return!1})}const t_=Object.freeze(Object.defineProperty({__proto__:null,createToolGroup:Zb,destroy:Gv,destroyToolGroup:Fv,getAllToolGroups:Jb,getToolGroup:Be,getToolGroupForViewport:Ae,getToolGroupsWithToolName:Hv},Symbol.toStringTag,{value:"Module"}));function Wv(i,t){const n=N(t),{renderingEngine:e,viewportId:o}=n,s=E.ANNOTATION_ADDED,a={annotation:i,viewportId:o,renderingEngineId:e.id};Rt(Z,s,a)}function Bv(i){const{toolName:t}=i.metadata,n=Hv(t);if(!n.length)return;const e=[];n.forEach(a=>{a.viewportsInfo.forEach(r=>{const{renderingEngineId:c,viewportId:l}=r,{FrameOfReferenceUID:d}=ae(l,c);i.metadata.FrameOfReferenceUID===d&&e.push(r)})});const o=E.ANNOTATION_ADDED,s={annotation:i};if(!e.length){Rt(Z,o,s);return}e.forEach(({renderingEngineId:a,viewportId:r})=>{s.viewportId=r,s.renderingEngineId=a,Rt(Z,o,s)})}function Gl(i){const t=E.ANNOTATION_REMOVED;Rt(Z,t,i)}function zt(i,t,n=Bt.HandlesUpdated){const e=t&&N(t),{viewportId:o,renderingEngineId:s}=e||{},a=E.ANNOTATION_MODIFIED;Rt(Z,a,{annotation:i,viewportId:o,renderingEngineId:s,changeType:n})}function ue(i){zv({annotation:i})}function Hl(i,t=!1){zv({annotation:i,contourHoleProcessingEnabled:t})}function zv(i){const t=E.ANNOTATION_COMPLETED;Rt(Z,t,i)}const e_=Object.freeze(Object.defineProperty({__proto__:null,triggerAnnotationAddedForElement:Wv,triggerAnnotationAddedForFOR:Bv,triggerAnnotationCompleted:ue,triggerAnnotationModified:zt,triggerAnnotationRemoved:Gl,triggerContourAnnotationCompleted:Hl},Symbol.toStringTag,{value:"Module"}));let $v;function Go(){return $v}function Uh(i){$v=i}function Yt(i,t){const n=Go(),e=n.getGroupKey(t);return n.getAnnotations(e,i)}function ne(i){return Go().getAnnotation(i)}function Ca(){return Go().getAllAnnotations()}function Wl(i){const{annotationUID:t,parentAnnotationUID:n}=i;if(!n)return;const e=ne(n),o=e.childAnnotationUIDs.indexOf(t);e.childAnnotationUIDs.splice(o,1),i.parentAnnotationUID=void 0}function Cs(i,t){const{annotationUID:n}=i,{annotationUID:e}=t;Wl(t),i.childAnnotationUIDs||(i.childAnnotationUIDs=[]),!i.childAnnotationUIDs.includes(e)&&(i.childAnnotationUIDs.push(e),t.parentAnnotationUID=n)}function jv(i){return i.parentAnnotationUID?ne(i.parentAnnotationUID):void 0}function Xi(i){return i.childAnnotationUIDs?.map(t=>ne(t))??[]}function Nt(i,t){i.annotationUID||(i.annotationUID=Se());const n=Go();if(t instanceof HTMLDivElement&&N(t)){const e=n.getGroupKey(t);n.addAnnotation(i,e),Wv(i,t)}else n.addAnnotation(i,void 0),Bv(i);return i.annotationUID}function n_(i,t){const n=Go(),e=n.getGroupKey(t);return n.getNumberOfAnnotations(e,i)}function Gt(i){if(!i)return;const t=Go(),n=t.getAnnotation(i);n&&(n.childAnnotationUIDs?.forEach(e=>Gt(e)),t.removeAnnotation(i),Gl({annotation:n,annotationManagerUID:t.uid}))}function o_(){const i=Go(),t=i.removeAllAnnotations();for(const n of t)Gl({annotation:n,annotationManagerUID:i.uid})}function i_(i,t){const n=Go(),e=n.getGroupKey(t),o=n.removeAnnotations(e,i);for(const s of o)Gl({annotation:s,annotationManagerUID:n.uid})}function Vh(i){let t=i;for(;t;)t.invalidated=!0,t=t.parentAnnotationUID?ne(t.parentAnnotationUID):void 0}const s_=Object.freeze(Object.defineProperty({__proto__:null,addAnnotation:Nt,addChildAnnotation:Cs,clearParentAnnotation:Wl,getAllAnnotations:Ca,getAnnotation:ne,getAnnotationManager:Go,getAnnotations:Yt,getChildAnnotations:Xi,getNumberOfAnnotations:n_,getParentAnnotation:jv,invalidateAnnotation:Vh,removeAllAnnotations:o_,removeAnnotation:Gt,removeAnnotations:i_,setAnnotationManager:Uh},Symbol.toStringTag,{value:"Module"}));function Xv(i){const t=i.toolName;if(!t)throw new Error(`No Tool Found for the ToolClass ${i.name}`);$.tools[t]||($.tools[t]={toolClass:i})}function a_(i){const t=i.toolName;return!!(t&&$.tools[t])}function Zr(i){return!!(i&&$.tools[i])}function r_(i){const t=i.toolName;if(!t)throw new Error(`No tool found for: ${i.name}`);if(!$.tools[t]!==void 0)delete $.tools[t];else throw new Error(`${t} cannot be removed because it has not been added`)}function bs(i,t){const n=t||i.currentTarget,{viewport:e}=N(n)||{};if(!e)return;const o=d_(i),s=l_(i),a=c_(n,s),r=u_(e,a);if(r)return{page:s,client:o,canvas:a,world:r}}function c_(i,t){const n=i.getBoundingClientRect();return[t[0]-n.left-window.pageXOffset,t[1]-n.top-window.pageYOffset]}function l_(i){return[i.pageX,i.pageY]}function d_(i){return[i.clientX,i.clientY]}function u_(i,t){try{return i.canvasToWorld(t)}catch(n){if(h_(n))return;throw n}}function h_(i){return i instanceof Error&&i.message.includes("because no data is mounted")}function qv(i){const t=i.currentTarget,n=N(t);if(!n)return;const{viewportId:e,renderingEngineId:o}=n,s=bs(i,t);if(!s)return;const a={page:[0,0],client:[0,0],canvas:[0,0],world:[0,0,0]},r={event:i,eventName:E.MOUSE_DOUBLE_CLICK,viewportId:e,renderingEngineId:o,camera:{},element:t,startPoints:s,lastPoints:s,currentPoints:s,deltaPoints:a};!Rt(t,E.MOUSE_DOUBLE_CLICK,r)&&(i.stopImmediatePropagation(),i.preventDefault())}const Ng=E.MOUSE_MOVE;function Jr(i){const t=i.currentTarget,n=N(t);if(!n)return;const{renderingEngineId:e,viewportId:o}=n,s=bs(i);if(!s)return;!Rt(t,Ng,{renderingEngineId:e,viewportId:o,camera:{},element:t,currentPoints:s,eventName:Ng,event:i})&&(i.stopImmediatePropagation(),i.preventDefault())}const{MOUSE_DOWN:kg,MOUSE_DOWN_ACTIVATE:f_,MOUSE_CLICK:g_,MOUSE_UP:m_,MOUSE_DRAG:Ug}=E,p_=400,v_=150,I_=3,Gu={mouseButton:void 0,element:null,renderingEngineId:void 0,viewportId:void 0,isClickEvent:!0,clickDelay:200,preventClickTimeout:null,startPoints:{page:[0,0],client:[0,0],canvas:[0,0],world:[0,0,0]},lastPoints:{page:[0,0],client:[0,0],canvas:[0,0],world:[0,0,0]}};let $t={mouseButton:void 0,renderingEngineId:void 0,viewportId:void 0,isClickEvent:!0,clickDelay:200,element:null,preventClickTimeout:null,startPoints:{page:[0,0],client:[0,0],canvas:[0,0],world:[0,0,0]},lastPoints:{page:[0,0],client:[0,0],canvas:[0,0],world:[0,0,0]}};const fn={doubleClickTimeout:null,mouseDownEvent:null,mouseUpEvent:null,ignoreDoubleClick:!1};function Yv(i){if(fn.doubleClickTimeout){if(i.buttons===fn.mouseDownEvent.buttons)return;fn.mouseDownEvent=i,Qc();return}fn.doubleClickTimeout=setTimeout(Qc,i.buttons===1?p_:v_),fn.mouseDownEvent=i,fn.ignoreDoubleClick=!1,$t.element=i.currentTarget,$t.mouseButton=i.buttons;const t=N($t.element);if(!t){$t=Re(Gu);return}const{renderingEngineId:n,viewportId:e}=t;$t.renderingEngineId=n,$t.viewportId=e,$t.preventClickTimeout=setTimeout(E_,$t.clickDelay);const o=bs(i,$t.element);if(!o){clearTimeout($t.preventClickTimeout),$t=Re(Gu);return}$t.element.removeEventListener("mousemove",Jr),$t.startPoints=ki(o),$t.lastPoints=ki(o),document.addEventListener("mouseup",Fh),document.addEventListener("mousemove",Kv)}function w_(i){const t=Bl($t.startPoints,$t.startPoints),n={event:i,eventName:kg,element:$t.element,mouseButton:$t.mouseButton,renderingEngineId:$t.renderingEngineId,viewportId:$t.viewportId,camera:{},startPoints:$t.startPoints,lastPoints:$t.startPoints,currentPoints:$t.startPoints,deltaPoints:t};$t.lastPoints=ki(n.lastPoints),Rt(n.element,kg,n)&&Rt(n.element,f_,n)}function Kv(i){if(!N($t.element)?.viewport)return;const n=bs(i,$t.element);if(!n)return;const e=tI($t.element,$t.lastPoints),o=Bl(n,e);if(fn.doubleClickTimeout)if(Jv(o.canvas))Qc();else return;const s={event:i,eventName:Ug,mouseButton:$t.mouseButton,renderingEngineId:$t.renderingEngineId,viewportId:$t.viewportId,camera:{},element:$t.element,startPoints:ki($t.startPoints),lastPoints:ki(e),currentPoints:n,deltaPoints:o};!Rt($t.element,Ug,s)&&(i.stopImmediatePropagation(),i.preventDefault()),$t.lastPoints=ki(n)}function Fh(i){if(clearTimeout($t.preventClickTimeout),fn.doubleClickTimeout)fn.mouseUpEvent?zc():(fn.mouseUpEvent=i,$t.element.addEventListener("mousemove",Zv));else{const t=$t.isClickEvent?g_:m_,n=bs(i,$t.element);if(!n){zc();return}const e=Bl(n,$t.lastPoints),o={event:i,eventName:t,mouseButton:$t.mouseButton,element:$t.element,renderingEngineId:$t.renderingEngineId,viewportId:$t.viewportId,camera:{},startPoints:ki($t.startPoints),lastPoints:ki($t.lastPoints),currentPoints:n,deltaPoints:e};Rt(o.element,t,o),zc()}document.removeEventListener("mousemove",Kv)}function Zv(i){const t=bs(i,$t.element);if(!t)return;const n=tI($t.element,$t.lastPoints),e=Bl(t,n);Jv(e.canvas)&&(Qc(),Jr(i))}function Jv(i){return Math.abs(i[0])+Math.abs(i[1])>I_}function E_(){$t.isClickEvent=!1}function Qc(){fn.ignoreDoubleClick=!0;const i=fn.mouseDownEvent,t=fn.mouseUpEvent;Qv(),w_(i),t&&Fh(t)}function Qv(){fn.doubleClickTimeout&&(clearTimeout(fn.doubleClickTimeout),fn.doubleClickTimeout=null),fn.mouseDownEvent=null,fn.mouseUpEvent=null}function zc(){document.removeEventListener("mouseup",Fh),$t.element?.removeEventListener("mousemove",Zv),$t.element?.addEventListener("mousemove",Jr),Qv(),$t=Re(Gu)}function ki(i){return Re(i)}function tI(i,t){const{viewport:n}=N(i)||{};if(!n)return t;let e;try{e=n.canvasToWorld(t.canvas)}catch(o){if(C_(o))return t;throw o}return{page:t.page,client:t.client,canvas:t.canvas,world:e}}function Bl(i,t){return!i||!t?{page:[0,0],client:[0,0],canvas:[0,0],world:[0,0,0]}:{page:$d(i.page,t.page),client:$d(i.client,t.client),canvas:$d(i.canvas,t.canvas),world:S_(i.world,t.world)}}function $d(i,t){return[i[0]-t[0],i[1]-t[1]]}function S_(i,t){return[i[0]-t[0],i[1]-t[1],i[2]-t[2]]}function C_(i){return i instanceof Error&&i.message.includes("because no data is mounted")}function b_(){return $t.mouseButton}function eI(i){fn.ignoreDoubleClick?(fn.ignoreDoubleClick=!1,i.stopImmediatePropagation(),i.preventDefault()):zc()}function nI(i){i.removeEventListener("dblclick",qv),i.removeEventListener("mousedown",Yv),i.removeEventListener("mousemove",Jr),i.removeEventListener("dblclick",eI,{capture:!0})}function __(i){nI(i),i.addEventListener("dblclick",qv),i.addEventListener("mousedown",Yv),i.addEventListener("mousemove",Jr),i.addEventListener("dblclick",eI,{capture:!0})}const oI={enable:__,disable:nI},y_=2e3,ua={mouse:0,touch:1};let Vg,Fg;function iI(i,t){const n=Date.now();if(i!==Vg){if(n-Fg<=y_)return t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),!1;Vg=i}Fg=n}const sI=iI.bind(null,ua.mouse),aI=iI.bind(null,ua.touch);function Gg(i,t,n){const e=n?sI:aI;t.forEach(function(o){i.addEventListener(o,e,{passive:!1})})}function Hg(i,t,n){const e=n?sI:aI;t.forEach(function(o){i.removeEventListener(o,e)})}const rI=["mousedown","mouseup","mousemove"],cI=["touchstart","touchend"];function lI(i){Hg(i,rI,ua.mouse),Hg(i,cI,ua.touch)}function x_(i){lI(i),Gg(i,rI,ua.mouse),Gg(i,cI,ua.touch)}const dI={enable:x_,disable:lI};function zl(i,t){const n=t||i.currentTarget,{viewport:e}=N(n)||{};if(!e)return[];const o=i.type==="touchend"?i.changedTouches:i.touches;return Object.keys(o).map(s=>{const a=T_(o[s]),r=D_(o[s]),c=P_(n,r),l=M_(e,c);if(l)return{page:r,client:a,canvas:c,world:l,touch:{identifier:s,radiusX:o[s].radiusX,radiusY:o[s].radiusY,force:o[s].force,rotationAngle:o[s].rotationAngle}}}).filter(Boolean)}function P_(i,t){const n=i.getBoundingClientRect();return[t[0]-n.left-window.pageXOffset,t[1]-n.top-window.pageYOffset]}function D_(i){return[i.pageX,i.pageY]}function T_(i){return[i.clientX,i.clientY]}function M_(i,t){try{return i.canvasToWorld(t)}catch(n){if(A_(n))return;throw n}}function A_(i){return i instanceof Error&&i.message.includes("because no data is mounted")}const $l=36,jl=6,Gh=24,Hh=300;function tl(i,t){const n=wr(i),e=wr(t);return{page:jd(n.page,e.page),client:jd(n.client,e.client),canvas:jd(n.canvas,e.canvas),world:O_(n.world,e.world)}}function Wh(i,t){const n=wr(i),e=wr(t);return{page:ta(n.page,e.page),client:ta(n.client,e.client),canvas:ta(n.canvas,e.canvas),world:uI(n.world,e.world)}}function L_(i,t){}function el(i,t){const n=Wg(i),e=Wg(t);return{page:n.page-e.page,client:n.client-e.client,canvas:n.canvas-e.canvas,world:n.world-e.world}}function qo(i){return Re(i)}function Hu(i){return Re(i)}function wr(i){return i.reduce((t,n)=>({page:[t.page[0]+n.page[0]/i.length,t.page[1]+n.page[1]/i.length],client:[t.client[0]+n.client[0]/i.length,t.client[1]+n.client[1]/i.length],canvas:[t.canvas[0]+n.canvas[0]/i.length,t.canvas[1]+n.canvas[1]/i.length],world:[t.world[0]+n.world[0]/i.length,t.world[1]+n.world[1]/i.length,t.world[2]+n.world[2]/i.length]}),{page:[0,0],client:[0,0],canvas:[0,0],world:[0,0,0]})}function Ro(i){return i.reduce((t,n)=>({page:[t.page[0]+n.page[0]/i.length,t.page[1]+n.page[1]/i.length],client:[t.client[0]+n.client[0]/i.length,t.client[1]+n.client[1]/i.length],canvas:[t.canvas[0]+n.canvas[0]/i.length,t.canvas[1]+n.canvas[1]/i.length],world:[t.world[0]+n.world[0]/i.length,t.world[1]+n.world[1]/i.length,t.world[2]+n.world[2]/i.length],touch:{identifier:null,radiusX:t.touch.radiusX+n.touch.radiusX/i.length,radiusY:t.touch.radiusY+n.touch.radiusY/i.length,force:t.touch.force+n.touch.force/i.length,rotationAngle:t.touch.rotationAngle+n.touch.rotationAngle/i.length}}),{page:[0,0],client:[0,0],canvas:[0,0],world:[0,0,0],touch:{identifier:null,radiusX:0,radiusY:0,force:0,rotationAngle:0}})}function jd(i,t){return[i[0]-t[0],i[1]-t[1]]}function O_(i,t){return[i[0]-t[0],i[1]-t[1],i[2]-t[2]]}function Wg(i){const t=[];for(let n=0;n<i.length;n++)for(let e=0;e<i.length;e++)n<e&&t.push({page:ta(i[n].page,i[e].page),client:ta(i[n].client,i[e].client),canvas:ta(i[n].canvas,i[e].canvas),world:uI(i[n].world,i[e].world)});return t.reduce((n,e)=>({page:n.page+e.page/t.length,client:n.client+e.client/t.length,canvas:n.canvas+e.canvas/t.length,world:n.world+e.world/t.length}),{page:0,client:0,canvas:0,world:0})}function ta(i,t){return Math.sqrt(Math.pow(i[0]-t[0],2)+Math.pow(i[1]-t[1],2))}function uI(i,t){return Math.sqrt(Math.pow(i[0]-t[0],2)+Math.pow(i[1]-t[1],2)+Math.pow(i[2]-t[2],2))}function hI(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(any-pointer:coarse)").matches}const R_=Object.freeze(Object.defineProperty({__proto__:null,MOUSE_PROXIMITY:jl,TOUCH_PROXIMITY:$l,TOUCH_TAP_MAX_CANVAS_DISTANCE:Gh,TOUCH_TAP_TOLERANCE_MS:Hh,copyPoints:Hu,copyPointsList:qo,getDeltaDistance:Wh,getDeltaDistanceBetweenIPoints:el,getDeltaPoints:tl,getDeltaRotation:L_,getMeanPoints:wr,getMeanTouchPoints:Ro,isMobile:hI},Symbol.toStringTag,{value:"Module"}));mv.getRuntimeSettings();const{TOUCH_START:Bg,TOUCH_START_ACTIVATE:N_,TOUCH_PRESS:zg,TOUCH_DRAG:$g,TOUCH_END:jg,TOUCH_TAP:Xg,TOUCH_SWIPE:Xd}=E,Er={page:[0,0],client:[0,0],canvas:[0,0],world:[0,0,0]},nl={page:0,client:0,canvas:0,world:0},fI={renderingEngineId:void 0,viewportId:void 0,element:null,startPointsList:[{...Er,touch:null}],lastPointsList:[{...Er,touch:null}],isTouchStart:!1,startTime:null,pressTimeout:null,pressDelay:700,pressMaxDistance:5,accumulatedDistance:nl,swipeDistanceThreshold:48,swiped:!1,swipeToleranceMs:300},Wu={renderingEngineId:void 0,viewportId:void 0,element:null,startPointsList:[{...Er,touch:null}],taps:0,tapTimeout:null,tapMaxDistance:Gh,tapToleranceMs:Hh};let Ct=Re(fI),qe=Re(Wu);function Gi(i,t,n){return Rt(i,t,n)}function gI(i){Ct.element=i.currentTarget;const t=N(Ct.element),{renderingEngineId:n,viewportId:e}=t;Ct.renderingEngineId=n,Ct.viewportId=e,!Ct.isTouchStart&&(clearTimeout(Ct.pressTimeout),Ct.pressTimeout=setTimeout(()=>k_(i),Ct.pressDelay),U_(i),document.addEventListener("touchmove",mI),document.addEventListener("touchend",pI))}function k_(i){if(Ct.accumulatedDistance.canvas>Ct.pressMaxDistance)return;const n={event:i,eventName:zg,renderingEngineId:Ct.renderingEngineId,viewportId:Ct.viewportId,camera:{},element:Ct.element,startPointsList:qo(Ct.startPointsList),lastPointsList:qo(Ct.lastPointsList),startPoints:Hu(Ro(Ct.startPointsList)),lastPoints:Hu(Ro(Ct.lastPointsList))};Gi(n.element,zg,n)}function U_(i){Ct.isTouchStart=!0,Ct.startTime=new Date;const t=zl(i,Ct.element),n=Ro(t),e=Er,o=nl,s={event:i,eventName:Bg,element:Ct.element,renderingEngineId:Ct.renderingEngineId,viewportId:Ct.viewportId,camera:{},startPointsList:t,lastPointsList:t,currentPointsList:t,startPoints:n,lastPoints:n,currentPoints:n,deltaPoints:e,deltaDistance:o};Ct.startPointsList=qo(s.startPointsList),Ct.lastPointsList=qo(s.lastPointsList),Gi(s.element,Bg,s)&&Gi(s.element,N_,s)}function mI(i){const t=zl(i,Ct.element),n=vI(Ct.element,Ct.lastPointsList),e=t.length===n.length?tl(t,n):Er,o=t.length===n.length?el(t,n):nl,s=t.length===n.length?Wh(t,Ct.lastPointsList):nl;Ct.accumulatedDistance={page:Ct.accumulatedDistance.page+s.page,client:Ct.accumulatedDistance.client+s.client,canvas:Ct.accumulatedDistance.canvas+s.canvas,world:Ct.accumulatedDistance.world+s.world};const a={event:i,eventName:$g,renderingEngineId:Ct.renderingEngineId,viewportId:Ct.viewportId,camera:{},element:Ct.element,startPoints:Ro(Ct.startPointsList),lastPoints:Ro(n),currentPoints:Ro(t),startPointsList:qo(Ct.startPointsList),lastPointsList:qo(n),currentPointsList:t,deltaPoints:e,deltaDistance:o};Gi(Ct.element,$g,a),F_(i,e),Ct.lastPointsList=qo(t)}function pI(i){clearTimeout(Ct.pressTimeout);const t=zl(i,Ct.element),n=vI(Ct.element,Ct.lastPointsList),e=t.length===n.length?tl(t,n):tl(t,t),o=t.length===n.length?el(t,n):el(t,t),s={event:i,eventName:jg,element:Ct.element,renderingEngineId:Ct.renderingEngineId,viewportId:Ct.viewportId,camera:{},startPointsList:qo(Ct.startPointsList),lastPointsList:qo(n),currentPointsList:t,startPoints:Ro(Ct.startPointsList),lastPoints:Ro(n),currentPoints:Ro(t),deltaPoints:e,deltaDistance:o};Gi(s.element,jg,s),V_(i),Ct=Re(fI),document.removeEventListener("touchmove",mI),document.removeEventListener("touchend",pI)}function V_(i){const t=new Date().getTime(),n=Ct.startTime.getTime();if(t-n>qe.tapToleranceMs||(qe.taps===0&&(qe.element=Ct.element,qe.renderingEngineId=Ct.renderingEngineId,qe.viewportId=Ct.viewportId,qe.startPointsList=Ct.startPointsList),qe.taps>0&&!(qe.element==Ct.element&&qe.renderingEngineId==Ct.renderingEngineId&&qe.viewportId==Ct.viewportId)))return;const e=zl(i,qe.element);Wh(e,qe.startPointsList).canvas>qe.tapMaxDistance||(clearTimeout(qe.tapTimeout),qe.taps+=1,qe.tapTimeout=setTimeout(()=>{if(Ct.isTouchStart){qe=Re(Wu);return}const s={event:i,eventName:Xg,element:qe.element,renderingEngineId:qe.renderingEngineId,viewportId:qe.viewportId,camera:{},currentPointsList:e,currentPoints:Ro(e),taps:qe.taps};Gi(s.element,Xg,s),qe=Re(Wu)},qe.tapToleranceMs))}function F_(i,t){const n=new Date().getTime(),e=Ct.startTime.getTime();if(Ct.swiped||n-e>Ct.swipeToleranceMs)return;const[o,s]=t.canvas,a={event:i,eventName:Xd,renderingEngineId:Ct.renderingEngineId,viewportId:Ct.viewportId,camera:{},element:Ct.element,swipe:null};Math.abs(o)>Ct.swipeDistanceThreshold&&(a.swipe=o>0?ss.RIGHT:ss.LEFT,Gi(a.element,Xd,a),Ct.swiped=!0),Math.abs(s)>Ct.swipeDistanceThreshold&&(a.swipe=s>0?ss.DOWN:ss.UP,Gi(a.element,Xd,a),Ct.swiped=!0)}function vI(i,t){const{viewport:n}=N(i)||{};return n?t.map(e=>{let o;try{o=n.canvasToWorld(e.canvas)}catch(s){if(G_(s))return;throw s}return{page:e.page,client:e.client,canvas:e.canvas,world:o,touch:e.touch}}).filter(Boolean):t}function G_(i){return i instanceof Error&&i.message.includes("because no data is mounted")}function II(i){dI.disable(i),i.removeEventListener("touchstart",gI)}function H_(i){II(i),dI.enable(i),i.addEventListener("touchstart",gI,{passive:!1})}const wI={enable:H_,disable:II},qg=10,Yg=40,Kg=800;function W_(i){let t=0,n=0,e=0,o=0;return"detail"in i&&(n=i.detail),"wheelDelta"in i&&(n=-i.wheelDelta/120),"wheelDeltaY"in i&&(n=-i.wheelDeltaY/120),"wheelDeltaX"in i&&(t=-i.wheelDeltaX/120),e=t*qg,o=n*qg,"deltaY"in i&&(o=i.deltaY),"deltaX"in i&&(e=i.deltaX),(e||o)&&i.deltaMode&&(i.deltaMode===1?(e*=Yg,o*=Yg):(e*=Kg,o*=Kg)),e&&!t&&(t=e<1?-1:1),o&&!n&&(n=o<1?-1:1),{spinX:t,spinY:n,pixelX:e,pixelY:o}}function EI(i){const t=i.currentTarget,n=N(t),{renderingEngineId:e,viewportId:o}=n;if(i.deltaY>-1&&i.deltaY<1)return;const s=bs(i);if(!s)return;i.preventDefault();const{spinX:a,spinY:r,pixelX:c,pixelY:l}=W_(i),d=r<0?-1:1,u={event:i,eventName:E.MOUSE_WHEEL,renderingEngineId:e,viewportId:o,element:t,camera:{},detail:i,wheel:{spinX:a,spinY:r,pixelX:c,pixelY:l,direction:d},points:s};Rt(t,E.MOUSE_WHEEL,u)}function B_(i){SI(i),i.addEventListener("wheel",EI,{passive:!1})}function SI(i){i.removeEventListener("wheel",EI)}const CI={enable:B_,disable:SI},z_={renderingEngineId:void 0,viewportId:void 0,key:void 0,keyCode:void 0,element:null};let an={renderingEngineId:void 0,viewportId:void 0,key:void 0,keyCode:void 0,element:null};function Xl(i){an.element=i.currentTarget;const t=N(an.element),{renderingEngineId:n,viewportId:e}=t;an.renderingEngineId=n,an.viewportId=e,an.key=i.key,an.keyCode=i.keyCode,i.preventDefault();const o={renderingEngineId:an.renderingEngineId,viewportId:an.viewportId,element:an.element,key:an.key,keyCode:an.keyCode};Rt(o.element,E.KEY_DOWN,o),document.addEventListener("keyup",bI),document.addEventListener("visibilitychange",Bh),an.element.removeEventListener("keydown",Xl)}function Bh(){document.removeEventListener("visibilitychange",Bh),document.visibilityState==="hidden"&&_I()}function bI(i){const t={renderingEngineId:an.renderingEngineId,viewportId:an.viewportId,element:an.element,key:an.key,keyCode:an.keyCode};document.removeEventListener("keyup",bI),document.removeEventListener("visibilitychange",Bh),an.element.addEventListener("keydown",Xl),an=Re(z_),Rt(t.element,E.KEY_UP,t)}function $_(){return an.keyCode}function _I(){an.keyCode=void 0}function j_(i){yI(i),i.addEventListener("keydown",Xl)}function yI(i){i.removeEventListener("keydown",Xl)}const ba={enable:j_,disable:yI,getModifierKey:$_};function Gs(){var i=new Kn(9);return Kn!=Float32Array&&(i[1]=0,i[2]=0,i[3]=0,i[5]=0,i[6]=0,i[7]=0),i[0]=1,i[4]=1,i[8]=1,i}function qd(i,t){return i[0]=t[0],i[1]=t[1],i[2]=t[2],i[3]=t[4],i[4]=t[5],i[5]=t[6],i[6]=t[8],i[7]=t[9],i[8]=t[10],i}function X_(i,t){if(i===t){var n=t[1],e=t[2],o=t[5];i[1]=t[3],i[2]=t[6],i[3]=n,i[5]=t[7],i[6]=e,i[7]=o}else i[0]=t[0],i[1]=t[3],i[2]=t[6],i[3]=t[1],i[4]=t[4],i[5]=t[7],i[6]=t[2],i[7]=t[5],i[8]=t[8];return i}function q_(i,t){var n=t[0],e=t[1],o=t[2],s=t[3],a=t[4],r=t[5],c=t[6],l=t[7],d=t[8],u=d*a-r*l,h=-d*s+r*c,f=l*s-a*c,g=n*u+e*h+o*f;return g?(g=1/g,i[0]=u*g,i[1]=(-d*e+o*l)*g,i[2]=(r*e-o*a)*g,i[3]=h*g,i[4]=(d*n-o*c)*g,i[5]=(-r*n+o*s)*g,i[6]=f*g,i[7]=(-l*n+e*c)*g,i[8]=(a*n-e*s)*g,i):null}function Y_(i,t,n){var e=t[0],o=t[1],s=t[2],a=t[3],r=t[4],c=t[5],l=t[6],d=t[7],u=t[8],h=n[0],f=n[1],g=n[2],m=n[3],p=n[4],v=n[5],I=n[6],w=n[7],C=n[8];return i[0]=h*e+f*a+g*l,i[1]=h*o+f*r+g*d,i[2]=h*s+f*c+g*u,i[3]=m*e+p*a+v*l,i[4]=m*o+p*r+v*d,i[5]=m*s+p*c+v*u,i[6]=I*e+w*a+C*l,i[7]=I*o+w*r+C*d,i[8]=I*s+w*c+C*u,i}function qi(){var i=new Kn(16);return Kn!=Float32Array&&(i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[11]=0,i[12]=0,i[13]=0,i[14]=0),i[0]=1,i[5]=1,i[10]=1,i[15]=1,i}function Bu(i,t,n,e,o,s,a,r,c,l,d,u,h,f,g,m){var p=new Kn(16);return p[0]=i,p[1]=t,p[2]=n,p[3]=e,p[4]=o,p[5]=s,p[6]=a,p[7]=r,p[8]=c,p[9]=l,p[10]=d,p[11]=u,p[12]=h,p[13]=f,p[14]=g,p[15]=m,p}function Qn(i){return i[0]=1,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=1,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[10]=1,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i}function K_(i,t){var n=t[0],e=t[1],o=t[2],s=t[3],a=t[4],r=t[5],c=t[6],l=t[7],d=t[8],u=t[9],h=t[10],f=t[11],g=t[12],m=t[13],p=t[14],v=t[15],I=n*r-e*a,w=n*c-o*a,C=n*l-s*a,S=e*c-o*r,b=e*l-s*r,_=o*l-s*c,y=d*m-u*g,D=d*p-h*g,T=d*v-f*g,P=u*p-h*m,x=u*v-f*m,M=h*v-f*p,L=I*M-w*x+C*P+S*T-b*D+_*y;return L?(L=1/L,i[0]=(r*M-c*x+l*P)*L,i[1]=(o*x-e*M-s*P)*L,i[2]=(m*_-p*b+v*S)*L,i[3]=(h*b-u*_-f*S)*L,i[4]=(c*T-a*M-l*D)*L,i[5]=(n*M-o*T+s*D)*L,i[6]=(p*C-g*_-v*w)*L,i[7]=(d*_-h*C+f*w)*L,i[8]=(a*x-r*T+l*y)*L,i[9]=(e*T-n*x-s*y)*L,i[10]=(g*b-m*C+v*I)*L,i[11]=(u*C-d*b-f*I)*L,i[12]=(r*D-a*P-c*y)*L,i[13]=(n*P-e*D+o*y)*L,i[14]=(m*w-g*S-p*I)*L,i[15]=(d*S-u*w+h*I)*L,i):null}function Z_(i,t,n){var e=t[0],o=t[1],s=t[2],a=t[3],r=t[4],c=t[5],l=t[6],d=t[7],u=t[8],h=t[9],f=t[10],g=t[11],m=t[12],p=t[13],v=t[14],I=t[15],w=n[0],C=n[1],S=n[2],b=n[3];return i[0]=w*e+C*r+S*u+b*m,i[1]=w*o+C*c+S*h+b*p,i[2]=w*s+C*l+S*f+b*v,i[3]=w*a+C*d+S*g+b*I,w=n[4],C=n[5],S=n[6],b=n[7],i[4]=w*e+C*r+S*u+b*m,i[5]=w*o+C*c+S*h+b*p,i[6]=w*s+C*l+S*f+b*v,i[7]=w*a+C*d+S*g+b*I,w=n[8],C=n[9],S=n[10],b=n[11],i[8]=w*e+C*r+S*u+b*m,i[9]=w*o+C*c+S*h+b*p,i[10]=w*s+C*l+S*f+b*v,i[11]=w*a+C*d+S*g+b*I,w=n[12],C=n[13],S=n[14],b=n[15],i[12]=w*e+C*r+S*u+b*m,i[13]=w*o+C*c+S*h+b*p,i[14]=w*s+C*l+S*f+b*v,i[15]=w*a+C*d+S*g+b*I,i}function fo(i,t,n){var e=n[0],o=n[1],s=n[2],a,r,c,l,d,u,h,f,g,m,p,v;return t===i?(i[12]=t[0]*e+t[4]*o+t[8]*s+t[12],i[13]=t[1]*e+t[5]*o+t[9]*s+t[13],i[14]=t[2]*e+t[6]*o+t[10]*s+t[14],i[15]=t[3]*e+t[7]*o+t[11]*s+t[15]):(a=t[0],r=t[1],c=t[2],l=t[3],d=t[4],u=t[5],h=t[6],f=t[7],g=t[8],m=t[9],p=t[10],v=t[11],i[0]=a,i[1]=r,i[2]=c,i[3]=l,i[4]=d,i[5]=u,i[6]=h,i[7]=f,i[8]=g,i[9]=m,i[10]=p,i[11]=v,i[12]=a*e+d*o+g*s+t[12],i[13]=r*e+u*o+m*s+t[13],i[14]=c*e+h*o+p*s+t[14],i[15]=l*e+f*o+v*s+t[15]),i}function go(i,t,n,e){var o=e[0],s=e[1],a=e[2],r=Math.hypot(o,s,a),c,l,d,u,h,f,g,m,p,v,I,w,C,S,b,_,y,D,T,P,x,M,L,R;return r<Js?null:(r=1/r,o*=r,s*=r,a*=r,c=Math.sin(n),l=Math.cos(n),d=1-l,u=t[0],h=t[1],f=t[2],g=t[3],m=t[4],p=t[5],v=t[6],I=t[7],w=t[8],C=t[9],S=t[10],b=t[11],_=o*o*d+l,y=s*o*d+a*c,D=a*o*d-s*c,T=o*s*d-a*c,P=s*s*d+l,x=a*s*d+o*c,M=o*a*d+s*c,L=s*a*d-o*c,R=a*a*d+l,i[0]=u*_+m*y+w*D,i[1]=h*_+p*y+C*D,i[2]=f*_+v*y+S*D,i[3]=g*_+I*y+b*D,i[4]=u*T+m*P+w*x,i[5]=h*T+p*P+C*x,i[6]=f*T+v*P+S*x,i[7]=g*T+I*P+b*x,i[8]=u*M+m*L+w*R,i[9]=h*M+p*L+C*R,i[10]=f*M+v*L+S*R,i[11]=g*M+I*L+b*R,t!==i&&(i[12]=t[12],i[13]=t[13],i[14]=t[14],i[15]=t[15]),i)}function J_(i,t,n){var e=n[0],o=n[1],s=n[2],a=Math.hypot(e,o,s),r,c,l;return a<Js?null:(a=1/a,e*=a,o*=a,s*=a,r=Math.sin(t),c=Math.cos(t),l=1-c,i[0]=e*e*l+c,i[1]=o*e*l+s*r,i[2]=s*e*l-o*r,i[3]=0,i[4]=e*o*l-s*r,i[5]=o*o*l+c,i[6]=s*o*l+e*r,i[7]=0,i[8]=e*s*l+o*r,i[9]=o*s*l-e*r,i[10]=s*s*l+c,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i)}function Q_(i,t){var n=t[0],e=t[1],o=t[2],s=t[4],a=t[5],r=t[6],c=t[8],l=t[9],d=t[10];return i[0]=Math.hypot(n,e,o),i[1]=Math.hypot(s,a,r),i[2]=Math.hypot(c,l,d),i}function Zg(i,t){var n=new Kn(3);Q_(n,t);var e=1/n[0],o=1/n[1],s=1/n[2],a=t[0]*e,r=t[1]*o,c=t[2]*s,l=t[4]*e,d=t[5]*o,u=t[6]*s,h=t[8]*e,f=t[9]*o,g=t[10]*s,m=a+d+g,p=0;return m>0?(p=Math.sqrt(m+1)*2,i[3]=.25*p,i[0]=(u-f)/p,i[1]=(h-c)/p,i[2]=(r-l)/p):a>d&&a>g?(p=Math.sqrt(1+a-d-g)*2,i[3]=(u-f)/p,i[0]=.25*p,i[1]=(r+l)/p,i[2]=(h+c)/p):d>g?(p=Math.sqrt(1+d-a-g)*2,i[3]=(h-c)/p,i[0]=(r+l)/p,i[1]=.25*p,i[2]=(u+f)/p):(p=Math.sqrt(1+g-a-d)*2,i[3]=(r-l)/p,i[0]=(h+c)/p,i[1]=(u+f)/p,i[2]=.25*p),i}function ty(i,t){var n=t[0],e=t[1],o=t[2],s=t[3],a=n+n,r=e+e,c=o+o,l=n*a,d=e*a,u=e*r,h=o*a,f=o*r,g=o*c,m=s*a,p=s*r,v=s*c;return i[0]=1-u-g,i[1]=d+v,i[2]=h-p,i[3]=0,i[4]=d-v,i[5]=1-l-g,i[6]=f+m,i[7]=0,i[8]=h+p,i[9]=f-m,i[10]=1-l-u,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i}function ey(i,t,n,e){var o,s,a,r,c,l,d,u,h,f,g=t[0],m=t[1],p=t[2],v=e[0],I=e[1],w=e[2],C=n[0],S=n[1],b=n[2];return Math.abs(g-C)<Js&&Math.abs(m-S)<Js&&Math.abs(p-b)<Js?Qn(i):(d=g-C,u=m-S,h=p-b,f=1/Math.hypot(d,u,h),d*=f,u*=f,h*=f,o=I*h-w*u,s=w*d-v*h,a=v*u-I*d,f=Math.hypot(o,s,a),f?(f=1/f,o*=f,s*=f,a*=f):(o=0,s=0,a=0),r=u*a-h*s,c=h*o-d*a,l=d*s-u*o,f=Math.hypot(r,c,l),f?(f=1/f,r*=f,c*=f,l*=f):(r=0,c=0,l=0),i[0]=o,i[1]=r,i[2]=d,i[3]=0,i[4]=s,i[5]=c,i[6]=u,i[7]=0,i[8]=a,i[9]=l,i[10]=h,i[11]=0,i[12]=-(o*g+s*m+a*p),i[13]=-(r*g+c*m+l*p),i[14]=-(d*g+u*m+h*p),i[15]=1,i)}function ny(i,t,n){return i[0]=t[0]*n,i[1]=t[1]*n,i[2]=t[2]*n,i[3]=t[3]*n,i[4]=t[4]*n,i[5]=t[5]*n,i[6]=t[6]*n,i[7]=t[7]*n,i[8]=t[8]*n,i[9]=t[9]*n,i[10]=t[10]*n,i[11]=t[11]*n,i[12]=t[12]*n,i[13]=t[13]*n,i[14]=t[14]*n,i[15]=t[15]*n,i}function xI(){var i=new Kn(4);return Kn!=Float32Array&&(i[0]=0,i[1]=0,i[2]=0,i[3]=0),i}function Yd(i,t,n,e){var o=new Kn(4);return o[0]=i,o[1]=t,o[2]=n,o[3]=e,o}function oy(i,t,n){return i[0]=t[0]*n,i[1]=t[1]*n,i[2]=t[2]*n,i[3]=t[3]*n,i}function iy(i,t){var n=t[0],e=t[1],o=t[2],s=t[3],a=n*n+e*e+o*o+s*s;return a>0&&(a=1/Math.sqrt(a)),i[0]=n*a,i[1]=e*a,i[2]=o*a,i[3]=s*a,i}function zu(i,t){return i[0]*t[0]+i[1]*t[1]+i[2]*t[2]+i[3]*t[3]}function sy(i,t,n){var e=t[0],o=t[1],s=t[2],a=t[3];return i[0]=n[0]*e+n[4]*o+n[8]*s+n[12]*a,i[1]=n[1]*e+n[5]*o+n[9]*s+n[13]*a,i[2]=n[2]*e+n[6]*o+n[10]*s+n[14]*a,i[3]=n[3]*e+n[7]*o+n[11]*s+n[15]*a,i}(function(){var i=xI();return function(t,n,e,o,s,a){var r,c;for(n||(n=4),e||(e=0),o?c=Math.min(o*n+e,t.length):c=t.length,r=e;r<c;r+=n)i[0]=t[r],i[1]=t[r+1],i[2]=t[r+2],i[3]=t[r+3],s(i,i,a),t[r]=i[0],t[r+1]=i[1],t[r+2]=i[2],t[r+3]=i[3];return t}})();function as(){var i=new Kn(4);return Kn!=Float32Array&&(i[0]=0,i[1]=0,i[2]=0),i[3]=1,i}function PI(i,t,n){n=n*.5;var e=Math.sin(n);return i[0]=e*t[0],i[1]=e*t[1],i[2]=e*t[2],i[3]=Math.cos(n),i}function $c(i,t,n,e){var o=t[0],s=t[1],a=t[2],r=t[3],c=n[0],l=n[1],d=n[2],u=n[3],h,f,g,m,p;return f=o*c+s*l+a*d+r*u,f<0&&(f=-f,c=-c,l=-l,d=-d,u=-u),1-f>Js?(h=Math.acos(f),g=Math.sin(h),m=Math.sin((1-e)*h)/g,p=Math.sin(e*h)/g):(m=1-e,p=e),i[0]=m*o+p*c,i[1]=m*s+p*l,i[2]=m*a+p*d,i[3]=m*r+p*u,i}function ay(i,t){var n=t[0]+t[4]+t[8],e;if(n>0)e=Math.sqrt(n+1),i[3]=.5*e,e=.5/e,i[0]=(t[5]-t[7])*e,i[1]=(t[6]-t[2])*e,i[2]=(t[1]-t[3])*e;else{var o=0;t[4]>t[0]&&(o=1),t[8]>t[o*3+o]&&(o=2);var s=(o+1)%3,a=(o+2)%3;e=Math.sqrt(t[o*3+o]-t[s*3+s]-t[a*3+a]+1),i[o]=.5*e,e=.5/e,i[3]=(t[s*3+a]-t[a*3+s])*e,i[s]=(t[s*3+o]+t[o*3+s])*e,i[a]=(t[a*3+o]+t[o*3+a])*e}return i}var ry=oy,cy=zu,DI=iy,ly=(function(){var i=B(),t=Ot(1,0,0),n=Ot(0,1,0);return function(e,o,s){var a=xt(o,s);return a<-.999999?(Me(i,t,o),mr(i)<1e-6&&Me(i,n,o),Wt(i,i),PI(e,i,Math.PI),e):a>.999999?(e[0]=0,e[1]=0,e[2]=0,e[3]=1,e):(Me(i,o,s),e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=1+a,DI(e,e))}})();(function(){var i=as(),t=as();return function(n,e,o,s,a,r){return $c(i,e,a,r),$c(t,o,s,r),$c(n,i,t,2*r*(1-r)),n}})();(function(){var i=Gs();return function(t,n,e,o){return i[0]=e[0],i[3]=e[1],i[6]=e[2],i[1]=o[0],i[4]=o[1],i[7]=o[2],i[2]=-n[0],i[5]=-n[1],i[8]=-n[2],DI(t,ay(t,i))}})();function It(){var i=new Kn(2);return Kn!=Float32Array&&(i[0]=0,i[1]=0),i}function gi(i){var t=new Kn(2);return t[0]=i[0],t[1]=i[1],t}function mo(i,t,n){return i[0]=t,i[1]=n,i}function Tn(i,t,n){return i[0]=t[0]+n[0],i[1]=t[1]+n[1],i}function pe(i,t,n){return i[0]=t[0]-n[0],i[1]=t[1]-n[1],i}function Oi(i,t,n){return i[0]=t[0]*n,i[1]=t[1]*n,i}function nr(i,t,n,e){return i[0]=t[0]+n[0]*e,i[1]=t[1]+n[1]*e,i}function _e(i,t){var n=t[0]-i[0],e=t[1]-i[1];return Math.hypot(n,e)}function Ni(i,t){var n=t[0]-i[0],e=t[1]-i[1];return n*n+e*e}function ha(i){var t=i[0],n=i[1];return Math.hypot(t,n)}function Ao(i,t){var n=t[0],e=t[1],o=n*n+e*e;return o>0&&(o=1/Math.sqrt(o)),i[0]=t[0]*o,i[1]=t[1]*o,i}function zo(i,t){return i[0]*t[0]+i[1]*t[1]}function dy(i,t,n,e){var o=t[0]-n[0],s=t[1]-n[1],a=Math.sin(e),r=Math.cos(e);return i[0]=o*r-s*a+n[0],i[1]=o*a+s*r+n[1],i}function TI(i,t){var n=i[0],e=i[1],o=t[0],s=t[1],a=Math.sqrt(n*n+e*e)*Math.sqrt(o*o+s*s),r=a&&(n*o+e*s)/a;return Math.acos(Math.min(Math.max(r,-1),1))}var uy=ha,No=pe,zh=_e;(function(){var i=It();return function(t,n,e,o,s,a){var r,c;for(n||(n=2),e||(e=0),o?c=Math.min(o*n+e,t.length):c=t.length,r=e;r<c;r+=n)i[0]=t[r],i[1]=t[r+1],s(i,i,a),t[r]=i[0],t[r+1]=i[1];return t}})();const hy="binaryLabelmap";function MI(i){return i.segmentOrder?.length?[...i.segmentOrder]:Object.keys(i.segments).map(Number).sort((t,n)=>t-n)}function AI(i){return`${i}-storage-0`}function fy(i){return i.volumeId?"volume":"stack"}function gy(i,t,n=AI(i.segmentationId)){const e={labelmapId:n,storageKind:fy(t),labelToSegmentIndex:{}};return t.volumeId!=null&&(e.volumeId=t.volumeId),t.referencedVolumeId!=null&&(e.referencedVolumeId=t.referencedVolumeId),t.referencedImageIds!=null&&(e.referencedImageIds=t.referencedImageIds),t.imageIds!=null&&(e.imageIds=t.imageIds),e}function my(i,t){const n=t.primaryLabelmapId;if(n&&t.labelmaps?.[n])return n;const e=Object.keys(t.labelmaps??{})[0]??AI(i.segmentationId);return t.primaryLabelmapId=e,e}function kn(i){const t=i.representationData.Labelmap;if(!t)return;t.labelmaps||={};const n=my(i,t);return t.labelmaps[n]||=gy(i,t,n),t.segmentBindings||={},t.sourceRepresentationName||=hy,MI(i).forEach(e=>{t.segmentBindings[e]||={labelmapId:n,labelValue:e}}),Object.values(t.labelmaps).forEach(e=>{e.labelToSegmentIndex={}}),Object.entries(t.segmentBindings).forEach(([e,o])=>{const s=t.labelmaps[o.labelmapId];s&&(s.labelToSegmentIndex||={},s.labelToSegmentIndex[o.labelValue]=Number(e))}),t}function py(i,t){const n=i.imageIds??[],e=i.referencedImageIds??n;if(e.length)return i.referencedImageIds?.length&&n.length>e.length&&n.length%e.length===0?e[t%e.length]:e[t]}function ql(i,t){i.imageIds?.forEach((n,e)=>{const o=py(i,e);!o||!n||t(o,n,e)})}function vy(i,t){const n=[];return ql(i,(e,o)=>{e===t&&n.push(o)}),n}function Iy(i){const t=new Map;return ql(i,n=>{t.set(n,(t.get(n)??0)+1)}),Array.from(t.values()).some(n=>n>1)}function _a(i,t){return kn(i)?.labelmaps?.[t]}function cn(i){const t=kn(i);return t?Object.values(t.labelmaps):[]}function Jg(i,t){const n=kn(i);n&&(n.labelmaps[t.labelmapId]=t)}function LI(i,t){const n=kn(i);if(!n)return;const e=n.labelmaps[t];e?.geometryVolumeId&&Q.getVolume(e.geometryVolumeId)&&Q.removeVolumeLoadObject(e.geometryVolumeId),delete n.labelmaps[t]}function $n(i){const t=wy(i);if(t)return t;const n=i.volumeId??i.geometryVolumeId;if(n){const a=Q.getVolume(n);if(a)return a}const e=i.imageIds??[];if(!e.length)return;const o=i.volumeId??i.geometryVolumeId??`${i.labelmapId}-geometry`;i.volumeId||(i.geometryVolumeId=o);const s=Q.getVolume(o);return s||jr(o,e)}function wy(i){if(i.volumeId||!Ey(i))return;const t=i.geometryVolumeId??`${i.labelmapId}-geometry`,n=Q.getVolume(t);if(n)return n;const e=new Map;ql(i,(r,c)=>{const l=e.get(r)??[];l.push(c),e.set(r,l)});const o=Array.from(e.keys());if(!o.length)return;let s=0;const a=pv(o,{getDerivedImageId:()=>`${t}-image-${s++}`,targetBuffer:{type:"Uint8Array"}});return a.forEach(r=>{const c=e.get(r.referencedImageId);if(!c?.length)return;const l=r.voxelManager,d=l.getScalarDataLength();c.forEach(u=>{const f=Q.getImage(u)?.voxelManager;if(!f)return;const g=f.getScalarDataLength(),m=Math.min(d,g);for(let p=0;p<m;p++){const v=Number(f.getAtIndex(p));v!==0&&l.setAtIndex(p,v)}})}),i.geometryVolumeId=t,jr(t,a.map(r=>r.imageId))}function Ey(i){return Iy(i)}function Sy(i,t){return cn(i).find(n=>n.imageIds?.includes(t))}function Cy(i,t){return cn(i).find(n=>n.volumeId===t||n.geometryVolumeId===t)}const by=.999,rr=.1,OI=.001,Qg="labelmapImageMapper";function RI(i){return i===Gn.COMPOSITE||i===Gn.AVERAGE_INTENSITY_BLEND}function Yl(i){const t=i;return t.type!==so.PLANAR_NEXT?!1:NI(t)===We.VTK_VOLUME_SLICE}function NI(i){const t=kI(i);if(t){const n=i.getDisplaySetRenderMode?.(t);if(n)return n}return i.getDefaultActor?.()?.actorMapper?.renderMode}function _y(i){const t=i.getDefaultActor?.();return t?.actorMapper?.mapper??t?.actorMapper?.actor?.getMapper?.()}function kI(i){const t=i.getSourceDataId?.();if(t)return t;const n=i._debug?.renderModes;if(n)return Object.entries(n).find(([e,o])=>i.getDisplaySetRole?.(e)==="source"&&o===We.VTK_VOLUME_SLICE)?.[0]??Object.entries(n).find(([,e])=>e===We.VTK_VOLUME_SLICE)?.[0]}function yy(i){const t=i,n=t.getResolvedView?.()?.toICamera?.();if(tm(n))return n;const e=t.getCamera?.();return tm(e)?e:void 0}function tm(i){const t=i;return!!(t&&em(t.viewPlaneNormal)&&em(t.viewUp))}function em(i){const t=i;return!!(t&&typeof t.length=="number"&&t.length>=3&&Number.isFinite(Number(t[0]))&&Number.isFinite(Number(t[1]))&&Number.isFinite(Number(t[2])))}function UI(i){if(!i.getDisplaySetPresentation)return;const t=kI(i);return t?i.getDisplaySetPresentation(t):void 0}function VI(i){if(i instanceof Xe)return i.getBlendMode?.();if(!Yl(i))return;const t=UI(i)?.blendMode;return t!==void 0?t:Gn.AVERAGE_INTENSITY_BLEND}function FI(i){if(i instanceof Xe)return i.getSlabThickness?.()??rr;if(!Yl(i))return rr;const t=_y(i)?.getSlabThickness?.();return typeof t=="number"?t:UI(i)?.slabThickness??rr}function GI(i){if(i?.useSliceRendering)return!0;if(typeof window>"u")return!1;const t=new URLSearchParams(window.location.search);if(!t.has(Qg))return!1;const n=t.get(Qg);if(n===null||n==="")return!0;const e=n.trim().toLowerCase();return e!=="0"&&e!=="false"&&e!=="off"}function $h(i,t){if(GI(t))return!0;if(!i?.representationData?.Labelmap)return!1;const n=cn(i);return n.length>1&&n.some(e=>e.storageKind==="stack")}function vi(i){const t=i instanceof Xe,n=Yl(i);if(!t&&!n)return!1;const e=VI(i);if(t&&!RI(e)||FI(i)>rr+OI)return!1;if(t)try{return i.getSliceViewInfo(),!0}catch{return!1}return!0}function HI(i){const t=i,n=i instanceof Xe,e=Yl(i);if(!n&&!e)return{key:"unsupported:viewport",sliceIndex:NaN,supported:!1};const o=yy(i);if(!o)return{key:"unsupported:camera",sliceIndex:NaN,supported:!1};const{viewPlaneNormal:s,viewUp:a}=o,r=Wt(B(),s),c=Wt(B(),a);let l;if(n)try{l=i.getSliceViewInfo().sliceIndex}catch{l=void 0}else l=t.getCurrentImageIdIndex?.();const d=VI(i),u=FI(i),h=[r.map(f=>f.toFixed(3)).join(","),c.map(f=>f.toFixed(3)).join(",")].join("|");if(n&&!RI(d))return{key:`unsupported:blend:${d}:${h}`,sliceIndex:l??NaN,supported:!1};if(u>rr+OI)return{key:`unsupported:slab:${u.toFixed(3)}:${h}`,sliceIndex:l??NaN,supported:!1};if(n)try{i.getSliceViewInfo()}catch{return{key:`unsupported:oblique:${h}`,sliceIndex:l??NaN,supported:!1}}return e&&NI(t)!==We.VTK_VOLUME_SLICE?{key:`unsupported:renderMode:${h}`,sliceIndex:l??NaN,supported:!1}:{key:`supported:${h}:${l??0}`,sliceIndex:l??NaN,supported:!0}}function zn(i,t){const n=i;if(GI(t)&&vi(i))return"image";if(i instanceof pn)return"volume";if(i instanceof Pn)return"image";const o=typeof n.getDefaultActor=="function"?n.getDefaultActor():void 0,s=o?.actorMapper,a=s?.renderMode;if(a===We.VTK_VOLUME||a===We.VTK_VOLUME_SLICE||a===We.CPU_VOLUME)return"volume";if(a===We.VTK_IMAGE||a===We.CPU_IMAGE)return"image";const r=typeof o?.actor?.getClassName=="function"?o.actor.getClassName():void 0;return r==="vtkVolume"?"volume":r==="vtkImageSlice"?"image":r==="CanvasActor"?s?.renderMode===We.CPU_VOLUME?"volume":"image":n.type===so.PLANAR_NEXT&&n.getVolumeId?.()?"volume":typeof n.getCurrentImageId=="function"?"image":"unsupported"}const{EPSILON:Os}=Qo;function WI(i,t,n=!1){let e=1/0,o=n?-1/0:0,s=1/0,a=n?-1/0:0,r=1/0,c=n?-1/0:0;const l=i[0]?.length===3;for(let d=0;d<i.length;d++){const u=i[d];e=Math.min(u[0],e),o=Math.max(u[0],o),s=Math.min(u[1],s),a=Math.max(u[1],a),l&&(r=Math.min(u[2]??r,r),c=Math.max(u[2]??c,c))}return t?(e=Math.max(n?t[0]+Os:0,e),o=Math.min(n?t[0]-Os:t[0]-1,o),s=Math.max(n?t[1]+Os:0,s),a=Math.min(n?t[1]-Os:t[1]-1,a),l&&t.length===3&&(r=Math.max(n?t[2]+Os:0,r),c=Math.min(n?t[2]-Os:t[2]-1,c))):n||(e=Math.max(0,e),o=Math.min(1/0,o),s=Math.max(0,s),a=Math.min(1/0,a),l&&(r=Math.max(0,r),c=Math.min(1/0,c))),l?[[e,o],[s,a],[r,c]]:[[e,o],[s,a],null]}function Ii(i,t){return WI(i,t,!1)}function xy(i,t){return WI(i,t,!0)}const Py=(i,t)=>JSON.stringify(i)===JSON.stringify(t);function jh(i,t,n,e){const o=n[0]/2,s=n[1]/2,a=n[2]/2,r=new Array(8);r[0]=wn(i,[e[0]-o,e[1]-s,e[2]-a]);const c=[[1,-1,-1],[-1,1,-1],[1,1,-1],[-1,-1,1],[1,-1,1],[-1,1,1],[1,1,1]];for(let l=0;l<7;l++){const[d,u,h]=c[l];r[l+1]=wn(i,[e[0]+d*o,e[1]+u*s,e[2]+h*a])}return Ii(r,t)}function BI(i,t){const{spacing:n}=i,e=i.voxelManager.getScalarDataLength(),o=[];let s=0;for(let a=0;a<t.length;a++){const{imageData:r,spacing:c,dimensions:l,voxelManager:d}=t[a].volume,u=t[a].volume.voxelManager.getScalarDataLength();u===e&&Py(c,n)&&(s=a);const h=t[a].lower,f=t[a].upper;o.push({imageData:r,lower:h,upper:f,spacing:c,dimensions:l,volumeSize:u,voxelManager:d})}return{volumeInfoList:o,baseVolumeIdx:s}}const Xh=new Map,Dy=i=>{const t=Xh.get(i);t&&(t.isDirty=!0)},Ty=i=>{const t=Xh.get(i);return t&&!t.isDirty?t.indices:null},My=(i,t)=>{Xh.set(i,{indices:t,isDirty:!1})};function He(i,t,n){const e={segmentationId:i,modifiedSlicesToUse:t,segmentIndex:n};Dy(i),Rt(Z,E.SEGMENTATION_DATA_MODIFIED,e)}function Co(i){const t={segmentationId:i};Rt(Z,E.SEGMENTATION_MODIFIED,t)}function qh(i){const t={segmentationId:i};Rt(Z,E.SEGMENTATION_REMOVED,t)}function Mo(i,t,n){const e={segmentationId:t,type:n,viewportId:i};Rt(Z,E.SEGMENTATION_REPRESENTATION_MODIFIED,e)}function $u(i,t,n){const e={viewportId:i,segmentationId:t,type:n};Rt(Z,E.SEGMENTATION_REPRESENTATION_REMOVED,e)}const Ay=Object.freeze(Object.defineProperty({__proto__:null,triggerSegmentationDataModified:He,triggerSegmentationModified:Co,triggerSegmentationRemoved:qh,triggerSegmentationRepresentationModified:Mo,triggerSegmentationRepresentationRemoved:$u},Symbol.toStringTag,{value:"Module"})),Ly={renderOutline:!0,outlineWidthAutoGenerated:3,outlineWidth:1,outlineWidthInactive:1,outlineOpacity:1,outlineOpacityInactive:.85,outlineDash:void 0,outlineDashInactive:void 0,outlineDashAutoGenerated:"5,3",activeSegmentOutlineWidthDelta:0,renderFill:!0,fillAlpha:.5,fillAlphaInactive:.3,fillAlphaAutoGenerated:.3};function Oy(){return Ly}const Ry={renderOutline:!0,renderOutlineInactive:!0,outlineWidth:3,outlineWidthInactive:2,activeSegmentOutlineWidthDelta:0,renderFill:!0,renderFillInactive:!0,fillAlpha:.5,fillAlphaInactive:.4,outlineOpacity:1,outlineOpacityInactive:.85};function Ny(){return Ry}class ky{constructor(){this.config={global:{},segmentations:{},viewportsStyle:{}}}setStyle(t,n,e=!0){const{viewportId:o,segmentationId:s,type:a,segmentIndex:r}=t,c=this.getStyle(t),l=e?{...c,...n}:n;let d;if(!o&&!s?d=l:e?d=this.copyActiveToInactiveIfNotProvided(l,a):d=l,!a)throw new Error("Type is required to set a style");if(o){this.config.viewportsStyle[o]||(this.config.viewportsStyle[o]={renderInactiveSegmentations:!1,representations:{}});const u=this.config.viewportsStyle[o].representations;if(s){u[s]||(u[s]={}),u[s][a]||(u[s][a]={});const h=u[s][a];r!==void 0?(h.perSegment||(h.perSegment={}),h.perSegment[r]=d):h.allSegments=d}else{const h="__allSegmentations__";u[h]||(u[h]={}),u[h][a]||(u[h][a]={}),u[h][a].allSegments=d}}else if(s){this.config.segmentations[s]||(this.config.segmentations[s]={}),this.config.segmentations[s][a]||(this.config.segmentations[s][a]={});const u=this.config.segmentations[s][a];r!==void 0?(u.perSegment||(u.perSegment={}),u.perSegment[r]=d):u.allSegments=d}else this.config.global[a]=d}copyActiveToInactiveIfNotProvided(t,n){const e={...t};if(n===St.Labelmap){const o=e;o.renderOutlineInactive??=o.renderOutline,o.outlineWidthInactive??=o.outlineWidth,o.renderFillInactive??=o.renderFill,o.fillAlphaInactive??=o.fillAlpha,o.outlineOpacityInactive??=o.outlineOpacity}else if(n===St.Contour){const o=e;o.outlineWidthInactive??=o.outlineWidth,o.outlineOpacityInactive??=o.outlineOpacity,o.outlineDashInactive??=o.outlineDash,o.renderOutlineInactive??=o.renderOutline,o.renderFillInactive??=o.renderFill,o.fillAlphaInactive??=o.fillAlpha}return e}getStyle(t){const{viewportId:n,segmentationId:e,type:o,segmentIndex:s}=t;let a=this.getDefaultStyle(o);if(this.config.global[o]&&(a={...a,...this.config.global[o]}),this.config.segmentations[e]?.[o]&&(a={...a,...this.config.segmentations[e][o].allSegments},s!==void 0&&this.config.segmentations[e][o].perSegment?.[s]&&(a={...a,...this.config.segmentations[e][o].perSegment[s]})),n&&this.config.viewportsStyle[n]){this.config.viewportsStyle[n].renderInactiveSegmentations;const r="__allSegmentations__";this.config.viewportsStyle[n].representations[r]?.[o]&&(a={...a,...this.config.viewportsStyle[n].representations[r][o].allSegments}),e&&this.config.viewportsStyle[n].representations[e]?.[o]&&(a={...a,...this.config.viewportsStyle[n].representations[e][o].allSegments},s!==void 0&&this.config.viewportsStyle[n].representations[e][o].perSegment?.[s]&&(a={...a,...this.config.viewportsStyle[n].representations[e][o].perSegment[s]}))}return a}getRenderInactiveSegmentations(t){return this.config.viewportsStyle[t]?.renderInactiveSegmentations}setRenderInactiveSegmentations(t,n){this.config.viewportsStyle[t]||(this.config.viewportsStyle[t]={renderInactiveSegmentations:!1,representations:{}}),this.config.viewportsStyle[t].renderInactiveSegmentations=n}getDefaultStyle(t){switch(t){case St.Labelmap:return Ny();case St.Contour:return Oy();case St.Surface:return{};default:throw new Error(`Unknown representation type: ${t}`)}}clearSegmentationStyle(t){this.config.segmentations[t]&&delete this.config.segmentations[t]}clearAllSegmentationStyles(){this.config.segmentations={}}clearViewportStyle(t){this.config.viewportsStyle[t]&&delete this.config.viewportsStyle[t]}clearAllViewportStyles(){for(const t in this.config.viewportsStyle){const e=this.config.viewportsStyle[t].renderInactiveSegmentations;this.config.viewportsStyle[t]={renderInactiveSegmentations:e,representations:{}}}}resetToGlobalStyle(){this.clearAllSegmentationStyles(),this.clearAllViewportStyles()}hasCustomStyle(t){const{type:n}=t,e=this.getStyle(t),o=this.getDefaultStyle(n);return!ab(e,o)}}const Yn=new ky;function Uy(i){const t={segmentationId:i};Rt(Z,E.SEGMENTATION_ADDED,t)}function Sc(i,t,n){if(n==null){delete i[t];return}i[t]=n}function pi(i){const t=kn(i);if(!t)return;const n=MI(i)[0]??1,e=t.primaryLabelmapId??t.segmentBindings[n]?.labelmapId??Object.keys(t.labelmaps)[0],o=t.labelmaps[e];o&&(Sc(t,"volumeId",o.volumeId),Sc(t,"referencedVolumeId",o.referencedVolumeId),Sc(t,"imageIds",o.imageIds),Sc(t,"referencedImageIds",o.referencedImageIds))}function nm(i){const t=new Map;return cn(i).forEach(n=>{ql(n,(e,o)=>{const s=t.get(e)??[];s.includes(o)||s.push(o),t.set(e,s)})}),t}function Hi(i,t){return kn(i)?.segmentBindings?.[t]}function cr(i,t,n){const e=kn(i);if(!e)return;const o=e.segmentBindings[t];if(o){const a=e.labelmaps[o.labelmapId];a?.labelToSegmentIndex&&delete a.labelToSegmentIndex[o.labelValue]}e.segmentBindings[t]=n;const s=e.labelmaps[n.labelmapId];s&&(s.labelToSegmentIndex||={},s.labelToSegmentIndex[n.labelValue]=t)}function Yh(i,t){const n=kn(i);return n?Object.entries(n.segmentBindings).filter(([,e])=>e.labelmapId===t).map(([e])=>Number(e)).sort((e,o)=>e-o):[]}function fa(i,t,n){const e=_a(i,t);if(!(!e||n==null))return e.labelToSegmentIndex?.[n]??n}function Sr(i,t){const n=Hi(i,t);if(n)return _a(i,n.labelmapId)}function Kl(i,t){return Sr(i,t)??cn(i)[0]}function Vy(i,t){const n=kn(i),e=n?.segmentBindings?.[t];if(!n||!e)return;const o=n.labelmaps[e.labelmapId];o?.labelToSegmentIndex&&delete o.labelToSegmentIndex[e.labelValue],delete n.segmentBindings[t],Yh(i,e.labelmapId).length===0&&LI(i,e.labelmapId),pi(i)}function Fy(i,t){const n=Q.getVolume(t.volumeId),e=`${i.segmentationId}-storage-${Se()}`,o=t.referencedVolumeId??n?.referencedVolumeId??t.volumeId,s=Xr(o,{volumeId:e});return{labelmapId:e,storageKind:"volume",volumeId:e,imageIds:s.imageIds,referencedVolumeId:o,referencedImageIds:t.referencedImageIds??n?.referencedImageIds,labelToSegmentIndex:{}}}function om(i,t){const n=t.referencedImageIds??t.imageIds??[],e=t.imageIds??[],s=(e[0]?Q.getImage(e[0]):null)?.voxelManager?.getConstructor?.().name??"Uint8Array",a=pv(n,{getDerivedImageId:r=>`${i.segmentationId}-storage-${Se()}-${r.slice(-12)}`,targetBuffer:{type:s}});return{labelmapId:`${i.segmentationId}-storage-${Se()}`,storageKind:"stack",imageIds:a.map(r=>r.imageId),referencedVolumeId:t.referencedVolumeId,referencedImageIds:n,labelToSegmentIndex:{}}}function Gy(i,t){return t.imageIds?.length||t.referencedImageIds?.length?om(i,t):t.volumeId?Fy(i,t):om(i,t)}function Hy(i,t,n={}){const e=Hi(i,t);if(!e)return;const o=_a(i,e.labelmapId);if(!o)return;if(Yh(i,o.labelmapId).length<=1)return o;const s=Gy(i,o);Jg(i,s);const a=[];if(o.volumeId&&s.volumeId){const l=Q.getVolume(o.volumeId),d=Q.getVolume(s.volumeId),u=[];l.voxelManager.forEach(({value:h,index:f})=>{h===e.labelValue&&(d.voxelManager.setAtIndex(f,1),l.voxelManager.setAtIndex(f,0),u.push(f))}),u.length&&a.push({source:l.voxelManager,target:d.voxelManager,indices:u})}else{const l=o.imageIds??[],d=s.imageIds??[];l.forEach((u,h)=>{const f=Q.getImage(u),g=Q.getImage(d[h]);if(!f||!g)return;const m=[];f.voxelManager.forEach(({value:p,index:v})=>{p===e.labelValue&&(g.voxelManager.setAtIndex(v,1),f.voxelManager.setAtIndex(v,0),m.push(v))}),m.length&&a.push({source:f.voxelManager,target:g.voxelManager,indices:m})})}const r={...e},c={labelmapId:s.labelmapId,labelValue:1};return cr(i,t,{...c}),pi(i),n.moveStepCallback?.({undo:()=>{for(const{source:l,target:d,indices:u}of a)for(const h of u)d.setAtIndex(h,0),l.setAtIndex(h,r.labelValue);cr(i,t,{...r}),LI(i,s.labelmapId),pi(i)},redo:()=>{Jg(i,s);for(const{source:l,target:d,indices:u}of a)for(const h of u)l.setAtIndex(h,0),d.setAtIndex(h,1);cr(i,t,{...c}),pi(i)}}),s}function Wy(i,t,n,e=[]){return Yh(i,t).filter(o=>o!==n&&!e.includes(o))}function By(i,t,n,e,o={}){if(!e||!n.length)return!1;const s=new Set(n);let a=!1;return e.forEach(({value:r})=>{if(!r||a)return;const c=fa(i,t,Number(r));c&&s.has(c)&&(a=!0)},{imageData:o.segmentationImageData,isInObject:o.isInObject,boundsIJK:o.isInObjectBoundsIJK}),a}function zy(i,t,n=[]){return!t||!n.length?[]:n.map(e=>Hi(i,e)).filter(e=>!!e&&e.labelmapId!==t)}function $y(i,t){const{segmentIndex:n}=t,e=t.overwriteSegmentIndices??[];if(!n)return{segmentIndex:n,labelValue:0,overwriteSegmentIndices:e,protectedSegmentIndices:[],crossLayerEraseBindings:[],movedSegment:!1};const o=Hi(i,n),s=o?_a(i,o.labelmapId):void 0;if(!o||!s)return{segmentIndex:n,labelValue:n,overwriteSegmentIndices:e,protectedSegmentIndices:[],crossLayerEraseBindings:[],movedSegment:!1};let a=s,r=o.labelmapId,c=o.labelValue,l=!1;const d=Wy(i,r,n,e),u=By(i,r,d,t.segmentationVoxelManager,{segmentationImageData:t.segmentationImageData,isInObject:t.isInObject,isInObjectBoundsIJK:t.isInObjectBoundsIJK});let h;if(u){const g=(t.moveSegmentToPrivateLabelmap??Hy)(i,n,{moveStepCallback:p=>h=p}),m=Hi(i,n);g&&m?(a=g,r=m.labelmapId,c=m.labelValue,l=g.labelmapId!==s.labelmapId):g&&(a=g,r=g.labelmapId,c=1,l=g.labelmapId!==s.labelmapId)}return{segmentIndex:n,labelmapId:r,labelValue:c,sourceLayer:s,activeLayer:a,overwriteSegmentIndices:e,protectedSegmentIndices:d,crossLayerEraseBindings:zy(i,r,e),movedSegment:l,moveStep:h}}function jy(i){const t=i;return typeof t?.getImageIds=="function"?t.getImageIds():[]}function zI(i){const t=i;return typeof t?.getCurrentImageId=="function"?t.getCurrentImageId():void 0}function Xy(i,t){const n=t.imageId??zI(t.viewport);if(!n)return-1;const e=t.sourceLayer?.imageIds?.indexOf(n)??-1;if(e>=0)return e;const o=i.imageIds?.indexOf(n)??-1;return o>=0?o:jy(t.viewport).indexOf(n)}function qy(i,t={}){const n=Xy(i,t);return n>=0?i.imageIds?.[n]:i.imageIds?.[0]}function $I(i,t={}){const n=qy(i,t);if(t.preferVolume||i.volumeId||t.viewport instanceof pn){const o=$n(i);return{imageId:n,imageData:o?.imageData,voxelManager:o?.voxelManager,volume:o}}const e=n?Q.getImage(n):void 0;return{imageId:n,voxelManager:e?.voxelManager,image:e}}function Yy(i,t,n,e){const o=$n(i);if(!o)return;const s=[];o.voxelManager.forEach(({value:a,index:r,pointIJK:c})=>{if(a!==t.labelValue)return;const l=o.imageData.indexToWorld(c);n.isInObject(l)&&(o.voxelManager.setAtIndex(r,0),s.push(r))},{imageData:o.imageData,boundsIJK:n.isInObjectBoundsIJK}),s.length&&n.crossLayerEraseCallback?.({voxelManager:o.voxelManager,labelValue:t.labelValue,indices:s}),o.voxelManager?.getArrayOfModifiedSlices?.()?.forEach(a=>e.add(a))}function Ky(i,t,n,e){const o=n.viewport,s=zI(n.viewport)??n.imageId,{image:a,voxelManager:r}=$I(i,{viewport:n.viewport,imageId:s});if(!a||!r)return;const c=[];r.forEach(({value:d,index:u,pointIJK:h})=>{if(d!==t.labelValue)return;const f=n.referenceImageData.indexToWorld(h);n.isInObject(f)&&(r.setAtIndex(u,0),c.push(u))},{imageData:n.referenceImageData,boundsIJK:n.isInObjectBoundsIJK}),c.length&&n.crossLayerEraseCallback?.({voxelManager:r,labelValue:t.labelValue,indices:c});const l=o.getCurrentImageIdIndex?.();typeof l=="number"&&e.add(l)}function Zy(i,t,n){if(!t?.crossLayerEraseBindings?.length)return[];const e=new Set;return t.crossLayerEraseBindings.forEach(o=>{const s=_a(i,o.labelmapId);if(s){if(n.viewport instanceof pn||s.volumeId){Yy(s,o,n,e);return}Ky(s,o,n,e)}}),Array.from(e)}class Jy{constructor(t){this.stackLabelmapImageIdReferenceMap=new Map,this.labelmapImageIdReferenceMap=new Map,this.keysBySegmentationId=new Map,this.completedScanResultsBySegmentationId=new Map,this.getSegmentation=t}reset(){this.stackLabelmapImageIdReferenceMap.clear(),this.labelmapImageIdReferenceMap.clear(),this.keysBySegmentationId.clear(),this.completedScanResultsBySegmentationId.clear()}removeSegmentation(t){this.stackLabelmapImageIdReferenceMap.delete(t),this.completedScanResultsBySegmentationId.delete(t);const n=this.keysBySegmentationId.get(t);if(n){for(const e of n)this.labelmapImageIdReferenceMap.delete(e);this.keysBySegmentationId.delete(t)}}setLabelmapImageIds(t,n,e){this.labelmapImageIdReferenceMap.set(n,e);let o=this.keysBySegmentationId.get(t);o||(o=new Set,this.keysBySegmentationId.set(t,o)),o.add(n)}getLabelmapImageIds(t){const n=t.Labelmap;let e;if(n){if(n?.labelmaps){const o=Object.values(n.labelmaps).flatMap(s=>s.imageIds?.length?s.imageIds:s.volumeId?Q.getVolume(s.volumeId)?.imageIds:[]);return Array.from(new Set(o.filter(Boolean)))}if(n.imageIds)e=n.imageIds;else if(n.volumeId){const o=n.volumeId;e=Q.getVolume(o).imageIds}return e}}getLabelmapImageIdsForImageId(t,n){const e=this.getSegmentation(n);if(e?.representationData?.Labelmap)return kn(e),nm(e).get(t)}updateLabelmapSegmentationImageReferences(t,n){const e=this.getSegmentation(n);if(!e)return;this.stackLabelmapImageIdReferenceMap.has(n)||this.stackLabelmapImageIdReferenceMap.set(n,new Map);const{representationData:o}=e;if(!o.Labelmap)return;const s=this.getLabelmapImageIds(o),a=le(t);if(!a||!s?.length)return;const r=a.viewport,c=this.generateScanKey("current",r,s);if(c&&this.hasCompletedScan(n,c))return this.getCompletedScanResult(n,c);const l=this.updateLabelmapSegmentationReferences(n,r,s);return c&&this.markCompletedScan(n,c,l),l}generateScanKey(t,n,e){const o=typeof n.getCurrentImageId=="function"?n.getCurrentImageId():void 0;if(o)return`${t}|${n.id}|${o}|${e.length}|${e[0]}|${e[e.length-1]}`}hasCompletedScan(t,n){return!!this.completedScanResultsBySegmentationId.get(t)?.has(n)}getCompletedScanResult(t,n){return this.completedScanResultsBySegmentationId.get(t)?.get(n)}markCompletedScan(t,n,e){let o=this.completedScanResultsBySegmentationId.get(t);o||(o=new Map,this.completedScanResultsBySegmentationId.set(t,o)),o.set(n,e)}getCurrentLabelmapImageIdsForViewport(t,n){const e=le(t);if(!e)return;const{viewport:o}=e;if(zn(o)!=="image"||typeof o.getCurrentImageId!="function")return;const a=o.getCurrentImageId(),r=this.getSegmentation(n);if(!r)return;kn(r);const l=o.getImageIds().indexOf(a),d=[];cn(r).forEach(m=>{const p=vy(m,a);if(p.length){d.push(...p);return}if(l!==-1&&m.imageIds?.[l]){d.push(m.imageIds[l]);return}m.imageIds?.some(v=>{const I=o.isReferenceViewable({referencedImageId:v},{asOverlay:!0});return I&&d.push(v),!!I})});const u=Array.from(new Set(d)),h=this.generateMapKey({segmentationId:n,referenceImageId:a});this.setLabelmapImageIds(n,h,u),this.stackLabelmapImageIdReferenceMap.has(n)||this.stackLabelmapImageIdReferenceMap.set(n,new Map);const f=Object.keys(r.segments).find(m=>r.segments[m].active),g=f?Sr(r,Number(f))?.imageIds?.[l]:void 0;return this.stackLabelmapImageIdReferenceMap.get(n).set(a,g??u[0]),u}getCurrentLabelmapImageIdForViewport(t,n){const e=le(t);if(!e)return;const{viewport:o}=e;if(zn(o)!=="image"||typeof o.getCurrentImageId!="function")return;const a=o.getCurrentImageId(),r=this.getCurrentLabelmapImageIdsForViewport(t,n);if(!r?.length)return;const c=this.getSegmentation(n),l=o.getImageIds().indexOf(a),d=c?Object.keys(c.segments).find(h=>c.segments[h].active):void 0;return(c&&d?Sr(c,Number(d))?.imageIds?.[l]:void 0)??r[0]}getStackSegmentationImageIdsForViewport(t,n){const e=this.getSegmentation(n);if(!e)return[];this.updateAllLabelmapSegmentationImageReferences(t,n);const s=le(t)?.viewport.getImageIds?.()??[],a=nm(e);return s.flatMap(r=>a.get(r)??[])}updateLabelmapSegmentationReferences(t,n,e,o){const s=n.getCurrentImageId();let a=!1;for(const r of e)n.isReferenceViewable({referencedImageId:r},{asOverlay:!0})&&(a=!0,this.stackLabelmapImageIdReferenceMap.get(t).set(s,r),this.updateLabelmapImageIdReferenceMap({segmentationId:t,referenceImageId:s,labelmapImageId:r}));return o?.(n,t,e),a?this.stackLabelmapImageIdReferenceMap.get(t).get(s):void 0}updateAllLabelmapSegmentationImageReferences(t,n){const e=this.getSegmentation(n);if(!e)return;this.stackLabelmapImageIdReferenceMap.has(n)||this.stackLabelmapImageIdReferenceMap.set(n,new Map);const{representationData:o}=e;if(!o.Labelmap)return;const s=this.getLabelmapImageIds(o),a=le(t);if(!a||!s?.length)return;const r=a.viewport,c=this.generateScanKey("all",r,s);c&&this.hasCompletedScan(n,c)||(c&&this.markCompletedScan(n,c),this.updateLabelmapSegmentationReferences(n,r,s,(l,d,u)=>{l.getImageIds().forEach((f,g)=>{for(const m of u)l.isReferenceViewable({referencedImageId:m,sliceIndex:g},{asOverlay:!0,withNavigation:!0})&&(this.stackLabelmapImageIdReferenceMap.get(d).set(f,m),this.updateLabelmapImageIdReferenceMap({segmentationId:d,referenceImageId:f,labelmapImageId:m}))})}))}updateLabelmapImageIdReferenceMap({segmentationId:t,referenceImageId:n,labelmapImageId:e}){const o=this.generateMapKey({segmentationId:t,referenceImageId:n});if(!this.labelmapImageIdReferenceMap.has(o)){this.setLabelmapImageIds(t,o,[e]);return}const s=this.labelmapImageIdReferenceMap.get(o)??[],a=Array.from(new Set([...s,e]));this.setLabelmapImageIds(t,o,a)}generateMapKey({segmentationId:t,referenceImageId:n}){return`${t}-${n}`}}const im={colorLUT:[],segmentations:[],viewportSegRepresentations:{}};class Qy{constructor(t){t||=Se(),this.state=Object.freeze(Re(im)),this.uid=t,this.labelmapImageReferenceResolver=new Jy(this.getSegmentation.bind(this))}getState(){return this.state}updateState(t){const n=Re(this.state);t(n),this.state=Object.freeze(n)}getColorLUT(t){return this.state.colorLUT[t]}getNextColorLUTIndex(){return this.state.colorLUT.length}resetState(){this.labelmapImageReferenceResolver.reset(),this.state=Object.freeze(Re(im))}getSegmentation(t){return this.state.segmentations.find(n=>n.segmentationId===t)}updateSegmentation(t,n){this.updateState(e=>{const o=e.segmentations.find(s=>s.segmentationId===t);if(!o){console.warn(`Segmentation with id ${t} not found. Update aborted.`);return}Object.assign(o,n),o.representationData?.Labelmap&&(kn(o),pi(o))}),Co(t)}addSegmentation(t){if(this.getSegmentation(t.segmentationId))throw new Error(`Segmentation with id ${t.segmentationId} already exists`);this.updateState(n=>{const e=Re(t);e.representationData?.Labelmap&&(kn(e),pi(e));const o=e.representationData.Labelmap;if(o?.volumeId&&!("imageIds"in o)){const s=this.getLabelmapImageIds(e.representationData);e.representationData.Labelmap.imageIds=s}n.segmentations.push(e)}),Uy(t.segmentationId)}removeSegmentation(t){this.labelmapImageReferenceResolver.removeSegmentation(t),this.updateState(n=>{const e=n.segmentations.filter(o=>o.segmentationId!==t);n.segmentations.splice(0,n.segmentations.length,...e)}),qh(t)}addSegmentationRepresentation(t,n,e,o){if(!le(t))return;if(this.getSegmentationRepresentations(t,{type:e,segmentationId:n}).length>0){console.debug("A segmentation representation of type",e,"already exists in viewport",t,"for segmentation",n),Mo(t,n,e);return}this.updateState(r=>{r.viewportSegRepresentations[t]||(r.viewportSegRepresentations[t]=[],Yn.setRenderInactiveSegmentations(t,!0)),e!==St.Labelmap?this.addDefaultSegmentationRepresentation(r,t,n,e,o):this.addLabelmapRepresentation(r,t,n,o)}),Mo(t,n,e)}addDefaultSegmentationRepresentation(t,n,e,o,s){const a=t.segmentations.find(c=>c.segmentationId===e);if(!a)return;const r={};Object.keys(a.segments).forEach(c=>{r[Number(c)]={visible:!0}}),t.viewportSegRepresentations[n].push({segmentationId:e,type:o,active:!0,visible:!0,colorLUTIndex:s?.colorLUTIndex||0,segments:r,config:{...sm(o),...s}}),this._setActiveSegmentation(t,n,e)}addLabelmapRepresentation(t,n,e,o=sm(St.Labelmap)){if(!le(n))return;const a=this.getSegmentation(e);if(!a)return;const{representationData:r}=a;if(!r.Labelmap)return this.addDefaultSegmentationRepresentation(t,n,e,St.Labelmap,o);this.processLabelmapRepresentationAddition(n,e),this.addDefaultSegmentationRepresentation(t,n,e,St.Labelmap,o)}async processLabelmapRepresentationAddition(t,n){const e=le(t);if(!e)return;const o=this.getSegmentation(n);if(!o)return;const s=zn(e.viewport)==="volume",{representationData:a}=o,r=!!a.Labelmap.volumeId;!s&&!r&&this.updateLabelmapSegmentationImageReferences(t,o.segmentationId)}updateLabelmapSegmentationImageReferences(t,n){return this.labelmapImageReferenceResolver.updateLabelmapSegmentationImageReferences(t,n)}getLabelmapImageIds(t){return this.labelmapImageReferenceResolver.getLabelmapImageIds(t)}getLabelmapImageIdsForImageId(t,n){return this.labelmapImageReferenceResolver.getLabelmapImageIdsForImageId(t,n)}getCurrentLabelmapImageIdsForViewport(t,n){return this.labelmapImageReferenceResolver.getCurrentLabelmapImageIdsForViewport(t,n)}getCurrentLabelmapImageIdForViewport(t,n){return this.labelmapImageReferenceResolver.getCurrentLabelmapImageIdForViewport(t,n)}getStackSegmentationImageIdsForViewport(t,n){return this.labelmapImageReferenceResolver.getStackSegmentationImageIdsForViewport(t,n)}removeSegmentationRepresentationsInternal(t,n){const e=[];return this.updateState(o=>{if(!o.viewportSegRepresentations[t])return;const s=o.viewportSegRepresentations[t];let a=!1;if(!n||Object.values(n).every(r=>r===void 0))e.push(...s),delete o.viewportSegRepresentations[t];else{const{segmentationId:r,type:c}=n;o.viewportSegRepresentations[t]=s.filter(l=>{const d=r&&c&&l.segmentationId===r&&l.type===c||r&&!c&&l.segmentationId===r||!r&&c&&l.type===c;return d&&(e.push(l),l.active&&(a=!0)),!d}),o.viewportSegRepresentations[t].length===0?delete o.viewportSegRepresentations[t]:a&&(o.viewportSegRepresentations[t][0].active=!0)}}),e}removeSegmentationRepresentations(t,n){const e=this.removeSegmentationRepresentationsInternal(t,n);e.forEach(s=>{$u(t,s.segmentationId,s.type)});const o=this.getSegmentationRepresentations(t);return o.length>0&&o[0].active&&Mo(t,o[0].segmentationId,o[0].type),e}removeSegmentationRepresentation(t,n,e){const o=this.removeSegmentationRepresentationsInternal(t,n);return e||o.forEach(({segmentationId:s,type:a})=>{$u(t,s,a)}),o}_setActiveSegmentation(t,n,e){const o=t.viewportSegRepresentations[n];o&&o.forEach(s=>{s.active=s.segmentationId===e})}setActiveSegmentation(t,n){this.updateState(e=>{const o=e.viewportSegRepresentations[t];o&&o.forEach(s=>{s.active=s.segmentationId===n})}),Mo(t,n)}getActiveSegmentation(t){if(!this.state.viewportSegRepresentations[t])return;const n=this.state.viewportSegRepresentations[t].find(e=>e.active);if(n)return this.getSegmentation(n.segmentationId)}getSegmentationRepresentations(t,n={}){const e=this.state.viewportSegRepresentations[t];return e?!n.type&&!n.segmentationId?e:e.filter(o=>{const s=n.type?o.type===n.type:!0,a=n.segmentationId?o.segmentationId===n.segmentationId:!0;return s&&a}):[]}getSegmentationRepresentation(t,n){return this.getSegmentationRepresentations(t,n)[0]}getSegmentationRepresentationVisibility(t,n){return this.getSegmentationRepresentation(t,n)?.visible}setSegmentationRepresentationVisibility(t,n,e){this.updateState(o=>{const s=o.viewportSegRepresentations[t]?.filter(a=>a.segmentationId===n.segmentationId&&a.type===n.type);s&&s.forEach(a=>{a.visible=e,Object.values(a.segments).forEach(r=>{r.visible=e})})}),Mo(t,n.segmentationId,n.type)}addColorLUT(t,n){this.updateState(e=>{e.colorLUT[n]&&console.warn("Color LUT table already exists, overwriting"),e.colorLUT[n]=Re(t)})}removeColorLUT(t){this.updateState(n=>{delete n.colorLUT[t]})}_getStackIdForImageIds(t){return t.map(n=>n.slice(-Math.round(n.length*.15))).join("_")}getAllViewportSegmentationRepresentations(){return Object.entries(this.state.viewportSegRepresentations).map(([t,n])=>({viewportId:t,representations:n}))}getSegmentationRepresentationsBySegmentationId(t){const n=[];return Object.entries(this.state.viewportSegRepresentations).forEach(([e,o])=>{const s=o.filter(a=>a.segmentationId===t);s.length>0&&n.push({viewportId:e,representations:s})}),n}}async function jI({imageIds:i,options:t}){const n=i,e=t?.volumeId||Se();return await Iv(e,n),{volumeId:e}}async function tx({segmentationId:i,options:t}){const n=me.getSegmentation(i),e=n.representationData.Labelmap,{volumeId:o}=await jI({imageIds:e.imageIds,options:t});n.representationData.Labelmap.volumeId=o}function sm(i){const t=vv.newInstance(),n=bh.newInstance();return n.addPoint(0,0),i===St.Labelmap?{cfun:t,ofun:n}:{}}const me=new Qy("DEFAULT");function Dt(i){return me.getSegmentation(i)}function Rn(i,t={}){return me.getSegmentationRepresentations(i,t)}function Zl(i,t){const n=me;if(!t.segmentationId||!t.type)throw new Error("getSegmentationRepresentation: No segmentationId or type provided, you need to provide at least one of them");return n.getSegmentationRepresentations(i,t)?.[0]}function XI(i){return me.getSegmentationRepresentationsBySegmentationId(i)}const{CalibrationTypes:es}=Ea,Kd="px",am="voxels",qI=[1,2,3,4],ju=["4,3","4,7","4,-1"],Hs={0:"px",1:"percent",2:"dB",3:"cm",4:"seconds",5:"hertz",6:"dB/seconds",7:"cm/sec",8:"cm²",9:"cm²/s",12:"degrees",[-1]:"mV"},Cc="²",ex=[es.ERMF,es.USER,es.ERROR,es.PROJECTION,es.CALIBRATED,es.UNKNOWN],ao=(i,t)=>{const{calibration:n,hasPixelSpacing:e,spacing:o=[1,1,1]}=i;let s=e?"mm":Kd;const a=e?"mm³":am;let r=s+Cc;const c=n?.scale||1;let l=c/(n?.columnPixelSpacing||o[0]),d=c/(n?.rowPixelSpacing||o[1]),u=c/o[2],h="";if(!n||!n.type&&!n.sequenceOfUltrasoundRegions)return{unit:s,areaUnit:r,scale:l,scaleY:d,scaleZ:u,volumeUnit:a};if(ex.includes(n?.type)&&(h=n.type),n.type===es.UNCALIBRATED)return{unit:Kd,areaUnit:Kd+Cc,scale:l,scaleY:d,scaleZ:u,volumeUnit:am};if(n.sequenceOfUltrasoundRegions){const f=n.sequenceOfUltrasoundRegions.find(g=>t.every(m=>m[0]>=g.regionLocationMinX0&&m[0]<=g.regionLocationMaxX1&&m[1]>=g.regionLocationMinY0&&m[1]<=g.regionLocationMaxY1)&&(qI.includes(g.regionDataType)||ju.includes(`${g.physicalUnitsXDirection},${g.physicalUnitsYDirection}`)));if(f&&f.physicalUnitsXDirection===f.physicalUnitsYDirection){const g=Math.abs(f.physicalDeltaX),m=Math.abs(f.physicalDeltaY);l=1/g,d=1/m,h="US Region",s=Hs[f.physicalUnitsXDirection]||"unknown",r=s+Cc}else if(f&&f.physicalUnitsYDirection===-1){const g=Math.abs(f.physicalDeltaX),m=Math.abs(f.physicalDeltaY);l=1/g,d=1/m,h="ECG Region",s=Hs[f.physicalUnitsXDirection]||Hs[f.physicalUnitsYDirection]||"unknown",r=(Hs[f.physicalUnitsYDirection]||"px")+Cc}}else n.scale&&(l=n.scale);return{unit:s+(h?` ${h}`:""),areaUnit:r+(h?` ${h}`:""),volumeUnit:a+(h?` ${h}`:""),scale:l,scaleY:d,scaleZ:u}},Cr=(i,t)=>{const[n]=t,{calibration:e}=i;let o=["raw"],s=[null],a="";if(!e||!e.type&&!e.sequenceOfUltrasoundRegions)return{units:o,values:s};if(e.sequenceOfUltrasoundRegions){const r=e.sequenceOfUltrasoundRegions.filter(m=>(qI.includes(m.regionDataType)||ju.includes(`${m.physicalUnitsXDirection},${m.physicalUnitsYDirection}`))&&ju.includes(`${m.physicalUnitsXDirection},${m.physicalUnitsYDirection}`));if(!r?.length)return{units:o,values:s};const c=r.find(m=>n[0]>=m.regionLocationMinX0&&n[0]<=m.regionLocationMaxX1&&n[1]>=m.regionLocationMinY0&&n[1]<=m.regionLocationMaxY1);if(!c)return{units:o,values:s};const{referencePixelX0:l=0,referencePixelY0:d=0}=c,{physicalDeltaX:u,physicalDeltaY:h}=c,f=(n[1]-c.regionLocationMinY0-d)*h,g=(n[0]-c.regionLocationMinX0-l)*u;a=c.physicalUnitsYDirection===-1?"ECG Region":"US Region",s=[g,f],o=[Hs[c.physicalUnitsXDirection]??"unknown",Hs[c.physicalUnitsYDirection]??"unknown"]}return{units:o,values:s,calibrationType:a}},Kh=i=>i.calibration?.aspect||1;function Qr(i,t){return i.minX<=t.maxX&&i.maxX>=t.minX&&i.minY<=t.maxY&&i.maxY>=t.minY}function ol(i,t){const n=i.maxX-i.minX,e=i.maxY-i.minY,o=[n,e],s=[i.minX+n/2,i.minY+e/2],a=[Math.abs(t[0]-s[0]),Math.abs(t[1]-s[1])],r=a[0]-o[0]*.5,c=a[1]-o[1]*.5;if(r>0&&c>0)return r*r+c*c;const l=Math.max(r,0)+Math.max(c,0);return l*l}function nx(i,t){return Math.sqrt(ol(i,t))}const ox=Object.freeze(Object.defineProperty({__proto__:null,distanceToPoint:nx,distanceToPointSquared:ol,intersectAABB:Qr},Symbol.toStringTag,{value:"Module"}));class YI{}class KI{constructor(t){this.storePointData=t.storePointData}getStatistics(){console.debug("InstanceCalculator getStatistics called")}}var Zh;const{PointsManager:ix}=oe;function br(i){return{max:[-1/0],min:[1/0],sum:[0],count:0,maxIJK:null,maxLPS:null,minIJK:null,minLPS:null,runMean:[0],m2:[0],m3:[0],m4:[0],allValues:[[]],pointsInShape:i?ix.create3(1024):null,sumLPS:[0,0,0]}}function ZI(i,t,n=null,e=null){Array.isArray(t)&&t.length>1&&i.max.length===1&&(i.max.push(i.max[0],i.max[0]),i.min.push(i.min[0],i.min[0]),i.sum.push(i.sum[0],i.sum[0]),i.runMean.push(0,0),i.m2.push(i.m2[0],i.m2[0]),i.m3.push(i.m3[0],i.m3[0]),i.m4.push(i.m4[0],i.m4[0]),i.allValues.push([],[])),i?.pointsInShape&&n&&i.pointsInShape.push(n);const o=Array.isArray(t)?t:[t];i.count+=1,n&&(i.sumLPS[0]+=n[0],i.sumLPS[1]+=n[1],i.sumLPS[2]+=n[2]),i.max.forEach((s,a)=>{const r=o[a];i.allValues[a].push(r);const c=i.count,l=r-i.runMean[a],d=l/c,u=l*d*(c-1);i.sum[a]+=r,i.runMean[a]+=d,i.m4[a]+=u*d*d*(c*c-3*c+3)+6*d*d*i.m2[a]-4*d*i.m3[a],i.m3[a]+=u*d*(c-2)-3*d*i.m2[a],i.m2[a]+=u,r<i.min[a]&&(i.min[a]=r,a===0&&(i.minIJK=e?[...e]:null,i.minLPS=n?[...n]:null)),r>i.max[a]&&(i.max[a]=r,a===0&&(i.maxIJK=e?[...e]:null,i.maxLPS=n?[...n]:null))})}function sx(i){if(i.length===0)return 0;const t=[...i].sort((e,o)=>e-o),n=Math.floor(t.length/2);return t.length%2===0?(t[n-1]+t[n])/2:t[n]}function JI(i,t){const n=i.sum.map(u=>u/i.count),e=i.m2.map(u=>Math.sqrt(u/i.count)),o=i.sumLPS.map(u=>u/i.count),s=i.m3.map((u,h)=>{const f=i.m2[h]/i.count;return f===0?0:u/(i.count*Math.pow(f,1.5))}),a=i.m4.map((u,h)=>{const f=i.m2[h]/i.count;return f===0?0:u/(i.count*f*f)-3}),r=i.allValues.map(u=>sx(u)),c={max:{name:"max",label:"Max Pixel",value:i.max.length===1?i.max[0]:i.max,unit:t,pointIJK:i.maxIJK?[...i.maxIJK]:null,pointLPS:i.maxLPS?[...i.maxLPS]:null},min:{name:"min",label:"Min Pixel",value:i.min.length===1?i.min[0]:i.min,unit:t,pointIJK:i.minIJK?[...i.minIJK]:null,pointLPS:i.minLPS?[...i.minLPS]:null},mean:{name:"mean",label:"Mean Pixel",value:n.length===1?n[0]:n,unit:t},stdDev:{name:"stdDev",label:"Standard Deviation",value:e.length===1?e[0]:e,unit:t},count:{name:"count",label:"Voxel Count",value:i.count,unit:null},median:{name:"median",label:"Median",value:r.length===1?r[0]:r,unit:t},skewness:{name:"skewness",label:"Skewness",value:s.length===1?s[0]:s,unit:null},kurtosis:{name:"kurtosis",label:"Kurtosis",value:a.length===1?a[0]:a,unit:null},maxLPS:{name:"maxLPS",label:"Max LPS",value:i.maxLPS?Array.from(i.maxLPS):null,unit:null},minLPS:{name:"minLPS",label:"Min LPS",value:i.minLPS?Array.from(i.minLPS):null,unit:null},pointsInShape:i.pointsInShape,center:{name:"center",label:"Center",value:o?[...o]:null,unit:null},array:[]};c.array.push(c.min,c.max,c.mean,c.stdDev,c.median,c.skewness,c.kurtosis,c.count,c.maxLPS,c.minLPS),c.center.value&&c.array.push(c.center);const l=i.pointsInShape!==null,d=br(l);return i.max=d.max,i.min=d.min,i.sum=d.sum,i.count=d.count,i.maxIJK=d.maxIJK,i.maxLPS=d.maxLPS,i.minIJK=d.minIJK,i.minLPS=d.minLPS,i.runMean=d.runMean,i.m2=d.m2,i.m3=d.m3,i.m4=d.m4,i.allValues=d.allValues,i.pointsInShape=d.pointsInShape,i.sumLPS=d.sumLPS,c}class bo extends YI{static statsInit(t){t.storePointData||(this.state.pointsInShape=null),this.state=br(t.storePointData)}}Zh=bo;bo.state=br(!0);bo.statsCallback=({value:i,pointLPS:t=null,pointIJK:n=null})=>{ZI(Zh.state,i,t,n)};bo.getStatistics=i=>JI(Zh.state,i?.unit);class QI extends KI{constructor(t){super(t),this.state=br(t.storePointData)}statsInit(t){this.state=br(t.storePointData)}statsCallback(t){ZI(this.state,t.value,t.pointLPS,t.pointIJK)}getStatistics(t){return JI(this.state,t?.unit)}}const ax=Object.freeze(Object.defineProperty({__proto__:null,BasicStatsCalculator:bo,Calculator:YI,InstanceBasicStatsCalculator:QI,InstanceCalculator:KI},Symbol.toStringTag,{value:"Module"}));function wi(i,t){if(i.length!==t.length)throw Error("Both points should have the same dimensionality");const[n,e,o=0]=i,[s,a,r=0]=t,c=s-n,l=a-e,d=r-o;return c*c+l*l+d*d}function ro(i,t){return Math.sqrt(wi(i,t))}function Xu(i,t){const[n,e]=i,[o,s]=t,a=2*o-n,r=2*s-e;return[a,r]}const rx=Object.freeze(Object.defineProperty({__proto__:null,distanceToPoint:ro,distanceToPointSquared:wi,mirror:Xu},Symbol.toStringTag,{value:"Module"}));function ga(i){const[t,n]=i;return ro(t,n)}function rs(i){const[t,n]=i,e=ro(t,n),o=[t[0]-e,t[1]-e],s=[t[0]+e,t[1]+e];return[o,s]}const cx=Object.freeze(Object.defineProperty({__proto__:null,getCanvasCircleCorners:rs,getCanvasCircleRadius:ga},Symbol.toStringTag,{value:"Module"}));function Jl(i,t,n={}){return n.precalculated||t0(i,n),n.precalculated(t)}const t0=(i,t={})=>{const{xRadius:n,yRadius:e,zRadius:o}=i;(t.invXRadiusSq===void 0||t.invYRadiusSq===void 0||t.invZRadiusSq===void 0)&&(t.invXRadiusSq=n!==0?1/n**2:0,t.invYRadiusSq=e!==0?1/e**2:0,t.invZRadiusSq=o!==0?1/o**2:0);const{invXRadiusSq:s,invYRadiusSq:a,invZRadiusSq:r}=t,{center:c}=i,[l,d,u]=c;return t.precalculated=h=>{const f=h[0]-l;let g=f*f*s;if(g>1)return!1;const m=h[1]-d;if(g+=m*m*a,g>1)return!1;const p=h[2]-u;return g+=p*p*r,g<=1},t};function il(i){const[t,n,e,o]=i,s=[e[0],n[1]],a=[o[0],t[1]];return[s,a]}const lx=Object.freeze(Object.defineProperty({__proto__:null,getCanvasEllipseCorners:il,pointInEllipse:Jl,precalculatePointInEllipse:t0},Symbol.toStringTag,{value:"Module"}));function sl(i,t,n){let e;const o=wi(i,t);if(i[0]===t[0]&&i[1]===t[1]&&(e=i),!e){const s=((n[0]-i[0])*(t[0]-i[0])+(n[1]-i[1])*(t[1]-i[1]))/o;s<0?e=i:s>1?e=t:e=[i[0]+s*(t[0]-i[0]),i[1]+s*(t[1]-i[1])]}return{point:[...e],distanceSquared:wi(n,e)}}function tc(i,t,n){return sl(i,t,n).distanceSquared}function Je(i,t,n){if(i.length!==2||t.length!==2||n.length!==2)throw Error("lineStart, lineEnd, and point should have 2 elements of [x, y]");return Math.sqrt(tc(i,t,n))}function bc(i){return typeof i=="number"?i?i<0?-1:1:i===i?0:NaN:NaN}function al(i,t,n,e,o=!1){const[s,a]=i,[r,c]=t,[l,d]=n,[u,h]=e;if(o){const x=(s-r)*(d-h)-(a-c)*(l-u);if(Math.abs(x)<1e-10)return;const M=((s-l)*(d-h)-(a-d)*(l-u))/x,L=s+M*(r-s),R=a+M*(c-a);return[L,R]}const f=c-a,g=s-r,m=r*a-s*c,p=f*l+g*d+m,v=f*u+g*h+m;if(p!==0&&v!==0&&bc(p)===bc(v))return;const I=h-d,w=l-u,C=u*d-l*h,S=I*s+w*a+C,b=I*r+w*c+C;if(S!==0&&b!==0&&bc(S)===bc(b))return;const _=f*w-I*g;let y;y=g*C-w*m;const D=y/_;y=I*m-f*C;const T=y/_;return[D,T]}const Wa=.01;function jc(i,t,n){const e=i[0]<=t[0]?i[0]:t[0],o=i[0]>=t[0]?i[0]:t[0],s=i[1]<=t[1]?i[1]:t[1],a=i[1]>=t[1]?i[1]:t[1];if(!(n[0]>=e-Wa&&n[0]<=o+Wa&&n[1]>=s-Wa&&n[1]<=a+Wa))return!1;const c=(t[1]-i[1])*(n[0]-t[0])-(t[0]-i[0])*(n[1]-t[1]);return(c>=0?c:-c)<=Wa}const dx=Object.freeze(Object.defineProperty({__proto__:null,distanceToPoint:Je,distanceToPointSquared:tc,distanceToPointSquaredInfo:sl,intersectLine:al,isPointOnLineSegment:jc},Symbol.toStringTag,{value:"Module"}));function Ql(i){if(i.length<3)return!1;const t=i.length,n=i[0],e=i[t-1],o=wi(n,e);return pr(0,o)}function Ln(i,t,n={closed:void 0}){if(i.length<3)return!1;const e=i.length;let o=0;const{closed:s,holes:a}=n;if(a?.length){for(const l of a)if(Ln(l,t))return!1}const r=!(s===void 0?Ql(i):s),c=i.length-(r?1:2);for(let l=0;l<=c;l++){const d=i[l],u=l===e-1?0:l+1,h=i[u],f=d[0]>=h[0]?d[0]:h[0],g=d[1]>=h[1]?d[1]:h[1],m=d[1]<=h[1]?d[1]:h[1];if(t[0]<=f&&t[1]>=m&&t[1]<g){let I=d[0]===h[0];if(!I){const w=(t[1]-d[1])*(h[0]-d[0])/(h[1]-d[1])+d[0];I=t[0]<=w}o+=I?1:0}}return!!(o%2)}function ma(i,t){for(let n=0,e=t.length;n<e;n++)if(!Ln(i,t[n]))return!1;return!0}function Ei(i,t){let n=i;const e=t?.numDimensions||2,o=e===3;if(!Array.isArray(i[0])){const u=i,h=u.length/e;n=new Array(u.length/e);for(let f=0,g=h;f<g;f++)n[f]=[u[f*e],u[f*e+1]],o&&n[f].push(u[f*e+2])}let s=1/0,a=1/0,r=-1/0,c=-1/0,l=1/0,d=-1/0;n=n;for(let u=0,h=n.length;u<h;u++){const[f,g,m]=n[u];s=s<f?s:f,a=a<g?a:g,r=r>f?r:f,c=c>g?c:g,o&&(l=l<m?l:m,d=d>m?d:m)}return o?{minX:s,maxX:r,minY:a,maxY:c,minZ:l,maxZ:d}:{minX:s,maxX:r,minY:a,maxY:c}}function ms(i){const t=i.length;let n=0,e=t-1;for(let o=0;o<t;o++)n+=(i[e][0]+i[o][0])*(i[e][1]-i[o][1]),e=o;return Math.abs(n/2)}function wo(i){if(i.length<3)return 0;const t=i[0];let n=0;for(let e=0,o=i.length;e<o;e++){const s=i[e],a=e===o-1?0:e+1,r=i[a],c=s[0]-t[0],l=s[1]-t[1],d=r[0]-t[0],u=r[1]-t[1];n+=c*u-l*d}return n*=.5,n}function ea(i){return wo(i)>=0?1:-1}function ux(i){const t=B(),n=i[0];for(let e=0,o=i.length;e<o;e++){const s=i[e],a=e===o-1?0:e+1,r=i[a],c=s[0]-n[0],l=s[1]-n[1],d=s[2]-n[2],u=r[0]-n[0],h=r[1]-n[1],f=r[2]-n[2];t[0]+=l*f-d*h,t[1]+=d*u-c*f,t[2]+=c*h-l*u}return bn(t,t,.5),t}function hx(i){const t=ux(i);return Wt(t,t)}function qu(i){const t=wo(i);return[0,0,t/Math.abs(t)]}const hn=1e-7;function Zd(i,t){return i[0]*t[1]-i[1]*t[0]}function Ke(i,t){return ve(i,t,hn)}function e0(i,t,n,e){const o=pe(It(),t,i),s=pe(It(),e,n),a=Zd(o,s),r=pe(It(),n,i),c=Zd(r,o);if(Math.abs(a)<hn){if(Math.abs(c)<hn){const u=zo(o,o),h=zo(s,s);if(u<hn||h<hn)return Ke(i,n)||Ke(i,e)?i:Ke(t,n)||Ke(t,e)?t:null;const f=zo(pe(It(),n,i),o)/u,g=zo(pe(It(),e,i),o)/u,m=zo(pe(It(),i,n),s)/h,p=zo(pe(It(),t,n),s)/h,v=I=>I>=-hn&&I<=1+hn;if(v(f)){const I=nr(It(),i,o,f);if(Ke(n,I))return n}if(v(g)){const I=nr(It(),i,o,g);if(Ke(e,I))return e}if(v(m)){const I=nr(It(),n,s,m);if(Ke(i,I))return i}if(v(p)){const I=nr(It(),n,s,p);if(Ke(t,I))return t}}return null}const l=Zd(r,s)/a,d=c/a;return l>=-hn&&l<=1+hn&&d>=-hn&&d<=1+hn?[i[0]+l*o[0],i[1]+l*o[1]]:null}var ui;(function(i){i[i.Vertex=0]="Vertex",i[i.Intersection=1]="Intersection"})(ui||(ui={}));var Mn;(function(i){i[i.Entering=0]="Entering",i[i.Exiting=1]="Exiting",i[i.Unknown=2]="Unknown"})(Mn||(Mn={}));function n0(i,t){if(i.length!==t.length)return!1;const n=i.length;if(n===0)return!0;let e=!0;for(let s=0;s<n;s++)if(!Ke(i[s],t[s])){e=!1;break}if(e)return!0;let o=!0;for(let s=0;s<n;s++)if(!Ke(i[s],t[n-1-s])){o=!1;break}if(o)return!0;for(let s=1;s<n;s++){let a=!0;for(let c=0;c<n;c++)if(!Ke(i[c],t[(c+s)%n])){a=!1;break}if(a)return!0;let r=!0;for(let c=0;c<n;c++)if(!Ke(i[c],t[(n-1-c+s)%n])){r=!1;break}if(r)return!0}return!1}function fx(i,t){if(i.length<3)return[];if(t.length<3)return[i.slice()];const n=t.slice();if(n0(i,t))return[];const e=wo(i),o=wo(n);Math.sign(e)===Math.sign(o)&&Math.abs(o)>hn&&n.reverse();const s=[];for(let d=0;d<i.length;d++){const u=i[d],h=i[(d+1)%i.length];for(let f=0;f<n.length;f++){const g=n[f],m=n[(f+1)%n.length],p=e0(u,h,g,m);if(p){const v=Math.sqrt(Ni(u,h)),I=Math.sqrt(Ni(g,m));s.push({coord:p,seg1Idx:d,seg2Idx:f,alpha1:v<hn?0:Math.sqrt(Ni(u,p))/v,alpha2:I<hn?0:Math.sqrt(Ni(g,p))/I})}}}const a=(d,u,h)=>{const f=[];let g=0;for(let p=0;p<d.length;p++){const v=d[p];f.push({id:`${u}_v${g++}`,coordinates:v,type:ui.Vertex,originalPolyIndex:u,originalVertexIndex:p,next:null,prev:null,isIntersection:!1,visited:!1});const I=h.filter(w=>(u===0?w.seg1Idx:w.seg2Idx)===p).sort((w,C)=>(u===0?w.alpha1:w.alpha2)-(u===0?C.alpha1:C.alpha2));for(const w of I){if(f.length>0&&Ke(f[f.length-1].coordinates,w.coord)){f[f.length-1].isIntersection||(f[f.length-1].isIntersection=!0,f[f.length-1].intersectionInfo=w,f[f.length-1].alpha=u===0?w.alpha1:w.alpha2);continue}f.push({id:`${u}_i${g++}`,coordinates:w.coord,type:ui.Intersection,originalPolyIndex:u,next:null,prev:null,isIntersection:!0,visited:!1,alpha:u===0?w.alpha1:w.alpha2,intersectionInfo:w})}}const m=[];if(f.length>0){m.push(f[0]);for(let p=1;p<f.length;p++)Ke(f[p].coordinates,m[m.length-1].coordinates)?f[p].isIntersection&&(m[m.length-1].isIntersection=!0,m[m.length-1].intersectionInfo=f[p].intersectionInfo,m[m.length-1].alpha=f[p].alpha):m.push(f[p])}if(m.length>0)for(let p=0;p<m.length;p++)m[p].next=m[(p+1)%m.length],m[p].prev=m[(p-1+m.length)%m.length];return m},r=a(i,0,s),c=a(n,1,s);r.forEach(d=>{if(d.isIntersection){const u=d.intersectionInfo,h=c.find(f=>f.isIntersection&&Ke(f.coordinates,d.coordinates)&&f.intersectionInfo.seg1Idx===u.seg1Idx&&f.intersectionInfo.seg2Idx===u.seg2Idx);if(h){d.partnerNode=h,h.partnerNode=d;const f=d.prev.coordinates,g=d.coordinates,m=h.next.coordinates;pe(It(),g,f),pe(It(),m,g);const p=[(d.prev.coordinates[0]+d.coordinates[0])/2,(d.prev.coordinates[1]+d.coordinates[1])/2];Ln(t,p)?d.intersectionDir=Mn.Exiting:d.intersectionDir=Mn.Entering}else d.isIntersection=!1}}),r.forEach(d=>delete d.intersectionInfo),c.forEach(d=>delete d.intersectionInfo);const l=[];for(let d=0;d<r.length;d++){const u=r[d];if(u.visited||u.isIntersection||Ln(t,u.coordinates))continue;const h=[];let f=u,g=!0,m=0;const p=(r.length+c.length)*2;do{if(m++>p){console.warn("Subtraction: Max iterations reached, possible infinite loop.");break}f.visited=!0,(h.length===0||!Ke(h[h.length-1],f.coordinates))&&h.push(f.coordinates),f.isIntersection&&(g?f.intersectionDir===Mn.Entering&&f.partnerNode&&(f=f.partnerNode,g=!1):f.partnerNode?(f=f.partnerNode,g=!0):console.warn("Subtraction: Intersection on source without partner.")),f=f.next}while(f!==u||!g);h.length>=3&&(Ke(h[0],h[h.length-1])&&h.pop(),h.length>=3&&l.push(h))}return l}function gx(i,t){if(i.length<3||t.length<3)return[];let n=t.slice();const e=wo(i),o=wo(n);if(Math.abs(e)<hn||Math.abs(o)<hn)return[];e<0&&(i=i.slice().reverse()),o<0&&(n=n.slice().reverse());const s=n,a=[];for(let u=0;u<i.length;u++){const h=i[u],f=i[(u+1)%i.length];for(let g=0;g<n.length;g++){const m=n[g],p=n[(g+1)%n.length],v=e0(h,f,m,p);if(v){const I=Math.sqrt(Ni(h,f)),w=Math.sqrt(Ni(m,p));a.push({coord:[...v],seg1Idx:u,seg2Idx:g,alpha1:I<hn?0:Math.sqrt(Ni(h,v))/I,alpha2:w<hn?0:Math.sqrt(Ni(m,v))/w})}}}if(a.length===0)return Ln(s,i[0])&&i.every(u=>Ln(s,u))?[[...i.map(u=>[...u])]]:Ln(i,n[0])&&n.every(u=>Ln(i,u))?[[...n.map(u=>[...u])]]:[];const r=(u,h,f)=>{const g=[];let m=0;for(let v=0;v<u.length;v++){const I=u[v];g.push({id:`${h}_v${m++}`,coordinates:[...I],type:ui.Vertex,originalPolyIndex:h,originalVertexIndex:v,next:null,prev:null,isIntersection:!1,visited:!1,processedInPath:!1,intersectionDir:Mn.Unknown});const w=f.filter(C=>(h===0?C.seg1Idx:C.seg2Idx)===v).sort((C,S)=>(h===0?C.alpha1:C.alpha2)-(h===0?S.alpha1:S.alpha2));for(const C of w){if(g.length>0&&Ke(g[g.length-1].coordinates,C.coord)){const S=g[g.length-1];S.isIntersection||(S.isIntersection=!0,S.intersectionInfo=C,S.alpha=h===0?C.alpha1:C.alpha2,S.type=ui.Intersection);continue}g.push({id:`${h}_i${m++}`,coordinates:[...C.coord],type:ui.Intersection,originalPolyIndex:h,next:null,prev:null,isIntersection:!0,visited:!1,processedInPath:!1,alpha:h===0?C.alpha1:C.alpha2,intersectionInfo:C,intersectionDir:Mn.Unknown})}}const p=[];if(g.length>0){p.push(g[0]);for(let v=1;v<g.length;v++)if(!Ke(g[v].coordinates,p[p.length-1].coordinates))p.push(g[v]);else{const I=p[p.length-1];g[v].isIntersection&&g[v].intersectionInfo&&(I.isIntersection=!0,I.intersectionInfo=g[v].intersectionInfo,I.alpha=g[v].alpha,I.type=ui.Intersection)}}if(p.length>1&&Ke(p[0].coordinates,p[p.length-1].coordinates)){const v=p[0],I=p.pop();I.isIntersection&&!v.isIntersection&&I.intersectionInfo&&(v.isIntersection=!0,v.intersectionInfo=I.intersectionInfo,v.alpha=I.alpha,v.type=ui.Intersection)}if(p.length>0)for(let v=0;v<p.length;v++)p[v].next=p[(v+1)%p.length],p[v].prev=p[(v-1+p.length)%p.length];return p},c=r(i,0,a),l=r(n,1,a);if(c.length===0||l.length===0)return[];c.forEach(u=>{if(u.isIntersection&&u.intersectionInfo){const h=u.intersectionInfo,f=l.find(g=>g.isIntersection&&g.intersectionInfo&&Ke(g.coordinates,u.coordinates)&&g.intersectionInfo.seg1Idx===h.seg1Idx&&g.intersectionInfo.seg2Idx===h.seg2Idx);if(f){u.partnerNode=f,f.partnerNode=u;const g=pe(It(),u.coordinates,u.prev.coordinates),m=pe(It(),f.next.coordinates,f.coordinates),p=g[0]*m[1]-g[1]*m[0];if(p>hn)u.intersectionDir=Mn.Entering,f.intersectionDir=Mn.Exiting;else if(p<-hn)u.intersectionDir=Mn.Exiting,f.intersectionDir=Mn.Entering;else{const v=[(u.prev.coordinates[0]+u.coordinates[0])/2,(u.prev.coordinates[1]+u.coordinates[1])/2];Ln(s,v)?(u.intersectionDir=Mn.Exiting,f.intersectionDir=Mn.Entering):(u.intersectionDir=Mn.Entering,f.intersectionDir=Mn.Exiting)}}else u.isIntersection=!1,u.intersectionInfo=void 0}});const d=[];for(const u of c){if(!u.isIntersection||u.visited||u.intersectionDir!==Mn.Entering)continue;let h=[],f=u,g=!0;const m=u;let p=0;const v=(c.length+l.length)*2;c.forEach(I=>I.processedInPath=!1),l.forEach(I=>I.processedInPath=!1);do{if(p++>v){console.warn("Intersection: Max iterations in path tracing.",m.id,f.id),h=[];break}if(f.processedInPath&&f!==m){console.warn("Intersection: Path processing loop detected, discarding path segment.",m.id,f.id),h=[];break}f.processedInPath=!0,f.visited=!0,(h.length===0||!Ke(h[h.length-1],f.coordinates))&&h.push([...f.coordinates]);let I=!1;f.isIntersection&&f.partnerNode&&(g?(f=f.partnerNode,g=!1,I=!0):(f=f.partnerNode,g=!0,I=!0)),f=f.next}while(f!==m||g&&f.originalPolyIndex!==0||!g&&f.originalPolyIndex!==1);if(p>v||h.length===0||h.length>0&&Ke(h[0],h[h.length-1])&&h.pop(),h.length>=3){const I=wo(h);(e>0&&I<0||e<0&&I>0)&&h.reverse(),d.push(h.map(w=>[...w]))}}return d}function Jh(i,t,n,e){let o=!1;const s=i[0]<t[0]?i[0]:t[0],a=i[1]<t[1]?i[1]:t[1],r=i[0]>t[0]?i[0]:t[0],c=i[1]>t[1]?i[1]:t[1],l=n[0]<e[0]?n[0]:e[0],d=n[1]<e[1]?n[1]:e[1],u=n[0]>e[0]?n[0]:e[0],h=n[1]>e[1]?n[1]:e[1];if(s>u||r<l||a>h||c<d)return!1;const f=[_c(i,t,n),_c(i,t,e),_c(n,e,i),_c(n,e,t)];return f[0]!==f[1]&&f[2]!==f[3]?!0:((f[0]===0&&yc(i,n,t)||f[1]===0&&yc(i,e,t)||f[2]===0&&yc(n,i,e)||f[3]===0&&yc(n,t,e))&&(o=!0),o)}function _c(i,t,n){const e=(t[1]-i[1])*(n[0]-t[0])-(t[0]-i[0])*(n[1]-t[1]);return e===0?0:e>0?1:2}function yc(i,t,n){return t[0]<=Math.max(i[0],n[0])&&t[0]>=Math.min(i[0],n[0])&&t[1]<=Math.max(i[1],n[1])&&t[1]>=Math.min(i[1],n[1])}function Qh(i,t,n,e=!0){const o=[],s=i.length,a=s-(e?1:2);for(let r=0;r<=a;r++){const c=i[r],l=r===s-1?0:r+1,d=i[l];Jh(t,n,c,d)&&o.push([r,l])}return o}function o0(i,t,n,e=!0){let o,s;e?(s=i.length-1,o=0):(s=0,o=1);for(let a=o;a<i.length;a++){const r=i[s],c=i[a];if(Jh(t,n,r,c))return[s,a];s=a}}function td(i,t){for(let n=0,e=i.length;n<e;n++){const o=i[n],s=n===e-1?0:n+1,a=i[s];if(o0(t,o,a)?.length===2)return!0}return!1}const mx=.01;function i0(i,t,n,e){const o=[t[0]-i[0],t[1]-i[1]],s=[e[0]-n[0],e[1]-n[1]],a=s[1]*o[0]-s[0]*o[1];if((a>=0?a:-a)<mx){const g=[i[0]<t[0]?i[0]:t[0],i[0]>t[0]?i[0]:t[0],i[1]<t[1]?i[1]:t[1],i[1]>t[1]?i[1]:t[1]],m=[n[0]<e[0]?n[0]:e[0],n[0]>e[0]?n[0]:e[0],n[1]<e[1]?n[1]:e[1],n[1]>e[1]?n[1]:e[1]];if(!(g[0]<=m[1]&&g[1]>=m[0]&&g[2]<=m[3]&&g[3]>=m[2])||!(jc(i,t,n)||jc(i,t,e)||jc(n,e,i)))return;const I=g[0]>m[0]?g[0]:m[0],w=g[1]<m[1]?g[1]:m[1],C=g[2]>m[2]?g[2]:m[2],S=g[3]<m[3]?g[3]:m[3],b=(I+w)*.5,_=(C+S)*.5;return[b,_]}let c=i[1]-n[1],l=i[0]-n[0];const d=s[0]*c-s[1]*l,u=o[0]*c-o[1]*l;c=d/a,l=u/a;const h=i[0]+c*o[0],f=i[1]+c*o[1];return[h,f]}var ds;(function(i){i[i.Vertex=0]="Vertex",i[i.Intersection=1]="Intersection"})(ds||(ds={}));var us;(function(i){i[i.Outside=-1]="Outside",i[i.Edge=0]="Edge",i[i.Inside=1]="Inside"})(us||(us={}));var Ws;(function(i){i[i.Exiting=-1]="Exiting",i[i.Unknown=0]="Unknown",i[i.Entering=1]="Entering"})(Ws||(Ws={}));function rm(i){for(let t=0,n=i.length;t<n;t++){const e=i[t];e.next||(e.next=i[t===n-1?0:t+1])}}function px(i,t){const n=[],e=[],o=new Map;let a=Ln(t,i[0])?Ws.Exiting:Ws.Entering;for(let r=0,c=i.length;r<c;r++){const l=i[r],d=Ln(t,l),u={type:ds.Vertex,coordinates:l,position:d?us.Inside:us.Outside,visited:!1,next:null};n.push(u);const h=i[r===c-1?0:r+1],f=Qh(t,l,h).map(g=>{const m=g[0],p=t[g[0]],v=t[g[1]],I=i0(l,h,p,v),w=wi(l,I);return{sourceLineSegmentId:m,coordinate:I,targetStartPointDistSquared:w}});f.sort((g,m)=>g.targetStartPointDistSquared-m.targetStartPointDistSquared),f.forEach(g=>{const{sourceLineSegmentId:m,coordinate:p}=g,v={type:ds.Intersection,coordinates:p,position:us.Edge,direction:a,visited:!1,next:null},I={...v,direction:Ws.Unknown,cloned:!0};a===Ws.Entering?v.next=I:I.next=v;let w=o.get(m);w||(w=[],o.set(m,w)),n.push(v),w.push(I),a*=-1})}for(let r=0,c=t.length;r<c;r++){const l=r,d=t[r],u={type:ds.Vertex,coordinates:d,visited:!1,next:null};e.push(u);const h=o.get(l);h?.length&&h.map(f=>({intersectionPoint:f,lineSegStartDistSquared:wi(d,f.coordinates)})).sort((f,g)=>f.lineSegStartDistSquared-g.lineSegStartDistSquared).map(({intersectionPoint:f})=>f).forEach(f=>e.push(f))}return rm(n),rm(e),{targetPolylinePoints:n,sourcePolylinePoints:e}}function vx(i){for(let t=0,n=i.length;t<n;t++){const e=i[t];if(!e.visited&&e.position===us.Outside&&e.type===ds.Vertex)return e}for(let t=0,n=i.length;t<n;t++){const e=i[t];if(!e.visited&&e.position===us.Outside)return e}}function Ix(i,t){const n=qu(i),e=qu(t),o=xt(e,n);if(pr(1,o)||(t=t.slice().reverse()),!td(t,i)&&ma(t,i))return t.slice();const{targetPolylinePoints:r}=px(i,t),c=vx(r);if(!c)return i.slice();const l=[c.coordinates];let d=c.next,u=0;const h=i.length+t.length+1e3;for(;d!==c&&u<h;){if(u++,d.type===ds.Intersection&&d.cloned){d=d.next;continue}if(l.push(d.coordinates),d=d.next,!d){console.warn("Broken linked list detected in mergePolylines, breaking loop");break}}return u>=h&&console.warn("Maximum iterations reached in mergePolylines, possible infinite loop detected"),l}const wx=.1;function ed(i,t=wx){const n=i.length;if(n<3)return i;const e=t*t,o=[[0,n-1]],s=new Array(n).fill(!1);let a=2;for(s[0]=!0,s[n-1]=!0;o.length;){const[c,l]=o.pop();if(l-c===1)continue;const d=i[c],u=i[l];let h=-1/0,f=-1;for(let g=c+1;g<l;g++){const m=i[g],p=tc(d,u,m);p>h&&(h=p,f=g)}h<e||(s[f]=!0,a++,o.push([f,l]),o.push([c,f]))}const r=new Array(a);for(let c=0,l=0;c<n;c++)s[c]&&(r[l++]=i[c]);return r}function s0(i,t,n,e=!0){const o=[],s=Qh(i,t,n,e);for(let a=0;a<s.length;a++){const r=i[s[a][0]],c=i[s[a][1]],l=i0(t,n,r,c);o.push(l)}return o}function Ex(i,t,n,e=!0){let o,s;e?(s=i.length-1,o=0):(s=0,o=1);const a=[];for(let d=o;d<i.length;d++){const u=i[s],h=i[d];Jh(t,n,u,h)&&a.push([s,d]),s=d}if(a.length===0)return;const r=[];a.forEach(d=>{const u=[i[d[0]],i[d[1]]],h=[(u[0][0]+u[1][0])/2,(u[0][1]+u[1][1])/2];r.push(_e(h,t))});const c=Math.min(...r),l=r.indexOf(c);return{segment:a[l],distance:c}}function ht(i,t=i.getViewReference()){const n=(ie(i)?i.getResolvedView()?.toICamera():void 0)||i.getCamera?.()||{},e=vc(t?.cameraFocalPoint||n.focalPoint),o=vc(t?.viewPlaneNormal||n.viewPlaneNormal),s=vc(t?.viewUp||n.viewUp),a=vc(n.position||e&&o&&[e[0]-o[0],e[1]-o[1],e[2]-o[2]]);return{focalPoint:e,position:a,viewPlaneNormal:o,viewUp:s}}const Rs=.001,Sx=(i,t)=>{let n,e,o;const s=ie(i);if(i instanceof Pn||s&&wv(i)==="stack"){const c=i.getImageData();if(!c)return;e=c.direction.slice(0,3),o=c.direction.slice(3,6),n=c.spacing}else{const c=i.getImageData(),{direction:l,spacing:d}=c,{viewPlaneNormal:u,viewUp:h}=s?ht(i):i.getCamera(),f=l.slice(0,3),g=l.slice(3,6),m=l.slice(6,9),p=B();Me(p,h,u);const v=Math.abs(xt(p,f)),I=Math.abs(xt(p,g)),w=Math.abs(xt(p,m));let C;if(Math.abs(1-v)<Rs)C=d[0],e=f;else if(Math.abs(1-I)<Rs)C=d[1],e=g;else if(Math.abs(1-w)<Rs)C=d[2],e=m;else throw new Error("No support yet for oblique plane planar contours");const S=Math.abs(xt(h,f)),b=Math.abs(xt(h,g)),_=Math.abs(xt(h,m));let y;if(Math.abs(1-S)<Rs)y=d[0],o=f;else if(Math.abs(1-b)<Rs)y=d[1],o=g;else if(Math.abs(1-_)<Rs)y=d[2],o=m;else throw new Error("No support yet for oblique plane planar contours");n=[C,y]}return{spacing:[n[0]/t,n[1]/t],xDir:e,yDir:o}},Cx=(i,t,n)=>zh(i,t)<n,bx=(i,t,n,e)=>{const{xDir:o,yDir:s,spacing:a}=e,r=N(i),{viewport:c}=r;if(!t.length)return t.push(n),console.log(">>>>> !canvasPoints. :: RETURN"),1;const l=c.canvasToWorld(t[t.length-1]),d=c.canvasToWorld(n),u=B();Oe(u,d,l);const h=Math.abs(xt(u,o)),f=Math.abs(xt(u,s)),g=Math.max(Math.floor(h/a[0]),Math.floor(f/a[0]));if(g>1){const m=t[t.length-1],p=zh(m,n),v=It();pe(v,n,m),mo(v,v[0]/p,v[1]/p);const I=p/g;for(let w=1;w<=g;w++)t.push([m[0]+I*v[0]*w,m[1]+I*v[1]*w])}else t.push(n);return g},_x=(i,t,n,e)=>{const o=[i[0]-t[0],i[1]-t[1]],s=[n[0]-t[0],n[1]-t[1]],a=o[0]*s[0]+o[1]*s[1];if(a<0)return!1;const r=Math.sqrt(s[0]*s[0]+s[1]*s[1]);if(r===0)return!1;const c=a/r,l=[s[0]/r,s[1]/r],d=[l[0]*c,l[1]*c],u=[t[0]+d[0],t[1]+d[1]];return!(_e(i,u)>e||_e(t,u)>_e(t,n))},yx=1e-6;function a0(i){let t;const n=Dv(i,50);for(let a=0;a<3;a++)if(n.every((r,c,l)=>Math.abs(r[a]-l[0][a])<yx)){t=a;break}if(t===void 0)throw new Error("Cannot find a shared dimension index for polyline, probably oblique plane");const e=[],o=(t+1)%3,s=(t+2)%3;for(let a=0;a<i.length;a++)e.push([i[a][o],i[a][s]]);return{sharedDimensionIndex:t,projectedPolyline:e}}function tf(i,t,n={}){const{sharedDimensionIndex:e,projectedPolyline:o}=a0(t),{holes:s}=n,a=[];if(s)for(let c=0;c<s.length;c++){const l=s[c],d=[];for(let u=0;u<l.length;u++)d.push([l[u][(e+1)%3],l[u][(e+2)%3]]);a.push(d)}const r=[i[(e+1)%3],i[(e+2)%3]];return Ln(o,r,{holes:a})}function r0(i){if(i.length<3)return i.slice();const t=i.map(s=>[s[0],s[1]]).sort((s,a)=>s[0]===a[0]?s[1]-a[1]:s[0]-a[0]);function n(s,a,r){return(a[0]-s[0])*(r[1]-s[1])-(a[1]-s[1])*(r[0]-s[0])}const e=[];for(const s of t){for(;e.length>=2&&n(e[e.length-2],e[e.length-1],s)<=0;)e.pop();e.push(s)}const o=[];for(let s=t.length-1;s>=0;s--){const a=t[s];for(;o.length>=2&&n(o[o.length-2],o[o.length-1],a)<=0;)o.pop();o.push(a)}return e.pop(),o.pop(),e.concat(o)}const Yi=Object.freeze(Object.defineProperty({__proto__:null,addCanvasPointsToArray:bx,arePolylinesIdentical:n0,containsPoint:Ln,containsPoints:ma,convexHull:r0,decimate:ed,getAABB:Ei,getArea:ms,getClosestLineSegmentIntersection:Ex,getFirstLineSegmentIntersectionIndexes:o0,getLineSegmentIntersectionsCoordinates:s0,getLineSegmentIntersectionsIndexes:Qh,getNormal2:qu,getNormal3:hx,getSignedArea:wo,getSubPixelSpacingAndXYDirections:Sx,getWindingDirection:ea,intersectPolyline:td,intersectPolylines:gx,isClosed:Ql,isPointInsidePolyline3D:tf,mergePolylines:Ix,pointCanProjectOnLine:_x,pointsAreWithinCloseContourProximity:Cx,projectTo2D:a0,subtractPolylines:fx},Symbol.toStringTag,{value:"Module"}));function xx(i,t,n,e){const o=[i,t],s=[i+n,t],a=[i+n,t],r=[i+n,t+e],c=[i+n,t+e],l=[i,t+e],d=[i,t+e];return{top:[o,s],right:[a,r],bottom:[c,l],left:[d,[i,t]]}}function ef(i,t){if(i.length!==4||t.length!==2)throw Error("rectangle:[left, top, width, height] or point: [x,y] not defined correctly");const[n,e,o,s]=i;let a=655535;const r=xx(n,e,o,s);return Object.keys(r).forEach(c=>{const[l,d]=r[c],u=Je(l,d,t);u<a&&(a=u)}),a}const Px=Object.freeze(Object.defineProperty({__proto__:null,distanceToPoint:ef},Symbol.toStringTag,{value:"Module"}));function Yu(i,t){let n=[0,0],e=Number.MAX_SAFE_INTEGER;return i.forEach(function(o){const s=Dx(t,o);s<e&&(e=s,n=[...o])}),n}function Dx(i,t){const[n,e]=i,[o,s]=t;return Math.sqrt(Math.pow(n-o,2)+Math.pow(e-s,2))}const Ku=1e-6,cm=1,Tx=0;function xc(i,t,n){const[e,o]=n;if(Math.abs(t)<Ku)return i<0;const s=i/t;if(t>0){if(s>o)return 0;s>e&&(n[0]=s)}else{if(s<e)return 0;s<o&&(n[1]=s)}return 1}function li(i,t,n,e,o){const[s,a]=i,[r,c]=t,l=r-s,d=c-a;if(e===void 0||o===void 0?(e=i,o=t):(e[0]=i[0],e[1]=i[1],o[0]=t[0],o[1]=t[1]),Math.abs(l)<Ku&&Math.abs(d)<Ku&&s>=n[0]&&s<=n[2]&&a>=n[1]&&a<=n[3])return cm;const u=[0,1];if(xc(n[0]-s,l,u)&&xc(s-n[2],-l,u)&&xc(n[1]-a,d,u)&&xc(a-n[3],-d,u)){const[h,f]=u;return f<1&&(o[0]=s+f*l,o[1]=a+f*d),h>0&&(e[0]+=h*l,e[1]+=h*d),cm}return Tx}const Mx=Object.freeze(Object.defineProperty({__proto__:null,findClosestPoint:Yu,liangBarksyClip:li},Symbol.toStringTag,{value:"Module"}));function Ax(i,t){const[n,e]=i,[o,s]=t,a=tn(B(),e,n),r=tn(B(),o,s),c=xt(a,r),l=mn(a),d=mn(r),u=c/(l*d);return Math.acos(u)*180/Math.PI}function Lx(i,t){const[n,e]=i,[o,s]=t,a=No(It(),e,n),r=No(It(),o,s),c=zo(a,r),l=ha(a),d=ha(r),u=c/(l*d);return Math.acos(u)*(180/Math.PI)}function na(i,t){return i[0].length===3?Ax(i,t):Lx(i,t)}const Ox=Object.freeze(Object.defineProperty({__proto__:null,angleBetweenLines:na},Symbol.toStringTag,{value:"Module"})),Rx=Object.freeze(Object.defineProperty({__proto__:null,BasicStatsCalculator:ax,aabb:ox,angle:Ox,circle:cx,ellipse:lx,lineSegment:dx,point:rx,polyline:Yi,rectangle:Px,vec2:Mx},Symbol.toStringTag,{value:"Module"})),{isEqual:Jd}=oe,{EPSILON:c0}=Qo,Nx=1-c0;function nf(i,t,n){const{viewPlaneNormal:e}=t,o=i.filter(c=>{const{planeRestriction:l,referencedImageId:d}=c.metadata;let{viewPlaneNormal:u}=c.metadata;if(l){const{inPlaneVector1:f,inPlaneVector2:g}=l;return!(f&&!Jd(0,xt(e,f))||g&&!Jd(0,xt(e,g)))}if(!c.metadata.referencedImageId&&!u&&c.metadata.FrameOfReferenceUID){for(const f of c.data.handles.points){const g=tn(B(),f,t.focalPoint),m=xt(g,e);if(!Jd(m,0))return!1}return c.metadata.viewPlaneNormal=e,c.metadata.cameraFocalPoint=t.focalPoint,!0}if(!u&&d){const{imageOrientationPatient:f}=rn("imagePlaneModule",d),g=Ot(f[0],f[1],f[2]),m=Ot(f[3],f[4],f[5]);u=B(),Me(u,g,m),c.metadata.viewPlaneNormal=u}const h=Math.abs(xt(e,u))>Nx;return u&&h});if(!o.length)return[];const s=n/2+c0,{focalPoint:a}=t,r=[];for(const c of o){const{data:l,metadata:d,isVisible:u}=c;if(!u)continue;const h=d.planeRestriction?.point||l.handles?.points?.[0]||l.contour?.polyline[0];if(!h){r.push(c);continue}const f=tn(B(),a,h);Math.abs(xt(f,e))<s&&r.push(c)}return r}function of(i,t,n,e){const o=B();Me(o,t,i);const s=Ot(...n),a=Ot(...e),r=B();Oe(r,s,a);const c=mn(r);if(c<1e-4)return{worldWidth:0,worldHeight:0};const l=xt(r,o)/(c*mn(o)),u=Math.sqrt(1-l*l)*c,h=l*c;return{worldWidth:u,worldHeight:h}}function ya(i,t,n={}){const e=i instanceof Xe,o=wv(i)==="volume";if(e||o){const s=e?i.getCamera():ht(i),{spacingInNormalDirection:a}=_h(i,s);return nf(t,s,a)}if(i instanceof Pn){const s=i.getCurrentImageId();if(!s)return[];const a=s.indexOf(":");n.imageURI=s.substring(a+1)}return t.filter(s=>s.isVisible?s.data.isCanvasAnnotation?!0:i.isReferenceViewable(s.metadata,n):!1)}function ec(i,t,n,e){const o=B();Me(o,t,i);const s=Ot(...n),a=Ot(...e),r=B();Oe(r,s,a);const c=mn(r);if(c<1e-4)return{worldWidth:0,worldHeight:0};const l=xt(r,o)/(c*mn(o)),u=Math.sqrt(1-l*l)*c,h=l*c;return{worldWidth:u,worldHeight:h}}function sf(i,t,n,e,o=.25){const s=af(i,t,{targetVolumeId:n,stepSize:o});let a;for(const r of s){const c=i.getIntensityFromWorld(r),l=e(c,r);l&&(a=l)}return a}function af(i,t,{targetVolumeId:n,stepSize:e}){const o=i.getCamera(),{viewPlaneNormal:s}=o,{spacingInNormalDirection:a}=_h(i,o,n),r=a*e||1,c=i.getBounds(),l=[];let d=[...t];for(;lm(d,c);)l.push([...d]),d[0]+=s[0]*r,d[1]+=s[1]*r,d[2]+=s[2]*r;for(d=[...t];lm(d,c);)l.push([...d]),d[0]-=s[0]*r,d[1]-=s[1]*r,d[2]-=s[2]*r;return l}const lm=function(i,t){const[n,e,o,s,a,r]=t,c=10;return i[0]>n+c&&i[0]<e-c&&i[1]>o+c&&i[1]<s-c&&i[2]>a+c&&i[2]<r-c},l0=(i,t,n,e,o,s,a,r)=>{const c=[Ot(n,e,o),Ot(s,e,o),Ot(n,a,o),Ot(s,a,o),Ot(n,e,r),Ot(s,e,r),Ot(n,a,r),Ot(s,a,r)],l=Ot(t[0],t[1],t[2]),d=Ot(i[0],i[1],i[2]),u=-xt(l,d);let h=null;for(const f of c){const g=xt(l,f)+u;if(h===null)h=Math.sign(g);else if(Math.sign(g)!==h)return!0}return!1},{EPSILON:kx}=Qo,Ux=1-kx;function nd(i,t){const{viewPlaneNormal:n}=t,e=i.filter(o=>{let s=o.metadata.viewPlaneNormal;if(!s){const{referencedImageId:r}=o.metadata,{imageOrientationPatient:c}=rn("imagePlaneModule",r),l=Ot(c[0],c[1],c[2]),d=Ot(c[3],c[4],c[5]);s=B(),Me(s,l,d),o.metadata.viewPlaneNormal=s}const a=Math.abs(xt(n,s))>Ux;return s&&a});return e.length?e:[]}const Vx={filterAnnotationsWithinSlice:nf,getWorldWidthAndHeightFromCorners:of,getWorldWidthAndHeightFromTwoPoints:ec,filterAnnotationsForDisplay:ya,getPointInLineOfSightWithCriteria:sf,isPlaneIntersectingAABB:l0,filterAnnotationsWithinSamePlane:nd,getPointsInLineOfSight:af},Fx=Object.freeze(Object.defineProperty({__proto__:null,default:Vx,filterAnnotationsForDisplay:ya,filterAnnotationsWithinSamePlane:nd,filterAnnotationsWithinSlice:nf,getPointInLineOfSightWithCriteria:sf,getPointsInLineOfSight:af,getWorldWidthAndHeightFromCorners:of,getWorldWidthAndHeightFromTwoPoints:ec,isPlaneIntersectingAABB:l0},Symbol.toStringTag,{value:"Module"}));function d0(i,t){const n=i.length,e=[];for(let o=0;o<n;o++){const s=i[o];s.getFrameOfReferenceUID()===t&&e.push(s)}return e}const{Active:Gx,Passive:Hx,Enabled:Wx}=se;function od(i,t){const n=i.length,e=[];for(let o=0;o<n;o++){const s=i[o],a=Ae(s.id,s.renderingEngineId);if(!a)continue;Bx(a,t)&&e.push(s)}return e}function Bx(i,t){const{toolOptions:n}=i,e=n[t];if(!e)return!1;const o=e.mode;return o===Gx||o===Hx||o===Wx}function u0(i,t,n=.999){const o=ht(t).viewPlaneNormal;return o?i.filter(s=>{const a=ht(s);return a.viewPlaneNormal?Math.abs(xt(a.viewPlaneNormal,o))>n:!1}):[]}function ft(i,t,n=!0){const e=N(i),{renderingEngine:o,FrameOfReferenceUID:s}=e;let a=o.getViewports();a=d0(a,s),a=od(a,t);const r=o.getViewport(e.viewportId);return n&&(a=u0(a,r)),a.map(l=>l.id)}const zx=Object.freeze(Object.defineProperty({__proto__:null,filterViewportsWithFrameOfReferenceUID:d0,filterViewportsWithParallelNormals:u0,filterViewportsWithToolEnabled:od,getViewportIdsWithToolToRender:ft},Symbol.toStringTag,{value:"Module"})),$x="viewport-element";function jx(i){const t=N(i),{viewportId:n,renderingEngineId:e}=t,o=`${n}:${e}`,s=Xx(i);return Object.keys($.svgNodeCache[o]).forEach(a=>{$.svgNodeCache[o][a].touched=!1}),{svgLayerElement:s,svgNodeCacheForCanvas:$.svgNodeCache,getSvgNode:qx.bind(this,o),appendNode:Yx.bind(this,s,o),setNodeTouched:Kx.bind(this,o),clearUntouched:Zx.bind(this,s,o)}}function Xx(i){const t=`.${$x}`;return i.querySelector(t)?.querySelector(":scope > .svg-layer")}function qx(i,t){if($.svgNodeCache[i]&&$.svgNodeCache[i][t])return $.svgNodeCache[i][t].domRef}function Yx(i,t,n,e){if(!$.svgNodeCache[t])return null;$.svgNodeCache[t][e]={touched:!0,domRef:n},i.appendChild(n)}function Kx(i,t){$.svgNodeCache[i]&&$.svgNodeCache[i][t]&&($.svgNodeCache[i][t].touched=!0)}function Zx(i,t){$.svgNodeCache[t]&&Object.keys($.svgNodeCache[t]).forEach(n=>{const e=$.svgNodeCache[t][n];!e.touched&&e.domRef&&(i.removeChild(e.domRef),delete $.svgNodeCache[t][n])})}const rl=new WeakMap;function Jx(i){rl.set(i,[])}function Qx(i,t){let n=rl.get(i);n||(n=[],rl.set(i,n)),n.push({x:t.x,y:t.y,width:t.width,height:t.height})}function tP(i){return rl.get(i)||[]}function h0(i,t){const n=jx(i);n.svgLayerElement&&Jx(n.svgLayerElement),t(n),n.clearUntouched()}function ti(i,t,n){return`${i}::${t}::${n}`}function oo(i,t){Object.keys(i).forEach(n=>{const e=t.getAttribute(n),o=i[n];o===void 0||o===""?t.removeAttribute(n):e!==o&&t.setAttribute(n,o)})}function ei(i,t){Object.keys(i).forEach(n=>{const e=i[n];e!==void 0&&e!==""&&t.setAttribute(n,e)})}function En(i,t,n,e,o,s={},a=""){const{color:r,fill:c,width:l,lineWidth:d,lineDash:u,fillOpacity:h,strokeOpacity:f}=Object.assign({color:"rgb(0, 255, 0)",fill:"transparent",width:"2",lineDash:void 0,lineWidth:void 0,strokeOpacity:1,fillOpacity:1},s),g=d||l,m="http://www.w3.org/2000/svg",p=ti(t,"circle",n),v=i.getSvgNode(p),I={cx:`${e[0]}`,cy:`${e[1]}`,r:`${o}`,stroke:r,fill:c,"stroke-width":g,"stroke-dasharray":u,"fill-opacity":h,"stroke-opacity":f};if(v)oo(I,v),i.setNodeTouched(p);else{const w=document.createElementNS(m,"circle");a!==""&&w.setAttribute("data-id",a),ei(I,w),i.appendNode(w,p)}}function id(i,t,n,e,o={},s=""){const{color:a,width:r,lineWidth:c,lineDash:l}=Object.assign({color:"rgb(0, 255, 0)",width:"2",lineWidth:void 0,lineDash:void 0},o),d=c||r,u="http://www.w3.org/2000/svg",h=ti(t,"ellipse",n),f=i.getSvgNode(h),[g,m,p,v]=e,I=Math.hypot(p[0]-v[0],p[1]-v[1]),w=Math.hypot(m[0]-g[0],m[1]-g[1]),C=Math.atan2(p[1]-v[1],p[0]-v[0])*180/Math.PI,S=[(p[0]+v[0])/2,(m[1]+g[1])/2],b=I/2,_=w/2,y={cx:`${S[0]}`,cy:`${S[1]}`,rx:`${b}`,ry:`${_}`,stroke:a,fill:"transparent",transform:`rotate(${C} ${S[0]} ${S[1]})`,"stroke-width":d,"stroke-dasharray":l};if(f)oo(y,f),i.setNodeTouched(h);else{const D=document.createElementNS(u,"ellipse");s!==""&&D.setAttribute("data-id",s),ei(y,D),i.appendNode(D,h)}}function eP(i,t,n,e,o,s={},a=""){const r=[(e[0]+o[0])/2,e[1]],c=[(e[0]+o[0])/2,o[1]],l=[e[0],(e[1]+o[1])/2],d=[o[0],(e[1]+o[1])/2];id(i,t,n,[c,r,l,d],s={},a="")}function cl(i,t,n,e,o={},s){const{color:a,handleRadius:r,width:c,lineWidth:l,fill:d,type:u,opacity:h}=Object.assign({color:"rgb(0, 255, 0)",handleRadius:"6",width:"2",lineWidth:void 0,fill:"transparent",type:"circle",opacity:1},o),f=l||c,g="http://www.w3.org/2000/svg",m=ti(t,"handle",`hg-${n}-index-${s}`);let p;if(u==="circle")p={cx:`${e[0]}`,cy:`${e[1]}`,r,stroke:a,fill:d,"stroke-width":f,opacity:h};else if(u==="rect"){const w=parseFloat(r)*1.5,C=e[0]-w*.5,S=e[1]-w*.5;p={x:`${C}`,y:`${S}`,width:`${w}`,height:`${w}`,stroke:a,fill:d,"stroke-width":f,rx:`${w*.1}`,opacity:h}}else throw new Error(`Unsupported handle type: ${u}`);const v=i.getSvgNode(m);if(v)oo(p,v),i.setNodeTouched(m);else{const I=document.createElementNS(g,u);ei(p,I),i.appendNode(I,m)}}function xe(i,t,n,e,o={}){e.forEach((s,a)=>{cl(i,t,n,s,o,a)})}function qt(i,t,n,e,o,s={},a=""){if(isNaN(e[0])||isNaN(e[1])||isNaN(o[0])||isNaN(o[1]))return;const{color:r="rgb(0, 255, 0)",width:c=10,lineWidth:l,lineDash:d,markerStartId:u=null,markerEndId:h=null,shadow:f=!1,strokeOpacity:g=1,textBoxLinkLineColor:m}=s,p=l||c,v="http://www.w3.org/2000/svg",I=ti(t,"line",n),w=i.getSvgNode(I),C=i.svgLayerElement.id,S=f?`url(#shadow-${C});`:"",b={x1:`${e[0]}`,y1:`${e[1]}`,x2:`${o[0]}`,y2:`${o[1]}`,stroke:m||r,filter:S,"stroke-width":p,"stroke-dasharray":d,"marker-start":u?`url(#${u})`:"","marker-end":h?`url(#${h})`:"","stroke-opacity":g};if(w)oo(b,w),i.setNodeTouched(I);else{const _=document.createElementNS(v,"line");a!==""&&_.setAttribute("data-id",a),ei(b,_),i.appendNode(_,I)}}function f0(i,t,n,e,o,s={}){if(isNaN(e[0])||isNaN(e[1])||isNaN(o[0])||isNaN(o[1]))return;const{color:a,width:r,lineWidth:c,lineDash:l}=Object.assign({color:"rgb(0, 255, 0)",width:"2",lineWidth:void 0,lineDash:void 0},s),d=o[0]+(e[0]-o[0])/2,u=[d,e[1]],h=[d,o[1]],f={start:e,end:u},g={start:u,end:h},m={start:h,end:o};qt(i,t,"1",f.start,f.end,{color:a,width:r,lineWidth:c,lineDash:l}),qt(i,t,"2",g.start,g.end,{color:a,width:r,lineWidth:c,lineDash:l}),qt(i,t,"3",m.start,m.end,{color:a,width:r,lineWidth:c,lineDash:l})}function Eo(i,t,n,e,o){if(e.length<2)return;const{color:s="rgb(0, 255, 0)",width:a=10,fillColor:r="none",fillOpacity:c=0,lineWidth:l,lineDash:d,closePath:u=!1,markerStartId:h=null,markerEndId:f=null}=o,g=l||a,m="http://www.w3.org/2000/svg",p=ti(t,"polyline",n),v=i.getSvgNode(p);let I="";for(const C of e)I+=`${C[0].toFixed(1)}, ${C[1].toFixed(1)} `;if(u){const C=e[0];I+=`${C[0]}, ${C[1]}`}const w={points:I,stroke:s,fill:r,"fill-opacity":c,"stroke-width":g,"stroke-dasharray":d,"marker-start":h?`url(#${h})`:"","marker-end":f?`url(#${f})`:""};if(v)oo(w,v),i.setNodeTouched(p);else{const C=document.createElementNS(m,"polyline");ei(w,C),i.appendNode(C,p)}}function ko(i,t,n,e,o){const a=e.length&&e[0].length&&Array.isArray(e[0][0])?e:[e],{color:r="rgb(0, 255, 0)",width:c=10,fillColor:l="none",fillOpacity:d=0,strokeOpacity:u=1,lineWidth:h,lineDash:f,lineCap:g,lineJoin:m,closePath:p=!1}=o,v=h||c,I="http://www.w3.org/2000/svg",w=ti(t,"path",n),C=i.getSvgNode(w);let S="";for(let _=0,y=a.length;_<y;_++){const D=a[_],T=D.length;if(!(T<2)){for(let P=0;P<T;P++){const x=D[P];S+=`${P?"L":"M"} ${x[0].toFixed(1)}, ${x[1].toFixed(1)} `}p&&(S+="Z ")}}if(!S)return;const b={d:S,stroke:r,fill:l,"fill-opacity":d,"stroke-opacity":u,"stroke-width":v,"stroke-dasharray":f,"stroke-linecap":g,"stroke-linejoin":m};if(C)oo(b,C),i.setNodeTouched(w);else{const _=document.createElementNS(I,"path");ei(b,_),i.appendNode(_,w)}}function Zu(i,t,n,e,o,s,a,r,c={},l="",d){const{color:u,fill:h,width:f,lineWidth:g,lineDash:m,fillOpacity:p,strokeOpacity:v}=Object.assign({color:"rgb(0, 255, 0)",fill:"transparent",width:"2",lineDash:void 0,lineWidth:void 0,strokeOpacity:1,fillOpacity:1},c),I=g||f,w="http://www.w3.org/2000/svg",C=ti(t,"fan",n),S=i.getSvgNode(C),b=a*Math.PI/180,_=r*Math.PI/180,y=e[0],D=e[1],T=y+s*Math.cos(b),P=D+s*Math.sin(b),x=y+s*Math.cos(_),M=D+s*Math.sin(_),L=y+o*Math.cos(b),R=D+o*Math.sin(b),U=y+o*Math.cos(_),W=D+o*Math.sin(_),K=r-a<=180?0:1;let j=`M ${T} ${P}`;j+=` A ${s} ${s} 0 ${K} 1 ${x} ${M}`,j+=` L ${U} ${W}`,j+=` A ${o} ${o} 0 ${K} 0 ${L} ${R}`,j+=" Z";const F={d:j,stroke:u,fill:h,"stroke-width":I,"stroke-dasharray":m,"fill-opacity":p,"stroke-opacity":v,"mix-blend-mode":"normal"};if(S)oo(F,S),i.setNodeTouched(C);else{const z=document.createElementNS(w,"path");l!==""&&z.setAttribute("data-id",l),d!==void 0&&(z.style.zIndex=d.toString()),ei(F,z),i.appendNode(z,C)}}function Ko(i,t,n,e,o,s={}){const a=Object.assign({fontFamily:"Helvetica, Arial, sans-serif",fontSize:"14px",color:"rgb(255, 255, 0)",background:"",padding:25,centerX:!1,centerY:!0},s),r=nP(i,t,n,e,o,a);return i.svgLayerElement&&Qx(i.svgLayerElement,r),r}function nP(i,t,n,e=[""],o,s){const{padding:a,color:r,fontFamily:c,fontSize:l,background:d,textBoxBorderRadius:u,textBoxMargin:h}=s;let f;const[g,m]=[o[0]+a,o[1]+a],p={color:d,textBoxBorderRadius:u,textBoxMargin:h},v="http://www.w3.org/2000/svg",I=ti(t,"text",n),w=i.getSvgNode(I);if(w){const C=w.querySelector("text"),S=Array.from(C.children);for(let y=0;y<S.length;y++){const D=S[y],T=e[y]||"";D.textContent=T}if(e.length>S.length){for(let y=0;y<e.length-S.length;y++){const D=e[y+S.length],T=dm(D);C.appendChild(T)}w.appendChild(C),i.appendNode(w,I)}const b={fill:r,"font-size":l,"font-family":c},_={transform:`translate(${g} ${m})`};oo(b,C),oo(_,w),w.setAttribute("data-annotation-uid",t),f=um(w,p),i.setNodeTouched(I)}else{const C=document.createElementNS(v,"g");C.setAttribute("data-annotation-uid",t),C.setAttribute("transform",`translate(${g} ${m})`);const S=oP(i,s);for(let b=0;b<e.length;b++){const _=e[b],y=dm(_);S.appendChild(y)}C.appendChild(S),i.appendNode(C,I),f=um(C,p)}return Object.assign({},f,{x:g+f.x,y:m+f.y,height:f.height,width:f.width})}function oP(i,t){const{color:n,fontFamily:e,fontSize:o}=t,a=document.createElementNS("http://www.w3.org/2000/svg","text"),r="user-select: none; pointer-events: none; -webkit-tap-highlight-color: rgba(255, 255, 255, 0);",c=`filter:url(#shadow-${i.svgLayerElement.id});`,l=`${r}${c}`;return a.setAttribute("x","0"),a.setAttribute("y","0"),a.setAttribute("fill",n),a.setAttribute("font-family",e),a.setAttribute("font-size",o),a.setAttribute("style",l),a.setAttribute("pointer-events","visible"),a}function dm(i){const n=document.createElementNS("http://www.w3.org/2000/svg","tspan");return n.setAttribute("x","0"),n.setAttribute("dy","1.2em"),n.textContent=i,n}function um(i,t){const{color:n,textBoxBorderRadius:e=0,textBoxMargin:o=0}=t;let s=i.querySelector("rect.background");const a=i.querySelector("text").getBBox();if(!n)return s&&i.removeChild(s),i.getBBox();s||(s=document.createElementNS("http://www.w3.org/2000/svg","rect"),s.setAttribute("class","background"),i.insertBefore(s,i.firstChild));const r=i.getBBox(),c={x:`${r.x}`,y:`${r.y}`,width:`${a.width+Number(o)*2}`,height:`${a.height+Number(o)*2}`,fill:n,rx:e,ry:e};return o&&Array.from(i.querySelector("text").querySelectorAll("tspan")).forEach((d,u)=>{u===0&&d.setAttribute("y",o),d.setAttribute("x",o)}),oo(c,s),r}function iP(i,t,n,e,o,s,a={}){const r=e.length>0?Yu(e,o):o,c=sP(s),l=Yu(c,r),d=Object.assign({color:"rgb(255, 255, 0)",lineWidth:"1",lineDash:"2,3"},a);qt(i,t,`link-${n}`,r,l,d)}function sP(i){const{x:t,y:n,height:e,width:o}=i,s=o/2,a=e/2,r=[t+s,n],c=[t,n+a],l=[t+s,n+e],d=[t+o,n+a];return[r,c,l,d]}function g0(i,t,n,e,o,s,a,r={}){const c=Object.assign({handleRadius:"6",centering:{x:!1,y:!0}},r),l=Ko(i,t,n,e,o,c);return iP(i,t,n,s,o,l,c),l}function rf(i,t,n,e,o={},s=""){const{color:a,width:r,lineWidth:c,lineDash:l}=Object.assign({color:"rgb(0, 255, 0)",width:"2",lineWidth:void 0,lineDash:void 0},o),d=c||r,u="http://www.w3.org/2000/svg",h=ti(t,"rect",n),f=i.getSvgNode(h),[g,m,p,v]=e,I=Math.hypot(g[0]-m[0],g[1]-m[1]),w=Math.hypot(g[0]-p[0],g[1]-p[1]),C=[(v[0]+g[0])/2,(v[1]+g[1])/2],S=[(p[0]+g[0])/2,(p[1]+g[1])/2],b=Math.atan2(C[1]-S[1],C[0]-S[0])*180/Math.PI,_={x:`${C[0]-I/2}`,y:`${C[1]-w/2}`,width:`${I}`,height:`${w}`,stroke:a,fill:"transparent",transform:`rotate(${b} ${C[0]} ${C[1]})`,"stroke-width":d,"stroke-dasharray":l};if(f)oo(_,f),i.setNodeTouched(h);else{const y=document.createElementNS(u,"rect");s!==""&&y.setAttribute("data-id",s),ei(_,y),i.appendNode(y,h)}}function nc(i,t,n,e,o,s={},a=""){const r=[e[0],e[1]],c=[o[0],e[1]],l=[e[0],o[1]],d=[o[0],o[1]];rf(i,t,n,[r,c,l,d],s,a)}const hm="http://www.w3.org/2000/svg";function ll(i,t,n,e,o,s={}){if(isNaN(e[0])||isNaN(e[1])||isNaN(o[0])||isNaN(o[1]))return;const{viaMarker:a=!1,color:r="rgb(0, 255, 0)",markerSize:c=10}=s;if(!a){aP(i,t,n,e,o,s);return}const l=i.svgLayerElement.id,u=`${`arrow-${t}`}-${l}`,h=i.svgLayerElement.querySelector("defs");let f=h.querySelector(`#${u}`);if(f){f.setAttribute("markerWidth",`${c}`),f.setAttribute("markerHeight",`${c}`);const g=f.querySelector("path");g&&g.setAttribute("fill",r)}else{f=document.createElementNS(hm,"marker"),f.setAttribute("id",u),f.setAttribute("viewBox","0 0 10 10"),f.setAttribute("refX","8"),f.setAttribute("refY","5"),f.setAttribute("markerWidth",`${c}`),f.setAttribute("markerHeight",`${c}`),f.setAttribute("orient","auto");const g=document.createElementNS(hm,"path");g.setAttribute("d","M 0 0 L 10 5 L 0 10 z"),g.setAttribute("fill",r),f.appendChild(g),h.appendChild(f)}s.markerEndId=u,qt(i,t,n,e,o,s)}function aP(i,t,n,e,o,s={}){const{color:a="rgb(0, 255, 0)",width:r=2,lineWidth:c,lineDash:l}=s,d=10,u=Math.atan2(o[1]-e[1],o[0]-e[0]),h={start:[o[0]-d*Math.cos(u-Math.PI/7),o[1]-d*Math.sin(u-Math.PI/7)],end:o},f={start:[o[0]-d*Math.cos(u+Math.PI/7),o[1]-d*Math.sin(u+Math.PI/7)],end:o};qt(i,t,n,e,o,{color:a,width:r,lineWidth:c,lineDash:l}),qt(i,t,"2",h.start,h.end,{color:a,width:r,lineWidth:c,lineDash:l}),qt(i,t,"3",f.start,f.end,{color:a,width:r,lineWidth:c,lineDash:l})}function m0(i,t,n,e,o,s={}){const{color:a,width:r,lineWidth:c,lineDash:l}=Object.assign({color:"rgb(0, 255, 0)",width:"2",lineWidth:void 0,lineDash:void 0},s),d=c||r,u="http://www.w3.org/2000/svg",h=ti(t,"rect",n),f=i.getSvgNode(h),g=[Math.min(e[0],o[0]),Math.min(e[1],o[1])],m=Math.abs(e[0]-o[0]),p=Math.abs(e[1]-o[1]),v={x:`${g[0]}`,y:`${g[1]}`,width:`${m}`,height:`${p}`,stroke:a,fill:"black","stroke-width":d,"stroke-dasharray":l};if(f)oo(v,f),i.setNodeTouched(h);else{const I=document.createElementNS(u,"rect");ei(v,I),i.appendNode(I,h)}}const _G=Object.freeze(Object.defineProperty({__proto__:null,draw:h0,drawArrow:ll,drawCircle:En,drawEllipse:eP,drawEllipseByCoordinates:id,drawFan:Zu,drawHandle:cl,drawHandles:xe,drawHeight:f0,drawLine:qt,drawLinkedTextBox:g0,drawPath:ko,drawPolyline:Eo,drawRect:nc,drawRectByCoordinates:rf,drawRedactionRect:m0,drawTextBox:Ko,setAttributesIfNecessary:oo,setNewAttributesIfValid:ei},Symbol.toStringTag,{value:"Module"}));function p0(i,t){const n=N(i),{renderingEngineId:e,viewportId:o}=n,s=Ae(o,e);if(!s)return[];const a=[],r=Object.keys(s.toolOptions);for(let c=0;c<r.length;c++){const l=r[c],d=s.toolOptions[l];if(d&&t.includes(d.mode)){const u=s.getToolInstance(l);a.push(u)}}return a}const{Active:rP,Passive:cP,Enabled:lP}=se;class dP{constructor(){this._needsRender=new Set,this._animationFrameSet=!1,this._animationFrameHandle=null,this._renderFlaggedViewports=()=>{this._throwIfDestroyed();const t=Array.from(this._viewportElements.values());for(let n=0;n<t.length;n++){const e=t[n];if(this._needsRender.has(e)&&(this._triggerRender(e),this._needsRender.delete(e),this._needsRender.size===0))break}this._animationFrameSet=!1,this._animationFrameHandle=null,this._render()},this._viewportElements=new Map}addViewportElement(t,n){this._viewportElements.set(t,n)}removeViewportElement(t,n){this._viewportElements.delete(t),this._needsRender.delete(n),this._reset()}renderViewport(t){this._setViewportsToBeRenderedNextFrame([t])}_throwIfDestroyed(){if(this.hasBeenDestroyed)throw new Error("this.destroy() has been manually called to free up memory, can not longer use this instance. Instead make a new one.")}_setAllViewportsToBeRenderedNextFrame(){[...this._viewportElements.values()].forEach(n=>{this._needsRender.add(n)}),this._renderFlaggedViewports()}_setViewportsToBeRenderedNextFrame(t){const n=[...this._viewportElements.values()];t.forEach(e=>{n.indexOf(e)!==-1&&this._needsRender.add(e)}),this._render()}_render(){this._needsRender.size>0&&this._animationFrameSet===!1&&(this._animationFrameHandle=window.requestAnimationFrame(this._renderFlaggedViewports),this._animationFrameSet=!0)}_triggerRender(t){const n=N(t);if(!n)return;if(!Ne(n.renderingEngineId)){console.warn("rendering Engine has been destroyed");return}const o=p0(t,[rP,cP,lP]),{renderingEngineId:s,viewportId:a}=n,r={element:t,renderingEngineId:s,viewportId:a};h0(t,c=>{let l=!1;const d=u=>{if(u.renderAnnotation){const h=u.renderAnnotation(n,c);l=l||h}};o.forEach(d),l&&Rt(t,E.ANNOTATION_RENDERED,{...r})})}_reset(){window.cancelAnimationFrame(this._animationFrameHandle),this._needsRender.clear(),this._animationFrameSet=!1,this._animationFrameHandle=null,this._setAllViewportsToBeRenderedNextFrame()}}const cf=new dP;function xa(i){cf.renderViewport(i)}function V(i){i.length&&i.forEach(t=>{const n=le(t);if(!n){console.warn(`Viewport not available for ${t}`);return}const{viewport:e}=n;if(!e){console.warn(`Viewport not available for ${t}`);return}const o=e.element;xa(o)})}function uP(i){return i[0]?.length===3}function hP(i,t){if(!t||t.length===0||t.length===i.length)return i;const n=t[t.length-1]-t[0]+1,e=Fd(t.map(s=>i[s][0])),o=Fd(t.map(s=>i[s][1]));if(uP(i)){const s=Fd(t.map(a=>i[a][2]));return Tg(Ga(e,n),Ga(o,n),Ga(s,n))}else return Tg(Ga(e,n),Ga(o,n))}function fP(i,t){const n=[],[e,o]=t,s=o-e+1,a=Math.floor(s/i);let r=0,c=Math.round((s-1)/(a-1)*r)+e;for(;c<=o;)n.push(c),r++,c=Math.round((s-1)/(a-1)*r)+e;return n}function dl(i,t,n,e){const o=n-t+1,s=Math.floor(e/100*o)??1,a=Math.floor(o/s)??1;if(isNaN(o)||!o||!a||o/a<2)return i;const r=Math.max(0,t),c=Math.min(i.length-1,n),l=i.slice(0,r),d=i.slice(c+1,i.length),u=fP(a,[r,c]),h=hP(i,u);return[...l,...h,...d]}function sd(i,t){return t?.autoGenerated?!1:i?.smoothing?.smoothOnAdd===!0||i?.smoothing?.smoothOnEdit===!0}function gP(i,t){return ro(i,t)<.001}function mP(i,t){return ro(i,t)===0}function pP(i,t){for(let n=0;n<i.length;n++)for(let e=0;e<t.length;e++)if(mP(i[n],t[e]))return[n,e]}function Bs(i,t,n){return(i+t+n)%t}function fm(i,t,n,e){const[,o,s]=i,[,a,r]=t,c=s.length,l=r.length;let d=i[0],u=t[0];if(!s[d]||!r[u]||!s[o]||!r[a])return[void 0,void 0];for(;d!==o&&u!==a;){if(n(r[u],s[d]))return[d,u];d=Bs(d,c,e),u=Bs(u,l,e)}return[void 0,void 0]}function vP(i,t){const[n,e]=pP(i,t)||[],o=(c,l)=>gP(c,l)===!1,[s,a]=fm([Bs(n,i.length,1),n,i],[Bs(e,t.length,1),e,t],o,1),[r]=fm([Bs(s,i.length,-1),s,i],[Bs(a,t.length,-1),a,t],o,-1);return[s,r]}function ad(i,t,n){const{interpolation:e,smoothing:o}=i,s=t;if(e){const{knotsRatioPercentageOnAdd:a,knotsRatioPercentageOnEdit:r,smoothOnAdd:c=!1,smoothOnEdit:l=!1}=o,d=n?r:a;if(n?l:c){const[h,f]=n?vP(t,n):[0,t.length-1];return!t[h]||!t[f]?t:dl(t,h,f,d)}}return s}const Pa=i=>{if(i.shiftKey)return i.ctrlKey?vn.ShiftCtrl:i.altKey?vn.ShiftAlt:i.metaKey?vn.ShiftMeta:vn.Shift;if(i.ctrlKey)return i.altKey?vn.CtrlAlt:i.metaKey?vn.CtrlMeta:vn.Ctrl;if(i.altKey)return i.metaKey&&vn.AltMeta||vn.Alt;if(i.metaKey)return vn.Meta};function IP(i,t){const n=i[0],e=i[i.length-1],o=It();mo(o,e[0]-n[0],e[1]-n[1]),Ao(o,o);const s=It(),a=It();mo(s,-o[1],o[0]),mo(a,o[1],-o[0]);const r=[(n[0]+e[0])/2,(n[1]+e[1])/2],c={dist:0,index:null};for(let u=0;u<i.length;u++){const h=i[u],f=zh(h,r);f>c.dist&&(c.dist=f,c.index=u)}return[i[c.index],r].map(t.canvasToWorld)}function lf(i,t,n){return n==="orthogonalT"?EP(i,t):n==="lineSegment"?null:n?IP(i,t):null}function wP(i,t){const{viewport:n}=i,e=t.data.contour.polyline.map(n.worldToCanvas);return lf(e,n,t.data.isOpenUShapeContour)}function EP(i,t){const n=i[0],e=i[i.length-1],o=No(It(),e,n);Ao(o,o);const s=[o[0],o[1]],a=[(n[0]+e[0])/2,(n[1]+e[1])/2],r=It();let c=null,l=null,d=null;for(const f of i){No(r,f,a);const g=zo(s,r);if(c!==null&&c*g<0){const m=Math.abs(c)/(Math.abs(c)+Math.abs(g));d=[l[0]+m*(f[0]-l[0]),l[1]+m*(f[1]-l[1])];break}if(Math.abs(g)<1e-10){d=f;break}c=g,l=f}return d?[d,a].map(t.canvasToWorld):(console.warn("No orthogonal intersection found for open U-shaped contour"),null)}var Qe;(function(i){i[i.CounterClockwise=-1]="CounterClockwise",i[i.Unknown=0]="Unknown",i[i.Clockwise=1]="Clockwise"})(Qe||(Qe={}));var Ce;(function(i){i[i.NoClip=0]="NoClip",i[i.Intersection=1]="Intersection",i[i.Union=2]="Union",i[i.Difference=3]="Difference",i[i.Xor=4]="Xor"})(Ce||(Ce={}));var Ze;(function(i){i[i.Subject=0]="Subject",i[i.Clip=1]="Clip"})(Ze||(Ze={}));var we;(function(i){i[i.EvenOdd=0]="EvenOdd",i[i.NonZero=1]="NonZero",i[i.Positive=2]="Positive",i[i.Negative=3]="Negative"})(we||(we={}));var ge;(function(i){i[i.IsOn=0]="IsOn",i[i.IsInside=1]="IsInside",i[i.IsOutside=2]="IsOutside"})(ge||(ge={}));var pt;(function(i){i.MaxInt64=9223372036854775807n,i.MaxCoord=Number(i.MaxInt64/4n),i.max_coord=i.MaxCoord,i.min_coord=-i.MaxCoord,i.Invalid64=Number(i.MaxInt64),i.floatingPointTolerance=1e-12,i.defaultMinimumEdgeLength=.1;function t(S,b,_){return(b.x-S.x)*(_.y-b.y)-(b.y-S.y)*(_.x-b.x)}i.crossProduct=t;function n(S,b,_){const y=b.x-S.x,D=_.y-b.y,T=b.y-S.y,P=_.x-b.x;if(Math.abs(y)<9e7&&Math.abs(D)<9e7&&Math.abs(T)<9e7&&Math.abs(P)<9e7){const it=y*D,tt=T*P;return it>tt?1:it<tt?-1:0}const x=y<0?-1:y>0?1:0,M=D<0?-1:D>0?1:0,L=T<0?-1:T>0?1:0,R=P<0?-1:P>0?1:0,U=x*M,W=L*R;if(U!==W)return U>W?1:-1;if(U===0)return 0;const K=BigInt(y),j=BigInt(D),F=BigInt(T),z=BigInt(P),q=K*j,J=F*z;return q===J?0:q>J?1:-1}i.crossProductSign=n;function e(S){if(S<-8||S>8)throw new Error("Error: Precision is out of range.")}i.checkPrecision=e;function o(S){return Math.abs(S)<=i.floatingPointTolerance}i.isAlmostZero=o;function s(S){return S<0?-1:S>0?1:0}i.triSign=s;function a(S,b){const _=BigInt(S),y=BigInt(b),D=_*y;return{lo64:Number(D&0xffffffffffffffffn),hi64:Number(D>>64n)}}i.multiplyUInt64=a;function r(S,b,_,y){const D=Math.abs(S),T=Math.abs(b),P=Math.abs(_),x=Math.abs(y);if(D<46341&&T<46341&&P<46341&&x<46341||D<9e7&&T<9e7&&P<9e7&&x<9e7)return S*b===_*y;const M=(S<0?-1:S>0?1:0)*(b<0?-1:b>0?1:0),L=(_<0?-1:_>0?1:0)*(y<0?-1:y>0?1:0);if(M!==L)return!1;if(M===0)return!0;const R=BigInt(D),U=BigInt(T),W=BigInt(P),K=BigInt(x);return R*U===W*K}i.productsAreEqual=r;function c(S,b,_){const y=b.x-S.x,D=_.y-b.y,T=b.y-S.y,P=_.x-b.x;return r(y,D,T,P)}i.isCollinear=c;function l(S,b,_){return(b.x-S.x)*(_.x-b.x)+(b.y-S.y)*(_.y-b.y)}i.dotProduct=l;function d(S,b){return S.y*b.x-b.y*S.x}i.crossProductD=d;function u(S,b){return S.x*b.x+S.y*b.y}i.dotProductD=u;function h(S){const b=Math.floor(S),_=S-b;return Math.abs(_-.5)<1e-10?b%2===0?b:b+1:Math.round(S)}i.roundToEven=h;function f(S){return S>=i.max_coord||S<=i.min_coord?i.Invalid64:Math.round(S)}i.checkCastInt64=f;function g(S,b,_,y){const D=b.y-S.y,T=b.x-S.x,P=y.y-_.y,x=y.x-_.x,M=D*x-P*T;if(M===0)return{intersects:!1,point:{x:0,y:0,z:0}};const L=((S.x-_.x)*P-(S.y-_.y)*x)/M;let R;if(L<=0)R={x:S.x,y:S.y,z:0};else if(L>=1)R={x:b.x,y:b.y,z:0};else{const U=S.x+L*T,W=S.y+L*D;R={x:Math.trunc(U),y:Math.trunc(W),z:0}}return{intersects:!0,point:R}}i.getLineIntersectPt=g;function m(S,b,_,y){const D=b.y-S.y,T=b.x-S.x,P=y.y-_.y,x=y.x-_.x,M=D*x-P*T;if(M===0)return{success:!1,ip:{x:0,y:0,z:0}};const L=((S.x-_.x)*P-(S.y-_.y)*x)/M;let R;return L<=0?R={...S,z:0}:L>=1?R={...b,z:0}:R={x:S.x+L*T,y:S.y+L*D,z:0},{success:!0,ip:R}}i.getLineIntersectPtD=m;function p(S,b,_,y,D=!1){if(!D)return t(S,_,y)*t(b,_,y)<0&&t(_,S,b)*t(y,S,b)<0;const T=t(S,_,y),P=t(b,_,y);if(T*P>0)return!1;const x=t(_,S,b),M=t(y,S,b);return x*M>0?!1:T!==0||P!==0||x!==0||M!==0}i.segsIntersect=p;function v(S){if(S.length===0)return{left:0,top:0,right:0,bottom:0};const b={left:Number.MAX_SAFE_INTEGER,top:Number.MAX_SAFE_INTEGER,right:Number.MIN_SAFE_INTEGER,bottom:Number.MIN_SAFE_INTEGER};for(const _ of S)_.x<b.left&&(b.left=_.x),_.x>b.right&&(b.right=_.x),_.y<b.top&&(b.top=_.y),_.y>b.bottom&&(b.bottom=_.y);return b.left===Number.MAX_SAFE_INTEGER?{left:0,top:0,right:0,bottom:0}:b}i.getBounds=v;function I(S,b,_){if(b.x===_.x&&b.y===_.y)return{x:b.x,y:b.y,z:0};const y=_.x-b.x,D=_.y-b.y,T=((S.x-b.x)*y+(S.y-b.y)*D)/(y*y+D*D),P=T<0?0:T>1?1:T;return{x:Math.round(b.x+P*y),y:Math.round(b.y+P*D),z:0}}i.getClosestPtOnSegment=I;function w(S,b){const _=b.length;let y=0;if(_<3)return ge.IsOutside;for(;y<_&&b[y].y===S.y;)y++;if(y===_)return ge.IsOutside;let D=b[y].y<S.y;const T=D;let P=0,x=y+1,M=_;for(;;){if(x===M){if(M===0||y===0)break;M=y,x=0}if(D)for(;x<M&&b[x].y<S.y;)x++;else for(;x<M&&b[x].y>S.y;)x++;if(x===M)continue;const R=b[x],U=x>0?b[x-1]:b[_-1];if(R.y===S.y){if(R.x===S.x||R.y===U.y&&S.x<U.x!=S.x<R.x)return ge.IsOn;if(x++,x===y)break;continue}if(!(S.x<R.x&&S.x<U.x))if(S.x>U.x&&S.x>R.x)P=1-P;else{const W=n(U,R,S);if(W===0)return ge.IsOn;W<0===D&&(P=1-P)}D=!D,x++}if(D===T)return P===0?ge.IsOutside:ge.IsInside;x===_&&(x=0);const L=x===0?n(b[_-1],b[0],S):n(b[x-1],b[x],S);return L===0?ge.IsOn:(L<0===D&&(P=1-P),P===0?ge.IsOutside:ge.IsInside)}i.pointInPolygon=w;function C(S,b){let _=ge.IsOn;for(const T of S)switch(w(T,b)){case ge.IsOutside:if(_===ge.IsOutside)return!1;_=ge.IsOutside;break;case ge.IsInside:if(_===ge.IsInside)return!0;_=ge.IsInside;break}const y=v(S),D={x:Math.round((y.left+y.right)/2),y:Math.round((y.top+y.bottom)/2)};return w(D,b)!==ge.IsOutside}i.path2ContainsPath1=C})(pt||(pt={}));var ye;(function(i){function t(c=0,l=0,d=0){return{x:Math.round(c),y:Math.round(l),z:d}}i.create=t;function n(c){return{x:Math.round(c.x),y:Math.round(c.y),z:c.z||0}}i.fromPointD=n;function e(c,l){return{x:Math.round(c.x*l),y:Math.round(c.y*l),z:c.z||0}}i.scale=e;function o(c,l){return c.x===l.x&&c.y===l.y}i.equals=o;function s(c,l){return{x:c.x+l.x,y:c.y+l.y,z:0}}i.add=s;function a(c,l){return{x:c.x-l.x,y:c.y-l.y,z:0}}i.subtract=a;function r(c){return c.z!==void 0&&c.z!==0?`${c.x},${c.y},${c.z} `:`${c.x},${c.y} `}i.toString=r})(ye||(ye={}));var hi;(function(i){function t(r=0,c=0,l=0){return{x:r,y:c,z:l}}i.create=t;function n(r){return{x:r.x,y:r.y,z:r.z||0}}i.fromPoint64=n;function e(r,c){return{x:r.x*c,y:r.y*c,z:r.z||0}}i.scale=e;function o(r,c){return pt.isAlmostZero(r.x-c.x)&&pt.isAlmostZero(r.y-c.y)}i.equals=o;function s(r){r.x=-r.x,r.y=-r.y}i.negate=s;function a(r,c=2){return r.z!==void 0&&r.z!==0?`${r.x.toFixed(c)},${r.y.toFixed(c)},${r.z}`:`${r.x.toFixed(c)},${r.y.toFixed(c)}`}i.toString=a})(hi||(hi={}));var In;(function(i){function t(h=0,f=0,g=0,m=0){return{left:h,top:f,right:g,bottom:m}}i.create=t;function n(){return{left:Number.MAX_SAFE_INTEGER,top:Number.MAX_SAFE_INTEGER,right:Number.MIN_SAFE_INTEGER,bottom:Number.MIN_SAFE_INTEGER}}i.createInvalid=n;function e(h){return h.right-h.left}i.width=e;function o(h){return h.bottom-h.top}i.height=o;function s(h){return h.bottom<=h.top||h.right<=h.left}i.isEmpty=s;function a(h){return h.left<Number.MAX_SAFE_INTEGER}i.isValid=a;function r(h){return{x:Math.round((h.left+h.right)/2),y:Math.round((h.top+h.bottom)/2)}}i.midPoint=r;function c(h,f){return f.x>h.left&&f.x<h.right&&f.y>h.top&&f.y<h.bottom}i.contains=c;function l(h,f){return f.left>=h.left&&f.right<=h.right&&f.top>=h.top&&f.bottom<=h.bottom}i.containsRect=l;function d(h,f){return Math.max(h.left,f.left)<=Math.min(h.right,f.right)&&Math.max(h.top,f.top)<=Math.min(h.bottom,f.bottom)}i.intersects=d;function u(h){return[{x:h.left,y:h.top,z:0},{x:h.right,y:h.top,z:0},{x:h.right,y:h.bottom,z:0},{x:h.left,y:h.bottom,z:0}]}i.asPath=u})(In||(In={}));var cs;(function(i){function t(u=0,h=0,f=0,g=0){return{left:u,top:h,right:f,bottom:g}}i.create=t;function n(){return{left:Number.MAX_VALUE,top:Number.MAX_VALUE,right:-Number.MAX_VALUE,bottom:-Number.MAX_VALUE}}i.createInvalid=n;function e(u){return u.right-u.left}i.width=e;function o(u){return u.bottom-u.top}i.height=o;function s(u){return u.bottom<=u.top||u.right<=u.left}i.isEmpty=s;function a(u){return{x:(u.left+u.right)/2,y:(u.top+u.bottom)/2}}i.midPoint=a;function r(u,h){return h.x>u.left&&h.x<u.right&&h.y>u.top&&h.y<u.bottom}i.contains=r;function c(u,h){return h.left>=u.left&&h.right<=u.right&&h.top>=u.top&&h.bottom<=u.bottom}i.containsRect=c;function l(u,h){return Math.max(u.left,h.left)<Math.min(u.right,h.right)&&Math.max(u.top,h.top)<Math.min(u.bottom,h.bottom)}i.intersects=l;function d(u){return[{x:u.left,y:u.top,z:0},{x:u.right,y:u.top,z:0},{x:u.right,y:u.bottom,z:0},{x:u.left,y:u.bottom,z:0}]}i.asPath=d})(cs||(cs={}));var zs;(function(i){function t(s){let a="";for(const r of s)a+=ye.toString(r);return a+`
|
|
168
|
+
`}i.toString64=t;function n(s,a=2){let r="";for(const c of s)r+=hi.toString(c,a)+", ";return r!==""&&(r=r.slice(0,-2)),r}i.toStringD=n;function e(s){return[...s].reverse()}i.reverse64=e;function o(s){return[...s].reverse()}i.reverseD=o})(zs||(zs={}));var gm;(function(i){function t(s){let a="";for(const r of s)a+=zs.toString64(r);return a}i.toString64=t;function n(s,a=2){let r="";for(const c of s)r+=zs.toStringD(c,a)+`
|
|
169
|
+
`;return r}i.toStringD=n;function e(s){return s.map(a=>zs.reverse64(a))}i.reverse64=e;function o(s){return s.map(a=>zs.reverseD(a))}i.reverseD=o})(gm||(gm={}));const SP=In.createInvalid(),CP=cs.createInvalid();var Le;(function(i){i[i.None=0]="None",i[i.OpenStart=1]="OpenStart",i[i.OpenEnd=2]="OpenEnd",i[i.LocalMax=4]="LocalMax",i[i.LocalMin=8]="LocalMin"})(Le||(Le={}));class bP{data=[];push(t){this.data.push(t),this.siftUp(this.data.length-1)}pop(){if(this.data.length===0)return null;const t=this.data[0],n=this.data.pop();return this.data.length>0&&(this.data[0]=n,this.siftDown(0)),t}clear(){this.data.length=0}siftUp(t){for(;t>0;){const n=t-1>>1;if(this.data[n]>=this.data[t])break;[this.data[n],this.data[t]]=[this.data[t],this.data[n]],t=n}}siftDown(t){const n=this.data.length;for(;;){let e=t;const o=(t<<1)+1,s=o+1;if(o<n&&this.data[o]>this.data[e]&&(e=o),s<n&&this.data[s]>this.data[e]&&(e=s),e===t)break;[this.data[t],this.data[e]]=[this.data[e],this.data[t]],t=e}}}class mm{pt;next=null;prev=null;flags;constructor(t,n,e){this.pt=t,this.flags=n,this.prev=e}}class v0{vertex;polytype;isOpen;constructor(t,n,e=!1){this.vertex=t,this.polytype=n,this.isOpen=e}equals(t){return t!==null&&this.vertex===t.vertex}}function _P(i,t,n){return{pt:{x:i.x,y:i.y,z:i.z||0},edge1:t,edge2:n}}class Ri{static _nextId=1;_debugId;pt;next;prev;outrec;horz;constructor(t,n){this._debugId=Ri._nextId++,this.pt=t,this.outrec=n,this.next=this,this.prev=this,this.horz=null}}var qn;(function(i){i[i.None=0]="None",i[i.Left=1]="Left",i[i.Right=2]="Right"})(qn||(qn={}));var pm;(function(i){i[i.Bottom=0]="Bottom",i[i.Middle=1]="Middle",i[i.Top=2]="Top"})(pm||(pm={}));class df{static _nextId=1;_debugId;idx=0;owner=null;frontEdge=null;backEdge=null;pts=null;polypath=null;bounds={left:0,top:0,right:0,bottom:0};path=[];isOpen=!1;splits=null;recursiveSplit=null;constructor(){this._debugId=df._nextId++}}class yP{leftOp;rightOp;leftToRight;constructor(t){this.leftOp=t,this.rightOp=null,this.leftToRight=!0}}class vm{op1;op2;constructor(t,n){this.op1=t,this.op2=n}}let Im=class{bot={x:0,y:0,z:0};top={x:0,y:0,z:0};curX=0;dx=0;windDx=0;windCount=0;windCount2=0;outrec=null;prevInAEL=null;nextInAEL=null;prevInSEL=null;nextInSEL=null;jump=null;vertexTop=null;localMin=null;isLeftBound=!1;joinWith=qn.None};var Ju;(function(i){function t(e,o,s,a){if((e.flags&Le.LocalMin)!==Le.None)return;e.flags|=Le.LocalMin;const r=new v0(e,o,s);a.push(r)}i.addLocMin=t;function n(e,o,s,a,r){for(let c=0,l=e.length;c<l;c++){const d=e[c];let u=null,h=null;for(let p=0,v=d.length;p<v;p++){const I=d[p];if(u===null)u=new mm(I,Le.None,null),r.push(u),h=u;else if(!(h.pt.x===I.x&&h.pt.y===I.y)){const w=new mm(I,Le.None,h);r.push(w),h.next=w,h=w}}if(h?.prev===null||(!s&&h.pt.x===u.pt.x&&h.pt.y===u.pt.y&&(h=h.prev),h.next=u,u.prev=h,!s&&h.next===h))continue;let f;if(s){let p=u.next;for(;p!==u&&p.pt.y===u.pt.y;)p=p.next;f=p.pt.y<=u.pt.y,f?(u.flags=Le.OpenStart,t(u,o,!0,a)):u.flags=Le.OpenStart|Le.LocalMax}else{for(h=u.prev;h!==u&&h.pt.y===u.pt.y;)h=h.prev;if(h===u)continue;f=h.pt.y>u.pt.y}const g=f;h=u;let m=u.next;for(;m!==u;)m.pt.y>h.pt.y&&f?(h.flags|=Le.LocalMax,f=!1):m.pt.y<h.pt.y&&!f&&(f=!0,t(h,o,s,a)),h=m,m=m.next;s?(h.flags|=Le.OpenEnd,f?h.flags|=Le.LocalMax:t(h,o,s,a)):f!==g&&(g?t(h,o,!1,a):h.flags|=Le.LocalMax)}}i.addPathsToVertexList=n})(Ju||(Ju={}));class xP{parent;children=[];constructor(t=null){this.parent=t}get isHole(){return this.getIsHole()}getLevel(){let t=0,n=this.parent;for(;n!==null;)++t,n=n.parent;return t}get level(){return this.getLevel()}getIsHole(){const t=this.getLevel();return t!==0&&(t&1)===0}get count(){return this.children.length}clear(){this.children.length=0}toStringInternal(t,n){let e="";const o=" ".repeat(n),s=this.children.length===1?"":"s";(n&1)===0?e+=`${o}+- hole (${t}) contains ${this.children.length} nested polygon${s}.
|
|
170
|
+
`:e+=`${o}+- polygon (${t}) contains ${this.children.length} hole${s}.
|
|
171
|
+
`;for(let a=0;a<this.count;a++)this.children[a].count>0&&(e+=this.children[a].toStringInternal(a,n+1));return e}toString(){if(this.level>0)return"";const t=this.children.length===1?"":"s";let n=`Polytree with ${this.children.length} polygon${t}.
|
|
172
|
+
`;for(let e=0;e<this.count;e++)this.children[e].count>0&&(n+=this.children[e].toStringInternal(e,1));return n+`
|
|
173
|
+
`}}class ul extends xP{scale=1;polygon=null;constructor(t=null){super(t)}get poly(){return this.polygon}addChild(t){const n=new ul(this);return n.scale=this.scale,n.polygon=pa.scalePathD(t,1/this.scale),this.children.push(n),n}addChildD(t){const n=new ul(this);return n.scale=this.scale,n.polygon=t,this.children.push(n),n}child(t){if(t<0||t>=this.children.length)throw new Error("Index out of range");return this.children[t]}area(){let t=this.polygon===null?0:pa.areaD(this.polygon);for(const n of this.children)t+=n.area();return t}}class I0 extends ul{get scaleValue(){return this.scale}}class Y{cliptype=Ce.NoClip;fillrule=we.EvenOdd;actives=null;sel=null;minimaList=[];intersectList=[];vertexList=[];outrecList=[];scanlineHeap=new bP;scanlineSet=new Set;scanlineArr=[];useScanlineArray=!1;horzSegList=[];horzJoinList=[];currentLocMin=0;currentBotY=0;isSortedMinimaList=!1;hasOpenPaths=!1;usingPolytree=!1;succeeded=!1;preserveCollinear=!0;reverseSolution=!1;constructor(){}getZCallback(){}xyEqual(t,n){return t.x===n.x&&t.y===n.y}setZ(t,n,e){const o=this.getZCallback();o&&(Y.getPolyType(t)===Ze.Subject?(this.xyEqual(e,t.bot)?e.z=t.bot.z:this.xyEqual(e,t.top)?e.z=t.top.z:this.xyEqual(e,n.bot)?e.z=n.bot.z:this.xyEqual(e,n.top)?e.z=n.top.z:e.z=0,o(t.bot,t.top,n.bot,n.top,e)):(this.xyEqual(e,n.bot)?e.z=n.bot.z:this.xyEqual(e,n.top)?e.z=n.top.z:this.xyEqual(e,t.bot)?e.z=t.bot.z:this.xyEqual(e,t.top)?e.z=t.top.z:e.z=0,o(n.bot,n.top,t.bot,t.top,e)))}static isOdd(t){return(t&1)!==0}static isHotEdge(t){return t.outrec!=null}static isOpen(t){return t.localMin.isOpen}static isOpenEnd(t){return t.localMin.isOpen&&Y.isOpenEndVertex(t.vertexTop)}static isOpenEndVertex(t){return(t.flags&(Le.OpenStart|Le.OpenEnd))!==Le.None}static getPrevHotEdge(t){let n=t.prevInAEL;for(;n!==null&&(Y.isOpen(n)||!Y.isHotEdge(n));)n=n.prevInAEL;return n}static isFront(t){return t===t.outrec.frontEdge}static getDx(t,n){const e=n.y-t.y;return e!==0?(n.x-t.x)/e:n.x>t.x?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY}static topX(t,n){return n===t.top.y||t.top.x===t.bot.x?t.top.x:n===t.bot.y?t.bot.x:pt.roundToEven(t.bot.x+t.dx*(n-t.bot.y))}static isHorizontal(t){return t.top.y===t.bot.y}static isHeadingRightHorz(t){return t.dx===Number.NEGATIVE_INFINITY}static isHeadingLeftHorz(t){return t.dx===Number.POSITIVE_INFINITY}static swapActives(t,n){return[n,t]}static getPolyType(t){return t.localMin.polytype}static isSamePolyType(t,n){return t.localMin.polytype===n.localMin.polytype}static setDx(t){t.dx=Y.getDx(t.bot,t.top)}static nextVertex(t){return t.windDx>0?t.vertexTop.next:t.vertexTop.prev}static prevPrevVertex(t){return t.windDx>0?t.vertexTop.prev.prev:t.vertexTop.next.next}static isMaxima(t){return"flags"in t?(t.flags&Le.LocalMax)!==Le.None:Y.isMaxima(t.vertexTop)}static getMaximaPair(t){let n=t.nextInAEL;for(;n!==null;){if(n.vertexTop===t.vertexTop)return n;n=n.nextInAEL}return null}boundingBoxesOverlap(t,n,e,o){const s=Math.min(t.x,n.x),a=Math.max(t.x,n.x),r=Math.min(t.y,n.y),c=Math.max(t.y,n.y),l=Math.min(e.x,o.x),d=Math.max(e.x,o.x),u=Math.min(e.y,o.y),h=Math.max(e.y,o.y);return!(a<l||d<s||c<u||h<r)}clearSolutionOnly(){for(;this.actives!==null;)this.deleteFromAEL(this.actives);this.scanlineHeap.clear(),this.scanlineSet.clear(),this.scanlineArr.length=0,this.disposeIntersectNodes(),this.outrecList.length=0,this.horzSegList.length=0,this.horzJoinList.length=0}clear(){this.clearSolutionOnly(),this.minimaList.length=0,this.vertexList.length=0,this.currentLocMin=0,this.isSortedMinimaList=!1,this.hasOpenPaths=!1}reset(){this.isSortedMinimaList||(this.minimaList.sort((t,n)=>n.vertex.pt.y-t.vertex.pt.y),this.isSortedMinimaList=!0),this.scanlineHeap.clear(),this.scanlineSet.clear(),this.scanlineArr.length=0,this.useScanlineArray=this.minimaList.length<=16;for(let t=this.minimaList.length-1;t>=0;t--)this.insertScanline(this.minimaList[t].vertex.pt.y);this.currentBotY=0,this.currentLocMin=0,this.actives=null,this.sel=null,this.succeeded=!0}upgradeScanlineStructureFromArray(){const t=this.scanlineArr;for(let n=0,e=t.length;n<e;n++){const o=t[n];this.scanlineSet.add(o),this.scanlineHeap.push(o)}t.length=0,this.useScanlineArray=!1}insertScanline(t){if(this.useScanlineArray){const n=this.scanlineArr;for(let e=0,o=n.length;e<o;e++)if(n[e]===t)return;n.push(t),n.length>64&&this.upgradeScanlineStructureFromArray();return}this.scanlineSet.has(t)||(this.scanlineSet.add(t),this.scanlineHeap.push(t))}popScanline(){if(this.useScanlineArray){const n=this.scanlineArr,e=n.length;if(e===0)return{success:!1,y:0};let o=0,s=n[0];for(let a=1;a<e;a++){const r=n[a];r>s&&(s=r,o=a)}return n[o]=n[e-1],n.pop(),{success:!0,y:s}}const t=this.scanlineHeap.pop();return t===null?{success:!1,y:0}:(this.scanlineSet.delete(t),{success:!0,y:t})}hasLocMinAtY(t){return this.currentLocMin<this.minimaList.length&&this.minimaList[this.currentLocMin].vertex.pt.y===t}popLocalMinima(){return this.minimaList[this.currentLocMin++]}addPath(t,n,e=!1){const o=[t];this.addPaths(o,n,e)}addPaths(t,n,e=!1){e&&(this.hasOpenPaths=!0),this.isSortedMinimaList=!1,Ju.addPathsToVertexList(t,n,e,this.minimaList,this.vertexList)}addReuseableData(t){if(t.minimaList.length!==0){this.isSortedMinimaList=!1;for(const n of t.minimaList)this.minimaList.push(new v0(n.vertex,n.polytype,n.isOpen)),n.isOpen&&(this.hasOpenPaths=!0)}}deleteFromAEL(t){const n=t.prevInAEL,e=t.nextInAEL;n===null&&e===null&&t!==this.actives||(n!==null?n.nextInAEL=e:this.actives=e,e!==null&&(e.prevInAEL=n))}getBounds(){const t={left:Number.MAX_SAFE_INTEGER,top:Number.MAX_SAFE_INTEGER,right:Number.MIN_SAFE_INTEGER,bottom:Number.MIN_SAFE_INTEGER};for(const n of this.vertexList){let e=n;do e.pt.x<t.left&&(t.left=e.pt.x),e.pt.x>t.right&&(t.right=e.pt.x),e.pt.y<t.top&&(t.top=e.pt.y),e.pt.y>t.bottom&&(t.bottom=e.pt.y),e=e.next;while(e!==n)}return In.isEmpty(t)?{left:0,top:0,right:0,bottom:0}:t}executeInternal(t,n){if(t===Ce.NoClip)return;this.fillrule=n,this.cliptype=t,this.reset();const e=this.popScanline();if(!e.success)return;let o=e.y;for(;this.succeeded;){this.insertLocalMinimaIntoAEL(o);let s;for(;(s=this.popHorz())!==null;)this.doHorizontal(s);this.horzSegList.length>0&&(this.convertHorzSegsToJoins(),this.horzSegList.length=0),this.currentBotY=o;const a=this.popScanline();if(!a.success)break;for(o=a.y,this.doIntersections(o),this.doTopOfScanbeam(o);(s=this.popHorz())!==null;)this.doHorizontal(s)}this.succeeded&&this.processHorzJoins()}insertLocalMinimaIntoAEL(t){for(;this.hasLocMinAtY(t);){const n=this.popLocalMinima();let e;(n.vertex.flags&Le.OpenStart)!==Le.None?e=null:(e=new Im,e.bot={x:n.vertex.pt.x,y:n.vertex.pt.y,z:n.vertex.pt.z||0},e.curX=n.vertex.pt.x,e.windDx=-1,e.vertexTop=n.vertex.prev,e.top={x:n.vertex.prev.pt.x,y:n.vertex.prev.pt.y,z:n.vertex.prev.pt.z||0},e.outrec=null,e.localMin=n,Y.setDx(e));let o;(n.vertex.flags&Le.OpenEnd)!==Le.None?o=null:(o=new Im,o.bot={x:n.vertex.pt.x,y:n.vertex.pt.y,z:n.vertex.pt.z||0},o.curX=n.vertex.pt.x,o.windDx=1,o.vertexTop=n.vertex.next,o.top={x:n.vertex.next.pt.x,y:n.vertex.next.pt.y,z:n.vertex.next.pt.z||0},o.outrec=null,o.localMin=n,Y.setDx(o)),e!==null&&o!==null?Y.isHorizontal(e)?Y.isHeadingRightHorz(e)&&([e,o]=Y.swapActives(e,o)):Y.isHorizontal(o)?Y.isHeadingLeftHorz(o)&&([e,o]=Y.swapActives(e,o)):e.dx<o.dx&&([e,o]=Y.swapActives(e,o)):e===null&&(e=o,o=null);let s;if(e.isLeftBound=!0,this.insertLeftEdge(e),Y.isOpen(e)?(this.setWindCountForOpenPathEdge(e),s=this.isContributingOpen(e)):(this.setWindCountForClosedPathEdge(e),s=this.isContributingClosed(e)),o!==null){for(o.windCount=e.windCount,o.windCount2=e.windCount2,this.insertRightEdge(e,o),s&&(this.addLocalMinPoly(e,o,e.bot,!0),Y.isHorizontal(e)||this.checkJoinLeft(e,e.bot));o.nextInAEL!==null&&this.isValidAelOrder(o.nextInAEL,o);)this.intersectEdges(o,o.nextInAEL,o.bot),this.swapPositionsInAEL(o,o.nextInAEL);Y.isHorizontal(o)?this.pushHorz(o):(this.checkJoinRight(o,o.bot),this.insertScanline(o.top.y))}else s&&this.startOpenPath(e,e.bot);Y.isHorizontal(e)?this.pushHorz(e):this.insertScanline(e.top.y)}}pushHorz(t){t.nextInSEL=this.sel,this.sel=t}popHorz(){const t=this.sel;return t===null?null:(this.sel=this.sel.nextInSEL,t)}doHorizontal(t){const n=Y.isOpen(t),e=t.bot.y,o=n?this.getCurrYMaximaVertexOpen(t):this.getCurrYMaximaVertex(t),{isLeftToRight:s,leftX:a,rightX:r}=this.resetHorzDirection(t,o);let c=a,l=r;if(Y.isHotEdge(t)){const d=this.addOutPt(t,{x:t.curX,y:e});this.addToHorzSegList(d)}for(;;){let d=s?t.nextInAEL:t.prevInAEL;for(;d!==null;){if(d.vertexTop===o){if(Y.isHotEdge(t)&&this.isJoined(d)&&this.split(d,d.top),Y.isHotEdge(t)){for(;t.vertexTop!==o;)this.addOutPt(t,t.top),this.updateEdgeIntoAEL(t);s?this.addLocalMaxPoly(t,d,t.top):this.addLocalMaxPoly(d,t,t.top)}this.deleteFromAEL(d),this.deleteFromAEL(t);return}if(o!==t.vertexTop||Y.isOpenEnd(t)){if(s&&d.curX>l||!s&&d.curX<c)break;if(d.curX===t.top.x&&!Y.isHorizontal(d)){const f=Y.nextVertex(t).pt;if(Y.isOpen(d)&&!Y.isSamePolyType(d,t)&&!Y.isHotEdge(d)){if(s&&Y.topX(d,f.y)>f.x||!s&&Y.topX(d,f.y)<f.x)break}else if(s&&Y.topX(d,f.y)>=f.x||!s&&Y.topX(d,f.y)<=f.x)break}}const h={x:d.curX,y:e};s?(this.intersectEdges(t,d,h),this.swapPositionsInAEL(t,d),this.checkJoinLeft(d,h),t.curX=d.curX,d=t.nextInAEL):(this.intersectEdges(d,t,h),this.swapPositionsInAEL(d,t),this.checkJoinRight(d,h),t.curX=d.curX,d=t.prevInAEL),Y.isHotEdge(t)&&this.addToHorzSegList(this.getLastOp(t))}if(n&&Y.isOpenEnd(t)){Y.isHotEdge(t)&&(this.addOutPt(t,t.top),Y.isFront(t)?t.outrec.frontEdge=null:t.outrec.backEdge=null,t.outrec=null),this.deleteFromAEL(t);return}if(Y.nextVertex(t).pt.y!==t.top.y)break;Y.isHotEdge(t)&&this.addOutPt(t,t.top),this.updateEdgeIntoAEL(t);const u=this.resetHorzDirection(t,o);c=u.leftX,l=u.rightX}if(Y.isHotEdge(t)){const d=this.addOutPt(t,t.top);this.addToHorzSegList(d)}this.updateEdgeIntoAEL(t)}convertHorzSegsToJoins(){let t=0;for(const n of this.horzSegList)this.updateHorzSegment(n)&&t++;if(!(t<2)){this.horzSegList.sort((n,e)=>this.horzSegSort(n,e));for(let n=0;n<t-1;n++){const e=this.horzSegList[n];for(let o=n+1;o<t;o++){const s=this.horzSegList[o];if(s.leftOp.pt.x>=e.rightOp.pt.x||s.leftToRight===e.leftToRight||s.rightOp.pt.x<=e.leftOp.pt.x)continue;const a=e.leftOp.pt.y;if(e.leftToRight){for(;e.leftOp.next.pt.y===a&&e.leftOp.next.pt.x<=s.leftOp.pt.x;)e.leftOp=e.leftOp.next;for(;s.leftOp.prev.pt.y===a&&s.leftOp.prev.pt.x<=e.leftOp.pt.x;)s.leftOp=s.leftOp.prev;const r=new vm(this.duplicateOp(e.leftOp,!0),this.duplicateOp(s.leftOp,!1));this.horzJoinList.push(r)}else{for(;e.leftOp.prev.pt.y===a&&e.leftOp.prev.pt.x<=s.leftOp.pt.x;)e.leftOp=e.leftOp.prev;for(;s.leftOp.next.pt.y===a&&s.leftOp.next.pt.x<=e.leftOp.pt.x;)s.leftOp=s.leftOp.next;const r=new vm(this.duplicateOp(s.leftOp,!0),this.duplicateOp(e.leftOp,!1));this.horzJoinList.push(r)}}}}}updateHorzSegment(t){const n=t.leftOp,e=this.getRealOutRec(n.outrec),o=e.frontEdge!==null,s=n.pt.y;let a=n,r=n;if(o){const l=e.pts,d=l.next;for(;a!==d&&a.prev.pt.y===s;)a=a.prev;for(;r!==l&&r.next.pt.y===s;)r=r.next}else{for(;a.prev!==r&&a.prev.pt.y===s;)a=a.prev;for(;r.next!==a&&r.next.pt.y===s;)r=r.next}const c=this.setHorzSegHeadingForward(t,a,r)&&t.leftOp.horz===null;return c?t.leftOp.horz=t:t.rightOp=null,c}setHorzSegHeadingForward(t,n,e){return n.pt.x===e.pt.x?!1:(n.pt.x<e.pt.x?(t.leftOp=n,t.rightOp=e,t.leftToRight=!0):(t.leftOp=e,t.rightOp=n,t.leftToRight=!1),!0)}horzSegSort(t,n){return t.rightOp===null?n.rightOp===null?0:1:n.rightOp===null?-1:t.leftOp.pt.x-n.leftOp.pt.x}duplicateOp(t,n){const e=new Ri(t.pt,t.outrec);return n?(e.next=t.next,e.next.prev=e,e.prev=t,t.next=e):(e.prev=t.prev,e.prev.next=e,e.next=t,t.prev=e),e}getRealOutRec(t){for(;t!==null&&t.pts===null;)t=t.owner;return t}doIntersections(t){this.buildIntersectList(t)&&(this.processIntersectList(),this.disposeIntersectNodes())}doTopOfScanbeam(t){this.sel=null;let n=this.actives;for(;n!==null;){if(n.top.y===t)if(n.curX=n.top.x,Y.isMaxima(n)){n=this.doMaxima(n);continue}else Y.isHotEdge(n)&&this.addOutPt(n,n.top),this.updateEdgeIntoAEL(n),Y.isHorizontal(n)&&this.pushHorz(n);else n.curX=Y.topX(n,t);n=n.nextInAEL}}processHorzJoins(){for(const t of this.horzJoinList){const n=this.getRealOutRec(t.op1.outrec),e=this.getRealOutRec(t.op2.outrec),o=t.op1.next,s=t.op2.prev;if(t.op1.next=t.op2,t.op2.prev=t.op1,o.prev=s,s.next=o,n===e){const a=this.newOutRec();a.pts=o,this.fixOutRecPts(a),n.pts.outrec===a&&(n.pts=t.op1,n.pts.outrec=n),this.usingPolytree?(this.path1InsidePath2(n.pts,a.pts)?([a.pts,n.pts]=[n.pts,a.pts],this.fixOutRecPts(n),this.fixOutRecPts(a),a.owner=n):this.path1InsidePath2(a.pts,n.pts)?a.owner=n:a.owner=n.owner,n.splits===null&&(n.splits=[]),n.splits.push(a.idx)):a.owner=n}else e.pts=null,this.usingPolytree?(this.setOwner(e,n),this.moveSplits(e,n)):e.owner=n}}fixOutRecPts(t){let n=t.pts;do n.outrec=t,n=n.next;while(n!==t.pts)}path1InsidePath2(t,n){let e=ge.IsOn,o=t;do{switch(this.pointInOpPolygon(o.pt,n)){case ge.IsOutside:if(e===ge.IsOutside)return!1;e=ge.IsOutside;break;case ge.IsInside:if(e===ge.IsInside)return!0;e=ge.IsInside;break}o=o.next}while(o!==t);return pt.path2ContainsPath1(this.getCleanPath(t),this.getCleanPath(n))}pointInOpPolygon(t,n){if(n===n.next||n.prev===n.next)return ge.IsOutside;let e=n;do{if(n.pt.y!==t.y)break;n=n.next}while(n!==e);if(n.pt.y===t.y)return ge.IsOutside;let o=n.pt.y<t.y;const s=o;let a=0;for(e=n.next;e!==n;){if(o)for(;e!==n&&e.pt.y<t.y;)e=e.next;else for(;e!==n&&e.pt.y>t.y;)e=e.next;if(e===n)break;if(e.pt.y===t.y){if(e.pt.x===t.x||e.pt.y===e.prev.pt.y&&t.x<e.prev.pt.x!=t.x<e.pt.x)return ge.IsOn;if(e=e.next,e===n)break;continue}if(e.pt.x<=t.x||e.prev.pt.x<=t.x)if(e.prev.pt.x<t.x&&e.pt.x<t.x)a=1-a;else{const r=pt.crossProduct(e.prev.pt,e.pt,t);if(r===0)return ge.IsOn;r<0===o&&(a=1-a)}o=!o,e=e.next}if(o===s)return a===0?ge.IsOutside:ge.IsInside;{const r=pt.crossProduct(e.prev.pt,e.pt,t);if(r===0)return ge.IsOn;r<0===o&&(a=1-a)}return a===0?ge.IsOutside:ge.IsInside}getCleanPath(t){const n=[];let e=t;for(;e.next!==t&&(e.pt.x===e.next.pt.x&&e.pt.x===e.prev.pt.x||e.pt.y===e.next.pt.y&&e.pt.y===e.prev.pt.y);)e=e.next;n.push(e.pt);let o=e;for(e=e.next;e!==t;)(e.pt.x!==e.next.pt.x||e.pt.x!==o.pt.x)&&(e.pt.y!==e.next.pt.y||e.pt.y!==o.pt.y)&&(n.push(e.pt),o=e),e=e.next;return n}moveSplits(t,n){if(t.splits!==null){n.splits===null&&(n.splits=[]);for(const e of t.splits)e!==n.idx&&n.splits.push(e);t.splits=null}}buildIntersectList(t){if(this.actives?.nextInAEL===null)return!1;this.adjustCurrXAndCopyToSEL(t);let n=this.sel;for(;n!==null&&n.jump!==null;){let e=null;for(;n!==null&&n.jump!==null;){let o=n,s=n.jump,a=s;const r=s?.jump||null;for(n.jump=r;n!==a&&s!==r;)if(s.curX<n.curX){let c=s.prevInSEL;for(;this.addNewIntersectNode(c,s,t),c!==n;)c=c.prevInSEL;if(c=s,s=this.extractFromSEL(c),a=s,n!==null&&this.insert1Before2InSEL(c,n),n!==o)continue;o=c,o.jump=r,e===null?this.sel=o:e.jump=o}else n=n.nextInSEL;e=o,n=r}n=this.sel}return this.intersectList.length>0}processIntersectList(){this.intersectList.sort((t,n)=>t.pt.y!==n.pt.y?t.pt.y>n.pt.y?-1:1:t.pt.x!==n.pt.x?t.pt.x<n.pt.x?-1:1:t.edge1.curX!==n.edge1.curX?t.edge1.curX<n.edge1.curX?-1:1:t.edge2.curX<n.edge2.curX?-1:t.edge2.curX>n.edge2.curX?1:0);for(let t=0;t<this.intersectList.length;++t){if(!this.edgesAdjacentInAEL(this.intersectList[t])){let e=t+1;for(;!this.edgesAdjacentInAEL(this.intersectList[e]);)e++;[this.intersectList[e],this.intersectList[t]]=[this.intersectList[t],this.intersectList[e]]}const n=this.intersectList[t];this.intersectEdges(n.edge1,n.edge2,n.pt),this.swapPositionsInAEL(n.edge1,n.edge2),n.edge1.curX=n.pt.x,n.edge2.curX=n.pt.x,this.checkJoinLeft(n.edge2,n.pt,!0),this.checkJoinRight(n.edge1,n.pt,!0)}}edgesAdjacentInAEL(t){return t.edge1.nextInAEL===t.edge2||t.edge1.prevInAEL===t.edge2}adjustCurrXAndCopyToSEL(t){let n=this.actives;for(this.sel=n;n!==null;)n.prevInSEL=n.prevInAEL,n.nextInSEL=n.nextInAEL,n.jump=n.nextInSEL,n.curX=Y.topX(n,t),n=n.nextInAEL}doMaxima(t){const n=t.prevInAEL;let e=t.nextInAEL;if(Y.isOpenEnd(t))return Y.isHotEdge(t)&&this.addOutPt(t,t.top),Y.isHorizontal(t)||(Y.isHotEdge(t)&&(Y.isFront(t)?t.outrec.frontEdge=null:t.outrec.backEdge=null,t.outrec=null),this.deleteFromAEL(t)),e;const o=Y.getMaximaPair(t);if(o===null)return e;for(this.isJoined(t)&&this.split(t,t.top),this.isJoined(o)&&this.split(o,o.top);e!==o;)this.intersectEdges(t,e,t.top),this.swapPositionsInAEL(t,e),e=t.nextInAEL;return Y.isOpen(t)?(Y.isHotEdge(t)&&this.addLocalMaxPoly(t,o,t.top),this.deleteFromAEL(o),this.deleteFromAEL(t),n!==null?n.nextInAEL:this.actives):(Y.isHotEdge(t)&&this.addLocalMaxPoly(t,o,t.top),this.deleteFromAEL(t),this.deleteFromAEL(o),n!==null?n.nextInAEL:this.actives)}updateEdgeIntoAEL(t){if(t.bot={x:t.top.x,y:t.top.y,z:t.top.z||0},t.vertexTop=Y.nextVertex(t),t.top={x:t.vertexTop.pt.x,y:t.vertexTop.pt.y,z:t.vertexTop.pt.z||0},t.curX=t.bot.x,Y.setDx(t),this.isJoined(t)&&this.split(t,t.bot),Y.isHorizontal(t)){Y.isOpen(t)||this.trimHorz(t,this.preserveCollinear);return}this.insertScanline(t.top.y),this.checkJoinLeft(t,t.bot),this.checkJoinRight(t,t.bot,!0)}trimHorz(t,n){let e=!1,o=Y.nextVertex(t).pt;for(;o.y===t.top.y&&!(n&&o.x<t.top.x!=t.bot.x<t.top.x||(t.vertexTop=Y.nextVertex(t),t.top=o,e=!0,Y.isMaxima(t)));)o=Y.nextVertex(t).pt;e&&Y.setDx(t)}addToHorzSegList(t){t.outrec.isOpen||this.horzSegList.push(new yP(t))}addNewIntersectNode(t,n,e){const o=pt.getLineIntersectPt(t.bot,t.top,n.bot,n.top);let s;if(o.intersects?s=o.point:s={x:t.curX,y:e,z:0},s.y>this.currentBotY||s.y<e){const r=Math.abs(t.dx),c=Math.abs(n.dx);r>100&&c>100?r>c?s=pt.getClosestPtOnSegment(s,t.bot,t.top):s=pt.getClosestPtOnSegment(s,n.bot,n.top):r>100?s=pt.getClosestPtOnSegment(s,t.bot,t.top):c>100?s=pt.getClosestPtOnSegment(s,n.bot,n.top):(s.y<e?s.y=e:s.y=this.currentBotY,r<c?s.x=Y.topX(t,s.y):s.x=Y.topX(n,s.y))}const a=_P(s,t,n);this.intersectList.push(a)}extractFromSEL(t){const n=t.nextInSEL;return n!==null&&(n.prevInSEL=t.prevInSEL),t.prevInSEL.nextInSEL=n,n}insert1Before2InSEL(t,n){t.prevInSEL=n.prevInSEL,t.prevInSEL!==null&&(t.prevInSEL.nextInSEL=t),t.nextInSEL=n,n.prevInSEL=t}getCurrYMaximaVertexOpen(t){let n=t.vertexTop;if(t.windDx>0)for(;n.next.pt.y===n.pt.y&&(n.flags&(Le.OpenEnd|Le.LocalMax))===Le.None;)n=n.next;else for(;n.prev.pt.y===n.pt.y&&(n.flags&(Le.OpenEnd|Le.LocalMax))===Le.None;)n=n.prev;return Y.isMaxima(n)||(n=null),n}getCurrYMaximaVertex(t){let n=t.vertexTop;if(t.windDx>0)for(;n.next.pt.y===n.pt.y;)n=n.next;else for(;n.prev.pt.y===n.pt.y;)n=n.prev;return Y.isMaxima(n)||(n=null),n}resetHorzDirection(t,n){if(t.bot.x===t.top.x){const e=t.curX,o=t.curX;let s=t.nextInAEL;for(;s!==null&&s.vertexTop!==n;)s=s.nextInAEL;return{isLeftToRight:s!==null,leftX:e,rightX:o}}return t.curX<t.top.x?{isLeftToRight:!0,leftX:t.curX,rightX:t.top.x}:{isLeftToRight:!1,leftX:t.top.x,rightX:t.curX}}getLastOp(t){const n=t.outrec;return t===n.frontEdge?n.pts:n.pts.next}insertLeftEdge(t){if(this.actives===null)t.prevInAEL=null,t.nextInAEL=null,this.actives=t;else if(!this.isValidAelOrder(this.actives,t))t.prevInAEL=null,t.nextInAEL=this.actives,this.actives.prevInAEL=t,this.actives=t;else{let n=this.actives;for(;n.nextInAEL!==null&&this.isValidAelOrder(n.nextInAEL,t);)n=n.nextInAEL;n.joinWith===qn.Right&&(n=n.nextInAEL),t.nextInAEL=n.nextInAEL,n.nextInAEL!==null&&(n.nextInAEL.prevInAEL=t),t.prevInAEL=n,n.nextInAEL=t}}insertRightEdge(t,n){n.nextInAEL=t.nextInAEL,t.nextInAEL!==null&&(t.nextInAEL.prevInAEL=n),n.prevInAEL=t,t.nextInAEL=n}setWindCountForOpenPathEdge(t){let n=this.actives;if(this.fillrule===we.EvenOdd){let e=0,o=0;for(;n!==t;)Y.getPolyType(n)===Ze.Clip?o++:Y.isOpen(n)||e++,n=n.nextInAEL;t.windCount=Y.isOdd(e)?1:0,t.windCount2=Y.isOdd(o)?1:0}else for(;n!==t;)Y.getPolyType(n)===Ze.Clip?t.windCount2+=n.windDx:Y.isOpen(n)||(t.windCount+=n.windDx),n=n.nextInAEL}setWindCountForClosedPathEdge(t){let n=t.prevInAEL;const e=Y.getPolyType(t);for(;n!==null&&(Y.getPolyType(n)!==e||Y.isOpen(n));)n=n.prevInAEL;if(n===null?(t.windCount=t.windDx,n=this.actives):this.fillrule===we.EvenOdd?(t.windCount=t.windDx,t.windCount2=n.windCount2,n=n.nextInAEL):(n.windCount*n.windDx<0?Math.abs(n.windCount)>1?n.windDx*t.windDx<0?t.windCount=n.windCount:t.windCount=n.windCount+t.windDx:t.windCount=Y.isOpen(t)?1:t.windDx:n.windDx*t.windDx<0?t.windCount=n.windCount:t.windCount=n.windCount+t.windDx,t.windCount2=n.windCount2,n=n.nextInAEL),this.fillrule===we.EvenOdd)for(;n!==t;)Y.getPolyType(n)!==e&&!Y.isOpen(n)&&(t.windCount2=t.windCount2===0?1:0),n=n.nextInAEL;else for(;n!==t;)Y.getPolyType(n)!==e&&!Y.isOpen(n)&&(t.windCount2+=n.windDx),n=n.nextInAEL}isContributingOpen(t){let n,e;switch(this.fillrule){case we.Positive:e=t.windCount>0,n=t.windCount2>0;break;case we.Negative:e=t.windCount<0,n=t.windCount2<0;break;default:e=t.windCount!==0,n=t.windCount2!==0;break}switch(this.cliptype){case Ce.Intersection:return n;case Ce.Union:return!e&&!n;default:return!n}}isContributingClosed(t){switch(this.fillrule){case we.Positive:if(t.windCount!==1)return!1;break;case we.Negative:if(t.windCount!==-1)return!1;break;case we.NonZero:if(Math.abs(t.windCount)!==1)return!1;break}switch(this.cliptype){case Ce.Intersection:return this.fillrule===we.Positive?t.windCount2>0:this.fillrule===we.Negative?t.windCount2<0:t.windCount2!==0;case Ce.Union:return this.fillrule===we.Positive?t.windCount2<=0:this.fillrule===we.Negative?t.windCount2>=0:t.windCount2===0;case Ce.Difference:const n=this.fillrule===we.Positive?t.windCount2<=0:this.fillrule===we.Negative?t.windCount2>=0:t.windCount2===0;return Y.getPolyType(t)===Ze.Subject?n:!n;case Ce.Xor:return!0;default:return!1}}addLocalMinPoly(t,n,e,o=!1){const s=this.newOutRec();if(t.outrec=s,n.outrec=s,Y.isOpen(t))s.owner=null,s.isOpen=!0,t.windDx>0?this.setSides(s,t,n):this.setSides(s,n,t);else{s.isOpen=!1;const r=Y.getPrevHotEdge(t);r!==null?(this.usingPolytree&&this.setOwner(s,r.outrec),s.owner=r.outrec,this.outrecIsAscending(r)===o?this.setSides(s,n,t):this.setSides(s,t,n)):(s.owner=null,o?this.setSides(s,t,n):this.setSides(s,n,t))}const a=new Ri(e,s);return s.pts=a,a}outrecIsAscending(t){return t===t.outrec.frontEdge}newOutRec(){const t=new df;return t.idx=this.outrecList.length,this.outrecList.push(t),t}startOpenPath(t,n){const e=this.newOutRec();e.isOpen=!0,t.windDx>0?(e.frontEdge=t,e.backEdge=null):(e.frontEdge=null,e.backEdge=t),t.outrec=e;const o=new Ri(n,e);return e.pts=o,o}checkJoinLeft(t,n,e=!1){const o=t.prevInAEL;if(!(o===null||!Y.isHotEdge(t)||!Y.isHotEdge(o)||Y.isHorizontal(t)||Y.isHorizontal(o)||Y.isOpen(t)||Y.isOpen(o))&&!((n.y<t.top.y+2||n.y<o.top.y+2)&&(t.bot.y>n.y||o.bot.y>n.y))){if(e){if(this.perpendicDistFromLineSqrd(n,o.bot,o.top)>.25)return}else if(t.curX!==o.curX)return;pt.isCollinear(t.top,n,o.top)&&(t.outrec.idx===o.outrec.idx?this.addLocalMaxPoly(o,t,n):t.outrec.idx<o.outrec.idx?this.joinOutrecPaths(t,o):this.joinOutrecPaths(o,t),o.joinWith=qn.Right,t.joinWith=qn.Left)}}checkJoinRight(t,n,e=!1){const o=t.nextInAEL;if(!(o===null||!Y.isHotEdge(t)||!Y.isHotEdge(o)||Y.isHorizontal(t)||Y.isHorizontal(o)||Y.isOpen(t)||Y.isOpen(o))&&!((n.y<t.top.y+2||n.y<o.top.y+2)&&(t.bot.y>n.y||o.bot.y>n.y))){if(e){if(this.perpendicDistFromLineSqrd(n,o.bot,o.top)>.25)return}else if(t.curX!==o.curX)return;pt.isCollinear(t.top,n,o.top)&&(t.outrec.idx===o.outrec.idx?this.addLocalMaxPoly(t,o,n):t.outrec.idx<o.outrec.idx?this.joinOutrecPaths(t,o):this.joinOutrecPaths(o,t),t.joinWith=qn.Right,o.joinWith=qn.Left)}}perpendicDistFromLineSqrd(t,n,e){const o=t.x-n.x,s=t.y-n.y,a=e.x-n.x,r=e.y-n.y;return a===0&&r===0?0:(o*r-a*s)*(o*r-a*s)/(a*a+r*r)}intersectEdges(t,n,e){let o=null;if(this.hasOpenPaths&&(Y.isOpen(t)||Y.isOpen(n))){if(Y.isOpen(t)&&Y.isOpen(n))return;if(Y.isOpen(n)&&([t,n]=Y.swapActives(t,n)),this.isJoined(n)&&this.split(n,e),this.cliptype===Ce.Union){if(!Y.isHotEdge(n))return}else if(n.localMin.polytype===Ze.Subject)return;switch(this.fillrule){case we.Positive:if(n.windCount!==1)return;break;case we.Negative:if(n.windCount!==-1)return;break;default:if(Math.abs(n.windCount)!==1)return;break}if(Y.isHotEdge(t))o=this.addOutPt(t,e),this.setZ(t,n,o.pt),Y.isFront(t)?t.outrec.frontEdge=null:t.outrec.backEdge=null,t.outrec=null;else if(e.x===t.localMin.vertex.pt.x&&e.y===t.localMin.vertex.pt.y&&!Y.isOpenEndVertex(t.localMin.vertex)){const l=this.findEdgeWithMatchingLocMin(t);if(l!==null&&Y.isHotEdge(l)){t.outrec=l.outrec,t.windDx>0?this.setSides(l.outrec,t,l):this.setSides(l.outrec,l,t);return}o=this.startOpenPath(t,e)}else o=this.startOpenPath(t,e);this.setZ(t,n,o.pt);return}this.isJoined(t)&&this.split(t,e),this.isJoined(n)&&this.split(n,e);let s,a;switch(t.localMin.polytype===n.localMin.polytype?this.fillrule===we.EvenOdd?(s=t.windCount,t.windCount=n.windCount,n.windCount=s):(t.windCount+n.windDx===0?t.windCount=-t.windCount:t.windCount+=n.windDx,n.windCount-t.windDx===0?n.windCount=-n.windCount:n.windCount-=t.windDx):(this.fillrule!==we.EvenOdd?t.windCount2+=n.windDx:t.windCount2=t.windCount2===0?1:0,this.fillrule!==we.EvenOdd?n.windCount2-=t.windDx:n.windCount2=n.windCount2===0?1:0),this.fillrule){case we.Positive:s=t.windCount,a=n.windCount;break;case we.Negative:s=-t.windCount,a=-n.windCount;break;default:s=Math.abs(t.windCount),a=Math.abs(n.windCount);break}const r=s===0||s===1,c=a===0||a===1;if(!(!Y.isHotEdge(t)&&!r||!Y.isHotEdge(n)&&!c))if(Y.isHotEdge(t)&&Y.isHotEdge(n))if(s!==0&&s!==1||a!==0&&a!==1||t.localMin.polytype!==n.localMin.polytype&&this.cliptype!==Ce.Xor)o=this.addLocalMaxPoly(t,n,e),o&&this.setZ(t,n,o.pt);else if(Y.isFront(t)||t.outrec===n.outrec){o=this.addLocalMaxPoly(t,n,e),o&&this.setZ(t,n,o.pt);const l=this.addLocalMinPoly(t,n,e);this.setZ(t,n,l.pt)}else{o=this.addOutPt(t,e),this.setZ(t,n,o.pt);const l=this.addOutPt(n,e);this.setZ(t,n,l.pt),this.swapOutrecs(t,n)}else if(Y.isHotEdge(t))o=this.addOutPt(t,e),this.setZ(t,n,o.pt),this.swapOutrecs(t,n);else if(Y.isHotEdge(n))o=this.addOutPt(n,e),this.setZ(t,n,o.pt),this.swapOutrecs(t,n);else{let l,d;switch(this.fillrule){case we.Positive:l=t.windCount2,d=n.windCount2;break;case we.Negative:l=-t.windCount2,d=-n.windCount2;break;default:l=Math.abs(t.windCount2),d=Math.abs(n.windCount2);break}if(!Y.isSamePolyType(t,n))o=this.addLocalMinPoly(t,n,e),this.setZ(t,n,o.pt);else if(s===1&&a===1){switch(o=null,this.cliptype){case Ce.Union:if(l>0&&d>0)return;o=this.addLocalMinPoly(t,n,e);break;case Ce.Difference:(Y.getPolyType(t)===Ze.Clip&&l>0&&d>0||Y.getPolyType(t)===Ze.Subject&&l<=0&&d<=0)&&(o=this.addLocalMinPoly(t,n,e));break;case Ce.Xor:o=this.addLocalMinPoly(t,n,e);break;default:if(l<=0||d<=0)return;o=this.addLocalMinPoly(t,n,e);break}o&&this.setZ(t,n,o.pt)}}}swapPositionsInAEL(t,n){const e=n.nextInAEL;e!==null&&(e.prevInAEL=t);const o=t.prevInAEL;o!==null&&(o.nextInAEL=n),n.prevInAEL=o,n.nextInAEL=t,t.prevInAEL=n,t.nextInAEL=e,n.prevInAEL===null&&(this.actives=n)}isValidAelOrder(t,n){if(n.curX!==t.curX)return n.curX>t.curX;const e=pt.crossProduct(t.top,n.bot,n.top);if(e!==0)return e<0;if(!Y.isMaxima(t)&&t.top.y>n.top.y)return pt.crossProduct(n.bot,t.top,Y.nextVertex(t).pt)<=0;if(!Y.isMaxima(n)&&n.top.y>t.top.y)return pt.crossProduct(n.bot,n.top,Y.nextVertex(n).pt)>=0;const o=n.bot.y,s=n.isLeftBound;return t.bot.y!==o||t.localMin.vertex.pt.y!==o?n.isLeftBound:t.isLeftBound!==s?s:pt.isCollinear(Y.prevPrevVertex(t).pt,t.bot,t.top)?!0:pt.crossProduct(Y.prevPrevVertex(t).pt,n.bot,Y.prevPrevVertex(n).pt)>0===s}isJoined(t){return t.joinWith!==qn.None}split(t,n){t.joinWith===qn.Right?(t.joinWith=qn.None,t.nextInAEL.joinWith=qn.None,this.addLocalMinPoly(t,t.nextInAEL,n,!0)):(t.joinWith=qn.None,t.prevInAEL.joinWith=qn.None,this.addLocalMinPoly(t.prevInAEL,t,n,!0))}setSides(t,n,e){t.frontEdge=n,t.backEdge=e}findEdgeWithMatchingLocMin(t){let n=t.nextInAEL;for(;n!==null;){if(n.localMin?.equals(t.localMin))return n;!Y.isHorizontal(n)&&!(t.bot.x===n.bot.x&&t.bot.y===n.bot.y)?n=null:n=n.nextInAEL}for(n=t.prevInAEL;n!==null;){if(n.localMin?.equals(t.localMin))return n;if(!Y.isHorizontal(n)&&!(t.bot.x===n.bot.x&&t.bot.y===n.bot.y))return null;n=n.prevInAEL}return n}addOutPt(t,n){const e=t.outrec,o=Y.isFront(t),s=e.pts,a=s.next;if(o&&n.x===s.pt.x&&n.y===s.pt.y)return s;if(!o&&n.x===a.pt.x&&n.y===a.pt.y)return a;const r=new Ri(n,e);return a.prev=r,r.prev=s,r.next=a,s.next=r,o&&(e.pts=r),r}addLocalMaxPoly(t,n,e){if(this.isJoined(t)&&this.split(t,e),this.isJoined(n)&&this.split(n,e),Y.isFront(t)===Y.isFront(n))if(Y.isOpenEnd(t))this.swapFrontBackSides(t.outrec);else if(Y.isOpenEnd(n))this.swapFrontBackSides(n.outrec);else return this.succeeded=!1,null;const o=this.addOutPt(t,e);if(t.outrec===n.outrec){const s=t.outrec;if(s.pts=o,this.usingPolytree){const a=Y.getPrevHotEdge(t);a===null?s.owner=null:this.setOwner(s,a.outrec)}this.uncoupleOutRec(t)}else Y.isOpen(t)?t.windDx<0?this.joinOutrecPaths(t,n):this.joinOutrecPaths(n,t):t.outrec.idx<n.outrec.idx?this.joinOutrecPaths(t,n):this.joinOutrecPaths(n,t);return o}swapFrontBackSides(t){const n=t.frontEdge;t.frontEdge=t.backEdge,t.backEdge=n,t.pts=t.pts.next}setOwner(t,n){for(;n.owner!==null&&n.owner.pts===null;)n.owner=n.owner.owner;let e=n;for(;e!==null&&e!==t;)e=e.owner;e!==null&&(n.owner=t.owner),t.owner=n}uncoupleOutRec(t){const n=t.outrec;n!==null&&(n.frontEdge.outrec=null,n.backEdge.outrec=null,n.frontEdge=null,n.backEdge=null)}joinOutrecPaths(t,n){const e=t.outrec.pts,o=n.outrec.pts,s=e.next,a=o.next;Y.isFront(t)?(a.prev=e,e.next=a,o.next=s,s.prev=o,t.outrec.pts=o,t.outrec.frontEdge=n.outrec.frontEdge,t.outrec.frontEdge!==null&&(t.outrec.frontEdge.outrec=t.outrec)):(s.prev=o,o.next=s,e.next=a,a.prev=e,t.outrec.backEdge=n.outrec.backEdge,t.outrec.backEdge!==null&&(t.outrec.backEdge.outrec=t.outrec)),n.outrec.frontEdge=null,n.outrec.backEdge=null,n.outrec.pts=null,this.setOwner(n.outrec,t.outrec),Y.isOpenEnd(t)&&(n.outrec.pts=t.outrec.pts,t.outrec.pts=null),t.outrec=null,n.outrec=null}swapOutrecs(t,n){const e=t.outrec,o=n.outrec;if(e===o){const s=e.frontEdge;e.frontEdge=e.backEdge,e.backEdge=s;return}e!==null&&(t===e.frontEdge?e.frontEdge=n:e.backEdge=n),o!==null&&(n===o.frontEdge?o.frontEdge=t:o.backEdge=t),t.outrec=o,n.outrec=e}disposeIntersectNodes(){this.intersectList.length=0}static ptsReallyClose(t,n){return Math.abs(t.x-n.x)<2&&Math.abs(t.y-n.y)<2}static isVerySmallTriangle(t){return t.next.next===t.prev&&(Y.ptsReallyClose(t.prev.pt,t.next.pt)||Y.ptsReallyClose(t.pt,t.next.pt)||Y.ptsReallyClose(t.pt,t.prev.pt))}static buildPath(t,n,e,o){if(t===null||t.next===t||!e&&t.next===t.prev)return!1;o.length=0;let s,a;for(n?(s=t.pt,a=t.prev):(t=t.next,s=t.pt,a=t.next),o.push(s);a!==t;)a.pt.x===s.x&&a.pt.y===s.y||(s=a.pt,o.push(s)),n?a=a.prev:a=a.next;return o.length!==3||e||!Y.isVerySmallTriangle(a)}buildPaths(t,n){t.length=0,n.length=0;let e=0;for(;e<this.outrecList.length;){const o=this.outrecList[e++];if(o.pts===null)continue;const s=[];o.isOpen?Y.buildPath(o.pts,this.reverseSolution,!0,s)&&n.push(s):(this.cleanCollinear(o),Y.buildPath(o.pts,this.reverseSolution,!1,s)&&t.push(s))}return!0}buildTree(t,n){t.clear(),n.length=0;let e=0;for(;e<this.outrecList.length;){const o=this.outrecList[e++];if(o.pts!==null){if(o.isOpen){const s=[];Y.buildPath(o.pts,this.reverseSolution,!0,s)&&n.push(s);continue}this.checkBounds(o)&&this.recursiveCheckOwners(o,t)}}}checkBounds(t){return t.pts===null?!1:In.isEmpty(t.bounds)?(this.cleanCollinear(t),t.pts===null||!Y.buildPath(t.pts,this.reverseSolution,!1,t.path)?!1:(t.bounds=pt.getBounds(t.path),!0)):!0}recursiveCheckOwners(t,n){if(!(t.polypath!==null||In.isEmpty(t.bounds))){for(;t.owner!==null&&!(t.owner.splits!==null&&this.checkSplitOwner(t,t.owner.splits)||t.owner.pts!==null&&this.checkBounds(t.owner)&&this.containsRect(t.owner.bounds,t.bounds)&&this.path1InsidePath2(t.pts,t.owner.pts));)t.owner=t.owner.owner;t.owner!==null?(t.owner.polypath===null&&this.recursiveCheckOwners(t.owner,n),t.polypath=t.owner.polypath.addChild(t.path)):t.polypath=n.addChild(t.path)}}cleanCollinear(t){if(t=this.getRealOutRec(t),t===null||t.isOpen)return;if(!this.isValidClosedPath(t.pts)){t.pts=null;return}let n=t.pts,e=n;for(;;){if(e!==null&&pt.isCollinear(e.prev.pt,e.pt,e.next.pt)&&(e.pt.x===e.prev.pt.x&&e.pt.y===e.prev.pt.y||e.pt.x===e.next.pt.x&&e.pt.y===e.next.pt.y||!this.preserveCollinear||pt.dotProduct(e.prev.pt,e.pt,e.next.pt)<0)){if(e===t.pts&&(t.pts=e.prev),e=this.disposeOutPt(e),!this.isValidClosedPath(e)){t.pts=null;return}n=e;continue}if(e===null||(e=e.next,e===n))break}this.fixSelfIntersects(t)}isValidClosedPath(t){return t!==null&&t.next!==t&&(t.next!==t.prev||!Y.isVerySmallTriangle(t))}disposeOutPt(t){const n=t.next===t?null:t.next;return t.prev.next=t.next,t.next.prev=t.prev,n}fixSelfIntersects(t){let n=t.pts;if(n.prev!==n.next.next)for(;;){if(n.next&&n.next.next&&this.boundingBoxesOverlap(n.prev.pt,n.pt,n.next.pt,n.next.next.pt)&&pt.segsIntersect(n.prev.pt,n.pt,n.next.pt,n.next.next.pt))if(n.next.next.next&&this.boundingBoxesOverlap(n.prev.pt,n.pt,n.next.next.pt,n.next.next.next.pt)&&pt.segsIntersect(n.prev.pt,n.pt,n.next.next.pt,n.next.next.next.pt))n=this.duplicateOp(n,!1),n.pt=n.next.next.next.pt,n=n.next;else{if((n===t.pts||n.next===t.pts)&&(t.pts=t.pts.prev),this.doSplitOp(t,n),t.pts===null)return;if(n=t.pts,n.prev===n.next.next)break;continue}if(n=n.next,n===t.pts)break}}doSplitOp(t,n){const e=n.prev,o=n.next.next;t.pts=e;const a=pt.getLineIntersectPt(e.pt,n.pt,n.next.pt,o.pt).point,r=Y.areaOutPt(e),c=Math.abs(r);if(c<2){t.pts=null;return}const l=this.areaTriangle(a,n.pt,n.next.pt),d=Math.abs(l);if(a.x===e.pt.x&&a.y===e.pt.y||a.x===o.pt.x&&a.y===o.pt.y)o.prev=e,e.next=o;else{const f=new Ri(a,t);f.prev=e,f.next=o,o.prev=f,e.next=f}if(!(d>1)||!(d>c)&&l>0!=r>0)return;const u=this.newOutRec();u.owner=t.owner,n.outrec=u,n.next.outrec=u;const h=new Ri(a,u);h.prev=n.next,h.next=n,u.pts=h,n.prev=h,n.next.next=h,this.usingPolytree&&(this.path1InsidePath2(e,h)?(u.splits===null&&(u.splits=[]),u.splits.push(t.idx)):(t.splits===null&&(t.splits=[]),t.splits.push(u.idx)))}static areaOutPt(t){let n=0,e=t;do n+=(e.prev.pt.y+e.pt.y)*(e.prev.pt.x-e.pt.x),e=e.next;while(e!==t);return n*.5}areaTriangle(t,n,e){return(e.y+t.y)*(e.x-t.x)+(t.y+n.y)*(t.x-n.x)+(n.y+e.y)*(n.x-e.x)}isValidOwner(t,n){for(;n!==null&&n!==t;)n=n.owner;return n===null}containsRect(t,n){return n.left>=t.left&&n.right<=t.right&&n.top>=t.top&&n.bottom<=t.bottom}checkSplitOwner(t,n){for(let e=0;e<n.length;e++){let o=this.outrecList[n[e]];if(o.pts===null&&o.splits!==null&&this.checkSplitOwner(t,o.splits))return!0;if(o=this.getRealOutRec(o),!(o===null||o===t||o.recursiveSplit===t)){if(o.recursiveSplit=t,o.splits!==null&&this.checkSplitOwner(t,o.splits))return!0;if(!(!this.checkBounds(o)||!this.containsRect(o.bounds,t.bounds)||!this.path1InsidePath2(t.pts,o.pts)))return this.isValidOwner(t,o)||(o.owner=t.owner),t.owner=o,!0}}return!1}}class hl extends Y{zCallback;getZCallback(){return this.zCallback}addPath(t,n,e=!1){super.addPath(t,n,e)}addReuseableData(t){super.addReuseableData(t)}addPaths(t,n,e=!1){super.addPaths(t,n,e)}addSubject(t){this.addPaths(t,Ze.Subject)}addOpenSubject(t){this.addPaths(t,Ze.Subject,!0)}addClip(t){this.addPaths(t,Ze.Clip)}execute(t,n,e,o){if(Array.isArray(e)){const s=e,a=o;s.length=0,a&&(a.length=0);try{this.executeInternal(t,n),this.buildPaths(s,a||[])}catch{this.succeeded=!1}return this.clearSolutionOnly(),this.succeeded}else{const s=e,a=o;s.clear(),a&&(a.length=0),this.usingPolytree=!0;try{this.executeInternal(t,n),this.buildTree(s,a||[])}catch{this.succeeded=!1}return this.clearSolutionOnly(),this.succeeded}}}class wm extends Y{zCallback;scale;invScale;constructor(t=2){super(),pt.checkPrecision(t),this.scale=Math.pow(10,t),this.invScale=1/this.scale}getZCallback(){return this.zCallback}scalePathDFromInt(t,n){const e=[];for(const o of t)e.push({x:o.x*n,y:o.y*n,z:o.z||0});return e}buildPathsD(t,n){t.length=0,n.length=0;let e=0;for(;e<this.outrecList.length;){const o=this.outrecList[e++];if(o.pts===null)continue;const s=[];o.isOpen?Y.buildPath(o.pts,this.reverseSolution,!0,s)&&n.push(this.scalePathDFromInt(s,this.invScale)):(this.cleanCollinear(o),Y.buildPath(o.pts,this.reverseSolution,!1,s)&&t.push(this.scalePathDFromInt(s,this.invScale)))}return!0}buildTreeD(t,n){t.clear(),n.length=0;let e=0;for(;e<this.outrecList.length;){const o=this.outrecList[e++];if(o.pts!==null){if(o.isOpen){const s=[];Y.buildPath(o.pts,this.reverseSolution,!0,s)&&n.push(this.scalePathDFromInt(s,this.invScale));continue}this.checkBounds(o)&&this.recursiveCheckOwners(o,t)}}}addPath(t,n,e=!1){super.addPath(pa.scalePath64(t,this.scale),n,e)}addPaths(t,n,e=!1){super.addPaths(pa.scalePaths64(t,this.scale),n,e)}addSubject(t){this.addPath(t,Ze.Subject)}addOpenSubject(t){this.addPath(t,Ze.Subject,!0)}addClip(t){this.addPath(t,Ze.Clip)}addSubjectPaths(t){this.addPaths(t,Ze.Subject)}addOpenSubjectPaths(t){this.addPaths(t,Ze.Subject,!0)}addClipPaths(t){this.addPaths(t,Ze.Clip)}execute(t,n,e,o){if(Array.isArray(e)){const s=e,a=o,r=[],c=[];s.length=0,a&&(a.length=0);let l=!0;try{this.executeInternal(t,n),this.buildPaths(r,c)}catch{l=!1}if(this.clearSolutionOnly(),!l)return!1;for(const d of r)s.push(this.scalePathDFromInt(d,this.invScale));if(a)for(const d of c)a.push(this.scalePathDFromInt(d,this.invScale));return!0}else{const s=e,a=o;s.clear(),a&&(a.length=0),this.usingPolytree=!0,s.scale=this.scale;let r=!0;try{this.executeInternal(t,n),this.buildTreeD(s,a||[])}catch{r=!1}return this.clearSolutionOnly(),r}}}var pa;(function(i){function t(r){let c=0;const l=r.length;if(l<3)return 0;let d=r[l-1];for(const u of r)c+=(d.y+u.y)*(d.x-u.x),d=u;return c*.5}i.area=t;function n(r){let c=0;const l=r.length;if(l<3)return 0;let d=r[l-1];for(const u of r)c+=(d.y+u.y)*(d.x-u.x),d=u;return c*.5}i.areaD=n;function e(r,c){const l=[];for(const d of r)l.push({x:Math.round(d.x*c),y:Math.round(d.y*c)});return l}i.scalePath64=e;function o(r,c){const l=[];for(const d of r)l.push(e(d,c));return l}i.scalePaths64=o;function s(r,c){const l=[];for(const d of r)l.push({x:d.x*c,y:d.y*c});return l}i.scalePathD=s;function a(r,c){const l=[];for(const d of r)l.push(s(d,c));return l}i.scalePathsD=a})(pa||(pa={}));var ri;(function(i){i[i.Miter=0]="Miter",i[i.Square=1]="Square",i[i.Bevel=2]="Bevel",i[i.Round=3]="Round"})(ri||(ri={}));var on;(function(i){i[i.Polygon=0]="Polygon",i[i.Joined=1]="Joined",i[i.Butt=2]="Butt",i[i.Square=3]="Square",i[i.Round=4]="Round"})(on||(on={}));class PP{inPaths;joinType;endType;pathsReversed;lowestPathIdx;constructor(t,n,e=on.Polygon){this.joinType=n,this.endType=e;const o=e===on.Polygon||e===on.Joined;this.inPaths=[];for(const s of t)this.inPaths.push(Fe.stripDuplicates(s,o));if(e===on.Polygon){const s=Fe.getLowestPathInfo(this.inPaths);this.lowestPathIdx=s.idx,this.pathsReversed=this.lowestPathIdx>=0&&s.isNegArea}else this.lowestPathIdx=-1,this.pathsReversed=!1}}class Fe{static Tolerance=1e-12;static arc_const=.002;groupList=[];pathOut=[];normals=[];solution=[];solutionTree=null;groupDelta=0;delta=0;mitLimSqr=0;stepsPerRad=0;stepSin=0;stepCos=0;joinType=ri.Bevel;endType=on.Polygon;arcTolerance=0;mergeGroups=!0;miterLimit=2;preserveCollinear=!1;reverseSolution=!1;zCallback;deltaCallback=null;constructor(t=2,n=0,e=!1,o=!1){this.miterLimit=t,this.arcTolerance=n,this.mergeGroups=!0,this.preserveCollinear=e,this.reverseSolution=o}clear(){this.groupList.length=0}ZCB=(t,n,e,o,s)=>{(t.z||0)!==0&&(t.z===e.z||t.z===o.z)?s.z=t.z:(e.z||0)!==0&&e.z===n.z?s.z=e.z:(n.z||0)!==0&&n.z===o.z?s.z=n.z:this.zCallback&&this.zCallback(t,n,e,o,s)};addPath(t,n,e){if(t.length===0)return;const o=[t];this.addPaths(o,n,e)}addPaths(t,n,e){t.length!==0&&this.groupList.push(new PP(t,n,e))}calcSolutionCapacity(){let t=0;for(const n of this.groupList)t+=n.endType===on.Joined?n.inPaths.length*2:n.inPaths.length;return t}checkPathsReversed(){let t=!1;for(const n of this.groupList)if(n.endType===on.Polygon){t=n.pathsReversed;break}return t}executeInternal(t){if(this.groupList.length===0)return;if(Math.abs(t)<.5){for(const s of this.groupList)for(const a of s.inPaths)this.solution.push(a);return}this.delta=t,this.mitLimSqr=this.miterLimit<=1?2:2/Fe.sqr(this.miterLimit);for(const s of this.groupList)this.doGroupOffset(s);if(this.groupList.length===0)return;const n=this.checkPathsReversed(),e=n?we.Negative:we.Positive,o=new hl;o.preserveCollinear=this.preserveCollinear,o.reverseSolution=this.reverseSolution!==n,o.zCallback=this.ZCB,o.addSubject(this.solution),this.solutionTree!==null?o.execute(Ce.Union,e,this.solutionTree):o.execute(Ce.Union,e,this.solution)}execute(t,n){if(Array.isArray(n)){const e=n;e.length=0,this.solution=e,this.executeInternal(t)}else{const e=n;e.clear(),this.solutionTree=e,this.solution=[],this.executeInternal(t)}}executeWithCallback(t,n){this.deltaCallback=t,this.execute(1,n)}static getUnitNormal(t,n){const e=n.x-t.x,o=n.y-t.y;if(e===0&&o===0)return{x:0,y:0};const s=1/Math.sqrt(e*e+o*o);return{x:o*s,y:-e*s}}static getLowestPathInfo(t){let n=-1,e=!1,o={x:Number.MAX_SAFE_INTEGER,y:Number.MIN_SAFE_INTEGER};for(let s=0;s<t.length;++s){let a=Number.MAX_VALUE;for(const r of t[s])if(!(r.y<o.y||r.y===o.y&&r.x>=o.x)){if(a===Number.MAX_VALUE){if(a=Fe.area(t[s]),a===0)break;e=a<0}n=s,o.x=r.x,o.y=r.y}}return{idx:n,isNegArea:e}}static translatePoint(t,n,e){return{x:t.x+n,y:t.y+e}}static reflectPoint(t,n){return{x:n.x+(n.x-t.x),y:n.y+(n.y-t.y)}}static almostZero(t,n=.001){return Math.abs(t)<n}static hypotenuse(t,n){return Math.sqrt(Math.pow(t,2)+Math.pow(n,2))}static normalizeVector(t){const n=Fe.hypotenuse(t.x,t.y);if(Fe.almostZero(n))return{x:0,y:0};const e=1/n;return{x:t.x*e,y:t.y*e}}static getAvgUnitVector(t,n){return Fe.normalizeVector({x:t.x+n.x,y:t.y+n.y})}static intersectPoint(t,n,e,o){if(pt.isAlmostZero(t.x-n.x)){if(pt.isAlmostZero(e.x-o.x))return{x:0,y:0};const s=(o.y-e.y)/(o.x-e.x),a=e.y-s*e.x;return{x:t.x,y:s*t.x+a}}if(pt.isAlmostZero(e.x-o.x)){const s=(n.y-t.y)/(n.x-t.x),a=t.y-s*t.x;return{x:e.x,y:s*e.x+a}}else{const s=(n.y-t.y)/(n.x-t.x),a=t.y-s*t.x,r=(o.y-e.y)/(o.x-e.x),c=e.y-r*e.x;if(pt.isAlmostZero(s-r))return{x:0,y:0};const l=(c-a)/(s-r);return{x:l,y:s*l+a}}}getPerpendic(t,n){return{x:Math.round(t.x+n.x*this.groupDelta),y:Math.round(t.y+n.y*this.groupDelta)}}getPerpendicD(t,n){return{x:t.x+n.x*this.groupDelta,y:t.y+n.y*this.groupDelta}}doBevel(t,n,e){let o,s;if(n===e){const a=Math.abs(this.groupDelta);o={x:Math.round(t[n].x-a*this.normals[n].x),y:Math.round(t[n].y-a*this.normals[n].y)},s={x:Math.round(t[n].x+a*this.normals[n].x),y:Math.round(t[n].y+a*this.normals[n].y)}}else o={x:Math.round(t[n].x+this.groupDelta*this.normals[e].x),y:Math.round(t[n].y+this.groupDelta*this.normals[e].y)},s={x:Math.round(t[n].x+this.groupDelta*this.normals[n].x),y:Math.round(t[n].y+this.groupDelta*this.normals[n].y)};this.pathOut.push(o),this.pathOut.push(s)}doSquare(t,n,e){let o;n===e?o={x:this.normals[n].y,y:-this.normals[n].x}:o=Fe.getAvgUnitVector({x:-this.normals[e].y,y:this.normals[e].x},{x:this.normals[n].y,y:-this.normals[n].x});const s=Math.abs(this.groupDelta);let a={x:t[n].x,y:t[n].y};a=Fe.translatePoint(a,s*o.x,s*o.y);const r=Fe.translatePoint(a,this.groupDelta*o.y,this.groupDelta*-o.x),c=Fe.translatePoint(a,this.groupDelta*-o.y,this.groupDelta*o.x),l=this.getPerpendicD(t[e],this.normals[e]);if(n===e){const d={x:l.x+o.x*this.groupDelta,y:l.y+o.y*this.groupDelta},u=Fe.intersectPoint(r,c,l,d);this.pathOut.push(ye.fromPointD(Fe.reflectPoint(u,a))),this.pathOut.push(ye.fromPointD(u))}else{const d=this.getPerpendicD(t[n],this.normals[e]),u=Fe.intersectPoint(r,c,l,d);this.pathOut.push(ye.fromPointD(u)),this.pathOut.push(ye.fromPointD(Fe.reflectPoint(u,a)))}}doMiter(t,n,e,o){const s=this.groupDelta/(o+1);this.pathOut.push({x:Math.round(t[n].x+(this.normals[e].x+this.normals[n].x)*s),y:Math.round(t[n].y+(this.normals[e].y+this.normals[n].y)*s)})}doRound(t,n,e,o){if(this.deltaCallback!==null){const c=Math.abs(this.groupDelta),l=this.arcTolerance>.01?this.arcTolerance:c*Fe.arc_const,d=Math.PI/Math.acos(1-l/c);this.stepSin=Math.sin(2*Math.PI/d),this.stepCos=Math.cos(2*Math.PI/d),this.groupDelta<0&&(this.stepSin=-this.stepSin),this.stepsPerRad=d/(2*Math.PI)}const s=t[n];let a={x:this.normals[e].x*this.groupDelta,y:this.normals[e].y*this.groupDelta};n===e&&hi.negate(a),this.pathOut.push({x:Math.round(s.x+a.x),y:Math.round(s.y+a.y)});const r=Math.ceil(this.stepsPerRad*Math.abs(o));for(let c=1;c<r;c++)a={x:a.x*this.stepCos-this.stepSin*a.y,y:a.x*this.stepSin+a.y*this.stepCos},this.pathOut.push({x:Math.round(s.x+a.x),y:Math.round(s.y+a.y)});this.pathOut.push(this.getPerpendic(t[n],this.normals[n]))}buildNormals(t){const n=t.length;if(this.normals.length=0,n!==0){for(let e=0;e<n-1;e++)this.normals.push(Fe.getUnitNormal(t[e],t[e+1]));this.normals.push(Fe.getUnitNormal(t[n-1],t[0]))}}offsetPoint(t,n,e,o){if(ye.equals(n[e],n[o]))return;let s=pt.crossProductD(this.normals[e],this.normals[o]);const a=pt.dotProductD(this.normals[e],this.normals[o]);if(s>1?s=1:s<-1&&(s=-1),this.deltaCallback!==null&&(this.groupDelta=this.deltaCallback(n,this.normals,e,o),t.pathsReversed&&(this.groupDelta=-this.groupDelta)),Math.abs(this.groupDelta)<Fe.Tolerance){this.pathOut.push(n[e]);return}if(a>-.999&&s*this.groupDelta<0)this.pathOut.push(this.getPerpendic(n[e],this.normals[o])),this.pathOut.push(n[e]),this.pathOut.push(this.getPerpendic(n[e],this.normals[e]));else if(a>.999&&this.joinType!==ri.Round)this.doMiter(n,e,o,a);else switch(this.joinType){case ri.Miter:a>this.mitLimSqr-1?this.doMiter(n,e,o,a):this.doSquare(n,e,o);break;case ri.Round:this.doRound(n,e,o,Math.atan2(s,a));break;case ri.Bevel:this.doBevel(n,e,o);break;default:this.doSquare(n,e,o);break}}offsetPolygon(t,n){this.pathOut=[];const e=n.length;let o=e-1;for(let s=0;s<e;s++)this.offsetPoint(t,n,s,o),o=s;this.solution.push([...this.pathOut])}offsetOpenJoined(t,n){this.offsetPolygon(t,n);const e=[...n].reverse();this.buildNormals(e),this.offsetPolygon(t,e)}offsetOpenPath(t,n){this.pathOut=[];const e=n.length-1;if(this.deltaCallback!==null&&(this.groupDelta=this.deltaCallback(n,this.normals,0,0)),Math.abs(this.groupDelta)<Fe.Tolerance)this.pathOut.push(n[0]);else switch(this.endType){case on.Butt:this.doBevel(n,0,0);break;case on.Round:this.doRound(n,0,0,Math.PI);break;default:this.doSquare(n,0,0);break}for(let o=1,s=0;o<e;o++)this.offsetPoint(t,n,o,s),s=o;for(let o=e;o>0;o--)this.normals[o]={x:-this.normals[o-1].x,y:-this.normals[o-1].y};if(this.normals[0]=this.normals[e],this.deltaCallback!==null&&(this.groupDelta=this.deltaCallback(n,this.normals,e,e)),Math.abs(this.groupDelta)<Fe.Tolerance)this.pathOut.push(n[e]);else switch(this.endType){case on.Butt:this.doBevel(n,e,e);break;case on.Round:this.doRound(n,e,e,Math.PI);break;default:this.doSquare(n,e,e);break}for(let o=e-1,s=e;o>0;o--)this.offsetPoint(t,n,o,s),s=o;this.solution.push([...this.pathOut])}doGroupOffset(t){t.endType===on.Polygon?(t.lowestPathIdx<0&&(this.delta=Math.abs(this.delta)),this.groupDelta=t.pathsReversed?-this.delta:this.delta):this.groupDelta=Math.abs(this.delta);const n=Math.abs(this.groupDelta);if(this.joinType=t.joinType,this.endType=t.endType,t.joinType===ri.Round||t.endType===on.Round){const e=this.arcTolerance>.01?this.arcTolerance:n*Fe.arc_const,o=Math.PI/Math.acos(1-e/n);this.stepSin=Math.sin(2*Math.PI/o),this.stepCos=Math.cos(2*Math.PI/o),this.groupDelta<0&&(this.stepSin=-this.stepSin),this.stepsPerRad=o/(2*Math.PI)}for(const e of t.inPaths){this.pathOut=[];const o=e.length;if(o===1){const s=e[0];if(this.deltaCallback!==null&&(this.groupDelta=this.deltaCallback(e,this.normals,0,0),t.pathsReversed&&(this.groupDelta=-this.groupDelta)),t.endType===on.Round){const a=Math.ceil(this.stepsPerRad*2*Math.PI);this.pathOut=Fe.ellipse(s,Math.abs(this.groupDelta),Math.abs(this.groupDelta),a)}else{const a=Math.ceil(Math.abs(this.groupDelta)),r={left:s.x-a,top:s.y-a,right:s.x+a,bottom:s.y+a};this.pathOut=[{x:r.left,y:r.top},{x:r.right,y:r.top},{x:r.right,y:r.bottom},{x:r.left,y:r.bottom}]}this.solution.push([...this.pathOut]);continue}switch(o===2&&t.endType===on.Joined&&(this.endType=t.joinType===ri.Round?on.Round:on.Square),this.buildNormals(e),this.endType){case on.Polygon:this.offsetPolygon(t,e);break;case on.Joined:this.offsetOpenJoined(t,e);break;default:this.offsetOpenPath(t,e);break}}}static stripDuplicates(t,n){const e=t.length,o=[];if(e===0)return o;let s=t[0];o.push(s);for(let a=1;a<e;a++)ye.equals(s,t[a])||(s=t[a],o.push(s));return n&&ye.equals(s,o[0])&&o.pop(),o}static area(t){let n=0;const e=t.length;if(e<3)return 0;let o=t[e-1];for(const s of t)n+=(o.y+s.y)*(o.x-s.x),o=s;return n*.5}static sqr(t){return t*t}static ellipse(t,n,e=0,o=0){if(n<=0)return[];e<=0&&(e=n),o<=2&&(o=Math.ceil(Math.PI*Math.sqrt((n+e)/2)));const s=Math.sin(2*Math.PI/o),a=Math.cos(2*Math.PI/o);let r=a,c=s;const l=[{x:Math.round(t.x+n),y:t.y}];for(let d=1;d<o;++d){l.push({x:Math.round(t.x+n*r),y:Math.round(t.y+e*c)});const u=r*a-c*s;c=c*a+r*s,r=u}return l}}class Em{next=null;prev=null;pt;ownerIdx=0;edge=null;constructor(t){this.pt=t}}var Et;(function(i){i[i.left=0]="left",i[i.top=1]="top",i[i.right=2]="right",i[i.bottom=3]="bottom",i[i.inside=4]="inside"})(Et||(Et={}));class At{rect;mp;rectPath;pathBounds={left:0,top:0,right:0,bottom:0};results=[];edges=[];currIdx=-1;constructor(t){this.currIdx=-1,this.rect=t,this.mp=In.midPoint(t),this.rectPath=In.asPath(this.rect),this.results=[],this.edges=[];for(let n=0;n<8;n++)this.edges[n]=[]}add(t,n=!1){let e=this.results.length,o;if(e===0||n)o=new Em(t),this.results.push(o),o.ownerIdx=e,o.prev=o,o.next=o;else{e--;const s=this.results[e];if(s&&ye.equals(s.pt,t))return s;o=new Em(t),o.ownerIdx=e,o.next=s.next,s.next.prev=o,s.next=o,o.prev=s,this.results[e]=o}return o}static path1ContainsPath2(t,n){let e=0;for(const o of n){switch(pt.pointInPolygon(o,t)){case ge.IsInside:e--;break;case ge.IsOutside:e++;break}if(Math.abs(e)>1)break}return e<=0}static isClockwise(t,n,e,o,s){return At.areOpposites(t,n)?pt.crossProduct(e,s,o)<0:At.headingClockwise(t,n)}static areOpposites(t,n){return Math.abs(t-n)===2}static headingClockwise(t,n){return(t+1)%4===n}static getAdjacentLocation(t,n){return(t+(n?1:3))%4}static unlinkOp(t){return t.next===t?null:(t.prev.next=t.next,t.next.prev=t.prev,t.next)}static unlinkOpBack(t){return t.next===t?null:(t.prev.next=t.next,t.next.prev=t.prev,t.prev)}static getEdgesForPt(t,n){let e=0;return t.x===n.left?e=1:t.x===n.right&&(e=4),t.y===n.top?e+=2:t.y===n.bottom&&(e+=8),e}static isHeadingClockwise(t,n,e){switch(e){case 0:return n.y<t.y;case 1:return n.x>t.x;case 2:return n.y>t.y;default:return n.x<t.x}}static hasHorzOverlap(t,n,e,o){return t.x<o.x&&n.x>e.x}static hasVertOverlap(t,n,e,o){return t.y<o.y&&n.y>e.y}static addToEdge(t,n){n.edge===null&&(n.edge=t,t.push(n))}static uncoupleEdge(t){if(t.edge!==null){for(let n=0;n<t.edge.length;n++)if(t.edge[n]===t){t.edge[n]=null;break}t.edge=null}}static setNewOwner(t,n){t.ownerIdx=n;let e=t.next;for(;e!==t;)e.ownerIdx=n,e=e.next}addCorner(t,n){this.add(At.headingClockwise(t,n)?this.rectPath[t]:this.rectPath[n])}addCornerWithDirection(t,n){if(n)return this.add(this.rectPath[t]),At.getAdjacentLocation(t,!0);{const e=At.getAdjacentLocation(t,!1);return this.add(this.rectPath[e]),e}}static getLocation(t,n){if(n.x===t.left&&n.y>=t.top&&n.y<=t.bottom)return{location:Et.left,isOnRect:!0};if(n.x===t.right&&n.y>=t.top&&n.y<=t.bottom)return{location:Et.right,isOnRect:!0};if(n.y===t.top&&n.x>=t.left&&n.x<=t.right)return{location:Et.top,isOnRect:!0};if(n.y===t.bottom&&n.x>=t.left&&n.x<=t.right)return{location:Et.bottom,isOnRect:!0};let e;return n.x<t.left?e=Et.left:n.x>t.right?e=Et.right:n.y<t.top?e=Et.top:n.y>t.bottom?e=Et.bottom:e=Et.inside,{location:e,isOnRect:!1}}static isHorizontal(t,n){return t.y===n.y}static getSegmentIntersection(t,n,e,o){const s=pt.crossProduct(t,e,o),a=pt.crossProduct(n,e,o);if(s===0){const l=t;return a===0?{intersects:!1,point:l}:ye.equals(t,e)||ye.equals(t,o)?{intersects:!0,point:l}:At.isHorizontal(e,o)?{intersects:t.x>e.x==t.x<o.x,point:l}:{intersects:t.y>e.y==t.y<o.y,point:l}}if(a===0){const l=n;return ye.equals(n,e)||ye.equals(n,o)?{intersects:!0,point:l}:At.isHorizontal(e,o)?{intersects:n.x>e.x==n.x<o.x,point:l}:{intersects:n.y>e.y==n.y<o.y,point:l}}if(s>0==a>0)return{intersects:!1,point:{x:0,y:0}};const r=pt.crossProduct(e,t,n),c=pt.crossProduct(o,t,n);if(r===0){const l=e;return ye.equals(e,t)||ye.equals(e,n)?{intersects:!0,point:l}:At.isHorizontal(t,n)?{intersects:e.x>t.x==e.x<n.x,point:l}:{intersects:e.y>t.y==e.y<n.y,point:l}}if(c===0){const l=o;return ye.equals(o,t)||ye.equals(o,n)?{intersects:!0,point:l}:At.isHorizontal(t,n)?{intersects:o.x>t.x==o.x<n.x,point:l}:{intersects:o.y>t.y==o.y<n.y,point:l}}return r>0==c>0?{intersects:!1,point:{x:0,y:0}}:pt.getLineIntersectPt(t,n,e,o)}static getIntersection(t,n,e,o){let s={x:0,y:0},a=o;switch(o){case Et.left:{const r=At.getSegmentIntersection(n,e,t[0],t[3]);if(r.intersects)return s=r.point,{intersects:!0,point:s,newLocation:a};if(n.y<t[0].y){const l=At.getSegmentIntersection(n,e,t[0],t[1]);if(l.intersects)return a=Et.top,{intersects:!0,point:l.point,newLocation:a}}const c=At.getSegmentIntersection(n,e,t[2],t[3]);return c.intersects?(a=Et.bottom,{intersects:!0,point:c.point,newLocation:a}):{intersects:!1,point:s,newLocation:a}}case Et.right:{const r=At.getSegmentIntersection(n,e,t[1],t[2]);if(r.intersects)return{intersects:!0,point:r.point,newLocation:a};if(n.y<t[0].y){const l=At.getSegmentIntersection(n,e,t[0],t[1]);if(l.intersects)return a=Et.top,{intersects:!0,point:l.point,newLocation:a}}const c=At.getSegmentIntersection(n,e,t[2],t[3]);return c.intersects?(a=Et.bottom,{intersects:!0,point:c.point,newLocation:a}):{intersects:!1,point:s,newLocation:a}}case Et.top:{const r=At.getSegmentIntersection(n,e,t[0],t[1]);if(r.intersects)return{intersects:!0,point:r.point,newLocation:a};if(n.x<t[0].x){const l=At.getSegmentIntersection(n,e,t[0],t[3]);if(l.intersects)return a=Et.left,{intersects:!0,point:l.point,newLocation:a}}if(n.x<=t[1].x)return{intersects:!1,point:s,newLocation:a};const c=At.getSegmentIntersection(n,e,t[1],t[2]);return c.intersects?(a=Et.right,{intersects:!0,point:c.point,newLocation:a}):{intersects:!1,point:s,newLocation:a}}case Et.bottom:{const r=At.getSegmentIntersection(n,e,t[2],t[3]);if(r.intersects)return{intersects:!0,point:r.point,newLocation:a};if(n.x<t[3].x){const l=At.getSegmentIntersection(n,e,t[0],t[3]);if(l.intersects)return a=Et.left,{intersects:!0,point:l.point,newLocation:a}}if(n.x<=t[2].x)return{intersects:!1,point:s,newLocation:a};const c=At.getSegmentIntersection(n,e,t[1],t[2]);return c.intersects?(a=Et.right,{intersects:!0,point:c.point,newLocation:a}):{intersects:!1,point:s,newLocation:a}}default:{const r=At.getSegmentIntersection(n,e,t[0],t[3]);if(r.intersects)return a=Et.left,{intersects:!0,point:r.point,newLocation:a};const c=At.getSegmentIntersection(n,e,t[0],t[1]);if(c.intersects)return a=Et.top,{intersects:!0,point:c.point,newLocation:a};const l=At.getSegmentIntersection(n,e,t[1],t[2]);if(l.intersects)return a=Et.right,{intersects:!0,point:l.point,newLocation:a};const d=At.getSegmentIntersection(n,e,t[2],t[3]);return d.intersects?(a=Et.bottom,{intersects:!0,point:d.point,newLocation:a}):{intersects:!1,point:s,newLocation:a}}}}getNextLocation(t,n,e,o){let s=e,a=n;switch(n){case Et.left:for(;s<=o&&t[s].x<=this.rect.left;)s++;if(s>o)break;t[s].x>=this.rect.right?a=Et.right:t[s].y<=this.rect.top?a=Et.top:t[s].y>=this.rect.bottom?a=Et.bottom:a=Et.inside;break;case Et.top:for(;s<=o&&t[s].y<=this.rect.top;)s++;if(s>o)break;t[s].y>=this.rect.bottom?a=Et.bottom:t[s].x<=this.rect.left?a=Et.left:t[s].x>=this.rect.right?a=Et.right:a=Et.inside;break;case Et.right:for(;s<=o&&t[s].x>=this.rect.right;)s++;if(s>o)break;t[s].x<=this.rect.left?a=Et.left:t[s].y<=this.rect.top?a=Et.top:t[s].y>=this.rect.bottom?a=Et.bottom:a=Et.inside;break;case Et.bottom:for(;s<=o&&t[s].y>=this.rect.bottom;)s++;if(s>o)break;t[s].y<=this.rect.top?a=Et.top:t[s].x<=this.rect.left?a=Et.left:t[s].x>=this.rect.right?a=Et.right:a=Et.inside;break;case Et.inside:for(;s<=o;){if(t[s].x<this.rect.left)a=Et.left;else if(t[s].x>this.rect.right)a=Et.right;else if(t[s].y>this.rect.bottom)a=Et.bottom;else if(t[s].y<this.rect.top)a=Et.top;else{this.add(t[s]),s++;continue}break}break}return{location:a,index:s}}static startLocsAreClockwise(t){let n=0;for(let e=1;e<t.length;e++)switch(t[e]-t[e-1]){case-1:n-=1;break;case 1:n+=1;break;case-3:n+=1;break;case 3:n-=1;break}return n>0}executeInternal(t){if(t.length<3||In.isEmpty(this.rect))return;const n=[];let e=Et.inside,o=e,s=e;const a=t.length-1,r=At.getLocation(this.rect,t[a]);let c=r.location;if(r.isOnRect){let u=a-1;for(;u>=0;){const h=At.getLocation(this.rect,t[u]);if(!h.isOnRect){s=h.location;break}u--}if(u<0){for(const h of t)this.add(h);return}s===Et.inside&&(c=Et.inside)}const l=c;let d=0;for(;d<=a;){s=c;const u=o,h=this.getNextLocation(t,c,d,a);if(c=h.location,d=h.index,d>a)break;const f=d===0?t[a]:t[d-1];o=c;const g=At.getIntersection(this.rectPath,t[d],f,o);if(!g.intersects){if(u===Et.inside){const p=At.isClockwise(s,c,f,t[d],this.mp);do n.push(s),s=At.getAdjacentLocation(s,p);while(s!==c);o=u}else if(s!==Et.inside&&s!==c){const p=At.isClockwise(s,c,f,t[d],this.mp);do s=this.addCornerWithDirection(s,p);while(s!==c)}++d;continue}const m=g.point;if(o=g.newLocation,c===Et.inside){if(e===Et.inside)e=o,n.push(s);else if(s!==o){const p=At.isClockwise(s,o,f,t[d],this.mp);do s=this.addCornerWithDirection(s,p);while(s!==o)}}else if(s!==Et.inside){c=s;const v=At.getIntersection(this.rectPath,f,t[d],c).point;if(u!==Et.inside&&u!==c&&this.addCorner(u,c),e===Et.inside&&(e=c,n.push(s)),c=o,this.add(v),ye.equals(m,v)){c=At.getLocation(this.rect,t[d]).location,this.addCorner(o,c),o=c;continue}}else c=o,e===Et.inside&&(e=o);this.add(m)}if(e===Et.inside){if(l===Et.inside||!In.containsRect(this.pathBounds,this.rect)||!At.path1ContainsPath2(t,this.rectPath))return;const u=At.startLocsAreClockwise(n);for(let h=0;h<4;h++){const f=u?h:3-h;this.add(this.rectPath[f]),At.addToEdge(this.edges[f*2],this.results[0])}}else if(c!==Et.inside&&(c!==e||n.length>2)){if(n.length>0){s=c;for(const u of n)s!==u&&(s=this.addCornerWithDirection(s,At.headingClockwise(s,u)),s=u);c=s}c!==e&&this.addCornerWithDirection(c,At.headingClockwise(c,e))}}execute(t){const n=[];if(In.isEmpty(this.rect))return n;for(const e of t)if(!(e.length<3)&&(this.pathBounds=pt.getBounds(e),!!In.intersects(this.rect,this.pathBounds))){if(In.containsRect(this.rect,this.pathBounds)){n.push(e);continue}this.executeInternal(e),this.checkEdges();for(let o=0;o<4;++o)this.tidyEdgePair(o,this.edges[o*2],this.edges[o*2+1]);for(const o of this.results){const s=this.getPath(o);s.length>0&&n.push(s)}this.results.length=0;for(let o=0;o<8;o++)this.edges[o].length=0}return n}checkEdges(){for(let t=0;t<this.results.length;t++){let n=this.results[t],e=n;if(n===null)continue;do if(pt.isCollinear(e.prev.pt,e.pt,e.next.pt)){if(e===n){if(e=At.unlinkOpBack(e),e===null)break;n=e.prev}else if(e=At.unlinkOpBack(e),e===null)break}else e=e.next;while(e!==n);if(e===null){this.results[t]=null;continue}this.results[t]=e;let o=At.getEdgesForPt(n.prev.pt,this.rect);e=n;do{const s=At.getEdgesForPt(e.pt,this.rect);if(s!==0&&e.edge===null){const a=o&s;for(let r=0;r<4;++r)(a&1<<r)!==0&&(At.isHeadingClockwise(e.prev.pt,e.pt,r)?At.addToEdge(this.edges[r*2],e):At.addToEdge(this.edges[r*2+1],e))}o=s,e=e.next}while(e!==n)}}tidyEdgePair(t,n,e){if(e.length===0)return;const o=t===1||t===3,s=t===1||t===2;let a=0,r=0;for(;a<n.length;){let c=n[a];if(c===null||c.next===c.prev){n[a++]=null,r=0;continue}const l=e.length;for(;r<l&&(e[r]===null||e[r].next===e[r].prev);)++r;if(r===l){++a,r=0;continue}let d,u,h;if(s?(c=n[a].prev,u=n[a],d=e[r],h=e[r].prev):(c=n[a],u=n[a].prev,d=e[r].prev,h=e[r]),o&&!At.hasHorzOverlap(c.pt,u.pt,d.pt,h.pt)||!o&&!At.hasVertOverlap(c.pt,u.pt,d.pt,h.pt)){++r;continue}const f=n[a].ownerIdx!==e[r].ownerIdx;if(f&&(this.results[d.ownerIdx]=null,At.setNewOwner(d,c.ownerIdx)),s?(c.next=d,d.prev=c,u.prev=h,h.next=u):(c.prev=d,d.next=c,u.next=h,h.prev=u),!f){const I=this.results.length;this.results.push(u),At.setNewOwner(u,I)}let g,m;s?(g=d,m=u):(g=c,m=h),this.results[g.ownerIdx]=g,this.results[m.ownerIdx]=m;let p,v;o?(p=g.pt.x>g.prev.pt.x,v=m.pt.x>m.prev.pt.x):(p=g.pt.y>g.prev.pt.y,v=m.pt.y>m.prev.pt.y),g.next===g.prev||ye.equals(g.pt,g.prev.pt)?v===s?(n[a]=m,e[r++]=null):(e[r]=m,n[a++]=null):m.next===m.prev||ye.equals(m.pt,m.prev.pt)?p===s?(n[a]=g,e[r++]=null):(e[r]=g,n[a++]=null):p===v?p===s?(n[a]=g,At.uncoupleEdge(m),At.addToEdge(n,m),e[r++]=null):(n[a++]=null,e[r]=m,At.uncoupleEdge(g),At.addToEdge(e,g),r=0):(p===s?n[a]=g:e[r]=g,v===s?n[a]=m:e[r]=m)}}getPath(t){const n=[];if(t===null||t.prev===t.next)return n;let e=t.next;for(;e!==null&&e!==t;)pt.isCollinear(e.prev.pt,e.pt,e.next.pt)?(t=e.prev,e=At.unlinkOp(e)):e=e.next;if(e===null)return[];for(n.push(t.pt),e=t.next;e!==t;)n.push(e.pt),e=e.next;return n}}class Sm extends At{constructor(t){super(t)}execute(t){const n=[];if(In.isEmpty(this.rect))return n;for(const e of t)if(!(e.length<2)&&(this.pathBounds=pt.getBounds(e),!!In.intersects(this.rect,this.pathBounds))){this.executeInternalLines(e);for(const o of this.results){const s=this.getPathLines(o);s.length>0&&n.push(s)}this.results.length=0;for(let o=0;o<8;o++)this.edges[o].length=0}return n}getPathLines(t){const n=[];if(t===null||t===t.next)return n;t=t.next,n.push(t.pt);let e=t.next;for(;e!==t;)n.push(e.pt),e=e.next;return n}executeInternalLines(t){if(this.results.length=0,t.length<2||In.isEmpty(this.rect))return;let n=Et.inside,e=1;const o=t.length-1,s=At.getLocation(this.rect,t[0]);let a=s.location;if(s.isOnRect){for(;e<=o;){const r=At.getLocation(this.rect,t[e]);if(!r.isOnRect){n=r.location;break}e++}if(e>o){for(const r of t)this.add(r);return}n===Et.inside&&(a=Et.inside),e=1}for(a===Et.inside&&this.add(t[0]);e<=o;){n=a;const r=this.getNextLocation(t,a,e,o);if(a=r.location,e=r.index,e>o)break;const c=t[e-1];let l=a;const d=At.getIntersection(this.rectPath,t[e],c,l);if(!d.intersects){++e;continue}const u=d.point;if(l=d.newLocation,a===Et.inside)this.add(u,!0);else if(n!==Et.inside){l=n;const f=At.getIntersection(this.rectPath,c,t[e],l).point;this.add(f,!0),this.add(u)}else this.add(u)}}}var $s;(function(i){function t(h,f,g,m){const p=m?0:1,v=h.length,I=f.length,w=[];for(const _ of f){const y=[];if(g)for(const D of h)y.push(ye.add(_,D));else for(const D of h)y.push(ye.subtract(_,D));w.push(y)}const C=[];let S=m?I-1:0,b=v-1;for(let _=p;_<I;_++){for(let y=0;y<v;y++){const D=[w[S][b],w[_][b],w[_][y],w[S][y]];a(D)?C.push(D):C.push(c(D)),b=y}S=_}return C}function n(h,f,g){return u(t(h,f,!0,g),we.NonZero)}i.sum=n;function e(h,f,g,m=2){const p=Math.pow(10,m),v=u(t(l(h,p),l(f,p),!0,g),we.NonZero);return d(v,1/p)}i.sumD=e;function o(h,f,g){return u(t(h,f,!1,g),we.NonZero)}i.diff=o;function s(h,f,g,m=2){const p=Math.pow(10,m),v=u(t(l(h,p),l(f,p),!1,g),we.NonZero);return d(v,1/p)}i.diffD=s;function a(h){return r(h)>=0}function r(h){let f=0;const g=h.length;if(g<3)return 0;let m=h[g-1];for(const p of h)f+=(m.y+p.y)*(m.x-p.x),m=p;return f*.5}function c(h){return[...h].reverse()}function l(h,f){const g=[];for(const m of h)g.push({x:pt.roundToEven(m.x*f),y:pt.roundToEven(m.y*f)});return g}function d(h,f){const g=[];for(const m of h){const p=[];for(const v of m)p.push({x:v.x*f,y:v.y*f});g.push(p)}return g}function u(h,f){const g=[],m=new hl;return m.addPaths(h,Ze.Subject),m.execute(Ce.Union,f,g),g}})($s||($s={}));var ls;(function(i){i[i.success=0]="success",i[i.fail=1]="fail",i[i.noPolygons=2]="noPolygons",i[i.pathsIntersect=3]="pathsIntersect"})(ls||(ls={}));var nn;(function(i){i[i.loose=0]="loose",i[i.ascend=1]="ascend",i[i.descend=2]="descend"})(nn||(nn={}));var Jn;(function(i){i[i.none=0]="none",i[i.collinear=1]="collinear",i[i.intersect=2]="intersect"})(Jn||(Jn={}));var ci;(function(i){i[i.neither=0]="neither",i[i.left=1]="left",i[i.right=2]="right"})(ci||(ci={}));class Qd{pt;edges=[];innerLM=!1;constructor(t){this.pt=t}}class DP{vL=null;vR=null;vB=null;vT=null;kind=nn.loose;triA=null;triB=null;isActive=!1;nextE=null;prevE=null}class TP{edges=new Array(3);constructor(t,n,e){this.edges[0]=t,this.edges[1]=n,this.edges[2]=e}}class _t{allVertices=[];allEdges=[];allTriangles=[];pendingDelaunayStack=[];horzEdgeStack=[];locMinStack=[];useDelaunay;firstActive=null;lowermostVertex=null;constructor(t=!0){this.useDelaunay=t}addPath(t){const n=t.length;if(n===0)return;let e=0,o,s;const a=_t.findLocMinIdx(t,n,e);if(!a.found)return;for(e=a.idx,o=_t.prev(e,n);t[o].x===t[e].x&&t[o].y===t[e].y;)o=_t.prev(o,n);s=_t.next(e,n);let r=e;for(;pt.crossProductSign(t[o],t[r],t[s])===0;){const f=_t.findLocMinIdx(t,n,r);if(!f.found)return;for(r=f.idx,o=_t.prev(r,n);t[o].x===t[r].x&&t[o].y===t[r].y;)o=_t.prev(o,n);s=_t.next(r,n)}const c=this.allVertices.length,l=new Qd(t[r]);this.allVertices.push(l),_t.leftTurning(t[o],t[r],t[s])&&(l.innerLM=!0);let d=l;for(r=s;;){if(this.locMinStack.push(d),(this.lowermostVertex===null||d.pt.y>this.lowermostVertex.pt.y||d.pt.y===this.lowermostVertex.pt.y&&d.pt.x<this.lowermostVertex.pt.x)&&(this.lowermostVertex=d),s=_t.next(r,n),pt.crossProductSign(d.pt,t[r],t[s])===0){r=s;continue}for(;t[r].y<=d.pt.y;){const g=new Qd(t[r]);for(this.allVertices.push(g),this.createEdge(d,g,nn.ascend),d=g,r=s,s=_t.next(r,n);pt.crossProductSign(d.pt,t[r],t[s])===0;)r=s,s=_t.next(r,n)}const f=d;for(;r!==e&&t[r].y>=d.pt.y;){const g=new Qd(t[r]);for(this.allVertices.push(g),this.createEdge(g,d,nn.descend),d=g,r=s,s=_t.next(r,n);pt.crossProductSign(d.pt,t[r],t[s])===0;)r=s,s=_t.next(r,n)}if(r===e)break;_t.leftTurning(f.pt,d.pt,t[r])&&(d.innerLM=!0)}this.createEdge(l,d,nn.descend);const u=this.allVertices.length-c,h=c;if(u<3||u===3&&(_t.distSqr(this.allVertices[h].pt,this.allVertices[h+1].pt)<=1||_t.distSqr(this.allVertices[h+1].pt,this.allVertices[h+2].pt)<=1||_t.distSqr(this.allVertices[h+2].pt,this.allVertices[h].pt)<=1))for(let f=c;f<this.allVertices.length;++f)this.allVertices[f].edges=[]}addPaths(t){let n=0;for(const e of t)n+=e.length;if(n===0)return!1;for(const e of t)this.addPath(e);return this.allVertices.length>2}cleanUp(){this.allVertices.length=0,this.allEdges.length=0,this.allTriangles.length=0,this.pendingDelaunayStack.length=0,this.horzEdgeStack.length=0,this.locMinStack.length=0,this.firstActive=null,this.lowermostVertex=null}fixupEdgeIntersects(){for(let t=0;t<this.allEdges.length;++t){const n=this.allEdges[t];for(let e=t+1;e<this.allEdges.length;++e){const o=this.allEdges[e];if(o.vL.pt.x>=n.vR.pt.x)break;if(o.vT.pt.y<n.vB.pt.y&&o.vB.pt.y>n.vT.pt.y&&_t.segsIntersect(o.vL.pt,o.vR.pt,n.vL.pt,n.vR.pt)===Jn.intersect&&!this.removeIntersection(o,n))return!1}}return!0}mergeDupOrCollinearVertices(){if(this.allVertices.length<2)return;let t=0;for(let n=1;n<this.allVertices.length;++n){const e=this.allVertices[t],o=this.allVertices[n];if(!(e.pt.x===o.pt.x&&e.pt.y===o.pt.y)){t=n;continue}(!e.innerLM||!o.innerLM)&&(e.innerLM=!1);for(const s of o.edges)s.vB===o?s.vB=e:s.vT=e,s.vL===o?s.vL=e:s.vR=e;e.edges.push(...o.edges),o.edges=[];for(let s=0;s<e.edges.length;++s){const a=e.edges[s];if(!(_t.isHorizontal(a)||a.vB!==e))for(let r=s+1;r<e.edges.length;++r){const c=e.edges[r];if(!(c.vB!==e||a.vT.pt.y===c.vT.pt.y||pt.crossProductSign(a.vT.pt,e.pt,c.vT.pt)!==0)){a.vT.pt.y<c.vT.pt.y?this.splitEdge(a,c):this.splitEdge(c,a);break}}}}}splitEdge(t,n){const e=t.vT,o=n.vT;_t.removeEdgeFromVertex(e,t),t.vT=o,t.vL===e?t.vL=o:t.vR=o,o.edges.push(t),this.createEdge(o,e,t.kind)}removeIntersection(t,n){let e=t.vL,o=n,s=_t.shortestDistFromSegment(t.vL.pt,n.vL.pt,n.vR.pt),a=_t.shortestDistFromSegment(t.vR.pt,n.vL.pt,n.vR.pt);if(a<s&&(s=a,e=t.vR),a=_t.shortestDistFromSegment(n.vL.pt,t.vL.pt,t.vR.pt),a<s&&(s=a,o=t,e=n.vL),a=_t.shortestDistFromSegment(n.vR.pt,t.vL.pt,t.vR.pt),a<s&&(s=a,o=t,e=n.vR),s>1)return!1;const r=o.vT;return _t.removeEdgeFromVertex(r,o),o.vL===r?o.vL=e:o.vR=e,o.vT=e,e.edges.push(o),e.innerLM=!1,o.vB.innerLM&&_t.getLocMinAngle(o.vB)<=0&&(o.vB.innerLM=!1),this.createEdge(e,r,o.kind),!0}createEdge(t,n,e){const o=new DP;return this.allEdges.push(o),t.pt.y===n.pt.y?(o.vB=t,o.vT=n):t.pt.y<n.pt.y?(o.vB=n,o.vT=t):(o.vB=t,o.vT=n),t.pt.x<=n.pt.x?(o.vL=t,o.vR=n):(o.vL=n,o.vR=t),o.kind=e,t.edges.push(o),n.edges.push(o),e===nn.loose&&(this.pendingDelaunayStack.push(o),this.addEdgeToActives(o)),o}createTriangle(t,n,e){const o=new TP(t,n,e);this.allTriangles.push(o);for(let s=0;s<3;++s){const a=o.edges[s];a.triA!==null?(a.triB=o,this.removeEdgeFromActives(a)):(a.triA=o,_t.isLooseEdge(a)||this.removeEdgeFromActives(a))}return o}forceLegal(t){if(t.triA===null||t.triB===null)return;let n=null,e=null;const o=[null,null,null],s=[null,null,null];for(let r=0;r<3;++r){if(t.triA.edges[r]===t)continue;const c=t.triA.edges[r],l=_t.edgeContains(c,t.vL);l===ci.left?(o[1]=c,n=c.vR):l===ci.right?(o[1]=c,n=c.vL):s[1]=c}for(let r=0;r<3;++r){if(t.triB.edges[r]===t)continue;const c=t.triB.edges[r],l=_t.edgeContains(c,t.vL);l===ci.left?(o[2]=c,e=c.vR):l===ci.right?(o[2]=c,e=c.vL):s[2]=c}if(n===null||e===null||pt.crossProductSign(n.pt,t.vL.pt,t.vR.pt)===0)return;const a=_t.inCircleTest(n.pt,t.vL.pt,t.vR.pt,e.pt);if(!(a===0||_t.rightTurning(n.pt,t.vL.pt,t.vR.pt)===a<0)){t.vL=n,t.vR=e,t.triA.edges[0]=t;for(let r=1;r<3;++r){const c=o[r];if(t.triA.edges[r]=c,_t.isLooseEdge(c)&&this.pendingDelaunayStack.push(c),!(c.triA===t.triA||c.triB===t.triA))if(c.triA===t.triB)c.triA=t.triA;else if(c.triB===t.triB)c.triB=t.triA;else throw new Error("Triangulation internal error")}t.triB.edges[0]=t;for(let r=1;r<3;++r){const c=s[r];if(t.triB.edges[r]=c,_t.isLooseEdge(c)&&this.pendingDelaunayStack.push(c),!(c.triA===t.triB||c.triB===t.triB))if(c.triA===t.triA)c.triA=t.triB;else if(c.triB===t.triA)c.triB=t.triB;else throw new Error("Triangulation internal error")}}}createInnerLocMinLooseEdge(t){if(this.firstActive===null)return null;const n=t.pt.x,e=t.pt.y;let o=this.firstActive,s=null,a=-1;for(;o!==null;){if(o.vL.pt.x<=n&&o.vR.pt.x>=n&&o.vB.pt.y>=e&&o.vB!==t&&o.vT!==t&&!_t.leftTurning(o.vL.pt,t.pt,o.vR.pt)){const d=_t.shortestDistFromSegment(t.pt,o.vL.pt,o.vR.pt);(s===null||d<a)&&(s=o,a=d)}o=o.nextE}if(s===null)return null;let r=s.vT.pt.y<=e?s.vB:s.vT,c=r.pt.x,l=r.pt.y;if(o=this.firstActive,c<n)for(;o!==null;)o.vR.pt.x>c&&o.vL.pt.x<n&&o.vB.pt.y>e&&o.vT.pt.y<l&&_t.segsIntersect(o.vB.pt,o.vT.pt,r.pt,t.pt)===Jn.intersect&&(r=o.vT.pt.y>e?o.vT:o.vB,c=r.pt.x,l=r.pt.y),o=o.nextE;else for(;o!==null;)o.vR.pt.x<c&&o.vL.pt.x>n&&o.vB.pt.y>e&&o.vT.pt.y<l&&_t.segsIntersect(o.vB.pt,o.vT.pt,r.pt,t.pt)===Jn.intersect&&(r=o.vT.pt.y>e?o.vT:o.vB,c=r.pt.x,l=r.pt.y),o=o.nextE;return this.createEdge(r,t,nn.loose)}horizontalBetween(t,n){const e=t.pt.y;let o,s;t.pt.x>n.pt.x?(o=n.pt.x,s=t.pt.x):(o=t.pt.x,s=n.pt.x);let a=this.firstActive;for(;a!==null&&!(a.vL.pt.y===e&&a.vR.pt.y===e&&a.vL.pt.x>=o&&a.vR.pt.x<=s&&(a.vL.pt.x!==o||a.vL.pt.x!==s));)a=a.nextE;return a}doTriangulateLeft(t,n,e){let o=null,s=null;const a=t.vB===n?t.vT:t.vB;for(const c of n.edges){if(c===t||!c.isActive)continue;const l=c.vT===n?c.vB:c.vT;if(l===a)continue;const d=pt.crossProductSign(a.pt,n.pt,l.pt);if(d===0){if(a.pt.x>n.pt.x==n.pt.x>l.pt.x)continue}else if(d>0||o!==null&&!_t.leftTurning(l.pt,n.pt,o.pt))continue;o=l,s=c}if(o===null||o.pt.y<e||s===null)return;if(o.pt.y<n.pt.y){if(_t.isLeftEdge(s))return}else if(o.pt.y>n.pt.y&&_t.isRightEdge(s))return;let r=_t.findLinkingEdge(o,a,o.pt.y<a.pt.y);if(r===null){if(o.pt.y===a.pt.y&&a.pt.y===e&&this.horizontalBetween(o,a)!==null)return;r=this.createEdge(o,a,nn.loose)}this.createTriangle(t,s,r),_t.edgeCompleted(r)||this.doTriangulateLeft(r,o,e)}doTriangulateRight(t,n,e){let o=null,s=null;const a=t.vB===n?t.vT:t.vB;for(const c of n.edges){if(c===t||!c.isActive)continue;const l=c.vT===n?c.vB:c.vT;if(l===a)continue;const d=pt.crossProductSign(a.pt,n.pt,l.pt);if(d===0){if(a.pt.x>n.pt.x==n.pt.x>l.pt.x)continue}else if(d<0||o!==null&&!_t.rightTurning(l.pt,n.pt,o.pt))continue;o=l,s=c}if(o===null||o.pt.y<e||s===null)return;if(o.pt.y<n.pt.y){if(_t.isRightEdge(s))return}else if(o.pt.y>n.pt.y&&_t.isLeftEdge(s))return;let r=_t.findLinkingEdge(o,a,o.pt.y>a.pt.y);if(r===null){if(o.pt.y===a.pt.y&&a.pt.y===e&&this.horizontalBetween(o,a)!==null)return;r=this.createEdge(o,a,nn.loose)}this.createTriangle(t,r,s),_t.edgeCompleted(r)||this.doTriangulateRight(r,o,e)}addEdgeToActives(t){t.isActive||(t.prevE=null,t.nextE=this.firstActive,t.isActive=!0,this.firstActive!==null&&(this.firstActive.prevE=t),this.firstActive=t)}removeEdgeFromActives(t){_t.removeEdgeFromVertex(t.vB,t),_t.removeEdgeFromVertex(t.vT,t);const n=t.prevE,e=t.nextE;e!==null&&(e.prevE=n),n!==null&&(n.nextE=e),t.isActive=!1,this.firstActive===t&&(this.firstActive=e)}execute(t){const n=[];if(!this.addPaths(t))return{result:ls.noPolygons,solution:n};if(this.lowermostVertex.innerLM){for(;this.locMinStack.length>0;){const o=this.locMinStack.pop();o.innerLM=!o.innerLM}for(const o of this.allEdges)o.kind===nn.ascend?o.kind=nn.descend:o.kind===nn.descend&&(o.kind=nn.ascend)}else this.locMinStack.length=0;if(this.allEdges.sort((o,s)=>o.vL.pt.x<s.vL.pt.x?-1:o.vL.pt.x>s.vL.pt.x?1:0),!this.fixupEdgeIntersects())return this.cleanUp(),{result:ls.pathsIntersect,solution:n};this.allVertices.sort((o,s)=>o.pt.y===s.pt.y?o.pt.x<s.pt.x?-1:o.pt.x>s.pt.x?1:0:s.pt.y<o.pt.y?-1:1),this.mergeDupOrCollinearVertices();let e=this.allVertices[0].pt.y;for(const o of this.allVertices)if(o.edges.length!==0){if(o.pt.y!==e){for(;this.locMinStack.length>0;){const s=this.locMinStack.pop(),a=this.createInnerLocMinLooseEdge(s);if(a===null)return this.cleanUp(),{result:ls.fail,solution:n};_t.isHorizontal(a)?a.vL===a.vB?this.doTriangulateLeft(a,a.vB,e):this.doTriangulateRight(a,a.vB,e):(this.doTriangulateLeft(a,a.vB,e),_t.edgeCompleted(a)||this.doTriangulateRight(a,a.vB,e)),this.addEdgeToActives(s.edges[0]),this.addEdgeToActives(s.edges[1])}for(;this.horzEdgeStack.length>0;){const s=this.horzEdgeStack.pop();_t.edgeCompleted(s)||(s.vB===s.vL?_t.isLeftEdge(s)&&this.doTriangulateLeft(s,s.vB,e):_t.isRightEdge(s)&&this.doTriangulateRight(s,s.vB,e))}e=o.pt.y}for(let s=o.edges.length-1;s>=0;--s){if(s>=o.edges.length)continue;const a=o.edges[s];_t.edgeCompleted(a)||_t.isLooseEdge(a)||(o===a.vB?(_t.isHorizontal(a)&&this.horzEdgeStack.push(a),o.innerLM||this.addEdgeToActives(a)):_t.isHorizontal(a)?this.horzEdgeStack.push(a):_t.isLeftEdge(a)?this.doTriangulateLeft(a,a.vB,o.pt.y):this.doTriangulateRight(a,a.vB,o.pt.y))}o.innerLM&&this.locMinStack.push(o)}for(;this.horzEdgeStack.length>0;){const o=this.horzEdgeStack.pop();!_t.edgeCompleted(o)&&o.vB===o.vL&&this.doTriangulateLeft(o,o.vB,e)}if(this.useDelaunay)for(;this.pendingDelaunayStack.length>0;){const o=this.pendingDelaunayStack.pop();this.forceLegal(o)}for(const o of this.allTriangles){const s=_t.pathFromTriangle(o),a=pt.crossProductSign(s[0],s[1],s[2]);a!==0&&(a<0&&s.reverse(),n.push(s))}return this.cleanUp(),{result:ls.success,solution:n}}static isLooseEdge(t){return t.kind===nn.loose}static isLeftEdge(t){return t.kind===nn.ascend}static isRightEdge(t){return t.kind===nn.descend}static isHorizontal(t){return t.vB.pt.y===t.vT.pt.y}static leftTurning(t,n,e){return pt.crossProductSign(t,n,e)<0}static rightTurning(t,n,e){return pt.crossProductSign(t,n,e)>0}static edgeCompleted(t){return t.triA===null?!1:t.triB!==null?!0:t.kind!==nn.loose}static edgeContains(t,n){return t.vL===n?ci.left:t.vR===n?ci.right:ci.neither}static getAngle(t,n,e){const o=Number(n.x-t.x),s=Number(n.y-t.y),a=Number(n.x-e.x),r=Number(n.y-e.y),c=o*a+s*r,l=o*r-s*a;return Math.atan2(l,c)}static getLocMinAngle(t){let n,e;return t.edges[0].kind===nn.ascend?(n=0,e=1):(e=0,n=1),_t.getAngle(t.edges[e].vT.pt,t.pt,t.edges[n].vT.pt)}static removeEdgeFromVertex(t,n){const e=t.edges.indexOf(n);if(e<0)throw new Error("Edge not found in vertex");t.edges.splice(e,1)}static findLocMinIdx(t,n,e){if(n<3)return{found:!1,idx:e};const o=e;let s=(e+1)%n;for(;t[s].y<=t[e].y;)if(e=s,s=(s+1)%n,e===o)return{found:!1,idx:e};for(;t[s].y>=t[e].y;)e=s,s=(s+1)%n;return{found:!0,idx:e}}static prev(t,n){return t===0?n-1:t-1}static next(t,n){return(t+1)%n}static findLinkingEdge(t,n,e){let o=null;for(const s of t.edges)if(s.vL===n||s.vR===n){if(s.kind===nn.loose||s.kind===nn.ascend===e)return s;o=s}return o}static pathFromTriangle(t){const n=[t.edges[0].vL.pt,t.edges[0].vR.pt],e=t.edges[1];return e.vL.pt.x===n[0].x&&e.vL.pt.y===n[0].y||e.vL.pt.x===n[1].x&&e.vL.pt.y===n[1].y?n.push(e.vR.pt):n.push(e.vL.pt),n}static inCircleTest(t,n,e,o){const s=Number(t.x-o.x),a=Number(t.y-o.y),r=s*s+a*a,c=Number(n.x-o.x),l=Number(n.y-o.y),d=c*c+l*l,u=Number(e.x-o.x),h=Number(e.y-o.y),f=u*u+h*h;return s*(l*f-h*d)-c*(a*f-h*r)+u*(a*d-l*r)}static shortestDistFromSegment(t,n,e){const o=Number(e.x-n.x),s=Number(e.y-n.y),a=Number(t.x-n.x),r=Number(t.y-n.y),c=a*o+r*s,l=o*o+s*s;return c<0?_t.distanceSqr(t,n):c>l?_t.distanceSqr(t,e):(a*s-o*r)*(a*s-o*r)/l}static segsIntersect(t,n,e,o){const s=Number(n.y-t.y),a=Number(n.x-t.x),r=Number(o.y-e.y),c=Number(o.x-e.x),l=s*c-r*a;if(l===0)return Jn.collinear;let d=Number(t.x-e.x)*r-Number(t.y-e.y)*c;if(d===0)return Jn.none;if(d>0){if(l<0||d>=l)return Jn.none}else if(l>0||d<=l)return Jn.none;if(d=Number(t.x-e.x)*s-Number(t.y-e.y)*a,d===0)return Jn.none;if(d>0){if(l>0&&d<l)return Jn.intersect}else if(l<0&&d>l)return Jn.intersect;return Jn.none}static distSqr(t,n){const e=Number(t.x-n.x),o=Number(t.y-n.y);return e*e+o*o}static distanceSqr(t,n){const e=Number(t.x-n.x),o=Number(t.y-n.y);return e*e+o*o}}var _r;(function(i){i.invalidRect64=SP,i.invalidRectD=CP;function t(A,O,k){return l(Ce.Intersection,A,O,k)}i.intersect=t;function n(A,O,k,H=2){return u(Ce.Intersection,A,O,k,H)}i.intersectD=n;function e(A,O,k){return typeof O=="number"?l(Ce.Union,A,null,O):l(Ce.Union,A,O,k)}i.union=e;function o(A,O,k,H){return typeof O=="number"?u(Ce.Union,A,null,O):u(Ce.Union,A,O,k,H||2)}i.unionD=o;function s(A,O,k){return l(Ce.Difference,A,O,k)}i.difference=s;function a(A,O,k,H=2){return u(Ce.Difference,A,O,k,H)}i.differenceD=a;function r(A,O,k){return l(Ce.Xor,A,O,k)}i.xor=r;function c(A,O,k,H=2){return u(Ce.Xor,A,O,k,H)}i.xorD=c;function l(A,O,k,H){const X=[];if(O===null)return X;const ct=new hl;return ct.addPaths(O,Ze.Subject),k!==null&&ct.addPaths(k,Ze.Clip),ct.execute(A,H,X),X}i.booleanOp=l;function d(A,O,k,H,X){if(O===null)return;const ct=new hl;ct.addPaths(O,Ze.Subject),k!==null&&ct.addPaths(k,Ze.Clip),ct.execute(A,X,H)}i.booleanOpWithPolyTree=d;function u(A,O,k,H,X=2){const ct=[],vt=new wm(X);return vt.addSubjectPaths(O),k!==null&&vt.addClipPaths(k),vt.execute(A,H,ct),ct}i.booleanOpD=u;function h(A,O,k,H,X,ct=2){if(O===null)return;const vt=new wm(ct);vt.addSubjectPaths(O),k!==null&&vt.addClipPaths(k),vt.execute(A,X,H)}i.booleanOpDWithPolyTree=h;function f(A,O,k,H,X=2,ct=0){const vt=new Fe(X,ct);vt.addPaths(A,k,H);const bt=[];return vt.execute(O,bt),bt}i.inflatePaths=f;function g(A,O,k,H,X=2,ct=2,vt=0){pt.checkPrecision(ct);const bt=Math.pow(10,ct),gt=it(A,bt),Dn=new Fe(X,bt*vt);Dn.addPaths(gt,k,H);const Xt=[];return Dn.execute(O*bt,Xt),q(Xt,1/bt)}i.inflatePathsD=g;function m(A,O,k){if("left"in A&&typeof A.left=="number"&&Number.isInteger(A.left)){const H=A;if(In.isEmpty(H))return[];if(Array.isArray(O[0])){const X=O;return X.length===0?[]:new At(H).execute(X)}else{const X=O;return X.length===0?[]:m(H,[X])}}else{const H=A,X=k||2;if(pt.checkPrecision(X),cs.isEmpty(H))return[];const ct=Math.pow(10,X),vt=K(H,ct);if(Array.isArray(O[0])){const bt=O;if(bt.length===0)return[];const gt=it(bt,ct),Xt=new At(vt).execute(gt);return q(Xt,1/ct)}else{const bt=O;return bt.length===0?[]:m(H,[bt],X)}}}i.rectClip=m;function p(A,O,k){if("left"in A&&typeof A.left=="number"&&Number.isInteger(A.left)){const H=A;if(In.isEmpty(H))return[];if(Array.isArray(O[0])){const X=O;return X.length===0?[]:new Sm(H).execute(X)}else{const X=O;return X.length===0?[]:p(H,[X])}}else{const H=A,X=k||2;if(pt.checkPrecision(X),cs.isEmpty(H))return[];const ct=Math.pow(10,X),vt=K(H,ct);if(Array.isArray(O[0])){const bt=O;if(bt.length===0)return[];const gt=it(bt,ct),Xt=new Sm(vt).execute(gt);return q(Xt,1/ct)}else{const bt=O;return bt.length===0?[]:p(H,[bt],X)}}}i.rectClipLines=p;function v(A,O,k){return $s.sum(A,O,k)}i.minkowskiSum=v;function I(A,O,k){return $s.sumD(A,O,k)}i.minkowskiSumD=I;function w(A,O,k){return $s.diff(A,O,k)}i.minkowskiDiff=w;function C(A,O,k){return $s.diffD(A,O,k)}i.minkowskiDiffD=C;function S(A){let O=0;const k=A.length;if(k<3)return 0;let H=A[k-1];for(const X of A)O+=(H.y+X.y)*(H.x-X.x),H=X;return O*.5}i.area=S;function b(A){let O=0;for(const k of A)O+=S(k);return O}i.areaPaths=b;function _(A){let O=0;const k=A.length;if(k<3)return 0;let H=A[k-1];for(const X of A)O+=(H.y+X.y)*(H.x-X.x),H=X;return O*.5}i.areaD=_;function y(A){let O=0;for(const k of A)O+=_(k);return O}i.areaPathsD=y;function D(A){return S(A)>=0}i.isPositive=D;function T(A){return _(A)>=0}i.isPositiveD=T;function P(A){let O="";for(const k of A)O+=ye.toString(k);return O+`
|
|
174
|
+
`}i.path64ToString=P;function x(A){let O="";for(const k of A)O+=P(k);return O}i.paths64ToString=x;function M(A,O=2){let k="";for(const H of A)k+=hi.toString(H,O);return k+`
|
|
175
|
+
`}i.pathDToString=M;function L(A,O=2){let k="";for(const H of A)k+=M(H,O);return k}i.pathsDToString=L;function R(A,O,k){const H=[];for(const X of A)H.push({x:X.x+O,y:X.y+k});return H}i.offsetPath=R;function U(A,O){return{x:Math.round(A.x*O),y:Math.round(A.y*O)}}i.scalePoint64=U;function W(A,O){return{x:A.x*O,y:A.y*O}}i.scalePointD=W;function K(A,O){return{left:Math.round(A.left*O),top:Math.round(A.top*O),right:Math.round(A.right*O),bottom:Math.round(A.bottom*O)}}i.scaleRect=K;function j(A,O){if(pt.isAlmostZero(O-1))return A;const k=[];for(const H of A)k.push({x:Math.round(H.x*O),y:Math.round(H.y*O)});return k}i.scalePath=j;function F(A,O){if(pt.isAlmostZero(O-1))return A;const k=[];for(const H of A)k.push(j(H,O));return k}i.scalePaths=F;function z(A,O){if(pt.isAlmostZero(O-1))return A;const k=[];for(const H of A)k.push(hi.scale(H,O));return k}i.scalePathD=z;function q(A,O){if(pt.isAlmostZero(O-1))return A;const k=[];for(const H of A)k.push(z(H,O));return k}i.scalePathsD=q;function J(A,O){const k=[];for(const H of A)k.push({x:Math.round(H.x*O),y:Math.round(H.y*O)});return k}i.scalePath64=J;function it(A,O){const k=[];for(const H of A)k.push(J(H,O));return k}i.scalePaths64=it;function tt(A,O){const k=[];for(const H of A)k.push({x:H.x*O,y:H.y*O});return k}i.scalePathDFromInt=tt;function ot(A,O){const k=[];for(const H of A)k.push(tt(H,O));return k}i.scalePathsDFromInt=ot;function nt(A){const O=[];for(const k of A)O.push(ye.fromPointD(k));return O}i.path64FromD=nt;function lt(A){const O=[];for(const k of A)O.push(nt(k));return O}i.paths64FromD=lt;function rt(A){const O=[];for(const k of A)O.push(ut(k));return O}i.pathsD=rt;function ut(A){const O=[];for(const k of A)O.push(hi.fromPoint64(k));return O}i.pathD=ut;function Tt(A,O,k){const H=[];for(const X of A)H.push({x:X.x+O,y:X.y+k});return H}i.translatePath=Tt;function kt(A,O,k){const H=[];for(const X of A)H.push(R(X,O,k));return H}i.translatePaths=kt;function Pt(A,O,k){const H=[];for(const X of A)H.push({x:X.x+O,y:X.y+k});return H}i.translatePathD=Pt;function te(A,O,k){const H=[];for(const X of A)H.push(Pt(X,O,k));return H}i.translatePathsD=te;function Ie(A){return[...A].reverse()}i.reversePath=Ie;function re(A){return[...A].reverse()}i.reversePathD=re;function Zt(A){const O=[];for(const k of A)O.push(Ie(k));return O}i.reversePaths=Zt;function ce(A){const O=[];for(const k of A)O.push(re(k));return O}i.reversePathsD=ce;function Ut(A){return pt.getBounds(A)}i.getBounds=Ut;function Ht(A){const O=In.createInvalid();for(const k of A)for(const H of k)H.x<O.left&&(O.left=H.x),H.x>O.right&&(O.right=H.x),H.y<O.top&&(O.top=H.y),H.y>O.bottom&&(O.bottom=H.y);return O.left===Number.MAX_SAFE_INTEGER?{left:0,top:0,right:0,bottom:0}:O}i.getBoundsPaths=Ht;function Jt(A){const O=cs.createInvalid();for(const k of A)k.x<O.left&&(O.left=k.x),k.x>O.right&&(O.right=k.x),k.y<O.top&&(O.top=k.y),k.y>O.bottom&&(O.bottom=k.y);return Math.abs(O.left-Number.MAX_VALUE)<pt.floatingPointTolerance?{left:0,top:0,right:0,bottom:0}:O}i.getBoundsD=Jt;function Pe(A){const O=cs.createInvalid();for(const k of A)for(const H of k)H.x<O.left&&(O.left=H.x),H.x>O.right&&(O.right=H.x),H.y<O.top&&(O.top=H.y),H.y>O.bottom&&(O.bottom=H.y);return Math.abs(O.left-Number.MAX_VALUE)<pt.floatingPointTolerance?{left:0,top:0,right:0,bottom:0}:O}i.getBoundsPathsD=Pe;function De(A){const O=Math.floor(A.length/2),k=[];for(let H=0;H<O;H++)k.push({x:A[H*2],y:A[H*2+1],z:0});return k}i.makePath=De;function ln(A){const O=Math.floor(A.length/2),k=[];for(let H=0;H<O;H++)k.push({x:A[H*2],y:A[H*2+1],z:0});return k}i.makePathD=ln;function Ve(A){return A*A}i.sqr=Ve;function Wo(A,O){return Ve(A.x-O.x)+Ve(A.y-O.y)}i.distanceSqr=Wo;function jn(A,O){return{x:Math.round((A.x+O.x)/2),y:Math.round((A.y+O.y)/2)}}i.midPoint=jn;function Bo(A,O){return{x:(A.x+O.x)/2,y:(A.y+O.y)/2}}i.midPointD=Bo;function co(A,O,k){A.left-=O,A.right+=O,A.top-=k,A.bottom+=k}i.inflateRect=co;function yi(A,O,k){A.left-=O,A.right+=O,A.top-=k,A.bottom+=k}i.inflateRectD=yi;function lo(A,O,k){return Ve(A.x-O.x)+Ve(A.y-O.y)<k}i.pointsNearEqual=lo;function xi(A,O,k){const H=A.length,X=[];if(H===0)return X;let ct=A[0];X.push(ct);for(let vt=1;vt<H;vt++)lo(ct,A[vt],O)||(ct=A[vt],X.push(ct));return k&&lo(ct,X[0],O)&&X.pop(),X}i.stripNearDuplicates=xi;function oi(A,O){const k=A.length,H=[];if(k===0)return H;let X=A[0];H.push(X);for(let ct=1;ct<k;ct++)ye.equals(X,A[ct])||(X=A[ct],H.push(X));return O&&ye.equals(X,H[0])&&H.pop(),H}i.stripDuplicates=oi;function st(A,O){A.poly&&A.poly.length>0&&O.push(A.poly);for(let k=0;k<A.count;k++)st(A.child(k),O)}function Mt(A){const O=[];for(let k=0;k<A.count;k++)st(A.child(k),O);return O}i.polyTreeToPaths64=Mt;function G(A,O){A.poly&&A.poly.length>0&&O.push(A.poly);for(let k=0;k<A.count;k++)G(A.child(k),O)}i.addPolyNodeToPathsD=G;function et(A){const O=[];for(let k=0;k<A.count;k++)G(A.child(k),O);return O}i.polyTreeToPathsD=et;function at(A,O,k){const H=A.x-O.x,X=A.y-O.y,ct=k.x-O.x,vt=k.y-O.y;return ct===0&&vt===0?0:Ve(H*vt-ct*X)/(ct*ct+vt*vt)}i.perpendicDistFromLineSqrd=at;function jt(A,O,k){const H=A.x-O.x,X=A.y-O.y,ct=k.x-O.x,vt=k.y-O.y;return ct===0&&vt===0?0:Ve(H*vt-ct*X)/(ct*ct+vt*vt)}i.perpendicDistFromLineSqrd64=jt;function je(A,O,k,H,X){for(;;){let ct=0,vt=0;for(;k>O&&ye.equals(A[O],A[k]);)X[k--]=!1;for(let bt=O+1;bt<k;++bt){const gt=jt(A[bt],A[O],A[k]);gt<=vt||(vt=gt,ct=bt)}if(vt<=H)return;if(X[ct]=!0,ct>O+1&&je(A,O,ct,H,X),ct<k-1){O=ct;continue}break}}function dn(A,O){const k=A.length;if(k<5)return A;const H=new Array(k).fill(!1);H[0]=!0,H[k-1]=!0,je(A,0,k-1,Ve(O),H);const X=[];for(let ct=0;ct<k;++ct)H[ct]&&X.push(A[ct]);return X}i.ramerDouglasPeucker=dn;function yo(A,O){const k=[];for(const H of A)k.push(dn(H,O));return k}i.ramerDouglasPeuckerPaths=yo;function Pi(A,O,k,H,X){for(;;){let ct=0,vt=0;for(;k>O&&hi.equals(A[O],A[k]);)X[k--]=!1;for(let bt=O+1;bt<k;++bt){const gt=at(A[bt],A[O],A[k]);gt<=vt||(vt=gt,ct=bt)}if(vt<=H)return;if(X[ct]=!0,ct>O+1&&Pi(A,O,ct,H,X),ct<k-1){O=ct;continue}break}}function pc(A,O){const k=A.length;if(k<5)return A;const H=new Array(k).fill(!1);H[0]=!0,H[k-1]=!0,Pi(A,0,k-1,Ve(O),H);const X=[];for(let ct=0;ct<k;++ct)H[ct]&&X.push(A[ct]);return X}i.ramerDouglasPeuckerD=pc;function Nd(A,O){const k=[];for(const H of A)k.push(pc(H,O));return k}i.ramerDouglasPeuckerPathsD=Nd;function uo(A,O,k){for(++A;A<=O&&k[A];)++A;if(A<=O)return A;for(A=0;k[A];)++A;return A}function Ts(A,O,k){for(A===0?A=O:--A;A>0&&k[A];)--A;if(!k[A])return A;for(A=O;k[A];)--A;return A}function Qi(A,O,k=!0){const H=A.length,X=H-1,ct=Ve(O);if(H<4)return A;const vt=new Array(H).fill(!1),bt=new Array(H).fill(0);let gt=0;k?(bt[0]=jt(A[0],A[X],A[1]),bt[X]=jt(A[X],A[0],A[X-1])):(bt[0]=Number.MAX_VALUE,bt[X]=Number.MAX_VALUE);for(let Xt=1;Xt<X;++Xt)bt[Xt]=jt(A[Xt],A[Xt-1],A[Xt+1]);for(;;){if(bt[gt]>ct){const en=gt;do gt=uo(gt,X,vt);while(gt!==en&&bt[gt]>ct);if(gt===en)break}const Xt=Ts(gt,X,vt),Zn=uo(gt,X,vt);if(Zn===Xt)break;let ii;if(bt[Zn]<bt[gt]){ii=Xt;const en=gt;gt=Zn;const Va=uo(Zn,X,vt);vt[gt]=!0,gt=Va;const kd=uo(Va,X,vt);(k||gt!==X&>!==0)&&(bt[gt]=jt(A[gt],A[en],A[kd])),(k||en!==0&&en!==X)&&(bt[en]=jt(A[en],A[ii],A[gt]))}else{ii=Ts(Xt,X,vt),vt[gt]=!0,gt=Zn;const en=uo(Zn,X,vt);(k||gt!==X&>!==0)&&(bt[gt]=jt(A[gt],A[Xt],A[en])),(k||Xt!==0&&Xt!==X)&&(bt[Xt]=jt(A[Xt],A[ii],A[gt]))}}const Dn=[];for(let Xt=0;Xt<H;Xt++)vt[Xt]||Dn.push(A[Xt]);return Dn}i.simplifyPath=Qi;function Ms(A,O,k=!0){const H=[];for(const X of A)H.push(Qi(X,O,k));return H}i.simplifyPaths=Ms;function Ua(A,O,k=!0){const H=A.length,X=H-1,ct=Ve(O);if(H<4)return A;const vt=new Array(H).fill(!1),bt=new Array(H).fill(0);let gt=0;k?(bt[0]=at(A[0],A[X],A[1]),bt[X]=at(A[X],A[0],A[X-1])):(bt[0]=Number.MAX_VALUE,bt[X]=Number.MAX_VALUE);for(let Xt=1;Xt<X;++Xt)bt[Xt]=at(A[Xt],A[Xt-1],A[Xt+1]);for(;;){if(bt[gt]>ct){const en=gt;do gt=uo(gt,X,vt);while(gt!==en&&bt[gt]>ct);if(gt===en)break}const Xt=Ts(gt,X,vt),Zn=uo(gt,X,vt);if(Zn===Xt)break;let ii;if(bt[Zn]<bt[gt]){ii=Xt;const en=gt;gt=Zn;const Va=uo(Zn,X,vt);vt[gt]=!0,gt=Va;const kd=uo(Va,X,vt);(k||gt!==X&>!==0)&&(bt[gt]=at(A[gt],A[en],A[kd])),(k||en!==0&&en!==X)&&(bt[en]=at(A[en],A[ii],A[gt]))}else{ii=Ts(Xt,X,vt),vt[gt]=!0,gt=Zn;const en=uo(Zn,X,vt);(k||gt!==X&>!==0)&&(bt[gt]=at(A[gt],A[Xt],A[en])),(k||Xt!==0&&Xt!==X)&&(bt[Xt]=at(A[Xt],A[ii],A[gt]))}}const Dn=[];for(let Xt=0;Xt<H;Xt++)vt[Xt]||Dn.push(A[Xt]);return Dn}i.simplifyPathD=Ua;function dC(A,O,k=!0){const H=[];for(const X of A)H.push(Ua(X,O,k));return H}i.simplifyPathsD=dC;function wg(A,O=!1){let k=A.length,H=0;if(!O){for(;H<k-1&&pt.isCollinear(A[k-1],A[H],A[H+1]);)H++;for(;H<k-1&&pt.isCollinear(A[k-2],A[k-1],A[H]);)k--}if(k-H<3)return!O||k<2||ye.equals(A[0],A[1])?[]:A;const X=[];let ct=A[H];for(X.push(ct),H++;H<k-1;H++)pt.isCollinear(ct,A[H],A[H+1])||(ct=A[H],X.push(ct));if(O)X.push(A[k-1]);else if(!pt.isCollinear(ct,A[k-1],X[0]))X.push(A[k-1]);else{for(;X.length>2&&pt.isCollinear(X[X.length-1],X[X.length-2],X[0]);)X.pop();X.length<3&&(X.length=0)}return X}i.trimCollinear=wg;function uC(A,O,k=!1){pt.checkPrecision(O);const H=Math.pow(10,O);let X=J(A,H);return X=wg(X,k),tt(X,1/H)}i.trimCollinearD=uC;function hC(A,O){return pt.pointInPolygon(A,O)}i.pointInPolygon=hC;function fC(A,O,k=2){pt.checkPrecision(k);const H=Math.pow(10,k),X=ye.fromPointD(hi.scale(A,H)),ct=J(O,H);return pt.pointInPolygon(X,ct)}i.pointInPolygonD=fC;function gC(A,O,k=0,H=0){if(O<=0)return[];k<=0&&(k=O),H<=2&&(H=Math.ceil(Math.PI*Math.sqrt((O+k)/2)));const X=Math.sin(2*Math.PI/H),ct=Math.cos(2*Math.PI/H);let vt=ct,bt=X;const gt=[{x:Math.round(A.x+O),y:A.y}];for(let Dn=1;Dn<H;++Dn){gt.push({x:Math.round(A.x+O*vt),y:Math.round(A.y+k*bt)});const Xt=vt*ct-bt*X;bt=bt*ct+vt*X,vt=Xt}return gt}i.ellipse=gC;function mC(A,O,k=0,H=0){if(O<=0)return[];k<=0&&(k=O),H<=2&&(H=Math.ceil(Math.PI*Math.sqrt((O+k)/2)));const X=Math.sin(2*Math.PI/H),ct=Math.cos(2*Math.PI/H);let vt=ct,bt=X;const gt=[{x:A.x+O,y:A.y}];for(let Dn=1;Dn<H;++Dn){gt.push({x:A.x+O*vt,y:A.y+k*bt});const Xt=vt*ct-bt*X;bt=bt*ct+vt*X,vt=Xt}return gt}i.ellipseD=mC;function pC(A,O=!0){return new _t(O).execute(A)}i.triangulate=pC;function vC(A,O,k=!0){let H;O<=0?H=1:O>8?H=Math.pow(10,8):H=Math.pow(10,O);const X=it(A,H),ct=new _t(k),{result:vt,solution:bt}=ct.execute(X);let gt;return vt===ls.success?gt=q(bt,1/H):gt=[],{result:vt,solution:gt}}i.triangulateD=vC})(_r||(_r={}));const{intersect:xG,intersectD:PG,union:DG,unionD:TG,difference:MG,differenceD:AG,xor:LG,xorD:OG,booleanOp:RG,booleanOpWithPolyTree:NG,booleanOpD:kG,booleanOpDWithPolyTree:UG,inflatePaths:VG,inflatePathsD:FG,rectClip:GG,rectClipLines:HG,minkowskiSum:WG,minkowskiSumD:BG,minkowskiDiff:zG,minkowskiDiffD:$G,area:jG,areaPaths:XG,areaD:qG,areaPathsD:YG,isPositive:KG,isPositiveD:ZG,getBounds:JG,getBoundsPaths:QG,getBoundsD:tH,getBoundsPathsD:eH,makePath:nH,makePathD:oH,scalePath64:iH,scalePaths64:sH,scalePathD:aH,scalePathsD:rH,translatePath:cH,translatePaths:lH,translatePathD:dH,translatePathsD:uH,reversePath:hH,reversePathD:fH,reversePaths:gH,reversePathsD:mH,stripDuplicates:pH,trimCollinear:vH,trimCollinearD:IH,pointInPolygon:wH,pointInPolygonD:EH,ellipse:SH,ellipseD:CH,simplifyPath:bH,simplifyPaths:_H,simplifyPathD:yH,simplifyPathsD:xH,ramerDouglasPeucker:PH,ramerDouglasPeuckerPaths:DH,ramerDouglasPeuckerD:TH,ramerDouglasPeuckerPathsD:MH,triangulate:AH,triangulateD:LH}=_r,w0=4;var Ge;(function(i){i[i.Union=0]="Union",i[i.Difference=1]="Difference",i[i.Intersection=2]="Intersection",i[i.Xor=3]="Xor"})(Ge||(Ge={}));const MP={[Ge.Union]:Ce.Union,[Ge.Difference]:Ce.Difference,[Ge.Intersection]:Ce.Intersection,[Ge.Xor]:Ce.Xor};function Qu(i){const t=i.length,n=new Array(t);for(let e=0;e<t;e++)n[e]={x:i[e][0],y:i[e][1]};return n}function Cm(i){const t=i.length,n=new Array(t);for(let e=0;e<t;e++)n[e]=[i[e].x,i[e].y];return n}function bm(i){const t=[];for(const n of i)if(n.outer.length>=3&&t.push(Qu(n.outer)),n.holes)for(const e of n.holes)e.length>=3&&t.push(Qu(e));return t}function E0(i){const t=[];return th(i,t),t}function th(i,t){for(let n=0;n<i.count;n++){const e=i.child(n);if(e.isHole){th(e,t);continue}const o=e.poly;if(!o||o.length<3)continue;const s={outer:Cm(o)},a=[];for(let r=0;r<e.count;r++){const c=e.child(r);if(c.isHole){const l=c.poly;l&&l.length>=3&&a.push(Cm(l)),th(c,t)}}a.length>0&&(s.holes=a),t.push(s)}}function Pc(i){return i.map(t=>({outer:t.outer.map(n=>[n[0],n[1]]),holes:t.holes?.map(n=>n.map(e=>[e[0],e[1]]))}))}function rd(i,t,n){if(i.length===0)return n===Ge.Union||n===Ge.Xor?Pc(t):[];if(t.length===0)return n===Ge.Intersection?[]:Pc(i);const e=bm(i),o=bm(t);if(e.length===0)return n===Ge.Union||n===Ge.Xor?Pc(t):[];if(o.length===0)return n===Ge.Intersection?[]:Pc(i);const s=new I0;return _r.booleanOpDWithPolyTree(MP[n],e,o,s,we.EvenOdd,w0),E0(s)}function S0(i){if(i.length<3)return[];const t=new I0;return _r.booleanOpDWithPolyTree(Ce.Union,[Qu(i)],null,t,we.EvenOdd,w0),E0(t)}const js=.01,AP=js*js;function C0(i,t){const n=i[0]-t[0],e=i[1]-t[1];return n*n+e*e}function LP(i,t){return i.minX<=t.maxX+js&&t.minX<=i.maxX+js&&i.minY<=t.maxY+js&&t.minY<=i.maxY+js}function OP(i,t){for(let n=0;n<i.length;n++)for(let e=0;e<t.length;e++)if(C0(i[n],t[e])<=AP)return!0;return!1}function b0(i,t){const n=ea(t)!==ea(i)?[...t].reverse():t;let e=1/0,o=0,s=0;for(let r=0;r<i.length;r++)for(let c=0;c<n.length;c++){const l=C0(i[r],n[c]);l<e&&(e=l,o=r,s=c)}const a=[...n.slice(s),...n.slice(0,s)];return[...i.slice(0,o+1),...a,a[0],...i.slice(o+1)]}function RP(i){const t=i.length,n=Array.from({length:t},(r,c)=>c),e=r=>{let c=r;for(;n[c]!==c;)c=n[c];for(;n[r]!==c;){const l=n[r];n[r]=c,r=l}return c},o=(r,c)=>{n[e(r)]=e(c)},s=i.map(r=>Ei(r));for(let r=0;r<t;r++)for(let c=r+1;c<t;c++)LP(s[r],s[c])&&OP(i[r],i[c])&&o(r,c);const a=new Map;for(let r=0;r<t;r++){const c=e(r),l=a.get(c);l?l.push(r):a.set(c,[r])}return[...a.values()]}function _0(i){if(i.length<2)return i;const t=i.map(e=>e.outer),n=RP(t);return n.length===i.length?i:n.map(e=>{if(e.length===1)return i[e[0]];let o=i[e[0]].outer;for(let a=1;a<e.length;a++)o=b0(o,i[e[a]].outer);const s=e.flatMap(a=>i[a].holes??[]);return s.length?{outer:o,holes:s}:{outer:o}})}function NP(i){const t=S0(i);if(t.length===0||t.length===1&&!t[0].holes?.length)return i;const e=_0(t).reduce((s,a)=>ms(a.outer)>ms(s.outer)?a:s);let o=e.outer;for(const s of e.holes??[])o=b0(o,s);return o}const{addCanvasPointsToArray:uf,pointsAreWithinCloseContourProximity:hf,getFirstLineSegmentIntersectionIndexes:y0,getSubPixelSpacingAndXYDirections:kP}=Yi;function UP(i,t,n){const e=i.detail,{currentPoints:o,element:s}=e,a=o.canvas,r=N(s),{viewport:c}=r,l=Pa(i.detail.event)===this.configuration.contourHoleAdditionModifierKey,{spacing:d,xDir:u,yDir:h}=kP(c,this.configuration.subPixelResolution)||{};!d||!u||!h||(this.isDrawing=!0,this.drawData={canvasPoints:[a],polylineIndex:0,contourHoleProcessingEnabled:l,newAnnotation:!0},this.commonData={annotation:t,viewportIdsToRender:n,spacing:d,xDir:u,yDir:h,movingTextBox:!1},$.isInteractingWithTool=!0,s.addEventListener(E.MOUSE_UP,this.mouseUpDrawCallback),s.addEventListener(E.MOUSE_DRAG,this.mouseDragDrawCallback),s.addEventListener(E.MOUSE_CLICK,this.mouseUpDrawCallback),s.addEventListener(E.TOUCH_END,this.mouseUpDrawCallback),s.addEventListener(E.TOUCH_DRAG,this.mouseDragDrawCallback),s.addEventListener(E.TOUCH_TAP,this.mouseUpDrawCallback),wt(s))}function VP(i){$.isInteractingWithTool=!1,i.removeEventListener(E.MOUSE_UP,this.mouseUpDrawCallback),i.removeEventListener(E.MOUSE_DRAG,this.mouseDragDrawCallback),i.removeEventListener(E.MOUSE_CLICK,this.mouseUpDrawCallback),i.removeEventListener(E.TOUCH_END,this.mouseUpDrawCallback),i.removeEventListener(E.TOUCH_DRAG,this.mouseDragDrawCallback),i.removeEventListener(E.TOUCH_TAP,this.mouseUpDrawCallback),Ft(i)}function FP(i){const t=i.detail,{currentPoints:n,element:e}=t,o=n.world,s=n.canvas,a=N(e),{viewport:r}=a,{annotation:c,viewportIdsToRender:l,xDir:d,yDir:u,spacing:h,movingTextBox:f}=this.commonData,{polylineIndex:g,canvasPoints:m,newAnnotation:p}=this.drawData;this.createMemo(e,c,{newAnnotation:p});const v=m[m.length-1],I=r.canvasToWorld(v),w=B();Oe(w,o,I);const C=Math.abs(xt(w,d)),S=Math.abs(xt(w,u));if(!(C<=h[0]&&S<=h[1])){if(f){this.isDrawing=!1;const{deltaPoints:b}=t,_=b.world,{textBox:y}=c.data.handles,{worldPosition:D}=y;D[0]+=_[0],D[1]+=_[1],D[2]+=_[2],y.hasMoved=!0}else{const b=this.findCrossingIndexDuringCreate(i);if(b!==void 0&&hf(m[0],m[b],this.configuration.closeContourProximity))this.applyCreateOnCross(i,b);else{const y=uf(e,m,s,this.commonData);this.drawData.polylineIndex=g+y}c.invalidated=!0}V(l),c.invalidated&&zt(c,e,Bt.HandlesUpdated)}}function GP(i){const{allowOpenContours:t}=this.configuration,{canvasPoints:n,contourHoleProcessingEnabled:e}=this.drawData,o=n[0],s=n[n.length-1],a=i.detail,{element:r}=a;this.doneEditMemo(),this.drawData.newAnnotation=!1,t&&!hf(o,s,this.configuration.closeContourProximity)?this.completeDrawOpenContour(r,{contourHoleProcessingEnabled:e}):this.completeDrawClosedContour(r,{contourHoleProcessingEnabled:e})}function HP(i,t){this.removeCrossedLinesOnCompleteDraw();const{canvasPoints:n}=this.drawData,{contourHoleProcessingEnabled:e,minPointsToSave:o}=t??{};if(o&&n.length<o||this.haltDrawing(i,n))return!1;const{annotation:s,viewportIdsToRender:a,movingTextBox:r}=this.commonData,c=N(i),{viewport:l}=c;uf(i,n,n[0],this.commonData),n.pop();const d=sd(this.configuration,s)?ad(this.configuration,n):n,u=NP(d);this.updateContourPolyline(s,{points:u,closed:!0,targetWindingDirection:Qe.Clockwise},l);const{textBox:h}=s.data.handles;return!h?.hasMoved&&!r&&Hl(s,e),this.isDrawing=!1,this.drawData=void 0,this.commonData=void 0,V(a),this.deactivateDraw(i),!0}function WP(){const{canvasPoints:i}=this.drawData,t=i.length,n=[i[0],i[t-1]],e=i.slice(0,-1).slice(1),o=y0(e,n[0],n[1],!1);if(o){const s=o[1];s===1?this.drawData.canvasPoints=i.splice(1):this.drawData.canvasPoints=i.splice(0,s)}}function BP(i,t){const{canvasPoints:n}=this.drawData,{contourHoleProcessingEnabled:e}=t??{};if(this.haltDrawing(i,n))return!1;const{annotation:o,viewportIdsToRender:s,movingTextBox:a}=this.commonData,r=N(i),{viewport:c}=r,l=sd(this.configuration,o)?ad(this.configuration,n):n;this.updateContourPolyline(o,{points:l,closed:!1},c);const{textBox:d}=o.data.handles,u=o.data.contour.polyline;return o.data.handles.points=[u[0],u[u.length-1]],!o.data.isOpenUShapeContour&&this.configuration?.openUShapeContour&&(o.data.isOpenUShapeContour=this.configuration.openUShapeContour),o.data.isOpenUShapeContour&&(o.data.openUShapeContourVectorToPeak=lf(n,c,o.data.isOpenUShapeContour)),!d.hasMoved&&!a&&Hl(o,e),this.isDrawing=!1,this.drawData=void 0,this.commonData=void 0,V(s),this.deactivateDraw(i),!0}function zP(i){const t=i.detail,{currentPoints:n,lastPoints:e}=t,o=n.canvas,s=e.canvas,{canvasPoints:a}=this.drawData,r=a.slice(0,-1),c=y0(r,o,s,!1);return c===void 0?void 0:c[0]}function $P(i,t){const n=i.detail,{element:e}=n,{canvasPoints:o,contourHoleProcessingEnabled:s}=this.drawData,{annotation:a,viewportIdsToRender:r}=this.commonData;uf(e,o,o[t],this.commonData),o.pop();const c=o.slice(t),l=ms(c);if(ve(l,0)){o.splice(t+1);return}o.splice(0,t);const d={contourHoleProcessingEnabled:s,minPointsToSave:3};this.completeDrawClosedContour(e,d)&&this.activateClosedContourEdit(i,a,r)}function jP(i){const{allowOpenContours:t}=this.configuration,{canvasPoints:n,contourHoleProcessingEnabled:e}=this.drawData,o=n[0],s=n[n.length-1];t&&!hf(o,s,this.configuration.closeContourProximity)?this.completeDrawOpenContour(i,{contourHoleProcessingEnabled:e}):this.completeDrawClosedContour(i,{contourHoleProcessingEnabled:e})}function XP(i,t){const n=Math.max(t*3,3);return i.length<n}function qP(i,t){const{subPixelResolution:n}=this.configuration;if(XP(t,n)){const{annotation:e,viewportIdsToRender:o}=this.commonData;return Gt(e.annotationUID),this.isDrawing=!1,this.drawData=void 0,this.commonData=void 0,V(o),this.deactivateDraw(i),!0}return!1}function YP(i){i.activateDraw=UP.bind(i),i.deactivateDraw=VP.bind(i),i.applyCreateOnCross=$P.bind(i),i.findCrossingIndexDuringCreate=zP.bind(i),i.completeDrawOpenContour=BP.bind(i),i.removeCrossedLinesOnCompleteDraw=WP.bind(i),i.mouseDragDrawCallback=FP.bind(i),i.mouseUpDrawCallback=GP.bind(i),i.completeDrawClosedContour=HP.bind(i),i.cancelDrawing=jP.bind(i),i.haltDrawing=qP.bind(i)}const{addCanvasPointsToArray:KP,getFirstLineSegmentIntersectionIndexes:ps}=Yi;function ZP(i,t){const n=i.detail,{element:e,currentPoints:o,lastPoints:s}=n,a=o.canvas,r=s.canvas,{editCanvasPoints:c,prevCanvasPoints:l}=this.editData,d=ps(l,a,r,t);if(d)this.editData.startCrossingIndex=d[0],this.removePointsUpUntilFirstCrossing(t);else if(l.length>=2)if(c.length>this.configuration.checkCanvasEditFallbackProximity){const u=c[0],h=[];for(let m=0;m<l.length;m++){const p=l[m],v=_e(p,u);h.push({distance:v,index:m})}h.sort((m,p)=>m.distance-p.distance);const f=[h[0],h[1]],g=Math.min(f[0].index,f[1].index);this.editData.startCrossingIndex=g}else{const u=It();pe(u,c[1],c[0]),Ao(u,u);const h=6,f=[c[0][0]-u[0]*h,c[0][1]-u[1]*h],g=ps(l,f,c[0],t);if(g){const m=[f];KP(e,m,c[0],this.commonData),c.unshift(...m),this.removePointsUpUntilFirstCrossing(t),this.editData.editIndex=c.length-1,this.editData.startCrossingIndex=g[0]}}}function JP(i){const{editCanvasPoints:t,prevCanvasPoints:n}=this.editData;let e=0;for(let o=0;o<t.length-1;o++){const s=[t[o],t[o+1]],a=!!ps(n,s[0],s[1],i);if(e++,a)break}t.splice(0,e),this.editData.editIndex=t.length-1}function QP(i,t){const n=i.detail,{currentPoints:e,lastPoints:o}=n,s=e.canvas,a=o.canvas,{prevCanvasPoints:r}=this.editData;return!!ps(r,s,a,t)}function tD(i){const{prevCanvasPoints:t,editCanvasPoints:n}=this.editData;for(let e=n.length-1;e>0;e--){const o=[n[e],n[e-1]],s=!!ps(t,o[0],o[1],i);if(n.pop(),s)break}}function eD(){const{editCanvasPoints:i,prevCanvasPoints:t,startCrossingIndex:n}=this.editData;if(n===void 0)return;const e=i[i.length-1],o=[];for(let a=0;a<t.length;a++){const r=t[a],c=_e(r,e);o.push({distance:c,index:a})}o.sort((a,r)=>a.distance-r.distance);const s=i.slice(0,-1);for(let a=0;a<o.length;a++){const{index:r}=o[a],c=t[r],l=i[i.length-1];if(!ps(s,c,l,!1))return r}return-1}function nD(i){const t=i.detail,{currentPoints:n,lastPoints:e}=t,o=n.canvas,s=e.canvas,{editCanvasPoints:a}=this.editData,r=a.slice(0,-2),c=ps(r,o,s,!1);if(!c)return;const l=c[0],d=a.length-l;for(let u=0;u<d;u++)a.pop()}function oD(i){i.checkForFirstCrossing=ZP.bind(i),i.removePointsUpUntilFirstCrossing=JP.bind(i),i.checkForSecondCrossing=QP.bind(i),i.findSnapIndex=eD.bind(i),i.removePointsAfterSecondCrossing=tD.bind(i),i.checkAndRemoveCrossesOnEditLine=nD.bind(i)}function io(i,t,n,e){const{canvasToWorld:o,worldToCanvas:s}=n,{data:a}=i,{targetWindingDirection:r}=t;let{points:c}=t,l=ea(c);e?.decimate?.enabled&&(c=ed(t.points,e?.decimate?.epsilon));let{closed:d}=t;const u=c.length,h=new Array(u);ea(c);const f=jv(i);if(d===void 0){let g=!1;if(c.length>3){const m=wi(c[0],c[u-1]);g=ve(0,m)}d=g}if(e?.updateWindingDirection!==!1){let g=f?f.data.contour.windingDirection*-1:r;g===void 0&&(g=l),g!==l&&c.reverse();const m=(a.handles?.points??[]).map(s);m.length>2&&ea(m)!==g&&a.handles.points.reverse(),l=g}for(let g=0;g<u;g++)h[g]=o(c[g]);a.contour.polyline=h,a.contour.closed=d,a.contour.windingDirection=l,Vh(i)}const{getSubPixelSpacingAndXYDirections:iD,addCanvasPointsToArray:x0,getArea:_m}=Yi;function sD(i,t,n){this.isEditingClosed=!0;const e=i.detail,{currentPoints:o,element:s}=e,a=o.canvas,r=N(s);if(!r)return;const{viewport:c}=r,l=t.data.contour.polyline.map(c.worldToCanvas),{spacing:d,xDir:u,yDir:h}=iD(c,this.configuration.subPixelResolution);this.editData={prevCanvasPoints:l,editCanvasPoints:[a],startCrossingIndex:void 0,editIndex:0,annotation:t},this.commonData={annotation:t,viewportIdsToRender:n,spacing:d,xDir:u,yDir:h,movingTextBox:!1},$.isInteractingWithTool=!0,s.addEventListener(E.MOUSE_UP,this.mouseUpClosedContourEditCallback),s.addEventListener(E.MOUSE_DRAG,this.mouseDragClosedContourEditCallback),s.addEventListener(E.MOUSE_CLICK,this.mouseUpClosedContourEditCallback),s.addEventListener(E.TOUCH_END,this.mouseUpClosedContourEditCallback),s.addEventListener(E.TOUCH_DRAG,this.mouseDragClosedContourEditCallback),s.addEventListener(E.TOUCH_TAP,this.mouseUpClosedContourEditCallback),wt(s)}function aD(i){$.isInteractingWithTool=!1,i.removeEventListener(E.MOUSE_UP,this.mouseUpClosedContourEditCallback),i.removeEventListener(E.MOUSE_DRAG,this.mouseDragClosedContourEditCallback),i.removeEventListener(E.MOUSE_CLICK,this.mouseUpClosedContourEditCallback),i.removeEventListener(E.TOUCH_END,this.mouseUpClosedContourEditCallback),i.removeEventListener(E.TOUCH_DRAG,this.mouseDragClosedContourEditCallback),i.removeEventListener(E.TOUCH_TAP,this.mouseUpClosedContourEditCallback),Ft(i)}function rD(i){const t=i.detail,{currentPoints:n,element:e}=t,o=n.world,s=n.canvas,a=N(e),{viewport:r}=a,{viewportIdsToRender:c,xDir:l,yDir:d,spacing:u}=this.commonData,{editIndex:h,editCanvasPoints:f,startCrossingIndex:g,annotation:m}=this.editData;this.createMemo(e,m);const p=f[f.length-1],v=r.canvasToWorld(p),I=B();Oe(I,o,v);const w=Math.abs(xt(I,l)),C=Math.abs(xt(I,d));if(w<=u[0]&&C<=u[1])return;g!==void 0&&this.checkAndRemoveCrossesOnEditLine(i);const S=x0(e,f,s,this.commonData),b=h+S;if(this.editData.editIndex=b,g===void 0&&f.length>1&&this.checkForFirstCrossing(i,!0),this.editData.snapIndex=this.findSnapIndex(),this.editData.snapIndex===-1){this.finishEditAndStartNewEdit(i);return}this.editData.fusedCanvasPoints=this.fuseEditPointsWithClosedContour(i),g!==void 0&&this.checkForSecondCrossing(i,!0)&&(this.removePointsAfterSecondCrossing(!0),this.finishEditAndStartNewEdit(i)),V(c)}function cD(i){const t=i.detail,{element:n}=t,e=N(n),{viewport:o,renderingEngine:s}=e,{annotation:a,viewportIdsToRender:r}=this.commonData,{fusedCanvasPoints:c,editCanvasPoints:l}=this.editData;io(a,{points:c,closed:!0,targetWindingDirection:Qe.Clockwise},o),a.autoGenerated&&(a.autoGenerated=!1),zt(a,n);const d=l.pop();this.editData={prevCanvasPoints:c,editCanvasPoints:[d],startCrossingIndex:void 0,editIndex:0,snapIndex:void 0,annotation:a},V(r)}function lD(i){const{prevCanvasPoints:t,editCanvasPoints:n,startCrossingIndex:e,snapIndex:o}=this.editData;if(e===void 0||o===void 0)return;const s=i.detail,{element:a}=s,r=[...n];x0(a,r,t[o],this.commonData),r.length>n.length&&r.pop();let c,l;e>o?(c=o,l=e):(c=e,l=o);const d=_e(t[c],r[0]),u=_e(t[c],r[r.length-1]),h=_e(t[l],r[0]),f=_e(t[l],r[r.length-1]),g=[];for(let S=0;S<c;S++){const b=t[S];g.push([b[0],b[1]])}let m=d+f,p=u+h;if(m<p)for(let S=0;S<r.length;S++){const b=r[S];g.push([b[0],b[1]])}else for(let S=r.length-1;S>=0;S--){const b=r[S];g.push([b[0],b[1]])}for(let S=l;S<t.length;S++){const b=t[S];g.push([b[0],b[1]])}const v=[];for(let S=c;S<l;S++){const b=t[S];v.push([b[0],b[1]])}if(m=h+u,p=f+d,m<p)for(let S=0;S<r.length;S++){const b=r[S];v.push([b[0],b[1]])}else for(let S=r.length-1;S>=0;S--){const b=r[S];v.push([b[0],b[1]])}const I=_m(g),w=_m(v);return I>w?g:v}function dD(i){const t=i.detail,{element:n}=t;this.completeClosedContourEdit(n)}function uD(i){const t=N(i),{viewport:n}=t,{annotation:e,viewportIdsToRender:o}=this.commonData;this.doneEditMemo();const{fusedCanvasPoints:s,prevCanvasPoints:a}=this.editData;if(s){const r=sd(this.configuration,e)?ad(this.configuration,s,a):s,c=this.configuration?.decimate||{};io(e,{points:r,closed:!0,targetWindingDirection:Qe.Clockwise},n,{decimate:{enabled:!!c.enabled,epsilon:c.epsilon}}),e.autoGenerated&&(e.autoGenerated=!1),zt(e,i)}this.isEditingClosed=!1,this.editData=void 0,this.commonData=void 0,V(o),this.deactivateClosedContourEdit(i)}function hD(i){this.completeClosedContourEdit(i)}function fD(i){i.activateClosedContourEdit=sD.bind(i),i.deactivateClosedContourEdit=aD.bind(i),i.mouseDragClosedContourEditCallback=rD.bind(i),i.mouseUpClosedContourEditCallback=dD.bind(i),i.finishEditAndStartNewEdit=cD.bind(i),i.fuseEditPointsWithClosedContour=lD.bind(i),i.cancelClosedContourEdit=hD.bind(i),i.completeClosedContourEdit=uD.bind(i)}const{addCanvasPointsToArray:P0,getSubPixelSpacingAndXYDirections:gD}=Yi;function mD(i,t,n){this.isEditingOpen=!0;const e=i.detail,{currentPoints:o,element:s}=e,a=o.canvas,r=N(s),{viewport:c}=r;this.doneEditMemo();const l=t.data.contour.polyline.map(c.worldToCanvas),{spacing:d,xDir:u,yDir:h}=gD(c,this.configuration.subPixelResolution);this.editData={prevCanvasPoints:l,editCanvasPoints:[a],startCrossingIndex:void 0,editIndex:0},this.commonData={annotation:t,viewportIdsToRender:n,spacing:d,xDir:u,yDir:h,movingTextBox:!1},$.isInteractingWithTool=!0,s.addEventListener(E.MOUSE_UP,this.mouseUpOpenContourEditCallback),s.addEventListener(E.MOUSE_DRAG,this.mouseDragOpenContourEditCallback),s.addEventListener(E.MOUSE_CLICK,this.mouseUpOpenContourEditCallback),s.addEventListener(E.TOUCH_END,this.mouseUpOpenContourEditCallback),s.addEventListener(E.TOUCH_DRAG,this.mouseDragOpenContourEditCallback),s.addEventListener(E.TOUCH_TAP,this.mouseUpOpenContourEditCallback),wt(s)}function pD(i){$.isInteractingWithTool=!1,i.removeEventListener(E.MOUSE_UP,this.mouseUpOpenContourEditCallback),i.removeEventListener(E.MOUSE_DRAG,this.mouseDragOpenContourEditCallback),i.removeEventListener(E.MOUSE_CLICK,this.mouseUpOpenContourEditCallback),i.removeEventListener(E.TOUCH_END,this.mouseUpOpenContourEditCallback),i.removeEventListener(E.TOUCH_DRAG,this.mouseDragOpenContourEditCallback),i.removeEventListener(E.TOUCH_TAP,this.mouseUpOpenContourEditCallback),Ft(i)}function vD(i){const t=i.detail,{currentPoints:n,element:e}=t,o=n.world,s=n.canvas,a=N(e),{viewport:r}=a,{viewportIdsToRender:c,xDir:l,yDir:d,spacing:u}=this.commonData,{editIndex:h,editCanvasPoints:f,startCrossingIndex:g}=this.editData,m=f[f.length-1],p=r.canvasToWorld(m),v=B();this.createMemo(e,this.commonData.annotation),Oe(v,o,p);const I=Math.abs(xt(v,l)),w=Math.abs(xt(v,d));if(I<=u[0]&&w<=u[1])return;g!==void 0&&this.checkAndRemoveCrossesOnEditLine(i);const C=P0(e,f,s,this.commonData),S=h+C;this.editData.editIndex=S,g===void 0&&f.length>1&&this.checkForFirstCrossing(i,!1),this.editData.snapIndex=this.findSnapIndex(),this.editData.fusedCanvasPoints=this.fuseEditPointsWithOpenContour(i),g!==void 0&&this.checkForSecondCrossing(i,!1)?(this.removePointsAfterSecondCrossing(!1),this.finishEditOpenOnSecondCrossing(i)):this.checkIfShouldOverwriteAnEnd(i)&&this.openContourEditOverwriteEnd(i),V(c)}function ID(i){const t=i.detail,{element:n}=t,e=N(n),{viewport:o}=e,{annotation:s,viewportIdsToRender:a}=this.commonData,r=this.fuseEditPointsForOpenContourEndEdit();io(s,{points:r,closed:!1},o);const c=s.data.contour.polyline;s.data.handles.points=[c[0],c[c.length-1]],s.data.handles.activeHandleIndex=1,zt(s,n),this.isEditingOpen=!1,this.editData=void 0,this.commonData=void 0,this.doneEditMemo(),this.deactivateOpenContourEdit(n),this.activateOpenContourEndEdit(i,s,a,null)}function wD(i){const t=i.detail,{currentPoints:n,lastPoints:e}=t,o=n.canvas,s=e.canvas,{snapIndex:a,prevCanvasPoints:r,startCrossingIndex:c}=this.editData;if(c===void 0||a===void 0)return!1;if(a===-1)return!0;if(a!==0&&a!==r.length-1)return!1;const l=o,d=s,u=r[a],h=It(),f=It();mo(h,l[0]-d[0],l[1]-d[1]),mo(f,l[0]-u[0],l[1]-u[1]);const g=zo(h,f),m=Math.sqrt(h[0]*h[0]+h[1]*h[1]),p=Math.sqrt(f[0]*f[0]+f[1]*f[1]);return Math.acos(g/(m*p))<Math.PI/2}function ED(){const{snapIndex:i,prevCanvasPoints:t,editCanvasPoints:n,startCrossingIndex:e}=this.editData,o=[];if(i===0)for(let r=t.length-1;r>=e;r--){const c=t[r];o.push([c[0],c[1]])}else for(let r=0;r<e;r++){const c=t[r];o.push([c[0],c[1]])}const s=_e(t[e],n[0]),a=_e(t[e],n[n.length-1]);if(s<a)for(let r=0;r<n.length;r++){const c=n[r];o.push([c[0],c[1]])}else for(let r=n.length-1;r>=0;r--){const c=n[r];o.push([c[0],c[1]])}return o}function SD(i){const{prevCanvasPoints:t,editCanvasPoints:n,startCrossingIndex:e,snapIndex:o}=this.editData;if(e===void 0||o===void 0)return;const s=i.detail,{element:a}=s,r=[...n];P0(a,r,t[o],this.commonData),r.length>n.length&&r.pop();let c,l;e>o?(c=o,l=e):(c=e,l=o);const d=_e(t[c],r[0]),u=_e(t[c],r[r.length-1]),h=_e(t[l],r[0]),f=_e(t[l],r[r.length-1]),g=[];for(let v=0;v<c;v++){const I=t[v];g.push([I[0],I[1]])}const m=d+f,p=u+h;if(m<p)for(let v=0;v<r.length;v++){const I=r[v];g.push([I[0],I[1]])}else for(let v=r.length-1;v>=0;v--){const I=r[v];g.push([I[0],I[1]])}for(let v=l;v<t.length;v++){const I=t[v];g.push([I[0],I[1]])}return g}function CD(i){const t=i.detail,{element:n}=t,e=N(n),{viewport:o,renderingEngine:s}=e,{annotation:a,viewportIdsToRender:r}=this.commonData,{fusedCanvasPoints:c,editCanvasPoints:l}=this.editData;io(a,{points:c,closed:!1},o);const d=a.data.contour.polyline;a.data.handles.points=[d[0],d[d.length-1]],zt(a,n);const u=l.pop();this.editData={prevCanvasPoints:c,editCanvasPoints:[u],startCrossingIndex:void 0,editIndex:0},V(r)}function bD(i){const t=i.detail,{element:n}=t;this.completeOpenContourEdit(n)}function _D(i){const t=N(i),{viewport:n}=t,{annotation:e,viewportIdsToRender:o}=this.commonData;this.doneEditMemo();const{fusedCanvasPoints:s,prevCanvasPoints:a}=this.editData;if(s){const r=sd(this.configuration)?ad(this.configuration,s,a):s,c=this.configuration?.decimate||{};io(e,{points:r,closed:!1},n,{decimate:{enabled:!!c.enabled,epsilon:c.epsilon}});const l=e.data.contour.polyline;e.data.handles.points=[l[0],l[l.length-1]],e.data.isOpenUShapeContour&&(e.data.openUShapeContourVectorToPeak=lf(s,n,e.data.isOpenUShapeContour)),zt(e,i)}this.isEditingOpen=!1,this.editData=void 0,this.commonData=void 0,V(o),this.deactivateOpenContourEdit(i)}function yD(i){this.completeOpenContourEdit(i)}function xD(i){i.activateOpenContourEdit=mD.bind(i),i.deactivateOpenContourEdit=pD.bind(i),i.mouseDragOpenContourEditCallback=vD.bind(i),i.mouseUpOpenContourEditCallback=bD.bind(i),i.fuseEditPointsWithOpenContour=SD.bind(i),i.finishEditOpenOnSecondCrossing=CD.bind(i),i.checkIfShouldOverwriteAnEnd=wD.bind(i),i.fuseEditPointsForOpenContourEndEdit=ED.bind(i),i.openContourEditOverwriteEnd=ID.bind(i),i.cancelOpenContourEdit=yD.bind(i),i.completeOpenContourEdit=_D.bind(i)}const{getSubPixelSpacingAndXYDirections:PD}=Yi;function DD(i,t,n,e){this.isDrawing=!0;const o=i.detail,{element:s}=o,a=N(s),{viewport:r}=a,{spacing:c,xDir:l,yDir:d}=PD(r,this.configuration.subPixelResolution),u=t.data.contour.polyline.map(r.worldToCanvas);t.data.handles.activeHandleIndex===0&&u.reverse();let f=!1;e?.worldPosition&&(f=!0),this.drawData={canvasPoints:u,polylineIndex:u.length-1},this.commonData={annotation:t,viewportIdsToRender:n,spacing:c,xDir:l,yDir:d,movingTextBox:f},$.isInteractingWithTool=!0,s.addEventListener(E.MOUSE_UP,this.mouseUpDrawCallback),s.addEventListener(E.MOUSE_DRAG,this.mouseDragDrawCallback),s.addEventListener(E.MOUSE_CLICK,this.mouseUpDrawCallback),s.addEventListener(E.TOUCH_END,this.mouseUpDrawCallback),s.addEventListener(E.TOUCH_DRAG,this.mouseDragDrawCallback),s.addEventListener(E.TOUCH_TAP,this.mouseUpDrawCallback),wt(s)}function TD(i){i.activateOpenContourEndEdit=DD.bind(i)}function D0(i){return(i.childAnnotationUIDs??[]).map(n=>ne(n).data.contour.polyline)}function oc(i,t){const n=D0(i),e=[];return n.forEach(o=>{const s=o.length,a=new Array(s);for(let r=0;r<s;r++)a[r]=t.worldToCanvas(o[r]);e.push(a)}),e}const{pointsAreWithinCloseContourProximity:MD}=Yi;function AD(i,t){const n={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:i.viewport.id,annotationUID:t.annotationUID},{lineWidth:e,lineDash:o,color:s,fillColor:a,fillOpacity:r}=this.getAnnotationStyle({annotation:t,styleSpecifier:n}),{closed:c}=t.data.contour;return{color:s,width:e,lineDash:o,fillColor:a,fillOpacity:this.configuration?.fillOpacity!==void 0?this.configuration.fillOpacity:r,closePath:c}}function LD(i,t,n){i?.viewport?.getImageData()&&(n.data.contour.closed?this.renderClosedContour(i,t,n):n.data.isOpenUShapeContour?(n.data.isOpenUShapeContour!=="lineSegment"&&OD(i,n),this.renderOpenUShapedContour(i,t,n)):this.renderOpenContour(i,t,n))}function OD(i,t){t.data.openUShapeContourVectorToPeak||(t.data.openUShapeContourVectorToPeak=wP(i,t))}function RD(i,t,n){if(n.parentAnnotationUID)return;const{viewport:e}=i,o=this._getRenderingOptions(i,n),s=n.data.contour.polyline.map(l=>e.worldToCanvas(l)),a=oc(n,e),r=[s,...a];ko(t,n.annotationUID,"1",r,o)}function ND(i,t,n){const{viewport:e}=i,o=this._getRenderingOptions(i,n),s=n.data.contour.polyline.map(c=>e.worldToCanvas(c));Eo(t,n.annotationUID,"1",s,o);const r=n.data.handles.activeHandleIndex;if(this.configuration.alwaysRenderOpenContourHandles?.enabled===!0){const c=this.configuration.alwaysRenderOpenContourHandles.radius,l="0",d=[s[0],s[s.length-1]];r===0?d.shift():r===1&&d.pop(),xe(t,n.annotationUID,l,d,{color:o.color,handleRadius:c})}if(r!==null){const l=r===0?0:s.length-1,d=s[l];xe(t,n.annotationUID,"1",[d],{color:o.color})}}function kD(i,t,n){const{viewport:e}=i,{openUShapeContourVectorToPeak:o}=n.data,{polyline:s}=n.data.contour;this.renderOpenContour(i,t,n);const a=n.data.isOpenUShapeContour==="lineSegment";if(!a&&!o)return;const r=e.worldToCanvas(s[0]),c=e.worldToCanvas(s[s.length-1]),l=this._getRenderingOptions(i,n);if(Eo(t,n.annotationUID,"first-to-last",[r,c],{color:l.color,width:l.width,closePath:!1,lineDash:"2,2"}),!a){const d=[e.worldToCanvas(o[0]),e.worldToCanvas(o[1])];Eo(t,n.annotationUID,"midpoint-to-open-contour",[d[0],d[1]],{color:l.color,width:l.width,closePath:!1,lineDash:"2,2"})}if(l.fillOpacity>0){const d=s.map(u=>e.worldToCanvas(u));ko(t,n.annotationUID,"u-shape-fill",[[...d,r]],{color:l.fillColor||l.color,fillColor:l.fillColor||l.color,fillOpacity:l.fillOpacity,closePath:!0,width:0})}}function UD(i,t,n){const e=this._getRenderingOptions(i,n),{allowOpenContours:o}=this.configuration,{canvasPoints:s}=this.drawData;if(e.closePath=!1,Eo(t,n.annotationUID,"1",s,e),o){const a=s[0],r=s[s.length-1];MD(a,r,this.configuration.closeContourProximity)?Eo(t,n.annotationUID,"2",[r,a],e):xe(t,n.annotationUID,"0",[a],{color:e.color,handleRadius:2})}}function VD(i,t,n){const{viewport:e}=i,{fusedCanvasPoints:o}=this.editData;if(o===void 0){this.renderClosedContour(i,t,n);return}const s=oc(n,e),a=[o,...s],r=this._getRenderingOptions(i,n),c="preview-1";n.parentAnnotationUID&&r.fillOpacity&&(r.fillOpacity=0),ko(t,n.annotationUID,c,a,r)}function FD(i,t,n){const{fusedCanvasPoints:e}=this.editData;if(e===void 0){this.renderOpenContour(i,t,n);return}const o=this._getRenderingOptions(i,n);Eo(t,n.annotationUID,"preview-1",e,o)}function GD(i,t,n){if(n.parentAnnotationUID)return;const{viewport:e}=i,o=this._getRenderingOptions(i,n),s=n.data.contour.polyline.map(g=>e.worldToCanvas(g)),a=oc(n,e),r="1",c=s[0],l=6,d=100,u=[];for(let g=0;g<d;g++){const m=g/d*2*Math.PI,p=c[0]+l*Math.cos(m),v=c[1]+l*Math.sin(m);u.push([p,v])}const h=[[c[0]-l*2,c[1]],[c[0]+l*2,c[1]],[c[0],c[1]-l*2],[c[0],c[1]+l*2]];ko(t,n.annotationUID,r+"-crosshair_v",[h[0],h[1]],o),ko(t,n.annotationUID,r+"-crosshair_h",[h[2],h[3]],o);const f=[u,...a];ko(t,n.annotationUID,r,f,o)}function HD(i){i.renderContour=LD.bind(i),i.renderClosedContour=RD.bind(i),i.renderOpenContour=ND.bind(i),i.renderPointContourWithMarker=GD.bind(i),i.renderOpenUShapedContour=kD.bind(i),i.renderContourBeingDrawn=UD.bind(i),i.renderClosedContourBeingEdited=VD.bind(i),i.renderOpenContourBeingEdited=FD.bind(i),i._getRenderingOptions=AD.bind(i)}function Ki(i,t){return!!Lh(i,t)?.isPreScaled}const WD=["SEG","RTSTRUCT","RTPLAN","SR","PR","KO"],T0=({modality:i,representationUID:t})=>!t&&(!i||!WD.includes(i));function M0(i,t){if(!T0(i))return!1;const{targetPredicate:n}=t?.configuration??{};return n?n(i,t):!0}const BD=(i,t)=>{const n=i.find(e=>M0(e,t));return n?[n]:[]},zD=(i,t)=>i.filter(n=>M0(n,t)),$D=i=>i.length?[i[0]]:[],jD=i=>i,XD=(...i)=>({modality:t})=>i.includes(t),qD=i=>({displaySetUID:t,referencedId:n,targetId:e})=>t?.includes(i)||n?.includes(i)||e.includes(i),A0={isPixelData:T0,firstPixelData:BD,allPixelData:zD,first:$D,all:jD,forModality:XD,forId:qD},{DefaultHistoryMemo:Ns}=Nl;class Ee{get configurationTyped(){return this.configuration}constructor(t,n){this.handlesMultiTouchGestures=!1,this.isPrimary=!1;const e=Ee.mergeDefaultProps(Ee.defaults,n),o=Hn(e,t),{configuration:s={},supportedInteractionTypes:a,toolGroupId:r}=o;this.toolGroupId=r,this.supportedInteractionTypes=a||[],this.configuration=Object.assign({},s),this.mode=se.Disabled}static mergeDefaultProps(t={},n){return n?Hn(t,n):t}static isSpecifiedTargetId(t){return(n,{targetId:e})=>e.includes(t)}get toolName(){return this.getToolName()}getToolName(){return this.constructor.toolName}applyActiveStrategy(t,n){const{strategies:e,activeStrategy:o}=this.configuration;return e[o]?.call(this,t,n)}applyActiveStrategyCallback(t,n,e,...o){const{strategies:s,activeStrategy:a}=this.configuration;if(!s[a])throw new Error(`applyActiveStrategyCallback: active strategy ${a} not found, check tool configuration or spellings`);return s[a][e]?.call(this,t,n,...o)}setConfiguration(t){this.configuration=Hn(this.configuration,t)}setActiveStrategy(t){this.setConfiguration({activeStrategy:t})}_isTouchInteraction(t){const n=t?.detail?.eventName;return n===E.TOUCH_START||n===E.TOUCH_START_ACTIVATE||n===E.TOUCH_DRAG||n===E.TOUCH_END||n===E.TOUCH_TAP||n===E.TOUCH_PRESS}getTargetImageData(t){if(t.startsWith("imageId:")){const n=t.split("imageId:")[1],e=eo(n);let o=Uu(e);return!o||!o.length||(o=o.filter(s=>s.getCurrentImageId()===n),!o||!o.length)?void 0:o[0].getImageData()}else if(t.startsWith("volumeId:")){const n=Fi(t),e=yh(n);return!e||!e.length?void 0:e[0].getImageData(n)}else if(t.startsWith("videoId:")){const n=eo(t),e=Uu(n);return!e||!e.length?void 0:e[0].getImageData()}else throw new Error('getTargetIdImage: targetId must start with "imageId:" or "volumeId:"')}getTargetId(t,n){return this.getMeasurementTargets(t,n)[0]}getMeasurementTargets(t,n){const{targetsFilter:e,isPreferredTargetId:o}=this.configurationTyped;if(o&&n?.cachedStats){for(const[a,r]of Object.entries(n.cachedStats))if(o(t,{targetId:a,cachedStat:r}))return[a]}if(e){const a=this.getMeasurementTargetCandidates(t,n),r={viewport:t,configuration:this.configurationTyped,data:n};return e(a,r).map(c=>c.targetId)}const s=t.getViewReferenceId?.();if(s)return[s];throw new Error("getMeasurementTargets: viewport must have a getViewReferenceId method")}getMeasurementTargetCandidates(t,n){const e=[],o=Ee.getViewportDisplaySets(t),s=t.getActors?.()||[];for(let a=0;a<s.length;a++){const{referencedId:r,representationUID:c}=s[a];if(!r)continue;const l=Q.getVolume(r);if(!l)continue;const d=Ee.findCachedStatsTargetId(n,r)||t.getViewReferenceId?.({volumeId:r});if(!d)continue;const u=o.find(g=>g.volumeId===r),h=u?.imageIds??(l.imageIds?.length?l.imageIds:void 0),f=u?.instance??Ee.getExemplarInstance(h);e.push({targetId:d,referencedId:r,representationUID:c,displaySet:u?.displaySet,displaySetUID:u?.displaySetUID,instance:f,modality:f?.Modality??l.metadata?.Modality,imageIds:h,index:a})}if(!e.length){const a=t.getViewReferenceId?.();if(a){const r=o[0];e.push({targetId:a,index:0,displaySet:r?.displaySet,displaySetUID:r?.displaySetUID,instance:r?.instance,modality:r?.modality,imageIds:r?.imageIds})}}return e}static getViewportDisplaySets(t){const n=t.getDisplaySets?.();if(!n?.length)return[];const e=xh;return n.map(({displaySetId:o})=>{const s=e.get(e.VIEWPORT_V2_DISPLAY_SET,o),a=Array.isArray(s)?s:s?.imageIds,r=a?.map(u=>rn("displaySetModule",u)).find(u=>u!==void 0),c=r?.imageIds?.length?Array.from(r.imageIds):a,l=r??s,d=r?.instances?.[0]??Ee.getExemplarInstance(c);return{displaySetUID:r?.displaySetId??o,displaySet:l,instance:d,imageIds:c,volumeId:s?.volumeId,modality:d?.Modality??(c?.length?rn("generalSeriesModule",c[0])?.modality:void 0)}})}static getExemplarInstance(t){if(t?.length)return rn("instance",t[0])}static findCachedStatsTargetId(t,n){if(t?.cachedStats)return Object.keys(t.cachedStats).find(e=>e.startsWith("volumeId:")&&Fi(e)===n)}ensureCachedStatsTargets(t,n,e){let o=!1;const s=t.cachedStats??={};for(const a of n){const r=s[a];(!r||e?.(r))&&(s[a]={},o=!0)}return o}undo(){this.doneEditMemo(),Ns.undo()}redo(){Ns.redo()}static createZoomPanMemo(t){if(!gr(t)||!Zs(t))return;const n={pan:t.getPan(),zoom:t.getZoom()},e={restoreMemo:()=>{const o=t.getPan(),s=t.getZoom(),a=t;t.setZoom(n.zoom),t.setPan(n.pan),typeof a.render=="function"&&a.render(),n.pan=o,n.zoom=s}};return Ns.push(e),e}doneEditMemo(){this.memo?.commitMemo?.()&&Ns.push(this.memo),this.memo=null}static startGroupRecording(){Ns.startGroupRecording()}static endGroupRecording(){Ns.endGroupRecording()}static calculateLengthInIndex(t,n,e=!1){const o=t?.scale||1,s=t?.scaleY||o,a=t?.scaleZ||o;let r=0;const c=n.length,l=e?0:1;let d=e?n[c-1]:n[0];for(let u=l;u<c;u++){const h=n[u],f=(h[0]-d[0])/o,g=(h[1]-d[1])/s,m=(h[2]-d[2])/a;r+=Math.sqrt(f*f+g*g+m*m),d=h}return r}static isInsideVolume(t,n){const{length:e}=n;for(let o=0;o<e;o++)if(!rb(n[o],t))return!1;return!0}}Ee.TOUCH_PROXIMITY=$l;Ee.MOUSE_PROXIMITY=jl;Ee.TOUCH_TAP_MAX_CANVAS_DISTANCE=Gh;Ee.TOUCH_TAP_TOLERANCE_MS=Hh;Ee.defaults={configuration:{strategies:{},defaultStrategy:void 0,activeStrategy:void 0,strategyOptions:{}}};Ee.toolName="BaseTool";const Ui=new Set;function cd(i,t=!0){const n=O0();i&&(t?JD(i,Ui,n):R0(i,Ui,n)),N0(n,Ui)}function YD(){const i=O0();QD(Ui,i),N0(i,Ui)}function KD(){return Array.from(Ui)}function ze(i){return Ui.has(i)}function ZD(){return Ui.size}function L0(i){const t=ze(i);return cd(i,t),t}function O0(){return Object.freeze({added:[],removed:[],locked:[]})}function JD(i,t,n){if(!t.has(i)){t.add(i),n.added.push(i);const e=ne(i);e&&(e.isLocked=!0)}}function R0(i,t,n){if(t.delete(i)){n.removed.push(i);const e=ne(i);e&&(e.isLocked=!1)}}function QD(i,t){i.forEach(n=>{R0(n,i,t)})}function N0(i,t){(i.added.length>0||i.removed.length>0)&&(t.forEach(n=>{i.locked.push(n)}),Rt(Z,E.ANNOTATION_LOCK_CHANGE,i))}const tT=Object.freeze(Object.defineProperty({__proto__:null,checkAndSetAnnotationLocked:L0,getAnnotationsLocked:KD,getAnnotationsLockedCount:ZD,isAnnotationLocked:ze,setAnnotationLocked:cd,unlockAllAnnotations:YD},Symbol.toStringTag,{value:"Module"})),jo=new Set;function So(i,t=!0,n=!1){t?eT(i,n):ff(i)}function eT(i,t=!1){const n=U0();if(!t){V0(jo,n);const e=ne(i);e&&(e.isSelected=!0)}if(i&&!jo.has(i)){jo.add(i),n.added.push(i);const e=ne(i);e&&(e.isSelected=!0)}F0(n,jo)}function ff(i){const t=U0();if(i){if(jo.delete(i)){t.removed.push(i);const n=ne(i);n.isSelected=!1}}else V0(jo,t);F0(t,jo)}function k0(){return Array.from(jo)}function nT(i){return k0().filter(t=>ne(t)?.metadata?.toolName===i)}function ic(i){return jo.has(i)}function oT(){return jo.size}function U0(){return Object.freeze({added:[],removed:[],selection:[]})}function V0(i,t){i.forEach(n=>{if(i.delete(n)){t.removed.push(n);const e=ne(n);e&&(e.isSelected=!1)}})}function F0(i,t){(i.added.length>0||i.removed.length>0)&&(t.forEach(n=>{i.selection.push(n)}),Rt(Z,E.ANNOTATION_SELECTION_CHANGE,i))}const iT=Object.freeze(Object.defineProperty({__proto__:null,deselectAnnotation:ff,getAnnotationsSelected:k0,getAnnotationsSelectedByToolName:nT,getAnnotationsSelectedCount:oT,isAnnotationSelected:ic,setAnnotationSelected:So},Symbol.toStringTag,{value:"Module"}));function G0(i){if(i){if(i.data&&i.highlighted)return To.Highlighted;if(ic(i.annotationUID))return To.Selected;if(ze(i.annotationUID))return To.Locked;if(i.data&&i.autoGenerated)return To.AutoGenerated}return To.Default}function sT(i,t,n){const e=Nn("textBoxFontSize",i,t,n),o=Nn("textBoxFontFamily",i,t,n);return`${e}px ${o}`}const aT=Object.freeze(Object.defineProperty({__proto__:null,getFont:sT,getState:G0,style:Nh},Symbol.toStringTag,{value:"Module"}));class Ci extends Ee{constructor(){super(...arguments),this.onImageSpacingCalibrated=t=>{const{element:n,imageId:e}=t.detail,o=eo(e),s=Go();s.getFramesOfReference().forEach(r=>{const l=s.getAnnotations(r)[this.getToolName()];!l||!l.length||(l.forEach(d=>{if(!d.metadata?.referencedImageId)return;eo(d.metadata.referencedImageId)===o&&(d.invalidated=!0,d.data.cachedStats={})}),xa(n))})}}filterInteractableAnnotationsForElement(t,n){if(!n?.length)return[];const e=N(t),{viewport:o}=e;return ya(o,n)}static createAnnotation(...t){let n={annotationUID:null,highlighted:!0,invalidated:!0,isLocked:!1,isVisible:!0,metadata:{toolName:this.toolName},data:{handles:{points:new Array,activeHandleIndex:null,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}},cachedStats:{},label:""}};for(const e of t)n=Hn(n,e);return n}createAnnotation(t,n,...e){const o=t.detail,{currentPoints:s,element:a}=o,{world:r}=s,c=N(a),{viewport:l}=c,d=l.getViewReference({points:[r]}),{viewPlaneNormal:u,viewUp:h,position:f}=ht(l,d),g=d.referencedImageId||(u?this.getReferencedImageId(l,r,u,h):void 0);return Ci.createAnnotation({metadata:{toolName:this.getToolName(),...d,...g?{referencedImageId:g}:{},...h?{viewUp:h}:{},...f?{cameraPosition:f}:{}},data:{handles:{points:n||[]}}},...e)}getReferencedImageId(t,n,e,o){const s=this.getTargetId(t);let a=s.split(/^[a-zA-Z]+:/)[1];if(t instanceof pn){const r=Fi(s),c=Q.getVolume(r);a=qr(c,n,e)}return a}getStyle(t,n,e){return Nn(t,n,G0(e),this.mode)}}Ci.toolName="AnnotationDisplayTool";const vs=new Set;function H0(i,t=!0){const n=W0();i&&(t?B0(i,vs,n):cT(i,vs,n)),z0(n)}function rT(){const i=W0();vs.forEach(t=>{B0(t,vs,i)}),z0(i)}function $e(i){if(ne(i))return!vs.has(i)}function W0(){return Object.freeze({lastVisible:[],lastHidden:[],hidden:[]})}function B0(i,t,n){if(t.delete(i)){n.lastVisible.push(i);const e=ne(i);e.isVisible=!0}}function cT(i,t,n){if(!t.has(i)){t.add(i),ic(i)&&ff(i),n.lastHidden.push(i);const e=ne(i);e.isVisible=!1}}function z0(i){(i.lastHidden.length>0||i.lastVisible.length>0)&&(vs.forEach(t=>{i.hidden.push(t)}),Rt(Z,E.ANNOTATION_VISIBILITY_CHANGE,i))}function $0(i){const t=!vs.has(i);return H0(i,t),t}const lT=Object.freeze(Object.defineProperty({__proto__:null,checkAndSetAnnotationVisibility:$0,isAnnotationVisible:$e,setAnnotationVisibility:H0,showAllAnnotations:rT},Symbol.toStringTag,{value:"Module"})),dT="viewport-element",fl=6;function gf(i,t,n=[]){if(!i?.length||!i[0])return[0,0];const e=fT(i),o=(e.top[1]+e.bottom[1])/2,s=[e.right[0],o];if(!t)return s;const{width:a,height:r}=gT(n),c=4,l=t.clientWidth-c,d=t.clientHeight-c;let u=e.right[0],h=o-r/2;u+a>l&&(u=e.left[0]-a),u=Math.max(c,Math.min(u,l-a)),h=Math.max(c,Math.min(h,d-r));const f=hT(t);if(f){const g=tP(f);if(g.length>0){const m=uT(u,h,a,r,g,c,l,d);u=m[0],h=m[1]}}return[u,h]}function uT(i,t,n,e,o,s,a,r){if(!tu(i,t,n,e,o))return[i,t];let c=t;for(let l=0;l<30;l++){const d=ym(i,c,n,e,o);if(!d)break;if(c=d.y+d.height+fl,c+e>r){c=1/0;break}}if(c!==1/0&&!tu(i,c,n,e,o))return[i,Math.max(s,Math.min(c,r-e))];c=t;for(let l=0;l<30;l++){const d=ym(i,c,n,e,o);if(!d)break;if(c=d.y-e-fl,c<s){c=-1/0;break}}return c!==-1/0&&!tu(i,c,n,e,o)?[i,Math.max(s,Math.min(c,r-e))]:[i,t]}function tu(i,t,n,e,o){const s=gl({x:i,y:t,width:n,height:e});return o.some(a=>Qr(s,gl(a,fl/2)))}function ym(i,t,n,e,o){const s=gl({x:i,y:t,width:n,height:e});return o.find(a=>Qr(s,gl(a,fl/2)))}function gl(i,t=0){return{minX:i.x-t,minY:i.y-t,maxX:i.x+i.width+t,maxY:i.y+i.height+t}}function hT(i){return i.querySelector(`.${dT}`)?.querySelector(":scope > .svg-layer")||null}function fT(i){const t=i.filter(Boolean),n=t[0];if(!n||t.length<2)return{left:n,right:n,top:n,bottom:n};let e=n,o=n,s=n,a=n;for(let r=1;r<t.length;r++){const c=t[r];c[0]<e[0]&&(e=c),c[0]>o[0]&&(o=c),c[1]<s[1]&&(s=c),c[1]>a[1]&&(a=c)}return{left:e,top:s,bottom:a,right:o}}function gT(i){const o=i.reduce((c,l)=>Math.max(c,l?.length??0),0),s=Math.max(i.length,1),a=o*8+50,r=s*17+50;return{width:a,height:r}}const mT=Object.freeze(Object.defineProperty({__proto__:null,getTextBoxCoordsCanvas:gf},Symbol.toStringTag,{value:"Module"}));function j0(i,t){const{segmentation:n}=i.data,{segmentation:e}=t.data;return n.segmentationId===e.segmentationId&&n.segmentIndex===e.segmentIndex}function xm(i){return i==="__proto__"||i==="constructor"||i==="prototype"}class X0{constructor(t){this.getGroupKey=n=>{if(typeof n=="string")return n;const o=N(n);if(!o)throw new Error("Element not enabled, you must have an enabled element if you are not providing a FrameOfReferenceUID");return o.FrameOfReferenceUID},this._imageVolumeModifiedHandler=n=>{const e=n.detail,{FrameOfReferenceUID:o}=e,a=this.annotations[o];a&&Object.keys(a).forEach(r=>{a[r].forEach(l=>{l.invalidated!==void 0&&(l.invalidated=!0)})})},this.getFramesOfReference=()=>Object.keys(this.annotations),this.getAnnotations=(n,e)=>{const o=this.annotations;return o[n]?e?o[n][e]?o[n][e]:[]:o[n]:[]},this.getAnnotation=n=>{const e=this.annotations;for(const o in e){const s=e[o];for(const a in s){const r=s[a];for(const c of r)if(n===c.annotationUID)return c}}},this.getNumberOfAnnotations=(n,e)=>{const o=this.getAnnotations(n,e);if(!o.length)return 0;if(e)return o.length;let s=0;for(const a in o)s+=o[a].length;return s},this.addAnnotation=(n,e)=>{const{metadata:o}=n,{FrameOfReferenceUID:s,toolName:a}=o;if(e=e||s,xm(e)||xm(a))return;const r=this.annotations;let c=r[e];c||(r[e]={},c=r[e]);let l=c[a];l||(c[a]=[],l=c[a]),this.preprocessingFn&&(n=this.preprocessingFn(n)),l.push(n)},this.removeAnnotation=n=>{const{annotations:e}=this;for(const o in e){const s=e[o];for(const a in s){const r=s[a],c=r.findIndex(l=>l.annotationUID===n);c!==-1&&(r.splice(c,1),r.length===0&&delete s[a])}Object.keys(s).length===0&&delete e[o]}},this.removeAnnotations=(n,e)=>{const o=this.annotations,s=[];if(!o[n])return s;if(e){const a=o[n][e];if(a)for(const r of a)this.removeAnnotation(r.annotationUID),s.push(r)}else for(const a in o[n]){const r=o[n][a];for(const c of r)this.removeAnnotation(c.annotationUID),s.push(c)}return s},this.saveAnnotations=(n,e)=>{const o=this.annotations;if(n&&e){const s=o[n];if(!s)return;const a=s[e];return Re(a)}else if(n){const s=o[n];return Re(s)}return Re(o)},this.restoreAnnotations=(n,e,o)=>{const s=this.annotations;if(e&&o){let a=s[e];a||(s[e]={},a=s[e]),a[o]=n}else e?s[e]=n:this.annotations=Re(n)},this.getAllAnnotations=()=>Object.values(this.annotations).map(n=>Object.values(n)).flat(2),this.getNumberOfAllAnnotations=()=>{let n=0;const e=this.annotations;for(const o in e){const s=e[o];for(const a in s){const r=s[a];n+=r.length}}return n},this.removeAllAnnotations=()=>{const n=[];for(const e of this.getAllAnnotations())this.removeAnnotation(e.annotationUID),n.push(e);return n},t||(t=Se()),this.annotations={},this.uid=t,Z.addEventListener(yt.IMAGE_VOLUME_MODIFIED,this._imageVolumeModifiedHandler)}setPreprocessingFn(t){this.preprocessingFn=t}}const pT=new X0("DEFAULT"),vT=i=>(i.data||(i.data={}),i.data.handles||(i.data.handles={}),i.data.handles.textBox||(i.data.handles.textBox={}),i),IT=i=>(i.data||(i.data={}),i.data.cachedStats||(i.data.cachedStats={}),i),mf=pT,wT=i=>{i=vT(i),i=IT(i);const t=i.annotationUID,n=L0(t);i.isLocked=n;const e=$0(t);return i.isVisible=e,i};mf.setPreprocessingFn(wT);Uh(mf);function ET(){Uh(mf)}function _o(i){if(!i.data.segmentation)throw new Error("removeContourSegmentationAnnotation: annotation does not have a segmentation data");const{segmentationId:t,segmentIndex:n}=i.data.segmentation,e=Dt(t),{annotationUIDsMap:o}=e?.representationData.Contour||{},s=o?.get(n);s&&(s.delete(i.annotationUID),s.size||o.delete(n))}function Ho(i){if(i.parentAnnotationUID)return;if(!i.data.segmentation)throw new Error("addContourSegmentationAnnotation: annotation does not have a segmentation data");const{segmentationId:t,segmentIndex:n}=i.data.segmentation,e=Dt(t);e.representationData.Contour||(e.representationData.Contour={annotationUIDsMap:new Map});let{annotationUIDsMap:o}=e.representationData.Contour;o||(o=new Map);let s=o?.get(n);s||(s=new Set,o.set(n,s)),e.segments[n].locked&&cd(i.annotationUID,!0),o.set(n,s.add(i.annotationUID))}const ST="PlanarFreehandContourSegmentationTool";function pf(i){const{polyline:t}=i.data?.contour||{};if(!t||t.length<3){console.warn("Skipping creation of new annotation due to invalid polyline:",t);return}Gt(i.annotationUID),_o(i);const n=t[0],e=t[t.length-1],o={metadata:{...i.metadata,toolName:ST,originalToolName:i.metadata.originalToolName||i.metadata.toolName},data:{cachedStats:{},handles:{points:[n,e],textBox:i.data.handles.textBox?{...i.data.handles.textBox}:void 0},contour:{...i.data.contour},spline:i.data.spline,segmentation:{...i.data.segmentation}},annotationUID:Se(),highlighted:!0,invalidated:!0,isLocked:!1,isVisible:void 0,interpolationUID:i.interpolationUID,interpolationCompleted:i.interpolationCompleted};return Nt(o,i.metadata.FrameOfReferenceUID),Ho(o),zt(o),o}function _s(i){const e=me.getState().viewportSegRepresentations;return Object.entries(e).filter(([,s])=>s.some(a=>a.segmentationId===i)).map(([s])=>s)}function vf(i){const t=_s(i);if(t?.length===0)return[];const n=[];for(const e of t){const{viewport:o}=le(e)||{};o&&n.push(o)}return n}function If(i){const t=vf(i);return t.length>0?t[0]:void 0}function wf(i,t,n=.99){const e=t.metadata?.viewPlaneNormal;if(!e||!Array.isArray(e))return;const o=B();Wt(o,e);for(const s of i){const a=ht(s);if(!a?.viewPlaneNormal)continue;const r=B();Wt(r,a.viewPlaneNormal);const c=xt(o,r);if(Math.abs(c)>=n)return s}}function yr(i){const t=Dt(i);if(!t)return;const n=t.representationData?.Contour;if(!n)return;const{annotationUIDsMap:e}=n;if(e)return e}function q0(i,t,n){const e={annotationUID:Se(),data:{contour:{closed:!0,polyline:[]},segmentation:{segmentationId:t,segmentIndex:n},handles:{}},handles:{},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{...i.metadata,toolName:i.metadata.toolName}};return e.data.segmentation.segmentationId=t,e.data.segmentation.segmentIndex=n,i.data.contour?.polyline&&(e.data.contour.polyline=[...i.data.contour.polyline]),i.data.handles?.points&&(e.data.handles.points=i.data.handles.points.map(o=>[...o])),e}function Y0(i,t,n,e){const o=yr(i),s=yr(n);if(!o||!s||!o?.has(t))return;const a=o.get(t),r=If(n);if(!r)return;const c=Ae(r.id),l=u=>{const h=q0(u,n,e);if(c){const f=c.getToolInstance(u.metadata.toolName);f&&typeof f.isSplineAnnotation=="function"&&f.isSplineAnnotation(u)&&f.createSplineObjectFromType(h,u.data.spline.type)}return Nt(h,r.element),d.add(h.annotationUID),h},d=new Set;for(const u of a){const h=ne(u),f=l(h);if(h?.childAnnotationUIDs){f.childAnnotationUIDs=[];for(const g of h.childAnnotationUIDs){const m=ne(g),p=l(m);p.parentAnnotationUID=f.annotationUID,f.childAnnotationUIDs.push(p.annotationUID)}}}s.set(e,d)}const Pm=1e-10,ml="PlanarFreehandContourSegmentationTool";function On(i,t){const n=i.length,e=new Array(n);for(let o=0;o<n;o++)e[o]=t.worldToCanvas(i[o]);return e}function eh(i,t){const n=i.length,e=new Array(n);for(let o=0;o<n;o++)e[o]=t.canvasToWorld(i[o]);return e}function K0(i,t){const n=Ei(i),e=Ei(t);if(!Qr(n,e))return{hasIntersection:!1,isContourHole:!1,isTargetInsideSource:!1};const s=td(i,t),a=!s&&ma(t,i),r=!s&&!a&&ma(i,t);return{hasIntersection:s||a||r,isContourHole:a,isTargetInsideSource:r}}function pl(i,t){return Xi(t).map(n=>{const e=n,o=On(e.data.contour.polyline,i);return{annotation:e,polyline:o}})}function Ef(i,t,n){Cs(t,n),_o(n);const{contour:e}=n.data,o=On(e.polyline,i);io(n,{points:o,closed:e.closed,targetWindingDirection:t.data.contour.windingDirection===Qe.Clockwise?Qe.CounterClockwise:Qe.Clockwise},i);const{element:s}=i;sc(i,[t,n])}function Z0(i,t,n,e,o){if(!Zr(ml)){console.warn(`${ml} is not registered in cornerstone. Cannot combine polylines.`);return}const s=o[0],a=Ln(n,s),r=pl(i,t),c=[{outer:n,holes:r.length?r.map(f=>f.polyline):void 0}],d=rd(c,[{outer:o}],a?Ge.Union:Ge.Difference),{element:u}=i;[e,t,...r.map(f=>f.annotation)].forEach(f=>{Gt(f.annotationUID),_o(f)}),d.forEach(f=>{if(f.outer.length<3)return;const g=xr(i,t,f.outer,Qe.Clockwise);Nt(g,u),Ho(g),zt(g,u),f.holes?.forEach(m=>{if(m.length<3)return;const p=xr(i,t,m,Qe.CounterClockwise);Nt(p,u),Cs(g,p),zt(p,u)})}),sc(i,[t,e])}function xr(i,t,n,e=Qe.Clockwise){const o=i.canvasToWorld(n[0]),s=i.canvasToWorld(n[n.length-1]),a={metadata:{...t.metadata,toolName:ml,originalToolName:t.metadata.originalToolName||t.metadata.toolName},data:{cachedStats:{},handles:{points:[o,s],textBox:t.data.handles.textBox?{...t.data.handles.textBox}:void 0},contour:{polyline:[],closed:!0},spline:t.data.spline,segmentation:{...t.data.segmentation}},annotationUID:Se(),highlighted:!0,invalidated:!0,isLocked:!1,isVisible:void 0,interpolationUID:t.interpolationUID,interpolationCompleted:t.interpolationCompleted};return io(a,{points:n,closed:!0,targetWindingDirection:e},i),a}function sc(i,t){const{element:n}=i,e=new Set([ml]);t.forEach(o=>{e.add(o.metadata.toolName)});for(const o of e.values())if(Zr(o)){const s=ft(n,o);V(s)}}function J0(i){if(!i||i.length<2)return i;const t=[i[0]];for(let n=1;n<i.length;n++){const e=i[n],o=t[t.length-1],s=Math.abs(e[0]-o[0]),a=Math.abs(e[1]-o[1]);(s>Pm||a>Pm)&&t.push(e)}return t}function CT(i){const t=[],n=new Set;for(let e of i){if(!e||e.length<3||(e=J0(e),e.length<3))continue;const s=[...e].sort((a,r)=>a[0]!==r[0]?a[0]-r[0]:a[1]-r[1]).map(a=>`${a[0].toFixed(6)},${a[1].toFixed(6)}`).join("|");n.has(s)||(n.add(s),t.push(e))}return t}const bT="PlanarFreehandContourSegmentationTool";function _T(i,t,n,e,o){return e.forEach(({polyline:s,viewReference:a,holePolylines:r})=>{if(s.length<3)return;const c=Dm(n,o,a);Nt(c,i.element);const l=s.map(u=>i.worldToCanvas(u));io(c,{points:l,closed:!0,targetWindingDirection:Qe.Clockwise},i);const d=t?.get(o)||new Set;d.add(c.annotationUID),t.set(o,d),r?.forEach(u=>{if(u.length<3)return;const h=Dm(n,o,a);Nt(h,i.element),Cs(c,h);const f=u.map(g=>i.worldToCanvas(g));io(h,{points:f,closed:!0,targetWindingDirection:Qe.CounterClockwise},i)})}),t}function Dm(i,t,n){return{annotationUID:Se(),data:{contour:{closed:!0,polyline:[]},segmentation:{segmentationId:i,segmentIndex:t},handles:{},cachedStats:{}},handles:{},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{toolName:bT,...n}}}function Sf(i){const{metadata:t}=i;if(!t)return{};const{FrameOfReferenceUID:n,referencedImageId:e,referencedImageURI:o,multiSliceReference:s,cameraFocalPoint:a,viewPlaneNormal:r,viewUp:c,sliceIndex:l,volumeId:d,bounds:u}=t;return{FrameOfReferenceUID:n,referencedImageId:e,referencedImageURI:o,multiSliceReference:s,cameraFocalPoint:a,viewPlaneNormal:r,viewUp:c,sliceIndex:l,volumeId:d,bounds:u}}function Q0(i,t){if(!i||!t||i.FrameOfReferenceUID!==t.FrameOfReferenceUID||i.referencedImageId!==t.referencedImageId||!i.viewPlaneNormal||!t.viewPlaneNormal||i.viewPlaneNormal.length!==t.viewPlaneNormal.length)return!1;for(let n=0;n<i.viewPlaneNormal.length;n++)if(i.viewPlaneNormal[n]!==t.viewPlaneNormal[n])return!1;return!0}function Tm(i){return{outer:i.polyline,holes:i.holePolylines?.length?i.holePolylines:void 0}}function Mm(i){const t=[];for(const n of i){if(n.polyline.length<3)continue;const e=t.find(o=>Q0(o.viewReference,n.viewReference));e?e.polygons.push(Tm(n)):t.push({viewReference:n.viewReference,polygons:[Tm(n)]})}return t}function eu(i,t){return i.map(n=>({polyline:n.outer,viewReference:t,...n.holes?.length?{holePolylines:n.holes}:{}}))}function ld(i,t,n){const e=Mm(i),o=Mm(t),s=[],a=new Set;for(const r of e){const c=o.find(l=>Q0(l.viewReference,r.viewReference));if(c){a.add(c);const l=rd(r.polygons,c.polygons,n);s.push(...eu(l,r.viewReference))}else n===Ge.Intersection||s.push(...eu(r.polygons,r.viewReference))}if(n===Ge.Union||n===Ge.Xor)for(const r of o)a.has(r)||s.push(...eu(r.polygons,r.viewReference));return s}function Pr(i,t){return ld(i,t,Ge.Union)}function yT(i){if(i.length===0)return[];if(i.length===1)return[...i[0]];let t=i[0];for(let n=1;n<i.length;n++)t=Pr(t,i[n]);return t}function xT(i,t,n){const e=o=>{const s=Xi(o).map(a=>On(a.data.contour.polyline,n));return{polyline:On(o.data.contour.polyline,n),viewReference:Sf(o),...s.length?{holePolylines:s}:{}}};return Pr(i.map(e),t.map(e))}function dd(i,t){return ld(i,t,Ge.Difference)}function PT(i,t){if(t.length===0)return[...i];let n=i;for(const e of t)n=dd(n,e);return n}function DT(i,t,n){const e=o=>{const s=Xi(o).map(a=>On(a.data.contour.polyline,n));return{polyline:On(o.data.contour.polyline,n),viewReference:Sf(o),...s.length?{holePolylines:s}:{}}};return dd(i.map(e),t.map(e))}function tw(i,t){return ld(i,t,Ge.Intersection)}function ew(i,t){return ld(i,t,Ge.Xor)}var Lo;(function(i){i[i.Union=0]="Union",i[i.Subtract=1]="Subtract",i[i.Intersect=2]="Intersect",i[i.XOR=3]="XOR",i[i.Copy=4]="Copy",i[i.Delete=5]="Delete"})(Lo||(Lo={}));function Am(i,t){const n=[],{annotationUIDsMap:e}=i||{};if(!e?.has(t))return;const o=e.get(t);for(const s of o){const a=ne(s),{polyline:r}=a.data.contour,c=Xi(a),l=c.length>0?c.map(d=>d.data.contour.polyline):void 0;n.push({polyline:r,viewReference:Sf(a),...l?{holePolylines:l}:{}})}return n}function TT(i,t,n){const e=Dt(t.segmentationId),o=Dt(n.segmentationId);if(!e||!o||!e.representationData.Contour||!o.representationData.Contour)return;const s=Am(e.representationData.Contour,t.segmentIndex),a=Am(o.representationData.Contour,n.segmentIndex);if(!s||!a)return;const r=s.map(({polyline:l,viewReference:d,holePolylines:u})=>({polyline:On(l,i),viewReference:d,...u?.length?{holePolylines:u.map(h=>On(h,i))}:{}})),c=a.map(({polyline:l,viewReference:d,holePolylines:u})=>({polyline:On(l,i),viewReference:d,...u?.length?{holePolylines:u.map(h=>On(h,i))}:{}}));return{polyLinesInfoCanvas1:r,polyLinesInfoCanvas2:c}}function MT(i,{segmentIndex:t,label:n,color:e}){if(!i?.segments)return;const o=i.segments[t]??{active:!1,locked:!1,segmentIndex:t,cachedStats:{},label:n,color:e};n!==void 0&&(o.label=n),e!==void 0&&(o.color=e),i.segments[t]=o}function nw(i){i.forEach(t=>{const n=ne(t);Gt(t),_o(n)}),i.clear()}function ud(i,t,n,e){const o=If(i.segmentationId);if(!o)return;const{polyLinesInfoCanvas1:s,polyLinesInfoCanvas2:a}=TT(o,i,t)||{};if(!s||!a)return;let r;switch(e){case Lo.Union:r=Pr(s,a);break;case Lo.Subtract:r=dd(s,a);break;case Lo.Intersect:r=tw(s,a);break;case Lo.XOR:r=ew(s,a);break;default:r=Pr(s,a);break}const c=r.map(({polyline:p,viewReference:v,holePolylines:I})=>({polyline:eh(p,o),viewReference:v,...I?.length?{holePolylines:I.map(w=>eh(w,o))}:{}})),l=n,d=Dt(l.segmentationId),u=l.segmentIndex,h=l.color,f=l.label,g=d.representationData.Contour,{annotationUIDsMap:m}=g;if(m){if(i.segmentationId===l.segmentationId&&i.segmentIndex===u){const p=m.get(u);p&&nw(p)}_T(o,m,d.segmentationId,c,u),MT(d,{segmentIndex:u,color:h,label:f})}}function AT(i,t,n){ud(i,t,n,Lo.Union)}function LT(i,t,n){ud(i,t,n,Lo.Subtract)}function OT(i,t,n){ud(i,t,n,Lo.Intersect)}function RT(i,t,n){ud(i,t,n,Lo.XOR)}function NT(i,t){Y0(i.segmentationId,i.segmentIndex,t.segmentationId,t.segmentIndex)}function kT(i){const t=Dt(i.segmentationId);if(!t){console.log("No active segmentation detected");return}if(!t.representationData.Contour){console.log("No contour representation found");return}const n=t.representationData.Contour,{annotationUIDsMap:e}=n;if(!e){console.log("No annotation map found");return}if(!e.has(i.segmentIndex)){console.log("Segmentation index has no annotations");return}const o=e.get(i.segmentIndex);nw(o)}function Da(i){return!!i.data?.segmentation}function UT(i,t,n){const e=[],o=Ei(t);for(let s=0;s<n.length;s++){const a=n[s],r=VT(a.data.contour.polyline,i),c=Ei(r);if(!Qr(o,c))continue;const d=td(t,r),u=!d&&ma(r,t);(d||u)&&e.push({targetAnnotation:a,targetPolyline:r,isContourHole:u})}return e}function VT(i,t){const n=i.length,e=new Array(n);for(let o=0;o<n;o++)e[o]=t.worldToCanvas(i[o]);return e}const vl="PlanarFreehandContourSegmentationTool";function FT(i,t,n,e){const o=e.filter(a=>a.isContourHole),s=e.filter(a=>!a.isContourHole);if(o.length>0){const a=o[0];HT(i,a.targetAnnotation,t),iw(i,[t,a.targetAnnotation]);return}if(s.length!==0){if(!Zr(vl)){console.warn(`${vl} is not registered in cornerstone. Cannot process multiple intersections.`);return}GT(i,t,n,s)}}function GT(i,t,n,e){const{element:o}=i,s=e.map(({targetAnnotation:g,targetPolyline:m})=>{const p=Om(i,g).map(v=>v.polyline);return{outer:m,holes:p.length?p:void 0}}),a=[{outer:n}],r=n[0],l=e.some(({targetPolyline:g})=>Ln(g,r))?Ge.Union:Ge.Difference,d=rd(s,a,l),u=[],h=[t];e.forEach(({targetAnnotation:g})=>{h.push(g),Om(i,g).forEach(m=>u.push(m.annotation))}),[...h,...u].forEach(g=>{Gt(g.annotationUID),_o(g)});const f=e[0].targetAnnotation;d.forEach(g=>{if(g.outer.length<3)return;const m=Lm(i,f,g.outer,Qe.Clockwise);Nt(m,o),Ho(m),zt(m,o),g.holes?.forEach(p=>{if(p.length<3)return;const v=Lm(i,f,p,Qe.CounterClockwise);Nt(v,o),Cs(m,v),zt(v,o)})}),iw(i,h)}function Lm(i,t,n,e=Qe.Clockwise){const o=i.canvasToWorld(n[0]),s=i.canvasToWorld(n[n.length-1]),a={metadata:{...t.metadata,toolName:vl,originalToolName:t.metadata.originalToolName||t.metadata.toolName},data:{cachedStats:{},handles:{points:[o,s],textBox:t.data.handles.textBox?{...t.data.handles.textBox}:void 0},contour:{polyline:[],closed:!0},spline:t.data.spline,segmentation:{...t.data.segmentation}},annotationUID:Se(),highlighted:!0,invalidated:!0,isLocked:!1,isVisible:void 0,interpolationUID:t.interpolationUID,interpolationCompleted:t.interpolationCompleted};return io(a,{points:n,closed:!0,targetWindingDirection:e},i),a}function Om(i,t){return Xi(t).map(n=>{const e=n,o=ow(e.data.contour.polyline,i);return{annotation:e,polyline:o}})}function HT(i,t,n){Cs(t,n),_o(n);const{contour:e}=n.data,o=ow(e.polyline,i);io(n,{points:o,closed:e.closed,targetWindingDirection:t.data.contour.windingDirection===Qe.Clockwise?Qe.CounterClockwise:Qe.Clockwise},i)}function ow(i,t){const n=i.length,e=new Array(n);for(let o=0;o<n;o++)e[o]=t.worldToCanvas(i[o]);return e}function iw(i,t){const{element:n}=i,e=new Set([vl]);t.forEach(o=>{e.add(o.metadata.toolName)});for(const o of e.values())if(Zr(o)){const s=ft(n,o);V(s)}}const{isEqual:Rm}=oe;function Cf(i){const{metadata:t}=i;return cb().filter(n=>{if(n.FrameOfReferenceUID===t.FrameOfReferenceUID){const e=n.viewport,{viewPlaneNormal:o,viewUp:s}=ht(e);return o?Rm(o,t.viewPlaneNormal)&&(!t.viewUp||Rm(s,t.viewUp)):!1}}).map(n=>n.viewport)}async function WT(i,t,n,e=!0){const o=typeof i=="string"?ne(i):i,s=typeof t=="string"?ne(t):t;if(!o||!s)throw new Error("Both source and target annotations must be valid");n||(n=BT(o));const a=On(o.data.contour.polyline,n),r=On(s.data.contour.polyline,n),c=K0(a,r);if(!c.hasIntersection){console.warn("No intersection found between the two annotations");return}if(c.isContourHole){if(!e){console.warn("Hole processing is disabled");return}Ef(n,s,o)}else Z0(n,s,r,o,a)}function BT(i){const t=Cf(i);if(!t.length)throw new Error("No viewport found for the annotation");return t[0]}const zT=Object.freeze(Object.defineProperty({__proto__:null,get LogicalOperation(){return Lo},add:AT,addContourSegmentationAnnotation:Ho,areSameSegment:j0,checkIntersection:K0,cleanupPolylines:CT,combinePolylines:Z0,contourSegmentationOperation:WT,convertContourPolylineToCanvasSpace:On,convertContourPolylineToWorld:eh,convertContourSegmentationAnnotation:pf,copy:NT,copyAnnotation:q0,copyContourSegment:Y0,createNewAnnotationFromPolyline:xr,createPolylineHole:Ef,deleteOperation:kT,findAllIntersectingContours:UT,getContourHolesData:pl,intersect:OT,intersectPolylinesSets:tw,isContourSegmentationAnnotation:Da,processMultipleIntersections:FT,removeContourSegmentationAnnotation:_o,removeDuplicatePoints:J0,subtract:LT,subtractAnnotationPolylines:DT,subtractMultiplePolylineSets:PT,subtractPolylineSets:dd,unifyAnnotationPolylines:xT,unifyMultiplePolylineSets:yT,unifyPolylineSets:Pr,updateViewportsForAnnotations:sc,xor:RT,xorPolylinesSets:ew},Symbol.toStringTag,{value:"Module"})),{PointsManager:$T}=oe;function jT(i,t){if(t==null||typeof t!="object"||!("polyline"in t))return t;const n=t;return{...n,polyline:null,pointsManager:$T.create3(n.polyline.length,n.polyline)}}const Nm=new Map([["pointsInVolume",null],["projectionPoints",null],["contour",jT],["spline",null]]);function sw(i){const t={};for(const[n,e]of Object.entries(i)){if(Nm.has(n)){const o=Nm.get(n);o&&(t[n]=o(n,e));continue}e==null||typeof e!="object"?t[n]=e:Array.isArray(e)?t[n]=e.map(o=>hd(o)):t[n]=sw(e)}return t}function hd(i){return i==null||typeof i!="object"?i:Array.isArray(i)?i.map(t=>hd(t)):sw(i)}const{DefaultHistoryMemo:nu}=Nl;class be extends Ci{static createAnnotationForViewport(t,...n){const e=t.getViewReference();return delete e.volumeId,this.createAnnotation({metadata:e},...n)}static createAndAddAnnotation(t,...n){const e=this.createAnnotationForViewport(t,...n);Nt(e,t.element),zt(e,t.element)}constructor(t,n){super(t,n),this._activateModify=e=>{$.isInteractingWithTool=!0,e.addEventListener(E.MOUSE_UP,this._endCallback),e.addEventListener(E.MOUSE_DRAG,this._dragCallback),e.addEventListener(E.MOUSE_CLICK,this._endCallback),e.addEventListener(E.TOUCH_END,this._endCallback),e.addEventListener(E.TOUCH_DRAG,this._dragCallback),e.addEventListener(E.TOUCH_TAP,this._endCallback)},this._deactivateModify=e=>{$.isInteractingWithTool=!1,e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.TOUCH_END,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback)},this.mouseMoveCallback=(e,o)=>{if(!o)return!1;const{element:s,currentPoints:a}=e.detail,r=a.canvas;let c=!1;for(const l of o){if(ze(l.annotationUID)||!$e(l.annotationUID))continue;const{data:d}=l,u=d.handles?d.handles.activeHandleIndex:void 0,h=this._imagePointNearToolOrHandle(s,l,r,6),f=h&&!l.highlighted,g=!h&&l.highlighted;f||g?(l.highlighted=!l.highlighted,c=!0):d.handles&&d.handles.activeHandleIndex!==u&&(c=!0)}return c},this.isSuvScaled=be.isSuvScaled,t.configuration?.getTextLines&&(this.configuration.getTextLines=t.configuration.getTextLines),t.configuration?.statsCalculator&&(this.configuration.statsCalculator=t.configuration.statsCalculator)}getHandleNearImagePoint(t,n,e,o){const s=N(t),{viewport:a}=s,{data:r}=n,{isCanvasAnnotation:c}=r,{points:l,textBox:d}=r.handles;if(d){const{worldBoundingBox:u}=d;if(u){const h={topLeft:a.worldToCanvas(u.topLeft),topRight:a.worldToCanvas(u.topRight),bottomLeft:a.worldToCanvas(u.bottomLeft),bottomRight:a.worldToCanvas(u.bottomRight)};if(e[0]>=h.topLeft[0]&&e[0]<=h.bottomRight[0]&&e[1]>=h.topLeft[1]&&e[1]<=h.bottomRight[1])return r.handles.activeHandleIndex=null,d}}for(let u=0;u<l?.length;u++){const h=l[u],f=c?h.slice(0,2):a.worldToCanvas(h);if(_e(e,f)<o===!0)return r.handles.activeHandleIndex=u,h}r.handles.activeHandleIndex=null}getLinkedTextBoxStyle(t,n){return{visibility:this.getStyle("textBoxVisibility",t,n),fontFamily:this.getStyle("textBoxFontFamily",t,n),fontSize:this.getStyle("textBoxFontSize",t,n),color:this.getStyle("textBoxColor",t,n),shadow:this.getStyle("textBoxShadow",t,n),background:this.getStyle("textBoxBackground",t,n),lineWidth:this.getStyle("textBoxLinkLineWidth",t,n),lineDash:this.getStyle("textBoxLinkLineDash",t,n),textBoxBorderRadius:this.getStyle("textBoxBorderRadius",t,n),textBoxMargin:this.getStyle("textBoxMargin",t,n),textBoxLinkLineColor:this.getStyle("textBoxLinkLineColor",t,n)}}renderLinkedTextBoxAnnotation(t){const{enabledElement:n,svgDrawingHelper:e,annotation:o,styleSpecifier:s,textLines:a,canvasCoordinates:r,textBoxUID:c="1",placementPoints:l}=t,{viewport:d}=n,{element:u}=d,{annotationUID:h,data:f}=o,g=this.getLinkedTextBoxStyle(s,o);if(!g.visibility)return f.handles.textBox={hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}},!1;f.handles.textBox||(f.handles.textBox={hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}});const m=l??r;if(!f.handles.textBox.hasMoved){const b=gf(m,u,a);f.handles.textBox.worldPosition=d.canvasToWorld(b)}const p=d.worldToCanvas(f.handles.textBox.worldPosition),v=g0(e,h,c,a,p,r,{},g),{x:I,y:w,width:C,height:S}=v;return f.handles.textBox.worldBoundingBox={topLeft:d.canvasToWorld([I,w]),topRight:d.canvasToWorld([I+C,w]),bottomLeft:d.canvasToWorld([I,w+S]),bottomRight:d.canvasToWorld([I+C,w+S])},!0}static isSuvScaled(t,n,e){const o=Fi(n),s=Q.getVolume(o);return s?s?.scaling?.PT!==void 0:typeof(e&&rn("scalingModule",e))?.suvbw=="number"}getAnnotationStyle(t){const{annotation:n,styleSpecifier:e}=t,o=m=>this.getStyle(m,e,n),{annotationUID:s}=n,a=$e(s),r=ze(s),c=o("lineWidth"),l=o("lineDash"),d=o("angleArcLineDash"),u=o("color"),h=o("markerSize"),f=o("shadow"),g=this.getLinkedTextBoxStyle(e,n);return{visibility:a,locked:r,color:u,lineWidth:c,lineDash:l,lineOpacity:1,fillColor:u,fillOpacity:0,shadow:f,textbox:g,markerSize:h,angleArcLineDash:d}}_imagePointNearToolOrHandle(t,n,e,o){if(this.getHandleNearImagePoint(t,n,e,o)||this.isPointNearTool(t,n,e,o,"mouse"))return!0}static createAnnotationState(t,n){const{data:e,annotationUID:o}=t;return{annotationUID:o,data:hd(e),deleting:n}}static createAnnotationMemo(t,n,e){if(!n)return;const{newAnnotation:o,deleting:s=o?!1:void 0}=e||{},{annotationUID:a}=n,r=be.createAnnotationState(n,s),c={restoreMemo:()=>{const l=be.createAnnotationState(n,s),{viewport:d}=N(t)||{};if(d?.setViewReference(n.metadata),r.deleting===!0){if(r.deleting=!1,Object.assign(n.data,r.data),n.data.contour){const h=n.data;h.contour.polyline=r.data.contour.pointsManager.points,delete r.data.contour.pointsManager,h.segmentation&&Ho(n)}r.data=l.data,Nt(n,t),So(n.annotationUID,!0),d?.render();return}if(r.deleting===!1){r.deleting=!0,r.data=l.data,So(n.annotationUID),Gt(n.annotationUID),d?.render();return}const u=ne(a);if(!u){console.warn("No current annotation");return}Object.assign(u.data,r.data),u.data.contour&&(u.data.contour.polyline=r.data.contour.pointsManager.points),r.data=l.data,u.invalidated=!0,t&&zt(u,t,Bt.History)},id:a,operationType:"annotation"};return nu.push(c),c}createMemo(t,n,e){this.memo||=be.createAnnotationMemo(t,n,e)}startGroupRecording(){nu.startGroupRecording()}endGroupRecording(){nu.endGroupRecording()}static hydrateBase(t,n,e,o={}){if(!n)return null;const{viewport:s}=n,a=s.getFrameOfReferenceUID(),r=ht(s),c=o.viewplaneNormal??r.viewPlaneNormal,l=o.viewUp??r.viewUp,d=o.toolInstance||new t;let u,h=c,f=l;if(o.referencedImageId)u=o.referencedImageId,h=void 0,f=void 0;else if(s instanceof Pn){const g=Oh(e[0],s);g!==void 0&&(u=s.getImageIds()[g])}else if(s instanceof pn)u=d.getReferencedImageId(s,e[0],c,l);else if(ie(s))u=s.getViewReference?.({points:[e[0]]})?.referencedImageId;else throw new Error("Unsupported viewport type");return{FrameOfReferenceUID:a,referencedImageId:u,viewPlaneNormal:h,viewUp:f,instance:d,viewport:s}}}be.toolName="AnnotationTool";class XT extends be{constructor(t,n){super(t,n)}static getContourSequence(t,n){const{data:e}=t,o=[];for(const r of e.contour.polyline)for(const c of r)o.push(c.toFixed(2));const{referencedImageId:s}=t.metadata,a=n.get("ImageSopInstanceReference",s);return{NumberOfContourPoints:o.length/3,ContourImageSequence:a,ContourGeometricType:"CLOSED_PLANAR",ContourData:o}}renderAnnotation(t,n){let e=!1;const{viewport:o}=t,{element:s}=o;if(!o.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),e;let a=Yt(this.getToolName(),s);if(!a?.length||(a=this.filterInteractableAnnotationsForElement(s,a),!a?.length))return e;const r=this.getTargetId(o),c={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:t.viewport.id};for(let l=0;l<a.length;l++){const d=a[l];c.annotationUID=d.annotationUID;const u=this.getAnnotationStyle({annotation:d,styleSpecifier:c});if(!u.visibility)continue;const h=this.renderAnnotationInstance({enabledElement:t,targetId:r,annotation:d,annotationStyle:u,svgDrawingHelper:n});e||=h,d.invalidated=!1}return e}createAnnotation(t){const n=super.createAnnotation(t);return Object.assign(n.data,{contour:{polyline:[],closed:!1}}),Object.assign(n,{interpolationUID:"",autoGenerated:!1}),n}addAnnotation(t,n){return Nt(t,n)}cancelAnnotation(t){}moveAnnotation(t,n){const{points:e}=t.data.handles;for(let o=0,s=e.length;o<s;o++){const a=e[o];a[0]+=n[0],a[1]+=n[1],a[2]+=n[2]}t.invalidated=!0,Xi(t).forEach(o=>this.moveAnnotation(o,n))}updateContourPolyline(t,n,e,o){const s=this.configuration?.decimate||{};io(t,n,e,{decimate:{enabled:!!s.enabled,epsilon:s.epsilon},updateWindingDirection:o?.updateWindingDirection})}getPolylinePoints(t){return t.data.contour?.polyline??t.data.polyline}renderAnnotationInstance(t){const{enabledElement:n,annotationStyle:e,svgDrawingHelper:o}=t,s=t.annotation;if(s.parentAnnotationUID)return;const{annotationUID:a}=s,{viewport:r}=n,{worldToCanvas:c}=r,l=this.getPolylinePoints(s).map(v=>c(v)),{lineWidth:d,lineDash:u,color:h,fillColor:f,fillOpacity:g}=e,m=oc(s,r),p=[l,...m];return ko(o,a,"contourPolyline",p,{color:h,lineDash:u,lineWidth:Math.max(.1,d),fillColor:f,fillOpacity:g}),!0}}class qT{constructor(){this.annotationUIDs=new Set,this._isVisible=!0,this.visibleFilter=this.unboundVisibleFilter.bind(this)}unboundVisibleFilter(t){return!this._isVisible||!this.annotationUIDs.has(t)}has(t){return this.annotationUIDs.has(t)}setVisible(t=!0,n,e){this._isVisible!==t&&(this._isVisible=t,this.annotationUIDs.forEach(o=>{const s=ne(o);if(!s){this.annotationUIDs.delete(o);return}if(s.isVisible===t||!t&&e?.(o)===!1)return;s.isVisible=t;const a={...n,annotation:s};Rt(Z,E.ANNOTATION_MODIFIED,a)}))}get isVisible(){return this._isVisible}findNearby(t,n){const e=[...this.annotationUIDs];if(e.length===0)return null;if(!t)return e[n===1?0:e.length-1];const o=e.indexOf(t);return o===-1||o+n<0||o+n>=e.length?null:e[o+n]}add(...t){t.forEach(n=>this.annotationUIDs.add(n))}remove(...t){t.forEach(n=>this.annotationUIDs.delete(n))}clear(){this.annotationUIDs.clear()}}const Uo={...s_,...e_,resetAnnotationManager:ET},OH=Object.freeze(Object.defineProperty({__proto__:null,AnnotationGroup:qT,FrameOfReferenceSpecificAnnotationManager:X0,config:aT,locking:tT,selection:iT,state:Uo,visibility:lT},Symbol.toStringTag,{value:"Module"})),km="PlanarFreehandContourSegmentationTool";function bf(i,t=[]){const{viewport:n,sliceData:e,annotation:o}=i,s=new Map,{toolName:a,originalToolName:r}=o.metadata,c=r||a,l=(Yt(c,n.element)||[]).filter(d=>!d.metadata.originalToolName||d.metadata.originalToolName===c);if(c!==km){const d=Yt(km,n.element);d?.length&&d.forEach(u=>{const{metadata:h}=u;h.originalToolName===c&&h.originalToolName!==h.toolName&&l.push(u)})}if(!l?.length)return s;for(let d=0;d<e.numberOfSlices;d++){const u=l.filter(f=>f.metadata.sliceIndex===d);if(!u?.length)continue;const h=u.filter(f=>t.every(g=>{const p=(g.parentKey?g.parentKey(f):f)?.[g.key];return Array.isArray(p)?p.every((v,I)=>v===g.value[I]):p===g.value}));h.length&&s.set(d,h)}return s}function YT(i,t){const n=bf(i,t),e=[];if(!n?.size)return e;for(const o of n.values())o.forEach(s=>{e.push(s)});return e}function aw(i,t,n){const e=Hn({data:{},metadata:{}},n);return Object.assign(e,{highlighted:!1,invalidated:!0,autoGenerated:!0,annotationUID:void 0,cachedStats:{},childAnnotationUIDs:[],parentAnnotationUID:void 0}),Object.assign(e.data,{handles:{points:t.points||t||[],interpolationSources:t.sources,activeHandleIndex:null,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}},contour:{...n.data.contour,polyline:i}}),e}function KT(i,t){const n=bf(t,[{key:"interpolationUID",value:t.interpolationUID}]),e=ZT(n);if(!e){console.warn("No annotations found to interpolate",n);return}const o=JT(n,i.annotationUID),s=[];for(let a=e[0]+1;a<e[1];a++)if(QT(n,a)){const r=eM(a,e,n);(r?.[0]===o||r?.[1]===o)&&tM(r,s,a)}return{interpolationData:n,interpolationList:s}}function ZT(i){let t=1/0,n=-1/0,e=!1;for(const[o,s]of i.entries())s.length&&(t=Math.min(o,t),n=Math.max(o,n),e=!0);if(e)return[t,n]}function JT(i,t){for(const[n,e]of i)for(let o=0;o<e.length;o++)if(e[o].annotationUID===t)return n}function QT(i,t){const n=i.get(t);return!n?.length||n.length===1&&n[0].autoGenerated}function tM(i,t,n){const[e]=i;t[e]||={pair:i,list:[]},t[e].list.push(n)}function eM(i,t,n){const e=[];let o=!0;for(let s=i-1;s>=t[0];s--){const a=n.get(s);if(a?.length){if(a[0].autoGenerated)continue;a.length>1&&(o=!1),e.push(s);break}}if(!(!o||!e.length)){for(let s=i+1;s<=t[1];s++){const a=n.get(s);if(a?.length){if(a[0].autoGenerated)continue;a.length>1&&(o=!1),e.push(s);break}}if(!(!o||e.length<2))return e}}const{PointsManager:Um}=oe;function nM(i,t={}){const{handleCount:n=12,isOpenUShapeContour:e}=t,o=Um.create3(n);o.sources=[];const{sources:s}=o,{length:a,sources:r=[]}=i,c=5;if(e){const f=i.subselect(n);return f.push(i.getPoint(i.length-1)),f}if(a<c*3)return i.subselect(n);const l=Math.floor(Math.max(2*a/n,c*2));r.forEach(()=>s.push(Um.create3(n)));const d=oM(i,c),u=iM(d,n),h=[];if(u?.length>2){let f=-1;const g=l/3;u.forEach(v=>{const[I,,w]=v,C=Math.ceil((I+w)/2);w-f<g||(C-I>2*g?(ks(h,f,I,l,a),f=ks(h,I,C,l,a)):f=ks(h,f,C,l,a),w-f>g&&(f=ks(h,f,w,l,a)))});const m=h[0];nh(m+a-f,a)>2*g&&ks(h,f,m-g,l,a)}else{const f=Math.floor(a/n);ks(h,-1,a-f,f,a)}return h.forEach(f=>{const g=i.getPointArray(f);o.push(g),r.forEach((m,p)=>s[p].push(m.getPoint(f)))}),o}function oM(i,t=6){const{length:n}=i,e=B(),o=B(),s=new Float32Array(n);for(let a=0;a<n;a++){const r=i.getPoint(a),c=i.getPoint(a-t),l=i.getPoint((a+t)%n);tn(e,r,c),tn(o,l,r);const d=xt(e,o)/(mr(e)*mr(o));s[a]=d}return s}function iM(i,t){const{max:n,deviation:e}=sM(i),{length:o}=i;if(e<.01||o<t*3)return[];const s=[];let a=null,r,c=0;for(let l=0;l<o;l++){const d=i[l];d<n-e?a?(a[2]=l,d<r&&(r=d,c=l),a[1]=c):(r=d,c=l,a=[l,l,l]):a&&(s.push(a),a=null)}return a&&(s[0][0]===0?s[0][0]=a[0]:(a[1]=c,a[2]=o-1,s.push(a))),s}function ks(i,t,n,e,o){n<t&&(n+=o);const s=n-t,a=Math.ceil(s/e);if(a<=0)return i[i.length-1]!==n&&i.push(nh(n,o)),n;for(let r=1;r<=a;r++){const c=nh(t+r*s/a,o);i.push(c)}return i[i.length-1]}function nh(i,t){return(Math.round(i)+t)%t}function sM(i){const{length:t}=i;let n=0,e=1/0,o=-1/0,s=0;for(let r=0;r<t;r++){const c=i[r];n+=c,e=Math.min(e,c),o=Math.max(o,c)}const a=n/t;for(let r=0;r<t;r++){const c=i[r]-a;s+=c*c}return{mean:a,max:o,min:e,sumSq:s,deviation:Math.sqrt(s/t)}}function aM(i){const{parentAnnotationUID:t,annotationUID:n}=i;if(!t)return i.interpolationUID;const e=Uo.getAnnotation(t),{interpolationUID:o}=e,s=e.childAnnotationUIDs.indexOf(n);return i.interpolationUID=`${o}-${s}`,i.interpolationUID}const{PointsManager:Ba}=oe,Vm=.2;function Il(i){if(!i.annotation)return;const{isInterpolationUpdate:t,annotation:n}=i;queueMicrotask(()=>{try{t&&(n.isInterpolationUpdate=!0,n.autoGenerated=!1),rM(i)}finally{t&&(n.autoGenerated=!0)}})}function rM(i){const{annotation:t}=i;aM(t);const{interpolationData:n,interpolationList:e}=KT(t,i)||{};if(!n||!e)return;const o={toolName:t.metadata.toolName,toolType:t.metadata.toolName,viewport:i.viewport};for(let l=0;l<e.length;l++)e[l]&&cM(e[l].list,e[l].pair,n,o);const{id:s,renderingEngineId:a,element:r}=i.viewport,c={annotation:t,element:r,viewportId:s,renderingEngineId:a};e.length&&(Rt(i.viewport.element,E.ANNOTATION_INTERPOLATION_PROCESS_COMPLETED,c),Rt(Z,E.ANNOTATION_INTERPOLATION_PROCESS_COMPLETED,c))}function cM(i,t,n,e){const o=n.get(t[0])[0],s=n.get(t[1])[0],a=$m(o.data.contour.polyline),r=$m(s.data.contour.polyline);console.warn("annotation0=",o);const{c1Interp:c,c2Interp:l}=fM(a,r);c.kIndex=t[0],l.kIndex=t[1],i.forEach(function(d){lM(c,l,d,t,n,a.x.length>r.x.length,e)})}function lM(i,t,n,e,o,s,a){const[r,c]=e,l=(n-r)/(c-r),d=o.get(r)[0],u=o.get(c)[0],h=hM(i,t,l,s),f=l>.5?u:d,g=f.data.isOpenUShapeContour,m=nM(h,{isOpenUShapeContour:g});o.has(n)?uM(h,m,n,f,a):dM(h,m,n,f,a)}function dM(i,t,n,e,o){const s=i.points,{viewport:a}=o,r=aw(s,t,e),c=a.getViewReference({sliceIndex:n});if(!c)throw new Error(`Can't find slice ${n}`);Object.assign(r.metadata,c),Uo.addAnnotation(r,a.element),e.onInterpolationComplete?.(r,e);const{parentAnnotationUID:l}=e;if(l){const d=Uo.getAnnotation(l),u=rw(d,n,o);Ef(a,u,r)}}function rw(i,t,n){const{viewport:e}=n,o=Uo.getAnnotations(i.metadata.toolName,e.element);for(let s=0;s<o.length;s++){const a=o[s];if(a.interpolationUID===i.interpolationUID&&a.metadata.sliceIndex===t)return a}}function uM(i,t,n,e,o){const s=rw(e,n,o),a=i.points,r=aw(a,t,s);Object.assign(s,{metadata:r.metadata,data:r.data})}function hM(i,t,n,e){const o=e?i.I:t.I,s=Ba.fromXYZ(i),a=Ba.fromXYZ(t),{length:r}=s,c=Ba.create3(r),l=B(),d=B(),u=Ba.create3(r);u.kIndex=i.kIndex;const h=Ba.create3(r);h.kIndex=t.kIndex;for(let f=0;f<i.x.length;f++)if(o[f]){const g=s.getPoint(f),m=a.getPoint(f);u.push(g),h.push(m),tn(l,m,g),c.push(ee(d,g,l,n))}return c.sources=[u,h],c}function fM(i,t){const n=zm(i),e=zm(t),o=Math.max(Math.ceil(n[n.length-1]/Vm),Math.ceil(e[e.length-1]/Vm)),s=Bm(n),a=Bm(e),r=o+t.x.length,c=o+i.x.length,l=Wm(r,s),d=Wm(c,a),u=Hm(r-2,i.x.length),h=Hm(c-2,t.x.length),f=Gm(l,u),g=Gm(d,h),m=Fm(i,f),p=Fm(t,g);return mM(m,p),gM(m,p)}function gM(i,t){const n={x:[],y:[],z:[],I:[]},e={x:[],y:[],z:[],I:[]};for(let o=0;o<i.x.length;o++)(i.I[o]||t.I[o])&&(n.x.push(i.x[o]),n.y.push(i.y[o]),n.z.push(i.z[o]),n.I.push(i.I[o]),e.x.push(t.x[o]),e.y.push(t.y[o]),e.z.push(t.z[o]),e.I.push(t.I[o]));return{c1Interp:n,c2Interp:e}}function mM(i,t){const n=i.x.length,e={startingNode:0,totalSquaredXYLengths:1/0};for(let s=0;s<n;s++){let a=s,r=0;for(let c=0;c<n;c++)r+=(i.x[a]-t.x[c])**2+(i.y[a]-t.y[c])**2+(i.z[a]-t.z[c])**2,a++,a===n&&(a=0);r<e.totalSquaredXYLengths&&(e.totalSquaredXYLengths=r,e.startingNode=s)}const o=e.startingNode;Dc(i.x,o),Dc(i.y,o),Dc(i.z,o),Dc(i.I,o)}function Dc(i,t){t-=i.length*Math.floor(t/i.length);const n=i.splice(0,t);return i.push(...n),i}function Fm(i,t){const n={x:[],y:[],z:[],I:[]};for(let e=0;e<i.x.length-1;e++){n.x.push(i.x[e]),n.y.push(i.y[e]),n.z.push(i.z[e]),n.I.push(!0);const o=(i.x[e+1]-i.x[e])/(t[e]+1),s=(i.y[e+1]-i.y[e])/(t[e]+1),a=(i.z[e+1]-i.z[e])/(t[e]+1);for(let r=0;r<t[e]-1;r++)n.x.push(n.x[n.x.length-1]+o),n.y.push(n.y[n.y.length-1]+s),n.z.push(n.z[n.z.length-1]+a),n.I.push(!1)}return n}function Gm(i,t){const n=[];for(let a=0;a<i.length;++a)n[a]=a;n.sort(function(a,r){return i[a]<i[r]?-1:1});const e=[];for(let a=0;a<t.length;a++)e.push(t[n[a]]);const o=e.reduce(function(a,r,c){return r&&a.push(c),a},[]),s=[];for(let a=0;a<o.length-1;a++)s.push(o[a+1]-o[a]);return s}function Hm(i,t){const n=new Array(i+t);return n.fill(!1,0,i),n.fill(!0,i,i+t),n}function Wm(i,t){const n=1/(i-1),e=[n];for(let o=1;o<i-2;o++)e.push(e[e.length-1]+n);return e.concat(t)}function Bm(i){const t=[];for(let n=0;n<i.length;n++)t.push(i[n]/i[i.length-1]);return t}function zm(i){const t=[0];for(let n=1;n<i.x.length;n++){const e=Math.sqrt((i.x[n]-i.x[n-1])**2+(i.y[n]-i.y[n-1])**2+(i.z[n]-i.z[n-1])**2);t.push(t[n-1]+e)}return t}function $m(i){const t={x:[],y:[],z:[]};for(let n=0;n<i.length;n++)t.x[n]=i[n][0],t.y[n]=i[n][1],t.z[n]=i[n][2];return t.x.push(t.x[0]),t.y.push(t.y[0]),t.z.push(t.z[0]),t}function cw(i){const{annotation:t}=i,n=bf(i,[{key:"interpolationUID",value:i.interpolationUID}]),e=t.metadata.sliceIndex;let o=-1,s=i.sliceData.numberOfSlices;for(const[r,c]of n.entries())r===e||!c.find(d=>!d.autoGenerated)||(r<e?o=Math.max(r,o):s=Math.min(r,s));const a=[];for(const[r,c]of n.entries())r<=o||r>=s||r===e||c.forEach(l=>{l.autoGenerated&&(Uo.removeAnnotation(l.annotationUID),a.push(l))});if(a.length){const r={annotations:a,element:i.viewport.element,viewportId:i.viewport.id,renderingEngineId:i.viewport.getRenderingEngine().id};Rt(i.viewport.element,E.INTERPOLATED_ANNOTATIONS_REMOVED,r)}if(o>=0&&s<i.sliceData.numberOfSlices){const r=n.get(s)[0],c={viewport:i.viewport,sliceData:{numberOfSlices:i.sliceData.numberOfSlices,imageIndex:r.metadata.sliceIndex},annotation:r,interpolationUID:r.interpolationUID};Il(c)}}function fd(i){const t=Cf(i);return t?.length?t.find(e=>e.getImageIds().some(o=>o===i.metadata.referencedImageId))??t[0]:void 0}var Is;const{uuidv4:pM}=oe,vM=[Bt.HandlesUpdated,Bt.InterpolationUpdated];class Wn{static addTool(t){this.toolNames.includes(t)||this.toolNames.push(t)}static removeTool(t){this.toolNames.includes(t)&&(this.toolNames=this.toolNames.filter(n=>n!==t))}static acceptAutoGenerated(t,n={}){const{toolNames:e,segmentationId:o,segmentIndex:s,sliceIndex:a}=n;for(const r of e||Is.toolNames){const c=Uo.getAnnotations(r,t);if(c?.length)for(const l of c){const{interpolationUID:d,data:u,autoGenerated:h,metadata:f}=l;d&&(l.interpolationCompleted=!0),h&&(s&&s!==u.segmentation.segmentIndex||a!==void 0&&f&&a!==f.sliceIndex||o&&o!==u.segmentation.segmentationId||(Ho(l),l.autoGenerated=!1))}}}}Is=Wn;Wn.toolNames=[];Wn.handleAnnotationCompleted=i=>{const t=i.detail.annotation;if(!t?.metadata)return;const{toolName:n,originalToolName:e}=t.metadata;if(!Is.toolNames.includes(n)&&!Is.toolNames.includes(e))return;const o=fd(t);if(!o){console.warn("Unable to find viewport for",t);return}const s=_f(o),a={viewport:o,sliceData:s,annotation:t,interpolationUID:t.interpolationUID},r=!!t.interpolationUID;if(t.autoGenerated=!1,r){cw(a),Il(a);return}const c=[{key:"segmentIndex",value:t.data.segmentation.segmentIndex,parentKey:h=>h.data.segmentation},{key:"viewPlaneNormal",value:t.metadata.viewPlaneNormal,parentKey:h=>h.metadata},{key:"viewUp",value:t.metadata.viewUp,parentKey:h=>h.metadata}];let l=YT(a,c);const{sliceIndex:d}=t.metadata,u=new Set;l.forEach(h=>{if(h.interpolationCompleted||h.metadata.sliceIndex===d){const{interpolationUID:f}=h;u.add(f)}}),l=l.filter(h=>!u.has(h.interpolationUID)),t.interpolationUID=l[0]?.interpolationUID||pM(),a.interpolationUID=t.interpolationUID,Il(a)};Wn.handleAnnotationUpdate=i=>{const t=i.detail.annotation,{changeType:n=Bt.HandlesUpdated}=i.detail;if(!t?.metadata)return;const{toolName:e,originalToolName:o}=t.metadata;if(!Is.toolNames.includes(e)&&!Is.toolNames.includes(o)||!vM.includes(n))return;const s=fd(t);if(!s){console.warn("Unable to find matching viewport for annotation interpolation",t);return}t.autoGenerated&&(Ho(t),t.autoGenerated=!1);const a=_f(s),r={viewport:s,sliceData:a,annotation:t,interpolationUID:t.interpolationUID,isInterpolationUpdate:n===Bt.InterpolationUpdated};Il(r)};Wn.handleAnnotationDelete=i=>{const t=i.detail.annotation;if(!t?.metadata)return;const{toolName:n}=t.metadata;if(!Is.toolNames.includes(n)||t.autoGenerated)return;const e=fd(t);if(!e){console.warn("No viewport, can't delete interpolated results",t);return}const o=_f(e),s={viewport:e,sliceData:o,annotation:t,interpolationUID:t.interpolationUID};t.autoGenerated=!1,cw(s)};function _f(i){return{numberOfSlices:i.getNumberOfSlices(),imageIndex:i.getCurrentImageIdIndex()}}function lw(i){i.forEach(t=>{const n=Be(t);if(!n){console.warn(`ToolGroup not available for ${t}`);return}n.getViewportsInfo().forEach(o=>{const{renderingEngineId:s,viewportId:a}=o,r=Ne(s);if(!r){console.warn(`RenderingEngine not available for ${s}`);return}const c=r.getViewport(a);xa(c.element)})})}function Wi(i){return me.getActiveSegmentation(i)}function xn(i){const t=Dt(i);if(t){const n=Object.keys(t.segments).find(e=>t.segments[e].active);return n?Number(n):void 0}}function dw(i,t={}){const n=i.annotationUIDsMap,e=t.segmentIndices?.length?t.segmentIndices:Array.from(n.keys()),o=new Map;return e.forEach(s=>{const a=n.get(s);let r=Array.from(a);r=r.filter(l=>!ne(l).parentAnnotationUID);const c=r.map(l=>{const d=ne(l),u=d.childAnnotationUIDs?.length,h=u&&d.childAnnotationUIDs.map(m=>{const p=ne(m);return{polyline:p.data.contour.polyline,isClosed:p.data.contour.closed}}),f=u&&h.map(m=>m.isClosed),g=u&&h.map(m=>m.polyline);return{polyline:d.data.contour.polyline,isClosed:d.data.contour.closed,annotationUID:d.annotationUID,referencedImageId:d.metadata.referencedImageId,holesPolyline:g,holesUIDs:d.childAnnotationUIDs,holesClosed:f}});o.set(s,c)}),{segmentIndices:e,annotationUIDsInSegmentMap:o}}function jm(i,t){if(!i||i.length===0)return[];if(!t)return[...i];const n=i[0],e=i[i.length-1];return n[0]===e[0]&&n[1]===e[1]&&n[2]===e[2]?[...i]:[...i,n]}function IM(i,t){const{annotationUIDsInSegmentMap:n}=dw(i);if(!n.has(t)){console.warn(`No contour information found for segmentIndex ${t}`);return}const e=new Map,o=n.get(t);for(const s of o){e.set(s.annotationUID,jm(s.polyline,s.isClosed));for(let a=0;a<s.holesUIDs?.length;a++)e.set(s.holesUIDs[a],jm(s.holesPolyline[a],s.holesClosed[a]))}return e}function ac(i,t){const n=vf(i),e=Dt(i);if(!e||!e.representationData.Contour)return;const o=e.representationData.Contour,{annotationUIDsMap:s}=o;if(!s||!s.get(t))return;const a=IM(o,t);if(!a)return;const r=Array.from(a?.keys()),c=new Map;for(const l of r){const d=ne(l),u=wf(n,d);c.set(l,On(a.get(l),u))}return c}function wM(i,t,n={epsilon:.1}){const e=Dt(i);if(!e){console.warn(`Invalid segmentation given ${i}`);return}if(!e.representationData.Contour){console.warn(`No contour representation found for segmentation ${i}`);return}const o=vf(i);if(!o){console.warn("No viewport associated to the segmentation found");return}const s=ac(i,t);if(!s){console.warn(`Error extracting contour data from segment ${t} in segmentation ${i}`);return}const a=Array.from(s?.keys());for(const r of a){const c=ne(r);if(!c)continue;const l=s.get(r),d=ed(l,n.epsilon),u=wf(o,c);u&&(c.data.contour.polyline=d.map(h=>u.canvasToWorld(h)),Vh(c))}}function gd(i){i&&(i.parentAnnotationUID&&Wl(i),Gt(i.annotationUID),_o(i))}function EM(i,t){const{viewPlaneNormal:n}=i.metadata,{viewPlaneNormal:e}=t.metadata,o=xt(n,e);if(!pr(1,Math.abs(o)))return!1;const{polyline:a}=i.data.contour,{polyline:r}=t.data.contour,c=xt(n,a[0]),l=xt(n,r[0]);return pr(c,l)}function uw(i,t,n){let e=-1;if(t.forEach((o,s)=>{e>=0||o.a==i.b&&(e=s)}),e>=0){const o=t[e];return t.splice(e,1),n.push(o.b),n[0]==o.b?{remainingLines:t,contourPoints:n,type:"CLOSED_PLANAR"}:uw(o,t,n)}return{remainingLines:t,contourPoints:n,type:"OPEN_PLANAR"}}function yf(i){if(i.length==0)return[];const t=[],n=i.shift();t.push(n.a),t.push(n.b);const e=uw(n,i,t);if(e.remainingLines.length==0)return[{type:e.type,contourPoints:e.contourPoints}];{const o=yf(e.remainingLines);return o.push({type:e.type,contourPoints:e.contourPoints}),o}}function SM(i){return yf(i)}const CM={findContours:yf,findContoursFromReducedSet:SM};function bM(i,t=!1){const n=i.getPoints(),e=i.getLines(),o=new Array(n.getNumberOfPoints()).fill(0).map((c,l)=>n.getPoint(l).slice()),s=new Array(e.getNumberOfCells()).fill(0).map((c,l)=>{const d=e.getCell(l*3).slice();return{a:d[0],b:d[1]}});if(t)return{points:o,lines:s};const a=[];for(const[c,l]of o.entries()){const d=a.findIndex(u=>u[0]===l[0]&&u[1]===l[1]&&u[2]===l[2]);if(d>=0)s.map(u=>(u.a===c&&(u.a=d),u.b===c&&(u.b=d),u));else{const u=a.length;a.push(l),s.map(h=>(h.a===c&&(h.a=u),h.b===c&&(h.b=u),h))}}const r=s.filter(c=>c.a!==c.b);return{points:a,lines:r}}const _M=(i,t)=>{const n=i[0],e=i[1];let o=!1;for(let s=0,a=t.length-1;s<t.length;a=s++){const r=t[s][0],c=t[s][1],l=t[a][0],d=t[a][1];c>e!=d>e&&n<(l-r)*(e-c)/(d-c)+r&&(o=!o)}return o};function yM(i,t,n){const e=[];i.contourPoints.forEach(s=>{e.push([n[s][0],n[s][1]])});let o=0;return t.contourPoints.forEach(s=>{_M([n[s][0],n[s][1]],e)||o++}),o===0}function xM(i,t,n=!0){const e=i.filter(r=>r.type!=="CLOSED_PLANAR"),o=i.filter(r=>r.type==="CLOSED_PLANAR"),s=[];let a=[];return o.forEach((r,c)=>{const l=[];o.forEach((d,u)=>{c!=u&&yM(r,d,t)&&l.push(u)}),l.length>0?s.push({contour:r,holes:l}):a.push(c)}),n&&(s.forEach(r=>{r.contour.type="CLOSEDPLANAR_XOR",e.push(r.contour),r.holes.forEach(c=>{o[c].type="CLOSEDPLANAR_XOR",e.push(o[c]),a=a.filter(l=>l!==c)})}),a.forEach(r=>{e.push(o[r])})),e}const PM={processContourHoles:xM};function DM(i,t){return ma(t,i)}function xf(i){const t=[],n=[];i.forEach((e,o)=>{Ql(e)&&n.push({polyline:e,originalIndex:o})});for(let e=0;e<n.length;e++){const o=n[e],s=Math.abs(wo(o.polyline)),a=[];for(let r=0;r<n.length;r++){if(e===r)continue;const c=n[r];Math.abs(wo(c.polyline))<s&&DM(c.polyline,o.polyline)&&a.push(c.originalIndex)}a.length>0&&t.push({contourIndex:o.originalIndex,holeIndexes:a.sort((r,c)=>r-c)})}return t.sort((e,o)=>e.contourIndex-o.contourIndex)}let wl={};function Pf(){return wl}function TM(i){wl=i}let Xm=!1;function Yo(){if(!wl.addons?.polySeg)return console.warn("PolySeg add-on not configured. This will prevent automatic conversion between segmentation representations (labelmap, contour, surface). To enable these features, install @cornerstonejs/polymorphic-segmentation and register it during initialization: cornerstoneTools.init({ addons: { polySeg } })."),null;const i=wl.addons.polySeg;return Xm||(i.init(),Xm=!0),i}let qm=!1;function md(){if(qm)return;qm=!0;const i=()=>new Worker(new URL(""+new URL("computeWorker-D8XJyv-f.js",import.meta.url).href,import.meta.url),{name:"compute",type:"module"}),t=Es(),o={maxWorkerInstances:1,autoTerminateOnIdle:Pf().computeWorker?.autoTerminateOnIdle??{enabled:!0,idleTimeThreshold:2e3}};t.registerWorker("compute",i,o)}function pd(){return me.getState().segmentations}function MM(i){const{segmentationId:t,representation:n,config:e}=i,{type:o,data:s}=n,a=s?{...s}:{};if(!a)throw new Error("Segmentation representation data may not be undefined");o===St.Contour&&AM(a);const r=LM(e?.segments,o,a);delete e?.segments;const c={segmentationId:t,label:e?.label??null,fallbackLabel:e?.fallbackLabel??null,cachedStats:e?.cachedStats??{},segments:r,segmentOrder:e?.segmentOrder??Object.keys(r).map(Number).sort((l,d)=>l-d),representationData:{[o]:{...a}}};return o===St.Labelmap&&(kn(c),pi(c)),c}function AM(i){i.geometryIds=i.geometryIds??[],i.annotationUIDsMap=i.annotationUIDsMap??new Map}function LM(i,t,n){const e={};return i?Object.entries(i).forEach(([o,s])=>{const{label:a,locked:r,cachedStats:c,active:l,...d}=s,u={segmentIndex:Number(o),label:a??`Segment ${o}`,locked:r??!1,cachedStats:c??{},active:l??!1,...d};e[o]=u}):t===St.Contour?OM(e,n):t===St.Surface?RM(e,n):e[1]=NM(),e}function OM(i,t){const{geometryIds:n}=t;n?.forEach(e=>{const o=Q.getGeometry(e);if(o?.data){const{segmentIndex:s}=o.data;i[s]={segmentIndex:s}}})}function RM(i,t){const{geometryIds:n}=t;n?.forEach(e=>{const o=Q.getGeometry(e);if(o?.data){const{segmentIndex:s}=o.data;i[s]={segmentIndex:s}}})}function NM(){return{segmentIndex:1,label:"Segment 1",locked:!1,cachedStats:{},active:!0}}function hw(i,t){const n=me;i.forEach(e=>{const o=MM(e);n.addSegmentation(o),t||Co(o.segmentationId)})}const fw=new Map;function ou(i,t){fw.set(i,t)}function Df(i){return fw.get(i)}const oa=new Map;function Tf(i,t,n){const e=Df(n)?.getUpdateFunction(i);e&&gw(t,n,e)}function gw(i,t,n){oa.has(i)||oa.set(i,new Map);const e=oa.get(i);e.has(t)&&Mf(i,t);const o=UM(i,t,n);Z.addEventListener(E.SEGMENTATION_DATA_MODIFIED,o),e.set(t,o)}function Mf(i,t){const n=oa.get(i);if(!n)return;const e=n.get(t);e&&(Z.removeEventListener(E.SEGMENTATION_DATA_MODIFIED,e),n.delete(t))}function kM(i){const t=oa.get(i);if(t){for(const n of t.values())Z.removeEventListener(E.SEGMENTATION_DATA_MODIFIED,n);oa.delete(i)}}function UM(i,t,n){const e=Yr(o=>{const s=o.detail?.segmentationId,a=Dt(s);s===i&&a?.representationData?.[t]&&(n(i),Co(i))},300);return(o=>{e(o)})}function Ta(i,t,n){return pw(i,t,n)}function mw(i,t,n){return pw(i,t,n)}function pw(i,t,n){const{segmentationId:e,type:o}=t;return VM(i,e,o,n),me.removeSegmentationRepresentations(i,{segmentationId:e,type:o})}function vw(){me.getAllViewportSegmentationRepresentations().forEach(({viewportId:t,representations:n})=>{n.forEach(({segmentationId:e,type:o})=>{Ta(t,{segmentationId:e,type:o})})}),me.resetState()}function Iw(i,t,n){Ta(i,{segmentationId:t,type:St.Labelmap},n)}function ww(i,t,n){Ta(i,{segmentationId:t,type:St.Contour},n)}function Ew(i,t,n){Ta(i,{segmentationId:t,type:St.Surface},n)}function VM(i,t,n,e){Rn(i,{segmentationId:t,type:n}).forEach(a=>{const r=Df(a.type);r?r.removeRepresentation(i,a.segmentationId,e):console.warn(`No display registered for segmentation representation type ${a.type}.`),Mf(a.segmentationId,a.type)});const{viewport:s}=le(i)||{};s&&s.render()}function Af(i){const t=me;t.getAllViewportSegmentationRepresentations().filter(({representations:e})=>e.some(o=>o.segmentationId===i)).map(({viewportId:e})=>e).forEach(e=>{mw(e,{segmentationId:i})}),t.removeSegmentation(i),qh(i)}function Sw(){const i=me;i.getState().segmentations.map(e=>e.segmentationId).forEach(e=>{Af(e)}),i.resetState()}function Cw(){return me.getNextColorLUTIndex()}const ia=[[0,0,0,0],[221,84,84,255],[77,228,121,255],[166,70,235,255],[189,180,116,255],[109,182,196,255],[204,101,157,255],[123,211,94,255],[93,87,218,255],[225,128,80,255],[73,232,172,255],[181,119,186,255],[176,193,112,255],[105,153,200,255],[208,97,120,255],[90,215,101,255],[135,83,222,255],[229,178,76,255],[122,183,181,255],[190,115,171,255],[149,197,108,255],[100,118,205,255],[212,108,93,255],[86,219,141,255],[183,79,226,255],[233,233,72,255],[118,167,187,255],[194,111,146,255],[116,201,104,255],[115,96,209,255],[216,147,89,255],[82,223,188,255],[230,75,224,255],[163,184,121,255],[114,143,191,255],[198,107,114,255],[99,206,122,255],[153,92,213,255],[220,192,85,255],[78,215,227,255],[234,71,173,255],[141,188,117,255],[110,113,195,255],[202,128,103,255],[95,210,157,255],[195,88,217,255],[206,224,81,255],[74,166,231,255],[185,120,139,255],[113,192,113,255],[133,106,199,255],[207,162,98,255],[91,214,198,255],[221,84,198,255],[159,228,77,255],[70,111,235,255],[189,119,116,255],[109,196,138,255],[165,101,204,255],[211,201,94,255],[87,191,218,255],[225,80,153,255],[106,232,73,255],[124,119,186,255],[193,142,112,255],[105,200,168,255],[203,97,208,255],[184,215,90,255],[83,147,222,255],[229,76,101,255],[122,183,130,255],[146,115,190,255],[197,171,108,255],[100,205,205,255],[212,93,177,255],[141,219,86,255],[79,97,226,255],[233,99,72,255],[118,187,150,255],[173,111,194,255],[197,201,104,255],[96,171,209,255],[216,89,137,255],[94,223,82,255],[107,75,230,255],[184,153,121,255],[114,191,175,255],[198,107,191,255],[166,206,99,255],[92,132,213,255],[220,85,91,255],[78,227,115,255],[159,71,234,255],[188,176,117,255],[110,185,195,255],[202,103,161,255],[129,210,95,255],[88,88,217,255],[224,123,81,255],[74,231,166,255],[177,120,185,255],[179,192,113,255],[106,156,199,255],[207,98,125,255],[91,214,96,255],[130,84,221,255],[228,171,77,255],[70,235,221,255],[189,116,174,255],[153,196,109,255],[101,123,204,255],[211,104,94,255],[87,218,136,255],[177,80,225,255],[232,225,73,255],[119,169,186,255],[193,112,149,255],[121,200,105,255],[111,97,208,255],[215,142,90,255],[83,222,181,255],[229,76,229,255],[165,183,122,255],[115,146,190,255],[197,108,119,255],[100,205,118,255],[148,93,212,255],[219,186,86,255],[79,220,226,255],[233,72,179,255],[144,187,118,255],[111,118,194,255],[201,124,104,255],[96,209,153,255],[189,89,216,255],[211,223,82,255],[75,172,230,255],[184,121,142,255],[117,191,114,255],[130,107,198,255],[206,157,99,255],[92,213,193,255],[220,85,203,255],[165,227,78,255],[71,118,234,255],[188,117,117,255],[110,195,135,255],[161,103,202,255],[210,195,95,255],[88,195,217,255],[224,81,158,255],[113,231,74,255],[123,120,185,255],[192,139,113,255],[106,199,164,255],[198,98,207,255],[188,214,91,255],[84,153,221,255],[228,77,108,255],[70,235,84,255],[143,116,189,255],[196,167,109,255],[101,204,199,255],[211,94,182,255],[147,218,87,255],[80,104,225,255],[232,93,73,255],[119,186,147,255],[170,112,193,255],[200,200,105,255],[97,175,208,255],[215,90,142,255],[100,222,83,255],[101,76,229,255],[183,150,122,255],[115,190,171,255],[197,108,194,255],[170,205,100,255],[93,138,212,255],[219,86,97,255],[79,226,110,255],[153,72,233,255],[187,173,118,255],[111,187,194,255],[201,104,165,255],[134,209,96,255],[89,95,216,255],[223,117,82,255],[75,230,159,255],[174,121,184,255],[182,191,114,255],[107,160,198,255],[206,99,130,255],[92,213,92,255],[124,85,220,255],[227,165,78,255],[71,234,214,255],[188,117,176,255],[156,195,110,255],[103,128,202,255],[210,100,95,255],[88,217,131,255],[170,81,224,255],[231,218,74,255],[120,172,185,255],[192,113,153,255],[125,199,106,255],[107,98,207,255],[214,137,91,255],[84,221,175,255],[222,77,228,255],[194,235,70,255],[116,149,189,255],[196,109,123,255],[101,204,114,255],[143,94,211,255],[218,180,87,255],[80,225,225,255],[232,73,186,255],[147,186,119,255],[112,122,193,255],[200,121,105,255],[97,208,148,255],[184,90,215,255],[216,222,83,255],[76,178,229,255],[183,122,145,255],[121,190,115,255],[126,108,197,255],[205,153,100,255],[93,212,187,255],[219,86,208,255],[171,226,79,255],[72,126,233,255],[187,118,121,255],[111,194,132,255],[157,104,201,255],[209,190,96,255],[89,200,216,255],[223,82,164,255],[120,230,75,255],[121,121,184,255],[191,136,114,255],[107,198,160,255],[192,99,206,255],[193,213,92,255],[85,158,220,255],[227,78,115,255],[71,234,78,255],[141,117,188,255],[195,163,110,255],[103,202,194,255],[210,95,186,255],[153,217,88,255],[81,111,224,255]],FM=255,Ym=FM+1;function lr(i,t){const n=me,e=t??Cw();let o=[...i];if(ve(o[0],[0,0,0,0])||(console.warn("addColorLUT: [0, 0, 0, 0] color is not provided for the background color (segmentIndex =0), automatically adding it"),o=[[0,0,0,0],...o]),o=o.map(s=>s.length===3?[s[0],s[1],s[2],255]:s),o.length<Ym){const s=ia.slice(o.length);o=[...o,...s]}for(;o.length<Ym;){const s=(o.length-1)%(ia.length-1)+1;o.push([...ia[s]])}return n.addColorLUT(o,e),e}function rc(i){return me.getColorLUT(i)}function GM(i){me.removeColorLUT(i)}function bw(i,t){return _w(i).map(s=>(t&&s.type===t,Dt(s.segmentationId))).filter(s=>s!==void 0)}function _w(i){return me.getState().viewportSegRepresentations[i]}function Zi(i,t){const n=ys(i,t);if(!n?.length)return;if(n.length===1)return n[0];const e=Dt(t),o=xn(t),s=o?Sr(e,o):void 0;return s?.imageIds?.length?n.find(a=>s.imageIds.includes(a))??n[0]:n[0]}function ys(i,t){return me.getCurrentLabelmapImageIdsForViewport(i,t)}function HM(i,t){return me.getLabelmapImageIdsForImageId(i,t)}function yw(i,t){return me.updateLabelmapSegmentationImageReferences(i,t)}function WM(i,t){return me.getStackSegmentationImageIdsForViewport(i,t)}function BM(){me.resetState()}function zM(){return me}const $M=Object.freeze(Object.defineProperty({__proto__:null,addColorLUT:lr,addSegmentations:hw,destroy:BM,getColorLUT:rc,getCurrentLabelmapImageIdForViewport:Zi,getCurrentLabelmapImageIdsForViewport:ys,getDefaultSegmentationStateManager:zM,getNextColorLUTIndex:Cw,getSegmentation:Dt,getSegmentationRepresentation:Zl,getSegmentationRepresentations:Rn,getSegmentationRepresentationsBySegmentationId:XI,getSegmentations:pd,getStackSegmentationImageIdsForViewport:WM,getViewportIdsWithSegmentation:_s,getViewportSegmentationRepresentations:_w,getViewportSegmentations:bw,removeAllSegmentationRepresentations:vw,removeAllSegmentations:Sw,removeColorLUT:GM,removeContourRepresentation:ww,removeLabelmapRepresentation:Iw,removeSegmentation:Af,removeSegmentationRepresentation:Ta,removeSurfaceRepresentation:Ew,updateLabelmapSegmentationImageReferences:yw},Symbol.toStringTag,{value:"Module"}));function xw(i){if(i.volumeId){if(i=i,!Q.getVolume(i.volumeId))throw new Error(`volumeId of ${i.volumeId} not found in cache, you should load and cache volume before adding segmentation`)}else if("imageIds"in i){if(i=i,!i.imageIds)throw new Error("The segmentationInput.representationData.imageIds is undefined, please provide a valid representationData.imageIds for stack data")}else throw new Error("The segmentationInput.representationData is undefined, please provide a valid representationData")}function jM(i){if(!i.representation.data)throw new Error("The segmentationInput.representationData.data is undefined, please provide a valid representationData.data");const t=i.representation.data;xw(t)}function XM(i){xw(i)}const qM=Object.freeze(Object.defineProperty({__proto__:null,validate:XM,validatePublic:jM},Symbol.toStringTag,{value:"Module"}));function Pw(i,t,n){const e=le(i);if(!e)return;const{renderingEngine:o,viewport:s}=e;if(!o||!s)return;const r=s.getActors().filter(n);return r.length>0?r[0]:void 0}function YM(i,t){const n=le(i);if(!n)return;const{renderingEngine:e,viewport:o}=n;if(!e||!o)return;const a=o.getActors().filter(t);return a.length>0?a:void 0}function Dr(i,t){return YM(i,n=>n.representationUID?.startsWith(`${t}-${St.Labelmap}`))}function Lf(i,t,n){return Pw(i,t,e=>e.representationUID?.startsWith(`${t}-${St.Labelmap}`)&&(!n||e.referencedId===n))}function KM(i,t,n){return Pw(i,t,e=>e.representationUID===Dw(t,n))}function Dw(i,t){return`${i}-${St.Surface}-${t}`}function Tw(i){const t=Q.getVolume(i);if(!t)return null;const n=t.referencedVolumeId;let e;if(n)e=Q.getVolume(n);else{const s=t.imageIds?.[0];if(!s)return null;const a=Q.getImage(s);if(!a)return null;const r=a.referencedImageId;let c=r?Q.getVolumeContainingImageId(r):void 0;c?.volume||(c=Q.getVolumeContainingImageId(a.imageId)),e=c?.volume}return e}function ZM({operationData:i}){const{volumeId:t}=i;if(!t){const c=new CustomEvent(yt.ERROR_EVENT,{detail:{type:"Segmentation",message:"No volume id found for the segmentation"},cancelable:!0});return Z.dispatchEvent(c),null}const n=Q.getVolume(t),e=Tw(t);if(!n||!e)return null;const{imageData:o}=n,{voxelManager:s}=n,{voxelManager:a,imageData:r}=e;return{segmentationImageData:o,segmentationVoxelManager:s,segmentationScalarData:null,imageScalarData:null,imageVoxelManager:a,imageData:r}}function JM({operationData:i,viewport:t,strategy:n}){const{segmentationId:e}=i;let o,s,a,r,c,l;if(n.ensureSegmentationVolumeFor3DManipulation)n.ensureSegmentationVolumeFor3DManipulation({operationData:i,viewport:t}),s=i.segmentationVoxelManager,o=i.segmentationImageData,a=null;else{const d=Zi(t.id,e);if(!d)return null;const u=Lf(t.id,e,d);if(!u)return null;const h=Q.getImage(d);o=u.actor.getMapper().getInputData(),s=h.voxelManager;const f=i.imageId,g=Q.getImage(f);if(!g)return null;a=g.getPixelData?.()}if(n.ensureImageVolumeFor3DManipulation)n.ensureImageVolumeFor3DManipulation({operationData:i,viewport:t}),c=i.imageVoxelManager,r=i.imageScalarData,l=i.imageData;else{const d=t.getCurrentImageId();if(!d)return null;const u=Q.getImage(d);l=u?null:t.getImageData(),r=u?.getPixelData()||l.getScalarData(),c=u?.voxelManager}return{segmentationImageData:o,segmentationScalarData:a,imageScalarData:r,segmentationVoxelManager:s,imageVoxelManager:c,imageData:l}}function Of({operationData:i,viewport:t,strategy:n}){return i?"volumeId"in i&&i.volumeId!=null||"referencedVolumeId"in i&&i.referencedVolumeId!=null?ZM({operationData:i}):JM({operationData:i,viewport:t,strategy:n}):null}function Ma(i){const{representationData:t}=Dt(i);if(!t.Labelmap)return;let{volumeId:n}=t.Labelmap,e;if(n&&(e=Q.getVolume(n),e))return e;const{imageIds:o}=t.Labelmap;if(n=Q.generateVolumeId(o),!(!o||o.length===0||!Ss(o)))return e=jr(n,o),e}const Mw={[dt.EnsureSegmentationVolumeFor3DManipulation]:i=>{const{operationData:t,viewport:n}=i,{segmentationId:e,imageIds:o}=t,s=n?n.getImageIds():o.map(c=>Q.getImage(c).referencedImageId);if(!Ss(s))throw new Error("Volume is not reconstructable for sphere manipulation");const r=Ma(e);r&&(t.segmentationVoxelManager=r.voxelManager,t.segmentationImageData=r.imageData)}};function vd(i){if(!i?.length||!Ss(i))return;const n=Q.generateVolumeId(i);let e=Q.getVolume(n);return e||(e=jr(n,i),e)}const Aw={[dt.EnsureImageVolumeFor3DManipulation]:i=>{const{operationData:t,viewport:n}=i;let e;if(n){if(e=n.getImageIds(),!Ss(e))throw new Error("Volume is not reconstructable for sphere manipulation")}else e=Dt(t.segmentationId).representationData.Labelmap.imageIds.map(r=>Q.getImage(r).referencedImageId);const o=vd(e);if(!o)throw new Error("Failed to create or get image volume");t.imageVoxelManager=o.voxelManager,t.imageData=o.imageData}},Zo=(i,t)=>{Rt(Z,yt.WEB_WORKER_PROGRESS,{progress:t,type:i})},Lw=(i,t)=>{const n=Dt(i);if(!n?.representationData)return console.debug("getSegmentationDataForWorker: segmentation missing or not ready",i),null;const{representationData:e}=n,{Labelmap:o}=e;if(!o)return console.debug("No labelmap found for segmentation",i),null;const s=o.volumeId,a=o.imageIds,r={segmentationId:i,volumeId:s,imageIds:a};let c=!!s;if(!c&&a){const d=a.map(u=>Q.getImage(u).referencedImageId);c=Ss(d)}let l=t;return l?Array.isArray(l)||(l=[l,255]):l=[xn(i)],{operationData:r,segVolumeId:s,segImageIds:a,reconstructableVolume:c,indices:l}},Ow=i=>Of({operationData:i,strategy:{ensureSegmentationVolumeFor3DManipulation:Mw.ensureSegmentationVolumeFor3DManipulation,ensureImageVolumeFor3DManipulation:Aw.ensureImageVolumeFor3DManipulation}}),Rw=i=>{const t=[],n=[];for(const e of i){const o=Q.getImage(e),s=o.getPixelData(),{origin:a,direction:r,spacing:c,dimensions:l}=Ev(o);t.push({scalarData:s,dimensions:l,spacing:c,origin:a,direction:r});const d=o.referencedImageId;if(d){const u=Q.getImage(d);if(!u)continue;const h=u.getPixelData(),f=u.voxelManager,g=[u.rowPixelSpacing,u.columnPixelSpacing];n.push({scalarData:h,dimensions:f?f.dimensions:[u.columns,u.rows,1],spacing:g})}}return{segmentationInfo:t,imageInfo:n}},QM=(i,t)=>{let n;if(i){const r=Q.getVolume(i).imageIds,c=Q.getImage(r[0]);c&&(n=c.referencedImageId)}else t?.length&&(n=Q.getImage(t[0]).referencedImageId);const e=Q.getImage(n),o=rn("scalingModule",n),s={isPreScaled:!!e?.preScale?.scaled,isSuvScaled:typeof o?.suvbw=="number"};return{refImageId:n,modalityUnitOptions:s}},{Labelmap:tA}=St;async function Nw({segmentations:i}){md(),Zo(no.GENERATE_CONTOUR_SETS,0);const{representationData:t,segments:n=[0,1],segmentationId:e}=i;let{volumeId:o}=t[tA];if(!o){const g=Ma(e);g&&(o=g.volumeId)}const s=Q.getVolume(o);if(!s){console.warn(`No volume found for ${o}`);return}const c={scalarData:s.voxelManager.getCompleteScalarDataArray(),dimensions:s.dimensions,spacing:s.imageData.getSpacing(),origin:s.imageData.getOrigin(),direction:s.imageData.getDirection()},l=Array.isArray(n)?n.filter(g=>g!==null).map(g=>g.segmentIndex||g):Object.values(n).filter(g=>g!==null).map(g=>g.segmentIndex||g),d=await Es().executeTask("compute","generateContourSetsFromLabelmapVolume",{segmentation:c,indices:l,mode:"individual"}),u=s.imageIds.map(g=>{const m=Q.getImage(g)?.referencedImageId;return m?Q.getImage(m):void 0}),h=u.map(g=>Ev(g)),f=d.map(g=>{const m=n[g.segment.segmentIndex]||{};if(!g.sliceContours.length)return null;const p=g.sliceContours[0].polyData.points[0];let v;if(p){const I=h.findIndex(w=>{const{scanAxisNormal:C,origin:S}=w,b=$o(C,S);return IC(p,b)});I!==-1&&(v=u[I].imageId)}return{label:m.label,color:m.color,metadata:{FrameOfReferenceUID:s.metadata.FrameOfReferenceUID,referencedImageId:v},sliceContours:g.sliceContours.map(I=>({contours:I.contours,polyData:I.polyData,FrameNumber:I.sliceIndex+1,sliceIndex:I.sliceIndex,FrameOfReferenceUID:s.metadata.FrameOfReferenceUID,referencedImageId:v}))}}).filter(g=>g!==null);return Zo(no.GENERATE_CONTOUR_SETS,100),f}class kw{constructor(){}static getContourSequence(t,n){const{data:e}=t,{projectionPoints:o,projectionPointsImageIds:s}=e.cachedStats;return o.map((a,r)=>{const c=eA(a),l=nA(s[r],n);return{NumberOfContourPoints:c.length/3,ContourImageSequence:l,ContourGeometricType:"CLOSED_PLANAR",ContourData:c}})}}kw.toolName="RectangleROIStartEndThreshold";function eA(i){return[...i[0],...i[1],...i[3],...i[2]].flat().map(o=>o.toFixed(2))}function nA(i,t){const n=t.get("sopCommonModule",i);return{ReferencedSOPClassUID:n.sopClassUID,ReferencedSOPInstanceUID:n.sopInstanceUID}}function oA(i){if(!i?.data)throw new Error("Tool data is empty");if(!i.metadata||!i.metadata.referencedImageId)throw new Error("Tool data is not associated with any imageId")}class Bi{constructor(){}static convert(t,n,e){oA(t);const{toolName:o}=t.metadata,s=Bi.TOOL_NAMES[o];if(!s)throw new Error(`Unknown tool type: ${o}, cannot convert to RTSSReport`);const a=s.getContourSequence(t,e),r=n.color?.slice(0,3)||[Math.floor(Math.random()*255),Math.floor(Math.random()*255),Math.floor(Math.random()*255)];return{ReferencedROINumber:n.segmentIndex,ROIDisplayColor:r,ContourSequence:Array.isArray(a)?a:[a]}}static register(t){Bi.TOOL_NAMES[t.toolName]=t}}Bi.TOOL_NAMES={};Bi.register(kw);function iA(i,t){Wn.acceptAutoGenerated(i,t)}const{isEqual:sA}=oe;function oh(i,t){const{polyline:n}=i.data.contour,{points:e}=i.data.handles,{length:o}=e;if(t===o)return n.length;if(t<0&&(t=(t+o)%o),t===0)return 0;const s=e[t],a=n.findIndex(c=>sA(s,c));if(a!==-1)return a;let r=1/0;return n.reduce((c,l,d)=>{const u=gb(l,s);return u<r?(r=u,d):c},-1)}function Uw(i,t){if(!i||i.length===0)return[];if(t<=0)return[];const n=[];for(let e=0;e<i.length;e++){const o=i[e];if(!o||o.length<3)continue;Ql(o)&&Math.abs(wo(o))/100<t&&n.push(e)}return n}const aA=Object.freeze(Object.defineProperty({__proto__:null,AnnotationToPointData:Bi,acceptAutogeneratedInterpolations:iA,areCoplanarContours:EM,contourFinder:CM,detectContourHoles:PM,findContourHoles:xf,findHandlePolylineIndex:oh,findIslands:Uw,generateContourSetsFromLabelmap:Nw,getContourHolesDataCanvas:oc,getContourHolesDataWorld:D0,getDeduplicatedVTKPolyDataPoints:bM,updateContourPolyline:io},Symbol.toStringTag,{value:"Module"}));function rA(i,t){const n=Dt(i);if(!n){console.warn(`Invalid segmentation given ${i}`);return}if(!n.representationData.Contour){console.warn(`No contour representation found for segmentation ${i}`);return}const e=ac(i,t);if(!e){console.warn(`Error extracting contour data from segment ${t} in segmentation ${i}`);return}const o=Array.from(e?.keys()),s=o.map(r=>e.get(r)),a=xf(s);a?.length>0&&a.forEach(r=>{r.holeIndexes.forEach(c=>{const l=ne(o[c]);gd(l)})})}function cA(i,t,n={threshold:3}){const e=Dt(i);if(!e){console.warn(`Invalid segmentation given ${i}`);return}if(!e.representationData.Contour){console.warn(`No contour representation found for segmentation ${i}`);return}const o=ac(i,t);if(!o){console.warn(`Error extracting contour data from segment ${t} in segmentation ${i}`);return}const s=Array.from(o?.keys()),a=s.map(c=>o.get(c)),r=Uw(a,n.threshold);r?.length>0&&r.forEach(c=>{const l=ne(s[c]);gd(l)})}function lA(i,t,n={knotsRatioPercentage:30}){const e=Dt(i);if(!e){console.warn(`Invalid segmentation given ${i}`);return}if(!e.representationData.Contour){console.warn(`No contour representation found for segmentation ${i}`);return}const o=e.representationData.Contour,{annotationUIDsMap:s}=o;if(!s){console.warn(`No contours found for segmentation ${i}`);return}if(!s.has(t)){console.warn(`Error extracting contour data from segment ${t} in segmentation ${i}`);return}s.get(t).forEach(r=>{const c=ne(r);if(!c)return;const l=c.data.contour.polyline;if(!l||l.length<3)return;const d=dl(l,0,l.length-1,n.knotsRatioPercentage);c.data.contour.polyline=d})}function dA(i,t,n,e){const o=Dt(i);if(!o){console.warn(`Invalid segmentation given ${i}`);return}if(!o.representationData.Contour){console.warn(`No contour representation found for segmentation ${i}`);return}const{annotationUIDsMap:s}=o?.representationData.Contour||{};if(!s){console.warn(`No annotation map found for segmentation ${i}`);return}const a=s?.get(t);if(!a){console.warn(`Segmentation index ${t} has no annotations in segmentation ${i}`);return}let r;if(n&&typeof e=="number"){const h=Dt(n);if(!h){console.warn(`Target segmentation ${n} does not exist.`);return}if(!h.representationData.Contour){console.warn(`No contour representation found for target segmentation ${n}`);return}r=h.representationData.Contour.annotationUIDsMap.get(e),r||(r=new Set,h.representationData.Contour.annotationUIDsMap.set(e,r))}const c=ac(i,t);if(!c){console.warn(`Error extracting contour data from segment ${t} in segmentation ${i}`);return}const l=Array.from(c?.keys()),d=l.map(h=>c.get(h)),u=xf(d);u?.length>0&&u.forEach(h=>{h.holeIndexes.forEach(f=>{const g=ne(l[f]);Wl(g),n&&typeof e=="number"?r.add(g.annotationUID):a.add(g.annotationUID)})})}const uA=Object.freeze(Object.defineProperty({__proto__:null,convertContourHoles:dA,decimateContours:wM,extractSegmentPolylines:ac,getAnnotationMapFromSegmentation:dw,getAnnotationsUIDMapFromSegmentation:yr,getViewportAssociatedToSegmentation:If,getViewportWithMatchingViewPlaneNormal:wf,removeCompleteContourAnnotation:gd,removeContourHoles:rA,removeContourIslands:cA,smoothContours:lA},Symbol.toStringTag,{value:"Module"}));function hA(i,t,n){const e=yr(i.segmentationId);if(!e)return;const o=e.get(t);o&&o.forEach(s=>{cd(s,n)})}function fA(i,t){const n=Dt(i);if(!n)throw new Error(`No segmentation state found for ${i}`);const{segments:e}=n;return e[t].locked}function gA(i,t,n=!0){const e=Dt(i);if(!e)throw new Error(`No segmentation state found for ${i}`);const{segments:o}=e;o[t].locked=n,e?.representationData?.Contour&&hA(e,t,n),Co(i)}function xs(i){const t=Dt(i);if(!t)throw new Error(`No segmentation state found for ${i}`);const{segments:n}=t;return Object.keys(n).filter(o=>n[o].locked).map(o=>parseInt(o))}const mA=Object.freeze(Object.defineProperty({__proto__:null,getLockedSegmentIndices:xs,isSegmentIndexLocked:fA,setSegmentIndexLocked:gA},Symbol.toStringTag,{value:"Module"}));function pA(i,t){if(!i)throw new Error("addColorLUT: colorLUT is required");return lr(i,t)}function vA(i,t,n){if(!rc(n))throw new Error(`setColorLUT: could not find colorLUT with index ${n}`);const e=Rn(i,{segmentationId:t});if(!e)throw new Error(`viewport specific state for viewport ${i} does not exist`);e.forEach(o=>{o.colorLUTIndex=n}),Mo(i,t)}function Jo(i,t,n){const e=Rn(i,{segmentationId:t});if(!e||e.length===0)return null;const o=e[0],{colorLUTIndex:s}=o,a=rc(s);let r=a[n];if(!r){if(typeof n!="number")return console.warn(`Can't create colour for LUT index ${n}`),null;r=a[n]=[0,0,0,0]}return r}function Vw(i,t,n,e){const o=Jo(i,t,n);for(let s=0;s<e.length;s++)o[s]=e[s];Mo(i,t)}const IA=Object.freeze(Object.defineProperty({__proto__:null,addColorLUT:pA,getSegmentIndexColor:Jo,setColorLUT:vA,setSegmentIndexColor:Vw},Symbol.toStringTag,{value:"Module"}));function Fw(i,t){return me.getSegmentationRepresentationVisibility(i,t)}function Rf(i,t){const n=Zl(i,t);return n?Object.entries(n.segments).reduce((o,[s,a])=>(a.visible||o.add(Number(s)),o),new Set):new Set}function Gw({segmentationId:i,segmentIndex:t,viewportId:n,autoGenerated:e=!1}){const o=Jo(n,i,t),s=Fw(n,{segmentationId:i,type:St.Contour}),r=Wi(n)?.segmentationId===i,c=Yn.getRenderInactiveSegmentations(n),d=Yn.getStyle({viewportId:n,segmentationId:i,type:St.Contour,segmentIndex:t});let u=1,h,f=1,g=0,m=d.renderFill??!0,p=d.renderOutline??!0;e?(u=d.outlineWidthAutoGenerated??u,h=d.outlineDashAutoGenerated??h,f=d.outlineOpacity??f,g=d.fillAlphaAutoGenerated??g):r?(u=d.outlineWidth??u,h=d.outlineDash??h,f=d.outlineOpacity??f,g=d.fillAlpha??g):(u=d.outlineWidthInactive??u,h=d.outlineDashInactive??h,f=d.outlineOpacityInactive??f,g=d.fillAlphaInactive??g,m=d.renderFillInactive??m,p=d.renderOutlineInactive??p),xn(i)===t&&(u+=d.activeSegmentOutlineWidthDelta),u=p?u:0,g=m?g:0;const v=`rgba(${o[0]}, ${o[1]}, ${o[2]}, ${f})`,I=`rgb(${o[0]}, ${o[1]}, ${o[2]})`,C=!Rf(n,{segmentationId:i,type:St.Contour}).has(t);return{color:v,fillColor:I,lineWidth:u,fillOpacity:g,lineDash:h,textbox:{color:v},visibility:r?s&&C:c}}class ws extends XT{constructor(t,n){super(t,n),this.configuration.interpolation?.enabled&&Wn.addTool(this.getToolName())}recordTouchLiftCommit(t){this._touchLiftCommit={canvasPoint:t,time:Date.now()}}isTouchTapEchoOfLiftCommit(t){if(!this._touchLiftCommit)return!1;const{canvasPoint:n,time:e}=this._touchLiftCommit;return Date.now()-e<=2*ws.TOUCH_TAP_TOLERANCE_MS?ro(t,n)<=ws.TOUCH_TAP_MAX_CANVAS_DISTANCE?(this._touchLiftCommit=void 0,!0):!1:(this._touchLiftCommit=void 0,!1)}onSetToolConfiguration(){this.configuration.interpolation?.enabled?Wn.addTool(this.getToolName()):Wn.removeTool(this.getToolName())}isContourSegmentationTool(){return!0}createAnnotation(t){const n=t.detail,{element:e}=n,o=N(e);if(!o)return;const{viewport:s}=o,a=super.createAnnotation(t);if(!this.isContourSegmentationTool())return a;const r=Wi(s.id);if(!r)throw new Error("No active segmentation detected, create one before using scissors tool");if(!r.representationData.Contour)throw new Error("A contour segmentation must be active");const{segmentationId:c}=r,l=xn(c);return Hn(a,{data:{segmentation:{segmentationId:c,segmentIndex:l}}})}addAnnotation(t,n){const e=super.addAnnotation(t,n);return this.isContourSegmentationTool()&&Ho(t),e}cancelAnnotation(t){this.isContourSegmentationTool()&&_o(t),super.cancelAnnotation(t)}getAnnotationStyle(t){const n=super.getAnnotationStyle(t);if(!this.isContourSegmentationTool())return n;const e=this._getContourSegmentationStyle(t);return Hn(n,e)}renderAnnotationInstance(t){const{annotation:n}=t,{invalidated:e}=n,o=super.renderAnnotationInstance(t);if(e&&this.isContourSegmentationTool()){const{segmentationId:s}=n.data.segmentation;He(s);const r=_s(s).map(c=>Ae(c)?.id).filter(c=>c!=null);lw(r)}return o}filterInteractableAnnotationsForElement(t,n){if(!n||!n.length)return;const e=super.filterInteractableAnnotationsForElement(t,n);if(!e||!e.length)return;const o=N(t),{viewport:s}=o;return e.filter(a=>{const r=a?.data?.segmentation?.segmentationId;return r?!!me.getSegmentationRepresentation(s.id,{segmentationId:r,type:St.Contour}):!0})}_getContourSegmentationStyle(t){const n=t.annotation,{segmentationId:e,segmentIndex:o}=n.data.segmentation,{viewportId:s}=t.styleSpecifier,a=Rn(s,{segmentationId:e});if(!a?.length)return{};a.length>1?a.find(p=>p.segmentationId===e&&p.type===St.Contour):a[0];const{autoGenerated:r}=n,l=xs(e).includes(o),{color:d,fillColor:u,lineWidth:h,fillOpacity:f,lineDash:g,visibility:m}=Gw({segmentationId:e,segmentIndex:o,viewportId:s,autoGenerated:r});return{color:d,fillColor:u,lineWidth:h,fillOpacity:f,lineDash:g,textbox:{color:d},visibility:m,locked:l}}}ws.PreviewSegmentIndex=255;function Hw(i,t){const n=rn("generalSeriesModule",i);return bi(n.modality,i,t)}function bi(i,t,n){return i==="CT"?"HU":i==="PT"?wA(t,n):""}function wA(i,t){return t.isPreScaled?t.isSuvScaled?"SUV":rn("generalSeriesModule",i)?.modality==="PT"?rn("petSeriesModule",i)?.units||"unitless":"unknown":"raw"}function Xc(i,t){if(t-i<=1){const e=Math.round((i+t)/2);return[e,e]}return[Math.floor(i),Math.ceil(t)]}const{pointCanProjectOnLine:Km}=Yi,{EPSILON:EA}=Qo,SA=1-EA;class Tr extends ws{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{storePointData:!1,shadow:!0,preventHandleOutsideImage:!1,contourHoleAdditionModifierKey:vn.Shift,alwaysRenderOpenContourHandles:{enabled:!1,radius:2},allowOpenContours:!0,closeContourProximity:10,checkCanvasEditFallbackProximity:6,makeClockWise:!0,subPixelResolution:4,smoothing:{smoothOnAdd:!1,smoothOnEdit:!1,knotsRatioPercentageOnAdd:40,knotsRatioPercentageOnEdit:40},interpolation:{enabled:!1,onInterpolationComplete:null},decimate:{enabled:!1,epsilon:.1},displayOnePointAsCrosshairs:!1,calculateStats:!0,getTextLines:CA,statsCalculator:bo}}){super(t,n),this.isDrawing=!1,this.isEditingClosed=!1,this.isEditingOpen=!1,this.addNewAnnotation=e=>{const o=e.detail,{element:s}=o,a=this.createAnnotation(e);this.addAnnotation(a,s);const r=ft(s,this.getToolName());return this.activateDraw(e,a,r),e.preventDefault(),V(r),a},this.handleSelectedCallback=(e,o,s)=>{const a=e.detail,{element:r}=a,c=ft(r,this.getToolName());this.activateOpenContourEndEdit(e,o,c,s)},this.toolSelectedCallback=(e,o)=>{const s=e.detail,{element:a}=s,r=ft(a,this.getToolName());o.data.contour.closed?this.activateClosedContourEdit(e,o,r):this.activateOpenContourEdit(e,o,r),e.preventDefault()},this.isPointNearTool=(e,o,s,a)=>{const r=N(e),{viewport:c}=r,{polyline:l}=o.data.contour;let d=c.worldToCanvas(l[0]);for(let f=1;f<l.length;f++){const g=d,m=c.worldToCanvas(l[f]);if(Km(s,g,m,a))return!0;d=m}if(!o.data.contour.closed)return!1;const u=c.worldToCanvas(l[0]),h=c.worldToCanvas(l[l.length-1]);return Km(s,u,h,a)},this.cancel=e=>{const o=this.isDrawing,s=this.isEditingOpen,a=this.isEditingClosed;o?this.cancelDrawing(e):s?this.cancelOpenContourEdit(e):a&&this.cancelClosedContourEdit(e)},this._calculateCachedStats=(e,o,s,a)=>{const{data:r}=e,{cachedStats:c}=r,{polyline:l,closed:d}=r.contour,u=Object.keys(c);for(let f=0;f<u.length;f++){const g=u[f],m=this.getTargetImageData(g);if(!m)continue;const{imageData:p,metadata:v,voxelManager:I}=m,w=l.map(ot=>o.worldToCanvas(ot)),C={isPreScaled:Ki(o,g),isSuvScaled:this.isSuvScaled(o,g,e.metadata.referencedImageId)},S=bi(v.Modality,e.metadata.referencedImageId,C),b=r.contour.polyline,_=b.length,y=new Array(_);for(let ot=0;ot<_;ot++)y[ot]=o.worldToCanvas(b[ot]);const{maxX:D,maxY:T,minX:P,minY:x}=Ei(y),M=o.canvasToWorld([P,x]),L=wn(p,M),R=o.canvasToWorld([D,T]),U=wn(p,R),K=ao(m,[L,U]),j=w[0],F=o.canvasToWorld(j),z=o.canvasToWorld([j[0]+1,j[1]]),q=o.canvasToWorld([j[0],j[1]+1]),J=ke(F,z),it=ke(F,q),tt={targetId:g,viewport:o,canvasCoordinates:w,points:l,imageData:p,metadata:v,voxelManager:I,cachedStats:c,modalityUnit:S,calibratedScale:K,deltaInX:J,deltaInY:it};d?this.updateClosedCachedStats(tt):this.updateOpenCachedStats(tt)}const h=e.invalidated;return e.invalidated=!1,h&&zt(e,a.viewport.element,Bt.StatsUpdated),c},this._renderStats=(e,o,s,a)=>{const{data:r}=e,c=this.getTargetId(o,r),l={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:s.viewport.id,annotationUID:e.annotationUID},d=this.configuration.getTextLines(r,c);if(!d||d.length===0)return;const u=r.contour.polyline.map(h=>o.worldToCanvas(h));this.renderLinkedTextBoxAnnotation({enabledElement:s,svgDrawingHelper:a,annotation:e,styleSpecifier:l,textLines:d,canvasCoordinates:u})},YP(this),oD(this),fD(this),xD(this),TD(this),HD(this),this._throttledCalculateCachedStats=Un(this._calculateCachedStats,100,{trailing:!0})}filterInteractableAnnotationsForElement(t,n){if(!n?.length)return[];const e=super.filterInteractableAnnotationsForElement(t,n);if(!e?.length)return[];const o=N(t),{viewport:s}=o;let a;if(s instanceof Xe){const r=s.getCamera(),{spacingInNormalDirection:c}=_h(s,r);a=this.filterAnnotationsWithinSlice(e,r,c)}else a=ya(s,n);return a}filterAnnotationsWithinSlice(t,n,e){const{viewPlaneNormal:o}=n,s=t.filter(l=>{let d=l.metadata.viewPlaneNormal;if(!l.metadata.referencedImageId&&!d&&l.metadata.FrameOfReferenceUID){for(const h of l.data.contour.polyline){const f=tn(B(),h,n.focalPoint),g=xt(f,n.viewPlaneNormal);if(!ve(g,0))return!1}return l.metadata.viewPlaneNormal=n.viewPlaneNormal,l.metadata.cameraFocalPoint=n.focalPoint,!0}if(!d){const{referencedImageId:h}=l.metadata,{imageOrientationPatient:f}=rn("imagePlaneModule",h),g=Ot(f[0],f[1],f[2]),m=Ot(f[3],f[4],f[5]);d=B(),Me(d,g,m),l.metadata.viewPlaneNormal=d}const u=Math.abs(xt(o,d))>SA;return d&&u});if(!s.length)return[];const a=e/2,{focalPoint:r}=n,c=[];for(const l of s){const u=l.data.contour.polyline[0];if(!l.isVisible)continue;const h=B();tn(h,r,u);const f=xt(h,o);Math.abs(f)<a&&c.push(l)}return c}isContourSegmentationTool(){return!1}createAnnotation(t){const n=t.detail.currentPoints.world,e=super.createAnnotation(t),o=a=>{a.data.handles.points.length=0};return Hn(e,{data:{contour:{polyline:[[...n]]},label:"",cachedStats:{}},onInterpolationComplete:o})}getAnnotationStyle(t){return super.getAnnotationStyle(t)}renderAnnotationInstance(t){const{enabledElement:n,targetId:e,svgDrawingHelper:o}=t,s=t.annotation;let a=!1;const{viewport:r,renderingEngine:c}=n,l=this.isDrawing,d=this.isEditingOpen,u=this.isEditingClosed;if(!(l||d||u))this.configuration.displayOnePointAsCrosshairs&&s.data.contour.polyline.length===1?this.renderPointContourWithMarker(n,o,s):this.renderContour(n,o,s);else{const m=this.commonData.annotation.annotationUID;if(s.annotationUID===m)if(l)this.renderContourBeingDrawn(n,o,s);else if(u)this.renderClosedContourBeingEdited(n,o,s);else if(d)this.renderOpenContourBeingEdited(n,o,s);else throw new Error(`Unknown ${this.getToolName()} annotation rendering state`);else this.configuration.displayOnePointAsCrosshairs&&s.data.contour.polyline.length===1?this.renderPointContourWithMarker(n,o,s):this.renderContour(n,o,s);a=!0}if(!this.configuration.calculateStats)return;const{data:h,invalidated:f}=s,g=h?.cachedStats;return(f||!g?.[e])&&this._calculateStatsIfActive(s,e,r,c,n),this._renderStats(s,r,n,o),a}_calculateStatsIfActive(t,n,e,o,s){const a=this.commonData?.annotation.annotationUID;if(!(t.annotationUID===a&&!this.commonData?.movingTextBox)&&!this.commonData?.movingTextBox){const{data:r}=t;r.cachedStats[n]?.unit?t.invalidated&&this._throttledCalculateCachedStats(t,e,o,s):(r.cachedStats[n]={Modality:null,area:null,max:null,mean:null,stdDev:null,areaUnit:null,unit:null},this._calculateCachedStats(t,e,o,s))}}updateClosedCachedStats({viewport:t,points:n,imageData:e,metadata:o,voxelManager:s,cachedStats:a,targetId:r,modalityUnit:c,canvasCoordinates:l,calibratedScale:d,deltaInX:u,deltaInY:h}){const{areaUnit:f,unit:g}=d,m=n.map(q=>e.worldToIndex(q)),p=e.getDimensions();let v=Number.MAX_SAFE_INTEGER,I=Number.MIN_SAFE_INTEGER,w=Number.MAX_SAFE_INTEGER,C=Number.MIN_SAFE_INTEGER,S=Number.MAX_SAFE_INTEGER,b=Number.MIN_SAFE_INTEGER;for(let q=0;q<n.length;q++){const J=m[q];v=Math.min(v,J[0]),I=Math.max(I,J[0]),w=Math.min(w,J[1]),C=Math.max(C,J[1]),S=Math.min(S,J[2]),b=Math.max(b,J[2])}v=Math.max(0,Math.min(p[0]-1,v)),I=Math.max(0,Math.min(p[0]-1,I)),w=Math.max(0,Math.min(p[1]-1,w)),C=Math.max(0,Math.min(p[1]-1,C)),S=Math.max(0,Math.min(p[2]-1,S)),b=Math.max(0,Math.min(p[2]-1,b)),[v,I]=Xc(v,I),[w,C]=Xc(w,C),[S,b]=Xc(S,b);const _=ms(l)*u*h,y=Tr.calculateLengthInIndex(d,m,closed),D=.01*(I-v),T=.01*(C-w),P=.01*(b-S);v=Math.floor(v-D),I=Math.ceil(I+D),w=Math.floor(w-T),C=Math.ceil(C+T),S=Math.floor(S-P),b=Math.ceil(b+P);const x=[[v,I],[w,C],[S,b]],M=e.indexToWorld([I,C,b]),L=t.worldToCanvas(M);let R=0,U=[],W=0,K;s&&(K=s.forEach(this.configuration.statsCalculator.statsCallback,{imageData:e,isInObject:(q,J)=>{let it=!0;const tt=t.worldToCanvas(q);return tt[1]!=R&&(W=0,R=tt[1],U=s0(l,tt,[L[0],tt[1]]),U.sort((function(ot){return function(nt,lt){return nt[ot]===lt[ot]?0:nt[ot]<lt[ot]?-1:1}})(0))),U.length&&tt[0]>U[0][0]&&(U.shift(),W++),W%2===0&&(it=!1),it},boundsIJK:x,returnPoints:this.configuration.storePointData}));const j=this.configuration.statsCalculator.getStatistics(),F={name:"area",value:_,unit:f,type:Io.Area},z={name:"perimeter",value:y,unit:g,type:Io.Linear};a[r]={Modality:o.Modality,area:_,perimeter:y,mean:j.mean?.value,max:j.max?.value,min:j.min?.value,stdDev:j.stdDev?.value,statsArray:[F,z,...j.array],pointsInShape:K,areaUnit:f,modalityUnit:c,unit:g}}updateOpenCachedStats({targetId:t,metadata:n,cachedStats:e,modalityUnit:o,calibratedScale:s,imageData:a,points:r}){const{unit:c}=s,l=r.map(h=>a.worldToIndex(h)),d=Tr.calculateLengthInIndex(s,l),u={name:"length",value:d,unit:c,type:Io.Linear};e[t]={Modality:n.Modality,length:d,modalityUnit:o,unit:c,statArray:[u]}}}Tr.toolName="PlanarFreehandROI";function CA(i,t){const n=i.cachedStats[t],{area:e,mean:o,stdDev:s,length:a,perimeter:r,max:c,min:l,isEmptyArea:d,unit:u,areaUnit:h,modalityUnit:f}=n||{},g=[];if(Fn(e)){const m=d?"Area: Oblique not supported":`Area: ${de(e)} ${h}`;g.push(m)}return Fn(o)&&g.push(`Mean: ${de(o)} ${f}`),Fn(c)&&g.push(`Max: ${de(c)} ${f}`),Fn(l)&&g.push(`Min: ${de(l)} ${f}`),Fn(s)&&g.push(`Std Dev: ${de(s)} ${f}`),Fn(r)&&g.push(`Perimeter: ${de(r)} ${u}`),Fn(a)&&g.push(`${de(a)} ${u}`),g}var Ww;class cc extends Tr{constructor(t){const n=Hn({configuration:{calculateStats:!1,allowOpenContours:!1}},t);super(n)}isContourSegmentationTool(){return!0}renderAnnotationInstance(t){const n=t.annotation,{invalidated:e}=n,o=super.renderAnnotationInstance(t);if(e){const{segmentationId:s}=n.data.segmentation;He(s)}return o}}Ww=cc;cc.toolName="PlanarFreehandContourSegmentationTool";Bi.register(Ww);const Tc=cc.toolName;class bA{constructor(){this._needsRender=new Set,this._pendingRenderQueue=[],this._animationFrameSet=!1,this._animationFrameHandle=null,this._getAllViewports=()=>Vi().flatMap(n=>n.getViewports()),this._renderFlaggedSegmentations=()=>{if(this._throwIfDestroyed(),Array.from(this._needsRender).forEach(n=>{this._triggerRender(n)}),this._needsRender.clear(),this._animationFrameSet=!1,this._animationFrameHandle=null,this._pendingRenderQueue.length>0){const n=this._pendingRenderQueue.shift();n&&n.length>0&&this._setViewportsToBeRenderedNextFrame(n)}}}renderSegmentationsForViewport(t){const n=t?[t]:this._getViewportIdsForSegmentation();this._setViewportsToBeRenderedNextFrame(n)}renderSegmentation(t){const n=this._getViewportIdsForSegmentation(t);this._setViewportsToBeRenderedNextFrame(n)}_getViewportIdsForSegmentation(t){const n=this._getAllViewports(),e=[];for(const o of n){const s=o.id;t?Rn(s,{segmentationId:t})?.length>0&&e.push(s):Rn(s)?.length>0&&e.push(s)}return e}_throwIfDestroyed(){if(this.hasBeenDestroyed)throw new Error("this.destroy() has been manually called to free up memory, can not longer use this instance. Instead make a new one.")}_setViewportsToBeRenderedNextFrame(t){if(this._animationFrameSet){this._pendingRenderQueue.push(t);return}t.forEach(n=>{this._needsRender.add(n)}),this._render()}_render(){this._needsRender.size>0&&this._animationFrameSet===!1&&(this._animationFrameHandle=window.requestAnimationFrame(this._renderFlaggedSegmentations),this._animationFrameSet=!0)}_triggerRender(t){const n=Rn(t);if(!n?.length)return;const{viewport:e}=le(t)||{};if(!e)return;const o=n.map(s=>{s.type===St.Contour&&this._addPlanarFreeHandToolIfAbsent(e);const a=Df(s.type),c=Dt(s.segmentationId).representationData[s.type]!==void 0;return a?a.render(e,s).then(()=>(c||Tf(e,s.segmentationId,s.type),{segmentationId:s.segmentationId,type:s.type})).catch(l=>(console.error(l),{segmentationId:s.segmentationId,type:s.type})):(console.warn(`No display registered for segmentation representation type ${s.type}.`),Promise.resolve({segmentationId:s.segmentationId,type:s.type}))});Promise.allSettled(o).then(s=>{const a=s.filter(l=>l.status==="fulfilled").map(l=>l.value);function r(l){const{element:d,viewportId:u}=l.detail;d.removeEventListener(yt.IMAGE_RENDERED,r),a.forEach(h=>{const f={viewportId:u,segmentationId:h.segmentationId,type:h.type};Rt(Z,E.SEGMENTATION_RENDERED,{...f})})}e.element.addEventListener(yt.IMAGE_RENDERED,r),e.render()})}_addPlanarFreeHandToolIfAbsent(t){Tc in $.tools||Xv(cc);const n=Ae(t.id);n.hasTool(Tc)||(n.addTool(Tc),n.setToolPassive(Tc))}}function _i(i){dr.renderSegmentationsForViewport(i)}function Nf(i){dr.renderSegmentation(i)}const _A=240,iu=new Map;function yA(i){if(i.getBlendMode?.()===Gn.LABELMAP_EDGE_PROJECTION_BLEND)return!0;const n=i;if(typeof n.getDisplaySetPresentation!="function")return!1;const e=[],o=n.getSourceDataId?.();return o&&e.push(o),n.getActors?.().forEach(s=>{s.representationUID&&e.push(String(s.representationUID))}),e.some(s=>(n.getDisplaySetPresentation(s)?.slabThickness??0)>0)}function xA(i){dr._getViewportIdsForSegmentation(i).forEach(n=>{const{viewport:e}=le(n)||{};if(!e)return;if(!yA(e)){dr.renderSegmentationsForViewport(n);return}const o=iu.get(n);o!==void 0&&clearTimeout(o),iu.set(n,setTimeout(()=>{iu.delete(n),dr.renderSegmentationsForViewport(n)},_A))})}const dr=new bA;function PA({modifiedSlicesToUse:i,representationData:t,type:n}){const e=t[n];DA(e).forEach(s=>{const{imageData:a,vtkOpenGLTexture:r,voxelManager:c}=s;let l;if(i?.length>0)l=i;else{const h=a.getDimensions()[2];l=[...Array(h).keys()]}r?.setUpdatedFrame&&l.forEach(h=>{r.setUpdatedFrame(h)}),c?.invalidateCache?.(),a.modified();const d=s.imageIds?.length??a.getDimensions()[2]??0,u=s.metadata?.FrameOfReferenceUID??"";Rt(Z,yt.IMAGE_VOLUME_MODIFIED,{volumeId:s.volumeId,FrameOfReferenceUID:u,numberOfFrames:d,framesProcessed:d})})}function DA(i){const t=[],n=new Set,e=o=>{!o?.volumeId||n.has(o.volumeId)||(n.add(o.volumeId),t.push(o))};return Object.values(i?.labelmaps??{}).forEach(o=>{e($n(o))}),e(i?.volumeId&&Q.getVolume(i.volumeId)),t}function Bw(i){return i.referencedImageIds?.length?i.referencedImageIds:(i.imageIds??(i.volumeId?Q.getVolume(i.volumeId)?.imageIds:void 0)??[]).map(n=>Q.getImage(n)?.referencedImageId).filter(Boolean)}function TA(i){const t=new Set;if(i.volumeId){const n=Q.getVolume(i.volumeId)?.metadata?.FrameOfReferenceUID;n&&t.add(n)}for(const n of Bw(i)){const e=rn("imagePlaneModule",n)?.frameOfReferenceUID;e&&t.add(e)}return[...t]}function MA(i,t){let n;try{n=i.getFrameOfReferenceUID?.()}catch{return!0}if(!n)return!0;const e=t.flatMap(o=>TA(o));return e.length?e.includes(n):!0}function AA(i,t){const n=t.flatMap(s=>Bw(s));if(!n.length)return!0;let e;try{e=i.getImageIds?.()??[]}catch{return!0}if(!e.length)return!0;const o=new Set(n);return e.some(s=>o.has(s))}function zw(i,t,n){if(n!==St.Labelmap||!i)return!0;const e=Dt(t);if(!e)return!0;const o=cn(e);return typeof i.getAllVolumeIds=="function"?MA(i,o):AA(i,o)}function $w(i){return`${i}-${St.Labelmap}`}function Ji({segmentationId:i,referencedId:t,sliceStateKey:n}){return[$w(i),t,n].filter(Boolean).join("-")}function Id(i,t){return typeof i=="string"&&i.startsWith($w(t))}function jw(i,t,n){const e=n.representationUID;if(!Id(e,t))return!1;const o=i;return typeof o.removeData!="function"?!1:(xh.remove(e),o.removeData(e),!0)}function wd(i,t){if(typeof i.getCurrentImageId!="function")return;const n=i.getCurrentImageId();if(!n||!zw(i,t,St.Labelmap))return;yw(i.id,t);const e=ys(i.id,t)??[],o=new Set(e),a=(Dr(i.id,t)??[]).filter(g=>!o.has(g.referencedId)),r=LA(a[0]?.actor);let c=!1,l=a.length>0;if(a.length){const g=[];a.forEach(m=>{jw(i,t,m)||g.push(m.uid)}),g.length&&i.removeActors(g),c=!0}const d=zn(i),u=i.getDefaultActor()?.actorMapper?.renderMode,h=Q.getImage(n)||{imageId:n},{origin:f}=i.getImageDataMetadata(h);e.forEach(g=>{const m=Q.getImage(g);if(!m){console.warn("No derived image found in the cache for segmentation representation",{segmentationId:t,derivedImageId:g});return}const p=Dr(i.id,t)?.find(C=>C.referencedId===g);if(!p){const C=Ji({segmentationId:t,referencedId:m.imageId});if(d==="image"&&u===We.CPU_IMAGE)i.addImages([{dataId:C,imageId:g,reference:{kind:"segmentation",segmentationId:t,representationUID:C,labelmapId:m.imageId},representationUID:C}]);else{const{dimensions:S,spacing:b,direction:_}=i.getImageDataMetadata(m),y=m.voxelManager.getConstructor(),D=m.voxelManager.getScalarData(),T=new y(D),P=_n.newInstance({dataType:_n.getDataType(T),name:"Pixels",numberOfComponents:1,values:T}),x=Ph.newInstance();x.setDimensions(S[0],S[1],1),x.setSpacing(b),x.setDirection(_),x.setOrigin(f),x.getPointData().setScalars(P),x.modified(),i.addImages([{dataId:C,imageId:g,reference:{kind:"segmentation",segmentationId:t,representationUID:C,labelmapId:m.imageId},representationUID:C,callback:({imageActor:M})=>{M.getMapper().setInputData(x),OA(M,r)}}])}c=!0,l=!0;return}const v=p.actorMapper,w=(v?.mapper?v.mapper:p.actor.getMapper()).getInputData();w.modified(),w.setDerivedImage?w.setDerivedImage(m):wC(w,m),l=!0}),c&&_i(i.id),l&&i.render()}function LA(i){const t=i?.getProperty?.();if(t)return{cfun:t.getRGBTransferFunction?.(0),ofun:t.getScalarOpacity?.(0)}}function OA(i,t){const n=i?.getProperty?.();if(n){if(t?.cfun&&n.setRGBTransferFunction&&n.setRGBTransferFunction(0,t.cfun),t?.ofun&&n.setScalarOpacity)n.setScalarOpacity(0,t.ofun);else if(n.setScalarOpacity){const e=bh.newInstance();e.addPoint(0,0),e.addPoint(1,1),e.setClamping(!1),n.setScalarOpacity(0,e)}n.setUseLookupTableScalarRange?.(!0),n.setInterpolationTypeToNearest?.(),i?.setForceTranslucent?.(!0),i?.setForceOpaque?.(!1)}}function RA({viewportIds:i,segmentationId:t}){i.forEach(n=>{let e=Rn(n,{segmentationId:t});e=e.filter(o=>o.type===St.Labelmap),e.forEach(o=>{if(o.segmentationId!==t)return;const s=le(n);if(!s)return;const{viewport:a}=s;zn(a)==="image"&&typeof a.getCurrentImageId=="function"&&wd(a,t)})})}const NA=i=>le(i)?.viewport??void 0,kA=function(i){const{segmentationId:t,modifiedSlicesToUse:n}=i.detail,{representationData:e}=Dt(t),o=_s(t),s=[],a=[],r=[];o.forEach(u=>{const h=NA(u);if(!h)return;const f=Rn(u,{segmentationId:t,type:St.Labelmap})[0],g=$h(Dt(t),f?.config),m=zn(h,{useSliceRendering:g});if(m==="volume"){s.push(u);return}m==="image"&&(g&&vi(h)?r.push(u):a.push(u))});const c=s.length>0,l=a.length>0;c&&PA({modifiedSlicesToUse:c&&l?[]:n,representationData:e,type:St.Labelmap}),l&&RA({viewportIds:a,segmentationId:t}),r.forEach(u=>{_i(u)})},Xw=function(i){const{segmentationId:t}=i.detail,{representationData:n}=Dt(t);n.Labelmap&&kA(i),xA(t)},qw=function(i){const{segmentationId:t}=i.detail;Nf(t)},UA=function(i){if(!i)return;const t=N(i);if(!t)return;const{viewport:n}=t,e=n instanceof pn,o=n.type===so.PLANAR_NEXT,s=typeof n.getCurrentImageId=="function";(e||o)&&i.addEventListener(yt.CAMERA_MODIFIED,hs),!(e||!s||zn(n)!=="image")&&(i.addEventListener(yt.PRE_STACK_NEW_IMAGE,hs),i.addEventListener(yt.IMAGE_RENDERED,hs))},VA=function(i){const t=N(i)?.viewport?.id;i.removeEventListener(yt.PRE_STACK_NEW_IMAGE,hs),i.removeEventListener(yt.IMAGE_RENDERED,hs),i.removeEventListener(yt.CAMERA_MODIFIED,hs),t&&or.delete(t)},or=new Map;function hs(i){const t=i.detail,{viewportId:n,renderingEngineId:e}=t,o=ae(n,e);if(!o)return;const{viewport:s}=o,a=Rn(n);if(!a?.length){or.delete(n);return}const r=a.filter(d=>d.type===St.Labelmap),c=r.some(d=>{const u=Dt(d.segmentationId);return vi(s)&&$h(u,d.config)});if(i.type===yt.CAMERA_MODIFIED){if(c){const u=HI(s);if(or.get(n)===u.key)return;or.set(n,u.key),_i(n);return}if(!(s.type===so.PLANAR_NEXT)){or.delete(n);return}}if(zn(s)!=="image"||vi(s)||typeof s.getCurrentImageId!="function")return;const l=s;r.forEach(d=>{const{segmentationId:u}=d;wd(l,u),i.type===yt.IMAGE_RENDERED&&l.element.removeEventListener(yt.IMAGE_RENDERED,hs)})}const Yw={enable:UA,disable:VA},Zm="PlanarFreehandContourSegmentationTool",{DefaultHistoryMemo:FA}=Nl;function GA(i,t){Kw(i,t,Ge.Union)}function HA(i,t){Kw(i,t,Ge.Difference)}function Kw(i,t,n){if(!Zr(Zm)){console.warn(`${Zm} is not registered. Cannot apply stroke.`),Mc(t);return}const e=On(t.data.contour.polyline,i);if(e.length<3){Mc(t);return}const o=$A(i,t),s=o.map(g=>{const m=On(g.data.contour.polyline,i),p=pl(i,g).map(v=>v.polyline);return{outer:m,holes:p.length?p:void 0}}),a=S0(e);if(a.length===0){Mc(t);return}const r=rd(s,a,n),c=n===Ge.Union?_0(r):r,l=[];for(const g of o){l.push(g);for(const m of pl(i,g))l.push(m.annotation)}const d=[t,...l];for(const g of d)Mc(g);const u=o[0]??t,{element:h}=i,f=[];for(const g of c){if(g.outer.length<3)continue;const m=xr(i,u,g.outer,Qe.Clockwise);Nt(m,h),Ho(m),f.push(m),g.holes?.forEach(p=>{if(p.length<3)return;const v=xr(i,u,p,Qe.CounterClockwise);Nt(v,h),Cs(m,v),f.push(v),zt(v,h)}),zt(m,h)}WA(t,l,f,i),sc(i,d)}function WA(i,t,n,e){const o={id:i.annotationUID,operationType:"annotation",restoreMemo:(s=!0)=>{const a=s?n:t,r=s?t:n;BA(a),zA(r,e.element),sc(e,[...a,...r])}};FA.replaceCurrentMemo(o,s=>s.id===i.annotationUID&&s.operationType==="annotation")}function BA(i){for(let t=i.length-1;t>=0;t--){const n=i[t];ne(n.annotationUID)&&Gt(n.annotationUID),_o(n)}}function zA(i,t){for(const n of i)ne(n.annotationUID)||(Nt(n,t),Ho(n))}function $A(i,t){const n=t.annotationUID;return Ca().filter(e=>!(!e.annotationUID||e.annotationUID===n||!Da(e)||!j0(e,t)||!i.isReferenceViewable(e.metadata)||e.parentAnnotationUID))}function Mc(i){Gt(i.annotationUID),_o(i)}const jA="PlanarFreehandContourSegmentationTool";async function XA(i){const t=i.detail.annotation;if(!Da(t))return;const n=YA(t),{contourHoleProcessingEnabled:e=!1}=i.detail;e?HA(n,t):GA(n,t),Rt(Z,E.ANNOTATION_CUT_MERGE_PROCESS_COMPLETED,{element:n.element,sourceAnnotation:t})}function qA(i,t=!1){const n=jA,e=Ae(i.id,i.renderingEngineId);let o;return e?e.hasTool(n)?e.getToolOptions(n)||(o=`Tool ${n} must be in active/passive state in ${e.id} toolGroup`):o=`Tool ${n} not added to ${e.id} toolGroup`:o=`ToolGroup not found for viewport ${i.id}`,o&&!t&&console.warn(o),!o}function YA(i){const t=Cf(i);return t.find(e=>qA(e,!0))??t[0]}function KA(i){const t=i.detail.annotation;_o(t)}function Zw(i){const t=i.detail.annotation;Da(t)&&XA(i)}function El(i){if(!i.detail.removed.length)return;Vi().forEach(e=>{const s=e.getViewports().map(a=>a.id);V(s)})}function Jw(i){const{viewportId:t}=i.detail;V([t])}function Qw(i){const t=i.detail.annotation;Da(t)&&KA(i)}const t1=function(i){xa(i.detail.element)},ZA=function(i){i.addEventListener(yt.IMAGE_RENDERED,t1)},JA=function(i){i.removeEventListener(yt.IMAGE_RENDERED,t1)},e1={enable:ZA,disable:JA},{Active:QA}=se;function lc(i,t,n){if($.isInteractingWithTool)return!1;const{renderingEngineId:e,viewportId:o}=n.detail,s=Ae(o,e);if(!s)return!1;let a;const r=Object.keys(s.toolOptions);for(let c=0;c<r.length;c++){const l=r[c],d=s.toolOptions[l],u=s.getToolInstance(l);if(d.mode===QA&&typeof u[t]=="function"){a=s.getToolInstance(l);break}}a&&a[t](n)}const n1=lc.bind(null,"Mouse","mouseClickCallback"),o1=lc.bind(null,"Mouse","doubleClickCallback");function i1(i,t,n,e="mouse"){const o=e==="touch"?$l:jl,s=[];return t.forEach(({tool:a,annotations:r})=>{for(const c of r){if(c.isLocked||!c.isVisible)continue;const l=a.getHandleNearImagePoint(i,c,n,o);if(l){s.push({tool:a,annotation:c,handle:l});break}}}),s}function dc(i,t){const n=[];for(let e=0;e<t.length;e++){const o=t[e];if(!o){console.warn("undefined tool in filterToolsWithAnnotationsForElement");continue}let s=Yt(o.constructor.toolName,i);s?.length&&(typeof o.filterInteractableAnnotationsForElement=="function"&&(s=o.filterInteractableAnnotationsForElement(i,s)),s?.length>0&&n.push({tool:o,annotations:s}))}return n}function kf(i,t,n,e="mouse"){const o=e==="touch"?$l:jl,s=[];return t.forEach(({tool:a,annotations:r})=>{for(const c of r){if(c.isLocked||!c.isVisible)continue;if(a.isPointNearTool(i,c,n,o,e)){s.push({tool:a,annotation:c});break}}}),s}const{Active:tL}=se;function Ed(i){const{renderingEngineId:t,viewportId:n,event:e}=i.detail,o=Pa(e)||ba.getModifierKey(),s=Ae(n,t);if(!s)return null;const a=Object.keys(s.toolOptions),r=s.getDefaultMousePrimary(),c=i.detail.buttons??e?.buttons??r;for(let l=0;l<a.length;l++){const d=a[l],u=s.toolOptions[d],h=u.bindings.length&&u.bindings.some(f=>f.mouseButton===c&&f.modifierKey===o);if(u.mode===tL&&h)return s.getToolInstance(d)}}function va(i,t,n){const{renderingEngineId:e,viewportId:o}=i.detail,s=Ae(o,e);if(!s)return[];const a=[],r=Object.keys(s.toolOptions);for(let c=0;c<r.length;c++){const l=r[c],d=s.toolOptions[l];if(t.includes(d.mode)){const u=s.getToolInstance(l);a.push(u)}}return a}function eL(i,t){const n=new Map,{renderingEngineId:e,viewportId:o}=i.detail,s=Ae(o,e);if(!s)return n;const a=Object.keys(s.toolOptions),r=s.getDefaultMousePrimary(),c=i.detail.event,l=c?.buttons??r,d=Pa(c)||ba.getModifierKey();for(let u=0;u<a.length;u++){const h=a[u],f=s.getToolInstance(h),g=f.configuration?.actions??{},m=Object.values(g);if(!m?.length||!t.includes(f.mode))continue;const p=m.find(v=>v.bindings?.length&&v.bindings.some(I=>I.mouseButton===l&&I.modifierKey===d));p&&n.set(f,p)}return n}const{Active:nL,Passive:oL}=se;function iL(i){if($.isInteractingWithTool)return!1;const t=i.detail,{element:n}=t,e=N(n),{canvas:o}=t.currentPoints;if(!e)return!1;const s=eL(i,[nL,oL]),a=Array.from(s.keys()),r=dc(n,a),c=kf(n,r,o);if(c.length>0){const{tool:l,annotation:d}=c[0],u=s.get(l);return(typeof u.method=="string"?l[u.method]:u.method).call(l,i,d),!0}return!1}const{Active:sL,Passive:aL}=se;function s1(i){if($.isInteractingWithTool)return;const t=Ed(i);if(t&&typeof t.preMouseDownCallback=="function"&&t.preMouseDownCallback(i))return;const n=va(i,[sL]),e=va(i,[aL]),o=[...n||[],...e||[]];if(iL(i))return;const a=i.detail,{element:r}=a,c=dc(r,o),l=a.currentPoints.canvas,d=i1(r,c,l,"mouse"),u=!!i.detail.event.shiftKey;if(d.length>0){const{tool:f,annotation:g,handle:m}=Jm(d);Qm(g.annotationUID,u),f.handleSelectedCallback(i,g,m,"Mouse");return}const h=kf(r,c,l,"mouse");if(h.length>0){const{tool:f,annotation:g}=Jm(h);Qm(g.annotationUID,u),f.toolSelectedCallback(i,g,"Mouse",l);return}t&&typeof t.postMouseDownCallback=="function"&&t.postMouseDownCallback(i)}function Jm(i){if(i.length>1){const t=i.find(n=>{const e=!ze(n.annotation.annotationUID),o=$e(n.annotation.annotationUID);return e&&o});if(t)return t}return i[0]}function Qm(i,t=!1){t?ic(i)?So(i,!1):So(i,!0,!0):So(i,!0,!1)}function a1(i){if($.isInteractingWithTool)return;const t=Ed(i);if(t&&!$.isMultiPartToolActive&&t.addNewAnnotation)try{const n=t.addNewAnnotation(i,"mouse");So(n.annotationUID)}catch(n){console.warn("Error adding new annotation, viewport not ready:",n)}}function r1(i){if($.isInteractingWithTool)return;const t=Ed(i);!t||typeof t.mouseDragCallback!="function"||t.mouseDragCallback(i)}const{Active:rL,Passive:cL}=se;function c1(i){if($.isInteractingWithTool||$.isMultiPartToolActive)return;const t=va(i,[rL,cL]),n=i.detail,{element:e}=n,o=dc(e,t),s=t.filter(r=>!o.some(l=>l.tool.getToolName()===r.getToolName()));let a=!1;for(const{tool:r,annotations:c}of o)typeof r.mouseMoveCallback=="function"&&(a=r.mouseMoveCallback(i,c)||a);s.forEach(r=>{typeof r.mouseMoveCallback=="function"&&r.mouseMoveCallback(i)}),a===!0&&xa(e)}const l1=lc.bind(null,"Mouse","mouseUpCallback");function d1(i){if($.isInteractingWithTool)return;i.detail.buttons=Fo.Wheel|(i.detail.event.buttons||0);const t=Ed(i);if(t)return t.mouseWheelCallback(i)}const lL=function(i){i.addEventListener(E.MOUSE_CLICK,n1),i.addEventListener(E.MOUSE_DOWN,s1),i.addEventListener(E.MOUSE_DOWN_ACTIVATE,a1),i.addEventListener(E.MOUSE_DOUBLE_CLICK,o1),i.addEventListener(E.MOUSE_DRAG,r1),i.addEventListener(E.MOUSE_MOVE,c1),i.addEventListener(E.MOUSE_UP,l1),i.addEventListener(E.MOUSE_WHEEL,d1)},dL=function(i){i.removeEventListener(E.MOUSE_CLICK,n1),i.removeEventListener(E.MOUSE_DOWN,s1),i.removeEventListener(E.MOUSE_DOWN_ACTIVATE,a1),i.removeEventListener(E.MOUSE_DOUBLE_CLICK,o1),i.removeEventListener(E.MOUSE_DRAG,r1),i.removeEventListener(E.MOUSE_MOVE,c1),i.removeEventListener(E.MOUSE_UP,l1),i.removeEventListener(E.MOUSE_WHEEL,d1)},u1={enable:lL,disable:dL},{Active:uL}=se;function h1(i){const{renderingEngineId:t,viewportId:n}=i.detail,e=b_(),o=ba.getModifierKey(),s=Ae(n,t);if(!s)return null;const a=Object.keys(s.toolOptions),r=s.getDefaultMousePrimary();for(let c=0;c<a.length;c++){const l=a[c],d=s.toolOptions[l];if(d.mode!==uL)continue;if(d.bindings.length&&d.bindings.some(h=>h.mouseButton===(e??r)&&h.modifierKey===o))return s.getToolInstance(l)}}function hL(i,t){const n=new Map,{renderingEngineId:e,viewportId:o}=i.detail,s=Ae(o,e);if(!s)return n;const a=Object.keys(s.toolOptions),r=i.detail.key;for(let c=0;c<a.length;c++){const l=a[c],d=s.getToolInstance(l),u=d.configuration?.actions;if(!u)continue;const h=Object.values(u);if(!h?.length||!t.includes(d.mode))continue;const f=h.find(g=>g.bindings?.some(m=>m.key===r));f&&n.set(d,f)}return n}function f1(i){const t=h1(i);if(t){const{renderingEngineId:e,viewportId:o}=i.detail,s=Ae(o,e),a=t.getToolName();Object.keys(s.toolOptions).includes(a)&&s.setViewportsCursorByToolName(a)}const n=hL(i,[se.Active]);if(n?.size){const{element:e}=i.detail;for(const[o,s]of[...n.entries()])(typeof s.method=="function"?s.method:o[s.method]).call(o,e,s,i)}}function g1(i){const t=h1(i);if(!t)return;const{renderingEngineId:n,viewportId:e}=i.detail,o=Ae(e,n);_I();const s=t.getToolName();Object.keys(o.toolOptions).includes(s)&&o.setViewportsCursorByToolName(s)}const fL=function(i){i.addEventListener(E.KEY_DOWN,f1),i.addEventListener(E.KEY_UP,g1)},gL=function(i){i.removeEventListener(E.KEY_DOWN,f1),i.removeEventListener(E.KEY_UP,g1)},m1={enable:fL,disable:gL},{Active:mL,Passive:pL,Enabled:vL}=se,p1=function(i){va(i,[mL,pL,vL]).forEach(n=>{n.onCameraModified&&n.onCameraModified(i)})},IL=function(i){i.addEventListener(yt.CAMERA_MODIFIED,p1)},wL=function(i){i.removeEventListener(yt.CAMERA_MODIFIED,p1)},v1={enable:IL,disable:wL},{Active:EL,Passive:SL,Enabled:CL}=se,I1=function(i){va(i,[EL,SL,CL]).forEach(n=>{n.onImageSpacingCalibrated&&n.onImageSpacingCalibrated(i)})},bL=function(i){i.addEventListener(yt.IMAGE_SPACING_CALIBRATED,I1)},_L=function(i){i.removeEventListener(yt.IMAGE_SPACING_CALIBRATED,I1)},w1={enable:bL,disable:_L},{Active:yL}=se;function Uf(i){const{renderingEngineId:t,viewportId:n}=i.detail,e=i.detail.event,o=Ae(n,t);if(!o)return null;const s=Object.keys(o.toolOptions),a=Object.keys(e.touches).length,r=Pa(e)||ba.getModifierKey(),c=o.getDefaultMousePrimary();for(let l=0;l<s.length;l++){const d=s[l],u=o.toolOptions[d],h=u.bindings.length&&u.bindings.some(f=>(f.numTouchPoints===a||a===1&&f.mouseButton===c)&&f.modifierKey===r);if(u.mode===yL&&h)return o.getToolInstance(d)}}function xL(i){i.mouseButton??=Fo.Primary,i.startPoints??=i.currentPoints,i.lastPoints??=i.currentPoints,i.deltaPoints??={page:[0,0],client:[0,0],canvas:[0,0],world:[0,0,0]}}function Sl(i,t,n){if(typeof i?.[t]=="function")return e=>i[t](e);if(i?.supportedInteractionTypes?.includes("Touch")&&typeof i[n]=="function")return e=>(xL(e.detail),i[n](e))}function tp(i,t,n){const{renderingEngineId:e,viewportId:o}=i.detail,s=Ae(o,e);if(!s)return[];const a=[],r=Object.keys(s.toolOptions);for(let c=0;c<r.length;c++){const l=r[c],d=s.toolOptions[l];if(t.includes(d.mode)){const u=s.getToolInstance(l);a.push(u)}}return a}const{Active:PL,Passive:DL}=se;function E1(i){if($.isInteractingWithTool)return;const t=Uf(i),n=Sl(t,"preTouchStartCallback","preMouseDownCallback");if(n&&n(i))return;const e=tp(i,[PL]),o=tp(i,[DL]),s=[...e||[],...o||[]],a=i.detail,{element:r}=a,c=dc(r,s),l=a.currentPoints.canvas,d=i1(r,c,l,"touch"),u=!1;if(d.length>0){const{tool:g,annotation:m,handle:p}=ep(d);np(m.annotationUID,u),g.handleSelectedCallback(i,m,p,"Touch");return}const h=kf(r,c,l,"touch");if(h.length>0){const{tool:g,annotation:m}=ep(h);np(m.annotationUID,u),g.toolSelectedCallback(i,m,"Touch",l);return}const f=Sl(t,"postTouchStartCallback","postMouseDownCallback");f&&f(i)}function ep(i){return i.length>1&&i.find(t=>!ze(t.annotation.annotationUID)&&$e(t.annotation.annotationUID))||i[0]}function np(i,t=!1){t?ic(i)?So(i,!1):So(i,!0,!0):So(i,!0,!1)}function S1(i){if($.isInteractingWithTool)return;const t=Uf(i);if(t&&!$.isMultiPartToolActive&&t.addNewAnnotation)try{const n=t.addNewAnnotation(i,"touch");So(n.annotationUID)}catch(n){console.warn("Error adding new annotation, viewport not ready:",n)}}function TL(i){if(!$.isInteractingWithTool||!(i.detail.currentPointsList?.length>1))return!1;const{renderingEngineId:t,viewportId:n,element:e}=i.detail,o=Ae(n,t);if(!o)return!1;let s=!1;for(const a of Object.keys(o.toolOptions)){const r=o.getToolInstance(a);if(r){if(r.handlesMultiTouchGestures){r.isDrawing&&(s=!0);continue}r.cancel?.(e)}}return s}function C1(i){const t=TL(i);if($.isInteractingWithTool&&!t)return;const n=Uf(i),e=Sl(n,"touchDragCallback","mouseDragCallback");e&&e(i)}const b1=lc.bind(null,"Touch","touchEndCallback"),{Active:ML}=se;function _1(i){if($.isInteractingWithTool)return;const{renderingEngineId:t,viewportId:n}=i.detail,e=Ae(n,t);if(!e)return;const o=Object.keys(e.toolOptions);for(let s=0;s<o.length;s++){const a=o[s];if(e.toolOptions[a].mode!==ML)continue;const c=e.getToolInstance(a),l=Sl(c,"touchTapCallback","mouseClickCallback");if(l){l(i);return}}}const y1=lc.bind(null,"Touch","touchPressCallback"),AL=function(i){i.addEventListener(E.TOUCH_START,E1),i.addEventListener(E.TOUCH_START_ACTIVATE,S1),i.addEventListener(E.TOUCH_DRAG,C1),i.addEventListener(E.TOUCH_END,b1),i.addEventListener(E.TOUCH_TAP,_1),i.addEventListener(E.TOUCH_PRESS,y1)},LL=function(i){i.removeEventListener(E.TOUCH_START,E1),i.removeEventListener(E.TOUCH_START_ACTIVATE,S1),i.removeEventListener(E.TOUCH_DRAG,C1),i.removeEventListener(E.TOUCH_END,b1),i.removeEventListener(E.TOUCH_TAP,_1),i.removeEventListener(E.TOUCH_PRESS,y1)},x1={enable:AL,disable:LL},OL=function(){Z.addEventListener(E.ANNOTATION_COMPLETED,Wn.handleAnnotationCompleted),Z.addEventListener(E.ANNOTATION_MODIFIED,Wn.handleAnnotationUpdate),Z.addEventListener(E.ANNOTATION_REMOVED,Wn.handleAnnotationDelete)},RL=function(){Z.removeEventListener(E.ANNOTATION_COMPLETED,Wn.handleAnnotationCompleted),Z.removeEventListener(E.ANNOTATION_MODIFIED,Wn.handleAnnotationUpdate),Z.removeEventListener(E.ANNOTATION_REMOVED,Wn.handleAnnotationDelete)},P1={enable:OL,disable:RL},{Active:NL,Passive:kL,Enabled:UL}=se,D1=function(i){va(i,[NL,kL,UL]).forEach(n=>{n.onResetCamera&&n.onResetCamera(i)})},VL=function(i){i.addEventListener(yt.CAMERA_RESET,D1)},FL=function(i){i.removeEventListener(yt.CAMERA_RESET,D1)},T1={enable:VL,disable:FL};function Vf(i){const{element:t,viewportId:n}=i.detail,e=GL(n);HL(t),WL(e,t),cf.addViewportElement(n,t),oI.enable(t),CI.enable(t),wI.enable(t),ba.enable(t),Yw.enable(t),e1.enable(t),v1.enable(t),w1.enable(t),T1.enable(t),u1.enable(t),m1.enable(t),x1.enable(t),$.enabledElements.push(t)}function GL(i){const t="http://www.w3.org/2000/svg",n=document.createElementNS(t,"svg"),e=`svg-layer-${i}`;n.classList.add("svg-layer"),n.setAttribute("id",e),n.setAttribute("xmlns","http://www.w3.org/2000/svg"),n.style.width="100%",n.style.height="100%",n.style.pointerEvents="none",n.style.position="absolute";const o=document.createElementNS(t,"defs"),s=document.createElementNS(t,"filter"),a=document.createElementNS(t,"feOffset"),r=document.createElementNS(t,"feColorMatrix"),c=document.createElementNS(t,"feBlend");return s.setAttribute("id",`shadow-${e}`),s.setAttribute("filterUnits","userSpaceOnUse"),a.setAttribute("result","offOut"),a.setAttribute("in","SourceGraphic"),a.setAttribute("dx","0.5"),a.setAttribute("dy","0.5"),r.setAttribute("result","matrixOut"),r.setAttribute("in","offOut"),r.setAttribute("in2","matrix"),r.setAttribute("values","0.2 0 0 0 0 0 0.2 0 0 0 0 0 0.2 0 0 0 0 0 1 0"),c.setAttribute("in","SourceGraphic"),c.setAttribute("in2","matrixOut"),c.setAttribute("mode","normal"),s.appendChild(a),s.appendChild(r),s.appendChild(c),o.appendChild(s),n.appendChild(o),n}function HL(i){const{viewportUid:t,renderingEngineUid:n}=i.dataset,e=`${t}:${n}`;$.svgNodeCache[e]={}}function WL(i,t){t.querySelector("div.viewport-element").appendChild(i)}function M1(i,t){const n=[];if(!t&&!i)throw new Error("At least one of renderingEngineId or viewportId should be given");for(let e=0;e<$.synchronizers.length;e++){const o=$.synchronizers[e],s=!o.isDisabled(),a=o.hasSourceViewport(t,i),r=o.hasTargetViewport(t,i);s&&(a||r)&&n.push(o)}return n}const BL="viewport-element";function Ff(i){const{element:t,viewportId:n}=i.detail;jL(t),XL(t),cf.removeViewportElement(n,t),oI.disable(t),CI.disable(t),wI.disable(t),ba.disable(t),Yw.disable(t),e1.disable(t),v1.disable(t),w1.disable(t),T1.disable(t),u1.disable(t),m1.disable(t),x1.disable(t),zL(t),$L(t),qL(t)}const zL=i=>{const t=N(i);if(!t)return;M1(t.viewportId,t.renderingEngineId).forEach(e=>{e.remove(t)})},$L=i=>{const t=N(i);if(!t)return;const{renderingEngineId:n,viewportId:e}=t,o=Ae(e,n);o&&o.removeViewports(n,e)};function jL(i){const{viewportUid:t,renderingEngineUid:n}=i.dataset,e=`${t}:${n}`;delete $.svgNodeCache[e]}function XL(i){const t=i.querySelector(`div.${BL}`),n=t.querySelector("svg");n&&t.removeChild(n)}const qL=function(i){const t=$.enabledElements.findIndex(n=>n===i);t>-1&&$.enabledElements.splice(t,1)};function YL(i){const t=p0(i,[se.Active,se.Passive]),n=dc(i,t);for(const{tool:e}of n){const o=e.cancel(i);if(o)return o}}class A1{constructor(t,n,e,o){this._viewportOptions={},this._onEvent=s=>{if(this._ignoreFiredEvents===!0||!this._targetViewports.length)return;const a=this._eventSource==="element"?N(s.currentTarget):le(s.detail?.viewportId);if(!a)return;const{renderingEngineId:r,viewportId:c}=a;this._sourceViewports.find(l=>l.viewportId===c)&&this.fireEvent({renderingEngineId:r,viewportId:c},s)},this._enabled=!0,this._eventName=n,this._eventHandler=e,this._eventListener=this._onEvent.bind(this),this._ignoreFiredEvents=!1,this._sourceViewports=[],this._targetViewports=[],this._options=o||{},this._eventSource=this._options.eventSource||"element",this._auxiliaryEvents=this._options.auxiliaryEvents||[],this.id=t}isDisabled(){return!this._enabled||!this._hasSourceElements()}setOptions(t,n={}){this._viewportOptions[t]=n}setEnabled(t){this._enabled=t}getOptions(t){return this._viewportOptions[t]}add(t){this.addTarget(t),this.addSource(t)}addSource(t){if(Ac(this._sourceViewports,t))return;const{renderingEngineId:n,viewportId:e}=t,o=Ne(n).getViewport(e);if(!o){console.warn(`Synchronizer.addSource: No viewport for ${n} ${e}`);return}(this._eventSource==="element"?o.element:Z).addEventListener(this._eventName,this._eventListener),this._auxiliaryEvents.forEach(({name:a,source:r="element"})=>{(r==="element"?o.element:Z).addEventListener(a,this._eventListener)}),this._updateDisableHandlers(),this._sourceViewports.push(t)}addTarget(t){Ac(this._targetViewports,t)||(this._targetViewports.push(t),this._updateDisableHandlers())}getSourceViewports(){return this._sourceViewports}getTargetViewports(){return this._targetViewports}destroy(){this._sourceViewports.forEach(t=>this.removeSource(t)),this._targetViewports.forEach(t=>this.removeTarget(t))}remove(t){this.removeTarget(t),this.removeSource(t)}removeSource(t){const n=op(this._sourceViewports,t);if(n===-1)return;const e=this._eventSource==="element"?this.getViewportElement(t):Z;this._sourceViewports.splice(n,1),e.removeEventListener(this._eventName,this._eventListener),this._auxiliaryEvents.forEach(({name:o,source:s="element"})=>{(s==="element"?this.getViewportElement(t):Z).removeEventListener(o,this._eventListener)}),this._updateDisableHandlers()}removeTarget(t){const n=op(this._targetViewports,t);n!==-1&&(this._targetViewports.splice(n,1),this._updateDisableHandlers())}hasSourceViewport(t,n){return Ac(this._sourceViewports,{renderingEngineId:t,viewportId:n})}hasTargetViewport(t,n){return Ac(this._targetViewports,{renderingEngineId:t,viewportId:n})}fireEvent(t,n){if(this.isDisabled()||this._ignoreFiredEvents)return;this._ignoreFiredEvents=!0;const e=[];try{for(let o=0;o<this._targetViewports.length;o++){const s=this._targetViewports[o];if(t.viewportId===s.viewportId)continue;const r=this._eventHandler(this,t,s,n,this._options);r instanceof Promise&&e.push(r)}}catch(o){console.warn(`Synchronizer, for: ${this._eventName}`,o)}finally{e.length?Promise.allSettled(e).then(()=>{this._ignoreFiredEvents=!1}):this._ignoreFiredEvents=!1}}_hasSourceElements(){return this._sourceViewports.length!==0}_updateDisableHandlers(){const t=KL(this._sourceViewports,this._targetViewports),n=this.remove.bind(this),e=o=>{n(o.detail.element)};t.forEach(o=>{const s=this.getEventSource(o);s&&(s.removeEventListener(yt.ELEMENT_DISABLED,e),s.addEventListener(yt.ELEMENT_DISABLED,e))})}getEventSource(t){return this._eventSource==="element"?this.getViewportElement(t):Z}getViewportElement(t){const{renderingEngineId:n,viewportId:e}=t,o=Ne(n);if(!o)return null;const s=o.getViewport(e);return s?s.element:null}}function KL(i,t){const n=[],e=i.concat(t);for(let o=0;o<e.length;o++){const s=e[o];n.some(a=>s.renderingEngineId===a.renderingEngineId&&s.viewportId===a.viewportId)||n.push(s)}return n}function op(i,t){return i.findIndex(n=>t.renderingEngineId===n.renderingEngineId&&t.viewportId===n.viewportId)}function Ac(i,t){return i.some(n=>n.renderingEngineId===t.renderingEngineId&&n.viewportId===t.viewportId)}function Ps(i,t,n,e){if($.synchronizers.some(a=>a.id===i))throw new Error(`Synchronizer with id '${i}' already exists.`);const s=new A1(i,t,n,e);return $.synchronizers.push(s),s}function ZL(){for(;$.synchronizers.length>0;)$.synchronizers.pop().destroy()}function JL(i){return $.synchronizers.find(t=>t.id===i)}function QL(){return $.synchronizers}function tO(i){const t=$.synchronizers.findIndex(n=>n.id===i);t>-1&&($.synchronizers[t].destroy(),$.synchronizers.splice(t,1))}const eO=Object.freeze(Object.defineProperty({__proto__:null,createSynchronizer:Ps,destroy:ZL,destroySynchronizer:tO,getAllSynchronizers:QL,getSynchronizer:JL,getSynchronizersForViewport:M1},Symbol.toStringTag,{value:"Module"})),RH=Object.freeze(Object.defineProperty({__proto__:null,Synchronizer:A1,SynchronizerManager:eO,ToolGroupManager:t_,addEnabledElement:Vf,addTool:Xv,cancelActiveManipulations:YL,hasTool:a_,removeEnabledElement:Ff,removeTool:r_,get state(){return $},svgNodeCache:Vl},Symbol.toStringTag,{value:"Module"})),Cl=function(i){const{viewportId:t}=i.detail;_i(t)},L1=function(i){const{segmentationId:t}=i.detail;Ca().filter(e=>t===e?.data?.segmentation?.segmentationId).forEach(e=>{Gt(e.annotationUID)})},O1=function(i){const t=i.detail?.viewportId;!t||!Rn(t)?.length||_i(t)};function nO(i,t,n,e){const o=i.getViewReference(),{viewPlaneNormal:s,FrameOfReferenceUID:a}=o,r={annotationUID:e?.annotationUID||Se(),data:{handles:{points:n}},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{toolName:t,viewPlaneNormal:s,FrameOfReferenceUID:a,referencedImageId:oO(i,n[0],s),...e}};return Nt(r,i.element),r}function oO(i,t,n){let e;if(i instanceof Pn)e=Gf(i,t,n);else if(i instanceof pn){const o=iO(i),s=Fi(o),a=Q.getVolume(s);e=qr(a,t,n)}else throw new Error("getReferencedImageId: viewport must be a StackViewport or BaseVolumeViewport");return e}function iO(i){const t=i.getViewReferenceId?.();if(t)return t;if(i instanceof pn)return`volumeId:${sO(i)}`;throw new Error("getTargetId: viewport must have a getTargetId method")}function sO(i){const t=i.getActors();if(t)return t.find(n=>n.actor.getClassName()==="vtkVolume")?.uid}function Gf(i,t,n){const e=i.getImageIds();if(!e||!e.length)return;const o=e.map(s=>{const{imagePositionPatient:a}=rn("imagePlaneModule",s),r=aO(t,a,n);return{imageId:s,distance:r}});return o.sort((s,a)=>s.distance-a.distance),o[0].imageId}function aO(i,t,n){const e=B();tn(e,i,t);const o=xt(e,n);return Math.abs(o)}function rO(i){if(!i)throw new Error(`No contours found for geometryId ${i.id}`);const t=i.id;if(i.type!==EC.CONTOUR)throw new Error(`Geometry type ${i.type} not supported for rendering.`);if(!i.data){console.warn(`No contours found for geometryId ${t}. Skipping render.`);return}}function cO(i,t,n,e){n.size?i.render():lO(i,t,e)}function lO(i,t,n){const{segmentationId:e}=n,o=new Map;t.forEach(s=>{const a=Q.getGeometry(s);if(!a){console.warn(`No geometry found for geometryId ${s}. Skipping render.`);return}const r=a.data.segmentIndex;rO(a);const c=Yn.getStyle({viewportId:i.id,segmentationId:e,type:St.Contour,segmentIndex:r}),l=a.data,d=ht(i).viewPlaneNormal;l.contours.forEach(u=>{const{points:h,color:f,id:g}=u,m=Gf(i,h[0],d),p={annotationUID:Se(),data:{contour:{closed:!0,polyline:h},segmentation:{segmentationId:e,segmentIndex:r,color:f,id:g},handles:{}},handles:{},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!0,isVisible:!0,metadata:{referencedImageId:m,toolName:"PlanarFreehandContourSegmentationTool",FrameOfReferenceUID:i.getFrameOfReferenceUID(),viewPlaneNormal:d}},v=i.element;Nt(p,v),Ho(p)}),c&&o.set(r,c)}),i.render()}function Hf({segmentationId:i,type:t,data:n}){const e=Dt(i);if(!e)throw new Error(`Segmentation ${i} not found`);switch(e.representationData[t]&&console.warn(`Representation data of type ${t} already exists for segmentation ${i}, overwriting it.`),t){case St.Labelmap:n&&(e.representationData[t]=n);break;case St.Contour:n&&(e.representationData[t]=n);break;case St.Surface:n&&(e.representationData[t]=n);break;default:throw new Error(`Invalid representation type ${t}`)}}async function Wf(i,t,n,e){const o=await n();return Hf({segmentationId:i,type:t,data:o}),e?.(),o}function R1(i){const t=Ty(i);if(t)return t;const n=Dt(i);if(!n)throw new Error(`No segmentation found for segmentationId ${i}`);let e;if(n.representationData.Labelmap)e=dO(n);else if(n.representationData.Contour)e=uO(n);else if(n.representationData.Surface)e=hO(n);else throw new Error(`Unsupported segmentation type: ${n.representationData}`);return My(i,e),e}function dO(i){return Object.keys(i.segments).map(Number).sort((t,n)=>t-n)}function uO(i){const{annotationUIDsMap:t,geometryIds:n}=i.representationData.Contour||{};if(!n)throw new Error(`No geometryIds found for segmentationId ${i.segmentationId}`);const e=new Set([...t.keys()]);return n.forEach(o=>{const s=Q.getGeometry(o);e.add(s.data.segmentIndex)}),Array.from(e).sort((o,s)=>o-s)}function hO(i){const t=i.representationData.Surface?.geometryIds??[];return Array.from(t.keys()).map(Number).sort((n,e)=>n-e)}const Us=new Map,ip=new Map;function fO(i,t,n=!1){const e=le(i);if(!e)return;const{viewport:o}=e;n&&o.render()}async function gO(i,t){const{segmentationId:n}=t,e=Dt(n);if(!e)return;let o=e.representationData[St.Contour];const s=Yo();if(!o&&Yo()?.canComputeRequestedRepresentation(n,St.Contour)&&!Us.get(i.id)){Us.set(i.id,!0);try{o=await Wf(n,St.Contour,()=>s.computeContourData(n,{viewport:i}))}catch(l){console.warn("Unable to compute contour data for segmentationId",n,l)}Us.set(i.id,!1)}else!o&&!Yo()&&console.debug(`No contour data found for segmentationId ${n} and PolySeg add-on is not configured. Unable to convert from other representations to contour. Please register PolySeg using cornerstoneTools.init({ addons: { polySeg } }) to enable automatic conversion.`);if(!o||!o.geometryIds?.length)return;let a=!1;const r=ht(i).viewPlaneNormal;o.annotationUIDsMap&&(a=!pO(o.annotationUIDsMap,r)),o.geometryIds.length>0&&(a=!mO(o.geometryIds,r));const c=ip.get(i.id)||new Set;if(a&&!Us.get(i.id)&&!c.has(n)&&i.viewportStatus===SC.RENDERED){Us.set(i.id,!0);const l=R1(n),u=(await s.computeSurfaceData(n,{segmentIndices:l,viewport:i})).geometryIds,h=[];for(const p of u.values()){const I=Q.getGeometry(p).data;h.push({points:I.points,polys:I.polys,segmentIndex:I.segmentIndex,id:I.segmentIndex})}const f=await s.clipAndCacheSurfacesForViewport(h,i),g=s.extractContourData(f),m=s.createAndAddContourSegmentationsFromClippedSurfaces(g,i,n);o.annotationUIDsMap=new Map([...o.annotationUIDsMap,...m]),c.add(n),ip.set(i.id,c),Us.set(i.id,!1)}cO(i,o.geometryIds,o.annotationUIDsMap,t)}function mO(i,t){let n=null,e=null;for(const d of i){const u=Q.getGeometry(d);if(!u)continue;const h=u.data;if(h.contours?.[0]?.points?.length>=3){n=u,e=h;break}}if(!n||!e)return!1;const o=e.contours,{points:s}=o[0],[a]=s,r=B(),{length:c}=s,l=Math.ceil(c/25);for(let d=1;d<c;d+=l){const u=s[d];if(tn(r,a,u),Wt(r,r),xt(t,r)>.1)return!1}return!0}function pO(i,t){const n=Array.from(i.values()).flat().map(o=>Array.from(o)).flat(),e=Dv(n,3);for(const o of e){const s=ne(o);if(s?.metadata){if(!s.metadata.viewPlaneNormal)continue;const a=s.metadata.viewPlaneNormal,r=Math.abs(t[0]*a[0]+t[1]*a[1]+t[2]*a[2]);if(Math.abs(r-1)>.01)return!1}}return!0}function vO(i){return null}const IO={getUpdateFunction:vO,render:gO,removeRepresentation:fO},wO=1e-4;function N1(i,t,n){if(n<=0){i.setPosition(0,0,0);return}const[e,o,s]=Wt(B(),t),a=n*wO;i.setPosition(e*a,o*a,s*a)}function su(i,t){let n=-1,e=0;if(t.forEach((o,s)=>{const a=xt(i,o);Math.abs(a)>Math.abs(e)&&(n=s,e=a)}),!(n===-1||Math.abs(e)<by))return{axis:n,sign:e>=0?1:-1}}function Sd(i){const t=i.getResolvedView?.()?.toICamera?.(),n=sp(t);if(n)return n;const e=i.getCamera?.();return sp(e)}function sp(i){const t=i,n=au(t?.focalPoint),e=au(t?.viewPlaneNormal),o=au(t?.viewUp);if(!(!n||!e||!o))return{focalPoint:n,viewPlaneNormal:e,viewUp:o}}function au(i){const t=i;if(!t||typeof t.length!="number"||t.length<3)return;const n=[Number(t[0]),Number(t[1]),Number(t[2])];return n.every(Number.isFinite)?n:void 0}function k1(i){const{direction:t}=i;return[[t[0],t[1],t[2]],[t[3],t[4],t[5]],[t[6],t[7],t[8]]]}function U1(i,t){const n=Sd(i);if(!n)return;const{viewPlaneNormal:e,viewUp:o,focalPoint:s}=n,a=Wt(B(),Me(B(),e,o)),r=Wt(B(),o),c=k1(t),l=su(a,c),d=su(r,c),u=su(e,c);if(!l||!d||!u||new Set([l.axis,d.axis,u.axis]).size!==3)return;const f=CC(t.imageData,s),g=Math.floor(f[u.axis]+.5-1e-6);if(!(g<0||g>=t.dimensions[u.axis]))return{key:[u.axis,g,l.axis,l.sign,d.axis,d.sign].join(":"),xAxis:l.axis,xSign:l.sign,yAxis:d.axis,ySign:d.sign,sliceAxis:u.axis,sliceIndex:g}}function Cd(i,t){const n=U1(t,i);if(!n)return;const e=k1(i),{dimensions:o,spacing:s,voxelManager:a}=i,r=o[n.xAxis],c=o[n.yAxis],l=a.getConstructor(),d=new l(r*c),u=[0,0,0];u[n.sliceAxis]=n.sliceIndex;const h=n.xSign>0?0:r-1,f=n.xSign>0?1:-1,g=n.ySign>0?0:c-1,m=n.ySign>0?1:-1;for(let y=0,D=g;y<c;y++,D+=m){u[n.yAxis]=D;const T=y*r;for(let P=0,x=h;P<r;P++,x+=f)u[n.xAxis]=x,d[T+P]=Number(a.getAtIJK(u[0],u[1],u[2]))}const p=[0,0,0];p[n.sliceAxis]=n.sliceIndex,p[n.xAxis]=n.xSign>0?0:r-1,p[n.yAxis]=n.ySign>0?0:c-1;const v=e[n.xAxis].map(y=>y*n.xSign),I=e[n.yAxis].map(y=>y*n.ySign),w=Sd(t);if(!w)return;const C=Wt(B(),w.viewPlaneNormal),S=_n.getDataType(d),b=_n.newInstance({dataType:S,name:"Pixels",numberOfComponents:1,values:d}),_=Ph.newInstance();return _.set({dataType:S,numberOfComponents:1},!0),_.setDimensions(r,c,1),_.setSpacing([s[n.xAxis],s[n.yAxis],1]),_.setDirection(new Float32Array([...v,...I,C[0],C[1],C[2]])),_.setOrigin(Yc(i.imageData,p)),_.getPointData().setScalars(b),_.modified(),{imageData:_,state:n}}const EO="labelmap-image-mapper-overlay";function Bf(i){const t=i;return t.type===so.PLANAR_NEXT&&typeof t.addImages=="function"&&typeof t.getCurrentImageId=="function"&&typeof t.render=="function"}function SO(i){const t=bC.newInstance();t.setInputData(i.imageData);const n=_C.newInstance();return n.setMapper(t),{uid:i.representationUID,actor:n,actorMapper:{actor:n,mapper:t,renderMode:We.VTK_IMAGE},referencedId:i.referencedId,representationUID:i.representationUID}}function ih(i){return`${i}::${EO}`}function CO(i){const n=i.getRenderingEngine().getOffscreenMultiRenderWindow(i.id),e=ih(i.id),o=i.getRenderer(),s=o.getViewport();let a=n.getRenderer(e);if(!a){const r=n.getRenderWindow();r.getNumberOfLayers()<2&&r.setNumberOfLayers(2),n.addRenderer({viewport:s,id:e,background:[0,0,0]}),a=n.getRenderer(e),a.setLayer(1),a.setPreserveDepthBuffer(!1)}return a.setActiveCamera(o.getActiveCamera()),a.setViewport(s[0],s[1],s[2],s[3]),a}function bO(i,t){const n=i.getRenderer(),e=CO(i);n.removeActor(t.actor),e.addActor(t.actor)}function _O(i,t,n){if(!vi(i))return[];const e=Bf(i);return cn(n).map(o=>{const s=$n(o);if(!s)return;const a=U1(i,s);if(a)return Ji({segmentationId:t,referencedId:o.labelmapId,...e?{}:{sliceStateKey:a.key}})}).filter(o=>!!o)}async function yO(i){const{viewport:t,segmentation:n,segmentationId:e}=i;if(vi(t)){if(Bf(t)){await TO({viewport:t,segmentation:n,segmentationId:e});return}cn(n).forEach(o=>{const s=$n(o);if(!s)return;const a=Cd(s,t);if(!a)return;const r=Ji({segmentationId:e,referencedId:o.labelmapId,sliceStateKey:a.state.key}),c=SO({imageData:a.imageData,referencedId:o.labelmapId,representationUID:r});t.addActor(c),bO(t,c)})}}function xO(i){const{viewport:t,segmentation:n,segmentationId:e,actorEntries:o}=i;if(!vi(t))return;if(Bf(t)){MO({viewport:t,segmentation:n,segmentationId:e,actorEntries:o});return}const s=new Map((o??t.getActors()).filter(a=>Id(a.representationUID,e)).map(a=>[a.referencedId,a]));cn(n).forEach(a=>{const r=s.get(a.labelmapId);if(!r)return;const c=$n(a);if(!c)return;const l=Cd(c,t);if(!l)return;const d=r.actor.getMapper();d.setInputData(l.imageData),d.modified(),r.actor.modified?.()})}function PO(i,t){if(i.type!==so.ORTHOGRAPHIC||!vi(i))return;const e=i.getRenderingEngine().getOffscreenMultiRenderWindow(i.id),o=e.getRenderer(ih(i.id));o&&(i.getActors().filter(s=>Id(s.representationUID,t)).forEach(s=>{o.removeActor(s.actor)}),o.getActors().length||e.removeRenderer(ih(i.id)))}function DO(i,t){if(t)return _a(i,t)??Sy(i,t)??Cy(i,t)??cn(i).find(n=>n.volumeId===t)}async function TO(i){const{viewport:t,segmentation:n,segmentationId:e}=i;for(const[o,s]of cn(n).entries()){const a=$n(s);if(!a)continue;const r=Cd(a,t);if(!r)continue;const c=t.getCurrentImageId()??a.imageIds[Math.min(Math.max(r.state.sliceIndex,0),Math.max(a.imageIds.length-1,0))];if(!c)continue;const l=Ji({segmentationId:e,referencedId:s.labelmapId});await t.addImages([{dataId:l,imageId:c,imageData:r.imageData,reference:{kind:"segmentation",segmentationId:e,representationUID:l,labelmapId:s.labelmapId},useWorldCoordinateImageData:!0,callback:({imageActor:d})=>{const u=d.getMapper(),h=Sd(t);u.setInputData(r.imageData),u.modified(),h&&N1(d,h.viewPlaneNormal,o+1)}}])}t.render()}function MO(i){const{viewport:t,segmentation:n,segmentationId:e,actorEntries:o}=i,s=new Map((o??t.getActors()).filter(a=>Id(a.representationUID,e)).map(a=>[a.referencedId,a]));cn(n).forEach((a,r)=>{const c=s.get(a.labelmapId);if(!c)return;const l=$n(a);if(!l)return;const d=Cd(l,t);if(!d)return;const u=c.actor.getMapper();u.setInputData(d.imageData),u.modified();const h=Sd(t);h&&N1(c.actor,h.viewPlaneNormal,r+1),c.actor.modified?.()})}function V1(i,t){PO(i,t);const n=Dr(i.id,t)??[],e=[];n.forEach(o=>{jw(i,t,o)||e.push(o.uid)}),e.length&&i.removeActors(e)}function bd({isVolumeImageMapper:i,kind:t,renderMode:n,segmentationId:e,unsupportedStateKey:o,updateAfterMount:s=!0,useSliceRendering:a,viewport:r,canRenderCurrentViewport:c=()=>t!=="unsupported",getExpectedRepresentationUIDs:l=()=>[],isActorEntryCompatible:d=()=>!0,mount:u=async()=>{},update:h=()=>{}}){const f=()=>V1(r,e),g=m=>AO(m,l())||(m??[]).some(p=>!d(p));return{kind:t,renderMode:n,useSliceRendering:a,isVolumeImageMapper:i,unsupportedStateKey:o,getExpectedRepresentationUIDs:l,mount:u,needsRemount:g,remove:f,update:h,reconcile:async({actorEntries:m,labelMapData:p})=>{if(!c())return m;let v=m;g(v)&&v?.length&&(f(),v=void 0);const I=!v?.length;return I&&await u({labelMapData:p}),v=Dr(r.id,e),v?.length&&(!I||s)&&h({actorEntries:v}),v}}}function F1(i){return i.actorMapper?.renderMode}function AO(i,t){const n=new Set((i??[]).map(o=>o.representationUID)),e=new Set(t);if(n.size!==e.size)return!0;for(const o of e)if(!n.has(o))return!0;return!1}const ru=new Map,LO=({cfun:i,ofun:t,actor:n})=>{n.getProperty().setRGBTransferFunction(1,i),n.getProperty().setScalarOpacity(1,t)};async function OO({viewport:i,volumeInputs:t,segmentationId:n}){const e=i.getDefaultActor(),{actor:o}=e,{uid:s}=e,a=i.getVolumeId();if(ru.get(s)?.added)return{uid:s,actor:o};const r=t,c=Q.getVolume(r[0].volumeId);if(!c)throw new Error(`imageVolume with id: ${c.volumeId} does not exist`);const{volumeId:l}=r[0],d=await yC(l);if(!d)throw new Error(`segImageVolume with id: ${d.volumeId} does not exist`);const h=d.voxelManager.getCompleteScalarDataArray(),{imageData:f}=d,g=Q.getVolume(a);if(g.vtkOpenGLTexture.hasUpdatedFrames())return;const I=g.voxelManager.getCompleteScalarDataArray(),w=2,C=new Float32Array(w*g.voxelManager.getScalarDataLength()),S=f.getDimensions();for(let z=0;z<S[2];++z)for(let q=0;q<S[1];++q)for(let J=0;J<S[0];++J){const it=J+S[0]*(q+S[1]*z);C[it*w+0]=I[it],C[it*w+1]=h[it]}i.removeActors([s]);const b=o.getMapper(),_=b.getInputData(),y=_.getPointData().getScalars()??null,D=xC(b);o.setMapper(D),D.setBlendMode(Gn.LABELMAP_EDGE_PROJECTION_BLEND);const T=D.getInputData().getPointData().getArray(0);T.setData(C),T.setNumberOfComponents(2);const P=o.getProperty().getColorMixPreset();o.getProperty().setColorMixPreset(1);const x=o.getProperty().getForceNearestInterpolation(1);o.getProperty().setForceNearestInterpolation(1,!0);const M=o.getProperty().getIndependentComponents();o.getProperty().setIndependentComponents(!0);const L=o.getProperty().getUseLabelOutline(),R=o.getProperty().getLabelOutlineOpacity(),U=o.getProperty().getLabelOutlineThickness(),W=r[0].representationUID??`${n}-${St.Labelmap}`;i.addActor({...e,representationUID:W}),ru.set(s,{added:!0,segmentationRepresentationUID:`${n}`,originalBlendMode:i.getBlendMode()});const K=o.get("preLoad");o.set({preLoad:LO});function j(z){const{segmentationId:q,modifiedSlicesToUse:J}=z.detail,{representationData:it}=Dt(q),{volumeId:tt}=it.Labelmap;if(tt!==d.volumeId)return;const ot=Q.getVolume(tt),nt=ot.voxelManager,lt=D.getInputData(),rt=lt.getPointData().getArray(0),ut=rt.getData(),Tt=2,kt=f.getDimensions(),Pt=kt[0]*kt[1],te=J?.length?J:Array.from({length:kt[2]},(Ie,re)=>re);for(const Ie of te){const re=Ie*Pt,ce=Q.getImage(ot.imageIds?.[Ie])?.voxelManager?.getScalarData?.();if(ce?.length===Pt)for(let Ut=0;Ut<Pt;++Ut)ut[(re+Ut)*Tt+1]=ce[Ut];else for(let Ut=0;Ut<Pt;++Ut){const Ht=re+Ut;ut[Ht*Tt+1]=nt.getAtIndex(Ht)}}rt.setData(ut),lt.modified(),i.render()}Z.addEventListenerDebounced(E.SEGMENTATION_DATA_MODIFIED,j,200);function F(z){if(z.detail.viewportId!==i.id||(Z.removeEventListenerDebounced(E.SEGMENTATION_DATA_MODIFIED,j),Z.removeEventListener(E.SEGMENTATION_REPRESENTATION_REMOVED,F),i.getActor(s)&&i.removeActors([s]),ru.delete(s),i.isDisabled))return;o.setMapper(b);const J=_.getPointData();y?J.setScalars(y):J.removeArray("Pixels"),_.modified(),o.getProperty().setColorMixPreset(P),o.getProperty().setForceNearestInterpolation(1,x),o.getProperty().setIndependentComponents(M),o.getProperty().setUseLabelOutline(L),o.getProperty().setLabelOutlineOpacity(R),o.getProperty().setLabelOutlineThickness(U),i.addActor({...e}),o.set(K),i.render()}return Z.addEventListener(E.SEGMENTATION_REPRESENTATION_REMOVED,F),{uid:s,actor:o}}function RO(i){const t=i;return t.type===so.PLANAR_NEXT&&typeof t.getVolumeId=="function"&&typeof t.getViewReference=="function"&&typeof t.getViewState=="function"&&typeof t.addDisplaySet=="function"&&typeof t.setDisplaySetPresentation=="function"&&typeof t.setViewReference=="function"}async function NO(i){const{blendMode:t,labelmapLayers:n,segmentationId:e,viewport:o,visibility:s}=i;if(!kO(o))return;const r=o.getVolumeId(),c=r?o.getViewReference({volumeId:r}):o.getViewReference(),l=o.getViewState().orientation,d=o.getSourceDataId?.(),u=d?o.getDisplaySetPresentation?.(d)?.slabThickness:void 0,h=Math.max(0,o.getCurrentImageIdIndex?.()??0);let f;for(const g of n){if(!g.volumeId)continue;const m=Q.getVolume(g.volumeId);if(!m)throw new Error(`imageVolume with id: ${g.volumeId} does not exist, you need to create/allocate the volume first`);const p=Ji({segmentationId:e,referencedId:g.labelmapId}),v=p;xh.add(v,{kind:"planar",imageIds:m.imageIds,initialImageIdIndex:Math.min(h,Math.max(m.imageIds.length-1,0)),reference:{kind:"segmentation",segmentationId:e,representationUID:p,labelmapId:g.labelmapId},volumeId:g.volumeId}),await o.addDisplaySet(v,{orientation:l,role:"overlay"}),o.setDisplaySetPresentation(v,{blendMode:t,visible:s,...u!==void 0?{slabThickness:u}:{}}),f||=o.getActors?.().find(I=>I.representationUID===p)}if(o.setViewReference(c),o.render?.(),f)return{uid:f.uid,actor:f.actor}}function kO(i){const t=i.getDefaultActor?.()?.actorMapper?.renderMode;if(t===We.CPU_VOLUME||t===We.VTK_VOLUME_SLICE)return t}const{uuidv4:G1}=oe;function UO({config:i,isVolumeImageMapper:t,renderMode:n,segmentation:e,segmentationId:o,useSliceRendering:s,viewport:a}){return bd({isVolumeImageMapper:t,kind:"legacy-volume",renderMode:n,segmentationId:o,useSliceRendering:s,viewport:a,getExpectedRepresentationUIDs:()=>FO(e,o),isActorEntryCompatible:r=>!VO(r),mount:({labelMapData:r})=>GO({config:i,labelMapData:r,segmentation:e,segmentationId:o,viewport:a})})}function VO(i){const t=F1(i);return t===We.VTK_IMAGE||t===We.CPU_IMAGE}function FO(i,t){return cn(i).filter(HO).map(n=>Ji({segmentationId:t,referencedId:n.labelmapId}))}async function GO({config:i,labelMapData:t,segmentation:n,segmentationId:e,viewport:o}){const{id:s}=o,a=!0,r=!1,c=!0,l=o,d=WO(n);if(!d.length){const m=BO(t,n);Q.getVolume(m)||await zO(t),d.push({labelmapId:m,storageKind:"volume",volumeId:m,imageIds:Q.getVolume(m)?.imageIds})}let u=i?.blendMode??Gn.MAXIMUM_INTENSITY_BLEND,h=u===Gn.LABELMAP_EDGE_PROJECTION_BLEND;if(h){const g=l.getVolumeId?.(),m=d[0]?.volumeId,p=g?Q.getVolume(g):void 0,v=m?Q.getVolume(m):void 0;if(!p||!v)h=!1,u=Gn.MAXIMUM_INTENSITY_BLEND,console.debug("Independent components unavailable (missing reference or segmentation volume) - falling back to regular volume addition");else{const I=v.dimensions,w=p.dimensions;(I[0]!==w[0]||I[1]!==w[1]||I[2]!==w[2])&&(h=!1,u=Gn.MAXIMUM_INTENSITY_BLEND,console.debug("Dimensions mismatch - falling back to regular volume addition"))}}const f=d.map(g=>({volumeId:g.volumeId,visibility:a,representationUID:Ji({segmentationId:e,referencedId:g.labelmapId}),useIndependentComponents:h,blendMode:u}));if(RO(o))return NO({blendMode:u,labelmapLayers:d,segmentationId:e,viewport:o,visibility:a});if(!f[0].useIndependentComponents){await Sb(o.getRenderingEngine(),f,[s],r,c),He(e);return}return OO({viewport:l,volumeInputs:f,segmentationId:e})}function HO(i){return!!(i.volumeId||i.geometryVolumeId||i.imageIds?.length)}function WO(i){return cn(i).map(t=>{if(t.volumeId)return t;const n=$n(t);if(n?.volumeId)return{...t,volumeId:n.volumeId}}).filter(t=>!!t)}function BO(i,t){let{volumeId:n}=i;return n||(n=G1(),t.representationData.Labelmap={...t.representationData.Labelmap,volumeId:n},i.volumeId=n,Co(t.segmentationId)),n}async function zO(i){const t=i;if(!(t.imageIds.length>0))throw new Error("cannot create labelmap, no imageIds found for the volume labelmap");return await Iv(i.volumeId??G1(),t.imageIds)}function $O({isVolumeImageMapper:i,renderMode:t,segmentationId:n,useSliceRendering:e,viewport:o}){return bd({isVolumeImageMapper:i,kind:"legacy-stack-image",renderMode:t,segmentationId:n,updateAfterMount:!1,useSliceRendering:e,viewport:o,canRenderCurrentViewport:()=>jO(o,n),getExpectedRepresentationUIDs:()=>XO(o,n),mount:()=>qO(o,n),update:()=>wd(o,n)})}function jO(i,t){return!!ys(i.id,t)?.length}function XO(i,t){return ys(i.id,t)?.map(n=>Ji({segmentationId:t,referencedId:n}))??[]}async function qO(i,t){wd(i,t),He(t)}function YO({isVolumeImageMapper:i,renderMode:t,segmentation:n,segmentationId:e,useSliceRendering:o,viewport:s}){return bd({isVolumeImageMapper:i,kind:"volume-slice-image-mapper",renderMode:t,segmentationId:e,useSliceRendering:o,viewport:s,getExpectedRepresentationUIDs:()=>_O(s,e,n),isActorEntryCompatible:a=>!KO(a),mount:()=>ZO({viewport:s,segmentation:n,segmentationId:e}),update:({actorEntries:a})=>xO({viewport:s,segmentation:n,segmentationId:e,actorEntries:a})})}function KO(i){const t=F1(i);return t===We.VTK_VOLUME||t===We.VTK_VOLUME_SLICE||t===We.CPU_VOLUME}async function ZO({viewport:i,segmentation:t,segmentationId:n}){await yO({viewport:i,segmentation:t,segmentationId:n}),He(n)}function JO({viewport:i,segmentation:t,representation:n}){const{segmentationId:e,config:o}=n,s=$h(t,o),a=zn(i,{useSliceRendering:s}),r=s&&vi(i);return a==="unsupported"?bd({isVolumeImageMapper:r,kind:"unsupported",renderMode:a,segmentationId:e,unsupportedStateKey:s?HI(i).key:void 0,useSliceRendering:s,viewport:i}):r?YO({isVolumeImageMapper:r,renderMode:a,segmentation:t,segmentationId:e,useSliceRendering:s,viewport:i}):a==="volume"?UO({config:o,isVolumeImageMapper:r,renderMode:a,segmentation:t,segmentationId:e,useSliceRendering:s,viewport:i}):$O({isVolumeImageMapper:r,renderMode:a,segmentationId:e,useSliceRendering:s,viewport:i})}function QO(i,t){me.setActiveSegmentation(i,t)}function ni(i){return Wi(i)}function t2(i,t){QO(i,t)}const e2=Object.freeze(Object.defineProperty({__proto__:null,getActiveSegmentation:ni,setActiveSegmentation:t2},Symbol.toStringTag,{value:"Module"})),ap=new WeakMap,cu=new WeakMap,lu=255;function n2(i,t,n){const{segmentationId:e}=n,{colorLUTIndex:o}=n,a=ni(i)?.segmentationId===e,r=Yn.getStyle({viewportId:i,type:St.Labelmap,segmentationId:e}),c=Yn.getRenderInactiveSegmentations(i),l=rc(o),d=Dt(e),u=DO(d,t.referencedId),h=Object.keys(d.segments).map(Number).map(j=>({segmentIndex:j,binding:Hi(d,j)})).filter(j=>!u||j.binding?.labelmapId===u.labelmapId),f=Math.max(1,...h.map(j=>j.binding?.labelValue??j.segmentIndex)),g=Math.max(l.length,f+1),m=Array.from({length:g-1},(j,F)=>{const z=F+1,q=u?.labelToSegmentIndex?.[z]??z;return{labelValue:z,segmentIndex:q}}),{outlineWidth:p,renderOutline:v,outlineOpacity:I,activeSegmentOutlineWidthDelta:w}=rp(r,a),C=Rf(i,{segmentationId:e,type:St.Labelmap}),S=t.actor,b=[{x:0,r:0,g:0,b:0,midpoint:.5,sharpness:1}],_=[{x:0,y:0,midpoint:.5,sharpness:1}];m.forEach(({labelValue:j,segmentIndex:F})=>{const z=l[F];if(!z)return;const q=Yn.getStyle({viewportId:i,type:St.Labelmap,segmentationId:e,segmentIndex:F}),{fillAlpha:J,renderFill:it}=rp(r,a,q);if(b.push({x:j,r:z[0]/lu,g:z[1]/lu,b:z[2]/lu,midpoint:.5,sharpness:1}),it){const tt=C.has(F)?0:z[3]/255*J;_.push({x:j,y:tt,midpoint:.5,sharpness:1})}else _.push({x:j,y:.01,midpoint:.5,sharpness:1})});const y=xn(n.segmentationId),D=new Array(g-1).fill(0);v&&m.forEach(({labelValue:j,segmentIndex:F})=>{C.has(F)||(D[j-1]=F===y?p+w:p)});const T=a||c,P=t.actorMapper?.renderMode===We.VTK_IMAGE||t.actorMapper?.renderMode===We.VTK_VOLUME_SLICE,{preLoad:x}=S.get?.("preLoad")||{preLoad:null},M=JSON.stringify({colorNodes:b,opacityNodes:_,renderOutline:v,outlineOpacity:I,outlineWidths:D,visible:T,useImageSliceProperties:P}),L=!x;if(L&&cu.get(S)===M)return;const{cfun:R,ofun:U}=o2(S);R.removeAllPoints(),U.removeAllPoints(),R.setNodes(b),U.setNodes(_),U.setClamping(!1);const W=t.actorMapper,K=W?.mapper?W.mapper:S.getMapper();if(x?x({cfun:R,ofun:U,actor:S}):(S.getProperty().setRGBTransferFunction(0,R),S.getProperty().setScalarOpacity(0,U),S.getProperty().setInterpolationTypeToNearest()),P){const j=S;j.setForceTranslucent(!0),j.setForceOpaque(!1),j.getProperty().setUseLookupTableScalarRange(!0)}v?(S.getProperty().setUseLabelOutline(v),S.getProperty().setLabelOutlineOpacity(I),S.getProperty().setLabelOutlineThickness(D),S.modified(),S.getProperty().modified(),K?.modified?.()):S.getProperty().setLabelOutlineThickness(D),S.setVisibility(T),S.modified(),S.getProperty().modified(),K?.modified?.(),L?cu.set(S,M):cu.delete(S)}function o2(i){const t=ap.get(i);if(t)return t;const n=vv.newInstance(),e=bh.newInstance();e.addPoint(0,0);const o={cfun:n,ofun:e};return ap.set(i,o),o}function rp(i,t,n){const o={...i,...n||{}};return{fillAlpha:t?o.fillAlpha:o.fillAlphaInactive,outlineWidth:t?o.outlineWidth:o.outlineWidthInactive,renderFill:t?o.renderFill:o.renderFillInactive,renderOutline:t?o.renderOutline:o.renderOutlineInactive,outlineOpacity:t?o.outlineOpacity:o.outlineOpacityInactive,activeSegmentOutlineWidthDelta:o.activeSegmentOutlineWidthDelta}}const sh=new Map;let du=!1;function i2(i,t,n=!1){W1(i,t);const e=le(i);if(!e)return;const{viewport:o}=e;V1(o,t),n&&o.render()}async function s2(i,t){const{segmentationId:n}=t,e=Dt(n);if(!e){console.warn("No segmentation found for segmentationId: ",n);return}let o=e.representationData[St.Labelmap],s=Dr(i.id,n);if(!o&&Yo()?.canComputeRequestedRepresentation(n,St.Labelmap)&&!du){du=!0;const r=Yo();if(o=await Wf(n,St.Labelmap,()=>r.computeLabelmapData(n,{viewport:i}),()=>{me.processLabelmapRepresentationAddition(i.id,n),setTimeout(()=>{He(n)},0)}),!o)throw new Error(`No labelmap data found for segmentationId ${n}.`);du=!1}else!o&&!Yo()&&console.debug(`No labelmap data found for segmentationId ${n} and PolySeg add-on is not configured. Unable to convert from other representations to labelmap. Please register PolySeg using cornerstoneTools.init({ addons: { polySeg } }) to enable automatic conversion.`);if(!o)return;const a=JO({viewport:i,segmentation:e,representation:t});if(a.kind==="unsupported"){s?.length&&a.remove(),a.unsupportedStateKey&&r2(i.id,n,a.unsupportedStateKey);return}if(W1(i.id,n),s=await a.reconcile({actorEntries:s,labelMapData:o}),!!s?.length)for(const r of s)n2(i.id,r,t)}function a2(i){}function H1(i,t){return`${i}:${t}`}function W1(i,t){sh.delete(H1(i,t))}function r2(i,t,n){const e=H1(i,t);sh.get(e)!==n&&(sh.set(e,n),Z.dispatchEvent(new CustomEvent(yt.ERROR_EVENT,{detail:{type:"Segmentation",message:"Labelmap image-mapper rendering is only supported on legacy orthographic single-slice volume viewports."},cancelable:!0})))}const c2={getUpdateFunction:a2,render:s2,removeRepresentation:i2};function l2(i,t){const n=N(i),{viewport:e}=n,s=e.getActors().filter(a=>a.representationUID&&typeof a.representationUID=="string"&&a.representationUID.startsWith(t));e.removeActors(s.map(a=>a.uid))}function d2(i,t,n){const o=KM(i.id,n,t.segmentIndex)?.actor,s=t.visible;if(o){if(o.setVisibility(s),!s)return;const m=o.getMapper(),p=m.getInputData(),v=t.points,I=t.polys,w=p.getPoints().getData(),C=p.getPolys().getData();if(v.length===w.length&&I.length===C.length)return;const S=Vo.newInstance();S.getPoints().setData(v,3);const b=la.newInstance({values:Float32Array.from(I)});S.setPolys(b),m.setInputData(S),m.modified(),i.getRenderer().resetCameraClippingRange();return}const a=t.points,r=t.polys,c=t.color,l=Vo.newInstance();l.getPoints().setData(a,3);const d=la.newInstance({values:Float32Array.from(r)});l.setPolys(d);const u=Oo.newInstance({});let h;u.setInputData(l);const f=vo.newInstance();f.setMapper(u),f.getProperty().setColor(c[0]/255,c[1]/255,c[2]/255),f.getProperty().setLineWidth(2);const g=Dw(n,t.segmentIndex);i.addActor({uid:Se(),actor:f,clippingFilter:h,representationUID:g}),i.resetCamera(),i.getRenderer().resetCameraClippingRange(),i.render()}function u2(i,t,n=!1){const e=le(i);if(!e)return;const{viewport:o}=e;l2(o.element,t),n&&o.render()}async function h2(i,t){const{segmentationId:n,type:e}=t,o=Dt(n);if(!o)return;let s=o.representationData[St.Surface];if(!s&&Yo()?.canComputeRequestedRepresentation(n,St.Surface)){const l=Yo();if(s=await Wf(n,St.Surface,()=>l.computeSurfaceData(n,{viewport:i})),!s)throw new Error(`No Surface data found for segmentationId ${n} even we tried to compute it`)}else!s&&!Yo()&&console.debug(`No surface data found for segmentationId ${n} and PolySeg add-on is not configured. Unable to convert from other representations to surface. Please register PolySeg using cornerstoneTools.init({ addons: { polySeg } }) to enable automatic conversion.`);if(!s){console.warn(`No Surface data found for segmentationId ${n}. Skipping render.`);return}const{geometryIds:a}=s;a?.size||console.warn(`No Surfaces found for segmentationId ${n}. Skipping render.`);const{colorLUTIndex:r}=t,c=rc(r);a.forEach(l=>{const d=Q.getGeometry(l);if(!d?.data){console.warn(`No Surfaces found for geometryId ${l}. Skipping render.`);return}const{segmentIndex:u}=d.data,f=Rf(i.id,{segmentationId:n,type:e}).has(u),g=d.data,m=c[u];g.color=m.slice(0,3),g.visible=!f,d2(i,g,n)}),i.render()}function f2(i){const t=Yo();return n=>t.updateSurfaceData(n,{viewport:i})}const g2={getUpdateFunction:f2,render:h2,removeRepresentation:u2};let cp=!1;function B1(){cp||(ou(St.Labelmap,c2),ou(St.Contour,IO),ou(St.Surface,g2),cp=!0)}B1();let ah=!1;function NH(i={}){ah||(B1(),TM(i),m2(),p2(),ah=!0)}function kH(){z1(),$1(),Gv(),Pb();const i=Go(),t=me;i.restoreAnnotations({}),t.resetState(),ah=!1}function m2(){z1();const i=yt.ELEMENT_ENABLED,t=yt.ELEMENT_DISABLED;Z.addEventListener(i,Vf),Z.addEventListener(t,Ff),Z.addEventListener(yt.RENDERING_PIPELINE_CHANGED,O1),P1.enable()}function z1(){const i=yt.ELEMENT_ENABLED,t=yt.ELEMENT_DISABLED;Z.removeEventListener(i,Vf),Z.removeEventListener(t,Ff),Z.removeEventListener(yt.RENDERING_PIPELINE_CHANGED,O1),P1.disable()}function p2(){$1(),Z.addEventListener(E.ANNOTATION_COMPLETED,Zw),Z.addEventListener(E.ANNOTATION_MODIFIED,Jw),Z.addEventListener(E.ANNOTATION_SELECTION_CHANGE,El),Z.addEventListener(E.ANNOTATION_SELECTION_CHANGE,El),Z.addEventListener(E.ANNOTATION_REMOVED,Qw),Z.addEventListener(E.SEGMENTATION_MODIFIED,qw),Z.addEventListener(E.SEGMENTATION_DATA_MODIFIED,Xw),Z.addEventListener(E.SEGMENTATION_REPRESENTATION_MODIFIED,Cl),Z.addEventListener(E.SEGMENTATION_REPRESENTATION_ADDED,Cl),Z.addEventListener(E.SEGMENTATION_REMOVED,L1)}function $1(){Z.removeEventListener(E.ANNOTATION_COMPLETED,Zw),Z.removeEventListener(E.ANNOTATION_MODIFIED,Jw),Z.removeEventListener(E.ANNOTATION_SELECTION_CHANGE,El),Z.removeEventListener(E.ANNOTATION_SELECTION_CHANGE,El),Z.removeEventListener(E.ANNOTATION_REMOVED,Qw),Z.removeEventListener(E.SEGMENTATION_MODIFIED,qw),Z.removeEventListener(E.SEGMENTATION_DATA_MODIFIED,Xw),Z.removeEventListener(E.SEGMENTATION_REPRESENTATION_MODIFIED,Cl),Z.removeEventListener(E.SEGMENTATION_REPRESENTATION_ADDED,Cl),Z.removeEventListener(E.SEGMENTATION_REMOVED,L1)}const UH=Object.freeze(Object.defineProperty({__proto__:null,COLOR_LUT:ia},Symbol.toStringTag,{value:"Module"})),VH="5.8.2";function Aa(i,t){const n=Kc.getPresentation(i,{selector:t});return n||i.getViewPresentation?.(t)}function uc(i,t){if(!t)return!1;const n=i,e=Kc.withPresentation(i,t);return e&&typeof n.setViewState=="function"?(n.setViewState(e),!0):typeof n.setViewPresentation=="function"?(n.setViewPresentation(t),!0):!1}const v2={pan:!0,zoom:!0};function I2(i,t,n,e){const{camera:o}=e.detail,s=Ne(n.renderingEngineId);if(!s)throw new Error(`No RenderingEngine for Id: ${n.renderingEngineId}`);const a=s.getViewport(n.viewportId);if(ie(a)){const c=Ne(t.renderingEngineId)?.getViewport(t.viewportId);if(!c)return;a.setViewReference(c.getViewReference());const l=Aa(c,v2);uc(a,l)}else a.setCamera(o);a.render()}const{CAMERA_MODIFIED:w2}=yt;function E2(i){return Ps(i,w2,I2)}function S2(i,t,n,e,o){const s=Ne(n.renderingEngineId);if(!s)throw new Error(`No RenderingEngine for Id: ${n.renderingEngineId}`);const a=s.getViewport(n.viewportId),r=s.getViewport(t.viewportId),c=Aa(r,o);uc(a,c)&&a.render()}const{CAMERA_MODIFIED:C2}=yt;function b2(i,t){return Ps(i,C2,S2,{viewPresentation:t})}function _2(i,t,n,e,o){const s=e.detail,{volumeId:a,range:r,invertStateChanged:c,invert:l,colormap:d}=s,u=Ne(n.renderingEngineId);if(!u)throw new Error(`Rendering Engine does not exist: ${n.renderingEngineId}`);const h=u.getViewport(n.viewportId),f={voiRange:r};if(o?.syncInvertState&&c&&(f.invert=l),o?.syncColormap&&d&&(f.colormap=d),h instanceof pn)h._actors&&h._actors.size>1?h.setProperties(f,a):h.setProperties(f);else if(h instanceof Pn)h.setProperties(f);else if(ie(h)){const g=h,m=a?g.findDataIdByVolumeId?.(a):void 0;m?g.setDisplaySetPresentation(m,f):a||g.setDisplaySetPresentation(f)}else throw new Error("Viewport type not supported.");h.render()}function y2(i,t){return t=Object.assign({syncInvertState:!0,syncColormap:!0},t),Ps(i,yt.VOI_MODIFIED,_2,{auxiliaryEvents:[{name:yt.COLORMAP_MODIFIED}],...t})}const x2={pan:!0,zoom:!0};function P2(i){return!!i&&typeof i=="object"&&"setViewState"in i&&typeof i.setViewState=="function"}function D2(i,t,n){if(!P2(t))return!1;const e=Kc.getPresentation(i,{selector:x2});if(!e)return!1;const o={};if(n?.syncZoom!==!1&&typeof e.zoom=="number"&&(o.zoom=e.zoom),n?.syncPan!==!1&&e.pan&&(o.pan=e.pan),o.zoom===void 0&&o.pan===void 0)return!1;const s=Kc.withPresentation(t,o);return s?(t.setViewState(s),!0):!1}function T2(i,t,n){const e=Ne(n.renderingEngineId);if(!e)throw new Error(`No RenderingEngine for Id: ${n.renderingEngineId}`);const o=i.getOptions(n.viewportId),s=e.getViewport(n.viewportId),a=e.getViewport(t.viewportId);if(D2(a,s,o)){s.render();return}if(o?.syncZoom!==!1&&Zs(a)&&Zs(s)){const c=a.getZoom();s.setZoom(c)}if(o?.syncPan!==!1&&gr(a)&&gr(s)){const c=a.getPan();s.setPan(c)}s.render()}const{CAMERA_MODIFIED:M2}=yt;function A2(i){return Ps(i,M2,T2)}function L2(i,t){const{viewPlaneNormal:n}=i.getCamera(),{viewPlaneNormal:e}=t.getCamera(),o=xt(n,e);return Math.abs(o)>.9}const lp=(i,t)=>PC.get("spatialRegistrationModule",i,t);function O2(i){if(i instanceof Xe||Sv(i))return!0;const n=i.getDefaultActor?.call(i)?.actorMapper?.renderMode;return n===We.CPU_VOLUME||n===We.VTK_VOLUME_SLICE}async function j1(i,t,n){const e=Ne(n.renderingEngineId);if(!e)throw new Error(`No RenderingEngine for Id: ${n.renderingEngineId}`);const o=e.getViewport(t.viewportId),s=i.getOptions(n.viewportId);if(s?.disabled)return;const a=e.getViewport(n.viewportId),r=o.getCurrentImageId(),l=rn("imagePlaneModule",r).imagePositionPatient,d=a.getImageIds();if(!L2(o,a))return;let u=lp(n.viewportId,t.viewportId);if(!u){const m=o.getFrameOfReferenceUID(),p=a.getFrameOfReferenceUID();if(m===p&&s?.useInitialPosition!==!1?u=Qn(qi()):(lb(o,a),u=lp(n.viewportId,t.viewportId)),!u)return}const h=Ue(B(),l,u),f=R2(h,d);let g=f.index;O2(a)&&(g=d.length-f.index-1),f.index!==-1&&a.getCurrentImageIdIndex()!==g&&await Tv(a.element,{imageIndex:g})}function R2(i,t){return t.reduce((n,e,o)=>{const{imagePositionPatient:s}=rn("imagePlaneModule",e),a=ke(s,i);return a<n.distance?{distance:a,index:o}:n},{distance:1/0,index:-1})}const{STACK_NEW_IMAGE:N2,VOLUME_NEW_IMAGE:FH}=yt;function X1(i){return Ps(i,N2,j1,{auxiliaryEvents:[{name:"VOLUME_NEW_IMAGE"}]})}function k2(i,t,n){const e=Ne(n.renderingEngineId);if(!e)throw new Error(`No RenderingEngine for Id: ${n.renderingEngineId}`);const o=e.getViewport(n.viewportId),a=e.getViewport(t.viewportId).getSlabThickness?.();a&&(o.setSlabThickness?.(a),o.render())}const{CAMERA_MODIFIED:U2}=yt;function V2(i){return Ps(i,U2,k2)}const F2=X1,GH=Object.freeze(Object.defineProperty({__proto__:null,createCameraPositionSynchronizer:E2,createImageSliceSynchronizer:X1,createPresentationViewSynchronizer:b2,createSlabThicknessSynchronizer:V2,createStackImageSynchronizer:F2,createVOISynchronizer:y2,createZoomPanSynchronizer:A2,imageSliceSyncCallback:j1},Symbol.toStringTag,{value:"Module"}));function G2(i,t,n=5){const e=N(i);if(!e)throw new Error("getAnnotationNearPoint: enabledElement not found");return q1(e,t,n)}function q1(i,t,n){const{renderingEngineId:e,viewportId:o}=i,s=Ae(o,e);if(!s)return null;const{_toolInstances:a}=s;for(const r in a){const c=H2(a[r],i,t,n);if(c)return c}return null}function H2(i,t,n,e){const{viewport:o}=t,s=Yt(i.constructor.toolName,o?.element),a=o?.getCurrentImageId?.();if(s?.length){const{element:r}=t.viewport;for(const c of s){const l=c.metadata?.referencedImageId;if(!(a&&l&&a!==l||!i.isPointNearTool)&&(i.isPointNearTool(r,c,n,e,"")||i.getHandleNearImagePoint(r,c,n,e)))return c}}return null}function Xs(i,t){return typeof i?.[t]=="function"}function Ds(i){return Xs(i,"getCurrentImageId")&&Xs(i,"getCurrentImageIdIndex")&&Xs(i,"getImageIds")&&Xs(i,"hasImageURI")}function W2(i){return Ds(i)&&Xs(i,"setStack")}function dp(i){return Ds(i)&&Xs(i,"calibrateSpacing")}const{calibratedPixelSpacingMetadataProvider:B2}=oe;function z2(i,t,n){typeof n=="number"&&(n={type:DC.USER,scale:n}),B2.add(i,n),t.getViewports().filter(o=>dp(o)||W2(o)).forEach(o=>{const s=o.getImageIds();if(s.includes(i)){if(dp(o)){o.calibrateSpacing(i);return}const a=o.getCurrentImageIdIndex();Promise.resolve(o.setStack(s,a)).then(()=>{o.render()}).catch(r=>{console.warn("calibrateImageSpacing: failed to refresh stack-compatible viewport",r)})}})}function Y1(i,t){const n=i.findIndex(([e,o])=>e===o);if(n===-1)throw new Error("3D bounding boxes not supported in an oblique plane");return i[n][0]-=t,i[n][1]+=t,i}const $2=Object.freeze(Object.defineProperty({__proto__:null,extend2DBoundingBoxInViewAxis:Y1,getBoundingBoxAroundShape:Ii,getBoundingBoxAroundShapeIJK:Ii,getBoundingBoxAroundShapeWorld:xy,snapIndexBounds:Xc},Symbol.toStringTag,{value:"Module"})),{transformWorldToIndex:uu}=oe;function K1(i,t,n){const[e,o]=i,s=Ot((e[0]+o[0])/2,(e[1]+o[1])/2,(e[2]+o[2])/2),a=ke(e,o)/2,{boundsIJK:r,topLeftWorld:c,bottomRightWorld:l}=X2(t,n,i,s,a);return{boundsIJK:r,centerWorld:s,radiusWorld:a,topLeftWorld:c,bottomRightWorld:l}}function Z1(i,t){const n=t.getDirection(),e=Ot(n[0],n[1],n[2]),o=Ot(n[3],n[4],n[5]),s=Ot(n[6],n[7],n[8]),a=Lv(B(),s);return K1(i,t,{row:e,column:o,normal:a})}function j2(i,t,n){if(!n)throw new Error("viewport is required in order to calculate the sphere bounds");const e=ht(n);if(!e.viewUp||!e.viewPlaneNormal)throw new Error("viewport view plane is required in order to calculate the sphere bounds");const o=Ot(e.viewUp[0],e.viewUp[1],e.viewUp[2]),s=Ot(e.viewPlaneNormal[0],e.viewPlaneNormal[1],e.viewPlaneNormal[2]),a=B();Me(a,o,s);const r={row:a,normal:s,column:Lv(B(),o)};return K1(i,t,r)}function X2(i,t,n,e,o){const s=i.getDimensions(),{row:a,column:r,normal:c}=t,l=B(),d=B();ee(l,e,c,o),ee(d,e,c,-o),ee(l,l,r,-o),ee(d,d,r,o),ee(l,l,a,-o),ee(d,d,a,o);const u=uu(i,l),h=uu(i,d),f=n.map(m=>uu(i,m));return{boundsIJK:Ii([u,h,...f],s),topLeftWorld:l,bottomRightWorld:d}}function J1(i,t=5){return parseFloat(i[0]).toFixed(t)+","+parseFloat(i[1]).toFixed(t)+","+parseFloat(i[2]).toFixed(t)+","}class q2{static setStartRange(t,n,e=t.getCurrentImageIdIndex()){this.setRange(t,n,e)}static setEndRange(t,n,e=t.getCurrentImageIdIndex()){this.setRange(t,n,void 0,e)}static setRange(t,n,e,o){const{metadata:s}=n;e===void 0&&(e=s.sliceIndex<o?s.sliceIndex:0,o===void 0&&(o=t.getNumberOfSlices()-1));const a=t.getSliceIndexForImage(s.multiSliceReference);o===void 0&&(o=a>=e?a:t.getNumberOfSlices()-1),o=Math.max(e,o),s.sliceIndex=Math.min(e,o),s.referencedImageId=t.getCurrentImageId(s.sliceIndex),s.referencedImageURI=void 0,o===s.sliceIndex?s.multiSliceReference=void 0:o!==s.multiSliceReference?.sliceIndex&&(s.multiSliceReference={referencedImageId:t.getCurrentImageId(o),sliceIndex:o});const r={viewportId:t.id,renderingEngineId:t.renderingEngineId,changeType:Bt.MetadataReferenceModified,annotation:n};Rt(Z,E.ANNOTATION_MODIFIED,r),this.setViewportFrameRange(t,s)}static setSingle(t,n,e=t.getCurrentImageIdIndex()){this.setRange(t,n,e,e)}static getFrameRange(t){const{metadata:n}=t,{sliceIndex:e,multiSliceReference:o}=n,s=o?.sliceIndex;return s?[e+1,s+1]:e+1}static getFrameRangeStr(t){const n=this.getFrameRange(t);return Array.isArray(n)?`${n[0]}-${n[1]}`:String(n)}static setViewportFrameRange(t,n){t.setFrameRange&&n.multiSliceReference?.sliceIndex&&t.setFrameRange(n.sliceIndex+1,n.multiSliceReference.sliceIndex+1)}}function Q1(i,t,n){const{imageData:e}=i,{overwrite:o,boundsIJK:s,segmentationId:a}=n;if(!a)throw new Error("Segmentation ID is required to be passed inside thresholdVolumeByRange as options");const r=n?.overlapType||0,c=i.voxelManager,l=i.voxelManager.getScalarDataLength();if(o)for(let w=0;w<l;w++)c.setAtIndex(w,0);const{baseVolumeIdx:d,volumeInfoList:u}=BI(i,t);let h,f,g;const m=(w,C,S)=>{const b=({value:L})=>{f=f+1,L>=g.lower&&L<=g.upper&&(h=h+1)},{imageData:_,dimensions:y,lower:D,upper:T}=w,P=jh(_,y,C,S);f=0,h=0,g={lower:D,upper:T};let x=!1;const{voxelManager:M}=_.get("voxelManager");return M.forEach(b,{imageData:_,boundsIJK:P}),r===0?x=h>0:r==1&&(x=h===f),x},p=(w,C)=>{const{imageData:S,lower:b,upper:_}=w,y=S.get("voxelManager").voxelManager,D=y.toIndex(C),T=y.getAtIndex(D);return!(T<=b||T>=_)},v=({index:w,pointIJK:C,pointLPS:S})=>{let b=u.length>0;for(let _=0;_<u.length&&(u[_].volumeSize===l?b=p(u[_],C):b=m(u[_],u[d].spacing,S),!!b);_++);b&&c.setAtIndex(w,n.segmentIndex||1)};return i.voxelManager.forEach(v,{imageData:e,boundsIJK:s}),He(n.segmentationId),i}const{isEqual:Y2}=oe,tE=[{name:"Area",attribute:"area",unitAttribute:"areaUnit"},{name:"Mean",attribute:"mean",unitAttribute:"modalityUnit"},{name:"Max",attribute:"max",unitAttribute:"modalityUnit"},{name:"Min",attribute:"min",unitAttribute:"modalityUnit"},{name:"Std Dev",attribute:"stdDev",unitAttribute:"modalityUnit"}];function zf(i){return function(t,n){const e=Array.isArray(n)?n:[n],o=e.map(a=>t.cachedStats[a]).filter(a=>i.some(({attribute:r})=>a?.[r]!==void 0&&a?.[r]!==null));if(!o.length)return;const s=[];for(const a of i)K2(s,nE(o,e,a.name,a.attribute,a.unitAttribute));return s}}const eE=zf(tE);function K2(i,t){t&&i.push(t)}function nE(i,t,n,e,o){const s=[`${n}:`];let a=null,r=null;for(const c of i){if(!Fn(c?.[e]))continue;const l=c[e],d=c[o];Y2(a,l)&&r===d||(s.push(`${de(l)} ${d}`),a=l,r=d)}if(!(s.length<=1))return s.join(" ")}var Mr;const{transformWorldToIndex:up,transformWorldToIndexContinuous:Z2}=oe;class hc extends be{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{storePointData:!1,shadow:!0,preventHandleOutsideImage:!1,calculateStats:!0,getTextLines:eE,statsCalculator:bo,targetsFilter:A0.allPixelData}}){super(t,n),this.addNewAnnotation=e=>{const o=e.detail,{currentPoints:s,element:a}=o,r=s.world,c=N(a),{viewport:l}=c;this.isDrawing=!0;const d=this.constructor.createAnnotationForViewport(l,{data:{handles:{points:[[...r],[...r],[...r],[...r]],textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}},cachedStats:{}}});Nt(d,a);const u=ft(a,this.getToolName());return this.editData={annotation:d,viewportIdsToRender:u,handleIndex:3,movingTextBox:!1,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),wt(a),e.preventDefault(),V(u),d},this.isPointNearTool=(e,o,s,a)=>{const r=N(e),{viewport:c}=r,{data:l}=o,{points:d}=l.handles,u=c.worldToCanvas(d[0]),h=c.worldToCanvas(d[3]),f=this._getRectangleImageCoordinates([u,h]),g=[s[0],s[1]],{left:m,top:p,width:v,height:I}=f;return ef([m,p,v,I],g)<=a},this.toolSelectedCallback=(e,o)=>{const s=e.detail,{element:a}=s;o.highlighted=!0;const r=ft(a,this.getToolName());this.editData={annotation:o,viewportIdsToRender:r,movingTextBox:!1},this._activateModify(a),wt(a),V(r),e.preventDefault()},this.handleSelectedCallback=(e,o,s)=>{const a=e.detail,{element:r}=a,{data:c}=o;o.highlighted=!0;let l=!1,d;s.worldPosition?l=!0:d=c.handles.points.findIndex(h=>h===s);const u=ft(r,this.getToolName());this.editData={annotation:o,viewportIdsToRender:u,handleIndex:d,movingTextBox:l},this._activateModify(r),wt(r),V(u),e.preventDefault()},this._endCallback=e=>{const o=e.detail,{element:s}=o,{annotation:a,viewportIdsToRender:r,newAnnotation:c,hasMoved:l}=this.editData,{data:d}=a;c&&!l||(d.handles.activeHandleIndex=null,this._deactivateModify(s),this._deactivateDraw(s),Ft(s),this.doneEditMemo(),this.editData=null,this.isDrawing=!1,this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&Gt(a.annotationUID),V(r),c&&ue(a))},this._dragCallback=e=>{this.isDrawing=!0;const o=e.detail,{element:s}=o,{annotation:a,viewportIdsToRender:r,handleIndex:c,movingTextBox:l,newAnnotation:d}=this.editData;this.createMemo(s,a,{newAnnotation:d});const{data:u}=a;if(l){const{deltaPoints:h}=o,f=h.world,{textBox:g}=u.handles,{worldPosition:m}=g;m[0]+=f[0],m[1]+=f[1],m[2]+=f[2],g.hasMoved=!0}else if(c===void 0){const{deltaPoints:h}=o,f=h.world,{points:g}=u.handles;g.forEach(m=>{m[0]+=f[0],m[1]+=f[1],m[2]+=f[2]}),a.invalidated=!0}else{const{currentPoints:h}=o,f=N(s),{worldToCanvas:g,canvasToWorld:m}=f.viewport,p=h.world,{points:v}=u.handles;v[c]=[...p];let I,w,C,S,b,_,y,D;switch(c){case 0:case 3:I=g(v[0]),S=g(v[3]),w=[S[0],I[1]],C=[I[0],S[1]],_=m(w),y=m(C),v[1]=_,v[2]=y;break;case 1:case 2:w=g(v[1]),C=g(v[2]),I=[C[0],w[1]],S=[w[0],C[1]],b=m(I),D=m(S),v[0]=b,v[3]=D;break}a.invalidated=!0}this.editData.hasMoved=!0,N(s),V(r),a.invalidated&&zt(a,s,Bt.HandlesUpdated)},this.cancel=e=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateDraw(e),this._deactivateModify(e),Ft(e);const{annotation:o,viewportIdsToRender:s,newAnnotation:a}=this.editData,{data:r}=o;return o.highlighted=!1,r.handles.activeHandleIndex=null,V(s),a&&ue(o),this.editData=null,o.annotationUID}},this._activateDraw=e=>{$.isInteractingWithTool=!0,e.addEventListener(E.MOUSE_UP,this._endCallback),e.addEventListener(E.MOUSE_DRAG,this._dragCallback),e.addEventListener(E.MOUSE_MOVE,this._dragCallback),e.addEventListener(E.MOUSE_CLICK,this._endCallback),e.addEventListener(E.TOUCH_END,this._endCallback),e.addEventListener(E.TOUCH_DRAG,this._dragCallback),e.addEventListener(E.TOUCH_TAP,this._endCallback)},this._deactivateDraw=e=>{$.isInteractingWithTool=!1,e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragCallback),e.removeEventListener(E.MOUSE_MOVE,this._dragCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.TOUCH_END,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback)},this._activateModify=e=>{$.isInteractingWithTool=!0,e.addEventListener(E.MOUSE_UP,this._endCallback),e.addEventListener(E.MOUSE_DRAG,this._dragCallback),e.addEventListener(E.MOUSE_CLICK,this._endCallback),e.addEventListener(E.TOUCH_END,this._endCallback),e.addEventListener(E.TOUCH_DRAG,this._dragCallback),e.addEventListener(E.TOUCH_TAP,this._endCallback)},this._deactivateModify=e=>{$.isInteractingWithTool=!1,e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.TOUCH_END,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(e,o)=>{let s=!1;const{viewport:a}=e,{element:r}=a;let c=Yt(this.getToolName(),r);if(!c?.length||(c=this.filterInteractableAnnotationsForElement(r,c),!c?.length))return s;const l=a.getRenderingEngine(),d={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:e.viewport.id};for(let u=0;u<c.length;u++){const h=c[u],{annotationUID:f,data:g}=h,{points:m,activeHandleIndex:p}=g.handles,v=m.map(M=>a.worldToCanvas(M)),I=this.getMeasurementTargets(a,g);d.annotationUID=f;const{color:w,lineWidth:C,lineDash:S}=this.getAnnotationStyle({annotation:h,styleSpecifier:d}),{viewPlaneNormal:b,viewUp:_}=ht(a);if(this.ensureCachedStatsTargets(g,I,M=>M.areaUnit==null))this._calculateCachedStats(h,b,_,e);else if(h.invalidated&&(this._throttledCalculateCachedStats(h,b,_,e),a instanceof Xe)){const{referencedImageId:M}=h.metadata;for(const L in g.cachedStats)L.startsWith("imageId")&&l.getViewports().filter(Ds).find(W=>{const K=eo(M),j=W.hasImageURI(K),F=eo(W.getCurrentImageId());return j&&F!==K})&&delete g.cachedStats[L]}if(!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),s;let y;if(!$e(f))continue;!ze(f)&&!this.editData&&p!==null&&p!==void 0&&(y=[v[p]]);const D=!!Nn("showHandlesAlways",{});(y||D)&&xe(o,f,"0",D?v:y,{color:w});const T=`${f}-rect`;rf(o,f,"0",v,{color:w,lineDash:S,lineWidth:C},T),s=!0;const x=this.configuration.getTextLines(g,I);x?.length&&this.renderLinkedTextBoxAnnotation({enabledElement:e,svgDrawingHelper:o,annotation:h,styleSpecifier:d,textLines:x,canvasCoordinates:v})}return s},this._getRectangleImageCoordinates=e=>{const[o,s]=e;return{left:Math.min(o[0],s[0]),top:Math.min(o[1],s[1]),width:Math.abs(o[0]-s[0]),height:Math.abs(o[1]-s[1])}},this._calculateCachedStats=(e,o,s,a)=>{if(!this.configuration.calculateStats)return;const{data:r}=e,{viewport:c}=a,{element:l}=c,d=r.handles.points,{cachedStats:u}=r;if(e.invalidated){const m=this.getMeasurementTargets(c,r);for(const p of Object.keys(u))delete u[p];this.ensureCachedStatsTargets(r,m)}const h=Object.keys(u);let f=!1;for(let m=0;m<h.length;m++){const p=h[m],v=this.getTargetImageData(p);if(!v)continue;const{dimensions:I,imageData:w,metadata:C,voxelManager:S}=v,b=d.map(T=>Z2(w,T)),_=up(w,d[0]),y=up(w,d[3]),D=!this._isInsideVolume(_,y,I);if(f||=D,D)u[p]={Modality:C.Modality};else{const T=Math.min(_[0],y[0]),P=Math.max(_[0],y[0]),x=Math.min(_[1],y[1]),M=Math.max(_[1],y[1]),L=Math.min(_[2],y[2]),R=Math.max(_[2],y[2]),U=[[T,P],[x,M],[L,R]],K=ao(v,[_,y]),j=Mr.calculateLengthInIndex(K,[b[0],b[1]]),F=Mr.calculateLengthInIndex(K,[b[0],b[2]]),z=Math.abs(j*F),{areaUnit:q}=K,J={isPreScaled:Ki(c,p),isSuvScaled:this.isSuvScaled(c,p,e.metadata.referencedImageId)},it=bi(C.Modality,e.metadata.referencedImageId,J);let tt;S&&(tt=S.forEach(this.configuration.statsCalculator.statsCallback,{boundsIJK:U,imageData:w,returnPoints:this.configuration.storePointData}));const ot=this.configuration.statsCalculator.getStatistics();u[p]={Modality:C.Modality,area:z,mean:ot.mean?.value,stdDev:ot.stdDev?.value,max:ot.max?.value,min:ot.min?.value,statsArray:ot.array,pointsInShape:tt,areaUnit:q,modalityUnit:it}}}this.isHandleOutsideImage=f;const g=e.invalidated;return e.invalidated=!1,g&&zt(e,l,Bt.StatsUpdated),u},this._isInsideVolume=(e,o,s)=>gn(e,s)&&gn(o,s),this._throttledCalculateCachedStats=Un(this._calculateCachedStats,100,{trailing:!0})}}Mr=hc;hc.toolName="RectangleROI";hc.hydrate=(i,t,n)=>{const e=le(i);if(!e)return;const{FrameOfReferenceUID:o,referencedImageId:s,viewPlaneNormal:a,instance:r,viewport:c}=Mr.hydrateBase(Mr,e,t,n),{toolInstance:l,...d}=n||{},u={annotationUID:n?.annotationUID||Se(),data:{handles:{points:t,activeHandleIndex:null},label:"",cachedStats:{}},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{toolName:r.getToolName(),viewPlaneNormal:a,FrameOfReferenceUID:o,referencedImageId:s,...d}};Nt(u,c.element),V([c.id])};const{transformWorldToIndex:za}=oe;class oE extends hc{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{storePointData:!1,numSlicesToPropagate:10,calculatePointsInsideVolume:!0,getTextLines:J2,statsCalculator:bo,showTextBox:!1,throttleTimeout:100}}){super(t,n),this.addNewAnnotation=e=>{const o=e.detail,{currentPoints:s,element:a}=o,r=s.world,c=N(a),{viewport:l,renderingEngine:d}=c;this.isDrawing=!0;const u=l.getCamera(),{viewPlaneNormal:h,viewUp:f}=u;let g,m,p;if(l instanceof Pn)throw new Error("Stack Viewport Not implemented");{const _=this.getTargetId(l);p=Fi(_),m=Q.getVolume(p),g=qr(m,r,h)}const v=Dh(m,h),I=this._getStartCoordinate(r,h),w=this._getEndCoordinate(r,v,h),C=l.getFrameOfReferenceUID(),S={highlighted:!0,invalidated:!0,metadata:{viewPlaneNormal:[...h],enabledElement:c,viewUp:[...f],FrameOfReferenceUID:C,referencedImageId:g,toolName:this.getToolName(),volumeId:p,spacingInNormal:v},data:{label:"",startCoordinate:I,endCoordinate:w,cachedStats:{pointsInVolume:[],projectionPoints:[],projectionPointsImageIds:[g],statistics:[]},handles:{textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}},points:[[...r],[...r],[...r],[...r]],activeHandleIndex:null}}};this._computeProjectionPoints(S,m),Nt(S,a);const b=ft(a,this.getToolName());return this.editData={annotation:S,viewportIdsToRender:b,handleIndex:3,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),wt(a),e.preventDefault(),V(b),S},this._endCallback=e=>{const o=e.detail,{element:s}=o,{annotation:a,viewportIdsToRender:r,newAnnotation:c,hasMoved:l}=this.editData,{data:d}=a;if(c&&!l)return;d.handles.activeHandleIndex=null,this._deactivateModify(s),this._deactivateDraw(s),Ft(s);const{metadata:u}=a,{enabledElement:h}=u;this.editData=null,this.isDrawing=!1,this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&Gt(a.annotationUID);const f=this.getTargetId(h.viewport),g=Q.getVolume(f.split(/volumeId:|\?/)[1]);this._computeProjectionPoints(a,g),this._computePointsInsideVolume(a,f,g,h),V(r),c?ue(a):zt(a,s)},this.renderAnnotation=(e,o)=>{let s=!1;const{viewport:a}=e;let r=Yt(this.getToolName(),a.element);if(!r?.length)return s;r=nd(r,a.getCamera());const c={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:e.viewport.id};for(let l=0;l<r.length;l++){const d=r[l],{annotationUID:u,data:h,metadata:f}=d,{startCoordinate:g,endCoordinate:m}=h,{points:p,activeHandleIndex:v}=h.handles,{enabledElement:I}=f,w=p.map(F=>a.worldToCanvas(F));c.annotationUID=u;const C=this.getStyle("lineWidth",c,d),S=this.getStyle("lineDash",c,d),b=this.getStyle("color",c,d),_=a.getCamera().focalPoint,y=a.getCamera().viewPlaneNormal;let D=this._resolveViewPlaneCoordinate(g,y),T=this._resolveViewPlaneCoordinate(m,y);if(this._isCoordinateTuple(g)){const F=this._getIndexOfCoordinatesForViewplaneNormal(y);h.handles.points.forEach(z=>{z[F]=D}),h.startCoordinate=D}this._isCoordinateTuple(m)&&(h.endCoordinate=T);const P=is(D),x=is(T),M=this._getCoordinateForViewplaneNormal(_,y),L=is(M);if(L<Math.min(P,x)||L>Math.max(P,x))continue;const R=I.viewport?.volumeIds.values();for(const F of R)d.invalidated&&d.metadata.volumeId===F&&this._throttledCalculateCachedStats(d,I);let U=!1;if((L===P||L===x)&&(U=!0),!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),s;let W;if(!$e(u))continue;!ze(u)&&!this.editData&&v!==null&&U&&(W=[w[v]]),W&&xe(o,u,"0",W,{color:b});let K=S;if(U||(K=2),nc(o,u,"0",w[0],w[3],{color:b,lineDash:K,lineWidth:C}),s=!0,this.configuration.showTextBox){const F=this.configuration.getTextLines(h,{metadata:f});if(!F||F.length===0||!this.renderLinkedTextBoxAnnotation({enabledElement:e,svgDrawingHelper:o,annotation:d,styleSpecifier:c,textLines:F,canvasCoordinates:w}))continue}}return s},this.configuration.calculatePointsInsideVolume?this._throttledCalculateCachedStats=Un(this._calculateCachedStatsTool,this.configuration.throttleTimeout,{trailing:!0}):this._throttledCalculateCachedStats=Yr(this._calculateCachedStatsTool,this.configuration.throttleTimeout)}_isCoordinateTuple(t){return Array.isArray(t)||ArrayBuffer.isView(t)}_resolveViewPlaneCoordinate(t,n){return this._isCoordinateTuple(t)?this._getCoordinateForViewplaneNormal(t,n):t}_computeProjectionPoints(t,n){const{data:e,metadata:o}=t,{viewPlaneNormal:s,spacingInNormal:a}=o,{imageData:r}=n,c=this._resolveViewPlaneCoordinate(e.startCoordinate,s),l=this._resolveViewPlaneCoordinate(e.endCoordinate,s),{points:d}=e.handles,u=za(r,d[0]),h=za(r,d[0]),f=B();r.indexToWorldVec3(u,f);const g=B();r.indexToWorldVec3(h,g);const m=this._getIndexOfCoordinatesForViewplaneNormal(s);m==2?(f[2]=c,g[2]=l):m==0?(f[0]=c,g[0]=l):m==1&&(f[1]=c,g[1]=l);const p=B();Oe(p,g,f);const v=mn(p);Wt(p,p);const I=[];for(let w=0;w<v;w+=a)I.push(d.map(C=>{const S=B();return ee(S,C,p,w),Array.from(S)}));e.cachedStats.projectionPoints=I}_computePointsInsideVolume(t,n,e,o){const{data:s,metadata:a}=t,{viewPlaneNormal:r,viewUp:c}=a,{viewport:l}=o,d=s.cachedStats.projectionPoints,u=[[]],h=this.getTargetImageData(n),f=s.handles.points[0],g=s.handles.points[3],{worldWidth:m,worldHeight:p}=of(r,c,f,g),v=ao(h,s.habdles),I=Math.abs(m*p)/(v.scale*v.scale),w={isPreScaled:Ki(l,n),isSuvScaled:this.isSuvScaled(l,n,t.metadata.referencedImageId)},C=bi(a.Modality,t.metadata.referencedImageId,w);for(let b=0;b<d.length;b++){if(!e)continue;const _=d[b][0],{dimensions:y,imageData:D,voxelManager:T}=e,P=za(D,f),x=za(D,_),M=this._getIndexOfCoordinatesForViewplaneNormal(r);P[0]=Math.floor(P[0]),P[1]=Math.floor(P[1]),P[2]=Math.floor(P[2]),P[M]=x[M];const L=za(D,g);if(L[0]=Math.floor(L[0]),L[1]=Math.floor(L[1]),L[2]=Math.floor(L[2]),L[M]=x[M],this._isInsideVolume(P,L,y)){this.isHandleOutsideImage=!1;const R=Math.min(P[0],L[0]),U=Math.max(P[0],L[0]),W=Math.min(P[1],L[1]),K=Math.max(P[1],L[1]),j=Math.min(P[2],L[2]),F=Math.max(P[2],L[2]),z=[[R,U],[W,K],[j,F]],q=T.forEach(this.configuration.statsCalculator.statsCallback,{boundsIJK:z,imageData:D,returnPoints:this.configuration.storePointData});u.push(q)}}const S=this.configuration.statsCalculator.getStatistics();s.cachedStats.pointsInVolume=u,s.cachedStats.statistics={Modality:a.Modality,area:I,mean:S.mean?.value,stdDev:S.stdDev?.value,max:S.max?.value,statsArray:S.array,areaUnit:v.areaUnit,modalityUnit:C}}_calculateCachedStatsTool(t,n){const e=t.data,{viewport:o}=n,{cachedStats:s}=e,a=this.getTargetId(o),r=Q.getVolume(a.split(/volumeId:|\?/)[1]);return this._computeProjectionPoints(t,r),this._computePointsInsideVolume(t,a,r,n),t.invalidated=!1,zt(t,o.element),s}_getStartCoordinate(t,n){const e=t;return this._getCoordinateForViewplaneNormal(e,n)}_getEndCoordinate(t,n,e){const o=this.configuration.numSlicesToPropagate,s=B();return ee(s,t,e,o*n),this._getCoordinateForViewplaneNormal(s,e)}_getIndexOfCoordinatesForViewplaneNormal(t){const n=[Math.abs(t[0]),Math.abs(t[1]),Math.abs(t[2])];return n.indexOf(Math.max(...n))}_getCoordinateForViewplaneNormal(t,n){const e=this._getIndexOfCoordinatesForViewplaneNormal(n);return t[e]}}function J2(i,t={}){const n=i.cachedStats.statistics,{area:e,mean:o,max:s,stdDev:a,areaUnit:r,modalityUnit:c}=n;if(o===void 0)return;const l=[];return l.push(`Area: ${de(e)} ${r}`),l.push(`Mean: ${de(o)} ${c}`),l.push(`Max: ${de(s)} ${c}`),l.push(`Std Dev: ${de(a)} ${c}`),l}oE.toolName="RectangleROIStartEndThreshold";class iE extends hc{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{shadow:!0,preventHandleOutsideImage:!1}}){super(t,n),this.addNewAnnotation=e=>{const o=e.detail,{currentPoints:s,element:a}=o,r=s.world,c=N(a),{viewport:l,renderingEngine:d}=c;this.isDrawing=!0;const u=l.getCamera(),{viewPlaneNormal:h,viewUp:f}=u,g=this.getTargetId(l);let m,p;if(l instanceof Pn)m=g.split("imageId:")[1];else{p=Fi(g);const C=Q.getVolume(p);m=qr(C,r,h)}const v=l.getFrameOfReferenceUID(),I={highlighted:!0,invalidated:!0,metadata:{viewPlaneNormal:[...h],enabledElement:c,viewUp:[...f],FrameOfReferenceUID:v,referencedImageId:m,toolName:this.getToolName(),volumeId:p},data:{label:"",handles:{textBox:{hasMoved:!1,worldPosition:null,worldBoundingBox:null},points:[[...r],[...r],[...r],[...r]],activeHandleIndex:null},segmentationId:null}};Nt(I,a);const w=ft(a,this.getToolName());return this.editData={annotation:I,viewportIdsToRender:w,handleIndex:3,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),wt(a),e.preventDefault(),V(w),I},this.renderAnnotation=(e,o)=>{let s=!1;const{viewport:a}=e,{element:r}=a;let c=Yt(this.getToolName(),r);if(!c?.length||(c=this.filterInteractableAnnotationsForElement(r,c),!c?.length))return s;const l={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:e.viewport.id};for(let d=0;d<c.length;d++){const u=c[d],{annotationUID:h,data:f}=u,{points:g,activeHandleIndex:m}=f.handles,p=g.map(b=>a.worldToCanvas(b));l.annotationUID=h;const v=this.getStyle("lineWidth",l,u),I=this.getStyle("lineDash",l,u),w=this.getStyle("color",l,u);if(!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),s;zt(u,r);let C;if(!$e(h))continue;!ze(h)&&!this.editData&&m!==null&&(C=[p[m]]),C&&xe(o,h,"0",C,{color:w}),nc(o,h,"0",p[0],p[3],{color:w,lineDash:I,lineWidth:v}),s=!0}return s}}}iE.toolName="RectangleROIThreshold";function sE(i,t,n={}){const e=[];return i.forEach(s=>{const{data:a}=s,{points:r}=a.handles,{imageData:c,dimensions:l}=t;let d=r;if(a.cachedStats?.projectionPoints){const{projectionPoints:f}=a.cachedStats;d=[].concat(...f)}const u=d.map(f=>wn(c,f));let h=Ii(u,l);n.numSlicesToProject&&!a.cachedStats?.projectionPoints&&(h=Y1(h,n.numSlicesToProject)),e.push(h)}),e.length===1?e[0]:e.reduce((s,a)=>({iMin:Math.min(s.iMin,a.iMin),jMin:Math.min(s.jMin,a.jMin),kMin:Math.min(s.kMin,a.kMin),iMax:Math.max(s.iMax,a.iMax),jMax:Math.max(s.jMax,a.jMax),kMax:Math.max(s.kMax,a.kMax)}),{iMin:1/0,jMin:1/0,kMin:1/0,iMax:-1/0,jMax:-1/0,kMax:-1/0})}function Q2(i,t,n,e){const o=i.map(r=>Uo.getAnnotation(r));tR(o);let s;for(let r=0;r<n.length;r++)(n[r].volume.voxelManager.getScalarDataLength()===t.voxelManager.getScalarDataLength()||r===0)&&(s=sE(o,n[r].volume,e));const a=Q1(t,n,{...e,boundsIJK:s,segmentationId:e.segmentationId});return a.modified(),a}function tR(i){const t=[iE.toolName,oE.toolName];for(const n of i){const e=n.metadata.toolName;if(!t.includes(e))throw new Error("rectangleROIThresholdVolumeByRange only supports RectangleROIThreshold and RectangleROIStartEndThreshold annotations")}}function aE(i,t=1,n="mergedLabelmap"){i.forEach(({direction:l,dimensions:d,origin:u,spacing:h})=>{if(!ve(d,i[0].dimensions)||!ve(l,i[0].direction)||!ve(h,i[0].spacing)||!ve(u,i[0].origin))throw new Error("labelmaps must have the same size and shape")});const e=i[0],o=e.voxelManager.getConstructor(),s=new o(e.voxelManager.getScalarDataLength());i.forEach(l=>{const d=l.voxelManager,u=d.getScalarDataLength();for(let h=0;h<u;h++)d.getAtIndex(h)===t&&(s[h]=t)});const a={scalarData:s,metadata:e.metadata,spacing:e.spacing,origin:e.origin,direction:e.direction,dimensions:e.dimensions},r=Q.getVolume(n);let c;return r?(c=r,c.voxelManager.setCompleteScalarDataArray(s)):c=Cv(n,a),c}async function eR(i){const{viewportId:t,renderingEngineId:n,options:e}=i;let{segmentationId:o}=i;const s=ae(t,n);if(!s)throw new Error("element disabled");const{viewport:a}=s;if(!(a instanceof Xe))throw new Error("Segmentation only supports VolumeViewport");const{uid:r}=a.getDefaultActor();if(o===void 0&&(o=`${r}-based-segmentation-${e?.volumeId??Se().slice(0,8)}`),e){const c=Re(e);await Cv(o,c)}else{const c=a.getVolumeId();Xr(c,{volumeId:o})}return o}function $f(i,t,n={}){const e=n.onFlood,o=n.onBoundary,s=n.equals,a=n.filter,r=n.diagonals||!1,c=S(t),l=b(),d=[],u=[],h=new Set,f=n.bounds;for(d.push({currentArgs:t});d.length>0;)g(d.pop());return{flooded:u};function g(y){const D=y.currentArgs,T=y.previousArgs;m(D)||(p(D),v(D)?(I(D),C(D)):w(T))}function m(y){const[D,T,P=0]=y,x=D+32768+65536*(T+32768+65536*(P+32768));return h.has(x)}function p(y){const[D,T,P=0]=y,x=D+32768+65536*(T+32768+65536*(P+32768));h.add(x)}function v(y){const D=S(y);return s?s(D,c):D===c}function I(y){u.push(y),e&&e(...y)}function w(y){const[D,T,P=0]=y,x=D+32768+65536*(T+32768+65536*(P+32768));f?.set(x,y),o&&o(...y)}function C(y){for(let D=0;D<l.length;D+=1){const T=l[D],P=y.slice(0);for(let x=0;x<y.length;x+=1)P[x]+=T[x];a?.(P)!==!1&&(m(P)||d.push({currentArgs:P,previousArgs:y}))}}function S(y){return i(...y)}function b(){return _(t.length).filter(function(D){const T=nR(D);return T!==0&&(T===1||r)})}function _(y){const D=[],T=function(P){return P.split("").map(function(x){return parseInt(x,10)-1})};for(let P=0;P<Math.pow(3,y);P+=1){const x=oR(P.toString(3),"0",y);D.push(T(x))}return D}}function nR(i){let t=0;for(let n=0;n<i.length;n+=1)i[n]!==0&&(t+=1);return t}function oR(i,t,n){return(new Array(n+1).join(t)+i).slice(-n)}const iR={[dt.OnInteractionStart]:i=>{const{segmentIndex:t,labelValue:n,previewSegmentIndex:e,segmentationVoxelManager:o,centerIJK:s,viewPlaneNormal:a,segmentationImageData:r,configuration:c}=i;if(!c?.useCenterSegmentIndex){i.centerSegmentIndexInfo.segmentIndex=null,i.centerSegmentIndexInfo.hasSegmentIndex=!1,i.centerSegmentIndexInfo.hasPreviewIndex=!1;return}let l=!1,d=!1;const u=[...o.getBoundsIJK()];Math.abs(a[0])>.8?u[0]=[s[0],s[0]]:Math.abs(a[1])>.8?u[1]=[s[1],s[1]]:Math.abs(a[2])>.8&&(u[2]=[s[2],s[2]]);const h=({value:g})=>{l||=g===(n??t),d||=g===e};if(o.forEach(h,{imageData:r,isInObject:i.isInObject,boundsIJK:u}),!l&&!d){i.centerSegmentIndexInfo.segmentIndex=null;return}const f=o.getAtIJKPoint(s);i.centerSegmentIndexInfo.segmentIndex=f,i.centerSegmentIndexInfo.hasSegmentIndex=l,i.centerSegmentIndexInfo.hasPreviewIndex=d}},sR={[dt.Initialize]:i=>{const{operationName:t,centerIJK:n,segmentationVoxelManager:e,imageVoxelManager:o,configuration:s,segmentIndex:a,viewport:r}=i;if(!s?.threshold?.isDynamic||!n||!a||t===dt.RejectPreview||t===dt.OnInteractionEnd)return;const c=e.getBoundsIJK(),{range:l,dynamicRadius:d=0}=s.threshold,u=l?0:d,{viewPlaneNormal:h}=ht(r);if(!h)return;const f=c.map((v,I)=>{const[w,C]=v;return[Math.max(w,n[I]-u),Math.min(C,n[I]+u)]});Math.abs(h[0])>.8?f[0]=[n[0],n[0]]:Math.abs(h[1])>.8?f[1]=[n[1],n[1]]:Math.abs(h[2])>.8&&(f[2]=[n[2],n[2]]);const g=l||[1/0,-1/0],m=u*u,p=({value:v,pointIJK:I})=>{if(Fu(n,I)>m)return;const C=Array.isArray(v)?mr(v):v;g[0]=Math.min(C,g[0]),g[1]=Math.max(C,g[1])};o.forEach(p,{boundsIJK:f}),s.threshold.range=g},[dt.OnInteractionStart]:i=>{const{configuration:t}=i;t?.threshold?.isDynamic&&(t.threshold.range=null)},[dt.ComputeInnerCircleRadius]:i=>{const{configuration:t,viewport:n}=i,e=t?.threshold;if(!e)return;const{dynamicRadius:o=0,isDynamic:s}=e;if(!s){e.dynamicRadiusInCanvas=0;return}if(o===0)return;const a=n.getImageData();if(!a)return;const{spacing:r}=a,c=[n.element.clientWidth/2,n.element.clientHeight/2],l=o*r[0],u=n.canvasToWorld(c).map(g=>g+l),h=n.worldToCanvas(u),f=Math.abs(c[0]-h[0]);e.dynamicRadiusInCanvas||(e.dynamicRadiusInCanvas=0),e.dynamicRadiusInCanvas=3+f}},aR={[dt.Initialize]:i=>{i.segmentIndex=0}},{isEqual:hu}=oe,hp={toIJK:i=>i,fromIJK:i=>i,type:"acquistion"},rR={toIJK:([i,t,n])=>[n,i,t],fromIJK:([i,t,n])=>[t,n,i],type:"jk"},cR={toIJK:([i,t,n])=>[i,n,t],fromIJK:([i,t,n])=>[i,n,t],type:"ik"};function rE(i,t){if(!(i instanceof pn))return{...hp,boundsIJKPrime:t};const{viewPlaneNormal:n}=i.getCamera(),e=hu(Math.abs(n[0]),1)&&rR||hu(Math.abs(n[1]),1)&&cR||hu(Math.abs(n[2]),1)&&hp;return e?{...e,boundsIJKPrime:e.fromIJK(t)}:{toIJK:null,boundsIJKPrime:null,fromIJK:null,error:`Only mappings orthogonal to acquisition plane are permitted, but requested ${n}`}}const{RLEVoxelMap:lR,VoxelManager:dR}=oe,uR=65535;var sn;(function(i){i[i.SEGMENT=-1]="SEGMENT",i[i.ISLAND=-2]="ISLAND",i[i.INTERIOR=-3]="INTERIOR",i[i.EXTERIOR=-4]="EXTERIOR",i[i.INTERIOR_SMALL=-5]="INTERIOR_SMALL",i[i.INTERIOR_TEST=-6]="INTERIOR_TEST"})(sn||(sn={}));class zi{constructor(t){this.fillInternalEdge=!1,this.maxInternalRemove=128,this.maxInternalRemove=t?.maxInternalRemove??this.maxInternalRemove,this.fillInternalEdge=t?.fillInternalEdge??this.fillInternalEdge}initialize(t,n,e){const o=!!n.sourceVoxelManager,s=o?n.sourceVoxelManager:n,a=o?n:dR.createRLEHistoryVoxelManager(s),{segmentIndex:r=1,previewSegmentIndex:c=1}=e,l=e.points||s.getPoints();if(!l?.length)return;const d=s.getBoundsIJK().map((C,S)=>[Math.min(C[0],...l.map(b=>b[S])),Math.max(C[1],...l.map(b=>b[S]))]);if(d.find(C=>C[0]<0||C[1]>uR))return;const{toIJK:u,fromIJK:h,boundsIJKPrime:f,error:g}=rE(t,d);if(g){console.warn("Not performing island removal for planes not orthogonal to acquisition plane",g);return}const[m,p,v]=h(s.dimensions),I=new lR(m,p,v),w=(C,S,b)=>{const _=s.toIndex(u([C,S,b])),y=s.getAtIndex(_);if(y===c||y===r)return sn.SEGMENT};return I.fillFrom(w,f),I.normalizer={toIJK:u,fromIJK:h,boundsIJKPrime:f},this.segmentSet=I,this.previewVoxelManager=a,this.segmentIndex=r,this.previewSegmentIndex=c??r,this.selectedPoints=l,!0}floodFillSegmentIsland(){const{selectedPoints:t,segmentSet:n}=this;let e=0;const{fromIJK:o}=n.normalizer;return t.forEach(s=>{const a=o(s),r=n.toIndex(a),[c,l,d]=a;n.get(r)===sn.SEGMENT&&(e+=n.floodFill(c,l,d,sn.ISLAND))}),e}removeExternalIslands(){const{previewVoxelManager:t,segmentSet:n}=this,{toIJK:e}=n.normalizer,o=(s,a)=>{const[,r,c]=n.toIJK(s);if(a.value!==sn.ISLAND)for(let l=a.start;l<a.end;l++){const d=e([l,r,c]),u=t.getAtIJKPoint(d);t.setAtIJKPoint(d,u===void 0?0:null)}};n.forEach(o,{rowModified:!0})}removeInternalIslands(){const{segmentSet:t,previewVoxelManager:n,previewSegmentIndex:e}=this,{height:o,normalizer:s,width:a}=t,{toIJK:r}=s;return t.forEachRow((c,l)=>{let d;for(const u of[...l])if(u.value===sn.ISLAND){if(!d){if(this.fillInternalEdge&&u.start>0)for(let h=0;h<u.start;h++)t.set(c+h,sn.INTERIOR);d=u;continue}for(let h=d.end;h<u.start;h++)t.set(c+h,sn.INTERIOR);d=u}if(this.fillInternalEdge&&d?.end<a)for(let u=d.end;u<a;u++)t.set(c+u,sn.INTERIOR)}),t.forEach((c,l)=>{if(l.value!==sn.INTERIOR)return;const[,d,u]=t.toIJK(c),h=d>0?t.getRun(d-1,u):null,f=d+1<o?t.getRun(d+1,u):null,g=d===o-1,m=d===0,p=zi.covers(l,h)||m&&this.fillInternalEdge,v=zi.covers(l,f)||g&&this.fillInternalEdge;l.end-l.start>2&&(!p||!v)&&t.floodFill(l.start,d,u,sn.EXTERIOR,{singlePlane:!0})}),t.forEach((c,l)=>{if(l.value!==sn.INTERIOR)return;const[,d,u]=t.toIJK(c),g=t.floodFill(l.start,d,u,sn.INTERIOR_TEST)>this.maxInternalRemove?sn.EXTERIOR:sn.INTERIOR_SMALL;t.floodFill(l.start,d,u,g)}),t.forEach((c,l)=>{if(l.value===sn.INTERIOR_SMALL)for(let d=l.start;d<l.end;d++){const u=r(t.toIJK(c+d));n.setAtIJKPoint(u,e),this.onInternalPointFilled(u)}}),n.getArrayOfModifiedSlices()}onInternalPointFilled(t){}static covers(t,n){if(!n)return!1;let{start:e}=t;const{end:o}=t;for(const s of n)if(e>=s.start&&e<s.end&&(e=s.end,e>=o))return!0;return!1}}const hR={[dt.OnInteractionEnd]:i=>{const{previewSegmentIndex:t,segmentIndex:n,labelValue:e,viewport:o,segmentationVoxelManager:s,activeStrategy:a,memo:r}=i;if(a!=="THRESHOLD_INSIDE_SPHERE_WITH_ISLAND_REMOVAL"||n===null)return;const c=new zi,l=r?.voxelManager||s;if(!c.initialize(o,l,{previewSegmentIndex:t,segmentIndex:e??n}))return;c.floodFillSegmentIsland(),c.removeExternalIslands(),c.removeInternalIslands();const d=l.getArrayOfModifiedSlices();d&&He(i.segmentationId,d,t)}},fR={[dt.Preview]:function(i){const{previewSegmentIndex:t,configuration:n,enabledElement:e}=i;if(!t||!n)return;this.onInteractionStart?.(e,i);const o=this.fill(e,i);return o&&this.onInteractionEnd?.(e,i),o},[dt.Initialize]:i=>{const{segmentIndex:t,previewColor:n,previewSegmentIndex:e}=i;if(i.modified=!1,e==null||t==null)return;_s(i.segmentationId)?.forEach(s=>{Vw(s,i.segmentationId,e,n)}),i.modified=!0},[dt.AcceptPreview]:i=>{const{previewSegmentIndex:t,segmentationVoxelManager:n,memo:e,segmentIndex:o,labelValue:s,centerSegmentIndexInfo:a}=i||{},{changedIndices:r}=a||{},c=e,l=({index:d})=>{const u=n.getAtIndex(d);r?.length>0?r.includes(d)&&c.voxelManager.setAtIndex(d,0):u===t&&c.voxelManager.setAtIndex(d,s??o)};n.forEach(l),He(i.segmentationId,n.getArrayOfModifiedSlices(),o),i.centerSegmentIndexInfo.changedIndices=[]},[dt.RejectPreview]:i=>{i&&TC.undoIf(t=>{const n=t;if(!n?.voxelManager)return!1;const{segmentationVoxelManager:e}=n;let o=!1;const s=({value:a})=>{a===i.previewSegmentIndex&&(o=!0)};return e.forEach(s),o})}},gR={[dt.Fill]:i=>{const{segmentsLocked:t,segmentationImageData:n,segmentationVoxelManager:e,brushStrategy:o,centerIJK:s}=i,a=o.createIsInThreshold?.(i),{setValue:r}=o,c=a?l=>{const{value:d,index:u}=l;t.includes(d)||!a(u)||r(i,l)}:l=>r(i,l);e.forEach(c,{imageData:n,isInObject:i.isInObject,boundsIJK:i.isInObjectBoundsIJK}),e.addPoint(s)}};function mR({operationData:i,existingValue:t,index:n}){const{previewSegmentIndex:e,memo:o,centerSegmentIndexInfo:s,previewOnHover:a,segmentIndex:r,labelValue:c}=i,l=c??r,{hasPreviewIndex:d,hasSegmentIndex:u,segmentIndex:h}=s;if(h===0&&u&&d){if(t===l||a)return;if(t===e){o.voxelManager.setAtIndex(n,0);return}return}if(h===0&&u&&!d){if(t===0||t!==l)return;o.voxelManager.setAtIndex(n,e),s.changedIndices.push(n);return}if(h===0&&!u&&d){if(t===l||a)return;if(t===e){o.voxelManager.setAtIndex(n,0);return}return}if(h===0&&!u&&!d){if(t===l)return;if(t===e){o.voxelManager.setAtIndex(n,e);return}return}if(h===e&&u&&d){if(t===l)return;o.voxelManager.setAtIndex(n,e);return}if(h===e&&!u&&d){if(t===l)return;o.voxelManager.setAtIndex(n,e);return}if(h===l&&u&&d){if(t===l)return;o.voxelManager.setAtIndex(n,e);return}if(h===l&&u&&!d){if(t===l)return;o.voxelManager.setAtIndex(n,e);return}}const pR={[dt.INTERNAL_setValue]:(i,{value:t,index:n})=>{const{segmentsLocked:e,previewSegmentIndex:o,memo:s,segmentationVoxelManager:a,centerSegmentIndexInfo:r,segmentIndex:c,labelValue:l,labelmapId:d,segmentationId:u}=i,h=a.getAtIndex(n),f=Dt(u),g=f&&d?fa(f,d,h):h,m=o??l??c;if(!e.includes(g)&&!(!r&&h===(l??c))&&!(r?.segmentIndex!==0&&h===(l??c))){if(r?.segmentIndex===null){s.voxelManager.setAtIndex(n,m);return}if(!o){let p=l??c;r&&(p=r.segmentIndex),s.voxelManager.setAtIndex(n,p);return}mR({operationData:i,existingValue:h,index:n})}}},vR={[dt.CreateIsInThreshold]:i=>{const{imageVoxelManager:t,segmentIndex:n,configuration:e}=i;if(!(!e||!n))return o=>{const s=t.getAtIndex(o),a=Array.isArray(s)?mn(s):s,{threshold:r}=e||{};return r?.range?.length?r.range[0]<=a&&a<=r.range[1]:!0}}},fp=10;function bl(){return{maxIJKs:[]}}function cE(i,t){const{value:n}=t,{maxIJKs:e}=i,o=e.length;if(typeof n!="number"||o>=fp&&n<e[0].value)return;const s={value:t.value,pointLPS:t.pointLPS?[t.pointLPS[0],t.pointLPS[1],t.pointLPS[2]]:void 0,pointIJK:t.pointIJK?[t.pointIJK[0],t.pointIJK[1],t.pointIJK[2]]:void 0};if(!o||n>=e[o-1].value)e.push(s);else for(let a=0;a<o;a++)if(n<=e[a].value){e.splice(a,0,s);break}o>=fp&&e.splice(0,1)}function lE(i,t,n){const{spacing:e,calibration:o}=n,{volumeUnit:s}=ao({calibration:o,hasPixelSpacing:!0},[]),a=e?e[0]*e[1]*e[2]:1;return t.volume={value:Array.isArray(t.count.value)?t.count.value.map(r=>r*a):t.count.value*a,unit:s,name:"volume",label:"Volume"},t.maxIJKs=i.maxIJKs.filter(r=>r.pointIJK!==void 0),t.array.push(t.volume),i.maxIJKs=[],t}class sa extends bo{static statsInit(t){super.statsInit(t),this.volumetricState=bl()}static statsCallback(t){super.statsCallback(t),cE(this.volumetricState,t)}static getStatistics(t){const n={...t,unit:t?.unit||"none",calibration:t?.calibration,hasPixelSpacing:t?.hasPixelSpacing},e=super.getStatistics(n);return lE(this.volumetricState,e,n)}}sa.volumetricState=bl();class gp extends QI{constructor(t){super(t),this.volumetricState=bl()}statsInit(t){super.statsInit(t),this.volumetricState=bl()}statsCallback(t){super.statsCallback(t),cE(this.volumetricState,t)}getStatistics(t){const n={...t,unit:t?.unit||"none",calibration:t?.calibration,hasPixelSpacing:t?.hasPixelSpacing},e=super.getStatistics(n);return lE(this.volumetricState,e,n)}}const IR=Math.pow(3*1e3/(4*Math.PI),1/3);async function dE({segmentationId:i,segmentIndices:t,mode:n="collective"}){md(),Zo(no.COMPUTE_STATISTICS,0);const e=Lw(i,t);if(!e)return;const{operationData:o,segVolumeId:s,segImageIds:a,reconstructableVolume:r,indices:c}=e,{refImageId:l,modalityUnitOptions:d}=QM(s,a),u=Hw(l,d);return r?await wR({operationData:o,indices:c,unit:u,mode:n}):await ER({segImageIds:a,indices:c,unit:u,mode:n})}async function wR({operationData:i,indices:t,unit:n,mode:e}){const o=Ow(i);if(!o)return;const{segmentationVoxelManager:s,imageVoxelManager:a,segmentationImageData:r,imageData:c}=o;if(!s||!r)return;const l=r.getSpacing(),{boundsIJK:d}=s;if(!d)return sa.getStatistics({spacing:l});const h={scalarData:s.getCompleteScalarDataArray(),dimensions:r.getDimensions(),spacing:r.getSpacing(),origin:r.getOrigin(),direction:r.getDirection()},f={scalarData:a.getCompleteScalarDataArray(),dimensions:c.getDimensions(),spacing:c.getSpacing(),origin:c.getOrigin(),direction:c.getDirection()};if(!f.scalarData?.length)return;const g=await Es().executeTask("compute","calculateSegmentsStatisticsVolume",{segmentationInfo:h,imageInfo:f,indices:t,unit:n,mode:e});if(Zo(no.COMPUTE_STATISTICS,100),e==="collective")return _l({stats:g,unit:n,spacing:l,segmentationImageData:r,imageVoxelManager:a});{const m={};return Object.entries(g).forEach(([p,v])=>{m[p]=_l({stats:v,unit:n,spacing:l,segmentationImageData:r,imageVoxelManager:a})}),m}}const fu=(i,t)=>{if(!i.array)return;const n=i.array.findIndex(e=>e.name===t.name);n!==-1?i.array[n]=t:i.array.push(t)},_l=({stats:i,unit:t,spacing:n,segmentationImageData:e,imageVoxelManager:o})=>{if(i.mean.unit=t,i.max.unit=t,i.min.unit=t,t!=="SUV")return i;const s=n.map(a=>Math.max(1,Math.round(1.1*IR/a)));for(const a of i.maxIJKs){const r=SR(a,s,e,o,n);if(!r)continue;const{mean:c}=r;(!i.peakValue||i.peakValue.value<=c.value)&&(i.peakValue={name:"peakValue",label:"Peak Value",value:c.value,unit:t},i.peakPoint={name:"peakLPS",label:"Peak SUV Point",value:a.pointLPS?[...a.pointLPS]:null,unit:null},fu(i,i.peakValue),fu(i,i.peakPoint))}if(i.volume&&i.mean){const a=i.volume.value,r=i.mean.value;i.lesionGlycolysis={name:"lesionGlycolysis",label:"Lesion Glycolysis",value:a*r,unit:`${i.volume.unit}·${t}`},fu(i,i.lesionGlycolysis)}return i};async function ER({segImageIds:i,indices:t,unit:n,mode:e}){Zo(no.COMPUTE_STATISTICS,0);const{segmentationInfo:o,imageInfo:s}=Rw(i),a=await Es().executeTask("compute","calculateSegmentsStatisticsStack",{segmentationInfo:o,imageInfo:s,indices:t,mode:e});Zo(no.COMPUTE_STATISTICS,100);const r=o[0].spacing,c=o[0],l=s[0].voxelManager;if(e==="collective")return _l({stats:a,unit:n,spacing:r,segmentationImageData:c,imageVoxelManager:l});{const d={};return Object.entries(a).forEach(([u,h])=>{d[u]=_l({stats:h,unit:n,spacing:r,segmentationImageData:c,imageVoxelManager:l})}),d}}function SR(i,t,n,e,o){const{pointIJK:s,pointLPS:a}=i;if(!s)return;const r=s.map((d,u)=>[d-t[u],d+t[u]]),c=(d,u)=>{const h=(u[0]-s[0])/t[0],f=(u[1]-s[1])/t[1],g=(u[2]-s[2])/t[2];return h*h+f*f+g*g<=1},l=({pointIJK:d,pointLPS:u})=>{const h=e.getAtIJKPoint(d);h!==void 0&&sa.statsCallback({value:h,pointLPS:u,pointIJK:d})};return sa.statsInit({storePointData:!1}),MC(n,{pointInShapeFn:c,callback:l,boundsIJK:r}),sa.getStatistics({spacing:o})}const CR={[dt.GetStatistics]:function(i,t,n){const{indices:e}=n,{segmentationId:o,viewport:s}=t;dE({segmentationId:o,segmentIndices:e})}},bR={[dt.CalculateCursorGeometry]:function(i,t){if(!t)return;const{configuration:n,activeStrategy:e,hoverData:o}=t,{viewport:s}=i,a=ht(s),{brushSize:r}=n;if(!a.viewUp||!a.viewPlaneNormal)return;const c=Ot(a.viewUp[0],a.viewUp[1],a.viewUp[2]),l=Ot(a.viewPlaneNormal[0],a.viewPlaneNormal[1],a.viewPlaneNormal[2]),d=B();Me(d,c,l);const{canvasToWorld:u}=s,{centerCanvas:h}=o,f=u([h[0],h[1]]),g=B(),m=B(),p=B(),v=B();for(let S=0;S<=2;S++)g[S]=f[S]-c[S]*r,m[S]=f[S]+c[S]*r,p[S]=f[S]-d[S]*r,v[S]=f[S]+d[S]*r;if(!o)return;const{brushCursor:I}=o,{data:w}=I;w.handles===void 0&&(w.handles={}),w.handles.points=[g,m,p,v],w.editPoints=[...w.handles.points];const C=n.strategies[e];typeof C?.computeInnerCircleRadius=="function"&&C.computeInnerCircleRadius({configuration:n,viewport:s}),w.invalidated=!1},[dt.RenderCursor]:function(i,t,n){if(!t)return;const{configuration:e,hoverData:o}=t,{viewport:s}=i,{brushCursor:a}=o,r=a.metadata;if(!r)return;const c=r.brushCursorUID||"brushCursor",l=a.data,d=`rgb(${r.segmentColor?.slice(0,3)||[0,0,0]})`;if(!s.getRenderingEngine()){console.warn("Rendering Engine has been destroyed");return}const u=l.handles?.points||[];Math.floor((u?.length||0)/4);const h=[];for(let m=0;m<u.length;m+=4){const p=u.slice(m,m+4);if(p.length<2)continue;const v=p.map(b=>s.worldToCanvas(b)),I=v[0],w=v[1],C=[Math.floor((I[0]+w[0])/2),Math.floor((I[1]+w[1])/2)],S=Math.round(Math.abs(I[1]-C[1]));h.push({center:C,radius:S})}const f=h[h.length-1];h.length>1&&ko(n,c,"stroke-preview",h.map(m=>m.center),{color:d,lineWidth:f.radius*2,strokeOpacity:.35,lineCap:"round",lineJoin:"round",lineDash:this.centerSegmentIndexInfo.segmentIndex===0?"6,4":void 0}),f&&En(n,c,"current-circle",f.center,f.radius,{color:d,lineWidth:2,strokeOpacity:1,lineDash:this.centerSegmentIndexInfo.segmentIndex===0?[1,2]:null},"brush-cursor");const{dynamicRadiusInCanvas:g}=e?.threshold||{dynamicRadiusInCanvas:0};g&&f&&En(n,c,"dynamic-radius",f.center,g,{color:d},"brush-cursor")}},Qt={determineSegmentIndex:iR,dynamicThreshold:sR,erase:aR,islandRemoval:hR,preview:fR,regionFill:gR,setValue:pR,threshold:vR,labelmapStatistics:CR,ensureSegmentationVolumeFor3DManipulation:Mw,ensureImageVolumeFor3DManipulation:Aw,circularCursor:bR},{VoxelManager:rh,RLEVoxelMap:_R}=oe;function Ar(i,t){return fE(i,t)}function uE(i){return{undo:()=>i.restoreMemo(!0),redo:()=>i.restoreMemo(!1)}}function hE(i){const t=i!==!1,n=this.priorSteps??[],e=this.postSteps??[],o=()=>{const{segmentationVoxelManager:s,undoVoxelManager:a,redoVoxelManager:r}=this,c=t?a:r;if(!c)return;c.forEach(({value:d,pointIJK:u})=>{s.setAtIJKPoint(u,d)});const l=c.getArrayOfModifiedSlices();He(this.segmentationId,l)};if(t){for(let s=e.length-1;s>=0;s--)e[s].undo();o();for(let s=n.length-1;s>=0;s--)n[s].undo()}else{for(const s of n)s.redo();o();for(const s of e)s.redo()}}function fE(i,t){const n=rh.createRLEHistoryVoxelManager(t);return{segmentationId:i,restoreMemo:hE,commitMemo:yR,segmentationVoxelManager:t,voxelManager:n,id:Se(),operationType:"labelmap"}}function yR(){if(this.redoVoxelManager)return!0;const i=!!(this.priorSteps?.length||this.postSteps?.length);if(!this.voxelManager.modifiedSlices.size)return i;const{segmentationVoxelManager:t}=this,n=rh.createRLEHistoryVoxelManager(t);_R.copyMap(n.map,this.voxelManager.map);for(const o of this.voxelManager.modifiedSlices.keys())n.modifiedSlices.add(o);this.undoVoxelManager=n;const e=rh.createRLEVolumeVoxelManager({dimensions:this.segmentationVoxelManager.dimensions});return this.redoVoxelManager=e,n.forEach(({index:o,pointIJK:s,value:a})=>{const r=t.getAtIJKPoint(s);r!==a&&e.setAtIndex(o,r)}),!0}const xR=Object.freeze(Object.defineProperty({__proto__:null,createLabelmapMemo:Ar,createRleMemo:fE,memoAsStep:uE,restoreMemo:hE},Symbol.toStringTag,{value:"Module"}));function PR(i){const t=Dt(i.segmentationId);if(!t)return[];const{memo:n}=i;return Zy(t,i.labelmapEditTransaction,{viewport:i.viewport,referenceImageData:i.segmentationImageData,isInObject:i.isInObject,isInObjectBoundsIJK:i.isInObjectBoundsIJK,imageId:i.imageId,crossLayerEraseCallback:n?({voxelManager:e,labelValue:o,indices:s})=>{(n.postSteps||=[]).push({undo:()=>{for(const a of s)e.setAtIndex(a,o);He(i.segmentationId)},redo:()=>{for(const a of s)e.setAtIndex(a,0);He(i.segmentationId)}})}:void 0})}function DR(i){const{segmentationId:t,segmentIndex:n,segmentsLocked:e,viewport:o}=i,s=Dt(t);if(!s||n===0)return[];const a=Pf().segmentation?.overwriteMode??"all";if(a==="none")return[];const r=Object.keys(s.segments).map(Number).filter(l=>l!==n&&!e.includes(l));if(a==="all")return r;const c=Zl(o.id,{segmentationId:t,type:St.Labelmap});return c?.visible?r.filter(l=>c.segments[l]?.visible!==!1):[]}function TR(i){const t=Dt(i.segmentationId);if(!t)return;i.overwriteSegmentIndices=DR(i);const n=$y(t,{segmentIndex:i.segmentIndex,overwriteSegmentIndices:i.overwriteSegmentIndices,segmentationVoxelManager:i.segmentationVoxelManager,segmentationImageData:i.segmentationImageData,isInObject:i.isInObject,isInObjectBoundsIJK:i.isInObjectBoundsIJK});if(i.labelmapEditTransaction=n,i.labelValue=n.labelValue,i.labelmapId=n.labelmapId,i.crossLayerEraseBindings=n.crossLayerEraseBindings,n.movedSegment&&n.activeLayer){const e=$I(n.activeLayer,{viewport:i.viewport,imageId:i.imageId,sourceLayer:n.sourceLayer});e.imageId&&(i.imageId=e.imageId),e.imageData&&(i.segmentationImageData=e.imageData),e.voxelManager&&(i.segmentationVoxelManager=e.voxelManager)}}const MR=new Set([We.CPU_IMAGE,We.CPU_VOLUME]);function AR(i){try{return i.getDefaultActor?.()}catch{return}}function LR(i){if(!i)return Eg();const t=i;if(t.useCPURendering===!0||t._cpuFallbackEnabledElement)return!0;const n=AR(i),e=n?.actorMapper?.renderMode;return e&&MR.has(e)||(typeof n?.actor?.getClassName=="function"?n.actor.getClassName():void 0)==="CanvasActor"?!0:Eg()}function gE(i){return Pf().segmentation?.overwriteMode!==void 0||LR(i)}class Bn{constructor(t,...n){this._initialize=[],this._fill=[],this._onInteractionStart=[],this.fill=(s,a)=>{const r=this.initialize(s,a,dt.Fill);if(!r)return;const l=!gE(r.viewport)||!r.previewOnHover,d=r.segmentationVoxelManager,u=r.segmentationImageData;if(l&&TR(r),r.memo?.segmentationVoxelManager!==r.segmentationVoxelManager){const v=r.memo;r.memo=r.createMemo(r.segmentationId,r.segmentationVoxelManager),v&&v!==r.memo&&v.commitMemo?.()&&(r.memo.priorSteps||=[]).push(uE(v))}const h=r.labelmapEditTransaction?.moveStep;if(h&&r.memo){const{segmentationId:v}=r;(r.memo.priorSteps||=[]).push({undo:()=>{h.undo(),He(v)},redo:()=>{h.redo(),He(v)}})}(r.segmentationVoxelManager!==d||r.segmentationImageData!==u)&&this._initialize.forEach(v=>v(r)),this._fill.forEach(v=>v(r));const{segmentationVoxelManager:f,segmentIndex:g}=r,m=PR(r),p=new Set([...f.getArrayOfModifiedSlices()??[],...m]);return He(r.segmentationId,Array.from(p),g),r},this.onInteractionStart=(s,a)=>{const r=this.initialize(s,a);r&&this._onInteractionStart.forEach(c=>c.call(this,r))},this.addPreview=(s,a)=>{const r=this.initialize(s,a,dt.AddPreview);if(r)return r},this.configurationName=t;const e=n.find(s=>s.hasOwnProperty(dt.CalculateCursorGeometry)),o=n.find(s=>s.hasOwnProperty(dt.RenderCursor));e||n.push({[dt.CalculateCursorGeometry]:Qt.circularCursor.calculateCursorGeometry}),o||n.push({[dt.RenderCursor]:Qt.circularCursor.renderCursor}),this.compositions=n,n.forEach(s=>{const a=typeof s=="function"?s():s;if(a)for(const r in a){if(!Bn.childFunctions[r])throw new Error(`Didn't find ${r} as a brush strategy`);Bn.childFunctions[r](this,a[r])}}),this.strategyFunction=(s,a)=>this.fill(s,a);for(const s of Object.keys(Bn.childFunctions))this.strategyFunction[s]=this[s]}initialize(t,n,e){const{viewport:o}=t,s=Of({operationData:n,viewport:o,strategy:this});if(!s||!s.imageVoxelManager||!s.segmentationVoxelManager||!s.segmentationImageData)return null;const{imageVoxelManager:a,segmentationVoxelManager:r,segmentationImageData:c}=s,l=n.createMemo(n.segmentationId,r),d={operationName:e,...n,segmentIndex:n.segmentIndex,enabledElement:t,imageVoxelManager:a,segmentationVoxelManager:r,segmentationImageData:c,viewport:o,centerWorld:null,isInObject:null,isInObjectBoundsIJK:null,brushStrategy:this,memo:l};return this._initialize.forEach(u=>u(d)),d}}Bn.COMPOSITIONS=Qt;Bn.childFunctions={[dt.OnInteractionStart]:xo(dt.OnInteractionStart,dt.Initialize),[dt.OnInteractionEnd]:xo(dt.OnInteractionEnd,dt.Initialize),[dt.Fill]:xo(dt.Fill),[dt.Initialize]:xo(dt.Initialize),[dt.CreateIsInThreshold]:Vs(dt.CreateIsInThreshold),[dt.Interpolate]:xo(dt.Interpolate,dt.Initialize),[dt.AcceptPreview]:xo(dt.AcceptPreview,dt.Initialize),[dt.RejectPreview]:xo(dt.RejectPreview,dt.Initialize),[dt.INTERNAL_setValue]:Vs(dt.INTERNAL_setValue),[dt.Preview]:Vs(dt.Preview,!1),[dt.ComputeInnerCircleRadius]:xo(dt.ComputeInnerCircleRadius),[dt.EnsureSegmentationVolumeFor3DManipulation]:xo(dt.EnsureSegmentationVolumeFor3DManipulation),[dt.EnsureImageVolumeFor3DManipulation]:xo(dt.EnsureImageVolumeFor3DManipulation),[dt.AddPreview]:xo(dt.AddPreview),[dt.GetStatistics]:Vs(dt.GetStatistics),[dt.CalculateCursorGeometry]:Vs(dt.CalculateCursorGeometry,!0),[dt.RenderCursor]:Vs(dt.RenderCursor,!0),compositions:null};function xo(i,t){const n=`_${i}`;return(e,o)=>{e[n]||=[],e[n].push(o),e[i]||=t?(s,a,...r)=>{const c=e[t](s,a,i);let l;return e[n].forEach(d=>{const u=d.call(e,c,...r);l||=u}),l}:(s,...a)=>{e[n].forEach(r=>r.call(e,s,...a))}}}function Vs(i,t=!0){return(n,e)=>{if(n[i])throw new Error(`The singleton method ${i} already exists`);n[i]=t?e:(o,s,...a)=>(s.enabledElement=o,e.call(n,s,...a))}}function mE(i,t){const{center:n,radius:e}=i,o=i.radius2||e*e;return(t[0]-n[0])*(t[0]-n[0])+(t[1]-n[1])*(t[1]-n[1])+(t[2]-n[2])*(t[2]-n[2])<=o}const{transformWorldToIndex:mp,transformIndexToWorld:pp,isEqual:OR,getNormalizedAspectRatio:RR}=oe;function pE(i){const[t,n,e,o]=i,s=[e[0],n[1]],a=[o[0],t[1]],r=[e[0],t[1]],c=[o[0],n[1]];return[s,a,r,c]}function NR(i,t,n,e,o){const s=Ot(i[0],i[1],i[2]),a=B();ee(a,s,t,e);const r=B();ee(r,s,t,-e);const c=B();ee(c,s,n,o);const l=B();return ee(l,s,n,-o),[r,a,l,c]}function kR(i,t,n){if(!i.length||t<=0||n<=0)return null;const e=t*t,o=n*n,s=i.map(r=>[r[0],r[1],r[2]]),a=[];for(let r=1;r<s.length;r++){const c=s[r-1],l=s[r],d=l[0]-c[0],u=l[1]-c[1],h=l[2]-c[2],f=d*d+u*u+h*h;a.push({start:c,vector:[d,u,h],lengthSquared:f})}return r=>{if(!r)return!1;for(const c of s){const l=r[0]-c[0],d=r[1]-c[1],u=r[2]-c[2];if(l*l/e+d*d/o+u*u<=1)return!0}for(const{start:c,vector:l,lengthSquared:d}of a){if(d===0){const b=r[0]-c[0],_=r[1]-c[1],y=r[2]-c[2];if(b*b/e+_*_/o+y*y<=1)return!0;continue}const u=r[0]-c[0],h=r[1]-c[1],f=r[2]-c[2],g=u*l[0]+h*l[1]+f*l[2],m=Math.max(0,Math.min(1,g/d)),p=c[0]+l[0]*m,v=c[1]+l[1]*m,I=c[2]+l[2]*m,w=r[0]-p,C=r[1]-v,S=r[2]-I;if(w*w/e+C*C/o+S*S<=1)return!0}return!1}}const vE={[dt.Initialize]:i=>{const{points:t,viewport:n,segmentationImageData:e,viewUp:o,viewPlaneNormal:s}=i;if(!t)return;const a=B();t.length>=2?(yn(a,t[0],t[1]),bn(a,a,.5)):Ov(a,t[0]),i.centerWorld=a,i.centerIJK=mp(e,a);const r=RR(n.getAspectRatio()),c=t.length>=2?ke(t[0],t[1])/2/r[1]:0,l=t.length>=2?ke(t[2],t[3])/2/r[0]:0,d=t.map(S=>n.worldToCanvas(S)),h=pE(d).map(S=>n.canvasToWorld(S)),f=Ot(o[0],o[1],o[2]);Wt(f,f);const g=Ot(s[0],s[1],s[2]);Wt(g,g);const m=B();Me(m,f,g),Wt(m,m);const v=(i.strokePointsWorld&&i.strokePointsWorld.length>0?i.strokePointsWorld:[i.centerWorld]).map(S=>ho(S)),w=v.flatMap(S=>NR(S,f,m,c,l)).map(S=>mp(e,S)),C=Ii(w,e.getDimensions());i.strokePointsWorld=v,i.isInObject=IE(h,{strokePointsWorld:v,segmentationImageData:e,xRadius:l,yRadius:c,aspectRatio:r}),i.isInObjectBoundsIJK=C}};function IE(i=[],t={}){if(!i||i.length!==4)throw new Error("createPointInEllipse: cornersInWorld must have 4 points");const[n,e,o,s]=i,a=t.aspectRatio||[1,1],r=B();yn(r,n,e),bn(r,r,.5);const c=B();Oe(c,s,n);const l=mn(c)/2;Wt(c,c);const d=B();Oe(d,o,n),Wt(d,d);const u=l/a[0],h=l/a[1],f=t.xRadius??u,g=t.yRadius??h,m=kR(t.strokePointsWorld||[],f,g);if(OR(u,h)){const p=u,v={center:r,radius:p,radius2:p*p};return(I,w)=>{let C=I;return!C&&w&&t.segmentationImageData&&(C=pp(t.segmentationImageData,w)),C?m?.(C)?!0:mE(v,C):!1}}return(p,v)=>{let I=p;if(!I&&v&&t.segmentationImageData&&(I=pp(t.segmentationImageData,v)),!I)return!1;if(m?.(I))return!0;const w=B();Oe(w,I,r);const C=xt(w,c),S=xt(w,d);return C*C/(u*u)+S*S/(h*h)<=1}}const wE=new Bn("Circle",Qt.regionFill,Qt.setValue,vE,Qt.determineSegmentIndex,Qt.preview,Qt.labelmapStatistics),UR=new Bn("CircleThreshold",Qt.regionFill,Qt.setValue,vE,Qt.determineSegmentIndex,Qt.dynamicThreshold,Qt.threshold,Qt.preview,Qt.islandRemoval,Qt.labelmapStatistics),_d=wE.strategyFunction,VR=UR.strategyFunction;function FR(){throw new Error("Not yet implemented")}const{transformWorldToIndex:vp,getNormalizedAspectRatio:GR}=oe,HR={[dt.Initialize]:i=>{const{points:t,viewport:n,segmentationImageData:e}=i;if(!t)return;const o=B();t.length>=2?(yn(o,t[0],t[1]),bn(o,o,.5)):Ov(o,t[0]),i.centerWorld=o,i.centerIJK=vp(e,o);const s=j2(t.slice(0,2),e,n),a=t.map(v=>n.worldToCanvas(v)),c=pE(a).map(v=>n.canvasToWorld(v)),l=GR(n.getAspectRatio()),d=t.length>=2?ke(t[0],t[1])/2/l[1]:0,u=t.length>=2?ke(t[2],t[3])/2/l[0]:0,h=i.strokePointsWorld&&i.strokePointsWorld.length>0?i.strokePointsWorld:[i.centerWorld],f=s.boundsIJK,g=i.centerIJK,p=h.reduce((v,I)=>{if(!I)return v;const w=vp(e,I),C=[w[0]-g[0],w[1]-g[1],w[2]-g[2]],S=[[f[0][0]+C[0],f[0][1]+C[0]],[f[1][0]+C[1],f[1][1]+C[1]],[f[2][0]+C[2],f[2][1]+C[2]]];return v?[[Math.min(v[0][0],S[0][0]),Math.max(v[0][1],S[0][1])],[Math.min(v[1][0],S[1][0]),Math.max(v[1][1],S[1][1])],[Math.min(v[2][0],S[2][0]),Math.max(v[2][1],S[2][1])]]:S},null)??s.boundsIJK;if(e){const v=e.getDimensions();i.isInObjectBoundsIJK=[[Math.max(0,Math.min(p[0][0],v[0]-1)),Math.max(0,Math.min(p[0][1],v[0]-1))],[Math.max(0,Math.min(p[1][0],v[1]-1)),Math.max(0,Math.min(p[1][1],v[1]-1))],[Math.max(0,Math.min(p[2][0],v[2]-1)),Math.max(0,Math.min(p[2][1],v[2]-1))]]}else i.isInObjectBoundsIJK=p;i.isInObject=IE(c,{strokePointsWorld:i.strokePointsWorld,segmentationImageData:e,xRadius:u,yRadius:d,aspectRatio:l})}},yd=new Bn("Sphere",Qt.regionFill,Qt.setValue,HR,Qt.determineSegmentIndex,Qt.preview,Qt.labelmapStatistics,Qt.ensureSegmentationVolumeFor3DManipulation),EE=yd.strategyFunction,WR=new Bn("SphereThreshold",...yd.compositions,Qt.dynamicThreshold,Qt.threshold,Qt.ensureSegmentationVolumeFor3DManipulation,Qt.ensureImageVolumeFor3DManipulation),BR=new Bn("SphereThreshold",...yd.compositions,Qt.dynamicThreshold,Qt.threshold,Qt.islandRemoval,Qt.ensureSegmentationVolumeFor3DManipulation,Qt.ensureImageVolumeFor3DManipulation),zR=WR.strategyFunction,$R=BR.strategyFunction,jR=new Bn("EraseSphere",Qt.erase,...yd.compositions),SE=jR.strategyFunction,XR=new Bn("EraseCircle",Qt.erase,...wE.compositions),CE=XR.strategyFunction,{transformWorldToIndex:bE}=oe,_E={[dt.Initialize]:i=>{const{points:t,viewport:n,segmentationImageData:e}=i;if(!t)return;const o=Ot(0,0,0);t.forEach(r=>{yn(o,o,r)}),bn(o,o,1/t.length),i.centerWorld=o,i.centerIJK=bE(e,o);const{boundsIJK:s,pointInShapeFn:a}=qR(n,t,e);i.isInObject=a,i.isInObjectBoundsIJK=s}};function qR(i,t,n){let e=t.map(w=>bE(n,w));e=e.map(w=>w.map(C=>Math.round(C)));const o=Ii(e,n.getDimensions()),[s,a,r,c]=t,l=B(),d=B();Oe(l,a,s),Oe(d,c,s);const u=mn(l),h=mn(d);Wt(l,l),Wt(d,d);const f=B();Me(f,l,d),Wt(f,f);const g=n.getDirection(),m=n.getSpacing(),{viewPlaneNormal:p}=ht(i),v=Dh({direction:g,spacing:m},p);return{boundsIJK:o,pointInShapeFn:w=>{const C=B();Oe(C,w,s);const S=xt(C,l),b=xt(C,d),_=Math.abs(xt(C,f));return S>=-v&&S<=u+v&&b>=-v&&b<=h+v&&_<=v}}}const YR=new Bn("Rectangle",Qt.regionFill,Qt.setValue,_E,Qt.determineSegmentIndex,Qt.preview,Qt.labelmapStatistics),KR=new Bn("RectangleThreshold",Qt.regionFill,Qt.setValue,_E,Qt.determineSegmentIndex,Qt.dynamicThreshold,Qt.threshold,Qt.preview,Qt.islandRemoval,Qt.labelmapStatistics),jf=YR.strategyFunction,ZR=KR.strategyFunction,JR=Object.freeze(Object.defineProperty({__proto__:null,fillInsideCircle:_d,fillInsideRectangle:jf,fillOutsideCircle:FR,thresholdInsideRectangle:ZR},Symbol.toStringTag,{value:"Module"}));class $i extends Ee{constructor(t,n){super(t,n),this.memoMap=new Map,this.acceptedMemoIds=new Map,this.centerSegmentIndexInfo={segmentIndex:null,hasSegmentIndex:!1,hasPreviewIndex:!1,changedIndices:[]}}_cancelTouchDraw(t){if(!this.isDrawing)return;const n=this.editData?.viewportIdsToRender;this._deactivateDraw(t),Ft(t),this.editData=null,this.isDrawing=!1,n&&V(n)}_historyRedoHandler(t){const{id:n,operationType:e}=t.detail;if(e==="labelmap"){if(this.acceptedMemoIds.has(n)){this._hoverData=null;const o=this.acceptedMemoIds.get(n),s=o?.element,a=this.getOperationData(s);if(!a)return;a.segmentIndex=o?.segmentIndex,s&&this.applyActiveStrategyCallback(N(s),a,dt.AcceptPreview)}this._previewData.isDrag=!0}}get _previewData(){return $i.previewData}hasPreviewData(){return!!this._previewData.preview}shouldResolvePreviewRequests(){return(this.mode==="Active"||this.mode==="Enabled")&&this.hasPreviewData()}createMemo(t,n){const e=n.id;if(this.memo&&this.memo.segmentationVoxelManager===n)return this.memo;let o=this.memoMap.get(e);return o?o.redoVoxelManager&&(o=Ar(t,n),this.memoMap.set(e,o)):(o=Ar(t,n),this.memoMap.set(e,o)),this.memo=o,o}createEditData(t){const n=N(t),{viewport:e}=n,o=Wi(e.id);if(!o)return null;const{segmentationId:s}=o,a=xs(s),{representationData:r}=Dt(s);return this.getEditData({viewport:e,representationData:r,segmentsLocked:a,segmentationId:s})}getEditData({viewport:t,representationData:n,segmentsLocked:e,segmentationId:o}){const s=zn(t),a=xn(o),r=Dt(o),c=a?Kl(r,a):void 0;if(s==="volume"||t instanceof pn){const d=c?$n(c):void 0,u=c?.volumeId??d?.volumeId;if(!d||!u)return;const f=t.getActors().filter(m=>m.referencedId).map(m=>Q.getVolume(m.referencedId)).filter(m=>!!m),g=f.find(m=>ve(m.dimensions,d.dimensions))?.volumeId||f[0]?.volumeId;return{volumeId:u,referencedVolumeId:this.configuration.threshold?.volumeId??c?.referencedVolumeId??d.referencedVolumeId??g,segmentsLocked:e}}if(s==="image"){const d=Zi(t.id,o);return d?{imageId:d,segmentsLocked:e}:void 0}const l=new CustomEvent(yt.ERROR_EVENT,{detail:{type:"Segmentation",message:"Cannot perform brush operation on the selected viewport"},cancelable:!0});return Z.dispatchEvent(l),null}createHoverData(t,n){const e=N(t),{viewport:o}=e,s=ht(o),{viewPlaneNormal:a,viewUp:r}=s;if(!a||!r)return;const c=[o.id],l=this.getActiveSegmentationData(o);if(!l)return;const{segmentIndex:d,segmentationId:u,segmentColor:h}=l;return{brushCursor:{metadata:{viewPlaneNormal:[...a],viewUp:[...r],FrameOfReferenceUID:o.getFrameOfReferenceUID(),referencedImageId:"",toolName:this.getToolName(),segmentColor:h},data:{}},centerCanvas:n,segmentIndex:d,viewport:o,segmentationId:u,segmentColor:h,viewportIdsToRender:c}}getActiveSegmentationData(t){const n=t.id,e=Wi(n);if(!e)return;const{segmentationId:o}=e,s=xn(o);if(!s)return;const a=Jo(n,o,s);return{segmentIndex:s,segmentationId:o,segmentColor:a}}getOperationData(t){const n=this._editData||this.createEditData(t),e=this._hoverData||this.createHoverData(t);if(!n||!e)return;const{segmentIndex:o,segmentationId:s,brushCursor:a}=e,{data:r,metadata:c={}}=a||{},{viewPlaneNormal:l,viewUp:d}=c,u=r?.editPoints||r?.handles?.points,h=this.configuration.preview?.previewColors?.[o],{viewport:f}=N(t)||{};if(!f||!o||!s)return;const g=Jo(f.id,s,o);if(!h&&!g)return;let m=null,p=null;return this.configuration.preview?.enabled&&(m=h||QR(...g),p=255),{...n,points:u,segmentIndex:o,viewPlaneNormal:l,previewOnHover:!this._previewData.isDrag,toolGroupId:this.toolGroupId,segmentationId:s,viewUp:d,centerSegmentIndexInfo:this.centerSegmentIndexInfo,activeStrategy:this.configuration.activeStrategy,configuration:this.configuration,previewColor:m,previewSegmentIndex:p,createMemo:this.createMemo.bind(this),hoverData:this._hoverData}}addPreview(t=this._previewData.element,n){const{_previewData:e}=this,o=n?.acceptReject;o===!0?this.acceptPreview(t):o===!1&&this.rejectPreview(t);const s=N(t),a=this.getOperationData(t);if(!s||!a)return;const r=this.applyActiveStrategyCallback(s,a,dt.AddPreview);return e.isDrag=!0,r?.modified&&(e.preview=r,e.element=t),r}rejectPreview(t=this._previewData.element){if(!t)return;this.doneEditMemo();const n=N(t),e=this.getOperationData(t);!n||!e||(this.applyActiveStrategyCallback(n,e,dt.RejectPreview),this._previewData.preview=null,this._previewData.isDrag=!1)}acceptPreview(t=this._previewData.element){if(!t)return;const n=this.getOperationData(t);if(!n)return;this.memo&&this.memo.id&&this.acceptedMemoIds.set(this.memo.id,{element:t,segmentIndex:n.segmentIndex});const e=N(t);this.applyActiveStrategyCallback(e,n,dt.AcceptPreview),this.doneEditMemo(),this._previewData.preview=null,this._previewData.isDrag=!1}static viewportContoursToLabelmap(t,n){const e=n?.removeContours??!0,o=Ca(),s=ya(t,o);if(!s?.length)return;const a=s.filter(p=>p.data.contour?.polyline?.length);if(!a.length)return;const c=new $i({},{configuration:{strategies:{FILL_INSIDE_CIRCLE:_d},activeStrategy:"FILL_INSIDE_CIRCLE"}}).addPreview(t.element),{memo:l,segmentationId:d}=c,u=l?.voxelManager,h=u.sourceVoxelManager||u,{dimensions:f}=u,g=t.getDefaultActor().actor.getMapper().getInputData();for(const p of a){const v=[[1/0,-1/0],[1/0,-1/0],[1/0,-1/0]],{polyline:I}=p.data.contour;for(const P of I)g.worldToIndex(P).forEach((M,L)=>{v[L][0]=Math.min(v[L][0],M),v[L][1]=Math.max(v[L][1],M)});v.forEach((P,x)=>{P[0]=Math.round(Math.max(0,P[0])),P[1]=Math.round(Math.min(f[x]-1,P[1]))});const w=xn(d),C=p.data.handles?.[0]||I[0],S=g.worldToIndex(C).map(Math.round),b=h.getAtIJKPoint(S)||0;let _=!1,y=!1;for(const P of I){const x=g.worldToIndex(P).map(Math.round),M=h.getAtIJKPoint(x);M===b?_=!0:M>=0&&(y=!0)}const T=_&&y?b:b===0?w:0;for(let P=v[0][0];P<=v[0][1];P++)for(let x=v[1][0];x<=v[1][1];x++)for(let M=v[2][0];M<=v[2][1];M++){const L=g.indexToWorld([P,x,M]);tf(L,I)&&u.setAtIJK(P,x,M,T)}e&&Gt(p.annotationUID)}const m=u.getArrayOfModifiedSlices();He(d,m)}}$i.previewData={preview:null,element:null,timerStart:0,timer:null,startPoint:[NaN,NaN],isDrag:!1};function QR(i,t,n,e,o=.4){return[Math.round(i+(255-i)*o),Math.round(t+(255-t)*o),Math.round(n+(255-n)*o),e]}const gu=.001;function yE(i){return[i[0],i[1],i[2]]}function xE(i,t){return Math.abs(i[0]-t[0])<gu&&Math.abs(i[1]-t[1])<gu&&Math.abs(i[2]-t[2])<gu}function tN(i=[],t){return!t||i.length&&xE(i[i.length-1],t)?i:[...i,yE(t)]}function eN(i=[],t=[]){if(!t.length)return i;const n=t.map(s=>yE(s));if(!i.length)return n;const e=i.slice(-n.length);return e.length===n.length&&e.every((s,a)=>xE(s,n[a]))?i:[...i,...n]}class nN{constructor(){this.strokePointsWorld=[],this.previewPoints=[],this.pendingPreviewCleanup=null}reset(){this.strokePointsWorld=[],this.previewPoints=[]}clearPendingCleanup(){this.pendingPreviewCleanup&&(Z.removeEventListener(E.SEGMENTATION_RENDERED,this.pendingPreviewCleanup.listener),this.pendingPreviewCleanup=null)}appendStrokePoint(t){this.strokePointsWorld=tN(this.strokePointsWorld,t)}getStrokePointsWorld(){return this.strokePointsWorld}capturePreviewCircle(t){if(!t)return;const n=t.brushCursor?.data?.editPoints;this.previewPoints=eN(this.previewPoints,n),t.brushCursor.data.handles.points=this.previewPoints}scheduleCleanup({element:t,centerCanvas:n,viewportId:e,segmentationId:o,refreshCursor:s}){this.clearPendingCleanup();const a=(r=>{const c=r.detail;c.viewportId!==e||c.segmentationId!==o||(this.clearPendingCleanup(),this.reset(),s(t,n))});this.pendingPreviewCleanup={viewportId:e,segmentationId:o,listener:a},Z.addEventListener(E.SEGMENTATION_RENDERED,a)}}class fs extends $i{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{strategies:{FILL_INSIDE_CIRCLE:_d,ERASE_INSIDE_CIRCLE:CE,FILL_INSIDE_SPHERE:EE,ERASE_INSIDE_SPHERE:SE,THRESHOLD_INSIDE_CIRCLE:VR,THRESHOLD_INSIDE_SPHERE:zR,THRESHOLD_INSIDE_SPHERE_WITH_ISLAND_REMOVAL:$R},defaultStrategy:"FILL_INSIDE_CIRCLE",activeStrategy:"FILL_INSIDE_CIRCLE",brushSize:25,useCenterSegmentIndex:!1,preview:{enabled:!1,previewColors:{0:[255,255,255,128]},previewTimeMs:250,previewMoveDistance:8,dragMoveDistance:4,dragTimeMs:500},actions:{[dt.AcceptPreview]:{method:dt.AcceptPreview,bindings:[{key:"Enter"}]},[dt.RejectPreview]:{method:dt.RejectPreview,bindings:[{key:"Escape"}]},[dt.Interpolate]:{method:dt.Interpolate,bindings:[{key:"i"}],configuration:{useBallStructuringElement:!0,noUseDistanceTransform:!0,noUseExtrapolation:!0}},interpolateExtrapolation:{method:dt.Interpolate,bindings:[{key:"e"}],configuration:{}}}}}){super(t,n),this._lastDragInfo=null,this._drawStartTimeStamp=0,this._lazyEdit=new nN,this.onSetToolPassive=e=>{this.disableCursor()},this.onSetToolEnabled=()=>{this.disableCursor()},this.onSetToolDisabled=e=>{this.disableCursor()},this.preMouseDownCallback=e=>{const o=e.detail,{element:s,currentPoints:a}=o,r=N(s),{viewport:c}=r;if(!Wi(c.id)){const f=new CustomEvent(yt.ERROR_EVENT,{detail:{type:"Segmentation",message:"No active segmentation detected, create a segmentation representation before using the brush tool"},cancelable:!0});return Z.dispatchEvent(f),!1}this._editData=this.createEditData(s),this._previewData.isDrag=!1,this._previewData.timerStart=Date.now(),this._drawStartTimeStamp=o.event?.timeStamp??0;const d=gi(a.canvas),u=c.canvasToWorld([d[0],d[1]]);if(this._lastDragInfo={canvas:d,world:ho(u)},this._hoverData=this.createHoverData(s,d),!this._hoverData)return this._editData=null,!1;this._calculateCursor(s,d),fs.activeCursorTool=this,this._resetLazyEditState(),this._isLazyLabelmapEditingEnabled(this._hoverData.viewport)&&(this._lazyEdit.appendStrokePoint(u),this._captureLazyPreviewCircle()),V(this._hoverData.viewportIdsToRender);const h=this.getOperationData(s);return h?(this._activateDraw(s),wt(s),e.preventDefault(),this.applyActiveStrategyCallback(r,h,dt.OnInteractionStart),!0):!1},this.mouseMoveCallback=e=>{if(this.isPrimary&&this.mode===se.Active){if(this.updateCursor(e),!this.configuration.preview.enabled)return;const{previewTimeMs:o,previewMoveDistance:s,dragMoveDistance:a}=this.configuration.preview,{currentPoints:r,element:c}=e.detail,{canvas:l}=r,{startPoint:d,timer:u,timerStart:h,isDrag:f}=this._previewData;if(f)return;const g=_e(l,d),m=Date.now()-h;if((g>s||m>o&&g>a)&&(u&&(window.clearTimeout(u),this._previewData.timer=null),f||this.rejectPreview(c)),!this._previewData.timer){const p=window.setTimeout(this.previewCallback,250);Object.assign(this._previewData,{timerStart:Date.now(),timer:p,startPoint:l,element:c})}}},this.previewCallback=()=>{if(this._previewData.isDrag){this._previewData.timer=null;return}this._previewData.timer=null;const e=this.getOperationData(this._previewData.element);if(!e)return;const o=N(this._previewData.element);if(!o)return;const{viewport:s}=o,a=this.configuration.activeStrategy,r=Of({operationData:e,viewport:s,strategy:a});if(!e)return;const c=this.createMemo(e.segmentationId,r.segmentationVoxelManager);this._previewData.preview=this.applyActiveStrategyCallback(N(this._previewData.element),{...e,...r,memo:c},dt.Preview)},this._dragCallback=e=>{const o=e.detail,{element:s,currentPoints:a}=o,{currentPointsList:r}=o;if(r?.length>1){this._cancelTouchDraw(s);return}const c=N(s),{viewport:l}=c;if(this.updateCursor(e),!this._hoverData)return;const{viewportIdsToRender:d}=this._hoverData;V(d);const u=_e(a.canvas,this._previewData.startPoint),{dragTimeMs:h,dragMoveDistance:f}=this.configuration.preview;if(!this._previewData.isDrag&&Date.now()-this._previewData.timerStart<h&&u<f)return;if(this._previewData.timer&&(window.clearTimeout(this._previewData.timer),this._previewData.timer=null),!this._lastDragInfo){const v=this._previewData.startPoint,I=l.canvasToWorld([v[0],v[1]]);this._lastDragInfo={canvas:gi(v),world:ho(I)}}const g=a.canvas,m=l.canvasToWorld([g[0],g[1]]);if(this._hoverData=this.createHoverData(s,g),!this._hoverData)return;if(this._calculateCursor(s,g),this._isLazyLabelmapEditingEnabled(this._hoverData.viewport))this._lazyEdit.appendStrokePoint(m),this._captureLazyPreviewCircle(),this._previewData.preview=null;else{const v=this.getOperationData(s);if(!v)return;v.strokePointsWorld=[ho(this._lastDragInfo.world),ho(m)],this._previewData.preview=this.applyActiveStrategy(c,v)}const p=gi(g);this._lastDragInfo={canvas:p,world:ho(m)},this._previewData.element=s,this._previewData.timerStart=Date.now()+h,this._previewData.isDrag=!0,this._previewData.startPoint=p},this._endCallback=e=>{const o=e.detail,{element:s}=o;if(o.eventName===E.TOUCH_TAP&&(o.event?.timeStamp??0)<this._drawStartTimeStamp)return;const a=N(s),r=this.getOperationData(s);if(!r)return;const c=this._isLazyLabelmapEditingEnabled(this._hoverData?.viewport);c&&this._previewData.isDrag?(r.strokePointsWorld=this._lazyEdit.getStrokePointsWorld().map(l=>ho(l)),this.applyActiveStrategy(a,r)):!this._previewData.preview&&!this._previewData.isDrag&&this.applyActiveStrategy(a,r),this.doneEditMemo(),this._deactivateDraw(s),Ft(s),this._editData=null,this._lastDragInfo=null,c&&this._previewData.isDrag?(this._scheduleLazyPreviewCleanup(s,e.detail.currentPoints.canvas,a.viewport.id,r.segmentationId,this._isTouchInteraction(e)),V(this._hoverData.viewportIdsToRender)):(this._resetLazyEditState(),this._isTouchInteraction(e)?this._clearCursor(s):this.updateCursor(e)),this.applyActiveStrategyCallback(a,r,dt.OnInteractionEnd),this._previewData.isDrag||this.acceptPreview(s)},this._activateDraw=e=>{e.addEventListener(E.MOUSE_UP,this._endCallback),e.addEventListener(E.MOUSE_DRAG,this._dragCallback),e.addEventListener(E.MOUSE_CLICK,this._endCallback),e.addEventListener(E.TOUCH_END,this._endCallback),e.addEventListener(E.TOUCH_DRAG,this._dragCallback),e.addEventListener(E.TOUCH_TAP,this._endCallback)},this._deactivateDraw=e=>{e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.TOUCH_END,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback)}}disableCursor(){this._clearPendingLazyPreviewCleanup(),this._hoverData=void 0,this._resetLazyEditState(),this.rejectPreview()}_isLazyLabelmapEditingEnabled(t){return gE(t??this._hoverData?.viewport)}_resetLazyEditState(){this._lazyEdit.reset()}_clearPendingLazyPreviewCleanup(){this._lazyEdit.clearPendingCleanup()}_refreshCursor(t,n){this._hoverData=this.createHoverData(t,n),this._hoverData&&(this._calculateCursor(t,n),fs.activeCursorTool=this,V(this._hoverData.viewportIdsToRender))}_scheduleLazyPreviewCleanup(t,n,e,o,s=!1){this._lazyEdit.scheduleCleanup({element:t,centerCanvas:n,viewportId:e,segmentationId:o,refreshCursor:s?a=>this._clearCursor(a):this._refreshCursor.bind(this)})}_captureLazyPreviewCircle(){!this._isLazyLabelmapEditingEnabled()||!this._hoverData||this._lazyEdit.capturePreviewCircle(this._hoverData)}updateCursor(t){const n=t.detail,{element:e}=n,{currentPoints:o}=n,s=o.canvas;this._refreshCursor(e,s)}_clearCursor(t){const n=this._hoverData?.viewportIdsToRender;if(this._hoverData=void 0,n?.length){V(n);return}const e=N(t);e&&V([e.viewport.id])}_cancelTouchDraw(t){const{memo:n}=this;n?.commitMemo?.()&&n.restoreMemo(!0),this.memo=null,this._deactivateDraw(t),Ft(t),this._editData=null,this._lastDragInfo=null,this._previewData.preview=null,this._previewData.isDrag=!1,this._previewData.timer&&(window.clearTimeout(this._previewData.timer),this._previewData.timer=null),this._resetLazyEditState(),this._clearCursor(t)}_calculateCursor(t,n){const e=N(t),o=this.getOperationData(t);!e||!o||this.applyActiveStrategyCallback(e,o,dt.CalculateCursorGeometry)}getStatistics(t,n){if(!t)return;const e=N(t),o=this.getOperationData(t);return!e||!o?void 0:this.applyActiveStrategyCallback(e,o,dt.GetStatistics,n)}rejectPreview(t=this._previewData.element){if(!t)return;this.doneEditMemo();const n=N(t);if(!n)return;const e=this.getOperationData(t);e&&(this.applyActiveStrategyCallback(n,e,dt.RejectPreview),this._previewData.preview=null,this._previewData.isDrag=!1)}acceptPreview(t=this._previewData.element){t&&super.acceptPreview(t)}interpolate(t,n){if(!t)return;const e=N(t),o=this.getOperationData(t);!e||!o||(this._previewData.preview=this.applyActiveStrategyCallback(e,o,dt.Interpolate,n.configuration),this._previewData.isDrag=!0)}invalidateBrushCursor(){if(this._hoverData===void 0)return;const{data:t}=this._hoverData.brushCursor,{viewport:n}=this._hoverData;t.invalidated=!0;const{segmentColor:e}=this.getActiveSegmentationData(n)||{};this._hoverData.brushCursor.metadata.segmentColor=e}renderAnnotation(t,n){if(!this._hoverData||fs.activeCursorTool!==this)return;const{viewport:e}=t;if(!this._hoverData.viewportIdsToRender.includes(e.id))return;if(this._hoverData.brushCursor.data.invalidated===!0){const{centerCanvas:a}=this._hoverData,{element:r}=e;this._calculateCursor(r,a)}this.applyActiveStrategyCallback(t,this.getOperationData(e.element),dt.RenderCursor,n)}}fs.toolName="Brush";function La(i,t){const n=Be(i);if(n===void 0)return[];const e=n._toolInstances;return Object.keys(e).length?t&&e[t]?[e[t]]:Object.values(e).filter(s=>s instanceof fs):[]}function oN(i,t,n){const e=Be(i);if(e===void 0)return;La(i,n).forEach(a=>{const r=a.configuration.minRadius,c=a.configuration.maxRadius;let l=r?Math.max(t,r):t;l=c?Math.min(l,c):l,a.configuration.brushSize=l,a.invalidateBrushCursor()});const s=e.getViewportIds();V(s)}function iN(i,t){const n=Be(i);if(n===void 0)return;const e=n._toolInstances;if(!Object.keys(e).length)return;const s=La(i,t)[0];if(s)return s.configuration.brushSize}function sN(i,t){const n=Be(i);if(n===void 0||(La(i).forEach(a=>{a.configuration.activeStrategy.toLowerCase().includes("threshold")&&(a.configuration={...a.configuration,threshold:{...a.configuration.threshold,...t}})}),!n.getViewportsInfo().length))return;const s=n.getViewportIds();V(s)}function aN(i){const t=Be(i);if(t===void 0)return;const n=t._toolInstances;if(!Object.keys(n).length)return;const o=La(i)[0];if(o)return o.configuration.threshold.range}class xd{static statsInit(t){const{storePointData:n,indices:e,mode:o}=t;this.mode=o,this.indices=e,this.calculators.clear(),this.mode==="individual"?e.forEach(s=>{this.calculators.set(s,new gp({storePointData:n}))}):this.calculators.set(e,new gp({storePointData:n}))}static statsCallback(t){const{segmentIndex:n,...e}=t;if(!n)throw new Error("Segment index is required for stats calculation");const o=this.mode==="individual"?this.calculators.get(n):this.calculators.get(this.indices);if(!o)throw new Error(`No calculator found for segment ${n}`);o.statsCallback(e)}static getStatistics(t){if(this.mode==="individual"){const e={};return this.calculators.forEach((o,s)=>{e[s]=o.getStatistics(t)}),e}return this.calculators.get(this.indices).getStatistics(t)}}xd.calculators=new Map;xd.indices=[];xd.mode="collective";function rN(i,t,n,e,o){if(!o)throw new Error("Segmentation ID is required to be passed inside thresholdSegmentationByRange");const{baseVolumeIdx:s,volumeInfoList:a}=BI(i,n),{voxelManager:r}=a[s],c=r,l=i.voxelManager.getScalarDataLength(),d=i.voxelManager;return a.forEach(u=>{const{volumeSize:h}=u;h===l?lN(d,c,t,u):cN(d,c,t,u,a,s,e)}),He(o),i}function cN(i,t,n,e,o,s,a){const{imageData:r,lower:c,upper:l,dimensions:d}=e;let u,h,f;const g=i.getScalarDataLength();for(let m=0;m<g;m++)if(g.getAtIndex(m)===n){const p=jh(r,d,o[s].spacing,o[s].imageData.getPoint(m)),v=({value:w})=>{u=u+1,w>=f.lower&&w<=f.upper&&(h=h+1)};u=0,h=0,f={lower:c,upper:l};let I=!1;i.forEach(v,{imageData:r,boundsIJK:p}),I=a===0?h>0:h===u,i.setAtIndex(m,I?n:0)}return{total:u,range:f,overlaps:h}}function lN(i,t,n,e){const{lower:o,upper:s}=e,a=i.getScalarDataLength();for(let r=0;r<a;r++)if(i.getAtIndex[r]===n){const c=t.getAtIndex(r);i.setAtIndex(r,c>=o&&c<=s?n:0)}}function Ip(i,t,n){const e=n.toIJK(i),o=n.toIJK(t),s=B(),{testIJK:a}=n,r=tn(B(),e,o),c=Math.round(Math.max(...r.map(Math.abs)));if(c<2)return!0;const l=bn(B(),r,1/c);for(let d=1;d<c;d++)if(ee(s,o,l,d),!a(s))return!1;return!0}function dN({dimensions:i,imageData:t,voxelManager:n,segmentIndex:e,containedSegmentIndices:o}){const s=i[0],a=s*i[1];return{testCenter:(r,c)=>{const l=yn(B(),r,c).map(p=>p/2),d=t.worldToIndex(l).map(Math.round),[u,h,f]=d,g=u+h*s+f*a,m=n.getAtIndex(g);return m===e||o?.has(m)},toIJK:r=>t.worldToIndex(r),testIJK:r=>{const[c,l,d]=r,u=Math.round(c)+Math.round(l)*s+Math.round(d)*a,h=n.getAtIndex(u);return h===e||o?.has(h)}}}function uN(i,t,n){const e=Q.getVolume(i);if(!e){console.warn(`No volume found for ${i}`);return}return dN({dimensions:e.dimensions,imageData:e.imageData,voxelManager:e.voxelManager,segmentIndex:t,containedSegmentIndices:n})}const $a=.01;function hN(i,t,n){const{sliceContours:e}=i,{segmentIndex:o,containedSegmentIndices:s}=n;let a;const r=uN(t,o,s);for(const c of e){const l=fN(c,r,a);l&&(a=l)}return a&&Object.assign(a,n),a}function fN(i,t,n={maxMajor:0,maxMinor:0}){const{points:e}=i.polyData,{maxMinor:o,maxMajor:s}=n;let a=s*s,r=o*o,c;for(let p=0;p<e.length;p++)for(let v=p+1;v<e.length;v++){const I=e[p],w=e[v],C=Fu(I,w);C<a||C-$a<a+$a&&c||t.testCenter(I,w)&&Ip(I,w,t)&&(a=C-$a,c=[p,v],r=0)}if(!c)return;a=Math.sqrt(a+$a);const l=e[c[0]],d=e[c[1]],u=tn(B(),l,d);bn(u,u,1/a);let h;for(let p=0;p<e.length;p++)for(let v=p+1;v<e.length;v++){const I=e[p],w=e[v],C=Fu(I,w);if(C<=r)continue;const S=tn(B(),I,w);Math.abs(xt(S,u))/Math.sqrt(C)>$a||t.testCenter(I,w)&&Ip(I,w,t)&&(r=C,h=[p,v])}if(!h)return;r=Math.sqrt(r);const f=e[h[0]],g=e[h[1]];return{majorAxis:[l,d],minorAxis:[f,g],maxMajor:a,maxMinor:r,...i}}async function PE(i){const t=await Nw({segmentations:i});if(!t?.length||!t[0].sliceContours.length)return;const{segments:n=[null,{label:"Unspecified",color:null,containedSegmentIndices:null}]}=i,e=Ma(i.segmentationId);if(!e)return;const o=n.findIndex(s=>!!s);if(o!==-1)return n[o].segmentIndex=o,hN(t[0],e.volumeId,n[o])}function DE(i,t){const{majorAxis:n,minorAxis:e,label:o="",sliceIndex:s}=i,[a,r]=n,[c,l]=e,d=[a,r,c,l];return{highlighted:!0,invalidated:!0,metadata:{toolName:"Bidirectional",...t.getViewReference({sliceIndex:s})},data:{handles:{points:d,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}},activeHandleIndex:null},label:o,cachedStats:{}},isLocked:!1,isVisible:!0}}var aa;class fc extends be{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{preventHandleOutsideImage:!1,getTextLines:gN}}){super(t,n),this.isPointNearTool=(e,o,s,a)=>{const r=N(e),{viewport:c}=r,{data:l}=o,{points:d}=l.handles;let u=c.worldToCanvas(d[0]),h=c.worldToCanvas(d[1]),f={start:{x:u[0],y:u[1]},end:{x:h[0],y:h[1]}},g=Je([f.start.x,f.start.y],[f.end.x,f.end.y],[s[0],s[1]]);return g<=a||(u=c.worldToCanvas(d[2]),h=c.worldToCanvas(d[3]),f={start:{x:u[0],y:u[1]},end:{x:h[0],y:h[1]}},g=Je([f.start.x,f.start.y],[f.end.x,f.end.y],[s[0],s[1]]),g<=a)},this.toolSelectedCallback=(e,o)=>{const s=e.detail,{element:a}=s;o.highlighted=!0;const r=ft(a,this.getToolName());this.editData={annotation:o,viewportIdsToRender:r,movingTextBox:!1},this._activateModify(a);const c=N(a),{renderingEngine:l}=c;V(r),wt(a),e.preventDefault()},this.handleSelectedCallback=(e,o,s)=>{const a=e.detail,{element:r}=a,c=o.data;o.highlighted=!0;let l=!1,d;s.worldPosition?l=!0:d=c.handles.points.findIndex(g=>g===s);const u=ft(r,this.getToolName());wt(r),this.editData={annotation:o,viewportIdsToRender:u,handleIndex:d,movingTextBox:l},this._activateModify(r);const h=N(r),{renderingEngine:f}=h;V(u),e.preventDefault()},this._endCallback=e=>{const o=e.detail,{element:s}=o,{annotation:a,viewportIdsToRender:r,newAnnotation:c,hasMoved:l}=this.editData,{data:d}=a;if(c&&!l)return;this.doneEditMemo(),d.handles.activeHandleIndex=null,this._deactivateModify(s),this._deactivateDraw(s),Ft(s);const{renderingEngine:u}=N(s);if(this.editData.handleIndex!==void 0){const{points:h}=d.handles,f=ke(h[0],h[1]);if(ke(h[2],h[3])>f){const m=[[...h[2]],[...h[3]]],p=[...h[0]],v=[...h[1]],I=It();mo(I,m[1][0]-m[0][0],m[1][1]-m[1][0]);const w=It();mo(w,-I[1],I[0]);const C=It();mo(C,v[0]-p[0],v[1]-p[0]);let S;zo(C,w)>0?S=[p,v]:S=[v,p],d.handles.points=[m[0],m[1],S[0],S[1]]}}this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&Gt(a.annotationUID),V(r),c&&ue(a),this.editData=null,this.isDrawing=!1},this._dragDrawCallback=e=>{this.isDrawing=!0;const o=e.detail,{currentPoints:s,element:a}=o,r=N(a),{viewport:c}=r,{worldToCanvas:l}=c,{annotation:d,viewportIdsToRender:u,handleIndex:h,newAnnotation:f}=this.editData;this.createMemo(a,d,{newAnnotation:f});const{data:g}=d,m=s.world;g.handles.points[h]=[...m];const p=g.handles.points.map(l),v={longLineSegment:{start:{x:p[0][0],y:p[0][1]},end:{x:p[1][0],y:p[1][1]}},shortLineSegment:{start:{x:p[2][0],y:p[2][1]},end:{x:p[3][0],y:p[3][1]}}},w=_e(p[0],p[1])/3,C=v.longLineSegment.start.x-v.longLineSegment.end.x,S=v.longLineSegment.start.y-v.longLineSegment.end.y,b=Math.sqrt(C*C+S*S),_=C/b,y=S/b,D=(v.longLineSegment.start.x+v.longLineSegment.end.x)/2,T=(v.longLineSegment.start.y+v.longLineSegment.end.y)/2,P=D+w*y,x=T-w*_,M=D-w*y,L=T+w*_;g.handles.points[2]=c.canvasToWorld([P,x]),g.handles.points[3]=c.canvasToWorld([M,L]),d.invalidated=!0,V(u),zt(d,a,Bt.HandlesUpdated),this.editData.hasMoved=!0},this._dragModifyCallback=e=>{this.isDrawing=!0;const o=e.detail,{element:s}=o,{annotation:a,viewportIdsToRender:r,handleIndex:c,movingTextBox:l,newAnnotation:d}=this.editData;this.createMemo(s,a,{newAnnotation:d});const{data:u}=a;if(l){const{deltaPoints:h}=o,f=h.world,{textBox:g}=u.handles,{worldPosition:m}=g;m[0]+=f[0],m[1]+=f[1],m[2]+=f[2],g.hasMoved=!0}else if(c===void 0){const{deltaPoints:h}=o,f=h.world;u.handles.points.forEach(m=>{m[0]+=f[0],m[1]+=f[1],m[2]+=f[2]}),a.invalidated=!0}else this._dragModifyHandle(e),a.invalidated=!0;V(r),a.invalidated&&zt(a,s,Bt.HandlesUpdated)},this._dragModifyHandle=e=>{const o=e.detail,{currentPoints:s,element:a}=o,r=N(a),{viewport:c}=r,{annotation:l,handleIndex:d}=this.editData,{data:u}=l,h=s.world,f=[c.worldToCanvas(u.handles.points[0]),c.worldToCanvas(u.handles.points[1]),c.worldToCanvas(u.handles.points[2]),c.worldToCanvas(u.handles.points[3])],g={start:{x:f[0][0],y:f[0][1]},end:{x:f[1][0],y:f[1][1]}},m={start:{x:f[2][0],y:f[2][1]},end:{x:f[3][0],y:f[3][1]}},p=[...h],v=c.worldToCanvas(p);if(d===0||d===1){const w=f[d===0?1:0],C=mo(It(),v[0]-w[0],v[1]-w[1]),S=mo(It(),f[d][0]-w[0],f[d][1]-w[1]);Ao(C,C),Ao(S,S);const b={start:{x:w[0],y:w[1]},end:{x:v[0],y:v[1]}};if(this._movingLongAxisWouldPutItThroughShortAxis(b,m))return;const _=w,y=this._getSignedAngle(S,C);let D=f[2][0],T=f[2][1],P=f[3][0],x=f[3][1];D-=_[0],T-=_[1],P-=_[0],x-=_[1];const M=D*Math.cos(y)-T*Math.sin(y),L=D*Math.sin(y)+T*Math.cos(y),R=P*Math.cos(y)-x*Math.sin(y),U=P*Math.sin(y)+x*Math.cos(y);D=M+_[0],T=L+_[1],P=R+_[0],x=U+_[1];const W=c.canvasToWorld([D,T]),K=c.canvasToWorld([P,x]);u.handles.points[d]=p,u.handles.points[2]=W,u.handles.points[3]=K}else{const I=d===2?3:2,w={longLineSegment:{start:g.start,end:g.end},shortLineSegment:{start:m.start,end:m.end}},C=pe(It(),[w.longLineSegment.end.x,w.longLineSegment.end.y],[w.longLineSegment.start.x,w.longLineSegment.start.y]),S=Ao(It(),C),b=pe(It(),[v[0],v[1]],[f[d][0],f[d][1]]),_=ha(b),y=this._getSignedAngle(S,b),D=Math.cos(y)*_,T=nr(It(),[f[I][0],f[I][1]],S,D);if(this._movingLongAxisWouldPutItThroughShortAxis({start:{x:v[0],y:v[1]},end:{x:T[0],y:T[1]}},{start:{x:w.longLineSegment.start.x,y:w.longLineSegment.start.y},end:{x:w.longLineSegment.end.x,y:w.longLineSegment.end.y}})||!al([v[0],v[1]],[T[0],T[1]],[g.start.x,g.start.y],[g.end.x,g.end.y]))return;u.handles.points[I]=c.canvasToWorld(T),u.handles.points[d]=p}},this.cancel=e=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateDraw(e),this._deactivateModify(e),Ft(e);const{annotation:o,viewportIdsToRender:s,newAnnotation:a}=this.editData,{data:r}=o;return o.highlighted=!1,r.handles.activeHandleIndex=null,V(s),a&&ue(o),this.editData=null,o.annotationUID}},this._activateDraw=e=>{$.isInteractingWithTool=!0,e.addEventListener(E.MOUSE_UP,this._endCallback),e.addEventListener(E.MOUSE_DRAG,this._dragDrawCallback),e.addEventListener(E.MOUSE_MOVE,this._dragDrawCallback),e.addEventListener(E.MOUSE_CLICK,this._endCallback),e.addEventListener(E.TOUCH_TAP,this._endCallback),e.addEventListener(E.TOUCH_END,this._endCallback),e.addEventListener(E.TOUCH_DRAG,this._dragDrawCallback)},this._deactivateDraw=e=>{$.isInteractingWithTool=!1,e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragDrawCallback),e.removeEventListener(E.MOUSE_MOVE,this._dragDrawCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback),e.removeEventListener(E.TOUCH_END,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragDrawCallback)},this._activateModify=e=>{$.isInteractingWithTool=!0,e.addEventListener(E.MOUSE_UP,this._endCallback),e.addEventListener(E.MOUSE_DRAG,this._dragModifyCallback),e.addEventListener(E.MOUSE_CLICK,this._endCallback),e.addEventListener(E.TOUCH_END,this._endCallback),e.addEventListener(E.TOUCH_DRAG,this._dragModifyCallback),e.addEventListener(E.TOUCH_TAP,this._endCallback)},this._deactivateModify=e=>{$.isInteractingWithTool=!1,e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragModifyCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.TOUCH_END,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragModifyCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(e,o)=>{let s=!0;const{viewport:a}=e,{element:r}=a;let c=Yt(this.getToolName(),r);if(!c?.length||(c=this.filterInteractableAnnotationsForElement(r,c),!c?.length))return s;const l=this.getTargetId(a),d=a.getRenderingEngine(),u={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:e.viewport.id};for(let h=0;h<c.length;h++){const f=c[h],{annotationUID:g,data:m}=f,{points:p,activeHandleIndex:v}=m.handles,I=p.map(L=>a.worldToCanvas(L));u.annotationUID=g;const{color:w,lineWidth:C,lineDash:S,shadow:b}=this.getAnnotationStyle({annotation:f,styleSpecifier:u});if(!m.cachedStats[l]||m.cachedStats[l].unit==null?(m.cachedStats[l]={length:null,width:null,unit:null},this._calculateCachedStats(f,d,e)):f.invalidated&&this._throttledCalculateCachedStats(f,d,e),!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),s;let _;if(!$e(g))continue;!ze(g)&&!this.editData&&v!==null&&(_=[I[v]]);const y=!!Nn("showHandlesAlways",{});(_||y)&&xe(o,g,"0",y?I:_,{color:w});const D=`${g}-line-1`,T=`${g}-line-2`;qt(o,g,"0",I[0],I[1],{color:w,lineDash:S,lineWidth:C,shadow:b},D),qt(o,g,"1",I[2],I[3],{color:w,lineDash:S,lineWidth:C,shadow:b},T),s=!0;const M=this.configuration.getTextLines(m,l);!M||M.length===0||this.renderLinkedTextBoxAnnotation({enabledElement:e,svgDrawingHelper:o,annotation:f,styleSpecifier:u,textLines:M,canvasCoordinates:I})}return s},this._movingLongAxisWouldPutItThroughShortAxis=(e,o)=>{const s=It();mo(s,o.end.x-o.start.x,o.end.y-o.start.y),Ao(s,s);const a={start:{x:o.start.x-s[0]*10,y:o.start.y-s[1]*10},end:{x:o.end.x+s[0]*10,y:o.end.y+s[1]*10}};return!al([a.start.x,a.start.y],[a.end.x,a.end.y],[e.start.x,e.start.y],[e.end.x,e.end.y])},this._calculateCachedStats=(e,o,s)=>{const{data:a}=e,{element:r}=s.viewport;a.handles.points[0],a.handles.points[1],a.handles.points[2],a.handles.points[3];const{cachedStats:c}=a,l=Object.keys(c);for(let u=0;u<l.length;u++){const h=l[u],f=this.getTargetImageData(h);if(!f)continue;const{imageData:g,dimensions:m}=f,p=a.handles.points.map(T=>g.worldToIndex(T)),v=p.slice(0,2),I=p.slice(2,4),w=ao(f,p),C=aa.calculateLengthInIndex(w,v),S=aa.calculateLengthInIndex(w,I),{unit:b}=w,_=C>S?C:S,y=C>S?S:C,D=b;this.isHandleOutsideImage=!aa.isInsideVolume(m,p),c[h]={length:_,width:y,unit:b,widthUnit:D,statsArray:[{value:_,name:"height",unit:b,type:Io.Linear},{value:y,name:"width",unit:b,type:Io.Linear}]}}const d=e.invalidated;return e.invalidated=!1,d&&zt(e,r,Bt.StatsUpdated),c},this._getSignedAngle=(e,o)=>Math.atan2(e[0]*o[1]-e[1]*o[0],e[0]*o[0]+e[1]*o[1]),this._throttledCalculateCachedStats=Un(this._calculateCachedStats,100,{trailing:!0})}addNewAnnotation(t){const n=t.detail,{currentPoints:e,element:o}=n,s=e.world;this.isDrawing=!0;const a=this.createAnnotation(t,[[...s],[...s],[...s],[...s]]);Nt(a,o);const r=ft(o,this.getToolName());return this.editData={annotation:a,viewportIdsToRender:r,handleIndex:1,movingTextBox:!1,newAnnotation:!0,hasMoved:!1},this._activateDraw(o),wt(o),t.preventDefault(),V(r),a}}aa=fc;fc.toolName="Bidirectional";fc.hydrate=(i,t,n)=>{const e=le(i);if(!e)return;const{FrameOfReferenceUID:o,referencedImageId:s,viewPlaneNormal:a,instance:r,viewport:c}=aa.hydrateBase(aa,e,t[0],n),[l,d]=t,[u,h]=l,[f,g]=d,m=[u,h,f,g],{toolInstance:p,...v}=n||{},I={annotationUID:n?.annotationUID||Se(),data:{handles:{points:m,activeHandleIndex:null,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}},cachedStats:{}},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{toolName:r.getToolName(),viewPlaneNormal:a,FrameOfReferenceUID:o,referencedImageId:s,...v}};return Nt(I,c.element),V([c.id]),I};function gN(i,t){const{cachedStats:n,label:e}=i,{length:o,width:s,unit:a}=n[t],r=[];return e&&r.push(e),o===void 0||r.push(`L: ${de(o)} ${a||a}`,`W: ${de(s)} ${a}`),r}async function mN(i,t){console.warn("Deprecation Alert: There is a new getSegmentLargestBidirectional function that handles volume, stack and individual segment cases properly. This function is deprecated and will be removed in a future version.");const{data:n}=t,e=N(i),o=(n.getSegment||pN)(e,n);if(!o)return;const s=e.viewport.getFrameOfReferenceUID(),a=pd(),{segmentIndex:r,segmentationId:c}=o,l=Uo.getAnnotations(this.toolName||fc.toolName,s);let d=!1;const u=l.filter(f=>{const g=f.data.segment;return g?(g.segmentationId===c&&g.segmentIndex===r&&(d=!0,f.data.segment=g),!0):!1});d||u.push({data:{segment:o}});let h;if(u.forEach(async f=>{const g=[],m=f.data.segment,{segmentIndex:p,segmentationId:v}=m;g[p]=m,Uo.removeAnnotation(f.annotationUID);const I=await PE({...a.find(S=>S.segmentationId===v),segments:g});if(!I)return;const w=DE(I,e.viewport);w.annotationUID=f.annotationUID,w.data.segment=m;const C=Uo.addAnnotation(w,s);if(m.segmentIndex===o.segmentIndex&&m.segmentationId===o.segmentationId){h=I;const{style:S}=o;S&&Nh.setAnnotationStyles(C,S)}}),h){const{sliceIndex:f}=h,g=e.viewport.getImageIds();Tv(i,{imageIndex:g.length-1-f}),e.viewport.render()}else console.warn("No bidirectional found");return h}function pN(i,t){const n=pd();if(!n.length)return;const e=t.segmentationId||n[0].segmentationId,o=t.segmentIndex??xn(e);if(!o)return;const s=t.segmentData?.get(o);return{label:`Segment ${o}`,segmentIndex:o,segmentationId:e,...s}}function TE(i){const t=Be(i);if(t===void 0)return;La(i).forEach(a=>{a.invalidateBrushCursor()});const e=t.getViewportsInfo();if(!Object.keys(e).map(a=>e[a]).length)return;const s=t.getViewportIds();V(s)}function Xf(i,t,n={}){const e=Dt(i),o=e.representationData,s=n?.representationType??Object.keys(o)[0];if(!s)throw new Error(`Segmentation ${i} does not have any representations`);switch(s){case St.Labelmap:return vN(e,t,n);case St.Contour:return IN(e,t,n);default:return}}function vN(i,t,{viewport:n}){if((n?zn(n):"unsupported")==="volume"||n instanceof pn){for(const s of cn(i)){const a=$n(s);if(!a)continue;const r=a.voxelManager,c=wn(a.imageData,t),l=r.getAtIJKPoint(c);if(l)return fa(i,s.labelmapId,l)}return}const o=ys(n.id,i.segmentationId);if(o?.length)for(const s of o){if(!Q.getImage(s))continue;const c=Lf(n.id,i.segmentationId,s)?.actor.getMapper().getInputData(),l=wn(c,t),d=c.getDimensions(),h=(c.voxelManager||kl.createScalarVolumeVoxelManager({dimensions:d,scalarData:c.getPointData().getScalars().getData()})).getAtIJKPoint(l);if(!h)continue;const f=cn(i).find(g=>g.imageIds?.includes(s));return f?fa(i,f.labelmapId,h):h}}function IN(i,t,{viewport:n}){const e=i.representationData.Contour,o=new Map;for(const[a,r]of e.annotationUIDsMap)for(const c of r){const l=ne(c);l&&o.set(l,Number(a))}const s=ya(n,Array.from(o.keys()));for(const a of s){const{polyline:r}=a.data.contour;if(tf(t,r))return o.get(a)}}function ME(i,t,{viewport:n,searchRadius:e}){const o=Dt(i);if((n?zn(n):"unsupported")==="volume"||n instanceof pn){for(const p of cn(o)){const v=$n(p);if(!v)continue;const I=v.voxelManager,w=v.imageData,C=wn(w,t),S=I.getAtIJK(C[0],C[1],C[2]),b=n.worldToCanvas(t);if(EN(b,S,n,w,e)&&S)return fa(o,p.labelmapId,S)}return}const a=Zi(n.id,i);if(!a||!Q.getImage(a))return;const l=Lf(n.id,i,a)?.actor.getMapper().getInputData(),d=wn(l,t),u=l.getDimensions(),h=l.voxelManager||kl.createScalarVolumeVoxelManager({dimensions:u,scalarData:l.getPointData().getScalars().getData()}),f=h.getAtIJKPoint(d);if(!wN(d,u,h,f)||!f)return;const m=cn(o).find(p=>p.imageIds?.includes(a));return m?fa(o,m.labelmapId,f):f}function AE(i,t,n=1){const e=Array.from({length:2*n+1},(o,s)=>s-n);for(const o of e)for(const s of e)for(const a of e){if(o===0&&s===0&&a===0)continue;const r=i(o,s,a);if(r!==void 0&&t!==r)return!0}return!1}function wN(i,t,n,e,o){return AE((a,r,c)=>{const l=[i[0]+a,i[1]+r,i[2]+c];return n.getAtIJK(l[0],l[1],l[2])},e,o)}function EN(i,t,n,e,o){return AE((a,r)=>{const c=[i[0]+a,i[1]+r],l=n.canvasToWorld(c),d=e.get("voxelManager").voxelManager,u=wn(e,l);return d.getAtIJK(u[0],u[1],u[2])},t,o)}function LE(i){const t=Dt(i),{annotationUIDsMap:n}=t.representationData.Contour;for(const[e,o]of n.entries())if(Array.from(o).find(a=>ne(a).highlighted))return e}const SN=`
|
|
176
|
+
const MAX_STRENGTH = 65535f;
|
|
177
|
+
|
|
178
|
+
// Workgroup size - X*Y*Z must be multiple of 32 for better performance
|
|
179
|
+
override workGroupSizeX = 1u;
|
|
180
|
+
override workGroupSizeY = 1u;
|
|
181
|
+
override workGroupSizeZ = 1u;
|
|
182
|
+
|
|
183
|
+
// Compare the current voxel to neighbors using a 9x9x9 window
|
|
184
|
+
override windowSize = 9i;
|
|
185
|
+
|
|
186
|
+
struct Params {
|
|
187
|
+
size: vec3u,
|
|
188
|
+
iteration: u32,
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// New structure to track bounds of modified voxels
|
|
192
|
+
struct Bounds {
|
|
193
|
+
minX: atomic<i32>,
|
|
194
|
+
minY: atomic<i32>,
|
|
195
|
+
minZ: atomic<i32>,
|
|
196
|
+
maxX: atomic<i32>,
|
|
197
|
+
maxY: atomic<i32>,
|
|
198
|
+
maxZ: atomic<i32>,
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
@group(0) @binding(0) var<uniform> params: Params;
|
|
202
|
+
@group(0) @binding(1) var<storage> volumePixelData: array<f32>;
|
|
203
|
+
@group(0) @binding(2) var<storage, read_write> labelmap: array<u32>;
|
|
204
|
+
@group(0) @binding(3) var<storage, read_write> strengthData: array<f32>;
|
|
205
|
+
@group(0) @binding(4) var<storage> prevLabelmap: array<u32>;
|
|
206
|
+
@group(0) @binding(5) var<storage> prevStrengthData: array<f32>;
|
|
207
|
+
@group(0) @binding(6) var<storage, read_write> updatedVoxelsCounter: array<atomic<u32>>;
|
|
208
|
+
@group(0) @binding(7) var<storage, read_write> modifiedBounds: Bounds;
|
|
209
|
+
|
|
210
|
+
fn getPixelIndex(ijkPos: vec3u) -> u32 {
|
|
211
|
+
let numPixelsPerSlice = params.size.x * params.size.y;
|
|
212
|
+
return ijkPos.x + ijkPos.y * params.size.x + ijkPos.z * numPixelsPerSlice;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
fn updateBounds(position: vec3i) {
|
|
216
|
+
// Atomically update min bounds (use min operation)
|
|
217
|
+
let oldMinX = atomicMin(&modifiedBounds.minX, position.x);
|
|
218
|
+
let oldMinY = atomicMin(&modifiedBounds.minY, position.y);
|
|
219
|
+
let oldMinZ = atomicMin(&modifiedBounds.minZ, position.z);
|
|
220
|
+
|
|
221
|
+
// Atomically update max bounds (use max operation)
|
|
222
|
+
let oldMaxX = atomicMax(&modifiedBounds.maxX, position.x);
|
|
223
|
+
let oldMaxY = atomicMax(&modifiedBounds.maxY, position.y);
|
|
224
|
+
let oldMaxZ = atomicMax(&modifiedBounds.maxZ, position.z);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
@compute @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)
|
|
228
|
+
fn main(
|
|
229
|
+
@builtin(global_invocation_id) globalId: vec3u,
|
|
230
|
+
) {
|
|
231
|
+
// Make sure it will not get out of bounds for volume with sizes that
|
|
232
|
+
// are not multiple of workGroupSize
|
|
233
|
+
if (
|
|
234
|
+
globalId.x >= params.size.x ||
|
|
235
|
+
globalId.y >= params.size.y ||
|
|
236
|
+
globalId.z >= params.size.z
|
|
237
|
+
) {
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// Initialize bounds for the first iteration
|
|
242
|
+
if (params.iteration == 0 && globalId.x == 0 && globalId.y == 0 && globalId.z == 0) {
|
|
243
|
+
// Initialize to opposite extremes to ensure any update will improve the bounds
|
|
244
|
+
atomicStore(&modifiedBounds.minX, i32(params.size.x));
|
|
245
|
+
atomicStore(&modifiedBounds.minY, i32(params.size.y));
|
|
246
|
+
atomicStore(&modifiedBounds.minZ, i32(params.size.z));
|
|
247
|
+
atomicStore(&modifiedBounds.maxX, -1);
|
|
248
|
+
atomicStore(&modifiedBounds.maxY, -1);
|
|
249
|
+
atomicStore(&modifiedBounds.maxZ, -1);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
let currentCoord = vec3i(globalId);
|
|
253
|
+
let currentPixelIndex = getPixelIndex(globalId);
|
|
254
|
+
|
|
255
|
+
let numPixels = arrayLength(&volumePixelData);
|
|
256
|
+
let currentPixelValue = volumePixelData[currentPixelIndex];
|
|
257
|
+
|
|
258
|
+
if (params.iteration == 0) {
|
|
259
|
+
// All non-zero initial labels are given maximum strength
|
|
260
|
+
strengthData[currentPixelIndex] = select(MAX_STRENGTH, 0., labelmap[currentPixelIndex] == 0);
|
|
261
|
+
|
|
262
|
+
// Update bounds for non-zero initial labels
|
|
263
|
+
if (labelmap[currentPixelIndex] != 0) {
|
|
264
|
+
updateBounds(currentCoord);
|
|
265
|
+
}
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// It should at least copy the values from previous state
|
|
270
|
+
var newLabel = prevLabelmap[currentPixelIndex];
|
|
271
|
+
var newStrength = prevStrengthData[currentPixelIndex];
|
|
272
|
+
|
|
273
|
+
let window = i32(ceil(f32(windowSize - 1) * .5));
|
|
274
|
+
let minWindow = -1i * window;
|
|
275
|
+
let maxWindow = 1i * window;
|
|
276
|
+
|
|
277
|
+
for (var k = minWindow; k <= maxWindow; k++) {
|
|
278
|
+
for (var j = minWindow; j <= maxWindow; j++) {
|
|
279
|
+
for (var i = minWindow; i <= maxWindow; i++) {
|
|
280
|
+
// Skip current voxel
|
|
281
|
+
if (i == 0 && j == 0 && k == 0) {
|
|
282
|
+
continue;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
let neighborCoord = currentCoord + vec3i(i, j, k);
|
|
286
|
+
|
|
287
|
+
// Boundary conditions. Do not grow outside of the volume
|
|
288
|
+
if (
|
|
289
|
+
neighborCoord.x < 0i || neighborCoord.x >= i32(params.size.x) ||
|
|
290
|
+
neighborCoord.y < 0i || neighborCoord.y >= i32(params.size.y) ||
|
|
291
|
+
neighborCoord.z < 0i || neighborCoord.z >= i32(params.size.z)
|
|
292
|
+
) {
|
|
293
|
+
continue;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
let neighborIndex = getPixelIndex(vec3u(neighborCoord));
|
|
297
|
+
let neighborPixelValue = volumePixelData[neighborIndex];
|
|
298
|
+
let prevNeighborStrength = prevStrengthData[neighborIndex];
|
|
299
|
+
let strengthCost = abs(neighborPixelValue - currentPixelValue);
|
|
300
|
+
let takeoverStrength = prevNeighborStrength - strengthCost;
|
|
301
|
+
|
|
302
|
+
if (takeoverStrength > newStrength) {
|
|
303
|
+
newLabel = prevLabelmap[neighborIndex];
|
|
304
|
+
newStrength = takeoverStrength;
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
if (labelmap[currentPixelIndex] != newLabel) {
|
|
311
|
+
atomicAdd(&updatedVoxelsCounter[params.iteration], 1u);
|
|
312
|
+
|
|
313
|
+
// Update bounds for modified voxels
|
|
314
|
+
updateBounds(currentCoord);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
labelmap[currentPixelIndex] = newLabel;
|
|
318
|
+
strengthData[currentPixelIndex] = newStrength;
|
|
319
|
+
}
|
|
320
|
+
`,CN=1024*1024*1024,wp=1.99*CN,mu={windowSize:3,maxProcessingTime:3e4,inspection:{numCyclesInterval:5,numCyclesBelowThreshold:3,threshold:1e-4}};async function Pd(i,t,n=mu){const e=[8,8,4],{windowSize:o,maxProcessingTime:s}=Object.assign({},mu,n),a=Object.assign({},mu.inspection,n.inspection),r=Q.getVolume(i),c=Q.getVolume(t),[l,d,u]=r.dimensions;if(c.dimensions[0]!==l||c.dimensions[1]!==d||c.dimensions[2]!==u)throw new Error("Volume and labelmap must have the same size");let h=Math.floor(Math.sqrt(d**2+l**2+u**2)/2);h=Math.min(h,500);const f=c.voxelManager.getCompleteScalarDataArray();let g=r.voxelManager.getCompleteScalarDataArray();g instanceof Float32Array||(g=new Float32Array(g));const m={maxStorageBufferBindingSize:wp,maxBufferSize:wp},v=await(await navigator.gpu?.requestAdapter()).requestDevice({requiredLimits:m}),I=g.byteLength,w=h*Uint32Array.BYTES_PER_ELEMENT,C=6*Int32Array.BYTES_PER_ELEMENT,S=v.createShaderModule({code:SN}),b=3,_=new Uint32Array([l,d,u,0]),y=v.createBuffer({size:_.byteLength,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),D=v.createBuffer({size:I,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST});v.queue.writeBuffer(D,0,g);const T=[0,1].map(()=>v.createBuffer({size:I,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST}));v.queue.writeBuffer(T[0],0,new Uint32Array(f));const P=[0,1].map(()=>v.createBuffer({size:I,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST})),x=v.createBuffer({size:w,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST}),M=v.createBuffer({size:C,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST}),L=new Int32Array([l,d,u,-1,-1,-1]);v.queue.writeBuffer(M,0,L);const R=v.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}},{binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:3,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:4,visibility:GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}},{binding:5,visibility:GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}},{binding:6,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:7,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}}]}),U=[0,1].map(Zt=>{const ce=T[Zt],Ut=P[Zt],Ht=T[(Zt+1)%2],Jt=P[(Zt+1)%2];return v.createBindGroup({layout:R,entries:[{binding:0,resource:{buffer:y}},{binding:1,resource:{buffer:D}},{binding:2,resource:{buffer:ce}},{binding:3,resource:{buffer:Ut}},{binding:4,resource:{buffer:Ht}},{binding:5,resource:{buffer:Jt}},{binding:6,resource:{buffer:x}},{binding:7,resource:{buffer:M}}]})}),W=v.createComputePipeline({layout:v.createPipelineLayout({bindGroupLayouts:[R]}),compute:{module:S,entryPoint:"main",constants:{workGroupSizeX:e[0],workGroupSizeY:e[1],workGroupSizeZ:e[2],windowSize:o}}}),K=[Math.ceil(l/e[0]),Math.ceil(d/e[1]),Math.ceil(u/e[2])],j=v.createBuffer({size:w,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),F=s?performance.now()+s:0;let z=a.numCyclesInterval,q=0;for(let Zt=0;Zt<h;Zt++){_[b]=Zt,v.queue.writeBuffer(y,0,_);const ce=v.createCommandEncoder(),Ut=ce.beginComputePass();if(Ut.setPipeline(W),Ut.setBindGroup(0,U[Zt%2]),Ut.dispatchWorkgroups(K[0],K[1],K[2]),Ut.end(),ce.copyBufferToBuffer(x,Zt*Uint32Array.BYTES_PER_ELEMENT,j,Zt*Uint32Array.BYTES_PER_ELEMENT,Uint32Array.BYTES_PER_ELEMENT),v.queue.submit([ce.finish()]),Zt>0&&!(Zt%z)){await j.mapAsync(GPUMapMode.READ,0,w);const Jt=j.getMappedRange(0,w),De=new Uint32Array(Jt.slice(0))[Zt]/g.length;if(j.unmap(),Zt>=1&&De<a.threshold){if(z=1,q++,q===a.numCyclesBelowThreshold)break}else z=a.numCyclesInterval}if(F&&performance.now()>F){console.warn(`Exceeded processing time limit (${s})ms`);break}}const J=v.createCommandEncoder(),it=(h+1)%2,tt=v.createBuffer({size:I,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),ot=v.createBuffer({size:C,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST});J.copyBufferToBuffer(T[it],0,tt,0,I),J.copyBufferToBuffer(M,0,ot,0,C),v.queue.submit([J.finish()]),await tt.mapAsync(GPUMapMode.READ,0,I);const nt=tt.getMappedRange(0,I),lt=new Uint32Array(nt);f.set(lt),tt.unmap(),await ot.mapAsync(GPUMapMode.READ,0,C);const rt=ot.getMappedRange(0,C),ut=new Int32Array(rt.slice(0));ot.unmap();const Tt=ut[0],kt=ut[1],Pt=ut[2],te=ut[3],Ie=ut[4],re=ut[5];c.voxelManager.setCompleteScalarDataArray(f),c.voxelManager.clearBounds(),c.voxelManager.setBounds([[Tt,te],[kt,Ie],[Pt,re]])}const{transformWorldToIndex:Lr}=oe,bN=254,_N=255,yN=.1,xN=.8;function PN(i,t){const{topLeftWorld:n,bottomRightWorld:e}=t,o=Lr(i.imageData,n),s=Lr(i.imageData,e);return{...t,topLeftIJK:o,bottomRightIJK:s}}function DN(i,t){const n=i.imageData.getDirection(),e=Ot(n[3],n[4],n[5]),{center:o,radius:s}=t,a=i.imageData,r=ee(B(),o,e,-s),c=ee(B(),o,e,s),l=Z1([c,r],a);return PN(i,l)}function TN(i,t,n){const e=i.imageData,o=ht(n),{ijkVecRowDir:s,ijkVecColDir:a}=Rh(e,o);if([s,a].some(d=>!ve(Math.abs(d[0]),1)&&!ve(Math.abs(d[1]),1)&&!ve(Math.abs(d[2]),1))){console.warn("Oblique view is not supported!");return}const{boundsIJK:c}=DN(i,t),l={minX:c[0][0],maxX:c[0][1]+1,minY:c[1][0],maxY:c[1][1]+1,minZ:c[2][0],maxZ:c[2][1]+1};return Mv(i.volumeId,l,{targetBuffer:{type:"Float32Array"}})}function MN(i,t,n,e){const o=i.voxelManager.getCompleteScalarDataArray(),s=n.center,[a,r,c]=i.dimensions,l=a*r,d=Lr(i.imageData,s),u=o[d[2]*l+d[1]*a+d[0]],h=e.positiveSeedValue??bN,f=e.positiveSeedVariance??yN,g=Math.abs(u*f),m=u-g,p=u+g,v=[[-1,0,0],[1,0,0],[0,-1,0],[0,1,0],[0,0,-1],[0,0,1]],I=d[2]*l+d[1]*a+d[0];t.voxelManager.setAtIndex(I,h);const w=[d];for(;w.length;){const C=w.shift(),[S,b,_]=C;for(let y=0,D=v.length;y<D;y++){const T=v[y],P=S+T[0],x=b+T[1],M=_+T[2];if(P<0||P>=a||x<0||x>=r||M<0||M>=c)continue;const L=M*l+x*a+P,R=o[L];t.voxelManager.getAtIndex(L)===h||R<m||R>p||(t.voxelManager.setAtIndex(L,h),w.push([P,x,M]))}}}function AN(i,t,n,e,o){const s=i.voxelManager.getCompleteScalarDataArray(),[a,r,c]=t.dimensions,l=a*r,{worldVecRowDir:d,worldVecSliceDir:u}=Rh(t.imageData,ht(e)),h=Lr(i.imageData,n.center),f=s[h[2]*a*r+h[1]*a+h[0]],g=o.negativeSeedVariance??xN,m=o?.negativeSeedValue??_N,p=Math.abs(f*g),v=f-p,I=f+p,w=360,C=2*Math.PI/w,S=PI(as(),u,C),b=ho(d);for(let _=0;_<w;_++){const y=ee(B(),n.center,b,n.radius),D=Lr(t.imageData,y),[T,P,x]=D;if(Rv(b,b,S),T<0||T>=a||P<0||P>=r||x<0||x>=c)continue;const M=T+P*a+x*l,L=s[M];(L<v||L>I)&&t.voxelManager.setAtIndex(M,m)}}async function LN(i,t,n,e){const o=await Xr(i.volumeId);return MN(i,o,t,e),AN(i,o,t,n,e),o}async function OE(i,t,n,e){const o=Q.getVolume(i),s=TN(o,t,n),a=await LN(s,t,n,e);return await Pd(s.volumeId,a.volumeId),a}const ON=254,RN=255,NN=[-1/0,-995],kN=[0,1900];function UN(i,t,n){const{negativeSeedValue:e=RN,negativePixelRange:o=NN}=n,s=i.voxelManager.getCompleteScalarDataArray(),[a,r,c]=t.dimensions,l=Math.floor(c/2),d=new Array(a*r).fill(!1),u=l*a*r,h=(g,m)=>{const p=[[g,m]];for(;p.length;){const[v,I]=p.shift(),w=I*a+v;if(v<0||v>=a||I<0||I>=r||d[w])continue;d[w]=!0;const C=u+w,S=s[C];S<o[0]||S>o[1]||(t.voxelManager.setAtIndex(C,e),p.push([v-1,I]),p.push([v+1,I]),p.push([v,I-1]),p.push([v,I+1]))}},f=(g,m,p,v)=>{for(let I=g;I!==m;I+=p){const w=v*a+I,C=u+w,S=s[C];if(S<o[0]||S>o[1])break;d[w]||h(I,v)}};for(let g=0;g<r;g++)f(0,a-1,1,g),f(a-1,0,-1,g)}function VN(i,t,n){const{positiveSeedValue:e=ON,positivePixelRange:o=kN}=n,s=i.voxelManager.getCompleteScalarDataArray();t.voxelManager.getCompleteScalarDataArray();const[a,r,c]=t.dimensions,l=Math.floor(c/2),d=Math.max(l-3,0),u=Math.max(d+5,c),h=a*r;for(let f=d;f<u;f++){const g=f*h;for(let m=0;m<r;m++){const p=m*a;for(let v=0;v<a;v++){const I=g+p+v,w=s[I];w>=o[0]&&w<=o[1]&&t.voxelManager.setAtIndex(I,e)}}}}async function FN(i,t){const n=Xr(i.volumeId);return VN(i,n,t),UN(i,n,t),n}async function RE(i,t,n){const{boundingBox:e}=t,{ijkTopLeft:o,ijkBottomRight:s}=e,a={minX:o[0],maxX:s[0],minY:o[1],maxY:s[1],minZ:o[2],maxZ:s[2]},r=Mv(i,a,{targetBuffer:{type:"Float32Array"}}),c=await FN(r,n);return await Pd(r.volumeId,c.volumeId),c}const GN=254,HN=255,qf=1,gc=1.8,WN=3.2,ch=30,BN=70,zN=50,{transformWorldToIndex:$N}=oe,ir=1e5;function NE(i,t,n){const{dimensions:e,imageData:o}=i,[s,a,r]=e,c=i.voxelManager,l=c.getCompleteScalarDataArray(),d=s*a,u=n?.initialNeighborhoodRadius??qf,h=n?.positiveStdDevMultiplier??gc,f=n?.negativeStdDevMultiplier??WN,g=n?.negativeSeedMargin??ch,m=n?.negativeSeedsTargetPatches??BN,p=$N(o,t).map(Math.round),v=c.toIndex(p);if(p[0]<0||p[0]>=s||p[1]<0||p[1]>=a||p[2]<0||p[2]>=r)return console.warn("Click position is outside volume bounds."),null;const I=db(l,e,p,u);I.count===0&&(I.mean=l[v],I.stdDev=0);const w=I.mean-h*I.stdDev,C=I.mean+h*I.stdDev,S=[[-1,0,0],[1,0,0],[0,-1,0],[0,1,0],[0,0,-1],[0,0,1]];let b=1/0,_=1/0,y=1/0,D=-1/0,T=-1/0,P=-1/0;const x=new Set,M=[],L=l[v];if(L>=w&&L<=C)x.add(v),M.push(p),b=D=p[0],_=T=p[1],y=P=p[2];else return console.warn("Clicked voxel intensity is outside the calculated positive range. No positive seeds generated."),{positiveSeedIndices:new Set,negativeSeedIndices:new Set};let R=0;for(;R<M.length&&x.size<ir;){const[Pt,te,Ie]=M[R++];b=Math.min(Pt,b),_=Math.min(te,_),y=Math.min(Ie,y),D=Math.max(Pt,D),T=Math.max(te,T),P=Math.max(Ie,P);for(let re=0;re<S.length;re++){const[Zt,ce,Ut]=S[re],Ht=Pt+Zt,Jt=te+ce,Pe=Ie+Ut;if(Ht<0||Ht>=s||Jt<0||Jt>=a||Pe<0||Pe>=r)continue;const De=Pe*d+Jt*s+Ht;if(x.has(De))continue;const ln=l[De];ln>=w&&ln<=C&&(x.add(De),x.size<ir&&M.push([Ht,Jt,Pe]))}}if(x.size>=ir&&console.debug(`Reached maximum number of positive seeds (${ir}). Stopping BFS.`),x.size===0)return console.warn("No positive seeds found after BFS."),{positiveSeedIndices:new Set,negativeSeedIndices:new Set};let U=0,W=0;x.forEach(Pt=>{const te=l[Pt];U+=te,W+=te*te});const K=x.size,j=U/K,F=W/K-j*j,z=Math.sqrt(Math.max(0,F)),q=f*z,J=Math.max(0,b-g),it=Math.max(0,_-g),tt=Math.max(0,y-g),ot=Math.min(s-1,D+g),nt=Math.min(a-1,T+g),lt=Math.min(r-1,P+g),rt=new Set;let ut=0,Tt=0;const kt=m*zN;for(;Tt<m&&ut<kt;){ut++;const Pt=Math.floor(Math.random()*(ot-J+1)+J),te=Math.floor(Math.random()*(nt-it+1)+it),Ie=Math.floor(Math.random()*(lt-tt+1)+tt),re=Ie*d+te*s+Pt;if(x.has(re)||rt.has(re))continue;const Zt=l[re];if(Math.abs(Zt-j)>q){let ce=!1;for(let Ut=-1;Ut<=1;Ut++){const Ht=te+Ut;if(!(Ht<0||Ht>=a))for(let Jt=-1;Jt<=1;Jt++){const Pe=Pt+Jt;if(Pe<0||Pe>=s)continue;const De=Ie*d+Ht*s+Pe;x.has(De)||rt.has(De)||(rt.add(De),ce=!0)}}ce&&Tt++}}return rt.size===0&&console.warn("Could not find any negative seeds. GrowCut might fail or produce poor results."),console.debug("positiveSeedIndices",x.size),console.debug("negativeSeedIndices",rt.size),{positiveSeedIndices:x,negativeSeedIndices:rt}}async function kE({referencedVolumeId:i,worldPosition:t,options:n}){const e=Q.getVolume(i),o=Xr(i);o.voxelManager.forEach(({index:d,value:u})=>{u!==0&&o.voxelManager.setAtIndex(d,0)});const s=n.seeds??NE(e,t,n),a=n?.positiveSeedValue??GN,r=n?.negativeSeedValue??HN;if(!s)return null;const{positiveSeedIndices:c,negativeSeedIndices:l}=s;return c.size<10||c.size>ir||l.size<10?(console.warn("Not enough seeds found. GrowCut might fail or produce poor results."),o):(c.forEach(d=>{o.voxelManager.setAtIndex(d,a)}),l.forEach(d=>{o.voxelManager.setAtIndex(d,r)}),await Pd(i,o.volumeId,n),o)}const jN=Object.freeze(Object.defineProperty({__proto__:null,run:Pd,runGrowCutForBoundingBox:RE,runGrowCutForSphere:OE,runOneClickGrowCut:kE},Symbol.toStringTag,{value:"Module"}));function Or(i,t){const n=Dt(i);if(typeof t=="string"&&(console.warn("segmentIndex is a string, converting to number"),t=Number(t)),Object.values(n.segments).forEach(o=>{o.active=!1}),!n.segments[t]&&(n.segments[t]={segmentIndex:t,label:"",locked:!1,cachedStats:{},active:!1},n.representationData?.Labelmap)){kn(n);const o=cn(n)[0];o&&(cr(n,t,{labelmapId:o.labelmapId,labelValue:t}),pi(n))}if(n.representationData?.Labelmap&&!Hi(n,t)){kn(n);const o=cn(n)[0];o&&(cr(n,t,{labelmapId:o.labelmapId,labelValue:t}),pi(n))}n.segments[t].active!==!0&&(n.segments[t].active=!0,Co(i));const e=_s(i);e.forEach(o=>{Rn(o,{segmentationId:i}).forEach(a=>{a.segments[t]||(a.segments[t]={visible:!0})})}),e.forEach(o=>{const s=Ae(o);s&&TE(s.id)})}const XN=Object.freeze(Object.defineProperty({__proto__:null,getActiveSegmentIndex:xn,setActiveSegmentIndex:Or},Symbol.toStringTag,{value:"Module"}));function qN(i,t){const{segmentationId:n,config:e}=t;if(!zw(le(i)?.viewport,n,t.type)){console.warn(`Skipping ${t.type} representation of segmentation "${n}" on viewport "${i}": the viewport is not a compatible destination for it.`);return}const o={colorLUTIndex:YN(e),...e};me.addSegmentationRepresentation(i,n,t.type,o);const{viewport:s}=le(i)||{};if(s&&Tf(s,n,t.type),!xn(n)){let a=1;const r=me.getSegmentation(n);if(r){const c=Object.keys(r.segments);c.length>0&&(a=c.map(l=>Number(l)).sort()[0]),Or(n,a)}}t.type===St.Contour&&V([i]),t.type===St.Surface&&He(n),Co(n)}function YN(i){const{colorLUTOrIndex:t}=i||{};return t===void 0?lr(Re(ia)):typeof t=="number"?t:Array.isArray(t)&&t.every(e=>Array.isArray(e)&&e.length===4)?lr(t):lr(Re(ia))}function Oa(i,t){t.map(n=>qN(i,n))}function Yf(i,t){return Oa(i,t.map(n=>({...n,type:St.Contour})))}function KN(i){const t={};for(const[n,e]of Object.entries(i))t[n]=Yf(n,e);return t}function UE(i,t){return Oa(i,t.map(n=>({...n,type:St.Labelmap})))}function ZN(i){for(const[t,n]of Object.entries(i))UE(t,n.map(e=>({...e,type:St.Labelmap})))}function VE(i,t){return Oa(i,t.map(n=>({...n,type:St.Surface})))}function JN(i){const t={};for(const[n,e]of Object.entries(i))t[n]=VE(n,e);return t}async function QN({segmentationId:i,viewportId:t,imageIds:n,options:e}){const o=Dt(i);if(e?.removeOriginal){const s=o.representationData.Labelmap;Q.getVolume(s.volumeId)&&Q.removeVolumeLoadObject(s.volumeId),o.representationData.Labelmap={imageIds:n}}else o.representationData.Labelmap={...o.representationData.Labelmap,imageIds:n};await Oa(t,[{segmentationId:i,type:St.Labelmap}]),Z.addEventListenerOnce(E.SEGMENTATION_RENDERED,()=>He(i))}async function tk({volumeId:i}){return{imageIds:Q.getVolume(i).imageIds}}function ek({segmentationId:i,options:t}){const n=Dt(i);if(!n)return;const{volumeId:e}=n.representationData.Labelmap,o=Q.getVolume(e);return QN({segmentationId:i,viewportId:t.viewportId,imageIds:o.imageIds,options:t})}async function FE(i){return jI(i)}function GE(i){const t=Dt(i);if(!t)return null;let n;const e=t.representationData.Labelmap;if("imageIds"in e){const{imageIds:o}=e,s=Q.getImage(o[0]),a=Q.getVolumeContainingImageId(s.referencedImageId);if(a?.volume)return a.volume;n=o.map(r=>Q.getImage(r).referencedImageId)}else if(e.volumeId){const{volumeId:o,referencedVolumeId:s}=e;if(s){const r=Q.getVolume(s);if(r)return r}const a=Q.getVolume(o);a&&(n=a.imageIds.map(r=>Q.getImage(r).referencedImageId))}return vd(n)}async function nk({segmentationId:i,segmentIndices:t,mode:n="individual"}){md(),Zo(no.COMPUTE_LARGEST_BIDIRECTIONAL,0);const e=Lw(i,t);if(!e)return;const{operationData:o,segImageIds:s,reconstructableVolume:a,indices:r}=e,c=a?await ok({operationData:o,indices:r,mode:n}):await ik({segImageIds:s,indices:r,mode:n});return Zo(no.COMPUTE_LARGEST_BIDIRECTIONAL,100),c}async function ok({operationData:i,indices:t,mode:n}){const e=Ow(i),{segmentationVoxelManager:o,segmentationImageData:s}=e,r={scalarData:o.getCompleteScalarDataArray(),dimensions:s.getDimensions(),spacing:s.getSpacing(),origin:s.getOrigin(),direction:s.getDirection()};return await Es().executeTask("compute","getSegmentLargestBidirectionalInternal",{segmentationInfo:r,indices:t,mode:n})}async function ik({segImageIds:i,indices:t,mode:n}){const{segmentationInfo:e}=Rw(i);return await Es().executeTask("compute","getSegmentLargestBidirectionalInternal",{segmentationInfo:e,indices:t,mode:n,isStack:!0})}async function sk({segmentationIds:i,segmentIndex:t}){md(),Zo(no.COMPUTE_STATISTICS,0);const n=Dt(i[0]),{imageIds:e}=n.representationData.Labelmap;if(!Ss(e))throw new Error("Invalid volume - TMTV cannot be calculated");return await ak({segmentationIds:i,segmentIndex:t})}async function ak({segmentationIds:i,segmentIndex:t}){const n=i.map(m=>Ma(m)),e=aE(n,t);if(!e)throw new Error("Invalid volume - TMTV cannot be calculated");const{imageData:o,dimensions:s,direction:a,origin:r,voxelManager:c}=e,l=o.getSpacing(),u={scalarData:c.getCompleteScalarDataArray(),dimensions:s,spacing:l,origin:r,direction:a},h=GE(i[0]),f={dimensions:h.dimensions,spacing:h.spacing,origin:h.origin,direction:h.direction,scalarData:h.voxelManager.getCompleteScalarDataArray()};if(f.scalarData.length===0||u.scalarData.length===0)return{[t]:{name:"TMTV",value:0}};const g=await Es().executeTask("compute","computeMetabolicStats",{segmentationInfo:u,imageInfo:f});return Zo(no.COMPUTE_STATISTICS,100),g}const rk=Object.freeze(Object.defineProperty({__proto__:null,IslandRemoval:zi,LabelmapMemo:xR,SegmentStatsCalculator:xd,VolumetricCalculator:sa,computeMetabolicStats:sk,computeStackLabelmapFromVolume:tk,computeVolumeLabelmapFromStack:FE,contourAndFindLargestBidirectional:PE,createBidirectionalToolData:DE,createLabelmapVolumeForViewport:eR,createMergedLabelmapForIndex:aE,floodFill:$f,getBrushSizeForToolGroup:iN,getBrushThresholdForToolGroup:aN,getBrushToolInstances:La,getHoveredContourSegmentationAnnotation:LE,getOrCreateImageVolume:vd,getOrCreateSegmentationVolume:Ma,getReferenceVolumeForSegmentation:GE,getReferenceVolumeForSegmentationVolume:Tw,getSegmentIndexAtLabelmapBorder:ME,getSegmentIndexAtWorldPoint:Xf,getSegmentLargestBidirectional:nk,getStatistics:dE,getUniqueSegmentIndices:R1,growCut:jN,invalidateBrushCursor:TE,rectangleROIThresholdVolumeByRange:Q2,segmentContourAction:mN,setBrushSizeForToolGroup:oN,setBrushThresholdForToolGroup:sN,thresholdSegmentationByRange:rN,thresholdVolumeByRange:Q1,triggerSegmentationRender:_i,triggerSegmentationRenderBySegmentationId:Nf,validateLabelmap:qM},Symbol.toStringTag,{value:"Module"})),ck=1e-10;function Ep(i){return Array.isArray(i)&&i.length===3&&i.every(t=>Number.isFinite(t))}function Do(i){if(!i)return null;let t;try{t=ht(i)}catch{return null}const n=t?.viewPlaneNormal,e=t?.focalPoint;if(!Ep(n)||!Ep(e)||mn(n)<ck)return null;const o=Wt(B(),n);return{normal:[o[0],o[1],o[2]],point:[e[0],e[1],e[2]]}}const Sp=1e-6;function lh(i,t){if(!i||!t)return null;const n=Wt(B(),i.normal),e=Wt(B(),t.normal),o=Me(B(),n,e),s=Nv(o);if(s<Sp*Sp)return null;const a=xt(n,i.point),r=xt(e,t.point),c=Me(B(),e,o),l=Me(B(),o,n),d=B();return ee(d,d,c,a),ee(d,d,l,r),bn(d,d,1/s),Wt(o,o),[...d,...o].every(u=>Number.isFinite(u))?{point:[d[0],d[1],d[2]],direction:[o[0],o[1],o[2]]}:null}function Ia(i,t){const n=Wt(B(),t.normal),e=Oe(B(),i,t.point);return xt(e,n)}function dh(i,t){const n=Wt(B(),t.normal),e=Ia(i,t);return[i[0]-e*n[0],i[1]-e*n[1],i[2]-e*n[2]]}function Kf(i){if(ie(i)){const{element:e}=i;return{clientWidth:e?.clientWidth??0,clientHeight:e?.clientHeight??0}}const{clientWidth:t=0,clientHeight:n=0}=i.canvas??{};return{clientWidth:t,clientHeight:n}}const lk=.001;function uh(i,t){if(!i||!t)return null;const{clientWidth:n,clientHeight:e}=Kf(t);if(!n||!e)return null;const o=Wt(B(),i.direction);if(mn(o)<1e-10)return null;const s=t.canvasToWorld([n/2,e/2]),a=Oe(B(),s,i.point),r=xt(a,o),c=ee(B(),i.point,o,r),l=t.canvasToWorld([0,0]),d=ke(s,l),u=Math.max(d*2,1),h=ee(B(),c,o,-u),f=ee(B(),c,o,u),g=t.worldToCanvas([h[0],h[1],h[2]]),m=t.worldToCanvas([f[0],f[1],f[2]]);if(![...g,...m].every(C=>Number.isFinite(C)))return null;const p=[g[0],g[1]],v=[m[0],m[1]];return li(p,v,[0,0,n,e])!==1||Math.hypot(v[0]-p[0],v[1]-p[1])<lk?null:[p,v]}function Cp(i){return i.getFrameOfReferenceUID?.()}function dk(i,t,n){const{registrationTransforms:e}=n;return e?.size?e.has(`${i}:${t}`)||e.has(`${t}:${i}`):!1}function uk(i,t,n){if(!i||!t||!n?.policy)return!1;switch(n.policy){case"frameOfReferenceUID":{const e=Cp(i),o=Cp(t);return!e||!o?!1:e===o?!0:dk(e,o,n)}case"explicit":{const{explicitLinks:e}=n;return e?.length?e.some(o=>o.sourceViewportId===i.id&&o.targetViewportId===t.id||o.sourceViewportId===t.id&&o.targetViewportId===i.id):!1}case"toolGroup":{const e=Ae(i.id,i.renderingEngineId),o=Ae(t.id,t.renderingEngineId);return!!e&&!!o&&e.id===o.id}default:return!1}}const{RENDERING_DEFAULTS:hk}=Qo;function pu(i){return ie(i)?hk.MINIMUM_SLAB_THICKNESS:i.getSlabThickness()}function yl(i,t){ie(i)&&i.setViewReference({cameraFocalPoint:t})}function Rr(i,t){if(!ie(i))return!1;if(i.getCurrentMode?.()==="stack"){const e=i;if(typeof e.getImageIds!="function"||typeof e.getCurrentImageIdIndex!="function")return!1;let o=null;try{o=Oh(t,e)}catch{return!1}return o===null||o<0?!1:(i.setViewReference({sliceIndex:o}),!0)}return i.setViewReference({cameraFocalPoint:[t[0],t[1],t[2]]}),!0}function Nr(i){if(!Sa(i))return{properties:{}};const t=i.getSourceDataId(),n={...(t?i.getDisplaySetPresentation(t):{})??{}},e=n.VOILUTFunction??n.voiLUTFunction;e!==void 0&&(n.VOILUTFunction=e);const o=Aa(i)??{};return{properties:n,rotation:o.rotation,flipHorizontal:o.flipHorizontal,flipVertical:o.flipVertical,currentImageId:i.getCurrentImageId()}}function HE(i,t){if(!i||!Number.isFinite(t)||t===0)return!1;let n;try{n=ht(i)}catch{return!1}const e=n?.viewPlaneNormal,o=n?.focalPoint,s=n?.position;if(!e||!o||!s)return!1;const a=ee(B(),o,e,t),r=ee(B(),s,e,t);return ie(i)?Rr(i,[a[0],a[1],a[2]]):(i.setCamera({focalPoint:[a[0],a[1],a[2]],position:[r[0],r[1],r[2]]}),!0)}function fk(i,t,n,e){if(!i||!t||!n||!Number.isFinite(e)||e===0||ie(i))return!1;const o=Wt(B(),n);if(mn(o)<1e-10)return!1;const s=i.getCamera?.(),{position:a,focalPoint:r,viewUp:c}=s??{};if(!a||!r||!c)return!1;const l=qi();fo(l,l,t),go(l,l,e,o),fo(l,l,[-t[0],-t[1],-t[2]]);const d=Ue(B(),a,l),u=Ue(B(),r,l),h=yn(B(),a,c),f=Ue(B(),h,l),g=Oe(B(),f,d);return i.setCamera({position:[d[0],d[1],d[2]],focalPoint:[u[0],u[1],u[2]],viewUp:[g[0],g[1],g[2]]}),!0}const gk=Object.freeze(Object.defineProperty({__proto__:null,areViewportsSpatiallyLinked:uk,clipWorldLineToViewportCanvas:uh,distancePointToPlane:Ia,getDisplayedCanvasSize:Kf,getViewportPlane:Do,intersectPlanes:lh,projectPointToPlane:dh,rotateViewportAroundWorldPoint:fk,translateViewportAlongNormal:HE},Symbol.toStringTag,{value:"Module"}));function mk(i){let t="";const n=i[0]<0?"R":"L",e=i[1]<0?"A":"P",o=i[2]<0?"F":"H",s=[Math.abs(i[0]),Math.abs(i[1]),Math.abs(i[2])],a=1e-4;for(let r=0;r<3;r++)if(s[0]>a&&s[0]>s[1]&&s[0]>s[2])t+=n,s[0]=0;else if(s[1]>a&&s[1]>s[0]&&s[1]>s[2])t+=e,s[1]=0;else if(s[2]>a&&s[2]>s[0]&&s[2]>s[1])t+=o,s[2]=0;else if(s[0]>a&&s[1]>a&&s[0]===s[1])t+=n+e,s[0]=0,s[1]=0;else if(s[0]>a&&s[2]>a&&s[0]===s[2])t+=n+o,s[0]=0,s[2]=0;else if(s[1]>a&&s[2]>a&&s[1]===s[2])t+=e+o,s[1]=0,s[2]=0;else break;return t}function pk(i){let t=i.replace("H","f");return t=t.replace("F","h"),t=t.replace("R","l"),t=t.replace("L","r"),t=t.replace("A","p"),t=t.replace("P","a"),t=t.toUpperCase(),t}const vk=Object.freeze(Object.defineProperty({__proto__:null,getOrientationStringLPS:mk,invertOrientationStringLPS:pk},Symbol.toStringTag,{value:"Module"}));var ra;(function(i){i.CLIP_STOPPED="CORNERSTONE_CINE_TOOL_STOPPED",i.CLIP_STARTED="CORNERSTONE_CINE_TOOL_STARTED"})(ra||(ra={}));const Zf={};function WE(i,t){const n=N(i),{viewportId:e}=n;Zf[e]=t}function Jf(i){const t=N(i),{viewportId:n}=t;return Zf[n]}function Ik(i){return Zf[i]}const{ViewportStatus:Qf}=Ea,{triggerEvent:vu}=oe,tg=!0,hh=new Map;function wk(i,t){let n,e;if(i===void 0)throw new Error("playClip: element must not be undefined");const o=N(i);if(!o)throw new Error("playClip: element must be a valid Cornerstone enabled element");t||(t={}),t.dynamicCineEnabled=t.dynamicCineEnabled??!0;const{viewport:s}=o,a=xk(s,t);let r=Jf(i);const c=t.dynamicCineEnabled;if(c&&zE(i),r?fh(i,{stopDynamicCine:!c,viewportId:s.id}):(r={intervalId:void 0,framesPerSecond:30,lastFrameTimeStamp:void 0,ignoreFrameTimeVector:!1,usingFrameTimeVector:!1,frameTimeVector:t.frameTimeVector??void 0,speed:t.frameTimeVectorSpeedMultiplier??1,reverse:t.reverse??!1,loop:t.loop??!0,bounce:t.bounce??!1},WE(i,r)),r.dynamicCineEnabled=t.dynamicCineEnabled,(t.framesPerSecond<0||t.framesPerSecond>0)&&(r.framesPerSecond=Number(t.framesPerSecond),r.reverse=r.framesPerSecond<0,r.ignoreFrameTimeVector=!0),r.ignoreFrameTimeVector!==!0&&r.frameTimeVector&&r.frameTimeVector.length===a.numScrollSteps&&a.frameTimeVectorEnabled){const{timeouts:u,isTimeVarying:h}=Ek(r.frameTimeVector,r.speed);n=u,e=h}t.bounce!==void 0&&(r.bounce=t.bounce);const l=()=>{const{numScrollSteps:u,currentStepIndex:h}=a;let f=h+(r.reverse?-1:1);if(f<0||f>=u)if(r.bounce)r.reverse=!r.reverse,f=h+(r.reverse?-1:1),f=Math.max(0,Math.min(u-1,f));else if(r.loop)f=r.reverse?u-1:0;else{fh(i,{stopDynamicCine:!c,viewportId:s.id}),vu(i,ra.CLIP_STOPPED,{element:i});return}const m=f-h;if(m)try{a.scroll(m)}catch(p){console.warn("Play clip not scrolling",p),$E(r),vu(i,ra.CLIP_STOPPED,{element:i})}};if(c){const u=eg(s);u&&hh.set(u.volumeId,i)}a.play?r.framesPerSecond=a.play(t.framesPerSecond):n&&n.length>0&&e?(r.usingFrameTimeVector=!0,r.intervalId=window.setTimeout(function u(){r.intervalId=window.setTimeout(u,n[a.currentStepIndex]),l()},0)):(r.usingFrameTimeVector=!1,r.intervalId=window.setInterval(l,1e3/Math.abs(r.framesPerSecond)));const d={element:i};vu(i,ra.CLIP_STARTED,d)}function BE(i,t={}){fh(i,{stopDynamicCine:!0,...t})}function fh(i,t={stopDynamicCine:!0,viewportId:void 0}){const{stopDynamicCine:n,viewportId:e}=t,o=N(i);let s;const a=o?.viewport;if(o){const{viewport:r}=o;s=Jf(r.element)}else if(e)s=Ik(e);else return;s&&$E(s),a instanceof bv?a.pause():n&&a instanceof pn&&zE(i)}function zE(i){const{viewport:t}=N(i);if(t instanceof Xe){const n=eg(t);if(n?.isDynamicVolume()){const e=hh.get(n.volumeId);hh.delete(n.volumeId),e&&e!==i&&BE(e)}}}function Ek(i,t){let n,e,o,s=0;const a=i.length,r=[];let c=!1;for((typeof t!="number"||t<=0)&&(t=1),n=1;n<a;n++)o=Number(i[n])/t|0,r.push(o),n===1?e=o:o!==e&&(c=!0),s+=o;return r.length>0&&(c?o=s/r.length|0:o=r[0],r.push(o)),{timeouts:r,isTimeVarying:c}}function $E(i){const t=i.intervalId;typeof t<"u"&&(i.intervalId=void 0,i.usingFrameTimeVector?clearTimeout(t):clearInterval(t))}function eg(i){if(!(i instanceof Xe))return;const t=i.getAllVolumeIds();if(!t?.length)return;const e=t.find(o=>Q.getVolume(o)?.isDynamicVolume())??t[0];return Q.getVolume(e)}function Sk(i,t){const n=i.getImageIds();return{get numScrollSteps(){return n.length},get currentStepIndex(){return i.getTargetImageIdIndex()},get frameTimeVectorEnabled(){return!0},waitForRenderedCount:0,scroll(e){if(this.waitForRenderedCount<=t&&i.viewportStatus!==Qf.RENDERED){this.waitForRenderedCount++;return}this.waitForRenderedCount=0,da(i,{delta:e,debounceLoading:tg})}}}function Ck(i,t){return{get numScrollSteps(){return i.getNumberOfSlices()},get currentStepIndex(){return i.getSliceIndex()},get frameTimeVectorEnabled(){return!0},waitForRenderedCount:0,scroll(n){if(this.waitForRenderedCount<=t&&i.viewportStatus!==Qf.RENDERED){this.waitForRenderedCount++;return}this.waitForRenderedCount=0,da(i,{delta:n,debounceLoading:tg})},play(n){return n&&i.setPlaybackRate(n/24),i.play(),i.getFrameRate()}}}function bk(i,t){const{volumeId:n}=t,e={viewPlaneNormal:B(),scrollInfo:null},o=()=>{const s=i.getCamera();if(!e.scrollInfo||!mb(s.viewPlaneNormal,e.viewPlaneNormal)){const r=AC(i,n);e.viewPlaneNormal=s.viewPlaneNormal,e.scrollInfo=r}return e.scrollInfo};return{get numScrollSteps(){return o().numScrollSteps},get currentStepIndex(){return o().currentStepIndex},get frameTimeVectorEnabled(){const s=i.getCamera(),a=t.direction.slice(6,9).map(c=>-c),r=xt(a,s.viewPlaneNormal);return pr(r,1)},scroll(s){o().currentStepIndex+=s,da(i,{delta:s})}}}function _k(i){return{get numScrollSteps(){return i.numDimensionGroups},get currentStepIndex(){return i.dimensionGroupNumber-1},get frameTimeVectorEnabled(){return!1},scroll(t){i.scroll(t)}}}function yk(i,t){return{get numScrollSteps(){return i.getNumberOfSlices()},get currentStepIndex(){return i.getSliceIndex()},get frameTimeVectorEnabled(){return i.getCurrentMode()==="stack"},waitForRenderedCount:0,scroll(n){const e=i.viewportStatus;if(this.waitForRenderedCount<=t&&e!==void 0&&e!==Qf.RENDERED){this.waitForRenderedCount++;return}this.waitForRenderedCount=0,da(i,{delta:n,debounceLoading:tg})}}}function xk(i,t){if(i instanceof Pn)return Sk(i,t.waitForRendered??30);if(i instanceof Xe){const n=eg(i);return t.dynamicCineEnabled&&n?.isDynamicVolume()?_k(n):bk(i,n)}if(i instanceof bv)return Ck(i,t.waitForRendered??30);if(ie(i))return yk(i,t.waitForRendered??30);throw new Error("Unknown viewport type")}const Pk=Object.freeze(Object.defineProperty({__proto__:null,Events:ra,addToolState:WE,getToolState:Jf,playClip:wk,stopClip:BE},Symbol.toStringTag,{value:"Module"}));function jE(i,t,n,e=[.7,.7,.7],o="",s=!0){if(t[0]===n[0]&&t[1]===n[1]&&t[2]===n[2])return{actor:null,source:null};const a=Ul.newInstance();a.setNumberOfPoints(2),a.setPoint(0,t[0],t[1],t[2]),a.setPoint(1,n[0],n[1],n[2]);const r=la.newInstance({values:[2,0,1]}),c=Vo.newInstance();c.setPoints(a),c.setLines(r);const l=Oo.newInstance();l.setInputData(c);const d=vo.newInstance();return d.setMapper(l),d.getProperty().setColor(...e),d.getProperty().setLineWidth(.5),d.getProperty().setOpacity(1),d.getProperty().setInterpolationToFlat(),d.getProperty().setAmbient(1),d.getProperty().setDiffuse(0),d.getProperty().setSpecular(0),d.setVisibility(s),i.addActor({actor:d,uid:o}),{actor:d,source:c}}function XE(i,t){const n=t.sphereRadiusScale||.01,e=i*n,o=t.minSphereRadius||2,s=t.maxSphereRadius||50;return Math.max(o,Math.min(s,e))}const Dk=Object.freeze(Object.defineProperty({__proto__:null,addLine3DBetweenPoints:jE,calculateAdaptiveSphereRadius:XE},Symbol.toStringTag,{value:"Module"}));function Tk(i,t){const n=t?.knotsRatioPercentage||30;return!i?.data?.contour?.polyline?.length||n<=0}function Mk(i,t){const n=qi(),e=yn(B(),t,i),o=Math.abs(i[0])>.1?Ot(-i[1],i[0],0):Ot(0,-i[2],i[1]);return ey(n,t,e,o),n}function Lc(i,t=Math.floor(Math.random()*(i.length-1))){if(t===0)return 0;const n=[...i],{length:e}=i;for(let o=0;o<e;o++)i[o]=n[(o+t+e)%e];return t}function qE(i,t){if(Tk(i,t))return!1;const{viewPlaneNormal:n}=i.metadata,{closed:e,polyline:o}=i.data.contour,s=Mk(n,i.data.contour.polyline[0]),a=i.data.contour.polyline.map(d=>{const u=Ue(B(),d,s);return[u[0],u[1]]});let r=e?Lc(a):0,c=dl(a,0,a.length-1,t?.knotsRatioPercentage||30);if(c===a)return!1;Lc(c,-r);for(let d=1;d<t?.loop;d++)r=e?Lc(c):0,c=dl(c,0,c.length-1,t?.knotsRatioPercentage||30),Lc(c,-r);const l=K_(qi(),s);return i.data.contour.polyline=c.map(d=>Ue([0,0,0],[...d,0],l)),!0}const Ak={smoothAnnotation:qE},Lk=Object.freeze(Object.defineProperty({__proto__:null,default:Ak,smoothAnnotation:qE},Symbol.toStringTag,{value:"Module"})),{isEqual:Oc}=oe,Ok=Ot(1,0,0),Rk=Ot(0,1,0),Nk=Ot(0,0,1),bp=[Ok,Rk,Nk];function kk(i){const t=Oe(B(),i[0],i[1]),n=Oe(B(),i[0],i[2]),e=_p(t,bp),o=_p(n,bp);return[...e,...o].every(a=>Oc(a,0)||Oc(a,90)||Oc(a,180)||Oc(a,270))}function _p(i,t){return t.map(n=>pb(i,n)*180/Math.PI)}const Uk=Object.freeze(Object.defineProperty({__proto__:null,getBoundsIJKFromRectangleAnnotations:sE,isAxisAlignedRectangle:kk},Symbol.toStringTag,{value:"Module"})),YE={};function KE(i,t){const n=N(i),{viewportId:e}=n;YE[e]=t}function Ra(i){const t=N(i),{viewportId:n}=t;return YE[n]}const gs=LC.Prefetch,Vk=0;function Fk(i,t){i=Math.round(i)||0,t=Math.round(t)||0;const n=[];let e=t-i+1;if(e<=0)return n;for(;e--;)n[e]=t--;return n}function Gk(i,t){let n=0,e=i.length-1;return i.forEach((o,s)=>{o<t?n=Math.max(s,n):o>t&&(e=Math.min(s,e))}),{low:n,high:e}}function Na(i){const t=N(i);if(!t)return null;const{viewport:n}=t;return!Ds(n)||Sv(n)||OC(n)&&!ie(n)?null:{currentImageIdIndex:n.getCurrentImageIdIndex(),imageIds:n.getImageIds()}}function Dd(i){return function(t){const n=t.detail;let e;try{e=Na(i)}catch{return}if(!e||!e.imageIds||e.imageIds.length===0)return;const s=e.imageIds.indexOf(n.imageId);if(s<0)return;const a=Ra(i);!a||!a.indicesToRequest||!a.indicesToRequest.length||a.indicesToRequest.push(s)}}const Hk=i=>{const t=new Set(i.imageIds);return n=>n.type!==gs||!t.has(n.additionalDetails.imageId)},{imageRetrieveMetadataProvider:Wk}=oe;let ur={maxImagesToPrefetch:1/0,preserveExistingPool:!0},gh;const Bk=10;function ZE(i){const t=Ra(i);if(!t)return;const n=t||{},e=Na(i);if(!e?.imageIds?.length){console.warn("CornerstoneTools.stackPrefetch: No images in stack.");return}const{currentImageIdIndex:o}=e;if(n.enabled=n.enabled&&(n.indicesToRequest?.length??0)>0,n.enabled===!1)return;function s(m){const p=n.indicesToRequest.indexOf(m);p>-1&&n.indicesToRequest.splice(p,1)}if(t.indicesToRequest.sort((m,p)=>m-p),n.indicesToRequest.slice().forEach(function(m){const p=e.imageIds[m];if(!p)return;(Math.abs(o-m)<6?Q.getImageLoadObject(p):Q.isLoaded(p))&&s(m)}),!n.indicesToRequest.length)return;ur.preserveExistingPool||fr.clearRequestStack(gs);const r=Gk(n.indicesToRequest,e.currentImageIdIndex);let c,l;function d(m){const p=e.imageIds.indexOf(m);if(s(p),n.indicesToRequest.length===0){const v={element:i,lastPrefetchedImageId:m};Rt(Z,E.STACK_PREFETCH_COMPLETE,v)}}let u=r.low,h=r.high;const f=[];for(;u>=0||h<n.indicesToRequest.length;){const m=e.currentImageIdIndex,p=m-n.indicesToRequest[u]>ur.maxImagesToPrefetch,v=n.indicesToRequest[h]-m>ur.maxImagesToPrefetch,I=!p&&u>=0,w=!v&&h<n.indicesToRequest.length;if(!w&&!I)break;I&&(l=n.indicesToRequest[u--],c=e.imageIds[l],f.push(c)),w&&(l=n.indicesToRequest[h++],c=e.imageIds[l],f.push(c))}const g=(m,p)=>{const{retrieveOptions:v={}}=rn(Wk.IMAGE_RETRIEVE_CONFIGURATION,m,"stack")||{};return p.retrieveOptions={...p.retrieveOptions,...v.default||Object.values(v)?.[0]||{}},_v(m,p).then(()=>d(m))};f.forEach(m=>{const p={requestType:gs};fr.addRequest(g.bind(null,m,p),gs,{imageId:m},Vk)})}function mh(i){clearTimeout(gh),gh=setTimeout(function(){const t=i.target;try{ZE(t)}catch{return}},Bk)}function zk(i){const t=Na(i);if(!t||!t.imageIds||t.imageIds.length===0){console.warn("CornerstoneTools.stackPrefetch: No images in stack.");return}const n={indicesToRequest:Fk(0,t.imageIds.length-1),enabled:!0,direction:1},e=n.indicesToRequest.indexOf(t.currentImageIdIndex);n.indicesToRequest.splice(e,1),KE(i,n),ZE(i),i.removeEventListener(yt.STACK_NEW_IMAGE,mh),i.addEventListener(yt.STACK_NEW_IMAGE,mh);const o=Dd(i);Z.removeEventListener(yt.IMAGE_CACHE_IMAGE_REMOVED,o),Z.addEventListener(yt.IMAGE_CACHE_IMAGE_REMOVED,o)}function $k(i){clearTimeout(gh),i.removeEventListener(yt.STACK_NEW_IMAGE,mh);const t=Dd(i);Z.removeEventListener(yt.IMAGE_CACHE_IMAGE_REMOVED,t);const n=Ra(i);n&&n.indicesToRequest.length&&(n.enabled=!1,fr.clearRequestStack(gs))}function jk(){return ur}function Xk(i){ur=i}const qk={enable:zk,disable:$k,getConfiguration:jk,setConfiguration:Xk},{imageRetrieveMetadataProvider:Yk}=oe;let kr={maxImagesToPrefetch:1/0,minBefore:2,maxAfter:2,directionExtraImages:10,preserveExistingPool:!1},ph;const Kk=5,JE={},Zk=(i,t=0)=>{const n=Na(i);if(!n)return;if(!n.imageIds?.length){console.warn("CornerstoneTools.stackPrefetch: No images in stack.");return}og(i),JE[i]=t,ng(i,t),i.removeEventListener(yt.STACK_NEW_IMAGE,vh),i.addEventListener(yt.STACK_NEW_IMAGE,vh);const e=Dd(i);Z.removeEventListener(yt.IMAGE_CACHE_IMAGE_REMOVED,e),Z.addEventListener(yt.IMAGE_CACHE_IMAGE_REMOVED,e)};function ng(i,t=0){const n=Na(i);if(!n)return;if(!n?.imageIds?.length){console.warn("CornerstoneTools.stackPrefetch: No images in stack.");return}const e=Ra(i);if(!e)return;const o=e||{};if(o.enabled=o.enabled&&(o.indicesToRequest?.length??0)>0,o.enabled===!1)return;function s(d){const u=o.indicesToRequest.indexOf(d);u>-1&&o.indicesToRequest.splice(u,1)}const a=o.indicesToRequest.slice(),{currentImageIdIndex:r}=n;if(a.forEach(d=>{const u=n.imageIds[d];if(!u)return;(Math.abs(r-d)<6?Q.getImageLoadObject(u):Q.isLoaded(u))&&s(d)}),!o.indicesToRequest.length)return;kr.preserveExistingPool||fr.filterRequests(Hk(n));function c(d){const u=n.imageIds.indexOf(d);s(u);const h=Q.getCachedImageBasedOnImageURI(d),{stats:f}=o,g=h?.image?.decodeTimeInMS||0;if(g){f.imageIds.set(d,g),f.decodeTimeInMS+=g;const m=h?.image?.loadTimeInMS||0;f.loadTimeInMS+=m}if(!o.indicesToRequest.length&&h?.sizeInBytes){const{sizeInBytes:m}=h,p=Q.getMaxCacheSize()/4/m;if(!o.cacheFill)f.initialTime=Date.now()-f.start,f.initialSize=f.imageIds.size,og(i,p),ng(i,t);else if(f.imageIds.size){f.fillTime=Date.now()-f.start;const{size:v}=f.imageIds;f.fillSize=v}}if(o.indicesToRequest.length===0){const m={element:i,lastPrefetchedImageId:d};Rt(Z,E.STACK_PREFETCH_COMPLETE,m)}}const l=(d,u)=>{const{retrieveOptions:h={}}=rn(Yk.IMAGE_RETRIEVE_CONFIGURATION,d,"stack")||{};return u.retrieveOptions={...u.retrieveOptions,...h.default||Object.values(h)?.[0]||{}},_v(d,u).then(()=>c(d))};o.indicesToRequest.forEach(d=>{const u=n.imageIds[d],h={requestType:gs};fr.addRequest(l.bind(null,u,h),gs,{imageId:u},t)})}function vh(i){clearTimeout(ph),ph=setTimeout(function(){const t=i.target;try{og(t),ng(t,JE[t])}catch{return}},Kk)}const Jk=i=>i<0?-1:1,og=(i,t)=>{const n=Na(i);if(!n)return;if(!n.imageIds?.length){console.warn("CornerstoneTools.stackPrefetch: No images in stack.");return}const{currentImageIdIndex:e}=n;let{maxAfter:o=2,minBefore:s=2}=kr;const{directionExtraImages:a=10}=kr,r=Ra(i)||{indicesToRequest:[],currentImageIdIndex:e,stackCount:0,enabled:!0,direction:1,stats:{start:Date.now(),imageIds:new Map,decodeTimeInMS:0,loadTimeInMS:0,totalBytes:0}},c=e-r.currentImageIdIndex;if(r.direction=Jk(c),r.currentImageIdIndex=e,r.enabled=!0,r.stackCount<100&&(r.stackCount+=a),Math.abs(c)>o||!c)if(r.stackCount=0,t){const h=e/n.imageIds.length;s=Math.ceil(t*h),o=Math.ceil(t*(1-h)),r.cacheFill=!0}else r.cacheFill=!1;else c<0?(s+=r.stackCount,o=0):(o+=r.stackCount,s=0);const l=Math.max(0,e-s),d=Math.min(n.imageIds.length-1,e+o),u=[];for(let h=e+1;h<=d;h++)u.push(h);for(let h=e-1;h>=l;h--)u.push(h);r.indicesToRequest=u,KE(i,r)};function Qk(i){clearTimeout(ph),i.removeEventListener(yt.STACK_NEW_IMAGE,vh);const t=Dd(i);Z.removeEventListener(yt.IMAGE_CACHE_IMAGE_REMOVED,t);const n=Ra(i);n&&(n.enabled=!1)}function tU(){return kr}function eU(i){kr=i}const nU={enable:Zk,disable:Qk,getConfiguration:tU,setConfiguration:eU},oU=Object.freeze(Object.defineProperty({__proto__:null,isViewportPreScaled:Ki},Symbol.toStringTag,{value:"Module"}));function iU(i,t){let n;const e=t.dimensionGroupNumbers||t.frameNumbers||Array.from({length:i.numDimensionGroups},(o,s)=>s+1);if(t.frameNumbers&&console.warn("Warning: frameNumbers parameter is deprecated. Please use dimensionGroupNumbers instead."),!t.maskVolumeId&&!t.worldCoordinate)throw new Error("You should provide either maskVolumeId or imageCoordinate");if(t.maskVolumeId&&t.worldCoordinate)throw new Error("You can only use one of maskVolumeId or imageCoordinate");if(t.maskVolumeId){const o=Q.getVolume(t.maskVolumeId);if(!o)throw new Error("Segmentation volume not found");const[s,a]=aU(e,i,o);return[s,a]}return t.worldCoordinate?sU(e,t.worldCoordinate,i):n}function sU(i,t,n){const{dimensions:e,imageData:o}=n,s=o.worldToIndex(t);if(s[0]=Math.floor(s[0]),s[1]=Math.floor(s[1]),s[2]=Math.floor(s[2]),!gn(s,e))throw new Error("outside bounds");const a=e[0],r=e[0]*e[1],c=[];return i.forEach(l=>{const d=s[2]*r+s[1]*a+s[0];c.push(n.voxelManager.getAtIndexAndDimensionGroup(d,l))}),c}function aU(i,t,n){const{imageData:e}=n,o=n.voxelManager,s=o.getScalarDataLength(),a=[];a.length=s;let r=0;for(let h=0,f=s;h<f;h++)o.getAtIndex(h)!==0&&(a[r++]=h);a.length=r;const c=[],l=t.voxelManager.getScalarDataLength()===s&&JSON.stringify(t.spacing)===JSON.stringify(n.spacing),d=[];if(l){for(let h=0;h<a.length;h++){const f=[],g=a[h];for(let m=0;m<i.length;m++)f.push(t.voxelManager.getAtIndexAndDimensionGroup(g,i[m]));c.push(f),d.push(o.toIJK(g))}return[c,d]}const u=({pointLPS:h,value:f,pointIJK:g})=>{if(f===0)return;const m=jh(t.imageData,t.dimensions,t.spacing,h);let p=0;const v=new Map;i.forEach(C=>v.set(C,0));const I=({index:C})=>{for(let S=0;S<i.length;S++){const b=t.voxelManager.getAtIndexAndDimensionGroup(C,i[S]),_=i[S];v.set(_,v.get(_)+b)}p++};t.voxelManager.forEach(I,{imageData:t.imageData,boundsIJK:m});const w=[];v.forEach(C=>{w.push(C/p)}),d.push(g),c.push(w)};return n.voxelManager.forEach(u,{imageData:e}),[c,d]}function QE(i,t){const n=i.getScalarDataLength(),e=new Float32Array(n);for(const o of t){const s=i.getDimensionGroupScalarData(o);for(let a=0;a<n;a++)e[a]+=s[a]}return e}function rU(i,t){const n=QE(i,t),e=t.length;for(let o=0;o<n.length;o++)n[o]/=e;return n}const tS={[Ud.SUM]:(i,t,n)=>{const e=QE(i,t);for(let o=0;o<e.length;o++)n(o,e[o])},[Ud.AVERAGE]:(i,t,n)=>{const e=rU(i,t);for(let o=0;o<e.length;o++)n(o,e[o])},[Ud.SUBTRACT]:(i,t,n)=>{if(t.length!==2)throw new Error("Please provide only 2 dimension groups for subtraction.");const e=i.getScalarDataLength(),o=i.getDimensionGroupScalarData(t[0]),s=i.getDimensionGroupScalarData(t[1]);for(let a=0;a<e;a++){const r=o[a]-s[a];n(a,r)}}};function cU(i,t,n){const{dimensionGroupNumbers:e,frameNumbers:o}=n;o&&console.warn("Warning: frameNumbers parameter is deprecated. Please use dimensionGroupNumbers instead.");const s=e||o||Array.from({length:i.numDimensionGroups},(d,u)=>u+1);if(s.length<=1)throw new Error("Please provide two or more dimension groups");const a=i.voxelManager,r=a.getScalarDataLength(),c=tS[t];if(!c)throw new Error(`Unsupported operation: ${t}`);const l=new Float32Array(r);return c(a,s,(d,u)=>{l[d]=u}),l}function lU(i,t,n){const{dimensionGroupNumbers:e,frameNumbers:o,targetVolume:s}=n;if(!s)throw new Error("A target volume must be provided");o&&console.warn("Warning: frameNumbers parameter is deprecated. Please use dimensionGroupNumbers instead.");const a=e||o||Array.from({length:i.numDimensionGroups},(d,u)=>u+1);if(a.length<=1)throw new Error("Please provide two or more dimension groups");const r=i.voxelManager,c=s.voxelManager,l=tS[t];if(!l)throw new Error(`Unsupported operation: ${t}`);l(r,a,(d,u)=>{c.setAtIndex(d,u)}),c.resetModifiedSlices();for(let d=0;d<s.dimensions[2];d++)c.modifiedSlices.add(d)}const dU=Object.freeze(Object.defineProperty({__proto__:null,generateImageFromTimeData:cU,getDataInTime:iU,updateVolumeFromTimeData:lU},Symbol.toStringTag,{value:"Module"}));function eS(i,t){const n=t*3;if(n<i.length)return Ot(i[n],i[n+1],i[n+2])}function nS(i){const t=i.getLines().getData();let n=0;const e=new Map;for(;n<t.length;){const r=t[n++],c=[];for(let l=0;l<r;l++)c.push(t[n+l]);e.set(c[0],c),n+=r}const o=[],s=r=>{for(const[c,l]of r.entries())if(l!==void 0)return c;return-1};let a=s(e);for(;a!==-1;){const r=[a];for(;e.has(a);){const c=e.get(a)[1];e.has(c)&&r.push(c),e.delete(a),a=c}o.push(r),a=s(e)}return o.length?o:void 0}function oS(i){const t=nS(i);if(!t)return;const n=i.getPoints().getData();return t.map(e=>e.map(o=>eS(n,o)))}const uU=Object.freeze(Object.defineProperty({__proto__:null,getPoint:eS,getPolyDataPointIndexes:nS,getPolyDataPoints:oS},Symbol.toStringTag,{value:"Module"}));var to;(function(i){i.Top="top",i.Left="left",i.Bottom="bottom",i.Right="right"})(to||(to={}));const hU=Object.freeze(Object.defineProperty({__proto__:null,get ColorbarRangeTextPosition(){return to}},Symbol.toStringTag,{value:"Module"})),mi=i=>i&&i.upper>i.lower,xl=i=>!!i&&i.width>0&&i.height>0,Ur=(i,t)=>!!i&&!!t&&i.lower===t.lower&&i.upper===t.upper,iS=(i,t)=>!!i&&!!t&&i.width===t.width&&i.height===t.height,fU=(i,t,n)=>[i[0]*(1-n)+t[0]*n,i[1]*(1-n)+t[1]*n,i[2]*(1-n)+t[2]*n],{clamp:gU}=oe;class ig{constructor(t){ig.validateProps(t);const{colormap:n,size:e={width:20,height:100},imageRange:o={lower:0,upper:1},voiRange:s={lower:0,upper:1},container:a,showFullPixelValueRange:r=!1}=t;this._colormap=n,this._imageRange=o,this._voiRange=s,this._showFullImageRange=r,this._canvas=this._createRootElement(e),a&&this.appendTo(a)}get colormap(){return this._colormap}set colormap(t){this._colormap=t,this.render()}get size(){const{width:t,height:n}=this._canvas;return{width:t,height:n}}set size(t){const{_canvas:n}=this;!xl(t)||iS(n,t)||(this._setCanvasSize(n,t),this.render())}get imageRange(){return{...this._imageRange}}set imageRange(t){!mi(t)||Ur(t,this._imageRange)||(this._imageRange=t,this.render())}get voiRange(){return{...this._voiRange}}set voiRange(t){!mi(t)||Ur(t,this._voiRange)||(this._voiRange=t,this.render())}get showFullImageRange(){return this._showFullImageRange}set showFullImageRange(t){t!==this._showFullImageRange&&(this._showFullImageRange=t,this.render())}appendTo(t){t.appendChild(this._canvas),this.render()}dispose(){const{_canvas:t}=this,{parentElement:n}=t;n?.removeChild(t)}static validateProps(t){const{size:n,imageRange:e,voiRange:o}=t;if(n&&!xl(n))throw new Error('Invalid "size"');if(e&&!mi(e))throw new Error('Invalid "imageRange"');if(o&&!mi(o))throw new Error('Invalid "voiRange"')}_setCanvasSize(t,n){const{width:e,height:o}=n;t.width=e,t.height=o,Object.assign(t.style,{width:`${e}px`,height:`${o}px`})}_createRootElement(t){const n=document.createElement("canvas");return Object.assign(n.style,{position:"absolute",top:"0",left:"0",pointerEvents:"none",boxSizing:"border-box"}),this._setCanvasSize(n,t),n}render(){if(!this._canvas.isConnected)return;const{_colormap:t}=this,{RGBPoints:n}=t,e=n.length/4,o=w=>{const C=4*w;if(!(w<0||w>=e))return{index:w,position:n[C],color:[n[C+1],n[C+2],n[C+3]]}},{width:s,height:a}=this._canvas,r=this._canvas.getContext("2d");if(!r)return;const c=s>a,l=c?s:a,{_voiRange:d}=this,u=this._showFullImageRange?this._imageRange:{...d};let h,f=o(0);const g=n[0],p=n[n.length-4]-g,v=(u.upper-u.lower)/(l-1);let I=u.lower;for(let w=0;w<l;w++){const C=(I-d.lower)/Math.abs(d.upper-d.lower),S=g+C*p;if(f)for(let y=f.index;y<e&&!(S<=f.position);y++)h=f,f=o(y+1);let b;if(!h)b=[...f.color];else if(!f)b=[...h.color];else{const y=(S-h.position)/(f.position-h.position);b=fU(h.color,f.color,y)}const _=b.map(y=>gU(Math.round(y*255),0,255));r.fillStyle=`rgb(${_[0]}, ${_[1]}, ${_[2]})`,c?r.fillRect(w,0,1,a):r.fillRect(0,a-w-1,s,1),I+=v}}}const ts={FONT:"10px Arial",COLOR:"white",TICK_SIZE:5,TICK_WIDTH:1,TICK_LABEL_MARGIN:3,MAX_NUM_TICKS:8,TICKS_STEPS:[1,2.5,5,10]};class sg{constructor(t){sg.validateProps(t);const{top:n=0,left:e=0,size:o={width:20,height:100},imageRange:s={lower:0,upper:1},voiRange:a={lower:0,upper:1},ticks:r,container:c,showFullPixelValueRange:l=!1}=t,{style:d,position:u}=r??{};this._imageRange=s,this._voiRange=a,this._font=d?.font??ts.FONT,this._color=d?.color??ts.COLOR,this._tickSize=d?.tickSize??ts.TICK_SIZE,this._tickWidth=d?.tickWidth??ts.TICK_WIDTH,this._labelMargin=d?.labelMargin??ts.TICK_LABEL_MARGIN,this._maxNumTicks=d?.maxNumTicks??ts.MAX_NUM_TICKS,this._rangeTextPosition=u??to.Right,this._showFullPixelValueRange=l,this._canvas=this._createCanvasElement(o,n,e),c&&this.appendTo(c)}get size(){const{width:t,height:n}=this._canvas;return{width:t,height:n}}set size(t){const{_canvas:n}=this;!xl(t)||iS(n,t)||(this._setCanvasSize(n,t),this.render())}get top(){return Number.parseInt(this._canvas.style.top)}set top(t){const{_canvas:n}=this,e=this.top;t!==e&&(n.style.top=`${t}px`,this.render())}get left(){return Number.parseInt(this._canvas.style.left)}set left(t){const{_canvas:n}=this,e=this.left;t!==e&&(n.style.left=`${t}px`,this.render())}get imageRange(){return{...this._imageRange}}set imageRange(t){!mi(t)||Ur(t,this._imageRange)||(this._imageRange=t,this.render())}get voiRange(){return{...this._voiRange}}set voiRange(t){!mi(t)||Ur(t,this._voiRange)||(this._voiRange=t,this.render())}get tickSize(){return this._tickSize}set tickSize(t){t!==this._tickSize&&(this._tickSize=t,this.render())}get tickWidth(){return this._tickWidth}set tickWidth(t){t!==this._tickWidth&&(this._tickWidth=t,this.render())}get color(){return this._color}set color(t){t!==this._color&&(this._color=t,this.render())}get showFullPixelValueRange(){return this._showFullPixelValueRange}set showFullPixelValueRange(t){t!==this._showFullPixelValueRange&&(this._showFullPixelValueRange=t,this.render())}get visible(){return this._canvas.style.display==="block"}set visible(t){t!==this.visible&&(this._canvas.style.display=t?"block":"none",t&&this.render())}appendTo(t){t.appendChild(this._canvas),this.render()}static validateProps(t){const{size:n,imageRange:e,voiRange:o}=t;if(n&&!xl(n))throw new Error('Invalid "size"');if(e&&!mi(e))throw new Error('Invalid "imageRange"');if(o&&!mi(o))throw new Error('Invalid "voiRange"')}_setCanvasSize(t,n){const{width:e,height:o}=n;t.width=e,t.height=o,Object.assign(t.style,{width:`${e}px`,height:`${o}px`})}_createCanvasElement(t,n,e){const o=document.createElement("canvas");return Object.assign(o.style,{display:"none",position:"absolute",boxSizing:"border-box",top:`${n}px`,left:`${e}px`}),this._setCanvasSize(o,t),o}_getTicks(t){const{lower:n,upper:e}=t,s=(e-n)/(this._maxNumTicks-1),a=Math.pow(10,-Math.floor(Math.log10(Math.abs(s)))),r=s*a,l=ts.TICKS_STEPS.find(g=>g>=r)/a,d=Math.ceil(e/l)*l,u=Math.floor(n/l)*l,h=Math.round((d-u)/l)+1,f=[];for(let g=0;g<h;g++)f.push(u+g*l);return{scaleMin:u,scaleMax:d,step:l,ticks:f}}_getLeftTickInfo({position:t,labelMeasure:n}){const{width:e}=this._canvas,s=[e-this.tickSize-n.width-this._labelMargin,t],a={start:[e-this._tickSize,t],end:[e,t]};return{labelPoint:s,tickPoints:a}}_getRightTickInfo({position:t}){const n=[this._tickSize+this._labelMargin,t],e={start:[0,t],end:[this._tickSize,t]};return{labelPoint:n,tickPoints:e}}_getTopTickInfo({position:t,labelMeasure:n}){const{height:e}=this._canvas,o=e-this.tickSize-this._labelMargin,s=[t,o],a={start:[t,e-this._tickSize],end:[t,e]};return{labelPoint:s,tickPoints:a}}_getBottomTickInfo({position:t,labelMeasure:n}){const e=[t,this._tickSize+this._labelMargin],o={start:[t,0],end:[t,this._tickSize]};return{labelPoint:e,tickPoints:o}}render(){const{_canvas:t}=this;if(!t.isConnected||!this.visible)return;const{width:n,height:e}=t,o=n>=e,s=o?n:e,a=t.getContext("2d"),{_voiRange:r}=this,c=this._showFullPixelValueRange?this._imageRange:{...r},l=c.upper-c.lower,{ticks:d}=this._getTicks(c);a.clearRect(0,0,n,e),a.font=this._font,a.textBaseline=o?"top":"middle",a.textAlign=o?"center":"left",a.fillStyle=this._color,a.strokeStyle=this._color,a.lineWidth=this.tickWidth,d.forEach(u=>{let h=Math.round(s*((u-c.lower)/l));if(o||(h=e-h),h<0||h>s)return;const f=u.toString(),g=a.measureText(f);let m;o?this._rangeTextPosition===to.Top?m=this._getTopTickInfo({position:h,labelMeasure:g}):m=this._getBottomTickInfo({position:h,labelMeasure:g}):this._rangeTextPosition===to.Left?m=this._getLeftTickInfo({position:h,labelMeasure:g}):m=this._getRightTickInfo({position:h});const{labelPoint:p,tickPoints:v}=m,{start:I,end:w}=v;return a.beginPath(),a.moveTo(I[0],I[1]),a.lineTo(w[0],w[1]),a.fillText(f,p[0],p[1]),a.stroke(),h})}}function mU(i,t,n){return(i>=t?[to.Top,to.Bottom]:[to.Left,to.Right]).includes(n)}class pU{constructor({id:t,container:n}){this._containerResizeCallback=e=>{let o,s;const{contentRect:a,contentBoxSize:r}=e[0];a?(o=a.width,s=a.height):r?.length&&(o=r[0].inlineSize,s=r[0].blockSize),this._containerSize={width:o,height:s},this.onContainerResize()},this._id=t,this._containerSize={width:0,height:0},this._rootElement=this.createRootElement(t),this._containerResizeObserver=new ResizeObserver(this._containerResizeCallback),n&&this.appendTo(n)}get id(){return this._id}get rootElement(){return this._rootElement}appendTo(t){const{_rootElement:n,_containerResizeObserver:e}=this,{parentElement:o}=n;!t||t===o||(o&&e.unobserve(o),t.appendChild(n),e.observe(t))}destroy(){const{_rootElement:t,_containerResizeObserver:n}=this,{parentElement:e}=t;e?.removeChild(t),n.disconnect()}get containerSize(){return{...this._containerSize}}createRootElement(t){const n=document.createElement("div");return n.id=t,n.classList.add("widget"),Object.assign(n.style,{width:"100%",height:"100%"}),n}onContainerResize(){}}const ja={MULTIPLIER:1,RANGE_TEXT_POSITION:to.Right,TICKS_BAR_SIZE:50};class Vr extends pU{constructor(t){super(t),this._isMouseOver=!1,this._isInteracting=!1,this._mouseOverCallback=n=>{this._isMouseOver=!0,this.showTicks(),n.stopPropagation()},this._mouseOutCallback=n=>{this._isMouseOver=!1,this.hideTicks(),n.stopPropagation()},this._mouseDownCallback=n=>{this._isInteracting=!0,this.showTicks(),this._addVOIEventListeners(n),n.stopPropagation()},this._mouseDragCallback=(n,e)=>{const o=this.getVOIMultipliers(),s=this._getPointsFromMouseEvent(n),{points:a,voiRange:r}=e,c=No(It(),s.local,a.local),l=c[0]*o[0],d=c[1]*o[1];if(!l&&!d)return;const{lower:u,upper:h}=r;let{windowWidth:f,windowCenter:g}=yv(u,h);f=Math.max(f+l,1),g+=d;const m=Th(f,g);this.voiRange=m,n.stopPropagation(),n.preventDefault()},this._mouseUpCallback=n=>{this._isInteracting=!1,this.hideTicks(),this._removeVOIEventListeners(),n.stopPropagation()},this._eventListenersManager=new ub,this._colormaps=Vr.getColormapsMap(t),this._activeColormapName=Vr.getInitialColormapName(t),this._canvas=this._createCanvas(t),this._ticksBar=this._createTicksBar(t),this._rangeTextPosition=t.ticks?.position??ja.RANGE_TEXT_POSITION,this._canvas.appendTo(this.rootElement),this._ticksBar.appendTo(this.rootElement),this._addRootElementEventListeners()}get activeColormapName(){return this._activeColormapName}set activeColormapName(t){if(t===this._activeColormapName)return;const n=this._colormaps.get(t);if(!n){console.warn(`Invalid colormap name (${t})`);return}this._activeColormapName=t,this._canvas.colormap=n}get imageRange(){return this._canvas.imageRange}set imageRange(t){this._canvas.imageRange=t,this._ticksBar.imageRange=t}get voiRange(){return this._canvas.voiRange}set voiRange(t){const{voiRange:n}=this._canvas;!mi(t)||Ur(t,n)||(this._canvas.voiRange=t,this._ticksBar.voiRange=t,this.onVoiChange(t))}get showFullImageRange(){return this._canvas.showFullImageRange}set showFullImageRange(t){this._canvas.showFullImageRange=t,this._ticksBar.showFullPixelValueRange=t}destroy(){super.destroy(),this._eventListenersManager.reset()}createRootElement(){const t=document.createElement("div");return Object.assign(t.style,{position:"relative",fontSize:"0",width:"100%",height:"100%"}),t}onContainerResize(){super.onContainerResize(),this.updateTicksBar(),this._canvas.size=this.containerSize}getVOIMultipliers(){return[ja.MULTIPLIER,ja.MULTIPLIER]}onVoiChange(t){}showTicks(){this.updateTicksBar(),this._ticksBar.visible=!0}hideTicks(){this._isInteracting||this._isMouseOver||(this._ticksBar.visible=!1)}static getColormapsMap(t){const{colormaps:n}=t;return n.reduce((e,o)=>e.set(o.Name,o),new Map)}static getInitialColormapName(t){const{activeColormapName:n,colormaps:e}=t;return!!n&&e.some(s=>s.Name===n)?n:e[0].Name}_createCanvas(t){const{imageRange:n,voiRange:e,showFullPixelValueRange:o}=t,s=this._colormaps.get(this._activeColormapName);return new ig({colormap:s,imageRange:n,voiRange:e,showFullPixelValueRange:o})}_createTicksBar(t){const n=t.ticks;return new sg({imageRange:t.imageRange,voiRange:t.voiRange,ticks:n,showFullPixelValueRange:t.showFullPixelValueRange})}_getPointsFromMouseEvent(t){const{rootElement:n}=this,e=[t.clientX,t.clientY],o=[t.pageX,t.pageY],s=n.getBoundingClientRect(),a=[o[0]-s.left-window.pageXOffset,o[1]-s.top-window.pageYOffset];return{client:e,page:o,local:a}}updateTicksBar(){const{width:t,height:n}=this.containerSize;if(t===0&&n===0)return;const{_ticksBar:e,_rangeTextPosition:o}=this,s=t>=n,a=s?t:ja.TICKS_BAR_SIZE,r=s?ja.TICKS_BAR_SIZE:n;if(!mU(t,n,o))throw new Error("Invalid rangeTextPosition value for the current colobar orientation");let c,l;e.size={width:a,height:r},s?(l=0,c=o===to.Top?-r:n):(c=0,l=o===to.Left?-a:t),e.top=c,e.left=l}_addRootElementEventListeners(){const{_eventListenersManager:t}=this,{rootElement:n}=this;t.addEventListener(n,"mouseover",this._mouseOverCallback),t.addEventListener(n,"mouseout",this._mouseOutCallback),t.addEventListener(n,"mousedown",this._mouseDownCallback)}_addVOIEventListeners(t){const{_eventListenersManager:n}=this,e=this._getPointsFromMouseEvent(t),o={...this._canvas.voiRange},s={points:e,voiRange:o};this._removeVOIEventListeners(),n.addEventListener(document,"voi.mouseup",this._mouseUpCallback),n.addEventListener(document,"voi.mousemove",a=>this._mouseDragCallback(a,s))}_removeVOIEventListeners(){const{_eventListenersManager:t}=this;t.removeEventListener(document,"voi.mouseup"),t.removeEventListener(document,"voi.mousemove")}}const Iu=4;function vU(i,t,n){const{modality:e,isPreScaled:o}=Lh(i,t)??{};if(e==="PT"){const{clientWidth:s,clientHeight:a}=i.element,r=5/Math.max(s,a),{fixedPTWindowWidth:c=!0}=n??{},l=c?0:r;return o?[l,r]:[l,Iu]}return[Iu,Iu]}const{Events:Mi}=Ea,Xa={lower:-1e3,upper:1e3};class qs extends Vr{constructor(t){const{element:n,volumeId:e}=t,o=qs._getImageRange(n,e),s=qs._getVOIRange(n,e);super({...t,imageRange:o,voiRange:s}),this.autoHideTicks=()=>{if(this._hideTicksTimeoutId)return;const a=this._hideTicksTime-Date.now();a<=0?this.hideTicks():this._hideTicksTimeoutId=window.setTimeout(()=>{this._hideTicksTimeoutId=0,this.autoHideTicks()},a)},this._stackNewImageCallback=()=>{this.imageRange=qs._getImageRange(this._element)},this._imageVolumeModifiedCallback=a=>{const{volumeId:r}=a.detail;if(r!==this._volumeId)return;const{_element:c}=this;this.imageRange=qs._getImageRange(c,r)},this._viewportVOIModifiedCallback=a=>{const{viewportId:r,volumeId:c,range:l,colormap:d}=a.detail,{viewport:u}=this.enabledElement;r!==u.id||c!==this._volumeId||(this.voiRange=l,d&&(this.activeColormapName=d.name),this.showAndAutoHideTicks())},this._viewportColormapModifiedCallback=a=>{const{viewportId:r,colormap:c,volumeId:l}=a.detail,{viewport:d}=this.enabledElement;r!==d.id||l!==this._volumeId||(this.activeColormapName=c.name)},this._element=n,this._volumeId=e,this._addCornerstoneEventListener()}get element(){return this._element}get enabledElement(){return N(this._element)}getVOIMultipliers(){const{viewport:t}=this.enabledElement;return vU(t,this._volumeId)}onVoiChange(t){super.onVoiChange(t);const n=this.enabledElement.viewport;if(n instanceof Pn)n.setProperties({voiRange:t}),n.render();else if(n instanceof Xe){const{_volumeId:e}=this,o=yh(e);n.setProperties({voiRange:t},e),o.forEach(s=>s.render())}else if(ie(n)){const{_volumeId:e}=this;e?n.setDisplaySetPresentation(e,{voiRange:t}):n.setDisplaySetPresentation({voiRange:t}),n.render()}}static _getImageRange(t,n){const e=N(t),{viewport:o}=e,s=o.getImageActor(n);if(!s)return Xa;const a=s.getMapper().getInputData(),r=a.getPointData().getScalars();let c;if(r)c=r.getRange();else{const l=a.get("voxelManager")?.voxelManager,d=n?Q.getVolume(n):void 0,u=l??d?.voxelManager;if(!u?.getRange)return Xa;const[h,f]=u.getRange();c=[h,f]}return c[0]===0&&c[1]===0?Xa:{lower:c[0],upper:c[1]}}static _getVOIRange(t,n){const e=N(t),{viewport:o}=e,s=o.getImageActor(n);if(!s)return Xa;const a=s.getProperty().getRGBTransferFunction(0).getRange();return a[0]===0&&a[1]===0?Xa:{lower:a[0],upper:a[1]}}showAndAutoHideTicks(t=1e3){this._hideTicksTime=Date.now()+t,this.showTicks(),this.autoHideTicks()}_addCornerstoneEventListener(){const{_element:t}=this;Z.addEventListener(Mi.IMAGE_VOLUME_MODIFIED,this._imageVolumeModifiedCallback),t.addEventListener(Mi.STACK_NEW_IMAGE,this._stackNewImageCallback),t.addEventListener(Mi.VOI_MODIFIED,this._viewportVOIModifiedCallback),t.addEventListener(Mi.COLORMAP_MODIFIED,this._viewportColormapModifiedCallback)}destroy(){super.destroy();const{_element:t}=this;Z.removeEventListener(Mi.IMAGE_VOLUME_MODIFIED,this._imageVolumeModifiedCallback),t.removeEventListener(Mi.STACK_NEW_IMAGE,this._stackNewImageCallback),t.removeEventListener(Mi.VOI_MODIFIED,this._viewportVOIModifiedCallback),t.removeEventListener(Mi.COLORMAP_MODIFIED,this._viewportColormapModifiedCallback)}}const IU=Object.freeze(Object.defineProperty({__proto__:null,Colorbar:Vr,Enums:hU,ViewportColorbar:qs},Symbol.toStringTag,{value:"Module"}));function sS(i,t,n,e,o){const s=[];let a=0;const r=i.scalarData;let c,l,d;if(i.color)for(l=0;l<o;l++)for(d=0;d<e;d++){c=((l+n)*i.columns+(d+t))*4;const u=r[c],h=r[c+1],f=r[c+2];s[a++]=.2126*u+.7152*h+.0722*f}else for(l=0;l<o;l++)for(d=0;d<e;d++)c=(l+n)*i.columns+(d+t),s[a++]=r[c];return s}function aS(i,t,n){const e=i.length;let o=n,s=t,a=0;if(e<2)return{min:o,max:s,mean:(t+n)/2};for(let r=0;r<e;r++){const c=i[r];o=Math.min(o,c),s=Math.max(s,c),a+=c}return{min:o,max:s,mean:a/e}}function rS(i){if(i instanceof Xe)return wU(i);if(i instanceof Pn)return EU(i);if(ie(i))return SU(i);throw new Error("Viewport not supported")}function wU(i){const{scalarData:t,width:n,height:e}=Av(i),{min:o,max:s}=Mh(t);return{scalarData:t,minPixelValue:o,maxPixelValue:s,width:n,height:e,rows:n,columns:e}}function EU(i){const t=i.getImageData(),{scalarData:n}=t,{min:e,max:o}=Mh(n),s=t.dimensions[0],a=t.dimensions[1],{rows:r,columns:c,color:l}=i.getCornerstoneImage();return{scalarData:n,width:s,height:a,minPixelValue:e,maxPixelValue:o,rows:r,columns:c,color:l}}function SU(i){const t=i.getCurrentImageId();if(!t){console.warn("WindowLevelRegionTool: the current native viewport slice has no backing image (reformatted/oblique volume plane); skipping region window level.");return}const n=Q.getImage(t);if(!n)throw new Error("Viewport not supported");const e=n.getPixelData(),{rows:o,columns:s,color:a}=n,{min:r,max:c}=Mh(e);return{scalarData:e,width:s,height:o,minPixelValue:r,maxPixelValue:c,rows:o,columns:s,color:a}}const CU=Object.freeze(Object.defineProperty({__proto__:null,calculateMinMaxMean:aS,extractWindowLevelRegionToolData:rS,getLuminanceFromRegion:sS},Symbol.toStringTag,{value:"Module"})),bU=Object.freeze(Object.defineProperty({__proto__:null,colorbar:IU,windowLevel:CU},Symbol.toStringTag,{value:"Module"})),{transformWorldToIndex:sr}=oe;function _U(i,t,n,e){const{boundsIJK:o,centerWorld:s,radiusWorld:a}=yU(t,i,e),r={center:s,radius:a},c=i.getDimensions();kl.createScalarVolumeVoxelManager({dimensions:c,scalarData:i.getPointData().getScalars().getData()}).forEach(n,{boundsIJK:o,isInObject:d=>mE(r,d),imageData:i})}function yU(i,t,n){const[e,o]=i,s=Ot((e[0]+o[0])/2,(e[1]+o[1])/2,(e[2]+o[2])/2),a=ke(e,o)/2;let r;if(!n){const c=sr(t,s),l=t.getSpacing(),d=Math.min(...l),u=Math.ceil(a/d);return r=[[c[0]-u,c[0]+u],[c[1]-u,c[1]+u],[c[2]-u,c[2]+u]],{boundsIJK:r,centerWorld:s,radiusWorld:a}}return r=xU(t,n,i,s,a),{boundsIJK:r,centerWorld:s,radiusWorld:a}}function xU(i,t,n,e,o){const[s,a]=n,r=i.getDimensions(),c=ht(t);if(!c.viewUp||!c.viewPlaneNormal)return Ii([sr(i,a),sr(i,s)],r);const l=Ot(c.viewUp[0],c.viewUp[1],c.viewUp[2]),d=Ot(c.viewPlaneNormal[0],c.viewPlaneNormal[1],c.viewPlaneNormal[2]),u=B();Me(u,l,d);const h=B(),f=B();ee(h,a,d,o),ee(f,s,d,-o),ee(h,h,u,-o),ee(f,f,u,o);const g=[sr(i,h),sr(i,f)];return Ii(g,r)}function cS(i){if(!Array.isArray(i)||i.length!==9)throw new Error("Matrix must be an array of 9 numbers");if(!i.every(t=>typeof t=="number"&&!isNaN(t)))throw new Error("Matrix must contain only valid numbers")}function lS(i){cS(i);const t=[[i[0],i[1],i[2]],[i[3],i[4],i[5]],[i[6],i[7],i[8]]],n=t[0][0]*(t[1][1]*t[2][2]-t[1][2]*t[2][1])-t[0][1]*(t[1][0]*t[2][2]-t[1][2]*t[2][0])+t[0][2]*(t[1][0]*t[2][1]-t[1][1]*t[2][0]);if(Math.abs(n)<1e-10)throw new Error("Matrix is not invertible (determinant is zero)");const e=[[t[1][1]*t[2][2]-t[1][2]*t[2][1],-(t[0][1]*t[2][2]-t[0][2]*t[2][1]),t[0][1]*t[1][2]-t[0][2]*t[1][1]],[-(t[1][0]*t[2][2]-t[1][2]*t[2][0]),t[0][0]*t[2][2]-t[0][2]*t[2][0],-(t[0][0]*t[1][2]-t[0][2]*t[1][0])],[t[1][0]*t[2][1]-t[1][1]*t[2][0],-(t[0][0]*t[2][1]-t[0][1]*t[2][0]),t[0][0]*t[1][1]-t[0][1]*t[1][0]]],o=[];for(let s=0;s<3;s++)for(let a=0;a<3;a++)o.push(e[s][a]/n);return o}function wu(i){const t=Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2]);return i.map(n=>n/t)}function PU(i){cS(i);const t=i.slice(0,3),n=i.slice(3,6),e=i.slice(6,9),o=wu(t),s=wu(n),a=wu(e),r={x:[1,0,0],y:[0,1,0],z:[0,0,1]},c=1e-10,l=o.every((u,h)=>Math.abs(u-r.x[h])<c)&&s.every((u,h)=>Math.abs(u-r.y[h])<c)&&a.every((u,h)=>Math.abs(u-r.z[h])<c),d=l?[...r.x,...r.y,...r.z]:lS([...o,...s,...a]);return{isStandard:l,rotationMatrix:d}}function DU(i,t,n){const e=i[0]-t[0],o=i[1]-t[1],s=i[2]-t[2];return[n[0]*e+n[1]*o+n[2]*s+t[0],n[3]*e+n[4]*o+n[5]*s+t[1],n[6]*e+n[7]*o+n[8]*s+t[2]]}function TU(i,t,n){const e=[];for(let o=0;o<n.length;o+=3){const s=n.slice(o,o+3),a=DU(s,t,i);e.push(...a)}return e}const MU=Object.freeze(Object.defineProperty({__proto__:null,checkStandardBasis:PU,inverse3x3Matrix:lS,rotatePoints:TU},Symbol.toStringTag,{value:"Module"}));function dS(i,t,n){i.data.label=n,zt(i,t,Bt.LabelChange)}function AU(i,t){const{data:n}=i,{points:e}=n.handles,{focalPoint:o,viewPlaneNormal:s}=t.getCamera(),a=xt(tn(B(),e[0],o),s);return e.forEach(r=>{yn(r,r,bn(B(),[-s[0],-s[1],-s[2]],a))}),t instanceof Pn&&(i.metadata.referencedImageId=t.getCurrentImageId()),i}function LU(i,t,n){const e=t*n,o=i.length/e;if(![1,3,4].includes(o))throw new Error("Buffer must be 1, 3, or 4 channels per pixel");const s=Array.from({length:n},()=>new Array(t).fill(!1));for(let p=0;p<n;p++)for(let v=0;v<t;v++){const w=(p*t+v)*o;let C=!1;for(let S=0;S<Math.min(3,o);S++)if(i[w+S]>0){C=!0;break}s[p][v]=C}const a=Array.from({length:n},()=>new Array(t).fill(0));let r=0;const c={};for(let p=0;p<n;p++)for(let v=0;v<t;v++)if(s[p][v]&&a[p][v]===0){r++;const I=(S,b)=>S<0||S>=t||b<0||b>=n?!1:s[b][S]&&a[b][S]===0;let w=0;$f(I,[v,p],{onFlood:(S,b)=>{a[b][S]=r,w++},diagonals:!1}),c[r]=w}if(r===0)return[];const l=Object.keys(c).reduce((p,v)=>c[p]>c[v]?p:v);function d(p,v){if(a[v][p]!==+l)return!1;for(const[I,w]of[[1,0],[-1,0],[0,1],[0,-1]]){const C=p+I,S=v+w;if(C<0||C>=t||S<0||S>=n||a[S][C]!==+l)return!0}return!1}let u=null;t:for(let p=0;p<n;p++)for(let v=0;v<t;v++)if(d(v,p)){u=[v,p];break t}if(!u)return[];const h=[[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1],[0,-1],[1,-1]],f=[];let g=u,m=[u[0]-1,u[1]];do{f.push([g[0],g[1]]);const p=m[0]-g[0],v=m[1]-g[1];let I=h.findIndex(C=>C[0]===p&&C[1]===v);I<0&&(I=0);let w=null;for(let C=1;C<=8;C++){const[S,b]=h[(I+C)%8],_=g[0]+S,y=g[1]+b;if(_>=0&&_<t&&y>=0&&y<n&&d(_,y)){w=[_,y];const[D,T]=h[(I+C-1+8)%8];m=[g[0]+D,g[1]+T];break}}if(!w)break;g=w}while(g[0]!==u[0]||g[1]!==u[1]);return f}function OU(i){const t=ed(i,2),n=r0(t);return{simplified:t,hull:n}}function RU(i,t=7){if(!i.length)throw new Error("Convex hull is empty");const n=i.length,e=v=>(v+1)%n,o=(v,I)=>{const w=[];for(let C=v;w.push(C),C!==I;C=e(C));return w};let s=0,a=0;for(let v=1;v<n;v++)i[v][0]<i[s][0]&&(s=v),i[v][0]>i[a][0]&&(a=v);const r=i[s],c=i[a],l=o(s,a),d=o(a,s),u=Math.min(...i.map(v=>v[1])),h=l.some(v=>i[v][1]===u)?l:d,f=Math.min(...h.map(v=>i[v][1]));let g=h.map(v=>i[v]).filter(v=>Math.abs(v[1]-f)<=t);g.length<2&&(g=h.map(v=>i[v]).sort((v,I)=>v[1]-I[1]).slice(0,2));const m=g.reduce((v,I)=>I[0]<v[0]?I:v,g[0]),p=g.reduce((v,I)=>I[0]>v[0]?I:v,g[0]);return{P1:m,P2:r,P3:c,P4:p}}function NU(i,t,n,e,o,s={}){const{maxDist:a=15,slack:r=2}=s,c={P1:{dx:-1,dy:-1},P2:{dx:-1,dy:1},P3:{dx:1,dy:1},P4:{dx:1,dy:-1}};function l(d,{dx:u,dy:h},f=5){const g=u<0?d[0]-a:d[0]-r,m=u<0?d[0]+r:d[0]+a,p=h<0?d[1]-a:d[1]-r,v=h<0?d[1]+r:d[1]+a;let I=d;for(const[w,C]of o){if(w<g||w>m||C<p||C>v)continue;const S=Math.round(w),b=Math.round(C);if(S<0||S>=t||b<0||b>=n)continue;const _=(S-I[0])*u,y=(b-I[0])*h;i[b*t+S]>f&&(_>0||y>0)&&(I=[w,C])}return I}return{P1:l(e.P1,c.P1),P2:l(e.P2,c.P2),P3:l(e.P3,c.P3),P4:l(e.P4,c.P4)}}function kU(i,t,n,e,o){const s=RU(e);return NU(i,t,n,s,o,{maxDist:20})}function yp(i,t){return Math.atan2(t[1]-i[1],t[0]-i[0])}function UU(i){const{P1:t,P2:n,P3:e,P4:o}=i,s=al(t,n,o,e,!0);if(!s)throw new Error("Fan edges appear parallel — no apex found");const a=s;let r=yp(a,t)*(180/Math.PI),c=yp(a,o)*(180/Math.PI);if(c<=r){const m=r;r=c,c=m}const l=Math.hypot(t[0]-a[0],t[1]-a[1]),d=Math.hypot(o[0]-a[0],o[1]-a[1]),u=Math.hypot(n[0]-a[0],n[1]-a[1]),h=Math.hypot(e[0]-a[0],e[1]-a[1]),f=Math.min(l,d),g=Math.max(u,h);return{center:a,startAngle:r,endAngle:c,innerRadius:f,outerRadius:g}}function ar(i,t,n,e,o={}){const{strokeStyle:s="#f00",lineWidth:a=2,quality:r=.92}=o,c=document.createElement("canvas");c.width=t,c.height=n;const l=c.getContext("2d"),d=t*n,u=i.length/d,h=l.createImageData(t,n),f=h.data;for(let g=0;g<d;g++){const m=g*u,p=g*4;if(u===1){const v=i[m];f[p]=v,f[p+1]=v,f[p+2]=v,f[p+3]=255}else f[p]=i[m],f[p+1]=i[m+1],f[p+2]=i[m+2],f[p+3]=u===4?i[m+3]:255}if(l.putImageData(h,0,0),e.length>0){l.strokeStyle=s,l.lineWidth=a,l.beginPath(),l.moveTo(e[0][0]+.5,e[0][1]+.5);for(let g=1;g<e.length;g++)l.lineTo(e[g][0]+.5,e[g][1]+.5);l.closePath(),l.stroke()}return c.toDataURL("image/jpeg",r)}function ag(i){const t=Q.getImage(i);if(!t)return;const n=t.width,e=t.height;return{pixelData:t.getPixelData(),width:n,height:e}}function uS(i,t){const n=document.createElement("a");n.href=i,n.download=t,document.body.appendChild(n),n.style.display="none",n.click(),n.remove()}function VU(i,t,n,e,o={}){const{center:s,startAngle:a,endAngle:r,innerRadius:c,outerRadius:l}=e,{strokeStyle:d="#0ff",lineWidth:u=2,quality:h=.92}=o,f=a*Math.PI/180,g=r*Math.PI/180,m=document.createElement("canvas");m.width=t,m.height=n;const p=m.getContext("2d"),v=t*n,I=i.length/v,w=p.createImageData(t,n),C=w.data;for(let S=0;S<v;S++){const b=S*4;if(I===1){const _=i[S];C[b]=_,C[b+1]=_,C[b+2]=_,C[b+3]=255}else{const _=S*I;C[b]=i[_],C[b+1]=i[_+1],C[b+2]=i[_+2],C[b+3]=I===4?i[_+3]:255}}p.putImageData(w,0,0),p.beginPath();for(let S=f;S<=g;S+=.01){const b=s[0]+c*Math.cos(S),_=s[1]+c*Math.sin(S);S===f?p.moveTo(b,_):p.lineTo(b,_)}for(let S=g;S>=f;S-=.01){const b=s[0]+l*Math.cos(S),_=s[1]+l*Math.sin(S);p.lineTo(b,_)}return p.closePath(),p.strokeStyle=d,p.lineWidth=u,p.stroke(),m.toDataURL("image/jpeg",h)}function FU(i,t=5){const{contour:n,simplified:e,hull:o,refined:s,fanGeometry:a}=rg(i),{pixelData:r,width:c,height:l}=ag(i)||{};if(!r)return;let d;t===1?d=ar(r,c,l,n):t===2?d=ar(r,c,l,e):t===3?d=ar(r,c,l,o):t===4?d=ar(r,c,l,[s.P1,s.P2,s.P3,s.P4]):d=VU(r,c,l,a,{strokeStyle:"#f00",lineWidth:3,quality:.95}),uS(d,"contour.jpg")}function rg(i){const{pixelData:t,width:n,height:e}=ag(i)||{};if(!t)return;const o=LU(t,n,e),{simplified:s,hull:a}=OU(o),r=kU(t,n,e,a,s),c=UU({P1:r.P1,P2:r.P2,P3:r.P3,P4:r.P4});return{contour:o,simplified:s,hull:a,refined:r,fanGeometry:c}}const GU=Object.freeze(Object.defineProperty({__proto__:null,calculateFanGeometry:rg,default:uS,downloadFanJpeg:FU,exportContourJpeg:ar,getPixelData:ag},Symbol.toStringTag,{value:"Module"})),{RENDERING_DEFAULTS:HU}=Qo,WU=.25,BU=2001;function hS(i){if(!ie(i))return null;try{if(i.getCurrentMode?.()!=="volume")return null}catch{return null}if(!Sa(i))return null;const t=i.getSourceDataId();if(!t)return null;const n=i.getDisplaySetPresentation(t),{blendMode:e,slabThickness:o}=n??{};let s;if(e===Gn.MAXIMUM_INTENSITY_BLEND)s="max";else if(e===Gn.MINIMUM_INTENSITY_BLEND)s="min";else return null;return!Number.isFinite(o)||o<=HU.MINIMUM_SLAB_THICKNESS?null:{mode:s,slabThicknessMm:o}}function fS(i,t){const n=hS(i);if(!n||!t)return null;const e=i.getVolumeId?.(),o=e?Q.getVolume(e):void 0;if(!o?.voxelManager||!o.dimensions||!o.spacing||!o.direction||!o.origin)return null;const s=Do(i);if(!s)return null;const a=s.normal,r=Math.abs(a[0])*o.spacing[0]+Math.abs(a[1])*o.spacing[1]+Math.abs(a[2])*o.spacing[2];if(!Number.isFinite(r)||r<=0)return null;const c=n.slabThicknessMm/2;let l=r*WU;const d=Math.min(Math.ceil(c/l),(BU-1)/2);l=c/d;const u=n.mode==="max";let h=NaN,f=0;const g=B(),m=p=>{ee(g,t,a,p);const v=kl.sampleAtWorld(o,[g[0],g[1],g[2]]);Number.isFinite(v)&&(Number.isNaN(h)||(u?v>h:v<h))&&(h=v,f=p)};m(0);for(let p=1;p<=d;p++)m(p*l),m(-p*l);return Number.isNaN(h)?null:[t[0]+a[0]*f,t[1]+a[1]*f,t[2]+a[2]*f]}const zU=de,HH=Object.freeze(Object.defineProperty({__proto__:null,AREA_METRICS:tE,AnnotationMultiSlice:q2,IslandRemoval:zi,annotationHydration:nO,boundingBox:$2,calibrateImageSpacing:z2,cine:Pk,contourSegmentation:zT,contours:aA,createGetTextLines:zf,createMultiResultLine:nE,debounce:Yr,defaultAreaGetTextLines:eE,draw3D:Dk,drawing:mT,dynamicVolume:dU,geometricSurfaceUtils:MU,getAnnotationNearPoint:G2,getAnnotationNearPointOnEnabledElement:q1,getCalibratedAspect:Kh,getCalibratedLengthUnitsAndScale:ao,getCalibratedProbeUnitsAndValue:Cr,getClosestImageIdForStackViewport:Gf,getOrCreateImageVolume:vd,getPixelValueUnits:bi,getPixelValueUnitsImageId:Hw,getSlabIntensityPickContext:hS,getSphereBoundsInfo:Z1,getViewportForAnnotation:fd,isObject:vb,jumpToFocalPoint:yl,math:Rx,moveAnnotationToViewPlane:AU,normalizeViewportPlane:rE,orientation:vk,pickIntensityPointInSlab:fS,planar:Fx,planarFreehandROITool:Lk,pointInSurroundingSphereCallback:_U,pointToString:J1,polyDataUtils:uU,rectangleROITool:Uk,roundNumber:zU,safeStructuredClone:hd,segmentation:rk,setAnnotationLabel:dS,spatial:gk,stackContextPrefetch:nU,stackPrefetch:qk,throttle:Un,touch:R_,triggerAnnotationRender:xa,triggerAnnotationRenderForToolGroupIds:lw,triggerAnnotationRenderForViewportIds:V,triggerEvent:Rt,usFanExtraction:GU,viewport:oU,viewportFilters:zx,voi:bU},Symbol.toStringTag,{value:"Module"})),WH=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));function gS(i,t){const n=me;i.forEach(e=>{n.updateSegmentation(e.segmentationId,e.payload),t||Co(e.segmentationId)})}function $U(i,t,n){me.setSegmentationRepresentationVisibility(i,t,n)}function jU(i,t,n){const e=Rn(i,t);e&&e.forEach(o=>{$U(i,{segmentationId:o.segmentationId,type:o.type},n)})}function XU(i,t){return Fw(i,t)}function qU(i,t,n,e){const o=Rn(i,t);o&&(o.forEach(s=>{!s.segments||!s.segments[n]||(s.visible||=e,s.segments[n].visible=e)}),Nf(t.segmentationId),Mo(i,t.segmentationId))}function YU(i,t,n){return!mS(i,t).has(n)}function mS(i,t){const n=Zl(i,t);return n?Object.entries(n.segments).reduce((o,[s,a])=>(a.visible||o.add(Number(s)),o),new Set):new Set}const KU=Object.freeze(Object.defineProperty({__proto__:null,getHiddenSegmentIndices:mS,getSegmentIndexVisibility:YU,getSegmentationRepresentationVisibility:XU,setSegmentIndexVisibility:qU,setSegmentationRepresentationVisibility:jU},Symbol.toStringTag,{value:"Module"}));function ZU(i){return Yn.getStyle(i)}function JU(i,t,n){Yn.setStyle(i,t,n),!i.viewportId&&!i.segmentationId&&pd().forEach(o=>{_i(o.segmentationId)}),Mo(i.viewportId,i.segmentationId,i.type)}function QU(i,t){Yn.setRenderInactiveSegmentations(i,t),_i(i),bw(i).forEach(e=>{Mo(i,e.segmentationId)})}function tV(i){return Yn.getRenderInactiveSegmentations(i)}function eV(){Yn.resetToGlobalStyle(),_i()}function nV(i){return Yn.hasCustomStyle(i)}const oV=Object.freeze(Object.defineProperty({__proto__:null,getRenderInactiveSegmentations:tV,getStyle:ZU,hasCustomStyle:nV,resetToGlobalStyle:eV,setRenderInactiveSegmentations:QU,setStyle:JU},Symbol.toStringTag,{value:"Module"})),iV=Object.freeze(Object.defineProperty({__proto__:null,color:IA,style:oV,visibility:KU},Symbol.toStringTag,{value:"Module"}));async function sV(i){const t=tx(i);return Co(i.segmentationId),t}const{DefaultHistoryMemo:aV}=Nl;function pS(i,t,n){const e=Dt(i);if(e.representationData.Labelmap){const o=Hi(e,t),s=Sr(e,t);o&&s&&((s.volumeId?[Q.getVolume(s.volumeId)]:(s.imageIds??[]).map(r=>Q.getImage(r))).forEach(r=>{if(!r)return;const{voxelManager:c}=r,l=n?.recordHistory?Ar(i,c):null,d=l?.voxelManager??c;c.forEach(({value:u,index:h})=>{u===o.labelValue&&d.setAtIndex(h,0)}),l?.commitMemo()&&aV.push(l)}),Vy(e,t)),He(i)}else throw new Error("Invalid segmentation type, only labelmap is supported right now")}function rV(i,t,n){const e=yr(i);if(!e)return;const o=e.get(t);if(!o)return;const s=Array.from(o),a=[];for(const r of s){const c=ne(r);Da(c)&&a.push(c)}if(a.length!==0)for(const r of a)r.parentAnnotationUID||(n?.recordHistory&&be.createAnnotationMemo(null,r,{deleting:!0}),gd(r))}function cV(i,t,n={setNextSegmentAsActive:!0}){const e=Dt(i);if(e?.representationData.Contour)rV(i,t,{recordHistory:n.recordHistory});else if(e?.representationData.Labelmap)pS(i,t,{recordHistory:n.recordHistory});else throw new Error("Invalid segmentation type");const o=xn(i)===t,{segments:s}=e;delete s[t];const a={...s};if(gS([{segmentationId:i,payload:{segments:a}}]),o&&n.setNextSegmentAsActive!==!1){const c=Object.keys(s).map(Number).sort((h,f)=>h-f),l=c.indexOf(t),d=c[l+1],u=c[l-1];d!==void 0?Or(i,d):u!==void 0&&Or(i,u)}_s(i).forEach(c=>{Rn(c,{segmentationId:i}).forEach(d=>{delete d.segments[t]})})}function lV(i){const t=me,n=Dt(i);return t.getLabelmapImageIds(n.representationData)}const dV={clearSegmentValue:pS,convertStackToVolumeLabelmap:sV,computeVolumeLabelmapFromStack:FE,convertVolumeToStackLabelmap:ek},BH=Object.freeze(Object.defineProperty({__proto__:null,activeSegmentation:e2,addContourRepresentationToViewport:Yf,addContourRepresentationToViewportMap:KN,addDefaultSegmentationListener:Tf,addLabelmapRepresentationToViewport:UE,addLabelmapRepresentationToViewportMap:ZN,addRepresentationData:Hf,addSegmentationListener:gw,addSegmentationRepresentations:Oa,addSegmentations:hw,addSurfaceRepresentationToViewport:VE,addSurfaceRepresentationToViewportMap:JN,config:iV,defaultSegmentationStateManager:me,getActiveSegmentation:Wi,getCurrentLabelmapImageIdsForViewport:ys,getLabelmapImageIds:lV,getLabelmapImageIdsForImageId:HM,helpers:dV,removeAllSegmentationListeners:kM,removeAllSegmentationRepresentations:vw,removeAllSegmentations:Sw,removeContourRepresentation:ww,removeLabelmapRepresentation:Iw,removeSegment:cV,removeSegmentation:Af,removeSegmentationListener:Mf,removeSegmentationRepresentation:Ta,removeSegmentationRepresentations:mw,removeSurfaceRepresentation:Ew,segmentIndex:XN,segmentLocking:mA,segmentationStyle:Yn,state:$M,strategies:JR,triggerSegmentationEvents:Ay,updateSegmentations:gS,utilities:uA},Symbol.toStringTag,{value:"Module"}));class cg{constructor(t){this._controlPoints=[],this._invalidated=!1,this._length=0,this._controlPoints=[],this._resolution=t?.resolution??20,this._fixedResolution=t?.fixedResolution??!1,this._closed=t?.closed??!1,this._invalidated=!0}get controlPoints(){return this._controlPoints}get numControlPoints(){return this._controlPoints.length}get resolution(){return this._resolution}set resolution(t){this._fixedResolution||this._resolution===t||(this._resolution=t,this.invalidated=!0)}get fixedResolution(){return this._fixedResolution}get closed(){return this._closed}set closed(t){this._closed!==t&&(this._closed=t,this.invalidated=!0)}get aabb(){return this._update(),this._aabb}get length(){return this._update(),this._length}get invalidated(){return this._invalidated}set invalidated(t){this._invalidated=t}hasTangentPoints(){return!1}addControlPoint(t){this._controlPoints.push([t[0],t[1]]),this.invalidated=!0}addControlPoints(t){t.forEach(n=>this.addControlPoint(n))}addControlPointAtU(t){const n=this._getLineSegmentAt(t),{start:e,end:o}=n.points,s=Math.floor(t),a=this._curveSegments[s],r=t-Math.floor(s),c=[e[0]+r*(o[0]-e[0]),e[1]+r*(o[1]-e[1])],l=this._controlPoints.indexOf(a.controlPoints.p1)+1;return this._controlPoints.splice(l,0,c),this.invalidated=!0,{index:l,point:c}}deleteControlPointByIndex(t){const n=this._closed?3:1;return t>=0&&t<this._controlPoints.length&&this._controlPoints.length>n?(this._controlPoints.splice(t,1),this.invalidated=!0,!0):!1}clearControlPoints(){this._controlPoints=[],this.invalidated=!0}setControlPoints(t){this.clearControlPoints(),this.addControlPoints(t)}updateControlPoint(t,n){if(t<0||t>=this._controlPoints.length)throw new Error("Index out of bounds");this._controlPoints[t]=[...n],this.invalidated=!0}getControlPoints(){return this._controlPoints.map(t=>[t[0],t[1]])}getClosestControlPoint(t){const n=this._controlPoints;let e=1/0,o=-1;for(let s=0,a=n.length;s<a;s++){const r=n[s],c=t[0]-r[0],l=t[1]-r[1],d=c*c+l*l;d<e&&(e=d,o=s)}return{index:o,point:o===-1?void 0:[...n[o]],distance:Math.sqrt(e)}}getClosestControlPointWithinDistance(t,n){const e=this.getClosestControlPoint(t);return e.distance<=n?e:void 0}getClosestPoint(t){this._update();const n=this._getCurveSegmmentsDistanceSquaredInfo(t);if(!n.length)return;n.sort((u,h)=>u.distanceSquared-h.distanceSquared);let e,o=-1,s=1/0,a,r;for(let u=0;u<n.length;u++){const h=n[u];if(h.distanceSquared>s)continue;const{curveSegmentIndex:f,curveSegment:g}=h,{lineSegments:m}=g;for(let p=0;p<m.length;p++){const v=m[p],{point:I,distanceSquared:w}=sl(v.points.start,v.points.end,t);w<s&&(r=v,o=f,a=h.curveSegment,e=I,s=w)}}const l=(r.previousLineSegmentsLength+ro(r.points.start,e))/a.length,d=o+l;return{point:e,uValue:d,distance:Math.sqrt(s)}}getClosestPointOnControlPointLines(t){const n=[...this._controlPoints];if(this._closed&&n.push(this._controlPoints[0]),!n.length)return;let e,o=1/0,s=n[0];for(let a=1,r=n.length;a<r;a++){const c=n[a],{point:l,distanceSquared:d}=sl(s,c,t);d<o&&(e=l,o=d),s=c}return{point:e,distance:Math.sqrt(o)}}getPolylinePoints(){return this._update(),this._convertCurveSegmentsToPolyline(this._curveSegments)}getPreviewPolylinePoints(t,n){if(this._closed)return[];this._update();const o=this.getClosestControlPointWithinDistance(t,n)?.index===0,s=this.getPreviewCurveSegments(t,o);return s?.length?this._convertCurveSegmentsToPolyline(s):[]}isPointNearCurve(t,n){this._update();const e=this._getCurveSegmmentsWithinDistance(t,n),o=n*n;for(let s=0;s<e.length;s++){const{lineSegments:a}=e[s];for(let r=0;r<a.length;r++){const c=a[r];if(tc(c.points.start,c.points.end,t)<=o)return!0}}return!1}containsPoint(t){if(this._update(),this._controlPoints.length<3)return!1;const e=[...this._curveSegments],o=this._getClosingCurveSegmentWithStraightLineSegment();o&&e.push(o);let s=0;for(let a=0;a<e.length;a++){const r=e[a],{aabb:c}=r;if(!(t[0]<=c.maxX&&t[1]>=c.minY&&t[1]<c.maxY))continue;const{lineSegments:d}=r;for(let u=0;u<d.length;u++){const h=d[u],{aabb:f}=h;if(t[0]<=f.maxX&&t[1]>=f.minY&&t[1]<f.maxY){const{start:m,end:p}=h.points,v=m[0]===p[0],I=(t[1]-m[1])*(p[0]-m[0])/(p[1]-m[1])+m[0];s+=v||t[0]<=I?1:0}}}return s%2===1}_update(){if(!this._invalidated)return;const t=this.getSplineCurves();let n=0,e=1/0,o=1/0,s=-1/0,a=-1/0;for(let r=0,c=t.length;r<c;r++){const{aabb:l,length:d}=t[r];e=e<=l.minX?e:l.minX,o=o<=l.minY?o:l.minY,s=s>=l.maxX?s:l.maxX,a=a>=l.maxY?a:l.maxY,n+=d}this._curveSegments=t,this._aabb={minX:e,minY:o,maxX:s,maxY:a},this._length=n,this._invalidated=!1}_convertCurveSegmentsToPolyline(t){this._update();const n=[];return t.forEach(({lineSegments:e},o)=>{e.forEach((s,a)=>{o===0&&a===0&&n.push([...s.points.start]),n.push([...s.points.end])})}),n}_getCurveSegmmentsDistanceSquaredInfo(t){this._update();const n=[],{_curveSegments:e}=this;for(let o=0;o<e.length;o++){const s=e[o],a=ol(s.aabb,t);n.push({curveSegmentIndex:o,curveSegment:s,distanceSquared:a})}return n}_getCurveSegmmentsWithinDistance(t,n){this._update();const e=n*n;if(ol(this.aabb,t)>e)return[];const o=this._getCurveSegmmentsDistanceSquaredInfo(t),s=[];for(let a=0,r=o.length;a<r;a++){const{curveSegment:c,distanceSquared:l}=o[a];l<=e&&s.push(c)}return s}_getLineSegmentAt(t){this._update();const n=Math.floor(t),e=t-n,o=this._curveSegments[n],{lineSegments:s}=o,a=o.length*e;for(let r=0;r<s.length;r++){const c=s[r],l=c.previousLineSegmentsLength+c.length;if(a>=c.previousLineSegmentsLength&&a<=l)return c}}_getClosingCurveSegmentWithStraightLineSegment(){if(this.closed)return;const t=this._controlPoints,n=t[0],e=t[t.length-1],o={points:{start:[...n],end:[...e]},aabb:{minX:Math.min(n[0],e[0]),minY:Math.min(n[1],e[1]),maxX:Math.max(n[0],e[0]),maxY:Math.max(n[1],e[1])}};return{aabb:{minX:o.aabb.minX,minY:o.aabb.minY,maxX:o.aabb.maxX,maxY:o.aabb.maxY},lineSegments:[o]}}}const uV=1e-8;class lg extends cg{getPreviewCurveSegments(t,n){const e=this._getNumCurveSegments()+1,o=Math.max(0,e-2),s=n?e:e-1,a=this.getTransformMatrix(),r=[...this.controlPoints],c=[];n||r.push(t);for(let l=o;l<=s;l++){const d=this._getCurveSegment(l,a,r,n);c.push(d)}return c}getSplineCurves(){const t=this._getNumCurveSegments(),n=new Array(t);if(t<=0)return[];const e=this.getTransformMatrix();let o=0;for(let s=0;s<t;s++){const a=this._getCurveSegment(s,e);a.previousCurveSegmentsLength=o,n[s]=a,o+=a.length}return n}_getNumCurveSegments(t=this.controlPoints,n=this.closed){return n?t.length:Math.max(0,t.length-1)}_getPoint(t,n,e=this.controlPoints,o=this.closed){const s=this._getNumCurveSegments(e,o),a=Math.floor(t);let r=a%s;const c=t-a;if(r<0||r>=s)if(this.closed)r=(s+r)%s;else return;const{p0:d,p1:u,p2:h,p3:f}=this._getCurveSegmentPoints(r,e,o),g=c*c,m=g*c,p=Yd(1,c,g,m),v=sy(xI(),p,n);return[zu(v,Yd(d[0],u[0],h[0],f[0])),zu(v,Yd(d[1],u[1],h[1],f[1]))]}_getCurveSegmentPoints(t,n=this.controlPoints,e=this.closed){const o=this._getNumCurveSegments(n,e),s=t,a=s-1,r=e?(s+1)%o:s+1,c=r+1,l=n[s],d=n[r];let u,h;return a>=0?u=n[a]:u=e?n[n.length-1]:Xu(d,l),c<n.length?h=n[c]:h=e?n[0]:Xu(l,d),{p0:u,p1:l,p2:d,p3:h}}_getLineSegments(t,n,e=this.controlPoints,o=this.closed){const s=this._getNumCurveSegments(e,o),a=this.resolution+1,r=1/a,c=t;let l=c+1;!o&&t===s-1&&(l-=uV);const d=[];let u,h,f=0;for(let g=0,m=c;g<=a;g++,m+=r){m=m>l?l:m;const p=this._getPoint(m,n,e,o);if(!g){u=p;continue}h=p;const v=h[0]-u[0],I=h[1]-u[1],w=Math.sqrt(v**2+I**2),C={minX:u[0]<=h[0]?u[0]:h[0],maxX:u[0]>=h[0]?u[0]:h[0],minY:u[1]<=h[1]?u[1]:h[1],maxY:u[1]>=h[1]?u[1]:h[1]};d.push({points:{start:u,end:h},aabb:C,length:w,previousLineSegmentsLength:f}),u=h,f+=w}return d}_getCurveSegment(t,n=this.getTransformMatrix(),e=this.controlPoints,o=this.closed){const{p0:s,p1:a,p2:r,p3:c}=this._getCurveSegmentPoints(t,e,o),l=this._getLineSegments(t,n,e,o);let d=0,u=1/0,h=1/0,f=-1/0,g=-1/0;return l.forEach(({aabb:m,length:p})=>{u=Math.min(u,m.minX),h=Math.min(h,m.minY),f=Math.max(f,m.maxX),g=Math.max(g,m.maxY),d+=p}),{controlPoints:{p0:s,p1:a,p2:r,p3:c},aabb:{minX:u,minY:h,maxX:f,maxY:g},length:d,previousCurveSegmentsLength:0,lineSegments:l}}}const hV=ny(qi(),Bu(1,4,1,0,-3,0,3,0,3,-6,3,0,-1,3,-3,1),1/6);class vS extends lg{getTransformMatrix(){return hV}}class Fr extends lg{constructor(t){super(t),this._scale=t?.scale??.5,this._fixedScale=t?.fixedScale??!1}get scale(){return this._scale}set scale(t){this._fixedScale||this._scale===t||(this._scale=t,this.invalidated=!0)}get fixedScale(){return this._fixedScale}getTransformMatrix(){const{scale:t}=this,n=2*t;return[0,1,0,0,-t,0,t,0,n,t-3,3-n,-t,-t,2-t,t-2,t]}}class IS extends Fr{constructor(){super({scale:.5,fixedScale:!0})}}class wS extends Fr{constructor(){super({resolution:0,fixedResolution:!0,scale:0,fixedScale:!0})}}class ES extends cg{getSplineCurves(){return[]}getLineSegments(){return[]}getPreviewCurveSegments(t,n){return[]}}const fV=[1,0,0,-2,2,0,1,-2,1];class gV extends ES{hasTangentPoints(){return!0}getTransformMatrix(){return fV}}const zH=Object.freeze(Object.defineProperty({__proto__:null,BSpline:vS,CardinalSpline:Fr,CatmullRomSpline:IS,CubicSpline:lg,LinearSpline:wS,QuadraticBezier:gV,QuadraticSpline:ES,Spline:cg},Symbol.toStringTag,{value:"Module"}));class mV extends Ee{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{limitToViewport:!1,ignoreX:!1,ignoreY:!1,ignoreZ:!1}}){super(t,n)}touchDragCallback(t){this._dragCallback(t)}mouseDragCallback(t){this._dragCallback(t)}_checkImageInViewport(t,n){const{canvas:e}=t,o=window.devicePixelRatio,s=0,a=e.width/o,r=0,c=e.height/o,l=t.getDefaultActor(),d=t.getRenderer();let u;l&&RC(l)?u=l.actor.getMapper().getInputData().getBounds():u=d.computeVisiblePropBounds();const[h,f]=t.worldToCanvas([u[0],u[2],u[4]]),[g,m]=t.worldToCanvas([u[1],u[3],u[5]]);if(t.getZoom()<=1){if(h+n[0]<s&&n[0]<0||g+n[0]>a&&n[0]>0||f+n[1]<r&&n[1]<0||m+n[1]>c&&n[1]>0)return!1}else if(h+n[0]>s&&n[0]>0||g+n[0]<a&&n[0]<0||f+n[1]>r&&n[1]>0||m+n[1]<c&&n[1]<0)return!1;return!0}_dragCallback(t){const{element:n,deltaPoints:e}=t.detail,o=N(n),s=e.world,a=e.canvas;if(s[0]===0&&s[1]===0&&s[2]===0)return;this.configuration.ignoreX&&(s[0]=0),this.configuration.ignoreY&&(s[1]=0),this.configuration.ignoreZ&&(s[2]=0);const r=o.viewport,c=pV(r);if(!vV(c)){if(!gr(r))return;const f=r.getPan();r.setPan([f[0]+a[0],f[1]+a[1]]),r.render();return}const{focalPoint:l,position:d}=c;if(this.configuration.limitToViewport&&!this._checkImageInViewport(r,a))return;const u=[d[0]-s[0],d[1]-s[1],d[2]-s[2]],h=[l[0]-s[0],l[1]-s[1],l[2]-s[2]];r.setCamera({focalPoint:h,position:u}),r.render()}}function pV(i){const t=i;return typeof t.getCamera=="function"?t.getCamera():void 0}function vV(i){return!!(i&&Array.isArray(i.focalPoint)&&Array.isArray(i.position))}mV.toolName="Pan";function IV(i){const t=Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2]);return t>0?[i[0]/t,i[1]/t,i[2]/t]:i}function Td(i,t){const n=i;if(ie(i)){if(i.type===so.PLANAR_NEXT&&typeof n.setViewReference=="function"){const e=i.getViewReference(),o=t.focalPoint??e?.cameraFocalPoint,s=t.viewUp??e?.viewUp;let a=t.viewPlaneNormal;!a&&t.position&&o&&(a=IV([t.position[0]-o[0],t.position[1]-o[1],t.position[2]-o[2]]));const r=i,c=()=>r.getResolvedView?.()?.toICamera?.()?.parallelScale,l=c(),d=r.getZoom?.();n.setViewReference({...e,cameraFocalPoint:o,viewPlaneNormal:a,viewUp:s}),r.invalidateResolvedView?.();const u=c();if(l&&u&&typeof d=="number"&&typeof r.setZoom=="function"){const h=u*d/l;Number.isFinite(h)&&h>0&&r.setZoom(h)}i.render();return}n.setViewState?.(t);return}n.setCamera?.(t)}function Md(i,t){const n=i;if(ie(i)){n.resetViewState?.(t);return}n.resetCamera?.(t)}class wV extends Ee{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{rotateIncrementDegrees:2,rotateSampleDistanceFactor:2}}){super(t,n),this._resizeObservers=new Map,this._hasResolutionChanged=!1,this.preMouseDownCallback=e=>{const o=e.detail,{element:s}=o,a=N(s),{viewport:r}=a,d=r.getDefaultActor().actor.getMapper();if(!("getSampleDistance"in d||"getCurrentSampleDistance"in d))return!0;const h=d.getSampleDistance();if(!this._hasResolutionChanged){const{rotateSampleDistanceFactor:f}=this.configuration;d.setSampleDistance(h*f),this._hasResolutionChanged=!0,this.cleanUp!==null&&(document.removeEventListener("mouseup",this.cleanUp),document.removeEventListener("touchend",this.cleanUp),document.removeEventListener("touchcancel",this.cleanUp)),this.cleanUp=()=>{document.removeEventListener("mouseup",this.cleanUp),document.removeEventListener("touchend",this.cleanUp),document.removeEventListener("touchcancel",this.cleanUp),d.setSampleDistance(h),r.render(),this._hasResolutionChanged=!1},document.addEventListener("mouseup",this.cleanUp,{once:!0}),document.addEventListener("touchend",this.cleanUp,{once:!0}),document.addEventListener("touchcancel",this.cleanUp,{once:!0})}return!0},this._getViewportsInfo=()=>Be(this.toolGroupId).viewportsInfo,this.onSetToolActive=()=>{const e=()=>{this._getViewportsInfo().forEach(({viewportId:s,renderingEngineId:a})=>{if(!this._resizeObservers.has(s)){const{viewport:r}=ae(s,a)||{viewport:null};if(!r)return;const{element:c}=r,l=new ResizeObserver(()=>{const d=ae(s,a);if(!d)return;const{viewport:u}=d,h=Aa(u);Md(u),uc(u,h),u.render()});l.observe(c),this._resizeObservers.set(s,l)}})};e(),this._viewportAddedListener=o=>{o.detail.toolGroupId===this.toolGroupId&&e()},Z.addEventListener(E.TOOLGROUP_VIEWPORT_ADDED,this._viewportAddedListener)},this.onSetToolDisabled=()=>{this._resizeObservers.forEach((e,o)=>{e.disconnect(),this._resizeObservers.delete(o)}),this._viewportAddedListener&&(Z.removeEventListener(E.TOOLGROUP_VIEWPORT_ADDED,this._viewportAddedListener),this._viewportAddedListener=null)},this.rotateCamera=(e,o,s,a)=>{const r=e.getVtkActiveCamera(),c=r.getViewUp(),l=r.getFocalPoint(),d=r.getPosition(),u=[0,0,0],h=[0,0,0],f=[0,0,0],g=Qn(new Float32Array(16));fo(g,g,o),go(g,g,a,s),fo(g,g,[-o[0],-o[1],-o[2]]),Ue(u,d,g),Ue(h,l,g),Qn(g),go(g,g,a,s),Ue(f,c,g),Td(e,{position:u,viewUp:f,focalPoint:h})},this.touchDragCallback=this._dragCallback.bind(this),this.mouseDragCallback=this._dragCallback.bind(this)}_dragCallback(t){const{element:n,currentPoints:e,lastPoints:o}=t.detail,s=e.canvas,a=o.canvas,{rotateIncrementDegrees:r}=this.configuration,c=N(n),{viewport:l}=c,d=ht(l),u=n.clientWidth,h=n.clientHeight,f=[s[0]/u,s[1]/h],g=[a[0]/u,a[1]/h],m=[u*.5,h*.5],p=l.canvasToWorld(m),I=(1+Math.abs([.5,.5][0]))**2,w=[g[0],0,0],C=[f[0],0,0],S=w[0]**2,b=C[0]**2,_=S>I?0:Math.sqrt(I-S),y=b>I?0:Math.sqrt(I-b),D=[w[0],0,_];Vt.normalize(D);const T=[C[0],0,y];Vt.normalize(T);const P=Vt.dot(D,T);if(Math.abs(P)>1e-4){const x=-2*Math.acos(Vt.clampValue(P,-1,1))*Math.sign(f[0]-g[0])*r,M=d.viewUp,L=d.viewPlaneNormal,R=[0,0,0],U=[0,0,0];Vt.cross(M,L,R),Vt.normalize(R),Vt.cross(L,R,U),Vt.normalize(U),Vt.normalize(M),this.rotateCamera(l,p,U,x);const W=(g[1]-f[1])*r;this.rotateCamera(l,p,R,W),l.render()}}}wV.toolName="TrackballRotate";function EV(i,t){t.classHierarchy.push("vtkSphereSource"),i.requestData=(n,e)=>{let o=e[0];const s=o?o.getPoints().getDataType():t.pointType;o=o?.initialize()||Vo.newInstance();let a=0,{thetaResolution:r}=t,c=t.startTheta<t.endTheta?t.startTheta:t.endTheta;c*=Math.PI/180;let l=t.endTheta>t.startTheta?t.endTheta:t.startTheta;l*=Math.PI/180;let d=t.startPhi<t.endPhi?t.startPhi:t.endPhi;d*=Math.PI/180;let u=t.endPhi>t.startPhi?t.endPhi:t.startPhi;u*=Math.PI/180,Math.abs(c-l)<2*Math.PI&&++r;const h=(l-c)/t.thetaResolution,f=t.startPhi<=0?1:0,g=t.phiResolution+(t.endPhi>=180?-1:0),m=t.phiResolution*r+2,p=t.phiResolution*2*t.thetaResolution;let v=0,I=Lt.newTypedArray(s,m*3),w=new Float32Array(m*3),C=0,S=new Uint32Array(p*5);t.startPhi<=0&&(I[v*3+0]=t.center[0],I[v*3+1]=t.center[1],I[v*3+2]=t.center[2]+t.radius,w[v*3+0]=0,w[v*3+1]=0,w[v*3+2]=1,v++,a++),t.endPhi>=180&&(I[v*3+0]=t.center[0],I[v*3+1]=t.center[1],I[v*3+2]=t.center[2]-t.radius,w[v*3+0]=0,w[v*3+1]=0,w[v*3+2]=-1,v++,a++);const b=t.phiResolution-a,_=(u-d)/(t.phiResolution-1);for(let T=0;T<r;T++){const P=c+T*h;for(let x=f;x<g;x++){const M=d+x*_,L=t.radius*Math.sin(M);w[v*3+0]=L*Math.cos(P),w[v*3+1]=L*Math.sin(P),w[v*3+2]=t.radius*Math.cos(M),I[v*3+0]=w[v*3+0]+t.center[0],I[v*3+1]=w[v*3+1]+t.center[1],I[v*3+2]=w[v*3+2]+t.center[2];let R=Math.sqrt(w[v*3+0]*w[v*3+0]+w[v*3+1]*w[v*3+1]+w[v*3+2]*w[v*3+2]);R=R===0?1:R,w[v*3+0]/=R,w[v*3+1]/=R,w[v*3+2]/=R,v++}}const y=b*r;if(Math.abs(c-l)<2*Math.PI&&--r,t.startPhi<=0)for(let T=0;T<r;T++)S[C++]=3,S[C++]=b*T+a,S[C++]=b*(T+1)%y+a,S[C++]=0;if(t.endPhi>=180){const T=b-1+a;for(let P=0;P<r;P++)S[C++]=3,S[C++]=b*P+T,S[C++]=a-1,S[C++]=b*(P+1)%y+T}for(let T=0;T<r;T++)for(let P=0;P<b-1;P++){const x=b*T+P+a,M=x+1,L=(b*(T+1)+P)%y+a+1;t.latLongTessellation?(S[C++]=4,S[C++]=x,S[C++]=M,S[C++]=L,S[C++]=L-1):(S[C++]=3,S[C++]=x,S[C++]=M,S[C++]=L,S[C++]=3,S[C++]=x,S[C++]=L,S[C++]=L-1)}I=I.subarray(0,v*3),o.getPoints().setData(I,3),w=w.subarray(0,v*3);const D=_n.newInstance({name:"Normals",values:w,numberOfComponents:3});o.getPointData().setNormals(D),S=S.subarray(0,C),o.getPolys().setData(S,1),e[0]=o}}var SV={radius:.5,latLongTessellation:!1,thetaResolution:8,startTheta:0,endTheta:360,phiResolution:8,startPhi:0,endPhi:180,center:[0,0,0],pointType:"Float64Array"};function SS(i,t,n={}){Object.assign(t,SV,n),Lt.obj(i,t),Lt.setGet(i,t,["radius","latLongTessellation","thetaResolution","startTheta","endTheta","phiResolution","startPhi","endPhi"]),Lt.setGetArray(i,t,["center"],3),Lt.algo(i,t,0,1),EV(i,t)}var CV=Lt.newInstance(SS,"vtkSphereSource"),bV={newInstance:CV,extend:SS};const Te={XMIN:0,XMAX:1,YMIN:2,YMAX:3,ZMIN:4,ZMAX:5},mt={XMIN:0,XMAX:1,YMIN:2,YMAX:3,ZMIN:4,ZMAX:5,XMIN_YMIN_ZMIN:6,XMIN_YMIN_ZMAX:7,XMIN_YMAX_ZMIN:8,XMIN_YMAX_ZMAX:9,XMAX_YMIN_ZMIN:10,XMAX_YMIN_ZMAX:11,XMAX_YMAX_ZMIN:12,XMAX_YMAX_ZMAX:13},Cn=6,_V=.01,yV=1e-10,xV=1e-8,PV=1e5,DV=1,xp=6;function TV(i){const t=i.getDirection();return{xDir:Wt([0,0,0],t.slice(0,3)),yDir:Wt([0,0,0],t.slice(3,6)),zDir:Wt([0,0,0],t.slice(6,9))}}function MV(i){const t=i.replace("corner_","");return{isXMin:t.includes("XMIN"),isXMax:t.includes("XMAX"),isYMin:t.includes("YMIN"),isYMax:t.includes("YMAX"),isZMin:t.includes("ZMIN"),isZMax:t.includes("ZMAX")}}function ns(i){return i.map(t=>({origin:[...t.origin],normal:[...t.normal]}))}function AV(i){return i===Te.XMIN||i===Te.XMAX?"SAGITTAL":i===Te.YMIN||i===Te.YMAX?"CORONAL":i===Te.ZMIN||i===Te.ZMAX?"AXIAL":null}function Pp(i){if(!i)return null;const t={AXIAL:[0,0,1],CORONAL:[0,1,0],SAGITTAL:[1,0,0]};for(const[n,e]of Object.entries(t))if(NC(1,xt(e,i),_V))return n;return null}function LV(i,t,n){const e=i.normal,o=i.origin,s=t,a=n,r=B();Me(r,e,s);const c=Nv(r);if(c<yV)return null;const l=Vt.dot(e,o),d=Vt.dot(s,a),u=B(),h=B();Me(u,s,r),bn(u,u,l),Me(h,r,e),bn(h,h,d);const f=B();if(yn(f,u,h),bn(f,f,1/c),!Number.isFinite(f[0])||!Number.isFinite(f[1])||!Number.isFinite(f[2]))return null;const g=B();return bn(g,r,1/Math.sqrt(c)),{direction:g,point:f}}function OV(i,t,n){const e=PV,o=ee([0,0,0],i,t,-e),s=ee([0,0,0],i,t,e),a=n.worldToCanvas(o),r=n.worldToCanvas(s),{clientWidth:c,clientHeight:l}=n.canvas,d=[0,0,c,l],u=gi(a),h=gi(r),f=!isNaN(u[0])&&!isNaN(u[1]),g=!isNaN(h[0])&&!isNaN(h[1]);if(!f||!g||li(u,h,d)===0)return null;const p=!isNaN(u[0])&&!isNaN(u[1]),v=!isNaN(h[0])&&!isNaN(h[1]);if(!p||!v)return null;const[I,w,C,S]=d,b=u[0]>=I-1&&u[0]<=C+1&&u[1]>=w-1&&u[1]<=S+1,_=h[0]>=I-1&&h[0]<=C+1&&h[1]>=w-1&&h[1]<=S+1;if(!b||!_)return null;const y=h[0]-u[0],D=h[1]-u[1];return Math.sqrt(y*y+D*D)<DV?null:{start:u,end:h}}const Gr=new Map;function RV(i,t){return Gr.has(i)?!1:(Gr.set(i,t),!0)}function Dp(i,t){Gr.get(i)===t&&Gr.delete(i)}function NV(i,t){return Gr.get(i)===t}class kV extends Ee{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{showCornerSpheres:!0,showHandles:!0,showClippingPlanes:!0,mobile:{enabled:!1,opacity:.8},initialCropFactor:.08,sphereColors:{SAGITTAL:[1,1,0],CORONAL:[0,1,0],AXIAL:[1,0,0],CORNERS:[0,0,1]},sphereRadius:8,grabSpherePixelDistance:20,rotateIncrementDegrees:2,rotateSampleDistanceFactor:2,rotateClippingPlanesIncrementDegrees:5}}){super(t,n),this._resizeObservers=new Map,this._hasResolutionChanged=!1,this.originalClippingPlanes=[],this.draggingSphereIndex=null,this.rotatePlanesOnDrag=!1,this.suppressPlaneRotationForCurrentDrag=!1,this.cornerDragOffset=null,this.faceDragOffset=null,this.volumeDirectionVectors=null,this.sphereStates=[],this.edgeLines={},this.onSetToolConfiguration=()=>{},this.onSetToolEnabled=()=>{},this.onCameraModified=e=>{const{element:o}=e.currentTarget?{element:e.currentTarget}:e.detail,s=N(o);this._updateClippingPlanes(s.viewport),s.viewport.render()},this.preMouseDownCallback=e=>{const o=e.detail,{element:s}=o,a=N(s),{viewport:r}=a;this.suppressPlaneRotationForCurrentDrag=NV(r.id,"orientation-controller");const c=this._getVolumeActor(r);if(!c)return!1;const l=c.getMapper(),d=[e.detail.currentPoints.canvas[0],e.detail.currentPoints.canvas[1]];this.draggingSphereIndex=null,this.cornerDragOffset=null,this.faceDragOffset=null;for(let f=0;f<this.sphereStates.length;++f){const g=r.worldToCanvas(this.sphereStates[f].point);if(Math.sqrt(Math.pow(d[0]-g[0],2)+Math.pow(d[1]-g[1],2))<this.configuration.grabSpherePixelDistance){this.draggingSphereIndex=f,s.style.cursor="grabbing";const p=this.sphereStates[f],v=r.canvasToWorld(d);if(p.isCorner)this.cornerDragOffset=[p.point[0]-v[0],p.point[1]-v[1],p.point[2]-v[2]],this.faceDragOffset=null;else{const I=this._getDirectionVectorForAxis(p.axis),w=[p.point[0]-v[0],p.point[1]-v[1],p.point[2]-v[2]];this.faceDragOffset=w[0]*I[0]+w[1]*I[1]+w[2]*I[2],this.cornerDragOffset=null}return!0}}if(!("getSampleDistance"in l||"getCurrentSampleDistance"in l))return!0;const h=l.getSampleDistance();if(!this._hasResolutionChanged){const{rotateSampleDistanceFactor:f}=this.configuration;l.setSampleDistance(h*f),this._hasResolutionChanged=!0,this.cleanUp!==null&&(document.removeEventListener("mouseup",this.cleanUp),document.removeEventListener("touchend",this.cleanUp),document.removeEventListener("touchcancel",this.cleanUp)),this.cleanUp=()=>{if(document.removeEventListener("mouseup",this.cleanUp),document.removeEventListener("touchend",this.cleanUp),document.removeEventListener("touchcancel",this.cleanUp),l.setSampleDistance(h),e.target.style.cursor="",this.draggingSphereIndex!==null){const g=this.sphereStates[this.draggingSphereIndex],[m]=this._getViewportsInfo(),v=Ne(m.renderingEngineId).getViewport(m.viewportId);g.isCorner&&(this._updateCornerSpheres(),this._updateFaceSpheresFromCorners(),this._updateClippingPlanesFromFaceSpheres(v))}this.draggingSphereIndex=null,this.cornerDragOffset=null,this.faceDragOffset=null,this.suppressPlaneRotationForCurrentDrag=!1,r.render(),this._hasResolutionChanged=!1},document.addEventListener("mouseup",this.cleanUp,{once:!0}),document.addEventListener("touchend",this.cleanUp,{once:!0}),document.addEventListener("touchcancel",this.cleanUp,{once:!0})}return!0},this._onMouseMoveSphere=e=>{if(this.draggingSphereIndex===null)return!1;const o=this.sphereStates[this.draggingSphereIndex];if(!o)return!1;const{viewport:s,world:a}=this._getViewportAndWorldCoords(e);if(!s||!a)return!1;if(o.isCorner){const r=this.cornerDragOffset?yn([0,0,0],a,this.cornerDragOffset):a,c=o.point,l=MV(o.uid),{xDir:d,yDir:u,zDir:h}=this._getDirectionVectors();if(!d||!u||!h)return!1;const f=[r[0]-c[0],r[1]-c[1],r[2]-c[2]],g=f[0]*d[0]+f[1]*d[1]+f[2]*d[2],m=f[0]*u[0]+f[1]*u[1]+f[2]*u[2],p=f[0]*h[0]+f[1]*h[1]+f[2]*h[2];if(l.isXMin){const v=this.sphereStates[mt.XMIN],I=[v.point[0]+g*d[0],v.point[1]+g*d[1],v.point[2]+g*d[2]];this._updateSpherePosition(mt.XMIN,I)}else if(l.isXMax){const v=this.sphereStates[mt.XMAX],I=[v.point[0]+g*d[0],v.point[1]+g*d[1],v.point[2]+g*d[2]];this._updateSpherePosition(mt.XMAX,I)}if(l.isYMin){const v=this.sphereStates[mt.YMIN],I=[v.point[0]+m*u[0],v.point[1]+m*u[1],v.point[2]+m*u[2]];this._updateSpherePosition(mt.YMIN,I)}else if(l.isYMax){const v=this.sphereStates[mt.YMAX],I=[v.point[0]+m*u[0],v.point[1]+m*u[1],v.point[2]+m*u[2]];this._updateSpherePosition(mt.YMAX,I)}if(l.isZMin){const v=this.sphereStates[mt.ZMIN],I=[v.point[0]+p*h[0],v.point[1]+p*h[1],v.point[2]+p*h[2]];this._updateSpherePosition(mt.ZMIN,I)}else if(l.isZMax){const v=this.sphereStates[mt.ZMAX],I=[v.point[0]+p*h[0],v.point[1]+p*h[1],v.point[2]+p*h[2]];this._updateSpherePosition(mt.ZMAX,I)}this._updateCornerSpheres(),this._updateFaceSpheresFromCorners()}else{const r=this._getDirectionVectorForAxis(o.axis),c=[a[0]-o.point[0],a[1]-o.point[1],a[2]-o.point[2]],l=c[0]*r[0]+c[1]*r[1]+c[2]*r[2],d=this.faceDragOffset!==null?l+this.faceDragOffset:l,u=[o.point[0]+d*r[0],o.point[1]+d*r[1],o.point[2]+d*r[2]];this._updateSpherePosition(this.draggingSphereIndex,u),this._updateCornerSpheresFromFaces(),this._updateFaceSpheresFromCorners(),this._updateCornerSpheres()}return this._updateClippingPlanesFromFaceSpheres(s),s.render(),this._notifyClippingPlanesChanged(),!0},this._onControlToolChange=e=>{const o=this._getViewport();if(e.detail.seriesInstanceUID===this.seriesInstanceUID)if(e.detail.clippingPlanes&&e.detail.clippingPlanes.length>=Cn){this.originalClippingPlanes=ns(e.detail.clippingPlanes),this._updateFaceSpheresFromClippingPlanes(),this._updateCornerSpheresFromFaces(),this._updateFaceSpheresFromCorners(),this._updateCornerSpheres();const s=this._getVolumeMapper(o);s&&this._applyClippingPlanesToMapper(s),o.render(),this._notifyClippingPlanesChanged(o)}else this._notifyClippingPlanesChanged(o)},this._getViewportsInfo=()=>Be(this.toolGroupId)?.viewportsInfo||[],this._initialize3DViewports=e=>{if(!e?.length||!e[0]){console.warn("VolumeCroppingTool: No viewportsInfo available for initialization of volumecroppingtool.");return}const o=this._getViewport();if(!o)return;const s=this._getVolumeActor(o);if(!s){console.warn("VolumeCroppingTool: No volume actors found in the viewport.");return}const a=s.getMapper().getInputData();if(!a){console.warn("VolumeCroppingTool: No image data found for volume actor.");return}this.seriesInstanceUID=a.seriesInstanceUID||"unknown",this.volumeDirectionVectors=TV(a);const{xDir:r,yDir:c,zDir:l}=this.volumeDirectionVectors,d=a.getDimensions(),u=this.configuration.initialCropFactor||.1,h=u*d[0],f=(1-u)*d[0],g=u*d[1],m=(1-u)*d[1],p=u*d[2],v=(1-u)*d[2],I=(h+f)/2,w=(g+m)/2,C=(p+v)/2,S=a.indexToWorld([h,w,C]),b=a.indexToWorld([f,w,C]),_=a.indexToWorld([I,g,C]),y=a.indexToWorld([I,m,C]),D=a.indexToWorld([I,w,p]),T=a.indexToWorld([I,w,v]),P=Di.newInstance({origin:S,normal:r}),x=Di.newInstance({origin:b,normal:[-r[0],-r[1],-r[2]]}),M=Di.newInstance({origin:_,normal:c}),L=Di.newInstance({origin:y,normal:[-c[0],-c[1],-c[2]]}),R=Di.newInstance({origin:D,normal:l}),U=Di.newInstance({origin:T,normal:[-l[0],-l[1],-l[2]]}),K=[P,x,M,L,R,U].map(nt=>({origin:[...nt.getOrigin()],normal:[...nt.getNormal()]}));this.originalClippingPlanes=K;const j=a.indexToWorld([0,0,0]),F=a.indexToWorld([d[0],d[1],d[2]]),z=ke(j,F),q=XE(z,this.configuration);this._addSphere(o,S,"x","min",null,q),this._addSphere(o,b,"x","max",null,q),this._addSphere(o,_,"y","min",null,q),this._addSphere(o,y,"y","max",null,q),this._addSphere(o,D,"z","min",null,q),this._addSphere(o,T,"z","max",null,q);const J=[a.indexToWorld([h,g,p]),a.indexToWorld([h,g,v]),a.indexToWorld([h,m,p]),a.indexToWorld([h,m,v]),a.indexToWorld([f,g,p]),a.indexToWorld([f,g,v]),a.indexToWorld([f,m,p]),a.indexToWorld([f,m,v])],it=["XMIN_YMIN_ZMIN","XMIN_YMIN_ZMAX","XMIN_YMAX_ZMIN","XMIN_YMAX_ZMAX","XMAX_YMIN_ZMIN","XMAX_YMIN_ZMAX","XMAX_YMAX_ZMIN","XMAX_YMAX_ZMAX"];for(let nt=0;nt<J.length;nt++)this._addSphere(o,J[nt],"corner",null,it[nt],q);[["XMIN_YMIN_ZMIN","XMAX_YMIN_ZMIN"],["XMIN_YMIN_ZMAX","XMAX_YMIN_ZMAX"],["XMIN_YMAX_ZMIN","XMAX_YMAX_ZMIN"],["XMIN_YMAX_ZMAX","XMAX_YMAX_ZMAX"],["XMIN_YMIN_ZMIN","XMIN_YMAX_ZMIN"],["XMIN_YMIN_ZMAX","XMIN_YMAX_ZMAX"],["XMAX_YMIN_ZMIN","XMAX_YMAX_ZMIN"],["XMAX_YMIN_ZMAX","XMAX_YMAX_ZMAX"],["XMIN_YMIN_ZMIN","XMIN_YMIN_ZMAX"],["XMIN_YMAX_ZMIN","XMIN_YMAX_ZMAX"],["XMAX_YMIN_ZMIN","XMAX_YMIN_ZMAX"],["XMAX_YMAX_ZMIN","XMAX_YMAX_ZMAX"]].forEach(([nt,lt])=>{const rt=this.sphereStates.find(Tt=>Tt.uid===`corner_${nt}`),ut=this.sphereStates.find(Tt=>Tt.uid===`corner_${lt}`);if(rt&&ut){const Tt=`edge_${nt}_${lt}`,{actor:kt,source:Pt}=jE(o,rt.point,ut.point,[.7,.7,.7],Tt,this.configuration.showHandles);this.edgeLines[Tt]={actor:kt,source:Pt,key1:nt,key2:lt}}});const ot=s.getMapper();ot.addClippingPlane(P),ot.addClippingPlane(x),ot.addClippingPlane(M),ot.addClippingPlane(L),ot.addClippingPlane(R),ot.addClippingPlane(U),Z.addEventListener(E.VOLUMECROPPINGCONTROL_TOOL_CHANGED,nt=>{this._onControlToolChange(nt)}),o.render()},this._getViewportAndWorldCoords=e=>{const o=this._getViewport(),s=e.detail.currentPoints.canvas[0],a=e.detail.currentPoints.canvas[1],r=o.canvasToWorld([s,a]);return{viewport:o,world:r}},this._getViewport=()=>{const e=this._getViewportsInfo();if(!e||e.length===0)return null;const[o]=e;return Ne(o.renderingEngineId)?.getViewport(o.viewportId)||null},this._onNewVolume=()=>{const e=this._getViewportsInfo();this.originalClippingPlanes=[],this.sphereStates=[],this.edgeLines={},this._initialize3DViewports(e)},this._rotateClippingPlanes=e=>{const{element:o,currentPoints:s,lastPoints:a}=e.detail,r=s.canvas,c=a.canvas,l=this.configuration.rotateClippingPlanesIncrementDegrees??this.configuration.rotateIncrementDegrees??5,d=N(o),{viewport:u}=d,h=ht(u),f=o.clientWidth,g=o.clientHeight,m=[r[0]/f,r[1]/g],p=[c[0]/f,c[1]/g],I=(1+Math.abs([.5,.5][0]))**2,w=[p[0],0,0],C=[m[0],0,0],S=w[0]**2,b=C[0]**2,_=S>I?0:Math.sqrt(I-S),y=b>I?0:Math.sqrt(I-b),D=[w[0],0,_];Vt.normalize(D);const T=[C[0],0,y];Vt.normalize(T);const P=Vt.dot(D,T);if(Math.abs(P)>1e-4){const x=20*Math.acos(Vt.clampValue(P,-1,1))*Math.sign(m[0]-p[0])*l,M=h.viewUp,L=h.viewPlaneNormal,R=[0,0,0],U=[0,0,0];Vt.cross(M,L,R),Vt.normalize(R),Vt.cross(L,R,U),Vt.normalize(U);const W=20*(m[1]-p[1])*l;let K;if(this.sphereStates.length>=Cn){const nt=[this.sphereStates[mt.XMIN],this.sphereStates[mt.XMAX],this.sphereStates[mt.YMIN],this.sphereStates[mt.YMAX],this.sphereStates[mt.ZMIN],this.sphereStates[mt.ZMAX]];K=[(nt[0].point[0]+nt[1].point[0]+nt[2].point[0]+nt[3].point[0]+nt[4].point[0]+nt[5].point[0])/Cn,(nt[0].point[1]+nt[1].point[1]+nt[2].point[1]+nt[3].point[1]+nt[4].point[1]+nt[5].point[1])/Cn,(nt[0].point[2]+nt[1].point[2]+nt[2].point[2]+nt[3].point[2]+nt[4].point[2]+nt[5].point[2])/Cn]}else K=[0,0,0];const j=Qn(new Float32Array(16));fo(j,j,K),go(j,j,x*Math.PI/180,U),fo(j,j,[-K[0],-K[1],-K[2]]);const F=Qn(new Float32Array(16));fo(F,F,K),go(F,F,W*Math.PI/180,R),fo(F,F,[-K[0],-K[1],-K[2]]);const z=qi();Z_(z,F,j);const q=Qn(new Float32Array(16));go(q,q,x*Math.PI/180,U);const J=Gs();qd(J,q);const it=Qn(new Float32Array(16));go(it,it,W*Math.PI/180,R);const tt=Gs();qd(tt,it);const ot=Gs();Y_(ot,tt,J);for(let nt=0;nt<this.originalClippingPlanes.length;++nt){const lt=this.originalClippingPlanes[nt],rt=Ot(lt.origin[0],lt.origin[1],lt.origin[2]);Ue(rt,rt,z),lt.origin=[rt[0],rt[1],rt[2]];const ut=Ot(lt.normal[0],lt.normal[1],lt.normal[2]);Dg(ut,ut,ot),Wt(ut,ut),lt.normal=[ut[0],ut[1],ut[2]]}this.sphereStates.length>=Cn&&(this.sphereStates[mt.XMIN].point=[...this.originalClippingPlanes[Te.XMIN].origin],this.sphereStates[mt.XMAX].point=[...this.originalClippingPlanes[Te.XMAX].origin],this.sphereStates[mt.YMIN].point=[...this.originalClippingPlanes[Te.YMIN].origin],this.sphereStates[mt.YMAX].point=[...this.originalClippingPlanes[Te.YMAX].origin],this.sphereStates[mt.ZMIN].point=[...this.originalClippingPlanes[Te.ZMIN].origin],this.sphereStates[mt.ZMAX].point=[...this.originalClippingPlanes[Te.ZMAX].origin],[mt.XMIN,mt.XMAX,mt.YMIN,mt.YMAX,mt.ZMIN,mt.ZMAX].forEach(lt=>{const rt=this.sphereStates[lt];rt.sphereSource.setCenter(...rt.point),rt.sphereSource.modified()}),[mt.XMIN_YMIN_ZMIN,mt.XMIN_YMIN_ZMAX,mt.XMIN_YMAX_ZMIN,mt.XMIN_YMAX_ZMAX,mt.XMAX_YMIN_ZMIN,mt.XMAX_YMIN_ZMAX,mt.XMAX_YMAX_ZMIN,mt.XMAX_YMAX_ZMAX].forEach(lt=>{const rt=this.sphereStates[lt];if(rt){const ut=Ot(rt.point[0],rt.point[1],rt.point[2]);Ue(ut,ut,z),rt.point=[ut[0],ut[1],ut[2]],rt.sphereSource.setCenter(...rt.point),rt.sphereSource.modified()}}),Object.values(this.edgeLines).forEach(({source:lt,key1:rt,key2:ut})=>{const Tt=this.sphereStates.find(Pt=>Pt.uid===`corner_${rt}`),kt=this.sphereStates.find(Pt=>Pt.uid===`corner_${ut}`);if(Tt&&kt){const Pt=lt.getPoints();Pt.setPoint(0,Tt.point[0],Tt.point[1],Tt.point[2]),Pt.setPoint(1,kt.point[0],kt.point[1],kt.point[2]),Pt.modified(),lt.modified()}})),this._updateClippingPlanes(u),u.render(),Rt(Z,E.VOLUMECROPPING_TOOL_CHANGED,{originalClippingPlanes:this.originalClippingPlanes,viewportId:u.id,renderingEngineId:u.renderingEngineId,seriesInstanceUID:this.seriesInstanceUID})}},this._rotateCamera=(e,o,s,a)=>{const r=e.getVtkActiveCamera(),c=r.getViewUp(),l=r.getFocalPoint(),d=r.getPosition(),u=[0,0,0],h=[0,0,0],f=[0,0,0],g=Qn(new Float32Array(16));fo(g,g,o),go(g,g,a,s),fo(g,g,[-o[0],-o[1],-o[2]]),Ue(u,d,g),Ue(h,l,g),Qn(g),go(g,g,a,s),Ue(f,c,g),Td(e,{position:u,viewUp:f,focalPoint:h})},this.touchDragCallback=this._dragCallback.bind(this),this.mouseDragCallback=this._dragCallback.bind(this)}onSetToolActive(){const t=this._getViewportsInfo(),n=()=>{t.forEach(({viewportId:o,renderingEngineId:s})=>{if(!this._resizeObservers.has(o)){const{viewport:a}=ae(o,s)||{viewport:null};if(!a)return;const{element:r}=a,c=new ResizeObserver(()=>{const l=ae(o,s);if(!l)return;const{viewport:d}=l,u=Aa(d);Md(d),uc(d,u),d.render()});c.observe(r),this._resizeObservers.set(o,c)}})};n(),this._viewportAddedListener=o=>{o.detail.toolGroupId===this.toolGroupId&&n()},Z.addEventListener(E.TOOLGROUP_VIEWPORT_ADDED,this._viewportAddedListener),this._unsubscribeToViewportNewVolumeSet(t),this._subscribeToViewportNewVolumeSet(t),this.sphereStates&&this.sphereStates.length===0&&(this.originalClippingPlanes=[],this._initialize3DViewports(t)),this.configuration.showClippingPlanes=!1,this.configuration.showHandles=!1;const e=this._getViewport();e&&this.originalClippingPlanes&&this.originalClippingPlanes.length>0&&(this._updateClippingPlanes(e),this.sphereStates&&this.sphereStates.length>0&&this._updateHandlesVisibility(),e.render())}onSetToolDisabled(){this._resizeObservers.forEach((n,e)=>{n.disconnect(),this._resizeObservers.delete(e)}),this._viewportAddedListener&&(Z.removeEventListener(E.TOOLGROUP_VIEWPORT_ADDED,this._viewportAddedListener),this._viewportAddedListener=null);const t=this._getViewportsInfo();this._unsubscribeToViewportNewVolumeSet(t)}setHandlesVisible(t){this.configuration.showHandles=t,t&&(this._updateFaceSpheresFromClippingPlanes(),this._updateCornerSpheres()),this._updateHandlesVisibility();const n=this._getViewportsInfo(),[e]=n;Ne(e.renderingEngineId).getViewport(e.viewportId).render()}getHandlesVisible(){return this.configuration.showHandles}setHandleRadius(t){this.configuration.sphereRadius=t,this.sphereStates.forEach(a=>{a?.sphereSource?.setRadius&&(a.sphereSource.setRadius(t),a.sphereSource.modified())});const n=this._getViewportsInfo(),[e]=n;if(!e)return;Ne(e.renderingEngineId)?.getViewport(e.viewportId)?.render()}getClippingPlanesVisible(){return this.configuration.showClippingPlanes}setClippingPlanesVisible(t){this.configuration.showClippingPlanes=t;const n=this._getViewport();this._updateClippingPlanes(n),this.sphereStates&&this.sphereStates.length>0&&(this.configuration.showHandles=t,this._updateHandlesVisibility()),t&&n&&this.originalClippingPlanes?.length>=Cn&&this._notifyClippingPlanesChanged(n),n.render()}getRotatePlanesOnDrag(){return this.rotatePlanesOnDrag}setRotatePlanesOnDrag(t){this.rotatePlanesOnDrag=t;const n=this._getViewport();n&&n.render()}_dragCallback(t){const{element:n,currentPoints:e,lastPoints:o}=t.detail;if(this.draggingSphereIndex!==null)this._onMouseMoveSphere(t);else{const s=t.detail.event?.shiftKey??!1;if((this.rotatePlanesOnDrag===!0||s)&&!this.suppressPlaneRotationForCurrentDrag){this._rotateClippingPlanes(t);return}const a=e.canvas,r=o.canvas,{rotateIncrementDegrees:c}=this.configuration,l=N(n),{viewport:d}=l,u=ht(d),h=n.clientWidth,f=n.clientHeight,g=[a[0]/h,a[1]/f],m=[r[0]/h,r[1]/f],p=[h*.5,f*.5],v=d.canvasToWorld(p),w=(1+Math.abs([.5,.5][0]))**2,C=[m[0],0,0],S=[g[0],0,0],b=C[0]**2,_=S[0]**2,y=b>w?0:Math.sqrt(w-b),D=_>w?0:Math.sqrt(w-_),T=[C[0],0,y];Vt.normalize(T);const P=[S[0],0,D];Vt.normalize(P);const x=Vt.dot(T,P);if(Math.abs(x)>1e-4){const M=-2*Math.acos(Vt.clampValue(x,-1,1))*Math.sign(g[0]-m[0])*c,L=u.viewUp,R=u.viewPlaneNormal,U=[0,0,0],W=[0,0,0];Vt.cross(L,R,U),Vt.normalize(U),Vt.cross(R,U,W),Vt.normalize(W),Vt.normalize(L),this._rotateCamera(d,v,W,M);const K=(m[1]-g[1])*c;this._rotateCamera(d,v,U,K)}d.render()}}_updateClippingPlanes(t){const n=this._getVolumeActor(t),e=this._getVolumeMapper(t);if(!n||!e)return;const o=n.getMatrix();if(!this.configuration.showClippingPlanes){e.removeAllClippingPlanes();return}const s=Gs();qd(s,o);const a=Gs();q_(a,s),X_(a,a);const r=this.originalClippingPlanes;if(!r||!r.length)return;e.removeAllClippingPlanes();const c=[],l=[];for(let d=0;d<r.length;++d){const u=r[d],h=B();Ue(h,new Float32Array(u.origin),o);const f=[h[0],h[1],h[2]],g=B();Dg(g,new Float32Array(u.normal),a),Wt(g,g);const m=[g[0],g[1],g[2]];c.push(f),l.push(m)}for(let d=0;d<c.length;++d){const u=Di.newInstance({origin:c[d],normal:l[d]});e.addClippingPlane(u)}}_updateHandlesVisibility(){this.sphereStates.forEach(t=>{t.sphereActor&&t.sphereActor.setVisibility(this.configuration.showHandles)}),Object.values(this.edgeLines).forEach(({actor:t})=>{t&&t.setVisibility(this.configuration.showHandles)})}_addSphere(t,n,e,o,s=null,a){const r=s?`corner_${s}`:`${e}_${o}`;if(this.sphereStates.find(p=>p.uid===r))return;const l=bV.newInstance();l.setCenter(n),l.setRadius(a);const d=Oo.newInstance();d.setInputConnection(l.getOutputPort());const u=vo.newInstance();u.setMapper(d);let h=[0,1,0];const f=this.configuration.sphereColors||{};s?h=f.CORNERS||[0,0,1]:e==="z"?h=f.AXIAL||[1,0,0]:e==="x"?h=f.SAGITTAL||[1,1,0]:e==="y"&&(h=f.CORONAL||[0,1,0]);const g=this.sphereStates.findIndex(p=>p.uid===r),m=[n[0],n[1],n[2]];g===-1?this.sphereStates.push({point:m,axis:e,uid:r,sphereSource:l,sphereActor:u,isCorner:!!s,color:h}):(this.sphereStates[g].point=m,this.sphereStates[g].sphereSource=l),u.getProperty().setColor(h),u.setVisibility(this.configuration.showHandles),t.addActor({actor:u,uid:r})}_getDirectionVectorForAxis(t){if(this.originalClippingPlanes&&this.originalClippingPlanes.length>=Cn)switch(t){case"x":return this.originalClippingPlanes[Te.XMIN].normal;case"y":return this.originalClippingPlanes[Te.YMIN].normal;case"z":return this.originalClippingPlanes[Te.ZMIN].normal;default:return[1,0,0]}if(!this.volumeDirectionVectors)return t==="x"?[1,0,0]:t==="y"?[0,1,0]:t==="z"?[0,0,1]:[1,0,0];switch(t){case"x":return this.volumeDirectionVectors.xDir;case"y":return this.volumeDirectionVectors.yDir;case"z":return this.volumeDirectionVectors.zDir;default:return[1,0,0]}}_getVolumeActor(t){return(t||this._getViewport())?.getActors?.()?.find(e=>e.actor?.getClassName?.()==="vtkVolume")?.actor}_getVolumeMapper(t){return this._getVolumeActor(t)?.getMapper()}_applyClippingPlanesToMapper(t){t.removeAllClippingPlanes();for(let n=0;n<Cn;++n){const e=Di.newInstance({origin:this.originalClippingPlanes[n].origin,normal:this.originalClippingPlanes[n].normal});t.addClippingPlane(e)}}_updateClippingPlanesFromFaceSpheres(t){const n=this._getVolumeMapper(t);n&&(this.originalClippingPlanes[Te.XMIN].origin=[...this.sphereStates[mt.XMIN].point],this.originalClippingPlanes[Te.XMAX].origin=[...this.sphereStates[mt.XMAX].point],this.originalClippingPlanes[Te.YMIN].origin=[...this.sphereStates[mt.YMIN].point],this.originalClippingPlanes[Te.YMAX].origin=[...this.sphereStates[mt.YMAX].point],this.originalClippingPlanes[Te.ZMIN].origin=[...this.sphereStates[mt.ZMIN].point],this.originalClippingPlanes[Te.ZMAX].origin=[...this.sphereStates[mt.ZMAX].point],this._applyClippingPlanesToMapper(n))}_updateCornerSpheresFromFaces(){const{xDir:t,yDir:n,zDir:e}=this._getDirectionVectors();if(!t||!n||!e)return;const o=this.sphereStates[mt.XMIN].point,s=this.sphereStates[mt.XMAX].point,a=this.sphereStates[mt.YMIN].point,r=this.sphereStates[mt.YMAX].point,c=this.sphereStates[mt.ZMIN].point,l=this.sphereStates[mt.ZMAX].point,d=[{key:"XMIN_YMIN_ZMIN",pos:this._calculateCornerFromFaces(o,a,c,t,n,e)},{key:"XMIN_YMIN_ZMAX",pos:this._calculateCornerFromFaces(o,a,l,t,n,e)},{key:"XMIN_YMAX_ZMIN",pos:this._calculateCornerFromFaces(o,r,c,t,n,e)},{key:"XMIN_YMAX_ZMAX",pos:this._calculateCornerFromFaces(o,r,l,t,n,e)},{key:"XMAX_YMIN_ZMIN",pos:this._calculateCornerFromFaces(s,a,c,t,n,e)},{key:"XMAX_YMIN_ZMAX",pos:this._calculateCornerFromFaces(s,a,l,t,n,e)},{key:"XMAX_YMAX_ZMIN",pos:this._calculateCornerFromFaces(s,r,c,t,n,e)},{key:"XMAX_YMAX_ZMAX",pos:this._calculateCornerFromFaces(s,r,l,t,n,e)}];for(const u of d){const h=this.sphereStates.findIndex(f=>f.uid===`corner_${u.key}`);h!==-1&&this._updateSpherePosition(h,u.pos)}}_updateFaceSpheresFromCorners(){if(!this.volumeDirectionVectors)return;const t=[this.sphereStates[mt.XMIN_YMIN_ZMIN].point,this.sphereStates[mt.XMIN_YMIN_ZMAX].point,this.sphereStates[mt.XMIN_YMAX_ZMIN].point,this.sphereStates[mt.XMIN_YMAX_ZMAX].point,this.sphereStates[mt.XMAX_YMIN_ZMIN].point,this.sphereStates[mt.XMAX_YMIN_ZMAX].point,this.sphereStates[mt.XMAX_YMAX_ZMIN].point,this.sphereStates[mt.XMAX_YMAX_ZMAX].point],n=this._averagePoints([t[0],t[1],t[2],t[3]]),e=this._averagePoints([t[4],t[5],t[6],t[7]]),o=this._averagePoints([t[0],t[1],t[4],t[5]]),s=this._averagePoints([t[2],t[3],t[6],t[7]]),a=this._averagePoints([t[0],t[2],t[4],t[6]]),r=this._averagePoints([t[1],t[3],t[5],t[7]]);this._updateSpherePosition(mt.XMIN,n),this._updateSpherePosition(mt.XMAX,e),this._updateSpherePosition(mt.YMIN,o),this._updateSpherePosition(mt.YMAX,s),this._updateSpherePosition(mt.ZMIN,a),this._updateSpherePosition(mt.ZMAX,r)}_updateCornerSpheres(){const{xDir:t,yDir:n,zDir:e}=this._getDirectionVectors();if(!t||!n||!e)return;const o=this.sphereStates[mt.XMIN].point,s=this.sphereStates[mt.XMAX].point,a=this.sphereStates[mt.YMIN].point,r=this.sphereStates[mt.YMAX].point,c=this.sphereStates[mt.ZMIN].point,l=this.sphereStates[mt.ZMAX].point,d=[{key:"XMIN_YMIN_ZMIN",pos:this._calculateCornerFromProjection(o,a,c,t,n,e)},{key:"XMIN_YMIN_ZMAX",pos:this._calculateCornerFromProjection(o,a,l,t,n,e)},{key:"XMIN_YMAX_ZMIN",pos:this._calculateCornerFromProjection(o,r,c,t,n,e)},{key:"XMIN_YMAX_ZMAX",pos:this._calculateCornerFromProjection(o,r,l,t,n,e)},{key:"XMAX_YMIN_ZMIN",pos:this._calculateCornerFromProjection(s,a,c,t,n,e)},{key:"XMAX_YMIN_ZMAX",pos:this._calculateCornerFromProjection(s,a,l,t,n,e)},{key:"XMAX_YMAX_ZMIN",pos:this._calculateCornerFromProjection(s,r,c,t,n,e)},{key:"XMAX_YMAX_ZMAX",pos:this._calculateCornerFromProjection(s,r,l,t,n,e)}];for(const u of d){const h=this.sphereStates.findIndex(f=>f.uid===`corner_${u.key}`);h!==-1&&this._updateSpherePosition(h,u.pos)}this._updateEdgeLines()}_unsubscribeToViewportNewVolumeSet(t){t.forEach(({viewportId:n,renderingEngineId:e})=>{const{viewport:o}=ae(n,e),{element:s}=o;s.removeEventListener(yt.VOLUME_VIEWPORT_NEW_VOLUME,this._onNewVolume)})}_subscribeToViewportNewVolumeSet(t){t.forEach(({viewportId:n,renderingEngineId:e})=>{const{viewport:o}=ae(n,e),{element:s}=o;s.addEventListener(yt.VOLUME_VIEWPORT_NEW_VOLUME,this._onNewVolume)})}_getDirectionVectors(){const t=this.originalClippingPlanes?.length>=Cn;return{xDir:t?this.originalClippingPlanes[Te.XMIN].normal:this.volumeDirectionVectors?.xDir||[1,0,0],yDir:t?this.originalClippingPlanes[Te.YMIN].normal:this.volumeDirectionVectors?.yDir||[0,1,0],zDir:t?this.originalClippingPlanes[Te.ZMIN].normal:this.volumeDirectionVectors?.zDir||[0,0,1]}}_updateSpherePosition(t,n){const e=this.sphereStates[t];e&&(e.point=n,e.sphereSource.setCenter(...n),e.sphereSource.modified())}_updateFaceSpheresFromClippingPlanes(){[{sphereIdx:mt.XMIN,planeIdx:Te.XMIN},{sphereIdx:mt.XMAX,planeIdx:Te.XMAX},{sphereIdx:mt.YMIN,planeIdx:Te.YMIN},{sphereIdx:mt.YMAX,planeIdx:Te.YMAX},{sphereIdx:mt.ZMIN,planeIdx:Te.ZMIN},{sphereIdx:mt.ZMAX,planeIdx:Te.ZMAX}].forEach(({sphereIdx:n,planeIdx:e})=>{const o=[...this.originalClippingPlanes[e].origin];this._updateSpherePosition(n,o)})}_averagePoints(t){const n=t.reduce((e,o)=>[e[0]+o[0],e[1]+o[1],e[2]+o[2]],[0,0,0]);return[n[0]/t.length,n[1]/t.length,n[2]/t.length]}_notifyClippingPlanesChanged(t){const n={originalClippingPlanes:this.originalClippingPlanes,seriesInstanceUID:this.seriesInstanceUID};t&&(n.viewportId=t.id,n.renderingEngineId=t.renderingEngineId),Rt(Z,E.VOLUMECROPPING_TOOL_CHANGED,n)}_calculateCornerFromFaces(t,n,e,o,s,a){const r=[n[0]-t[0],n[1]-t[1],n[2]-t[2]],c=r[0]*s[0]+r[1]*s[1]+r[2]*s[2],l=[e[0]-t[0],e[1]-t[1],e[2]-t[2]],d=l[0]*a[0]+l[1]*a[1]+l[2]*a[2];return[t[0]+c*s[0]+d*a[0],t[1]+c*s[1]+d*a[1],t[2]+c*s[2]+d*a[2]]}_calculateCornerFromProjection(t,n,e,o,s,a){const r=t[0]*o[0]+t[1]*o[1]+t[2]*o[2],c=n[0]*s[0]+n[1]*s[1]+n[2]*s[2],l=e[0]*a[0]+e[1]*a[1]+e[2]*a[2];return[r*o[0]+c*s[0]+l*a[0],r*o[1]+c*s[1]+l*a[1],r*o[2]+c*s[2]+l*a[2]]}_updateEdgeLines(){Object.values(this.edgeLines).forEach(({source:t,key1:n,key2:e})=>{const o=this.sphereStates.find(a=>a.uid===`corner_${n}`),s=this.sphereStates.find(a=>a.uid===`corner_${e}`);if(o&&s){const a=t.getPoints();a.setPoint(0,o.point[0],o.point[1],o.point[2]),a.setPoint(1,s.point[0],s.point[1],s.point[2]),a.modified(),t.modified()}})}}kV.toolName="VolumeCropping";const qa={DRAG:1};class UV extends be{constructor(t={},n={supportedInteractionTypes:["Mouse"],configuration:{viewportIndicators:!1,viewportIndicatorsConfig:{radius:5,x:null,y:null},extendReferenceLines:!0,initialCropFactor:.2,mobile:{enabled:!1,opacity:.8},lineColors:{AXIAL:[1,0,0],CORONAL:[0,1,0],SAGITTAL:[1,1,0],UNKNOWN:[0,0,1]},lineWidth:1.5,lineWidthActive:2.5}}){super(t,n),this.clippingPlanes=[],this.initializeViewport=({renderingEngineId:o,viewportId:s})=>{if(!o||!s){console.warn("VolumeCroppingControlTool: Missing renderingEngineId or viewportId");return}const a=ae(s,o);if(!a)return;const{viewport:r}=a,c=r.getActors();if(c&&c.length>0){const m=c[0].actor.getMapper().getInputData();m&&(this.seriesInstanceUID=m.seriesInstanceUID||"unknown")}const{element:l}=r,{position:d,focalPoint:u}=ht(r);let h=this._getAnnotations(a);h=this.filterInteractableAnnotationsForElement(l,h),h?.length&&Gt(h[0].annotationUID);const f=Pp(ht(r).viewPlaneNormal),g={highlighted:!1,metadata:{cameraPosition:[...d],cameraFocalPoint:[...u],toolName:this.getToolName()},data:{handles:{activeOperation:null,clippingPlanes:this.clippingPlanes.length>0?ns(this.clippingPlanes):[]},activeViewportIds:[],viewportId:s,referenceLines:[],orientation:f}};Nt(g,l)},this._getViewportsInfo=()=>Be(this.toolGroupId).viewportsInfo,this.resetCroppingSpheres=()=>{const o=this._getViewportsInfo();for(const s of o){const{viewportId:a,renderingEngineId:r}=s,c=ae(a,r),l=c.viewport;Md(l,{resetPan:!0,resetZoom:!0,resetToCenter:!0,resetRotation:!0,suppressEvents:!0}),l.resetSlabThickness();const{element:m}=l;let p=this._getAnnotations(c);p=this.filterInteractableAnnotationsForElement(m,p),p.length&&Gt(p[0].annotationUID),l.render()}this._initializeViewports(o)},this._initializeViewports=o=>{if(!o?.length||!o[0]){console.warn("VolumeCroppingControlTool: No valid viewportsInfo for initialization.");return}o.forEach(s=>{this.initializeViewport(s)}),V(o.map(({viewportId:s})=>s))},this.cancel=()=>{},this.isPointNearTool=(o,s,a,r)=>!!this._pointNearTool(o,s,a,xp),this.toolSelectedCallback=(o,s,a)=>{const r=o.detail,{element:c}=r;s.highlighted=!0,this._activateModify(c),wt(c),o.preventDefault()},this.onResetCamera=o=>{this.resetCroppingSpheres()},this.mouseMoveCallback=(o,s)=>{if(!s)return;const{element:a,currentPoints:r}=o.detail,c=r.canvas;let l=!1;for(let d=0;d<s.length;d++){const u=s[d];if(ze(u.annotationUID))continue;const{data:h,highlighted:f}=u;if(!h.handles)continue;h.activeViewportIds=[];const g=this._pointNearTool(a,u,c,xp);(g&&!f||!g&&f)&&(u.highlighted=!f,l=!0)}return l},this.filterInteractableAnnotationsForElement=(o,s)=>{if(!s||!s.length)return[];const a=N(o);let r=null;if(a.viewport){const{viewPlaneNormal:l}=ht(a.viewport);l&&(r=Pp(l))}return s.filter(l=>!!(l.data.orientation&&r&&l.data.orientation===r))},this.renderAnnotation=(o,s)=>{function a(x,M,L,R){const U=M[0]-x[0],W=M[1]-x[1],K=R[0]-L[0],j=R[1]-L[1],F=-K*W+U*j;if(Math.abs(F)<xV)return null;const z=(-W*(x[0]-L[0])+U*(x[1]-L[1]))/F,q=(K*(x[1]-L[1])-j*(x[0]-L[0]))/F;return z>=0&&z<=1&&q>=0&&q<=1?[x[0]+q*U,x[1]+q*W]:null}const r=this._getViewportsInfo();if(!r||r.length===0)return!1;let c=!1;const{viewport:l,renderingEngine:d}=o,{element:u}=l,h=this._getAnnotations(o),f=ht(l),m=this.filterInteractableAnnotationsForElement(u,h)[0];if(!m||!m.data)return c;const p=m.annotationUID,{clientWidth:v,clientHeight:I}=l.canvas,w=Math.sqrt(v*v+I*I),C=m.data;let S=m.data.handles.clippingPlanes;if(!S||S.length<Cn)if(this.clippingPlanes&&this.clippingPlanes.length>=Cn)S=this.clippingPlanes,C.handles.clippingPlanes=ns(this.clippingPlanes);else return!1;const{viewPlaneNormal:b,focalPoint:_}=f,y=[],D=["min","max","min","max","min","max"];for(let x=0;x<Cn;x++){const M=S[x],L=LV(M,b,_);if(!L)continue;const R=OV(L.point,L.direction,l);R&&y.push([{id:l.id,canvas:l.canvas},R.start,R.end,D[x],x])}C.referenceLines=y;const T=this._getReferenceLineColor(l.id),P=T!==void 0?T:"rgb(200, 200, 200)";if(y.forEach((x,M)=>{const[L,R,U,W,K]=x;if(K===void 0||K<0||K>=Cn)return;const j=[];for(let lt=0;lt<y.length;++lt){if(lt===M)continue;const rt=y[lt],ut=a(R,U,rt[1],rt[2]);ut&&j.push({with:rt[3],point:ut})}const F=AV(K),z=this.configuration.lineColors||{},q=F?z[F]||z.UNKNOWN||[1,0,0]:[1,0,0],J=kC(q);this._getReferenceLineControllable(L.id);const it=C.activeViewportIds.find(lt=>lt===L.id);let tt=this.configuration.lineWidth??1.5;C.handles.activeOperation!==null&&C.handles.activeOperation===qa.DRAG&&it&&(tt=this.configuration.activeLineWidth??2.5);const nt=`plane_${K}`;if(j.length===2?qt(s,p,nt,j[0].point,j[1].point,{color:J,lineWidth:tt}):qt(s,p,nt,R,U,{color:J,lineWidth:tt}),this.configuration.extendReferenceLines&&j.length===2){const lt=j.map(rt=>({...rt,distance:_e(R,rt.point)})).sort((rt,ut)=>rt.distance-ut.distance);qt(s,p,nt+"_dashed_before",R,lt[0].point,{color:J,lineWidth:tt,lineDash:[4,4]}),qt(s,p,nt+"_dashed_after",lt[1].point,U,{color:J,lineWidth:tt,lineDash:[4,4]})}}),c=!0,this.configuration.viewportIndicators){const{viewportIndicatorsConfig:x}=this.configuration,M=x?.xOffset||.95,L=x?.yOffset||.05,R=[v*M,I*L],U=x?.circleRadius||w*.01;En(s,p,"0",R,U,{color:P,fill:P})}return c},this._getAnnotations=o=>{const{viewport:s}=o,a=Yt(this.getToolName(),s.element)||[],r=this._getViewportsInfo().map(({viewportId:l})=>l);return a.filter(l=>{const{data:d}=l;return r.includes(d.viewportId)})},this._onSphereMoved=o=>{if(o.detail.originalClippingPlanes)this._syncWithVolumeCroppingTool(o.detail.originalClippingPlanes);else return o.detail.seriesInstanceUID!==this.seriesInstanceUID,void 0},this._onNewVolume=()=>{const o=this._getViewportsInfo();if(o&&o.length>0){const{viewportId:s,renderingEngineId:a}=o[0],r=Ne(a);if(!r)return;const c=r.getViewport(s);if(!c)return;const l=c.getActors();if(l.length>0){const d=l[0].actor.getMapper().getInputData();d&&(this.seriesInstanceUID=d.seriesInstanceUID)}}this._initializeViewports(o),Rt(Z,E.VOLUMECROPPINGCONTROL_TOOL_CHANGED,{toolGroupId:this.toolGroupId,viewportsInfo:o,seriesInstanceUID:this.seriesInstanceUID})},this._activateModify=o=>{$.isInteractingWithTool=!this.configuration.mobile?.enabled,o.addEventListener(E.MOUSE_UP,this._endCallback),o.addEventListener(E.MOUSE_DRAG,this._dragCallback),o.addEventListener(E.MOUSE_CLICK,this._endCallback),o.addEventListener(E.TOUCH_END,this._endCallback),o.addEventListener(E.TOUCH_DRAG,this._dragCallback),o.addEventListener(E.TOUCH_TAP,this._endCallback)},this._deactivateModify=o=>{$.isInteractingWithTool=!1,o.removeEventListener(E.MOUSE_UP,this._endCallback),o.removeEventListener(E.MOUSE_DRAG,this._dragCallback),o.removeEventListener(E.MOUSE_CLICK,this._endCallback),o.removeEventListener(E.TOUCH_END,this._endCallback),o.removeEventListener(E.TOUCH_DRAG,this._dragCallback),o.removeEventListener(E.TOUCH_TAP,this._endCallback)},this._endCallback=o=>{const s=o.detail,{element:a}=s;this.editData.annotation.data.handles.activeOperation=null,this.editData.annotation.data.activeViewportIds=[],this._deactivateModify(a),Ft(a),this.editData=null;const c=ft(a,this.getToolName(),!1);V(c)},this._dragCallback=o=>{const s=o.detail,a=s.deltaPoints.world;if(Math.abs(a[0])<.001&&Math.abs(a[1])<.001&&Math.abs(a[2])<.001)return;const{element:r}=s,c=N(r),{viewport:l}=c;if(l.type===so.VOLUME_3D)return;const d=this._getAnnotations(c),h=this.filterInteractableAnnotationsForElement(r,d)[0];if(!h)return;const{handles:f}=h.data,g=f.clippingPlanes;if(f.activeOperation===qa.DRAG&&g&&g.length>=Cn){if(f.activePlaneIndex!==void 0&&f.activePlaneIndex>=0&&f.activePlaneIndex<Cn){const p=f.activePlaneIndex,v=g[p],I=v.normal,C=Vt.dot(a,I);v.origin[0]+=I[0]*C,v.origin[1]+=I[1]*C,v.origin[2]+=I[2]*C}else f.activeType==="min"?(g[0].origin[0]+=a[0],g[2].origin[1]+=a[1],g[4].origin[2]+=a[2]):f.activeType==="max"&&(g[1].origin[0]+=a[0],g[3].origin[1]+=a[1],g[5].origin[2]+=a[2]);this.clippingPlanes=ns(g);const m=this._getViewportsInfo();m.forEach(({viewportId:p,renderingEngineId:v})=>{const I=ae(p,v);I&&this._getAnnotations(I).forEach(C=>{C.data?.handles&&(C.data.handles.clippingPlanes=ns(this.clippingPlanes))})}),V(m.map(({viewportId:p})=>p)),Rt(Z,E.VOLUMECROPPINGCONTROL_TOOL_CHANGED,{toolGroupId:this.toolGroupId,clippingPlanes:this.clippingPlanes,handleType:f.activeType,seriesInstanceUID:this.seriesInstanceUID})}},this._getReferenceLineColor=t.configuration?.getReferenceLineColor||(()=>"rgb(0, 200, 0)"),this._getReferenceLineControllable=t.configuration?.getReferenceLineControllable||(()=>!0);const e=Be(this.toolGroupId)?.viewportsInfo;if(Z.addEventListener(E.VOLUMECROPPING_TOOL_CHANGED,this._onSphereMoved),e&&e.length>0){const{viewportId:o,renderingEngineId:s}=e[0],a=Ne(s);if(!a)return;const r=a.getViewport(o);if(!r)return;const c=r.getActors();if(!c||!c.length){console.warn(`VolumeCroppingControlTool: No volume actors found in viewport ${o}.`);return}const l=c[0].actor.getMapper().getInputData();l&&(this.seriesInstanceUID=l.seriesInstanceUID||"unknown")}}onSetToolInactive(){}onSetToolActive(){const t=this._getViewportsInfo();let n=!1;for(const e of t){const o=ae(e.viewportId,e.renderingEngineId),s=this._getAnnotations(o);if(s&&s.length>0){n=!0;break}}if(!n)this._unsubscribeToViewportNewVolumeSet(t),this._subscribeToViewportNewVolumeSet(t),this._initializeViewports(t),Rt(Z,E.VOLUMECROPPINGCONTROL_TOOL_CHANGED,{toolGroupId:this.toolGroupId,viewportsInfo:t,seriesInstanceUID:this.seriesInstanceUID});else for(const e of t){const o=ae(e.viewportId,e.renderingEngineId);if(!o)continue;const s=this._getAnnotations(o);s&&s.length>0&&s.forEach(a=>{Gt(a.annotationUID)}),o.viewport.render()}}onSetToolEnabled(){Z.addEventListener(E.VOLUMECROPPING_TOOL_CHANGED,this._onSphereMoved)}onSetToolDisabled(){const t=this._getViewportsInfo();this._unsubscribeToViewportNewVolumeSet(t),Z.removeEventListener(E.VOLUMECROPPING_TOOL_CHANGED,this._onSphereMoved),t.forEach(({renderingEngineId:n,viewportId:e})=>{const o=ae(e,n);if(!o)return;const s=this._getAnnotations(o);s?.length&&s.forEach(a=>{Gt(a.annotationUID)})})}_syncWithVolumeCroppingTool(t){if(!t||t.length<Cn)return;this.clippingPlanes=ns(t);const n=this._getViewportsInfo();n.forEach(({viewportId:e,renderingEngineId:o})=>{const s=ae(e,o);s&&this._getAnnotations(s).forEach(r=>{r.data?.handles&&(r.data.handles.clippingPlanes=ns(this.clippingPlanes))})}),V(n.map(({viewportId:e})=>e))}addNewAnnotation(t){const n=t.detail,{element:e}=n,o=N(e),{viewport:s}=o,a=this._getAnnotations(o),r=this.filterInteractableAnnotationsForElement(s.element,a);if(!r||r.length===0||!r[0])return null;const{data:c}=r[0],l=[],d=c.referenceLines||[];for(let u=0;u<d.length;++u){const h=d[u][0];this._getReferenceLineControllable(h.id)&&l.push(h.id)}return c.activeViewportIds=[...l],c.handles.activeOperation=qa.DRAG,t.preventDefault(),wt(e),this._activateModify(e),r[0]}handleSelectedCallback(t,n,e,o){this.toolSelectedCallback(t,n,o)}_unsubscribeToViewportNewVolumeSet(t){t.forEach(({viewportId:n,renderingEngineId:e})=>{const{viewport:o}=ae(n,e),{element:s}=o;s.removeEventListener(yt.VOLUME_VIEWPORT_NEW_VOLUME,this._onNewVolume)})}_subscribeToViewportNewVolumeSet(t){t.forEach(({viewportId:n,renderingEngineId:e})=>{const{viewport:o}=ae(n,e),{element:s}=o;s.addEventListener(yt.VOLUME_VIEWPORT_NEW_VOLUME,this._onNewVolume)})}_pointNearTool(t,n,e,o){const{data:s}=n,a=s.referenceLines,r=[];if(a)for(let c=0;c<a.length;++c){const[l,d,u,h,f]=a[c];Je(d,u,[e[0],e[1]])<=o&&(r.push(l.id),s.handles.activeOperation=qa.DRAG,s.handles.activeType=h,s.handles.activePlaneIndex=f)}return s.activeViewportIds=[...r],this.editData={annotation:n},s.handles.activeOperation===qa.DRAG}}UV.toolName="VolumeCroppingControl";const Eu=4,Tp=1024,VV="PT";class FV extends Ee{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"]}){super(t,n),this._getImageDynamicRangeFromMiddleSlice=(e,o)=>{const s=Math.floor(o[2]/2),a=o[0]*o[1];let r,c;e instanceof Float32Array?(r=4,c=Float32Array):e instanceof Uint8Array?(r=1,c=Uint8Array):e instanceof Uint16Array?(r=2,c=Uint16Array):e instanceof Int16Array&&(r=2,c=Int16Array);const l=e.buffer,d=s*a*r,u=new c(l,d,a),{max:h,min:f}=this._getMinMax(u,a);return h-f}}touchDragCallback(t){this.mouseDragCallback(t)}mouseDragCallback(t){const{element:n,deltaPoints:e}=t.detail,o=N(n),{viewport:s}=o;let a,r,c,l,d,u,h=!1;const f=GV(s);if(!f?.voiRange)throw new Error("Viewport is not a valid type");if(s instanceof Xe){if(a=s.getVolumeId(),u=yh(a),{lower:r,upper:c}=f.voiRange,!Q.getVolume(a))throw new Error("Volume not found "+a)}else if(f.voiRange)({lower:r,upper:c}=f.voiRange);else throw new Error("Viewport is not a valid type");const g=Lh(s,a);if(l=g?.modality,h=!!g?.isPreScaled,l===VV&&h?d=this.getPTScaledNewRange({deltaPointsCanvas:e.canvas,lower:r,upper:c,clientHeight:n.clientHeight,isPreScaled:h,viewport:s,volumeId:a}):d=this.getNewRange({viewport:s,deltaPointsCanvas:e.canvas,volumeId:a,lower:r,upper:c,voiLutFunction:f.VOILUTFunction}),!(d.lower>=d.upper)&&(HV(s,{voiRange:d}),s.render(),s instanceof Xe)){u.forEach(m=>{s!==m&&m.render()});return}}getPTScaledNewRange({deltaPointsCanvas:t,lower:n,upper:e,clientHeight:o,viewport:s,volumeId:a,isPreScaled:r}){let c=Eu;r?c=5/o:c=this._getMultiplierFromDynamicRange(s,a)||Eu;const d=t[1]*c;return e-=d,e=r?Math.max(e,.1):e,{lower:n,upper:e}}getNewRange({viewport:t,deltaPointsCanvas:n,volumeId:e,lower:o,upper:s,voiLutFunction:a}){const r=this._getMultiplierFromDynamicRange(t,e)||Eu,c=n[0]*r,l=n[1]*r;let{windowWidth:d,windowCenter:u}=yv(o,s);return d+=c,u+=l,d=Math.max(d,1),Th(d,u,a)}_getMultiplierFromDynamicRange(t,n){let e;if(n){const s=Q.getVolume(n),{voxelManager:a}=t.getImageData(),c=a.getMiddleSliceData().reduce((h,f)=>[Math.min(h[0],f),Math.max(h[1],f)],[1/0,-1/0]),l=s?.metadata?.BitsStored,d=l?2**l:1/0,u=c[1]-c[0];e=Number.isFinite(u)?Math.min(u,d):d}else e=this._getImageDynamicRangeFromViewport(t);const o=e/Tp;return Number.isFinite(o)?o>1?Math.round(o):o:Tp}_getImageDynamicRangeFromViewport(t){const{imageData:n,voxelManager:e}=t.getImageData();if(e?.getRange){const r=e.getRange();return r[1]-r[0]}const o=n.getDimensions();if(n.getRange){const r=n.getRange();return r[1]-r[0]}let s;if(n.getScalarData?s=n.getScalarData():s=n.getPointData().getScalars().getData(),o[2]!==1)return this._getImageDynamicRangeFromMiddleSlice(s,o);let a;if(s.getRange)a=s.getRange();else{const{min:r,max:c}=this._getMinMax(s,s.length);a=[r,c]}return a[1]-a[0]}_getMinMax(t,n){let e=1/0,o=-1/0;for(let s=0;s<n;s++){const a=t[s];a<e&&(e=a),a>o&&(o=a)}return{max:o,min:e}}}FV.toolName="WindowLevel";function GV(i){const t=i;if(typeof t.getProperties=="function")return t.getProperties();const n=CS(i);if(!n)return;const e=n.viewport.getDisplaySetPresentation?.(n.dataId),o=n.viewport.getDefaultVOIRange?.(n.dataId);return{...e||{},voiRange:e?.voiRange??o}}function HV(i,t){const n=i;if(typeof n.setProperties=="function"){n.setProperties(t);return}const e=CS(i);e&&e.viewport.setDisplaySetPresentation?.(e.dataId,t)}function CS(i){const t=i,n=t.getSourceDataId?.();if(!(!n||typeof t.getDisplaySetPresentation!="function"||typeof t.setDisplaySetPresentation!="function"))return{viewport:t,dataId:n}}class WV extends be{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{minWindowWidth:10}}){super(t,n),this.addNewAnnotation=e=>{const o=e.detail,{currentPoints:s,element:a}=o,r=s.world,c=N(a),{viewport:l}=c;this.isDrawing=!0;const d=ht(l),{viewPlaneNormal:u,viewUp:h}=d,f=this.getReferencedImageId(l,r,u,h),g=l.getFrameOfReferenceUID(),m={invalidated:!0,highlighted:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...u],viewUp:[...h],FrameOfReferenceUID:g,referencedImageId:f},data:{handles:{points:[[...r],[...r],[...r],[...r]]},cachedStats:{}}};Nt(m,a);const p=ft(a,this.getToolName());return this.editData={annotation:m,viewportIdsToRender:p},this._activateDraw(a),wt(a),e.preventDefault(),V(p),m},this._endCallback=e=>{const o=e.detail,{element:s}=o,{annotation:a,viewportIdsToRender:r}=this.editData;this._deactivateDraw(s),Ft(s),this.editData=null,this.isDrawing=!1,Gt(a.annotationUID),V(r),ue(a),this.applyWindowLevelRegion(a,s)},this._dragCallback=e=>{this.isDrawing=!0;const o=e.detail,{element:s}=o,{annotation:a,viewportIdsToRender:r}=this.editData,{data:c}=a,{currentPoints:l}=o,d=N(s),{worldToCanvas:u,canvasToWorld:h}=d.viewport,f=l.world,{points:g}=c.handles,m=3;g[m]=[...f];const p=u(g[0]),v=u(g[3]),I=[v[0],p[1]],w=[p[0],v[1]],C=h(I),S=h(w);g[1]=C,g[2]=S,a.invalidated=!0,V(r)},this._activateDraw=e=>{$.isInteractingWithTool=!0,e.addEventListener(E.MOUSE_UP,this._endCallback),e.addEventListener(E.MOUSE_DRAG,this._dragCallback),e.addEventListener(E.MOUSE_MOVE,this._dragCallback),e.addEventListener(E.MOUSE_CLICK,this._endCallback),e.addEventListener(E.TOUCH_END,this._endCallback),e.addEventListener(E.TOUCH_DRAG,this._dragCallback),e.addEventListener(E.TOUCH_TAP,this._endCallback)},this._deactivateDraw=e=>{$.isInteractingWithTool=!1,e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragCallback),e.removeEventListener(E.MOUSE_MOVE,this._dragCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.TOUCH_END,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(e,o)=>{let s=!1;const{viewport:a}=e,{element:r}=a;let c=Yt(this.getToolName(),r);if(!c?.length||(c=this.filterInteractableAnnotationsForElement(r,c),!c?.length))return s;const l={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:e.viewport.id};for(let d=0;d<c.length;d++){const u=c[d],{annotationUID:h,data:f}=u,{points:g}=f.handles,m=g.map(S=>a.worldToCanvas(S));l.annotationUID=h;const{color:p,lineWidth:v,lineDash:I}=this.getAnnotationStyle({annotation:u,styleSpecifier:l});if(!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),s;const w=`${h}-rect`;nc(o,h,"0",m[0],m[3],{color:p,lineDash:I,lineWidth:v},w),s=!0}return s},this.applyWindowLevelRegion=(e,o)=>{const s=N(o),{viewport:a}=s,r=rS(a);if(!r)return;const{data:c}=e,{points:l}=c.handles,d=l.map(D=>a.worldToCanvas(D)),u=d[0],h=d[3];let f=Math.min(u[0],h[0]),g=Math.min(u[1],h[1]),m=Math.abs(u[0]-h[0]),p=Math.abs(u[1]-h[1]);f=Pg(f,0,r.width),g=Pg(g,0,r.height),m=Math.floor(Math.min(m,Math.abs(r.width-f))),p=Math.floor(Math.min(p,Math.abs(r.height-g)));const v=sS(r,Math.round(f),Math.round(g),m,p),I=aS(v,r.minPixelValue,r.maxPixelValue);this.configuration.minWindowWidth===void 0&&(this.configuration.minWindowWidth=10);const w=Math.max(Math.abs(I.max-I.min),this.configuration.minWindowWidth),C=I.mean,S=Sa(a)?a:void 0,b=S?.getSourceDataId(),_=S?b?S.getDisplaySetPresentation(b)?.voiLUTFunction:void 0:a.getProperties().VOILUTFunction,y=Th(w,C,_);S?b?S.setDisplaySetPresentation(b,{voiRange:y}):S.setDisplaySetPresentation({voiRange:y}):a.setProperties({voiRange:y}),a.render()},this.cancel=()=>null,this.isPointNearTool=()=>null,this.toolSelectedCallback=()=>null,this.handleSelectedCallback=()=>null,this._activateModify=()=>null,this._deactivateModify=()=>null}}WV.toolName="WindowLevelRegion";class BV extends Ee{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{invert:!1,debounceIfNotLoaded:!0,loop:!1}}){super(t,n),this.deltaY=1}mouseWheelCallback(t){this._scroll(t)}mouseDragCallback(t){this._dragCallback(t)}touchDragCallback(t){this._dragCallback(t)}_dragCallback(t){this._scrollDrag(t)}_scrollDrag(t){const{deltaPoints:n,viewportId:e,renderingEngineId:o}=t.detail,{viewport:s}=ae(e,o),{debounceIfNotLoaded:a,invert:r,loop:c}=this.configuration,l=n.canvas[1];let d;s instanceof Xe&&(d=s.getVolumeId());const u=this._getPixelPerImage(s),h=l+this.deltaY;if(u)if(Math.abs(h)>=u){const f=Math.round(h/u);da(s,{delta:r?-f:f,volumeId:d,debounceLoading:a,loop:c}),this.deltaY=h%u}else this.deltaY=h}_scroll(t){const{wheel:n,element:e}=t.detail,{direction:o}=n,{invert:s}=this.configuration,{viewport:a}=N(e),r=o*(s?-1:1);da(a,{delta:r,debounceLoading:this.configuration.debounceIfNotLoaded,loop:this.configuration.loop,volumeId:a instanceof pn?a.getVolumeId():void 0,scrollSlabs:this.configuration.scrollSlabs})}_getPixelPerImage(t){const{element:n}=t,e=t.getNumberOfSlices();return Math.max(2,n.offsetHeight/Math.max(e,8))}}BV.toolName="StackScroll";class zV extends Ee{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"]}){super(t,n),this.mouseWheelCallback=e=>{const{element:o,wheel:s}=e.detail,a=N(o),{viewport:r}=a,{invert:c}=this.configuration,l=s.direction*10*(c?-1:1);this.setAngle(r,l)},this.touchDragCallback=this._dragCallback.bind(this),this.mouseDragCallback=this._dragCallback.bind(this)}_dragCallback(t){const{element:n,currentPoints:e,startPoints:o}=t.detail,s=e.world,a=o.world,r=N(n),{viewport:c}=r,l=ht(c),d=n.clientWidth,u=n.clientHeight,h=[d*.5,u*.5],f=c.canvasToWorld(h);let g=na([a,f],[f,s]);const{viewPlaneNormal:m}=l;if(!m)return;const p=tn(B(),f,a),v=tn(B(),f,s),I=Me(B(),p,v);xt(m,I)>0&&(g=-g),!Number.isNaN(g)&&this.setAngle(c,g)}setAngle(t,n){const{viewPlaneNormal:e,viewUp:o}=ht(t);if(!(!e||!o)){if(t instanceof pn){const s=(n+360)%360*Math.PI/180,a=Qn(new Float32Array(16));go(a,a,s,e);const r=Ue(B(),o,a);t.setCamera({viewUp:r})}else{const s=Aa(t);if(!s)return;const{rotation:a=0}=s;if(!uc(t,{rotation:(a+n+360)%360}))return}t.render()}}}zV.toolName="PlanarRotate";class $V extends Ee{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{zoomToCenter:!1,minZoomScale:.001,maxZoomScale:3e3,pinchToZoom:!0,pan:!0,invert:!1}}){super(t,n),this.preMouseDownCallback=e=>{const o=e.detail,{element:s,currentPoints:a}=o,r=a.world,l=N(s).viewport,d=Ya(l);if(!hr(d))return!1;const{focalPoint:u}=d;this.initialMousePosWorld=r;let h=Ot(u[0]-r[0],u[1]-r[1],u[2]-r[2]);return h=Wt(B(),h),this.dirVec=h,!1},this.preTouchStartCallback=e=>{if(!this.configuration.pinchToZoom)return this.preMouseDownCallback(e)},this._dragParallelProjection=(e,o,s,a=!1)=>{const{element:r,deltaPoints:c}=e.detail,l=a?e.detail.deltaDistance.canvas:c.canvas[1],d=[r.clientWidth,r.clientHeight],{parallelScale:u,focalPoint:h,position:f}=s,g=5/d[1],m=l*g*(this.configuration.invert?-1:1),p=(1-m)*u;let v=h,I=f;if(!this.configuration.zoomToCenter){const _=ke(h,this.initialMousePosWorld);I=ee(B(),f,this.dirVec,-_*m),v=ee(B(),h,this.dirVec,-_*m)}const w=o.getImageData();let C=[1,1,1],S=p,b=!1;if(w){C=w.spacing;const{dimensions:_}=w,y=_[0]*C[0],D=_[1]*C[1],T=d[0]/d[1],P=UC().rendering?.useLegacyCameraFOV?1.1:1,x=o.options?.displayArea,M=x?.imageArea?.[0]??P,L=x?.imageArea?.[1]??P,R=y*M,U=D*L,W=R/U;let K;W>T?K=R/T*.5:K=U*.5;const{minZoomScale:j,maxZoomScale:F}=this.configuration,z=K/F,q=K/j;p<z?(S=z,b=!0):p>q&&(S=q,b=!0)}o.setCamera({parallelScale:S,focalPoint:b?h:v,position:b?f:I})},this._dragPerspectiveProjection=(e,o,s,a=!1)=>{const{element:r,deltaPoints:c}=e.detail,l=a?e.detail.deltaDistance.canvas:c.canvas[1],d=[r.clientWidth,r.clientHeight],{position:u,focalPoint:h,viewPlaneNormal:f}=s,g=Vt.distance2BetweenPoints(u,h),m=Math.sqrt(g)/d[1],p=[-f[0],-f[1],-f[2]],v=this.configuration.invert?l/m:l*m;let I=v*p[0];u[0]+=I,h[0]+=I,I=v*p[1],u[1]+=I,h[1]+=I,I=v*p[2],u[2]+=I,h[2]+=I,o.setCamera({position:u,focalPoint:h})},this.initialMousePosWorld=[0,0,0],this.dirVec=[0,0,0],this.configuration.pinchToZoom?this.touchDragCallback=this._pinchCallback.bind(this):this.touchDragCallback=this._dragCallback.bind(this),this.mouseDragCallback=this._dragCallback.bind(this)}mouseWheelCallback(t){this._zoom(t)}_pinchCallback(t){if(t.detail.currentPointsList.length>1){const{element:e,currentPoints:o}=t.detail,s=N(e),{viewport:a}=s,r=Ya(a),c=o.world;if(!hr(r)){Zs(a)&&(this._dragViewportZoom(t,a),a.render()),this.configuration.pan&&this._panCallback(t);return}const{focalPoint:l}=r;this.initialMousePosWorld=c;let d=Ot(l[0]-c[0],l[1]-c[1],l[2]-c[2]);d=Wt(B(),d),this.dirVec=d,Su(r)&&r.parallelProjection?this._dragParallelProjection(t,a,r,!0):jV(r)&&this._dragPerspectiveProjection(t,a,r,!0),a.render()}this.configuration.pan&&this._panCallback(t)}_dragCallback(t){const{element:n}=t.detail,e=N(n),{viewport:o}=e,s=Ya(o);if(Su(s))s.parallelProjection?this._dragParallelProjection(t,o,s):this._dragPerspectiveProjection(t,o,s);else{if(!Zs(o))return;this._dragViewportZoom(t,o)}o.render()}_zoom(t){const{element:n,points:e}=t.detail,o=N(n),{viewport:s}=o,a=Ya(s),c=t.detail.wheel.direction;if(!Su(a)){if(!Zs(s))return;const d=this.configuration.zoomToCenter?void 0:e.canvas;this._applyViewportZoomDelta(s,n,-c*5,d),s.render();return}const l={detail:{element:n,eventName:E.MOUSE_WHEEL,renderingEngineId:o.renderingEngineId,viewportId:s.id,camera:{},deltaPoints:{page:e.page,client:e.client,world:e.world,canvas:[0,-c*5]},startPoints:e,lastPoints:e,currentPoints:e}};s.type===so.STACK&&this.preMouseDownCallback(l),this._dragCallback(l)}_panCallback(t){const{element:n,deltaPoints:e}=t.detail,o=N(n),s=e.world,a=o.viewport,r=Ya(a);if(!hr(r)){if(!gr(a))return;const h=a.getPan();a.setPan([h[0]+e.canvas[0],h[1]+e.canvas[1]]),a.render();return}const{focalPoint:c,position:l}=r,d=[l[0]-s[0],l[1]-s[1],l[2]-s[2]],u=[c[0]-s[0],c[1]-s[1],c[2]-s[2]];a.setCamera({focalPoint:u,position:d}),a.render()}_dragViewportZoom(t,n){const{element:e,deltaPoints:o,startPoints:s}=t.detail,a=this.configuration.zoomToCenter?void 0:s?.canvas;this._applyViewportZoomDelta(n,e,o.canvas[1],a)}_applyViewportZoomDelta(t,n,e,o){const s=t.getZoom(),a=5/Math.max(n.clientHeight,1),r=e*a*(this.configuration.invert?-1:1),c=Math.max(1-r,.01),l=s/c,d=Math.min(Math.max(l,this.configuration.minZoomScale),this.configuration.maxZoomScale);t.setZoom(d,o)}}function Ya(i){const t=i;return typeof t.getCamera=="function"?t.getCamera():void 0}function hr(i){return!!(i&&Array.isArray(i.focalPoint)&&Array.isArray(i.position))}function Su(i){return!!(hr(i)&&typeof i.parallelProjection=="boolean"&&typeof i.parallelScale=="number"&&Array.isArray(i.viewPlaneNormal))}function jV(i){return!!(hr(i)&&Array.isArray(i.viewPlaneNormal))}$V.toolName="Zoom";class XV extends Ee{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{targetViewportIds:[]}}){super(t,n)}mouseClickCallback(t){const{element:n,currentPoints:e}=t.detail,o=N(n),{viewport:s,renderingEngine:a}=o,r=s.getVolumeId();if(!r)throw new Error("MIPJumpToClickTool: targetId is not a volumeId, you should only use MIPJumpToClickTool with a volumeId as the targetId");let c=-1/0;const l=(g,m)=>{if(g>c)return c=g,m},d=sf(s,e.world,r,l);if(!d||!d.length)return;const{targetViewportIds:u,toolGroupId:h}=this.configuration;a.getViewports().filter(g=>{if(u?.indexOf(g.id)>=0)return!0;const m=Ae(g.id,a.id);return!!(h&&h===m?.id)}).forEach(g=>{g instanceof Xe?g.jumpToWorld(d):console.warn("Cannot jump to specified world coordinates for a viewport that is not a VolumeViewport")})}}XV.toolName="MIPJumpToClickTool";const{RENDERING_DEFAULTS:Cu}=Qo;function Ka(i){if(ie(i)){const{element:e}=i;return{clientWidth:e.clientWidth,clientHeight:e.clientHeight}}const{clientWidth:t,clientHeight:n}=i.canvas;return{clientWidth:t,clientHeight:n}}function qV(){return"rgb(0, 200, 0)"}function YV(){return!0}function KV(){return!0}function ZV(){return!0}const Po={DRAG:1,ROTATE:2,SLAB:3};class bS extends be{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{shadow:!0,viewportIndicators:!1,viewportIndicatorsConfig:{radius:5,x:null,y:null},autoPan:{enabled:!1,panSize:10},handleRadius:3,enableHDPIHandles:!1,referenceLinesCenterGapRadius:20,referenceLinesCenterGapRatio:null,minimal:{enabled:!1,lineLengthInPx:40},filterActorUIDsToSetSlabThickness:[],slabThicknessBlendMode:Gn.MAXIMUM_INTENSITY_BLEND,centerPoint:{enabled:!1,color:"rgba(255, 255, 0, 0.5)",size:2},mobile:{enabled:hI(),opacity:.8,handleRadius:9,referenceLinesCenterGapRatio:.05}}}){super(t,n),this.toolCenter=[0,0,0],this._volumeViewportNewVolumeListeners=new Map,this._toolGroupViewportAddedListener=null,this._toolGroupViewportRemovedListener=null,this._ignoreFiredEvents=!1,this.initializeViewport=({renderingEngineId:e,viewportId:o})=>{const s=ae(o,e);if(!s)return;const{FrameOfReferenceUID:a,viewport:r}=s,{element:c}=r,{position:l,focalPoint:d,viewPlaneNormal:u}=ht(r);let h=this._getAnnotations(s);h=this.filterInteractableAnnotationsForElement(c,h),h?.length&&Gt(h[0].annotationUID);const f={highlighted:!1,metadata:{cameraPosition:[...l],cameraFocalPoint:[...d],FrameOfReferenceUID:a,toolName:this.getToolName()},data:{handles:{rotationPoints:[],slabThicknessPoints:[],toolCenter:this.toolCenter},activeOperation:null,activeViewportIds:[],viewportId:o}};Nt(f,c);const{clientWidth:g,clientHeight:m}=Ka(r);return{normal:u,point:r.canvasToWorld([g/2,m/2])}},this._getViewportsInfo=()=>Be(this.toolGroupId).viewportsInfo,this._reinitializeListenersAndCenter=()=>{this._unbindToolGroupViewportListeners(),this._clearAllVolumeListenersAndViewportState(),this._bindToolGroupViewportListeners(),this._syncVolumeListenersWithToolGroup(),this._computeToolCenter(this._getViewportsInfo())},this.resetCrosshairs=()=>{const e=this._getViewportsInfo();for(const o of e){const{viewportId:s,renderingEngineId:a}=o,r=ae(s,a);if(!r)continue;const c=r.viewport,l=!0,d=!0,u=!0,h=!0;ie(c)?c.resetViewState({resetPan:l,resetZoom:d,resetOrientation:h,resetFlip:!0}):(c.resetCamera({resetPan:l,resetZoom:d,resetToCenter:u,resetRotation:h,suppressEvents:!0}),c.resetSlabThickness());const{element:g}=c;let m=this._getAnnotations(r);m=this.filterInteractableAnnotationsForElement(g,m),m.length&&Gt(m[0].annotationUID),c.render()}this._computeToolCenter(e)},this.computeToolCenter=()=>{const e=this._getViewportsInfo();this._computeToolCenter(e)},this._computeToolCenter=e=>{if(!e.length||e.length===1){console.warn("For crosshairs to operate, at least two viewports must be given.");return}e.forEach(o=>{this.initializeViewport(o)}),this._recomputeToolCenterFromAbsoluteCameras({emitEvent:!0,updateViewportCameras:!0})},this.addNewAnnotation=e=>{const o=e.detail,{element:s}=o,{currentPoints:a}=o,r=a.world;this._syncVolumeListenersWithToolGroup(),this._recomputeToolCenterFromAbsoluteCameras({emitEvent:!1,updateViewportCameras:!1});const c=N(s),{viewport:l}=c;this._jump(c,r);const d=this._getAnnotations(c),u=this.filterInteractableAnnotationsForElement(l.element,d),{data:h}=u[0],{rotationPoints:f}=h.handles,g=[];for(let m=0;m<f.length-1;++m){const p=f[m][1],v=this._getReferenceLineControllable(p.id),I=this._getReferenceLineDraggableRotatable(p.id);!v||!I||(g.push(p.id),m++)}return h.activeViewportIds=[...g],h.handles.activeOperation=Po.DRAG,e.preventDefault(),wt(s),this._activateModify(s,e),u[0]},this.cancel=()=>{console.log("Not implemented yet")},this.handleSelectedCallback=(e,o)=>{const s=e.detail,{element:a}=s;o.highlighted=!0,this._activateModify(a,e),wt(a),e.preventDefault()},this.isPointNearTool=(e,o,s,a)=>!!this._pointNearTool(e,o,s,a),this.toolSelectedCallback=(e,o,s)=>{const a=e.detail,{element:r}=a;o.highlighted=!0,this._activateModify(r,e),wt(r),e.preventDefault()},this.onCameraModified=e=>{const o=e.detail,{element:s}=o,a=N(s);if(!a)return;const{renderingEngine:r}=a,c=a.viewport;if(this._syncVolumeListenersWithToolGroup(),this._ignoreFiredEvents||!this._getViewportsInfo().some(({viewportId:p,renderingEngineId:v})=>p===c.id&&v===r.id))return;const d=this._getAnnotations(a),h=this.filterInteractableAnnotationsForElement(s,d)[0],f=ht(c);h&&(h.metadata.cameraPosition=[...f.position],h.metadata.cameraFocalPoint=[...f.focalPoint]),this._recomputeToolCenterFromAbsoluteCameras({emitEvent:!0,updateViewportCameras:!1}),this.configuration.autoPan?.enabled&&Ae(c.id,r.id).getViewportIds().filter(I=>I!==c.id).forEach(I=>{this._autoPanViewportIfNecessary(I,r)});const m=ft(s,this.getToolName(),!1);V(m)},this.onResetCamera=e=>{this.resetCrosshairs()},this.mouseMoveCallback=(e,o)=>{if(!o)return!1;const{element:s,currentPoints:a}=e.detail,r=a.canvas;let c=!1;for(let l=0;l<o.length;l++){const d=o[l];if(ze(d.annotationUID))continue;const{data:u,highlighted:h}=d;if(!u.handles)continue;const f=u.handles.activeOperation,g=u.activeViewportIds&&u.activeViewportIds.length>0?[...u.activeViewportIds]:[];u.activeViewportIds=[],u.handles.activeOperation=null;const m=this.getHandleNearImagePoint(s,d,r,6);let p=!1;m?p=!0:p=this._pointNearTool(s,d,r,6),p&&!h||!p&&h?(d.highlighted=!h,c=!0):(u.handles.activeOperation!==f||!this._areViewportIdArraysEqual(u.activeViewportIds,g))&&(c=!0)}return c},this.filterInteractableAnnotationsForElement=(e,o)=>{if(!o||!o.length)return[];const s=N(e),{viewportId:a}=s;return o.filter(c=>c.data.viewportId===a)},this.renderAnnotation=(e,o)=>{let s=!1;const{viewport:a,renderingEngine:r}=e,{element:c}=a,l=this._getAnnotations(e),d=ht(a),h=this.filterInteractableAnnotationsForElement(c,l)[0];if(!l?.length||!h?.data)return s;const f=h.annotationUID,{clientWidth:g,clientHeight:m}=Ka(a),p=Math.sqrt(g*g+m*m),v=Math.min(g,m),I=h.data,w=a.worldToCanvas(this.toolCenter),C=this._filterAnnotationsByUniqueViewportOrientations(e,l),S=[],b=[0,0,g,m];C.forEach(P=>{const{data:x}=P;x.handles.toolCenter=this.toolCenter;const M=r.getViewport(x.viewportId),L=ht(M),R=this._getReferenceLineControllable(M.id),U=this._getReferenceLineDraggableRotatable(M.id),W=this._getReferenceLineSlabThicknessControlsOn(M.id),{clientWidth:K,clientHeight:j}=Ka(M),F=Math.sqrt(K*K+j*j),z=[K*.5,j*.5],q=M.canvasToWorld(z),J=[0,0,0];Vt.cross(d.viewPlaneNormal,L.viewPlaneNormal,J),Vt.normalize(J),Vt.multiplyScalar(J,F);const it=[0,0,0];Vt.add(q,J,it);const tt=[0,0,0];Vt.subtract(q,J,tt);const ot=a.worldToCanvas(it),nt=a.worldToCanvas(q),lt=It();pe(lt,ot,nt),Ao(lt,lt);const rt=It();Oi(rt,lt,p*100);const ut=It();Oi(ut,lt,v*.2);const Tt=It(),kt=this.configuration.mobile,Pt=kt?.enabled?kt:this.configuration,{referenceLinesCenterGapRatio:te}=Pt,Ie=Za(this.configuration),re=te>0?v*te:this.configuration.referenceLinesCenterGapRadius;Oi(Tt,lt,C.length===2?re:0);const Zt=It(),ce=It(),Ut=It(),Ht=It();let Jt=gi(w);if((!U||!R)&&(Jt=gi(nt)),Tn(Zt,Jt,Tt),Tn(ce,Jt,rt),pe(Ut,Jt,Tt),pe(Ht,Jt,rt),li(Zt,ce,b),li(Ut,Ht,b),Ie.enabled){const Pi=It();Oi(Pi,lt,Ie.lineLengthInPx),Tn(Zt,Jt,Tt),Tn(ce,Zt,Pi),pe(Ut,Jt,Tt),pe(Ht,Ut,Pi),li(Zt,ce,b),li(Ut,Ht,b)}const Pe=Mp(Zt,ce),De=Mp(Ut,Ht);let ln=gi(w);!U&&W&&(ln=gi(nt));let Ve=[...this.toolCenter];!U&&W&&(Ve=[...q]);const Wo=[0,0,0];Vt.subtract(it,tt,Wo),Vt.normalize(Wo);const{viewPlaneNormal:jn}=d,{matrix:Bo}=po.buildFromDegree().rotate(90,jn),co=[0,0,0];Ue(co,Wo,Bo);const yi=pu(M),lo=[...co];Vt.multiplyScalar(lo,yi);const xi=[0,0,0];Vt.add(Ve,lo,xi);const oi=a.worldToCanvas(xi),st=It();pe(st,ln,oi);const Mt=It();pe(Mt,ln,rt),Tn(Mt,Mt,st);const G=It();Tn(G,ln,rt),Tn(G,G,st),li(Mt,G,b);const et=It();Tn(et,ln,rt),pe(et,et,st);const at=It();pe(at,ln,rt),pe(at,at,st),li(et,at,b);const jt=It(),je=It(),dn=It(),yo=It();pe(jt,ln,ut),Tn(jt,jt,st),Tn(je,ln,ut),Tn(je,je,st),pe(dn,ln,ut),pe(dn,dn,st),Tn(yo,ln,ut),pe(yo,yo,st),S.push([M,Zt,ce,Ut,Ht,Mt,G,et,at,Pe,De,jt,je,dn,yo])});const _=[],y=[],D=this._getReferenceLineColor(a.id),T=D!==void 0?D:"rgb(200, 200, 200)";if(S.forEach((P,x)=>{const M=P[0],L=Za(this.configuration),R=this._getReferenceLineColor(M.id),U=this._getReferenceLineControllable(M.id),W=!L.enabled&&(this._getReferenceLineDraggableRotatable(M.id)||this.configuration.mobile?.enabled),K=!L.enabled&&(this._getReferenceLineSlabThicknessControlsOn(M.id)||this.configuration.mobile?.enabled),j=I.activeViewportIds.find(it=>it===M.id);let F=R!==void 0?R:"rgb(200, 200, 200)",z=1;const q=I.handles.activeOperation!==null&&I.handles.activeOperation===Po.DRAG&&j;q&&(z=2.5);let J=`${x}`;if(U&&(W||L.enabled)?(J=`${x}One`,qt(o,f,J,P[1],P[2],{color:F,lineWidth:z}),J=`${x}Two`,qt(o,f,J,P[3],P[4],{color:F,lineWidth:z})):qt(o,f,J,P[2],P[4],{color:F,lineWidth:z}),U){F=R!==void 0?R:"rgb(200, 200, 200)";const it=I.handles.activeOperation===Po.ROTATE,tt=[P[9],P[10]],ot=[a.canvasToWorld(P[9]),M,P[1],P[2]],nt=[a.canvasToWorld(P[10]),M,P[3],P[4]];_.push(ot,nt);const lt=I.handles.activeOperation===Po.SLAB,rt=[P[11],P[12],P[13],P[14]];if(!L.enabled){const Pt=[a.canvasToWorld(P[11]),M,P[5],P[6]],te=[a.canvasToWorld(P[12]),M,P[5],P[6]],Ie=[a.canvasToWorld(P[13]),M,P[7],P[8]],re=[a.canvasToWorld(P[14]),M,P[7],P[8]];y.push(Pt,te,Ie,re)}let ut=this.configuration.handleRadius*(this.configuration.enableHDPIHandles?window.devicePixelRatio:1),Tt=1;if(this.configuration.mobile?.enabled&&(ut=this.configuration.mobile.handleRadius,Tt=this.configuration.mobile.opacity),(q||this.configuration.mobile?.enabled)&&!it&&!lt&&W&&K){let Pt=`${x}One`;xe(o,f,Pt,tt,{color:F,handleRadius:ut,opacity:Tt,type:"circle"}),Pt=`${x}Two`,xe(o,f,Pt,rt,{color:F,handleRadius:ut,opacity:Tt,type:"rect"})}else if(q&&!it&&!lt&&W){const Pt=`${x}`;xe(o,f,Pt,tt,{color:F,handleRadius:ut,opacity:Tt,type:"circle"})}else if(j&&!it&&!lt&&K){const Pt=`${x}`;xe(o,f,Pt,rt,{color:F,handleRadius:ut,opacity:Tt,type:"rect"})}else if(it&&W){const Pt=`${x}`,te=this.configuration.handleRadius*(this.configuration.enableHDPIHandles?window.devicePixelRatio:1);xe(o,f,Pt,tt,{color:F,handleRadius:te,fill:F,type:"circle"})}else if(lt&&j&&K){const Pt=this.configuration.handleRadius*(this.configuration.enableHDPIHandles?window.devicePixelRatio:1);xe(o,f,J,rt,{color:F,handleRadius:Pt,fill:F,type:"rect"})}pu(M)>.5&&K&&(J=`${x}STOne`,qt(o,f,J,P[5],P[6],{color:F,width:1,lineDash:[2,3]}),J=`${x}STTwo`,qt(o,f,J,P[7],P[8],{color:F,width:P,lineDash:[2,3]}))}}),s=!0,I.handles.rotationPoints=_,I.handles.slabThicknessPoints=y,this.configuration.viewportIndicators){const{viewportIndicatorsConfig:P}=this.configuration,x=P?.xOffset||.95,M=P?.yOffset||.05,L=[g*x,m*M],R=P?.circleRadius||p*.01;En(o,f,"0",L,R,{color:T,fill:T})}if(this.configuration.centerPoint?.enabled){const L=this.configuration.centerPoint.color||"rgba(255, 255, 0, 0.5)",R=Math.min(this.configuration.centerPoint.size||2,5);En(o,f,"centerPoint",w,R,{color:L,fill:L})}return s},this._getAnnotations=e=>{const{viewport:o}=e,s=Yt(this.getToolName(),o.element)||[],a=this._getViewportsInfo().map(({viewportId:c})=>c);return s.filter(c=>{const{data:l}=c;return a.includes(l.viewportId)})},this._onNewVolume=e=>{this._syncVolumeListenersWithToolGroup(),this._recomputeToolCenterFromAbsoluteCameras({emitEvent:!0,updateViewportCameras:!1})},this._areViewportIdArraysEqual=(e,o)=>{if(e.length!==o.length)return!1;for(let s=0;s<e.length;s++){const a=e[s];let r=!1;for(let c=0;c<o.length;++c)if(a===o[c]){r=!0;break}if(r===!1)return!1}return!0},this._getAnnotationsForViewportsWithDifferentCameras=(e,o)=>{const{viewportId:s,renderingEngine:a,viewport:r}=e,c=o.filter(f=>f.data.viewportId!==s);if(!c||!c.length)return[];const l=ht(r),{viewPlaneNormal:d,position:u}=l;return c.filter(f=>{const{viewportId:g}=f.data,m=a.getViewport(g),p=ht(m);return!(ve(p.viewPlaneNormal,d,.01)&&ve(p.position,u,1))})},this._filterViewportWithSameOrientation=(e,o,s)=>{const{renderingEngine:a}=e,{data:r}=o,c=a.getViewport(r.viewportId),l=s.filter(f=>{const{data:g}=f,m=a.getViewport(g.viewportId);return this._getReferenceLineControllable(m.id)===!0});if(!l||!l.length)return[];const d=ht(c),u=d.viewPlaneNormal;return Vt.normalize(u),l.filter(f=>{const{viewportId:g}=f.data,m=a.getViewport(g),p=ht(m),v=p.viewPlaneNormal;return Vt.normalize(v),ve(u,v,.01)&&ve(d.viewUp,p.viewUp,.01)})},this._filterAnnotationsByUniqueViewportOrientations=(e,o)=>{const{renderingEngine:s,viewport:a}=e,c=ht(a).viewPlaneNormal;Vt.normalize(c);const l=o.filter(f=>{const{data:g}=f,m=s.getViewport(g.viewportId),p=this._getReferenceLineControllable(m.id);return a!==m&&p===!0}),d=[];for(let f=0;f<l.length;++f){const g=l[f],{viewportId:m}=g.data,p=s.getViewport(m),v=ht(p),I=v.viewPlaneNormal;if(Vt.normalize(I),ve(c,I,.01)||Fa(c,I,.01))continue;let w=!1;for(let C=0;C<d.length;++C){const S=d[C],{viewportId:b}=S.data,_=s.getViewport(b),y=ht(_);ve(y.viewPlaneNormal,v.viewPlaneNormal,.01)&&ve(y.position,v.position,1)&&(w=!0)}w||d.push(g)}const u=o.filter(f=>{const{data:g}=f,m=s.getViewport(g.viewportId),p=this._getReferenceLineControllable(m.id);return a!==m&&p!==!0});for(let f=0;f<u.length;++f){const g=u[f],{viewportId:m}=g.data,p=s.getViewport(m),v=ht(p),I=v.viewPlaneNormal;if(Vt.normalize(I),ve(c,I,.01)||Fa(c,I,.01))continue;let w=!1;for(let C=0;C<d.length;++C){const S=d[C],{viewportId:b}=S.data,_=s.getViewport(b),y=ht(_);ve(y.viewPlaneNormal,v.viewPlaneNormal,.01)&&ve(y.position,v.position,1)&&(w=!0)}w||d.push(g)}const h=this._getAnnotationsForViewportsWithDifferentCameras(e,o);for(let f=0;f<h.length;++f){const g=h[f];if(d.some(C=>C===g))continue;const{viewportId:m}=g.data,p=s.getViewport(m),v=ht(p),I=v.viewPlaneNormal;if(Vt.normalize(I),ve(c,I,.01)||Fa(c,I,.01))continue;let w=!1;for(let C=0;C<d.length;++C){const S=d[C],{viewportId:b}=S.data,_=s.getViewport(b),y=ht(_);ve(y.viewPlaneNormal,v.viewPlaneNormal,.01)&&ve(y.position,v.position,1)&&(w=!0)}w||d.push(g)}return d},this._checkIfViewportsRenderingSameScene=(e,o)=>{if(ie(e)||ie(o)){const r=e.getViewReference?.(),c=o.getViewReference?.(),l=r?.dataId??r?.FrameOfReferenceUID,d=c?.dataId??c?.FrameOfReferenceUID;return!!l&&l===d}const s=e.getAllVolumeIds(),a=o.getAllVolumeIds();return s.length===a.length&&s.every(r=>a.includes(r))},this._jump=(e,o)=>{$.isInteractingWithTool=!0;const{viewport:s,renderingEngine:a}=e,r=this._getAnnotations(e),c=[0,0,0];Vt.subtract(o,this.toolCenter,c);const d=this._getAnnotationsForViewportsWithDifferentCameras(e,r).filter(u=>{const{data:h}=u,f=a.getViewport(h.viewportId),g=this._checkIfViewportsRenderingSameScene(s,f);return this._getReferenceLineControllable(f.id)&&this._getReferenceLineDraggableRotatable(f.id)&&g});return d.length===0?($.isInteractingWithTool=!1,!1):(this._applyDeltaShiftToSelectedViewportCameras(a,d,c),this._recomputeToolCenterFromAbsoluteCameras({emitEvent:!0,updateViewportCameras:!1}),s.render(),$.isInteractingWithTool=!1,!0)},this._activateModify=(e,o)=>{this._syncVolumeListenersWithToolGroup(),this._recomputeToolCenterFromAbsoluteCameras({emitEvent:!1,updateViewportCameras:!1}),$.isInteractingWithTool=!(this._isTouchInteraction(o)&&this.configuration.mobile?.enabled),e.addEventListener(E.MOUSE_UP,this._endCallback),e.addEventListener(E.MOUSE_DRAG,this._dragCallback),e.addEventListener(E.MOUSE_CLICK,this._endCallback),e.addEventListener(E.TOUCH_END,this._endCallback),e.addEventListener(E.TOUCH_DRAG,this._dragCallback),e.addEventListener(E.TOUCH_TAP,this._endCallback)},this._deactivateModify=e=>{$.isInteractingWithTool=!1,e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.TOUCH_END,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback)},this._endCallback=e=>{const o=e.detail,{element:s}=o;this.editData?.annotation?.data&&(this.editData.annotation.data.handles.activeOperation=null,this.editData.annotation.data.activeViewportIds=[]),this._deactivateModify(s),this._recomputeToolCenterFromAbsoluteCameras({emitEvent:!0,updateViewportCameras:!1}),Ft(s),this.editData=null;const r=ft(s,this.getToolName(),!1);V(r)},this._dragCallback=e=>{const o=e.detail,s=o.deltaPoints.world;if(Math.abs(s[0])<.001&&Math.abs(s[1])<.001&&Math.abs(s[2])<.001)return;const{element:a}=o,r=N(a),{renderingEngine:c,viewport:l}=r,d=this._getAnnotations(r),h=this.filterInteractableAnnotationsForElement(a,d)[0];if(!h)return;const{handles:f}=h.data,{currentPoints:g}=e.detail,m=g.canvas;if(f.activeOperation===Po.DRAG){const w=this._getAnnotationsForViewportsWithDifferentCameras(r,d).filter(C=>{const{data:S}=C,b=c.getViewport(S.viewportId),_=this._getReferenceLineControllable(b.id),y=this._getReferenceLineDraggableRotatable(b.id);return _===!0&&y===!0&&h.data.activeViewportIds.find(D=>D===b.id)});this._applyDeltaShiftToSelectedViewportCameras(c,w,s),this._recomputeToolCenterFromAbsoluteCameras({emitEvent:!0,updateViewportCameras:!1})}else if(f.activeOperation===Po.ROTATE){if(ie(r.viewport))return;const w=this._getAnnotationsForViewportsWithDifferentCameras(r,d).filter(R=>{const{data:U}=R,W=c.getViewport(U.viewportId),K=this._getReferenceLineControllable(W.id),j=this._getReferenceLineDraggableRotatable(W.id);return K===!0&&j===!0}),C=It(),S=It(),b=[this.toolCenter[0],this.toolCenter[1],this.toolCenter[2]],_=l.worldToCanvas(b),y=o.currentPoints.canvas,D=It();No(D,y,o.deltaPoints.canvas),No(C,D,_),No(S,y,_);let T=TI(C,S);this._isClockWise(_,D,y)&&(T*=-1),T=Math.round(T*100)/100;const P=ht(l).viewPlaneNormal,{matrix:x}=po.buildFromRadian().translate(b[0],b[1],b[2]).rotate(T,P).translate(-b[0],-b[1],-b[2]),M=[],L=this._ignoreFiredEvents;this._ignoreFiredEvents=!0;try{w.forEach(R=>{const{data:U}=R;U.handles.toolCenter=b;const W=c.getViewport(U.viewportId),K=ht(W),{viewUp:j,position:F,focalPoint:z}=K;j[0]+=F[0],j[1]+=F[1],j[2]+=F[2],Ue(z,z,x),Ue(F,F,x),Ue(j,j,x),j[0]-=F[0],j[1]-=F[1],j[2]-=F[2],W.setCamera({position:F,viewUp:j,focalPoint:z}),M.push(W.id)})}finally{this._ignoreFiredEvents=L}c.renderViewports(M),this._recomputeToolCenterFromAbsoluteCameras({emitEvent:!0,updateViewportCameras:!1})}else if(f.activeOperation===Po.SLAB){if(ie(r.viewport))return;const w=this._getAnnotationsForViewportsWithDifferentCameras(r,d).filter(b=>{const{data:_}=b,y=c.getViewport(_.viewportId),D=this._getReferenceLineControllable(y.id),T=this._getReferenceLineSlabThicknessControlsOn(y.id);return D===!0&&T===!0&&h.data.activeViewportIds.find(P=>P===y.id)});if(w.length===0)return;const C=this._filterViewportWithSameOrientation(r,w[0],d),S=[];S.push(l.id),C.forEach(b=>{const{data:_}=b,y=c.getViewport(_.viewportId),T=ht(y).viewPlaneNormal,P=Vt.dot(s,T),x=[...T];if(Vt.multiplyScalar(x,P),Math.abs(x[0])>.001||Math.abs(x[1])>.001||Math.abs(x[2])>.001){const M=Math.sqrt(x[0]*x[0]+x[1]*x[1]+x[2]*x[2]),L=o.lastPoints.world,R=[0,0,0],U=[this.toolCenter[0],this.toolCenter[1],this.toolCenter[2]];if(!this._getReferenceLineDraggableRotatable(y.id)){const{rotationPoints:ot}=this.editData.annotation.data.handles,nt=ot.filter(lt=>lt[1].uid===y.id);if(nt.length===2){const lt=l.canvasToWorld(nt[0][3]),rt=l.canvasToWorld(nt[1][3]);Vt.add(lt,rt,U),Vt.multiplyScalar(U,.5)}}Vt.subtract(L,U,R);const K=Vt.dot(R,T),j=[...T];Vt.multiplyScalar(j,K);const F=[j[0],j[1],j[2]];Wt(F,F);const z=[x[0],x[1],x[2]];Wt(z,z);let q=pu(y);Fa(F,z,.001)?q-=M:q+=M,q=Math.abs(q),q=Math.max(Cu.MINIMUM_SLAB_THICKNESS,q),this._pointNearReferenceLine(h,m,6,y)&&(q=Cu.MINIMUM_SLAB_THICKNESS),Ae(y.id,c.id).getToolInstance(this.getToolName()).setSlabThickness(y,q),S.push(y.id)}}),c.renderViewports(S),this._recomputeToolCenterFromAbsoluteCameras({emitEvent:!0,updateViewportCameras:!1})}const v=ft(a,this.getToolName(),!1);V(v)},this._pointNearReferenceLine=(e,o,s,a)=>{const{data:r}=e,{rotationPoints:c}=r.handles;for(let l=0;l<c.length-1;++l){const d=c[l][1];if(d.id!==a.id||!this._getReferenceLineControllable(d.id))continue;const h={start:{x:c[l][2][0],y:c[l][2][1]},end:{x:c[l][3][0],y:c[l][3][1]}},f=Je([h.start.x,h.start.y],[h.end.x,h.end.y],[o[0],o[1]]),g={start:{x:c[l+1][2][0],y:c[l+1][2][1]},end:{x:c[l+1][3][0],y:c[l+1][3][1]}},m=Je([g.start.x,g.start.y],[g.end.x,g.end.y],[o[0],o[1]]);if(f<=s||m<=s)return!0;l++}return!1},this._toViewportKey=(e,o)=>`${e}::${o}`,this._isFinitePoint3=e=>!e||e.length!==3?!1:Number.isFinite(e[0])&&Number.isFinite(e[1])&&Number.isFinite(e[2]),this._bindToolGroupViewportListeners=()=>{this._toolGroupViewportAddedListener||(this._toolGroupViewportAddedListener=(e=>{e.detail?.toolGroupId===this.toolGroupId&&(this._syncVolumeListenersWithToolGroup(),this._computeToolCenter(this._getViewportsInfo()))}),Z.addEventListener(E.TOOLGROUP_VIEWPORT_ADDED,this._toolGroupViewportAddedListener)),this._toolGroupViewportRemovedListener||(this._toolGroupViewportRemovedListener=(e=>{e.detail?.toolGroupId===this.toolGroupId&&(this._syncVolumeListenersWithToolGroup(),this._recomputeToolCenterFromAbsoluteCameras({emitEvent:!0,updateViewportCameras:!1}))}),Z.addEventListener(E.TOOLGROUP_VIEWPORT_REMOVED,this._toolGroupViewportRemovedListener))},this._unbindToolGroupViewportListeners=()=>{this._toolGroupViewportAddedListener&&(Z.removeEventListener(E.TOOLGROUP_VIEWPORT_ADDED,this._toolGroupViewportAddedListener),this._toolGroupViewportAddedListener=null),this._toolGroupViewportRemovedListener&&(Z.removeEventListener(E.TOOLGROUP_VIEWPORT_REMOVED,this._toolGroupViewportRemovedListener),this._toolGroupViewportRemovedListener=null)},this._syncVolumeListenersWithToolGroup=()=>{const e=this._getViewportsInfo(),o=new Set;e.forEach(s=>{const{viewportId:a,renderingEngineId:r}=s,c=this._toViewportKey(r,a);o.add(c);const l=ae(a,r),d=this._volumeViewportNewVolumeListeners.get(c);if(!l){d&&(d.element.removeEventListener(yt.VOLUME_VIEWPORT_NEW_VOLUME,d.handler),this._volumeViewportNewVolumeListeners.delete(c));return}const{viewport:u}=l,{element:h}=u;if(d&&d.element!==h&&(d.element.removeEventListener(yt.VOLUME_VIEWPORT_NEW_VOLUME,d.handler),this._volumeViewportNewVolumeListeners.delete(c)),this._volumeViewportNewVolumeListeners.has(c))return;const f=(g=>this._onNewVolume(g));h.addEventListener(yt.VOLUME_VIEWPORT_NEW_VOLUME,f),this._volumeViewportNewVolumeListeners.set(c,{element:h,handler:f})}),Array.from(this._volumeViewportNewVolumeListeners.entries()).forEach(([s,a])=>{o.has(s)||(a.element.removeEventListener(yt.VOLUME_VIEWPORT_NEW_VOLUME,a.handler),this._volumeViewportNewVolumeListeners.delete(s))})},this._clearAllVolumeListenersAndViewportState=()=>{this._volumeViewportNewVolumeListeners.forEach(e=>{e.element.removeEventListener(yt.VOLUME_VIEWPORT_NEW_VOLUME,e.handler)}),this._volumeViewportNewVolumeListeners.clear()},this._calculateToolCenterFromAbsoluteCameras=()=>{const e=this._getViewportsInfo(),o=[];if(e.forEach(l=>{const d=ae(l.viewportId,l.renderingEngineId);if(!d)return;const u=ht(d.viewport),h=[...u.viewPlaneNormal],f=[...u.focalPoint];if(!this._isFinitePoint3(h)||!this._isFinitePoint3(f))return;Wt(h,h),o.some(m=>ve(m.normal,h,.001)||Fa(m.normal,h,.001))||o.push({normal:h,point:f})}),o.length<2)return null;const s=$o(o[0].normal,o[0].point),a=$o(o[1].normal,o[1].point);let r;if(o.length>=3)r=$o(o[2].normal,o[2].point);else{const l=B();if(Me(l,o[0].normal,o[1].normal),mn(l)<1e-6)return null;Wt(l,l);const d=this._isFinitePoint3(this.toolCenter)?[...this.toolCenter]:[(o[0].point[0]+o[1].point[0])*.5,(o[0].point[1]+o[1].point[1])*.5,(o[0].point[2]+o[1].point[2])*.5];r=$o(l,d)}const c=VC(s,a,r);return this._isFinitePoint3(c)?c:null},this._recomputeToolCenterFromAbsoluteCameras=({emitEvent:e=!0,updateViewportCameras:o=!1}={})=>{const s=this._calculateToolCenterFromAbsoluteCameras();return s?(ve(this.toolCenter,s,.001)||(o?this.setToolCenter(s,!e):(this.toolCenter=s,e&&Rt(Z,E.CROSSHAIR_TOOL_CENTER_CHANGED,{toolGroupId:this.toolGroupId,toolCenter:this.toolCenter}))),s):null},this._getReferenceLineColor=t.configuration?.getReferenceLineColor||qV,this._getReferenceLineControllable=t.configuration?.getReferenceLineControllable||YV,this._getReferenceLineDraggableRotatable=t.configuration?.getReferenceLineDraggableRotatable||KV,this._getReferenceLineSlabThicknessControlsOn=t.configuration?.getReferenceLineSlabThicknessControlsOn||ZV}onSetToolActive(){this._reinitializeListenersAndCenter()}onSetToolPassive(){this._reinitializeListenersAndCenter()}onSetToolEnabled(){this._reinitializeListenersAndCenter()}onSetToolDisabled(){const t=this._getViewportsInfo();this._unbindToolGroupViewportListeners(),this._clearAllVolumeListenersAndViewportState(),this._ignoreFiredEvents=!1,this.editData=null,$.isInteractingWithTool=!1,t.forEach(({renderingEngineId:n,viewportId:e})=>{const o=ae(e,n);if(!o)return;const s=this._getAnnotations(o);s?.length&&s.forEach(a=>{Gt(a.annotationUID)})})}setToolCenter(t,n=!1){const e=this._getViewportsInfo(),o=this._ignoreFiredEvents;this._ignoreFiredEvents=!0;try{e.forEach(({renderingEngineId:s,viewportId:a})=>{const r=Ne(s);if(!r)return;const c=r.getViewport(a);if(!c)return;const l=ht(c),{focalPoint:d,position:u,viewPlaneNormal:h}=l,f=[t[0]-d[0],t[1]-d[1],t[2]-d[2]],g=f[0]*h[0]+f[1]*h[1]+f[2]*h[2],m=[g*h[0],g*h[1],g*h[2]],p=[d[0]+m[0],d[1]+m[1],d[2]+m[2]],v=[u[0]+m[0],u[1]+m[1],u[2]+m[2]];ie(c)?yl(c,p):c.setCamera({focalPoint:p,position:v}),c.render()})}finally{this._ignoreFiredEvents=o}this.toolCenter=t,n||Rt(Z,E.CROSSHAIR_TOOL_CENTER_CHANGED,{toolGroupId:this.toolGroupId,toolCenter:this.toolCenter})}getHandleNearImagePoint(t,n,e,o){const s=N(t),{viewport:a}=s;let r=this._getRotationHandleNearImagePoint(a,n,e,o);if(r!==null||(r=this._getSlabThicknessHandleNearImagePoint(a,n,e,o),r!==null))return r}_unsubscribeToViewportNewVolumeSet(t){this._syncVolumeListenersWithToolGroup()}_subscribeToViewportNewVolumeSet(t){this._syncVolumeListenersWithToolGroup()}_autoPanViewportIfNecessary(t,n){const e=n.getViewport(t);if(ie(e))return;const{clientWidth:o,clientHeight:s}=Ka(e),a=e.worldToCanvas(this.toolCenter),r=this.configuration.autoPan.panSize,c=[a[0],a[1]];if(a[0]<0?c[0]=r:a[0]>o&&(c[0]=o-r),a[1]<0?c[1]=r:a[1]>s&&(c[1]=s-r),c[0]===a[0]&&c[1]===a[1])return;const l=e.canvasToWorld(c),d=[l[0]-this.toolCenter[0],l[1]-this.toolCenter[1],l[2]-this.toolCenter[2]],u=ht(e),{focalPoint:h,position:f}=u,g=[f[0]-d[0],f[1]-d[1],f[2]-d[2]],m=[h[0]-d[0],h[1]-d[1],h[2]-d[2]],p=this._ignoreFiredEvents;this._ignoreFiredEvents=!0;try{e.setCamera({focalPoint:m,position:g})}finally{this._ignoreFiredEvents=p}e.render()}setSlabThickness(t,n){if(ie(t))return;let e;const{filterActorUIDsToSetSlabThickness:o}=this.configuration;o&&o.length>0&&(e=o);let s=this.configuration.slabThicknessBlendMode;n===Cu.MINIMUM_SLAB_THICKNESS&&(s=Gn.COMPOSITE),t.setBlendMode(s,e,!1),t.setSlabThickness(n,e)}_isClockWise(t,n,e){return(n[0]-t[0])*(e[1]-t[1])-(n[1]-t[1])*(e[0]-t[0])>0}_applyDeltaShiftToSelectedViewportCameras(t,n,e){n.forEach(o=>{this._applyDeltaShiftToViewportCamera(t,o,e)})}_applyDeltaShiftToViewportCamera(t,n,e){const{data:o}=n,s=t.getViewport(o.viewportId),a=ht(s),r=a.viewPlaneNormal,c=Vt.dot(e,r),l=[...r];if(Vt.multiplyScalar(l,c),Math.abs(l[0])>.001||Math.abs(l[1])>.001||Math.abs(l[2])>.001){const d=[0,0,0],u=[0,0,0];Vt.add(a.focalPoint,l,d),Vt.add(a.position,l,u);const h=this._ignoreFiredEvents;this._ignoreFiredEvents=!0;try{ie(s)?yl(s,d):s.setCamera({focalPoint:d,position:u})}finally{this._ignoreFiredEvents=h}s.render()}}_getRotationHandleNearImagePoint(t,n,e,o){const s=Za(this.configuration),{data:a}=n,{rotationPoints:r}=a.handles;for(let c=0;c<r.length;c++){const l=r[c][0],d=r[c][1];if(!this._getReferenceLineControllable(d.id)||!(!s.enabled&&this._getReferenceLineDraggableRotatable(d.id)))continue;const f=t.worldToCanvas(l);if(_e(e,f)<o)return a.handles.activeOperation=Po.ROTATE,this.editData={annotation:n},l}return null}_getSlabThicknessHandleNearImagePoint(t,n,e,o){const s=Za(this.configuration),{data:a}=n,{slabThicknessPoints:r}=a.handles;for(let c=0;c<r.length;c++){const l=r[c][0],d=r[c][1];if(!this._getReferenceLineControllable(d.id)||!(!s.enabled&&this._getReferenceLineSlabThicknessControlsOn(d.id)))continue;const f=t.worldToCanvas(l);if(_e(e,f)<o)return a.handles.activeOperation=Po.SLAB,a.activeViewportIds=[d.id],this.editData={annotation:n},l}return null}_pointNearTool(t,n,e,o){const s=Za(this.configuration),a=N(t),{viewport:r}=a,{clientWidth:c,clientHeight:l}=Ka(r),d=Math.sqrt(c*c+l*l),{data:u}=n,{rotationPoints:h}=u.handles,{slabThicknessPoints:f}=u.handles,g=[];for(let m=0;m<h.length-1;++m){const p=h[m][1],v=this._getReferenceLineControllable(p.id),I=this._getReferenceLineDraggableRotatable(p.id);if(!v||!I&&!s.enabled)continue;const w={start:{x:h[m][2][0],y:h[m][2][1]},end:{x:h[m][3][0],y:h[m][3][1]}},C=Je([w.start.x,w.start.y],[w.end.x,w.end.y],[e[0],e[1]]),S={start:{x:h[m+1][2][0],y:h[m+1][2][1]},end:{x:h[m+1][3][0],y:h[m+1][3][1]}},b=Je([S.start.x,S.start.y],[S.end.x,S.end.y],[e[0],e[1]]);(C<=o||b<=o)&&(g.push(p.id),u.handles.activeOperation=Po.DRAG),m++}for(let m=0;m<f.length-1;++m){const p=f[m][1];if(g.find(L=>L===p.id))continue;const v=this._getReferenceLineControllable(p.id),I=!s.enabled&&this._getReferenceLineSlabThicknessControlsOn(p.id);if(!v||!I)continue;const w=f[m][2],C=f[m][3],S=It();Tn(S,w,C),Oi(S,S,.5);const b=It();pe(b,w,S),Ao(b,b);const _=It();Oi(_,b,d*.05);const y=It(),D=It();Tn(y,S,_),pe(D,S,_);const T={start:{x:y[0],y:y[1]},end:{x:w[0],y:w[1]}},P=Je([T.start.x,T.start.y],[T.end.x,T.end.y],[e[0],e[1]]),x={start:{x:D[0],y:D[1]},end:{x:C[0],y:C[1]}},M=Je([x.start.x,x.start.y],[x.end.x,x.end.y],[e[0],e[1]]);(P<=o||M<=o)&&(g.push(p.id),u.handles.activeOperation=null),m++}return u.activeViewportIds=[...g],this.editData={annotation:n},u.handles.activeOperation===Po.DRAG}}bS.minimalModeExamples=new Map([["Default",{enabled:!1,lineLengthInPx:40}],["Minimal 40px",{enabled:!0,lineLengthInPx:40}],["Minimal 80px",{enabled:!0,lineLengthInPx:80}]]);function Za(i){const t=i?.minimal;if(!t?.enabled)return{enabled:!1,lineLengthInPx:0};const n=typeof t.lineLengthInPx=="number"&&Number.isFinite(t.lineLengthInPx)?t.lineLengthInPx:40;return{enabled:!0,lineLengthInPx:Math.max(0,n)}}function Mp(i,t){const n=It();return Tn(n,i,t),Oi(n,n,.5),n}bS.toolName="Crosshairs";const Pl=new Map;function _S(i,t){return`${i.id}:${t}`}function Ap(i,t,n){const[e,o,s]=t,a=Ul.newInstance();a.setNumberOfPoints(6),a.setPoint(0,e-n,o,s),a.setPoint(1,e+n,o,s),a.setPoint(2,e,o-n,s),a.setPoint(3,e,o+n,s),a.setPoint(4,e,o,s-n),a.setPoint(5,e,o,s+n);const r=la.newInstance({values:[2,0,1,2,2,3,2,4,5]});i.setPoints(a),i.setLines(r),i.modified()}function yS(i){return typeof i?.getRenderer=="function"?i.getRenderer():void 0}function JV(i,t,n){const e=yS(i);if(!e||!t)return;const{lineLengthMm:o,color:s,uidPrefix:a}=n,r=Math.max(o/2,1),c=_S(i,a);let l=Pl.get(c);const d=l&&!!e.getActors?.().includes(l.actor);if(!l||!d){l&&e.removeActor(l.actor);const u=Vo.newInstance();Ap(u,t,r);const h=Oo.newInstance();h.setInputData(u);const f=vo.newInstance();f.setMapper(h),f.getProperty().setColor(...s),f.getProperty().setLineWidth(1.5),f.getProperty().setInterpolationToFlat(),f.getProperty().setAmbient(1),f.getProperty().setDiffuse(0),f.getProperty().setSpecular(0),e.addActor(f),e.resetCameraClippingRange?.(),l={actor:f,polyData:u},Pl.set(c,l)}else Ap(l.polyData,t,r);i.render()}function Lp(i,t){const n=_S(i,t),e=Pl.get(n);if(Pl.delete(n),!e)return;const o=yS(i);o&&(o.removeActor(e.actor),i.render())}const{ViewportType:Op}=Ea,QV=1e-4,t5=1e-6;function Rp(i){return Array.isArray(i)&&i.length===3&&i.every(t=>Number.isFinite(t))}function e5(i){if(typeof i=="string"){const t=i.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);if(t)return[Number(t[1])/255,Number(t[2])/255,Number(t[3])/255];const n=i.match(/^#([0-9a-f]{6})$/i);if(n){const e=parseInt(n[1],16);return[(e>>16&255)/255,(e>>8&255)/255,(e&255)/255]}}return[1,1,0]}class xS extends be{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{pointColor:"rgb(255, 255, 0)",pointRadius:4,markerStyle:"crosshair",centerGapRadius:12,offSliceDisplay:"projectedWithDistance",offSliceToleranceMm:.5,autoInitializeOnEnable:!0,clickToSet:!1,snapToSlabIntensity:!0,jumpOnSet:!0,jumpMode:"sliceOnly",preservePanZoom:!0,liveUpdateOnShiftMouseMove:!0,liveJumpOnShiftMouseMove:!0,showIn2D:!0,showIn3D:!0,threeDViewportIds:[],threeDLineLengthMm:100,linkPolicy:"frameOfReferenceUID",explicitLinkedViewportIds:[]}}){super(t,n),this._state={worldPoint:null,visible:!0,locked:!1,cursorWorldPoint:null},this._annotation=null,this._isDragging=!1,this._autoInitialized=!1,this.addNewAnnotation=e=>{const o=e.detail,{element:s,currentPoints:a}=o,r=N(s);if(!r||this._state.locked)return this._getAnnotationOrDetached();const c=o.event;if(!this.configuration.clickToSet&&!c?.shiftKey)return this._getAnnotationOrDetached();const{viewport:l,renderingEngine:d,FrameOfReferenceUID:u}=r;return this._isPlanarViewport(l)?(this.setWorldPoint(this._resolveInteractionWorldPoint(l,a.world),{sourceViewportId:l.id,sourceRenderingEngineId:d?.id,frameOfReferenceUID:u}),e.preventDefault(),wt(s),this._startDrag(s),this._getAnnotationOrDetached()):this._getAnnotationOrDetached()},this.toolSelectedCallback=(e,o)=>{const{element:s}=e.detail;this._state.locked||(o.highlighted=!0,wt(s),this._startDrag(s),e.preventDefault())},this.handleSelectedCallback=(e,o,s,a="Mouse")=>{this.toolSelectedCallback(e,o)},this.doubleClickCallback=e=>{const{element:o,currentPoints:s}=e.detail,a=N(o);if(!a||!this._state.worldPoint)return;const r=this._getMarkerCanvasPosition(a.viewport);!r||Math.hypot(r[0]-s.canvas[0],r[1]-s.canvas[1])>this.configuration.pointRadius+6||(this.jumpLinkedViewportsToWorldPoint(),e.preventDefault())},this.mouseMoveCallback=(e,o)=>{const{element:s,currentPoints:a}=e.detail,r=e.detail.event;let c=!1;if(this.configuration.liveUpdateOnShiftMouseMove&&r?.shiftKey&&!this._state.locked){const l=N(s),d=l?.viewport;d&&this._isPlanarViewport(d)&&(this._state.cursorWorldPoint=[a.world[0],a.world[1],a.world[2]],this.setWorldPoint(this._resolveInteractionWorldPoint(d,a.world),{sourceViewportId:d.id,sourceRenderingEngineId:l.renderingEngine?.id,frameOfReferenceUID:l.FrameOfReferenceUID,jump:this.configuration.liveJumpOnShiftMouseMove}),c=!0)}if(o?.length)for(const l of o){const d=this.isPointNearTool(s,l,a.canvas,6,"mouse");d!==!!l.highlighted&&(l.highlighted=d,c=!0)}return c},this.isPointNearTool=(e,o,s,a,r)=>{const c=N(e);if(!c)return!1;const l=this._getMarkerCanvasPosition(c.viewport);return l?Math.hypot(l[0]-s[0],l[1]-s[1])<=this.configuration.pointRadius+a:!1},this.filterInteractableAnnotationsForElement=(e,o)=>{if(!o?.length||!this._state.worldPoint)return[];const s=N(e);return!s||!this._getMarkerCanvasPosition(s.viewport)?[]:o.filter(a=>a.metadata.toolName===this.getToolName())},this.cancel=e=>{this._isDragging&&(this._isDragging=!1,this._deactivateModify(e),Ft(e))},this._dragCallback=e=>{const o=e.detail,{element:s,currentPoints:a}=o,r=N(s);if(!r||this._state.locked)return;const{viewport:c,renderingEngine:l,FrameOfReferenceUID:d}=r;this._isPlanarViewport(c)&&(this._state.cursorWorldPoint=[a.world[0],a.world[1],a.world[2]],this.setWorldPoint(this._resolveInteractionWorldPoint(c,a.world),{sourceViewportId:c.id,sourceRenderingEngineId:l?.id,frameOfReferenceUID:d}))},this._endCallback=e=>{const{element:o}=e.detail;this._isDragging=!1,this._deactivateModify(o),Ft(o),this._state.cursorWorldPoint=null,this._renderLinkedViewports()},this.renderAnnotation=(e,o)=>{this._maybeAutoInitialize(e);const{viewport:s}=e,{worldPoint:a,visible:r}=this._state,{showIn2D:c,pointColor:l,pointRadius:d,markerStyle:u,offSliceDisplay:h,offSliceToleranceMm:f}=this.configuration;if(!a||!r||!c||!this._isPlanarViewport(s)||!this._isViewportLinked(s))return!1;const g=Do(s);if(!g)return!1;const m=Ia(a,g),p=dh(a,g),v=s.worldToCanvas(p);if(!v||!v.every(_=>Number.isFinite(_)))return!1;const I=this._getEffectiveOffSliceTolerance(s,g,f),w=Math.abs(m)<=I;if(!w&&h==="hide")return!1;const C=this._annotation?.annotationUID??`WorldCrosshair-${this.toolGroupId}`,S=!!this._annotation?.highlighted,b={color:l,width:S?2:1,...w?{}:{lineDash:"3,3",strokeOpacity:.7}};if(u==="point")En(o,C,"marker",v,d,{...b,fill:w?l:"transparent"},`${C}-marker`);else{const{clientWidth:_,clientHeight:y}=Kf(s),D=Math.max(this.configuration.centerGapRadius??0,0),[T,P]=v;[["marker-h1",[0,P],[T-D,P]],["marker-h2",[T+D,P],[_,P]],["marker-v1",[T,0],[T,P-D]],["marker-v2",[T,P+D],[T,y]]].forEach(([M,L,R])=>{const U=Math.hypot(R[0]-L[0],R[1]-L[1]),W=R[0]>=L[0]&&R[1]>=L[1];U<1||!W||qt(o,C,M,L,R,b,`${C}-${M}`)})}if(!w&&h==="projectedWithDistance"){const y=`${m>=0?"+":"-"}${Math.abs(m).toFixed(1)} mm`;Ko(o,C,"marker-distance",[y],[v[0]+d+6,v[1]+d+6],{color:l})}return!0}}setWorldPoint(t,n={}){if(!Rp(t))return;const e=[t[0],t[1],t[2]],o=this._state.worldPoint,s=!o||ke(o,e)>QV;n.sourceViewportId!==void 0&&(this._state.sourceViewportId=n.sourceViewportId),n.sourceRenderingEngineId!==void 0&&(this._state.sourceRenderingEngineId=n.sourceRenderingEngineId);const a=n.frameOfReferenceUID!==void 0&&n.frameOfReferenceUID!==this._state.frameOfReferenceUID;n.frameOfReferenceUID!==void 0&&(this._state.frameOfReferenceUID=n.frameOfReferenceUID),s&&(this._state.worldPoint=e,this._autoInitialized=!0),(s||a)&&this._syncAnnotation(),s&&(n.suppressEvents||Rt(Z,E.WORLD_CROSSHAIR_POINT_CHANGED,this._getEventDetail())),(n.jump??this.configuration.jumpOnSet)&&this._jumpLinkedViewports({suppressEvents:!0}),s&&this._update3DLines(),this._renderLinkedViewports()}getWorldPoint(){const{worldPoint:t}=this._state;return t?[t[0],t[1],t[2]]:null}clearWorldPoint(t={}){this._state.worldPoint&&(this._state.worldPoint=null,this._state.cursorWorldPoint=null,this._syncAnnotation(),this._update3DLines(),t.suppressEvents||Rt(Z,E.WORLD_CROSSHAIR_POINT_CLEARED,this._getEventDetail()),this._renderLinkedViewports())}clearWorldCrosshair(t={}){this.clearWorldPoint(t)}jumpLinkedViewportsToWorldPoint(t={}){this._jumpLinkedViewports({...t,suppressEvents:!1})}setVisibility(t){this._state.visible!==t&&(this._state.visible=t,this._update3DLines(),this._renderLinkedViewports())}setLocked(t){this._state.locked=t}getState(){return{toolGroupId:this.toolGroupId,...this._state,worldPoint:this.getWorldPoint(),cursorWorldPoint:this._state.cursorWorldPoint?[...this._state.cursorWorldPoint]:null}}onSetToolEnabled(){this._syncAnnotation(),this._maybeAutoInitialize(),this._update3DLines(),this._renderLinkedViewports()}onSetToolActive(){this.onSetToolEnabled()}onSetToolPassive(){this.onSetToolEnabled()}onSetToolDisabled(){this._isDragging=!1,this._autoInitialized=!1,$.isInteractingWithTool=!1,this._annotation?.annotationUID&&Gt(this._annotation.annotationUID),this._annotation=null,this._get3DViewports().forEach(t=>Lp(t,this._getMarkerUIDPrefix())),this._renderLinkedViewports()}getHandleNearImagePoint(t,n,e,o){if(this.isPointNearTool(t,n,e,o,"mouse"))return this._state.worldPoint}_startDrag(t){this._isDragging=!0,this._activateModify(t)}_maybeAutoInitialize(t){if(this._autoInitialized||this._state.worldPoint||!this.configuration.autoInitializeOnEnable)return;let n=t?.viewport,e=t?.renderingEngine?.id,o=t?.FrameOfReferenceUID;if(!n)for(const a of this._getViewportsInfo()){const r=ae(a.viewportId,a.renderingEngineId);if(r&&this._isPlanarViewport(r.viewport)){n=r.viewport,e=r.renderingEngine?.id,o=r.FrameOfReferenceUID;break}}if(!n||!this._isPlanarViewport(n))return;let s;try{({focalPoint:s}=ht(n))}catch{return}Rp(s)&&this.setWorldPoint(s,{sourceViewportId:n.id,sourceRenderingEngineId:e,frameOfReferenceUID:o??n.getFrameOfReferenceUID?.(),jump:!1})}_jumpLinkedViewports(t={}){const{worldPoint:n}=this._state;if(!n)return;const e=t.jumpMode??this.configuration.jumpMode,o=$.isInteractingWithTool;$.isInteractingWithTool=!0;try{this._getLinkedViewports().forEach(s=>{this._jumpViewportToPoint(s,n,e)})}finally{$.isInteractingWithTool=o}t.suppressEvents||Rt(Z,E.WORLD_CROSSHAIR_JUMPED_TO_POINT,this._getEventDetail())}_jumpViewportToPoint(t,n,e){if(!this._isPlanarViewport(t))return;let o;try{o=ht(t)}catch{return}const{focalPoint:s,viewPlaneNormal:a}=o;if(!s||!a)return;const r=Oe(B(),n,s),c=xt(r,a);if(e==="centered"){if(!Rr(t,n))return;t.setViewState({anchorWorld:[n[0],n[1],n[2]],anchorCanvas:[.5,.5]}),t.render();return}if(Math.abs(c)<t5)return;const l=ee(B(),s,a,c);Rr(t,[l[0],l[1],l[2]])&&t.render()}_get3DViewports(){const{threeDViewportIds:t}=this.configuration;return t?.length?t.map(n=>le(n)?.viewport).filter(n=>n&&n.type===Op.VOLUME_3D_NEXT&&ie(n)):[]}_update3DLines(){const{showIn3D:t,threeDLineLengthMm:n,pointColor:e}=this.configuration,{worldPoint:o,visible:s}=this._state,a=this._getMarkerUIDPrefix();this._get3DViewports().forEach(r=>{t&&s&&o?JV(r,o,{lineLengthMm:n,color:e5(e),uidPrefix:a}):Lp(r,a)})}_getMarkerUIDPrefix(){return`WorldCrosshair-${this.toolGroupId}`}_isPlanarViewport(t){return t?.type===Op.PLANAR_NEXT&&ie(t)}_getViewportsInfo(){return Be(this.toolGroupId)?.viewportsInfo??[]}_getLinkedViewports(){const t=this._getViewportsInfo().map(({viewportId:a,renderingEngineId:r})=>ae(a,r)?.viewport).filter(a=>a&&this._isPlanarViewport(a)),{linkPolicy:n,explicitLinkedViewportIds:e}=this.configuration,{sourceViewportId:o,frameOfReferenceUID:s}=this._state;return n==="explicit"?t.filter(a=>a.id===o||e?.includes(a.id)):n==="frameOfReferenceUID"&&s?t.filter(a=>a.id===o||a.getFrameOfReferenceUID?.()===s):t}_isViewportLinked(t){if(!this._isPlanarViewport(t)||!this._getViewportsInfo().some(({viewportId:a})=>a===t.id))return!1;const{linkPolicy:n,explicitLinkedViewportIds:e}=this.configuration,{sourceViewportId:o,frameOfReferenceUID:s}=this._state;return t.id===o?!0:n==="explicit"?!!e?.includes(t.id):n==="frameOfReferenceUID"&&s?t.getFrameOfReferenceUID?.()===s:!0}_renderLinkedViewports(){const t=this._getLinkedViewports().map(n=>n.id);t.length&&V(t)}_getMarkerCanvasPosition(t){const{worldPoint:n,visible:e}=this._state,{showIn2D:o,offSliceDisplay:s,offSliceToleranceMm:a}=this.configuration;if(!n||!e||!o||!this._isPlanarViewport(t)||!this._isViewportLinked(t))return null;const r=Do(t);if(!r)return null;const c=Ia(n,r),l=this._getEffectiveOffSliceTolerance(t,r,a);if(Math.abs(c)>l&&s==="hide")return null;const d=dh(n,r),u=t.worldToCanvas(d);return!u||!u.every(h=>Number.isFinite(h))?null:u}_resolveInteractionWorldPoint(t,n){return this.configuration.snapToSlabIntensity?fS(t,n)??n:n}_getSourceSlabThicknessMm(t){if(!Sa(t))return 0;const n=t.getSourceDataId();if(!n)return 0;const o=t.getDisplaySetPresentation(n)?.slabThickness;return Number.isFinite(o)&&o>0?o:0}_getEffectiveOffSliceTolerance(t,n,e){const o=this._getSourceSlabThicknessMm(t),s=Math.max(e,o>0?o/2+.01:0);let a;try{a=t.getImageData?.()?.spacing}catch{a=void 0}if(!a||a.length!==3)return s;const[r,c,l]=n.normal,d=Math.abs(r)*a[0]+Math.abs(c)*a[1]+Math.abs(l)*a[2];return!Number.isFinite(d)||d<=0?s:Math.max(s,d/2+.01)}_syncAnnotation(){const{worldPoint:t,frameOfReferenceUID:n}=this._state;if(!t){this._annotation?.annotationUID&&Gt(this._annotation.annotationUID),this._annotation=null;return}if(this._annotation&&n&&this._annotation.metadata.FrameOfReferenceUID!==n&&(Gt(this._annotation.annotationUID),this._annotation=null),this._annotation){this._annotation.data.handles.points=[[t[0],t[1],t[2]]],this._annotation.invalidated=!0;return}if(!n)return;const e={highlighted:!1,invalidated:!0,metadata:{toolName:this.getToolName(),FrameOfReferenceUID:n},data:{handles:{points:[[t[0],t[1],t[2]]]}}};Nt(e,n),this._annotation=e}_getAnnotationOrDetached(){return this._annotation?this._annotation:{annotationUID:Se(),highlighted:!1,invalidated:!1,metadata:{toolName:this.getToolName()},data:{handles:{points:[]}}}}_getEventDetail(){const{sourceViewportId:t,sourceRenderingEngineId:n,frameOfReferenceUID:e}=this._state;return{toolGroupId:this.toolGroupId,worldPoint:this.getWorldPoint(),sourceViewportId:t,sourceRenderingEngineId:n,frameOfReferenceUID:e}}}xS.toolLabel="Reference Point";xS.toolName="WorldCrosshair";const{ViewportType:n5}=Ea,{RENDERING_DEFAULTS:Ja}=Qo,Rc=6,Qa=12,Np=.85,o5=50;class PS extends be{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{showCurrentSliceLine:!0,showSlabThickness:!0,showBoundaryLines:!1,showIntermediateLines:!1,draggable:!0,rotatable:!0,slabThicknessControls:!0,lineWidth:1,activeLineWidth:2.5,handleRadius:3,alignGroupsOnEnable:!0,rotationPivotPolicy:"currentIntersection",familyColors:{axial:"rgb(200, 60, 60)",sagittal:"rgb(220, 200, 60)",coronal:"rgb(60, 200, 60)"},setWorldCrosshairOnIntersectionDoubleClick:!1,jumpToIntersectionOnDoubleClick:!1,slabThicknessBlendMode:Gn.MAXIMUM_INTENSITY_BLEND,perViewportLines:!1}}){super(t,n),this._activeOperation=null,this._renderedLines=new Map,this._pendingHandle=null,this._editData=null,this._mprFamilyByViewportId=new Map,this._passViewportsById=null,this._passPlaneGroups=null,this._passCacheClearScheduled=!1,this.onCameraModified=e=>{const o=e.detail?.viewportId;if(!o){this._renderToolViewports();return}const s=new Set;for(const[a,r]of this._renderedLines){if(a===o){r.length&&s.add(a);continue}r.some(c=>c.leaderViewportId===o)&&s.add(a)}s.size&&V([...s])},this.renderAnnotation=(e,o)=>{const{viewport:s}=e,a=this._computeLinesForTarget(s);if(this._renderedLines.set(s.id,a),!a.length)return!1;const c=this._getOrCreateViewportAnnotation(s)?.annotationUID??`SliceIntersection-${s.id}`,{lineWidth:l,activeLineWidth:d,handleRadius:u,showCurrentSliceLine:h}=this.configuration;return a.forEach(f=>{const{groupId:g,canvasPoints:m,color:p,isActive:v}=f,I=v?d:l;h&&qt(o,c,`line-${g}`,m[0],m[1],{color:p,width:I},`${c}-line-${g}`),f.slabLineSegments.forEach((w,C)=>{qt(o,c,`slab-${g}-${C}`,w[0],w[1],{color:p,width:1,lineDash:"4,4",strokeOpacity:.8})}),f.boundaryLineSegments.forEach((w,C)=>{qt(o,c,`boundary-${g}-${C}`,w[0],w[1],{color:p,width:1,lineDash:"4,4",strokeOpacity:.8})}),f.rotateHandles.forEach((w,C)=>{En(o,c,`rotate-handle-${g}-${C}`,w,u,{color:p,fill:p})}),f.slabHandles.forEach((w,C)=>{En(o,c,`slab-handle-${g}-${C}`,w,u,{color:p,fill:"transparent"})})}),!0},this.addNewAnnotation=e=>{const{element:o}=e.detail,s=N(o);return s?this._getOrCreateViewportAnnotation(s.viewport)??this._createDetachedAnnotation():this._createDetachedAnnotation()},this.isPointNearTool=(e,o,s,a,r)=>{const c=N(e);return c?!!this._findLineNear(c.viewport.id,s,Rc,!0):!1},this.toolSelectedCallback=(e,o)=>{const{element:s,currentPoints:a}=e.detail,r=N(s);if(!r)return;const c=this._findLineNear(r.viewport.id,a.canvas,Rc);c&&(this._selectLine(c),this.configuration.draggable&&this._startManipulation(s,c,"translate"),e.preventDefault())},this.handleSelectedCallback=(e,o,s,a="Mouse")=>{const{element:r}=e.detail,c=this._pendingHandle;if(this._pendingHandle=null,!c)return;const{operation:l,lineInfo:d}=c;l==="rotate"&&!this.configuration.rotatable||l==="slabThickness"&&!this.configuration.slabThicknessControls||(this._selectLine(d),this._startManipulation(r,d,l),e.preventDefault())},this.doubleClickCallback=e=>{const{setWorldCrosshairOnIntersectionDoubleClick:o,jumpToIntersectionOnDoubleClick:s}=this.configuration;if(!o&&!s)return;const{element:a,currentPoints:r}=e.detail,c=N(a);if(!c)return;const{viewport:l}=c,d=this._findLineNear(l.id,r.canvas,Rc);if(!d)return;const u=this._closestPointOnLine(d.line,r.world);s&&this._centerViewportOnPoint(l,u),o&&Be(this.toolGroupId)?.getToolInstance?.("WorldCrosshair")?.setWorldPoint?.(u,{sourceViewportId:l.id,sourceRenderingEngineId:c.renderingEngine?.id,frameOfReferenceUID:c.FrameOfReferenceUID}),e.preventDefault()},this.mouseMoveCallback=(e,o)=>{const{element:s,currentPoints:a}=e.detail,r=N(s);if(!r)return!1;const{viewport:c}=r;if(!this._isPlanarViewport(c))return!1;const l=this._findLineNear(c.id,a.canvas,Rc,!0);let d=!1;return l?((this._activeGroupId!==l.groupId||this._activeTargetViewportId!==c.id)&&(this._activeGroupId=l.groupId,this._activeTargetViewportId=c.id,d=!0),d):(this._activeTargetViewportId===c.id&&(this._activeTargetViewportId=void 0,d=!0),d)},this.filterInteractableAnnotationsForElement=(e,o)=>{if(!o?.length)return[];const s=N(e);if(!s)return[];const{viewportId:a}=s;return o.filter(r=>r.data.viewportId===a)},this.cancel=e=>{this._editData&&this._endManipulation(e,{suppressEvents:!1})},this._endCallback=e=>{const{element:o}=e.detail;this._endManipulation(o)},this._dragCallback=e=>{const o=this._editData;if(!o)return;const s=o.memberViewportIds.map(a=>this._getViewportById(a)).filter(Boolean);if(s.length){switch(o.operation){case"translate":this._applyTranslate(s,e,o);break;case"rotate":this._applyRotate(s,e,o);break;case"slabThickness":this._applySlabThickness(s,e,o);break}this._renderToolViewports()}}}getState(){return{toolGroupId:this.toolGroupId,activeGroupId:this._activeGroupId,activeTargetViewportId:this._activeTargetViewportId,activeOperation:this._activeOperation}}getPlaneGroups(){return this._getPlaneGroups().map(t=>({...t,viewportIds:[...t.viewportIds]}))}refreshPlaneFamilies(){this._mprFamilyByViewportId.clear(),this._clearPassCaches(),this._renderToolViewports()}onSetToolEnabled(){this.configuration.alignGroupsOnEnable&&this._alignPlaneGroups(),this._renderToolViewports()}onSetToolActive(){this.onSetToolEnabled()}onSetToolPassive(){this.onSetToolEnabled()}onSetToolDisabled(){this._editData=null,this._pendingHandle=null,this._activeOperation=null,this._activeGroupId=void 0,this._activeTargetViewportId=void 0,$.isInteractingWithTool=!1,this._renderedLines.clear(),this._mprFamilyByViewportId.clear(),this._clearPassCaches(),this._getViewportsInfo().forEach(({viewportId:t,renderingEngineId:n})=>{const e=ae(t,n);if(!e)return;Yt(this.getToolName(),e.viewport.element)?.forEach(s=>{Gt(s.annotationUID)})})}_getMprFamily(t){const n=this._mprFamilyByViewportId.get(t.id);if(n)return n;const e=Do(t);if(!e)return null;const[o,s,a]=e.normal.map(Math.abs),r=a>=o&&a>=s?"axial":o>=s?"sagittal":"coronal";return this._mprFamilyByViewportId.set(t.id,r),r}_getPlaneGroups(){return this._passPlaneGroups||(this._passPlaneGroups=this._computePlaneGroups(),this._schedulePassCacheClear()),this._passPlaneGroups}_computePlaneGroups(){const t=this._getToolGroupViewports().filter(e=>this._isPlanarViewport(e));if(this.configuration.perViewportLines)return t.map(e=>{const o=this._getMprFamily(e),s=e.getFrameOfReferenceUID?.();return!o||!s?null:{id:e.id,family:o,frameOfReferenceUID:s,viewportIds:[e.id],leaderViewportId:e.id}}).filter(Boolean);const n=new Map;return t.forEach(e=>{const o=this._getMprFamily(e),s=e.getFrameOfReferenceUID?.();if(!o||!s)return;const a=`${s}:${o}`;let r=n.get(a);r||(r={id:a,family:o,frameOfReferenceUID:s,viewportIds:[],leaderViewportId:e.id},n.set(a,r)),r.viewportIds.push(e.id);const c=this._getViewportById(r.leaderViewportId);!this._isVolumeModeViewport(c)&&this._isVolumeModeViewport(e)&&(r.leaderViewportId=e.id)}),[...n.values()]}_alignPlaneGroups(){const t=$.isInteractingWithTool;$.isInteractingWithTool=!0;try{this._getPlaneGroups().forEach(n=>{if(n.viewportIds.length<2)return;const e=this._getViewportById(n.leaderViewportId),o=e&&Do(e);o&&n.viewportIds.forEach(s=>{if(s===n.leaderViewportId)return;const a=this._getViewportById(s);!a||!this._isPlanarViewport(a)||Rr(a,o.point)&&a.render()})})}finally{$.isInteractingWithTool=t}}_computeLinesForTarget(t){if(!t||!this._isPlanarViewport(t))return[];const n=Do(t);if(!n)return[];const e=t.getFrameOfReferenceUID?.();if(!e)return[];const o=[];return this._getPlaneGroups().forEach(s=>{if(s.frameOfReferenceUID!==e||s.viewportIds.includes(t.id))return;const a=this._computeLineForGroup(t,n,s);a&&o.push(a)}),o}_computeLineForGroup(t,n,e){const o=this._getViewportById(e.leaderViewportId);if(!o)return null;const s=Do(o);if(!s)return null;const a=lh(n,s);if(!a)return null;const r=uh(a,t);if(!r)return null;const{familyColors:c,getLineColor:l}=this.configuration,d=l?.(e.family,e.id,t.id)??c?.[e.family]??"rgb(0, 200, 200)",u=this._activeGroupId===e.id&&this._activeTargetViewportId===t.id,h={groupId:e.id,family:e.family,leaderViewportId:e.leaderViewportId,memberViewportIds:[...e.viewportIds],targetViewportId:t.id,line:a,leaderPlane:s,canvasPoints:r,slabLineSegments:[],boundaryLineSegments:[],rotateHandles:[],slabHandles:[],color:d,isActive:u};return this._appendSlabGeometry(h,t,n,o,s),this._appendBoundaryGeometry(h,t,n,o,s),u&&this._appendHandles(h,t,o),h}_clipOffsetPlaneIntersection(t,n,e,o){const s={normal:e.normal,point:[e.point[0]+e.normal[0]*o,e.point[1]+e.normal[1]*o,e.point[2]+e.normal[2]*o]},a=lh(n,s);return a?uh(a,t):null}_appendSlabGeometry(t,n,e,o,s){if(!this.configuration.showSlabThickness||!this._isVolumeModeViewport(o))return;const a=this._getSourceSlabThickness(o);!a||a<=Ja.MINIMUM_SLAB_THICKNESS||[a/2,-a/2].forEach(r=>{const c=this._clipOffsetPlaneIntersection(n,e,s,r);c&&t.slabLineSegments.push(c)})}_appendBoundaryGeometry(t,n,e,o,s){const{showBoundaryLines:a,showIntermediateLines:r}=this.configuration;if(!a&&!r)return;const c=this._getSourceExtentAlongNormal(o,s);if(!c)return;const{minOffset:l,maxOffset:d,spacing:u}=c,h=[];if(a&&h.push(l,d),r&&u>0){const f=d-l,g=Math.max(u,f/o5);for(let m=Math.ceil(l/g)*g;m<d;m+=g)Math.abs(m)>1e-6&&h.push(m)}h.forEach(f=>{const g=this._clipOffsetPlaneIntersection(n,e,s,f);g&&t.boundaryLineSegments.push(g)})}_getSourceExtentAlongNormal(t,n){let e;try{e=t.getImageData?.()}catch{return null}const o=e?.imageData?.getBounds?.();if(!o||o.length!==6)return null;const[s,a,r,c,l,d]=o,u=[[s,r,l],[a,r,l],[s,c,l],[a,c,l],[s,r,d],[a,r,d],[s,c,d],[a,c,d]];let h=1/0,f=-1/0;if(u.forEach(p=>{const v=Ia(p,n);h=Math.min(h,v),f=Math.max(f,v)}),!Number.isFinite(h)||!Number.isFinite(f))return null;const g=e?.spacing??[],m=Math.min(...g.filter(p=>Number.isFinite(p)&&p>0),1/0);return{minOffset:h,maxOffset:f,spacing:Number.isFinite(m)?m:0}}_appendHandles(t,n,e){const{rotatable:o,slabThicknessControls:s,showSlabThickness:a}=this.configuration,[r,c]=t.canvasPoints,l=this._isVolumeModeViewport(e);o&&l&&(t.rotateHandles=[.25,.75].map(d=>[r[0]+(c[0]-r[0])*d,r[1]+(c[1]-r[1])*d])),s&&a&&l&&(t.slabHandles=this._computeSlabHandles(t,n,e))}_computeSlabHandles(t,n,e){const[o,s]=t.canvasPoints,a=[o[0]+(s[0]-o[0])*Np,o[1]+(s[1]-o[1])*Np],r=this._getSourceSlabThickness(e),c=n.canvasToWorld(a),{normal:l}=t.leaderPlane,d=[c[0]+l[0]*(r/2),c[1]+l[1]*(r/2),c[2]+l[2]*(r/2)],u=n.worldToCanvas(d);if(Math.hypot(u[0]-a[0],u[1]-a[1])>=Qa){const m=[c[0]-l[0]*(r/2),c[1]-l[1]*(r/2),c[2]-l[2]*(r/2)];return[u,n.worldToCanvas(m)]}const f=Ao(It(),pe(It(),s,o)),g=[-f[1],f[0]];return[[a[0]+g[0]*Qa,a[1]+g[1]*Qa],[a[0]-g[0]*Qa,a[1]-g[1]*Qa]]}getHandleNearImagePoint(t,n,e,o){this._pendingHandle=null;const s=N(t);if(!s)return;const a=this._renderedLines.get(s.viewport.id)??[];for(const r of a){if(r.rotateHandles.some(d=>Math.hypot(d[0]-e[0],d[1]-e[1])<=this.configuration.handleRadius+o))return this._pendingHandle={operation:"rotate",lineInfo:r},r.line.point;if(r.slabHandles.some(d=>Math.hypot(d[0]-e[0],d[1]-e[1])<=this.configuration.handleRadius+o))return this._pendingHandle={operation:"slabThickness",lineInfo:r},r.line.point}}_startManipulation(t,n,e){const o=this._getViewportById(n.targetViewportId);if(this._editData={targetViewportId:n.targetViewportId,groupId:n.groupId,family:n.family,memberViewportIds:[...n.memberViewportIds],operation:e},e==="rotate"&&o){const s=Do(o);this._editData.rotationAxis=s?.normal,this._editData.pivotWorld=this._resolveRotationPivot(o,n)}this._activeOperation=e,wt(t),this._activateModify(t),Rt(Z,E.SLICE_INTERSECTION_MANIPULATION_STARTED,this._getManipulationDetail(e))}_endManipulation(t,{suppressEvents:n=!1}={}){const e=this._editData;this._deactivateModify(t),Ft(t),this._editData=null,this._activeOperation=null,e&&!n&&Rt(Z,E.SLICE_INTERSECTION_MANIPULATION_ENDED,this._getManipulationDetail(e.operation,e)),this._renderToolViewports()}_applyTranslate(t,n,e){const o=n.detail.startPoints?.world,s=n.detail.currentPoints?.world,a=n.detail.deltaPoints?.world,r=o&&s?Oe(B(),s,o):a;if(!r)return;const c=!!(o&&s),l=e?.memberStartPlanePoints??new Map;e&&(e.memberStartPlanePoints=l),t.forEach(d=>{const u=Do(d);if(!u)return;if(!c){const m=xt(r,u.normal);HE(d,m)&&d.render();return}let h=l.get(d.id);h||(h=[...u.point],l.set(d.id,h));const f=xt(r,u.normal),g=[h[0]+u.normal[0]*f,h[1]+u.normal[1]*f,h[2]+u.normal[2]*f];Rr(d,g)&&d.render()})}_applyRotate(t,n,e){const{pivotWorld:o,rotationAxis:s,targetViewportId:a}=e;if(!o||!s)return;const r=this._getViewportById(a);if(!r)return;const c=n.detail,l=c.currentPoints?.canvas,d=c.deltaPoints?.canvas;if(!l||!d)return;const u=r.worldToCanvas(o),h=[l[0]-d[0],l[1]-d[1]],f=pe(It(),h,u),g=pe(It(),l,u);if(ha(f)<1e-6||ha(g)<1e-6)return;let m=TI(f,g);if(!Number.isFinite(m)||m===0||(f[0]*g[1]-f[1]*g[0]>0&&(m*=-1),m=Math.round(m*100)/100,m===0))return;const v=Wt(B(),s);if(mn(v)<1e-10)return;const I=J_(qi(),m,v);I&&(e.memberStartScales??=new Map,t.forEach(w=>{if(!this._isVolumeModeViewport(w))return;const{viewPlaneNormal:C,viewUp:S}=ht(w);if(!C||!S)return;const b=w;e.memberStartScales.has(w.id)||e.memberStartScales.set(w.id,b.getScale?.()??null);const _=Ue(B(),C,I),y=Ue(B(),S,I);w.setViewReference({viewPlaneNormal:[_[0],_[1],_[2]],viewUp:[y[0],y[1],y[2]],cameraFocalPoint:[o[0],o[1],o[2]]});const D=e.memberStartScales.get(w.id);D&&b.setScale?.(D),w.render()}))}_applySlabThickness(t,n,e){const o=n.detail.currentPoints?.world;if(!o)return;const s=t.find(l=>this._isVolumeModeViewport(l)),a=s&&Do(s);if(!a)return;const r=Math.max(Ja.MINIMUM_SLAB_THICKNESS,Math.abs(Ia(o,a))*2);let c=!1;t.forEach(l=>{this._setViewportSlabThickness(l,r)&&(c=!0)}),c&&Rt(Z,E.SLICE_INTERSECTION_SLAB_THICKNESS_CHANGED,this._getManipulationDetail("slabThickness",e))}_setViewportSlabThickness(t,n){if(!this._isVolumeModeViewport(t))return!1;const e=this._getSourceDataId(t);if(!e)return!1;const o=this._getSourceSlabThickness(t);if(Math.abs(o-n)<1e-6)return!1;let s=this.configuration.slabThicknessBlendMode;return n<=Ja.MINIMUM_SLAB_THICKNESS&&(s=Gn.COMPOSITE),t.setDisplaySetPresentation(e,{slabThickness:n,blendMode:s}),t.render(),!0}_isPlanarViewport(t){return t?.type===n5.PLANAR_NEXT&&ie(t)}_isVolumeModeViewport(t){if(!t||!this._isPlanarViewport(t))return!1;try{return t.getCurrentMode?.()==="volume"}catch{return!1}}_getSourceDataId(t){if(Sa(t))return t.getSourceDataId()}_getSourceSlabThickness(t){const n=this._getSourceDataId(t);if(!n)return Ja.MINIMUM_SLAB_THICKNESS;const o=t.getDisplaySetPresentation(n)?.slabThickness;return Number.isFinite(o)&&o>0?o:Ja.MINIMUM_SLAB_THICKNESS}_resolveRotationPivot(t,n){const{rotationPivotPolicy:e}=this.configuration;if(e==="worldCrosshairPointIfAvailable"){const a=Be(this.toolGroupId)?.getToolInstance?.("WorldCrosshair")?.getWorldPoint?.();if(a)return a}if(e==="viewportCenter"){const{focalPoint:s}=ht(t);if(s)return s}const{focalPoint:o}=ht(t);return this._closestPointOnLine(n.line,o??n.line.point)}_closestPointOnLine(t,n){const e=Oe(B(),n,t.point),o=xt(e,t.direction);return[t.point[0]+t.direction[0]*o,t.point[1]+t.direction[1]*o,t.point[2]+t.direction[2]*o]}_centerViewportOnPoint(t,n){this._isPlanarViewport(t)&&(t.setViewState({anchorWorld:[n[0],n[1],n[2]],anchorCanvas:[.5,.5]}),t.render())}_selectLine(t){this._activeGroupId=t.groupId,this._activeTargetViewportId=t.targetViewportId,Rt(Z,E.SLICE_INTERSECTION_LINE_SELECTED,{toolGroupId:this.toolGroupId,groupId:t.groupId,targetViewportId:t.targetViewportId})}_findLineNear(t,n,e,o=!1){const s=this._renderedLines.get(t)??[],a=this.configuration.handleRadius+e;for(const r of s)if(Je(r.canvasPoints[0],r.canvasPoints[1],n)<=e||o&&[...r.rotateHandles,...r.slabHandles].some(d=>Math.hypot(d[0]-n[0],d[1]-n[1])<=a))return r;return null}_getViewportsInfo(){return Be(this.toolGroupId)?.viewportsInfo??[]}_getToolGroupViewports(){return this._getViewportsInfo().map(({viewportId:t,renderingEngineId:n})=>ae(t,n)?.viewport).filter(Boolean)}_getViewportById(t){if(t)return this._passViewportsById||(this._passViewportsById=new Map(this._getToolGroupViewports().map(n=>[n.id,n])),this._schedulePassCacheClear()),this._passViewportsById.get(t)}_clearPassCaches(){this._passViewportsById=null,this._passPlaneGroups=null}_schedulePassCacheClear(){this._passCacheClearScheduled||(this._passCacheClearScheduled=!0,queueMicrotask(()=>{this._passCacheClearScheduled=!1,this._clearPassCaches()}))}_renderToolViewports(){const t=this._getViewportsInfo().map(({viewportId:n})=>n);t.length&&V(t)}_getOrCreateViewportAnnotation(t){const{element:n}=t;if(!n)return null;const o=Yt(this.getToolName(),n)?.find(a=>a.data.viewportId===t.id);if(o)return o;const s={highlighted:!1,invalidated:!1,metadata:{toolName:this.getToolName(),FrameOfReferenceUID:t.getFrameOfReferenceUID?.()},data:{viewportId:t.id,handles:{points:[]}}};return Nt(s,n),s}_createDetachedAnnotation(){return{annotationUID:Se(),highlighted:!1,invalidated:!1,metadata:{toolName:this.getToolName()},data:{viewportId:"",handles:{points:[]}}}}_getManipulationDetail(t,n=this._editData){return{toolGroupId:this.toolGroupId,groupId:n?.groupId??this._activeGroupId??"",family:n?.family,viewportIds:n?.memberViewportIds??[],targetViewportId:n?.targetViewportId??this._activeTargetViewportId??"",operation:t}}}PS.toolLabel="Slice Intersections";PS.toolName="SliceIntersection";const Nc="magnify-viewport";class i5 extends Ee{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{magnifySize:10,magnifyWidth:250,magnifyHeight:250,touchOffset:40}}){super(t,n),this._hasBeenRemoved=!1,this.preMouseDownCallback=e=>{const o=e.detail,{element:s,currentPoints:a}=o,r=N(s),{viewport:c,renderingEngine:l}=r;if(!(c instanceof Pn)&&!ie(c))throw new Error("MagnifyTool only works on Stack or native planar viewports");const d=this._getReferencedImageId(c);if(!d)throw new Error("MagnifyTool: No referenced image id found, reconstructed planes not supported yet");const u=ft(s,this.getToolName()),h=e.type===E.TOUCH_START;return this.editData={referencedImageId:d,viewportIdsToRender:u,enabledElement:r,renderingEngine:l,currentPoints:a,isTouch:h},this._createMagnificationViewport(),this._activateDraw(s),wt(s),e.preventDefault(),V(u),!0},this.preTouchStartCallback=e=>{this.preMouseDownCallback(e)},this._positionMagnifyElement=(e,o,s)=>{const{magnifyWidth:a,magnifyHeight:r,touchOffset:c}=this.configuration;let l=o[0]-a/2,d=o[1]-r/2;if(this.editData?.isTouch){d=o[1]-r-(c??0);const u=Math.max(s.clientWidth-a,0),h=Math.max(s.clientHeight-r,0);l=Math.min(Math.max(l,0),u),d=Math.min(Math.max(d,0),h)}e.style.top=`${d}px`,e.style.left=`${l}px`},this._createMagnificationViewport=()=>{const{enabledElement:e,referencedImageId:o,viewportIdsToRender:s,renderingEngine:a,currentPoints:r}=this.editData,{viewport:c}=e,{element:l}=c,d=ie(c)?Nr(c):void 0,u=d?d.properties:c.getProperties(),{rotation:h,flipHorizontal:f,flipVertical:g}=d??c.getViewPresentation(),{canvas:m,world:p}=r;let v;if(v=l.querySelector(".magnifyTool"),v===null){const w=document.createElement("div");w.classList.add("magnifyTool"),w.style.display="block",w.style.width=`${this.configuration.magnifyWidth}px`,w.style.height=`${this.configuration.magnifyHeight}px`,w.style.position="absolute",v=w,l.querySelector(".viewport-element").appendChild(w);const S={viewportId:Nc,type:so.STACK,element:v};a.enableElement(S)}this._positionMagnifyElement(v,m,l);const I=a.getViewport(Nc);I.setStack([o]).then(()=>{if(this._hasBeenRemoved)return;I.setProperties(u),I.setViewPresentation({rotation:h,flipHorizontal:f,flipVertical:g});const{focalPoint:w,position:C,viewPlaneNormal:S}=I.getCamera();let b;if(ie(c)){const T=c.element,P=c.canvasToWorld([0,0]),x=c.canvasToWorld([0,1]);b=ke(P,x)*T.clientHeight/2}else({parallelScale:b}=c.getCamera());const _=Math.sqrt(Math.pow(w[0]-C[0],2)+Math.pow(w[1]-C[1],2)+Math.pow(w[2]-C[2],2)),y=[p[0],p[1],p[2]],D=[y[0]+_*S[0],y[1]+_*S[1],y[2]+_*S[2]];I.setCamera({parallelScale:b*(1/this.configuration.magnifySize),focalPoint:y,position:D}),I.render()}),v.style.display="block",V(s)},this._cancelCallback=e=>{e.preventDefault(),e.stopPropagation(),this._dragEndCallback(e)},this._dragCallback=e=>{const o=e.detail,{deltaPoints:s,element:a,currentPoints:r}=o,c=s.world,l=r.canvas,d=N(a),{renderingEngine:u}=d,h=u.getViewport(Nc),f=a.querySelector(".magnifyTool");if(!f)return;this._positionMagnifyElement(f,l,a);const{focalPoint:g,position:m}=h.getCamera(),p=[m[0]+c[0],m[1]+c[1],m[2]+c[2]],v=[g[0]+c[0],g[1]+c[1],g[2]+c[2]];h.setCamera({focalPoint:v,position:p}),h.render()},this._dragEndCallback=e=>{let{element:o}=e.detail;if(o===void 0){const{enabledElement:l}=this.editData,{viewport:d}=l;o=d.element}const s=N(o),{renderingEngine:a}=s;a.disableElement(Nc);const r=o.querySelector(".viewport-element"),c=r.querySelector(".magnifyTool");r.removeChild(c),this._deactivateDraw(o),Ft(o),this._hasBeenRemoved=!0},this._activateDraw=e=>{$.isInteractingWithTool=!0,this._hasBeenRemoved=!1,e.addEventListener(E.MOUSE_UP,this._dragEndCallback),e.addEventListener(E.MOUSE_DRAG,this._dragCallback),e.addEventListener(E.MOUSE_CLICK,this._dragEndCallback),e.addEventListener("contextmenu",this._cancelCallback),e.addEventListener(E.TOUCH_END,this._dragEndCallback),e.addEventListener(E.TOUCH_DRAG,this._dragCallback)},this._deactivateDraw=e=>{$.isInteractingWithTool=!1,e.removeEventListener(E.MOUSE_UP,this._dragEndCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragCallback),e.removeEventListener(E.MOUSE_CLICK,this._dragEndCallback),e.removeEventListener("contextmenu",this._cancelCallback),e.removeEventListener(E.TOUCH_END,this._dragEndCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragCallback)}}_getReferencedImageId(t){const n=this.getTargetId(t);let e;return t instanceof Pn?e=n.split("imageId:")[1]:ie(t)&&(e=Nr(t).currentImageId),e}}i5.toolName="Magnify";const s5="advancedMagnifyTool",a5=125,{Events:Ai}=Ea,kp=i=>!!i.representationUID;var Ih;(function(i){i.ShowZoomFactorsList="showZoomFactorsList"})(Ih||(Ih={}));const DS="AdvancedMagnify",r5=1-FC;class wa extends be{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{shadow:!0,magnifyingGlass:{radius:125,zoomFactor:3,zoomFactorList:[1.5,2,2.5,3,3.5,4,4.5,5],autoPan:{enabled:!0,padding:10}},actions:{showZoomFactorsList:{method:"showZoomFactorsList",bindings:[{mouseButton:Fo.Secondary,modifierKey:vn.Shift}]}}}}){super(t,n),this.addNewAnnotation=e=>{const o=e.detail,{currentPoints:s,element:a}=o,r=N(a),{viewport:c,renderingEngine:l}=r,d=s.world,u=s.canvas,{magnifyingGlass:h}=this.configuration,{radius:f,zoomFactor:g,autoPan:m}=h,p=this._getWorldHandlePoints(c,u,f),v=ie(c),{viewPlaneNormal:I,viewUp:w}=v?ht(c):c.getCamera(),C=v?Nr(c).currentImageId:this.getReferencedImageId(c,d,I,w),S=Se(),b=Se(),_=c.getFrameOfReferenceUID(),y={annotationUID:S,highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...I],viewUp:[...w],FrameOfReferenceUID:_,referencedImageId:C},data:{sourceViewportId:c.id,magnifyViewportId:b,zoomFactor:g,isCanvasAnnotation:!1,handles:{points:p,activeHandleIndex:null}}};this.magnifyViewportManager.createViewport(y,{magnifyViewportId:b,sourceEnabledElement:r,position:u,radius:f,zoomFactor:g,autoPan:{enabled:m.enabled,padding:m.padding,callback:T=>{const P=y.data.handles.points,{world:x}=T.delta;for(let M=0,L=P.length;M<L;M++){const R=P[M];R[0]+=x[0],R[1]+=x[1],R[2]+=x[2]}y.invalidated=!0}}}),Nt(y,a);const D=ft(a,this.getToolName());return e.preventDefault(),V(D),y},this.onSetToolDisabled=()=>{this.magnifyViewportManager.dispose(),Ca().forEach(o=>{o.metadata.toolName===this.getToolName()&&Gt(o.annotationUID)})},this.isPointNearTool=(e,o,s,a,r)=>{const{viewport:c}=N(e),{points:l}=o.data.handles,{radius:d,center:u}=this._getCanvasCircleData(c,l),h=ga([u,s]);return Math.abs(h-d)<a*2||r==="touch"&&h<d},this.toolSelectedCallback=(e,o)=>{const s=e.detail,{element:a}=s;o.highlighted=!0;const r=ft(a,this.getToolName());this.editData={annotation:o,viewportIdsToRender:r},wt(a),this._activateModify(a),V(r),e.preventDefault()},this.handleSelectedCallback=(e,o,s)=>{const a=e.detail,{element:r}=a,{data:c}=o;o.highlighted=!0;const{points:l}=c.handles,d=l.findIndex(h=>h===s),u=ft(r,this.getToolName());this.editData={annotation:o,viewportIdsToRender:u,handleIndex:d},this._activateModify(r),wt(r),V(u),e.preventDefault()},this._endCallback=e=>{const o=e.detail,{element:s}=o,{annotation:a,viewportIdsToRender:r,newAnnotation:c}=this.editData,{data:l}=a;l.handles.activeHandleIndex=null,this._deactivateModify(s),Ft(s),this.editData=null,this.isDrawing=!1,V(r),c&&ue(a)},this._dragDrawCallback=e=>{this.isDrawing=!0;const o=e.detail,{element:s}=o,{viewport:a}=N(s),{deltaPoints:r}=o,c=r?.canvas??[0,0,0],{annotation:l,viewportIdsToRender:d}=this.editData,{points:u}=l.data.handles,h=this._getWorldDeltaFromCanvasDelta(a,u,c);this._applyWorldDelta(u,h),l.invalidated=!0,this.editData.hasMoved=!0,V(d)},this._dragModifyCallback=e=>{this.isDrawing=!0;const o=e.detail,{element:s}=o,{annotation:a,viewportIdsToRender:r,handleIndex:c}=this.editData,{data:l}=a;if(c===void 0){const{deltaPoints:d}=o,u=d.canvas??[0,0,0],h=l.handles.points,f=this._getWorldDeltaFromCanvasDelta(N(s).viewport,h,u);this._applyWorldDelta(h,f),a.invalidated=!0}else this._dragHandle(e),a.invalidated=!0;V(r)},this._pressModifyCallback=e=>{const{element:o,startPoints:s}=e.detail,a=this.editData.annotation,r=wa.TOUCH_PROXIMITY;this.isPointNearTool(o,a,s.canvas,r)&&(e.stopImmediatePropagation(),this._endCallback(e),this.showZoomFactorsList(e,a))},this._dragHandle=e=>{const o=e.detail,{element:s}=o,{viewport:a}=N(s),{annotation:r}=this.editData,{data:c}=r,{points:l}=c.handles,{center:d}=this._getCanvasCircleData(a,l),{currentPoints:u}=o,h=u.canvas,f=ga([d,h]),m=this._getCanvasHandlePoints(d,f).map(p=>a.canvasToWorld(p));l[0]=m[0],l[1]=m[1],l[2]=m[2],l[3]=m[3]},this.cancel=e=>{if(!this.isDrawing)return;this.isDrawing=!1,this._deactivateModify(e),Ft(e);const{annotation:o,viewportIdsToRender:s,newAnnotation:a}=this.editData,{data:r}=o;return o.highlighted=!1,r.handles.activeHandleIndex=null,V(s),a&&ue(o),this.editData=null,o.annotationUID},this._activateModify=e=>{$.isInteractingWithTool=!0,e.addEventListener(E.MOUSE_UP,this._endCallback),e.addEventListener(E.MOUSE_DRAG,this._dragModifyCallback),e.addEventListener(E.MOUSE_CLICK,this._endCallback),e.addEventListener(E.TOUCH_END,this._endCallback),e.addEventListener(E.TOUCH_DRAG,this._dragModifyCallback),e.addEventListener(E.TOUCH_TAP,this._endCallback),e.addEventListener(E.TOUCH_PRESS,this._pressModifyCallback)},this._deactivateModify=e=>{$.isInteractingWithTool=!1,e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragModifyCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.TOUCH_END,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragModifyCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback),e.removeEventListener(E.TOUCH_PRESS,this._pressModifyCallback)},this.renderAnnotation=(e,o)=>{let s=!1;const{viewport:a}=e,{element:r}=a;let c=Yt(this.getToolName(),r);if(!c?.length)return s;c=c?.filter(u=>u.data.sourceViewportId===a.id);const l=this.filterInteractableAnnotationsForElement(r,c);if(!l?.length)return s;const d={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:e.viewport.id};for(let u=0;u<l.length;u++){const h=l[u],{annotationUID:f,data:g}=h,{magnifyViewportId:m,zoomFactor:p,handles:v}=g,{points:I,activeHandleIndex:w}=v,{center:C,radius:S,canvasPoints:b}=this._getCanvasCircleData(a,I);d.annotationUID=f,this.getStyle("lineWidth",d,h),this.getStyle("lineDash",d,h);const _=this.getStyle("color",d,h);if(!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),s;let y;if(!$e(f))continue;if(!ze(f)&&!this.editData&&w!==null){const x=b[w];y=[[x[0],x[1],0]]}y&&xe(o,f,"0",y,{color:_});const D=`${f}-advancedMagnify`;En(o,f,"0",C,S,{color:_,lineWidth:5},D);const P=this.magnifyViewportManager.getViewport(m);P.position=C,P.radius=S,P.zoomFactor=p,P.update(),s=!0}return s},this.touchPressCallback=e=>{const{element:o,startPoints:s}=e.detail,a=N(o);if(!a)return;const{viewport:r}=a,c=s.canvas,l=wa.TOUCH_PROXIMITY,u=(Yt(this.getToolName(),o)??[]).filter(h=>h.data.sourceViewportId===r.id).find(h=>$e(h.annotationUID)&&!ze(h.annotationUID)&&this.isPointNearTool(o,h,c,l));u&&this.showZoomFactorsList(e,u)},this._getWorldHandlePoints=(e,o,s)=>this._getCanvasHandlePoints(o,s).map(r=>e.canvasToWorld(r)),this._getCanvasCircleData=(e,o)=>{const s=o.map(u=>e.worldToCanvas(u)),a=s[0],r=s[2],c=s[3],l=Math.abs(r[1]-a[1])*.5,d=[c[0]+l,a[1]+l];return{canvasPoints:s,center:d,radius:l}},this._getCanvasHandlePoints=(e,o)=>[[e[0],e[1]-o,0],[e[0]+o,e[1],0],[e[0],e[1]+o,0],[e[0]-o,e[1],0]],this.magnifyViewportManager=Ys.getInstance()}showZoomFactorsList(t,n){const{element:e}=t.detail,o="currentPoints"in t.detail?t.detail.currentPoints:t.detail.startPoints,s=N(e),{viewport:a}=s,{canvas:r}=o,c=e.querySelector(":scope .viewport-element"),l=n.data.zoomFactor,d=()=>u.remove(),u=this._getZoomFactorsListDropdown(l,h=>{h!==void 0&&(n.data.zoomFactor=Number.parseFloat(h),n.invalidated=!0),d(),a.render()});Object.assign(u.style,{left:`${r[0]}px`,top:`${r[1]}px`}),c.appendChild(u),u.focus()}_getZoomFactorsListDropdown(t,n){const{zoomFactorList:e}=this.configuration.magnifyingGlass,o=document.createElement("select");o.size=5,Object.assign(o.style,{width:"50px",position:"absolute"}),["mousedown","mouseup","mousemove","click","touchstart","touchend","touchmove"].forEach(r=>{o.addEventListener(r,c=>c.stopPropagation())});let s=!1;const a=r=>{s||(s=!0,n(r))};return o.addEventListener("change",r=>{r.stopPropagation(),a(o.value)}),o.addEventListener("click",r=>{r.stopPropagation(),r.target?.tagName==="OPTION"&&a(o.value)}),o.addEventListener("blur",()=>a(o.value)),o.addEventListener("keydown",r=>{((r.keyCode??r.which===27)||r.key?.toLowerCase()==="escape")&&(r.stopPropagation(),a())}),e.forEach(r=>{const c=document.createElement("option");c.label=r,c.title=`Zoom factor ${r.toFixed(1)}`,c.value=r,c.defaultSelected=r===t,o.add(c)}),o}_getWorldDeltaFromCanvasDelta(t,n,e){if(!e)return[0,0,0];const o=n[0],s=t.worldToCanvas(o),a=t.canvasToWorld([s[0]+e[0],s[1]+e[1]]);return[a[0]-o[0],a[1]-o[1],a[2]-o[2]]}_applyWorldDelta(t,n){if(n)for(let e=0,o=t.length;e<o;e++){const s=t[e];s[0]+=n[0],s[1]+=n[1],s[2]+=n[2]}}}wa.Actions=Ih;class Ys{constructor(){this.createViewport=(t,n)=>{const{magnifyViewportId:e,sourceEnabledElement:o,position:s,radius:a,zoomFactor:r,autoPan:c}=n,{viewport:l}=o,{element:d}=l,u=new c5({magnifyViewportId:e,sourceEnabledElement:o,radius:a,position:s,zoomFactor:r,autoPan:c,annotation:t});return this._addSourceElementEventListener(d),this._magnifyViewportsMap.set(u.viewportId,{annotation:t,magnifyViewport:u,magnifyViewportInfo:n}),u},this._annotationRemovedCallback=t=>{const{annotation:n}=t.detail;n.metadata.toolName===DS&&this.destroyViewport(n.data.magnifyViewportId)},this._newStackImageCallback=t=>{const{viewportId:n,imageId:e}=t.detail,o=this._getMagnifyViewportsMapEntriesBySourceViewportId(n),{viewport:s}=le(n);s.stackActorReInitialized&&this._reset(n),o.forEach(({annotation:a})=>{a.metadata.referencedImageId=e,a.invalidated=!0})},this._newVolumeImageCallback=t=>{const{renderingEngineId:n,viewportId:e}=t.detail,s=Ne(n).getViewport(e),{viewPlaneNormal:a}=ie(s)?ht(s):s.getCamera();this._getMagnifyViewportsMapEntriesBySourceViewportId(e).forEach(({annotation:c})=>{const{viewPlaneNormal:l}=c.metadata;if(!(Math.abs(xt(l,a))>r5))return;const{handles:u}=c.data,h=s.canvasToWorld([0,0]),f=tn(B(),h,u.points[0]),g=xt(f,a),m=bn(B(),a,g);for(let p=0,v=u.points.length;p<v;p++){const I=u.points[p];I[0]+=m[0],I[1]+=m[1],I[2]+=m[2]}c.invalidated=!0})},this._magnifyViewportsMap=new Map,this._initialize()}static getInstance(){return Ys._singleton=Ys._singleton??new Ys,Ys._singleton}getViewport(t){return this._magnifyViewportsMap.get(t)?.magnifyViewport}dispose(){this._removeEventListeners(),this._destroyViewports()}destroyViewport(t){const n=this._magnifyViewportsMap.get(t);if(n){const{magnifyViewport:e}=n,{viewport:o}=e.sourceEnabledElement,{element:s}=o;this._removeSourceElementEventListener(s),e.dispose(),this._magnifyViewportsMap.delete(t)}}_destroyViewports(){Array.from(this._magnifyViewportsMap.keys()).forEach(n=>this.destroyViewport(n))}_getMagnifyViewportsMapEntriesBySourceViewportId(t){return Array.from(this._magnifyViewportsMap.values()).filter(({magnifyViewport:e})=>{const{viewport:o}=e.sourceEnabledElement;return o.id===t})}_reset(t){this._getMagnifyViewportsMapEntriesBySourceViewportId(t).forEach(({magnifyViewport:e,annotation:o,magnifyViewportInfo:s})=>{this.destroyViewport(e.viewportId);const a=le(t);this.createViewport(o,{...s,sourceEnabledElement:{...a}})})}_addEventListeners(){Z.addEventListener(E.ANNOTATION_REMOVED,this._annotationRemovedCallback)}_removeEventListeners(){Z.removeEventListener(E.ANNOTATION_REMOVED,this._annotationRemovedCallback)}_addSourceElementEventListener(t){t.addEventListener(Ai.STACK_NEW_IMAGE,this._newStackImageCallback);const n=o=>{const{viewportId:s}=o.detail;this._reset(s)};t.addEventListener(Ai.VIEWPORT_NEW_IMAGE_SET,n);const e=o=>{const{viewportId:s}=o.detail;this._reset(s)};t.addEventListener(Ai.VOLUME_VIEWPORT_NEW_VOLUME,e),t.addEventListener(Ai.VOLUME_NEW_IMAGE,this._newVolumeImageCallback),t.newStackHandler=n,t.newVolumeHandler=e}_removeSourceElementEventListener(t){t.removeEventListener(Ai.STACK_NEW_IMAGE,this._newStackImageCallback),t.removeEventListener(Ai.VOLUME_NEW_IMAGE,this._newVolumeImageCallback),t.removeEventListener(Ai.VIEWPORT_NEW_IMAGE_SET,t.newStackHandler),t.removeEventListener(Ai.VOLUME_VIEWPORT_NEW_VOLUME,t.newVolumeHandler),delete t.newStackHandler,delete t.newVolumeHandler}_initialize(){this._addEventListeners()}}class c5{constructor({magnifyViewportId:t,sourceEnabledElement:n,radius:e=a5,position:o=[0,0],zoomFactor:s,autoPan:a,annotation:r}){this._enabledElement=null,this._sourceToolGroup=null,this._magnifyToolGroup=null,this._isViewportReady=!1,this._radius=0,this._resized=!1,this._canAutoPan=!1,this._viewportId=t??Se(),this._sourceEnabledElement=n,this._autoPan=a,this._annotation=r,this.radius=e,this.position=o,this.zoomFactor=s,this.visible=!0,this._browserMouseDownCallback=this._browserMouseDownCallback.bind(this),this._browserMouseUpCallback=this._browserMouseUpCallback.bind(this),this._browserTouchStartCallback=this._browserTouchStartCallback.bind(this),this._browserTouchEndCallback=this._browserTouchEndCallback.bind(this),this._touchPressCallback=this._touchPressCallback.bind(this),this._handleToolModeChanged=this._handleToolModeChanged.bind(this),this._mouseDragCallback=this._mouseDragCallback.bind(this),this._resizeViewportAsync=Yr(this._resizeViewport.bind(this),1),this._initialize()}get sourceEnabledElement(){return this._sourceEnabledElement}get viewportId(){return this._viewportId}get radius(){return this._radius}set radius(t){Math.abs(this._radius-t)>1e-5&&(this._radius=t,this._resized=!0)}update(){const{radius:t,position:n,visible:e}=this,{viewport:o}=this._enabledElement,{element:s}=o,a=2*t,[r,c]=n;this._resized&&(this._resizeViewportAsync(),this._resized=!1),Object.assign(s.style,{display:e?"block":"hidden",width:`${a}px`,height:`${a}px`,left:`${-t}px`,top:`${-t}px`,transform:`translate(${r}px, ${c}px)`}),this._isViewportReady&&(this._syncViewports(),o.render())}dispose(){const{viewport:t}=this._enabledElement,{element:n}=t,e=t.getRenderingEngine();this._removeEventListeners(n),e.disableElement(t.id),n.parentNode&&n.parentNode.removeChild(n)}_handleToolModeChanged(t){const{_magnifyToolGroup:n}=this,{toolGroupId:e,toolName:o,mode:s,toolBindingsOptions:a}=t.detail;if(this._sourceToolGroup?.id===e)switch(s){case se.Active:n.setToolActive(o,a);break;case se.Passive:n.setToolPassive(o);break;case se.Enabled:n.setToolEnabled(o);break;case se.Disabled:n.setToolDisabled(o);break;default:throw new Error(`Unknow tool mode (${s})`)}}_inheritBorderRadius(t){const n=t.querySelector(".viewport-element"),e=t.querySelector(".cornerstone-canvas");n.style.borderRadius="inherit",e.style.borderRadius="inherit"}_createViewportNode(){const t=document.createElement("div"),{radius:n}=this,e=n*2;return t.classList.add(s5),Object.assign(t.style,{display:"block",width:`${e}px`,height:`${e}px`,position:"absolute",overflow:"hidden",borderRadius:"50%",boxSizing:"border-box",left:`${-n}px`,top:`${-n}px`,transform:"translate(-1000px, -1000px)"}),t}_convertZoomFactorToParallelScale(t,n,e){if(ie(t)){const a=t.element,r=a.clientWidth,c=a.clientHeight,l=t.canvasToWorld([0,0]),d=t.canvasToWorld([0,1]),h=ke(l,d)*c/2,f=n.canvas.offsetWidth/r;return h*(1/e)*f}const{parallelScale:o}=t.getCamera(),s=n.canvas.offsetWidth/t.canvas.offsetWidth;return o*(1/e)*s}_isStackViewport(t){return"setStack"in t}_isVolumeViewport(t){return"addVolumes"in t}_cloneToolGroups(t,n){const e=t.getActors(),o=`${n.id}-toolGroup`,s=Ae(t.id,t.renderingEngineId),a=s.clone(o,r=>{const c=s.getToolInstance(r);return c instanceof be&&!(c instanceof wa)});return a.addViewport(n.id,n.renderingEngineId),e.filter(kp).forEach(r=>{Oa(this.viewportId,[{segmentationId:r.referencedId,type:St.Labelmap}])}),{sourceToolGroup:s,magnifyToolGroup:a}}_cloneStack(t,n){const e=t.getImageIds();n.setStack(e).then(()=>{this._isViewportReady=!0,this.update()})}_cloneVolumes(t,n){const o=t.getActors().filter(s=>!kp(s)).map(s=>({volumeId:s.referencedId}));return n.setVolumes(o).then(()=>{this._isViewportReady=!0,this.update()}),n}_cloneViewport(t,n){const{viewportId:e}=this,o=t.getRenderingEngine(),{options:s}=t,a=ie(t),r={element:n,viewportId:e,type:a?so.STACK:t.type,defaultOptions:a?{}:{...s}};o.enableElement(r);const c=o.getViewport(e);a||this._isStackViewport(t)?this._cloneStack(t,c):this._isVolumeViewport(t)&&this._cloneVolumes(t,c),this._inheritBorderRadius(n);const l=this._cloneToolGroups(t,c);this._sourceToolGroup=l.sourceToolGroup,this._magnifyToolGroup=l.magnifyToolGroup}_cancelMouseEventCallback(t){t.stopPropagation(),t.preventDefault()}_browserMouseUpCallback(t){const{element:n}=this._enabledElement.viewport;document.removeEventListener("mouseup",this._browserMouseUpCallback),n.addEventListener("mouseup",this._cancelMouseEventCallback),n.addEventListener("mousemove",this._cancelMouseEventCallback)}_browserMouseDownCallback(t){const{element:n}=this._enabledElement.viewport;this._canAutoPan=!!t.target?.closest(".advancedMagnifyTool"),document.addEventListener("mouseup",this._browserMouseUpCallback),n.removeEventListener("mouseup",this._cancelMouseEventCallback),n.removeEventListener("mousemove",this._cancelMouseEventCallback)}_browserTouchEndCallback(t){if(t.touches?.length>0)return;const{element:n}=this._enabledElement.viewport;document.removeEventListener("touchend",this._browserTouchEndCallback),document.removeEventListener("touchcancel",this._browserTouchEndCallback),n.addEventListener("touchend",this._cancelMouseEventCallback,{passive:!1}),n.addEventListener("touchmove",this._cancelMouseEventCallback,{passive:!1})}_browserTouchStartCallback(t){const{element:n}=this._enabledElement.viewport;t.touches?.length===1&&(this._canAutoPan=!!t.target?.closest(".advancedMagnifyTool")),document.addEventListener("touchend",this._browserTouchEndCallback),document.addEventListener("touchcancel",this._browserTouchEndCallback),n.removeEventListener("touchend",this._cancelMouseEventCallback),n.removeEventListener("touchmove",this._cancelMouseEventCallback)}_mouseDragCallback(t){if(!$.isInteractingWithTool)return;const{_autoPan:n}=this;if(!n.enabled||!this._canAutoPan)return;const{currentPoints:e}=t.detail,{viewport:o}=this._enabledElement,{canvasToWorld:s}=o,{canvas:a}=e,{radius:r}=this,c=[r,r],l=ro(c,a),d=r-n.padding;if(l<=d)return;const u=l-d,h=No(It(),a,c);Ao(h,h),Oi(h,h,u);const f=Tn(It(),this.position,h),g=s(this.position),m=s(f),p=tn(B(),m,g),v={points:{currentPosition:{canvas:this.position,world:g},newPosition:{canvas:f,world:m}},delta:{canvas:h,world:p}};n.callback(v)}_touchPressCallback(t){if($.isInteractingWithTool)return;const n=this._sourceToolGroup?.getToolInstance(DS);if(!n||!this._annotation)return;const{viewport:e}=this._sourceEnabledElement,o=t.detail.startPoints.canvas,s=[o[0]+this.position[0]-this.radius,o[1]+this.position[1]-this.radius];n.showZoomFactorsList({detail:{element:e.element,startPoints:{canvas:s}}},this._annotation)}_addBrowserEventListeners(t){document.addEventListener("mousedown",this._browserMouseDownCallback,!0),t.addEventListener("mousedown",this._cancelMouseEventCallback),t.addEventListener("mouseup",this._cancelMouseEventCallback),t.addEventListener("mousemove",this._cancelMouseEventCallback),t.addEventListener("dblclick",this._cancelMouseEventCallback),document.addEventListener("touchstart",this._browserTouchStartCallback,!0),t.addEventListener("touchstart",this._cancelMouseEventCallback,{passive:!1}),t.addEventListener("touchend",this._cancelMouseEventCallback,{passive:!1}),t.addEventListener("touchmove",this._cancelMouseEventCallback,{passive:!1})}_removeBrowserEventListeners(t){document.removeEventListener("mousedown",this._browserMouseDownCallback,!0),document.removeEventListener("mouseup",this._browserMouseUpCallback),t.removeEventListener("mousedown",this._cancelMouseEventCallback),t.removeEventListener("mouseup",this._cancelMouseEventCallback),t.removeEventListener("mousemove",this._cancelMouseEventCallback),t.removeEventListener("dblclick",this._cancelMouseEventCallback),document.removeEventListener("touchstart",this._browserTouchStartCallback,!0),document.removeEventListener("touchend",this._browserTouchEndCallback),document.removeEventListener("touchcancel",this._browserTouchEndCallback),t.removeEventListener("touchstart",this._cancelMouseEventCallback),t.removeEventListener("touchend",this._cancelMouseEventCallback),t.removeEventListener("touchmove",this._cancelMouseEventCallback)}_addEventListeners(t){Z.addEventListener(E.TOOL_MODE_CHANGED,this._handleToolModeChanged),t.addEventListener(E.MOUSE_MOVE,this._mouseDragCallback),t.addEventListener(E.MOUSE_DRAG,this._mouseDragCallback),t.addEventListener(E.TOUCH_DRAG,this._mouseDragCallback),t.addEventListener(E.TOUCH_PRESS,this._touchPressCallback),this._addBrowserEventListeners(t)}_removeEventListeners(t){Z.removeEventListener(E.TOOL_MODE_CHANGED,this._handleToolModeChanged),t.addEventListener(E.MOUSE_MOVE,this._mouseDragCallback),t.addEventListener(E.MOUSE_DRAG,this._mouseDragCallback),t.removeEventListener(E.TOUCH_DRAG,this._mouseDragCallback),t.removeEventListener(E.TOUCH_PRESS,this._touchPressCallback),this._removeBrowserEventListeners(t)}_initialize(){const{_sourceEnabledElement:t}=this,{viewport:n}=t,{canvas:e}=n,o=this._createViewportNode();e.parentNode.appendChild(o),this._addEventListeners(o),this._cloneViewport(n,o),this._enabledElement=N(o)}_syncViewportsCameras(t,n){const e=t.canvasToWorld(this.position),o=this._convertZoomFactorToParallelScale(t,n,this.zoomFactor),s=ie(t)?Nr(t):void 0,{flipHorizontal:a,flipVertical:r}=s??t.getCamera(),{focalPoint:c,position:l,viewPlaneNormal:d}=n.getCamera(),u=Math.sqrt(Math.pow(c[0]-l[0],2)+Math.pow(c[1]-l[1],2)+Math.pow(c[2]-l[2],2)),h=[e[0],e[1],e[2]],f=[h[0]+u*d[0],h[1]+u*d[1],h[2]+u*d[2]];n.setCamera({parallelScale:o,focalPoint:h,position:f,flipHorizontal:a,flipVertical:r})}_syncStackViewports(t,n){n.setImageIdIndex(t.getCurrentImageIdIndex())}_syncViewports(){const{viewport:t}=this._sourceEnabledElement,{viewport:n}=this._enabledElement,e=ie(t),o=e?Nr(t).properties:t.getProperties();n.getImageData()&&(n.setProperties(o),this._syncViewportsCameras(t,n),(e||this._isStackViewport(t))&&this._syncStackViewports(t,n),this._syncViewportsCameras(t,n),n.render())}_resizeViewport(){const{viewport:t}=this._enabledElement;t.getRenderingEngine().resize()}}wa.toolName="AdvancedMagnify";const{EPSILON:bu}=Qo;class l5 extends Ci{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{sourceViewportId:"",enforceSameFrameOfReference:!0,showFullDimension:!1}}){super(t,n),this.editData=null,this._init=()=>{const o=Vi()[0];if(!o)return;let s=o.getViewports();s=od(s,this.getToolName());const a=o.getViewport(this.configuration.sourceViewportId);if(!a?.getImageData?.())return;const{element:r}=a,{viewUp:c,viewPlaneNormal:l}=ht(a),d=Vu(a);let u=this.editData?.annotation;const h=a.getFrameOfReferenceUID();if(u)this.editData.annotation.data.handles.points=d;else{const f={highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...l],viewUp:[...c],FrameOfReferenceUID:h,referencedImageId:null},data:{handles:{points:d}}};Nt(f,r),u=f}this.editData={sourceViewportId:a.id,renderingEngine:o,annotation:u},V(s.filter(f=>f.id!==a.id).map(f=>f.id))},this.onSetToolEnabled=()=>{this._init()},this.onSetToolConfiguration=()=>{this._init()},this.onCameraModified=e=>{this._init()},this.renderAnnotation=(e,o)=>{const{viewport:s}=e;if(!this.editData)return!1;const{annotation:a,sourceViewportId:r}=this.editData;let c=!1;const{viewport:l}=le(r)||{};if(!l||l.id===s.id||!a||!a?.data?.handles?.points||this.configuration.enforceSameFrameOfReference&&l.getFrameOfReferenceUID()!==s.getFrameOfReferenceUID())return c;const d={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:e.viewport.id},u=a.data.handles.points[0],h=a.data.handles.points[1],f=a.data.handles.points[2],g=a.data.handles.points[3],{focalPoint:m,viewPlaneNormal:p,viewUp:v}=ht(s),{viewPlaneNormal:I}=ht(l);if(this.isParallel(p,I))return c;const w=$o(p,m),C=[u,f,h,g],S=[u,h,f,g];let b=C,_=Oe(B(),C[0],C[1]);_=Wt(B(),_);let y=Oe(B(),C[2],C[0]);y=Wt(B(),y);const D=Me(B(),_,y);if(this.isParallel(D,p))return c;this.isPerpendicular(_,p)&&(b=S);const T=Zc(b[0],b[1],w),P=Zc(b[2],b[3],w),{annotationUID:x}=a;d.annotationUID=x;const M=this.getStyle("lineWidth",d,a),L=this.getStyle("lineDash",d,a),R=this.getStyle("color",d,a),U=this.getStyle("shadow",d,a);let W=[T,P].map(F=>s.worldToCanvas(F));if(this.configuration.showFullDimension&&(W=this.handleFullDimension(s,T,p,v,P,W)),W.length<2)return c;const K=`${x}-line`;return qt(o,x,"1",W[0],W[1],{color:R,width:M,lineDash:L,shadow:U},K),c=!0,c},this.isPerpendicular=(e,o)=>{const s=xt(e,o);return Math.abs(s)<bu}}handleFullDimension(t,n,e,o,s,a){t.getRenderingEngine();const r=this.getTargetId(t),c=this.getTargetImageData(r),l=this.getReferencedImageId(t,n,e,o);if(l&&c)try{const{imageData:d,dimensions:u}=c,[h,f,g,m]=[d.indexToWorld([0,0,0]),d.indexToWorld([u[0]-1,0,0]),d.indexToWorld([u[0]-1,u[1]-1,0]),d.indexToWorld([0,u[1]-1,0])].map(I=>Sg(l,I)),[p,v]=[n,s].map(I=>Sg(l,I));a=[[h,f],[f,g],[m,g],[h,m]].map(([I,w])=>this.intersectInfiniteLines(I,w,p,v)).filter(I=>I&&this.isInBound(I,u)).map(I=>{const w=GC(l,I);return t.worldToCanvas(w)})}catch(d){console.log(d)}return a}intersectInfiniteLines(t,n,e,o){const[s,a]=t,[r,c]=n,[l,d]=e,[u,h]=o,f=c-a,g=s-r,m=r*a-s*c,p=h-d,v=l-u,I=u*d-l*h;if(Math.abs(f*v-p*g)<bu)return;const w=(g*I-v*m)/(f*v-p*g),C=(p*m-f*I)/(f*v-p*g);return[w,C]}isParallel(t,n){return Math.abs(xt(t,n))>1-bu}isInBound(t,n){return t[0]>=0&&t[0]<=n[0]&&t[1]>=0&&t[1]<=n[1]}}l5.toolName="ReferenceLines";const{EPSILON:Up}=Qo;class d5 extends Ci{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{sourceImageIds:[]}}){super(t,n),this.onSetToolEnabled=()=>{this._init()},this.onSetToolActive=()=>{this._init()},this._init=()=>{const e=this.configuration.sourceImageIds;if(!e?.length){console.warn("OverlayGridTool: No sourceImageIds provided in configuration");return}const o=rn("imagePlaneModule",e[0]);if(!o){console.warn("OverlayGridTool: No imagePlaneModule found for sourceImageIds");return}const{frameOfReferenceUID:s}=o,a=Be(this.toolGroupId).viewportsInfo;if(!a?.length){console.warn("OverlayGridTool: No viewports found");return}if(!Yt(this.getToolName(),s)?.length){const c=e.map(d=>this.calculateImageIdPointSets(d)),l={highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),FrameOfReferenceUID:s,referencedImageId:null},data:{viewportData:new Map,pointSets:c}};Nt(l,s)}V(a.map(({viewportId:c})=>c))},this.calculateImageIdPointSets=e=>{const{imagePositionPatient:o,rows:s,columns:a,rowCosines:r,columnCosines:c,rowPixelSpacing:l,columnPixelSpacing:d}=rn("imagePlaneModule",e),u=[...o],h=[...o],f=[...o],g=[...o];return ee(h,o,c,a*d),ee(f,o,r,s*l),ee(g,f,c,a*d),{pointSet1:[u,f,h,g],pointSet2:[u,h,f,g]}},this.renderAnnotation=(e,o)=>{const s=this.configuration.sourceImageIds;let a=!1;if(!s?.length)return a;const{viewport:r,FrameOfReferenceUID:c}=e;if(r.getImageIds().length<2)return a;const d=Yt(this.getToolName(),c);if(!d?.length)return a;const u=d[0],{annotationUID:h}=u,{focalPoint:f,viewPlaneNormal:g}=ht(r),m={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:e.viewport.id},p=this.getImageIdNormal(s[0]);if(this.isParallel(g,p))return a;const v=$o(g,f),I=u.data.pointSets,w=u.data.viewportData;for(let C=0;C<s.length;C++){const{pointSet1:S,pointSet2:b}=I[C],_=w.get(r.id)||this.initializeViewportData(w,r.id);if(!_.pointSetsToUse[C]){let W=S,K=Oe(B(),S[0],S[1]);K=Wt(B(),K),this.isPerpendicular(K,g)&&(W=b),_.pointSetsToUse[C]=W,_.lineStartsWorld[C]=Zc(W[0],W[1],v),_.lineEndsWorld[C]=Zc(W[2],W[3],v)}const y=_.lineStartsWorld[C],D=_.lineEndsWorld[C];m.annotationUID=h;const T=this.getStyle("lineWidth",m,u),P=this.getStyle("lineDash",m,u),x=this.getStyle("color",m,u),M=this.getStyle("shadow",m,u),L=[y,D].map(W=>r.worldToCanvas(W)),R=`${h}-line`,U=`${C}`;qt(o,h,U,L[0],L[1],{color:x,width:T,lineDash:P,shadow:M},R)}return a=!0,a},this.initializeViewportData=(e,o)=>(e.set(o,{pointSetsToUse:[],lineStartsWorld:[],lineEndsWorld:[]}),e.get(o)),this.isPerpendicular=(e,o)=>{const s=xt(e,o);return Math.abs(s)<Up}}isParallel(t,n){return Math.abs(xt(t,n))>1-Up}getImageIdNormal(t){const{imageOrientationPatient:n}=rn("imagePlaneModule",t),e=Ot(n[0],n[1],n[2]),o=Ot(n[3],n[4],n[5]);return Me(B(),e,o)}}d5.toolName="OverlayGrid";class u5 extends Ci{constructor(t={},n={configuration:{opacity:.5}}){super(t,n),this._init=()=>{const e=Be(this.toolGroupId).viewportsInfo;if(!e?.length){console.warn(this.getToolName()+"Tool: No viewports found");return}const o=Ne(e[0].renderingEngineId)?.getViewport(e[0].viewportId);if(!o)return;const s=o.getFrameOfReferenceUID();if(!Yt(this.getToolName(),s)?.length){const r=new Map;h5(r,e);const c={highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),FrameOfReferenceUID:s,referencedImageId:null},data:{actorsWorldPointsMap:r}};Nt(c,s)}V(e.map(({viewportId:r})=>r))},this.onSetToolEnabled=()=>{this._init()},this.onCameraModified=e=>{this._init()},this.renderAnnotation=(e,o)=>{const{viewport:s,FrameOfReferenceUID:a}=e;let r=!1;const c=Yt(this.getToolName(),a);if(!c?.length)return r;const l=c[0],{annotationUID:d}=l,u=l.data.actorsWorldPointsMap;TS(u,s);const h=s.getActors(),f=MS(s);return h.forEach(g=>{if(!g?.clippingFilter)return;const m=u.get(g.uid);if(!m||!m.get(f))return;let p=1;const{worldPointsSet:v,color:I}=m.get(f);for(let w=0;w<v.length;w++){const S=v[w].map(y=>s.worldToCanvas(y)),b={color:I,fillColor:I,fillOpacity:this.configuration.opacity,closePath:!0,lineWidth:2},_=g.uid+"#"+p;ko(o,d,_,S,b),p++}}),r=!0,r}}}function h5(i,t){t.forEach(({viewportId:n,renderingEngineId:e})=>{const o=Ne(e)?.getViewport(n);TS(i,o)})}function TS(i,t){const n=t.getActors(),e=MS(t);n.forEach(o=>{if(!o?.clippingFilter)return;let s=i.get(o.uid);if(s||(s=new Map,i.set(o.uid,s)),!s.get(e)){const a=o.clippingFilter.getOutputData(),r=oS(a);if(!r)return;const c=o.actor.getProperty().getColor(),l=f5(c);s.set(e,{worldPointsSet:r,color:l})}})}function MS(i){const{viewPlaneNormal:t}=i.getCamera(),n=i.getCurrentImageIdIndex();return`${i.id}-${J1(t)}-${n}`}function f5(i){function t(n){let e=Math.floor(n*255).toString(16);return e.length===1&&(e="0"+e),e}return"#"+t(i[0])+t(i[1])+t(i[2])}u5.toolName="SegmentationIntersection";class g5 extends Ci{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{shadow:!0,preventHandleOutsideImage:!1,displayThreshold:5,positionSync:!0,disableCursor:!1}}){super(t,n),this.isDrawing=!1,this.isHandleOutsideImage=!1,this._elementWithCursor=null,this._currentCursorWorldPosition=null,this._currentCanvasPosition=null,this._disableCursorEnabled=!1,this.mouseMoveCallback=e=>{const{detail:o}=e,{element:s,currentPoints:a}=o;this._currentCursorWorldPosition=a.world,this._currentCanvasPosition=a.canvas,this._elementWithCursor=s;const r=this.getActiveAnnotation(s);return r===null?(this.createInitialAnnotation(a.world,s),!1):(this.updateAnnotationPosition(s,r),!1)},this.createInitialAnnotation=(e,o)=>{const s=N(o);if(!s)throw new Error("No enabled element found");const{viewport:a,renderingEngine:r}=s;this.isDrawing=!0;const c=ht(a),{viewPlaneNormal:l,viewUp:d}=c;if(!l||!d)throw new Error("Camera not found");const u=this.getReferencedImageId(a,e,l,d),h=a.getFrameOfReferenceUID(),f={highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...l],viewUp:[...d],FrameOfReferenceUID:h,referencedImageId:u},data:{label:"",handles:{points:[[...e]],activeHandleIndex:null,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}}}};if(Yt(this.getToolName(),o).length>0)return null;if(Nt(f,o)===null)return;const p=ft(o,this.getToolName(),!1);V(p)},this.onCameraModified=e=>{const o=e.detail,{previousCamera:s,camera:a}=o,r=o.element||e.currentTarget||e.target;if(!r||!s)return;const l=N(r).viewport;if(r!==this._elementWithCursor)return;const d=s.focalPoint,u=a.viewPlaneNormal,h=a.focalPoint,f=[0,0,0];if(Vt.subtract(h,d,f),f.reduce((p,v)=>p+v,0)===0)return;const g=Vt.dot(f,u);if(Math.abs(g)<.01||!this._currentCanvasPosition)return;const m=l.canvasToWorld(this._currentCanvasPosition);this._currentCursorWorldPosition=m,this.updateAnnotationPosition(r,this.getActiveAnnotation(r))},this.renderAnnotation=(e,o)=>{let s=!1;const{viewport:a,FrameOfReferenceUID:r}=e,c=this._elementWithCursor===a.element;this.configuration.positionSync&&!c&&this.updateViewportImage(a);const{element:l}=a;let d=Yt(this.getToolName(),l);if(!d?.length||(d=this.filterInteractableAnnotationsForElement(l,d),!d?.length))return s;const u={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:e.viewport.id};for(let h=0;h<d.length;h++){const f=d[h],{annotationUID:g,data:m}=f,{handles:p}=m,{points:v}=p;if(!g)return s;u.annotationUID=g;const I=parseFloat(this.getStyle("lineWidth",u,f)),w=I,C=this.getStyle("lineDash",u,f),S=this.getStyle("color",u,f);if(v[0].some(x=>isNaN(x)))return s;const b=v.map(x=>a.worldToCanvas(x));if(!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),s;if(!$e(g))continue;const _={upper:"upper",right:"right",lower:"lower",left:"left"},[y,D]=b[0],T=c?20:7,P=c?5:7;qt(o,g,_.upper,[y,D-(T/2+P)],[y,D-T/2],{color:S,lineDash:C,lineWidth:w}),qt(o,g,_.lower,[y,D+(T/2+P)],[y,D+T/2],{color:S,lineDash:C,lineWidth:w}),qt(o,g,_.right,[y+(T/2+P),D],[y+T/2,D],{color:S,lineDash:C,lineWidth:w}),qt(o,g,_.left,[y-(T/2+P),D],[y-T/2,D],{color:S,lineDash:C,lineWidth:w}),s=!0}return s},this._disableCursorEnabled=this.configuration.disableCursor}onSetToolActive(){if(this._disableCursorEnabled=this.configuration.disableCursor,!this._disableCursorEnabled)return;const t=Be(this.toolGroupId).viewportsInfo;if(!t)return;t.map(e=>ae(e.viewportId,e.renderingEngineId)).forEach(e=>{e&&wt(e.viewport.element)})}onSetToolDisabled(){if(!this._disableCursorEnabled)return;const t=Be(this.toolGroupId).viewportsInfo;if(!t)return;t.map(e=>ae(e.viewportId,e.renderingEngineId)).forEach(e=>{e&&Ft(e.viewport.element)})}getActiveAnnotation(t){const n=Yt(this.getToolName(),t);return n.length?n[0]:null}updateAnnotationPosition(t,n){const e=this._currentCursorWorldPosition;if(!e||!n.data?.handles?.points)return;n.data.handles.points=[[...e]],n.invalidated=!0;const o=ft(t,this.getToolName(),!1);N(t)&&V(o)}filterInteractableAnnotationsForElement(t,n){if(!(n instanceof Array)||n.length===0)return[];const e=n[0],o=N(t)?.viewport;if(!o)return[];const s=ht(o),{viewPlaneNormal:a,focalPoint:r}=s;if(!a||!r)return[];const c=e.data?.handles?.points;if(!(c instanceof Array)||c.length!==1)return[];const l=c[0],d=$o(a,r);return Vd(d,l)<this.configuration.displayThreshold?[e]:[]}updateViewportImage(t){const n=this._currentCursorWorldPosition;if(!(!n||n.some(e=>isNaN(e)))){if(t instanceof Pn){const e=Oh(n,t);if(e===null)return;e!==t.getCurrentImageIdIndex()&&t.setImageIdIndex(e)}else if(t instanceof Xe){const{focalPoint:e,viewPlaneNormal:o}=ht(t);if(!e||!o)return;const s=$o(o,e),a=Vd(s,n,!0);if(Math.abs(a)<.5)return;const r=Wt(B(),Ot(...o)),c=bn(B(),r,a),l=yn(B(),Ot(...e),c);{t.setCamera({focalPoint:l});const d=t.getRenderingEngine();d&&d.renderViewport(t.id)}}else if(ie(t)){const{focalPoint:e,viewPlaneNormal:o}=ht(t);if(!e||!o)return;const s=$o(o,e),a=Vd(s,n,!0);if(Math.abs(a)<.5)return;const r=Wt(B(),Ot(...o)),c=bn(B(),r,a),l=yn(B(),Ot(...e),c);yl(t,l);const d=t.getRenderingEngine();d&&d.renderViewport(t.id)}}}}g5.toolName="ReferenceCursors";const Vp=[];class m5 extends Ci{constructor(t={},n={configuration:{viewportId:"",scaleLocation:"bottom"}}){super(t,n),this.editData=null,this._init=()=>{const o=Vi()[0];if(!o)return;const s=Be(this.toolGroupId).viewportsInfo;if(!s)return;const a=s.map(g=>ae(g.viewportId,g.renderingEngineId));let{viewport:r}=a[0];const{FrameOfReferenceUID:c}=a[0];if(this.configuration.viewportId&&a.forEach(g=>{g.viewport.id==this.configuration.viewportId&&(r=g.viewport)}),!r)return;const{viewUp:l,viewPlaneNormal:d}=ht(r),u=Vu(r);let h=this.editData?.annotation;const f=Yt(this.getToolName(),r.element);f.length&&(h=f.filter(g=>g.data?.viewportId==r.id)[0]),a.forEach(g=>{const{viewport:m}=g;if(!Vp.includes(m.id)){const p={metadata:{toolName:this.getToolName(),viewPlaneNormal:[...d],viewUp:[...l],FrameOfReferenceUID:c,referencedImageId:null},data:{handles:{points:Vu(m)},viewportId:m.id}};Vp.push(m.id),Nt(p,m.element),h=p}}),this.editData?.annotation&&this.editData.annotation.data.viewportId==r.id&&(this.editData.annotation.data.handles.points=u,this.editData.annotation.data.viewportId=r.id),this.editData={viewport:r,renderingEngine:o,annotation:h}},this.onSetToolEnabled=()=>{this._init()},this.onCameraModified=e=>{this.configuration.viewportId=e.detail.viewportId,this._init()},this.computeScaleSize=(e,o,s)=>{const a=[16e3,8e3,4e3,2e3,1e3,500,250,100,50,25,10,5,2];let r;return s=="top"||s=="bottom"?r=a.filter(c=>c<e*.6&&c>e*.2):r=a.filter(c=>c<o*.6&&c>o*.2),r[0]},this.computeEndScaleTicks=(e,o)=>{const s={bottom:[[0,-10],[0,-10]],top:[[0,10],[0,10]],left:[[0,0],[10,0]],right:[[0,0],[-10,0]]},a=[[e[1][0]+s[o][0][0],e[1][1]+s[o][0][0]],[e[1][0]+s[o][1][0],e[1][1]+s[o][1][1]]],r=[[e[0][0]+s[o][0][0],e[0][1]+s[o][0][0]],[e[0][0]+s[o][1][0],e[0][1]+s[o][1][1]]];return{endTick1:a,endTick2:r}},this.computeInnerScaleTicks=(e,o,s,a,r)=>{let c;o=="bottom"||o=="top"?c=r[0][0]-a[0][0]:(o=="left"||o=="right")&&(c=r[0][1]-a[0][1]);const l=[],d=[],u=[];let h=e;e>=50&&(h=e/10);const f=c/h;for(let g=0;g<h-1;g++){const m={bottom:[[f*(g+1),0],[f*(g+1),5]],top:[[f*(g+1),0],[f*(g+1),-5]],left:[[0,f*(g+1)],[-5,f*(g+1)]],right:[[0,f*(g+1)],[5,f*(g+1)]]};l.push(`${s}-tick${g}`),d.push(`tick${g}`),(g+1)%5==0?u.push([[a[0][0]+m[o][0][0],a[0][1]+m[o][0][1]],[a[1][0]+m[o][0][0],a[1][1]+m[o][0][1]]]):u.push([[a[0][0]+m[o][0][0],a[0][1]+m[o][0][1]],[a[1][0]+m[o][1][0],a[1][1]+m[o][1][1]]])}return{tickIds:l,tickUIDs:d,tickCoordinates:u}},this.computeWorldScaleCoordinates=(e,o,s)=>{let a,r=Oe(B(),s[0],s[1]);r=Wt(B(),r);let c=Oe(B(),s[2],s[0]);c=Wt(B(),c);const l={bottom:[s[1],s[2]],top:[s[0],s[3]],right:[s[2],s[3]],left:[s[0],s[1]]},d=yn(B(),l[o][0],l[o][0]).map(h=>h/2),u=e/2/Math.sqrt(Math.pow(r[0],2)+Math.pow(r[1],2)+Math.pow(r[2],2));return o=="top"||o=="bottom"?a=[Oe(B(),d,c.map(h=>h*u)),yn(B(),d,c.map(h=>h*u))]:(o=="left"||o=="right")&&(a=[yn(B(),d,r.map(h=>h*u)),Oe(B(),d,r.map(h=>h*u))]),a},this.computeCanvasScaleCoordinates=(e,o,s,a,r)=>{let c;if(r=="top"||r=="bottom"){const l=o[0][0]-o[1][0];c=[[e.width/2-l/2,s.height],[e.width/2+l/2,s.height]]}else if(r=="left"||r=="right"){const l=o[0][1]-o[1][1];c=[[a.width,e.height/2-l/2],[a.width,e.height/2+l/2]]}return c},this.computeScaleBounds=(e,o,s,a)=>{const r=o*Math.min(1e3,e.width),c=s*Math.min(1e3,e.height),l={bottom:[-c,-r],top:[c,r],left:[c,r],right:[-c,-r]},d={bottom:[e.height,e.width],top:[0,e.width],left:[e.height,0],right:[e.height,e.width]};return{height:d[a][0]+l[a][0],width:d[a][1]+l[a][1]}}}renderAnnotation(t,n){if(!this.editData||!this.editData.viewport)return;const e=this.configuration.scaleLocation,{viewport:o}=t,a=Yt(this.getToolName(),o.element).filter(ot=>ot.data?.viewportId==o.id)[0],r=t.viewport.canvas,c=!1;if(!o||!a)return c;const l={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:t.viewport.id},d={width:r.width/window.devicePixelRatio||1,height:r.height/window.devicePixelRatio||1},u=a.data.handles.points[0],h=a.data.handles.points[1],f=a.data.handles.points[2],g=a.data.handles.points[3],m=[u,f,h,g],p=ke(f,g),v=ke(u,f),I=this.computeScaleBounds(d,.05,.05,e),w=this.computeScaleBounds(d,.05,.05,e),C=this.computeScaleSize(p,v,e),S=this.computeWorldScaleCoordinates(C,e,m).map(ot=>o.worldToCanvas(ot)),b=this.computeCanvasScaleCoordinates(d,S,w,I,e),_=this.computeEndScaleTicks(b,e),{annotationUID:y}=a;l.annotationUID=y;const D=this.getStyle("lineWidth",l,a),T=this.getStyle("lineDash",l,a),P=this.getStyle("color",l,a),x=this.getStyle("shadow",l,a),M=`${y}-scaleline`;qt(n,y,"1",b[0],b[1],{color:P,width:D,lineDash:T,shadow:x},M);const R=`${y}-left`;qt(n,y,"2",_.endTick1[0],_.endTick1[1],{color:P,width:D,lineDash:T,shadow:x},R);const W=`${y}-right`;qt(n,y,"3",_.endTick2[0],_.endTick2[1],{color:P,width:D,lineDash:T,shadow:x},W);const j={bottom:[-10,-42],top:[-12,-35],left:[-40,-20],right:[-50,-20]},F=[b[0][0]+j[e][0],b[0][1]+j[e][1]],z=this._getTextLines(C),{tickIds:q,tickUIDs:J,tickCoordinates:it}=this.computeInnerScaleTicks(C,e,y,_.endTick1,_.endTick2);for(let ot=0;ot<J.length;ot++)qt(n,y,J[ot],it[ot][0],it[ot][1],{color:P,width:D,lineDash:T,shadow:x},q[ot]);return Ko(n,y,"text0",z,[F[0],F[1]],{fontFamily:"Helvetica Neue, Helvetica, Arial, sans-serif",fontSize:"14px",lineDash:"2,3",lineWidth:"1",shadow:!0,color:P}),c}_getTextLines(t){let n,e;return t>=50?(n=t/10,e=" cm"):(n=t,e=" mm"),[n.toString().concat(e)]}}m5.toolName="ScaleOverlay";const AS=(i,t,n)=>{if(!t?.data?.contour?.polyline?.length)return;const{polyline:e}=t.data.contour,{length:o}=e;let s=1/0;for(let a=0;a<o;a++){const r=i.worldToCanvas(e[a]),c=ro(r,n);s=Math.min(s,c)}if(!(s===1/0||isNaN(s)))return s};class qc{constructor(){this.toolInfo={toolSize:null,radius:null,maxToolSize:null}}renderShape(t,n,e){En(t,"SculptorTool","0",n,this.toolInfo.toolSize,e)}configureToolSize(t){const n=this.toolInfo;if(n.toolSize&&n.maxToolSize)return;const o=t.detail.element,a=Math.min(o.clientWidth,o.clientHeight)/24;n.toolSize=a,n.radius=null,n.maxToolSize=a}updateToolSize(t,n,e){const o=this.toolInfo,s=AS(n,e,t);s>0&&(o.toolSize=Math.min(o.maxToolSize,s),this.computeWorldRadius(n,!0))}getMaxSpacing(t){return Math.max(this.toolInfo.toolSize/4,t)}computeWorldRadius(t,n=!1){if(!this.toolInfo.radius||n){const e=t.canvasToWorld([0,0]),o=t.canvasToWorld([this.toolInfo.toolSize,0]);this.toolInfo.radius=mn(tn(B(),e,o))}return this.toolInfo.radius}getEdge(t,n,e,o){const s=yn(B(),n,e||n);bn(s,s,.5);const a=t.worldToCanvas(s),r=No(It(),a,o),c=Math.atan2(r[1],r[0]),l=this.interpolatePoint(t,c,o),d=t.worldToCanvas(l);return{point:l,angle:c,canvasPoint:d}}interpolatePoint(t,n,e){const[o,s]=e,a=this.toolInfo.toolSize,r=Math.cos(n)*a,c=Math.sin(n)*a,l=[o+r,s+c];return t.canvasToWorld(l)}isInCursor(t,n){return ke(t,n)<this.toolInfo.radius}}qc.shapeName="Circle";const{isEqual:p5}=oe;class v5 extends Ee{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{minSpacing:1,referencedToolNames:["PlanarFreehandROI","PlanarFreehandContourSegmentationTool"],toolShape:"circle",referencedToolName:"PlanarFreehandROI",updateCursorSize:"dynamic"}}){super(t,n),this.registeredShapes=new Map,this.isActive=!1,this.commonData={activeAnnotationUID:null,viewportIdsToRender:[],isEditingOpenContour:!1,canvasLocation:void 0,external:!0,closed:!1},this.preMouseDownCallback=e=>{const o=e.detail,{element:s}=o;if(this.configureToolSize(e),this.selectFreehandTool(o),this.commonData.activeAnnotationUID!==null)return this.isActive=!0,wt(s),this.activateModify(s),!0},this.mouseMoveCallback=e=>{this.mode===se.Active?(this.configureToolSize(e),this.updateCursor(e)):this.commonData.canvasLocation=void 0},this.endCallback=e=>{const o=e.detail,{element:s}=o;this.isActive=!1,this.deactivateModify(s),Ft(s);const a=this.getToolInstance(s);a.doneEditMemo?.();const c=this.filterSculptableAnnotationsForElement(s).find(l=>l.annotationUID===this.commonData.activeAnnotationUID);a.configuration.calculateStats&&(c.invalidated=!0),zt(c,s,Bt.HandlesUpdated)},this.dragCallback=e=>{const o=e.detail,s=o.element;this.updateCursor(e);const a=this.filterSculptableAnnotationsForElement(s),r=a.find(l=>l.annotationUID===this.commonData.activeAnnotationUID);if(!a?.length||!this.isActive)return;const c=r.data.contour.polyline;this.sculpt(o,c)},this.registerShapes(qc.shapeName,qc),this.setToolShape(this.configuration.toolShape)}registerShapes(t,n){const e=new n;this.registeredShapes.set(t,e)}sculpt(t,n){const e=this.configuration,o=t.element,s=N(o),{viewport:a}=s,r=this.registeredShapes.get(this.selectedShape);this.sculptData={mousePoint:t.currentPoints.world,mouseCanvasPoint:t.currentPoints.canvas,points:n,maxSpacing:r.getMaxSpacing(e.minSpacing),element:o,contours:[{annotationUID:this.commonData.activeAnnotationUID,points:n}]};const c=this.intersect(a,r);if(!c.length)return;const l=this.getContourSelections(c,n.length),{closed:d}=this.commonData;for(const u of l){const h=new Array,f=u[u.length-1];let g=d?f.relIndex:0,m;for(const p of u)p.isEnter?(_u(h,n,g,p.index),m=p):this.interpolatePoints(a,m,p,n,h),g=p.index;if(l.length>1&&wo(h.map(a.worldToCanvas))<0){console.warn("Skipping internal area");continue}!d&&g<n.length-1&&_u(h,n,g),n.splice(0,n.length),_u(n,h);return}}intersect(t,n){const{contours:e,mousePoint:o,mouseCanvasPoint:s}=this.sculptData,{closed:a}=this.commonData;n.computeWorldRadius(t);const r=new Array;for(const c of e){const{annotationUID:l,points:d}=c;let u=!1;const{length:h}=d;for(let f=0;f<=h;f++){const g=f%h,m=d[g],p=n.isInCursor(m,o);if(f===0){if(u=p,!a&&p){const I=n.getEdge(t,m,null,s);r.push({annotationUID:l,isEnter:p,index:f,point:I.point,angle:I.angle})}continue}if(g===0&&!a){if(u){const I=n.getEdge(t,d[h-1],null,s);r.push({annotationUID:l,isEnter:!1,index:h-1,point:I.point,angle:I.angle})}continue}if(u===p)continue;u=p;const v=n.getEdge(t,m,d[f-1],s);r.push({annotationUID:l,isEnter:p,index:f,point:v.point,angle:v.angle})}}return r}interpolatePoints(t,n,e,o,s){const{external:a,closed:r}=this.commonData,c=o[n.index%o.length],l=o[e.index%o.length],d=tn(B(),l,c);if(p5(mn(d),0))return;const u=this.registeredShapes.get(this.selectedShape),h=(n.angle+2*Math.PI)%(Math.PI*2),f=(e.angle+2*Math.PI)%(Math.PI*2);let g=f<h?f+2*Math.PI:f;const m=f>h?f-2*Math.PI:f;(a&&!r&&Math.abs(m-h)<Math.abs(g-h)||a&&r)&&(g=m);const p=Math.ceil(Math.abs(h-g)/.25);for(let v=0;v<=p;v++){const I=(h*(p-v)+v*g)/p;s.push(u.interpolatePoint(t,I,this.sculptData.mouseCanvasPoint))}}getContourSelections(t,n){const e=new Array,o=t.length/2;if(!o||t.length%2)return e;let s=Number.NEGATIVE_INFINITY;for(let a=0;a<o;a++){const r=this.findNext(t,s);if(!r){console.error("Couldnt' find an entry");continue}const c=this.findNext(t,r.angle,!1);if(!c){console.error("Couldn't find an exit for",r);continue}c.relIndex||=c.index<r.index?c.index+n:c.index,e.push([r,c])}e.sort((a,r)=>a[0].index-r[0].index);for(let a=0;a<e.length-1;){const r=e[a],c=this.findMergeable(e,r,a);c?r.push(...c):a++}return e.length>1&&console.warn("************* More than 1 result",e),e}findMergeable(t,n,e){const o=n[n.length-1];for(let s=e+1;s<t.length;s++){const[a]=t[s];if(a.index>=o.relIndex){const r=t[s];return t.splice(s,1),r}}}findNext(t,n,e=!0){if(t.length===1){const[r]=t;return t.splice(0,1),r}let o,s;for(let r=0;r<t.length;r++){const c=t[r];if(c.isEnter==e){const l=(c.angle-n+2*Math.PI)%(2*Math.PI);(!o||l<s)&&(o={i:r,intersection:c},s=l)}}if(!o){console.warn("Couldn't find an exit point for entry",JSON.stringify(t));return}t.splice(o.i,1);const{intersection:a}=o;return a}interpolatePointsWithinMaxSpacing(t,n,e,o){const{element:s}=this.sculptData,a=N(s),{viewport:r}=a,c=I5(t+1,n.length),l=r.worldToCanvas(n[t]),d=r.worldToCanvas(n[c]);ro(l,d)>o&&e.push(t)}updateCursor(t){const n=t.detail,e=n.element,o=N(e),{viewport:s}=o;this.commonData.viewportIdsToRender=[s.id];const a=this.filterSculptableAnnotationsForElement(e);if(!a?.length)return;const r=a.find(c=>c.annotationUID===this.commonData.activeAnnotationUID);if(this.commonData.canvasLocation=n.currentPoints.canvas,this.isActive)r.highlighted=!0;else{const c=this.registeredShapes.get(this.selectedShape),l=n.currentPoints.canvas;this.configuration.updateCursorSize==="dynamic"&&c.updateToolSize(l,s,r)}V(this.commonData.viewportIdsToRender)}getToolInstance(t){const n=N(t),{renderingEngineId:e,viewportId:o}=n;return Ae(o,e).getToolInstance(this.configuration.referencedToolName)}filterSculptableAnnotationsForElement(t){const{configuration:n}=this,e=[],o=this.getToolInstance(t);return n.referencedToolNames.forEach(s=>{const a=Yt(s,t);a&&e.push(...a)}),o.filterInteractableAnnotationsForElement(t,e)}configureToolSize(t){this.registeredShapes.get(this.selectedShape).configureToolSize(t)}selectFreehandTool(t){const n=this.getClosestFreehandToolOnElement(t);if(n===void 0)return;const e=ne(n);if(this.commonData.activeAnnotationUID=n,this.commonData.closed=e.data.contour.closed,this.commonData.external=!0,this.commonData.closed){const{element:o}=t,s=N(o),{viewport:a}=s,r=e.data.contour.polyline.map(l=>a.worldToCanvas(l)),c=t.currentPoints.canvas;this.commonData.external=!Ln(r,c,{closed:!0})}}getClosestFreehandToolOnElement(t){const{element:n}=t,e=N(n),{viewport:o}=e,s=this.configuration,a=this.filterSculptableAnnotationsForElement(n);if(!a?.length)return;const r=t.currentPoints.canvas,c={distance:1/0,toolIndex:void 0,annotationUID:void 0};for(let l=0;l<a?.length;l++){if(a[l].isLocked||!a[l].isVisible)continue;const d=AS(o,a[l],r);d!==-1&&d<c.distance&&(c.distance=d,c.toolIndex=l,c.annotationUID=a[l].annotationUID)}return this.commonData.isEditingOpenContour=!a[c.toolIndex].data.contour.closed,s.referencedToolName=a[c.toolIndex].metadata.toolName,c.annotationUID}activateModify(t){const n=ne(this.commonData.activeAnnotationUID);this.getToolInstance(t).createMemo?.(t,n),t.addEventListener(E.MOUSE_UP,this.endCallback),t.addEventListener(E.MOUSE_CLICK,this.endCallback),t.addEventListener(E.MOUSE_DRAG,this.dragCallback),t.addEventListener(E.TOUCH_TAP,this.endCallback),t.addEventListener(E.TOUCH_END,this.endCallback),t.addEventListener(E.TOUCH_DRAG,this.dragCallback)}deactivateModify(t){t.removeEventListener(E.MOUSE_UP,this.endCallback),t.removeEventListener(E.MOUSE_CLICK,this.endCallback),t.removeEventListener(E.MOUSE_DRAG,this.dragCallback),t.removeEventListener(E.TOUCH_TAP,this.endCallback),t.removeEventListener(E.TOUCH_END,this.endCallback),t.removeEventListener(E.TOUCH_DRAG,this.dragCallback)}setToolShape(t){this.selectedShape=this.registeredShapes.get(t)??qc.shapeName}renderAnnotation(t,n){const{viewport:e}=t,{element:o}=e,s=this.commonData.viewportIdsToRender;if(!this.commonData.canvasLocation||this.mode!==se.Active||!s.includes(e.id)||!this.filterSculptableAnnotationsForElement(o)?.length)return;const r={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:t.viewport.id};let c=Nn("color",r,To.Default,this.mode);this.isActive&&(c=Nn("color",r,To.Highlighted,this.mode)),this.registeredShapes.get(this.selectedShape).renderShape(n,this.commonData.canvasLocation,{color:c})}}function _u(i,t,n=0,e=t.length){e<n&&(e=e+t.length);for(let o=n;o<e;o++)i.push(t[o%t.length])}const I5=(i,t)=>(i+t)%t;v5.toolName="SculptorTool";const w5={Z:[0,0,1]};class E5 extends Ee{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{direction:w5.Z,rotateIncrementDegrees:30,rotateDragDegreesPerPixel:.5}}){super(t,n)}mouseWheelCallback(t){const{element:n,wheel:e}=t.detail,{rotateIncrementDegrees:o}=this.configuration,{direction:s}=e,a=s*(o*Math.PI)/180;this._rotate(n,a)}mouseDragCallback(t){this._dragCallback(t)}touchDragCallback(t){this._dragCallback(t)}_dragCallback(t){const{element:n,deltaPoints:e}=t.detail,{rotateDragDegreesPerPixel:o}=this.configuration,s=e.canvas[0];if(!s)return;const a=s*o*Math.PI/180;this._rotate(n,a)}_rotate(t,n){const e=N(t),{viewport:o}=e,{direction:s}=this.configuration,a=ht(o),{viewUp:r,position:c,focalPoint:l}=a,[d,u,h]=l,[f,g,m]=s,p=[0,0,0],v=[0,0,0],I=[0,0,0],w=Qn(new Float32Array(16));fo(w,w,[d,u,h]),go(w,w,n,[f,g,m]),fo(w,w,[-d,-u,-h]),Ue(p,c,w),Ue(v,l,w),Qn(w),go(w,w,n,[f,g,m]),Ue(I,r,w),Td(o,{position:p,viewUp:I,focalPoint:v}),o.render()}}E5.toolName="VolumeRotateMouseWheel";var LS;class Ad extends be{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{shadow:!0,getTextCallback:S5,changeTextCallback:C5,preventHandleOutsideImage:!1}}){super(t,n),this.isPointNearTool=(e,o,s,a)=>{const r=N(e),{viewport:c}=r,{annotationUID:l}=o,d=o.data.handles.points[0],u=c.worldToCanvas(d);if(_e(s,u)<a)return!0;const f=e.querySelector("svg");if(!f)return!1;const g=f.querySelector(`g[data-annotation-uid="${l}"]`);if(!g)return!1;const m=g,p=m.getBBox(),v=m.getAttribute("transform");let I=0,w=0;if(v){const _=v.match(/translate\(([-\d.]+)\s+([-\d.]+)\)/);_&&(I=parseFloat(_[1]),w=parseFloat(_[2]))}const C=p.x+I,S=p.y+w;return s[0]>=C&&s[0]<=C+p.width&&s[1]>=S&&s[1]<=S+p.height},this.addNewAnnotation=e=>{const o=e.detail,{currentPoints:s,element:a}=o,r=s.world;wt(a),this.isDrawing=!0;const c=this.createAnnotation(e,[[...r],[...r]]);Nt(c,a);const l=ft(a,this.getToolName());return this.editData={annotation:c,newAnnotation:!0,viewportIdsToRender:l,offset:[0,0,0]},e.preventDefault(),V(l),this.configuration.getTextCallback(d=>{if(!d){Gt(c.annotationUID),V(l),this.isDrawing=!1;return}Ft(a),c.data.label=d,ue(c),V(l)}),this.createMemo(a,c,{newAnnotation:!0}),c},this.toolSelectedCallback=(e,o)=>{const s=e.detail,{element:a,currentPoints:r}=s;o.highlighted=!0;const c=ft(a,this.getToolName());let l=[0,0,0];if(r&&r.world){const d=r.world,u=o.data.handles.points[0];l=[u[0]-d[0],u[1]-d[1],u[2]-d[2]]}this.editData={annotation:o,viewportIdsToRender:c,offset:l},this._activateModify(a),wt(a),V(c),e.preventDefault()},this._endCallback=e=>{const o=e.detail,{element:s}=o,{annotation:a,viewportIdsToRender:r,newAnnotation:c}=this.editData;this._deactivateDraw(s),this._deactivateModify(s),Ft(s),c&&this.createMemo(s,a,{newAnnotation:c}),this.editData=null,this.isDrawing=!1,this.doneEditMemo(),this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&Gt(a.annotationUID),V(r),c&&ue(a)},this._dragCallback=e=>{const o=e.detail,{currentPoints:s,element:a}=o,r=s.world,{annotation:c,viewportIdsToRender:l,offset:d}=this.editData;d?c.data.handles.points[0]=[r[0]+d[0],r[1]+d[1],r[2]+d[2]]:c.data.handles.points[0]=[...r],c.invalidated=!0,V(l),zt(c,a,Bt.LabelChange)},this.cancel=e=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateModify(e),Ft(e);const{annotation:o,viewportIdsToRender:s,newAnnotation:a}=this.editData,{data:r}=o;return o.highlighted=!1,r.handles.activeHandleIndex=null,V(s),a&&ue(o),this.editData=null,o.annotationUID}},this._activateModify=e=>{$.isInteractingWithTool=!0,e.addEventListener(E.MOUSE_UP,this._endCallback),e.addEventListener(E.MOUSE_DRAG,this._dragCallback),e.addEventListener(E.MOUSE_CLICK,this._endCallback),e.addEventListener(E.TOUCH_TAP,this._endCallback),e.addEventListener(E.TOUCH_END,this._endCallback),e.addEventListener(E.TOUCH_DRAG,this._dragCallback)},this._deactivateModify=e=>{$.isInteractingWithTool=!1,e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragCallback),e.removeEventListener(E.TOUCH_END,this._endCallback)},this._activateDraw=e=>{$.isInteractingWithTool=!0,e.addEventListener(E.MOUSE_UP,this._endCallback),e.addEventListener(E.MOUSE_DRAG,this._dragCallback),e.addEventListener(E.MOUSE_MOVE,this._dragCallback),e.addEventListener(E.MOUSE_CLICK,this._endCallback),e.addEventListener(E.TOUCH_TAP,this._endCallback),e.addEventListener(E.TOUCH_END,this._endCallback),e.addEventListener(E.TOUCH_DRAG,this._dragCallback)},this._deactivateDraw=e=>{$.isInteractingWithTool=!1,e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragCallback),e.removeEventListener(E.MOUSE_MOVE,this._dragCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback),e.removeEventListener(E.TOUCH_END,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragCallback)},this.renderAnnotation=(e,o)=>{let s=!1;const{viewport:a}=e,{element:r}=a;let c=Yt(this.getToolName(),r);if(!c?.length)return s;c=this.filterInteractableAnnotationsForElement(r,c);const l={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:e.viewport.id};for(let d=0;d<c.length;d++){const u=c[d],{annotationUID:h,data:f}=u,g=f.handles.points[0];l.annotationUID=h;const m=a.worldToCanvas(g);if(s=!0,!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),s;if(!$e(h)||!f.label)continue;const p=this.getLinkedTextBoxStyle(l,u);Ko(o,h,"1",[f.label],m,{...p,padding:0})}return s}}handleSelectedCallback(t,n,e,o){}_doneChangingTextCallback(t,n,e){n.data.label=e;const o=ft(t,this.getToolName());V(o),zt(n,t)}_isInsideVolume(t,n,e){return gn(t,e)&&gn(n,e)}}LS=Ad;Ad.toolName="Label";Ad.hydrate=(i,t,n,e)=>{const o=le(i);if(!o)return;const{viewport:s}=o,a=s.getFrameOfReferenceUID(),{viewPlaneNormal:r,viewUp:c}=ht(s),l=new LS,d=l.getReferencedImageId(s,t,r,c),u={annotationUID:e?.annotationUID||Se(),data:{label:n,handles:{points:[t]}},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{toolName:l.getToolName(),viewPlaneNormal:r,FrameOfReferenceUID:a,referencedImageId:d,...e}};Nt(u,s.element),V([s.id])};function S5(i){return i(prompt("Enter your annotation:"))}function C5(i,t,n){return n(prompt("Enter your annotation:"))}Ad.toolName="Label";var Hr;class dg extends be{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{preventHandleOutsideImage:!1,getTextLines:b5,actions:{undo:{method:"undo",bindings:[{key:"z"}]},redo:{method:"redo",bindings:[{key:"y"}]}}}}){super(t,n),this.addNewAnnotation=e=>{const o=e.detail,{currentPoints:s,element:a}=o,r=s.world;wt(a),this.isDrawing=!0;const c=this.createAnnotation(e,[[...r],[...r]]);Nt(c,a);const l=ft(a,this.getToolName());return this.editData={annotation:c,viewportIdsToRender:l,handleIndex:1,movingTextBox:!1,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),e.preventDefault(),V(l),c},this.isPointNearTool=(e,o,s,a)=>{const r=N(e),{viewport:c}=r,{data:l}=o,[d,u]=l.handles.points,h=c.worldToCanvas(d),f=c.worldToCanvas(u),g={start:{x:h[0],y:h[1]},end:{x:f[0],y:f[1]}};return Je([g.start.x,g.start.y],[g.end.x,g.end.y],[s[0],s[1]])<=a},this.toolSelectedCallback=(e,o)=>{const s=e.detail,{element:a}=s;o.highlighted=!0;const r=ft(a,this.getToolName());this.editData={annotation:o,viewportIdsToRender:r,movingTextBox:!1},this._activateModify(a),wt(a),V(r),e.preventDefault()},this._endCallback=e=>{const o=e.detail,{element:s}=o,{annotation:a,viewportIdsToRender:r,newAnnotation:c,hasMoved:l}=this.editData,{data:d}=a;c&&!l||(d.handles.activeHandleIndex=null,this._deactivateModify(s),this._deactivateDraw(s),Ft(s),this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&Gt(a.annotationUID),V(r),this.doneEditMemo(),c&&ue(a),this.editData=null,this.isDrawing=!1)},this._dragCallback=e=>{this.isDrawing=!0;const o=e.detail,{element:s}=o,{annotation:a,viewportIdsToRender:r,handleIndex:c,movingTextBox:l,newAnnotation:d}=this.editData,{data:u}=a;if(this.createMemo(s,a,{newAnnotation:d}),l){const{deltaPoints:h}=o,f=h.world,{textBox:g}=u.handles,{worldPosition:m}=g;m[0]+=f[0],m[1]+=f[1],m[2]+=f[2],g.hasMoved=!0}else if(c===void 0){const{deltaPoints:h}=o,f=h.world;u.handles.points.forEach(m=>{m[0]+=f[0],m[1]+=f[1],m[2]+=f[2]}),a.invalidated=!0}else{const{currentPoints:h}=o,f=h.world;u.handles.points[c]=[...f],a.invalidated=!0}this.editData.hasMoved=!0,V(r),a.invalidated&&zt(a,s,Bt.HandlesUpdated)},this.cancel=e=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateDraw(e),this._deactivateModify(e),Ft(e);const{annotation:o,viewportIdsToRender:s,newAnnotation:a}=this.editData,{data:r}=o;return o.highlighted=!1,r.handles.activeHandleIndex=null,V(s),a&&ue(o),this.editData=null,o.annotationUID}},this._activateModify=e=>{$.isInteractingWithTool=!0,e.addEventListener(E.MOUSE_UP,this._endCallback),e.addEventListener(E.MOUSE_DRAG,this._dragCallback),e.addEventListener(E.MOUSE_CLICK,this._endCallback),e.addEventListener(E.TOUCH_END,this._endCallback),e.addEventListener(E.TOUCH_DRAG,this._dragCallback),e.addEventListener(E.TOUCH_TAP,this._endCallback)},this._deactivateModify=e=>{$.isInteractingWithTool=!1,e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.TOUCH_END,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback)},this._activateDraw=e=>{$.isInteractingWithTool=!0,e.addEventListener(E.MOUSE_UP,this._endCallback),e.addEventListener(E.MOUSE_DRAG,this._dragCallback),e.addEventListener(E.MOUSE_MOVE,this._dragCallback),e.addEventListener(E.MOUSE_CLICK,this._endCallback),e.addEventListener(E.TOUCH_END,this._endCallback),e.addEventListener(E.TOUCH_DRAG,this._dragCallback),e.addEventListener(E.TOUCH_TAP,this._endCallback)},this._deactivateDraw=e=>{$.isInteractingWithTool=!1,e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragCallback),e.removeEventListener(E.MOUSE_MOVE,this._dragCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.TOUCH_END,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(e,o)=>{let s=!1;const{viewport:a}=e,{element:r}=a;let c=Yt(this.getToolName(),r);if(!c?.length||(c=this.filterInteractableAnnotationsForElement(r,c),!c?.length))return s;const l=this.getTargetId(a),d=a.getRenderingEngine(),u={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:e.viewport.id};for(let h=0;h<c.length;h++){const f=c[h],{annotationUID:g,data:m}=f,{points:p,activeHandleIndex:v}=m.handles;u.annotationUID=g;const{color:I,lineWidth:w,lineDash:C,shadow:S}=this.getAnnotationStyle({annotation:f,styleSpecifier:u}),b=p.map(x=>a.worldToCanvas(x));if(!m.cachedStats[l]||m.cachedStats[l].unit==null?(m.cachedStats[l]={length:null,unit:null},this._calculateCachedStats(f,d,e)):f.invalidated&&this._throttledCalculateCachedStats(f,d,e),!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),s;let _;if(!$e(g))continue;!ze(g)&&!this.editData&&v!==null&&(_=[b[v]]);const y=!!Nn("showHandlesAlways",{});(_||y)&&xe(o,g,"0",b,{color:I,lineDash:C,lineWidth:w});const D=`${g}-line`;if(qt(o,g,"1",b[0],b[1],{color:I,width:w,lineDash:C,shadow:S},D),s=!0,!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),s;const P=this.configuration.getTextLines(m,l);this.renderLinkedTextBoxAnnotation({enabledElement:e,svgDrawingHelper:o,annotation:f,styleSpecifier:u,textLines:P??[],canvasCoordinates:b})}return s},this._throttledCalculateCachedStats=Un(this._calculateCachedStats,100,{trailing:!0})}handleSelectedCallback(t,n,e){const o=t.detail,{element:s}=o,{data:a}=n;n.highlighted=!0;let r=!1,c;e.worldPosition?r=!0:c=a.handles.points.findIndex(d=>d===e);const l=ft(s,this.getToolName());this.editData={annotation:n,viewportIdsToRender:l,handleIndex:c,movingTextBox:r},this._activateModify(s),wt(s),V(l),t.preventDefault()}_calculateCachedStats(t,n,e){const o=t.data,{element:s}=e.viewport,{cachedStats:a}=o,r=Object.keys(a);for(let l=0;l<r.length;l++){const d=r[l],u=this.getTargetImageData(d);if(!u)continue;const{imageData:h,dimensions:f}=u,g=o.handles.points.map(w=>h.worldToIndex(w)),m=ao(u,g),{unit:p}=m,v=Hr.calculateLengthInIndex(m,g);this.isHandleOutsideImage=!Hr.isInsideVolume(f,g);const I={name:"length",value:v,unit:p,type:Io.Linear};a[d]={length:v,unit:p,statsArray:[I]}}const c=t.invalidated;return t.invalidated=!1,c&&zt(t,s,Bt.StatsUpdated),a}}Hr=dg;dg.toolName="Length";dg.hydrate=(i,t,n)=>{const e=le(i);if(!e)return;const{FrameOfReferenceUID:o,referencedImageId:s,viewPlaneNormal:a,instance:r,viewport:c}=Hr.hydrateBase(Hr,e,t,n),{toolInstance:l,...d}=n||{},u={annotationUID:n?.annotationUID||Se(),data:{handles:{points:t}},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{toolName:r.getToolName(),viewPlaneNormal:a,FrameOfReferenceUID:o,referencedImageId:s,...d}};Nt(u,c.element),V([c.id])};function b5(i,t){const n=i.cachedStats[t],{length:e,unit:o}=n;return e==null||isNaN(e)?void 0:[`${de(e)} ${o}`]}const{transformWorldToIndex:Fp}=oe;class _5 extends be{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{preventHandleOutsideImage:!1,getTextLines:y5}}){super(t,n),this.addNewAnnotation=e=>{const o=e.detail,{currentPoints:s,element:a}=o,r=s.world;wt(a),this.isDrawing=!0;const c=this.createAnnotation(e,[[...r],[...r]]);Nt(c,a);const l=ft(a,this.getToolName());return this.editData={annotation:c,viewportIdsToRender:l,handleIndex:1,movingTextBox:!1,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),e.preventDefault(),V(l),c},this.isPointNearTool=(e,o,s,a)=>{const r=N(e),{viewport:c}=r,{data:l}=o,[d,u]=l.handles.points,h=c.worldToCanvas(d),f=c.worldToCanvas(u),g={start:{x:h[0],y:h[1]},end:{x:f[0],y:f[1]}};return Je([g.start.x,g.start.y],[g.end.x,g.end.y],[s[0],s[1]])<=a},this.toolSelectedCallback=(e,o)=>{const s=e.detail,{element:a}=s;o.highlighted=!0;const r=ft(a,this.getToolName());this.editData={annotation:o,viewportIdsToRender:r,movingTextBox:!1},this._activateModify(a),wt(a),N(a),V(r),e.preventDefault()},this._endCallback=e=>{const o=e.detail,{element:s}=o,{annotation:a,viewportIdsToRender:r,newAnnotation:c,hasMoved:l}=this.editData,{data:d}=a;if(c&&!l)return;d.handles.activeHandleIndex=null,this._deactivateModify(s),this._deactivateDraw(s),Ft(s);const u=N(s),{renderingEngine:h}=u;this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&Gt(a.annotationUID),V(r),this.doneEditMemo(),c&&ue(a),this.editData=null,this.isDrawing=!1},this._dragCallback=e=>{this.isDrawing=!0;const o=e.detail,{element:s}=o,{annotation:a,viewportIdsToRender:r,handleIndex:c,movingTextBox:l,newAnnotation:d}=this.editData,{data:u}=a;if(this.createMemo(s,a,{newAnnotation:d}),l){const{deltaPoints:g}=o,m=g.world,{textBox:p}=u.handles,{worldPosition:v}=p;v[0]+=m[0],v[1]+=m[1],v[2]+=m[2],p.hasMoved=!0}else if(c===void 0){const{deltaPoints:g}=o,m=g.world;u.handles.points.forEach(v=>{v[0]+=m[0],v[1]+=m[1],v[2]+=m[2]}),a.invalidated=!0}else{const{currentPoints:g}=o,m=g.world;u.handles.points[c]=[...m],a.invalidated=!0}this.editData.hasMoved=!0;const h=N(s),{renderingEngine:f}=h;V(r)},this.cancel=e=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateDraw(e),this._deactivateModify(e),Ft(e);const{annotation:o,viewportIdsToRender:s,newAnnotation:a}=this.editData,{data:r}=o;return o.highlighted=!1,r.handles.activeHandleIndex=null,N(e),V(s),a&&ue(o),this.editData=null,o.annotationUID}},this._activateModify=e=>{$.isInteractingWithTool=!0,e.addEventListener(E.MOUSE_UP,this._endCallback),e.addEventListener(E.MOUSE_DRAG,this._dragCallback),e.addEventListener(E.MOUSE_CLICK,this._endCallback),e.addEventListener(E.TOUCH_END,this._endCallback),e.addEventListener(E.TOUCH_DRAG,this._dragCallback),e.addEventListener(E.TOUCH_TAP,this._endCallback)},this._deactivateModify=e=>{$.isInteractingWithTool=!1,e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.TOUCH_END,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback)},this._activateDraw=e=>{$.isInteractingWithTool=!0,e.addEventListener(E.MOUSE_UP,this._endCallback),e.addEventListener(E.MOUSE_DRAG,this._dragCallback),e.addEventListener(E.MOUSE_MOVE,this._dragCallback),e.addEventListener(E.MOUSE_CLICK,this._endCallback),e.addEventListener(E.TOUCH_END,this._endCallback),e.addEventListener(E.TOUCH_DRAG,this._dragCallback),e.addEventListener(E.TOUCH_TAP,this._endCallback)},this._deactivateDraw=e=>{$.isInteractingWithTool=!1,e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragCallback),e.removeEventListener(E.MOUSE_MOVE,this._dragCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.TOUCH_END,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(e,o)=>{let s=!1;const{viewport:a}=e,{element:r}=a;let c=Yt(this.getToolName(),r);if(!c?.length||(c=this.filterInteractableAnnotationsForElement(r,c),!c?.length))return s;const l=this.getTargetId(a),d=a.getRenderingEngine(),u={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:e.viewport.id};for(let h=0;h<c.length;h++){const f=c[h],{annotationUID:g,data:m}=f,{points:p,activeHandleIndex:v}=m.handles;u.annotationUID=g;const{color:I,lineWidth:w,lineDash:C,shadow:S}=this.getAnnotationStyle({annotation:f,styleSpecifier:u}),b=p.map(P=>a.worldToCanvas(P));let _;if(!m.cachedStats[l]||m.cachedStats[l].unit==null?(m.cachedStats[l]={length:null,unit:null},this._calculateCachedStats(f,d,e)):f.invalidated&&this._throttledCalculateCachedStats(f,d,e),!$e(g))continue;!ze(g)&&!this.editData&&v!==null&&(_=[b[v]]);const y=!!Nn("showHandlesAlways",{});if((_||y)&&xe(o,g,"0",b,{color:I,lineDash:C,lineWidth:w}),f0(o,g,"0",b[0],b[1],{color:I,width:w,lineDash:C}),s=!0,!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),s;const T=this.configuration.getTextLines(m,l);this.renderLinkedTextBoxAnnotation({enabledElement:e,svgDrawingHelper:o,annotation:f,styleSpecifier:u,textLines:T??[],canvasCoordinates:b})}return s},this._throttledCalculateCachedStats=Un(this._calculateCachedStats,100,{trailing:!0})}handleSelectedCallback(t,n,e){const o=t.detail,{element:s}=o,{data:a}=n;n.highlighted=!0;let r=!1,c;e.worldPosition?r=!0:c=a.handles.points.findIndex(h=>h===e);const l=ft(s,this.getToolName());this.editData={annotation:n,viewportIdsToRender:l,handleIndex:c,movingTextBox:r},this._activateModify(s),wt(s);const d=N(s),{renderingEngine:u}=d;V(l),t.preventDefault()}_calculateHeight(t,n){const e=n[0]-t[0],o=n[1]-t[1],s=n[2]-t[2];if(e==0)return o!=0?Math.abs(s):0;if(o==0)return Math.abs(s);if(s==0)return Math.abs(o)}_calculateCachedStats(t,n,e){const o=t.data,{element:s}=e.viewport,a=o.handles.points[0],r=o.handles.points[1],{cachedStats:c}=o,l=Object.keys(c);for(let u=0;u<l.length;u++){const h=l[u],f=this.getTargetImageData(h);if(!f)continue;const{imageData:g,dimensions:m}=f,p=Fp(g,a),v=Fp(g,r),I=[p,v],{scale:w,unit:C}=ao(f,I),S=this._calculateHeight(a,r)/w,b=this._isInsideVolume(p,v,m);this.isHandleOutsideImage=b,c[h]={height:S,unit:C}}const d=t.invalidated;return t.invalidated=!1,d&&zt(t,s,Bt.StatsUpdated),c}_isInsideVolume(t,n,e){return gn(t,e)&&gn(n,e)}}_5.toolName="Height";function y5(i,t){const n=i.cachedStats[t],{height:e,unit:o}=n;return e==null||isNaN(e)?void 0:[`${de(e)} ${o}`]}var Dl;const{transformWorldToIndex:x5}=oe;class mc extends be{constructor(t={},n){super(t,be.mergeDefaultProps(Dl.probeDefaults,n)),this.addNewAnnotation=(e,o="Mouse")=>{const s=e.detail,{currentPoints:a,element:r}=s,c=N(r),{viewport:l}=c,d=o.toLowerCase()==="touch",u=this.getTouchAdjustedWorldPos(l,a,d);this.isDrawing=!0;const h=this.constructor.createAnnotationForViewport(l,{data:{handles:{points:[[...u]]}}});Nt(h,r);const f=ft(r,this.getToolName());return this.editData={annotation:h,newAnnotation:!0,viewportIdsToRender:f},this._activateModify(r),wt(r),e.preventDefault(),V(f),h},this._endCallback=e=>{const o=e.detail,{element:s}=o,{annotation:a,viewportIdsToRender:r,newAnnotation:c}=this.editData,{viewportId:l,renderingEngine:d}=N(s);this.eventDispatchDetail={viewportId:l,renderingEngineId:d.id},this._deactivateModify(s),Ft(s),c&&this.createMemo(s,a,{newAnnotation:c}),this.editData=null,this.isDrawing=!1,this.doneEditMemo(),this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&Gt(a.annotationUID),V(r),c&&ue(a)},this._dragCallback=e=>{this.isDrawing=!0;const o=e.detail,{currentPoints:s,element:a}=o,{viewport:r}=N(a),c=e.type===E.TOUCH_DRAG,l=this.getTouchAdjustedWorldPos(r,s,c),{annotation:d,viewportIdsToRender:u,newAnnotation:h}=this.editData,{data:f}=d;this.createMemo(a,d,{newAnnotation:h}),f.handles.points[0]=[...l],d.invalidated=!0,V(u)},this.cancel=e=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateModify(e),Ft(e);const{annotation:o,viewportIdsToRender:s,newAnnotation:a}=this.editData,{data:r}=o;return o.highlighted=!1,r.handles.activeHandleIndex=null,V(s),a&&ue(o),this.editData=null,o.annotationUID}},this._activateModify=e=>{$.isInteractingWithTool=!0,e.addEventListener(E.MOUSE_UP,this._endCallback),e.addEventListener(E.MOUSE_DRAG,this._dragCallback),e.addEventListener(E.MOUSE_CLICK,this._endCallback),e.addEventListener(E.TOUCH_END,this._endCallback),e.addEventListener(E.TOUCH_DRAG,this._dragCallback),e.addEventListener(E.TOUCH_TAP,this._endCallback)},this._deactivateModify=e=>{$.isInteractingWithTool=!1,e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.TOUCH_END,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(e,o)=>{let s=!1;const{viewport:a}=e,{element:r}=a;let c=Yt(this.getToolName(),r);if(!c?.length||(c=this.filterInteractableAnnotationsForElement(r,c),!c?.length))return s;const l=a.getRenderingEngine(),d={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:e.viewport.id};for(let u=0;u<c.length;u++){const h=c[u],f=h.annotationUID,g=h.data,m=g.handles.points[0],p=a.worldToCanvas(m),v=this.getTargetId(a,g);d.annotationUID=f;const{color:I,lineWidth:w}=this.getAnnotationStyle({annotation:h,styleSpecifier:d});if(g.cachedStats||(g.cachedStats={}),!g.cachedStats[v]||g.cachedStats[v].value===null)g.cachedStats[v]={Modality:null,index:null,value:null},this._calculateCachedStats(h,l,e,Bt.StatsUpdated);else if(h.invalidated&&(this._calculateCachedStats(h,l,e),a instanceof Xe)){const{referencedImageId:_}=h.metadata;if(_)for(const y in g.cachedStats)y.startsWith("imageId")&&l.getViewports().filter(Ds).find(P=>{const x=P.getCurrentImageId();if(!x)return!1;const M=eo(_),L=P.hasImageURI(M),R=eo(x);return L&&R!==M})&&delete g.cachedStats[y]}if(!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),s;if(!$e(f))continue;xe(o,f,"0",[p],{color:I,lineWidth:w,handleRadius:this.configuration.handleRadius}),s=!0;const S=this.getLinkedTextBoxStyle(d,h);if(!S.visibility)continue;const b=this.configuration.getTextLines(g,v);if(b){const _=gf([p],r,b);Ko(o,f,"0",b,_,S)}}return s}}isPointNearTool(t,n,e,o){const s=N(t),{viewport:a}=s,{data:r}=n,c=r.handles.points[0],l=a.worldToCanvas(c);return _e(e,l)<o}toolSelectedCallback(){}getHandleNearImagePoint(t,n,e,o){const s=N(t),{viewport:a}=s,{data:r}=n,c=r.handles.points[0],l=a.worldToCanvas(c);if(_e(e,l)<o===!0)return c}getTouchAdjustedWorldPos(t,n,e){const{touchCanvasOffset:o}=this.configuration;if(!e||!o)return n.world;const{x:s=0,y:a=0}=o;if(!s&&!a)return n.world;const[r,c]=n.canvas;return t.canvasToWorld([r+s,c+a])}handleSelectedCallback(t,n){const e=t.detail,{element:o}=e;n.highlighted=!0;const s=ft(o,this.getToolName());this.editData={annotation:n,viewportIdsToRender:s},this._activateModify(o),wt(o),V(s),t.preventDefault()}_calculateCachedStats(t,n,e,o=Bt.StatsUpdated){const s=t.data,{renderingEngineId:a,viewport:r}=e,{element:c}=r,l=s.handles.points[0],{cachedStats:d}=s,u=Object.keys(d);for(let f=0;f<u.length;f++){const g=u[f],m={isPreScaled:Ki(r,g),isSuvScaled:this.isSuvScaled(r,g,t.metadata.referencedImageId)},p=this.getTargetImageData(g);if(!p)continue;const{dimensions:v,imageData:I,metadata:w,voxelManager:C}=p,S=w?.Modality;let b=x5(I,l);if(b=Ib(b,b),gn(b,v)){if(this.isHandleOutsideImage=!1,g.startsWith("imageId:")&&S!=="ECG"){const D=g.split("imageId:")[1],T=eo(D),x=Uu(T)[0];b[2]=x.getCurrentImageIdIndex()}let _,y;if(S==="ECG"){const D=Cr(p,[b]);_=D.values,y=D.units}else if(S==="US"){_=C?.getAtIJKPoint(b);const D=Cr(p,[b]),T=D.values.every(P=>P!==null);_=T?D.values:_,y=T?D.units:"raw"}else _=C?.getAtIJKPoint(b),y=bi(S,t.metadata.referencedImageId,m);d[g]={index:b,value:_,Modality:S,modalityUnit:y},t.invalidated=!0}else this.isHandleOutsideImage=!0,d[g]={index:b,Modality:S}}const h=t.invalidated;return t.invalidated=!1,h&&zt(t,c,o),d}}Dl=mc;mc.toolName="Probe";mc.probeDefaults={supportedInteractionTypes:["Mouse","Touch"],configuration:{shadow:!0,preventHandleOutsideImage:!1,getTextLines:P5,handleRadius:"6",textCanvasOffset:{x:6,y:-6},touchCanvasOffset:{x:0,y:-40}}};mc.hydrate=(i,t,n)=>{const e=le(i);if(!e)return;const{FrameOfReferenceUID:o,referencedImageId:s,viewPlaneNormal:a,viewUp:r,instance:c,viewport:l}=Dl.hydrateBase(Dl,e,t,n),{toolInstance:d,...u}=n||{},h={annotationUID:n?.annotationUID||Se(),data:{handles:{points:t}},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{toolName:c.getToolName(),viewPlaneNormal:a,FrameOfReferenceUID:o,referencedImageId:s,...u}};Nt(h,l.element),V([l.id])};function P5(i,t){const n=i.cachedStats[t],{index:e,value:o,modalityUnit:s}=n;if(o===void 0||!e)return;const a=[];if(a.push(`(${e[0]}, ${e[1]}, ${e[2]})`),o instanceof Array&&s instanceof Array)for(let r=0;r<o.length;r++)a.push(`${de(o[r])} ${s[r]}`);else a.push(`${de(o)} ${s}`);return a}class D5 extends mc{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{shadow:!0,preventHandleOutsideImage:!1,getTextLines:T5}}){super(t,n),this.postMouseDownCallback=e=>{const o=e.detail,{currentPoints:s,element:a}=o,r=N(a),{viewport:c}=r,l=e.type===E.TOUCH_START,d=this.getTouchAdjustedWorldPos(c,s,l);this.isDrawing=!0;const u=ht(c),{viewPlaneNormal:h,viewUp:f}=u,g=this.getReferencedImageId(c,d,h,f),m={invalidated:!0,highlighted:!0,isVisible:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...h],viewUp:[...f],FrameOfReferenceUID:c.getFrameOfReferenceUID(),referencedImageId:g},data:{label:"",handles:{points:[[...d]]},cachedStats:{}}},p=ft(a,this.getToolName());return this.editData={annotation:m,newAnnotation:!0,viewportIdsToRender:p},this._activateModify(a),wt(a),e.preventDefault(),V(p),m},this.postTouchStartCallback=e=>this.postMouseDownCallback(e),this.renderAnnotation=(e,o)=>{let s=!1;const{viewport:a}=e;if(!this.editData||!this.filterInteractableAnnotationsForElement(a.element,[this.editData.annotation])?.length)return s;const c=a.getRenderingEngine(),l={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:e.viewport.id},d=this.editData.annotation,u=d.annotationUID,h=d.data,f=h.handles.points[0],g=a.worldToCanvas(f),m=this.getTargetId(a,h);l.annotationUID=u;const{color:p}=this.getAnnotationStyle({annotation:d,styleSpecifier:l});if(!h.cachedStats[m]||h.cachedStats[m].value===null?(h.cachedStats[m]={Modality:null,index:null,value:null},this._calculateCachedStats(d,c,e)):d.invalidated&&this._calculateCachedStats(d,c,e),!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),s;xe(o,u,"0",[g],{color:p}),s=!0;const I=this.configuration.getTextLines(h,m);if(I){const w=[g[0]+6,g[1]-6];Ko(o,u,"0",I,[w[0],w[1]],this.getLinkedTextBoxStyle(l,d))}return s}}}D5.toolName="DragProbe";function T5(i,t){const n=i.cachedStats[t],{index:e,value:o,modalityUnit:s}=n;if(o===void 0)return;const a=[];return a.push(`(${e[0]}, ${e[1]}, ${e[2]})`),a.push(`${o.toFixed(2)} ${s}`),a}var Wr;const{transformWorldToIndex:Gp}=oe;class ug extends be{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{shadow:!0,preventHandleOutsideImage:!1,storePointData:!1,centerPointRadius:0,calculateStats:!0,getTextLines:M5,statsCalculator:bo}}){super(t,n),this.isHandleOutsideImage=!1,this.addNewAnnotation=e=>{const o=e.detail,{currentPoints:s,element:a}=o,r=s.world;this.isDrawing=!0;const c=this.createAnnotation(e,[[...r],[...r],[...r],[...r]]);Nt(c,a);const l=ft(a,this.getToolName());return this.editData={annotation:c,viewportIdsToRender:l,centerWorld:r,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),wt(a),e.preventDefault(),V(l),c},this.isPointNearTool=(e,o,s,a)=>{const r=N(e),{viewport:c}=r,{data:l}=o,{points:d}=l.handles,u=d.map(y=>c.worldToCanvas(y)),[h,f,g,m]=u,p=Math.hypot(g[0]-m[0],g[1]-m[1]),v=Math.hypot(f[0]-h[0],f[1]-h[1]),I=Math.atan2(g[1]-m[1],g[0]-m[0]),w=[(g[0]+m[0])/2,(f[1]+h[1])/2],C={center:w,xRadius:(p-a)/2,yRadius:(v-a)/2,angle:I},S={center:w,xRadius:(p+a)/2,yRadius:(v+a)/2,angle:I},b=this._pointInEllipseCanvas(C,s);return!!(this._pointInEllipseCanvas(S,s)&&!b)},this.toolSelectedCallback=(e,o)=>{const s=e.detail,{element:a}=s;o.highlighted=!0;const r=ft(a,this.getToolName());this.editData={annotation:o,viewportIdsToRender:r,movingTextBox:!1},wt(a),this._activateModify(a);const c=N(a),{renderingEngine:l}=c;V(r),e.preventDefault()},this.handleSelectedCallback=(e,o,s)=>{const a=e.detail,{element:r}=a,{data:c}=o;o.highlighted=!0;let l=!1,d,u,h,f,g,m;if(s.worldPosition)l=!0;else{const{points:v}=c.handles,{viewport:I}=N(r),{worldToCanvas:w,canvasToWorld:C}=I;d=v.findIndex(b=>b===s);const S=v.map(w);m=S[d],f=Math.abs(S[2][0]-S[3][0]),g=Math.abs(S[0][1]-S[1][1]),u=[(S[2][0]+S[3][0])/2,(S[0][1]+S[1][1])/2],h=C(u)}const p=ft(r,this.getToolName());this.editData={annotation:o,viewportIdsToRender:p,handleIndex:d,canvasWidth:f,canvasHeight:g,centerWorld:h,originalHandleCanvas:m,movingTextBox:l},this._activateModify(r),wt(r),V(p),e.preventDefault()},this._endCallback=e=>{const o=e.detail,{element:s}=o,{annotation:a,viewportIdsToRender:r,newAnnotation:c,hasMoved:l}=this.editData,{data:d}=a;c&&!l||(this.doneEditMemo(),a.highlighted=!1,d.handles.activeHandleIndex=null,this._deactivateModify(s),this._deactivateDraw(s),Ft(s),this.editData=null,this.isDrawing=!1,this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&Gt(a.annotationUID),V(r),c&&ue(a))},this._dragDrawCallback=e=>{this.isDrawing=!0;const o=e.detail,{element:s}=o,{currentPoints:a}=o,r=a.canvas,c=N(s),{viewport:l}=c,{canvasToWorld:d}=l,{annotation:u,viewportIdsToRender:h,centerWorld:f,newAnnotation:g}=this.editData;this.createMemo(s,u,{newAnnotation:g});const m=l.worldToCanvas(f),{data:p}=u,v=Math.abs(r[0]-m[0]),I=Math.abs(r[1]-m[1]),w=[m[0],m[1]-I],C=[m[0],m[1]+I],S=[m[0]-v,m[1]],b=[m[0]+v,m[1]];p.handles.points=[d(w),d(C),d(S),d(b)],u.invalidated=!0,this.editData.hasMoved=!0,V(h),zt(u,s,Bt.HandlesUpdated)},this._dragModifyCallback=e=>{this.isDrawing=!0;const o=e.detail,{element:s}=o,{annotation:a,viewportIdsToRender:r,handleIndex:c,movingTextBox:l,newAnnotation:d}=this.editData;this.createMemo(s,a,{newAnnotation:d});const{data:u}=a;if(l){const{deltaPoints:g}=o,m=g.world,{textBox:p}=u.handles,{worldPosition:v}=p;v[0]+=m[0],v[1]+=m[1],v[2]+=m[2],p.hasMoved=!0}else if(c===void 0){const{deltaPoints:g}=o,m=g.world;u.handles.points.forEach(v=>{v[0]+=m[0],v[1]+=m[1],v[2]+=m[2]}),a.invalidated=!0}else this._dragHandle(e),a.invalidated=!0;const h=N(s),{renderingEngine:f}=h;V(r),a.invalidated&&zt(a,s,Bt.HandlesUpdated)},this._dragHandle=e=>{const o=e.detail,{element:s}=o,{viewport:a}=N(s),{canvasToWorld:r,worldToCanvas:c}=a,{annotation:l,canvasWidth:d,canvasHeight:u,handleIndex:h,centerWorld:f,originalHandleCanvas:g}=this.editData,m=a.worldToCanvas(f),{data:p}=l,{points:v}=p.handles,{currentPoints:I}=o,w=I.canvas;if(h===0||h===1){const C=Math.abs(w[1]-m[1]),S=[m[0],m[1]-C],b=[m[0],m[1]+C];v[0]=r(S),v[1]=r(b);const _=w[0]-g[0],y=d/2+_,D=[m[0]-y,m[1]],T=[m[0]+y,m[1]];v[2]=r(D),v[3]=r(T)}else{const C=Math.abs(w[0]-m[0]),S=[m[0]-C,m[1]],b=[m[0]+C,m[1]];v[2]=r(S),v[3]=r(b);const _=w[1]-g[1],y=u/2+_,D=[m[0],m[1]-y],T=[m[0],m[1]+y];v[0]=r(D),v[1]=r(T)}},this.cancel=e=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateDraw(e),this._deactivateModify(e),Ft(e);const{annotation:o,viewportIdsToRender:s,newAnnotation:a}=this.editData,{data:r}=o;return o.highlighted=!1,r.handles.activeHandleIndex=null,V(s),a&&ue(o),this.editData=null,o.annotationUID}},this._activateModify=e=>{$.isInteractingWithTool=!0,e.addEventListener(E.MOUSE_UP,this._endCallback),e.addEventListener(E.MOUSE_DRAG,this._dragModifyCallback),e.addEventListener(E.MOUSE_CLICK,this._endCallback),e.addEventListener(E.TOUCH_END,this._endCallback),e.addEventListener(E.TOUCH_DRAG,this._dragModifyCallback),e.addEventListener(E.TOUCH_TAP,this._endCallback)},this._deactivateModify=e=>{$.isInteractingWithTool=!1,e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragModifyCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.TOUCH_END,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragModifyCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback)},this._activateDraw=e=>{$.isInteractingWithTool=!0,e.addEventListener(E.MOUSE_UP,this._endCallback),e.addEventListener(E.MOUSE_DRAG,this._dragDrawCallback),e.addEventListener(E.MOUSE_MOVE,this._dragDrawCallback),e.addEventListener(E.MOUSE_CLICK,this._endCallback),e.addEventListener(E.TOUCH_END,this._endCallback),e.addEventListener(E.TOUCH_DRAG,this._dragDrawCallback),e.addEventListener(E.TOUCH_TAP,this._endCallback)},this._deactivateDraw=e=>{$.isInteractingWithTool=!1,e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragDrawCallback),e.removeEventListener(E.MOUSE_MOVE,this._dragDrawCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.TOUCH_END,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragDrawCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(e,o)=>{let s=!1;const{viewport:a}=e,{element:r}=a;let c=Yt(this.getToolName(),r);if(!c?.length||(c=this.filterInteractableAnnotationsForElement(r,c),!c?.length))return s;const l=a.getRenderingEngine(),d={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:e.viewport.id};for(let u=0;u<c.length;u++){const h=c[u],{annotationUID:f,data:g}=h,{handles:m}=g,{points:p,activeHandleIndex:v}=m,I=this.getTargetId(a,g);d.annotationUID=f;const{color:w,lineWidth:C,lineDash:S}=this.getAnnotationStyle({annotation:h,styleSpecifier:d}),b=p.map(L=>a.worldToCanvas(L)),_=il(b),{centerPointRadius:y}=this.configuration;if(!g.cachedStats[I]||g.cachedStats[I].areaUnit==null)g.cachedStats[I]={Modality:null,area:null,max:null,mean:null,stdDev:null,areaUnit:null},this._calculateCachedStats(h,a,l);else if(h.invalidated&&(this._throttledCalculateCachedStats(h,a,l,e),a instanceof Xe)){const{referencedImageId:L}=h.metadata;for(const R in g.cachedStats)R.startsWith("imageId")&&l.getViewports().filter(Ds).find(K=>{const j=eo(L),F=K.hasImageURI(j),z=eo(K.getCurrentImageId());return F&&z!==j})&&delete g.cachedStats[R]}if(!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),s;let D;if(!$e(f))continue;!ze(f)&&!this.editData&&v!==null&&(D=[b[v]]);const T=!!Nn("showHandlesAlways",{});(D||T)&&xe(o,f,"0",T?b:D,{color:w});const P=`${f}-ellipse`,x="0";if(id(o,f,x,b,{color:w,lineDash:S,lineWidth:C},P),y>0&&Math.min(Math.abs(_[0][0]-_[1][0])/2,Math.abs(_[0][1]-_[1][1])/2)>3*y){const R=this._getCanvasEllipseCenter(b);En(o,f,`${x}-center`,R,y,{color:w,lineDash:S,lineWidth:C})}s=!0;const M=this.configuration.getTextLines(g,I);!M||M.length===0||this.renderLinkedTextBoxAnnotation({enabledElement:e,svgDrawingHelper:o,annotation:h,styleSpecifier:d,textLines:M,canvasCoordinates:b,placementPoints:_})}return s},this._calculateCachedStats=(e,o,s)=>{if(!this.configuration.calculateStats)return;const a=e.data,{element:r}=o,{points:c}=a.handles,l=c.map(S=>o.worldToCanvas(S)),{viewPlaneNormal:d,viewUp:u}=ht(o),[h,f]=il(l),g=o.canvasToWorld(h),m=o.canvasToWorld(f),{cachedStats:p}=a,v=Object.keys(p),I=g,w=m;for(let S=0;S<v.length;S++){const b=v[S],_=this.getTargetImageData(b);if(!_)continue;const{dimensions:y,imageData:D,metadata:T,voxelManager:P}=_,x=Gp(D,I);x[0]=Math.floor(x[0]),x[1]=Math.floor(x[1]),x[2]=Math.floor(x[2]);const M=Gp(D,w);if(M[0]=Math.floor(M[0]),M[1]=Math.floor(M[1]),M[2]=Math.floor(M[2]),this._isInsideVolume(x,M,y)){const L=Math.min(x[0],M[0]),R=Math.max(x[0],M[0]),U=Math.min(x[1],M[1]),W=Math.max(x[1],M[1]),K=Math.min(x[2],M[2]),j=Math.max(x[2],M[2]),F=[[L,R],[U,W],[K,j]],z=[(g[0]+m[0])/2,(g[1]+m[1])/2,(g[2]+m[2])/2],q=Math.abs(g[0]-m[0])/2,J=Math.abs(g[1]-m[1])/2,it=Math.abs(g[2]-m[2])/2,tt={center:z,xRadius:q<Ks/2?0:q,yRadius:J<Ks/2?0:J,zRadius:it<Ks/2?0:it},{worldWidth:ot,worldHeight:nt}=ec(d,u,I,w),lt=ot===0&&nt===0,ut=ao(_,[x,M]),{areaUnit:Tt}=ut,kt=Kh(_),Pt=c.map(Jt=>D.worldToIndex(Jt)),te=Wr.calculateLengthInIndex(ut,Pt.slice(2,4)),Ie=Wr.calculateLengthInIndex(ut,Pt.slice(0,2)),re=Math.abs(Math.PI*(te/2)*(Ie/kt/2)),Zt={isPreScaled:Ki(o,b),isSuvScaled:this.isSuvScaled(o,b,e.metadata.referencedImageId)},ce=bi(T.Modality,e.metadata.referencedImageId,Zt);let Ut;P&&(Ut=P.forEach(this.configuration.statsCalculator.statsCallback,{isInObject:Jt=>Jl(tt,Jt,{fast:!0}),boundsIJK:F,imageData:D,returnPoints:this.configuration.storePointData}));const Ht=this.configuration.statsCalculator.getStatistics();p[b]={Modality:T.Modality,area:re,mean:Ht.mean?.value,max:Ht.max?.value,min:Ht.min?.value,stdDev:Ht.stdDev?.value,statsArray:Ht.array,pointsInShape:Ut,isEmptyArea:lt,areaUnit:Tt,modalityUnit:ce}}else this.isHandleOutsideImage=!0,p[b]={Modality:T.Modality}}const C=e.invalidated;return e.invalidated=!1,C&&zt(e,r,Bt.StatsUpdated),p},this._isInsideVolume=(e,o,s)=>gn(e,s)&&gn(o,s),this._throttledCalculateCachedStats=Un(this._calculateCachedStats,100,{trailing:!0})}_pointInEllipseCanvas(t,n){const{xRadius:e,yRadius:o,center:s,angle:a}=t,r=dy(It(),n,s,-a);if(e<=0||o<=0)return!1;const c=[r[0]-s[0],r[1]-s[1]];return c[0]*c[0]/(e*e)+c[1]*c[1]/(o*o)<=1}_getCanvasEllipseCenter(t){const[n,e,o,s]=t,a=[o[0],e[1]],r=[s[0],n[1]];return[(a[0]+r[0])/2,(a[1]+r[1])/2]}}Wr=ug;ug.toolName="EllipticalROI";ug.hydrate=(i,t,n)=>{const e=le(i);if(!e)return;const{FrameOfReferenceUID:o,referencedImageId:s,viewPlaneNormal:a,instance:r,viewport:c}=Wr.hydrateBase(Wr,e,t,n),{toolInstance:l,...d}=n||{},u={annotationUID:n?.annotationUID||Se(),data:{handles:{points:t,activeHandleIndex:null},label:"",cachedStats:{}},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{toolName:r.getToolName(),viewPlaneNormal:a,FrameOfReferenceUID:o,referencedImageId:s,...d}};Nt(u,c.element),V([c.id])};function M5(i,t){const n=i.cachedStats[t],{area:e,mean:o,stdDev:s,max:a,isEmptyArea:r,areaUnit:c,modalityUnit:l,min:d}=n,u=[];if(Fn(e)){const h=r?"Area: Oblique not supported":`Area: ${de(e)} ${c}`;u.push(h)}return Fn(o)&&u.push(`Mean: ${de(o)} ${l}`),Fn(a)&&u.push(`Max: ${de(a)} ${l}`),Fn(d)&&u.push(`Min: ${de(d)} ${l}`),Fn(s)&&u.push(`Std Dev: ${de(s)} ${l}`),u}function Tl(i,t){const{viewUp:n,viewPlaneNormal:e}=ht(t),o=B();Me(o,n,e);const[s,a]=i,r=ke(s,a),c=B(),l=B(),d=B(),u=B();for(let f=0;f<=2;f++)c[f]=s[f]-n[f]*r,l[f]=s[f]+n[f]*r,d[f]=s[f]-o[f]*r,u[f]=s[f]+o[f]*r;return[c,l,d,u]}var Br;const{transformWorldToIndex:Hp}=oe;class ji extends be{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{shadow:!0,preventHandleOutsideImage:!1,storePointData:!1,centerPointRadius:0,calculateStats:!0,getTextLines:A5,statsCalculator:bo,simplified:!0,targetsFilter:A0.allPixelData}}){super(t,n),this.isHandleOutsideImage=!1,this.addNewAnnotation=e=>{const o=e.detail,{currentPoints:s,element:a}=o,r=s.world;this.isDrawing=!0;let c;this.configuration.simplified?c=[[...r],[...r]]:c=[[...r],[...r],[...r],[...r],[...r]];const l=this.createAnnotation(e,c);Nt(l,a);const d=ft(a,this.getToolName());return this.editData={annotation:l,viewportIdsToRender:d,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),wt(a),e.preventDefault(),V(d),l},this.isPointNearTool=(e,o,s,a)=>{const r=N(e),{viewport:c}=r,{points:l}=o.data.handles,u=Tl(l.slice(0,2),c).map(w=>c.worldToCanvas(w)),h=il(u),[f,g]=h,m={left:Math.min(f[0],g[0])+a/2,top:Math.min(f[1],g[1])+a/2,width:Math.abs(f[0]-g[0])-a,height:Math.abs(f[1]-g[1])-a},p={left:Math.min(f[0],g[0])-a/2,top:Math.min(f[1],g[1])-a/2,width:Math.abs(f[0]-g[0])+a,height:Math.abs(f[1]-g[1])+a},v=this._pointInEllipseCanvas(m,s);return!!(this._pointInEllipseCanvas(p,s)&&!v)},this.toolSelectedCallback=(e,o)=>{const s=e.detail,{element:a}=s;o.highlighted=!0;const r=ft(a,this.getToolName());this.editData={annotation:o,viewportIdsToRender:r,movingTextBox:!1},wt(a),this._activateModify(a),V(r),e.preventDefault()},this.handleSelectedCallback=(e,o,s)=>{const a=e.detail,{element:r}=a,{data:c}=o;o.highlighted=!0;let l=!1,d;if(s.worldPosition)l=!0;else{const{points:h}=c.handles;d=h.findIndex(f=>f===s)}const u=ft(r,this.getToolName());this.editData={annotation:o,viewportIdsToRender:u,handleIndex:d,movingTextBox:l},this._activateModify(r),wt(r),V(u),e.preventDefault()},this._endCallback=e=>{const o=e.detail,{element:s}=o,{annotation:a,viewportIdsToRender:r,newAnnotation:c,hasMoved:l}=this.editData,{data:d}=a;c&&!l||(this.doneEditMemo(),a.highlighted=!1,d.handles.activeHandleIndex=null,this._deactivateModify(s),this._deactivateDraw(s),Ft(s),this.editData=null,this.isDrawing=!1,this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&Gt(a.annotationUID),V(r),c&&ue(a))},this._dragDrawCallback=e=>{this.isDrawing=!0;const o=e.detail,{element:s,currentPoints:a}=o,{world:r,canvas:c}=a,l=N(s),{viewport:d}=l,{canvasToWorld:u}=d,{annotation:h,viewportIdsToRender:f,newAnnotation:g}=this.editData;this.createMemo(s,h,{newAnnotation:g});const{data:m}=h,p=m.handles.points[0],v=d.worldToCanvas(p);if(this.configuration.simplified)m.handles.points[1]=r;else{const I=_e(v,c);m.handles.points[0]=[...p],m.handles.points[1]=u([v[0],v[1]-I]),m.handles.points[2]=u([v[0],v[1]+I]),m.handles.points[3]=u([v[0]-I,v[1]]),m.handles.points[4]=u([v[0]+I,v[1]])}h.invalidated=!0,this.editData.hasMoved=!0,V(f),zt(h,s,Bt.HandlesUpdated)},this._dragModifyCallback=e=>{this.isDrawing=!0;const o=e.detail,{element:s}=o,{annotation:a,viewportIdsToRender:r,handleIndex:c,movingTextBox:l,newAnnotation:d}=this.editData;this.createMemo(s,a,{newAnnotation:d});const{data:u}=a;if(l){const{deltaPoints:h}=o,f=h.world,{textBox:g}=u.handles,{worldPosition:m}=g;m[0]+=f[0],m[1]+=f[1],m[2]+=f[2],g.hasMoved=!0}else if(c===void 0){const{deltaPoints:h}=o,f=h.world;u.handles.points.forEach(m=>{m[0]+=f[0],m[1]+=f[1],m[2]+=f[2]}),a.invalidated=!0}else this._dragHandle(e),a.invalidated=!0;V(r),a.invalidated&&zt(a,s,Bt.HandlesUpdated)},this._dragHandle=e=>{const o=e.detail,{element:s}=o,a=N(s),{canvasToWorld:r,worldToCanvas:c}=a.viewport,{annotation:l,handleIndex:d}=this.editData,{data:u}=l,{points:h}=u.handles,{currentPoints:f,deltaPoints:g}=o;if(d===0){const m=g.world;h.forEach(p=>{yn(p,p,m)})}else{const m=h[0],p=c(m),v=f.canvas,I=_e(p,v);h[1]=r([p[0],p[1]-I]),h[2]=r([p[0],p[1]+I]),h[3]=r([p[0]-I,p[1]]),h[4]=r([p[0]+I,p[1]])}l.invalidated=!0},this.cancel=e=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateDraw(e),this._deactivateModify(e),Ft(e);const{annotation:o,viewportIdsToRender:s,newAnnotation:a}=this.editData;return o.highlighted=!1,o.data.handles.activeHandleIndex=null,V(s),a&&ue(o),this.editData=null,o.annotationUID}},this._activateModify=e=>{$.isInteractingWithTool=!0,e.addEventListener(E.MOUSE_UP,this._endCallback),e.addEventListener(E.MOUSE_DRAG,this._dragModifyCallback),e.addEventListener(E.MOUSE_CLICK,this._endCallback),e.addEventListener(E.TOUCH_END,this._endCallback),e.addEventListener(E.TOUCH_DRAG,this._dragModifyCallback),e.addEventListener(E.TOUCH_TAP,this._endCallback)},this._deactivateModify=e=>{$.isInteractingWithTool=!1,e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragModifyCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.TOUCH_END,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragModifyCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback)},this._activateDraw=e=>{$.isInteractingWithTool=!0,e.addEventListener(E.MOUSE_UP,this._endCallback),e.addEventListener(E.MOUSE_DRAG,this._dragDrawCallback),e.addEventListener(E.MOUSE_MOVE,this._dragDrawCallback),e.addEventListener(E.MOUSE_CLICK,this._endCallback),e.addEventListener(E.TOUCH_END,this._endCallback),e.addEventListener(E.TOUCH_DRAG,this._dragDrawCallback),e.addEventListener(E.TOUCH_TAP,this._endCallback)},this._deactivateDraw=e=>{$.isInteractingWithTool=!1,e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragDrawCallback),e.removeEventListener(E.MOUSE_MOVE,this._dragDrawCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.TOUCH_END,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragDrawCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(e,o)=>{let s=!1;const{viewport:a}=e,{element:r}=a;let c=Yt(this.getToolName(),r);if(!c?.length||(c=this.filterInteractableAnnotationsForElement(r,c),!c?.length))return s;const l=a.getRenderingEngine(),d={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:e.viewport.id};for(let u=0;u<c.length;u++){const h=c[u],{annotationUID:f,data:g}=h,{handles:m}=g,{points:p,activeHandleIndex:v}=m,I=this.getMeasurementTargets(a,g);d.annotationUID=f;const{color:w,lineWidth:C,lineDash:S}=this.getAnnotationStyle({annotation:h,styleSpecifier:d}),b=p.map(W=>a.worldToCanvas(W)),_=b[0],y=ga([_,b[1]]),D=rs([_,b[1]]),{centerPointRadius:T}=this.configuration;if(this.ensureCachedStatsTargets(g,I,W=>W.areaUnit==null))this._calculateCachedStats(h,a,l,e);else if(h.invalidated&&(this._throttledCalculateCachedStats(h,a,l,e),a instanceof Xe)){const{referencedImageId:W}=h.metadata;for(const K in g.cachedStats)K.startsWith("imageId")&&l.getViewports().filter(Ds).find(z=>{const q=eo(W),J=z.hasImageURI(q),it=eo(z.getCurrentImageId());return J&&it!==q})&&delete g.cachedStats[K]}if(!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),s;let P;if(!$e(f))continue;!ze(f)&&!this.editData&&v!==null&&(this.configuration.simplified?P=[b[v]]:P=b);const x=!!Nn("showHandlesAlways",{});(P||x)&&xe(o,f,"0",x?b:P,{color:w});const M=`${f}-circle`,L="0",U=Tl([p[0],p[1]],a).map(W=>a.worldToCanvas(W));if(id(o,f,L,U,{color:w,lineDash:S,lineWidth:C},M),T>0&&y>3*T&&En(o,f,`${L}-center`,_,T,{color:w,lineDash:S,lineWidth:C}),s=!0,this.configuration.calculateStats){const W=this.configuration.getTextLines(g,I);if(!W||W.length===0)continue;const K=[_,b[1]];if(!this.renderLinkedTextBoxAnnotation({enabledElement:e,svgDrawingHelper:o,annotation:h,styleSpecifier:d,textLines:W,canvasCoordinates:K,placementPoints:D}))continue}}return s},this._calculateCachedStats=(e,o,s,a)=>{if(!this.configuration.calculateStats)return;const{data:r}=e,{element:c}=o,l=e.invalidated,{points:d}=r.handles,u=d.map(S=>o.worldToCanvas(S)),h=u[0],f=u[1],[g,m]=rs([h,f]),p=o.canvasToWorld(g),v=o.canvasToWorld(m),{cachedStats:I}=r;if(l){const S=this.getMeasurementTargets(o,r);for(const b of Object.keys(I))delete I[b];this.ensureCachedStatsTargets(r,S)}const w=Object.keys(I);let C=!1;for(let S=0;S<w.length;S++){const b=w[S],_=this.getTargetImageData(b);if(!_)continue;const{dimensions:y,imageData:D,metadata:T,voxelManager:P}=_,x=d.map(nt=>D.worldToIndex(nt)),M=ao(_,x),L=Br.calculateLengthInIndex(M,x.slice(0,2)),R=Math.PI*L*L,U=2*Math.PI*L,W=L===0,{unit:K,areaUnit:j}=M,F={name:"area",value:R,unit:j,type:Io.Area},z={name:"circumference",value:U,unit:K,type:Io.Linear},q={name:"radius",value:L,unit:K,type:Io.Linear},J=[F,q,z];I[b]={Modality:T.Modality,area:R,isEmptyArea:W,areaUnit:j,radius:L,radiusUnit:K,perimeter:U,statsArray:J};const it=Hp(D,p),tt=Hp(D,v),ot=!Ee.isInsideVolume(y,[it,tt]);if(C||=ot,!ot){const nt=Math.min(it[0],tt[0]),lt=Math.max(it[0],tt[0]),rt=Math.min(it[1],tt[1]),ut=Math.max(it[1],tt[1]),Tt=Math.min(it[2],tt[2]),kt=Math.max(it[2],tt[2]),Pt=[[nt,lt],[rt,ut],[Tt,kt]],te=d[0],Ie=Math.abs(p[0]-v[0])/2,re=Math.abs(p[1]-v[1])/2,Zt=Math.abs(p[2]-v[2])/2,ce={center:te,xRadius:Ie<Ks/2?0:Ie,yRadius:re<Ks/2?0:re,zRadius:Zt<Ks/2?0:Zt},Ut={isPreScaled:Ki(o,b),isSuvScaled:this.isSuvScaled(o,b,e.metadata.referencedImageId)},Ht=bi(T.Modality,e.metadata.referencedImageId,Ut);let Jt;P&&(Jt=P.forEach(this.configuration.statsCalculator.statsCallback,{isInObject:De=>Jl(ce,De,{fast:!0}),boundsIJK:Pt,imageData:D,returnPoints:this.configuration.storePointData}));const Pe=this.configuration.statsCalculator.getStatistics();I[b]={...I[b],Modality:T.Modality,mean:Pe.mean?.value,max:Pe.max?.value,min:Pe.min?.value,pointsInShape:Jt,stdDev:Pe.stdDev?.value,modalityUnit:Ht,statsArray:[...J,...Pe.array]}}}return this.isHandleOutsideImage=C,e.invalidated=!1,l&&zt(e,c,Bt.StatsUpdated),I},this._throttledCalculateCachedStats=Un(this._calculateCachedStats,100,{trailing:!0})}_pointInEllipseCanvas(t,n){const e=t.width/2,o=t.height/2;if(e<=0||o<=0)return!1;const s=[t.left+e,t.top+o],a=[n[0]-s[0],n[1]-s[1]];return a[0]*a[0]/(e*e)+a[1]*a[1]/(o*o)<=1}}Br=ji;ji.toolName="CircleROI";ji.hydrate=(i,t,n)=>{const e=le(i);if(!e)return;const{FrameOfReferenceUID:o,referencedImageId:s,viewPlaneNormal:a,instance:r,viewport:c}=Br.hydrateBase(Br,e,t,n),{toolInstance:l,...d}=n||{},u={annotationUID:n?.annotationUID||Se(),data:{handles:{points:t,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}},activeHandleIndex:null},label:"",cachedStats:{}},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{toolName:r.getToolName(),viewPlaneNormal:a,FrameOfReferenceUID:o,referencedImageId:s,...d}};Nt(u,c.element),V([c.id])};ji.CIRCLE_ROI_METRICS=[{name:"Mean",attribute:"mean",unitAttribute:"modalityUnit"},{name:"Max",attribute:"max",unitAttribute:"modalityUnit"},{name:"Min",attribute:"min",unitAttribute:"modalityUnit"},{name:"Std Dev",attribute:"stdDev",unitAttribute:"modalityUnit"}];ji.getTextLines=zf(Br.CIRCLE_ROI_METRICS);function A5(i,t){const n=i.cachedStats[t[0]],e=[];if(!n)return e;const{radius:o,radiusUnit:s,area:a,isEmptyArea:r,areaUnit:c}=n;if(Fn(o)){const d=r?"Radius: Oblique not supported":`Radius: ${de(o)} ${s}`;e.push(d)}if(Fn(a)){const d=r?"Area: Oblique not supported":`Area: ${de(a)} ${c}`;e.push(d)}const l=ji.getTextLines(i,t);return l&&e.push(...l),e}const kc=5;class L5 extends be{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{shadow:!0,preventHandleOutsideImage:!1,degrees:[45,135,225,315],diameters:[10,30,60]}}){super(t,n),this.isHandleOutsideImage=!1,this.addNewAnnotation=e=>{const o=e.detail,{currentPoints:s,element:a}=o,r=s.world,c=N(a),{viewport:l,renderingEngine:d}=c;this.isDrawing=!0;const u=ht(l),{viewPlaneNormal:h,viewUp:f}=u,g=this.getReferencedImageId(l,r,h,f),m=l.getFrameOfReferenceUID(),p={highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...h],viewUp:[...f],FrameOfReferenceUID:m,referencedImageId:g,...l.getViewReference({points:[r]})},data:{label:"",handles:{points:[[...r]]}}};Nt(p,a);const v=ft(a,this.getToolName());return this.editData={annotation:p,viewportIdsToRender:v,newAnnotation:!0},this._activateDraw(a),wt(a),e.preventDefault(),V(v),p},this.isPointNearTool=(e,o,s,a)=>{const r=N(e),{viewport:c}=r,{data:l}=o,{points:d}=l.handles,u=c.worldToCanvas(d[0]),h=ga([u,s]);return Math.abs(h)<a},this.toolSelectedCallback=(e,o)=>{const s=e.detail,{element:a}=s;o.highlighted=!0;const r=ft(a,this.getToolName());this.editData={annotation:o,viewportIdsToRender:r},wt(a),this._activateModify(a);const c=N(a),{renderingEngine:l}=c;V(r),e.preventDefault()},this.handleSelectedCallback=(e,o)=>{const s=e.detail,{element:a}=s;o.highlighted=!0;const r=ft(a,this.getToolName());this.editData={annotation:o,viewportIdsToRender:r},this._activateModify(a),wt(a);const c=N(a),{renderingEngine:l}=c;V(r),e.preventDefault()},this._endCallback=e=>{const o=e.detail,{element:s}=o,{annotation:a,viewportIdsToRender:r,newAnnotation:c,hasMoved:l}=this.editData,{data:d}=a;if(c&&!l)return;a.highlighted=!1,d.handles.activeHandleIndex=null,this._deactivateModify(s),this._deactivateDraw(s),Ft(s);const{renderingEngine:u}=N(s);this.editData=null,this.isDrawing=!1,this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&Gt(a.annotationUID),V(r),c&&ue(a)},this._dragDrawCallback=e=>{this.isDrawing=!0;const o=e.detail,{element:s}=o,{currentPoints:a}=o,r=a.canvas,c=N(s),{renderingEngine:l,viewport:d}=c,{canvasToWorld:u}=d,{annotation:h,viewportIdsToRender:f}=this.editData,{data:g}=h;g.handles.points=[u(r),u(r)],h.invalidated=!0,this.editData.hasMoved=!0,V(f)},this._dragModifyCallback=e=>{this.isDrawing=!0;const o=e.detail,{element:s}=o,{annotation:a,viewportIdsToRender:r}=this.editData,{data:c}=a,{deltaPoints:l}=o,d=l.world;c.handles.points.forEach(g=>{g[0]+=d[0],g[1]+=d[1],g[2]+=d[2]}),a.invalidated=!0;const h=N(s),{renderingEngine:f}=h;V(r)},this._dragHandle=e=>{const o=e.detail,{element:s}=o,a=N(s),{canvasToWorld:r,worldToCanvas:c}=a.viewport,{annotation:l}=this.editData,{data:d}=l,{points:u}=d.handles,h=u.map(w=>c(w)),{currentPoints:f}=o,g=f.canvas,m=g[0]-h[0][0],p=g[1]-h[0][1],v=g,I=[h[1][0]+m,h[1][1]+p];u[0]=r(v),u[1]=r(I)},this.cancel=e=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateDraw(e),this._deactivateModify(e),Ft(e);const{annotation:o,viewportIdsToRender:s,newAnnotation:a}=this.editData,{data:r}=o;o.highlighted=!1,r.handles.activeHandleIndex=null;const{renderingEngine:c}=N(e);return V(s),a&&ue(o),this.editData=null,o.annotationUID}},this._activateModify=e=>{$.isInteractingWithTool=!0,e.addEventListener(E.MOUSE_UP,this._endCallback),e.addEventListener(E.MOUSE_DRAG,this._dragModifyCallback),e.addEventListener(E.MOUSE_CLICK,this._endCallback),e.addEventListener(E.TOUCH_END,this._endCallback),e.addEventListener(E.TOUCH_DRAG,this._dragModifyCallback),e.addEventListener(E.TOUCH_TAP,this._endCallback)},this._deactivateModify=e=>{$.isInteractingWithTool=!1,e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragModifyCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.TOUCH_END,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragModifyCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback)},this._activateDraw=e=>{$.isInteractingWithTool=!0,e.addEventListener(E.MOUSE_UP,this._endCallback),e.addEventListener(E.MOUSE_DRAG,this._dragDrawCallback),e.addEventListener(E.MOUSE_MOVE,this._dragDrawCallback),e.addEventListener(E.MOUSE_CLICK,this._endCallback),e.addEventListener(E.TOUCH_END,this._endCallback),e.addEventListener(E.TOUCH_DRAG,this._dragDrawCallback),e.addEventListener(E.TOUCH_TAP,this._endCallback)},this._deactivateDraw=e=>{$.isInteractingWithTool=!1,e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragDrawCallback),e.removeEventListener(E.MOUSE_MOVE,this._dragDrawCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.TOUCH_END,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragDrawCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(e,o)=>{let s=!1;const{viewport:a}=e,{element:r}=a;let c=Yt(this.getToolName(),r);if(!c?.length||(c=this.filterInteractableAnnotationsForElement(r,c),!c?.length))return s;const l={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:e.viewport.id};for(let d=0;d<c.length;d++){const u=c[d],{annotationUID:h,data:f}=u,{handles:g}=f,{points:m}=g;l.annotationUID=h;const{color:p,lineWidth:v,lineDash:I}=this.getAnnotationStyle({annotation:u,styleSpecifier:l}),C=m.map(P=>a.worldToCanvas(P))[0];if(!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),s;if(!$e(h))continue;let S=`${h}-crosshair-vertical`,b=[C[0],C[1]+kc],_=[C[0],C[1]-kc];qt(o,h,S,b,_,{color:p,lineDash:I,lineWidth:v}),S=`${h}-crosshair-horizontal`,b=[C[0]+kc,C[1]],_=[C[0]-kc,C[1]],qt(o,h,S,b,_,{color:p,lineDash:I,lineWidth:v});const y=this.configuration.diameters.map(P=>this.worldMeasureToCanvas(P,a));for(let P=0;P<y.length;P++){const x=`${h}-circle-${P}`,M=`${h}-circle-${P}`;En(o,h,M,C,y[P]/2,{color:p,lineDash:I,lineWidth:v},x)}const D=P=>P*Math.PI/180,T=this.configuration.degrees.map(P=>D(P));for(let P=0;P<T.length;P++){const x=`${h}-line-${P}`,M=[Math.cos(T[P])*y[0]/2+C[0],Math.sin(T[P])*y[0]/2+C[1]],L=[Math.cos(T[P])*y[2]/2+C[0],Math.sin(T[P])*y[2]/2+C[1]];qt(o,h,x,M,L,{color:p,lineDash:I,lineWidth:v})}s=!0}return s}}worldMeasureToCanvas(t,n){const e=n.canvasToWorld([n.canvas.width/2,n.canvas.height/2]),{viewUp:o}=ht(n),s=ee(B(),e,o,t),a=n.worldToCanvas(e),r=n.worldToCanvas(s);return Math.sqrt(Math.pow(r[0]-a[0],2)+Math.pow(r[1]-a[1],2))}}L5.toolName="ETDRSGrid";var Ml;const OS=3,yu=10,O5={resolution:20,controlPointAdditionDistance:6,controlPointDeletionDistance:6,showControlPointsConnectors:!1,controlPointAdditionEnabled:!0,controlPointDeletionEnabled:!0};var fi;(function(i){i.Cardinal="CARDINAL",i.Linear="LINEAR",i.CatmullRom="CATMULLROM",i.BSpline="BSPLINE"})(fi||(fi={}));var zr;(function(i){i.AddControlPoint="addControlPoint",i.DeleteControlPoint="deleteControlPoint"})(zr||(zr={}));const R5=["CatmullRomSplineROI","LinearSplineROI","BSplineROI","CardinalSplineROI"];class ka extends ws{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{preventHandleOutsideImage:!1,calculateStats:!0,allowOpenSplines:!1,simplifiedSpline:!1,getTextLines:N5,contourHoleAdditionModifierKey:vn.Shift,decimate:{enabled:!1,epsilon:.1},spline:{configuration:{[fi.Cardinal]:{Class:Fr,scale:.5},[fi.CatmullRom]:{Class:IS},[fi.Linear]:{Class:wS},[fi.BSpline]:{Class:vS,controlPointAdditionEnabled:!1,controlPointDeletionEnabled:!1,showControlPointsConnectors:!0}},type:fi.CatmullRom,drawPreviewEnabled:!0,enableTwoPointPreview:!1,touchCloseCurveDistance:36,lastControlPointDeletionKeys:["Backspace","Delete"]},actions:{[zr.AddControlPoint]:{method:"addControlPointCallback",bindings:[{mouseButton:Fo.Primary,modifierKey:vn.Shift}]},[zr.DeleteControlPoint]:{method:"deleteControlPointCallback",bindings:[{mouseButton:Fo.Primary,modifierKey:vn.Ctrl}]}}}}){super(t,n),this.splineToolNames=["CatmullRomSplineROI","LinearSplineROI","BSplineROI","CardinalSplineROI"],this.handlesMultiTouchGestures=!0,this.isHandleOutsideImage=!1,this.fireChangeOnUpdate=null,this.isPointNearTool=(e,o,s,a)=>{const{instance:r}=o.data.spline;return r?r.isPointNearCurve(s,a):!1},this.toolSelectedCallback=(e,o)=>{const s=e.detail,{element:a}=s;o.highlighted=!0;const r=ft(a,this.getToolName());this.editData={annotation:o,viewportIdsToRender:r,movingTextBox:!1},this._activateModify(a),V(r),e.preventDefault()},this.handleSelectedCallback=(e,o,s)=>{const a=e.detail,{element:r}=a,{data:c}=o;o.highlighted=!0;let l=!1,d;if(s.worldPosition)l=!0;else{const{points:h}=c.handles;d=h.findIndex(f=>f===s)}const u=ft(r,this.getToolName());this.editData={annotation:o,viewportIdsToRender:u,handleIndex:d,movingTextBox:l},this._activateModify(r),V(u),e.preventDefault()},this._endCallback=e=>{const o=e.detail,{element:s}=o,{annotation:a,viewportIdsToRender:r,newAnnotation:c,contourHoleProcessingEnabled:l}=this.editData,{data:d}=a;a.autoGenerated=!1,d.handles.activeHandleIndex=null,this._deactivateModify(s),this._deactivateDraw(s);const u=N(s),h=this.getTargetImageData(this.getTargetId(u.viewport)),{imageData:f,dimensions:g}=h;this.isHandleOutsideImage=d.handles.points.map(p=>wn(f,p)).some(p=>!gn(p,g)),this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&Gt(a.annotationUID);const m=c?Bt.Completed:Bt.HandlesUpdated;this.fireChangeOnUpdate?(this.fireChangeOnUpdate.annotationUID=a.annotationUID,this.fireChangeOnUpdate.changeType=m):this.fireChangeOnUpdate={annotationUID:a.annotationUID,changeType:m,contourHoleProcessingEnabled:l},V(r),this.doneEditMemo(),this.editData=null,this.isDrawing=!1},this._keyDownCallback=e=>{const o=e.detail,{element:s}=o,a=o.key??"",{lastControlPointDeletionKeys:r}=this.configuration.spline;if(!r.includes(a))return;const{annotation:l}=this.editData,{data:d}=l;if(d.handles.points.length===OS){this.cancel(s);return}else{const u=d.handles.points.length-1;this._deleteControlPointByIndex(s,l,u)}e.preventDefault()},this._mouseMoveCallback=e=>{const{drawPreviewEnabled:o}=this.configuration.spline;if(!o)return;const{element:s}=e.detail,{renderingEngine:a}=N(s),r=ft(s,this.getToolName());this.editData.lastCanvasPoint=e.detail.currentPoints.canvas,this.editData.closeCurveDistance=e.type===E.TOUCH_DRAG?this.configuration.spline.touchCloseCurveDistance:yu,V(r),e.preventDefault()},this._mouseDownCallback=e=>{const o=e.type===E.TOUCH_TAP||e.type===E.TOUCH_END,s=e.type===E.TOUCH_TAP&&e.detail.taps>=2,a=e.type===E.MOUSE_DOUBLE_CLICK||s;if(s&&this.isTouchTapEchoOfLiftCommit(e.detail.currentPoints.canvas))return;const{annotation:r,viewportIdsToRender:c}=this.editData,{data:l}=r;if(l.contour.closed)return;this.doneEditMemo();const d=e.detail,{currentPoints:u,element:h}=d,{canvas:f,world:g}=u;let m=l.handles.points.length>=2&&a&&!this.configuration.allowOpenSplines,p=!0;if(l.handles.points.length&&this.createMemo(h,r,{newAnnotation:l.handles.points.length===1}),l.handles.points.length>=3){this.createMemo(h,r);const{instance:I}=l.spline,w=o?this.configuration.spline.touchCloseCurveDistance:yu;I.getClosestControlPointWithinDistance(f,w)?.index===0&&(p=!1,m=!this.configuration.allowOpenSplines)}p&&l.handles.points.push(g),l.contour.closed=l.contour.closed||m,r.invalidated=!0,V(c);const v=a&&this.configuration.allowOpenSplines&&l.handles.points.length>=3;(l.contour.closed||v)&&this._endCallback(e),e.preventDefault()},this._touchDragDuringDrawCallback=e=>{e.detail.currentPointsList.length>1||this._mouseMoveCallback(e)},this._touchEndDuringDrawCallback=e=>{const{startPointsList:o,currentPointsList:s,startPoints:a,currentPoints:r}=e.detail;o.length>1||s.length>1||ro(a.canvas,r.canvas)<=Ml.TOUCH_TAP_MAX_CANVAS_DISTANCE||(this.recordTouchLiftCommit(r.canvas),this._mouseDownCallback(e))},this._dragCallback=e=>{this.isDrawing=!0;const o=e.detail,{element:s}=o,{annotation:a,viewportIdsToRender:r,handleIndex:c,movingTextBox:l,newAnnotation:d}=this.editData,{data:u}=a;if(this.createMemo(s,a,{newAnnotation:d}),l){const{deltaPoints:g}=o,m=g.world,{textBox:p}=u.handles,{worldPosition:v}=p;v[0]+=m[0],v[1]+=m[1],v[2]+=m[2],p.hasMoved=!0}else if(c===void 0){const{deltaPoints:g}=o,m=g.world;this.moveAnnotation(a,m)}else{const{currentPoints:g}=o,m=g.world;u.handles.points[c]=[...m],a.invalidated=!0}this.editData.hasMoved=!0;const h=N(s),{renderingEngine:f}=h;V(r)},this.triggerAnnotationCompleted=(e,o)=>{const s=E.ANNOTATION_COMPLETED,a={annotation:e,changeType:Bt.Completed,contourHoleProcessingEnabled:o};Rt(Z,s,a)},this.triggerAnnotationModified=(e,o,s=Bt.StatsUpdated)=>{const{viewportId:a,renderingEngineId:r}=o,c=E.ANNOTATION_MODIFIED;Rt(Z,c,{annotation:e,viewportId:a,renderingEngineId:r,changeType:s})},this.triggerChangeEvent=(e,o,s=Bt.StatsUpdated,a)=>{s===Bt.Completed?this.triggerAnnotationCompleted(e,a):this.triggerAnnotationModified(e,o,s)},this._activateDraw=e=>{$.isInteractingWithTool=!0,e.addEventListener(E.KEY_DOWN,this._keyDownCallback),e.addEventListener(E.MOUSE_MOVE,this._mouseMoveCallback),e.addEventListener(E.MOUSE_DOWN,this._mouseDownCallback),e.addEventListener(E.MOUSE_DOUBLE_CLICK,this._mouseDownCallback),e.addEventListener(E.TOUCH_TAP,this._mouseDownCallback),e.addEventListener(E.TOUCH_DRAG,this._touchDragDuringDrawCallback),e.addEventListener(E.TOUCH_END,this._touchEndDuringDrawCallback)},this._deactivateDraw=e=>{$.isInteractingWithTool=!1,e.removeEventListener(E.KEY_DOWN,this._keyDownCallback),e.removeEventListener(E.MOUSE_MOVE,this._mouseMoveCallback),e.removeEventListener(E.MOUSE_DOWN,this._mouseDownCallback),e.removeEventListener(E.MOUSE_DOUBLE_CLICK,this._mouseDownCallback),e.removeEventListener(E.TOUCH_TAP,this._mouseDownCallback),e.removeEventListener(E.TOUCH_DRAG,this._touchDragDuringDrawCallback),e.removeEventListener(E.TOUCH_END,this._touchEndDuringDrawCallback)},this._renderStats=(e,o,s)=>{const a=e.data,{viewport:r}=o,c=this.getTargetId(r);if(!a.spline.instance.closed)return;const l={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:o.viewport.id,annotationUID:e.annotationUID},d=this.configuration.getTextLines(a,c);if(!d||d.length===0)return;const u=a.handles.points.map(h=>r.worldToCanvas(h));this.renderLinkedTextBoxAnnotation({enabledElement:o,svgDrawingHelper:s,annotation:e,styleSpecifier:l,textLines:d,canvasCoordinates:u,textBoxUID:"textBox"})},this.addControlPointCallback=(e,o)=>{const{data:s}=o,a=s.spline.type,r=this._getSplineConfig(a),c=r.controlPointAdditionDistance;if(r.controlPointAdditionEnabled===!1)return;const l=e.detail,{element:d}=l,u=N(d),{renderingEngine:h,viewport:f}=u,{canvasToWorld:g}=f,{instance:m}=s.spline,p=e.detail.currentPoints.canvas,v=m.getClosestPoint(p);if(v.distance>c)return;const{index:I,point:w}=m.addControlPointAtU(v.uValue);s.handles.points.splice(I,0,g(w)),o.invalidated=!0;const C=ft(d,this.getToolName());V(C)},this.deleteControlPointCallback=(e,o)=>{const s=o.data.spline.type,a=this._getSplineConfig(s),r=a.controlPointDeletionDistance;if(a.controlPointDeletionEnabled===!1)return;const c=e.detail,{element:l,currentPoints:d}=c,{canvas:u}=d,{instance:h}=o.data.spline,f=h.getClosestControlPointWithinDistance(u,r);f&&this._deleteControlPointByIndex(l,o,f.index)},this._calculateCachedStats=(e,o)=>{if(!this.configuration.calculateStats)return;const s=e.data;if(!s.contour.closed)return;const a=N(o);if(!a)return;const{viewport:r}=a,{cachedStats:c}=s,{polyline:l}=s.contour,d=Object.keys(c);for(let h=0;h<d.length;h++){const f=d[h],g=this.getTargetImageData(f);if(!g)continue;const{metadata:m}=g,p=l.map(T=>r.worldToCanvas(T)),v=p[0],I=r.canvasToWorld(v),w=r.canvasToWorld([v[0]+1,v[1]]),C=r.canvasToWorld([v[0],v[1]+1]),S=ke(I,w),b=ke(I,C),{imageData:_}=g,{areaUnit:y}=ao(g,()=>{const{maxX:T,maxY:P,minX:x,minY:M}=Ei(p),L=r.canvasToWorld([x,M]),R=wn(_,L),U=r.canvasToWorld([T,P]),W=wn(_,U);return[R,W]}),D=ms(p)*S*b;c[f]={Modality:m.Modality,area:D,areaUnit:y}}const u=e.invalidated;return e.invalidated=!1,u&&this.triggerAnnotationModified(e,a,Bt.StatsUpdated),c},this._throttledCalculateCachedStats=Un(this._calculateCachedStats,100,{trailing:!0}),this.annotationCompletedBinded=this.annotationCompleted.bind(this)}annotationCompleted(t){const{sourceAnnotation:n}=t.detail;!this.splineToolNames.includes(n?.metadata?.toolName)||!this.configuration.simplifiedSpline||!this.isContourSegmentationTool()||pf(n)}initializeListeners(){Z.addEventListener(E.ANNOTATION_COMPLETED,this.annotationCompletedBinded)}removeListeners(){Z.removeEventListener(E.ANNOTATION_COMPLETED,this.annotationCompletedBinded)}onSetToolEnabled(){this.initializeListeners()}onSetToolActive(){this.initializeListeners()}onSetToolDisabled(){this.removeListeners()}addNewAnnotation(t){const n=t.detail,{currentPoints:e,element:o}=n,{canvas:s}=e,a=Pa(t.detail.event)===this.configuration.contourHoleAdditionModifierKey,r=this.createAnnotation(t);this.isDrawing=!0,this.addAnnotation(r,o);const c=ft(o,this.getToolName());return this.editData={annotation:r,viewportIdsToRender:c,movingTextBox:!1,newAnnotation:!0,hasMoved:!1,lastCanvasPoint:s,contourHoleProcessingEnabled:a},this._activateDraw(o),t.preventDefault(),V(c),r}cancel(t){if(!this.isDrawing)return;this.isDrawing=!1,this._deactivateDraw(t),this._deactivateModify(t);const{annotation:n,viewportIdsToRender:e,newAnnotation:o}=this.editData;o&&Gt(n.annotationUID),super.cancelAnnotation(n);const s=N(t),{renderingEngine:a}=s;return V(e),this.editData=null,n.annotationUID}isContourSegmentationTool(){return!1}renderAnnotationInstance(t){const{enabledElement:n,targetId:e,svgDrawingHelper:o,annotationStyle:s}=t,{viewport:a}=n,{worldToCanvas:r}=a,{element:c}=a,l=t.annotation,{annotationUID:d,data:u,highlighted:h}=l,{handles:f}=u,{points:g,activeHandleIndex:m}=f,p=this.editData?.newAnnotation,{lineWidth:v,lineDash:I,color:w,locked:C}=s,S=g.map(L=>r(L)),{drawPreviewEnabled:b}=this.configuration.spline;l.data.spline&&!l.data.spline.instance&&(l.data.spline.instance=new(this._getSplineConfig(l.data.spline.type)).Class);const _=l.data.spline.type,y=this._getSplineConfig(_),D=l.data.spline.instance,T=Xi(l);if(T.findIndex(L=>!L)!==-1)throw new Error(`Can't find annotation for child ${l.childAnnotationUIDs.join()}`);[l,...T].filter(L=>this._isSplineROIAnnotation(L)).forEach(L=>{const U=this._updateSplineInstance(c,L).getPolylinePoints();this.updateContourPolyline(L,{points:U,closed:u.contour.closed,targetWindingDirection:Qe.Clockwise},a,{updateWindingDirection:u.contour.closed})}),super.renderAnnotationInstance(t),!u.cachedStats[e]||u.cachedStats[e].areaUnit==null?(u.cachedStats[e]={Modality:null,area:null,areaUnit:null},this._calculateCachedStats(l,c)):l.invalidated&&this._throttledCalculateCachedStats(l,c);let M;if(!C&&!this.editData&&m!==null&&(M=[S[m]]),(M||p||h)&&xe(o,d,"0",S,{color:w,lineWidth:v,handleRadius:"3"}),b&&D.numControlPoints>=1&&this.editData?.lastCanvasPoint&&!D.closed){const{lastCanvasPoint:L}=this.editData,{enableTwoPointPreview:R}=this.configuration.spline;if(D.numControlPoints===1&&R){const W=[S[0],L];Eo(o,d,"previewSplineChange",W,{color:"#9EA0CA",lineDash:I,lineWidth:1})}else if(D.numControlPoints>1){const U=D.getPreviewPolylinePoints(L,this.editData?.closeCurveDistance??yu);Eo(o,d,"previewSplineChange",U,{color:"#9EA0CA",lineDash:I,lineWidth:1})}}if(y.showControlPointsConnectors){const L=[...S];D.closed&&L.push(S[0]),Eo(o,d,"controlPointsConnectors",L,{color:"rgba(255, 255, 255, 0.5)",lineWidth:1})}return this._renderStats(l,n,o),this.fireChangeOnUpdate?.annotationUID===d&&(this.triggerChangeEvent(l,n,this.fireChangeOnUpdate.changeType,this.fireChangeOnUpdate.contourHoleProcessingEnabled),this.fireChangeOnUpdate=null),l.invalidated=!1,!0}createInterpolatedSplineControl(t){if(t.data.handles.points?.length)return;const{polyline:n}=t.data.contour;if(!n||!n.length)return;t.data.handles.points=[];const{points:e}=t.data.handles,o=Math.max(10,Math.floor(n.length/20));for(let s=0;s<n.length-o;s+=o)e.push(n[s]);e.push(n[n.length-1])}isSplineAnnotation(t){return R5.includes(t?.metadata?.toolName)}createSplineObjectFromType(t,n){const e=this._getSplineConfig(n),o=new e.Class;t.data.spline={type:e.type,instance:o,resolution:e.resolution}}createAnnotation(t){const n=super.createAnnotation(t),{world:e}=t.detail.currentPoints,{type:o}=this.configuration.spline,s=this._getSplineConfig(o),a=new s.Class,r=()=>({type:s.type,instance:a,resolution:s.resolution});let c;return this.configuration.interpolation?.enabled&&(c=l=>{l.data.spline||=r(),this.createInterpolatedSplineControl(l)}),Hn(n,{data:{handles:{points:[[...e]]},spline:r(),cachedStats:{}},onInterpolationComplete:c})}_deleteControlPointByIndex(t,n,e){const o=N(t),{points:s}=n.data.handles;s.length===3?Gt(n.annotationUID):s.splice(e,1);const{renderingEngine:a}=o,r=ft(t,this.getToolName());n.invalidated=!0,V(r)}_isSplineROIAnnotation(t){return!!t.data?.spline}_getSplineConfig(t){const{configuration:n}=this,e=n.spline.configuration;return Object.assign({type:t},O5,e[t])}_updateSplineInstance(t,n){const e=N(t),{viewport:o}=e,{worldToCanvas:s}=o,{data:a}=n,{type:r,instance:c}=n.data.spline,l=this._getSplineConfig(r),u=a.handles.points.map(s),h=l.resolution!==void 0?parseInt(l.resolution):void 0,f=l.scale!==void 0?parseFloat(l.scale):void 0;return c.setControlPoints(u),c.closed=!!a.contour.closed,!c.fixedResolution&&h!==void 0&&c.resolution!==h&&(c.resolution=h,n.invalidated=!0),c instanceof Fr&&!c.fixedScale&&f!==void 0&&c.scale!==f&&(c.scale=f,n.invalidated=!0),c}}Ml=ka;ka.toolName="SplineROI";ka.SplineTypes=fi;ka.Actions=zr;ka.hydrate=(i,t,n)=>{const e=le(i);if(!e)return;if(t.length<OS){console.warn("Spline requires at least 3 control points");return}const{FrameOfReferenceUID:o,referencedImageId:s,viewPlaneNormal:a,viewUp:r,instance:c,viewport:l}=Ml.hydrateBase(Ml,e,t,n),d=n?.splineType||fi.CatmullRom,h=c._getSplineConfig(d).Class,f=new h,{toolInstance:g,...m}=n||{},p={annotationUID:n?.annotationUID||Se(),data:{handles:{points:t},label:"",cachedStats:{},spline:{type:d,instance:f},contour:{closed:!0}},highlighted:!1,autoGenerated:!1,invalidated:!0,isLocked:!1,isVisible:!0,metadata:{toolName:c.getToolName(),viewPlaneNormal:a,FrameOfReferenceUID:o,referencedImageId:s,...m}};Nt(p,l.element),V([l.id])};function N5(i,t){const n=i.cachedStats[t],{area:e,isEmptyArea:o,areaUnit:s}=n,a=[];if(e){const r=o?"Area: Oblique not supported":`Area: ${de(e)} ${s}`;a.push(r)}return a}class k5 extends ka{constructor(t){const n=Hn({configuration:{calculateStats:!1}},t);super(n),this.annotationCutMergeCompletedBinded=this.annotationCutMergeCompleted.bind(this)}isContourSegmentationTool(){return!0}initializeListeners(){Z.addEventListener(E.ANNOTATION_CUT_MERGE_PROCESS_COMPLETED,this.annotationCutMergeCompletedBinded)}removeListeners(){Z.removeEventListener(E.ANNOTATION_CUT_MERGE_PROCESS_COMPLETED,this.annotationCutMergeCompletedBinded)}annotationCutMergeCompleted(t){const{sourceAnnotation:n}=t.detail;this.toolName!==n?.metadata?.toolName||!this.splineToolNames.includes(n?.metadata?.toolName)||!this.configuration.simplifiedSpline||!n?.annotationUID||!ne(n.annotationUID)||pf(n)}}k5.toolName="SplineContourSegmentationTool";class U5{constructor({numBits:t,getPriority:n,areEqual:e}){this._bucketCount=1<<t,this._mask=this._bucketCount-1,this._size=0,this._currentBucketIndex=0,this._buckets=this._buildArray(this._bucketCount),this._getPriority=typeof n<"u"?n:o=>o,this._areEqual=typeof e=="function"?e:(o,s)=>o===s}push(t){const n=this._getBucketIndex(t),e=this._buckets[n],o={value:t,next:e};this._buckets[n]=o,this._size++}pop(){if(this._size===0)throw new Error("Cannot pop because the queue is empty.");for(;this._buckets[this._currentBucketIndex]===null;)this._currentBucketIndex=(this._currentBucketIndex+1)%this._bucketCount;const t=this._buckets[this._currentBucketIndex];return this._buckets[this._currentBucketIndex]=t.next,this._size--,t.value}remove(t){if(!t)return!1;const n=this._getBucketIndex(t),e=this._buckets[n];let o=e,s;for(;o!==null&&!this._areEqual(t,o.value);)s=o,o=o.next;return o===null?!1:(o===e?this._buckets[n]=o.next:s.next=o.next,this._size--,!0)}isEmpty(){return this._size===0}_getBucketIndex(t){return this._getPriority(t)&this._mask}_buildArray(t){const n=new Array(t);return n.fill(null),n}}const xu=4294967295,V5=2/(3*Math.PI);class Al{constructor(t,n,e){this._getPointIndex=(s,a)=>{const{width:r}=this;return s*r+a},this._getPointCoordinate=s=>{const a=s%this.width,r=Math.floor(s/this.width);return[a,r]},this._getPointCost=s=>Math.round(this.searchGranularity*this.costs[s]);const o=t.length;this.searchGranularityBits=8,this.searchGranularity=1<<this.searchGranularityBits,this.width=n,this.height=e,this.grayscalePixelData=t,this.laplace=null,this.gradXNew=null,this.gradYNew=null,this.laplace=this._computeLaplace(),this.gradMagnitude=this._computeGradient(),this.gradXNew=this._computeGradientX(),this.gradYNew=this._computeGradientY(),this.visited=new Array(o),this.parents=new Uint32Array(o),this.costs=new Float32Array(o)}startSearch(t){const n=this._getPointIndex(t[1],t[0]);this.startPoint=null,this.visited.fill(!1),this.parents.fill(xu),this.costs.fill(1/0),this.priorityQueueNew=new U5({numBits:this.searchGranularityBits,getPriority:this._getPointCost}),this.startPoint=t,this.costs[n]=0,this.priorityQueueNew.push(n)}findMinNearby(t,n=2){const[e,o]=t,{costs:s}=this,a=[Math.max(0,e-n),Math.min(e+n+1,this.width)],r=[Math.max(0,o-n),Math.min(o+n+1,this.height)];let c=s[this._getPointIndex(o,e)]*.8,l=t;for(let d=a[0];d<a[1];d++)for(let u=r[0];u<r[1];u++){const h=1-(Math.abs(d-t[0])+Math.abs(u-t[1]))/n/2,g=s[this._getPointIndex(u,d)]*.8+h*.2;g<c&&(l=[d,u],c=g)}return l}findPathToPoint(t){if(!this.startPoint)throw new Error("There is no search in progress");const{startPoint:n,_getPointIndex:e,_getPointCoordinate:o}=this,s=e(n[1],n[0]),a=e(t[1],t[0]),{visited:r,parents:c,costs:l,priorityQueueNew:d}=this;if(a===s)return[];for(;!d.isEmpty()&&c[a]===xu;){const f=d.pop();if(r[f])continue;const g=o(f),m=this._getNeighborPoints(g);r[f]=!0;for(let p=0,v=m.length;p<v;p++){const I=m[p],w=e(I[1],I[0]),C=this._getWeightedDistance(g,I),S=l[f]+C;S<l[w]&&(l[w]!==1/0&&d.remove(w),l[w]=S,c[w]=f,d.push(w))}}const u=[];let h=a;for(;h!==xu;)u.push(o(h)),h=c[h];return u.reverse()}_getDeltaX(t,n){const{grayscalePixelData:e,width:o}=this;let s=this._getPointIndex(n,t);return t+1===o&&s--,e[s+1]-e[s]}_getDeltaY(t,n){const{grayscalePixelData:e,width:o,height:s}=this;let a=this._getPointIndex(n,t);return n+1===s&&(a-=o),e[a]-e[a+o]}_getGradientMagnitude(t,n){const e=this._getDeltaX(t,n),o=this._getDeltaY(t,n);return Math.sqrt(e*e+o*o)}_getLaplace(t,n){const{grayscalePixelData:e,_getPointIndex:o}=this,s=e[o(n-2,t)],a=e[o(n-1,t-1)],r=e[o(n-1,t)],c=e[o(n-1,t+1)],l=e[o(n,t-2)],d=e[o(n,t-1)],u=e[o(n,t)],h=e[o(n,t+1)],f=e[o(n,t+2)],g=e[o(n+1,t-1)],m=e[o(n+1,t)],p=e[o(n+1,t+1)],v=e[o(n+2,t)];let I=s;return I+=a+2*r+c,I+=l+2*d-16*u+2*h+f,I+=g+2*m+p,I+=v,I}_computeGradient(){const{width:t,height:n}=this,e=new Float32Array(t*n);let o=0,s=0,a=0,r=0;for(r=0;r<n-1;r++){for(a=0;a<t-1;a++)e[o]=this._getGradientMagnitude(a,r),s=Math.max(e[o],s),o++;e[o]=e[o-1],o++}for(let c=e.length;o<c;o++)e[o]=e[o-t];for(let c=0,l=e.length;c<l;c++)e[c]=1-e[c]/s;return e}_computeLaplace(){const{width:t,height:n,_getPointIndex:e}=this,o=new Float32Array(t*n);o.fill(1,0,e(2,0));for(let s=2;s<n-2;s++){o[e(s,0)]=1,o[e(s,1)]=1;for(let a=2;a<t-2;a++)o[e(s,a)]=this._getLaplace(a,s)>.33?0:1;o[e(s,t-2)]=1,o[e(s,t-1)]=1}return o.fill(1,e(n-2,0)),o}_computeGradientX(){const{width:t,height:n}=this,e=new Float32Array(t*n);let o=0;for(let s=0;s<n;s++)for(let a=0;a<t;a++)e[o++]=this._getDeltaX(a,s);return e}_computeGradientY(){const{width:t,height:n}=this,e=new Float32Array(t*n);let o=0;for(let s=0;s<n;s++)for(let a=0;a<t;a++)e[o++]=this._getDeltaY(a,s);return e}_getGradientUnitVector(t,n){const{gradXNew:e,gradYNew:o,_getPointIndex:s}=this,a=e[s(n,t)],r=o[s(n,t)];let c=Math.sqrt(a*a+r*r);return c=Math.max(c,1e-100),[a/c,r/c]}_getGradientDirection(t,n,e,o){const s=this._getGradientUnitVector(t,n),a=this._getGradientUnitVector(e,o);let r=s[1]*(e-t)-s[0]*(o-n),c=a[1]*(e-t)-a[0]*(o-n);r<0&&(r=-r,c=-c),t!==e&&n!==o&&(r*=Math.SQRT1_2,c*=Math.SQRT1_2),c=Math.min(Math.max(c,-1),1);const l=V5*(Math.acos(Math.min(r,1))+Math.acos(c));return isNaN(l)||!isFinite(l)?(console.warn("Found non-direction:",t,n,e,o,r,c,l),1):l}getCost(t,n){return this._getWeightedDistance(t,n)}_getWeightedDistance(t,n){const{_getPointIndex:e,width:o,height:s}=this,[a,r]=t,[c,l]=n;if(c<0||c>=o||l<0||l>=s)return 1;if(a<0||r<0||a>=o||r>=s)return 0;const d=e(l,c);let u=this.gradMagnitude[d];(a===c||r===l)&&(u*=Math.SQRT1_2);const h=this.laplace[d],f=this._getGradientDirection(a,r,c,l);return .43*u+.43*h+.11*f}_getNeighborPoints(t){const{width:n,height:e}=this,o=[],s=Math.max(t[0]-1,0),a=Math.max(t[1]-1,0),r=Math.min(t[0]+1,n-1),c=Math.min(t[1]+1,e-1);for(let l=a;l<=c;l++)for(let d=s;d<=r;d++)(d!==t[0]||l!==t[1])&&o.push([d,l]);return o}static createInstanceFromRawPixelData(t,n,e,o){const s=t.length,a=new Float32Array(s),{lower:r,upper:c}=o,l=c-r;for(let d=0,u=t.length;d<u;d++)a[d]=Math.max(0,Math.min(1,(t[d]-r)/l));return new Al(a,n,e)}}class ai{constructor(t,n){this.pointArray=t?t.slice():[],this._controlPointIndexes=n?n.slice():[]}getPoint(t){return this.pointArray[t]}getLastPoint(){return this.pointArray[this.pointArray.length-1]}isControlPoint(t){const n=this.pointArray.indexOf(t);if(n!==-1)return this._controlPointIndexes.indexOf(n)!==-1;throw new Error("Error: isControlPoint called with not in list point.")}addPoint(t){this.pointArray.push(t)}addControlPoint(t){const n=this.pointArray.indexOf(t);if(n!==-1)this._controlPointIndexes.push(n);else throw new Error("Cannot mark a non registered point as control point.")}getControlPoints(){return this._controlPointIndexes.map(t=>this.pointArray[t])}getNumControlPoints(){return this._controlPointIndexes.length}removeLastControlPoint(){this._controlPointIndexes.length&&this._controlPointIndexes.pop()}getLastControlPoint(){if(this._controlPointIndexes.length)return this.pointArray[this._controlPointIndexes[this._controlPointIndexes.length-1]]}removeLastPoints(t){this.pointArray.splice(this.pointArray.length-t,t)}addPoints(t){this.pointArray=this.pointArray.concat(t)}prependPath(t){const n=t.pointArray.length,e=[];this.pointArray=t.pointArray.concat(this.pointArray);for(let o=0;o<this._controlPointIndexes.length;++o)e[o]=this._controlPointIndexes[o]+n;this._controlPointIndexes=t._controlPointIndexes.concat(e)}appendPath(t){this.addPoints(t.pointArray),t._controlPointIndexes.forEach(n=>this._controlPointIndexes.push(n))}}const F5=10**2;class Ld extends ws{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{getTextLines:G5,calculateStats:!0,preventHandleOutsideImage:!1,contourHoleAdditionModifierKey:vn.Shift,snapHandleNearby:2,touchCloseCurveDistance:36,interpolation:{enabled:!1,nearestEdge:2,showInterpolationPolyline:!1},decimate:{enabled:!1,epsilon:.1},actions:{cancelInProgress:{method:"cancelInProgress",bindings:[{key:"Escape"}]}}}}){super(t,n),this.handlesMultiTouchGestures=!0,this.isHandleOutsideImage=!1,this.isPointNearTool=(e,o,s,a)=>{const r=N(e),{viewport:c}=r,l=a*a,d=o.data.contour.polyline.map(h=>c.worldToCanvas(h));let u=d[d.length-1];for(let h=0;h<d.length;h++){const f=d[h];if(tc(u,f,s)<=l)return!0;u=f}return!1},this.toolSelectedCallback=(e,o)=>{const s=e.detail,{element:a}=s;o.highlighted=!0;const r=ft(a,this.getToolName());this.editData={annotation:o,viewportIdsToRender:r,movingTextBox:!1},this._activateModify(a),V(r),e.preventDefault()},this.handleSelectedCallback=(e,o,s)=>{const a=e.detail,{element:r}=a,{data:c}=o;o.highlighted=!0;let l=!1,d;if(s.worldPosition)l=!0;else{const{points:h}=c.handles;d=h.findIndex(f=>f===s)}const u=ft(r,this.getToolName());this.editData={annotation:o,viewportIdsToRender:u,handleIndex:d,movingTextBox:l},this._activateModify(r),V(u),e.preventDefault()},this._endCallback=(e,o=!1)=>{const s=e.detail,{element:a}=s,{annotation:r,viewportIdsToRender:c,newAnnotation:l,contourHoleProcessingEnabled:d}=this.editData,{data:u}=r;this.doneEditMemo(),u.handles.activeHandleIndex=null,this._deactivateModify(a),this._deactivateDraw(a);const h=N(a);if(this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage||o){Gt(r.annotationUID),this.clearEditData(),V(c);return}V(c);const f=l?Bt.Completed:Bt.HandlesUpdated;this.triggerChangeEvent(r,h,f,d),this.clearEditData()},this.triggerChangeEvent=(e,o,s=Bt.StatsUpdated,a=!1)=>{s===Bt.Completed?Hl(e,a):zt(e,o.viewport.element,s)},this._mouseDownCallback=e=>{const o=e.type===E.TOUCH_TAP||e.type===E.TOUCH_END,s=e.type===E.TOUCH_TAP&&e.detail.taps>=2,a=e.type===E.MOUSE_DOUBLE_CLICK||s;if(s&&this.isTouchTapEchoOfLiftCommit(e.detail.currentPoints.canvas))return;const{annotation:r,viewportIdsToRender:c,worldToSlice:l,sliceToWorld:d,newAnnotation:u}=this.editData;if(this.editData.closed)return;const h=e.detail,{element:f}=h,{currentPoints:g}=h,{canvas:m,world:p}=g;let v=p;const I=N(f),{viewport:w}=I,C=this.editData.currentPath.getControlPoints();let S=C.length>=2&&a;if(this.doneEditMemo(),this.createMemo(f,r,{newAnnotation:u&&C.length===1}),C.length>=2){const y={index:-1,distSquared:1/0},D=o?this.configuration.touchCloseCurveDistance**2:F5;for(let T=0,P=C.length;T<P;T++){const x=C[T],M=d(x),L=w.worldToCanvas(M),R=wi(m,L);R<=D&&R<y.distSquared&&(y.distSquared=R,y.index=T)}y.index===0&&(S=!0)}const{snapHandleNearby:b}=this.configuration;if(b&&!this.editData.closed){const y=new ai,D=this.scissors.findMinNearby(l(p),1),T=this.scissors.findPathToPoint(D);y.addPoints(T),y.prependPath(this.editData.confirmedPath),v=d(D),this.editData.currentPath=y}this.editData.closed=this.editData.closed||S,this.editData.confirmedPath=this.editData.currentPath;const _=this.editData.currentPath.getLastPoint();this.editData.confirmedPath.addControlPoint(_),r.data.handles.points.push(d(_)),this.scissors.startSearch(l(v)),r.invalidated=!0,V(c),this.editData.closed&&(S&&(r.data.isOpenUShapeContour="lineSegment"),this.updateAnnotation(this.editData.confirmedPath),this._endCallback(e)),e.preventDefault()},this._mouseMoveCallback=e=>{const{element:o,currentPoints:s}=e.detail,{world:a,canvas:r}=s,c=ft(o,this.getToolName());this.editData.lastCanvasPoint=r;const{width:l,height:d}=this.scissors,{worldToSlice:u}=this.editData,h=u(a);if(h[0]<0||h[1]<0||h[0]>=l||h[1]>=d)return;const f=this.scissors.findPathToPoint(h),g=new ai;g.addPoints(f),g.prependPath(this.editData.confirmedPath),this.editData.currentPath=g,V(c),e.preventDefault()},this._touchDragDuringDrawCallback=e=>{e.detail.currentPointsList.length>1||this._mouseMoveCallback(e)},this._touchEndDuringDrawCallback=e=>{const{startPointsList:o,currentPointsList:s,startPoints:a,currentPoints:r}=e.detail;o.length>1||s.length>1||ro(a.canvas,r.canvas)<=Ld.TOUCH_TAP_MAX_CANVAS_DISTANCE||(this.recordTouchLiftCommit(r.canvas),this._mouseDownCallback(e))},this._dragCallback=e=>{this.isDrawing=!0;const o=e.detail,{element:s}=o,{annotation:a,viewportIdsToRender:r,movingTextBox:c,handleIndex:l,newAnnotation:d}=this.editData;this.createMemo(s,a,{newAnnotation:d});const{data:u}=a;if(c){const{deltaPoints:h}=o,f=h.world,{textBox:g}=u.handles,{worldPosition:m}=g;m[0]+=f[0],m[1]+=f[1],m[2]+=f[2],g.hasMoved=!0}else if(l===void 0)console.warn("Drag annotation not implemented");else{const{currentPoints:h}=o,f=h.world;this.editHandle(f,s,a,l)}this.editData.hasMoved=!0,V(r)},this.cancel=e=>{if(!this.isDrawing)return;this.isDrawing=!1,this._deactivateDraw(e),this._deactivateModify(e);const{annotation:o,viewportIdsToRender:s,newAnnotation:a}=this.editData;return a&&Gt(o.annotationUID),V(s),this.doneEditMemo(),this.scissors=null,o.annotationUID},this._activateDraw=e=>{$.isInteractingWithTool=!0,e.addEventListener(E.MOUSE_MOVE,this._mouseMoveCallback),e.addEventListener(E.MOUSE_DOWN,this._mouseDownCallback),e.addEventListener(E.MOUSE_DOUBLE_CLICK,this._mouseDownCallback),e.addEventListener(E.TOUCH_TAP,this._mouseDownCallback),e.addEventListener(E.TOUCH_DRAG,this._touchDragDuringDrawCallback),e.addEventListener(E.TOUCH_END,this._touchEndDuringDrawCallback)},this._deactivateDraw=e=>{$.isInteractingWithTool=!1,e.removeEventListener(E.MOUSE_MOVE,this._mouseMoveCallback),e.removeEventListener(E.MOUSE_DOWN,this._mouseDownCallback),e.removeEventListener(E.MOUSE_DOUBLE_CLICK,this._mouseDownCallback),e.removeEventListener(E.TOUCH_TAP,this._mouseDownCallback),e.removeEventListener(E.TOUCH_DRAG,this._touchDragDuringDrawCallback),e.removeEventListener(E.TOUCH_END,this._touchEndDuringDrawCallback)},this._calculateCachedStats=(e,o)=>{if(!this.configuration.calculateStats)return;const s=e.data;if(!s.contour.closed)return;const a=N(o),{viewport:r}=a,{cachedStats:c}=s,{polyline:l}=s.contour,d=Object.keys(c);for(let h=0;h<d.length;h++){const f=d[h],g=this.getTargetImageData(f);if(!g)continue;const{metadata:m}=g,p=l.map(T=>r.worldToCanvas(T)),v=p[0],I=r.canvasToWorld(v),w=r.canvasToWorld([v[0]+1,v[1]]),C=r.canvasToWorld([v[0],v[1]+1]),S=ke(I,w),b=ke(I,C),{imageData:_}=g,{areaUnit:y}=ao(g,()=>{const{maxX:T,maxY:P,minX:x,minY:M}=Ei(p),L=r.canvasToWorld([x,M]),R=wn(_,L),U=r.canvasToWorld([T,P]),W=wn(_,U);return[R,W]}),D=ms(p)*S*b;c[f]={Modality:m.Modality,area:D,areaUnit:y}}const u=e.invalidated;return e.invalidated=!1,u&&this.triggerAnnotationModified(e,a,Bt.StatsUpdated),c},this._renderStats=(e,o,s)=>{const a=e.data,{viewport:r}=o,c=this.getTargetId(r);if(!a.contour.closed)return;const l={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:o.viewport.id,annotationUID:e.annotationUID},d=this.configuration.getTextLines(a,c);if(!d||d.length===0)return;const u=a.handles.points.map(h=>r.worldToCanvas(h));this.renderLinkedTextBoxAnnotation({enabledElement:o,svgDrawingHelper:s,annotation:e,styleSpecifier:l,textLines:d,canvasCoordinates:u,textBoxUID:"textBox"})},this.triggerAnnotationModified=(e,o,s=Bt.StatsUpdated)=>{const{viewportId:a,renderingEngineId:r}=o,c=E.ANNOTATION_MODIFIED;Rt(Z,c,{annotation:e,viewportId:a,renderingEngineId:r,changeType:s})},this._throttledCalculateCachedStats=Un(this._calculateCachedStats,100,{trailing:!0})}setupBaseEditData(t,n,e,o,s){const a=N(n),{viewport:r}=a;this.isDrawing=!0;const c=r.getImageData(),{imageData:l}=c;let d,u,h,f,g;if(!(r instanceof Xe))h=c.dimensions[0],f=c.dimensions[1],d=y=>{const D=wn(l,y);return[D[0],D[1]]},u=y=>Yc(l,[y[0],y[1],0]),g=c.scalarData;else if(r instanceof Xe){const y=Av(r),{sliceToIndexMatrix:D,indexToSliceMatrix:T}=y;d=P=>{const x=wn(l,P),M=Ue([0,0,0],x,T);return[M[0],M[1]]},u=P=>{const x=Ue([0,0,0],[P[0],P[1],0],D);return Yc(l,x)},g=y.scalarData,h=y.width,f=y.height}else throw new Error("Viewport not supported");g=hb(g,h,f);let m;const p=r;if(Sa(p)){const y=p.getSourceDataId();m=(y?p.getDisplaySetPresentation(y)?.voiRange:void 0)??p.getDefaultVOIRange(y)??void 0}else({voiRange:m}=r.getProperties());const v=d(t);this.scissors=Al.createInstanceFromRawPixelData(g,h,f,m),o&&(this.scissorsNext=Al.createInstanceFromRawPixelData(g,h,f,m),this.scissorsNext.startSearch(d(o))),this.scissors.startSearch(v);const I=!o,w=new ai,C=new ai,S=I?void 0:new ai;w.addPoint(v),w.addControlPoint(v);const b=ft(n,this.getToolName()),_=r.worldToCanvas(t);this.editData={annotation:e,viewportIdsToRender:b,newAnnotation:I,hasMoved:!1,lastCanvasPoint:_,confirmedPath:w,currentPath:C,confirmedPathNext:S,closed:!1,handleIndex:this.editData?.handleIndex??e.handles?.activeHandleIndex,worldToSlice:d,sliceToWorld:u,contourHoleProcessingEnabled:s}}addNewAnnotation(t){const n=t.detail,{currentPoints:e,element:o}=n,{world:s}=e,a=this.createAnnotation(t),r=Pa(t.detail.event)===this.configuration.contourHoleAdditionModifierKey;return this.setupBaseEditData(s,o,a,void 0,r),this.addAnnotation(a,o),this._activateDraw(o),t.preventDefault(),V(this.editData.viewportIdsToRender),a}clearEditData(){this.editData=null,this.scissors=null,this.scissorsNext=null,this.isDrawing=!1}editHandle(t,n,e,o){const{data:s}=e,{points:a}=s.handles,{length:r}=a,c=a[(o-1+r)%r],l=a[(o+1)%r];if(!this.editData?.confirmedPathNext){this.setupBaseEditData(c,n,e,l);const{polyline:w}=s.contour,C=new ai,S=new ai,{worldToSlice:b}=this.editData,_=oh(e,o-1),y=oh(e,o+1);if(y===-1||_===-1)throw new Error(`Can't find handle index ${y===-1&&l} ${_===-1&&c}`);o===0?S.addPoints(w.slice(y+1,_).map(b)):(C.addPoints(w.slice(0,_+1).map(b)),S.addPoints(w.slice(y,w.length).map(b))),this.editData.confirmedPath=C,this.editData.confirmedPathNext=S}const{editData:d,scissors:u}=this,{worldToSlice:h,sliceToWorld:f}=d,{activeHandleIndex:g}=s.handles;if(g==null)s.handles.activeHandleIndex=o;else if(g!==o)throw new Error(`Trying to edit a different handle than the one currently being edited ${o}!==${s.handles.activeHandleIndex}`);const m=h(t);if(m[0]<0||m[0]>=u.width||m[1]<0||m[1]>=u.height)return;a[o]=f(m);const p=u.findPathToPoint(m),v=this.scissorsNext.findPathToPoint(m),I=new ai;I.prependPath(d.confirmedPath),o!==0&&I.addPoints(p),I.addPoints(v.reverse()),I.appendPath(d.confirmedPathNext),o===0&&I.addPoints(p),d.currentPath=I,e.invalidated=!0,d.hasMoved=!0,d.closed=!0}renderAnnotation(t,n){return this.updateAnnotation(this.editData?.currentPath),super.renderAnnotation(t,n)}isContourSegmentationTool(){return!1}createAnnotation(t){const n=super.createAnnotation(t),{world:e}=t.detail.currentPoints;return Hn(n,{data:{handles:{points:[[...e]]}}})}cancelInProgress(t,n,e){if(!this.editData){this.undo();return}this._endCallback(e,!0)}renderAnnotationInstance(t){const{annotation:n,enabledElement:e,svgDrawingHelper:o,annotationStyle:s,targetId:a}=t,{viewport:r}=e,{element:c}=r,{worldToCanvas:l}=r,{annotationUID:d,data:u,highlighted:h}=n,{handles:f}=u,g=this.editData?.newAnnotation,{lineWidth:m,lineDash:p,color:v}=s;if(h||g&&n.annotationUID===this.editData?.annotation?.annotationUID){const w=f.points.map(l);xe(o,d,"0",w,{color:v,lineDash:p,lineWidth:m})}return super.renderAnnotationInstance(t),!u.cachedStats[a]||u.cachedStats[a]?.areaUnit===null?(u.cachedStats[a]={Modality:null,area:null,areaUnit:null},this._calculateCachedStats(n,c)):n.invalidated&&this._throttledCalculateCachedStats(n,c),this._renderStats(n,e,o),!0}updateAnnotation(t){if(!this.editData||!t)return;const{annotation:n,sliceToWorld:e,worldToSlice:o,closed:s,newAnnotation:a}=this.editData;let{pointArray:r}=t;r.length>1&&(r=[...r,r[0]]);const c=a&&s?Qe.Clockwise:void 0;this.updateContourPolyline(n,{points:r,closed:s,targetWindingDirection:c},{canvasToWorld:e,worldToCanvas:o})}}Ld.toolName="LivewireContour";function G5(i,t){const n=i.cachedStats[t],{area:e,areaUnit:o}=n,s=[];if(e){const a=`Area: ${de(e)} ${o}`;s.push(a)}return s}var RS;class NS extends Ld{updateInterpolatedAnnotation(t,n){this.editData||!t.invalidated||!t.data.handles.interpolationSources||(t.data.contour.originalPolyline=t.data.contour.polyline,queueMicrotask(()=>{if(!t.data.handles.interpolationSources)return;const{points:e}=t.data.handles,{element:o}=n.viewport;this.setupBaseEditData(e[0],o,t);const{length:s}=e,{scissors:a}=this,{nearestEdge:r,repeatInterpolation:c}=this.configuration.interpolation;t.data.handles.originalPoints=e;const{worldToSlice:l,sliceToWorld:d}=this.editData,u=[];if(r){let f=l(e[e.length-1]);e.forEach((g,m)=>{const p=l(g);f=p,u.push(p),a.startSearch(f),a.findPathToPoint(p),a.findPathToPoint(l(e[(m+3)%e.length]));const v=a.findMinNearby(p,r);ve(p,v)||(u[m]=v,f=v,e[m]=d(v))})}const h=new ai;for(let f=0;f<s-1;f++){a.startSearch(l(e[f]));const g=a.findPathToPoint(l(e[(f+1)%s]));h.addPoints(g)}this.updateAnnotation(h),this.scissors=null,this.scissorsNext=null,this.editData=null,t.data.handles.interpolationSources=null,c&&zt(t,n.viewport.element,Bt.InterpolationUpdated)}))}renderAnnotationInstance(t){const{enabledElement:n,svgDrawingHelper:e}=t,o=t.annotation,{annotationUID:s}=o,{viewport:a}=n,{worldToCanvas:r}=a,{showInterpolationPolyline:c}=this.configuration.interpolation||{};this.updateInterpolatedAnnotation?.(o,n);const{originalPolyline:l}=o.data.contour,d=super.renderAnnotationInstance(t);if(c&&l&&o.autoGenerated){const u=l.map(r);u.push(u[0]),Eo(e,s,"interpolationContour-0",u,{color:"#70ffff",lineWidth:1,fillOpacity:0})}return d}isContourSegmentationTool(){return!0}}RS=NS;NS.toolName="LivewireContourSegmentationTool";Bi.register(RS);var ca;class hg extends be{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{shadow:!0,getTextCallback:H5,changeTextCallback:W5,preventHandleOutsideImage:!1,arrowFirst:!0,arrowHeadStyle:"legacy"}}){super(t,n),this.addNewAnnotation=e=>{this.startGroupRecording();const o=e.detail,{currentPoints:s,element:a}=o,r=s.world;wt(a),this.isDrawing=!0;const{arrowFirst:c}=this.configuration,l=this.createAnnotation(e,[[...r],[...r]],{data:{handles:{arrowFirst:c}}});Nt(l,a);const d=ft(a,this.getToolName());return this.editData={annotation:l,viewportIdsToRender:d,handleIndex:1,movingTextBox:!1,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),e.preventDefault(),V(d),l},this.isPointNearTool=(e,o,s,a)=>{const r=N(e),{viewport:c}=r,{data:l}=o,[d,u]=l.handles.points,h=c.worldToCanvas(d),f=c.worldToCanvas(u),g={start:{x:h[0],y:h[1]},end:{x:f[0],y:f[1]}};return Je([g.start.x,g.start.y],[g.end.x,g.end.y],[s[0],s[1]])<=a},this.toolSelectedCallback=(e,o)=>{const s=e.detail,{element:a}=s;o.highlighted=!0;const r=ft(a,this.getToolName());this.editData={annotation:o,viewportIdsToRender:r,movingTextBox:!1},this._activateModify(a),wt(a);const c=N(a),{renderingEngine:l}=c;V(r),e.preventDefault()},this._endCallback=e=>{const o=e.detail,{element:s}=o,{annotation:a,viewportIdsToRender:r,newAnnotation:c,hasMoved:l,movingTextBox:d}=this.editData,{data:u}=a;c&&!l||(u.handles.activeHandleIndex=null,this._deactivateModify(s),this._deactivateDraw(s),Ft(s),this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&Gt(a.annotationUID),c?this.configuration.getTextCallback(h=>{if(!h){Gt(a.annotationUID),V(r),this.editData=null,this.isDrawing=!1;return}a.data.label=h,zt(a,s,Bt.HandlesUpdated),ue(a),this.createMemo(s,a,{newAnnotation:!!this.memo}),dS(a,s,h),this.endGroupRecording(),this.doneEditMemo(),V(r)}):d||zt(a,s,Bt.HandlesUpdated),this.doneEditMemo(),this.editData=null,this.isDrawing=!1)},this._dragCallback=e=>{this.isDrawing=!0;const o=e.detail,{element:s}=o,{annotation:a,viewportIdsToRender:r,handleIndex:c,movingTextBox:l,newAnnotation:d}=this.editData;this.createMemo(s,a,{newAnnotation:d});const{data:u}=a;if(l){const{deltaPoints:h}=o,f=h.world,{textBox:g}=u.handles,{worldPosition:m}=g;m[0]+=f[0],m[1]+=f[1],m[2]+=f[2],g.hasMoved=!0}else if(c===void 0){const{deltaPoints:h}=o,f=h.world;u.handles.points.forEach(m=>{m[0]+=f[0],m[1]+=f[1],m[2]+=f[2]}),a.invalidated=!0}else{const{currentPoints:h}=o,f=h.world;u.handles.points[c]=[...f],a.invalidated=!0}this.editData.hasMoved=!0,V(r),a.invalidated&&zt(a,s,Bt.HandlesUpdated)},this.touchTapCallback=e=>{e.detail.taps==2&&this.doubleClickCallback(e,ca.TOUCH_PROXIMITY)},this.doubleClickCallback=(e,o=ca.MOUSE_PROXIMITY)=>{const s=e.detail,{element:a}=s;let r=Yt(this.getToolName(),a);if(r=this.filterInteractableAnnotationsForElement(a,r),!r?.length)return;const c=r.find(d=>this.isPointNearTool(a,d,s.currentPoints.canvas,o));if(!c)return;const l=c;this.configuration.changeTextCallback(c,e.detail,this._doneChangingTextCallback.bind(this,a,l)),this.editData=null,this.isDrawing=!1,e.stopImmediatePropagation(),e.preventDefault()},this.cancel=e=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateDraw(e),this._deactivateModify(e),Ft(e);const{annotation:o,viewportIdsToRender:s,newAnnotation:a}=this.editData,{data:r}=o;return o.highlighted=!1,r.handles.activeHandleIndex=null,V(s),a&&ue(o),this.editData=null,o.annotationUID}},this._activateModify=e=>{$.isInteractingWithTool=!0,e.addEventListener(E.MOUSE_UP,this._endCallback),e.addEventListener(E.MOUSE_DRAG,this._dragCallback),e.addEventListener(E.MOUSE_CLICK,this._endCallback),e.addEventListener(E.TOUCH_TAP,this._endCallback),e.addEventListener(E.TOUCH_END,this._endCallback),e.addEventListener(E.TOUCH_DRAG,this._dragCallback)},this._deactivateModify=e=>{$.isInteractingWithTool=!1,e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragCallback),e.removeEventListener(E.TOUCH_END,this._endCallback)},this._activateDraw=e=>{$.isInteractingWithTool=!0,e.addEventListener(E.MOUSE_UP,this._endCallback),e.addEventListener(E.MOUSE_DRAG,this._dragCallback),e.addEventListener(E.MOUSE_MOVE,this._dragCallback),e.addEventListener(E.MOUSE_CLICK,this._endCallback),e.addEventListener(E.TOUCH_TAP,this._endCallback),e.addEventListener(E.TOUCH_END,this._endCallback),e.addEventListener(E.TOUCH_DRAG,this._dragCallback)},this._deactivateDraw=e=>{$.isInteractingWithTool=!1,e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragCallback),e.removeEventListener(E.MOUSE_MOVE,this._dragCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback),e.removeEventListener(E.TOUCH_END,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragCallback)},this.renderAnnotation=(e,o)=>{let s=!1;const{viewport:a}=e,{element:r}=a;let c=Yt(this.getToolName(),r);if(!c?.length||(c=this.filterInteractableAnnotationsForElement(r,c),!c?.length))return s;const l={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:e.viewport.id};for(let d=0;d<c.length;d++){const u=c[d],{annotationUID:h,data:f}=u,{handles:g,label:m}=f,{points:p,activeHandleIndex:v}=g;l.annotationUID=h;const{color:I,lineWidth:w,lineDash:C,markerSize:S}=this.getAnnotationStyle({annotation:u,styleSpecifier:l}),b=p.map(T=>a.worldToCanvas(T));let _;if(!ze(h)&&!this.editData&&v!==null&&(_=[b[v]]),!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),s;if(!$e(h))continue;const y=!!Nn("showHandlesAlways",{});(_||y)&&xe(o,h,"0",b,{color:I,lineWidth:w});const D="1";this.configuration.arrowFirst?ll(o,h,D,b[1],b[0],{color:I,width:w,lineDash:C,viaMarker:this.configuration.arrowHeadStyle!=="legacy",markerSize:S}):ll(o,h,D,b[0],b[1],{color:I,width:w,lineDash:C,viaMarker:this.configuration.arrowHeadStyle!=="legacy",markerSize:S}),s=!0,m&&this.renderLinkedTextBoxAnnotation({enabledElement:e,svgDrawingHelper:o,annotation:u,styleSpecifier:l,textLines:[m],canvasCoordinates:b})}return s}}handleSelectedCallback(t,n,e){const o=t.detail,{element:s}=o,{data:a}=n;n.highlighted=!0;let r=!1,c;e.worldPosition?r=!0:c=a.handles.points.findIndex(h=>h===e);const l=ft(s,this.getToolName());this.editData={annotation:n,viewportIdsToRender:l,handleIndex:c,movingTextBox:r},this._activateModify(s),wt(s);const d=N(s),{renderingEngine:u}=d;V(l),t.preventDefault()}_doneChangingTextCallback(t,n,e){n.data.label=e;const o=ft(t,this.getToolName());V(o),zt(n,t)}_isInsideVolume(t,n,e){return gn(t,e)&&gn(n,e)}}ca=hg;hg.toolName="ArrowAnnotate";hg.hydrate=(i,t,n,e)=>{const o=le(i);if(!o)return;const{FrameOfReferenceUID:s,referencedImageId:a,viewPlaneNormal:r,instance:c,viewport:l}=ca.hydrateBase(ca,o,t,e),{toolInstance:d,...u}=e||{},h=ca.createAnnotation({annotationUID:e?.annotationUID||Se(),data:{label:n||"",handles:{points:t}},autoGenerated:!1,metadata:{toolName:c.getToolName(),viewPlaneNormal:r,FrameOfReferenceUID:s,referencedImageId:a,...u}});Nt(h,l.element),V([l.id])};function H5(i){return i(prompt("Enter your annotation:"))}function W5(i,t,n){return n(prompt("Enter your annotation:"))}var wh;class fg extends be{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{shadow:!0,showAngleArc:!1,arcOffset:5,preventHandleOutsideImage:!1,getTextLines:B5}}){super(t,n),this.addNewAnnotation=e=>{if(this.angleStartedNotYetCompleted)return;this.angleStartedNotYetCompleted=!0;const o=e.detail,{currentPoints:s,element:a}=o,r=s.world;wt(a),this.isDrawing=!0;const c=this.createAnnotation(e,[[...r],[...r]]);Nt(c,a);const l=ft(a,this.getToolName());return this.editData={annotation:c,viewportIdsToRender:l,handleIndex:1,movingTextBox:!1,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),e.preventDefault(),V(l),c},this.isPointNearTool=(e,o,s,a)=>{const r=N(e),{viewport:c}=r,{data:l}=o,[d,u,h]=l.handles.points,f=c.worldToCanvas(d),g=c.worldToCanvas(u),m={start:{x:f[0],y:f[1]},end:{x:g[0],y:g[1]}};if(Je([m.start.x,m.start.y],[m.end.x,m.end.y],[s[0],s[1]])<=a)return!0;if(!h)return!1;const v=c.worldToCanvas(h),I={start:{x:g[0],y:g[1]},end:{x:v[0],y:v[1]}};return Je([I.start.x,I.start.y],[I.end.x,I.end.y],[s[0],s[1]])<=a},this.toolSelectedCallback=(e,o)=>{const s=e.detail,{element:a}=s;o.highlighted=!0;const r=ft(a,this.getToolName());this.editData={annotation:o,viewportIdsToRender:r,movingTextBox:!1},this._activateModify(a),wt(a);const c=N(a),{renderingEngine:l}=c;V(r),e.preventDefault()},this._endCallback=e=>{const o=e.detail,{element:s}=o,{annotation:a,viewportIdsToRender:r,newAnnotation:c,hasMoved:l}=this.editData,{data:d}=a;if(c&&!l)return;if(this.angleStartedNotYetCompleted&&d.handles.points.length===2){this.editData.handleIndex=2;return}this.angleStartedNotYetCompleted=!1,d.handles.activeHandleIndex=null,this._deactivateModify(s),this._deactivateDraw(s),Ft(s);const u=N(s),{renderingEngine:h}=u;this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&Gt(a.annotationUID),V(r),this.doneEditMemo(),c&&ue(a),this.editData=null,this.isDrawing=!1},this._dragCallback=e=>{this.isDrawing=!0;const o=e.detail,{element:s}=o,{annotation:a,viewportIdsToRender:r,handleIndex:c,movingTextBox:l,newAnnotation:d}=this.editData,{data:u}=a;if(this.createMemo(s,a,{newAnnotation:d}),l){const{deltaPoints:g}=o,m=g.world,{textBox:p}=u.handles,{worldPosition:v}=p;v[0]+=m[0],v[1]+=m[1],v[2]+=m[2],p.hasMoved=!0}else if(c===void 0){const{deltaPoints:g}=o,m=g.world;u.handles.points.forEach(v=>{v[0]+=m[0],v[1]+=m[1],v[2]+=m[2]}),a.invalidated=!0}else{const{currentPoints:g}=o,m=g.world;u.handles.points[c]=[...m],a.invalidated=!0}this.editData.hasMoved=!0;const h=N(s),{renderingEngine:f}=h;V(r),a.invalidated&&zt(a,s,Bt.HandlesUpdated)},this.cancel=e=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateDraw(e),this._deactivateModify(e),Ft(e);const{annotation:o,viewportIdsToRender:s,newAnnotation:a}=this.editData,{data:r}=o;return o.highlighted=!1,r.handles.activeHandleIndex=null,V(s),a&&ue(o),this.editData=null,this.angleStartedNotYetCompleted=!1,o.annotationUID}},this._activateModify=e=>{$.isInteractingWithTool=!0,e.addEventListener(E.MOUSE_UP,this._endCallback),e.addEventListener(E.MOUSE_DRAG,this._dragCallback),e.addEventListener(E.MOUSE_CLICK,this._endCallback),e.addEventListener(E.TOUCH_TAP,this._endCallback),e.addEventListener(E.TOUCH_END,this._endCallback),e.addEventListener(E.TOUCH_DRAG,this._dragCallback)},this._deactivateModify=e=>{$.isInteractingWithTool=!1,e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback),e.removeEventListener(E.TOUCH_END,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragCallback)},this._activateDraw=e=>{$.isInteractingWithTool=!0,e.addEventListener(E.MOUSE_UP,this._endCallback),e.addEventListener(E.MOUSE_DRAG,this._dragCallback),e.addEventListener(E.MOUSE_MOVE,this._dragCallback),e.addEventListener(E.MOUSE_CLICK,this._endCallback),e.addEventListener(E.TOUCH_TAP,this._endCallback),e.addEventListener(E.TOUCH_END,this._endCallback),e.addEventListener(E.TOUCH_DRAG,this._dragCallback)},this._deactivateDraw=e=>{$.isInteractingWithTool=!1,e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragCallback),e.removeEventListener(E.MOUSE_MOVE,this._dragCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback),e.removeEventListener(E.TOUCH_END,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragCallback)},this.renderAnnotation=(e,o)=>{let s=!1;const{viewport:a}=e,{element:r}=a;let c=Yt(this.getToolName(),r);if(!c?.length||(c=this.filterInteractableAnnotationsForElement(r,c),!c?.length))return s;const l=this.getTargetId(a),d=a.getRenderingEngine(),u={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:e.viewport.id};for(let h=0;h<c.length;h++){const f=c[h],{annotationUID:g,data:m}=f,{points:p,activeHandleIndex:v}=m.handles;u.annotationUID=g;const{color:I,lineWidth:w,lineDash:C,angleArcLineDash:S}=this.getAnnotationStyle({annotation:f,styleSpecifier:u}),b=p.map(x=>a.worldToCanvas(x));!m.cachedStats[l]||m.cachedStats[l].angle==null?(m.cachedStats[l]={angle:null},this._calculateCachedStats(f,d,e)):f.invalidated&&this._throttledCalculateCachedStats(f,d,e);let _;if(!ze(f.annotationUID)&&!this.editData&&v!==null&&(_=[b[v]]),!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),s;if(!$e(g))continue;const y=!!Nn("showHandlesAlways",{});(_||y)&&xe(o,g,"0",b,{color:I,lineDash:C,lineWidth:w});let D="1";if(qt(o,g,D,b[0],b[1],{color:I,width:w,lineDash:C}),s=!0,b.length!==3)return s;if(D="2",qt(o,g,D,b[1],b[2],{color:I,width:w,lineDash:C}),this.configuration.showAngleArc){const x=b[1],M=this.configuration.arcOffset,L=Math.min(Je([x[0],x[1]],[b[0][0],b[0][1]],[b[2][0],b[2][1]]),Je([x[0],x[1]],[b[2][0],b[2][1]],[b[0][0],b[0][1]]))/M,R=[];let U=Math.atan2(b[0][1]-x[1],b[0][0]-x[0]),W=Math.atan2(b[2][1]-x[1],b[2][0]-x[0]);if(W<U&&(W+=2*Math.PI),W-U>Math.PI){const F=U;U=W,W=F+2*Math.PI}const j=32;for(let F=0;F<=j;F++){const z=U+F/j*(W-U);R.push([x[0]+L*Math.cos(z),x[1]+L*Math.sin(z)])}ko(o,g,"3",R,{color:I,width:w,lineDash:S})}if(!m.cachedStats[l]?.angle)continue;const T=this.configuration.getTextLines(m,l),P=[b[1],b[1]];this.renderLinkedTextBoxAnnotation({enabledElement:e,svgDrawingHelper:o,annotation:f,styleSpecifier:u,textLines:T,canvasCoordinates:b,placementPoints:P})}return s},this._throttledCalculateCachedStats=Un(this._calculateCachedStats,100,{trailing:!0})}handleSelectedCallback(t,n,e){const o=t.detail,{element:s}=o,{data:a}=n;n.highlighted=!0;let r=!1,c;e.worldPosition?r=!0:c=a.handles.points.findIndex(h=>h===e);const l=ft(s,this.getToolName());this.editData={annotation:n,viewportIdsToRender:l,handleIndex:c,movingTextBox:r},this._activateModify(s),wt(s);const d=N(s),{renderingEngine:u}=d;V(l),t.preventDefault()}_calculateCachedStats(t,n,e){const o=t.data,{element:s}=e.viewport;if(o.handles.points.length!==3)return;const a=o.handles.points[0],r=o.handles.points[1],c=o.handles.points[2],{cachedStats:l}=o,d=Object.keys(l);for(let h=0;h<d.length;h++){const f=d[h],g=na([a,r],[r,c]),m=this.getTargetImageData(f);if(!m)continue;const{dimensions:p,imageData:v}=m;this.isHandleOutsideImage=[a,r,c].map(I=>wn(v,I)).some(I=>!gn(I,p)),l[f]={angle:isNaN(g)?"Incomplete Angle":g}}const u=t.invalidated;return t.invalidated=!1,u&&zt(t,s,Bt.StatsUpdated),l}}wh=fg;fg.toolName="Angle";fg.hydrate=(i,t,n)=>{const e=le(i);if(!e)return;const{FrameOfReferenceUID:o,referencedImageId:s,viewPlaneNormal:a,instance:r,viewport:c}=wh.hydrateBase(wh,e,t,n),{toolInstance:l,...d}=n||{},u={annotationUID:n?.annotationUID||Se(),data:{handles:{points:t}},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{toolName:r.getToolName(),viewPlaneNormal:a,FrameOfReferenceUID:o,referencedImageId:s,...d}};Nt(u,c.element),V([c.id])};function B5(i,t){const n=i.cachedStats[t],{angle:e}=n;return e===void 0?void 0:isNaN(e)?[`${e}`]:[`${de(e)} °`]}const z5=(...i)=>{const t=i[0].length===2?[0,0]:[0,0,0],n=i.length;for(const e of i)t[0]+=e[0]/n,t[1]+=e[1]/n,t.length===3&&(t[2]+=e[2]/n);return t},si=z5;class $5 extends be{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{shadow:!0,preventHandleOutsideImage:!1,getTextLines:j5,showArcLines:!1}}){super(t,n),this.addNewAnnotation=e=>{if(this.angleStartedNotYetCompleted)return;this.angleStartedNotYetCompleted=!0;const o=e.detail,{currentPoints:s,element:a}=o,r=s.world;wt(a),this.isDrawing=!0;const c=this.createAnnotation(e,[[...r],[...r]]);Nt(c,a);const l=ft(a,this.getToolName());return this.editData={annotation:c,viewportIdsToRender:l,handleIndex:1,movingTextBox:!1,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),e.preventDefault(),V(l),c},this.isPointNearTool=(e,o,s,a)=>{const r=N(e),{viewport:c}=r,{data:l}=o,{distanceToPoint:d,distanceToPoint2:u}=this.distanceToLines({viewport:c,points:l.handles.points,canvasCoords:s,proximity:a});return d<=a||u<=a},this.toolSelectedCallback=(e,o,s,a,r=6)=>{const c=e.detail,{element:l}=c;o.highlighted=!0;const d=ft(l,this.getToolName()),u=N(l),{renderingEngine:h,viewport:f}=u,{isNearFirstLine:g,isNearSecondLine:m}=this.distanceToLines({viewport:f,points:o.data.handles.points,canvasCoords:a,proximity:r});this.editData={annotation:o,viewportIdsToRender:d,movingTextBox:!1,isNearFirstLine:g,isNearSecondLine:m},this._activateModify(l),wt(l),V(d),e.preventDefault()},this._endCallback=e=>{const o=e.detail,{element:s}=o,{annotation:a,viewportIdsToRender:r,newAnnotation:c,hasMoved:l}=this.editData,{data:d}=a;if(c&&!l)return;if(this.doneEditMemo(),this.angleStartedNotYetCompleted&&d.handles.points.length<4){Ft(s),this.editData.handleIndex=d.handles.points.length;return}this.angleStartedNotYetCompleted=!1,d.handles.activeHandleIndex=null,this._deactivateModify(s),this._deactivateDraw(s),Ft(s);const u=N(s),{renderingEngine:h}=u;this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&Gt(a.annotationUID),V(r),c&&ue(a),this.editData=null,this.isDrawing=!1},this._mouseDownCallback=e=>{const{annotation:o,handleIndex:s}=this.editData,a=e.detail,{element:r,currentPoints:c}=a,l=c.world,{data:d}=o;if(s===1){d.handles.points[1]=l,this.editData.hasMoved=d.handles.points[1][0]!==d.handles.points[0][0]||d.handles.points[1][1]!==d.handles.points[0][0];return}if(s===3){d.handles.points[3]=l,this.editData.hasMoved=d.handles.points[3][0]!==d.handles.points[2][0]||d.handles.points[3][1]!==d.handles.points[2][0],this.angleStartedNotYetCompleted=!1;return}this.editData.hasMoved=!1,wt(r),d.handles.points[2]=d.handles.points[3]=l,this.editData.handleIndex=d.handles.points.length-1},this._dragCallback=e=>{this.isDrawing=!0;const o=e.detail,{element:s}=o,{annotation:a,viewportIdsToRender:r,handleIndex:c,movingTextBox:l,isNearFirstLine:d,isNearSecondLine:u,newAnnotation:h}=this.editData;this.createMemo(s,a,{newAnnotation:h});const{data:f}=a;if(l){const{deltaPoints:p}=o,v=p.world,{textBox:I}=f.handles,{worldPosition:w}=I;w[0]+=v[0],w[1]+=v[1],w[2]+=v[2],I.hasMoved=!0}else if(c===void 0&&(d||u)){const{deltaPoints:p}=o,v=p.world,I=f.handles.points;d?[I[0],I[1]].forEach(C=>{C[0]+=v[0],C[1]+=v[1],C[2]+=v[2]}):u&&[I[2],I[3]].forEach(C=>{C[0]+=v[0],C[1]+=v[1],C[2]+=v[2]}),a.invalidated=!0}else{const{currentPoints:p}=o,v=p.world;f.handles.points[c]=[...v],a.invalidated=!0}this.editData.hasMoved=!0;const g=N(s),{renderingEngine:m}=g;V(r),a.invalidated&&zt(a,s,Bt.HandlesUpdated)},this.cancel=e=>{if(!this.isDrawing)return;this.isDrawing=!1,this._deactivateDraw(e),this._deactivateModify(e),Ft(e);const{annotation:o,viewportIdsToRender:s,newAnnotation:a}=this.editData,{data:r}=o;r.handles.points.length<4&&Gt(o.annotationUID),o.highlighted=!1,r.handles.activeHandleIndex=null;const c=N(e),{renderingEngine:l}=c;return V(s),a&&ue(o),this.editData=null,this.angleStartedNotYetCompleted=!1,o.annotationUID},this._activateModify=e=>{$.isInteractingWithTool=!0,e.addEventListener(E.MOUSE_UP,this._endCallback),e.addEventListener(E.MOUSE_DRAG,this._dragCallback),e.addEventListener(E.MOUSE_CLICK,this._endCallback),e.addEventListener(E.TOUCH_END,this._endCallback),e.addEventListener(E.TOUCH_DRAG,this._dragCallback),e.addEventListener(E.TOUCH_START,this._mouseDownCallback),e.addEventListener(E.TOUCH_TAP,this._endCallback)},this._deactivateModify=e=>{$.isInteractingWithTool=!1,e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.TOUCH_END,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragCallback),e.removeEventListener(E.TOUCH_START,this._mouseDownCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback)},this._activateDraw=e=>{$.isInteractingWithTool=!0,e.addEventListener(E.MOUSE_UP,this._endCallback),e.addEventListener(E.MOUSE_DRAG,this._dragCallback),e.addEventListener(E.MOUSE_MOVE,this._dragCallback),e.addEventListener(E.MOUSE_CLICK,this._endCallback),e.addEventListener(E.MOUSE_DOWN,this._mouseDownCallback),e.addEventListener(E.TOUCH_END,this._endCallback),e.addEventListener(E.TOUCH_DRAG,this._dragCallback),e.addEventListener(E.TOUCH_START,this._mouseDownCallback),e.addEventListener(E.TOUCH_TAP,this._endCallback)},this._deactivateDraw=e=>{$.isInteractingWithTool=!1,e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragCallback),e.removeEventListener(E.MOUSE_MOVE,this._dragCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.MOUSE_DOWN,this._mouseDownCallback),e.removeEventListener(E.TOUCH_END,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragCallback),e.removeEventListener(E.TOUCH_START,this._mouseDownCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(e,o)=>{let s=!1;const{viewport:a}=e,{element:r}=a;let c=Yt(this.getToolName(),r);if(!c?.length||(c=this.filterInteractableAnnotationsForElement(r,c),!c?.length))return s;const l=a.getRenderingEngine(),d={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:e.viewport.id};for(let u=0;u<c.length;u++){const h=c[u],{annotationUID:f,data:g}=h,{points:m,activeHandleIndex:p}=g.handles,v=this.getTargetId(a,g);d.annotationUID=f;const{color:I,lineWidth:w,lineDash:C}=this.getAnnotationStyle({annotation:h,styleSpecifier:d}),S=m.map(F=>a.worldToCanvas(F));!g.cachedStats[v]||g.cachedStats[v].angle==null?(g.cachedStats[v]={angle:null,arc1Angle:null,arc2Angle:null,points:{world:{arc1Start:null,arc1End:null,arc2Start:null,arc2End:null,arc1Angle:null,arc2Angle:null},canvas:{arc1Start:null,arc1End:null,arc2Start:null,arc2End:null,arc1Angle:null,arc2Angle:null}}},this._calculateCachedStats(h,l,e)):h.invalidated&&this._throttledCalculateCachedStats(h,l,e);let b;if(!ze(f)&&!this.editData&&p!==null&&(b=[S[p]]),!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),s;if(!$e(f))continue;const _=!!Nn("showHandlesAlways",{});(b||_)&&xe(o,f,"0",S,{color:I,lineDash:C,lineWidth:w});const y=[S[0],S[1]],D=[S[2],S[3]];let T="line1";if(qt(o,f,T,y[0],y[1],{color:I,width:w,lineDash:C}),s=!0,S.length<4)return s;T="line2",qt(o,f,T,D[0],D[1],{color:I,width:w,lineDash:C}),T="linkLine";const P=si(y[0],y[1]),x=si(D[0],D[1]);qt(o,f,T,P,x,{color:I,lineWidth:"1",lineDash:"1,4"});const{arc1Start:M,arc1End:L,arc2End:R,arc2Start:U}=g.cachedStats[v].points.canvas,{arc1Angle:W,arc2Angle:K}=g.cachedStats[v];if(this.configuration.showArcLines&&(T="arc1",qt(o,f,T,M,L,{color:I,lineWidth:"1"}),T="arc2",qt(o,f,T,U,R,{color:I,lineWidth:"1"})),!g.cachedStats[v]?.angle)continue;const j=this.configuration.getTextLines(g,v);if(this.renderLinkedTextBoxAnnotation({enabledElement:e,svgDrawingHelper:o,annotation:h,styleSpecifier:d,textLines:j??[],canvasCoordinates:S,textBoxUID:"cobbAngleText"})&&this.configuration.showArcLines){const F=this.getLinkedTextBoxStyle(d,h),z="arcAngle1",q=[`${W.toFixed(2)} °`],J=si(M,L);Ko(o,f,z,q,J,{...F,padding:3});const it="arcAngle2",tt=[`${K.toFixed(2)} °`],ot=si(U,R);Ko(o,f,it,tt,ot,{...F,padding:3})}}return s},this.distanceToLines=({viewport:e,points:o,canvasCoords:s,proximity:a})=>{const[r,c,l,d]=o,u=e.worldToCanvas(r),h=e.worldToCanvas(c),f=e.worldToCanvas(l),g=e.worldToCanvas(d),m={start:{x:u[0],y:u[1]},end:{x:h[0],y:h[1]}},p={start:{x:f[0],y:f[1]},end:{x:g[0],y:g[1]}},v=Je([m.start.x,m.start.y],[m.end.x,m.end.y],[s[0],s[1]]),I=Je([p.start.x,p.start.y],[p.end.x,p.end.y],[s[0],s[1]]);let w=!1,C=!1;return v<=a?w=!0:I<=a&&(C=!0),{distanceToPoint:v,distanceToPoint2:I,isNearFirstLine:w,isNearSecondLine:C}},this.getArcsStartEndPoints=({firstLine:e,secondLine:o,mid1:s,mid2:a})=>{const r=[s,a],c=na(e,r),l=na(o,r),d=c>90?1:0,u=l>90?0:1,h=si(r[0],r[1]),f=Math.sqrt((r[1][0]-r[0][0])**2+(r[1][1]-r[0][1])**2),g=.1,m=si(e[0],e[1]),p=si(o[0],o[1]),v=[e[d][0]-m[0],e[d][1]-m[1]],I=Math.sqrt(v[0]**2+v[1]**2),w=[v[0]/I,v[1]/I],C=[m[0]+w[0]*f*g,m[1]+w[1]*f*g],S=[h[0]-s[0],h[1]-s[1]],b=Math.sqrt(S[0]**2+S[1]**2),_=[S[0]/b,S[1]/b],y=[s[0]+_[0]*f*g,s[1]+_[1]*f*g],D=[o[u][0]-p[0],o[u][1]-p[1]],T=Math.sqrt(D[0]**2+D[1]**2),P=[D[0]/T,D[1]/T],x=[p[0]+P[0]*f*g,p[1]+P[1]*f*g],M=[h[0]-a[0],h[1]-a[1]],L=Math.sqrt(M[0]**2+M[1]**2),R=[M[0]/L,M[1]/L],U=[a[0]+R[0]*f*g,a[1]+R[1]*f*g];return{arc1Start:C,arc1End:y,arc2Start:x,arc2End:U,arc1Angle:c>90?180-c:c,arc2Angle:l>90?180-l:l}},this._throttledCalculateCachedStats=Un(this._calculateCachedStats,25,{trailing:!0})}handleSelectedCallback(t,n,e,o="mouse"){const s=t.detail,{element:a}=s,{data:r}=n;n.highlighted=!0;let c=!1,l;e.worldPosition?c=!0:l=r.handles.points.findIndex(u=>u===e);const d=ft(a,this.getToolName());this.editData={annotation:n,viewportIdsToRender:d,handleIndex:l,movingTextBox:c},this._activateModify(a),wt(a),V(d),t.preventDefault()}_calculateCachedStats(t,n,e){const o=t.data;if(o.handles.points.length!==4)return;const s=[null,null],a=[null,null];let r=Number.MAX_VALUE;for(let y=0;y<2;y+=1)for(let D=2;D<4;D+=1){const T=ke(o.handles.points[y],o.handles.points[D]);T<r&&(r=T,s[1]=o.handles.points[y],s[0]=o.handles.points[(y+1)%2],a[0]=o.handles.points[D],a[1]=o.handles.points[2+(D-1)%2])}const{viewport:c}=e,{element:l}=c,d=o.handles.points.map(y=>c.worldToCanvas(y)),u=[d[0],d[1]],h=[d[2],d[3]],f=si(u[0],u[1]),g=si(h[0],h[1]),{arc1Start:m,arc1End:p,arc2End:v,arc2Start:I,arc1Angle:w,arc2Angle:C}=this.getArcsStartEndPoints({firstLine:u,secondLine:h,mid1:f,mid2:g}),{cachedStats:S}=o,b=Object.keys(S);for(let y=0;y<b.length;y++){const D=b[y];S[D]={angle:na(s,a),arc1Angle:w,arc2Angle:C,points:{canvas:{arc1Start:m,arc1End:p,arc2End:v,arc2Start:I},world:{arc1Start:c.canvasToWorld(m),arc1End:c.canvasToWorld(p),arc2End:c.canvasToWorld(v),arc2Start:c.canvasToWorld(I)}}}}const _=t.invalidated;return t.invalidated=!1,_&&zt(t,l,Bt.StatsUpdated),S}}$5.toolName="CobbAngle";function j5(i,t){const n=i.cachedStats[t],{angle:e}=n;return e===void 0?void 0:[`${e.toFixed(2)} °`]}const{transformWorldToIndexContinuous:Wp}=oe;class X5 extends be{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{shadow:!0,preventHandleOutsideImage:!1,getTextLines:q5,displayBothAxesDistances:!1}}){super(t,n),this.addNewAnnotation=e=>{if(this.startedDrawing)return;this.startedDrawing=!0;const o=e.detail,{currentPoints:s,element:a}=o,r=s.world,c=N(a),{viewport:l}=c;if(!(l instanceof Pn)&&!(l instanceof HC))throw new Error("UltrasoundDirectionalTool can only be used on a StackViewport or ECGViewport");wt(a),this.isDrawing=!0;const d=this.createAnnotation(e,[[...r],[...r]]);Nt(d,a);const u=ft(a,this.getToolName());return this.editData={annotation:d,viewportIdsToRender:u,handleIndex:1,movingTextBox:!1,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),e.preventDefault(),V(u),d},this.isPointNearTool=(e,o,s,a)=>{const r=N(e),{viewport:c}=r,{data:l}=o,[d,u]=l.handles.points,h=c.worldToCanvas(d),f=c.worldToCanvas(u),g={start:{x:h[0],y:h[1]},end:{x:f[0],y:f[1]}};return Je([g.start.x,g.start.y],[g.end.x,g.end.y],[s[0],s[1]])<=a},this._endCallback=e=>{const o=e.detail,{element:s}=o,{annotation:a,viewportIdsToRender:r,newAnnotation:c,hasMoved:l}=this.editData,{data:d}=a;if(c&&!l)return;if(this.startedDrawing&&d.handles.points.length===1){this.editData.handleIndex=1;return}this.startedDrawing=!1,d.handles.activeHandleIndex=null,this._deactivateModify(s),this._deactivateDraw(s),Ft(s);const u=N(s),{renderingEngine:h}=u;this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&Gt(a.annotationUID),V(r),c&&ue(a),this.editData=null,this.isDrawing=!1},this._dragCallback=e=>{this.isDrawing=!0;const o=e.detail,{element:s}=o,{annotation:a,viewportIdsToRender:r,handleIndex:c,movingTextBox:l}=this.editData,{data:d}=a;if(l){const{deltaPoints:f}=o,g=f.world,{textBox:m}=d.handles,{worldPosition:p}=m;p[0]+=g[0],p[1]+=g[1],p[2]+=g[2],m.hasMoved=!0}else if(c===void 0){const{deltaPoints:f}=o,g=f.world;d.handles.points.forEach(p=>{p[0]+=g[0],p[1]+=g[1],p[2]+=g[2]}),a.invalidated=!0}else{const{currentPoints:f}=o,g=f.world;d.handles.points[c]=[...g],a.invalidated=!0}this.editData.hasMoved=!0;const u=N(s),{renderingEngine:h}=u;V(r)},this.cancel=e=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateDraw(e),this._deactivateModify(e),Ft(e);const{annotation:o,viewportIdsToRender:s,newAnnotation:a}=this.editData,{data:r}=o;return o.highlighted=!1,r.handles.activeHandleIndex=null,V(s),a&&ue(o),this.editData=null,this.startedDrawing=!1,o.annotationUID}},this._activateModify=e=>{$.isInteractingWithTool=!0,e.addEventListener(E.MOUSE_UP,this._endCallback),e.addEventListener(E.MOUSE_DRAG,this._dragCallback),e.addEventListener(E.MOUSE_CLICK,this._endCallback),e.addEventListener(E.TOUCH_TAP,this._endCallback),e.addEventListener(E.TOUCH_END,this._endCallback),e.addEventListener(E.TOUCH_DRAG,this._dragCallback)},this._deactivateModify=e=>{$.isInteractingWithTool=!1,e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback),e.removeEventListener(E.TOUCH_END,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragCallback)},this._activateDraw=e=>{$.isInteractingWithTool=!0,e.addEventListener(E.MOUSE_UP,this._endCallback),e.addEventListener(E.MOUSE_DRAG,this._dragCallback),e.addEventListener(E.MOUSE_MOVE,this._dragCallback),e.addEventListener(E.MOUSE_CLICK,this._endCallback),e.addEventListener(E.TOUCH_TAP,this._endCallback),e.addEventListener(E.TOUCH_END,this._endCallback),e.addEventListener(E.TOUCH_DRAG,this._dragCallback)},this._deactivateDraw=e=>{$.isInteractingWithTool=!1,e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragCallback),e.removeEventListener(E.MOUSE_MOVE,this._dragCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback),e.removeEventListener(E.TOUCH_END,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragCallback)},this.renderAnnotation=(e,o)=>{let s=!1;const{viewport:a}=e,{element:r}=a;let c=Yt(this.getToolName(),r);if(!c?.length||(c=this.filterInteractableAnnotationsForElement(r,c),!c?.length))return s;const l=this.getTargetId(a),d=a.getRenderingEngine(),u={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:e.viewport.id};for(let h=0;h<c.length;h++){const f=c[h],{annotationUID:g,data:m}=f,{points:p}=m.handles;u.annotationUID=g;const v=this.getStyle("color",u,f),I=p.map(_=>a.worldToCanvas(_));if(!m.cachedStats[l]||m.cachedStats[l].xValues==null?(m.cachedStats[l]={xValues:[0,0],yValues:[0,0],isHorizontal:!1,units:[""],isUnitless:!1},this._calculateCachedStats(f,d,e)):f.invalidated&&this._throttledCalculateCachedStats(f,d,e),!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),s;let w="0";if(cl(o,g,w,I[0],{color:v},0),s=!0,I.length!==2)return s;if(w="1",cl(o,g,w,I[1],{color:v},1),m.cachedStats[l].isUnitless){const _=`${g}-line-1`;qt(o,g,"1",I[0],I[1],{color:v,width:1,shadow:this.configuration.shadow},_)}else{const _=I[0],y=I[1],D=y[1]-_[1],T=y[0]-_[0],P=m.cachedStats[l].isHorizontal;let x=[0,0];P?x=[_[0]+T,_[1]]:x=[_[0],_[1]+D];let M=`${g}-line-1`,L="1";qt(o,g,L,I[0],x,{color:v,width:1,shadow:this.configuration.shadow},M),M=`${g}-line-2`,L="2",qt(o,g,L,I[1],x,{color:v,width:1,lineDash:[1,1],shadow:this.configuration.shadow},M)}const S=this.configuration.getTextLines(m,l,this.configuration),b=[I[1],I[1]];this.renderLinkedTextBoxAnnotation({enabledElement:e,svgDrawingHelper:o,annotation:f,styleSpecifier:u,textLines:S,canvasCoordinates:I,placementPoints:b})}return s},this._throttledCalculateCachedStats=Un(this._calculateCachedStats,100,{trailing:!0})}toolSelectedCallback(t,n,e,o){}handleSelectedCallback(t,n,e){const o=t.detail,{element:s}=o,{data:a}=n;n.highlighted=!0;const r=ft(s,this.getToolName());let c;e.worldPosition||(c=a.handles.points.findIndex(u=>u===e)),this.editData={handleIndex:c,annotation:n,viewportIdsToRender:r},this._activateModify(s),wt(s);const l=N(s),{renderingEngine:d}=l;V(r),t.preventDefault()}_calculateCachedStats(t,n,e){const o=t.data,{element:s}=e.viewport;if(o.handles.points.length!==2)return;const{cachedStats:a}=o,r=Object.keys(a);for(let l=0;l<r.length;l++){const d=r[l],u=this.getTargetImageData(d);if(!u)continue;const{imageData:h}=u,f=o.handles.points[0],g=o.handles.points[1],m=Wp(h,f),p=Wp(h,g),{values:v,units:I}=Cr(u,[m]),{values:w,units:C}=Cr(u,[p]);let S,b,_,y,D=!1;if(I[0]!==C[0]||I[1]!==C[1]||I[0]==="raw"&&C[0]==="raw"){const T=ro(f,g);S=[T,0],b=[T,0],_=["px"],D=!0}else{const T=e.viewport.worldToCanvas(f),P=e.viewport.worldToCanvas(g),x=P[1]-T[1],M=P[0]-T[0];y=Math.abs(M)>Math.abs(x),S=[v[0],w[0]],b=[v[1],w[1]],_=[I[0],I[1]]}a[d]={xValues:S,yValues:b,isHorizontal:y,units:_,isUnitless:D}}const c=t.invalidated;return t.invalidated=!1,c&&zt(t,s,Bt.StatsUpdated),a}}X5.toolName="UltrasoundDirectionalTool";function q5(i,t,n){const e=i.cachedStats[t],{xValues:o,yValues:s,units:a,isUnitless:r,isHorizontal:c}=e;if(r)return[`${de(o[0])} px`];if(n.displayBothAxesDistances){const l=Math.abs(o[1]-o[0]),d=Math.abs(s[1]-s[0]);return[`${de(l)} ${a[0]}`,`${de(d)} ${a[1]}`]}if(c){const l=Math.abs(o[1]-o[0]);return[`${de(l)} ${a[0]}`]}else{const l=Math.abs(s[1]-s[0]);return[`${de(l)} ${a[1]}`]}}function Y5(i){return(i%360+360)%360}function Eh(i,t){const n=t[0]-i[0],e=t[1]-i[1],o=Math.atan2(e,n)*(180/Math.PI);return Y5(o)}function Ll(i,t){const n=Eh(i,t[0]),e=Eh(i,t[1]);return n<e?[n,e]:[e,n]}function Sh(i){if(!i.length)return[];i.sort((n,e)=>n[0]-e[0]);const t=[i[0].slice()];for(let n=1;n<i.length;n++){const e=t[t.length-1],o=i[n];o[0]<=e[1]?e[1]=Math.max(e[1],o[1]):t.push(o.slice())}return t}function Bp(i,t){const[n,e]=t;if(e<=n)return[];const o=i.map(([d,u])=>[Math.max(d,n),Math.min(u,e)]).filter(([d,u])=>u>d);if(o.length===0)return[[n,e]];o.sort((d,u)=>d[0]-u[0]);const s=[];let[a,r]=o[0];for(let d=1;d<o.length;d++){const[u,h]=o[d];u<=r?r=Math.max(r,h):(s.push([a,r]),[a,r]=[u,h])}s.push([a,r]);const c=[];let l=n;for(const[d,u]of s)d>l&&c.push([l,d]),l=Math.max(l,u);return l<e&&c.push([l,e]),c}function kS(i,t){const n=[];for(const e of t){const o=Math.max(i[0],e[0]),s=Math.min(i[1],e[1]);o<s&&n.push([o,s])}return n}function K5(i,t,n){const e=t.map(d=>Ll(i,d)),o=Sh(e),s=o.reduce((d,[u,h])=>d+(h-u),0);if(s===0)return 0;const a=[];for(const d of n){const u=Ll(i,d),h=kS(u,o);a.push(...h)}const l=Sh(a).reduce((d,[u,h])=>d+(h-u),0)/s*100;return Math.min(100,Math.max(0,l))}var Ye;const{transformIndexToWorld:zp}=oe;class Od extends be{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{preventHandleOutsideImage:!1,getTextLines:Z5,center:null,innerRadius:null,outerRadius:null,startAngle:null,endAngle:null,bLineColor:"rgb(60, 255, 60)",pleuraColor:"rgb(0, 4, 255)",drawDepthGuide:!0,depth_ratio:.5,depthGuideColor:"rgb(0, 255, 255)",depthGuideThickness:4,depthGuideDashLength:20,depthGuideDashGap:16,depthGuideOpacity:.2,fanOpacity:.1,showFanAnnotations:!0,updatePercentageCallback:null,actions:{undo:{method:"undo",bindings:[{key:"z"}]},redo:{method:"redo",bindings:[{key:"y"}]}}}}){super(t,n),this.pleuraAnnotations=[],this.bLineAnnotations=[],this.addNewAnnotation=e=>{const o=e.detail,{currentPoints:s,element:a}=o,r=s.world,c=N(a),{viewport:l}=c;wt(a),this.isDrawing=!0;const{viewPlaneNormal:d,viewUp:u,position:h}=ht(l),f=this.getReferencedImageId(l,r,d,u),g={highlighted:!0,invalidated:!0,metadata:{...l.getViewReference({points:[r]}),toolName:this.getToolName(),referencedImageId:f,viewUp:u,cameraPosition:h},data:{handles:{points:[[...r],[...r]],activeHandleIndex:null},annotationType:this.getActiveAnnotationType(),label:""}};Nt(g,a);const m=ft(a,this.getToolName());return this.editData={annotation:g,viewportIdsToRender:m,handleIndex:1,movingTextBox:!1,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),e.preventDefault(),V(m),g},this.isPointNearTool=(e,o,s,a)=>{const r=N(e),{viewport:c}=r,{data:l}=o,[d,u]=l.handles.points,h=c.worldToCanvas(d),f=c.worldToCanvas(u),g={start:{x:h[0],y:h[1]},end:{x:f[0],y:f[1]}};return Je([g.start.x,g.start.y],[g.end.x,g.end.y],[s[0],s[1]])<=a},this.toolSelectedCallback=(e,o)=>{const s=e.detail,{element:a}=s;o.highlighted=!0;const r=ft(a,this.getToolName());this.editData={annotation:o,viewportIdsToRender:r,movingTextBox:!1},this._activateModify(a),wt(a),V(r),e.preventDefault()},this._endCallback=e=>{const o=e.detail,{element:s}=o,{annotation:a,viewportIdsToRender:r,newAnnotation:c,hasMoved:l}=this.editData,{data:d}=a;c&&!l||(d.handles.activeHandleIndex=null,this._deactivateModify(s),this._deactivateDraw(s),Ft(s),this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&Gt(a.annotationUID),V(r),this.doneEditMemo(),c&&ue(a),this.editData=null,this.isDrawing=!1)},this._dragCallback=e=>{this.isDrawing=!0;const o=e.detail,{element:s}=o,{viewport:a}=N(s)||{};if(!a)return;const{annotation:r,viewportIdsToRender:c,handleIndex:l,movingTextBox:d,newAnnotation:u}=this.editData,{data:h}=r;if(this.createMemo(s,r,{newAnnotation:u}),d){const{deltaPoints:f}=o,g=f.world,{textBox:m}=h.handles,{worldPosition:p}=m;p[0]+=g[0],p[1]+=g[1],p[2]+=g[2],m.hasMoved=!0}else if(l===void 0){const{deltaPoints:f}=o,g=f.world,m=h.handles.points;m.every(v=>{const I=[v[0]+g[0],v[1]+g[1],v[2]+g[2]];return this.isInsideFanShape(a,I)})&&(m.forEach(v=>{v[0]+=g[0],v[1]+=g[1],v[2]+=g[2]}),r.invalidated=!0)}else{const{currentPoints:f}=o,g=f.world;this.isInsideFanShape(a,g)&&(h.handles.points[l]=[...g],r.invalidated=!0)}this.editData.hasMoved=!0,V(c),r.invalidated&&zt(r,s,Bt.HandlesUpdated)},this.cancel=e=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateDraw(e),this._deactivateModify(e),Ft(e);const{annotation:o,viewportIdsToRender:s,newAnnotation:a}=this.editData,{data:r}=o;return o.highlighted=!1,r.handles.activeHandleIndex=null,V(s),a&&ue(o),this.editData=null,o.annotationUID}},this._activateModify=e=>{$.isInteractingWithTool=!0,e.addEventListener(E.MOUSE_UP,this._endCallback),e.addEventListener(E.MOUSE_DRAG,this._dragCallback),e.addEventListener(E.MOUSE_CLICK,this._endCallback),e.addEventListener(E.TOUCH_END,this._endCallback),e.addEventListener(E.TOUCH_DRAG,this._dragCallback),e.addEventListener(E.TOUCH_TAP,this._endCallback)},this._deactivateModify=e=>{$.isInteractingWithTool=!1,e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.TOUCH_END,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback)},this._activateDraw=e=>{$.isInteractingWithTool=!0,e.addEventListener(E.MOUSE_UP,this._endCallback),e.addEventListener(E.MOUSE_DRAG,this._dragCallback),e.addEventListener(E.MOUSE_MOVE,this._dragCallback),e.addEventListener(E.MOUSE_CLICK,this._endCallback),e.addEventListener(E.TOUCH_END,this._endCallback),e.addEventListener(E.TOUCH_DRAG,this._dragCallback),e.addEventListener(E.TOUCH_TAP,this._endCallback)},this._deactivateDraw=e=>{$.isInteractingWithTool=!1,e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragCallback),e.removeEventListener(E.MOUSE_MOVE,this._dragCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.TOUCH_END,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(e,o)=>{let s=!1;const{viewport:a}=e,{element:r}=a;if(!this.getFanShapeGeometryParameters(a))return;const{imageData:c}=a.getImageData()||{};if(!c)return s;this.configuration.drawDepthGuide&&this.drawDepthGuide(o,a);let l=Yt(this.getToolName(),r);if(!l?.length||(l=this.filterInteractableAnnotationsForElement(r,l),!l?.length))return s;this.getTargetId(a),a.getRenderingEngine();const d={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:e.viewport.id},u=a.worldToCanvas(zp(c,this.configuration.center)),h=this.getIndexToCanvasRatio(a),f=this.configuration.innerRadius*h,g=this.configuration.outerRadius*h,m=a.getCurrentImageId(),p=l.filter(_=>_.data.annotationType===Ye.USPleuraBLineAnnotationType.PLEURA&&_.metadata.referencedImageId===m).map(_=>{const y=_.data.handles.points.map(T=>a.worldToCanvas(T));return Ll(u,y)}),v=Sh(p),I=[],w=[],C=_=>{const{annotationUID:y,data:D}=_,{points:T,activeHandleIndex:P}=D.handles;d.annotationUID=y;const{color:x,lineWidth:M,lineDash:L,shadow:R}=this.getAnnotationStyle({annotation:_,styleSpecifier:d}),U=T.map(F=>a.worldToCanvas(F));if(!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),s;let W;if(!$e(y))return;!ze(y)&&!this.editData&&P!==null&&(W=[U[P]]),W&&xe(o,y,"0",U,{color:this.getColorForLineType(_),fill:this.getColorForLineType(_),lineDash:L,lineWidth:M});const K=`${y}-line`;if(qt(o,y,"1",U[0],U[1],{color:this.getColorForLineType(_),width:M,lineDash:L,shadow:R},K),this.configuration.showFanAnnotations){const F=Ll(u,U);let z=0;_.data.annotationType===Ye.USPleuraBLineAnnotationType.BLINE?Bp(w,F).forEach(J=>{kS(J,v).forEach(tt=>{z++;const ot=z,nt=`${y}-fan-${ot}`,lt=`2-${ot}`;Zu(o,y,lt,u,f,g,tt[0],tt[1],{color:"transparent",fill:this.getColorForLineType(_),fillOpacity:this.configuration.fanOpacity,width:M,lineDash:L,shadow:R},nt,10),w.push(tt)})}):_.data.annotationType===Ye.USPleuraBLineAnnotationType.PLEURA&&Bp(I,F).forEach((J,it)=>{z++;const tt=z,ot=`${y}-fan-${tt}`,nt=`2-${tt}`;Zu(o,y,nt,u,f,g,J[0],J[1],{color:"transparent",fill:this.getColorForLineType(_),fillOpacity:this.configuration.fanOpacity,width:M,lineDash:L,shadow:R},ot,5),I.push(J)})}};return l.filter(_=>_.data.annotationType===Ye.USPleuraBLineAnnotationType.PLEURA&&_.metadata.referencedImageId===m).forEach(_=>{if(!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),s;C(_)}),l.filter(_=>_.data.annotationType===Ye.USPleuraBLineAnnotationType.BLINE&&_.metadata.referencedImageId===m).forEach(_=>{if(!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),s;C(_)}),s=!0,this.configuration.updatePercentageCallback&&a&&this.configuration.updatePercentageCallback(this.calculateBLinePleuraPercentage(a)),s},this.activeAnnotationType=Ye.USPleuraBLineAnnotationType.BLINE}static filterAnnotations(t,n=()=>!0){const e=Yt(Ye.toolName,t);return e?.length?e.filter(s=>{const a=s.metadata.referencedImageId;return n(a)}):[]}static countAnnotations(t,n=()=>!0){const e=Yt(Ye.toolName,t),{viewport:o}=N(t),s=o.getImageIds(),a=c=>{const l=s.findIndex(d=>d===c);return l===-1?0:l};if(!e?.length)return;const r=new Map;return e.forEach(c=>{const l=c.metadata.referencedImageId;if(!n(l))return;const{annotationType:d}=c.data;let u;r.has(l)?u=r.get(l):u={frame:a(l),bLine:0,pleura:0},d===Ye.USPleuraBLineAnnotationType.PLEURA?u.pleura++:d===Ye.USPleuraBLineAnnotationType.BLINE&&u.bLine++,r.set(l,u)}),r}static deleteAnnotations(t,n=()=>!1){const e=Yt(Ye.toolName,t);e?.length&&e.forEach(o=>{n(o.metadata.referencedImageId)&&Gt(o.annotationUID)})}setActiveAnnotationType(t){this.activeAnnotationType=t}getActiveAnnotationType(){return this.activeAnnotationType}deleteLastAnnotationType(t,n){let e;const o=Yt(Ye.toolName,t);if(n===Ye.USPleuraBLineAnnotationType.PLEURA?e=o.filter(s=>s.data.annotationType===Ye.USPleuraBLineAnnotationType.PLEURA):n===Ye.USPleuraBLineAnnotationType.BLINE&&(e=o.filter(s=>s.data.annotationType===Ye.USPleuraBLineAnnotationType.BLINE)),e?.length>0){const s=e.pop();Gt(s.annotationUID)}}handleSelectedCallback(t,n,e){const o=t.detail,{element:s}=o,{data:a}=n;n.highlighted=!0;let r=!1,c;e.worldPosition?r=!0:c=a.handles.points.findIndex(d=>d===e);const l=ft(s,this.getToolName());this.editData={annotation:n,viewportIdsToRender:l,handleIndex:c,movingTextBox:r},this._activateModify(s),wt(s),V(l),t.preventDefault()}isInsideFanShape(t,n){if(!this.getFanShapeGeometryParameters(t))return!1;const{imageData:e}=t.getImageData()||{};if(e){const o=t.worldToCanvas(e.indexToWorld(this.configuration.center)),s=t.worldToCanvas(n),a=Eh(o,s);return a>=this.configuration.startAngle&&a<=this.configuration.endAngle}}updateFanGeometryConfiguration(t){t&&(this.isFanShapeGeometryParametersValid(t)&&(this.configuration.center=[t.center[0],t.center[1],0]),this.configuration.innerRadius=t.innerRadius,this.configuration.outerRadius=t.outerRadius,this.configuration.startAngle=t.startAngle,this.configuration.endAngle=t.endAngle)}deriveFanGeometryFromViewport(t){const n=t.getCurrentImageId(),{fanGeometry:e}=rg(n)||{};e&&this.updateFanGeometryConfiguration(e)}isFanShapeGeometryParametersValid(t){return t||(t=this.configuration),t?.center&&t?.innerRadius>0&&t?.outerRadius&&t?.startAngle>0&&t?.startAngle<360&&t?.endAngle>0&&t?.endAngle<360}getFanShapeGeometryParameters(t){if(this.isFanShapeGeometryParametersValid())return!0;if(!this.isFanShapeGeometryParametersValid()){const n=t.getCurrentImageId(),e=rn("ultrasoundFanShapeGeometry",n);this.updateFanGeometryConfiguration(e)}return this.isFanShapeGeometryParametersValid()||this.deriveFanGeometryFromViewport(t),this.isFanShapeGeometryParametersValid()}calculateBLinePleuraPercentage(t){if(!this.getFanShapeGeometryParameters(t))return;const{imageData:n}=t.getImageData()||{};if(!n)return;const{element:e}=t,o=t.worldToCanvas(n.indexToWorld(this.configuration.center)),s=t.getCurrentImageId(),a=Yt(this.getToolName(),e)||[],r=a.filter(l=>l.data.annotationType===Ye.USPleuraBLineAnnotationType.PLEURA&&l.metadata.referencedImageId===s).map(l=>l.data.handles.points.map(u=>t.worldToCanvas(u))),c=a.filter(l=>l.data.annotationType===Ye.USPleuraBLineAnnotationType.BLINE&&l.metadata.referencedImageId===s).map(l=>l.data.handles.points.map(u=>t.worldToCanvas(u)));return K5(o,r,c)}getColorForLineType(t){const{annotationType:n}=t.data,{bLineColor:e,pleuraColor:o}=this.configuration;return n===Ye.USPleuraBLineAnnotationType.BLINE?e:n===Ye.USPleuraBLineAnnotationType.PLEURA?o:e}getIndexToCanvasRatio(t){const{imageData:n}=t.getImageData()||{},e=t.worldToCanvas(n.indexToWorld([1,0,0])),o=t.worldToCanvas(n.indexToWorld([2,0,0])),s=[o[0]-e[0],o[1]-e[1]];return Math.sqrt(s[0]*s[0]+s[1]*s[1])}drawDepthGuide(t,n){if(!this.getFanShapeGeometryParameters(n))return;const{imageData:e}=n.getImageData()||{};if(!e)return;const o=g=>g*180/Math.PI,s=g=>g*Math.PI/180,a=g=>n.worldToCanvas(zp(e,g)),r=this.configuration.innerRadius+this.configuration.depth_ratio*(this.configuration.outerRadius-this.configuration.innerRadius),c=this.configuration.startAngle,d=this.configuration.endAngle-c,u=s(d)*r;let h=Math.round(u/(this.configuration.depthGuideDashLength+this.configuration.depthGuideDashGap));h<=0&&(h=Math.max(15,Math.round(d/5)));const f=d/h;for(let g=0;g<h;g++){const m=s(c+g*f),p=s(c+g*f+o(this.configuration.depthGuideDashLength)/r),v=[this.configuration.center[0]+r*Math.cos(m),this.configuration.center[1]+r*Math.sin(m),0],I=[this.configuration.center[0]+r*Math.cos(p),this.configuration.center[1]+r*Math.sin(p),0];qt(t,n.id,`depthGuide-${g}`,a(v),a(I),{color:this.configuration.depthGuideColor,lineWidth:this.configuration.depthGuideThickness,strokeOpacity:this.configuration.depthGuideOpacity})}}_isInsideVolume(t,n,e){return gn(t,e)&&gn(n,e)}}Ye=Od;Od.toolName="UltrasoundPleuraBLineTool";Od.USPleuraBLineAnnotationType={BLINE:"bLine",PLEURA:"pleura"};Od.hydrate=(i,t,n)=>{const e=le(i);if(!e)return;const{FrameOfReferenceUID:o,referencedImageId:s,viewPlaneNormal:a,instance:r,viewport:c}=Ye.hydrateBase(Ye,e,t,n),{toolInstance:l,...d}=n||{},u={annotationUID:n?.annotationUID||Se(),data:{handles:{points:t}},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{toolName:r.getToolName(),viewPlaneNormal:a,FrameOfReferenceUID:o,referencedImageId:s,...d}};Nt(u,c.element),V([c.id])};function Z5(i,t){return[""]}class gg extends be{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{getTextCallback:J5,changeTextCallback:Q5,canvasPosition:[10,10],canvasSize:10,handleRadius:"6",seriesLevel:!1,isPoint:!1}}){super(t,n),this.addNewAnnotation=e=>{const o=e.detail,{element:s,currentPoints:a}=o,r=N(s),{viewport:c}=r,l=a.world,d=this.constructor.createAnnotationForViewport(c,{data:{handles:{points:[[...l]]},seriesLevel:this.configuration.seriesLevel,isPoint:this.configuration.isPoint}});Nt(d,s);const u=ft(s,this.getToolName());return e.preventDefault(),V(u),this.configuration.getTextCallback(h=>{if(!h){Gt(d.annotationUID),V(u),this.isDrawing=!1;return}d.data.label=h,ue(d),V(u)}),this.createMemo(s,d,{newAnnotation:!0}),d},this.isPointNearTool=(e,o,s,a)=>{const r=N(e),{viewport:c}=r,{data:l}=o;if(!l?.isPoint)return!1;const{canvasPosition:d,canvasSize:u}=this.configuration;return d?.length?Math.abs(s[0]-d[0]+u/2)<=u/2&&Math.abs(s[1]-d[1]+u/2)<=u/2:!1},this.toolSelectedCallback=(e,o)=>{o.highlighted=!0,e.preventDefault()},this._endCallback=e=>{const o=e.detail,{element:s}=o,{annotation:a,viewportIdsToRender:r,newAnnotation:c}=this.editData,{viewportId:l,renderingEngine:d}=N(s);this.eventDispatchDetail={viewportId:l,renderingEngineId:d.id},this._deactivateModify(s),Ft(s),c&&this.createMemo(s,a,{newAnnotation:c}),this.editData=null,this.isDrawing=!1,this.doneEditMemo(),this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&Gt(a.annotationUID),V(r),c&&ue(a)},this.doubleClickCallback=e=>{const o=e.detail,{element:s}=o;let a=Yt(this.getToolName(),s);if(a=this.filterInteractableAnnotationsForElement(s,a),!a?.length)return;const r=a.find(l=>this.isPointNearTool(s,l,o.currentPoints.canvas,6));if(!r)return;const c=r;this.createMemo(s,c),this.configuration.changeTextCallback(r,e.detail,this._doneChangingTextCallback.bind(this,s,c)),this.isDrawing=!1,this.doneEditMemo(),e.stopImmediatePropagation(),e.preventDefault()},this._dragCallback=e=>{this.isDrawing=!0;const o=e.detail,{currentPoints:s,element:a}=o,r=s.world,{annotation:c,viewportIdsToRender:l,newAnnotation:d}=this.editData,{data:u}=c;this.createMemo(a,c,{newAnnotation:d}),u.handles.points[0]=[...r],c.invalidated=!0,V(l)},this._activateModify=e=>{$.isInteractingWithTool=!0,e.addEventListener(E.MOUSE_UP,this._endCallback),e.addEventListener(E.MOUSE_DRAG,this._dragCallback),e.addEventListener(E.MOUSE_CLICK,this._endCallback),e.addEventListener(E.TOUCH_END,this._endCallback),e.addEventListener(E.TOUCH_DRAG,this._dragCallback),e.addEventListener(E.TOUCH_TAP,this._endCallback)},this._deactivateModify=e=>{$.isInteractingWithTool=!1,e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.TOUCH_END,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(e,o)=>{let s=!1;const{viewport:a}=e,{element:r}=a;let c=Yt(this.getToolName(),r);if(!c?.length||(c=this.filterInteractableAnnotationsForElement(r,c),!c?.length))return s;const l={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:e.viewport.id};for(let d=0;d<c.length;d++){const u=c[d],{annotationUID:h,data:f}=u;l.annotationUID=h;const{color:g,lineWidth:m}=this.getAnnotationStyle({annotation:u,styleSpecifier:l}),{canvasPosition:p,canvasSize:v}=this.configuration,I="1";if(f?.isPoint){const w=f.handles.points[0],C=a.worldToCanvas(w);xe(o,h,I,[C],{color:g,lineWidth:m,handleRadius:this.configuration.handleRadius})}else p?.length&&ll(o,h,I,p.map(w=>w+v),p,{color:g,width:1});if(s=!0,!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),s}return s}}handleSelectedCallback(t,n){const e=t.detail,{element:o}=e;n.highlighted=!0;const s=ft(o,this.getToolName());this.editData={annotation:n,viewportIdsToRender:s},this._activateModify(o),wt(o),V(s),t.preventDefault()}static setPoint(t,n=!t.data.isPoint,e){t.data.isPoint=n,zt(t,e)}_doneChangingTextCallback(t,n,e){n.data.label=e;const o=ft(t,this.getToolName());V(o),zt(n,t)}cancel(t){if(this.isDrawing){this.isDrawing=!1,this._deactivateModify(t),Ft(t);const{annotation:n,viewportIdsToRender:e,newAnnotation:o}=this.editData,{data:s}=n;return n.highlighted=!1,s.handles.activeHandleIndex=null,V(e),o&&ue(n),this.editData=null,n.annotationUID}}_isInsideVolume(t,n,e){return gn(t,e)&&gn(n,e)}}gg.toolName="KeyImage";gg.dataSeries={data:{seriesLevel:!0}};gg.dataPoint={data:{isPoint:!0}};function J5(i){return i(prompt("Enter your annotation:"))}function Q5(i,t,n){return n(prompt("Enter your annotation:"))}class tF extends Ee{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"]}){super(t,n),this.preMouseDownCallback=e=>this._deleteNearbyAnnotations(e,"mouse"),this.preTouchStartCallback=e=>this._deleteNearbyAnnotations(e,"touch")}_deleteNearbyAnnotations(t,n){const{renderingEngineId:e,viewportId:o,element:s,currentPoints:a}=t.detail,r=Ae(o,e);if(!r)return!1;const c=r._toolInstances,l=[];for(const d in c){const u=c[d];if(typeof u.isPointNearTool!="function"||typeof u.filterInteractableAnnotationsForElement!="function")continue;const h=Yt(d,s),f=u.filterInteractableAnnotationsForElement(s,h);if(f)for(const g of f)u.isPointNearTool(s,g,a.canvas,10,n)&&l.push(g.annotationUID)}for(const d of l){So(d);const u=ne(d);be.createAnnotationMemo(s,u,{deleting:!0}),Gt(d)}return t.preventDefault(),!0}}tF.toolName="Eraser";const{transformWorldToIndex:$p,transformIndexToWorld:eF}=oe;class Si extends Ee{constructor(t,n){const e=Hn({configuration:{positiveStdDevMultiplier:gc,shrinkExpandIncrement:.1,islandRemoval:{enabled:!1}}},n);super(t,e)}async preMouseDownCallback(t){const n=t.detail,{element:e,currentPoints:o}=n,{world:s}=o,a=N(e),{viewport:r,renderingEngine:c}=a,{viewUp:l}=ht(r),{segmentationId:d,segmentIndex:u,labelmapVolumeId:h,referencedVolumeId:f}=await this.getLabelmapSegmentationData(r);if(!this._isOrthogonalView(r,f))throw new Error("Oblique view is not supported yet");return this.growCutData={metadata:{...r.getViewReference({points:[s]}),viewUp:l},segmentation:{segmentationId:d,segmentIndex:u,labelmapVolumeId:h,referencedVolumeId:f},viewportId:r.id,renderingEngineId:c.id},t.preventDefault(),!0}shrink(){this._runLastCommand({shrinkExpandAmount:-this.configuration.shrinkExpandIncrement})}expand(){this._runLastCommand({shrinkExpandAmount:this.configuration.shrinkExpandIncrement})}refresh(){this._runLastCommand()}async getGrowCutLabelmap(t){throw new Error("Not implemented")}async runGrowCut(){const{growCutData:t,configuration:n}=this,{segmentation:{segmentationId:e,segmentIndex:o,labelmapVolumeId:s}}=t,a=Q.getVolume(s);let r=0;const c=async({shrinkExpandAmount:l=0}={})=>{l!==0&&(this.seeds=null),r+=l;const d=Math.max(.1,n.positiveStdDevMultiplier+r),u=l<0?Math.max(1,ch-Math.abs(r)*3):ch+r*3,h={...t,options:{...t.options||{},positiveSeedValue:o,negativeSeedValue:255,positiveStdDevMultiplier:d,negativeSeedMargin:u}},f=await this.getGrowCutLabelmap(h),{isPartialVolume:g}=n;(g?this.applyPartialGrowCutLabelmap:this.applyGrowCutLabelmap)(e,o,a,f),this._removeIslands(h)};await c(),Si.lastGrowCutCommand=c,this.growCutData=null}applyPartialGrowCutLabelmap(t,n,e,o){const s=o.voxelManager.getCompleteScalarDataArray(),a=e.voxelManager,[r,c,l]=o.dimensions,[d,u]=e.dimensions,h=r*c,f=d*u;for(let g=0;g<l;g++)for(let m=0;m<c;m++){const p=[0,m,g],v=eF(o.imageData,p),I=$p(e.imageData,v),[w,C,S]=I,b=m*r+g*h,_=w+C*d+S*f;for(let y=0;y<r;y++){const D=s[b+y]===n?n:0;a.setAtIndex(_+y,D)}}He(t)}applyGrowCutLabelmap(t,n,e,o){const s=e.voxelManager;o.voxelManager.forEach(({value:r,index:c})=>{r===n&&s.setAtIndex(c,r)}),He(t)}_runLastCommand({shrinkExpandAmount:t=0}={}){const n=Si.lastGrowCutCommand;n&&n({shrinkExpandAmount:t})}async getLabelmapSegmentationData(t){const n=ni(t.id);if(!n)throw new Error("No active segmentation found");const{segmentationId:e}=n,o=xn(e),{representationData:s}=Dt(e),a=s[St.Labelmap];let{volumeId:r,referencedVolumeId:c}=a;if(!r){const l=t.getImageIds();if(Ss(l))r=Ma(e).volumeId;else{const d=t.getCurrentImageId(),u=Q.getImage(d),h=Cg(d);c=this._createFakeVolume([u.imageId,h.imageId]).volumeId;const g=Zi(t.id,e),m=Cg(g);r=this._createFakeVolume([g,m.imageId]).volumeId}}if(!c){const{imageIds:l}=a,d=l.map(f=>Q.getImage(f).referencedImageId),u=Q.generateVolumeId(d),h=Q.getVolume(u);c=h?h.volumeId:(await jr(u,d)).volumeId}return{segmentationId:e,segmentIndex:o,labelmapVolumeId:r,referencedVolumeId:c}}_createFakeVolume(t){const n=Q.generateVolumeId(t),e=Q.getVolume(n);if(e)return e;const o=WC(t,n),s=o.spacing;s[2]===0&&(s[2]=1);const a=new BC({volumeId:n,dataType:o.dataType,metadata:Re(o.metadata),dimensions:o.dimensions,spacing:o.spacing,origin:o.origin,direction:o.direction,referencedVolumeId:o.referencedVolumeId,imageIds:o.imageIds,referencedImageIds:o.referencedImageIds});return Q.putVolumeSync(n,a),a}_isOrthogonalView(t,n){const o=Q.getVolume(n).imageData,s=ht(t),{ijkVecColDir:a,ijkVecSliceDir:r}=Rh(o,s);return[a,r].every(c=>ve(Math.abs(c[0]),1)||ve(Math.abs(c[1]),1)||ve(Math.abs(c[2]),1))}getRemoveIslandData(t){}_removeIslands(t){const{islandRemoval:n}=this.configuration;if(!n.enabled)return;const{segmentation:{segmentIndex:e,labelmapVolumeId:o},renderingEngineId:s,viewportId:a}=t,r=Q.getVolume(o),c=this.getRemoveIslandData(t);if(!c)return;const[l,d]=r.dimensions,u=l*d,{worldIslandPoints:h=[],islandPointIndexes:f=[]}=c;let g=[...c?.ijkIslandPoints??[]];const p=Ne(s).getViewport(a),{voxelManager:v}=r,I=new zi;g=g.concat(h.map(w=>$p(r.imageData,w))),g=g.concat(f.map(w=>{const C=w%l,S=Math.floor(w/l)%d,b=Math.floor(w/u);return[C,S,b]})),I.initialize(p,v,{points:g,previewSegmentIndex:e,segmentIndex:e}),I.floodFillSegmentIsland(),I.removeExternalIslands(),I.removeInternalIslands()}getSegmentStyle({segmentationId:t,viewportId:n,segmentIndex:e}){return Gw({segmentationId:t,segmentIndex:e,viewportId:n})}}Si.lastGrowCutCommand=null;Si.toolName="GrowCutBaseTool";class nF extends Si{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{isPartialVolume:!0,positiveSeedVariance:.5,negativeSeedVariance:.9}}){super(t,n),this._dragCallback=e=>{const o=e.detail,{element:s,currentPoints:a}=o,{world:r}=a,c=N(s),{viewport:l}=c;this.growCutData.circleBorderPoint=r,V([l.id])},this._endCallback=async e=>{const o=e.detail,{element:s}=o,a=N(s),{viewport:r}=a;this.runGrowCut(),this._deactivateDraw(s),this.growCutData=null,Ft(s),V([r.id])},this._deactivateDraw=e=>{e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.TOUCH_END,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback)}}async preMouseDownCallback(t){const n=t.detail,{element:e,currentPoints:o}=n,{world:s}=o,a=N(e),{viewport:r,renderingEngine:c}=a;return await super.preMouseDownCallback(t),Object.assign(this.growCutData,{circleCenterPoint:s,circleBorderPoint:s}),this._activateDraw(e),wt(e),V([r.id]),!0}async getGrowCutLabelmap(t){const{segmentation:{referencedVolumeId:n},renderingEngineId:e,viewportId:o,circleCenterPoint:s,circleBorderPoint:a,options:r}=t,{positiveSeedVariance:c,negativeSeedVariance:l,positiveStdDevMultiplier:d}=this.configuration,u=d??1,f=(r?.positiveStdDevMultiplier?Math.max(r.positiveStdDevMultiplier,.01):u)/u,g={...r,positiveSeedVariance:Math.max(.01,(c??1)*f),negativeSeedVariance:Math.max(.01,(l??1)*f)},p=Ne(e).getViewport(o),v=mr(tn(B(),s,a));return OE(n,{center:s,radius:v},p,g)}_activateDraw(t){t.addEventListener(E.MOUSE_UP,this._endCallback),t.addEventListener(E.MOUSE_DRAG,this._dragCallback),t.addEventListener(E.MOUSE_CLICK,this._endCallback),t.addEventListener(E.TOUCH_END,this._endCallback),t.addEventListener(E.TOUCH_DRAG,this._dragCallback),t.addEventListener(E.TOUCH_TAP,this._endCallback)}renderAnnotation(t,n){if(!this.growCutData)return;const{viewport:e}=t,{segmentation:o,circleCenterPoint:s,circleBorderPoint:a}=this.growCutData,r=e.worldToCanvas(s),c=e.worldToCanvas(a),l=No(It(),c,r),d=uy(l);if(ve(d,0))return;const u="growcut",h="0",{color:f}=this.getSegmentStyle({segmentationId:o.segmentationId,segmentIndex:o.segmentIndex,viewportId:e.id});En(n,u,h,r,d,{color:f})}}nF.toolName="RegionSegment";class oF extends Si{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{isPartialVolume:!1,positiveSeedVariance:.4,negativeSeedVariance:.9,subVolumePaddingPercentage:.1,islandRemoval:{enabled:!1}}}){super(t,n),this.mouseTimer=null,this.allowedToProceed=!1}mouseMoveCallback(t){if(this.mode!==se.Active)return;const n=t.detail,{currentPoints:e,element:o}=n,{world:s}=e;o.style.cursor="default",this.mouseTimer!==null&&(window.clearTimeout(this.mouseTimer),this.mouseTimer=null),this.mouseTimer=window.setTimeout(()=>{this.onMouseStable(t,s,o)},this.configuration.mouseStabilityDelay||500)}async onMouseStable(t,n,e){await super.preMouseDownCallback(t);const o=Q.getVolume(this.growCutData.segmentation.referencedVolumeId),s=NE(o,n,{})||{positiveSeedIndices:new Set,negativeSeedIndices:new Set},{positiveSeedIndices:a,negativeSeedIndices:r}=s;let c;a.size/r.size>20||r.size<30?(c="not-allowed",this.allowedToProceed=!1):(c="copy",this.allowedToProceed=!0);const l=N(e);e&&(e.style.cursor=c,requestAnimationFrame(()=>{e.style.cursor!==c&&(e.style.cursor=c)})),this.allowedToProceed&&(this.seeds=s),l&&l.viewport&&l.viewport.render()}async preMouseDownCallback(t){if(!this.allowedToProceed)return!1;const n=t.detail,{currentPoints:e,element:o}=n;N(o)&&(o.style.cursor="wait",requestAnimationFrame(()=>{o.style.cursor!=="wait"&&(o.style.cursor="wait")}));const{world:a}=e;return await super.preMouseDownCallback(t),this.growCutData=Hn(this.growCutData,{worldPoint:a,islandRemoval:{worldIslandPoints:[a]}}),this.growCutData.worldPoint=a,this.growCutData.islandRemoval={worldIslandPoints:[a]},await this.runGrowCut(),o&&(o.style.cursor="default"),!0}getRemoveIslandData(t){const{worldPoint:n}=t;return{worldIslandPoints:[n]}}async getGrowCutLabelmap(t){const{segmentation:{referencedVolumeId:n},worldPoint:e,options:o}=t,{subVolumePaddingPercentage:s}=this.configuration,a={...o,subVolumePaddingPercentage:s,seeds:this.seeds};return kE({referencedVolumeId:n,worldPosition:e,options:a})}}oF.toolName="RegionSegmentPlus";const{logger:iF}=oe,{growCutLog:Fs}=iF;class Ol extends zi{constructor(t){super(t),this.verboseLogging=!1,this.usingPreviewLayer=!1,this.internalFilledPoints=[],this.verboseLogging=t?.verboseLogging??this.verboseLogging}initialize(t,n,e){this.usingPreviewLayer=!!n.sourceVoxelManager;const o=super.initialize(t,n,e);if(o&&this.verboseLogging){const{segmentSet:s}=this;Fs.info("islandRemoval: initialize",{segmentIndex:this.segmentIndex,previewSegmentIndex:this.previewSegmentIndex,segmentSetDimensions:{width:s.width,height:s.height,depth:s.depth},boundsIJKPrime:s.normalizer.boundsIJKPrime,clickedPoints:this.selectedPoints,segmentVoxelsInPlaneGrid:Ol.countRleValueVolume(s,sn.SEGMENT)})}return o}static countRleValueVolume(t,n){let e=0;return t.forEach((o,s)=>{s.value===n&&(e+=s.end-s.start)}),e}floodFillSegmentIsland(){if(this.verboseLogging){const{selectedPoints:n,segmentSet:e}=this,{fromIJK:o}=e.normalizer;for(const s of n){const a=o(s),r=e.get(e.toIndex(a));r!==sn.SEGMENT&&Fs.info("islandRemoval: floodFillSegmentIsland click skipped (not SEGMENT)",{clickedPointVolumeIJK:s,ijkPrime:a,segmentSetAtIndex:r})}}const t=super.floodFillSegmentIsland();return this.verboseLogging&&Fs.info("islandRemoval: floodFillSegmentIsland done",{totalIslandVoxels:t,islandVoxelsAfterFlood:Ol.countRleValueVolume(this.segmentSet,sn.ISLAND)}),t}removeExternalIslands(){const{previewVoxelManager:t,segmentSet:n}=this,{toIJK:e}=n.normalizer,o=t.sourceVoxelManager??t;if(!this.usingPreviewLayer)return Fs.warn("islandRemoval: removeExternalIslands has no preview layer; external island cleanup of accepted voxels is skipped. Run island removal through a preview layer to clear external islands."),0;let s=0;const a=(r,c)=>{const[,l,d]=n.toIJK(r);if(c.value!==sn.ISLAND)for(let u=c.start;u<c.end;u++){const h=e([u,l,d]);o.getAtIJKPoint(h)===this.previewSegmentIndex&&(t.setAtIJKPoint(h,null),s+=1)}};return n.forEach(a,{rowModified:!0}),this.verboseLogging&&Fs.info("islandRemoval: removeExternalIslands",{clearedVoxels:s}),s}removeInternalIslands(){this.internalFilledPoints=[];const t=super.removeInternalIslands();return this.verboseLogging&&Fs.info("islandRemoval: removeInternalIslands",{modifiedSliceCount:t?.length,internalFilledPoints:this.internalFilledPoints.length,maxInternalRemove:this.maxInternalRemove}),t}onInternalPointFilled(t){this.internalFilledPoints.push(t)}getInternalFilledPoints(){return this.internalFilledPoints}}const os=1;async function US(i,t,n){const{width:e,height:o,depth:s,equals:a,ensureSliceLoaded:r,yieldEvery:c=500,planar:l=!1,maxDeltaK:d,maxDeltaIJ:u,isCancelled:h,maxVoxels:f,shouldContinue:g,validateEvery:m=2048}=n,[p,v,I]=t;if(p<0||p>=e||v<0||v>=o||I<0||I>=s)return{sliceMasks:new Map,voxelCount:0,truncated:!1,bbox:null};r&&await r(I);const w=i(p,v,I);if(!a(w,w))return{sliceMasks:new Map,voxelCount:0,truncated:!1,bbox:null};const C=e*o,S=new Map;function b(tt){let ot=S.get(tt);return ot||(ot=new Uint8Array(C),S.set(tt,ot)),ot}function _(tt,ot,nt){const lt=S.get(tt);return lt?(lt[nt*e+ot]&os)!==0:!1}function y(tt,ot,nt){b(tt)[nt*e+ot]|=os}function D(tt,ot,nt){return nt*C+ot*e+tt}function T(tt){const ot=tt%e,nt=Math.floor(tt/e),lt=nt%o,rt=Math.floor(nt/o);return[ot,lt,rt]}const P=l?[[1,0,0],[-1,0,0],[0,1,0],[0,-1,0]]:[[1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[0,0,1],[0,0,-1]],x=[];let M=0;x.push(D(p,v,I)),y(I,p,v);let L=p,R=p,U=v,W=v,K=I,j=I;const F=()=>({min:[L,U,K],max:[R,W,j]});let z=0,q=!1,J=m;for(;M<x.length&&!h?.();){if(f!==void 0&&x.length>f){q=!0;break}if(g&&x.length>=J&&(J+=m,!g({voxelCount:x.length,bbox:F()}))){q=!0;break}z++,c>0&&z%c===0&&await new Promise(rt=>setTimeout(rt,0));const tt=x[M++],[ot,nt,lt]=T(tt);for(let rt=0;rt<P.length;rt++){const ut=ot+P[rt][0],Tt=nt+P[rt][1],kt=lt+P[rt][2];if(ut<0||ut>=e||Tt<0||Tt>=o||kt<0||kt>=s||d>=0&&Math.abs(kt-I)>d||u>=0&&(Math.abs(ut-p)>u||Math.abs(Tt-v)>u)||l&&kt!==I||_(kt,ut,Tt))continue;if(r&&(await r(kt),h?.()))break;const Pt=i(ut,Tt,kt);a(Pt,w)&&(y(kt,ut,Tt),x.push(D(ut,Tt,kt)),ut<L?L=ut:ut>R&&(R=ut),Tt<U?U=Tt:Tt>W&&(W=Tt),kt<K?K=kt:kt>j&&(j=kt))}}const it=x.length;return{sliceMasks:S,voxelCount:it,truncated:q,bbox:it>0?F():null}}const{VoxelManager:jp}=oe;function sF({labelmapVolume:i,sliceMasks:t,width:n,height:e,paintIndex:o,historyVoxelManager:s}){const a=[];let r=0;const c=i.voxelManager,l=s,[d,u,h]=i.dimensions;if(d!==n||u!==e)throw new Error(`commitSliceMasksToLabelmapVolume: labelmap in-plane dimensions ${d}x${u} do not match mask dimensions ${n}x${e}`);const f=n*e,g=f*h,m=Array.from(t.keys()).sort((p,v)=>p-v);for(let p=0;p<m.length;p++){const v=m[p];if(v<0||v>=h)continue;const I=t.get(v);if(!I||I.length!==f)continue;let w=!1,C=1/0,S=1/0,b=-1/0,_=-1/0;const y=(T,P,x)=>{for(let M=P;M<x;M++)a.push([M,T,v]);r+=x-P,w=!0,C=Math.min(C,P),b=Math.max(b,x-1),S=Math.min(S,T),_=Math.max(_,T)};if(!l&&c.scalarData&&c.scalarData.length>=g&&typeof c.scalarData.fill=="function"){const T=v*f,P=c.scalarData;for(let x=0;x<e;x++){const M=x*n;for(let L=0;L<n;){const R=M+L;if(!(I[R]&os)){L++;continue}const U=L;for(;L<n&&I[M+L]&os;)L++;P.fill(o,T+M+U,T+M+L),y(x,U,L)}}}else{const T=i.imageIds,x=(T?.length&&v<T.length?Q.getImage(T[v]):null)?.voxelManager;if(!l&&x?.scalarData&&x.scalarData.length>=f&&typeof x.scalarData.fill=="function"){const M=x.scalarData;for(let L=0;L<e;L++){const R=L*n;for(let U=0;U<n;){const W=R+U;if(!(I[W]&os)){U++;continue}const K=U;for(;U<n&&I[R+U]&os;)U++;M.fill(o,R+K,R+U),y(L,K,U)}}x.modifiedSlices.add(v)}else{const M=l??c;for(let L=0;L<e;L++){const R=L*n;for(let U=0;U<n;U++){if(!(I[R+U]&os))continue;const W=v*f+R+U;M.setAtIndex(W,o),a.push([U,L,v]),r++,w=!0,C=Math.min(C,U),b=Math.max(b,U),S=Math.min(S,L),_=Math.max(_,L)}}}}w&&(c.modifiedSlices.add(v),Number.isFinite(C)&&Number.isFinite(S)&&Number.isFinite(b)&&Number.isFinite(_)&&(jp.addBounds(c.boundsIJK,[C,S,v]),jp.addBounds(c.boundsIJK,[b,_,v])))}return{floodedPoints:a,voxelCount:r}}function aF(i){const t=i.dimensions[2],n=i.imageIds;if(!n?.length)return async()=>{};const e=new Set,o=new Map;return async function(a){if(!Number.isFinite(a)||a<0||a>=t||e.has(a))return;const r=o.get(a);if(r)return r;const c=n[a];if(!c)return;const l=zC(c).then(()=>{e.add(a)}).finally(()=>{o.delete(a)});return o.set(a,l),l}}function VS(i,t,n,e,o){const[s,a,r]=t;let c=0,l=0,d=0;const[u,h,f]=n.map(Math.round);for(let v=f-e;v<=f+e;v++)if(!(v<0||v>=r)){for(let I=h-e;I<=h+e;I++)if(!(I<0||I>=a))for(let w=u-e;w<=u+e;w++){if(w<0||w>=s)continue;const C=Number(i.getAtIJK(w,I,v)),S=o?o(C):C;c+=S,l+=S*S,d++}}if(d===0){if(u>=0&&u<s&&h>=0&&h<a&&f>=0&&f<r){const v=Number(i.getAtIJK(u,h,f));return{mean:o?o(v):v,stdDev:0,count:1}}return{mean:0,stdDev:0,count:0}}const g=c/d,m=l/d-g*g,p=Math.sqrt(Math.max(0,m));return{mean:g,stdDev:p,count:d}}function Rd(i,t){const n=i.getProperties;if(typeof n!="function")return null;const e=t?n.call(i,t):n.call(i);if(!e?.voiRange)return null;const{lower:o,upper:s}=e.voiRange;return typeof o!="number"||typeof s!="number"?null:{voiRange:{lower:o,upper:s},VOILUTFunction:e.VOILUTFunction,invert:e.invert===!0}}const{transformWorldToIndex:FS,mapScalarToViewportVoiIntensity:GS,mapMappedBandToRawRange:HS}=oe,{growCutLog:un}=Ah,Xp=!1,qp=i=>{},Yp=i=>{},Kp="cornerstone.tools: floodFill: islandRemoval:external",Zp="cornerstone.tools: floodFill: islandRemoval:internal";function rF(i,t){const n=i.getProperties;if(typeof n!="function")return null;const o=(t?n.call(i,t):n.call(i))?.voiRange;if(!o||typeof o.lower!="number"||typeof o.upper!="number")return null;const{lower:s,upper:a}=o;return{lower:s,upper:a,windowWidth:a-s,windowCenter:(s+a)/2}}function cF(i,t,n){const{dimensions:e,imageData:o}=i,[s,a,r]=e,c=i.voxelManager,l=n?.initialNeighborhoodRadius??qf,d=n?.positiveStdDevMultiplier??gc,u=FS(o,t).map(Math.round);if(u[0]<0||u[0]>=s||u[1]<0||u[1]>=a||u[2]<0||u[2]>=r)return un.warn("intensity range: click outside volume",{ijkStart:u,dimensions:[s,a,r]}),null;const h=VS(c,e,u,l);if(h.count===0){const p=Number(c.getAtIJKPoint(u));h.mean=p,h.stdDev=0}const f=h.mean-d*h.stdDev,g=h.mean+d*h.stdDev,m=c.getAtIJKPoint(u);return m<f||m>g?(un.warn("intensity range: clicked voxel intensity is outside the calculated positive range"),null):{min:f,max:g,ijkStart:u,diagnostics:{neighborhoodMean:h.mean,neighborhoodStdDev:h.stdDev,clickedVoxelValue:m,positiveStdDevMultiplier:d,neighborhoodRadius:l,strategy:"meanStdRaw"}}}function lF(i,t,n,e){const{dimensions:o,imageData:s}=i,[a,r,c]=o,l=i.voxelManager,d=e?.initialNeighborhoodRadius??qf,u=e?.positiveStdDevMultiplier??gc,h=FS(s,t).map(Math.round);if(h[0]<0||h[0]>=a||h[1]<0||h[1]>=r||h[2]<0||h[2]>=c)return un.info("intensity range (VOI-mapped): click outside volume",{ijkStart:h,dimensions:[a,r,c]}),null;const f=y=>GS(y,n),g=VS(l,o,h,d,f);if(g.count===0){const y=Number(l.getAtIJKPoint(h));g.mean=f(y),g.stdDev=0}let m=g.mean-u*g.stdDev,p=g.mean+u*g.stdDev;if(m=Math.max(0,Math.min(1,m)),p=Math.max(0,Math.min(1,p)),m>p){const y=m;m=p,p=y}const{rawMin:v,rawMax:I}=HS(m,p,n),w=Number(l.getAtIJKPoint(h)),C=Math.min(v,I),S=Math.max(v,I),b=Math.min(C,w),_=Math.max(S,w);return{min:b,max:_,ijkStart:h,diagnostics:{neighborhoodMean:g.mean,neighborhoodStdDev:g.stdDev,clickedVoxelValue:w,positiveStdDevMultiplier:u,neighborhoodRadius:d,strategy:"meanStdVoiMapped",mappedBand:{min:m,max:p}}}}function Jp(i,t,n){return n?.voiMapping?lF(i,t,n.voiMapping,n):cF(i,t,n)}function dF(i,t,n,e,o,s){if(o.getIntensityRange){const l=o.getIntensityRange(i,t,s);return l||un.warn("flood fill intensity range: strategy/custom getIntensityRange returned null (e.g. missing canvasPoint/VOI for canvas-disk, click outside volume, or fixed-% rejection)",{referencedVolumeId:e,worldPosition:t}),l}const a=Rd(n,e),r={...s,voiMapping:a??void 0};let c=Jp(i,t,r);return!c&&r.voiMapping&&(un.info("flood fill intensity range: VOI-mapped mean±σ failed; falling back to raw mean±σ",{referencedVolumeId:e}),c=Jp(i,t,{...r,voiMapping:void 0})),c||un.warn("flood fill intensity range: default mean±σ (VOI + raw fallback) could not resolve a band",{referencedVolumeId:e,worldPosition:t}),c}function uF(i,t){const[n,e,o]=i.dimensions,[s,a,r]=t.dimensions;if(n!==s||e!==a||o!==r)throw new Error(`runFloodFillSegmentation: labelmap dimensions [${s},${a},${r}] must match referenced volume [${n},${e},${o}]`)}function hF(i,t){return t!==void 0?{paintIndex:t,usePreview:t!==i}:i===255?{paintIndex:255,usePreview:!1}:{paintIndex:255,usePreview:!0}}function Pu(i,t,n,e,o,s,a){for(let r=0;r<o.length;r++){const[c,l,d]=o[r],u=d*s+l*a+c;i.getAtIndex(u)===n&&t.setAtIndex(u,e)}}async function fF({referencedVolumeId:i,worldPosition:t,viewport:n,labelmapVolume:e,options:o={}}){const s=Q.getVolume(i);uF(s,e);const a=e,r=o.segmentIndex??1,{paintIndex:c,usePreview:l}=hF(r,o.floodPreviewSegmentIndex),[d,u]=s.voxelManager.getRange(),h=rF(n,i);un.info("segmentation path: flood fill (floodfill_full)",{referencedVolumeId:i,volumeScalarRange:{min:d,max:u},displayVoi:h,floodPreview:l?c:null,segmentIndex:r});const f=Rd(n,i),g={positiveStdDevMultiplier:o.positiveStdDevMultiplier,initialNeighborhoodRadius:o.initialNeighborhoodRadius,viewport:n,element:o.element,referencedVolumeId:i,canvasPoint:o.canvasPoint,canvasDiskRadiusPx:o.intensitySamplingDiskRadiusCanvasPx,voiMapping:f??void 0},m=dF(s,t,n,i,o,g);if(!m)return un.warn("flood fill: aborted before fill (no intensity range)",{referencedVolumeId:i,worldPosition:t}),null;const{min:p,max:v,ijkStart:I,diagnostics:w}=m;let C=p,S=v;const b=.2;if(f&&w?.mappedBand){const _=w.mappedBand,y=Math.max(0,Math.min(1,Math.min(_.min,_.max))),D=Math.max(0,Math.min(1,Math.max(_.min,_.max))),T=D-y;if(T>b){const P=Number(s.voxelManager.getAtIJKPoint(I)),x=Math.max(0,Math.min(1,GS(P,f))),M=b/2,L=Math.max(0,x-M),R=Math.min(1,x+M),{rawMin:U,rawMax:W}=HS(L,R,f);C=Math.min(U,W,P),S=Math.max(U,W,P),un.info("flood fill: clipped wide WL band around seed",{maxWlBandFraction:b,originalMappedBand:{min:y,max:D,width:T},clippedMappedBand:{min:L,max:R,width:R-L}})}}un.info("intensity tolerance band",{toleranceMin:C,toleranceMax:S,width:S-C,...w});{const{dimensions:_}=s,[y,D,T]=_,P=s.voxelManager,x=y*D,M=a.voxelManager,L=o.historyVoxelManager??a.voxelManager;let R=C,U=S;const W=Number(P.getAtIJKPoint(I));Number.isFinite(W)&&(W<R&&(un.info("flood fill: expanded tolerance min to include seed voxel",{seedScalar:W,previousMin:R}),R=W),W>U&&(un.info("flood fill: expanded tolerance max to include seed voxel",{seedScalar:W,previousMax:U}),U=W));const K=(Ht,Jt,Pe)=>{if(Ht<0||Ht>=y||Jt<0||Jt>=D||Pe<0||Pe>=T)return;const De=Pe*x+Jt*y+Ht;return P.getAtIndex(De)},j=Ht=>Ht>=R&&Ht<=U,F=o.ensureSliceLoaded??aF(s),z=o.planar===!0;z&&un.info("flood fill: planar mode (fixed slice index k)",{ijkStart:I});const{sliceMasks:q,voxelCount:J,truncated:it,bbox:tt}=await US(K,I,{width:y,height:D,depth:T,equals:(Ht,Jt)=>Ht!==void 0&&typeof Ht=="number"&&j(Ht),ensureSliceLoaded:F,yieldEvery:o.yieldEvery??500,planar:z,maxDeltaK:o.maxDeltaK,maxDeltaIJ:o.maxDeltaIJ,isCancelled:o.isCancelled,maxVoxels:o.maxVoxels,shouldContinue:o.shouldContinueRegion}),ot=!it&&tt&&o.shouldContinueRegion&&!o.shouldContinueRegion({voxelCount:J,bbox:tt});if(it||ot)return un.warn("flood fill: rejected — region stopped by budget or shape gate; nothing committed",{maxVoxels:o.maxVoxels,voxelCountAtStop:J,bbox:tt,ijkStart:I}),o.onRejected?.({voxelCount:J,bbox:tt}),null;if(J===0)return un.info("flood fill: zero voxels (range may be too tight or seed isolated)",{ijkStart:I,toleranceMin:R,toleranceMax:U}),a;if(o.isCancelled?.()===!0)return un.info("flood fill: cancellation requested; nothing committed",{ijkStart:I,voxelCountAtCancel:J}),null;const{floodedPoints:nt,voxelCount:lt}=sF({labelmapVolume:a,sliceMasks:q,width:y,height:D,paintIndex:c,historyVoxelManager:o.historyVoxelManager});if(lt===0||nt.length===0)return un.warn("flood fill: commit produced no labelmap voxels",{filledVoxelCount:J,committedVoxels:lt,ijkStart:I}),a;let rt=nt;un.info("flood fill: complete",{voxelCount:nt.length,ijkStart:I,paintIndex:c,usePreview:l});const ut=o.applyExternalIslandRemoval!==!1,Tt=o.applyInternalIslandRemoval!==!1&&ut;if(!ut&&!Tt)return l&&Pu(M,L,c,r,nt,x,y),o.onCommitted?.(rt),a;const kt=o.islandRemovalVerboseLogging===!0,Pt=new Ol({maxInternalRemove:o.maxInternalRemove??128,fillInternalEdge:!1,verboseLogging:kt}),te=[I];if(!Pt.initialize(n,o.historyVoxelManager??a.voxelManager,{points:te,segmentIndex:r,previewSegmentIndex:l?c:r}))return un.warn("island removal: initialize failed",{segmentIndex:r,ijkStart:I}),l&&Pu(M,L,c,r,nt,x,y),o.onCommitted?.(rt),a;let re=0,Zt=0,ce;ut&&(qp(Kp),re=Pt.floodFillSegmentIsland(),Zt=Pt.removeExternalIslands(),Yp(Kp),Tt&&(qp(Zp),ce=Pt.removeInternalIslands()?.length,Yp(Zp))),un.info("island removal: complete",{segmentIndex:r,applyExternalIslandRemoval:ut,applyInternalIslandRemoval:Tt,floodedPointsBeforeIsland:nt.length,islandFloodVoxelsFromSegmentSet:re,externalIslandClearVoxels:Zt,internalRemovalModifiedSlices:ce,islandRemovalVerboseLogging:kt});const Ut=Tt?Pt.getInternalFilledPoints():[];return rt=Ut.length>0?nt.concat(Ut):nt,l&&Pu(M,L,c,r,rt,x,y),o.onCommitted?.(rt),Xp&&nt.length>0,a}}const{transformWorldToIndex:gF,mapScalarToViewportVoiIntensity:mF,mapViewportVoiIntensityToScalar:pF,getVolumeDirectionVectors:vF}=oe,{growCutLog:IF}=Ah,Uc=96,Li=4,wF=6,EF=8,SF=.6,CF=10,bF=2,Qp=4,_F=3,yF=.02;function tv(i){if(!i.length)return 0;const t=i.slice().sort((n,e)=>n-e);return t[Math.floor(t.length/2)]}function WS(i,t){const{seedByte:n,polarity:e,voiMapping:o,rawWindow:s,seedScalar:a}=i,r=Math.max(0,Math.min(255,e>0?n-t:n+t)),c=e>0?255:0,l=g=>o?pF(g/255,o):s.min+g/255*s.span,d=l(r),u=l(c);let h,f;return u>=d?(h=d,f=1/0):(h=-1/0,f=d),Number.isFinite(a)&&(h=Math.min(h,a),f=Math.max(f,a)),{min:h,max:f}}function xF(i,t){const n=Math.max(0,Math.min(255,Math.round(t))),{min:e,max:o}=WS(i,n);return{min:e,max:o,ijkStart:[...i.seedIjk],diagnostics:{neighborhoodMean:Number.isFinite(i.seedScalar)?i.seedScalar:0,neighborhoodStdDev:0,clickedVoxelValue:Number.isFinite(i.seedScalar)?i.seedScalar:0,positiveStdDevMultiplier:1,neighborhoodRadius:Li,strategy:"adaptiveRegion:atTolerance",adaptive:{toleranceBytes:n,regionSizePx:-1,backgroundByte:-1,seedByte:i.seedByte,seedSnapped:!1,windowSize:[0,0],polarity:i.polarity}}}}function PF(i){const{dimensions:t,getScalar:n,ijkClick:e,voiMapping:o}=i,s=i.inPlaneAxes??[0,1],a=i.inPlaneSpacing??[1,1];for(let st=0;st<3;st++)if(e[st]<0||e[st]>=t[st])return{viable:!1,reason:"outside-volume",range:null};const[r,c]=s,l=Math.max(0,e[r]-Uc),d=Math.min(t[r]-1,e[r]+Uc),u=Math.max(0,e[c]-Uc),h=Math.min(t[c]-1,e[c]+Uc),f=d-l+1,g=h-u+1,m=f*g,p=Number.isFinite(a[0])&&a[0]>0?a[0]:1,v=Number.isFinite(a[1])&&a[1]>0?a[1]:1,I=p*v,w=Math.max(wF,Math.ceil(EF/I)),C=Math.max(w+1,Math.floor(m*SF)),S=(st,Mt)=>{const G=[...e];return G[r]=l+st,G[c]=u+Mt,Number(n(G[0],G[1],G[2]))},b=new Float64Array(m);let _=1/0,y=-1/0;for(let st=0;st<g;st++)for(let Mt=0;Mt<f;Mt++){const G=S(Mt,st);b[st*f+Mt]=G,Number.isFinite(G)&&(G<_&&(_=G),G>y&&(y=G))}if(!Number.isFinite(_))return{viable:!1,reason:"outside-volume",range:null};const D=y-_||1,T=new Int16Array(m);for(let st=0;st<m;st++){const Mt=b[st];if(!Number.isFinite(Mt)){T[st]=-1;continue}const G=o?mF(Mt,o):(Mt-_)/D;T[st]=Math.max(0,Math.min(255,Math.round(G*255)))}const P=[];for(let st=0;st<f;st++){T[st]>=0&&P.push(T[st]);const Mt=(g-1)*f+st;g>1&&T[Mt]>=0&&P.push(T[Mt])}for(let st=1;st<g-1;st++){const Mt=st*f,G=st*f+(f-1);T[Mt]>=0&&P.push(T[Mt]),f>1&&T[G]>=0&&P.push(T[G])}const x=tv(P),M=e[r]-l,L=e[c]-u;let R=M,U=L,W=-1,K=1/0;const j=Li*Li;for(let st=-Li;st<=Li;st++)for(let Mt=-Li;Mt<=Li;Mt++){if(Mt*Mt+st*st>j)continue;const G=M+Mt,et=L+st;if(G<0||G>=f||et<0||et>=g)continue;const at=T[et*f+G];if(at<0)continue;const jt=Math.abs(at-x),je=Mt*Mt+st*st;(jt>W||jt===W&&je<K)&&(W=jt,K=je,R=G,U=et)}if(W<0)return{viable:!1,reason:"outside-volume",range:null};if(W<CF)return{viable:!1,reason:"flat-region",range:null};const F=T[U*f+R],z=F>=x?1:-1,q=st=>z>0?st:255-st,J=[];for(let st=-1;st<=1;st++)for(let Mt=-1;Mt<=1;Mt++){const G=R+Mt,et=U+st;if(G<0||G>=f||et<0||et>=g)continue;const at=T[et*f+G];at>=0&&Math.abs(at-F)<=Math.abs(at-x)&&J.push(at)}const it=J.length?tv(J):F,tt=q(it),ot=st=>{const Mt=T[st];return Mt<0?-1:Math.max(0,tt-q(Mt))},nt=new Array(256),lt=(st,Mt)=>{let G=nt[st];G||(G=[],nt[st]=G),G.push(Mt)},rt=new Uint8Array(m),ut=U*f+R,Tt=ot(ut);if(Tt<0)return{viable:!1,reason:"flat-region",range:null};lt(Tt,ut),rt[ut]=1;const kt=[],Pt=L*f+M;let te=-1;const Ie=[[-1,0],[1,0],[0,-1],[0,1]],re=[],Zt=new Map;Ie.forEach(([st,Mt],G)=>{const et=M+st,at=L+Mt;if(et<0||et>=f||at<0||at>=g){re.push(null);return}re.push(-1),Zt.set(at*f+et,G)});let ce=0,Ut=-1,Ht=-1;t:for(let st=0;st<256;st++){const Mt=nt[st];if(Mt?.length){for(let et=0;et<Mt.length;et++){const at=Mt[et];if(rt[at]===2)continue;rt[at]=2,ce++,at===Pt&&(te=st);const jt=Zt.get(at);jt!==void 0&&(re[jt]=st);const je=at%f,dn=Math.floor(at/f);if(Ut<0&&(je===0||je===f-1||dn===0||dn===g-1)&&(Ut=st),ce>C){Ht=st;break t}const yo=[at-1,at+1,at-f,at+f],Pi=je>0,pc=je<f-1,Nd=dn>0,uo=dn<g-1,Ts=[Pi,pc,Nd,uo];for(let Qi=0;Qi<4;Qi++){if(!Ts[Qi])continue;const Ms=yo[Qi];if(rt[Ms]!==0)continue;const Ua=ot(Ms);Ua<0||(rt[Ms]=1,lt(Math.max(st,Ua),Ms))}}Mt.length=0}const G=kt.length?kt[kt.length-1].size:0;ce>G&&kt.push({level:st,size:ce})}const Jt=Ht>=0?Ht-1:255,Pe=[];{let st=-1,Mt=0,G=0;const et=(at,jt)=>{st>=0&&at>=st&&Pe.push({startLevel:st,endLevel:at,width:at-st,size:jt}),st=-1};for(let at=0;at<=Jt;at++){const jt=Mt;let je=0;G<kt.length&&kt[G].level===at&&(je=kt[G].size-Mt,Mt=kt[G].size,G++);const dn=Math.max(_F,Math.floor(jt*yF));Mt>0&&je<=dn?st<0&&(st=at):et(at-1,jt)}et(Jt,Mt)}let De=null;for(const st of Pe){const Mt=Ut>=0?Math.min(st.endLevel,Ut-1):st.endLevel;if(Mt<st.startLevel)continue;const G={...st,endLevel:Mt,width:Mt-st.startLevel};G.size<w||G.size>C||(!De||G.width>De.width)&&(De=G)}const ln=()=>({growthCurve:kt.map(st=>[st.level,st.size]),quietRuns:Pe.map(st=>[st.startLevel,st.endLevel,st.size]),seedByte:it,backgroundByte:x,polarity:z,borderTouchLevel:Ut,explosionLevel:Ht,clickJoinLevel:te,minRegionPx:w,maxRegionPx:C,pxAreaMm2:I});if(!De||De.width<Qp){const st=Pe.find(G=>G.size<w&&G.width>=Qp&&(Ut<0||G.startLevel<Ut)),Mt=De?.size??st?.size??ce;return{viable:!1,reason:st?"too-small":"unbounded",range:null,regionSizePx:Mt,regionAreaMm2:Mt*I,debug:ln()}}let Ve=De.startLevel+Math.floor(De.width/2);Ve=Math.min(Math.max(Ve,bF),De.endLevel);const Wo=i.toleranceScale&&i.toleranceScale>0?i.toleranceScale:1;Ve=Math.max(1,Math.min(255,Math.round(Ve*Wo)));const jn=De;if(te<0||te>Ve)return{viable:!1,reason:"off-target",range:null,regionSizePx:jn.size,regionAreaMm2:jn.size*I,debug:ln()};const Bo=[...e];Bo[r]=l+R,Bo[c]=u+U;const co=b[ut],yi=b[L*f+M],lo={seedByte:it,polarity:z,voiMapping:o??null,rawWindow:{min:_,span:D},seedIjk:Bo,seedScalar:Number.isFinite(co)?co:0,growthCurve:kt.map(st=>[st.level,st.size]),chosenToleranceBytes:Ve,growthEndLevel:Jt,pxAreaMm2:I},{min:xi,max:oi}=WS(lo,Ve);return{viable:!0,reason:"ok",regionSizePx:jn.size,regionAreaMm2:jn.size*I,toleranceBytes:Ve,clickNeighborJoinLevels:re,expandContext:lo,range:{min:xi,max:oi,ijkStart:Bo,diagnostics:{neighborhoodMean:Number.isFinite(co)?co:0,neighborhoodStdDev:0,clickedVoxelValue:Number.isFinite(yi)?yi:0,positiveStdDevMultiplier:Wo,neighborhoodRadius:Li,strategy:"adaptiveRegion",adaptive:{toleranceBytes:Ve,regionSizePx:jn.size,regionAreaMm2:jn.size*I,backgroundByte:x,seedByte:it,polarity:z,seedSnapped:R!==M||U!==L,windowSize:[f,g],growthCurve:kt.map(st=>[st.level,st.size]),explosionLevel:Ht,borderTouchLevel:Ut}}}}}function DF(i,t){if(!t)return[0,1];try{const n=t.getCamera(),{ijkVecSliceDir:e}=vF(i.imageData,n),o=e.map(Math.abs);let s=0;o[1]>=o[0]&&o[1]>=o[2]?s=1:o[2]>=o[0]&&o[2]>=o[1]&&(s=2);const a=[0,1,2].filter(r=>r!==s);return[a[0],a[1]]}catch{return[0,1]}}function ev(i,t,n){const{dimensions:e,imageData:o,spacing:s}=i,a=i.voxelManager,[r,c]=e,l=r*c,d=gF(o,t).map(Math.round),u=n?.voiMapping??(n?.viewport&&n?.referencedVolumeId?Rd(n.viewport,n.referencedVolumeId):null),h=n?.positiveStdDevMultiplier?n.positiveStdDevMultiplier/gc:1,f=DF(i,n?.viewport),g=[s?.[f[0]]??1,s?.[f[1]]??1],m=PF({dimensions:e,getScalar:(p,v,I)=>Number(a.getAtIndex(I*l+v*r+p)),ijkClick:d,inPlaneAxes:f,inPlaneSpacing:g,voiMapping:u,toleranceScale:h});return IF.debug("adaptiveRegion probe",{ijkClick:d,viable:m.viable,reason:m.reason,regionSizePx:m.regionSizePx,regionAreaMm2:m.regionAreaMm2,toleranceBytes:m.toleranceBytes,band:m.range?{min:m.range.min,max:m.range.max}:null}),m}const nv=`url("data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20width='24'%20height='24'%3E%3Ccircle%20cx='12'%20cy='12'%20r='9'%20fill='none'%20stroke='%2300dc82'%20stroke-width='2'/%3E%3Cpath%20d='M12%208v8M8%2012h8'%20stroke='%2300dc82'%20stroke-width='2'%20stroke-linecap='round'/%3E%3C/svg%3E") 12 12, copy`,ov=`url("data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20width='24'%20height='24'%3E%3Ccircle%20cx='12'%20cy='12'%20r='9'%20fill='none'%20stroke='%23ff5a5a'%20stroke-width='2'/%3E%3Cpath%20d='M5.7%205.7L18.3%2018.3'%20stroke='%23ff5a5a'%20stroke-width='2'%20stroke-linecap='round'/%3E%3C/svg%3E") 12 12, not-allowed`,iv=`url("data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20width='24'%20height='24'%3E%3Ccircle%20cx='12'%20cy='12'%20r='9'%20fill='none'%20stroke='%23a0a6ad'%20stroke-width='2'%20stroke-dasharray='4%203'/%3E%3C/svg%3E") 12 12, progress`,{growCutLog:Sn}=Ah,TF=100,MF=6,AF=1500,LF=1.15,OF=.85,RF=.08,NF=2e3,kF=2e6,sv="The region here does not form a self-contained, lesion-like shape; nothing was segmented.",UF=1e4,av=2,Vc=2500,rv=8;class mg extends Si{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{maxDeltaK:25,maxDeltaIJ:512,actions:{cancelInProgress:{method:"cancelInProgress",bindings:[{key:"Escape"}]}}}}){super(t,n),this.segmentationInProgress=!1,this.hoverThrottleTimer=null,this.pendingHoverEvent=null,this.lastHoverElement=null,this.lastProbe=null,this.lastClick=null,this.clickAbortController=null,this.dryRunToken=null,this.confirmedRegion=null,this.rejectedRegions=[],this.preTouchStartCallback=async e=>this.mode!==se.Active||this.segmentationInProgress?!1:(await this.runHoverProbe(e),this.lastProbe&&!this.lastProbe.ok?(Sn.info("tap ignored: probe reported no proper region",{canvasPoint:this.lastProbe.canvas}),this.notifySegmentationError("No meaningful region at the tapped location; nothing was segmented."),!0):this.preMouseDownCallback(e))}notifySegmentationError(t){const n=new CustomEvent(yt.ERROR_EVENT,{detail:{type:"Segmentation",message:t},cancelable:!0});Z.dispatchEvent(n)}cancelInProgress(){return this.cancelActiveOperation()}cancelActiveOperation(){return!this.clickAbortController||this.clickAbortController.signal.aborted?!1:(this.clickAbortController.abort(),!0)}clearHoverState(){this.hoverThrottleTimer!==null&&(window.clearTimeout(this.hoverThrottleTimer),this.hoverThrottleTimer=null),this.pendingHoverEvent=null,this.lastProbe=null,this.confirmedRegion=null,this.rejectedRegions=[],this.dryRunToken&&(this.dryRunToken.cancelled=!0,this.dryRunToken=null),this.lastHoverElement&&(this.lastHoverElement.style.cursor="",this.lastHoverElement=null)}pointerOnConfirmedRegion(t,n,e){const o=this.confirmedRegion;if(!o||o.viewportId!==n.id||Date.now()>o.expiresAt)return!1;const s=wn(t.imageData,e).map(Math.round);for(let l=0;l<3;l++)if(s[l]<o.bbox.min[l]||s[l]>o.bbox.max[l])return!1;const[a,r]=t.dimensions,c=Number(t.voxelManager.getAtIndex(s[2]*a*r+s[1]*a+s[0]));return!Number.isFinite(c)||c<o.bandMin||c>o.bandMax?!1:(o.expiresAt=Date.now()+Vc,!0)}static bandsAreSimilar(t,n,e,o){const s=(a,r)=>{if(!Number.isFinite(a)||!Number.isFinite(r))return a===r;const c=Math.max(Math.abs(a),Math.abs(r),1e-6);return Math.abs(a-r)<=.25*c};return s(t,e)&&s(n,o)}matchesRejectedRegion(t,n){const e=Date.now();this.rejectedRegions=this.rejectedRegions.filter(a=>a.expiresAt>e);const o=n.ijkStart,s=this.rejectedRegions.find(a=>{if(a.viewportId!==t)return!1;for(let r=0;r<3;r++)if(o[r]<a.bbox.min[r]||o[r]>a.bbox.max[r])return!1;return mg.bandsAreSimilar(n.min,n.max,a.bandMin,a.bandMax)});return s?(s.expiresAt=e+Vc,!0):!1}rememberRejectedRegion(t,n,e,o){n&&(this.rejectedRegions.push({viewportId:t,bbox:{min:[...n.min],max:[...n.max]},bandMin:e,bandMax:o,expiresAt:Date.now()+Vc}),this.rejectedRegions.length>rv&&this.rejectedRegions.splice(0,this.rejectedRegions.length-rv))}safeSpacing(t){const n=t.spacing??[1,1,1];return[0,1,2].map(e=>Number.isFinite(n[e])&&n[e]>0?n[e]:1)}computeVoxelBudget(t){const[n,e,o]=this.safeSpacing(t);return Math.max(1e3,Math.ceil(kF/(n*e*o)))}makeRegionShapeGate(t){const n=this.safeSpacing(t),e=n[0]*n[1]*n[2],o=this.configuration.maxDeltaK;return({voxelCount:s,bbox:a})=>{if(typeof o=="number"&&o>=0&&a.max[2]-a.min[2]+1>=2*o+1)return!1;const r=s*e;if(r<NF)return!0;let c=1;for(let l=0;l<3;l++)c*=(a.max[l]-a.min[l]+1)*n[l];return r/c>=RF}}onSetToolPassive(){this.clearHoverState()}onSetToolDisabled(){this.clearHoverState()}buildProbeOptions(t,n,e){return{viewport:t,element:n,referencedVolumeId:e,voiMapping:Rd(t,e)??void 0}}mouseMoveCallback(t){if(this.mode!==se.Active)return;const{element:n}=t.detail;if(this.lastHoverElement=n,this.segmentationInProgress){n.style.cursor="wait";return}this.queueHoverProbe(t)}queueHoverProbe(t){this.pendingHoverEvent=t,this.hoverThrottleTimer===null&&this.flushHoverProbe()}flushHoverProbe(){const t=this.pendingHoverEvent;this.pendingHoverEvent=null,t&&(this.runHoverProbe(t),this.hoverThrottleTimer=window.setTimeout(()=>{this.hoverThrottleTimer=null,this.pendingHoverEvent&&this.flushHoverProbe()},TF))}getViewportSliceIndex(t){const n=t.getSliceIndex;if(typeof n!="function")return null;try{const e=n.call(t);return Number.isFinite(e)?e:null}catch{return null}}async runHoverProbe(t){if(this.mode!==se.Active||this.segmentationInProgress)return;const{element:n,currentPoints:e}=t.detail,s=N(n)?.viewport;if(!s)return;this.dryRunToken&&(this.dryRunToken.cancelled=!0,this.dryRunToken=null);let a="unknown",r=null;try{if(ni(s.id)){const l=await this.getLabelmapSegmentationData(s);if(l){const{referencedVolumeId:d}=l;if(!this._isOrthogonalView(s,d))a="blocked";else{const u=Q.getVolume(d);if(u)if(this.pointerOnConfirmedRegion(u,s,e.world))a="plus";else{const h=this.buildProbeOptions(s,n,d),f=ev(u,e.world,h);!f.viable||!f.range||this.matchesRejectedRegion(s.id,f.range)?a="blocked":this.neighborsAgree(f)?(a="pending",r={refVolume:u,range:f.range}):a="blocked"}}}}}catch(l){Sn.debug("hover probe: could not evaluate",{message:l instanceof Error?l.message:String(l)}),a="unknown"}const c=a==="unknown"?null:{viewportId:s.id,canvas:[...e.canvas],sliceIndex:this.getViewportSliceIndex(s),ok:a!=="blocked",at:Date.now()};if(this.lastProbe=c,n.style.cursor=a==="plus"?nv:a==="blocked"?ov:iv,a==="pending"&&r&&c){const l={cancelled:!1};this.dryRunToken=l,this.runConfinementDryRun(r.refVolume,r.range,l,c,n)}}neighborsAgree(t){const n=t.clickNeighborJoinLevels,e=t.toleranceBytes;if(!n||typeof e!="number")return!0;let o=0,s=0;for(const a of n)a!==null&&(s++,a>=0&&a<=e&&o++);return s<av?o===s:o>=av}async runConfinementDryRun(t,n,e,o,s){const{dimensions:a}=t,[r,c,l]=a,d=r*c,u=t.voxelManager,{min:h,max:f}=n,g=this.makeRegionShapeGate(t);try{const{truncated:m,voxelCount:p,bbox:v}=await US((w,C,S)=>Number(u.getAtIndex(S*d+C*r+w)),[...n.ijkStart],{width:r,height:c,depth:l,equals:w=>typeof w=="number"&&Number.isFinite(w)&&w>=h&&w<=f,yieldEvery:UF,maxDeltaK:this.configuration.maxDeltaK,maxDeltaIJ:this.configuration.maxDeltaIJ,isCancelled:()=>e.cancelled,maxVoxels:this.computeVoxelBudget(t),shouldContinue:g});if(e.cancelled)return;!m&&v&&g({voxelCount:p,bbox:v})?(this.confirmedRegion={viewportId:o.viewportId,bbox:v,bandMin:h,bandMax:f,expiresAt:Date.now()+Vc},this.lastProbe===o&&(o.ok=!0,s.style.cursor=nv)):(this.rememberRejectedRegion(o.viewportId,v,h,f),this.lastProbe===o&&(o.ok=!1,s.style.cursor=ov))}catch(m){Sn.debug("hover dry-run: could not evaluate",{message:m instanceof Error?m.message:String(m)})}finally{this.dryRunToken===e&&(this.dryRunToken=null)}}probeAppliesToClick(t,n){const e=this.lastProbe;if(!e||e.viewportId!==t.id||Date.now()-e.at>AF||e.sliceIndex!==this.getViewportSliceIndex(t))return!1;const o=n[0]-e.canvas[0],s=n[1]-e.canvas[1];return Math.sqrt(o*o+s*s)<=MF}async preMouseDownCallback(t){if(this.segmentationInProgress)return!1;const{currentPoints:n,element:e}=t.detail,{world:o,canvas:s}=n,a=e?N(e):void 0;if(a?.viewport&&this.probeAppliesToClick(a.viewport,s)&&this.lastProbe?.ok===!1)return Sn.info("click ignored: hover probe reported no proper region",{canvasPoint:s}),!1;let r=!1;try{r=await super.preMouseDownCallback(t)}catch(l){const d=l instanceof Error?l.message:"Click segmentation failed.";return Sn.info("ClickSegment: click setup rejected",{message:d}),this.notifySegmentationError(d),!1}if(!r||!this.growCutData)return!1;const c=this.growCutData;return this.growCutData=null,this.runClick(c,o,e).catch(l=>{const d=l instanceof Error?l.message:"Click segmentation failed.";this.notifySegmentationError(d),Sn.error("ClickSegment: segmentation failed",{message:d})}),!0}async runClick(t,n,e){const{segmentation:o,viewportId:s,renderingEngineId:a}=t,{referencedVolumeId:r,labelmapVolumeId:c,segmentIndex:l}=o,u=Ne(a)?.getViewport(s);if(!u)throw new Error("ClickSegment: viewport not found for click.");const h=Q.getVolume(r),f=Q.getVolume(c);if(!h||!f)throw new Error("ClickSegment: referenced or labelmap volume not in cache.");const g=ev(h,n,this.buildProbeOptions(u,u.element,r));if(!g.viable||!g.range||!g.expandContext){Sn.info("ClickSegment: click found no meaningful region",{reason:g.reason,regionAreaMm2:g.regionAreaMm2}),this.notifySegmentationError("No meaningful region at the clicked location. Move the pointer until the plus cursor appears.");return}Sn.info("ClickSegment: click",{worldPoint:n,toleranceBytes:g.toleranceBytes,regionAreaMm2:g.regionAreaMm2,band:{min:g.range.min,max:g.range.max}});const m=this.beginLabelmapMemo(o,f);let p;try{p=await this.fillWithRange(g.range,{segmentation:o,viewportId:s,renderingEngineId:a},u,f,e,m)}finally{this.doneEditMemo()}this.lastClick={expandContext:g.expandContext,toleranceBytes:g.expandContext.chosenToleranceBytes,worldPoint:[...n],filledPoints:p,segmentation:o,viewportId:s,renderingEngineId:a},Sn.info("ClickSegment: click complete",{filledVoxels:p.length,segmentIndex:l})}async fillWithRange(t,n,e,o,s,a){const{segmentation:r}=n,{referencedVolumeId:c,segmentIndex:l,segmentationId:d}=r;this.segmentationInProgress=!0,s&&(s.style.cursor="wait");const u=new AbortController;this.clickAbortController=u;let h=[],f=!1;try{const g=Q.getVolume(c);if(!g)throw new Error("ClickSegment: referenced volume is no longer cached; cannot fill.");if(!await fF({referencedVolumeId:c,worldPosition:this.indexToWorld(g,t.ijkStart),viewport:e,labelmapVolume:o,options:{segmentIndex:l,getIntensityRange:()=>t,element:e.element,applyExternalIslandRemoval:!0,applyInternalIslandRemoval:!0,maxDeltaK:this.configuration.maxDeltaK,maxDeltaIJ:this.configuration.maxDeltaIJ,isCancelled:()=>u.signal.aborted,maxVoxels:this.computeVoxelBudget(g),shouldContinueRegion:this.makeRegionShapeGate(g),historyVoxelManager:a?.voxelManager,onRejected:({voxelCount:p,bbox:v})=>{f=!0,Sn.info("ClickSegment: fill rejected by shape gate",{voxelCount:p,bbox:v})},onCommitted:p=>{h=p}}}))throw u.signal.aborted?new Error("ClickSegment: fill cancelled."):new Error(f?sv:"ClickSegment: fill produced no result (band rejected).");return He(d),h}finally{this.clickAbortController===u&&(this.clickAbortController=null),this.segmentationInProgress=!1,s&&(s.style.cursor=iv)}}indexToWorld(t,n){return Yc(t.imageData,n)}beginLabelmapMemo(t,n){const e=Ar(t.segmentationId,n.voxelManager);return this.memo=e,e}curveSizeAt(t,n){let e=0;for(const[o,s]of t.growthCurve){if(o>n)break;e=s}return e}pickNextTolerance(t){const n=this.lastClick;if(!n)return null;const{expandContext:e,toleranceBytes:o}=n,s=this.curveSizeAt(e,o);if(t>0){for(const[a,r]of e.growthCurve)if(!(a<=o)&&r>=Math.max(s+1,s*LF))return a;return null}for(let a=e.growthCurve.length-1;a>=0;a--){const[r,c]=e.growthCurve[a];if(!(r>=o)&&c<=Math.min(s-1,s*OF))return r}return null}expand(){this.stepTolerance(1)}shrink(){this.stepTolerance(-1)}refresh(){const t=this.lastClick;!t||this.segmentationInProgress||this.refillAtTolerance(t.toleranceBytes).catch(n=>{Sn.error("ClickSegment: refresh failed",{message:n instanceof Error?n.message:String(n)})})}stepTolerance(t){if(this.segmentationInProgress)return;const n=this.lastClick;if(!n){Sn.info("ClickSegment: no click to expand/shrink yet");return}const e=this.pickNextTolerance(t);if(e===null){Sn.info("ClickSegment: no further step available",{direction:t>0?"expand":"shrink",toleranceBytes:n.toleranceBytes});return}Sn.info("ClickSegment: stepping tolerance",{direction:t>0?"expand":"shrink",fromToleranceBytes:n.toleranceBytes,toToleranceBytes:e,predictedRegionPx:this.curveSizeAt(n.expandContext,e)});const o=n.toleranceBytes;this.refillAtTolerance(e).catch(s=>{const a=s instanceof Error?s.message:String(s);if(a===sv&&t>0){Sn.info("ClickSegment: expand blocked by the lesion shape gate; previous result kept",{previousTolerance:o}),this.notifySegmentationError("Expanding further would leak beyond a lesion-like shape; kept the previous result.");return}Sn.error("ClickSegment: expand/shrink failed",{message:a})})}async refillAtTolerance(t){const n=this.lastClick;if(!n)return;const{segmentation:e,viewportId:o,renderingEngineId:s}=n,a=Q.getVolume(e.labelmapVolumeId),c=Ne(s)?.getViewport(o);if(!a||!c){Sn.warn("ClickSegment: labelmap or viewport gone; cannot expand/shrink");return}const l=this.beginLabelmapMemo(e,a);try{const{voxelManager:d}=a,u=l.voxelManager,[h,f]=a.dimensions,g=h*f,{segmentIndex:m}=e,p=[];for(const[I,w,C]of n.filledPoints){const S=C*g+w*h+I;d.getAtIndex(S)===m&&(u.setAtIndex(S,0),p.push(S))}const v=xF(n.expandContext,t);try{const I=await this.fillWithRange(v,{segmentation:e,viewportId:o,renderingEngineId:s},c,a,this.lastHoverElement??void 0,l);n.toleranceBytes=t,n.filledPoints=I,Sn.info("ClickSegment: refill complete",{toleranceBytes:t,filledVoxels:I.length})}catch(I){for(const w of p)u.setAtIndex(w,m);throw He(e.segmentationId),I}}finally{this.doneEditMemo()}}}mg.toolName="ClickSegment";const VF=[-1/0,-995],FF=[0,1900],GF=[1e3,1900],{transformWorldToIndex:Fc,transformIndexToWorld:Du}=oe;class HF extends Si{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{isPartialVolume:!0,positivePixelRange:FF,negativePixelRange:VF,islandRemoval:{enabled:!0,islandPixelRange:GF}}}){super(t,n),this._dragCallback=e=>{const o=e.detail,{element:s,currentPoints:a}=o,{world:r}=a,c=N(s),{viewport:l}=c,d=this._getHorizontalLineWorldPoints(c,r);this.growCutData.horizontalLines[1]=d,V([l.id])},this._endCallback=async e=>{const o=e.detail,{element:s}=o,a=N(s),{viewport:r}=a;this._deactivateDraw(s),await this.runGrowCut(),this.growCutData=null,Ft(s),V([r.id])},this._deactivateDraw=e=>{e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.TOUCH_END,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback)}}async preMouseDownCallback(t){const n=t.detail,{element:e,currentPoints:o}=n,{world:s}=o,a=N(e),{viewport:r,renderingEngine:c}=a,l=this._getHorizontalLineWorldPoints(a,s);return await super.preMouseDownCallback(t),this.growCutData.horizontalLines=[l,l],this._activateDraw(e),wt(e),V([r.id]),!0}renderAnnotation(t,n){if(!this.growCutData)return;const{segmentation:e,horizontalLines:o}=this.growCutData;if(o.length!==2)return;const{viewport:s}=t,{segmentationId:a,segmentIndex:r}=e,[c,l]=o,[d,u]=c,[h,f]=l,g=[d,u,f,h].map(b=>s.worldToCanvas(b)),m="growCutRect",p="0",{color:v,fillColor:I,lineWidth:w,fillOpacity:C,lineDash:S}=this.getSegmentStyle({segmentationId:a,segmentIndex:r,viewportId:s.id});Eo(n,m,p,g,{color:v,fillColor:I,fillOpacity:C,lineWidth:w,lineDash:S,closePath:!0})}async getGrowCutLabelmap(t){const{segmentation:{segmentIndex:n,referencedVolumeId:e},renderingEngineId:o,viewportId:s,horizontalLines:a}=t,c=Ne(o).getViewport(s),[l,d]=a,u=[l[0],l[1],d[1],d[0]],h=Q.getVolume(e),{topLeft:f,bottomRight:g}=this._getWorldBoundingBoxFromProjectedSquare(c,u),m=Fc(h.imageData,f),p=Fc(h.imageData,g),v={boundingBox:{ijkTopLeft:m,ijkBottomRight:p}},I=this.configuration,w={positiveSeedValue:n,negativeSeedValue:255,negativePixelRange:I.negativePixelRange,positivePixelRange:I.positivePixelRange};return RE(e,v,w)}getRemoveIslandData(){const{segmentation:{segmentIndex:t,referencedVolumeId:n,labelmapVolumeId:e}}=this.growCutData,o=Q.getVolume(n),s=Q.getVolume(e),a=o.voxelManager.getCompleteScalarDataArray(),r=s.voxelManager.getCompleteScalarDataArray(),{islandPixelRange:c}=this.configuration.islandRemoval,l=[];for(let d=0,u=r.length;d<u;d++){if(r[d]!==t)continue;const h=a[d];h>=c[0]&&h<=c[1]&&l.push(d)}return{islandPointIndexes:l}}_activateDraw(t){t.addEventListener(E.MOUSE_UP,this._endCallback),t.addEventListener(E.MOUSE_DRAG,this._dragCallback),t.addEventListener(E.MOUSE_CLICK,this._endCallback),t.addEventListener(E.TOUCH_END,this._endCallback),t.addEventListener(E.TOUCH_DRAG,this._dragCallback),t.addEventListener(E.TOUCH_TAP,this._endCallback)}_projectWorldPointAcrossSlices(t,n,e){const o=this._getViewportVolume(t),{dimensions:s}=o,a=Fc(o.imageData,n),r=e.findIndex(d=>ve(Math.abs(d),1));if(r===-1)throw new Error("Non-orthogonal direction vector");const c=[...a],l=[...a];return c[r]=0,l[r]=s[r]-1,[c,l]}_getCuboidIJKEdgePointsFromProjectedWorldPoint(t,n){const{viewPlaneNormal:e}=ht(t);return this._projectWorldPointAcrossSlices(t,n,e)}_getWorldCuboidCornerPoints(t,n){const e=[],o=this._getViewportVolume(t);return n.forEach(s=>{const r=this._getCuboidIJKEdgePointsFromProjectedWorldPoint(t,s).map(c=>Du(o.imageData,c));e.push(...r)}),e}_getWorldBoundingBoxFromProjectedSquare(t,n){const e=this._getWorldCuboidCornerPoints(t,n),o=[...e[0]],s=[...e[0]];return e.forEach(a=>{wb(o,o,a),Eb(s,s,a)}),{topLeft:o,bottomRight:s}}_getViewportVolume(t){if(!(t instanceof pn))throw new Error("Viewport is not a BaseVolumeViewport");const n=t.getAllVolumeIds()[0];return Q.getVolume(n)}_getHorizontalLineIJKPoints(t,n){const{viewport:e}=t,o=this._getViewportVolume(e),{dimensions:s}=o,a=Fc(o.imageData,n),{viewUp:r,viewPlaneNormal:c}=ht(e),d=Me(B(),r,c).findIndex(f=>ve(Math.abs(f),1)),u=[...a],h=[...a];return u[d]=0,h[d]=s[d]-1,[u,h]}_getHorizontalLineWorldPoints(t,n){const{viewport:e}=t,o=this._getViewportVolume(e),[s,a]=this._getHorizontalLineIJKPoints(t,n),r=Du(o.imageData,s),c=Du(o.imageData,a);return[r,c]}}HF.toolName="WholeBodySegment";function WF(i,t,n=!0){const e=Object.assign({},t,{segmentIndex:0});jf(i,e)}function BF(i,t){WF(i,t,!0)}class zF extends $i{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{strategies:{FILL_INSIDE:jf,ERASE_INSIDE:BF},defaultStrategy:"FILL_INSIDE",activeStrategy:"FILL_INSIDE"}}){super(t,n),this.preMouseDownCallback=e=>{if(this.isDrawing===!0)return;const o=e.detail,{currentPoints:s,element:a}=o,r=s.world,c=N(a),{viewport:l}=c;this.isDrawing=!0;const d=ht(l),{viewPlaneNormal:u,viewUp:h}=d,f=ni(l.id);if(!f)throw new Error("No active segmentation detected, create one before using scissors tool");const{segmentationId:g}=f,m=xn(g),p=xs(g),v=Jo(l.id,g,m),{representationData:I}=Dt(g);I[St.Labelmap];const w={highlighted:!0,invalidated:!0,metadata:{viewPlaneNormal:[...u],viewUp:[...h],FrameOfReferenceUID:l.getFrameOfReferenceUID(),referencedImageId:"",toolName:this.getToolName(),segmentColor:v},data:{handles:{points:[[...r],[...r],[...r],[...r]],activeHandleIndex:null}}},C=ft(a,this.getToolName());if(this.editData={annotation:w,segmentIndex:m,segmentationId:g,segmentsLocked:p,segmentColor:v,viewportIdsToRender:C,handleIndex:3,movingTextBox:!1,newAnnotation:!0,hasMoved:!1,volumeId:null,referencedVolumeId:null,imageId:null},zn(l)==="volume"||l instanceof pn){const b=Kl(Dt(g),m),_=b?$n(b):void 0;if(!_)return;this.editData={...this.editData,volumeId:_.volumeId,referencedVolumeId:b?.referencedVolumeId??_.referencedVolumeId}}else{const b=Zi(l.id,g);this.editData={...this.editData,imageId:b}}return this._activateDraw(a),wt(a),e.preventDefault(),V(C),!0},this._dragCallback=e=>{const o=e.detail,{element:s}=o,{currentPointsList:a}=o;if(a?.length>1){this._cancelTouchDraw(s);return}this.isDrawing=!0;const{annotation:r,viewportIdsToRender:c,handleIndex:l}=this.editData,{data:d}=r,{currentPoints:u}=o,h=N(s),{worldToCanvas:f,canvasToWorld:g}=h.viewport,m=u.world,{points:p}=d.handles;p[l]=[...m];let v,I,w,C,S,b,_,y;switch(l){case 0:case 3:v=f(p[0]),C=f(p[3]),I=[C[0],v[1]],w=[v[0],C[1]],b=g(I),_=g(w),p[1]=b,p[2]=_;break;case 1:case 2:I=f(p[1]),w=f(p[2]),v=[w[0],I[1]],C=[I[0],w[1]],S=g(v),y=g(C),p[0]=S,p[3]=y;break}r.invalidated=!0,this.editData.hasMoved=!0,V(c)},this._endCallback=e=>{const o=e.detail,{element:s}=o,{annotation:a,newAnnotation:r,hasMoved:c}=this.editData,{data:l}=a;if(r&&!c)return;l.handles.activeHandleIndex=null,this._deactivateDraw(s),Ft(s);const d=N(s),u={...this.editData,points:l.handles.points,createMemo:this.createMemo.bind(this)};this.editData=null,this.isDrawing=!1,this.applyActiveStrategy(d,u),this.doneEditMemo()},this._activateDraw=e=>{e.addEventListener(E.MOUSE_UP,this._endCallback),e.addEventListener(E.MOUSE_DRAG,this._dragCallback),e.addEventListener(E.MOUSE_MOVE,this._dragCallback),e.addEventListener(E.MOUSE_CLICK,this._endCallback),e.addEventListener(E.TOUCH_END,this._endCallback),e.addEventListener(E.TOUCH_DRAG,this._dragCallback),e.addEventListener(E.TOUCH_TAP,this._endCallback)},this._deactivateDraw=e=>{e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragCallback),e.removeEventListener(E.MOUSE_MOVE,this._dragCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback),e.removeEventListener(E.TOUCH_END,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragCallback)},this.renderAnnotation=(e,o)=>{let s=!1;if(!this.editData)return s;const{viewport:a}=e,{annotation:r}=this.editData,c=r.metadata,l=r.annotationUID,d=r.data,{points:u}=d.handles,h=u.map(m=>a.worldToCanvas(m)),f=`rgb(${c.segmentColor.slice(0,3)})`;return a.getRenderingEngine()?(nc(o,l,"0",h[0],h[3],{color:f}),s=!0,s):(console.warn("Rendering Engine has been destroyed"),s)}}}zF.toolName="RectangleScissor";const $F=1e-4;function BS(i,t){const n=i.map(p=>t.worldToCanvas(p)),[e,o,s,a]=n,r=[(e[0]+o[0])/2,(e[1]+o[1])/2],c=ke(i[0],i[1]),l=ke(i[2],i[3]),d=_e(e,o),h=_e(s,a)/l,f=d/c,g=c/2,m=Math.abs(h-f)>$F?g*Math.min(h,f):d/2;return{center:r,radius:Math.round(m)}}class jF extends $i{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{strategies:{FILL_INSIDE:_d,ERASE_INSIDE:CE},defaultStrategy:"FILL_INSIDE",activeStrategy:"FILL_INSIDE"}}){super(t,n),this.preMouseDownCallback=e=>{if(this.isDrawing===!0)return;const o=e.detail,{currentPoints:s,element:a}=o,r=s.world,c=s.canvas,l=N(a),{viewport:d}=l;this.isDrawing=!0;const u=ht(d),{viewPlaneNormal:h,viewUp:f}=u,g=ni(d.id);if(!g)throw new Error("No active segmentation detected, create one before using scissors tool");const{segmentationId:m}=g,p=xn(m),v=xs(m),I=Jo(d.id,m,p),{representationData:w}=Dt(m);if(!w.Labelmap)throw new Error("No labelmap data found for the active segmentation, create one before using scissors tool");const S={invalidated:!0,highlighted:!0,metadata:{viewPlaneNormal:[...h],viewUp:[...f],FrameOfReferenceUID:d.getFrameOfReferenceUID(),referencedImageId:"",toolName:this.getToolName(),segmentColor:I},data:{handles:{points:[[...r],[...r],[...r],[...r]],activeHandleIndex:null},isDrawing:!0,cachedStats:{}}},b=[d.id];if(this.editData={annotation:S,centerCanvas:c,segmentIndex:p,segmentationId:m,segmentsLocked:v,segmentColor:I,viewportIdsToRender:b,handleIndex:3,movingTextBox:!1,newAnnotation:!0,hasMoved:!1,volumeId:null,referencedVolumeId:null,imageId:null},zn(d)==="volume"||d instanceof pn){const y=Kl(Dt(m),p),D=y?$n(y):void 0;if(!D)return;this.editData={...this.editData,volumeId:D.volumeId,referencedVolumeId:y?.referencedVolumeId??D.referencedVolumeId}}else{const y=Zi(d.id,m);this.editData={...this.editData,imageId:y}}return this._activateDraw(a),wt(a),e.preventDefault(),V(b),!0},this._dragCallback=e=>{const o=e.detail,{element:s}=o,{currentPointsList:a}=o;if(a?.length>1){this._cancelTouchDraw(s);return}this.isDrawing=!0;const{currentPoints:r}=o,c=r.canvas,l=N(s),{renderingEngine:d,viewport:u}=l,{canvasToWorld:h}=u,{annotation:f,viewportIdsToRender:g,centerCanvas:m}=this.editData,{data:p}=f,v=h(m),I=h(c);p.handles.points=Tl([v,I],u),f.invalidated=!0,this.editData.hasMoved=!0,V(g)},this._endCallback=e=>{const o=e.detail,{element:s}=o,{annotation:a,newAnnotation:r,hasMoved:c}=this.editData,{data:l}=a,{viewPlaneNormal:d,viewUp:u}=a.metadata;if(r&&!c)return;l.handles.activeHandleIndex=null,this._deactivateDraw(s),Ft(s);const h=N(s),f={...this.editData,points:l.handles.points,viewPlaneNormal:d,viewUp:u,createMemo:this.createMemo.bind(this)};this.editData=null,this.isDrawing=!1,this.applyActiveStrategy(h,f),this.doneEditMemo()},this._activateDraw=e=>{e.addEventListener(E.MOUSE_UP,this._endCallback),e.addEventListener(E.MOUSE_DRAG,this._dragCallback),e.addEventListener(E.MOUSE_CLICK,this._endCallback),e.addEventListener(E.MOUSE_MOVE,this._dragCallback),e.addEventListener(E.TOUCH_TAP,this._endCallback),e.addEventListener(E.TOUCH_DRAG,this._dragCallback),e.addEventListener(E.TOUCH_END,this._endCallback)},this._deactivateDraw=e=>{e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.MOUSE_MOVE,this._dragCallback),e.removeEventListener(E.TOUCH_END,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(e,o)=>{let s=!1;if(!this.editData)return s;const{viewport:a}=e,{viewportIdsToRender:r}=this.editData;if(!r.includes(a.id))return s;const{annotation:c}=this.editData,l=c.metadata,d=c.annotationUID,u=c.data,{points:h}=u.handles,{center:f,radius:g}=BS(h,a),m=`rgb(${l.segmentColor.slice(0,3)})`;return a.getRenderingEngine()?(En(o,d,"0",f,g,{color:m}),s=!0,s):(console.warn("Rendering Engine has been destroyed"),s)}}}jF.toolName="CircleScissor";class XF extends $i{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{strategies:{FILL_INSIDE:EE,ERASE_INSIDE:SE},defaultStrategy:"FILL_INSIDE",activeStrategy:"FILL_INSIDE"}}){super(t,n),this.preMouseDownCallback=e=>{if(this.isDrawing===!0)return;this.doneEditMemo();const o=e.detail,{currentPoints:s,element:a}=o,r=s.world,c=s.canvas,l=N(a),{viewport:d}=l;this.isDrawing=!0;const u=ht(d),{viewPlaneNormal:h,viewUp:f}=u;if(!h||!f)throw new Error("Unable to resolve viewport view plane for scissors tool");const g=ni(d.id);if(!g)throw new Error("No active segmentation detected, create one before using scissors tool");const{segmentationId:m}=g,p=xn(m),v=xs(m),I=Jo(d.id,m,p);this.isDrawing=!0;const w={metadata:{viewPlaneNormal:[...h],viewUp:[...f],FrameOfReferenceUID:d.getFrameOfReferenceUID(),referencedImageId:"",toolName:this.getToolName(),segmentColor:I},data:{invalidated:!0,handles:{points:[[...r],[...r],[...r],[...r]],activeHandleIndex:null},cachedStats:{},highlighted:!0}},C=[d.id];this.editData={annotation:w,centerCanvas:c,segmentIndex:p,segmentationId:m,segmentsLocked:v,segmentColor:I,toolGroupId:this.toolGroupId,viewportIdsToRender:C,handleIndex:3,movingTextBox:!1,newAnnotation:!0,hasMoved:!1,volumeId:null,referencedVolumeId:null,imageId:null};const{representationData:S}=Dt(m),b=this.getEditData({viewport:d,representationData:S,segmentsLocked:v,segmentationId:m});return this.editData={...this.editData,...b},this._activateDraw(a),wt(a),e.preventDefault(),V(C),!0},this._dragCallback=e=>{const o=e.detail,{element:s}=o,{currentPointsList:a}=o;if(a?.length>1){this._cancelTouchDraw(s);return}this.isDrawing=!0;const{currentPoints:r}=o,c=r.canvas,l=N(s),{renderingEngine:d,viewport:u}=l,{canvasToWorld:h}=u,{annotation:f,viewportIdsToRender:g,centerCanvas:m}=this.editData,{data:p}=f,v=h(m),I=h(c);p.handles.points=Tl([v,I],u),f.invalidated=!0,this.editData.hasMoved=!0,V(g)},this._endCallback=e=>{const o=e.detail,{element:s}=o,{annotation:a,newAnnotation:r,hasMoved:c,segmentIndex:l,segmentsLocked:d}=this.editData,{data:u}=a,{viewPlaneNormal:h,viewUp:f}=a.metadata;if(r&&!c)return;a.highlighted=!1,u.handles.activeHandleIndex=null,this._deactivateDraw(s),Ft(s);const g=N(s),m={...this.editData,points:u.handles.points,segmentIndex:l,segmentsLocked:d,viewPlaneNormal:h,viewUp:f,createMemo:this.createMemo.bind(this)};this.editData=null,this.isDrawing=!1,this.applyActiveStrategy(g,m),this.doneEditMemo()},this._activateDraw=e=>{e.addEventListener(E.MOUSE_UP,this._endCallback),e.addEventListener(E.MOUSE_DRAG,this._dragCallback),e.addEventListener(E.MOUSE_CLICK,this._endCallback),e.addEventListener(E.MOUSE_MOVE,this._dragCallback),e.addEventListener(E.TOUCH_END,this._endCallback),e.addEventListener(E.TOUCH_TAP,this._endCallback),e.addEventListener(E.TOUCH_DRAG,this._dragCallback)},this._deactivateDraw=e=>{e.removeEventListener(E.MOUSE_UP,this._endCallback),e.removeEventListener(E.MOUSE_DRAG,this._dragCallback),e.removeEventListener(E.MOUSE_CLICK,this._endCallback),e.removeEventListener(E.MOUSE_MOVE,this._dragCallback),e.removeEventListener(E.TOUCH_END,this._endCallback),e.removeEventListener(E.TOUCH_DRAG,this._dragCallback),e.removeEventListener(E.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(e,o)=>{let s=!1;if(!this.editData)return s;const{viewport:a}=e,{viewportIdsToRender:r}=this.editData;if(!r.includes(a.id))return s;const{annotation:c}=this.editData,l=c.metadata,d=c.annotationUID,u=c.data,{points:h}=u.handles,{center:f,radius:g}=BS(h,a),m=`rgb(${l.segmentColor.slice(0,3)})`;return a.getRenderingEngine()?(En(o,d,"0",f,g,{color:m}),s=!0,s):(console.warn("Rendering Engine has been destroyed"),s)}}}XF.toolName="SphereScissor";const{transformWorldToIndex:Tu}=oe;class qF extends ji{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"],configuration:{simplified:!0,storePointData:!1,numSlicesToPropagate:10,calculatePointsInsideVolume:!0,getTextLines:YF,statsCalculator:bo,showTextBox:!1,throttleTimeout:100}}){super(t,n),this.isHandleOutsideImage=!1,this.addNewAnnotation=e=>{const o=e.detail,{currentPoints:s,element:a}=o,r=s.world,c=N(a),{viewport:l}=c;this.isDrawing=!0;const d=l.getCamera(),{viewPlaneNormal:u,viewUp:h}=d;let f,g,m;if(l instanceof Pn)throw new Error("Stack Viewport Not implemented");{const _=this.getTargetId(l);m=Fi(_),g=Q.getVolume(m),f=qr(g,r,u)}const p=Dh(g,u),v=this._getStartCoordinate(r,p,u),I=this._getEndCoordinate(r,p,u),w=l.getFrameOfReferenceUID();let C;this.configuration.simplified?C=[[...r],[...r]]:C=[[...r],[...r],[...r],[...r],[...r]];const S={highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...u],viewUp:[...h],FrameOfReferenceUID:w,referencedImageId:f,volumeId:m,spacingInNormal:p,enabledElement:c},data:{label:"",startCoordinate:v,endCoordinate:I,handles:{textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}},points:C,activeHandleIndex:null},cachedStats:{pointsInVolume:[],projectionPoints:[],statistics:[]}}};this._computeProjectionPoints(S,g),Nt(S,a);const b=ft(a,this.getToolName());return this.editData={annotation:S,viewportIdsToRender:b,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),wt(a),e.preventDefault(),V(b),S},this._endCallback=e=>{const o=e.detail,{element:s}=o,{annotation:a,viewportIdsToRender:r,newAnnotation:c,hasMoved:l}=this.editData,{data:d}=a;if(c&&!l)return;a.highlighted=!1,d.handles.activeHandleIndex=null,this._deactivateModify(s),this._deactivateDraw(s),Ft(s);const{metadata:u}=a,{enabledElement:h}=u;this.editData=null,this.isDrawing=!1,this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&Gt(a.annotationUID);const f=this.getTargetId(h.viewport),g=Q.getVolume(f.split(/volumeId:|\?/)[1]);this._computePointsInsideVolume(a,g,f,h),V(r),c?ue(a):zt(a,s)},this.renderAnnotation=(e,o)=>{let s=!1;const{viewport:a}=e;let r=Yt(this.getToolName(),a.element);if(!r?.length)return s;r=nd(r,a.getCamera());const c={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:e.viewport.id};for(let l=0;l<r.length;l++){const d=r[l],{annotationUID:u,data:h,metadata:f}=d,{startCoordinate:g,endCoordinate:m}=h,{points:p,activeHandleIndex:v}=h.handles,{enabledElement:I}=f;c.annotationUID=u;const w=this.getStyle("lineWidth",c,d),C=this.getStyle("lineDash",c,d),S=this.getStyle("color",c,d),b=p.map(ot=>a.worldToCanvas(ot)),_=b[0],y=ga([b[0],b[1]]),{centerPointRadius:D}=this.configuration,T=rs([b[0],b[1]]),P=a.getCamera().focalPoint,x=a.getCamera().viewPlaneNormal;let M=g,L=m;Array.isArray(g)&&(M=this._getCoordinateForViewplaneNormal(M,x),h.startCoordinate=M),Array.isArray(m)&&(L=this._getCoordinateForViewplaneNormal(L,x),h.endCoordinate=L);const R=is(h.startCoordinate),U=is(h.endCoordinate),W=this._getCoordinateForViewplaneNormal(P,x),K=is(W);if(K<Math.min(R,U)||K>Math.max(R,U))continue;const j=is((h.startCoordinate+h.endCoordinate)/2);let F=!1;K===j&&(F=!0),h.handles.points[0][this._getIndexOfCoordinatesForViewplaneNormal(x)]=j;const z=I.viewport?.volumeIds.values();for(const ot of z)d.invalidated&&d.metadata.volumeId===ot&&this._throttledCalculateCachedStats(d,I);if(!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),s;let q;if(!$e(u))continue;!ze(u)&&!this.editData&&v!==null&&F&&(this.configuration.simplified?q=[b[v]]:q=b),q&&xe(o,u,"0",q,{color:S});let J=w,it=C;F?(J=w,it=[]):it=[5,5];const tt="0";if(En(o,u,tt,_,y,{color:S,lineDash:it,lineWidth:J}),D>0&&y>3*D&&En(o,u,`${tt}-center`,_,D,{color:S,lineDash:C,lineWidth:w}),s=!0,this.configuration.showTextBox){const ot=this.configuration.getTextLines(h,{metadata:f});if(!ot||ot.length===0)continue;const nt=[b[0],b[1]];if(!this.renderLinkedTextBoxAnnotation({enabledElement:e,svgDrawingHelper:o,annotation:d,styleSpecifier:c,textLines:ot,canvasCoordinates:nt,placementPoints:T}))continue}}return s},this.configuration.calculatePointsInsideVolume?this._throttledCalculateCachedStats=Un(this._calculateCachedStatsTool,this.configuration.throttleTimeout,{trailing:!0}):this._throttledCalculateCachedStats=Yr(this._calculateCachedStatsTool,this.configuration.throttleTimeout)}_computeProjectionPoints(t,n){const{data:e,metadata:o}=t,{viewPlaneNormal:s,spacingInNormal:a}=o,{startCoordinate:r,endCoordinate:c}=e,{points:l}=e.handles,d=this._getIndexOfCoordinatesForViewplaneNormal(s),u=ho(l[0]);u[d]=r;const h=ho(l[0]);h[d]=c;const f=B();Oe(f,h,u);const g=mn(f);if(g===0){const v=l.map(I=>{const w=ho(I);return w[d]=r,Array.from(w)});e.cachedStats.projectionPoints=[v];return}Wt(f,f);const m=Re(l);m[0][d]=r,m[1][d]=r;const p=[];for(let v=0;v<=g+1e-6;v+=a)p.push(m.map(I=>{const w=B();return ee(w,I,f,v),Array.from(w)}));e.cachedStats.projectionPoints=p}_computePointsInsideVolume(t,n,e,o){const{data:s,metadata:a}=t,{viewPlaneNormal:r,viewUp:c}=a,{viewport:l}=o,d=s.cachedStats.projectionPoints,u=[[]],h=this.getTargetImageData(e),f=s.handles.points.map(T=>l.worldToCanvas(T)),g=rs([f[0],f[1]])[0],m=rs([f[0],f[1]])[1],p=l.canvasToWorld(g),v=l.canvasToWorld(m),{worldWidth:I,worldHeight:w}=ec(r,c,p,v),C=ao(h,s.handles.points),S=Kh(h),b=Math.abs(Math.PI*(I/C.scale/2)*(w/S/C.scale/2)),_={isPreScaled:Ki(l,e),isSuvScaled:this.isSuvScaled(l,e,t.metadata.referencedImageId)},y=bi(a.Modality,t.metadata.referencedImageId,_);for(let T=0;T<d.length;T++){if(!n)continue;const P=d[T][0],x=d[T].map(ot=>l.worldToCanvas(ot)),[M,L]=rs([x[0],x[1]]),R=l.canvasToWorld(M),U=l.canvasToWorld(L),W=R,K=U,{dimensions:j,imageData:F,voxelManager:z}=n,q=Tu(F,W),J=Tu(F,P),it=this._getIndexOfCoordinatesForViewplaneNormal(r);q[0]=Math.floor(q[0]),q[1]=Math.floor(q[1]),q[2]=Math.floor(q[2]),q[it]=J[it];const tt=Tu(F,K);if(tt[0]=Math.floor(tt[0]),tt[1]=Math.floor(tt[1]),tt[2]=Math.floor(tt[2]),tt[it]=J[it],ji.isInsideVolume(j,[q,tt])){const ot=Math.min(q[0],tt[0]),nt=Math.max(q[0],tt[0]),lt=Math.min(q[1],tt[1]),rt=Math.max(q[1],tt[1]),ut=Math.min(q[2],tt[2]),Tt=Math.max(q[2],tt[2]),kt=[[ot,nt],[lt,rt],[ut,Tt]],te={center:P,xRadius:Math.abs(R[0]-U[0])/2,yRadius:Math.abs(R[1]-U[1])/2,zRadius:Math.abs(R[2]-U[2])/2},Ie=z.forEach(this.configuration.statsCalculator.statsCallback,{isInObject:re=>Jl(te,re),boundsIJK:kt,imageData:F,returnPoints:this.configuration.storePointData});u.push(Ie)}}const D=this.configuration.statsCalculator.getStatistics();s.cachedStats.pointsInVolume=u,s.cachedStats.statistics={Modality:a.Modality,area:b,mean:D.mean?.value,stdDev:D.stdDev?.value,max:D.max?.value,statsArray:D.array,areaUnit:C.areaUnit,modalityUnit:y}}_calculateCachedStatsTool(t,n){const e=t.data,{viewport:o}=n,{cachedStats:s}=e,a=this.getTargetId(o),r=Q.getVolume(a.split(/volumeId:|\?/)[1]);return this._computeProjectionPoints(t,r),this._computePointsInsideVolume(t,r,a,n),t.invalidated=!1,zt(t,o.element),s}_getStartCoordinate(t,n,e){const o=this.configuration.numSlicesToPropagate,s=Math.round(o/2),a=B();return ee(a,t,e,s*-n),this._getCoordinateForViewplaneNormal(a,e)}_getEndCoordinate(t,n,e){const o=this.configuration.numSlicesToPropagate,s=o-Math.round(o/2),a=B();return ee(a,t,e,s*n),this._getCoordinateForViewplaneNormal(a,e)}_getIndexOfCoordinatesForViewplaneNormal(t){const n=[Math.abs(t[0]),Math.abs(t[1]),Math.abs(t[2])];return n.indexOf(Math.max(...n))}_getCoordinateForViewplaneNormal(t,n){const e=this._getIndexOfCoordinatesForViewplaneNormal(n);return t[e]}}function YF(i,t={}){const n=i.cachedStats.statistics,{area:e,mean:o,max:s,stdDev:a,areaUnit:r,modalityUnit:c}=n;if(o===void 0)return;const l=[];return l.push(`Area: ${de(e)} ${r}`),l.push(`Mean: ${de(o)} ${c}`),l.push(`Max: ${de(s)} ${c}`),l.push(`Std Dev: ${de(a)} ${c}`),l}qF.toolName="CircleROIStartEndThreshold";const{transformWorldToIndex:cv,isEqual:Mu}=oe;class KF extends Ee{constructor(t={},n={supportedInteractionTypes:["Mouse","Touch"]}){super(t,n),this.preMouseDownCallback=e=>{const o=e.detail,{currentPoints:s,element:a}=o,r=s.world,c=N(a),{viewport:l}=c,d=l.getCamera(),{viewPlaneNormal:u}=d,h=ni(l.id);if(!h)throw new Error("No active segmentation detected, create one before using scissors tool");const{segmentationId:f}=h,g=xn(f),m=xs(f),{representationData:p}=Dt(f);let v,I,w,C;if(this.doneEditMemo(),zn(l)==="volume"||l instanceof pn){const U=Kl(Dt(f),g),W=U?$n(U):void 0;if(!W)return;({dimensions:v,direction:I}=W),C=W.voxelManager,w=cv(W.imageData,r)}else{const U=Zi(l.id,f);if(!U)throw new Error("No active segmentation imageId detected, create one before using scissors tool");const{imageData:W}=l.getImageData();v=W.getDimensions(),I=W.getDirection(),C=Q.getImage(U).voxelManager,w=cv(W,r)}const b=this.getFixedDimension(u,I);if(b===void 0){console.warn("Oblique paint fill not yet supported");return}const{floodFillGetter:_,getLabelValue:y,getScalarDataPositionFromPlane:D,inPlaneSeedPoint:T,fixedDimensionValue:P}=this.generateHelpers(C,v,w,b);if(w[0]<0||w[0]>=v[0]||w[1]<0||w[1]>=v[1]||w[2]<0||w[2]>=v[2])return;const x=y(w[0],w[1],w[2]);if(m.includes(x))return;const M=$f(_,T),{flooded:L}=M;L.forEach(U=>{const W=D(U[0],U[1]);C.setAtIndex(W,g)});const R=this.getFramesModified(b,P,M);return He(f,R),!0},this.getFramesModified=(e,o,s)=>{const{flooded:a}=s;if(e===2)return[o];let r=1/0,c=-1/0;for(let d=0;d<a.length;d++){const u=a[d][1];u<r&&(r=u),u>c&&(c=u)}const l=[];for(let d=r;d<=c;d++)l.push(d);return l},this.generateHelpers=(e,o,s,a=2)=>{let r,c;switch(a){case 0:r=s[0],c=[s[1],s[2]];break;case 1:r=s[1],c=[s[0],s[2]];break;case 2:r=s[2],c=[s[0],s[1]];break;default:throw new Error(`Invalid fixedDimension: ${a}`)}const l=(f,g,m)=>e.toIndex([f,g,m]),d=(f,g,m)=>e.getAtIJK(f,g,m),u=this.generateFloodFillGetter(o,a,r,d);return{getScalarDataPositionFromPlane:this.generateGetScalarDataPositionFromPlane(l,a,r),getLabelValue:d,floodFillGetter:u,inPlaneSeedPoint:c,fixedDimensionValue:r}},this.generateFloodFillGetter=(e,o,s,a)=>{let r;switch(o){case 0:r=(c,l)=>{if(!(c>=e[1]||c<0||l>=e[2]||l<0))return a(s,c,l)};break;case 1:r=(c,l)=>{if(!(c>=e[0]||c<0||l>=e[2]||l<0))return a(c,s,l)};break;case 2:r=(c,l)=>{if(!(c>=e[0]||c<0||l>=e[1]||l<0))return a(c,l,s)};break;default:throw new Error(`Invalid fixedDimension: ${o}`)}return r},this.generateGetScalarDataPositionFromPlane=(e,o,s)=>{let a;switch(o){case 0:a=(r,c)=>e(s,r,c);break;case 1:a=(r,c)=>e(r,s,c);break;case 2:a=(r,c)=>e(r,c,s);break;default:throw new Error(`Invalid fixedDimension: ${o}`)}return a}}getFixedDimension(t,n){const e=n.slice(0,3),o=n.slice(3,6),s=n.slice(6,9),a=[Math.abs(t[0]),Math.abs(t[1]),Math.abs(t[2])],r=[Math.abs(e[0]),Math.abs(e[1]),Math.abs(e[2])];if(Mu(a,r))return 0;const c=[Math.abs(o[0]),Math.abs(o[1]),Math.abs(o[2])];if(Mu(a,c))return 1;const l=[Math.abs(s[0]),Math.abs(s[1]),Math.abs(s[2])];if(Mu(a,l))return 2}}KF.toolName="PaintFill";var ZF={TOP_LEFT:"TOP_LEFT",TOP_RIGHT:"TOP_RIGHT",BOTTOM_LEFT:"BOTTOM_LEFT",BOTTOM_RIGHT:"BOTTOM_RIGHT"},pg={Corners:ZF},{vtkErrorMacro:Au}=Lt,{Corners:Gc}=pg;function JF(i,t){t.classHierarchy.push("vtkOrientationMarkerWidget");const n={...i},e=[],o=xv.newInstance(),s=new ResizeObserver(h=>{i.updateViewport()});let a=null,r=null,c=null,l=null,d=null;function u(){t._interactor.isAnimating()||i.updateMarkerOrientation()}t._onParentRendererChanged=()=>i.updateViewport(),i.computeViewport=()=>{const h=t.parentRenderer||t._interactor.getCurrentRenderer(),[f,g,m,p]=h.getViewport(),v=t._interactor.getView(),I=v.getSize(),[w,C]=v.getViewportSize(h),S=Math.min(w,C);let b=t.viewportSize*S;b=Math.max(Math.min(t.minPixelSize,S),Math.min(t.maxPixelSize,b));const _=b/I[0],y=b/I[1];switch(t.viewportCorner){case Gc.TOP_LEFT:return[f,p-y,f+_,p];case Gc.TOP_RIGHT:return[m-_,p-y,m,p];case Gc.BOTTOM_LEFT:return[f,g,f+_,g+y];case Gc.BOTTOM_RIGHT:return[m-_,g,m,g+y];default:return Au("Invalid widget corner"),null}},i.updateViewport=()=>{t.enabled&&(o.setViewport(...i.computeViewport()),t._interactor.render())},i.updateMarkerOrientation=()=>{const h=(t.parentRenderer||t._interactor.getCurrentRenderer()).getActiveCamera();if(!h)return;const f=h.getReferenceByName("position"),g=h.getReferenceByName("focalPoint"),m=h.getReferenceByName("viewUp");if(e[0]!==f[0]||e[1]!==f[1]||e[2]!==f[2]||e[3]!==g[0]||e[4]!==g[1]||e[5]!==g[2]||e[6]!==m[0]||e[7]!==m[1]||e[8]!==m[2]){e[0]=f[0],e[1]=f[1],e[2]=f[2],e[3]=g[0],e[4]=g[1],e[5]=g[2],e[6]=m[0],e[7]=m[1],e[8]=m[2];const p=o.getActiveCamera();p.setPosition(f[0],f[1],f[2]),p.setFocalPoint(g[0],g[1],g[2]),p.setViewUp(m[0],m[1],m[2]),o.resetCamera()}},i.setEnabled=h=>{if(h){if(t.enabled)return;if(!t.actor){Au("Must set actor before enabling orientation marker.");return}if(!t._interactor){Au("Must set interactor before enabling orientation marker.");return}const f=t.parentRenderer||t._interactor.getCurrentRenderer(),g=f.getRenderWindow();g.addRenderer(o),g.getNumberOfLayers()<2&&g.setNumberOfLayers(2),o.setLayer(g.getNumberOfLayers()-1),o.setInteractive(t.interactiveRenderer),o.addViewProp(t.actor),t.actor.setVisibility(!0),a=f.onEvent(m=>{m.type==="ActiveCameraEvent"&&(r&&r.unsubscribe(),r=m.camera.onModified(u))}),r=f.getActiveCamera().onModified(u),c=t._interactor.onAnimation(i.updateMarkerOrientation),l=t._interactor.onEndAnimation(i.updateMarkerOrientation),s.observe(t._interactor.getView().getCanvas()),i.updateViewport(),i.updateMarkerOrientation(),t.enabled=!0}else{if(!t.enabled)return;t.enabled=!1,s.disconnect(),a.unsubscribe(),a=null,r.unsubscribe(),r=null,c.unsubscribe(),c=null,l.unsubscribe(),l=null,t.actor.setVisibility(!1),o.removeViewProp(t.actor);const f=t._interactor?.findPokedRenderer()?.getRenderWindow();f&&f.removeRenderer(o)}i.modified()},i.setViewportCorner=h=>{h!==t.viewportCorner&&(t.viewportCorner=h,i.updateViewport())},i.setViewportSize=h=>{const f=Math.min(1,Math.max(0,h));f!==t.viewportSize&&(t.viewportSize=f,i.updateViewport())},i.setActor=h=>{const f=t.enabled;i.setEnabled(!1),t.actor=h,i.setEnabled(f)},i.getRenderer=()=>o,i.delete=()=>{n.delete(),d&&(d.unsubscribe(),d=null),a&&(a.unsubscribe(),a=null),r&&(r.unsubscribe(),r=null),c&&(c.unsubscribe(),c=null),l&&(l.unsubscribe(),l=null),s.disconnect()},d=i.onModified(i.updateViewport)}var QF={viewportCorner:pg.Corners.BOTTOM_LEFT,viewportSize:.2,minPixelSize:50,maxPixelSize:200,parentRenderer:null,interactiveRenderer:!1};function zS(i,t,n={}){Object.assign(t,QF,n),Lt.obj(i,t),Lt.get(i,t,["enabled","viewportCorner","viewportSize","interactiveRenderer"]),Lt.setGet(i,t,["_interactor","minPixelSize","maxPixelSize","parentRenderer"]),Lt.get(i,t,["actor"]),Lt.moveToProtected(i,t,["interactor"]),JF(i,t)}var t3=Lt.newInstance(zS,"vtkOrientationMarkerWidget"),lv={newInstance:t3,extend:zS,...pg};function $S(i,t=[0,0,0,0]){const[n,e,o,s]=t,a=i.getContext("2d").getImageData(n,e,o||i.width,s||i.height),r=Ph.newInstance({type:"vtkImageData"});r.setOrigin(0,0,0),r.setSpacing(1,1,1),r.setExtent(0,(o||i.width)-1,0,(s||i.height)-1,0,0);const c=_n.newInstance({numberOfComponents:4,values:new Uint8Array(a.data.buffer)});return c.setName("scalars"),r.getPointData().setScalars(c),r}function e3(i,t={flipX:!1,flipY:!1,rotate:0}){const n=document.createElement("canvas");n.width=i.width,n.height=i.height;const e=n.getContext("2d"),{flipX:o,flipY:s,rotate:a}=t;return e.translate(n.width/2,n.height/2),e.scale(o?-1:1,s?-1:1),e.rotate(a*Math.PI/180),e.drawImage(i,-i.width/2,-i.height/2),$S(n)}var jS={canvasToImageData:$S,imageToImageData:e3},XS={default:{defaultStyle:{fontStyle:"bold",fontFamily:"Arial",fontColor:"black",fontSizeScale:i=>i/2,faceColor:"white",edgeThickness:.1,edgeColor:"black",resolution:400},xMinusFaceProperty:{text:"X-",faceColor:"yellow"},xPlusFaceProperty:{text:"X+",faceColor:"yellow"},yMinusFaceProperty:{text:"Y-",faceColor:"red"},yPlusFaceProperty:{text:"Y+",faceColor:"red"},zMinusFaceProperty:{text:"Z-",faceColor:"#008000"},zPlusFaceProperty:{text:"Z+",faceColor:"#008000"}},lps:{xMinusFaceProperty:{text:"R",faceRotation:-90},xPlusFaceProperty:{text:"L",faceRotation:90},yMinusFaceProperty:{text:"A",faceRotation:0},yPlusFaceProperty:{text:"P",faceRotation:180},zMinusFaceProperty:{text:"I",faceRotation:180},zPlusFaceProperty:{text:"S",faceRotation:0}}};function qS(i,t){t.set(i)}function n3(i,t){return qS(XS[i],t)}function o3(i,t){XS[i]=t}var i3={applyDefinitions:qS,applyPreset:n3,registerStylePreset:o3},s3={xPlus:0,xMinus:1,yPlus:2,yMinus:3,zPlus:4,zMinus:5};function a3(i,t){t.classHierarchy.push("vtkAnnotatedCubeActor"),t.xPlusFaceProperty={...t.xPlusFaceProperty},t.xMinusFaceProperty={...t.xMinusFaceProperty},t.yPlusFaceProperty={...t.yPlusFaceProperty},t.yMinusFaceProperty={...t.yMinusFaceProperty},t.zPlusFaceProperty={...t.zPlusFaceProperty},t.zMinusFaceProperty={...t.zMinusFaceProperty};let n=null;const e=document.createElement("canvas"),o=Oo.newInstance(),s=Pv.newInstance();s.setInterpolate(!0);function a(c,l=null){l&&Object.assign(t[`${c}FaceProperty`],l);const d={...t.defaultStyle,...t[`${c}FaceProperty`]};e.width=d.resolution,e.height=d.resolution;const u=e.getContext("2d");u.fillStyle=d.faceColor,u.fillRect(0,0,e.width,e.height),d.edgeThickness>0&&(u.strokeStyle=d.edgeColor,u.lineWidth=d.edgeThickness*e.width,u.strokeRect(0,0,e.width,e.height)),u.save(),u.translate(0,e.height),u.scale(1,-1),u.translate(e.width/2,e.height/2),u.rotate(-Math.PI*(d.faceRotation/180));const h=d.fontSizeScale(d.resolution);u.fillStyle=d.fontColor,u.textAlign="center",u.textBaseline="middle",u.font=`${d.fontStyle} ${h}px "${d.fontFamily}"`,u.fillText(d.text,0,0),u.restore();const f=jS.canvasToImageData(e);s.setInputData(f,s3[c]),i.modified()}function r(){n=$C.newInstance({generate3DTextureCoordinates:!0}),o.setInputConnection(n.getOutputPort()),a("xPlus"),a("xMinus"),a("yPlus"),a("yMinus"),a("zPlus"),a("zMinus")}i.setDefaultStyle=c=>{t.defaultStyle={...t.defaultStyle,...c},r()},i.setXPlusFaceProperty=c=>a("xPlus",c),i.setXMinusFaceProperty=c=>a("xMinus",c),i.setYPlusFaceProperty=c=>a("yPlus",c),i.setYMinusFaceProperty=c=>a("yMinus",c),i.setZPlusFaceProperty=c=>a("zPlus",c),i.setZMinusFaceProperty=c=>a("zMinus",c),r(),o.setInputConnection(n.getOutputPort()),i.setMapper(o),i.addTexture(s)}var r3={defaultStyle:{text:"",faceColor:"white",faceRotation:0,fontFamily:"Arial",fontColor:"black",fontStyle:"normal",fontSizeScale:i=>i/1.8,edgeThickness:.1,edgeColor:"black",resolution:200}};function YS(i,t,n={}){Object.assign(t,r3,n),vo.extend(i,t,n),Lt.get(i,t,["defaultStyle","xPlusFaceProperty","xMinusFaceProperty","yPlusFaceProperty","yMinusFaceProperty","zPlusFaceProperty","zMinusFaceProperty"]),a3(i,t)}var c3=Lt.newInstance(YS,"vtkAnnotatedCubeActor"),dv={newInstance:c3,extend:YS,Presets:i3},{vtkErrorMacro:l3}=Lt;function d3(i,t){let n=0;return i.map((e,o)=>o===n?(n+=e+1,e):e+t)}function Hc(i,t,n,e){i.set(d3(t,n),e)}function u3(i,t){t.classHierarchy.push("vtkAppendPolyData"),i.requestData=(n,e)=>{const o=i.getNumberOfInputPorts();if(!o){l3("No input specified.");return}if(o===1){e[0]=n[0];return}const s=e[0]&&n[0]!==e[0]?e[0].initialize():Vo.newInstance();let a=0,r=0,c=1,l=1,d=0,u=0,h=0,f=0,g=!0,m=!0,p=!0;for(let P=0;P<o;P++){const x=n[P];if(!x)continue;const M=x.getPoints().getNumberOfPoints();a+=M,d+=x.getVerts().getNumberOfValues(),u+=x.getLines().getNumberOfValues(),h+=x.getStrips().getNumberOfValues(),f+=x.getPolys().getNumberOfValues(),M&&(l&&(l=0,r=x.getPoints().getDataType()),c=x.getPoints().getDataType(),r=r>c?r:c);const L=x.getPointData();L?(g=g&&L.getNormals()!==null,m=m&&L.getTCoords()!==null,p=p&&L.getScalars()!==null):(g=!1,m=!1,p=!1)}t.outputPointsPrecision===ku.SINGLE?r=bg.FLOAT:t.outputPointsPrecision===ku.DOUBLE&&(r=bg.DOUBLE);const v=Ul.newInstance({dataType:r});v.setNumberOfPoints(a);const I=v.getData(),w=new Uint32Array(d),C=new Uint32Array(u),S=new Uint32Array(h),b=new Uint32Array(f);let _=null,y=null,D=null;const T=n[o-1];if(g){const P=T.getPointData().getNormals();_=_n.newInstance({numberOfComponents:3,numberOfTuples:a,size:3*a,dataType:P.getDataType(),name:P.getName()})}if(m){const P=T.getPointData().getTCoords();y=_n.newInstance({numberOfComponents:2,numberOfTuples:a,size:2*a,dataType:P.getDataType(),name:P.getName()})}if(p){const P=T.getPointData().getScalars();D=_n.newInstance({numberOfComponents:P.getNumberOfComponents(),numberOfTuples:a,size:a*P.getNumberOfComponents(),dataType:P.getDataType(),name:P.getName()})}a=0,d=0,u=0,h=0,f=0;for(let P=0;P<o;P++){const x=n[P];I.set(x.getPoints().getData(),a*3),Hc(w,x.getVerts().getData(),a,d),d+=x.getVerts().getNumberOfValues(),Hc(C,x.getLines().getData(),a,u),u+=x.getLines().getNumberOfValues(),Hc(S,x.getStrips().getData(),a,h),h+=x.getStrips().getNumberOfValues(),Hc(b,x.getPolys().getData(),a,f),f+=x.getPolys().getNumberOfValues();const M=x.getPointData();if(g){const L=M.getNormals();_.getData().set(L.getData(),a*3)}if(m){const L=M.getTCoords();y.getData().set(L.getData(),a*2)}if(p){const L=M.getScalars();D.getData().set(L.getData(),a*D.getNumberOfComponents())}a+=x.getPoints().getNumberOfPoints()}s.setPoints(v),s.getVerts().setData(w),s.getLines().setData(C),s.getStrips().setData(S),s.getPolys().setData(b),_&&s.getPointData().setNormals(_),y&&s.getPointData().setTCoords(y),D&&s.getPointData().setScalars(D),e[0]=s}}var h3={outputPointsPrecision:ku.DEFAULT};function KS(i,t,n={}){Object.assign(t,h3,n),Lt.setGet(i,t,["outputPointsPrecision"]),Lt.obj(i,t),Lt.algo(i,t,1,1),u3(i,t)}var f3=Lt.newInstance(KS,"vtkAppendPolyData"),ZS={newInstance:f3,extend:KS};function g3(i,t){t.classHierarchy.push("vtkConeSource"),i.requestData=(n,e)=>{const o=2*Math.PI/t.resolution,s=-t.height/2,a=t.resolution+1,r=4*t.resolution+1+t.resolution;let c=0;const l=Lt.newTypedArray(t.pointType,a*3);let d=0;const u=new Uint32Array(r);l[0]=t.height/2,l[1]=0,l[2]=0,t.capping&&(u[d++]=t.resolution);for(let f=0;f<t.resolution;f++)c++,l[c*3+0]=s,l[c*3+1]=t.radius*Math.cos(f*o),l[c*3+2]=t.radius*Math.sin(f*o),t.capping&&(u[t.resolution-d+++1]=c);for(let f=0;f<t.resolution;f++)u[d++]=3,u[d++]=0,u[d++]=f+1,u[d++]=f+2>t.resolution?1:f+2;po.buildFromRadian().translate(...t.center).rotateFromDirections([1,0,0],t.direction).apply(l);const h=e[0]?.initialize()||Vo.newInstance();h.getPoints().setData(l,3),h.getPolys().setData(u,1),e[0]=h}}var m3={height:1,radius:.5,resolution:6,center:[0,0,0],direction:[1,0,0],capping:!0,pointType:"Float64Array"};function JS(i,t,n={}){Object.assign(t,m3,n),Lt.obj(i,t),Lt.setGet(i,t,["height","radius","resolution","capping"]),Lt.setGetArray(i,t,["center","direction"],3),Lt.algo(i,t,0,1),g3(i,t)}var p3=Lt.newInstance(JS,"vtkConeSource"),v3={newInstance:p3,extend:JS};function I3(i,t){t.classHierarchy.push("vtkCylinderSource"),i.requestData=(n,e)=>{const o=2*Math.PI/t.resolution;let s=2*t.resolution,a=5*t.resolution;t.capping&&(s=4*t.resolution,a=7*t.resolution+2);const r=Lt.newTypedArray(t.pointType,s*3);let c=0;const l=new Uint32Array(a),d=new Float32Array(s*3),u=_n.newInstance({numberOfComponents:3,values:d,name:"Normals"}),h=new Float32Array(s*2),f=_n.newInstance({numberOfComponents:2,values:h,name:"TCoords"}),g=[0,0,0],m=[0,0,0],p=[0,0,0],v=[0,0,0],I=[0,0],w=[0,0],C=t.otherRadius==null?t.radius:t.otherRadius;for(let b=0;b<t.resolution;b++){g[0]=Math.cos(b*o+t.initAngle),m[0]=g[0],p[0]=t.radius*g[0]+t.center[0],v[0]=p[0],I[0]=Math.abs(2*b/t.resolution-1),w[0]=I[0],p[1]=.5*t.height+t.center[1],v[1]=-.5*t.height+t.center[1],I[1]=0,w[1]=1,g[2]=-Math.sin(b*o+t.initAngle),m[2]=g[2],p[2]=C*g[2]+t.center[2],v[2]=p[2];const _=2*b;for(let y=0;y<3;y++)d[_*3+y]=g[y],d[(_+1)*3+y]=m[y],r[_*3+y]=p[y],r[(_+1)*3+y]=v[y],y<2&&(h[_*2+y]=I[y],h[(_+1)*2+y]=w[y])}for(let b=0;b<t.resolution;b++){l[c++]=4,l[c++]=2*b,l[c++]=2*b+1;const _=(2*b+3)%(2*t.resolution);l[c++]=_,l[c++]=_-1}if(t.capping){for(let b=0;b<t.resolution;b++){p[0]=t.radius*Math.cos(b*o+t.initAngle),v[0]=p[0],I[0]=p[0],w[0]=p[0],p[0]+=t.center[0],v[0]+=t.center[0],g[1]=1,m[1]=-1,p[1]=.5*t.height+t.center[1],v[1]=-.5*t.height+t.center[1],p[2]=-C*Math.sin(b*o+t.initAngle),v[2]=p[2],I[1]=p[2],w[1]=p[2],p[2]+=t.center[2],v[2]+=t.center[2];const _=2*t.resolution+b,y=3*t.resolution+t.resolution-b-1;for(let D=0;D<3;D++)d[3*_+D]=g[D],d[3*y+D]=m[D],r[3*_+D]=p[D],r[3*y+D]=v[D],D<2&&(h[2*_+D]=I[D],h[2*y+D]=w[D])}l[c++]=t.resolution;for(let b=0;b<t.resolution;b++)l[c++]=2*t.resolution+b;l[c++]=t.resolution;for(let b=0;b<t.resolution;b++)l[c++]=3*t.resolution+b}po.buildFromRadian().translate(...t.center).rotateFromDirections([0,1,0],t.direction).translate(...t.center.map(b=>b*-1)).apply(r),po.buildFromRadian().rotateFromDirections([0,1,0],t.direction).apply(d);const S=e[0]?.initialize()||Vo.newInstance();S.getPoints().setData(r,3),S.getPolys().setData(l,1),S.getPointData().setNormals(u),S.getPointData().setTCoords(f),e[0]=S}}var w3={height:1,initAngle:0,radius:1,resolution:6,center:[0,0,0],direction:[0,1,0],capping:!0,pointType:"Float64Array"};function QS(i,t,n={}){Object.assign(t,w3,n),Lt.obj(i,t),Lt.setGet(i,t,["height","initAngle","otherRadius","radius","resolution","capping"]),Lt.setGetArray(i,t,["center","direction"],3),Lt.algo(i,t,0,1),I3(i,t)}var E3=Lt.newInstance(QS,"vtkCylinderSource"),S3={newInstance:E3,extend:QS};function C3(i,t){t.classHierarchy.push("vtkArrowSource"),i.requestData=(n,e)=>{const o=S3.newInstance({capping:!0});o.setResolution(t.shaftResolution),o.setRadius(t.shaftRadius),o.setHeight(1-t.tipLength),o.setCenter(0,(1-t.tipLength)*.5,0);const s=o.getOutputData(),a=s.getPoints().getData(),r=s.getPointData().getNormals().getData();po.buildFromDegree().rotateZ(-90).apply(a).apply(r);const c=v3.newInstance();c.setResolution(t.tipResolution),c.setHeight(t.tipLength),c.setRadius(t.tipRadius);const l=c.getOutputData(),d=l.getPoints().getData();po.buildFromRadian().translate(1-t.tipLength*.5,0,0).apply(d);const u=ZS.newInstance();u.setInputData(s),u.addInputData(l);const h=u.getOutputData(),f=h.getPoints().getData();po.buildFromRadian().translate(-.5+t.tipLength*.5,0,0).apply(f),t.invert?(po.buildFromRadian().rotateFromDirections([1,0,0],t.direction).scale(-1,-1,-1).apply(f),e[0]=h):(po.buildFromRadian().rotateFromDirections([1,0,0],t.direction).scale(1,1,1).apply(f),e[0]=u.getOutputData())}}var b3={tipResolution:6,tipRadius:.1,tipLength:.35,shaftResolution:6,shaftRadius:.03,invert:!1,direction:[1,0,0],pointType:"Float64Array"};function tC(i,t,n={}){Object.assign(t,b3,n),Lt.obj(i,t),Lt.setGet(i,t,["tipResolution","tipRadius","tipLength","shaftResolution","shaftRadius","invert"]),Lt.setGetArray(i,t,["direction"],3),Lt.algo(i,t,0,1),C3(i,t)}var _3=Lt.newInstance(tC,"vtkArrowSource"),Lu={newInstance:_3,extend:tC};function Ou(i){const t=i.getPoints().getBounds(),n=[-(t[0]+t[1])*.5,-(t[2]+t[3])*.5,-(t[4]+t[5])*.5];po.buildFromDegree().translate(...n).apply(i.getPoints().getData())}function Ru(i,t,n=!1){const e=i.getPoints().getBounds(),o=[0,0,0];n?o[t]=-e[t*2+1]:o[t]=-e[t*2],po.buildFromDegree().translate(...o).apply(i.getPoints().getData())}function Nu(i,t,n,e){const o=i.getPoints().getData().length,s=new Uint8ClampedArray(o);let a=0;for(;a<o;)s[a++]=t,s[a++]=n,s[a++]=e;i.getPointData().setScalars(_n.newInstance({name:"color",numberOfComponents:3,values:s}))}function y3(i,t){t.classHierarchy.push("vtkAxesActor");const n=Oo.newInstance();i.setMapper(n),i.update=()=>{let o={...t.config,...t.xConfig};const s=Lu.newInstance({direction:[1,0,0],...o}).getOutputData();t.config.recenter?Ou(s):Ru(s,0,o.invert),Nu(s,...o.color),o={...t.config,...t.yConfig};const a=Lu.newInstance({direction:[0,1,0],...o}).getOutputData();t.config.recenter?Ou(a):Ru(a,1,o.invert),Nu(a,...o.color),o={...t.config,...t.zConfig};const r=Lu.newInstance({direction:[0,0,1],...o}).getOutputData();t.config.recenter?Ou(r):Ru(r,2,o.invert),Nu(r,...o.color);const c=ZS.newInstance();c.setInputData(s),c.addInputData(a),c.addInputData(r),n.setInputConnection(c.getOutputPort())},i.update();const e=Lt.debounce(i.update,0);i.setXAxisColor=o=>i.setXConfig({...i.getXConfig(),color:o}),i.setYAxisColor=o=>i.setYConfig({...i.getYConfig(),color:o}),i.setZAxisColor=o=>i.setZConfig({...i.getZConfig(),color:o}),i.getXAxisColor=()=>t.getXConfig().color,i.getYAxisColor=()=>t.getYConfig().color,i.getZAxisColor=()=>t.getZConfig().color,t._onConfigChanged=e,t._onXConfigChanged=e,t._onYConfigChanged=e,t._onZConfigChanged=e}function x3(i){return{config:{recenter:!0,tipResolution:60,tipRadius:.1,tipLength:.2,shaftResolution:60,shaftRadius:.03,invert:!1,...i?.config},xConfig:{color:[255,0,0],invert:!1,...i?.xConfig},yConfig:{color:[255,255,0],invert:!1,...i?.yConfig},zConfig:{color:[0,128,0],invert:!1,...i?.zConfig}}}function eC(i,t,n={}){vo.extend(i,t,x3(n)),Lt.setGet(i,t,["config","xConfig","yConfig","zConfig"]),y3(i,t)}var P3=Lt.newInstance(eC,"vtkAxesActor"),D3={newInstance:P3,extend:eC},Rl;(function(i){i[i.ANNOTATED_CUBE=1]="ANNOTATED_CUBE",i[i.AXES=2]="AXES",i[i.CUSTOM=3]="CUSTOM"})(Rl||(Rl={}));class Xo extends Ee{constructor(t={},n={configuration:{orientationWidget:{enabled:!0,viewportCorner:lv.Corners.BOTTOM_RIGHT,viewportSize:.15,minPixelSize:100,maxPixelSize:300},overlayMarkerType:Xo.OVERLAY_MARKER_TYPES.ANNOTATED_CUBE,overlayConfiguration:{[Xo.OVERLAY_MARKER_TYPES.ANNOTATED_CUBE]:{faceProperties:{xPlus:{text:"L",faceColor:"#ffff00",faceRotation:90},xMinus:{text:"R",faceColor:"#ffff00",faceRotation:270},yPlus:{text:"P",faceColor:"#00ffff",fontColor:"white",faceRotation:180},yMinus:{text:"A",faceColor:"#00ffff",fontColor:"white"},zPlus:{text:"S"},zMinus:{text:"I"}},defaultStyle:{fontStyle:"bold",fontFamily:"Arial",fontColor:"black",fontSizeScale:e=>e/2,faceColor:"#0000ff",edgeThickness:.1,edgeColor:"black",resolution:400}},[Xo.OVERLAY_MARKER_TYPES.AXES]:{},[Xo.OVERLAY_MARKER_TYPES.CUSTOM]:{polyDataURL:"https://raw.githubusercontent.com/Slicer/Slicer/80ad0a04dacf134754459557bf2638c63f3d1d1b/Base/Logic/Resources/OrientationMarkers/Human.vtp"}}}}){super(t,n),this._resizeObservers=new Map,this.onSetToolEnabled=()=>{this.initViewports(),this._subscribeToViewportEvents()},this.onSetToolActive=()=>{this.initViewports(),this._subscribeToViewportEvents()},this.onSetToolDisabled=()=>{this.cleanUpData(),this._unsubscribeToViewportNewVolumeSet()},this._getViewportsInfo=()=>Be(this.toolGroupId).viewportsInfo,this.resize=e=>{const o=this.orientationMarkers[e];if(!o)return;const{orientationWidget:s}=o;s.updateViewport()},this.orientationMarkers={},this.updatingOrientationMarker={}}_unsubscribeToViewportNewVolumeSet(){const t=()=>{this._getViewportsInfo().forEach(({viewportId:e,renderingEngineId:o})=>{const{viewport:s}=ae(e,o),{element:a}=s;a.removeEventListener(yt.VOLUME_VIEWPORT_NEW_VOLUME,this.initViewports.bind(this)),this._resizeObservers.get(e).unobserve(a)})};Z.removeEventListener(E.TOOLGROUP_VIEWPORT_ADDED,n=>{n.detail.toolGroupId===this.toolGroupId&&(t(),this.initViewports())})}_subscribeToViewportEvents(){const t=()=>{this._getViewportsInfo().forEach(({viewportId:e,renderingEngineId:o})=>{const{viewport:s}=ae(e,o),{element:a}=s;this.initViewports(),a.addEventListener(yt.VOLUME_VIEWPORT_NEW_VOLUME,this.initViewports.bind(this));const r=new ResizeObserver(()=>{setTimeout(()=>{const c=ae(e,o);if(!c)return;const{viewport:l}=c;this.resize(e),l.render()},100)});r.observe(a),this._resizeObservers.set(e,r)})};t(),Z.addEventListener(E.TOOLGROUP_VIEWPORT_ADDED,n=>{n.detail.toolGroupId===this.toolGroupId&&(t(),this.initViewports())})}cleanUpData(){Vi()[0].getViewports().forEach(o=>{const s=this.orientationMarkers[o.id];if(!s)return;const{actor:a,orientationWidget:r}=s;r?.setEnabled(!1),r?.delete(),a?.delete(),o.getRenderingEngine().getOffscreenMultiRenderWindow(o.id).getRenderWindow().render(),o.getRenderingEngine().render(),delete this.orientationMarkers[o.id]})}initViewports(){const n=Vi()[0];if(!n)return;let e=n.getViewports();e=od(e,this.getToolName()),e.forEach(o=>{if(typeof o.getWidget!="function")return;const s=o.getWidget(this.getToolName());(!s||s.isDeleted())&&this.addAxisActorInViewport(o)})}async addAxisActorInViewport(t){const n=t.id;if(!this.updatingOrientationMarker[n]){this.updatingOrientationMarker[n]=!0;const e=this.configuration.overlayMarkerType,o=this.configuration.overlayConfiguration[e];if(this.orientationMarkers[n]){const{actor:g,orientationWidget:m}=this.orientationMarkers[n];t.getRenderer().removeActor(g),m.setEnabled(!1)}let s;e===1?s=this.createAnnotationCube(o):e===2?s=D3.newInstance():e===3&&(s=await this.createCustomActor());const a=t.getRenderer(),r=t.getRenderingEngine().getOffscreenMultiRenderWindow(n).getRenderWindow(),{enabled:c,viewportCorner:l,viewportSize:d,minPixelSize:u,maxPixelSize:h}=this.configuration.orientationWidget,f=lv.newInstance({actor:s,interactor:r.getInteractor(),parentRenderer:a});f.setEnabled(c),f.setViewportCorner(l),f.setViewportSize(d),f.setMinPixelSize(u),f.setMaxPixelSize(h),f.updateMarkerOrientation(),this.orientationMarkers[n]={orientationWidget:f,actor:s},t.addWidget(this.getToolName(),f),r.render(),t.getRenderingEngine().render(),this.updatingOrientationMarker[n]=!1}}async createCustomActor(){const t=this.configuration.overlayConfiguration[Rl.CUSTOM].polyDataURL,e=await(await fetch(t)).arrayBuffer(),o=jC.newInstance();o.parseAsArrayBuffer(e),o.update();const s=Vo.newInstance();s.shallowCopy(o.getOutputData()),s.getPointData().setActiveScalars("Color");const a=Oo.newInstance();a.setInputData(s),a.setColorModeToDirectScalars();const r=vo.newInstance();return r.setMapper(a),r.rotateZ(180),r}createAnnotationCube(t){const n=dv.newInstance();return n.setDefaultStyle({...t.defaultStyle}),n.setXPlusFaceProperty({...t.faceProperties.xPlus}),n.setXMinusFaceProperty({...t.faceProperties.xMinus}),n.setYPlusFaceProperty({...t.faceProperties.yPlus}),n.setYMinusFaceProperty({...t.faceProperties.yMinus}),n.setZPlusFaceProperty({...t.faceProperties.zPlus}),n.setZMinusFaceProperty({...t.faceProperties.zMinus}),n}async createAnnotatedCubeActor(){const t=dv.newInstance(),{faceProperties:n,defaultStyle:e}=this.configuration.annotatedCube;return t.setDefaultStyle(e),Object.keys(n).forEach(o=>{const s=`set${o.charAt(0).toUpperCase()+o.slice(1)}FaceProperty`;t[s](n[o])}),t}}Xo.CUBE=1;Xo.AXIS=2;Xo.VTPFILE=3;Xo.OVERLAY_MARKER_TYPES=Rl;Xo.toolName="OrientationMarker";function nC(i,t,n){let e=-1,o=-1,s=0,a=1;for(let d=0;d<3;d++)for(let u=0;u<2;u++){const h=2*d+u,f=(i[h]-t[d])*(1-2*u),g=(i[h]-n[d])*(1-2*u);if(f>0&&g>0)return;if(f>0||g>0){let m=0;if(f!==0&&(m=f/(f-g)),f>0?m>=s&&(s=m,e=h):m<=a&&(a=m,o=h),s>a&&(e<0||o<0))return}}function r(d,u){const h=[0,0,0];for(let f=0;f<2;f++)for(let g=0;g<3;g++)d===2*g||d===2*g+1?h[g]=i[d]:(h[g]=t[g]*(1-u)+n[g]*u,h[g]<i[2*g]&&(h[g]=i[2*g]),h[g]>i[2*g+1]&&(h[g]=i[2*g+1]));return h}const c=r(e,s),l=r(o,a);return{t1:s,t2:a,x1:c,x2:l}}var T3={};function M3(i,t){t.classHierarchy.push("vtkBox"),i.setBounds=(...n)=>{let e=[];if(Array.isArray(n[0]))e=n[0];else for(let o=0;o<n.length;o++)e.push(n[o]);if(e.length!==6){console.log("vtkBox.setBounds",e,n);return}di.setBounds(t.bbox,e)},i.getBounds=()=>[...t.bbox],i.evaluateFunction=(n,e,o)=>{const s=Array.isArray(n)?n:[n,e,o];let a,r,c,l=-Number.MAX_VALUE,d=0;const u=di.getMinPoint(t.bbox),h=di.getMaxPoint(t.bbox);let f=1;for(let g=0;g<3;g++)a=di.getLength(t.bbox,g),a!==0?(c=(s[g]-u[g])/a,c<0?(f=0,r=u[g]-s[g]):c>1?(f=0,r=s[g]-h[g]):(c<=.5?r=u[g]-s[g]:r=s[g]-h[g],r>l&&(l=r))):(r=Math.abs(s[g]-u[g]),r>0&&(f=0)),r>0&&(d+=r*r);return d=Math.sqrt(d),f?l:d},i.addBounds=(...n)=>{let e=[];if(Array.isArray(n[0]))e=n[0];else for(let o=0;o<n.length;o++)e.push(n[o]);e.length===6&&(di.addBounds(t.bbox,...e),i.modified())},i.addBox=n=>i.addBounds(n.getBounds()),i.intersectWithLine=(n,e)=>nC(t.bbox,n,e)}var A3={bbox:[...di.INIT_BOUNDS]};function oC(i,t,n={}){Object.assign(t,A3,n),XC.extend(i,t,n),M3(i,t)}var L3=Lt.newInstance(oC,"vtkBox"),O3={newInstance:L3,extend:oC,intersectWithLine:nC,...T3};function R3(i,t){t.classHierarchy.push("vtkAbstractPicker"),i.initialize=()=>{t.renderer=null,t.selectionPoint[0]=0,t.selectionPoint[1]=0,t.selectionPoint[2]=0,t.pickPosition[0]=0,t.pickPosition[1]=0,t.pickPosition[2]=0},i.initializePickList=()=>{t.pickList=[]},i.addPickList=n=>{t.pickList.push(n)},i.deletePickList=n=>{const e=t.pickList.indexOf(n);e!==-1&&t.pickList.splice(e,1)}}var N3={renderer:null,selectionPoint:[0,0,0],pickPosition:[0,0,0],pickFromList:!1,pickList:[]};function iC(i,t,n={}){Object.assign(t,N3,n),Lt.obj(i,t),Lt.get(i,t,["renderer"]),Lt.getArray(i,t,["selectionPoint","pickPosition"]),Lt.setGet(i,t,["pickFromList","pickList"]),R3(i,t)}var k3=Lt.newInstance(iC,"vtkAbstractPicker"),U3={newInstance:k3,extend:iC},{vtkErrorMacro:V3}=Lt,{vtkWarningMacro:Wc}=Lt;function F3(i,t){t.classHierarchy.push("vtkPicker");const n={...i};function e(){n.initialize(),t.actors=[],t.pickedPositions=[],t.mapperPosition[0]=0,t.mapperPosition[1]=0,t.mapperPosition[2]=0,t.mapper=null,t.dataSet=null,t.globalTMin=Number.MAX_VALUE}function o(a,r,c){let l=0;const d=c.getRenderWindow().getViews()[0],u=c.getViewport(),h=d.getSize();let f=h[0]*u[0],g=h[1]*u[1];const m=d.displayToNormalizedDisplay(f,g,a),p=c.normalizedDisplayToWorld(m[0],m[1],m[2],r);f=h[0]*u[2],g=h[1]*u[3];const v=d.displayToNormalizedDisplay(f,g,a),I=c.normalizedDisplayToWorld(v[0],v[1],v[2],r);for(let w=0;w<3;w++)l+=(I[w]-p[w])*(I[w]-p[w]);return Math.sqrt(l)}function s(a,r,c,l){const d=new Float64Array(4),u=new Float64Array(4),h=[],f=[],g=t.pickFromList?t.pickList:a.getActors(),m=new Float64Array(3),p=new Float64Array(3);g.forEach(I=>{const w=I.getMapper(),C=I.getProperty?.().getOpacity?.()===0;if(!(I.getNestedPickable()&&I.getNestedVisibility()&&!C))return;t.transformMatrix=I.getMatrix().slice(0),KC(t.transformMatrix,t.transformMatrix),ZC(t.transformMatrix,t.transformMatrix),Jc(d,c,t.transformMatrix),Jc(u,l,t.transformMatrix),yg(d,d,1/d[3]),yg(u,u,1/u[3]),JC(u,d,h);const S=w?di.inflate(w.getBounds(),r):[...di.INIT_BOUNDS];if(di.intersectBox(S,d,h,f,[])){QC(m,t.transformMatrix);const b=t.intersectWithLine(d,u,r*.333*(m[0]+m[1]+m[2]),I,w);if(b<Number.MAX_VALUE){p[0]=(1-b)*c[0]+b*l[0],p[1]=(1-b)*c[1]+b*l[1],p[2]=(1-b)*c[2]+b*l[2];const _=t.actors.indexOf(I);if(_!==-1){const y=t.pickedPositions[_];Bc(c,p)<Bc(c,y)&&(t.pickedPositions[_]=p.slice(0))}else t.actors.push(I),t.pickedPositions.push(p.slice(0))}}});const v=[];for(let I=0;I<t.pickedPositions.length;I++)v.push({actor:t.actors[I],pickedPosition:t.pickedPositions[I],distance2:Bc(c,t.pickedPositions[I])});v.sort((I,w)=>{const C=I.distance2,S=w.distance2;return C<S?-1:C>S?1:0}),t.pickedPositions=[],t.actors=[],v.forEach(I=>{t.pickedPositions.push(I.pickedPosition),t.actors.push(I.actor)})}t.intersectWithLine=(a,r,c,l,d)=>{if(!d)return Number.MAX_VALUE;const u=d.getCenter(),h=qC(new Float64Array(3),r,a),f=_g(h,h);return f===0?2:(h[0]*(u[0]-a[0])+h[1]*(u[1]-a[1])+h[2]*(u[2]-a[2]))/f},i.pick=(a,r)=>{if(a.length!==3&&Wc("vtkPicker.pick - selection needs three components"),!r)throw V3("vtkPicker.pick - renderer cannot be null"),new Error("renderer cannot be null");e();const c=a[0],l=a[1];let d=a[2];t.renderer=r,t.selectionPoint[0]=c,t.selectionPoint[1]=l,t.selectionPoint[2]=d;const u=new Float64Array(4),h=new Float64Array(4),f=r.getActiveCamera(),g=f.getPosition(),m=f.getFocalPoint(),p=r.getRenderWindow().getViews()[0],v=p.getViewportSize(r);if(v[1]===0){Wc("vtkPicker.pick - viewport area is 0");return}const I=v[0]/v[1];let w=[];w=r.worldToNormalizedDisplay(m[0],m[1],m[2],I),w=p.normalizedDisplayToDisplay(w[0],w[1],w[2]),d=w[2];const C=p.displayToNormalizedDisplay(c,l,d),S=r.normalizedDisplayToWorld(C[0],C[1],C[2],I);for(let M=0;M<3;M++)t.pickPosition[M]=S[M];const b=[];for(let M=0;M<3;M++)b[M]=t.pickPosition[M]-g[M];const _=[];for(let M=0;M<3;M++)_[M]=m[M]-g[M];tr(_);const y=_g(_,b);if(y===0){Wc("Picker::Pick Cannot process points");return}const D=f.getClippingRange();let T,P;if(f.getParallelProjection()){T=D[0]-y,P=D[1]-y;for(let M=0;M<3;M++)u[M]=t.pickPosition[M]+T*_[M],h[M]=t.pickPosition[M]+P*_[M]}else{T=D[0]/y,P=D[1]/y;for(let M=0;M<3;M++)u[M]=g[M]+T*b[M],h[M]=g[M]+P*b[M]}u[3]=1,h[3]=1;const x=o(d,I,r)*t.tolerance;s(t.renderer,x,u,h)},i.pick3DPoint=(a,r,c)=>{if(!c)throw new Error("renderer cannot be null");e(),t.renderer=c,YC(t.selectionPoint,a);const l=c.getRenderWindow().getViews()[0].getViewportSize(c);if(l[1]===0){Wc("vtkPicker.pick3DPoint - viewport area is 0");return}const d=l[0]/l[1];s(c,o(t.selectionPoint[2],d,c)*t.tolerance,a,r)}}var G3={tolerance:.025,mapperPosition:[0,0,0],mapper:null,dataSet:null,actors:[],pickedPositions:[],transformMatrix:null,globalTMin:Number.MAX_VALUE};function sC(i,t,n={}){Object.assign(t,G3,n),U3.extend(i,t,n),Lt.setGet(i,t,["tolerance"]),Lt.setGetArray(i,t,["mapperPosition"],3),Lt.get(i,t,["mapper","dataSet","actors","pickedPositions"]),Lt.event(i,t,"pickChange"),F3(i,t)}var H3=Lt.newInstance(sC,"vtkPicker"),W3={newInstance:H3,extend:sC};function uv(){return{[er.VTK_LINE]:ib.newInstance(),[er.VTK_POLY_LINE]:ob.newInstance(),[er.VTK_TRIANGLE]:nb.newInstance(),[er.VTK_QUAD]:eb.newInstance()}}function aC(i,t,n,e){const o={planeId:-1,t1:0,t2:1,intersect:0},s=i.getNumberOfClippingPlanes(),a=[];for(let r=0;r<s;r++){i.getClippingPlaneInDataCoords(t,r,a);const c=a[0]*n[0]+a[1]*n[1]+a[2]*n[2]+a[3],l=a[0]*e[0]+a[1]*e[1]+a[2]*e[2]+a[3];if(c<0&&l<0)return 0;if(c<0||l<0){let d=0;if(c!==0&&(d=c/(c-l)),c<0?d>=o.t1&&(o.t1=d,o.planeId=r):d<=o.t2&&(o.t2=d),o.t1>o.t2)return o.intersect=0,o}}return o.intersect=1,o}var B3={clipLineWithPlane:aC};function z3(i,t){t.classHierarchy.push("vtkCellPicker");const n={...i};function e(){t.cellId=-1,t.pCoords[0]=0,t.pCoords[1]=0,t.pCoords[2]=0,t.cellIJK[0]=0,t.cellIJK[1]=0,t.cellIJK[2]=0,t.mapperNormal[0]=0,t.mapperNormal[1]=0,t.mapperNormal[2]=1,t.pickNormal[0]=0,t.pickNormal[1]=0,t.pickNormal[2]=1}function o(){t.dataSet=null,t.mapper=null,e()}i.initialize=()=>{o(),n.initialize()},i.computeSurfaceNormal=(s,a,r,c)=>{const l=s.getPointData().getNormals();if(l){c[0]=0,c[1]=0,c[2]=0;const d=[];for(let u=0;u<3;u++)l.getTuple(a.getPointsIds()[u],d),c[0]+=d[0]*r[u],c[1]+=d[1]*r[u],c[2]+=d[2]*r[u];tr(c)}else return 0;return 1},i.pick=(s,a)=>{i.initialize();const r=n.pick(s,a);if(r){const c=a.getActiveCamera(),l=[];if(c.getPosition(l),c.getParallelProjection()){const d=[];c.getFocalPoint(d),t.pickNormal[0]=l[0]-d[0],t.pickNormal[1]=l[1]-d[1],t.pickNormal[2]=l[2]-d[2]}else t.pickNormal[0]=l[0]-t.pickPosition[0],t.pickNormal[1]=l[1]-t.pickPosition[1],t.pickNormal[2]=l[2]-t.pickPosition[2];tr(t.pickNormal)}return r},t.intersectWithLine=(s,a,r,c,l)=>{let d=Number.MAX_VALUE,u=0,h=1;const f=1e-14,g=aC(l,t.transformMatrix,s,a);if(l&&!g.intersect)return Number.MAX_VALUE;if(l.isA("vtkImageMapper")||l.isA("vtkImageArrayMapper")){const m=l.intersectWithLineForCellPicking(s,a);m&&(d=m.t,t.cellIJK=m.ijk,t.pCoords=m.pCoords)}else if(l.isA("vtkVolumeMapper")){const m=O3.intersectWithLine(l.getBounds(),s,a);u=m?.t1>g.t1?m.t1:g.t1,h=m?.t2<g.t2?m.t2:g.t2,d=t.intersectVolumeWithLine(s,a,u,h,r,c)}else l.isA("vtkMapper")&&(d=t.intersectActorWithLine(s,a,u,h,r,l));if(d<t.globalTMin){if(t.globalTMin=d,Math.abs(d-u)<f&&g.clippingPlaneId>=0){t.mapperPosition[0]=s[0]*(1-u)+a[0]*u,t.mapperPosition[1]=s[1]*(1-u)+a[1]*u,t.mapperPosition[2]=s[2]*(1-u)+a[2]*u;const p=[];l.getClippingPlaneInDataCoords(t.transformMatrix,g.clippingPlaneId,p),tr(p),t.mapperNormal[0]=-p[0],t.mapperNormal[1]=-p[1],t.mapperNormal[2]=-p[2]}tb(t.pickPosition,t.mapperPosition,t.transformMatrix);const m=t.transformMatrix;t.mapperNormal[0]=m[0]*t.pickNormal[0]+m[4]*t.pickNormal[1]+m[8]*t.pickNormal[2],t.mapperNormal[1]=m[1]*t.pickNormal[0]+m[5]*t.pickNormal[1]+m[9]*t.pickNormal[2],t.mapperNormal[2]=m[2]*t.pickNormal[0]+m[6]*t.pickNormal[1]+m[10]*t.pickNormal[2]}return d},t.intersectVolumeWithLine=(s,a,r,c,l,d)=>{let u=Number.MAX_VALUE;const h=d.getMapper(),f=h.getInputData(),g=f.getDimensions(),m=f.getPointData().getScalars().getData(),p=f.getExtent(),v=f.getWorldToIndex(),I=1;let w=h.getOpacityTextureWidth();w<=0&&(w=1024);const C=new Float32Array(w),S=new Float32Array(w);let b,_;const y=d.getMapper().getSampleDistance();for(let F=0;F<I;++F){b=d.getProperty().getScalarOpacity(F),_=b.getRange(),b.getTable(_[0],_[1],w,C,1);const z=y/d.getProperty().getScalarOpacityUnitDistance(F);for(let q=0;q<w;++q)S[q]=1-(1-C[q])**z}const D=w/(_[1]-_[0]+1),T=[0,0,0,1],P=[0,0,0,1];if(T[0]=s[0],T[1]=s[1],T[2]=s[2],P[0]=a[0],P[1]=a[1],P[2]=a[2],r!==0||c!==1)for(let F=0;F<3;F++)T[F]=s[F]*(1-r)+a[F]*r,P[F]=s[F]*(1-c)+a[F]*c;const x=[0,0,0,0],M=[0,0,0,0];Jc(x,T,v),Jc(M,P,v);const L=[0,0,0],R=[0,0,0],U=g[1]*g[0],W=g[0],K=1/Math.sqrt(Bc(x,M));let j;for(let F=0;F<1;F+=K){j=!0;for(let z=0;z<3;z++)L[z]=x[z]*(1-F)+M[z]*F;for(let z=0;z<3;z++)L[z]<p[2*z]?(L[z]=p[2*z],j=!1):L[z]>p[2*z+1]&&(L[z]=p[2*z+1],j=!1),R[z]=Math.round(L[z]);if(j){let z=m[R[2]*U+R[1]*W+R[0]];if(z<_[0]?z=_[0]:z>_[1]&&(z=_[1]),z=Math.floor((z-_[0])*D),C[z]>t.opacityThreshold){u=r*(1-F)+c*F;break}}}return u},t.intersectActorWithLine=(s,a,r,c,l,d)=>{let u=Number.MAX_VALUE;const h=[0,0,0];let f=Number.MAX_VALUE;const g=[0,0,0];let m=null,p=null,v=null,I=null;const w=[],C=d.getInputData(),S=[0,0,0],b=[0,0,0];if(S[0]=s[0],S[1]=s[1],S[2]=s[2],b[0]=a[0],b[1]=a[1],b[2]=a[2],r!==0||c!==1)for(let _=0;_<3;_++)S[_]=s[_]*(1-r)+a[_]*r,b[_]=s[_]*(1-c)+a[_]*c;if(C.getCells){C.getCells()||C.buildLinks();const _=uv(),y=uv(),D=C.getNumberOfCells();for(let T=0;T<D;T++){const P=[0,0,0];if(v=C.getCellType(T),v===er.VTK_EMPTY_CELL)continue;const x=_[v];if(x==null)continue;p=y[v],C.getCell(T,x);let M;if(xg.hasSubCells(v)?M=x.intersectWithLine(r,c,s,a,l,w,P):M=x.intersectWithLine(s,a,l,w,P),M.intersect===1&&M.t<=u+t.tolerance&&M.t>=r&&M.t<=c){const L=x.getParametricDistance(P);if(L<f||L===f&&M.t<u){u=M.t,f=L,I=M.subId,m=T,x.deepCopy(p);for(let R=0;R<3;R++)h[R]=w[R],g[R]=P[R]}}}}if(m>=0&&u<t.globalTMin){o();const _=p.getNumberOfPoints(),y=new Array(_);for(let x=0;x<_;x++)y[x]=0;const D=[];xg.hasSubCells(v)?p.evaluateLocation(I,g,D,y):p.evaluateLocation(g,D,y),t.dataSet=C,t.cellId=m,t.pCoords[0]=g[0],t.pCoords[1]=g[1],t.pCoords[2]=g[2];let T=0,P=-1;for(let x=0;x<_;x++)y[x]>T&&(P=x,T=y[x]);P!==-1&&(t.pointId=p.getPointsIds()[P]),t.mapperPosition[0]=h[0],t.mapperPosition[1]=h[1],t.mapperPosition[2]=h[2],i.computeSurfaceNormal(C,p,y,t.mapperNormal)||(t.mapperNormal[0]=s[0]-a[0],t.mapperNormal[1]=s[1]-a[1],t.mapperNormal[2]=s[2]-a[2],tr(t.mapperNormal))}return u}}var $3={cellId:-1,pCoords:[],cellIJK:[],pickNormal:[],mapperNormal:[],opacityThreshold:.2};function rC(i,t,n={}){Object.assign(t,$3,n),W3.extend(i,t,n),Lt.getArray(i,t,["pickNormal","mapperNormal","pCoords","cellIJK"]),Lt.setGet(i,t,["opacityThreshold"]),Lt.get(i,t,["cellId"]),z3(i,t)}var j3=Lt.newInstance(rC,"vtkCellPicker"),X3={newInstance:j3,extend:rC,...B3};const q3=[4,0,1,2,3,4,4,5,6,7,4,8,9,10,11,4,12,13,14,15,4,16,17,18,19,4,20,21,22,23],Y3=[3,0,16,8,3,1,9,20,3,2,23,13,3,3,12,19,3,4,17,11,3,5,10,21,3,6,14,22,3,7,18,15],K3=[4,0,1,9,8,4,1,2,23,20,4,2,3,12,13,4,3,0,16,19,4,4,5,10,11,4,5,6,22,21,4,6,7,15,14,4,7,4,17,18,4,8,11,17,16,4,9,20,21,10,4,13,23,22,14,4,12,19,18,15],Kt=.792;function Z3(i,t){t.classHierarchy.push("vtkRhombicuboctahedronSource"),i.requestData=(n,e)=>{const o=e[0]?.initialize()||Vo.newInstance();e[0]=o;let s=1;t.scale!==void 0&&t.scale!==null&&(Array.isArray(t.scale)?s=t.scale[0]||1:typeof t.scale=="number"&&(s=t.scale));const a=1.4,r=[];r.push(-Kt,-Kt,-a),r.push(Kt,-Kt,-a),r.push(Kt,Kt,-a),r.push(-Kt,Kt,-a),r.push(-Kt,-Kt,a),r.push(Kt,-Kt,a),r.push(Kt,Kt,a),r.push(-Kt,Kt,a),r.push(-Kt,-a,-Kt),r.push(Kt,-a,-Kt),r.push(Kt,-a,Kt),r.push(-Kt,-a,Kt),r.push(-Kt,a,-Kt),r.push(Kt,a,-Kt),r.push(Kt,a,Kt),r.push(-Kt,a,Kt),r.push(-a,-Kt,-Kt),r.push(-a,-Kt,Kt),r.push(-a,Kt,Kt),r.push(-a,Kt,-Kt),r.push(a,-Kt,-Kt),r.push(a,-Kt,Kt),r.push(a,Kt,Kt),r.push(a,Kt,-Kt);let c=null;if(t.generate3DTextureCoordinates){c=new Float64Array(72);for(let f=0;f<24;f++){const g=r[f*3],m=r[f*3+1],p=r[f*3+2],v=Math.sqrt(g*g+m*m+p*p)||1;c[f*3]=g/v,c[f*3+1]=m/v,c[f*3+2]=p/v}}for(let f=0;f<r.length;f++)r[f]*=s;const l=Float64Array.from(r);o.getPoints().setData(l,3);const d=new Float64Array(72);for(let f=0;f<24;f++){const g=l[f*3],m=l[f*3+1],p=l[f*3+2],v=Math.sqrt(g*g+m*m+p*p);d[f*3]=g/v,d[f*3+1]=m/v,d[f*3+2]=p/v}const u=_n.newInstance({name:"Normals",values:d,numberOfComponents:3});if(o.getPointData().setNormals(u),c){const f=_n.newInstance({name:"TextureCoordinates",values:c,numberOfComponents:3});o.getPointData().setTCoords(f)}const h=[];if(t.generateMainFaces&&h.push(...q3),t.generateEdgeFaces&&h.push(...K3),t.generateCornerFaces&&h.push(...Y3),h.length>0){const f=la.newInstance({values:Uint16Array.from(h)});o.getPolys().deepCopy(f)}else o.getPolys().initialize();o.modified()}}const J3={scale:1,generate3DTextureCoordinates:!1,generateMainFaces:!0,generateEdgeFaces:!0,generateCornerFaces:!0};function cC(i,t,n={}){Object.assign(t,J3,n),Lt.obj(i,t),Lt.setGet(i,t,["scale","generate3DTextureCoordinates","generateMainFaces","generateEdgeFaces","generateCornerFaces"]),Lt.algo(i,t,0,1),Z3(i,t)}const Q3=Lt.newInstance(cC,"vtkRhombicuboctahedronSource"),vg={newInstance:Q3,extend:cC};function tG(i,t,n){const e=vg.newInstance({generate3DTextureCoordinates:!1,generateMainFaces:!0,generateEdgeFaces:!1,generateCornerFaces:!1,scale:i});e.update();const o=e.getOutputData();if(o){const s=[];for(let r=0;r<6;r++){const c=r%3,l=Math.floor(r/3),d=c/3,u=(c+1)/3,h=l/2,f=(l+1)/2;s.push(d,h),s.push(u,h),s.push(u,f),s.push(d,f)}const a=_n.newInstance({name:"TextureCoordinates",values:new Float32Array(s),numberOfComponents:2});o.getPointData().setTCoords(a),o.modified()}return o}function eG(i,t){const n=vg.newInstance({generate3DTextureCoordinates:!1,generateMainFaces:!1,generateEdgeFaces:!0,generateCornerFaces:!1,scale:i});n.update();const e=n.getOutputData();if(e){const o=[],s=e.getNumberOfCells();for(let r=0;r<s;r++)o.push(t[0],t[1],t[2],255);const a=_n.newInstance({name:"Colors",values:new Uint8Array(o),numberOfComponents:4});e.getCellData().setScalars(a),e.modified()}return e}function nG(i,t){const n=vg.newInstance({generate3DTextureCoordinates:!1,generateMainFaces:!1,generateEdgeFaces:!1,generateCornerFaces:!0,scale:i});n.update();const e=n.getOutputData();if(e){const o=[],s=e.getNumberOfCells();for(let r=0;r<s;r++)o.push(t[0],t[1],t[2],255);const a=_n.newInstance({name:"Colors",values:new Uint8Array(o),numberOfComponents:4});e.getCellData().setScalars(a),e.modified()}return e}function oG(i){const n=document.createElement("canvas");n.width=256*3,n.height=256*2;const e=n.getContext("2d");return i.forEach((o,s)=>{const a=s%3,r=Math.floor(s/3),c=a*256,l=r*256;e.fillStyle=`rgb(${o.faceColor[0]}, ${o.faceColor[1]}, ${o.faceColor[2]})`,e.fillRect(c,l,256,256),o.text&&(e.save(),e.translate(c+256/2,l+256/2),o.flipVertical&&e.scale(1,-1),o.flipHorizontal&&e.scale(-1,1),e.rotate((o.rotation||0)*Math.PI/180),e.fillStyle=`rgb(${o.textColor[0]}, ${o.textColor[1]}, ${o.textColor[2]})`,e.font="bold 180px Arial",e.textAlign="center",e.textBaseline="middle",e.fillText(o.text,0,0),e.restore())}),jS.canvasToImageData(n)}function iG(i,t){t.classHierarchy.push("vtkAnnotatedRhombicuboctahedronActor");function n(){let e=1;t.scale!==void 0&&t.scale!==null&&(Array.isArray(t.scale)?e=t.scale[0]||1:typeof t.scale=="number"&&(e=t.scale));const o=[],s=c=>{const l=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(c);return l?l.slice(1,4).map(d=>parseInt(d,16)):[255,255,255]},a=c=>{if(!c)return[0,0,0];const l=c.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);if(l)return[parseInt(l[1],10),parseInt(l[2],10),parseInt(l[3],10)];if(c.startsWith("#"))return s(c);const d={black:[0,0,0],white:[255,255,255],red:[255,0,0],green:[0,255,0],blue:[0,0,255]};return d[c.toLowerCase()]?d[c.toLowerCase()]:[0,0,0]},r={zMinus:s(t.zMinusFaceProperty.faceColor||t.defaultStyle.faceColor),zPlus:s(t.zPlusFaceProperty.faceColor||t.defaultStyle.faceColor),yMinus:s(t.yMinusFaceProperty.faceColor||t.defaultStyle.faceColor),yPlus:s(t.yPlusFaceProperty.faceColor||t.defaultStyle.faceColor),xMinus:s(t.xMinusFaceProperty.faceColor||t.defaultStyle.faceColor),xPlus:s(t.xPlusFaceProperty.faceColor||t.defaultStyle.faceColor)};if(t.showMainFaces!==!1){const c=[{faceColor:r.zMinus,text:t.zMinusFaceProperty.text||"I",textColor:a(t.zMinusFaceProperty.fontColor||t.defaultStyle.fontColor),rotation:0},{faceColor:r.zPlus,text:t.zPlusFaceProperty.text||"S",textColor:a(t.zPlusFaceProperty.fontColor||t.defaultStyle.fontColor),rotation:0,flipVertical:!0},{faceColor:r.yMinus,text:t.yMinusFaceProperty.text||"A",textColor:a(t.yMinusFaceProperty.fontColor||t.defaultStyle.fontColor),rotation:180},{faceColor:r.yPlus,text:t.yPlusFaceProperty.text||"P",textColor:a(t.yPlusFaceProperty.fontColor||t.defaultStyle.fontColor),rotation:180},{faceColor:r.xMinus,text:t.xMinusFaceProperty.text||"L",textColor:a(t.xMinusFaceProperty.fontColor||t.defaultStyle.fontColor),rotation:90,flipVertical:!0},{faceColor:r.xPlus,text:t.xPlusFaceProperty.text||"R",textColor:a(t.xPlusFaceProperty.fontColor||t.defaultStyle.fontColor),rotation:90}],l=oG(c),d=tG(e);if(d){const u=vo.newInstance(),h=Oo.newInstance();h.setInputData(d),u.setMapper(h);const f=Pv.newInstance();f.setInputData(l),f.setInterpolate(!0),u.addTexture(f);const g=u.getProperty();g.setBackfaceCulling(!1),g.setFrontfaceCulling(!1),g.setLighting(!1),g.setAmbient(1),g.setDiffuse(0),g.setSpecular(0),o.push(u)}}if(t.showEdgeFaces!==!1){const c=t.edgeColor??[200,200,200],l=eG(e,c);if(l){const d=vo.newInstance(),u=Oo.newInstance();u.setInputData(l),u.setScalarModeToUseCellData(),u.setScalarVisibility(!0),u.setColorModeToDirectScalars(),d.setMapper(u);const h=d.getProperty();h.setBackfaceCulling(!1),h.setFrontfaceCulling(!1),h.setLighting(!1),h.setAmbient(1),h.setDiffuse(0),h.setSpecular(0),o.push(d)}}if(t.showCornerFaces!==!1){const c=t.cornerColor??[150,150,150],l=nG(e,c);if(l){const d=vo.newInstance(),u=Oo.newInstance();u.setInputData(l),u.setScalarModeToUseCellData(),u.setScalarVisibility(!0),u.setColorModeToDirectScalars(),d.setMapper(u);const h=d.getProperty();h.setBackfaceCulling(!1),h.setFrontfaceCulling(!1),h.setLighting(!1),h.setAmbient(1),h.setDiffuse(0),h.setSpecular(0),o.push(d)}}return o}i.setDefaultStyle=e=>{t.defaultStyle={...t.defaultStyle,...e}},i.setXPlusFaceProperty=e=>{Object.assign(t.xPlusFaceProperty,e),i.modified()},i.setXMinusFaceProperty=e=>{Object.assign(t.xMinusFaceProperty,e),i.modified()},i.setYPlusFaceProperty=e=>{Object.assign(t.yPlusFaceProperty,e),i.modified()},i.setYMinusFaceProperty=e=>{Object.assign(t.yMinusFaceProperty,e),i.modified()},i.setZPlusFaceProperty=e=>{Object.assign(t.zPlusFaceProperty,e),i.modified()},i.setZMinusFaceProperty=e=>{Object.assign(t.zMinusFaceProperty,e),i.modified()},i.setShowMainFaces=e=>{t.showMainFaces!==e&&(t.showMainFaces=e)},i.setShowEdgeFaces=e=>{t.showEdgeFaces!==e&&(t.showEdgeFaces=e)},i.setShowCornerFaces=e=>{t.showCornerFaces!==e&&(t.showCornerFaces=e)},i.setRhombScale=e=>{t.scale!==e&&(t.scale=e)},i.getActors=()=>n()}const sG={defaultStyle:{text:"",faceColor:"white",faceRotation:0,fontFamily:"Arial",fontColor:"black",fontStyle:"normal",fontSizeScale:i=>i/1.8,edgeThickness:.1,edgeColor:"black",resolution:200},xPlusFaceProperty:{},xMinusFaceProperty:{},yPlusFaceProperty:{},yMinusFaceProperty:{},zPlusFaceProperty:{},zMinusFaceProperty:{},showMainFaces:!0,showEdgeFaces:!0,showCornerFaces:!0,scale:1};function lC(i,t,n={}){Object.assign(t,sG,n),vo.extend(i,t,n),t.xPlusFaceProperty={...t.xPlusFaceProperty},t.xMinusFaceProperty={...t.xMinusFaceProperty},t.yPlusFaceProperty={...t.yPlusFaceProperty},t.yMinusFaceProperty={...t.yMinusFaceProperty},t.zPlusFaceProperty={...t.zPlusFaceProperty},t.zMinusFaceProperty={...t.zMinusFaceProperty},Lt.get(i,t,["defaultStyle","xPlusFaceProperty","xMinusFaceProperty","yPlusFaceProperty","yMinusFaceProperty","zPlusFaceProperty","zMinusFaceProperty","showMainFaces","showEdgeFaces","showCornerFaces","scale"]),iG(i,t)}const aG=Lt.newInstance(lC,"vtkAnnotatedRhombicuboctahedronActor"),rG={newInstance:aG,extend:lC};class cG{constructor(){this.actors=new Map,this.pickers=new Map,this.overlayRenderers=new Map,this.renderWindows=new Map,this.highlightedFace=null,this.mouseHandlers=new Map,this._highlightColor=[255,255,255],this._restingAmbient=1,this._hoverAmbient=1}createActors(t){const n=r=>`#${r.map(c=>{const l=Math.round(c).toString(16);return l.length===1?"0"+l:l}).join("")}`,e=r=>`rgb(${r[0]}, ${r[1]}, ${r[2]})`,o=rG.newInstance({edgeColor:t.edgeColor??[200,200,200],cornerColor:t.cornerColor??[150,150,150]}),s={fontStyle:"bold",fontFamily:"Arial",fontColor:"black",fontSizeScale:r=>r/2,faceColor:n(t.faceColors.topBottom),edgeThickness:.1,edgeColor:"black",resolution:400};o.setDefaultStyle(s),o.setXPlusFaceProperty({text:"L",faceColor:n(t.faceColors.leftRight),fontColor:e(t.letterColors.xPlus),faceRotation:0}),o.setXMinusFaceProperty({text:"R",faceColor:n(t.faceColors.leftRight),fontColor:e(t.letterColors.xMinus),faceRotation:0}),o.setYPlusFaceProperty({text:"P",faceColor:n(t.faceColors.frontBack),fontColor:e(t.letterColors.yPlus),faceRotation:180}),o.setYMinusFaceProperty({text:"A",faceColor:n(t.faceColors.frontBack),fontColor:e(t.letterColors.yMinus),faceRotation:0}),o.setZPlusFaceProperty({text:"S",faceColor:n(t.faceColors.topBottom),fontColor:e(t.letterColors.zPlus)}),o.setZMinusFaceProperty({text:"I",faceColor:n(t.faceColors.topBottom),fontColor:e(t.letterColors.zMinus)}),o.setShowMainFaces(!0),o.setShowEdgeFaces(t.showEdgeFaces),o.setShowCornerFaces(t.showCornerFaces);const a=o.getActors();return this._highlightColor=t.highlightColor??[255,255,255],this._restingAmbient=t.restingAmbient??1,this._hoverAmbient=t.hoverAmbient??1,a.forEach(r=>{const c=r.getProperty();c.setOpacity(t.opacity),c.setAmbient(this._restingAmbient),r.setVisibility(!0)}),a}addActorsToViewport(t,n,e){this.actors.get(t)&&this.removeActorsFromViewport(t,n);const s=n.getRenderingEngine().getOffscreenMultiRenderWindow(n.id).getRenderWindow(),r=n.getRenderingEngine()?.getRenderer(t)??n.getRenderer(),c=xv.newInstance();c.setLayer(1),c.setInteractive(!1),c.setPreserveColorBuffer(!0),c.setActiveCamera(r.getActiveCamera());const l=r.getViewport();c.setViewport(...l),s.getNumberOfLayers()<2&&s.setNumberOfLayers(2),s.addRenderer(c),e.forEach(d=>{c.addActor(d)}),this.actors.set(t,e),this.overlayRenderers.set(t,c),this.renderWindows.set(t,s)}removeActorsFromViewport(t,n){const e=this.actors.get(t),o=this.overlayRenderers.get(t),s=this.renderWindows.get(t);e&&o&&(e.forEach(a=>{o.removeActor(a)}),s&&s.removeRenderer(o),o.delete()),this.actors.delete(t),this.overlayRenderers.delete(t),this.renderWindows.delete(t)}setupPicker(t,n){const e=X3.newInstance({opacityThreshold:1e-4});return e.setPickFromList(!0),e.setTolerance(.001),e.initializePickList(),n.forEach(o=>{e.addPickList(o)}),this.pickers.set(t,e),e}pickAtPosition(t,n,e,o,s){const a=this.pickers.get(n);if(!a)return null;const r=this.overlayRenderers.get(n)??e.getRenderingEngine()?.getRenderer(n)??e.getRenderer();if(!r)return null;const c=o.getBoundingClientRect(),l=t.clientX-c.left,d=t.clientY-c.top,u=window.devicePixelRatio||1,h=[l*u,d*u],f=e.canvas,{width:g,height:m}=f,[p,v,I,w]=r.getViewport(),C=I-p,S=w-v,b=h[0]/g*C*g,_=h[1]/m*S*m,y=[b,S*m-_],D=[y[0],y[1],0];a.pick(D,r);const T=a.getActors();if(T.length===0)return null;const P=T[0],x=a.getCellId();if(s.includes(P)&&x!==-1){const M=s.indexOf(P);return{pickedActor:P,cellId:x,actorIndex:M}}return null}calculateMarkerPosition(t,n,e){const o=t.canvas;if(!o)return null;const s=window.devicePixelRatio||1,a=o.clientWidth||o.width/s,r=o.clientHeight||o.height/s,l=(t.type===so.VOLUME_3D?1.3:1.1)*e,d=e*.5,u=Math.max(0,(a-e)/2),h=Math.max(0,(r-e)/2),f=Math.min(l,u,h);let g,m;switch(n){case"top-left":g=f+d,m=f+d;break;case"top-right":g=a-f-d,m=f+d;break;case"bottom-left":g=f+d,m=r-f-d;break;default:g=a-f-d,m=r-f-d}const p=[g,m],v=t.canvasToWorld(p);return[v[0],v[1],v[2]]}positionActors(t,n,e){const o=t.canvas;if(!o)return console.warn("OrientationControllerWidget: No canvas available"),!1;const a=(t.getRenderingEngine()?.getRenderer(t.id)??t.getRenderer())?.getActiveCamera();if(!a)return!1;const c=a.getParallelScale()*2,l=window.devicePixelRatio||1,d=o.clientHeight||o.height/l,u=o.clientWidth||o.width/l,h=c/d,g=Math.min(u,d)*e.size,m=g*h;return n.forEach(p=>{p.setScale(m,m,m);const v=this.calculateMarkerPosition(t,e.position,g);if(!v){console.warn("OrientationControllerWidget: Could not get world position");return}p.setPosition(v[0],v[1],v[2]),p.setOrientation(0,0,0)}),!0}highlightFace(t,n,e,o=!1){if(this.highlightedFace&&this.highlightedFace.actor===t&&this.highlightedFace.cellId===n&&this.highlightedFace.isMainFace===o)return;if(this.clearHighlight(),o){const f=t.getTextures?.(),m=Array.isArray(f)?f[0]:f?.getItem?.(0),p=m?.getInputData?.(),v=p?.getPointData().getScalars(),I=v?.getData(),w=p?.getDimensions();if(!p||!v||!I||!w||n<0||n>5){const z=t.getMapper().getInputData();if(!z?.getCellPoints)return;const{cellPointIds:q}=z.getCellPoints(n);if(!q||q.length<3)return;const J=z.getPoints().getData(),it=[];Array.from(q).forEach(Ht=>{const Jt=Ht*3;it.push(J[Jt],J[Jt+1],J[Jt+2])});const tt=Ul.newInstance();tt.setData(new Float32Array(it),3);const ot=la.newInstance({values:new Uint32Array([q.length,...Array.from(q,(Ht,Jt)=>Jt)])}),nt=Vo.newInstance();nt.setPoints(tt),nt.setPolys(ot);const lt=Oo.newInstance();lt.setInputData(nt);const rt=vo.newInstance();rt.setMapper(lt);const[ut,Tt,kt]=t.getScale(),[Pt,te,Ie]=t.getPosition(),[re,Zt,ce]=t.getOrientation();rt.setScale(ut,Tt,kt),rt.setPosition(Pt,te,Ie),rt.setOrientation(re,Zt,ce),rt.setPickable(!1);const Ut=rt.getProperty();Ut.setLighting(!1),Ut.setAmbient(1),Ut.setDiffuse(0),Ut.setColor(1,1,1),Ut.setOpacity(.58),this.overlayRenderers.get(e.id)?.addActor(rt),this.highlightedFace={actor:t,cellId:n,originalColor:[0,0,0,0],viewport:e,isMainFace:!0,mainFaceHighlightActor:rt},e.render();return}const[C,S]=w,b=Math.floor(C/3),_=Math.floor(S/2),y=n%3,D=Math.floor(n/3),T=y*b,P=D*_,x=new Uint8Array(b*_*4);let M=0;for(let F=0;F<_;F++)for(let z=0;z<b;z++){const q=((P+F)*C+(T+z))*4;x[M++]=I[q],x[M++]=I[q+1],x[M++]=I[q+2],x[M++]=I[q+3]}const L=[((P+8)*C+(T+8))*4,((P+8)*C+(T+b-9))*4,((P+_-9)*C+(T+8))*4,((P+_-9)*C+(T+b-9))*4],R=[0,0,0];L.forEach(F=>{R[0]+=I[F],R[1]+=I[F+1],R[2]+=I[F+2]}),R[0]/=L.length,R[1]/=L.length,R[2]/=L.length;const U=42,W=72,K=(F,z)=>{if(F<0||F>=b||z<0||z>=_)return!1;const q=((P+z)*C+(T+F))*4,J=I[q]-R[0],it=I[q+1]-R[1],tt=I[q+2]-R[2];return Math.sqrt(J*J+it*it+tt*tt)>=U},j=Math.max(4,Math.floor(b*.035));for(let F=0;F<_;F++)for(let z=0;z<b;z++){if(z<j||z>=b-j||F<j||F>=_-j||K(z,F))continue;const J=((P+F)*C+(T+z))*4;I[J]=Math.min(255,I[J]+W),I[J+1]=Math.min(255,I[J+1]+W),I[J+2]=Math.min(255,I[J+2]+W)}for(let F=0;F<_;F++)for(let z=0;z<b;z++){if(!(z<j||z>=b-j||F<j||F>=_-j))continue;const J=((P+F)*C+(T+z))*4;I[J]=0,I[J+1]=0,I[J+2]=0}v.modified(),p.modified(),m.modified?.(),t.modified?.(),this.highlightedFace={actor:t,cellId:n,originalColor:[0,0,0,0],viewport:e,isMainFace:!0,mainFaceTextureData:x,mainFaceTile:{x0:T,y0:P,width:b,height:_,imageWidth:C}},e.render();return}const a=t.getMapper().getInputData();if(!a)return;const c=a.getCellData().getScalars();if(!c)return;const l=c.getData(),d=n*4,u=[l[d],l[d+1],l[d+2],l[d+3]];this.highlightedFace={actor:t,cellId:n,originalColor:u,viewport:e,isMainFace:!1};const h=this._highlightColor;l[d]=h[0],l[d+1]=h[1],l[d+2]=h[2],l[d+3]=255,c.modified(),a.modified(),e.render()}clearHighlight(){if(!this.highlightedFace)return;const{actor:t,cellId:n,originalColor:e,viewport:o,isMainFace:s}=this.highlightedFace;if(s){const h=this.highlightedFace.mainFaceTextureData,f=this.highlightedFace.mainFaceTile,m=t.getTextures?.()?.[0],p=m?.getInputData?.(),v=p?.getPointData().getScalars(),I=v?.getData();if(h&&f&&v&&p&&I){let w=0;for(let C=0;C<f.height;C++)for(let S=0;S<f.width;S++){const b=((f.y0+C)*f.imageWidth+(f.x0+S))*4;I[b]=h[w++],I[b+1]=h[w++],I[b+2]=h[w++],I[b+3]=h[w++]}v.modified(),p.modified(),m.modified?.(),t.modified?.()}else this.highlightedFace.mainFaceHighlightActor&&(this.overlayRenderers.get(o.id)?.removeActor(this.highlightedFace.mainFaceHighlightActor),this.highlightedFace.mainFaceHighlightActor.delete());o.render(),this.highlightedFace=null;return}const r=t.getMapper().getInputData();if(!r){this.highlightedFace=null;return}const l=r.getCellData().getScalars();if(!l){this.highlightedFace=null;return}const d=l.getData(),u=n*4;d[u]=e[0],d[u+1]=e[1],d[u+2]=e[2],d[u+3]=e[3],l.modified(),r.modified(),o.render(),this.highlightedFace=null}setupMouseHandlers(t,n,e,o,s){let a=!1,r=!1;const c=I=>{o.forEach(w=>{w.getProperty().setAmbient(I?this._hoverAmbient:this._restingAmbient)}),e.render()};let l=!1,d=null,u=null;const h=3,f=I=>{if(a){if(u){const C=I.clientX-u.x,S=I.clientY-u.y;C*C+S*S>h*h&&(l=!0)}return}const w=this.pickAtPosition(I,t,e,n,o);if(w){r||(r=!0,c(!0));const{pickedActor:C,cellId:S,actorIndex:b}=w;this.highlightFace(C,S,e,b===0),s.onFaceHover&&s.onFaceHover(w)}else r&&(r=!1,c(!1)),this.clearHighlight(),s.onFaceHover&&s.onFaceHover(null)},g=I=>{if(I.button!==0)return;const w=this.pickAtPosition(I,t,e,n,o);w&&(a=!0,l=!1,d=w,u={x:I.clientX,y:I.clientY},RV(t,"orientation-controller"))},m=I=>{if(a&&!l&&d){let w=d.cellId;d.actorIndex===1?w=d.cellId+6:d.actorIndex===2&&(w=d.cellId+18),s.onFacePicked({...d,cellId:w}),I.preventDefault(),I.stopImmediatePropagation(),I.stopPropagation()}a=!1,r&&(r=!1,c(!1)),l=!1,d=null,u=null,Dp(t,"orientation-controller"),this.clearHighlight()},p=I=>{this.pickAtPosition(I,t,e,n,o)&&(I.preventDefault(),I.stopImmediatePropagation())};n.addEventListener("mousemove",f,!0),n.addEventListener("mousedown",g,!0),n.addEventListener("mouseup",m),n.addEventListener("mouseleave",m),n.addEventListener("dblclick",p,!0);const v=()=>{n.removeEventListener("mousemove",f,!0),n.removeEventListener("mousedown",g,!0),n.removeEventListener("mouseup",m),n.removeEventListener("mouseleave",m),n.removeEventListener("dblclick",p,!0),Dp(t,"orientation-controller")};return this.mouseHandlers.set(t,{cleanup:v}),{cleanup:v}}getActors(t){return this.actors.get(t)}syncOverlayViewport(t,n){const e=this.overlayRenderers.get(t);if(!e)return;const o=n.getRenderingEngine()?.getRenderer(t)??n.getRenderer();if(!o)return;const s=o.getViewport();e.setViewport(...s)}getOrientationForFace(t){const n=new Map;n.set(0,{viewPlaneNormal:[0,0,-1],viewUp:[0,-1,0]}),n.set(1,{viewPlaneNormal:[0,0,1],viewUp:[0,1,0]}),n.set(2,{viewPlaneNormal:[0,-1,0],viewUp:[0,0,1]}),n.set(3,{viewPlaneNormal:[0,1,0],viewUp:[0,0,1]}),n.set(4,{viewPlaneNormal:[-1,0,0],viewUp:[0,0,1]}),n.set(5,{viewPlaneNormal:[1,0,0],viewUp:[0,0,1]});const e=1/Math.sqrt(2);n.set(6,{viewPlaneNormal:[0,-e,-e],viewUp:[0,-e,e]}),n.set(7,{viewPlaneNormal:[e,0,-e],viewUp:[0,0,1]}),n.set(8,{viewPlaneNormal:[0,e,-e],viewUp:[0,-e,-e]}),n.set(9,{viewPlaneNormal:[-e,0,-e],viewUp:[0,0,1]}),n.set(10,{viewPlaneNormal:[0,-e,e],viewUp:[0,e,e]}),n.set(11,{viewPlaneNormal:[e,0,e],viewUp:[0,0,1]}),n.set(12,{viewPlaneNormal:[0,e,e],viewUp:[0,e,-e]}),n.set(13,{viewPlaneNormal:[-e,0,e],viewUp:[0,0,1]}),n.set(14,{viewPlaneNormal:[-e,-e,0],viewUp:[0,0,1]}),n.set(15,{viewPlaneNormal:[e,-e,0],viewUp:[0,0,1]}),n.set(16,{viewPlaneNormal:[e,e,0],viewUp:[0,0,1]}),n.set(17,{viewPlaneNormal:[-e,e,0],viewUp:[0,0,1]});const o=1/Math.sqrt(3);return n.set(18,{viewPlaneNormal:[-o,-o,-o],viewUp:[0,0,1]}),n.set(19,{viewPlaneNormal:[o,-o,-o],viewUp:[0,0,1]}),n.set(20,{viewPlaneNormal:[o,o,-o],viewUp:[0,0,1]}),n.set(21,{viewPlaneNormal:[-o,o,-o],viewUp:[0,0,1]}),n.set(22,{viewPlaneNormal:[-o,-o,o],viewUp:[0,0,1]}),n.set(23,{viewPlaneNormal:[o,-o,o],viewUp:[0,0,1]}),n.set(24,{viewPlaneNormal:[o,o,o],viewUp:[0,0,1]}),n.set(25,{viewPlaneNormal:[-o,o,o],viewUp:[0,0,1]}),n.get(t)||null}cleanup(t){if(t){const n=this.mouseHandlers.get(t);n&&(n.cleanup(),this.mouseHandlers.delete(t));const e=this.overlayRenderers.get(t),o=this.renderWindows.get(t);e&&(o&&o.removeRenderer(e),e.delete()),this.actors.delete(t),this.pickers.delete(t),this.overlayRenderers.delete(t),this.renderWindows.delete(t)}else this.mouseHandlers.forEach(n=>n.cleanup()),this.mouseHandlers.clear(),this.overlayRenderers.forEach((n,e)=>{const o=this.renderWindows.get(e);o&&o.removeRenderer(n),n.delete()}),this.overlayRenderers.clear(),this.renderWindows.clear(),this.actors.clear(),this.pickers.clear();this.clearHighlight()}}const hv=500,lG=1e3,fv={marker:{topBottom:[0,0,255],frontBack:[0,255,255],leftRight:[255,255,0]},gray:{topBottom:[180,180,180],frontBack:[180,180,180],leftRight:[180,180,180]},rgy:{topBottom:[255,0,0],frontBack:[0,255,0],leftRight:[255,255,0]}},gv={mixed:{zMinus:[255,255,255],zPlus:[255,255,255],yMinus:[255,255,255],yPlus:[255,255,255],xMinus:[0,0,0],xPlus:[0,0,0]},rgy:{zMinus:[255,255,255],zPlus:[255,255,255],yMinus:[255,255,255],yPlus:[255,255,255],xMinus:[0,0,0],xPlus:[0,0,0]},white:{zMinus:[255,255,255],zPlus:[255,255,255],yMinus:[255,255,255],yPlus:[255,255,255],xMinus:[255,255,255],xPlus:[255,255,255]},black:{zMinus:[0,0,0],zPlus:[0,0,0],yMinus:[0,0,0],yPlus:[0,0,0],xMinus:[0,0,0],xPlus:[0,0,0]}},dG="rgy",uG="mixed",hG={resetZoom:!1,resetPan:!0,resetToCenter:!0};class fG extends Ee{constructor(t={},n={supportedInteractionTypes:["Mouse"],configuration:{enabled:!0,opacity:1,size:.04,position:"bottom-right",colorScheme:"rgy",letterColorScheme:"mixed",showEdgeFaces:!0,showCornerFaces:!0,keepOrientationUp:!0,highlightColor:[255,255,255],edgeColor:[200,200,200],cornerColor:[150,150,150],restingAmbient:1,hoverAmbient:1}}){super(t,n),this.widget=new cG,this.resizeObservers=new Map,this.cameraHandlers=new Map,this.animationFrameHandles=new Map,this.animationTokens=new Map,this._getViewportsInfo=()=>Be(this.toolGroupId)?.viewportsInfo||[],this.onSetToolConfiguration=()=>{this._getViewportsInfo().some(({viewportId:s})=>this.widget.getActors(s)!==null)&&(this.removeMarkers(),this.addMarkers())},this.onViewportAdded=e=>{const{viewportId:o,renderingEngineId:s,toolGroupId:a}=e.detail;a===this.toolGroupId&&(this.widget.getActors(o)||setTimeout(()=>{this.addMarkerToViewport(o,s)},hv))},this.onViewportRemoved=e=>{const{viewportId:o,renderingEngineId:s,toolGroupId:a}=e.detail;if(a!==this.toolGroupId)return;const r=ae(o,s);if(r){const{viewport:l}=r;l.isOrientationChangeable()&&this.widget.removeActorsFromViewport(o,l);const d=this.cameraHandlers.get(o);d&&(l.element.removeEventListener(yt.CAMERA_MODIFIED,d),this.cameraHandlers.delete(o))}this.widget.cleanup(o);const c=this.resizeObservers.get(o);c&&(c.disconnect(),this.resizeObservers.delete(o))},this.addMarkers=()=>{this._getViewportsInfo().forEach(({viewportId:o,renderingEngineId:s})=>{const a=ae(o,s);if(!a)return;const{viewport:r}=a;r.isOrientationChangeable()&&(this.widget.getActors(o)||setTimeout(()=>{this.addMarkerToViewport(o,s)},hv))})},this.onCameraModified=e=>{const{viewportId:o}=e.detail;if(!o)return;const s=this.widget.getActors(o);if(!s)return;const r=this._getViewportsInfo().find(u=>u.viewportId===o);if(!r)return;const c=ae(o,r.renderingEngineId);if(!c)return;const{viewport:l}=c;if(!l.isOrientationChangeable())return;const d=l;this.widget.positionActors(d,s,this.getPositionConfig()),this.widget.syncOverlayViewport(o,d),l.render()}}getPositionConfig(){return{position:this.configuration.position||"bottom-right",size:this.configuration.size||.04}}getFaceColors(){const t=this.configuration.colorScheme||"rgy";if(this.configuration.faceColors){const n=this.configuration.faceColors;if(n.topBottom&&n.frontBack&&n.leftRight)return{topBottom:n.topBottom,frontBack:n.frontBack,leftRight:n.leftRight}}return fv[t]??fv[dG]}getLetterColors(){const t=this.configuration.letterColorScheme||"mixed";return gv[t]??gv[uG]}onSetToolEnabled(){this.removeMarkers(),this.addMarkers(),Z.addEventListener(E.TOOLGROUP_VIEWPORT_ADDED,this.onViewportAdded),Z.addEventListener(E.TOOLGROUP_VIEWPORT_REMOVED,this.onViewportRemoved)}onSetToolDisabled(){this.removeMarkers(),Z.removeEventListener(E.TOOLGROUP_VIEWPORT_ADDED,this.onViewportAdded),Z.removeEventListener(E.TOOLGROUP_VIEWPORT_REMOVED,this.onViewportRemoved)}removeMarkers(){this._getViewportsInfo().forEach(({viewportId:n,renderingEngineId:e})=>{const o=ae(n,e);if(o){const{viewport:a}=o;a.isOrientationChangeable()&&this.widget.removeActorsFromViewport(n,a);const r=this.cameraHandlers.get(n);r&&(a.element.removeEventListener(yt.CAMERA_MODIFIED,r),this.cameraHandlers.delete(n))}const s=this.resizeObservers.get(n);s&&(s.disconnect(),this.resizeObservers.delete(n))}),this.widget.cleanup(),this.resizeObservers.forEach(n=>n.disconnect()),this.resizeObservers.clear(),this.cameraHandlers.clear(),this.animationFrameHandles.forEach(n=>cancelAnimationFrame(n)),this.animationFrameHandles.clear(),this.animationTokens.clear()}createAnnotatedRhombActor(){const t=this.getFaceColors(),n=this.getLetterColors();return this.widget.createActors({faceColors:t,letterColors:n,opacity:this.configuration.opacity??1,showEdgeFaces:this.configuration.showEdgeFaces!==!1,showCornerFaces:this.configuration.showCornerFaces!==!1,highlightColor:this.configuration.highlightColor??[255,255,255],edgeColor:this.configuration.edgeColor??[200,200,200],cornerColor:this.configuration.cornerColor??[150,150,150],restingAmbient:this.configuration.restingAmbient??1,hoverAmbient:this.configuration.hoverAmbient??1})}addMarkerToViewport(t,n){if(this.widget.getActors(t))return;const e=ae(t,n);if(!e){console.warn("OrientationControllerTool: No enabled element found");return}const{viewport:o}=e;if(!o.isOrientationChangeable()){console.warn("OrientationControllerTool: Viewport does not support orientation changes");return}const s=o.element,a=o,r=this.createAnnotatedRhombActor();this.widget.addActorsToViewport(t,a,r),this.widget.positionActors(a,r,this.getPositionConfig())?o.render():(console.warn("OrientationControllerTool: Initial positioning failed, retrying..."),setTimeout(()=>{this.widget.positionActors(a,r,this.getPositionConfig())?o.render():console.error("OrientationControllerTool: Retry positioning also failed")},lG)),this.widget.syncOverlayViewport(t,a),this.widget.setupPicker(t,r),this.widget.setupMouseHandlers(t,s,a,r,{onFacePicked:u=>{const h=this.widget.getOrientationForFace(u.cellId);h&&this.animateCameraToOrientation(a,h.viewPlaneNormal,h.viewUp)},onFaceHover:u=>{u?this.widget.highlightFace(u.pickedActor,u.cellId,a,u.actorIndex===0):this.widget.clearHighlight()}});const l=new ResizeObserver(()=>{this.updateMarkerPosition(t,n)});l.observe(s),this.resizeObservers.set(t,l);const d=u=>{u.detail.viewportId===t&&this.onCameraModified(u)};s.addEventListener(yt.CAMERA_MODIFIED,d),this.cameraHandlers.set(t,d)}updateMarkerPosition(t,n){const e=ae(t,n);if(!e)return;const o=this.widget.getActors(t);if(!o)return;const{viewport:s}=e;s.isOrientationChangeable()&&(this.widget.positionActors(s,o,this.getPositionConfig()),this.widget.syncOverlayViewport(t,s),s.render())}animateCameraToOrientation(t,n,e){const o=t.id,s=this.animationFrameHandles.get(o);s!==void 0&&(cancelAnimationFrame(s),this.animationFrameHandles.delete(o));const a=(this.animationTokens.get(o)??0)+1;this.animationTokens.set(o,a);const r=this.configuration.keepOrientationUp!==!1,l=t.getRenderer().getActiveCamera(),d=l.getDirectionOfProjection(),u=l.getViewUp(),h=Ot(-d[0],-d[1],-d[2]),f=Ot(u[0],u[1],u[2]),g=B();Me(g,f,h),Wt(g,g);const m=Bu(g[0],g[1],g[2],0,f[0],f[1],f[2],0,h[0],h[1],h[2],0,0,0,0,1),p=Wt(B(),n);let v;if(r)v=Ot(e[0],e[1],e[2]);else{const R=Wt(B(),h),U=as();ly(U,R,p),v=B(),Rv(v,f,U),Wt(v,v)}const I=xt(v,p);if(ee(v,v,p,-I),mn(v)<1e-4){v=ho(f);const R=xt(v,p);ee(v,v,p,-R)}Wt(v,v);const w=B();Me(w,v,p),Wt(w,w),Me(v,p,w),Wt(v,v);const C=Bu(w[0],w[1],w[2],0,v[0],v[1],v[2],0,p[0],p[1],p[2],0,0,0,0,1),S=Zg(as(),m),b=Zg(as(),C);let _=cy(S,b);if(_<0&&(ry(b,b,-1),_=-_),_>.99996)return;const D=150,T=performance.now(),P=[p[0],p[1],p[2]],x=[v[0],v[1],v[2]],M=R=>{if(this.animationTokens.get(o)!==a)return;const U=R-T,W=Math.min(1,U/D),K=W>=1,j=W<.5?2*W*W:1-Math.pow(-2*W+2,2)/2,F=as();$c(F,S,b,j);const z=qi();ty(z,F);const q=z.slice(8,11),J=z.slice(4,7);if(Td(t,{viewPlaneNormal:K?P:q,viewUp:K?x:J}),Md(t,hG),t.render(),K)this.animationFrameHandles.delete(o);else{const it=requestAnimationFrame(M);this.animationFrameHandles.set(o,it)}},L=requestAnimationFrame(M);this.animationFrameHandles.set(o,L)}}fG.toolName="OrientationControllerTool";class $r extends Ee{constructor(t={},n={supportedInteractionTypes:["Mouse"],configuration:{hoverTimeout:100,mode:$r.SelectMode.Border,searchRadius:6}}){super(t,n),this.mouseMoveCallback=e=>{if(this.mode===se.Active)return this.hoverTimer&&clearTimeout(this.hoverTimer),this.hoverTimer=setTimeout(()=>{this._setActiveSegment(e),this.hoverTimer=null},this.configuration.hoverTimeout),!0},this.onSetToolEnabled=()=>{this.onSetToolActive()},this.onSetToolActive=()=>{this.hoverTimer=null},this.onSetToolDisabled=()=>{this.hoverTimer=null},this.hoverTimer=null}_setActiveSegment(t={}){if($.isInteractingWithTool)return;const{element:n,currentPoints:e}=t.detail,o=e.world,s=N(n);if(!s)return;const{viewport:a}=s,r=ni(a.id);r&&this._setActiveSegmentForType(r,o,a)}_setActiveSegmentForType(t,n,e){if(!e.getImageData())return;const{segmentationId:s,representationData:a}=t;let r;if(this.configuration.mode===$r.SelectMode.Inside?r=Xf(s,n,{viewport:e}):a.Labelmap?r=ME(s,n,{viewport:e,searchRadius:this.configuration.searchRadius}):a.Contour?r=LE(s):a.Surface,!r||r===0)return;Or(s,r);const l=e.getRenderingEngine().getViewports().map(d=>d.id);Co(s),V(l)}}$r.SelectMode={Inside:"Inside",Border:"Border"};$r.toolName="SegmentSelectTool";var Ch;class Ig extends fc{constructor(t={}){super(t),this.renderAnnotation=(n,e)=>{let o=!0;const{viewport:s}=n,{element:a}=s,r=s.id;let c=Yt(this.getToolName(),a);if(!c?.length||(c=this.filterInteractableAnnotationsForElement(a,c),!c?.length))return o;const l=this.getTargetId(s),d=s.getRenderingEngine(),u={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let h=0;h<c.length;h++){const f=c[h],{annotationUID:g,data:m}=f,{points:p,activeHandleIndex:v}=m.handles,I=p.map(U=>s.worldToCanvas(U));u.annotationUID=g;const{segmentIndex:w,segmentationId:C}=f.metadata,{lineWidth:S,lineDash:b,shadow:_}=this.getAnnotationStyle({annotation:f,styleSpecifier:u}),D=`rgb(${Jo(r,C,w).slice(0,3).join(",")})`;if(!m.cachedStats[l]||m.cachedStats[l].unit==null?(m.cachedStats[l]={length:null,width:null,unit:null},this._calculateCachedStats(f,d,n)):f.invalidated&&this._throttledCalculateCachedStats(f,d,n),!s.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;let T;if(!$e(g))continue;!ze(g)&&!this.editData&&v!==null&&(T=[I[v]]),T&&xe(e,g,"0",T,{color:D});const P=`${g}-line-1`,x=`${g}-line-2`;qt(e,g,"0",I[0],I[1],{color:D,lineWidth:S,lineDash:b,shadow:_},P),qt(e,g,"1",I[2],I[3],{color:D,lineWidth:S,lineDash:b,shadow:_},x),o=!0;const R=this.configuration.getTextLines(m,l);!R||R.length===0||this.renderLinkedTextBoxAnnotation({enabledElement:n,svgDrawingHelper:e,annotation:f,styleSpecifier:u,textLines:R,canvasCoordinates:I})}return o}}addNewAnnotation(t){const n=t.detail,{currentPoints:e,element:o}=n,s=e.world,a=N(o),{viewport:r}=a;this.isDrawing=!0;const c=ht(r),{viewPlaneNormal:l,viewUp:d}=c,u=this.getReferencedImageId(r,s,l,d),h=r.getFrameOfReferenceUID(),f={highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...l],viewUp:[...d],FrameOfReferenceUID:h,referencedImageId:u,...r.getViewReference({points:[s]})},data:{handles:{points:[[...s],[...s],[...s],[...s]],textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}},activeHandleIndex:null},label:"",cachedStats:{}}};Nt(f,o);const g=ft(o,this.getToolName());return this.editData={annotation:f,viewportIdsToRender:g,handleIndex:1,movingTextBox:!1,newAnnotation:!0,hasMoved:!1},this._activateDraw(o),wt(o),t.preventDefault(),V(g),f}}Ch=Ig;Ig.toolName="SegmentBidirectional";Ig.hydrate=(i,t,n)=>{const e=le(i);if(!e)return;const{viewport:o}=e,r=Ca().filter(b=>b.metadata.toolName==="SegmentBidirectional").find(b=>{const{metadata:_}=b;return _.segmentIndex===n?.segmentIndex&&_.segmentationId===n?.segmentationId});r&&Gt(r.annotationUID);const{FrameOfReferenceUID:c,referencedImageId:l,viewPlaneNormal:d,instance:u}=Ch.hydrateBase(Ch,e,t[0],n),[h,f]=t,[g,m]=h,[p,v]=f,I=[g,m,p,v],{toolInstance:w,...C}=n||{},S={annotationUID:n?.annotationUID||Se(),data:{handles:{points:I,activeHandleIndex:null,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}},cachedStats:{}},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{segmentIndex:n?.segmentIndex,segmentationId:n?.segmentationId,toolName:u.getToolName(),viewPlaneNormal:d,FrameOfReferenceUID:c,referencedImageId:l,...C}};return Nt(S,o.element),V([o.id]),S};class gG extends Ee{constructor(t={data:{handles:{textBox:{worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}}}},n={supportedInteractionTypes:["Mouse"],configuration:{hoverTimeout:100,searchRadius:6,color:null,background:null}}){super(t,n),this.mouseMoveCallback=e=>(this.hoverTimer&&clearTimeout(this.hoverTimer),this.hoverTimer=setTimeout(()=>{this._setHoveredSegment(e),this.hoverTimer=null},this.configuration.hoverTimeout),!0),this.onSetToolEnabled=()=>{this.onSetToolActive()},this.onSetToolActive=()=>{this.hoverTimer=null},this.onSetToolDisabled=()=>{this.hoverTimer=null},this.data=t.data??{handles:{textBox:{worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}}},this.hoverTimer=null}_setHoveredSegment(t={}){if($.isInteractingWithTool)return;const{element:n,currentPoints:e}=t.detail,o=e.world,s=N(n);if(!s)return;const{viewport:a}=s,r=ni(a.id);r&&this._setHoveredSegmentForType(r,o,a)}_setHoveredSegmentForType(t,n,e){if(!e.getImageData())return;const{segmentationId:s}=t,a=Xf(s,n,{viewport:e}),r=t.segments[a],c=this.configuration.color??Jo(e.id,s,a),l=r?.label,d=e.worldToCanvas(n);if(this._editData={hoveredSegmentIndex:a,hoveredSegmentLabel:l,canvasCoordinates:d,color:c},!a||a===0)return;const h=e.getRenderingEngine().getViewports().map(f=>f.id);Co(s),V(h)}renderAnnotation(t,n){if(!this._editData)return;const{viewport:e}=t,{hoveredSegmentIndex:o,hoveredSegmentLabel:s,canvasCoordinates:a,color:r}=this._editData;if(!o)return;const c=-15,l=[a[0]+c,a[1]+c],d=Ko(n,"segmentSelectLabelAnnotation","segmentSelectLabelTextBox",[s??"(unnamed segment)"],l,{color:`rgba(${r[0]}, ${r[1]}, ${r[2]}, ${r[3]})`,background:this.configuration.background??void 0}),u=a[0],h=a[1],{width:f,height:g}=d;this.data.handles.textBox.worldBoundingBox={topLeft:e.canvasToWorld([u,h]),topRight:e.canvasToWorld([u+f,h]),bottomLeft:e.canvasToWorld([u,h+g]),bottomRight:e.canvasToWorld([u+f,h+g])}}}gG.toolName="SegmentLabelTool";class Vn extends cc{constructor(t={}){const n=Hn({configuration:{calculateStats:!1,allowOpenContours:!1}},t);super(n),this.onViewportAddedToToolGroupBinded=this.onViewportAddedToToolGroup.bind(this),this.onSegmentationModifiedBinded=this.onSegmentationModified.bind(this)}initializeListeners(){Vn.annotationsToViewportMap.clear(),Vn.viewportIdsChecked=[],Z.addEventListener(E.ANNOTATION_MODIFIED,this.annotationModified),Z.addEventListener(E.ANNOTATION_COMPLETED,this.annotationCompleted),Z.addEventListener(E.TOOLGROUP_VIEWPORT_ADDED,this.onViewportAddedToToolGroupBinded),Z.addEventListener(E.SEGMENTATION_MODIFIED,this.onSegmentationModifiedBinded),Z.addEventListener(E.SEGMENTATION_REPRESENTATION_MODIFIED,this.onSegmentationModifiedBinded)}cleanUpListeners(){Vn.annotationsToViewportMap.clear(),Vn.viewportIdsChecked=[],Z.removeEventListener(E.ANNOTATION_MODIFIED,this.annotationModified),Z.removeEventListener(E.ANNOTATION_COMPLETED,this.annotationCompleted),Z.removeEventListener(E.TOOLGROUP_VIEWPORT_ADDED,this.onViewportAddedToToolGroup.bind(this)),Z.removeEventListener(E.SEGMENTATION_MODIFIED,this.onSegmentationModified.bind(this)),Z.removeEventListener(E.SEGMENTATION_REPRESENTATION_MODIFIED,this.onSegmentationModified.bind(this))}async checkContourSegmentation(t){if(Vn.viewportIdsChecked.includes(t))return;const n=Wi(t);if(!n)return console.log("No active segmentation detected"),!1;const e=n.segmentationId;return n.representationData.Contour?Vn.viewportIdsChecked.push(t):(Vn.viewportIdsChecked.push(t),await Yf(t,[{segmentationId:e,type:St.Contour}]),Hf({segmentationId:e,type:St.Contour,data:{}})),!0}onViewportAddedToToolGroup(t){const{toolGroupId:n,viewportId:e}=t.detail;n===this.toolGroupId&&this.checkContourSegmentation(e)}onSegmentationModified(t){const{segmentationId:n}=t.detail||{};if(!n)return;const e=XI(n);e&&e.forEach(async({viewportId:o})=>await this.checkContourSegmentation(o))}onSetToolEnabled(){this.initializeListeners()}onSetToolActive(){this.initializeListeners()}onSetToolDisabled(){this.cleanUpListeners()}annotationModified(t){const{annotation:n,renderingEngineId:e,viewportId:o}=t.detail,s=Ne(e)?.getViewport(o);s&&Vn.annotationsToViewportMap.set(n.annotationUID,s)}annotationCompleted(t){const{annotation:n}=t.detail,{polyline:e}=n.data?.contour||{};if(n?.metadata?.toolName===Vn.toolName&&e&&Vn.annotationsToViewportMap.has(n.annotationUID)){const o=Vn.annotationsToViewportMap.get(n.annotationUID);e.length>3&&fs.viewportContoursToLabelmap(o)}}}Vn.toolName="LabelMapEditWithContour";Vn.annotationsToViewportMap=new Map;Vn.viewportIdsChecked=[];class mG extends be{constructor(t={}){super(t,{supportedInteractionTypes:["Mouse","Touch"],configuration:{shadow:!0,preventHandleOutsideImage:!1}}),this.addNewAnnotation=n=>{const e=n.detail,{currentPoints:o,element:s}=e,a=o.world,r=N(s),{viewport:c}=r;this.isDrawing=!0;const l=this.constructor.createAnnotationForViewport(c,{data:{handles:{points:[[...a],[...a],[...a],[...a]]}}});Nt(l,s);const d=ft(s,this.getToolName(),!1);return this.editData={annotation:l,viewportUIDsToRender:d,handleIndex:3,newAnnotation:!0,hasMoved:!1},this._activateDraw(s),wt(s),n.preventDefault(),V(d),l},this.getHandleNearImagePoint=(n,e,o,s)=>{const a=N(n),{viewport:r}=a,{data:c}=e,{points:l}=c.handles;for(let d=0;d<l.length;d++){const u=l[d],h=r.worldToCanvas(u);if(_e(o,h)<s===!0)return c.handles.activeHandleIndex=d,u}c.handles.activeHandleIndex=null},this.isPointNearTool=(n,e,o,s)=>{const a=N(n),{viewport:r}=a,{data:c}=e,{points:l}=c.handles,d=r.worldToCanvas(l[0]),u=r.worldToCanvas(l[3]),h=this._getRectangleImageCoordinates([d,u]),f=[o[0],o[1]],{left:g,top:m,width:p,height:v}=h;if(ef([g,m,p,v],f)<=s)return!0},this.toolSelectedCallback=(n,e,o="mouse")=>{const s=n.detail,{element:a}=s,{data:r}=e;r.active=!0;const c=ft(a,this.getToolName(),!1);this.editData={annotation:e,viewportUIDsToRender:c},this._activateModify(a),wt(a),V(c),n.preventDefault()},this.handleSelectedCallback=(n,e,o,s="mouse")=>{const a=n.detail,{element:r}=a,{data:c}=e;c.active=!0;let l;o.worldPosition||(l=c.handles.points.findIndex(u=>u===o));const d=ft(r,this.getToolName(),!1);this.editData={annotation:e,viewportUIDsToRender:d,handleIndex:l},this._activateModify(r),wt(r),V(d),n.preventDefault()},this._endCallback=n=>{const e=n.detail,{element:o}=e,{annotation:s,viewportUIDsToRender:a,newAnnotation:r,hasMoved:c}=this.editData,{data:l}=s;r&&!c||(this.doneEditMemo(),l.active=!1,l.handles.activeHandleIndex=null,this._deactivateModify(o),this._deactivateDraw(o),Ft(o),this.editData=null,this.isDrawing=!1,this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&Gt(s.annotationUID),V(a))},this._dragCallback=n=>{this.isDrawing=!0;const e=n.detail,{element:o}=e,{annotation:s,viewportUIDsToRender:a,handleIndex:r,newAnnotation:c}=this.editData;this.createMemo(o,s,{newAnnotation:c});const{data:l}=s;if(r===void 0){const{deltaPoints:d}=e,u=d.world,{points:h}=l.handles;h.forEach(f=>{f[0]+=u[0],f[1]+=u[1],f[2]+=u[2]}),l.invalidated=!0}else{const{currentPoints:d}=e,u=N(o),{worldToCanvas:h,canvasToWorld:f}=u.viewport,g=d.world,{points:m}=l.handles;m[r]=[...g];let p,v,I,w,C,S,b,_;switch(r){case 0:case 3:p=h(m[0]),w=h(m[3]),v=[w[0],p[1]],I=[p[0],w[1]],S=f(v),b=f(I),m[1]=S,m[2]=b;break;case 1:case 2:v=h(m[1]),I=h(m[2]),p=[I[0],v[1]],w=[v[0],I[1]],C=f(p),_=f(w),m[0]=C,m[3]=_;break}l.invalidated=!0}this.editData.hasMoved=!0,N(o),V(a)},this._activateDraw=n=>{$.isInteractingWithTool=!0,n.addEventListener(E.MOUSE_UP,this._endCallback),n.addEventListener(E.MOUSE_DRAG,this._dragCallback),n.addEventListener(E.MOUSE_MOVE,this._dragCallback),n.addEventListener(E.MOUSE_CLICK,this._endCallback),n.addEventListener(E.TOUCH_END,this._endCallback),n.addEventListener(E.TOUCH_DRAG,this._dragCallback)},this._deactivateDraw=n=>{$.isInteractingWithTool=!1,n.removeEventListener(E.MOUSE_UP,this._endCallback),n.removeEventListener(E.MOUSE_DRAG,this._dragCallback),n.removeEventListener(E.MOUSE_MOVE,this._dragCallback),n.removeEventListener(E.MOUSE_CLICK,this._endCallback),n.removeEventListener(E.TOUCH_END,this._endCallback),n.removeEventListener(E.TOUCH_DRAG,this._dragCallback)},this._activateModify=n=>{$.isInteractingWithTool=!0,n.addEventListener(E.MOUSE_UP,this._endCallback),n.addEventListener(E.MOUSE_DRAG,this._dragCallback),n.addEventListener(E.MOUSE_CLICK,this._endCallback),n.addEventListener(E.TOUCH_END,this._endCallback),n.addEventListener(E.TOUCH_DRAG,this._dragCallback)},this._deactivateModify=n=>{$.isInteractingWithTool=!1,n.removeEventListener(E.MOUSE_UP,this._endCallback),n.removeEventListener(E.MOUSE_DRAG,this._dragCallback),n.removeEventListener(E.MOUSE_CLICK,this._endCallback),n.removeEventListener(E.TOUCH_END,this._endCallback),n.removeEventListener(E.TOUCH_DRAG,this._dragCallback)},this.renderAnnotation=(n,e)=>{const{viewport:s}=n,{element:a}=s;let r=Yt(this.getToolName(),a);if(!r?.length||(r=this.filterInteractableAnnotationsForElement(a,r),!r?.length))return!1;const c={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let l=0;l<r.length;l++){const d=r[l],{annotationUID:u}=d,h=d.data,{points:f,activeHandleIndex:g}=h.handles,m=f.map(S=>s.worldToCanvas(S)),p=this.getStyle("lineWidth",c,d),v=this.getStyle("lineDash",c,d),I=this.getStyle("color",c,d);if(!s.getRenderingEngine()){console.warn("Rendering Engine has been destroyed");return}let w;!this.editData&&g!==null&&(w=[m[g]]),w&&xe(e,u,"0",w,{color:I}),m0(e,u,"0",m[0],m[3],{color:"black",lineDash:v,lineWidth:p})}},this._getRectangleImageCoordinates=n=>{const[e,o]=n;return{left:Math.min(e[0],o[0]),top:Math.min(e[1],o[1]),width:Math.abs(e[0]-o[0]),height:Math.abs(e[1]-o[1])}},this._calculateCachedStats=(n,e,o,s,a)=>{const{data:r}=n,{viewportUID:c,renderingEngineUID:l,sceneUID:d}=a,u=r.handles.points[0],h=r.handles.points[3],{cachedStats:f}=r,g=Object.keys(f);for(let p=0;p<g.length;p++){const v=g[p],{imageVolume:I}=this._getImageVolumeFromTargetUID(v,s),{dimensions:w,scalarData:C,vtkImageData:S,metadata:b}=I,_=Ot(0,0,0),y=Ot(0,0,0);if(S.worldToIndexVec3(u,_),_[0]=Math.floor(_[0]),_[1]=Math.floor(_[1]),_[2]=Math.floor(_[2]),S.worldToIndexVec3(h,y),y[0]=Math.floor(y[0]),y[1]=Math.floor(y[1]),y[2]=Math.floor(y[2]),this._isInsideVolume(_,y,w)){this.isHandleOutsideImage=!1;const D=Math.min(_[0],y[0]),T=Math.max(_[0],y[0]),P=Math.min(_[1],y[1]),x=Math.max(_[1],y[1]),M=Math.min(_[2],y[2]),L=Math.max(_[2],y[2]),{worldWidth:R,worldHeight:U}=ec(e,o,u,h),W=R*U;let K=0,j=0,F=0;const z=w[0],q=w[0]*w[1];for(let J=M;J<=L;J++)for(let it=P;it<=x;it++)for(let tt=D;tt<=T;tt++){const ot=C[J*q+it*z+tt];K++,j+=ot}j/=K;for(let J=M;J<=L;J++)for(let it=P;it<=x;it++)for(let tt=D;tt<=T;tt++){const nt=C[J*q+it*z+tt]-j;F+=nt*nt}F/=K,F=Math.sqrt(F),f[v]={Modality:b.Modality,area:W,mean:j,stdDev:F}}else this.isHandleOutsideImage=!0,f[v]={Modality:b.Modality}}const m=n.invalidated;if(n.invalidated=!1,m){const p=E.ANNOTATION_MODIFIED,v={annotation:n,viewportUID:c,renderingEngineUID:l,sceneUID:d,changeType:Bt.StatsUpdated};Rt(Z,p,v)}return f},this._isInsideVolume=(n,e,o)=>gn(n,o)&&gn(e,o),this._getTargetVolumeUID=n=>{if(this.configuration.volumeUID)return this.configuration.volumeUID;const e=n.getVolumeActors();if(!(!e&&!e.length))return e[0].uid},this._throttledCalculateCachedStats=Un(this._calculateCachedStats,100,{trailing:!0})}cancel(t){if(!this.isDrawing)return;this.isDrawing=!1,this._deactivateDraw(t),this._deactivateModify(t),Ft(t);const{annotation:n,viewportUIDsToRender:e}=this.editData,{data:o}=n;return o.active=!1,o.handles.activeHandleIndex=null,V(e),this.editData=null,n.annotationUID}_getImageVolumeFromTargetUID(t,n){let e,o;if(t.startsWith("stackTarget")){const s=t.indexOf(":"),a=t.substring(s+1);e=n.getViewport(a).getImageData()}else e=Q.getVolume(t);return{imageVolume:e,viewport:o}}_getTargetStackUID(t){return`stackTarget:${t.uid}`}}mG.toolName="VideoRedaction";export{wa as AdvancedMagnifyTool,fg as AngleTool,Ci as AnnotationDisplayTool,be as AnnotationTool,hg as ArrowAnnotateTool,Ee as BaseTool,fc as BidirectionalTool,fs as BrushTool,UH as CONSTANTS,qF as CircleROIStartEndThresholdTool,ji as CircleROITool,jF as CircleScissorsTool,mg as ClickSegmentTool,$5 as CobbAngleTool,bS as CrosshairsTool,D5 as DragProbeTool,L5 as ETDRSGridTool,ug as EllipticalROITool,CG as Enums,tF as EraserTool,_5 as HeightTool,gg as KeyImageTool,Vn as LabelMapEditWithContourTool,Ad as LabelTool,$i as LabelmapBaseTool,dg as LengthTool,NS as LivewireContourSegmentationTool,Ld as LivewireContourTool,XV as MIPJumpToClickTool,i5 as MagnifyTool,fG as OrientationControllerTool,Xo as OrientationMarkerTool,d5 as OverlayGridTool,KF as PaintFillTool,mV as PanTool,cc as PlanarFreehandContourSegmentationTool,Tr as PlanarFreehandROITool,zV as PlanarRotateTool,mc as ProbeTool,oE as RectangleROIStartEndThresholdTool,iE as RectangleROIThresholdTool,hc as RectangleROITool,zF as RectangleScissorsTool,g5 as ReferenceCursors,l5 as ReferenceLinesTool,oF as RegionSegmentPlusTool,nF as RegionSegmentTool,m5 as ScaleOverlayTool,v5 as SculptorTool,Ig as SegmentBidirectionalTool,gG as SegmentLabelTool,$r as SegmentSelectTool,u5 as SegmentationIntersectionTool,PS as SliceIntersectionTool,XF as SphereScissorsTool,k5 as SplineContourSegmentationTool,ka as SplineROITool,BV as StackScrollTool,A1 as Synchronizer,eO as SynchronizerManager,t_ as ToolGroupManager,wV as TrackballRotateTool,WH as Types,X5 as UltrasoundDirectionalTool,Od as UltrasoundPleuraBLineTool,mG as VideoRedactionTool,UV as VolumeCroppingControlTool,kV as VolumeCroppingTool,E5 as VolumeRotateTool,HF as WholeBodySegmentTool,WV as WindowLevelRegionTool,FV as WindowLevelTool,xS as WorldCrosshairTool,$V as ZoomTool,Xv as addTool,OH as annotation,YL as cancelActiveManipulations,bG as cursors,kH as destroy,_G as drawing,NH as init,A0 as measurementTargetFilters,r_ as removeTool,BH as segmentation,zH as splines,$ as state,RH as store,GH as synchronizers,HH as utilities,VH as version};
|