/usr/share/grafana/public/build
(()=>{var gl={14699:(ae,pt,Ct)=>{var ot=Ct(79002),O=function(){return new At};for(var C in ot){O[C+"Raw"]=function(R){return function(V){return typeof V=="number"&&(V=Array.prototype.slice.call(arguments)),ot[R](V)}}(C);var f=/(\w+)2(\w+)/.exec(C),k=f[1],vt=f[2];O[k]=O[k]||{},O[k][vt]=O[C]=function(R){return function(V){typeof V=="number"&&(V=Array.prototype.slice.call(arguments));var J=ot[R](V);if(typeof J=="string"||J===void 0)return J;for(var et=0;et<J.length;et++)J[et]=Math.round(J[et]);return J}}(C)}var At=function(){this.convs={}};At.prototype.routeSpace=function(R,V){var J=V[0];return J===void 0?this.getValues(R):(typeof J=="number"&&(J=Array.prototype.slice.call(V)),this.setValues(R,J))},At.prototype.setValues=function(R,V){return this.space=R,this.convs={},this.convs[R]=V,this},At.prototype.getValues=function(R){var V=this.convs[R];if(!V){var J=this.space,et=this.convs[J];V=O[J][R](et),this.convs[R]=V}return V},["rgb","hsl","hsv","cmyk","keyword"].forEach(function(R){At.prototype[R]=function(V){return this.routeSpace(R,arguments)}}),ae.exports=O},38846:(ae,pt)=>{"use strict";var Ct;Ct={value:!0},pt.fe=pt.Qf=Ct=Ct=Ct=Ct=void 0;const ot=`\r `;function O(At){return k.isNullOrWhiteSpace(At)}function C(At,...R){return k.join(At,...R)}function f(At,...R){return k.format(At,...R)}Ct="",Ct=O,Ct=C,Ct=f;class k{static regexNumber=/{(\d+(:\w*)?)}/g;static regexObject=/{(\w+(:\w*)?)}/g;static empty="";static Empty="";static IsNullOrWhiteSpace(R){return k.isNullOrWhiteSpace(R)}static Join(R,...V){return k.join(R,...V)}static Format(R,...V){return k.format(R,...V)}static isNullOrWhiteSpace(R){try{return R==null||R=="undefined"?!0:R.toString().replace(/\s/g,"").length<1}catch(V){return console.log(V),!1}}static join(R,...V){try{var J=V[0];if(Array.isArray(J)||J instanceof Array){let _=k.empty;for(let c=0;c<J.length;c++){var et=J[c];c<J.length-1?_+=et+R:_+=et}return _}if(typeof J=="object"){let _=k.empty;const c=J;return Object.keys(J).forEach(zt=>{_+=c[zt]+R}),_=_.slice(0,_.length-R.length)}var D=V;return k.joinString(R,...D)}catch(_){return console.log(_),k.empty}}static format(R,...V){try{return R.match(k.regexNumber)?k.formatString(k.regexNumber,R,V):R.match(k.regexObject)?k.formatString(k.regexObject,R,V,!0):R}catch(J){return console.log(J),k.empty}}static formatString(R,V,J,et=!1){return V.replace(R,function(D,_){var c=D.split(":");1<c.length&&(_=c[0].replace("{",""),D=c[1].replace("}",""));let zt;return(zt=(et?J[0]:J)[_])==null||zt==null||D.match(/{\d+}/)||(zt=k.parsePattern(D,zt))!==void 0&&zt!=null?zt:k.empty})}static parsePattern(R,V){switch(R){case"L":return V=V.toLocaleLowerCase();case"U":return V=V.toLocaleUpperCase();case"d":if(typeof V=="string")return k.getDisplayDateFromString(V);if(V instanceof Date)return k.format("{0:00}.{1:00}.{2:0000}",V.getDate(),V.getMonth(),V.getFullYear());break;case"s":if(typeof V=="string")return k.getSortableDateFromString(V);if(V instanceof Date)return k.format("{0:0000}-{1:00}-{2:00}",V.getFullYear(),V.getMonth(),V.getDate());break;case"n":{var D=(V=typeof V!="string"?V.toString():V).replace(/,/g,".");if(isNaN(parseFloat(D))||D.length<=3)break;D=D.split(/\D+/g);let _=D;var D=(_=1<D.length?[k.joinString("",...D.splice(0,D.length-1)),D[D.length-1]]:_)[0],J=D.length%3,et=0<J?D.substring(0,J):k.empty,D=D.substring(J).match(/.{3}/g);return V=et+"."+k.join(".",D)+(1<_.length?","+_[1]:"")}case"x":return this.decimalToHexString(V);case"X":return this.decimalToHexString(V,!0)}return typeof V!="number"&&isNaN(V)||isNaN(+R)||k.isNullOrWhiteSpace(V)?V:k.formatNumber(V,R)}static decimalToHexString(R,V=!1){return R=parseFloat(R).toString(16),V?R.toLocaleUpperCase():R}static getDisplayDateFromString(R){var V=R.split("-");if(V.length<=1)return R;let J=V[V.length-1];return R=V[V.length-2],V=V[V.length-3],(J=(J=J.split("T")[0]).split(" ")[0])+`.${R}.`+V}static getSortableDateFromString(R){var V=R.replace(",","").split(".");if(V.length<=1)return R;R=V[V.length-1].split(" ");let J=k.empty,et=(1<R.length&&(J=R[R.length-1]),V[V.length-1].split(" ")[0]+`-${V[V.length-2]}-`+V[V.length-3]);return!k.isNullOrWhiteSpace(J)&&1<J.length?et+="T"+J:et+="T00:00:00",et}static formatNumber(et,J){var J=J.length,et=et.toString();return J<=et.length?et:(J=J-et.length,++J,new Array(J).join("0")+et)}static joinString(R,...V){let J=k.empty;for(let D=0;D<V.length;D++)if(!(typeof V[D]=="string"&&k.isNullOrWhiteSpace(V[D])||typeof V[D]!="number"&&typeof V[D]!="string")){var et=""+V[D];J+=et;for(let _=D+1;_<V.length;_++)if(!k.isNullOrWhiteSpace(V[_])){J+=R,D=_-1;break}}return J}}pt.Qf=k;class vt{Values;constructor(R=""){this.Values=[],k.isNullOrWhiteSpace(R)||(this.Values=new Array(R))}toString(){return this.Values.join(k.empty)}ToString(){return this.toString()}append(R){this.Values.push(R)}Append(R){this.append(R)}appendLine(R){this.Values.push(ot+R)}AppendLine(R){this.appendLine(R)}appendFormat(R,...V){this.Values.push(k.format(R,...V))}AppendFormat(R,...V){this.appendFormat(R,...V)}appendLineFormat(R,...V){this.Values.push(ot+k.format(R,...V))}AppendLineFormat(R,...V){return this.appendLineFormat(R,...V)}clear(){this.Values=[]}Clear(){this.clear()}}pt.fe=vt},38941:(ae,pt,Ct)=>{"use strict";var ot;ot={value:!0};const O=Ct(48436);class C extends O.LinkedList{constructor(...k){super(...k)}get front(){return this.head}enqueue(k){this.append(k)}dequeue(){return this.removeHead()}}pt.o=C},48436:(ae,pt)=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});class Ct{constructor(...C){this._head=this._tail=null,this._length=0,C.length>0&&C.forEach(f=>{this.append(f)})}*iterator(){let C=this._head;for(;C;)yield C.value,C=C.next}[Symbol.iterator](){return this.iterator()}get head(){return this._head?this._head.value:null}get tail(){return this._tail?this._tail.value:null}get length(){return this._length}insert(C,f,k=!1){if(k&&this.isDuplicate(C))return!1;let vt=new ot(C),At=this._head;if(At)for(;;){if(At.value===f)return vt.next=At.next,vt.prev=At,At.next=vt,vt.next?vt.next.prev=vt:this._tail=vt,this._length++,!0;if(At.next)At=At.next;else return!1}else return!1}append(C,f=!1){if(f&&this.isDuplicate(C))return!1;let k=new ot(C);return this._tail?(this._tail.next=k,k.prev=this._tail,this._tail=k):this._head=this._tail=k,this._length++,!0}prepend(C,f=!1){if(f&&this.isDuplicate(C))return!1;let k=new ot(C);return this._head?(k.next=this._head,this._head.prev=k,this._head=k):this._head=this._tail=k,this._length++,!0}remove(C){let f=this._head;if(f){if(f.value===C)return this._head=f.next,this._head.prev=null,f.next=f.prev=null,this._length--,f.value;for(;;){if(f.value===C)return f.next?(f.prev.next=f.next,f.next.prev=f.prev,f.next=f.prev=null):(f.prev.next=null,this._tail=f.prev,f.next=f.prev=null),this._length--,f.value;if(f.next)f=f.next;else return}}}removeHead(){let C=this._head;if(C)return this._head.next?(this._head.next.prev=null,this._head=this._head.next,C.next=C.prev=null):(this._head=null,this._tail=null),this._length--,C.value}removeTail(){let C=this._tail;if(C)return this._tail.prev?(this._tail.prev.next=null,this._tail=this._tail.prev,C.next=C.prev=null):(this._head=null,this._tail=null),this._length--,C.value}first(C){let f=this.iterator(),k=[],vt=Math.min(C,this.length);for(let At=0;At<vt;At++){let R=f.next();k.push(R.value)}return k}toArray(){return[...this]}isDuplicate(C){return new Set(this.toArray()).has(C)}}pt.LinkedList=Ct;class ot{constructor(C){this.value=C,this.next=null,this.prev=null}}pt.LinkedListItem=ot},58982:(ae,pt,Ct)=>{var ot=Ct(14699);ae.exports=function(O){var C,f,k,vt;if(C=/^((?:rgb|hs[lv]|cmyk|xyz|lab)a?)\s*\(([^\)]*)\)/.exec(O)){var At=C[1],R=At.replace(/a$/,""),V=R==="cmyk"?4:3;f=ot[R],k=C[2].replace(/^\s+|\s+$/g,"").split(/\s*,\s*/).map(function(et,D){return/%$/.test(et)&&D===V?parseFloat(et)/100:(/%$/.test(et),parseFloat(et))}),At===R&&k.push(1),vt=k[V]===void 0?1:k[V],k=k.slice(0,V),f[R]=function(){return k}}else if(/^#[A-Fa-f0-9]+$/.test(O)){var R=O.replace(/^#/,""),V=R.length;f=ot.rgb,k=R.split(V===3?/(.)/:/(..)/),k=k.filter(Boolean).map(function(_){return parseInt(V===3?_+_:_,16)}),vt=1,f.rgb=function(){return k},k[0]||(k[0]=0),k[1]||(k[1]=0),k[2]||(k[2]=0)}else f=ot.keyword,f.keyword=function(){return O},k=O,vt=1;var J={rgb:void 0,hsl:void 0,hsv:void 0,cmyk:void 0,keyword:void 0,hex:void 0};try{J.rgb=f.rgb(k)}catch{}try{J.hsl=f.hsl(k)}catch{}try{J.hsv=f.hsv(k)}catch{}try{J.cmyk=f.cmyk(k)}catch{}try{J.keyword=f.keyword(k)}catch{}return J.rgb&&(J.hex="#"+J.rgb.map(function(et){var D=et.toString(16);return D.length===1?"0"+D:D}).join("")),J.rgb&&(J.rgba=J.rgb.concat(vt)),J.hsl&&(J.hsla=J.hsl.concat(vt)),J.hsv&&(J.hsva=J.hsv.concat(vt)),J.cmyk&&(J.cmyka=J.cmyk.concat(vt)),J}},64106:ae=>{"use strict";function pt(O,C){function f(){this.constructor=O}f.prototype=C.prototype,O.prototype=new f}function Ct(O,C,f,k){this.message=O,this.expected=C,this.found=f,this.location=k,this.name="SyntaxError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Ct)}pt(Ct,Error),Ct.buildMessage=function(O,C){var f={literal:function(et){return'"'+vt(et.text)+'"'},class:function(et){var D="",_;for(_=0;_<et.parts.length;_++)D+=et.parts[_]instanceof Array?At(et.parts[_][0])+"-"+At(et.parts[_][1]):At(et.parts[_]);return"["+(et.inverted?"^":"")+D+"]"},any:function(et){return"any character"},end:function(et){return"end of input"},other:function(et){return et.description}};function k(et){return et.charCodeAt(0).toString(16).toUpperCase()}function vt(et){return et.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,function(D){return"\\x0"+k(D)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(D){return"\\x"+k(D)})}function At(et){return et.replace(/\\/g,"\\\\").replace(/\]/g,"\\]").replace(/\^/g,"\\^").replace(/-/g,"\\-").replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,function(D){return"\\x0"+k(D)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(D){return"\\x"+k(D)})}function R(et){return f[et.type](et)}function V(et){var D=new Array(et.length),_,c;for(_=0;_<et.length;_++)D[_]=R(et[_]);if(D.sort(),D.length>0){for(_=1,c=1;_<D.length;_++)D[_-1]!==D[_]&&(D[c]=D[_],c++);D.length=c}switch(D.length){case 1:return D[0];case 2:return D[0]+" or "+D[1];default:return D.slice(0,-1).join(", ")+", or "+D[D.length-1]}}function J(et){return et?'"'+vt(et)+'"':"end of input"}return"Expected "+V(O)+" but "+J(C)+" found."};function ot(O,C){C=C!==void 0?C:{};var f={},k={start:Ds},vt=Ds,At="strict",R=gt("strict",!0),V="graph",J=gt("graph",!0),et="digraph",D=gt("digraph",!0),_="{",c=gt("{",!1),zt="}",qe=gt("}",!1),Pt=function(p,S,x,I){I===null&&(I=[]);var G={type:S.toLowerCase(),children:I};return p&&(G.strict=!0),x&&(G.id=x),G},Qi=";",N=gt(";",!1),pi=function(p,S){return S},Js=function(p,S){return[p].concat(S)},mi="=",Rt=gt("=",!1),ri=function(p,S){return{type:"attr_stmt",target:"graph",attr_list:[{type:"attr",id:p,eq:S}]}},$i="node",yt=gt("node",!0),Zs="edge",xt=gt("edge",!0),wn=function(p,S){return{type:"attr_stmt",target:p,attr_list:S}},ys="[",Cs=gt("[",!1),_s="]",at=gt("]",!1),vn=function(p,S){return(p||[]).concat(S||[])},w=function(p,S){return S},Pi=",",As=gt(",",!1),Pr=function(p,S,x){return[{type:"attr",id:p,eq:S}].concat(x||[])},Sr=function(p,S,x){var I=[p];return I=I.concat(S.map(function(G){return G.id})),{type:"edge_stmt",edge_list:I,attr_list:x||[]}},In="->",tn=gt("->",!1),st="--",be=gt("--",!1),X=function(p,S,x){return[{type:"edgeRHS",edgeop:p,id:S}].concat(x||[])},Dt=function(p,S){return{type:"node_stmt",node_id:p,attr_list:S||[]}},M=function(p,S){return S?{type:"node_id",id:p,port:S}:{type:"node_id",id:p}},Y=Zt("port"),U=":",W=gt(":",!1),K=function(p,S){return S},$=function(p,S){return{type:"port",id:p,compass_pt:S||null}},it=function(p){return{type:"port",compass_pt:p||null}},ht="subgraph",v=gt("subgraph",!0),L=function(p){return p?{type:"subgraph",id:p}:{type:"subgraph"}},j=function(p,S){return p=p||{type:"subgraph"},p.children=S||[],p},Es="n",we=gt("n",!1),yr="ne",Ut=gt("ne",!1),Nt="e",lo=gt("e",!1),$t="se",Cr=gt("se",!1),ho="s",en=gt("s",!1),Tn="sw",he=gt("sw",!1),xn="w",On=gt("w",!1),fe="nw",Yt=gt("nw",!1),Xi=Zt("UNICODE_STRING"),uo=function(p,S){return p+S.join("")},Ki=function(p,S){return p+S},Bi="$",Li=gt("$",!1),co="_",bs=gt("_",!1),sn=Zt("NUMBER"),ws="-",nn=gt("-",!1),Gi=".",Bn=gt(".",!1),Yi=/^[0-9]/,Ji=Ve([["0","9"]],!1,!1),Ar=function(p){return parseFloat(hn())},ia=function(p){return{type:"id",value:p.slice(1,p.length-1),html:!0}},Ge="<",Mt=gt("<",!1),vs=">",Si=gt(">",!1),Is=function(p){return"<"+p.join("")+">"},ze=Te(),Zi=function(p){return p},Vt=function(p){return p.join("")},Ln='"',Fn=gt('"',!1),go=function(p){return p.join("")},Dn=function(){return hn()},Jt="\\",Ft=gt("\\",!1),Ts=function(p){return p[1]==='"'?'"':p[0]+p[1]},oi=function(){return""},fo=/^[\n\r\u2028\u2029]/,rn=Ve([` `,"\r","\u2028","\u2029"],!1,!1),Er=Zt("end of line"),xs=` `,po=gt(` `,!1),Rn=`\r `,mo=gt(`\r `,!1),Po="\r",br=gt("\r",!1),Nn="\u2028",on=gt("\u2028",!1),So="\u2029",yo=gt("\u2029",!1),Gt=/^[^"\\\0-\x1F\x7F]/,Gn=Ve(['"',"\\",["\0",""],"\x7F"],!0,!1),Co='\\"',sa=gt('\\"',!1),na=function(){return'"'},ra=function(){return"\\"},oa=Zt("COMMENT"),_i=Zt("BLOCK_COMMENT"),an="/*",Ue=gt("/*",!1),ke="*/",Os=gt("*/",!1),ft=function(p){return p},Me=function(p){return p.join("")},kn=Zt("C_COMMENT"),ai="//",ts=gt("//",!1),es=/^[\n]/,is=Ve([` `],!1,!1),wr=function(p){return p.join("")},vr=Zt("MACRO_COMMENT"),ue="#",ve=gt("#",!1),li=Zt("WHITESPACE"),je=/^[\n\r]/,Bs=Ve([` `,"\r"],!1,!1),ki=/^[ \t]/,Xt=Ve([" "," "],!1,!1),Mn=/^[a-z\xB5\xDF-\xF6\xF8-\xFF\u0101\u0103\u0105\u0107\u0109\u010B\u010D\u010F\u0111\u0113\u0115\u0117\u0119\u011B\u011D\u011F\u0121\u0123\u0125\u0127\u0129\u012B\u012D\u012F\u0131\u0133\u0135\u0137-\u0138\u013A\u013C\u013E\u0140\u0142\u0144\u0146\u0148-\u0149\u014B\u014D\u014F\u0151\u0153\u0155\u0157\u0159\u015B\u015D\u015F\u0161\u0163\u0165\u0167\u0169\u016B\u016D\u016F\u0171\u0173\u0175\u0177\u017A\u017C\u017E-\u0180\u0183\u0185\u0188\u018C-\u018D\u0192\u0195\u0199-\u019B\u019E\u01A1\u01A3\u01A5\u01A8\u01AA-\u01AB\u01AD\u01B0\u01B4\u01B6\u01B9-\u01BA\u01BD-\u01BF\u01C6\u01C9\u01CC\u01CE\u01D0\u01D2\u01D4\u01D6\u01D8\u01DA\u01DC-\u01DD\u01DF\u01E1\u01E3\u01E5\u01E7\u01E9\u01EB\u01ED\u01EF-\u01F0\u01F3\u01F5\u01F9\u01FB\u01FD\u01FF\u0201\u0203\u0205\u0207\u0209\u020B\u020D\u020F\u0211\u0213\u0215\u0217\u0219\u021B\u021D\u021F\u0221\u0223\u0225\u0227\u0229\u022B\u022D\u022F\u0231\u0233-\u0239\u023C\u023F-\u0240\u0242\u0247\u0249\u024B\u024D\u024F-\u0293\u0295-\u02AF\u0371\u0373\u0377\u037B-\u037D\u0390\u03AC-\u03CE\u03D0-\u03D1\u03D5-\u03D7\u03D9\u03DB\u03DD\u03DF\u03E1\u03E3\u03E5\u03E7\u03E9\u03EB\u03ED\u03EF-\u03F3\u03F5\u03F8\u03FB-\u03FC\u0430-\u045F\u0461\u0463\u0465\u0467\u0469\u046B\u046D\u046F\u0471\u0473\u0475\u0477\u0479\u047B\u047D\u047F\u0481\u048B\u048D\u048F\u0491\u0493\u0495\u0497\u0499\u049B\u049D\u049F\u04A1\u04A3\u04A5\u04A7\u04A9\u04AB\u04AD\u04AF\u04B1\u04B3\u04B5\u04B7\u04B9\u04BB\u04BD\u04BF\u04C2\u04C4\u04C6\u04C8\u04CA\u04CC\u04CE-\u04CF\u04D1\u04D3\u04D5\u04D7\u04D9\u04DB\u04DD\u04DF\u04E1\u04E3\u04E5\u04E7\u04E9\u04EB\u04ED\u04EF\u04F1\u04F3\u04F5\u04F7\u04F9\u04FB\u04FD\u04FF\u0501\u0503\u0505\u0507\u0509\u050B\u050D\u050F\u0511\u0513\u0515\u0517\u0519\u051B\u051D\u051F\u0521\u0523\u0525\u0527\u0561-\u0587\u1D00-\u1D2B\u1D6B-\u1D77\u1D79-\u1D9A\u1E01\u1E03\u1E05\u1E07\u1E09\u1E0B\u1E0D\u1E0F\u1E11\u1E13\u1E15\u1E17\u1E19\u1E1B\u1E1D\u1E1F\u1E21\u1E23\u1E25\u1E27\u1E29\u1E2B\u1E2D\u1E2F\u1E31\u1E33\u1E35\u1E37\u1E39\u1E3B\u1E3D\u1E3F\u1E41\u1E43\u1E45\u1E47\u1E49\u1E4B\u1E4D\u1E4F\u1E51\u1E53\u1E55\u1E57\u1E59\u1E5B\u1E5D\u1E5F\u1E61\u1E63\u1E65\u1E67\u1E69\u1E6B\u1E6D\u1E6F\u1E71\u1E73\u1E75\u1E77\u1E79\u1E7B\u1E7D\u1E7F\u1E81\u1E83\u1E85\u1E87\u1E89\u1E8B\u1E8D\u1E8F\u1E91\u1E93\u1E95-\u1E9D\u1E9F\u1EA1\u1EA3\u1EA5\u1EA7\u1EA9\u1EAB\u1EAD\u1EAF\u1EB1\u1EB3\u1EB5\u1EB7\u1EB9\u1EBB\u1EBD\u1EBF\u1EC1\u1EC3\u1EC5\u1EC7\u1EC9\u1ECB\u1ECD\u1ECF\u1ED1\u1ED3\u1ED5\u1ED7\u1ED9\u1EDB\u1EDD\u1EDF\u1EE1\u1EE3\u1EE5\u1EE7\u1EE9\u1EEB\u1EED\u1EEF\u1EF1\u1EF3\u1EF5\u1EF7\u1EF9\u1EFB\u1EFD\u1EFF-\u1F07\u1F10-\u1F15\u1F20-\u1F27\u1F30-\u1F37\u1F40-\u1F45\u1F50-\u1F57\u1F60-\u1F67\u1F70-\u1F7D\u1F80-\u1F87\u1F90-\u1F97\u1FA0-\u1FA7\u1FB0-\u1FB4\u1FB6-\u1FB7\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FC7\u1FD0-\u1FD3\u1FD6-\u1FD7\u1FE0-\u1FE7\u1FF2-\u1FF4\u1FF6-\u1FF7\u210A\u210E-\u210F\u2113\u212F\u2134\u2139\u213C-\u213D\u2146-\u2149\u214E\u2184\u2C30-\u2C5E\u2C61\u2C65-\u2C66\u2C68\u2C6A\u2C6C\u2C71\u2C73-\u2C74\u2C76-\u2C7B\u2C81\u2C83\u2C85\u2C87\u2C89\u2C8B\u2C8D\u2C8F\u2C91\u2C93\u2C95\u2C97\u2C99\u2C9B\u2C9D\u2C9F\u2CA1\u2CA3\u2CA5\u2CA7\u2CA9\u2CAB\u2CAD\u2CAF\u2CB1\u2CB3\u2CB5\u2CB7\u2CB9\u2CBB\u2CBD\u2CBF\u2CC1\u2CC3\u2CC5\u2CC7\u2CC9\u2CCB\u2CCD\u2CCF\u2CD1\u2CD3\u2CD5\u2CD7\u2CD9\u2CDB\u2CDD\u2CDF\u2CE1\u2CE3-\u2CE4\u2CEC\u2CEE\u2CF3\u2D00-\u2D25\u2D27\u2D2D\uA641\uA643\uA645\uA647\uA649\uA64B\uA64D\uA64F\uA651\uA653\uA655\uA657\uA659\uA65B\uA65D\uA65F\uA661\uA663\uA665\uA667\uA669\uA66B\uA66D\uA681\uA683\uA685\uA687\uA689\uA68B\uA68D\uA68F\uA691\uA693\uA695\uA697\uA723\uA725\uA727\uA729\uA72B\uA72D\uA72F-\uA731\uA733\uA735\uA737\uA739\uA73B\uA73D\uA73F\uA741\uA743\uA745\uA747\uA749\uA74B\uA74D\uA74F\uA751\uA753\uA755\uA757\uA759\uA75B\uA75D\uA75F\uA761\uA763\uA765\uA767\uA769\uA76B\uA76D\uA76F\uA771-\uA778\uA77A\uA77C\uA77F\uA781\uA783\uA785\uA787\uA78C\uA78E\uA791\uA793\uA7A1\uA7A3\uA7A5\uA7A7\uA7A9\uA7FA\uFB00-\uFB06\uFB13-\uFB17\uFF41-\uFF5A]/,ss=Ve([["a","z"],"\xB5",["\xDF","\xF6"],["\xF8","\xFF"],"\u0101","\u0103","\u0105","\u0107","\u0109","\u010B","\u010D","\u010F","\u0111","\u0113","\u0115","\u0117","\u0119","\u011B","\u011D","\u011F","\u0121","\u0123","\u0125","\u0127","\u0129","\u012B","\u012D","\u012F","\u0131","\u0133","\u0135",["\u0137","\u0138"],"\u013A","\u013C","\u013E","\u0140","\u0142","\u0144","\u0146",["\u0148","\u0149"],"\u014B","\u014D","\u014F","\u0151","\u0153","\u0155","\u0157","\u0159","\u015B","\u015D","\u015F","\u0161","\u0163","\u0165","\u0167","\u0169","\u016B","\u016D","\u016F","\u0171","\u0173","\u0175","\u0177","\u017A","\u017C",["\u017E","\u0180"],"\u0183","\u0185","\u0188",["\u018C","\u018D"],"\u0192","\u0195",["\u0199","\u019B"],"\u019E","\u01A1","\u01A3","\u01A5","\u01A8",["\u01AA","\u01AB"],"\u01AD","\u01B0","\u01B4","\u01B6",["\u01B9","\u01BA"],["\u01BD","\u01BF"],"\u01C6","\u01C9","\u01CC","\u01CE","\u01D0","\u01D2","\u01D4","\u01D6","\u01D8","\u01DA",["\u01DC","\u01DD"],"\u01DF","\u01E1","\u01E3","\u01E5","\u01E7","\u01E9","\u01EB","\u01ED",["\u01EF","\u01F0"],"\u01F3","\u01F5","\u01F9","\u01FB","\u01FD","\u01FF","\u0201","\u0203","\u0205","\u0207","\u0209","\u020B","\u020D","\u020F","\u0211","\u0213","\u0215","\u0217","\u0219","\u021B","\u021D","\u021F","\u0221","\u0223","\u0225","\u0227","\u0229","\u022B","\u022D","\u022F","\u0231",["\u0233","\u0239"],"\u023C",["\u023F","\u0240"],"\u0242","\u0247","\u0249","\u024B","\u024D",["\u024F","\u0293"],["\u0295","\u02AF"],"\u0371","\u0373","\u0377",["\u037B","\u037D"],"\u0390",["\u03AC","\u03CE"],["\u03D0","\u03D1"],["\u03D5","\u03D7"],"\u03D9","\u03DB","\u03DD","\u03DF","\u03E1","\u03E3","\u03E5","\u03E7","\u03E9","\u03EB","\u03ED",["\u03EF","\u03F3"],"\u03F5","\u03F8",["\u03FB","\u03FC"],["\u0430","\u045F"],"\u0461","\u0463","\u0465","\u0467","\u0469","\u046B","\u046D","\u046F","\u0471","\u0473","\u0475","\u0477","\u0479","\u047B","\u047D","\u047F","\u0481","\u048B","\u048D","\u048F","\u0491","\u0493","\u0495","\u0497","\u0499","\u049B","\u049D","\u049F","\u04A1","\u04A3","\u04A5","\u04A7","\u04A9","\u04AB","\u04AD","\u04AF","\u04B1","\u04B3","\u04B5","\u04B7","\u04B9","\u04BB","\u04BD","\u04BF","\u04C2","\u04C4","\u04C6","\u04C8","\u04CA","\u04CC",["\u04CE","\u04CF"],"\u04D1","\u04D3","\u04D5","\u04D7","\u04D9","\u04DB","\u04DD","\u04DF","\u04E1","\u04E3","\u04E5","\u04E7","\u04E9","\u04EB","\u04ED","\u04EF","\u04F1","\u04F3","\u04F5","\u04F7","\u04F9","\u04FB","\u04FD","\u04FF","\u0501","\u0503","\u0505","\u0507","\u0509","\u050B","\u050D","\u050F","\u0511","\u0513","\u0515","\u0517","\u0519","\u051B","\u051D","\u051F","\u0521","\u0523","\u0525","\u0527",["\u0561","\u0587"],["\u1D00","\u1D2B"],["\u1D6B","\u1D77"],["\u1D79","\u1D9A"],"\u1E01","\u1E03","\u1E05","\u1E07","\u1E09","\u1E0B","\u1E0D","\u1E0F","\u1E11","\u1E13","\u1E15","\u1E17","\u1E19","\u1E1B","\u1E1D","\u1E1F","\u1E21","\u1E23","\u1E25","\u1E27","\u1E29","\u1E2B","\u1E2D","\u1E2F","\u1E31","\u1E33","\u1E35","\u1E37","\u1E39","\u1E3B","\u1E3D","\u1E3F","\u1E41","\u1E43","\u1E45","\u1E47","\u1E49","\u1E4B","\u1E4D","\u1E4F","\u1E51","\u1E53","\u1E55","\u1E57","\u1E59","\u1E5B","\u1E5D","\u1E5F","\u1E61","\u1E63","\u1E65","\u1E67","\u1E69","\u1E6B","\u1E6D","\u1E6F","\u1E71","\u1E73","\u1E75","\u1E77","\u1E79","\u1E7B","\u1E7D","\u1E7F","\u1E81","\u1E83","\u1E85","\u1E87","\u1E89","\u1E8B","\u1E8D","\u1E8F","\u1E91","\u1E93",["\u1E95","\u1E9D"],"\u1E9F","\u1EA1","\u1EA3","\u1EA5","\u1EA7","\u1EA9","\u1EAB","\u1EAD","\u1EAF","\u1EB1","\u1EB3","\u1EB5","\u1EB7","\u1EB9","\u1EBB","\u1EBD","\u1EBF","\u1EC1","\u1EC3","\u1EC5","\u1EC7","\u1EC9","\u1ECB","\u1ECD","\u1ECF","\u1ED1","\u1ED3","\u1ED5","\u1ED7","\u1ED9","\u1EDB","\u1EDD","\u1EDF","\u1EE1","\u1EE3","\u1EE5","\u1EE7","\u1EE9","\u1EEB","\u1EED","\u1EEF","\u1EF1","\u1EF3","\u1EF5","\u1EF7","\u1EF9","\u1EFB","\u1EFD",["\u1EFF","\u1F07"],["\u1F10","\u1F15"],["\u1F20","\u1F27"],["\u1F30","\u1F37"],["\u1F40","\u1F45"],["\u1F50","\u1F57"],["\u1F60","\u1F67"],["\u1F70","\u1F7D"],["\u1F80","\u1F87"],["\u1F90","\u1F97"],["\u1FA0","\u1FA7"],["\u1FB0","\u1FB4"],["\u1FB6","\u1FB7"],"\u1FBE",["\u1FC2","\u1FC4"],["\u1FC6","\u1FC7"],["\u1FD0","\u1FD3"],["\u1FD6","\u1FD7"],["\u1FE0","\u1FE7"],["\u1FF2","\u1FF4"],["\u1FF6","\u1FF7"],"\u210A",["\u210E","\u210F"],"\u2113","\u212F","\u2134","\u2139",["\u213C","\u213D"],["\u2146","\u2149"],"\u214E","\u2184",["\u2C30","\u2C5E"],"\u2C61",["\u2C65","\u2C66"],"\u2C68","\u2C6A","\u2C6C","\u2C71",["\u2C73","\u2C74"],["\u2C76","\u2C7B"],"\u2C81","\u2C83","\u2C85","\u2C87","\u2C89","\u2C8B","\u2C8D","\u2C8F","\u2C91","\u2C93","\u2C95","\u2C97","\u2C99","\u2C9B","\u2C9D","\u2C9F","\u2CA1","\u2CA3","\u2CA5","\u2CA7","\u2CA9","\u2CAB","\u2CAD","\u2CAF","\u2CB1","\u2CB3","\u2CB5","\u2CB7","\u2CB9","\u2CBB","\u2CBD","\u2CBF","\u2CC1","\u2CC3","\u2CC5","\u2CC7","\u2CC9","\u2CCB","\u2CCD","\u2CCF","\u2CD1","\u2CD3","\u2CD5","\u2CD7","\u2CD9","\u2CDB","\u2CDD","\u2CDF","\u2CE1",["\u2CE3","\u2CE4"],"\u2CEC","\u2CEE","\u2CF3",["\u2D00","\u2D25"],"\u2D27","\u2D2D","\uA641","\uA643","\uA645","\uA647","\uA649","\uA64B","\uA64D","\uA64F","\uA651","\uA653","\uA655","\uA657","\uA659","\uA65B","\uA65D","\uA65F","\uA661","\uA663","\uA665","\uA667","\uA669","\uA66B","\uA66D","\uA681","\uA683","\uA685","\uA687","\uA689","\uA68B","\uA68D","\uA68F","\uA691","\uA693","\uA695","\uA697","\uA723","\uA725","\uA727","\uA729","\uA72B","\uA72D",["\uA72F","\uA731"],"\uA733","\uA735","\uA737","\uA739","\uA73B","\uA73D","\uA73F","\uA741","\uA743","\uA745","\uA747","\uA749","\uA74B","\uA74D","\uA74F","\uA751","\uA753","\uA755","\uA757","\uA759","\uA75B","\uA75D","\uA75F","\uA761","\uA763","\uA765","\uA767","\uA769","\uA76B","\uA76D","\uA76F",["\uA771","\uA778"],"\uA77A","\uA77C","\uA77F","\uA781","\uA783","\uA785","\uA787","\uA78C","\uA78E","\uA791","\uA793","\uA7A1","\uA7A3","\uA7A5","\uA7A7","\uA7A9","\uA7FA",["\uFB00","\uFB06"],["\uFB13","\uFB17"],["\uFF41","\uFF5A"]],!1,!1),Vn=/^[\u02B0-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0374\u037A\u0559\u0640\u06E5-\u06E6\u07F4-\u07F5\u07FA\u081A\u0824\u0828\u0971\u0E46\u0EC6\u10FC\u17D7\u1843\u1AA7\u1C78-\u1C7D\u1D2C-\u1D6A\u1D78\u1D9B-\u1DBF\u2071\u207F\u2090-\u209C\u2C7C-\u2C7D\u2D6F\u2E2F\u3005\u3031-\u3035\u303B\u309D-\u309E\u30FC-\u30FE\uA015\uA4F8-\uA4FD\uA60C\uA67F\uA717-\uA71F\uA770\uA788\uA7F8-\uA7F9\uA9CF\uAA70\uAADD\uAAF3-\uAAF4\uFF70\uFF9E-\uFF9F]/,Ir=Ve([["\u02B0","\u02C1"],["\u02C6","\u02D1"],["\u02E0","\u02E4"],"\u02EC","\u02EE","\u0374","\u037A","\u0559","\u0640",["\u06E5","\u06E6"],["\u07F4","\u07F5"],"\u07FA","\u081A","\u0824","\u0828","\u0971","\u0E46","\u0EC6","\u10FC","\u17D7","\u1843","\u1AA7",["\u1C78","\u1C7D"],["\u1D2C","\u1D6A"],"\u1D78",["\u1D9B","\u1DBF"],"\u2071","\u207F",["\u2090","\u209C"],["\u2C7C","\u2C7D"],"\u2D6F","\u2E2F","\u3005",["\u3031","\u3035"],"\u303B",["\u309D","\u309E"],["\u30FC","\u30FE"],"\uA015",["\uA4F8","\uA4FD"],"\uA60C","\uA67F",["\uA717","\uA71F"],"\uA770","\uA788",["\uA7F8","\uA7F9"],"\uA9CF","\uAA70","\uAADD",["\uAAF3","\uAAF4"],"\uFF70",["\uFF9E","\uFF9F"]],!1,!1),hi=/^[\xAA\xBA\u01BB\u01C0-\u01C3\u0294\u05D0-\u05EA\u05F0-\u05F2\u0620-\u063F\u0641-\u064A\u066E-\u066F\u0671-\u06D3\u06D5\u06EE-\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u0800-\u0815\u0840-\u0858\u08A0\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0972-\u0977\u0979-\u097F\u0985-\u098C\u098F-\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC-\u09DD\u09DF-\u09E1\u09F0-\u09F1\u0A05-\u0A0A\u0A0F-\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32-\u0A33\u0A35-\u0A36\u0A38-\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2-\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0-\u0AE1\u0B05-\u0B0C\u0B0F-\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32-\u0B33\u0B35-\u0B39\u0B3D\u0B5C-\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99-\u0B9A\u0B9C\u0B9E-\u0B9F\u0BA3-\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58-\u0C59\u0C60-\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0-\u0CE1\u0CF1-\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32-\u0E33\u0E40-\u0E45\u0E81-\u0E82\u0E84\u0E87-\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA-\u0EAB\u0EAD-\u0EB0\u0EB2-\u0EB3\u0EBD\u0EC0-\u0EC4\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065-\u1066\u106E-\u1070\u1075-\u1081\u108E\u10D0-\u10FA\u10FD-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17DC\u1820-\u1842\u1844-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE-\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C77\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5-\u1CF6\u2135-\u2138\u2D30-\u2D67\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3006\u303C\u3041-\u3096\u309F\u30A1-\u30FA\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA014\uA016-\uA48C\uA4D0-\uA4F7\uA500-\uA60B\uA610-\uA61F\uA62A-\uA62B\uA66E\uA6A0-\uA6E5\uA7FB-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA6F\uAA71-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5-\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADC\uAAE0-\uAAEA\uAAF2\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40-\uFB41\uFB43-\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF66-\uFF6F\uFF71-\uFF9D\uFFA0-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/,Fi=Ve(["\xAA","\xBA","\u01BB",["\u01C0","\u01C3"],"\u0294",["\u05D0","\u05EA"],["\u05F0","\u05F2"],["\u0620","\u063F"],["\u0641","\u064A"],["\u066E","\u066F"],["\u0671","\u06D3"],"\u06D5",["\u06EE","\u06EF"],["\u06FA","\u06FC"],"\u06FF","\u0710",["\u0712","\u072F"],["\u074D","\u07A5"],"\u07B1",["\u07CA","\u07EA"],["\u0800","\u0815"],["\u0840","\u0858"],"\u08A0",["\u08A2","\u08AC"],["\u0904","\u0939"],"\u093D","\u0950",["\u0958","\u0961"],["\u0972","\u0977"],["\u0979","\u097F"],["\u0985","\u098C"],["\u098F","\u0990"],["\u0993","\u09A8"],["\u09AA","\u09B0"],"\u09B2",["\u09B6","\u09B9"],"\u09BD","\u09CE",["\u09DC","\u09DD"],["\u09DF","\u09E1"],["\u09F0","\u09F1"],["\u0A05","\u0A0A"],["\u0A0F","\u0A10"],["\u0A13","\u0A28"],["\u0A2A","\u0A30"],["\u0A32","\u0A33"],["\u0A35","\u0A36"],["\u0A38","\u0A39"],["\u0A59","\u0A5C"],"\u0A5E",["\u0A72","\u0A74"],["\u0A85","\u0A8D"],["\u0A8F","\u0A91"],["\u0A93","\u0AA8"],["\u0AAA","\u0AB0"],["\u0AB2","\u0AB3"],["\u0AB5","\u0AB9"],"\u0ABD","\u0AD0",["\u0AE0","\u0AE1"],["\u0B05","\u0B0C"],["\u0B0F","\u0B10"],["\u0B13","\u0B28"],["\u0B2A","\u0B30"],["\u0B32","\u0B33"],["\u0B35","\u0B39"],"\u0B3D",["\u0B5C","\u0B5D"],["\u0B5F","\u0B61"],"\u0B71","\u0B83",["\u0B85","\u0B8A"],["\u0B8E","\u0B90"],["\u0B92","\u0B95"],["\u0B99","\u0B9A"],"\u0B9C",["\u0B9E","\u0B9F"],["\u0BA3","\u0BA4"],["\u0BA8","\u0BAA"],["\u0BAE","\u0BB9"],"\u0BD0",["\u0C05","\u0C0C"],["\u0C0E","\u0C10"],["\u0C12","\u0C28"],["\u0C2A","\u0C33"],["\u0C35","\u0C39"],"\u0C3D",["\u0C58","\u0C59"],["\u0C60","\u0C61"],["\u0C85","\u0C8C"],["\u0C8E","\u0C90"],["\u0C92","\u0CA8"],["\u0CAA","\u0CB3"],["\u0CB5","\u0CB9"],"\u0CBD","\u0CDE",["\u0CE0","\u0CE1"],["\u0CF1","\u0CF2"],["\u0D05","\u0D0C"],["\u0D0E","\u0D10"],["\u0D12","\u0D3A"],"\u0D3D","\u0D4E",["\u0D60","\u0D61"],["\u0D7A","\u0D7F"],["\u0D85","\u0D96"],["\u0D9A","\u0DB1"],["\u0DB3","\u0DBB"],"\u0DBD",["\u0DC0","\u0DC6"],["\u0E01","\u0E30"],["\u0E32","\u0E33"],["\u0E40","\u0E45"],["\u0E81","\u0E82"],"\u0E84",["\u0E87","\u0E88"],"\u0E8A","\u0E8D",["\u0E94","\u0E97"],["\u0E99","\u0E9F"],["\u0EA1","\u0EA3"],"\u0EA5","\u0EA7",["\u0EAA","\u0EAB"],["\u0EAD","\u0EB0"],["\u0EB2","\u0EB3"],"\u0EBD",["\u0EC0","\u0EC4"],["\u0EDC","\u0EDF"],"\u0F00",["\u0F40","\u0F47"],["\u0F49","\u0F6C"],["\u0F88","\u0F8C"],["\u1000","\u102A"],"\u103F",["\u1050","\u1055"],["\u105A","\u105D"],"\u1061",["\u1065","\u1066"],["\u106E","\u1070"],["\u1075","\u1081"],"\u108E",["\u10D0","\u10FA"],["\u10FD","\u1248"],["\u124A","\u124D"],["\u1250","\u1256"],"\u1258",["\u125A","\u125D"],["\u1260","\u1288"],["\u128A","\u128D"],["\u1290","\u12B0"],["\u12B2","\u12B5"],["\u12B8","\u12BE"],"\u12C0",["\u12C2","\u12C5"],["\u12C8","\u12D6"],["\u12D8","\u1310"],["\u1312","\u1315"],["\u1318","\u135A"],["\u1380","\u138F"],["\u13A0","\u13F4"],["\u1401","\u166C"],["\u166F","\u167F"],["\u1681","\u169A"],["\u16A0","\u16EA"],["\u1700","\u170C"],["\u170E","\u1711"],["\u1720","\u1731"],["\u1740","\u1751"],["\u1760","\u176C"],["\u176E","\u1770"],["\u1780","\u17B3"],"\u17DC",["\u1820","\u1842"],["\u1844","\u1877"],["\u1880","\u18A8"],"\u18AA",["\u18B0","\u18F5"],["\u1900","\u191C"],["\u1950","\u196D"],["\u1970","\u1974"],["\u1980","\u19AB"],["\u19C1","\u19C7"],["\u1A00","\u1A16"],["\u1A20","\u1A54"],["\u1B05","\u1B33"],["\u1B45","\u1B4B"],["\u1B83","\u1BA0"],["\u1BAE","\u1BAF"],["\u1BBA","\u1BE5"],["\u1C00","\u1C23"],["\u1C4D","\u1C4F"],["\u1C5A","\u1C77"],["\u1CE9","\u1CEC"],["\u1CEE","\u1CF1"],["\u1CF5","\u1CF6"],["\u2135","\u2138"],["\u2D30","\u2D67"],["\u2D80","\u2D96"],["\u2DA0","\u2DA6"],["\u2DA8","\u2DAE"],["\u2DB0","\u2DB6"],["\u2DB8","\u2DBE"],["\u2DC0","\u2DC6"],["\u2DC8","\u2DCE"],["\u2DD0","\u2DD6"],["\u2DD8","\u2DDE"],"\u3006","\u303C",["\u3041","\u3096"],"\u309F",["\u30A1","\u30FA"],"\u30FF",["\u3105","\u312D"],["\u3131","\u318E"],["\u31A0","\u31BA"],["\u31F0","\u31FF"],["\u3400","\u4DB5"],["\u4E00","\u9FCC"],["\uA000","\uA014"],["\uA016","\uA48C"],["\uA4D0","\uA4F7"],["\uA500","\uA60B"],["\uA610","\uA61F"],["\uA62A","\uA62B"],"\uA66E",["\uA6A0","\uA6E5"],["\uA7FB","\uA801"],["\uA803","\uA805"],["\uA807","\uA80A"],["\uA80C","\uA822"],["\uA840","\uA873"],["\uA882","\uA8B3"],["\uA8F2","\uA8F7"],"\uA8FB",["\uA90A","\uA925"],["\uA930","\uA946"],["\uA960","\uA97C"],["\uA984","\uA9B2"],["\uAA00","\uAA28"],["\uAA40","\uAA42"],["\uAA44","\uAA4B"],["\uAA60","\uAA6F"],["\uAA71","\uAA76"],"\uAA7A",["\uAA80","\uAAAF"],"\uAAB1",["\uAAB5","\uAAB6"],["\uAAB9","\uAABD"],"\uAAC0","\uAAC2",["\uAADB","\uAADC"],["\uAAE0","\uAAEA"],"\uAAF2",["\uAB01","\uAB06"],["\uAB09","\uAB0E"],["\uAB11","\uAB16"],["\uAB20","\uAB26"],["\uAB28","\uAB2E"],["\uABC0","\uABE2"],["\uAC00","\uD7A3"],["\uD7B0","\uD7C6"],["\uD7CB","\uD7FB"],["\uF900","\uFA6D"],["\uFA70","\uFAD9"],"\uFB1D",["\uFB1F","\uFB28"],["\uFB2A","\uFB36"],["\uFB38","\uFB3C"],"\uFB3E",["\uFB40","\uFB41"],["\uFB43","\uFB44"],["\uFB46","\uFBB1"],["\uFBD3","\uFD3D"],["\uFD50","\uFD8F"],["\uFD92","\uFDC7"],["\uFDF0","\uFDFB"],["\uFE70","\uFE74"],["\uFE76","\uFEFC"],["\uFF66","\uFF6F"],["\uFF71","\uFF9D"],["\uFFA0","\uFFBE"],["\uFFC2","\uFFC7"],["\uFFCA","\uFFCF"],["\uFFD2","\uFFD7"],["\uFFDA","\uFFDC"]],!1,!1),ln=/^[\u01C5\u01C8\u01CB\u01F2\u1F88-\u1F8F\u1F98-\u1F9F\u1FA8-\u1FAF\u1FBC\u1FCC\u1FFC]/,Ls=Ve(["\u01C5","\u01C8","\u01CB","\u01F2",["\u1F88","\u1F8F"],["\u1F98","\u1F9F"],["\u1FA8","\u1FAF"],"\u1FBC","\u1FCC","\u1FFC"],!1,!1),Wn=/^[A-Z\xC0-\xD6\xD8-\xDE\u0100\u0102\u0104\u0106\u0108\u010A\u010C\u010E\u0110\u0112\u0114\u0116\u0118\u011A\u011C\u011E\u0120\u0122\u0124\u0126\u0128\u012A\u012C\u012E\u0130\u0132\u0134\u0136\u0139\u013B\u013D\u013F\u0141\u0143\u0145\u0147\u014A\u014C\u014E\u0150\u0152\u0154\u0156\u0158\u015A\u015C\u015E\u0160\u0162\u0164\u0166\u0168\u016A\u016C\u016E\u0170\u0172\u0174\u0176\u0178-\u0179\u017B\u017D\u0181-\u0182\u0184\u0186-\u0187\u0189-\u018B\u018E-\u0191\u0193-\u0194\u0196-\u0198\u019C-\u019D\u019F-\u01A0\u01A2\u01A4\u01A6-\u01A7\u01A9\u01AC\u01AE-\u01AF\u01B1-\u01B3\u01B5\u01B7-\u01B8\u01BC\u01C4\u01C7\u01CA\u01CD\u01CF\u01D1\u01D3\u01D5\u01D7\u01D9\u01DB\u01DE\u01E0\u01E2\u01E4\u01E6\u01E8\u01EA\u01EC\u01EE\u01F1\u01F4\u01F6-\u01F8\u01FA\u01FC\u01FE\u0200\u0202\u0204\u0206\u0208\u020A\u020C\u020E\u0210\u0212\u0214\u0216\u0218\u021A\u021C\u021E\u0220\u0222\u0224\u0226\u0228\u022A\u022C\u022E\u0230\u0232\u023A-\u023B\u023D-\u023E\u0241\u0243-\u0246\u0248\u024A\u024C\u024E\u0370\u0372\u0376\u0386\u0388-\u038A\u038C\u038E-\u038F\u0391-\u03A1\u03A3-\u03AB\u03CF\u03D2-\u03D4\u03D8\u03DA\u03DC\u03DE\u03E0\u03E2\u03E4\u03E6\u03E8\u03EA\u03EC\u03EE\u03F4\u03F7\u03F9-\u03FA\u03FD-\u042F\u0460\u0462\u0464\u0466\u0468\u046A\u046C\u046E\u0470\u0472\u0474\u0476\u0478\u047A\u047C\u047E\u0480\u048A\u048C\u048E\u0490\u0492\u0494\u0496\u0498\u049A\u049C\u049E\u04A0\u04A2\u04A4\u04A6\u04A8\u04AA\u04AC\u04AE\u04B0\u04B2\u04B4\u04B6\u04B8\u04BA\u04BC\u04BE\u04C0-\u04C1\u04C3\u04C5\u04C7\u04C9\u04CB\u04CD\u04D0\u04D2\u04D4\u04D6\u04D8\u04DA\u04DC\u04DE\u04E0\u04E2\u04E4\u04E6\u04E8\u04EA\u04EC\u04EE\u04F0\u04F2\u04F4\u04F6\u04F8\u04FA\u04FC\u04FE\u0500\u0502\u0504\u0506\u0508\u050A\u050C\u050E\u0510\u0512\u0514\u0516\u0518\u051A\u051C\u051E\u0520\u0522\u0524\u0526\u0531-\u0556\u10A0-\u10C5\u10C7\u10CD\u1E00\u1E02\u1E04\u1E06\u1E08\u1E0A\u1E0C\u1E0E\u1E10\u1E12\u1E14\u1E16\u1E18\u1E1A\u1E1C\u1E1E\u1E20\u1E22\u1E24\u1E26\u1E28\u1E2A\u1E2C\u1E2E\u1E30\u1E32\u1E34\u1E36\u1E38\u1E3A\u1E3C\u1E3E\u1E40\u1E42\u1E44\u1E46\u1E48\u1E4A\u1E4C\u1E4E\u1E50\u1E52\u1E54\u1E56\u1E58\u1E5A\u1E5C\u1E5E\u1E60\u1E62\u1E64\u1E66\u1E68\u1E6A\u1E6C\u1E6E\u1E70\u1E72\u1E74\u1E76\u1E78\u1E7A\u1E7C\u1E7E\u1E80\u1E82\u1E84\u1E86\u1E88\u1E8A\u1E8C\u1E8E\u1E90\u1E92\u1E94\u1E9E\u1EA0\u1EA2\u1EA4\u1EA6\u1EA8\u1EAA\u1EAC\u1EAE\u1EB0\u1EB2\u1EB4\u1EB6\u1EB8\u1EBA\u1EBC\u1EBE\u1EC0\u1EC2\u1EC4\u1EC6\u1EC8\u1ECA\u1ECC\u1ECE\u1ED0\u1ED2\u1ED4\u1ED6\u1ED8\u1EDA\u1EDC\u1EDE\u1EE0\u1EE2\u1EE4\u1EE6\u1EE8\u1EEA\u1EEC\u1EEE\u1EF0\u1EF2\u1EF4\u1EF6\u1EF8\u1EFA\u1EFC\u1EFE\u1F08-\u1F0F\u1F18-\u1F1D\u1F28-\u1F2F\u1F38-\u1F3F\u1F48-\u1F4D\u1F59\u1F5B\u1F5D\u1F5F\u1F68-\u1F6F\u1FB8-\u1FBB\u1FC8-\u1FCB\u1FD8-\u1FDB\u1FE8-\u1FEC\u1FF8-\u1FFB\u2102\u2107\u210B-\u210D\u2110-\u2112\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u2130-\u2133\u213E-\u213F\u2145\u2183\u2C00-\u2C2E\u2C60\u2C62-\u2C64\u2C67\u2C69\u2C6B\u2C6D-\u2C70\u2C72\u2C75\u2C7E-\u2C80\u2C82\u2C84\u2C86\u2C88\u2C8A\u2C8C\u2C8E\u2C90\u2C92\u2C94\u2C96\u2C98\u2C9A\u2C9C\u2C9E\u2CA0\u2CA2\u2CA4\u2CA6\u2CA8\u2CAA\u2CAC\u2CAE\u2CB0\u2CB2\u2CB4\u2CB6\u2CB8\u2CBA\u2CBC\u2CBE\u2CC0\u2CC2\u2CC4\u2CC6\u2CC8\u2CCA\u2CCC\u2CCE\u2CD0\u2CD2\u2CD4\u2CD6\u2CD8\u2CDA\u2CDC\u2CDE\u2CE0\u2CE2\u2CEB\u2CED\u2CF2\uA640\uA642\uA644\uA646\uA648\uA64A\uA64C\uA64E\uA650\uA652\uA654\uA656\uA658\uA65A\uA65C\uA65E\uA660\uA662\uA664\uA666\uA668\uA66A\uA66C\uA680\uA682\uA684\uA686\uA688\uA68A\uA68C\uA68E\uA690\uA692\uA694\uA696\uA722\uA724\uA726\uA728\uA72A\uA72C\uA72E\uA732\uA734\uA736\uA738\uA73A\uA73C\uA73E\uA740\uA742\uA744\uA746\uA748\uA74A\uA74C\uA74E\uA750\uA752\uA754\uA756\uA758\uA75A\uA75C\uA75E\uA760\uA762\uA764\uA766\uA768\uA76A\uA76C\uA76E\uA779\uA77B\uA77D-\uA77E\uA780\uA782\uA784\uA786\uA78B\uA78D\uA790\uA792\uA7A0\uA7A2\uA7A4\uA7A6\uA7A8\uA7AA\uFF21-\uFF3A]/,Hn=Ve([["A","Z"],["\xC0","\xD6"],["\xD8","\xDE"],"\u0100","\u0102","\u0104","\u0106","\u0108","\u010A","\u010C","\u010E","\u0110","\u0112","\u0114","\u0116","\u0118","\u011A","\u011C","\u011E","\u0120","\u0122","\u0124","\u0126","\u0128","\u012A","\u012C","\u012E","\u0130","\u0132","\u0134","\u0136","\u0139","\u013B","\u013D","\u013F","\u0141","\u0143","\u0145","\u0147","\u014A","\u014C","\u014E","\u0150","\u0152","\u0154","\u0156","\u0158","\u015A","\u015C","\u015E","\u0160","\u0162","\u0164","\u0166","\u0168","\u016A","\u016C","\u016E","\u0170","\u0172","\u0174","\u0176",["\u0178","\u0179"],"\u017B","\u017D",["\u0181","\u0182"],"\u0184",["\u0186","\u0187"],["\u0189","\u018B"],["\u018E","\u0191"],["\u0193","\u0194"],["\u0196","\u0198"],["\u019C","\u019D"],["\u019F","\u01A0"],"\u01A2","\u01A4",["\u01A6","\u01A7"],"\u01A9","\u01AC",["\u01AE","\u01AF"],["\u01B1","\u01B3"],"\u01B5",["\u01B7","\u01B8"],"\u01BC","\u01C4","\u01C7","\u01CA","\u01CD","\u01CF","\u01D1","\u01D3","\u01D5","\u01D7","\u01D9","\u01DB","\u01DE","\u01E0","\u01E2","\u01E4","\u01E6","\u01E8","\u01EA","\u01EC","\u01EE","\u01F1","\u01F4",["\u01F6","\u01F8"],"\u01FA","\u01FC","\u01FE","\u0200","\u0202","\u0204","\u0206","\u0208","\u020A","\u020C","\u020E","\u0210","\u0212","\u0214","\u0216","\u0218","\u021A","\u021C","\u021E","\u0220","\u0222","\u0224","\u0226","\u0228","\u022A","\u022C","\u022E","\u0230","\u0232",["\u023A","\u023B"],["\u023D","\u023E"],"\u0241",["\u0243","\u0246"],"\u0248","\u024A","\u024C","\u024E","\u0370","\u0372","\u0376","\u0386",["\u0388","\u038A"],"\u038C",["\u038E","\u038F"],["\u0391","\u03A1"],["\u03A3","\u03AB"],"\u03CF",["\u03D2","\u03D4"],"\u03D8","\u03DA","\u03DC","\u03DE","\u03E0","\u03E2","\u03E4","\u03E6","\u03E8","\u03EA","\u03EC","\u03EE","\u03F4","\u03F7",["\u03F9","\u03FA"],["\u03FD","\u042F"],"\u0460","\u0462","\u0464","\u0466","\u0468","\u046A","\u046C","\u046E","\u0470","\u0472","\u0474","\u0476","\u0478","\u047A","\u047C","\u047E","\u0480","\u048A","\u048C","\u048E","\u0490","\u0492","\u0494","\u0496","\u0498","\u049A","\u049C","\u049E","\u04A0","\u04A2","\u04A4","\u04A6","\u04A8","\u04AA","\u04AC","\u04AE","\u04B0","\u04B2","\u04B4","\u04B6","\u04B8","\u04BA","\u04BC","\u04BE",["\u04C0","\u04C1"],"\u04C3","\u04C5","\u04C7","\u04C9","\u04CB","\u04CD","\u04D0","\u04D2","\u04D4","\u04D6","\u04D8","\u04DA","\u04DC","\u04DE","\u04E0","\u04E2","\u04E4","\u04E6","\u04E8","\u04EA","\u04EC","\u04EE","\u04F0","\u04F2","\u04F4","\u04F6","\u04F8","\u04FA","\u04FC","\u04FE","\u0500","\u0502","\u0504","\u0506","\u0508","\u050A","\u050C","\u050E","\u0510","\u0512","\u0514","\u0516","\u0518","\u051A","\u051C","\u051E","\u0520","\u0522","\u0524","\u0526",["\u0531","\u0556"],["\u10A0","\u10C5"],"\u10C7","\u10CD","\u1E00","\u1E02","\u1E04","\u1E06","\u1E08","\u1E0A","\u1E0C","\u1E0E","\u1E10","\u1E12","\u1E14","\u1E16","\u1E18","\u1E1A","\u1E1C","\u1E1E","\u1E20","\u1E22","\u1E24","\u1E26","\u1E28","\u1E2A","\u1E2C","\u1E2E","\u1E30","\u1E32","\u1E34","\u1E36","\u1E38","\u1E3A","\u1E3C","\u1E3E","\u1E40","\u1E42","\u1E44","\u1E46","\u1E48","\u1E4A","\u1E4C","\u1E4E","\u1E50","\u1E52","\u1E54","\u1E56","\u1E58","\u1E5A","\u1E5C","\u1E5E","\u1E60","\u1E62","\u1E64","\u1E66","\u1E68","\u1E6A","\u1E6C","\u1E6E","\u1E70","\u1E72","\u1E74","\u1E76","\u1E78","\u1E7A","\u1E7C","\u1E7E","\u1E80","\u1E82","\u1E84","\u1E86","\u1E88","\u1E8A","\u1E8C","\u1E8E","\u1E90","\u1E92","\u1E94","\u1E9E","\u1EA0","\u1EA2","\u1EA4","\u1EA6","\u1EA8","\u1EAA","\u1EAC","\u1EAE","\u1EB0","\u1EB2","\u1EB4","\u1EB6","\u1EB8","\u1EBA","\u1EBC","\u1EBE","\u1EC0","\u1EC2","\u1EC4","\u1EC6","\u1EC8","\u1ECA","\u1ECC","\u1ECE","\u1ED0","\u1ED2","\u1ED4","\u1ED6","\u1ED8","\u1EDA","\u1EDC","\u1EDE","\u1EE0","\u1EE2","\u1EE4","\u1EE6","\u1EE8","\u1EEA","\u1EEC","\u1EEE","\u1EF0","\u1EF2","\u1EF4","\u1EF6","\u1EF8","\u1EFA","\u1EFC","\u1EFE",["\u1F08","\u1F0F"],["\u1F18","\u1F1D"],["\u1F28","\u1F2F"],["\u1F38","\u1F3F"],["\u1F48","\u1F4D"],"\u1F59","\u1F5B","\u1F5D","\u1F5F",["\u1F68","\u1F6F"],["\u1FB8","\u1FBB"],["\u1FC8","\u1FCB"],["\u1FD8","\u1FDB"],["\u1FE8","\u1FEC"],["\u1FF8","\u1FFB"],"\u2102","\u2107",["\u210B","\u210D"],["\u2110","\u2112"],"\u2115",["\u2119","\u211D"],"\u2124","\u2126","\u2128",["\u212A","\u212D"],["\u2130","\u2133"],["\u213E","\u213F"],"\u2145","\u2183",["\u2C00","\u2C2E"],"\u2C60",["\u2C62","\u2C64"],"\u2C67","\u2C69","\u2C6B",["\u2C6D","\u2C70"],"\u2C72","\u2C75",["\u2C7E","\u2C80"],"\u2C82","\u2C84","\u2C86","\u2C88","\u2C8A","\u2C8C","\u2C8E","\u2C90","\u2C92","\u2C94","\u2C96","\u2C98","\u2C9A","\u2C9C","\u2C9E","\u2CA0","\u2CA2","\u2CA4","\u2CA6","\u2CA8","\u2CAA","\u2CAC","\u2CAE","\u2CB0","\u2CB2","\u2CB4","\u2CB6","\u2CB8","\u2CBA","\u2CBC","\u2CBE","\u2CC0","\u2CC2","\u2CC4","\u2CC6","\u2CC8","\u2CCA","\u2CCC","\u2CCE","\u2CD0","\u2CD2","\u2CD4","\u2CD6","\u2CD8","\u2CDA","\u2CDC","\u2CDE","\u2CE0","\u2CE2","\u2CEB","\u2CED","\u2CF2","\uA640","\uA642","\uA644","\uA646","\uA648","\uA64A","\uA64C","\uA64E","\uA650","\uA652","\uA654","\uA656","\uA658","\uA65A","\uA65C","\uA65E","\uA660","\uA662","\uA664","\uA666","\uA668","\uA66A","\uA66C","\uA680","\uA682","\uA684","\uA686","\uA688","\uA68A","\uA68C","\uA68E","\uA690","\uA692","\uA694","\uA696","\uA722","\uA724","\uA726","\uA728","\uA72A","\uA72C","\uA72E","\uA732","\uA734","\uA736","\uA738","\uA73A","\uA73C","\uA73E","\uA740","\uA742","\uA744","\uA746","\uA748","\uA74A","\uA74C","\uA74E","\uA750","\uA752","\uA754","\uA756","\uA758","\uA75A","\uA75C","\uA75E","\uA760","\uA762","\uA764","\uA766","\uA768","\uA76A","\uA76C","\uA76E","\uA779","\uA77B",["\uA77D","\uA77E"],"\uA780","\uA782","\uA784","\uA786","\uA78B","\uA78D","\uA790","\uA792","\uA7A0","\uA7A2","\uA7A4","\uA7A6","\uA7A8","\uA7AA",["\uFF21","\uFF3A"]],!1,!1),ns=/^[\u16EE-\u16F0\u2160-\u2182\u2185-\u2188\u3007\u3021-\u3029\u3038-\u303A\uA6E6-\uA6EF]/,Mi=Ve([["\u16EE","\u16F0"],["\u2160","\u2182"],["\u2185","\u2188"],"\u3007",["\u3021","\u3029"],["\u3038","\u303A"],["\uA6E6","\uA6EF"]],!1,!1),Tr=/^[0-9\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0BE6-\u0BEF\u0C66-\u0C6F\u0CE6-\u0CEF\u0D66-\u0D6F\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F29\u1040-\u1049\u1090-\u1099\u17E0-\u17E9\u1810-\u1819\u1946-\u194F\u19D0-\u19D9\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\uA620-\uA629\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19]/,rs=Ve([["0","9"],["\u0660","\u0669"],["\u06F0","\u06F9"],["\u07C0","\u07C9"],["\u0966","\u096F"],["\u09E6","\u09EF"],["\u0A66","\u0A6F"],["\u0AE6","\u0AEF"],["\u0B66","\u0B6F"],["\u0BE6","\u0BEF"],["\u0C66","\u0C6F"],["\u0CE6","\u0CEF"],["\u0D66","\u0D6F"],["\u0E50","\u0E59"],["\u0ED0","\u0ED9"],["\u0F20","\u0F29"],["\u1040","\u1049"],["\u1090","\u1099"],["\u17E0","\u17E9"],["\u1810","\u1819"],["\u1946","\u194F"],["\u19D0","\u19D9"],["\u1A80","\u1A89"],["\u1A90","\u1A99"],["\u1B50","\u1B59"],["\u1BB0","\u1BB9"],["\u1C40","\u1C49"],["\u1C50","\u1C59"],["\uA620","\uA629"],["\uA8D0","\uA8D9"],["\uA900","\uA909"],["\uA9D0","\uA9D9"],["\uAA50","\uAA59"],["\uABF0","\uABF9"],["\uFF10","\uFF19"]],!1,!1),P=0,rt=0,yi=[{line:1,column:1}],Wt=0,Ie=[],F=0,re;if("startRule"in C){if(!(C.startRule in k))throw new Error(`Can't start parsing from rule "`+C.startRule+'".');vt=k[C.startRule]}function hn(){return O.substring(rt,P)}function ui(){return Fs(rt,P)}function qn(p,S){throw S=S!==void 0?S:Fs(rt,P),ci([Zt(p)],O.substring(rt,P),S)}function xr(p,S){throw S=S!==void 0?S:Fs(rt,P),zn(p,S)}function gt(p,S){return{type:"literal",text:p,ignoreCase:S}}function Ve(p,S,x){return{type:"class",parts:p,inverted:S,ignoreCase:x}}function Te(){return{type:"any"}}function pe(){return{type:"end"}}function Zt(p){return{type:"other",description:p}}function Or(p){var S=yi[p],x;if(S)return S;for(x=p-1;!yi[x];)x--;for(S=yi[x],S={line:S.line,column:S.column};x<p;)O.charCodeAt(x)===10?(S.line++,S.column=1):S.column++,x++;return yi[p]=S,S}function Fs(p,S){var x=Or(p),I=Or(S);return{start:{offset:p,line:x.line,column:x.column},end:{offset:S,line:I.line,column:I.column}}}function q(p){P<Wt||(P>Wt&&(Wt=P,Ie=[]),Ie.push(p))}function zn(p,S){return new Ct(p,null,null,S)}function ci(p,S,x){return new Ct(Ct.buildMessage(p,S),p,S,x)}function Ds(){var p,S;if(p=[],S=Di(),S!==f)for(;S!==f;)p.push(S),S=Di();else p=f;return p}function Di(){var p,S,x,I,G,z,nt,jt,Qt,$e,Se,$n,qr;return p=P,S=ct(),S!==f?(O.substr(P,6).toLowerCase()===At?(x=O.substr(P,6),P+=6):(x=f,F===0&&q(R)),x===f&&(x=null),x!==f?(I=ct(),I!==f?(O.substr(P,5).toLowerCase()===V?(G=O.substr(P,5),P+=5):(G=f,F===0&&q(J)),G===f&&(O.substr(P,7).toLowerCase()===et?(G=O.substr(P,7),P+=7):(G=f,F===0&&q(D))),G!==f?(z=ct(),z!==f?(nt=We(),nt===f&&(nt=null),nt!==f?(jt=ct(),jt!==f?(O.charCodeAt(P)===123?(Qt=_,P++):(Qt=f,F===0&&q(c)),Qt!==f?($e=Vi(),$e===f&&($e=null),$e!==f?(Se=ct(),Se!==f?(O.charCodeAt(P)===125?($n=zt,P++):($n=f,F===0&&q(qe)),$n!==f?(qr=ct(),qr!==f?(rt=p,S=Pt(x,G,nt,$e),p=S):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f),p}function Vi(){var p,S,x,I,G,z,nt,jt,Qt,$e,Se;if(p=P,S=ct(),S!==f)if(x=os(),x!==f)if(I=ct(),I!==f)if(O.charCodeAt(P)===59?(G=Qi,P++):(G=f,F===0&&q(N)),G===f&&(G=null),G!==f){for(z=[],nt=P,jt=ct(),jt!==f?(Qt=os(),Qt!==f?($e=ct(),$e!==f?(O.charCodeAt(P)===59?(Se=Qi,P++):(Se=f,F===0&&q(N)),Se===f&&(Se=null),Se!==f?(rt=nt,jt=pi(x,Qt),nt=jt):(P=nt,nt=f)):(P=nt,nt=f)):(P=nt,nt=f)):(P=nt,nt=f);nt!==f;)z.push(nt),nt=P,jt=ct(),jt!==f?(Qt=os(),Qt!==f?($e=ct(),$e!==f?(O.charCodeAt(P)===59?(Se=Qi,P++):(Se=f,F===0&&q(N)),Se===f&&(Se=null),Se!==f?(rt=nt,jt=pi(x,Qt),nt=jt):(P=nt,nt=f)):(P=nt,nt=f)):(P=nt,nt=f)):(P=nt,nt=f);z!==f?(rt=p,S=Js(x,z),p=S):(P=p,p=f)}else P=p,p=f;else P=p,p=f;else P=p,p=f;else P=p,p=f;return p}function os(){var p,S,x,I,G,z;return p=P,S=We(),S!==f?(x=ct(),x!==f?(O.charCodeAt(P)===61?(I=mi,P++):(I=f,F===0&&q(Rt)),I!==f?(G=ct(),G!==f?(z=We(),z!==f?(rt=p,S=ri(S,z),p=S):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f),p===f&&(p=Wi(),p===f&&(p=Lr(),p===f&&(p=Et(),p===f&&(p=Fr(),p===f&&(p=P,S=We(),S!==f?(O.charCodeAt(P)===61?(x=mi,P++):(x=f,F===0&&q(Rt)),x!==f?(I=We(),I!==f?(S=[S,x,I],p=S):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)))))),p}function Wi(){var p,S,x;return p=P,O.substr(P,5).toLowerCase()===V?(S=O.substr(P,5),P+=5):(S=f,F===0&&q(J)),S===f&&(O.substr(P,4).toLowerCase()===$i?(S=O.substr(P,4),P+=4):(S=f,F===0&&q(yt)),S===f&&(O.substr(P,4).toLowerCase()===Zs?(S=O.substr(P,4),P+=4):(S=f,F===0&&q(xt)))),S!==f?(x=Ci(),x!==f?(rt=p,S=wn(S,x),p=S):(P=p,p=f)):(P=p,p=f),p}function Ci(){var p,S,x,I,G,z,nt,jt,Qt;return p=P,S=ct(),S!==f?(O.charCodeAt(P)===91?(x=ys,P++):(x=f,F===0&&q(Cs)),x!==f?(I=ct(),I!==f?(G=Br(),G===f&&(G=null),G!==f?(z=ct(),z!==f?(O.charCodeAt(P)===93?(nt=_s,P++):(nt=f,F===0&&q(at)),nt!==f?(jt=ct(),jt!==f?(Qt=Ci(),Qt===f&&(Qt=null),Qt!==f?(rt=p,S=vn(G,Qt),p=S):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f),p}function Br(){var p,S,x,I,G,z,nt,jt;return p=P,S=ct(),S!==f?(x=We(),x!==f?(I=P,G=ct(),G!==f?(O.charCodeAt(P)===61?(z=mi,P++):(z=f,F===0&&q(Rt)),z!==f?(nt=ct(),nt!==f?(jt=We(),jt!==f?(rt=I,G=w(x,jt),I=G):(P=I,I=f)):(P=I,I=f)):(P=I,I=f)):(P=I,I=f),I===f&&(I=null),I!==f?(G=ct(),G!==f?(O.charCodeAt(P)===44?(z=Pi,P++):(z=f,F===0&&q(As)),z===f&&(O.charCodeAt(P)===59?(z=Qi,P++):(z=f,F===0&&q(N))),z===f&&(z=null),z!==f?(nt=Br(),nt===f&&(nt=null),nt!==f?(rt=p,S=Pr(x,I,nt),p=S):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f),p}function Lr(){var p,S,x,I;return p=P,S=Et(),S===f&&(S=Qe()),S!==f?(x=Rs(),x!==f?(I=Ci(),I===f&&(I=null),I!==f?(rt=p,S=Sr(S,x,I),p=S):(P=p,p=f)):(P=p,p=f)):(P=p,p=f),p}function Rs(){var p,S,x,I,G,z,nt;return p=P,S=ct(),S!==f?(O.substr(P,2)===In?(x=In,P+=2):(x=f,F===0&&q(tn)),x===f&&(O.substr(P,2)===st?(x=st,P+=2):(x=f,F===0&&q(be))),x!==f?(I=ct(),I!==f?(G=Et(),G===f&&(G=Qe()),G!==f?(z=ct(),z!==f?(nt=Rs(),nt===f&&(nt=null),nt!==f?(rt=p,S=X(x,G,nt),p=S):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f),p}function Fr(){var p,S,x;return p=P,S=Qe(),S!==f?(x=Ci(),x===f&&(x=null),x!==f?(rt=p,S=Dt(S,x),p=S):(P=p,p=f)):(P=p,p=f),p}function Qe(){var p,S,x;return p=P,S=We(),S!==f?(x=me(),x===f&&(x=null),x!==f?(rt=p,S=M(S,x),p=S):(P=p,p=f)):(P=p,p=f),p}function me(){var p,S,x,I,G,z;return F++,p=P,O.charCodeAt(P)===58?(S=U,P++):(S=f,F===0&&q(W)),S!==f?(x=We(),x!==f?(I=P,O.charCodeAt(P)===58?(G=U,P++):(G=f,F===0&&q(W)),G!==f?(z=ce(),z!==f?(rt=I,G=K(x,z),I=G):(P=I,I=f)):(P=I,I=f),I===f&&(I=null),I!==f?(rt=p,S=$(x,I),p=S):(P=p,p=f)):(P=p,p=f)):(P=p,p=f),p===f&&(p=P,O.charCodeAt(P)===58?(S=U,P++):(S=f,F===0&&q(W)),S!==f?(x=ce(),x!==f?(rt=p,S=it(x),p=S):(P=p,p=f)):(P=p,p=f)),F--,p===f&&(S=f,F===0&&q(Y)),p}function Et(){var p,S,x,I,G,z;return p=P,S=P,O.substr(P,8).toLowerCase()===ht?(x=O.substr(P,8),P+=8):(x=f,F===0&&q(v)),x!==f?(I=ct(),I!==f?(G=We(),G===f&&(G=null),G!==f?(z=ct(),z!==f?(rt=S,x=L(G),S=x):(P=S,S=f)):(P=S,S=f)):(P=S,S=f)):(P=S,S=f),S===f&&(S=null),S!==f?(O.charCodeAt(P)===123?(x=_,P++):(x=f,F===0&&q(c)),x!==f?(I=Vi(),I===f&&(I=null),I!==f?(G=ct(),G!==f?(O.charCodeAt(P)===125?(z=zt,P++):(z=f,F===0&&q(qe)),z!==f?(rt=p,S=j(S,I),p=S):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f),p}function ce(){var p;return O.charCodeAt(P)===110?(p=Es,P++):(p=f,F===0&&q(we)),p===f&&(O.substr(P,2)===yr?(p=yr,P+=2):(p=f,F===0&&q(Ut)),p===f&&(O.charCodeAt(P)===101?(p=Nt,P++):(p=f,F===0&&q(lo)),p===f&&(O.substr(P,2)===$t?(p=$t,P+=2):(p=f,F===0&&q(Cr)),p===f&&(O.charCodeAt(P)===115?(p=ho,P++):(p=f,F===0&&q(en)),p===f&&(O.substr(P,2)===Tn?(p=Tn,P+=2):(p=f,F===0&&q(he)),p===f&&(O.charCodeAt(P)===119?(p=xn,P++):(p=f,F===0&&q(On)),p===f&&(O.substr(P,2)===fe?(p=fe,P+=2):(p=f,F===0&&q(Yt))))))))),p}function We(){var p;return p=Dr(),p===f&&(p=un(),p===f&&(p=Rr(),p===f&&(p=Ri(),p===f&&(p=Un())))),p}function Dr(){var p,S,x,I;if(F++,p=P,S=Pe(),S!==f){for(x=[],I=ut();I!==f;)x.push(I),I=ut();x!==f?(rt=p,S=uo(S,x),p=S):(P=p,p=f)}else P=p,p=f;return F--,p===f&&(S=f,F===0&&q(Xi)),p}function un(){var p,S,x;return p=P,S=Rr(),S!==f?(x=Dr(),x!==f?(rt=p,S=Ki(S,x),p=S):(P=p,p=f)):(P=p,p=f),p}function Pe(){var p;return p=Vr(),p===f&&(O.charCodeAt(P)===36?(p=Bi,P++):(p=f,F===0&&q(Li)),p===f&&(O.charCodeAt(P)===95?(p=co,P++):(p=f,F===0&&q(bs)))),p}function ut(){var p;return p=Pe(),p===f&&(p=wi()),p}function Rr(){var p,S,x,I,G,z,nt,jt,Qt;if(F++,p=P,S=P,O.charCodeAt(P)===45?(x=ws,P++):(x=f,F===0&&q(nn)),x===f&&(x=null),x!==f){if(I=P,O.charCodeAt(P)===46?(G=Gi,P++):(G=f,F===0&&q(Bn)),G!==f){if(z=[],Yi.test(O.charAt(P))?(nt=O.charAt(P),P++):(nt=f,F===0&&q(Ji)),nt!==f)for(;nt!==f;)z.push(nt),Yi.test(O.charAt(P))?(nt=O.charAt(P),P++):(nt=f,F===0&&q(Ji));else z=f;z!==f?(G=[G,z],I=G):(P=I,I=f)}else P=I,I=f;if(I===f){if(I=P,G=[],Yi.test(O.charAt(P))?(z=O.charAt(P),P++):(z=f,F===0&&q(Ji)),z!==f)for(;z!==f;)G.push(z),Yi.test(O.charAt(P))?(z=O.charAt(P),P++):(z=f,F===0&&q(Ji));else G=f;if(G!==f){if(z=P,O.charCodeAt(P)===46?(nt=Gi,P++):(nt=f,F===0&&q(Bn)),nt!==f){for(jt=[],Yi.test(O.charAt(P))?(Qt=O.charAt(P),P++):(Qt=f,F===0&&q(Ji));Qt!==f;)jt.push(Qt),Yi.test(O.charAt(P))?(Qt=O.charAt(P),P++):(Qt=f,F===0&&q(Ji));jt!==f?(nt=[nt,jt],z=nt):(P=z,z=f)}else P=z,z=f;z===f&&(z=null),z!==f?(G=[G,z],I=G):(P=I,I=f)}else P=I,I=f}I!==f?(x=[x,I],S=x):(P=S,S=f)}else P=S,S=f;return S!==f&&(rt=p,S=Ar(S)),p=S,F--,p===f&&(S=f,F===0&&q(sn)),p}function Un(){var p,S;return p=P,S=Ns(),S!==f&&(rt=p,S=ia(S)),p=S,p}function Ns(){var p,S,x,I;if(p=P,O.charCodeAt(P)===60?(S=Ge,P++):(S=f,F===0&&q(Mt)),S!==f){for(x=[],I=Nr(),I===f&&(I=Ns());I!==f;)x.push(I),I=Nr(),I===f&&(I=Ns());x!==f?(O.charCodeAt(P)===62?(I=vs,P++):(I=f,F===0&&q(Si)),I!==f?(rt=p,S=Is(x),p=S):(P=p,p=f)):(P=p,p=f)}else P=p,p=f;return p}function Nr(){var p,S,x,I,G;if(p=P,S=[],x=P,I=P,F++,O.charCodeAt(P)===62?(G=vs,P++):(G=f,F===0&&q(Si)),G===f&&(O.charCodeAt(P)===60?(G=Ge,P++):(G=f,F===0&&q(Mt))),F--,G===f?I=void 0:(P=I,I=f),I!==f?(O.length>P?(G=O.charAt(P),P++):(G=f,F===0&&q(ze)),G!==f?(rt=x,I=Zi(G),x=I):(P=x,x=f)):(P=x,x=f),x!==f)for(;x!==f;)S.push(x),x=P,I=P,F++,O.charCodeAt(P)===62?(G=vs,P++):(G=f,F===0&&q(Si)),G===f&&(O.charCodeAt(P)===60?(G=Ge,P++):(G=f,F===0&&q(Mt))),F--,G===f?I=void 0:(P=I,I=f),I!==f?(O.length>P?(G=O.charAt(P),P++):(G=f,F===0&&q(ze)),G!==f?(rt=x,I=Zi(G),x=I):(P=x,x=f)):(P=x,x=f);else S=f;return S!==f&&(rt=p,S=Vt(S)),p=S,p}function Ri(){var p,S,x,I;if(p=P,O.charCodeAt(P)===34?(S=Ln,P++):(S=f,F===0&&q(Fn)),S!==f){for(x=[],I=as();I!==f;)x.push(I),I=as();x!==f?(O.charCodeAt(P)===34?(I=Ln,P++):(I=f,F===0&&q(Fn)),I!==f?(rt=p,S=go(x),p=S):(P=p,p=f)):(P=p,p=f)}else P=p,p=f;return p}function as(){var p,S,x;return p=cn(),p===f&&(p=P,S=P,F++,O.charCodeAt(P)===34?(x=Ln,P++):(x=f,F===0&&q(Fn)),x===f&&(x=Gr()),F--,x===f?S=void 0:(P=S,S=f),S!==f?(x=Mr(),x!==f?(rt=p,S=Dn(),p=S):(P=p,p=f)):(P=p,p=f),p===f&&(p=Ai())),p}function cn(){var p,S,x,I;return p=P,S=P,O.charCodeAt(P)===92?(x=Jt,P++):(x=f,F===0&&q(Ft)),x!==f?(O.length>P?(I=O.charAt(P),P++):(I=f,F===0&&q(ze)),I!==f?(x=[x,I],S=x):(P=S,S=f)):(P=S,S=f),S!==f&&(rt=p,S=Ts(S)),p=S,p}function Ai(){var p,S,x;return p=P,O.charCodeAt(P)===92?(S=Jt,P++):(S=f,F===0&&q(Ft)),S!==f?(x=kr(),x!==f?(rt=p,S=oi(),p=S):(P=p,p=f)):(P=p,p=f),p}function Gr(){var p;return fo.test(O.charAt(P))?(p=O.charAt(P),P++):(p=f,F===0&&q(rn)),p}function kr(){var p,S;return F++,O.charCodeAt(P)===10?(p=xs,P++):(p=f,F===0&&q(po)),p===f&&(O.substr(P,2)===Rn?(p=Rn,P+=2):(p=f,F===0&&q(mo)),p===f&&(O.charCodeAt(P)===13?(p=Po,P++):(p=f,F===0&&q(br)),p===f&&(O.charCodeAt(P)===8232?(p=Nn,P++):(p=f,F===0&&q(on)),p===f&&(O.charCodeAt(P)===8233?(p=So,P++):(p=f,F===0&&q(yo)))))),F--,p===f&&(S=f,F===0&&q(Er)),p}function Mr(){var p;return O.length>P?(p=O.charAt(P),P++):(p=f,F===0&&q(ze)),p}function Gs(){var p,S,x;if(p=P,S=[],x=Ei(),x!==f)for(;x!==f;)S.push(x),x=Ei();else S=f;return S!==f&&(rt=p,S=go(S)),p=S,p}function Ei(){var p,S,x;return Gt.test(O.charAt(P))?(p=O.charAt(P),P++):(p=f,F===0&&q(Gn)),p===f&&(p=P,O.substr(P,2)===Co?(S=Co,P+=2):(S=f,F===0&&q(sa)),S!==f&&(rt=p,S=na()),p=S,p===f&&(p=P,O.charCodeAt(P)===92?(S=Jt,P++):(S=f,F===0&&q(Ft)),S!==f?(x=Bt(),x!==f?(rt=p,S=oi(),p=S):(P=p,p=f)):(P=p,p=f),p===f&&(p=P,O.charCodeAt(P)===92?(S=Jt,P++):(S=f,F===0&&q(Ft)),S!==f&&(rt=p,S=ra()),p=S))),p}function jn(){var p,S;return F++,p=Qn(),p===f&&(p=ks(),p===f&&(p=bi())),F--,p===f&&(S=f,F===0&&q(oa)),p}function Qn(){var p,S,x,I,G,z;if(F++,p=P,O.substr(P,2)===an?(S=an,P+=2):(S=f,F===0&&q(Ue)),S!==f){for(x=[],I=P,G=P,F++,O.substr(P,2)===ke?(z=ke,P+=2):(z=f,F===0&&q(Os)),F--,z===f?G=void 0:(P=G,G=f),G!==f?(O.length>P?(z=O.charAt(P),P++):(z=f,F===0&&q(ze)),z!==f?(rt=I,G=ft(z),I=G):(P=I,I=f)):(P=I,I=f);I!==f;)x.push(I),I=P,G=P,F++,O.substr(P,2)===ke?(z=ke,P+=2):(z=f,F===0&&q(Os)),F--,z===f?G=void 0:(P=G,G=f),G!==f?(O.length>P?(z=O.charAt(P),P++):(z=f,F===0&&q(ze)),z!==f?(rt=I,G=ft(z),I=G):(P=I,I=f)):(P=I,I=f);x!==f?(O.substr(P,2)===ke?(I=ke,P+=2):(I=f,F===0&&q(Os)),I!==f?(rt=p,S=Me(x),p=S):(P=p,p=f)):(P=p,p=f)}else P=p,p=f;return F--,p===f&&(S=f,F===0&&q(_i)),p}function ks(){var p,S,x,I,G,z;if(F++,p=P,O.substr(P,2)===ai?(S=ai,P+=2):(S=f,F===0&&q(ts)),S!==f){for(x=[],I=P,G=P,F++,es.test(O.charAt(P))?(z=O.charAt(P),P++):(z=f,F===0&&q(is)),F--,z===f?G=void 0:(P=G,G=f),G!==f?(O.length>P?(z=O.charAt(P),P++):(z=f,F===0&&q(ze)),z!==f?(rt=I,G=Zi(z),I=G):(P=I,I=f)):(P=I,I=f);I!==f;)x.push(I),I=P,G=P,F++,es.test(O.charAt(P))?(z=O.charAt(P),P++):(z=f,F===0&&q(is)),F--,z===f?G=void 0:(P=G,G=f),G!==f?(O.length>P?(z=O.charAt(P),P++):(z=f,F===0&&q(ze)),z!==f?(rt=I,G=Zi(z),I=G):(P=I,I=f)):(P=I,I=f);x!==f?(es.test(O.charAt(P))?(I=O.charAt(P),P++):(I=f,F===0&&q(is)),I===f&&(I=null),I!==f?(rt=p,S=wr(x),p=S):(P=p,p=f)):(P=p,p=f)}else P=p,p=f;return F--,p===f&&(S=f,F===0&&q(kn)),p}function bi(){var p,S,x,I,G,z;if(F++,p=P,O.charCodeAt(P)===35?(S=ue,P++):(S=f,F===0&&q(ve)),S!==f){for(x=[],I=P,G=P,F++,es.test(O.charAt(P))?(z=O.charAt(P),P++):(z=f,F===0&&q(is)),F--,z===f?G=void 0:(P=G,G=f),G!==f?(O.length>P?(z=O.charAt(P),P++):(z=f,F===0&&q(ze)),z!==f?(rt=I,G=Zi(z),I=G):(P=I,I=f)):(P=I,I=f);I!==f;)x.push(I),I=P,G=P,F++,es.test(O.charAt(P))?(z=O.charAt(P),P++):(z=f,F===0&&q(is)),F--,z===f?G=void 0:(P=G,G=f),G!==f?(O.length>P?(z=O.charAt(P),P++):(z=f,F===0&&q(ze)),z!==f?(rt=I,G=Zi(z),I=G):(P=I,I=f)):(P=I,I=f);x!==f?(es.test(O.charAt(P))?(I=O.charAt(P),P++):(I=f,F===0&&q(is)),I===f&&(I=null),I!==f?(rt=p,S=wr(x),p=S):(P=p,p=f)):(P=p,p=f)}else P=p,p=f;return F--,p===f&&(S=f,F===0&&q(vr)),p}function ct(){var p,S;for(F++,p=[],S=ls(),S===f&&(S=jn());S!==f;)p.push(S),S=ls(),S===f&&(S=jn());return F--,p===f&&(S=f,F===0&&q(li)),p}function Bt(){var p,S;if(p=[],je.test(O.charAt(P))?(S=O.charAt(P),P++):(S=f,F===0&&q(Bs)),S!==f)for(;S!==f;)p.push(S),je.test(O.charAt(P))?(S=O.charAt(P),P++):(S=f,F===0&&q(Bs));else p=f;return p}function ls(){var p,S;if(p=[],ki.test(O.charAt(P))?(S=O.charAt(P),P++):(S=f,F===0&&q(Xt)),S===f&&(S=Bt()),S!==f)for(;S!==f;)p.push(S),ki.test(O.charAt(P))?(S=O.charAt(P),P++):(S=f,F===0&&q(Xt)),S===f&&(S=Bt());else p=f;return p}function Vr(){var p;return p=Hr(),p===f&&(p=Ao(),p===f&&(p=xe(),p===f&&(p=dn(),p===f&&(p=Wr(),p===f&&(p=hs()))))),p}function Ao(){var p;return Mn.test(O.charAt(P))?(p=O.charAt(P),P++):(p=f,F===0&&q(ss)),p}function dn(){var p;return Vn.test(O.charAt(P))?(p=O.charAt(P),P++):(p=f,F===0&&q(Ir)),p}function Wr(){var p;return hi.test(O.charAt(P))?(p=O.charAt(P),P++):(p=f,F===0&&q(Fi)),p}function xe(){var p;return ln.test(O.charAt(P))?(p=O.charAt(P),P++):(p=f,F===0&&q(Ls)),p}function Hr(){var p;return Wn.test(O.charAt(P))?(p=O.charAt(P),P++):(p=f,F===0&&q(Hn)),p}function hs(){var p;return ns.test(O.charAt(P))?(p=O.charAt(P),P++):(p=f,F===0&&q(Mi)),p}function wi(){var p;return Tr.test(O.charAt(P))?(p=O.charAt(P),P++):(p=f,F===0&&q(rs)),p}if(re=vt(),re!==f&&P===O.length)return re;throw re!==f&&P<O.length&&q(pe()),ci(Ie,Wt<O.length?O.charAt(Wt):null,Wt<O.length?Fs(Wt,Wt+1):Fs(Wt,Wt))}ae.exports={SyntaxError:Ct,parse:ot}},79002:ae=>{ae.exports={rgb2hsl:pt,rgb2hsv:Ct,rgb2hwb:ot,rgb2cmyk:O,rgb2keyword:C,rgb2xyz:f,rgb2lab:k,rgb2lch:vt,hsl2rgb:At,hsl2hsv:R,hsl2hwb:V,hsl2cmyk:J,hsl2keyword:et,hsv2rgb:D,hsv2hsl:_,hsv2hwb:c,hsv2cmyk:zt,hsv2keyword:qe,hwb2rgb:Pt,hwb2hsl:Qi,hwb2hsv:N,hwb2cmyk:pi,hwb2keyword:Js,cmyk2rgb:mi,cmyk2hsl:Rt,cmyk2hsv:ri,cmyk2hwb:$i,cmyk2keyword:yt,keyword2rgb:Pi,keyword2hsl:As,keyword2hsv:Pr,keyword2hwb:Sr,keyword2cmyk:In,keyword2lab:tn,keyword2xyz:st,xyz2rgb:Zs,xyz2lab:xt,xyz2lch:wn,lab2xyz:ys,lab2rgb:_s,lab2lch:Cs,lch2lab:at,lch2xyz:vn,lch2rgb:w};function pt(M){var Y=M[0]/255,U=M[1]/255,W=M[2]/255,K=Math.min(Y,U,W),$=Math.max(Y,U,W),it=$-K,ht,v,L;return $==K?ht=0:Y==$?ht=(U-W)/it:U==$?ht=2+(W-Y)/it:W==$&&(ht=4+(Y-U)/it),ht=Math.min(ht*60,360),ht<0&&(ht+=360),L=(K+$)/2,$==K?v=0:L<=.5?v=it/($+K):v=it/(2-$-K),[ht,v*100,L*100]}function Ct(M){var Y=M[0],U=M[1],W=M[2],K=Math.min(Y,U,W),$=Math.max(Y,U,W),it=$-K,ht,v,L;return $==0?v=0:v=it/$*1e3/10,$==K?ht=0:Y==$?ht=(U-W)/it:U==$?ht=2+(W-Y)/it:W==$&&(ht=4+(Y-U)/it),ht=Math.min(ht*60,360),ht<0&&(ht+=360),L=$/255*1e3/10,[ht,v,L]}function ot(M){var Y=M[0],U=M[1],$=M[2],W=pt(M)[0],K=1/255*Math.min(Y,Math.min(U,$)),$=1-1/255*Math.max(Y,Math.max(U,$));return[W,K*100,$*100]}function O(M){var Y=M[0]/255,U=M[1]/255,W=M[2]/255,K,$,it,ht;return ht=Math.min(1-Y,1-U,1-W),K=(1-Y-ht)/(1-ht)||0,$=(1-U-ht)/(1-ht)||0,it=(1-W-ht)/(1-ht)||0,[K*100,$*100,it*100,ht*100]}function C(M){return X[JSON.stringify(M)]}function f(M){var Y=M[0]/255,U=M[1]/255,W=M[2]/255;Y=Y>.04045?Math.pow((Y+.055)/1.055,2.4):Y/12.92,U=U>.04045?Math.pow((U+.055)/1.055,2.4):U/12.92,W=W>.04045?Math.pow((W+.055)/1.055,2.4):W/12.92;var K=Y*.4124+U*.3576+W*.1805,$=Y*.2126+U*.7152+W*.0722,it=Y*.0193+U*.1192+W*.9505;return[K*100,$*100,it*100]}function k(M){var Y=f(M),U=Y[0],W=Y[1],K=Y[2],$,it,ht;return U/=95.047,W/=100,K/=108.883,U=U>.008856?Math.pow(U,.3333333333333333):7.787*U+.13793103448275862,W=W>.008856?Math.pow(W,.3333333333333333):7.787*W+.13793103448275862,K=K>.008856?Math.pow(K,.3333333333333333):7.787*K+.13793103448275862,$=116*W-16,it=500*(U-W),ht=200*(W-K),[$,it,ht]}function vt(M){return Cs(k(M))}function At(M){var Y=M[0]/360,U=M[1]/100,W=M[2]/100,K,$,it,ht,v;if(U==0)return v=W*255,[v,v,v];W<.5?$=W*(1+U):$=W+U-W*U,K=2*W-$,ht=[0,0,0];for(var L=0;L<3;L++)it=Y+.3333333333333333*-(L-1),it<0&&it++,it>1&&it--,6*it<1?v=K+($-K)*6*it:2*it<1?v=$:3*it<2?v=K+($-K)*(.6666666666666666-it)*6:v=K,ht[L]=v*255;return ht}function R(M){var Y=M[0],U=M[1]/100,W=M[2]/100,K,$;return W===0?[0,0,0]:(W*=2,U*=W<=1?W:2-W,$=(W+U)/2,K=2*U/(W+U),[Y,K*100,$*100])}function V(M){return ot(At(M))}function J(M){return O(At(M))}function et(M){return C(At(M))}function D(M){var Y=M[0]/60,U=M[1]/100,v=M[2]/100,W=Math.floor(Y)%6,K=Y-Math.floor(Y),$=255*v*(1-U),it=255*v*(1-U*K),ht=255*v*(1-U*(1-K)),v=255*v;switch(W){case 0:return[v,ht,$];case 1:return[it,v,$];case 2:return[$,v,ht];case 3:return[$,it,v];case 4:return[ht,$,v];case 5:return[v,$,it]}}function _(M){var Y=M[0],U=M[1]/100,W=M[2]/100,K,$;return $=(2-U)*W,K=U*W,K/=$<=1?$:2-$,K=K||0,$/=2,[Y,K*100,$*100]}function c(M){return ot(D(M))}function zt(M){return O(D(M))}function qe(M){return C(D(M))}function Pt(M){var Y=M[0]/360,U=M[1]/100,W=M[2]/100,K=U+W,$,it,ht,v;switch(K>1&&(U/=K,W/=K),$=Math.floor(6*Y),it=1-W,ht=6*Y-$,($&1)!=0&&(ht=1-ht),v=U+ht*(it-U),$){default:case 6:case 0:r=it,g=v,b=U;break;case 1:r=v,g=it,b=U;break;case 2:r=U,g=it,b=v;break;case 3:r=U,g=v,b=it;break;case 4:r=v,g=U,b=it;break;case 5:r=it,g=U,b=v;break}return[r*255,g*255,b*255]}function Qi(M){return pt(Pt(M))}function N(M){return Ct(Pt(M))}function pi(M){return O(Pt(M))}function Js(M){return C(Pt(M))}function mi(M){var Y=M[0]/100,U=M[1]/100,W=M[2]/100,K=M[3]/100,$,it,ht;return $=1-Math.min(1,Y*(1-K)+K),it=1-Math.min(1,U*(1-K)+K),ht=1-Math.min(1,W*(1-K)+K),[$*255,it*255,ht*255]}function Rt(M){return pt(mi(M))}function ri(M){return Ct(mi(M))}function $i(M){return ot(mi(M))}function yt(M){return C(mi(M))}function Zs(M){var Y=M[0]/100,U=M[1]/100,W=M[2]/100,K,$,it;return K=Y*3.2406+U*-1.5372+W*-.4986,$=Y*-.9689+U*1.8758+W*.0415,it=Y*.0557+U*-.204+W*1.057,K=K>.0031308?1.055*Math.pow(K,.4166666666666667)-.055:K=K*12.92,$=$>.0031308?1.055*Math.pow($,.4166666666666667)-.055:$=$*12.92,it=it>.0031308?1.055*Math.pow(it,.4166666666666667)-.055:it=it*12.92,K=Math.min(Math.max(0,K),1),$=Math.min(Math.max(0,$),1),it=Math.min(Math.max(0,it),1),[K*255,$*255,it*255]}function xt(M){var Y=M[0],U=M[1],W=M[2],K,$,it;return Y/=95.047,U/=100,W/=108.883,Y=Y>.008856?Math.pow(Y,.3333333333333333):7.787*Y+.13793103448275862,U=U>.008856?Math.pow(U,.3333333333333333):7.787*U+.13793103448275862,W=W>.008856?Math.pow(W,.3333333333333333):7.787*W+.13793103448275862,K=116*U-16,$=500*(Y-U),it=200*(U-W),[K,$,it]}function wn(M){return Cs(xt(M))}function ys(M){var Y=M[0],U=M[1],W=M[2],K,$,it,ht;return Y<=8?($=Y*100/903.3,ht=7.787*($/100)+.13793103448275862):($=100*Math.pow((Y+16)/116,3),ht=Math.pow($/100,.3333333333333333)),K=K/95.047<=.008856?K=95.047*(U/500+ht-.13793103448275862)/7.787:95.047*Math.pow(U/500+ht,3),it=it/108.883<=.008859?it=108.883*(ht-W/200-.13793103448275862)/7.787:108.883*Math.pow(ht-W/200,3),[K,$,it]}function Cs(M){var Y=M[0],U=M[1],W=M[2],K,$,it;return K=Math.atan2(W,U),$=K*360/2/Math.PI,$<0&&($+=360),it=Math.sqrt(U*U+W*W),[Y,it,$]}function _s(M){return Zs(ys(M))}function at(M){var Y=M[0],U=M[1],W=M[2],K,$,it;return it=W/360*2*Math.PI,K=U*Math.cos(it),$=U*Math.sin(it),[Y,K,$]}function vn(M){return ys(at(M))}function w(M){return _s(at(M))}function Pi(M){return be[M]}function As(M){return pt(Pi(M))}function Pr(M){return Ct(Pi(M))}function Sr(M){return ot(Pi(M))}function In(M){return O(Pi(M))}function tn(M){return k(Pi(M))}function st(M){return f(Pi(M))}var be={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]},X={};for(var Dt in be)X[JSON.stringify(be[Dt])]=Dt},79275:(ae,pt,Ct)=>{var ot=Ct(64106);ae.exports=ot.parse},89796:(ae,pt,Ct)=>{"use strict";var ot;ot={value:!0};const O=Ct(48436);class C extends O.LinkedList{constructor(...k){super(...k)}get top(){return this.head}get size(){return this.length}push(k){this.prepend(k)}pop(){return this.removeHead()}}pt.B=C}},ea={};function Ys(ae){var pt=ea[ae];if(pt!==void 0)return pt.exports;var Ct=ea[ae]={exports:{}};return gl[ae](Ct,Ct.exports,Ys),Ct.exports}var Zu={};(()=>{"use strict";class ae{bind(t){this.entity&&this.entity.setAttr(t,this)}constructor(t,e){this.entity=t,this.bind(e)}}class pt{}pt.GeomObjectIndex=0,pt.DrawingObjectIndex=1,pt.AlgorithmDataIndex=2,pt.ViewerIndex=3;class Ct{constructor(){this.actions=new Set}forEach(t){this.actions.forEach(e=>e(t,null))}subscribe(t){this.actions.add(t)}unsubscribe(t){this.actions.delete(t)}raise(t,e){this.actions.forEach(i=>i(t,e))}}class ot extends ae{constructor(t){super(t,pt.GeomObjectIndex)}static getGeom(t){return t==null?null:t.getAttr(pt.GeomObjectIndex)}get parent(){const t=this.entity.parent;return t?ot.getGeom(t):null}rebind(t){this.entity=t,this.bind(pt.GeomObjectIndex)}*getAncestors(){let t=this.parent;for(;t!=null;)yield t,t=t.parent}}class O{static solve(t,e,i,s,n,o){const a=t*n-s*e;if(!(Math.abs(a)<O.eps))return{x:(i*n-o*e)/a,y:(t*o-s*i)/a}}}O.eps=1e-8;class C{}C.distanceEpsilonPrecision=6,C.mult=Math.pow(10,6),C.defaultLeafBoxesOffset=.5,C.lineSegmentThreshold=.05,C.intersectionEpsilon=1e-4,C.distanceEpsilon=Math.pow(10,-C.distanceEpsilonPrecision),C.squareOfDistanceEpsilon=Math.pow(10,-C.distanceEpsilonPrecision*2),C.tolerance=1e-8;function f(l,t){return(l?1:0)-(t?1:0)}function k(l,t){const e=l-t;return e<0?-1:e===0?0:1}function vt(l,t){const e=k(l.y,t.y);return e||k(l.x,t.x)}function At(l,t){const e=k(l.x,t.x);return e||k(l.y,t.y)}function R(l,t){const e=l-t;return-C.distanceEpsilon<=e&&e<=C.distanceEpsilon}function V(l,t){return et(l,t)>0}function J(l,t){return et(l,t)<0}function et(l,t){const e=l-t;return e<=-C.distanceEpsilon?-1:e>=C.distanceEpsilon?1:0}var D;(function(l){l[l.Clockwise=0]="Clockwise",l[l.Counterclockwise=1]="Counterclockwise",l[l.Collinear=2]="Collinear"})(D||(D={}));function _(l,t){return l.sub(t).length}class c{static RoundPoint(t){return new c(c.RoundDouble(t.x),c.RoundDouble(t.y))}static RoundDouble(t){return Math.round(t*C.mult)/C.mult}toJSON(){return{x:this.x,y:this.y}}static fromJSON(t){return new c(t.x,t.y)}static ProjectionToLine(t,e,i){let s=e.sub(t);const n=s.length;if(n<C.distanceEpsilon)return t;s=s.div(n);const o=i.sub(t).dot(s);return t.add(s.mul(o))}static RayIntersectsRayInteriors(t,e,i,s){const n=c.lineLineIntersection(t,t.add(e),i,i.add(s));if(n&&n.sub(t).dot(e.div(e.l1))>C.distanceEpsilon&&n.sub(i).dot(s.div(s.l1))>C.distanceEpsilon)return n}static IntervalIntersectsRay(t,e,i,s){const n=c.lineLineIntersection(t,e,i,i.add(s));if(!n)return;const o=t.sub(n),a=n.sub(e);if(!(o.dot(a)<=0)&&!(n.sub(i).dot(s)<0)&&o.dot(o)>C.squareOfDistanceEpsilon&&a.dot(a)>=C.squareOfDistanceEpsilon)return n}static PointToTheLeftOfLineOrOnLine(t,e,i){return c.signedDoubledTriangleArea(t,e,i)>=0}static PointToTheLeftOfLine(t,e,i){return c.signedDoubledTriangleArea(t,e,i)>0}static PointIsInsideCone(t,e,i,s){return c.PointToTheRightOfLineOrOnLine(t,e,i)&&c.PointToTheLeftOfLineOrOnLine(t,e,s)}static PointToTheRightOfLineOrOnLine(t,e,i){return c.signedDoubledTriangleArea(e,i,t)<=0}static PointToTheRightOfLine(t,e,i){return c.signedDoubledTriangleArea(e,i,t)<0}static closeIntersections(t,e){return c.close(t,e,C.intersectionEpsilon)}get l1(){return Math.abs(this.x_)+Math.abs(this.y_)}dot(t){return this.x*t.x+this.y*t.y}get x(){return this.x_}get y(){return this.y_}compareTo(t){const e=k(this.x,t.x);return e!==0?e:k(this.y,t.y)}toString(){return"("+this.x+","+this.y+")"}static close(t,e,i){return t.sub(e).length<=i}static closeSquare(t,e,i){const s=e.sub(t);return s.dot(s)<=i}static closeDistEps(t,e,i=C.distanceEpsilon){return t.sub(e).length<=i}normalize(){const t=this.length;return new c(this.x/t,this.y/t)}get length(){return Math.sqrt(this.x*this.x+this.y*this.y)}get lengthSquared(){return this.x*this.x+this.y*this.y}constructor(t,e){this.x_=t,this.y_=e}static middle(t,e){return t.add(e).div(2)}scale(t,e){return new c(this.x*t,this.y*e)}add(t){return new c(this.x+t.x,this.y+t.y)}sub(t){return new c(this.x-t.x,this.y-t.y)}mul(t){return new c(this.x*t,this.y*t)}div(t){return new c(this.x/t,this.y/t)}equal(t){return t.x===this.x&&t.y===this.y}neg(){return new c(-this.x,-this.y)}static lineLineIntersection(t,e,i,s){const n=e.sub(t),o=i.sub(s),a=i.sub(t),h=O.solve(n.x,o.x,a.x,n.y,o.y,a.y);if(h!==void 0)return t.add(n.mul(h.x))}static segSegIntersection(t,e,i,s){const n=e.sub(t),o=i.sub(s),a=i.sub(t),h=C.tolerance,u=O.solve(n.x,o.x,a.x,n.y,o.y,a.y);if(u!==void 0&&u.x>-h&&u.x<1+h&&u.y>-h&&u.y<1+h)return t.add(n.mul(u.x))}static parallelWithinEpsilon(t,e,i){const s=t.length,n=e.length;return s<i||n<i?!0:(t=t.div(s),e=e.div(n),Math.abs(-t.x*e.y+t.y*e.x)<i)}static crossProduct(t,e){return t.x*e.y-t.y*e.x}static dot(t,e){return t.x*e.x+t.y*e.y}static add(t,e){return t.add(e)}rotate90Ccw(){return new c(-this.y,this.x)}rotate90Cw(){return new c(this.y,-this.x)}clone(){return new c(this.x,this.y)}rotate(t){const e=Math.cos(t),i=Math.sin(t);return new c(e*this.x-i*this.y,i*this.x+e*this.y)}static mkPoint(t,e,i,s){return e.mul(t).add(s.mul(i))}static convSum(t,e,i){return e.add(i.sub(e).mul(t))}static anglePCP(t,e,i){return c.angle(t.sub(e),i.sub(e))}static angle(t,e){const i=t.x,s=t.y,n=e.x,o=e.y,a=i*o-s*n,h=i*n+s*o;if(Math.abs(h)<C.tolerance)return Math.abs(a)<C.tolerance?0:a<-C.tolerance?3*Math.PI/2:Math.PI/2;if(Math.abs(a)<C.tolerance)return h<-C.tolerance?Math.PI:0;const u=Math.atan2(a,h);return a>=-C.tolerance?u:Math.PI*2+u}static signedDoubledTriangleArea(t,e,i){return(e.x-t.x)*(i.y-t.y)-(i.x-t.x)*(e.y-t.y)}static getTriangleOrientation(t,e,i){const s=c.signedDoubledTriangleArea(t,e,i);return s>C.distanceEpsilon?D.Counterclockwise:s<-C.distanceEpsilon?D.Clockwise:D.Collinear}static getTriangleOrientationWithIntersectionEpsilon(t,e,i){const s=c.signedDoubledTriangleArea(t,e,i);return s>C.intersectionEpsilon?D.Counterclockwise:s<-C.intersectionEpsilon?D.Clockwise:D.Collinear}static ClosestPointAtLineSegment(t,e,i){const s=i.sub(e),n=t.sub(e),o=s.dot(n),a=s.dot(s);return o<=0+C.tolerance?e:a<=o+C.tolerance?i:e.add(s.mul(o/a))}static pointToTheLeftOfLineOrOnLine(t,e,i){return c.signedDoubledTriangleArea(t,e,i)>=0}static pointToTheLeftOfLine(t,e,i){return c.signedDoubledTriangleArea(t,e,i)>0}static pointToTheRightOfLineOrOnLine(t,e,i){return c.signedDoubledTriangleArea(e,i,t)<=0}static pointToTheRightOfLine(t,e,i){return c.signedDoubledTriangleArea(e,i,t)<0}static canProject(t,e,i){const s=i.sub(e);return!(t.sub(e).dot(s)<0||t.sub(i).dot(s)>0)}static distToLineSegment(t,e,i){const s=i.sub(e),n=t.sub(e);let o,a;if((o=s.dot(n))<=C.tolerance)return{par:0,dist:n.length};if((a=s.dot(s))<=o+C.tolerance)return{par:1,dist:t.sub(i).length};const h=o/a;return{par:h,dist:e.add(s.mul(h)).length}}}class zt{constructor(){this._next=null,this.prev=null}get point(){return this._point}set point(t){this._point=t}get next(){return this._next}set next(t){this._next=t}get nextOnPolyline(){return this.polyline.next(this)}get prevOnPolyline(){return this.polyline.prev(this)}getNext(){return this.next}setNext(t){this.next=t,this.polyline!=null&&this.polyline.setInitIsRequired()}getPrev(){return this.prev}setPrev(t){this.prev=t,this.polyline!=null&&this.polyline.setInitIsRequired()}static mkFromPoint(t){const e=new zt;return e.point=t,e}}var qe;(function(l){l[l.Corner=0]="Corner",l[l.VertexA=1]="VertexA",l[l.otherCorner=2]="otherCorner",l[l.VertexB=3]="VertexB"})(qe||(qe={}));class Pt{contains(t){const e=t.sub(this.corner),i=C.distanceEpsilon,s=e.dot(this.bRot);if(s>this.abRot+i||s<-i)return!1;const n=e.dot(this.aRot);return n<=this.baRot+i&&n>=-i}get area(){return Math.abs(this.a.x*this.b.y-this.a.y*this.b.x)}vertex(t){switch(t){case qe.Corner:return this.corner;case qe.VertexA:return this.aPlusCorner;case qe.otherCorner:return this.otherCorner;case qe.VertexB:return this.bPlusCorner;default:return}}static parallelogramOfTwo(t,e){const i=new Pt,s=t.corner,n={minx:s.x,maxx:s.x,miny:s.y,maxy:s.y};return Pt.pumpMinMax(n,t.aPlusCorner),Pt.pumpMinMax(n,t.otherCorner),Pt.pumpMinMax(n,t.bPlusCorner),Pt.pumpMinMax(n,e.corner),Pt.pumpMinMax(n,e.aPlusCorner),Pt.pumpMinMax(n,e.otherCorner),Pt.pumpMinMax(n,e.bPlusCorner),i.corner=new c(n.minx,n.miny),i.a=new c(0,n.maxy-n.miny),i.b=new c(n.maxx-n.minx,0),i.aPlusCorner=i.a.add(i.corner),i.otherCorner=i.b.add(i.aPlusCorner),i.bPlusCorner=i.b.add(i.corner),i.aRot=new c(-i.a.y,i.a.x),i.aRot.length>.5&&(i.aRot=i.aRot.normalize()),i.bRot=new c(-i.b.y,i.b.x),i.bRot.length>.5&&(i.bRot=i.bRot.normalize()),i.abRot=i.a.dot(i.bRot),i.baRot=i.b.dot(i.aRot),i.abRot<0&&(i.abRot=-i.abRot,i.bRot=i.bRot.neg()),i.baRot<0&&(i.baRot=-i.baRot,i.aRot=i.aRot.neg()),i.isSeg=i.a.sub(i.b).length<C.distanceEpsilon,i}static pumpMinMax(t,e){e.x<t.minx?t.minx=e.x:e.x>t.maxx&&(t.maxx=e.x),e.y<t.miny?t.miny=e.y:e.y>t.maxy&&(t.maxy=e.y)}static intersect(t,e){return!(Pt.separByA(t,e)||Pt.separByA(e,t)||Pt.separByB(t,e)||Pt.separByB(e,t))===!1?!1:!(t.isSeg&&e.isSeg)||!c.parallelWithinEpsilon(t.otherCorner.sub(t.corner),e.otherCorner.sub(e.corner),1e-5)?!0:Pt.ParallelSegsIntersect(e,t)}static ParallelSegsIntersect(t,e){const i=t.corner,s=t.otherCorner,n=e.corner,o=e.otherCorner,a=s.sub(i),h=0,u=a.dot(a);let d=n.sub(i).dot(a),m=o.sub(i).dot(a);if(d>m){const y=d;d=m,m=y}return!(m<h-C.distanceEpsilon||d>u+C.distanceEpsilon)}static separByB(t,e){const i=C.distanceEpsilon,s=e.vertex(0).sub(t.corner).dot(t.bRot),n=[qe.VertexA,qe.otherCorner,qe.VertexB];if(s>t.abRot+i){for(const o of n)if(e.vertex(o).sub(t.corner).dot(t.bRot)<=t.abRot+i)return!1;return!0}else if(s<-i){for(const o of n)if(e.vertex(o).sub(t.corner).dot(t.bRot)>=-i)return!1;return!0}return!1}static separByA(t,e){const i=C.distanceEpsilon;let s=e.corner.sub(t.corner);const n=c.dot(s,t.aRot);return n>t.baRot+i?(s=e.aPlusCorner.sub(t.corner),!(c.dot(s,t.aRot)<=t.baRot+i||(s=e.bPlusCorner.sub(t.corner),c.dot(s,t.aRot)<=t.baRot+i)||(s=e.otherCorner.sub(t.corner),c.dot(s,t.aRot)<=t.baRot+i))):n<-i?(s=e.aPlusCorner.sub(t.corner),!(c.dot(s,t.aRot)>=-i||(s=e.bPlusCorner.sub(t.corner),c.dot(s,t.aRot)>=-i)||(s=e.otherCorner.sub(t.corner),c.dot(s,t.aRot)>=-i))):!1}static parallelogramByCornerSideSide(t,e,i){const s=new Pt;return s.corner=t,s.a=e,s.b=i,s.aRot=new c(-e.y,e.x),s.aRot.length>.5&&(s.aRot=s.aRot.normalize()),s.bRot=new c(-i.y,i.x),s.bRot.length>.5&&(s.bRot=s.bRot.normalize()),s.abRot=s.bRot.dot(e),s.baRot=i.dot(s.aRot),s.abRot<0&&(s.abRot=-s.abRot,s.bRot=s.bRot.neg()),s.baRot<0&&(s.baRot=-s.baRot,s.aRot=s.aRot.neg()),s.isSeg=e.sub(i).length<C.distanceEpsilon,s.aPlusCorner=e.add(t),s.otherCorner=i.add(s.aPlusCorner),s.bPlusCorner=i.add(t),s}static getParallelogramOfAGroup(t){let e=0,i=0,s=0,n=0,o=!0;for(const a of t){const h=Qi(a);for(const u of h){const d=u.x,m=u.y;o?(o=!1,e=i=d,s=n=m):(d<e?e=d:d>i&&(i=d),m<s?s=m:m>n&&(n=m))}}return Pt.parallelogramByCornerSideSide(new c(e,s),new c(0,n-s),new c(i-e,0))}}function*Qi(l){yield l.corner,yield l.aPlusCorner,yield l.otherCorner,yield l.bPlusCorner}class N{static fromJSON(t){return N.mkPP(c.fromJSON(t.start),c.fromJSON(t.end))}toJSON(){return{start:this.start.toJSON(),end:this.end.toJSON()}}offsetCurve(t,e){return null}constructor(t,e,i,s){this.parStart=0,this.parEnd=1,this.start=new c(t,e),this.end=new c(i,s)}trim(t,e){if(t=Math.max(this.parStart,t),e=Math.min(this.parEnd,e),t>e)throw"wrong params in trimming";const i=this.value(t),s=this.value(e);return c.close(i,s,C.distanceEpsilon)?null:N.mkPP(i,s)}value(t){return this.start.add(this.end.sub(this.start).mul(t))}trimWithWrap(t,e){return null}pNodeOverICurve(){const t=this.end.sub(this.start).mul(.5);return{parallelogram:Pt.parallelogramByCornerSideSide(this.start,t,t),seg:this,leafBoxesOffset:0,node:{low:0,high:1,chord:this}}}normal(){let t=this.start.sub(this.end);return t=t.div(t.length),new c(-t.y,t.x)}static mkPP(t,e){return new N(t.x,t.y,e.x,e.y)}static mkLinePXY(t,e,i){return new N(t.x,t.y,e,i)}derivative(t){return this.end.sub(this.start)}secondDerivative(t){return new c(0,0)}thirdDerivative(t){return new c(0,0)}reverse(){return N.mkPP(this.end,this.start)}translate(t){this.start=this.start.add(t),this.end=this.end.add(t)}scaleFromOrigin(t,e){return N.mkPP(this.start.scale(t,e),this.end.scale(t,e))}getParameterAtLength(t){const e=this.end.sub(this.start).length;if(e<C.tolerance)return 0;const i=t/e;return i>1?1:i<0?0:i}transform(t){return N.mkPP(t.multiplyPoint(this.start),t.multiplyPoint(this.end))}closestParameterWithinBounds(t,e,i){let s=this.closestParameter(t);return s<e&&(s=e),s>i&&(s=i),s}lengthPartial(t,e){return this.value(e).sub(this.value(t)).length}get length(){return this.start.sub(this.end).length}get boundingBox(){return X.mkPP(this.start,this.end)}clone(){return N.mkPP(this.start.clone(),this.end.clone())}static closestParameterOnLineSegment(t,e,i){const s=i.sub(e),n=t.sub(e),o=s.dot(n);if(o<=0+C.tolerance)return 0;const a=s.dot(s);return a<=o+C.tolerance?1:o/a}closestParameter(t){return N.closestParameterOnLineSegment(t,this.start,this.end)}leftDerivative(t){return this.derivative(t)}rightDerivative(t){return this.derivative(t)}static IntersectPPPP(t,e,i,s){const n=c.lineLineIntersection(t,e,i,s);if(n!=null&&pi(n,t,e)&&pi(n,i,s))return n}curvature(t){return 0}curvatureDerivative(t){return 0}curvatureSecondDerivative(t){return 0}static minDistBetweenLineSegments(t,e,i,s){const n=e.sub(t),o=s.sub(i),a=t.sub(i),h=c.crossProduct(n,o),u=n.dot(n),d=n.dot(o),m=o.dot(o),y=n.dot(a),E=o.dot(a);let T,B;const H=Math.abs(h);let tt=H,lt=H;H<C.tolerance?(T=0,tt=1,B=E,lt=m):(T=c.crossProduct(o,a),B=c.crossProduct(n,a),h<0&&(T=-T,B=-B),T<0?(T=0,B=E,lt=m):T>tt&&(T=tt=1,B=E+d,lt=m)),B<0?(B=0,-y<0?T=0:-y>u?T=tt:(T=-y,tt=u)):B>lt&&(B=lt=1,-y+d<0?T=0:-y+d>u?T=tt:(T=-y+d,tt=u));const Q=Math.abs(T)<C.tolerance?0:T/tt,dt=Math.abs(B)<C.tolerance?0:B/lt;return{parab:Q,parcd:dt,dist:a.add(n.mul(Q).sub(o.mul(dt))).length}}}function pi(l,t,e){return l.x>=Math.min(t.x,e.x)-C.distanceEpsilon&&l.y>=Math.min(t.y,e.y)-C.distanceEpsilon&&l.x<=Math.max(t.x,e.x)+C.distanceEpsilon&&l.y<=Math.max(t.y,e.y)+C.distanceEpsilon}function Js(l,t,e,i){const s=c.getTriangleOrientation(l,t,e),n=c.getTriangleOrientation(l,t,i),o=c.getTriangleOrientation(e,i,l),a=c.getTriangleOrientation(e,i,t);return!!(s!=n&&o!=a||s==D.Collinear&&pi(e,l,t)||n==D.Collinear&&pi(i,l,t)||o==D.Collinear&&pi(l,e,i)||a==D.Collinear&&pi(t,e,i))}function mi(l,t,e,i,s){return{parallelogram:e,seg:i,leafBoxesOffset:s,node:{low:l,high:t,chord:null}}}class Rt{static distToSegm(t,e,i){const s=i.sub(e);if(s.length<C.intersectionEpsilon)return t.sub(e.add(i).div(2)).length;let n=new c(-s.y,s.x);return n=n.mul(1/n.length),Math.abs(t.sub(e).dot(n))}static createParallelogramOnSubSeg(t,e,i){let s=i.derivative(t);const n=i.derivative(e),o=new c(-n.y,n.x),a=i.value(t),h=i.value(e),d=h.sub(a).dot(o),m=s.dot(o),y=Math.abs(d)<C.distanceEpsilon;if(!y&&Math.abs(m)<C.distanceEpsilon)return;const E=y?0:d/m;return s=s.mul(E),Pt.parallelogramByCornerSideSide(a,s,h.sub(a).sub(s))}static createParallelogramNodeForCurveSeg(t,e,i,s){if(t===i.parStart&&e===i.parEnd&&c.close(i.start,i.end,C.distanceEpsilon))return Rt.createNodeWithSegmentSplit(t,e,i,s);const o=i.value(t),a=i.value(e),h=a.sub(o),u=i.value((t+e)/2);if(Rt.distToSegm(u,o,a)<=C.intersectionEpsilon&&h.dot(h)<C.lineSegmentThreshold*C.lineSegmentThreshold&&e-t<C.lineSegmentThreshold){const d=N.mkPP(o,a),m=d.pNodeOverICurve();m.seg=i;const y=m.node;return y.low=t,y.high=e,y.chord=d,m}if(Rt.WithinEpsilon(i,t,e,s)){const d=Rt.createParallelogramOnSubSeg(t,e,i);if(d!==void 0)return mi(t,e,d,i,s)}return Rt.createNodeWithSegmentSplit(t,e,i,s)}static WithinEpsilon(t,e,i,s){const o=(i-e)/3,a=t.value(e),h=t.value(i);return Rt.distToSegm(t.value(e+o),a,h)>s?!1:Rt.distToSegm(t.value(e+o*2),a,h)<=s}static createParallelogramNodeForCurveSegDefaultOffset(t){return Rt.createParallelogramNodeForCurveSeg(t.parStart,t.parEnd,t,C.defaultLeafBoxesOffset)}static createNodeWithSegmentSplit(t,e,i,s){const n={parallelogram:null,seg:i,leafBoxesOffset:1,node:{children:[]}},o=n.node;return o.children.push(Rt.createParallelogramNodeForCurveSeg(t,.5*(t+e),i,s)),o.children.push(Rt.createParallelogramNodeForCurveSeg(.5*(t+e),e,i,s)),n.parallelogram=Pt.parallelogramOfTwo(o.children[0].parallelogram,o.children[1].parallelogram),n}}class ri{constructor(t,e,i,s,n){this.par0=t,this.par1=e,this.x=i,this.seg0=s,this.seg1=n}}class $i{static closestPoint(t,e,i,s,n){let h=i,u=0,d=0,m,y=!1;do{const E=t.value(h),T=t.derivative(h),B=t.secondDerivative(h),H=T.dot(T)+E.sub(e).dot(B);if(Math.abs(H)<C.tolerance)return h;m=E.sub(e).dot(T.div(H)),h-=m,h>n+C.tolerance?(h=n,d++):h<s-C.tolerance&&(h=s,d++),u++}while(Math.abs(m)>C.tolerance&&!(y=u>=5||d>=5));return y&&t.value(i).sub(e).length<C.distanceEpsilon&&(h=i),h}}class yt{isFullEllipse(){return this.parEnd===Math.PI*2&&this.parStart===0}static fromJSON(t){return new yt(t.parStart,t.parEnd,c.fromJSON(t.axis0),c.fromJSON(t.axis1),c.fromJSON(t.center))}toJSON(){return{parStart:this.parStart,parEnd:this.parEnd,axis0:this.aAxis.toJSON(),axis1:this.bAxis.toJSON(),center:this.center.toJSON()}}offsetCurve(t,e){const i=e.sub(this.center),s=c.angle(this.aAxis,i);if(this.aAxis.mul(Math.cos(s)).add(this.bAxis.mul(Math.sin(s))).length<i.length){const o=this.aAxis.length,a=this.bAxis.length;return yt.mkEllipsePPP(this.aAxis.normalize().mul(o+t),this.bAxis.normalize().mul(a+t),this.center)}{const o=this.aAxis.length,a=this.bAxis.length;return yt.mkEllipsePPP(this.aAxis.normalize().mul(o-t),this.bAxis.normalize().mul(a-t),this.center)}}reverse(){return null}static mkEllipsePPP(t,e,i){return new yt(0,Math.PI*2,t,e,i)}constructor(t,e,i,s,n){for(this.parStart=t,this.parEnd=e,this.aAxis=i,this.bAxis=s,this.center=n,this.pNode=null,this.setBoundingBox();this.parStart<0;)this.parStart+=Math.PI*2,this.parEnd+=Math.PI*2}get start(){return this.value(this.parStart)}get end(){return this.value(this.parEnd)}trim(t,e){return new yt(Math.max(t,this.parStart),Math.min(e,this.parEnd),this.aAxis,this.bAxis,this.center)}trimWithWrap(t,e){return null}get boundingBox(){return this.box}value(t){return this.center.add(c.mkPoint(Math.cos(t),this.aAxis,Math.sin(t),this.bAxis))}derivative(t){return c.mkPoint(-Math.sin(t),this.aAxis,Math.cos(t),this.bAxis)}secondDerivative(t){return c.mkPoint(-Math.cos(t),this.aAxis,-Math.sin(t),this.bAxis)}thirdDerivative(t){return c.mkPoint(Math.sin(t),this.aAxis,-Math.cos(t),this.bAxis)}pNodeOverICurve(){return this.pNode!=null?this.pNode:this.pNode=Rt.createParallelogramNodeForCurveSegDefaultOffset(this)}setBoundingBox(){if(R(this.parStart,0)&&R(this.parEnd,Math.PI*2))this.box=this.fullBox();else{this.box=X.mkPP(this.start,this.end);let t;for(let e=Math.ceil(this.parStart/(Math.PI/2));(t=e*Math.PI/2)<this.parEnd;e++)t>this.parStart&&this.box.add(this.value(t))}}static mkEllipse(t,e,i,s,n,o){return new yt(t,e,i,s,new c(n,o))}static mkFullEllipsePPP(t,e,i){return new yt(0,Math.PI*2,t,e,i)}static mkFullEllipseNNP(t,e,i){return new yt(0,Math.PI*2,new c(t,0),new c(0,e),i)}static mkCircle(t,e){return yt.mkFullEllipseNNP(t,t,e)}translate(t){this.center=this.center.add(t),this.box.center=this.box.center.add(t),this.pNode=null}scaleFromOrigin(t,e){return new yt(this.parStart,this.parEnd,this.aAxis.mul(t),this.bAxis.mul(e),this.center.scale(t,e))}getParameterAtLength(t){let i=this.parStart,s=this.parEnd;const n=t+.001,o=t-.001;for(;s-i>C.distanceEpsilon;){const a=.5*(s+i),h=this.lengthPartial(this.parStart,a);if(h>n)s=a;else if(h<o)i=a;else return a}return(s+i)/2}transform(t){if(t!=null){const e=t.multiplyPoint(this.aAxis).sub(t.offset()),i=t.multiplyPoint(this.bAxis).sub(t.offset());return new yt(this.parStart,this.parEnd,e,i,t.multiplyPoint(this.center))}return this.clone()}closestParameterWithinBounds(t,e,i){const n=(i-e)/9;let o=e,a=Number.MAX_VALUE;for(let u=0;u<=8;u++){const d=e+u*n,m=t.sub(this.value(d)),y=m.dot(m);y<a&&(a=y,o=d)}o===0&&i===Math.PI*2&&(e=-Math.PI);let h=$i.closestPoint(this,t,o,e,i);return h<0&&(h+=2*Math.PI),h}lengthPartial(t,e){return w.lengthWithInterpolationAndThreshold(this.trim(t,e),C.lineSegmentThreshold/100)}get length(){return(this.aAxis.length+this.bAxis.length)*Math.abs(this.parEnd-this.parStart)/2}clone(){return new yt(this.parStart,this.parEnd,this.aAxis.clone(),this.bAxis.clone(),this.center.clone())}closestParameter(t){let e=0;const i=8,s=(this.parEnd-this.parStart)/(i+1);let n=this.parStart,o=Number.MAX_VALUE;for(let u=0;u<=i;u++){const d=this.parStart+u*s,m=t.sub(this.value(d)),y=m.dot(m);y<o&&(o=y,n=d)}let a=!1;n===0&&this.parEnd===Math.PI*2&&(a=!0,e=this.parStart,this.parStart=-Math.PI);let h=$i.closestPoint(this,t,n,this.parStart,this.parEnd);return h<0&&(h+=2*Math.PI),a&&(this.parStart=e),h}leftDerivative(t){return this.derivative(t)}rightDerivative(t){return this.derivative(t)}curvature(t){throw"NotImplementedException()"}curvatureDerivative(t){throw"NotImplementedException();"}curvatureSecondDerivative(t){throw"NotImplementedException()"}orientedCounterclockwise(){return c.crossProduct(this.aAxis,this.bAxis)>0}fullBox(){const t=this.aAxis.add(this.bAxis);return X.mkPP(this.center.add(t),this.center.sub(t))}isArc(){return Math.abs(this.aAxis.dot(this.bAxis))<C.tolerance&&Math.abs(this.aAxis.length-this.bAxis.length)<C.tolerance&&c.closeDistEps(this.aAxis.rotate90Ccw(),this.bAxis)}}class Zs{initValues(){this.a=this.curveA.value(this.si),this.b=this.curveB.value(this.ti),this.a_b=this.a.sub(this.b),this.ad=this.curveA.derivative(this.si),this.add=this.curveA.secondDerivative(this.si),this.bd=this.curveB.derivative(this.ti),this.bdd=this.curveB.secondDerivative(this.ti)}constructor(t,e,i,s,n,o,a,h){this.curveA=t,this.curveB=e,this.aMin=i,this.bMin=n,this.aMax=s,this.bMax=o,this.aGuess=a,this.bGuess=h,this.si=a,this.ti=h}Fs(){return this.a_b.dot(this.ad)}Fss(){return this.a_b.dot(this.add)+this.ad.dot(this.ad)}Fst(){return-this.bd.dot(this.ad)}Ftt(){return-this.a_b.dot(this.bdd)+this.bd.dot(this.bd)}Ft(){return-this.a_b.dot(this.bd)}delta(t,e,i,s){return t*s-i*e}solve(){let t=0;const e=10;let i=0;const s=100;let n=!1;if(this.initValues(),this.curveA instanceof N&&this.curveB instanceof N){let a=this.curveB.derivative(0);a=a.div(a.length);const h=this.curveA.normal(),u=Math.abs(h.dot(a));if(Math.abs(u)<C.distanceEpsilon||this.delta(this.Fss(),this.Fst(),this.Fst(),this.Ftt())<C.tolerance){this.success=!0,this.parallelLineSegLineSegMinDist();return}}let o;do{const a=this.delta(this.Fss(),this.Fst(),this.Fst(),this.Ftt());if(Math.abs(a)<C.tolerance){this.success=!1,n=!0;break}o={s:this.delta(-this.Fs(),this.Fst(),-this.Ft(),this.Ftt())/a,t:this.delta(this.Fss(),-this.Fs(),this.Fst(),-this.Ft())/a};const h=this.si+o.s,u=this.ti+o.t;let d;h>this.aMax+C.distanceEpsilon||h<this.aMin-C.distanceEpsilon||u>this.bMax+C.distanceEpsilon||u<this.bMin-C.distanceEpsilon?(t++,this.chopDsDt(o),this.si+=o.s,this.ti+=o.t,d=!0):(d=!1,this.si=h,this.ti=u,this.si>this.aMax?this.si=this.aMax:this.si<this.aMin&&(this.si=this.aMin),this.ti>this.bMax?this.ti=this.bMax:this.ti<this.bMin&&(this.ti=this.bMin)),this.initValues(),i++,n=t>=e||i>=s||o.s===0&&o.t===0&&d}while((Math.abs(o.s)>=C.tolerance||Math.abs(o.t)>=C.tolerance)&&!n);if(n){const a=this.curveA.value(this.aGuess).sub(this.curveB.value(this.bGuess));if(a.dot(a)<C.distanceEpsilon*C.distanceEpsilon){this.aSolution=this.aGuess,this.bSolution=this.bGuess,this.aPoint=this.curveA.value(this.aGuess),this.bPoint=this.curveB.value(this.bGuess),this.success=!0;return}}this.aSolution=this.si,this.bSolution=this.ti,this.aPoint=this.a,this.bPoint=this.b,this.success=!n}chopDsDt(t){if(t.s!==0&&t.t!==0){let e=1;this.si+t.s>this.aMax?e=(this.aMax-this.si)/t.s:this.si+t.s<this.aMin&&(e=(this.aMin-this.si)/t.s);let i=1;this.ti+t.t>this.bMax?i=(this.bMax-this.ti)/t.t:this.ti+t.t<this.bMin&&(i=(this.bMin-this.ti)/t.t);const s=Math.min(e,i);t.s*=s,t.t*=s}else t.s===0?this.ti+t.t>this.bMax?t.t=this.bMax-this.ti:this.ti+t.t<this.bMin&&(t.t=this.bMin-this.ti):this.si+t.s>this.aMax?t.s=this.aMax-this.si:this.si+t.s<this.aMin&&(t.s=this.aMin-this.si)}parallelLineSegLineSegMinDist(){const t=this.curveA,e=this.curveB,i=t.start,s=t.end,n=e.start,o=e.end;let a=s.sub(i);const h=a.length;let u=0,d,m,y;if(h>C.distanceEpsilon){a=a.div(h),d=a.dot(s.sub(i)),m=a.dot(n.sub(i)),y=a.dot(o.sub(i));let E=!1;if(m>y){E=!0;const T=m;m=y,y=T}if(y<u)this.aSolution=0,this.bSolution=E?0:1;else if(m>d)this.aSolution=1,this.bSolution=E?1:0;else{const T=Math.min(d,y);this.aSolution=T/(d-u),this.bSolution=(T-m)/(y-m),E&&(this.bSolution=1-this.bSolution)}}else{let E=o.sub(n);const T=E.length;if(T>C.distanceEpsilon)if(E=E.div(T),u=0,d=E.dot(o.sub(n)),m=E.dot(i.sub(n)),m<u)this.bSolution=0,this.aSolution=1;else if(m>d)this.bSolution=1,this.aSolution=0;else{const B=Math.min(d,m);this.bSolution=B/(d-u),this.aSolution=0}else this.aSolution=0,this.bSolution=0}this.aPoint=this.curveA.value(this.aSolution),this.bPoint=this.curveB.value(this.bSolution)}}class xt{toJSON(){return{b:this.b.map(t=>t.toJSON())}}static fromJSON(t){return xt.mkBezier(t.b.map(c.fromJSON))}leftDerivative(t){return this.derivative(t)}rightDerivative(t){return this.derivative(t)}B(t){return this.b[t]}pNodeOverICurve(){return this.pBoxNode!=null?this.pBoxNode:this.pBoxNode=Rt.createParallelogramNodeForCurveSegDefaultOffset(this)}value(t){const e=t*t,i=e*t;return this.l.mul(i).add(this.e.mul(e).add(this.c.mul(t)).add(this.b[0]))}static adjustParamTo01(t){return t>1?1:t<0?0:t}trim(t,e){if(t=xt.adjustParamTo01(t),e=xt.adjustParamTo01(e),t>e)return this.trim(e,t);if(t>1-C.tolerance)return new xt(this.b[3],this.b[3],this.b[3],this.b[3]);const i=new Array(3),s=new Array(2),n=this.casteljau(t,i,s),o=new xt(n,s[1],i[2],this.b[3]),a=o.casteljau((e-t)/(1-t),i,s);return new xt(o.b[0],i[0],s[0],a)}trimWithWrap(t,e){throw"NotImplementedException()"}casteljau(t,e,i){const s=1-t;for(let n=0;n<3;n++)e[n]=c.mkPoint(s,this.b[n],t,this.b[n+1]);for(let n=0;n<2;n++)i[n]=c.mkPoint(s,e[n],t,e[n+1]);return c.mkPoint(s,i[0],t,i[1])}derivative(t){return this.l.mul(3*t*t).add(this.e.mul(2*t)).add(this.c)}secondDerivative(t){return c.mkPoint(6*t,this.l,2,this.e)}thirdDerivative(t){return this.l.mul(6)}constructor(t,e,i,s){this.b=new Array(4),this.parStart=0,this.parEnd=1,this.b[0]=t,this.b[1]=e,this.b[2]=i,this.b[3]=s,this.c=this.b[1].sub(this.b[0]).mul(3),this.e=this.b[2].sub(this.b[1]).mul(3).sub(this.c),this.l=this.b[3].sub(this.b[0]).sub(this.c).sub(this.e)}get start(){return this.b[0]}get end(){return this.b[3]}reverse(){return new xt(this.b[3],this.b[2],this.b[1],this.b[0])}translate(t){this.b[0]=this.b[0].add(t),this.b[1]=this.b[1].add(t),this.b[2]=this.b[2].add(t),this.b[3]=this.b[3].add(t),this.c=this.b[1].sub(this.b[0]).mul(3),this.e=this.b[2].sub(this.b[1]).mul(3).sub(this.c),this.l=this.b[3].sub(this.b[0]).sub(this.c).sub(this.e),this.bbox&&(this.bbox=X.translate(this.bbox,t)),this.pBoxNode=null}scaleFromOrigin(t,e){return new xt(this.b[0].scale(t,e),this.b[1].scale(t,e),this.b[2].scale(t,e),this.b[3].scale(t,e))}offsetCurve(t,e){return null}lengthPartial(t,e){return this.trim(t,e).length}get length(){return xt.lengthOnControlPolygon(this.b[0],this.b[1],this.b[2],this.b[3])}static lengthOnControlPolygon(t,e,i,s){const n=s.sub(t).length,o=e.sub(t).length+i.sub(e).length+s.sub(i).length;if(o-n>C.lineSegmentThreshold){const a=c.middle(t,e),h=c.middle(e,i),u=c.middle(i,s),d=c.middle(a,h),m=c.middle(u,h),y=c.middle(d,m);return xt.lengthOnControlPolygon(t,a,d,y)+xt.lengthOnControlPolygon(y,m,u,s)}return(o+n)/2}get boundingBox(){return this.bbox?this.bbox:this.bbox=X.mkOnPoints(this.b)}transform(t){return new xt(t.multiplyPoint(this.b[0]),t.multiplyPoint(this.b[1]),t.multiplyPoint(this.b[2]),t.multiplyPoint(this.b[3]))}closestParameterWithinBounds(t,e,i){const s=(i-e)/8;let n=0,o=Number.MAX_VALUE;for(let a=0;a<9;a++){const h=t.sub(this.value(a*s+e)),u=h.dot(h);u<o&&(o=u,n=a*s+e)}return $i.closestPoint(this,t,n,e,i)}clone(){return new xt(this.b[0],this.b[1],this.b[2],this.b[3])}static mkBezier(t){return new xt(t[0],t[1],t[2],t[3])}curvature(t){const e=this.G(t);return this.F(t)/e}F(t){return this.Xp(t)*this.Ypp(t)-this.Yp(t)*this.Xpp(t)}G(t){const e=this.Xp(t),i=this.Yp(t),s=e*e+i*i;return Math.sqrt(s*s*s)}Xp(t){return 3*this.l.x*t*t+2*this.e.x*t+this.c.x}Ypp(t){return 6*this.l.y*t+2*this.e.y}Yp(t){return 3*this.l.y*t*t+2*this.e.y*t+this.c.y}Xpp(t){return 6*this.l.x*t+2*this.e.x}Xppp(t){return 6*this.l.x}Yppp(t){return 6*this.l.y}curvatureDerivative(t){const e=this.G(t);return(this.Fp(t)*e-this.Gp(t)*this.F(t))/(e*e)}Fp(t){return this.Xp(t)*this.Yppp(t)-this.Yp(t)*this.Xppp(t)}Fpp(t){return this.Xpp(t)*this.Yppp(t)-this.Ypp(t)*this.Xppp(t)}closestParameter(t){let i=0,s=Number.MAX_VALUE;for(let n=0;n<9;n++){const o=t.sub(this.value(n*.125)),a=o.dot(o);a<s&&(s=a,i=n*.125)}return $i.closestPoint(this,t,i,0,1)}curvatureSecondDerivative(t){const e=this.G(t);return(this.Qp(t)*e-2*this.Q(t)*this.Gp(t))/(e*e*e)}Q(t){return this.Fp(t)*this.G(t)-this.Gp(t)*this.F(t)}Qp(t){return this.Fpp(t)*this.G(t)-this.Gpp(t)*this.F(t)}Gpp(t){const e=this.Xp(t),i=this.Yp(t),s=this.Xpp(t),n=this.Ypp(t),o=this.Xppp(t),a=this.Yppp(t),h=Math.sqrt(e*e+i*i),u=e*s+i*n;return 3*(u*u/h+h*(s*s+e*o+n*n+i*a))}Gp(t){const e=this.Xp(t),i=this.Yp(t),s=this.Xpp(t),n=this.Ypp(t);return 3*Math.sqrt(e*e+i*i)*(e*s+i*n)}getParameterAtLength(t){let e=0,i=1;for(;i-e>C.tolerance;){const s=(i+e)/2,n=this.evaluateError(t,s);if(n>0)i=s;else if(n<0)e=s;else return s}return(e+i)/2}evaluateError(t,e){const i=1-e,s=c.mkPoint(i,this.b[0],e,this.b[1]),n=c.mkPoint(i,this.b[1],e,this.b[2]),o=c.mkPoint(i,this.b[2],e,this.b[3]),a=c.mkPoint(i,s,e,n),h=c.mkPoint(i,n,e,o),u=c.mkPoint(i,a,e,h),d=xt.lengthOnControlPolygon(this.b[0],s,a,u);return d>t+C.distanceEpsilon?1:d<t-C.distanceEpsilon?-1:0}}function wn(l){return l.seg.value(l.par)}function ys(l){return l.seg.derivative(l.par)}function Cs(l){return l.seg.secondDerivative(l.par)}function _s(l){return l.seg.thirdDerivative(l.par)}var at;(function(l){l[l.Outside=0]="Outside",l[l.Boundary=1]="Boundary",l[l.Inside=2]="Inside"})(at||(at={}));function vn(l){if(l instanceof yt)return{tag:"ellipse",segData:l.toJSON()};if(l instanceof N)return{tag:"lineSegment",segData:l.toJSON()};if(l instanceof xt)return{tag:"bezier",segData:l.toJSON()};throw new Error("not implemented")}class w{static fromJSON(t){const e=new w;for(const i of t.segs)switch(i.tag){case"bezier":e.addSegment(xt.fromJSON(i.segData));break;case"ellipse":e.addSegment(yt.fromJSON(i.segData));break;case"lineSegment":e.addSegment(N.fromJSON(i.segData));break;default:throw new Error("not implemented")}return e}toJSON(){return{segs:this.segs.map(t=>vn(t))}}static CurvesIntersect(t,e){return t===e||w.intersectionOne(t,e,!1)!=null}static lengthWithInterpolationAndThreshold(t,e){throw new Error("not implemented")}static lengthWithInterpolation(t){throw"not implemented"}get parStart(){return 0}get parEnd(){return this.parEnd_}lengthPartial(t,e){const i={start:t,end:e};this.adjustStartEndEndParametersToDomain(i);const s=this.getSegIndexParam(t),n=this.getSegIndexParam(e);if(s.segIndex<n.segIndex){let o=this.segs[s.segIndex],a=o.lengthPartial(s.par,o.parEnd);for(let h=s.segIndex+1;h<n.segIndex;h++)a+=this.segs[h].length;return o=this.segs[n.segIndex],a+o.lengthPartial(o.parStart,n.par)}else throw new Error("not implemented.")}reverse(){const t=new w;for(let e=this.segs.length-1;e>=0;e--)t.addSegment(this.segs[e].reverse());return t}constructor(){this.segs=[],this.parEnd_=0}mkCurveWithSegs(t){this.segs=t;for(const e of t)this.parEnd_+=w.paramSpan(e)}get start(){return this.segs[0].start}get end(){return this.segs[this.segs.length-1].end}scaleFromOrigin(t,e){const i=new w;for(const s of this.segs)i.addSegment(s.scaleFromOrigin(t,e));return i}trim(t,e){const i={start:t,end:e};this.adjustStartEndEndParametersToDomain(i);const s=this.getSegIndexParam(i.start),n=this.getSegIndexParam(i.end);if(s.segIndex===n.segIndex)return this.segs[s.segIndex].trim(s.par,n.par);let o=new w;s.par<this.segs[s.segIndex].parEnd&&(o=o.addSegment(this.segs[s.segIndex].trim(s.par,this.segs[s.segIndex].parEnd)));for(let a=s.segIndex+1;a<n.segIndex;a++)o=o.addSegment(this.segs[a]);return this.segs[n.segIndex].parStart<n.par&&(o=o.addSegment(this.segs[n.segIndex].trim(this.segs[n.segIndex].parStart,n.par))),o}translate(t){for(const e of this.segs)e.translate(t);this.boundingBox_&&(this.boundingBox_=X.translate(this.boundingBox_,t)),this.pBNode=null}adjustStartEndEndParametersToDomain(t){if(t.start>t.end){const e=t.start;t.start=t.end,t.end=e}t.start<this.parStart&&(t.start=this.parStart),t.end>this.parEnd&&(t.end=this.parEnd)}trimWithWrap(t,e){if(t<e)return this.trim(t,e);const i=new w;return i.addSegment(this.trim(t,this.parEnd)),i.addSegment(this.trim(this.parStart,e)),i}addSegs(t){for(const e of t)this.addSegment(e);return this}addSegment(t){if(t==null)return this;if(this.boundingBox_=null,!(t instanceof w))this.segs.push(t),this.parEnd_+=w.paramSpan(t);else for(const e of t.segs)this.segs.push(e),this.parEnd_+=w.paramSpan(e);return this}pNodeOverICurve(){if(this.pBNode!=null)return this.pBNode;const t=[],e=[];for(const i of this.segs){const s=i.pNodeOverICurve();t.push(s.parallelogram),e.push(s)}return this.pBNode={parallelogram:Pt.getParallelogramOfAGroup(t),seg:this,leafBoxesOffset:C.defaultLeafBoxesOffset,node:{children:e}},this.pBNode}static intersectionOne(t,e,i){let s=w.curveCurveXWithParallelogramNodesOne(t.pNodeOverICurve(),e.pNodeOverICurve());return i&&s!=null&&(s=w.liftIntersectionToCurves(t,e,s)),s}static getAllIntersections(t,e,i){return t instanceof N?w.getAllIntersectionsOfLineAndICurve(t,e,i):w.getAllIntersectionsInternal(t,e,i)}static getAllIntersectionsInternal(t,e,i){const s=[];if(w.curveCurveXWithParallelogramNodes(t.pNodeOverICurve(),e.pNodeOverICurve(),s),i)for(let n=0;n<s.length;n++)s[n]=w.liftIntersectionToCurves(t,e,s[n]);return s}static getAllIntersectionsOfLineAndICurve(t,e,i){return e instanceof st?w.getAllIntersectionsOfLineAndPolyline(t,e):e instanceof w?w.getAllIntersectionsOfLineAndCurve(t,e,i):e instanceof yt&&e.isArc()?w.getAllIntersectionsOfLineAndArc(t,e):w.getAllIntersectionsInternal(t,e,i)}static getAllIntersectionsOfLineAndCurve(t,e,i){const s=[],n=t.pNodeOverICurve(),o=e.pNodeOverICurve();if(Pt.intersect(n.parallelogram,o.parallelogram)===!1)return s;let a=0;for(const h of e.segs){const u=w.getAllIntersections(t,h,!1);if(i){for(const d of u)d.par1+=a-h.parStart,d.seg1=e;a+=h.parEnd-h.parStart}for(const d of u)w.alreadyInside(s,d)||s.push(d)}return s}static closeIntersections(t,e){return c.close(t.x,e.x,C.intersectionEpsilon)}static closeIntersectionPoints(t,e){return c.close(t,e,C.intersectionEpsilon)}static alreadyInside(t,e){for(let i=0;i<t.length;i++){const s=t[i];if(w.closeIntersections(s,e))return!0}return!1}static getAllIntersectionsOfLineAndArc(t,e){let i=t.end.sub(t.start);const s=[],n=i.length;if(n<C.distanceEpsilon){const m=t.start.sub(e.center);if(R(m.length,e.aAxis.length)){let y=c.angle(e.aAxis,m);e.parStart-C.tolerance<=y&&(y=Math.max(y,e.parStart),y<=e.parEnd+C.tolerance&&(y=Math.min(e.parEnd,y),s.push(new ri(0,y,t.start,t,e))))}return s}const o=i.rotate90Ccw().div(n),a=t.start.sub(e.center).dot(o),h=e.center.add(o.mul(a)),u=e.aAxis.length,d=Math.abs(a);if(u<d-C.distanceEpsilon)return s;if(i=o.rotate90Cw(),R(u,d))w.tryToAddPointToLineCircleCrossing(t,e,s,h,n,i);else{const m=Math.sqrt(u*u-a*a),y=i.mul(m);w.tryToAddPointToLineCircleCrossing(t,e,s,h.add(y),n,i),w.tryToAddPointToLineCircleCrossing(t,e,s,h.sub(y),n,i)}return s}static tryToAddPointToLineCircleCrossing(t,e,i,s,n,o){let h=s.sub(t.start).dot(o);if(h<-C.distanceEpsilon||(h=Math.max(h,0),h>n+C.distanceEpsilon))return;h=Math.min(h,n),h/=n;let u=c.angle(e.aAxis,s.sub(e.center));e.parStart-C.tolerance<=u&&(u=Math.max(u,e.parStart),u<=e.parEnd+C.tolerance&&(u=Math.min(e.parEnd,u),i.push(new ri(h,u,s,t,e))))}static getAllIntersectionsOfLineAndPolyline(t,e){const i=[];let s=0,n=e.startPoint;for(;n!=null&&n.getNext()!=null;n=n.getNext()){const o=w.crossTwoLineSegs(t.start,t.end,n.point,n.getNext().point,0,1,0,1);o&&(w.adjustSolution(t.start,t.end,n.point,n.getNext().point,o),w.oldIntersection(i,o.x)||i.push(new ri(o.aSol,s+o.bSol,o.x,t,e))),s++}if(e.closed){const o=w.crossTwoLineSegs(t.start,t.end,n.point,e.start,0,1,0,1);o&&(w.adjustSolution(t.start,t.end,n.point,e.start,o),w.oldIntersection(i,o.x)||i.push(new ri(o.aSol,s+o.bSol,o.x,t,e)))}return i}static adjustSolution(t,e,i,s,n){w.closeIntersectionPoints(n.x,t)?(n.x=t,n.aSol=0):w.closeIntersectionPoints(n.x,e)&&(n.x=e,n.aSol=1),w.closeIntersectionPoints(n.x,i)?(n.x=i,n.bSol=Math.floor(n.bSol)):w.closeIntersectionPoints(n.x,s)&&(n.x=s,n.bSol=Math.ceil(n.bSol))}static curveCurveXWithParallelogramNodesOne(t,e){if(!Pt.intersect(t.parallelogram,e.parallelogram))return null;const i=t.node,s=e.node,n=i.hasOwnProperty("children"),o=s.hasOwnProperty("children");if(n&&o)for(const a of i.children)for(const h of s.children){const u=w.curveCurveXWithParallelogramNodesOne(a,h);if(u!=null)return u}else if(o)for(const a of s.children){const h=w.curveCurveXWithParallelogramNodesOne(t,a);if(h!=null)return h}else if(n)for(const a of i.children){const h=w.curveCurveXWithParallelogramNodesOne(a,e);if(h!=null)return h}else return w.crossOverIntervalsOne(t,e);return null}static curveCurveXWithParallelogramNodes(t,e,i){if(!Pt.intersect(t.parallelogram,e.parallelogram))return;const s=t.node.hasOwnProperty("children"),n=e.node.hasOwnProperty("children");if(s&&n)for(const o of t.node.children)for(const a of e.node.children)w.curveCurveXWithParallelogramNodes(o,a,i);else if(n)for(const o of e.node.children)w.curveCurveXWithParallelogramNodes(t,o,i);else if(s)for(const o of t.node.children)w.curveCurveXWithParallelogramNodes(o,e,i);else i=w.crossOverLeaves(t,e,i)}static crossOverIntervalsOne(t,e){const i=t.node,s=e.node,n=(i.high-i.low)/2,o=(s.high-s.low)/2;for(let a=1;a<2;a++){const h=a*n+i.low;for(let u=1;u<2;u++){const d=u*o+s.low;let m;if(i.chord==null&&s.chord==null?m=w.crossWithinIntervalsWithGuess(t.seg,e.seg,i.low,i.high,s.low,s.high,h,d):i.chord!=null&&s.chord==null?m=w.crossWithinIntervalsWithGuess(i.chord,e.seg,0,1,s.low,s.high,.5*a,d):i.chord==null?(m=w.crossWithinIntervalsWithGuess(t.seg,s.chord,i.low,i.high,0,1,h,.5*u),m&&(m.bSol=s.low+m.bSol*(s.high-s.low))):(m=w.crossWithinIntervalsWithGuess(i.chord,s.chord,0,1,0,1,.5*a,.5*u),m&&(m.aSol=i.low+m.aSol*(i.high-i.low),m.bSol=s.low+m.bSol*(s.high-s.low))),m)return w.createIntersectionOne(t,e,m.aSol,m.bSol,m.x)}}return w.goDeeperOne(t,e)}static crossOverLeaves(t,e,i){const s=t.node,n=e.node;let o=!1;const a=(s.high-s.low)/2+s.low,h=(n.high-n.low)/2+n.low;let u;return s.chord==null&&n.chord==null?u=w.crossWithinIntervalsWithGuess(t.seg,e.seg,s.low,s.high,n.low,n.high,a,h):s.chord!=null&&n.chord==null?(u=w.crossWithinIntervalsWithGuess(s.chord,e.seg,0,1,n.low,n.high,.5,h),u&&(u.aSol=s.low+u.aSol*(s.high-s.low))):s.chord==null?(u=w.crossWithinIntervalsWithGuess(t.seg,n.chord,s.low,s.high,0,1,a,.5),u&&(u.bSol=n.low+u.bSol*(n.high-n.low))):(u=w.crossWithinIntervalsWithGuess(s.chord,n.chord,0,1,0,1,.5,.5),u&&(u.bSol=n.low+u.bSol*(n.high-n.low),u.aSol=s.low+u.aSol*(s.high-s.low))),u&&(w.addIntersection(t,e,i,u),o=!0),o||w.goDeeper(i,t,e),i}static addIntersection(t,e,i,s){const n=t.node;w.closeIntersectionPoints(s.x,t.seg.value(n.low))?(s.x=t.seg.value(n.low),s.aSol=n.low):w.closeIntersectionPoints(s.x,t.seg.value(n.high))&&(s.x=t.seg.value(n.high),s.aSol=n.high);const o=e.node;if(w.closeIntersectionPoints(s.x,e.seg.value(o.low))?(s.x=e.seg.value(o.low),s.bSol=o.low):w.closeIntersectionPoints(s.x,e.seg.value(o.high))&&(s.x=e.seg.value(o.high),s.bSol=o.high),!w.oldIntersection(i,s.x)){const h=new ri(s.aSol,s.bSol,s.x,t.seg,e.seg);i.push(h)}}static oldIntersection(t,e){for(const i of t)if(e.sub(i.x).length<C.distanceEpsilon*100)return!0;return!1}static createIntersectionOne(t,e,i,s,n){const o=t.node,a=e.node;return w.closeIntersectionPoints(n,t.seg.value(o.low))?(n=t.seg.value(o.low),i=o.low):w.closeIntersectionPoints(n,t.seg.value(o.high))&&(n=t.seg.value(o.high),i=o.high),w.closeIntersectionPoints(n,e.seg.value(a.low))?(n=e.seg.value(a.low),s=a.low):w.closeIntersectionPoints(n,e.seg.value(a.high))&&(n=e.seg.value(a.high),s=a.high),new ri(i,s,n,t.seg,e.seg)}static liftIntersectionToCurves_(t,e,i,s,n,o,a){const h=t instanceof w?w.liftParameterToCurve(t,i-o.parStart,o):i,u=e instanceof w?w.liftParameterToCurve(e,s-a.parStart,a):s;return new ri(h,u,n,t,e)}static DropIntersectionToSegs(t){let e,i;if(t.seg0 instanceof w){const o=t.seg0.getSegParam(t.par0);e=o.seg,i=o.par}else i=t.par0,e=t.seg0;let s,n;if(t.seg1 instanceof w){const o=t.seg1.getSegParam(t.par1);n=o.par,s=o.seg}else n=t.par1,s=t.seg1;return new ri(i,n,t.x,e,s)}static liftIntersectionToCurves(t,e,i){return w.liftIntersectionToCurves_(t,e,i.par0,i.par1,i.x,i.seg0,i.seg1)}static liftParameterToCurve(t,e,i){if(t===i)return e;if(!t.hasOwnProperty("segs"))return;const s=t;let n=0;for(const o of s.segs){if(o===i)return e+n;n+=w.paramSpan(o)}throw"bug in liftParameterToCurve"}static paramSpan(t){return t.parEnd-t.parStart}static goDeeperOne(t,e){const i=t.node,s=e.node;if(t.leafBoxesOffset>C.distanceEpsilon&&e.leafBoxesOffset>C.distanceEpsilon){const a=Rt.createParallelogramNodeForCurveSeg(i.low,i.high,t.seg,t.leafBoxesOffset/2),h=Rt.createParallelogramNodeForCurveSeg(s.low,s.high,e.seg,e.leafBoxesOffset/2);return w.curveCurveXWithParallelogramNodesOne(a,h)}if(t.leafBoxesOffset>C.distanceEpsilon){const a=Rt.createParallelogramNodeForCurveSeg(i.low,i.high,t.seg,t.leafBoxesOffset/2);return w.curveCurveXWithParallelogramNodesOne(a,e)}if(e.leafBoxesOffset>C.distanceEpsilon){const a=Rt.createParallelogramNodeForCurveSeg(s.low,s.high,e.seg,e.leafBoxesOffset/2);return w.curveCurveXWithParallelogramNodesOne(t,a)}const n=t.seg.value(i.low),o=t.seg.value(i.high);if(!c.closeDistEps(n,o)){const a=e.seg.value(s.low),h=e.seg.value(s.high);if(!c.closeDistEps(a,h)){const u=t.seg instanceof N?t.seg:N.mkPP(n,o),d=e.seg instanceof N?e.seg:N.mkPP(a,h),m=w.crossWithinIntervalsWithGuess(u,d,0,1,0,1,.5,.5);if(m)return w.adjustParameters(t,u,e,d,m),w.createIntersectionOne(t,e,m.aSol,m.bSol,m.x)}}return null}static goDeeper(t,e,i){const s=e.node,n=i.node,o=e.leafBoxesOffset>C.distanceEpsilon,a=i.leafBoxesOffset>C.distanceEpsilon;if(o&&a){const h=Rt.createParallelogramNodeForCurveSeg(s.low,s.high,e.seg,e.leafBoxesOffset/2),u=Rt.createParallelogramNodeForCurveSeg(n.low,n.high,i.seg,i.leafBoxesOffset/2);w.curveCurveXWithParallelogramNodes(h,u,t)}else if(o){const h=Rt.createParallelogramNodeForCurveSeg(s.low,s.high,e.seg,e.leafBoxesOffset/2);w.curveCurveXWithParallelogramNodes(h,i,t)}else if(a){const h=Rt.createParallelogramNodeForCurveSeg(n.low,n.high,i.seg,i.leafBoxesOffset/2);w.curveCurveXWithParallelogramNodes(e,h,t)}else{const h=e.seg.value(s.low),u=e.seg.value(s.high);if(!c.closeDistEps(h,u)){const d=i.seg.value(n.low),m=i.seg.value(n.high);if(!c.closeDistEps(d,m)){const y=e.seg instanceof N?e.seg:N.mkPP(h,u),E=i.seg instanceof N?i.seg:N.mkPP(d,m),T=w.crossWithinIntervalsWithGuess(y,E,0,1,0,1,.5,.5);T&&(w.adjustParameters(e,y,i,E,T),w.addIntersection(e,i,t,T))}}}}static adjustParameters(t,e,i,s,n){if(e!==t.seg&&!(t.seg instanceof st))n.aSol=t.seg.closestParameter(n.x);else{const o=t.node;n.aSol=o.low+n.aSol*(o.high-o.low)}if(s!==i.seg&&!(i.seg instanceof st))n.bSol=i.seg.closestParameter(n.x);else{const o=i.node;n.bSol=o.low+n.bSol*(o.high-o.low)}}getSegParam(t){let e=this.parStart;for(const s of this.segs){const n=e+s.parEnd-s.parStart;if(t>=e&&t<=n)return{par:t-e+s.parStart,seg:s};e=n}const i=this.segs[this.segs.length-1];return{seg:i,par:i.parEnd}}getSegIndexParam(t){let e=0;const i=this.segs.length;for(let n=0;n<i;n++){const o=this.segs[n],a=e+o.parEnd-o.parStart;if(t>=e&&t<=a)return{segIndex:n,par:t-e+o.parStart};e=a}const s=this.segs[i-1];return{segIndex:i-1,par:s.parEnd}}value(t){return wn(this.getSegParam(t))}derivative(t){return ys(this.getSegParam(t))}secondDerivative(t){return Cs(this.getSegParam(t))}thirdDerivative(t){return _s(this.getSegParam(t))}static crossWithinIntervalsWithGuess(t,e,i,s,n,o,a,h){if(t instanceof N&&e instanceof N){const m=w.crossTwoLineSegs(t.start,t.end,e.start,e.end,i,s,n,o);if(m!==void 0)return m}const u=w.minDistWithinIntervals(t,e,i,s,n,o,a,h);if(u==null)return;const d=u.aX.sub(u.bX);return d.dot(d)>=C.distanceEpsilon?void 0:{aSol:u.aSol,bSol:u.bSol,x:c.middle(u.aX,u.bX)}}static crossTwoLineSegs(t,e,i,s,n,o,a,h){const u=e.sub(t),d=i.sub(s),m=i.sub(t),y=O.solve(u.x,d.x,m.x,u.y,d.y,m.y);if(y==null)return;let E=y.x,T=y.y;const B=t.add(u.mul(E));if(!(E<n-C.tolerance)&&(E=Math.max(E,n),!(E>o+C.tolerance)&&(E=Math.min(E,o),!(T<a-C.tolerance)&&(T=Math.max(T,a),!(T>h+C.tolerance)))))return T=Math.min(T,h),{aSol:E,bSol:T,x:B}}static PointRelativeToCurveLocation(t,e){if(!e.boundingBox.contains(t))return at.Outside;const i=2*e.boundingBox.diagonal,s=Math.PI/180;let n=0;for(let o=13;o<360;o+=13){const a=new c(Math.cos(o*s),Math.sin(o*s)),h=N.mkPP(t,t.add(a.mul(i))),u=this.getAllIntersectionsOfLineAndICurve(h,e,!0);if(w.AllIntersectionsAreGood(u,e)){for(const m of u)if(c.closeDistEps(m.x,t))return at.Boundary;if(u.length%2===1?n++:n--,n>=2)return at.Inside;if(n<=-2)return at.Outside}}return at.Boundary}static AllIntersectionsAreGood(t,e){const i=e.hasOwnProperty("segs");let s=null;if(i||e instanceof st&&(s=e.toCurve()),s){for(const n of t)if(!w.RealCut(w.DropIntersectionToSegs(n),s,!1))return!1}return!0}static RealCut(t,e,i){const s=t.seg0,n=t.seg1,o=t.par0,a=t.par1,h=t.x,u=s.derivative(o).normalize(),d=n.derivative(a).normalize().rotate(Math.PI/2);if(c.closeDistEps(h,n.end)){let y=null;for(let B=0;B<e.segs.length-1;B++)if(e.segs[B]===n){y=e.segs[B+1];break}if(y==null)return!1;const E=u.rotate(Math.PI/2);return!(E.dot(n.derivative(n.parEnd))*E.dot(y.derivative(y.parStart))<C.tolerance)}if(c.closeDistEps(h,n.start)){let y=null;for(let B=e.segs.length-1;B>0;B--)if(e.segs[B]===n){y=e.segs[B-1];break}if(y==null)return!1;const E=u.rotate(Math.PI/2);return!(E.dot(n.derivative(n.parStart))*E.dot(y.derivative(y.parEnd))<C.tolerance)}const m=u.dot(d);return i?m>C.distanceEpsilon:Math.abs(m)>C.distanceEpsilon}static realCutWithClosedCurve(t,e,i){const s=t.seg0,n=t.seg1,o=t.par0,a=t.par1,h=t.x,u=s.derivative(o).normalize(),d=n.derivative(a).normalize().rotate(Math.PI/2);if(c.closeDistEps(h,n.end)){let y=null;for(let B=0;B<e.segs.length;B++)if(e.segs[B]===n){y=e.segs[(B+1)%e.segs.length];break}if(y==null)throw new Error;const E=u.rotate(Math.PI/2);return!(E.dot(n.derivative(n.parEnd))*E.dot(y.derivative(y.parStart))<C.tolerance)}if(c.closeDistEps(h,n.start)){let y=null;for(let B=0;B<e.segs.length;B++)if(e.segs[B]===n){y=e.segs[B>0?B-1:e.segs.length-1];break}const E=u.rotate(Math.PI/2);return!(E.dot(n.derivative(n.parStart))*E.dot(y.derivative(y.parEnd))<C.tolerance)}const m=u.dot(d);return i?m>C.distanceEpsilon:Math.abs(m)>C.distanceEpsilon}static minDistWithinIntervals(t,e,i,s,n,o,a,h){const u=new Zs(t,e,i,s,n,o,a,h);return u.solve(),u.success?{aSol:u.aSolution,bSol:u.bSolution,aX:u.aPoint,bX:u.bPoint}:void 0}offsetCurve(t,e){throw new Error("Method not implemented.")}get boundingBox(){if(this.boundingBox_)return this.boundingBox_;if(this.segs.length===0)this.boundingBox_=X.mkEmpty();else{const t=this.segs[0].boundingBox.clone();for(let e=1;e<this.segs.length;e++)t.addRecSelf(this.segs[e].boundingBox);return this.boundingBox_=t}}clone(){const t=new w;for(const e of this.segs)t.addSegment(e.clone());return this.boundingBox_!=null&&(t.boundingBox_=this.boundingBox_.clone()),t}getParameterAtLength(t){let e=0;for(const i of this.segs){const s=i.length;if(s>=t)return e+i.getParameterAtLength(t);t-=s,e+=i.parEnd-i.parStart}return this.parEnd}get length(){let t=0;for(const e of this.segs)t+=e.length;return t}transform(t){const e=new w;for(const i of this.segs)e.addSegment(i.transform(t));return this.boundingBox_&&(e.boundingBox_=this.boundingBox_.transform(t)),e}closestParameterWithinBounds(t,e,i){let s=0,n=Number.MAX_VALUE,o=0;for(const a of this.segs){if(o>i)break;const h=w.paramSpan(a);if(o+h>=e){const d=Math.max(a.parStart,a.parStart+(e-o)),m=Math.min(a.parEnd,a.parStart+(i-o)),y=a.closestParameterWithinBounds(t,d,m),E=t.sub(a.value(y)),T=E.dot(E);T<n&&(s=o+y-a.parStart,n=T)}o+=h}return s}closestParameter(t){let e=0,i=Number.MAX_VALUE,s=0;for(const n of this.segs){const o=n.closestParameter(t),a=t.sub(n.value(o)),h=a.dot(a);if(h<i){if(e=s+o-n.parStart,h===0)break;i=h}s+=w.paramSpan(n)}return e}static addLineSegment(t,e,i){return t.addSegment(N.mkPP(e,i))}static addLineSegmentCNNP(t,e,i,s){return w.addLineSegment(t,new c(e,i),s)}static addLineSegmentCNNNN(t,e,i,s,n){w.addLineSegment(t,new c(e,i),new c(s,n))}static continueWithLineSegmentNN(t,e,i){w.addLineSegment(t,t.end,new c(e,i))}static continueWithLineSegmentP(t,e){w.addLineSegment(t,t.end,e)}static closeCurve(t){return w.continueWithLineSegmentP(t,t.start),t}leftDerivative(t){const e=this.tryToGetLeftSegment(t);return e!=null?e.derivative(e.parEnd):this.derivative(t)}rightDerivative(t){const e=this.tryToGetRightSegment(t);return e!=null?e.derivative(e.parStart):this.derivative(t)}tryToGetLeftSegment(t){if(Math.abs(t-this.parStart)<C.tolerance)return this.start.equal(this.end)?this.segs[this.segs.length-1]:null;for(const e of this.segs)if(t-=w.paramSpan(e),Math.abs(t)<C.tolerance)return e;return null}tryToGetRightSegment(t){if(Math.abs(t-this.parEnd)<C.tolerance)return this.start===this.end?this.segs[0]:null;for(const e of this.segs){if(Math.abs(t)<C.tolerance)return e;t-=w.paramSpan(e)}return null}static ClosestPoint(t,e){return t.value(t.closestParameter(e))}static CurveIsInsideOther(t,e){if(!e.boundingBox.containsRect(t.boundingBox))return!1;const i=w.getAllIntersections(t,e,!0);if(i.length===0)return w.NonIntersectingCurveIsInsideOther(t,e);if(i.length===1)return t.start.equal(i[0].x)?w.PointRelativeToCurveLocation(t.value((t.parStart+t.parEnd)/2),e)==at.Inside:w.PointRelativeToCurveLocation(t.start,e)===at.Inside;for(const s of w.PointsBetweenIntersections(t,i))if(w.PointRelativeToCurveLocation(s,e)===at.Outside)return!1;return!0}static*PointsBetweenIntersections(t,e){e.sort((a,h)=>a.par0-h.par0);for(let a=0;a<e.length-1;a++)yield t.value((e[a].par0+e[a+1].par0)/2);const i=e[e.length-1].par0,s=e[0].par0,n=t.parEnd-i+(s-t.parStart);let o=i+n/2;o>t.parEnd&&(o=t.parStart+(o-t.parEnd)),yield t.value(o)}static NonIntersectingCurveIsInsideOther(t,e){for(let i=t.parStart;i<t.parEnd;i+=.5){const s=w.PointRelativeToCurveLocation(t.value(i),e);if(at.Boundary!==s)return at.Inside===s}return at.Outside!==w.PointRelativeToCurveLocation(t.end,e)}static ClosedCurveInteriorsIntersect(t,e){if(!e.boundingBox.intersects(t.boundingBox))return!1;const i=w.getAllIntersections(t,e,!0);if(i.length===0)return w.NonIntersectingCurveIsInsideOther(t,e)||w.NonIntersectingCurveIsInsideOther(e,t);if(i.length===1)return t.start.equal(i[0].x)?w.PointRelativeToCurveLocation(t.value((t.parStart+t.parEnd)/2),e)===at.Inside||!e.start.equal(i[0].x)?w.PointRelativeToCurveLocation(e.start,t)===at.Inside:w.PointRelativeToCurveLocation(e.value((e.parStart+e.parEnd)/2),t)===at.Inside:w.PointRelativeToCurveLocation(t.start,e)===at.Inside;for(const s of w.PointsBetweenIntersections(t,i))if(w.PointRelativeToCurveLocation(s,e)===at.Inside)return!0;return!0}curvature(t){const e=this.getSegParam(t);return e.seg.curvature(e.par)}curvatureDerivative(t){throw new Error("Not implemente")}curvatureSecondDerivative(t){throw new Error("Not implemented")}static createBezierSeg(t,e,i,s,n){const o=c.mkPoint(t,i.point,1-t,s.point),a=c.mkPoint(e,n.point,1-e,s.point),h=s.point.mul(2/3);return new xt(o,o.div(3).add(h),h.add(a.div(3)),a)}static createBezierSegN(t,e,i,s){const n=i.mul(s);return new xt(t,t.add(n),e.add(n),e)}static findCorner(t){const e=t.next;if(e.next==null)return;const i=e.next;if(i!=null)return{b:e,c:i}}static trimEdgeSplineWithNodeBoundaries(t,e,i,s){let n=i.parStart,o=i.parEnd;t!=null&&(n=w.findNewStart(i,n,t,s)),e!=null&&(o=w.findNewEnd(i,e,s,o));const a=Math.min(n,o),h=Math.max(n,o);return a<h?i.trim(a,h):i}static findNewEnd(t,e,i,s){const n=w.getAllIntersections(t,e,!0);if(n.length===0)return s=t.parEnd,s;if(i){s=t.parEnd;for(const o of n)o.par0<s&&(s=o.par0)}else{s=t.parStart;for(const o of n)o.par0>s&&(s=o.par0)}return s}static findNewStart(t,e,i,s){const n=w.getAllIntersections(t,i,!0);if(n.length===0){e=t.parStart;return}if(s){e=t.parStart;for(const o of n)o.par0>e&&(e=o.par0)}else{e=t.parEnd;for(const o of n)o.par0<e&&(e=o.par0)}return e}static polylineAroundClosedCurve(t){if(t instanceof yt)return w.refineEllipse(t);if(t instanceof st)return t;if(t instanceof w&&w.allSegsAreLines(t)){const e=new st;for(const i of t.segs)e.addPoint(i.start);if(e.closed=!0,!e.isClockwise())return e.reverse()}return t.boundingBox.perimeter()}static allSegsAreLines(t){for(const e of t.segs)if(!(e instanceof N))return!1;return!0}static refineEllipse(t){const e=t.boundingBox.perimeter(),i=Math.PI/4,s=t.boundingBox.width,n=t.boundingBox.height,o=Math.sqrt(s*s+n*n),a=[];for(let u=0;u<4;u++){const d=i+u*Math.PI/2,m=t.value(d),y=t.derivative(d).normalize().mul(o),E=N.mkPP(m.sub(y),m.add(y));for(const T of w.getAllIntersections(e,E,!0))a.push(T)}a.sort((u,d)=>u.par0<d.par0?-1:u.par0>d.par0?1:0);const h=new st;return a.forEach(u=>h.addPoint(u.x)),h.closed=!0,h}static polyFromBox(t){const e=new st;return e.addPoint(t.leftTop),e.addPoint(t.rightTop),e.addPoint(t.rightBottom),e.addPoint(t.leftBottom),e.closed=!0,e}}function Pi(l,t,e,i,s,n){if(s instanceof LineSegment)return!0;for(const o of[1/3,.5,2/3]){const a=l*o+e*(1-o);if(Point.closeSquare(s.value(a),Point.mkPoint(o,t,1-o,i),n*n)===!1)return!1}return!0}function As(l,t,e,i,s,n){let o=[];if(Pi(l,t,e,i,s,n))o.push(t),o.push(i);else{const a=.5*(l+e),h=s.value(a);o=As(l,t,a,h,s,n);const u=As(a,h,e,i,s,n).slice(1);o=o.concat(u)}return o}function Pr(l,t){return As(l.parStart,l.start,l.parEnd,l.end,l,t)}function*Sr(l,t){if(t.containsRectWithPadding(l.boundingBox,1)){yield l;return}const e=t.perimeter(),i=w.getAllIntersections(l,e,!0);if(i.length==0){t.contains(l.start)&&(yield l);return}i.sort((o,a)=>o.par0-a.par0);const s=[l.parStart];let n=0;for(;n<i.length;n++){const o=i[n];o.par0>s[s.length-1]+GeomConstants.distanceEpsilon&&s.push(o.par0)}for(l.parEnd>s[s.length-1]+GeomConstants.distanceEpsilon&&s.push(l.parEnd),n=0;n<s.length-1;n++)tn(l,s[n],s[n+1],t)&&(yield l.trim(s[n],s[n+1]))}function*In(l,t){if(l==null)return;if(t.containsRect(l.boundingBox)){yield l;return}const e=w.getAllIntersections(l,t.perimeter(),!0);if(e.length==0){t.contains(l.start)&&(yield l);return}e.sort((n,o)=>n.par0-o.par0);const i=[l.parStart];let s=0;for(;s<e.length;s++){const n=e[s];n.par0>i[i.length-1]+GeomConstants.distanceEpsilon&&i.push(n.par0)}for(l.parEnd>i[i.length-1]+GeomConstants.distanceEpsilon&&i.push(l.parEnd),s=0;s<i.length-1;s++)if(tn(l,i[s],i[s+1],t)){const n=l.trim(i[s],i[s+1]);n&&(yield n)}}function tn(l,t,e,i){const s=(e-t)/5;for(let n=1;n<5;n++){const o=t+s*n;if(i.contains(l.value(o)))return!0}return!1}class st{constructor(){this.initIsRequired=!0,this.isClosed_=!1}toJSON(){return{points:Array.from(this).map(t=>t.toJSON())}}static fromJSON(t){return st.mkFromPoints(t.points.map(e=>c.fromJSON(e)))}RemoveStartPoint(){const t=this.startPoint.next;t.prev=null,this.startPoint=t,this.setInitIsRequired()}RemoveEndPoint(){const t=this.endPoint.prev;t.next=null,this.endPoint=t,this.setInitIsRequired()}setInitIsRequired(){this.initIsRequired=!0}addPointXY(t,e){this.addPoint(new c(t,e))}isClockwise(){return c.getTriangleOrientation(this.startPoint.point,this.startPoint.next.point,this.startPoint.next.next.point)==D.Clockwise}addPoint(t){const e=new zt;e.polyline=this,e.point=t.clone(),this.endPoint!=null?(this.endPoint.next=e,e.prev=this.endPoint,this.endPoint=e):this.startPoint=this.endPoint=e,this.setInitIsRequired()}PrependPoint(t){const e=zt.mkFromPoint(t);e.polyline=this,this.startPoint!=null?c.closeDistEps(t,this.startPoint.point)||(this.startPoint.prev=e,e.next=this.startPoint,this.startPoint=e):(this.endPoint=e,this.startPoint=e),this.setInitIsRequired()}*[Symbol.iterator](){for(let t=this.startPoint;t!=null;t=t.next)yield t.point}*polylinePoints(){for(let t=this.startPoint;t!=null;t=t.next)yield t}*skip(t){for(let e=this.startPoint;e!=null;e=e.next)t>0?t--:yield e}static parallelogramOfLineSeg(t,e){const i=e.sub(t).div(2);return Pt.parallelogramByCornerSideSide(t,i,i)}static mkFromPoints(t){const e=new st;for(const i of t)e.addPoint(i);return e}static mkClosedFromPoints(t){const e=st.mkFromPoints(t);return e.closed=!0,e}calculatePbNode(){const t=[],e=[];let i=this.startPoint,s=0;for(;i.next!=null;){const n=st.parallelogramOfLineSeg(i.point,i.next.point);t.push(n),e.push({parallelogram:n,seg:this,leafBoxesOffset:0,node:{low:s,high:s+1,chord:N.mkPP(i.point,i.next.point)}}),i=i.next,s++}if(this.isClosed_){const n=st.parallelogramOfLineSeg(this.endPoint.point,this.startPoint.point);t.push(n),e.push({parallelogram:n,seg:this,leafBoxesOffset:0,node:{low:s,high:s+1,chord:N.mkPP(this.endPoint.point,this.startPoint.point)}})}this.pBNode={parallelogram:Pt.getParallelogramOfAGroup(t),seg:this,leafBoxesOffset:0,node:{children:e}}}init(){this.bBox=X.rectangleOnPoint(this.startPoint.point);for(const t of this.skip(1))this.bBox.add(t.point);this.updateCount(),this.calculatePbNode(),this.initIsRequired=!1}updateCount(){this.count_=0;for(let t=this.startPoint;t!=null;t=t.next)this.count_++}get count(){return this.initIsRequired&&this.init(),this.count_}get closed(){return this.isClosed_}set closed(t){this.isClosed_=t}value(t){this.initIsRequired&&this.init();const e=this.getAdjustedParamAndStartEndPoints(t);return c.convSum(e.t,e.a,e.b)}getAdjustedParamAndStartEndPoints(t){let e=this.startPoint;for(;e.next!=null;){if(t<=1)return{a:e.point,b:e.next.point,t};e=e.next,t-=1}if(this.closed&&t<=1)return{a:this.endPoint.point,b:this.startPoint.point,t};throw new Error("out of the parameter domain")}derivative(t){const e=this.getAdjustedParamAndStartEndPoints(t);return e.b.sub(e.a)}secondDerivative(t){return new c(0,0)}thirdDerivative(t){return new c(0,0)}pNodeOverICurve(){return this.initIsRequired&&this.init(),this.pBNode}get boundingBox(){return this.initIsRequired&&this.init(),this.bBox}get parStart(){return 0}get parEnd(){return this.initIsRequired&&this.init(),this.closed?this.count_:this.count_-1}static polylineFromCurve(t){const e=new st;e.addPoint(t.start);for(const i of t.segs)e.addPoint(i.end);return e.closed=t.start===t.end,e}trim(t,e){let i=this.toCurve();return i=i.trim(t,e),i instanceof w?st.polylineFromCurve(i):st.mkFromPoints([i.start,i.end])}trimWithWrap(t,e){throw new Error("Method not implemented.")}translate(t){let e=this.startPoint;do{if(e.point=e.point.add(t),e===this.endPoint)break;e=e.getNext()}while(!0);this.setInitIsRequired()}scaleFromOrigin(t,e){throw new Error("Method not implemented.")}get start(){return this.startPoint.point}get end(){return this.endPoint.point}reverse(){const t=new st;t.closed=this.closed;let e=this.endPoint;do{if(t.addPoint(e.point),e===this.startPoint)break;e=e.getPrev()}while(!0);return t}offsetCurve(t,e){throw new Error("Method not implemented.")}lengthPartial(t,e){throw new Error("Method not implemented.")}get length(){throw new Error("Method not implemented.")}getParameterAtLength(t){throw new Error("Method not implemented.")}transform(t){const e=new st;for(const i of this.polylinePoints())e.addPoint(t.multiplyPoint(i.point));return e.closed=this.closed,e}closestParameterWithinBounds(t,e,i){throw new Error("Method not implemented.")}closestParameter(t){let e=0,i=Number.MAX_VALUE,s=0,n=this.startPoint;for(;n.next!=null;){const o=N.mkPP(n.point,n.next.point),a=o.closestParameter(t),h=o.value(a).sub(t),u=h.dot(h);u<i&&(i=u,e=a+s),n=n.next,s++}if(this.closed){const o=N.mkPP(this.endPoint.point,this.startPoint.point),a=o.closestParameter(t),h=o.value(a).sub(t);h.dot(h)<i&&(e=a+s)}return e}clone(){const t=new st;t.closed=this.closed;let e=this.startPoint;do{if(t.addPoint(e.point),e===this.endPoint)break;e=e.getNext()}while(!0);return t}leftDerivative(t){throw new Error("Method not implemented.")}rightDerivative(t){throw new Error("Method not implemented.")}curvature(t){throw new Error("Method not implemented.")}curvatureDerivative(t){throw new Error("Method not implemented.")}curvatureSecondDerivative(t){throw new Error("Method not implemented.")}next(t){var e;return(e=t.next)!==null&&e!==void 0?e:this.closed?this.startPoint:null}prev(t){var e;return(e=t.prev)!==null&&e!==void 0?e:this.closed?this.endPoint:null}toCurve(){const t=new w;w.addLineSegment(t,this.startPoint.point,this.startPoint.next.point);let e=this.startPoint.next;for(;(e=e.next)!=null;)w.continueWithLineSegmentP(t,e.point);return this.closed&&w.continueWithLineSegmentP(t,this.startPoint.point),t}RemoveCollinearVertices(){for(let t=this.startPoint.next;t.next!=null;t=t.next)c.getTriangleOrientation(t.prev.point,t.point,t.next.point)===D.Collinear&&(t.prev.next=t.next,t.next.prev=t.prev);return this.setInitIsRequired(),this}}class be{pad(t){this.width+=t*2}constructor(t,e=t){this.width=t,this.height=e}}class X{transform(t){return X.mkPP(t.multiplyPoint(this.leftTop),t.multiplyPoint(this.rightBottom))}translate(t){return X.mkSizeCenter(this.size,this.center.add(t))}equal(t){return this.left_===t.left&&this.right_===t.right&&this.top_===t.top&&this.bottom_===t.bottom}equalEps(t){return R(this.left_,t.left)&&R(this.right_,t.right)&&R(this.top_,t.top)&&R(this.bottom_,t.bottom)}static mkSizeCenter(t,e){const i=t.width/2,s=t.height/2;return new X({left:e.x-i,right:e.x+i,bottom:e.y-s,top:e.y+s})}constructor(t){this.left_=t.left,this.right_=t.right,this.top_=t.top,this.bottom=t.bottom}add_rect(t){return this.addRec(t)}contains_point(t){return this.contains(t)}contains_rect(t){return this.containsRect(t)}intersection_rect(t){return this.intersection(t)}intersects_rect(t){return this.intersects(t)}unite(t){return X.rectangleOfTwo(this,t)}contains_point_radius(t,e){return this.containsWithPadding(t,e)}intersects(t){return this.intersectsOnX(t)&&this.intersectsOnY(t)}intersection(t){if(!this.intersects(t)){const o=X.mkEmpty();return o.setToEmpty(),o}const e=Math.max(this.left,t.left),i=Math.min(this.right,t.right),s=Math.max(this.bottom,t.bottom),n=Math.min(this.top,t.top);return new X({left:e,bottom:s,right:i,top:n})}get center(){return this.leftTop.add(this.rightBottom).mul(.5)}set center(t){const e=this.leftTop.add(this.rightBottom).mul(.5),i=t.sub(e);this.leftTop=this.leftTop.add(i),this.rightBottom=this.rightBottom.add(i)}intersectsOnY(t){return!(t.bottom_>this.top_+C.distanceEpsilon||t.top_<this.bottom_-C.distanceEpsilon)}intersectsOnX(t){return!(t.left>this.right_+C.distanceEpsilon||t.right<this.left_-C.distanceEpsilon)}static mkEmpty(){return new X({left:0,right:-1,bottom:0,top:-1})}get left(){return this.left_}set left(t){this.left_=t,this.onUpdated()}get right(){return this.right_}set right(t){this.right_=t,this.onUpdated()}get top(){return this.top_}set top(t){this.top_=t,this.onUpdated()}get bottom(){return this.bottom_}set bottom(t){this.bottom_=t,this.onUpdated()}get leftBottom(){return new c(this.left_,this.bottom_)}set leftBottom(t){this.left_=t.x,this.bottom=t.y}get rightTop(){return new c(this.right_,this.top_)}set rightTop(t){this.right_=t.x,this.top_=t.y}get leftTop(){return new c(this.left_,this.top_)}set leftTop(t){this.left_=t.x,this.top_=t.y}get rightBottom(){return new c(this.right_,this.bottom_)}set rightBottom(t){this.right_=t.x,this.bottom=t.y}onUpdated(){}static mkPP(t,e){const i=new X({left:t.x,right:t.x,top:t.y,bottom:t.y});return i.add(e),i}static rectangleOnPoint(t){return new X({left:t.x,right:t.x,top:t.y,bottom:t.y})}static mkLeftBottomSize(t,e,i){const s=t+i.width,n=e+i.height;return new X({left:t,right:s,top:n,bottom:e})}static getRectangleOnCoords(t,e,i,s){const n=new X({left:t,bottom:e,right:t,top:e});return n.add(new c(i,s)),n}static mkOnPoints(t){const e=X.mkEmpty();for(const i of t)e.add(i);return e}static mkOnRectangles(t){const e=X.mkEmpty();for(const i of t)e.addRecSelf(i);return e}get width(){return this.right_-this.left_}set width(t){const e=t/2,i=(this.left_+this.right_)/2;this.left_=i-e,this.right_=i+e}isEmpty(){return this.right<this.left}setToEmpty(){this.left=0,this.right=-1}get height(){return this.top_-this.bottom_}set height(t){const e=t/2,i=(this.top_+this.bottom_)/2;this.top_=i+e,this.bottom=i-e}static rectangleOfTwo(t,e){const i=new X({left:t.left_,right:t.right_,top:t.top_,bottom:t.bottom_});return i.addRecSelf(e),i}containsWithPadding(t,e){return this.left_-e-C.distanceEpsilon<=t.x&&t.x<=this.right_+e+C.distanceEpsilon&&this.bottom_-e-C.distanceEpsilon<=t.y&&t.y<=this.top_+e+C.distanceEpsilon}get area(){return(this.right_-this.left_)*(this.top_-this.bottom_)}add(t){this.isEmpty()?(this.left_=this.right_=t.x,this.top_=this.bottom=t.y):(this.left_>t.x&&(this.left_=t.x),this.top_<t.y&&(this.top_=t.y),this.right_<t.x&&(this.right_=t.x),this.bottom_>t.y&&(this.bottom=t.y))}addRecSelf(t){this.add(t.leftTop),this.add(t.rightBottom)}addRec(t){const e=this.clone();return e.add(t.leftTop),e.add(t.rightBottom),e}static translate(t,e){const i=t.clone();return i.center=t.center.add(e),i}static transform(t,e){return X.mkPP(e.multiplyPoint(t.leftTop),e.multiplyPoint(t.rightBottom))}contains(t){return this.containsWithPadding(t,0)}containsRect(t){return this.contains(t.leftTop)&&this.contains(t.rightBottom)}containsRectWithPadding(t,e){return this.containsWithPadding(t.leftTop,e)&&this.containsWithPadding(t.rightBottom,e)}get diagonal(){return Math.sqrt(this.width*this.width+this.height*this.height)}padWidth(t){this.left-=t,this.right+=t}padHeight(t){this.top+=t,this.bottom-=t}pad(t){t<-this.width/2&&(t=-this.width/2),t<-this.height/2&&(t=-this.height/2),this.padWidth(t),this.padHeight(t)}padEverywhere(t){this.left-=t.left,this.right+=t.right,this.bottom-=t.bottom,this.top+=t.top}static intersect(t,e){return t.intersects(e)?X.mkPP(new c(Math.max(t.left,e.left),Math.max(t.bottom,e.bottom)),new c(Math.min(t.right,e.right),Math.min(t.top,e.top))):X.mkEmpty()}perimeter(){const t=new st;return t.addPoint(this.leftTop),t.addPoint(this.rightTop),t.addPoint(this.rightBottom),t.addPoint(this.leftBottom),t.closed=!0,t}scaleAroundCenter(t){this.width=this.width*t,this.height=this.height*t}clone(){return new X({left:this.left,right:this.right,top:this.top,bottom:this.bottom})}get size(){return new be(this.width,this.height)}set size(t){this.width=t.width,this.height=t.height}static creatRectangleWithSize(t,e){const i=t.width/2,s=e.x-i,n=e.x+i,o=t.height/2,a=e.y-o,h=e.y+o;return new X({left:s,right:n,top:h,bottom:a})}addPointWithSize(t,e){const i=t.width/2,s=t.height/2;this.add(new c(e.x-i,e.y-s)),this.add(new c(e.x+i,e.y-s)),this.add(new c(e.x-i,e.y+s)),this.add(new c(e.x+i,e.y+s))}}class Dt{constructor(){this.previouisBezierCoefficient=.5,this.nextBezierCoefficient=.5,this.previousTangentCoefficient=1/3,this.nextTangentCoefficient=1/3}static mkSiteP(t){const e=new Dt;return e.point=t,e}static mkSiteSP(t,e){const i=new Dt;return i.point=e,i.prev=t,t.next=i,i}static mkSiteSPS(t,e,i){const s=new Dt;return s.prev=t,s.point=e,s.next=i,t.next=s,i.prev=s,s}get turn(){return this.next==null||this.prev==null?0:c.getTriangleOrientation(this.prev.point,this.point,this.next.point)}clone(){const t=new Dt;return t.previouisBezierCoefficient=this.previouisBezierCoefficient,t.point=this.point,t}}let M=0;class Y{static mkFromPoints(t){let e=null,i=null;for(const s of t)if(i==null)i=Dt.mkSiteP(s),e=new Y(i);else{const n=Dt.mkSiteP(s);n.prev=i,i.next=n,i=n}return e}clone(){let t=this.headSite,e=null,i,s=null;for(;t!=null;)i=t.clone(),i.prev=e,e!=null?e.next=i:s=i,t=t.next,e=i;return new Y(s)}constructor(t){this.headSite=t}get lastSite(){let t=this.headSite;for(;t.next!=null;)t=t.next;return t}*[Symbol.iterator](){let t=this.headSite;for(;t!=null;)yield t.point,t=t.next}createCurve(){const t=new w;let e=this.headSite,i;do{const s=w.findCorner(e);if(s==null)break;const n=Y.createBezierSegOnSite(s.b);t.segs.length===0?c.closeDistEps(e.point,n.start)||w.addLineSegment(t,e.point,n.start):c.closeDistEps(t.end,n.start)||w.continueWithLineSegmentP(t,n.start),t.addSegment(n),e=s.b}while(!0);return t.segs.length===0?c.closeDistEps(e.point,e.next.point)?t.segs.push(new xt(e.point,e.point.add(new c(5,5)),e.point.add(new c(-5,5)),i.point)):w.addLineSegment(t,e.point,e.next.point):c.closeDistEps(t.end,e.next.point)||w.continueWithLineSegmentP(t,e.next.point),t}static createBezierSegOnSite(t){const e=t.previouisBezierCoefficient,i=t.nextBezierCoefficient,s=t.prev,n=t.next,o=s.point.mul(e).add(t.point.mul(1-e)),a=n.point.mul(i).add(t.point.mul(1-i)),h=o.mul(t.previousTangentCoefficient).add(t.point.mul(1-t.previousTangentCoefficient)),u=a.mul(t.nextTangentCoefficient).add(t.point.mul(1-t.nextTangentCoefficient));return xt.mkBezier([o,h,u,a])}}class U{get Elements(){return this.elements}getElem(t,e){return this.elements[t][e]}setElem(t,e,i){this.elements[t][e]=i}static Divide(t,e){return t.multiply(e.inverse())}isIdentity(){return R(this.elements[0][0],1)&&R(this.elements[0][1],0)&&R(this.elements[0][2],0)&&R(this.elements[1][0],0)&&R(this.elements[1][1],1)&&R(this.elements[1][2],0)}offset(){return new c(this.getElem(0,2),this.getElem(1,2))}static getIdentity(){return new U(1,0,0,0,1,0)}constructor(t,e,i,s,n,o){this.elements=[[t,e,i],[s,n,o]]}static rotation(t){const e=Math.cos(t),i=Math.sin(t);return new U(e,-i,0,i,e,0)}static scaleAroundCenterTransformation(t,e,i){const s=1-t,n=1-e;return new U(t,0,s*i.x,0,e,n*i.y)}multiplyPoint(t){return new c(this.getElem(0,0)*t.x+this.getElem(0,1)*t.y+this.getElem(0,2),this.getElem(1,0)*t.x+this.getElem(1,1)*t.y+this.getElem(1,2))}multiply(t){return t!=null?new U(this.getElem(0,0)*t.getElem(0,0)+this.getElem(0,1)*t.getElem(1,0),this.getElem(0,0)*t.getElem(0,1)+this.getElem(0,1)*t.getElem(1,1),this.getElem(0,0)*t.getElem(0,2)+this.getElem(0,1)*t.getElem(1,2)+this.getElem(0,2),this.getElem(1,0)*t.getElem(0,0)+this.getElem(1,1)*t.getElem(1,0),this.getElem(1,0)*t.getElem(0,1)+this.getElem(1,1)*t.getElem(1,1),this.getElem(1,0)*t.getElem(0,2)+this.getElem(1,1)*t.getElem(1,2)+this.getElem(1,2)):null}inverse(){const t=this.getElem(0,0)*this.getElem(1,1)-this.getElem(1,0)*this.getElem(0,1),e=this.getElem(1,1)/t,i=-this.getElem(0,1)/t,s=-this.getElem(1,0)/t,n=this.getElem(0,0)/t,o=-e*this.getElem(0,2)-i*this.getElem(1,2),a=-s*this.getElem(0,2)-n*this.getElem(1,2);return new U(e,i,o,s,n,a)}}class W{static mkEllipse(t,e,i){return yt.mkFullEllipseNNP(t,e,i)}static createParallelogram(t,e,i){const s=e/2,n=t/2,o=i.x,a=i.y,h=80*Math.PI/180,u=s/Math.tan(h);return st.mkClosedFromPoints([new c(-n-u+o,-s+a),new c(n+o,-s+a),new c(n+o+u,s+a),new c(-n+o,s+a)])}static createHexagon(t,e,i){const s=e/2,n=t/2,o=i.x,a=i.y;return st.mkClosedFromPoints([new c(-n+o,-s+a),new c(n+o,-s+a),new c(n+(s+o),0+a),new c(n+o,s+a),new c(-n+o,s+a),new c(-(n-s)+o,0+a)])}static createOctagon(t,e,i){const s=t/2,n=e/2,o=new Array(8);o[0]=new c(s+W.octagonPad*s,n-n*W.octagonPad),o[3]=new c(o[0].x*-1,o[0].y),o[4]=new c(o[3].x,o[3].y*-1),o[7]=new c(o[0].x,o[0].y*-1),o[1]=new c(s-s*W.octagonPad,n+n*W.octagonPad),o[2]=new c(o[1].x*-1,o[1].y),o[6]=new c(o[1].x,o[1].y*-1),o[5]=new c(o[2].x,o[2].y*-1);for(let a=0;a<8;a++)o[a]=o[a].add(i);return st.mkClosedFromPoints(o)}static createInvertedHouse(t,e,i){const s=W.createHouse(t,e,i);return W.rotateCurveAroundCenterByDegree(s,i,180)}static createHouse(t,e,i){const s=t/2,n=e/2,o=i.x,a=i.y,h=new w;return w.addLineSegmentCNNNN(h,o-s,a-n,o+s,a-n),w.continueWithLineSegmentNN(h,o+s,a+n),w.continueWithLineSegmentNN(h,o,a+2*n),w.continueWithLineSegmentNN(h,o-s,a+n),w.closeCurve(h)}static mkDiamond(t,e,i){const s=t,n=e,o=i.x,a=i.y,h=new w,u=[new c(o,a-n),new c(o+s,a),new c(o,a+n),new c(o-s,a)];return h.addSegs([N.mkPP(u[0],u[1]),N.mkPP(u[1],u[2]),N.mkPP(u[2],u[3]),N.mkPP(u[3],u[0])]),h}static rotateCurveAroundCenterByDegree(t,e,i){return W.rotateCurveAroundCenterByRadian(t,e,i*Math.PI/180)}static rotateCurveAroundCenterByRadian(t,e,i){const s=Math.cos(i),n=Math.sin(i),o=new U(1,0,e.x,0,1,e.y).multiply(new U(s,-n,0,n,s,0)).multiply(new U(1,0,-e.x,0,1,-e.y));return t.transform(o)}static mkCircle(t,e){return yt.mkCircle(t,e)}static createRectangle(t,e,i){const s=t/2,n=e/2,o=i.x,a=i.y,h=new w,u=[new c(o-s,a-n),new c(o+s,a-n),new c(o+s,a+n),new c(o-s,a+n)];return h.addSegs([N.mkPP(u[0],u[1]),N.mkPP(u[1],u[2]),N.mkPP(u[2],u[3]),N.mkPP(u[3],u[0])]),h}static isRoundedRect(t){if(!(t instanceof w))return;const e=t.segs;if(e.length!==8&&e.length!==4)return;const i=e.length===8;let s,n;for(let o=0;o<4;o++){const a=i?2*o+1:o;if(o===0){if(!(e[a]instanceof yt))return;const h=e[a];s=h.aAxis.length,n=h.bAxis.length}else{if(!(e[a]instanceof yt))return;const h=e[a];if(s!==h.aAxis.length||n!==h.bAxis.length)return}}return{radX:s,radY:n}}static mkRectangleWithRoundedCorners(t,e,i,s,n=new c(0,0)){if(i===0||s===0)return W.createRectangle(t,e,n);const o=new w,a=t/2;i>a/2&&(i=a/2);const h=e/2;s>h/2&&(s=h/2);const u=n.x,d=n.y,m=a-i,y=h-s,E=d+h,T=d-h,B=u-a,H=u+a,tt=new c(i,0),lt=new c(0,s);return m>0&&o.addSegment(N.mkPP(new c(u-m,T),new c(u+m,T))),o.addSegment(yt.mkEllipse(1.5*Math.PI,2*Math.PI,tt,lt,u+m,d-y)),y>0&&o.addSegment(N.mkPP(new c(H,d-y),new c(H,d+y))),o.addSegment(yt.mkEllipse(0,.5*Math.PI,tt,lt,u+m,d+y)),m>0&&o.addSegment(N.mkPP(new c(u+m,E),new c(u-m,E))),o.addSegment(yt.mkEllipse(.5*Math.PI,Math.PI,tt,lt,u-m,d+y)),y>0&&o.addSegment(N.mkPP(new c(B,d+y),new c(B,d-y))),o.addSegment(yt.mkEllipse(Math.PI,1.5*Math.PI,tt,lt,u-m,d-y)),o}}W.octagonPad=1/4;function K(l){return l.parEnd-l.parStart}function $(l){switch(l.type){case"ellipse":return yt.fromJSON(l.data);case"curve":return w.fromJSON(l.data);case"lineSegment":return N.fromJSON(l.data);case"bezier":return xt.fromJSON(l.data);case"polyline":return st.fromJSON(l.data)}}function it(l){if(l instanceof Ellipse)return"ellipse";if(l instanceof Curve)return"curve";if(l instanceof LineSegment)return"lineSegment";if(l instanceof BezierSeg)return"bezier";if(l instanceof Polyline)return"polyline";throw new Error("not implemented")}function ht(l){return{type:it(l),data:l.toJSON()}}var v;(function(l){l[l.None=0]="None",l[l.North=1]="North",l[l.East=2]="East",l[l.South=4]="South",l[l.West=8]="West"})(v||(v={}));class L{static get DifferenceEpsilon(){return L.differenceEpsilon}static EqualPP(t,e){return L.Equal(t.x,e.x)&&L.Equal(t.y,e.y)}static Equal(t,e){return L.Compare(t,e)===0}static Compare(t,e){let i=0;return t+L.DifferenceEpsilon<e?i=-1:e+L.DifferenceEpsilon<t&&(i=1),i}static ComparePP(t,e){let i=L.Compare(t.x,e.x);return i===0&&(i=L.Compare(t.y,e.y)),i}static LessOrEqual(t,e){const i=L.Compare(t,e);return i<0||i===0}static Less(t,e){return L.Compare(t,e)<0}static GetDirections(t,e){return j.DirectionFromPointToPoint(t,e)}static IsPureDirection(t,e){return j.IsPureDirection(L.GetDirections(t,e))}static IsPureDirectionD(t){return j.IsPureDirection(t)}static IsPureLower(t,e){const i=L.GetDirections(t,e);return v.East===i||v.North===i}static GetPureDirectionVV(t,e){return L.GetDirections(t.point,e.point)}}L.differenceEpsilon=C.distanceEpsilon/2;class j{constructor(t){this.Dir=t}get Right(){return new j(j.RotateRight(this.Dir))}static RotateRight(t){switch(t){case v.North:return v.East;case v.East:return v.South;case v.South:return v.West;case v.West:return v.North;default:throw new Error}}static RotateLeft(t){switch(t){case v.North:return v.West;case v.West:return v.South;case v.South:return v.East;case v.East:return v.North;default:throw new Error}}static ToIndex(t){switch(t){case v.North:return 0;case v.East:return 1;case v.South:return 2;case v.West:return 3;default:throw new Error}}static VectorDirection(t){let e=v.None;return t.x>L.DifferenceEpsilon?e=v.East:t.x<-L.DifferenceEpsilon&&(e=v.West),t.y>L.DifferenceEpsilon?e=e|v.North:t.y<-L.DifferenceEpsilon&&(e=e|v.South),e}static VectorDirectionPP(t,e){let i=v.None;const s=e.x-t.x,n=e.y-t.y;return s>L.DifferenceEpsilon?i=v.East:-s>L.DifferenceEpsilon&&(i=v.West),n>L.DifferenceEpsilon?i|=v.North:-n>L.DifferenceEpsilon&&(i|=v.South),i}static DirectionFromPointToPoint(t,e){return j.VectorDirectionPP(t,e)}static OppositeDir(t){switch(t){case v.North:return v.South;case v.West:return v.East;case v.South:return v.North;case v.East:return v.West;default:return v.None}}static IsPureDirection(t){switch(t){case v.North:return!0;case v.East:return!0;case v.South:return!0;case v.West:return!0;default:return!1}}static IsPureDirectionPP(t,e){return j.IsPureDirection(j.DirectionFromPointToPoint(t,e))}static DirectionsAreParallel(t,e){return t===e||t===j.OppositeDir(e)}ToPoint(){let t=0,e=0;return(this.Dir&v.East)===v.East&&t++,(this.Dir&v.North)===v.North&&e++,(this.Dir&v.West)===v.West&&t--,(this.Dir&v.South)===v.South&&e--,new c(t,e)}static toPoint(t){return new j(t).ToPoint()}static negate(t){return new j(j.OppositeDir(t.Dir))}}class Es extends ot{clone(){const t=new Es(null,null);return t.isPositioned=this.isPositioned,t._boundingBox=this._boundingBox.clone(),t.attachmentSegmentEnd=this.attachmentSegmentEnd,t.attachmentSegmentStart=this.attachmentSegmentStart,t}get isPositioned(){return this._isPositioned}set isPositioned(t){this._isPositioned=t}constructor(t,e){super(t),this._isPositioned=!1,e&&(this.boundingBox=X.mkPP(new c(0,0),new c(e.width,e.height)))}get boundingBox(){return this._boundingBox}set boundingBox(t){this._boundingBox=t}setBoundingBox(t){this.isPositioned=!0,this._boundingBox=t}get width(){return this.boundingBox.width}set width(t){this.boundingBox.width=t}get height(){return this.boundingBox.height}set height(t){this.boundingBox.height=t}get center(){return this.boundingBox.center}set center(t){this.boundingBox.center=t}translate(t){this.isPositioned&&(this.center=this.center.add(t))}transform(t){this.isPositioned&&(this.center=t.multiplyPoint(this.center))}positionCenter(t){this.boundingBox.center=t,this.isPositioned=!0}}class we extends ot{*getSmoothPolyPoints(){yield this.source.center,this.curve instanceof w?yield*this.getCurvePoints(this.curve):this.curve instanceof N?(yield this.curve.start,yield this.curve.end):this.curve instanceof yt?(yield this.curve.start,yield this.curve.value((this.curve.parStart+this.curve.parEnd)/.5),yield this.curve.end):this.curve instanceof xt&&(yield this.curve.start,yield this.curve.value(.25),yield this.curve.value(.75),yield this.curve.end),yield this.target.center}*getCurvePoints(t){for(const e of t.segs)if(yield e.start,e instanceof xt){const i=yr(e);i&&(yield i)}yield t.end}static getGeom(t){return ot.getGeom(t)}clone(){const t=new we(null);return this.smoothedPolyline&&(t.smoothedPolyline=this.smoothedPolyline.clone()),t.curve=this.curve.clone(),this.sourceArrowhead!=null&&(t.sourceArrowhead=this.sourceArrowhead.clone()),this.targetArrowhead!=null&&(t.targetArrowhead=this.targetArrowhead.clone()),t}get label(){return this.edge!=null&&this.edge.label!=null?ot.getGeom(this.edge.label):null}set label(t){this.edge.label.setAttr(pt.GeomObjectIndex,t)}RaiseLayoutChangeEvent(t){this.edge.raiseEvents(t)}requireRouting(){this.curve=null,this.smoothedPolyline=null}translate(t){if(!(t.x===0&&t.y===0)){if(this.curve!=null&&this.curve.translate(t),this.smoothedPolyline!=null)for(let e=this.smoothedPolyline.headSite,i=this.smoothedPolyline.headSite;e!=null;e=e.next,i=i.next)e.point=i.point.add(t);if(this.sourceArrowhead!=null&&this.sourceArrowhead.tipPosition&&(this.sourceArrowhead.tipPosition=this.sourceArrowhead.tipPosition.add(t)),this.targetArrowhead!=null&&this.targetArrowhead.tipPosition&&(this.targetArrowhead.tipPosition=this.targetArrowhead.tipPosition.add(t)),this.edge.label){const e=Es.getGeom(this.edge.label);e&&e.translate(t)}}}GetMaxArrowheadLength(){let t=0;return this.sourceArrowhead!=null&&(t=this.sourceArrowhead.length),this.targetArrowhead!=null&&this.targetArrowhead.length>t?this.targetArrowhead.length:t}transform(t){if(this.curve!=null){if(this.curve=this.curve.transform(t),this.smoothedPolyline!=null)for(let e=this.smoothedPolyline.headSite,i=this.smoothedPolyline.headSite;e!=null;e=e.next,i=i.next)e.point=t.multiplyPoint(e.point);this.sourceArrowhead!=null&&(this.sourceArrowhead.tipPosition=t.multiplyPoint(this.sourceArrowhead.tipPosition)),this.targetArrowhead!=null&&(this.targetArrowhead.tipPosition=t.multiplyPoint(this.targetArrowhead.tipPosition))}}get edge(){return this.entity}get source(){return ot.getGeom(this.edge.source)}*sourceArrowheadPoints(t){if(this.sourceArrowhead==null)return;yield this.sourceArrowhead.tipPosition;let e=this.sourceArrowhead.tipPosition.sub(this.curve.start);e=e.rotate90Cw().mul(Math.tan(t*.5*(Math.PI/180))),yield e.add(this.curve.start),yield this.curve.start.sub(e)}*targetArrowheadPoints(t){if(this.targetArrowhead==null)return;yield this.targetArrowhead.tipPosition;let e=this.targetArrowhead.tipPosition.sub(this.curve.end);e=e.rotate90Cw().mul(Math.tan(t*.5*(Math.PI/180))),yield e.add(this.curve.end),yield this.curve.end.sub(e)}get boundingBox(){const t=X.mkEmpty();if(this.smoothedPolyline!=null)for(const i of this.smoothedPolyline)t.add(i);this.curve!=null&&t.addRecSelf(this.curve.boundingBox);for(const i of this.sourceArrowheadPoints(25))t.add(i);for(const i of this.targetArrowheadPoints(25))t.add(i);this.label&&t.addRecSelf(this.label.boundingBox);const e=this.lineWidth;return t.left-=e,t.top+=e,t.right+=e,t.bottom-=e,t}isInterGraphEdge(){return this.edge.isInterGraphEdge()}get target(){return ot.getGeom(this.edge.target)}constructor(t){super(t),this.lineWidth=1}toString(){return this.source.toString()+"->"+this.target}static RouteSelfEdge(t,e,i){const s=t.boundingBox.width,n=t.boundingBox.height,o=t.boundingBox.center,a=new c(o.x-s/4,o.y),h=new c(o.x-s/4,o.y-n/2-e),u=new c(o.x+s/4,o.y-n/2-e),d=new c(o.x+s/4,o.y);return i.smoothedPolyline=Y.mkFromPoints([a,h,u,d]),i.smoothedPolyline.createCurve()}underCollapsedGraph(){return this.source.underCollapsedGraph()||this.target.underCollapsedGraph()}EdgeToAncestor(){return this.edge.EdgeToAncestor()}}function yr(l){return c.lineLineIntersection(l.b[0],l.b[1],l.b[2],l.b[3])}var Ut=Ys(89796),Nt;(function(l){l[l.Continue=0]="Continue",l[l.Stop=1]="Stop"})(Nt||(Nt={}));function lo(l,t,e,i,s,n){for(let a=0;a<l.length;a++){if(a===t||a===e)continue;const h=n.box0.add_rect(l[a].irect),u=h.area-n.box0.area,d=n.box1.add_rect(l[a].irect),m=d.area-n.box1.area;i.length*2<s.length?(i.push(l[a]),n.box0=h):s.length*2<i.length?(s.push(l[a]),n.box1=d):u<m?(i.push(l[a]),n.box0=h):m<u?(s.push(l[a]),n.box1=d):n.box0.area<n.box1.area?(i.push(l[a]),n.box0=h):(s.push(l[a]),n.box1=d)}}function $t(l){if(l.length===0)return null;if(l.length===1)return l[0];const t={b0:l[0].irect,seed0:1},e=ho(l,t),i=[],s=[];i.push(l[t.seed0]),s.push(l[e]);const n={box0:l[t.seed0].irect,box1:l[e].irect};lo(l,t.seed0,e,i,s,n);const o=Tn(l.length);return o.irect=n.box0.add_rect(n.box1),o.Left=$t(i),o.Right=$t(s),o}function Cr(l,t){return l.add_rect(t).area}function ho(l,t){let e=Cr(t.b0,l[t.seed0].irect);for(let s=2;s<l.length;s++){const n=Cr(t.b0,l[s].irect);n>e&&(t.seed0=s,e=n)}let i;for(let s=0;s<l.length;s++)if(s!==t.seed0){i=s;break}e=l[t.seed0].irect.add_rect(l[i].irect).area;for(let s=0;s<l.length;s++){if(s===t.seed0)continue;const n=l[t.seed0].irect.add_rect(l[s].irect).area;n>e&&(i=s,e=n)}return i}function en(l,t){if(l==null||t==null)return null;const e=Array.from(l).map(i=>he(i,t(i)));return $t(e)}function Tn(l){const t=new On;return t.Count=l,t}function he(l,t){const e=new On;return e.UserData=l,e.irect=t,e.Count=1,e}function xn(l,t,e){return l.irect.intersects_rect(e)?t(l.UserData)===Nt.Continue?l.Left!=null?xn(l.Left,t,e)===Nt.Continue&&xn(l.Right,t,e)===Nt.Continue?Nt.Continue:Nt.Stop:Nt.Continue:Nt.Stop:Nt.Continue}class On{toString(){return this.IsLeaf?this.Count.toString()+" "+this.UserData:this.Count.toString()}get IsLeaf(){return this.left==null}get Left(){return this.left}set Left(t){this.left!=null&&this.left.Parent===this&&(this.left.Parent=null),this.left=t,this.left!=null&&(this.left.Parent=this)}get Right(){return this.right}set Right(t){this.right!=null&&this.right.Parent===this&&(this.right.Parent=null),this.right=t,this.right!=null&&(this.right.Parent=this)}get IsLeftChild(){return this===this.Parent.Left}FirstIntersectedNode(t){var e;return t.intersects_rect(this.irect)?this.IsLeaf?this:(e=this.Left.FirstIntersectedNode(t))!==null&&e!==void 0?e:this.Right.FirstIntersectedNode(t):null}FirstHitNodeWithPredicate(t,e){var i;return this.irect.contains_point(t)?this.IsLeaf?e(t,this.UserData)===Nt.Stop?this:null:(i=this.Left.FirstHitNodeWithPredicate(t,e))!==null&&i!==void 0?i:this.Right.FirstHitNodeWithPredicate(t,e):null}FirstHitByRectWithPredicate(t,e){var i;return this.irect.intersects_rect(t)?this.IsLeaf?e(this.UserData)===Nt.Stop?this:null:(i=this.Left.FirstHitByRectWithPredicate(t,e))!==null&&i!==void 0?i:this.Right.FirstHitByRectWithPredicate(t,e):null}FirstHitNode(t){var e;return this.irect.contains_point(t)?this.IsLeaf?this:(e=this.Left.FirstHitNode(t))!==null&&e!==void 0?e:this.Right.FirstHitNode(t):null}*AllHitItems(t,e=null){const i=new Ut.B;for(i.push(this);i.size>0;){const s=i.pop();s.irect.intersects_rect(t)&&(s.IsLeaf?(e==null||e(s.UserData))&&(yield s.UserData):(i.push(s.left),i.push(s.right)))}}*AllHitItems_(t){const e=new Ut.B;for(e.push(this);e.size>0;){const i=e.pop();i.irect.contains_point(t)&&(i.IsLeaf?yield i.UserData:(e.push(i.left),e.push(i.right)))}}VisitTree(t,e){xn(this,t,e)}Clone(){const t=Tn(this.Count);return t.UserData=this.UserData,t.irect=this.irect,this.Left!=null&&(t.Left=this.Left.Clone()),this.Right!=null&&(t.Right=this.Right.Clone()),t}*GetNodeItemsIntersectingRectangle(t){for(const e of this.GetLeafRectangleNodesIntersectingRectangle(t))yield e.UserData}*GetLeafRectangleNodesIntersectingRectangle(t){const e=new Ut.B;for(e.push(this);e.size>0;){const i=e.pop();i.irect.intersects_rect(t)&&(i.IsLeaf?yield i:(e.push(i.left),e.push(i.right)))}}*GetAllLeaves(){for(const t of this.GetAllLeafNodes())yield t.UserData}*GetAllLeafNodes(){for(const t of this.EnumRectangleNodes(!0))yield t}*EnumRectangleNodes(t){const e=new Ut.B;for(e.push(this);e.size>0;){const i=e.pop();(i.IsLeaf||!t)&&(yield i),i.IsLeaf||(e.push(i.left),e.push(i.right))}}TraverseHierarchy(t,e){e(t),t.Left!=null&&this.TraverseHierarchy(t.Left,e),t.Right!=null&&this.TraverseHierarchy(t.Right,e)}}class fe{constructor(t,e){vt(t,e)<0?(this._first=t,this._second=e):(this._first=e,this._second=t)}get first(){return this._first}get second(){return this._second}get Length(){return _(this._first,this._second)}CompareTo(t){const e=vt(this._first,t._first);return e!==0?e:vt(this._second,t._second)}static equal(t,e){return t._first.equal(e._first)&&t._second.equal(e._second)}toString(){return this._first+(" "+this._second)}}class Yt{delete(t){return this.deletexy(t.x,t.y)}clear(){this.mapOfSets.clear(),this.size_=0}get size(){return this.size_}static mk(t){const e=new Yt;for(const i of t)e.add(i);return e}addxy(t,e){let i=this.mapOfSets.get(t);i==null&&this.mapOfSets.set(t,i=new Set),i.has(e)||this.size_++,i.add(e)}add(t){return this.addxy(t.x,t.y),this}deletexy(t,e){const i=this.mapOfSets.get(t);return i!=null&&i.delete(e)?(this.size_--,!0):!1}hasxy(t,e){return this.mapOfSets.has(t)&&this.mapOfSets.get(t).has(e)}has(t){return this.hasxy(t.x,t.y)}constructor(){this.size_=0,this.mapOfSets=new Map}forEach(t,e){for(const i of this)t(i,i,e)}*entries(){for(const t of this)yield[t,t]}keys(){return this.values()}*values(){for(const t of this.mapOfSets)for(const e of t[1])yield new c(t[0],e)}[Symbol.iterator](){return this.values()}}function Xi(l,t){const e=new Set;for(const i of l)t.has(i)||e.add(i);return e}function uo(l,t){const e=new Yt;for(const i of l)t.has(i)||e.add(i);return e}function Ki(l,t){const e=new Set(l);for(const i of t)e.add(i);return e}function Bi(l,t){for(const e of t)l.push(e)}function Li(l,t){const e=new Set;if(l.size<t.size)for(const i of l)t.has(i)&&e.add(i);else for(const i of t)l.has(i)&&e.add(i);return e}function co(l){if(l.length===0)return new Set;let t=l[0];for(let e=1;e<l.length;e++)t=Li(t,l[e]);return t}function bs(l,t){for(const e of t)l.add(e)}function sn(l,t){if(l.size!==t.size)return!1;for(const e of l)if(!t.has(e))return!1;return!0}function ws(l,t){const e=[];for(const i of l)for(const s of t(i))e.push(s);return e}function nn(l,t,e){let i=l.get(t);i||(i=new Set,l.set(t,i)),i.add(e)}function Gi(l,t,e){let i=l.get(t);i||(i=new Array,l.set(t,i)),i.push(e)}function Bn(l,t,e){let i=l.get(t);i||(i=new Set,l.set(t,i)),i.add(e)}function Yi(l,t,e){Bn(l,new fe(t[0],t[1]),e)}function Ji(l,t,e){const i=l.get(t);i&&i.delete(e)}function Ar(l,t,e){Ji(l,new fe(t[0],t[1]),e)}function ia(l,t){const e=l.findIndex(i=>i===t);e>=0&&l.splice(e,1)}var Ge=Ys(38941);class Mt{static assert(t,e=null){if(!t)throw e!=null?(console.log(e),new Error(e)):new Error("condition does not hold")}}class vs{constructor(){this.attrs=[],this._parent=null}addEvent(t){this.events.push(t)}removeEvent(t){const e=this.events.indexOf(t);e>=0&&(this.events=this.events.splice(e,1))}raiseEvents(t){this.events.forEach(e=>e(t))}clearAttr(){this.attrs=[]}setAttr(t,e){this.attrs[t]=e}getAttr(t){return this.attrs[t]}get parent(){return this._parent}set parent(t){this._parent=t}*getAncestors(){let t=this.parent;for(;t!=null;)yield t,t=t.parent}isDescendantOf(t){for(const e of this.getAncestors())if(e===t)return!0;return!1}}var Si;(function(l){l[l.None=0]="None",l[l.FromAncestor=1]="FromAncestor",l[l.ToAncestor=2]="ToAncestor"})(Si||(Si={}));class Is extends vs{constructor(t,e){super(),this.source=t,this.target=e,t!==e?(t.outEdges.add(this),e.inEdges.add(this)):t.selfEdges.add(this)}add(){this.source!==this.target?(this.source.outEdges.add(this),this.target.inEdges.add(this)):this.source.selfEdges.add(this)}remove(){this.source!==this.target?(this.source.outEdges.delete(this),this.target.inEdges.delete(this)):this.source.selfEdges.delete(this)}toString(){return"("+this.source.toString()+"->"+this.target.toString()+")"}isInterGraphEdge(){return this.source.parent!==this.target.parent}EdgeToAncestor(){return this.source instanceof Vt&&this.target.isDescendantOf(this.source)?Si.FromAncestor:this.target instanceof Vt&&this.source.isDescendantOf(this.target)?Si.ToAncestor:Si.None}}class ze extends vs{removeOutEdge(t){this.outEdges.delete(t)}removeInEdge(t){this.inEdges.delete(t)}get id(){return this._id}set id(t){this._id=t}toString(){return this.id}constructor(t){super(),this.inEdges=new Set,this.outEdges=new Set,this.selfEdges=new Set,this.id=t}*_edges(){for(const t of this.inEdges)yield t;for(const t of this.outEdges)yield t;for(const t of this.selfEdges)yield t}get edges(){return this._edges()}get outDegree(){return this.outEdges.size}get inDegree(){return this.inEdges.size}get selfDegree(){return this.selfEdges.size}get degree(){return this.outDegree+this.inDegree+this.selfDegree}}class Zi{constructor(){this.nodeMap=new Map}remove(t){this.nodeMap.delete(t.id)}get size(){return this.nodeMap.size}*nodes_(){for(const t of this.nodeMap.values())yield t}*graphs_(){for(const t of this.nodes_())t instanceof Vt&&(yield t)}findShallow(t){return this.nodeMap.get(t)}get nodesShallow(){return this.nodes_()}get graphs(){return this.graphs_()}*_edges(){for(const t of this.nodeMap.values()){for(const e of t.outEdges)yield e;for(const e of t.selfEdges)yield e}}interGraphEdges(){throw new Error("not implemented")}get nodeShallowCount(){return this.nodeMap.size}get edgeCount(){let t=0;for(const e of this.nodeMap.values())t+=e.outDegree+e.selfDegree;return t}get edges(){return this._edges()}addNode(t){this.nodeMap.set(t.id,t)}nodeIsConsistent(t){for(const e of t.outEdges)if(e.source!==t||e.source===e.target)return!1;for(const e of t.inEdges)if(e.target!==t||e.source===e.target)return!1;for(const e of t.selfEdges)if(e.target!==e.source||e.source!==t)return!1;return!0}isConsistent(){for(const t of this.nodeMap.values())if(!this.nodeIsConsistent(t))return!1;return!0}}class Vt extends ze{remove(t){this.nodeCollection.remove(t)}removeSubgraph(){const t=this.parent;t&&t.removeNode(this);for(const e of this.outGoingEdges())e.attachedAtSource?e.node.removeOutEdge(e.edge):e.node.removeInEdge(e.edge)}*outGoingEdges(){for(const t of this.outEdges){const e=t.target;this.isAncestor(e)||(yield{edge:t,node:e,attachedAtSource:!1})}for(const t of this.inEdges){const e=t.source;this.isAncestor(e)||(yield{edge:t,node:e,attachedAtSource:!0})}for(const t of this.nodesBreadthFirst){for(const e of t.outEdges){const i=e.target;i!==this&&(this.isAncestor(i)||(yield{edge:e,node:i,attachedAtSource:!1}))}for(const e of t.inEdges){const i=e.source;i!==this&&(this.isAncestor(i)||(yield{edge:e,node:i,attachedAtSource:!0}))}}}isAncestor(t){for(const e of t.getAncestors())if(e===this)return!0;return!1}*getClusteredConnectedComponents(){const t=new Set,e=new Ge.o;for(const i of this.nodesBreadthFirst){if(t.has(i))continue;t.add(i),e.enqueue(i);const s=new Set;do{const n=e.dequeue();n.parent===this&&s.add(n);for(const o of this.reachableFrom(n))t.has(o)||(t.add(o),e.enqueue(o))}while(e.length>0);yield Array.from(s)}}*reachableFrom(t){for(const e of t.outEdges)yield e.target;for(const e of t.inEdges)yield e.source;t instanceof Vt&&(yield*t.shallowNodes),t.parent!=this&&(yield t.parent)}hasSomeAttrOnIndex(t){for(const e of this.nodesBreadthFirst)if(e.getAttr(t))return!0;for(const e of this.deepEdges)if(e.getAttr(t))return!0;return!1}*graphs(){for(const t of this.nodeCollection.graphs)yield t}noEmptySubgraphs(){for(const t of this.subgraphsBreadthFirst())if(t.shallowNodeCount===0)return!1;return!0}hasSubgraphs(){for(const t of this.shallowNodes)if(t instanceof Vt)return!0;return!1}*subgraphsBreadthFirst(){for(const t of this.nodesBreadthFirst)t instanceof Vt&&(yield t)}isEmpty(){return this.shallowNodeCount===0}setEdge(t,e){const i=this.nodeCollection.findShallow(t);if(i==null)return;const s=this.nodeCollection.findShallow(e);if(s!=null)return new Is(i,s)}get shallowNodes(){return this.nodeCollection.nodesShallow}get nodesBreadthFirst(){return this.nodesBreadthFirst_()}*nodesBreadthFirst_(){for(const t of this.nodeCollection.nodesShallow)yield t,t instanceof Vt&&(yield*t.nodesBreadthFirst)}constructor(t="__graph__"){super(t),this.nodeCollection=new Zi}findNodeRecursive(t){const e=this.nodeCollection.findShallow(t);if(e)return e;for(const i of this.shallowNodes)if(i instanceof Vt){const s=i.findNodeRecursive(t);if(s)return s}return null}findNode(t){return this.nodeCollection.findShallow(t)}get shallowEdges(){return this.nodeCollection.edges}get deepEdges(){return this.deepEdgesIt()}*deepEdgesIt(){for(const t of this.nodesBreadthFirst){for(const e of t.outEdges)yield e;for(const e of t.selfEdges)yield e;for(const e of t.inEdges)this.isAncestor(e.source)||(yield e)}}isConsistent(){return this.parent?this.parent.isConsistent():this.eachNodeIdIsUnique()&&this.nodeCollection.isConsistent()}nodeIsConsistent(t){return this.nodeCollection.nodeIsConsistent(t)}removeNode(t){for(const e of t.outEdges)e.target.inEdges.delete(e);for(const e of t.inEdges)e.source.outEdges.delete(e);this.nodeCollection.remove(t);for(const e of this.subgraphsBreadthFirst())e.removeNode(t)}addNode(t){return Mt.assert(this.findNodeRecursive(t.id)==null),t.parent=this,this.nodeCollection.addNode(t),t}get shallowNodeCount(){return this.nodeCollection.nodeShallowCount}get nodeCountDeep(){let t=this.nodeCollection.size;for(const e of this.shallowNodes)e instanceof Vt&&(t+=e.nodeCountDeep);return t}get edgeCount(){return this.nodeCollection.edgeCount}liftNode(t){for(;t!=null&&t.parent!==this;)t=t.parent;return t}get deepEdgesCount(){let t=0;for(const e of this.nodesBreadthFirst)t+=e.outDegree+e.selfDegree;return t}eachNodeIdIsUnique(){const t=new Set;for(const e of this.nodesBreadthFirst){if(t.has(e.id))return!1;t.add(e.id)}return!0}*allElements(){for(const t of this.allSuccessorsWidthFirst()){yield t;for(const e of t.selfEdges)yield e;for(const e of t.outEdges)yield e;for(const e of t.inEdges)this.isAncestor(e.source)||(yield e)}yield*this.edges}*allSuccessorsWidthFirst(){for(const t of this.shallowNodes)yield t;for(const t of this.shallowNodes)t instanceof Vt&&(yield*t.allSuccessorsWidthFirst())}*allSuccessorsDepthFirst(){for(const t of this.shallowNodes)t instanceof Vt&&(yield*t.allSuccessorsDepthFirst()),yield t}}function*Ln(l){const t=new Set,e=new Ge.o;for(const n of l.shallowNodes){if(t.has(n))continue;const o=new Array;for(s(n,e,t);e.length>0;){const a=e.dequeue();o.push(a);for(const h of i(a))s(h,e,t)}yield o}function*i(n){for(const o of n.outEdges)yield o.target;for(const o of n.inEdges)yield o.source}function s(n,o,a){a.has(n)||(o.enqueue(n),a.add(n))}}function Fn(l,t){t.parent&&t.parent.remove(t),l.addNode(t)}function go(l,t){let e=new Map;const i=l.nodeCountDeep;let s=1/i;for(const n of l.nodesBreadthFirst)e.set(n,s);for(let n=0;n<50;n++){s=(1-t)/i;const o=new Map;for(const a of l.nodesBreadthFirst)o.set(a,s);for(const a of l.nodesBreadthFirst){let h=o.get(a);for(const u of a.inEdges){const d=u.source;h+=t*(e.get(d)/d.outDegree)}o.set(a,h)}e=o}return e}function Dn(l,t){return t.has(l.source)&&t.has(l.target)}class Jt extends ot{clone(){const t=new Jt(null);return this.boundaryCurve&&(t.boundaryCurve=this.boundaryCurve.clone()),t}translate(t){t.x===0&&t.y===0||this.boundaryCurve.translate(t)}toJSON(){return{boundaryCurve:this.boundaryCurve}}get node(){return this.entity}get boundaryCurve(){return this._boundaryCurve}set boundaryCurve(t){t!=null&&t.boundingBox&&(t.boundingBox.height<Jt.minHeight||t.boundingBox.width<Jt.minWidth)&&(t=W.mkCircle(Jt.minWidth,t.boundingBox.center)),this._boundaryCurve=t}get id(){return this.node.id}toString(){return this.id}static mkNode(t,e){const i=new Jt(e);return i.boundaryCurve=t,i}get center(){return this.boundaryCurve.boundingBox.center}set center(t){const e=t.sub(this.center);this.boundaryCurve.translate(e)}fitBoundaryCurveToTarget(t){if(this.boundaryCurve!=null){const e=W.isRoundedRect(this.boundaryCurve);if(e==null){const i=t.width/this.boundaryCurve.boundingBox.width,s=t.height/this.boundaryCurve.boundingBox.height;this.boundaryCurve=this.boundaryCurve.scaleFromOrigin(i,s),this.boundaryCurve.translate(t.center.sub(this.boundaryCurve.boundingBox.center))}else this.boundaryCurve=W.mkRectangleWithRoundedCorners(t.width,t.height,e.radX,e.radY,t.center)}}static getGeom(t){return t.getAttr(pt.GeomObjectIndex)}*inEdges(){for(const t of this.node.inEdges)yield ot.getGeom(t)}*outEdges(){for(const t of this.node.outEdges)yield ot.getGeom(t)}*selfEdges(){for(const t of this.node.selfEdges)yield ot.getGeom(t)}get boundingBox(){return this.boundaryCurve?this.boundaryCurve.boundingBox:null}set boundingBox(t){this.boundaryCurve&&(Math.abs(t.width-this.width)<1e-4&&Math.abs(t.height-this.height)<1e-4?this.center=t.center:this.fitBoundaryCurveToTarget(t))}get width(){return this.boundaryCurve.boundingBox.width}get height(){return this.boundaryCurve.boundingBox.height}transform(t){this.boundaryCurve!=null&&(this.boundaryCurve=this.boundaryCurve.transform(t))}underCollapsedGraph(){const t=this.node.parent;if(t==null)return!1;const e=ot.getGeom(t);return e==null?!1:e.isCollapsed?!0:e.underCollapsedGraph()}*getAncestors(){for(const t of this.node.getAncestors())yield ot.getGeom(t)}}Jt.minHeight=2,Jt.minWidth=3;class Ft{ProgressStep(){}constructor(t){this.cancelToken=t}}class Ts{}Ts.GoldenRatio=(1+Math.sqrt(5))/2,Ts.GoldenRatioRemainder=2-Ts.GoldenRatio;class oi extends Ft{constructor(t,e){super(null),this.desiredAspectRatio=1.2,this.bestPacking=null,this.cachedCosts=new Map,this.rectangles=t,this.desiredAspectRatio=e}get PackedWidth(){return this.bestPacking!=null?this.bestPacking.PackedWidth:0}get PackedHeight(){return this.bestPacking!=null?this.bestPacking.PackedHeight:0}Pack(t,e,i){const s=oi.GetGoldenSectionStep(t,e),n=Math.max(i/10,(e-t)/oi.MaxSteps);e+=n,this.bestPackingCost=Number.MAX_VALUE,this.rectangles.length===1?this.PackLimit(t):this.rectangles.length===2?(this.PackLimit(t),this.PackLimit(e)):this.rectangles.length>2&&oi.GoldenSectionSearch(a=>this.PackLimit(a),t,s,e,n);const o=this.bestPacking.getRects();for(let a=0;a<this.rectangles.length;a++)this.rectangles[a]=o[a]}PackLimit(t){let e=this.cachedCosts.get(t);if(e==null){const i=this.createPacking(this.rectangles,t);i.run(),this.cachedCosts.set(t,e=Math.abs(i.PackedAspectRatio-this.desiredAspectRatio)),e<this.bestPackingCost&&(this.bestPackingCost=e,this.bestPacking=i)}return e}static GoldenSectionSearch(t,e,i,s,n){if(Math.abs(e-s)<n)return t(e)<t(s)?e:s;const o=oi.GetGoldenSectionStep(i,s),a=t(i),h=t(o),u=()=>oi.GoldenSectionSearch(t,o,i,e,n),d=()=>oi.GoldenSectionSearch(t,i,o,s,n);if(h<a)return d();if(h>a)return u();const m=d(),y=u();return t(y)<t(m)?y:m}static GetGoldenSectionStep(t,e){return t<e?t+Ts.GoldenRatioRemainder*(e-t):t-Ts.GoldenRatioRemainder*(t-e)}}oi.MaxSteps=1e3;class fo extends Ft{get PackedWidth(){return this.packedWidth}set PackedWidth(t){this.packedWidth=t}get PackedHeight(){return this.packedHeight}set PackedHeight(t){this.packedHeight=t}get PackedAspectRatio(){return this.PackedWidth/this.PackedHeight}getRects(){const t=[];for(const[e,i]of this.rectsToCenters)e.center=i,t.push(e);return t}}class rn extends fo{constructor(t,e,i=!1){super(null),this.rectsToCenters=new Map,this.rectanglesByDescendingHeight=i?t:rn.SortRectangles(t),this.wrapWidth=e}static SortRectangles(t){return t.sort((e,i)=>i.height-e.height),t}run(){this.Pack()}Pack(){this.PackedWidth=0,this.PackedHeight=0;const t=new Ut.B;let e=!1,i=0,s=0,n=0;const o=this.rectanglesByDescendingHeight;for(let a=0;e||a<o.length;){const h=o[a],u=t.length>0?t.top:null;if(u==null||u.right+h.width<=this.wrapWidth&&i+h.height<=u.top){const m=new c(u?u.right:0,i).add(new c(h.width/2,h.height/2));h.center=m,this.rectsToCenters.set(h,m),s=Math.max(s,h.right),n=Math.max(n,h.top),t.push(h),e=!1}else i=u.top,t.pop(),e=!0;e||a++}this.PackedWidth=s,this.PackedHeight=n}}class Er extends oi{constructor(t,e){super(rn.SortRectangles(t),e),this.createPacking=(i,s)=>new rn(i,s,!0)}run(){let t=Number.MAX_VALUE,e=0,i=0;for(const s of this.rectangles){const n=s.width;i+=n,t=Math.min(t,n),e=Math.max(e,n)}this.Pack(e,i,t)}}function xs(l){return new on($t(l.map(([t,e])=>he(e,t))))}function po(l,t){l.UserData=t.UserData,l.Left=t.Left,l.Right=t.Right,l.Count--,l.irect=t.irect}function Rn(l){for(let t=l.Parent;t!=null;t=t.Parent)t.Count--,t.irect=t.Left.irect.add_rect(t.Right.irect)}function mo(l,t){const e=new Array;for(const s of l.GetAllLeafNodes())s!==t&&e.push(s);const i=$t(e);l.Count=i.Count,l.Left=i.Left,l.Right=i.Right,l.irect=i.Left.irect.add_rect(i.Right.irect)}function Po(l){for(let t=l.Parent;t!=null;t=t.Parent)if(!br(t))return t;return null}function br(l){return 2*l.Left.Count>=l.Right.Count&&2*l.Right.Count>=l.Left.Count}function Nn(l,t,e,i){return l.irect.intersects_rect(t)?l.IsLeaf?i(l.UserData)?--e.bound!==0:!0:Nn(l.Left,t,e,i)&&Nn(l.Right,t,e,i):!0}class on{clear(){this.RootNode=null}NumberOfIntersectedIsLessThanBound(t,e,i){return Nn(this._rootNode,t,{bound:e},i)}get RootNode(){return this._rootNode}set RootNode(t){this._rootNode=t}constructor(t){this._rootNode=t}*GetAllLeaves(){if(this._rootNode!=null&&this.Count>0)for(const t of this._rootNode.GetAllLeaves())yield t}get Count(){return this._rootNode==null?0:this._rootNode.Count}Add(t,e){this.AddNode(he(e,t))}AddNode(t){this._rootNode==null?this._rootNode=t:this.Count<=2?this._rootNode=$t(Array.from(this._rootNode.GetAllLeafNodes()).concat([t])):this.AddNodeToTreeRecursive(t,this._rootNode)}Rebuild(){this._rootNode=$t(Array.from(this._rootNode.GetAllLeafNodes()))}AddNodeToTreeRecursive(t,e){if(e.IsLeaf)e.Left=he(e.UserData,e.irect),e.Right=t,e.Count=2;else{e.Count++;let i,s;if(2*e.Left.Count<e.Right.Count)this.AddNodeToTreeRecursive(t,e.Left),e.Left.irect=e.Left.irect.add_rect(t.irect);else if(2*e.Right.Count<e.Left.Count)this.AddNodeToTreeRecursive(t,e.Right),e.Right.irect=e.Right.irect.add_rect(t.irect);else{i=e.Left.irect.add_rect(t.irect);const n=i.area-e.Left.irect.area;s=e.Right.irect.add_rect(t.irect);const o=s.area-e.Right.irect.area;n<o?(this.AddNodeToTreeRecursive(t,e.Left),e.Left.irect=i):n>o?(this.AddNodeToTreeRecursive(t,e.Right),e.Right.irect=s):i.area<s.area?(this.AddNodeToTreeRecursive(t,e.Left),e.Left.irect=i):(this.AddNodeToTreeRecursive(t,e.Right),e.Right.irect=s)}}e.irect=e.Left.irect.add_rect(e.Right.irect)}GetAllIntersecting(t){return this._rootNode==null||this.Count===0?[]:Array.from(this._rootNode.GetNodeItemsIntersectingRectangle(t))}OneIntersecting(t){if(this._rootNode==null||this.Count===0)return;const e=this._rootNode.FirstIntersectedNode(t);if(e!=null)return{intersectedLeaf:e.UserData}}GetAllLeavesIntersectingRectangle(t){return this._rootNode==null||this.Count===0?[]:this._rootNode.GetLeafRectangleNodesIntersectingRectangle(t)}IsIntersecting(t){if(this._rootNode==null||this.Count===0)return!1;for(const e of this._rootNode.GetNodeItemsIntersectingRectangle(t))return!0;return!1}Contains(t,e){if(this._rootNode==null)return!1;for(const i of this._rootNode.GetLeafRectangleNodesIntersectingRectangle(t))if(i.UserData===e)return!0;return!1}Remove(t,e){if(this._rootNode==null)return;let i;for(const s of this._rootNode.GetLeafRectangleNodesIntersectingRectangle(t))s.UserData===e&&(i=s);if(i!=null)return this.RootNode.Count===1?this.RootNode=null:this.RemoveLeaf(i),i.UserData}RemoveLeaf(t){const e=Po(t);if(e!=null)mo(e,t),Rn(e);else{const i=t.Parent;i==null?this._rootNode=new On:(po(i,t.IsLeftChild?i.Right:i.Left),Rn(i))}}UnbalancedNode(t){for(let e=t.Parent;e!=null;e=e.Parent)if(!br(e))return e;return null}}class So extends X{constructor(t){super(t),this.radX=t.radX,this.radY=t.radY,this.roundedRect_=W.mkRectangleWithRoundedCorners(this.width,this.height,t.radX,t.radY,this.center)}onUpdated(){this.isEmpty||(this.roundedRect_=W.mkRectangleWithRoundedCorners(this.width,this.height,this.radX,this.radY,this.center))}isOk(){return this.isEmpty()?!0:this.roundedRect_.boundingBox.equalEps(this)}setRect(t){this.left=t.left,this.right=t.right,this.top=t.top,this.bottom=t.bottom,this.isEmpty()||(this.roundedRect_=W.mkRectangleWithRoundedCorners(t.width,t.height,this.radX,this.radY,this.center))}}function yo(l,t){const e=t.map(n=>[n,n.boundingBox]),i=e.map(n=>n[1]),s=new Er(i,1.5);s.run();for(const[n,o]of e){const a=o.leftBottom.sub(n.boundingBox.leftBottom);n.translate(a)}l.boundingBox=new X({left:0,bottom:0,right:s.PackedWidth,top:s.PackedHeight})}class Gt extends Jt{isAncestor(t){return this.graph.isAncestor(t.node)}deepTranslate(t){for(const e of this.nodesBreadthFirst){e instanceof Gt?e.boundingBox=e.boundingBox.translate(t):e.translate(t);for(const i of e.selfEdges())i.translate(t);for(const i of e.outEdges())this.graph.isAncestor(i.target.node)&&i.translate(t)}this.boundingBox=this.boundingBox.translate(t)}clone(){const t=new Gt(null);return t.boundingBox=this.boundingBox.clone(),t.layoutSettings=this.layoutSettings,t.margins=this.margins,t.radX=this.radX,t.radY=this.radY,t}calculateBoundsFromChildren(){const t=X.mkEmpty();for(const e of this.shallowNodes)t.addRecSelf(e.boundingBox);return t.padEverywhere(this.margins),t}*allSuccessorsWidthFirst(){for(const t of this.graph.allSuccessorsWidthFirst())yield Jt.getGeom(t)}static getGeom(t){return ot.getGeom(t)}edgeCurveOrArrowheadsIntersectRect(t,e){for(const n of t.sourceArrowheadPoints(25))if(e.contains(n))return!0;for(const n of t.targetArrowheadPoints(25))if(e.contains(n))return!0;const i=t.curve,s=e.perimeter();return w.intersectionOne(i,s,!1)!=null||w.PointRelativeToCurveLocation(i.start,s)===at.Inside}isEmpty(){return this.graph.isEmpty()}setSettingsRecursively(t){this.layoutSettings=t;for(const e of this.nodesBreadthFirst){const i=e;i.layoutSettings=t}}get layoutSettings(){return this._layoutSettings}set layoutSettings(t){this._layoutSettings=t}get labelSize(){return this._labelSize}set labelSize(t){this._labelSize=t}get boundingBox(){return this.rrect?this.rrect.clone():null}set boundingBox(t){t?this.rrect.setRect(t):this.rrect.roundedRect_=null}transform(t){if(!t.isIdentity()){for(const e of this.shallowNodes)e.transform(t);for(const e of this.shallowEdges)e.transform(t),e.label&&e.label.transform(t);this.boundingBox=this.rrect==null||this.rrect.isEmpty()?this.pumpTheBoxToTheGraphWithMargins():this.boundingBox.transform(t)}}translate(t){t.x===0&&t.y===0||this.deepTranslate(t)}get nodesBreadthFirst(){return this.nodesBreadthFirstIter()}*nodesBreadthFirstIter(){for(const t of this.graph.nodesBreadthFirst)yield ot.getGeom(t)}setEdge(t,e){const i=this.graph.setEdge(t,e);return new we(i)}getPumpedGraphWithMarginsBox(){const t={b:X.mkEmpty()};return Gn(this,t),t.b.padEverywhere(this.margins),t.b}pumpTheBoxToTheGraphWithMargins(){return this.boundingBox=this.getPumpedGraphWithMarginsBox()}get center(){return this.boundingBox||this.boundingBox.isEmpty?this.boundingBox.center:new c(0,0)}set center(t){const e=t.sub(this.center),i=new U(1,0,e.x,0,1,e.y);this.transform(i)}get left(){return this.boundingBox.left}get right(){return this.boundingBox.right}get top(){return this.boundingBox.top}get bottom(){return this.boundingBox.bottom}CheckClusterConsistency(){throw new Error("Method not implemented.")}get edgeCount(){return this.graph.edgeCount}get boundaryCurve(){return this.rrect.roundedRect_}set boundaryCurve(t){throw new Error}get shallowNodes(){return this.shallowNodes_()}*shallowNodes_(){for(const t of this.graph.shallowNodes)yield ot.getGeom(t)}get deepEdges(){return this.deepEdgesIt()}*deepEdgesIt(){for(const t of this.graph.deepEdges)yield ot.getGeom(t)}get shallowEdges(){return this.shallowEdgesIt()}*shallowEdgesIt(){for(const t of this.graph.shallowEdges)yield ot.getGeom(t)}static mk(t,e=new be(0,0)){const i=new Gt(new Vt(t));return i.labelSize=e,i}get Clusters(){return this.subgraphs()}*subgraphs(){for(const t of this.graph.subgraphsBreadthFirst())yield ot.getGeom(t)}static mkWithGraphAndLabel(t,e){const i=new Gt(t);return i.labelSize=e,i}constructor(t){super(t),this.margins={left:10,top:10,bottom:10,right:10},this.radX=10,this.radY=10,this.rrect=new So({left:0,right:-1,top:20,bottom:0,radX:this.radX,radY:this.radY})}get deepNodeCount(){let t=0;for(const e of this.graph.nodesBreadthFirst)t++;return t}get subgraphsDepthFirst(){return this.getSubgraphsDepthFirst()}*getSubgraphsDepthFirst(){for(const t of this.graph.allSuccessorsDepthFirst())t instanceof Vt&&(yield Gt.getGeom(t))}get uniformMargins(){return Math.max(this.margins.left,this.margins.right,this.margins.right,this.margins.bottom)}set uniformMargins(t){this.margins.left=this.margins.right=this.margins.right=this.margins.bottom=t}get height(){return this.boundingBox.height}get width(){return this.boundingBox.width}get shallowNodeCount(){return this.graph.shallowNodeCount}get graph(){return this.entity}liftNode(t){const e=this.graph.liftNode(t.node);return e?ot.getGeom(e):null}findNode(t){const e=this.graph.findNode(t);return e?ot.getGeom(e):null}addNode(t){return this.graph.addNode(t.node),t}addLabelToGraphBB(t){this.labelSize&&(t.top+=this.labelSize.height+2,t.width<this.labelSize.width&&(t.width=this.labelSize.width))}}function Gn(l,t){for(const i of l.shallowEdges){if(!e(i))continue;const s=i.curve.boundingBox;if(t.b.addRecSelf(s),i.edge.label!=null){const n=ot.getGeom(i.edge.label);n&&t.b.addRecSelf(n.boundingBox)}}for(const i of l.shallowNodes)"shallowEdges"in i&&Gn(i,t),!(i.underCollapsedGraph()||!i.boundingBox)&&t.b.addRecSelf(i.boundingBox);l instanceof Gt&&l.addLabelToGraphBB(t.b);function e(i){if(i==null||i.curve==null||i.underCollapsedGraph())return!1;if(l instanceof Gt){const s=l.entity;return s.isAncestor(i.source.entity)&&s.isAncestor(i.target.entity)}else return!0}}function*Co(l,t,e=!0){const i=l.GetAllIntersecting(t);if(e)for(const s of i)s instanceof Node&&(yield s);else for(const s of i)(s instanceof Node||s instanceof Edge)&&(yield s)}function sa(l){const t=Array.from(l.nodesBreadthFirst).concat(Array.from(l.deepEdges)).map(e=>[GeomObject.getGeom(e).boundingBox,e]);return mkRTree(t)}function*na(l,t,e){if(!l)return;const i=Rectangle.mkSizeCenter(new Size(t*2),e);for(const n of l.RootNode.AllHitItems(i,null))"edge"in n?s(e,n.pp._first,n.pp._second)<t&&(yield GeomObject.getGeom(n.edge)):yield GeomObject.getGeom(n);function s(n,o,a){const h=a.sub(o),u=h.length;if(u<1/10)return n.sub(Point.middle(o,a)).length;const d=h.rotate90Cw();return Math.abs(n.sub(o).dot(d))/u}}function ra(l,t){if(l==null)return null;const e=Array.from(l.nodesBreadthFirst).map(n=>[GeomNode.getGeom(n).boundingBox,n]),i=[];for(const n of l.deepEdges){const o=n.getAttr(AttributeRegistry.GeomObjectIndex);if(!o||(o.label&&i.push([o.label.boundingBox,n.label]),!o.curve))continue;const a=interpolateICurve(o.curve,t/2);o.sourceArrowhead&&i.push([Rectangle.mkPP(o.sourceArrowhead.tipPosition,o.curve.start),{edge:n,pp:new PointPair(o.sourceArrowhead.tipPosition,o.curve.start)}]);for(let h=0;h<a.length-1;h++)i.push([Rectangle.mkPP(a[h],a[h+1]),{edge:n,pp:new PointPair(a[h],a[h+1])}]);o.targetArrowhead&&i.push([Rectangle.mkPP(o.curve.end,o.targetArrowhead.tipPosition),{edge:n,pp:new PointPair(o.curve.end,o.targetArrowhead.tipPosition)}])}const s=e.concat(i);return mkRTree(s)}class oa{get curveClips(){return this._curveClips}set curveClips(t){this._curveClips=t}constructor(t){this._curveClips=[],this.arrowheads=[],this.nodes=[],this.labels=[],this.rect=t,this._curveClips=[]}addCurveClip(t){Assert.assert(!(t.curve instanceof Curve),"CurveClip.curve should not be a Curve!"),this._curveClips.push(t)}isEmpty(){return this._curveClips.length==0&&this.arrowheads.length==0&&this.nodes.length==0&&this.labels.length==0}initCurveClips(){this._curveClips=[]}clear(){this.arrowheads=[],this.nodes=[],this.labels=[],this._curveClips=[]}get entityCount(){return this._curveClips.length+this.arrowheads.length+this.labels.length+this.nodes.length}addElement(t){if(t instanceof GeomNode)this.nodes.push(t);else if(t instanceof GeomLabel)this.labels.push(t);else if("curve"in t)if(t.curve instanceof Curve)for(const e of t.curve.segs)this.addCurveClip({edge:t.edge,curve:e,startPar:e.parStart,endPar:e.parEnd});else this.addCurveClip(t);else this.arrowheads.push(t)}}class _i{get Parents(){return Array.from(this.parents.values())}get Children(){return Array.from(this.children.values())}get BoundaryCurve(){return this.boundaryCurve}set BoundaryCurve(t){this.boundaryCurve=t}get BoundingBox(){return this.BoundaryCurve.boundingBox}get Ports(){return this.ports}static mkShape(){return new _i(null)}constructor(t=null){this.parents=new Set,this.children=new Set,this.ports=new Set,this.BoundaryCurve=t}get IsGroup(){return this.children.size>0}*Descendants(){const t=new Ge.o;for(const e of this.Children)t.enqueue(e);for(;t.length>0;){const e=t.dequeue();yield e;for(const i of e.Children)t.enqueue(i)}}*Ancestors(){const t=new Ge.o;for(const e of this.Parents)t.enqueue(e);for(;t.length>0;){const e=t.dequeue();yield e;for(const i of e.Parents)t.enqueue(i)}}AddParent(t){this.parents.add(t),t.children.add(this)}AddChild(t){t.parents.add(this),this.children.add(t)}RemoveChild(t){this.children.delete(t),t.parents.delete(this)}RemoveParent(t){this.parents.delete(t),t.children.delete(this)}ToString(){return this.UserData?this.UserData.toString():"null"}}class an{}class Ue extends an{constructor(t,e){super(),this.curve=this.curve,this.location=e.clone()}get Location(){return this.location}set Location(t){this.location=t}Translate(t){this.location=this.location.add(t)}get Curve(){return this.curve}set Curve(t){this.curve=t}}class ke extends Ue{static mk(t,e){return new ke(t,e,new c(0,0))}get CenterDelegate(){return this.centerDelegate}set CenterDelegate(t){this.centerDelegate=t}get CurveDelegate(){return this.curveDelegate}set CurveDelegate(t){this.curveDelegate=t}get LocationOffset(){return this.locationOffset}set LocationOffset(t){this.locationOffset=t}constructor(t,e,i){super(null,e().add(i)),this.LocationOffset=i,this.CurveDelegate=t,this.CenterDelegate=e}get Location(){return this.CenterDelegate().add(this.LocationOffset)}get Curve(){return this.CurveDelegate()}}class Os{constructor(t,e,i,s,n){this.color=t,e!==void 0&&(this.item=e),i!==void 0&&(this.parent=i),s!==void 0&&(this.left=s),n!==void 0&&(this.right=n)}toString(){return this.item.toString()}}var ft;(function(l){l[l.Red=0]="Red",l[l.Black=1]="Black"})(ft||(ft={}));class Me{[Symbol.iterator](){return this.allNodes()}constructor(t){this.comparer=t,this.count=0,this.root=this.nil=new Os(ft.Black)}clear(){this.root=this.nil=new Os(ft.Black)}toNull(t){return t!==this.nil?t:null}isEmpty(){return this.root===this.nil}getComparer(){return this.comparer}getRoot(){return this.root}find(t,e=this.root){let i;for(;e!==this.nil&&(i=this.comparer(t,e.item))!==0;)e=i<0?e.left:e.right;return this.toNull(e)}findFirst(t,e=this.root){if(e===this.nil)return null;let i=null;for(;e!==this.nil;)e=t(e.item)?(i=e).left:e.right;return i}findLast(t,e=this.root){if(e===this.nil)return null;let i=null;for(;e!==this.nil;)e=t(e.item)?(i=e).right:e.left;return i}treeMinimum(t=this.root){for(;t.left!==this.nil;)t=t.left;return this.toNull(t)}treeMaximum(t=this.root){for(;t.right!==this.nil;)t=t.right;return this.toNull(t)}next(t){if(t.right!==this.nil)return this.treeMinimum(t.right);let e=t.parent;for(;e!==this.nil&&t===e.right;)t=e,e=e.parent;return this.toNull(e)}previous(t){if(t.left!==this.nil)return this.treeMaximum(t.left);let e=t.parent;for(;e!==this.nil&&t===e.left;)t=e,e=e.parent;return this.toNull(e)}leftRotate(t){const e=t.right;t.right=e.left,e.left!==this.nil&&(e.left.parent=t),e.parent=t.parent,t.parent===this.nil?this.root=e:t===t.parent.left?t.parent.left=e:t.parent.right=e,e.left=t,t.parent=e}rightRotate(t){const e=t.left;t.left=e.right,e.right!==this.nil&&(e.right.parent=t),e.parent=t.parent,t.parent===this.nil?this.root=e:t===t.parent.right?t.parent.right=e:t.parent.left=e,e.right=t,t.parent=e}deleteFixup(t){for(;t!==this.root&&t.color===ft.Black;)if(t===t.parent.left){let e=t.parent.right;e.color===ft.Red&&(e.color=ft.Black,t.parent.color=ft.Red,this.leftRotate(t.parent),e=t.parent.right),e.left.color===ft.Black&&e.right.color===ft.Black?(e.color=ft.Red,t=t.parent):(e.right.color===ft.Black&&(e.left.color=ft.Black,e.color=ft.Red,this.rightRotate(e),e=t.parent.right),e.color=t.parent.color,t.parent.color=ft.Black,e.right.color=ft.Black,this.leftRotate(t.parent),t=this.root)}else{let e=t.parent.left;e.color===ft.Red&&(e.color=ft.Black,t.parent.color=ft.Red,this.rightRotate(t.parent),e=t.parent.left),e.right.color===ft.Black&&e.left.color===ft.Black?(e.color=ft.Red,t=t.parent):(e.left.color===ft.Black&&(e.right.color=ft.Black,e.color=ft.Red,this.leftRotate(e),e=t.parent.left),e.color=t.parent.color,t.parent.color=ft.Black,e.left.color=ft.Black,this.rightRotate(t.parent),t=this.root)}t.color=ft.Black}deleteSubTree(t){let e;if(t.left===this.nil||t.right===this.nil)e=t;else for(e=t.right;e.left!==this.nil;)e=e.left;const i=e.left!==this.nil?e.left:e.right;return i.parent=e.parent,e.parent===this.nil?this.root=i:e===e.parent.left?e.parent.left=i:e.parent.right=i,e!==t&&(t.item=e.item),e.color===ft.Black&&this.deleteFixup(i),this.toNull(t)}deleteNodeInternal(t){this.count--,this.deleteSubTree(t)}remove(t){const e=this.find(t);return e!=null?(this.count--,this.deleteSubTree(e)):null}insert(t){const e=this.treeInsert(t);return this.insertPrivate(e),this.toNull(e)}treeInsert(t){let e=this.nil,i=this.root,s=0;for(;i!==this.nil;)e=i,s=this.comparer(t,i.item),i=s<0?i.left:i.right;const n=new Os(ft.Black,t,e,this.nil,this.nil);return e===this.nil?this.root=n:s<0?e.left=n:e.right=n,this.toNull(n)}insertPrivate(t){for(this.count++,t.color=ft.Red;t!==this.root&&t.parent.color===ft.Red;)if(t.parent===t.parent.parent.left){const e=t.parent.parent.right;e.color===ft.Red?(t.parent.color=ft.Black,e.color=ft.Black,t.parent.parent.color=ft.Red,t=t.parent.parent):(t===t.parent.right&&(t=t.parent,this.leftRotate(t)),t.parent.color=ft.Black,t.parent.parent.color=ft.Red,this.rightRotate(t.parent.parent))}else{const e=t.parent.parent.left;e.color===ft.Red?(t.parent.color=ft.Black,e.color=ft.Black,t.parent.parent.color=ft.Red,t=t.parent.parent):(t===t.parent.left&&(t=t.parent,this.rightRotate(t)),t.parent.color=ft.Black,t.parent.parent.color=ft.Red,this.leftRotate(t.parent.parent))}this.root.color=ft.Black}*allNodes(){if(this.isEmpty())return;let t=this.treeMinimum();for(;t!=null;)yield t.item,t=this.next(t)}toString(){let t="{",e=0;for(const i of this.allNodes())t+=i.toString(),e!==this.count-1&&(t+=` `),e++;return t+"}"}}class kn{*[Symbol.iterator](){for(let t=1;t<=this.heapSize;t++)yield this.A[t]}Enqueue(t){let e=this.heapSize+1;this.A[e]=t,this.heapSize++;let i=e>>1,s,n;for(;e>1&&this.Less(s=this.A[e],n=this.A[i]);)this.A[i]=s,this.A[e]=n,e=i,i=e>>1}Dequeue(){if(this.heapSize<1)throw new Error;const t=this.A[1],e=this.A[this.heapSize];return this.heapSize--,this.ChangeMinimum(e),t}ChangeMinimum(t){this.A[1]=t;let e=1,i=2,s=!1;for(;i<this.heapSize&&!s;){s=!0;const n=this.A[i],o=this.A[i+1];this.compare(n,o)<0?this.compare(n,t)<0&&(this.A[e]=n,this.A[i]=t,s=!1,e=i,i=e<<1):this.compare(o,t)<0&&(this.A[e]=o,this.A[i+1]=t,s=!1,e=i+1,i=e<<1)}if(i===this.heapSize){const n=this.A[i];this.compare(n,t)<0&&(this.A[e]=n,this.A[i]=t)}}get Count(){return this.heapSize}Less(t,e){return this.compare(t,e)<0}constructor(t){this.heapSize=0,this.A=[],this.compare=t}GetMinimum(){return this.A[1]}}class ai{}class ts extends ai{get Site(){return this.Vertex.point}constructor(t){super(),this.Vertex=t}get Polyline(){return this.Vertex.polyline}}class es extends ts{constructor(t){super(t)}}class is{constructor(t){this.lineSweeper=t}Compare(t,e){switch(c.getTriangleOrientation(e.Start,e.End,this.x)){case D.Collinear:return 0;case D.Clockwise:return 1;default:return-1}}SetOperand(t){this.x=this.IntersectionOfSideAndSweepLine(t)}IntersectionOfSideAndSweepLine(t){const e=t.Direction.dot(this.lineSweeper.SweepDirection),i=(this.lineSweeper.Z-t.Start.dot(this.lineSweeper.SweepDirection))/e;return t.Start.add(t.Direction.mul(i))}}class wr extends ai{constructor(t){super(),this.site=t}get Site(){return this.site}}class vr{constructor(t,e){this.PreviousZ=Number.NEGATIVE_INFINITY,this.z=Number.NEGATIVE_INFINITY,this.Obstacles=t??[],this.SweepDirection=e,this.DirectionPerp=e.rotate(-Math.PI/2),this.EventQueue=new kn((i,s)=>this.Compare(i,s)),this.ObstacleSideComparer=new is(this),this.LeftObstacleSideTree=new Me((i,s)=>this.ObstacleSideComparer.Compare(i,s)),this.RightObstacleSideTree=new Me((i,s)=>this.ObstacleSideComparer.Compare(i,s))}get EventQueue(){return this.eventQueue}set EventQueue(t){this.eventQueue=t}get DirectionPerp(){return this.directionPerp}set DirectionPerp(t){this.directionPerp=t}get Z(){return this.z}set Z(t){t>this.z+C.tolerance&&(this.PreviousZ=this.z),this.z=t}GetZS(t){return this.SweepDirection.dot(t.Site)}GetZP(t){return this.SweepDirection.dot(t)}SegmentIsNotHorizontal(t,e){return Math.abs(t.sub(e).dot(this.SweepDirection))>C.distanceEpsilon}RemoveLeftSide(t){this.ObstacleSideComparer.SetOperand(t),this.LeftObstacleSideTree.remove(t)}RemoveRightSide(t){this.ObstacleSideComparer.SetOperand(t),this.RightObstacleSideTree.remove(t)}InsertLeftSide(t){this.ObstacleSideComparer.SetOperand(t),this.LeftObstacleSideTree.insert(t)}InsertRightSide(t){this.ObstacleSideComparer.SetOperand(t),this.RightObstacleSideTree.insert(t)}FindFirstObstacleSideToTheLeftOfPoint(t){const e=this.RightObstacleSideTree.findLast(i=>c.pointToTheRightOfLineOrOnLine(t,i.Start,i.End));return e==null?null:e.item}FindFirstObstacleSideToToTheRightOfPoint(t){const e=this.LeftObstacleSideTree.findFirst(i=>!c.pointToTheRightOfLineOrOnLine(t,i.Start,i.End));return e==null?null:e.item}EnqueueEvent(t){this.eventQueue.Enqueue(t)}InitQueueOfEvents(){for(const t of this.Obstacles)this.EnqueueLowestPointsOnObstacles(t);if(this.Ports!=null)for(const t of this.Ports.values())this.EnqueueEvent(new wr(t))}EnqueueLowestPointsOnObstacles(t){const e=this.GetLowestPoint(t);this.EnqueueEvent(new es(e))}GetLowestPoint(t){let e=t.startPoint,i=t.startPoint.next;for(;i!=null;i=i.next)this.Less(i.point,e.point)&&(e=i);return e}Compare(t,e){const i=t.Site,s=e.Site;return this.ComparePoints(i,s)}Less(t,e){return this.ComparePoints(t,e)<0}ComparePoints(t,e){let i=this.SweepDirection.dot(t),s=this.SweepDirection.dot(e);return i<s?-1:i>s?1:(i=this.directionPerp.dot(t),s=this.directionPerp.dot(e),i<s?-1:i>s?1:0)}}var ue=Ys(38846);class ve{static closeuv(t,e){return c.closeDistEps(t.point,ve.u,.1)&&c.closeDistEps(e.point,ve.v,.1)}constructor(t,e,i=1){this.LengthMultiplier=1,this.Source=t,this.Target=e,this.Weight=i}get SourcePoint(){return this.Source.point}get TargetPoint(){return this.Target.point}get Length(){return this.SourcePoint.sub(this.TargetPoint).length*this.LengthMultiplier}toString(){return ue.Qf.format("{0}->{1} ({2})",this.Source,this.Target,this.Weight)}ReversedClone(){return new ve(this.Target,this.Source)}Clone(){return new ve(this.Source,this.Target)}}ve.u=new c(545.833,840.458),ve.v=new c(606.1667261889578,786.2917261889578),ve.DefaultWeight=1;class li extends ve{static constructorVV(t,e){return new li(t,e,0)}constructor(t,e,i=0){super(t,e,i)}}class je{deleteP(t){return this.delete(t.x,t.y)}clear(){this.m.clear()}get size(){return this.m.size}setxy(t,e,i){this.m.set(Bs(t,e),i)}set(t,e){this.setxy(t.x,t.y,e)}delete(t,e){return this.m.delete(Bs(t,e))}hasxy(t,e){return this.m.has(Bs(t,e))}has(t){return this.hasxy(t.x,t.y)}getxy(t,e){return this.m.get(Bs(t,e))}get(t){return this.getxy(t.x,t.y)}constructor(){this.m=new Map}*keys(){for(const t of this.m.keys()){const e=t.split(",");yield new c(Number(e[0]),Number(e[1]))}}*[Symbol.iterator](){for(const[t,e]of this.m){const i=t.split(",");yield[new c(Number(i[0]),Number(i[1])),e]}}*values(){yield*this.m.values()}}function Bs(l,t){return l.toString()+","+t.toString()}class ki{get InEdges(){return this._inEdges}get OutEdges(){return this._outEdges}get Degree(){return this._inEdges.length+this.OutEdges.count}InEdgesLength(){return this._inEdges.length}addInEdge(t){this._inEdges.push(t)}get IsTerminal(){return this._isTerminal}set IsTerminal(t){this._isTerminal=t}get IsShortestPathTerminal(){return this._isShortestPathTerminal}set IsShortestPathTerminal(t){this._isShortestPathTerminal=t}constructor(t){this._inEdges=new Array,this._outEdges=new Me((e,i)=>this.Compare(e,i)),this.point=t}toString(){return this.point.toString()}RemoveOutEdge(t){this.OutEdges.remove(t)}RemoveInEdge(t){const e=this._inEdges.indexOf(t);if(e===-1)return;const i=this._inEdges.length-1;e!==i&&(this._inEdges[e]=this._inEdges[i]),this._inEdges.pop()}static FindFirst(t,e){return ki.FindFirst_t(t.root,t,e)}static FindFirst_t(t,e,i){if(t===e.nil)return null;let s=null;for(;t!==e.nil;)t=t.item.TargetPoint.compareTo(i)>=0?(s=t).left:t.right;return s}get(t){let e=ki.FindFirst(this.OutEdges,t.point);return e!=null&&e.item.Target===t||(e=ki.FindFirst(t.OutEdges,this.point),e!=null&&e.item.Target===this)?e.item:null}Compare(t,e){return t.TargetPoint.compareTo(e.TargetPoint)}ClearEdges(){this._outEdges.clear(),this._inEdges=[]}}class Xt{constructor(){this.activeVertices=new Set,this.VertexFactory=t=>new ki(t),this.pointToVertexMap=new je}*edges_(){for(const t of this.pointToVertexMap.values())for(const e of t.OutEdges)yield e}get Edges(){return this.edges_()}ClearPrevEdgesTable(){for(const t of this.activeVertices)t.prevEdge=null;this.activeVertices.clear()}ShrinkLengthOfPrevEdge(t,e){t.prevEdge.LengthMultiplier=e}PreviosVertex(t){const e=t.prevEdge;return e?e.Source===t?e.Target:e.Source:null}SetPreviousEdge(t,e){this.activeVertices.add(t),t.prevEdge=e}AddHole(t){let e=t.startPoint;for(;e!==t.endPoint;)this.AddEdgePlPl(e,e.next),e=e.next;this.AddEdgePlPl(t.endPoint,t.startPoint)}static*OrientHolesClockwise(t){for(const e of t)for(let i=e.startPoint;;i=i.next){const s=c.getTriangleOrientation(i.point,i.next.point,i.next.next.point);if(s!==D.Collinear){yield s===D.Clockwise?e:e.reverse();break}}}AddVertexP(t){const e=this.pointToVertexMap.get(t);if(e)return e;const i=this.VertexFactory(t);return this.pointToVertexMap.set(t,i),i}AddVertexV(t){this.pointToVertexMap.set(t.point,t)}ContainsVertex(t){return this.pointToVertexMap.has(t)}static AddEdgeVV(t,e){let i;if(i=t.get(e))return i;if(t===e)throw new Error("Self-edges are not allowed");const s=new ve(t,e);return t.OutEdges.insert(s),e.InEdges.push(s),s}AddEdgePlPl(t,e){this.AddEdgePP(t.point,e.point)}static AddEdge(t){t.Source.OutEdges.insert(t),t.Target.addInEdge(t)}AddEdgeF(t,e,i){let s=this.FindVertex(t),n=null;if(s!=null&&(n=this.FindVertex(e),n!=null)){const a=s.get(n);if(a)return a}s==null?(s=this.AddVertexP(t),n=this.AddVertexP(e)):n==null&&(n=this.AddVertexP(e));const o=i(s,n);return s.OutEdges.insert(o),n.addInEdge(o),o}AddEdgePP(t,e){return this.AddEdgeF(t,e,(i,s)=>new ve(i,s))}FindVertex(t){return this.pointToVertexMap.get(t)}Vertices(){return this.pointToVertexMap.values()}RemoveVertex(t){for(const e of t.OutEdges)e.Target.RemoveInEdge(e);for(const e of t.InEdges)e.Source.RemoveOutEdge(e);this.pointToVertexMap.deleteP(t.point)}FindEdgePP(t,e){const i=this.FindVertex(t);if(i==null)return null;const s=this.FindVertex(e);return s==null?null:i.get(s)}static RemoveEdge(t){t.Source.RemoveOutEdge(t),t.Target.RemoveInEdge(t)}ClearEdges(){for(const t of this.Vertices())t.ClearEdges()}}class Mn{constructor(){this.Removed=!1}}class ss extends Mn{get Start(){return this.start}get End(){return this.EndVertex.point}constructor(t,e,i){super(),this.start=t,this.EndVertex=e,this.ConeSide=i}get Direction(){return this.End.sub(this.Start)}toString(){return"BrokenConeSide: "+(this.Start+(","+this.End))}}class Vn{get Removed(){return this.removed}set Removed(t){this.removed=t}constructor(t,e){this.apex=t,this.coneSweeper=e}get Apex(){return this.apex}set Apex(t){this.apex=t}get RightSideDirection(){return this.coneSweeper.ConeRightSideDirection}get LeftSideDirection(){return this.coneSweeper.ConeLeftSideDirection}get RightSide(){return this.rightSide}set RightSide(t){this.rightSide=t,this.rightSide.Cone=this}get LeftSide(){return this.leftSide}set LeftSide(t){this.leftSide=t,this.leftSide.Cone=this}}class Ir extends ai{get ConeToClose(){return this.coneToClose}get Site(){return this.site}constructor(t,e){super(),this.site=t,this.coneToClose=e}toString(){return"ConeClosureEvent "+this.site}}class hi extends Mn{constructor(t){super(),this.Cone=t}get Start(){return this.Cone.Apex}get Direction(){return this.Cone.LeftSideDirection}toString(){return"ConeLeftSide "+this.Start+(" "+this.Direction)}}class Fi extends Mn{constructor(t){super(),this.Cone=t}get Start(){return this.Cone.Apex}get Direction(){return this.Cone.RightSideDirection}toString(){return"ConeRightSide "+this.Start+" "+this.Direction}}class ln{SetOperand(t){this.x=this.IntersectionOfSegmentAndSweepLine(t)}constructor(t){this.coneSweeper=t}Compare(t,e){const i=t instanceof ss,s=e instanceof ss;return i?s?this.CompareBrokenSides(t,e):this.CompareObstacleSideAndConeSide(e):s?this.CompareConeSideAndObstacleSide(t,e):ln.CompareNotIntersectingSegs(t,e)}static CompareNotIntersectingSegs(t,e){switch(c.getTriangleOrientation(t.Start,e.Start,e.Start.add(e.Direction))){case D.Counterclockwise:return-1;case D.Clockwise:return 1;default:return 0}}CompareObstacleSideAndConeSide(t){const e=c.getTriangleOrientation(this.x,t.Start,t.Start.add(t.Direction));return e===D.Counterclockwise?-1:e===D.Clockwise?1:t instanceof hi?-1:1}CompareConeSideAndObstacleSide(t,e){const i=c.getTriangleOrientation(this.x,e.start,e.End);return i===D.Counterclockwise?-1:i===D.Clockwise||t instanceof hi?1:-1}IntersectionOfSegmentAndSweepLine(t){const e=t.Direction.dot(this.coneSweeper.SweepDirection),i=(this.coneSweeper.Z-t.Start.dot(this.coneSweeper.SweepDirection))/e;return t.Start.add(t.Direction.mul(i))}CompareBrokenSides(t,e){return t.EndVertex===e.EndVertex?ln.CompareNotIntersectingSegs(t.ConeSide,e.ConeSide):c.getTriangleOrientation(this.x,e.start,e.EndVertex.point)===D.Counterclockwise?-1:1}}class Ls extends ai{get EndVertex(){return this.endVertex}constructor(t,e,i){super(),this.coneLeftSide=t,this.intersectionPoint=e,this.endVertex=i}get Site(){return this.intersectionPoint}toString(){return"LeftIntersectionEvent "+this.intersectionPoint}}class Wn{get Direction(){return this.End.sub(this.Start)}toString(){return this.Start+" "+this.End}}class Hn extends Wn{Init(t){this.StartVertex=t}constructor(t){super(),this.Init(t)}get Polyline(){return this.StartVertex.polyline}get Start(){return this.StartVertex.point}get End(){return this.EndVertex.point}}class ns extends Hn{constructor(t){super(t),this.end=t.nextOnPolyline.point}get End(){return this.end}get EndVertex(){return this.StartVertex.nextOnPolyline}}class Mi extends ts{constructor(t){super(t)}}class Tr extends ai{get EndVertex(){return this.endVertex}set EndVertex(t){this.endVertex=t}constructor(t,e,i){super(),this.coneRightSide=t,this.intersectionPoint=e,this.endVertex=i}get Site(){return this.intersectionPoint}toString(){return"RightIntersectionEvent "+this.intersectionPoint}}class rs extends Hn{constructor(t){super(t),this.end=t.prevOnPolyline.point}get End(){return this.end}get EndVertex(){return this.StartVertex.prevOnPolyline}}class P extends ts{constructor(t){super(t)}}class rt extends vr{constructor(t,e,i,s,n,o,a){super(t,e),this.visibilityGraph=n,this.ConeRightSideDirection=i,this.ConeLeftSideDirection=s,this.coneSideComparer=new ln(this),this.leftConeSides=new Me((h,u)=>this.coneSideComparer.Compare(h,u)),this.rightConeSides=new Me((h,u)=>this.coneSideComparer.Compare(h,u)),this.Ports=o,this.BorderPolyline=a,this.PortEdgesCreator=(h,u)=>new li(h,u,0)}static Sweep(t,e,i,s,n,o){new rt(t,e,e.rotate(-i/2),e.rotate(i/2),s,n,o).Calculate()}Calculate(){for(this.InitQueueOfEvents();this.EventQueue.Count>0;)this.ProcessEvent(this.EventQueue.Dequeue());this.BorderPolyline!=null&&this.CloseRemainingCones(),this.CreatePortEdges()}CreatePortEdges(){if(this.portEdgesGraph!=null)for(const t of this.portEdgesGraph.Edges)this.visibilityGraph.AddEdgeF(t.SourcePoint,t.TargetPoint,this.PortEdgesCreator)}CloseRemainingCones(){if(this.leftConeSides.count===0)return;let t=this.BorderPolyline.startPoint,e=this.leftConeSides.count;do{const i=this.leftConeSides.treeMinimum().item.Cone;t=this.FindPolylineSideIntersectingConeRightSide(t,i),t=this.GetPolylinePointInsideOfConeAndRemoveCones(t,i),e--}while(this.leftConeSides.count>0&&e>0)}GetPolylinePointInsideOfConeAndRemoveCones(t,e){const i=t.nextOnPolyline,s=rt.FindInsidePoint(t.point,i.point,e);return c.closeDistEps(s,t.point)?(this.AddEdgeAndRemoveCone(e,t.point),this.AddEdgesAndRemoveRemainingConesByPoint(t.point)):c.closeDistEps(s,i.point)?(this.AddEdgeAndRemoveCone(e,i.point),this.AddEdgesAndRemoveRemainingConesByPoint(i.point),t=i):(t=rt.InsertPointIntoPolylineAfter(this.BorderPolyline,t,s),this.AddEdgeAndRemoveCone(e,t.point),this.AddEdgesAndRemoveRemainingConesByPoint(t.point)),t}static FindInsidePoint(t,e,i){return rt.FindInsidePointBool(t,e,i.Apex,i.Apex.add(i.LeftSideDirection),i.Apex.add(i.RightSideDirection))}static FindInsidePointBool(t,e,i,s,n){if(c.closeDistEps(t,e)||c.PointIsInsideCone(t,i,s,n))return t;if(c.PointIsInsideCone(e,i,s,n))return e;const o=c.middle(t,e);return c.pointToTheLeftOfLine(o,i,s)?rt.FindInsidePointBool(o,e,i,s,n):rt.FindInsidePointBool(t,o,i,s,n)}AddEdgesAndRemoveRemainingConesByPoint(t){const e=new Array;for(const i of this.leftConeSides)if(c.PointToTheRightOfLineOrOnLine(t,i.Start,i.Start.add(i.Direction)))e.push(i.Cone);else break;for(const i of e)this.AddEdgeAndRemoveCone(i,t)}FindPolylineSideIntersectingConeRightSide(t,e){const i=t,s=e.Apex,n=e.Apex.add(this.ConeRightSideDirection);let o=rt.GetSign(t,s,n);for(;;){const a=t.nextOnPolyline,h=rt.GetSign(a,s,n);if(h-o>0)return t;if(t=a,o=h,t===i)throw new Error("cannod decide if the polyline intersects the cone!")}}static GetSign(t,e,i){const s=c.signedDoubledTriangleArea(e,i,t.point);return s<0?1:s>0?-1:0}AddEdgeAndRemoveCone(t,e){this.Ports!=null&&this.Ports.has(t.Apex)?this.CreatePortEdge(t,e):this.visibilityGraph.AddEdgePP(t.Apex,e),this.RemoveCone(t)}CreatePortEdge(t,e){this.portEdgesGraph==null&&(this.portEdgesGraph=new Xt);const i=this.portEdgesGraph.FindVertex(t.Apex),s=i!=null?Array.from(i.InEdges).concat(Array.from(i.OutEdges.allNodes())):null;if(s)for(const n of s){const o=(n.Target===i?n.Source:n.Target).point;Xt.RemoveEdge(n),this.portEdgesGraph.AddEdgePP(o,e)}this.portEdgesGraph.AddEdgePP(t.Apex,e)}static InsertPointIntoPolylineAfter(t,e,i){let s;return e.next!=null?(s=zt.mkFromPoint(i),s.prev=e,s.next=e.next,e.next.prev=s,e.next=s):(s=zt.mkFromPoint(i),s.prev=e,e.next=s,t.endPoint=s),s.polyline=t,t.setInitIsRequired(),s}ProcessEvent(t){t instanceof ts?this.ProcessVertexEvent(t):t instanceof Tr?this.ProcessRightIntersectionEvent(t):t instanceof Ls?this.ProcessLeftIntersectionEvent(t):(t instanceof Ir?t.ConeToClose.Removed||this.RemoveCone(t.ConeToClose):this.ProcessPortObstacleEvent(t),this.Z=this.GetZS(t))}ProcessPortObstacleEvent(t){this.Z=this.GetZS(t),this.GoOverConesSeeingVertexEvent(t),this.CreateConeOnVertex(t)}ProcessLeftIntersectionEvent(t){if(t.coneLeftSide.Removed===!1)if(Math.abs(t.EndVertex.point.sub(t.Site).dot(this.SweepDirection))<C.distanceEpsilon)this.RemoveCone(t.coneLeftSide.Cone);else{this.RemoveSegFromLeftTree(t.coneLeftSide),this.Z=this.GetZP(t.Site);const e=new ss(t.Site,t.EndVertex,t.coneLeftSide);this.InsertToTree(this.leftConeSides,e),t.coneLeftSide.Cone.LeftSide=e,this.LookForIntersectionOfObstacleSideAndLeftConeSide(t.Site,t.EndVertex),this.TryCreateConeClosureForLeftSide(e)}else this.Z=this.GetZP(t.Site)}TryCreateConeClosureForLeftSide(t){if(t.Cone.RightSide instanceof Fi){const e=t.Cone.RightSide;c.getTriangleOrientation(e.Start,e.Start.add(e.Direction),t.EndVertex.point)==D.Clockwise&&this.CreateConeClosureEvent(t,e)}}CreateConeClosureEvent(t,e){const i=c.RayIntersectsRayInteriors(t.start,t.Direction,e.Start,e.Direction);if(i){const s=new Ir(i,t.Cone);this.EnqueueEvent(s)}}ProcessRightIntersectionEvent(t){if(t.coneRightSide.Removed)this.Z=this.GetZP(t.Site);else{this.RemoveSegFromRightTree(t.coneRightSide),this.Z=this.GetZP(t.Site);const e=new ss(t.Site,t.EndVertex,t.coneRightSide);this.InsertToTree(this.rightConeSides,e),t.coneRightSide.Cone.RightSide=e,this.LookForIntersectionOfObstacleSideAndRightConeSide(t.Site,t.EndVertex),this.TryCreateConeClosureForRightSide(e)}}TryCreateConeClosureForRightSide(t){if(t.Cone.LeftSide instanceof hi){const e=t.Cone.LeftSide;c.getTriangleOrientation(e.Start,e.Start.add(e.Direction),t.EndVertex.point)==D.Counterclockwise&&this.CreateConeClosureEvent(t,e)}}RemoveConesClosedBySegment(t,e){this.CloseConesCoveredBySegment(t,e,this.GetZP(t)>this.GetZP(e)?this.leftConeSides:this.rightConeSides)}CloseConesCoveredBySegment(t,e,i){let s=i.findFirst(a=>c.getTriangleOrientation(a.Start,a.Start.add(a.Direction),t)===D.Counterclockwise);if(s==null||!c.IntervalIntersectsRay(t,e,s.item.Start,s.item.Direction))return;const o=new Array;do o.push(s.item.Cone),s=i.next(s);while(s!=null&&c.IntervalIntersectsRay(t,e,s.item.Start,s.item.Direction)!==void 0);for(const a of o)this.RemoveCone(a)}ProcessVertexEvent(t){this.Z=this.GetZS(t),this.GoOverConesSeeingVertexEvent(t),this.AddConeAndEnqueueEvents(t)}static Diamond(t){return W.mkDiamond(2,2,t)}AddConeAndEnqueueEvents(t){if(t instanceof Mi){const e=t.Vertex.nextOnPolyline;this.CloseConesAddConeAtLeftVertex(t,e)}else if(t instanceof P){const e=t.Vertex.prevOnPolyline;this.CloseConesAddConeAtRightVertex(t,e)}else this.CloseConesAddConeAtLeftVertex(t,t.Vertex.nextOnPolyline),this.CloseConesAddConeAtRightVertex(t,t.Vertex.prevOnPolyline)}CloseConesAddConeAtRightVertex(t,e){const i=t.Vertex.nextOnPolyline.point;this.directionPerp.dot(t.Site.sub(i))>C.distanceEpsilon&&this.RemoveConesClosedBySegment(i,t.Vertex.point),this.directionPerp.dot(e.point.sub(t.Site))>C.distanceEpsilon&&this.RemoveConesClosedBySegment(t.Site,e.point);const s=t.Site,n=s.add(this.ConeLeftSideDirection),o=s.add(this.ConeRightSideDirection),a=e.point;this.GetZP(s.sub(i))>C.distanceEpsilon&&this.RemoveRightSide(new rs(t.Vertex.nextOnPolyline)),this.GetZP(s.sub(e.point))>C.distanceEpsilon&&this.RemoveLeftSide(new ns(e)),this.GetZP(a)+C.distanceEpsilon<this.GetZS(t)&&this.CreateConeOnVertex(t),c.PointToTheRightOfLineOrOnLine(a,s,n)?c.PointToTheLeftOfLineOrOnLine(a,s,o)?this.CaseToTheLeftOfLineOrOnLineConeRp(t,e):(this.GetZP(a.sub(s))>C.distanceEpsilon&&(this.LookForIntersectionOfObstacleSideAndLeftConeSide(t.Site,e),this.InsertRightSide(new rs(t.Vertex))),this.EnqueueRightVertexEvent(new P(e))):(this.CreateConeOnVertex(t),c.PointToTheLeftOfLineOrOnLine(a.add(this.DirectionPerp),a,s)&&this.EnqueueRightVertexEvent(new P(e)))}CaseToTheLeftOfLineOrOnLineConeRp(t,e){this.EnqueueRightVertexEvent(new P(e));const i=new Vn(t.Vertex.point,this),s=new ss(i.Apex,e,new hi(i));i.LeftSide=s,i.RightSide=new Fi(i);const n=this.InsertToTree(this.rightConeSides,i.RightSide);this.LookForIntersectionWithConeRightSide(n);const o=this.InsertToTree(this.leftConeSides,i.LeftSide);this.FixConeLeftSideIntersections(s,o),this.GetZP(e.point.sub(t.Site))>C.distanceEpsilon&&this.InsertRightSide(new rs(t.Vertex))}LookForIntersectionOfObstacleSideAndRightConeSide(t,e){const i=this.GetLastNodeToTheLeftOfPointInRightSegmentTree(t);if(i!=null&&i.item instanceof Fi){const s=c.IntervalIntersectsRay(t,e.point,i.item.Start,this.ConeRightSideDirection);s&&this.SegmentIsNotHorizontal(s,e.point)&&this.EnqueueEvent(this.CreateRightIntersectionEvent(i.item,s,e))}}CreateRightIntersectionEvent(t,e,i){return new Tr(t,e,i)}GetLastNodeToTheLeftOfPointInRightSegmentTree(t){return this.rightConeSides.findLast(e=>rt.PointIsToTheRightOfSegment(t,e))}LookForIntersectionOfObstacleSideAndLeftConeSide(t,e){const i=this.GetFirstNodeToTheRightOfPoint(t);if(i==null||!(i.item instanceof hi))return;const s=i.item,n=c.IntervalIntersectsRay(t,e.point,s.Start,this.ConeLeftSideDirection);n&&this.EnqueueEvent(new Ls(s,n,e))}GetFirstNodeToTheRightOfPoint(t){return this.leftConeSides.findFirst(e=>rt.PointIsToTheLeftOfSegment(t,e))}static PointIsToTheLeftOfSegment(t,e){return c.getTriangleOrientation(e.Start,e.Start.add(e.Direction),t)===D.Counterclockwise}static PointIsToTheRightOfSegment(t,e){return c.getTriangleOrientation(e.Start,e.Start.add(e.Direction),t)===D.Clockwise}FixConeLeftSideIntersections(t,e){do e=this.leftConeSides.next(e);while(e!=null&&c.PointToTheRightOfLineOrOnLine(t.Start,e.item.Start,e.item.Start.add(e.item.Direction)));if(e!=null&&e.item instanceof hi){const i=e.item,s=c.IntervalIntersectsRay(t.start,t.End,i.Start,i.Direction);s&&this.EnqueueEvent(new Ls(i,s,t.EndVertex))}}InsertToTree(t,e){return this.coneSideComparer.SetOperand(e),t.insert(e)}CloseConesAddConeAtLeftVertex(t,e){const i=t.Vertex.prevOnPolyline.point;t.Site.sub(i).dot(this.directionPerp)<-C.distanceEpsilon&&this.RemoveConesClosedBySegment(t.Site,i),e.point.sub(t.Site).dot(this.directionPerp)<-C.distanceEpsilon&&this.RemoveConesClosedBySegment(e.point,t.Site);const s=t.Site,n=s.add(this.ConeLeftSideDirection),o=s.add(this.ConeRightSideDirection),a=e.point;this.GetZP(s.sub(i))>C.distanceEpsilon&&this.RemoveLeftSide(new ns(t.Vertex.prevOnPolyline));const h=this.GetZP(a)-this.Z;h<-C.distanceEpsilon&&this.RemoveRightSide(new rs(e));const u=a.sub(t.Site);if(h<-C.distanceEpsilon||R(h,0)&&this.GetZP(u)>0&&u.dot(this.directionPerp)>-C.distanceEpsilon)this.CreateConeOnVertex(t);else if(!c.PointToTheLeftOfLineOrOnLine(a,s,o))this.CreateConeOnVertex(t),this.EnqueueEvent(new Mi(e));else if(c.PointToTheLeftOfLineOrOnLine(a,s,n))this.EnqueueEvent(new Mi(e)),this.GetZP(u)>C.distanceEpsilon&&(this.LookForIntersectionOfObstacleSideAndRightConeSide(t.Site,e),this.InsertLeftSide(new ns(t.Vertex)));else{this.EnqueueEvent(new Mi(e));const d=new Vn(t.Vertex.point,this),m=new ss(t.Vertex.point,e,new Fi(d));d.RightSide=m,d.LeftSide=new hi(d),this.LookForIntersectionWithConeLeftSide(this.InsertToTree(this.leftConeSides,d.LeftSide));const y=this.InsertToTree(this.rightConeSides,m);this.FixConeRightSideIntersections(m,y),this.GetZP(u)>C.distanceEpsilon&&this.InsertLeftSide(new ns(t.Vertex))}}RemoveCone(t){t.Removed=!0,this.RemoveSegFromLeftTree(t.LeftSide),this.RemoveSegFromRightTree(t.RightSide)}RemoveSegFromRightTree(t){this.coneSideComparer.SetOperand(t);let e=this.rightConeSides.remove(t);if(t.Removed=!0,e==null){const i=this.Z;this.Z=Math.max(this.GetZP(t.Start),this.Z-.01),this.coneSideComparer.SetOperand(t),e=this.rightConeSides.remove(t),this.Z=i}}RemoveSegFromLeftTree(t){if(t.Removed=!0,this.coneSideComparer.SetOperand(t),this.leftConeSides.remove(t)==null){const i=this.Z;this.Z=Math.max(this.GetZP(t.Start),this.Z-.01),this.coneSideComparer.SetOperand(t),this.leftConeSides.remove(t),this.Z=i}}FixConeRightSideIntersections(t,e){do e=this.rightConeSides.previous(e);while(e!=null&&c.PointToTheLeftOfLineOrOnLine(t.start,e.item.Start,e.item.Start.add(e.item.Direction)));if(e!=null){let i;if(e.item instanceof Fi){const s=e.item;(i=c.IntervalIntersectsRay(t.start,t.End,s.Start,s.Direction))&&this.EnqueueEvent(this.CreateRightIntersectionEvent(s,i,t.EndVertex))}}}CreateConeOnVertex(t){const e=new Vn(t.Site,this);e.LeftSide=new hi(e),e.RightSide=new Fi(e);const i=this.InsertToTree(this.leftConeSides,e.LeftSide),s=this.InsertToTree(this.rightConeSides,e.RightSide);this.LookForIntersectionWithConeRightSide(s),this.LookForIntersectionWithConeLeftSide(i)}LookForIntersectionWithConeLeftSide(t){if(t.item instanceof hi){const e=t.item,i=this.FindFirstObstacleSideToTheLeftOfPoint(e.Start);i!=null&&this.TryIntersectionOfConeLeftSideAndObstacleSide(e,i)}else{const e=t.item;t=this.leftConeSides.next(t),t!=null&&t.item instanceof hi&&this.TryIntersectionOfConeLeftSideAndObstacleConeSide(t.item,e)}}LookForIntersectionWithConeRightSide(t){if(t.item instanceof Fi){const e=t.item,i=this.FindFirstObstacleSideToToTheRightOfPoint(e.Start);i!=null&&this.TryIntersectionOfConeRightSideAndObstacleSide(e,i)}else{const e=t.item;t=this.rightConeSides.previous(t),t!=null&&t.item instanceof Fi&&this.TryIntersectionOfConeRightSideAndObstacleConeSide(t.item,e)}}TryIntersectionOfConeRightSideAndObstacleConeSide(t,e){const i=c.IntervalIntersectsRay(e.start,e.End,t.Start,t.Direction);i&&this.EnqueueEvent(this.CreateRightIntersectionEvent(t,i,e.EndVertex))}TryIntersectionOfConeRightSideAndObstacleSide(t,e){const i=c.IntervalIntersectsRay(e.Start,e.End,t.Start,t.Direction);i&&this.EnqueueEvent(this.CreateRightIntersectionEvent(t,i,e.EndVertex))}TryIntersectionOfConeLeftSideAndObstacleConeSide(t,e){const i=c.IntervalIntersectsRay(e.start,e.End,t.Start,t.Direction);i&&this.EnqueueEvent(new Ls(t,i,e.EndVertex))}TryIntersectionOfConeLeftSideAndObstacleSide(t,e){const i=c.IntervalIntersectsRay(e.Start,e.End,t.Start,t.Direction);i&&this.EnqueueEvent(new Ls(t,i,e.EndVertex))}ExtendSegmentToZ(t){const e=t.Direction.dot(this.SweepDirection),i=(this.Z+40-t.Start.dot(this.SweepDirection))/e;return N.mkPP(t.Start,t.Start.add(t.Direction.mul(i)))}GoOverConesSeeingVertexEvent(t){let e=this.FindFirstSegmentInTheRightTreeNotToTheLeftOfVertex(t);if(e==null)return;const s=e.item.Cone,n=s.LeftSide;if(rt.VertexIsToTheLeftOfSegment(t,n))return;const o=[s];if(this.coneSideComparer.SetOperand(n),e=this.leftConeSides.find(n),e==null){const a=this.Z;this.Z=Math.max(this.GetZP(n.Start),this.PreviousZ),this.coneSideComparer.SetOperand(n),e=this.leftConeSides.find(n),this.Z=a}if(!(e==null&&(e=this.GetRbNodeEmergency(n),e==null))){for(e=this.leftConeSides.next(e);e!=null&&!rt.VertexIsToTheLeftOfSegment(t,e.item);)o.push(e.item.Cone),e=this.leftConeSides.next(e);for(const a of o)this.AddEdgeAndRemoveCone(a,t.Site)}}GetRbNodeEmergency(t){if(this.leftConeSides.count===0)return null;for(let e=this.leftConeSides.treeMinimum();e!=null;e=this.leftConeSides.next(e))if(e.item===t)return e;return null}static VertexIsToTheLeftOfSegment(t,e){return c.getTriangleOrientation(e.Start,e.Start.add(e.Direction),t.Site)===D.Counterclockwise}static VertexIsToTheRightOfSegment(t,e){return c.getTriangleOrientation(e.Start,e.Start.add(e.Direction),t.Site)===D.Clockwise}FindFirstSegmentInTheRightTreeNotToTheLeftOfVertex(t){return this.rightConeSides.findFirst(e=>!rt.VertexIsToTheRightOfSegment(t,e))}EnqueueRightVertexEvent(t){this.GetZP(t.Site.sub(t.Vertex.prevOnPolyline.point))>C.tolerance||this.EnqueueEvent(t)}invariant(){for(const t of this.leftConeSides)if(t.Removed)return!1;for(const t of this.rightConeSides)if(t.Removed)return!1;return!0}}class yi extends Ft{constructor(t,e){super(null),this.coneAngle=Math.PI/6,this.ports=new Yt,this._obstacles=Array.from(Xt.OrientHolesClockwise(t)),this._visibilityGraph=e}static mk(t,e,i,s,n){const o=new yi(t,e);return o.Ports=s,o.BorderPolyline=n,o.ConeAngle=i,o}get ConeAngle(){return this.coneAngle}set ConeAngle(t){this.coneAngle=t}get Ports(){return this.ports}set Ports(t){this.ports=t}get BorderPolyline(){return this.borderPolyline}set BorderPolyline(t){this.borderPolyline=t}get Bidirectional(){return this._bidirectional}set Bidirectional(t){this._bidirectional=t}static GetTotalSteps(t){return Math.floor((2*Math.PI-t/2)/t)+1}run(){const t=2*Math.PI-this.coneAngle/2;if(this.Bidirectional)this.HandleBideractionalCase();else{let e;for(let i=0;(e=this.coneAngle*i)<=t;i++)super.ProgressStep(),this.AddDirection(new c(Math.cos(e),Math.sin(e)),this.BorderPolyline,this._visibilityGraph)}}HandleBideractionalCase(){const t=Math.PI/this.coneAngle;for(let e=0;e<t;e++){const i=e*this.coneAngle,s=new Xt;this.AddDirection(new c(Math.cos(i),Math.sin(i)),this.BorderPolyline,s);const n=new Xt;this.AddDirection(new c(Math.cos(i)*-1,Math.sin(i)*-1),this.BorderPolyline,n),this.AddIntersectionOfBothDirectionSweepsToTheResult(s,n)}}AddIntersectionOfBothDirectionSweepsToTheResult(t,e){for(const i of t.Edges)e.FindEdgePP(i.SourcePoint,i.TargetPoint)!=null&&this._visibilityGraph.AddEdgePP(i.SourcePoint,i.TargetPoint)}AddDirection(t,e,i){rt.Sweep(this._obstacles,t,this.coneAngle,i,this.Ports,e)}}class Wt extends an{mk(t,e){const i=new Wt(t);return i.HookSize=e,i}constructor(t){super(),this.adjustmentAngle=Math.PI/10,this.hookSize=9,this.curve=t,this.location=this.curve().start}get Location(){return this.location}get Curve(){return this.curve()}SetLocation(t){this.location=t}get AdjustmentAngle(){return this.adjustmentAngle}set AdjustmentAngle(t){this.adjustmentAngle=t}get HookSize(){return this.hookSize}set HookSize(t){this.hookSize=t}}class Ie extends ke{get LoosePolyline(){return this.loosePolyline}set LoosePolyline(t){this.loosePolyline=t}constructor(t,e,i=new c(0,0)){super(t,e,i)}static mk(t,e){return new Ie(t,e)}}class F extends an{get Location(){return this.curve.value(this.parameter)}set Location(t){throw new Error("Method should not be called.")}static mk(t,e){const i=new F;return i.curve=t,i.parameter=e,i}get Parameter(){return this.parameter}set Parameter(t){this.parameter=t}get Curve(){return this.curve}set Curve(t){this.curve=t}}class re{constructor(){this.capacityOverflowCoefficient=re.DefaultCapacityOverflowCoefficientMultiplier,this.RotateBundles=!1,this.MaxHubRadius=50,this.MinHubRadius=.1,this.CreateUnderlyingPolyline=!1,this.pathLengthImportance=re.DefaultPathLengthImportance,this.inkImportance=re.DefaultInkImportance,this.edgeSeparation=re.DefaultEdgeSeparation,this._edgeWidthShrinkCoeff=1,this.useCubicBezierSegmentsInsideOfHubs=!1,this.angleThreshold=Math.PI/180*45,this.hubRepulsionImportance=100,this.bundleRepulsionImportance=100,this.minimalRatioOfGoodCdtEdges=.9,this.highestQuality=!0,this.KeepOverlaps=!1,this.StopAfterShortestPaths=!1}toJSON(){const t={};return this.capacityOverflowCoefficient!=re.DefaultCapacityOverflowCoefficientMultiplier&&(t.capacityOverflowCoefficient=this.capacityOverflowCoefficient),this.RotateBundles&&(t.RotateBundles=this.RotateBundles),this.MaxHubRadius!=50&&(t.MaxHubRadius=this.MaxHubRadius),this.MinHubRadius!=.1&&(t.MinHubRadius=this.MinHubRadius),this.CreateUnderlyingPolyline&&(t.CreateUnderlyingPolyline=this.CreateUnderlyingPolyline),this.pathLengthImportance!=re.DefaultPathLengthImportance&&(t.pathLengthImportance=this.pathLengthImportance),this.inkImportance!=re.DefaultInkImportance&&(t.inkImportance=this.inkImportance),this.edgeSeparation!=re.DefaultEdgeSeparation&&(t.edgeSeparation=this.edgeSeparation),this._edgeWidthShrinkCoeff!=1&&(t._edgeWidthShrinkCoeff=this._edgeWidthShrinkCoeff),this.useCubicBezierSegmentsInsideOfHubs&&(t.useCubicBezierSegmentsInsideOfHubs=this.useCubicBezierSegmentsInsideOfHubs),this.angleThreshold!=Math.PI/180*45&&(t.angleThreshold=this.angleThreshold),this.hubRepulsionImportance!=100&&(t.hubRepulsionImportance=this.hubRepulsionImportance),this.bundleRepulsionImportance!=100&&(t.bundleRepulsionImportance=this.bundleRepulsionImportance),this.minimalRatioOfGoodCdtEdges!=.9&&(t.minimalRatioOfGoodCdtEdges=this.minimalRatioOfGoodCdtEdges),this.highestQuality||(t.highestQuality=this.highestQuality),this.KeepOverlaps&&(t.KeepOverlaps=this.KeepOverlaps),this.StopAfterShortestPaths&&(t.StopAfterShortestPaths=this.StopAfterShortestPaths),t}static createFromJSON(t){const e=new re;return t.capacityOverflowCoefficient&&(e.capacityOverflowCoefficient=t.capacityOverflowCoefficient),t.RotateBundles&&(e.RotateBundles=t.RotateBundles),t.MaxHubRadius&&(e.MaxHubRadius=t.MaxHubRadius),t.MinHubRadius&&(e.MinHubRadius=t.MinHubRadius),t.CreateUnderlyingPolyline&&(e.CreateUnderlyingPolyline=t.CreateUnderlyingPolyline),t.pathLengthImportance&&(e.pathLengthImportance=t.pathLengthImportance),t.inkImportance&&(e.inkImportance=t.inkImportance),t.edgeSeparation&&(e.edgeSeparation=t.edgeSeparation),t._edgeWidthShrinkCoeff&&(e._edgeWidthShrinkCoeff=t._edgeWidthShrinkCoeff),t.useCubicBezierSegmentsInsideOfHubs&&(e.useCubicBezierSegmentsInsideOfHubs=t.useCubicBezierSegmentsInsideOfHubs),t.angleThreshold&&(e.angleThreshold=t.angleThreshold),t.hubRepulsionImportance&&(e.hubRepulsionImportance=t.hubRepulsionImportance),t.bundleRepulsionImportance&&(e.bundleRepulsionImportance=t.bundleRepulsionImportance),t.minimalRatioOfGoodCdtEdges&&(e.minimalRatioOfGoodCdtEdges=t.minimalRatioOfGoodCdtEdges),t.highestQuality&&(e.HighestQuality=t.highestQuality),t.KeepOverlaps&&(e.KeepOverlaps=t.KeepOverlaps),t.StopAfterShortestPaths&&(e.StopAfterShortestPaths=t.StopAfterShortestPaths),e}get CapacityOverflowCoefficient(){return this.capacityOverflowCoefficient}set CapacityOverflowCoefficient(t){this.capacityOverflowCoefficient=t}get PathLengthImportance(){return this.pathLengthImportance}set PathLengthImportance(t){this.pathLengthImportance=t}get InkImportance(){return this.inkImportance}set InkImportance(t){this.inkImportance=t}get EdgeSeparation(){return this.edgeSeparation}set EdgeSeparation(t){this.edgeSeparation=t}get edgeWidthShrinkCoeff(){return this._edgeWidthShrinkCoeff}set edgeWidthShrinkCoeff(t){this._edgeWidthShrinkCoeff=t}ActualEdgeWidth(t,e=this.edgeWidthShrinkCoeff){return e*(this.edgeSeparation+t.lineWidth)}get UseCubicBezierSegmentsInsideOfHubs(){return this.useCubicBezierSegmentsInsideOfHubs}set UseCubicBezierSegmentsInsideOfHubs(t){this.useCubicBezierSegmentsInsideOfHubs=t}get AngleThreshold(){return this.angleThreshold}set AngleThreshold(t){this.angleThreshold=t}get HubRepulsionImportance(){return this.hubRepulsionImportance}set HubRepulsionImportance(t){this.hubRepulsionImportance=t}get BundleRepulsionImportance(){return this.bundleRepulsionImportance}set BundleRepulsionImportance(t){this.bundleRepulsionImportance=t}get MinimalRatioOfGoodCdtEdges(){return this.minimalRatioOfGoodCdtEdges}set MinimalRatioOfGoodCdtEdges(t){this.minimalRatioOfGoodCdtEdges=t}get HighestQuality(){return this.highestQuality}set HighestQuality(t){this.highestQuality=t}}re.DefaultCapacityOverflowCoefficientMultiplier=1e3,re.DefaultPathLengthImportance=500,re.DefaultInkImportance=.01,re.DefaultEdgeSeparation=.5;class hn extends _i{get BoundaryCurve(){return this.node.boundaryCurve}set BoundaryCurve(t){if(t)throw new Error("Cannot set BoundaryCurve directly for RelativeShape")}constructor(t){super(null),this.node=t}}class ui{static GetShapes(t,e){const i=new Map;for(const s of t)ui.ProcessAncestorDescendantCouple(s.target,s.source,i),ui.InsertEdgePortsToShapes(i,s);for(const s of e)ui.ProcessAncestorDescendantCouple(s.source,s.target,i),ui.InsertEdgePortsToShapes(i,s);return ui.BindShapes(i),Array.from(i.values())}static InsertEdgePortsToShapes(t,e){t.get(e.target).Ports.add(e.targetPort),t.get(e.source).Ports.add(e.sourcePort)}static BindShapes(t){for(const[e,i]of t){if(!(e instanceof Gt))continue;const s=e;for(const n of xr(s)){const o=t.get(n);o&&i.AddChild(o)}}}static ProcessAncestorDescendantCouple(t,e,i){let s=qn(e);do{for(const n of xr(s))ui.CreateShapeIfNeeeded(n,i);if(s===t)break;s=qn(s)}while(!0);ui.CreateShapeIfNeeeded(s,i)}static CreateShapeIfNeeeded(t,e){e.has(t)||e.set(t,new hn(t))}static NumberOfActiveNodesIsUnderThreshold(t,e,i){const s=new Set;for(const n of t)if(ui.SetOfActiveNodesIsLargerThanThreshold(n.target,n.source,s,i))return!1;for(const n of e)if(ui.SetOfActiveNodesIsLargerThanThreshold(n.source,n.target,s,i))return!1;return!0}static SetOfActiveNodesIsLargerThanThreshold(t,e,i,s){let n=qn(e);for(;;){for(const o of xr(n))if(i.add(o),i.size>s)return!0;if(n===t)break;n=qn(n)}return i.add(n),i.size>s}}function qn(l){const t=l.node.parent;return ot.getGeom(t)}function*xr(l){for(const t of l.graph.shallowNodes)yield ot.getGeom(t)}class gt{constructor(t){this.stamp=0,this.SetPivotAndAllocateHullPointsArray(t)}SetPivotAndAllocateHullPointsArray(t){this.pivot=new c(0,Number.MAX_SAFE_INTEGER);let e=-1,i=0;for(const s of t)s.y<this.pivot.y?(this.pivot=s,e=i):s.y===this.pivot.y&&s.x>this.pivot.x&&(this.pivot=s,e=i),i++;if(i>=1){this.hullPoints=new Array(i-1),i=0;for(const s of t)i!==e?this.hullPoints[i++]={point:s,deleted:!1,stamp:this.stamp++}:e=-1}}get StackTopPoint(){return this.stack.point}get StackSecondPoint(){return this.stack.next.point}static*CalculateConvexHull(t){const e=new gt(t);for(const i of e.Calculate())yield i}*Calculate(){if(this.pivot.y!==Number.MAX_SAFE_INTEGER){if(this.hullPoints.length===0){yield this.pivot;return}this.SortAllPointsWithoutPivot(),this.Scan();for(const t of this.EnumerateStack())yield t}}*EnumerateStack(){let t=this.stack;for(;t!=null;)yield t.point,t=t.next}Scan(){let t=0;for(;this.hullPoints[t].deleted;)t++;for(this.stack={point:this.pivot,next:null},this.Push(t++),t<this.hullPoints.length&&(this.hullPoints[t].deleted?t++:this.Push(t++));t<this.hullPoints.length;)this.hullPoints[t].deleted?t++:this.LeftTurn(t)?this.Push(t++):this.Pop();for(;this.StackHasMoreThanTwoPoints()&&!this.LeftTurnToPivot();)this.Pop()}LeftTurnToPivot(){return c.getTriangleOrientation(this.StackSecondPoint,this.StackTopPoint,this.pivot)===D.Counterclockwise}StackHasMoreThanTwoPoints(){return this.stack.next!=null&&this.stack.next.next!=null}Pop(){this.stack=this.stack.next}LeftTurn(t){if(this.stack.next==null)return!0;const e=c.getTriangleOrientationWithIntersectionEpsilon(this.StackSecondPoint,this.StackTopPoint,this.hullPoints[t].point);return e===D.Counterclockwise?!0:e===D.Clockwise?!1:this.BackSwitchOverPivot(this.hullPoints[t].point)}BackSwitchOverPivot(t){return this.stack.next.next!=null?!1:this.StackTopPoint.x>this.pivot.x+C.distanceEpsilon&&t.x<this.pivot.x-C.distanceEpsilon}Push(t){this.stack={point:this.hullPoints[t].point,next:this.stack}}SortAllPointsWithoutPivot(){this.hullPoints.sort(Ve(this.pivot))}static createConvexHullAsClosedPolyline(t){return st.mkClosedFromPoints(Array.from(gt.CalculateConvexHull(t)))}}function Ve(l){return(t,e)=>{if(t===e)return 0;if(t==null)return-1;if(e==null)return 1;switch(c.getTriangleOrientationWithIntersectionEpsilon(l,t.point,e.point)){case D.Counterclockwise:return-1;case D.Clockwise:return 1;case D.Collinear:const i=t.point.x-l.x,s=e.point.x-l.x;if(i>C.distanceEpsilon&&s<-C.distanceEpsilon)return-1;if(i<-C.distanceEpsilon&&s>C.distanceEpsilon)return 1;const n=t.point.sub(l),o=e.point.sub(l),a=n.l1-o.l1;return a<0?(t.deleted=!0,-1):a>0?(e.deleted=!0,1):(t.stamp>e.stamp?t.deleted=!0:e.deleted=!0,0)}throw new Error}}function Te(l,t,e){l.irect.intersects_rect(t.irect)&&(l.Left==null?t.Left==null?e(l.UserData,t.UserData):(Te(l,t.Left,e),Te(l,t.Right,e)):t.Left!=null?(Te(l.Left,t.Left,e),Te(l.Left,t.Right,e),Te(l.Right,t.Left,e),Te(l.Right,t.Right,e)):(Te(l.Left,t,e),Te(l.Right,t,e)))}function pe(l,t,e){l.irect.intersects_rect(t.irect)&&(l===t?Fs(l,e):l.Left==null?t.Left==null?e(l.UserData,t.UserData):(pe(l,t.Left,e),pe(l,t.Right,e)):t.Left!=null?(pe(l.Left,t.Left,e),pe(l.Left,t.Right,e),pe(l.Right,t.Left,e),pe(l.Right,t.Right,e)):(pe(l.Left,t,e),pe(l.Right,t,e)))}function Zt(l,t,e){if(!l.irect.intersects_rect(t.irect))return!1;if(l===t)return Or(l,e);if(l.Left==null){if(t.Left==null)return e(l.UserData,t.UserData);if(Zt(l,t.Left,e)||Zt(l,t.Right,e))return!0}else if(t.Left!=null){if(Zt(l.Left,t.Left,e)||Zt(l.Left,t.Right,e)||Zt(l.Right,t.Left,e)||Zt(l.Right,t.Right,e))return!0}else if(Zt(l.Left,t,e)||Zt(l.Right,t,e))return!0;return!1}function Or(l,t){return l.Left==null?!1:Zt(l.Left,l.Left,t)||Zt(l.Left,l.Right,t)||Zt(l.Right,l.Right,t)}function Fs(l,t){l.Left!=null&&(pe(l.Left,l.Left,t),pe(l.Left,l.Right,t),pe(l.Right,l.Right,t))}const q=BigInt("6364136223846793005"),zn=(BigInt(1)<<BigInt(32))-BigInt(1),ci=(BigInt(1)<<BigInt(64))-BigInt(1);class Ds{constructor(t,e){this._state=BigInt(0),this._inc=(BigInt(e)<<BigInt(1)|BigInt(1))&ci,this._random_b(),this._state=this._state+BigInt(t)&ci,this._random_b()}_random_b(){const t=this._state;this._state=t*q+this._inc&ci;const e=(t>>BigInt(18)^t)>>BigInt(27),i=t>>BigInt(59),s=i^BigInt(31);return(e>>i|e<<s)&zn}_advance(t){t&=ci;let e=BigInt(1),i=q,s=BigInt(0),n=this._inc;for(;t>0;)t&BigInt(1)&&(e=e*i&ci,s=s*i+n&ci),n=(i+BigInt(1))*n&ci,i=i*i&ci,t>>=BigInt(1);this._state=e*this._state+s&ci}randint(t){if(t>zn)throw new TypeError(`Bound too large: ${t}`);if(t<=0)throw new TypeError(`Empty sample space for r: 0 \u2264 r < ${t}`);const e=BigInt(t),i=(zn^e)%e;for(;;){const s=this._random_b();if(s>=i)return Number(s%e)}}random(){return Number(this._random_b())/Math.pow(2,32)}}let Di;function Vi(l){return Di==null&&(Di=new Ds(0,0)),Di.randint(l)}function os(l){Di=new Ds(l,0)}function Wi(){return Di==null&&(Di=new Ds(0,0)),Di.random()}function*Ci(l){const t=new Array(l.nodeCount).fill(!1),e=new Ge.o;for(let i=0;i<l.nodeCount;i++)if(!t[i]){const s=new Array;for(Lr(i,e,t);e.length>0;){const n=e.dequeue();s.push(n);for(const o of Br(l,n))Lr(o,e,t)}yield s}}function*Br(l,t){for(const e of l.outEdges[t])yield e.target;for(const e of l.inEdges[t])yield e.source}function Lr(l,t,e){e[l]===!1&&(t.enqueue(l),e[l]=!0)}function Rs(l){const t=new me;return t.SetEdges(l,me.vertexCount(l)),t}function Fr(l){const t=new me;return t.SetEdges(l,me.vertexCount(l)),t}function Qe(l,t){const e=new me;return e.SetEdges(l,t),e}class me{constructor(){this.nodeCount=0}*incidentEdges(t){for(const e of this.outEdges[t])yield e;for(const e of this.inEdges[t])yield e}static deleteFromArray(t,e){const i=t.indexOf(e,0);i>-1&&t.splice(i,1)}removeEdge(t){me.deleteFromArray(this.edges,t),t.source!==t.target?(me.deleteFromArray(this.outEdges[t.source],t),me.deleteFromArray(this.inEdges[t.target],t)):me.deleteFromArray(this.selfEdges[t.source],t)}static vertexCount(t){let e=0;for(const i of t)i.source>=e&&(e=i.source),i.target>=e&&(e=i.target);return++e}SetEdges(t,e){this.edges=t,this.nodeCount=e;const i=new Array(this.nodeCount).fill(0),s=new Array(this.nodeCount).fill(0),n=new Array(this.nodeCount).fill(0);this.outEdges=new Array(this.nodeCount),this.inEdges=new Array(this.nodeCount),this.selfEdges=new Array(this.nodeCount);for(const o of this.edges)o.source!==o.target?(i[o.source]++,s[o.target]++):n[o.source]++;for(let o=0;o<this.nodeCount;o++)this.outEdges[o]=new Array(i[o]),i[o]=0,this.inEdges[o]=new Array(s[o]),s[o]=0,this.selfEdges[o]=new Array(n[o]),n[o]=0;for(const o of this.edges){const a=o.source,h=o.target;a!==h?(this.outEdges[a][i[a]++]=o,this.inEdges[h][s[h]++]=o):this.selfEdges[a][n[a]++]=o}}inEdgesCount(t){return this.inEdges[t].length}outEdgesCount(t){return this.outEdges[t].length}selfEdgesCount(t){return this.selfEdges[t].length}addEdge(t){this.edges.push(t),t.source!==t.target?(this.outEdges[t.source].push(t),this.inEdges[t.target].push(t)):this.selfEdges[t.source].push(t)}*nodesOfConnectedGraph(){if(this.edges.length===0)return;const t=new Set,e=new Ge.o;let i=this.edges[0].source;for(me.enqueue(t,e,i),yield i;e.length>0;){i=e.dequeue();for(const s of this.outEdges[i]){const n=s.target;t.has(n)||(me.enqueue(t,e,n),yield n)}for(const s of this.inEdges[i]){const n=s.source;t.has(n)||(me.enqueue(t,e,n),yield n)}}}*pred(t){for(const e of this.inEdges[t])yield e.source}*succ(t){for(const e of this.outEdges[t])yield e.target}static enqueue(t,e,i){e.enqueue(i),t.add(i)}}class Et{constructor(t,e){this.x=t,this.y=e}get source(){return this.x}get target(){return this.y}isDiagonal(){return this.x===this.y}}var ce;(function(l){l[l.Increasing=0]="Increasing",l[l.Decreasing=1]="Decreasing",l[l.Extremum=2]="Extremum"})(ce||(ce={}));class We{get Sequence(){return this.f}set Sequence(t){this.f=t}get Length(){return this.length}set Length(t){this.length=t}constructor(t,e){this.f=t,this.length=e}FindMinimum(){let t=0,e=this.length-1,i=t+Math.floor((e-t)/2);const s=this.f(i);if(s>=this.f(0)&&s>=this.f(this.length-1))return this.f(0)<this.f(this.length-1)?0:this.length-1;for(;e-t>1;)switch(i=t+Math.floor((e-t)/2),this.BehaviourAtIndex(i)){case ce.Decreasing:t=i;break;case ce.Increasing:e=i;break;case ce.Extremum:return i}return t===e||this.f(t)<=this.f(e)?t:e}BehaviourAtIndex(t){const e=this.f(t);if(t===0){const n=this.f(1);return n===e?ce.Extremum:n>e?ce.Increasing:ce.Decreasing}if(t===this.length-1){const n=this.f(this.length-2);return n===e?ce.Extremum:n>e?ce.Decreasing:ce.Increasing}const i=e-this.f(t-1),s=this.f(t+1)-e;return i*s<=0?ce.Extremum:i>0?ce.Increasing:ce.Decreasing}FindMaximum(){let t=0,e=this.length-1,i=t+Math.floor((e-t)/2);const s=this.f(i);if(s<=this.f(0)&&s<=this.f(this.length-1))return this.f(0)>this.f(this.length-1)?0:this.length-1;for(;e-t>1;)switch(i=t+Math.floor((e-t)/2),this.BehaviourAtIndex(i)){case ce.Decreasing:e=i;break;case ce.Increasing:t=i;break;case ce.Extremum:return i}return t===e||this.f(t)>=this.f(e)?t:e}}class Dr{toArray(){const t=[];for(let e=0;e<this.length;e++)t.push(this.f(e));return t}constructor(t,e){this.f=t,this.length=e}GetAdjustedSequenceForMinimum(){const t=this.f(0),i=(this.f(this.length-1)-t)/(this.length-1);return s=>Math.min(this.f(s),t+i*s)}GetAdjustedSequenceForMaximum(){const t=this.f(0),i=(this.f(this.length-1)-t)/(this.length-1);return s=>Math.max(this.f(s),t+i*s)}FindMinimum(){return this.f(0)===this.f(this.length-1)?new We(this.f,this.length).FindMinimum():new We(this.GetAdjustedSequenceForMinimum(),this.length).FindMinimum()}FindMaximum(){return this.f(0)===this.f(this.length-1)?new We(this.f,this.length).FindMaximum():new We(this.GetAdjustedSequenceForMaximum(),this.length).FindMaximum()}}class un{constructor(t,e){this.P=t,this.Q=e}LeftFromLineOnP(t,e,i){const s=this.P.pnt(t);return this.upperBranchOnP?c.pointToTheLeftOfLineOrOnLine(i,s,e):c.pointToTheRightOfLineOrOnLine(i,s,e)}LeftFromLineOnQ(t,e,i){const s=this.Q.pnt(t);return this.lowerBranchOnQ?c.pointToTheLeftOfLineOrOnLine(i,s,e):c.pointToTheRightOfLineOrOnLine(i,s,e)}PrevOnP(t){return this.upperBranchOnP?this.P.Prev(t):this.P.Next(t)}PrevOnQ(t){return this.lowerBranchOnQ?this.Q.Prev(t):this.Q.Next(t)}NextOnP(t){return this.upperBranchOnP?this.P.Next(t):this.P.Prev(t)}NextOnQ(t){return this.lowerBranchOnQ?this.Q.Next(t):this.Q.Prev(t)}MedianOnP(t,e){return this.upperBranchOnP?this.P.Median(t,e):this.P.Median(e,t)}MedianOnQ(t,e){return this.lowerBranchOnQ?this.Q.Median(t,e):this.Q.Median(e,t)}ModuleP(t,e){return this.upperBranchOnP?this.P.Module(e-t):this.P.Module(t-e)}ModuleQ(t,e){return this.lowerBranchOnQ?this.Q.Module(e-t):this.Q.Module(t-e)}TangentBetweenBranches(t,e,i,s){for(;e!==t||s!==i;){const n=e!==t?this.MedianOnP(t,e):t,o=s!==i?this.MedianOnQ(i,s):i,a=this.P.pnt(n),h=this.Q.pnt(o);let u=!0;this.ModuleP(t,e)>1?this.LeftFromLineOnP(this.NextOnP(n),a,h)?t=n:this.LeftFromLineOnP(this.PrevOnP(n),a,h)?e=n:u=!1:e!==t?this.LeftFromLineOnP(e,this.P.pnt(t),h)?t=e:this.LeftFromLineOnP(t,this.P.pnt(e),h)?e=t:u=!1:u=!1;let d=!0;this.ModuleQ(i,s)>1?this.LeftFromLineOnQ(this.NextOnQ(o),h,a)?i=o:this.LeftFromLineOnQ(this.PrevOnQ(o),h,a)?s=o:d=!1:s!==i?this.LeftFromLineOnQ(s,this.Q.pnt(i),a)?i=s:this.LeftFromLineOnQ(i,this.Q.pnt(s),a)?s=i:d=!1:d=!1,!u&&!d&&(t=n,e=n,i=o,s=o)}return[t,s]}FindDividingBisector(t){const e={pClosest:void 0,qClosest:void 0,p1:void 0,p2:void 0,q1:void 0,q2:void 0};this.FindClosestFeatures(e),t.bisectorPivot=c.middle(e.pClosest,e.qClosest),t.bisectorRay=e.pClosest.sub(e.qClosest).rotate(Math.PI/2),t.p1=e.p1,t.p2=e.p2,t.q1=e.q1,t.q2=e.q2}FindClosestPoints(){const t={q2:void 0,p1:void 0,p2:void 0,q1:void 0,pClosest:void 0,qClosest:void 0};return this.FindClosestFeatures(t),{pClosest:t.pClosest,qClosest:t.qClosest}}FindClosestFeatures(t){const e={leftTangentPoint:void 0,rightTangentPoint:void 0};this.P.GetTangentPoints(e,this.Q.pp(0).point),t.p2=e.leftTangentPoint,t.p1=e.rightTangentPoint,t.p2===t.p1&&(t.p2+=this.P.count),this.Q.GetTangentPoints(e,this.P.pp(0).point),t.q1=e.leftTangentPoint,t.q2=e.rightTangentPoint,t.q2===t.q1&&(t.q2+=this.Q.count),this.FindClosestPoints_(t)}FindClosestPoints_(t){for(;this.ChunksAreLong(t.p2,t.p1,t.q2,t.q1);)this.ShrinkChunks(t);t.p1===t.p2?(t.pClosest=this.P.pp(t.p2).point,t.q1===t.q2?t.qClosest=this.Q.pp(t.q1).point:(t.qClosest=c.ClosestPointAtLineSegment(t.pClosest,this.Q.pp(t.q1).point,this.Q.pp(t.q2).point),c.closeDistEps(t.qClosest,this.Q.pnt(t.q1))?t.q2=t.q1:c.closeDistEps(t.qClosest,this.Q.pnt(t.q2))&&(t.q1=t.q2))):(t.qClosest=this.Q.pp(t.q1).point,t.pClosest=c.ClosestPointAtLineSegment(t.qClosest,this.P.pp(t.p1).point,this.P.pp(t.p2).point),c.closeDistEps(t.pClosest,this.P.pnt(t.p1))?t.p2=t.p1:c.closeDistEps(t.qClosest,this.P.pnt(t.p2))&&(t.p1=t.p2))}ChunksAreLong(t,e,i,s){const n=this.P.Module(t-e)+1;if(n>2)return!0;const o=this.Q.Module(s-i)+1;return o>2||n===2&&o===2}ShrinkChunks(t){const e=t.p1===t.p2?t.p1:this.P.Median(t.p1,t.p2),i=t.q1===t.q2?t.q1:this.Q.Median(t.q2,t.q1),s=this.P.pp(e).point,n=this.Q.pp(i).point,o={a1:void 0,a2:void 0,b1:void 0,b2:void 0};if(this.GetAnglesAtTheMedian(e,i,s,n,o),!this.InternalCut(t,e,i,o.a1,o.a2,o.b1,o.b2)&&!un.OneOfChunksContainsOnlyOneVertex(t,e,i,o.a1,o.b1)&&!this.OnlyOneChunkContainsExactlyTwoVertices(t,{mp:e,mq:i},o)){if(t.p2===this.P.Next(t.p1)&&t.q1===this.Q.Next(t.q2)){const a=N.minDistBetweenLineSegments(this.P.pnt(t.p1),this.P.pnt(t.p2),this.Q.pnt(t.q1),this.Q.pnt(t.q2));a.parab===0?t.p2=t.p1:a.parab===1?t.p1=t.p2:a.parcd===0?t.q2=t.q1:a.parcd===1&&(t.q1=t.q2);return}o.a1<=Math.PI&&o.a2<=Math.PI&&o.b1<=Math.PI&&o.b2<=Math.PI?o.a1+o.b1>Math.PI?o.a1>=Math.PI/2?t.p1=e:t.q1=i:o.a2>=Math.PI/2?t.p2=e:t.q2=i:o.a1>Math.PI?t.p1=e:o.a2>Math.PI?t.p2=e:o.b1>Math.PI?t.q1=i:t.q2=i}}InternalCut(t,e,i,s,n,o,a){let h=!1;if(s>=Math.PI&&n>=Math.PI){const u=this.P.pp(e).point,d=this.Q.pp(i).point,m=this.P.pp(this.P.Next(e)).point,y=c.getTriangleOrientation(u,d,this.Q.pp(0).point),E=c.getTriangleOrientation(u,d,m);y===E?t.p1=this.P.Next(e):t.p2=this.P.Prev(e),h=!0}if(o>=Math.PI&&a>=Math.PI){const u=this.P.pp(e).point,d=this.Q.pp(i).point,m=this.Q.pp(this.Q.Next(i)).point,y=c.getTriangleOrientation(u,d,this.P.pp(0).point),E=c.getTriangleOrientation(u,d,m);y===E?t.q2=this.Q.Next(i):t.q1=this.Q.Prev(i),h=!0}return h}GetAnglesAtTheMedian(t,e,i,s,n){n.a1=c.anglePCP(s,i,this.P.pnt(this.P.Prev(t))),n.a2=c.anglePCP(this.P.pnt(this.P.Next(t)),i,s),n.b1=c.anglePCP(this.Q.pnt(this.Q.Next(e)),s,i),n.b2=c.anglePCP(i,s,this.Q.pnt(this.Q.Prev(e)))}OnlyOneChunkContainsExactlyTwoVertices(t,e,i){const s=t.p2===this.P.Next(t.p1),n=t.q1===this.Q.Next(t.q2);return s&&!n?(this.ProcessShortSide(t,e.mp,e.mq,i.a1,i.b1,i.a2,i.b2),!0):n&&!s?(this.SwapEverything(t,e,i),this.ProcessShortSide(t,e.mp,e.mq,i.a1,i.b1,i.a2,i.b2),this.SwapEverything(t,e,i),!0):!1}SwapEverything(t,e,i){this.SwapPq();let s=t.p2;t.p2=t.q1,t.q1=s,s=t.q2,t.q2=t.p1,t.p1=s,s=e.mq,e.mq=e.mp,e.mp=s,s=i.a2,i.a2=i.b1,i.b1=s,s=i.b2,i.b2=i.a1,i.a1=s}ProcessShortSide(t,e,i,s,n,o,a){e===t.p2?this.ProcessSide(t,i,s,n,a):o<=Math.PI?o+a>=Math.PI?o>=Math.PI/2?t.p2=t.p1:t.q2=i:n>=Math.PI/2?t.q1=i:o<a&&(c.canProject(this.Q.pnt(i),this.P.pp(t.p1).point,this.P.pp(t.p2).point)?t.q1=i:t.p1=t.p2):s+n<=Math.PI?t.p1=t.p2:t.p2=t.p1}SwapPq(){const t=this.P;this.P=this.Q,this.Q=t}ProcessSide(t,e,i,s,n){const o=this.Q.pnt(e);i<=Math.PI?i+s>=Math.PI?i>=Math.PI/2?t.p1=t.p2:t.q1=e:n>=Math.PI/2?t.q2=e:i<n&&(c.canProject(o,this.P.pp(t.p1).point,this.P.pp(t.p2).point)?t.q2=e:t.p2=t.p1):(t.p2=t.p1,s>=Math.PI?t.q1=e:n>=Math.PI&&(t.q2=e))}static OneOfChunksContainsOnlyOneVertex(t,e,i,s,n){return t.p1===t.p2?(n>=Math.PI/2?t.q1=i:t.q2=i,!0):t.q1===t.q2?(s>=Math.PI/2?t.p1=e:t.p2=e,!0):!1}CalculateLeftTangents(){const t={bisectorPivot:null,bisectorRay:null,p1:0,p2:0,q1:0,q2:0};this.FindDividingBisector(t);const e=this.P.FindTheFurthestVertexFromBisector(t.p1,t.p2,t.bisectorPivot,t.bisectorRay),i=this.Q.FindTheFurthestVertexFromBisector(t.q2,t.q1,t.bisectorPivot,t.bisectorRay);this.upperBranchOnP=!1,this.lowerBranchOnQ=!0,this.leftPLeftQ=this.TangentBetweenBranches(e,t.p1,i,t.q1),this.lowerBranchOnQ=!1,this.leftPRightQ=this.TangentBetweenBranches(e,t.p1,i,t.q2)}CalculateRightTangents(){const t={bisectorPivot:null,bisectorRay:null,p1:0,p2:0,q1:0,q2:0};this.FindDividingBisector(t);const e=this.P.FindTheFurthestVertexFromBisector(t.p1,t.p2,t.bisectorPivot,t.bisectorRay),i=this.Q.FindTheFurthestVertexFromBisector(t.q2,t.q1,t.bisectorPivot,t.bisectorRay);this.upperBranchOnP=!0,this.lowerBranchOnQ=!0,this.rightPLeftQ=this.TangentBetweenBranches(e,t.p2,i,t.q1),this.lowerBranchOnQ=!1,this.rightPRightQ=this.TangentBetweenBranches(e,t.p2,i,t.q2)}}class Pe{static mkFromPoints(t){return new Pe(st.mkClosedFromPoints(t))}get Polyline(){return this.polyline}constructor(t){this.polyline=t,this.points=new Array;for(let e=this.polyline.startPoint;e;e=e.next)this.points.push(e)}Next(t){return this.Module(t+1)}Prev(t){return this.Module(t-1)}get count(){return this.Polyline.count}Module(t){return t<0?t+this.count:t<this.count?t:t-this.count}pp(t){return this.points[this.Module(t)]}pnt(t){return this.pp(t).point}toString(){return this.polyline.toString()}Median(t,e){return e>t?Math.floor((e+t)/2):this.Module(e+Math.floor((this.count+t)/2))}FindTheFurthestVertexFromBisector(t,e,i,s){let n=s.rotate(Math.PI/2);this.polyline.startPoint.point.sub(i).dot(n)<0&&(n=n.mul(-1)),t===e&&(e=this.Next(t));do{const o=this.Median(e,t),a=this.pnt(o);this.pnt(this.Next(o)).sub(a).dot(n)>=0?e=this.Next(o):this.pnt(this.Prev(o)).sub(a).dot(n)>=0?t=this.Prev(o):e=o,t=o}while(t!==e);return t}static TestPolygonDist(t,e){let i=Number.MAX_SAFE_INTEGER;for(let s=0;s<t.count;s++)for(let n=0;n<e.count;n++){const o=N.minDistBetweenLineSegments(t.pnt(s),t.pnt(s+1),e.pnt(n),e.pnt(n+1));i=Math.min(i,o.dist)}return i}static Distance(t,e){const s=new un(t,e).FindClosestPoints();return{p:s.pClosest,q:s.qClosest,dist:s.pClosest.sub(s.qClosest).length}}static DistanceOnly(t,e){return Pe.Distance(t,e).dist}static PolygonIsLegalDebug(t){const e=t.Polyline;for(let i=e.startPoint;i.next!=null&&i.next.next!=null;i=i.next)if(c.getTriangleOrientation(i.point,i.next.point,i.next.next.point)===D.Collinear)return!1;return!0}static DistancePoint(t,e){let i=Number.MAX_VALUE;for(let s=0;s<t.count;s++){const n=c.distToLineSegment(e,t.points[s].point,t.points[(s+1)%t.count].point).dist;i=Math.min(i,n)}return i}GetTangentPoints(t,e){const i=new Dr(this.GetSequenceDelegate(e),this.count);t.leftTangentPoint=i.FindMaximum(),t.rightTangentPoint=i.FindMinimum()}GetSequenceDelegate(t){const e=this.pnt(0);return i=>{const s=c.anglePCP(e,t,this.pnt(i));return s<Math.PI?s:s-2*Math.PI}}}class ut{ObstaclesIntersectLine(t,e){return this.ObstaclesIntersectICurve(N.mkPP(t,e))}static PadCorner(t,e,i,s,n){const o=ut.GetPaddedCorner(e,i,s,n);return o.numberOfPoints===-1?!1:(t.addPoint(o.a),o.numberOfPoints===2&&t.addPoint(o.b),!0)}static CurveIsClockwise(t,e){return c.getTriangleOrientation(e,t.start,t.start.add(t.derivative(t.parStart)))==D.Clockwise}static PaddedPolylineBoundaryOfNode(t,e,i=!1){return ut.CreatePaddedPolyline(w.polylineAroundClosedCurve(t),e,i)}static LoosePolylineWithFewCorners(t,e,i){return e<C.distanceEpsilon?t:ut.CreateLoosePolylineOnBisectors(t,e,i)}static CreateLoosePolylineOnBisectors(t,e,i){const s=Array.from(ut.BisectorPoints(t,e));i&&o();const n=gt.CalculateConvexHull(s);return st.mkClosedFromPoints(n);function o(){for(let a=0;a<s.length;a++){const h=s[a];s[a]=new c(h.x+(2*Wi()-1)*i,h.y+(2*Wi()-1)*i)}}}static CreateRectNodeOfPolyline(t){return he(t,t.boundingBox)}CreateLooseObstacles(){this.tightPolylinesToLooseDistances=new Map,this.LooseObstacles=new Array;for(const t of this.TightObstacles){const e=ut.FindMaxPaddingForTightPolyline(this.RootOfTightHierarchy,t,this.LoosePadding);this.tightPolylinesToLooseDistances.set(t,e),this.LooseObstacles.push(ut.LoosePolylineWithFewCorners(t,e,this.randomizationShift))}this.RootOfLooseHierarchy=ut.CalculateHierarchy(this.LooseObstacles)}CreateTightObstacles(){this.RootOfTightHierarchy=this.CreateTightObstacles_(),this.OverlapsDetected=this.TightObstacles.size<this.Obstacles.length}Calculate(){this.IgnoreTightPadding?this.CreateTightObstaclesIgnoringTightPadding():this.CreateTightObstacles(),this.IsEmpty()||this.CreateLooseObstacles()}IsEmpty(){return this.TightObstacles==null||this.TightObstacles.size===0}constructor(t,e,i,s){this.randomizationShift=.01,this.TightObstacles=new Set,this.Obstacles=t,this.TightPadding=e,this.LoosePadding=i,this.IgnoreTightPadding=s}ObstaclesIntersectICurve(t){const e=t.boundingBox;return ut.CurveIntersectsRectangleNode(t,e,this.RootOfTightHierarchy)}static CurveIntersectsRectangleNode(t,e,i){if(!i.irect.intersects(e))return!1;if(i.UserData!=null){const s=i.UserData;return w.intersectionOne(s,t,!1)!=null||ut.PointIsInside(s.start,t)}return ut.CurveIntersectsRectangleNode(t,e,i.Left)||ut.CurveIntersectsRectangleNode(t,e,i.Right)}static PointIsInside(t,e){return w.PointRelativeToCurveLocation(t,e)===at.Inside}CreateTightObstaclesIgnoringTightPadding(){const t=this.Obstacles.map(s=>w.polylineAroundClosedCurve(s)),e=ut.CalculateHierarchy(t),i=ut.GetOverlappedPairSet(e);if(this.TightObstacles=new Set,i.size===0){for(const s of t){const n=ut.FindMaxPaddingForTightPolyline(e,s,this.TightPadding);this.TightObstacles.add(ut.LoosePolylineWithFewCorners(s,n,this.randomizationShift))}this.RootOfTightHierarchy=ut.CalculateHierarchy(Array.from(this.TightObstacles))}else{for(const s of t)this.TightObstacles.add(ut.CreatePaddedPolyline(s,this.TightPadding));if(!this.IsEmpty())for(this.RootOfTightHierarchy=ut.CalculateHierarchy(Array.from(this.TightObstacles)),this.OverlapsDetected=!1;ut.GetOverlappedPairSet(this.RootOfTightHierarchy).size>0;)this.RootOfTightHierarchy=ut.ReplaceTightObstaclesWithConvexHulls(this.TightObstacles,Array.from(i)),this.OverlapsDetected=!0}}CreateTightObstacles_(){if(this.Obstacles.length===0)return null;for(const t of this.Obstacles)ut.CalculateTightPolyline(this.TightObstacles,this.TightPadding,t);return ut.RemovePossibleOverlapsInTightPolylinesAndCalculateHierarchy(this.TightObstacles)}static CalculateTightPolyline(t,e,i){const s=ut.PaddedPolylineBoundaryOfNode(i,e);t.add(s)}static CalculateHierarchy(t){const e=t.map(i=>ut.CreateRectNodeOfPolyline(i));return $t(e)}static RemovePossibleOverlapsInTightPolylinesAndCalculateHierarchy(t,e=null){let i=ut.CalculateHierarchy(Array.from(t)),s;for(;(s=ut.GetOverlappedPairSet(i)).size>0;)i=ut.ReplaceTightObstaclesWithConvexHulls(t,Array.from(s),e);return i}static MapToInt(t){const e=new Map;for(let i=0;i<t.length;i++)e.set(t[i],i);return e}static ReplaceTightObstaclesWithConvexHulls(t,e,i=null){const s=new Set;for(const u of e)s.add(u[0]),s.add(u[1]);const n=Array.from(s),o=ut.MapToInt(n),a=Fr(Array.from(e).map(u=>new Et(o.get(u[0]),o.get(u[1])))),h=Ci(a);for(const u of h){const d=u.map(T=>n[T]),m=ws(d,T=>T),y=gt.createConvexHullAsClosedPolyline(m),E=new Array;for(const T of d)t.delete(T),i!=null&&(E.push(...i.get(T)),i.delete(T));i?.set(y,E),t.add(y)}return ut.CalculateHierarchy(Array.from(t))}static OneCurveLiesInsideOfOther(t,e){return w.PointRelativeToCurveLocation(t.start,e)!==at.Outside||w.PointRelativeToCurveLocation(e.start,t)!==at.Outside}static PolylinesIntersect(t,e){return w.CurvesIntersect(t,e)||ut.OneCurveLiesInsideOfOther(t,e)}static GetOverlappedPairSet(t){const e=new Set;return pe(t,t,(i,s)=>{ut.PolylinesIntersect(i,s)&&e.add([i,s])}),e}static*BisectorPoints(t,e){for(let i=t.startPoint;i!=null;i=i.next){const s={skip:!1},n=ut.GetStickingVertexOnBisector(i,e,s);s.skip||(yield n)}}static GetStickingVertexOnBisector(t,e,i){const s=t.polyline.prev(t).point,n=t.point,o=t.polyline.next(t).point;let a=n.sub(s).normalize().add(n.sub(o).normalize());const h=a.length;return h<C.tolerance?i.skip=!0:(i.skip=!1,a=a.div(h)),a.mul(e).add(n)}static FindMaxPaddingForTightPolyline(t,e,i){let s=i;const n=new Pe(e),o=e.boundingBox.clone();o.pad(2*i);for(const a of Array.from(t.GetNodeItemsIntersectingRectangle(o)).filter(h=>h!==e)){const h=Pe.Distance(n,new Pe(a)).dist;s=Math.min(s,h/ut.LooseDistCoefficient)}return s}static GetPaddedCorner(t,e,i,s){const n=t.point,o=e.point,a=i.point;if(c.getTriangleOrientation(n,o,a)===D.Counterclockwise)return{a:void 0,b:void 0,numberOfPoints:-1};let h=o.sub(n).rotate(Math.PI/2).normalize();if(ut.CornerIsNotTooSharp(n,o,a)){h=h.mul(s);const T=a.sub(o).normalize().mul(s).rotate(Math.PI/2),B=c.lineLineIntersection(n.add(h),o.add(h),o.add(T),a.add(T));return{a:B,b:B,numberOfPoints:1}}const u=o.sub(n).normalize().add(o.sub(a).normalize());if(u.length<C.intersectionEpsilon){const T=o.add(h.mul(s));return{a:T,b:T,numberOfPoints:1}}const d=u.normalize().mul(s),m=d.rotate(Math.PI/2),y=(s-d.dot(h))/m.dot(h),E=m.mul(y);return{a:d.add(E).add(o),b:d.sub(E).add(o),numberOfPoints:2}}static CornerIsNotTooSharp(t,e,i){const s=t.sub(e).rotate(Math.PI/4).add(e);return c.getTriangleOrientation(e,s,i)===D.Counterclockwise}static CreatePaddedPolyline(t,e,i=!1){const s=new st,n=i?Rr(t):t;if(!ut.PadCorner(s,n.endPoint.prev,n.endPoint,n.startPoint,e)||!ut.PadCorner(s,n.endPoint,n.startPoint,n.startPoint.next,e))return ut.CreatePaddedPolyline(st.mkClosedFromPoints(Array.from(gt.CalculateConvexHull(n))),e);for(let o=n.startPoint;o.next.next!=null;o=o.next)if(!ut.PadCorner(s,o,o.next,o.next.next,e))return ut.CreatePaddedPolyline(st.mkClosedFromPoints(Array.from(gt.CalculateConvexHull(n))),e);return s.closed=!0,s}}ut.LooseDistCoefficient=2.1;function Rr(l){const t=new st,e=.01;for(let i=l.startPoint;i;i=i.next){const s=i.point.x+e*Wi(),n=i.point.y+e*Wi();t.addPointXY(s,n)}return t.closed=l.closed,t}class Un{get TightPolyline(){return this.tightPoly}set TightPolyline(t){this.tightPoly=t}static mk(t,e,i){const s=new Un;return s.TightPolyline=t,s.LooseShape=e,s.Distance=i,s}toString(){return(this.TightPolyline==null?"null":this.TightPolyline.toString().substring(0,5))+","+(this.LooseShape==null?"null":this.LooseShape.toString().substring(0,5))}}class Ns{constructor(t,e,i,s){this.loosePolylinesToNodes=new Map,this.MainShape=t,this.TightPadding=e,this.LoosePadding=i,this.ShapesToTightLooseCouples=s}Calculate(t){os(3),this.MainShape.Children.length!==0&&(this.CreateTightObstacles(),this.CreateTigthLooseCouples(t),this.OverlapsDetected&&this.FillTheMapOfShapeToTightLooseCouples())}FillTheMapOfShapeToTightLooseCouples(){const t=$t(this.MainShape.Children.map(e=>he(e,e.BoundingBox)));Te(t,this.coupleHierarchy,this.TryMapShapeToTightLooseCouple.bind(this))}TryMapShapeToTightLooseCouple(t,e){Ns.ShapeIsInsideOfPoly(t,e.TightPolyline)&&this.ShapesToTightLooseCouples.set(t,e)}static ShapeIsInsideOfPoly(t,e){return w.PointRelativeToCurveLocation(t.BoundaryCurve.start,e)===at.Inside}CreateTigthLooseCouples(t){const e=new Array;for(const i of this.tightHierarchy.GetAllLeaves()){const s=ut.FindMaxPaddingForTightPolyline(this.tightHierarchy,i,this.LoosePadding),n=ut.LoosePolylineWithFewCorners(i,s,t),o=new _i(n),a=Un.mk(i,o,s),h=this.tightToShapes.get(i);for(const u of h)this.ShapesToTightLooseCouples.set(u,a);e.push(a)}this.coupleHierarchy=$t(e.map(i=>he(i,i.TightPolyline.boundingBox)))}CreateTightObstacles(){this.tightToShapes=new Map;const t=new Set(this.MainShape.Children.map(this.InitialTightPolyline.bind(this))),e=t.size;this.tightHierarchy=ut.RemovePossibleOverlapsInTightPolylinesAndCalculateHierarchy(t,this.tightToShapes),this.OverlapsDetected=e>t.size}InitialTightPolyline(t){let e=ut.PaddedPolylineBoundaryOfNode(t.BoundaryCurve,this.TightPadding);const i=ws(this.LoosePolylinesUnderShape(t),n=>n).filter(n=>w.PointRelativeToCurveLocation(n,e)===at.Outside);if(i.length==0)return this.tightToShapes&&this.tightToShapes.set(e,[t]),e;const s=Array.from(e).concat(i);return e=st.mkClosedFromPoints(gt.CalculateConvexHull(s)),this.tightToShapes&&this.tightToShapes.set(e,[t]),e}LoosePolylinesUnderShape(t){return t.Children.map(e=>this.ShapesToTightLooseCouples.get(e).LooseShape.BoundaryCurve)}}class Nr{constructor(t,e,i){this.indexToA=t,this.priority=e,this.v=i}}class Ri{get count(){return this.heapSize}ContainsElement(t){return this.cache.has(t)}constructor(t=k){this.heapSize=0,this.compare=t,this.cache=new Map,this.A=[]}SwapWithParent(t){const e=this.A[t>>1];this.PutAtI(t>>1,this.A[t]),this.PutAtI(t,e)}Enqueue(t,e){let i=++this.heapSize;const s=new Nr(i,e,t);for(this.cache.set(t,s),this.A[i]=s;i>1&&this.compare(this.A[i>>1].priority,e)>0;)this.SwapWithParent(i),i>>=1}IsEmpty(){return this.heapSize===0}PutAtI(t,e){this.A[t]=e,e.indexToA=t}Dequeue(){if(this.heapSize===0)throw new Error("dequeue on an empty queue");const t=this.A[1].v;return this.MoveQueueOneStepForward(t),t}DequeueAndGetPriority(t){if(this.heapSize===0)throw new Error("dequeue on an empty queue");const e=this.A[1].v;return t.priority=this.A[1].priority,this.MoveQueueOneStepForward(e),e}MoveQueueOneStepForward(t){this.cache.delete(t),this.PutAtI(1,this.A[this.heapSize]);let e=1;for(;;){let i=e;const s=e<<1;s<=this.heapSize&&this.compare(this.A[s].priority,this.A[e].priority)<0&&(i=s);const n=s+1;if(n<=this.heapSize&&this.compare(this.A[n].priority,this.A[i].priority)<0&&(i=n),i!==e)this.SwapWithParent(i);else break;e=i}this.heapSize--}DecreasePriority(t,e){const i=this.cache.get(t);if(!i)return;i.priority=e;let s=i.indexToA;for(;s>1&&this.compare(this.A[s].priority,this.A[s>>1].priority)<0;){this.SwapWithParent(s);s>>=1}}*GetEnumerator(){for(let t=1;t<=this.heapSize;t++)yield this.A[t].v}Peek(t){if(this.count===0){t.priority=0;return}return t.priority=this.A[1].priority,this.A[1].v}toString(){const t=new ue.fe;for(const e of this.A)t.Append(e+",");return t.ToString()}}class as{constructor(t,e,i){this.upperBound=Number.POSITIVE_INFINITY,this._visGraph=i,this._visGraph.ClearPrevEdgesTable();for(const s of i.Vertices())s.Distance=Number.POSITIVE_INFINITY;this.source=t,this.targets=new Set(e),this.source.Distance=0}GetPath(){const t=new Ri(k);for(this.source.Distance=0,t.Enqueue(this.source,0);!t.IsEmpty()&&(this.current=t.Dequeue(),!this.targets.has(this.current));){for(const e of this.current.OutEdges)this.PassableOutEdge(e)&&this.ProcessNeighbor(t,e,e.Target);for(const e of this.current.InEdges)this.PassableInEdge(e)&&this.ProcessNeighbor(t,e,e.Source)}return this._visGraph.PreviosVertex(this.current)==null?null:this.CalculatePath()}PassableOutEdge(t){return t.Source===this.source||this.targets.has(t.Target)||!as.IsForbidden(t)}PassableInEdge(t){return this.targets.has(t.Source)||t.Target===this.source||!as.IsForbidden(t)}static IsForbidden(t){return t.IsPassable!=null&&!t.IsPassable()||t instanceof li}ProcessNeighbor(t,e,i){const s=e.Length,n=this.current.Distance+s;n>=this.upperBound||(this.targets.has(i)&&(this.upperBound=n,this.closestTarget=i),i!==this.source&&this._visGraph.PreviosVertex(i)==null?(i.Distance=n,this._visGraph.SetPreviousEdge(i,e),t.Enqueue(i,n)):n<i.Distance&&(i.Distance=n,this._visGraph.SetPreviousEdge(i,e),t.DecreasePriority(i,n)))}CalculatePath(){if(this.closestTarget==null)return null;const t=new Array;let e=this.closestTarget;do t.push(e),e=this._visGraph.PreviosVertex(e);while(e!==this.source);return t.push(this.source),t.reverse()}}class cn{get LengthMultiplier(){return this._lengthMultiplier}set LengthMultiplier(t){this._lengthMultiplier=t}get LengthMultiplierForAStar(){return this._lengthMultiplierForAStar}set LengthMultiplierForAStar(t){this._lengthMultiplierForAStar=t}constructor(t,e,i){this._lengthMultiplier=1,this._lengthMultiplierForAStar=1,this._visGraph=t,this._source=e,this._target=i,this._source.Distance=0}GetPath(t){const e=new Ri(k);for(this._source.Distance=0,this._target.Distance=Number.POSITIVE_INFINITY,e.Enqueue(this._source,this.H(this._source));!e.IsEmpty();){const i={priority:0},s=e.DequeueAndGetPriority(i);if(i.priority>=this._target.Distance)break;for(const n of s.OutEdges)if(this.PassableOutEdge(n)){const o=n.Target;this.ProcessNeighbor(e,s,n,o)}for(const n of s.InEdges)if(this.PassableInEdge(n)){const o=n.Source;this.ProcessNeighbor(e,s,n,o)}}return this._visGraph.PreviosVertex(this._target)==null?null:this.CalculatePath(t)}PassableOutEdge(t){return t.Source===this._source||t.Target===this._target||!cn.IsForbidden(t)}PassableInEdge(t){return t.Source===this._target||t.Target===this._source||!cn.IsForbidden(t)}static IsForbidden(t){return t.IsPassable!=null&&!t.IsPassable()||t instanceof li}ProcessNeighborN(t,e,i,s,n){const o=i.Length+n,a=e.Distance+o;s!==this._source&&this._visGraph.PreviosVertex(s)==null?(s.Distance=a,this._visGraph.SetPreviousEdge(s,i),s!==this._target&&t.Enqueue(s,this.H(s))):s!==this._source&&a<s.Distance&&(s.Distance=a,this._visGraph.SetPreviousEdge(s,i),s!==this._target&&t.DecreasePriority(s,this.H(s)))}ProcessNeighbor(t,e,i,s){const n=i.Length,o=e.Distance+n;s!==this._source&&this._visGraph.PreviosVertex(s)==null?(s.Distance=o,this._visGraph.SetPreviousEdge(s,i),s!==this._target&&t.Enqueue(s,this.H(s))):s!==this._source&&o<s.Distance&&(s.Distance=o,this._visGraph.SetPreviousEdge(s,i),s!==this._target&&t.DecreasePriority(s,this.H(s)))}H(t){return t.Distance+t.point.sub(this._target.point).length*this.LengthMultiplierForAStar}CalculatePath(t){const e=new Array;let i=this._target;do e.push(i),t&&this._visGraph.ShrinkLengthOfPrevEdge(i,this.LengthMultiplier),i=this._visGraph.PreviosVertex(i);while(i!==this._source);return e.push(this._source),e.reverse()}}var Ai;(function(l){l[l.Regular=0]="Regular",l[l.Tangent=1]="Tangent"})(Ai||(Ai={}));class Gr{toString(){return ue.Qf.format("{0},{1}",this.Start,this.End)}get Start(){return this.leftTangent.End.point}get End(){return this.rightTangent.End.point}constructor(t,e){this.LeftTangent=t,this.RightTangent=e}get LeftTangent(){return this.leftTangent}set LeftTangent(t){this.leftTangent=t}get RightTangent(){return this.rightTangent}set RightTangent(t){this.rightTangent=t}get RbNode(){return this.rbNode}set RbNode(t){this.rbNode=t}}class kr{get Comp(){return this.comp}set Comp(t){this.comp=t}get IsHigh(){return!this.IsLow}get IsLow(){return this.lowTangent}set IsLow(t){this.lowTangent=t}get SeparatingPolygons(){return this.separatingPolygons}set SeparatingPolygons(t){this.separatingPolygons=t}get Diagonal(){return this.diagonal}set Diagonal(t){this.diagonal=t}get Start(){return this.start}set Start(t){this.start=t}get End(){return this.end}set End(t){this.end=t}constructor(t,e){this.start=t,this.End=e}toString(){return ue.Qf.format("{0},{1}",this.Start,this.End)}}class Mr{get PointOnTangentAndInsertedDiagonal(){return this.pointOnTheRay}set PointOnTangentAndInsertedDiagonal(t){this.pointOnTheRay=t}Compare(t,e){if(t.Start.equal(e.Start))return 0;switch(c.getTriangleOrientation(this.PointOnTangentAndInsertedDiagonal,e.Start,e.End)){case D.Counterclockwise:return-1;default:return 1}}static BelongsToTheDiagonal(t,e,i){return c.closeDistEps(t,c.ClosestPointAtLineSegment(t,e,i))}static IntersectDiagonalWithRay(t,e,i){const s=e.sub(t),n=i.Start,o=i.End,a=O.solve(o.x-n.x,s.x*-1,t.x-n.x,o.y-n.y,s.y*-1,t.y-n.y);return t.add(s.mul(a.y))}}class Gs{constructor(t){this.pivot=t}IComparer(t,e){if(t===e)return 0;if(t==null)return-1;if(e==null)return 1;const i=t.Start.point.sub(this.pivot),s=e.Start.point.sub(this.pivot);return Gs.CompareVectorsByAngleToXAxis(i,s)}static CompareVectorsByAngleToXAxis(t,e){return t.y>=0?e.y<0?-1:Gs.CompareVectorsPointingToTheSameYHalfPlane(t,e):e.y>=0?1:Gs.CompareVectorsPointingToTheSameYHalfPlane(t,e)}static CompareVectorsPointingToTheSameYHalfPlane(t,e){const i=t.x*e.y-t.y*e.x;if(i>C.tolerance)return-1;if(i<-C.tolerance)return 1;if(t.x>=0){if(e.x<0)return-1}else if(e.x>=0)return 1;let s=Math.abs(t.x)-Math.abs(e.x);return s<0?-1:s>0?1:(s=Math.abs(t.y)-Math.abs(e.y),s<0?-1:s>0?1:0)}}class Ei extends Ft{run(){this.useLeftPTangents=!0,this.CalculateAndAddEdges(),this.useLeftPTangents=!1,this.CalculateAndAddEdges()}CalculateAndAddEdges(){for(const t of this.addedPolygons)this.CalculateVisibleTangentsFromPolygon(t);this.ProgressStep()}CalculateVisibleTangentsFromPolygon(t){this.currentPolygon=t,this.AllocateDataStructures(),this.OrganizeTangents(),this.InitActiveDiagonals(),this.Sweep()}AllocateDataStructures(){this.tangents=new Array,this.diagonals=new Array,this.activeDiagonalTree=new Me(this.activeDiagonalComparer.Compare.bind(this.activeDiagonalComparer))}Sweep(){if(!(this.tangents.length<2))for(let t=1;t<this.tangents.length;t++){const e=this.tangents[t];e.Diagonal!=null?(e.Diagonal.RbNode===this.activeDiagonalTree.treeMinimum()&&this.AddVisibleEdge(e),e.IsHigh&&this.RemoveDiagonalFromActiveNodes(e.Diagonal)):e.IsLow&&(this.activeDiagonalComparer.PointOnTangentAndInsertedDiagonal=e.End.point,this.InsertActiveDiagonal(new Gr(e,e.Comp)),e.Diagonal.RbNode===this.activeDiagonalTree.treeMinimum()&&this.AddVisibleEdge(e))}}AddVisibleEdge(t){Xt.AddEdgeVV(jn(this.visibilityGraph,t.start),jn(this.visibilityGraph,t.End))}InitActiveDiagonals(){if(this.tangents.length===0)return;const t=this.tangents[0],e=t.start.point,i=t.End.point;for(const s of this.diagonals)Ei.RayIntersectDiagonal(e,i,s)&&(this.activeDiagonalComparer.PointOnTangentAndInsertedDiagonal=Mr.IntersectDiagonalWithRay(e,i,s),this.InsertActiveDiagonal(s));if(t.Diagonal.RbNode===this.activeDiagonalTree.treeMinimum()&&this.AddVisibleEdge(t),t.IsLow===!1){const s=t.Diagonal;this.RemoveDiagonalFromActiveNodes(s)}}RemoveDiagonalFromActiveNodes(t){const e=this.activeDiagonalTree.deleteSubTree(t.RbNode);e!=null&&e.item!=null&&(e.item.RbNode=e),t.LeftTangent.Diagonal=null,t.RightTangent.Diagonal=null}InsertActiveDiagonal(t){t.RbNode=this.activeDiagonalTree.insert(t),Ei.MarkDiagonalAsActiveInTangents(t)}static MarkDiagonalAsActiveInTangents(t){t.LeftTangent.Diagonal=t,t.RightTangent.Diagonal=t}static RayIntersectDiagonal(t,e,i){const s=i.Start,n=i.End;return c.getTriangleOrientation(t,s,n)===D.Counterclockwise&&c.getTriangleOrientation(t,e,s)!==D.Counterclockwise&&c.getTriangleOrientation(t,e,n)!==D.Clockwise}static TangentComparison(t,e){return Gs.CompareVectorsByAngleToXAxis(t.End.point.sub(t.start.point),e.End.point.sub(e.start.point))}*AllObstacles(){for(const t of this.addedPolygons)yield t;if(this.polygons)for(const t of this.polygons)yield t}OrganizeTangents(){for(const t of this.AllObstacles())t!==this.currentPolygon&&this.ProcessPolygonQ(t);this.tangents.sort(Ei.TangentComparison)}ProcessPolygonQ(t){const e=new un(this.currentPolygon,t);this.useLeftPTangents?e.CalculateLeftTangents():e.CalculateRightTangents();let i=this.useLeftPTangents?e.leftPLeftQ:e.rightPLeftQ;const s=new kr(this.currentPolygon.pp(i[0]),t.pp(i[1]));s.IsLow=!0,s.SeparatingPolygons=!this.useLeftPTangents,i=this.useLeftPTangents?e.leftPRightQ:e.rightPRightQ;const n=new kr(this.currentPolygon.pp(i[0]),t.pp(i[1]));n.IsLow=!1,n.SeparatingPolygons=this.useLeftPTangents,s.Comp=n,n.Comp=s,this.tangents.push(s),this.tangents.push(n),this.diagonals.push(new Gr(s,n))}constructor(t,e,i){super(null),this.polygons=[],this.activeDiagonalComparer=new Mr,this.polygons=t,this.visibilityGraph=i,this.addedPolygons=e}}function jn(l,t){return l.FindVertex(t.point)}class Qn{get Pivot(){return this.pivot}set Pivot(t){this.pivot=t}get IntersectionOfTheRayAndInsertedEdge(){return this.pointOnTheRay}set IntersectionOfTheRayAndInsertedEdge(t){this.pointOnTheRay=t}Compare(t,e){switch(c.getTriangleOrientation(this.IntersectionOfTheRayAndInsertedEdge,e.point,e.nextOnPolyline.point)){case D.Counterclockwise:return-1;default:return 1}}IntersectionPointBelongsToTheInsertedEdge(t){const e=t.point.sub(this.IntersectionOfTheRayAndInsertedEdge),i=t.nextOnPolyline.point.sub(this.IntersectionOfTheRayAndInsertedEdge);return Math.abs(e.x*i.y-i.x*e.y)<C.distanceEpsilon}IntersectEdgeWithRayPPP(t,e,i){const s=O.solve(e.x-t.x,-i.x,this.Pivot.x-t.x,e.y-t.y,-i.y,this.Pivot.y-t.y);if(!(-C.tolerance<=s.x&&s.x<=1+C.tolerance))throw new Error;if(!s)throw new Error;return this.Pivot.add(i.mul(s.y))}IntersectEdgeWithRay(t,e){return this.IntersectEdgeWithRayPPP(t.point,t.nextOnPolyline.point,e)}static constructorPP(t,e){const i=new Qn;return i.pivot=t,i.pointOnTheRay=e,i}}class ks{get Start(){return this.start}set Start(t){this.start=t}get End(){return this.end}set End(t){this.end=t}constructor(t,e){this.start=t,this.end=e}*Sides(){let t=this.start;for(;t!==this.end;){const e=t;yield e,t=e.nextOnPolyline}}MoveStartClockwise(){return this.Start!==this.End?(this.Start=this.Start.nextOnPolyline,!0):!1}toString(){return ue.Qf.format("Stem({0},{1})",this.Start,this.End)}}class bi{get QVertex(){return this.qV}set QVertex(t){this.qV=t}static CalculatePointVisibilityGraph(t,e,i,s){const n=e.FindVertex(i);if(n!=null)return n;const o=new bi(t,e,i,s);return o.FillGraph(),o.QVertex}FillGraph(){this.ComputeHoleBoundariesPossiblyVisibleFromQ(),this.visibleBoundaries.size>0&&(this.SortSAndInitActiveSides(),this.Sweep())}SortSAndInitActiveSides(){this.InitHeapAndInsertActiveSides();for(let t=this.heapForSorting.GetMinimum();this.sortedListOfPolypoints.push(t.Start),t.MoveStartClockwise()?this.heapForSorting.ChangeMinimum(t):this.heapForSorting.Dequeue(),this.heapForSorting.Count!==0;t=this.heapForSorting.GetMinimum());}InitHeapAndInsertActiveSides(){for(const t of this.GetInitialVisibleBoundaryStemsAndInsertActiveSides())this.heapForSorting.Enqueue(t)}*GetInitialVisibleBoundaryStemsAndInsertActiveSides(){for(const[t,e]of this.visibleBoundaries){let i=!1;for(const s of e.Sides()){const n=s;if(n.point.y<this.q.y){if(s.nextOnPolyline.point.y>=this.q.y){const o=c.getTriangleOrientation(this.q,n.point,s.nextOnPolyline.point);if(o===D.Counterclockwise||o===D.Collinear){i=!0,yield new ks(e.Start,s),yield new ks(s.nextOnPolyline,e.End),this.RegisterActiveSide(s);break}}}else{if(n.point.y>this.q.y)break;if(s.point.x>=this.q.x){i=!0,yield new ks(s,e.End),s!==e.Start&&(yield new ks(e.Start,t.prev(n))),this.RegisterActiveSide(s);break}}}i||(yield e)}}RegisterActiveSide(t){this.activeEdgeComparer.IntersectionOfTheRayAndInsertedEdge=this.activeEdgeComparer.IntersectEdgeWithRay(t,new c(1,0)),this.sideNodes.set(t,this.activeSidesTree.insert(t))}constructor(t,e,i,s){this.sideNodes=new Map,this.visibleBoundaries=new Map,this.sortedListOfPolypoints=new Array,this.holes=Array.from(t),this.visibilityGraph=e,this.q=i,this.qPolylinePoint=zt.mkFromPoint(this.q),this.QVertex=this.visibilityGraph.AddVertexP(this.qPolylinePoint.point),this.visibilityKind=s;const n=new Gs(this.q);this.heapForSorting=new kn(n.IComparer.bind(n))}Sweep(){for(const t of this.sortedListOfPolypoints)this.SweepPolylinePoint(t)}SweepPolylinePoint(t){const e=bi.GetIncomingSide(t),i=this.GetOutgoingSide(t);this.activeEdgeComparer.IntersectionOfTheRayAndInsertedEdge=t.point;let s;if(s=this.sideNodes.get(e)){if(s===this.activeSidesTree.treeMinimum()&&this.AddEdge(t),i!=null)s.item=i,this.sideNodes.set(i,s);else{const n=this.activeSidesTree.deleteSubTree(s);n!=null&&n.item!=null&&this.sideNodes.set(n.item,n)}this.sideNodes.delete(e)}else if(i!=null){let n;(n=this.sideNodes.get(i))||(n=this.activeSidesTree.insert(i),this.sideNodes.set(i,n),n===this.activeSidesTree.treeMinimum()&&this.AddEdge(t))}else throw new Error}AddEdge(t){(this.visibilityKind===Ai.Regular||this.visibilityKind===Ai.Tangent&&bi.LineTouchesPolygon(this.QVertex.point,t))&&this.visibilityGraph.AddEdgeF(this.QVertex.point,t.point,(e,i)=>new li(e,i))}static LineTouchesPolygon(t,e){const i=e.polyline.prev(e).point,s=e.polyline.next(e).point,n=e.point;return c.signedDoubledTriangleArea(t,n,i)*c.signedDoubledTriangleArea(t,n,s)>=0}GetOutgoingSide(t){const e=this.visibleBoundaries.get(t.polyline);return t===e.End?null:t}static GetIncomingSide(t){return t.prevOnPolyline}ComputeHoleBoundariesPossiblyVisibleFromQ(){this.InitActiveEdgesAndActiveEdgesComparer();for(const t of this.holes)this.ComputeVisiblePartOfTheHole(t)}InitActiveEdgesAndActiveEdgesComparer(){this.activeEdgeComparer=new Qn,this.activeEdgeComparer.pivot=this.q,this.activeSidesTree=new Me(this.activeEdgeComparer.Compare.bind(this.activeEdgeComparer))}ComputeVisiblePartOfTheHole(t){let e,i=!0;for(e=t.startPoint;!this.HoleSideIsVisibleFromQ(t,e);e=t.next(e))i=!1;let s=t.next(e);if(i)for(;this.HoleSideIsVisibleFromQ(t,t.prev(e));)e=t.prev(e);for(;this.HoleSideIsVisibleFromQ(t,s);s=t.next(s));this.visibleBoundaries.set(t,new ks(e,s))}HoleSideIsVisibleFromQ(t,e){return c.signedDoubledTriangleArea(this.q,e.point,t.next(e).point)>=-C.squareOfDistanceEpsilon}}class ct extends Ft{constructor(){super(...arguments),this.IgnoreTightPadding=!0,this.activeRectangle=X.mkEmpty(),this.activePolygons=new Array,this.alreadyAddedOrExcludedPolylines=new Set,this.UseEdgeLengthMultiplier=!1,this.UseInnerPolylingShortcutting=!0,this.UsePolylineEndShortcutting=!0,this.AllowedShootingStraightLines=!0,this.LookForRoundedVertices=!1}rerouteEdge(t){const e=t.smoothedPolyline?st.mkFromPoints(t.smoothedPolyline):st.mkFromPoints(t.getSmoothPolyPoints());this.pathOptimizer.run(e),t.curve=this.pathOptimizer.poly.toCurve()}static constructorANNN(t,e,i,s){return ct.constructorANNNB(t,e,i,s,!1)}get Obstacles(){return this.obstacles_}set Obstacles(t){this.obstacles_=t}get EnteringAngleBound(){return this.enteringAngleBound_}set EnteringAngleBound(t){this.enteringAngleBound_=t}get SourceTightPolyline(){return this._sourceTightPolyline}set SourceTightPolyline(t){this._sourceTightPolyline=t}get TargetTightPolyline(){return this.targetTightPolyline}set TargetTightPolyline(t){this.targetTightPolyline=t}get TargetLoosePolyline(){return this.targetLoosePolyline}set TargetLoosePolyline(t){this.targetLoosePolyline=t}get VisibilityGraph(){return this.visibilityGraph}set VisibilityGraph(t){this.visibilityGraph=t}get SourcePort(){return this.sourcePort}set SourcePort(t){if(this.sourcePort=t,this.sourcePort!=null)if(this.SourceTightPolyline=ct.GetFirstHitPolyline(this.sourcePort.Location,this.ObstacleCalculator.RootOfTightHierarchy),this.sourcePort instanceof Ue)this.alreadyAddedOrExcludedPolylines.add(this.SourceLoosePolyline),this.StartPointOfEdgeRouting=this.SourcePort.Location;else{const e=this.sourcePort;this.StartPointOfEdgeRouting=this.TakeBoundaryPortOutsideOfItsLoosePolyline(e.Curve,e.Parameter,this.SourceLoosePolyline)}}get TargetPort(){return this.targetPort}set TargetPort(t){this.targetPort=t}get LoosePadding(){return this.loosePadding}set LoosePadding(t){this.loosePadding=t,this.ObstacleCalculator!=null&&(this.ObstacleCalculator.LoosePadding=t)}get OffsetForPolylineRelaxing(){return this.TightPadding*.75}get StartPointOfEdgeRouting(){return this.startPointOfRouting_}set StartPointOfEdgeRouting(t){this.startPointOfRouting_=t}ExtendVisibilityGraphToLocation(t){this.VisibilityGraph==null&&(this.VisibilityGraph=new Xt);let e=null;if(!this.activeRectangle.contains(t)){this.activeRectangle.isEmpty?this.activeRectangle=X.mkPP(this.SourcePort.Location,t):this.activeRectangle.add(t),e=this.GetAddedPolygonesAndMaybeExtendActiveRectangle();for(const i of e)this.VisibilityGraph.AddHole(i.Polyline)}e==null||e.length===0?(this.targetVV!=null&&this.VisibilityGraph.RemoveVertex(this.targetVV),this.CalculateEdgeTargetVisibilityGraph(t)):(this.RemovePointVisibilityGraphs(),new Ei(e,this.activePolygons,this.VisibilityGraph).run(),Bi(this.activePolygons,e),this.CalculateEdgeTargetVisibilityGraph(t),this.CalculateSourcePortVisibilityGraph())}RemovePointVisibilityGraphs(){this.targetVV!=null&&this.VisibilityGraph.RemoveVertex(this.targetVV),this.sourceVV!=null&&this.VisibilityGraph.RemoveVertex(this.sourceVV)}CalculateEdgeTargetVisibilityGraph(t){this.targetVV=bi.CalculatePointVisibilityGraph(Array.from(this.GetActivePolylines()),this.VisibilityGraph,t,Ai.Tangent)}CalculateSourcePortVisibilityGraph(){this.sourceVV=bi.CalculatePointVisibilityGraph(Array.from(this.GetActivePolylines()),this.VisibilityGraph,this.StartPointOfEdgeRouting,Ai.Tangent)}TakeBoundaryPortOutsideOfItsLoosePolyline(t,e,i){const s=t.value(e);let n=t.leftDerivative(e).normalize().add(t.rightDerivative(e).normalize()).normalize();c.getTriangleOrientation(ct.PointInsideOfConvexCurve(t),s,s.add(n))==D.Counterclockwise&&(n=n.mul(-1)),n=n.rotate(Math.PI/2);const o=i.boundingBox.diagonal;let a=N.mkPP(s,s.add(n.mul(o)));const h=w.intersectionOne(a,i,!1).x;let u=n.mul(h.sub(s).length/2);for(;;){a=N.mkPP(s,h.add(u));let d=!1;for(const m of ct.IntersectionsOfLineAndRectangleNodeOverPolylineLR(a,this.ObstacleCalculator.RootOfLooseHierarchy))if(m.seg1!==i){u=u.div(1.5),d=!0;break}if(!d)break}return a.end}static PointInsideOfConvexCurve(t){return t.value(0).add(t.value(1.5)).div(2)}*GetActivePolylines(){for(const t of this.activePolygons)yield t.Polyline}GetAddedPolygonesAndMaybeExtendActiveRectangle(){const t=this.activeRectangle,e=new Array;let i;do{i=!1;for(const s of this.ObstacleCalculator.RootOfLooseHierarchy.GetNodeItemsIntersectingRectangle(this.activeRectangle))this.alreadyAddedOrExcludedPolylines.has(s)||(t.addRec(s.boundingBox),e.push(new Pe(s)),this.alreadyAddedOrExcludedPolylines.add(s),i=!0);i&&(this.activeRectangle=t)}while(i);return e}PolylineSegmentIntersectsTightHierarchy(t,e){return this.PolylineIntersectsPolyRectangleNodeOfTightHierarchyPPR(t,e,this.ObstacleCalculator.RootOfTightHierarchy)}PolylineIntersectsPolyRectangleNodeOfTightHierarchyPPR(t,e,i){return this.PolylineIntersectsPolyRectangleNodeOfTightHierarchy(N.mkPP(t,e),i)}PolylineIntersectsPolyRectangleNodeOfTightHierarchy(t,e){if(!t.boundingBox.intersects(e.irect))return!1;if(e.UserData!=null){for(const i of w.getAllIntersections(t,e.UserData,!1))if(i.seg1!==this.SourceTightPolyline&&i.seg1!==this.TargetTightPolyline||(i.seg1===this.SourceTightPolyline&&this.SourcePort)instanceof F||(i.seg1===this.TargetTightPolyline&&this.TargetPort)instanceof F)return!0;return!1}return this.PolylineIntersectsPolyRectangleNodeOfTightHierarchy(t,e.Left)||this.PolylineIntersectsPolyRectangleNodeOfTightHierarchy(t,e.Right)}static IntersectionsOfLineAndRectangleNodeOverPolylineLR(t,e){const i=new Array;return ct.IntersectionsOfLineAndRectangleNodeOverPolyline(t,e,i),i}static IntersectionsOfLineAndRectangleNodeOverPolyline(t,e,i){if(e!=null&&t.boundingBox.intersects(e.irect)){if(e.UserData!=null){Bi(i,w.getAllIntersections(t,e.UserData,!0));return}ct.IntersectionsOfLineAndRectangleNodeOverPolyline(t,e.Left,i),ct.IntersectionsOfLineAndRectangleNodeOverPolyline(t,e.Right,i)}}LineCanBeAcceptedForRouting(t){const e=this.SourcePort instanceof Ue,i=this.TargetPort instanceof Ue;if(!e&&!this.targetIsInsideOfSourceTightPolyline&&!this.InsideOfTheAllowedConeOfBoundaryPort(t.end,this.SourcePort)||!i&&this.TargetPort!=null&&!this.sourceIsInsideOfTargetTightPolyline&&!this.InsideOfTheAllowedConeOfBoundaryPort(t.start,this.TargetPort))return!1;const s=ct.IntersectionsOfLineAndRectangleNodeOverPolylineLR(t,this.ObstacleCalculator.RootOfTightHierarchy);for(const n of s)if(n.seg1!==this.SourceTightPolyline&&n.seg1!==this.targetTightPolyline)return!1;return!0}InsideOfTheAllowedConeOfBoundaryPort(t,e){const i=e.Curve,s=ut.CurveIsClockwise(i,ct.PointInsideOfConvexCurve(i)),n=e.Location,o=this.GetPointOnTheRightBoundaryPortConeSide(n,i,s,e.Parameter),a=this.GetPointOnTheLeftBoundaryPortConeSide(n,i,s,e.Parameter);return c.getTriangleOrientation(n,o,t)!==D.Clockwise&&c.getTriangleOrientation(n,t,a)!==D.Clockwise}GetPointOnTheRightBoundaryPortConeSide(t,e,i,s){const n=i?e.rightDerivative(s):e.leftDerivative(s).neg();return t.add(n.rotate(this.EnteringAngleBound))}GetPointOnTheLeftBoundaryPortConeSide(t,e,i,s){const n=i?e.leftDerivative(s).neg():e.rightDerivative(s);return t.add(n.rotate(-this.EnteringAngleBound))}SmoothenCorners(t){let e=t.headSite,i={b:null,c:null};for(;i=w.findCorner(e);)e=this.SmoothOneCorner(e,i.c,i.b)}SmoothOneCorner(t,e,i){let o=.5,a,h,u;t.prev==null?(u=2,h=1):e.next==null?(u=1,h=2):u=h=1;do a=w.createBezierSeg(o*u,o*h,t,i,e),i.previouisBezierCoefficient=o*u,i.nextBezierCoefficient=o*h,o/=1.5;while(d()>this.loosePadding&&o>.01);return o*=1.5,o<.5&&o>.01&&(o=.5*(o+o*1.5),a=w.createBezierSeg(o*u,o*h,t,i,e),d()>this.loosePadding&&(i.previouisBezierCoefficient=o*u,i.nextBezierCoefficient=o*h)),i;function d(){const m=a.closestParameter(i.point);return i.point.sub(a.value(m)).length}}TryToRemoveInflectionsAndCollinearSegments(t){let e=!0;const i={s:null};for(;e;)for(e=!1,i.s=t.headSite;i.s!=null&&i.s.next!=null;i.s=i.s.next)i.s.turn*i.s.next.turn<0&&(e=this.TryToRemoveInflectionEdge(i)||e)}TryToRemoveInflectionEdge(t){if(!this.ObstacleCalculator.ObstaclesIntersectLine(t.s.prev.point,t.s.next.point)){const e=t.s.prev,i=t.s.next;return e.next=i,i.prev=e,t.s=e,!0}if(!this.ObstacleCalculator.ObstaclesIntersectLine(t.s.prev.point,t.s.next.next.point)){const e=t.s.prev,i=t.s.next.next;return e.next=i,i.prev=e,t.s=e,!0}if(!this.ObstacleCalculator.ObstaclesIntersectLine(t.s.point,t.s.next.next.point)){const e=t.s.next.next;return t.s.next=e,e.prev=t.s,!0}return!1}GetShortestPolyline(t,e){this.CleanTheGraphForShortestPath();const s=new cn(this.visibilityGraph,t,e).GetPath(this.UseEdgeLengthMultiplier);if(s==null)return null;let n=st.mkFromPoints(Array.from(s).map(o=>o.point)).RemoveCollinearVertices();return this.pathOptimizer&&(this.pathOptimizer.run(n),n=this.pathOptimizer.poly),n}CleanTheGraphForShortestPath(){this.visibilityGraph.ClearPrevEdgesTable()}get OverlapsDetected(){return this.ObstacleCalculator.OverlapsDetected}get TightHierarchy(){return this.ObstacleCalculator.RootOfTightHierarchy}set TightHierarchy(t){this.ObstacleCalculator.RootOfTightHierarchy=t}get LooseHierarchy(){return this.ObstacleCalculator.RootOfLooseHierarchy}set LooseHierarchy(t){this.ObstacleCalculator.RootOfLooseHierarchy=t}CalculateObstacles(){this.ObstacleCalculator=new ut(this.Obstacles,this.TightPadding,this.LoosePadding,this.IgnoreTightPadding),this.ObstacleCalculator.Calculate()}static constructorANNNB(t,e,i,s,n){const o=new ct(null);return o.IgnoreTightPadding=n,o.EnteringAngleBound=80*(Math.PI/180),o.TightPadding=e,o.LoosePadding=i,s>0?(Mt.assert(s>Math.PI/180),Mt.assert(s<=90*(Math.PI/180)),o.UseSpanner=!0,o.ExpectedProgressSteps=yi.GetTotalSteps(s)):o.ExpectedProgressSteps=t.length,o.ConeSpannerAngle=s,o.Obstacles=t,o.CalculateObstacles(),o}RouteEdgeToLocation(t){this.TargetPort=new Ue(null,t),this.TargetTightPolyline=null,this.TargetLoosePolyline=null;const e=new we(null);let i=N.mkPP(this.SourcePort.Location,t);if(this.LineCanBeAcceptedForRouting(i)){this._polyline=new st,this._polyline.addPoint(i.start),this._polyline.addPoint(i.end);const s=Y.mkFromPoints(this._polyline);return e.curve=s.createCurve(),e}return this.SourcePort instanceof F&&(i=N.mkPP(this.StartPointOfEdgeRouting,t),ct.IntersectionsOfLineAndRectangleNodeOverPolylineLR(i,this.ObstacleCalculator.RootOfTightHierarchy).length==0)?(this._polyline=new st,this._polyline.addPoint(this.SourcePort.Location),this._polyline.addPoint(i.start),this._polyline.addPoint(i.end),e.curve=Y.mkFromPoints(this._polyline).createCurve(),e):(this.ExtendVisibilityGraphToLocation(t),this._polyline=this.GetShortestPolyline(this.sourceVV,this.targetVV),this.SourcePort instanceof F&&this._polyline.PrependPoint(this.SourcePort.Location),e.curve=Y.mkFromPoints(this._polyline).createCurve(),e)}RouteEdgeToPort(t,e,i,s){return this.ObstacleCalculator.IsEmpty()?this.sourcePort!=null&&this.targetPort!=null?(s.smoothedPolyline=this.SmoothedPolylineFromTwoPoints(this.sourcePort.Location,this.targetPort.Location),N.mkPP(this.sourcePort.Location,this.targetPort.Location)):null:(this.TargetPort=t,this.TargetTightPolyline=ct.GetFirstHitPolyline(t.Location,this.ObstacleCalculator.RootOfTightHierarchy),t instanceof F?this.RouteEdgeToBoundaryPort(e,i,s):this.RouteEdgeToFloatingPortOfNode(e,i,s))}SmoothedPolylineFromTwoPoints(t,e){return this._polyline=new st,this._polyline.addPoint(t),this._polyline.addPoint(e),Y.mkFromPoints(this._polyline)}RouteEdgeToFloatingPortOfNode(t,e,i){return this.sourcePort instanceof Ue?this.RouteFromFloatingPortToFloatingPort(t,e,i):this.RouteFromBoundaryPortToFloatingPort(t,e,i)}RouteFromBoundaryPortToFloatingPort(t,e,i){const s=this.SourcePort.Location,n=this.targetPort.Location;let o=N.mkPP(s,n);if(this.LineCanBeAcceptedForRouting(o))return i.smoothedPolyline=this.SmoothedPolylineFromTwoPoints(o.start,o.end),o;if(!this.targetIsInsideOfSourceTightPolyline){const h=this.TakeBoundaryPortOutsideOfItsLoosePolyline(this.SourcePort.Curve,this.SourcePort.Parameter,this.SourceLoosePolyline);if(o=N.mkPP(h,n),this.LineAvoidsTightHierarchyLP(o,t))return i.smoothedPolyline=this.SmoothedPolylineFromTwoPoints(o.start,o.end),o}this.ExtendVisibilityGraphToLocationOfTargetFloatingPort(t),this._polyline=this.GetShortestPolyline(this.sourceVV,this.targetVV);const a=this.SourceTightPolyline;return this.targetIsInsideOfSourceTightPolyline||(this.SourceTightPolyline=null),this.SourceTightPolyline=a,this._polyline.PrependPoint(s),this.SmoothCornersAndReturnCurve(e,i)}SmoothCornersAndReturnCurve(t,e){return e.smoothedPolyline=Y.mkFromPoints(this._polyline),t&&this.SmoothenCorners(e.smoothedPolyline),e.smoothedPolyline.createCurve()}RouteFromFloatingPortToFloatingPort(t,e,i){return this.ExtendVisibilityGraphToLocationOfTargetFloatingPort(t),this._polyline=this.GetShortestPolyline(this.sourceVV,this.targetVV),this._polyline==null?null:(i.smoothedPolyline=Y.mkFromPoints(this._polyline),this.SmoothCornersAndReturnCurve(e,i))}TryShortcutPolyPoint(t){return this.LineAvoidsTightHierarchyLPP(N.mkPP(t.point,t.next.next.point),this.SourceTightPolyline,this.targetTightPolyline)?(t.next=t.next.next,t.next.prev=t,!0):!1}ExtendVisibilityGraphToLocationOfTargetFloatingPort(t){this.VisibilityGraph==null&&(this.VisibilityGraph=new Xt);let e=null;const i=this.targetPort.Location;if(!this.activeRectangle.contains(i)){this.activeRectangle.isEmpty?this.activeRectangle=X.mkPP(this.SourcePort.Location,i):this.activeRectangle.add(i),e=this.GetAddedPolygonesAndMaybeExtendActiveRectangle();for(const s of e)this.VisibilityGraph.AddHole(s.Polyline)}e==null?(this.targetVV!=null&&this.VisibilityGraph.RemoveVertex(this.targetVV),this.CalculateEdgeTargetVisibilityGraphForFloatingPort(i,t),this.sourceVV==null&&this.CalculateSourcePortVisibilityGraph()):(this.RemovePointVisibilityGraphs(),new Ei(e,this.activePolygons,this.VisibilityGraph).run(),Bi(this.activePolygons,e),this.CalculateEdgeTargetVisibilityGraphForFloatingPort(i,t),this.CalculateSourcePortVisibilityGraph())}CalculateEdgeTargetVisibilityGraphForFloatingPort(t,e){this.UseSpanner?this.targetVV=this.AddTransientVisibilityEdgesForPort(t,e):this.targetVV=bi.CalculatePointVisibilityGraph(this.GetActivePolylinesWithException(e),this.VisibilityGraph,t,Ai.Tangent)}AddTransientVisibilityEdgesForPort(t,e){let i=this.GetVertex(t);if(i!=null)return i;if(i=this.visibilityGraph.AddVertexP(t),e!=null)for(const s of e)this.visibilityGraph.AddEdgeF(t,s,(n,o)=>new li(n,o));else i=bi.CalculatePointVisibilityGraph(this.GetActivePolylines(),this.VisibilityGraph,t,Ai.Tangent);return i}GetVertex(t){let e=this.visibilityGraph.FindVertex(t);return e==null&&this.LookForRoundedVertices&&(e=this.visibilityGraph.FindVertex(c.RoundPoint(t))),e}*GetActivePolylinesWithException(t){for(const e of this.activePolygons)e.Polyline!==t&&(yield e.Polyline)}RouteEdgeToBoundaryPort(t,e,i){return this.TargetLoosePolyline=t,this.sourcePort instanceof Ue?this.RouteFromFloatingPortToBoundaryPort(e,i):this.RouteFromBoundaryPortToBoundaryPort(e,i)}RouteFromBoundaryPortToBoundaryPort(t,e){const i=this.SourcePort.Location;let s;const n=this.targetPort.Location;let o=N.mkPP(i,n);if(this.LineCanBeAcceptedForRouting(o))this._polyline=new st,this._polyline.addPoint(o.start),this._polyline.addPoint(o.end),e.smoothedPolyline=this.SmoothedPolylineFromTwoPoints(o.start,o.end),s=Y.mkFromPoints(this._polyline).createCurve();else{const a=this.TakeBoundaryPortOutsideOfItsLoosePolyline(this.targetPort.Curve,this.targetPort.Parameter,this.TargetLoosePolyline);if(o=N.mkPP(i,a),this.InsideOfTheAllowedConeOfBoundaryPort(a,this.SourcePort)&&this.LineAvoidsTightHierarchyLP(o,this._sourceTightPolyline))this._polyline=new st,this._polyline.addPoint(o.start),this._polyline.addPoint(o.end),this._polyline.addPoint(n),s=this.SmoothCornersAndReturnCurve(t,e);else if(o=N.mkPP(this.StartPointOfEdgeRouting,n),this.InsideOfTheAllowedConeOfBoundaryPort(this.StartPointOfEdgeRouting,this.TargetPort)&&this.LineAvoidsTightHierarchy(o))this._polyline=new st,this._polyline.addPoint(i),this._polyline.addPoint(o.start),this._polyline.addPoint(o.end),s=this.SmoothCornersAndReturnCurve(t,e);else{let h;if(h=N.IntersectPPPP(i,this.StartPointOfEdgeRouting,n,a))this._polyline=new st,this._polyline.addPoint(i),this._polyline.addPoint(h),this._polyline.addPoint(n),s=this.SmoothCornersAndReturnCurve(t,e);else if(c.closeDistEps(this.StartPointOfEdgeRouting,a))this._polyline=new st,this._polyline.addPoint(i),this._polyline.addPoint(a),this._polyline.addPoint(n),s=this.SmoothCornersAndReturnCurve(t,e);else if(this.LineAvoidsTightHierarchy(N.mkPP(this.StartPointOfEdgeRouting,a)))this._polyline=new st,this._polyline.addPoint(i),this._polyline.addPoint(this.StartPointOfEdgeRouting),this._polyline.addPoint(a),this._polyline.addPoint(n),s=this.SmoothCornersAndReturnCurve(t,e);else{this.ExtendVisibilityGraphToTargetBoundaryPort(a),this._polyline=this.GetShortestPolyline(this.sourceVV,this.targetVV);const u={tmpTargetTight:null},d=this.HideSourceTargetTightsIfNeeded(u);this.RecoverSourceTargetTights(d,u.tmpTargetTight),this._polyline.PrependPoint(i),this._polyline.addPoint(n),s=this.SmoothCornersAndReturnCurve(t,e)}}}return s}RecoverSourceTargetTights(t,e){this.SourceTightPolyline=t,this.TargetTightPolyline=e}HideSourceTargetTightsIfNeeded(t){const e=this.SourceTightPolyline;return t.tmpTargetTight=this.TargetTightPolyline,this.TargetTightPolyline=null,this.SourceTightPolyline=null,e}LineAvoidsTightHierarchy(t){return ct.IntersectionsOfLineAndRectangleNodeOverPolylineLR(t,this.ObstacleCalculator.RootOfTightHierarchy).length===0}RouteFromFloatingPortToBoundaryPort(t,e){const i=this.targetPort.Location;let s;if(this.InsideOfTheAllowedConeOfBoundaryPort(this.sourcePort.Location,this.targetPort)&&(s=N.mkPP(this.SourcePort.Location,i),this.LineCanBeAcceptedForRouting(s)))return e.smoothedPolyline=this.SmoothedPolylineFromTwoPoints(s.start,s.end),s;const n=this.TakeBoundaryPortOutsideOfItsLoosePolyline(this.TargetPort.Curve,this.TargetPort.Parameter,this.TargetLoosePolyline);if(s=N.mkPP(this.SourcePort.Location,n),this.LineAvoidsTightHierarchyLP(s,this._sourceTightPolyline))return this._polyline=st.mkFromPoints([s.start,s.end,i]),e.smoothedPolyline=Y.mkFromPoints(this._polyline),e.smoothedPolyline.createCurve();this.ExtendVisibilityGraphToTargetBoundaryPort(n),this._polyline=this.GetShortestPolyline(this.sourceVV,this.targetVV),this._polyline.addPoint(i);const o={smoothedPolyline:null};return this.SmoothCornersAndReturnCurve(t,o)}LineAvoidsTightHierarchyLP(t,e){let i=!0;for(const s of ct.IntersectionsOfLineAndRectangleNodeOverPolylineLR(t,this.ObstacleCalculator.RootOfTightHierarchy))if(s.seg1!==e){i=!1;break}return i}LineAvoidsTightHierarchyLPP(t,e,i){let s=!0;for(const n of ct.IntersectionsOfLineAndRectangleNodeOverPolylineLR(t,this.ObstacleCalculator.RootOfTightHierarchy))if(!(n.seg1===e||n.seg1===i)){s=!1;break}return s}LineAvoidsTightHierarchyPPPP(t,e,i,s){return this.LineAvoidsTightHierarchyLPP(N.mkPP(t,e),i,s)}ExtendVisibilityGraphToTargetBoundaryPort(t){let e=null;if(this.VisibilityGraph==null&&(this.VisibilityGraph=new Xt),!this.activeRectangle.contains(t)||!this.activeRectangle.containsRect(this.TargetLoosePolyline.boundingBox)){this.activeRectangle.isEmpty?(this.activeRectangle=this.TargetLoosePolyline.boundingBox.clone(),this.activeRectangle.add(this.SourcePort.Location),this.activeRectangle.add(this.StartPointOfEdgeRouting),this.activeRectangle.add(t)):(this.activeRectangle.add(t),this.activeRectangle.addRec(this.TargetLoosePolyline.boundingBox)),e=this.GetAddedPolygonesAndMaybeExtendActiveRectangle();for(const i of e)this.VisibilityGraph.AddHole(i.Polyline)}e==null?(this.targetVV!=null&&this.VisibilityGraph.RemoveVertex(this.targetVV),this.CalculateEdgeTargetVisibilityGraph(t)):(this.RemovePointVisibilityGraphs(),new Ei(e,this.activePolygons,this.VisibilityGraph).run(),Bi(this.activePolygons,e),this.CalculateEdgeTargetVisibilityGraph(t),this.CalculateSourcePortVisibilityGraph())}GetHitLoosePolyline(t){return this.ObstacleCalculator.IsEmpty()||this.ObstacleCalculator.RootOfLooseHierarchy==null?null:ct.GetFirstHitPolyline(t,this.ObstacleCalculator.RootOfLooseHierarchy)}static GetFirstHitPolyline(t,e){const i=ct.GetFirstHitRectangleNode(t,e);return i?i.UserData:null}static GetFirstHitRectangleNode(t,e){return e==null?null:e.FirstHitNodeWithPredicate(t,(i,s)=>w.PointRelativeToCurveLocation(i,s)!==at.Outside?Nt.Stop:Nt.Continue)}Clean(){this.TargetPort=null,this.SourcePort=null,this.SourceTightPolyline=null,this.SourceLoosePolyline=null,this.TargetLoosePolyline=null,this.targetTightPolyline=null,this.VisibilityGraph=null,this.targetVV=null,this.sourceVV=null,this.activePolygons=[],this.alreadyAddedOrExcludedPolylines.clear(),this.activeRectangle.setToEmpty()}SetSourcePortAndSourceLoosePolyline(t,e){this.SourceLoosePolyline=e,this.sourcePort=t,this.sourcePort!=null&&(this.SourceTightPolyline=ct.GetFirstHitPolyline(this.sourcePort.Location,this.ObstacleCalculator.RootOfTightHierarchy),this.sourcePort instanceof Ue?(this.alreadyAddedOrExcludedPolylines.add(this.SourceLoosePolyline),this.StartPointOfEdgeRouting=this.SourcePort.Location):this.StartPointOfEdgeRouting=this.TakeBoundaryPortOutsideOfItsLoosePolyline(this.SourcePort.Curve,this.sourcePort.Parameter,this.SourceLoosePolyline))}run(){this.CalculateWholeTangentVisibilityGraph()}CalculateWholeTangentVisibilityGraph(){this.VisibilityGraph=new Xt,this.CalculateWholeVisibilityGraphOnExistingGraph()}CalculateWholeVisibilityGraphOnExistingGraph(){this.activePolygons=Array.from(this.AllPolygons());for(const e of this.ObstacleCalculator.LooseObstacles)this.VisibilityGraph.AddHole(e);let t;this.UseSpanner?t=new yi(this.ObstacleCalculator.LooseObstacles,this.VisibilityGraph):t=new Ei(new Array,this.activePolygons,this.visibilityGraph),t.run()}RouteSplineFromPortToPortWhenTheWholeGraphIsReady(t,e,i,s){const n=t instanceof Ue&&e instanceof F||t instanceof Wt;if(n){const a=t;t=e,e=a}this.sourcePort=t,this.targetPort=e,this.FigureOutSourceTargetPolylinesAndActiveRectangle();let o=this.GetEdgeGeomByRouting(i,s);return o==null?null:(this.targetVV=null,this.sourceVV=null,n&&(o=o.reverse()),o)}GetEdgeGeomByRouting(t,e){this.sourceIsInsideOfTargetTightPolyline=this.TargetTightPolyline==null||w.PointRelativeToCurveLocation(this.sourcePort.Location,this.TargetTightPolyline)===at.Inside;let i;if(this.sourcePort instanceof F){const s=this.sourcePort;this.StartPointOfEdgeRouting=this.targetIsInsideOfSourceTightPolyline?s.Location:this.TakeBoundaryPortOutsideOfItsLoosePolyline(s.Curve,s.Parameter,this.SourceLoosePolyline),this.CalculateSourcePortVisibilityGraph();const n={smoothedPolyline:null};this.targetPort instanceof F?i=this.RouteFromBoundaryPortToBoundaryPort(t,n):i=this.RouteFromBoundaryPortToFloatingPort(this.targetLoosePolyline,t,n)}else this.targetPort instanceof Ue?(this.ExtendVisibilityGraphFromFloatingSourcePort(),i=this.RouteFromFloatingPortToFloatingPort(this.targetLoosePolyline,t,e)):i=this.RouteFromFloatingPortToAnywherePort(this.targetPort.LoosePolyline,t,e,this.targetPort);return i}RouteFromFloatingPortToAnywherePort(t,e,i,s){return s.Curve.boundingBox.contains(this.sourcePort.Location)?(this.sourceVV=this.GetVertex(this.sourcePort.Location),this._polyline=this.GetShortestPolylineToMulitpleTargets(this.sourceVV,Array.from(this.Targets(t))),this._polyline==null?null:(this.FixLastPolylinePointForAnywherePort(s),s.HookSize>0&&this.BuildHook(s),this.SmoothCornersAndReturnCurve(e,i))):(i.smoothedPolyline=null,null)}BuildHook(t){const e=t.Curve,i=yt.mkFullEllipseNNP(t.HookSize,t.HookSize,this._polyline.end),s=w.getAllIntersections(e,i,!0);c.getTriangleOrientation(s[0].x,this._polyline.end,this._polyline.endPoint.prev.point)==D.Counterclockwise&&s.reverse();const n=this._polyline.end.sub(this._polyline.endPoint.prev.point).normalize(),o=e.derivative(s[0].par0).normalize(),a=o.dot(n);if(Math.abs(a)<.2)this.ExtendPolyline(o,s[0],n,t);else{const h=e.derivative(s[1].par0).normalize();h.dot(n)<a?this.ExtendPolyline(h,s[1],n,t):this.ExtendPolyline(o,s[0],n,t)}}ExtendPolyline(t,e,i,s){let n=t.rotate(Math.PI/2);n.dot(i)<0&&(n=n.neg());const o=e.x.add(n.mul(s.HookSize));let a;(a=c.lineLineIntersection(o,o.add(t),this._polyline.end,this._polyline.end.add(i)))&&(this._polyline.addPoint(a),this._polyline.addPoint(o),this._polyline.addPoint(e.x))}FixLastPolylinePointForAnywherePort(t){for(;;){const e=this.GetLastPointInsideOfCurveOnPolyline(t.Curve);e.next.next=null,this._polyline.endPoint=e.next;let i=e.next.point.sub(e.point);i=i.normalize().mul(t.Curve.boundingBox.diagonal);const s=i.rotate(t.AdjustmentAngle*-1),n=i.rotate(t.AdjustmentAngle),o=w.intersectionOne(t.Curve,N.mkPP(e.point,e.point.add(s)),!0),a=w.intersectionOne(t.Curve,N.mkPP(e.point,e.point.add(n)),!0);if(o==null||a==null)return;const h=ct.GetTrimmedCurveForHookingUpAnywhere(t.Curve,e,o,a),u=h.value(h.closestParameter(e.point));if(!this.LineAvoidsTightHierarchyLPP(N.mkPP(e.point,u),this.SourceTightPolyline,null)){const d=w.intersectionOne(t.Curve,N.mkPP(e.point,e.next.point),!1);if(d==null)return;this._polyline.endPoint.point=d.x;break}if(this._polyline.endPoint.point=u,e.prev==null||!this.TryShortcutPolyPoint(e.prev))break}}static GetTrimmedCurveForHookingUpAnywhere(t,e,i,s){const n=c.getTriangleOrientation(s.x,i.x,e.point)===D.Clockwise,o=i.par0,a=s.par0;let h,u,d;return n?o<a?t.trim(o,a):(u=t.trim(o,t.parEnd),h=t.trim(t.parStart,a),d=new w,d.addSegs([u,h])):a<o?t.trim(a,o):(u=t.trim(a,t.parEnd),h=t.trim(t.parStart,o),d=new w,d.addSegs([u,h]))}GetLastPointInsideOfCurveOnPolyline(t){for(let e=this._polyline.endPoint.prev;e!=null;e=e.prev)if(e.prev==null||w.PointRelativeToCurveLocation(e.point,t)===at.Inside)return e;throw new Error}GetShortestPolylineToMulitpleTargets(t,e){this.CleanTheGraphForShortestPath();const s=new as(t,e,this.VisibilityGraph).GetPath();if(s==null)return null;const n=new st;for(const o of s)n.addPoint(o.point);return n.RemoveCollinearVertices()}Targets(t){return Array.from(t).map(e=>this.visibilityGraph.FindVertex(e))}ExtendVisibilityGraphFromFloatingSourcePort(){const t=this.sourcePort;this.StartPointOfEdgeRouting=t.Location,this.UseSpanner?this.sourceVV=this.AddTransientVisibilityEdgesForPort(this.sourcePort.Location,this.SourceLoosePolyline):this.sourceVV=bi.CalculatePointVisibilityGraph(Array.from(this.GetActivePolylines()).filter(e=>e!==this.SourceLoosePolyline),this.VisibilityGraph,this.StartPointOfEdgeRouting,Ai.Tangent)}FigureOutSourceTargetPolylinesAndActiveRectangle(){let t=this.sourcePort.Curve.value(this.sourcePort.Curve.parStart);this._sourceTightPolyline=ct.GetFirstHitPolyline(t,this.ObstacleCalculator.RootOfTightHierarchy),this.SourceLoosePolyline=ct.GetFirstHitPolyline(t,this.ObstacleCalculator.RootOfLooseHierarchy),t=this.targetPort.Curve.value(this.targetPort.Curve.parStart),this.targetTightPolyline=ct.GetFirstHitPolyline(t,this.ObstacleCalculator.RootOfTightHierarchy),this.targetLoosePolyline=ct.GetFirstHitPolyline(t,this.ObstacleCalculator.RootOfLooseHierarchy),this.activeRectangle=X.mkPP(new c(Number.NEGATIVE_INFINITY,Number.POSITIVE_INFINITY),new c(Number.POSITIVE_INFINITY,Number.NEGATIVE_INFINITY))}*AllPolygons(){for(const t of this.ObstacleCalculator.LooseObstacles)yield new Pe(t)}GetVisibilityGraph(){return this.VisibilityGraph}AddActivePolygons(t){Bi(this.activePolygons,t)}ClearActivePolygons(){this.activePolygons=[]}}class Bt{toJSON(){let t="{";return this.tipPosition&&(t+='"tipPosition": '+this.tipPosition.toJSON()),t+="}",t}clone(){const t=new Bt;return t.length=this.length,t.width=this.width,t.tipPosition=this.tipPosition,t}constructor(){this.length=Bt.defaultArrowheadLength,this.width=0,this.length=Bt.defaultArrowheadLength}static calculateArrowheads(t){if(t.sourceArrowhead==null&&t.targetArrowhead==null)return!0;const e=Bt.findTrimStartForArrowheadAtSource(t);if(e==null)return!1;const i=Bt.findTrimEndForArrowheadAtTarget(t);if(i==null||e>i-C.intersectionEpsilon||w.closeIntersectionPoints(t.curve.value(e),t.curve.value(i)))return!1;const s=t.curve.trim(e,i);return s==null?!1:(t.sourceArrowhead!=null&&(t.sourceArrowhead.tipPosition=t.curve.start),t.targetArrowhead!=null&&(t.targetArrowhead.tipPosition=t.curve.end),t.curve=s,!0)}static getIntersectionsWithArrowheadCircle(t,e,i){const s=yt.mkFullEllipseNNP(e,e,i);return w.getAllIntersections(s,t,!0)}static findTrimEndForArrowheadAtTarget(t){const e=C.distanceEpsilon*C.distanceEpsilon;let i=t.curve.parEnd;if(t.targetArrowhead==null||t.targetArrowhead.length<=C.distanceEpsilon)return i;const s=t.curve;let n=t.targetArrowhead.length,o,a,h=10;do{if(h--,h===0)return;a=Bt.getIntersectionsWithArrowheadCircle(s,n,s.end),i=a.length!==0?Math.max(...a.map(u=>u.par1)):s.parEnd,o=t.curve.value(i),n/=2}while(o.sub(s.start).lengthSquared<e||a.length===0);return i}static findTrimStartForArrowheadAtSource(t){if(t.sourceArrowhead==null||t.sourceArrowhead.length<=C.distanceEpsilon)return t.curve.parStart;const e=C.distanceEpsilon*C.distanceEpsilon;let i=t.sourceArrowhead.length,s;const n=t.curve;let o,a=10,h;for(;--a>0;){if(o=Bt.getIntersectionsWithArrowheadCircle(n,i,n.start),o.length===0)return n.parStart;if(h=Math.min(...o.map(u=>u.par1)),s=o.filter(u=>u.par1===h)[0].x,s.sub(n.end).lengthSquared>=e)return h;i/=2}}static trimSplineAndCalculateArrowheads(t,e,i){return Bt.trimSplineAndCalculateArrowheadsII(t,t.source.boundaryCurve,t.target.boundaryCurve,e,i)}static trimSplineAndCalculateArrowheadsII(t,e,i,s,n){if(t.curve=w.trimEdgeSplineWithNodeBoundaries(e,i,s,n),t.curve==null)return!1;if((t.sourceArrowhead==null||t.sourceArrowhead.length<C.distanceEpsilon)&&(t.targetArrowhead==null||t.targetArrowhead.length<C.distanceEpsilon))return!0;let o=!1;const a=t.sourceArrowhead!=null?t.sourceArrowhead.length:0,h=t.targetArrowhead!=null?t.targetArrowhead.length:0,u=t.curve.end.sub(t.curve.start).length;t.sourceArrowhead!=null&&(t.sourceArrowhead.length=Math.min(u,a)),t.targetArrowhead!=null&&(t.targetArrowhead.length=Math.min(u,h));let d=10;for(;(t.sourceArrowhead!=null&&t.sourceArrowhead.length>C.intersectionEpsilon||t.targetArrowhead!=null&&t.targetArrowhead.length>C.intersectionEpsilon)&&!o&&(o=Bt.calculateArrowheads(t),o||(t.sourceArrowhead!=null&&(t.sourceArrowhead.length*=.5),t.targetArrowhead!=null&&(t.targetArrowhead.length*=.5)),d--,d!==0););return o||(t.sourceArrowhead!=null&&(t.sourceArrowhead.tipPosition=s.start),t.targetArrowhead!=null&&(t.targetArrowhead.tipPosition=s.end)),t.sourceArrowhead!=null&&(t.sourceArrowhead.length=a),t.targetArrowhead!=null&&(t.targetArrowhead.length=h),o}static createBigEnoughSpline(t){const e=t.source.center;let i=t.target.center;const s=i.sub(e),n=s.length;let o;n<.001?(o=new c(1,0),i=e.add(o.rotate(Math.PI/2))):o=s.rotate(Math.PI/2);let a=1;t.sourceArrowhead!=null&&(a+=t.sourceArrowhead.length),t.targetArrowhead!=null&&(a+=t.targetArrowhead.length),o=o.normalize().mul(1.5*a);for(let h=1;h<1e4;h=h*2){const u=w.createBezierSegN(e,i,o,h);if(Bt.trimSplineAndCalculateArrowheadsII(t,t.source.boundaryCurve,t.target.boundaryCurve,u,!1))return}Bt.createEdgeCurveWithNoTrimming(t,e,i)}static createEdgeCurveWithNoTrimming(t,e,i){const s=i.sub(e).normalize();let n=e,o=i;const a=t.targetArrowhead;a!=null&&(a.tipPosition=i,o=i.sub(s.mul(a.length)));const h=t.sourceArrowhead;h!=null&&(h.tipPosition=e,n=e.add(s.mul(h.length))),t.curve=N.mkPP(n,o)}}Bt.defaultArrowheadLength=5;class ls{constructor(){this.m=new Map}clear(){this.m.clear()}get size(){return this.m.size}set(t,e){this.m.set(dn(t),e)}delete(t){this.m.delete(dn(t))}has(t){return this.m.has(dn(t))}getPP(t,e){return this.get(new fe(t,e))}get(t){return this.m.get(dn(t))}*keys(){for(const t of this.m.keys())yield Vr(t)}*[Symbol.iterator](){for(const[t,e]of this.m)yield[Vr(t),e]}*values(){yield*this.m.values()}}function Vr(l){const t=l.split(" "),e=t[0],i=t[1];let s=e.split(",");const n=new c(Number(s[0]),Number(s[1]));s=i.split(",");const o=new c(Number(s[0]),Number(s[1]));return new fe(n,o)}function Ao(l,t){return[Wr(l),Wr(t)].sort().join(" ")}function dn(l){return Ao(l.first,l.second)}function Wr(l){return l.x.toString()+","+l.y.toString()}class xe{static GetShapes(t,e=Array.from(t.shallowEdges)){const i=new Map;Hr(t,i);for(const s of e){let n=i.get(s.source);n&&s.sourcePort!=null&&n.Ports.add(s.sourcePort),n=i.get(s.target),n&&s.targetPort!=null&&n.Ports.add(s.targetPort)}return Array.from(i.values())}static CreateShapeWithCenterPort(t){const e=new hn(t),i=ke.mk(()=>t.boundaryCurve,()=>t.center);e.Ports.add(i);for(const s of t.inEdges())xe.FixPortAtTarget(i,s);for(const s of t.outEdges())xe.FixPortAtSource(i,s);for(const s of t.selfEdges())xe.FixPortAtSource(i,s),xe.FixPortAtTarget(i,s);return e}static CreateShapeWithClusterBoundaryPort(t){const e=new hn(t),i=Ie.mk(()=>t.boundaryCurve,()=>t.center);e.Ports.add(i);let s;for(const n of t.inEdges())n.EdgeToAncestor()===Si.ToAncestor?(s==null&&(s=new Wt(()=>t.boundaryCurve)),n.targetPort=s):xe.FixPortAtTarget(i,n);for(const n of t.outEdges())n.EdgeToAncestor()===Si.FromAncestor?(s==null&&(s=new Wt(()=>t.boundaryCurve)),n.sourcePort=s):xe.FixPortAtSource(i,n);for(const n of t.selfEdges())xe.FixPortAtSource(i,n),xe.FixPortAtTarget(i,n);return e}static FixPortAtSource(t,e){e!=null&&e.sourcePort==null&&(e.sourcePort=t)}static FixPortAtTarget(t,e){e!=null&&e.targetPort==null&&(e.targetPort=t)}}function Hr(l,t){for(const e of l.shallowNodes)if(e instanceof Gt){const i=xe.CreateShapeWithClusterBoundaryPort(e);t.set(e,i);const s=e;if(!s.isCollapsed){Hr(s,t);for(const n of s.shallowNodes)i.AddChild(t.get(n))}}else t.set(e,xe.CreateShapeWithCenterPort(e))}class hs{isEmpty(){if(this.arrayOfMaps.length===0)return!0;for(const t of this.arrayOfMaps)if(t.size>0)return!1;return!0}set(t,e,i){let s=this.arrayOfMaps[t];s===void 0&&(this.arrayOfMaps[t]=s=new Map),s.set(e,i)}setPair(t,e){this.set(t.x,t.y,e)}delete(t,e){if(t<0||t>=this.arrayOfMaps.length)return;const i=this.arrayOfMaps[t];i!==void 0&&(i.delete(e),i.size===0&&(this.arrayOfMaps[t]=void 0))}has(t,e){if(t<0||t>=this.arrayOfMaps.length)return!1;const i=this.arrayOfMaps[t];return i===void 0?!1:i.has(e)}get(t,e){if(t<0||t>=this.arrayOfMaps.length)return null;const i=this.arrayOfMaps[t];return i===void 0?null:i.get(e)}getI(t){return this.get(t.x,t.y)}constructor(){this.arrayOfMaps=new Array}*keys(){for(let t=0;t<this.arrayOfMaps.length;t++){const e=this.arrayOfMaps[t];if(e!==void 0)for(const i of e)yield new Et(t,i[0])}}*keyValues(){for(let t=0;t<this.arrayOfMaps.length;t++){const e=this.arrayOfMaps[t];if(e!==void 0)for(const i of e)yield[new Et(t,i[0]),i[1]]}}*values(){for(let t=0;t<this.arrayOfMaps.length;t++){const e=this.arrayOfMaps[t];if(e!==void 0)for(const i of e)yield i[1]}}get size(){let t=0;for(let e=0;e<this.arrayOfMaps.length;e++){const i=this.arrayOfMaps[e];i!==void 0&&(t+=i.size)}return t}}var wi;(function(l){l[l.NotVisited=0]="NotVisited",l[l.InStack=1]="InStack",l[l.Visited=2]="Visited"})(wi||(wi={}));class p{constructor(t,e){this.v=t,this.i=e}}class S{static getFeedbackSetWithConstraints(t,e){throw new Error("Method not implemented.")}static push(t,e,i,s){e[i]=wi.InStack,t.push(new p(i,s))}static getFeedbackSet(t){const e=new hs;if(t==null||t.nodeCount===0)return[];const i=new Array(t.nodeCount).fill(wi.NotVisited);for(let s=0;s<t.nodeCount;s++){if(i[s]===wi.Visited)continue;const n=new Ut.B;let o=0;for(S.push(n,i,s,o);n.size>0;){const a=n.pop();s=a.v,i[s]=wi.Visited,o=a.i;let h=t.outEdges[s];for(;o<h.length;o++){const u=h[o];if(u.source===u.target)continue;const d=i[u.target];d===wi.InStack?e.set(u.source,u.target,u):d===wi.NotVisited&&(S.push(n,i,s,o+1),s=u.target,i[u.target]=wi.Visited,h=t.outEdges[s],o=-1)}}}return Array.from(e.values())}}class x{constructor(){this.isEmpty=!0}AddValue(t){this.isEmpty?(this.max=t,this.min=t,this.isEmpty=!1):t<this.min?this.min=t:t>this.max&&(this.max=t)}get length(){return this.max-this.min}static sign(t){return t>C.distanceEpsilon?1:t<-C.distanceEpsilon?-1:0}}class I{SetActiveState(t,e){this.IsActive=t,this.VectorIndex=e,this.IsActive?(this.Left.ActiveConstraintCount++,this.Right.ActiveConstraintCount++):(this.Left.ActiveConstraintCount--,this.Right.ActiveConstraintCount--)}SetVectorIndex(t){this.VectorIndex=t}Reinitialize(){this.IsActive=!1,this.IsUnsatisfiable=!1,this.ClearDfDv()}UpdateGap(t){this.Gap=t}static constructorVVNB(t,e,i,s){const n=new I(t);return n.Left=t,n.Right=e,n.Gap=i,n.IsEquality=s,n.Lagrangian=0,n.IsActive=!1,n}constructor(t){this.Right=t,this.Left=t}ToString(){return ue.Qf.format(" Cst: [{0}] [{1}] {2} {3:F5} vio {4:F5} Lm {5:F5}/{6:F5} {7}actv",this.Left,this.Right,this.IsEquality?"==":">=",this.Gap,this.Violation,this.Lagrangian,this.Lagrangian*2,this.IsActive?"+":this.IsUnsatisfiable?"!":"-")}get Violation(){return this.Left.ActualPos*this.Left.Scale+(this.Gap-this.Right.ActualPos*this.Right.Scale)}ClearDfDv(){this.Lagrangian=0}CompareTo(t){let e=this.Left.CompareTo(t.Left);return e===0&&(e=this.Right.CompareTo(t.Right)),e===0&&(e=k(this.Gap,t.Gap)),e}}class G{static constructorDCVV(t,e,i,s){const n=new G(e);return n.Set(t,e,i,s),n}constructor(t){this.ConstraintToEval=t,this.Depth=-1}Set(t,e,i,s){return this.Parent=t,this.ConstraintToEval=e,this.VariableToEval=i,this.VariableDoneEval=s,this.Depth=0,this.ChildrenHaveBeenPushed=!1,e.Lagrangian=0,this}get IsLeftToRight(){return this.VariableToEval===this.ConstraintToEval.Right}toString(){return ue.Qf.format("{0} {1}{2} - {3}{4} ({5})","",this.IsLeftToRight?"":"*",this.ConstraintToEval.Left.Name,this.IsLeftToRight?"*":"",this.ConstraintToEval.Right.Name,this.Depth)}}class z{constructor(t,e){this.Constraint=t,this.IsForward=e}}class nt{constructor(t,e){this.Variables=new Array,t!=null&&this.AddVariable(t),this.allConstraints=e}toString(){return ue.Qf.format("[Block: nvars = {0} refpos = {1:F5} scale = {2:F5}]",this.Variables.length,this.ReferencePos,this.Scale)}ComputeDfDv(t){this.allConstraints.DfDvStack=new Ut.B;const e=new I(t);this.dfDvDummyParentNode=new G(e);const i=this.GetDfDvNode(this.dfDvDummyParentNode,e,t,null);for(this.allConstraints.DfDvStack.push(i);;){const s=this.allConstraints.DfDvStack.top,n=this.allConstraints.DfDvStack.length;if(!s.ChildrenHaveBeenPushed){s.ChildrenHaveBeenPushed=!0;for(const o of s.VariableToEval.LeftConstraints)if(o.IsActive&&o.Right!==s.VariableDoneEval){const a=this.GetDfDvNode(s,o,o.Right,s.VariableToEval);o.Right.ActiveConstraintCount===1?this.ProcessDfDvLeafNodeDirectly(a):this.PushDfDvNode(a)}for(const o of s.VariableToEval.RightConstraints)if(o.IsActive&&o.Left!==s.VariableDoneEval){const a=this.GetDfDvNode(s,o,o.Left,s.VariableToEval);o.Left.ActiveConstraintCount===1?this.ProcessDfDvLeafNodeDirectly(a):this.PushDfDvNode(a)}if(this.allConstraints.DfDvStack.length>n)continue}if(this.allConstraints.DfDvStack.pop(),this.ProcessDfDvLeafNode(s),s===i)break}}ProcessDfDvLeafNode(t){const e=t.VariableToEval.DfDv;t.IsLeftToRight?(t.ConstraintToEval.Lagrangian=t.ConstraintToEval.Lagrangian+e,t.Parent.ConstraintToEval.Lagrangian=t.Parent.ConstraintToEval.Lagrangian+t.ConstraintToEval.Lagrangian):(t.ConstraintToEval.Lagrangian=(t.ConstraintToEval.Lagrangian+e)*-1,t.Parent.ConstraintToEval.Lagrangian=t.Parent.ConstraintToEval.Lagrangian-t.ConstraintToEval.Lagrangian),this.CheckForConstraintPathTarget(t),this.Debug_CheckForViolatedActiveConstraint(t.ConstraintToEval),this.allConstraints.RecycleDfDvNode(t)}Debug_CheckForViolatedActiveConstraint(t){t.Violation>this.allConstraints.SolverParameters.GapTolerance}ProcessDfDvLeafNodeDirectly(t){this.ProcessDfDvLeafNode(t)}GetDfDvNode(t,e,i,s){const n=this.allConstraints.DfDvRecycleStack.size>0?this.allConstraints.DfDvRecycleStack.pop().Set(t,e,i,s):G.constructorDCVV(t,e,i,s);return n.Depth=n.Parent.Depth+1,this.allConstraints.MaxConstraintTreeDepth<n.Depth&&(this.allConstraints.MaxConstraintTreeDepth=n.Depth),n}PushDfDvNode(t){this.PushOnDfDvStack(t)}AddVariableAndPushDfDvNode(t,e){t.push(e.VariableToEval),this.PushOnDfDvStack(e)}PushOnDfDvStack(t){this.allConstraints.DfDvStack.push(t)}CheckForConstraintPathTarget(t){if(this.pathTargetVariable===t.VariableToEval){for(;t.Parent!==this.dfDvDummyParentNode;)this.constraintPath.push(new z(t.ConstraintToEval,t.IsLeftToRight)),t=t.Parent;this.pathTargetVariable=null}}Expand(t){this.constraintPath==null&&(this.constraintPath=new Array),this.constraintPath=[],this.pathTargetVariable=t.Right,this.ComputeDfDv(t.Left);let e=null;if(this.constraintPath.length>0){for(const o of this.constraintPath)o.IsForward&&(e==null||o.Constraint.Lagrangian<e.Lagrangian)&&(o.Constraint.IsEquality||(e=o.Constraint));e!=null&&this.allConstraints.DeactivateConstraint(e)}if(this.constraintPath=[],this.pathTargetVariable=null,e==null){t.IsUnsatisfiable=!0,this.allConstraints.NumberOfUnsatisfiableConstraints++;return}const i=new Array;this.GetConnectedVariables(i,t.Right,t.Left);const s=t.Violation,n=i.length;for(let o=0;o<n;o++)i[o].OffsetInBlock=i[o].OffsetInBlock+s;this.allConstraints.ActivateConstraint(t),t.ClearDfDv(),this.UpdateReferencePos()}Split(t){if(t&&this.UpdateReferencePos(),this.Variables.length<2)return null;let e=null;this.ComputeDfDv(this.Variables[0]);let i=this.allConstraints.SolverParameters.Advanced.MinSplitLagrangianThreshold;const s=this.Variables.length;for(let n=0;n<s;n++)for(const o of this.Variables[n].LeftConstraints)o.IsActive&&!o.IsEquality&&o.Lagrangian<i&&(e=o,i=o.Lagrangian);return e==null?null:this.SplitOnConstraint(e)}SplitOnConstraint(t){this.allConstraints.DeactivateConstraint(t);let e=new nt(null,this.allConstraints);return this.TransferConnectedVariables(e,t.Right,t.Left),e.Variables.length>0?(this.UpdateReferencePos(),e.UpdateReferencePos()):e=null,e}AddVariable(t){this.Variables.push(t),t.Block=this,this.Variables.length===1?(this.Scale=t.Scale,this.ReferencePos=t.ActualPos,this.sumAd=t.ActualPos*t.Weight,this.sumAb=0,this.sumA2=t.Weight,t.OffsetInBlock=0):this.AddVariableToBlockSums(t)}UpdateReferencePos(){this.Scale=this.Variables[0].Scale,this.sumAd=0,this.sumAb=0,this.sumA2=0;const t=this.Variables.length;for(let e=0;e<t;e++)this.AddVariableToBlockSums(this.Variables[e]);this.UpdateReferencePosFromSums()}AddVariableToBlockSums(t){const e=this.Scale/t.Scale,i=t.OffsetInBlock/t.Scale,s=e*t.Weight;this.sumAd+=s*t.DesiredPos,this.sumAb+=s*i,this.sumA2+=s*e}UpdateReferencePosFromSums(){if(!(Number.isFinite(this.sumAd)&&Number.isFinite(this.sumAb)&&Number.isFinite(this.sumA2)))throw new Error("infinite numbers");this.ReferencePos=(this.sumAd-this.sumAb)/this.sumA2,this.UpdateVariablePositions()}UpdateVariablePositions(){const t=this.Scale*this.ReferencePos,e=this.Variables.length;for(let i=0;i<e;i++){const s=this.Variables[i];s.ActualPos=(t+s.OffsetInBlock)/s.Scale}}GetConnectedVariables(t,e,i){this.RecurseGetConnectedVariables(t,e,i)}RecurseGetConnectedVariables(t,e,i){this.allConstraints.DfDvStack=new Ut.B;const s=new I(e);for(this.dfDvDummyParentNode=new G(s),this.allConstraints.DfDvStack.push(this.GetDfDvNode(this.dfDvDummyParentNode,s,e,i)),t.push(e);this.allConstraints.DfDvStack.length>0;){const n=this.allConstraints.DfDvStack.top,o=this.allConstraints.DfDvStack.length;if(!n.ChildrenHaveBeenPushed){n.ChildrenHaveBeenPushed=!0;for(const a of n.VariableToEval.LeftConstraints)a.IsActive&&a.Right!==n.VariableDoneEval&&(a.Right.ActiveConstraintCount===1?t.push(a.Right):this.AddVariableAndPushDfDvNode(t,this.GetDfDvNode(n,a,a.Right,n.VariableToEval)));for(const a of n.VariableToEval.RightConstraints)a.IsActive&&a.Left!==n.VariableDoneEval&&(a.Left.ActiveConstraintCount===1?t.push(a.Left):this.AddVariableAndPushDfDvNode(t,this.GetDfDvNode(n,a,a.Left,n.VariableToEval)))}this.allConstraints.DfDvStack.length>o||this.allConstraints.RecycleDfDvNode(this.allConstraints.DfDvStack.pop())}}TransferConnectedVariables(t,e,i){this.GetConnectedVariables(t.Variables,e,i);const s=t.Variables.length;for(let o=0;o<s;o++)t.Variables[o].Block=t;let n=this.Variables.length-1;for(let o=this.Variables.length-1;o>=0;o--)this.Variables[o].Block===t&&(o<n&&(this.Variables[o]=this.Variables[n]),n--);if(this.Variables=this.Variables.slice(0,n+1),this.Variables.length===0){for(let o=0;o<s;o++){const a=t.Variables[o];this.Variables.push(a),a.Block=this}t.Variables=[]}}}class jt{get Count(){return this.Vector.length}item(t){return this.Vector[t]}constructor(){this.Vector=new Array}Add(t){t.VectorIndex=this.Vector.length,this.Vector.push(t)}Remove(t){const e=this.Vector[this.Vector.length-1];this.Vector[t.VectorIndex]=e,e.VectorIndex=t.VectorIndex,this.Vector.pop()}toString(){return this.Vector.toString()}}class Qt{constructor(){this.nextConstraintIndex=0,this.DfDvStack=new Ut.B,this.DfDvRecycleStack=new Ut.B}get IsEmpty(){return this.Vector==null}Create(t){this.Vector=new Array(t),this.firstActiveConstraintIndex=t}Add(t){t.SetVectorIndex(this.nextConstraintIndex),this.Vector[this.nextConstraintIndex++]=t}ActivateConstraint(t){this.firstActiveConstraintIndex--,this.SwapConstraint(t)}DeactivateConstraint(t){this.SwapConstraint(t),this.firstActiveConstraintIndex++}SwapConstraint(t){const e=this.Vector[this.firstActiveConstraintIndex];e.SetVectorIndex(t.VectorIndex),this.Vector[t.VectorIndex]=e,this.Vector[this.firstActiveConstraintIndex]=t,t.SetActiveState(!t.IsActive,this.firstActiveConstraintIndex)}Reinitialize(){if(this.Vector!=null){for(const t of this.Vector)t.Reinitialize();this.firstActiveConstraintIndex=this.Vector.length}}RecycleDfDvNode(t){this.DfDvRecycleStack.length<1024&&this.DfDvRecycleStack.push(t)}toString(){return this.Vector.toString()}}class $e{constructor(){this.GapTolerance=1e-4,this.QpscConvergenceEpsilon=1e-5,this.QpscConvergenceQuotient=1e-6,this.OuterProjectIterationsLimit=-1,this.InnerProjectIterationsLimit=-1,this.TimeLimit=-1,this.Advanced=new Se}Clone(){const t=this.MemberwiseClone();return t.Advanced=this.Advanced.Clone(),t}MemberwiseClone(){const t=new $e;return t.GapTolerance=this.GapTolerance,t.QpscConvergenceEpsilon=this.QpscConvergenceEpsilon,t.QpscConvergenceQuotient=this.QpscConvergenceQuotient,t.OuterProjectIterationsLimit=this.OuterProjectIterationsLimit,t.InnerProjectIterationsLimit=this.InnerProjectIterationsLimit,t.TimeLimit=this.TimeLimit,t}}class Se{constructor(){this.ForceQpsc=!1,this.ScaleInQpsc=!0,this.MinSplitLagrangianThreshold=-1e-7,this.UseViolationCache=!0,this.ViolationCacheMinBlocksDivisor=10,this.ViolationCacheMinBlocksCount=100}Clone(){const t=new Se;return t.ForceQpsc=this.ForceQpsc,t.ScaleInQpsc=this.ScaleInQpsc,t.MinSplitLagrangianThreshold=this.MinSplitLagrangianThreshold,t.UseViolationCache=this.UseViolationCache,t.ViolationCacheMinBlocksDivisor=this.ViolationCacheMinBlocksDivisor,t.ViolationCacheMinBlocksCount=this.ViolationCacheMinBlocksCount,t}}class $n{constructor(t){this.Variable=t,this.OrigWeight=t.Weight,this.OrigScale=t.Scale,this.OrigDesiredPos=this.Variable.DesiredPos}}class qr{constructor(t,e){this.Value=t,this.Column=e}}class Ye{constructor(t,e){this.newMatrixRow=new Array,this.previousFunctionValue=Number.MAX_VALUE,this.solverParameters=t,this.matrixQ=new Array(e).fill(0),this.vectorWiDi=new Array(e).fill(0),this.vectorQpscVars=new Array(e).fill(0),this.gradientVector=new Array(e).fill(0),this.vectorQg=new Array(e).fill(0),this.vectorPrevY=new Array(e).fill(0),this.vectorCurY=new Array(e).fill(0)}AddVariable(t){if(this.isFirstProjectCall=!0,this.vectorWiDi[t.Ordinal]=2*(t.Weight*t.DesiredPos)*-1,this.vectorPrevY[t.Ordinal]=t.Weight,t.Neighbors!=null)for(const e of t.Neighbors)this.vectorPrevY[t.Ordinal]=this.vectorPrevY[t.Ordinal]+e.Weight,this.vectorPrevY[e.Neighbor.Ordinal]=this.vectorPrevY[e.Neighbor.Ordinal]-e.Weight;for(let e=0;e<this.vectorPrevY.length;e++)this.vectorPrevY[e]!==0&&(this.newMatrixRow.push(new qr(this.vectorPrevY[e]*2,e)),this.vectorPrevY[e]=0);this.matrixQ[t.Ordinal]=Array.from(this.newMatrixRow),this.newMatrixRow=[],this.vectorQpscVars[t.Ordinal]=new $n(t),t.Weight=1}VariablesComplete(){for(const t of this.vectorQpscVars){const e=t.Variable;for(const i of this.matrixQ[e.Ordinal])i.Column===e.Ordinal&&(this.solverParameters.Advanced.ScaleInQpsc&&(e.Scale=1/Math.sqrt(Math.abs(i.Value)),Number.isFinite(e.Scale)||(e.Scale=1),e.Scale,this.vectorWiDi[e.Ordinal]=this.vectorWiDi[e.Ordinal]*e.Scale),this.vectorCurY[e.Ordinal]=e.ActualPos,e.DesiredPos=e.ActualPos)}if(this.solverParameters.Advanced.ScaleInQpsc)for(let t=0;t<this.matrixQ.length;t++){const e=this.matrixQ[t];for(let i=0;i<e.length;i++)e[i].Column===t?e[i].Value=1:e[i].Value=e[i].Value*(this.vectorQpscVars[t].Variable.Scale*this.vectorQpscVars[e[i].Column].Variable.Scale)}}PreProject(){if(this.isFirstProjectCall)for(const s of this.vectorQpscVars)this.vectorCurY[s.Variable.Ordinal]=s.Variable.ActualPos;if(this.MatrixVectorMultiply(this.vectorCurY,this.gradientVector),this.HasConverged())return!1;Ye.VectorVectorAdd(this.gradientVector,this.vectorWiDi,this.gradientVector);const t=Ye.VectorVectorMultiply(this.gradientVector,this.gradientVector);let e=0;if(t!==0&&(this.MatrixVectorMultiply(this.gradientVector,this.vectorQg),e=Ye.VectorVectorMultiply(this.vectorQg,this.gradientVector)),e===0)return!1;const i=t/e;Ye.VectorCopy(this.vectorPrevY,this.vectorCurY),Ye.VectorScaledVectorSubtract(this.vectorPrevY,i,this.gradientVector,this.vectorCurY);for(let s=0;s<this.vectorCurY.length;s++)this.vectorQpscVars[s].Variable.DesiredPos=this.vectorCurY[s];return!0}PostProject(){for(const i of this.vectorQpscVars)this.vectorCurY[i.Variable.Ordinal]=i.Variable.ActualPos;Ye.VectorVectorSubtract(this.vectorPrevY,this.vectorCurY,this.vectorCurY);const t=Ye.VectorVectorMultiply(this.gradientVector,this.vectorCurY);let e=0;if(t!==0){this.MatrixVectorMultiply(this.vectorCurY,this.vectorQg);const i=Ye.VectorVectorMultiply(this.vectorQg,this.vectorCurY);e=i===0?1:t/i,e>1?e=1:e<0&&(e=0)}return Ye.VectorScaledVectorSubtract(this.vectorPrevY,e,this.vectorCurY,this.vectorCurY),this.isFirstProjectCall=!1,e>0}QpscComplete(){for(const t of this.vectorQpscVars)t.Variable.Weight=t.OrigWeight,t.Variable.DesiredPos=t.OrigDesiredPos,this.solverParameters.Advanced.ScaleInQpsc&&(t.Variable.ActualPos=t.Variable.ActualPos*t.Variable.Scale,t.Variable.Scale=t.OrigScale);return this.previousFunctionValue}HasConverged(){const t=this.GetFunctionValue(this.vectorCurY);let e=!1;if(!this.isFirstProjectCall){const i=this.previousFunctionValue-t;let s=0;if(i!==0){const n=this.previousFunctionValue!==0?this.previousFunctionValue:t;s=Math.abs(i/n)}(Math.abs(i)<this.solverParameters.QpscConvergenceEpsilon||Math.abs(s)<this.solverParameters.QpscConvergenceQuotient)&&(e=!0)}return this.previousFunctionValue=t,e}GetFunctionValue(t){return Ye.VectorVectorMultiply(this.gradientVector,t)/2+Ye.VectorVectorMultiply(this.vectorWiDi,t)}static VectorVectorMultiply(t,e){let i=0;for(let s=0;s<t.length;s++)i=i+t[s]*e[s];return i}MatrixVectorMultiply(t,e){let i=0;for(const s of this.matrixQ){let n=0;for(const o of s)n=n+o.Value*t[o.Column];e[i++]=n}}static VectorVectorAdd(t,e,i){for(let s=0;s<t.length;s++)i[s]=t[s]+e[s]}static VectorVectorSubtract(t,e,i){for(let s=0;s<t.length;s++)i[s]=t[s]-e[s]}static VectorScaledVectorSubtract(t,e,i,s){for(let n=0;n<t.length;n++)s[n]=t[n]-e*i[n]}static VectorCopy(t,e){for(let i=0;i<e.length;i++)t[i]=e[i]}}class zr{constructor(){this.NumberOfUnsatisfiableConstraints=0,this.OuterProjectIterations=0,this.InnerProjectIterationsTotal=0,this.MinInnerProjectIterations=0,this.MaxInnerProjectIterations=0,this.MaxConstraintTreeDepth=0,this.GoalFunctionValue=0,this.TimeLimitExceeded=!1,this.OuterProjectIterationsLimitExceeded=!1,this.InnerProjectIterationsLimitExceeded=!1}get ExecutionLimitExceeded(){return this.TimeLimitExceeded||this.OuterProjectIterationsLimitExceeded||this.InnerProjectIterationsLimitExceeded}Clone(){const t=new zr;return t.GoalFunctionValue=this.GoalFunctionValue,t.InnerProjectIterationsLimitExceeded=this.InnerProjectIterationsLimitExceeded,t.InnerProjectIterationsTotal=this.InnerProjectIterationsTotal,t.MaxConstraintTreeDepth=this.MaxConstraintTreeDepth,t.OuterProjectIterations=this.OuterProjectIterations,t.OuterProjectIterationsLimitExceeded=this.OuterProjectIterationsLimitExceeded,t.AlgorithmUsed=this.AlgorithmUsed,t.NumberOfUnsatisfiableConstraints=this.NumberOfUnsatisfiableConstraints,t.MaxInnerProjectIterations=this.MaxInnerProjectIterations,t}}var Ur;(function(l){l[l.ProjectOnly=0]="ProjectOnly",l[l.QpscWithScaling=1]="QpscWithScaling",l[l.QpscWithoutScaling=2]="QpscWithoutScaling"})(Ur||(Ur={}));class fl{constructor(t,e){this.Neighbor=t,this.Weight=e}}class pl{get DfDv(){return 2*(this.Weight*(this.ActualPos-this.DesiredPos))/this.Scale}constructor(t,e,i,s,n){if(this.ActiveConstraintCount=0,s<=0)throw new Error("weight");if(n<=0)throw new Error("scale");let o=i*s;if(!Number.isFinite(o)||Number.isNaN(o))throw new Error("desiredPos");if(o=i*n,!Number.isFinite(o)||Number.isNaN(o))throw new Error("desiredPos");this.Ordinal=t,this.UserData=e,this.DesiredPos=i,this.Weight=s,this.Scale=n,this.OffsetInBlock=0,this.ActualPos=this.DesiredPos}Reinitialize(){this.ActiveConstraintCount=0,this.OffsetInBlock=0,this.ActualPos=this.DesiredPos}AddNeighbor(t,e){this.Neighbors==null&&(this.Neighbors=new Array),this.Neighbors.push(new fl(t,e))}toString(){return ue.Qf.format("{0} {1:F5} ({2:F5}) {3:F5} {4:F5}",this.Name,this.ActualPos,this.DesiredPos,this.Weight,this.Scale)}get Name(){return this.UserData==null?"-0-":this.UserData.toString()}SetConstraints(t,e){this.LeftConstraints=t,this.RightConstraints=e}CompareTo(t){return k(this.Ordinal,t.Ordinal)}}class Xn{get IsFull(){return this.numConstraints===Xn.MaxConstraints}Clear(){this.LowViolation=0,this.numConstraints=0,this.constraints||(this.constraints=new Array(Xn.MaxConstraints))}FilterBlock(t){this.LowViolation=Number.MAX_VALUE;const e=this.numConstraints>0;for(let i=this.numConstraints-1;i>=0;i--){const s=this.constraints[i];if(s.Left.Block===t||s.Right.Block===t||s.IsActive||s.IsUnsatisfiable)i<this.numConstraints-1&&(this.constraints[i]=this.constraints[this.numConstraints-1]),this.numConstraints--;else{const n=s.Left.ActualPos*s.Left.Scale+(s.Gap-s.Right.ActualPos*s.Right.Scale);n<this.LowViolation&&(this.LowViolation=n)}}return this.numConstraints===0&&(this.LowViolation=0),e}FindIfGreater(t){let e=null;for(let i=0;i<this.numConstraints;i++){const s=this.constraints[i],n=s.Left.ActualPos*s.Left.Scale+(s.Gap-s.Right.ActualPos*s.Right.Scale);n>t&&(t=n,e=s)}return e}Insert(t,e){let i=0,s=e,n=e;for(let o=0;o<this.numConstraints;o++){const a=this.constraints[o],h=a.Left.ActualPos*a.Left.Scale+(a.Gap-a.Right.ActualPos*a.Right.Scale);h<s?(n=s,i=o,s=h):h<n&&(n=h)}this.IsFull?(this.constraints[i]=t,this.LowViolation=n):(this.constraints[this.numConstraints++]=t,this.IsFull&&(this.LowViolation=s))}}Xn.MaxConstraints=20;class aa{constructor(t,e){this.NumberOfLeftConstraints=0,this.Constraints=t,this.NumberOfLeftConstraints=e}}class ml{constructor(){this.allBlocks=new jt,this.allConstraints=new Qt,this.numberOfConstraints=0,this.numberOfVariables=0,this.equalityConstraints=new Array,this.loadedVariablesAndConstraintLists=new Map,this.emptyConstraintList=new Array(0),this.updatedConstraints=new Array,this.violationCache=new Xn,this.violationCacheMinBlockCutoff=0,this.nextVariableOrdinal=0,this.solverParams=new $e,this.solverSolution=new zr}get IsQpsc(){return this.hasNeighbourPairs||this.solverParams.Advanced.ForceQpsc}AddVariableAN(t,e){return this.AddVariableANNN(t,e,1,1)}AddVariableANN(t,e,i){return this.AddVariableANNN(t,e,i,1)}AddVariableANNN(t,e,i,s){if(!this.allConstraints.IsEmpty)throw new Error("Cannot add Variables or Constraints once Solve() has been called");const n=new pl(this.nextVariableOrdinal++,t,e,i,s),o=new nt(n,this.allConstraints);return n.Block=o,this.allBlocks.Add(o),this.numberOfVariables++,this.loadedVariablesAndConstraintLists.set(n,new aa(new Array,0)),n}UpdateVariables(){for(const t of this.allBlocks.Vector)t.UpdateReferencePos()}get Variables(){return ws(this.allBlocks.Vector,t=>t.Variables)}get VariableCount(){return this.numberOfVariables}*Constraints(){if(this.allConstraints.IsEmpty)for(const t of this.loadedVariablesAndConstraintLists.keys()){const e=this.loadedVariablesAndConstraintLists.get(t);if(e.Constraints!=null){const i=e.Constraints.length;for(let s=0;s<i;s++){const n=e.Constraints[s];if(t===n.Left)return yield,n}}}else for(const t of this.allConstraints.Vector)yield t}get ConstraintCount(){return this.numberOfConstraints}AddEqualityConstraint(t,e,i){return this.AddConstraintVVNB(t,e,i,!0)}AddConstraintVVNB(t,e,i,s){if(!this.allConstraints.IsEmpty)throw new Error("Cannot add Variables or Constraints once Solve() has been called");if(t===e)throw new Error("Cannot add a constraint between a variable and itself");const n=this.loadedVariablesAndConstraintLists.get(t),o=this.loadedVariablesAndConstraintLists.get(e),a=I.constructorVVNB(t,e,i,s);return this.loadedVariablesAndConstraintLists.set(t,new aa(n.Constraints,n.NumberOfLeftConstraints+1)),n.Constraints.push(a),o.Constraints.push(a),this.numberOfConstraints++,s&&this.equalityConstraints.push(a),a}AddConstraint(t,e,i){return this.AddConstraintVVNB(t,e,i,!1)}SetConstraintUpdate(t,e){e!==t.Gap&&this.updatedConstraints.push([t,e])}AddNeighborPair(t,e,i){if(i<=0||Number.isNaN(i)||!Number.isFinite(i))throw new Error("relationshipWeight");if(t===e)throw new Error;t.AddNeighbor(e,i),e.AddNeighbor(t,i),this.hasNeighbourPairs=!0}Solve(){return this.SolvePar(null)}SolvePar(t){t&&(this.solverParams=t.Clone()),this.solverParams.OuterProjectIterationsLimit<0&&(this.solverParams.OuterProjectIterationsLimit=100*(Math.floor(Math.log2(this.numberOfVariables))+1)),this.solverParams.InnerProjectIterationsLimit<0&&(this.solverParams.InnerProjectIterationsLimit=this.numberOfConstraints*2+100*(Math.max(0,Math.floor(Math.log2(this.numberOfConstraints)))+1));const e=!this.allConstraints.IsEmpty;if(this.CheckForUpdatedConstraints(),this.solverSolution=new zr,this.solverSolution.MinInnerProjectIterations=Number.MAX_VALUE,this.allConstraints.MaxConstraintTreeDepth=0,this.allConstraints.SolverParameters=this.solverParams,this.numberOfConstraints===0){if(!this.IsQpsc)return this.solverSolution.Clone()}else e||this.SetupConstraints();return this.allConstraints.NumberOfUnsatisfiableConstraints=0,this.MergeEqualityConstraints(),this.IsQpsc?this.SolveQpsc():(this.SolveByStandaloneProject(),this.CalculateStandaloneProjectGoalFunctionValue()),this.solverSolution.MinInnerProjectIterations>this.solverSolution.MaxInnerProjectIterations&&(this.solverSolution.MinInnerProjectIterations=this.solverSolution.MaxInnerProjectIterations),this.solverSolution.NumberOfUnsatisfiableConstraints=this.allConstraints.NumberOfUnsatisfiableConstraints,this.solverSolution.MaxConstraintTreeDepth=this.allConstraints.MaxConstraintTreeDepth,this.solverSolution.Clone()}CheckForUpdatedConstraints(){if(this.updatedConstraints.length===0)return;let t=this.IsQpsc;for(const[e,i]of this.updatedConstraints){const s=e;if(s.UpdateGap(i),!t&&!s.IsEquality){this.SplitOnConstraintIfActive(s);continue}t=!0}this.updatedConstraints=[],t&&this.ReinitializeBlocks()}SplitOnConstraintIfActive(t){if(t.IsActive){const e=t.Left.Block.SplitOnConstraint(t);e!=null&&this.allBlocks.Add(e)}}SetupConstraints(){this.allConstraints.Create(this.numberOfConstraints);for(const t of this.loadedVariablesAndConstraintLists.keys()){const e=this.loadedVariablesAndConstraintLists.get(t),i=e.Constraints;let s=0,n=0,o=0;i!=null&&(s=i.length,n=e.NumberOfLeftConstraints,o=s-n);let a=this.emptyConstraintList;n!==0&&(a=new Array(n));let h=this.emptyConstraintList;o!==0&&(h=new Array(o)),t.SetConstraints(a,h);let u=0,d=0;for(let m=0;m<s;m++){const y=i[m];t===y.Left?a[u++]=y:h[d++]=y}for(const m of t.LeftConstraints)this.allConstraints.Add(m)}this.loadedVariablesAndConstraintLists.clear(),this.violationCacheMinBlockCutoff=Number.MAX_VALUE,this.solverParams.Advanced.UseViolationCache&&this.solverParams.Advanced.ViolationCacheMinBlocksDivisor>0&&(this.violationCacheMinBlockCutoff=Math.min(this.allBlocks.Count/this.solverParams.Advanced.ViolationCacheMinBlocksDivisor,this.solverParams.Advanced.ViolationCacheMinBlocksCount))}SolveByStandaloneProject(){for(;;){if(!this.RunProject())return;if(!this.SplitBlocks())break}}RunProject(){return this.solverSolution.OuterProjectIterations++,this.Project(),!this.CheckForLimitsExceeded()}CheckForLimitsExceeded(){return this.solverParams.OuterProjectIterationsLimit>0&&this.solverSolution.OuterProjectIterations>=this.solverParams.OuterProjectIterationsLimit?(this.solverSolution.OuterProjectIterationsLimitExceeded=!0,!0):!!this.solverSolution.InnerProjectIterationsLimitExceeded}CalculateStandaloneProjectGoalFunctionValue(){this.solverSolution.GoalFunctionValue=0;const t=this.allBlocks.Count;for(let e=0;e<t;e++){const i=this.allBlocks.item(e),s=i.Variables.length;for(let n=0;n<s;n++){const o=i.Variables[n];this.solverSolution.GoalFunctionValue+=o.Weight*(o.ActualPos*o.ActualPos),this.solverSolution.GoalFunctionValue-=2*(o.Weight*(o.DesiredPos*o.ActualPos))}}}SolveQpsc(){if(this.solverSolution.AlgorithmUsed=this.solverParams.Advanced.ScaleInQpsc?Ur.QpscWithScaling:Ur.QpscWithoutScaling,!this.QpscMakeFeasible())return;const t=new Ye(this.solverParams,this.numberOfVariables);for(const i of this.allBlocks.Vector)for(const s of i.Variables)t.AddVariable(s);t.VariablesComplete(),this.ReinitializeBlocks(),this.MergeEqualityConstraints();let e=!1;for(;!(!t.PreProject()&&!e||(e=this.SplitBlocks(),!this.RunProject())||!t.PostProject()&&!e););this.solverSolution.GoalFunctionValue=t.QpscComplete()}QpscMakeFeasible(){return this.RunProject()}ReinitializeBlocks(){const t=Array.from(this.allBlocks.Vector);this.allBlocks.Vector=[];for(const e of t)for(const i of e.Variables){i.Reinitialize();const s=new nt(i,this.allConstraints);this.allBlocks.Add(s)}this.allConstraints.Reinitialize(),this.violationCache.Clear()}MergeEqualityConstraints(){for(const t of this.equalityConstraints){if(t.Left.Block===t.Right.Block){Math.abs(t.Violation)>this.solverParams.GapTolerance&&(t.IsUnsatisfiable=!0,this.allConstraints.NumberOfUnsatisfiableConstraints++);continue}this.MergeBlocks(t)}}Project(){if(this.numberOfConstraints===0)return!1;this.violationCache.Clear(),this.lastModifiedBlock=null;let t=this.allBlocks.Count>this.violationCacheMinBlockCutoff,e=1;const i={maxViolation:0};let s=this.GetMaxViolatedConstraint(i,t);if(!s)return!1;for(;s;){if(s.Left.Block===s.Right.Block?(s.Left.Block.Expand(s),s.IsUnsatisfiable&&this.violationCache.Clear(),this.lastModifiedBlock=s.Left.Block):this.lastModifiedBlock=this.MergeBlocks(s),this.solverParams.InnerProjectIterationsLimit>0&&e>=this.solverParams.InnerProjectIterationsLimit){this.solverSolution.InnerProjectIterationsLimitExceeded=!0;break}t=this.allBlocks.Count>this.violationCacheMinBlockCutoff,t||this.violationCache.Clear(),e++;const n={maxViolation:0};s=this.GetMaxViolatedConstraint(n,t)}return this.solverSolution.InnerProjectIterationsTotal=this.solverSolution.InnerProjectIterationsTotal+e,this.solverSolution.MaxInnerProjectIterations<e&&(this.solverSolution.MaxInnerProjectIterations=e),this.solverSolution.MinInnerProjectIterations>e&&(this.solverSolution.MinInnerProjectIterations=e),!0}MergeBlocks(t){let e=t.Left.Block,i=t.Right.Block,s=t.Left.OffsetInBlock+(t.Gap-t.Right.OffsetInBlock);i.Variables.length>e.Variables.length&&(e=t.Right.Block,i=t.Left.Block,s=-s);const n=i.Variables.length;for(let o=0;o<n;o++){const a=i.Variables[o];a.OffsetInBlock+=s,e.AddVariable(a)}return e.UpdateReferencePosFromSums(),this.allConstraints.ActivateConstraint(t),this.allBlocks.Remove(i),e}SplitBlocks(){const t=new Array,e=this.allBlocks.Count;for(let s=0;s<e;s++){const o=this.allBlocks.item(s).Split(this.IsQpsc);o!=null&&t.push(o)}const i=t.length;for(let s=0;s<i;s++){const n=t[s];this.allBlocks.Add(n)}return t.length!==0}GetMaxViolatedConstraint(t,e){t.maxViolation=this.solverParams.GapTolerance;const i=this.SearchViolationCache(t.maxViolation);return i??this.SearchAllConstraints(t.maxViolation,e)}SearchViolationCache(t){let e=null;if(this.lastModifiedBlock==null)return;this.lastModifiedBlock.Variables.length<this.numberOfVariables+1&&this.violationCache.FilterBlock(this.lastModifiedBlock);const i=this.lastModifiedBlock.Variables.length;for(let n=0;n<i;n++){const o=this.lastModifiedBlock.Variables[n];for(const a of o.LeftConstraints)if(!a.IsActive&&!a.IsUnsatisfiable){const h=a.Left.ActualPos*a.Left.Scale+(a.Gap-a.Right.ActualPos*a.Right.Scale);V(h,t)&&(e!=null&&t>this.violationCache.LowViolation&&this.violationCache.Insert(e,t),t=a.Violation,e=a)}for(const a of o.RightConstraints)if(!a.IsActive&&!a.IsUnsatisfiable&&a.Left.Block!==this.lastModifiedBlock){const h=a.Left.ActualPos*a.Left.Scale+(a.Gap-a.Right.ActualPos*a.Right.Scale);V(h,t)&&(e!=null&&t>this.violationCache.LowViolation&&this.violationCache.Insert(e,t),t=h,e=a)}}const s=this.violationCache.FindIfGreater(t);return s!=null&&(e!=null&&t>this.violationCache.LowViolation&&this.violationCache.Insert(e,t),e=s),e}SearchAllConstraints(t,e){let i=null;this.violationCache.Clear();for(const s of this.allConstraints.Vector){if(s.IsActive)break;if(s.IsUnsatisfiable)continue;const n=s.Left.ActualPos*s.Left.Scale+(s.Gap-s.Right.ActualPos*s.Right.Scale);let o=null,a=0;V(n,t)&&(t>this.violationCache.LowViolation&&(o=i,a=t),t=n,i=s),e&&(o==null&&s!==i&&(!this.violationCache.IsFull||n>this.violationCache.LowViolation)&&(o=s,a=n),o!=null&&a>this.violationCache.LowViolation&&this.violationCache.Insert(o,a))}return i}}class Kn{constructor(){this.variables=new Map,this.fixedVars=new Map,this.FailToAdjustEpsilon=.001,this.InitSolver()}AddVariableWithIdealPositionNNN(t,e,i){this.variables.set(t,this.solver.AddVariableANN(t,e,i))}AddVariableWithIdealPositionNN(t,e){this.AddVariableWithIdealPositionNNN(t,e,1)}AddLeftRightSeparationConstraintNNNB(t,e,i,s){const n=this.GetVariable(t);if(n==null)return;const o=this.GetVariable(e);o!=null&&this.solver.AddConstraintVVNB(n,o,i,s)}AddLeftRightSeparationConstraintNNN(t,e,i){this.AddLeftRightSeparationConstraintNNNB(t,e,i,!1)}AddGoalTwoVariablesAreCloseNNN(t,e,i){const s=this.GetVariable(t);if(s==null)return;const n=this.GetVariable(e);n!=null&&this.solver.AddNeighborPair(s,n,i)}AddGoalTwoVariablesAreClose(t,e){this.AddGoalTwoVariablesAreCloseNNN(t,e,1)}GetVariable(t){return this.variables.get(t)}Solve(){this.SolveP(null)}SolveP(t){const e={executionLimitExceeded:!1};this.SolvePNS(t,e)}SolvePNS(t,e){let i;do{this.solution=null;let s=null;if(t!=null&&(s=t,s==null))throw new Error("parameters");this.solution=this.solver.SolvePar(s),e.executionLimitExceeded=this.solution.ExecutionLimitExceeded,i=this.AdjustConstraintsForMovedFixedVars()}while(i&&this.solution.ExecutionLimitExceeded===!1);return this.solution.ExecutionLimitExceeded===!1}AdjustConstraintsForMovedFixedVars(){const t=new Set;for(const[e,i]of this.fixedVars.entries())Kn.Close(i,this.GetVariableResolvedPosition(e))||t.add(e);return t.size===0?!1:this.AdjustConstraintsForMovedFixedVarSet(t)}static Close(t,e){return Math.abs(t-e)<5e-4}AdjustConstraintsForMovedFixedVarSet(t){for(;t.size>0;){let e;for(const i of t){e=i;break}if(!this.AdjustSubtreeOfFixedVar(e,t))return!1}return!0}AdjustSubtreeOfFixedVar(t,e){const i={successInAdjusting:!1},s=this.AdjustConstraintsOfNeighborsOfFixedVariable(t,i);if(!i.successInAdjusting||s.length===0)return!1;for(const n of s)e.delete(n);return!0}AdjustConstraintsOfNeighborsOfFixedVariable(t,e){const i=this.variables.get(t).Block.Variables,s=new x,n=new x;let o=1;for(const a of i)this.fixedVars.has(a.UserData)&&(s.AddValue(a.ActualPos),n.AddValue(a.DesiredPos),n.length>0&&(o=Math.max(o,s.length/n.length)));return o===1&&(o=2),e.successInAdjusting=this.FixActiveConstraints(i,o),i.map(a=>a.UserData)}FixActiveConstraints(t,e){let i=!1;for(const s of t)for(const n of s.LeftConstraints)n.IsActive&&(n.Gap>this.FailToAdjustEpsilon&&(i=!0),this.solver.SetConstraintUpdate(n,n.Gap/e));return i}GetVariableResolvedPosition(t){const e=this.GetVariable(t);return e==null?0:e.ActualPos}InitSolver(){this.solver=new ml,this.variables.clear()}AddFixedVariable(t,e){this.AddVariableWithIdealPositionNNN(t,e,Kn.FixedVarWeight),this.fixedVars.set(t,e)}ContainsVariable(t){return this.variables.has(t)}GetVariableIdealPosition(t){return this.variables.get(t).DesiredPos}get Solution(){return this.solution}}Kn.FixedVarWeight=1e9;class Pl{constructor(){this.lowBound=Number.NEGATIVE_INFINITY,this.upperBound=Number.POSITIVE_INFINITY}get Position(){return this.position}set Position(t){t<this.lowBound?this.position=this.lowBound:t>this.upperBound?this.position=this.upperBound:this.position=t}get LowBound(){return this.lowBound}set LowBound(t){this.lowBound=t}get UpperBound(){return this.upperBound}set UpperBound(t){this.upperBound=t}toString(){return this.lowBound+(" "+(this.Position+(" "+this.upperBound)))}}class Sl{constructor(t){this.idealPositions=new Map,this.varList=new Array,this.constraints=new Set,this.solverShell=new Kn,this.boundsToInt=new Map,this.varSepartion=t}SetLowBound(t,e){const i=this.Var(e);i.LowBound=Math.max(t,i.LowBound)}Var(t){return this.varList[t]}SetUpperBound(t,e){const i=this.Var(t);i.UpperBound=Math.min(e,i.UpperBound)}Solve(){this.SolveByRegularSolver()}SolveByRegularSolver(){this.CreateVariablesForBounds();for(let t=0;t<this.varList.length;t++){const e=this.varList[t];e.IsFixed?this.solverShell.AddFixedVariable(t,e.Position):(this.solverShell.AddVariableWithIdealPositionNN(t,this.idealPositions.get(t)),e.LowBound!==Number.NEGATIVE_INFINITY&&this.constraints.add(new Et(this.GetBoundId(e.LowBound),t)),e.UpperBound!==Number.POSITIVE_INFINITY&&this.constraints.add(new Et(t,this.GetBoundId(e.UpperBound))))}this.CreateGraphAndRemoveCycles();for(const t of this.graph.edges){let e=0;t.x<this.varList.length&&(e+=this.varList[t.x].Width),t.y<this.varList.length&&(e+=this.varList[t.y].Width),e/=2,this.solverShell.AddLeftRightSeparationConstraintNNN(t.x,t.y,this.varSepartion+e)}this.solverShell.Solve();for(let t=0;t<this.varList.length;t++)this.varList[t].Position=this.solverShell.GetVariableResolvedPosition(t)}GetBoundId(t){return this.boundsToInt.get(t)}CreateVariablesForBounds(){for(const t of this.varList)t.IsFixed||(t.LowBound!==Number.NEGATIVE_INFINITY&&this.RegisterBoundVar(t.LowBound),t.UpperBound!==Number.POSITIVE_INFINITY&&this.RegisterBoundVar(t.UpperBound))}RegisterBoundVar(t){if(!this.boundsToInt.has(t)){const e=this.varList.length+this.boundsToInt.size;this.boundsToInt.set(t,e),this.solverShell.AddFixedVariable(e,t)}}CreateGraphAndRemoveCycles(){this.graph=Qe(Array.from(this.constraints),this.varList.length+this.boundsToInt.size);const t=S.getFeedbackSet(this.graph);if(t!=null)for(const e of t)this.graph.removeEdge(e)}GetVariablePosition(t){return this.varList[t].Position}AddConstraint(t,e){this.constraints.add(new Et(t,e))}AddVariableNNNN(t,e,i,s){this.idealPositions.set(t,i),this.AddVariableNNBN(t,e,!1,s)}AddFixedVariable(t,e){this.AddVariableNNBN(t,e,!0,0)}AddVariableNNBN(t,e,i,s){const n=new Pl;n.Position=e,n.IsFixed=i,n.Width=s,this.varList.push(n)}}const _u={dumpDebugCurves:null};class wt{clone(){const t=new wt;return t.transparency=this.transparency,t.width=this.width,t.color=this.color,t.icurve=this.icurve.clone(),t.label=this.label,t.dashArray=this.dashArray,t.drawPN=this.drawPN,t}static mkDebugCurveTWCILD(t,e,i,s,n,o,a=!1){const h=new wt;return h.transparency=t,h.width=e,h.color=i,h.icurve=s,h.label=n,h.dashArray=o,h.drawPN=a,h}static mkDebugCurveTWCI(t,e,i,s){return wt.mkDebugCurveTWCILD(t,e,i,s,null,null)}static mkDebugCurveWCI(t,e,i){return wt.mkDebugCurveTWCI(255,t,e,i)}static mkDebugCurveCI(t,e){return wt.mkDebugCurveWCI(1,t,e)}static mkDebugCurveI(t){return wt.mkDebugCurveCI("Black",t)}}wt.colors=["DeepSkyBlue","IndianRed","Orange","Gold","DarkRed","Plum","Red","Violet","Indigo","Yellow","OrangeRed","Tomato","Purple","SaddleBrown","Green","Navy","Aqua","Pink","Bisque","Black","BlanchedAlmond","Blue","BlueViolet","Brown","Lime","BurlyWood","Chocolate","Coral","CornflowerBlue","Cornsilk","Crimson","Cyan","CadetBlue","Chartreuse","DarkBlue","DarkCyan","DarkGoldenrod","DarkGray","DarkGreen","DarkKhaki","DarkMagenta","DarkOliveGreen","DarkOrange","DarkOrchid","DarkSalmon","DarkSeaGreen","DarkSlateBlue","DarkSlateGray","DarkTurquoise","DarkViolet","DeepPink","DimGray","DodgerBlue","Firebrick","FloralWhite","ForestGreen","Fuchsia","CodeAnalysis","Gainsboro","GhostWhite","Goldenrod","Gray","GreenYellow","Honeydew","HotPink","Ivory","Lavender","LavenderBlush","LawnGreen","LemonChiffon","LightBlue","LightCoral","LightCyan","LightGoldenrodYellow","LightGray","LightGreen","LightPink","LightSalmon","LightSeaGreen","LightSkyBlue","LightSlateGray","LightSteelBlue","LightYellow","LimeGreen","Linen","Magenta","Maroon","MediumAquamarine","MediumBlue","MediumOrchid","MediumPurple","MediumSeaGreen","MediumSlateBlue","MediumSpringGreen","MediumTurquoise","MediumVioletRed","MidnightBlue","MintCream","MistyRose","Moccasin","NavajoWhite","OldLace","Olive","OliveDrab","Orchid","PaleGoldenrod","PaleGreen","PaleTurquoise","PaleVioletRed","PapayaWhip","PeachPuff","Peru","PowderBlue","RosyBrown","RoyalBlue","Salmon","SandyBrown","SeaGreen","CodeAnalysis","SeaShell","Sienna","Silver","SkyBlue","SlateBlue","SlateGray","Snow","SpringGreen","SteelBlue","Tan","Teal","Thistle","Transparent","Turquoise","Aquamarine","Azure","Beige","Wheat","White","WhiteSmoke","YellowGreen","Khaki","AntiqueWhite"];let yl=function(l,t){console.log("should be set from outside")};function tc(l){yl=l}class Cl extends ve{constructor(t,e){super(t,e),this.RightNeighbors=new Set,this.setOfLongestSegs=new Set,this.RightBound=Number.POSITIVE_INFINITY,this.LeftBound=Number.NEGATIVE_INFINITY,this.Direction=j.DirectionFromPointToPoint(t.point,e.point)}AddRightNeighbor(t){this.RightNeighbors.add(t)}get LongestNudgedSegments(){return this.setOfLongestSegs}AddLongestNudgedSegment(t){this.setOfLongestSegs.add(t)}BoundFromRight(t){t=Math.max(t,this.LeftBound),this.RightBound=Math.min(t,this.RightBound)}BoundFromLeft(t){t=Math.min(t,this.RightBound),this.LeftBound=Math.max(t,this.LeftBound)}}class Hi{constructor(t){this.Point=t}*GetEnumerator(){let t;for(t=this;t!=null;t=t.Next)yield t.Point}get X(){return this.Point.x}get Y(){return this.Point.y}InsertVerts(t,e,i){for(e--;t<e;e--)this.SetNewNext(i[e])}InsertVertsInReverse(t,e,i){for(t++;t<e;t++)this.SetNewNext(i[t])}SetNewNext(t){const e=new Hi(t),i=this.Next;this.Next=e,e.Next=i}}class jr{toString(){return this.Source+(" "+this.Target)}constructor(t,e){this.IsFixed=!1,this.Reversed=!1,this.index=-1,this.AxisEdge=t,this.Width=e}get LongestNudgedSegment(){return this.longestNudgedSegment}set LongestNudgedSegment(t){this.longestNudgedSegment=t,this.longestNudgedSegment!=null&&(this.longestNudgedSegment.AddEdge(this),this.AxisEdge.AddLongestNudgedSegment(this.longestNudgedSegment))}get Source(){return this.Reversed?this.AxisEdge.TargetPoint:this.AxisEdge.SourcePoint}get Target(){return this.Reversed?this.AxisEdge.SourcePoint:this.AxisEdge.TargetPoint}static VectorsAreParallel(t,e){return R(t.x*e.y-t.y*e.x,0)}static EdgesAreParallel(t,e){return jr.VectorsAreParallel(t.AxisEdge.TargetPoint.sub(t.AxisEdge.SourcePoint),e.AxisEdge.TargetPoint.sub(e.AxisEdge.SourcePoint))}get Direction(){return this.Reversed?j.OppositeDir(this.AxisEdge.Direction):this.AxisEdge.Direction}get Index(){return this.index}set Index(t){this.index=t}}class ye{get PathVisibilityGraph(){return this.pathVisibilityGraph}constructor(t){this.pathVisibilityGraph=new Xt,this.axisEdgesToPathOrders=new Map,this.OriginalPaths=t}GetOrder(){return this.FillTheVisibilityGraphByWalkingThePaths(),this.InitPathOrder(),this.OrderPaths(),this.axisEdgesToPathOrders}FillTheVisibilityGraphByWalkingThePaths(){for(const t of this.OriginalPaths)this.FillTheVisibilityGraphByWalkingPath(t)}FillTheVisibilityGraphByWalkingPath(t){const e=this.CreatePathEdgesFromPoints(s(),t.Width);let i=e.next();for(i.done||t.SetFirstEdge(i.value);(i=e.next()).done===!1;)t.AddEdge(i.value);function*s(){if(t.PathPoints instanceof Hi)for(let n=t.PathPoints;n!=null;n=n.Next)yield n.Point;else for(const n of t.PathPoints)yield n}}*CreatePathEdgesFromPoints(t,e){let i=t.next(),s=i.value;for(;!(i=t.next()).done;)yield this.CreatePathEdge(s,i.value,e),s=i.value}CreatePathEdge(t,e,i){switch(j.DirectionFromPointToPoint(t,e)){case v.East:case v.North:return new jr(this.GetAxisEdge(t,e),i);case v.South:case v.West:{const n=new jr(this.GetAxisEdge(e,t),i);return n.Reversed=!0,n}default:throw new Error("Not a rectilinear path")}}GetAxisEdge(t,e){return this.PathVisibilityGraph.AddEdgeF(t,e,(i,s)=>new Cl(i,s))}InitPathOrder(){for(const t of this.PathVisibilityGraph.Edges)this.axisEdgesToPathOrders.set(t,new Array);for(const t of this.OriginalPaths)for(const e of t.PathEdges())this.axisEdgesToPathOrders.get(e.AxisEdge).push(e)}OrderPaths(){for(const t of ye.WalkGraphEdgesInTopologicalOrderIfPossible(this.PathVisibilityGraph))this.OrderPathEdgesSharingEdge(t)}OrderPathEdgesSharingEdge(t){const e=this.PathOrderOfVisEdge(t);e.sort(ye.CompareTwoPathEdges);let i=0;for(const s of e)s.Index=i++}static CompareTwoPathEdges(t,e){if(t===e)return 0;const i=ye.CompareInDirectionStartingFromAxisEdge(t,e,t.AxisEdge,t.AxisEdge.Direction);return i!==0?i:-ye.CompareInDirectionStartingFromAxisEdge(t,e,t.AxisEdge,j.OppositeDir(t.AxisEdge.Direction))}static CompareInDirectionStartingFromAxisEdge(t,e,i,s){for(;;){if(t=ye.GetNextPathEdgeInDirection(t,i,s),t==null||(e=ye.GetNextPathEdgeInDirection(e,i,s),e==null))return 0;if(t.AxisEdge===e.AxisEdge){s=ye.FindContinuedDirection(i,s,t.AxisEdge),i=t.AxisEdge;const u=ye.GetExistingOrder(t,e);if(u===ye.NotOrdered)continue;return s===i.Direction?u:-u}const n=s===i.Direction?i.Target:i.Source,o=ye.OtherVertex(t.AxisEdge,n),a=ye.OtherVertex(e.AxisEdge,n),h=ye.ProjectionForCompare(i,s!==i.Direction);return k(h(o.point),h(a.point))}}static FindContinuedDirection(t,e,i){return t.Direction===e?i.Source===t.Target?i.Direction:j.OppositeDir(i.Direction):i.Source===t.Source?i.Direction:j.OppositeDir(i.Direction)}static OtherVertex(t,e){return t.Source===e?t.Target:t.Source}static ProjectionForCompare(t,e){return t.Direction===v.North?e?i=>-i.x:i=>i.x:e?i=>i.y:i=>-i.y}static GetNextPathEdgeInDirection(t,e,i){return e.Direction===i?t.Reversed?t.Prev:t.Next:t.Reversed?t.Next:t.Prev}static GetExistingOrder(t,e){const i=t.Index;if(i===-1)return ye.NotOrdered;const s=e.Index;return k(i,s)}PathOrderOfVisEdge(t){return this.axisEdgesToPathOrders.get(t)}static InitQueueOfSources(t,e,i){for(const s of i.Vertices()){const n=s.InEdgesLength();e.set(s,n),n===0&&t.enqueue(s)}}static*WalkGraphEdgesInTopologicalOrderIfPossible(t){const e=new Ge.o,i=new Map;for(ye.InitQueueOfSources(e,i,t);e.length>0;){const s=e.dequeue();for(const n of s.OutEdges){const o=i.get(n.Target);i.set(n.Target,o-1),o===1&&e.enqueue(n.Target),yield n}}}}ye.NotOrdered=Number.MAX_VALUE;class Al extends ai{constructor(t,e){super(),this.site=e,this.AxisEdge=t}get Site(){return this.site}}class la extends ai{constructor(t,e){super(),this.site=e,this.AxisEdge=t}get Site(){return this.site}}class El{get Edges(){return this.edges}AddEdge(t){this.UpPoint=t.TargetPoint,this.edges.add(t)}constructor(t){this.edges=new Set,this.Source=t}RemoveAxis(t){this.edges.delete(t)}IsEmpty(){return this.edges.size===0}}class qi extends vr{constructor(t,e,i,s,n){super(e,new j(t).ToPoint()),this.DirectionPerp=new j(t).Right.ToPoint(),this.PathOrders=s,this.xProjection=t===v.North?o=>o.x:o=>-o.y,this.edgeContainersTree=new Me((o,a)=>this.CompareAA(o,a)),this.SweepPole=j.VectorDirection(this.SweepDirection),this.AxisEdges=n,this.AxisEdgesToObstaclesTheyOriginatedFrom=i}FindFreeSpace(){this.InitTheQueueOfEvents(),this.ProcessEvents()}ProcessEvents(){for(;this.EventQueue.Count>0;)this.ProcessEvent(this.EventQueue.Dequeue())}ProcessEvent(t){t instanceof ts?this.ProcessVertexEvent(t):(this.Z=this.GetZP(t.Site),t instanceof la?this.ProcessLowEdgeEvent(t):this.ProcessHighEdgeEvent(t))}ProcessHighEdgeEvent(t){const e=t.AxisEdge;this.RemoveEdge(e),this.ConstraintEdgeWithObstaclesAtZ(e,e.Target.point)}ProcessLowEdgeEvent(t){const e=t.AxisEdge,i=this.GetOrCreateAxisEdgesContainer(e);i.item.AddEdge(e);const s=this.edgeContainersTree.previous(i);if(s!=null)for(const o of s.item.edges)for(const a of i.item.edges)this.TryToAddRightNeighbor(o,a);const n=this.edgeContainersTree.next(i);if(n!=null)for(const o of i.item.Edges)for(const a of n.item.edges)this.TryToAddRightNeighbor(o,a);this.ConstraintEdgeWithObstaclesAtZ(e,e.Source.point)}TryToAddRightNeighbor(t,e){this.ProjectionsOfEdgesOverlap(t,e)&&t.AddRightNeighbor(e)}ProjectionsOfEdgesOverlap(t,e){return this.SweepPole===v.North?!(t.TargetPoint.y<e.SourcePoint.y-C.distanceEpsilon||e.TargetPoint.y<t.SourcePoint.y-C.distanceEpsilon):!(t.TargetPoint.x<e.SourcePoint.x-C.distanceEpsilon||e.TargetPoint.x<t.SourcePoint.x-C.distanceEpsilon)}GetObstacleBoundaries(t){return this.Obstacles.map(e=>wt.mkDebugCurveWCI(1,t,e))}ConstraintEdgeWithObstaclesAtZ(t,e){this.ConstraintEdgeWithObstaclesAtZFromLeft(t,e),this.ConstraintEdgeWithObstaclesAtZFromRight(t,e)}ConstraintEdgeWithObstaclesAtZFromRight(t,e){const i=this.GetActiveSideFromRight(e);if(i==null||this.NotRestricting(t,i.item.Polyline))return;const s=this.ObstacleSideComparer.IntersectionOfSideAndSweepLine(i.item);t.BoundFromRight(s.dot(this.DirectionPerp))}GetActiveSideFromRight(t){return this.LeftObstacleSideTree.findFirst(e=>qi.PointToTheLeftOfLineOrOnLineLocal(t,e.Start,e.End))}ConstraintEdgeWithObstaclesAtZFromLeft(t,e){const i=this.GetActiveSideFromLeft(e);if(i==null||this.NotRestricting(t,i.item.Polyline))return;const s=this.ObstacleSideComparer.IntersectionOfSideAndSweepLine(i.item);t.BoundFromLeft(s.dot(this.DirectionPerp))}static PointToTheLeftOfLineOrOnLineLocal(t,e,i){return c.signedDoubledTriangleArea(t,e,i)>-qi.AreaComparisonEpsilon}static PointToTheRightOfLineOrOnLineLocal(t,e,i){return c.signedDoubledTriangleArea(e,i,t)<qi.AreaComparisonEpsilon}GetActiveSideFromLeft(t){return this.RightObstacleSideTree.findLast(e=>qi.PointToTheRightOfLineOrOnLineLocal(t,e.Start,e.End))}static EdgeMidPoint(t){return c.middle(t.SourcePoint,t.TargetPoint)}GetOrCreateAxisEdgesContainer(t){const e=t.Source.point,i=this.GetAxisEdgesContainerNode(e);return i??this.edgeContainersTree.insert(new El(e))}GetAxisEdgesContainerNode(t){const e=this.xProjection(t),i=this.edgeContainersTree.findFirst(s=>this.xProjection(s.Source)>=e-C.distanceEpsilon/2);return i!=null&&this.xProjection(i.item.Source)<=e+C.distanceEpsilon/2?i:null}ProcessVertexEvent(t){this.Z=this.GetZS(t),t instanceof Mi?this.ProcessLeftVertex(t,t.Vertex.nextOnPolyline):t instanceof P?this.ProcessRightVertex(t,t.Vertex.prevOnPolyline):(this.ProcessLeftVertex(t,t.Vertex.nextOnPolyline),this.ProcessRightVertex(t,t.Vertex.prevOnPolyline))}ProcessRightVertex(t,e){const i=t.Site;this.ProcessPrevSegmentForRightVertex(t,i);const s=e.point.sub(t.Site),n=s.dot(this.DirectionPerp),o=s.dot(this.SweepDirection);o<=C.distanceEpsilon?n>0&&o>=0?this.EnqueueEvent(new P(e)):this.RestrictEdgeContainerToTheRightOfEvent(t.Vertex):(this.InsertRightSide(new rs(t.Vertex)),this.EnqueueEvent(new P(e)),this.RestrictEdgeContainerToTheRightOfEvent(t.Vertex))}RestrictEdgeContainerToTheRightOfEvent(t){const e=t.point,i=this.xProjection(e),s=this.edgeContainersTree.findFirst(n=>i<=this.xProjection(n.Source));if(s!=null)for(const n of s.item.Edges)this.NotRestricting(n,t.polyline)||n.BoundFromLeft(this.DirectionPerp.dot(e))}NotRestricting(t,e){return this.AxisEdgesToObstaclesTheyOriginatedFrom.get(t)===e}ProcessPrevSegmentForRightVertex(t,e){const i=t.Vertex.nextOnPolyline.point;e.sub(i).dot(this.SweepDirection)>C.distanceEpsilon&&this.RemoveRightSide(new rs(t.Vertex.nextOnPolyline))}RemoveEdge(t){const e=this.GetAxisEdgesContainerNode(t.Source.point);e.item.RemoveAxis(t),e.item.IsEmpty()&&this.edgeContainersTree.deleteNodeInternal(e)}ProcessLeftVertex(t,e){const i=t.Site;this.ProcessPrevSegmentForLeftVertex(t,i);const s=e.point.sub(t.Site),n=s.dot(this.DirectionPerp),o=s.dot(this.SweepDirection);o<=C.distanceEpsilon?n<0&&o>=0&&this.EnqueueEvent(new Mi(e)):(this.InsertLeftSide(new ns(t.Vertex)),this.EnqueueEvent(new Mi(e))),this.RestrictEdgeFromTheLeftOfEvent(t.Vertex)}RestrictEdgeFromTheLeftOfEvent(t){const e=t.point,i=this.GetContainerNodeToTheLeftOfEvent(e);if(i!=null)for(const s of i.item.Edges)this.NotRestricting(s,t.polyline)||s.BoundFromRight(e.dot(this.DirectionPerp))}GetContainerNodeToTheLeftOfEvent(t){const e=this.xProjection(t);return this.edgeContainersTree.findLast(i=>this.xProjection(i.Source)<=e)}ProcessPrevSegmentForLeftVertex(t,e){const i=t.Vertex.prevOnPolyline.point;e.sub(i).dot(this.SweepDirection)>C.distanceEpsilon&&this.RemoveLeftSide(new ns(t.Vertex.prevOnPolyline))}InitTheQueueOfEvents(){this.InitQueueOfEvents();for(const t of this.AxisEdges)this.EnqueueEventsForEdge(t)}EnqueueEventsForEdge(t){this.EdgeIsParallelToSweepDir(t)&&(this.EnqueueEvent(qi.EdgeLowPointEvent(t,t.Source.point)),this.EnqueueEvent(qi.EdgeHighPointEvent(t,t.Target.point)))}EdgeIsParallelToSweepDir(t){return t.Direction===this.SweepPole||t.Direction===j.OppositeDir(this.SweepPole)}static EdgeHighPointEvent(t,e){return new Al(t,e)}static EdgeLowPointEvent(t,e){return new la(t,e)}CompareAA(t,e){return k(t.Source.dot(this.DirectionPerp),e.Source.dot(this.DirectionPerp))}}qi.AreaComparisonEpsilon=C.intersectionEpsilon;class bl extends Wn{constructor(t){super(),this.CompassDirection=v.None,this.edges=new Array,this._isFixed=!1,this.Id=-1,this.IdealPosition=0,this.Id=t}get Start(){return this.start}get End(){return this.end}get Edges(){return this.edges}AddEdge(t){if(this.Edges.length===0){let e=j.VectorDirectionPP(t.Source,t.Target);switch(e){case v.South:e=v.North;break;case v.West:e=v.East;break}this.CompassDirection=e,this.start=t.Source,this.end=t.Source}switch(this.CompassDirection){case v.North:this.TryPointForStartAndEndNorth(t.Source),this.TryPointForStartAndEndNorth(t.Target);break;case v.East:this.TryPointForStartAndEndEast(t.Source),this.TryPointForStartAndEndEast(t.Target);break}this.Edges.push(t)}TryPointForStartAndEndNorth(t){t.y<this.start.y?this.start=t:t.y>this.end.y&&(this.end=t)}TryPointForStartAndEndEast(t){t.x<this.start.x?this.start=t:t.x>this.end.x&&(this.end=t)}get IsFixed(){return this._isFixed}set IsFixed(t){this._isFixed=t}get Width(){let t=0;for(const e of this.edges)t=Math.max(t,e.Width);return t}GetLeftBound(){if(!this.IsFixed){let t=Number.NEGATIVE_INFINITY;for(const e of this.edges)t=Math.max(t,e.AxisEdge.LeftBound);return t}return this.CompassDirection===v.North?this.Edges[0].Source.x:-this.Edges[0].Source.y}GetRightBound(){if(!this.IsFixed){let t=Number.POSITIVE_INFINITY;for(const e of this.edges)t=Math.min(t,e.AxisEdge.RightBound);return t}return this.Position()}Position(){return this.CompassDirection===v.North?this.Edges[0].Source.x:-this.Edges[0].Source.y}}class Ni{constructor(t,e){this.tree=new Me((i,s)=>k(i.Point.x,s.Point.x)),this.VerticalPoints=e,this.HorizontalPoints=t}SplitPoints(){this.VerticalPoints.length===0||this.HorizontalPoints.length===0||(this.InitEventQueue(),this.ProcessEvents())}ProcessEvents(){for(;!this.Queue.IsEmpty();){const t={priority:0},e=this.Queue.DequeueAndGetPriority(t);this.ProcessEvent(e,t.priority)}}ProcessEvent(t,e){R(t.Next.Point.x,t.Point.x)?e===Ni.Low(t)?this.ProcessLowLinkedPointEvent(t):this.ProcessHighLinkedPointEvent(t):this.IntersectWithTree(t)}IntersectWithTree(t){let e,i,s;const n=t.Y;if(t.Point.x<t.Next.Point.x?(i=t.Point.x,e=t.Next.Point.x,s=!0):(e=t.Point.x,i=t.Next.Point.x,s=!1),s)for(let o=this.tree.findFirst(a=>i<=a.Point.x);o!=null&&o.item.Point.x<=e;o=this.tree.next(o)){const a=new c(o.item.Point.x,n);t=Ni.TrySplitHorizontalPoint(t,a,!0),Ni.TrySplitVerticalPoint(o.item,a)}else for(let o=this.tree.findLast(a=>a.Point.x<=e);o!=null&&o.item.Point.x>=i;o=this.tree.previous(o)){const a=new c(o.item.Point.x,n);t=Ni.TrySplitHorizontalPoint(t,a,!1),Ni.TrySplitVerticalPoint(o.item,a)}}static TrySplitVerticalPoint(t,e){Ni.Low(t)+C.distanceEpsilon<e.y&&e.y+C.distanceEpsilon<Ni.High(t)&&t.SetNewNext(e)}static TrySplitHorizontalPoint(t,e,i){return i&&t.X+C.distanceEpsilon<e.x&&e.x+C.distanceEpsilon<t.Next.X||!i&&t.Next.X+C.distanceEpsilon<e.x&&e.x+C.distanceEpsilon<t.X?(t.SetNewNext(e),t.Next):t}ProcessHighLinkedPointEvent(t){this.tree.remove(t)}ProcessLowLinkedPointEvent(t){this.tree.insert(t)}InitEventQueue(){this.Queue=new Ri(k);for(const t of this.VerticalPoints)this.Queue.Enqueue(t,Ni.Low(t));for(const t of this.HorizontalPoints)this.Queue.Enqueue(t,t.Point.y)}static Low(t){return Math.min(t.Point.y,t.Next.Point.y)}static High(t){return Math.max(t.Point.y,t.Next.Point.y)}}class gn{constructor(t){this.verticesToPathOffsets=new je,this.Paths=t}MergePaths(){this.InitVerticesToPathOffsetsAndRemoveSelfCycles();for(const t of this.Paths)this.ProcessPath(t)}ProcessPath(t){const e=new Map;let i=null;for(let s=t.PathPoints;s!=null;s=s.Next){const n=this.verticesToPathOffsets.get(s.Point);if(i!=null){if(e.size>0)for(const[o,a]of n){const h=e.get(o);h&&(this.CollapseLoopingPath(o,h,a,t,s),e.delete(o))}for(const[o,a]of i)n.has(o)||e.set(o,a)}i=n}}CollapseLoopingPath(t,e,i,s,n){const o=gn.FindLinkedPointInPath(s,e.Point),a=Array.from(gn.GetPointsInBetween(o,n));gn.Before(e,i)?(this.CleanDisappearedPiece(e,i,t),this.ReplacePiece(e,i,a,t)):(this.CleanDisappearedPiece(i,e,t),this.ReplacePiece(i,e,a.reverse(),t))}static*GetPointsInBetween(t,e){for(let i=t.Next;i!==e;i=i.Next)yield i.Point}ReplacePiece(t,e,i,s){let n=t;for(const o of i){const a=new Hi(o);n.Next=a,n=a,this.verticesToPathOffsets.get(o).set(s,n)}n.Next=e}CleanDisappearedPiece(t,e,i){for(const s of gn.GetPointsInBetween(t,e))this.verticesToPathOffsets.get(s).delete(i)}static Before(t,e){for(t=t.Next;t!=null;t=t.Next)if(t===e)return!0;return!1}static FindLinkedPointInPath(t,e){for(let i=t.PathPoints;;i=i.Next)if(i.Point.equal(e))return i}InitVerticesToPathOffsetsAndRemoveSelfCycles(){for(const t of this.Paths)for(let e=t.PathPoints;e!=null;e=e.Next){let i=this.verticesToPathOffsets.get(e.Point);i||this.verticesToPathOffsets.set(e.Point,i=new Map);const s=i.get(t);s?(this.CleanDisappearedPiece(s,e,t),s.Next=e.Next):i.set(t,e)}}}class Oe{static RefinePaths(t,e){Oe.AdjustPaths(t);const i=Oe.CreatePathsToFirstLinkedVerticesMap(t);Oe.Refine(Array.from(i.values())),Oe.CrossVerticalAndHorizontalSegs(i.values()),Oe.ReconstructPathsFromLinkedVertices(i),e&&new gn(t).MergePaths()}static AdjustPaths(t){for(const e of t)e.PathPoints=Oe.AdjustPathPoints(e.PathPoints)}static AdjustPathPoints(t){if(!t||t.length===0)return;const e=[];let i=c.RoundPoint(t[0]);e.push(i);for(let s=1;s<t.length;s++){const n=c.RoundPoint(t[s]);i.equal(n)||(i=n,e.push(i))}return e}static CrossVerticalAndHorizontalSegs(t){const e=new Array,i=new Array;for(const s of t)for(let n=s;n.Next!=null;n=n.Next)R(n.Point.x,n.Next.Point.x)?i.push(n):e.push(n);new Ni(e,i).SplitPoints()}static ReconstructPathsFromLinkedVertices(t){for(const[e,i]of t)e.PathPoints=i}static Refine(t){Oe.RefineInDirection(v.North,t),Oe.RefineInDirection(v.East,t)}static*groupByProj(t,e){const i=new Map;for(const s of e){const n=t(s.Point);let o=i.get(n);o||(o=new Array,i.set(n,o)),o.push(s)}for(const s of i.values())yield s}static RefineInDirection(t,e){const i={projectionToPerp:void 0,projectionToDirection:void 0};Oe.GetProjectionsDelegates(t,i);const s=Array.from(Oe.GetAllLinkedVertsInDirection(i.projectionToPerp,e)),n=Oe.groupByProj(i.projectionToPerp,s);for(const o of n)Oe.RefineCollinearBucket(o,i.projectionToDirection)}static GetProjectionsDelegates(t,e){t===v.East?(e.projectionToDirection=i=>i.x,e.projectionToPerp=i=>i.y):(e.projectionToPerp=i=>i.x,e.projectionToDirection=i=>i.y)}static*GetAllLinkedVertsInDirection(t,e){for(const i of e)for(let s=i;s.Next!=null;s=s.Next)R(t(s.Point),t(s.Next.Point))&&(yield s)}static RefineCollinearBucket(t,e){const i=new Set,s=new Array;for(const a of t){let h=e(a.Point);i.has(h)||(i.add(h),s.push([a.Point,h])),h=e(a.Next.Point),i.has(h)||(i.add(h),s.push([a.Next.Point,h]))}s.sort((a,h)=>a[1]-h[1]);const n=s.map(a=>a[0]),o=new Map;for(let a=0;a<s.length;a++)o.set(s[a][1],a);for(const a of t){const h=o.get(e(a.Point)),u=o.get(e(a.Next.Point));Math.abs(u-h)>1&&Oe.InsertPoints(a,n,h,u)}}static InsertPoints(t,e,i,s){i<s?t.InsertVerts(i,s,e):t.InsertVertsInReverse(s,i,e)}static CreatePathsToFirstLinkedVerticesMap(t){const e=new Map;for(const i of t)e.set(i,Oe.CreateLinkedVertexOfEdgePath(i));return e}static CreateLinkedVertexOfEdgePath(t){const e=t.PathPoints;let i=new Hi(e[0]);const s=i;for(let n=1;n<e.length;n++)i.Next=new Hi(e[n]),i=i.Next;return s}}class Ms{constructor(t,e){this.Points=t,this.I=e}static equal(t,e){return t.I===e.I&&t.Points===e.Points}get Start(){return this.Points[this.I]}get End(){return this.Points[this.I+1]}}class Vs{constructor(t,e){this.segTree=new on(null),this.crossedOutPaths=new Set,this.HierarchyOfObstacles=new on(e),this.Paths=t}static RemoveStaircases(t,e){new Vs(t,e).Calculate()}Calculate(){this.InitHierarchies();let t;do{t=!1;for(const e of this.Paths.filter(i=>!this.crossedOutPaths.has(i)))this.ProcessPath(e)&&(t=!0)}while(t)}ProcessPath(t){const e={pts:t.PathPoints,canHaveStaircase:!1};return this.ProcessPoints(e)?(t.PathPoints=e.pts,!0):(e.canHaveStaircase||this.crossedOutPaths.add(t),!1)}ProcessPoints(t){const e=this.FindStaircaseStart(t);return e<0?!1:(t.pts=this.RemoveStaircasePN(t.pts,e),!0)}FindStaircaseStart(t){if(t.canHaveStaircase=!1,t.pts.length<5)return-1;const e=[new Ms(t.pts,0),new Ms(t.pts,1),new Ms(t.pts,2),new Ms(t.pts,3)];let i=0;for(let s=0;;){const n={canHaveStaircaseAtI:!1};if(this.IsStaircase(t.pts,s,e,n))return t.canHaveStaircase=!0,s;if(t.canHaveStaircase=t.canHaveStaircase||n.canHaveStaircaseAtI,s++,t.pts.length<s+5)return-1;e[i]=new Ms(t.pts,s+3),i++,i%=4}}static GetFlippedPoint(t,e){return R(t[e].y,t[e+1].y)?new c(t[e+4].x,t[e].y):new c(t[e].x,t[e+4].y)}Crossing(t,e,i){return Vs.IsCrossing(N.mkPP(t,e),this.segTree,i)}static IsCrossing(t,e,i){for(const s of e.GetAllIntersecting(t.boundingBox))if(i.findIndex(n=>n===s)===-1)return!0;return!1}IntersectObstacleHierarchyPPP(t,e,i){return this.IntersectObstacleHierarchyL(N.mkPP(t,e))||this.IntersectObstacleHierarchyL(N.mkPP(e,i))}IntersectObstacleHierarchyL(t){return this.HierarchyOfObstacles.GetAllIntersecting(t.boundingBox).some(e=>w.intersectionOne(t,e,!1)!=null)}IsStaircase(t,e,i,s){const n=t[e],o=t[e+1];let a=t[e+2];const h=t[e+3],u=t[e+4];return s.canHaveStaircaseAtI=!1,j.DirectionFromPointToPoint(n,o)!==j.DirectionFromPointToPoint(a,h)||j.DirectionFromPointToPoint(o,a)!==j.DirectionFromPointToPoint(h,u)||(a=Vs.GetFlippedPoint(t,e),this.IntersectObstacleHierarchyPPP(o,a,h))?!1:(s.canHaveStaircaseAtI=!0,!this.Crossing(o,a,i))}RemoveStaircasePN(t,e){const i=t[e],s=t[e+1],n=Math.abs(i.y-s.y)<C.distanceEpsilon/2;return this.RemoveStaircasePNB(t,e,n)}RemoveStaircasePNB(t,e,i){this.RemoveSegs(t);const s=new Array(t.length-2);vl(t,s,e+1);const n=t[e+1],o=t[e+3];return s[e+1]=i?new c(o.x,n.y):new c(n.x,o.y),wl(t,e+4,s,e+2,s.length-e-2),this.InsertNewSegs(s,e),s}RemoveSegs(t){for(let e=0;e<t.length-1;e++)this.RemoveSeg(new Ms(t,e))}RemoveSeg(t){this.segTree.Remove(Vs.Rect(t),t)}InsertNewSegs(t,e){this.InsSeg(t,e),this.InsSeg(t,e+1)}InitHierarchies(){for(const t of this.Paths)this.InsertPathSegs(t)}InsertPathSegs(t){this.InsertSegs(t.PathPoints)}InsertSegs(t){for(let e=0;e<t.length-1;e++)this.InsSeg(t,e)}InsSeg(t,e){const i=new Ms(t,e);this.segTree.Add(Vs.Rect(i),i)}static Rect(t){return X.mkPP(t.Start,t.End)}}function wl(l,t,e,i,s){for(;s-- >0;)e[i++]=l[t++]}function vl(l,t,e){let i=0;for(;e-- >0;)t[i++]=l[i++]}class Ht{get HasGroups(){return this.HierarchyOfGroups!=null&&this.HierarchyOfGroups.Count>0}constructor(t,e,i,s){this.AncestorsSets=s,this.HierarchyOfGroups=$t(Array.from(s.keys()).filter(n=>n.IsGroup).map(n=>he(n,n.BoundingBox))),this.Obstacles=i,this.EdgeSeparation=2*e,this.Paths=t,this.HierarchyOfObstacles=$t(i.map(n=>he(n,n.boundingBox))),this.MapPathsToTheirObstacles()}MapPathsToTheirObstacles(){this.PathToObstacles=new Map;for(const t of this.Paths)this.MapPathToItsObstacles(t)}MapPathToItsObstacles(t){if(!t.PathPoints||t.PathPoints.length===0)return;const e=t.PathPoints,i=this.HierarchyOfObstacles.FirstHitNodeWithPredicate(e[0],Ht.ObstacleTest),s=this.HierarchyOfObstacles.FirstHitNodeWithPredicate(e[e.length-1],Ht.ObstacleTest);i!=null&&s!=null&&this.PathToObstacles.set(t,[i.UserData,s.UserData])}static ObstacleTest(t,e){return w.PointRelativeToCurveLocation(t,e)!==at.Outside?Nt.Stop:Nt.Continue}Calculate(t,e){this.NudgingDirection=t,Oe.RefinePaths(this.Paths,e),this.GetPathOrdersAndPathGraph(),this.MapAxisEdgesToTheirObstacles(),this.DrawPaths()}MapAxisEdgesToTheirObstacles(){this.axisEdgesToObstaclesTheyOriginatedFrom=new Map;for(const t of this.Paths)this.MapPathEndAxisEdgesToTheirObstacles(t);for(const t of this.Paths)this.UmmapPathInteriourFromStrangerObstacles(t)}UmmapPathInteriourFromStrangerObstacles(t){const e=this.FindFirstUnmappedEdge(t);if(e==null)return;const i=this.FindLastUnmappedEdge(t);for(let s=e;s!=null&&s!==i;s=s.Next)this.axisEdgesToObstaclesTheyOriginatedFrom.delete(s.AxisEdge)}FindLastUnmappedEdge(t){for(let e=t.LastEdge;e!=null;e=e.Prev)if(e.AxisEdge.Direction!==this.NudgingDirection)return e;return null}FindFirstUnmappedEdge(t){for(let e=t.FirstEdge;e!=null;e=e.Next)if(e.AxisEdge.Direction!==this.NudgingDirection)return e;return null}MapPathEndAxisEdgesToTheirObstacles(t){const e=this.PathToObstacles.get(t);e&&(this.ProcessThePathStartToMapAxisEdgesToTheirObstacles(t,e[0]),this.ProcessThePathEndToMapAxisEdgesToTheirObstacles(t,e[1]))}ProcessThePathEndToMapAxisEdgesToTheirObstacles(t,e){for(let i=t.LastEdge;i!=null&&j.DirectionsAreParallel(i.Direction,this.NudgingDirection);i=i.Prev)this.axisEdgesToObstaclesTheyOriginatedFrom.set(i.AxisEdge,e)}ProcessThePathStartToMapAxisEdgesToTheirObstacles(t,e){for(let i=t.FirstEdge;i!=null&&j.DirectionsAreParallel(i.Direction,this.NudgingDirection);i=i.Next)this.axisEdgesToObstaclesTheyOriginatedFrom.set(i.AxisEdge,e)}GetPathOrdersAndPathGraph(){const t=new ye(this.Paths);this.PathOrders=t.GetOrder(),this.PathVisibilityGraph=t.PathVisibilityGraph}static GetCurvesForShow(t,e){const i=new Array;for(const s of t){const n=new st;for(const o of s.PathPoints)n.addPoint(o);i.push(n)}return i.concat(Array.from(e))}DrawPaths(){this.SetWidthsOfArrowheads(),this.CreateLongestNudgedSegments(),this.FindFreeSpaceInDirection(Array.from(this.PathVisibilityGraph.Edges)),this.MoveLongestSegsIdealPositionsInsideFeasibleIntervals(),this.PositionShiftedEdqges()}SetWidthsOfArrowheads(){for(const t of this.Paths)Ht.SetWidthsOfArrowheadsForEdge(t)}static SetWidthsOfArrowheadsForEdge(t){const e=t.GeomEdge;if(e.targetArrowhead!=null){const i=t.LastEdge;i.Width=Math.max(e.targetArrowhead.width,i.Width)}if(e.sourceArrowhead!=null){const i=t.FirstEdge;i.Width=Math.max(e.sourceArrowhead.width,i.Width)}}PositionShiftedEdqges(){this.Solver=new Sl(this.EdgeSeparation);for(let t=0;t<this.LongestNudgedSegs.length;t++)this.CreateVariablesOfLongestSegment(this.LongestNudgedSegs[t]);this.CreateConstraintsOfTheOrder(),this.CreateConstraintsBetweenLongestSegments(),this.Solver.SolveByRegularSolver(),this.ShiftPathEdges()}MoveLongestSegsIdealPositionsInsideFeasibleIntervals(){for(let t=0;t<this.LongestNudgedSegs.length;t++){const e=this.LongestNudgedSegs[t];Ht.MoveLongestSegIdealPositionsInsideFeasibleInterval(e)}}static MoveLongestSegIdealPositionsInsideFeasibleInterval(t){if(t.IsFixed)return;const e=t.GetLeftBound(),i=t.GetRightBound();t.IdealPosition<e?t.IdealPosition=e:t.IdealPosition>i&&(t.IdealPosition=i)}ShiftPathEdges(){for(const t of this.Paths)t.PathPoints=this.GetShiftedPoints(t)}GetShiftedPoints(t){return Ht.RemoveSwitchbacksAndMiddlePoints(this.GetShiftedPointsSimple(t))}static Rectilinearise(t,e){if(t.x===e.x||t.y===e.y)return e;const i=Math.abs(t.x-e.x),s=Math.abs(t.y-e.y);return i<s?new c(t.x,e.y):new c(e.x,t.y)}GetShiftedPointsSimple(t){const e=[],i=t.FirstEdge;e.push(this.ShiftedPoint(i.Source,i.LongestNudgedSegment));for(const s of t.PathEdges())e.push(this.ShiftedEdgePositionOfTarget(s));return e}ShiftedEdgePositionOfTarget(t){return t.LongestNudgedSegment!=null||t.Next==null?this.ShiftedPoint(t.Target,t.LongestNudgedSegment):this.ShiftedPoint(t.Next.Source,t.Next.LongestNudgedSegment)}ShiftedPoint(t,e){if(e==null)return t;const i=this.Solver.GetVariablePosition(e.Id);return this.NudgingDirection===v.North?new c(i,t.y):new c(t.x,-i)}static LineSegOfLongestSeg(t,e){const i=e===v.East?n=>n.x:n=>n.y,s={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY};for(const n of t.Edges)Ht.UpdateMinMaxWithPoint(s,i,n.Source),Ht.UpdateMinMaxWithPoint(s,i,n.Target);return e===v.East?new N(s.min,-t.IdealPosition,s.max,-t.IdealPosition):new N(t.IdealPosition,s.min,t.IdealPosition,s.max)}static UpdateMinMaxWithPoint(t,e,i){const s=e(i);t.min>s&&(t.min=s),t.max<s&&(t.max=s)}CreateConstraintsBetweenLongestSegments(){for(const t of this.LongestNudgedSegs)this.CreateConstraintsBetweenLongestSegmentsForSegment(t)}CreateConstraintsBetweenLongestSegmentsForSegment(t){const e=new Set;for(const i of t.Edges){const s=i.AxisEdge;if(s!=null)for(const n of s.RightNeighbors)for(const o of n.LongestNudgedSegments)e.add(o)}for(const i of e)this.ConstraintTwoLongestSegs(t,i)}CreateConstraintsOfTheOrder(){for(const t of this.PathOrders)Ht.ParallelToDirection(t[0],this.NudgingDirection)&&this.CreateConstraintsOfThePathOrder(t[1])}static ParallelToDirection(t,e){switch(e){case v.North:case v.South:return R(t.SourcePoint.x,t.TargetPoint.x);default:return R(t.SourcePoint.y,t.TargetPoint.y)}}CreateConstraintsOfThePathOrder(t){let e=null;for(const i of t.filter(s=>s.LongestNudgedSegment!=null))e!=null&&this.ConstraintTwoLongestSegs(e.LongestNudgedSegment,i.LongestNudgedSegment),e=i}ConstraintTwoLongestSegs(t,e){(!t.IsFixed||!e.IsFixed)&&this.Solver.AddConstraint(t.Id,e.Id)}CreateVariablesOfLongestSegment(t){if(t.IsFixed)this.Solver.AddFixedVariable(t.Id,Ht.SegmentPosition(t,this.NudgingDirection));else{const e=t.GetLeftBound(),i=t.GetRightBound();e>=i?(this.Solver.AddFixedVariable(t.Id,Ht.SegmentPosition(t,this.NudgingDirection)),t.IsFixed=!0):(this.Solver.AddVariableNNNN(t.Id,Ht.SegmentPosition(t,this.NudgingDirection),t.IdealPosition,t.Width),e!==Number.NEGATIVE_INFINITY&&this.Solver.SetLowBound(e,t.Id),i!==Number.POSITIVE_INFINITY&&this.Solver.SetUpperBound(t.Id,i))}}static SegmentPosition(t,e){return e===v.North?t.Start.x:-t.Start.y}FindFreeSpaceInDirection(t){this.BoundAxisEdgesByRectsKnownInAdvance(),new qi(this.NudgingDirection,this.Obstacles,this.axisEdgesToObstaclesTheyOriginatedFrom,this.PathOrders,t).FindFreeSpace()}BoundAxisEdgesByRectsKnownInAdvance(){for(const t of this.Paths)this.HasGroups&&this.BoundPathByMinCommonAncestors(t),this.BoundAxisEdgesAdjacentToSourceAndTargetOnEdge(t)}BoundPathByMinCommonAncestors(t){for(const e of this.GetMinCommonAncestors(t.GeomEdge)){const i=e.BoundingBox;for(const s of t.PathEdges()){const n=s.AxisEdge;n.Direction===this.NudgingDirection&&this.BoundAxisEdgeByRect(i,n)}}}GetMinCommonAncestors(t){this.PortToShapes==null&&(this.PortToShapes=Ht.MapPortsToShapes(this.AncestorsSets.keys()));const e=Il(this.AncestorsForPort(t.sourcePort),this.AncestorsForPort(t.targetPort));return Array.from(e).filter(i=>!i.Children.some(s=>e.has(s)))}AncestorsForPort(t){const e=this.PortToShapes.get(t);return e?this.AncestorsSets.get(e):new Set(this.HierarchyOfGroups.AllHitItems(X.mkPP(t.Location,t.Location),null))}BoundAxisEdgeAdjacentToObstaclePort(t,e){t.Curve==null?this.BoundAxisByPoint(t.Location,e):t.Curve.boundingBox.contains(t.Location)&&this.BoundAxisEdgeByRect(t.Curve.boundingBox,e)}BoundAxisByPoint(t,e){e!=null&&e.Direction===this.NudgingDirection&&(this.NudgingDirection===v.North?(e.BoundFromLeft(t.x),e.BoundFromRight(t.x)):(e.BoundFromLeft(-t.y),e.BoundFromRight(-t.y)))}BoundAxisEdgesAdjacentToSourceAndTargetOnEdge(t){this.BoundAxisEdgeAdjacentToObstaclePort(t.GeomEdge.sourcePort,t.FirstEdge.AxisEdge),this.BoundAxisEdgeAdjacentToObstaclePort(t.GeomEdge.targetPort,t.LastEdge.AxisEdge)}BoundAxisEdgeByRect(t,e){e!=null&&e.Direction===this.NudgingDirection&&(this.NudgingDirection===v.North?(e.BoundFromLeft(t.left),e.BoundFromRight(t.right)):(e.BoundFromLeft(t.top*-1),e.BoundFromRight(t.bottom*-1)))}CreateLongestNudgedSegments(){const t=this.NudgingDirection===v.East?e=>-e.y:e=>e.x;this.LongestNudgedSegs=new Array;for(let e=0;e<this.Paths.length;e++)this.CreateLongestNudgedSegmentsForPath(this.Paths[e],t)}CreateLongestNudgedSegmentsForPath(t,e){this.GoOverPathAndCreateLongSegs(t),Ht.CalculateIdealPositionsForLongestSegs(t,e)}static CalculateIdealPositionsForLongestSegs(t,e){let i=null,s=null,n=e(t.Start);for(const o of t.PathEdges())if(o.LongestNudgedSegment!=null){if(i=o.LongestNudgedSegment,s!=null){let a;Ht.SetIdealPositionForSeg(s,a=e(s.start),n,e(i.Start)),n=a,s=null}}else i!=null&&(s=i,i=null);s!=null?Ht.SetIdealPositionForSeg(s,e(s.Start),n,e(t.End)):i!=null&&(i.IdealPosition=e(i.Start))}static SetIdealPositionForSeg(t,e,i,s){const n=Math.max(i,s),o=Math.min(i,s);o+C.distanceEpsilon<e?e<n?t.IdealPosition=.5*(n+o):t.IdealPosition=n:t.IdealPosition=o}GoOverPathAndCreateLongSegs(t){let e=null;const i=j.OppositeDir(this.NudgingDirection);for(const s of t.PathEdges()){const n=s.Direction;n===this.NudgingDirection||n===i?(e==null?(s.LongestNudgedSegment=e=new bl(this.LongestNudgedSegs.length),this.LongestNudgedSegs.push(e)):s.LongestNudgedSegment=e,s.IsFixed&&(e.IsFixed=!0)):(s.LongestNudgedSegment=null,e=null)}}static BuildPolylineForPath(t){const e={points:t.PathPoints.map(i=>i.clone())};return Ht.ExtendPolylineToPorts(e,t),e.points}static ExtendPolylineToPorts(t,e){Ht.ExtendPolylineToSourcePort(t,e.GeomEdge.sourcePort.Location),Ht.ExtendPolylineToTargetPort(t,e.GeomEdge.targetPort.Location),t.points.length<2&&(t.points=new Array(2),t.points[0]=e.GeomEdge.sourcePort.Location,t.points[1]=e.GeomEdge.targetPort.Location)}static ExtendPolylineToTargetPort(t,e){const i=t.points.length-1,s=j.VectorDirectionPP(t.points[i-1],t.points[i]);if(Ht.ProjectionsAreClose(t.points[i-1],s,e)){t.points=t.points.slice(0,i);return}const n=t.points[i];s===v.East||s===v.West?t.points[i]=new c(e.x,n.y):t.points[i]=new c(n.x,e.y)}static ProjectionsAreClose(t,e,i){return e===v.East||e===v.West?R(t.x,i.x):R(t.y,i.y)}static ExtendPolylineToSourcePort(t,e){const i=j.VectorDirectionPP(t.points[0],t.points[1]);if(Ht.ProjectionsAreClose(t.points[1],i,e)){t.points=t.points.slice(1);return}const s=t.points[0];i===v.East||i===v.West?t.points[0]=new c(e.x,s.y):t.points[0]=new c(s.x,e.y)}static RemoveSwitchbacksAndMiddlePoints(t){const e=[];let i=t[0];e.push(i);let s=t[1],n=j.VectorDirectionPP(i,s),o=1;for(;++o<t.length;){const a=j.VectorDirectionPP(s,t[o]);a===n||j.OppositeDir(a)===n||a===v.None||(c.closeDistEps(i,s)||e.push(i=Ht.Rectilinearise(i,s)),n=a),s=t[o]}return c.closeDistEps(i,s)||e.push(Ht.Rectilinearise(i,s)),e}static NudgePaths(t,e,i,s,n){if(t.length===0)return;const o=new Ht(t,e,i,s);o.Calculate(v.North,!0),o.Calculate(v.East,!1),o.Calculate(v.North,!1),n&&o.RemoveStaircases();for(const a of t)a.GeomEdge.curve=st.mkFromPoints(Ht.BuildPolylineForPath(a))}RemoveStaircases(){Vs.RemoveStaircases(this.Paths,this.HierarchyOfObstacles)}static MapPortsToShapes(t){const e=new Map;for(const i of t)for(const s of i.Ports)e.set(s,i);return e}static*GetEdgePathFromPathEdgesAsDebugCurves(t,e,i,s){const n=s.ArrayOfPathPoints(),o=n.length,a=o>1?(e-t)/(o-1):1;for(let h=0;h<n.length-1;h++)yield wt.mkDebugCurveTWCI(200,t+a*h,i,N.mkPP(n[h],n[h+1]))}}function Il(l,t){const e=new Set;if(l.size<t.size)for(const i of l)t.has(i)&&e.add(i);else for(const i of t)l.has(i)&&e.add(i);return e}class Tl{constructor(t,e){this.Crossings=[],this.Location=t,this.Crossings=e}}class Yn{Count(){return this.ListOfPointsAndCrossings.length}constructor(){this.ListOfPointsAndCrossings=[],this.index=0,this.ListOfPointsAndCrossings=new Array}Add(t,e){this.ListOfPointsAndCrossings.push(new Tl(t,e))}Pop(){return this.ListOfPointsAndCrossings[this.index++]}CurrentIsBeforeOrAt(t){return this.index>=this.ListOfPointsAndCrossings.length?!1:L.ComparePP(this.ListOfPointsAndCrossings[this.index].Location,t)<=0}get First(){return this.ListOfPointsAndCrossings[0]}get Last(){return this.ListOfPointsAndCrossings[this.ListOfPointsAndCrossings.length-1]}Reset(){this.index=0}MergeFrom(t){if(this.Reset(),t==null)return;const e=this.ListOfPointsAndCrossings.length;let i=0;const s=t.ListOfPointsAndCrossings.length;let n=0;const o=new Array(this.ListOfPointsAndCrossings.length);for(;i<e||n<s;){if(i>=e){o.push(t.ListOfPointsAndCrossings[n++]);continue}if(n>=s){o.push(this.ListOfPointsAndCrossings[i++]);continue}const a=this.ListOfPointsAndCrossings[i],h=t.ListOfPointsAndCrossings[n],u=L.ComparePP(a.Location,h.Location);u===0?(o.push(a),++i,++n):u===-1?(o.push(a),++i):(o.push(h),++n)}this.ListOfPointsAndCrossings=o}Trim(t,e){this.Reset(),!(this.ListOfPointsAndCrossings==null||this.ListOfPointsAndCrossings.length===0)&&(this.ListOfPointsAndCrossings=this.ListOfPointsAndCrossings.filter(i=>L.ComparePP(i.Location,t)>=0&&L.ComparePP(i.Location,e)<=0))}static ToCrossingArray(t,e){let i=0;const s=t.length;for(let a=0;a<s;a++)t[a].DirectionToInside===e&&i++;if(i===0)return null;const n=new Array(i);let o=0;for(let a=0;a<s;a++)t[a].DirectionToInside===e&&(n[o++]=t[a]);return n}ToString(){return ue.Qf.format("{0} [{1}]",this.ListOfPointsAndCrossings.length,this.index)}}class Z{static EdgeDirectionVE(t){return Z.EdgeDirectionVV(t.Source,t.Target)}static EdgeDirectionVV(t,e){return L.GetDirections(t.point,e.point)}static GetEdgeEnd(t,e){const i=Z.EdgeDirectionVE(t);return e===i?t.Target:t.Source}static FindAdjacentVertex(t,e){for(const i of t.InEdges)if(L.GetDirections(t.point,i.SourcePoint)===e)return i.Source;for(const i of t.OutEdges)if(L.GetDirections(t.point,i.TargetPoint)===e)return i.Target;return null}static FindAdjacentEdge(t,e){for(const i of t.InEdges)if(L.GetDirections(i.SourcePoint,t.point)===e)return i;for(const i of t.OutEdges)if(L.GetDirections(t.point,i.TargetPoint)===e)return i;return null}static FindBendPointBetween(t,e,i){return Z.IsVerticalD(i)?new c(e.x,t.y):new c(t.x,e.y)}static SegmentIntersectionPPP(t,e,i){const s=L.GetDirections(t,e);return Z.IsVerticalD(s)?new c(t.x,i.y):new c(i.x,t.y)}static SegmentIntersectionSP(t,e){return Z.SegmentIntersectionPPP(t.Start,t.End,e)}static SegmentsIntersection(t,e){return Z.IntervalsIntersect(t.Start,t.End,e.Start,e.End)}static SegmentsIntersectLL(t,e){return Z.IntervalsIntersect(t.start,t.end,e.start,e.end)}static IntervalsOverlapSS(t,e){return Z.IntervalsOverlapPPPP(t.Start,t.End,e.Start,e.End)}static IntervalsOverlapPPPP(t,e,i,s){return Z.IntervalsAreCollinear(t,e,i,s)&&L.ComparePP(t,s)!==L.ComparePP(e,i)}static IntervalsAreCollinear(t,e,i,s){const n=Z.IsVerticalPP(t,e);return Z.IsVerticalPP(i,s)===n?n?L.Equal(t.x,i.x):L.Equal(t.y,i.y):!1}static IntervalsAreSame(t,e,i,s){return L.EqualPP(t,i)&&L.EqualPP(e,s)}static IntervalsIntersect(t,e,i,s){const n=Z.SegmentIntersectionPPP(t,e,i);return Z.PointIsOnSegmentPPP(t,e,n)&&Z.PointIsOnSegmentPPP(i,s,n)?n:void 0}static SegmentIntersectionEP(t,e){return Z.SegmentIntersectionPPP(t.SourcePoint,t.TargetPoint,e)}static PointIsOnSegmentPPP(t,e,i){return L.EqualPP(t,i)||L.EqualPP(e,i)||L.GetDirections(t,i)===L.GetDirections(i,e)}static PointIsOnSegmentSP(t,e){return Z.PointIsOnSegmentPPP(t.Start,t.End,e)}static IsVerticalD(t){return(t&(v.North|v.South))!==0}static IsVerticalE(t){return Z.IsVerticalD(L.GetDirections(t.SourcePoint,t.TargetPoint))}static IsVerticalPP(t,e){return Z.IsVerticalD(L.GetDirections(t,e))}static IsVertical(t){return Z.IsVerticalD(L.GetDirections(t.start,t.end))}static IsAscending(t){return(t&(v.North|v.East))!==0}static Slope(t,e,i){const s=e.sub(t);return s.dot(i.PerpDirectionAsPoint)/s.dot(i.DirectionAsPoint)}static SortAscending(t,e){const i=L.GetDirections(t,e);return v.None===i||Z.IsAscending(i)?[t,e]:[e,t]}static RectangleBorderIntersect(t,e,i){switch(i){case v.North:case v.South:return new c(e.x,Z.GetRectangleBound(t,i));case v.East:case v.West:return new c(Z.GetRectangleBound(t,i),e.y);default:throw new Error}}static GetRectangleBound(t,e){switch(e){case v.North:return t.top;case v.South:return t.bottom;case v.East:return t.right;case v.West:return t.left;default:throw new Error}}static RectangleInteriorsIntersect(t,e){return L.Compare(t.bottom,e.top)<0&&L.Compare(e.bottom,t.top)<0&&L.Compare(t.left,e.right)<0&&L.Compare(e.left,t.right)<0}static PointIsInRectangleInterior(t,e){return L.Compare(t.y,e.top)<0&&L.Compare(e.bottom,t.y)<0&&L.Compare(t.x,e.right)<0&&L.Compare(e.left,t.x)<0}}class _t{get Dir(){return this.dir}set Dir(t){this.dir=t}constructor(t){this.Dir=t,this.DirectionAsPoint=j.toPoint(this.Dir),this.PerpDirection=v.North===t?v.East:v.North,this.PerpDirectionAsPoint=j.toPoint(this.PerpDirection),this.OppositeDirection=j.OppositeDir(t)}get IsHorizontal(){return v.East===this.Dir}get IsVertical(){return v.North===this.Dir}Compare(t,e){const i=this.ComparePerpCoord(t,e);return i!==0?i:this.CompareScanCoord(t,e)}CompareScanCoord(t,e){return L.Compare(t.sub(e).dot(this.DirectionAsPoint),0)}ComparePerpCoord(t,e){return L.Compare(t.sub(e).dot(this.PerpDirectionAsPoint),0)}IsFlatS(t){return this.IsFlatPP(t.Start,t.End)}IsFlatPP(t,e){return L.Equal(e.sub(t).dot(this.PerpDirectionAsPoint),0)}IsPerpendicularS(t){return this.IsPerpendicularPP(t.Start,t.End)}IsPerpendicularPP(t,e){return L.Equal(e.sub(t).dot(this.DirectionAsPoint),0)}Coord(t){return t.dot(this.DirectionAsPoint)}Min(t,e){return this.Compare(t,e)<=0?t:e}Max(t,e){return this.Compare(t,e)>=0?t:e}get PerpendicularInstance(){return this.IsHorizontal?_t.VerticalInstance:_t.HorizontalInstance}static GetInstance(t){return Z.IsVerticalD(t)?_t.VerticalInstance:_t.HorizontalInstance}ToString(){return this.Dir.toString()}}_t.HorizontalInstance=new _t(v.East),_t.VerticalInstance=new _t(v.North);class mt extends Wn{static mk(t,e){return new mt(t,e,mt.NormalWeight,null)}constructor(t,e,i,s){super(),this.Update(t,e),this.Weight=i,this.GroupBoundaryPointAndCrossingsList=s}get Start(){return this.startPoint}get End(){return this.endPoint}get IsVertical(){return mt.IsVerticalSegment(this.Start,this.End)}get ScanDirection(){return this.IsVertical?_t.VerticalInstance:_t.HorizontalInstance}get IsOverlapped(){return mt.OverlappedWeight===this.Weight}get IsReflection(){return mt.ReflectionWeight===this.Weight}static IsVerticalSegment(t,e){return t.x===e.x}MergeGroupBoundaryCrossingList(t){t!=null&&(this.GroupBoundaryPointAndCrossingsList==null&&(this.GroupBoundaryPointAndCrossingsList=new Yn),this.GroupBoundaryPointAndCrossingsList.MergeFrom(t))}TrimGroupBoundaryCrossingList(){this.GroupBoundaryPointAndCrossingsList!=null&&this.GroupBoundaryPointAndCrossingsList.Trim(this.Start,this.End)}Update(t,e){this.startPoint=t,this.endPoint=e}SetInitialVisibilityVertex(t){this.LowestVisibilityVertex=t,this.HighestVisibilityVertex=t}AppendVisibilityVertex(t,e){if(this.HighestVisibilityVertex==null)this.AddGroupCrossingsBeforeHighestVisibilityVertex(t,e)||this.SetInitialVisibilityVertex(e);else{if(L.IsPureLower(e.point,this.HighestVisibilityVertex.point))return;this.AddGroupCrossingsBeforeHighestVisibilityVertex(t,e)||this.AppendHighestVisibilityVertex(e)}}AddVisibilityEdge(t,e){const i=new ve(t,e,this.Weight);return Xt.AddEdge(i),i}AppendHighestVisibilityVertex(t){L.EqualPP(this.HighestVisibilityVertex.point,t.point)||(this.AddVisibilityEdge(this.HighestVisibilityVertex,t),this.HighestVisibilityVertex=t)}LoadStartOverlapVertexIfNeeded(t){if(this.NeedStartOverlapVertex){const e=t.FindVertex(this.Start);this.AppendVisibilityVertex(t,e??t.AddVertexP(this.Start))}}LoadEndOverlapVertexIfNeeded(t){if(this.NeedEndOverlapVertex){const e=t.FindVertex(this.End);this.AppendVisibilityVertex(t,e??t.AddVertexP(this.End))}}OnSegmentIntersectorBegin(t){this.AppendGroupCrossingsThroughPoint(t,this.Start)||this.LoadStartOverlapVertexIfNeeded(t)}OnSegmentIntersectorEnd(t){this.AppendGroupCrossingsThroughPoint(t,this.End),this.GroupBoundaryPointAndCrossingsList=null,(this.HighestVisibilityVertex==null||L.IsPureLower(this.HighestVisibilityVertex.point,this.End))&&this.LoadEndOverlapVertexIfNeeded(t)}static Subsume(t,e,i,s,n,o,a,h){return h.extendStart=!0,h.extendEnd=!0,t.seg==null||!Z.IntervalsOverlapPPPP(t.seg.Start,t.seg.End,e,i)?!1:t.seg.Weight!==s?t.seg.Start===e&&t.seg.End===i?(t.seg.Weight=Math.min(t.seg.Weight,s),!0):!1:(h.extendStart=o.CompareScanCoord(e,t.seg.Start)===-1,h.extendEnd=o.CompareScanCoord(i,t.seg.End)===1,(h.extendStart||h.extendEnd)&&(a.Remove(t.seg),t.seg.startPoint=o.Min(t.seg.Start,e),t.seg.endPoint=o.Max(t.seg.End,i),t.seg=a.InsertUnique(t.seg).item,t.seg.MergeGroupBoundaryCrossingList(n)),!0)}IntersectsSegment(t){return Z.SegmentsIntersection(this,t)!==void 0}toString(){return"["+this.Start+" -> "+this.End+(this.IsOverlapped?" olap":" free")+"]"}ContainsPoint(t){return L.EqualPP(this.Start,t)||L.EqualPP(this.End,t)||L.GetDirections(this.Start,t)===L.GetDirections(t,this.End)}get HasSparsePerpendicularCoords(){return this.sparsePerpendicularCoords==null?!1:this.sparsePerpendicularCoords.size>0}CreatePointFromPerpCoord(t){return this.IsVertical?new c(this.Start.x,t):new c(t,this.Start.y)}AddSparseVertexCoord(t){this.sparsePerpendicularCoords==null&&(this.sparsePerpendicularCoords=new Set),this.sparsePerpendicularCoords.add(t)}AddSparseEndpoint(t){return this.sparsePerpendicularCoords.has(t)?!1:(this.sparsePerpendicularCoords.add(t),!0)}CreateSparseVerticesAndEdges(t){var e;if(this.sparsePerpendicularCoords!=null){this.AppendGroupCrossingsThroughPoint(t,this.Start);for(const i of Array.from(this.sparsePerpendicularCoords.values()).sort(k)){const s=this.CreatePointFromPerpCoord(i);this.AppendVisibilityVertex(t,(e=t.FindVertex(s))!==null&&e!==void 0?e:t.AddVertexP(s))}this.AppendGroupCrossingsThroughPoint(t,this.End),this.GroupBoundaryPointAndCrossingsList=null,this.sparsePerpendicularCoords.clear(),this.sparsePerpendicularCoords=null}}HasVisibility(){return this.LowestVisibilityVertex!=null}AddGroupCrossingsBeforeHighestVisibilityVertex(t,e){return this.AppendGroupCrossingsThroughPoint(t,e.point)?(L.IsPureLower(this.HighestVisibilityVertex.point,e.point)&&(this.AddVisibilityEdge(this.HighestVisibilityVertex,e),this.HighestVisibilityVertex=e),!0):!1}AppendGroupCrossingsThroughPoint(t,e){var i;if(this.GroupBoundaryPointAndCrossingsList==null)return!1;let s=!1;for(;this.GroupBoundaryPointAndCrossingsList.CurrentIsBeforeOrAt(e);){const n=this.GroupBoundaryPointAndCrossingsList.Pop();let o=null,a=null;L.ComparePP(n.Location,this.Start)>0&&(o=Yn.ToCrossingArray(n.Crossings,this.ScanDirection.OppositeDirection)),L.ComparePP(n.Location,this.End)<0&&(a=Yn.ToCrossingArray(n.Crossings,this.ScanDirection.Dir)),s=!0;const h=(i=t.FindVertex(n.Location))!==null&&i!==void 0?i:t.AddVertexP(n.Location);t.AddVertexP(n.Location),o!=null||a!=null?(this.AddLowCrossings(t,h,o),this.AddHighCrossings(t,h,a)):this.LowestVisibilityVertex==null?this.SetInitialVisibilityVertex(h):this.AppendHighestVisibilityVertex(h)}return s}static GetCrossingInteriorVertex(t,e,i){var s;const n=i.GetInteriorVertexPoint(e.point);return(s=t.FindVertex(n))!==null&&s!==void 0?s:t.AddVertexP(n)}AddCrossingEdge(t,e,i,s){let n=null;this.HighestVisibilityVertex!=null&&(L.EqualPP(this.HighestVisibilityVertex.point,i.point)?n=t.FindEdgePP(e.point,i.point):this.AppendHighestVisibilityVertex(e)),n==null&&(n=this.AddVisibilityEdge(e,i));const o=s.map(h=>h.Group.InputShape),a=n.IsPassable;a==null?n.IsPassable=()=>{for(const h of o)if(h.IsTransparent)return!0;return!1}:n.IsPassable=()=>{for(const h of o)if(h.IsTransparent||a())return!0;return!1},this.LowestVisibilityVertex==null&&this.SetInitialVisibilityVertex(e),this.HighestVisibilityVertex=i}AddLowCrossings(t,e,i){if(i!=null){const s=mt.GetCrossingInteriorVertex(t,e,i[0]);this.AddCrossingEdge(t,s,e,i)}}AddHighCrossings(t,e,i){if(i!=null){const s=mt.GetCrossingInteriorVertex(t,e,i[0]);this.AddCrossingEdge(t,e,s,i)}}}mt.NormalWeight=ve.DefaultWeight,mt.ReflectionWeight=5,mt.OverlappedWeight=500;class ha{constructor(t,e,i,s,n){this.IsClosed=!1,this.Vertex=t,this.Direction=e!=null?j.DirectionFromPointToPoint(e.Vertex.point,t.point):v.None,this.ResetEntry(e,i,s,n)}ResetEntry(t,e,i,s){this.PreviousEntry=t,this.Length=e,this.NumberOfBends=i,this.Cost=s}get PreviousVertex(){return this.PreviousEntry==null?null:this.PreviousEntry.Vertex}toString(){return this.Vertex.point+(" "+(this.Direction+(" "+(this.IsClosed+(" "+this.Cost)))))}}class Eo{constructor(){this.Clear()}Set(t,e){this.Vertex=t,this.Weight=e}Clear(){this.Vertex=null,this.Weight=Number.NaN}}class Lt{CombinedCost(t,e){return this.LengthImportance*t+this.BendsImportance*e}TotalCostFromSourceToVertex(t,e){return this.CombinedCost(t,e)+this.sourceCostAdjustment}constructor(){this.nextNeighbors=[new Eo,new Eo,new Eo],this.LengthImportance=1,this.BendsImportance=1}InitPath(t,e,i){if(e===i||!this.InitEntryDirectionsAtTarget(i))return!1;this.Target=i,this.Source=e;const s=this.TotalCostFromSourceToVertex(0,0)+this.HeuristicDistanceFromVertexToTarget(e.point,v.None);return s>=this.upperBoundOnCost?!1:(this.queue=new Ri(k),this.visitedVertices=[e],t==null?this.EnqueueInitialVerticesFromSource(s):this.EnqueueInitialVerticesFromSourceEntries(t),this.queue.count>0)}InitEntryDirectionsAtTarget(t){this.EntryDirectionsToTarget=v.None;for(const e of t.OutEdges)this.EntryDirectionsToTarget=this.EntryDirectionsToTarget|j.DirectionFromPointToPoint(e.TargetPoint,t.point);for(const e of t.InEdges)this.EntryDirectionsToTarget=this.EntryDirectionsToTarget|j.DirectionFromPointToPoint(e.SourcePoint,t.point);return this.EntryDirectionsToTarget!==v.None}static IsInDirs(t,e){return t===(t&e)}MultistageAdjustedCostBound(t){return Number.isFinite(t)?t+this.BendsImportance:t}HeuristicDistanceFromVertexToTarget(t,e){const i=this.Target.point.sub(t);if(R(i.x,0)&&R(i.y,0))return this.targetCostAdjustment;const s=j.VectorDirection(i);let n;return e===v.None?(e=v.East|(v.North|(v.West|v.South)),n=this.GetNumberOfBends(e,s)):n=this.GetNumberOfBends(e,s),this.CombinedCost(Lt.ManhattanDistance(t,this.Target.point),n)+this.targetCostAdjustment}GetNumberOfBends(t,e){return j.IsPureDirection(e)?this.GetNumberOfBendsForPureDirection(t,e):Lt.GetBendsForNotPureDirection(e,t,this.EntryDirectionsToTarget)}GetNumberOfBendsForPureDirection(t,e){return(e&t)===e?Lt.IsInDirs(e,this.EntryDirectionsToTarget)?0:Lt.IsInDirs(Lt.Left(e),this.EntryDirectionsToTarget)||Lt.IsInDirs(Lt.Right(e),this.EntryDirectionsToTarget)?2:4:this.GetNumberOfBendsForPureDirection(Lt.AddOneTurn[t],e)+1}static GetBendsForNotPureDirection(t,e,i){const s=t&e;if(s===v.None)return Lt.GetBendsForNotPureDirection(t,Lt.AddOneTurn[e],i)+1;const n=t&i;return n===v.None?Lt.GetBendsForNotPureDirection(t,e,Lt.AddOneTurn[i])+1:(s|n)===t?1:2}static Left(t){switch(t){case v.None:return v.None;case v.North:return v.West;case v.East:return v.North;case v.South:return v.East;case v.West:return v.South;default:throw new Error("direction")}}static Right(t){switch(t){case v.None:return v.None;case v.North:return v.East;case v.East:return v.South;case v.South:return v.West;case v.West:return v.North;default:throw new Error("direction")}}static RestorePathV(t){return Lt.RestorePath(t,null)}static RestorePath(t,e){if(t.entry==null)return[];const i=new Array;let s=!1,n=v.None;for(;;){n===t.entry.Direction?s=!0:(s=!1,i.push(t.entry.Vertex.point),n=t.entry.Direction);const o=t.entry.PreviousEntry;if(o==null||t.entry.Vertex===e)break;t.entry=o}return s&&i.push(t.entry.Vertex.point),i.reverse(),i}QueueReversedEntryToNeighborVertexIfNeeded(t,e,i){const s={numberOfBends:0,length:0},n=e.PreviousVertex,o=Lt.GetLengthAndNumberOfBendsToNeighborVertex(t,n,i,s);if(this.CombinedCost(s.length,s.numberOfBends)<this.CombinedCost(e.Length,e.NumberOfBends)||t.Vertex.Degree===1){const a=this.TotalCostFromSourceToVertex(s.length,s.numberOfBends)+this.HeuristicDistanceFromVertexToTarget(n.point,o);this.EnqueueEntry(t,n,s.length,s.numberOfBends,a)}}UpdateEntryToNeighborVertexIfNeeded(t,e,i){const s={numberOfBends:0,length:0},n=Lt.GetLengthAndNumberOfBendsToNeighborVertex(t,e.Vertex,i,s);if(this.CombinedCost(s.length,s.numberOfBends)<this.CombinedCost(e.Length,e.NumberOfBends)){const o=this.TotalCostFromSourceToVertex(s.length,s.numberOfBends)+this.HeuristicDistanceFromVertexToTarget(e.Vertex.point,n);e.ResetEntry(t,s.length,s.numberOfBends,o),this.queue.DecreasePriority(e,o)}}CreateAndEnqueueEntryToNeighborVertex(t,e,i){const s={numberOfBends:0,length:0},n=Lt.GetLengthAndNumberOfBendsToNeighborVertex(t,e,i,s),o=this.TotalCostFromSourceToVertex(s.length,s.numberOfBends)+this.HeuristicDistanceFromVertexToTarget(e.point,n);o<this.upperBoundOnCost&&(e.VertexEntries==null&&this.visitedVertices.push(e),this.EnqueueEntry(t,e,s.length,s.numberOfBends,o))}EnqueueEntry(t,e,i,s,n){const o=new ha(e,t,i,s,n);e.SetVertexEntry(o),this.queue.Enqueue(o,o.Cost)}static GetLengthAndNumberOfBendsToNeighborVertex(t,e,i,s){s.length=t.Length+Lt.ManhattanDistance(t.Vertex.point,e.point)*i;const n=j.DirectionFromPointToPoint(t.Vertex.point,e.point);return s.numberOfBends=t.NumberOfBends,t.Direction!==v.None&&n!==t.Direction&&s.numberOfBends++,n}static ManhattanDistance(t,e){return Math.abs(e.x-t.x)+Math.abs(e.y-t.y)}GetPathWithCost(t,e,i,s,n,o,a){if(this.upperBoundOnCost=a,this.sourceCostAdjustment=i,this.targetCostAdjustment=o,!this.InitPath(t,e,n))return null;for(;this.queue.count>0;){const h=this.queue.Dequeue(),u=h.Vertex;if(u===this.Target){if(s==null)return this.Cleanup(),h;if(h.Direction,this.EntryDirectionsToTarget===v.None){let m=0;for(const y of this.Target.VertexEntries)s[m++]=y;return this.Cleanup(),null}this.upperBoundOnCost=Math.min(this.MultistageAdjustedCostBound(h.Cost),this.upperBoundOnCost);continue}h.IsClosed=!0;for(const m of this.nextNeighbors)m.Clear();const d=Lt.Right(h.Direction);this.ExtendPathAlongInEdges(h,u.InEdges,d),this.ExtendPathAlongOutEdges(h,u.OutEdges,d);for(const m of this.nextNeighbors)m.Vertex!=null&&this.ExtendPathToNeighborVertex(h,m.Vertex,m.Weight)}if(s!=null&&this.Target.VertexEntries!=null)for(let h=0;h<this.Target.VertexEntries.length;h++)s[h]=this.Target.VertexEntries[h];return this.Cleanup(),null}ExtendPathAlongInEdges(t,e,i){for(const s of e)this.ExtendPathAlongEdge(t,s,!0,i)}ExtendPathAlongOutEdges(t,e,i){let s=e.isEmpty()?null:e.treeMinimum();for(;s!=null;s=e.next(s))this.ExtendPathAlongEdge(t,s.item,!1,i)}ExtendPathAlongEdge(t,e,i,s){if(!Lt.IsPassable(e))return;const n=i?e.Source:e.Target;if(n===t.PreviousVertex){if(t.Vertex.Degree>1||t.Vertex!==this.Source)return;this.ExtendPathToNeighborVertex(t,n,e.Weight);return}const o=j.DirectionFromPointToPoint(t.Vertex.point,n.point);let a=this.nextNeighbors[2];o!==t.Direction&&(a=this.nextNeighbors[o===s?1:0]),a.Set(n,e.Weight)}EnqueueInitialVerticesFromSource(t){const e=new ha(this.Source,null,0,0,t);e.IsClosed=!0;for(const i of this.Source.OutEdges)Lt.IsPassable(i)&&this.ExtendPathToNeighborVertex(e,i.Target,i.Weight);for(const i of this.Source.InEdges)Lt.IsPassable(i)&&this.ExtendPathToNeighborVertex(e,i.Source,i.Weight)}EnqueueInitialVerticesFromSourceEntries(t){for(const e of t)e!=null&&this.queue.Enqueue(e,e.Cost)}ExtendPathToNeighborVertex(t,e,i){const s=j.DirectionFromPointToPoint(t.Vertex.point,e.point),n=e.VertexEntries!=null?e.VertexEntries[j.ToIndex(s)]:null;n==null?this.CreateAndEnqueueReversedEntryToNeighborVertex(t,e,i)||this.CreateAndEnqueueEntryToNeighborVertex(t,e,i):n.IsClosed||this.UpdateEntryToNeighborVertexIfNeeded(t,n,i)}CreateAndEnqueueReversedEntryToNeighborVertex(t,e,i){if(t.Vertex.VertexEntries!=null){const s=j.DirectionFromPointToPoint(e.point,t.Vertex.point),n=t.Vertex.VertexEntries[j.ToIndex(s)];if(n!=null)return this.QueueReversedEntryToNeighborVertexIfNeeded(t,n,i),!0}return!1}static IsPassable(t){return t.IsPassable==null||t.IsPassable()}Cleanup(){for(const t of this.visitedVertices)t.RemoveVertexEntries();this.visitedVertices=[],this.queue=null}}Lt.DefaultBendPenaltyAsAPercentageOfDistance=4,Lt.AddOneTurn=[v.None,v.North|v.East|v.West,v.North|v.East|v.South,15,v.East|v.South|v.West,15,15,15,13,15,15,15,15,15,15,15];class Jn{constructor(t){this.bendPenaltyAsAPercentageOfDistance=Lt.DefaultBendPenaltyAsAPercentageOfDistance,this.currentPassTargetEntries=new Array(4),this.bendPenaltyAsAPercentageOfDistance=t}GetPath(t,e){const i={entry:this.GetPathStage(null,t,null,e)};return Lt.RestorePathV(i)}GetPathStage(t,e,i,s){const n=new Lt,o={bestEntry:null,bestCost:Number.MAX_VALUE/mt.OverlappedWeight};let a=Number.POSITIVE_INFINITY;const h=Jn.Barycenter(e),u=Jn.Barycenter(s),d=Lt.ManhattanDistance(h,u);n.BendsImportance=Math.max(.001,d*(this.bendPenaltyAsAPercentageOfDistance*.01));const m=n.LengthImportance,y=i!=null?this.currentPassTargetEntries:null,E=[];for(const H of e)for(const tt of s)E.push([H,tt]);E.sort(([H,tt],[lt,Q])=>T(H,tt)-T(lt,Q));for(const[H,tt]of E){if(c.closeDistEps(H.point,tt.point))continue;const lt=B(H,h)*m,Q=B(tt,u)*m;let dt=o.bestCost;if(i!=null){for(let oe=0;oe<y.length;oe++)y[oe]=null;dt=n.MultistageAdjustedCostBound(o.bestCost)}const It=n.GetPathWithCost(t,H,lt,y,tt,Q,dt);if(y!=null){Jn.UpdateTargetEntriesForEachDirection(i,y,o);continue}if(It==null)continue;const Tt=It.Cost/T(H,tt);(It.Cost<o.bestCost||R(It.Cost,o.bestCost)&&Tt<a)&&(o.bestCost=It.Cost,o.bestEntry=It,a=It.Cost/T(H,tt))}return o.bestEntry;function T(H,tt){return Lt.ManhattanDistance(H.point,tt.point)}function B(H,tt){return Lt.ManhattanDistance(H.point,tt)}}static UpdateTargetEntriesForEachDirection(t,e,i){for(let s=0;s<e.length;s++){const n=e[s];n!=null&&(t[s]==null||n.Cost<t[s].Cost)&&(t[s]=n,n.Cost<i.bestCost&&(i.bestCost=n.Cost,i.bestEntry=n))}}static Barycenter(t){let e=new c(0,0);for(const i of t)e=e.add(i.point);return e.div(t.length)}}class xl{get PathPoints(){return this._pathPoints}set PathPoints(t){this._pathPoints=t}get Width(){return this.GeomEdge.lineWidth}constructor(t){this.GeomEdge=t}get End(){return this.LastEdge.Target}get Start(){return this.FirstEdge.Source}ArrayOfPathPoints(){return this._pathPoints instanceof Hi?Array.from(ua(this._pathPoints)):this._pathPoints}*PathEdges(){for(let t=this.FirstEdge;t!=null;t=t.Next)yield t}AddEdge(t){t.Path=this,this.LastEdge.Next=t,t.Prev=this.LastEdge,this.LastEdge=t}SetFirstEdge(t){this.FirstEdge=t,this.LastEdge=t,t.Path=this}toString(){const t=new ue.fe;this.PathPoints instanceof Hi&&t.Append("L");for(const e of ua(this.PathPoints))t.Append(e.toString());return t.ToString()}}function*ua(l){if(l instanceof Hi)for(let t=l;t!=null;t=t.Next)yield t.Point;else for(const t of l)yield t}class ca extends Hn{get Obstacle(){return this.obstacle}set Obstacle(t){this.obstacle=t}constructor(t,e,i,s){super(e),this.Slope=0,this.SlopeInverse=0,this.Obstacle=t,this.endVertex=s?e.nextOnPolyline:e.prevOnPolyline,i.IsPerpendicularPP(e.point,this.endVertex.point)||(this.Slope=Z.Slope(e.point,this.endVertex.point,i),this.SlopeInverse=1/this.Slope)}get EndVertex(){return this.endVertex}}class vi extends ca{constructor(t,e,i){super(t,e,i,i.IsHorizontal)}}class Zn extends ca{constructor(t,e,i){super(t,e,i,i.IsVertical)}}class ge{get PaddedPolyline(){return this._PaddedPolyline}set PaddedPolyline(t){this._PaddedPolyline=t}get looseVisibilityPolyline(){return this._looseVisibilityPolyline==null&&(this._looseVisibilityPolyline=ge.CreateLoosePolyline(this.VisibilityPolyline)),this._looseVisibilityPolyline}set looseVisibilityPolyline(t){this._looseVisibilityPolyline=t}GetPortChanges(t){return t.addedPorts=Xi(this.InputShape.Ports,this.Ports),t.removedPorts=Xi(this.Ports,this.InputShape.Ports),t.addedPorts.size===0&&t.removedPorts.size===0?!1:(this.Ports=new Set(this.InputShape.Ports),!0)}get IsInConvexHull(){return this.ConvexHull!=null}get IsGroup(){return this.InputShape!=null&&this.InputShape.IsGroup}get VisibilityBoundingBox(){return this.VisibilityPolyline.boundingBox}get VisibilityPolyline(){return this.ConvexHull!=null?this.ConvexHull.Polyline:this.PaddedPolyline}static CreateSentinel(t,e,i,s){const n=ge.mk(t,e,s);return n.CreateInitialSides(n.PaddedPolyline.startPoint,i),n}CreateInitialSides(t,e){this.ActiveLowSide=new vi(this,t,e),this.ActiveHighSide=new Zn(this,t,e),e.IsFlatS(this.ActiveHighSide)&&(this.ActiveHighSide=new Zn(this,this.ActiveHighSide.EndVertex,e))}constructor(t,e){t!=null&&(this.PaddedPolyline=ut.PaddedPolylineBoundaryOfNode(t.BoundaryCurve,e),ge.RoundVerticesAndSimplify(this.PaddedPolyline),this.IsRectangle=this.IsPolylineRectangle(),this.InputShape=t,this.Ports=new Set(this.InputShape.Ports))}static mk(t,e,i){const s=new ge(null,0);return s.PaddedPolyline=st.mkClosedFromPoints([c.RoundPoint(t),c.RoundPoint(e)]),s.Ordinal=i,s}IsPolylineRectangle(){if(this.PaddedPolyline.count!==4)return!1;let t=this.PaddedPolyline.startPoint,e=t.nextOnPolyline,i=j.VectorDirectionPP(t.point,e.point);if(!j.IsPureDirection(i))return!1;do{t=e,e=t.nextOnPolyline;const s=j.DirectionFromPointToPoint(t.point,e.point);if(s!==j.RotateRight(i))return!1;i=s}while(t!==this.PaddedPolyline.startPoint);return!0}static RoundVerticesAndSimplify(t){let e=t.startPoint;do e.point=c.RoundPoint(e.point),e=e.nextOnPolyline;while(e!==t.startPoint);ge.RemoveCloseAndCollinearVerticesInPlace(t),t.setInitIsRequired()}get IsPrimaryObstacle(){return this.ConvexHull==null||this===this.ConvexHull.PrimaryObstacle}static RemoveCloseAndCollinearVerticesInPlace(t){const e=C.intersectionEpsilon*10;for(let i=t.startPoint.next;i!=null;i=i.next)c.close(i.prev.point,i.point,e)&&(i.next==null?t.RemoveEndPoint():(i.prev.next=i.next,i.next.prev=i.prev));return c.close(t.start,t.end,e)&&t.RemoveStartPoint(),t=t.RemoveCollinearVertices(),t.endPoint.prev!=null&&t.endPoint.prev!==t.startPoint&&c.getTriangleOrientation(t.endPoint.prev.point,t.end,t.start)===D.Collinear&&t.RemoveEndPoint(),t.startPoint.next!=null&&t.endPoint.prev!==t.startPoint&&c.getTriangleOrientation(t.end,t.start,t.startPoint.next.point)===D.Collinear&&t.RemoveStartPoint(),t.setInitIsRequired(),t}get isOverlapped(){return this.clump!==void 0&&this.clump.length>0}get IsSentinel(){return this.InputShape==null}IsInSameClump(t){return this.isOverlapped&&this.clump===t.clump}Close(){this.ActiveLowSide=null,this.ActiveHighSide=null}SetConvexHull(t){this.clump=null,this.IsRectangle=!1,this.ConvexHull=t,this.looseVisibilityPolyline=null}static CreateLoosePolyline(t){const e=ut.CreatePaddedPolyline(t,C.intersectionEpsilon*10);return ge.RoundVerticesAndSimplify(e),e}get IsTransparentAncestor(){return this.InputShape==null?!1:this.InputShape.IsTransparent}set IsTransparentAncestor(t){this.InputShape.IsTransparent=t}}ge.FirstSentinelOrdinal=1,ge.FirstNonSentinelOrdinal=10;class Ol{get Obstacle(){return this.ObstaclePort.Obstacle}get InitialWeight(){return this.IsOverlapped?mt.OverlappedWeight:mt.NormalWeight}get IsCollinearWithPort(){return j.IsPureDirection(L.GetDirections(this.VisibilityBorderIntersect,this.ObstaclePort.Location))}get IsVertical(){return Z.IsVertical(this.MaxVisibilitySegment)}get WantVisibilityIntersection(){return!this.IsOverlapped&&this.CanExtend&&(!this.ObstaclePort.HasCollinearEntrances||this.IsCollinearWithPort)}get CanExtend(){return L.GetDirections(this.MaxVisibilitySegment.start,this.MaxVisibilitySegment.end)!==v.None}constructor(t,e,i,s){this.IsOverlapped=!1,this.unpaddedToPaddedBorderWeight=mt.NormalWeight,this.ObstaclePort=t,this.UnpaddedBorderIntersect=e,this.OutwardDirection=i;const n=N.mkPP(this.UnpaddedBorderIntersect,Z.RectangleBorderIntersect(t.Obstacle.VisibilityBoundingBox,this.UnpaddedBorderIntersect,i)),o=w.getAllIntersections(n,t.Obstacle.VisibilityPolyline,!0);this.VisibilityBorderIntersect=c.RoundPoint(o[0].x);const a={pacList:null};this.MaxVisibilitySegment=s.CreateMaxVisibilitySegment(this.VisibilityBorderIntersect,this.OutwardDirection,a),this.pointAndCrossingsList=a.pacList,(this.Obstacle.isOverlapped||this.Obstacle.IsGroup&&!this.Obstacle.IsInConvexHull)&&(this.IsOverlapped=s.IntersectionIsInsideAnotherObstacle(null,this.Obstacle,this.VisibilityBorderIntersect,_t.GetInstance(this.OutwardDirection)),(!this.Obstacle.IsGroup||this.IsOverlapped||this.InteriorEdgeCrossesObstacle(s))&&(this.unpaddedToPaddedBorderWeight=mt.OverlappedWeight)),this.Obstacle.IsInConvexHull&&this.unpaddedToPaddedBorderWeight===mt.NormalWeight&&this.SetUnpaddedToPaddedBorderWeightFromHullSiblingOverlaps(s)}SetUnpaddedToPaddedBorderWeightFromHullSiblingOverlaps(t){(this.Obstacle.IsGroup?this.InteriorEdgeCrossesObstacle(t):this.InteriorEdgeCrossesConvexHullSiblings())&&(this.unpaddedToPaddedBorderWeight=mt.OverlappedWeight)}InteriorEdgeCrossesObstacle(t){const e=X.mkPP(this.UnpaddedBorderIntersect,this.VisibilityBorderIntersect);return this.InteriorEdgeCrossesObstacleRFI(e,i=>i.VisibilityPolyline,Array.from(t.Root.GetLeafRectangleNodesIntersectingRectangle(e)).filter(i=>!i.UserData.IsGroup&&i.UserData!==this.Obstacle).map(i=>i.UserData))}InteriorEdgeCrossesConvexHullSiblings(){const t=X.mkPP(this.UnpaddedBorderIntersect,this.VisibilityBorderIntersect);return this.InteriorEdgeCrossesObstacleRFI(t,e=>e.PaddedPolyline,this.Obstacle.ConvexHull.Obstacles.filter(e=>e!==this.Obstacle))}InteriorEdgeCrossesObstacleRFI(t,e,i){let s=null;for(const n of i){const o=e(n);if(!Z.RectangleInteriorsIntersect(t,o.boundingBox))continue;if(s=s??N.mkPP(this.UnpaddedBorderIntersect,this.VisibilityBorderIntersect),w.intersectionOne(s,o,!1)!=null||at.Outside!==w.PointRelativeToCurveLocation(this.UnpaddedBorderIntersect,o))return!0}return!1}get HasGroupCrossings(){return this.pointAndCrossingsList!=null&&this.pointAndCrossingsList.Count()>0}HasGroupCrossingBeforePoint(t){if(!this.HasGroupCrossings)return!1;const e=Z.IsAscending(this.OutwardDirection)?this.pointAndCrossingsList.First:this.pointAndCrossingsList.Last;return L.GetDirections(this.MaxVisibilitySegment.start,e.Location)===L.GetDirections(e.Location,t)}AddToAdjacentVertex(t,e,i,s){let n=t.VisGraph.FindVertex(this.VisibilityBorderIntersect);if(n!=null){this.ExtendEdgeChain(t,n,n,i,s);return}this.OutwardDirection===L.GetDirections(e.point,this.VisibilityBorderIntersect)?(this.VisibilityBorderIntersect=e.point,n=e):(n=t.FindOrAddVertex(this.VisibilityBorderIntersect),t.FindOrAddEdge(n,e,this.InitialWeight)),this.ExtendEdgeChain(t,n,e,i,s)}ExtendEdgeChain(t,e,i,s,n){t.ExtendEdgeChainVRLPB(i,s,this.MaxVisibilitySegment,this.pointAndCrossingsList,this.IsOverlapped);const o=t.FindOrAddVertex(this.UnpaddedBorderIntersect);t.FindOrAddEdge(o,e,this.unpaddedToPaddedBorderWeight),n&&t.ConnectVertexToTargetVertex(this.ObstaclePort.CenterVertex,o,this.OutwardDirection,this.InitialWeight)}toString(){return ue.Qf.format("{0} {1}~{2} {3}",this.ObstaclePort.Location,this.UnpaddedBorderIntersect,this.VisibilityBorderIntersect,this.OutwardDirection)}}class Bl{constructor(t,e){this.HasCollinearEntrances=!1,this.VisibilityRectangle=X.mkEmpty(),this.Port=t,this.Obstacle=e,this.PortEntrances=new Array,this.Location=c.RoundPoint(this.Port.Location)}CreatePortEntrance(t,e,i){const s=new Ol(this,t,e,i);this.PortEntrances.push(s),this.VisibilityRectangle.add(s.MaxVisibilitySegment.end),this.HasCollinearEntrances=this.HasCollinearEntrances||s.IsCollinearWithPort}ClearVisibility(){this.PortEntrances=[]}AddToGraph(t,e){e&&(this.CenterVertex=t.FindOrAddVertex(this.Location))}RemoveFromGraph(){this.CenterVertex=null}get LocationHasChanged(){return!c.closeDistEps(this.Location,c.RoundPoint(this.Port.Location))}get PortCurve(){return this.Port.Curve}get PortLocation(){return this.Port.Location}toString(){return this.Port+this.Obstacle.toString()}}class Ll{get Point(){return this.Vertex.point}get InitialWeight(){return this.IsOverlapped?mt.OverlappedWeight:mt.NormalWeight}get IsOutOfBounds(){return v.None!==this.OutOfBoundsDirectionFromGraph}constructor(t,e){this.maxVisibilitySegmentsAndCrossings=new Array(4),this.OutOfBoundsDirectionFromGraph=v.None,this.GetVertex(t,e)}GetVertex(t,e){this.Vertex=t.FindOrAddVertex(e)}AddEdgeToAdjacentEdge(t,e,i,s){const n=Z.SegmentIntersectionEP(e,this.Point);let o=t.VisGraph.FindVertex(n);return o!=null?this.AddToAdjacentVertex(t,o,i,s):o=t.AddEdgeToTargetEdge(this.Vertex,e,n),this.ExtendEdgeChain(t,o,i,s),o}AddToAdjacentVertex(t,e,i,s){L.EqualPP(this.Point,e.point)||t.FindOrAddEdge(this.Vertex,e,this.InitialWeight),this.ExtendEdgeChain(t,e,i,s)}ExtendEdgeChain(t,e,i,s){let n=this.IsOverlapped;n&&(n=t.ObstacleTree.PointIsInsideAnObstaclePD(e.point,i));const o=this.GetSegmentAndCrossings(this.IsOverlapped?e:this.Vertex,i,t);t.ExtendEdgeChainVRLPB(e,s,o[0],o[1],n)}GetSegmentAndCrossings(t,e,i){const s=j.ToIndex(e);let n=this.maxVisibilitySegmentsAndCrossings[s];if(n==null){const o={pacList:null};n=[i.ObstacleTree.CreateMaxVisibilitySegment(t.point,e,o),o.pacList],this.maxVisibilitySegmentsAndCrossings[s]=n}else L.GetDirections(t.point,n[0].start)===e&&(n[0].start=t.point);return n}MaxVisibilityInDirectionForNonOverlappedFreePoint(t,e){return this.GetSegmentAndCrossings(this.Vertex,t,e)[0].end}AddOobEdgesFromGraphCorner(t,e){const i=L.GetDirections(e,this.Vertex.point),s=t.VisGraph.FindVertex(e);t.ConnectVertexToTargetVertex(s,this.Vertex,i&(v.North|v.South),mt.NormalWeight),t.ConnectVertexToTargetVertex(s,this.Vertex,i&(v.East|v.West),mt.NormalWeight)}RemoveFromGraph(){this.Vertex=null}toString(){return this.Vertex.toString()}}class bo{constructor(t,e){this.BoundaryWidth=C.distanceEpsilon,this.Group=t,this.DirectionToInside=e}GetInteriorVertexPoint(t){return c.RoundPoint(t.add(j.toPoint(this.DirectionToInside).mul(this.BoundaryWidth)))}toString(){return ue.Qf.format("{0} {1}",this.DirectionToInside,this.Group)}}bo.BoundaryWidth=C.distanceEpsilon;class wo extends ai{constructor(t){super(),this.site=t}get Site(){return this.site}}class Qr extends ts{constructor(t,e){super(e),this.Obstacle=t}}class $r extends Qr{constructor(t,e){super(t,e)}}class Fl{AddPendingPerpendicularCoord(t){this.pendingPerpCoords==null&&(this.pendingPerpCoords=new Array),this.pendingPerpCoords.push(t)}ResetForIntersections(){this.CurrentSegment=this.FirstSegment}get IsHorizontal(){return!this.FirstSegment.IsVertical}constructor(t){this.Coord=t}TraverseToSegmentContainingPoint(t){if(this.CurrentSegment.ContainsPoint(t))return!0;const e=this.IsHorizontal?t.y:t.x;if(!L.Equal(this.Coord,e)){for(;this.MoveNext(););return!1}for(;;){if((this.CurrentSegment.NextSegment==null||L.GetDirections(this.CurrentSegment.End,t)==L.GetDirections(t,this.CurrentSegment.NextSegment.Start))&&c.closeIntersections(this.CurrentSegment.End,t))return this.CurrentSegment.Update(this.CurrentSegment.Start,t),!0;if(!this.MoveNext())return!1;if(this.CurrentSegment.ContainsPoint(t))return!0;if(L.IsPureLower(t,this.CurrentSegment.Start))return this.CurrentSegment.Update(t,this.CurrentSegment.End),!0}}MoveNext(){return this.CurrentSegment=this.CurrentSegment.NextSegment,this.HasCurrent}get HasCurrent(){return this.CurrentSegment!=null}PointIsCurrentEndAndNextStart(t){return t.equal(this.CurrentSegment.End)&&this.CurrentSegment.NextSegment!=null&&t.equal(this.CurrentSegment.NextSegment.Start)}AddPerpendicularCoord(t){const e=this.IsHorizontal?new c(t,this.Coord):new c(this.Coord,t);this.TraverseToSegmentContainingPoint(e),this.CurrentSegment.AddSparseVertexCoord(t)}toString(){return this.FirstSegment==null?"-0- "+this.Coord:this.IsHorizontal?"(H) Y === "+this.Coord:"(V) X === "}AppendScanSegment(t){this.FirstSegment==null?this.FirstSegment=t:this.CurrentSegment.NextSegment=t,this.CurrentSegment=t}AddPendingPerpendicularCoordsToScanSegments(){if(this.pendingPerpCoords!=null){this.ResetForIntersections();for(const t of this.pendingPerpCoords)this.AddPerpendicularCoord(t)}}}class da{constructor(t,e){this.CurrentSlotIndex=0,this.vector=[],this.IsHorizontal=e;const i=Array.from(t).sort((s,n)=>s>n?1:s<n?-1:0);for(const s of i)this.vector.push(new Fl(s))}get Length(){return this.vector.length}get CurrentSlot(){return this.vector[this.CurrentSlotIndex]}Item(t){return this.vector[t]}CreateScanSegment(t,e,i,s){this.CurrentSlot.AppendScanSegment(new mt(t,e,i,s))}ScanSegmentsCompleteForCurrentSlot(){this.CurrentSlotIndex++}ScanSegmentsComplete(){for(const t of this.vector)t.AddPendingPerpendicularCoordsToScanSegments()}Items(){return this.vector}ResetForIntersections(){for(const t of this.vector)t.ResetForIntersections()}FindNearest(t,e){let i=0,s=this.vector.length-1;if(t<=this.vector[i].Coord)return i;if(t>=this.vector[s].Coord)return s;for(;s-i>2;){const n=i+(s-i>>1),o=this.vector[n];if(t<o.Coord){s=n;continue}if(t>o.Coord){i=n;continue}return n}for(i++;i<=s;i++){const n=this.vector[i];if(t<n.Coord)return e>0?i:i-1;if(t===n.Coord)break}return i}CreateSparseVerticesAndEdges(t){for(const e of this.vector){e.ResetForIntersections();for(let i=e.FirstSegment;i!=null;i=i.NextSegment)i.CreateSparseVerticesAndEdges(t)}}GetParallelCoord(t){return this.IsHorizontal?t.y:t.x}GetPerpendicularCoord(t){return this.IsHorizontal?t.x:t.y}ConnectAdjoiningSegmentEndpoints(){for(const t of this.vector){t.ResetForIntersections();let e=t.FirstSegment;for(let i=e.NextSegment;i!=null;i=i.NextSegment){if(i.HasSparsePerpendicularCoords&&e.HasSparsePerpendicularCoords&&i.Start===e.End){const s=this.GetPerpendicularCoord(i.Start);e.AddSparseEndpoint(s),i.AddSparseEndpoint(s)}e=i}}}toString(){return(this.IsHorizontal?"(H) count":"(V) count === ")+this.vector.length}}class Ws extends ai{constructor(t,e,i){super(),this.InitialObstacle=t,this.ReflectingObstacle=e,this.site=i}static mk(t,e,i){const s=new Ws(t.ReflectingObstacle,e,i);return s.PreviousSite=t,s}IsStaircaseStep(t){return this.InitialObstacle===t}get Site(){return this.site}}class ga{constructor(){this.eventTree=new kn((t,e)=>this.Compare(t,e))}Reset(t){this.scanDirection=t}Enqueue(t){this.eventTree.Enqueue(t)}Dequeue(){return this.eventTree.Dequeue()}get Count(){return this.eventTree.Count}Compare(t,e){if(t===e)return 0;if(t==null)return-1;if(e==null)return 1;let i=this.scanDirection.ComparePerpCoord(t.Site,e.Site);if(i)return i;const s=t instanceof Ws?0:1,n=e instanceof Ws?0:1;return i=s-n,i||this.scanDirection.CompareScanCoord(t.Site,e.Site)}}class fa{constructor(){this.pointCrossingMap=new je,this.pointList=new Array}AddIntersection(t,e,i){let s=this.pointCrossingMap.get(t);s||(s=new Array,this.pointCrossingMap.set(t,s));const n=s.length;for(let a=0;a<n;a++){const h=s[a];if(h.Group===e)return h}const o=new bo(e,i);return s.push(o),o}Clear(){this.pointCrossingMap.clear()}GetOrderedListBetween(t,e){if(this.pointCrossingMap.size===0)return null;if(L.ComparePP(t,e)>0){const n=t;t=e,e=n}this.pointList=[];for(const n of this.pointCrossingMap.keys())L.ComparePP(n,t)>=0&&L.ComparePP(n,e)<=0&&this.pointList.push(n);this.pointList.sort((n,o)=>n.compareTo(o));const i=new Yn,s=this.pointList.length;for(let n=0;n<s;n++){const o=this.pointList[n];i.Add(o,this.pointCrossingMap.get(o))}return i}toString(){return ue.Qf.format("{0}",this.pointCrossingMap.size)}}class pa extends Ws{constructor(t,e,i){super(t.ReflectingObstacle,e.Obstacle,i),this.Side=e}}class Dl{constructor(t){this.staleSites=new Array,this.scanDirection=t,this.eventTree=new Me((e,i)=>this.CompareBB(e,i)),this.findFirstPred=e=>this.CompareToFindFirstPoint(e.Site)>=0}Add(t){this.eventTree.insert(t)}MarkStaleSite(t){this.staleSites.push(t)}RemoveStaleSites(){const t=this.staleSites.length;if(t>0){for(let e=0;e<t;e++)this.RemoveExact(this.staleSites[e]);this.staleSites=[]}}RemoveSitesForFlatBottom(t,e){for(let i=this.FindFirstInRange(t,e);i!=null;i=this.FindNextInRange(i,e))this.MarkStaleSite(i.item);this.RemoveStaleSites()}Find(t){return this.FindFirstInRange(t,t)}RemoveExact(t){const e=this.eventTree.find(t);return e!=null&&e.item.Site===t.Site?(this.eventTree.deleteNodeInternal(e),!0):!1}FindFirstInRange(t,e){this.findFirstPoint=t;const i=this.eventTree.findFirst(this.findFirstPred);return i!=null&&this.Compare(i.item.Site,e)<=0?i:null}CompareToFindFirstPoint(t){return this.Compare(t,this.findFirstPoint)}FindNextInRange(t,e){const i=this.eventTree.next(t);return i!=null&&this.Compare(i.item.Site,e)<=0?i:null}CompareBB(t,e){return this.scanDirection.CompareScanCoord(t.Site,e.Site)}Compare(t,e){return this.scanDirection.CompareScanCoord(t,e)}}class ma extends Qr{constructor(t,e){super(t,e)}}class Pa extends Qr{constructor(t,e){super(t,e)}}class Sa extends Qr{constructor(t,e){super(t,e)}}class ya extends Ws{constructor(t,e,i){super(t.ReflectingObstacle,e.obstacle,i),this.Side=e}}class Ca{get LowNeighborSide(){return this.LowNeighbor==null?null:this.LowNeighbor.item}get HighNeighborSide(){return this.HighNeighbor==null?null:this.HighNeighbor.item}Clear(){this.LowNeighbor=null,this.LowOverlapEnd=null,this.GroupSideInterveningBeforeLowNeighbor=null,this.HighNeighbor=null,this.HighOverlapEnd=null,this.GroupSideInterveningBeforeHighNeighbor=null}SetSides(t,e,i,s){if(Z.IsAscending(t)){this.HighNeighbor=e,this.HighOverlapEnd=i,this.GroupSideInterveningBeforeHighNeighbor=s;return}this.LowNeighbor=e,this.LowOverlapEnd=i,this.GroupSideInterveningBeforeLowNeighbor=s}}class Ii{has(t){return this.hasxy(t.x,t.y)}remove(t){if(!(t.x<0||t.x>=this.arrayOfSets.length))return this.arrayOfSets[t.x].delete(t.y)}hasxy(t,e){if(t<0||t>=this.arrayOfSets.length)return!1;const i=this.arrayOfSets[t];return i!==void 0&&i.has(e)}constructor(){this.arrayOfSets=new Array}static mk(t){const e=new Ii;for(const i of t)e.add(i);return e}*values(){for(let t=0;t<this.arrayOfSets.length;t++){const e=this.arrayOfSets[t];if(e)for(const i of e.values())yield new Et(t,i)}}add(t){let e=this.arrayOfSets[t.x];e==null&&(this.arrayOfSets[t.x]=e=new Set),e.add(t.y)}addNN(t,e){let i=this.arrayOfSets[t];i==null&&(this.arrayOfSets[t]=i=new Set),i.add(e)}clear(){for(const t of this.arrayOfSets)t&&t.clear()}}class Aa{constructor(t,e){this.Polyline=t,this.Obstacles=Array.from(e),this.PrimaryObstacle=this.Obstacles[0],ge.RoundVerticesAndSimplify(this.Polyline)}}class fn{static MungeClosestIntersectionInfo(t,e,i){const s=e.seg1.boundingBox,n=c.RoundPoint(e.x).clone();return i?new c(fn.MungeIntersect(t.x,n.x,s.left,s.right),n.y):new c(n.x,fn.MungeIntersect(t.y,n.y,s.bottom,s.top))}static MungeIntersect(t,e,i,s){if(t<e){const n=Math.min(i,s);e<n&&(e=n)}else if(t>e){const n=Math.max(i,s);e>n&&(e=n)}return c.RoundDouble(e)}}class te{constructor(){this.CurrentGroupBoundaryCrossingMap=new fa,this.overlapPairs=new Ii,this.hasOverlaps=!1,this.lookupIntPair=new Et(-1,-1)}get GraphBox(){return this.Root.irect}Init(t,e,i){this.CreateObstacleListAndOrdinals(t),this.AncestorSets=e,this.CreateRoot(),this.shapeIdToObstacleMap=i}CreateObstacleListAndOrdinals(t){this.allObstacles=Array.from(t);let e=ge.FirstNonSentinelOrdinal;for(const i of this.allObstacles)i.Ordinal=e++}OrdinalToObstacle(t){return this.allObstacles[t-ge.FirstNonSentinelOrdinal]}CreateRoot(){this.Root=te.CalculateHierarchy(this.GetAllObstacles()),this.OverlapsExist()&&(this.AccreteClumps(),this.AccreteConvexHulls(),this.GrowGroupsToAccommodateOverlaps(),this.Root=te.CalculateHierarchy(this.GetAllObstacles().filter(t=>t.IsPrimaryObstacle)))}OverlapsExist(){return this.Root==null?!1:(pe(this.Root,this.Root,(t,e)=>this.CheckForInitialOverlaps(t,e)),this.hasOverlaps)}OverlapPairAlreadyFound(t,e){return this.lookupIntPair.x=e.Ordinal,this.lookupIntPair.y=t.Ordinal,this.overlapPairs.has(this.lookupIntPair)}CheckForInitialOverlaps(t,e){if(this.hasOverlaps)return;const i={bIsInsideA:!1,aIsInsideB:!1};if(te.ObstaclesIntersect(t,e,i)){this.hasOverlaps=!0;return}!i.aIsInsideB&&!i.bIsInsideA||t.IsGroup&&e.IsGroup||t.IsGroup&&i.bIsInsideA||e.IsGroup&&i.aIsInsideB||(this.hasOverlaps=!0)}AccreteClumps(){this.AccumulateObstaclesForClumps(),this.CreateClumps()}AccreteConvexHulls(){for(;;)if(this.AccumulateObstaclesForConvexHulls(),!this.CreateConvexHulls())return}static CalculateHierarchy(t){const e=Array.from(t).map(i=>he(i,i.VisibilityBoundingBox));return $t(e)}AccumulateObstaclesForClumps(){this.overlapPairs.clear();const t=te.CalculateHierarchy(this.GetAllObstacles().filter(e=>!e.IsGroup&&e.IsRectangle));t!=null&&Te(t,t,(e,i)=>this.EvaluateOverlappedPairForClump(e,i))}EvaluateOverlappedPairForClump(t,e){if(t===e||this.OverlapPairAlreadyFound(t,e))return;const i={bIsInsideA:!1,aIsInsideB:!1};!te.ObstaclesIntersect(t,e,i)&&!i.aIsInsideB&&!i.bIsInsideA||this.overlapPairs.add(new Et(t.Ordinal,e.Ordinal))}AccumulateObstaclesForConvexHulls(){this.overlapPairs.clear();const t=te.CalculateHierarchy(this.GetAllObstacles().filter(e=>e.IsPrimaryObstacle&&!e.IsGroup));t!=null&&Te(t,t,(e,i)=>this.EvaluateOverlappedPairForConvexHull(e,i))}EvaluateOverlappedPairForConvexHull(t,e){if(t===e||this.OverlapPairAlreadyFound(t,e))return;const i={bIsInsideA:!1,aIsInsideB:!1};!te.ObstaclesIntersect(t,e,i)&&!i.aIsInsideB&&!i.bIsInsideA||!t.IsInConvexHull&&!e.IsInConvexHull&&t.IsRectangle&&e.IsRectangle||(this.overlapPairs.add(new Et(t.Ordinal,e.Ordinal)),this.AddClumpToConvexHull(t),this.AddClumpToConvexHull(e),this.AddConvexHullToConvexHull(t),this.AddConvexHullToConvexHull(e))}GrowGroupsToAccommodateOverlaps(){for(;;)if(this.AccumulateObstaclesForGroupOverlaps(),!this.GrowGroupsToResolveOverlaps())return}AccumulateObstaclesForGroupOverlaps(){const t=te.CalculateHierarchy(this.GetAllObstacles().filter(i=>i.IsGroup)),e=te.CalculateHierarchy(this.GetAllObstacles().filter(i=>i.IsPrimaryObstacle));t==null||e==null||Te(t,e,(i,s)=>this.EvaluateOverlappedPairForGroup(i,s))}EvaluateOverlappedPairForGroup(t,e){if(t===e||this.OverlapPairAlreadyFound(t,e))return;const i={bIsInsideA:!1,aIsInsideB:!1},s=te.ObstaclesIntersect(t,e,i);if(!(!s&&!i.aIsInsideB&&!i.bIsInsideA)){if(t.IsRectangle&&e.IsRectangle){e.IsGroup||(i.aIsInsideB||te.FirstRectangleContainsACornerOfTheOther(e.VisibilityBoundingBox,t.VisibilityBoundingBox))&&(e.OverlapsGroupCorner=!0);return}!s&&(e.IsGroup||i.bIsInsideA)||this.overlapPairs.add(new Et(t.Ordinal,e.Ordinal))}}static FirstRectangleContainsACornerOfTheOther(t,e){return t.contains(e.leftBottom)||t.contains(e.leftTop)||t.contains(e.rightTop)||t.contains(e.rightBottom)}static FirstPolylineStartIsInsideSecondPolyline(t,e){return w.PointRelativeToCurveLocation(t.start,e)!==at.Outside}AddClumpToConvexHull(t){if(t.isOverlapped){for(const e of t.clump.filter(i=>i.Ordinal!==t.Ordinal))this.overlapPairs.add(new Et(t.Ordinal,e.Ordinal));t.clump=[]}}AddConvexHullToConvexHull(t){if(t.IsInConvexHull){for(const e of t.ConvexHull.Obstacles.filter(i=>i.Ordinal!==t.Ordinal))this.overlapPairs.add(new Et(t.Ordinal,e.Ordinal));t.ConvexHull.Obstacles=[]}}CreateClumps(){const t=Rs(Array.from(this.overlapPairs.values())),e=Ci(t);for(const i of e){if(i.length===1)continue;const s=i.map(n=>this.OrdinalToObstacle(n));for(const n of s)n.clump=s}}CreateConvexHulls(){let t=!1;const e=Rs(Array.from(this.overlapPairs.values())),i=Ci(e);for(const s of i){if(s.length===1)continue;t=!0;const n=s.map(this.OrdinalToObstacle),o=ws(n,h=>h.VisibilityPolyline),a=new Aa(gt.createConvexHullAsClosedPolyline(o),n);for(const h of n)h.SetConvexHull(a)}return t}GrowGroupsToResolveOverlaps(){let t=!1;for(const e of this.overlapPairs.values()){t=!0;const i=this.OrdinalToObstacle(e.x),s=this.OrdinalToObstacle(e.y);te.ResolveGroupAndGroupOverlap(i,s)||te.ResolveGroupAndObstacleOverlap(i,s)}return this.overlapPairs.clear(),t}static ResolveGroupAndGroupOverlap(t,e){return e.IsGroup?(t.VisibilityPolyline.boundingBox.area>e.VisibilityPolyline.boundingBox.area?te.ResolveGroupAndObstacleOverlap(t,e):te.ResolveGroupAndObstacleOverlap(e,t),!0):!1}static ResolveGroupAndObstacleOverlap(t,e){let i=e.looseVisibilityPolyline;te.GrowGroupAroundLoosePolyline(t,i);const s={bIsInsideA:!1,aIsInsideB:!1};for(;te.ObstaclesIntersect(e,t,s)||!s.aIsInsideB;)i=ge.CreateLoosePolyline(i),te.GrowGroupAroundLoosePolyline(t,i)}static GrowGroupAroundLoosePolyline(t,e){const i=Array.from(t.VisibilityPolyline).concat(Array.from(e));t.SetConvexHull(new Aa(gt.createConvexHullAsClosedPolyline(i),[t]))}static ObstaclesIntersect(t,e,i){return w.CurvesIntersect(t.VisibilityPolyline,e.VisibilityPolyline)?(i.aIsInsideB=!1,i.bIsInsideA=!1,!0):(i.aIsInsideB=te.FirstPolylineStartIsInsideSecondPolyline(t.VisibilityPolyline,e.VisibilityPolyline),i.bIsInsideA=!i.aIsInsideB&&te.FirstPolylineStartIsInsideSecondPolyline(e.VisibilityPolyline,t.VisibilityPolyline),t.IsRectangle&&e.IsRectangle?!1:te.ObstaclesAreCloseEnoughToBeConsideredTouching(t,e,i.aIsInsideB,i.bIsInsideA)?(i.aIsInsideB=!1,i.bIsInsideA=!1,!0):!1)}static ObstaclesAreCloseEnoughToBeConsideredTouching(t,e,i,s){if(!i&&!s)return w.CurvesIntersect(t.looseVisibilityPolyline,e.VisibilityPolyline);const n=i?t.looseVisibilityPolyline:e.looseVisibilityPolyline,o=i?e.VisibilityPolyline:t.VisibilityPolyline;for(const a of n)if(w.PointRelativeToCurveLocation(a,o)===at.Outside){const h=w.ClosestPoint(o,a);if(!c.closeIntersections(a,h))return!0}return!1}AdjustSpatialAncestors(){if(this.SpatialAncestorsAdjusted)return!1;for(const e of this.GetAllGroups()){const i=e.VisibilityBoundingBox;for(const s of this.Root.GetNodeItemsIntersectingRectangle(i))if(s!==e&&w.ClosedCurveInteriorsIntersect(s.VisibilityPolyline,e.VisibilityPolyline)){if(s.IsInConvexHull)for(const n of s.ConvexHull.Obstacles)this.AncestorSets.get(n.InputShape).add(e.InputShape);this.AncestorSets.get(s.InputShape).add(e.InputShape)}}let t=new Array;for(const e of this.Root.GetAllLeaves()){const i=e.VisibilityBoundingBox;t=t.concat(Array.from(this.AncestorSets.get(e.InputShape)).filter(s=>!i.intersects(this.shapeIdToObstacleMap.get(s).VisibilityBoundingBox)));for(const s of t)this.AncestorSets.get(e.InputShape).delete(s);t=[]}return this.SpatialAncestorsAdjusted=!0,!0}GetAllGroups(){return this.GetAllObstacles().filter(t=>t.IsGroup)}Clear(){this.Root=null,this.AncestorSets=null}CreateMaxVisibilitySegment(t,e,i){const s=Z.RectangleBorderIntersect(this.GraphBox,t,e);if(L.GetDirections(t,s)===v.None)return i.pacList=null,N.mkPP(t,t);const n=this.RestrictSegmentWithObstacles(t,s);return i.pacList=this.CurrentGroupBoundaryCrossingMap.GetOrderedListBetween(n.start,n.end),n}GetAllObstacles(){return this.allObstacles}GetAllPrimaryObstacles(){return this.Root.GetAllLeaves()}IntersectionIsInsideAnotherObstacle(t,e,i,s){return this.insideHitTestIgnoreObstacle1=e,this.insideHitTestIgnoreObstacle2=t,this.insideHitTestScanDirection=s,this.Root.FirstHitNodeWithPredicate(i,this.InsideObstacleHitTest.bind(this))!=null}PointIsInsideAnObstaclePD(t,e){return this.PointIsInsideAnObstacle(t,_t.GetInstance(e))}PointIsInsideAnObstacle(t,e){return this.insideHitTestIgnoreObstacle1=null,this.insideHitTestIgnoreObstacle2=null,this.insideHitTestScanDirection=e,this.Root.FirstHitNodeWithPredicate(t,this.InsideObstacleHitTest.bind(this))!=null}InsideObstacleHitTest(t,e){if(e===this.insideHitTestIgnoreObstacle1||e===this.insideHitTestIgnoreObstacle2||e.IsGroup||!Z.PointIsInRectangleInterior(t,e.VisibilityBoundingBox))return Nt.Continue;const i=Z.RectangleBorderIntersect(e.VisibilityBoundingBox,t,this.insideHitTestScanDirection.dir).add(this.insideHitTestScanDirection.DirectionAsPoint),s=Z.RectangleBorderIntersect(e.VisibilityBoundingBox,t,this.insideHitTestScanDirection.OppositeDirection).sub(this.insideHitTestScanDirection.DirectionAsPoint),n=N.mkPP(s,i),o=w.getAllIntersections(n,e.VisibilityPolyline,!0);if(o.length===2){const a=c.RoundPoint(o[0].x),h=c.RoundPoint(o[1].x);if(!L.EqualPP(t,a)&&!L.EqualPP(t,h)&&t.compareTo(a)!==t.compareTo(h)&&!R(Math.floor(o[0].par1),Math.floor(o[1].par1)))return Nt.Stop}return Nt.Continue}SegmentCrossesAnObstacle(t,e){this.stopAtGroups=!0,this.wantGroupCrossings=!1;const i=this.RestrictSegmentPrivate(t,e);return!L.EqualPP(i.end,e)}SegmentCrossesANonGroupObstacle(t,e){this.stopAtGroups=!1,this.wantGroupCrossings=!1;const i=this.RestrictSegmentPrivate(t,e);return!L.EqualPP(i.end,e)}RestrictSegmentWithObstacles(t,e){return this.stopAtGroups=!1,this.wantGroupCrossings=!0,this.RestrictSegmentPrivate(t,e)}RestrictSegmentPrivate(t,e){return this.GetRestrictedIntersectionTestSegment(t,e),this.currentRestrictedRay=N.mkPP(t,e),this.restrictedRayLengthSquared=t.sub(e).lengthSquared,this.CurrentGroupBoundaryCrossingMap.Clear(),this.RecurseRestrictRayWithObstacles(this.Root),this.currentRestrictedRay}GetRestrictedIntersectionTestSegment(t,e){const i=L.GetDirections(t,e),s=v.West===i?this.GraphBox.right:v.East===i?this.GraphBox.left:t.x,n=v.West===i?this.GraphBox.left:v.East===i?this.GraphBox.right:e.x,o=v.South===i?this.GraphBox.top*2:v.North===i?this.GraphBox.bottom:t.y,a=v.South===i?this.GraphBox.bottom:v.North===i?this.GraphBox.top:t.y;this.restrictedIntersectionTestSegment=N.mkPP(new c(s,o),new c(n,a))}RecurseRestrictRayWithObstacles(t){if(!Z.RectangleInteriorsIntersect(this.currentRestrictedRay.boundingBox,t.irect))return;const e=t.UserData;if(e!=null){const i=w.getAllIntersections(this.restrictedIntersectionTestSegment,e.VisibilityPolyline,!0);if(!e.IsGroup||this.stopAtGroups){this.LookForCloserNonGroupIntersectionToRestrictRay(i);return}this.wantGroupCrossings&&this.AddGroupIntersectionsToRestrictedRay(e,i);return}this.RecurseRestrictRayWithObstacles(t.Left),this.RecurseRestrictRayWithObstacles(t.Right)}LookForCloserNonGroupIntersectionToRestrictRay(t){let e=0,i=null,s=this.restrictedRayLengthSquared;const n=L.GetDirections(this.restrictedIntersectionTestSegment.start,this.restrictedIntersectionTestSegment.end);for(const o of t){const a=c.RoundPoint(o.x),h=L.GetDirections(this.currentRestrictedRay.start,a);if(h===j.OppositeDir(n))continue;if(e++,v.None===h){s=0,i=o;continue}const u=a.sub(this.currentRestrictedRay.start).lengthSquared;if(u<s){if(o.x.sub(this.currentRestrictedRay.start).lengthSquared<C.squareOfDistanceEpsilon)continue;s=u,i=o}}if(i!=null){if(e===1){const o=c.RoundPoint(i.x);if(c.closeIntersections(o,this.currentRestrictedRay.start)||c.closeIntersections(o,this.currentRestrictedRay.end))return}this.restrictedRayLengthSquared=s,this.currentRestrictedRay.end=fn.MungeClosestIntersectionInfo(this.currentRestrictedRay.start,i,!Z.IsVerticalPP(this.currentRestrictedRay.start,this.currentRestrictedRay.end))}}AddGroupIntersectionsToRestrictedRay(t,e){for(const i of e){const s=c.RoundPoint(i.x);if(s.sub(this.currentRestrictedRay.start).lengthSquared>this.restrictedRayLengthSquared)continue;const o=L.GetDirections(this.currentRestrictedRay.start,this.currentRestrictedRay.end),a=i.seg1,h=j.VectorDirection(a.derivative(i.par1));let u=o;(h&j.RotateRight(o))!==0&&(u=j.OppositeDir(u)),this.CurrentGroupBoundaryCrossingMap.AddIntersection(s,t,u)}}}class Rl{constructor(t,e){this.scanDirection=t,this.SideTree=new Me((i,s)=>this.Compare(i,s)),this.linePositionAtLastInsertOrRemove=e}Insert(t,e){return this.linePositionAtLastInsertOrRemove=e,this.SideTree.insert(t)}get Count(){return this.SideTree.count}Remove(t,e){this.linePositionAtLastInsertOrRemove=e,this.SideTree.remove(t)}Find(t){return this.scanDirection.ComparePerpCoord(this.linePositionAtLastInsertOrRemove,t.Start)===-1?null:this.SideTree.find(t)}NextLowB(t){return this.NextLowR(this.Find(t))}NextLowR(t){return this.SideTree.previous(t)}NextHighB(t){return this.NextHighR(this.Find(t))}NextHighR(t){return this.SideTree.next(t)}Next(t,e){return Z.IsAscending(t)?this.SideTree.next(e):this.SideTree.previous(e)}Lowest(){return this.SideTree.treeMinimum()}Compare(t,e){if(t.Obstacle===e.Obstacle)return t===e?0:t instanceof vi?-1:1;const i=ee.ScanLineIntersectSidePBS(this.linePositionAtLastInsertOrRemove,t,this.scanDirection),s=ee.ScanLineIntersectSidePBS(this.linePositionAtLastInsertOrRemove,e,this.scanDirection);let n=i.compareTo(s);if(n===0){const o=t instanceof vi,a=e instanceof vi;n=f(o,a),n===0&&(n=k(t.Obstacle.Ordinal,e.Obstacle.Ordinal))}return n}}class Xr{constructor(t){this.lookupSegment=mt.mk(new c(0,0),new c(0,1)),this.ScanDirection=t,this.segmentTree=new Me((e,i)=>this.Compare(e,i)),this.findIntersectorPred=e=>this.CompareIntersector(e),this.findPointPred=e=>this.CompareToPoint(e)}get Segments(){return this.segmentTree.allNodes()}InsertUnique(t){this.AssertValidSegmentForInsertion(t);const e=this.segmentTree.find(t);return e??this.segmentTree.insert(t)}AssertValidSegmentForInsertion(t){}Remove(t){this.segmentTree.remove(t)}Find(t,e){this.lookupSegment.Update(t,e);const i=this.segmentTree.find(this.lookupSegment);return i!=null&&L.EqualPP(i.item.End,e)?i.item:null}FindLowestIntersector(t,e){const i=this.FindLowestIntersectorNode(t,e);return i!=null?i.item:null}FindLowestIntersectorNode(t,e){this.lookupSegment.Update(t,t);let i=this.segmentTree.findLast(this.findIntersectorPred);if(L.EqualPP(t,e))i!=null&&this.ScanDirection.Compare(i.item.End,t)<0&&(i=null);else for(this.lookupSegment.Update(t,e);i!=null&&!i.item.IntersectsSegment(this.lookupSegment);){if(this.ScanDirection.Compare(i.item.Start,e)>0)return null;i=this.segmentTree.next(i)}return i}FindHighestIntersector(t,e){this.lookupSegment.Update(e,e);let i=this.segmentTree.findLast(this.findIntersectorPred);if(L.EqualPP(t,e))i!=null&&this.ScanDirection.Compare(i.item.End,t)<0&&(i=null);else for(this.lookupSegment.Update(t,e);i!=null&&!i.item.IntersectsSegment(this.lookupSegment);){if(this.ScanDirection.Compare(i.item.End,t)<0)return null;i=this.segmentTree.previous(i)}return i!=null?i.item:null}CompareIntersector(t){return this.ScanDirection.Compare(t.Start,this.lookupSegment.Start)<=0}FindSegmentContainingPoint(t,e){return this.FindSegmentOverlappingPoints(t,t,e)}FindSegmentOverlappingPoints(t,e,i){this.lookupSegment.Update(t,e);const s=this.segmentTree.findFirst(this.findPointPred);if(s!=null){const n=s.item;if(this.ScanDirection.Compare(n.Start,e)<=0)return n}return null}CompareToPoint(t){return this.ScanDirection.Compare(t.End,this.lookupSegment.Start)>=0}MergeAndRemoveNextNode(t,e){return this.ScanDirection.Compare(t.End,e.item.End)===-1&&t.Update(t.Start,e.item.End),t.MergeGroupBoundaryCrossingList(e.item.GroupBoundaryPointAndCrossingsList),this.segmentTree.deleteNodeInternal(e),this.segmentTree.find(t)}MergeSegments(){if(this.segmentTree.count<2)return;let t=this.segmentTree.treeMinimum(),e=this.segmentTree.next(t);for(;e!=null;e=this.segmentTree.next(t))switch(this.ScanDirection.Compare(e.item.Start,t.item.End)){case 1:t=e;break;case 0:e.item.IsOverlapped===t.item.IsOverlapped?t=this.MergeAndRemoveNextNode(t.item,e):(t.item.NeedEndOverlapVertex=!0,e.item.NeedStartOverlapVertex=!0,t=e);break;default:if(t.item.IsOverlapped!==e.item.IsOverlapped){if(t.item.IsOverlapped)t.item.Start===e.item.Start?t=this.MergeAndRemoveNextNode(e.item,t):(t.item.Update(t.item.Start,e.item.Start),t=e);else if(t.item.End===e.item.End)t=this.MergeAndRemoveNextNode(t.item,e);else{const s=e.item,n=t.item;this.segmentTree.deleteNodeInternal(e),s.Update(n.End,s.End),this.segmentTree.insert(s),s.TrimGroupBoundaryCrossingList(),t=this.segmentTree.find(n)}break}t=this.MergeAndRemoveNextNode(t.item,e);break}}Compare(t,e){if(t===e)return 0;if(t==null)return-1;if(e==null)return 1;let i=this.ScanDirection.Compare(t.Start,e.Start);return i===0&&(i=this.ScanDirection.Compare(t.End,e.End)*-1),i}}class Nl extends ki{constructor(t){super(t)}SetVertexEntry(t){this.VertexEntries==null&&(this.VertexEntries=new Array(4)),this.VertexEntries[j.ToIndex(t.Direction)]=t}RemoveVertexEntries(){this.VertexEntries=null}}class ee{constructor(t){this.ObstacleTree=new te,this.CurrentGroupBoundaryCrossingMap=new fa,this.LowNeighborSides=new Ca,this.HighNeighborSides=new Ca,this.ScanDirection=_t.HorizontalInstance,this.eventQueue=new ga,this.HorizontalScanSegments=new Xr(_t.HorizontalInstance),this.VerticalScanSegments=new Xr(_t.VerticalInstance),this.wantReflections=t}get ParallelScanSegments(){return this.ScanDirection.IsHorizontal?this.HorizontalScanSegments:this.VerticalScanSegments}get PerpendicularScanSegments(){return this.ScanDirection.IsHorizontal?this.VerticalScanSegments:this.HorizontalScanSegments}static NewVisibilityGraph(){const t=new Xt;return t.VertexFactory=e=>new Nl(e),t}GenerateVisibilityGraph(){if(this.ObstacleTree.Root==null)return;this.InitializeEventQueue(_t.HorizontalInstance);let t=ge.FirstSentinelOrdinal,e=new c(this.ObstacleTree.GraphBox.left-ee.SentinelOffset,this.ObstacleTree.GraphBox.bottom-ee.SentinelOffset),i=new c(this.ObstacleTree.GraphBox.left-ee.SentinelOffset,this.ObstacleTree.GraphBox.top+ee.SentinelOffset),s=ge.CreateSentinel(e,i,this.ScanDirection,t++);this.scanLine.Insert(s.ActiveHighSide,this.ObstacleTree.GraphBox.leftBottom),e=new c(this.ObstacleTree.GraphBox.right+ee.SentinelOffset,this.ObstacleTree.GraphBox.bottom-ee.SentinelOffset),i=new c(this.ObstacleTree.GraphBox.right+ee.SentinelOffset,this.ObstacleTree.GraphBox.top+ee.SentinelOffset),s=ge.CreateSentinel(e,i,this.ScanDirection,t++),this.scanLine.Insert(s.ActiveLowSide,this.ObstacleTree.GraphBox.leftBottom),this.ProcessEvents(),this.InitializeEventQueue(_t.VerticalInstance),e=new c(this.ObstacleTree.GraphBox.left-ee.SentinelOffset,this.ObstacleTree.GraphBox.bottom-ee.SentinelOffset),i=new c(this.ObstacleTree.GraphBox.right+ee.SentinelOffset,this.ObstacleTree.GraphBox.bottom-ee.SentinelOffset),s=ge.CreateSentinel(e,i,this.ScanDirection,t++),this.scanLine.Insert(s.ActiveHighSide,this.ObstacleTree.GraphBox.leftBottom),e=new c(this.ObstacleTree.GraphBox.left-ee.SentinelOffset,this.ObstacleTree.GraphBox.top+ee.SentinelOffset),i=new c(this.ObstacleTree.GraphBox.right+ee.SentinelOffset,this.ObstacleTree.GraphBox.top+ee.SentinelOffset),s=ge.CreateSentinel(e,i,this.ScanDirection,t),this.scanLine.Insert(s.ActiveLowSide,this.ObstacleTree.GraphBox.leftBottom),this.ProcessEvents()}static ScanLineIntersectSidePBS(t,e,i){const s=e.Direction;let n=e.Start.x,o=e.Start.y;return i.IsHorizontal?(n+=s.x/s.y*(t.y-e.Start.y),n=fn.MungeIntersect(t.x,n,e.Start.x,e.End.x),o=t.y):(n=t.x,o+=s.y/s.x*(t.x-e.Start.x),o=fn.MungeIntersect(t.y,o,e.Start.y,e.End.y)),new c(n,o)}GetOpenVertex(t){let e=t.startPoint,i=this.TraversePolylineForEvents(e),s=this.PointCompare(i.point,e.point);for(;;i=this.TraversePolylineForEvents(i)){const n=this.PointCompare(i.point,e.point);if(n<=0)e=i;else if(n>0&&s<=0)break;s=n}return e}TraversePolylineForEvents(t){return this.ScanDirection.IsHorizontal?t.nextOnPolyline:t.prevOnPolyline}InitializeEventQueue(t){this.ScanDirection=t,this.eventQueue.Reset(this.ScanDirection),this.EnqueueBottomVertexEvents(),this.scanLine=new Rl(this.ScanDirection,this.ObstacleTree.GraphBox.leftBottom),this.lookaheadScan=new Dl(this.ScanDirection)}EnqueueBottomVertexEvents(){for(const t of this.ObstacleTree.GetAllPrimaryObstacles()){const e=this.GetOpenVertex(t.VisibilityPolyline);this.eventQueue.Enqueue(new $r(t,e))}}IsFlat(t){return this.ScanDirection.IsFlatS(t)}IsPerpendicular(t){return this.ScanDirection.IsPerpendicularS(t)}ScanLineIntersectSide(t,e){return ee.ScanLineIntersectSidePBS(t,e,this.ScanDirection)}SideReflectsUpward(t){return t instanceof vi?this.ScanDirection.Coord(t.End)>this.ScanDirection.Coord(t.Start):this.ScanDirection.Coord(t.End)<this.ScanDirection.Coord(t.Start)}SideReflectsDownward(t){return t instanceof vi?this.ScanDirection.Coord(t.End)<this.ScanDirection.Coord(t.Start):this.ScanDirection.Coord(t.End)>this.ScanDirection.Coord(t.Start)}StoreLookaheadSite(t,e,i,s){if(this.wantReflections&&!this.IsPerpendicular(e)){if(!s&&!Z.PointIsInRectangleInterior(i,e.Obstacle.VisibilityBoundingBox))return;this.SideReflectsUpward(e)&&this.lookaheadScan.Find(i)==null&&this.lookaheadScan.Add(new Ws(t,e.Obstacle,i))}}LoadReflectionEvents(t){this.LoadReflectionEventsBB(t,t)}LoadReflectionEventsBB(t,e){if(t==null||this.SideReflectsUpward(t)||this.IsPerpendicular(t))return;const i=X.mkPP(t.Start,t.End),s=X.mkPP(e.Start,e.End);if(this.ScanDirection.IsHorizontal?!i.intersectsOnX(s):!i.intersectsOnY(s))return;const n=X.intersect(i,s),o=n.leftBottom,a=n.rightTop;let h=this.lookaheadScan.FindFirstInRange(o,a);for(;h!=null;){const u=ee.ScanLineIntersectSidePBS(h.item.Site,t,this.ScanDirection.PerpendicularInstance);this.ScanDirection.ComparePerpCoord(u,h.item.Site)>0?this.AddReflectionEvent(h.item,t,u):h.item.ReflectingObstacle!==t.Obstacle&&this.lookaheadScan.MarkStaleSite(h.item),h=this.lookaheadScan.FindNextInRange(h,a)}this.lookaheadScan.RemoveStaleSites()}AddPerpendicularReflectionSegment(t,e,i){if(this.lookaheadScan.RemoveExact(t.PreviousSite)){if(e==null)return!1;if(t.PreviousSite.IsStaircaseStep(t.ReflectingObstacle)){if(!Z.PointIsInRectangleInterior(t.Site,t.ReflectingObstacle.VisibilityBoundingBox)||!this.InsertPerpendicularReflectionSegment(t.PreviousSite.Site,t.Site))return!1;if(i!=null&&t.IsStaircaseStep(i.Obstacle))return this.ScanLineCrossesObstacle(t.Site,i.Obstacle)}}return!1}AddParallelReflectionSegment(t,e,i,s){{const n=this.ScanLineIntersectSide(s.Site,e??i),o=e!=null?n:s.Site,a=e!=null?s.Site:n;return e==null?e=this.scanLine.NextLowB(i).item:i=this.scanLine.NextHighB(e).item,this.InsertParallelReflectionSegment(o,a,t,e,i,s)}}AddReflectionEvent(t,e,i){const s=e;s!=null?this.eventQueue.Enqueue(new ya(t,s,i)):this.eventQueue.Enqueue(new pa(t,e,i))}AddSideToScanLine(t,e){const i=this.scanLine.Insert(t,e);return this.LoadReflectionEvents(t),i}RemoveSideFromScanLine(t,e){this.scanLine.Remove(t.item,e)}PointCompare(t,e){return this.ScanDirection.Compare(t,e)}Clear(){this.ObstacleTree.Clear(),this.eventQueue=new ga,this.HorizontalScanSegments=new Xr(_t.HorizontalInstance),this.VerticalScanSegments=new Xr(_t.VerticalInstance),this.VisibilityGraph=null}ProcessEvents(){for(;this.eventQueue.Count>0;){const t=this.eventQueue.Dequeue();t instanceof $r?this.ProcessEventO(t):t instanceof ma?this.ProcessEventLB(t):t instanceof Pa?this.ProcessEventHB(t):t instanceof Sa?this.ProcessEventCV(t):t instanceof ya?this.ProcessEventLR(t):t instanceof pa?this.ProcessEventHR(t):this.ProcessCustomEvent(t),this.LowNeighborSides.Clear(),this.HighNeighborSides.Clear()}}ProcessCustomEvent(t){}ScanLineCrossesObstacle(t,e){return this.ScanDirection.ComparePerpCoord(t,e.VisibilityBoundingBox.leftBottom)>0&&this.ScanDirection.ComparePerpCoord(t,e.VisibilityBoundingBox.rightTop)<0}FindInitialNeighborSides(t,e){e.lowNborSideNode=this.scanLine.NextLowR(t),e.highNborSideNode=this.scanLine.NextHighR(t)}FindNeighborsBRR(t,e,i){this.LowNeighborSides.Clear(),this.HighNeighborSides.Clear(),this.FindNeighbors(t,e,this.LowNeighborSides),this.FindNeighbors(t,i,this.HighNeighborSides)}FindNeighbors(t,e,i){const s=t instanceof $r?e.item.Start:e.item.End,n={lowNborSideNode:null,highNborSideNode:null};this.FindInitialNeighborSides(e,n),this.SkipToNeighbor(this.ScanDirection.OppositeDirection,e.item,s,n.lowNborSideNode,i),this.SkipToNeighbor(this.ScanDirection.Dir,e.item,s,n.highNborSideNode,i)}SkipToNeighbor(t,e,i,s,n){let o=null,a=null;for(;;s=this.scanLine.Next(t,s))if(s.item.Obstacle!==e.Obstacle){if(s.item.Obstacle.IsGroup){this.ProcessGroupSideEncounteredOnTraversalToNeighbor(s,i,t)&&a==null&&(a=s.item);continue}if(s.item instanceof Zn===Z.IsAscending(t)){this.ScanLineCrossesObstacle(i,s.item.Obstacle)&&(o=s,a=null);continue}break}n.SetSides(t,s,o,a)}ProcessGroupSideEncounteredOnTraversalToNeighbor(t,e,i){if(!this.ScanLineCrossesObstacle(e,t.item.Obstacle))return!1;const s=t.item instanceof vi===Z.IsAscending(i)?i:j.OppositeDir(i),n=this.ScanLineIntersectSide(e,t.item);return this.CurrentGroupBoundaryCrossingMap.AddIntersection(n,t.item.Obstacle,s),!0}FindNeighborsAndProcessVertexEvent(t,e,i){this.CurrentGroupBoundaryCrossingMap.Clear(),this.FindNeighborsBRR(i,t,e),this.ProcessVertexEvent(t,e,i),this.CurrentGroupBoundaryCrossingMap.Clear()}ProcessEventO(t){var e,i;const s=t.Obstacle;s.CreateInitialSides(t.Vertex,this.ScanDirection),this.AddSideToScanLine(s.ActiveLowSide,t.Site);const n=this.AddSideToScanLine(s.ActiveHighSide,t.Site),o=this.scanLine.Find(s.ActiveLowSide);this.FindNeighborsAndProcessVertexEvent(o,n,t);const a=(e=this.LowNeighborSides.GroupSideInterveningBeforeLowNeighbor)!==null&&e!==void 0?e:this.LowNeighborSides.LowNeighborSide;this.SideReflectsUpward(a)&&this.LoadReflectionEvents(s.ActiveLowSide);const h=(i=this.HighNeighborSides.GroupSideInterveningBeforeHighNeighbor)!==null&&i!==void 0?i:this.HighNeighborSides.HighNeighborSide;if(this.SideReflectsUpward(h)&&this.LoadReflectionEvents(s.ActiveHighSide),s.ActiveHighSide.Start!==s.ActiveLowSide.Start){const u=new Zn(s,t.Vertex,this.ScanDirection);this.lookaheadScan.RemoveSitesForFlatBottom(u.Start,u.End)}this.EnqueueLowBendVertexEvent(s.ActiveLowSide),this.EnqueueHighBendOrCloseVertexEvent(s.ActiveHighSide)}ProcessEventLB(t){const e=t.Obstacle,i=new vi(e,t.Vertex,this.ScanDirection);this.ScanDirection.ComparePerpCoord(i.End,i.Start)>0&&(this.RemoveSideFromScanLine(this.scanLine.Find(e.ActiveLowSide),t.Site),this.AddSideToScanLine(i,t.Site),e.ActiveLowSide=i,this.EnqueueLowBendVertexEvent(i))}EnqueueLowBendVertexEvent(t){this.eventQueue.Enqueue(new ma(t.Obstacle,t.EndVertex))}ProcessEventHB(t){const e=t.Obstacle,i=new Zn(e,t.Vertex,this.ScanDirection);this.RemoveSideFromScanLine(this.scanLine.Find(e.ActiveHighSide),t.Site);const s=this.AddSideToScanLine(i,t.Site);if(e.ActiveHighSide=i,this.EnqueueHighBendOrCloseVertexEvent(e.ActiveHighSide),this.wantReflections&&this.ScanDirection.IsHorizontal&&i.Start.x===e.VisibilityBoundingBox.right&&this.SideReflectsUpward(i)){const n=this.scanLine.NextHighR(s);n.item instanceof vi&&this.SideReflectsDownward(n.item)&&(!e.isOverlapped||!this.ObstacleTree.PointIsInsideAnObstacle(i.Start,this.ScanDirection))&&(this.StoreLookaheadSite(n.item.Obstacle,i,i.Start,!0),this.LoadReflectionEvents(n.item))}}EnqueueHighBendOrCloseVertexEvent(t){const e=t.Obstacle,i=this.ScanDirection.IsHorizontal?t.EndVertex.prevOnPolyline:t.EndVertex.nextOnPolyline;this.ScanDirection.ComparePerpCoord(i.point,t.End)>0?this.eventQueue.Enqueue(new Pa(e,t.EndVertex)):this.eventQueue.Enqueue(new Sa(e,t.EndVertex))}CreateCloseEventSegmentsAndFindNeighbors(t){const e=t.Obstacle;let i=this.scanLine.Find(e.ActiveLowSide),s=this.scanLine.Find(e.ActiveHighSide);if(this.scanLine.Compare(e.ActiveLowSide,e.ActiveHighSide)===1){const n=i;i=s,s=n}if(this.FindNeighborsAndProcessVertexEvent(i,s,t),this.wantReflections&&e.isOverlapped)for(let n=this.scanLine.NextHighR(i);n.item!==s.item;n=this.scanLine.NextHighR(n))this.LoadReflectionEvents(n.item);this.scanLine.Remove(e.ActiveLowSide,t.Site),this.scanLine.Remove(e.ActiveHighSide,t.Site)}ProcessEventCV(t){this.CreateCloseEventSegmentsAndFindNeighbors(t);const e=this.LowNeighborSides.LowNeighbor.item,i=this.HighNeighborSides.HighNeighbor.item,s=t.Obstacle;this.LoadReflectionEvents(e),this.LoadReflectionEvents(i),s.Close()}ProcessEventLR(t){const e=t.Side.Obstacle,i=this.scanLine.NextLowB(t.Side).item;this.AddPerpendicularReflectionSegment(t,t.Side,i)&&this.AddParallelReflectionSegment(e,i,null,t)&&this.LoadReflectionEvents(e.ActiveLowSide)}ProcessEventHR(t){const e=t.Side.Obstacle,i=this.scanLine.NextHighB(t.Side).item;this.AddPerpendicularReflectionSegment(t,t.Side,i)&&this.AddParallelReflectionSegment(e,null,i,t)&&this.LoadReflectionEvents(e.ActiveHighSide)}MakeInBoundsLocation(t){const e=Math.max(t.x,this.ObstacleTree.GraphBox.left),i=Math.max(t.y,this.ObstacleTree.GraphBox.bottom);return new c(Math.min(e,this.ObstacleTree.GraphBox.right),Math.min(i,this.ObstacleTree.GraphBox.top))}IsInBoundsV(t){return this.IsInBoundsP(t.point)}IsInBoundsP(t){return L.EqualPP(t,this.MakeInBoundsLocation(t))}}ee.SentinelOffset=1;class Je extends ee{constructor(){super(!1),this.horizontalVertexPoints=new Yt,this.verticalVertexPoints=new Yt,this.boundingBoxSteinerPoints=new Yt,this.xCoordAccumulator=new Set,this.yCoordAccumulator=new Set,this.horizontalCoordMap=new Map,this.verticalCoordMap=new Map}Clear(){super.Clear(),this.Cleanup()}Cleanup(){this.horizontalVertexPoints.clear(),this.verticalVertexPoints.clear(),this.boundingBoxSteinerPoints.clear(),this.xCoordAccumulator.clear(),this.yCoordAccumulator.clear(),this.horizontalCoordMap.clear(),this.verticalCoordMap.clear()}GenerateVisibilityGraph(){this.AccumulateVertexCoords(),this.CreateSegmentVectorsAndPopulateCoordinateMaps(),this.RunScanLineToCreateSegmentsAndBoundingBoxSteinerPoints(),this.GenerateSparseIntersectionsFromVertexPoints(),this.CreateScanSegmentTrees(),this.Cleanup()}AccumulateVertexCoords(){for(const t of this.ObstacleTree.GetAllObstacles())this.xCoordAccumulator.add(t.VisibilityBoundingBox.left),this.xCoordAccumulator.add(t.VisibilityBoundingBox.right),this.yCoordAccumulator.add(t.VisibilityBoundingBox.top),this.yCoordAccumulator.add(t.VisibilityBoundingBox.bottom)}CreateSegmentVectorsAndPopulateCoordinateMaps(){this.horizontalScanSegmentVector=new da(this.yCoordAccumulator,!0),this.verticalScanSegmentVector=new da(this.xCoordAccumulator,!1);for(let t=0;t<this.horizontalScanSegmentVector.Length;t++)this.horizontalCoordMap.set(this.horizontalScanSegmentVector.Item(t).Coord,t);for(let t=0;t<this.verticalScanSegmentVector.Length;t++)this.verticalCoordMap.set(this.verticalScanSegmentVector.Item(t).Coord,t)}RunScanLineToCreateSegmentsAndBoundingBoxSteinerPoints(){super.GenerateVisibilityGraph(),this.horizontalScanSegmentVector.ScanSegmentsComplete(),this.verticalScanSegmentVector.ScanSegmentsComplete(),this.xCoordAccumulator.clear(),this.yCoordAccumulator.clear()}InitializeEventQueue(t){super.InitializeEventQueue(t),this.SetVectorsAndCoordMaps(t),this.AddAxisCoordinateEvents(t)}AddAxisCoordinateEvents(t){if(t.IsHorizontal){for(const e of this.yCoordAccumulator)this.eventQueue.Enqueue(new wo(new c(this.ObstacleTree.GraphBox.left-Je.SentinelOffset,e)));return}for(const e of this.xCoordAccumulator)this.eventQueue.Enqueue(new wo(new c(e,this.ObstacleTree.GraphBox.bottom-Je.SentinelOffset)))}ProcessCustomEvent(t){this.ProcessAxisCoordinate(t)||this.ProcessCustomEvent(t)}ProcessAxisCoordinate(t){return t instanceof wo?(this.CreateScanSegmentsOnAxisCoordinate(t.Site),!0):!1}InsertPerpendicularReflectionSegment(t,e){return!1}InsertParallelReflectionSegment(t,e,i,s,n,o){return!1}ProcessVertexEvent(t,e,i){const s=this.ScanDirection.IsHorizontal?this.horizontalVertexPoints:this.verticalVertexPoints;s.add(i.Site);const n=this.LowNeighborSides.LowNeighbor.item,o=this.HighNeighborSides.HighNeighbor.item,a=this.ScanDirection.Dir,h=this.ScanDirection.OppositeDirection,u=this.ScanLineIntersectSide(i.Site,n),d=this.ScanLineIntersectSide(i.Site,o);if(this.ObstacleTree.GraphBox.contains(u)){const y=Z.RectangleBorderIntersect(n.Obstacle.VisibilityBoundingBox,u,a);L.IsPureLower(y,i.Site)&&this.boundingBoxSteinerPoints.add(y)}if(this.ObstacleTree.GraphBox.contains(d)){const y=Z.RectangleBorderIntersect(o.Obstacle.VisibilityBoundingBox,d,h);L.IsPureLower(i.Site,y)&&this.boundingBoxSteinerPoints.add(y)}const m={lowCorner:void 0,highCorner:void 0};Je.GetBoundingCorners(t.item.Obstacle.VisibilityBoundingBox,i instanceof $r,this.ScanDirection.IsHorizontal,m),(L.IsPureLower(u,m.lowCorner)||n.Obstacle.IsInSameClump(i.Obstacle))&&s.add(m.lowCorner),(L.IsPureLower(m.highCorner,d)||o.Obstacle.IsInSameClump(i.Obstacle))&&s.add(m.highCorner)}static GetBoundingCorners(t,e,i,s){if(e){s.lowCorner=t.leftBottom,s.highCorner=i?t.rightBottom:t.leftTop;return}s.lowCorner=i?t.leftTop:t.rightBottom,s.highCorner=t.rightTop}CreateScanSegmentsOnAxisCoordinate(t){this.CurrentGroupBoundaryCrossingMap.Clear();const e=this.scanLine.Lowest();let i=this.scanLine.NextHighR(e),s=0,n=t,o=!1;for(;i!=null;i=this.scanLine.NextHighR(i)){if(this.SkipSide(n,i.item))continue;if(i.item.Obstacle.IsGroup){(s===0||o)&&this.HandleGroupCrossing(t,i.item);continue}if(i.item instanceof vi){if(s>0){s++;continue}n=this.CreateScanSegment(n,i.item,mt.NormalWeight),this.CurrentGroupBoundaryCrossingMap.Clear(),s=1,o=i.item.Obstacle.isOverlapped;continue}s++,!(s>0)&&(n=i.item.Obstacle.isOverlapped||i.item.Obstacle.OverlapsGroupCorner?this.CreateScanSegment(n,i.item,mt.OverlappedWeight):this.ScanLineIntersectSide(n,i.item),this.CurrentGroupBoundaryCrossingMap.Clear(),o=!1)}const a=this.ScanDirection.IsHorizontal?new c(this.ObstacleTree.GraphBox.right+Je.SentinelOffset,n.y):new c(n.x,this.ObstacleTree.GraphBox.top+Je.SentinelOffset);this.parallelSegmentVector.CreateScanSegment(n,a,mt.NormalWeight,this.CurrentGroupBoundaryCrossingMap.GetOrderedListBetween(n,a)),this.parallelSegmentVector.ScanSegmentsCompleteForCurrentSlot()}HandleGroupCrossing(t,e){if(!this.ScanLineCrossesObstacle(t,e.Obstacle))return;const i=e instanceof vi?this.ScanDirection.Dir:this.ScanDirection.OppositeDirection,s=this.ScanLineIntersectSide(t,e),n=this.CurrentGroupBoundaryCrossingMap.AddIntersection(s,e.Obstacle,i);this.AddPerpendicularCoordForGroupCrossing(s);const o=n.GetInteriorVertexPoint(s);this.AddPerpendicularCoordForGroupCrossing(o)}AddPerpendicularCoordForGroupCrossing(t){const e=this.FindPerpendicularSlot(t,0);e!==-1&&this.perpendicularSegmentVector.Item(e).AddPendingPerpendicularCoord(this.parallelSegmentVector.CurrentSlot.Coord)}SkipSide(t,e){if(e.Obstacle.IsSentinel)return!0;const i=e.Obstacle.VisibilityBoundingBox;return this.ScanDirection.IsHorizontal?t.y===i.bottom||t.y===i.top:t.x===i.left||t.x===i.right}CreateScanSegment(t,e,i){const s=this.ScanLineIntersectSide(t,e);return t!==s&&this.parallelSegmentVector.CreateScanSegment(t,s,i,this.CurrentGroupBoundaryCrossingMap.GetOrderedListBetween(t,s)),s}GenerateSparseIntersectionsFromVertexPoints(){this.VisibilityGraph=Je.NewVisibilityGraph(),this.GenerateSparseIntersectionsAlongHorizontalAxis(),this.GenerateSparseIntersectionsAlongVerticalAxis(),this.ConnectAdjoiningScanSegments(),this.horizontalScanSegmentVector.CreateSparseVerticesAndEdges(this.VisibilityGraph),this.verticalScanSegmentVector.CreateSparseVerticesAndEdges(this.VisibilityGraph)}GenerateSparseIntersectionsAlongHorizontalAxis(){this.currentAxisPointComparer=vt;const t=Array.from(this.horizontalVertexPoints.values()).sort(this.currentAxisPointComparer),e=Array.from(this.boundingBoxSteinerPoints.values()).sort(this.currentAxisPointComparer);this.ScanDirection=_t.HorizontalInstance,this.SetVectorsAndCoordMaps(this.ScanDirection),this.GenerateSparseIntersections(t,e)}GenerateSparseIntersectionsAlongVerticalAxis(){this.currentAxisPointComparer=(i,s)=>i.compareTo(s);const t=Array.from(this.verticalVertexPoints.values()).sort(this.currentAxisPointComparer),e=Array.from(this.boundingBoxSteinerPoints.values()).sort(this.currentAxisPointComparer);this.ScanDirection=_t.VerticalInstance,this.SetVectorsAndCoordMaps(this.ScanDirection),this.GenerateSparseIntersections(t,e)}SetVectorsAndCoordMaps(t){t.IsHorizontal?(this.parallelSegmentVector=this.horizontalScanSegmentVector,this.perpendicularSegmentVector=this.verticalScanSegmentVector,this.perpendicularCoordMap=this.verticalCoordMap):(this.parallelSegmentVector=this.verticalScanSegmentVector,this.perpendicularSegmentVector=this.horizontalScanSegmentVector,this.perpendicularCoordMap=this.horizontalCoordMap)}ConnectAdjoiningScanSegments(){this.horizontalScanSegmentVector.ConnectAdjoiningSegmentEndpoints(),this.verticalScanSegmentVector.ConnectAdjoiningSegmentEndpoints()}GenerateSparseIntersections(t,e){this.perpendicularSegmentVector.ResetForIntersections(),this.parallelSegmentVector.ResetForIntersections();let i=1;const s={j:0};for(const n of this.parallelSegmentVector.Items())for(;!(!n.CurrentSegment.ContainsPoint(t[i])&&(!this.AddSteinerPointsToInterveningSegments(t[i],e,s,n)||!n.TraverseToSegmentContainingPoint(t[i])));){if(this.AddPointsToCurrentSegmentIntersections(e,s,n),this.GenerateIntersectionsFromVertexPointForCurrentSegment(t[i],n),n.PointIsCurrentEndAndNextStart(t[i])){n.MoveNext();continue}if(++i>=t.length)return}}AddSteinerPointsToInterveningSegments(t,e,i,s){for(;i.j<e.length&&this.currentAxisPointComparer(e[i.j],t)===-1;){if(!s.TraverseToSegmentContainingPoint(e[i.j]))return!1;this.AddPointsToCurrentSegmentIntersections(e,i,s)}return!0}AddPointsToCurrentSegmentIntersections(t,e,i){for(;e.j<t.length&&i.CurrentSegment.ContainsPoint(t[e.j]);e.j++){const s=this.FindPerpendicularSlot(t[e.j],0);this.AddSlotToSegmentIntersections(i,s)}}GenerateIntersectionsFromVertexPointForCurrentSegment(t,e){const i=this.FindPerpendicularSlot(e.CurrentSegment.Start,1),s=this.FindPerpendicularSlot(e.CurrentSegment.End,-1),n=this.FindPerpendicularSlot(t,0);i>=s||(this.AddSlotToSegmentIntersections(e,i),this.AddSlotToSegmentIntersections(e,s),n>i&&n<s&&(this.AddSlotToSegmentIntersections(e,n),this.AddBinaryDivisionSlotsToSegmentIntersections(e,i,n,s)))}FindPerpendicularSlot(t,e){return Je.FindIntersectingSlot(this.perpendicularSegmentVector,this.perpendicularCoordMap,t,e)}static FindIntersectingSlot(t,e,i,s){const n=t.GetParallelCoord(i),o=e.get(n);return o!==void 0?o:s===0?-1:t.FindNearest(n,s)}AddSlotToSegmentIntersections(t,e){const i=this.perpendicularSegmentVector.Item(e);t.CurrentSegment.AddSparseVertexCoord(i.Coord),i.AddPerpendicularCoord(t.Coord)}AddBinaryDivisionSlotsToSegmentIntersections(t,e,i,s){let n=0,o=this.perpendicularSegmentVector.Length-1;for(;o-n>1;){const a=n+Math.floor((o-n)/2);if(i<=a){o=a,i<o&&o<=s&&this.AddSlotToSegmentIntersections(t,o);continue}n=a,i>n&&n>=e&&this.AddSlotToSegmentIntersections(t,n)}}CreateScanSegmentTrees(){Je.CreateScanSegmentTree(this.horizontalScanSegmentVector,this.HorizontalScanSegments),Je.CreateScanSegmentTree(this.verticalScanSegmentVector,this.VerticalScanSegments)}static CreateScanSegmentTree(t,e){for(const i of t.Items())for(let s=i.FirstSegment;s!=null;s=s.NextSegment)s.HasVisibility()&&e.InsertUnique(s)}}class Ze{get ObstacleTree(){return this.GraphGenerator.ObstacleTree}get VisGraph(){return this.GraphGenerator.VisibilityGraph}get IsSparseVg(){return this.GraphGenerator instanceof Je}constructor(t){this.AddedVertices=new Array,this.AddedEdges=new Array,this.edgesToRestore=new Array,this.LimitPortVisibilitySpliceToEndpointBoundingBox=!1,this.GraphGenerator=t}AddVertex(t){const e=this.VisGraph.AddVertexP(t);return this.AddedVertices.push(e),e}FindOrAddVertex(t){const e=this.VisGraph.FindVertex(t);return e??this.AddVertex(t)}FindOrAddEdgeVV(t,e){return this.FindOrAddEdge(t,e,mt.NormalWeight)}FindOrAddEdge(t,e,i){const s=L.GetPureDirectionVV(t,e),n={bracketSource:void 0,bracketTarget:void 0,splitVertex:void 0};Ze.GetBrackets(t,e,s,n);let o=this.VisGraph.FindEdgePP(n.bracketSource.point,n.bracketTarget.point);return o=o!=null?this.SplitEdge(o,n.splitVertex):this.CreateEdge(n.bracketSource,n.bracketTarget,i),o}static GetBrackets(t,e,i,s){if(s.splitVertex=e,!Ze.FindBracketingVertices(t,e.point,i,s)){const n={bracketSource:null,bracketTarget:null};Ze.FindBracketingVertices(e,t.point,j.OppositeDir(i),n)&&(s.bracketSource=n.bracketTarget,s.splitVertex=t),s.bracketTarget=n.bracketSource}}static FindBracketingVertices(t,e,i,s){for(s.bracketSource=t;s.bracketTarget=Z.FindAdjacentVertex(s.bracketSource,i),s.bracketTarget!=null;){if(c.closeDistEps(s.bracketTarget.point,e))return!0;if(i!==L.GetDirections(s.bracketTarget.point,e))break;s.bracketSource=s.bracketTarget}return s.bracketTarget!=null}CreateEdge(t,e,i){let s=t,n=e;L.IsPureLower(s.point,n.point)||(s=e,n=t);const o=new li(s,n,i);return Xt.AddEdge(o),this.AddedEdges.push(o),o}RemoveFromGraph(){this.RemoveAddedVertices(),this.RemoveAddedEdges(),this.RestoreRemovedEdges()}RemoveAddedVertices(){for(const t of this.AddedVertices)this.VisGraph.FindVertex(t.point)!=null&&this.VisGraph.RemoveVertex(t);this.AddedVertices=[]}RemoveAddedEdges(){for(const t of this.AddedEdges)this.VisGraph.FindVertex(t.SourcePoint)!=null&&Xt.RemoveEdge(t);this.AddedEdges=[]}RestoreRemovedEdges(){for(const t of this.edgesToRestore)Xt.AddEdge(t);this.edgesToRestore=[]}FindNextEdge(t,e){return Z.FindAdjacentEdge(t,e)}FindPerpendicularOrContainingEdge(t,e,i){for(;;){const s=Z.FindAdjacentVertex(t,e);if(s==null)break;const n=L.GetDirections(s.point,i);if((j.OppositeDir(e)&n)!==0)return this.VisGraph.FindEdgePP(t.point,s.point);t=s}return null}FindNearestPerpendicularOrContainingEdge(t,e,i){let s;e&L.GetDirections(t.point,i);let n=t;const o=s;for(;v.None!==o;){const h=Z.FindAdjacentVertex(n,s);if(h==null||(j.OppositeDir(s)&L.GetDirections(h.point,i))!==0)break;n=h,e&L.GetDirections(n.point,i)}let a;for(;a=this.FindPerpendicularOrContainingEdge(n,e,i),!(a!=null||n===t);)n=Z.FindAdjacentVertex(n,j.OppositeDir(s));return a}ConnectVertexToTargetVertex(t,e,i,s){if(c.closeDistEps(t.point,e.point))return;const n=L.GetDirections(t.point,e.point);if(L.IsPureDirectionD(n)){this.FindOrAddEdgeVV(t,e);return}const o=Z.FindBendPointBetween(t.point,e.point,i),a=this.FindOrAddVertex(o);this.FindOrAddEdge(t,a,s),this.FindOrAddEdge(a,e,s)}AddEdgeToTargetEdge(t,e,i){let s=this.VisGraph.FindVertex(i);return s==null&&(s=this.AddVertex(i),this.SplitEdge(e,s)),this.FindOrAddEdgeVV(t,s),s}SplitEdge(t,e){return t==null?null:c.closeDistEps(t.Source.point,e.point)||c.closeDistEps(t.Target.point,e.point)?t:(t instanceof li||this.edgesToRestore.push(t),Xt.RemoveEdge(t),(this.IsSparseVg||t.Weight===mt.OverlappedWeight)&&e.Degree>0?(this.FindOrAddEdge(e,t.Source,t.Weight),this.FindOrAddEdge(e,t.Target,t.Weight)):(this.CreateEdge(e,t.Target,t.Weight),this.CreateEdge(t.Source,e,t.Weight)))}ExtendEdgeChainVRLPB(t,e,i,s,n){const o=L.GetDirections(i.start,i.end);if(o===v.None)return;const a=Z.GetRectangleBound(e,o),h=Z.IsVerticalD(o)?c.RoundPoint(new c(t.point.x,a)):c.RoundPoint(new c(a,t.point.y));if(c.closeDistEps(h,t.point)||L.GetDirections(t.point,h)!==o)return;let u=i;L.GetDirections(h,u.end)===o&&(u=N.mkPP(u.start,h)),this.ExtendEdgeChain(t,o,u,i,s,n)}ExtendEdgeChain(t,e,i,s,n,o){if(L.GetDirections(t.point,i.end)!==e)return;let h=j.RotateLeft(e),u=Z.FindAdjacentVertex(t,h);if(u==null&&(h=j.OppositeDir(h),u=Z.FindAdjacentVertex(t,h),u==null))return;const d=j.OppositeDir(h),m={spliceTarget:null};this.ExtendSpliceWorker(u,e,d,i,s,o,m)&&this.ExtendSpliceWorker(m.spliceTarget,e,h,i,s,o,m),this.SpliceGroupBoundaryCrossings(n,t,i)}SpliceGroupBoundaryCrossings(t,e,i){if(t==null||t.Count()===0)return;t.Reset();let s=i.start,n=i.end,o=L.GetDirections(s,n);Z.IsAscending(o)||(s=i.end,n=i.start,o=j.OppositeDir(o)),e=Ze.TraverseToFirstVertexAtOrAbove(e,s,j.OppositeDir(o));for(let a=e;a!=null;a=Z.FindAdjacentVertex(a,o)){const h=L.ComparePP(a.point,n)>=0;for(;t.CurrentIsBeforeOrAt(a.point);){const u=t.Pop();L.ComparePP(u.Location,e.point)>0&&L.ComparePP(u.Location,n)<=0&&this.SpliceGroupBoundaryCrossing(a,u,j.OppositeDir(o)),L.ComparePP(u.Location,e.point)>=0&&L.ComparePP(u.Location,n)<0&&this.SpliceGroupBoundaryCrossing(a,u,o)}if(h)break}}static TraverseToFirstVertexAtOrAbove(t,e,i){let s=t;const n=j.OppositeDir(i);for(;;){const o=Z.FindAdjacentVertex(s,i);if(o==null||L.GetDirections(o.point,e)===n)break;s=o}return s}SpliceGroupBoundaryCrossing(t,e,i){var s,n;const o=Yn.ToCrossingArray(e.Crossings,i);if(o!=null){const a=(s=this.VisGraph.FindVertex(e.Location))!==null&&s!==void 0?s:this.AddVertex(e.Location);t.point.equal(a.point)||this.FindOrAddEdgeVV(t,a);const h=o[0].GetInteriorVertexPoint(e.Location),u=(n=this.VisGraph.FindVertex(h))!==null&&n!==void 0?n:this.AddVertex(h),d=this.FindOrAddEdgeVV(a,u),m=o.map(y=>y.Group.InputShape);d.IsPassable=()=>m.some(y=>y.IsTransparent)}}ExtendSpliceWorker(t,e,i,s,n,o,a){let h=Z.FindAdjacentVertex(t,i);a.spliceTarget=Z.FindAdjacentVertex(h,i);const u={spliceSource:t};for(;Ze.GetNextSpliceSource(u,i,e);){const d=Z.FindBendPointBetween(h.point,u.spliceSource.point,j.OppositeDir(i));if(Ze.IsPointPastSegmentEnd(n,d))break;if(a.spliceTarget=Ze.GetSpliceTarget(u,i,d),a.spliceTarget==null){if(this.IsSkippableSpliceSourceWithNullSpliceTarget(u.spliceSource,e))continue;if(this.ObstacleTree.SegmentCrossesAnObstacle(u.spliceSource.point,d))return!1}let m=this.VisGraph.FindVertex(d);if(m!=null){if(a.spliceTarget==null||this.VisGraph.FindEdgePP(h.point,d)!=null)return a.spliceTarget==null&&this.FindOrAddEdge(h,m,o?mt.OverlappedWeight:mt.NormalWeight),!1}else m=this.AddVertex(d);if(this.FindOrAddEdge(h,m,o?mt.OverlappedWeight:mt.NormalWeight),this.FindOrAddEdge(u.spliceSource,m,o?mt.OverlappedWeight:mt.NormalWeight),o&&(o=this.SeeIfSpliceIsStillOverlapped(e,m)),h=m,(e&L.GetDirections(d,s.end))===0){a.spliceTarget=null;break}}return a.spliceTarget!=null}static GetNextSpliceSource(t,e,i){let s=Z.FindAdjacentVertex(t.spliceSource,i);if(s==null)for(s=t.spliceSource;;){if(s=Z.FindAdjacentVertex(s,j.OppositeDir(e)),s==null)return!1;const n=Z.FindAdjacentVertex(s,i);if(n!=null){s=n;break}}return t.spliceSource=s,!0}static GetSpliceTarget(t,e,i){const s=L.GetDirections(t.spliceSource.point,i);let n=s,o=t.spliceSource;for(;n===s&&(t.spliceSource=o,o=Z.FindAdjacentVertex(t.spliceSource,e),o!=null);){if(c.closeDistEps(o.point,i)){o=Z.FindAdjacentVertex(o,e);break}n=L.GetDirections(o.point,i)}return o}SeeIfSpliceIsStillOverlapped(t,e){let i=this.FindNextEdge(e,j.RotateLeft(t)),s=i==null?!1:mt.NormalWeight===i.Weight;return s||(i=this.FindNextEdge(e,j.RotateRight(t)),s=i==null?!1:mt.NormalWeight===i.Weight),!s||this.ObstacleTree.PointIsInsideAnObstaclePD(e.point,t)}IsSkippableSpliceSourceWithNullSpliceTarget(t,e){if(Ze.IsSkippableSpliceSourceEdgeWithNullTarget(Z.FindAdjacentEdge(t,e)))return!0;const i=Z.FindAdjacentEdge(t,j.OppositeDir(e));return Ze.IsSkippableSpliceSourceEdgeWithNullTarget(i)||Ze.IsReflectionEdge(i)}static IsSkippableSpliceSourceEdgeWithNullTarget(t){return t!=null&&t.IsPassable!=null&&R(t.Length,bo.BoundaryWidth)}static IsReflectionEdge(t){return t!=null&&t.Weight===mt.ReflectionWeight}static IsPointPastSegmentEnd(t,e){return L.GetDirections(t.start,t.end)===L.GetDirections(t.end,e)}toString(){return ue.Qf.format("{0} {1}",this.AddedVertices.length,this.edgesToRestore.length)}}class _n{get LimitPortVisibilitySpliceToEndpointBoundingBox(){return this.TransUtil.LimitPortVisibilitySpliceToEndpointBoundingBox}set LimitPortVisibilitySpliceToEndpointBoundingBox(t){this.TransUtil.LimitPortVisibilitySpliceToEndpointBoundingBox=t}get VisGraph(){return this.graphGenerator.VisibilityGraph}get HScanSegments(){return this.graphGenerator.HorizontalScanSegments}get VScanSegments(){return this.graphGenerator.VerticalScanSegments}get ObstacleTree(){return this.graphGenerator.ObstacleTree}get AncestorSets(){return this.ObstacleTree.AncestorSets}constructor(t){this.obstaclePortMap=new Map,this.freePointMap=new je,this.freePointLocationsUsedByRouteEdges=new Yt,this.RouteToCenterOfObstacles=!1,this.obstaclePortsInGraph=new Array,this.freePointsInGraph=new Set,this.activeAncestors=new Array,this.TransUtil=new Ze(t),this.graphGenerator=t}Clear(){this.TransUtil.RemoveFromGraph(),this.obstaclePortMap.clear()}CreateObstaclePorts(t){for(const e of t.Ports)this.CreateObstaclePort(t,e)}CreateObstaclePort(t,e){if(e.Curve==null)return null;const i=c.RoundPoint(e.Location);if(at.Outside===w.PointRelativeToCurveLocation(i,t.InputShape.BoundaryCurve)||t.InputShape.BoundaryCurve!==e.Curve&&at.Outside===w.PointRelativeToCurveLocation(i,e.Curve))return null;const s=new Bl(e,t);return this.obstaclePortMap.set(e,s),s}FindVertices(t){const e=new Array,i=this.obstaclePortMap.get(t);if(i)if(this.RouteToCenterOfObstacles)e.push(i.CenterVertex);else for(const s of i.PortEntrances){const n=this.VisGraph.FindVertex(s.UnpaddedBorderIntersect);n!=null&&e.push(n)}else e.push(this.VisGraph.FindVertex(c.RoundPoint(t.Location)));return e}RemoveObstaclePorts(t){for(const e of t.Ports)this.RemoveObstaclePort(e)}RemoveObstaclePort(t){this.obstaclePortMap.delete(t)}AddControlPointsToGraph(t,e){this.GetPortSpliceLimitRectangle(t),this.activeAncestors=[];const i={oport:null},s={oport:null},n=this.FindAncestorsAndObstaclePort(t.sourcePort,i),o=this.FindAncestorsAndObstaclePort(t.targetPort,s);if(this.AncestorSets.size>0&&i.oport!=null&&s.oport!=null){const a=Xi(o,n),h=Xi(n,o);this.ActivateAncestors(h,a,e)}this.AddPortToGraph(t.sourcePort,i.oport),this.AddPortToGraph(t.targetPort,s.oport)}ConnectOobWaypointToEndpointVisibilityAtGraphBoundary(t,e){if(t==null||!t.IsOutOfBounds)return;const i=this.FindVertices(e);let s=t.OutOfBoundsDirectionFromGraph&(v.North|v.South);this.ConnectToGraphAtPointsCollinearWithVertices(t,s,i),s=t.OutOfBoundsDirectionFromGraph&(v.East|v.West),this.ConnectToGraphAtPointsCollinearWithVertices(t,s,i)}ConnectToGraphAtPointsCollinearWithVertices(t,e,i){if(v.None===e)return;const s=j.OppositeDir(e);for(const n of i){const o=this.InBoundsGraphBoxIntersect(n.point,e),a=this.VisGraph.FindVertex(o);a!=null&&this.TransUtil.ConnectVertexToTargetVertex(t.Vertex,a,s,mt.NormalWeight)}}SetAllAncestorsActive(t,e){if(this.AncestorSets.size===0)return!1;this.ObstacleTree.AdjustSpatialAncestors(),this.ClearActiveAncestors();const i={oport:null},s={oport:null},n=this.FindAncestorsAndObstaclePort(t.sourcePort,s),o=this.FindAncestorsAndObstaclePort(t.targetPort,i);return this.AncestorSets.size>0&&n!=null&&o!=null?(this.ActivateAncestors(n,o,e),!0):!1}SetAllGroupsActive(){this.ClearActiveAncestors();for(const t of this.ObstacleTree.GetAllGroups())t.IsTransparentAncestor=!0,this.activeAncestors.push(t)}FindAncestorsAndObstaclePort(t,e){return e.oport=this.FindObstaclePort(t),this.AncestorSets.size===0?null:e.oport!=null?this.AncestorSets.get(e.oport.Obstacle.InputShape):new Set(Array.from(this.ObstacleTree.Root.AllHitItems(X.mkPP(t.Location,t.Location),i=>i.IsGroup)).map(i=>i.InputShape))}ActivateAncestors(t,e,i){for(const s of Ki(t,e)){const n=i.get(s);n.IsTransparentAncestor=!0,this.activeAncestors.push(n)}}ClearActiveAncestors(){for(const t of this.activeAncestors)t.IsTransparentAncestor=!1;this.activeAncestors=[]}RemoveControlPointsFromGraph(){this.ClearActiveAncestors(),this.RemoveObstaclePortsFromGraph(),this.RemoveFreePointsFromGraph(),this.TransUtil.RemoveFromGraph(),this.portSpliceLimitRectangle=X.mkEmpty()}RemoveObstaclePortsFromGraph(){for(const t of this.obstaclePortsInGraph)t.RemoveFromGraph();this.obstaclePortsInGraph=[]}RemoveFreePointsFromGraph(){for(const t of this.freePointsInGraph)t.RemoveFromGraph();this.freePointsInGraph.clear()}RemoveStaleFreePoints(){if(this.freePointMap.size>this.freePointLocationsUsedByRouteEdges.size){const t=Array.from(this.freePointMap).filter(e=>!this.freePointLocationsUsedByRouteEdges.has(e[0]));for(const e of t)this.freePointMap.deleteP(e[0])}}ClearVisibility(){this.freePointMap.clear();for(const t of this.obstaclePortMap.values())t.ClearVisibility()}BeginRouteEdges(){this.RemoveControlPointsFromGraph(),this.freePointLocationsUsedByRouteEdges.clear()}EndRouteEdges(){this.RemoveStaleFreePoints()}FindObstaclePort(t){let e=this.obstaclePortMap.get(t);if(e){const i={removedPorts:null,addedPorts:null};if(e.Obstacle.GetPortChanges(i)){for(const s of i.addedPorts)this.CreateObstaclePort(e.Obstacle,s);for(const s of i.removedPorts)this.RemoveObstaclePort(s);e=this.obstaclePortMap.get(t)}}return e}AddPortToGraph(t,e){if(e!=null){this.AddObstaclePortToGraph(e);return}this.AddFreePointToGraph(t.Location)}AddObstaclePortToGraph(t){if(!(t.LocationHasChanged&&(this.RemoveObstaclePort(t.Port),t=this.CreateObstaclePort(t.Obstacle,t.Port),t==null))){t.AddToGraph(this.TransUtil,this.RouteToCenterOfObstacles),this.obstaclePortsInGraph.push(t),this.CreateObstaclePortEntrancesIfNeeded(t);for(const e of t.PortEntrances)this.AddObstaclePortEntranceToGraph(e)}}CreateObstaclePortEntrancesIfNeeded(t){t.PortEntrances.length>0||this.CreateObstaclePortEntrancesFromPoints(t)}GetPortVisibilityIntersection(t){const e=this.FindObstaclePort(t.sourcePort),i=this.FindObstaclePort(t.targetPort);if(e==null||i==null||e.Obstacle.IsInConvexHull||i.Obstacle.IsInConvexHull||(this.CreateObstaclePortEntrancesIfNeeded(e),this.CreateObstaclePortEntrancesIfNeeded(i),!e.VisibilityRectangle.intersects(i.VisibilityRectangle)))return null;for(const s of e.PortEntrances)if(s.WantVisibilityIntersection)for(const n of i.PortEntrances){if(!n.WantVisibilityIntersection)continue;const o=s.IsVertical===n.IsVertical?_n.GetPathPointsFromOverlappingCollinearVisibility(s,n):_n.GetPathPointsFromIntersectingVisibility(s,n);if(o!=null)return o}return null}static GetPathPointsFromOverlappingCollinearVisibility(t,e){return!Z.IntervalsAreSame(t.MaxVisibilitySegment.start,t.MaxVisibilitySegment.end,e.MaxVisibilitySegment.end,e.MaxVisibilitySegment.start)||t.HasGroupCrossings||e.HasGroupCrossings||c.closeDistEps(t.UnpaddedBorderIntersect,e.UnpaddedBorderIntersect)?null:[t.UnpaddedBorderIntersect,e.UnpaddedBorderIntersect]}static GetPathPointsFromIntersectingVisibility(t,e){const i=Z.SegmentsIntersectLL(t.MaxVisibilitySegment,e.MaxVisibilitySegment);return!i||t.HasGroupCrossingBeforePoint(i)||e.HasGroupCrossingBeforePoint(i)?null:[t.UnpaddedBorderIntersect,i,e.UnpaddedBorderIntersect]}CreateObstaclePortEntrancesFromPoints(t){const e=this.graphGenerator.ObstacleTree.GraphBox,i=X.mkPP(c.RoundPoint(t.PortCurve.boundingBox.leftBottom),c.RoundPoint(t.PortCurve.boundingBox.rightTop)),s=c.RoundPoint(t.PortLocation);let n=!1;const o={xx0:null,xx1:null};if(!L.Equal(s.y,i.top)&&!L.Equal(s.y,i.bottom)){n=!0;const a=new N(e.left,s.y,e.right,s.y);this.GetBorderIntersections(s,a,t.PortCurve,o);let h=new c(Math.min(o.xx0.x,o.xx1.x),s.y);h.x<i.left&&(h=new c(i.left,h.y));let u=new c(Math.max(o.xx0.x,o.xx1.x),s.y);u.x>i.right&&(u=new c(i.right,u.y)),this.CreatePortEntrancesAtBorderIntersections(i,t,s,h,u)}if(!L.Equal(s.x,i.left)&&!L.Equal(s.x,i.right)){n=!0;const a=new N(s.x,e.bottom,s.x,e.top);this.GetBorderIntersections(s,a,t.PortCurve,o);let h=new c(s.x,Math.min(o.xx0.y,o.xx1.y));h.y<e.bottom&&(h=new c(h.x,e.bottom));let u=new c(s.x,Math.max(o.xx0.y,o.xx1.y));u.y>e.top&&(u=new c(u.x,e.top)),this.CreatePortEntrancesAtBorderIntersections(i,t,s,h,u)}n||this.CreateEntrancesForCornerPort(i,t,s)}GetBorderIntersections(t,e,i,s){const n=w.getAllIntersections(e,i,!0);s.xx0=c.RoundPoint(n[0].x),s.xx1=c.RoundPoint(n[1].x)}CreatePortEntrancesAtBorderIntersections(t,e,i,s,n){const o=L.GetDirections(s,n);L.EqualPP(s,i)||this.CreatePortEntrance(t,e,n,o),L.EqualPP(n,i)||this.CreatePortEntrance(t,e,s,j.OppositeDir(o))}static GetDerivative(t,e){const i=t.PortCurve.closestParameter(e);let s=t.PortCurve.derivative(i);const n=(t.PortCurve.parStart+t.PortCurve.parEnd)/2;return ut.CurveIsClockwise(t.PortCurve,t.PortCurve.value(n))||(s=s.mul(-1)),s}CreatePortEntrance(t,e,i,s){e.CreatePortEntrance(i,s,this.ObstacleTree);const n=_t.GetInstance(s);let o=Z.GetRectangleBound(t,s)-n.Coord(i);if(o<0&&(o=-o),o>C.intersectionEpsilon){const a=j.VectorDirection(_n.GetDerivative(e,i));let h;s|j.OppositeDir(s),v.None!==(s&a)&&(h=j.OppositeDir(h)),e.CreatePortEntrance(i,h,this.ObstacleTree)}}CreateEntrancesForCornerPort(t,e,i){let s=v.North;L.EqualPP(i,t.leftBottom)?s=v.South:L.EqualPP(i,t.leftTop)?s=v.West:L.EqualPP(i,t.rightTop)?s=v.North:L.EqualPP(i,t.rightBottom)&&(s=v.East),e.CreatePortEntrance(i,s,this.ObstacleTree),e.CreatePortEntrance(i,j.RotateRight(s),this.ObstacleTree)}AddObstaclePortEntranceToGraph(t){const e=this.VisGraph.FindVertex(t.VisibilityBorderIntersect);if(e){t.ExtendEdgeChain(this.TransUtil,e,e,this.portSpliceLimitRectangle,this.RouteToCenterOfObstacles);return}const i={targetVertex:null},s=t.IsOverlapped?mt.OverlappedWeight:mt.NormalWeight;this.FindorCreateNearestPerpEdgePPDNT(t.MaxVisibilitySegment.end,t.VisibilityBorderIntersect,t.OutwardDirection,s,i)!=null&&t.AddToAdjacentVertex(this.TransUtil,i.targetVertex,this.portSpliceLimitRectangle,this.RouteToCenterOfObstacles)}InBoundsGraphBoxIntersect(t,e){return Z.RectangleBorderIntersect(this.graphGenerator.ObstacleTree.GraphBox,t,e)}FindorCreateNearestPerpEdgePPDN(t,e,i,s){const n={targetVertex:null};return this.FindorCreateNearestPerpEdgePPDNT(t,e,i,s,n)}FindorCreateNearestPerpEdgePPDNT(t,e,i,s,n){const o=Z.SortAscending(t,e),a=o[0],h=o[1],u=Z.IsVerticalD(i)?this.HScanSegments:this.VScanSegments,d=Z.IsAscending(i)?u.FindLowestIntersector(a,h):u.FindHighestIntersector(a,h);if(d==null)return n.targetVertex=null,null;const m=Z.SegmentIntersectionSP(d,a);return this.FindOrCreateNearestPerpEdgeFromNearestPerpSegment(Z.IsAscending(i)?a:h,d,m,s,n)}FindOrCreateNearestPerpEdgeFromNearestPerpSegment(t,e,i,s,n){var o;const a={segsegVertex:this.VisGraph.FindVertex(i),targetVertex:null};if(a.segsegVertex==null){const m=this.FindOrCreateSegmentIntersectionVertexAndAssociatedEdge(t,i,e,s,a);if(m!=null)return m}else if(L.EqualPP(t,i))return n.targetVertex=a.segsegVertex,this.TransUtil.FindNextEdge(n.targetVertex,j.OppositeDir(e.ScanDirection.Dir));const h=L.GetDirections(i,t);let u=L.GetDirections(a.segsegVertex.point,t);if(h===u){const m={bracketTarget:null,bracketSource:null};return Ze.FindBracketingVertices(a.segsegVertex,t,h,m),(o=this.TransUtil.FindNextEdge(m.bracketSource,j.RotateLeft(h)))!==null&&o!==void 0?o:this.TransUtil.FindNextEdge(m.bracketSource,j.RotateRight(h))}u&=~h;const d=this.TransUtil.FindNearestPerpendicularOrContainingEdge(a.segsegVertex,u,t);return d==null?(n.targetVertex=this.TransUtil.AddVertex(i),this.TransUtil.FindOrAddEdge(n.targetVertex,e.HighestVisibilityVertex,e.Weight)):(a.segsegVertex=Z.GetEdgeEnd(d,j.OppositeDir(u)),i=Z.SegmentIntersectionPPP(t,i,a.segsegVertex.point),L.EqualPP(a.segsegVertex.point,i)?(n.targetVertex=a.segsegVertex,this.TransUtil.FindNextEdge(a.segsegVertex,u)):(n.targetVertex=this.TransUtil.FindOrAddVertex(i),this.TransUtil.FindOrAddEdge(a.segsegVertex,n.targetVertex,s)))}FindOrCreateSegmentIntersectionVertexAndAssociatedEdge(t,e,i,s,n){const a=(i.IsVertical?this.HScanSegments:this.VScanSegments).FindHighestIntersector(i.Start,e);if(a==null)return n.segsegVertex=null,n.targetVertex=this.TransUtil.AddVertex(e),this.TransUtil.FindOrAddEdge(n.targetVertex,i.LowestVisibilityVertex,i.Weight);const h=Z.SegmentsIntersection(i,a);if(n.segsegVertex=this.VisGraph.FindVertex(h),!n.segsegVertex){n.segsegVertex=this.TransUtil.AddVertex(h);const u=this.AddEdgeToClosestSegmentEnd(i,n.segsegVertex,i.Weight);if(this.AddEdgeToClosestSegmentEnd(a,n.segsegVertex,a.Weight),L.EqualPP(n.segsegVertex.point,e))return n.targetVertex=n.segsegVertex,u}return L.EqualPP(t,e)?(n.targetVertex=this.TransUtil.FindOrAddVertex(e),this.TransUtil.FindOrAddEdge(n.segsegVertex,n.targetVertex,s)):(n.targetVertex=null,null)}AddEdgeToClosestSegmentEnd(t,e,i){return L.IsPureLower(t.HighestVisibilityVertex.point,e.point)?this.TransUtil.FindOrAddEdge(t.HighestVisibilityVertex,e,i):L.IsPureLower(e.point,t.LowestVisibilityVertex.point)?this.TransUtil.FindOrAddEdge(e,t.LowestVisibilityVertex,i):this.TransUtil.FindOrAddEdgeVV(t.LowestVisibilityVertex,e)}GetPortSpliceLimitRectangle(t){if(!this.LimitPortVisibilitySpliceToEndpointBoundingBox){this.portSpliceLimitRectangle=this.graphGenerator.ObstacleTree.GraphBox;return}this.portSpliceLimitRectangle=this.GetPortRectangle(t.sourcePort),this.portSpliceLimitRectangle.addRecSelf(this.GetPortRectangle(t.targetPort))}GetPortRectangle(t){const e=this.obstaclePortMap.get(t);return e?e.Obstacle.VisibilityBoundingBox.clone():X.mkOnPoints([c.RoundPoint(t.Location)])}AddToLimitRectangle(t){this.graphGenerator.IsInBoundsP(t)&&this.portSpliceLimitRectangle.add(t)}FindOrCreateFreePoint(t){let e=this.freePointMap.get(t);return e?e.GetVertex(this.TransUtil,t):(e=new Ll(this.TransUtil,t),this.freePointMap.set(t,e)),this.freePointsInGraph.add(e),this.freePointLocationsUsedByRouteEdges.add(t),e}AddFreePointToGraph(t){t=c.RoundPoint(t);const e=this.VisGraph.FindVertex(t),i=this.FindOrCreateFreePoint(t);if(e!=null)return i;if(!this.graphGenerator.IsInBoundsP(t))return this.CreateOutOfBoundsFreePoint(i),i;let s=null;i.IsOverlapped=this.ObstacleTree.PointIsInsideAnObstacle(i.Point,this.HScanSegments.ScanDirection);let n;if(this.VScanSegments.FindSegmentContainingPoint(t,!0),n!=null){const a={targetVertex:null};s=this.FindOrCreateNearestPerpEdgeFromNearestPerpSegment(t,n,t,i.InitialWeight,a)}let o=v.South;if(s!=null)o=Z.EdgeDirectionVE(s),this.ConnectFreePointToLateralEdge(i,j.RotateLeft(o)),this.ConnectFreePointToLateralEdge(i,j.RotateRight(o));else for(let a=0;a<4;a++)this.ConnectFreePointToLateralEdge(i,o),o=j.RotateLeft(o);return i}CreateOutOfBoundsFreePoint(t){const e=t.Point,i=this.graphGenerator.MakeInBoundsLocation(e),s=L.GetDirections(i,e);if(t.OutOfBoundsDirectionFromGraph=s,!L.IsPureDirectionD(s)){t.AddOobEdgesFromGraphCorner(this.TransUtil,i);return}let n=this.VisGraph.FindVertex(i);const o=j.OppositeDir(s);if(n!=null)t.AddToAdjacentVertex(this.TransUtil,n,o,this.portSpliceLimitRectangle);else{const u=this.FindorCreateNearestPerpEdgePPDN(e,i,s,mt.NormalWeight);u!=null&&(n=t.AddEdgeToAdjacentEdge(this.TransUtil,u,o,this.portSpliceLimitRectangle))}const a=Z.FindAdjacentVertex(n,j.RotateLeft(o));a!=null&&this.TransUtil.ConnectVertexToTargetVertex(t.Vertex,a,o,mt.NormalWeight);const h=Z.FindAdjacentVertex(n,j.RotateRight(o));h!=null&&this.TransUtil.ConnectVertexToTargetVertex(t.Vertex,h,o,mt.NormalWeight)}ConnectFreePointToLateralEdge(t,e){const i=t.IsOverlapped?this.InBoundsGraphBoxIntersect(t.Point,e):t.MaxVisibilityInDirectionForNonOverlappedFreePoint(e,this.TransUtil),s=this.FindorCreateNearestPerpEdgePPDN(i,t.Point,e,t.InitialWeight);s!=null&&t.AddEdgeToAdjacentEdge(this.TransUtil,s,e,this.portSpliceLimitRectangle)}}class le extends Ft{get RouteToCenterOfObstacles(){return this.PortManager.RouteToCenterOfObstacles}set RouteToCenterOfObstacles(t){this.PortManager.RouteToCenterOfObstacles=t}get LimitPortVisibilitySpliceToEndpointBoundingBox(){return this.PortManager.LimitPortVisibilitySpliceToEndpointBoundingBox}set LimitPortVisibilitySpliceToEndpointBoundingBox(t){this.PortManager.LimitPortVisibilitySpliceToEndpointBoundingBox=t}AddEdgeGeometryToRoute(t){c.closeDistEps(c.RoundPoint(t.sourcePort.Location),c.RoundPoint(t.targetPort.Location))?this.selfEdges.push(t):this.EdgesToRoute.push(t)}get EdgeGeometriesToRoute(){return this.EdgesToRoute}RemoveAllEdgeGeometriesToRoute(){this.EdgesToRoute=[]}get UseSparseVisibilityGraph(){return this.GraphGenerator instanceof Je}get Obstacles(){return Array.from(this.ShapeToObstacleMap.values()).map(t=>t.InputShape)}get PaddedObstacles(){return Array.from(this.ShapeToObstacleMap.values()).map(t=>t.PaddedPolyline)}AddObstacles(t){this.AddShapes(t),this.RebuildTreeAndGraph()}AddShapes(t){for(const e of t)this.AddObstacleWithoutRebuild(e)}AddObstacle(t){this.AddObstacleWithoutRebuild(t),this.RebuildTreeAndGraph()}UpdateObstacles(t){for(const e of t)this.UpdateObstacleWithoutRebuild(e);this.RebuildTreeAndGraph()}UpdateObstacle(t){this.UpdateObstacleWithoutRebuild(t),this.RebuildTreeAndGraph()}RemoveObstacles(t){for(const e of t)this.RemoveObstacleWithoutRebuild(e);this.RebuildTreeAndGraph()}RemoveObstacle(t){this.RemoveObstacleWithoutRebuild(t),this.RebuildTreeAndGraph()}AddObstacleWithoutRebuild(t){if(t.BoundaryCurve==null)throw new Error("Shape must have a BoundaryCurve");this.CreatePaddedObstacle(t)}UpdateObstacleWithoutRebuild(t){if(t.BoundaryCurve==null)throw new Error("Shape must have a BoundaryCurve");this.PortManager.RemoveObstaclePorts(this.ShapeToObstacleMap.get(t)),this.CreatePaddedObstacle(t)}CreatePaddedObstacle(t){const e=new ge(t,this.Padding);this.ShapeToObstacleMap.set(t,e),this.PortManager.CreateObstaclePorts(e)}RemoveObstacleWithoutRebuild(t){const e=this.ShapeToObstacleMap.get(t);this.ShapeToObstacleMap.delete(t),this.PortManager.RemoveObstaclePorts(e)}RemoveAllObstacles(){this.InternalClear(!1)}RebuildTreeAndGraph(){const t=this.ObsTree.Root!=null,e=this.GraphGenerator.VisibilityGraph!=null;this.InternalClear(!0),t&&this.GenerateObstacleTree(),e&&this.GenerateVisibilityGraph()}get VisibilityGraph(){return this.GenerateVisibilityGraph(),this.GraphGenerator.VisibilityGraph}Clear(){this.InternalClear(!1)}static constructorEmpty(){return le.constructorC(null)}static constructorC(t){return new le([],le.DefaultPadding,le.DefaultCornerFitRadius)}static constructorI(t){return new le(t,le.DefaultPadding,le.DefaultCornerFitRadius)}static constructorINN(t,e,i){return new le(t,e,i)}constructor(t,e,i){super(null),this.Padding=0,this.CornerFitRadius=0,this.edgeSeparatian=3,this.BendPenaltyAsAPercentageOfDistance=0,this.ShapeToObstacleMap=new Map,this.EdgesToRoute=new Array,this.removeStaircases=!0,this.selfEdges=new Array,this.Padding=e,this.CornerFitRadius=i,this.BendPenaltyAsAPercentageOfDistance=Lt.DefaultBendPenaltyAsAPercentageOfDistance,this.GraphGenerator=new Je,this.PortManager=new _n(this.GraphGenerator),this.AddShapes(t)}static constructorGNAN(t,e,i,s){const n=new le(xe.GetShapes(t),i,s);if(e==null)for(const o of t.deepEdges)n.AddEdgeGeometryToRoute(o);else for(const o of e)n.AddEdgeGeometryToRoute(o);return n}run(){this.GenerateVisibilityGraph(),this.GeneratePaths()}GeneratePaths(){const t=this.EdgesToRoute.map(e=>new xl(e));this.FillEdgePathsWithShortestPaths(t),this.NudgePaths(t),this.RouteSelfEdges(),this.FinaliseEdgeGeometries()}RouteSelfEdges(){for(const t of this.selfEdges){const e={smoothedPolyline:null};t.curve=we.RouteSelfEdge(t.sourcePort.Curve,Math.max(this.Padding,2*t.GetMaxArrowheadLength()),e)}}FillEdgePathsWithShortestPaths(t){this.PortManager.BeginRouteEdges();const e=new Jn(this.BendPenaltyAsAPercentageOfDistance);for(const i of t)this.AddControlPointsAndGeneratePath(e,i);this.PortManager.EndRouteEdges()}AddControlPointsAndGeneratePath(t,e){const i=this.PortManager.GetPortVisibilityIntersection(e.GeomEdge);if(i!=null){this.GeneratePathThroughVisibilityIntersection(e,i);return}this.SpliceVisibilityAndGeneratePath(t,e)}GeneratePathThroughVisibilityIntersection(t,e){t.PathPoints=e}SpliceVisibilityAndGeneratePath(t,e){this.PortManager.AddControlPointsToGraph(e.GeomEdge,this.ShapeToObstacleMap),this.GeneratePath(t,e,!1)||this.RetryPathsWithAdditionalGroupsEnabled(t,e),this.PortManager.RemoveControlPointsFromGraph()}GeneratePath(t,e,i){const s=this.PortManager.FindVertices(e.GeomEdge.sourcePort),n=this.PortManager.FindVertices(e.GeomEdge.targetPort);return le.GetSingleStagePath(e,t,s,n,i)}static GetSingleStagePath(t,e,i,s,n){return t.PathPoints=e.GetPath(i,s),n&&le.EnsureNonNullPath(t),t.PathPoints!=null&&t.PathPoints.length>0}static EnsureNonNullPath(t){t.PathPoints==null&&(L.IsPureDirection(t.GeomEdge.sourcePort.Location,t.GeomEdge.targetPort.Location)?t.PathPoints=[t.GeomEdge.sourcePort.Location,t.GeomEdge.targetPort.Location]:t.PathPoints=[t.GeomEdge.sourcePort.Location,new c(t.GeomEdge.sourcePort.Location.x,t.GeomEdge.targetPort.Location.y),t.GeomEdge.targetPort.Location])}RetryPathsWithAdditionalGroupsEnabled(t,e){(!this.PortManager.SetAllAncestorsActive(e.GeomEdge,this.ShapeToObstacleMap)||!this.GeneratePath(t,e,!1))&&(this.PortManager.SetAllGroupsActive(),this.GeneratePath(t,e,!0))}NudgePaths(t){const e=this.ObsTree.SpatialAncestorsAdjusted?qt.GetAncestorSetsMap(this.Obstacles):this.AncestorsSets;Ht.NudgePaths(t,this.edgeSeparatian,this.PaddedObstacles,e,this.RemoveStaircases)}get RemoveStaircases(){return this.removeStaircases}set RemoveStaircases(t){this.removeStaircases=t}FinaliseEdgeGeometries(){for(const t of this.EdgesToRoute.concat(this.selfEdges)){if(t.curve==null)continue;t.curve instanceof st&&(t.curve=le.FitArcsIntoCorners(this.CornerFitRadius,Array.from(t.curve))),le.CalculateArrowheads(t)}}CreateVisibilityGraph(){this.GraphGenerator.Clear(),this.InitObstacleTree(),this.GraphGenerator.GenerateVisibilityGraph()}static CalculateArrowheads(t){Bt.trimSplineAndCalculateArrowheadsII(t,t.sourcePort.Curve,t.targetPort.Curve,t.curve,!0)}get ObsTree(){return this.GraphGenerator.ObstacleTree}GenerateObstacleTree(){if(this.Obstacles==null||this.Obstacles.length===0)throw new Error("No obstacles have been added");this.ObsTree.Root==null&&this.InitObstacleTree()}InitObstacleTree(){this.AncestorsSets=qt.GetAncestorSetsMap(this.Obstacles),this.ObsTree.Init(this.ShapeToObstacleMap.values(),this.AncestorsSets,this.ShapeToObstacleMap)}InternalClear(t){this.GraphGenerator.Clear(),this.ClearShortestPaths(),t?this.PortManager.ClearVisibility():(this.PortManager.Clear(),this.ShapeToObstacleMap.clear(),this.EdgesToRoute=[])}ClearShortestPaths(){for(const t of this.EdgesToRoute)t.curve=null}GenerateVisibilityGraph(){if(this.Obstacles==null||this.Obstacles.length===0)throw new Error("No obstacles have been set");this.GraphGenerator.VisibilityGraph==null&&this.CreateVisibilityGraph()}static FitArcsIntoCorners(t,e){if(t==0)return st.mkFromPoints(e);const i=le.GetFittedArcSegs(t,e),s=new w;let n=null;for(const o of i){const a=le.EllipseIsAlmostLineSegment(o);n!=null?a?w.continueWithLineSegmentP(s,le.CornerPoint(o)):(w.continueWithLineSegmentP(s,o.start),s.addSegment(o)):a?w.addLineSegment(s,e[0],le.CornerPoint(o)):(w.addLineSegment(s,e[0],o.start),s.addSegment(o)),n=o}return s.segs.length>0?w.continueWithLineSegmentP(s,e[e.length-1]):w.addLineSegment(s,e[0],e[e.length-1]),s}static CornerPoint(t){return t.center.add(t.aAxis.add(t.bAxis))}static EllipseIsAlmostLineSegment(t){return t.aAxis.lengthSquared<1e-4||t.aAxis.lengthSquared<1e-4}static*GetFittedArcSegs(t,e){let i=e[1].sub(e[0]),s=i.normalize(),n=Math.min(t,i.length/2);for(let o=1;o<e.length-1;o++){i=e[o+1].sub(e[o]);const a=i.length;if(a<C.intersectionEpsilon){yield new yt(0,0,new c(0,0),new c(0,0),e[o]);continue}const h=i.div(a);Math.abs(h.dot(s))>.9&&(yield new yt(0,0,new c(0,0),new c(0,0),e[o]));const u=Math.min(t,i.length/2),d=h.mul(-u),m=s.mul(n);yield new yt(0,Math.PI/2,d,m,e[o].sub(m.add(d))),s=h,n=u}}}le.DefaultPadding=1,le.DefaultCornerFitRadius=3;class us{constructor(t,e,i,s=1){this.Source=t,this.Target=e,this.CrossingWeight=i,this.Weight=s}toString(){return ue.Qf.format("{0}->{1}",this.Source,this.Target)}}class pn{static FindClosestPoints(t,e){const i=w.minDistWithinIntervals(t,e,t.parStart,t.parEnd,e.parStart,e.parEnd,(t.parStart+t.parEnd)/2,(e.parStart+e.parEnd)/2);if(i)return{curveClosestPoint:i.aX,labelSideClosest:i.bX}}static GetSegmentInFrontOfLabel(t,e){if(t instanceof w){for(const i of t.segs)if((i.start.y-e)*(i.end.y-e)<=0)return i}return null}static ShiftLabel(t,e,i){const s=t.lineWidth/2,n=e.sub(i),o=n.length;o>s&&t.label.positionCenter(t.label.center.add(n.div(o*(o-s))))}static updateLabel(t,e){let i=null;e.labelIsToTheRightOfTheSpline?(t.label.positionCenter(new c(e.x+e.rightAnchor/2,e.y)),i=N.mkPP(t.label.boundingBox.leftTop,t.label.boundingBox.leftBottom)):e.labelIsToTheLeftOfTheSpline&&(t.label.positionCenter(new c(e.x-e.leftAnchor/2,e.y)),i=N.mkPP(t.label.boundingBox.rightTop,t.label.boundingBox.rightBottom));const s=pn.GetSegmentInFrontOfLabel(t.curve,t.label.center.y);if(s!=null&&w.getAllIntersections(t.curve,w.polyFromBox(t.label.boundingBox),!1).length===0){const n=pn.FindClosestPoints(s,i);if(n)pn.ShiftLabel(t,n.curveClosestPoint,n.labelSideClosest);else{let o,a;const h=s.closestParameter(i.start),u=s.closestParameter(i.end);s.value(h).sub(i.start).length<s.value(u).sub(i.end).length?(o=s.value(h),a=i.start):(o=s.value(u),a=i.end),pn.ShiftLabel(t,o,a)}}}}class Ti{get CrossingWeight(){return 1}constructor(t,e,i,s=1,n=1){this.reversed=!1,this.source=t,this.target=e,this.edge=i,this.weight=s,this.separation=n}get hasLabel(){return this.edge.label!=null}get labelWidth(){return this.edge.label.width}get labelHeight(){return this.edge.label.height}reverse(){const t=this.source;this.source=this.target,this.target=t,this.reversed=!this.reversed}toString(){return"edge("+this.source+"->"+this.target+")"}get curve(){return this.edge.curve}set curve(t){this.edge.curve=t}get underlyingPolyline(){return this.edge.smoothedPolyline}get LayerSpan(){return this.LayerEdges!=null?this.LayerEdges.length:0}isSelfEdge(){return this.source===this.target}reversedClone(){const t=new Ti(this.target,this.source,this.edge);if(this.LayerEdges!=null){const e=this.LayerEdges.length;t.LayerEdges=new Array(e);for(let i=0;i<e;i++){const s=this.LayerEdges[e-1-i];t.LayerEdges[i]=new us(s.Target,s.Source,s.CrossingWeight)}t.LayerEdges[0].Source=this.target,t.LayerEdges[this.LayerEdges.length-1].Target=this.source}return t}get count(){return this.LayerEdges.length}getNode(t){if(t>=0){if(t<this.LayerEdges.length)return this.LayerEdges[t].Source;if(t===this.LayerEdges.length)return this.LayerEdges[t-1].Target}throw new Error("wrong index "+t)}updateEdgeLabelPosition(t){if(this.edge.label!=null){const e=this.LayerEdges.length/2,i=this.LayerEdges[e];pn.updateLabel(this.edge,t[i.Source])}}[Symbol.iterator](){return this.nodes()}*nodes(){yield this.LayerEdges[0].Source;for(const t of this.LayerEdges)yield t.Target}}class Gl{constructor(){this.maxLayerOfGeomGraph=new Set,this.minLayerOfGeomGraph=new Set,this.sameLayerConstraints=new Array,this.upDownConstraints=new Array,this.gluedUpDownIntConstraints=new Ii,this.sameLayerDictionaryOfRepresentatives=new Map,this.representativeToItsLayer=new Map,this.maxLayerInt=new Array,this.minLayerInt=new Array,this.sameLayerInts=new Array,this.upDownInts=new Array}getFeedbackSetExternal(t,e){throw new Error("Method not implemented.")}pinNodeToMaxLayer(t){this.maxLayerOfGeomGraph.add(t)}pinNodeToMinLayer(t){this.minLayerOfGeomGraph.add(t)}get isEmpty(){return this.maxLayerOfGeomGraph.size===0&&this.minLayerOfGeomGraph.size===0&&this.sameLayerConstraints.length===0&&this.upDownConstraints.length===0}clear(){this.maxLayerOfGeomGraph.clear(),this.minLayerOfGeomGraph.clear(),this.sameLayerConstraints=[],this.upDownConstraints=[]}getFeedbackSetImp(t,e){return this.nodeIdToIndex=e,this.intGraph=t,this.maxRepresentative=-1,this.minRepresentative=-1,this.createIntegerConstraints(),this.glueTogetherSameConstraintsMaxAndMin(),this.addMaxMinConstraintsToGluedConstraints(),this.removeCyclesFromGluedConstraints(),this.getFeedbackSet()}removeCyclesFromGluedConstraints(){const t=Qe(Array.from(this.gluedUpDownIntConstraints.values()),this.intGraph.nodeCount),e=S.getFeedbackSetWithConstraints(t,null);for(const i of e)this.gluedUpDownIntConstraints.remove(i)}addMaxMinConstraintsToGluedConstraints(){if(this.maxRepresentative!==-1)for(let t=0;t<this.intGraph.nodeCount;t++){const e=this.nodeToRepr(t);e!==this.maxRepresentative&&this.gluedUpDownIntConstraints.add(new Et(this.maxRepresentative,e))}if(this.minRepresentative!==-1)for(let t=0;t<this.intGraph.nodeCount;t++){const e=this.nodeToRepr(t);e!==this.minRepresentative&&this.gluedUpDownIntConstraints.add(new Et(e,this.minRepresentative))}}glueTogetherSameConstraintsMaxAndMin(){this.createDictionaryOfSameLayerRepresentatives();const t=this.upDownInts.map(this.gluedIntPairNN);this.gluedUpDownIntConstraints=new Ii}gluedIntPairNN(t){return new Et(this.nodeToRepr(t[0]),this.nodeToRepr(t[1]))}gluedIntPairI(t){return new Et(this.nodeToRepr(t.source),this.nodeToRepr(t.target))}gluedIntPair(t){return new Et(this.nodeToRepr(t.source),this.nodeToRepr(t.target))}gluedIntEdge(t){const e=this.nodeToRepr(t.source),i=this.nodeToRepr(t.target),s=new Ti(e,i,t.edge);return s.separation=t.separation,s.weight=0,s}nodeToRepr(t){const e=this.sameLayerDictionaryOfRepresentatives.get(t);return e||t}createDictionaryOfSameLayerRepresentatives(){const t=this.createGraphOfSameLayers();for(const e of Ci(t))this.glueSameLayerNodesOfALayer(e)}createGraphOfSameLayers(){return Qe(this.createEdgesOfSameLayers(),this.intGraph.nodeCount)}createEdgesOfSameLayers(){const t=new Array;return this.maxRepresentative!==-1&&this.maxLayerInt.filter(e=>e!==this.maxRepresentative).map(e=>new Et(this.maxRepresentative,e)).forEach(e=>t.push(e)),this.minRepresentative!==-1&&this.minLayerInt.filter(e=>e!==this.minRepresentative).map(e=>new Et(this.minRepresentative,e)).forEach(e=>t.push(e)),this.sameLayerInts.forEach(e=>t.push(new Et(e[0],e[1]))),t}glueSameLayerNodesOfALayer(t){if(t.length>1){let e=-1;if(this.componentsIsMaxLayer(t))for(const i of t)this.sameLayerDictionaryOfRepresentatives.set(i,e=this.maxRepresentative);else if(this.componentIsMinLayer(t))for(const i of t)this.sameLayerDictionaryOfRepresentatives.set(i,e=this.minRepresentative);else for(const i of t)e===-1&&(e=i),this.sameLayerDictionaryOfRepresentatives.set(i,e);this.representativeToItsLayer.set(e,t)}}componentIsMinLayer(t){return t.findIndex(e=>this.minRepresentative===e)>=0}componentsIsMaxLayer(t){return t.findIndex(e=>this.maxRepresentative===e)>=0}createIntegerConstraints(){this.createMaxIntConstraints(),this.createMinIntConstraints(),this.createUpDownConstraints(),this.createSameLayerConstraints()}createSameLayerConstraints(){this.sameLayerInts=this.createIntConstraintsFromStringCouples(this.sameLayerConstraints)}createUpDownConstraints(){this.upDownInts=this.createIntConstraintsFromStringCouples(this.upDownConstraints)}createIntConstraintsFromStringCouples(t){return t.map(e=>[this.nodeIndex(e[0]),this.nodeIndex(e[1])]).filter(e=>e[0]!==-1&&e[1]!==-1)}createMinIntConstraints(){this.minLayerInt=this.createIntConstraintsFromExtremeLayer(this.minLayerOfGeomGraph),this.minLayerInt.length>0&&(this.minRepresentative=this.minLayerInt[0])}createMaxIntConstraints(){this.maxLayerInt=this.createIntConstraintsFromExtremeLayer(this.maxLayerOfGeomGraph),this.maxLayerInt.length>0&&(this.maxRepresentative=this.maxLayerInt[0])}createIntConstraintsFromExtremeLayer(t){return Array.from(t).map(e=>this.nodeIndex(e)).filter(e=>e!==-1)}nodeIndex(t){const e=this.nodeIdToIndex.get(t.node.id);return e||-1}getFeedbackSet(){return this.gluedIntGraph=this.createGluedGraph(),Array.from(this.unglueIntPairs(S.getFeedbackSetWithConstraints(this.gluedIntGraph,this.gluedUpDownIntConstraints)))}*unglueIntPairs(t){for(const e of t)for(const i of this.unglueEdge(e))yield i}*unglueEdge(t){for(const e of this.unglueNode(t.source))for(const i of this.intGraph.outEdges[e])this.nodeToRepr(i.target)===t.target&&(yield i)}createGluedGraph(){const t=new Ii;return this.intGraph.edges.forEach(e=>t.add(this.gluedIntPairI(e))),Qe(Array.from(t.values()),this.intGraph.nodeCount)}unglueNode(t){const e=this.representativeToItsLayer.get(t);return e||[t]}getGluedNodeCounts(){const t=new Array(this.nodeIdToIndex.size).fill(0);for(let e=0;e<t.length;e++)t[this.nodeToRepr(e)]++;return t}}function kl(l,t){return[l,t]}class Ml{constructor(){this.leftRightConstraints=new Array,this.leftRightNeighbors=new Array,this.nodeToBlockRoot=new Map,this.upDownVerticalConstraints=new Array,this.BlockRootToBlock=new Map}get IsEmpty(){return this.leftRightNeighbors.length===0&&this.upDownVerticalConstraints.length===0&&this.leftRightConstraints.length===0}AddSameLayerNeighbors(t){for(let e=0;e<t.length-1;e++)this.AddSameLayerNeighborsPair(t[e],t[e+1])}AddSameLayerNeighborsPair(t,e){this.leftRightNeighbors.push([t,e])}NodeToBlockRootSoft(t){const e=this.nodeToBlockRoot.get(t);return e||t}CreateMappingOfNeibBlocks(){const t=this.BasicGraphFromLeftRightIntNeibs();for(let e=0;e<t.nodeCount;e++)if(t.inEdges[e].length===0&&!this.nodeToBlockRoot.has(e)){const i=new Array;let s=e;for(let n=t.outEdges[s];n.length>0;n=t.outEdges[s])s=n[0].y,i.push(s),this.nodeToBlockRoot.set(s,e);i.length>0&&this.BlockRootToBlock.set(e,i)}}BasicGraphFromLeftRightIntNeibs(){return Rs(Array.from(this.LeftRightIntNeibs.values()).map(t=>new Et(t.x,t.y)))}NodeIndex(t){const e=this.nodeIdToIndex.get(t.id);return e||-1}PrepareForOrdering(t,e){this.nodeIdToIndex=t,this.MapNodesToToIntegers(e),this.CreateMappingOfNeibBlocks(),this.LiftLeftRightRelationsToNeibBlocks()}LiftLeftRightRelationsToNeibBlocks(){this.LeftRighInts=Ii.mk(this.leftRightConstraints.map(e=>kl(this.NodeIndex(e[0]),this.NodeIndex(e[1]))).filter(e=>e[0]!==-1&&e[1]!==-1).map(e=>new Et(this.NodeToBlockRootSoft(e[0]),this.NodeToBlockRootSoft(e[1]))).filter(e=>e.x!==e.x));const t=S.getFeedbackSet(Rs(Array.from(this.LeftRighInts.values())));for(const e of t)this.LeftRighInts.remove(new Et(e.source,e.target))}MapNodesToToIntegers(t){this.LeftRightIntNeibs=Ii.mk(Array.from(this.leftRightNeighbors.values()).map(e=>[this.NodeIndex(e[0]),this.NodeIndex(e[1])]).filter(e=>e[0]!==-1&&e[1]!==-1).map(e=>new Et(e[0],e[1]))),this.VerticalInts=Ii.mk(this.upDownVerticalConstraints.map(e=>[this.NodeIndex(e[0]),this.NodeIndex(e[1])]).filter(e=>e[0]!==-1&&e[1]!==-1&&t[e[0]]>t[e[1]]).map(e=>new Et(e[0],e[1])))}}var di;(function(l){l[l.TB=0]="TB",l[l.LR=1]="LR",l[l.BT=2]="BT",l[l.RL=3]="RL",l[l.None=4]="None"})(di||(di={}));var Be;(function(l){l[l.Spline=0]="Spline",l[l.SplineBundling=1]="SplineBundling",l[l.StraightLine=2]="StraightLine",l[l.SugiyamaSplines=3]="SugiyamaSplines",l[l.Rectilinear=4]="Rectilinear",l[l.RectilinearToCenter=5]="RectilinearToCenter",l[l.None=6]="None"})(Be||(Be={}));class tr{toJSON(){const t={};return this.EdgeRoutingMode!=Be.Spline&&(t.edgeRoutingMode=Be.Spline),this.ConeAngle!=30*(Math.PI/180)&&(t.coneAngle=this.ConeAngle),this.padding!=3&&(t.padding=this.padding),this.polylinePadding!=1.5&&(t.polylinePadding=this.polylinePadding),this.bundlingSettings&&(t.bundlingSettingsJSON=this.bundlingSettings.toJSON()),t}static fromJSON(t){const e=new tr;return t.edgeRoutingMode&&(t.edgeRoutingMode=e.edgeRoutingMode),t.coneAngle&&(e.coneAngle=t.coneAngle),t.padding&&(e.padding=t.padding),t.polylinePadding&&(e.polylinePadding=t.polylinePadding),t.bundlingSettingsJSON&&(e.bundlingSettings=re.createFromJSON(t.bundlingSettingsJSON)),t.routingToParentConeAngle&&(e.routingToParentConeAngle=t.routingToParentConeAngle),t.simpleSelfLoopsForParentEdgesThreshold&&(e.simpleSelfLoopsForParentEdgesThreshold=t.simpleSelfLoopsForParentEdgesThreshold),t.incrementalRoutingThreshold&&(e.incrementalRoutingThreshold=t.incrementalRoutingThreshold),t.routeMultiEdgesAsBundles&&(e.routeMultiEdgesAsBundles=t.routeMultiEdgesAsBundles),t.KeepOriginalSpline&&(e.KeepOriginalSpline=t.KeepOriginalSpline),e}constructor(){this.coneAngle=30*(Math.PI/180),this.padding=2,this.polylinePadding=1,this.routingToParentConeAngle=Math.PI/6,this.simpleSelfLoopsForParentEdgesThreshold=200,this.incrementalRoutingThreshold=5e6,this.routeMultiEdgesAsBundles=!0,this.KeepOriginalSpline=!1,this.EdgeRoutingMode=Be.Spline}get EdgeRoutingMode(){return this.edgeRoutingMode}set EdgeRoutingMode(t){t===Be.SplineBundling&&this.bundlingSettings==null&&this.bundlingSettings==null&&(this.bundlingSettings=new re),this.edgeRoutingMode=t}get ConeAngle(){return this.coneAngle}set ConeAngle(t){this.coneAngle=t}get Padding(){return this.padding}set Padding(t){this.padding=t}get PolylinePadding(){return this.polylinePadding}set PolylinePadding(t){this.polylinePadding=t}get RoutingToParentConeAngle(){return this.routingToParentConeAngle}set RoutingToParentConeAngle(t){this.routingToParentConeAngle=t}get SimpleSelfLoopsForParentEdgesThreshold(){return this.simpleSelfLoopsForParentEdgesThreshold}set SimpleSelfLoopsForParentEdgesThreshold(t){this.simpleSelfLoopsForParentEdgesThreshold=t}get IncrementalRoutingThreshold(){return this.incrementalRoutingThreshold}set IncrementalRoutingThreshold(t){this.incrementalRoutingThreshold=t}get RouteMultiEdgesAsBundles(){return this.routeMultiEdgesAsBundles}set RouteMultiEdgesAsBundles(t){this.routeMultiEdgesAsBundles=t}}class mn{constructor(){this.edgeRoutingSettings=new tr,this.nodeSeparation=10,this.packingAspectRatio=1.5}static fromJSON(t){const e=new mn;return t.nodeSeparation!=10&&(e.nodeSeparation=t.nodeSeparation),t.packingAspectRatio&&(e.packingAspectRatio=t.packingAspectRatio),t.edgeRoutingSettings&&(e.edgeRoutingSettings=tr.fromJSON(t.edgeRoutingSettings)),e}toJSON(){let t=!1;const e={};return this.nodeSeparation!=10&&(e.nodeSeparation=this.nodeSeparation,t=!0),this.packingAspectRatio!=1.5&&(e.packingAspectRatio=this.packingAspectRatio,t=!0),(e.edgeRoutingSettings=this.edgeRoutingSettings.toJSON())&&(t=!0),t?e:void 0}get NodeSeparation(){return this.nodeSeparation}set NodeSeparation(t){this.nodeSeparation=t}get PackingAspectRatio(){return this.packingAspectRatio}set PackingAspectRatio(t){this.packingAspectRatio=t}}var Pn;(function(l){l[l.None=0]="None",l[l.Top=1]="Top",l[l.Bottom=2]="Bottom"})(Pn||(Pn={}));class Hs{get NodeSeparation(){return this.commonSettings.NodeSeparation}get edgeRoutingSettings(){return this.commonSettings.edgeRoutingSettings}set edgeRoutingSettings(t){this.commonSettings.edgeRoutingSettings=t}toJSON(){const t={};return this.sameRanks&&(t.sameRanks=this.sameRanks),this.verticalConstraints&&(t.verticalConstraints=this.verticalConstraints),this.horizontalConstraints&&(t.horizontalConstraints=this.horizontalConstraints),this.NoGainAdjacentSwapStepsBound!=5&&(t.horizontalConstraints=this.horizontalConstraints),this.NoGainStepsForOrderingMultiplier!=1&&(t.RepetitionCoefficientForOrdering=this.NoGainStepsForOrderingMultiplier),this.AspectRatio&&(t.AspectRatio=this.AspectRatio),this.MaxNumberOfPassesInOrdering!=24&&(t.MaxNumberOfPassesInOrdering=this.MaxNumberOfPassesInOrdering),this.BrandesThreshold!=600&&(t.BrandesThreshold=this.BrandesThreshold),this.LabelCornersPreserveCoefficient!=.1&&(t.LabelCornersPreserveCoefficient=this.LabelCornersPreserveCoefficient),this.MinNodeHeight!=72*.5/4&&(t.MinNodeHeight=this.MinNodeHeight),this.MinNodeWidth!=72*.75/4&&(t.MinNodeWidth=this.MinNodeWidth),this.SnapToGridByY!=Pn.None&&(t.SnapToGridByY=this.SnapToGridByY),this.yLayerSep!=30&&(t.yLayerSep=this.yLayerSep),this.transform&&(t.transform=this.transform.elements),this.GridSizeByY&&(t.GridSizeByY=this.GridSizeByY),this.GridSizeByX&&(t.GridSizeByX=this.GridSizeByX),t.commonLayoutSettings=this.commonSettings.toJSON(),t}static fromJSON(t){const e=new Hs;return t.sameRanks&&(e.sameRanks=t.sameRanks),t.verticalConstraints&&(e.verticalConstraints=t.verticalConstraints),t.horizontalConstraints&&(e.horizontalConstraints=t.horizontalConstraints),t.NoGainAdjacentSwapStepsBound&&(e.horizontalConstraints=t.horizontalConstraints),t.RepetitionCoefficientForOrdering&&(e.NoGainStepsForOrderingMultiplier=t.RepetitionCoefficientForOrdering),t.AspectRatio&&(e.AspectRatio=t.AspectRatio),t.MaxNumberOfPassesInOrdering&&(e.MaxNumberOfPassesInOrdering=t.MaxNumberOfPassesInOrdering),t.BrandesThreshold&&(e.BrandesThreshold=t.BrandesThreshold),t.LabelCornersPreserveCoefficient&&(e.LabelCornersPreserveCoefficient=t.LabelCornersPreserveCoefficient),t.MinNodeHeight&&(e.MinNodeHeight=t.MinNodeHeight),t.MinNodeWidth&&(e.MinNodeWidth=e.MinNodeWidth),t.SnapToGridByY&&(e.SnapToGridByY=t.SnapToGridByY),t.yLayerSep&&(e.yLayerSep=t.yLayerSep),t.transform&&(e.transform=new U(t.transform[0][0],t.transform[0][1],t.transform[0][2],t.transform[1][0],t.transform[1][1],t.transform[1][2])),t.GridSizeByY&&(e.GridSizeByY=t.GridSizeByY),t.GridSizeByX&&(e.GridSizeByX=t.GridSizeByX),t.commonLayoutSettings&&(e.commonSettings=mn.fromJSON(t.commonLayoutSettings)),e}get LayerSeparation(){return this.yLayerSep}set LayerSeparation(t){this.yLayerSep=Math.max(30,t)}ActualLayerSeparation(t){return t?this.LayerSeparation/2:this.LayerSeparation}constructor(){this.commonSettings=new mn,this.verticalConstraints=new Gl,this.horizontalConstraints=new Ml,this.NoGainAdjacentSwapStepsBound=5,this.NoGainStepsForOrderingMultiplier=1,this.AspectRatio=0,this.MaxNumberOfPassesInOrdering=24,this.BrandesThreshold=600,this.LabelCornersPreserveCoefficient=.1,this.MinNodeHeight=72*.5/4,this.MinNodeWidth=72*.75/4,this.SnapToGridByY=Pn.None,this.yLayerSep=30,this.transform=U.getIdentity(),this.GridSizeByY=0,this.GridSizeByX=0,this.commonSettings.edgeRoutingSettings.EdgeRoutingMode=Be.SugiyamaSplines}transformIsRotation(t){const e=U.rotation(t);for(let i=0;i<2;i++)for(let s=0;s<3;s++)if(!R(e.elements[i][s],this.transform.elements[i][s]))return!1;return!0}get layerDirection(){if(this.transformIsRotation(0))return di.TB;if(this.transformIsRotation(Math.PI/2))return di.LR;if(this.transformIsRotation(-Math.PI/2))return di.RL;if(this.transformIsRotation(Math.PI))return di.BT;throw new Error("unexpected layout direction")}set layerDirection(t){switch(t){case di.TB:this.transform=U.getIdentity();break;case di.LR:this.transform=U.rotation(Math.PI/2);break;case di.RL:this.transform=U.rotation(-Math.PI/2);break;case di.BT:this.transform=U.rotation(Math.PI);break;default:throw new Error("unexpected layout direction")}}}class Ea extends Ft{constructor(t,e,i){super(null),this.graph=t,this.source=e,this.length=i}get Result(){return this.result}run(){const t=new Ri((s,n)=>s-n),e=new Map;for(const s of this.graph.shallowNodes){const n=s===this.source?0:Number.POSITIVE_INFINITY;t.Enqueue(s,n),e.set(s,n)}for(;t.count>0;){const s={priority:0},n=t.DequeueAndGetPriority(s);e.set(n,s.priority);const o=e.get(n);for(const a of n.inEdges()){const h=a.source,u=o+this.length(a);e.get(h)>u&&(e.set(h,u),t.DecreasePriority(h,u))}for(const a of n.outEdges()){const h=a.target,u=o+this.length(a);e.get(h)>u&&(e.set(h,u),t.DecreasePriority(h,u))}}this.result=new Array(this.graph.shallowNodeCount);let i=0;for(const s of this.graph.shallowNodes){const n=e.get(s);n!==void 0?this.result[i++]=n:this.result[i++]=Number.POSITIVE_INFINITY}}}class vo extends Ft{get Result(){return this.result}set Result(t){this.result=t}constructor(t,e){super(null),this.graph=t,this.length=e}run(){this.result=new Array(this.graph.shallowNodeCount);let t=0;for(const e of this.graph.shallowNodes){const i=new Ea(this.graph,e,this.length);i.run(),this.Result[t++]=i.Result}}static Stress(t,e){let i=0;if(t.edgeCount===0)return i;const s=new vo(t,e);s.run();const n=s.Result;let o=0;for(const h of t.shallowEdges)o+=e(h);o/=t.edgeCount;let a=0;for(const h of t.shallowNodes){let u=0;for(const d of t.shallowNodes){if(a!==u){const m=h.center.sub(d.center).length,y=o*n[a][u],E=y-m;i+=E*E/(y*y)}u++}a++}return i}}class Vl extends Ft{get Result(){return this.result}constructor(t,e,i){super(null),this.graph=t,this.pivotArray=e,this.length=i}run(){this.result=new Array(this.pivotArray.length);const t=Array.from(this.graph.shallowNodes),e=new Array(this.graph.shallowNodeCount).fill(Number.POSITIVE_INFINITY);let i=t[0];this.pivotArray[0]=0;for(let s=0;;s++){const n=new Ea(this.graph,i,this.length);if(n.run(),this.Result[s]=n.Result,s+1<this.pivotArray.length){let o=0;for(let a=0;a<this.Result[s].length;a++)e[a]=Math.min(e[a],this.Result[s][a]),e[a]>e[o]&&(o=a);i=t[o],this.pivotArray[s+1]=o}else break}}}class Wl{static Rotate(t,e,i){const s=Math.sin(i*(Math.PI/180)),n=Math.cos(i*(Math.PI/180));for(let o=0;o<t.length;o++){const a=n*t[o]+s*e[o];e[o]=n*e[o]-s*t[o],t[o]=a}}}class kt{static DoubleCenter(t){const e=new Array(t.length).fill(0),i=new Array(t[0].length).fill(0);let s=0;for(let n=0;n<t.length;n++)for(let o=0;o<t[0].length;o++)e[n]+=t[n][o],i[o]+=t[n][o],s+=t[n][o];for(let n=0;n<t.length;n++)e[n]/=t.length;for(let n=0;n<t[0].length;n++)i[n]/=t[0].length;s/=t.length,s/=t[0].length;for(let n=0;n<t.length;n++)for(let o=0;o<t[0].length;o++)t[n][o]-=e[n]+i[o]-s}static SquareEntries(t){for(let e=0;e<t.length;e++)for(let i=0;i<t[0].length;i++)t[e][i]=Math.pow(t[e][i],2)}static Multiply(t,e){for(let i=0;i<t.length;i++)for(let s=0;s<t[0].length;s++)t[i][s]*=e}static MultiplyX(t,e){if(t[0].length!==e.length)return null;const i=new Array(e.length).fill(0);for(let s=0;s<t.length;s++)for(let n=0;n<t[0].length;n++)i[s]+=t[s][n]*e[n];return i}static Norm(t){let e=0;for(let i=0;i<t.length;i++)e+=Math.pow(t[i],2);return Math.sqrt(e)}static Normalize(t){const e=kt.Norm(t);if(e<=0)return 0;for(let i=0;i<t.length;i++)t[i]/=e;return e}static RandomUnitLengthVector(t){const e=new Array(t);for(let i=0;i<t;i++)e[i]=Wi();return kt.Normalize(e),e}static SpectralDecomposition(t,e){kt.SpectralDecompositionIE(t,e,30,1e-6)}static SpectralDecompositionIE(t,e,i,s){const n=t[0].length;e.u1=kt.RandomUnitLengthVector(n),e.lambda1=0,e.u2=kt.RandomUnitLengthVector(n),e.lambda2=0;let o=0;const a=1-s;for(let h=0;h<i&&o<a;h++){const u=kt.MultiplyX(t,e.u1),d=kt.MultiplyX(t,e.u2);e.lambda1=kt.Normalize(u),e.lambda2=kt.Normalize(d),kt.MakeOrthogonal(d,u),kt.Normalize(d),o=Math.min(kt.DotProduct(e.u1,u),kt.DotProduct(e.u2,d)),e.u1=u,e.u2=d}}static DotProduct(t,e){if(t.length!==e.length)return 0;let i=0;for(let s=0;s<t.length;s++)i+=t[s]*e[s];return i}static MakeOrthogonal(t,e){if(t.length!==e.length)return;const i=kt.DotProduct(t,e)/kt.DotProduct(e,e);for(let s=0;s<t.length;s++)t[s]-=i*e[s]}static ClassicalScaling(t,e){const i=new Array(t.length);for(let s=0;s<t.length;s++)i[s]=t[s].slice();kt.SquareEntries(i),kt.DoubleCenter(i),kt.Multiply(i,-.5),kt.SpectralDecomposition(i,e),e.lambda1=Math.sqrt(Math.abs(e.lambda1)),e.lambda2=Math.sqrt(Math.abs(e.lambda2));for(let s=0;s<e.u1.length;s++)e.u1[s]*=e.lambda1,e.u2[s]*=e.lambda2}static DistanceScalingSubset(t,e,i,s,n){const o=e.length,a=t.length,h=new Array(a);for(let d=0;d<a;d++)for(let m=0;m<o;m++)t[d][m]===0&&(h[d]=m);const u=new Array(a).fill(0);for(let d=0;d<a;d++)for(let m=0;m<o;m++)h[d]!==m&&(u[d]+=s[d][m]);for(let d=0;d<n;d++)for(let m=0;m<a;m++){let y=0,E=0;for(let T=0;T<o;T++)if(m!==T){let B=Math.sqrt(Math.pow(e[h[m]]-e[T],2)+Math.pow(i[h[m]]-i[T],2));B>0&&(B=1/B),y+=s[m][T]*(e[T]+t[m][T]*(e[h[m]]-e[T])*B),E+=s[m][T]*(i[T]+t[m][T]*(i[h[m]]-i[T])*B)}e[h[m]]=y/u[m],i[h[m]]=E/u[m]}}static DistanceScaling(t,e,i,s,n){const o=e.length,a=new Array(o).fill(0);for(let h=0;h<o;h++)for(let u=0;u<o;u++)h!==u&&(a[h]+=s[h][u]);for(let h=0;h<n;h++)for(let u=0;u<o;u++){let d=0,m=0;for(let y=0;y<o;y++)if(u!==y){let E=Math.sqrt(Math.pow(e[u]-e[y],2)+Math.pow(i[u]-i[y],2));E>0&&(E=1/E),d+=s[u][y]*(e[y]+t[u][y]*(e[u]-e[y])*E),m+=s[u][y]*(i[y]+t[u][y]*(i[u]-i[y])*E)}e[u]=d/a[u],i[u]=m/a[u]}}static ExponentialWeightMatrix(t,e){const i=new Array(t.length);for(let s=0;s<t.length;s++){i[s]=new Array(t[s].length).fill(0);for(let n=0;n<t[s].length;n++)t[s][n]>0&&(i[s][n]=Math.pow(t[s][n],e))}return i}static EuclideanDistanceMatrix(t,e){const i=new Array(t.length);for(let s=0;s<t.length;s++){i[s]=new Array(t.length);for(let n=0;n<t.length;n++)i[s][n]=Math.sqrt(Math.pow(t[s]-t[n],2)+Math.pow(e[s]-e[n],2))}return i}static LandmarkClassicalScaling(t,e,i){const s=new Array(t.length);for(let a=0;a<t.length;a++){s[a]=new Array(t.length);for(let h=0;h<t.length;h++)s[a][h]=t[a][i[h]]}kt.SquareEntries(s);const n=new Array(t.length).fill(0);for(let a=0;a<t.length;a++){for(let h=0;h<t.length;h++)n[a]+=s[a][h];n[a]/=t.length}kt.DoubleCenter(s),kt.Multiply(s,-.5);const o={u1:new Array,u2:new Array,lambda1:0,lambda2:0};kt.SpectralDecomposition(s,o),o.lambda1=Math.sqrt(Math.abs(o.lambda1)),o.lambda2=Math.sqrt(Math.abs(o.lambda2)),e.x=new Array(t[0].length).fill(0),e.y=new Array(t[0].length).fill(0);for(let a=0;a<e.x.length;a++)for(let h=0;h<s.length;h++){const u=(Math.pow(t[h][a],2)-n[h])/2;e.x[a]-=o.u1[h]*u,e.y[a]-=o.u2[h]*u}}}class Hl{constructor(t,e){this.constrained=!1,this.Capacity=1e6,ie.AbovePP(t.point,e.point)===1?(this.upperSite=t,this.lowerSite=e):(this.lowerSite=t,this.upperSite=e),this.upperSite.AddEdgeToSite(this)}get CcwTriangle(){return this.ccwTriangle}set CcwTriangle(t){this.ccwTriangle=t}get CwTriangle(){return this.cwTriangle}set CwTriangle(t){this.cwTriangle=t}GetOtherTriangle_c(t){return this.cwTriangle.Contains(t)?this.ccwTriangle:this.cwTriangle}IsAdjacent(t){return t===this.upperSite||t===this.lowerSite}GetOtherTriangle_T(t){return this.ccwTriangle===t?this.cwTriangle:this.ccwTriangle}toString(){return ue.Qf.format("({0},{1})",this.upperSite,this.lowerSite)}OtherSite(t){return this.upperSite===t?this.lowerSite:this.upperSite}}class er{cleanRemovedEdges(){for(const t of this.Edges)t.CcwTriangle===null&&t.CwTriangle===null&&this.Edges.splice(this.Edges.indexOf(t),1)}constructor(t){this.Owner=null,this.InEdges=new Array,this.point=t}static mkSO(t,e){const i=new er(t);return i.Owner=e,i}AddEdgeToSite(t){this.Edges==null&&(this.Edges=new Array),this.Edges.push(t)}EdgeBetweenUpperSiteAndLowerSite(t){if(this.Edges!=null){for(const e of this.Edges)if(e.lowerSite===t)return e}return null}AddInEdge(t){this.InEdges.push(t)}*Triangles(){let t;if(this.Edges!=null&&this.Edges.length>0)t=this.Edges[0];else if(this.InEdges!=null&&this.InEdges.length>0)t=this.InEdges[0];else return;let e=t;do{const i=e.upperSite===this?e.CcwTriangle:e.CwTriangle;if(i==null){e=null;break}yield i,e=i.Edges.getItem(i.Edges.index(e)+2)}while(e!==t);if(e!==t){e=t;do{const i=e.upperSite===this?e.CwTriangle:e.CcwTriangle;if(i==null)break;yield i,e=i.Edges.getItem(i.Edges.index(e)+1)}while(!0)}}toString(){return this.point.toString()}}class Sn{get x(){return this.LeftSite.point.x}constructor(t,e){this.RightSite=e.upperSite===t?e.lowerSite:e.upperSite,this.LeftSite=t,this.Edge=e}toString(){return"("+this.LeftSite.toString()+", "+this.Edge.toString()+","+this.RightSite.toString()+")"}}class Io{has(t){return t===this.item0||t===this.item1||t===this.item2}index(t){return t===this.item0?0:t===this.item1?1:t===this.item2?2:-1}getItem(t){switch(t){case 0:case 3:case-3:return this.item0;case 1:case 4:case-2:return this.item1;case 2:case 5:case-1:return this.item2;default:throw new Error}}setItem(t,e){switch(t){case 0:case 3:case-3:this.item0=e;break;case 1:case 4:case-2:this.item1=e;break;case 2:case 5:case-1:this.item2=e;break;default:throw new Error}}[Symbol.iterator](){return this.GetEnumerator()}*GetEnumerator(){yield this.item0,yield this.item1,yield this.item2}}function ec(l,t,e){const i=new Io;return i.item0=l,i.item1=t,i.item2=e,i}class He{constructor(){this.Edges=new Io,this.Sites=new Io}containsPoint(t){return He.PointLocationForTriangle(t,this)!==at.Outside}static PointLocationForTriangle(t,e){let i=!1;for(let s=0;s<3;s++){const n=c.signedDoubledTriangleArea(t,e.Sites.getItem(s).point,e.Sites.getItem(s+1).point);if(n<-C.distanceEpsilon)return at.Outside;n<C.distanceEpsilon&&(i=!0)}return i?at.Boundary:at.Inside}intersectsLine(t,e,i){if(He.PointLocationForTriangle(t,this)!=at.Outside||He.PointLocationForTriangle(e,this)!=at.Outside)return!0;for(const s of this.Edges)if(this.abIntersectsTrianglSide(t,e,s))return!0;return!1}abIntersectsTrianglSide(t,e,i){return Js(t,e,i.lowerSite.point,i.upperSite.point)}static mkSSSD(t,e,i,s){const n=c.getTriangleOrientation(t.point,e.point,i.point),o=new He;switch(n){case D.Counterclockwise:o.FillCcwTriangle(t,e,i,s);break;case D.Clockwise:o.FillCcwTriangle(t,i,e,s);break;default:throw new Error}return o}static mkSED(t,e,i){const s=new He;switch(c.getTriangleOrientation(e.upperSite.point,e.lowerSite.point,t.point)){case D.Counterclockwise:e.CcwTriangle=s,s.Sites.setItem(0,e.upperSite),s.Sites.setItem(1,e.lowerSite);break;case D.Clockwise:e.CwTriangle=s,s.Sites.setItem(0,e.lowerSite),s.Sites.setItem(1,e.upperSite);break;default:throw new Error}return s.Edges.setItem(0,e),s.Sites.setItem(2,t),s.CreateEdge(1,i),s.CreateEdge(2,i),s}static mkSSSEE(t,e,i,s,n,o){const a=He.mkSSSD(t,e,i,o);return a.Edges.setItem(0,s),a.Edges.setItem(1,n),a.BindEdgeToTriangle(t,s),a.BindEdgeToTriangle(e,n),a.CreateEdge(2,o),a}BindEdgeToTriangle(t,e){t===e.upperSite?e.CcwTriangle=this:e.CwTriangle=this}FillCcwTriangle(t,e,i,s){this.Sites.setItem(0,t),this.Sites.setItem(1,e),this.Sites.setItem(2,i);for(let n=0;n<3;n++)this.CreateEdge(n,s)}CreateEdge(t,e){const i=this.Sites.getItem(t),s=this.Sites.getItem(t+1),n=e(i,s);this.Edges.setItem(t,n),this.BindEdgeToTriangle(i,n)}Contains(t){return this.Sites.has(t)}OppositeEdge(t){const e=this.Sites.index(t);return this.Edges.getItem(e+1)}OppositeSite(t){const e=this.Edges.index(t);return this.Sites.getItem(e+2)}BoundingBox(){const t=X.mkPP(this.Sites.getItem(0).point,this.Sites.getItem(1).point);return t.add(this.Sites.getItem(2).point),t}static mkSSSEED(t,e,i,s,n,o){const a=new He;return a.Sites.setItem(0,t),a.Sites.setItem(1,e),a.Sites.setItem(2,i),a.Edges.setItem(0,s),a.Edges.setItem(1,n),a.BindEdgeToTriangle(t,s),a.BindEdgeToTriangle(e,n),a.CreateEdge(2,o),a}toString(){return this.Sites.getItem(0).toString()+","+this.Sites.getItem(1).toString()+","+this.Sites.getItem(2).toString()}}class ba{constructor(t){this.Edge=t}}class Ce extends Ft{constructor(t,e,i,s){if(super(null),this.front=new Me((o,a)=>o.x-a.x),this.triangles=new Set,this.listOfSites=t,this.listOfSites.length===0)return;this.p_1=e,this.p_2=i,this.createEdgeDelegate=s;const n=He.mkSSSD(e,i,this.listOfSites[0],s);this.triangles.add(n),this.front.insert(new Sn(e,n.Edges.getItem(2))),this.front.insert(new Sn(this.listOfSites[0],n.Edges.getItem(1)))}run(){if(this.listOfSites.length!==0){for(let t=1;t<this.listOfSites.length;t++)this.ProcessSite(this.listOfSites[t]);this.FinalizeTriangulation()}}FinalizeTriangulation(){this.RemoveP1AndP2Triangles(),this.triangles.size>0&&this.MakePerimeterConvex()}MakePerimeterConvex(){let t=this.CreateDoubleLinkedListOfPerimeter();do{const e=this.FindConcaveEdge(t);if(e==null)return;t=this.ShortcutTwoListElements(e)}while(!0)}FindConcaveEdge(t){let e=t,i;do{if(i=e.Next,c.getTriangleOrientation(e.Start.point,e.End.point,i.End.point)===D.Counterclockwise)return e;e=i}while(i!==t);return null}static FindPivot(t){let e=t,i=t;do i=i.Next,(i.Start.point.x<e.Start.point.x||i.Start.point.x===e.Start.point.x&&i.Start.point.y<e.Start.point.y)&&(e=i);while(i!==t);return e}FindFirsePerimeterEdge(){for(const t of this.triangles)for(const e of t.Edges)if(e.GetOtherTriangle_T(t)==null)return e;return null}CreateDoubleLinkedListOfPerimeter(){const t=this.FindFirsePerimeterEdge();let e=t,i=null,s,n=null;const o=new Array;do s=Ce.CreatePerimeterElementFromEdge(e),o.push(N.mkPP(s.Start.point,s.End.point)),e=Ce.FindNextEdgeOnPerimeter(e),n!=null?(s.Prev=n,n.Next=s):i=s,n=s;while(e!==t);return i.Prev=s,s.Next=i,i}static FindNextEdgeOnPerimeter(t){var e;let i=(e=t.CwTriangle)!==null&&e!==void 0?e:t.CcwTriangle;for(t=i.Edges.getItem(i.Edges.index(t)+2);t.CwTriangle!=null&&t.CcwTriangle!=null;)i=t.GetOtherTriangle_T(i),t=i.Edges.getItem(i.Edges.index(t)+2);return t}static CreatePerimeterElementFromEdge(t){const e=new ba(t);return t.CwTriangle!=null?(e.Start=t.upperSite,e.End=t.lowerSite):(e.End=t.upperSite,e.Start=t.lowerSite),e}RemoveP1AndP2Triangles(){const t=new Set;for(const e of this.triangles)(e.Sites.has(this.p_1)||e.Sites.has(this.p_2))&&t.add(e);for(const e of t)Ce.RemoveTriangleWithEdges(this.triangles,e)}static RemoveTriangleWithEdges(t,e){t.delete(e);for(const i of e.Edges)i.CwTriangle===e?i.CwTriangle=null:i.CcwTriangle=null,i.CwTriangle==null&&i.CcwTriangle==null&&To(i.upperSite.Edges,i)}static RemoveTriangleButLeaveEdges(t,e){t.delete(e);for(const i of e.Edges)i.CwTriangle===e?i.CwTriangle=null:i.CcwTriangle=null}ProcessSite(t){this.PointEvent(t);for(let e=0;e<t.Edges.length;e++){const i=t.Edges[e];i.constrained&&this.EdgeEvent(i)}}EdgeEvent(t){Ce.EdgeIsProcessed(t)||(this.traversingEdge=t,this.runEdgeInserter())}static EdgeIsProcessed(t){return t.CwTriangle!=null||t.CcwTriangle!=null}ShowFrontWithSite(t,e=null){const i=new Array;if(t.Edges!=null)for(const s of t.Edges)i.push(wt.mkDebugCurveTWCI(200,.8,s.constrained?"Pink":"Brown",N.mkPP(s.upperSite.point,s.lowerSite.point)));i.push(wt.mkDebugCurveTWCI(200,1,"Brown",yt.mkFullEllipseNNP(.5,.5,t.point)));for(const s of this.triangles)for(let n=0;n<3;n++){const o=s.Edges.getItem(n);i.push(wt.mkDebugCurveTWCI(o.constrained?155:100,o.constrained?.8:.4,o.constrained?"Pink":"Navy",N.mkPP(o.upperSite.point,o.lowerSite.point)))}if(e!=null)for(const s of e)i.push(wt.mkDebugCurveTWCI(100,.5,"Red",s));for(const s of this.front)i.push(wt.mkDebugCurveTWCI(100,5.5,"Green",N.mkPP(s.Edge.upperSite.point,s.Edge.lowerSite.point)))}Show(t){Ce.ShowCdt(Array.from(this.triangles.values()),this.front,null,null,[],t)}static ShowCdt(t,e,i,s,n,o){let a=new Array;if(i!=null)for(const h of i)a.push(wt.mkDebugCurveTWCI(200,.1,"Red",h));if(s!=null)for(const h of s)a.push(wt.mkDebugCurveTWCI(200,.1,"Blue",h));if(e!=null)for(const h of e)a.push(wt.mkDebugCurveTWCI(200,.1,"Green",N.mkPP(h.Edge.upperSite.point,h.Edge.lowerSite.point)));for(const h of t)for(let u=0;u<3;u++){const d=h.Edges.getItem(u);a.push(Ce.GetDebugCurveOfCdtEdge(d))}a=a.concat(n)}static GetDebugCurveOfCdtEdge(t){return t.CcwTriangle==null||t.CwTriangle==null?wt.mkDebugCurveTWCI(255,.5,t.constrained?"Brown":"Black",N.mkPP(t.upperSite.point,t.lowerSite.point)):wt.mkDebugCurveTWCI(200,t.constrained?.8:.2,t.constrained?"Pink":"Navy",N.mkPP(t.upperSite.point,t.lowerSite.point))}PointEvent(t){const e=this.ProjectToFront(t),i={rightSite:null},s=e.item.x+C.distanceEpsilon<t.point.x?this.MiddleCase(t,e,i):this.LeftCase(t,e,i);let n=this.InsertSiteIntoFront(s,t,i.rightSite);this.TriangulateEmptySpaceToTheRight(n),n=Ce.FindNodeInFrontBySite(this.front,s),this.TriangulateEmptySpaceToTheLeft(n)}LeftCase(t,e,i){const s=e.item;this.InsertAndLegalizeTriangle(t,s);const n=this.front.previous(e),o=n.item.LeftSite;i.rightSite=e.item.RightSite,this.InsertAndLegalizeTriangle(t,n.item),this.front.deleteNodeInternal(n);const a=this.front.remove(s);return o}MiddleCase(t,e,i){const s=e.item.LeftSite;return i.rightSite=e.item.RightSite,this.InsertAndLegalizeTriangle(t,e.item),this.front.deleteNodeInternal(e),s}TriangulateEmptySpaceToTheLeft(t){const e=t.item.RightSite;let i=this.front.previous(t);for(;i!=null;){const s=i.item,n=s.LeftSite,o=s.RightSite;if(o.point.sub(e.point).dot(n.point.sub(o.point))<0)t=this.ShortcutTwoFrontElements(i,t),i=this.front.previous(t);else{this.TryTriangulateBasinToTheLeft(t);break}}}ShortcutTwoListElements(t){var e;const i=t.Next;let s=He.mkSSSEE(t.Start,t.End,i.End,t.Edge,i.Edge,this.createEdgeDelegate);this.triangles.add(s);const n=s.Edges.getItem(2);this.LegalizeEdge(t.Start,s.OppositeEdge(t.Start)),s=(e=n.CcwTriangle)!==null&&e!==void 0?e:n.CwTriangle,this.LegalizeEdge(i.End,s.OppositeEdge(i.End));const o=new ba(n);return o.Start=t.Start,o.End=i.End,t.Prev.Next=o,o.Prev=t.Prev,o.Next=i.Next,i.Next.Prev=o,o}ShortcutTwoFrontElements(t,e){var i;const s=t.item,n=e.item;let o=He.mkSSSEED(s.LeftSite,s.RightSite,n.RightSite,s.Edge,n.Edge,this.createEdgeDelegate);this.triangles.add(o),this.front.deleteNodeInternal(t),this.front.remove(n);const a=o.Edges.getItem(2);return this.LegalizeEdge(s.LeftSite,o.OppositeEdge(s.LeftSite)),o=(i=a.CcwTriangle)!==null&&i!==void 0?i:a.CwTriangle,this.LegalizeEdge(n.RightSite,o.OppositeEdge(n.RightSite)),this.front.insert(new Sn(s.LeftSite,a))}TryTriangulateBasinToTheLeft(t){if(!Ce.DropsSharpEnoughToTheLeft(t.item))return;const e=new Ut.B;for(e.push(t.item.LeftSite);;){const i=e.pop();t=Ce.FindNodeInFrontBySite(this.front,i);const s=this.front.previous(t);if(s==null)return;if(c.getTriangleOrientation(s.item.LeftSite.point,t.item.LeftSite.point,t.item.RightSite.point)==D.Counterclockwise)e.push(s.item.LeftSite),this.ShortcutTwoFrontElements(s,t);else if(t.item.LeftSite.point.y>t.item.RightSite.point.y)e.push(s.item.LeftSite);else{if(s.item.LeftSite.point.y<=s.item.RightSite.point.y)return;e.push(s.item.LeftSite)}}}static DropsSharpEnoughToTheLeft(t){const e=t.Edge;if(t.RightSite!==e.upperSite)return!1;const i=e.lowerSite.point.sub(e.upperSite.point);return i.x>=.5*i.y}InsertSiteIntoFront(t,e,i){let s=null,n=null;for(const o of e.Edges)if(n==null&&o.lowerSite===t&&(n=o),s==null&&o.lowerSite===i&&(s=o),n!=null&&s!=null)break;return this.front.insert(new Sn(t,n)),this.front.insert(new Sn(e,s))}TriangulateEmptySpaceToTheRight(t){const i=t.item.LeftSite.point;let s=this.front.next(t);for(;s!=null;){const n=s.item,o=n.LeftSite,a=n.RightSite;if(o.point.sub(i).dot(a.point.sub(o.point))<0)t=this.ShortcutTwoFrontElements(t,s),s=this.front.next(t);else{this.TryTriangulateBasinToTheRight(t);break}}}TryTriangulateBasinToTheRight(t){if(!Ce.DropsSharpEnoughToTheRight(t.item))return;const e=new Ut.B;for(e.push(t.item.LeftSite);;){const i=e.pop();t=Ce.FindNodeInFrontBySite(this.front,i);const s=this.front.next(t);if(s==null)return;if(c.getTriangleOrientation(t.item.LeftSite.point,t.item.RightSite.point,s.item.RightSite.point)==D.Counterclockwise)this.ShortcutTwoFrontElements(t,s),e.push(i);else if(t.item.LeftSite.point.y>t.item.RightSite.point.y)e.push(t.item.RightSite);else{if(s.item.LeftSite.point.y>=s.item.RightSite.point.y)return;e.push(t.item.RightSite)}}}static DropsSharpEnoughToTheRight(t){const e=t.Edge;if(t.LeftSite!==e.upperSite)return!1;const i=e.lowerSite.point.sub(e.upperSite.point);return i.x<=-.5*i.y}static FindNodeInFrontBySite(t,e){return t.findLast(i=>i.LeftSite.point.x<=e.point.x)}InsertAndLegalizeTriangle(t,e){var i;if(c.getTriangleOrientation(t.point,e.LeftSite.point,e.RightSite.point)!==D.Collinear){const s=He.mkSED(t,e.Edge,this.createEdgeDelegate);this.triangles.add(s),this.LegalizeEdge(t,s.Edges.getItem(0))}else{const s=e.Edge;To(s.upperSite.Edges,s);let n=(i=s.CcwTriangle)!==null&&i!==void 0?i:s.CwTriangle;const o=n.OppositeSite(s);Ce.RemoveTriangleButLeaveEdges(this.triangles,n),n=He.mkSSSD(e.LeftSite,o,t,this.createEdgeDelegate);const a=He.mkSSSD(e.RightSite,o,t,this.createEdgeDelegate);this.triangles.add(n),this.triangles.add(a),this.LegalizeEdge(t,n.OppositeEdge(t)),this.LegalizeEdge(t,a.OppositeEdge(t))}}LegalizeEdge(t,e){e.constrained||e.CcwTriangle==null||e.CwTriangle==null||(e.CcwTriangle.Contains(t)?this.LegalizeEdgeForOtherCwTriangle(t,e):this.LegalizeEdgeForOtherCcwTriangle(t,e))}LegalizeEdgeForOtherCwTriangle(t,e){const i=e.CwTriangle.Edges.index(e);if(wa(t,e.upperSite,e.CwTriangle.Sites.getItem(i+2),e.lowerSite)){const s=va(t,e);this.LegalizeEdge(t,s.CwTriangle.OppositeEdge(t)),this.LegalizeEdge(t,s.CcwTriangle.OppositeEdge(t))}}LegalizeEdgeForOtherCcwTriangle(t,e){const i=e.CcwTriangle.Edges.index(e);if(wa(t,e.lowerSite,e.CcwTriangle.Sites.getItem(i+2),e.upperSite)){const s=va(t,e);this.LegalizeEdge(t,s.CwTriangle.OppositeEdge(t)),this.LegalizeEdge(t,s.CcwTriangle.OppositeEdge(t))}}ProjectToFront(t){return this.front.findLast(e=>e.x<=t.point.x)}runEdgeInserter(){this.initEdgeInserter(),this.TraceEdgeThroughTriangles(),this.TriangulatePolygon0(this.rightPolygon,this.traversingEdge.upperSite,this.traversingEdge.lowerSite,!0),this.TriangulatePolygon0(this.leftPolygon,this.traversingEdge.upperSite,this.traversingEdge.lowerSite,!1),this.UpdateFront()}initEdgeInserter(){this.rightPolygon=new Array,this.leftPolygon=new Array,this.addedTriangles=new Array,this.piercedEdge=null,this.piercedTriangle=null,this.piercedToTheLeftFrontElemNode=null,this.piercedToTheRightFrontElemNode=null}UpdateFront(){const t=new Set;for(const e of this.addedTriangles)for(const i of e.Edges)if(i.CwTriangle==null||i.CcwTriangle==null){if(i.lowerSite==this.p_2&&i.upperSite==this.p_1)continue;t.add(i)}for(const e of t)this.AddEdgeToFront(e)}AddEdgeToFront(t){const e=t.upperSite.point.x<t.lowerSite.point.x?t.upperSite:t.lowerSite;this.front.insert(new Sn(e,t))}TriangulatePolygon0(t,e,i,s){t.length>0&&this.TriangulatePolygon1(0,t.length-1,t,e,i,s)}TriangulatePolygon1(t,e,i,s,n,o){let a=i[t],h=t;for(let m=t+1;m<=e;m++){const y=i[m];d(y)&&(h=m,a=y)}const u=He.mkSSSD(s,n,a,this.createEdgeDelegate);this.triangles.add(u),this.addedTriangles.push(u),t<h&&this.TriangulatePolygon1(t,h-1,i,s,a,o),h<e&&this.TriangulatePolygon1(h+1,e,i,a,n,o);function d(m){return o?xo(m,s,a,n):xo(m,s,n,a)}}TraceEdgeThroughTriangles(){this.initEdgeTracer(),this.Traverse()}Traverse(){for(;!this.BIsReached();)this.piercedToTheLeftFrontElemNode!=null?this.ProcessLeftFrontPiercedElement():this.piercedToTheRightFrontElemNode!=null?this.ProcessRightFrontPiercedElement():this.ProcessPiercedEdge();this.piercedTriangle!=null&&this.removePiercedTriangle(this.piercedTriangle),this.FindMoreRemovedFromFrontElements();for(const t of this.elementsToBeRemovedFromFront)this.front.remove(t)}ProcessLeftFrontPiercedElement(){let t=this.piercedToTheLeftFrontElemNode;do this.elementsToBeRemovedFromFront.push(t.item),this.AddSiteToLeftPolygon(t.item.LeftSite),t=this.front.previous(t);while(c.pointToTheLeftOfLine(t.item.LeftSite.point,this.a.point,this.b.point));if(this.elementsToBeRemovedFromFront.push(t.item),this.AddSiteToRightPolygon(t.item.LeftSite),t.item.LeftSite===this.b){this.piercedToTheLeftFrontElemNode=t;return}this.FindPiercedTriangle(t),this.piercedToTheLeftFrontElemNode=null}FindPiercedTriangle(t){var e;const i=t.item.Edge,s=(e=i.CcwTriangle)!==null&&e!==void 0?e:i.CwTriangle,n=s.Edges.index(i);for(let o=1;o<=2;o++){const a=s.Edges.getItem(o+n),h=x.sign(c.signedDoubledTriangleArea(a.lowerSite.point,this.a.point,this.b.point));if(x.sign(c.signedDoubledTriangleArea(a.upperSite.point,this.a.point,this.b.point))*h<=0){this.piercedTriangle=s,this.piercedEdge=a;break}}}FindMoreRemovedFromFrontElements(){for(const t of this.removedTriangles)for(const e of t.Edges)if(e.CcwTriangle==null&&e.CwTriangle==null){const i=e.upperSite.point.x<e.lowerSite.point.x?e.upperSite:e.lowerSite,s=Ce.FindNodeInFrontBySite(this.front,i);s.item.Edge===e&&this.elementsToBeRemovedFromFront.push(s.item)}}ProcessPiercedEdge(){this.piercedEdge.CcwTriangle===this.piercedTriangle?(this.AddSiteToLeftPolygon(this.piercedEdge.lowerSite),this.AddSiteToRightPolygon(this.piercedEdge.upperSite)):(this.AddSiteToLeftPolygon(this.piercedEdge.upperSite),this.AddSiteToRightPolygon(this.piercedEdge.lowerSite)),this.removePiercedTriangle(this.piercedTriangle),this.PrepareNextStateAfterPiercedEdge()}PrepareNextStateAfterPiercedEdge(){var t,e;const i=(t=this.piercedEdge.CwTriangle)!==null&&t!==void 0?t:this.piercedEdge.CcwTriangle,s=i.Edges.index(this.piercedEdge);for(let n=1;n<=2;n++){const o=i.Edges.getItem(n+s),a=x.sign(c.signedDoubledTriangleArea(o.lowerSite.point,this.a.point,this.b.point));if(x.sign(c.signedDoubledTriangleArea(o.upperSite.point,this.a.point,this.b.point))*a<=0){if(o.CwTriangle!=null&&o.CcwTriangle!=null){this.piercedTriangle=i,this.piercedEdge=o;break}this.piercedTriangle=null,this.piercedEdge=null;const u=o.upperSite.point.x<o.lowerSite.point.x?o.upperSite:o.lowerSite,d=Ce.FindNodeInFrontBySite(this.front,u);u.point.x<this.a.point.x?this.piercedToTheLeftFrontElemNode=d:this.piercedToTheRightFrontElemNode=d,this.removePiercedTriangle((e=o.CwTriangle)!==null&&e!==void 0?e:o.CcwTriangle);break}}}removePiercedTriangle(t){this.triangles.delete(t);for(const e of t.Edges)e.CwTriangle===t?e.CwTriangle=null:e.CcwTriangle=null,this.removedTriangles.push(t)}ProcessRightFrontPiercedElement(){let t=this.piercedToTheRightFrontElemNode;do this.elementsToBeRemovedFromFront.push(t.item),this.AddSiteToRightPolygon(t.item.RightSite),t=this.front.next(t);while(c.pointToTheRightOfLine(t.item.RightSite.point,this.a.point,this.b.point));if(this.elementsToBeRemovedFromFront.push(t.item),this.AddSiteToLeftPolygon(t.item.RightSite),t.item.RightSite===this.b){this.piercedToTheRightFrontElemNode=t;return}this.FindPiercedTriangle(t),this.piercedToTheRightFrontElemNode=null}AddSiteToLeftPolygon(t){this.AddSiteToPolygonWithCheck(t,this.leftPolygon)}AddSiteToPolygonWithCheck(t,e){t!==this.b&&(e.length===0||e[e.length-1]!==t)&&e.push(t)}AddSiteToRightPolygon(t){this.AddSiteToPolygonWithCheck(t,this.rightPolygon)}BIsReached(){var t;const e=(t=this.piercedToTheLeftFrontElemNode)!==null&&t!==void 0?t:this.piercedToTheRightFrontElemNode;return e!=null?e.item.Edge.IsAdjacent(this.b):this.piercedEdge.IsAdjacent(this.b)}initEdgeTracer(){this.elementsToBeRemovedFromFront=[],this.a=this.traversingEdge.upperSite,this.b=this.traversingEdge.lowerSite,this.removedTriangles=[];const t=Ce.FindNodeInFrontBySite(this.front,this.a),e=this.front.previous(t);if(c.pointToTheLeftOfLine(this.b.point,e.item.LeftSite.point,e.item.RightSite.point))this.piercedToTheLeftFrontElemNode=e;else if(c.pointToTheRightOfLine(this.b.point,t.item.RightSite.point,t.item.LeftSite.point))this.piercedToTheRightFrontElemNode=t;else for(const i of this.a.Edges){const s=i.CcwTriangle;if(s==null||c.pointToTheLeftOfLine(this.b.point,i.lowerSite.point,i.upperSite.point))continue;const n=s.Edges.index(i),o=s.Sites.getItem(n+2);if(c.pointToTheLeftOfLineOrOnLine(this.b.point,o.point,i.upperSite.point)){this.piercedEdge=s.Edges.getItem(n+1),this.piercedTriangle=s;break}}}}function To(l,t){if(l.length===0)return;const e=l.findIndex(i=>t===i);e>=0&&(e!==l.length-1&&(l[e]=l[l.length-1]),l.pop())}function wa(l,t,e,i){return ql(l,t,e,i)&&xo(l,t,e,i)}function ql(l,t,e,i){return c.getTriangleOrientation(t.point,l.point,e.point)===D.Clockwise&&c.getTriangleOrientation(e.point,l.point,i.point)===D.Clockwise}function xo(l,t,e,i){const s=t.point.x-l.point.x,n=t.point.y-l.point.y,o=e.point.x-l.point.x,a=e.point.y-l.point.y,h=i.point.x-l.point.x,u=i.point.y-l.point.y,d=s*s+n*n,m=o*o+a*a,y=h*h+u*u;return s*(a*y-u*m)-o*(n*y-u*d)+h*(n*m-a*d)>C.tolerance}function ic(l){if(Point.getTriangleOrientation(l.Sites.getItem(0).point,l.Sites.getItem(1).point,l.Sites.getItem(2).point)!=TriangleOrientation.Counterclockwise)return!1;for(let t=0;t<3;t++){const e=l.Edges.getItem(t),i=l.Sites.getItem(t),s=l.Sites.getItem(t+1);if(!e.IsAdjacent(i)||!e.IsAdjacent(s))return!1;if(e.upperSite===i){if(e.CcwTriangle!==l)return!1}else if(e.CwTriangle!==l)return!1}return!0}function va(l,t){let e,i;t.CcwTriangle.Contains(l)?(e=t.CcwTriangle,i=t.CwTriangle):(e=t.CwTriangle,i=t.CcwTriangle);const s=e.Edges.index(t),n=i.Edges.index(t),o=i.Sites.getItem(n+2),a=e.Edges.getItem(s+1),h=i.Edges.getItem(n+1),u=ie.GetOrCreateEdge(l,o);return e.Sites.setItem(s+1,o),e.Edges.setItem(s,h),e.Edges.setItem(s+1,u),i.Sites.setItem(n+1,l),i.Edges.setItem(n,a),i.Edges.setItem(n+1,u),h.lowerSite===o?h.CcwTriangle=e:h.CwTriangle=e,a.lowerSite===l?a.CcwTriangle=i:a.CwTriangle=i,u.upperSite===l?(u.CcwTriangle=i,u.CwTriangle=e):(u.CcwTriangle=e,u.CwTriangle=i),To(t.upperSite.Edges,t),u}class ie extends Ft{constructor(t,e,i){super(null),this.isolatedSites=[],this.obstacles=[],this.PointsToSites=new je,this.simplifyObstacles=!0,this.rectangleNodeOnTriangles=null,this.isolatedSites=t,this.obstacles=e,this.isolatedSegments=i}static constructor_(t){const e=new ie(null,null,null);return e.isolatedSitesWithObject=t,e}FillAllInputSites(){if(this.isolatedSitesWithObject!=null)for(const t of this.isolatedSitesWithObject)this.AddSite(t[0],t[1]);if(this.isolatedSites!=null)for(const t of this.isolatedSites)this.AddSite(t,null);if(this.obstacles!=null)for(const t of this.obstacles)this.AddPolylineToAllInputSites(t);if(this.isolatedSegments!=null)for(const t of this.isolatedSegments)this.AddConstrainedEdge(t.A,t.B,null);this.AddP1AndP2(),this.allInputSites=Array.from(this.PointsToSites.values())}AddSite(t,e){let i;return(i=this.PointsToSites.get(t))?i.Owner=e:(i=er.mkSO(t,e),this.PointsToSites.set(t,i)),i}AddP1AndP2(){const t=X.mkEmpty();for(const s of this.PointsToSites.keys())t.add(s);const e=10,i=10;this.P1=new er(t.leftBottom.add(new c(-e,-i))),this.P2=new er(t.rightBottom.add(new c(e,-i)))}AddPolylineToAllInputSites(t){if(this.simplifyObstacles)for(let e=t.startPoint;e!=null;){const i=e.point;if(e=e.next,!e)break;for(;e.next&&c.getTriangleOrientation(i,e.point,e.next.point)===D.Collinear;)e=e.next;this.AddConstrainedEdge(i,e.point,t)}else for(let e=t.startPoint;e.next!=null;e=e.next)this.AddConstrainedEdge(e.point,e.next.point,t);t.closed&&this.AddConstrainedEdge(t.endPoint.point,t.startPoint.point,t)}AddConstrainedEdge(t,e,i){const s=ie.AbovePP(t,e);let n,o;s>0?(n=this.AddSite(t,i),o=this.AddSite(e,i)):(n=this.AddSite(e,i),o=this.AddSite(t,i));const a=ie.CreateEdgeOnOrderedCouple(n,o);a.constrained=!0}static GetOrCreateEdge(t,e){if(ie.AboveCC(t,e)===1){const i=t.EdgeBetweenUpperSiteAndLowerSite(e);return i??ie.CreateEdgeOnOrderedCouple(t,e)}else{const i=e.EdgeBetweenUpperSiteAndLowerSite(t);return i??ie.CreateEdgeOnOrderedCouple(e,t)}}static CreateEdgeOnOrderedCouple(t,e){return new Hl(t,e)}GetTriangles(){return this.sweeper.triangles}run(){this.Initialization(),this.SweepAndFinalize()}SweepAndFinalize(){this.sweeper=new Ce(this.allInputSites,this.P1,this.P2,ie.GetOrCreateEdge),this.sweeper.run(),this.cleanRemovedEdges()}cleanRemovedEdges(){for(const t of this.PointsToSites.values())t.cleanRemovedEdges()}Initialization(){this.FillAllInputSites(),this.allInputSites.sort(ie.OnComparison)}static OnComparison(t,e){return ie.AboveCC(t,e)}static AbovePP(t,e){let i=t.y-e.y;return i>0?1:i<0?-1:(i=t.x-e.x,i>0?-1:i<0?1:0)}static AboveCC(t,e){return ie.AbovePP(t.point,e.point)}RestoreEdgeCapacities(){for(const t of this.allInputSites)for(const e of t.Edges)e.constrained||(e.ResidualCapacity=e.Capacity)}SetInEdges(){for(const t of this.PointsToSites.values())for(const e of t.Edges)e.lowerSite.AddInEdge(e)}FindSite(t){return this.PointsToSites.get(t)}static PointIsInsideOfTriangle(t,e){for(let i=0;i<3;i++){const s=e.Sites.getItem(i).point,n=e.Sites.getItem(i+1).point;if(c.signedDoubledTriangleArea(t,s,n)<C.distanceEpsilon*-1)return!1}return!0}getRectangleNodeOnTriangles(){return this.rectangleNodeOnTriangles==null&&(this.rectangleNodeOnTriangles=$t(Array.from(this.GetTriangles().values()).map(t=>he(t,t.BoundingBox())))),this.rectangleNodeOnTriangles}}function Ia(l){const t=Array.from(l.GetAllLeaves()),e=l.irect,i=e.diagonal/4,s=e.clone();return s.pad(i),zl(t.concat([s.perimeter()]))}function zl(l){const t=new ie(null,l,null);return t.run(),t}class ir{constructor(t,e){this.start=t,this.end=e}add(t){this.add_d(t)}add_rect(t){const e=t,i=this.clone();return i.add_d(e.start),i.add_d(e.end),i}clone(){return new ir(this.start,this.end)}contains_point(t){return this.contains_d(t)}contains_rect(t){const e=t;return this.contains_d(e.start)&&this.contains_d(e.end)}intersection_rect(t){const e=t;return new ir(Math.max(this.start,e.start),Math.min(this.end,e.end))}intersects_rect(t){const e=t;return this.intersects(e)}contains_point_radius(t,e){return this.contains_d(t-e)&&this.contains_d(t+e)}static mkInterval(t,e){const i=new ir(t.start,t.end);return i.add_d(e.start),i.add_d(e.end),i}add_d(t){this.start>t&&(this.start=t),this.end<t&&(this.end=t)}get Start(){return this.start}set Start(t){this.start=t}get Length(){return this.end-this.start}contains_d(t){return this.start<=t&&t<=this.end}GetInRange(t){return t<this.start?this.start:t>this.end?this.end:t}intersects(t){return t.start>this.end+C.distanceEpsilon?!1:!(t.end<this.start-C.distanceEpsilon)}}class Ta{get Count(){return this.heapSize}constructor(t){this.heapSize=0,this._priors=new Array(t),this._heap=new Array(t+1),this._reverse_heap=new Array(t)}SwapWithParent(t){const e=this._heap[t>>1];this.PutAtI(t>>1,this._heap[t]),this.PutAtI(t,e)}Enqueue(t,e){this.heapSize++;let i=this.heapSize;for(this._priors[t]=e,this.PutAtI(i,t);i>1&&this._priors[this._heap[i>>1]]>e;)this.SwapWithParent(i),i>>=1}PutAtI(t,e){this._heap[t]=e,this._reverse_heap[e]=t}Dequeue(){if(this.heapSize===0)throw new Error;const t=this._heap[1];if(this.heapSize>1){this.PutAtI(1,this._heap[this.heapSize]);let e=1;for(;;){let i=e;const s=e<<1;s<=this.heapSize&&this._priors[this._heap[s]]<this._priors[this._heap[e]]&&(i=s);const n=s+1;if(n<=this.heapSize&&this._priors[this._heap[n]]<this._priors[this._heap[i]]&&(i=n),i!==e)this.SwapWithParent(i);else break;e=i}}return this.heapSize--,t}IsEmpty(){return this.heapSize===0}DecreasePriority(t,e){this._priors[t]=e;let i=this._reverse_heap[t];for(;i>1&&this._priors[this._heap[i]]<this._priors[this._heap[i>>1]];){this.SwapWithParent(i);i>>=1}}}class Ul{constructor(t,e,i,s){this._numberOfOverlaps=0,this._proximityEdges=t,this._nodeSizes=e,this._nodePositions=i,this._forLayers=s,this._q=new Ta(e.length*2)}Run(){return this.InitQueue(),this.FindOverlaps(),this._numberOfOverlaps}FindOverlaps(){for(;this._q.Count>0;){let t=this._q.Dequeue();t<this._nodePositions.length?(this.FindOverlapsWithInterval(t),this.AddIntervalToTree(t)):(t-=this._nodePositions.length,this.RemoveIntervalFromTree(t))}}RemoveIntervalFromTree(t){this._intervalTree.Remove(this.GetInterval(t),t)}AddIntervalToTree(t){const e=this.GetInterval(t);this._intervalTree==null&&(this._intervalTree=xs([])),this._intervalTree.Add(e,t)}FindOverlapsWithInterval(t){if(this._intervalTree==null)return;const e=this.GetInterval(t);for(const i of this._intervalTree.GetAllIntersecting(e)){const s=xi.GetIdealEdge(t,i,this._nodePositions[t],this._nodePositions[i],this._nodeSizes);if(s.overlapFactor<=1)return;this._proximityEdges.push(s),this._numberOfOverlaps++}}GetInterval(t){const e=this._nodeSizes[t].width/2,i=this._nodePositions[t].x;return new ir(i-e,i+e)}InitQueue(){for(let t=0;t<this._nodeSizes.length;t++){const e=this._nodeSizes[t].height/2,i=this._nodePositions[t].y;this._q.Enqueue(t,i-e),this._q.Enqueue(this._nodeSizes.length+t,i+e)}}}class xa{constructor(t,e,i){this.treeNodes=new Set,this.hedgehog=new Map,this.graph=t,this.weight=e,this.root=i,this.q=new Ta(this.graph.nodeCount)}NodeIsInTree(t){return this.treeNodes.has(t)}GetTreeEdges(){const t=new Array;for(this.Init();t.length<this.graph.nodeCount-1&&this.q.Count>0;)this.AddEdgeToTree(t);return t}AddEdgeToTree(t){const e=this.q.Dequeue(),i=this.hedgehog.get(e);this.treeNodes.add(e),t.push(i),this.UpdateOutEdgesOfV(e),this.UpdateInEdgesOfV(e)}UpdateOutEdgesOfV(t){for(const e of this.graph.outEdges[t]){const i=e.target;if(this.NodeIsInTree(i))continue;const s=this.hedgehog.get(i);if(s){const n=this.weight(s),o=this.weight(e);o<n&&(this.q.DecreasePriority(i,o),this.hedgehog.set(i,e))}else this.q.Enqueue(i,this.weight(e)),this.hedgehog.set(i,e)}}UpdateInEdgesOfV(t){for(const e of this.graph.inEdges[t]){const i=e.source;if(this.NodeIsInTree(i))continue;const s=this.hedgehog.get(i);if(s){const n=this.weight(s),o=this.weight(e);o<n&&(this.q.DecreasePriority(i,o),this.hedgehog.set(i,e))}else this.q.Enqueue(i,this.weight(e)),this.hedgehog.set(i,e)}}Init(){this.treeNodes.add(this.root);for(const t of this.graph.outEdges[this.root]){const e=this.weight(t);this.q.Enqueue(t.target,e),this.hedgehog.set(t.target,t)}for(const t of this.graph.inEdges[this.root]){const e=this.weight(t);this.q.Enqueue(t.source,e),this.hedgehog.set(t.source,t)}}}class Oo{static GetMst(t,e){if(t.length===0)return null;const i=t.map(a=>new Et(a.source,a.target)),s=new hs;for(let a=0;a<t.length;a++)s.setPair(i[a],t[a]);const n=Qe(i,e);return new xa(n,a=>s.get(a.source,a.target).weight,i[0].source).GetTreeEdges().map(a=>s.get(a.source,a.target))}static GetMstOnCdt(t,e){const i=Array.from(t.PointsToSites.values()),s=new Map;for(let h=0;h<i.length;h++)s.set(i[h],h);const n=Oo.GetEdges(i,s),o=Fr(Array.from(n.keys()));return new xa(o,h=>e(n.get(h.source,h.target)),0).GetTreeEdges().map(h=>n.get(h.source,h.target))}static GetEdges(t,e){const i=new hs;for(let s=0;s<t.length;s++){const n=t[s],o=e.get(n);for(const a of n.Edges)i.set(o,e.get(a.lowerSite),a)}return i}}class Bo{constructor(){this.epsilon=.01,this.iterationsMax=1e3,this.stopOnMaxIterat=!1,this.nodeSeparation=4,this.randomizationSeed=1,this.randomizationShift=.1}get StopOnMaxIterat(){return this.stopOnMaxIterat}set StopOnMaxIterat(t){this.stopOnMaxIterat=t}get Epsilon(){return this.epsilon}set Epsilon(t){this.epsilon=t}get IterationsMax(){return this.iterationsMax}set IterationsMax(t){this.iterationsMax=t}get NodeSeparation(){return this.nodeSeparation}set NodeSeparation(t){this.nodeSeparation=t}get RandomizationSeed(){return this.randomizationSeed}set RandomizationSeed(t){this.randomizationSeed=t}get RandomizationShift(){return this.randomizationShift}set RandomizationShift(t){this.randomizationShift=t}Clone(){const t=new Bo;return t.Epsilon=this.Epsilon,t.IterationsMax=this.IterationsMax,t.StopOnMaxIterat=this.StopOnMaxIterat,t.NodeSeparation=this.NodeSeparation,t.RandomizationSeed=this.RandomizationSeed,t.RandomizationShift=this.randomizationShift,t}}class xi{constructor(t,e){this._settings=t,this._nodes=e}static RemoveOverlaps(t,e){const i=new Bo;i.RandomizationShift=1,i.NodeSeparation=e,new xi(i,t).RemoveOverlaps()}RemoveOverlaps(){if(this._nodes.length<3){this.RemoveOverlapsOnTinyGraph();return}const t={nodePositions:new Array,nodeSizes:new Array};for(jl(this._settings,this._nodes,t,this._settings.RandomizationShift),this.lastRunNumberIterations=0;this.OneIteration(t.nodePositions,t.nodeSizes,!1);)this.lastRunNumberIterations++;for(;this.OneIteration(t.nodePositions,t.nodeSizes,!0);)this.lastRunNumberIterations++;for(let e=0;e<this._nodes.length;e++)this._nodes[e].center=t.nodePositions[e]}RemoveOverlapsOnTinyGraph(){if(this._nodes.length!==1&&this._nodes.length===2){const t=this._nodes[0],e=this._nodes[1];c.closeDistEps(t.center,e.center)&&(e.center=e.center.add(new c(.001,0)));const i=this.GetIdealDistanceBetweenTwoNodes(t,e),s=c.middle(t.center,e.center);let n=t.center.sub(e.center);const o=n.length;n=n.mul(.5*(i/o)),t.center=s.add(n),e.center=s.sub(n)}}GetIdealDistanceBetweenTwoNodes(t,e){const i=t.center.sub(e.center),s=Math.abs(i.x),n=Math.abs(i.y),o=(t.width+e.width)/2+this._settings.NodeSeparation,a=(t.height+e.height)/2+this._settings.NodeSeparation;let h=Number.POSITIVE_INFINITY,u=Number.POSITIVE_INFINITY;return s>C.tolerance&&(h=o/s),n>C.tolerance&&(u=a/n),Math.min(h,u)*i.length}static AvgEdgeLength(t){let e=0,i=0;for(const s of t)for(const n of s.outEdges())i+=s.center.sub(n.target.center).length,e++;return e>0?i/e:1}OneIteration(t,e,i){const s=new Array;for(let d=0;d<t.length;d++)s.push([t[d],d]);const n=ie.constructor_(s);n.run();const o=new Map;for(let d=0;d<t.length;d++)o.set(n.PointsToSites.get(t[d]),d);let a=0;const h=new Array;for(const d of n.PointsToSites.values())for(const m of d.Edges){const y=m.upperSite.point,E=m.lowerSite.point,T=o.get(m.upperSite),B=o.get(m.lowerSite),H=xi.GetIdealEdge(T,B,y,E,e);h.push(H),H.overlapFactor>1&&a++}if(a===0||i){const d=this.FindProximityEdgesWithSweepLine(h,e,t);if(a===0&&d===0||a===0&&!i)return!1}const u=Oo.GetMst(h,t.length);return xi.MoveNodePositions(u,t,u[0].source),!0}FindProximityEdgesWithSweepLine(t,e,i){return new Ul(t,e,i,this._overlapForLayers).Run()}static GetIdealEdge(t,e,i,s,n){const o={overlapFactor:0},a=xi.GetIdealEdgeLength(t,e,i,s,n,o),h=i.sub(s).length,u=X.mkSizeCenter(n[t],i),d=X.mkSizeCenter(n[e],s),m=o.overlapFactor>1?h-a:xi.GetDistanceRects(u,d);return{source:Math.min(t,e),target:Math.max(t,e),overlapFactor:o.overlapFactor,idealDistance:a,weight:m}}static GetIdealEdgeLength(t,e,i,s,n,o){const a=i.sub(s),h=a.length,u=Math.abs(a.x),d=Math.abs(a.y),m=(n[t].width+n[e].width)/2,y=(n[t].height+n[e].height)/2;if(u>=m||d>=y)return o.overlapFactor=1,a.length;let E;const T=1e-10;if(u>T)d>T?E=Math.min(m/u,y/d):E=m/u;else if(d>T)E=y/d;else return o.overlapFactor=2,Math.sqrt(m*m+y*y)/4;return E=Math.max(E,1.001),o.overlapFactor=E,E*h}static GetDistanceRects(t,e){if(t.intersects(e))return 0;let i=0,s=0;return(t.right<e.left||e.right<t.left)&&(s=t.left-e.right),t.top<e.bottom?i=e.bottom-t.top:e.top<t.bottom&&(i=t.bottom-e.top),Math.sqrt(s*s+i*i)}static MoveNodePositions(t,e,i){const s=e.map(o=>o.clone()),n=new Set;n.add(i);for(let o=0;o<t.length;o++){const a=t[o];n.has(a.source)?xi.MoveNode(a.source,a.target,s,e,n,a.idealDistance):xi.MoveNode(a.target,a.source,s,e,n,a.idealDistance)}}static MoveNode(t,e,i,s,n,o){let a=i[e].sub(i[t]);a=a.mul(o/a.length+.01),s[e]=s[t].add(a),n.add(e)}GetLastRunIterations(){return this.lastRunNumberIterations}}function jl(l,t,e,i){e.nodePositions=t.map(s=>s.center),i&&Ql(e.nodePositions,new Ds(0,0),i),e.nodeSizes=t.map(s=>{const n=s.boundingBox.size;return n.width+=l.NodeSeparation,n.height+=l.NodeSeparation,n})}function Ql(l,t,e){const i=new Yt;for(let s=0;s<l.length;s++){let n=l[s];if(e||i.has(n))do{const o=n.x+(2*t.random()-1)*e,a=n.y+(2*t.random()-1)*e;n=new c(o,a)}while(i.has(n));l[s]=n,i.add(n)}}class sr extends Ft{constructor(t,e,i,s){super(i),this.settings=t,this.graph=e,this.length=s}run(){this.LayoutConnectedGraphWithMds(),this.graph.pumpTheBoxToTheGraphWithMargins()}static ScaleToAverageEdgeLength(t,e,i,s){const n=new Map;let o=0;for(const u of t.shallowNodes)n.set(u,o),o++;let a=0,h=0;for(const u of t.shallowEdges){const d=n.get(u.source),m=n.get(u.target);h+=Math.sqrt(Math.pow(e[d]-e[m],2)+Math.pow(i[d]-i[m],2)),a+=s(u)}if(a>0&&(h/=a),h>0)for(let u=0;u<e.length;u++)e[u]/=h,i[u]/=h}static LayoutGraphWithMds(t,e,i,s){if(i.x=new Array(t.shallowNodeCount),i.y=new Array(t.shallowNodeCount),i.x.length===0)return;if(i.x.length===1){i.x[0]=i.y[0]=0;return}const n=Math.min(e.PivotNumber,t.shallowNodeCount),o=e.GetNumberOfIterationsWithMajorization(t.shallowNodeCount),a=e.Exponent,h=new Array(n),u=new Vl(t,h,s);u.run();const d=u.Result;if(kt.LandmarkClassicalScaling(d,i,h),sr.ScaleToAverageEdgeLength(t,i.x,i.y,s),o>0){const m=new vo(t,s);m.run();const y=m.Result,E=kt.ExponentialWeightMatrix(y,a);kt.DistanceScalingSubset(y,i.x,i.y,E,o)}}LayoutConnectedGraphWithMds(){const t={x:[],y:[]};sr.LayoutGraphWithMds(this.graph,this.settings,t,this.length),this.settings.RotationAngle!==0&&Wl.Rotate(t.x,t.y,this.settings.RotationAngle);let e=0;for(const i of this.graph.shallowNodes)i.boundingBox&&(i.center=new c(t.x[e]*this.settings.ScaleX,t.y[e]*this.settings.ScaleY)),e++;this.settings.removeOverlaps&&xi.RemoveOverlaps(Array.from(this.graph.shallowNodes),this.settings.NodeSeparation),this.graph.pumpTheBoxToTheGraphWithMargins()}ScaleNodes(t,e){for(const i of t)i.center=i.center.mul(e)}static PackGraphs(t,e){if(t.length===0)return X.mkEmpty();if(t.length===1)return t[0].boundingBox;const i=t.map(o=>o.boundingBox),s=new Array;for(const o of t)s.push({g:o,lb:o.boundingBox.leftBottom.clone()});const n=new Er(i,e.PackingAspectRatio);n.run();for(const{g:o,lb:a}of s){const h=o.boundingBox.leftBottom.sub(a);o.translate(h)}return new X({left:0,bottom:0,right:n.PackedWidth,top:n.PackedHeight})}}class nr{constructor(){this.commonSettings=new mn,this.pivotNumber=50,this.iterationsWithMajorization=30,this.scaleX=100,this.scaleY=100,this.exponent=-2,this.rotationAngle=0,this._removeOverlaps=!0,this._callIterationsWithMajorizationThreshold=2e3,this.adjustScale=!1}static fromJSON(t){const e=new nr;return t.pivotNumber&&(e.pivotNumber=t.pivotNumber),t.iterationsWithMajorization&&(e.iterationsWithMajorization=t.iterationsWithMajorization),t.scaleX&&(e.scaleX=t.scaleX),t.scaleY&&(e.scaleY=t.scaleY),t.exponent&&(e.exponent=t.exponent),t.rotationAngle&&(e.rotationAngle=t.rotationAngle),t.removeOverlaps!=null&&(e._removeOverlaps=t.removeOverlaps),t._callIterationsWithMajorizationThreshold&&(e._callIterationsWithMajorizationThreshold=t._callIterationsWithMajorizationThreshold),e}toJSON(){const t={};return this.pivotNumber!=50&&(t.pivotNumber=this.pivotNumber),this.iterationsWithMajorization!=30&&(t.iterationsWithMajorization=this.iterationsWithMajorization),this.scaleX!=200&&(t.scaleX=this.scaleX),this.scaleY!=200&&(t.scaleY=this.scaleY),this.exponent!=-2&&(t.exponent=this.exponent),this.rotationAngle!=0&&(t.rotationAngle=this.rotationAngle),this._removeOverlaps||(t.removeOverlaps=this._removeOverlaps),this._callIterationsWithMajorizationThreshold!=3e3&&(t._callIterationsWithMajorizationThreshold=this._callIterationsWithMajorizationThreshold),t}get NodeSeparation(){return this.commonSettings.NodeSeparation}set NodeSeparation(t){this.commonSettings.NodeSeparation=t}get edgeRoutingSettings(){return this.commonSettings.edgeRoutingSettings}set edgeRoutingSettings(t){this.commonSettings.edgeRoutingSettings=t}get removeOverlaps(){return this._removeOverlaps}set removeOverlaps(t){this._removeOverlaps=t}get PivotNumber(){return this.pivotNumber}set PivotNumber(t){this.pivotNumber=t}get IterationsWithMajorization(){return this.iterationsWithMajorization}set IterationsWithMajorization(t){this.iterationsWithMajorization=t}get ScaleX(){return this.scaleX}set ScaleX(t){this.scaleX=t}get ScaleY(){return this.scaleY}set ScaleY(t){this.scaleY=t}get Exponent(){return this.exponent}set Exponent(t){this.exponent=t}get RotationAngle(){return this.rotationAngle}set RotationAngle(t){this.rotationAngle=t%360}get AdjustScale(){return this.adjustScale}set AdjustScale(t){this.adjustScale=t}GetNumberOfIterationsWithMajorization(t){return t>this.CallIterationsWithMajorizationThreshold?0:this.IterationsWithMajorization}get CallIterationsWithMajorizationThreshold(){return this._callIterationsWithMajorizationThreshold}set CallIterationsWithMajorizationThreshold(t){this._callIterationsWithMajorizationThreshold=t}}function sc(l,t=null){const e=l.layoutSettings instanceof MdsLayoutSettings?l.layoutSettings:new MdsLayoutSettings;enforceLayoutSettings(l,e),layoutGeomGraphDetailed(l,t,$l,routeEdges,optimalPackingRunner)}class Lo extends Ft{get scaleX(){return this.settings.ScaleX}set scaleX(t){this.settings.ScaleX=t}get scaleY(){return this.settings.ScaleY}set scaleY(t){this.settings.ScaleY=t}constructor(t,e,i,s){super(e),this.graph=t,this.length=i,this.settings=s,this.settings.ScaleX=this.settings.ScaleY=200}run(){new sr(this.settings,this.graph,this.cancelToken,this.length).run()}}function $l(l,t){new Lo(l,t,()=>1,l.layoutSettings).run()}function Oa(l,t,e){if(t)for(const i of t){if(e&&e.canceled)return;_e.RouteEdge(i)}else for(const i of l.nodesBreadthFirst){if(e&&e.canceled)return;for(const s of i.outEdges())s.curve==null&&_e.RouteEdge(s);for(const s of i.selfEdges())s.curve==null&&_e.RouteEdge(s)}}class _e extends Ft{constructor(t,e){super(null),this.edges=t,this.padding=e}run(){qt.CreatePortsIfNeeded(this.edges);for(const t of this.edges)_e.RouteEdge(t)}static RouteEdge(t){const e=t;e.sourcePort==null&&(e.sourcePort=ke.mk(()=>t.source.boundaryCurve,()=>t.source.center)),e.targetPort==null&&(e.targetPort=ke.mk(()=>t.target.boundaryCurve,()=>t.target.center)),_e.ContainmentLoop(e)||(e.curve=_e.GetEdgeLine(t)),Bt.trimSplineAndCalculateArrowheadsII(e,e.sourcePort.Curve,e.targetPort.Curve,t.curve,!1)}static ContainmentLoop(t){const e=t.sourcePort.Curve,i=t.targetPort.Curve;if(e==null||i==null)return!1;const s=e.boundingBox,n=i.boundingBox,o=s.containsRect(n),a=!o&&n.containsRect(s);return o||a?(t.curve=_e.CreateLoop(s,n,a),!0):!1}static CreateLoop(t,e,i){return i?_e.CreateLoop_(t,e,!1):_e.CreateLoop_(e,t,!0)}static CreateLoop_(t,e,i){const s=t.center,n=_e.FindClosestPointOnBoxBoundary(t.center,e);let o=n.sub(s);const h=(Math.abs(o.x)<C.distanceEpsilon?Math.min(s.y-e.bottom,e.top-s.y):Math.min(s.x-e.left,e.right-s.x))/2,u=1,d=Math.min(u,h);o.length<=C.distanceEpsilon&&(o=new c(1,0));const m=o.normalize(),y=m.rotate(Math.PI/2),E=n.add(m.mul(u)),T=E.add(y.mul(d)),B=n.add(y.mul(d)),H=s.add(y.mul(d));return(i?Y.mkFromPoints([H,B,T,E,n,s]):Y.mkFromPoints([s,n,E,T,B,H])).createCurve()}static FindClosestPointOnBoxBoundary(t,e){const i=t.x-e.left<e.right-t.x?e.left:e.right,s=t.y-e.bottom<e.top-t.y?e.bottom:e.top;return Math.abs(i-t.x)<Math.abs(s-t.y)?new c(i,t.y):new c(t.x,s)}static GetEdgeLine(t){let e,i;t.sourcePort==null?(e=t.source.center,i=t.source.boundaryCurve):(e=t.sourcePort.Location,i=t.sourcePort.Curve);let s,n;t.targetPort==null?(s=t.target.center,n=t.target.boundaryCurve):(s=t.targetPort.Location,n=t.targetPort.Curve);let o=N.mkPP(e,s),a=w.getAllIntersections(i,o,!1);if(a.length>0){let h=o.trim(a[0].par1,1);h instanceof N&&(o=h,a=w.getAllIntersections(n,o,!1),a.length>0&&(h=o.trim(0,a[0].par1),h instanceof N&&(o=h)))}return o}static CreateSimpleEdgeCurveWithUnderlyingPolyline(t){const e=t.sourcePort?t.sourcePort.Location:t.source.center,i=t.targetPort?t.targetPort.Location:t.target.center;if(t.source===t.target){const s=2/(3*t.source.boundaryCurve.boundingBox.width),n=t.source.boundingBox.height/4;t.smoothedPolyline=_e.CreateUnderlyingPolylineForSelfEdge(e,s,n),t.curve=t.smoothedPolyline.createCurve()}else t.smoothedPolyline=Y.mkFromPoints([e,i]),t.curve=t.smoothedPolyline.createCurve();Bt.trimSplineAndCalculateArrowheadsII(t,t.source.boundaryCurve,t.target.boundaryCurve,t.curve,!1)}static CreateUnderlyingPolylineForSelfEdge(t,e,i){const s=t.add(new c(0,i)),n=t.add(new c(e,i)),o=t.add(new c(e,i*-1)),a=t.add(new c(0,i*-1));let h=Dt.mkSiteP(t);const u=new Y(h);return h=Dt.mkSiteSP(h,s),h=Dt.mkSiteSP(h,n),h=Dt.mkSiteSP(h,o),h=Dt.mkSiteSP(h,a),Dt.mkSiteSP(h,t),u}static SetStraightLineEdgesWithUnderlyingPolylines(t){qt.CreatePortsIfNeeded(Array.from(t.deepEdges));for(const e of t.deepEdges)_e.CreateSimpleEdgeCurveWithUnderlyingPolyline(e)}}var qs;(function(l){l[l.OverlapsOtherLabels=0]="OverlapsOtherLabels",l[l.OverlapsNodes=1]="OverlapsNodes",l[l.OverlapsEdges=2]="OverlapsEdges",l[l.OverlapsNothing=Number.MAX_VALUE]="OverlapsNothing"})(qs||(qs={}));var Xe;(function(l){l[l.Any=0]="Any",l[l.Port=1]="Port",l[l.Starboard=2]="Starboard",l[l.Top=3]="Top",l[l.Bottom=4]="Bottom",l[l.Left=5]="Left",l[l.Right=6]="Right"})(Xe||(Xe={}));class Xl{}class Kl{constructor(){this.points=[],this.coveredLength=0}AddFirst(t){if(this.points.length!==0){const e=this.points[0];this.coveredLength=this.coveredLength+t.Center.sub(e.Center).length}return this.points.unshift(t),this.coveredLength}AddLast(t){if(this.points.length!==0){const e=this.points[this.points.length-1];this.coveredLength=this.coveredLength+t.Center.sub(e.Center).length}return this.points.push(t),this.coveredLength}}var yn;(function(l){l[l.AlongCurve=0]="AlongCurve",l[l.Horizontal=1]="Horizontal"})(yn||(yn={}));class Ba{constructor(t){this.location=t,this.boundingBox=X.rectangleOnPoint(t)}}class rr{constructor(t,e){this.data=e,this.boundingBox=t}}class Yl{constructor(t){this.innerPoints=[],this.outerPoints=[],this.placementSide=Xe.Any,this.placementOffset=.5,this.edgePoints=t,this.placementSide}}class bt extends Ft{get CollisionGranularity(){return this.granularity}set CollisionGranularity(t){this.granularity=t}static constructorG(t){return new bt(Array.from(t.nodesBreadthFirst),Array.from(t.deepEdges).filter(e=>e.label))}static constructorGA(t,e){return new bt(Array.from(t.nodesBreadthFirst),e.filter(i=>i.label))}constructor(t,e){super(null),this.placementStrategy=[yn.Horizontal,yn.AlongCurve],this.obstacleMaps=[],this.edgeInfos=new Map,this.granularity=bt.MinGranularity,this.ScaleCollisionGranularity=!0,this.granularity=this.ScaleCollisionGranularity?this.interpolateGranularity(e.length):bt.MinGranularity,this.InitializeObstacles(t,e),this.edges=e}interpolateGranularity(t){if(t<=bt.LowerEdgeBound)return bt.MaxGranularity;if(t>=bt.UpperEdgeBound)return bt.MinGranularity;const e=(bt.UpperEdgeBound-bt.LowerEdgeBound)/(t-bt.LowerEdgeBound);return Math.ceil(bt.MinGranularity+e)}InitializeObstacles(t,e){const i=this.GetEdgeObstacles(e);this.obstacleMaps[1]=xs(t.map(s=>[s.boundingBox,new rr(s.boundingBox,s)])),this.obstacleMaps[2]=xs(i.map(s=>[s.boundingBox,new rr(s.boundingBox,s)]))}static CurvePoints(t,e){const i=[],s=t.end.sub(t.start).lengthSquared/(e*e);return bt.SubdivideCurveSegment(i,t,s,t.parStart,t.parEnd),i.sort(bt.compareByArgument),i}static compareByArgument(t,e){return t[0]<e[0]?-1:t[0]>e[0]?1:0}static SubdivideCurveSegment(t,e,i,s,n){if(t.length>64)return;const o=e.value(s),a=e.value(n);if(o.sub(a).lengthSquared>i){const h=(s+n)/2;bt.SubdivideCurveSegment(t,e,i,s,h),bt.SubdivideCurveSegment(t,e,i,h,n)}else t.push([s,o])}static PlaceLabelsAtDefaultPositions(t,e){for(const i of e)i.label&&new bt([i.source,i.target],[i]).run()}GetEdgeObstacles(t){const e=[];for(const i of t){if(i.curve==null)continue;const s=bt.CurvePoints(i.curve,this.CollisionGranularity);this.edgeInfos.set(i,new Yl(s));for(const n of s)e.push(new Ba(n[1]))}return e}AddLabelObstacle(t){this.labelObstacleMap==null?(this.labelObstacleMap=xs([[t.boundingBox,t]]),this.obstacleMaps[0]=this.labelObstacleMap):this.labelObstacleMap.Add(t.boundingBox,t)}run(){this.edges.sort((t,e)=>this.edgeInfos.get(t).edgePoints.length-this.edgeInfos.get(e).edgePoints.length);for(const t of this.edges)this.PlaceLabel(t)}PlaceLabel(t){let e=!1;for(const i of this.placementStrategy){switch(i){case yn.AlongCurve:e=this.PlaceEdgeLabelOnCurve(t.label);break;case yn.Horizontal:e=this.PlaceEdgeLabelHorizontally(t);break;default:throw new Error("unexpected case")}if(e)break}e?this.CalculateCenterLabelInfoCenter(t.label):this.PlaceLabelAtFirstPosition(t.label)}getLabelInfo(t){const e=t.parent;return this.edgeInfos.get(e)}PlaceLabelAtFirstPosition(t){const e=t.parent,i=e.curve,s=this.edgeInfos.get(e).edgePoints,n=this.StartIndex(t,s.map(y=>y[1])),o=s[n][1];let a=i.derivative(s[n][0]);a.length<C.distanceEpsilon&&(a=new c(1,1)),a=a.normalize();const h=new be(t.width,t.height),u=this.getLabelInfo(t),d=bt.GetPossibleSides(u.placementSide,a)[0],m=bt.GetLabelBounds(o,a,h,d);this.SetLabelBounds(this.getLabelInfo(t),m)}StartIndex(t,e){const i=this.getLabelInfo(t);return Math.min(e.length-1,Math.max(0,Math.floor(e.length*i.placementOffset)))}CalculateCenterLabelInfoCenter(t){const e=this.getLabelInfo(t);let i=new c(0,0);for(const s of e.innerPoints)i=i.add(s);for(const s of e.outerPoints)i=i.add(s);t.positionCenter(i.div(e.innerPoints.length+e.outerPoints.length))}PlaceEdgeLabelHorizontally(t){const e=t.label,s=this.getLabelInfo(e).edgePoints,n=new be(e.width,e.height);let o=-1,a=X.mkEmpty();const h=t.curve;for(const u of bt.ExpandingSearch(this.StartIndex(e,s.map(d=>d[1])),0,s.length)){const d=s[u];let m=h.derivative(d[0]);if(!R(m.lengthSquared,0)){m=m.normalize();for(const y of bt.GetPossibleSides(this.getLabelInfo(e).placementSide,m)){const E=bt.GetLabelBounds(d[1],m,n,y),T=this.ConflictIndexRL(E,e);if(T>o&&(o=T,a=E,o===Number.MAX_VALUE))break}if(o===Number.MAX_VALUE)break}}if(o>=0){this.SetLabelBounds(this.getLabelInfo(e),a);const u=new rr(a,null);this.AddLabelObstacle(u);const d=this.getLabelInfo(e);return o===0?d.placementResult=qs.OverlapsOtherLabels:o===1?d.placementResult=qs.OverlapsNodes:o===2?d.placementResult=qs.OverlapsEdges:d.placementResult=qs.OverlapsNothing,!0}return!1}static GetLabelBounds(t,e,i,s){const n=e.rotate(Math.PI/2).mul(s),o=t.add(n),a=1;let h=n.x>0?o.x:o.x-i.width,u=n.y>0?o.y:o.y-i.height;if(Math.abs(n.x)<.75){const d=Math.acos(Math.abs(n.y)/a),m=a/Math.sin(d),y=a/Math.cos(d);h+=(n.x>0?-1:1)*Math.min(m,i.width/2),u+=(n.y>0?1:-1)*y}else if(Math.abs(n.y)<.75){const d=Math.acos(Math.abs(n.x)/a),m=a/Math.sin(d),y=a/Math.cos(d);h+=(n.x>0?1:-1)*y,u+=(n.y>0?-1:1)*Math.min(m,i.height/2)}return X.mkLeftBottomSize(h,u,i)}SetLabelBounds(t,e){t.innerPoints=[e.leftTop,e.rightTop],t.outerPoints=[e.leftBottom,e.rightBottom]}static GetPossibleSides(t,e){switch(e.length===0&&(t=Xe.Any),t){case Xe.Port:return[-1];case Xe.Starboard:return[1];case Xe.Top:return R(e.x,0)?bt.GetPossibleSides(Xe.Left,e):[1];case Xe.Bottom:return R(e.x,0)?bt.GetPossibleSides(Xe.Right,e):[e.x<0?-1:1];case Xe.Left:return R(e.y,0)?bt.GetPossibleSides(Xe.Top,e):[e.y<0?-1:1];case Xe.Right:return R(e.y,0)?bt.GetPossibleSides(Xe.Bottom,e):[e.y<0?1:-1];default:return[-1,1]}}static*ExpandingSearch(t,e,i){let s=t+1,n=s;for(;n>e;)yield--n;for(;s<i;)yield s++}static PointSetLength(t){let e=0,i=null;for(const s of t)i!=null&&(e+=i.sub(s.Center).length),i=s.Center;return e}PlaceEdgeLabelOnCurve(t){const e=t.parent,i=this.getLabelInfo(t);i.innerPoints=null;const s=i.edgePoints,n=3,o=t.height/2,a=new be(o,o),h=t.width;for(const u of bt.ExpandingSearch(this.StartIndex(t,s),0,s.length)){const d=this.GetSidesAndEdgeCurve(t,e,s,u);for(const m of d){const y=new Kl,E={coveredLength:0};if(this.ProcessExpandingSearchOnSide(u,s,e.curve,m,o,n,a,E,y,h),E.coveredLength>=h)return this.CaseOfCoveredLengthGreaterThanLabelLength(t,y,E.coveredLength,h,a),!0}}return!1}CaseOfCoveredLengthGreaterThanLabelLength(t,e,i,s,n){const o=new Array,a=new Array,h=Array.from(e.points),u=i-s;if(u>0){let m=h[h.length-1],y=h[h.length-2],E=m.Center.sub(y.Center),T=E.length;u>T&&(m=h[0],y=h[1],E=m.Center.sub(y.Center),T=E.length);const B=E.mul((T-u)/T);m.Center=y.Center.add(B),m.Inner=y.Inner.add(B),m.Outer=y.Outer.add(B)}this.GoOverOrderedPointsAndAddLabelObstacels(h,o,a,n);const d=this.getLabelInfo(t);d.innerPoints=o,d.outerPoints=a}GoOverOrderedPointsAndAddLabelObstacels(t,e,i,s){for(const n of t){const o=n.Center;e.push(n.Inner),i.push(n.Outer);const a=new rr(X.mkSizeCenter(new be(s.width*2,s.height*2),o),null);this.AddLabelObstacle(a)}}ProcessExpandingSearchOnSide(t,e,i,s,n,o,a,h,u,d){for(const m of bt.ExpandingSearch(t,0,e.length)){const[y,E]=e[m],T=i.derivative(y);if(R(T.lengthSquared,0))continue;const B=T.rotate(Math.PI/2).normalize().mul(s),H=E.add(B.mul(n+o));if(this.Conflict(H,n,a))break;{const tt=new Xl;if(tt.Center=H,tt.Inner=E.add(B.mul(o)),tt.Outer=E.add(B.mul(2*n+o)),h.coveredLength=m<=t?u.AddFirst(tt):u.AddLast(tt),h.coveredLength>=d)break}}}GetSidesAndEdgeCurve(t,e,i,s){const n=e.curve.derivative(i[s][0]);return bt.GetPossibleSides(this.getLabelInfo(t).placementSide,n)}Conflict(t,e,i){return this.ConflictIndex(t,e,i)!==Number.MAX_VALUE}ConflictIndexRL(t,e){const i=e.parent,s=i.source,n=i.target;for(let o=0;o<this.obstacleMaps.length;o++)if(this.obstacleMaps[o]!=null){for(const a of this.obstacleMaps[o].GetAllIntersecting(t))if(!(o===qs.OverlapsNodes&&a instanceof rr&&a.data instanceof Gt&&(s.node.isDescendantOf(a.data.graph)||n.node.isDescendantOf(a.data))))return o}return Number.MAX_VALUE}ConflictIndex(t,e,i){const s=X.creatRectangleWithSize(new be(i.width*2,i.height*2),t),n=e*e;for(let o=0;o<this.obstacleMaps.length;o++)if(this.obstacleMaps[o]!=null){for(let a=0;a<this.obstacleMaps.length;a++)if(this.obstacleMaps[a]!=null)for(const h of this.obstacleMaps[a].GetAllIntersecting(s))if(h instanceof Ba){if(t.sub(h.location).lengthSquared<n)return a}else return a;return Number.MAX_VALUE}}}bt.MinGranularity=5,bt.MaxGranularity=50,bt.LowerEdgeBound=500,bt.UpperEdgeBound=3e3;class zi extends ae{clone(){throw new Error("Method not implemented.")}rebind(t){this.entity=t,this.bind(pt.AlgorithmDataIndex)}constructor(t,e=null){super(t,pt.AlgorithmDataIndex),this.data=e}static getAlgData(t){return t.getAttr(pt.AlgorithmDataIndex)}}function Fo(l){const t=zi.getAlgData(l.node);return t==null?null:t.data}class Jl{get Center(){return this.center}set Center(t){this.geomNode.center=t,this.center=t}ResetBounds(){this.previousCenter=this.geomNode.center,this.center=this.geomNode.center,this.Width=this.geomNode.width,this.Height=this.geomNode.height}constructor(t,e){this.force=new c(0,0),this.stayWeight=1,this.index=t,this.geomNode=e,this.ResetBounds()}ToString(){return"FINode("+(this.index+("):"+this.geomNode))}}class Zl{constructor(t){this._length=1,this.mEdge=t,this.sourceFiNode=Fo(this.mEdge.source),this.targetFiNode=Fo(this.mEdge.target)}get source(){return this.sourceFiNode.index}get target(){return this.targetFiNode.index}get length(){return this._length}set length(t){this._length=t}vector(){return this.sourceFiNode.geomNode.center.sub(this.targetFiNode.geomNode.center)}}class Le{get Center(){return this.c}set Center(t){this.c=t}get Radius(){return this.r}set Radius(t){this.r=t,this.r2=t*t}Distance2(t){const e=this.c.y-t.y,i=this.c.x-t.x;return i*i+e*e}Contains(t){return this.Distance2(t)-1e-7<=this.r2}ContainsPN(t,e){for(let i=0;i<t.length;i++)if(e.findIndex(s=>s==i)==-1&&!this.Contains(t[i]))return!1;return!0}static constructorP(t){const e=new Le;return e.c=t,e.r=0,e.r2=0,e}static midPoint(t,e){return new c((e.x+t.x)/2,(e.y+t.y)/2)}static constructorPP(t,e){const i=new Le;return i.c=Le.midPoint(t,e),i.r2=i.Distance2(t),i.r=Math.sqrt(i.r2),Mt.assert(i.OnBoundary(t)),Mt.assert(i.OnBoundary(e)),i}OnBoundary(t){const e=this.Distance2(t);return Math.abs(e-this.r2)/(e+this.r2)<1e-5}static centre(t,e,i){Mt.assert(e.x!=t.x),Mt.assert(i.x!=e.x);const s=(e.y-t.y)/(e.x-t.x),n=(i.y-e.y)/(i.x-e.x);Mt.assert(n!=s);let o;const a=(s*n*(t.y-i.y)+n*(t.x+e.x)-s*(e.x+i.x))/(2*(n-s));return Math.abs(s)>Math.abs(n)?o=(t.y+e.y)/2-(a-(t.x+e.x)/2)/s:o=(e.y+i.y)/2-(a-(e.x+i.x)/2)/n,new c(a,o)}static Collinear(t,e,i){return t.x*(e.y-i.y)+(e.x*(i.y-t.y)+i.x*(t.y-e.y))==0}static constructorPPP(t,e,i){Le.count++;const s=new Le;if(Le.Collinear(t,e,i)){const n=new c(Math.min(t.x,Math.min(e.x,i.x)),Math.min(t.y,Math.max(e.y,i.y))),o=new c(Math.max(t.x,Math.max(e.x,i.x)),Math.max(t.y,Math.max(e.y,i.y)));s.c=Le.midPoint(n,o),s.r2=s.Distance2(o),s.r=Math.sqrt(s.r2)}else{const n=e.x-t.x,o=i.x-e.x,a=i.x-t.x;n!=0?o!=0?s.c=Le.centre(t,e,i):(Mt.assert(a!=0),s.c=Le.centre(e,t,i)):(Mt.assert(o!=0),s.c=Le.centre(e,i,t)),s.r2=s.Distance2(t),s.r=Math.sqrt(s.r2),Mt.assert(s.OnBoundary(t)),Mt.assert(s.OnBoundary(e)),Mt.assert(s.OnBoundary(i))}return s}}Le.count=0;function _l(l){const t=l.slice();return th(t),Do(t,l.length,[],0)}function th(l){let t,e,i;for(i=l.length-1;i>0;i--)t=Vi(i+1),e=l[i],l[i]=l[t],l[t]=e;return l}function Do(l,t,e,i){let s=null;return i===3?s=eh(e[0],e[1],e[2]):t===1&&i===0?s={x:l[0].x,y:l[0].y,r:0}:t===0&&i===2?s=La(e[0],e[1]):t===1&&i===1?s=La(e[0],l[0]):(s=Do(l,t-1,e,i),ih(l[t-1],s)||(e[i++]=l[t-1],s=Do(l,t-1,e,i))),s}function eh(l,t,e){const i=l.x,s=l.y,n=t.x,o=t.y,a=e.x,h=e.y,u=n-i,d=o-s,m=a-i,y=h-s,E=u*(n+i)*.5+d*(o+s)*.5,T=m*(a+i)*.5+y*(h+s)*.5,B=u*y-d*m,H=(y*E-d*T)/B,tt=(-m*E+u*T)/B;return{x:H,y:tt,r:Math.sqrt((i-H)*(i-H)+(s-tt)*(s-tt))}}function La(l,t){const e=l.x,i=l.y,s=t.x,n=t.y,o=.5*(e+s),a=.5*(i+n);return{x:o,y:a,r:Math.sqrt((e-o)*(e-o)+(i-a)*(i-a))}}function ih(l,t){return(t.x-l.x)*(t.x-l.x)+(t.y-l.y)*(t.y-l.y)<=t.r*t.r}class sh{static LinearComputation(t){const e=_l(t),i=new Le;return i.Center=new c(e.x,e.y),i.Radius=e.r,i}static SlowComputation(t){const e=t.length;let i=null,s=null;for(let n=0;n<e;n++)for(let o=0;o<e;o++){if(n!=o){const a=Le.constructorPP(t[n],t[o]);a.ContainsPN(t,[n,o])&&(i==null||i.Radius>a.Radius)&&(i=a,s=[n,o])}for(let a=0;a<e;a++)if(a!=n&&a!=o&&!Le.Collinear(t[n],t[o],t[a])){const h=Le.constructorPPP(t[n],t[o],t[a]);h.ContainsPN(t,[n,o,a])&&(i==null||i.Radius>h.Radius)&&(i=h,s=[n,o,a])}}return Mt.assert(s!=null),i}}class gi{static constructorNPA(t,e,i){const s=new gi;s.p=t,s.z0=new se(e.x,e.y),s.a=new Array(t);for(let n=0;n<t;n++)s.a[n]=s.compute(n,i);return s}static constructorPMM(t,e,i){const s=new gi;Mt.assert(e.p==i.p),s.p=e.p,s.z0=new se(t.x,t.y);const n=i.shift(s.z0),o=e.shift(s.z0);s.a=new Array(s.p);for(let a=0;a<s.p;a++)s.a[a]=Ro(o[a],n[a]);return s}static factorial(t){let e=1;for(let i=2;i<=t;i++)e*=i;return e}static binomial(t,e){return gi.factorial(t)/(gi.factorial(e)*gi.factorial(t-e))}sum(t,e){let i=se.constructorN(0);for(let s=1;s<=t;s++){const n=se.constructorN(gi.binomial(t-1,s-1));i=Ro(i,cs(this.a[s],cs(se.Pow(e,t-s),n)))}return i}shift(t){const e=new Array(this.p),i=e[0]=this.a[0],s=or(this.z0,t);for(let n=1;n<this.p;n++){const o=se.constructorN(n);e[n]=Ro(cs(rh(i),No(se.Pow(s,n),o)),this.sum(n,s))}return e}compute(t,e){const i=e.length;let s=se.constructorN(0);if(t==0)s.re=i;else{for(let n=0;n<i;n++){const o=e[n],a=new se(o.x,o.y);s=or(s,se.Pow(or(a,this.z0),t))}s.divideBy(t)}return s}ApproximateForce(t){const e=new se(t.x,t.y),i=or(e,this.z0);let s=No(this.a[0],i),n=i,o=0;for(;s=or(s,No(nh(this.a[o],o),n)),o++,o!=this.p;)n=cs(n,i);return new c(s.re,-s.im)}static Force(t,e){const i=e.sub(t),s=i.lengthSquared;return s<.1?s!=0?i.div(.1):new c(1,0):i.div(s)}}class se{constructor(t,e){this.re=t,this.im=e}static constructorN(t){return new se(t,0)}divideBy(t){this.re/=t,this.im/=t}static Pow(t,e){switch(Mt.assert(e>=0),e){case 0:return se.constructorN(1);case 1:return t;case 2:return cs(t,t);case 3:return cs(t,cs(t,t));default:return cs(se.Pow(t,e/2),se.Pow(t,e/2+e%2))}}}function Ro(l,t){return new se(l.re+t.re,l.im+t.im)}function cs(l,t){return new se(l.re*t.re-l.im*t.im,l.re*t.im+t.re*l.im)}function nh(l,t){return new se(l.re*t,l.im*t)}function or(l,t){return new se(l.re-t.re,l.im-t.im)}function rh(l){return new se(-l.re,-l.im)}function No(l,t){const e=t.re*t.re+t.im*t.im;if(e==0)return se.constructorN(0);const i=l.re*t.re+l.im*t.im,s=l.im*t.re-l.re*t.im;return new se(i/e,s/e)}var fi;(function(l){l[l.Horizontal=0]="Horizontal",l[l.Vertical=1]="Vertical"})(fi||(fi={}));class Fa{intersects(t){return t.med.Center.sub(this.med.Center).length<t.med.Radius+this.med.Radius}}class oh extends Fa{constructor(t,e,i){super(),this.med=t,this.parent=e.parent,this.parent!=null&&(this.parent.leftChild==e?this.parent.leftChild=this:this.parent.rightChild=this),this.leftChild=e,this.rightChild=i,e.parent=this,i.parent=this}computeMultipoleCoefficients(t){this.leftChild.computeMultipoleCoefficients(t),this.rightChild.computeMultipoleCoefficients(t),this.multipoleCoefficients=gi.constructorPMM(this.med.Center,this.leftChild.multipoleCoefficients,this.rightChild.multipoleCoefficients)}}class Kr extends Fa{constructor(t){super(),this.particles=t,this.ComputeMinimumEnclosingDisc()}computeMultipoleCoefficients(t){this.multipoleCoefficients=gi.constructorNPA(t,this.med.Center,this.ps)}ComputeMinimumEnclosingDisc(){const t=this.Size();this.ps=new Array(t);for(let e=0;e<t;e++)this.ps[e]=this.particles[0][e].point;return this.med=sh.LinearComputation(this.ps)}Min(t){return this.particles[t][0].pos(t)}Size(){return this.particles[0].length}Max(t){return this.particles[t][this.Size()-1].pos(t)}Dimension(t){return this.Max(t)-this.Min(t)}Split(t){const e=this.Dimension(fi.Horizontal)>this.Dimension(fi.Vertical)?fi.Horizontal:fi.Vertical,i=e==fi.Horizontal?fi.Vertical:fi.Horizontal,s=this.Size(),n=s>>1,o=s-n,a=[new Array(n),new Array(n)],h=[new Array(o),new Array(o)];let u=0,d=0;for(let y=0;y<s;y++){const E=this.particles[e][y];y<n?(a[e][y]=E,E.splitLeft=!0):(h[e][y-n]=E,E.splitLeft=!1)}for(let y=0;y<s;y++){const E=this.particles[i][y];E.splitLeft?a[i][d++]=E:h[i][u++]=E}const m=this.med;return this.particles=a,this.ComputeMinimumEnclosingDisc(),t.rightSibling=new Kr(h),new oh(m,this,t.rightSibling)}ComputeForces(){for(const t of this.particles[0])for(const e of this.particles[0])t!=e&&(t.force=t.force.add(gi.Force(t.point,e.point)))}}class ah{pos(t){return t==fi.Horizontal?this.point.x:this.point.y}constructor(t){this.point=t,this.force=new c(0,0)}}class lh{particlesBy(t){return this.particles.map(e=>e).sort((e,i)=>e.pos(t)-i.pos(t))}constructor(t,e){this.particles=t;const i=new Array;i.push(this.particlesBy(fi.Horizontal)),i.push(this.particlesBy(fi.Vertical)),this.leaves=new Array;let s=new Kr(i);this.leaves.push(s);const n={rightSibling:null};this.root=s.Split(n),this.leaves.push(n.rightSibling);const o=new hh(e);for(o.EnqueueLL(s,n.rightSibling);o.length>0;)s=o.dequeue(),s.Split(n),this.leaves.push(n.rightSibling),o.EnqueueLL(s,n.rightSibling)}ComputeForces(t){this.root.computeMultipoleCoefficients(t);for(const e of this.leaves){e.ComputeForces();const i=new Array;for(i.push(this.root);i.length>0;){const s=i.pop();if(e.intersects(s))if(s instanceof Kr)for(const n of e.particles[0])for(const o of s.particles[0])n!=o&&(n.force=n.force.add(gi.Force(n.point,o.point)));else{const n=s;i.push(n.leftChild),i.push(n.rightChild)}else for(const n of e.particles[0])n.force=n.force.sub(s.multipoleCoefficients.ApproximateForce(n.point))}}}}class hh extends Ge.o{constructor(t){super(),this.B=t}EnqueueLL(t,e){t.Size()>this.B&&this.enqueue(t),e.Size()>this.B&&this.enqueue(e)}}class ar extends Ft{constructor(t,e,i){if(super(null),this.clustersInfo=new Map,this.clusterEdges=new Array,this.graph=t,this.settings=e,this.initFiNodesEdges(),this.edges=Array.from(this.graph.shallowEdges).map(s=>zi.getAlgData(s.edge).data),this.nodes=Array.from(this.graph.shallowNodes).map(s=>zi.getAlgData(s.node).data),this.components=new Array,this.settings.InterComponentForces)this.components.push(this.nodes);else{this.basicGraph=Qe(this.edges,this.nodes.length);for(const s of Ci(this.basicGraph)){const n=new Array(s.length);let o=0;for(const a of s)n[o++]=this.nodes[a];this.components.push(n)}}this.computeWeight(t),this.setCurrentConstraintLevel(i)}initFiNodesEdges(){let t=0;for(const e of this.graph.shallowNodes){const i=new Jl(t++,e);new zi(e.node,i)}for(const e of this.graph.shallowEdges){const i=new Zl(e);new zi(e.edge,i)}}getCurrentConstraintLevel(){return this.currentConstraintLevel}setCurrentConstraintLevel(t){this.currentConstraintLevel=t,this.settings.Unconverge()}ResetNodePositions(){for(const t of this.nodes)t.ResetBounds()}AddRepulsiveForce(t,e){t.force=e.mul(10*this.settings.RepulsiveForceConstant)}AddLogSpringForces(t,e,i){const s=e.length,n=7e-4*this.settings.AttractiveForceConstant*s*Math.log((s+.1)/(i+.1));t.sourceFiNode.force=t.sourceFiNode.force.add(e.mul(n)),t.targetFiNode.force=t.targetFiNode.force.sub(e.mul(n))}AddSquaredSpringForces(t,e,i){const s=e.length,n=i*i+.1,o=this.settings.AttractiveForceConstant*(s-i)/n;t.sourceFiNode.force=t.sourceFiNode.force.add(e.mul(o)),t.targetFiNode.force=t.targetFiNode.force.sub(e.mul(o))}AddSpringForces(t){let e;if(this.settings.RespectEdgePorts){let i=t.sourceFiNode.Center,s=t.targetFiNode.Center;const n=t.mEdge.sourcePort;n instanceof Ue&&(i=n.Location);const o=t.mEdge.targetPort;o instanceof Ue&&(s=o.Location),e=i.sub(s)}else e=t.vector();this.settings.LogScaleEdgeForces?this.AddLogSpringForces(t,e,t.length):this.AddSquaredSpringForces(t,e,t.length)}static AddGravityForce(t,e,i){i!=null&&(i.force=i.force.sub(t.sub(i.Center).mul(e*1e-4)))}ComputeRepulsiveForces(t){const e=t.length;if(e>16&&this.settings.ApproximateRepulsion){const i=new Array(t.length),s=2*(Math.PI/e);let n=0;for(let a=0;a<e;a++)i[a]=new ah(t[a].Center.add(new c(Math.cos(n),Math.sin(n)).mul(1e-5))),n+=s;new lh(i,8).ComputeForces(5);for(let a=0;a<t.length;a++)this.AddRepulsiveForce(t[a],i[a].force)}else for(const i of t){let s=new c(0,0);for(const n of t)i!=n&&(s=s.add(gi.Force(i.Center,n.Center)));this.AddRepulsiveForce(i,s)}}SetBarycenter(t){const e=this.clustersInfo.get(t);if(e!=null)return e.barycenter;let i=new c(0,0);if(t.shallowNodeCount||uh(t)){const s=this.clustersInfo.get(t);if((s==null||s.weight==null)&&this.computeWeight(t),s.weight!=null){for(const n of t.shallowNodes)n instanceof Jt?i=i.add(n.center):i=i.add(this.SetBarycenter(n).mul(this.clustersInfo.get(n).weight));this.clustersInfo.get(t).barycenter=i=i.div(s.weight)}}else this.clustersInfo.get(t).barycenter=i;return i}computeWeight(t){let e=0;for(const s of t.shallowNodes)s.entity instanceof Vt?e+=this.computeWeight(s):e++;let i=this.clustersInfo.get(t);return i==null&&this.clustersInfo.set(t,i={barycenter:new c(0,0)}),i.weight=e,e}AddClusterForces(t){if(t!=null){this.SetBarycenter(t);for(const e of this.clusterEdges){const i=ot.getGeom(e.source),s=ot.getGeom(e.target),n=zi.getAlgData(e.source).data,o=zi.getAlgData(e.target).data,a=i.hasOwnProperty("shallowNodes"),h=a?this.clustersInfo.get(i).barycenter:i.center,u=s.hasOwnProperty("shallowNodes"),d=u?this.clustersInfo.get(s).barycenter:s.center;let m=h.sub(d);const y=m.length,E=1e-8*(this.settings.AttractiveInterClusterForceConstant*(y*Math.log(y+.1)));if(m=m.mul(E),a){const T=i;for(const B of T.shallowNodes){const H=zi.getAlgData(B.node).data;H.force=H.force.add(m)}}else n.force=n.force.add(m);if(u){const T=s;for(const B of T.shallowNodes){const H=zi.getAlgData(B.node).data;H.force=H.force.sub(m)}}else o.force=o.force.sub(m)}for(const e of t.subgraphsDepthFirst){const i=this.clustersInfo.get(e).barycenter;for(const s of e.shallowNodes)ar.AddGravityForce(i,this.settings.ClusterGravity,Fo(s))}}}ComputeForces(){if(this.components!=null)for(const t of this.components)this.ComputeRepulsiveForces(t);else this.ComputeRepulsiveForces(this.nodes);this.edges.forEach(t=>this.AddSpringForces(t));for(const t of this.components){let e=new c(0,0);for(let s=0;s<t.length;s++)e=e.add(t[s].Center);e=e.div(t.length);let i=Number.NEGATIVE_INFINITY;for(let s=0;s<t.length;s++){const n=t[s];ar.AddGravityForce(e,this.settings.GravityConstant,n),n.force.length>i&&(i=n.force.length)}if(i>100)for(let s=0;s<t.length;s++)t[s].force=t[s].force.mul(100/i)}this.AddClusterForces(this.graph)}VerletIntegration(){const t=this.energy;this.energy=this.ComputeDescentDirection(1),this.UpdateStepSize(t);let e=0;for(let i=0;i<this.nodes.length;i++){const s=this.nodes[i];e+=s.Center.sub(s.previousCenter).lengthSquared}return e}ComputeDescentDirection(t){this.ResetForceVectors(),this.settings.ApplyForces&&this.ComputeForces();let e=0;for(const i of this.nodes){e=e+i.force.lengthSquared;let s=i.Center.sub(i.previousCenter).mul(this.settings.Friction);const n=i.force.mul(-this.stepSize*t);i.previousCenter=i.Center,Mt.assert(!Number.isNaN(n.x),"!double.IsNaN(a.X)"),Mt.assert(!Number.isNaN(n.y),"!double.IsNaN(a.Y)"),Mt.assert(Number.isFinite(n.x),"!double.IsInfinity(a.X)"),Mt.assert(Number.isFinite(n.y),"!double.IsInfinity(a.Y)"),s=s.add(n),s=s.div(i.stayWeight),i.Center=i.Center.add(s)}return e}ResetForceVectors(){for(const t of this.nodes)t.force=new c(0,0)}UpdateStepSize(t){this.energy<t?++this.progress>=3&&(this.progress=0,this.stepSize/=this.settings.Decay):(this.progress=0,this.stepSize*=this.settings.Decay)}RungeKuttaIntegration(){const t=new Array(this.nodes.length),e=new Array(this.nodes.length),i=new Array(this.nodes.length),s=new Array(this.nodes.length),n=new Array(this.nodes.length),o=this.energy;for(let h=0;h<this.nodes.length;h++)this.nodes[h].previousCenter=this.nodes[h].Center,t[h]=this.nodes[h].Center;const a=3;this.ComputeDescentDirection(a);for(let h=0;h<this.nodes.length;h++)e[h]=this.nodes[h].Center.sub(this.nodes[h].previousCenter),this.nodes[h].Center=t[h].add(e[h].mul(.5));this.ComputeDescentDirection(a);for(let h=0;h<this.nodes.length;h++)i[h]=this.nodes[h].Center.sub(this.nodes[h].previousCenter),this.nodes[h].previousCenter=t[h],this.nodes[h].Center=t[h].add(i[h].mul(.5));this.ComputeDescentDirection(a);for(let h=0;h<this.nodes.length;h++)s[h]=this.nodes[h].Center.sub(this.nodes[h].previousCenter),this.nodes[h].previousCenter=t[h],this.nodes[h].Center=t[h].add(s[h]);this.energy=this.ComputeDescentDirection(a);for(let h=0;h<this.nodes.length;h++){n[h]=this.nodes[h].Center.sub(this.nodes[h].previousCenter),this.nodes[h].previousCenter=t[h];const u=e[h].add(i[h].mul(2).add(s[h].mul(2)).add(n[h])).div(6);this.nodes[h].Center=t[h].add(u)}return this.UpdateStepSize(o),this.nodes.reduce((h,u)=>u.Center.sub(u.previousCenter).lengthSquared+h,0)}run(){this.settings.Converged=!1,this.settings.EdgeRoutesUpToDate=!1,this.settings.Iterations++==0&&(this.stepSize=this.settings.InitialStepSize,this.energy=Number.MAX_VALUE,this.progress=0);for(let t=0;t<this.settings.MinorIterations;t++){if((this.settings.RungeKuttaIntegration?this.RungeKuttaIntegration():this.VerletIntegration())<this.settings.DisplacementThreshold||this.settings.Iterations>this.settings.MaxIterations){this.settings.Converged=!0;break}this.ProgressStep()}}}function uh(l){for(const t of l.Clusters)return!0;return!1}class ds{get edgeRoutingSettings(){return this.commonSettings.edgeRoutingSettings}set edgeRoutingSettings(t){this.commonSettings.edgeRoutingSettings=t}get PackingAspectRatio(){return this.commonSettings.PackingAspectRatio}set PackingAspectRatio(t){this.commonSettings.PackingAspectRatio=t}get NodeSeparation(){return this.commonSettings.NodeSeparation}set NodeSeparation(t){this.commonSettings.NodeSeparation=t}get MaxIterations(){return this.maxIterations}set MaxIterations(t){this.maxIterations=t}get MinorIterations(){return this.minorIterations}set MinorIterations(t){this.minorIterations=t}get Iterations(){return this.iterations}set Iterations(t){this.iterations=t}get ProjectionIterations(){return this.projectionIterations}set ProjectionIterations(t){this.projectionIterations=t}get ApproximateRepulsion(){return this.approximateRepulsion}set ApproximateRepulsion(t){this.approximateRepulsion=t}get InitialStepSize(){return this.initialStepSize}set InitialStepSize(t){if(t<=0||t>2)throw new Error("ForceScalar should be greater than 0 and less than 2 (if we let you set it to 0 nothing would happen, greater than 2 would most likely be very unstable!)");this.initialStepSize=t}get Decay(){return this.decay}set Decay(t){if(t<.1||t>1)throw new Error("Setting decay too small gives no progress. 1==no decay, 0.1==minimum allowed value");this.decay=t}get Friction(){return this.friction}set Friction(t){if(t<0||t>1)throw new Error("Setting friction less than 0 or greater than 1 would just be strange. 1==no friction, 0==no conservation of velocity");this.friction=t}get RepulsiveForceConstant(){return this.repulsiveForceConstant}set RepulsiveForceConstant(t){this.repulsiveForceConstant=t}get AttractiveForceConstant(){return this.attractiveForceConstant}set AttractiveForceConstant(t){this.attractiveForceConstant=t}get GravityConstant(){return this.gravity}set GravityConstant(t){this.gravity=t}get InterComponentForces(){return this.interComponentForces}set InterComponentForces(t){this.interComponentForces=t}get ApplyForces(){return this.applyForces}set ApplyForces(t){this.applyForces=t}constructor(){this.commonSettings=new mn,this.maxIterations=100,this.clusterMargin=10,this.minorIterations=3,this.projectionIterations=5,this.approximateRepulsion=!0,this.RungeKuttaIntegration=!1,this.initialStepSize=1.4,this.decay=.9,this.friction=.8,this.repulsiveForceConstant=1,this.attractiveForceConstant=1,this.gravity=1,this.interComponentForces=!0,this.applyForces=!0,this.AvoidOverlaps=!0,this.approximateRouting=!0,this.logScaleEdgeForces=!0,this.displacementThreshold=.1,this.maxConstraintLevel=2,this.minConstraintLevel=0,this.attractiveInterClusterForceConstant=1,this.clusterGravity=1,this.commonSettings.NodeSeparation*=2}ResetLayout(){this.Unconverge(),this.algorithm!=null&&this.algorithm.ResetNodePositions()}Unconverge(){this.iterations=0,this.converged=!1}InitializeLayoutGN(t,e){this.InitializeLayout(t,e)}InitializeLayout(t,e){this.algorithm=new ar(t,this,e),this.ResetLayout()}Uninitialize(){this.algorithm=null}get IsInitialized(){return this.algorithm!=null}IncrementalRunG(t){this.IncrementalRunGF(t)}SetupIncrementalRun(t){this.IsInitialized?this.IsDone&&this.ResetLayout():this.InitializeLayout(t,this.MaxConstraintLevel)}IncrementalRunGF(t){this.SetupIncrementalRun(t),this.algorithm.run()}IncrementalRun(t,e){t?.throwIfCanceled(),this.SetupIncrementalRun(e),this.algorithm.cancelToken=t,this.algorithm.run()}Clone(){return ds.ctorClone(this)}get ApproximateRouting(){return this.approximateRouting}set ApproximateRouting(t){this.approximateRouting=t}get LogScaleEdgeForces(){return this.logScaleEdgeForces}set LogScaleEdgeForces(t){this.logScaleEdgeForces=t}get DisplacementThreshold(){return this.displacementThreshold}set DisplacementThreshold(t){this.displacementThreshold=t}get Converged(){return this.converged}set Converged(t){this.converged=t}get PercentDone(){return this.Converged?100:100*this.iterations/this.MaxIterations}get IsDone(){return this.Converged||this.iterations>=this.MaxIterations}get Energy(){return this.algorithm!=null?this.algorithm.energy:0}get MaxConstraintLevel(){return this.maxConstraintLevel}set MaxConstraintLevel(t){this.maxConstraintLevel!=t&&(this.maxConstraintLevel=t,this.IsInitialized&&this.Uninitialize())}get MinConstraintLevel(){return this.minConstraintLevel}set MinConstraintLevel(t){this.minConstraintLevel=t}getCurrentConstraintLevel(){return this.algorithm==null?0:this.algorithm.getCurrentConstraintLevel()}setCurrentConstraintLevel(t){this.algorithm.setCurrentConstraintLevel(t)}get AttractiveInterClusterForceConstant(){return this.attractiveInterClusterForceConstant}set AttractiveInterClusterForceConstant(t){this.attractiveInterClusterForceConstant=t}static ctorClone(t){const e=new ds;return e.maxIterations=t.maxIterations,e.minorIterations=t.minorIterations,e.projectionIterations=t.projectionIterations,e.approximateRepulsion=t.approximateRepulsion,e.initialStepSize=t.initialStepSize,e.RungeKuttaIntegration=t.RungeKuttaIntegration,e.decay=t.decay,e.friction=t.friction,e.repulsiveForceConstant=t.repulsiveForceConstant,e.attractiveForceConstant=t.attractiveForceConstant,e.gravity=t.gravity,e.interComponentForces=t.interComponentForces,e.applyForces=t.applyForces,e.AvoidOverlaps=t.AvoidOverlaps,e.RespectEdgePorts=t.RespectEdgePorts,e.RouteEdges=t.RouteEdges,e.approximateRouting=t.approximateRouting,e.logScaleEdgeForces=t.logScaleEdgeForces,e.displacementThreshold=t.displacementThreshold,e.minConstraintLevel=t.minConstraintLevel,e.maxConstraintLevel=t.maxConstraintLevel,e.attractiveInterClusterForceConstant=t.attractiveInterClusterForceConstant,e.clusterGravity=t.clusterGravity,e.PackingAspectRatio=t.PackingAspectRatio,e.NodeSeparation=t.NodeSeparation,e.clusterMargin=t.clusterMargin,e}get ClusterGravity(){return this.clusterGravity}set ClusterGravity(t){this.clusterGravity=t}static CreateFastIncrementalLayoutSettings(){const t=new ds;return t.ApplyForces=!1,t.ApproximateRepulsion=!0,t.ApproximateRouting=!0,t.AttractiveForceConstant=1,t.AttractiveInterClusterForceConstant=1,t.AvoidOverlaps=!0,t.ClusterGravity=1,t.Decay=.9,t.DisplacementThreshold=5e-8,t.Friction=.8,t.GravityConstant=1,t.InitialStepSize=2,t.InterComponentForces=!1,t.Iterations=0,t.LogScaleEdgeForces=!1,t.MaxConstraintLevel=2,t.MaxIterations=20,t.MinConstraintLevel=0,t.MinorIterations=1,t.ProjectionIterations=5,t.RepulsiveForceConstant=2,t.RespectEdgePorts=!1,t.RouteEdges=!1,t.RungeKuttaIntegration=!0,t.NodeSeparation=20,t}}class ch{constructor(t){this.topNodes=t}get nodesBreadthFirst(){return this.nodesBreadthFirst_()}*nodesBreadthFirst_(){for(const t of this.topNodes)if(yield Jt.getGeom(t),t instanceof Vt)for(const e of t.nodesBreadthFirst)yield Jt.getGeom(e)}get Clusters(){return this.clusters()}*clusters(){for(const t of this.topNodes)t instanceof Vt&&(yield Gt.getGeom(t))}get subgraphsDepthFirst(){return this.subgraphsDepthFirst_()}*subgraphsDepthFirst_(){for(const t of this.topNodes)if(t instanceof Vt){const e=Gt.getGeom(t);yield*e.subgraphsDepthFirst,yield e}}get shallowEdges(){return this.edges_()}*edges_(){for(const t of this.topNodes){for(const e of t.outEdges)yield we.getGeom(e);for(const e of t.selfEdges)yield we.getGeom(e)}}get shallowNodes(){return this.shallowNodes_()}*shallowNodes_(){for(const t of this.topNodes)yield Jt.getGeom(t)}pumpTheBoxToTheGraphWithMargins(){const t={b:X.mkEmpty()};return Gn(this,t),this.boundingBox=t.b}get shallowNodeCount(){return this.topNodes.length}translate(t){this.boundingBox&&(this.boundingBox.center=this.boundingBox.center.add(t));for(const e of this.topNodes)Jt.getGeom(e).translate(t)}}class Da{static LinearInterpolation(t,e,i,s,n){if(t<e)return s;if(t>i)return n;const o=(t-e)/(i-e);return s+o*(n-s)}static NegativeLinearInterpolation(t,e,i,s,n){if(t<e)return n;if(t>i)return s;const o=(t-e)/(i-e);return s+(1-o)*(n-s)}}class dh extends Ft{constructor(t,e){super(null),this.SingleComponent=!1,this.graph=t,this.settings=ds.ctorClone(e),this.settings.ApplyForces=!0,this.settings.InterComponentForces=!0,this.settings.RungeKuttaIntegration=!1,this.settings.RespectEdgePorts=!1}run(){if(this.SingleComponent)this.componentCount=1,this.LayoutComponent(this.graph);else{const t=Array.from(this.graph.graph.getClusteredConnectedComponents()).map(e=>new ch(e));this.componentCount=t.length;for(const e of t)this.LayoutComponent(e);this.graph.boundingBox=sr.PackGraphs(t,this.settings.commonSettings)}}LayoutComponent(t){if(t.shallowNodeCount>1){if(this.settings.MaxIterations=Da.NegativeLinearInterpolation(t.shallowNodeCount,50,500,5,10),this.settings.MinorIterations=Da.NegativeLinearInterpolation(t.shallowNodeCount,50,500,3,20),this.settings.MinConstraintLevel==0){const i=new nr;i.removeOverlaps=!1,i.IterationsWithMajorization=0,new Lo(t,null,()=>1,new nr).run()}const e=new ar(t,this.settings,this.settings.MinConstraintLevel);for(const i of this.GetConstraintLevels(t)){if(i>this.settings.MaxConstraintLevel)break;i>this.settings.MinConstraintLevel&&e.setCurrentConstraintLevel(i);do e.run();while(!this.settings.IsDone)}this.settings.AvoidOverlaps&&xi.RemoveOverlaps(Array.from(this.graph.shallowNodes),this.settings.NodeSeparation)}t.pumpTheBoxToTheGraphWithMargins(),t.uniformMargins=this.settings.NodeSeparation,t.translate(t.boundingBox.leftBottom.mul(-1))}GetConstraintLevels(t){const e=new Set;return e.add(0),this.settings.AvoidOverlaps&&t.shallowNodeCount<2e3&&e.add(2),e}}function Ra(l){if(l instanceof SugiyamaLayoutSettings)return 0;if(l instanceof IPsepColaSetting)return 1;if(l instanceof MdsLayoutSettings)return 2;if(l instanceof FastIncrementalLayoutSettings)return 3;throw new Error("not implemented")}function gh(l,t){(!l.layoutSettings||Ra(l.layoutSettings)!==Ra(t))&&(l.layoutSettings=t);for(const e of l.shallowNodes)e instanceof GeomGraph&&gh(e,l.layoutSettings)}function Na(l){l.layoutSettings||(l.layoutSettings=Ga(l))}function fh(l){let t=l.parent;for(;t;){if(t.layoutSettings)return t.layoutSettings;t=t.parent}return null}function Ga(l){const t=fh(l);if(t)return t;if(l.graph.shallowNodeCount>2e3||l.graph.deepEdgesCount>4e3)return new ds;let i=!1;for(const s of l.deepEdges)if(s.sourceArrowhead!=null||s.targetArrowhead!=null){i=!0;break}return i?new Hs:new ds}function ph(l,t,e=()=>1){if(Na(l),l.layoutSettings instanceof Hs)new qo(l,l.layoutSettings,t).run();else if(l.layoutSettings instanceof nr)new Lo(l,t,e,l.layoutSettings).run();else if(l.layoutSettings instanceof ds){const i=new dh(l,l.layoutSettings);i.SingleComponent=!0,i.run()}else throw new Error("not implemented")}function mh(l,t=null){Na(l),Va(l,t,ph,Ma,yo),bh(l)}function ka(l){do{if(l.layoutSettings&&l.layoutSettings.commonSettings.edgeRoutingSettings)return l.layoutSettings.commonSettings.edgeRoutingSettings;const e=l.graph.parent;if(e)l=ot.getGeom(e);else break}while(!0);const t=new tr;return t.EdgeRoutingMode=Be.Spline,t}function Ma(l,t,e){const i=ka(l);i.EdgeRoutingMode===Be.Rectilinear?yh(l,t,e):i.EdgeRoutingMode===Be.Spline||i.EdgeRoutingMode===Be.SplineBundling?Vh(l,t,e):i.EdgeRoutingMode===Be.StraightLine?Oa(l,t,e):i.EdgeRoutingMode!==Be.None&&new qt(l,t).run(),Wa(l,t)}function Va(l,t,e,i,s,n=1,o=()=>1){if(l.graph.isEmpty())return;const a=l.shallowNodes.next();l.parent==null&&(os(n),Ch(l));const h=E();y(l);const u=Ph(l.graph),d=Sh(l);if(T(),u.forEach(B=>{B[0].edge.remove(),B[1].add()}),d.forEach(B=>{for(const H of B.graph.shallowNodes)H.parent=l.graph}),h.forEach(B=>B.add()),l.graph.parent==null){const B=m(l);i(l,B,t),Wa(l,B),l.pumpTheBoxToTheGraphWithMargins()}function m(B){const H=[];for(const tt of B.nodesBreadthFirst){for(const lt of tt.outEdges())lt.curve==null&&H.push(lt);for(const lt of tt.selfEdges())lt.curve==null&&H.push(lt)}return H}function y(B){for(const H of B.shallowNodes)H instanceof Gt&&Va(H,t,e,i,s)}function E(){const B=new Set,H=l.graph;if(H.parent==null)return B;for(const tt of H.shallowNodes){for(const lt of tt.outEdges){const Q=H.liftNode(lt.target);(Q==null||Q===tt)&&B.add(lt)}for(const lt of tt.inEdges){const Q=H.liftNode(lt.source);(Q==null||Q===tt)&&B.add(lt)}}for(const tt of B)tt.remove();return B}function T(){if(d.length===1)e(l,t,o);else{for(const B of d)e(B,t,o),B.boundingBox=B.pumpTheBoxToTheGraphWithMargins();s(l,d)}}}function Ph(l){const t=new Array;for(const e of l.nodesBreadthFirst){const i=l.liftNode(e);if(i!=null)for(const s of e.outEdges.values()){const n=s.target,o=l.liftNode(n);if(o==null||i===e&&o===n||i===o)continue;s.remove();const a=new Is(i,o),h=new we(a);t.push([h,s])}}return t}function Sh(l){var t;const e=l.graph,i=Ln(e),s=[];let n=0;for(const o of i){const a=new Vt(e.id+n++);a.parent=e;const h=new Gt(a);h.layoutSettings=(t=l.layoutSettings)!==null&&t!==void 0?t:Ga(l);for(const u of o)u.parent=a,a.addNode(u);s.push(h)}return s}function yh(l,t,e,i=1,s=3,n=3){const o=le.constructorGNAN(l,t,i,s);o.edgeSeparatian=n,o.run()}function Wa(l,t){if(t.length===0)return;bt.constructorGA(l,t).run()}function Ch(l){for(const t of l.deepEdges)t.label&&(t.label.isPositioned=!1)}function Ah(l){if(GeomGraph.getGeom(l)==null)return!1;for(const t of l.shallowNodes){const e=GeomObject.getGeom(t);if(e==null||e.boundaryCurve==null||t instanceof Graph&&Ah(t)===!1)return!1}for(const t of l.edges)if(GeomEdge.getGeom(t)==null)return!1;return!0}function Eh(l){const t=GeomGraph.getGeom(l);if(t==null||t.boundingBox==null||t.boundingBox.isEmpty())return!1;for(const e of l.shallowNodes){const i=GeomObject.getGeom(e);if(i==null||i.boundaryCurve==null||e instanceof Graph&&Eh(e)===!1)return!1}for(const e of l.deepEdges){const i=GeomEdge.getGeom(e);if(i==null||i.curve==null)return!1}return!0}function bh(l){const t=l.boundingBox.leftBottom;if(t.x<0||t.y<0){const e=new c(-t.x,-t.y);l.translate(e)}}class Go{static constructorStatic(t,e){const i=new Go;i.edges=t,i.nodeBoundaries=e,i.boundingBox=X.mkEmpty();for(const s of i.nodeBoundaries)i.boundingBox=i.boundingBox.addRec(s.boundingBox);return i}AddGraph(t){this.edges=this.edges.concat(t.edges),this.nodeBoundaries=Ki(this.nodeBoundaries,t.nodeBoundaries),this.boundingBox.addRec(t.boundingBox)}AddNodeBoundary(t){this.nodeBoundaries.add(t),this.boundingBox.addRec(t.boundingBox)}}var ko;(function(l){l[l.Success=0]="Success",l[l.Overlaps=1]="Overlaps",l[l.EdgeSeparationIsTooLarge=2]="EdgeSeparationIsTooLarge"})(ko||(ko={}));class Yr{get CurrentPiercedEdge(){return this.currentPiercedEdge}get CurrentTriangle(){return this.currentTriangle}constructor(t,e,i){this.currentTriangle=t,this.start=e,this.end=i}FindFirstPiercedEdge(){const t=this.GetHyperplaneSign(this.currentTriangle.Sites.item0),e=this.GetHyperplaneSign(this.currentTriangle.Sites.item1);if(t!==e&&c.getTriangleOrientation(this.end,this.currentTriangle.Sites.item0.point,this.currentTriangle.Sites.item1.point)==D.Clockwise)return this.positiveSign=t,this.negativeSign=e,this.currentTriangle.Edges.item0;const i=this.GetHyperplaneSign(this.currentTriangle.Sites.item2);return e!==i&&c.getTriangleOrientation(this.end,this.currentTriangle.Sites.item1.point,this.currentTriangle.Sites.item2.point)==D.Clockwise?(this.positiveSign=e,this.negativeSign=i,this.currentTriangle.Edges.item1):(this.positiveSign=i,this.negativeSign=t,this.currentTriangle.Edges.item2)}FindNextPierced(){if(this.currentTriangle=this.currentPiercedEdge.GetOtherTriangle_T(this.currentTriangle),this.currentTriangle==null){this.currentPiercedEdge=null;return}const t=this.currentTriangle.Edges.index(this.currentPiercedEdge);let e;const i=this.currentTriangle.Sites.getItem(t+2),s=this.GetHyperplaneSign(i);this.negativeSign===0?s===-1||s===0?(this.negativeSign=s,e=t+1):e=t+2:this.positiveSign===0?s===1||s===0?(this.positiveSign=s,e=t+2):e=t+1:s!==this.positiveSign?(this.negativeSign=s,e=t+1):(this.positiveSign=s,e=t+2),this.currentPiercedEdge=c.signedDoubledTriangleArea(this.end,this.currentTriangle.Sites.getItem(e).point,this.currentTriangle.Sites.getItem(e+1).point)<-C.distanceEpsilon?this.currentTriangle.Edges.getItem(e):null}GetHyperplaneSign(t){const e=c.signedDoubledTriangleArea(this.start,t.point,this.end);return e>C.distanceEpsilon?1:e<-C.distanceEpsilon?-1:0}MoveNext(){return this.currentPiercedEdge==null?this.currentPiercedEdge=this.FindFirstPiercedEdge():this.FindNextPierced(),this.currentPiercedEdge!=null}}class Mo{EdgeIsLegal_(t,e,i,s){if(ie.PointIsInsideOfTriangle(e,i))return!0;const n=new Yr(i,t,e);for(;n.MoveNext();){const o=n.CurrentPiercedEdge;if(o.constrained){const a=o.lowerSite.Owner;if(!s.has(a))return!1}}return!0}constructor(t,e){this.ComputeForcesForBundles=!1,this.metroGraphData=t,this.bundlingSettings=e}BundleAvoidsObstacles(t,e,i,s,n,o){o.closestDist=new Array;const a=this.metroGraphData.looseIntersections.ObstaclesToIgnoreForBundle(t,e),h=this.FindCloseObstaclesForBundle(e.cdtTriangle,s,i,a,n);if(h==null)return!1;for(const u of h){const d=u[1];o.closestDist.push(d)}return!0}FindCloseObstaclesForBundle(t,e,i,s,n){const o=new Map,a=[];if(!this.ThreadLineSegmentThroughTriangles(t,e,i,s,a))return null;if(!this.ComputeForcesForBundles&&!this.bundlingSettings.HighestQuality)return o;const h=new Set;for(const u of a)for(const d of u.Sites){if(h.has(d))continue;h.add(d);const m=d.Owner;if(s.has(m))continue;const y=Mo.FindPolylinePoint(m,d.point),E=N.minDistBetweenLineSegments(y.point,y.nextOnPolyline.point,e,i),T=E.dist,B=E.parab,H=E.parcd,tt=N.minDistBetweenLineSegments(y.point,y.prevOnPolyline.point,e,i),lt=tt.dist,Q=tt.parab,dt=tt.parcd;let It,Tt,oe;if(T<lt){if(oe=T,oe>n)continue;It=y.point.add(y.nextOnPolyline.point.sub(y.point).mul(B)),Tt=e.add(i.sub(e).mul(H))}else{if(oe=lt,oe>n)continue;It=y.point.add(y.prevOnPolyline.point.sub(y.point).mul(Q)),Tt=e.add(i.sub(e).mul(dt))}o.get(m)||o.set(m,[It,Tt])}return o}ThreadLineSegmentThroughTriangles(t,e,i,s,n){if(ie.PointIsInsideOfTriangle(i,t))return n.push(t),!0;const o=new Yr(t,e,i);for(n.push(t);o.MoveNext();){n.push(o.CurrentTriangle);const a=o.CurrentPiercedEdge;if(a.constrained){const h=a.lowerSite.Owner;if(!s.has(h))return!1}}return o.CurrentTriangle!=null&&n.push(o.CurrentTriangle),!0}static PointLocationInsideTriangle(t,e){let i=!1;for(let s=0;s<3;s++){const n=c.signedDoubledTriangleArea(t,e.Sites.getItem(s).point,e.Sites.getItem(s+1).point);if(n<C.distanceEpsilon*-1)return at.Outside;n<C.distanceEpsilon&&(i=!0)}return i?at.Boundary:at.Inside}static FindPolylinePoint(t,e){for(const i of t.polylinePoints())if(i.point.equal(e))return i;throw new Error("polyline point "+e+" not found")}EdgeIsLegal(t,e,i,s){const n=[],o=this.metroGraphData.looseIntersections.ObstaclesToIgnoreForBundle(t,e);return this.ThreadLineSegmentThroughTriangles(t.cdtTriangle,i,s,o,n)}EdgeIsLegalSSPPS(t,e,i){const s=t.Position,n=t.cdtTriangle,o=e.Position;if(ie.PointIsInsideOfTriangle(o,n))return!0;const a=new Yr(n,s,o);for(;a.MoveNext();){const h=a.CurrentPiercedEdge;if(h.constrained){const u=h.lowerSite.Owner;if(!i.has(u))return!1}}return!0}}class Oi{constructor(t,e,i,s){this.metroGraphData=t,this.obstaclesToIgnoreLambda=s,this.bundlingSettings=e,this.obstacleTree=i}ObstaclesToIgnoreForBundle(t,e){return t!=null&&e!=null?Ki(this.obstaclesToIgnoreLambda(t),this.obstaclesToIgnoreLambda(e)):t==null&&e==null?new Set:t!=null?this.obstaclesToIgnoreLambda(t):this.obstaclesToIgnoreLambda(e)}HubAvoidsObstaclesSPNBA(t,e,i,s){const n={minimalDistance:i};return Oi.IntersectCircleWithTree(this.obstacleTree,e,i,this.obstaclesToIgnoreLambda(t),s.touchedObstacles,n)}HubAvoidsObstaclesPNS__(t,e,i){const s={touchedObstacles:Array()},n={minimalDistance:0};return this.HubAvoidsObstaclesPNSTT(t,e,i,s,n)}GetMinimalDistanceToObstacles(t,e,i){const s=new Array,n={minimalDistance:i};return Oi.IntersectCircleWithTree(this.obstacleTree,e,i,this.obstaclesToIgnoreLambda(t),s,n)?n.minimalDistance:0}HubAvoidsObstaclesPNSTT(t,e,i,s,n){return s.touchedObstacles=new Array,n.minimalDistance=e,Oi.IntersectCircleWithTree(this.obstacleTree,t,e,i,s.touchedObstacles,n)}static IntersectCircleWithTree(t,e,i,s,n,o){if(!t.irect.contains_point_radius(e,i))return!0;if(t.UserData==null){let a=Oi.IntersectCircleWithTree(t.Left,e,i,s,n,o);if(!a||(a=Oi.IntersectCircleWithTree(t.Right,e,i,s,n,o),!a))return!1}else{const a=t.UserData;if(s.has(a))return!0;if(w.PointRelativeToCurveLocation(e,a)!==at.Outside)return Oi.containingPoly=a,!1;const u=a.value(a.closestParameter(e)),d=u.sub(e).length;d<=i&&n.push([a,u]),o.minimalDistance=Math.min(d,o.minimalDistance)}return!0}static Create4gon(t,e,i,s){let n=e.sub(t).normalize();return n=new c(n.y,n.x*-1),st.mkFromPoints([t.add(n.mul(i/2)),t.sub(n.mul(i/2)),e.sub(n.mul(s/2)),e.add(n.mul(s/2))])}}class wh{constructor(t,e,i,s){this.Width=e,this.Polyline=t,this.sourceAndTargetLoosePolylines=i,this.Index=s}UpdateLengths(){let t=0;for(let e=this.Polyline.startPoint;e.next!=null;e=e.next)t+=e.next.point.sub(e.point).length;this.Length=t,this.IdealLength=this.Polyline.end.sub(this.Polyline.start).length}}class vh{constructor(t,e,i){this.metroline=t,this.station=e,this.polyPoint=i}get Metroline(){return this.metroline}get PolyPoint(){return this.polyPoint}}class Ih{constructor(t,e,i){this.Radius=0,this.BundleBases=new Map,this.MetroNodeInfos=new Array,this._cachedIdealRadius=0,this.SerialNumber=t,this.IsReal=e,this.Position=i}debStop(){return this.SerialNumber===28&&this.Position.sub(new c(841.2662778763244,303.3817005853006)).length<.001}get Position(){return this._Position}set Position(t){this._Position=t}getELP(){return this.EnterableLoosePolylines}setELP(t){this.EnterableLoosePolylines=t}addEL(t){this.EnterableLoosePolylines.add(t)}get cachedIdealRadius(){return this._cachedIdealRadius}set cachedIdealRadius(t){this._cachedIdealRadius=t}AddEnterableLoosePolyline(t){this.EnterableLoosePolylines==null&&(this.EnterableLoosePolylines=new Set),this.EnterableLoosePolylines.add(t)}AddEnterableTightPolyline(t){this.EnterableTightPolylines==null&&(this.EnterableTightPolylines=new Set),this.EnterableTightPolylines.add(t)}}class Th{constructor(){this.Width=0,this.Metrolines=new Array,this.cachedBundleCost=0}get Count(){return this.Metrolines.length}}class Fe{constructor(t,e){this.metroGraphData=t,this.bundlingSettings=e}CreateNodeRadii(){for(const t of this.metroGraphData.VirtualStations())t.Radius=0,t.cachedIdealRadius=Fe.CalculateIdealHubRadiusWithNeighborsMBS(this.metroGraphData,this.bundlingSettings,t);this.GrowHubs(!1),this.GrowHubs(!0);for(const t of this.metroGraphData.VirtualStations())t.Radius=Math.max(t.Radius,this.bundlingSettings.MinHubRadius)}GrowHubs(t){const e=new Ri(k);for(const s of this.metroGraphData.VirtualStations())e.Enqueue(s,-this.CalculatePotential(s,t));let i=!1;for(;!e.IsEmpty();){const s={priority:0},n=e.DequeueAndGetPriority(s);if(s.priority>=0)break;this.TryGrowHub(n,t)&&(e.Enqueue(n,-this.CalculatePotential(n,t)),i=!0)}return i}TryGrowHub(t,e){const i=this.CalculateAllowedHubRadius(t);if(t.Radius>=i)return!1;const s=e?Fe.CalculateIdealHubRadiusWithAdjacentEdges(this.bundlingSettings,t):t.cachedIdealRadius;if(t.Radius>=s)return!1;let o=.05*(s-t.Radius);o<1&&(o=1);const a=Math.min(t.Radius+o,i);return a<=t.Radius?!1:(t.Radius=a,!0)}CalculatePotential(t,e){const i=e?Fe.CalculateIdealHubRadiusWithAdjacentEdges(this.bundlingSettings,t):t.cachedIdealRadius;return i<=t.Radius?0:(i-t.Radius)/i}CalculateAllowedHubRadius(t){let e=this.bundlingSettings.MaxHubRadius;for(const s of t.Neighbors){const n=s.Position.sub(t.Position).length;e=Math.min(e,n/1.05-s.Radius)}const i=this.metroGraphData.tightIntersections.GetMinimalDistanceToObstacles(t,t.Position,e);return i<e&&(e=i-.001),Math.max(e,.1)}static CalculateIdealHubRadius(t,e,i){let s=1;for(const n of i.Neighbors){const a=t.GetWidthSSN(n,i,e.EdgeSeparation)/2+e.EdgeSeparation;s=Math.max(s,a)}return s=Math.min(s,2*e.MaxHubRadius),s}static CalculateIdealHubRadiusWithNeighborsMBS(t,e,i){return Fe.CalculateIdealHubRadiusWithNeighborsMBNP(t,e,i,i.Position)}static CalculateIdealHubRadiusWithNeighborsMBNP(t,e,i,s){let n=Fe.CalculateIdealHubRadius(t,e,i);if(i.Neighbors.length>1){const o=i.Neighbors;for(let a=0;a<o.length;a++){const h=o[a],u=o[(a+1)%o.length];n=Math.max(n,Fe.GetMinRadiusForTwoAdjacentBundles(n,i,s,h,u,t,e))}}return n=Math.min(n,2*e.MaxHubRadius),n}static CalculateIdealHubRadiusWithAdjacentEdges(t,e){let i=t.MaxHubRadius;for(const s of e.Neighbors)i=Math.min(i,e.Position.sub(s.Position).length/2);return i}static GetMinRadiusForTwoAdjacentBundles(t,e,i,s,n,o,a){const h=o.GetWidthSSN(e,s,a.EdgeSeparation),u=o.GetWidthSSN(e,n,a.EdgeSeparation);return Fe.GetMinRadiusForTwoAdjacentBundlesNPPPNNB(t,i,s.Position,n.Position,h,u,a)}static GetMinRadiusForTwoAdjacentBundlesNPPPNNB(t,e,i,s,n,o,a){if(n<C.distanceEpsilon||o<C.distanceEpsilon)return t;let h=c.anglePCP(i,e,s);if(h=Math.min(h,Math.PI*2-h),h<C.distanceEpsilon)return 2*a.MaxHubRadius;if(h>=Math.PI/2)return t*1.05;const u=Math.sin(h),d=Math.cos(h),m=n/(4*u),y=o/(4*u);let E=2*Math.sqrt(m*m+(y*y+2*(m*(y*d))));return E=Math.min(E,2*a.MaxHubRadius),E=Math.max(E,t),E}}class Jr{constructor(t,e,i,s){this.metroGraphData=t,this.bundlingSettings=e,this.costCalculator=i,this.cdt=s}InitializeCostCache(){for(const t of this.metroGraphData.VirtualStations())t.cachedIdealRadius=Fe.CalculateIdealHubRadiusWithNeighborsMBS(this.metroGraphData,this.bundlingSettings,t),t.cachedRadiusCost=this.costCalculator.RadiusCost(t,t.Position),t.cachedBundleCost=0;for(const t of this.metroGraphData.VirtualEdges()){const e=t[0],i=t[1],s=this.metroGraphData.GetIjInfo(e,i);s.cachedBundleCost=this.costCalculator.BundleCost(e,i,e.Position),e.cachedBundleCost+=s.cachedBundleCost,i.cachedBundleCost+=s.cachedBundleCost}}UpdateCostCache(t){const e=this.cdt.getRectangleNodeOnTriangles();t.cdtTriangle=e.FirstHitNodeWithPredicate(t.Position,Jr.testPointInside).UserData,t.cachedIdealRadius=Fe.CalculateIdealHubRadiusWithNeighborsMBS(this.metroGraphData,this.bundlingSettings,t),t.cachedRadiusCost=this.costCalculator.RadiusCost(t,t.Position),t.cachedBundleCost=0;for(const i of t.Neighbors){i.IsReal||(i.cachedIdealRadius=Fe.CalculateIdealHubRadiusWithNeighborsMBS(this.metroGraphData,this.bundlingSettings,i),i.cachedRadiusCost=this.costCalculator.RadiusCost(i,i.Position));const s=this.metroGraphData.GetIjInfo(t,i);i.cachedBundleCost-=s.cachedBundleCost,s.cachedBundleCost=this.costCalculator.BundleCost(t,i,t.Position),t.cachedBundleCost+=s.cachedBundleCost,i.cachedBundleCost+=s.cachedBundleCost}}static testPointInside(t,e){return ie.PointIsInsideOfTriangle(t,e)?Nt.Stop:Nt.Continue}}class Ha{constructor(){this.mainMap=new Map}get isEmpty(){return this.mainMap.size===0||this.everyMapIsEmpty()}everyMapIsEmpty(){for(const t of this.mainMap.values())if(t.size)return!1;return!0}get(t,e){const i=this.mainMap.get(t);if(i)return i.get(e)}has(t,e){const i=this.mainMap.get(t);return i?i.has(e):!1}set(t,e,i){let s=this.mainMap.get(t);s||(s=new Map,this.mainMap.set(t,s)),s.set(e,i)}*[Symbol.iterator](){for(const[t,e]of this.mainMap)for(const[i,s]of e)yield[t,i,s]}*keys(){for(const[t,e]of this.mainMap)for(const[i]of e)yield[t,i]}}class xh{constructor(t,e,i,s,n,o,a,h){this.cachedEnterableLooseForEnd=new je,this.bundlingSettings=s,this.regularEdges=t,n!=null?this.cdt=n:this.cdt=Ia(e),this.EdgeLooseEnterable=o,this.EdgeTightEnterable=a,this.LoosePolylineOfPort=h,this.looseIntersections=new Oi(this,s,e,u=>u.getELP()),this.tightIntersections=new Oi(this,s,i,u=>u.EnterableTightPolylines),this.cdtIntersections=new Mo(this,s),this.Initialize(!1)}get Ink(){return this.ink}get Edges(){return this.regularEdges}VirtualStations(){return Array.from(this.Stations).filter(t=>!t.IsReal)}get Metrolines(){return this.metrolines}get LooseTree(){return this.looseIntersections.obstacleTree}get TightTree(){return this.tightIntersections.obstacleTree}*VirtualEdges(){for(const t of this.edgeInfoDictionary.keys())yield t}RealEdgeCount(t,e){const i=t.SerialNumber<e.SerialNumber?[t,e]:[e,t],s=this.edgeInfoDictionary.get(i[0],i[1]);return s?s.Count:0}MetroNodeInfosOfNode(t){return t.MetroNodeInfos}GetIjInfo(t,e){const i=t.SerialNumber<e.SerialNumber?[t,e]:[e,t];return this.edgeInfoDictionary.get(i[0],i[1])}MoveNode(t,e){const i=t.Position;this.PointToStations.deleteP(i),this.PointToStations.set(e,t),t.Position=e;for(const s of this.MetroNodeInfosOfNode(t))s.PolyPoint.point=e;for(const s of this.MetroNodeInfosOfNode(t)){const n=s.Metroline,o=s.PolyPoint.prev.point,a=s.PolyPoint.next.point;n.Length+=a.sub(e).length+o.sub(e).length-a.sub(i).length-o.sub(i).length}for(const s of t.Neighbors)this.ink+=e.sub(s.Position).length-i.sub(s.Position).length;this.SortNeighbors(t);for(const s of t.Neighbors)this.SortNeighbors(s)}GetWidthSSN(t,e,i){const s=t.SerialNumber<e.SerialNumber?[t,e]:[e,t],n=this.edgeInfoDictionary.get(s[0],s[1]);return n?n.Width+(n.Count-1)*i:0}GetWidthAN(t,e){let i=0;for(const n of t)i+=n.Width;const s=t.length;return i+=s>0?(s-1)*e:0,i}Initialize(t){this.SimplifyRegularEdges(),this.InitializeStationData(),this.InitializeEdgeData(),this.InitializeVirtualGraph(),this.InitializeEdgeNodeInfo(t),this.InitializeCdtInfo()}SimplifyRegularEdges(){for(const t of this.regularEdges)this.SimplifyRegularEdge(t)}SimplifyRegularEdge(t){const e=t.curve,i=new Ut.B,s=new Yt;for(let n=e.endPoint;n!=null;n=n.prev){const o=n.point;if(s.has(n.point)){let a=n.next;do{const h=i.top;if(!h.equal(o))s.delete(h),i.pop(),a=a.next;else break}while(!0);a.prev=n.prev,a.prev.next=a}else i.push(o),s.add(o)}}InitializeStationData(){this.Stations=[],this.PointToStations=new je;for(const t of this.regularEdges){const e=t.curve;this.ProcessPolylinePoints(e)}}ProcessPolylinePoints(t){let e=t.startPoint;for(this.RegisterStation(e,!0),e=e.next;e!==t.endPoint;e=e.next)this.RegisterStation(e,!1);this.RegisterStation(e,!0)}RegisterStation(t,e){if(!this.PointToStations.has(t.point)){const i=new Ih(this.Stations.length,e,t.point);this.PointToStations.set(t.point,i),this.Stations.push(i)}}InitializeEdgeData(){this.metrolines=new Array;for(let t=0;t<this.regularEdges.length;t++){const e=this.regularEdges[t];this.InitEdgeData(e,t)}}InitEdgeData(t,e){const i=new wh(t.curve,this.bundlingSettings.ActualEdgeWidth(t),this.EdgeSourceAndTargetFunc(t),e);this.metrolines.push(i),this.PointToStations.get(i.Polyline.start).BoundaryCurve=t.sourcePort.Curve,this.PointToStations.get(i.Polyline.end).BoundaryCurve=t.targetPort.Curve}EdgeSourceAndTargetFunc(t){return()=>[this.LoosePolylineOfPort(t.sourcePort),this.LoosePolylineOfPort(t.targetPort)]}InitializeVirtualGraph(){const t=new Map;for(const e of this.metrolines){let i=this.PointToStations.get(e.Polyline.start),s;for(let n=e.Polyline.startPoint;n.next!=null;n=n.next,i=s)s=this.PointToStations.get(n.next.point),nn(t,i,s),nn(t,s,i)}for(const e of this.Stations)e.Neighbors=Array.from(t.get(e))}GetUnorderedIjInfo(t,e){return t.SerialNumber<e.SerialNumber?this.GetCreateOrderedIjInfo(t,e):this.GetCreateOrderedIjInfo(e,t)}static closedeb(t,e){return t.Position.sub(new c(360.561,428.416)).length<.1&&e.Position.sub(new c(414.281,440.732)).length<.1}GetCreateOrderedIjInfo(t,e){let i=this.edgeInfoDictionary.get(t,e);return i||(i=new Th,this.edgeInfoDictionary.set(t,e,i),i)}InitializeEdgeNodeInfo(t){this.edgeInfoDictionary=new Ha,this.InitAllMetroNodeInfos(t),this.SortAllNeighbors(),this.InitEdgeIjInfos(),this.ink=0;for(const e of this.VirtualEdges())this.ink+=e[0].Position.sub(e[1].Position).length}InitAllMetroNodeInfos(t){for(let e=0;e<this.metrolines.length;e++){const i=this.metrolines[e];this.InitMetroNodeInfos(i),this.InitNodeEnterableLoosePolylines(i,this.regularEdges[e]),t&&this.InitNodeEnterableTightPolylines(i,this.regularEdges[e]),i.UpdateLengths()}}InitMetroNodeInfos(t){for(let e=t.Polyline.startPoint;e!=null;e=e.next){const i=this.PointToStations.get(e.point);i.MetroNodeInfos.push(new vh(t,i,e))}}InitNodeEnterableLoosePolylines(t,e){const i=this.EdgeLooseEnterable!=null?this.EdgeLooseEnterable.get(e):new Set;for(let s=t.Polyline.startPoint.next;s!=null&&s.next!=null;s=s.next){const n=this.PointToStations.get(s.point);n.getELP()!=null?n.setELP(Li(n.getELP(),i)):n.setELP(new Set(i))}this.AddLooseEnterableForMetrolineStartEndPoints(t)}AddLooseEnterableForMetrolineStartEndPoints(t){this.AddLooseEnterableForEnd(t.Polyline.start),this.AddLooseEnterableForEnd(t.Polyline.end)}AddTightEnterableForMetrolineStartEndPoints(t){this.AddTightEnterableForEnd(t.Polyline.start),this.AddTightEnterableForEnd(t.Polyline.end)}AddLooseEnterableForEnd(t){const e=this.PointToStations.get(t);if(this.cachedEnterableLooseForEnd.has(t))e.setELP(this.cachedEnterableLooseForEnd.get(t));else{for(const i of this.LooseTree.AllHitItems_(t))w.PointRelativeToCurveLocation(t,i)===at.Inside&&e.AddEnterableLoosePolyline(i);this.cachedEnterableLooseForEnd.set(t,e.getELP())}}AddTightEnterableForEnd(t){const e=this.PointToStations.get(t);for(const i of this.TightTree.AllHitItems_(t))w.PointRelativeToCurveLocation(t,i)===at.Inside&&e.AddEnterableTightPolyline(i)}InitNodeEnterableTightPolylines(t,e){const i=this.EdgeTightEnterable!=null?this.EdgeTightEnterable.get(e):new Set;for(let s=t.Polyline.startPoint.next;s!=null&&s.next!=null;s=s.next){const n=this.PointToStations.get(s.point),o=n.EnterableTightPolylines;o!=null?n.EnterableTightPolylines=Li(o,i):n.EnterableTightPolylines=new Set(i)}this.AddTightEnterableForMetrolineStartEndPoints(t)}SortAllNeighbors(){for(const t of this.Stations)this.SortNeighbors(t)}SortNeighbors(t){if(t.Neighbors.length<=2)return;const e=t.Neighbors[0].Position,i=t.Position;t.Neighbors.sort((s,n)=>zs(e.sub(i),s.Position.sub(i),n.Position.sub(i)))}InitEdgeIjInfos(){for(const t of this.metrolines){const e=t.Polyline;let i=this.PointToStations.get(e.start),s;for(let n=t.Polyline.startPoint;n.next!=null;n=n.next,i=s){s=this.PointToStations.get(n.next.point);const o=this.GetUnorderedIjInfo(i,s);o.Width+=t.Width,o.Metrolines.push(t)}}}InitializeCdtInfo(){const t=this.cdt.getRectangleNodeOnTriangles();for(const e of this.Stations)e.cdtTriangle=t.FirstHitNodeWithPredicate(e.Position,Jr.testPointInside).UserData}PointIsAcceptableForEdge(t,e){if(this.LoosePolylineOfPort==null)return!0;const i=t.sourceAndTargetLoosePolylines();return w.PointRelativeToCurveLocation(e,i[0])===at.Outside&&w.PointRelativeToCurveLocation(e,i[1])===at.Outside}}function zs(l,t,e){const i=c.crossProduct(l,e),s=l.dot(e),n=c.crossProduct(l,t),o=l.dot(t);return R(n,0)&&Zr(o,0)?R(i,0)&&Zr(s,0)?0:1:R(i,0)&&Zr(s,0)?-1:R(n,0)||R(i,0)||n*i>0?et(c.crossProduct(e,t),0):-et(Math.sign(n),0)}function Zr(l,t){return et(l,t)>=0}class ne{constructor(t,e){this.metroGraphData=t,this.bundlingSettings=e}static InkError(t,e,i){return(t-e)*i.InkImportance}static PathLengthsError(t,e,i,s){return(t-e)*(s.PathLengthImportance/i)}static RError(t,e,i){return t<=e?0:i.HubRepulsionImportance*((1-e/t)*(t-e))}static BundleError(t,e,i){return t<=e?0:i.BundleRepulsionImportance*((1-e/t)*(t-e))}static Cost(t,e){let i=e.InkImportance*t.Ink;for(const s of t.Metrolines)i+=e.PathLengthImportance*s.Length/s.IdealLength;return i+=this.CostOfForces(t),i}static CostOfForces(t){let e=0;for(const i of t.VirtualStations())e=e+i.cachedRadiusCost;for(const i of t.VirtualEdges()){const s=i[0],n=i[1];e+=t.GetIjInfo(s,n).cachedBundleCost}return e}InkGain(t,e){const i=this.metroGraphData.Ink;let s=this.metroGraphData.Ink;for(const n of t.Neighbors){const o=n.Position;s-=o.sub(t.Position).length,s+=o.sub(e).length}return ne.InkError(i,s,this.bundlingSettings)}PathLengthsGain(t,e){let i=0;for(const s of this.metroGraphData.MetroNodeInfosOfNode(t)){const n=s.Metroline.Length,o=s.PolyPoint.prev.point,a=s.PolyPoint.next.point,h=s.Metroline.Length+a.sub(e).length+o.sub(e).length-a.sub(t.Position).length-o.sub(t.Position).length;i+=ne.PathLengthsError(n,h,s.Metroline.IdealLength,this.bundlingSettings)}return i}RadiusGain(t,e){let i=0;return i=i+t.cachedRadiusCost,i=i-this.RadiusCost(t,e),i}RadiusCost(t,e){let i;c.closeDistEps(t.Position,e)?i=t.cachedIdealRadius:i=Fe.CalculateIdealHubRadiusWithNeighborsMBNP(this.metroGraphData,this.bundlingSettings,t,e);const s={touchedObstacles:[]};if(!this.metroGraphData.looseIntersections.HubAvoidsObstaclesSPNBA(t,e,i,s))return ne.Inf;let n=0;for(const o of s.touchedObstacles){const a=o[1].sub(e).length;n+=ne.RError(i,a,this.bundlingSettings)}return n}BundleGain(t,e){let i=t.cachedBundleCost;for(const s of t.Neighbors){const n=this.BundleCost(t,s,e);if(Zr(n,ne.Inf))return-ne.Inf;i-=n}return i}BundleCost(t,e,i){const s=this.metroGraphData.GetWidthSSN(t,e,this.bundlingSettings.EdgeSeparation),n={closestDist:[]};if(!this.metroGraphData.cdtIntersections.BundleAvoidsObstacles(t,e,i,e.Position,s,n))return ne.Inf;let o=0;for(const a of n.closestDist){const h=a[0].sub(a[1]).length;o+=ne.BundleError(s/2,h,this.bundlingSettings)}return o}}ne.Inf=1e9;class Oh{get Polylines(){return Array.from(this.polylineToEdgeGeom.keys())}constructor(t){this.polylineToEdgeGeom=new Map,this.pathsThroughPoints=new je,this.interestingPoints=new Yt,this.metroGraphData=t}Run(){this.Init(),this.SwitchFlips()}Init(){for(const t of this.metroGraphData.Edges)this.polylineToEdgeGeom.set(t.curve,t);for(const t of this.Polylines)this.RegisterPolylinePointInPathsThrough(t.polylinePoints())}RegisterPolylinePointInPathsThrough(t){for(const e of t)this.RegisterPolylinePointInPathsThroughP(e)}RegisterPolylinePointInPathsThroughP(t){Bh(this.pathsThroughPoints,t.point,t)}UnregisterPolylinePointsInPathsThrough(t){for(const e of t)this.UnregisterPolylinePointInPathsThrough(e)}UnregisterPolylinePointInPathsThrough(t){Lh(this.pathsThroughPoints,t.point,t)}SwitchFlips(){const t=new Set(this.Polylines),e=new Ge.o;for(const i of this.Polylines)e.enqueue(i);for(;e.length>0;){const i=e.dequeue();t.delete(i);const s=this.ProcessPolyline(i);s!=null&&(t.has(i)||(t.add(i),e.enqueue(i)),t.has(s)||(t.add(s),e.enqueue(s)))}}ProcessPolyline(t){const e=new Map;for(let i=t.startPoint.next;i!=null;i=i.next){this.FillDepartedPolylinePoints(i,e);for(const s of this.pathsThroughPoints.get(i.point)){const n=e.get(s.polyline);if(n){if(this.ProcessFlip(i,n))return s.polyline;e.delete(s.polyline)}}}return null}FillDepartedPolylinePoints(t,e){const i=t.prev.point;for(const s of this.pathsThroughPoints.get(i))this.IsNeighborOnTheSamePolyline(s,t)||e.has(s.polyline)||e.set(s.polyline,s)}ProcessFlip(t,e){const i=t.polyline,s=e.polyline,n=t.point,o=e.point,a=this.polylineToEdgeGeom.get(i),h=this.polylineToEdgeGeom.get(s);if(a.lineWidth!==h.lineWidth||this.metroGraphData.EdgeLooseEnterable==null||!sn(this.metroGraphData.EdgeLooseEnterable.get(a),this.metroGraphData.EdgeLooseEnterable.get(h)))return!1;let u=this.FindPointsOnPolyline(i,n,o);const d=u[0],m=u[1],y=u[2];u=this.FindPointsOnPolyline(s,n,o);const E=u[0],T=u[1],B=u[2],H=this.FindRelationOnFirstPoint(d,E,y,B),tt=this.FindRelationOnLastPoint(m,T,y,B);return H!==2&&tt!==2||H===1||tt===1?!1:(this.UnregisterPolylinePointsInPathsThrough(i.polylinePoints()),this.UnregisterPolylinePointsInPathsThrough(s.polylinePoints()),this.Swap(d,E,m,T,y,B),this.RegisterPolylinePointInPathsThrough(i.polylinePoints()),this.RegisterPolylinePointInPathsThrough(s.polylinePoints()),this.RegisterInterestingPoint(d.point),this.RegisterInterestingPoint(m.point),this.numberOfReducedCrossings++,!0)}FindPointsOnPolyline(t,e,i){let s,n;for(let o=t.startPoint;o!=null;o=o.next)if(s==null)if(o.point.equal(e)){if(n!=null)return[o,n,!1];s=o}else n==null&&o.point.equal(i)&&(n=o);else if(o.point.equal(i))return[s,o,!0]}PolylinePointsAreInForwardOrder(t,e){for(let i=t;i!=null;i=i.next)if(i===e)return!0;return!1}Next(t,e){return e?t.next:t.prev}Prev(t,e){return e?t.prev:t.next}FindRelationOnFirstPoint(t,e,i,s){const n=t,o=e;for(;;){const a=this.Prev(t,i),h=this.Prev(e,s);if(a==null||h==null)return 0;if(!a.point.equal(h.point))break;t=a,e=h}return this.PolylinesIntersect(n,o,t,e,i,s)}FindRelationOnLastPoint(t,e,i,s){const n=t,o=e;for(;;){const a=this.Next(t,i),h=this.Next(e,s);if(a==null||h==null)return 0;if(!a.point.equal(h.point))break;t=a,e=h}for(;this.Next(t,i).point.equal(this.Prev(e,s).point);)t=this.Next(t,i),e=this.Prev(e,s);return this.PolylinesIntersect(t,e,n,o,i,s)}PolylinesIntersect(t,e,i,s,n,o){const a=this.Prev(t,n),h=this.Next(t,n),u=this.Next(i,n),d=this.Prev(i,n),m=this.Next(e,o),y=this.Prev(s,o);if(t.point.equal(i.point)){const E=t.point,T=zs(d.point.sub(E),y.point.sub(E),h.point.sub(E)),B=zs(d.point.sub(E),m.point.sub(E),h.point.sub(E));return T===B?1:2}else{const E=zs(a.point.sub(t.point),h.point.sub(t.point),m.point.sub(t.point)),T=zs(u.point.sub(i.point),y.point.sub(i.point),d.point.sub(i.point));return E===T?1:2}}Swap(t,e,i,s,n,o){const a=this.GetRangeOnPolyline(this.Next(t,n),i,n),h=this.GetRangeOnPolyline(this.Next(e,o),s,o);this.ChangePolylineSegment(t,i,n,h),this.ChangePolylineSegment(e,s,o,a),lr.RemoveSelfCyclesFromPolyline(t.polyline),lr.RemoveSelfCyclesFromPolyline(e.polyline)}ChangePolylineSegment(t,e,i,s){let n=t;for(const o of s){const a=zt.mkFromPoint(o.point);a.polyline=n.polyline,i?(a.prev=n,n.next=a):(a.next=n,n.prev=a),n=a}i?(n.next=e,e.prev=n):(n.prev=e,e.next=n)}GetRangeOnPolyline(t,e,i){const s=new Array;for(let n=t;n!==e;n=this.Next(n,i))s.push(n);return s}IsNeighborOnTheSamePolyline(t,e){return t.prev!=null&&t.prev.point.equal(e.point)||t.next!=null&&t.next.point.equal(e.point)}RegisterInterestingPoint(t){this.interestingPoints.has(t)||this.interestingPoints.add(t)}GetChangedHubs(){return this.interestingPoints}NumberOfReducedCrossings(){return this.numberOfReducedCrossings}PolylineIsOK(t){const e=new Yt;for(let i=t.startPoint;i!=null;i=i.next){if(i===t.startPoint){if(i.prev!=null)return!1}else if(i.prev.next!==i)return!1;if(i===t.endPoint){if(i.next!=null)return!1}else if(i.next.prev!==i)return!1;if(e.has(i.point))return!1;e.add(i.point)}return!(t.startPoint.prev!=null||t.endPoint.next!=null)}}function Bh(l,t,e){let i=l.get(t);i||(i=new Set,l.set(t,i)),i.add(e)}function Lh(l,t,e){const i=l.get(t);i&&(i.delete(e),i.size===0&&l.deleteP(t))}class lr{constructor(t,e){this.foundCrossings=new Yt,this.crossingsThatShouldBecomeHubs=new Yt,this.metroGraphData=t,this.polylineAcceptsPoint=e}*Vertices(){for(const t of this.Polylines)for(const e of t.polylinePoints())yield e}get Polylines(){return this.metroGraphData.Edges.map(t=>t.curve)}Edges(){const t=new ls;for(const e of this.Vertices())e.next&&t.set(new fe(e.point,e.next.point),0);return Array.from(t.keys())}run(){if(this.metroGraphData.Edges.length===0)return!1;const t=new ls,e=new on(null);for(const a of this.Vertices()){const h=X.mkOnPoints([a.point]);h.pad(C.intersectionEpsilon),e.Add(h,a.point)}const i=en(this.Edges(),a=>X.mkPP(a.first,a.second));pe(i,i,(a,h)=>this.IntersectTwoEdges.bind(a,h,t,e)),this.SortInsertedPoints(t);const s=this.InsertPointsIntoPolylines(t),n=this.FixPaths(),o=this.RemoveUnimportantCrossings();return n||s||o}FixPaths(){let t=!1;return this.RemoveSelfCycles()&&(t=!0),this.ReduceEdgeCrossings()&&(t=!0),t}SortInsertedPoints(t){for(const e of t)this.SortInsideSegment(e[0],e[1])}SortInsideSegment(t,e){e.sort((i,s)=>k(_(i,t.first),_(s,t.first)))}InsertPointsIntoPolylines(t){let e=!1;for(const i of this.metroGraphData.Metrolines)return this.InsertPointsIntoPolyline(i,t)&&(e=!0),e}InsertPointsIntoPolyline(t,e){let i=!1;for(let s=t.Polyline.startPoint;s.next!=null;s=s.next)this.InsertPointsOnPolypoint(s,e,t)&&(i=!0);return i}InsertPointsOnPolypoint(t,e,i){const s=new fe(t.point,t.next.point),n=t.point!==s.first,o=e.get(s);if(!o)return!1;const a=t.next,h=t.polyline;if(n)for(let u=o.length-1;u>=0;u--){if(this.polylineAcceptsPoint!=null&&!this.polylineAcceptsPoint(i,o[u]))continue;const d=zt.mkFromPoint(o[u]);d.prev=t,d.polyline=h,t.next=d,t=d}else for(let u=0;u<o.length;u++){if(this.polylineAcceptsPoint!=null&&!this.polylineAcceptsPoint(i,o[u]))continue;const d=zt.mkFromPoint(o[u]);d.prev=t,d.polyline=h,t.next=d,t=d}return t.next=a,a.prev=t,!0}RemoveSelfCycles(){let t=!1;for(const e of this.Polylines)lr.RemoveSelfCyclesFromPolyline(e)&&(t=!0);return t}static RemoveSelfCyclesFromPolyline(t){let e=!1;const i=new je;for(let s=t.startPoint;s!=null;s=s.next){const n=s.point,o=i.get(n);if(o){for(let a=o.next;a!==s.next;a=a.next)i.deleteP(a.point);o.next=s.next,s.next.prev=o,e=!0}else i.set(s.point,s)}return e}ReduceEdgeCrossings(){const t=new Oh(this.metroGraphData);t.Run();for(const e of t.GetChangedHubs())this.crossingsThatShouldBecomeHubs.add(e);return t.NumberOfReducedCrossings()>0}RemoveUnimportantCrossings(){let t=!1;this.pointsToDelete=uo(this.foundCrossings,this.crossingsThatShouldBecomeHubs);for(const e of this.Polylines)this.RemoveUnimportantCrossingsFromPolyline(e)&&(t=!0);return t}RemoveUnimportantCrossingsFromPolyline(t){let e=!1;for(let i=t.startPoint.next;i!=null&&i.next!=null;i=i.next)if(this.pointsToDelete.has(i.point)&&c.getTriangleOrientation(i.prev.point,i.point,i.next.point)===D.Collinear){const s=i.prev,n=i.next;s.next=n,n.prev=s,i=s,e=!0}return e}IntersectTwoEdges(t,e,i,s){const n=N.IntersectPPPP(t.first,t.second,e.first,e.second);if(n){const o=this.FindExistingVertexOrCreateNew(s,n);(this.AddVertexToSplittingList(t,i,o)||this.AddVertexToSplittingList(e,i,o))&&this.foundCrossings.add(o)}}FindExistingVertexOrCreateNew(t,e){const i=t.RootNode.FirstHitNode(e);if(i!=null)return i.UserData;const s=X.mkOnPoints([e]);return s.pad(C.intersectionEpsilon),t.Add(s,e),e}AddVertexToSplittingList(t,e,i){if(!w.closeIntersectionPoints(i,t.first)&&!w.closeIntersectionPoints(i,t.second)){let s=e.get(t);if(s||(s=new Array,e.set(t,s)),!s.find(n=>n.equal(i)))return s.push(i),!0}return!1}}class qa{isCorrectlyOrienected(){return c.getTriangleOrientation(this.Curve.boundingBox.center,this.Curve.value(this.parEnd),this.Curve.value(this.parStart))!==D.Counterclockwise}get Count(){return this.points.length}constructor(t,e,i,s){this.BelongsToRealNode=s,this.Curve=e,this.Position=i,this.points=new Array(t),this.tangents=new Array(t),this.OrientedHubSegments=new Array(t)}get CurveCenter(){return this.Curve.boundingBox.center}get OppositeBase(){return this.OutgoingBundleInfo!=null?this.OutgoingBundleInfo.TargetBase:this.IncomingBundleInfo.SourceBase}get length(){return this.points.length}get Points(){return this.points}get Tangents(){return this.tangents}get InitialMidParameter(){return this.initialMidParameter}set InitialMidParameter(t){this.initialMidParameter=t,this.InitialMidPoint=this.Curve.value(t)}get ParStart(){return this.parStart}set ParStart(t){this.parStart=t,this.StartPoint=this.Curve.value(this.parStart)}get ParEnd(){return this.parEnd}set ParEnd(t){this.parEnd=t,this.EndPoint=this.Curve.value(this.parEnd)}get ParMid(){return(this.parStart+this.parEnd)/2}get MidPoint(){return c.middle(this.StartPoint,this.EndPoint)}get Span(){return this.SpanBetweenTwoParameters(this.parStart,this.parEnd)}SpanBetweenTwoParameters(t,e){return t<=e?e-t:e-t+K(this.Curve)}RotateLeftPoint(t,e){return t===0?this.EndPoint:this.RotatePoint(t,this.parEnd,e)}RotateRigthPoint(t,e){return t===0?this.StartPoint:this.RotatePoint(t,this.parStart,e)}RotatePoint(t,e,i){const s=K(this.Curve)*i;return e+=t*s,e=this.AdjustParam(e),this.Curve.value(e)}AdjustParam(t){return t>this.Curve.parEnd?t=this.Curve.parStart+(t-this.Curve.parEnd):t<this.Curve.parStart&&(t=this.Curve.parEnd-(this.Curve.parStart-t)),t}RotateBy(t,e,i){const s=K(this.Curve)*i;t!==0&&(this.ParStart=this.AdjustParam(this.ParStart+t*s)),e!==0&&(this.ParEnd=this.AdjustParam(this.ParEnd+e*s))}RelativeOrderOfBasesIsPreserved(t,e,i){const s=K(this.Curve)*i,n=this.parStart+t*s,o=this.parStart<this.parEnd?this.parEnd+e*s:this.parEnd+K(this.Curve)+e*s;if(n>o||this.SpanBetweenTwoParameters(n,o)>K(this.Curve)/2)return!1;if(this.Prev==null||this.SpanBetweenTwoParameters(this.Prev.ParMid,this.ParMid)>s&&this.SpanBetweenTwoParameters(this.ParMid,this.Next.ParMid)>s)return!0;const a=this.RotateLeftPoint(e,i),h=this.RotateRigthPoint(t,i),u=c.middle(a,h),d=this.MidPoint;return!(c.getTriangleOrientation(this.CurveCenter,this.Prev.MidPoint,d)!=c.getTriangleOrientation(this.CurveCenter,this.Prev.MidPoint,u)||c.getTriangleOrientation(this.CurveCenter,this.Next.MidPoint,d)!=c.getTriangleOrientation(this.CurveCenter,this.Next.MidPoint,u))}}class gs{constructor(t,e,i,s){this.SourceBase=t,this.TargetBase=e,this.obstaclesToIgnore=i,this.HalfWidthArray=s,this.TotalRequiredWidth=this.HalfWidthArray.reduce((o,a)=>o+a,0)*2,this.longEnoughSideLength=t.Curve.boundingBox.addRec(e.Curve.boundingBox).diagonal;const n=Math.max(t.Curve.boundingBox.diagonal,e.Curve.boundingBox.diagonal);if(this.TotalRequiredWidth>n){const o=this.TotalRequiredWidth/n;for(let a=0;a<this.HalfWidthArray.length;a++)this.HalfWidthArray[a]/=o;this.TotalRequiredWidth/=o}}SetParamsFeasiblySymmetrically(t){this.CalculateTightObstaclesForBundle(t,this.obstaclesToIgnore),this.SetEndParamsSymmetrically()}CalculateTightObstaclesForBundle(t,e){const i=this.SourceBase.Curve.boundingBox.diagonal/2,s=this.TargetBase.Curve.boundingBox.diagonal/2,n=Oi.Create4gon(this.SourceBase.Position,this.TargetBase.Position,i*2,s*2);this.tightObstaclesInTheBoundingBox=Array.from(t.AllHitItems(n.boundingBox,o=>!e.has(o)&&w.ClosedCurveInteriorsIntersect(n,o)))}SetEndParamsSymmetrically(){const t=this.TargetBase.Position,e=this.SourceBase.Position,i=t.sub(e).normalize(),s=i.rotate90Ccw(),n=c.middle(t,e),o=i.mul(this.longEnoughSideLength),a=n.add(o),h=n.sub(o);if(this.SetRLParamsIfWidthIsFeasible(s.mul(this.TotalRequiredWidth/2),a,h)){this.SetInitialMidParams();return}let u=this.TotalRequiredWidth,d=0,m=u/2;for(;u-d>gs.FeasibleWidthEpsilon;)this.SetRLParamsIfWidthIsFeasible(s.mul(m/2),a,h)?d=m:u=m,m=.5*(u+d);m<=gs.FeasibleWidthEpsilon&&(this.SetRLParamsIfWidthIsFeasible_(s.mul(gs.FeasibleWidthEpsilon),new c(0,0),a,h)||this.SetRLParamsIfWidthIsFeasible_(new c(0,0),s.mul(-gs.FeasibleWidthEpsilon),a,h))&&(m=2*gs.FeasibleWidthEpsilon),this.SourceBase.InitialMidParameter=this.SourceBase.AdjustParam(this.SourceBase.ParStart+this.SourceBase.Span/2),this.TargetBase.InitialMidParameter=this.TargetBase.AdjustParam(this.TargetBase.ParStart+this.TargetBase.Span/2)}mkNameFromLRST(){return"./tmp/leftRight"+this.SourceBase.Position.toString()+"_"+this.TargetBase.Position.toString()+".svg"}SetRLParamsIfWidthIsFeasible(t,e,i){return this.SetRLParamsIfWidthIsFeasible_(t,t.neg(),e,i)}SetRLParamsIfWidthIsFeasible_(t,e,i,s){const n={par:0},o={par:0},a={par:0},h={par:0};let u=this.TrimSegWithBoundaryCurves(N.mkPP(i.add(t),s.add(t)),o,a);return u==null||this.tightObstaclesInTheBoundingBox.find(m=>w.intersectionOne(u,m,!1)!=null)||(u=this.TrimSegWithBoundaryCurves(N.mkPP(i.add(e),s.add(e)),h,n),u==null)||this.tightObstaclesInTheBoundingBox.find(m=>w.intersectionOne(u,m,!1)!=null)?!1:(this.SourceBase.IsParent?(this.SourceBase.ParStart=o.par,this.SourceBase.ParEnd=h.par):(this.SourceBase.ParStart=h.par,this.SourceBase.ParEnd=o.par),this.TargetBase.IsParent?(this.TargetBase.ParStart=n.par,this.TargetBase.ParEnd=a.par):(this.TargetBase.ParStart=a.par,this.TargetBase.ParEnd=n.par),!0)}SetInitialMidParams(){const t={par:0},e={par:0};this.TrimSegWithBoundaryCurves(N.mkPP(this.TargetBase.CurveCenter,this.TargetBase.CurveCenter),e,t)!=null?(this.SourceBase.InitialMidParameter=e.par,this.TargetBase.InitialMidParameter=t.par):(this.SourceBase.InitialMidParameter=this.SourceBase.AdjustParam(this.SourceBase.ParStart+this.SourceBase.Span/2),this.TargetBase.InitialMidParameter=this.TargetBase.AdjustParam(this.TargetBase.ParStart+this.TargetBase.Span/2))}mkNameFromST(){return"./tmp/mparam"+this.SourceBase.Position.toString()+"_"+this.TargetBase.Position.toString()+".svg"}TrimSegWithBoundaryCurves(t,e,i){let s=w.getAllIntersections(t,this.SourceBase.Curve,!0);if(s.length===0)return i.par=0,e.par=0,null;let n;if(s.length===1?n=s[0]:this.SourceBase.IsParent?n=s[0].par0<s[1].par0?s[1]:s[0]:n=s[0].par0<s[1].par0?s[0]:s[1],s=w.getAllIntersections(t,this.TargetBase.Curve,!0),s.length===0)return i.par=0,e.par=0,null;let o;return s.length===1?o=s[0]:this.TargetBase.IsParent?o=s[0].par0>s[1].par0?s[1]:s[0]:o=s[0].par0>s[1].par0?s[0]:s[1],e.par=n.par1,i.par=o.par1,N.mkPP(n.x,o.x)}RotateBy(t,e,i,s,n){const o=t!==0||e!==0,a=i!==0||s!==0;o&&this.SourceBase.RotateBy(t,e,n),a&&this.TargetBase.RotateBy(i,s,n),this.UpdateSourceAndTargetBases(o,a)}UpdateSourceAndTargetBases(t,e){t&&this.UpdatePointsOnBundleBase(this.SourceBase),e&&this.UpdatePointsOnBundleBase(this.TargetBase),this.UpdateTangentsOnBases()}UpdateTangentsOnBases(){const t=this.TargetBase.length;for(let e=0;e<t;e++){let i=this.TargetBase.Points[e].sub(this.SourceBase.Points[t-1-e]);const s=i.length;s>=C.tolerance&&(i=i.div(s),this.TargetBase.Tangents[e]=i,this.SourceBase.Tangents[t-1-e]=i.neg())}}UpdatePointsOnBundleBase(t){const e=t.length,i=t.Points,s=N.mkPP(t.EndPoint,t.StartPoint),n=1/this.TotalRequiredWidth;let o=this.HalfWidthArray[0];i[0]=s.value(o*n);for(let a=1;a<e;a++)o+=this.HalfWidthArray[a-1]+this.HalfWidthArray[a],i[a]=s.value(o*n)}RotationIsLegal(t,e,i,s,n){if(!this.SourceBase.IsParent&&!this.TargetBase.IsParent){if(e!==0||i!==0){const o=this.SourceBase.RotateLeftPoint(e,n),a=this.TargetBase.RotateRigthPoint(i,n);if(!this.LineIsLegal(o,a))return!1}if(t!==0||s!==0){const o=this.SourceBase.RotateRigthPoint(t,n),a=this.TargetBase.RotateLeftPoint(s,n);if(!this.LineIsLegal(o,a))return!1}}else{if(e!==0||s!==0){const o=this.SourceBase.RotateLeftPoint(e,n),a=this.TargetBase.RotateLeftPoint(s,n);if(!this.LineIsLegal(o,a))return!1}if(t!==0||i!==0){const o=this.SourceBase.RotateRigthPoint(t,n),a=this.TargetBase.RotateRigthPoint(i,n);if(!this.LineIsLegal(o,a))return!1}}return!((t!==0||e!==0)&&!this.SourceBase.RelativeOrderOfBasesIsPreserved(t,e,n)||(i!==0||s!==0)&&!this.TargetBase.RelativeOrderOfBasesIsPreserved(i,s,n))}LineIsLegal(t,e){return this.tightObstaclesInTheBoundingBox.find(i=>w.intersectionOne(N.mkPP(t,e),i,!1)!=null)==null}}gs.FeasibleWidthEpsilon=.1;class za{get Segment(){return this.segment}set Segment(t){this.segment=t}constructor(t,e,i,s){this.Segment=t,this.Reversed=e,this.Index=i,this.BundleBase=s}value(t){return this.Reversed?this.Segment.value(this.Segment.parEnd-t):this.Segment.value(t)}}class St{constructor(t,e,i){this.fixedBundles=new Set,this.stepsWithProgress=0,this.metroOrdering=t,this.metroGraphData=e,this.bundlingSettings=i}Run(){this.AllocateBundleBases(),this.SetBasesRightLeftParamsToTheMiddles(),this.bundlingSettings.KeepOverlaps?(this.UpdateSourceAndTargetBases(),this.CreateOrientedSegs()):(this.SetRightLeftParamsFeasiblySymmetrically(),this.AdjustStartEndParamsToAvoidBaseOverlaps(),this.UpdateSourceAndTargetBases(),this.CreateOrientedSegs(),this.bundlingSettings.RotateBundles&&this.RotateBundlesToDiminishCost(),this.AdjustStartEndParamsToAvoidBaseOverlaps(),this.UpdateSourceAndTargetBases())}AllocateBundleBases(){this.externalBases=new Map,this.internalBases=new Map,this.Bundles=new Array;for(const t of this.metroGraphData.Stations)t.BoundaryCurve==null&&(t.BoundaryCurve=yt.mkCircle(t.Radius,t.Position));for(const t of this.metroGraphData.Stations)for(const e of t.Neighbors)if(t.SerialNumber<e.SerialNumber){const i=new qa(this.metroGraphData.RealEdgeCount(t,e),t.BoundaryCurve,t.Position,t.IsReal);t.BundleBases.set(e,i);const s=new qa(this.metroGraphData.RealEdgeCount(t,e),e.BoundaryCurve,e.Position,e.IsReal);e.BundleBases.set(t,s),w.PointRelativeToCurveLocation(e.Position,t.BoundaryCurve)!==at.Outside?(i.IsParent=!0,Gi(this.internalBases,t,i),Gi(this.externalBases,e,s)):w.PointRelativeToCurveLocation(t.Position,e.BoundaryCurve)!==at.Outside?(s.IsParent=!0,Gi(this.externalBases,t,i),Gi(this.internalBases,e,s)):(Gi(this.externalBases,t,i),Gi(this.externalBases,e,s));const n=this.metroGraphData.tightIntersections.ObstaclesToIgnoreForBundle(t,e),o=new gs(i,s,n,Array.from(this.metroOrdering.GetOrder(t,e)).map(a=>a.Width/2));i.OutgoingBundleInfo=s.IncomingBundleInfo=o,this.Bundles.push(o)}this.SetBundleBaseNeighbors()}SetBundleBaseNeighbors(){for(const t of this.externalBases.keys()){const e=this.externalBases.get(t);this.SortBundlesCounterClockwise(e),this.SetLeftRightBases(e)}for(const t of this.internalBases.keys()){const e=this.internalBases.get(t);this.SortBundlesCounterClockwise(e),this.SetLeftRightBases(e)}}SortBundlesCounterClockwise(t){if(t.length>2){const e=t[0].OppositeBase.Position,i=t[0].CurveCenter;t.sort((s,n)=>zs(e.sub(i),s.OppositeBase.Position.sub(i),n.OppositeBase.Position.sub(i)))}}SetLeftRightBases(t){const e=t.length;if(!(e<=1))for(let i=0;i<e;i++)t[i].Prev=t[(i-1+e)%e],t[i].Next=t[(i+1)%e]}CreateOrientedSegs(){for(const t of this.metroGraphData.Metrolines)this.CreateOrientedSegsOnLine(t)}CreateOrientedSegsOnLine(t){for(let e=t.Polyline.startPoint.next;e.next!=null;e=e.next)this.CreateOrientedSegsOnLineVertex(t,e)}CreateOrientedSegsOnLineVertex(t,e){const i=this.metroGraphData.PointToStations.get(e.prev.point),s=this.metroGraphData.PointToStations.get(e.point),n=this.metroGraphData.PointToStations.get(e.next.point),o=s.BundleBases.get(i),a=s.BundleBases.get(n),h=this.metroOrdering.GetLineIndexInOrder(i,s,t),u=this.metroOrdering.GetLineIndexInOrder(n,s,t),d=o.OrientedHubSegments[h]=new za(null,!1,h,o),m=a.OrientedHubSegments[u]=new za(null,!0,u,a);m.Other=d,d.Other=m}UpdateSourceAndTargetBases(){for(const t of this.Bundles)t.UpdateSourceAndTargetBases(!0,!0)}SetBasesRightLeftParamsToTheMiddles(){for(const t of this.Bundles){const e=t.SourceBase,i=t.TargetBase;e.ParEnd=e.ParStart=this.GetBaseMiddleParamInDirection(e,e.Position,i.Position),i.ParEnd=i.ParStart=this.GetBaseMiddleParamInDirection(i,i.Position,e.Position)}}GetBaseMiddleParamInDirection(t,e,i){const s=t.Curve;if(s instanceof yt){const a=s;if(a.isArc())return c.angle(a.aAxis,i.sub(e))}const o=w.getAllIntersections(s,N.mkPP(e,i),!0);for(const a of o){const h=a.x;if(h.sub(e).dot(h.sub(i))<=0)return a.par0}throw new Error}SetRightLeftParamsFeasiblySymmetrically(){for(const t of this.Bundles)t.SetParamsFeasiblySymmetrically(this.metroGraphData.TightTree)}AdjustStartEndParamsToAvoidBaseOverlaps(){for(const t of this.externalBases.values())this.AdjustCurrentBundleWidthsOnCurve(t);for(const t of this.internalBases.values())this.AdjustCurrentBundleWidthsOnCurve(t)}AdjustCurrentBundleWidthsOnCurve(t){const e=t.length;if(!(e<=1))for(let i=0;i<e;i++){const s=t[i],n=s.Next;this.ShrinkBasesToMakeTwoConsecutiveNeighborsHappy(s,n)}}ShrinkBasesToMakeTwoConsecutiveNeighborsHappy(t,e){const i=Fh(t,e);if(i==null||R(i.start,i.end))return;const s=i.rbaseMiddle,n=i.lbaseMiddle;if(s<n){const u=t;t=e,e=u}const o=t.Span,a=e.Span,h=(i.end*o+i.start*a)/(a+o);t.ParStart=t.AdjustParam(h+C.distanceEpsilon),e.ParEnd=e.AdjustParam(h-C.distanceEpsilon)}RegularCut(t,e,i,s,n,o){let a=(n*s+o*t)/(n+o);const h=Math.min(e,s),u=Math.max(t,i);return a<u&&(a=u),a>h&&(a=h),a}RotateBundlesToDiminishCost(){let t=St.MaxParameterChange;const e={cost:this.Cost()};let i=0;for(;i++<St.MaxIterations;){const s=e.cost;if(this.RotateBundlesToDiminishCostOneIteration(t,e),t=this.UpdateParameterChange(t,s,e.cost),t<St.MinParameterChange)break}}UpdateParameterChange(t,e,i){return i+1<e?(this.stepsWithProgress++,this.stepsWithProgress>=5&&(this.stepsWithProgress=0,this.fixedBundles.clear())):(this.stepsWithProgress=0,t*=.8,this.fixedBundles.clear()),t}RotateBundlesToDiminishCostOneIteration(t,e){let i=!1;for(const s of this.Bundles)this.fixedBundles.has(s)||(this.OptimizeBundle(s,t,e)?i=!0:this.fixedBundles.add(s));return i}OptimizeBundle(t,e,i){const s=this.CostBi(t);if(s<St.CostThreshold)return!1;let n=0,o=-1,a=-1;for(let h=0;h<St.Deltas.length-1;h++){let u=this.DeltaWithChangedAngles(St.Deltas[h][0],St.Deltas[h][1],0,0,t,s,e);u>St.CostDeltaThreshold&&u>n&&(a=h,o=St.Deltas.length-1,n=u),u=this.DeltaWithChangedAngles(0,0,St.Deltas[h][0],St.Deltas[h][1],t,s,e),u>St.CostDeltaThreshold&&u>n&&(a=St.Deltas.length-1,o=h,n=u)}return n<St.CostDeltaThreshold?!1:(i.cost-=n,t.RotateBy(St.Deltas[a][0],St.Deltas[a][1],St.Deltas[o][0],St.Deltas[o][1],e),!0)}DeltaWithChangedAngles(t,e,i,s,n,o,a){if(!n.RotationIsLegal(t,e,i,s,a))return 0;n.RotateBy(t,e,i,s,a);const h=this.CostBN(n,o);return n.RotateBy(t*-1,e*-1,i*-1,s*-1,a),o-h}CostBi(t){return St.SeparationCoeff*this.SeparationCost(t)+(St.SqueezeCoeff*this.SqueezeCost(t)+(St.AssymetryCoeff*this.AssymetryCost(t)+St.CenterCoeff*this.CenterCostBi(t)))}CostBN(t,e){let i=0;return i=i+St.CenterCoeff*this.CenterCostBi(t),i>e||(i=i+St.SeparationCoeff*this.SeparationCost(t),i>e)||(i=i+St.SqueezeCoeff*this.SqueezeCost(t),i>e)||(i=i+St.AssymetryCoeff*this.AssymetryCost(t)),i}SqueezeCost(t){const i=t.TargetBase.MidPoint.sub(t.SourceBase.MidPoint).normalize().rotate90Ccw(),s=Math.abs(t.SourceBase.StartPoint.sub(t.SourceBase.EndPoint).dot(i)),n=Math.abs(t.TargetBase.StartPoint.sub(t.TargetBase.EndPoint).dot(i)),o=Math.abs(t.TotalRequiredWidth-s)/t.TotalRequiredWidth,a=Math.abs(t.TotalRequiredWidth-n)/t.TotalRequiredWidth,h=Math.abs(s-n)/t.TotalRequiredWidth;return Math.exp(o*10)-1+(Math.exp(a*10)-1)+h}CenterCostBi(t){return!t.SourceBase.BelongsToRealNode&&!t.TargetBase.BelongsToRealNode?0:this.CenterCostBb(t.SourceBase)+this.CenterCostBb(t.TargetBase)}CenterCostBb(t){if(!t.BelongsToRealNode)return 0;const e=t.ParMid,i=Math.min(t.InitialMidParameter,e),s=Math.max(t.InitialMidParameter,e),n=Math.min(s-i,i+(K(t.Curve)-s));return t.CurveCenter.equal(t.Position)||t.IsParent?25*(n*n):500*(n*n)}AssymetryCost(t){return this.GetAssymetryCostForBase(t.SourceBase)+this.GetAssymetryCostForBase(t.TargetBase)}GetAssymetryCostForBase(t){if(t.BelongsToRealNode)return 0;const e=t.OppositeBase.BelongsToRealNode?200:500;let i=0;for(const s of t.OrientedHubSegments){const n=s.Index,o=s.Other.Index,a=t.Points[n],h=t.Tangents[n],u=s.Other.BundleBase,d=u.Points[o],m=u.Tangents[o],y=t.Count+u.Count;i+=this.GetAssymetryCostOnData(a,h,d,m,e)/y}return i}GetAssymetryCostOnData(t,e,i,s,n){const o=t.sub(i),a=o.length;if(a<C.distanceEpsilon)return 0;const h=e.add(s).dot(o),u=c.crossProduct(o,e),d=c.crossProduct(o,s),m=u-d,y=h*h+m*m,E=u*u+d*d;return 10*y+n*E}SeparationCost(t){return this.SeparationCostForBundleBase(t.SourceBase)+this.SeparationCostForBundleBase(t.TargetBase)}SeparationCostForBundleBase(t){return t.Prev==null?0:this.SeparationCostForAdjacentBundleBases(t,t.Prev)+this.SeparationCostForAdjacentBundleBases(t,t.Next)}SeparationCostForAdjacentBundleBases(t,e){const i=t.Curve,s=this.IntervalsOverlapLength(t.ParStart,t.ParEnd,e.ParStart,e.ParEnd,i),n=Math.min(t.Span,e.Span);return Math.exp(s/(n*10))-1}IntervalsOverlapLength(t,e,i,s,n){const o=n.parStart,a=n.parEnd;return t<e?i<s?this.IntersectRegularIntervals(t,e,i,s):this.IntersectRegularIntervals(t,e,i,a)+this.IntersectRegularIntervals(t,e,o,s):i<s?this.IntersectRegularIntervals(t,a,i,s)+this.IntersectRegularIntervals(o,e,i,s):this.IntersectRegularIntervals(t,a,i,a)+this.IntersectRegularIntervals(o,e,o,s)}IntersectRegularIntervals(t,e,i,s){const n=Math.max(t,i),o=Math.min(e,s);return n<o?o-n:0}Cost(){let t=0;for(const e of this.Bundles){const i=St.SeparationCoeff*this.SeparationCost(e),s=St.AssymetryCoeff*this.AssymetryCost(e),n=St.SqueezeCoeff*this.SqueezeCost(e),o=St.CenterCoeff*this.CenterCostBi(e);t+=(i+s)/2+n+o}return t}}St.Deltas=[[1,-1],[1,-1]],St.SeparationCoeff=1,St.SqueezeCoeff=1,St.CenterCoeff=10,St.AssymetryCoeff=1,St.MaxIterations=200,St.MaxParameterChange=8/360,St.MinParameterChange=.1/360,St.CostThreshold=1e-5,St.CostDeltaThreshold=.01;function Fh(l,t){const e=K(l.Curve);let i=l.ParEnd,s=l.ParStart<l.ParEnd?l.ParStart:l.ParStart-e,n=t.ParEnd,o=t.ParStart<t.ParEnd?t.ParStart:t.ParStart-e;i>n?i-o>e&&(o+=e,n+=e):n-s>e&&(s+=e,i+=e);const a=Math.min(i,n),h=Math.max(s,o);return h<=a?{start:h,end:a,rbaseMiddle:(s+i)/2,lbaseMiddle:(o+n)/2}:null}class Dh{constructor(){this.Metrolines=new Array}Add(t){this.Metrolines.push(t)}}class _r{constructor(t){this.Metrolines=t,this.BuildOrder()}*GetOrder(t,e){const i=new fe(t.Position,e.Position),s=this.bundles.get(i).Metrolines;if(t.Position===i.first)for(let n=0;n<s.length;n++)yield s[n];else for(let n=s.length-1;n>=0;n--)yield s[n]}GetLineIndexInOrder(t,e,i){const s=new fe(t.Position,e.Position),n=t.Position!==s.first,o=this.bundles.get(s).LineIndexInOrder;return n?o.size-1-o.get(i):o.get(i)}BuildOrder(){this.bundles=new ls;for(const t of this.Metrolines)for(let e=t.Polyline.startPoint;e.next!=null;e=e.next){const i=new fe(e.point,e.next.point);let s=this.bundles.get(i);s||this.bundles.set(i,s=new Dh),s.Add(t)}for(const t of this.bundles)this.BuildOrderPP(t[0],t[1])}BuildOrderPP(t,e){if(!e.orderFixed){e.Metrolines.sort((i,s)=>this.CompareLines(i,s,t.first,t.second)),e.orderFixed=!0,e.LineIndexInOrder=new Map;for(let i=0;i<e.Metrolines.length;i++)e.LineIndexInOrder.set(e.Metrolines[i],i)}}CompareLines(t,e,i,s){const n={polyPoint:null,next:null,prev:null};this.FindStationOnLine(i,s,t,n);const o=n.polyPoint,a=n.next,h=n.prev;this.FindStationOnLine(i,s,e,n);const u=n.polyPoint,d=n.next,m=n.prev;let y=o,E=u,T,B;for(;(B=h(y))!=null&&(T=m(E))!=null&&B.point.equal(T.point);){const H=new fe(B.point,y.point);if(this.bundles.get(H).orderFixed)return this.CompareOnFixedOrder(H,t,e,!B.point.equal(H.first));y=B,E=T}if(B!=null&&T!=null){const H=y.point;return-_r.IsLeft(a(y).point.sub(H),B.point.sub(H),T.point.sub(H))}for(y=o,E=u;(B=a(y))!=null&&(T=d(E))!=null&&B.point.equal(T.point);){const H=new fe(B.point,y.point);if(this.bundles.get(H).orderFixed)return this.CompareOnFixedOrder(H,t,e,!y.point.equal(H.first));y=B,E=T}if(B!=null&&T!=null){const H=y.point;return _r.IsLeft(h(y).point.sub(H),B.point.sub(H),T.point.sub(H))}return k(t.Index,e.Index)}CompareOnFixedOrder(t,e,i,s){const n=this.bundles.get(t).LineIndexInOrder;return(s?-1:1)*k(n.get(e),n.get(i))}FindStationOnLine(t,e,i,s){for(let n=i.Polyline.startPoint;n.next!=null;n=n.next){if(n.point.equal(t)&&n.next.point.equal(e)){s.next=o=>o.next,s.prev=o=>o.prev,s.polyPoint=n;return}if(n.point.equal(e)&&n.next.point.equal(t)){s.next=o=>o.prev,s.prev=o=>o.next,s.polyPoint=n.next;return}}throw new Error}static IsLeft(t,e,i){return zs(t,e,i)}}class Ot extends Ft{constructor(t,e){super(null),this.metroGraphData=t,this.bundlingSettings=e}run(){this.CreateMetroOrdering(),this.InitRadii(),this.FinalizePaths()}InitRadii(){new Fe(this.metroGraphData,this.bundlingSettings).CreateNodeRadii()}CreateMetroOrdering(){this.metroOrdering=new _r(this.metroGraphData.Metrolines)}FinalizePaths(){this.CreateBundleBases(),this.CreateSegmentsInsideHubs(),this.CreateCurves()}CreateBundleBases(){new St(this.metroOrdering,this.metroGraphData,this.bundlingSettings).Run()}CreateCurves(){for(let t=0;t<this.metroGraphData.Metrolines.length;t++)this.CreateCurveLine(this.metroGraphData.Metrolines[t],this.metroGraphData.Edges[t])}CreateCurveLine(t,e){const i=new w;let n=Ot.FindCurveStart(this.metroGraphData,this.metroOrdering,t);const o=Ot.HubSegsOfLine(this.metroGraphData,this.metroOrdering,t);for(const a of o)a!=null&&(i.addSegment(N.mkPP(n,a.start)),i.addSegment(a),n=a.end);i.addSegment(N.mkPP(n,Ot.FindCurveEnd(this.metroGraphData,this.metroOrdering,t))),e.curve=i}static FindCurveStart(t,e,i){const s=t.PointToStations.get(i.Polyline.startPoint.point),n=t.PointToStations.get(i.Polyline.startPoint.next.point),o=s.BundleBases.get(n),a=o.IsParent?e.GetLineIndexInOrder(s,n,i):e.GetLineIndexInOrder(n,s,i);return o.Points[a]}static FindCurveEnd(t,e,i){const s=t.PointToStations.get(i.Polyline.endPoint.prev.point),n=t.PointToStations.get(i.Polyline.endPoint.point),o=n.BundleBases.get(s),a=o.IsParent?e.GetLineIndexInOrder(n,s,i):e.GetLineIndexInOrder(s,n,i);return o.Points[a]}static*HubSegsOfLine(t,e,i){for(let s=i.Polyline.startPoint.next;s.next!=null;s=s.next)yield Ot.SegOnLineVertex(t,e,i,s)}static SegOnLineVertex(t,e,i,s){const n=t.PointToStations.get(s.prev.point),o=t.PointToStations.get(s.point),a=o.BundleBases.get(n),h=e.GetLineIndexInOrder(n,o,i);if(a.OrientedHubSegments[h]==null||a.OrientedHubSegments[h].Segment==null){const u=t.PointToStations.get(s.next.point),d=o.BundleBases.get(u),m=e.GetLineIndexInOrder(u,o,i);return N.mkPP(a.Points[h],d.Points[m])}return a.OrientedHubSegments[h].Segment}CreateSegmentsInsideHubs(){for(const t of this.metroGraphData.Metrolines)this.CreateOrientedSegsOnLine(t);this.bundlingSettings.UseCubicBezierSegmentsInsideOfHubs&&this.FanBezierSegs()}CreateOrientedSegsOnLine(t){for(let e=t.Polyline.startPoint.next;e.next!=null;e=e.next)this.CreateICurveForOrientedSeg(t,e)}CreateICurveForOrientedSeg(t,e){const i=this.metroGraphData.PointToStations.get(e.prev.point),s=this.metroGraphData.PointToStations.get(e.point),n=this.metroGraphData.PointToStations.get(e.next.point),o=s.BundleBases.get(i),a=s.BundleBases.get(n),h=this.metroOrdering.GetLineIndexInOrder(i,s,t),u=this.metroOrdering.GetLineIndexInOrder(n,s,t),d=this.bundlingSettings.UseCubicBezierSegmentsInsideOfHubs?Ot.StandardBezier(o.Points[h],o.Tangents[h],a.Points[u],a.Tangents[u]):Ot.BiArc(o.Points[h],o.Tangents[h],a.Points[u],a.Tangents[u]);o.OrientedHubSegments[h].Segment=d,a.OrientedHubSegments[u].Segment=d}static ShowHubs(t,e,i,s,n=[]){let o=Ot.GetAllDebugCurves(e,t);i!=null&&o.push(wt.mkDebugCurveTWCI(255,1,"red",W.mkDiamond(5,25,i.Position))),o=o.concat(n)}static GetAllDebugCurves(t,e){return Ot.GraphNodes(e).concat(Ot.VertexDebugCurves(t,e)).concat(Ot.DebugEdges(e))}static DebugEdges(t){return t.Edges.map(e=>wt.mkDebugCurveTWCI(40,.1,"gray",e.curve))}static VertexDebugCurves(t,e){return Ot.DebugCircles(e).concat(Ot.DebugHubBases(e)).concat(Ot.DebugSegs(e)).concat(Ot.BetweenHubs(t,e))}static BetweenHubs(t,e){const i=[];for(const s of e.Metrolines){const n=Ot.GetInterestingSegs(e,t,s),o=Ot.GetMonotoneColor(s.Polyline.start,s.Polyline.end,n);for(const a of n)i.push(wt.mkDebugCurveTWCI(100,s.Width,o,N.mkPP(a[0],a[1])))}return i}static GetInterestingSegs(t,e,i){const s=new Array;if(t.Stations.length===0||t.Stations[0].BundleBases==null||t.Stations[0].BundleBases.size===0)return[];let n=Ot.FindCurveStart(t,e,i);const o=Ot.HubSegsOfLine(t,e,i);for(const a of o)a!=null&&(s.push([n,a.start]),n=a.end);return s.push([n,Ot.FindCurveEnd(t,e,i)]),s}static GetMonotoneColor(t,e,i){return"green"}static DebugHubBases(t){const e=new Array;for(const i of t.Stations)for(const s of i.BundleBases.values())e.push(wt.mkDebugCurveTWCI(100,1,"red",N.mkPP(s.EndPoint,s.StartPoint)));return e}static DebugCircles(t){return t.Stations.map(e=>wt.mkDebugCurveTWCI(100,.1,"blue",W.mkCircle(e.Radius,e.Position)))}static DebugSegs(t){const e=new Array;for(const i of t.VirtualStations())for(const s of i.BundleBases.values())for(const n of s.OrientedHubSegments)if(n!=null)if(n.Segment==null){const o=n.Other.BundleBase,a=n.Index,h=n.Other.Index;e.push(N.mkPP(s.Points[a],o.Points[h]))}else e.push(n.Segment);return e.map(i=>wt.mkDebugCurveTWCI(100,.01,"green",i))}static GraphNodes(t){return t.Edges.map(i=>i.sourcePort.Curve).concat(t.Edges.map(i=>i.targetPort.Curve)).map(i=>wt.mkDebugCurveTWCI(40,1,"black",i))}static BiArc(t,e,i,s){const n=t.sub(i);if(n.length<C.distanceEpsilon)return null;const o=n.dot(e.sub(s)),a=-e.dot(s);if(e.dot(i.sub(t))<=0&&e.dot(s)<=0)return Ot.StandardBezier(t,e,i,s);const h=2*(a-1),u=2*o,d=n.dot(n);let m;if(Math.abs(h)<C.distanceEpsilon)if(Math.abs(u)>C.distanceEpsilon)m=-d/u;else return null;else{let lt=u*u-4*h*d;lt<0&&(lt=0),lt=Math.sqrt(lt),m=(-u+lt)/(2*h),m<0&&(m=(-u-lt)/(2*h))}const y=t.add(e.mul(m)),E=i.add(s.mul(m)),T=c.middle(y,E),B=c.getTriangleOrientation(t,y,T),H=c.getTriangleOrientation(T,E,i);if(B!==H)return Ot.StandardBezier(t,e,i,s);const tt=new w;return tt.addSegs([Ot.ArcOn(t,y,T),Ot.ArcOn(T,E,i)]),tt}static ArcOn(t,e,i){const s={center:null};if(Math.abs(c.signedDoubledTriangleArea(t,e,i))<1e-4||!Ot.FindArcCenter(t,e,i,s))return N.mkPP(t,i);const n=s.center,o=_(t,n);if(_(t,e)/o<1e-4)return N.mkPP(t,i);const h=t.sub(n);let u=Math.atan2(h.y,h.x);const d=i.sub(n);let m=Math.atan2(d.y,d.x),y=m-u;if(y<0&&(y+=2*Math.PI,m+=2*Math.PI),y<=Math.PI)return new yt(u,m,new c(o,0),new c(0,o),n);for(m>2*Math.PI&&(m-=2*Math.PI),u=Math.PI-u,m=Math.PI-m,u<0&&(u+=2*Math.PI);m<u;)m+=2*Math.PI;return y=m-u,new yt(u,m,new c(-o,0),new c(0,o),n)}static FindArcCenter(t,e,i,s){const n=e.sub(t).rotate90Cw(),o=e.sub(i).rotate90Cw();return s.center=c.lineLineIntersection(t,t.add(n),i,i.add(o)),s.center!=null}static StandardBezier(t,e,i,s){const n=_(t,i)/4;return xt.mkBezier([t,t.add(e.mul(n)),i.add(s.mul(n)),i])}FanBezierSegs(){let t=!0;const e=5;let i=0;for(;t&&i++<e;){t=!1;for(const s of this.metroGraphData.Stations)for(const n of s.BundleBases.values())t||(t=this.FanEdgesOfHubSegment(n))}}FanEdgesOfHubSegment(t){let e=!1;for(let i=0;i<t.Count-1;i++)e||(e=this.FanCouple(t,i,t.CurveCenter,t.Curve.boundingBox.diagonal/2));return e}FanCouple(t,e,i,s){const n=t.OrientedHubSegments[e],o=t.OrientedHubSegments[e+1];if(n==null||Js(n.Segment.start,n.Segment.end,o.Segment.start,o.Segment.end)||c.getTriangleOrientation(n.value(0),n.value(.5),n.value(1))!=c.getTriangleOrientation(o.value(0),o.value(.5),o.value(1)))return!1;const h=this.BaseLength(n),u=this.BaseLength(o);return Math.abs(h-u)<C.intersectionEpsilon?!1:h>u?this.AdjustLongerSeg(n,o,i,s):this.AdjustLongerSeg(o,n,i,s)}AdjustLongerSeg(t,e,i,s){const n=t.value(0).sub(e.value(0)),o=t.value(1).sub(e.value(1)),a=Math.min(n.length,o.length),h=e.value(.5),u=Math.max(n.length,o.length);return this.NicelyAligned(t.Segment,n,o,h,a,u)===0?!1:this.FitLonger(t,n,o,h,a,u,i,s)}FitLonger(t,e,i,s,n,o,a,h){let u=t.Segment;const d=u.start,m=u.end;let y=0;const E=10;let T=u.start.mul(1-Ot.SqueezeBound).add(u.B(1).mul(Ot.SqueezeBound)),B=u.end.mul(1-Ot.SqueezeBound).add(u.B(2).mul(Ot.SqueezeBound)),H=u.B(1).mul(2).sub(u.start),tt=u.B(2).mul(2).sub(u.end);const lt={highP:H};this.PullControlPointToTheCircle(u.start,lt,a,h),H=lt.highP;let Q=this.NicelyAligned(u,e,i,s,n,o);do{if(Q===-1){const dt=c.middle(u.B(1),T),It=c.middle(u.B(2),B);H=u.B(1),tt=u.B(2),u=new xt(d,dt,It,m)}else{const dt=c.middle(u.B(1),H),It=(u.B(2),tt);T=u.B(1),B=u.B(2),u=new xt(d,dt,It,m)}if((Q=this.NicelyAligned(u,e,i,s,n,o))===0)return t.Segment=u,t.Other.Segment=u,!0;if(y++>E)return!1}while(!0)}PullControlPointToTheCircle(t,e,i,s){const n=c.ProjectionToLine(t,e.highP,i),o=Math.sqrt(s*s-n.sub(i).lengthSquared),a=e.highP.sub(n),h=a.length;h>o&&(e.highP=n.add(a.mul(o/h)))}NicelyAligned(t,e,i,s,n,o){const h=t.value(.5).sub(s),u=h.length;return e.dot(h)<0||i.dot(h)<0||u<n-.001?1:u>o+.001?-1:0}BaseLength(t){return t.value(0).sub(t.value(1)).lengthSquared}}Ot.SqueezeBound=.2;class de{static FixRouting(t,e){return this.FixRoutingMBP(t,e,null)}static FixRoutingMBP(t,e,i){return new de(t,e).FixRoutingP(i)}constructor(t,e){this.stepsWithProgress=0,this.metroGraphData=t,this.bundlingSettings=e,this.costCalculator=new ne(this.metroGraphData,this.bundlingSettings),this.cache=new Jr(this.metroGraphData,this.bundlingSettings,this.costCalculator,this.metroGraphData.cdt)}FixRoutingP(t){this.stationsForOptimizations=this.GetStationsForOptimizations(t),this.cache.InitializeCostCache();let e=de.MaxStep,i=Number.POSITIVE_INFINITY,s=this.metroGraphData.VirtualStations().map(o=>o.Position),n=0;for(;n++<de.MaxIterations;){const o=this.TryMoveStations();if(n<=1&&!o)return!1;if(!o)break;const a=i;i=ne.Cost(this.metroGraphData,this.bundlingSettings),e=this.UpdateMaxStep(e,a,i);const h=s;if(s=this.metroGraphData.VirtualStations().map(u=>u.Position),e<de.MinStep||this.Converged(e,h,s))break}return!0}static stationsArePositionedCorrectly(t){for(const e of t.VirtualEdges())if(!this.edgeIsPositionedCorrectly(e,t))return!1;return!0}static edgeIsPositionedCorrectly(t,e){const i=t[0],s=t[1],n=e.looseIntersections.ObstaclesToIgnoreForBundle(i,s),o=N.mkPP(i.Position,s.Position),a=Array.from(e.looseIntersections.obstacleTree.GetNodeItemsIntersectingRectangle(o.boundingBox)).filter(h=>!n.has(h)).filter(h=>w.CurvesIntersect(o,h));return a.length>0?(Ot.ShowHubs(e,null,null,"./tmp/badcross.svg",[wt.mkDebugCurveTWCI(200,1,"Brown",o),wt.mkDebugCurveTWCI(200,1,"Red",W.mkCircle(2,i.Position)),wt.mkDebugCurveTWCI(200,1,"Blue",W.mkCircle(5,s.Position)),wt.mkDebugCurveTWCI(100,1,"Blue",W.mkCircle(5,s.Position))].concat(a.map(h=>wt.mkDebugCurveTWCI(100,1,"Pink",h)))),!1):!0}GetStationsForOptimizations(t){if(t==null)return new Set(this.metroGraphData.VirtualStations());{const e=new Set;for(const i of t){const s=this.metroGraphData.PointToStations.get(i);s&&!s.IsReal&&e.add(s)}return e}}Converged(t,e,i){let s=0,n=0;for(let a=0;a<e.length;a++)n+=e[a].sub(i[a]).lengthSquared,s+=e[a].lengthSquared;return Math.sqrt(n/s)<de.MinRelativeChange}UpdateMaxStep(t,e,i){return i+1<e?(this.stepsWithProgress++,this.stepsWithProgress>=5&&(this.stepsWithProgress=0,t=Math.min(de.MaxStep,t/.8))):(this.stepsWithProgress=0,t*=.8),t}TryMoveStations(){let t=!1;const e=new Set;for(const i of this.stationsForOptimizations)if(this.TryMoveStation(i)){t=!0,e.add(i);for(const s of i.Neighbors)s.IsReal||e.add(s)}return this.stationsForOptimizations=e,t}TryMoveStation(t){let e=this.BuildDirection(t);if(e.length===0)return!1;let i=this.BuildStepLength(t,e);if(i<de.MinStep&&(e=Rh(),i=this.BuildStepLength(t,e),i<de.MinStep))return!1;const s=e.mul(i),n=t.Position.add(s);return this.metroGraphData.PointToStations.has(n)||!this.moveIsLegalForAdjacentBundles(t,n)?!1:(this.metroGraphData.MoveNode(t,n),this.cache.UpdateCostCache(t),!0)}moveIsLegalForAdjacentBundles(t,e){for(const i of this.metroGraphData.looseIntersections.obstacleTree.AllHitItems(X.mkOnPoints([e]),s=>w.PointRelativeToCurveLocation(e,s)!==at.Outside))if(t.getELP().has(i)===!1)return!1;for(const i of t.Neighbors){const s=this.metroGraphData.looseIntersections.ObstaclesToIgnoreForBundle(i,t);if(!this.metroGraphData.cdtIntersections.EdgeIsLegal_(i.Position,e,i.cdtTriangle,s))return!1}return!0}BuildDirection(t){const e=this.BuildForceForInk(t),i=this.BuildForceForPathLengths(t),s=this.BuildForceForRadius(t),n=this.BuildForceForBundle(t),o=e.add(i.add(s.add(n)));return o.length<.1?new c(0,0):o.normalize()}BuildStepLength(t,e){let i=de.MinStep,s=this.CostGain(t,t.Position.add(e.mul(i)));if(s<.01)return 0;for(;2*i<=de.MaxStep;){const n=this.CostGain(t,t.Position.add(e.mul(i*2)));if(n<=s)break;i*=2,s=n}return i}CostGain(t,e){const s=this.costCalculator.RadiusGain(t,e);if(s<-12345678)return-12345678;const n=this.costCalculator.BundleGain(t,e);if(n<-12345678)return-12345678;const o=this.costCalculator.InkGain(t,e),a=this.costCalculator.PathLengthsGain(t,e);return s+o+a+n}BuildForceForInk(t){let e=new c(0,0);for(const s of t.Neighbors){const n=s.Position.sub(t.Position);e=e.add(n.normalize())}return e.mul(this.bundlingSettings.InkImportance)}BuildForceForPathLengths(t){let e=new c(0,0);for(const s of this.metroGraphData.MetroNodeInfosOfNode(t)){const n=s.Metroline,o=s.PolyPoint.next.point,a=s.PolyPoint.prev.point,h=o.sub(t.Position),u=a.sub(t.Position);e=e.add(h.div(h.length*n.IdealLength)),e=e.add(u.div(u.length*n.IdealLength))}return e.mul(this.bundlingSettings.PathLengthImportance)}BuildForceForRadius(t){let e=new c(0,0);const i=t.cachedIdealRadius,s={touchedObstacles:[]};if(!this.metroGraphData.looseIntersections.HubAvoidsObstaclesSPNBA(t,t.Position,i,s))throw Ot.ShowHubs(this.metroGraphData,null,t,"./tmp/hubs.svg",[wt.mkDebugCurveTWCI(255,1,"Brown",Oi.containingPoly),wt.mkDebugCurveTWCI(100,1,"Blue",W.mkCircle(i,t.Position))]),new Error;for(const a of s.touchedObstacles){const u=2*(1-a[1].sub(t.Position).length/i),d=t.Position.sub(a[1]).normalize();e=e.add(d.mul(u))}return e.mul(this.bundlingSettings.HubRepulsionImportance)}BuildForceForBundle(t){let e=new c(0,0);for(const s of t.Neighbors){const n=this.metroGraphData.GetWidthSSN(t,s,this.bundlingSettings.EdgeSeparation),o={closestDist:[]},a=this.metroGraphData.cdtIntersections.BundleAvoidsObstacles(t,s,t.Position,s.Position,n/2,o);for(const h of o.closestDist){const d=2*(1-h[0].sub(h[1]).length/(n/2)),m=h[0].sub(h[1]).normalize().neg();e=e.add(m.mul(d))}}return e.mul(this.bundlingSettings.BundleRepulsionImportance)}}de.MaxIterations=100,de.MaxStep=50,de.MinStep=1,de.MinRelativeChange=5e-4;function Rh(){return new c(1+2*Wi(),1+2*Wi())}class Us{constructor(t,e){this.metroGraphData=t,this.bundlingSettings=e}static FixRouting(t,e){const i=new Us(t,e);i.GlueConflictingStations(),i.UnglueEdgesFromBundleToSaveInk(!0);let s=0;const n=10;for(;++s<n;){let o=i.GlueConflictingStations();if(o||(o=i.RelaxConstrainedEdges()),o||(o=s<=3&&i.UnglueEdgesFromBundleToSaveInk(!1)),o||(o=i.GlueCollinearNeighbors(s)),o||(o=s===3&&i.RemoveDoublePathCrossings()),!o)break}for(t.cdtIntersections.ComputeForcesForBundles=!0,i.RemoveDoublePathCrossings(),i.UnglueEdgesFromBundleToSaveInk(!0);i.GlueConflictingStations(););t.Initialize(!0)}GlueConflictingStations(){const t=this.GetCirclesHierarchy();if(t==null)return!1;const e=new Map,i=new Set;if(pe(t,t,(n,o)=>this.TryToGlueStations(n,o,e,i)),e.size===0)return!1;for(let n=0;n<this.metroGraphData.Edges.length;n++)this.RegenerateEdge(e,n);const s=new Yt;for(const n of i){s.add(n.Position);for(const o of n.Neighbors)o.IsReal||s.add(o.Position)}return this.metroGraphData.Initialize(!1),de.FixRoutingMBP(this.metroGraphData,this.bundlingSettings,s),!0}GetCirclesHierarchy(){for(const i of this.metroGraphData.VirtualStations())i.Radius=this.GetCurrentHubRadius(i);const t=this.metroGraphData.VirtualStations().map(e);return $t(t);function e(i){const s=i.Position,n=Math.max(i.Radius,5),o=new c(n,n),a=X.mkPP(s.add(o),s.sub(o));return he(i,a)}}GetCurrentHubRadius(t){if(t.IsReal)return t.BoundaryCurve.boundingBox.diagonal/2;{const e=t.cachedIdealRadius;let i=this.metroGraphData.looseIntersections.GetMinimalDistanceToObstacles(t,t.Position,e);for(const s of t.Neighbors)i=Math.min(i,t.Position.sub(s.Position).length);return i}}TryToGlueStations(t,e,i,s){if(!sn(t.getELP(),e.getELP()))return!1;const n=t.Position.sub(e.Position).length,o=Math.max(t.Radius,5),a=Math.max(e.Radius,5);n>=o+a||this.TryGlueOrdered(t,e,s,i)||this.TryGlueOrdered(e,t,s,i)}TryGlueOrdered(t,e,i,s){return!s.has(t)&&!i.has(t)&&this.StationGluingIsAllowed(t,e,s)?(this.Map(t,e,i,s),!0):!1}Map(t,e,i,s){s.set(t,e),i.add(e)}StationGluingIsAllowed(t,e,i){for(const n of t.Neighbors){const o=Us.Glued(n,i),a=this.metroGraphData.looseIntersections.ObstaclesToIgnoreForBundle(o,t);if(!this.metroGraphData.cdtIntersections.EdgeIsLegalSSPPS(o,e,a))return!1}return!(this.ComputeCostDeltaAfterStationGluing(t,e,i)<0)}ComputeCostDeltaAfterStationGluing(t,e,i){const s=t.Position.sub(e.Position).length;if(t.Radius>=s||e.Radius>=s)return 1;let n=0;const o=this.metroGraphData.Ink;let a=this.metroGraphData.Ink-e.Position.sub(t.Position).length;for(const h of t.Neighbors){const u=Us.Glued(h,i);a-=u.Position.sub(t.Position).length,a+=this.metroGraphData.RealEdgeCount(u,e)===0?u.Position.sub(e.Position).length:0}n+=ne.InkError(o,a,this.bundlingSettings);for(const h of this.metroGraphData.MetroNodeInfosOfNode(t)){const u=h.Metroline.Length;let d=h.Metroline.Length;const m=h.PolyPoint,y=m.prev,E=m.next;d-=y.point.sub(t.Position).length+E.point.sub(t.Position).length,d+=y.point.sub(e.Position).length+E.point.sub(e.Position).length,n+=ne.PathLengthsError(u,d,h.Metroline.IdealLength,this.bundlingSettings)}return n}RegenerateEdge(t,e){const i=this.metroGraphData.Metrolines[e].Polyline;for(const o of i)if(!this.metroGraphData.PointToStations.has(o))return;let s=!1;for(const o of i)if(t.has(this.metroGraphData.PointToStations.get(o))){s=!0;break}if(!s)return;const n=Array.from(i).map(o=>this.metroGraphData.PointToStations.get(o));this.metroGraphData.Edges[e].curve=st.mkFromPoints(Us.GluedPolyline(n,t))}static GluedPolyline(t,e){let i;const s=new Ut.B;s.push(t[0]);const n=new Set;for(i=1;i<t.length-1;i++){const o=Us.Glued(t[i],e);if(n.has(o)){for(;s.top!==o;)n.delete(s.pop());continue}c.closeDistEps(o.Position,s.top.Position)||(n.add(o),s.push(o))}return s.push(t[i]),Array.from(s).reverse().map(o=>o.Position)}static Glued(t,e){var i;return(i=e.get(t))!==null&&i!==void 0?i:t}UnglueEdgesFromBundleToSaveInk(t){const e=new ls;this.ink=this.metroGraphData.Ink,this.polylineLength=new Map;for(const n of this.metroGraphData.Metrolines){this.polylineLength.set(n,n.Length);for(let o=n.Polyline.startPoint;o.next!=null;o=o.next){const a=new fe(o.point,o.next.point);Bn(e,a,n)}}const i=new Yt;let s=!1;for(const n of this.metroGraphData.Metrolines){const o=Li(this.metroGraphData.PointToStations.get(n.Polyline.start).getELP(),this.metroGraphData.PointToStations.get(n.Polyline.end).getELP());this.TrySeparateOnPolyline(n,e,i,o)&&(s=!0)}return s&&this.metroGraphData.Initialize(!1),(t||s)&&de.FixRoutingMBP(this.metroGraphData,this.bundlingSettings,t?null:i),s}TrySeparateOnPolyline(t,e,i,s){let n=!1,o=!0;for(;o;){o=!1;for(let a=t.Polyline.startPoint;a.next!=null&&a.next.next!=null;a=a.next)this.TryShortcutPolypoint(a,e,i,s)&&(o=!0);o&&(n=!0)}return n}TryShortcutPolypoint(t,e,i,s){return this.SeparationShortcutAllowed(t,e,s)?(i.add(t.point),i.add(t.next.point),i.add(t.next.next.point),this.RemoveShortcuttedPolypoint(t,e),!0):!1}SeparationShortcutAllowed(t,e,i){const s=t.point,n=t.next.point,o=t.next.next.point,a=this.metroGraphData.PointToStations.get(s),h=this.metroGraphData.PointToStations.get(n),u=this.metroGraphData.PointToStations.get(o),d=Ki(a.getELP(),u.getELP()),m=co([i,h.getELP(),d]);return!(!this.metroGraphData.cdtIntersections.EdgeIsLegalSSPPS(a,u,m)||this.GetInkgain(t,e,s,n,o)<0)}GetInkgain(t,e,i,s,n){const[o,a,h]=this.FindPolylines(t,e);let u=0;const d=this.ink;let m=this.ink;const y=i.sub(s).length,E=s.sub(n).length,T=i.sub(n).length;o.size===h.size&&(m-=y),a.size===h.size&&(m-=E);const B=e.get(new fe(i,n));(!B||B.size===0)&&(m+=T),u+=ne.InkError(d,m,this.bundlingSettings);for(const It of h){const Tt=this.polylineLength.get(It),oe=Tt-(y+E-T);u+=ne.PathLengthsError(Tt,oe,It.IdealLength,this.bundlingSettings)}let H=this.GetCurrentHubRadius(this.metroGraphData.PointToStations.get(i));const tt=this.metroGraphData.GetWidthAN(Array.from(h),this.bundlingSettings.EdgeSeparation),lt=this.metroGraphData.GetWidthAN(Array.from(Xi(o,h)),this.bundlingSettings.EdgeSeparation);let Q=Fe.GetMinRadiusForTwoAdjacentBundlesNPPPNNB(H,i,n,s,tt,lt,this.bundlingSettings);Q>H&&(u-=ne.RError(Q,H,this.bundlingSettings)),H=this.GetCurrentHubRadius(this.metroGraphData.PointToStations.get(n));const dt=this.metroGraphData.GetWidthAN(Array.from(Xi(a,h)),this.bundlingSettings.EdgeSeparation);return Q=Fe.GetMinRadiusForTwoAdjacentBundlesNPPPNNB(H,n,s,i,dt,tt,this.bundlingSettings),Q>H&&(u-=ne.RError(Q,H,this.bundlingSettings)),u}RemoveShortcuttedPolypoint(t,e){const i=t.point,s=t.next.point,n=t.next.next.point,[o,a,h]=this.FindPolylines(t,e),u=_(i,s),d=_(s,n),m=_(i,n);o.size===h.size&&(this.ink-=u),a.size===h.size&&(this.ink-=d);const y=e.get(new fe(i,n));(!y||y.size===0)&&(this.ink+=m);for(const E of h){const T=this.polylineLength.get(E);this.polylineLength.set(E,T-(u+d-m))}for(const E of h){const T=Array.from(E.Polyline.polylinePoints()).find(B=>B.point.equal(s));this.RemovePolypoint(T),Ar(e,[i,s],E),Ar(e,[s,n],E),Yi(e,[i,n],E)}}FindPolylines(t,e){const i=t.point,s=t.next.point,n=t.next.next.point,o=e.getPP(i,s),a=e.getPP(s,n),h=Li(o,a);return[o,a,h]}RemovePolypoint(t){const e=t.prev,i=t.next;e.next=i,i.prev=e}GlueCollinearNeighbors(t){const e=new Yt;let i=!1;for(const s of this.metroGraphData.Stations)this.GlueCollinearNeighborsSPN(s,e,t)&&(i=!0);return i&&(this.metroGraphData.Initialize(!1),de.FixRoutingMBP(this.metroGraphData,this.bundlingSettings,e)),i}GlueCollinearNeighborsSPN(t,e,i){if(t.Neighbors.length<=1)return!1;const s=new Ha,n=t.Neighbors;for(let o=0;o<n.length;o++)this.TryToGlueEdges(t,n[o],n[(o+1)%n.length],s,i);if(s.isEmpty)return!1;for(const o of s)this.GlueEdge(o),e.add(o[0].Position),e.add(o[1].Position),e.add(o[2]);return!0}TryToGlueEdges(t,e,i,s,n){if(c.anglePCP(e.Position,t.Position,i.Position)<this.bundlingSettings.AngleThreshold){const a=_(e.Position,t.Position),h=_(i.Position,t.Position),u=Math.min(a,h)/Math.max(a,h);if(u<.05)return;if(a<h){if(this.EdgeGluingIsAllowedSSS(t,e,i)){this.AddEdgeToGlue(t,i,e,e.Position,s);return}}else if(this.EdgeGluingIsAllowedSSS(t,i,e)){this.AddEdgeToGlue(t,e,i,i.Position,s);return}if(n<5&&u>.5){const d=this.ConstructGluingPoint(t,e,i);this.EdgeGluingIsAllowedSSSP(t,e,i,d)&&this.AddEdgeToGlue(t,i,e,d,s)}}}ConstructGluingPoint(t,e,i){const s=Math.min(_(e.Position,t.Position),_(i.Position,t.Position)/2),n=e.Position.sub(t.Position).normalize().add(i.Position.sub(t.Position).normalize());return t.Position.add(n.mul(s/2))}EdgeGluingIsAllowedSSS(t,e,i){if(e.IsReal||i.IsReal||!sn(e.getELP(),i.getELP())||!this.metroGraphData.cdtIntersections.EdgeIsLegal(e,i,e.Position,i.Position))return!1;const s=this.metroGraphData.looseIntersections.ObstaclesToIgnoreForBundle(t,i);return!(ct.IntersectionsOfLineAndRectangleNodeOverPolylineLR(N.mkPP(t.Position,e.Position),this.metroGraphData.LooseTree).find(h=>!s.has(h.seg1))||ct.IntersectionsOfLineAndRectangleNodeOverPolylineLR(N.mkPP(e.Position,i.Position),this.metroGraphData.LooseTree).find(h=>!s.has(h.seg1))||this.ComputeCostDeltaAfterEdgeGluing(t,e,i,e.Position)<0)}EdgeGluingIsAllowedSSSP(t,e,i,s){return!(!this.metroGraphData.looseIntersections.HubAvoidsObstaclesPNS__(s,0,Li(e.getELP(),i.getELP()))||!this.metroGraphData.cdtIntersections.EdgeIsLegal(t,null,t.Position,s)||!this.metroGraphData.cdtIntersections.EdgeIsLegal(e,null,e.Position,s)||!this.metroGraphData.cdtIntersections.EdgeIsLegal(i,null,i.Position,s)||this.ComputeCostDeltaAfterEdgeGluing(t,e,i,s)<0)}ComputeCostDeltaAfterEdgeGluing(t,e,i,s){let n=0;const o=this.metroGraphData.Ink,a=this.metroGraphData.Ink-_(t.Position,i.Position)-_(t.Position,e.Position)+_(t.Position,s)+_(s,e.Position)+_(s,i.Position);n+=ne.InkError(o,a,this.bundlingSettings);for(const m of this.metroGraphData.GetIjInfo(t,i).Metrolines){const y=m.Length,E=m.Length-_(t.Position,i.Position)+_(t.Position,s)+_(s,i.Position);n+=ne.PathLengthsError(y,E,m.IdealLength,this.bundlingSettings)}for(const m of this.metroGraphData.GetIjInfo(t,e).Metrolines){const y=m.Length,E=m.Length-_(t.Position,e.Position)+_(t.Position,s)+_(s,e.Position);n+=ne.PathLengthsError(y,E,m.IdealLength,this.bundlingSettings)}const h=t.cachedIdealRadius,u=this.GetCurrentHubRadius(t),d=Fe.GetMinRadiusForTwoAdjacentBundles(u,t,t.Position,e,i,this.metroGraphData,this.bundlingSettings);return d>u&&(n+=ne.RError(d,u,this.bundlingSettings)),h>_(t.Position,s)&&!t.IsReal&&(n-=ne.RError(h,_(t.Position,s),this.bundlingSettings)),n}AddEdgeToGlue(t,e,i,s,n){n.has(i,t)||n.has(e,t)||n.has(t,i)||n.has(t,e)||(n.set(t,i,s),n.set(t,e,s))}GlueEdge(t){const e=t[0],i=t[1],s=t[2];for(const n of e.MetroNodeInfos.map(o=>o.PolyPoint))n.next!=null&&n.next.point.equal(i.Position)?this.SplitPolylinePoint(n,s):n.prev!=null&&n.prev.point.equal(i.Position)&&this.SplitPolylinePoint(n.prev,s)}SplitPolylinePoint(t,e){if(t.point===e||t.next.point===e)return;const i=zt.mkFromPoint(e);i.polyline=t.polyline,i.next=t.next,i.prev=t,i.next.prev=i,i.prev.next=i}RelaxConstrainedEdges(){const t=new Yt;let e=!1;for(const i of this.metroGraphData.VirtualEdges())this.RelaxConstrainedEdge(i[0],i[1],t)&&(e=!0);return e&&(this.metroGraphData.Initialize(!1),de.FixRoutingMBP(this.metroGraphData,this.bundlingSettings,t)),e}RelaxConstrainedEdge(t,e,i){const s=this.metroGraphData.GetWidthSSN(t,e,this.bundlingSettings.EdgeSeparation),n={closestDist:new Array};this.metroGraphData.cdtIntersections.BundleAvoidsObstacles(t,e,t.Position,e.Position,.99*s/2,n);const o=n.closestDist;if(o.length>0){let a=-1,h;for(const u of o){const d=Math.min(_(t.Position,u[1]),_(e.Position,u[1])),m=_(t.Position,e.Position);if(d/m<.1)continue;const E=_(u[0],u[1]);(a===-1||E<a)&&(a=E,h=u[1])}if(a===-1||!this.metroGraphData.looseIntersections.HubAvoidsObstaclesPNS__(h,0,Li(t.getELP(),e.getELP())))return!1;i.add(h),i.add(t.Position),i.add(e.Position);for(const u of this.metroGraphData.GetIjInfo(t,e).Metrolines){let d=null;for(const m of u.Polyline.polylinePoints())if(m.point.equal(t.Position)){d=m;break}d.next!=null&&d.next.point.equal(e.Position)?this.SplitPolylinePoint(d,h):this.SplitPolylinePoint(d.prev,h)}return!0}return!1}RemoveDoublePathCrossings(){const t=new lr(this.metroGraphData,this.metroGraphData.PointIsAcceptableForEdge.bind(this)).run();return t&&(this.metroGraphData.Initialize(!1),de.FixRouting(this.metroGraphData,this.bundlingSettings)),t}}class to{constructor(t,e,i){this.upperBound=Number.POSITIVE_INFINITY,this._visGraph=i,i.ClearPrevEdgesTable();for(const s of i.Vertices())s.Distance=Number.POSITIVE_INFINITY;this.sources=t,this.targets=new Set(e)}GetPath(){const t=new Ri;for(const e of this.sources)e.Distance=0,t.Enqueue(e,0);for(;!t.IsEmpty()&&(this._current=t.Dequeue(),!this.targets.has(this._current));){for(const e of this._current.OutEdges)this.PassableOutEdge(e)&&this.ProcessNeighbor(t,e,e.Target);for(const e of this._current.InEdges.filter(this.PassableInEdge.bind))this.ProcessNeighbor(t,e,e.Source)}return this._visGraph.PreviosVertex(this._current)==null?null:this.CalculatePath()}PassableOutEdge(t){return this.targets.has(t.Target)||!to.IsForbidden(t)}PassableInEdge(t){return this.targets.has(t.Source)||!to.IsForbidden(t)}static IsForbidden(t){return(t.IsPassable!=null&&!t.IsPassable()||t)instanceof li}ProcessNeighbor(t,e,i){const s=e.Length,n=this._current.Distance+s;n>=this.upperBound||(this.targets.has(i)&&(this.upperBound=n,this.closestTarget=i),this._visGraph.PreviosVertex(i)==null?(i.Distance=n,this._visGraph.SetPreviousEdge(i,e),t.Enqueue(i,n)):n<i.Distance&&(i.Distance=n,this._visGraph.SetPreviousEdge(i,e),t.DecreasePriority(i,n)))}CalculatePath(){if(this.closestTarget==null)return null;const t=new Array;let e=this.closestTarget;do t.push(e),e=this._visGraph.PreviosVertex(e);while(e.Distance>0);return t.push(e),t.reverse()}}class hr extends Ft{constructor(t,e,i,s,n,o,a,h,u,d){super(null),this.bundlingSettings=s,this.bundlingSettings.edgeWidthShrinkCoeff=1,this.edgesToRoute=t,this.regularEdges=t.filter(m=>m.source!==m.target),this.VisibilityGraph=i,this.shortestPathRouter=e,this.LoosePadding=n,this.LooseHierarchy=a,this.TightHierarchy=o,this.EdgeLooseEnterable=h,this.EdgeTightEnterable=u,this.loosePolylineOfPort=d,os(0)}ThereAreOverlaps(t){return Zt(t,t,w.CurvesIntersect)}run(){if(this.ThereAreOverlaps(this.TightHierarchy)){this.Status=ko.Overlaps;return}this.FixLocationsForHookAnywherePorts(this.edgesToRoute),this.RoutePathsWithSteinerDijkstra(),this.FixChildParentEdges(),this.bundlingSettings.StopAfterShortestPaths||this.OrderOptimizeNudgeEtc(),this.RouteSelfEdges(),this.FixArrowheads()}OrderOptimizeNudgeEtc(){const t=new xh(this.regularEdges,this.LooseHierarchy,this.TightHierarchy,this.bundlingSettings,this.shortestPathRouter.cdt,this.EdgeLooseEnterable,this.EdgeTightEnterable,this.loosePolylineOfPort);Us.FixRouting(t,this.bundlingSettings),new Ot(t,this.bundlingSettings).run()}FixChildParentEdges(){for(const t of this.regularEdges){const e=t.sourcePort,i=t.targetPort;if(e.Curve.boundingBox.containsRect(i.Curve.boundingBox)){const s=w.intersectionOne(e.Curve,N.mkPP(t.curve.start,t.curve.end),!1),n=t.curve;n.startPoint.point=s.x}if(i.Curve.boundingBox.containsRect(e.Curve.boundingBox)){const s=w.intersectionOne(i.Curve,N.mkPP(t.curve.start,t.curve.end),!0),n=t.curve;n.endPoint.point=s.x}}}FixLocationsForHookAnywherePorts(t){for(const e of t){let i=e.sourcePort instanceof Wt;if(i){const s=e.sourcePort;s.SetLocation(this.FigureOutHookLocation(s.LoosePolyline,e.targetPort,e))}else if(i=e.targetPort instanceof Wt,i){const s=e.targetPort;s.SetLocation(this.FigureOutHookLocation(s.LoosePolyline,e.sourcePort,e))}}}FigureOutHookLocation(t,e,i){return e instanceof Ie?this.FigureOutHookLocationForClusterOtherPort(t,e,i):this.FigureOutHookLocationForSimpleOtherPort(t,e,i)}FigureOutHookLocationForClusterOtherPort(t,e,i){const s=this.shortestPathRouter.MakeTransparentShapesOfEdgeGeometry(i),o=new to(Array.from(e.LoosePolyline).map(this.VisibilityGraph.FindVertex.bind),Array.from(t).map(this.VisibilityGraph.FindVertex.bind),this.VisibilityGraph).GetPath();for(const a of s)a.IsTransparent=!1;return o[o.length-1].point}FigureOutHookLocationForSimpleOtherPort(t,e,i){const s=e.Location,n=this.shortestPathRouter.MakeTransparentShapesOfEdgeGeometry(i),a=new as(this.VisibilityGraph.FindVertex(s),Array.from(t).map(h=>this.VisibilityGraph.FindVertex(h)),this.VisibilityGraph).GetPath();for(const h of n)h.IsTransparent=!1;return a[a.length-1].point}RoutePathsWithSteinerDijkstra(){this.shortestPathRouter.VisibilityGraph=this.VisibilityGraph,this.shortestPathRouter.BundlingSettings=this.bundlingSettings,this.shortestPathRouter.geomEdges=this.regularEdges,this.shortestPathRouter.ObstacleHierarchy=this.LooseHierarchy,this.shortestPathRouter.RouteEdges(),this.shortestPathRouter.cdt!=null&&this.AdjustEdgeSeparation()}AdjustEdgeSeparation(){const t=new Map;this.shortestPathRouter.FillCrossedCdtEdges(t);const e=this.GetPathsOnCdtEdge(t);this.bundlingSettings.edgeWidthShrinkCoeff=this.CalculateEdgeWidthShrinkCoeff(e)}GetPathsOnCdtEdge(t){const e=new Map;for(const i of t.keys())for(const s of t.get(i))nn(e,s,i);return e}CalculateEdgeWidthShrinkCoeff(t){let e=0,i=this.bundlingSettings.edgeWidthShrinkCoeff;if(this.EdgeSeparationIsOkMN(t,i))return i;let s=!1;for(;!s||Math.abs(i-e)>.01;){const n=(e+i)/2;this.EdgeSeparationIsOkMN(t,n)?(e=n,s=!0):i=n}return e}EdgeSeparationIsOkMN(t,e){for(const i of t.keys())if(!this.EdgeSeparationIsOk(i,t.get(i),e))return!1;return!0}EdgeSeparationIsOk(t,e,i){return Array.from(e).map(n=>this.bundlingSettings.ActualEdgeWidth(n,i)).reduce((n,o)=>n+o,0)<=t.Capacity}RouteSelfEdges(){for(const t of this.edgesToRoute)if(t.source===t.target){const e={smoothedPolyline:null};t.curve=we.RouteSelfEdge(t.source.boundaryCurve,this.LoosePadding*2,e)}}FixArrowheads(){for(const t of this.edgesToRoute)Bt.trimSplineAndCalculateArrowheadsII(t,t.source.boundaryCurve,t.target.boundaryCurve,t.curve,!1)}}hr.SuperLoosePaddingCoefficient=1.1;class Nh{constructor(t,e,i){this.numberOfPassedPaths=0,this.VisibilityEdge=t,this.Source=e,this.Target=i}get TargetPoint(){return this.Target.Point}get SourcePoint(){return this.Source.Point}get IsOccupied(){return this.numberOfPassedPaths>0}get IsPassable(){return this.Target.IsTargetOfRouting||this.Source.IsSourceOfRouting||this.VisibilityEdge.IsPassable==null||this.VisibilityEdge.IsPassable()}AddOccupiedEdge(){this.numberOfPassedPaths++}RemoveOccupiedEdge(){this.numberOfPassedPaths--}}class Gh{get Prev(){return this.PrevEdge==null?null:this.PrevEdge.Source===this?this.PrevEdge.Target:this.PrevEdge.Source}constructor(t){this.InBoneEdges=new Array,this.OutBoneEdges=new Array,this.VisibilityVertex=t}get Point(){return this.VisibilityVertex.point}get Cost(){return this.IsSourceOfRouting?this.cost:this.Prev==null?Number.POSITIVE_INFINITY:this.cost}set Cost(t){this.cost=t}SetPreviousToNull(){this.PrevEdge=null}}class fs{constructor(t,e,i){this.EdgesToRoutes=new Map,this.EdgesToRouteSources=new Map,this.MakeTransparentShapesOfEdgeGeometry=t,this.cdt=e,this.Gates=i}CreateGraphElements(){for(const t of this.vertexArray){const e=t.VisibilityVertex;for(const i of e.InEdges){const s=new Nh(i,this.VisibilityVerticesToSdVerts.get(i.Source),this.VisibilityVerticesToSdVerts.get(i.Target)),n=this.VisibilityVerticesToSdVerts.get(i.Source);t.InBoneEdges.push(s),n.OutBoneEdges.push(s)}}}CreateRoutingGraph(){this.vertexArray=[],this.VisibilityVerticesToSdVerts=new Map;for(const t of this.VisibilityGraph.Vertices()){const e=new Gh(t);this.vertexArray.push(e),this.VisibilityVerticesToSdVerts.set(t,e)}this.CreateGraphElements()}RouteEdges(){this.Initialize(),this.RestoreCapacities();for(const t of this.geomEdges)this.EdgesToRoutes.set(t,this.RouteEdge(t));this.RerouteEdges();for(const t of this.geomEdges)this.SetEdgeGeometryCurve(t)}SetEdgeGeometryCurve(t){const e=new st;let i=this.EdgesToRouteSources.get(t);e.addPoint(i.Point);for(const o of this.EdgesToRoutes.get(t))o.SourcePoint.equal(i.Point)?(e.addPoint(o.TargetPoint),i=o.Target):(e.addPoint(o.SourcePoint),i=o.Source);t.curve=e,t.sourcePort instanceof Ie&&fs.ExtendPolylineStartToClusterBoundary(e,t.sourcePort.Curve),t.targetPort instanceof Ie&&fs.ExtendPolylineEndToClusterBoundary(e,t.targetPort.Curve)}static ExtendPolylineEndToClusterBoundary(t,e){const i=e.closestParameter(t.end);t.addPoint(e.value(i))}static ExtendPolylineStartToClusterBoundary(t,e){const i=e.closestParameter(t.start);t.PrependPoint(e.value(i))}RerouteEdges(){this.RestoreCapacities();for(const t of this.geomEdges){const e=this.RerouteEdge(t);this.EdgesToRoutes.set(t,e)}}RestoreCapacities(){this.cdt!=null&&this.cdt.RestoreEdgeCapacities()}RerouteEdge(t){const e=this.EdgesToRoutes.get(t);for(const i of e)i.RemoveOccupiedEdge();return this.RouteEdge(t)}RouteEdge(t){this.CurrentEdgeGeometry=t;for(let s=0;s<this.vertexArray.length;s++){const n=this.vertexArray[s];n.SetPreviousToNull(),n.IsTargetOfRouting=n.IsSourceOfRouting=!1}const e=this.MakeTransparentShapesOfEdgeGeometry(t),i=this.RouteEdgeWithGroups();for(const s of e)s.IsTransparent=!1;return i}RouteEdgeWithGroups(){for(let t=0;t<2;t++){this.SetLengthCoefficient(),this.Queue=new Ri,this.sourceLoosePoly=this.SetPortVerticesAndObstacles(this.CurrentEdgeGeometry.sourcePort,!0),this.targetLoosePoly=this.SetPortVerticesAndObstacles(this.CurrentEdgeGeometry.targetPort,!1);const e=this.RouteOnKnownSourceTargetVertices(this.CurrentEdgeGeometry.targetPort.Location.sub(this.CurrentEdgeGeometry.sourcePort.Location).normalize(),t===0);if(e!=null)return e;for(let i=0;i<this.vertexArray.length;i++)this.vertexArray[i].SetPreviousToNull()}throw new Error}RouteOnKnownSourceTargetVertices(t,e){for(this.LowestCostToTarget=Number.POSITIVE_INFINITY,this.ClosestTargetVertex=null;this.Queue.count>0;){const i={priority:0},s=this.Queue.DequeueAndGetPriority(i);if(!(i.priority>=this.LowestCostToTarget)){for(let n=0;n<s.OutBoneEdges.length;n++){const o=s.OutBoneEdges[n];o.IsPassable&&this.ProcessOutcomingBoneEdge(s,o,t,e)}for(let n=0;n<s.InBoneEdges.length;n++){const o=s.InBoneEdges[n];o.IsPassable&&this.ProcessIncomingBoneEdge(s,o,t,e)}}}return this.GetPathAndUpdateRelatedCosts()}ProcessOutcomingBoneEdge(t,e,i,s){s&&i.dot(e.TargetPoint.sub(e.SourcePoint))<0||this.ProcessBoneEdge(t,e.Target,e)}ProcessIncomingBoneEdge(t,e,i,s){s&&i.dot(e.SourcePoint.sub(e.TargetPoint))<0||this.ProcessBoneEdge(t,e.Source,e)}ProcessBoneEdge(t,e,i){const s=this.GetEdgeAdditionalCost(i,t.Cost);if(!(e.Cost<=s))if(e.Cost=s,e.PrevEdge=i,this.Queue.ContainsElement(e))this.Queue.DecreasePriority(e,s);else{if(e.IsTargetOfRouting){let n=0;this.CurrentEdgeGeometry.targetPort instanceof Ie&&(n=this.LengthCoefficient*e.Point.sub(this.CurrentEdgeGeometry.targetPort.Location).length),s+n<this.LowestCostToTarget&&(this.LowestCostToTarget=s+n,this.ClosestTargetVertex=e);return}this.Enqueue(e)}}GetPathAndUpdateRelatedCosts(){let t=this.ClosestTargetVertex;if(t==null)return null;const e=new Array;for(;t.PrevEdge!=null;)e.push(t.PrevEdge),this.RegisterPathInBoneEdge(t.PrevEdge),t=t.Prev;return this.EdgesToRouteSources.set(this.CurrentEdgeGeometry,t),e.reverse(),e}RegisterPathInBoneEdge(t){t.AddOccupiedEdge(),this.cdt!=null&&this.BundlingSettings.CapacityOverflowCoefficient!==0&&this.UpdateResidualCostsOfCrossedCdtEdges(t)}UpdateResidualCostsOfCrossedCdtEdges(t){for(const e of t.CrossedCdtEdges)this.AdjacentToSourceOrTarget(e)||(e.ResidualCapacity===e.Capacity?e.ResidualCapacity-=this.BundlingSettings.edgeWidthShrinkCoeff*this.CurrentEdgeGeometry.lineWidth:e.ResidualCapacity-=this.BundlingSettings.ActualEdgeWidth(this.CurrentEdgeGeometry))}H(t){return t.Cost+this.LengthCoefficient*t.Point.sub(this.CurrentEdgeGeometry.targetPort.Location).length}GetEdgeAdditionalCost(t,e){const i=t.TargetPoint.sub(t.SourcePoint).length;return this.LengthCoefficient*i+e+(t.IsOccupied?0:this.BundlingSettings.InkImportance*i)+this.CapacityOverflowCost(t)}CapacityOverflowCost(t){if(this.cdt==null||this.BundlingSettings.CapacityOverflowCoefficient===0)return 0;let e=0;for(const i of this.CrossedCdtEdgesOfBoneEdge(t))e+=this.CostOfCrossingCdtEdgeLocal(this.capacityOverlowPenaltyMultiplier,this.BundlingSettings,this.CurrentEdgeGeometry,i);return e}CrossedCdtEdgesOfBoneEdge(t){return t.CrossedCdtEdges!=null?Array.from(t.CrossedCdtEdges):Array.from(t.CrossedCdtEdges=this.ThreadBoneEdgeThroughCdt(t))}ThreadBoneEdgeThroughCdt(t){const e=t.SourcePoint,i=t.Source.Triangle,s=new Set,n=t.TargetPoint;if(ie.PointIsInsideOfTriangle(n,i))return s;const o=new Yr(i,e,n);for(;o.MoveNext();){const a=o.CurrentPiercedEdge;this.Gates.has(a)&&s.add(a)}return s}static CostOfCrossingCdtEdge(t,e,i,s){let n=i.lineWidth*e.edgeWidthShrinkCoeff;s.Capacity!==s.ResidualCapacity&&(n+=e.EdgeSeparation*e.edgeWidthShrinkCoeff);const o=s.ResidualCapacity-n;return o>=0?0:-o*t}CostOfCrossingCdtEdgeLocal(t,e,i,s){return this.AdjacentToSourceOrTarget(s)?0:fs.CostOfCrossingCdtEdge(t,e,i,s)}AdjacentToSourceOrTarget(t){return t.upperSite.Owner===this.sourceLoosePoly||t.lowerSite.Owner===this.sourceLoosePoly||t.upperSite.Owner===this.targetLoosePoly||t.lowerSite.Owner===this.targetLoosePoly}SetLengthCoefficient(){const t=this.GetIdealDistanceBetweenSourceAndTarget(this.CurrentEdgeGeometry);this.LengthCoefficient=this.BundlingSettings.PathLengthImportance/t}GetIdealDistanceBetweenSourceAndTarget(t){return t.sourcePort.Location.sub(t.targetPort.Location).length}SetPortVerticesAndObstacles(t,e){let i;if(t instanceof Ie){i=t.LoosePolyline;for(const n of i){let o=0;e&&(o=this.LengthCoefficient*n.sub(this.CurrentEdgeGeometry.sourcePort.Location).length),this.AddAndEnqueueVertexToEnds(n,e,o)}}else if(t instanceof Wt){i=t.LoosePolyline;for(const n of i)this.AddAndEnqueueVertexToEnds(n,e,0)}else{this.AddAndEnqueueVertexToEnds(t.Location,e,0);const s=Array.from(this.ObstacleHierarchy.GetNodeItemsIntersectingRectangle(t.Curve.boundingBox));let n=s[0].boundingBox.diagonal;i=s[0];for(let o=1;o<s.length;o++){const a=s[o],h=a.boundingBox.diagonal;h<n&&(n=h,i=a)}}return i}Enqueue(t){this.Queue.Enqueue(t,this.H(t))}AddAndEnqueueVertexToEnds(t,e,i){const s=this.FindVertex(t),n=this.VisibilityVerticesToSdVerts.get(s);e?(n.IsSourceOfRouting=!0,n.Cost=i,this.Enqueue(n)):n.IsTargetOfRouting=!0}FindVertex(t){return this.VisibilityGraph.FindVertex(t)}Initialize(){this.CreateRoutingGraph(),this.cdt!=null&&(this.capacityOverlowPenaltyMultiplier=fs.CapacityOverflowPenaltyMultiplier(this.BundlingSettings),this.SetVertexTriangles(),this.CalculateCapacitiesOfTrianglulation())}CalculateCapacitiesOfTrianglulation(){for(const t of this.Gates)fs.CalculateCdtEdgeCapacityForEdge(t)}static CalculateCdtEdgeCapacityForEdge(t){if(t.constrained||t.CwTriangle==null||t.CcwTriangle==null)return;const e=t.upperSite.Owner,i=t.lowerSite.Owner;if(e!==i){const s=Pe.DistancePoint(new Pe(e),t.lowerSite.point),n=Pe.DistancePoint(new Pe(i),t.upperSite.point);t.Capacity=(s+n)/2}}SetVertexTriangles(){const t=$t(Array.from(this.cdt.GetTriangles()).map(i=>he(i,i.BoundingBox()))),e=$t(this.vertexArray.map(i=>he(i,X.mkOnPoints([i.Point]))));Te(t,e,(i,s)=>this.TryToAssigenTriangleToVertex(i,s))}TryToAssigenTriangleToVertex(t,e){e.Triangle==null&&ie.PointIsInsideOfTriangle(e.Point,t)&&(e.Triangle=t)}static CapacityOverflowPenaltyMultiplier(t){return t.CapacityOverflowCoefficient*(t.PathLengthImportance+t.InkImportance)}FillCrossedCdtEdges(t){for(const e of this.geomEdges){this.sourceLoosePoly=this.SetPortVerticesAndObstacles(e.sourcePort,!0),this.targetLoosePoly=this.SetPortVerticesAndObstacles(e.targetPort,!1);for(const i of this.EdgesToRoutes.get(e))for(const s of this.CrossedCdtEdgesOfBoneEdge(i))this.AdjacentToSourceOrTarget(s)||nn(t,e,s)}}}class eo{constructor(t,e,i,s,n){this.multiEdges=t,this.interactiveEdgeRouter=e,this.bundlingSettings=s,this.bundlingSettings.edgeWidthShrinkCoeff=1,this.transparentShapeSetter=n,this.nodeTree=en(i,o=>o.boundingBox)}run(){for(const t of this.GetIndependantPreGraphs())new hr(t.edges,new fs(this.transparentShapeSetter,null,null),this.interactiveEdgeRouter.VisibilityGraph,this.bundlingSettings,this.interactiveEdgeRouter.LoosePadding,this.interactiveEdgeRouter.TightHierarchy,this.interactiveEdgeRouter.LooseHierarchy,null,null,null).run()}GetPortCurve(t){return this.nodeTree.FirstHitNodeWithPredicate(t.Location,(i,s)=>w.PointRelativeToCurveLocation(i,s)!==at.Outside?Nt.Stop:Nt.Continue).UserData}GetIndependantPreGraphs(){const t=this.CreateInitialPregraphs();do{const e=t.length,i={preGraphs:t};if(this.UniteConnectedPreGraphs(i),e<=t.length)break}while(!0);return t}UniteConnectedPreGraphs(t){const e=eo.GetIntersectionGraphOfPreGraphs(t.preGraphs);if(e==null)return;const i=Ci(e),s=new Array;for(const n of i){let o=null;for(const a of n)o==null?(o=t.preGraphs[a],s.push(o)):o.AddGraph(t.preGraphs[a])}t.preGraphs=s;for(const n of t.preGraphs)this.AddIntersectingNodes(n)}AddIntersectingNodes(t){const e=t.boundingBox;for(const i of this.nodeTree.GetNodeItemsIntersectingRectangle(e))t.AddNodeBoundary(i)}static GetIntersectionGraphOfPreGraphs(t){const e=eo.EnumeratePairsOfIntersectedPreGraphs(t);return e.length?Qe(e,t.length):null}static EnumeratePairsOfIntersectedPreGraphs(t){const e=Array.from(Array(t.length).keys()),i=en(e,n=>t[n].boundingBox),s=new Array;return pe(i,i,(n,o)=>s.push(new Et(n,o))),s}CreateInitialPregraphs(){return this.multiEdges.map(t=>this.CreatePregraphFromSetOfEdgeGeometries(t))}CreatePregraphFromSetOfEdgeGeometries(t){const e=new Set,i=t[0],s=this.GetPortCurve(i.sourcePort),n=s.boundingBox;e.add(s),e.add(i.targetPort.Curve),n.addRec(i.targetPort.Curve.boundingBox);const o=this.nodeTree.GetNodeItemsIntersectingRectangle(n);for(const a of o)e.add(a);return Go.constructorStatic(t,e)}}class kh{constructor(){this.triangles=new Set}setCdt(t){this.cdt=t,this.cdt.SetInEdges();const e=new Set;for(const i of t.GetTriangles())for(const s of i.Sites)s.Owner!=null&&e.add(s.Owner)}outsideOfObstacles(t){var e;if(t==null)return!1;const i=(e=t.Sites.item0.Owner)!==null&&e!==void 0?e:t.Sites.item1.Owner;return i===this.sourcePoly||i===this.targetPoly||!Mh(t)}run(t){if(this.triangles.clear(),this.poly=t,this.d=[],t.count<=2||this.cdt==null)return;this.sourcePoly=this.findPoly(t.start),this.targetPoly=this.findPoly(t.end),this.findChannelTriangles();let e=this.getPerimeterEdges();e=this.fillTheCollapedSites(e);const i=new ie([],[],Array.from(e).map(n=>({A:n.lowerSite.point,B:n.upperSite.point})));i.run();const s=this.getSleeve(this.findSourceTriangle(i));if(s==null){console.log("failed to create sleeve");return}if(s.length==0){this.poly=st.mkFromPoints([t.start,t.end]);return}this.initDiagonals(s),this.refineFunnel()}getAllCrossedTriangles(t,e,i){const s=[],n=[];let o=null;for(n.push(t);n.length>0;){const a=n.pop();if(o==null&&a.containsPoint(i)&&(o=a),a.intersectsLine(e,i,0)){s.push(a);for(const h of a.Edges){const u=h.GetOtherTriangle_T(a);u&&!s.includes(u)&&!n.includes(u)&&n.push(u)}}}return{triangles:s,containsEnd:o}}findChannelTriangles(){let e=this.cdt.FindSite(this.poly.start).Triangles().next().value;this.triangles.clear();for(let i=this.poly.startPoint;i.next!=null;i=i.next){const s=this.getAllCrossedTriangles(e,i.point,i.next.point);e=s.containsEnd;for(const n of s.triangles)this.outsideOfObstacles(n)&&this.triangles.add(n)}}findPoly(t){var e;const i=this.cdt.FindSite(t);for(const s of i.Edges)return(e=s.lowerSite.Owner)!==null&&e!==void 0?e:s.upperSite.Owner}fillTheCollapedSites(t){const e=new Map;for(const n of t)s(n.lowerSite,n),s(n.upperSite,n);const i=[];for(const[n,o]of e)o.length>2&&i.push(n);if(i.length==0)return t;for(const n of i)for(const o of n.Triangles())this.outsideOfObstacles(o)&&this.triangles.add(o);return this.getPerimeterEdges();function s(n,o){let a=e.get(n);a==null&&e.set(n,a=[]),a.push(o)}}findSourceTriangle(t){let e;for(const i of t.GetTriangles())if(i.containsPoint(this.poly.start)){e=i;break}return e}refineFunnel(){const t=[];let e=this.poly.start;const i={point:e},s={point:e};let n={point:this.d[0].left,prev:i},o={point:this.d[0].right,prev:s};i.next=n,s.next=o;let a;for(let Q=1;Q<this.d.length;Q++)u(Q,this.d);this.d.push({right:this.poly.end,left:n.point}),u(this.d.length-1,this.d);const h=st.mkFromPoints(t);for(let Q=s;Q!=null;Q=Q.next)h.addPoint(Q.point);this.poly=h;function u(Q,dt){if(dt[Q-1].left!==dt[Q].left){a=dt[Q].left;let Tt=n;for(;!(H(Tt)||y(Tt));Tt=Tt.prev);H(Tt)?T():lt(Tt)}else{a=dt[Q].right;let Tt=o;for(;!(H(Tt)||E(Tt));Tt=Tt.prev);H(Tt)?B():tt(Tt)}}function d(Q){return Q.next==null?!0:c.pointToTheLeftOfLineOrOnLine(a,Q.point,Q.next.point)}function m(Q){return Q.next==null?!0:c.pointToTheRightOfLineOrOnLine(a,Q.point,Q.next.point)}function y(Q){return c.pointToTheLeftOfLine(a,Q.prev.point,Q.point)}function E(Q){return c.pointToTheRightOfLine(a,Q.prev.point,Q.point)}function T(){let Q=s;for(;!d(Q);)Q=Q.next;if(!H(Q)){let dt=s;for(;!dt.point.equal(Q.point);dt=dt.next)t.push(dt.point);s.point=dt.point,s.next=dt.next,e=dt.point,o.point.equal(s.point)&&(o.prev=o.next=null)}i.point=e,n.point=a,n.prev=i,i.next=n}function B(){let Q=i;for(;!m(Q);)Q=Q.next;if(!H(Q)){let dt=i;for(;!dt.point.equal(Q.point);dt=dt.next)t.push(dt.point);i.point=dt.point,i.next=dt.next,e=dt.point,n.point.equal(i.point)&&(n.prev=i.next=null)}s.point=e,o.point=a,o.prev=s,s.next=o}function H(Q){return Q.point==e}function tt(Q){Q!=o?(o.point=a,o.prev=Q,Q.next=o):(o={point:a,prev:Q},Q.next=o)}function lt(Q){Q!=n?(n.point=a,n.prev=Q,Q.next=n):(n={point:a,prev:Q},Q.next=n)}}initDiagonals(t){for(const e of t){const i=e.edge,s=e.source.OppositeSite(i);c.getTriangleOrientation(s.point,i.lowerSite.point,i.upperSite.point)==D.Counterclockwise?this.d.push({left:i.upperSite.point,right:i.lowerSite.point}):this.d.push({right:i.upperSite.point,left:i.lowerSite.point})}}getSleeve(t){const e=new Ge.o;e.enqueue(t);const i=new Map;for(i.set(t,void 0);e.length>0;){const s=e.dequeue(),n=i.get(s);if(s.containsPoint(this.poly.end))return this.recoverPath(t,i,s);for(const o of s.Edges){if(o.constrained||n!==void 0&&o===n)continue;const a=o.GetOtherTriangle_T(s);a!=null&&(i.has(a)||(i.set(a,o),e.enqueue(a)))}}}recoverPath(t,e,i){const s=[];for(let n=i;n!=t&&n!==t;){const o=e.get(n);n=o.GetOtherTriangle_T(n),s.push({source:n,edge:o})}return s.reverse()}getPerimeterEdges(){const t=new Set;for(const e of this.triangles)for(const i of e.Edges)this.triangles.has(i.GetOtherTriangle_T(e))||t.add(i);return t}}function Mh(l){return l.Sites.item0.Owner==null||l.Sites.item1.Owner==null||l.Sites.item2.Owner==null?!0:l.Sites.item0.Owner==l.Sites.item1.Owner&&l.Sites.item0.Owner==l.Sites.item2.Owner}class qt extends Ft{get ContinueOnOverlaps(){return this.continueOnOverlaps}set ContinueOnOverlaps(t){this.continueOnOverlaps=t}get LoosePadding(){return this.loosePadding}set LoosePadding(t){this.loosePadding=t}get MultiEdgesSeparation(){return this.multiEdgesSeparation}set MultiEdgesSeparation(t){this.multiEdgesSeparation=t}static mk2(t,e){return qt.mk5(t,e.Padding,e.PolylinePadding,e.ConeAngle,e.bundlingSettings)}static mk4(t,e,i,s){return new qt(t,Array.from(t.deepEdges),e,i,s,null)}static mk5(t,e,i,s,n){return new qt(t,Array.from(t.deepEdges),e,i,s,n)}constructor(t,e,i=1,s=2,n=30*(Math.PI/180),o=null,a=null){super(a),this.continueOnOverlaps=!0,this.shapesToTightLooseCouples=new Map,this.multiEdgesSeparation=.5,this.routeMultiEdgesAsBundles=!0,this.UsePolylineEndShortcutting=!0,this.UseInnerPolylingShortcutting=!0,this.AllowedShootingStraightLines=!0,this._overlapsDetected=!1,this.edges=e,this.BundlingSettings=o,this.geomGraph=t,this.LoosePadding=s,this.tightPadding=i,this.coneAngle=n,this.routeMultiEdgesAsBundles=e.length<1e3&&t.deepNodeCount<1e3}static mk6(t,e,i,s,n,o){const a=qt.mk4(t,e,i,s),h=ui.GetShapes(n,o);return a.Initialize(h,s),a}Initialize(t,e){this.rootShapes=t.filter(i=>i.Parents==null||i.Parents.length===0),this.coneAngle=e,this.coneAngle===0&&(this.coneAngle=Math.PI/6)}run(){if(this.edges.length==0||this.geomGraph.isEmpty())return;console.time("SplineRouter");const t=xe.GetShapes(this.geomGraph,this.edges);this.BundlingSettings==null&&this.geomGraph.layoutSettings&&this.geomGraph.layoutSettings.commonSettings.edgeRoutingSettings&&this.geomGraph.layoutSettings.commonSettings.edgeRoutingSettings.bundlingSettings&&(this.BundlingSettings=this.geomGraph.layoutSettings.commonSettings.edgeRoutingSettings.bundlingSettings),this.Initialize(t,this.coneAngle),this.GetOrCreateRoot(),this.RouteOnRoot(),this.RemoveRoot(),console.timeEnd("SplineRouter")}rerouteOnSubsetOfNodes(t){this.RouteMultiEdgesAsBundles=!1,this.edges=Array.from(this.geomGraph.deepEdges).filter(i=>Dn(i.edge,t));const e=xe.GetShapes(this.geomGraph,this.edges);this.rootShapes=e.filter(i=>i.Parents==null||i.Parents.length===0),this.GetOrCreateRoot(),this.CalculateShapeToBoundaries(this.root),this.calcLooseShapesToNodes(),this.CalculatePortsToShapes(),this.rerouteOnActiveNodes(t),this.RemoveRoot()}calcLooseShapesToNodes(){if(this.loosePolylinesToNodes=new Map,!this.OverlapsDetected){for(const[i,s]of this.shapesToTightLooseCouples)this.loosePolylinesToNodes.set(s.LooseShape.BoundaryCurve,new Set([i.node.node]));return}const t=en(this.geomGraph.nodesBreadthFirst,i=>i.boundingBox),e=this.GetLooseHierarchy();Te(e,t,(i,s)=>{if(w.CurveIsInsideOther(s.boundaryCurve,i)){let n=this.loosePolylinesToNodes.get(i);for(const o of s.getAncestors())if(!(o instanceof Gt&&o.parent==null)&&o.boundaryCurve!=null&&w.CurveIsInsideOther(o.boundaryCurve,i))return;n==null&&this.loosePolylinesToNodes.set(i,n=new Set),n.add(s.node)}})}RouteOnRoot(){os(0),this.CalculatePortsToShapes(),this.CalculatePortsToEnterableShapes(),this.CalculateShapeToBoundaries(this.root),!(this.OverlapsDetected&&!this.ContinueOnOverlaps)&&(this.BindLooseShapes(),this.SetLoosePolylinesForAnywherePorts(),this.CalculateVisibilityGraph(),this.RouteOnVisGraph())}CalculatePortsToEnterableShapes(){this.portsToEnterableShapes=new Map;for(const[t,e]of this.portsToShapes){const i=new Set;qt.EdgesAttachedToPortAvoidTheNode(t)||i.add(e),this.portsToEnterableShapes.set(t,i)}for(const t of this.rootShapes)for(const e of t.Descendants())for(const i of e.Ports){const s=this.portsToEnterableShapes.get(i);bs(s,Array.from(e.Ancestors()).filter(n=>n.BoundaryCurve!=null))}}static EdgesAttachedToPortAvoidTheNode(t){return t instanceof F||t instanceof Ie}SetLoosePolylinesForAnywherePorts(){for(const[t,e]of this.shapesToTightLooseCouples)for(const i of t.Ports){if(i instanceof Wt){const n=i;n.LoosePolyline=e.LooseShape.BoundaryCurve}if(i instanceof Ie){const n=i;n.LoosePolyline=e.LooseShape.BoundaryCurve}}}BindLooseShapes(){this.looseRoot=new _i;for(const t of this.root.Children){const e=this.shapesToTightLooseCouples.get(t).LooseShape;this.BindLooseShapesUnderShape(t),this.looseRoot.AddChild(e)}}BindLooseShapesUnderShape(t){const e=this.shapesToTightLooseCouples.get(t).LooseShape;for(const i of t.Children){const s=this.shapesToTightLooseCouples.get(i).LooseShape;e.AddChild(s),this.BindLooseShapesUnderShape(i)}}CalculateShapeToBoundaries(t){if(this.ProgressStep(),t.Children.length===0)return;for(const i of t.Children)this.CalculateShapeToBoundaries(i);const e=Number.POSITIVE_INFINITY;this.obstacleCalculator=new Ns(t,this.tightPadding,Math.min(this.AdjustedLoosePadding,e),this.shapesToTightLooseCouples),this.obstacleCalculator.Calculate(.01),this.OverlapsDetected||(this.OverlapsDetected=this.obstacleCalculator.OverlapsDetected)}get OverlapsDetected(){return this._overlapsDetected}set OverlapsDetected(t){this._overlapsDetected=t}get AdjustedLoosePadding(){return this.BundlingSettings==null?this.LoosePadding:this.LoosePadding*hr.SuperLoosePaddingCoefficient}GroupEdgesByPassport(){const t=new Array;for(const e of this.edges){const i=this.EdgePassport(e);let s=t.find(n=>sn(n.passport,i));s||(s={passport:i,edges:[]},t.push(s)),s.edges.push(e)}return t}RouteOnVisGraph(){if(this.ancestorSets=qt.GetAncestorSetsMap(Array.from(this.root.Descendants())),this.BundlingSettings==null){const t=this.GroupEdgesByPassport();for(let e=0;e<t.length;e++){const i=t[e],s=i.passport,n=this.GetObstaclesFromPassport(s),o=this.CreateInteractiveEdgeRouter(Array.from(n));this.RouteEdgesWithTheSamePassport(i,o,n)}}else this.RouteBundles()}rerouteOnActiveNodes(t){if(this.ancestorSets=qt.GetAncestorSetsMap(Array.from(this.root.Descendants())),this.BundlingSettings==null)for(const e of this.GroupEdgesByPassport()){const i=e.passport,s=this.GetObstaclesFromPassport(i),n=new Set;for(const a of s){const h=this.LooseShapeOfOriginalShape(a);for(const u of this.loosePolylinesToNodes.get(h.BoundaryCurve))t.has(u)&&n.add(a)}const o=this.CreateInteractiveEdgeRouter(Array.from(n));this.rerouteEdgesWithTheSamePassportActiveNodes(e,o,n,t)}else this.RouteBundles()}getDebugCurvesFromEdgesAndCdt(t){const e=Array.from(this.geomGraph.deepEdges).map(i=>i.curve).filter(i=>i!=null).filter(i=>i.count>5).map(i=>wt.mkDebugCurveTWCI(200,1,"Red",i));for(const i of t.PointsToSites.values())for(const s of i.Edges)e.push(wt.mkDebugCurveTWCI(200,.5,s.constrained?"Blue":"Green",N.mkPP(s.lowerSite.point,s.upperSite.point)));return e}RouteEdgesWithTheSamePassport(t,e,i){const s={regularEdges:[],multiEdges:[]};try{const n=this.getCdtFromPassport(i);e.pathOptimizer.setCdt(n)}catch{e.pathOptimizer.setCdt(null)}if(this.RouteMultiEdgesAsBundles){if(this.SplitOnRegularAndMultiedges(t.edges,s),s.regularEdges.length>0)for(let n=0;n<s.regularEdges.length;n++)this.routeEdge(e,s.regularEdges[n]);s.multiEdges!=null&&(this.ScaleDownLooseHierarchy(e,i),this.RouteMultiEdges(s.multiEdges,e,t.passport))}else for(let n=0;n<t.edges.length;n++)this.routeEdge(e,t.edges[n])}rerouteEdgesWithTheSamePassportActiveNodes(t,e,i,s){const n={regularEdges:[],multiEdges:[]};try{const o=this.getCdtFromPassport(i);e.pathOptimizer.setCdt(o)}catch(o){console.log(o),e.pathOptimizer.setCdt(null)}if(this.RouteMultiEdgesAsBundles){if(this.SplitOnRegularAndMultiedges(t.edges,n),n.regularEdges.length>0)for(let o=0;o<n.regularEdges.length;o++){const a=n.regularEdges[o];Mt.assert(Dn(a.edge,s)),this.rerouteEdge(e,a)}n.multiEdges!=null&&(this.ScaleDownLooseHierarchy(e,i),this.RouteMultiEdges(n.multiEdges,e,t.passport))}else for(let o=0;o<t.edges.length;o++){const a=t.edges[o];Dn(a.edge,s)&&this.rerouteEdge(e,a)}}rerouteEdge(t,e){try{t.rerouteEdge(e),Bt.trimSplineAndCalculateArrowheadsII(e,e.sourcePort.Curve,e.targetPort.Curve,e.curve,!1)}catch{console.log("failed")}}getCdtFromPassport(t){const e=new Set,i=[],s=X.mkEmpty();for(const a of t){const h=this.LoosePolyOfOriginalShape(a);if(h!=null){e.add(h);for(const u of a.Ports)i.push(u.Location);s.addRecSelf(h.boundingBox)}}s.pad(Math.max(s.diagonal/4,100));const n=Array.from(e);n.push(s.perimeter());const o=new ie(i,n,[]);return o.run(),o}get RouteMultiEdgesAsBundles(){return this.routeMultiEdgesAsBundles}set RouteMultiEdgesAsBundles(t){this.routeMultiEdgesAsBundles=t}routeEdge(t,e){const i=this.makeTransparentShapesOfEdgeAndGetTheShapes(e);this.ProgressStep(),this.RouteEdgeInternal(e,t),qt.SetTransparency(i,!1)}ScaleDownLooseHierarchy(t,e){const i=new Array;for(const s of e){const n=this.shapesToTightLooseCouples.get(s);i.push(ut.LoosePolylineWithFewCorners(n.TightPolyline,n.Distance/1.1,0))}t.LooseHierarchy=qt.CreateLooseObstacleHierarachy(i),t.ClearActivePolygons(),t.AddActivePolygons(i.map(s=>new Pe(s)))}RouteMultiEdges(t,e,i){const s=[];for(const a of i)for(const h of a.Children)s.push(h.BoundaryCurve);const n=new re;n.InkImportance=1e-5,n.EdgeSeparation=this.MultiEdgesSeparation,new eo(t,e,s,n,a=>this.makeTransparentShapesOfEdgeAndGetTheShapes(a)).run()}SplitOnRegularAndMultiedges(t,e){const i=new ls;for(const s of t)qt.IsEdgeToParent(s)?e.regularEdges.push(s):qt.RegisterInPortLocationsToEdges(s,i);e.multiEdges=null;for(const s of i.values())s.length===1||this.OverlapsDetected?Bi(e.regularEdges,s):(e.multiEdges==null&&(e.multiEdges=new Array),e.multiEdges.push(s))}static RegisterInPortLocationsToEdges(t,e){let i;const s=new fe(t.sourcePort.Location,t.targetPort.Location);i=e.get(s),i||(i=new Array,e.set(s,i)),i.push(t)}static IsEdgeToParent(t){return t.sourcePort instanceof Wt||t.targetPort instanceof Wt}CreateInteractiveEdgeRouter(t){const e=new Set(t.map(s=>this.shapesToTightLooseCouples.get(s).LooseShape.BoundaryCurve)),i=new ct(this.cancelToken);return i.pathOptimizer=new kh,i.ObstacleCalculator=new ut(t.map(s=>s.BoundaryCurve),this.tightPadding,this.loosePadding,!1),i.VisibilityGraph=this.visGraph,i.TightHierarchy=this.CreateTightObstacleHierarachy(t),i.LooseHierarchy=qt.CreateLooseObstacleHierarachy(Array.from(e)),i.UseSpanner=!0,i.LookForRoundedVertices=!0,i.TightPadding=this.tightPadding,i.LoosePadding=this.LoosePadding,i.UseEdgeLengthMultiplier=this.UseEdgeLengthMultiplier,i.UsePolylineEndShortcutting=this.UsePolylineEndShortcutting,i.UseInnerPolylingShortcutting=this.UseInnerPolylingShortcutting,i.AllowedShootingStraightLines=this.AllowedShootingStraightLines,i.AddActivePolygons(Array.from(e).map(s=>new Pe(s))),i}GetObstaclesFromPassport(t){if(t.size===0)return new Set(this.root.Children);const e=this.GetCommonAncestorsAbovePassport(t),i=this.GetAllAncestors(t),s=new Set;for(const a of t)for(const h of a.Children)i.has(h)||s.add(h);const n=Ki(new Set(t),s),o=new Ge.o;for(const a of t)e.has(a)||o.enqueue(a);for(;o.length>0;){const a=o.dequeue();for(const h of a.Parents){for(const u of h.Children)i.has(u)||s.add(u);!e.has(h)&&!n.has(h)&&(o.enqueue(h),n.add(h))}}return s}GetAllAncestors(t){if(t.size===0)return new Set;let e=new Set(t);for(const i of t)e=Ki(e,this.ancestorSets.get(i));return e}GetCommonAncestorsAbovePassport(t){if(t.size===0)return new Set;const e=Array.from(t);let i=this.ancestorSets.get(e[0]);for(let s=1;s<e.length;s++){const n=e[s];i=Li(i,this.ancestorSets.get(n))}return i}RouteBundles(){this.ScaleLooseShapesDown(),this.CalculateEdgeEnterablePolylines();const t=this.GetLooseHierarchy(),e=Ia(t),i=new fs(n=>this.makeTransparentShapesOfEdgeAndGetTheShapes(n),e,this.FindCdtGates(e));new hr(this.edges,i,this.visGraph,this.BundlingSettings,this.LoosePadding,this.GetTightHierarchy(),t,this.enterableLoose,this.enterableTight,n=>this.LoosePolyOfOriginalShape(this.portsToShapes.get(n))).run()}CreateTheMapToParentLooseShapes(t,e){for(const i of t.Children){const n=this.shapesToTightLooseCouples.get(i).LooseShape.BoundaryCurve;e.set(n,t),this.CreateTheMapToParentLooseShapes(i,e)}}FindCdtGates(t){const e=new Map;this.CreateTheMapToParentLooseShapes(this.root,e);const i=new Set;for(const s of t.PointsToSites.values())for(const n of s.Edges){if(n.CwTriangle==null&&n.CcwTriangle==null)continue;const o=s.Owner,a=n.lowerSite.Owner;if(o===a)continue;const h=e.get(o);if(h){const u=e.get(a);h===u&&i.add(n)}}return i}CalculateEdgeEnterablePolylines(){this.enterableLoose=new Map,this.enterableTight=new Map;for(const t of this.edges){const e=new Set,i=new Set;this.GetEdgeEnterablePolylines(t,e,i),this.enterableLoose.set(t,e),this.enterableTight.set(t,i)}}GetEdgeEnterablePolylines(t,e,i){const s=this.portsToShapes.get(t.sourcePort),n=this.portsToShapes.get(t.targetPort);s!==this.root&&this.GetEnterablesForShape(s,e,i),n!==this.root&&this.GetEnterablesForShape(n,e,i)}GetEnterablesForShape(t,e,i){for(const s of this.ancestorSets.get(t)){const n=this.LoosePolyOfOriginalShape(s);n&&e.add(n);const o=this.TightPolyOfOriginalShape(s);o&&i.add(o)}}GetTightHierarchy(){return $t(Array.from(this.shapesToTightLooseCouples.values()).map(t=>he(t.TightPolyline,t.TightPolyline.boundingBox)))}GetLooseHierarchy(){const t=new Set;for(const e of this.shapesToTightLooseCouples.values())t.add(e.LooseShape.BoundaryCurve);return $t(Array.from(t).map(e=>he(e,e.boundingBox)))}ScaleLooseShapesDown(){for(const[,t]of this.shapesToTightLooseCouples)t.LooseShape.BoundaryCurve=ut.LoosePolylineWithFewCorners(t.TightPolyline,t.Distance/hr.SuperLoosePaddingCoefficient,0)}EdgePassport(t){const e=new Set,i=this.portsToShapes.get(t.sourcePort),s=this.portsToShapes.get(t.targetPort);return this.IsAncestor(i,s)?(bs(e,s.Parents),e.add(i),e):this.IsAncestor(s,i)?(bs(e,i.Parents),e.add(s),e):(i!==this.looseRoot&&bs(e,i.Parents),s!==this.looseRoot&&bs(e,s.Parents),e)}*AllPorts(){for(const t of this.edges)yield t.sourcePort,yield t.targetPort}CalculatePortsToShapes(){this.portsToShapes=new Map;for(const t of this.root.Descendants())for(const e of t.Ports)this.portsToShapes.set(e,t);for(const t of this.AllPorts())this.portsToShapes.has(t)||(this.root.Ports.add(t),this.portsToShapes.set(t,this.root))}RouteEdgeInternal(t,e){const i=new Array;t.sourcePort instanceof Wt||Bi(i,this.AddVisibilityEdgesFromPort(t.sourcePort)),t.targetPort instanceof Wt||Bi(i,this.AddVisibilityEdgesFromPort(t.targetPort));const s={smoothedPolyline:null};if(c.closeDistEps(t.sourcePort.Location,t.targetPort.Location)?t.curve=we.RouteSelfEdge(t.sourcePort.Curve,Math.max(this.LoosePadding*2,t.GetMaxArrowheadLength()),s):t.curve=e.RouteSplineFromPortToPortWhenTheWholeGraphIsReady(t.sourcePort,t.targetPort,!0,s),t.smoothedPolyline=null,t.curve==null)throw new Error;for(const n of i)Xt.RemoveEdge(n);Bt.trimSplineAndCalculateArrowheadsII(t,t.sourcePort.Curve,t.targetPort.Curve,t.curve,!1)}*AddVisibilityEdgesFromPort(t){let e,i;if(t instanceof F||!(e=this.portsToShapes.get(t))||!(i=this.shapesToTightLooseCouples.get(e)))return;const s=i.LooseShape;for(const n of s.BoundaryCurve)this.visGraph.FindEdgePP(t.Location,n)==null&&(yield this.visGraph.AddEdgePP(t.Location,n))}makeTransparentShapesOfEdgeAndGetTheShapes(t){const e=this.portsToShapes.get(t.sourcePort),i=this.portsToShapes.get(t.targetPort),s=new Array;for(const n of this.GetTransparentShapes(t.sourcePort,t.targetPort,e,i))n!=null&&s.push(this.LooseShapeOfOriginalShape(n));for(const n of this.portsToEnterableShapes.get(t.sourcePort))s.push(this.LooseShapeOfOriginalShape(n));for(const n of this.portsToEnterableShapes.get(t.targetPort))s.push(this.LooseShapeOfOriginalShape(n));return qt.SetTransparency(s,!0),s}LooseShapeOfOriginalShape(t){return t===this.root?this.looseRoot:this.shapesToTightLooseCouples.get(t).LooseShape}LoosePolyOfOriginalShape(t){return this.LooseShapeOfOriginalShape(t).BoundaryCurve}TightPolyOfOriginalShape(t){return t===this.root?null:this.shapesToTightLooseCouples.get(t).TightPolyline}*GetTransparentShapes(t,e,i,s){for(const n of this.ancestorSets.get(i))yield n;for(const n of this.ancestorSets.get(s))yield n;qt.EdgesAttachedToPortAvoidTheNode(t)||(yield i),qt.EdgesAttachedToPortAvoidTheNode(e)||(yield s)}static SetTransparency(t,e){for(const i of t)i.IsTransparent=e}IsAncestor(t,e){let i;return e!=null&&(i=this.ancestorSets.get(e))!=null&&i.has(t)}static CreateLooseObstacleHierarachy(t){return $t(t.map(e=>he(e,e.boundingBox)))}CreateTightObstacleHierarachy(t){const e=t.map(i=>this.shapesToTightLooseCouples.get(i).TightPolyline);return $t(e.map(i=>he(i,i.boundingBox)))}CalculateVisibilityGraph(){const t=this.LineSweeperPorts!=null?Yt.mk(this.LineSweeperPorts):new Yt;this.ProcessHookAnyWherePorts(t),this.portRTree=xs(Array.from(t.values()).map(e=>[X.rectangleOnPoint(e),e])),this.visGraph=new Xt,this.FillVisibilityGraphUnderShape(this.root)}ProcessHookAnyWherePorts(t){for(const e of this.edges)e.sourcePort instanceof Wt||e.sourcePort instanceof Ie||t.add(e.sourcePort.Location),e.targetPort instanceof Wt||e.targetPort instanceof Ie||t.add(e.targetPort.Location)}FillVisibilityGraphUnderShape(t){const e=t.Children;for(let d=0;d<e.length;d++){const m=e[d];this.FillVisibilityGraphUnderShape(m)}const i=this.shapesToTightLooseCouples.get(t),s=i?i.LooseShape.BoundaryCurve:null,n=i?i.LooseShape:this.looseRoot,o=new Set(n.Children.map(d=>d.BoundaryCurve)),a=this.RemoveInsidePortsAndSplitBoundaryIfNeeded(s);let h=new Xt,u=yi.mk([],h,this.coneAngle,a,s);u.run(),h=new Xt,u=yi.mk(Array.from(o),h,this.coneAngle,a,s),u.run(),this.ProgressStep();for(const d of h.Edges)this.TryToCreateNewEdgeAndSetIsPassable(d,n);this.AddBoundaryEdgesToVisGraph(s)}TryToCreateNewEdgeAndSetIsPassable(t,e){let i=this.visGraph.FindEdgePP(t.SourcePoint,t.TargetPoint);i==null&&(i=this.visGraph.AddEdgePP(t.SourcePoint,t.TargetPoint),e!=null&&(i.IsPassable=()=>e.IsTransparent))}AddBoundaryEdgesToVisGraph(t){if(t==null)return;let e;for(let i=t.startPoint;e=i.nextOnPolyline,this.visGraph.AddEdgePP(i.point,e.point),e!==t.startPoint;i=e);}RemoveInsidePortsAndSplitBoundaryIfNeeded(t){const e=new Yt;if(t==null){for(const n of this.portRTree.GetAllLeaves())e.add(n);return this.portRTree.clear(),e}const i=t.boundingBox,s=this.portRTree.GetAllIntersecting(i);for(const n of s)switch(w.PointRelativeToCurveLocation(n,t)){case at.Inside:e.add(n),this.portRTree.Remove(X.rectangleOnPoint(n),n);break;case at.Boundary:this.portRTree.Remove(X.rectangleOnPoint(n),n);const o=qt.FindPointOnPolylineToInsertAfter(t,n);if(o!=null)rt.InsertPointIntoPolylineAfter(t,o,n);else throw new Error;break}return e}static FindPointOnPolylineToInsertAfter(t,e){for(let i=t.startPoint;;){const s=i.nextOnPolyline;if(c.closeDistEps(e,i.point)||c.closeDistEps(e,s.point))return null;const n=c.distToLineSegment(e,i.point,s.point).dist;if(R(n,0))return i;if(i=s,i===t.startPoint)throw new Error}}GetOrCreateRoot(){if(this.rootShapes.length===1){const t=this.rootShapes[0];if(t.BoundaryCurve==null){this.root=t;return}}this.rootWasCreated=!0,this.root=new _i(null);for(const t of this.rootShapes)this.root.AddChild(t)}RemoveRoot(){if(this.rootWasCreated){for(const t of this.rootShapes)t.RemoveParent(this.root);this.root=null,this.rootWasCreated=!1}}static GetAncestorSetsMap(t){const e=new Map;for(const i of t.filter(s=>!e.has(s)))e.set(i,qt.GetAncestorSet(i,e));return e}static GetAncestorSet(t,e){const i=new Set(t.Parents);for(const s of t.Parents){let n=e.get(s);n||e.set(s,n=qt.GetAncestorSet(s,e));for(const o of n)i.add(o)}return i}static CreatePortsIfNeeded(t){for(const e of t){if(e.sourcePort==null){const i=e;new ke(()=>i.source.boundaryCurve,()=>i.source.center,new c(0,0))}if(e.targetPort==null){const i=e;new ke(()=>i.target.boundaryCurve,()=>i.target.center,new c(0,0))}}}}function Vh(l,t,e){const i=ka(l);new qt(l,t,i.Padding,i.PolylinePadding,i.coneAngle,i.bundlingSettings,e).run()}class nc{getTileData(t,e,i){const s=this.levels[i];return s?s.get(t,e):null}*getTilesOfLevel(t){const e=this.levels[t];if(e!=null)for(const[i,s]of e.keyValues())yield{x:i.x,y:i.y,data:s}}constructor(t,e){this.numberOfNodesOnLevel=[],this.nodeScales=[],this.tileCapacity=5e3,this.levels=[],this.nodeIndexInSortedNodes=new Map,this.geomGraph=t,this.topLevelTileRect=e,this.tileSizes=[],this.tileSizes.push(e.size)}getMinTileSize(){let t=0,e=0,i=0;for(const s of this.geomGraph.nodesBreadthFirst)s instanceof GeomGraph||(i==0?(t=s.width,e=s.height):(t=(i*t+s.width)/(i+1),e=(i*e+s.height)/(i+1)),i++);return new Size(t*10,e*10)}fillTheLowestLayer(){const t=new IntPairMap,e=new Tile(this.topLevelTileRect),i=e.arrowheads,s=e.labels;for(const o of this.geomGraph.graph.deepEdges)n(o);e.nodes=Array.from(this.geomGraph.nodesBreadthFirst),t.set(0,0,e),this.levels.push(t);function n(o){const a=GeomEdge.getGeom(o),h=GeomEdge.getGeom(o).curve;if(h instanceof Curve)for(const u of h.segs)e.addElement({edge:o,curve:u,startPar:u.parStart,endPar:u.parEnd});else e.addElement({edge:o,curve:h,startPar:h.parStart,endPar:h.parEnd});a.sourceArrowhead&&i.push({edge:a.edge,tip:a.sourceArrowhead.tipPosition,base:a.curve.start}),a.targetArrowhead&&i.push({edge:a.edge,tip:a.targetArrowhead.tipPosition,base:a.curve.end}),a.label&&s.push(a.label)}}buildUpToLevel(t){if(this.fillTheLowestLayer(),this.minTileSize=this.getMinTileSize(),this.pageRank=pagerank(this.geomGraph.graph,.85),!this.needToSubdivide())return 1;for(let i=1;i<=t&&!this.subdivideLevel(i);i++);this.sortedNodes=Array.from(this.pageRank.keys()).sort(this.compareByPagerank.bind(this));for(let i=0;i<this.sortedNodes.length;i++)this.nodeIndexInSortedNodes.set(this.sortedNodes[i],i);for(let i=0;i<this.levels.length-1;i++)this.numberOfNodesOnLevel.push(this.filterOutEntities(this.levels[i],i));this.numberOfNodesOnLevel.push(this.sortedNodes.length);const e=new SplineRouter(this.geomGraph,[]);for(let i=this.levels.length-2;i>=0;i--){const s=this.setOfNodesOnTheLevel(i);e.rerouteOnSubsetOfNodes(s),this.regenerateCurveClipsUpToLevel(i,s)}return this.calculateNodeRank(),this.levels.length}keepInsideGraphBoundingBox(t){const e=this.geomGraph.boundingBox,i=t.width/2,s=t.height/2;return Math.min((t.center.x-e.left)/i,(e.top-t.center.y)/s,(e.right-t.center.x)/i,(t.center.y-e.bottom)/s)}diminishScaleToAvoidTree(t,e,i){Assert.assert(e.intersects(i));let s;const n=i.center.x,o=i.center.y,a=i.height/2,h=i.width/2;if(n<e.left)s=(e.left-n)/a;else if(n>e.right)s=(n-e.right)/a;else return 1;let u;if(o<e.bottom)u=(e.bottom-o)/h;else if(o>e.top)u=(o-e.top)/h;else return s;return Math.min(s,u)}needToSubdivide(){let t=!1;for(const e of this.levels[0].values())if(e.entityCount>this.tileCapacity){t=!0;break}return t}setOfNodesOnTheLevel(t){const e=new Set;for(const i of this.levels[t].values())for(const s of i.nodes)e.add(s.node);return e}regenerateCurveClipsUpToLevel(t,e){this.clearCurveClipsInLevelsUpTo(t);for(const i of this.levels[0].values())this.regenerateCurveClipsUnderTileUpToLevel(i,t,e)}clearCurveClipsInLevelsUpTo(t){for(let e=0;e<=t;e++)for(const i of this.levels[e].values())i.initCurveClips()}regenerateCurveClipsUnderTileUpToLevel(t,e,i){t.arrowheads=[],t.initCurveClips();for(const s of this.geomGraph.deepEdges)if(edgeNodesBelongToSet(s.edge,i)){if(s.curve instanceof Curve)for(const n of s.curve.segs)t.addElement({edge:s.edge,curve:n,startPar:n.parStart,endPar:n.parEnd});else t.addElement({edge:s.edge,curve:s.curve,startPar:s.curve.parStart,endPar:s.curve.parEnd});s.sourceArrowhead&&t.arrowheads.push({edge:s.edge,tip:s.sourceArrowhead.tipPosition,base:s.curve.start}),s.targetArrowhead&&t.arrowheads.push({edge:s.edge,tip:s.targetArrowhead.tipPosition,base:s.curve.end})}for(let s=1;s<=e;s++)this.regenerateCurveClipsWhenPreviosLayerIsDone(s),this.removeEmptyTiles(s)}removeEmptyTiles(t){const e=this.levels[t],i=[];for(const[s,n]of e.keyValues())n.isEmpty()&&i.push(s);for(const s of i)e.delete(s.x,s.y)}regenerateCurveClipsWhenPreviosLayerIsDone(t){for(const[e,i]of this.levels[t-1].keyValues())this.subdivideTile(e,t,i,!0)}calculateNodeRank(){this.nodeRank=new Map;const t=this.sortedNodes.length,e=Math.log10(t);for(let i=0;i<t;i++)this.nodeRank.set(this.sortedNodes[i],e-Math.log10(i+1))}compareByPagerank(t,e){return this.pageRank.get(e)-this.pageRank.get(t)}filterOutEntities(t,e){const i=this.transferDataOfLevelToMap(t);let s=0;for(;s<this.sortedNodes.length;s++){const n=this.sortedNodes[s];if(!this.addNodeToLevel(t,n,i))break}return this.removeEmptyTiles(e),s}addNodeToLevel(t,e,i){const s=i.get(e);for(const o of s)if(o.tile.entityCount>=this.tileCapacity)return!1;for(const o of s){const a=o.tile,h=o.data;a.addElement(h)}for(const o of e.selfEdges){const a=i.get(o);for(const h of a){const u=h.tile,d=h.data;u.addElement(d)}if(o.label)for(const h of i.get(o.label)){const u=h.tile,d=h.data;u.addElement(d)}}const n=this.nodeIndexInSortedNodes.get(e);for(const o of e.inEdges){const a=o.source;if(!(this.nodeIndexInSortedNodes.get(a)>n)){for(const u of i.get(o)){const d=u.tile,m=u.data;d.addElement(m)}if(o.label)for(const u of i.get(o.label)){const d=u.tile,m=u.data;d.addElement(m)}}}for(const o of e.outEdges){const a=o.target;if(!(this.nodeIndexInSortedNodes.get(a)>n)){for(const u of i.get(o)){const d=u.tile,m=u.data;d.addElement(m)}if(o.label&&i.get(o.label))for(const u of i.get(o.label)){const d=u.tile,m=u.data;d.addElement(m)}}}return!0}transferDataOfLevelToMap(t){const e=new Map;for(const s of t.values()){for(const n of s.curveClips){const o=n.edge;i(o).push({tile:s,data:n})}for(const n of s.labels){const o=n.parent.edge;i(o).push({tile:s,data:n})}for(const n of s.nodes){const o=n.node;i(o).push({tile:s,data:n})}for(const n of s.arrowheads){const o=n.edge;i(o).push({tile:s,data:n})}s.clear()}return e;function i(s){let n=e.get(s);return n||e.set(s,n=new Array),n}}subdivideLevel(t){console.log("subdivideLevel",t);const e=Math.pow(2,t);if(this.levels[t]=new IntPairMap,this.subdivideTilesOnLevel(t))return console.log("done subdividing at level",t,"because each tile contains less than",this.tileCapacity),!0;const{w:s,h:n}=this.getWHOnLevel(t);return s<=this.minTileSize.width&&n<=this.minTileSize.height?(console.log("done subdividing at level",t," because of tile size = ",s,n,"is less than ",this.minTileSize),!0):!1}countClips(t){let e=0;for(const i of this.levels[t].values())e+=i.curveClips.length;return e}getWHOnLevel(t){for(let e=this.tileSizes.length;e<=t;e++){const i=this.tileSizes[e-1];this.tileSizes.push(new Size(i.width/2,i.height/2))}return{w:this.tileSizes[t].width,h:this.tileSizes[t].height}}subdivideTilesOnLevel(t){let i=!0;for(const[s,n]of this.levels[t-1].keyValues()){const o=this.subdivideTile(s,t,n,!1);i&&(i=o.allSmall)}return this.removeEmptyTiles(t),console.log("generated",this.levels[t].size,"tiles"),i}subdivideTile(t,e,i,s){const{w:n,h:o}=this.getWHOnLevel(e),a=this.levels[e],h=t.x,u=t.y,d=this.topLevelTileRect.left+h*n*2,m=this.topLevelTileRect.bottom+u*o*2,y=new Array(4);for(let Q=0;Q<2;Q++)for(let dt=0;dt<2;dt++)y[Q*2+dt]=new IntPair(h*2+Q,u*2+dt);s||this.generateSubtilesWithoutTileClips(d,n,m,o,y,i,e);const E=new LineSegment(d,m+o,d+2*n,m+o),T=new LineSegment(d+n,m,d+n,m+2*o);tt();let B=0,H=!0;for(const Q of y){const dt=a.get(Q.x,Q.y);dt!=null&&(B++,dt.entityCount>this.tileCapacity&&(H=!1))}return{count:B,allSmall:H};function tt(){for(const Q of i.curveClips){const dt=Q.curve,It=lt(dt,Q.startPar,Q.endPar);if(Assert.assert(It.length>=2),It.length==2){const Tt=(It[0]+It[1])/2,oe=dt.value(Tt),Ss=oe.x<=d+n?0:1,pr=oe.y<=m+o?0:1,oo=2*Ss+pr,ao=y[oo];let Xs=a.getI(ao);if(!Xs){const Ks=d+Ss*n,mr=m+pr*o;Xs=new Tile(new Rectangle({left:Ks,bottom:mr,top:mr+o,right:Ks+n})),a.setPair(ao,Xs)}Xs.addCurveClip({curve:dt,edge:Q.edge,startPar:It[0],endPar:It[1]})}else for(let Tt=0;Tt<It.length-1;Tt++){const oe=(It[Tt]+It[Tt+1])/2,Ss=dt.value(oe),pr=Ss.x<=d+n?0:1,oo=Ss.y<=m+o?0:1,ao=2*pr+oo,Xs=y[ao];let Ks=a.getI(Xs);if(!Ks){const mr=d+pr*n,dl=m+oo*o;Ks=new Tile(new Rectangle({left:mr,bottom:dl,top:dl+o,right:mr+n})),a.setPair(Xs,Ks)}Ks.addCurveClip({curve:dt,edge:Q.edge,startPar:It[Tt],endPar:It[Tt+1]})}}}function lt(Q,dt,It){let Tt=Array.from(Curve.getAllIntersections(Q,E,!0)).concat(Array.from(Curve.getAllIntersections(Q,T,!0))).map(oe=>oe.par0);return Tt.sort((oe,Ss)=>oe-Ss),[dt].concat(Tt.filter(oe=>oe>=dt&&oe<=It)).concat(It)}}addSubtilesToLevel(t,e,i,s,n){for(let o=0;o<2;o++)for(let a=0;a<2;a++){const h=t[o*2+a];h.isEmpty()||(e.set(2*i+o,2*s+a,h),n&&h.entityCount>this.tileCapacity&&(n=!1))}return n}generateSubtilesWithoutTileClips(t,e,i,s,n,o,a){let h=0;for(let u=0;u<2;u++)for(let d=0;d<2;d++){const m=new Rectangle({left:t+e*u,right:t+e*(u+1),bottom:i+s*d,top:i+s*(d+1)}),y=this.generateOneSubtileExceptEdgeClips(o,m);y&&this.levels[a].set(n[h].x,n[h].y,y),h++}}innerClips(t,e,i){const s=[],n=Array.from(Curve.getAllIntersections(t,i,!0)).concat(Array.from(Curve.getAllIntersections(t,e,!0)));n.sort((a,h)=>a.par0-h.par0);const o=[t.parStart];for(let a=0;a<n.length;a++){const h=n[a];h.par0>o[o.length-1]+GeomConstants.distanceEpsilon&&o.push(h.par0)}if(t.parEnd>o[o.length-1]+GeomConstants.distanceEpsilon&&o.push(t.parEnd),o.length<=2)return s.push(t),s;for(let a=0;a<o.length-1;a++)s.push(t.trim(o[a],o[a+1]));return s}generateOneSubtileExceptEdgeClips(t,e){const i=new Tile(e);for(const s of t.nodes)s.boundingBox.intersects(e)&&i.nodes.push(s);for(const s of t.labels)s.boundingBox.intersects(e)&&i.labels.push(s);for(const s of t.arrowheads){const n=Rectangle.mkPP(s.base,s.tip),a=s.tip.sub(s.base).div(3).rotate90Cw();n.add(s.base.add(a)),n.add(s.base.sub(a)),n.intersects(e)&&i.arrowheads.push(s)}return i.isEmpty()?null:i}}class Ua extends vs{toString(){return"label of "+(this.parent?this.parent.toString():"null")}constructor(t){super(),this.parent=t}}class ti{static CreatePortsAndRouteEdges(t,e,i,s,n,o=null){ti.FillRouter(t,e,i,s,n).run(),ti.CreateSelfEdges(Array.from(s).filter(h=>h.sourcePort.Location===h.targetPort.Location),t)}static CreatePortsAndRouteEdges_(t,e,i,s,n,o,a){ti.CreatePortsAndRouteEdges(t,e,i,s,n)}static CreatePortsAndRouteEdges__(t,e,i,s,n,o){ti.CreatePortsAndRouteEdges(t,e,i,s,n)}static FillRouter(t,e,i,s,n){const o=new Map;ti.FillNodeShapesMap(i,s,o);const a=new RectilinearEdgeRouter(o.values(),e,t);for(const h of s)h.sourcePort=ja(o.get(h.source).Ports),h.targetPort=ja(o.get(h.target).Ports),a.AddEdgeGeometryToRoute(h);return a}static FillNodeShapesMap(t,e,i){for(const s of t){const n=ti.CreateShapeWithRelativeNodeAtCenter(s);i.set(s,n)}for(const s of e){let n=s.source;i.has(n)||i.set(n,ti.CreateShapeWithRelativeNodeAtCenter(n)),n=s.target,i.has(n)||i.set(n,ti.CreateShapeWithRelativeNodeAtCenter(n))}}static CreateSelfEdges(t,e){for(const i of t)ti.CreateSimpleEdgeCurveWithGivenFitRadius(i,e)}static CreateSimpleEdgeCurveWithGivenFitRadius(t,e){const i=t.source.center,s=t.target.center;if(t.source===t.target){const n=t.source.boundaryCurve.boundingBox.width/2,o=t.source.boundingBox.height/4;t.smoothedPolyline=ti.CreateUnderlyingPolylineForSelfEdge(i,n,o);for(let a=t.smoothedPolyline.headSite.next;a.next!=null;a=a.next)ti.CalculateCoefficiensUnderSite(a,e);t.curve=t.smoothedPolyline.createCurve()}else t.smoothedPolyline=SmoothedPolyline.mkFromPoints([i,s]),t.curve=t.smoothedPolyline.createCurve();Arrowhead.trimSplineAndCalculateArrowheadsII(t,t.source.boundaryCurve,t.target.boundaryCurve,t.curve,!0)||Arrowhead.createBigEnoughSpline(t)}static CreateSimpleEdgeCurve(t){const e=t.source.center,i=t.target.center;if(t.source===t.target){const s=t.source.boundaryCurve.boundingBox.width/2,n=t.source.boundingBox.height/4;t.smoothedPolyline=ti.CreateUnderlyingPolylineForSelfEdge(e,s,n),t.curve=t.smoothedPolyline.createCurve()}else t.smoothedPolyline=SmoothedPolyline.mkFromPoints([e,i]),t.curve=t.smoothedPolyline.createCurve();Arrowhead.trimSplineAndCalculateArrowheadsII(t,t.source.boundaryCurve,t.target.boundaryCurve,t.curve,!0)||Arrowhead.createBigEnoughSpline(t)}static CreateUnderlyingPolylineForSelfEdge(t,e,i){const s=t.add(new Point(0,i)),n=t.add(new Point(e,i)),o=t.add(new Point(e,i*-1)),a=t.add(new Point(0,i*-1));let h=CornerSite.mkSiteP(t);const u=new SmoothedPolyline(h);return h=CornerSite.mkSiteSP(h,s),h=CornerSite.mkSiteSP(h,n),h=CornerSite.mkSiteSP(h,o),h=CornerSite.mkSiteSP(h,a),CornerSite.mkSiteSP(h,t),u}static CreateShapeWithRelativeNodeAtCenter(t){const e=new RelativeShape(t);return e.Ports.add(new RelativeFloatingPort(()=>t.boundaryCurve,()=>t.center,new Point(0,0))),e}static CalculateCoefficiensUnderSite(t,e){let i=e/t.point.sub(t.prev.point).length;i=Math.min(.5,i),t.previouisBezierCoefficient=i,i=e/t.next.point.sub(t.point).length,i=Math.min(.5,i),t.nextBezierCoefficient=i}}function ja(l){for(const t of l)return t}class ur extends me{constructor(t,e){super(),this.SetEdges(t,e)}}class Wh{*RegularMultiedges(){for(const[t,e]of this.Multiedges.keyValues())t.x!==t.y&&(yield e)}*AllIntEdges(){for(const t of this.Multiedges.values())for(const e of t)yield e}addFeedbackSet(t){for(const e of t){const i=new Et(e.source,e.target),s=new Et(e.target,e.source),n=this.Multiedges.get(i.x,i.y);for(const o of n)o.reverse();if(this.Multiedges.has(s.x,s.y)){const o=this.Multiedges.get(s.x,s.y);for(const a of n)o.push(a)}else this.Multiedges.set(s.x,s.y,n);this.Multiedges.delete(i.x,i.y)}}constructor(t){this.MultipleMiddles=new Set,this.Multiedges=new hs}registerOriginalEdgeInMultiedges(t){let e=this.Multiedges.get(t.source,t.target);e==null&&this.Multiedges.set(t.source,t.target,e=[]),e.push(t)}*SkeletonEdges(){for(const[t,e]of this.Multiedges.keyValues())t.x!==t.y&&(yield e[0])}GetMultiedge(t,e){return this.GetMultiedgeI(new Et(t,e))}GetMultiedgeI(t){return this.Multiedges.has(t.x,t.y)?this.Multiedges.get(t.x,t.y):new Array}}function Vo(l,t){for(let e=0;e<l.length;e++)t[e]=l[e]}class Ui{constructor(t){this.initialize(t)}initialize(t){this.y=t,this.verticesToX=null,this.layers=null}DropEmptyLayers(){const t=new Array(this.Layers.length);let e=0;for(let o=0;o<this.Layers.length;o++)t[o]=e,this.Layers[o].length===0&&e++;if(e===0)return this;const i=new Array(this.y.length);for(let o=0;o<i.length;o++)i[o]=this.y[o]-t[this.y[o]];const s=new Array(this.layers.length-e);for(let o=0;o<this.layers.length;o++)this.layers[o].length>0&&(s[o-t[o]]=Array.from(this.layers[o]));const n=new Ui(i);return n.layers=s,n}updateLayers(t){this.layers==null&&this.InitLayers();for(let e=0;e<this.layers.length;e++)Vo(t[e],this.layers[e]);this.UpdateXFromLayers()}UpdateXFromLayers(){this.layers==null&&this.InitLayers(),this.verticesToX==null&&(this.verticesToX=new Array(this.y.length));for(const t of this.layers){let e=0;for(const i of t)this.verticesToX[i]=e++}}get x(){return this.verticesToX!=null?this.verticesToX:(this.verticesToX=new Array(this.y.length),this.UpdateXFromLayers(),this.verticesToX)}ReversedClone(){const t=new Array(this.y.length),e=this.Layers.length-1;for(let i=0;i<this.y.length;i++)t[i]=e-this.y[i];return new Ui(t)}get Layers(){return this.layers!=null?this.layers:(this.InitLayers(),this.layers)}set Layers(t){this.layers=t}InitLayers(){let t=0;for(const i of this.y)i+1>t&&(t=i+1);const e=new Array(t).fill(0);for(const i of this.y)e[i]++;this.layers=new Array(t);for(let i=0;i<t;i++)this.layers[i]=new Array(e[i]),e[i]=0;for(let i=0;i<this.y.length;i++){const s=this.y[i];this.layers[s][e[s]++]=i}}}function rc(l){if(l.layers==null)return!0;for(const t of l.layers)if(Hh(t))return!1;return!0}function Hh(l){const t=new Set;for(const e of l){if(e==null||t.has(e))return!0;t.add(e)}return!1}class Wo extends Ft{static Balance(t,e,i,s){new Wo(t,e,i,s).run()}constructor(t,e,i,s){super(s),this.jumpers=new Set,this.possibleJumperFeasibleIntervals=new Map,this.nodeCount=i,this.dag=t,this.layering=e,this.Init()}run(){for(;this.jumpers.size>0;)this.Jump(this.ChooseJumper())}Init(){this.CalculateLayerCounts(),this.InitJumpers()}Jump(t){this.jumpers.delete(t);const e=this.possibleJumperFeasibleIntervals.get(t),i=this.CalcJumpInfo(e.x,e.y,t);if(i==null)return;this.layering[t]=i.layerToJumpTo;const s=this.nodeCount[t];this.vertsCounts[i.jumperLayer]-=s,this.vertsCounts[i.layerToJumpTo]+=s,this.UpdateRegionsForPossibleJumpersAndInsertJumpers(i.jumperLayer,t)}IsJumper(t){return this.possibleJumperFeasibleIntervals.has(t)}UpdateRegionsForPossibleJumpersAndInsertJumpers(t,e){const i=new Set;for(const n of this.dag.pred(e))this.IsJumper(n)&&(this.CalculateRegionAndInsertJumper(n),i.add(n));for(const n of this.dag.succ(e))this.IsJumper(n)&&(this.CalculateRegionAndInsertJumper(n),i.add(n));const s=new Array;for(const n of this.possibleJumperFeasibleIntervals)i.has(n[0])||n[1].x>t&&n[1].y<t&&s.push(n[0]);for(const n of s)this.CalculateRegionAndInsertJumper(n)}InitJumpers(){const t=new Array(this.dag.nodeCount).fill(0);for(const e of this.dag.edges)t[e.source]-=e.weight,t[e.target]+=e.weight;this.possibleJumperFeasibleIntervals=new Map;for(let e=0;e<this.dag.nodeCount;e++)t[e]===0&&this.CalculateRegionAndInsertJumper(e)}CalculateRegionAndInsertJumper(t){const e=new Et(this.Up(t),this.Down(t));this.possibleJumperFeasibleIntervals.set(t,e),this.InsertJumper(e.x,e.y,t)}InsertJumper(t,e,i){this.CalcJumpInfo(t,e,i)!=null&&this.jumpers.add(i)}CalcJumpInfo(t,e,i){const s=this.layering[i];let n=-1,o=this.vertsCounts[s]-2*this.nodeCount[i];for(let a=t-1;a>s;a--)this.vertsCounts[a]<o&&(o=this.vertsCounts[a],n=a);for(let a=s-1;a>e;a--)this.vertsCounts[a]<o&&(o=this.vertsCounts[a],n=a);if(n!==-1)return{jumperLayer:s,layerToJumpTo:n}}Up(t){let e=Number.MAX_SAFE_INTEGER;for(const i of this.dag.inEdges[t]){const s=this.layering[i.source]-i.separation+1;s<e&&(e=s)}return e===Number.MAX_SAFE_INTEGER&&(e=this.layering[t]+1),e}Down(t){let e=Number.NEGATIVE_INFINITY;for(const i of this.dag.outEdges[t]){const s=this.layering[i.target]+i.separation-1;s>e&&(e=s)}return e===Number.NEGATIVE_INFINITY&&(e=this.layering[t]-1),e}CalculateLayerCounts(){this.vertsCounts=new Array(Math.max(...this.layering)+1).fill(0);for(const t of this.layering)this.vertsCounts[t]+=this.nodeCount[t]}ChooseJumper(){for(const t of this.jumpers)return t;throw new Error("there are no jumpers to choose")}}class js{constructor(t){this.Initialize(t)}Initialize(t){this.BaseGraph=t,this.totalNumberOfNodes=t.nodeCount;for(const e of this.BaseGraph.edges)if(e.LayerEdges!=null)for(const i of e.LayerEdges){const s=Math.max(i.Source,i.Target)+1;s>this.totalNumberOfNodes&&(this.totalNumberOfNodes=s)}this.firstVirtualNode=Number.POSITIVE_INFINITY;for(const e of this.BaseGraph.edges)if(e.LayerEdges!=null)for(let i=1;i<e.LayerEdges.length;i++){const s=e.LayerEdges[i];this.firstVirtualNode=Math.min(this.firstVirtualNode,s.Source)}this.firstVirtualNode===Number.POSITIVE_INFINITY&&(this.firstVirtualNode=this.BaseGraph.nodeCount,this.totalNumberOfNodes=this.BaseGraph.nodeCount),this.virtualNodesToInEdges=new Array(this.totalNumberOfNodes-this.firstVirtualNode),this.virtualNodesToOutEdges=new Array(this.totalNumberOfNodes-this.firstVirtualNode);for(const e of this.BaseGraph.edges)if(e.LayerSpan>0)for(const i of e.LayerEdges)i.Target!==e.target&&(this.virtualNodesToInEdges[i.Target-this.firstVirtualNode]=i),i.Source!==e.source&&(this.virtualNodesToOutEdges[i.Source-this.firstVirtualNode]=i)}*edges_(){for(const t of this.BaseGraph.edges)if(t.LayerSpan>0)for(const e of t.LayerEdges)yield e}get Edges(){return this.edges_()}*InEdges(t){if(t<this.BaseGraph.nodeCount)for(const e of this.BaseGraph.inEdges[t])e.source!==e.target&&e.LayerEdges!=null&&(yield js.LastEdge(e));else t>=this.firstVirtualNode&&(yield this.InEdgeOfVirtualNode(t))}static LastEdge(t){return t.LayerEdges[t.LayerEdges.length-1]}InEdgeOfVirtualNode(t){return this.virtualNodesToInEdges[t-this.firstVirtualNode]}*OutEdges(t){if(t<this.BaseGraph.nodeCount)for(const e of this.BaseGraph.outEdges[t])e.source!==e.target&&e.LayerEdges!=null&&(yield js.FirstEdge(e));else t>=this.firstVirtualNode&&(yield this.OutEdgeOfVirtualNode(t))}OutDegreeIsMoreThanOne(t){return t<this.BaseGraph.nodeCount?this.BaseGraph.outEdges[t].length>1:!1}InDegreeIsMoreThanOne(t){return t<this.BaseGraph.nodeCount?this.BaseGraph.inEdges[t].length>1:!1}OutEdgeOfVirtualNode(t){return this.virtualNodesToOutEdges[t-this.firstVirtualNode]}static FirstEdge(t){return t.LayerEdges[0]}InEdgesCount(t){return this.RealInEdgesCount(t)}RealInEdgesCount(t){return t<this.BaseGraph.nodeCount?this.BaseGraph.inEdges[t].filter(e=>e.LayerEdges!=null).length:1}OutEdgesCount(t){return this.RealOutEdgesCount(t)}RealOutEdgesCount(t){return t<this.BaseGraph.nodeCount?this.BaseGraph.outEdges[t].filter(e=>e.LayerEdges!=null).length:1}get NodeCount(){return this.totalNumberOfNodes}IsRealNode(t){return t<this.BaseGraph.nodeCount}IsVirtualNode(t){return!this.IsRealNode(t)}ReversedClone(){const t=this.CreateReversedEdges();return new js(new ur(t,this.BaseGraph.nodeCount))}CreateReversedEdges(){const t=new Array;for(const e of this.BaseGraph.edges)e.isSelfEdge()||t.push(e.reversedClone());return t}*Succ(t){for(const e of this.OutEdges(t))yield e.Target}*Pred(t){for(const e of this.InEdges(t))yield e.Source}}class cr{constructor(t,e,i,s){this.la=e,this.database=i,this.layeredGraph=t,this.intGraph=s}static InsertLayers(t,e,i,s){const n=new cr(t,e,i,s);return n.InsertLayers(),{layeredGraph:n.nLayeredGraph,la:n.Nla.DropEmptyLayers()}}get NLayering(){return this.Nla.y}InsertLayers(){this.EditOldLayering(),this.CreateFullLayeredGraph(),this.InitNewLayering(),this.MapVirtualNodesToEdges(),this.FillUnsortedNewOddLayers(),this.WidenOriginalLayers(),this.SortNewOddLayers()}EditOldLayering(){let t=this.intGraph.nodeCount;for(const e of this.database.RegularMultiedges()){let i=0;const s=e[0];if(i=s.LayerSpan*2,i>0){for(const n of s.LayerEdges)n.Target!==s.target&&(t++,this.UpdateOldLayer(t++,n.Target));t+=(i-1)*(e.length-1)+1}}}UpdateOldLayer(t,e){const i=this.la.x[e],s=this.la.y[e],n=this.la.Layers[s];n[i]=t}WidenOriginalLayers(){for(let t=0;t<this.la.Layers.length;t++){const e=this.Nla.Layers[t*2];let i=0;for(const s of this.la.Layers[t]){const n=this.virtNodesToIntEdges[s];if(n!=null){const o=this.NLayering[n.source]-this.NLayering[s],a=this.database.Multiedges.get(n.source,n.target);for(const h of a)if(h!==n){const u=h.LayerEdges[o].Source;e[i]=u,this.Nla.x[u]=i++}else e[i]=s,this.Nla.x[s]=i++}else e[i]=s,this.Nla.x[s]=i++}}}FillUnsortedNewOddLayers(){const t=new Array(this.Nla.Layers.length).fill(0);for(let e=this.intGraph.nodeCount;e<this.nLayeredGraph.NodeCount;e++){const i=this.NLayering[e];i%2===1&&(this.Nla.Layers[i][t[i]++]=e)}}MapVirtualNodesToEdges(){this.virtNodesToIntEdges=new Array(this.NLayering.length);for(const t of this.database.AllIntEdges())if(t.source!==t.target&&t.LayerEdges!=null)for(const e of t.LayerEdges)e.Target!==t.target&&(this.virtNodesToIntEdges[e.Target]=t)}CreateFullLayeredGraph(){this.totalNodes=this.intGraph.nodeCount;for(const t of this.database.RegularMultiedges()){let e=0,i=!0;for(const s of t)if(i&&(i=!1,e=s.LayerSpan*2),e>0){s.LayerEdges=new Array(e);for(let n=0;n<e;n++){const o={currentVV:this.totalNodes},a=Qs.GetSource(o,s,n);this.totalNodes=o.currentVV;const h=Qs.GetTarget(this.totalNodes,s,n,e);s.LayerEdges[n]=new us(a,h,s.CrossingWeight)}cr.RegisterDontStepOnVertex(this.database,s)}}this.nLayeredGraph=new js(this.intGraph)}SortNewOddLayers(){for(let t=1;t<this.Nla.Layers.length;t+=2){const e=new Map,i=this.Nla.Layers[t];for(const o of i){let a=-1;for(const d of this.nLayeredGraph.InEdges(o))a=d.Source;let h=-1;for(const d of this.nLayeredGraph.OutEdges(o))h=d.Target;const u=this.Nla.x[a]+this.Nla.x[h];if(e.has(u)){const d=e.get(u);if(typeof d=="number"){const m=new Array;m.push(d),m.push(o),e.set(u,m)}else d.push(o)}else e.set(u,o)}const s=Array.from(e.entries()).sort((o,a)=>o[0]-a[0]);let n=0;for(const o of s.map(a=>a[1]))if(typeof o=="number")i[n++]=o;else for(const a of o)i[n++]=a;for(let o=0;o<i.length;o++)this.Nla.x[i[o]]=o}}InitNewLayering(){this.Nla=new Ui(new Array(this.totalNodes));for(let i=0;i<this.layeredGraph.NodeCount;i++)this.NLayering[i]=this.la.y[i]*2;for(const[i,s]of this.database.Multiedges.keyValues())if(i.x!==i.y&&this.la.y[i.x]!==this.la.y[i.y]){const n=this.la.y[i.x]*2;for(const o of s){let a=n-1;for(const h of o.LayerEdges)h.Target!==o.target&&(this.NLayering[h.Target]=a--)}}const t=new Array(2*this.la.Layers.length-1),e=new Array(t.length).fill(0);for(const i of this.NLayering)e[i]++;for(let i=0;i<e.length;i++)t[i]=new Array(e[i]);this.Nla=new Ui(this.NLayering),this.Nla.Layers=t}static RegisterDontStepOnVertex(t,e){if(t.Multiedges.get(e.source,e.target).length>1){const i=e.LayerEdges[Math.floor(e.LayerEdges.length/2)];t.MultipleMiddles.add(i.Source)}}}class Qs{get NLayering(){return this.Nla.y}static InsertPaths(t,e,i,s){const n=new Qs(t,e,i,s);return n.InsertPaths(),{layeredGraph:n.NLayeredGraph,la:n.Nla}}constructor(t,e,i,s){this.virtNodesToIntEdges=new Map,this.la=e,this.database=i,this.layeredGraph=t,this.intGraph=s}InsertPaths(){this.CreateFullLayeredGraph(),this.InitNewLayering(),this.MapVirtualNodesToEdges(),this.WidenOriginalLayers()}WidenOriginalLayers(){for(let t=0;t<this.la.Layers.length;t++){const e=this.Nla.Layers[t];let i=0;for(const s of this.la.Layers[t]){const n=this.virtNodesToIntEdges.get(s);if(n!=null){const o=this.NLayering[n.source]-this.NLayering[s],a=this.database.Multiedges.get(n.source,n.target);for(const h of a)if(!this.EdgeIsFlat(h))if(h!==n){const u=h.LayerEdges[o].Source;e[i]=u,this.Nla.x[u]=i++}else e[i]=s,this.Nla.x[s]=i++}else e[i]=s,this.Nla.x[s]=i++}}}EdgeIsFlat(t){return this.la.y[t.source]===this.la.y[t.target]}MapVirtualNodesToEdges(){for(const t of this.database.RegularMultiedges())for(const e of t)if(!this.EdgeIsFlat(e))for(const i of e.LayerEdges)i.Target!==e.target&&this.virtNodesToIntEdges.set(i.Target,e)}CreateFullLayeredGraph(){let t=this.layeredGraph.NodeCount;for(const[e,i]of this.database.Multiedges.keyValues())if(e.x!==e.y){let s=!0,n=0;for(const o of i){if(s)s=!1,n=o.LayerSpan;else if(o.LayerEdges=new Array(n),n===1)o.LayerEdges[0]=new us(o.source,o.target,o.CrossingWeight);else for(let a=0;a<n;a++){const h={currentVV:t},u=Qs.GetSource(h,o,a);t=h.currentVV;const d=Qs.GetTarget(t,o,a,n);o.LayerEdges[a]=new us(u,d,o.CrossingWeight)}cr.RegisterDontStepOnVertex(this.database,o)}}this.NLayeredGraph=new js(this.intGraph)}static GetTarget(t,e,i,s){return i<s-1?t:e.target}static GetSource(t,e,i){return i===0?e.source:t.currentVV++}InitNewLayering(){this.Nla=new Ui(new Array(this.NLayeredGraph.NodeCount));for(let i=0;i<this.layeredGraph.NodeCount;i++)this.NLayering[i]=this.la.y[i];for(const[i,s]of this.database.Multiedges.keyValues())if(i.x!==i.y&&this.la.y[i.x]!==this.la.y[i.y]){let n=0,o=!0;for(const a of s){o&&(o=!1,n=this.la.y[a.source]);let h=n-1;for(const u of a.LayerEdges)this.NLayering[u.Target]=h--}}const t=new Array(this.la.Layers.length),e=new Array(t.length).fill(0);for(const i of this.NLayering)e[i]++;for(let i=0;i<e.length;i++)t[i]=new Array(e[i]);this.Nla=new Ui(this.NLayering),this.Nla.Layers=t}}class dr{constructor(t,e,i){this.numberOfCrossings=e,this.la=t,this.virtVertexStart=i}LayerGroupDisbalance(t,e,i){return e===1?this.LayerGroupDisbalanceWithOrigSeparators(t,i):this.LayerGroupDisbalanceWithVirtSeparators(t,e)}LayerGroupDisbalanceWithVirtSeparators(t,e){let i=0;for(let s=0;s<t.length;){const n=this.CurrentOrigGroupDelta(s,t,e);s=n.i,i+=n.ret}return i}CurrentOrigGroupDelta(t,e,i){let s=0,n=t;for(;n<e.length&&e[n]<this.virtVertexStart;n++)s++;return t=n+1,{ret:Math.abs(i-s),i:t}}LayerGroupDisbalanceWithOrigSeparators(t,e){let i=0;for(let s=0;s<t.length;){const n=this.CurrentVirtGroupDelta(s,t,e);i+=n.ret,s=n.i}return i}CurrentVirtGroupDelta(t,e,i){let s=0,n=t;for(;n<e.length&&e[n]>=this.virtVertexStart;n++)s++;return t=n+1,{ret:Math.abs(i-s),i:t}}static less(t,e){return t.numberOfCrossings<e.numberOfCrossings}static greater(t,e){return t.numberOfCrossings>e.numberOfCrossings}IsPerfect(){return this.numberOfCrossings===0}}class qh{constructor(t){this.x=t}Compare(t,e){const i=this.x[t.Source]-this.x[e.Source];return i!==0?i:this.x[t.Target]-this.x[e.Target]}}class zh{constructor(t){this.x=t}Compare(t,e){const i=this.x[t.Target]-this.x[e.Target];return i!==0?i:this.x[t.Source]-this.x[e.Source]}}function io(){return Vi(2)===0}function Uh(l,t,e){const i=e.Layers[l+1],s=e.Layers[l];return s.length<=i.length?Qh(s,t,e):jh(i,s,t,e)}function jh(l,t,e,i){const s=Qa(t,e),n=new zh(i.x);s.sort((u,d)=>n.Compare(u,d));let o=1;for(;o<l.length;)o*=2;const a=new Array(2*o-1).fill(0);o--;let h=0;for(const u of s){let d=o+i.x[u.Source];const m=u.CrossingWeight;for(a[d]+=m;d>0;)d%2!==0&&(h+=m*a[d+1]),d=Math.floor((d-1)/2),a[d]+=m}return h}function Qh(l,t,e){const i=Qa(l,t),s=new qh(e.x);i.sort((h,u)=>s.Compare(h,u));let n=1;for(;n<l.length;)n*=2;const o=new Array(2*n-1).fill(0);n--;let a=0;for(const h of i){let u=n+e.x[h.Target];const d=h.CrossingWeight;for(o[u]+=d;u>0;)u%2!==0&&(a+=d*o[u+1]),u=Math.floor((u-1)/2),o[u]+=d}return a}function Qa(l,t){return ws(l,e=>t.InEdges(e))}function $a(l,t){let e=0;for(let i=0;i<t.Layers.length-1;i++)e+=Uh(i,l,t);return e}class Cn extends Ft{get NoGainStepsBound(){return this.SugSettings.NoGainAdjacentSwapStepsBound*this.SugSettings.NoGainStepsForOrderingMultiplier}get SeedOfRandom(){return Vi(100)}constructor(t,e,i,s,n,o,a){super(a),this.tryReverse=!0,this.MaxNumberOfAdjacentExchanges=50,this.cancelToken=a,this.tryReverse=e,this.startOfVirtNodes=s,this.layerArrays=i,this.layering=i.y,this.nOfLayers=i.Layers.length,this.layers=i.Layers,this.properLayeredGraph=t,this.hasCrossWeights=n,this.SugSettings=o}get MaxOfIterations(){return this.SugSettings.MaxNumberOfPassesInOrdering*this.SugSettings.NoGainStepsForOrderingMultiplier}static OrderLayers(t,e,i,s,n){let o=!1;for(const h of t.Edges)if(h.CrossingWeight!==1){o=!0;break}new Cn(t,!0,e,i,o,s,n).run()}run(){if(this.Calculate(),this.tryReverse){const t=this.layerArrays.ReversedClone(),e=new Cn(this.properLayeredGraph.ReversedClone(),!1,t,this.startOfVirtNodes,this.hasCrossWeights,this.SugSettings,this.cancelToken);if(e.run(),dr.less(e.measure,this.measure)){for(let i=0;i<this.nOfLayers;i++)Vo(t.Layers[i],this.layerArrays.Layers[this.nOfLayers-1-i]);this.layerArrays.UpdateXFromLayers()}}}Calculate(){this.Init(),this.layerArraysCopy=Cn.CloneLayers(this.layers,this.layerArraysCopy);let t=0;this.measure=new dr(this.layerArraysCopy,$a(this.properLayeredGraph,this.layerArrays),this.startOfVirtNodes);for(let e=0;e<this.MaxOfIterations&&t<this.NoGainStepsBound&&!this.measure.IsPerfect();e++){const i=e%2===0;this.LayerByLayerSweep(i),this.AdjacentExchange();const s=new dr(this.layerArrays.Layers,$a(this.properLayeredGraph,this.layerArrays),this.startOfVirtNodes);dr.less(this.measure,s)?(this.Restore(),t++):(dr.less(s,this.measure)||io())&&(t=0,this.layerArraysCopy=Cn.CloneLayers(this.layers,this.layerArraysCopy),this.measure=s)}}static CloneLayers(t,e){if(e==null){e=new Array(t.length);for(let i=0;i<t.length;i++)e[i]=t[i].map(s=>s)}else for(let i=0;i<t.length;i++)Vo(t[i],e[i]);return e}Restore(){this.layerArrays.updateLayers(this.layerArraysCopy)}LayerByLayerSweep(t){if(t)for(let e=1;e<this.nOfLayers;e++)this.SweepLayer(e,!0);else for(let e=this.nOfLayers-2;e>=0;e--)this.SweepLayer(e,!1)}SweepLayer(t,e){const i=this.layers[t],s=new Array(i.length);for(let o=0;o<s.length;o++)s[o]=this.WMedian(i[o],e);this.Sort(t,s);const n=this.layerArrays.Layers[t];for(let o=0;o<n.length;o++)this.layerArrays.x[n[o]]=o}Sort(t,e){const i=new Map,s=this.layers[t];let n=0;for(const h of e){const u=s[n++];if(h!==-1)if(!i.has(h))i.set(h,u);else{const d=i.get(h);if(typeof d!="number"){const m=d;if(io())m.push(u);else{const y=Vi(m.length),E=m[y];m[y]=u,m.push(E)}}else{const m=d,y=new Array;i.set(h,y),io()?(y.push(m),y.push(u)):(y.push(u),y.push(m))}}}const o=Array.from(i).sort((h,u)=>h[0]-u[0]).map(h=>h[1]);let a=0;for(n=0;n<s.length;)if(e[n]!==-1){const h=o[a++];if(typeof h=="number")s[n++]=h;else{const u=h;for(const d of u){for(;e[n]===-1;)n++;s[n++]=d}}}else n++}WMedian(t,e){let i,s;if(e?(i=this.properLayeredGraph.OutEdges(t),s=this.properLayeredGraph.OutEdgesCount(t)):(i=this.properLayeredGraph.InEdges(t),s=this.properLayeredGraph.InEdgesCount(t)),s===0)return-1;const n=new Array(s);let o=0;if(e)for(const d of i)n[o++]=this.X[d.Target];else for(const d of i)n[o++]=this.X[d.Source];n.sort((d,m)=>d-m);const a=Math.floor(s/2);if(s%2===1)return n[a];if(s===2)return .5*(n[0]+n[1]);const h=n[a-1]-n[0],u=n[s-1]-n[a];return Math.floor((n[a-1]*h+n[a]*u)/(h+u))}Init(){const t=new Array(this.nOfLayers).fill(0),e=new Ut.B;for(let s=0;s<this.properLayeredGraph.NodeCount;s++)this.properLayeredGraph.InEdgesCount(s)===0&&e.push(s);const i=new Array(this.properLayeredGraph.NodeCount).fill(!1);for(;e.size>0;){const s=e.pop(),n=this.layerArrays.y[s];this.layerArrays.Layers[n][t[n]]=s,this.layerArrays.x[s]=t[n],t[n]++;for(const o of this.properLayeredGraph.Succ(s))i[o]||(i[o]=!0,e.push(o))}this.X=this.layerArrays.x}AdjacentExchange(){this.InitArrays();let t=0,e=!0;for(;e&&t++<this.MaxNumberOfAdjacentExchanges;){e=!1;for(let i=0;i<this.layers.length;i++)e=this.AdjExchangeLayer(i)||e;for(let i=this.layers.length-2;i>=0;i--)e=this.AdjExchangeLayer(i)||e}}AllocArrays(){const t=this.properLayeredGraph.NodeCount;this.predecessors=new Array(t),this.successors=new Array(t),this.pOrder=new Array(t),this.sOrder=new Array(t),this.hasCrossWeights&&(this.outCrossingCount=new Array(t),this.inCrossingCount=new Array(t));for(let e=0;e<t;e++){let i=this.properLayeredGraph.InEdgesCount(e);if(this.predecessors[e]=new Array(i),this.hasCrossWeights){const s=this.inCrossingCount[e]=new Map;for(const n of this.properLayeredGraph.InEdges(e))s.set(n.Source,n.CrossingWeight)}if(this.pOrder[e]=new Map,i=this.properLayeredGraph.OutEdgesCount(e),this.successors[e]=new Array(i),this.sOrder[e]=new Map,this.hasCrossWeights){const s=this.outCrossingCount[e]=new Map;for(const n of this.properLayeredGraph.OutEdges(e))s.set(n.Target,n.CrossingWeight)}}}InitArrays(){this.successors==null&&this.AllocArrays();for(let t=0;t<this.properLayeredGraph.NodeCount;t++)this.pOrder[t]=new Map,this.sOrder[t]=new Map;for(const t of this.layers)this.InitPsArraysForLayer(t)}CalcPair(t,e){const i=this.successors[t],s=this.successors[e],n=this.predecessors[t],o=this.predecessors[e];if(this.hasCrossWeights){const a=this.outCrossingCount[t],h=this.outCrossingCount[e],u=this.inCrossingCount[t],d=this.inCrossingCount[e];return{cuv:this.CountOnArraysUV(i,s,a,h)+this.CountOnArraysUV(n,o,u,d),cvu:this.CountOnArraysUV(s,i,h,a)+this.CountOnArraysUV(o,n,d,u)}}else return{cuv:this.CountOnArrays(i,s)+this.CountOnArrays(n,o),cvu:this.CountOnArrays(s,i)+this.CountOnArrays(o,n)}}InitPsArraysForLayer(t){for(const e of t){for(const i of this.properLayeredGraph.Pred(e)){const s=this.sOrder[i],n=s.size;this.successors[i][n]=e,s.set(e,n)}for(const i of this.properLayeredGraph.Succ(e)){const s=this.pOrder[i],n=s.size;this.predecessors[i][n]=e,s.set(e,n)}}}CountOnArrays(t,e){let i=0;const s=e.length-1;let n=-1,o=0;for(const a of t){const h=this.X[a];for(;n<s&&this.X[e[n+1]]<h;n++)o++;i+=o}return i}CountOnArraysUV(t,e,i,s){let n=0;const o=e.length-1;let a=-1,h=0;for(const u of t){const d=this.X[u];let m;for(;a<o&&this.X[m=e[a+1]]<d;a++)h+=s.get(m);n+=h*i.get(u)}return n}AdjExchangeLayer(t){const e=this.layers[t];return this.ExchangeWithGainWithNoDisturbance(e)?!0:(this.DisturbLayer(e),this.ExchangeWithGainWithNoDisturbance(e))}Swap(t,e){const i=this.X[t],s=this.X[e],n=this.layering[t],o=this.layers[n];o[i]=e,o[s]=t,this.X[t]=s,this.X[e]=i,this.UpdateSsContainingUv(t,e),this.UpdatePsContainingUv(t,e)}UpdatePsContainingUv(t,e){if(this.successors[t].length<=this.successors[e].length)for(const i of this.successors[t]){const s=this.pOrder[i];if(s.has(e)){const n=s.get(e),o=this.predecessors[i];o[n-1]=e,o[n]=t,s.set(e,n-1),s.set(t,n)}}else for(const i of this.successors[e]){const s=this.pOrder[i];if(s.has(t)){const n=s.get(e),o=this.predecessors[i];o[n-1]=e,o[n]=t,s.set(e,n-1),s.set(t,n)}}}UpdateSsContainingUv(t,e){if(this.predecessors[t].length<=this.predecessors[e].length)for(const i of this.predecessors[t]){const s=this.sOrder[i];if(s.has(e)){const n=s.get(e),o=this.successors[i];o[n-1]=e,o[n]=t,s.set(e,n-1),s.set(t,n)}}else for(const i of this.predecessors[e]){const s=this.sOrder[i];if(s.has(t)){const n=s.get(e),o=this.successors[i];o[n-1]=e,o[n]=t,s.set(e,n-1),s.set(t,n)}}}DisturbLayer(t){for(let e=0;e<t.length-1;e++)this.AdjacentSwapToTheRight(t,e)}ExchangeWithGainWithNoDisturbance(t){let e=!1,i;do i=this.ExchangeWithGain(t),e=e||i;while(i);return e}ExchangeWithGain(t){for(let e=0;e<t.length-1;e++)if(this.SwapWithGain(t[e],t[e+1]))return this.SwapToTheLeft(t,e),this.SwapToTheRight(t,e+1),!0;return!1}SwapToTheLeft(t,e){for(let i=e-1;i>=0;i--)this.AdjacentSwapToTheRight(t,i)}SwapToTheRight(t,e){for(let i=e;i<t.length-1;i++)this.AdjacentSwapToTheRight(t,i)}AdjacentSwapToTheRight(t,e){const i=t[e],s=t[e+1],n=this.SwapGain(i,s);(n>0||n===0&&io())&&this.Swap(i,s)}SwapGain(t,e){const i=this.CalcPair(t,e);return i.cuv-i.cvu}UvAreOfSameKind(t,e){return t<this.startOfVirtNodes&&e<this.startOfVirtNodes||t>=this.startOfVirtNodes&&e>=this.startOfVirtNodes}NeighborsForbidTheSwap(t,e){return this.UpperNeighborsForbidTheSwap(t,e)||this.LowerNeighborsForbidTheSwap(t,e)}LowerNeighborsForbidTheSwap(t,e){let i,s;return(i=this.properLayeredGraph.OutEdgesCount(t))===0||(s=this.properLayeredGraph.OutEdgesCount(e))===0?!1:this.X[this.successors[t][i>>1]]<this.X[this.successors[e][s>>1]]}UpperNeighborsForbidTheSwap(t,e){const i=this.properLayeredGraph.InEdgesCount(t),s=this.properLayeredGraph.InEdgesCount(e);return i===0||s===0?!1:this.X[this.predecessors[t][i>>1]]<this.X[this.predecessors[e][s>>1]]}CalcDeltaBetweenGroupsToTheLeftAndToTheRightOfTheSeparator(t,e,i){const s=this.GetKindDelegate(i);let n=0;for(let a=e-1;a>=0&&!s(t[a]);a--)n++;let o=0;for(let a=e+1;a<t.length&&!s(t[a]);a++)o++;return n-o}IsOriginal(t){return t<this.startOfVirtNodes}IsVirtual(t){return t>=this.startOfVirtNodes}GetKindDelegate(t){return this.IsVirtual(t)?this.IsVirtual:this.IsOriginal}SwapWithGain(t,e){return this.SwapGain(t,e)>0?(this.Swap(t,e),!0):!1}}class so{constructor(t,e,i){this.properLayeredGraph=t,this.layerArrays=e,this.nodePositions=i}static UpdateLayerArrays0(t,e,i){new so(t,e,i).UpdateLayerArrays()}static UpdateLayerArrays1(t,e){const i=so.BuildInitialNodePositions(t,e);this.UpdateLayerArrays0(t,e,i)}static BuildInitialNodePositions(t,e){const i=new Map;for(let s=0;s<e.Layers.length;s++){let n=0,o=0;for(;n<e.Layers[s].length;){for(;n<e.Layers[s].length&&t.IsVirtualNode(e.Layers[s][n]);)n++;for(let a=o;a<n;a++)i.set(e.Layers[s][a],new c(s,o));n<e.Layers[s].length&&i.set(e.Layers[s][n],new c(s,n)),n++,o=n}}return i}UpdateLayerArrays(){let t=this.CreateInitialOrdering();t=this.BuildOrdering(t),this.RestoreLayerArrays(t)}CreateInitialOrdering(){const t=new je;for(const e of this.layerArrays.Layers)for(const i of e){const s=this.nodePositions.get(i);t.hasxy(s.x,s.y)||t.setxy(s.x,s.y,[]),t.getxy(s.x,s.y).push(i)}return t}BuildOrdering(t){const e=new je,i=new Map;for(const s of this.layerArrays.Layers)for(const n of s){const o=this.nodePositions.get(n);e.hasxy(o.x,o.y)||(this.BuildNodeOrdering(t.get(o),i),e.set(o,t.get(o)))}return e}BuildNodeOrdering(t,e){t.sort(this.Comparison(e));for(let i=0;i<t.length;i++)e.set(t[i],i)}firstSucc(t){for(const e of this.properLayeredGraph.Succ(t))return e}firstPred(t){for(const e of this.properLayeredGraph.Pred(t))return e}Comparison(t){return(e,i)=>{const s=this.firstSucc(e),n=this.firstSucc(i);let o=this.firstPred(e),a=this.firstPred(i);const h=this.nodePositions.get(s),u=this.nodePositions.get(n),d=this.nodePositions.get(o),m=this.nodePositions.get(a);if(!h.equal(u))return d.equal(m)?h.compareTo(u):d.compareTo(m);if(this.properLayeredGraph.IsVirtualNode(s)){if(!d.equal(m))return d.compareTo(m);const y=t.get(s),E=t.get(n);return k(y,E)}for(;this.nodePositions.get(o).equal(this.nodePositions.get(a))&&this.properLayeredGraph.IsVirtualNode(o);)o=this.firstPred(o),a=this.firstPred(a);return this.nodePositions.get(o).equal(this.nodePositions.get(a))?k(e,i):this.nodePositions.get(o).compareTo(this.nodePositions.get(a))}}RestoreLayerArrays(t){for(const e of this.layerArrays.Layers){let i=0,s=0;for(;i<e.length;){for(;i<e.length&&this.nodePositions.get(e[s]).equal(this.nodePositions.get(e[i]));)i++;const n=t.get(this.nodePositions.get(e[s]));for(let o=s;o<i;o++)e[o]=n[o-s];s=i}}this.layerArrays.UpdateXFromLayers()}}function oc(l){const t=new Array(l.nodeCount).fill(!1),e=new Array(l.nodeCount).fill(!1);for(let i=0;i<l.nodeCount;i++)if(Xa(l,i,t,e))return!0;return!1}class no{static getOrder(t,e){const i=Qe(e.map(([s,n])=>new Et(s,n)),t);return no.getOrderOnGraph(i)}static getOrderOnGraph(t){const e=new Array(t.nodeCount).fill(!1),i=new Ut.B,s=[];let n;for(let o=0;o<t.nodeCount;o++){if(e[o])continue;let a=o;e[a]=!0;let h=0;n=t.outEdges[o];do{for(;h<n.length;h++){const u=n[h].target;e[u]||(e[u]=!0,i.push({edges:n,index:h+1,current_u:a}),a=u,n=t.outEdges[a],h=-1)}if(s.push(a),i.length>0){const u=i.pop();n=u.edges,h=u.index,a=u.current_u}else break}while(!0)}return s.reverse()}}function Xa(l,t,e,i){if(i[t])return!0;if(e[t])return!1;i[t]=!0,e[t]=!0;for(const s of l.outEdges[t])if(Xa(l,s.target,e,i))return!0;return i[t]=!1,!1}class $h{GetLayers(){const t=no.getOrderOnGraph(this.graph),e=new Array(this.graph.nodeCount).fill(0);let i=this.graph.nodeCount;for(;i-- >0;){const s=t[i];for(const n of this.graph.inEdges[s]){const o=n.source,a=e[s]+n.separation;e[o]<a&&(e[o]=a)}}return e}checkTopoOrder(t){for(const e of this.graph.edges)if(Xh(e,t))return!1;return!0}constructor(t){this.graph=t}}function Xh(l,t){const e=t.findIndex(s=>s===l.source),i=t.findIndex(s=>s===l.target);return e===-1||i===-1||e>=i}class Ke{constructor(t){this.inTree=!1,this.cut=Ke.infinity,this.iedge=t}get source(){return this.iedge.source}get target(){return this.iedge.target}get separation(){return this.iedge.separation}get crossingWeight(){return this.iedge.CrossingWeight}get weight(){return this.iedge.weight}}Ke.infinity=Number.MAX_SAFE_INTEGER;function Kh(l){const t=new Array;for(const e of l.edges)t.push(new Ke(e));return Qe(t,l.nodeCount)}class Ho{constructor(t,e,i,s,n){this.v=t,this.outEnum=e,this.i=i,this.inEnum=s,this.j=n}}class Ka{get weight(){return this.graph.edges.map(t=>t.weight*(this.layers[t.source]-this.layers[t.target])).reduce((t,e)=>t+e,0)}get nodeCount(){return this.vertices.length}setLow(t,e){this.vertices[t].low=e}setLim(t,e){this.vertices[t].lim=e}setParent(t,e){this.vertices[t].parent=e}constructor(t,e){this.layers=null,this.treeVertices=[],this.vertices=[],this.leaves=[],this.graph=Kh(t),this.networkCancelToken=e;for(let i=0;i<this.graph.nodeCount;i++)this.vertices.push({inTree:!1,lim:-1,low:-1,parent:null})}GetLayers(){return this.layers==null&&this.run(),this.layers}shiftLayerToZero(){const t=Math.min(...this.layers);for(let e=0;e<this.layers.length;e++)this.layers[e]-=t}addVertexToTree(t){this.vertices[t].inTree=!0}vertexInTree(t){return this.vertices[t].inTree}lim(t){return this.vertices[t].lim}low(t){return this.vertices[t].low}parent(t){return this.vertices[t].parent}feasibleTree(){for(this.initLayers();this.tightTree()<this.nodeCount;){const t=this.getNonTreeEdgeIncidentToTheTreeWithMinimalAmountOfSlack();if(t==null)break;let e=this.slack(t);this.vertexInTree(t.source)&&(e=-e);for(const i of this.treeVertices)this.layers[i]+=e}this.initCutValues()}vertexSourceTargetVal(t,e){const i=e.source,s=e.target;return this.lim(i)>this.lim(s)?this.lim(t)<=this.lim(s)&&this.low(s)<=this.lim(t)?0:1:this.lim(t)<=this.lim(i)&&this.low(i)<=this.lim(t)?1:0}incidentEdges(t){return this.graph.incidentEdges(t)}allLowCutsHaveBeenDone(t){for(const e of this.incidentEdges(t))if(e.inTree&&e.cut===Ke.infinity&&e!==this.parent(t))return!1;return!0}edgeSourceTargetVal(t,e){return this.vertexSourceTargetVal(t.source,e)-this.vertexSourceTargetVal(t.target,e)}initCutValues(){this.initLimLowAndParent();let t=new Ut.B;for(const i of this.leaves)t.push(i);let e=new Ut.B;for(;t.length>0;){for(;t.length>0;){const s=t.pop(),n=this.parent(s);if(n==null)continue;let o=0;for(const h of this.incidentEdges(s))if(h.inTree===!1){const u=this.edgeSourceTargetVal(h,n);u!==0&&(o+=u*h.weight)}else if(h===n)o+=h.weight;else{const u=n.source===h.target||n.target===h.source?1:-1,d=this.edgeContribution(h,s);o+=d*u}n.cut=o;const a=n.source===s?n.target:n.source;this.allLowCutsHaveBeenDone(a)&&e.push(a)}const i=t;t=e,e=i}}edgeContribution(t,e){let i=t.cut-t.weight;for(const s of this.incidentEdges(e))if(s.inTree===!1){const n=this.edgeSourceTargetVal(s,t);n===-1?i+=s.weight:n===1&&(i-=s.weight)}return i}initLimLowAndParent(){this.initLowLimParentAndLeavesOnSubtree(1,0)}initLowLimParentAndLeavesOnSubtree(t,e){const i=new Ut.B;let s=this.graph.outEdges[e],n=-1,o=this.graph.inEdges[e],a=-1;for(i.push(new Ho(e,s,n,o,a)),this.vertices[e].low=t;i.length>0;){const h=i.pop();e=h.v,s=h.outEnum,n=h.i,o=h.inEnum,a=h.j;let u;do{for(u=!0;++n<s.length;){const d=s[n];!d.inTree||this.vertices[d.target].low>0||(i.push(new Ho(e,s,n,o,a)),e=d.target,this.setParent(e,d),this.setLow(e,t),s=this.graph.outEdges[e],n=-1,o=this.graph.inEdges[e],a=-1)}for(;++a<o.length;){const d=o[a];if(!(!d.inTree||this.vertices[d.source].low>0)){i.push(new Ho(e,s,n,o,a)),e=d.source,this.setLow(e,t),this.setParent(e,d),s=this.graph.outEdges[e],n=-1,o=this.graph.inEdges[e],a=-1,u=!1;break}}}while(!u);this.setLim(e,t++),this.lim(e)===this.low(e)&&this.leaves.push(e)}}updateLimLowLeavesAndParentsUnderNode(t){const e=this.vertices[t].low,i=this.vertices[t].lim;this.leaves=[];for(let s=0;s<this.nodeCount;s++)e<=this.vertices[s].lim&&this.vertices[s].lim<=i?this.setLow(s,0):this.low(s)===this.lim(s)&&this.leaves.push(s);this.initLowLimParentAndLeavesOnSubtree(e,t)}slack(t){return this.layers[t.source]-this.layers[t.target]-t.separation}getNonTreeEdgeIncidentToTheTreeWithMinimalAmountOfSlack(){let t=null,e=Ke.infinity;for(const i of this.treeVertices){for(const s of this.graph.outEdges[i]){if(this.vertexInTree(s.source)&&this.vertexInTree(s.target))continue;const n=this.slack(s);if(n<e&&(t=s,e=n,n===1))return s}for(const s of this.graph.inEdges[i]){if(this.vertexInTree(s.source)&&this.vertexInTree(s.target))continue;const n=this.slack(s);if(n<e&&(t=s,e=n,n===1))return s}}return t}tightTree(){this.treeVertices=[];for(const e of this.graph.edges)e.inTree=!1;for(let e=1;e<this.nodeCount;e++)this.vertices[e].inTree=!1;this.vertices[0].inTree=!0,this.treeVertices.push(0);const t=new Ut.B;for(t.push(0);t.length>0;){const e=t.pop();for(const i of this.graph.outEdges[e])this.vertexInTree(i.target)||this.layers[i.source]-this.layers[i.target]===i.separation&&(t.push(i.target),this.addVertexToTree(i.target),this.treeVertices.push(i.target),i.inTree=!0);for(const i of this.graph.inEdges[e])this.vertexInTree(i.source)||this.layers[i.source]-this.layers[i.target]===i.separation&&(t.push(i.source),this.addVertexToTree(i.source),this.treeVertices.push(i.source),i.inTree=!0)}return this.treeVertices.length}leaveEnterEdge(){let t,e,i=0;for(const o of this.graph.edges)o.inTree&&o.cut<i&&(i=o.cut,t=o);if(t==null)return null;let s=!1,n=Ke.infinity;for(const o of this.graph.edges){const a=this.slack(o);if(o.inTree===!1&&this.edgeSourceTargetVal(o,t)===-1&&(a<n||a===n&&(s=Vi(2)===1))){if(n=a,e=o,n===0&&!s)break;s=!1}}if(e==null)throw new Error;return{leaving:t,entering:e}}exchange(t,e){const i=this.commonPredecessorOfSourceAndTargetOfF(e);this.createPathForCutUpdates(t,e,i),this.updateLimLowLeavesAndParentsUnderNode(i),this.updateCuts(t),this.updateLayersUnderNode(i)}updateLayersUnderNode(t){const e=new Ut.B;e.push(t);for(let i=0;i<this.nodeCount;i++)this.low(t)<=this.lim(i)&&this.lim(i)<=this.lim(t)&&i!==t&&(this.layers[i]=Ke.infinity);for(;e.length>0;){const i=e.pop();for(const s of this.graph.outEdges[i])s.inTree&&this.layers[s.target]===Ke.infinity&&(this.layers[s.target]=this.layers[i]-s.separation,e.push(s.target));for(const s of this.graph.inEdges[i])s.inTree&&this.layers[s.source]===Ke.infinity&&(this.layers[s.source]=this.layers[i]+s.separation,e.push(s.source))}}updateCuts(t){let e=new Ut.B,i=new Ut.B;for(e.push(t.source),e.push(t.target);e.length>0;){for(;e.length>0;){const n=e.pop(),o=this.parent(n);if(o==null||o.cut!==Ke.infinity)continue;let a=0;for(const u of this.incidentEdges(n))if(u.inTree===!1)a+=this.edgeSourceTargetVal(u,o)*u.weight;else if(u===o)a+=u.weight;else{const d=o.source===u.target||o.target===u.source?1:-1,m=this.edgeContribution(u,n);a+=m*d}o.cut=a;const h=o.source===n?o.target:o.source;this.allLowCutsHaveBeenDone(h)&&i.push(h)}const s=e;e=i,i=s}}createPathForCutUpdates(t,e,i){let s=e.target;for(;s!==i;){const n=this.parent(s);n.cut=Ke.infinity,s=n.source===s?n.target:n.source}e.cut=Ke.infinity,t.inTree=!1,e.inTree=!0}commonPredecessorOfSourceAndTargetOfF(t){let e,i;this.lim(t.source)<this.lim(t.target)?(e=this.lim(t.source),i=this.lim(t.target)):(e=this.lim(t.target),i=this.lim(t.source));let s=t.source;for(;!(this.low(s)<=e&&i<=this.lim(s));){const n=this.parent(s);n.cut=Ke.infinity,s=n.source===s?n.target:n.source}return s}checkCutValues(){for(const t of this.graph.edges)if(t.inTree){let e=0;for(const i of this.graph.edges)e+=this.edgeSourceTargetVal(i,t)*i.weight;t.cut!==e&&console.log(ue.Qf.format("cuts are wrong for {0}; should be {1} but is {2}",t,e,t.cut))}}initLayers(){const t=new $h(this.graph);return this.layers=t.GetLayers()}run(){if(this.graph.edges.length===0&&this.graph.nodeCount===0)this.layers=[];else{this.feasibleTree();let t;for(;(t=this.leaveEnterEdge())!=null;)this.exchange(t.leaving,t.entering);this.shiftLayerToZero()}}}class Yh{GetLayers(){return new Ka(this.graph,this.Cancel).GetLayers()}ShrunkComponent(t){const e=[];for(const i of t){const s=i[0],n=i[1];for(const o of this.graph.outEdges[s]){const a=new Ti(n,t.get(o.target),o.edge);a.separation=o.separation,a.weight=o.weight,e.push(a)}}return new ur(e,t.size)}constructor(t,e){this.graph=t,this.Cancel=e}}class ei{toString(){return"la:ra "+this.la+" "+this.ra+" ta:ba "+this.ta+" "+this.ba+" x:y "+this.x_+" "+this.y_}get leftAnchor(){return this.la}set leftAnchor(t){this.la=Math.max(t,0)}get rightAnchor(){return this.ra}set rightAnchor(t){this.ra=Math.max(t,0)}get topAnchor(){return this.ta}set topAnchor(t){this.ta=Math.max(t,0)}get bottomAnchor(){return this.ba}set bottomAnchor(t){this.ba=Math.max(t,0)}get left(){return this.x_-this.la}get right(){return this.x_+this.ra}get top(){return this.y_+this.ta}set top(t){this.y_+=t-this.ta}get bottom(){return this.y_-this.ba}set bottom(t){this.y_+=t-this.ba}get leftTop(){return new c(this.left,this.top)}get leftBottom(){return new c(this.left,this.bottom)}get rightBottom(){return new c(this.right,this.bottom)}get node(){return this.node_}set node(t){this.node_=t,this.polygonalBoundary_=null}get rightTop(){return new c(this.right,this.top)}constructor(t){this.padding=0,this.alreadySitsOnASpline=!1,this.labelIsToTheLeftOfTheSpline=!1,this.labelIsToTheRightOfTheSpline=!1,this.labelCornersPreserveCoefficient=t}static mkAnchor(t,e,i,s,n,o){const a=new ei(o);return a.la=t,a.ra=e,a.ta=i,a.ba=s,a.node=n,a}get x(){return this.x_}set x(t){this.polygonalBoundary_=null,this.x_=t}get y(){return this.y_}set y(t){this.polygonalBoundary_=null,this.y_=t}get origin(){return new c(this.x,this.y)}get width(){return this.la+this.ra}get height(){return this.ta+this.ba}get hasLabel(){return this.labelIsToTheLeftOfTheSpline||this.labelIsToTheLeftOfTheSpline}get LabelWidth(){if(this.labelIsToTheLeftOfTheSpline)return this.leftAnchor;if(this.labelIsToTheRightOfTheSpline)return this.rightAnchor;throw new Error}get polygonalBoundary(){return this.polygonalBoundary_!=null?this.polygonalBoundary_:this.polygonalBoundary_=ei.pad(this.creatPolygonalBoundaryWithoutPadding(),this.padding)}static pad(t,e){return e===0?t:ei.curveIsConvex(t)?ei.padConvexCurve(t,e):ei.padConvexCurve(t.boundingBox.perimeter(),e)}static padCorner(t,e,i,s,n){const o=ei.getPaddedCorner(e,i,s,n);t.addPoint(o.a),o.numberOfPoints===2&&t.addPoint(o.b)}static padConvexCurve(t,e){const i=new st;ei.padCorner(i,t.endPoint.prev,t.endPoint,t.startPoint,e),ei.padCorner(i,t.endPoint,t.startPoint,t.startPoint.next,e);for(let s=t.startPoint;s.next.next!=null;s=s.next)ei.padCorner(i,s,s.next,s.next.next,e);return i.closed=!0,i}static getPaddedCorner(t,e,i,s){const n=t.point,o=e.point,a=i.point,h=c.getTriangleOrientation(n,o,a)===D.Counterclockwise,u=o.sub(n),d=u.rotate((h?-Math.PI:Math.PI)/2).normalize(),m=u.normalize().add(o.sub(a).normalize());if(m.length<C.intersectionEpsilon)return{a:o.add(d.mul(s)),b:null,numberOfPoints:1};const y=m.normalize().mul(s),E=y.rotate(Math.PI/2),T=(s-y.dot(d))/E.dot(d);return{a:y.add(E.mul(T)).add(o),b:y.sub(E.mul(T)).add(o),numberOfPoints:2}}static*orientations(t){yield c.getTriangleOrientation(t.endPoint.point,t.startPoint.point,t.startPoint.next.point),yield c.getTriangleOrientation(t.endPoint.prev.point,t.endPoint.point,t.startPoint.point);let e=t.startPoint;for(;e.next.next!=null;)yield c.getTriangleOrientation(e.point,e.next.point,e.next.next.point),e=e.next}static curveIsConvex(t){let e=D.Collinear;for(const i of ei.orientations(t))if(i!==D.Collinear){if(e===D.Collinear)e=i;else if(i!==e)return!1}return!0}creatPolygonalBoundaryWithoutPadding(){return this.hasLabel?this.labelIsToTheLeftOfTheSpline?this.polygonOnLeftLabel():this.polygonOnRightLabel():this.nodeBoundary==null?this.standardRectBoundary():w.polylineAroundClosedCurve(this.nodeBoundary)}get nodeBoundary(){return this.node==null?null:this.node.boundaryCurve}standardRectBoundary(){const t=new st;return t.addPoint(this.leftTop),t.addPoint(this.rightTop),t.addPoint(this.rightBottom),t.addPoint(this.leftBottom),t.closed=!0,t}polygonOnLeftLabel(){const t=this.left+(1-this.labelCornersPreserveCoefficient)*this.LabelWidth;return st.mkClosedFromPoints([new c(t,this.top),this.rightTop,this.rightBottom,new c(t,this.bottom),new c(this.left,this.y)])}polygonOnRightLabel(){const t=this.right-(1-this.labelCornersPreserveCoefficient)*this.LabelWidth;return st.mkClosedFromPoints([new c(t,this.top),new c(this.right,this.y),new c(t,this.bottom),this.leftBottom,this.leftTop])}move(t){this.x+=t.x,this.y+=t.y}}class $s{get CurrentEnumRightUp(){return(this.LR?0:1)+2*(this.BT?0:1)}IsVirtual(t){return t>=this.nOfOriginalVertices}Source(t){return this.BT?t.Source:t.Target}Target(t){return this.BT?t.Target:t.Source}static CalculateXCoordinates(t,e,i,s,n){new $s(t,e,i,s,n).Calculate()}Calculate(){this.SortInAndOutEdges(),this.RightUpSetup(),this.CalcBiasedAlignment(),this.LeftUpSetup(),this.CalcBiasedAlignment(),this.RightDownSetup(),this.CalcBiasedAlignment(),this.LeftDownSetup(),this.CalcBiasedAlignment(),this.HorizontalBalancing()}SortInAndOutEdges(){this.FillLowMedians(),this.FillUpperMedins()}FillUpperMedins(){this.upperMedians=new Array(this.graph.NodeCount);for(let t=0;t<this.graph.NodeCount;t++)this.FillUpperMediansForNode(t)}CompareByX(t,e){return this.la.x[t]-this.la.x[e]}FillUpperMediansForNode(t){let e=this.graph.InEdgesCount(t);if(e>0){const i=new Array(e);e=0;for(const n of this.graph.InEdges(t))i[e++]=n.Source;i.sort((n,o)=>this.CompareByX(n,o));const s=Math.floor(e/2);s*2===e?this.upperMedians[t]=new Et(i[s-1],i[s]):this.upperMedians[t]=i[s]}else this.upperMedians[t]=-1}FillLowMedians(){this.lowMedians=new Array(this.graph.NodeCount);for(let t=0;t<this.graph.NodeCount;t++)this.FillLowMediansForNode(t)}FillLowMediansForNode(t){let e=this.graph.OutEdgesCount(t);if(e>0){const i=new Array(e);e=0;for(const n of this.graph.OutEdges(t))i[e++]=n.Target;i.sort((n,o)=>this.CompareByX(n,o));const s=Math.floor(e/2);s*2===e?this.lowMedians[t]=new Et(i[s-1],i[s]):this.lowMedians[t]=i[s]}else this.lowMedians[t]=-1}HorizontalBalancing(){let t=-1;const e=new Array(4),i=new Array(4);let s=Number.MAX_VALUE;for(let o=0;o<4;o++){const a={a:0,b:0};this.AssignmentBounds(o,a),e[o]=a.a,i[o]=a.b;const h=i[o]-e[o];h<s&&(t=o,s=h)}for(let o=0;o<4;o++){let a;if($s.IsLeftMostAssignment(o)?a=e[t]-e[o]:a=i[t]-i[o],this.x=this.xCoords[o],a!==0)for(let h=0;h<this.nOfVertices;h++)this.x[h]=this.x[h]+a}const n=new Array(4);for(let o=0;o<this.nOfVertices;o++)n[0]=this.xCoords[0][o],n[1]=this.xCoords[1][o],n[2]=this.xCoords[2][o],n[3]=this.xCoords[3][o],n.sort((a,h)=>a-h),this.anchors[o].x=(n[1]+n[2])/2}static IsLeftMostAssignment(t){return t===0||t===2}AssignmentBounds(t,e){if(this.nOfVertices===0)e.a=0,e.b=0;else{this.x=this.xCoords[t],e.a=e.b=this.x[0];for(let i=1;i<this.nOfVertices;i++){const s=this.x[i];s<e.a?e.a=s:s>e.b&&(e.b=s)}}}CalcBiasedAlignment(){this.ConflictElimination(),this.Align()}LeftUpSetup(){this.LR=!1,this.BT=!0}LeftDownSetup(){this.LR=!1,this.BT=!1}RightDownSetup(){this.LR=!0,this.BT=!1}RightUpSetup(){this.LR=!0,this.BT=!0}ConflictElimination(){this.RemoveMarksFromEdges(),this.MarkConflictingEdges()}*UpperEdgeMedians(t){const e=this.BT?this.upperMedians[t]:this.lowMedians[t];if(typeof e!="number"){const s=e;this.LR?(yield s.x,yield s.y):(yield s.y,yield s.x)}else{const s=e;s>=0&&(yield s)}}MarkConflictingEdges(){let t=this.LowerOf(0,this.h-1);const e=t,i=this.UpperOf(0,this.h-1),s=this.NextLower(i);for(;this.IsBelow(t,i);t=this.NextUpper(t))this.IsBelow(e,t)&&this.IsBelow(t,s)&&this.ConflictsWithAtLeastOneInnerEdgeForALayer(t)}NextUpper(t){return this.BT?t+1:t-1}NextLower(t){return this.BT?t-1:t+1}UpperOf(t,e){return this.BT?Math.max(t,e):Math.min(t,e)}LowerOf(t,e){return this.BT?Math.min(t,e):Math.max(t,e)}IsBelow(t,e){return this.BT?t<e:e<t}LeftMost(t,e){return this.LR?Math.min(t,e):Math.max(t,e)}RightMost(t,e){return this.LR?Math.max(t,e):Math.min(t,e)}IsNotRightFrom(t,e){return this.LR?t<=e:e<=t}IsLeftFrom(t,e){return this.LR?t<e:e<t}NextRight(t){return this.LR?t+1:t-1}NextLeft(t){return this.LR?t-1:t+1}ConflictsWithAtLeastOneInnerEdgeForALayer(t){if(t>=0&&t<this.la.Layers.length){const e=this.la.Layers[t];let i=null,s=this.LeftMost(0,e.length-1);const n=this.RightMost(0,e.length-1);for(;this.IsNotRightFrom(s,n)&&i==null;s=this.NextRight(s))i=this.InnerEdgeByTarget(e[s]);if(i!=null){const o=this.Pos(this.Source(i));for(let h=this.LeftMost(0,e.length-1);this.IsLeftFrom(h,s);h=this.NextRight(h))for(const u of this.InEdges(e[h]))this.IsLeftFrom(o,this.Pos(this.Source(u)))&&this.MarkEdge(u);let a=this.Pos(this.Source(i));for(;this.IsNotRightFrom(s,n);){const h=this.AlignmentToTheRightOfInner(e,s,o);if(s=this.NextRight(s),h!=null){const u=this.Pos(this.Source(h));this.MarkEdgesBetweenInnerAndNewInnerEdges(e,i,h,a,u),i=h,a=u}}for(let h=this.NextRight(this.Pos(this.Target(i)));this.IsNotRightFrom(h,n);h=this.NextRight(h))for(const u of this.InEdges(e[h]))this.IsLeftFrom(this.Pos(this.Source(u)),this.Pos(this.Source(i)))&&this.MarkEdge(u)}}}InEdgeOfVirtualNode(t){return this.BT?this.graph.InEdgeOfVirtualNode(t):this.graph.OutEdgeOfVirtualNode(t)}InEdges(t){return this.BT?this.graph.InEdges(t):this.graph.OutEdges(t)}MarkEdgesBetweenInnerAndNewInnerEdges(t,e,i,s,n){let o=this.NextRight(this.Pos(this.Target(e)));for(;this.IsLeftFrom(o,this.Pos(this.Target(i)));o=this.NextRight(o))for(const a of this.InEdges(t[o])){const h=this.Pos(this.Source(a));this.IsLeftFrom(h,s)?this.MarkEdge(a):this.IsLeftFrom(n,h)&&this.MarkEdge(a)}}AlignmentToTheRightOfInner(t,e,i){if(this.NumberOfInEdges(t[e])===1){let n=null;for(const o of this.InEdges(t[e]))n=o;return this.IsInnerEdge(n)&&this.IsLeftFrom(i,this.Pos(n.Source))?n:null}return null}NumberOfInEdges(t){return this.BT?this.graph.InEdgesCount(t):this.graph.OutEdgesCount(t)}Pos(t){return this.la.x[t]}InnerEdgeByTarget(t){if(this.IsVirtual(t)){const e=this.InEdgeOfVirtualNode(t);if(this.IsVirtual(this.Source(e)))return e}return null}IsInnerEdge(t){return this.IsVirtual(t.Source)&&this.IsVirtual(t.Target)}RemoveMarksFromEdges(){this.markedEdges.clear()}constructor(t,e,i,s,n){this.xCoords=new Array(4),this.la=t,this.graph=e,this.nOfOriginalVertices=i,this.nOfVertices=this.graph.NodeCount,this.markedEdges=new Ii,this.h=this.la.Layers.length,this.root=new Array(this.nOfVertices),this.align=new Array(this.nOfVertices),this.anchors=s,this.nodeSep=n}Align(){this.CreateBlocks(),this.AssignCoordinatesByLongestPath()}AssignCoordinatesByLongestPath(){this.x=this.xCoords[this.CurrentEnumRightUp]=new Array(this.nOfVertices);const t=new Array;for(let s=0;s<this.nOfVertices;s++)if(s===this.root[s]){let n=s;do{const o={neighbor:0};this.TryToGetRightNeighbor(n,o)&&t.push(new Ti(s,this.root[o.neighbor],null)),n=this.align[n]}while(n!==s)}const e=Qe(t,this.nOfVertices),i=no.getOrderOnGraph(e);for(const s of i)if(s===this.root[s]){let n=0,o=!0,a=s;do{const h={neighbor:0};this.TryToGetLeftNeighbor(a,h)&&(o?(n=this.x[this.root[h.neighbor]]+this.DeltaBetweenVertices(h.neighbor,a),o=!1):n=this.RightMost(n,this.x[this.root[h.neighbor]]+this.DeltaBetweenVertices(h.neighbor,a))),a=this.align[a]}while(a!==s);this.x[s]=n}for(const s of i)if(s===this.root[s]&&e.inEdges[s].length===0){let n=s,o=this.RightMost(-$s.infinity,$s.infinity);const a=o;do{const h={neighbor:0};this.TryToGetRightNeighbor(n,h)&&(o=this.LeftMost(o,this.x[this.root[h.neighbor]]-this.DeltaBetweenVertices(n,h.neighbor))),n=this.align[n]}while(n!==s);a!==o&&(this.x[s]=o)}for(let s=0;s<this.nOfVertices;s++)s!==this.root[s]&&(this.x[s]=this.x[this.root[s]])}TryToGetRightNeighbor(t,e){const i=this.NextRight(this.Pos(t)),s=this.la.Layers[this.la.y[t]];return i>=0&&i<s.length?(e.neighbor=s[i],!0):!1}TryToGetLeftNeighbor(t,e){const i=this.NextLeft(this.Pos(t)),s=this.la.Layers[this.la.y[t]];return i>=0&&i<s.length?(e.neighbor=s[i],!0):!1}CreateBlocks(){for(let e=0;e<this.nOfVertices;e++)this.root[e]=this.align[e]=e;const t=this.LowerOf(0,this.h-1);for(let e=this.NextLower(this.UpperOf(0,this.h-1));!this.IsBelow(e,t);e=this.NextLower(e)){const i=this.la.Layers[e];let s=this.LeftMost(-1,this.la.Layers[this.NextUpper(e)].length);const n=this.RightMost(0,i.length-1);for(let o=this.LeftMost(0,i.length-1);this.IsNotRightFrom(o,n);o=this.NextRight(o)){const a=i[o];for(const h of this.UpperEdgeMedians(a))if(!this.IsMarked(a,h)&&this.IsLeftFrom(s,this.Pos(h))){this.align[h]=a,this.root[a]=this.root[h],this.align[a]=this.root[h],s=this.Pos(h);break}}}}IsMarked(t,e){return this.BT?this.markedEdges.hasxy(e,t):this.markedEdges.hasxy(t,e)}MarkEdge(t){this.markedEdges.addNN(t.Source,t.Target)}DeltaBetweenVertices(t,e){let i;if(this.Pos(t)>this.Pos(e)){const s=t;t=e,e=s,i=-1}else i=1;return(this.anchors[t].rightAnchor+this.anchors[e].leftAnchor+this.nodeSep)*i}}$s.infinity=1e7;class Jh extends me{constructor(t,e,i,s,n){super(),this.weightMultiplierOfOriginalOriginal=1,this.weightMultOfOneVirtual=3,this.weightMultiplierOfTwoVirtual=8,this.SetEdges(s,n),this.virtualVerticesStart=t.nodeCount,this.virtualVerticesEnd=e.NodeCount-1,this.layeredGraph=e,this.layerArrays=i}EdgeWeightMultiplier(t){const e=t.source,i=t.target;if(e<this.layeredGraph.NodeCount&&this.layerArrays.y[e]===this.layerArrays.y[i]&&this.layerArrays.x[e]===this.layerArrays.x[i]+1)return 0;let s=0,n=-1,o=-1;for(const h of this.outEdges[e])o===-1?o=h.target:n=h.target;return o>=this.virtualVerticesStart&&o<=this.virtualVerticesEnd&&s++,n>=this.virtualVerticesStart&&n<=this.virtualVerticesEnd&&s++,s===0?this.weightMultiplierOfOriginalOriginal:s===1?this.weightMultOfOneVirtual:this.weightMultiplierOfTwoVirtual}SetEdgeWeights(){for(const t of this.edges)t.weight=t.weight*this.EdgeWeightMultiplier(t)}}var Ae;(function(l){l[l.Top=0]="Top",l[l.Internal=1]="Internal",l[l.Bottom=2]="Bottom"})(Ae||(Ae={}));class An{static Calculate(t,e=0){return new An(t,e).Calculate()}constructor(t,e){this.groupSplitThreshold=2,this.initialNodes=t,this.groupSplitThreshold=e}Calculate(){return this.Calc(this.initialNodes)}Calc(t){if(t.length===0)return null;if(t.length===1)return t[0];const e=t[0].parallelogram;let i=1,s=Pt.parallelogramOfTwo(e,t[i].parallelogram).area;for(let d=2;d<t.length;d++){const m=Pt.parallelogramOfTwo(e,t[d].parallelogram).area;m>s&&(i=d,s=m)}let n;for(let d=0;d<t.length;d++)if(d!==i){n=d;break}s=Pt.parallelogramOfTwo(t[i].parallelogram,t[n].parallelogram).area;for(let d=0;d<t.length;d++){if(d===i)continue;const m=Pt.parallelogramOfTwo(t[i].parallelogram,t[d].parallelogram).area;m>s&&(n=d,s=m)}const o=new Array,a=new Array;o.push(t[i]),a.push(t[n]);let h=t[i].parallelogram,u=t[n].parallelogram;for(let d=0;d<t.length;d++){if(d===i||d===n)continue;const m=Pt.parallelogramOfTwo(h,t[d].parallelogram),y=m.area-h.area,E=Pt.parallelogramOfTwo(u,t[d].parallelogram),T=E.area-u.area;o.length*this.groupSplitThreshold<a.length?(o.push(t[d]),h=m):a.length*this.groupSplitThreshold<o.length?(a.push(t[d]),u=E):y<T?(o.push(t[d]),h=m):(a.push(t[d]),u=E)}return{parallelogram:Pt.parallelogramOfTwo(h,u),node:{children:[this.Calc(o),this.Calc(a)]},seg:void 0,leafBoxesOffset:void 0}}}class ii{constructor(t,e,i,s,n,o,a,h){this.topNode=t,this.bottomNode=e,this.topSite=i,this.bottomSite=i.next,this.currentTopSite=i,this.currentBottomSite=i.next,this.layerArrays=s,this.layeredGraph=n,this.originalGraph=o,this.anchors=a,this.layerSeparation=h}static Refine(t,e,i,s,n,o,a,h){new ii(t,e,i,n,o,a,s,h).Refine()}Refine(){for(this.Init();this.InsertSites(););}FixCorner(t,e,i){if(t.equal(e))return e;const s=c.ClosestPointAtLineSegment(e,t,i);let n=e.sub(s);const o=Math.abs(n.y),a=this.layerSeparation/2;return o>a&&(n=n.mul(a/(o*2))),n.add(e)}InsertSites(){return Vi(2)===0?this.CalculateNewTopSite()||this.CalculateNewBottomSite():this.CalculateNewBottomSite()||this.CalculateNewTopSite()}CalculateNewBottomSite(){const t=this.currentBottomSite.point.sub(this.currentTopSite.point);let e=ii.absCotan(t),i,s=!1;for(const n of this.bottomCorners()){const o=ii.absCotan(n.sub(this.currentBottomSite.point));o<e&&(e=o,i=n,s=!0)}return s?R(e,ii.absCotan(t))?!1:(this.currentBottomSite=Dt.mkSiteSPS(this.currentTopSite,this.FixCorner(this.currentTopSite.point,i,this.currentBottomSite.point),this.currentBottomSite),!0):!1}static absCotan(t){return Math.abs(t.x/t.y)}CalculateNewTopSite(){const t=this.currentBottomSite.point.sub(this.currentTopSite.point);let e=ii.absCotan(t),i,s=!1;for(const n of this.topCorners()){const o=ii.absCotan(n.sub(this.currentTopSite.point));o<e&&(e=o,i=n,s=!0)}return s?R(e,ii.absCotan(t))?!1:(this.currentTopSite=Dt.mkSiteSPS(this.currentTopSite,this.FixCorner(this.currentTopSite.point,i,this.currentBottomSite.point),this.currentBottomSite),!0):!1}Init(){this.IsTopToTheLeftOfBottom()?(this.topCorners=()=>this.CornersToTheRightOfTop(),this.bottomCorners=()=>this.CornersToTheLeftOfBottom()):(this.topCorners=()=>this.CornersToTheLeftOfTop(),this.bottomCorners=()=>this.CornersToTheRightOfBottom())}IsTopToTheLeftOfBottom(){return this.topSite.point.x<this.topSite.next.point.x}*NodeCorners(t){for(const e of this.anchors[t].polygonalBoundary.polylinePoints())yield e.point}*CornersToTheLeftOfBottom(){const t=this.layerArrays.x[this.bottomNode],e=this.currentTopSite.point.x,i=this.currentBottomSite.point.x;for(const s of this.LeftFromTheNode(this.NodeLayer(this.bottomNode),t,Ae.Bottom,e,i))for(const n of this.NodeCorners(s))n.y>this.currentBottomSite.point.y&&ii.PossibleCorner(e,i,n)&&(yield n)}*CornersToTheLeftOfTop(){const t=this.layerArrays.x[this.topNode],e=this.currentBottomSite.point.x,i=this.currentTopSite.point.x;for(const s of this.LeftFromTheNode(this.NodeLayer(this.topNode),t,Ae.Top,e,i))for(const n of this.NodeCorners(s))n.y<this.currentTopSite.point.y&&ii.PossibleCorner(e,i,n)&&(yield n)}*CornersToTheRightOfBottom(){const t=this.layerArrays.x[this.bottomNode],e=this.currentBottomSite.point.x,i=this.currentTopSite.point.x;for(const s of this.RightFromTheNode(this.NodeLayer(this.bottomNode),t,Ae.Bottom,e,i))for(const n of this.NodeCorners(s))n.y>this.currentBottomSite.point.y&&ii.PossibleCorner(e,i,n)&&(yield n)}*CornersToTheRightOfTop(){const t=this.layerArrays.x[this.topNode],e=this.currentTopSite.point.x,i=this.currentBottomSite.point.x;for(const s of this.RightFromTheNode(this.NodeLayer(this.topNode),t,Ae.Top,e,i))for(const n of this.NodeCorners(s))n.y<this.currentTopSite.point.y&&ii.PossibleCorner(e,i,n)&&(yield n)}static PossibleCorner(t,e,i){return i.x>t&&i.x<e}NodeLayer(t){return this.layerArrays.Layers[this.layerArrays.y[t]]}IsLabel(t){return this.anchors[t].hasLabel}NodeUCanBeCrossedByNodeV(t,e){return this.IsLabel(t)||this.IsLabel(e)?!1:!!(this.IsVirtualVertex(t)&&this.IsVirtualVertex(e)&&this.AdjacentEdgesIntersect(t,e))}AdjacentEdgesIntersect(t,e){return this.Intersect(this.IncomingEdge(t),this.IncomingEdge(e))||this.Intersect(this.OutcomingEdge(t),this.OutcomingEdge(e))}Intersect(t,e){return(this.layerArrays.x[t.Source]-this.layerArrays.x[e.Source])*(this.layerArrays.x[t.Target]-this.layerArrays.x[e.Target])<0}IncomingEdge(t){for(const e of this.layeredGraph.InEdges(t))return e;throw new Error}OutcomingEdge(t){for(const e of this.layeredGraph.OutEdges(t))return e;throw new Error}IsVirtualVertex(t){return t>=this.originalGraph.shallowNodeCount}*RightFromTheNode(t,e,i,s,n){let o=0,a=0;i===Ae.Bottom&&(o=Number.MAX_VALUE),i===Ae.Top&&(a=Number.MAX_VALUE);const h=t[e];for(let u=e+1;u<t.length;u++){const d=t[u];if(this.NodeUCanBeCrossedByNodeV(d,h))continue;const m=this.anchors[d];if(m.left>=n)break;m.right>s&&(m.topAnchor>a+C.distanceEpsilon?(a=m.topAnchor,yield d):m.bottomAnchor>o+C.distanceEpsilon&&(o=m.bottomAnchor,yield d))}}*LeftFromTheNode(t,e,i,s,n){let o=0,a=0;i===Ae.Bottom&&(o=Number.MAX_VALUE),i===Ae.Top&&(a=Number.MAX_VALUE);const h=t[e];for(let u=e-1;u>-1;u--){const d=t[u];if(this.NodeUCanBeCrossedByNodeV(d,h))continue;const m=this.anchors[d];if(m.right<=s)break;m.left<n&&(m.topAnchor>a+C.distanceEpsilon?(a=m.topAnchor,yield d):m.bottomAnchor>o+C.distanceEpsilon&&(o=m.bottomAnchor,yield d))}}}function ac(l){return DebugCurve.mkDebugCurveTWCI(100,1,"black",l.polygonalBoundary)}function lc(l,t){return DebugCurve.mkDebugCurveTWCI(200,2,t,CurveFactory.mkCircle(10,l))}class De{constructor(t,e,i,s,n,o,a){this.thinRightNodes=new Array,this.thinWestNodes=new Array,this.database=a,this.edgePath=t,this.anchors=e,this.layerArrays=n,this.originalGraph=i,this.settings=s,this.layeredGraph=o,this.eastHierarchy=this.BuildEastHierarchy(),this.westHierarchy=this.BuildWestHierarchy()}BuildEastHierarchy(){const t=this.FindEastBoundaryAnchorCurves(),e=new Array;for(const i of t)e.push(i.pNodeOverICurve());return this.thinEastHierarchy=An.Calculate(this.thinRightNodes),An.Calculate(e)}BuildWestHierarchy(){const t=this.FindWestBoundaryAnchorCurves(),e=new Array;for(const i of t)e.push(i.pNodeOverICurve());return this.thinWestHierarchy=An.Calculate(this.thinWestNodes),An.Calculate(e)}FindEastBoundaryAnchorCurves(){const t=new Array;let e=0;for(const i of this.edgePath){let s=null;for(const n of this.EastBoundaryNodesOfANode(i,ps.GetNodeKind(e,this.edgePath))){const o=this.anchors[n];(s==null||s.origin.x>o.origin.x)&&(s=o),t.push(o.polygonalBoundary)}s!=null&&this.thinRightNodes.push(N.mkLinePXY(s.origin,this.originalGraph.right,s.y).pNodeOverICurve()),e++}return t}FindWestBoundaryAnchorCurves(){const t=[];let e=0;for(const i of this.edgePath.nodes()){let s=-1;for(const n of this.LeftBoundaryNodesOfANode(i,ps.GetNodeKind(e,this.edgePath)))(s===-1||this.layerArrays.x[n]>this.layerArrays.x[s])&&(s=n),t.push(this.anchors[n].polygonalBoundary);if(s!==-1){const n=this.anchors[s];this.thinWestNodes.push(N.mkLinePXY(n.origin,this.originalGraph.left,n.origin.y).pNodeOverICurve())}e++}return t}*FillRightTopAndBottomVerts(t,e,i){let s=0,n=0;i===Ae.Bottom?s=Number.MAX_VALUE:i===Ae.Top&&(n=Number.MAX_VALUE);const o=t[e];for(let a=e+1;a<t.length;a++){const h=t[a],u=this.anchors[h];u.topAnchor>n?this.NodeUCanBeCrossedByNodeV(h,o)||(n=u.topAnchor,u.bottomAnchor>s&&(s=u.bottomAnchor),yield h):u.bottomAnchor>s&&(this.NodeUCanBeCrossedByNodeV(h,o)||(s=u.bottomAnchor,u.topAnchor>n&&(n=u.topAnchor),yield h))}}*FillLeftTopAndBottomVerts(t,e,i){let s=0,n=0;i===Ae.Top?n=Number.MAX_VALUE:i===Ae.Bottom&&(s=Number.MAX_VALUE);const o=t[e];for(let a=e-1;a>=0;a--){const h=t[a],u=this.anchors[h];u.topAnchor>n+C.distanceEpsilon?this.NodeUCanBeCrossedByNodeV(h,o)||(n=u.topAnchor,s=Math.max(s,u.bottomAnchor),yield h):u.bottomAnchor>s+C.distanceEpsilon&&(this.NodeUCanBeCrossedByNodeV(h,o)||(n=Math.max(n,u.topAnchor),s=u.bottomAnchor,yield h))}}IsVirtualVertex(t){return t>=this.originalGraph.shallowNodeCount}IsLabel(t){return this.anchors[t].hasLabel}NodeUCanBeCrossedByNodeV(t,e){return this.IsLabel(t)||this.IsLabel(e)?!1:!!(this.IsVirtualVertex(t)&&this.IsVirtualVertex(e)&&this.EdgesIntersectSomewhere(t,e))}EdgesIntersectSomewhere(t,e){return this.UVAreMiddlesOfTheSameMultiEdge(t,e)?!1:this.IntersectAbove(t,e)||this.IntersectBelow(t,e)}UVAreMiddlesOfTheSameMultiEdge(t,e){return!!(this.database.MultipleMiddles.has(t)&&this.database.MultipleMiddles.has(e)&&this.SourceOfTheOriginalEdgeContainingAVirtualNode(t)===this.SourceOfTheOriginalEdgeContainingAVirtualNode(e))}SourceOfTheOriginalEdgeContainingAVirtualNode(t){for(;this.IsVirtualVertex(t);)t=this.IncomingEdge(t).Source;return t}IntersectBelow(t,e){do{const i=this.OutcomingEdge(t),s=this.OutcomingEdge(e);if(this.Intersect(i,s))return!0;t=i.Target,e=s.Target}while(this.IsVirtualVertex(t)&&this.IsVirtualVertex(e));return t===e}IntersectAbove(t,e){do{const i=this.IncomingEdge(t),s=this.IncomingEdge(e);if(this.Intersect(i,s))return!0;t=i.Source,e=s.Source}while(this.IsVirtualVertex(t)&&this.IsVirtualVertex(e));return t===e}Intersect(t,e){const i=this.layerArrays.x[t.Source]-this.layerArrays.x[e.Source],s=this.layerArrays.x[t.Target]-this.layerArrays.x[e.Target];return i>0&&s<0||i<0&&s>0}IncomingEdge(t){return this.layeredGraph.InEdgeOfVirtualNode(t)}OutcomingEdge(t){return this.layeredGraph.OutEdgeOfVirtualNode(t)}EastBoundaryNodesOfANode(t,e){return this.FillRightTopAndBottomVerts(this.NodeLayer(t),this.layerArrays.x[t],e)}NodeLayer(t){return this.layerArrays.Layers[this.layerArrays.y[t]]}LeftBoundaryNodesOfANode(t,e){return this.FillLeftTopAndBottomVerts(this.NodeLayer(t),this.layerArrays.x[t],e)}getSpline(t){return this.createRefinedPolyline(t),this.createSmoothedPolyline()}get GetPolyline(){return new Y(this.headSite)}LineSegIntersectBound(t,e){const i=N.mkPP(t,e);return De.CurveIntersectsHierarchy(i,this.westHierarchy)||De.CurveIntersectsHierarchy(i,this.thinWestHierarchy)||De.CurveIntersectsHierarchy(i,this.eastHierarchy)||De.CurveIntersectsHierarchy(i,this.thinEastHierarchy)}SegIntersectWestBound(t,e){return De.SegIntersectsBound(t,e,this.westHierarchy)||De.SegIntersectsBound(t,e,this.thinWestHierarchy)}SegIntersectEastBound(t,e){return De.SegIntersectsBound(t,e,this.eastHierarchy)||De.SegIntersectsBound(t,e,this.thinEastHierarchy)}TryToRemoveInflectionCorner(t){if(!t.s.next||!t.s.prev||t.s.turn===D.Counterclockwise&&this.SegIntersectEastBound(t.s.prev,t.s.next)||t.s.turn===D.Clockwise&&this.SegIntersectWestBound(t.s.prev,t.s.next)){t.cut=!1,t.s=t.s.next;return}const e=t.s.next;t.s.prev.next=e,e.prev=t.s.prev,t.s=e,t.cut=!0}static SegIntersectsBound(t,e,i){return De.CurveIntersectsHierarchy(N.mkPP(t.point,e.point),i)}static CurveIntersectsHierarchy(t,e){if(e==null||!Pt.intersect(t.pNodeOverICurve().parallelogram,e.parallelogram))return!1;if(e.node.hasOwnProperty("children")){const i=e.node;return De.CurveIntersectsHierarchy(t,i.children[0])||De.CurveIntersectsHierarchy(t,i.children[1])}return w.intersectionOne(t,e.seg,!1)!=null}static Flat(t){return c.getTriangleOrientation(t.prev.point,t.point,t.next.point)===D.Collinear}Reverse(){const t=new De(this.edgePath,this.anchors,this.originalGraph,this.settings,this.layerArrays,this.layeredGraph,this.database);let e=this.headSite,i=null;for(;e!=null;)t.headSite=e.clone(),t.headSite.next=i,i!=null&&(i.prev=t.headSite),i=t.headSite,e=e.next;return t}createRefinedPolyline(t){this.CreateInitialListOfSites();let e=this.headSite,i;for(let s=0;s<this.edgePath.count;s++)i=e.next,this.RefineBeetweenNeighborLayers(e,this.EdgePathNode(s),this.EdgePathNode(s+1)),e=i;this.TryToRemoveInflections(),t&&this.OptimizeShortPath()}RefineBeetweenNeighborLayers(t,e,i){ii.Refine(e,i,t,this.anchors,this.layerArrays,this.layeredGraph,this.originalGraph,this.settings.LayerSeparation)}CreateInitialListOfSites(){let t=this.headSite=Dt.mkSiteP(this.EdgePathPoint(0));for(let e=1;e<=this.edgePath.count;e++)t=Dt.mkSiteSP(t,this.EdgePathPoint(e))}get TailSite(){let t=this.headSite;for(;t.next!=null;)t=t.next;return t}OptimizeForThreeSites(){const t=this.EdgePathNode(0),e=this.EdgePathNode(2),i=this.anchors[t],s=this.anchors[e];if(R(i.x,s.x))return;const n={ax:i.x,bx:s.x,sign:0};if(!this.FindLegalPositions(i,s,n))return;const o=(i.y-s.y)/(i.bottom-s.top),a=.5*(n.ax+n.bx),h=n.sign*((n.ax-n.bx)*.5);n.ax=a+o*(h*n.sign),n.bx=a-o*(h*n.sign),this.headSite.point=new c(n.ax,i.y);const u=this.headSite.next,d=u.point.y;u.point=new c(this.MiddlePos(n.ax,n.bx,i,s,d),d),u.next.point=new c(n.bx,s.y);const m=this.anchors[this.EdgePathNode(1)];m.x=u.point.x}OptimizeForTwoSites(){const t=this.EdgePathNode(0),e=this.EdgePathNode(1),i=this.anchors[t],s=this.anchors[e];if(R(i.x,s.x))return;const n={ax:i.x,bx:s.x,sign:0};if(!this.FindPositions(i,s,n))return;const o=(i.y-s.y)/(i.bottom-s.top),a=.5*(n.ax+n.bx),h=n.sign*((n.ax-n.bx)*.5);n.ax=a+o*(h*n.sign),n.bx=a-o*(h*n.sign),this.headSite.point=new c(n.ax,i.y),this.headSite.next.point=new c(n.bx,s.y)}FindLegalPositions(t,e,i){return this.FindPositions(t,e,i)?this.PositionsAreLegal(i.ax,i.bx,i.sign,t,e,this.EdgePathNode(1)):!1}FindPositions(t,e,i){let s,n;if(i.ax<i.bx?(i.sign=1,n=Math.max(i.ax,e.left),s=Math.min(t.right,i.bx)):(i.sign=-1,n=Math.max(t.left,i.bx),s=Math.min(e.right,i.ax)),n<=s)i.bx=.5*(n+s),i.ax=.5*(n+s);else{if(this.OriginToOriginSegCrossesAnchorSide(t,e))return!1;i.sign===1?(i.ax=t.right-.1*t.rightAnchor,i.bx=e.left):(i.ax=t.left+.1*t.leftAnchor,i.bx=e.right)}return!0}OriginToOriginSegCrossesAnchorSide(t,e){const i=N.mkPP(t.origin,e.origin);return t.x<e.x&&w.CurvesIntersect(i,N.mkPP(t.rightBottom,t.rightTop))||w.CurvesIntersect(i,N.mkPP(e.leftBottom,t.leftTop))||t.x>e.x&&w.CurvesIntersect(i,N.mkPP(t.leftBottom,t.leftTop))||w.CurvesIntersect(i,N.mkPP(e.rightBottom,t.rightTop))}OptimizeShortPath(){this.edgePath.count>2||(this.edgePath.count===2&&this.headSite.next.next!=null&&this.headSite.next.next.next==null&&this.anchors[this.EdgePathNode(1)].node==null?this.OptimizeForThreeSites():this.edgePath.count===1&&this.OptimizeForTwoSites())}PositionsAreLegal(t,e,i,s,n,o){if(!R(t,e)&&(t-e)*i>0)return!1;const a=this.anchors[o],h=this.MiddlePos(t,e,s,n,a.y);return this.MiddleAnchorLegal(h,o,a)?!this.LineSegIntersectBound(new c(t,s.bottom),new c(e,n.top)):!1}MiddleAnchorLegal(t,e,i){const s=this.NodeLayer(e),n=this.layerArrays.x[e],o=t-i.x;return!(n>0&&this.anchors[s[n-1]].right>o+i.left||n<s.length-1&&this.anchors[s[n+1]].left<o+i.right)}MiddlePos(t,e,i,s,n){const o=i.y-n,a=n-s.y;return(t*o+e*a)/(o+a)}TryToRemoveInflections(){if(this.TurningAlwaySameDirection())return;let t=!0;for(;t;){t=!1;for(const e={s:this.headSite,cut:!1};e.s;)this.TryToRemoveInflectionCorner(e),t=e.cut||t}}TurningAlwaySameDirection(){let t=0;for(let e=this.headSite.next;e!=null&&e.next!=null;e=e.next){const i=e.turn;if(t===0)i>0?t=1:i<0&&(t=-1);else if(t*i<0)return!1}return!0}EdgePathPoint(t){return this.anchors[this.EdgePathNode(t)].origin}EdgePathNode(t){return t===this.edgePath.count?this.edgePath.LayerEdges[this.edgePath.count-1].Target:this.edgePath.LayerEdges[t].Source}createSmoothedPolyline(){this.RemoveVerticesWithNoTurns();let t=new w;const e=this.headSite,i=w.findCorner(e);return i!==void 0?(this.createFilletCurve(t,{a:e,b:i.b,c:i.c}),t=this.ExtendCurveToEndpoints(t)):t.addSegment(N.mkPP(this.headSite.point,this.TailSite.point)),t}curveIsLegal(t){return!0}RemoveVerticesWithNoTurns(){for(;this.RemoveVerticesWithNoTurnsOnePass(););}RemoveVerticesWithNoTurnsOnePass(){let t=!1;for(let e=this.headSite;e.next!=null&&e.next.next!=null;e=e.next)De.Flat(e.next)&&(t=!0,e.next=e.next.next,e.next.prev=e);return t}ExtendCurveToEndpoints(t){let e=this.headSite.point;if(!c.closeDistEps(e,t.start)){const i=new w;i.addSegs([N.mkPP(e,t.start),t]),t=i}return e=this.TailSite.point,c.closeDistEps(e,t.end)||t.addSegment(N.mkPP(t.end,e)),t}createFilletCurve(t,e){for(;this.AddSmoothedCorner(e.a,e.b,e.c,t),e.a=e.b,e.b=e.c,e.b.next!=null;)e.c=e.b.next}AddSmoothedCorner(t,e,i,s){let n=.5,o;do o=w.createBezierSeg(n,n,t,e,i),e.previouisBezierCoefficient=n,n/=2;while(this.BezierSegIntersectsBoundary(o));if(n*=2,n<.5){n=.5*(n+n*2);const a=w.createBezierSeg(n,n,t,e,i);this.BezierSegIntersectsBoundary(a)||(e.nextBezierCoefficient=n,e.previouisBezierCoefficient=n,o=a)}s.segs.length>0&&!c.closeDistEps(s.end,o.start)&&s.addSegment(N.mkPP(s.end,o.start)),s.addSegment(o)}BezierSegIntersectsBoundary(t){return c.signedDoubledTriangleArea(t.B(0),t.B(1),t.B(2))<0?this.BezierSegIntersectsTree(t,this.thinWestHierarchy)||this.BezierSegIntersectsTree(t,this.westHierarchy):this.BezierSegIntersectsTree(t,this.thinEastHierarchy)||this.BezierSegIntersectsTree(t,this.eastHierarchy)}BezierSegIntersectsTree(t,e){if(e==null)return!1;if(Pt.intersect(t.pNodeOverICurve().parallelogram,e.parallelogram))if(e.node.hasOwnProperty("children")){const i=e.node;return this.BezierSegIntersectsTree(t,i.children[0])||this.BezierSegIntersectsTree(t,i.children[1])}else return De.BezierSegIntersectsBoundary(t,e.seg);else return!1}static BezierSegIntersectsBoundary(t,e){for(const i of w.getAllIntersections(t,e,!1))if(e instanceof w){const s=e;if(w.realCutWithClosedCurve(i,s,!1))return!0}else return!0;return!1}}class ps extends Ft{constructor(t,e,i,s,n,o){super(null),this.settings=t,this.OriginalGraph=e,this.Database=i,this.ProperLayeredGraph=n,this.LayerArrays=s,this.IntGraph=o}run(){this.createSplines()}createSplines(){this.createRegularSplines(),this.createSelfSplines(),this.IntGraph!=null&&this.RouteFlatEdges(),this.OriginalGraph.graph.parent==null&&this.RouteUnroutedEdges()}RouteUnroutedEdges(){const t=[];for(const o of this.OriginalGraph.deepEdges)o.curve||t.push(o);if(t.length==0)return;const i=(this.OriginalGraph.layoutSettings?this.OriginalGraph.layoutSettings:new Hs).commonSettings.edgeRoutingSettings;new qt(this.OriginalGraph,t,i.padding,i.polylinePadding,i.coneAngle,i.bundlingSettings,this.cancelToken).run(),bt.constructorGA(this.OriginalGraph,t).run()}RouteFlatEdges(){}createRegularSplines(){for(const t of this.Database.RegularMultiedges()){if(Zh(t))continue;const e=t.length,i=e===1&&this.MayOptimizeEdge(t[0]);for(let s=Math.floor(e/2);s<e;s++)this.createSplineForNonSelfEdge(t[s],i);for(let s=Math.floor(e/2)-1;s>=0;s--)this.createSplineForNonSelfEdge(t[s],i)}}MayOptimizeEdge(t){return!(this.ProperLayeredGraph.OutDegreeIsMoreThanOne(t.source)||this.ProperLayeredGraph.InDegreeIsMoreThanOne(t.target)||Ya(t.edge.source)||Ya(t.edge.target))}createSelfSplines(){for(const[t,e]of this.Database.Multiedges.keyValues()){const i=t;if(i.x===i.y){const s=this.Database.Anchors[i.x];let n=s.leftAnchor;for(const o of e){const a=this.settings.NodeSeparation+(this.settings.MinNodeWidth+n),h=s.bottomAnchor/2,u=s.origin,d=u.add(new c(0,h)),m=u.add(new c(a,h)),y=u.add(new c(a,-h)),E=u.add(new c(0,-h));let T=Dt.mkSiteP(u);const B=new Y(T);T=Dt.mkSiteSP(T,d),T=Dt.mkSiteSP(T,m),T=Dt.mkSiteSP(T,y),T=Dt.mkSiteSP(T,E),Dt.mkSiteSP(T,u);const H=B.createCurve();if(o.curve=H,n=a,o.edge.label!=null){n+=o.edge.label.width;const tt=H.value((H.parStart+H.parEnd)/2),lt=new c(tt.x+o.labelWidth/2,s.y),Q=new c(o.edge.label.width/2,o.edge.label.height/2),dt=X.mkPP(lt.add(Q),lt.sub(Q));o.edge.label.width=dt.width,o.edge.label.height=dt.height,o.edge.label.positionCenter(lt)}Bt.trimSplineAndCalculateArrowheadsII(o.edge,o.edge.source.boundaryCurve,o.edge.target.boundaryCurve,H,!1)}}}}createSplineForNonSelfEdge(t,e){t.LayerEdges!=null&&(this.drawSplineBySmothingThePolyline(t,e),t.IsVirtualEdge||(t.updateEdgeLabelPosition(this.Database.Anchors),Bt.trimSplineAndCalculateArrowheadsII(t.edge,t.edge.source.boundaryCurve,t.edge.target.boundaryCurve,t.curve,!0)))}drawSplineBySmothingThePolyline(t,e){const s=new De(t,this.Database.Anchors,this.OriginalGraph,this.settings,this.LayerArrays,this.ProperLayeredGraph,this.Database).getSpline(e);t.reversed?t.curve=s.reverse():t.curve=s}static UpdateLabel(t,e){let i=null;e.labelIsToTheRightOfTheSpline?(t.label.positionCenter(new c(e.x+e.rightAnchor/2,e.y)),i=N.mkPP(t.label.boundingBox.leftTop,t.label.boundingBox.leftBottom)):e.labelIsToTheLeftOfTheSpline&&(t.label.positionCenter(new c(e.x-e.leftAnchor/2,e.y)),i=N.mkPP(t.label.boundingBox.rightTop,t.label.boundingBox.rightBottom));const s=ps.GetSegmentInFrontOfLabel(t.curve,t.label.center.y);if(s!=null&&w.getAllIntersections(t.curve,w.polyFromBox(t.label.boundingBox),!1).length===0){const n={curveClosestPoint:void 0,labelSideClosest:void 0};if(ps.FindClosestPoints(n,s,i))ps.ShiftLabel(t,n);else{const o=s.closestParameter(i.start),a=s.closestParameter(i.end);s.value(o).sub(i.start).length<s.value(a).sub(i.end).length?(n.curveClosestPoint=s.value(o),n.labelSideClosest=i.start):(n.curveClosestPoint=s.value(a),n.labelSideClosest=i.end),ps.ShiftLabel(t,n)}}}static ShiftLabel(t,e){const i=t.lineWidth/2,s=e.curveClosestPoint.sub(e.labelSideClosest),n=s.length;n>i&&t.label.positionCenter(t.label.center.add(s.div(n*(n-i))))}static FindClosestPoints(t,e,i){const s=w.minDistWithinIntervals(e,i,e.parStart,e.parEnd,i.parStart,i.parEnd,(e.parStart+e.parEnd)/2,(i.parStart+i.parEnd)/2);return s?(t.curveClosestPoint=s.aX,t.labelSideClosest=s.bX,!0):!1}static GetSegmentInFrontOfLabel(t,e){if(t instanceof w){const i=t;for(const s of i.segs)if((s.start.y-e)*(s.end.y-e)<=0)return s}return null}static GetNodeKind(t,e){return t===0?Ae.Top:t<e.count?Ae.Internal:Ae.Bottom}}function Zh(l){if(l.length<4)return!1;for(const t of l)if(t.edge.label)return!1;return!0}function Ya(l){return l.node.selfEdges.size>0}function _h(l,t){new qo(l,l.layoutSettings,t).run()}function hc(l,t,e){const i=l.layoutSettings?l.layoutSettings:new SugiyamaLayoutSettings;if(enforceLayoutSettings(l,i),layoutGeomGraphDetailed(l,t,_h,routeEdges,optimalPackingRunner),e){const s=new PlaneTransformation(1,0,-l.boundingBox.left,0,-1,l.top);l.transform(s)}}class qo extends Ft{get extremeAspectRatio(){const t=this.originalGraph.boundingBox,e=t.width/t.height;return e<1/50||e>50}get verticalConstraints(){return this.sugiyamaSettings.verticalConstraints}get HorizontalConstraints(){return this.sugiyamaSettings.horizontalConstraints}constructor(t,e,i){if(super(i),this.LayersAreDoubled=!1,t==null)return;this.originalGraph=t,this.sugiyamaSettings=e;const s=Array.from(t.shallowNodes);this.nodeIdToIndex=new Map;let n=0;for(const a of s)this.nodeIdToIndex.set(a.id,n++);const o=[];for(const a of this.originalGraph.shallowEdges){const h=this.nodeIdToIndex.get(a.source.id);if(h==null)continue;const u=this.nodeIdToIndex.get(a.target.id);if(u==null)continue;const d=new Ti(h,u,a);o.push(d)}this.IntGraph=new ur(o,t.shallowNodeCount),this.IntGraph.nodes=s,this.database=new Wh(s.length);for(const a of this.IntGraph.edges)this.database.registerOriginalEdgeInMultiedges(a);this.cycleRemoval()}run(){if(this.originalGraph.shallowNodeCount===0){this.originalGraph.boundingBox=X.mkEmpty();return}fu(this.originalGraph,this.sugiyamaSettings.transform),this.engineLayerArrays=this.calculateLayers(),this.sugiyamaSettings.edgeRoutingSettings.EdgeRoutingMode===Be.SugiyamaSplines&&this.runPostLayering(),pu(this.originalGraph,this.sugiyamaSettings.transform)}runPostLayering(){const t=this.sugiyamaSettings.commonSettings.edgeRoutingSettings,e=this.constrainedOrdering!=null?Be.Spline:t.EdgeRoutingMode;this.extremeAspectRatio?Oa(this.originalGraph,Array.from(this.originalGraph.deepEdges),this.cancelToken):e===Be.SugiyamaSplines?this.calculateEdgeSplines():Ma(this.originalGraph,Array.from(this.originalGraph.deepEdges),this.cancelToken)}SetLabels(){throw new Error("not implementedt")}cycleRemoval(){const t=this.sugiyamaSettings.verticalConstraints,e=t.isEmpty?S.getFeedbackSet(this.IntGraph):t.getFeedbackSetExternal(this.IntGraph,this.nodeIdToIndex);this.database.addFeedbackSet(e)}calculateLayers(){this.CreateGluedDagSkeletonForLayering();const t=this.CalculateLayerArrays();return this.UpdateNodePositionData(),t}UpdateNodePositionData(){for(let t=0;t<this.IntGraph.nodeCount&&t<this.database.Anchors.length;t++)this.IntGraph.nodes[t].center=this.database.Anchors[t].origin;if(this.sugiyamaSettings.GridSizeByX>0)for(let t=0;t<this.originalGraph.shallowNodeCount;t++)this.SnapLeftSidesOfTheNodeToGrid(t,this.sugiyamaSettings.GridSizeByX)}SnapLeftSidesOfTheNodeToGrid(t,e){const i=this.IntGraph.nodes[t],s=this.database.Anchors[t];s.leftAnchor-=e/2,s.rightAnchor-=e/2;const n=i.boundingBox.left,o=Math.floor(n/e),a=n-o*e;Math.abs(a)<.001||(Math.abs(a)<=e/2?i.center=i.center.add(new c(-a,0)):i.center=i.center.add(new c(e-a,0)),s.x=i.center.x)}GetCurrentHeight(){const t=new x;for(const e of this.NodeAnchors())t.AddValue(e.top),t.AddValue(e.bottom);return t.length}*NodeAnchors(){const t=Math.min(this.IntGraph.nodeCount,this.anchors.length);for(let e=0;e<t;e++)yield this.anchors[e]}GetCurrentWidth(){const t=new x;for(const e of this.NodeAnchors())t.AddValue(e.left),t.AddValue(e.right);return t.length}ExtendLayeringToUngluedSameLayerVertices(t){const e=this.verticalConstraints;for(let i=0;i<t.length;i++)t[i]=t[e.nodeToRepr(i)];return t}calculateEdgeSplines(){new ps(this.sugiyamaSettings,this.originalGraph,this.database,this.engineLayerArrays,this.properLayeredGraph,this.IntGraph).run()}YLayeringAndOrdering(t){let e=t.GetLayers();Wo.Balance(this.gluedDagSkeletonForLayering,e,this.GetNodeCountsOfGluedDag(),null),e=this.ExtendLayeringToUngluedSameLayerVertices(e);let i=new Ui(e);if(this.HorizontalConstraints==null||this.HorizontalConstraints.IsEmpty)return i=this.YLayeringAndOrderingWithoutHorizontalConstraints(i),i;throw new Error("not implemented")}CreateProperLayeredGraph(t){const e=t.length;let i=0;for(const n of this.database.SkeletonEdges()){const o=nu(t,n);o>0&&(n.LayerEdges=new Array(o));let a=0;if(o>1){let h=e+i++,u=new us(n.source,h,n.CrossingWeight,n.weight);n.LayerEdges[a++]=u;for(let d=0;d<o-2;d++)h++,i++,u=new us(h-1,h,n.CrossingWeight,n.weight),n.LayerEdges[a++]=u;u=new us(h,n.target,n.CrossingWeight,n.weight),n.LayerEdges[a]=u}else if(o===1){const h=new us(n.source,n.target,n.CrossingWeight,n.weight);n.LayerEdges[a]=h}}const s=new Array(this.originalGraph.shallowNodeCount+i).fill(0);for(const n of this.database.SkeletonEdges())if(n.LayerEdges!=null){let o=t[n.source];s[n.source]=o--;for(const a of n.LayerEdges)s[a.Target]=o--}else s[n.source]=t[n.source],s[n.target]=t[n.target];return this.properLayeredGraph=new js(new ur(Array.from(this.database.SkeletonEdges()),t.length)),this.properLayeredGraph.BaseGraph.nodes=this.IntGraph.nodes,new Ui(s)}YLayeringAndOrderingWithoutHorizontalConstraints(t){const e=this.CreateProperLayeredGraph(t.y);return Cn.OrderLayers(this.properLayeredGraph,e,this.originalGraph.shallowNodeCount,this.sugiyamaSettings,this.cancelToken),so.UpdateLayerArrays1(this.properLayeredGraph,e),e}CalculateYLayers(){const t=this.YLayeringAndOrdering(new Yh(this.gluedDagSkeletonForLayering,this.cancelToken));return this.constrainedOrdering!=null?t:this.InsertLayersIfNeeded(t)}InsertLayersIfNeeded(t){this.InsertVirtualEdgesIfNeeded(t);const e=this.AnalyzeNeedToInsertLayersAndHasMultiedges(t);if(e.needToInsertLayers){const i=cr.InsertLayers(this.properLayeredGraph,t,this.database,this.IntGraph);this.properLayeredGraph=i.layeredGraph,t=i.la,this.LayersAreDoubled=!0}else if(e.multipleEdges){const i=Qs.InsertPaths(this.properLayeredGraph,t,this.database,this.IntGraph);this.properLayeredGraph=i.layeredGraph,t=i.la}return this.RecreateIntGraphFromDataBase(),t}RecreateIntGraphFromDataBase(){let t=new Array;for(const e of this.database.Multiedges.values())t=t.concat(e);this.IntGraph.SetEdges(t,this.IntGraph.nodeCount)}InsertVirtualEdgesIfNeeded(t){if(this.constrainedOrdering==null){for(const[e,i]of this.database.Multiedges.keyValues())if(i.length%2===0&&t.y[e.x]-1===t.y[e.y]){const s=new we(null),n=new Ti(e.x,e.y,s);n.IsVirtualEdge=!0,i.splice(i.length/2,0,n),this.IntGraph.addEdge(n)}}}AnalyzeNeedToInsertLayersAndHasMultiedges(t){let e=!1,i=!1;for(const s of this.IntGraph.edges)if(s.hasLabel&&t.y[s.source]!==t.y[s.target]){e=!0;break}if(e===!1&&this.constrainedOrdering==null){for(const[s,n]of this.database.Multiedges.keyValues())if(n.length>1&&(i=!0,t.y[s.x]-t.y[s.y]===1)){e=!0;break}}return{needToInsertLayers:e,multipleEdges:i}}UseBrandesXCalculations(t){return t.x.length>=this.sugiyamaSettings.BrandesThreshold}CalculateAnchorsAndYPositions(t){this.anchors=eu(this.database,this.properLayeredGraph,this.originalGraph,this.IntGraph,this.sugiyamaSettings),iu(t,500,this.originalGraph,this.database,this.IntGraph,this.sugiyamaSettings,this.LayersAreDoubled)}OptimizeEdgeLabelsLocations(){for(let t=0;t<this.anchors.length;t++){const e=this.anchors[t];if(e.labelIsToTheRightOfTheSpline){const i=this.GetSuccessorAndPredecessor(t);if(!lu(e,i.predecessor,i.successor)){const s=i.predecessor.origin.sub(e.origin).length+i.successor.origin.sub(e.origin).length,n=e.right-e.leftAnchor,o=new c(n,e.y);i.predecessor.origin.sub(o).length+i.successor.origin.sub(o).length<s&&tl(e)}}}}GetSuccessorAndPredecessor(t){let e;for(const s of this.properLayeredGraph.InEdges(t))e=s.Source;let i;for(const s of this.properLayeredGraph.OutEdges(t))i=s.Target;return{predecessor:this.anchors[e],successor:this.anchors[i]}}CalculateLayerArrays(){const t=this.CalculateYLayers();return this.constrainedOrdering==null?(this.CalculateAnchorsAndYPositions(t),this.UseBrandesXCalculations(t)?this.CalculateXPositionsByBrandes(t):this.CalculateXLayersByGansnerNorth(t)):this.anchors=this.database.Anchors,this.OptimizeEdgeLabelsLocations(),this.engineLayerArrays=t,this.StraightensShortEdges(),this.CalculateOriginalGraphBox(),t}StretchToDesiredAspectRatio(t,e){t>e?this.StretchInYDirection(t/e):t<e&&this.StretchInXDirection(e/t)}StretchInYDirection(t){const e=(this.originalGraph.boundingBox.top+this.originalGraph.boundingBox.bottom)/2;for(const s of this.database.Anchors)s.bottomAnchor=s.bottomAnchor*t,s.topAnchor=s.topAnchor*t,s.y=e+t*(s.y-e);const i=this.originalGraph.height*t;this.originalGraph.boundingBox=new X({left:this.originalGraph.boundingBox.left,top:e+i/2,right:this.originalGraph.boundingBox.right,bottom:e-i/2})}StretchInXDirection(t){const e=(this.originalGraph.boundingBox.left+this.originalGraph.boundingBox.right)/2;for(const s of this.database.Anchors)s.leftAnchor=s.leftAnchor*t,s.rightAnchor=s.rightAnchor*t,s.x=e+t*(s.x-e);const i=this.originalGraph.width*t;this.originalGraph.boundingBox=new X({left:e-i/2,top:this.originalGraph.boundingBox.top,right:e+i/2,bottom:this.originalGraph.boundingBox.bottom})}CalculateOriginalGraphBox(){if(this.anchors.length===0)return;const t=new X({left:this.anchors[0].left,top:this.anchors[0].top,right:this.anchors[0].right,bottom:this.anchors[0].bottom});for(let e=1;e<this.anchors.length;e++){const i=this.anchors[e];t.add(i.leftTop),t.add(i.rightBottom)}this.originalGraph.labelSize&&this.originalGraph.addLabelToGraphBB(t),t.padEverywhere(this.originalGraph.margins),this.originalGraph.boundingBox=t}StraightensShortEdges(){if(!(this.anchors.length<20))for(;this.StraightenEdgePaths(););}StraightenEdgePaths(){let t=!1;for(const e of this.database.AllIntEdges())e.LayerSpan===2&&(t=this.ShiftVertexWithNeighbors(e.LayerEdges[0].Source,e.LayerEdges[0].Target,e.LayerEdges[1].Target)||t);return t}ShiftVertexWithNeighbors(t,e,i){const s=this.database.Anchors[t],n=this.database.Anchors[i],o=this.database.Anchors[e],a=(o.y-s.y)*((n.x-s.x)/(n.y-s.y))+s.x,h=1e-4;return a>o.x+h?this.TryShiftToTheRight(a,e):a<o.x-h?this.TryShiftToTheLeft(a,e):!1}TryShiftToTheLeft(t,e){const i=this.engineLayerArrays.Layers[this.engineLayerArrays.y[e]],s=this.engineLayerArrays.x[e];if(s>0){const n=this.database.Anchors[i[s-1]],o=Math.max(n.right+(this.sugiyamaSettings.NodeSeparation+this.database.Anchors[e].leftAnchor),t);return o<this.database.Anchors[e].x-1?(this.database.Anchors[e].x=o,!0):!1}return this.database.Anchors[e].x=t,!0}TryShiftToTheRight(t,e){const i=this.engineLayerArrays.Layers[this.engineLayerArrays.y[e]],s=this.engineLayerArrays.x[e];if(s<i.length-1){const n=this.database.Anchors[i[s+1]],o=Math.min(n.left-(this.sugiyamaSettings.NodeSeparation-this.database.Anchors[e].rightAnchor),t);return o>this.database.Anchors[e].x+1?(this.database.Anchors[e].x=o,!0):!1}return this.database.Anchors[e].x=t,!0}CalculateXLayersByGansnerNorth(t){this.xLayoutGraph=this.CreateXLayoutGraph(t),this.CalculateXLayersByGansnerNorthOnProperLayeredGraph()}CalculateXLayersByGansnerNorthOnProperLayeredGraph(){const t=new Ka(this.xLayoutGraph,null).GetLayers();for(let e=0;e<this.database.Anchors.length;e++)this.anchors[e].x=t[e]}CreateXLayoutGraph(t){let e=this.properLayeredGraph.NodeCount;const i=new Array;for(const n of this.properLayeredGraph.Edges){const o=new Ti(e,n.Source,null),a=new Ti(e,n.Target,null);a.weight=n.Weight,o.weight=n.Weight,o.separation=0,a.separation=0,e++,i.push(o),i.push(a)}for(const n of t.Layers)for(let o=n.length-1;o>0;o--){const a=n[o],h=n[o-1],u=new Ti(a,h,null),d=this.database.Anchors[a],m=this.database.Anchors[h],y=d.leftAnchor+(m.rightAnchor+this.sugiyamaSettings.NodeSeparation);u.separation=Math.ceil(y+.5),i.push(u)}const s=new Jh(this.IntGraph,this.properLayeredGraph,t,i,e);return s.SetEdgeWeights(),s}CalculateXPositionsByBrandes(t){$s.CalculateXCoordinates(t,this.properLayeredGraph,this.originalGraph.shallowNodeCount,this.database.Anchors,this.sugiyamaSettings.NodeSeparation)}GluedDagSkeletonEdges(){const t=new hs;for(const[i,s]of this.database.Multiedges.keyValues()){if(i.isDiagonal())continue;const n=this.verticalConstraints.gluedIntEdge(s[0]);n.source!==n.target&&t.set(n.source,n.target,n)}const e=Array.from(this.verticalConstraints.gluedUpDownIntConstraints.values()).map(i=>su(i,null));for(const i of e)t.set(i.source,i.target,i);return Array.from(t.values())}static CalcAnchorsForOriginalNode(t,e,i,s,n){const o={leftAnchor:0,rightAnchor:0,topAnchor:0,bottomAnchor:0};if(e.nodes!=null){const u=e.nodes[t];cu(o,u,n)}du(t,o,s,n);const a=n.MinNodeWidth/2;o.leftAnchor<a&&(o.leftAnchor=a),o.rightAnchor<a&&(o.rightAnchor=a);const h=n.MinNodeHeight/2;o.topAnchor<h&&(o.topAnchor=h),o.bottomAnchor<h&&(o.bottomAnchor=h),i[t]=ei.mkAnchor(o.leftAnchor,o.rightAnchor,o.topAnchor,o.bottomAnchor,e.nodes[t],n.LabelCornersPreserveCoefficient),i[t].padding=1}CreateGluedDagSkeletonForLayering(){this.gluedDagSkeletonForLayering=new ur(this.GluedDagSkeletonEdges(),this.originalGraph.shallowNodeCount),this.SetGluedEdgesWeights()}SetGluedEdgesWeights(){const t=new hs;for(const e of this.gluedDagSkeletonForLayering.edges)t.set(e.source,e.target,e);for(const[e,i]of this.database.Multiedges.keyValues())if(e.x!==e.y){const s=this.verticalConstraints.gluedIntPair(e);if(s.x===s.y)continue;const n=t.get(s.x,s.y);for(const o of i)n.weight+=o.weight}}GetNodeCountsOfGluedDag(){return this.verticalConstraints.isEmpty?new Array(this.IntGraph.nodeCount).fill(1):this.verticalConstraints.getGluedNodeCounts()}}function Ja(l,t){if(t===0)return 0;const e=Math.floor(l/t),i=l-e*t;return Math.abs(i)<1e-4?0:t-i}function tu(l,t){for(const e of l)if(e<t)return!0;return!1}function eu(l,t,e,i,s){const n=l.Anchors=new Array(t.NodeCount);for(let o=0;o<n.length;o++)n[o]=new ei(s.LabelCornersPreserveCoefficient);for(let o=0;o<e.shallowNodeCount;o++)qo.CalcAnchorsForOriginalNode(o,i,n,l,s);for(const o of l.AllIntEdges())if(o.LayerEdges!=null){for(const a of o.LayerEdges){const h=a.Target;if(h!==o.target){const u=n[h];l.MultipleMiddles.has(h)?(u.leftAnchor=u.rightAnchor=zo()*4,u.topAnchor=u.bottomAnchor=Za(s)/2):(u.leftAnchor=u.rightAnchor=zo()/2,u.topAnchor=u.bottomAnchor=Za(s)/2)}}if(o.hasLabel){const a=o.LayerEdges[o.LayerEdges.length/2].Source,h=n[a],u=o.labelWidth,d=o.labelHeight;h.rightAnchor=u,h.leftAnchor=zo()*8,h.topAnchor<d/2&&(h.topAnchor=h.bottomAnchor=d/2),h.labelIsToTheRightOfTheSpline=!0}}return n}function zo(){return 1}function Za(l){return l.MinNodeHeight*1.5/8}function _a(l,t,e,i,s,n){let o=0;if(e>0){const a=hu(t.Layers[e-1],t.y,i);if(a.length){const h=s.LayerSeparation/3,u=n;o=Math.max(...a.map(d=>uu(d,u,h,l)))}}return o}function iu(l,t,e,i,s,n,o){const a=i.Anchors;let h=e.margins.top+t,u=0;for(const d of l.Layers){let m=0,y=0;for(const tt of d){const lt=a[tt];lt.bottomAnchor>m&&(m=lt.bottomAnchor),lt.topAnchor>y&&(y=lt.topAnchor)}ru(d,m,y,e.shallowNodeCount,i.Anchors);const E=_a(i,l,u,s,n,h),T=h+m+E;let B=T+y;if(ou(n)){B+=Ja(B,n.GridSizeByY);for(const tt of d)a[tt].top=B}else if(au(n)){let tt=T-m;tt+=Ja(tt,tt);for(const lt of d)a[lt].bottom=tt,B=Math.max(a[lt].top,B)}else for(const tt of d)a[tt].y=T;const H=n.ActualLayerSeparation(o);h=B+H,u++}_a(i,l,u,s,n,h)}function su(l,t){const e=new Ti(l.x,l.y,t);return e.weight=0,e.separation=1,e}function nu(l,t){return l[t.source]-l[t.target]}function ru(l,t,e,i,s){if(tu(l,i)){for(const n of l)if(n>=i){const o=s[n];o.bottomAnchor=t,o.topAnchor=e}}}function ou(l){return l.SnapToGridByY===Pn.Top}function au(l){return l.SnapToGridByY===Pn.Bottom}function lu(l,t,e){if(l.labelIsToTheRightOfTheSpline){if(c.getTriangleOrientation(t.origin,l.origin,e.origin)===D.Clockwise)return!0;const i=l.leftAnchor,s=l.rightAnchor,n=l.x;return tl(l),c.getTriangleOrientation(t.origin,l.origin,e.origin)===D.Counterclockwise?!0:(l.x=n,l.leftAnchor=i,l.rightAnchor=s,l.labelIsToTheRightOfTheSpline=!0,l.labelIsToTheLeftOfTheSpline=!1,!1)}return!1}function tl(l){const t=l.right,e=l.leftAnchor;l.leftAnchor=l.rightAnchor,l.rightAnchor=e,l.x=t-l.rightAnchor,l.labelIsToTheLeftOfTheSpline=!0,l.labelIsToTheRightOfTheSpline=!1}function hu(l,t,e){const i=new Ii;for(const s of l)if(!(s>=e.nodeCount))for(const n of e.outEdges[s])t[n.source]===t[n.target]&&i.addNN(n.source,n.target);return Array.from(i.values())}function uu(l,t,e,i){let s=0;const n=i.GetMultiedgeI(l);for(const o of n){s+=e;const a=o.edge.label;a!=null&&(a.positionCenter(new c(a.center.x,t+s+a.height/2)),s+=a.height)}return s}function cu(l,t,e){l.rightAnchor=l.leftAnchor=(t.width+e.GridSizeByX)/2,l.topAnchor=l.bottomAnchor=t.height/2}function du(l,t,e,i){const s=gu(e,l,t,i);t.rightAnchor+=s}function gu(l,t,e,i){let s=0;const n=l.GetMultiedge(t,t);if(n.length>0){for(const o of n)o.edge.label!=null&&(e.rightAnchor+=o.edge.label.width,e.topAnchor<o.edge.label.height/2&&(e.topAnchor=e.bottomAnchor=o.edge.label.height/2));s+=(i.NodeSeparation+i.MinNodeWidth)*n.length}return s}function fu(l,t){if(t.isIdentity())return;const e=t.inverse();for(const i of l.shallowNodes)i.transform(e);for(const i of l.shallowEdges)if(i.label!=null){const s=X.mkPP(e.multiplyPoint(new c(0,0)),e.multiplyPoint(new c(i.label.width,i.label.height)));i.label.width=s.width,i.label.height=s.height}}function pu(l,t){if(!t.isIdentity()){for(const e of l.shallowNodes)e.transform(t);for(const e of l.shallowEdges)if(e.label!=null){const i=X.mkPP(t.multiplyPoint(new c(0,0)),t.multiplyPoint(new c(e.label.width,e.label.height)));e.label.width=i.width,e.label.height=i.height}mu(l,t),l.graph.parent==null&&(l.boundingBox=null)}}function mu(l,t){for(const e of l.shallowEdges)e.label&&e.label.transform(t),Pu(t,e)}function Pu(l,t){if(t.curve!=null){t.curve=t.curve.transform(l);const e=t;e.sourceArrowhead!=null&&(e.sourceArrowhead.tipPosition=l.multiplyPoint(e.sourceArrowhead.tipPosition)),e.targetArrowhead!=null&&(e.targetArrowhead.tipPosition=l.multiplyPoint(e.targetArrowhead.tipPosition)),Su(t,l)}}function Su(l,t){if(l.smoothedPolyline!=null)for(let e=l.smoothedPolyline.headSite;e!=null;e=e.next)e.point=t.multiplyPoint(e.point)}var yu=Ys(79275),ms;(function(l){l[l.normal=0]="normal",l[l.inv=1]="inv",l[l.dot=2]="dot",l[l.invdot=3]="invdot",l[l.odot=4]="odot",l[l.invodot=5]="invodot",l[l.none=6]="none",l[l.tee=7]="tee",l[l.empty=8]="empty",l[l.invempty=9]="invempty",l[l.diamond=10]="diamond",l[l.odiamond=11]="odiamond",l[l.ediamond=12]="ediamond",l[l.crow=13]="crow",l[l.box=14]="box",l[l.obox=15]="obox",l[l.open=16]="open",l[l.halfopen=17]="halfopen",l[l.vee=18]="vee"})(ms||(ms={}));var Kt;(function(l){l[l.diamond=0]="diamond",l[l.ellipse=1]="ellipse",l[l.box=2]="box",l[l.circle=3]="circle",l[l.record=4]="record",l[l.plaintext=5]="plaintext",l[l.point=6]="point",l[l.mdiamond=7]="mdiamond",l[l.msquare=8]="msquare",l[l.polygon=9]="polygon",l[l.doublecircle=10]="doublecircle",l[l.house=11]="house",l[l.invhouse=12]="invhouse",l[l.parallelogram=13]="parallelogram",l[l.octagon=14]="octagon",l[l.tripleoctagon=15]="tripleoctagon",l[l.triangle=16]="triangle",l[l.trapezium=17]="trapezium",l[l.drawFromGeometry=18]="drawFromGeometry",l[l.hexagon=19]="hexagon"})(Kt||(Kt={}));var Uo;(function(l){l[l.same=0]="same",l[l.min=1]="min",l[l.source=2]="source",l[l.max=3]="max",l[l.sink=4]="sink"})(Uo||(Uo={}));var jo;(function(l){l[l.none=0]="none",l[l.dashed=1]="dashed",l[l.solid=2]="solid",l[l.invis=3]="invis",l[l.bold=4]="bold",l[l.filled=5]="filled",l[l.diagonals=6]="diagonals",l[l.dotted=7]="dotted",l[l.rounded=8]="rounded"})(jo||(jo={}));var Qo;(function(l){l[l.forward=0]="forward",l[l.back=1]="back",l[l.both=2]="both",l[l.none=3]="none"})(Qo||(Qo={}));var $o;(function(l){l[l.in=0]="in",l[l.out=1]="out"})($o||($o={}));class A{static mkWithKeyword(t,e,i,s,n){const o=new A(t,e,i,s);return o.keyword=n,o}static parse(t){switch(t.toLowerCase()){case"aliceblue":return A.AliceBlue;case"antiquewhite":return A.AntiqueWhite;case"aqua":return A.Aqua;case"aquamarine":return A.Aquamarine;case"azure":return A.Azure;case"beige":return A.Beige;case"bisque":return A.Bisque;case"black":return A.Black;case"blanchedalmond":return A.BlanchedAlmond;case"blue":return A.Blue;case"blueviolet":return A.BlueViolet;case"brown":return A.Brown;case"burlywood":return A.BurlyWood;case"cadetblue":return A.CadetBlue;case"chartreuse":return A.Chartreuse;case"chocolate":return A.Chocolate;case"coral":return A.Coral;case"cornflowerblue":return A.CornflowerBlue;case"cornsilk":return A.Cornsilk;case"crimson":return A.Crimson;case"cyan":return A.Cyan;case"darkblue":return A.DarkBlue;case"darkcyan":return A.DarkCyan;case"darkgoldenrod":return A.DarkGoldenrod;case"darkgray":return A.DarkGray;case"darkgreen":return A.DarkGreen;case"darkkhaki":return A.DarkKhaki;case"darkmagenta":return A.DarkMagenta;case"darkolivegreen":return A.DarkOliveGreen;case"darkorange":return A.DarkOrange;case"darkorchid":return A.DarkOrchid;case"darkred":return A.DarkRed;case"darksalmon":return A.DarkSalmon;case"darkseagreen":return A.DarkSeaGreen;case"darkslateblue":return A.DarkSlateBlue;case"darkslategray":return A.DarkSlateGray;case"darkturquoise":return A.DarkTurquoise;case"darkviolet":return A.DarkViolet;case"deeppink":return A.DeepPink;case"deepskyblue":return A.DeepSkyBlue;case"dimgray":return A.DimGray;case"dodgerblue":return A.DodgerBlue;case"firebrick":return A.Firebrick;case"floralwhite":return A.FloralWhite;case"forestgreen":return A.ForestGreen;case"fuchsia":return A.Fuchsia;case"gainsboro":return A.Gainsboro;case"ghostwhite":return A.GhostWhite;case"gold":return A.Gold;case"goldenrod":return A.Goldenrod;case"gray":return A.Gray;case"green":return A.Green;case"greenyellow":return A.GreenYellow;case"honeydew":return A.Honeydew;case"hotpink":return A.HotPink;case"indianred":return A.IndianRed;case"indigo":return A.Indigo;case"ivory":return A.Ivory;case"khaki":return A.Khaki;case"lavender":return A.Lavender;case"lavenderblush":return A.LavenderBlush;case"lawngreen":return A.LawnGreen;case"lemonchiffon":return A.LemonChiffon;case"lightblue":return A.LightBlue;case"lightcoral":return A.LightCoral;case"lightcyan":return A.LightCyan;case"lightgoldenrodyellow":return A.LightGoldenrodYellow;case"lightgray":case"lightgrey":return A.LightGray;case"lightgreen":return A.LightGreen;case"lightpink":return A.LightPink;case"lightsalmon":return A.LightSalmon;case"lightseagreen":return A.LightSeaGreen;case"lightskyblue":return A.LightSkyBlue;case"lightslategray":return A.LightSlateGray;case"lightsteelblue":return A.LightSteelBlue;case"lightyellow":return A.LightYellow;case"lime":return A.Lime;case"limegreen":return A.LimeGreen;case"linen":return A.Linen;case"magenta":return A.Magenta;case"maroon":return A.Maroon;case"mediumaquamarine":return A.MediumAquamarine;case"mediumblue":return A.MediumBlue;case"mediumorchid":return A.MediumOrchid;case"mediumpurple":return A.MediumPurple;case"mediumseagreen":return A.MediumSeaGreen;case"mediumslateblue":return A.MediumSlateBlue;case"mediumspringgreen":return A.MediumSpringGreen;case"mediumturquoise":return A.MediumTurquoise;case"mediumvioletred":return A.MediumVioletRed;case"midnightblue":return A.MidnightBlue;case"mintcream":return A.MintCream;case"mistyrose":return A.MistyRose;case"moccasin":return A.Moccasin;case"navajowhite":return A.NavajoWhite;case"navy":return A.Navy;case"oldlace":return A.OldLace;case"olive":return A.Olive;case"olivedrab":return A.OliveDrab;case"orange":return A.Orange;case"orangered":return A.OrangeRed;case"orchid":return A.Orchid;case"palegoldenrod":return A.PaleGoldenrod;case"palegreen":return A.PaleGreen;case"paleturquoise":return A.PaleTurquoise;case"palevioletred":return A.PaleVioletRed;case"papayawhip":return A.PapayaWhip;case"peachpuff":return A.PeachPuff;case"peru":return A.Peru;case"pink":return A.Pink;case"plum":return A.Plum;case"powderblue":return A.PowderBlue;case"purple":return A.Purple;case"red":return A.Red;case"rosybrown":return A.RosyBrown;case"royalblue":return A.RoyalBlue;case"saddlebrown":return A.SaddleBrown;case"salmon":return A.Salmon;case"sandybrown":return A.SandyBrown;case"seagreen":return A.SeaGreen;case"seashell":return A.SeaShell;case"sienna":return A.Sienna;case"silver":return A.Silver;case"skyblue":return A.SkyBlue;case"slateblue":return A.SlateBlue;case"slategray":return A.SlateGray;case"snow":return A.Snow;case"springgreen":return A.SpringGreen;case"steelblue":return A.SteelBlue;case"tan":return A.Tan;case"teal":return A.Teal;case"thistle":return A.Thistle;case"tomato":return A.Tomato;case"transparent":return A.Transparent;case"turquoise":return A.Turquoise;case"violet":return A.Violet;case"wheat":return A.Wheat;case"white":return A.White;case"whitesmoke":return A.WhiteSmoke;case"yellow":return A.Yellow;case"yellowgreen":return A.YellowGreen;default:return}}get keyword(){return this.keyword_}set keyword(t){this.keyword_=t}constructor(t,e,i,s){this.a=t,this.r=e,this.g=i,this.b=s}static mkRGB(t,e,i){return new A(255,t,e,i)}get A(){return this.a}set A(t){this.a=t}get R(){return this.r}set R(t){this.r=t}get G(){return this.g}set G(t){this.g=t}get B(){return this.b}set B(t){this.b=t}static Xex(t){const e=t.toString(16);return e.length===1?"0"+e:e.substring(e.length-2,2)}static equal(t,e){return t.a===e.a&&t.r===e.r&&t.b===e.b&&t.g===e.g}toString(){return this.keyword?this.keyword:'"#'+A.Xex(this.R)+A.Xex(this.G)+A.Xex(this.B)+(this.A===255?"":A.Xex(this.A))+'"'}static get AliceBlue(){return A.mkWithKeyword(255,240,248,255,"aliceblue")}static get AntiqueWhite(){return A.mkWithKeyword(255,250,235,215,"antiquewhite")}static get Aqua(){return A.mkWithKeyword(255,0,255,255,"aqua")}static get Aquamarine(){return A.mkWithKeyword(255,127,255,212,"aquamarine")}static get Azure(){return A.mkWithKeyword(255,240,255,255,"azure")}static get Beige(){return A.mkWithKeyword(255,245,245,220,"beige")}static get Bisque(){return A.mkWithKeyword(255,255,228,196,"bisque")}static get Black(){return A.mkWithKeyword(255,0,0,0,"black")}static get BlanchedAlmond(){return A.mkWithKeyword(255,255,235,205,"blanchedalmond")}static get Blue(){return A.mkWithKeyword(255,0,0,255,"blue")}static get BlueViolet(){return A.mkWithKeyword(255,138,43,226,"blueviolet")}static get Brown(){return A.mkWithKeyword(255,165,42,42,"brown")}static get BurlyWood(){return A.mkWithKeyword(255,222,184,135,"burlywood")}static get CadetBlue(){return A.mkWithKeyword(255,95,158,160,"cadetblue")}static get Chartreuse(){return A.mkWithKeyword(255,127,255,0,"chartreuse")}static get Chocolate(){return A.mkWithKeyword(255,210,105,30,"chocolate")}static get Coral(){return A.mkWithKeyword(255,255,127,80,"coral")}static get CornflowerBlue(){return A.mkWithKeyword(255,100,149,237,"cornflowerblue")}static get Cornsilk(){return A.mkWithKeyword(255,255,248,220,"cornsilk")}static get Crimson(){return A.mkWithKeyword(255,220,20,60,"crimson")}static get Cyan(){return A.mkWithKeyword(255,0,255,255,"cyan")}static get DarkBlue(){return A.mkWithKeyword(255,0,0,139,"darkblue")}static get DarkCyan(){return A.mkWithKeyword(255,0,139,139,"darkcyan")}static get DarkGoldenrod(){return A.mkWithKeyword(255,184,134,11,"darkgoldenrod")}static get DarkGray(){return A.mkWithKeyword(255,169,169,169,"darkgray")}static get DarkGreen(){return A.mkWithKeyword(255,0,100,0,"darkgreen")}static get DarkKhaki(){return A.mkWithKeyword(255,189,183,107,"darkkhaki")}static get DarkMagenta(){return A.mkWithKeyword(255,139,0,139,"darkmagenta")}static get DarkOliveGreen(){return A.mkWithKeyword(255,85,107,47,"darkolivegreen")}static get DarkOrange(){return A.mkWithKeyword(255,255,140,0,"darkorange")}static get DarkOrchid(){return A.mkWithKeyword(255,153,50,204,"darkorchid")}static get DarkRed(){return A.mkWithKeyword(255,139,0,0,"darkred")}static get DarkSalmon(){return A.mkWithKeyword(255,233,150,122,"darksalmon")}static get DarkSeaGreen(){return A.mkWithKeyword(255,143,188,139,"darkseagreen")}static get DarkSlateBlue(){return A.mkWithKeyword(255,72,61,139,"darkslateblue")}static get DarkSlateGray(){return A.mkWithKeyword(255,47,79,79,"darkslategray")}static get DarkTurquoise(){return A.mkWithKeyword(255,0,206,209,"darkturquoise")}static get DarkViolet(){return A.mkWithKeyword(255,148,0,211,"darkviolet")}static get DeepPink(){return A.mkWithKeyword(255,255,20,147,"deeppink")}static get DeepSkyBlue(){return A.mkWithKeyword(255,0,191,255,"deepskyblue")}static get DimGray(){return A.mkWithKeyword(255,105,105,105,"dimgray")}static get DodgerBlue(){return A.mkWithKeyword(255,30,144,255,"dodgerblue")}static get Firebrick(){return A.mkWithKeyword(255,178,34,34,"firebrick")}static get FloralWhite(){return A.mkWithKeyword(255,255,250,240,"floralwhite")}static get ForestGreen(){return A.mkWithKeyword(255,34,139,34,"forestgreen")}static get Fuchsia(){return A.mkWithKeyword(255,255,0,255,"fuchsia")}static get Gainsboro(){return A.mkWithKeyword(255,220,220,220,"gainsboro")}static get GhostWhite(){return A.mkWithKeyword(255,248,248,255,"ghostwhite")}static get Gold(){return A.mkWithKeyword(255,255,215,0,"gold")}static get Goldenrod(){return A.mkWithKeyword(255,218,165,32,"goldenrod")}static get Gray(){return A.mkWithKeyword(255,128,128,128,"gray")}static get Green(){return A.mkWithKeyword(255,0,128,0,"green")}static get GreenYellow(){return A.mkWithKeyword(255,173,255,47,"greenyellow")}static get Honeydew(){return A.mkWithKeyword(255,240,255,240,"honeydew")}static get HotPink(){return A.mkWithKeyword(255,255,105,180,"hotpink")}static get IndianRed(){return A.mkWithKeyword(255,205,92,92,"indianred")}static get Indigo(){return A.mkWithKeyword(255,75,0,130,"indigo")}static get Ivory(){return A.mkWithKeyword(255,255,255,240,"ivory")}static get Khaki(){return A.mkWithKeyword(255,240,230,140,"khaki")}static get Lavender(){return A.mkWithKeyword(255,230,230,250,"lavender")}static get LavenderBlush(){return A.mkWithKeyword(255,255,240,245,"lavenderblush")}static get LawnGreen(){return A.mkWithKeyword(255,124,252,0,"lawngreen")}static get LemonChiffon(){return A.mkWithKeyword(255,255,250,205,"lemonchiffon")}static get LightBlue(){return A.mkWithKeyword(255,173,216,230,"lightblue")}static get LightCoral(){return A.mkWithKeyword(255,240,128,128,"lightcoral")}static get LightCyan(){return A.mkWithKeyword(255,224,255,255,"lightcyan")}static get LightGoldenrodYellow(){return A.mkWithKeyword(255,250,250,210,"lightgoldenrodyellow")}static get LightGray(){return A.mkWithKeyword(255,211,211,211,"lightgray")}static get LightGreen(){return A.mkWithKeyword(255,144,238,144,"lightgreen")}static get LightPink(){return A.mkWithKeyword(255,255,182,193,"lightpink")}static get LightSalmon(){return A.mkWithKeyword(255,255,160,122,"lightsalmon")}static get LightSeaGreen(){return A.mkWithKeyword(255,32,178,170,"lightseagreen")}static get LightSkyBlue(){return A.mkWithKeyword(255,135,206,250,"lightskyblue")}static get LightSlateGray(){return A.mkWithKeyword(255,119,136,153,"lightslategray")}static get LightSteelBlue(){return A.mkWithKeyword(255,176,196,222,"lightsteelblue")}static get LightYellow(){return A.mkWithKeyword(255,255,255,224,"lightyellow")}static get Lime(){return A.mkWithKeyword(255,0,255,0,"lime")}static get LimeGreen(){return A.mkWithKeyword(255,50,205,50,"limegreen")}static get Linen(){return A.mkWithKeyword(255,250,240,230,"linen")}static get Magenta(){return A.mkWithKeyword(255,255,0,255,"magenta")}static get Maroon(){return A.mkWithKeyword(255,128,0,0,"maroon")}static get MediumAquamarine(){return A.mkWithKeyword(255,102,205,170,"mediumaquamarine")}static get MediumBlue(){return A.mkWithKeyword(255,0,0,205,"mediumblue")}static get MediumOrchid(){return A.mkWithKeyword(255,186,85,211,"mediumorchid")}static get MediumPurple(){return A.mkWithKeyword(255,147,112,219,"mediumpurple")}static get MediumSeaGreen(){return A.mkWithKeyword(255,60,179,113,"mediumseagreen")}static get MediumSlateBlue(){return A.mkWithKeyword(255,123,104,238,"mediumslateblue")}static get MediumSpringGreen(){return A.mkWithKeyword(255,0,250,154,"mediumspringgreen")}static get MediumTurquoise(){return A.mkWithKeyword(255,72,209,204,"mediumturquoise")}static get MediumVioletRed(){return A.mkWithKeyword(255,199,21,133,"mediumvioletred")}static get MidnightBlue(){return A.mkWithKeyword(255,25,25,112,"midnightblue")}static get MintCream(){return A.mkWithKeyword(255,245,255,250,"mintcream")}static get MistyRose(){return A.mkWithKeyword(255,255,228,225,"mistyrose")}static get Moccasin(){return A.mkWithKeyword(255,255,228,181,"moccasin")}static get NavajoWhite(){return A.mkWithKeyword(255,255,222,173,"navajowhite")}static get Navy(){return A.mkWithKeyword(255,0,0,128,"navy")}static get OldLace(){return A.mkWithKeyword(255,253,245,230,"oldlace")}static get Olive(){return A.mkWithKeyword(255,128,128,0,"olive")}static get OliveDrab(){return A.mkWithKeyword(255,107,142,35,"olivedrab")}static get Orange(){return A.mkWithKeyword(255,255,165,0,"orange")}static get OrangeRed(){return A.mkWithKeyword(255,255,69,0,"orangered")}static get Orchid(){return A.mkWithKeyword(255,218,112,214,"orchid")}static get PaleGoldenrod(){return A.mkWithKeyword(255,238,232,170,"palegoldenrod")}static get PaleGreen(){return A.mkWithKeyword(255,152,251,152,"palegreen")}static get PaleTurquoise(){return A.mkWithKeyword(255,175,238,238,"paleturquoise")}static get PaleVioletRed(){return A.mkWithKeyword(255,219,112,147,"palevioletred")}static get PapayaWhip(){return A.mkWithKeyword(255,255,239,213,"papayawhip")}static get PeachPuff(){return A.mkWithKeyword(255,255,218,185,"peachpuff")}static get Peru(){return A.mkWithKeyword(255,205,133,63,"peru")}static get Pink(){return A.mkWithKeyword(255,255,192,203,"pink")}static get Plum(){return A.mkWithKeyword(255,221,160,221,"plum")}static get PowderBlue(){return A.mkWithKeyword(255,176,224,230,"powderblue")}static get Purple(){return A.mkWithKeyword(255,128,0,128,"purple")}static get Red(){return A.mkWithKeyword(255,255,0,0,"red")}static get RosyBrown(){return A.mkWithKeyword(255,188,143,143,"rosybrown")}static get RoyalBlue(){return A.mkWithKeyword(255,65,105,225,"royalblue")}static get SaddleBrown(){return A.mkWithKeyword(255,139,69,19,"saddlebrown")}static get Salmon(){return A.mkWithKeyword(255,250,128,114,"salmon")}static get SandyBrown(){return A.mkWithKeyword(255,244,164,96,"sandybrown")}static get SeaGreen(){return A.mkWithKeyword(255,46,139,87,"seagreen")}static get SeaShell(){return A.mkWithKeyword(255,255,245,238,"seashell")}static get Sienna(){return A.mkWithKeyword(255,160,82,45,"sienna")}static get Silver(){return A.mkWithKeyword(255,192,192,192,"silver")}static get SkyBlue(){return A.mkWithKeyword(255,135,206,235,"skyblue")}static get SlateBlue(){return A.mkWithKeyword(255,106,90,205,"slateblue")}static get SlateGray(){return A.mkWithKeyword(255,112,128,144,"slategray")}static get Snow(){return A.mkWithKeyword(255,255,250,250,"snow")}static get SpringGreen(){return A.mkWithKeyword(255,0,255,127,"springgreen")}static get SteelBlue(){return A.mkWithKeyword(255,70,130,180,"steelblue")}static get Tan(){return A.mkWithKeyword(255,210,180,140,"tan")}static get Teal(){return A.mkWithKeyword(255,0,128,128,"teal")}static get Thistle(){return A.mkWithKeyword(255,216,191,216,"thistle")}static get Tomato(){return A.mkWithKeyword(255,255,99,71,"tomato")}static get Transparent(){return A.mkWithKeyword(0,255,255,255,"transparent")}static get Turquoise(){return A.mkWithKeyword(255,64,224,208,"turquoise")}static get Violet(){return A.mkWithKeyword(255,238,130,238,"violet")}static get Wheat(){return A.mkWithKeyword(255,245,222,179,"wheat")}static get White(){return A.mkWithKeyword(255,255,255,255,"white")}static get WhiteSmoke(){return A.mkWithKeyword(255,245,245,245,"whitesmoke")}static get Yellow(){return A.mkWithKeyword(255,255,255,0,"yellow")}static get YellowGreen(){return A.mkWithKeyword(255,154,205,50,"yellowgreen")}}class Ee extends ae{rebind(t){this.entity=t,this.bind(pt.DrawingObjectIndex)}static copyValidFields(t,e){t==null||e==null||(t.color&&t.color.keyword&&t.color.keyword.toLowerCase()!=="black"&&(e.color=t.color),t.fillColor&&(e.fillColor=t.fillColor),t.labelfontcolor&&t.labelfontcolor.keyword.toLowerCase()!=="black"&&(e.labelfontcolor=t.labelfontcolor),t.labelText!=null&&t.labelText!==""&&t.labelText!==t.id&&(e.labelText=t.labelText),t.fontColor&&t.fontColor.keyword&&t.fontColor.keyword.toLowerCase()!=="black"&&(e.fontColor=t.fontColor),t.styles&&t.styles.length&&(e.styles=t.styles.map(i=>i)),t.pencolor&&t.pencolor.keyword!=="black"&&(e.pencolor=t.pencolor),t.penwidth&&t.penwidth!==1&&(e.penwidth=t.penwidth),t.rankdir&&(e.rankdir=t.rankdir),t.fontname&&t.fontname!==Ee.defaultLabelFontName&&(e.fontname=t.fontname),t.margin&&(e.margin=t.margin),t.fontsize&&t.fontsize!==Ee.defaultLabelFontSize&&(e.fontsize=t.fontsize),t.orientation&&(e.orientation=t.orientation),t.ranksep&&(e.ranksep=t.ranksep),t.arrowtail&&(e.arrowtail=t.arrowtail),t.arrowhead&&(e.arrowhead=t.arrowhead),t.ordering&&(e.ordering=t.ordering),t.bgcolor&&(e.bgcolor=t.bgcolor),t.pos&&(e.pos=t.pos),t.nodesep&&(e.nodesep=t.nodesep),t.arrowsize&&(e.arrowsize=t.arrowsize),t.samehead&&(e.samehead=t.samehead),t.layersep&&(e.layersep=t.layersep),t.clusterRank&&(e.clusterRank=t.clusterRank))}get labelText(){return this._labelText}set labelText(t){this._labelText=t}get arrowhead(){return this._arrowhead}set arrowhead(t){this._arrowhead=t}get id(){return this._id}set id(t){this._id=t}constructor(t){super(t,pt.DrawingObjectIndex),this.labelfontcolor=A.Black,this.styles=[],this.penwidth=1,this.fontname=Ee.defaultLabelFontName,this.fontsize=Ee.defaultLabelFontSize}static getDrawingObj(t){return t==null?null:t.getAttr(pt.DrawingObjectIndex)}}Ee.defaultLabelFontName="Times-Roman",Ee.defaultLabelFontSize=12;class si extends Ee{clone(){throw new Error("Method not implemented.")}get Padding(){return this.padding}set Padding(t){this.padding=Math.max(0,t)}get XRadius(){return this.xRad}set XRadius(t){this.xRad=t}get YRadius(){return this.yRad}set YRadius(t){this.yRad=t}static get DefaultFillColor(){return si.defaultFillColor}static set DefaultFillColor(t){si.defaultFillColor=t}get ShapeEnum(){return this.shape}set ShapeEnum(t){this.shape=t}get LabelMargin(){return this.labelMargin}set LabelMargin(t){this.labelMargin=t}constructor(t){super(t),this.shape=Kt.box,this.padding=2,this.xRad=3,this.yRad=3,this.labelMargin=1,this.labelWidthToHeightRatio=1,t!=null&&(this.labelText=t.id)}get LabelWidthToHeightRatio(){return this.labelWidthToHeightRatio}set LabelWidthToHeightRatio(t){this.labelWidthToHeightRatio=t}get node(){return this.entity}get id(){return this.node?this.node.id:""}}si.defaultFillColor=A.LightGray;class gr extends Ee{constructor(t,e){super(t),this.directed=!0,this.directed=e,e?this.arrowhead=ms.normal:this.arrowhead=ms.none,this.arrowtail=ms.none}clone(){const t=new gr(null,this.directed);return Ee.copyValidFields(this,t),t.directed=this.directed,t.arrowtail=this.arrowtail,t.arrowhead=this.arrowhead,t}}class ji extends si{constructor(){super(...arguments),this.graphVisData={sameRanks:new Array,minRanks:new Array,maxRanks:new Array,sourceRanks:new Array,sinkRanks:new Array}}get defaultNodeObject(){return this._defaultNodeObject}set defaultNodeObject(t){this._defaultNodeObject=t}static getDrawingGraph(t){return Ee.getDrawingObj(t)}get graph(){return this.entity}findNode(t){const i=this.graph.findNode(t);return i==null?null:Ee.getDrawingObj(i)}hasDirectedEdge(){for(const t of this.graph.deepEdges)if(Ee.getDrawingObj(t).directed)return!0;return!1}createGeometry(t=e=>e?new be(e.length*8+8,20):null){const e=new Gt(this.graph);this.textMeasure=t;const i={fontFamily:this.fontname,fontSize:this.fontsize,fontStyle:"normal"};this.labelText&&(e.labelSize=t(this.labelText,i));for(const s of this.graph.nodesBreadthFirst)this.createNodeGeometry(s);for(const s of this.graph.deepEdges)this.createEdgeGeometry(s);if(this.rankdir){const s=e.layoutSettings=new Hs;s.layerDirection=this.rankdir}return e}createEdgeGeometry(t){const e=gr.getDrawingObj(t)||new gr(t,!0),i=new we(t);if(e.arrowhead!=ms.none&&(i.targetArrowhead=new Bt),e.arrowtail!=ms.none&&(i.sourceArrowhead=new Bt),e.labelText){const s=this.textMeasure(e.labelText,{fontSize:e.fontsize,fontFamily:e.fontname,fontStyle:"normal"}),n=t.label=new Ua(t);new Es(n,X.mkPP(new c(0,0),new c(s.width,s.height))),e.measuredTextSize=s}e.penwidth&&(i.lineWidth=e.penwidth)}curveByShape(t,e,i,s){let n;switch(s.shape){case Kt.diamond:n=W.mkDiamond(t,e,i);break;case Kt.ellipse:n=W.mkEllipse(t/1.6,e/1.6,i);break;case Kt.record:case Kt.box:n=W.mkRectangleWithRoundedCorners(t,e,s.XRadius,s.YRadius,i);break;case Kt.circle:n=W.mkCircle(Math.sqrt(t*t+e*e),i);break;case Kt.plaintext:break;case Kt.point:break;case Kt.mdiamond:break;case Kt.msquare:break;case Kt.polygon:break;case Kt.doublecircle:n=W.mkCircle(Math.sqrt(t*t+e*e)+2*s.penwidth,i);break;case Kt.house:n=W.createHouse(t,e,i);break;case Kt.invhouse:n=W.createInvertedHouse(t,e,i);break;case Kt.parallelogram:n=W.createParallelogram(t,e,i);break;case Kt.octagon:n=W.createOctagon(t,e,i);break;case Kt.tripleoctagon:break;case Kt.triangle:break;case Kt.trapezium:break;case Kt.drawFromGeometry:break;case Kt.hexagon:n=W.createHexagon(t,e,i);break}return n??W.mkRectangleWithRoundedCorners(t,e,s.XRadius,s.YRadius,i)}createNodeGeometry(t,e=new c(0,0)){if(t instanceof Vt){const i=Ee.getDrawingObj(t)||new ji(t),s=new Gt(t);i.labelText&&(s.labelSize=i.measuredTextSize=Xo(i,this.textMeasure))}else{const i=si.getDrawingObj(t)||new si(t);let s=new be(1,1);i.labelText&&(s=Xo(i,this.textMeasure)),i.measuredTextSize=s;const n=new Jt(t),o=s.width+i.LabelMargin*2,a=s.height+i.LabelMargin*2;n.boundaryCurve=this.curveByShape(o,a,e,i)}}measureLabelSizes(t){var e;for(const i of this.graph.nodesBreadthFirst){const s=si.getDrawingObj(i);s.measuredTextSize=(e=Xo(s,t))!==null&&e!==void 0?e:new be(1,1)}}}function Xo(l,t){return l.labelText?t(l.labelText,{fontSize:l.fontsize,fontFamily:l.fontname,fontStyle:"normal"}):null}class Ko{constructor(t,e,i){this.fixedNodes=new Set,this.separation=e,this.rtree=new RTree(createRectangleNodeOnData(t,s=>this.GetPaddedBoxOfNode(s))),this.pushingNodes=i}get FixedNodes(){return this.fixedNodes}GetPaddedBoxOfNode(t){const e=t.boundaryCurve.boundingBox.clone();return e.pad(this.separation/2),e}PushNodes(){this.fixedNodes.clear(),insertRange(this.fixedNodes,this.pushingNodes);const t=new Queue;for(const i of this.pushingNodes)t.enqueue(i);const e=new Array;for(;t.length>0;){const i=t.dequeue();for(const s of this.PushByNodeAndReportPushedAsFixed(i))t.enqueue(s),this.fixedNodes.add(s),e.push(s)}return e}PushByNodeAndReportPushedAsFixed(t){const e=[],i=this.GetPaddedBoxOfNode(t);for(const s of this.rtree.GetAllLeavesIntersectingRectangle(i))this.fixedNodes.has(s.UserData)||this.PushNodeAndUpdateRTree(t,s)&&e.push(s.UserData);return e}PushNodeAndUpdateRTree(t,e){const i=e.UserData.center.sub(t.center),s=t.width/2+e.UserData.width/2,n=t.height/2+e.UserData.height/2,o=Math.abs(i.x),a=Math.abs(i.y),h=o-s,u=a-n;if(h>=this.separation||u>=this.separation)return!1;if(o>=a){const d=i.x>0?this.separation-h:h-this.separation;this.PushByX(d,e)}else{const d=i.y>0?this.separation-u:u-this.separation;this.PushByY(d,e)}return this.UpdateBoundingBoxesOfPushedAndUpParents(e),!0}PushByX(t,e){const i=new Point(t,0);Ko.PushByPoint(e,i)}static PushByPoint(t,e){t.UserData.center=t.UserData.center.add(e),t.UserData instanceof GeomGraph&&t.UserData.translate(e)}PushByY(t,e){const i=new Point(0,t);Ko.PushByPoint(e,i)}UpdateBoundingBoxesOfPushedAndUpParents(t){t.irect=this.GetPaddedBoxOfNode(t.UserData);let e=t.Parent;for(;e!=null;)e.irect=e.Left.irect.add_rect(e.Right.irect),e=e.Parent}UpdateRTreeByChangedNodeBox(t,e){const i=this.FindClusterNode(t,e);this.UpdateBoundingBoxesOfPushedAndUpParents(i)}FindClusterNode(t,e){const i=this.rtree.RootNode;return this.FindClusterNodeRecurse(i,t,e)}FindClusterNodeRecurse(t,e,i){if(t.UserData!=null)return t.UserData===e?t:null;let s=null;return i.intersects(t.left.irect)&&(s=this.FindClusterNodeRecurse(t.Left,e,i)),s??(i.intersects(t.right.irect)?this.FindClusterNodeRecurse(t.Right,e,i):null)}FirstPushingNode(){return this.pushingNodes[0]}}class uc{get geomGraph(){return this.geomGraph_}set geomGraph(t){this.geomGraph_=t}constructor(t,e,i){this.listOfPushers=new Array,this.labelFixtures=new Map,this.geomGraph=e,this.nodeSeparation=i.NodeSeparation,this.layoutSettings=i,this.pushingNodesArray=t,this.InitBumperPushers()}InitBumperPushers(){if(this.pushingNodesArray.length===0)return;let t=GeomGraph.getGeom(this.pushingNodesArray[0].node.parent),e=this.pushingNodesArray;do if(this.listOfPushers.push(new BumperPusher(t.shallowNodes,this.nodeSeparation,e)),t.graph.parent)t=GeomGraph.getGeom(t.graph.parent),e=[t];else break;while(!0)}RunPushers(){for(let t=0;t<this.listOfPushers.length;t++){const e=this.listOfPushers[t];e.PushNodes();const i=e.FirstPushingNode().node.parent;if(i===this.geomGraph_.graph)break;const s=GeomGraph.getGeom(i),n=s.boundingBox;if(s.calculateBoundsFromChildren(),s.boundingBox.equalEps(n))break;this.listOfPushers[t+1].UpdateRTreeByChangedNodeBox(s,n)}}Drag(t){if(!(t.x==null&&t.y==null)){for(const e of this.pushingNodesArray)e.translate(t);this.RunPushers(),this.RouteChangedEdges()}}RouteChangedEdges(){this.changedEdges=this.GetChangedEdges(this.GetChangedNodes()),this.InitLabelFixtures(this.changedEdges),new SplineRouter(this.geomGraph_,this.changedEdges,this.layoutSettings.commonSettings.edgeRoutingSettings.Padding,this.layoutSettings.commonSettings.edgeRoutingSettings.PolylinePadding,this.layoutSettings.commonSettings.edgeRoutingSettings.ConeAngle,this.layoutSettings.commonSettings.edgeRoutingSettings.bundlingSettings).run(),this.PositionLabels(this.changedEdges)}PositionLabels(t){for(const e of t)this.PositionEdgeLabel(e)}PositionEdgeLabel(t){const e=this.labelFixtures.get(t);if(e==null)return;const i=t.curve,s=i.length*e.RelativeLengthOnCurve,n=i.getParameterAtLength(s),o=i.derivative(n),a=(e.RightSide?o.rotate90Cw():o.rotate90Ccw()).normalize().mul(e.NormalLength);t.label.positionCenter(i.value(n).add(a))}InitLabelFixtures(t){for(const e of t)this.InitLabelFixture(e)}InitLabelFixture(t){if(t.label==null||this.labelFixtures.has(t))return;const e=t.curve.closestParameter(t.label.center),i=t.curve,n=i.derivative(e).rotate90Cw(),o=t.label.center.sub(i.value(e)),a=new LabelFixture(i.lengthPartial(0,e)/i.length,o.dot(n)>0,o.length);this.labelFixtures.set(t,a)}GetChangedEdges(t){const e=[],i=Rectangle.mkOnRectangles(Array.from(t).map(n=>n.boundingBox)),s=i.perimeter();for(const n of this.geomGraph.deepEdges)this.EdgeNeedsRouting(i,n,s,t)&&e.push(n);return e}EdgeNeedsRouting(t,e,i,s){return e.curve==null||s.has(e.source)||s.has(e.target)||e.source.boundingBox.intersects(t)||e.target.boundaryCurve.boundingBox.intersects(t)?!0:e.boundingBox.intersects(t)?Curve.intersectionOne(i,e.curve,!1)!=null:!1}GetChangedNodes(){const t=new Set;for(const e of this.listOfPushers)for(const i of e.FixedNodes)t.add(i);return t}}class cc{constructor(){this._canUndo=!0}updateDeltaForDragUndo(t){const e=this.data;e.delta=t}registerUndoDrag(t){this.data==null&&(this.data={draggedEnts:new Set,delta:null,changeData:new Map}),"draggedEnts"in this.data&&this.data.draggedEnts.add(t)}undo(){if(Assert.assert(this.canUndo),this.data instanceof Map)for(const[t,e]of this.data)for(const i of e)i.new=t.getAttr(Yo(i.old)).clone(),i.old.rebind(t);else if(this.data&&"deletedEnts"in this.data)for(const t of this.data.deletedEnts)el(t);else if("insertedEnts"in this.data)for(const t of this.data.insertedEnts){const e=t.parent;if(t instanceof Node)e.removeNode(t);else if(t instanceof Edge)t.remove();else throw new Error("not implemented")}else if("draggedEnts"in this.data){for(const t of this.data.draggedEnts)GeomObject.getGeom(t).translate(this.data.delta);for(const[t,e]of this.data.changeData)for(const i of e)i.new=t.getAttr(Yo(i.old)).clone(),i.old.rebind(t)}else throw new Error("not implemented");this.canUndo=!1}redo(){if(Assert.assert(this.canRedo),this.data instanceof Map)for(const[t,e]of this.data)for(const i of e)i.new.rebind(t);else if("deletedEnts"in this.data)for(const t of this.data.deletedEnts)if(t instanceof Graph)t.removeSubgraph();else if(t instanceof Node)t.parent.removeNode(t);else if(t instanceof Edge)t.remove();else if(t instanceof Label){const e=t.parent;e.label=null}else throw new Error("unexpected type in redo");else if("draggedEnts"in this.data){const t=this.data.delta.neg();for(const e of this.data.draggedEnts)GeomObject.getGeom(e).translate(t);for(const[e,i]of this.data.changeData)for(const s of i)s.new.rebind(e)}else if("insertedEnts"in this.data)for(const t of this.data.insertedEnts)el(t);else throw new Error("not implemented");this.canUndo=!0}addOldNewPair(t,e){this.data||(this.data=new Map);const i="draggedEnts"in this.data?this.data.changeData:this.data;i.has(t)||i.set(t,[]);const s=Yo(e),n=i.get(t);n[s]==null&&(n[s]={old:e.clone(),new:null})}registerDelete(t){this.data||(this.data={deletedEnts:new Set}),this.data.deletedEnts.add(t)}registerAdd(t){this.data||(this.data={insertedEnts:new Set}),this.data.insertedEnts.add(t)}get canRedo(){return!this._canUndo}get canUndo(){return this._canUndo}set canUndo(t){this._canUndo=t}*entities(){if(this.data)if(this.data instanceof Map)yield*this.data.keys();else if("draggedEnts"in this.data)yield*this.data.changeData.keys(),yield*this.data.draggedEnts;else if("deletedEnts"in this.data)yield*this.data.deletedEnts;else if("insertedEnts"in this.data)yield*this.data.insertedEnts;else throw new Error("not implemented")}}function Yo(l){let t;return l instanceof GeomObject?t=AttributeRegistry.GeomObjectIndex:l instanceof DrawingObject?t=AttributeRegistry.DrawingObjectIndex:t=AttributeRegistry.ViewerIndex,t}function el(l){if(l instanceof Label){const t=l.parent;t.label=l}else if(l instanceof Graph){l.parent.addNode(l);for(const e of l.edges)e.add();for(const e of l.nodesBreadthFirst){for(const i of e.outEdges)i.add();for(const i of e.inEdges)i.add()}}else l instanceof Node?l.parent.addNode(l):l instanceof Edge&&l.add()}class dc{updateDeltaForDragUndo(t){this.currentBridge.updateDeltaForDragUndo(t)}registerForUndoDrag(t){this.currentBridge==null&&(this.currentBridge=new UndoRedoAction),this.currentBridge.registerUndoDrag(t)}registerDelete(t){this.currentBridge==null&&(this.currentBridge=new UndoRedoAction),this.currentBridge.registerDelete(t)}registerAdd(t){this.createUndoPoint(),this.currentBridge.registerAdd(t)}*entitiesToBeChangedByRedo(){this.currentBridge!=null&&(this.currentBridge.canRedo?yield*this.currentBridge.entities():this.currentBridge.next!=null&&this.currentBridge.next.canRedo&&(yield*this.currentBridge.next.entities()))}*entitiesToBeChangedByUndo(){this.currentBridge!=null&&(this.currentBridge.canUndo?yield*this.currentBridge.entities():this.currentBridge.prev!=null&&this.currentBridge.prev.canUndo&&(yield*this.currentBridge.prev.entities()))}registerForUndo(t){this.currentBridge==null&&(this.currentBridge=new UndoRedoAction),this.currentBridge.addOldNewPair(t,t.getAttr(AttributeRegistry.GeomObjectIndex))}canUndo(){return this.currentBridge==null?!1:!!(this.currentBridge.canUndo||this.currentBridge.prev!=null&&this.currentBridge.prev.canUndo)}canRedo(){return this.currentBridge==null?!1:!!(this.currentBridge.canRedo||this.currentBridge.next!=null&&this.currentBridge.next.canRedo)}undo(){this.canUndo&&(this.currentBridge.canUndo?this.currentBridge.undo():this.currentBridge.prev.undo(),this.currentBridge.prev&&(this.currentBridge=this.currentBridge.prev))}redo(){this.canRedo&&(this.currentBridge.canRedo?this.currentBridge.redo():this.currentBridge.next.redo(),this.currentBridge.next&&(this.currentBridge=this.currentBridge.next))}createUndoPoint(){const t=new UndoRedoAction;if(!this.currentBridge)this.currentBridge=t;else if(this.currentBridge.canUndo)this.currentBridge.next=t,t.prev=this.currentBridge,this.currentBridge=t;else{Assert.assert(this.currentBridge.canRedo);const e=this.currentBridge.prev;e&&(t.prev=e,e.next=t),this.currentBridge=t}}}var ro;(function(l){l[l.Incremental=0]="Incremental",l[l.Default=1]="Default"})(ro||(ro={}));class ni{constructor(){this.edgesToReroute=new Set,this.objectsToDrag=new Set,this.undoList=new UndoList}updateDeltaForDragUndo(t){this.undoList.updateDeltaForDragUndo(t)}registerDelete(t){this.undoList.registerDelete(t)}registerAdd(t){this.undoList.registerAdd(t)}*entitiesToBeChangedByRedo(){yield*this.undoList.entitiesToBeChangedByRedo()}*entitiesToBeChangedByUndo(){yield*this.undoList.entitiesToBeChangedByUndo()}createUndoPoint(){this.undoList.createUndoPoint()}get LayoutSettings(){return this.graph().layoutSettings}get EdgeRoutingMode(){return this.LayoutSettings.commonSettings.edgeRoutingSettings.EdgeRoutingMode}get canUndo(){return this.undoList.canUndo()}get canRedo(){return this.undoList.canRedo()}static calculateAttachmentSegment(t){const e=GeomObject.getGeom(t.parent.entity);if(e!=null)if(ni.CalculateAttachedSegmentEnd(t,e),Point.closeDistEps(t.attachmentSegmentEnd,t.center))t.attachmentSegmentStart=t.center;else{const i=Curve.intersectionOne(t.boundingBox.perimeter(),LineSegment.mkPP(t.attachmentSegmentEnd,t.center),!1);t.attachmentSegmentStart=i!=null?i.x:t.center}}static CalculateAttachedSegmentEnd(t,e){t.attachmentSegmentEnd=e.curve.value(e.curve.closestParameter(t.center))}drag(t,e,i){if(!(t.x==0&&t.y==0)){for(const s of this.objectsToDrag)this.registerForUndoDrag(s.entity);this.geomEdgeWithSmoothedPolylineExposed==null?this.EdgeRoutingMode!==EdgeRoutingMode.Rectilinear&&this.EdgeRoutingMode!==EdgeRoutingMode.RectilinearToCenter?this.dragObjectsForNonRectilinearCase(t,e):this.DragObjectsForRectilinearCase(t):this.dragPolylineCorner(i,t)}}registerForUndoDrag(t){this.undoList.registerForUndoDrag(t)}DragObjectsForRectilinearCase(t){for(const e of this.objectsToDrag)e instanceof GeomNode&&e.translate(t);throw RectilinearInteractiveEditor.CreatePortsAndRouteEdges(this.LayoutSettings.commonSettings.NodeSeparation/3,1,this.graph().nodesBreadthFirst,this.graph().deepEdges,this.LayoutSettings.commonSettings.edgeRoutingSettings.EdgeRoutingMode),EdgeLabelPlacement.constructorG(this.graph()).run(),this.propagateChangesToClusterParents(),new Error("not implemented")}dragObjectsForNonRectilinearCase(t,e){e===ro.Incremental?this.DragIncrementally(t):this.dragWithStraightLines(t)}dragWithStraightLines(t){for(const e of this.objectsToDrag)e instanceof GeomGraph?e.deepTranslate(t):e.translate(t);this.propagateChangesToClusterParents(),this.routeEdgesAsStraightLines()}propagateChangesToClusterParents(){const t=new Set;for(const e of this.objectsToDrag){if(!(e instanceof GeomNode))continue;const i=e;for(const s of i.node.getAncestors()){const n=GeomObject.getGeom(s);n!==this.graph()&&!this.objectsToDrag.has(n)&&t.add(n)}}if(t.size>0)for(const e of this.graph().subgraphsDepthFirst){const i=e;if(t.has(i)){const s=i.getPumpedGraphWithMarginsBox();if(!s.equalEps(i.boundingBox)){this.registerForUndo(i.entity);for(const n of i.selfEdges())this.addToEdgesToReroute(n);for(const n of i.inEdges())this.addToEdgesToReroute(n);for(const n of i.outEdges())this.addToEdgesToReroute(n);i.boundingBox=s}}}}addToEdgesToReroute(t){this.edgesToReroute.add(t)}DragWithSplinesOrBundles(t){for(const e of this.objectsToDrag)e instanceof GeomNode&&e.translate(t);this.RunSplineRouterAndPutLabels()}RunSplineRouterAndPutLabels(){SplineRouter.mk5(this.graph(),this.LayoutSettings.commonSettings.edgeRoutingSettings.Padding,this.LayoutSettings.commonSettings.edgeRoutingSettings.PolylinePadding,this.LayoutSettings.commonSettings.edgeRoutingSettings.ConeAngle,this.LayoutSettings.commonSettings.edgeRoutingSettings.bundlingSettings).run(),EdgeLabelPlacement.constructorG(this.graph()).run()}registerForUndo(t){this.undoList.registerForUndo(t)}routeEdgesAsStraightLines(){for(const e of this.edgesToReroute)this.registerForUndo(e.entity),StraightLineEdges.CreateSimpleEdgeCurveWithUnderlyingPolyline(e),e.label&&this.registerForUndo(e.edge.label);EdgeLabelPlacement.constructorGA(this.graph(),Array.from(this.edgesToReroute)).run()}DragIncrementally(t){this.incrementalDragger==null&&this.InitIncrementalDragger(),this.incrementalDragger.Drag(t)}dragPolylineCorner(t,e){const i=ni.findClosestCornerForEdit(this.geomEdgeWithSmoothedPolylineExposed.smoothedPolyline,t);i.point=i.point.add(e),i.prev==null?il(this.geomEdgeWithSmoothedPolylineExposed.source,i):i.next==null&&il(this.geomEdgeWithSmoothedPolylineExposed.target,i),ni.createCurveOnChangedPolyline(this.geomEdgeWithSmoothedPolylineExposed)}static dragEdgeWithSite(t,e,i){i.point=i.point.add(t),ni.createCurveOnChangedPolyline(e)}static createCurveOnChangedPolyline(t){const e=t.smoothedPolyline.createCurve();Arrowhead.trimSplineAndCalculateArrowheadsII(t,t.source.boundaryCurve,t.target.boundaryCurve,e,!1)||Arrowhead.createBigEnoughSpline(t),t.sourcePort=new RelativeFloatingPort(()=>t.source.boundaryCurve,()=>t.source.center,i().sub(t.source.center)),t.targetPort=new RelativeFloatingPort(()=>t.target.boundaryCurve,()=>t.target.center,s().sub(t.target.center));function i(){return t.sourceArrowhead?t.sourceArrowhead.tipPosition:t.curve.start}function s(){return t.targetArrowhead?t.targetArrowhead.tipPosition:t.curve.end}}prepareForObjectDragging(t,e){this.geomEdgeWithSmoothedPolylineExposed=null,this.calculateObjectToDragAndEdgesToReroute(t),this.undoList.createUndoPoint(),e===ro.Incremental&&this.InitIncrementalDragger()}PrepareForClusterCollapseChange(t){throw new Error("not implemented")}InitIncrementalDragger(){this.incrementalDragger=new IncrementalDragger(Array.from(this.objectsToDrag).filter(t=>t instanceof GeomNode),this.graph(),this.LayoutSettings)}clearDraggedSets(){this.objectsToDrag.clear(),this.edgesToReroute.clear()}addToObjectsToDrag(t){this.objectsToDrag.add(t)}calculateObjectToDragAndEdgesToReroute(t){this.clearDraggedSets();for(const e of t)this.addToObjectsToDrag(e),e instanceof GeomEdge&&(this.addToObjectsToDrag(e.source),this.addToObjectsToDrag(e.target));this.removeClusterSuccessorsFromObjectsToDrag(),this.calculateDragSetsForEdges()}removeClusterSuccessorsFromObjectsToDrag(){const t=new Array;for(const e of this.objectsToDrag)this.hasAncestorInObjectsToDrag(e)&&t.push(e);for(const e of t)this.objectsToDrag.delete(e)}calculateDragSetsForEdges(){for(const t of Array.from(this.objectsToDrag))t instanceof GeomGraph?this.addGeomGraphEdgesToRerouteOrDrag(t):t instanceof GeomNode?this.addNodeEdgesToRerouteOrDrag(t):t instanceof GeomEdge&&t.edge.label&&this.addToObjectsToDrag(t.edge.label.getAttr(AttributeRegistry.GeomObjectIndex))}addNodeEdgesToRerouteOrDrag(t){Assert.assert(!(t instanceof GeomGraph));for(const e of t.selfEdges())this.addToObjectsToDrag(e);for(const e of t.inEdges())this.hasSelfOrAncestorInObjectsToDrag(e.source)?this.addToObjectsToDrag(e):this.addToEdgesToReroute(e);for(const e of t.outEdges())this.hasSelfOrAncestorInObjectsToDrag(e.target)?this.addToObjectsToDrag(e):this.addToEdgesToReroute(e);if(t instanceof GeomGraph)for(const e of t.nodesBreadthFirst)this.addNodeEdgesToRerouteOrDrag(e)}addGeomGraphEdgesToRerouteOrDrag(t){Assert.assert(t instanceof GeomGraph);for(const e of t.selfEdges())this.addToObjectsToDrag(e);for(const e of t.inEdges())t.isAncestor(e.source)||(this.hasSelfOrAncestorInObjectsToDrag(e.source)?this.addToObjectsToDrag(e):this.addToEdgesToReroute(e));for(const e of t.outEdges())t.isAncestor(e.target)||(this.hasSelfOrAncestorInObjectsToDrag(e.target)?this.addToObjectsToDrag(e):this.addToEdgesToReroute(e));for(const e of t.nodesBreadthFirst){for(const i of e.outEdges()){const s=i.target;t.isAncestor(s)||(this.hasSelfOrAncestorInObjectsToDrag(s)?this.addToObjectsToDrag(i):this.addToEdgesToReroute(i))}for(const i of e.inEdges()){const s=i.source;t.isAncestor(s)||(this.hasSelfOrAncestorInObjectsToDrag(s)?this.addToObjectsToDrag(i):this.addToEdgesToReroute(i))}}}hasSelfOrAncestorInObjectsToDrag(t){for(;t;){if(this.objectsToDrag.has(t))return!0;t=t.parent}return!1}hasAncestorInObjectsToDrag(t){for(t=t.parent;t;){if(this.objectsToDrag.has(t))return!0;t=t.parent}return!1}static CalculateMiddleOffsetsForMultiedge(t,e,i,s){const n=ni.GetMiddleAnglesOfMultiedge(t,e),a=Array.from(n.keys()).sort((y,E)=>y-E).map(y=>n.get(y)),h=s*6,u=a.length/2,d=u*2===a.length;let m;if(d){m=-(h/2);for(let y=u-1;y>=0;y--){const E=a[y];i.set(E,m),m-=h+(E.label?E.label.width:0)}m=h/2;for(let y=u;y<a.length;y++){const E=a[y];i.set(E,m),m+=h+(E.label?E.label.width:0)}}else{m=0;for(let y=u;y>=0;y--){const E=a[y];i.set(E,m),m=h+(E.label?E.label.width:0)}m=h;for(let y=u+1;y<a.length;y++){const E=a[y];i.set(E,m),m+=h+(E.label?E.label.width:0)}}}static GetMiddleAnglesOfMultiedge(t,e){const i=new Map,s=t[0],n=e.center,o=ni.Middle(s.curve);i.set(0,s);for(let a=1;a<t.length;a++){const h=t[a],u=ni.Middle(h.curve);let d=Point.anglePCP(o,n,u);d>Math.PI&&(d-=Math.PI*2),i.set(d,h)}return i}static Middle(t){return t.value(.5*t.parStart+.5*t.parEnd)}static*GetMultiEdges(t){const e=new Map;for(const i of t.outEdges())ni.GetOrCreateListOfMultiedge(e,i.target).push(i);for(const i of t.inEdges())ni.GetOrCreateListOfMultiedge(e,i.source).push(i);for(const i of e.values())i.length>1&&(yield i)}static GetOrCreateListOfMultiedge(t,e){let i=t.get(e);return i||(t.set(e,i=[]),i)}prepareForGeomEdgeChange(t){Assert.assert(this.geomEdgeWithSmoothedPolylineExposed===t),this.createUndoPoint(),this.registerForUndo(t.edge)}undo(){this.undoList.undo()}redo(){this.undoList.redo()}clear(){this.objectsToDrag=new Set,this.edgesToReroute.clear(),this.undoList=new UndoList}static getPreviousCornerSite(t,e){let i=t.smoothedPolyline.headSite,s=i.next;for(;s!=null;){if(ni.betweenSites(i,s,e))return i;i=s,s=s.next}return null}static betweenSites(t,e,i){const s=LineSegment.closestParameterOnLineSegment(i,t.point,e.point);return s>.1&&s<.9}insertSite(t,e,i){this.prepareForGeomEdgeChange(t);const s=CornerSite.mkSiteSPS(i,e,i.next);ni.dragEdgeWithSite(new Point(0,0),t,s)}deleteSite(t,e){this.prepareForGeomEdgeChange(t),Assert.assert(this.geomEdgeWithSmoothedPolylineExposed===t),e.prev.next=e.next,e.next.prev=e.prev,ni.dragEdgeWithSite(new Point(0,0),t,e.prev)}static findClosestCornerForEdit(t,e,i=Number.POSITIVE_INFINITY){i!==Number.POSITIVE_INFINITY&&(i*=i);let s=t.headSite,n=s,o=n.point.sub(e).lengthSquared;for(;s.next!=null;){s=s.next;const a=e.sub(s.point).lengthSquared;a<o&&(n=s,o=a)}return o>i?null:n}ReactOnViewChange(){}ForgetDragging(){this.incrementalDragger=null}}function il(l,t){const e=l.boundaryCurve;if(Curve.PointRelativeToCurveLocation(t.point,e)!=PointLocation.Outside)return;const s=LineSegment.mkPP(l.center,t.point),n=Curve.intersectionOne(s,e,!1);n&&(t.point=n.x)}var sl;(function(l){l[l.Default=0]="Default",l[l.Node=1]="Node",l[l.Edge=2]="Edge"})(sl||(sl={}));var nl;(function(l){l[l.None=0]="None",l[l.Alt=1]="Alt",l[l.Control=2]="Control",l[l.Shift=4]="Shift",l[l.Windows=8]="Windows"})(nl||(nl={}));function Re(l){return l.getAttr(AttributeRegistry.ViewerIndex)}function fr(l){return GeomObject.getGeom(l.entity)}function Cu(l){return l&&l.entity instanceof Node}class Ne{resizeLabel(t,e){const i=e.getAttr(AttributeRegistry.DrawingObjectIndex);i.labelText=t,this.viewer.invalidate(e.getAttr(AttributeRegistry.ViewerIndex))}get hasEdgeInsertionPort(){return this.SourcePort!=null||this.TargetPort!=null}get insertingEdge(){return this.insertionMode==InsertionMode.Edge}createUndoPoint(){this.geomGraphEditor.createUndoPoint()}registerDelete(t){this.geomGraphEditor.registerDelete(t)}registerAdd(t){this.geomGraphEditor.registerAdd(t)}forget(t){this.dragGroup.delete(t),this.edgeWithSmoothedPolylineExposed===t&&(this.edgeWithSmoothedPolylineExposed=null)}get edgeWithSmoothedPolylineExposed(){return this._edgeWithSmoothedPolylineExposed}set edgeWithSmoothedPolylineExposed(t){this._edgeWithSmoothedPolylineExposed!==t&&this._edgeWithSmoothedPolylineExposed&&(this._edgeWithSmoothedPolylineExposed.selectedForEditing=!1),this._edgeWithSmoothedPolylineExposed=t,t?(t.selectedForEditing=!0,this.geomGraphEditor.geomEdgeWithSmoothedPolylineExposed=GeomEdge.getGeom(t.edge)):this.geomGraphEditor.geomEdgeWithSmoothedPolylineExposed=null}get ActiveDraggedObject(){return this.aActiveDraggedObject}set ActiveDraggedObject(t){this.aActiveDraggedObject=t}get interactiveEdgeRouter(){return this._interactiveEdgeRouter}set interactiveEdgeRouter(t){this._interactiveEdgeRouter=t}constructor(t){this.RadiusOfPolylineCorner=10,this.geomEdge=new GeomEdge(null),this.EdgeAttr=new DrawingEdge(null,!0),this.arrowheadLength=Arrowhead.defaultArrowheadLength,this.dragGroup=new Set,this.geomGraphEditor=new GeometryGraphEditor,this.mouseMoveThreshold=.05,this.sourceLoosePolylineWrap={loosePolyline:null},this.sourceOfInsertedEdgeWrap={node:null},this.sourcePortWrap={port:null},this.targetOfInsertedEdgeWrap={node:null},this.targetPortWrap={port:null},this.dragging=!1,this.edgeAttr=new DrawingEdge(null,!0),this.viewer=t,this.decorateObjectForDragging=this.defaultObjectDecorator,this.removeObjDraggingDecorations=this.defaultObjectDecoratorRemover,this.DecorateEdgeForDragging=Ne.TheDefaultEdgeDecoratorStub,this.decorateEdgeLabelForDragging=this.defaultEdgeLabelDecorator,this.RemoveEdgeDraggingDecorations=Ne.TheDefaultEdgeDecoratorStub,this.geomGraphEditor.graph=()=>GeomGraph.getGeom(this._graph)}ViewerObjectUnderMouseCursorChanged(t,e){this.TargetPort!=null&&(this.viewer.RemoveTargetPortEdgeRouting(),this.TargetPort=null)}ViewChangeEventHandler(t,e){this._graph!=null}get graph(){return this._graph}set graph(t){this._graph=t,this.geomGraphEditor.clear()}get MouseMoveThreshold(){return this.mouseMoveThreshold}set MouseMoveThreshold(t){this.mouseMoveThreshold=t}get DecorateEdgeForDragging(){return this.decorateEdgeForDragging}set DecorateEdgeForDragging(t){this.decorateEdgeForDragging=t}get RemoveEdgeDraggingDecorations(){return this.removeEdgeDraggingDecorations}set RemoveEdgeDraggingDecorations(t){this.removeEdgeDraggingDecorations=t}get NodeInsertPredicate(){return this.nodeInsertPredicate}set NodeInsertPredicate(t){this.nodeInsertPredicate=t}get SourceOfInsertedEdge(){return this.sourceOfInsertedEdgeWrap.node}set SourceOfInsertedEdge(t){this.sourceOfInsertedEdgeWrap.node=t}get TargetOfInsertedEdge(){return this.targetOfInsertedEdgeWrap.node}set TargetOfInsertedEdge(t){this.targetOfInsertedEdgeWrap.node=t}get SourcePort(){return this.sourcePortWrap.port}set SourcePort(t){this.sourcePortWrap.port=t}get TargetPort(){return this.targetPortWrap.port}set TargetPort(t){this.targetPortWrap.port=t}get CanUndo(){return this.geomGraphEditor.canUndo}get CanRedo(){return this.geomGraphEditor.canRedo}get insertionMode(){return this.viewer==null?InsertionMode.Default:this.viewer.insertionMode}set insertionMode(t){this.viewer!=null&&(this.viewer.insertionMode=t)}viewerGraphChanged(){this._graph=this.viewer.graph,this.geomGraphEditor.clear(),this._graph!=null&&GeomGraph.getGeom(this._graph)!=null&&this.geomGraphEditor.clear(),this.ActiveDraggedObject=null,this.dragGroup.clear(),this.cleanObstacles()}cleanObstacles(){this.interactiveEdgeRouter=null,this.looseObstaclesToTheirViewerNodes=null,this.SourceOfInsertedEdge=null,this.TargetOfInsertedEdge=null,this.SourcePort=null,this.TargetPort=null,this.viewer.RemoveSourcePortEdgeRouting(),this.viewer.RemoveTargetPortEdgeRouting()}RelayoutOnIsCollapsedChanged(t){this.geomGraphEditor.PrepareForClusterCollapseChange([t]);const e=GeomGraph.getGeom(t.node);e.isCollapsed?this.CollapseCluster(t.node):this.ExpandCluster(e);for(const i of this.geomGraphEditor.entitiesToBeChangedByUndo())this.invalidate(i)}relayout(t){let e=t;for(;e.parent!=null;)e=e.parent;layoutGeomGraph(e),this.MakeExpandedNodesVisible(t.entity)}ExpandCluster(t){t!=null&&this.relayout(t)}MakeExpandedNodesVisible(t){for(const e of t.shallowNodes){const i=Re(e);Ne.UnhideNodeEdges(e),i.isVisible=!0,e instanceof Graph&&e.getAttr(AttributeRegistry.GeomObjectIndex).isCollapsed==!1&&this.MakeExpandedNodesVisible(e)}}static UnhideNodeEdges(t){for(const e of t.selfEdges){const i=Re(e);i.isVisible=!0}for(const e of t.outEdges)Re(e.target).isVisible&&(Re(e).isVisible=!0);for(const e of t.inEdges)Re(e.source).isVisible&&(Re(e).isVisible=!0)}CollapseCluster(t){Ne.HideCollapsed(t);const e=GeomGraph.getGeom(t),i=e.center;e.boundingBox=Rectangle.mkSizeCenter(e.labelSize,i),this.relayout(e)}static HideCollapsed(t){for(const e of t.shallowNodes)Re(e).isVisible=!1,e instanceof Graph&&GeomGraph.getGeom(e).isCollapsed==!1&&Ne.HideCollapsed(e)}defaultObjectDecorator(t){if(t.entity instanceof Label){this.decorateEdgeLabelForDragging(t);return}const e=DrawingNode.getDrawingObj(t.entity),i=e.penwidth;t.unmarkedForDraggingCallback||(t.unmarkedForDraggingCallback=()=>DrawingObject.getDrawingObj(t.entity).penwidth=i),e.penwidth=Math.max(this.viewer.LineThicknessForEditing,i*2),this.invalidate(t.entity)}defaultObjectDecoratorRemover(t){const e=t.unmarkedForDraggingCallback;e&&(e(),t.unmarkedForDraggingCallback=null,this.invalidate(t.entity));const i=t.entity;if(i instanceof Node)for(const s of i.edges)this.removeObjDraggingDecorations(Re(s))}static TheDefaultEdgeDecoratorStub(t){}defaultEdgeLabelDecorator(t){const e=t.entity.getAttr(AttributeRegistry.GeomObjectIndex);t.markedForDragging&&(GeometryGraphEditor.calculateAttachmentSegment(e),t.unmarkedForDraggingCallback=()=>{this.invalidate(t.entity)}),this.invalidate(t.entity)}static LeftButtonIsPressed(t){return(t.buttons&1)==1}static MiddleButtonIsPressed(t){return(t.buttons&4)==4}static RightButtonIsPressed(t){return(t.buttons&2)==2}MouseDownPointAndMouseUpPointsAreFarEnoughOnScreen(t){if(this.mouseDownScreenPoint==null)return!1;const e=t.clientX,i=t.clientY,s=(this.mouseDownScreenPoint.x-e)/this.viewer.DpiX,n=(this.mouseDownScreenPoint.y-i)/this.viewer.DpiY;return Math.sqrt(s*s+n*n)>this.MouseMoveThreshold/3}analyzeLeftMouseButtonClick(t){this.edgeWithSmoothedPolylineExposed?this.toggleCornerForSelectedEdge():this.viewer.objectUnderMouseCursor&&this.analyzeLeftMouseButtonClickOnObjectUnderCursor(t)}analyzeLeftMouseButtonClickOnObjectUnderCursor(t){const e=this.viewer.objectUnderMouseCursor,i=t.ctrlKey||t.shiftKey,s=e.entity;if(s instanceof Edge){const n=s.getAttr(AttributeRegistry.GeomObjectIndex);n!=null&&this.viewer.layoutEditingEnabled&&(n.smoothedPolyline==null&&(n.smoothedPolyline=Ne.CreateUnderlyingPolyline(n)),this.edgeWithSmoothedPolylineExposed!==e&&this.switchToEdgeEditing(e))}else e.markedForDragging?this.unselectForDragging(e):(i||this.unselectEverything(),this.selectObjectForDragging(e)),this.unselectEdge()}toggleCornerForSelectedEdge(){const t=GeometryGraphEditor.findClosestCornerForEdit(GeomEdge.getGeom(this.edgeWithSmoothedPolylineExposed.edge).smoothedPolyline,this.mouseDownGraphPoint,this.edgeWithSmoothedPolylineExposed.radiusOfPolylineCorner);if(t==null)this.tryInsertCorner();else{if(t.prev==null||t.next==null)return;this.geomGraphEditor.createUndoPoint(),this.geomGraphEditor.registerForUndo(this.edgeWithSmoothedPolylineExposed.edge),this.geomGraphEditor.deleteSite(GeomEdge.getGeom(this.edgeWithSmoothedPolylineExposed.edge),t),this.invalidate(this.edgeWithSmoothedPolylineExposed.entity)}}tryInsertCorner(){if(!this.closeEnoughToSelectedEdge())this.unselectEdge();else{const t=GeometryGraphEditor.getPreviousCornerSite(GeomEdge.getGeom(this.edgeWithSmoothedPolylineExposed.edge),this.mouseDownGraphPoint);if(t==null||t.next==null)return;this.geomGraphEditor.insertSite(GeomEdge.getGeom(this.edgeWithSmoothedPolylineExposed.edge),this.mouseDownGraphPoint,t),this.invalidate(this.edgeWithSmoothedPolylineExposed.edge)}}closeEnoughToSelectedEdge(){const t=GeomEdge.getGeom(this.edgeWithSmoothedPolylineExposed.edge).curve,e=t.closestParameter(this.mouseDownGraphPoint);return t.value(e).sub(this.mouseDownGraphPoint).length<this.edgeWithSmoothedPolylineExposed.radiusOfPolylineCorner}static CreateUnderlyingPolyline(t){return SmoothedPolyline.mkFromPoints(Ne.CurvePoints(t))}static*CurvePoints(t){if(yield t.source.center,t.curve instanceof Curve){const i=t.curve;i.segs.length>0&&(yield i.start);for(let s=0;s<i.segs.length;s++)yield i.segs[s].end}yield t.target.center}ModifierKeyIsPressed(){return(this.viewer.modifierKeys&ModifierKeysEnum.Control)==ModifierKeysEnum.Control||(this.viewer.modifierKeys&ModifierKeysEnum.Shift)==ModifierKeysEnum.Shift}switchToEdgeEditing(t){this.unselectEverything(),this.edgeWithSmoothedPolylineExposed=t,t.radiusOfPolylineCorner=this.viewer.smoothedPolylineCircleRadius,this.DecorateEdgeForDragging(t),this.invalidate(t.entity)}*ViewerNodes(){for(const t of this.viewer.entities)t.entity instanceof Node&&(yield t.entity.getAttr(AttributeRegistry.ViewerIndex))}selectObjectForDragging(t){t.markedForDragging==!1&&(t.markedForDragging=!0,this.dragGroup.add(t),this.decorateObjectForDragging(t))}prepareToRemoveFromDragGroup(t){t.markedForDragging=!1,this.removeObjDraggingDecorations(t)}unselectForDragging(t){this.prepareToRemoveFromDragGroup(t),this.dragGroup.delete(t)}unselectEverything(){for(const t of this.dragGroup)this.prepareToRemoveFromDragGroup(t);this.dragGroup.clear(),this.unselectEdge()}unselectEdge(){this.edgeWithSmoothedPolylineExposed!=null&&(this.edgeWithSmoothedPolylineExposed.selectedForEditing=!1,this.removeEdgeDraggingDecorations(this.edgeWithSmoothedPolylineExposed),this.invalidate(this.edgeWithSmoothedPolylineExposed.edge),this.edgeWithSmoothedPolylineExposed=null)}static*Edges(t){for(const e of t.entity.edges)yield Re(e)}viewerMouseDown(t,e){if(!this.viewer.layoutEditingEnabled||this.viewer.graph==null||(this.viewer.setObjectUnderCursorFromEvent(e),this.mouseDownGraphPoint=this.viewer.screenToSource(e),this.mouseDownScreenPoint=new Point(e.clientX,e.clientY),!Ne.LeftButtonIsPressed(e)))return!1;if(this.leftMouseButtonWasPressed=!0,this.insertingEdge)return!0;if(this.insertionMode==InsertionMode.Node)return this.insertNode(),!0;if(this.edgeWithSmoothedPolylineExposed!=null)return this.mouseIsInsideOfCornerSite(e)&&e.preventDefault(),!0;const i=this.viewer.objectUnderMouseCursor;return i&&!this.viewer.objectUnderMouseCursor.hasOwnProperty("edge")?(this.ActiveDraggedObject=i,!0):this.ActiveDraggedObject!=null?(e.preventDefault(),!0):!1}insertNode(){const t=this.findNodeID(),e=new Node(t);this._graph.addNode(e),new DrawingNode(e);const i=this.viewer.createIViewerNodeN(e,this.mouseDownGraphPoint);this.viewer.addNode(i,!0)}findNodeID(){let t=0,e="node"+t.toString();for(;this._graph.findNode(e);)e="node"+ ++t;return e}viewerMouseMove(t,e){this.viewer.layoutEditingEnabled&&(Ne.LeftButtonIsPressed(e)?this.ActiveDraggedObject!=null||this.activeCornerSite!=null?this.drag(e):this.insertingEdge?this.mouseMoveInsertEdgeLeftButtonOn(e):this.MouseMoveLiveSelectObjectsForDragging(e):this.insertingEdge&&this.mouseMoveInsertEdgeNoButtons(e))}setDraggingFlag(t){!this.dragging&&this.MouseDownPointAndMouseUpPointsAreFarEnoughOnScreen(t)&&(this.dragging=!0)}TrySetNodePort(t,e,i,s){if(this.graph==null)return;Assert.assert(this.insertingEdge);const n=this.viewer.screenToSource(t);return s.loosePolyline=null,this.DraggingStraightLine()?e.node=this.setPortWhenDraggingStraightLine(i,n):(this.interactiveEdgeRouter==null&&this.PrepareForEdgeDragging(),s.loosePolyline=this.interactiveEdgeRouter.GetHitLoosePolyline(n),s.loosePolyline!=null?this.SetPortUnderLoosePolyline(n,s.loosePolyline,e,i):(e.node=null,i.port=null)),i.port!=null}setPortWhenDraggingStraightLine(t,e){if(Cu(this.viewer.objectUnderMouseCursor)){const i=this.viewer.objectUnderMouseCursor,s={portParameter:0},n=fr(i);return this.NeedToCreateBoundaryPort(e,i,s)?t.port=this.CreateOrUpdateCurvePort(s.portParameter,n,t.port):Ne.PointIsInside(e,n.boundaryCurve)?t.port=this.CreateFloatingPort(n,e):t.port=null,i}return t.port=null,null}CreateOrUpdateCurvePort(t,e,i){if(!(i instanceof CurvePort))return CurvePort.mk(e.boundaryCurve,t);const n=i;return n.parameter=t,n.curve=e.boundaryCurve,i}CreateFloatingPort(t,e){return new FloatingPort(t.boundaryCurve,e)}SetPortUnderLoosePolyline(t,e,i,s){let n=Number.POSITIVE_INFINITY,o=0;for(const a of this.GetViewerNodesInsideOfLooseObstacle(e)){const h=a.entity.getAttr(AttributeRegistry.GeomObjectIndex).boundaryCurve;if(Ne.PointIsInside(t,h)){i.node=a,this.SetPortForMousePositionInsideOfNode(t,i.node,s);return}const u=h.closestParameter(t),d=h.value(u).sub(t).length;d<n&&(o=u,n=d,i.node=a)}s.port=this.CreateOrUpdateCurvePort(o,fr(i.node),s.port)}GetViewerNodesInsideOfLooseObstacle(t){return this.looseObstaclesToTheirViewerNodes==null&&this.InitLooseObstaclesToViewerNodeMap(),this.looseObstaclesToTheirViewerNodes.get(t)}InitLooseObstaclesToViewerNodeMap(){this.looseObstaclesToTheirViewerNodes=new Map;for(const t of this.ViewerNodes()){const e=this.interactiveEdgeRouter.GetHitLoosePolyline(fr(t).center);let i=this.looseObstaclesToTheirViewerNodes.get(e);i==null&&this.looseObstaclesToTheirViewerNodes.set(e,i=new Array),i.push(t)}}SetPortForMousePositionInsideOfNode(t,e,i){const s=fr(e),n={portParameter:0};this.NeedToCreateBoundaryPort(t,e,n)?i.port=this.CreateOrUpdateCurvePort(n.portParameter,s,i.port):i.port=this.CreateFloatingPort(s,t)}static PointIsInside(t,e){return Curve.PointRelativeToCurveLocation(t,e)==PointLocation.Inside}NeedToCreateBoundaryPort(t,e,i){const s=e.entity.getAttr(AttributeRegistry.DrawingObjectIndex),n=fr(e).boundaryCurve;i.portParameter=n.closestParameter(t);const o=n.value(i.portParameter);return t.sub(o).length<=this.viewer.smoothedPolylineCircleRadius*2+s.penwidth/2?(this.TryToSnapToTheSegmentEnd(i,n,o),!0):!1}TryToSnapToTheSegmentEnd(t,e,i){if(e instanceof Curve){const s=e.getSegIndexParam(t.portParameter),n=s.par,o=e.segs[s.segIndex];n-o.parStart<o.parEnd-n&&(o.start.sub(i).length<this.viewer.smoothedPolylineCircleRadius*2?t.portParameter-=n-o.parStart:o.end.sub(i).length<this.viewer.smoothedPolylineCircleRadius*2&&(t.portParameter+=+(o.parEnd-n)))}}drag(t){if(!this.dragging)if(this.MouseDownPointAndMouseUpPointsAreFarEnoughOnScreen(t))this.prepareFirstTimeDragging();else return;const e=this.viewer.screenToSource(t);this.handleTheMouseCursorOutOfTheBoundingBox(e),this.geomGraphEditor.drag(e.sub(this._lastDragPoint),this.GetDraggingMode(),this._lastDragPoint);for(const i of this.geomGraphEditor.entitiesToBeChangedByUndo())this.invalidate(i);t.stopPropagation(),this._lastDragPoint=e}prepareFirstTimeDragging(){this.dragging=!0,this.activeCornerSite!=null?this.geomGraphEditor.prepareForGeomEdgeChange(this.edgeWithSmoothedPolylineExposed.edge.getAttr(AttributeRegistry.GeomObjectIndex)):this.ActiveDraggedObject!=null&&(this.unselectEdge(),this.ActiveDraggedObject.markedForDragging||this.unselectEverything(),this.prepareForDragging()),this._lastDragPoint=this.mouseDownGraphPoint}handleTheMouseCursorOutOfTheBoundingBox(t){const e=this.viewer.smoothedPolylineCircleRadius,i=Rectangle.mkSizeCenter(new Size(e,e),t),s=GeomGraph.getGeom(this._graph);s.boundingBox.containsRect(i)||(this.geomGraphEditor.registerForUndo(this._graph),s.boundingBox=s.boundingBox.addRec(i),this.invalidate(this._graph))}prepareForDragging(){this.selectObjectForDragging(this.ActiveDraggedObject),this.geomGraphEditor.prepareForObjectDragging(this.DraggedGeomObjects(),this.GetDraggingMode())}GetDraggingMode(){return(this.viewer.modifierKeys&ModifierKeysEnum.Shift)==ModifierKeysEnum.Shift||this.viewer.IncrementalDraggingModeAlways?DraggingMode.Incremental:DraggingMode.Default}static RouteEdgesRectilinearly(t){const e=t.graph.getAttr(AttributeRegistry.GeomObjectIndex),i=e.layoutSettings;RectilinearInteractiveEditor.CreatePortsAndRouteEdges(i.commonSettings.NodeSeparation/3,1,e.nodesBreadthFirst,e.deepEdges,i.commonSettings.edgeRoutingSettings.EdgeRoutingMode),EdgeLabelPlacement.constructorG(e).run()}*DraggedGeomObjects(){const t=Ne.GetActiveObjectCluster(this.ActiveDraggedObject);for(const e of this.dragGroup)Ne.GetActiveObjectCluster(e)==t&&(yield GeomObject.getGeom(e.entity))}static GetActiveObjectCluster(t){return t.entity.parent}viewerMouseUp(t,e){e.defaultPrevented||this.viewer.layoutEditingEnabled&&this.handleMouseUpOnLayoutEnabled(e)}handleMouseUpOnLayoutEnabled(t){if(!this.MouseDownPointAndMouseUpPointsAreFarEnoughOnScreen(t)&&this.leftMouseButtonWasPressed)this.viewer.objectUnderMouseCursor!=null||this.edgeWithSmoothedPolylineExposed!=null?(this.analyzeLeftMouseButtonClick(t),t.preventDefault()):this.unselectEverything();else if(this.dragging){this.insertingEdge?this.InsertEdgeOnMouseUp():(this.geomGraphEditor.updateDeltaForDragUndo(this.mouseDownGraphPoint.sub(this._lastDragPoint)),this.interactiveEdgeRouter=null,this.looseObstaclesToTheirViewerNodes=null);const i=GeomGraph.getGeom(this._graph),s=i.getPumpedGraphWithMarginsBox();s.equal(i.boundingBox)||(this.geomGraphEditor.registerForUndo(this._graph),i.boundingBox=s,this.invalidate(this._graph),t.preventDefault())}this.dragging=!1,this.geomGraphEditor.ForgetDragging(),this.activeCornerSite=null,this.ActiveDraggedObject=null,this.leftMouseButtonWasPressed=!1,this.TargetPort!=null&&this.viewer.RemoveTargetPortEdgeRouting(),this.SourcePort!=null&&this.viewer.RemoveSourcePortEdgeRouting(),this.TargetOfInsertedEdge=null,this.SourceOfInsertedEdge=null,this.TargetPort=null,this.SourcePort=null}InsertEdgeOnMouseUp(){if(this.viewer.stopDrawingRubberEdge(),this.TargetPort!=null){const t=this.FinishRoutingEdge();this.addEdgeToTheViewer(t)}this.interactiveEdgeRouter.Clean()}addEdgeToTheViewer(t){const e=this.viewer.createEdgeWithGivenGeometry(t);this.viewer.addEdge(e,!0)}mkArrowhead(){const t=new Arrowhead;return t.length=this.arrowheadLength,t}FinishRoutingEdge(){const t=new Edge(this.sourceOfInsertedEdgeWrap.node.entity,this.targetOfInsertedEdgeWrap.node.entity);t.add();const e=this.EdgeAttr.clone();return e.rebind(t),this.geomEdge.rebind(t),this.geomEdge.sourceArrowhead=e.arrowtail==ArrowTypeEnum.none?null:this.mkArrowhead(),this.geomEdge.targetArrowhead=e.arrowhead==ArrowTypeEnum.none?null:this.mkArrowhead(),this.TargetOfInsertedEdge!=this.SourceOfInsertedEdge?(this.geomEdge.curve instanceof LineSegment||(this.interactiveEdgeRouter.TryToRemoveInflectionsAndCollinearSegments(this.geomEdge.smoothedPolyline),this.interactiveEdgeRouter.SmoothenCorners(this.geomEdge.smoothedPolyline),this.geomEdge.curve=this.geomEdge.smoothedPolyline.createCurve()),Arrowhead.trimSplineAndCalculateArrowheads(this.geomEdge,this.geomEdge.curve,!0)):this.geomEdge=Ne.CreateEdgeGeometryForSelfEdge(this.SourceOfInsertedEdge.entity),this.viewer.RemoveSourcePortEdgeRouting(),this.viewer.RemoveTargetPortEdgeRouting(),t}static CreateEdgeGeometryForSelfEdge(t){const e=new Edge(t,t),i=new GeomEdge(e);return StraightLineEdges.CreateSimpleEdgeCurveWithUnderlyingPolyline(i),i}SelectEntitiesForDraggingWithRectangle(t){}mouseIsInsideOfCornerSite(t){const e=this.viewer.screenToSource(t),i=this.edgeWithSmoothedPolylineExposed.edge.getAttr(AttributeRegistry.DrawingObjectIndex).penwidth;return this.activeCornerSite=GeometryGraphEditor.findClosestCornerForEdit(GeomEdge.getGeom(this.edgeWithSmoothedPolylineExposed.edge).smoothedPolyline,e,this.edgeWithSmoothedPolylineExposed.radiusOfPolylineCorner+i),this.activeCornerSite!==null}MouseScreenPointIsCloseEnoughToVertex(t,e){return t.sub(this.mouseDownGraphPoint).length<e}invalidate(t){const e=Re(t);if(e){if(e.entity instanceof Label){if(e.markedForDragging){const i=GeomObject.getGeom(e.entity);GeometryGraphEditor.calculateAttachmentSegment(i)}}else e.entity instanceof Edge&&e.entity.label&&this.viewer.invalidate(Re(e.entity.label));if(this.viewer.invalidate(e),t instanceof Graph){for(const i of t.nodesBreadthFirst)this.viewer.invalidate(Re(i));for(const i of t.deepEdges)this.viewer.invalidate(Re(i)),i.label&&this.viewer.invalidate(Re(i.label))}}}undo(){if(this.geomGraphEditor.canUndo){const t=new Set(this.geomGraphEditor.entitiesToBeChangedByUndo());this.geomGraphEditor.undo();for(const e of t){const i=Re(e);i.markedForDragging?this.dragGroup.add(i):this.dragGroup.delete(i),this.invalidate(e)}}}redo(){if(this.geomGraphEditor.canRedo){const t=new Set(this.geomGraphEditor.entitiesToBeChangedByRedo());this.geomGraphEditor.redo();for(const e of t){const i=Re(e);i.markedForDragging?this.dragGroup.add(i):this.dragGroup.delete(i),this.invalidate(e)}}}static RectRouting(t){return t==EdgeRoutingMode.Rectilinear||t==EdgeRoutingMode.RectilinearToCenter}PrepareForEdgeDragging(){if(this.viewer.graph==null||this.DraggingStraightLine())return;const t=GeomGraph.getGeom(this.viewer.graph).layoutSettings;if(!Ne.RectRouting(t.commonSettings.edgeRoutingSettings.EdgeRoutingMode)&&this.interactiveEdgeRouter==null){const e=t.commonSettings.NodeSeparation/3,i=.65*e;this.interactiveEdgeRouter=InteractiveEdgeRouter.constructorANNN(Array.from(this._graph.nodesBreadthFirst).map(s=>GeomNode.getGeom(s).boundaryCurve),e,i,0)}}mouseMoveInsertEdgeNoButtons(t){const e=this.SourceOfInsertedEdge;this.TrySetNodePort(t,this.sourceOfInsertedEdgeWrap,this.sourcePortWrap,this.sourceLoosePolylineWrap)?this.viewer.SetSourcePortForEdgeRouting(this.sourcePortWrap.port.Location):e!=null&&this.viewer.RemoveSourcePortEdgeRouting()}mouseMoveInsertEdgeLeftButtonOn(t){if(this.SourcePort!=null){if(this.setDraggingFlag(t),this.dragging){const e={loosePolyline:null};this.TrySetNodePort(t,this.targetOfInsertedEdgeWrap,this.targetPortWrap,e)?(this.viewer.setTargetPortForEdgeRouting(this.targetPortWrap.port.Location),this.drawEdgeInteractivelyToPort(e.loosePolyline,this.DraggingStraightLine())):(this.viewer.RemoveTargetPortEdgeRouting(),this.DrawEdgeInteractivelyToLocation(t,this.DraggingStraightLine()))}t.preventDefault()}}MouseMoveLiveSelectObjectsForDragging(t){this.unselectEverything(),Au(t)&&(this.viewer.modifierKeys&ModifierKeysEnum.Shift)!=ModifierKeysEnum.Shift&&this.SelectEntitiesForDraggingWithRectangle(t)}DrawEdgeInteractivelyToLocation(t,e){this.DrawEdgeInteractivelyToLocationP(this.viewer.screenToSource(t),e)}DrawEdgeInteractivelyToLocationP(t,e){this.geomEdge=e?this.getStraightLineEdge(t):this.CalculateEdgeInteractivelyToLocation(t),this.viewer.drawRubberEdge(this.geomEdge)}getStraightLineEdge(t){const e=new GeomEdge(null);return e.curve=LineSegment.mkPP(this.SourcePort.Location,t),e}CalculateEdgeInteractivelyToLocation(t){return this.interactiveEdgeRouter.SourcePort==null&&this.interactiveEdgeRouter.SetSourcePortAndSourceLoosePolyline(this.SourcePort,this.sourceLoosePolylineWrap.loosePolyline),this.interactiveEdgeRouter.RouteEdgeToLocation(t)}drawEdgeInteractivelyToPort(t,e){this.geomEdge=e?this.getStraightLineEdge(this.TargetPort.Location):this.CalculateEdgeInteractively(this.TargetPort,t),this.viewer.drawRubberEdge(this.geomEdge)}DraggingStraightLine(){return this.viewer.graph==null?!0:this.interactiveEdgeRouter!=null&&this.interactiveEdgeRouter.OverlapsDetected}CalculateEdgeInteractively(t,e){this.interactiveEdgeRouter.SourcePort==null&&this.interactiveEdgeRouter.SetSourcePortAndSourceLoosePolyline(this.SourcePort,this.sourceLoosePolylineWrap.loosePolyline);let i,s=null;if(this.SourceOfInsertedEdge==this.TargetOfInsertedEdge)i=LineSegment.mkPP(this.SourcePort.Location,this.TargetPort.Location);else{const o={smoothedPolyline:null};i=this.interactiveEdgeRouter.RouteEdgeToPort(t,e,!1,o),s=o.smoothedPolyline}const n=new GeomEdge(null);return n.curve=i,n.smoothedPolyline=s,n}}function Au(l){return(l.buttons&1)==1}var Eu=Ys(58982);function En(l){const t=Eu(l);if(t.keyword!=null)return A.parse(t.keyword.toString());if(t!=null){if(t.rgba!=null)return new A(t.rgba[3],t.rgba[0],t.rgba[1],t.rgba[2]);if(t.rgb!=null)return A.mkRGB(t.rgb[0],t.rgb[1],t.rgb[2])}return A.Black}function Jo(l,t,e){for(const s of e.attr_list)if(s.type==="attr"){const n=s.eq;switch(s.id){case"edgeCurve":{const o=Ps(l),a=JSON.parse(n);o.curve=$(a)}break;case"graphBoundingBox":{const o=Ps(l),a=JSON.parse(n);o.boundingBox=new X(a)}break;case"boundaryCurve":{const o=Ps(l),a=JSON.parse(n),h=$(a);o instanceof Gt?o.boundingBox=h.boundingBox:o.boundaryCurve=h}break;case"geomEdge":{const o=Ps(l);break}case"sourceArrowhead":{const o=Ps(l);o.sourceArrowhead==null&&(o.sourceArrowhead=new Bt);break}case"targetArrowhead":{const o=Ps(l);o.targetArrowhead==null&&(o.targetArrowhead=new Bt);break}case"sourceArrowheadTip":{const o=Ps(l);o.sourceArrowhead==null&&(o.sourceArrowhead=new Bt),n!=="none"&&(o.sourceArrowhead.tipPosition=c.fromJSON(JSON.parse(n)));break}case"targetArrowheadTip":{const o=Ps(l);o.targetArrowhead==null&&(o.targetArrowhead=new Bt),n!=="none"&&(o.targetArrowhead.tipPosition=c.fromJSON(JSON.parse(n)));break}case"geomEdgeLabel":{const o=JSON.parse(n),a=l;i(a),new Es(a.label,new X(o)).setBoundingBox(new X(o));break}case"color":t.color=En(n);break;case"pencolor":t.pencolor=En(n);break;case"labelfontcolor":t.labelfontcolor=En(n);break;case"fontcolor":t.fontColor=En(n);break;case"fillcolor":t.fillColor=En(n);break;case"style":for(const o of wu(n))t.styles.push(o);break;case"shape":{const o=t;o.shape=vu(n);break}case"peripheries":t.peripheries=parseInt(n);break;case"headlabel":t.headlabel=n;break;case"label":if(typeof n=="string"){let a=0;t.labelText="";do{const h=n.indexOf("\\n",a);if(h>=0)t.labelText+=n.substring(a,h)+` `,a=h+2;else{t.labelText+=n.substring(a);break}}while(!0)}else typeof n=="number"&&(t.labelText=n.toString());l instanceof Is&&i(l);break;case"size":t.size=_o(n);break;case"pos":t.pos=_o(n);break;case"rankdir":t.rankdir=Iu(n);break;case"fontname":t.fontname=n;break;case"fontsize":t.fontsize=parseFloat(n);break;case"width":t.width=parseFloat(n);break;case"penwidth":t.penwidth=parseFloat(n);break;case"height":t.height=parseFloat(n);break;case"margin":t.margin=parseFloat(n);break;case"len":t.len=parseFloat(n);break;case"minlen":t.minlen=parseFloat(n);break;case"rank":t.rank=Tu(n);break;case"charset":t.charset=n;break;case"orientation":t.orientation=n;break;case"ratio":t.ratio=n;break;case"weight":t.weight=parseFloat(n);break;case"nodesep":t.nodesep=parseFloat(n);break;case"layersep":t.layersep=parseFloat(n);break;case"arrowsize":t.arrowsize=parseFloat(n);break;case"rotate":t.rotate=parseFloat(n);break;case"ranksep":t.ranksep=parseFloat(n);break;case"splines":t.splines=n==="true";break;case"overlap":t.overlap=n==="true";break;case"arrowtail":t.arrowtail=ol(n);break;case"taillabel":t.taillabel=n;break;case"arrowhead":t.arrowhead=ol(n);break;case"ordering":t.ordering=xu(n);break;case"URL":t.URL=n;break;case"dir":t.dir=Ou(n);break;case"concentrate":t.concentrate=n==="true";break;case"compound":t.compound=n==="true";break;case"lhead":t.lhead=n;break;case"ltail":t.ltail=n;break;case"bgcolor":t.bgcolor=En(n);break;case"center":t.center=n===!0||parseInt(n)===1;break;case"colorscheme":t.colorscheme=n;break;case"sides":t.sides=parseInt(n);break;case"distortion":t.distortion=parseFloat(n);break;case"skew":t.skew=parseFloat(n);break;case"bb":t.bb=Bu(n);break;case"labelloc":t.labelloc=n;break;case"decorate":t.decorate=n==="true";break;case"tailclip":t.tailclip=n==="true";break;case"headclip":t.headclip=n==="true";break;case"constraint":t.constraint=n==="true";break;case"gradientangle":t.gradientangle=parseFloat(n);break;case"samehead":t.samehead=n;break;case"href":t.href=n;break;case"imagepath":t.imagepath=n;break;case"image":t.image=n;break;case"labeljust":t.labejust=n;break;case"layers":t.layers=n.split(",");break;case"layer":t.layer=n;break;case"f":t.f=parseFloat(n);break;case"nojustify":t.nojustify=n==="true";break;case"root":t.root=n==="true";break;case"page":t.page=_o(n);break;case"pname":t.pname=n;break;case"kind":t.kind=n;break;case"fname":t.fname=n;break;case"subkind":t.subkind=n;break;case"area":t.area=parseFloat(n);break;case"tailport":t.tailport=n;break;case"headport":t.headport=n;break;case"wt":t.wt=n;break;case"id":t instanceof si||(t.id=n);break;case"edgetooltip":t.edgetooltip=n;break;case"headtooltip":t.headtooltip=n;break;case"tailtooltip":t.tailtooltip=n;break;case"headURL":t.headURL=n;break;case"tailURL":t.tailURL=n;break;case"labelURL":t.labelURL=n;break;case"edgeurl":t.edgeurl=n;break;case"shapefile":t.shapefile=n;break;case"xlabel":t.xlabel=n;break;case"sametail":t.sametail=n;break;case"clusterrank":t.clusterRank=n;break;case"measuredTextSize":t.measuredTextSize=JSON.parse(n);break;default:break}}else throw new Error("unexpected type "+s.type);function i(s){s.label==null&&(s.label=new Ua(s))}}function bn(l,t){const e=Ee.getDrawingObj(t);l.attr_list!=null&&Jo(t,e,l)}class rl{constructor(t){this.nodeMap=new Map,this.ast=t}parseEdge(t,e,i,s,n){let o,a;if(t.type==="node_id"){const u=t.id.toString();o=this.nodeMap.get(u),o==null?o=this.newNode(u,i,!1):this.tryToMoveToADeeperGraph(o,i)}else{const u=[];for(const d of t.children)if(d.type==="node_stmt")for(const m of this.parseEdge(d.node_id,e,i,s,n))u.push(m);else if(d.type!=="attr_stmt")throw new Error("not implemented");for(const d of t.children)if(d.type==="attr_stmt")for(const m of u)bn(d,m);return u}if(e.type==="node_id"){const u=e.id.toString();a=this.nodeMap.get(u),a==null?a=this.newNode(u,i,!1):this.tryToMoveToADeeperGraph(a,i)}else if(e.type==="subgraph"){const u=new Array;for(const d of e.children)if(d.type==="node_stmt")for(const m of this.parseEdge(t,d.node_id,i,s,n))u.push(m);else if(d.type!=="attr_stmt")throw new Error("not implemented");for(const d of e.children)if(d.type==="attr_stmt")for(const m of u)bn(d,m);return u}const h=new Is(o,a);return new gr(h,s),bn(n,h),[h]}tryToMoveToADeeperGraph(t,e){Mt.assert(t.parent!=null);const i=t.parent;i!=e&&s(i)<s(e)&&(i.remove(t),e.addNode(t));function s(n){let o=0,a=n.parent;for(;a;)o++,a=a.parent;return o}}newNode(t,e,i){let s=this.nodeMap.get(t);if(s==null){s=new ze(t),this.nodeMap.set(t,s),e.addNode(s);const n=new si(s);n.labelText=t;const o=ji.getDrawingObj(e);Ee.copyValidFields(o.defaultNodeObject,n)}else i&&Fn(e,s);return s}parseNode(t,e,i){const s=t.node_id.id.toString(),n=this.newNode(s,e,i);return Ee.getDrawingObj(n)==null&&new si(n),bn(t,n),n}parse(){return this.ast==null?null:(this.graph=new Vt(this.ast[0].id?this.ast[0].id.toString():"__graph__"),this.drawingGraph=new ji(this.graph),this.parseUnderGraph(this.ast[0].children,this.graph,this.ast[0].type==="digraph",!1),Fu(this.graph),Du(this.graph),this.graph)}parseGraphAttr(t,e){if(t.target==="node"){const i=ji.getDrawingObj(e);i.defaultNodeObject==null&&(i.defaultNodeObject=new si(null)),Jo(null,i.defaultNodeObject,t)}else t.target==="graph"&&bn(t,e)}getEntitiesSubg(t,e,i){let s=[];for(const n of t.children)if(n.type==="edge_stmt")for(let o=0;o<n.edge_list.length-1;o++)for(const a of this.parseEdge(n.edge_list[o],n.edge_list[o+1],e,i,n))s.push(a);else if(n.type!=="attr_stmt")if(n.type==="node_stmt")s.push(this.parseNode(n,e,!0));else if(n.type==="subgraph")if(n.id!=null){const o=new Vt(n.id.toString());e.addNode(o),this.nodeMap.set(o.id,o);const a=new ji(o);this.parseUnderGraph(n.children,o,i,!0),s.push(a.graph),o.isEmpty&&(e.removeNode(o),this.nodeMap.delete(o.id))}else s=s.concat(this.getEntitiesSubg(n,e,i));else throw new Error("Function not implemented.");return s}parseUnderGraph(t,e,i,s){for(const n of t)switch(n.type){case"node_stmt":this.parseNode(n,e,s);break;case"edge_stmt":{const o=n.edge_list;for(let a=0;a<o.length-1;a++)this.parseEdge(o[a],o[a+1],e,i,n)}break;case"subgraph":if(!this.process_same_rank(n,ji.getDrawingGraph(e)))if(n.id==null){const o=this.getEntitiesSubg(n,e,i);Lu(n,ji.getDrawingGraph(e),o)}else{const o=new Vt(n.id.toString());this.nodeMap.set(n.id.toString(),o),e.addNode(o),new ji(o),this.parseUnderGraph(n.children,o,i,!0),o.isEmpty()&&(e.remove(o),this.nodeMap.delete(o.id))}break;case"attr_stmt":this.parseGraphAttr(n,e);break;default:throw new Error("not implemented")}}process_same_rank(t,e){const i=t.children[0];if(i==null||i.type!=="attr_stmt")return!1;const s=i.attr_list;if(s==null||s.length===0)return!1;const n=s[0];if(n.type!=="attr"||n.id!=="rank")return!1;switch(n.eq){case"min":for(let o=1;o<t.children.length;o++){const a=t.children[o];if(a.type==="node_stmt")e.graphVisData.minRanks.push(a.node_id.id.toString());else throw new Error}return!0;case"max":for(let o=1;o<t.children.length;o++){const a=t.children[o];if(a.type==="node_stmt")e.graphVisData.minRanks.push(a.node_id.id.toString());else throw new Error}return!0;case"same":{const o=[];for(let a=1;a<t.children.length;a++){const h=t.children[a];h.type==="node_stmt"?(this.newNode(h.node_id.id.toString(),e.graph,!1),o.push(h.node_id.id.toString())):h.type==="attr_stmt"&&h.target==="node"&&(e.defaultNodeObject==null&&(e.defaultNodeObject=new si(null)),Jo(null,e.defaultNodeObject,h))}return e.graphVisData.sameRanks.push(o),!0}case"source":{for(let o=1;o<t.children.length;o++){const a=t.children[o];if(a.type==="node_stmt")e.graphVisData.sourceRanks.push(a.node_id.id.toString());else throw new Error}return!0}case"sink":for(let o=1;o<t.children.length;o++){const a=t.children[o];if(a.type==="node_stmt")e.graphVisData.sinkRanks.push(a.node_id.id.toString());else throw new Error}return!0;default:throw new Error("incorrect rank")}}}function Zo(l){try{return new rl(yu(l)).parse()}catch(t){return console.log("cannot parse the graph"),console.log(t.message),console.log("start: line =",t.location.start.line,"col=",t.location.start.column,"offset=",t.location.start.offset),console.log("end: line =",t.location.end.line,"col=",t.location.end.column,"offset=",t.location.end.offset),console.log("expected=",t.expected),console.log("found=",t.found),null}}function bu(l){try{return new rl([l]).parse()}catch(t){return console.log(t.message),null}}function*wu(l){const t=l.split(",");for(const e of t){const s=jo[e];s&&(yield s)}}function vu(l){const t=l.toLowerCase();return Kt[t]}function _o(l){const t=l.split(",");return[parseFloat(t[0]),parseFloat(t[1])]}function Iu(l){return di[l]}function Tu(l){return Uo[l]}function ol(l){return ms[l]}function xu(l){return $o[l]}function Ou(l){return Qo[l]}function Bu(l){const t=l.split(",");return[parseFloat(t[0]),parseFloat(t[1]),parseFloat(t[2]),parseFloat(t[3])]}function Lu(l,t,e){for(const i of l.children)if(i.type==="attr_stmt")for(const s of e)bn(i,s)}function Fu(l){const t=[];for(const e of l.subgraphsBreadthFirst())e.isEmpty()&&t.push(e);for(const e of t){const i=e.parent;i&&i.removeNode(e)}}function Du(l){for(const t of l.subgraphsBreadthFirst())Gt.getGeom(t)==null&&t.hasSomeAttrOnIndex(pt.GeomObjectIndex)&&new Gt(t);Gt.getGeom(l)==null&&l.hasSomeAttrOnIndex(pt.GeomObjectIndex)&&new Gt(l)}function gc(l){const t=qu(l);return{type:Wu(l),id:l.id,children:Nu(l,t)}}function Ru(l){return{type:"edge_stmt",edge_list:[{type:"node_id",id:l.source.id},{type:"node_id",id:l.target.id}],attr_list:Array.from(Gu(l))}}function Nu(l,t){const e=new Map,i=[],s=GeomGraph.getGeom(l);if(s){const n=Array.from(ll(s));i.push({type:"attr_stmt",target:"graph",attr_list:n})}Uu(i,l);for(const n of l.nodesBreadthFirst)e.set(n.id,ku(n));for(const n of l.nodesBreadthFirst){if(n.parent===l)continue;e.get(n.parent.id).children.push(e.get(n.id))}for(const n of l.deepEdges){const o=Ru(n),a=Hu(n,t);a===l?i.push(o):e.get(a.id).children.push(o)}for(const n of l.shallowNodes)i.push(e.get(n.id));return i}function*Gu(l){const t=GeomObject.getGeom(l);if(t&&(yield{type:"attr",id:"geomEdge",eq:"none"},t.curve&&(yield{type:"attr",id:"edgeCurve",eq:JSON.stringify(iCurveToJSON(t.curve))}),t.sourceArrowhead&&(yield{type:"attr",id:"sourceArrowhead",eq:"none"},t.sourceArrowhead.tipPosition&&(yield{type:"attr",id:"sourceArrowheadTip",eq:JSON.stringify(t.sourceArrowhead.tipPosition.toJSON())})),t.targetArrowhead&&(yield{type:"attr",id:"targetArrowhead",eq:"none"},t.targetArrowhead.tipPosition&&(yield{type:"attr",id:"targetArrowheadTip",eq:JSON.stringify(t.targetArrowhead.tipPosition.toJSON())})),l.label)){const e=l.label.getAttr(AttributeRegistry.GeomObjectIndex).boundingBox,i={left:e.left,right:e.right,top:e.top,bottom:e.bottom};yield{type:"attr",id:"geomEdgeLabel",eq:JSON.stringify(i)}}yield*ta(DrawingObject.getDrawingObj(l))}function ku(l){if(l instanceof Graph){const e=Array.from(ll(GeomGraph.getGeom(l))),i=[],s={type:"attr_stmt",target:"graph",attr_list:e};return i.push(s),{type:"subgraph",children:i,id:l.id}}else return{type:"node_stmt",node_id:{type:"node_id",id:l.id},attr_list:Array.from(Vu(l))}}function Mu(l){const t=GeomNode.getGeom(l).boundaryCurve;return{type:"attr",id:"boundaryCurve",eq:JSON.stringify(iCurveToJSON(t))}}function*Vu(l){GeomObject.getGeom(l)&&(yield Mu(l)),yield*ta(DrawingObject.getDrawingObj(l))}function*ta(l){l.color&&(yield{type:"attr",id:"color",eq:l.color.toString()}),l.fillColor&&(yield{type:"attr",id:"fillColor",eq:l.fillColor.toString()}),l.labelfontcolor&&(yield{type:"attr",id:"labelfontcolor",eq:l.labelfontcolor.toString()}),!(l.labelText==null||l.labelText==="")&&l.entity&&l.labelText!==l.id&&(yield{type:"attr",id:"label",eq:l.labelText}),l.fontColor&&l.fontColor.keyword.toLowerCase()!=="black"&&(yield{type:"attr",id:"fontColor",eq:l.fontColor.toString()}),l.styles&&l.styles.length&&(yield{type:"attr",id:"style",eq:l.styles.map(e=>StyleEnum[e]).reduce((e,i)=>e.concat(","+i))}),l.pencolor&&l.pencolor.keyword!=="black"&&(yield{type:"attr",id:"pencolor",eq:l.pencolor.toString()}),l.penwidth&&l.penwidth!==1&&(yield{type:"attr",id:"penwidth",eq:l.penwidth.toString()}),l.rankdir&&(yield{type:"attr",id:"rankdir",eq:l.rankdir.toString()}),l.fontname&&l.fontname!==DrawingObject.defaultLabelFontName&&(yield{type:"attr",id:"fontname",eq:l.fontname}),l.margin&&(yield{type:"attr",id:"margin",eq:l.margin.toString()}),l.fontsize&&l.fontsize!==DrawingObject.defaultLabelFontSize&&(yield{type:"attr",id:"fontsize",eq:l.fontsize.toString()}),l.orientation&&(yield{type:"attr",id:"orientation",eq:l.orientation.toString()}),l.ranksep&&(yield{type:"attr",id:"ranksep",eq:l.ranksep.toString()}),l.arrowtail&&(yield{type:"attr",id:"arrowtail",eq:ArrowTypeEnum[l.arrowtail]}),l.arrowhead&&(yield{type:"attr",id:"arrowhead",eq:ArrowTypeEnum[l.arrowhead]}),l.ordering&&(yield{type:"attr",id:"ordering",eq:l.ordering.toString()}),l.bgcolor&&(yield{type:"attr",id:"bgcolor",eq:l.bgcolor.toString()}),l.pos&&(yield{type:"attr",id:"pos",eq:l.pos.toString()}),l.nodesep&&(yield{type:"attr",id:"nodesep",eq:l.nodesep.toString()}),l.arrowsize&&(yield{type:"attr",id:"arrowsize",eq:l.arrowsize.toString()}),l.samehead&&(yield{type:"attr",id:"samehead",eq:l.samehead.toString()}),l.layersep&&(yield{type:"attr",id:"layersep",eq:l.layersep.toString()}),l.clusterRank&&(yield{type:"attr",id:"clusterrank",eq:l.clusterRank.toString()}),l.measuredTextSize&&(yield{type:"attr",id:"measuredTextSize",eq:JSON.stringify(l.measuredTextSize)}),l instanceof DrawingNode&&(l.shape&&l.shape!==ShapeEnum.box&&(yield{type:"attr",id:"shape",eq:l.shape.toString()}),l.xRad&&l.xRad!==3&&(yield{type:"attr",id:"xRad",eq:l.xRad.toString()}),l.yRad&&l.yRad!==3&&(yield{type:"attr",id:"yRad",eq:l.yRad.toString()}),l.padding&&l.padding!==2&&(yield{type:"attr",id:"padding",eq:l.padding.toString()}))}function Wu(l){return DrawingGraph.getDrawingGraph(l).hasDirectedEdge()?"digraph":"graph"}function Hu(l,t){let e=l.source,i=l.target,s=t.get(e.id),n=t.get(i.id);for(;s>n;)e=e.parent,s--;for(;s<n;)i=i.parent,n--;for(;e.parent!==i.parent;)e=e.parent,i=i.parent;return e.parent}function qu(l){const t=new Map;return t.set(l.id,0),al(l,t),t}function al(l,t){const e=t.get(l.id)+1;for(const i of l.shallowNodes)t.set(i.id,e),i instanceof Graph&&al(i,t)}function Ps(l){var t;return(t=ot.getGeom(l))!==null&&t!==void 0?t:zu(l)}function zu(l){if(l instanceof Vt)return new Gt(l);if(l instanceof ze)return new Jt(l);if(l instanceof Is)return new we(l);throw new Error("unsupported type "+l)}function Uu(l,t){const e=DrawingGraph.getDrawingObj(t);if(e==null)return;const i=e.defaultNodeObject;i&&l.push({type:"attr_stmt",target:"node",attr_list:Array.from(ta(i))})}function*ll(l){if(l==null)return;const t=l.boundingBox;if(t&&t.isEmpty()===!1){const e={left:t.left,right:t.right,top:t.top,bottom:t.bottom};yield{type:"attr",id:"graphBoundingBox",eq:JSON.stringify(e)}}l.radX!==10&&(yield{type:"attr",id:"radX",eq:l.radX.toString()}),l.radY!==10&&(yield{type:"attr",id:"radY",eq:l.radY.toString()})}function hl(l){const t=new Graph;try{const e=l.split(/\r\n|\r|\n/);for(const i of e){if(i.length==0||i.charAt(0)=="#")continue;const s=i.split(/\t| |,/);if(s.length<2)return console.log("cannot parse",i),null;const n=s[0],o=s[1],a=ul(t,n),h=ul(t,o),u=new Edge(a,h);new DrawingEdge(u,!0)}}catch(e){console.log(e.message)}return new DrawingGraph(t),t}function ul(l,t){let e=l.findNode(t);return e==null&&(e=l.addNode(new Node(t)),new DrawingNode(e)),e}async function fc(l){const t=await l.text();let e;return l.name.toLowerCase().endsWith(".json")?e=cl(JSON.parse(t)):l.name.toLowerCase().endsWith(".txt")||l.name.toLowerCase().endsWith(".tsv")||l.name.toLowerCase().endsWith(".csv")?e=hl(t):e=Zo(t),e&&(e.id=l.name),e}async function pc(l){const t=l.slice(l.lastIndexOf("/")+1),e=await fetch(l);let i;if(t.endsWith(".json")){const s=await e.json();i=cl(s)}else if(t.endsWith(".txt")){const s=await e.text();i=hl(s)}else{const s=await e.text();i=Zo(s)}return i&&(i.id=t),i}function cl(l){return"nodes"in l?ju(l):bu(l)}function ju(l){const t=new Graph;for(const e of l.nodes){const i=String(e.id),s=t.addNode(new Node(i)),n=new DrawingNode(s),{label:o=i,shape:a="box"}=e;n.labelText=o,n.ShapeEnum=ShapeEnum[a],"weight"in e&&(n.weight=e.weight),"color"in e&&(n.color=parseColor(e.color))}for(const e of l.edges){const i=t.setEdge(String(e.source),String(e.target)),s=new DrawingEdge(i,!1),{arrowhead:n="none",arrowtail:o="none",directed:a=!0}=e;s.arrowhead=ArrowTypeEnum[n],s.arrowtail=ArrowTypeEnum[o],s.directed=a,"weight"in e&&(s.weight=e.weight),"color"in e&&(s.color=parseColor(e.color))}return new DrawingGraph(t),t}function Qu(l,t){const{mappedEdges:e,DOTToIdMap:i}=$u(l,t),s=Xu(e,i),n=Zo(s),o=new Gt(n);for(const E of n.deepEdges)new we(E);for(const E of n.nodesBreadthFirst){const T=new Jt(E);T.boundaryCurve=W.mkCircle(50,new c(0,0))}o.layoutSettings=new Hs,o.layoutSettings.layerDirection=di.LR,o.layoutSettings.LayerSeparation=60,o.layoutSettings.commonSettings.NodeSeparation=40,mh(o);const a={};for(const E of o.nodesBreadthFirst)a[i[E.id]]={obj:E};for(const E of l)a[E.id]={...a[E.id],datum:{...E,x:a[E.id].obj.center.x,y:a[E.id].obj.center.y}};const h=t.map(E=>({...E,source:a[E.source].datum,target:a[E.target].datum})),u=[];for(const E of h){const T=u.find(H=>H.nodes.has(E.source)),B=u.find(H=>H.nodes.has(E.target));T&&B?T!==B&&(B.nodes.forEach(T.nodes.add,T.nodes),u.splice(u.indexOf(B),1),T.top=Math.min(T.top,B.top),T.bottom=Math.max(T.bottom,B.bottom),T.left=Math.min(T.left,B.left),T.right=Math.max(T.right,B.right)):T?(T.nodes.add(E.target),T.top=Math.min(T.top,E.target.y),T.bottom=Math.max(T.bottom,E.target.y),T.left=Math.min(T.left,E.target.x),T.right=Math.max(T.right,E.target.x)):B?(B.nodes.add(E.source),B.top=Math.min(B.top,E.source.y),B.bottom=Math.max(B.bottom,E.source.y),B.left=Math.min(B.left,E.source.x),B.right=Math.max(B.right,E.source.x)):u.push({top:Math.min(E.source.y,E.target.y),bottom:Math.max(E.source.y,E.target.y),left:Math.min(E.source.x,E.target.x),right:Math.max(E.source.x,E.target.x),nodes:new Set([E.source,E.target])})}let d=0,m=0;for(const E of u)if(d===0)d=E.bottom+200,m=E.left;else{const T=d-E.top,B=m-E.left;for(const H of E.nodes)H.x+=B,H.y+=T;d+=E.bottom-E.top+200}const y=Object.values(a).map(E=>E.datum);return Yu(y),[y,h]}function $u(l,t){const e=[],i={},s={};let n=0;for(const o of l)i[o.id]=n.toString(10),s[n.toString(10)]=o.id,n++;for(const o of t)e.push({source:i[o.source],target:i[o.target]});return{mappedEdges:e,DOTToIdMap:s,idToDOTMap:i}}function Xu(l,t){let e=` digraph G { rankdir="LR"; TBbalance="min" `;for(const i of l)e+=i.source+"->"+i.target+` [ minlen=3 ] `;return e+=Ku(t),e+="}",e}function Ku(l){let t="";for(const e of Object.keys(l))t+=e+` [fixedsize=true, width=1.2, height=1.7] `;return t}function Yu(l){const t=Ju(l);for(let e of l)e.x=e.x-t.center.x,e.y=e.y-t.center.y}function Ju(l){if(l.length===0)return{top:0,right:0,bottom:0,left:0,center:{x:0,y:0}};const t=l.reduce((s,n)=>(n.x>s.right&&(s.right=n.x),n.x<s.left&&(s.left=n.x),n.y>s.bottom&&(s.bottom=n.y),n.y<s.top&&(s.top=n.y),s),{top:1/0,right:-1/0,bottom:-1/0,left:1/0}),e=t.top+(t.bottom-t.top)/2,i=t.left+(t.right-t.left)/2;return{...t,center:{x:i,y:e}}}addEventListener("message",async l=>{const{nodes:t,edges:e,config:i}=l.data,[s,n]=Qu(t,e,i);postMessage({nodes:s,edges:n})})})()})(); //# sourceMappingURL=1183.7444f51e5996a7f23c7d.js.map
.
Edit
..
Edit
1117.145ac642f59357bc40d8.js
Edit
1117.145ac642f59357bc40d8.js.map
Edit
1118.c684d1aadf16a6c70620.js
Edit
1118.c684d1aadf16a6c70620.js.map
Edit
1122.5fbf0d7cd148c610616d.js
Edit
1122.5fbf0d7cd148c610616d.js.map
Edit
1142.a4b35a0e8699cafd901e.js
Edit
1142.a4b35a0e8699cafd901e.js.map
Edit
1162.81868b3ac499fa5ea04b.js
Edit
1162.81868b3ac499fa5ea04b.js.map
Edit
1183.7444f51e5996a7f23c7d.js
Edit
1183.7444f51e5996a7f23c7d.js.map
Edit
1282.ae38cac1b732d8ac1d96.js
Edit
1282.ae38cac1b732d8ac1d96.js.map
Edit
130.a58aaeea748f37ee6482.js
Edit
130.a58aaeea748f37ee6482.js.map
Edit
1419.59f53ae25085b28e1e11.js
Edit
1419.59f53ae25085b28e1e11.js.map
Edit
1420.e63ce495727f83b8887d.js
Edit
1420.e63ce495727f83b8887d.js.map
Edit
1438.ccdd05d7188edf4191ff.js
Edit
1438.ccdd05d7188edf4191ff.js.map
Edit
1446.fe7b1f4563629b80793f.js
Edit
1446.fe7b1f4563629b80793f.js.map
Edit
1484.3da94e44ecdadcd342d4.js
Edit
1484.3da94e44ecdadcd342d4.js.map
Edit
1492.4026c6e7130c3afdae87.js
Edit
1494.ef220afb67ff6c52c7af.js
Edit
1494.ef220afb67ff6c52c7af.js.map
Edit
1560.538cd2395be11ba4e2c9.js
Edit
1560.538cd2395be11ba4e2c9.js.map
Edit
1579.c391ef869d4f7bfc0d1c.js
Edit
1579.c391ef869d4f7bfc0d1c.js.map
Edit
1646.d7d87a40853795910533.js
Edit
1646.d7d87a40853795910533.js.map
Edit
1710.7db3f56c6714c0c340e0.js
Edit
1710.7db3f56c6714c0c340e0.js.map
Edit
1716.f71f518289da5d2229bc.js
Edit
1716.f71f518289da5d2229bc.js.map
Edit
1740.baf38e7ee007e1a6935e.js
Edit
1740.baf38e7ee007e1a6935e.js.map
Edit
1821.c9a2456dc8d78cf6b02f.js
Edit
1821.c9a2456dc8d78cf6b02f.js.map
Edit
1888.d33142738af4fbf8a230.js
Edit
1888.d33142738af4fbf8a230.js.map
Edit
1914.5f33b3c2133b5bb7ea6e.js
Edit
1914.5f33b3c2133b5bb7ea6e.js.map
Edit
198.65a768ff6c601d19ea3f.js
Edit
198.65a768ff6c601d19ea3f.js.map
Edit
1990.9171129a8deabb59bf30.js
Edit
1990.9171129a8deabb59bf30.js.map
Edit
2018.5ff00ee0456301c1cf43.js
Edit
2018.5ff00ee0456301c1cf43.js.map
Edit
205.2eb73847215c8d021cc9.js
Edit
205.2eb73847215c8d021cc9.js.map
Edit
2077.a5848ca4b4b9fdebca17.js
Edit
2077.a5848ca4b4b9fdebca17.js.map
Edit
2094.97e7f0876201e76a77fd.js
Edit
2094.97e7f0876201e76a77fd.js.map
Edit
2150.7576285186c713978b39.js
Edit
2150.7576285186c713978b39.js.map
Edit
2152.b55841e6f422682a3891.js
Edit
2152.b55841e6f422682a3891.js.map
Edit
221.0fc4d14d0a67f3a25d64.js
Edit
221.0fc4d14d0a67f3a25d64.js.map
Edit
2218.623d73bd0985ddf5f8c4.js
Edit
2218.623d73bd0985ddf5f8c4.js.map
Edit
2223.e65417164a45701ed9dc.js
Edit
2223.e65417164a45701ed9dc.js.map
Edit
2244.70c156ada2487a05595c.js
Edit
2244.70c156ada2487a05595c.js.map
Edit
2278.f887de0a65e1b784ea9f.js
Edit
2278.f887de0a65e1b784ea9f.js.map
Edit
2288.6a65ba08c6c0f4f83435.js
Edit
2288.6a65ba08c6c0f4f83435.js.map
Edit
2311.73e1a2b949d289f5d6c9.js
Edit
2311.73e1a2b949d289f5d6c9.js.map
Edit
2398.d142e32be48079fc63c0.js
Edit
2398.d142e32be48079fc63c0.js.map
Edit
2405.c1b37a7cc8182472f6a6.js
Edit
2405.c1b37a7cc8182472f6a6.js.map
Edit
2446.0418c7ea000998178d8b.js
Edit
2446.0418c7ea000998178d8b.js.map
Edit
2450.d73c024ff7273aebf911.js
Edit
2450.d73c024ff7273aebf911.js.map
Edit
2586.668c65b61e9ea31b5bca.js
Edit
2586.668c65b61e9ea31b5bca.js.map
Edit
265.ed6933785cc750cbd9ed.js
Edit
265.ed6933785cc750cbd9ed.js.map
Edit
2658.7f70ebc378803654a814.js
Edit
2658.7f70ebc378803654a814.js.map
Edit
2686.ae267304ddd1380c30c7.js
Edit
2686.ae267304ddd1380c30c7.js.map
Edit
2692.fa24ada7d987a7ee05f1.js
Edit
2692.fa24ada7d987a7ee05f1.js.map
Edit
2699.b79e57051a1a63376320.js
Edit
2699.b79e57051a1a63376320.js.map
Edit
2710.e1ac8e57578a838f5bd8.js
Edit
2710.e1ac8e57578a838f5bd8.js.map
Edit
2744.d6b14bf01022bdb8eab5.js
Edit
2744.d6b14bf01022bdb8eab5.js.map
Edit
2745.8049d948cb362dfc6cb3.js
Edit
2745.8049d948cb362dfc6cb3.js.map
Edit
2835.01beb5b1a252d779aad7.js
Edit
2835.01beb5b1a252d779aad7.js.map
Edit
2961.4b27b21453fdbb115dd4.js
Edit
2961.4b27b21453fdbb115dd4.js.map
Edit
2962.85c9dc0cca68efab5e0c.js
Edit
2962.85c9dc0cca68efab5e0c.js.map
Edit
2975.e64aaea6ff35a7d3b3fd.js
Edit
2975.e64aaea6ff35a7d3b3fd.js.map
Edit
3003.f51365051eb27cf765d8.js
Edit
3003.f51365051eb27cf765d8.js.map
Edit
3042.44bad7d2d0536000b808.js
Edit
3042.44bad7d2d0536000b808.js.map
Edit
3062.ad5844391370fcc7525a.js
Edit
3062.ad5844391370fcc7525a.js.map
Edit
3082.704af6779ad700a5fa42.js
Edit
3082.704af6779ad700a5fa42.js.map
Edit
3096.aed61083f1ba4803ae84.js
Edit
3096.aed61083f1ba4803ae84.js.map
Edit
3126.10c85e1f02105e470a69.js
Edit
3126.10c85e1f02105e470a69.js.map
Edit
3169.0b88a5a2340f70961599.js
Edit
3169.0b88a5a2340f70961599.js.map
Edit
3171.c79c28e2611563e2dbcb.js
Edit
3171.c79c28e2611563e2dbcb.js.map
Edit
3182.831f754ed3b6f10441a0.js
Edit
3182.831f754ed3b6f10441a0.js.map
Edit
3192.2cb90eadf3399270363e.js
Edit
3192.2cb90eadf3399270363e.js.map
Edit
3217.c6faaa4f5637068f90f3.js
Edit
3217.c6faaa4f5637068f90f3.js.map
Edit
3259.c8e4d6ad93201a56e49f.js
Edit
3259.c8e4d6ad93201a56e49f.js.map
Edit
3284.79c2897655286b0c1f6d.js
Edit
3284.79c2897655286b0c1f6d.js.map
Edit
3303.225dae64cff0c2280c3b.js
Edit
3303.225dae64cff0c2280c3b.js.map
Edit
3326.cabc370d66d7ecfbd2c3.js
Edit
3326.cabc370d66d7ecfbd2c3.js.map
Edit
344.85cff3029cbbb5463c7e.js
Edit
344.85cff3029cbbb5463c7e.js.map
Edit
3466.fda7da0cb4150e59da98.js
Edit
3466.fda7da0cb4150e59da98.js.map
Edit
3474.74dfd856a9528c758a57.js
Edit
3474.74dfd856a9528c758a57.js.map
Edit
348.fd20e2547f12dbed76c7.js
Edit
348.fd20e2547f12dbed76c7.js.map
Edit
3495.9c1ae6f61edf7aef207b.js
Edit
3495.9c1ae6f61edf7aef207b.js.map
Edit
3501.a0ee7c2b24136aa91eb5.js
Edit
3501.a0ee7c2b24136aa91eb5.js.map
Edit
3520.a3c2b474e2dcaf9879fc.js
Edit
3520.a3c2b474e2dcaf9879fc.js.map
Edit
3605.41e3c44dfe2ca2966198.js
Edit
3605.41e3c44dfe2ca2966198.js.map
Edit
362.e5ce68af98ee6713a4e7.js
Edit
362.e5ce68af98ee6713a4e7.js.map
Edit
3622.0b196041f825b42c5233.js
Edit
3622.0b196041f825b42c5233.js.map
Edit
3630.1ffe9229d5c27fd0823a.js
Edit
3630.1ffe9229d5c27fd0823a.js.map
Edit
3659.f5dc1bb19d36546aadb8.js
Edit
3659.f5dc1bb19d36546aadb8.js.map
Edit
3688.ec5e74c60569e9498687.js
Edit
3688.ec5e74c60569e9498687.js.map
Edit
3718.b570aa4fa35f8dfc686e.js
Edit
3718.b570aa4fa35f8dfc686e.js.map
Edit
3726.84ef8bb1304f7adbc7f3.js
Edit
3726.84ef8bb1304f7adbc7f3.js.map
Edit
398.ceeafcf522343c717c4b.js
Edit
398.ceeafcf522343c717c4b.js.map
Edit
4064.e52eb763993ad947e4a1.js
Edit
4064.e52eb763993ad947e4a1.js.map
Edit
407.594046bd73cc88c29e80.js
Edit
407.594046bd73cc88c29e80.js.map
Edit
4113.3fa5432815c4662eb03e.js
Edit
4113.3fa5432815c4662eb03e.js.map
Edit
4114.c4741f0a73781d3f87dc.js
Edit
4114.c4741f0a73781d3f87dc.js.map
Edit
4120.968e1408d894f8515330.js
Edit
4120.968e1408d894f8515330.js.map
Edit
4162.8b8a683fa98d677f9137.js
Edit
4162.8b8a683fa98d677f9137.js.map
Edit
4209.de7f2b850ee1292a67e5.js
Edit
4209.de7f2b850ee1292a67e5.js.map
Edit
4224.cc13db0c6e3f7fdb05c9.js
Edit
4224.cc13db0c6e3f7fdb05c9.js.map
Edit
4251.28e90ad13c8fe749062c.js
Edit
4251.28e90ad13c8fe749062c.js.map
Edit
4334.396d65b7ba31733108e9.js
Edit
4334.396d65b7ba31733108e9.js.map
Edit
4350.6db49924324f8061d361.js
Edit
4350.6db49924324f8061d361.js.map
Edit
4463.24a3e34bed64cbbb8b99.js
Edit
4463.24a3e34bed64cbbb8b99.js.map
Edit
4514.03e966fee9064d7305dd.js
Edit
4514.03e966fee9064d7305dd.js.map
Edit
4564.ea4a09ba96ddbf74a0ee.js
Edit
4564.ea4a09ba96ddbf74a0ee.js.map
Edit
46.7809585ddbb4791e248a.js
Edit
46.7809585ddbb4791e248a.js.map
Edit
4630.54d7f3b9d384c6b95bbc.js
Edit
4630.54d7f3b9d384c6b95bbc.js.map
Edit
4656.a07d832134b096826a58.js
Edit
4656.a07d832134b096826a58.js.map
Edit
468.d3a2ba8b0d226ca1475b.js
Edit
468.d3a2ba8b0d226ca1475b.js.map
Edit
4680.abd86af55b75e75326ab.js
Edit
4680.abd86af55b75e75326ab.js.map
Edit
4691.2f69f76af87a66a1513c.js
Edit
4691.2f69f76af87a66a1513c.js.map
Edit
4698.c9a2c562b12da12dc66e.js
Edit
4698.c9a2c562b12da12dc66e.js.map
Edit
4791.fc3ef0337811ab73b164.js
Edit
4791.fc3ef0337811ab73b164.js.map
Edit
4814.2d8cb562606e508512d8.js
Edit
4814.2d8cb562606e508512d8.js.map
Edit
4824.2da8107f19d58bf153e0.js
Edit
4824.2da8107f19d58bf153e0.js.map
Edit
4839.f4d2edd5c2678ef2b624.js
Edit
4839.f4d2edd5c2678ef2b624.js.map
Edit
4857.4971a98037d2ec3b663d.js
Edit
4857.4971a98037d2ec3b663d.js.map
Edit
4865.be02c1283a83523c4414.js
Edit
4865.be02c1283a83523c4414.js.map
Edit
494.5463fc5a297eaedd150f.js
Edit
494.5463fc5a297eaedd150f.js.map
Edit
4958.226af5f19bf47305a407.js
Edit
4958.226af5f19bf47305a407.js.map
Edit
4962.bbff24c5a85e9314600a.js
Edit
4962.bbff24c5a85e9314600a.js.map
Edit
4964.1f2cc5acc0078feb7b08.js
Edit
4964.1f2cc5acc0078feb7b08.js.map
Edit
4965.ccdc00d808390be53820.js
Edit
4965.ccdc00d808390be53820.js.map
Edit
5065.a2c71dab50ccb4174ee2.js
Edit
5065.a2c71dab50ccb4174ee2.js.map
Edit
5074.92e2d1ae98dcd913506e.js
Edit
5074.92e2d1ae98dcd913506e.js.map
Edit
5091.987ffc33b70121541e5d.js
Edit
5091.987ffc33b70121541e5d.js.map
Edit
5106.581eaf66a6592320d97a.js
Edit
5106.581eaf66a6592320d97a.js.map
Edit
5110.96d49ea826be96c65045.js
Edit
5110.96d49ea826be96c65045.js.map
Edit
5130.cbdddcd716a093bdbaac.js
Edit
5130.cbdddcd716a093bdbaac.js.map
Edit
5196.9b7364caf64a8583ad01.js
Edit
5196.9b7364caf64a8583ad01.js.map
Edit
5198.2cd64d4e16a385dd9b91.js
Edit
5198.2cd64d4e16a385dd9b91.js.map
Edit
5280.2c29942977baa2dfbe0e.js
Edit
5280.2c29942977baa2dfbe0e.js.map
Edit
5364.0288d9c98f74f26b73e7.js
Edit
5364.0288d9c98f74f26b73e7.js.map
Edit
5446.ad01d0b233122dd49849.js
Edit
5446.ad01d0b233122dd49849.js.map
Edit
5550.5bf3e7d23d6b104740fd.js
Edit
5550.5bf3e7d23d6b104740fd.js.map
Edit
5618.909592bbe054b70f2377.js
Edit
5618.909592bbe054b70f2377.js.map
Edit
5648.a1fc2b0cbbca9bfa1d94.js
Edit
5648.a1fc2b0cbbca9bfa1d94.js.map
Edit
5664.c55be32f6d459ac3f3d8.js
Edit
5664.c55be32f6d459ac3f3d8.js.map
Edit
5671.e1e396b75d7b95ef461f.js
Edit
5671.e1e396b75d7b95ef461f.js.map
Edit
5742.117597ec799ab75cb2f4.js
Edit
5742.117597ec799ab75cb2f4.js.map
Edit
5747.b9389680058c12ffba68.js
Edit
5747.b9389680058c12ffba68.js.map
Edit
5757.5a4b7f2368dd09da42be.js
Edit
5786.c45dfaf9e1d969472e5e.js
Edit
5786.c45dfaf9e1d969472e5e.js.map
Edit
5790.29b0a5797fd46e9664f5.js
Edit
5790.29b0a5797fd46e9664f5.js.map
Edit
5923.b9c876b4bf528d8511cb.js
Edit
5923.b9c876b4bf528d8511cb.js.map
Edit
5984.1efdc4bb85100bd19ca9.js
Edit
5984.1efdc4bb85100bd19ca9.js.map
Edit
5995.5c7a375f33ea1cd16daa.js
Edit
5995.5c7a375f33ea1cd16daa.js.map
Edit
6018.befdd11bf701ea71f7bf.js
Edit
6018.befdd11bf701ea71f7bf.js.map
Edit
6029.bdcbf27bcdd36812f646.js
Edit
6029.bdcbf27bcdd36812f646.js.map
Edit
6088.7f526abfdb4003574c68.js
Edit
6088.7f526abfdb4003574c68.js.map
Edit
613.084d33252856771cf6e1.js
Edit
613.084d33252856771cf6e1.js.map
Edit
6185.2a7c893c6b3f2f0dadb8.js
Edit
6185.2a7c893c6b3f2f0dadb8.js.map
Edit
6208.571f272269524cfd14e7.js
Edit
6208.571f272269524cfd14e7.js.map
Edit
6236.30d1fa6aee173c946c50.js
Edit
6236.30d1fa6aee173c946c50.js.map
Edit
6244.64f83fc5d05560979c51.js
Edit
6244.64f83fc5d05560979c51.js.map
Edit
6260.b8be95165766a81dade2.js
Edit
6260.b8be95165766a81dade2.js.map
Edit
630.56b78dcdaeeb9d9c2967.js
Edit
630.56b78dcdaeeb9d9c2967.js.map
Edit
6302.a2ffa52069511df9772f.js
Edit
6302.a2ffa52069511df9772f.js.map
Edit
6315.f4d87fc6f8ae3cb40e38.js
Edit
6315.f4d87fc6f8ae3cb40e38.js.map
Edit
6414.7520859a2d9cc0a63d7f.js
Edit
6414.7520859a2d9cc0a63d7f.js.map
Edit
6446.1d75a8140260005fffbd.js
Edit
6446.1d75a8140260005fffbd.js.map
Edit
6743.67a52a99e2fdd1ae1e10.js
Edit
6743.67a52a99e2fdd1ae1e10.js.map
Edit
6759.0454d3c1e41385379bdc.js
Edit
6759.0454d3c1e41385379bdc.js.map
Edit
6772.0d4a074848bc323be8f8.js
Edit
6772.0d4a074848bc323be8f8.js.map
Edit
680.726adca366b4ecb272db.js
Edit
680.726adca366b4ecb272db.js.map
Edit
6830.a4b0ecf3a6d784ca7609.js
Edit
6830.a4b0ecf3a6d784ca7609.js.map
Edit
6834.0c9ef40e2f2b5428983d.js
Edit
6834.0c9ef40e2f2b5428983d.js.map
Edit
6857.252a60422ee275193aa7.js
Edit
6857.252a60422ee275193aa7.js.map
Edit
6940.b6c74df14413f0188f0d.js
Edit
6940.b6c74df14413f0188f0d.js.map
Edit
6990.d663924714fc213b17c6.js
Edit
6990.d663924714fc213b17c6.js.map
Edit
7018.5a037d2577fedc8d10f1.js
Edit
7018.5a037d2577fedc8d10f1.js.map
Edit
7031.047b15171c23b248efa0.js
Edit
7031.047b15171c23b248efa0.js.map
Edit
7033.141597840e42815ef6a4.js
Edit
7033.141597840e42815ef6a4.js.map
Edit
7048.3746fc9a274bf8ff72f1.js
Edit
7048.3746fc9a274bf8ff72f1.js.map
Edit
7051.604a402d305e093c00c2.js
Edit
7051.604a402d305e093c00c2.js.map
Edit
7061.f18464bcd6c6d7455662.js
Edit
7061.f18464bcd6c6d7455662.js.map
Edit
7080.9cdd1b7a0bf62b48e1fe.js
Edit
7080.9cdd1b7a0bf62b48e1fe.js.map
Edit
7200.d4425528f6cee80f9931.js
Edit
7200.d4425528f6cee80f9931.js.map
Edit
7235.46f071d3e4d0bb976223.js
Edit
7235.46f071d3e4d0bb976223.js.map
Edit
7246.03f5a8496e53f64602e2.js
Edit
7246.03f5a8496e53f64602e2.js.map
Edit
7249.3bea4aaf890f89fdad45.js
Edit
7249.3bea4aaf890f89fdad45.js.map
Edit
7299.cdff402b076dfea09ead.js
Edit
7299.cdff402b076dfea09ead.js.map
Edit
7348.6fd722455e8c7e077815.js
Edit
7348.6fd722455e8c7e077815.js.map
Edit
7396.ded473b7a47dc42fbb59.js
Edit
7396.ded473b7a47dc42fbb59.js.map
Edit
7466.b7c17c526c7b734dd5f7.js
Edit
7466.b7c17c526c7b734dd5f7.js.map
Edit
7539.5f405cae3b15e1e2f6fa.js
Edit
7539.5f405cae3b15e1e2f6fa.js.map
Edit
7585.084552e02c66201a55be.js
Edit
7585.084552e02c66201a55be.js.map
Edit
7626.38819cc0696f2d25cf99.js
Edit
7626.38819cc0696f2d25cf99.js.map
Edit
7651.5024ed8dd1beb08d01ab.js
Edit
7651.5024ed8dd1beb08d01ab.js.map
Edit
7681.7ef7b4f86e99abd7b7e1.js
Edit
7681.7ef7b4f86e99abd7b7e1.js.map
Edit
7691.0ad86f0c686b19ce829e.js
Edit
7691.0ad86f0c686b19ce829e.js.map
Edit
7790.4c141092868e7208a087.js
Edit
7790.4c141092868e7208a087.js.map
Edit
7806.dff3509790e494ca5a45.js
Edit
7806.dff3509790e494ca5a45.js.map
Edit
7836.afe37ef4be354f0a3b91.js
Edit
7836.afe37ef4be354f0a3b91.js.map
Edit
7882.e1721e9d6ac2d421bcda.js
Edit
7882.e1721e9d6ac2d421bcda.js.map
Edit
7886.8499ded396232466be7d.js
Edit
7886.8499ded396232466be7d.js.map
Edit
7887.a6dcfd824d57598ba1c3.js
Edit
7887.a6dcfd824d57598ba1c3.js.map
Edit
7969.a048d8060cabf1aede33.js
Edit
7969.a048d8060cabf1aede33.js.map
Edit
7996.bd232896e4559d37a26f.js
Edit
7996.bd232896e4559d37a26f.js.map
Edit
8016.8145cd87abcdd0646db2.js
Edit
8016.8145cd87abcdd0646db2.js.map
Edit
8018.c31846109f2dff21d8c4.js
Edit
8018.c31846109f2dff21d8c4.js.map
Edit
8056.4e8f71ed4d507f89b487.js
Edit
8056.4e8f71ed4d507f89b487.js.map
Edit
8177.52abd0953ac914f69e26.js
Edit
8177.52abd0953ac914f69e26.js.map
Edit
8220.aeea4a8f0893b3447b56.js
Edit
8220.aeea4a8f0893b3447b56.js.map
Edit
8224.75bd73bf51ff7a2fc4a0.js
Edit
8224.75bd73bf51ff7a2fc4a0.js.map
Edit
8230.d65bce2998eec95c6082.js
Edit
8230.d65bce2998eec95c6082.js.map
Edit
8260.c1da67af19b9259d5651.js
Edit
8260.c1da67af19b9259d5651.js.map
Edit
8271.0ee36e030014244adb47.js
Edit
8271.0ee36e030014244adb47.js.map
Edit
8332.a62e8632a336661f2969.js
Edit
8332.a62e8632a336661f2969.js.map
Edit
8334.1196f5ddcef25711fc25.js
Edit
8334.1196f5ddcef25711fc25.js.map
Edit
8347.de402f9280cd7a316c57.js
Edit
8347.de402f9280cd7a316c57.js.map
Edit
8390.9de755da2e214cc845a3.js
Edit
8390.9de755da2e214cc845a3.js.map
Edit
8393.30e95ae45cbe5455dcda.js
Edit
8393.30e95ae45cbe5455dcda.js.map
Edit
8477.4dad0537d13cf9315e86.js
Edit
8477.4dad0537d13cf9315e86.js.map
Edit
8494.659892f00c9d15ae441a.js
Edit
8494.659892f00c9d15ae441a.js.map
Edit
8530.0460c988ee4a40ce7769.js
Edit
8530.0460c988ee4a40ce7769.js.map
Edit
8542.317c15ed57f68fcf0c97.js
Edit
8542.317c15ed57f68fcf0c97.js.map
Edit
8547.390120a5caf7646e0e3e.js
Edit
8547.390120a5caf7646e0e3e.js.map
Edit
8566.5c8f392bb383ab92eed0.js
Edit
8566.5c8f392bb383ab92eed0.js.map
Edit
8622.5acf73c1485a11dfb0ab.js
Edit
8622.5acf73c1485a11dfb0ab.js.map
Edit
8706.f17afa6bcdfd511d5b03.js
Edit
8706.f17afa6bcdfd511d5b03.js.map
Edit
874.d24410518317d605c708.js
Edit
874.d24410518317d605c708.js.map
Edit
8813.e5137844631f6ddedbce.js
Edit
8813.e5137844631f6ddedbce.js.map
Edit
8856.2720526447b3adb5c75f.js
Edit
8856.2720526447b3adb5c75f.js.map
Edit
886.5f3383e84b10a6530b97.js
Edit
886.5f3383e84b10a6530b97.js.map
Edit
8864.2f4ee982114c25634e55.js
Edit
8864.2f4ee982114c25634e55.js.map
Edit
8902.71f14964ec6cea84dc8e.js
Edit
8902.71f14964ec6cea84dc8e.js.map
Edit
8932.e59e50ddb63414e0f2b9.js
Edit
8932.e59e50ddb63414e0f2b9.js.map
Edit
8990.665213a5c89afd6b2f83.js
Edit
8990.665213a5c89afd6b2f83.js.map
Edit
9034.a32e36472481cbe5d72d.js
Edit
9034.a32e36472481cbe5d72d.js.map
Edit
9038.f03b25f160057d4a0bf6.js
Edit
9038.f03b25f160057d4a0bf6.js.map
Edit
904.b68cd2a0cd6d68c5f1ae.js
Edit
904.b68cd2a0cd6d68c5f1ae.js.map
Edit
9044.441f64d6d946cc93be46.js
Edit
9044.441f64d6d946cc93be46.js.map
Edit
9147.8309cadbc384209d62e5.js
Edit
9147.8309cadbc384209d62e5.js.map
Edit
9150.38487365ffd149b730af.js
Edit
9150.38487365ffd149b730af.js.map
Edit
9292.e6befb57f8f116ad95a8.js
Edit
9292.e6befb57f8f116ad95a8.js.map
Edit
9355.95d7e1782f93f339549e.js
Edit
9355.95d7e1782f93f339549e.js.map
Edit
9388.88d95a230e9432e7037b.js
Edit
9388.88d95a230e9432e7037b.js.map
Edit
9390.c72fcd228017f7647b38.js
Edit
9390.c72fcd228017f7647b38.js.map
Edit
9414.642bfe0d5eb16efd0c16.js
Edit
9414.642bfe0d5eb16efd0c16.js.map
Edit
9449.502f2a824d0203e88d4d.js
Edit
9449.502f2a824d0203e88d4d.js.map
Edit
946.48c5e8c688cf29424295.js
Edit
946.48c5e8c688cf29424295.js.map
Edit
9473.e6fc327da88d88712828.js
Edit
9473.e6fc327da88d88712828.js.map
Edit
9510.1e255e96fe40aad2ed6f.js
Edit
9510.1e255e96fe40aad2ed6f.js.map
Edit
9521.e65411d726c29d77c526.js
Edit
9521.e65411d726c29d77c526.js.map
Edit
9538.a2289ff9ad06e24e391f.js
Edit
9538.a2289ff9ad06e24e391f.js.map
Edit
957.3c35d66aa698d8bdfe05.js
Edit
957.3c35d66aa698d8bdfe05.js.map
Edit
9571.41558d40bff9ea8c0726.js
Edit
9571.41558d40bff9ea8c0726.js.map
Edit
9578.9cfae16465bb9bc1f336.js
Edit
9578.9cfae16465bb9bc1f336.js.map
Edit
968.d4b150f9211c478b7b05.js
Edit
968.d4b150f9211c478b7b05.js.map
Edit
970.46f17b76711e4961a575.js
Edit
970.46f17b76711e4961a575.js.map
Edit
9700.02180b7a06c8a1f7606b.js
Edit
9700.02180b7a06c8a1f7606b.js.map
Edit
9744.aa6baaf988a68fa6a9ba.js
Edit
9744.aa6baaf988a68fa6a9ba.js.map
Edit
9820.6b462d83575efd05c883.js
Edit
9820.6b462d83575efd05c883.js.map
Edit
9838.06bd7dfd4290786f80e3.js
Edit
9838.06bd7dfd4290786f80e3.js.map
Edit
9992.fb08517d3ff77e887443.js
Edit
9992.fb08517d3ff77e887443.js.map
Edit
9996.21c451f22ff76b4bb683.js
Edit
9996.21c451f22ff76b4bb683.js.map
Edit
AdminAuthentication.076c98c6380fd1e42f7e.js
Edit
AdminAuthentication.076c98c6380fd1e42f7e.js.map
Edit
AdminEditOrgPage.8df8167ea6ff8f4803bd.js
Edit
AdminEditOrgPage.8df8167ea6ff8f4803bd.js.map
Edit
AdminListOrgsPage.176dac9ed391bda8952b.js
Edit
AdminListOrgsPage.176dac9ed391bda8952b.js.map
Edit
AdminSettings.7373ed8fa9b943bb2098.js
Edit
AdminSettings.7373ed8fa9b943bb2098.js.map
Edit
AlertGroups.81264e6e5009c36eed6e.js
Edit
AlertGroups.81264e6e5009c36eed6e.js.map
Edit
AlertRuleListIndex.98e7328feeaa2ffe67eb.js
Edit
AlertRuleListIndex.98e7328feeaa2ffe67eb.js.map
Edit
AlertingDisabled.b2c834be0ca4666dd793.js
Edit
AlertingDisabled.b2c834be0ca4666dd793.js.map
Edit
AlertingGroupDetails.3a2c6ef8085b505852e4.js
Edit
AlertingGroupDetails.3a2c6ef8085b505852e4.js.map
Edit
AlertingGroupEdit.69cfe9d5f37a1fc65326.js
Edit
AlertingGroupEdit.69cfe9d5f37a1fc65326.js.map
Edit
AlertingHome.06f307ab9a2a5d8b7f93.js
Edit
AlertingHome.06f307ab9a2a5d8b7f93.js.map
Edit
AlertingImportFromDSRules.f1224bcb622d25e2c94f.js
Edit
AlertingImportFromDSRules.f1224bcb622d25e2c94f.js.map
Edit
AlertingRedirectToRule.9ed1d16829d6833d2827.js
Edit
AlertingRedirectToRule.9ed1d16829d6833d2827.js.map
Edit
AlertingRuleForm.2e69d3f00eb6221e7355.js
Edit
AlertingRuleForm.2e69d3f00eb6221e7355.js.map
Edit
AlertingSettings.7a5f782f877cec4790cb.js
Edit
AlertingSettings.7a5f782f877cec4790cb.js.map
Edit
AlertingTriage.1174f36b4937ad0047c1.js
Edit
AlertingTriage.1174f36b4937ad0047c1.js.map
Edit
BenchmarksPage.ef387f4598ba2b2236ad.js
Edit
BenchmarksPage.ef387f4598ba2b2236ad.js.map
Edit
BookmarksPage.8fe93eb7377073f0c985.js
Edit
BookmarksPage.8fe93eb7377073f0c985.js.map
Edit
ChangePasswordPage.f21b0b1dd107ccd33c1a.js
Edit
ChangePasswordPage.f21b0b1dd107ccd33c1a.js.map
Edit
Connections.949b6389e73bcadb2109.js
Edit
Connections.949b6389e73bcadb2109.js.map
Edit
ContactPoints.9ae2d1927d60c6169b87.js
Edit
ContactPoints.9ae2d1927d60c6169b87.js.map
Edit
CorrelationsFeatureToggle.ec2f1aefce6b456e15eb.js
Edit
CorrelationsFeatureToggle.ec2f1aefce6b456e15eb.js.map
Edit
CorrelationsPage.bd7fcd24ed0b5fe8ac3e.js
Edit
CorrelationsPage.bd7fcd24ed0b5fe8ac3e.js.map
Edit
CreateTeam.429acf93986740280312.js
Edit
CreateTeam.429acf93986740280312.js.map
Edit
DashboardImport.3e9b6f980b81d6f1c755.js
Edit
DashboardImport.3e9b6f980b81d6f1c755.js.map
Edit
DashboardListPage.abeb0c29f072f888f9fb.js
Edit
DashboardListPage.abeb0c29f072f888f9fb.js.map
Edit
DashboardPage.72557fe6dd1a022b7d48.js
Edit
DashboardPage.72557fe6dd1a022b7d48.js.map
Edit
DashboardPageProxy.80adfefad8a885d8e2ef.js
Edit
DashboardPageProxy.80adfefad8a885d8e2ef.js.map
Edit
DashboardScenePage.83fe1fa9509b50120d65.js
Edit
DashboardScenePage.83fe1fa9509b50120d65.js.map
Edit
EditContactPoint.0c33428ddc8ba974d946.js
Edit
EditContactPoint.0c33428ddc8ba974d946.js.map
Edit
EditMuteTiming.8760cc9c77560acf0cd6.js
Edit
EditMuteTiming.8760cc9c77560acf0cd6.js.map
Edit
EditRepositoryPage.d71faaab1af2c8d70a22.js
Edit
EditRepositoryPage.d71faaab1af2c8d70a22.js.map
Edit
EmbeddedDashboard.57de550bce819e3d52e6.js
Edit
EmbeddedDashboard.57de550bce819e3d52e6.js.map
Edit
FileHistoryPage.154ab77c19bbe0ebed20.js
Edit
FileHistoryPage.154ab77c19bbe0ebed20.js.map
Edit
FileStatusPage.36f58cd61202ec603d22.js
Edit
FileStatusPage.36f58cd61202ec603d22.js.map
Edit
FolderAlerting.0b9acb6c42276aaee57d.js
Edit
FolderAlerting.0b9acb6c42276aaee57d.js.map
Edit
FolderLibraryPanelsPage.44f8cabf542ec314d176.js
Edit
FolderLibraryPanelsPage.44f8cabf542ec314d176.js.map
Edit
GettingStartedPage.4bea37f1c9bdcfd0f41b.js
Edit
GettingStartedPage.4bea37f1c9bdcfd0f41b.js.map
Edit
GlobalConfig.1377596507974d18caf6.js
Edit
GlobalConfig.1377596507974d18caf6.js.map
Edit
HistoryPage.4da98f4fa313ee3676ca.js
Edit
HistoryPage.4da98f4fa313ee3676ca.js.map
Edit
LdapSettingsPage.0e9f08d5e59150ecf466.js
Edit
LdapSettingsPage.0e9f08d5e59150ecf466.js.map
Edit
LibraryPanelsPage.824580d7751526c658e2.js
Edit
LibraryPanelsPage.824580d7751526c658e2.js.map
Edit
ListPublicDashboardPage.64c26ffd3ebe6c9076f3.js
Edit
ListPublicDashboardPage.64c26ffd3ebe6c9076f3.js.map
Edit
LoginPage.db48423ed1b455431daa.js
Edit
LoginPage.db48423ed1b455431daa.js.map
Edit
MetricsDrilldownRedirect.fcad4bdff346974952f4.js
Edit
MetricsDrilldownRedirect.fcad4bdff346974952f4.js.map
Edit
MigrateToCloud.5b474ad00e8a3d979750.js
Edit
MigrateToCloud.5b474ad00e8a3d979750.js.map
Edit
NewMuteTiming.2f6302420674f1c73aba.js
Edit
NewMuteTiming.2f6302420674f1c73aba.js.map
Edit
NewOrgPage.be31eaee06e2043d609b.js
Edit
NewOrgPage.be31eaee06e2043d609b.js.map
Edit
NewReceiverView.f1d83eb66a39882b8661.js
Edit
NewReceiverView.f1d83eb66a39882b8661.js.map
Edit
NewSilencePage.2643a48031f7e5d8f376.js
Edit
NewSilencePage.2643a48031f7e5d8f376.js.map
Edit
NotificationPoliciesPage.9333d10ecad1452ebf27.js
Edit
NotificationPoliciesPage.9333d10ecad1452ebf27.js.map
Edit
NotificationsPage.57df4ff5ba1433a4345d.js
Edit
NotificationsPage.57df4ff5ba1433a4345d.js.map
Edit
OrgDetailsPage.7b5835c30585aae81343.js
Edit
OrgDetailsPage.7b5835c30585aae81343.js.map
Edit
PlaylistEditPage.8310e384af659e40c313.js
Edit
PlaylistEditPage.8310e384af659e40c313.js.map
Edit
PlaylistNewPage.f45b642a98a747e28c0d.js
Edit
PlaylistNewPage.f45b642a98a747e28c0d.js.map
Edit
PlaylistPage.9af74957a1cdfb125338.js
Edit
PlaylistPage.9af74957a1cdfb125338.js.map
Edit
PlaylistStartPage.8011a98267ac64c7fa05.js
Edit
PlaylistStartPage.8011a98267ac64c7fa05.js.map
Edit
PluginExtensionsLog.54c02047d569b0c05823.js
Edit
PluginExtensionsLog.54c02047d569b0c05823.js.map
Edit
PluginListPage.e50c18fed21c23ca4ee8.js
Edit
PluginListPage.e50c18fed21c23ca4ee8.js.map
Edit
PluginPage.ae424531bce63dd4721e.js
Edit
PluginPage.ae424531bce63dd4721e.js.map
Edit
ProfileFeatureTogglePage.27378dcbb7520611348e.js
Edit
ProfileFeatureTogglePage.27378dcbb7520611348e.js.map
Edit
ProvisioningWizardPage.c4e4a8f431b4719b0e95.js
Edit
ProvisioningWizardPage.c4e4a8f431b4719b0e95.js.map
Edit
PublicDashboardPage.33d6ec8f685f1b70b9a6.js
Edit
PublicDashboardPage.33d6ec8f685f1b70b9a6.js.map
Edit
RecentlyDeleted.5e0ec16474d939fd9683.js
Edit
RecentlyDeleted.5e0ec16474d939fd9683.js.map
Edit
RecentlyDeletedPage.1dbc2b80b28204de8237.js
Edit
RecentlyDeletedPage.1dbc2b80b28204de8237.js.map
Edit
RepositoryListPage.ec3a0af1cbe2740800bf.js
Edit
RepositoryListPage.ec3a0af1cbe2740800bf.js.map
Edit
RepositoryStatusPage.9aee60589e35a4a19ec2.js
Edit
RepositoryStatusPage.9aee60589e35a4a19ec2.js.map
Edit
SelectOrgPage.910a8d842019a6d7fe93.js
Edit
SelectOrgPage.910a8d842019a6d7fe93.js.map
Edit
SendResetMailPage.513361d6980f98ff8139.js
Edit
SendResetMailPage.513361d6980f98ff8139.js.map
Edit
ServerStats.2830ca154f465dbdecea.js
Edit
ServerStats.2830ca154f465dbdecea.js.map
Edit
ServiceAccountCreatePage.80fcbdd2b7f5aa4e2da1.js
Edit
ServiceAccountCreatePage.80fcbdd2b7f5aa4e2da1.js.map
Edit
ServiceAccountPage.48944056459bb412ff33.js
Edit
ServiceAccountPage.48944056459bb412ff33.js.map
Edit
ServiceAccountsPage.d20b1eb9f87661f10b45.js
Edit
ServiceAccountsPage.d20b1eb9f87661f10b45.js.map
Edit
SignupInvited.fe2c29f380e9888c28cf.js
Edit
SignupInvited.fe2c29f380e9888c28cf.js.map
Edit
SilencesTablePage.b998fdbdcc3d60a81739.js
Edit
SilencesTablePage.b998fdbdcc3d60a81739.js.map
Edit
SnapshotListPage.6feaf24adb92e6a302ec.js
Edit
SnapshotListPage.6feaf24adb92e6a302ec.js.map
Edit
SoloPanelPage.7fc6a934aaadf4c1f84d.js
Edit
SoloPanelPage.7fc6a934aaadf4c1f84d.js.map
Edit
SoloPanelPageOld.bde57e000dd0a0108685.js
Edit
SoloPanelPageOld.bde57e000dd0a0108685.js.map
Edit
SupportBundles.1f46603ad3494624d67a.js
Edit
SupportBundles.1f46603ad3494624d67a.js.map
Edit
SupportBundlesCreate.5eaea61a9713f057277b.js
Edit
SupportBundlesCreate.5eaea61a9713f057277b.js.map
Edit
TeamList.6b088f83e6e8cb66b21d.js
Edit
TeamList.6b088f83e6e8cb66b21d.js.map
Edit
TeamPages.9d8b5dceef8be43c6923.js
Edit
TeamPages.9d8b5dceef8be43c6923.js.map
Edit
Templates.7a02a8497ebca052dcfb.js
Edit
Templates.7a02a8497ebca052dcfb.js.map
Edit
TestStuffPage.982c641592b2f7c9db40.js
Edit
TestStuffPage.982c641592b2f7c9db40.js.map
Edit
ThemePlayground.aeeec77fd8e9c1482f55.js
Edit
ThemePlayground.aeeec77fd8e9c1482f55.js.map
Edit
UserAdminPage.fc4d562eef05d9f59aca.js
Edit
UserAdminPage.fc4d562eef05d9f59aca.js.map
Edit
UserCreatePage.b7036214c66612fb31e9.js
Edit
UserCreatePage.b7036214c66612fb31e9.js.map
Edit
UserInvitePage.4a9bcd4084d7ae454c73.js
Edit
UserInvitePage.4a9bcd4084d7ae454c73.js.map
Edit
UserListPage.a452e1153ae820f58ac9.js
Edit
UserListPage.a452e1153ae820f58ac9.js.map
Edit
UserProfileEditPage.82c11690282e669eabb1.js
Edit
UserProfileEditPage.82c11690282e669eabb1.js.map
Edit
alert-rules-drawer-content.c95bb5ddd3fc813cae92.js
Edit
alert-rules-drawer-content.c95bb5ddd3fc813cae92.js.map
Edit
alert-rules-toolbar-button.0d86c1adae7edb55ff76.js
Edit
alert-rules-toolbar-button.0d86c1adae7edb55ff76.js.map
Edit
alertListPanel.0110106a8d1ab70d65d5.js
Edit
alertListPanel.0110106a8d1ab70d65d5.js.map
Edit
alertmanagerPlugin.2b59de5e7b7a556f87f1.js
Edit
alertmanagerPlugin.2b59de5e7b7a556f87f1.js.map
Edit
annoListPanel.0005a0eab0b05e24d970.js
Edit
annoListPanel.0005a0eab0b05e24d970.js.map
Edit
app.8385deda1df49aa75ec2.js
Edit
app.8385deda1df49aa75ec2.js.map
Edit
assets-manifest.json
Edit
barChartPanel.eecdaeab7d146d477721.js
Edit
barChartPanel.eecdaeab7d146d477721.js.map
Edit
barGaugePanel.6d9e94bbb72ba92a0e9b.js
Edit
barGaugePanel.6d9e94bbb72ba92a0e9b.js.map
Edit
candlestickPanel.af0e0decd06e7b7ab286.js
Edit
candlestickPanel.af0e0decd06e7b7ab286.js.map
Edit
canvasPanel.ddab72fab6e58c3419b2.js
Edit
canvasPanel.ddab72fab6e58c3419b2.js.map
Edit
cloudwatchPlugin.06ef34f60000c4f7ea37.js
Edit
cloudwatchPlugin.06ef34f60000c4f7ea37.js.map
Edit
dark.b66fa87185b9a313ec14.js
Edit
dashListPanel.23b954da0c4888602048.js
Edit
dashListPanel.23b954da0c4888602048.js.map
Edit
dataGridPanel.bb5d4b678cba38dd380b.js
Edit
debugPanel.fff63da32084d7a2e236.js
Edit
debugPanel.fff63da32084d7a2e236.js.map
Edit
elasticsearchPlugin.3f2edb012f5162b48903.js
Edit
elasticsearchPlugin.3f2edb012f5162b48903.js.map
Edit
explore-feature-toggle-page.3de03fa91c88d05cea1c.js
Edit
explore-feature-toggle-page.3de03fa91c88d05cea1c.js.map
Edit
explore.dd32637df83326225e0d.js
Edit
explore.dd32637df83326225e0d.js.map
Edit
flamegraphPanel.cc6c5b4bcd69e406fbb7.js
Edit
flamegraphPanel.cc6c5b4bcd69e406fbb7.js.map
Edit
gaugePanel.5da3c4e39a652e281cc4.js
Edit
gaugePanel.5da3c4e39a652e281cc4.js.map
Edit
gazetteer
Edit
geomapPanel.67ebb4567e9b5fa5074b.js
Edit
gettingStartedPanel.833059170dbbf8d5c4bf.js
Edit
gettingStartedPanel.833059170dbbf8d5c4bf.js.map
Edit
grafana.1492.25120d27db88f863e058.css
Edit
grafana.4350.a45e45977094df4a0bc9.css
Edit
grafana.5790.ffb3a9cd952d3cd7471b.css
Edit
grafana.DashboardPage.a66335f88cd003e4a44f.css
Edit
grafana.DashboardPageProxy.a66335f88cd003e4a44f.css
Edit
grafana.app.1f6473bb54b1e1647be8.css
Edit
grafana.dark.1e8d85816912aadbbba5.css
Edit
grafana.dataGridPanel.c1fc5db1829b1b31eb4d.css
Edit
grafana.geomapPanel.0057d964fa972bb207ec.css
Edit
grafana.light.111a5a99fcebc0962ddc.css
Edit
grafana.livePanel.25120d27db88f863e058.css
Edit
grafana.react-monaco-editor.ffb3a9cd952d3cd7471b.css
Edit
grafana.swagger.d0a2da197b9827204ac1.css
Edit
grafana.tablePanel.25120d27db88f863e058.css
Edit
grafanaPlugin.f21cdb4b84a732cc9dd8.js
Edit
grafanaPlugin.f21cdb4b84a732cc9dd8.js.map
Edit
heatmapPanel.7834b997bc573eddba88.js
Edit
heatmapPanel.7834b997bc573eddba88.js.map
Edit
histogramPanel.9953bfeccf8774500c0c.js
Edit
histogramPanel.9953bfeccf8774500c0c.js.map
Edit
img
Edit
influxdbPlugin.7a899e63be0a65d41e13.js
Edit
influxdbPlugin.7a899e63be0a65d41e13.js.map
Edit
light.827d442410485e491818.js
Edit
livePanel.2a43f499bc746d928d45.js
Edit
livePanel.2a43f499bc746d928d45.js.map
Edit
logsPanel.a328022d248508a083c1.js
Edit
logsPanel.a328022d248508a083c1.js.map
Edit
loki-query-field.f9a0b82b636d4821760c.js
Edit
loki-query-field.f9a0b82b636d4821760c.js.map
Edit
maps
Edit
mixedPlugin.3a69de93f366afbb2f85.js
Edit
newsPanel.c17f40f7c88ea14620e7.js
Edit
newsPanel.c17f40f7c88ea14620e7.js.map
Edit
nodeGraphPanel.f717a9075d994a9a8af4.js
Edit
nodeGraphPanel.f717a9075d994a9a8af4.js.map
Edit
opentsdbPlugin.1795eab1c223ea030c2e.js
Edit
opentsdbPlugin.1795eab1c223ea030c2e.js.map
Edit
pieChartPanel.45166aa6d57d163817ea.js
Edit
pieChartPanel.45166aa6d57d163817ea.js.map
Edit
prometheusPlugin.c3a55eb5353085fc3d2b.js
Edit
prometheusPlugin.c3a55eb5353085fc3d2b.js.map
Edit
radialBarPanel.294c52d497d8f5c2bebb.js
Edit
radialBarPanel.294c52d497d8f5c2bebb.js.map
Edit
runtime.a37cc2f12a959f33871a.js
Edit
runtime.a37cc2f12a959f33871a.js.map
Edit
sql-query-editor.e767d4a2aef360034bd9.js
Edit
sql-query-editor.e767d4a2aef360034bd9.js.map
Edit
statPanel.3a7f191bfb27fd320014.js
Edit
statPanel.3a7f191bfb27fd320014.js.map
Edit
stateTimelinePanel.08d857b143ef89dc195f.js
Edit
stateTimelinePanel.08d857b143ef89dc195f.js.map
Edit
static
Edit
statusHistoryPanel.29f7b8dc01039ba795af.js
Edit
statusHistoryPanel.29f7b8dc01039ba795af.js.map
Edit
swagger.06875a6266679f54141d.js
Edit
swagger.06875a6266679f54141d.js.map
Edit
tablePanel.43861ce2a60617dcd19d.js
Edit
tablePanel.43861ce2a60617dcd19d.js.map
Edit
textPanel.867ee60d01b2039aa159.js
Edit
textPanel.867ee60d01b2039aa159.js.map
Edit
timeseriesPanel.b4a947da450030262a31.js
Edit
timeseriesPanel.b4a947da450030262a31.js.map
Edit
tracesPanel.35bfc3e5ff6bea4212a3.js
Edit
tracesPanel.35bfc3e5ff6bea4212a3.js.map
Edit
trendPanel.001aff2bd153e737c464.js
Edit
trendPanel.001aff2bd153e737c464.js.map
Edit
vis-data.b34535ebabc0fcb91557.js
Edit
vis-data.b34535ebabc0fcb91557.js.map
Edit
vis-network.1b41caf21892c9525709.js
Edit
vis-network.1b41caf21892c9525709.js.map
Edit
welcomeBanner.1a693c9dc02006be4f0b.js
Edit
welcomeBanner.1a693c9dc02006be4f0b.js.map
Edit
xychart.cb20af67a6c495ba6ccd.js
Edit
xychart.cb20af67a6c495ba6ccd.js.map
Edit